def visit_Compare(self, node: ast.Compare) -> Any: if len(node.comparators) != 1: return self.generic_visit(node) left = astutils.evalnode(self.visit(node.left), self.globals) right = astutils.evalnode(self.visit(node.comparators[0]), self.globals) if (isinstance(left, sympy.Basic) or isinstance(right, sympy.Basic)): if isinstance(node.ops[0], ast.Eq): return sympy.Eq(left, right) elif isinstance(node.ops[0], ast.NotEq): return sympy.Ne(left, right) return self.generic_visit(node)
def print_Power(self, rule): with self.new_step(): self.append("The integral of {} is {} when {}:".format( self.format_math(rule.symbol**sympy.Symbol('n')), self.format_math((rule.symbol**(1 + sympy.Symbol('n'))) / (1 + sympy.Symbol('n'))), self.format_math(sympy.Ne(sympy.Symbol('n'), -1)), )) self.append( self.format_math_display( sympy.Eq(sympy.Integral(rule.context, rule.symbol), _manualintegrate(rule))))
class convergent(core.Factory): integer_constants = True positive_constants = True # Simple negative powers template_0 = sp.Integral(1 / ((x + A) * (x + B)), (x, C, sp.oo)) conds_0 = [sp.Ne(A, B)] # Exponential template_1 = sp.Integral(x * sp.exp(-A * (x - B)), (x, B, sp.oo)) # Power and logarithm template_2 = sp.Integral(1 / (x * (sp.ln(x)) ** P), (x, D, sp.oo)) conds_2 = [core.Domain(A, [1, 2])]
def add_neumann_boundary(eqs, fields, flag_field, boundary_flag="neumann_flag", inverse_flag=False): """ Replaces all neighbor accesses by flag field guarded accesses. If flag in neighboring cell is set, the center value is used instead Args: eqs: list of equations containing field accesses to direct neighbors fields: fields for which the Neumann boundary should be applied flag_field: integer field marking boundary cells boundary_flag: if flag field has value 'boundary_flag' (no bit operations yet) the cell is assumed to be boundary inverse_flag: if true, boundary cells are where flag field has not the value of boundary_flag Returns: list of equations with guarded field accesses """ if not hasattr(fields, "__len__"): fields = [fields] fields = set(fields) if type(boundary_flag) is str: boundary_flag = TypedSymbol(boundary_flag, dtype=create_type(DEFAULT_FLAG_TYPE)) substitutions = {} for eq in eqs: for fa in eq.atoms(Field.Access): if fa.field not in fields: continue if not all(offset in (-1, 0, 1) for offset in fa.offsets): raise ValueError("Works only for single neighborhood stencils") if all(offset == 0 for offset in fa.offsets): continue if inverse_flag: condition = sp.Eq( bitwise_and(flag_field[tuple(fa.offsets)], boundary_flag), 0) else: condition = sp.Ne( bitwise_and(flag_field[tuple(fa.offsets)], boundary_flag), 0) center = fa.field(*fa.index) substitutions[fa] = sp.Piecewise((center, condition), (fa, True)) return [eq.subs(substitutions) for eq in eqs]
def test_make_integral_01(): integral, params = _make_integral_01() intgr = integral.doit() u0, k, l, t = params # eq: k == l, neq: k != l ref_eq = k * u0 * t ref_neq = -k * u0 / (k - l) * (exp(t * (l - k)) - 1) refined_eq = integral.subs({l: k}).doit() assert (refined_eq - ref_eq).simplify() == 0 eq_assumption = sympy.Q.is_true(sympy.Ne(l, k)) refined_neq = sympy.refine(intgr, eq_assumption).simplify() assert (refined_neq - ref_neq).simplify() == 0
def convert_relation(rel): if rel.expr(): return convert_expr(rel.expr()) lh = convert_relation(rel.relation(0)) rh = convert_relation(rel.relation(1)) if rel.LT(): return sympy.StrictLessThan(lh, rh) elif rel.LTE(): return sympy.LessThan(lh, rh) elif rel.GT(): return sympy.StrictGreaterThan(lh, rh) elif rel.GTE(): return sympy.GreaterThan(lh, rh) elif rel.EQUAL(): return sympy.Eq(lh, rh) elif rel.NEQ(): return sympy.Ne(lh, rh)
def power_rule(integral): integrand, symbol = integral base, exp = integrand.as_base_exp() if symbol not in exp.free_symbols and isinstance(base, sympy.Symbol): if sympy.simplify(exp + 1) == 0: return ReciprocalRule(base, integrand, symbol) return PowerRule(base, exp, integrand, symbol) elif symbol not in base.free_symbols and isinstance(exp, sympy.Symbol): rule = ExpRule(base, exp, integrand, symbol) if fuzzy_not(sympy.log(base).is_zero): return rule elif sympy.log(base).is_zero: return ConstantRule(1, 1, symbol) return PiecewiseRule([(rule, sympy.Ne(sympy.log(base), 0)), (ConstantRule(1, 1, symbol), True)], integrand, symbol)
def convert_relation(rel): if rel.expr(): return convert_expr(rel.expr()) lh = convert_relation(rel.relation(0)) rh = convert_relation(rel.relation(1)) if rel.LT(): return sympy.StrictLessThan(lh, rh, evaluate=False) elif rel.LTE(): return sympy.LessThan(lh, rh, evaluate=False) elif rel.GT(): return sympy.StrictGreaterThan(lh, rh, evaluate=False) elif rel.GTE(): return sympy.GreaterThan(lh, rh, evaluate=False) elif rel.EQUAL(): return sympy.Eq(lh, rh, evaluate=False) elif rel.ASSIGNMENT(): # !Use Global variances variances[lh] = rh var[str(lh)] = rh return rh elif rel.UNEQUAL(): return sympy.Ne(lh, rh, evaluate=False)
('$PRED cl = int(-2.2)', S('CL'), -2), ('$PRED CL = INT(0.2)', S('CL'), 0), ('$PRED CL = SQRT(X)', S('CL'), sympy.sqrt(S('X'))), ('$PRED CL = MOD(1, 2)', S('CL'), sympy.Mod(1, 2)), ('$PRED CL = GAMLN(2 + X) ;COMMENT', S('CL'), sympy.loggamma(S('X') + 2)), ('$PRED C02 = PHI(2 + X)', S('C02'), (1 + sympy.erf(2 + S('X')) / sympy.sqrt(2)) / 2), ('$PRED IF (X.EQ.2) CL=23', S('CL'), sympy.Piecewise((23, sympy.Eq(S('X'), 2)))), ('$PRED if (x.EQ.2) Cl=23', S('CL'), sympy.Piecewise((23, sympy.Eq(S('X'), 2)))), ( '$PRED IF (X.NE.1.5) CL=THETA(1)', S('CL'), sympy.Piecewise((S('THETA(1)'), sympy.Ne(S('X'), 1.5))), ), ('$PRED IF (X.EQ.2+1) CL=23', S('CL'), sympy.Piecewise((23, sympy.Eq(S('X'), 3)))), ( '$PRED IF (X < ETA(1)) CL=23', S('CL'), sympy.Piecewise((23, sympy.Lt(S('X'), S('ETA(1)')))), ), ( '$PK IF(AMT.GT.0) BTIME=TIME', S('BTIME'), sympy.Piecewise((S('TIME'), sympy.Gt(S('AMT'), 0))), ), ( '$PRED IF (X.EQ.2.AND.Y.EQ.3) CL=23',
def _make_comparison_question(context, left, right): """Makes a question for comparing two values.""" if random.choice([False, True]) and sympy.Ne(left.value, right.value): # Do question of form: "Which is bigger: a or b?". if random.choice([False, True]): answer = (left.handle if sympy.Gt(left.value, right.value) else right.handle) template = random.choice([ 'Что больше: {left} или {right}?', 'Какое из чисел больше: {left} или {right}?', ]) else: answer = (left.handle if sympy.Lt(left.value, right.value) else right.handle) template = random.choice([ 'Что меньше: {left} или {right}?', 'Какое число меньше: {left} или {right}?' ]) return example.Problem(question=example.question(context, template, left=left, right=right), answer=answer) comparisons = { '<': sympy.Lt, '<=': sympy.Le, '>': sympy.Gt, '>=': sympy.Ge, '=': sympy.Eq, '!=': sympy.Ne, } templates = { '<': [ 'Правда ли, что {left} ' + ops.LT_SYMBOL + ' {right}?', '{left} меньше, чем {right}?', 'Число {left} меньше числа {right}?', ], '<=': [ 'Правда ли, что {left} ' + ops.LE_SYMBOL + ' {right}?', 'Правда ли, что {left} меньше или равно {right}?', 'Число {left} не больше {right}?', 'Число {left} не превосходит {right}?', ], '>': [ 'Правда ли, что {left} ' + ops.GT_SYMBOL + ' {right}?', '{left} больше, чем {right}?', 'Число {left} больше числа {right}?', ], '>=': [ 'Правда ли, что {left} ' + ops.GE_SYMBOL + ' {right}?', 'Правда ли, что {left} больше или равно {right}?', 'Число {left} не меньше {right}?', ], '=': [ 'Правда ли, что {left} ' + ops.EQ_SYMBOL + ' {right}?', 'Равны ли {left} и {right}?', 'Число {left} равно числу {right}?', 'Одинаковы ли {left} и {right}?', ], '!=': [ 'Правда ли, что {left} ' + ops.NE_SYMBOL + ' {right}?', 'Число {left} не равно {right}?', 'Числа {left} и {right} не равны?', 'Значения числа {left} и числа {right} отличаются?', '{left} и {right} не равны друг другу?', ], } comparison = random.choice(list(comparisons.keys())) template = random.choice(templates[comparison]) question = example.question(context, template, left=left, right=right) answer = comparisons[comparison](left.value, right.value) return example.Problem(question=question, answer=answer)
def gen_neq(self, ident, val): return sym.Ne(val.exp_a, val.exp_b)
def test_booleans(self, printer, x): assert printer.doprint(sp.Eq(x, x)) == printer.doprint(True) == 'true' assert printer.doprint(sp.Ne(x, x)) == printer.doprint(False) == 'false'
def _ex_not_equal(self, e): return sp.Ne(self.ex(e[0]), self.ex(e[1]))
sympy.sin(S('X')) + sympy.cos(S('X'))), ('$PRED S22 = ABS(1 + 2 + SIN(X))', S('S22'), sympy.Abs(3 + sympy.sin(S('X')))), ('$PRED CL = TAN(X) * EXP(Y)', S('CL'), sympy.tan(S('X')) * sympy.exp(S('Y'))), ('$PRED K_ = ATAN(1) - ASIN(X)/ACOS(X)', S('K_'), sympy.atan(1) - sympy.asin(S('X')) / sympy.acos(S('X'))), ('$PRED CL = INT(-2.2)', S('CL'), -2), ('$PRED CL = INT(0.2)', S('CL'), 0), ('$PRED CL = MOD(1, 2)', S('CL'), sympy.Mod(1, 2)), ('$PRED CL = GAMLN(2 + X) ;COMMENT', S('CL'), sympy.loggamma(S('X') + 2)), ('$PRED IF (X.EQ.2) CL=23', S('CL'), sympy.Piecewise((23, sympy.Eq(S('X'), 2)))), ('$PRED IF (X.NE.1.5) CL=THETA(1)', S('CL'), sympy.Piecewise((S('THETA(1)'), sympy.Ne(S('X'), 1.5)))), ('$PRED IF (X.EQ.2+1) CL=23', S('CL'), sympy.Piecewise((23, sympy.Eq(S('X'), 3)))), ('$PRED IF (X < ETA(1)) CL=23', S('CL'), sympy.Piecewise((23, sympy.Lt(S('X'), S('ETA(1)'))))), ('$PK IF(AMT.GT.0) BTIME=TIME', S('BTIME'), sympy.Piecewise((S('TIME'), sympy.Gt(S('AMT'), 0)))), ('$PRED IF (X.EQ.2.AND.Y.EQ.3) CL=23', S('CL'), sympy.Piecewise( (23, sympy.And(sympy.Eq(S('X'), 2), sympy.Eq(S('Y'), 3))))), ('$PRED IF (X.EQ.2.OR.Y.EQ.3) CL=23', S('CL'), sympy.Piecewise( (23, sympy.Or(sympy.Eq(S('X'), 2), sympy.Eq(S('Y'), 3))))), ('$PRED IF (.NOT.X.EQ.2) CL=25', S('CL'), sympy.Piecewise((25, sympy.Not(sympy.Eq(S('X'), 2))))), ('$PRED IF (Q.EQ.(R+C)/D) L=0', S('L'),
def eval_power(base, exp, integrand, symbol): return sympy.Piecewise( ((base**(exp + 1)) / (exp + 1), sympy.Ne(exp, -1)), (sympy.log(base), True), )
def _make_comparison_question(context, left, right): """Makes a question for comparing two values.""" if random.choice([False, True]) and sympy.Ne(left.value, right.value): # Do question of form: "Which is bigger: a or b?". if random.choice([False, True]): answer = (left.handle if sympy.Gt(left.value, right.value) else right.handle) template = random.choice([ 'Mana yang lebih besar: {left} atau {right}?', ]) else: answer = (left.handle if sympy.Lt(left.value, right.value) else right.handle) template = random.choice([ 'Mana yang lebih kecil: {left} atau {right}?', ]) return example.Problem(question=example.question(context, template, left=left, right=right), answer=answer) comparisons = { '<': sympy.Lt, '<=': sympy.Le, '>': sympy.Gt, '>=': sympy.Ge, '=': sympy.Eq, '!=': sympy.Ne, } templates = { '<': [ 'Apakah {left} ' + ops.LT_SYMBOL + ' {right}?', 'Apakah {left} kurang dari {right}?', 'Apakah {left} lebih kecil dari {right}?', ], '<=': [ 'Apakah {left} ' + ops.LE_SYMBOL + ' {right}?', 'Apakah {left} kurang dari atau sama dengan {right}?', 'Apakah {left} lebih banyak {right}?', 'Apakah {left} paling tidak sama dengan {right}?', ], '>': [ 'Apakah {left} ' + ops.GT_SYMBOL + ' {right}?', 'Apakah {left} lebih dari {right}?', 'Apakah {left} lebih besar dari {right}?', ], '>=': [ 'Apakah {left} ' + ops.GE_SYMBOL + ' {right}?', 'Apakah {left} lebih dari atau sama dengan {right}?', 'Apakah {left} setidaknya {right}?', 'Apakah {left} setidaknya sama besar dengan {right}?', ], '=': [ 'Apakah {left} ' + ops.EQ_SYMBOL + ' {right}?', 'Apakah {left} dan {right} sama?', 'Apakah {left} sama dengan {right}?', 'Apakah {left} dan {right} memiliki nilai yang sama?', ], '!=': [ 'Apakah {left} ' + ops.NE_SYMBOL + ' {right}?', 'Apakah {left} tidak sama dengan {right}?', 'Apakah {left} dan {right} berbeda?', 'Apakah {left} dan {right} tidak sama?', 'Apakah {left} dan {right} memiliki nilai yang berbeda?', ], } comparison = random.choice(list(comparisons.keys())) template = random.choice(templates[comparison]) question = example.question(context, template, left=left, right=right) answer = comparisons[comparison](left.value, right.value) return example.Problem(question=question, answer=answer)
def _make_comparison_question(context, left, right): """Makes a question for comparing two values.""" if random.choice([False, True]) and sympy.Ne(left.value, right.value): # Do question of form: "Which is bigger: a or b?". if random.choice([False, True]): answer = (left.handle if sympy.Gt(left.value, right.value) else right.handle) template = random.choice([ 'Which is bigger: {left} or {right}?', 'Which is greater: {left} or {right}?', ]) else: answer = (left.handle if sympy.Lt(left.value, right.value) else right.handle) template = random.choice([ 'Which is smaller: {left} or {right}?', ]) return example.Problem(question=example.question(context, template, left=left, right=right), answer=answer) comparisons = { '<': sympy.Lt, '<=': sympy.Le, '>': sympy.Gt, '>=': sympy.Ge, '=': sympy.Eq, '!=': sympy.Ne, } templates = { '<': [ 'Is {left} ' + ops.LT_SYMBOL + ' {right}?', 'Is {left} less than {right}?', 'Is {left} smaller than {right}?', ], '<=': [ 'Is {left} ' + ops.LE_SYMBOL + ' {right}?', 'Is {left} less than or equal to {right}?', 'Is {left} at most {right}?', 'Is {left} at most as big as {right}?', ], '>': [ 'Is {left} ' + ops.GT_SYMBOL + ' {right}?', 'Is {left} greater than {right}?', 'Is {left} bigger than {right}?', ], '>=': [ 'Is {left} ' + ops.GE_SYMBOL + ' {right}?', 'Is {left} greater than or equal to {right}?', 'Is {left} at least {right}?', 'Is {left} at least as big as {right}?', ], '=': [ 'Does {left} ' + ops.EQ_SYMBOL + ' {right}?', 'Are {left} and {right} equal?', 'Is {left} equal to {right}?', 'Do {left} and {right} have the same value?', ], '!=': [ 'Is {left} ' + ops.NE_SYMBOL + ' {right}?', 'Is {left} not equal to {right}?', 'Are {left} and {right} unequal?', 'Are {left} and {right} nonequal?', 'Are {left} and {right} non-equal?', 'Do {left} and {right} have different values?', ], } comparison = random.choice(list(comparisons.keys())) template = random.choice(templates[comparison]) question = example.question(context, template, left=left, right=right) answer = comparisons[comparison](left.value, right.value) return example.Problem(question=question, answer=answer)
def test_reader_writer(self): # Test using the proper reader/writer try: import sympy as sp except ImportError: print('Sympy not found, skipping test.') return # Create writer and reader w = mypy.SymPyExpressionWriter() r = mypy.SymPyExpressionReader(self._model) # Name a = self._a ca = sp.Symbol('c.a') self.assertEqual(w.ex(a), ca) self.assertEqual(r.ex(ca), a) # Number with unit b = myokit.Number('12', 'pF') cb = sp.Float(12) self.assertEqual(w.ex(b), cb) # Note: Units are lost in sympy im/ex-port! #self.assertEqual(r.ex(cb), b) # Number without unit b = myokit.Number('12') cb = sp.Float(12) self.assertEqual(w.ex(b), cb) self.assertEqual(r.ex(cb), b) # Prefix plus x = myokit.PrefixPlus(b) self.assertEqual(w.ex(x), cb) # Note: Sympy doesn't seem to have a prefix plus self.assertEqual(r.ex(cb), b) # Prefix minus # Note: SymPy treats -x as Mul(NegativeOne, x) # But for numbers just returns a number with a negative value x = myokit.PrefixMinus(b) self.assertEqual(w.ex(x), -cb) self.assertEqual(float(r.ex(-cb)), float(x)) # Plus x = myokit.Plus(a, b) self.assertEqual(w.ex(x), ca + cb) # Note: SymPy likes to re-order the operands... self.assertEqual(float(r.ex(ca + cb)), float(x)) # Minus x = myokit.Minus(a, b) self.assertEqual(w.ex(x), ca - cb) self.assertEqual(float(r.ex(ca - cb)), float(x)) # Multiply x = myokit.Multiply(a, b) self.assertEqual(w.ex(x), ca * cb) self.assertEqual(float(r.ex(ca * cb)), float(x)) # Divide x = myokit.Divide(a, b) self.assertEqual(w.ex(x), ca / cb) self.assertEqual(float(r.ex(ca / cb)), float(x)) # Quotient x = myokit.Quotient(a, b) self.assertEqual(w.ex(x), ca // cb) self.assertEqual(float(r.ex(ca // cb)), float(x)) # Remainder x = myokit.Remainder(a, b) self.assertEqual(w.ex(x), ca % cb) self.assertEqual(float(r.ex(ca % cb)), float(x)) # Power x = myokit.Power(a, b) self.assertEqual(w.ex(x), ca**cb) self.assertEqual(float(r.ex(ca**cb)), float(x)) # Sqrt x = myokit.Sqrt(a) cx = sp.sqrt(ca) self.assertEqual(w.ex(x), cx) # Note: SymPy converts sqrt to power self.assertEqual(float(r.ex(cx)), float(x)) # Exp x = myokit.Exp(a) cx = sp.exp(ca) self.assertEqual(w.ex(x), cx) self.assertEqual(r.ex(cx), x) # Log(a) x = myokit.Log(a) cx = sp.log(ca) self.assertEqual(w.ex(x), cx) self.assertEqual(r.ex(cx), x) # Log(a, b) x = myokit.Log(a, b) cx = sp.log(ca, cb) self.assertEqual(w.ex(x), cx) self.assertEqual(float(r.ex(cx)), float(x)) # Log10 x = myokit.Log10(b) cx = sp.log(cb, 10) self.assertEqual(w.ex(x), cx) self.assertAlmostEqual(float(r.ex(cx)), float(x)) # Sin x = myokit.Sin(a) cx = sp.sin(ca) self.assertEqual(w.ex(x), cx) self.assertEqual(r.ex(cx), x) # Cos x = myokit.Cos(a) cx = sp.cos(ca) self.assertEqual(w.ex(x), cx) self.assertEqual(r.ex(cx), x) # Tan x = myokit.Tan(a) cx = sp.tan(ca) self.assertEqual(w.ex(x), cx) self.assertEqual(r.ex(cx), x) # ASin x = myokit.ASin(a) cx = sp.asin(ca) self.assertEqual(w.ex(x), cx) self.assertEqual(r.ex(cx), x) # ACos x = myokit.ACos(a) cx = sp.acos(ca) self.assertEqual(w.ex(x), cx) self.assertEqual(r.ex(cx), x) # ATan x = myokit.ATan(a) cx = sp.atan(ca) self.assertEqual(w.ex(x), cx) self.assertEqual(r.ex(cx), x) # Floor x = myokit.Floor(a) cx = sp.floor(ca) self.assertEqual(w.ex(x), cx) self.assertEqual(r.ex(cx), x) # Ceil x = myokit.Ceil(a) cx = sp.ceiling(ca) self.assertEqual(w.ex(x), cx) self.assertEqual(r.ex(cx), x) # Abs x = myokit.Abs(a) cx = sp.Abs(ca) self.assertEqual(w.ex(x), cx) self.assertEqual(r.ex(cx), x) # Equal x = myokit.Equal(a, b) cx = sp.Eq(ca, cb) self.assertEqual(w.ex(x), cx) self.assertEqual(r.ex(cx), x) # NotEqual x = myokit.NotEqual(a, b) cx = sp.Ne(ca, cb) self.assertEqual(w.ex(x), cx) self.assertEqual(r.ex(cx), x) # More x = myokit.More(a, b) cx = sp.Gt(ca, cb) self.assertEqual(w.ex(x), cx) self.assertEqual(r.ex(cx), x) # Less x = myokit.Less(a, b) cx = sp.Lt(ca, cb) self.assertEqual(w.ex(x), cx) self.assertEqual(r.ex(cx), x) # MoreEqual x = myokit.MoreEqual(a, b) cx = sp.Ge(ca, cb) self.assertEqual(w.ex(x), cx) self.assertEqual(r.ex(cx), x) # LessEqual x = myokit.LessEqual(a, b) cx = sp.Le(ca, cb) self.assertEqual(w.ex(x), cx) self.assertEqual(r.ex(cx), x) # Not x = myokit.Not(a) cx = sp.Not(ca) self.assertEqual(w.ex(x), cx) self.assertEqual(r.ex(cx), x) # And cond1 = myokit.More(a, b) cond2 = myokit.Less(a, b) c1 = sp.Gt(ca, cb) c2 = sp.Lt(ca, cb) x = myokit.And(cond1, cond2) cx = sp.And(c1, c2) self.assertEqual(w.ex(x), cx) self.assertEqual(r.ex(cx), x) # Or x = myokit.Or(cond1, cond2) cx = sp.Or(c1, c2) self.assertEqual(w.ex(x), cx) self.assertEqual(r.ex(cx), x) # If # Note: sympy only does piecewise, not if x = myokit.If(cond1, a, b) cx = sp.Piecewise((ca, c1), (cb, True)) self.assertEqual(w.ex(x), cx) self.assertEqual(r.ex(cx), x.piecewise()) # Piecewise c = myokit.Number(1) cc = sp.Float(1) x = myokit.Piecewise(cond1, a, cond2, b, c) cx = sp.Piecewise((ca, c1), (cb, c2), (cc, True)) self.assertEqual(w.ex(x), cx) self.assertEqual(r.ex(cx), x) # Myokit piecewise's (like CellML's) always have a final True # condition (i.e. an 'else'). SymPy doesn't require this, so test if # we can import this --> It will add an "else 0" x = myokit.Piecewise(cond1, a, myokit.Number(0)) cx = sp.Piecewise((ca, c1)) self.assertEqual(r.ex(cx), x) # SymPy function without Myokit equivalent --> Should raise exception cu = sp.principal_branch(cx, cc) self.assertRaisesRegex(ValueError, 'Unsupported type', r.ex, cu) # Derivative m = self._model.clone() avar = m.get('c.a') r = mypy.SymPyExpressionReader(self._model) avar.promote(4) x = myokit.Derivative(self._a) cx = sp.symbols('dot(c.a)') self.assertEqual(w.ex(x), cx) self.assertEqual(r.ex(cx), x) # Equation e = myokit.Equation(a, b) ce = sp.Eq(ca, cb) self.assertEqual(w.eq(e), ce) # There's no backwards equivalent for this! # The ereader can handle it, but it becomes and Equals expression. # Test sympy division del (m, avar, x, cx, e, ce) a = self._model.get('c.a') b = self._model.get('c').add_variable('bbb') b.set_rhs('1 / a') e = b.rhs() ce = w.ex(b.rhs()) e = r.ex(ce) self.assertEqual( e, myokit.Multiply(myokit.Number(1), myokit.Power(myokit.Name(a), myokit.Number(-1)))) # Test sympy negative numbers a = self._model.get('c.a') e1 = myokit.PrefixMinus(myokit.Name(a)) ce = w.ex(e1) e2 = r.ex(ce) self.assertEqual(e1, e2)
o = sympy.Symbol('o', real=True) D_ = sympy.Symbol('D_', real=True, positive=True) dD_dtheta, d2D_dtheta2 = sympy.symbols('dD_dtheta, d2D_dtheta2', real=True) theta, dtheta_do, d2theta_do2 = sympy.symbols('theta, dtheta_do, d2theta_do2', real=True) k = sympy.Symbol('k', integer=True, nonnegative=True) k_o = sympy.Symbol('k_o', real=True) D = sympy.Function('D', real=True, positive=True) subs = [(D_, D(theta)), (dD_dtheta, D(theta).diff(theta)), (d2D_dtheta2, D(theta).diff(theta, 2)), (k_o, sympy.Piecewise((k / o, sympy.Ne(k, 0)), (0, sympy.Eq(k, 0))))] backsubs = [sub[::-1] for sub in subs[::-1]] ################################ y = theta, dtheta_do d2theta_do2 = -((o / 2 + dD_dtheta * dtheta_do) / D_ + k_o) * dtheta_do fun = (dtheta_do, d2theta_do2) ################################ J = sympy.Matrix(fun).subs(subs).jacobian(y).subs(backsubs) xs, [J] = sympy.cse(J, optimizations='basic')
S('CL'), sympy.Piecewise((0, S('X') < 0), (sympy.sqrt(S('X')), True)), ), ('$PRED CL = MOD(1, 2)', S('CL'), sympy.Mod(1, 2)), ('$PRED CL = GAMLN(2 + X) ;COMMENT', S('CL'), sympy.loggamma(S('X') + 2)), ('$PRED C02 = PHI(2 + X)', S('C02'), (1 + sympy.erf(2 + S('X')) / sympy.sqrt(2)) / 2), ('$PRED IF (X.EQ.2) CL=23', S('CL'), sympy.Piecewise((23, sympy.Eq(S('X'), 2)), (0, True))), ('$PRED if (x.EQ.2) Cl=23', S('CL'), sympy.Piecewise((23, sympy.Eq(S('X'), 2)), (0, True))), ( '$PRED IF (X.NE.1.5) CL=THETA(1)', S('CL'), sympy.Piecewise((S('THETA(1)'), sympy.Ne(S('X'), 1.5)), (0, True)), ), ( '$PRED IF (X.EQ.2+1) CL=23', S('CL'), sympy.Piecewise((23, sympy.Eq(S('X'), 3)), (0, True)), ), ( '$PRED IF (X < ETA(1)) CL=23', S('CL'), sympy.Piecewise((23, sympy.Lt(S('X'), S('ETA(1)'))), (0, True)), ), ( '$PK IF(AMT.GT.0) BTIME=TIME', S('BTIME'), sympy.Piecewise((S('TIME'), sympy.Gt(S('AMT'), 0)), (0, True)),