def __init__(self, ex: Union[str, Number, sympy.Expr]) -> None: """Create an Expression object. Receives the mathematical expression which shall be represented by the object as a string which will be parsed using py_expression_eval. For available operators, functions and constants see SymPy documentation Args: ex (string): The mathematical expression represented as a string """ super().__init__() if isinstance(ex, sympy.Expr): self._original_expression = None self._sympified_expression = ex self._variables = get_variables(self._sympified_expression) elif isinstance(ex, ExpressionScalar): self._original_expression = ex._original_expression self._sympified_expression = ex._sympified_expression self._variables = ex._variables elif isinstance(ex, (int, float)): self._original_expression = ex self._sympified_expression = sympify(ex) self._variables = () else: self._original_expression = ex self._sympified_expression = sympify(ex) self._variables = get_variables(self._sympified_expression) self._exact_rational_lambdified = None
def test_as_expression(self): sts = [DummyPulseTemplate(duration='t1', defined_channels={'A'}, integrals={'A': ExpressionScalar('2+k')}), DummyPulseTemplate(duration='t1', defined_channels={'B', 'C'}, integrals={'B': ExpressionScalar('t1-t0*3.1'), 'C': ExpressionScalar('l')})] pulse = AtomicMultiChannelPulseTemplate(*sts) self.assertEqual({'A': ExpressionScalar(sympify('(2+k) / t1') * pulse._AS_EXPRESSION_TIME), 'B': ExpressionScalar(sympify('(t1-t0*3.1)/t1') * pulse._AS_EXPRESSION_TIME), 'C': ExpressionScalar(sympify('l/t1') * pulse._AS_EXPRESSION_TIME)}, pulse._as_expression())
def evaluate_symbolic(self, substitutions: Mapping[Any, Any]) -> 'Expression': if len(substitutions) == 0: return self return Expression.make( recursive_substitution(sympify(self.underlying_expression), substitutions))
def _sympify(cls, other: Union['ExpressionScalar', Number, sympy.Expr]) -> sympy.Expr: return other._sympified_expression if isinstance(other, cls) else sympify(other)
def evaluate_symbolic(self, substitutions: Dict[Any, Any]) -> 'Expression': return Expression.make( recursive_substitution(sympify(self.underlying_expression), substitutions))