Python sympy.Expr() Examples
The following are 30
code examples of sympy.Expr().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
sympy
, or try the search function
.
Example #1
Source File: expressions.py From qupulse with MIT License | 6 votes |
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 = str(ex) self._sympified_expression = ex else: self._original_expression = ex self._sympified_expression = sympify(ex) self._variables = get_variables(self._sympified_expression)
Example #2
Source File: symbolic.py From simupy with BSD 2-Clause "Simplified" License | 6 votes |
def output_equation(self, output_equation): if isinstance(output_equation, sp.Expr): output_equation = Array([output_equation]) if output_equation is None and self.dim_state == 0: output_equation = empty_array() else: if output_equation is None: output_equation = self.state assert output_equation.atoms(sp.Symbol) <= ( set(self.constants_values.keys()) | set([dynamicsymbols._t]) ) if self.dim_state: assert find_dynamicsymbols(output_equation) <= set(self.state) else: assert find_dynamicsymbols(output_equation) <= set(self.input) self.dim_output = len(output_equation) self._output_equation = output_equation self.update_output_equation_function()
Example #3
Source File: test_distributions.py From symfit with GNU General Public License v2.0 | 6 votes |
def test_exp(): """ Make sure that symfit.distributions.Exp produces the expected sympy expression. """ l = Parameter(positive=True) x = Variable() new = l * sympy.exp(- l * x) assert isinstance(new, sympy.Expr) e = Exp(x, l) assert issubclass(e.__class__, sympy.Expr) assert new == e # A pdf should always integrate to 1 on its domain assert sympy.integrate(e, (x, 0, sympy.oo)) == 1
Example #4
Source File: test_distributions.py From symfit with GNU General Public License v2.0 | 6 votes |
def test_gaussian(): """ Make sure that symfit.distributions.Gaussians produces the expected sympy expression. """ x0 = Parameter() sig = Parameter(positive=True) x = Variable() new = sympy.exp(-(x - x0)**2/(2*sig**2))/sympy.sqrt((2*sympy.pi*sig**2)) assert isinstance(new, sympy.Expr) g = Gaussian(x, x0, sig) assert issubclass(g.__class__, sympy.Expr) assert new == g # A pdf should always integrate to 1 on its domain assert sympy.integrate(g, (x, -sympy.oo, sympy.oo)) == 1
Example #5
Source File: distributions.py From symfit with GNU General Public License v2.0 | 6 votes |
def Exp(x, l): """ .. math:: f(x) = l e^{- l x} Exponential Distribution pdf. :param x: free variable. :param l: rate parameter. :return: sympy.Expr for an Exponential Distribution pdf. """ return l * sympy.exp(- l * x) # def Beta(): # sympy.stats.Beta()
Example #6
Source File: models.py From symfit with GNU General Public License v2.0 | 6 votes |
def __init__(self, model): """ Initiate a Model from a dict:: a = Model({y: x**2}) Preferred way of initiating ``Model``, since now you know what the dependent variable is called. :param model: dict of ``Expr``, where dependent variables are the keys. """ if not isinstance(model, Mapping): try: iter(model) except TypeError: # Model is still a scalar model model = [model] # TODO: this will break upon deprecating the auto-generation of # names for Variables. At this time, a DummyVariable object # should be introduced to fulfill the same role. model = {Variable(): expr for expr in model} self._init_from_dict(model)
Example #7
Source File: extended_sympy.py From devito with MIT License | 6 votes |
def __new__(cls, lhs, rhs, params=None): try: rhs = Integer(rhs) if rhs == 0: raise ValueError("Cannot divide by 0") elif rhs == 1: return lhs except TypeError: # We must be sure the symbolic RHS is of type int if not hasattr(rhs, 'dtype'): raise ValueError("Symbolic RHS `%s` lacks dtype" % rhs) if not issubclass(rhs.dtype, np.integer): raise ValueError("Symbolic RHS `%s` must be of type `int`, found " "`%s` instead" % (rhs, rhs.dtype)) obj = sympy.Expr.__new__(cls, lhs, rhs) obj.lhs = lhs obj.rhs = rhs return obj
Example #8
Source File: extended_sympy.py From devito with MIT License | 6 votes |
def __new__(cls, function, pointer, params=None): args = [] if isinstance(pointer, str): pointer = Symbol(pointer) args.append(pointer) if isinstance(function, FunctionFromPointer): args.append(function) elif not isinstance(function, str): raise ValueError("`function` must be FunctionFromPointer or str") _params = [] for p in as_tuple(params): if isinstance(p, str): _params.append(Symbol(p)) elif not isinstance(p, Expr): raise ValueError("`params` must be an iterable of Expr or str") else: _params.append(p) args.extend(_params) obj = sympy.Expr.__new__(cls, *args) obj.function = function obj.pointer = pointer obj.params = tuple(_params) return obj
Example #9
Source File: formulation.py From pyblp with MIT License | 6 votes |
def __init__(self, formula: str, expression: sp.Expr) -> None: """Parse the column name into a patsy term and replace any categorical variables in its SymPy expression with the correct indicator variable symbols. """ self.expression = expression self.names = {str(s) for s in expression.free_symbols} # replace categorical variable symbols with their indicator counterparts for factor in parse_terms(formula)[-1].factors: name = factor.name() base_symbol = CategoricalTreatment.parse_base_symbol(name) if base_symbol is not None: self.expression = self.expression.replace(base_symbol, CategoricalTreatment.parse_full_symbol(name)) # cache evaluated derivatives self.derivatives: Dict[str, sp.Expr] = {}
Example #10
Source File: type_tensor.py From coremltools with BSD 3-Clause "New" or "Revised" License | 6 votes |
def canonical_shape(shape): """ Return shape as tuple of int or Symbol. This utility function ensures the shape tuple using a single integer type (to its best effort). Args: shape: tuple(int|long|np.int*|Symbol|SymbolExpr...) """ def try_cast(x): try: # In python2.7, long and int are different types. # If we cast a long int whose value is out of the range of int, # the result is still long, avoiding overflow: # # `type(2<<64) == long # true` # `type(int(2<<64)) == long # true` x = int(x) except TypeError: # ignore symbolic value (sm.Symbol or sm.Expr) pass return x return tuple(try_cast(x) for x in shape)
Example #11
Source File: sympy.py From qupulse with MIT License | 6 votes |
def sympify(expr: Union[str, Number, sympy.Expr, numpy.str_], **kwargs) -> sympy.Expr: if isinstance(expr, numpy.str_): # putting numpy.str_ in sympy.sympify behaves unexpected in version 1.1.1 # It seems to ignore the locals argument expr = str(expr) try: return sympy.sympify(expr, **kwargs, locals=sympify_namespace) except TypeError as err: if True:#err.args[0] == "'Symbol' object is not subscriptable": indexed_base = get_subscripted_symbols(expr) return sympy.sympify(expr, **kwargs, locals={**{k: sympy.IndexedBase(k) for k in indexed_base}, **sympify_namespace}) else: raise
Example #12
Source File: uniform_bspline.py From bspline-regression with MIT License | 6 votes |
def basis_functions(d, x): """Symbolically evaluate the uniform B-spline basis functions. Parameters ---------- d : int The degree of the uniform B-spline. x : sp.Symbol Interpolation parameter. Returns ------- b : list of sp.Expr, len = d + 1 List of B-spline basis functions, where `b[i]` is the interpolating expression over the unit interval. """ if d < 0: raise ValueError('d < 0 (= {})'.format(d)) return [ib[1].subs({x : x + ib[0]}).expand() for ib in enumerate(B(0, d + 1, x))][::-1] # uniform_bspline_basis
Example #13
Source File: symbolic.py From lingvo with Apache License 2.0 | 6 votes |
def EvalExpr(value_type, x): """Evaluates x with symbol_to_value_map within the current context. Args: value_type: the target value type (see VALUE_TYPE). x: a sympy.Expr, an object, or a list/tuple of Exprs and objects. Returns: Evaluation result of 'x'. """ if isinstance(x, (list, tuple)): return type(x)(EvalExpr(value_type, y) for y in x) elif isinstance(x, sympy.Expr): symbol_to_value_map = SymbolToValueMap.Get(value_type) if not symbol_to_value_map: return x # In theory the below should be equivalent to: # y = x.subs(symbol_to_value_map). # In practice subs() doesn't work for when values are Tensors. k, v = list(zip(*(list(symbol_to_value_map.items())))) y = sympy.lambdify(k, x)(*v) return y else: return x
Example #14
Source File: sympy_interface.py From fungrim with MIT License | 6 votes |
def sympy_to_grim(expr, **kwargs): import sympy assert isinstance(expr, sympy.Expr) if expr.is_Integer: return Expr(int(expr)) if expr.is_Symbol: return Expr(symbol_name=expr.name) if expr is sympy.pi: return Pi if expr is sympy.E: return ConstE if expr is sympy.I: return ConstI if expr.is_Add: args = [sympy_to_grim(x, **kwargs) for x in expr.args] return Add(*args) if expr.is_Mul: args = [sympy_to_grim(x, **kwargs) for x in expr.args] return Mul(*args) if expr.is_Pow: args = [sympy_to_grim(x, **kwargs) for x in expr.args] b, e = args return Pow(b, e) raise NotImplementedError("converting %s to Grim", type(expr))
Example #15
Source File: sympy_tests.py From qupulse with MIT License | 5 votes |
def test_indexed_substitution_cases(self): if type(self) is SubstitutionTests: raise unittest.SkipTest('sympy.Expr.subs does not handle simultaneous substitutions of indexed entities.') for expr, subs, expected in indexed_substitution_cases: result = self.substitute(expr, subs) self.assertEqual(result, expected)
Example #16
Source File: expressions.py From qupulse with MIT License | 5 votes |
def __le__(self, other: Union['ExpressionScalar', Number, sympy.Expr]) -> Union[bool, None]: result = self._sympified_expression <= self._sympify(other) return None if isinstance(result, sympy.Rel) else bool(result)
Example #17
Source File: sympy_tests.py From qupulse with MIT License | 5 votes |
def test_vector_valued_cases(self): if type(self) is SubstitutionTests: raise unittest.SkipTest('sympy.Expr.subs does not handle simultaneous substitutions of indexed entities.') for expr, subs, expected in vector_valued_cases: result = self.substitute(expr, subs) self.assertEqual(result, expected)
Example #18
Source File: sympy_tests.py From qupulse with MIT License | 5 votes |
def substitute(self, expression: sympy.Expr, substitutions: dict): return recursive_substitution(expression, substitutions).doit()
Example #19
Source File: sympy_tests.py From qupulse with MIT License | 5 votes |
def substitute(self, expression: sympy.Expr, substitutions: dict): return substitute_with_eval(expression, substitutions)
Example #20
Source File: sympy_tests.py From qupulse with MIT License | 5 votes |
def evaluate(self, expression: Union[sympy.Expr, np.ndarray], parameters): if isinstance(expression, np.ndarray): variables = set.union(*map(set, map(get_variables, expression.flat))) else: variables = get_variables(expression) return evaluate_lambdified(expression, variables=list(variables), parameters=parameters, lambdified=None)[0]
Example #21
Source File: sympy.py From qupulse with MIT License | 5 votes |
def evaluate_lambdified(expression: Union[sympy.Expr, numpy.ndarray], variables: Sequence[str], parameters: Dict[str, Union[numpy.ndarray, Number]], lambdified) -> Tuple[Any, Any]: lambdified = lambdified or sympy.lambdify(variables, expression, _lambdify_modules) return lambdified(**parameters), lambdified
Example #22
Source File: expressions.py From qupulse with MIT License | 5 votes |
def __ge__(self, other: Union['ExpressionScalar', Number, sympy.Expr]) -> Union[bool, None]: result = self._sympified_expression >= self._sympify(other) return None if isinstance(result, sympy.Rel) else bool(result)
Example #23
Source File: expressions.py From qupulse with MIT License | 5 votes |
def __gt__(self, other: Union['ExpressionScalar', Number, sympy.Expr]) -> Union[bool, None]: result = self._sympified_expression > self._sympify(other) return None if isinstance(result, sympy.Rel) else bool(result)
Example #24
Source File: expressions.py From qupulse with MIT License | 5 votes |
def __lt__(self, other: Union['ExpressionScalar', Number, sympy.Expr]) -> Union[bool, None]: result = self._sympified_expression < self._sympify(other) return None if isinstance(result, sympy.Rel) else bool(result)
Example #25
Source File: expressions.py From qupulse with MIT License | 5 votes |
def underlying_expression(self) -> sympy.Expr: return self._sympified_expression
Example #26
Source File: expressions.py From qupulse with MIT License | 5 votes |
def underlying_expression(self) -> Union[sympy.Expr, numpy.ndarray]: raise NotImplementedError()
Example #27
Source File: parameters.py From qupulse with MIT License | 5 votes |
def sympified_expression(self) -> sympy.Expr: return self._expression.underlying_expression
Example #28
Source File: parameters.py From qupulse with MIT License | 5 votes |
def __init__(self, relation: Union[str, sympy.Expr]): super().__init__() if isinstance(relation, str) and '==' in relation: # The '==' operator is interpreted by sympy as exactly, however we need a symbolical evaluation self._expression = sympy.Eq(*sympy.sympify(relation.split('=='))) else: self._expression = sympy.sympify(relation) if not isinstance(self._expression, sympy.boolalg.Boolean): raise ValueError('Constraint is not boolean') self._expression = Expression(self._expression)
Example #29
Source File: sympy.py From qupulse with MIT License | 5 votes |
def almost_equal(lhs: sympy.Expr, rhs: sympy.Expr, epsilon: float=1e-15) -> Optional[bool]: """Returns True (or False) if the two expressions are almost equal (or not). Returns None if this cannot be determined.""" relation = sympy.simplify(sympy.Abs(lhs - rhs) <= epsilon) if relation is sympy.true: return True elif relation is sympy.false: return False else: return None
Example #30
Source File: output_shape_for.py From netharn with Apache License 2.0 | 5 votes |
def _simplify(shape): import sympy if isinstance(shape, (tuple, list)): shape = shape.__class__([_simplify(v) for v in shape]) elif isinstance(shape, dict): shape = shape.__class__([(k, _simplify(v)) for k, v in shape.items()]) elif isinstance(shape, sympy.Expr): shape = sympy.simplify(shape) return shape