def test_sstrrepr(): assert sstr("abc") == "abc" assert sstrrepr("abc") == "'abc'" e = ["a", "b", "c", x] assert sstr(e) == "[a, b, c, x]" assert sstrrepr(e) == "['a', 'b', 'c', x]"
def test_Matrix(): M = Matrix([[x**+1, 1], [y, x + y]]) assert str(M) == sstr(M) == "[x, 1]\n[y, x + y]" M = Matrix() assert str(M) == sstr(M) == "[]" M = Matrix(0, 1, lambda i, j: 0) assert str(M) == sstr(M) == "[]"
def test_PrettyPoly(): from sympy.polys.domains import QQ F = QQ.frac_field(x, y) R = QQ[x, y] assert sstr(F.convert(x / (x + y))) == sstr(x / (x + y)) assert sstr(R.convert(x + y)) == sstr(x + y)
def test_sstrrepr(): assert sstr('abc') == 'abc' assert sstrrepr('abc') == "'abc'" e = ['a', 'b', 'c', x] assert sstr(e) == "[a, b, c, x]" assert sstrrepr(e) == "['a', 'b', 'c', x]"
def test_set(): assert sstr(set()) == 'set()' assert sstr(frozenset()) == 'frozenset()' assert sstr(set([1, 2, 3])) == 'set([1, 2, 3])' assert sstr( set([1, x, x**2, x**3, x**4])) == 'set([1, x, x**2, x**3, x**4])'
def replaceWith(s, symbols, i): ''' Replaces `With` and `Module by python functions` ''' if type(s) == Function('With') or type(s) == Function('Module'): constraints = ', ' result = ' def With{}({}):'.format(i, ', '.join(symbols)) if type(s.args[0]) == Function('List'): # get all local varibles of With and Module L = list(s.args[0].args) else: L = [s.args[0]] for i in L: # define local variables if isinstance(i, Set): result += '\n {} = {}'.format(i.args[0], sstr(i.args[1], sympy_integers=True)) elif isinstance(i, Symbol): result += "\n {} = Symbol('{}')".format(i, i) if type(s.args[1]) == Function('CompoundExpression'): # Expand CompoundExpression C = s.args[1] if isinstance(C.args[0], Set): result += '\n {} = {}'.format(C.args[0].args[0], C.args[0].args[1]) result += '\n return {}'.format(sstr(C.args[1], sympy_integers=True)) return result, constraints elif type(s.args[1]) == Function('Condition'): C = s.args[1] if len(C.args) == 2: constraints += 'CustomConstraint(lambda {}: {})'.format(', '.join([str(i) for i in C.free_symbols]), sstr(C.args[1], sympy_integers=True)) result += '\n return {}'.format(sstr(C.args[0], sympy_integers=True)) return result, constraints result += '\n return {}'.format(sstr(s.args[1], sympy_integers=True)) return result, constraints else: return sstr(s, sympy_integers=True), ''
def test_noncommutative(): A, B, C = symbols('A,B,C', commutative=False) assert sstr(A*B*C**-1) == "A*B*C**(-1)" assert sstr(C**-1*A*B) == "C**(-1)*A*B" assert sstr(A*C**-1*B) == "A*C**(-1)*B" assert sstr(sqrt(A)) == "sqrt(A)" assert sstr(1/sqrt(A)) == "A**(-1/2)"
def test_printmethod(): class R(abs): def _sympystr(self, printer): return "foo(%s)" % printer._print(self.args[0]) assert sstr(R(x)) == "foo(x)" class R(abs): def _sympystr(self, printer): return "foo" assert sstr(R(x)) == "foo"
def test_Rational(): n1 = Rational(1, 4) n2 = Rational(1, 3) n3 = Rational(2, 4) n4 = Rational(2, -4) n5 = Rational(0) n7 = Rational(3) n8 = Rational(-3) assert str(n1*n2) == "1/12" assert str(n1*n2) == "1/12" assert str(n3) == "1/2" assert str(n1*n3) == "1/8" assert str(n1 + n3) == "3/4" assert str(n1 + n2) == "7/12" assert str(n1 + n4) == "-1/4" assert str(n4*n4) == "1/4" assert str(n4 + n2) == "-1/6" assert str(n4 + n5) == "-1/2" assert str(n4*n5) == "0" assert str(n3 + n4) == "0" assert str(n1**n7) == "1/64" assert str(n2**n7) == "1/27" assert str(n2**n8) == "27" assert str(n7**n8) == "1/27" assert str(Rational("-25")) == "-25" assert str(Rational("1.25")) == "5/4" assert str(Rational("-2.6e-2")) == "-13/500" assert str(S("25/7")) == "25/7" assert str(S("-123/569")) == "-123/569" assert str(S("0.1[23]", rational=1)) == "61/495" assert str(S("5.1[666]", rational=1)) == "31/6" assert str(S("-5.1[666]", rational=1)) == "-31/6" assert str(S("0.[9]", rational=1)) == "1" assert str(S("-0.[9]", rational=1)) == "-1" assert str(sqrt(Rational(1, 4))) == "1/2" assert str(sqrt(Rational(1, 36))) == "1/6" assert str((123**25) ** Rational(1, 25)) == "123" assert str((123**25 + 1)**Rational(1, 25)) != "123" assert str((123**25 - 1)**Rational(1, 25)) != "123" assert str((123**25 - 1)**Rational(1, 25)) != "122" assert str(sqrt(Rational(81, 36))**3) == "27/8" assert str(1/sqrt(Rational(81, 36))**3) == "8/27" assert str(sqrt(-4)) == str(2*I) assert str(2**Rational(1, 10**10)) == "2**(1/10000000000)" assert sstr(Rational(2, 3), sympy_integers=True) == "S(2)/3" x = Symbol("x") assert sstr(x**Rational(2, 3), sympy_integers=True) == "x**(S(2)/3)" assert sstr(Eq(x, Rational(2, 3)), sympy_integers=True) == "Eq(x, S(2)/3)" assert sstr(Limit(x, x, Rational(7, 2)), sympy_integers=True) == \ "Limit(x, x, S(7)/2)"
def test_Matrix_str(): M = Matrix([[x**+1, 1], [y, x + y]]) assert str(M) == "Matrix([[x, 1], [y, x + y]])" assert sstr(M) == "Matrix([\n[x, 1],\n[y, x + y]])" M = Matrix([[1]]) assert str(M) == sstr(M) == "Matrix([[1]])" M = Matrix([[1, 2]]) assert str(M) == sstr(M) == "Matrix([[1, 2]])" M = Matrix() assert str(M) == sstr(M) == "Matrix(0, 0, [])" M = Matrix(0, 1, lambda i, j: 0) assert str(M) == sstr(M) == "Matrix(0, 1, [])"
def __repr__(self): str_sol = 'HolonomicSequence(%s, %s)' % ((self.recurrence).__repr__(), sstr(self.n)) if not self._have_init_cond: return str_sol else: cond_str = '' seq_str = 0 for i in self.u0: cond_str += ', u(%s) = %s' % (sstr(seq_str), sstr(i)) seq_str += 1 sol = str_sol + cond_str return sol
def __repr__(self): str_sol = 'HolonomicFunction(%s, %s)' % ((self.annihilator).__repr__(), sstr(self.x)) if not self._have_init_cond: return str_sol else: cond_str = '' diff_str = '' for i in self.y0: cond_str += ', f%s(%s) = %s' % (diff_str, sstr(self.x0), sstr(i)) diff_str += "'" sol = str_sol + cond_str return sol
def downvalues_rules(r, parsed): ''' Function which generates parsed rules by substituting all possible combinations of default values. ''' res = [] index = 0 for i in r: print('parsing rule {}'.format(r.index(i) + 1)) # Parse Pattern if i[1][1][0] == 'Condition': p = i[1][1][1].copy() else: p = i[1][1].copy() optional = get_default_values(p, {}) pattern = generate_sympy_from_parsed(p.copy(), replace_Int=True) pattern, free_symbols = add_wildcards(pattern, optional=optional) free_symbols = list(set(free_symbols)) #remove common symbols # Parse Transformed Expression and Constraints if i[2][0] == 'Condition': # parse rules without constraints seperately constriant = divide_constraint(i[2][2], free_symbols) # seperate And constraints into indivdual constraints FreeQ_vars, FreeQ_x = seperate_freeq(i[2][2].copy()) # seperate FreeQ into indivdual constraints transformed = generate_sympy_from_parsed(i[2][1].copy(), symbols=free_symbols) else: constriant = '' FreeQ_vars, FreeQ_x = [], [] transformed = generate_sympy_from_parsed(i[2].copy(), symbols=free_symbols) FreeQ_constraint = parse_freeq(FreeQ_vars, FreeQ_x, free_symbols) pattern = sympify(pattern) pattern = sstr(pattern, sympy_integers=True) pattern = setWC(pattern) transformed = sympify(transformed) index += 1 if type(transformed) == Function('With') or type(transformed) == Function('Module'): # define seperate function when With appears transformed, With_constraints = replaceWith(transformed, free_symbols, index) parsed += ' pattern' + str(index) +' = Pattern(' + pattern + '' + FreeQ_constraint + '' + constriant + With_constraints + ')' parsed += '\n{}'.format(transformed) parsed += '\n ' + 'rule' + str(index) +' = ReplacementRule(' + 'pattern' + sstr(index, sympy_integers=True) + ', lambda ' + ', '.join(free_symbols) + ' : ' + 'With{}({})'.format(index, ', '.join(free_symbols)) + ')\n ' else: transformed = sstr(transformed, sympy_integers=True) parsed += ' pattern' + str(index) +' = Pattern(' + pattern + '' + FreeQ_constraint + '' + constriant + ')' parsed += '\n ' + 'rule' + str(index) +' = ReplacementRule(' + 'pattern' + sstr(index, sympy_integers=True) + ', lambda ' + ', '.join(free_symbols) + ' : ' + transformed + ')\n ' parsed += 'rubi.add(rule'+ str(index) +')\n\n' parsed += ' return rubi\n' return parsed
def downvalues_rules(r, parsed): ''' Function which generates parsed rules by substituting all possible combinations of default values. ''' res = [] index = 0 for i in r: #print('parsing rule {}'.format(r.index(i) + 1)) # uncomment to display number of rules parsed # Parse Pattern if i[1][1][0] == 'Condition': p = i[1][1][1].copy() else: p = i[1][1].copy() optional = get_default_values(p, {}) pattern = generate_sympy_from_parsed(p.copy(), replace_Int=True) pattern, free_symbols = add_wildcards(pattern, optional=optional) free_symbols = list(set(free_symbols)) #remove common symbols # Parse Transformed Expression and Constraints if i[2][0] == 'Condition': # parse rules without constraints seperately constriant = divide_constraint(i[2][2], free_symbols) # seperate And constraints into indivdual constraints FreeQ_vars, FreeQ_x = seperate_freeq(i[2][2].copy()) # seperate FreeQ into indivdual constraints transformed = generate_sympy_from_parsed(i[2][1].copy(), symbols=free_symbols) else: constriant = '' FreeQ_vars, FreeQ_x = [], [] transformed = generate_sympy_from_parsed(i[2].copy(), symbols=free_symbols) FreeQ_constraint = parse_freeq(FreeQ_vars, FreeQ_x) pattern = sympify(pattern) pattern = sstr(pattern, sympy_integers=True) pattern = setWC(pattern) transformed = sympify(transformed) transformed = sstr(transformed, sympy_integers=True) index += 1 parsed = parsed + ' pattern' + str(index) +' = Pattern(' + pattern + '' + FreeQ_constraint + '' + constriant + ')' parsed = parsed + '\n ' + 'rule' + str(index) +' = ReplacementRule(' + 'pattern' + sstr(index, sympy_integers=True) + ', lambda ' + ', '.join(free_symbols) + ' : ' + transformed + ')\n ' parsed = parsed + 'rubi.add(rule'+ str(index) +')\n\n' parsed = parsed + ' return rubi\n' # Replace modified functions such as `_Sum` parsed = parsed.replace('_Sum', 'Sum') return parsed
def __str__(self): """ Return latex version of expression as string Use symbol_name_dict from create_symbol_name_dict to convert some symbols into their corresponding latex expressions. In addition, if expression is a LinearEntity, then display as equation of line set to zero. """ from sympy.geometry.line import LinearEntity expression = self._expression symbol_name_dict = create_symbol_name_dict() if isinstance(expression, LinearEntity): xvar = self._parameters.get("xvar", "x") yvar = self._parameters.get("yvar", "y") output = "%s = 0" % latex(expression.equation(x=xvar, y=yvar), symbol_names=symbol_name_dict) else: try: output = latex(expression, symbol_names=symbol_name_dict) except RuntimeError: # for now, since dividing by one creates infinite recursion # in latex printer, use sstr print from sympy.printing import sstr output = sstr(expression) except: output = "[error]" return output
def __str__(self): string = 'Univariate Differential Operator Algebra in intermediate '\ + sstr(self.gen_symbol) + ' over the base ring ' + \ (self.base).__str__() return string
def test_set(): assert sstr(set()) == 'set()' assert sstr(frozenset()) == 'frozenset()' assert sstr(set([1])) == '{1}' assert sstr(frozenset([1])) == 'frozenset({1})' assert sstr(set([1, 2, 3])) == '{1, 2, 3}' assert sstr(frozenset([1, 2, 3])) == 'frozenset({1, 2, 3})' assert sstr( set([1, x, x**2, x**3, x**4])) == '{1, x, x**2, x**3, x**4}' assert sstr( frozenset([1, x, x**2, x**3, x**4])) == 'frozenset({1, x, x**2, x**3, x**4})'
def test_full_prec(): assert sstr(S("0.3"), full_prec=True) == "0.300000000000000" assert sstr(S("0.3"), full_prec="auto") == "0.300000000000000" assert sstr(S("0.3"), full_prec=False) == "0.3" assert sstr(S("0.3") * x, full_prec=True) in ["0.300000000000000*x", "x*0.300000000000000"] assert sstr(S("0.3") * x, full_prec="auto") in ["0.3*x", "x*0.3"] assert sstr(S("0.3") * x, full_prec=False) in ["0.3*x", "x*0.3"]
def __str__(self): listofpoly = self.listofpoly print_str = '' for i, j in enumerate(listofpoly): if j == self.parent.base.zero: continue if i == 0: print_str += '(' + sstr(j) + ')' continue if print_str: print_str += ' + ' if i == 1: print_str += '(' + sstr(j) + ')Dx' continue print_str += '(' + sstr(j) + ')' + 'Dx**' + sstr(i) return print_str
def test_Quantity_str(): assert sstr(second, abbrev=True) == "s" assert sstr(joule, abbrev=True) == "J" assert str(second) == "second" assert str(joule) == "joule"
def test_infinity(): assert sstr(oo*I) == "oo*I"
def __repr__(self): return sstr(self)
def test_SparseMatrix(): M = SparseMatrix([[x**+1, 1], [y, x + y]]) assert str(M) == "Matrix([[x, 1], [y, x + y]])" assert sstr(M) == "Matrix([\n[x, 1],\n[y, x + y]])"
def __str__(self): from sympy.printing import sstr return sstr(self, order=None)
def downvalues_rules(r, header, cons_dict, cons_index): ''' Function which generates parsed rules by substituting all possible combinations of default values. ''' parsed = '\n\n' cons = '' cons_import = [] index = 0 for i in r: print('parsing rule {}'.format(r.index(i) + 1)) # Parse Pattern if i[1][1][0] == 'Condition': p = i[1][1][1].copy() else: p = i[1][1].copy() optional = get_default_values(p, {}) pattern = generate_sympy_from_parsed(p.copy(), replace_Int=True) pattern, free_symbols = add_wildcards(pattern, optional=optional) free_symbols = list(set(free_symbols)) #remove common symbols # Parse Transformed Expression and Constraints if i[2][0] == 'Condition': # parse rules without constraints separately constriant, constraint_def, cons_index = divide_constraint( i[2][2], free_symbols, cons_index, cons_dict, cons_import ) # separate And constraints into individual constraints FreeQ_vars, FreeQ_x = seperate_freeq( i[2][2].copy()) # separate FreeQ into individual constraints transformed = generate_sympy_from_parsed(i[2][1].copy(), symbols=free_symbols) else: constriant = '' constraint_def = '' FreeQ_vars, FreeQ_x = [], [] transformed = generate_sympy_from_parsed(i[2].copy(), symbols=free_symbols) FreeQ_constraint, free_cons_def, cons_index = parse_freeq( FreeQ_vars, FreeQ_x, cons_index, cons_dict, cons_import, free_symbols) pattern = sympify(pattern, locals={ "Or": Function("Or"), "And": Function("And"), "Not": Function("Not") }) pattern = sstr(pattern, sympy_integers=True) pattern = setWC(pattern) transformed = sympify(transformed, locals={ "Or": Function("Or"), "And": Function("And"), "Not": Function("Not") }) constraint_def = constraint_def + free_cons_def cons += constraint_def index += 1 if type(transformed) == Function('With') or type( transformed) == Function( 'Module'): # define separate function when With appears transformed, With_constraints = replaceWith( transformed, free_symbols, index) parsed += ' pattern' + str( index ) + ' = Pattern(' + pattern + '' + FreeQ_constraint + '' + constriant + With_constraints + ')' parsed += '\n{}'.format(transformed) parsed += '\n ' + 'rule' + str( index) + ' = ReplacementRule(' + 'pattern' + sstr( index, sympy_integers=True) + ', lambda ' + ', '.join( free_symbols) + ' : ' + 'With{}({})'.format( index, ', '.join(free_symbols)) + ')\n ' else: transformed = sstr(transformed, sympy_integers=True) parsed += ' pattern' + str( index ) + ' = Pattern(' + pattern + '' + FreeQ_constraint + '' + constriant + ')' parsed += '\n ' + 'rule' + str( index) + ' = ReplacementRule(' + 'pattern' + sstr( index, sympy_integers=True) + ', lambda ' + ', '.join( free_symbols) + ' : ' + transformed + ')\n ' parsed += 'rubi.add(rule' + str(index) + ')\n\n' parsed += ' return rubi\n' header += ' from sympy.integrals.rubi.constraints import ' + ', '.join( word for word in cons_import) parsed = header + parsed return parsed, cons_index, cons
def test_true_false(): assert str(true) == repr(true) == sstr(true) == "True" assert str(false) == repr(false) == sstr(false) == "False"
def __str__(self): string = 'Univariate Recurrence Operator Algebra in intermediate '\ + sstr(self.gen_symbol) + ' over the base ring ' + \ (self.base).__str__() return string
def test_Dict(): assert str(Dict({1: 1 + x})) == sstr({1: 1 + x}) == "{1: x + 1}" assert str(Dict({1: x**2, 2: y*x})) in ( "{1: x**2, 2: x*y}", "{2: x*y, 1: x**2}") assert sstr(Dict({1: x**2, 2: y*x})) == "{1: x**2, 2: x*y}"
def test_Predicate(): assert sstr(Q.even) == 'Q.even'
def test_AppliedPredicate(): assert sstr(Q.even(x)) == 'Q.even(x)'
def _divide_constriant(s, symbols): # Creates a CustomConstraint of the form `CustomConstraint(lambda a, x: FreeQ(a, x))` lambda_symbols = list(set(get_free_symbols(s, symbols, []))) return 'CustomConstraint(lambda {}: {})'.format(', '.join(lambda_symbols), sstr(sympify(generate_sympy_from_parsed(s)), sympy_integers=True))
def test_PrettyPoly(): F = QQ.frac_field(x, y) R = QQ[x, y] assert sstr(F.convert(x / (x + y))) == sstr(x / (x + y)) assert sstr(R.convert(x + y)) == sstr(x + y)
def test_settings(): raises(TypeError, lambda: sstr(S(4), method="garbage"))
def __str__(self): """String representation of a TWave.""" from sympy.printing import sstr return type(self).__name__ + sstr(self.args)
def __repr__(self): from sympy.printing import sstr return sstr(self)
def __str__(self): from sympy.printing import sstr return type(self).__name__ + sstr(self.args)
def test_list(): assert str([x]) == sstr([x]) == "[x]" assert str([x**2, x*y + 1]) == sstr([x**2, x*y + 1]) == "[x**2, x*y + 1]" assert str([x**2, [y + x]]) == sstr([x**2, [y + x]]) == "[x**2, [x + y]]"
def __str__(self): return sstr(self)
def __str__(self): """String representation of a GeometryEntity.""" from sympy.printing import sstr return type(self).__name__ + sstr(tuple(self))
def __str__(self): return 'System(\n' + sstr(self.f) + ',\n' \ + sstr(self.g) + ')'
def test_Geometry(): assert sstr(Point(0, 0)) == 'Point2D(0, 0)' assert sstr(Circle(Point(0, 0), 3)) == 'Circle(Point2D(0, 0), 3)'
def test_NDimArray(): assert sstr(NDimArray(1.0), full_prec=True) == '1.00000000000000' assert sstr(NDimArray(1.0), full_prec=False) == '1.0' assert sstr(NDimArray([1.0, 2.0]), full_prec=True) == '[1.00000000000000, 2.00000000000000]' assert sstr(NDimArray([1.0, 2.0]), full_prec=False) == '[1.0, 2.0]'
def __str__(self): return 'StateSpaceModel(\n' + sstr(self.A) + ',\n' \ + sstr(self.B) + ',\n' \ + sstr(self.C) + ',\n' \ + sstr(self.D) + ')'
def __str__(self): str_sol = 'Beam({}, {}, {})'.format(sstr(self._length), sstr(self._elastic_modulus), sstr(self._second_moment)) return str_sol
def test_infinity(): assert sstr(oo * I) == "oo*I"
def test_tuple(): assert str((x,)) == sstr((x,)) == "(x,)" assert str((x + y, 1 + x)) == sstr((x + y, 1 + x)) == "(x + y, x + 1)" assert str((x + y, ( 1 + x, x**2))) == sstr((x + y, (1 + x, x**2))) == "(x + y, (x + 1, x**2))"
def test_SparseMatrix(): M = SparseMatrix([[x**+1, 1], [y, x + y]]) assert str(M) == sstr(M) == "[x, 1]\n[y, x + y]"
def __str__(self): from sympy.printing import sstr return type(self).__name__ + ': ' + sstr( [self._permittivity, self._permeability, self._n])
def test_printing_str_array_expressions(): assert sstr(ArraySymbol("A", (2, 3, 4))) == "A" assert sstr(ArrayElement("A", (2, 1 / (1 - x), 0))) == "A[2, 1/(1 - x), 0]" M = MatrixSymbol("M", 3, 3) N = MatrixSymbol("N", 3, 3) assert sstr(ArrayElement(M * N, [x, 0])) == "(M*N)[x, 0]"
def test_list(): assert str([x]) == sstr([x]) == "[x]" assert str([x**2, x * y + 1]) == sstr([x**2, x * y + 1 ]) == "[x**2, x*y + 1]" assert str([x**2, [y + x]]) == sstr([x**2, [y + x]]) == "[x**2, [x + y]]"
def _divide_constriant(s, symbols): # Creates a CustomConstraint of the form `CustomConstraint(lambda a, x: FreeQ(a, x))` if s[0] == 'FreeQ': return '' lambda_symbols = list(set(get_free_symbols(s, symbols, []))) return 'CustomConstraint(lambda {}: {})'.format(', '.join(lambda_symbols), sstr(sympify(generate_sympy_from_parsed(s)), sympy_integers=True))
def test_tuple(): assert str((x, )) == sstr((x, )) == "(x,)" assert str((x + y, 1 + x)) == sstr((x + y, 1 + x)) == "(x + y, x + 1)" assert str((x + y, (1 + x, x**2))) == sstr( (x + y, (1 + x, x**2))) == "(x + y, (x + 1, x**2))"