def rhs_name_transform_inplace(self, name_map): """Replace atoms on the RHS with values in the name_map""" for name in name_map: replacment = name_map[name] self.rhs = MathUtil.str_expr_replacement(name, replacment, self.rhs)
def test_str_expr_replacement(self): # Signature: name(cls, frm, to, expr_string, func_ok=False) # replaces all occurences of name 'frm' with 'to' in expr_string # ('frm' may not occur as a function name on the rhs) ... # 'to' can be an arbitrary string so this function can also be used for # argument substitution. # # Returns the resulting string. # from nineml.abstraction_layer.component.util import MathUtil t = "b*c + d/(e*sin(f+g/e)) + b1 + e_ / exp(12*g)" t = MathUtil.str_expr_replacement("b", "B", t) self.assertEqual(t, "B*c + d/(e*sin(f+g/e)) + b1 + e_ / exp(12*g)") # 'e' is a builtin, so this function doesn't care. t = MathUtil.str_expr_replacement(frm="e", to="E", expr_string=t) self.assertEqual(t, "B*c + d/(E*sin(f+g/E)) + b1 + e_ / exp(12*g)")
def rhs_as_python_func(self, namespace={}): """ Returns a python callable which evaluates the expression in namespace and returns the result """ rhs = self.rhs rhs = rhs.replace('!', ' not ') rhs = rhs.replace('&', ' and ') rhs = rhs.replace('|', ' or ') name_map = { 'true': 'True', 'false': 'False' } for frm, to in name_map.iteritems(): rhs = MathUtil.str_expr_replacement(frm, to, rhs) lmda_str = "lambda %s: %s" % (','.join(self.rhs_names), rhs) return eval(lmda_str, str_to_npfunc_map, namespace)