Python sympy.Mul() Examples
The following are 30
code examples of sympy.Mul().
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
.
![](https://www.programcreek.com/common/static/images/search.png)
Example #1
Source File: duration_test.py From Cirq with Apache License 2.0 | 6 votes |
def test_repr_preserves_type_information(): t = sympy.Symbol('t') assert repr(cirq.Duration(micros=1500)) == 'cirq.Duration(micros=1500)' assert repr(cirq.Duration(micros=1500.0)) == 'cirq.Duration(micros=1500.0)' assert repr(cirq.Duration(millis=1.5)) == 'cirq.Duration(micros=1500.0)' assert repr(cirq.Duration( micros=1500 * t)) == ("cirq.Duration(micros=sympy.Mul(sympy.Integer(1500), " "sympy.Symbol('t')))") assert repr(cirq.Duration(micros=1500.0 * t)) == ( "cirq.Duration(micros=sympy.Mul(sympy.Float('1500.0', precision=53), " "sympy.Symbol('t')))") assert repr(cirq.Duration(millis=1.5 * t)) == ( "cirq.Duration(micros=sympy.Mul(sympy.Float('1500.0', precision=53), " "sympy.Symbol('t')))")
Example #2
Source File: process_latex.py From latex2sympy with MIT License | 6 votes |
def convert_unary(unary): if hasattr(unary, 'unary'): nested_unary = unary.unary() else: nested_unary = unary.unary_nofunc() if hasattr(unary, 'postfix_nofunc'): first = unary.postfix() tail = unary.postfix_nofunc() postfix = [first] + tail else: postfix = unary.postfix() if unary.ADD(): return convert_unary(nested_unary) elif unary.SUB(): return sympy.Mul(-1, convert_unary(nested_unary), evaluate=False) elif postfix: return convert_postfix_list(postfix)
Example #3
Source File: process_latex.py From latex2sympy with MIT License | 6 votes |
def convert_mp(mp): if hasattr(mp, 'mp'): mp_left = mp.mp(0) mp_right = mp.mp(1) else: mp_left = mp.mp_nofunc(0) mp_right = mp.mp_nofunc(1) if mp.MUL() or mp.CMD_TIMES() or mp.CMD_CDOT(): lh = convert_mp(mp_left) rh = convert_mp(mp_right) return sympy.Mul(lh, rh, evaluate=False) elif mp.DIV() or mp.CMD_DIV() or mp.COLON(): lh = convert_mp(mp_left) rh = convert_mp(mp_right) return sympy.Mul(lh, sympy.Pow(rh, -1, evaluate=False), evaluate=False) else: if hasattr(mp, 'unary'): return convert_unary(mp.unary()) else: return convert_unary(mp.unary_nofunc())
Example #4
Source File: reformulation.py From pytfa with Apache License 2.0 | 6 votes |
def subs_bilinear(expr): """ Substitutes bilinear forms from an expression with dedicated variables :param expr: :return: """ bilinear_ix = [isinstance(x,sympy.Mul) for e,x in enumerate(expr.args)] new_expr = expr.copy() replacement_dict = dict() for bix in bilinear_ix: term = expr.args[bix] name = '__MUL__'.join(term.args) z = sympy.Symbol(name = name) new_expr = new_expr.subs(term,z) replacement_dict[term] = z return new_expr, replacement_dict
Example #5
Source File: test_differentiable.py From devito with MIT License | 6 votes |
def test_differentiable(): a = Function(name="a", grid=Grid((10, 10))) e = Function(name="e", grid=Grid((10, 10))) assert isinstance(1.2 * a.dx, Mul) assert isinstance(e + a, Add) assert isinstance(e * a, Mul) assert isinstance(a * a, Pow) assert isinstance(1 / (a * a), Pow) addition = a + 1.2 * a.dx assert isinstance(addition, Add) assert all(isinstance(a, Differentiable) for a in addition.args) addition2 = a + e * a.dx assert isinstance(addition2, Add) assert all(isinstance(a, Differentiable) for a in addition2.args)
Example #6
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 #7
Source File: density.py From sympsi with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _generate_outer_prod(self, arg1, arg2): c_part1, nc_part1 = arg1.args_cnc() c_part2, nc_part2 = arg2.args_cnc() if ( len(nc_part1) == 0 or len(nc_part2) == 0 ): raise ValueError('Atleast one-pair of' ' Non-commutative instance required' ' for outer product.') # Muls of Tensor Products should be expanded # before this function is called if (isinstance(nc_part1[0], TensorProduct) and len(nc_part1) == 1 and len(nc_part2) == 1): op = tensor_product_simp(nc_part1[0] * Dagger(nc_part2[0])) else: op = Mul(*nc_part1) * Dagger(Mul(*nc_part2)) return Mul(*c_part1)*Mul(*c_part2)*op
Example #8
Source File: test_differentiable.py From devito with MIT License | 6 votes |
def test_diffify(): a = Function(name="a", grid=Grid((10, 10))) e = Function(name="e", grid=Grid((10, 10))) assert isinstance(diffify(sympy.Mul(*[1.2, a.dx])), Mul) assert isinstance(diffify(sympy.Add(*[a, e])), Add) assert isinstance(diffify(sympy.Mul(*[e, a])), Mul) assert isinstance(diffify(sympy.Mul(*[a, a])), Pow) assert isinstance(diffify(sympy.Pow(*[a*a, -1])), Pow) addition = diffify(sympy.Add(*[a, sympy.Mul(*[1.2, a.dx])])) assert isinstance(addition, Add) assert all(isinstance(a, Differentiable) for a in addition.args) addition2 = diffify(sympy.Add(*[a, sympy.Mul(*[e, a.dx])])) assert isinstance(addition2, Add) assert all(isinstance(a, Differentiable) for a in addition2.args)
Example #9
Source File: operatorordering.py From sympsi with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _normal_order_terms(expr, recursive_limit=10, _recursive_depth=0): """ Helper function for normal_order: look through each term in an addition expression and call _normal_order_factor to perform the normal ordering on the factors. """ new_terms = [] for term in expr.args: if isinstance(term, Mul): new_term = _normal_order_factor(term, recursive_limit=recursive_limit, _recursive_depth=_recursive_depth) new_terms.append(new_term) else: new_terms.append(term) return Add(*new_terms)
Example #10
Source File: operatorordering.py From sympsi with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _normal_ordered_form_terms(expr, independent=False, recursive_limit=10, _recursive_depth=0): """ Helper function for normal_ordered_form: loop through each term in an addition expression and call _normal_ordered_form_factor to perform the factor to an normally ordered expression. """ new_terms = [] for term in expr.args: if isinstance(term, Mul): new_term = _normal_ordered_form_factor( term, recursive_limit=recursive_limit, _recursive_depth=_recursive_depth, independent=independent) new_terms.append(new_term) elif isinstance(term, Expectation): term = Expectation(normal_ordered_form(term.args[0]), term.is_normal_order) new_terms.append(term) else: new_terms.append(term) return Add(*new_terms)
Example #11
Source File: manipulation.py From devito with MIT License | 6 votes |
def pow_to_mul(expr): if expr.is_Atom or expr.is_Indexed: return expr elif expr.is_Pow: base, exp = expr.as_base_exp() if exp > 10 or exp < -10 or int(exp) != exp or exp == 0: # Large and non-integer powers remain untouched return expr elif exp == -1: # Reciprocals also remain untouched, but we traverse the base # looking for other Pows return expr.func(pow_to_mul(base), exp, evaluate=False) elif exp > 0: return sympy.Mul(*[base]*int(exp), evaluate=False) else: # SymPy represents 1/x as Pow(x,-1). Also, it represents # 2/x as Mul(2, Pow(x, -1)). So we shouldn't end up here, # but just in case SymPy changes its internal conventions... posexpr = sympy.Mul(*[base]*(-int(exp)), evaluate=False) return sympy.Pow(posexpr, -1, evaluate=False) else: return expr.func(*[pow_to_mul(i) for i in expr.args], evaluate=False)
Example #12
Source File: operator.py From sympsi with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _replace_op_func(e, variable): if isinstance(e, Operator): return OperatorFunction(e, variable) if e.is_Number: return e if isinstance(e, Pow): return Pow(_replace_op_func(e.base, variable), e.exp) new_args = [_replace_op_func(arg, variable) for arg in e.args] if isinstance(e, Add): return Add(*new_args) elif isinstance(e, Mul): return Mul(*new_args) else: return e
Example #13
Source File: differentiable.py From devito with MIT License | 5 votes |
def __div__(self, other): return Mul(self, Pow(other, sympy.S.NegativeOne))
Example #14
Source File: duration.py From Cirq with Apache License 2.0 | 5 votes |
def _decompose_into_amount_unit_suffix(self) -> Tuple[int, str, str]: if (isinstance(self._picos, sympy.Mul) and len(self._picos.args) == 2 and isinstance(self._picos.args[0], (sympy.Integer, sympy.Float))): scale = self._picos.args[0] rest = self._picos.args[1] else: scale = self._picos rest = 1 if scale % 1000_000_000 == 0: amount = scale / 1000_000_000 unit = 'millis' suffix = 'ms'
Example #15
Source File: quirk_gate.py From Cirq with Apache License 2.0 | 5 votes |
def _is_supported_formula(formula: sympy.Basic) -> bool: if isinstance(formula, (sympy.Symbol, sympy.Integer, sympy.Float, sympy.Rational, sympy.NumberSymbol)): return True if isinstance(formula, (sympy.Add, sympy.Mul)): return all(_is_supported_formula(f) for f in formula.args) return False
Example #16
Source File: _expr.py From chempy with BSD 2-Clause "Simplified" License | 5 votes |
def _implicit_conversion(obj): if isinstance(obj, (int, float)): return Constant(obj) elif isinstance(obj, Expr): return obj elif isinstance(obj, str): return Symbol(unique_keys=(obj,)) if sympy is not None: if isinstance(obj, sympy.Mul): if len(obj.args) != 2: raise NotImplementedError("Did you use evaluate=False?") return _MulExpr([_implicit_conversion(obj.args[0]), _implicit_conversion(obj.args[1])]) elif isinstance(obj, sympy.Add): if len(obj.args) != 2: raise NotImplementedError("Did you use evaluate=False?") return _AddExpr([_implicit_conversion(obj.args[0]), _implicit_conversion(obj.args[1])]) elif isinstance(obj, sympy.Pow): return _PowExpr(_implicit_conversion(obj.base), _implicit_conversion(obj.exp)) elif isinstance(obj, sympy.Float): return Constant(float(obj)) elif isinstance(obj, sympy.Symbol): return Symbol(unique_keys=(obj.name,)) raise NotImplementedError( "Don't know how to convert %s (of type %s)" % (obj, type(obj)))
Example #17
Source File: differentiable.py From devito with MIT License | 5 votes |
def __mul__(self, other): return Mul(self, other)
Example #18
Source File: differentiable.py From devito with MIT License | 5 votes |
def __imul__(self, other): return Mul(self, other)
Example #19
Source File: ops.py From mathematics_dataset with Apache License 2.0 | 5 votes |
def expanded_signs_and_terms(self): """Returns a list of arguments, plus any sub-arguments from sub-adds. E.g., if this op is `Add(Add(2, Neg(3)), Mul(4, 5), 1)`, then will return `[(True, 2), (False, 3), (True, Mul(4, 5)), (True, 1)]` (the arguments of the inner add have been extracted). """
Example #20
Source File: differentiable.py From devito with MIT License | 5 votes |
def __rdiv__(self, other): return Mul(other, Pow(self, sympy.S.NegativeOne))
Example #21
Source File: differentiable.py From devito with MIT License | 5 votes |
def __neg__(self): return Mul(sympy.S.NegativeOne, self)
Example #22
Source File: differentiable.py From devito with MIT License | 5 votes |
def _gather_for_diff(self): """ We handle Mul arguments by hand in case of staggered inputs such as `f(x)*g(x + h_x/2)` that will be transformed into f(x + h_x/2)*g(x + h_x/2) and priority of indexing is applied to have single indices as in this example. The priority is from least to most: - param - NODE - staggered """ if len(set(f.staggered for f in self._args_diff)) == 1: return self func_args = highest_priority(self) new_args = [] ref_inds = func_args.indices_ref._getters for f in self.args: if f not in self._args_diff: new_args.append(f) elif f is func_args: new_args.append(f) else: ind_f = f.indices_ref._getters mapper = {ind_f.get(d, d): ref_inds.get(d, d) for d in self.dimensions if ind_f.get(d, d) is not ref_inds.get(d, d)} if mapper: new_args.append(f.subs(mapper)) else: new_args.append(f) return self.func(*new_args, evaluate=False)
Example #23
Source File: differentiable.py From devito with MIT License | 5 votes |
def _doit(obj, args=None): cls = diffify._cls(obj) args = args or obj.args if cls is obj.__class__: # Try to just update the args if possible (Add, Mul) try: return obj._new_rawargs(*args, is_commutative=obj.is_commutative) # Or just return the object (Float, Symbol, Function, ...) except AttributeError: return obj # Create object directly from args, avoid any rebuild return cls(*args, evaluate=False)
Example #24
Source File: sympy.py From qupulse with MIT License | 5 votes |
def numpy_compatible_mul(*args) -> Union[sympy.Mul, sympy.Array]: if any(isinstance(a, sympy.NDimArray) for a in args): result = 1 for a in args: result = result * (numpy.array(a.tolist()) if isinstance(a, sympy.NDimArray) else a) return sympy.Array(result) else: return sympy.Mul(*args)
Example #25
Source File: sympy.py From qupulse with MIT License | 5 votes |
def substitute_with_eval(expression: sympy.Expr, substitutions: Dict[str, Union[sympy.Expr, numpy.ndarray, str]]) -> sympy.Expr: """Substitutes only sympy.Symbols. Workaround for numpy like array behaviour. ~Factor 3 slower compared to subs""" substitutions = {k: v if isinstance(v, sympy.Expr) else sympify(v) for k, v in substitutions.items()} for symbol in get_free_symbols(expression): symbol_name = str(symbol) if symbol_name not in substitutions: substitutions[symbol_name] = symbol string_representation = sympy.srepr(expression) return eval(string_representation, sympy.__dict__, {'Symbol': substitutions.__getitem__, 'Mul': numpy_compatible_mul})
Example #26
Source File: sympy.py From qupulse with MIT License | 5 votes |
def _recursive_substitution(expression: sympy.Expr, substitutions: Dict[sympy.Symbol, sympy.Expr]) -> sympy.Expr: if not expression.free_symbols: return expression elif expression.func is sympy.Symbol: return substitutions.get(expression, expression) elif expression.func is sympy.Mul: func = numpy_compatible_mul else: func = expression.func substitutions = {s: substitutions.get(s, s) for s in get_free_symbols(expression)} return func(*(_recursive_substitution(arg, substitutions) for arg in expression.args))
Example #27
Source File: process_latex.py From latex2sympy with MIT License | 5 votes |
def convert_postfix_list(arr, i=0): if i >= len(arr): raise Exception("Index out of bounds") res = convert_postfix(arr[i]) if isinstance(res, sympy.Expr): if i == len(arr) - 1: return res # nothing to multiply by else: if i > 0: left = convert_postfix(arr[i - 1]) right = convert_postfix(arr[i + 1]) if isinstance(left, sympy.Expr) and isinstance(right, sympy.Expr): left_syms = convert_postfix(arr[i - 1]).atoms(sympy.Symbol) right_syms = convert_postfix(arr[i + 1]).atoms(sympy.Symbol) # if the left and right sides contain no variables and the # symbol in between is 'x', treat as multiplication. if len(left_syms) == 0 and len(right_syms) == 0 and str(res) == "x": return convert_postfix_list(arr, i + 1) # multiply by next return sympy.Mul(res, convert_postfix_list(arr, i + 1), evaluate=False) else: # must be derivative wrt = res[0] if i == len(arr) - 1: raise Exception("Expected expression for derivative") else: expr = convert_postfix_list(arr, i + 1) return sympy.Derivative(expr, wrt)
Example #28
Source File: process_latex.py From latex2sympy with MIT License | 5 votes |
def convert_frac(frac): diff_op = False partial_op = False lower_itv = frac.lower.getSourceInterval() lower_itv_len = lower_itv[1] - lower_itv[0] + 1 if (frac.lower.start == frac.lower.stop and frac.lower.start.type == PSLexer.DIFFERENTIAL): wrt = get_differential_var_str(frac.lower.start.text) diff_op = True elif (lower_itv_len == 2 and frac.lower.start.type == PSLexer.SYMBOL and frac.lower.start.text == '\\partial' and (frac.lower.stop.type == PSLexer.LETTER or frac.lower.stop.type == PSLexer.SYMBOL)): partial_op = True wrt = frac.lower.stop.text if frac.lower.stop.type == PSLexer.SYMBOL: wrt = wrt[1:] if diff_op or partial_op: wrt = sympy.Symbol(wrt) if (diff_op and frac.upper.start == frac.upper.stop and frac.upper.start.type == PSLexer.LETTER and frac.upper.start.text == 'd'): return [wrt] elif (partial_op and frac.upper.start == frac.upper.stop and frac.upper.start.type == PSLexer.SYMBOL and frac.upper.start.text == '\\partial'): return [wrt] upper_text = rule2text(frac.upper) expr_top = None if diff_op and upper_text.startswith('d'): expr_top = process_sympy(upper_text[1:]) elif partial_op and frac.upper.start.text == '\\partial': expr_top = process_sympy(upper_text[len('\\partial'):]) if expr_top: return sympy.Derivative(expr_top, wrt) expr_top = convert_expr(frac.upper) expr_bot = convert_expr(frac.lower) return sympy.Mul(expr_top, sympy.Pow(expr_bot, -1, evaluate=False), evaluate=False)
Example #29
Source File: _ode_composition.py From pygom with GNU General Public License v2.0 | 5 votes |
def _getExpression(expr, input_dict): """ all the operations is dependent on the conditions whether all the elements are leafs or only some of them. Only return expressions and not the individual elements """ t = expr.args if len(expr.atoms()) > 1 else [expr] # print t # find out the length of the components within this node t_lengths = np.array(list(map(_expressionLength, t))) # print(tLengths) if np.all(t_lengths == 0): # if all components are leafs, then the node is an expression input_dict.setdefault(expr, 0) input_dict[expr] += 1 else: for i, ti in enumerate(t): # if the leaf is a singleton, then it is an expression # else, go further along the tree if t_lengths[i] == 0: input_dict.setdefault(ti, 0) input_dict[ti] += 1 else: if isinstance(ti, sympy.Mul): _getExpression(ti, input_dict) elif isinstance(ti, sympy.Pow): input_dict.setdefault(ti, 0) input_dict[ti] += 1
Example #30
Source File: arithmetic.py From mathematics_dataset with Apache License 2.0 | 5 votes |
def _surd_coefficients(sympy_exp): """Extracts coefficients a, b, where sympy_exp = a + b * sqrt(base).""" sympy_exp = sympy.simplify(sympy.expand(sympy_exp)) def extract_b(b_sqrt_base): """Returns b from expression of form b * sqrt(base).""" if isinstance(b_sqrt_base, sympy.Pow): # Just form sqrt(base) return 1 else: assert isinstance(b_sqrt_base, sympy.Mul) assert len(b_sqrt_base.args) == 2 assert b_sqrt_base.args[0].is_rational assert isinstance(b_sqrt_base.args[1], sympy.Pow) # should be sqrt. return b_sqrt_base.args[0] if sympy_exp.is_rational: # Form: a. return sympy_exp, 0 elif isinstance(sympy_exp, sympy.Add): # Form: a + b * sqrt(base) assert len(sympy_exp.args) == 2 assert sympy_exp.args[0].is_rational a = sympy_exp.args[0] b = extract_b(sympy_exp.args[1]) return a, b else: # Form: b * sqrt(base). return 0, extract_b(sympy_exp)