Nektar++
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
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
 
def check_append_safety
 
def add_methods_to_amara
 
def _rel_error_ok
 def eq(self, other): """Compare 2 units elements for equality. More...
 
def equals
 
def model
 
def extract
 
def copy
 
def description
 
def get_units_by_name
 
def expand
 
def is_base_unit
 
def is_simple
 
def get_multiplicative_factor
 
def get_multiplier
 
def get_offset
 
def create_new
 
def _based_on
 
def simplify
 
def _best_parent
 
def quotient
 
def dimensionally_equivalent
 
def child_i
 
def _child1
 
def varobj
 
def vars_in
 
def same_tree
 
def _xfer_complexity
 
def _adjust_complexity
 
def classify_child_variables
 

Variables

 processors = None
 
string __version__ = "$Revision: 25949 $"
 
string format = "%(name)s: %(levelname)s: %(message)s"
 
 stream = sys.stderr)
 
dictionary NSS
 
tuple VarTypes
 
tuple CELLML_SUBSET_ELTS
 
tuple 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...
 
tuple unit_elements = set(d.values())
 
string uname = u'___units_'
 
tuple units = self.model._get_units_obj(units)
 _u = units More...
 
string msg = "Adding units "
 print "Adding",units.name, hash(units), units.description(), print "(was",id(_u),"now",id(units),")" Ensure referenced units exist More...
 
dictionary attrs = {(u'cml:units', NSS[u'cml']): units.name}
 
 _cml_expanded
 
 base_units
 

Function Documentation

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.

References CellMLToNektar.pycml.child_i().

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

Referenced by CellMLToNektar.pycml.create_new().

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

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

Definition at line 3460 of file pycml.py.

References CellMLToNektar.pycml.child_i().

Referenced by CellMLToNektar.pycml.mathml_root._set_in_units(), CellMLToNektar.pycml.mathml_piecewise.evaluate(), CellMLToNektar.pycml.mathml_logbase.evaluate(), CellMLToNektar.pycml.mathml_degree.evaluate(), CellMLToNektar.pycml.mathml_apply.get_units(), and CellMLToNektar.pycml.mathml_apply.operator().

3461 def _child1(elt):
3462  "Get the first child element of elt."
3463  return child_i(elt, 1)
3464 
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.

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

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

Definition at line 323 of file pycml.py.

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

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().

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

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

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

Definition at line 3449 of file pycml.py.

Referenced by CellMLToNektar.pycml._adjust_complexity(), CellMLToNektar.optimize.LinearityAnalyser._check_expr(), CellMLToNektar.pycml._child1(), CellMLToNektar.pycml.mathml_piecewise._get_binding_time(), CellMLToNektar.optimize.LinearityAnalyser._rearrange_expr(), CellMLToNektar.pycml.mathml_piecewise._reduce(), CellMLToNektar.pycml.mathml_piecewise._set_in_units(), CellMLToNektar.pycml.mathml_constructor._tree_complexity(), CellMLToNektar.optimize.LookupTableAnalyser.analyse_for_lut(), CellMLToNektar.pycml.mathml_piecewise.evaluate(), CellMLToNektar.pycml.mathml_piecewise.get_units(), CellMLToNektar.translators.CellMLTranslator.output_expr(), CellMLToNektar.translators.CellMLTranslator.output_piecewise(), and CellMLToNektar.pycml.mathml_piecewise.tree_complexity().

3450 def child_i(elt, i):
3451  "Return the i'th child element of elt. Indexing starts at 1."
3452  j = 0
3453  for e in elt.xml_children:
3454  if getattr(e, 'nodeType', None) == Node.ELEMENT_NODE:
3455  j += 1
3456  if j == i: return e
3457  else:
3458  # Not found :(
3459  raise ValueError("<"+elt.localName+"> does not have "+str(i)+
" child element(s).")
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.

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

Referenced by Nektar::LibUtilities::GaussPoints.CalculateDerivMatrix(), Nektar.CopyArray(), Nektar.CopyArrayN(), Nektar::LinearSystem.FactorMatrix(), CellMLToNektar.pycml.mathml_apply.get_units(), CellMLToNektar.pycml.mathml_piecewise.get_units(), Nektar::NekMeshUtils::Tetrahedron.GetCurvedNodes(), Nektar::NekMeshUtils::Prism.GetCurvedNodes(), Nektar::NekMeshUtils::Triangle.GetCurvedNodes(), Nektar::ArrayInitializationPolicy< ObjectType, typename boost::enable_if< boost::is_fundamental< ObjectType > >::type >.Initialize(), Nektar::LibUtilities::SessionReader.LoadDoc(), Nektar::NekMatrix< DataType, StandardMatrixTag >.NekMatrix(), Nektar.NekMultiplyLowerTriangularMatrix(), Nektar.NekMultiplyUpperTriangularMatrix(), Nektar::NekVector< DataType >.NekVector(), Nektar::NekVector< DataType >.operator=(), Nektar::NekMatrix< DataType, StandardMatrixTag >.operator=(), Nektar::Utilities::OutputNekpp.Process(), Nektar::StorageSmvBsr< T >.processBcoInput(), Nektar::Utilities.quadTensorNodeOrdering(), Nektar::NekMatrix< DataType, StandardMatrixTag >.ResizeDataArrayIfNeeded(), Nektar::Utilities.triTensorNodeOrdering(), Nektar::LibUtilities::FieldIOHdf5.v_Write(), and Nektar::FieldUtils::OutputTecplotBinary.WriteDoubleOrFloat().

2664  def copy(self):
2665  """Return a new UnitsSet containing this cellml_units object.
2666 
2667  Used for interface compatibility with UnitsSet, where the method performs a shallow copy.
2668  """
2669  return UnitsSet([self])
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.

References CellMLToNektar.pycml._based_on().

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

Referenced by CellMLToNektar.translators.CellMLTranslator.output_assignment().

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

References CellMLToNektar.pycml.simplify().

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

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

References CellMLToNektar.pycml.get_multiplicative_factor().

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

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

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

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(), Nektar::Utilities::ProcessOptiExtract.Process(), and Nektar::Utilities::ProcessJac.Process().

2658  def extract(self, check_equality=False):
2659  """Return these units.
2660 
2661  Used for interface compatibility with UnitsSet."""
2662  return self
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.

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

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

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

Referenced by CellMLToNektar.pycml.UnitsSet.extract().

2900  def get_offset(self):
2901  """Return the offset associated with this units definition.
2902 
2903  If these are simple units, return the offset on our unit child.
2904  Otherwise, return 0.
2905  """
2906  if self.is_simple():
2907  o = self.unit.get_offset()
2908  else:
2909  o = 0
2910  return o
def CellMLToNektar.pycml.get_units_by_name (   self,
  uname 
)
Return an object representing the element that defines the units named `uname'.

Definition at line 2725 of file pycml.py.

2726  def get_units_by_name(self, uname):
2727  """Return an object representing the element that defines the units named `uname'."""
2728  # Look up units in our parent model or component element instead
2729  return self.xml_parent.get_units_by_name(uname)
def CellMLToNektar.pycml.import_processors ( )
Lazy import.

Definition at line 84 of file pycml.py.

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

84 
85 def import_processors():
86  """Lazy import."""
87  global processors
88  if processors is None:
89  import processors
90 
def import_processors
Definition: pycml.py:84
def CellMLToNektar.pycml.is_base_unit (   self)
Return True iff this is a base units definition.

Definition at line 2857 of file pycml.py.

2858  def is_base_unit(self):
2859  """Return True iff this is a base units definition."""
return getattr(self, u'base_units', u'no') == u'yes'
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.

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

Referenced by CellMLToNektar.pycml.amara_parse_cellml().

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

Definition at line 2654 of file pycml.py.

2655  def model(self):
2656  return self.rootNode.model
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.

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

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

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

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

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

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

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

Variable Documentation

string CellMLToNektar.pycml.__version__ = "$Revision: 25949 $"

Definition at line 91 of file pycml.py.

CellMLToNektar.pycml._cml_expanded

Definition at line 2742 of file pycml.py.

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

Definition at line 3847 of file pycml.py.

CellMLToNektar.pycml.base_units

Definition at line 2948 of file pycml.py.

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

Definition at line 161 of file pycml.py.

tuple 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.

string CellMLToNektar.pycml.format = "%(name)s: %(levelname)s: %(message)s"

Definition at line 101 of file pycml.py.

Referenced by Nektar::SolverUtils.AddSummaryItem(), Nektar::SolverUtils::EquationSystem.EvaluateFunctionFld(), Nektar::SolverUtils::EquationSystem.EvaluateFunctionPts(), Nektar::LibUtilities::PtsIO.Import(), Nektar::LibUtilities::SessionReader.LoadDoc(), Nektar::LibUtilities::SessionReader.PartitionMesh(), Nektar::FieldUtils::OutputInfo.Process(), Nektar::FieldUtils::OutputVtk.Process(), Nektar::LibUtilities::PtsIO.SetUpFieldMetaData(), Nektar::LibUtilities::FieldIOXml.SetUpFieldMetaData(), Nektar::LibUtilities::FieldIO.SetUpOutput(), Nektar::SolverUtils::FilterHistoryPoints.v_Initialise(), Nektar::SolverUtils::FilterHistoryPoints.v_Update(), Nektar::LibUtilities::MeshPartition.WriteAllPartitions(), Nektar::IterativeElasticSystem.WriteGeometry(), and Nektar::LibUtilities::MeshPartition.WriteLocalPartition().

CellMLToNektar.pycml.msg = "Adding units "

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

Definition at line 3834 of file pycml.py.

Referenced by Nektar::LibUtilities::Equation.Equation(), ErrorUtil.Error(), Nektar::LibUtilities::Equation.Evaluate(), Nektar::MultiRegions::ExpList.GetExpIndex(), and Nektar::Utilities::InputStar.SetupElements().

tuple 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.

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.

CellMLToNektar.pycml.processors = None

Definition at line 83 of file pycml.py.

CellMLToNektar.pycml.stream = sys.stderr)

Definition at line 102 of file pycml.py.

Referenced by Nektar::IncNavierStokes.SetUpWomersley().

string CellMLToNektar.pycml.uname = u'___units_'

Definition at line 3124 of file pycml.py.

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

Definition at line 3116 of file pycml.py.

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

_u = units

Definition at line 3825 of file pycml.py.

list CellMLToNektar.pycml.units_name_counter = [0]

Definition at line 2966 of file pycml.py.

tuple CellMLToNektar.pycml.VarTypes
Initial value:
1 = Enum('Unknown', 'Free', 'State', 'MaybeConstant', 'Constant',
2  'Computed', 'Mapped')

Definition at line 142 of file pycml.py.