Nektar++
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
Public Member Functions | Static Public Member Functions | Public Attributes | List of all members
CellMLToNektar.validator.CellMLValidator Class Reference
Inheritance diagram for CellMLToNektar.validator.CellMLValidator:
Inheritance graph
[legend]
Collaboration diagram for CellMLToNektar.validator.CellMLValidator:
Collaboration graph
[legend]

Public Member Functions

def __init__
 
def quit
 
def validate
 

Static Public Member Functions

def setup_logging
 
def cleanup_logging
 

Public Attributes

 relaxng_validator
 

Detailed Description

Definition at line 69 of file validator.py.

Constructor & Destructor Documentation

def CellMLToNektar.validator.CellMLValidator.__init__ (   self,
  create_relaxng_validator = True 
)
Initialise a validator for CellML files.

Definition at line 70 of file validator.py.

70 
71  def __init__(self, create_relaxng_validator=True):
72  """Initialise a validator for CellML files."""
73  # Create validator from RELAX NG schema
74  self.relaxng_validator = None
75  if create_relaxng_validator:
76  schema_base = os.path.join(pycml_path, 'cellml1.0')
77  run_errors = []
78  for klass in [LxmlRelaxngValidator, RvpRelaxngValidator]:
79  try:
80  self.relaxng_validator = klass(schema_base)
81  except ValidatorError, e:
82  run_errors.append(str(e))
83  else:
84  break
85  if not self.relaxng_validator:
86  msg = '\n\t'.join(["Unable to run a RELAX NG validator. Please install lxml or rvp."]
87  + run_errors)
88  raise ValidatorError(msg)

Member Function Documentation

def CellMLToNektar.validator.CellMLValidator.cleanup_logging (   handlers)
static
Flush logger & remove handlers.

Definition at line 136 of file validator.py.

137  def cleanup_logging(handlers):
138  """Flush logger & remove handlers."""
139  logger = logging.getLogger('validator')
140  for handler in handlers:
141  handler.flush()
142  logger.removeHandler(handler)
def CellMLToNektar.validator.CellMLValidator.quit (   self)
Since using __del__ is precarious, we provide this method to allow
the RVP process to be killed cleanly.  Call it when the validator
is finished with, or you'll get an interesting error when the program
terminates (if using RVP).

Definition at line 89 of file validator.py.

References CellMLToNektar.validator.CellMLValidator.relaxng_validator, and CellMLToNektar.validator.CellMLValidator.setup_logging().

89 
90  def quit(self):
91  """
92  Since using __del__ is precarious, we provide this method to allow
93  the RVP process to be killed cleanly. Call it when the validator
94  is finished with, or you'll get an interesting error when the program
95  terminates (if using RVP).
96  """
97  if self.relaxng_validator:
98  self.relaxng_validator.quit()
99  return
def CellMLToNektar.validator.CellMLValidator.setup_logging (   show_errors = True,
  error_stream = sys.stderr,
  show_warnings = True,
  warning_stream = sys.stderr,
  space_errors = False,
  loglevel = logging.WARNING,
  kwargs 
)
static
Set up loggers for validation errors/warnings.

Set show_errors or show_warnings to False to suppress the output of
validation error or warning messages, respectively.  When not
suppressed, the messages will be output to the streams given by
error_stream and warning_stream; these should be file-like objects.

If space_errors is True, a blank line will be inserted between
each message.

Definition at line 104 of file validator.py.

Referenced by CellMLToNektar.validator.CellMLValidator.quit().

