def from_factored_str(cls, numerator, denomenator, factor_numerator): if factor_numerator: unpacked_numerator = cls.no_powers(factor_list(numerator)) else: unpacked_numerator = [str(numerator.expand())] unpacked_denomenator = cls.no_powers(factor_list(denomenator)) return cls(unpacked_numerator, unpacked_denomenator)
def apply_list(self, expr, vars, evaluation): "FactorTermsList[expr_, vars_List]" if expr == Integer(0): return Expression("List", Integer(1), Integer(0)) elif isinstance(expr, Number): return Expression("List", expr, Integer(1)) for x in vars.leaves: if not (isinstance(x, Atom)): return evaluation.message("CoefficientList", "ivar", x) sympy_expr = expr.to_sympy() if sympy_expr is None: return Expression("List", Integer(1), expr) sympy_expr = sympy.together(sympy_expr) sympy_vars = [ x.to_sympy() for x in vars.leaves if isinstance(x, Symbol) and sympy_expr.is_polynomial(x.to_sympy()) ] result = [] numer, denom = sympy_expr.as_numer_denom() try: if denom == 1: # Get numerical part num_coeff, num_polys = sympy.factor_list(sympy.Poly(numer)) result.append(num_coeff) # Get factors are independent of sub list of variables if (sympy_vars and isinstance(expr, Expression) and any( x.free_symbols.issubset(sympy_expr.free_symbols) for x in sympy_vars)): for i in reversed(range(len(sympy_vars))): numer = sympy.factor(numer) / sympy.factor(num_coeff) num_coeff, num_polys = sympy.factor_list( sympy.Poly(numer), *[x for x in sympy_vars[:(i + 1)]]) result.append(sympy.expand(num_coeff)) # Last factor numer = sympy.factor(numer) / sympy.factor(num_coeff) result.append(sympy.expand(numer)) else: num_coeff, num_polys = sympy.factor_list(sympy.Poly(numer)) den_coeff, den_polys = sympy.factor_list(sympy.Poly(denom)) result = [ num_coeff / den_coeff, sympy.expand( sympy.factor(numer) / num_coeff / (sympy.factor(denom) / den_coeff)), ] except sympy.PolynomialError: # MMA does not raise error for non poly result.append(sympy.expand(numer)) # evaluation.message(self.get_name(), 'poly', expr) return Expression("List", *[from_sympy(i) for i in result])
def get_lc(self): numerator_factors = factor_list(self.get_n_str()) n_no_lc = self.no_powers(numerator_factors, include_lc=False) n_lc = int(numerator_factors[0]) denomenator_factors = factor_list(self.get_d_str()) d_no_lc = self.no_powers(denomenator_factors, include_lc=False) d_lc = int(denomenator_factors[0]) return n_lc, n_no_lc, d_lc, d_no_lc
def check_solutions(eq): """ Determines whether solutions returned by diophantine() satisfy the original equation. Hope to generalize this so we can remove functions like check_ternay_quadratic, check_solutions_normal, check_solutions() """ s = diophantine(eq) terms = factor_list(eq)[1] var = list(eq.free_symbols) var.sort(key=default_sort_key) okay = True while len(s) and okay: solution = s.pop() okay = False for term in terms: subeq = term[0] if simplify(_mexpand(Subs(subeq, var, solution).doit())) == 0: okay = True break return okay
def reduce_squarefree(self): eqs_sqf = [] factored_eqs_sqf = {} flag = False for eq in self.eqs: # If factored before, just copy the factorization eq_expr = eq.expr if eq_expr in self.factored_eqs: eqs_sqf.append(eq) factored_eqs_sqf[eq_expr] = self.factored_eqs[eq_expr] continue factors = sp.factor_list(eq, extension = True) factors = [ factor[0] for factor in factors[1] ] eq_sqf = to_poly(1, self.X_vars) for factor in factors: eq_sqf *= factor eq_sqf = to_poly(eq_sqf / eq_sqf.LC(order = 'grevlex'), self.X_vars) eqs_sqf.append(eq_sqf) factored_eqs_sqf[eq_sqf.expr] = factors if not flag and eq_sqf.LM() != eq.LM(): flag = True self.eqs = eqs_sqf self.factored_eqs = factored_eqs_sqf return flag
def apply_list(self, expr, vars, evaluation): 'FactorTermsList[expr_, vars_List]' if expr == Integer(0): return Expression('List', Integer(1), Integer(0)) elif isinstance(expr, Number): return Expression('List', expr, Integer(1)) for x in vars.leaves: if not(isinstance(x, Atom)): return evaluation.message('CoefficientList', 'ivar', x) sympy_expr = expr.to_sympy() if sympy_expr is None: return Expression('List', Integer(1), expr) sympy_expr = sympy.together(sympy_expr) sympy_vars = [x.to_sympy() for x in vars.leaves if isinstance(x, Symbol) and sympy_expr.is_polynomial(x.to_sympy())] result = [] numer, denom = sympy_expr.as_numer_denom() try: from sympy import factor, factor_list, Poly if denom == 1: # Get numerical part num_coeff, num_polys = factor_list(Poly(numer)) result.append(num_coeff) # Get factors are independent of sub list of variables if (sympy_vars and isinstance(expr, Expression) and any(x.free_symbols.issubset(sympy_expr.free_symbols) for x in sympy_vars)): for i in reversed(range(len(sympy_vars))): numer = factor(numer) / factor(num_coeff) num_coeff, num_polys = factor_list(Poly(numer), *[x for x in sympy_vars[:(i+1)]]) result.append(sympy.expand(num_coeff)) # Last factor numer = factor(numer) / factor(num_coeff) result.append(sympy.expand(numer)) else: num_coeff, num_polys = factor_list(Poly(numer)) den_coeff, den_polys = factor_list(Poly(denom)) result = [num_coeff / den_coeff, sympy.expand(factor(numer)/num_coeff / (factor(denom)/den_coeff))] except sympy.PolynomialError: # MMA does not raise error for non poly result.append(sympy.expand(numer)) # evaluation.message(self.get_name(), 'poly', expr) return Expression('List', *[from_sympy(i) for i in result])
def factorlist(): try: print('factor list: {}'.format(request.json)) ps = parse_expr(request.json['expression'], locals()) return jsonify({'in': latex(ps), 'out': latex(factor_list(ps))}) except Exception as e: print(e) return str(e), 400
def geratriz(basedir, gx, gy): count = 0 limit = 1000000 while count < limit: p = pij(gx, gy) + pij(gx, gy) - pij(gx, gy) if len(factor_list(p)[1]) == 1: dirname = f"{basedir}/gx={gx}/gy={gy}" filename = f"{dirname}/{hash(p)}" pathlib.Path(dirname).mkdir(parents=True, exist_ok=True) np.save(filename, np.array([p])) count = count + 1
def get_max_even_divisor(polynomial): """ :param polynomial: sympy polynomial :return: leading coefficient of poly, max polynomial divisor of poly that's even power, remainder of poly / max_divisor """ _factors = factor_list(polynomial) _coeff_leading = _factors[0] _factors_non_constant = _factors[1] _factors_max_even_divisor = [(_p, 2 * (n // 2)) for (_p, n) in _factors_non_constant] _factors_remainder = [(_p, n - 2 * (n // 2)) for (_p, n) in _factors_non_constant] _max_even_divisor = np.prod([_p.as_expr() ** n for (_p, n) in _factors_max_even_divisor]) _remainder = np.prod([_p.as_expr() ** n for (_p, n) in _factors_remainder]) return _coeff_leading, _max_even_divisor, _remainder
def eqn_to_mul_add(eqn): atoms = {s: 0 for s in eqn.atoms() if s.is_symbol} if not atoms: return eqn coeff, factors = sp.factor_list(eqn) if len(factors) > 1: for factor, power in factors: coeff *= eqn_to_mul_add(factor) return coeff elif not factors: return coeff this_factor, power = factors[0] _, terms = this_factor.as_coeff_add() for term in terms: for atom in term.atoms(): if atom in atoms: atoms[atom] += 1 root, _ = max(atoms.items(), key=lambda x: x[1]) b = this_factor.coeff(root, 0) a = 0 for i in range(10): a += this_factor.coeff(root, i + 1) * (root**i) a = eqn_to_mul_add(a) b = eqn_to_mul_add(b) result = coeff for i in range(power): result *= (a * root + b) return result
def divides(a,b): x = b/a print(re(x)) real = factor_list(re(x)*Number(1))[0] imaginary = factor_list(im(x)*Number(1))[0] return real.is_Integer and imaginary.is_Integer
def sympy_factor(self, p): sympy_p = self.sympy_from_upolynomial(p) if (p.ring().modulus() is None): return sympy.factor_list(sympy_p) else: return sympy.factor_list(sympy_p, modulus=p.ring().modulus())
def compute_ifactors(poly): for (ipoly, _) in sp.factor_list(poly)[1]: yield ipoly
def integral_basis(f,x,y): """ Compute the integral basis {b1, ..., bg} of the algebraic function field C[x,y] / (f). """ # If the curve is not monic then map y |-> y/lc(x) where lc(x) # is the leading coefficient of f T = sympy.Dummy('T') d = sympy.degree(f,y) lc = sympy.LC(f,y) if x in lc: f = sympy.ratsimp( f.subs(y,y/lc)*lc**(d-1) ) else: f = f/lc lc = 1 # # Compute df # p = sympy.Poly(f,[x,y]) n = p.degree(y) res = sympy.resultant(p,p.diff(y),y) factors = sympy.factor_list(res)[1] df = [k for k,deg in factors if (deg > 1) and (sympy.LC(k) == 1)] # # Compute series truncations at appropriate x points # alpha = [] r = [] for l in range(len(df)): k = df[l] alphak = sympy.roots(k).keys()[0] rk = compute_series_truncations(f,x,y,alphak,T) alpha.append(alphak) r.append(rk) # # Main Loop # a = [sympy.Dummy('a%d'%k) for k in xrange(n)] b = [1] for d in range(1,n): bd = y*b[-1] for l in range(len(df)): k = df[l] alphak = alpha[l] rk = r[l] found_something = True while found_something: # construct system of equations consisting of the coefficients # of negative powers of (x-alphak) in the substitutions # A(r_{k,1}),...,A(r_{k,n}) A = (sum(ak*bk for ak,bk in zip(a,b)) + bd) / (x - alphak) coeffs = [] for rki in rk: # substitute and extract coefficients A_rki = A.subs(y,rki) coeffs.extend(_negative_power_coeffs(A_rki, x, alphak)) # solve the coefficient equations for a0,...,a_{d-1} coeffs = [coeff.as_numer_denom()[0] for coeff in coeffs] sols = sympy.solve_poly_system(coeffs, a[:d]) if sols is None or sols == []: found_something = False else: sol = sols[0] bdm1 = sum( sol[i]*bk for i,bk in zip(range(d),b) ) bd = (bdm1 + bd) / k # bd found. Append to list of basis elements b.append( bd ) # finally, convert back to singularized curve if necessary for i in xrange(1,len(b)): b[i] = b[i].subs(y,y*lc).ratsimp() return b
f= sym.lambdify(x,sym1,'numpy') a=np.arange(1,10,0.01) f(a) # return the np.ndarray # it's fast Eq(f,2) or f-2 from sympy.utilities.autowrap import ufuncify g = ufuncify([x],f) ufuncify is better than lambdify for larger than 1 s; do to its compile overhead ############################################################ # 1.1 sym1.simplify() sym1.expand() sym1.factor() sym.factor_list(expr) sym1.collect(x) sym1.coeff(x,2) sym1.cancel() sym1.apart() # tajziye kasr ha # 1.2 sym1.trigsimp() sym1.rewrite(sin) # tan(x).rewrite(sin) , foctorial(x).rewrite(gamma) ###### # 2.1 sym1.series(x,x0,n) sym1.removeO() ########################################################### # 3.1 # 3.2 sym.solveset(f,x,domain=sym.S.Complexes) sym.solveset(f<0,domain=sym.S.Reals)