Nektar++
Classes | Functions | Variables
CellMLToNektar.pycml Namespace Reference

Classes

class  cellml_component
 
class  cellml_model
 
class  cellml_unit
 
class  cellml_units
 
class  cellml_variable
 
class  comment_base
 
class  element_base
 
class  EvaluationError
 
class  mathml
 
class  mathml_abs
 
class  mathml_and
 
class  mathml_apply
 
class  mathml_arccos
 
class  mathml_arcsin
 
class  mathml_arctan
 
class  mathml_ci
 
class  mathml_cn
 
class  mathml_constructor
 
class  mathml_cos
 
class  mathml_degree
 
class  mathml_diff
 
class  mathml_divide
 
class  mathml_eq
 
class  mathml_exp
 
class  mathml_geq
 
class  mathml_gt
 
class  mathml_lambda
 
class  mathml_leq
 
class  mathml_ln
 
class  mathml_log
 
class  mathml_logbase
 
class  mathml_lt
 
class  mathml_math
 
class  mathml_minus
 
class  mathml_neq
 
class  mathml_operator
 
class  mathml_or
 
class  mathml_otherwise
 
class  mathml_piece
 
class  mathml_piecewise
 
class  mathml_plus
 
class  mathml_power
 
class  mathml_rem
 
class  mathml_root
 
class  mathml_sin
 
class  mathml_tan
 
class  mathml_times
 
class  mathml_units_mixin
 MathML elements #. More...
 
class  mathml_units_mixin_choose_nearest
 
class  mathml_units_mixin_container
 
class  mathml_units_mixin_equalise_operands
 
class  mathml_units_mixin_set_operands
 
class  mathml_units_mixin_tokens
 
class  MathsError
 
class  reduce_commutative_nary
 
class  UnitsError
 
class  UnitsSet
 

Functions

def import_processors ()
 
def make_xml_binder ()
 Helpful utility functions #. More...
 
def amara_parse_cellml (source, uri=None, prefixes=None)
 
def check_append_safety (elt)
 
def add_methods_to_amara ()
 
def _rel_error_ok (self, value1, value2, tol)
 def eq(self, other): """Compare 2 units elements for equality. More...
 
def equals (self, other)
 
def model (self)
 
def extract (self, check_equality=False)
 
def copy (self)
 
def description (self, force=False, cellml=False)
 
def get_units_by_name (self, uname)
 
def expand (self)
 
def is_base_unit (self)
 
def is_simple (self)
 
def get_multiplicative_factor (self)
 
def get_multiplier (self)
 
def get_offset (self)
 
def create_new (parent, name, bases, add_to_parent=False, standard=False)
 
def _based_on (self, units=None, prefix=None, exponent=None, multiplier=None, offset=None)
 
def simplify (self, other_units=None, other_exponent=1)
 
def _best_parent (self, other_units)
 
def quotient (self, other_units)
 
def dimensionally_equivalent (self, other_units)
 
def child_i (elt, i)
 
def _child1 (elt)
 
def varobj (self, ci_elt)
 
def vars_in (self, expr)
 
def same_tree (self, other, this=None)
 
def _xfer_complexity (self, new_elt)
 
def _adjust_complexity (self, old_elt, new_elt)
 
def classify_child_variables (self, elt, **kwargs)
 

Variables

 processors = None
 
list __version__ = "$Revision: 25949 $"[11:-2]
 
 level
 
 format
 
 stream
 
 WARNING_TRANSLATE_ERROR
 
dictionary NSS
 
 VarTypes
 
 CELLML_SUBSET_ELTS
 
 BINDING_TIMES = Enum('static', 'dynamic')
 
list units_name_counter = [0]
 
 new_units = dimensionless
 print "Keeping d'less ref with m =",m,"from", print self.description(), if other_units: print "and",other_units.description() else: print More...
 
 unit_elements = set(d.values())
 
string uname = u'___units_' + str(self.units_name_counter[0])
 
 _cml_generated
 
 xml_parent
 
def units = self.model._get_units_obj(units)
 _u = units More...
 
string msg = "Adding units " + units.name + " as "
 
 name
 
 cellml
 
dictionary attrs = {(u'cml:units', NSS[u'cml']): units.name}
 
 _cml_expanded
 
 base_units
 

Function Documentation

◆ _adjust_complexity()

def CellMLToNektar.pycml._adjust_complexity (   self,
  old_elt,
  new_elt 
)
private
Adjust ancestor complexity because old_elt changed to new_elt.

The purpose of this method is to allow us to keep track of
what the complexity of each expression node *was* prior to PE
being performed.  Thus we cannot just re-compute complexities,
but must update values using the original complexities.  If a
variable definition is instantiated, then the complexity of
the expression containing the lookup must be adjusted to
reflect the additional expense of evaluating the defining
expression.

When this method is called, only new_elt is a child of self.

Definition at line 3923 of file pycml.py.

3923 def _adjust_complexity(self, old_elt, new_elt):
3924 """Adjust ancestor complexity because old_elt changed to new_elt.
3925
3926 The purpose of this method is to allow us to keep track of
3927 what the complexity of each expression node *was* prior to PE
3928 being performed. Thus we cannot just re-compute complexities,
3929 but must update values using the original complexities. If a
3930 variable definition is instantiated, then the complexity of
3931 the expression containing the lookup must be adjusted to
3932 reflect the additional expense of evaluating the defining
3933 expression.
3934
3935 When this method is called, only new_elt is a child of self.
3936 """
3937 #print "Adjusting", element_xpath(self), "due to", element_xpath(old_elt),
3938 #if isinstance(old_elt, mathml_ci):
3939 # print unicode(old_elt)
3940 #else:
3941 # print
3942 try:
3943 new = new_elt._cml_complexity
3944 old = old_elt._cml_complexity
3945 except AttributeError:
3946 return
3947 #print " by", new-old
3948 elt = self
3949 while elt:
3950 if isinstance(elt, mathml_piecewise):
3951 # Piecewise is tricky to adjust! So we 're-compute' instead.
3952 ac, piece_ac = 0, []
3953 for piece in getattr(elt, u'piece', []):
3954 ac += child_i(piece, 2)._cml_complexity
3955 piece_ac.append(child_i(piece, 1)._cml_complexity)
3956 if hasattr(elt, u'otherwise'):
3957 piece_ac.append(child_i(elt.otherwise, 1)._cml_complexity)
3958 ac += max(piece_ac)
3959 elt._cml_complexity = ac
3960 elif hasattr(elt, '_cml_complexity'):
3961 elt._cml_complexity += (new - old)
3962 elt = getattr(elt, 'xml_parent', None)
3963 return
3964
def _adjust_complexity(self, old_elt, new_elt)
Definition: pycml.py:3923
def child_i(elt, i)
Definition: pycml.py:3449

References CellMLToNektar.pycml.child_i().

◆ _based_on()

def CellMLToNektar.pycml._based_on (   self,
  units = None,
  prefix = None,
  exponent = None,
  multiplier = None,
  offset = None 
)
private
Convenience function for defining new units.

Definition at line 2940 of file pycml.py.

2941 multiplier=None, offset=None):
2942 """Convenience function for defining new units."""
2943 for v in ['units', 'prefix', 'exponent', 'multiplier', 'offset']:
2944 # Coerce from str to unicode
2945 exec "if type(%s) == str: %s = unicode(%s)" % (v,v,v)
2946 # Check type
2947 exec "assert(%s is None or type(%s) == unicode)" % (v,v)
2948 assert(not hasattr(self, 'base_units') or self.base_units == u'no')
2949 attrs = {u'units': units}
2950 if offset:
2951 # Simple units definition
2952 assert(not hasattr(self, 'unit'))
2953 attrs[u'offset'] = offset
2954 if not prefix is None: attrs[u'prefix'] = prefix
2955 if not exponent is None: attrs[u'exponent'] = exponent
2956 else:
2957 # Complex units definition
2958 if not prefix is None: attrs[u'prefix'] = prefix
2959 if not exponent is None: attrs[u'exponent'] = exponent
2960 if not multiplier is None: attrs[u'multiplier'] = multiplier
2961 self.xml_append(self.xml_create_element(u'unit', NSS[u'cml'],
2962 attributes=attrs))
2963 return
2964

◆ _best_parent()

def CellMLToNektar.pycml._best_parent (   self,
  other_units 
)
private
Return a suitable parent for units formed from self and other_units.

If either constituent is in a component, that component should be the
parent, otherwise the model should be.

Definition at line 3143 of file pycml.py.

3143 def _best_parent(self, other_units):
3144 """Return a suitable parent for units formed from self and other_units.
3145
3146 If either constituent is in a component, that component should be the
3147 parent, otherwise the model should be.
3148 """
3149 p1, p2 = self.xml_parent, other_units and other_units.xml_parent
3150 if p2 and p1 != p2 and isinstance(p1, cellml_model):
3151 p1 = p2
3152 return p1
3153
def _best_parent(self, other_units)
Definition: pycml.py:3143

◆ _child1()

def CellMLToNektar.pycml._child1 (   elt)
private

◆ _rel_error_ok()

def CellMLToNektar.pycml._rel_error_ok (   self,
  value1,
  value2,
  tol 
)
private

def eq(self, other): """Compare 2 units elements for equality.

