Nektar++
Public Member Functions | Static Public Member Functions | Public Attributes | List of all members
CellMLToNektar.validator.CellMLValidator Class Reference
Inheritance diagram for CellMLToNektar.validator.CellMLValidator:
[legend]

Public Member Functions

def __init__ (self, create_relaxng_validator=True)
 
def quit (self)
 
def validate (self, source, return_doc=False, assume_valid=False, **kw)
 

Static Public Member Functions

def setup_logging (show_errors=True, error_stream=sys.stderr, show_warnings=True, warning_stream=sys.stderr, space_errors=False, loglevel=logging.WARNING, **kwargs)
 
def cleanup_logging (handlers)
 

Public Attributes

 relaxng_validator
 

Detailed Description

Definition at line 69 of file validator.py.

Constructor & Destructor Documentation

◆ __init__()

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

Member Function Documentation

◆ cleanup_logging()

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

Definition at line 136 of file validator.py.

136 def cleanup_logging(handlers):
137 """Flush logger & remove handlers."""
138 logger = logging.getLogger('validator')
139 for handler in handlers:
140 handler.flush()
141 logger.removeHandler(handler)
142

◆ quit()

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.

89 def quit(self):
90 """
91 Since using __del__ is precarious, we provide this method to allow
92 the RVP process to be killed cleanly. Call it when the validator
93 is finished with, or you'll get an interesting error when the program
94 terminates (if using RVP).
95 """
96 if self.relaxng_validator:
97 self.relaxng_validator.quit()
98 return
99
def quit(self)
def del(self): """ Tell our RVP process to quit.
Definition: validator.py:288

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

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

◆ setup_logging()

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 101 of file validator.py.

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

◆ validate()

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.

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

References CellMLToNektar.pycml.amara_parse_cellml(), CellMLToNektar.utilities.DEBUG(), CellMLToNektar.validator.CellMLValidator.relaxng_validator, and CellMLToNektar.validator.CellMLValidator.validate().

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

Member Data Documentation

◆ relaxng_validator

CellMLToNektar.validator.CellMLValidator.relaxng_validator