105  **kwargs):
106  """Set up loggers for validation errors/warnings.
107 
108  Set show_errors or show_warnings to False to suppress the output of
109  validation error or warning messages, respectively. When not
110  suppressed, the messages will be output to the streams given by
111  error_stream and warning_stream; these should be file-like objects.
112 
113  If space_errors is True, a blank line will be inserted between
114  each message.
115  """
116  logger = logging.getLogger('validator')
117  logger.setLevel(loglevel)
118  if space_errors:
119  formatter = logging.Formatter(fmt="%(message)s\n")
120  else:
121  formatter = logging.Formatter(fmt="%(message)s")
122  error_handler = logging.StreamHandler(error_stream)
123  error_handler.setLevel(logging.ERROR)
124  error_handler.setFormatter(formatter)
125  warning_handler = logging.StreamHandler(warning_stream)
126  warning_handler.addFilter(OnlyWarningsFilter())
127  warning_handler.setFormatter(formatter)
128  if not show_errors:
129  error_handler.setLevel(logging.CRITICAL)
130  if not show_warnings:
131  warning_handler.setLevel(logging.CRITICAL)
132  logger.addHandler(error_handler)
133  logger.addHandler(warning_handler)
134  return error_handler, warning_handler
def CellMLToNektar.validator.CellMLValidator.validate (   self,
  source,
  return_doc = False,
  assume_valid = False,
  kw 
)
Validate the given document.

source should be a file-like object, URI, local file name,
or '-' for standard input.  If a file-like object, it must support
the seek method to reset it.

If return_doc is True then the result is a tuple (valid, document),
where if valid==True then document is an Amara binding of the CellML
document.
Otherwise just return True iff the document is valid.

If xml_context is True, then the failing XML tree will be displayed
with every units error.

The assume_valid option allows you to skip RELAX NG validation, along
with many of the checks in the Python code.  This is useful for speeding
transformation of models that are known to pass these checks.

See cellml_model.validate and setup_logging for other keyword arguments.

Definition at line 143 of file validator.py.

References CellMLToNektar.pycml.amara_parse_cellml(), and CellMLToNektar.utilities.DEBUG().

144  def validate(self, source, return_doc=False, assume_valid=False, **kw):
145  """Validate the given document.
146 
147  source should be a file-like object, URI, local file name,
148  or '-' for standard input. If a file-like object, it must support
149  the seek method to reset it.
150 
151  If return_doc is True then the result is a tuple (valid, document),
152  where if valid==True then document is an Amara binding of the CellML
153  document.
154  Otherwise just return True iff the document is valid.
155 
156  If xml_context is True, then the failing XML tree will be displayed
157  with every units error.
158 
159  The assume_valid option allows you to skip RELAX NG validation, along
160  with many of the checks in the Python code. This is useful for speeding
161  transformation of models that are known to pass these checks.
162 
163  See cellml_model.validate and setup_logging for other keyword arguments.
164  """
165  logging_info = CellMLValidator.setup_logging(**kw)
166 
167  # Validate against RELAX NG schema
168  DEBUG('validator', 'CellML Validator version', __version__)
169  res = True
170  # Get stream of CellML document
171  if source == '-':
172  stream = sys.stdin
173  elif hasattr(source, 'read'):
174  stream = source
175  elif bt.Uri.IsAbsolute(source):
176  stream = bt.Url.UrlOpen(source)
177  else:
178  if not os.path.isfile(source):
179  res = False
180  logging.getLogger('validator').error('File ' + source + ' does not exist.')
181  else:
182  stream = file(source, 'r')
183  # Parse & validate
184  if res and not assume_valid:
185  DEBUG('validator', 'Starting RELAX NG validation')
186  res = self.relaxng_validator.validate(stream)
187  if stream == source:
188  source.seek(0)
189  elif not stream == sys.stdin:
190  stream.close()
191  DEBUG('validator', 'Finished RELAX NG:', res)
192 
193  # Check further rules that can't be expressed by a (RELAX NG) schema.
194  # We use our own Python code for this.
195  if res:
196  DEBUG('validator', 'Loading model with Amara')
197  doc = amara_parse_cellml(source)
198  DEBUG('validator', 'Validating loaded model')
199  res = doc.model.validate(assume_valid=assume_valid, **kw)
200  DEBUG('validator', 'Validation complete:', res)
201  else:
202  doc = None
203 
204  # Flush logger & remove handlers
205  CellMLValidator.cleanup_logging(logging_info)
206 
207  # Return result
208  if return_doc:
209  return (res, doc)
210  else:
211  if doc:
212  doc.model.clean_up()
213  return res
214 
def amara_parse_cellml
Definition: pycml.py:191

Member Data Documentation

CellMLToNektar.validator.CellMLValidator.relaxng_validator

Definition at line 73 of file validator.py.

Referenced by CellMLToNektar.validator.CellMLValidator.quit().