return self.equals(other) def ne(self, other): """Inverse of self.__eq__(other).""" return not self.__eq__(other)

Test if the relative difference of 2 values is within tol.

Definition at line 2627 of file pycml.py.

2627 def _rel_error_ok(self, value1, value2, tol):
2628 """Test if the relative difference of 2 values is within tol."""
2629 if abs(value1) == 0.0:
2630 return abs(value2) < tol
2631 else:
2632 return (abs(value1-value2)/abs(value1)) < tol
2633
def _rel_error_ok(self, value1, value2, tol)
def eq(self, other): """Compare 2 units elements for equality.
Definition: pycml.py:2627
scalarT< T > abs(scalarT< T > in)
Definition: scalar.hpp:298

References tinysimd.abs().

◆ _xfer_complexity()

def CellMLToNektar.pycml._xfer_complexity (   self,
  new_elt 
)
private
Transfer our complexity to the new element.

PE is replacing us by a new element.  If we are annotated with
a complexity - the complexity of this expression prior to PE -
then transfer the annotation to the new element.

Definition at line 3911 of file pycml.py.

3911 def _xfer_complexity(self, new_elt):
3912 """Transfer our complexity to the new element.
3913
3914 PE is replacing us by a new element. If we are annotated with
3915 a complexity - the complexity of this expression prior to PE -
3916 then transfer the annotation to the new element.
3917 """
3918 try:
3919 new_elt._cml_complexity = self._cml_complexity
3920 except AttributeError:
3921 pass
3922 return
def _xfer_complexity(self, new_elt)
Definition: pycml.py:3911

◆ add_methods_to_amara()

def CellMLToNektar.pycml.add_methods_to_amara ( )

Definition at line 323 of file pycml.py.

324 def getAttributeNS(self, ns, local, default=u""):
325 """
326 Get the value of an attribute specified by namespace and localname.
327
328 Optionally can also pass a default value if the attribute
329 doesn't exist (defaults to the empty string).
330 """
331 attrs = getattr(self, 'xml_attributes', {})
332 keys = [ (ns_, SplitQName(qname)[1])
333 for _, (qname, ns_) in attrs.items() ]
334 values = [ unicode(getattr(self, attr))
335 for attr, (qname, ns_) in attrs.items() ]
336 attr_dict = dict(zip(keys, values))
337 return attr_dict.get((ns, local), default)
338
339 def xml_element_children(self, elt=None):
340 """Return an iterable over child elements of this element."""
341 if elt is None:
342 elt = self
343 for child in elt.xml_children:
344 if getattr(child, 'nodeType', None) == Node.ELEMENT_NODE:
345 yield child
346
347 def safe_remove_child(self, child, parent=None):
348 """Remove a child element from parent in such a way that it can safely be added elsewhere."""
349 if parent is None: parent = self
350 parent.xml_remove_child(child)
351 child.next_elem = None
352
353 def replace_child(self, old, new, parent=None):
354 """Replace child old of parent with new."""
355 if parent is None: parent = self
356 parent.xml_insert_after(old, new)
357 self.safe_remove_child(old, parent)
358
359 import new
360 for method in ['getAttributeNS', 'xml_element_children', 'safe_remove_child', 'replace_child']:
361 meth = new.instancemethod(locals()[method], None, amara.bindery.element_base)
362 setattr(amara.bindery.element_base, method, meth)
363
def add_methods_to_amara()
Definition: pycml.py:323

References CellMLToNektar.pycml.add_methods_to_amara().

Referenced by CellMLToNektar.pycml.add_methods_to_amara().

◆ amara_parse_cellml()

def CellMLToNektar.pycml.amara_parse_cellml (   source,
  uri = None,
  prefixes = None 
)
Parse a CellML source with default rules and bindings.

Definition at line 191 of file pycml.py.

191def amara_parse_cellml(source, uri=None, prefixes=None):
192 """Parse a CellML source with default rules and bindings."""
193 binder = make_xml_binder()
194 rules = [bt.ws_strip_element_rule(u'*')]
195 return amara_parse(source, rules=rules, binderobj=binder)
196
def amara_parse_cellml(source, uri=None, prefixes=None)
Definition: pycml.py:191
def make_xml_binder()
Helpful utility functions #.
Definition: pycml.py:168
def amara_parse(source, uri=None, rules=None, binderobj=None, prefixes=None)
Definition: utilities.py:192

References CellMLToNektar.utilities.amara_parse(), and CellMLToNektar.pycml.make_xml_binder().

Referenced by CellMLToNektar.processors.ModelModifier._get_units_object(), CellMLToNektar.translators.SolverInfo.add_jacobian_matrix(), and CellMLToNektar.validator.CellMLValidator.validate().

◆ check_append_safety()

def CellMLToNektar.pycml.check_append_safety (   elt)
Check whether elt is safe to make a child, i.e. that it isn't
already a child elsewhere.

Definition at line 197 of file pycml.py.

197def check_append_safety(elt):
198 """
199 Check whether elt is safe to make a child, i.e. that it isn't
200 already a child elsewhere.
201 """
202 assert getattr(elt, 'next_elem', None) is None
203 parent = getattr(elt, 'xml_parent', None)
204 if parent:
205 assert elt not in parent.xml_children
206
def check_append_safety(elt)
Definition: pycml.py:197

Referenced by CellMLToNektar.pycml.mathml_lambda.create_new(), CellMLToNektar.pycml.mathml_apply.create_new(), and CellMLToNektar.pycml.mathml_piecewise.create_new().

◆ child_i()

def CellMLToNektar.pycml.child_i (   elt,
  i 
)

◆ classify_child_variables()

def CellMLToNektar.pycml.classify_child_variables (   self,
  elt,
**  kwargs 
)
Classify variables in the given expression according to how they are used.

In the process, compute and return a set of variables on which that expression depends.

If dependencies_only then the variable classification will not be
done, only dependencies will be analysed.  This is useful for doing
a 'light' re-analysis if the dependency set has been reduced; if the
set has increased then the topological sort of equations may need to
be redone.

The function needs_special_treatment may be supplied to override the
default recursion into sub-trees.  It takes a single sub-tree as
argument, and should either return the dependency set for that
sub-tree, or None to use the default recursion.  This is used when
re-analysing dependencies after applying lookup tables, since table
lookups only depend on the keying variable.

Definition at line 3965 of file pycml.py.

3965 def classify_child_variables(self, elt, **kwargs):
3966 """Classify variables in the given expression according to how they are used.
3967
3968 In the process, compute and return a set of variables on which that expression depends.
3969
3970 If dependencies_only then the variable classification will not be
3971 done, only dependencies will be analysed. This is useful for doing
3972 a 'light' re-analysis if the dependency set has been reduced; if the
3973 set has increased then the topological sort of equations may need to
3974 be redone.
3975
3976 The function needs_special_treatment may be supplied to override the
3977 default recursion into sub-trees. It takes a single sub-tree as
3978 argument, and should either return the dependency set for that
3979 sub-tree, or None to use the default recursion. This is used when
3980 re-analysing dependencies after applying lookup tables, since table
3981 lookups only depend on the keying variable.
3982 """
3983 if hasattr(elt, 'classify_variables'):
3984 dependencies = elt.classify_variables(**kwargs)
3985 else:
3986 dependencies = set()
3987 needs_special_treatment = kwargs.get('needs_special_treatment', lambda e: None)
3988 for e in elt.xml_element_children():
3989 child_deps = needs_special_treatment(e)
3990 if child_deps is None:
3991 child_deps = self.classify_child_variables(e, **kwargs)
3992 dependencies.update(child_deps)
3993 return dependencies
3994
def classify_child_variables(self, elt, **kwargs)
Definition: pycml.py:3965

◆ copy()

def CellMLToNektar.pycml.copy (   self)
Return a new UnitsSet containing this cellml_units object.

Used for interface compatibility with UnitsSet, where the method performs a shallow copy.

Definition at line 2663 of file pycml.py.

2663 def copy(self):
2664 """Return a new UnitsSet containing this cellml_units object.
2665
2666 Used for interface compatibility with UnitsSet, where the method performs a shallow copy.
2667 """
2668 return UnitsSet([self])
2669
def copy(self)
Definition: pycml.py:2663

Referenced by Nektar::MetricFile.CalculateHash(), Nektar.CopyArray(), Nektar.CopyArrayN(), Nektar::SolverUtils::DriverParareal.CopyConvergedCheckPoints(), CppCommandLine.CppCommandLine(), Nektar::LinearSystem.FactorMatrix(), CellMLToNektar.pycml.mathml_apply.get_units(), CellMLToNektar.pycml.mathml_piecewise.get_units(), Nektar::ArrayInitializationPolicy< ObjectType, typename std::enable_if< std::is_fundamental< ObjectType >::value >::type >.Initialize(), Nektar::LibUtilities::SessionReader.LoadDoc(), Nektar::NekMatrix< DataType, StandardMatrixTag >.NekMatrix(), Nektar.NekMultiplyLowerTriangularMatrix(), Nektar.NekMultiplyUpperTriangularMatrix(), Nektar::NekMatrix< DataType, StandardMatrixTag >.operator=(), Nektar::StorageSmvBsr< T >.processBcoInput(), Nektar::NekMatrix< DataType, StandardMatrixTag >.ResizeDataArrayIfNeeded(), Nektar::LibUtilities::GaussPoints.v_CalculateDerivMatrix(), Nektar::FieldUtils::InputSemtex.v_Process(), Nektar::LibUtilities::FieldIOHdf5.v_Write(), and Nektar::FieldUtils::OutputTecplotBinary.WriteDoubleOrFloat().

◆ create_new()

def CellMLToNektar.pycml.create_new (   parent,
  name,
  bases,
  add_to_parent = False,
  standard = False 
)
static
Create a new units definition element.

It requires either a cellml_model or cellml_component element
to be passed as the parent for the definition.  If
add_to_parent is set to true the new units element will be
appended to parent's children.

The bases parameter should be a list of dictionaries suitable
for use as the keyword arguments of cellml_units._based_on.
If the list is empty it will be defined as a base unit.

Definition at line 2912 of file pycml.py.

2912 def create_new(parent, name, bases, add_to_parent=False, standard=False):
2913 """Create a new units definition element.
2914
2915 It requires either a cellml_model or cellml_component element
2916 to be passed as the parent for the definition. If
2917 add_to_parent is set to true the new units element will be
2918 appended to parent's children.
2919
2920 The bases parameter should be a list of dictionaries suitable
2921 for use as the keyword arguments of cellml_units._based_on.
2922 If the list is empty it will be defined as a base unit.
2923 """
2924 # Create the units element
2925 attrs = {u'name': unicode(name)}
2926 if not bases:
2927 attrs[u'base_units'] = u'yes'
2928 if standard:
2929 attrs[u'standard'] = u'yes'
2930 u = parent.xml_create_element(u'units', NSS[u'cml'], attributes=attrs)
2931 if add_to_parent:
2932 parent.xml_append(u)
2933 else:
2934 u.xml_parent = parent # Hack so units lookups work
2935 # Add references to units we're based on
2936 for basis in bases:
2937 u._based_on(**basis)
2938 return u
2939
def create_new(parent, name, bases, add_to_parent=False, standard=False)
Definition: pycml.py:2912

◆ description()

def CellMLToNektar.pycml.description (   self,
  force = False,
  cellml = False 
)
Return a human-readable name for these units.

The name will be descriptive and based on the consituent <unit> elements, e.g. 'volt per second^2'

By default, if these are user-defined units, then return self.name.  Set force to True to override this behaviour.

Set cellml to True to get a description that is also a valid CellML identifier.

Definition at line 2670 of file pycml.py.

2670 def description(self, force=False, cellml=False):
2671 """Return a human-readable name for these units.
2672
2673 The name will be descriptive and based on the consituent <unit> elements, e.g. 'volt per second^2'
2674
2675 By default, if these are user-defined units, then return self.name. Set force to True to override this behaviour.
2676
2677 Set cellml to True to get a description that is also a valid CellML identifier.
2678 """
2679 if self.is_base_unit():
2680 desc = self.name
2681 elif not force and not self._cml_generated:
2682 desc = self.name
2683 else:
2684 descs, per_descs = [], []
2685 # Multiplier
2686 m = self.get_multiplier()
2687 if m != 1:
2688 descs.append(unicode(m))
2689 # Constituent units
2690 dimensionless = self.get_units_by_name('dimensionless')
2691 for unit in self.unit:
2692 if unit.get_units_element() is dimensionless:
2693 continue
2694 desc = [getattr(unit, u'prefix_', u''), unit.get_units_element().name]
2695 e = unit.get_exponent()
2696 if int(e) == e:
2697 # Cast to integer so name looks nicer.
2698 e = int(e)
2699 if abs(e) != 1:
2700 desc.extend(['^', str(abs(e))])
2701 desc = u''.join(desc)
2702 if e < 0:
2703 per_descs.append(desc)
2704 else:
2705 descs.append(desc)
2706 # Sort unit descriptions for readability
2707 descs.sort()
2708 descs = u' '.join(descs)
2709 per_descs.sort()
2710 desc = u' per '.join([descs] + per_descs)
2711 if not desc:
2712 desc = u'dimensionless'
2713 elif descs:
2714 desc = u"'" + desc + u"'"
2715 else:
2716 # Remove unwanted space from the start
2717 desc = u"'" + desc[1:] + u"'"
2718 # Convert to CellML identifier?
2719 if cellml:
2720 desc = desc.replace(u"'", u"").replace(u"^", u"")
2721 desc = desc.replace(u"*", u"").replace(u".", u"_")
2722 desc = desc.replace(u" ", u"_")
2723 return desc
2724
def description(self, force=False, cellml=False)
Definition: pycml.py:2670

References tinysimd.abs().

Referenced by main(), CellMLToNektar.translators.CellMLTranslator.output_assignment(), Nektar::LibUtilities::SessionReader.ParseCommandLineArguments(), and CellMLToNektar.pycml.cellml_units.uniquify_tuple().

◆ dimensionally_equivalent()

def CellMLToNektar.pycml.dimensionally_equivalent (   self,
  other_units 
)
Return True iff other_units is dimensionally equivalent to self.

As per appendix C.2.2, two units definitions have dimensional
equivalence if, when each is recursively expanded and
simplified into a product of base units, each has the same set
of base units with the same exponent on corresponding base units.

Definition at line 3185 of file pycml.py.

3185 def dimensionally_equivalent(self, other_units):
3186 """Return True iff other_units is dimensionally equivalent to self.
3187
3188 As per appendix C.2.2, two units definitions have dimensional
3189 equivalence if, when each is recursively expanded and
3190 simplified into a product of base units, each has the same set
3191 of base units with the same exponent on corresponding base units.
3192 """
3193 u1 = self.expand().simplify()
3194 if isinstance(other_units, UnitsSet):
3195 other_units = other_units.extract()
3196 u2 = other_units.expand().simplify()
3197 # Build dictionaries mapping base_unit_obj to exponent.
3198 d1, d2 = {}, {}
3199 if u1.is_base_unit():
3200 d1[u1] = 1
3201 else:
3202 for u in u1.unit:
3203 d1[u.get_units_element()] = u.get_exponent()
3204 if u2.is_base_unit():
3205 d2[u2] = 1
3206 else:
3207 for u in u2.unit:
3208 d2[u.get_units_element()] = u.get_exponent()
3209 # Compare keys: do u1 & u2 have the same set of base units?
3210 sym_diff = set(d1.keys()) ^ set(d2.keys())
3211 if sym_diff:
3212 dimensionless = self.get_units_by_name(u'dimensionless')
3213 if not sym_diff == set([dimensionless]):
3214 # Symmetric difference is non-empty, but not an ignorable
3215 # instance of dimensionless
3216 return False
3217 # Compare corresponding exponents
3218 for k in d1:
3219 try:
3220 if d1[k] != d2[k]: return False
3221 except KeyError:
3222 # One may have dimensionless as a key
3223 pass
3224 # We have a match!
3225 return True
3226
3227
def simplify(self, other_units=None, other_exponent=1)
Definition: pycml.py:2967
def dimensionally_equivalent(self, other_units)
Definition: pycml.py:3185

References CellMLToNektar.pycml.simplify().

Referenced by CellMLToNektar.CellMLToNektarTranslator.CellMLToNektarTranslator.generate_interface().

◆ equals()

def CellMLToNektar.pycml.equals (   self,
  other 
)
Compare 2 units elements for equality.

Two units are deemed equal if they are both dimensionally equivalent and have the same
multiplicative factor (to within a relative tolerance of 10^-6).

If both are simple units, they must also have the same offset.

Definition at line 2634 of file pycml.py.

2634 def equals(self, other):
2635 """Compare 2 units elements for equality.
2636
2637 Two units are deemed equal if they are both dimensionally equivalent and have the same
2638 multiplicative factor (to within a relative tolerance of 10^-6).
2639
2640 If both are simple units, they must also have the same offset.
2641 """
2642 equal = isinstance(other, cellml_units) and \
2643 self.dimensionally_equivalent(other) and \
2644 self._rel_error_ok(self.expand().get_multiplicative_factor(),
2645 other.expand().get_multiplicative_factor(),
2646 1e-6)
2647 if equal and self.is_simple():
2648 equal = self._rel_error_ok(self.unit.get_offset(),
2649 other.unit.get_offset(),
2650 1e-6)
2651 return equal
2652
def get_offset(self)
Definition: pycml.py:2899
def get_multiplicative_factor(self)
Definition: pycml.py:2876
def equals(self, other)
Definition: pycml.py:2634

References CellMLToNektar.pycml.get_multiplicative_factor(), and CellMLToNektar.pycml.get_offset().

Referenced by CellMLToNektar.processors.ModelModifier._convert_initial_value().

◆ expand()

def CellMLToNektar.pycml.expand (   self)
Expand to a product of powers of base units.

Expand this units definition according to the algorithm given in appendix C.3.4 of the CellML spec.

Caches and returns the resulting <units> object, which will be
newly created if there are any changes made, or this object if not.

Definition at line 2730 of file pycml.py.

2730 def expand(self):
2731 """Expand to a product of powers of base units.
2732
2733 Expand this units definition according to the algorithm given in appendix C.3.4 of the CellML spec.
2734
2735 Caches and returns the resulting <units> object, which will be
2736 newly created if there are any changes made, or this object if not.
2737 """
2738 if self._cml_expanded is None:
2739 # Do the expansion
2740 if self.is_base_unit():
2741 # We are a base unit, so stop the recursion; the result is us
2742 self._cml_expanded = self
2743 elif self.is_simple():
2744 # Simple units definition, i.e. only one <unit> element,
2745 # exponent=1, and referenced units are simple or base.
2746 # Expand the units referenced by our <unit> element
2747 expanded_child = self.unit.get_units_element().expand()
2748 # Get our multiplicative factor & offset as numbers
2749 m1p1 = self.unit.get_multiplicative_factor()
2750 o1 = self.unit.get_offset()
2751 if expanded_child.is_base_unit():
2752 # New multiplier, etc. are just ours
2753 m_new = m1p1
2754 o_new = o1
2755 # Referenced units are expanded_child
2756 ref_obj_new = expanded_child
2757 else:
2758 # Get the multiplier & offset of our expanded child
2759 m2p2 = expanded_child.unit.get_multiplicative_factor()
2760 o2 = expanded_child.unit.get_offset()
2761 # Calculate new multiplier, etc. per Equation (11)
2762 m_new = m1p1*m2p2
2763 o_new = o1 + o2/m1p1
2764 # Referenced units are those referenced by expanded_child
2765 # These will be base units
2766 ref_obj_new = expanded_child.unit.get_units_element()
2767 # Create the new units & unit elements
2768 attrs = {u'name': self.name}
2769 self._cml_expanded = self.xml_create_element(u'units',
2770 NSS[u'cml'],
2771 attributes=attrs)
2772 self._cml_expanded._cml_generated = True
2773 attrs = {u'units': ref_obj_new.name,
2774 u'multiplier': unicode(m_new),
2775 u'offset': unicode(o_new)}
2776 unit = self.xml_create_element(u'unit', NSS[u'cml'],
2777 attributes=attrs)
2778 # Manually set the reference object for unit, since we have
2779 # it handy
2780 unit._set_units_element(ref_obj_new)
2781 self._cml_expanded.xml_append(unit)
2782 else:
2783 # Complex units definition, i.e. multiple <unit> elements,
2784 # or non-unitary exponent, at some point within this defn.
2785 # Create the new units element so we can add children to it
2786 attrs = {u'name': self.name}
2787 exp_units = self.xml_create_element(u'units', NSS[u'cml'],
2788 attributes=attrs)
2789 exp_units._cml_generated = True
2790 # Compute m_t (Equation (18)) expanding referenced
2791 # units as we go
2792 m_t = 1
2793 for unit in self.unit:
2794 m_t *= unit.get_multiplicative_factor() # * is assoc. :)
2795 # We'll need the exponent to modify units referenced
2796 # by this reference
2797 e = unit.get_exponent()
2798 # Expand referenced units
2799 exp_u = unit.get_units_element().expand()
2800 if exp_u.is_base_unit():
2801 # Create reference to exp_u
2802 attrs = {u'units': exp_u.name,
2803 u'exponent': unicode(e)}
2804 u = self.xml_create_element(u'unit', NSS[u'cml'],
2805 attributes=attrs)
2806 exp_units.xml_append(u)
2807 else:
2808 # Process units referenced by exp_u, which will be
2809 # base units.
2810 for u in exp_u.unit:
2811 m_t *= u.get_multiplicative_factor() ** e
2812 attrs = {u'units': u.units,
2813 u'exponent': unicode(
2814 u.get_exponent() * e)}
2815 u_new = u.xml_create_element(u'unit',
2816 NSS[u'cml'],
2817 attributes=attrs)
2818 exp_units.xml_append(u_new)
2819 # Set the multiplier for the expanded units to m_t.
2820 # Since a <units> elements doesn't have a multiplier
2821 # attribute, we set it on the first <unit> element.
2822 # Note that all the <unit> elements have been newly created,
2823 # so have an implicit multiplier of 1 currently.
2824 # Note also that the fact that each <unit> has an exponent
2825 # doesn't matter, since the exponent doesn't affect the
2826 # multiplier.
2827 # Alan pointed out a bug: if the <unit> elements are
2828 # in non-canonical order then we can get identical
2829 # units (according to the intended canonical form)
2830 # comparing as non-equal, because expansion put the
2831 # multiplicative factor on different <unit> elements
2832 # in each case. Hence we have to put the factor on
2833 # the first <unit> element according to a canonical
2834 # sorting order.
2835 # TODO: Be a bit cleverer about this? In the base unit case
2836 # above we could do exp_units.xml_append(unit.clone()) and
2837 # not have its multiplicative factor contributing to m_t.
2838 # Would then need to multiply here, since first unit may
2839 # already have multiplier != 1.
2840 # Alternative idea from Alan: I have just noticed that
2841 # when expanding a complex units definition based on a
2842 # complex units definition, we can get away with not
2843 # sorting the unit elements. All that is required is
2844 # to create a new unit element which type is
2845 # dimensionless and value of its multiplier attribute
2846 # m*10^(p*e). This avoids having to sort things and
2847 # propagating the multiplier attribute...
2848 first_unit = sorted(exp_units.unit, key=lambda u: u.units)[0]
2849 first_unit.multiplier = unicode(m_t)
2850 # Cache result
2851 self._cml_expanded = exp_units
2852 # Set parent of the expanded units to be our parent
2853 self._cml_expanded.xml_parent = self.xml_parent
2854 # Returned the cached result
2855 return self._cml_expanded
2856
def expand(self)
Definition: pycml.py:2730

◆ extract()

def CellMLToNektar.pycml.extract (   self,
  check_equality = False 
)
Return these units.

Used for interface compatibility with UnitsSet.

Definition at line 2657 of file pycml.py.

2657 def extract(self, check_equality=False):
2658 """Return these units.
2659
2660 Used for interface compatibility with UnitsSet."""
2661 return self
2662
def extract(self, check_equality=False)
Definition: pycml.py:2657

Referenced by CellMLToNektar.pycml.mathml_units_mixin._add_units_conversion(), CellMLToNektar.pycml.mathml._ensure_units_exist(), CellMLToNektar.pycml.mathml_eq._set_in_units(), CellMLToNektar.processors.InterfaceGenerator._split_ode(), Geometry_Init(), Geometry_Init_Curved(), CellMLToNektar.pycml.mathml_cn.get_units(), and CellMLToNektar.pycml.mathml_ci.get_units().

◆ get_multiplicative_factor()

def CellMLToNektar.pycml.get_multiplicative_factor (   self)
Return the multiplicative factor of this units definition.

The multiplicative factor of a units definition can be defined as
the product of the multiplicative factors of its unit children.

Definition at line 2876 of file pycml.py.

2876 def get_multiplicative_factor(self):
2877 """Return the multiplicative factor of this units definition.
2878
2879 The multiplicative factor of a units definition can be defined as
2880 the product of the multiplicative factors of its unit children.
2881 """
2882 m = reduce(operator.mul,
2883 map(lambda unit: unit.get_multiplicative_factor(),
2884 getattr(self, u'unit', [])),
2885 1)
2886 return m
2887

Referenced by CellMLToNektar.pycml.mathml_units_mixin_choose_nearest._set_in_units(), CellMLToNektar.pycml.mathml_units_mixin_equalise_operands._set_in_units(), CellMLToNektar.pycml.equals(), and CellMLToNektar.pycml.UnitsSet.extract().

◆ get_multiplier()

def CellMLToNektar.pycml.get_multiplier (   self)
Return the multiplier of this units definition.

The multiplier of a units definition can be defined as the product
of the multipliers of its unit children.

Definition at line 2888 of file pycml.py.

2888 def get_multiplier(self):
2889 """Return the multiplier of this units definition.
2890
2891 The multiplier of a units definition can be defined as the product
2892 of the multipliers of its unit children.
2893 """
2894 return reduce(operator.mul,
2895 map(lambda unit: unit.get_multiplier(),
2896 getattr(self, u'unit', [])),
2897 1)
2898
def get_multiplier(self)
Definition: pycml.py:2888

◆ get_offset()

def CellMLToNektar.pycml.get_offset (   self)
Return the offset associated with this units definition.

If these are simple units, return the offset on our unit child.
Otherwise, return 0.

Definition at line 2899 of file pycml.py.

2899 def get_offset(self):
2900 """Return the offset associated with this units definition.
2901
2902 If these are simple units, return the offset on our unit child.
2903 Otherwise, return 0.
2904 """
2905 if self.is_simple():
2906 o = self.unit.get_offset()
2907 else:
2908 o = 0
2909 return o
2910

References CellMLToNektar.pycml.get_offset().

Referenced by CellMLToNektar.pycml.equals(), CellMLToNektar.pycml.UnitsSet.extract(), CellMLToNektar.pycml.get_offset(), and CellMLToNektar.pycml.cellml_units.uniquify_tuple().

◆ get_units_by_name()

def CellMLToNektar.pycml.get_units_by_name (   self,
  uname 
)

◆ import_processors()

def CellMLToNektar.pycml.import_processors ( )
Lazy import.

Definition at line 84 of file pycml.py.

85 """Lazy import."""
86 global processors
87 if processors is None:
88 import processors
89
90
def import_processors()
Definition: pycml.py:84

Referenced by CellMLToNektar.pycml.cellml_model.add_units_conversions().

◆ is_base_unit()

def CellMLToNektar.pycml.is_base_unit (   self)
Return True iff this is a base units definition.

Definition at line 2857 of file pycml.py.

2857 def is_base_unit(self):
2858 """Return True iff this is a base units definition."""
2859 return getattr(self, u'base_units', u'no') == u'yes'
def is_base_unit(self)
Definition: pycml.py:2857

◆ is_simple()

def CellMLToNektar.pycml.is_simple (   self)
Return True iff this is a simple units definition.

Units are simple if:
  there is 1 <unit> element
  the exponent is omitted or has value 1.0
  the referenced units are simple or base units

Definition at line 2860 of file pycml.py.

2860 def is_simple(self):
2861 """Return True iff this is a simple units definition.
2862
2863 Units are simple if:
2864 there is 1 <unit> element
2865 the exponent is omitted or has value 1.0
2866 the referenced units are simple or base units
2867 """
2868 simple = False
2869 if not self.is_base_unit() and len(self.unit) == 1:
2870 if self.unit.get_exponent() == 1.0:
2871 u = self.unit.get_units_element()
2872 if u.is_base_unit() or u.is_simple():
2873 simple = True
2874 return simple
2875
def is_simple(self)
Definition: pycml.py:2860

◆ make_xml_binder()

def CellMLToNektar.pycml.make_xml_binder ( )

Helpful utility functions #.

Create a specialised binder, given some mappings from element names
to python classes, and setting namespace prefixes.

Definition at line 168 of file pycml.py.

168def make_xml_binder():
169 """
170 Create a specialised binder, given some mappings from element names
171 to python classes, and setting namespace prefixes.
172 """
173 binder = amara.bindery.binder(prefixes=NSS)
174 binder.set_binding_class(NSS[u'cml'], "model", cellml_model)
175 binder.set_binding_class(NSS[u'cml'], "component", cellml_component)
176 binder.set_binding_class(NSS[u'cml'], "variable", cellml_variable)
177 binder.set_binding_class(NSS[u'cml'], "units", cellml_units)
178 binder.set_binding_class(NSS[u'cml'], "unit", cellml_unit)
179 for mathml_elt in ['math', 'degree', 'logbase', 'otherwise',
180 'diff', 'plus', 'minus', 'times', 'divide',
181 'exp', 'ln', 'log', 'abs', 'power', 'root',
182 'leq', 'geq', 'lt', 'gt', 'eq', 'neq',
183 'rem',
184 'ci', 'cn', 'apply', 'piecewise', 'piece',
185 'sin', 'cos', 'tan', 'arcsin', 'arccos', 'arctan']:
186 exec "binder.set_binding_class(NSS[u'm'], '%s', mathml_%s)" % (mathml_elt, mathml_elt)
187 binder.set_binding_class(NSS[u'm'], "and_", mathml_and)
188 binder.set_binding_class(NSS[u'm'], "or_", mathml_or)
189 return binder
190

Referenced by CellMLToNektar.pycml.amara_parse_cellml().

◆ model()

def CellMLToNektar.pycml.model (   self)

Definition at line 2654 of file pycml.py.

2654 def model(self):
2655 return self.rootNode.model
2656
def model(self)
Definition: pycml.py:2654

◆ quotient()

def CellMLToNektar.pycml.quotient (   self,
  other_units 
)
Form the quotient of two units definitions.

This method does not simplify the resulting units.
Quotient units will be cached.

Definition at line 3154 of file pycml.py.

3154 def quotient(self, other_units):
3155 """Form the quotient of two units definitions.
3156
3157 This method does not simplify the resulting units.
3158 Quotient units will be cached.
3159 """
3160 if not other_units in self._cml_quotients:
3161 # Create new <units> element
3162 self.units_name_counter[0] += 1
3163 uname = u'___units_' + str(self.units_name_counter[0])
3164 quotient_units = self.xml_create_element(
3165 u'units', NSS[u'cml'], attributes={u'name': uname})
3166 quotient_units._cml_generated = True
3167 quotient_units.xml_parent = self._best_parent(other_units)
3168 # Invent references to the constituent units
3169 u = self.xml_create_element(u'unit', NSS[u'cml'],
3170 attributes={u'units': self.name})
3171 u._set_units_element(self)
3172 quotient_units.xml_append(u)
3173 u = self.xml_create_element(u'unit', NSS[u'cml'],
3174 attributes={u'units': self.name,
3175 u'exponent': u'-1'})
3176 u._set_units_element(other_units)
3177 quotient_units.xml_append(u)
3178 # Cache
3179 if self.model._is_new_units_obj(quotient_units):
3180 quotient_units.xml_parent.add_units(uname, quotient_units)
3181 quotient_units = self.model._get_units_obj(quotient_units)
3182 self._cml_quotients[other_units] = quotient_units
3183 return self._cml_quotients[other_units]
3184
def quotient(self, other_units)
Definition: pycml.py:3154

Referenced by CellMLToNektar.processors.InterfaceGenerator._split_ode().

◆ same_tree()

def CellMLToNektar.pycml.same_tree (   self,
  other,
  this = None 
)
Check whether this element represents the same tree as a given element.

Definition at line 3897 of file pycml.py.

3897 def same_tree(self, other, this=None):
3898 """Check whether this element represents the same tree as a given element."""
3899 if this is None: this = self
3900 equal = (this.localName == other.localName
3901 and len(getattr(this, 'xml_children', [])) == len(getattr(other, 'xml_children', [])))
3902 if equal and this.localName in [u'cn', u'ci']:
3903 equal = unicode(this) == unicode(other)
3904 if equal and hasattr(this, 'xml_children'):
3905 for tc, oc in zip(self.xml_element_children(this), self.xml_element_children(other)):
3906 if not self.same_tree(oc, tc):
3907 equal = False
3908 break
3909 return equal
3910
def same_tree(self, other, this=None)
Definition: pycml.py:3897

◆ simplify()

def CellMLToNektar.pycml.simplify (   self,
  other_units = None,
  other_exponent = 1 
)
Simplify these units.

Create a new <units> element representing a simplified version of
this element.  This implements the algorithm of appendix C.3.1.  It
is however slightly different, in order to allow for units
conversions rather than just preserving dimensional equivalence.

If other_units is not None, then produce a simplified version of
the product of these units and other_units.  other_units are
considered to be raised to the power of other_exponent (so a
quotient can be performed by passing other_exponent=-1).  Note that
other_exponent should have numeric type.

If other_units is a UnitsSet, then we construct a UnitsSet
containing self, and call the simplify method on that, thus
returning a UnitsSet instance.

Multiplicative factors on the original <unit> objects are
maintained on the generated references, by taking the product of
all factors from <unit> objects that contribute to the new <unit>
object.  Note that this means that we may need to retain a
reference to dimensionless with a multiplier, for example if the
quotient of centimetres by metres is taken.

Offsets are only permitted on simple units, so may not appear where
there are multiple <unit> elements.  Hence when a product of units
is taken, any offsets are discarded.

Definition at line 2967 of file pycml.py.

2967 def simplify(self, other_units=None, other_exponent=1):
2968 """Simplify these units.
2969
2970 Create a new <units> element representing a simplified version of
2971 this element. This implements the algorithm of appendix C.3.1. It
2972 is however slightly different, in order to allow for units
2973 conversions rather than just preserving dimensional equivalence.
2974
2975 If other_units is not None, then produce a simplified version of
2976 the product of these units and other_units. other_units are
2977 considered to be raised to the power of other_exponent (so a
2978 quotient can be performed by passing other_exponent=-1). Note that
2979 other_exponent should have numeric type.
2980
2981 If other_units is a UnitsSet, then we construct a UnitsSet
2982 containing self, and call the simplify method on that, thus
2983 returning a UnitsSet instance.
2984
2985 Multiplicative factors on the original <unit> objects are
2986 maintained on the generated references, by taking the product of
2987 all factors from <unit> objects that contribute to the new <unit>
2988 object. Note that this means that we may need to retain a
2989 reference to dimensionless with a multiplier, for example if the
2990 quotient of centimetres by metres is taken.
2991
2992 Offsets are only permitted on simple units, so may not appear where
2993 there are multiple <unit> elements. Hence when a product of units
2994 is taken, any offsets are discarded.
2995 """
2996 if isinstance(other_units, UnitsSet):
2997 # Use the set version of simplify
2998 return UnitsSet([self]).simplify(other_units, other_exponent)
2999
3000 # Check for result in cache (see #1714)
3001 if (other_units, other_exponent) in self._cml_simplified:
3002 return self._cml_simplified[(other_units, other_exponent)]
3003
3004 # Make a list of all <unit> elements to be included
3005 units = []
3006 if self.is_base_unit():
3007 # We are a base unit, so invent a reference to ourselves
3008 u = self.xml_create_element(u'unit', NSS[u'cml'],
3009 attributes={u'units': self.name})
3010 u.xml_parent = self # Hack, but it might need a parent...
3011 u._set_units_element(self)
3012 units.append(u)
3013 else:
3014 units = list(self.unit)
3015 our_unit_elements = frozenset(units)
3016 other_unit_elements = None
3017 if not other_units is None:
3018 if other_units.is_base_unit():
3019 # other_units are base units, so invent a reference
3020 attrs = {u'units': other_units.name,
3021 u'exponent': unicode(other_exponent)}
3022 u = self.xml_create_element(u'unit', NSS[u'cml'],
3023 attributes=attrs)
3024 u.xml_parent = other_units
3025 u._set_units_element(other_units)
3026 units.append(u)
3027 if other_exponent == 1:
3028 other_unit_elements = frozenset([u])
3029 else:
3030 if other_exponent == 1:
3031 units.extend(list(other_units.unit))
3032 other_unit_elements = frozenset(other_units.unit)
3033 else:
3034 for unit in other_units.unit:
3035 # Need to create a new <unit> element with different
3036 # exponent and multiplier
3037 u = unit.clone()
3038 u.exponent = unicode(other_exponent *
3039 u.get_exponent())
3040 u.multiplier = unicode(u.get_multiplier() **
3041 other_exponent)
3042 units.append(u)
3043 # Sort <unit> elements according to the <units> objects they
3044 # reference
3045 dimensionless = self.get_units_by_name(u'dimensionless')
3046 d = {dimensionless: []}
3047 for unit in units:
3048 obj = unit.get_units_element()
3049 if obj in d:
3050 d[obj].append(unit)
3051 else:
3052 d[obj] = [unit]
3053 # Collapse equivalent units references into a single reference.
3054 # That is, all references to the same object get collapsed into a new
3055 # reference to that object with different exponent, etc.
3056 for obj in d.keys():
3057 if obj != dimensionless and len(d[obj]) > 1:
3058 # Sum the exponents
3059 expt = sum(map(lambda u: u.get_exponent(), d[obj]))
3060 # If exponents cancel, replace with ref to dimensionless
3061 if expt == 0:
3062 attrs = {u'units': u'dimensionless'}
3063 else:
3064 attrs = {u'units': d[obj][0].units,
3065 u'exponent': unicode(expt)}
3066 # Compute the multiplier for the new unit reference, as
3067 # the product of multiplicative factors on the originals
3068 m = reduce(operator.mul,
3069 map(lambda u: u.get_multiplicative_factor(),
3070 d[obj]))
3071 attrs[u'multiplier'] = unicode(m)
3072 # Create a new reference
3073 new = self.xml_create_element(u'unit', NSS[u'cml'],
3074 attributes=attrs)
3075 new.xml_parent = self
3076 if expt == 0:
3077 # Note an extra reference to dimensionless...
3078 d[dimensionless].append(new)
3079 # ...and remove the references to obj from d
3080 del d[obj]
3081 else:
3082 d[obj] = new
3083 elif obj != dimensionless and d[obj]:
3084 # d[obj] is a singleton list. Create a new reference and
3085 # store it instead (a new reference is needed to avoid
3086 # altering the linked list from self.unit).
3087 d[obj] = d[obj][0].clone()
3088 # Note d must have at least one key, namely dimensionless
3089 # If dimensionless is referenced in addition to other units,
3090 # remove the references to dimensionless.
3091 # But remember the multipliers!
3092 m = reduce(operator.mul,
3093 map(lambda u: u.get_multiplicative_factor(),
3094 d[dimensionless]),
3095 1)
3096 if m == 1:
3097 del d[dimensionless]
3098 else:
3099 # Retain a single reference to dimensionless, with the
3100 # combined multiplier.
3101 d[dimensionless] = d[dimensionless][0].clone()
3102 d[dimensionless].multiplier = unicode(m)

References CellMLToNektar.pycml.simplify().

Referenced by CellMLToNektar.pycml.mathml_units_mixin._add_units_conversion(), CellMLToNektar.pycml.dimensionally_equivalent(), CellMLToNektar.CellMLToNektarTranslator.CellMLToNektarTranslator.generate_interface(), and CellMLToNektar.pycml.simplify().

◆ varobj()

def CellMLToNektar.pycml.varobj (   self,
  ci_elt 
)
Return the variable object for the given ci element.

This method is more general than ci_elt.variable, working even
for ci elements outside of a component.  Such elements *must*
contain a fully qualified variable name, i.e. including the
name of the component the variable occurs in.  This method
handles a variety of encodings of variable names that contain
the component name.

Definition at line 3853 of file pycml.py.

3853 def varobj(self, ci_elt):
3854 """Return the variable object for the given ci element.
3855
3856 This method is more general than ci_elt.variable, working even
3857 for ci elements outside of a component. Such elements *must*
3858 contain a fully qualified variable name, i.e. including the
3859 name of the component the variable occurs in. This method
3860 handles a variety of encodings of variable names that contain
3861 the component name.
3862 """
3863 try:
3864 var = ci_elt.variable
3865 except:
3866 varname = unicode(ci_elt).strip()
3867 var = cellml_variable.get_variable_object(self.model, varname)
3868 return var
3869
def varobj(self, ci_elt)
Definition: pycml.py:3853

◆ vars_in()

def CellMLToNektar.pycml.vars_in (   self,
  expr 
)
Return a list of 'variable' objects used in the given expression.

This method doesn't make use of the dependency information
generated when validating the model, but parses the
mathematics afresh.  It is used to refresh the dependency
lists after partial evaluation, and to determine dependencies
in mathematics added outside the normal model structure
(e.g. Jacobian calculation).

If an ODE appears, includes the mathml_apply instance defining
the ODE.  Otherwise all returned objects will be
cellml_variable instances.

Definition at line 3870 of file pycml.py.

3870 def vars_in(self, expr):
3871 """Return a list of 'variable' objects used in the given expression.
3872
3873 This method doesn't make use of the dependency information
3874 generated when validating the model, but parses the
3875 mathematics afresh. It is used to refresh the dependency
3876 lists after partial evaluation, and to determine dependencies
3877 in mathematics added outside the normal model structure
3878 (e.g. Jacobian calculation).
3879
3880 If an ODE appears, includes the mathml_apply instance defining
3881 the ODE. Otherwise all returned objects will be
3882 cellml_variable instances.
3883 """
3884 res = set()
3885 if isinstance(expr, mathml_ci):
3886 res.add(self.varobj(expr))
3887 elif isinstance(expr, mathml_apply) and \
3888 expr.operator().localName == u'diff':
3889 dep_var = self.varobj(expr.ci)
3890 indep_var = self.varobj(expr.bvar.ci)
3891 res.add(dep_var.get_ode_dependency(indep_var))
3892 elif hasattr(expr, 'xml_children'):
3893 for child in expr.xml_children:
3894 res.update(self.vars_in(child))
3895 return res
3896
def vars_in(self, expr)
Definition: pycml.py:3870

Variable Documentation

◆ __version__

list CellMLToNektar.pycml.__version__ = "$Revision: 25949 $"[11:-2]
private

Definition at line 91 of file pycml.py.

◆ _cml_expanded

CellMLToNektar.pycml._cml_expanded
private

Definition at line 2742 of file pycml.py.

◆ _cml_generated

CellMLToNektar.pycml._cml_generated
private

Definition at line 3128 of file pycml.py.

◆ attrs

dictionary CellMLToNektar.pycml.attrs = {(u'cml:units', NSS[u'cml']): units.name}

Definition at line 3847 of file pycml.py.

◆ base_units

CellMLToNektar.pycml.base_units

Definition at line 2948 of file pycml.py.

◆ BINDING_TIMES

CellMLToNektar.pycml.BINDING_TIMES = Enum('static', 'dynamic')

Definition at line 161 of file pycml.py.

◆ cellml

CellMLToNektar.pycml.cellml

Definition at line 3835 of file pycml.py.

◆ CELLML_SUBSET_ELTS

CellMLToNektar.pycml.CELLML_SUBSET_ELTS
Initial value:
1= frozenset(
2 ['math', 'cn', 'sep', 'ci', 'apply', 'piecewise', 'piece', 'otherwise',
3 'eq', 'neq', 'gt', 'lt', 'geq', 'leq',
4 'plus', 'minus', 'times', 'divide', 'power', 'root', 'abs',
5 'exp', 'ln', 'log', 'floor', 'ceiling', 'factorial',
6 'and', 'or', 'not', 'xor',
7 'diff', 'degree', 'bvar', 'logbase',
8 'sin', 'cos', 'tan', 'sec', 'csc', 'cot',
9 'sinh', 'cosh', 'tanh', 'sech', 'csch', 'coth',
10 'arcsin', 'arccos', 'arctan', 'arcsec', 'arccsc', 'arccot',
11 'arcsinh', 'arccosh', 'arctanh', 'arcsech', 'arccsch', 'arccoth',
12 'true', 'false', 'notanumber', 'pi', 'infinity', 'exponentiale',
13 'semantics', 'annotation', 'annotation-xml'])

Definition at line 146 of file pycml.py.

◆ format

CellMLToNektar.pycml.format

Definition at line 101 of file pycml.py.

Referenced by Nektar::SolverUtils.AddSummaryItem(), Nektar::SolverUtils::UnsteadySystem.CheckSteadyState(), Nektar::LinearisedAdvection.DFT(), Nektar::SolverUtils::FileFieldInterpolator.DFT(), Nektar::SolverUtils::CouplingCwipi.DumpRawFields(), Nektar::SolverUtils::SessionFunction.EvaluateFld(), Nektar::SolverUtils::SessionFunction.EvaluatePts(), Nektar::LibUtilities::PtsIO.Import(), Nektar::LibUtilities::SessionReader.LoadDoc(), Nektar::SolverUtils::FilterLagrangianPoints.OutputStatPoints(), Nektar::LibUtilities::FieldIOXml.SetUpFieldMetaData(), Nektar::LibUtilities::PtsIO.SetUpFieldMetaData(), Nektar::LibUtilities::FieldIO.SetUpOutput(), Nektar::SolverUtils::DriverParallelInTime.SolutionConvergenceMonitoring(), Nektar::SolverUtils::ForcingMovingReferenceFrame.UpdateFrameVelocity(), Nektar::SolverUtils::DriverParareal.v_Execute(), Nektar::SolverUtils::DriverPFASST.v_Execute(), Nektar::FieldUtils::OutputFld.v_GetFullOutName(), Nektar::FieldUtils::OutputVtkBase.v_GetFullOutName(), Nektar::SolverUtils::FilterLagrangianPoints.v_Initialise(), Nektar::SpatialDomains::MeshGraphIOXml.v_PartitionMesh(), Nektar::FieldUtils::OutputInfo.v_Process(), Nektar::FieldUtils::ProcessAverageFld.v_Process(), Nektar::SolverUtils::CouplingFile.v_Receive(), Nektar::SolverUtils::CouplingFile.v_Send(), Nektar::SolverUtils::FilterHistoryPoints.v_WriteData(), Nektar::FilterCellHistoryPoints.v_WriteData(), Nektar::IterativeElasticSystem.WriteGeometry(), Nektar::FieldUtils::OutputVtk.WritePVtu(), Nektar::FieldUtils::OutputVtkBase.WritePVtu(), and Nektar::SpatialDomains::MeshGraphIOXml.WriteXMLGeometry().

◆ level

CellMLToNektar.pycml.level

◆ msg

string CellMLToNektar.pycml.msg = "Adding units " + units.name + " as "

◆ name

CellMLToNektar.pycml.name

Definition at line 3835 of file pycml.py.

Referenced by Nektar::LibUtilities::H5::CompoundDataType.Add(), Nektar::LibUtilities::TagWriter.AddChild(), Nektar::LibUtilities::Interpreter::ExpressionEvaluator.AddConstant(), Nektar::LibUtilities::Interpreter.AddConstant(), Nektar::SpatialDomains::Movement.AddInterface(), Nektar::LibUtilities::H5::CompoundDataType.AddString(), Nektar::SolverUtils.AddSummaryItem(), Nektar::FieldUtils::ConfigOption.as(), Nektar::SolverUtils::RiemannSolver.CheckAuxScal(), Nektar::SolverUtils::RiemannSolver.CheckAuxVec(), Nektar::SolverUtils::RiemannSolver.CheckParams(), Nektar::SolverUtils::RiemannSolver.CheckScalars(), Nektar::SolverUtils::RiemannSolver.CheckVectors(), Nektar::LibUtilities::H5::Attribute.Create(), Nektar::LibUtilities::H5::CanHaveAttributes.CreateAttribute(), Nektar::LibUtilities::H5::CanHaveGroupsDataSets.CreateDataSet(), CreateExceptionClass(), Nektar::LibUtilities::H5::CanHaveGroupsDataSets.CreateGroup(), Nektar::LibUtilities::H5::CanHaveGroupsDataSets.CreateWriteDataSet(), NekFactory_Register< tFac< tKey, tBase, tParam... > >.DoRegister(), EquationSystem_GetFunction1(), EquationSystem_GetFunction2(), EquationSystem_WriteFld(), export_DisContField_Helper(), export_Geom_2d(), export_Geom_3d(), Nektar::LibUtilities::H5::CanHaveAttributes.GetAttribute(), Nektar::LibUtilities::Interpreter::ExpressionEvaluator.GetConstant(), Nektar::LibUtilities::Interpreter.GetConstant(), Nektar::LibUtilities::H5::Group.GetElementNames(), Nektar::SolverUtils::EquationSystem.GetFunction(), Nektar::LibUtilities::Interpreter::ExpressionEvaluator.GetParameter(), Nektar::LibUtilities::Interpreter.GetParameter(), Nektar::LibUtilities::H5::CanHaveAttributes::AttrIterator.helper(), Nektar::LibUtilities::H5::CanHaveGroupsDataSets::LinkIterator.helper(), main(), Nektar::LibUtilities::SessionReader.MatchSolverInfoAsEnum(), Nektar::LibUtilities::H5::Attribute.Open(), Nektar::LibUtilities::H5::CanHaveAttributes.OpenAttribute(), Nektar::LibUtilities::H5::CanHaveGroupsDataSets.OpenDataSet(), Nektar::LibUtilities::H5::CanHaveGroupsDataSets.OpenGroup(), NekFactory_Register< tFac< tKey, tBase, tParam... > >.operator()(), Nektar::SolverUtils::FilterFieldConvert.OutputField(), Nektar::FieldUtils::OutputVtk.OutputFromExpLowOrderMultiBlock(), Nektar::SpatialDomains::BoundaryConditions.ReadBoundaryRegions(), Nektar::SpatialDomains::MeshGraphIOXml.ReadComposites(), Nektar::SpatialDomains::Movement.ReadInterfaces(), Nektar::LibUtilities::H5::CanHaveAttributes.SetAttribute(), Nektar::SolverUtils::RiemannSolver.SetAuxScal(), Nektar::SolverUtils::RiemannSolver.SetAuxVec(), Nektar::SolverUtils::RiemannSolver.SetParam(), Nektar::LibUtilities::Equation.SetParameter(), Nektar::LibUtilities::Interpreter::ExpressionEvaluator.SetParameter(), Nektar::LibUtilities::Interpreter.SetParameter(), Nektar::SolverUtils::RiemannSolver.SetScalar(), Nektar::SolverUtils::RiemannSolver.SetVector(), Nektar::LibUtilities::H5TagWriter.v_AddChild(), Nektar::LibUtilities::XmlTagWriter.v_AddChild(), Nektar::SolverUtils::DriverArpack.v_Execute(), Nektar::Poisson.v_GenerateSummary(), Nektar::Projection.v_GenerateSummary(), Nektar::FieldUtils::OutputFileBase.v_Process(), and Nektar::FieldUtils::ProcessMean.v_Process().

◆ new_units

def CellMLToNektar.pycml.new_units = dimensionless

print "Keeping d'less ref with m =",m,"from", print self.description(), if other_units: print "and",other_units.description() else: print

print "Adding",uname,hash(new_units),new_units.description()

print ".simplify", uname

Definition at line 3113 of file pycml.py.

◆ NSS

dictionary CellMLToNektar.pycml.NSS
Initial value:
1= {u'm' : u'http://www.w3.org/1998/Math/MathML',
2 u'cml': u'http://www.cellml.org/cellml/1.0#',
3 # Our extensions; URIs will probably change?
4 u'pe': u'https://chaste.comlab.ox.ac.uk/cellml/ns/partial-evaluation#',
5 u'lut': u'https://chaste.comlab.ox.ac.uk/cellml/ns/lookup-tables',
6 u'solver': u'https://chaste.comlab.ox.ac.uk/cellml/ns/solver-info',
7 u'oxmeta': u'https://chaste.comlab.ox.ac.uk/cellml/ns/oxford-metadata#',
8 u'pycml': u'https://chaste.comlab.ox.ac.uk/cellml/ns/pycml#',
9 u'proto': u'https://chaste.cs.ox.ac.uk/nss/protocol/0.1#',
10 # Metadata-related
11 u'cmeta' : u"http://www.cellml.org/metadata/1.0#",
12 u'rdf' : u"http://www.w3.org/1999/02/22-rdf-syntax-ns#",
13 u'dc' : u"http://purl.org/dc/elements/1.1/",
14 u'dcterms': u"http://purl.org/dc/terms/",
15 u'bqs' : u"http://www.cellml.org/bqs/1.0#",
16 u'vCard' : u"http://www.w3.org/2001/vcard-rdf/3.0#",
17 u'cg' : u"http://www.cellml.org/metadata/graphs/1.0#",
18 u'cs' : u"http://www.cellml.org/metadata/simulation/1.0#",
19 u'csub' : u"http://www.cellml.org/metadata/custom_subset/1.0#",
20 u'bqbiol' : u"http://biomodels.net/biology-qualifiers/",
21 # Temporary documentation namespace
22 u'doc' : u"http://cellml.org/tmp-documentation"
23 }

Definition at line 116 of file pycml.py.

◆ processors

CellMLToNektar.pycml.processors = None

Definition at line 83 of file pycml.py.

◆ stream

CellMLToNektar.pycml.stream

Definition at line 102 of file pycml.py.

◆ uname

string CellMLToNektar.pycml.uname = u'___units_' + str(self.units_name_counter[0])

Definition at line 3124 of file pycml.py.

◆ unit_elements

CellMLToNektar.pycml.unit_elements = set(d.values())

Definition at line 3116 of file pycml.py.

◆ units

CellMLToNektar.pycml.units = self.model._get_units_obj(units)

_u = units

print "Adding",units.name, hash(units), units.description(), print "(was",id(_u),"now",id(units),")" Ensure referenced units exist

Definition at line 3825 of file pycml.py.

◆ units_name_counter

list CellMLToNektar.pycml.units_name_counter = [0]

Definition at line 2966 of file pycml.py.

◆ VarTypes

CellMLToNektar.pycml.VarTypes
Initial value:
1= Enum('Unknown', 'Free', 'State', 'MaybeConstant', 'Constant',
2 'Computed', 'Mapped')
def Enum(*names)
Definition: enum.py:8

Definition at line 142 of file pycml.py.

◆ WARNING_TRANSLATE_ERROR

CellMLToNektar.pycml.WARNING_TRANSLATE_ERROR

Definition at line 108 of file pycml.py.

◆ xml_parent

CellMLToNektar.pycml.xml_parent

Definition at line 3130 of file pycml.py.