def find_zeroes(expr, var): """find all zero points of a sympy expression(var). Args: expr (sympy.expr): The sympy expression for which the zero points are requested. var (sympy.expr): The variable(s) of the expression Returns: set: a set of floating numbers which are the variable values as the zero points of the expression. Note: The most naive way to find zeros is to use sympy.solve(sympy.Eq(expr, 0), var). However, if we use the following expr as an example, (1/(x-2)+2) / (1 + 1/x + 1/(x-1)) sympy.solve can only find the x=3/2 zero point, without the x=0 and x=1. Our custom function is more smart, it can find more complete solutions, {0,1,3/2} in the above example. I admit that this find_zeroes function has not been comprehensive due to its simple implementation, yet smart enough for the code author's application. """ from sympy.core.power import Pow from sympy.core.mul import Mul from sympy.core.add import Add from sympy import solve, Eq, cancel, fraction from operator import or_ from functools import reduce # recurse the function on each arg if the top function is an addition # e.g. 4 * sqrt(b) * sqrt(c) should also be regarded as a sqrt expression. expr = cancel(expr) n, d = fraction(expr) zeros_from_numerator = set(solve(Eq(n, 0), var)) return zeros_from_numerator
def eval_trigsubstitution(theta, func, rewritten, substep, restriction, integrand, symbol): func = func.subs(sympy.sec(theta), 1/sympy.cos(theta)) trig_function = list(func.find(TrigonometricFunction)) assert len(trig_function) == 1 trig_function = trig_function[0] relation = sympy.solve(symbol - func, trig_function) assert len(relation) == 1 numer, denom = sympy.fraction(relation[0]) if isinstance(trig_function, sympy.sin): opposite = numer hypotenuse = denom adjacent = sympy.sqrt(denom**2 - numer**2) inverse = sympy.asin(relation[0]) elif isinstance(trig_function, sympy.cos): adjacent = numer hypotenuse = denom opposite = sympy.sqrt(denom**2 - numer**2) inverse = sympy.acos(relation[0]) elif isinstance(trig_function, sympy.tan): opposite = numer adjacent = denom hypotenuse = sympy.sqrt(denom**2 + numer**2) inverse = sympy.atan(relation[0]) substitution = [ (sympy.sin(theta), opposite/hypotenuse), (sympy.cos(theta), adjacent/hypotenuse), (sympy.tan(theta), opposite/adjacent), (theta, inverse) ] return sympy.Piecewise( (_manualintegrate(substep).subs(substitution).trigsimp(), restriction) )
def point_on_curve(Xi, Yi): """ Return the (x, y)-coordinates of the point on the curve closest to (Xi, Yi) """ global l_function # Pythagoras's theorem gives us the distance: distance = sp.real_root((Xi - x)**2 + (Yi - function)**2, 2) # We're interested in the points where the derivative of the distance equals zero: derivative = sp.fraction(distance.diff().simplify()) derivative_zero = sp.solveset(derivative[0], x) # Previous line returns all solutions in the complex plane while we only want the real answers: derivative_zero = np.array( [n if sp.re(n) == n else None for n in derivative_zero]) derivative_zero = derivative_zero[derivative_zero != None] # Return the result closest to the function shortest_distance = np.Inf x_new = np.Inf for x_i in derivative_zero: if r(x_i, l_function(x_i), Xi, Yi) < shortest_distance: shortest_distance = r(x_i, l_function(x_i), Xi, Yi) x_new = x_i return (x_new, l_function(x_new))
def PD_controller_gains(desired_pole, open_loop_tf): kp, kd, s = symbols('kp kd s') PD_controller_tf = kp + kd * s gain_product = PD_controller_tf * open_loop_tf closed_tf = get_closed_loop_tf(gain_product) numerator, char_eq = fraction(simplify(closed_tf)) find_kp(desired_pole, char_eq.subs(kd, 0))
def StrTabVarSimple(classe): u = rd.randint(0, 2) if classe == "Seconde": u = -1 v = rd.randint(0, 2) if u == -1: if v == 0: A = IdRemarq() S1 = StrFexpr(A) expr = A if v == 1: A = racinepib() * AxPb() S1 = StrFexpr(A) expr = A if v == 2: A = IdRemarq() expr = sp.sqrt(A) S1 = StrFexpr(expr) deriv = sp.diff(expr, x) [a, b] = fraction(deriv) resultat = solveset(a >= 0, domain=S.Reals) if u == 0: expr = AxPbCarreDur() + sgnnbre() + AxPb() S1 = StrFexpr(expr) if u == 1: expr = AxPb() * AxPb() S1 = StrFexpr(expr) if u == 2: expr = AxPbCubeDur() S1 = StrFexpr(expr) if (u != -1 or v != 2): deriv = sp.diff(expr, x) resultat = solveset(deriv >= 0, domain=S.Reals) return [S1, sp.latex(resultat), sp.latex(deriv)]
def symToTransferFn(Y): Y = sympy.expand(sympy.simplify(Y)) n, d = sympy.fraction(Y) n, d = sympy.Poly(n, s), sympy.Poly(d, s) num, den = n.all_coeffs(), d.all_coeffs() num, den = [float(f) for f in num], [float(f) for f in den] return num, den
def check_3c(answer): import sympy temp = sympy.Rational(1) for i in range(19): temp = 1 + 1 / temp return answer == sympy.fraction(temp)[0]
def symbolic_transfer_function( eq: Union[sp.Expr, int, float]) -> ct.TransferFunction: """ Transform a symbolic equation to a transfer function (sympy -> control) :param eq: your symbolic sympy based equation :return: a control Transfer Function class """ s = sp.var('s') try: if eq.is_real: pass except: if not isinstance(eq, float) and not isinstance(eq, int): used_symbols = [str(sym) for sym in eq.free_symbols] if not len(used_symbols) == 1 or "s" not in used_symbols: raise Exception( "invalid equation, please use correct transfer function equation (e.g. 1/(s**2+3))" ) n, d = sp.fraction(sp.factor(eq)) num = sp.Poly(sp.expand(n), s).all_coeffs() den = sp.Poly(sp.expand(d), s).all_coeffs() num: [float] = [float(v) for v in num] den: [float] = [float(v) for v in den] return ct.TransferFunction(num, den)
def expand(self, **hints): gradient = hints.get('gradient', False) prod = hints.get('prod', False) quotient = hints.get('quotient', False) if gradient: if isinstance(self.args[1], Add): return VecAdd( *[self.func(a).expand(**hints) for a in self.args[1].args]) # if isinstance(self.args[1], Mul): num, den = fraction(self.args[1]) if den != S.One and quotient: # quotient rule return (den * Grad(num) - num * Grad(den)) / den**2 if prod and den == 1: # product rule args = self.args[1].args if len(args) > 1: new_args = [] for i, a in enumerate(args): new_args.append( VecMul(*args[:i], *args[i + 1:], self.func(a))) return VecAdd(*new_args) return self
def test_sym2poly(self): # setup the test variables s, K = sym.symbols("s, K") oltf = 1/(s+1) cltf = oltf/(1 + oltf) num, den = sym.fraction(cltf) # num = 1, test that it can handle # an expression with no symbols res1 = symbolic.sym2poly(num) res2 = symbolic.sym2poly(num, var=s) self.assertEqual(res1, res2) # den = s+2, test that it can handle a # mono variable expression res1 = symbolic.sym2poly(den) res2 = symbolic.sym2poly(den, var=s) self.assertEqual(res1, res2) # assert that you have to specify variable # if using symbolic coefficients p = K*s**2 + 5*s with self.assertRaises(Exception): symbolic.sym2poly(p) symbolic.sym2poly(p, var=s) # asser that numerator and denominator # can be processed at the same time numden = symbolic.sym2poly(num, den) self.assertEqual(len(numden), 2)
def _integrify_basis( basis ): """ Take a vector basis with sympy.Rational in the entries, and scale them so they are all integers by finding the least common multiple of the denominators and multiplying by that. """ def _gcd(a, b): """Return greatest common divisor using Euclid's Algorithm.""" while b: a, b = b, a % b return a def _lcm(a, b): """Return lowest common multiple.""" return a * b // _gcd(a, b) def _lcmm(*args): """Return lcm of args.""" return reduce(_lcm, args) #This is intended for lists of type sympy.Rational assert( use_symbolic_math ) new_basis = [] for vec in basis: #Make a list of the denominators denominators = [sympy.fraction(e)[1] for e in vec] #Find the least common multiple least_common_multiple = _lcmm( *denominators ) #Multiply all the entries by that, make it a python Fraction object new_vec = [ Fraction( int(e*least_common_multiple), 1 ) for e in vec] new_basis.append(new_vec) return new_basis
def get_candinate_reactive_best_responses(opponents): """ Creates a set of possible optimal solutions. """ p_1, p_2 = sym.symbols("p_1, p_2") utility = opt_mo.tournament_utility((p_1, p_2, p_1, p_2), opponents) derivatives = [sym.diff(utility, i) for i in [p_1, p_2]] derivatives = [expr.factor() for expr in derivatives] fractions = [sym.fraction(expr) for expr in derivatives] num, den = [[expr for expr in fraction] for fraction in zip(*fractions)] candinate_roots_p_one = _roots_using_eliminator_method(num, p_1, p_2) candinate_roots_p_two = set() if len(candinate_roots_p_one) > 0: candinate_roots_p_two.update( _roots_solving_system_of_singel_unknown(num, p_2, candinate_roots_p_one, p_1)) for p_one in [0, 1]: coeffs = sym.Poly(num[1].subs({p_1: p_one}), p_2).all_coeffs() roots = _roots_in_bound(coeffs) candinate_roots_p_two.update(roots) candinate_set = candinate_roots_p_one | candinate_roots_p_two | set([0, 1]) return candinate_set
def _integrify_basis(basis: Any) -> Any: """ Take a vector basis with sympy.Rational in the entries, and scale them so they are all integers by finding the least common multiple of the denominators and multiplying by that. """ def _gcd(a: int, b: int): """Return greatest common divisor using Euclid's Algorithm.""" while b: a, b = b, a % b return a def _lcm(a: int, b: int) -> int: """Return lowest common multiple.""" return a * b // _gcd(a, b) def _lcmm(*args: int) -> int: """Return lcm of args.""" return reduce(_lcm, args) new_basis = [] for vec in basis: # Make a list of the denominators denominators: List[int] = [sympy.fraction(e)[1] for e in vec] # Find the least common multiple least_common_multiple = _lcmm(*denominators) # Multiply all the entries by that, make it a python Fraction object new_vec = [Fraction(int(e * least_common_multiple), 1) for e in vec] new_basis.append(new_vec) return new_basis
def fix_expressions(cc_num, common_denom_expr, lmatrix, species_independent, species_dependent): fix_denom = SymcaToolBox.get_fix_denom( lmatrix, species_independent, species_dependent ) fix = False cd_num, cd_denom = fraction(common_denom_expr) ret2 = cd_num if type(cc_num) is list: new_cc_num = cc_num[:] else: new_cc_num = cc_num[:, :] for i, each in enumerate(new_cc_num): new_cc_num[i] = ((each * cd_denom)).expand() for each in new_cc_num: for symb in fix_denom.atoms(Symbol): if symb in each.atoms(Symbol): fix = True break if fix: break if fix: for i, each in enumerate(new_cc_num): new_cc_num[i] = (each / fix_denom).expand() ret2 = (cd_num / fix_denom).expand() return new_cc_num, ret2
def eval_trigsubstitution(theta, func, rewritten, substep, restriction, integrand, symbol): func = func.subs(sympy.sec(theta), 1 / sympy.cos(theta)) trig_function = list(func.find(TrigonometricFunction)) assert len(trig_function) == 1 trig_function = trig_function[0] relation = sympy.solve(symbol - func, trig_function) assert len(relation) == 1 numer, denom = sympy.fraction(relation[0]) if isinstance(trig_function, sympy.sin): opposite = numer hypotenuse = denom adjacent = sympy.sqrt(denom**2 - numer**2) inverse = sympy.asin(relation[0]) elif isinstance(trig_function, sympy.cos): adjacent = numer hypotenuse = denom opposite = sympy.sqrt(denom**2 - numer**2) inverse = sympy.acos(relation[0]) elif isinstance(trig_function, sympy.tan): opposite = numer adjacent = denom hypotenuse = sympy.sqrt(denom**2 + numer**2) inverse = sympy.atan(relation[0]) substitution = [(sympy.sin(theta), opposite / hypotenuse), (sympy.cos(theta), adjacent / hypotenuse), (sympy.tan(theta), opposite / adjacent), (theta, inverse)] return sympy.Piecewise( (_manualintegrate(substep).subs(substitution).trigsimp(), restriction))
def set_primitive_set(self): """ Set up deap set of primitives, needed for genetic programming """ self.pset = gp.PrimitiveSet(self.get_unique_str(), 1) self.pset.renameArguments(ARG0=str(self.var)) # add these symbols into primitive set for S in self.series_to_sum.free_symbols - {self.var}: self.pset.addTerminal(S, name=str(S)) # Add basic operations into the self.use_func( (operator.mul, 2), (operator.div, 2), (operator.sub, 2), (operator.add, 2) ) # find unique number from series unique_num = set() for s_term in self.partitioned_series: unique_num.update(S for S in sympy.postorder_traversal(s_term) if S.is_Number) # convert numbers into fractions and extract nominator and denominator separately unique_num = itertools.chain(*(sympy.fraction(S) for S in unique_num)) self.unique_num = sorted(set(unique_num)) return self
def fraction2N_negP(x): '''N*2**P -> (N,-P) where P<=0''' N, D = fraction(x) negP = int(D).bit_length() - one if not D == 2**negP: raise ValueError('x != N*2**P where P<=0') assert x == N / 2**negP return N, negP
def wiener_attack_rsa(public_key): N = public_key[0] e = public_key[1] # cf = continued_fraction_periodic(e, N) convergents = list(continued_fraction_convergents(cf)) polynomial_power = 0 for i in convergents: polynomial_power += 1 n, d = fraction(i) if n != 0: exp = ((e * d) - 1) / n n2, d2 = fraction(exp) #if d2 == 1: factors = (np.roots([1, -((N - n2) + 1), N])) return factors
def parse_coefficient(line, dimension_symbol, args): '''Decomposes the coefficent into numerator and denominator and \ calculates the order of epsilon of the coefficient.''' d = sp.symbols(dimension_symbol) eps = sp.symbols("eps") coeff_n, coeff_d = sp.fraction(sp.cancel(sp.together(sp.sympify(line).subs(d,4-2*eps)))) coefficient = Coefficient([str(coeff_n)],[str(coeff_d)],args['mandelstam_symbols']+args['mass_symbols']) return coefficient
def convert(Vs): Vs = sy.simplify(Vs) num, den = sy.fraction(Vs) num = np.array(sy.Poly(num, s).all_coeffs(), dtype=np.complex64) den = np.array(sy.Poly(den, s).all_coeffs(), dtype=np.complex64) Vo_sig = sp.lti(num, den) print(Vo_sig) return Vo_sig
def to_coeffs_and_denominator(poly): g = poly g_coeffs, g_gcd = to_coeffs_and_gcd(g) g_numerator, g_denominator = fraction(g_gcd) assert g_gcd > 0 assert g_numerator == 1 r = (g_coeffs, g_denominator) return r
def solve(a, b): s = sympy.fraction(sympy.Rational(a,b)) if sympy.log(s[1],2) % 1 != 0: return 'impossible' y = sympy.ceiling(sympy.log(s[1]/s[0],2)) if y > 40: return 'impossible' else: return str(y)
def d1c_roots(self, h_): # substitute U_0**2 into eq. 2.8 for given value of h and # simplify to create a polynomial in d1c d1cp = WHBase.eq28().subs(U0 ** 2, u_squared()) d1cp = d1cp.subs({h: h_, S: self.S, d0: self.d0}) d1cp = sp.fraction(d1cp.simplify())[0] # get all roots of this polynomial d1c_roots = sp.roots(d1cp, filter=None, multiple=True) return np.array(d1c_roots, dtype=complex)
def AnalyseLogA(expr): S1 = StrFexpr(expr) deriv = sp.diff(expr, x) sgn = together(deriv) [a, b] = fraction(sgn) a = a.expand() sgn = a / b deriv = sgn resultat = solveset(sgn > 0, domain=S.Reals) return [S1, deriv, resultat]
def my_pretty(frac): """ Write a symbolic rational function as a pretty string that can be printed. :param frac: A rational function. :type frac: A symbolic rational function. :return: A pretty version of the input. :rtype: A string. """ num, denom = sympy.fraction(sympy.factor(frac)) return sympy.pretty(num) + "\n" + "/\n" + sympy.pretty(denom) + "\n\n\n\n\n"
def check_4a(answer): import sympy temp = (sympy.sqrt(3) + sympy.sqrt(2)) / (sympy.sqrt(3) - sympy.sqrt(2)) temp = sympy.fraction(temp) temp = (temp[0] * temp[0], temp[1] * temp[0]) temp = (temp[0].simplify(), temp[1].simplify()) temp = temp[0] / temp[1] return answer == temp
def m2n(fnStr, verbose=True): """A function to convert mathematica output into numpy format WARNING: suspect this may be buggy. Required Inputs fnStr :: str :: The mathematica string in FortranFormat Optional Inputs verbose :: bool :: True prints to screen so it can be copied Only supports the output from the two mathematica files in this directory The best way to use this is inside iPython: This example assumes the `Fn // FortranFormat` output from Mathematica is in the clipboard %paste fnStr fnStr = '\n'.join(fnStr) n,d = m2n(fnStr, verbose=True) """ b = Symbol(r'\beta') pa = Symbol(r'\rho') phi = Symbol(r'\phi') theta = Symbol(r'\theta') tau = Symbol(r'\tau') x = Symbol('x') # list if items to remove and replace: [(new, old)] replaceLst = [("E**", "exp"), ("Cos", "cos"), ("/exp(b*tau)", "*x"), ('\n', ''), (' ', ''), ("--", "+")] replaceLst.extend([("/exp(%d*b*tau)" % i, "*x**%d" % i) for i in range(2, 5)]) replaceLst.extend([("exp(-%d*b*tau)" % i, "x**%d" % i) for i in range(2, 5)]) for old, new in replaceLst: fnStr = fnStr.replace(old, new) f = mm.sympify(fnStr) numerator, denominator = [poly(item, x) for item in fraction(f)] # get coefficients starting lowest order to highest order numerator = numerator.all_coeffs() denominator = denominator.all_coeffs() # numpy is in the opposite order numerator.reverse() denominator.reverse() if verbose: print '::: polynomial coefficients: Ordering is 0th -> nth :::' print 'Numerator Array:\n', numerator print '\nDenominator Array:\n', denominator else: return numerator, denominator
def simplify_n_monic(tt): num, den = sp.fraction(sp.simplify(tt)) num = sp.poly(num, s) den = sp.poly(den, s) lcnum = sp.LC(num) lcden = sp.LC(den) return (sp.simplify(lcnum / lcden) * (sp.monic(num) / sp.monic(den)))
def plot(H, show_actual_plot=True, savefig=None): """ """ if type(H) == str: H_str = H else: # e.g. sympy.core.mul.Mul H_str = str(H) tf = Tf(TransferFunction(*sympy.fraction(H_str), s)) tf.plot(show_actual_plot, savefig)
def extract_coefficients(func, t): tx = (diff(func[0], t)) ty = (diff(func[1], t)) eq = together(tx * tx + ty * ty) n, _ = fraction(eq) poly = Poly(n, t) coeffs = poly.all_coeffs() coeffs.reverse() return poly, coeffs
def currents(model): """Extract intrinsic current terms from the model This function assumes that the model is biophysical: the model's first equation is for voltage, specified by current conservation. """ dV = model["equations"][0][1] I_net = sp.fraction(dV)[0] forcing_vars = forcing_names(model) return (term for term in I_net.args if str(term) not in forcing_vars)
def row_sym2dsf(rowsym, names): '''Convert a sympy row into a dictionary of keys to (numerator, denominator) tuples''' from sympy import fraction ret = {} assert len(rowsym) == len(names), (len(rowsym), len(names)) for namei, name in enumerate(names): v = rowsym[namei] if v: (num, den) = fraction(v) ret[name] = (int(num), int(den)) return ret
def transfer_function(): t, s = symbols('t, s') f = ( 4*(s+2)*((s+Rational(2))**3) )/((s+6)*( (s+4)**2 ) ) H = syslin( f ) # disp( ilaplace(apart(H), s, t) ) # can't direct # http://docs.sympy.org/0.6.7/modules/simplify.html numer, _denom = fraction(H) disp(numer) print roots( numer ) # fixme: !!! complex roots! print roots( denom(H) )
def continued_fraction_dc(x): int_part = floor(x) if x == int_part: next_x = None else: next_x = 1 / (x - int_part) next_x = together(next_x) N, D = fraction(next_x) assert D > 0 assert N > D #assert not D > N # here fire!!! return int_part, next_x
def make_internals_dict(cc_sol, cc_names, common_denom_expr, path_to): simpl_dic = {} for i, each in enumerate(cc_sol): expr = each / common_denom_expr expr = SymcaToolBox.maxima_factor(expr, path_to) num, denom = fraction(expr) if not simpl_dic.has_key(denom): simpl_dic[denom] = [[], []] simpl_dic[denom][0].append(cc_names[i]) simpl_dic[denom][1].append(num) return simpl_dic
def nth_pow_continued_fraction(x, n, L, more=False): x0 = x**(one / n) return continued_fraction_L(x0, L, more) ans = cf, x = nth_pow_continued_fraction(2, 3, 102, 1) ''' ([1, 3, 1, 5, 1, 1, 4, 1, 1, 8, 1, 14, 1, 10, 2, 1, 4, 12, 2, 3, 2, 1, 3, 4, 1, 1, 2, 14, 3, 12, 1, 15, 3, 1, 4, 534, 1, 1, 5, 1, 1, 121, 1, 2, 2, 4, 10, 3, 2, 2, 41, 1, 1, 1, 3, 7, 2, 2, 9, 4, 1, 3, 7, 6, 1, 1, 2, 2, 9, 3, 1, 1, 69, 4, 4, 5, 12, 1, 1, 5, 15, 1, 4, 1, 1, 1, 1, 1, 89, 1, 22, 186, 6, 2, 3, 1, 3, 2, 1, 1, 5, 0], (-133450479581198331510402510274281177418327310779117149571 + 105919715836427477757469402582631193698068222179903783354*2**(1/3))/(-18946643396438422418200496503661148314139229271682874349*2**(1/3) + 23871274840024462774930909433822752859720888716067576820)) NOTE: the final 0... ''' N, D = continued_fraction2numerator_denominator(cf) N, D = (fraction(x))
def _print_Pow(self, power): from sympy import fraction b, e = power.as_base_exp() if power.is_commutative: if e is S.NegativeOne: return prettyForm("1")/self._print(b) n, d = fraction(e) if n is S.One and d.is_Atom and not e.is_Integer: return self._print_nth_root(b, e) if e.is_Rational and e < 0: return prettyForm("1")/self._print(b)**self._print(-e) # None of the above special forms, do a standard power return self._print(b)**self._print(e)
def maxima_factor(expression, path_to): """ This function is equivalent to the sympy.cancel() function but uses maxima instead """ maxima_in_file = join(path_to,'in.txt').replace('\\','\\\\') maxima_out_file = join(path_to,'out.txt').replace('\\','\\\\') if expression.is_Matrix: expr_mat = expression[:, :] # print expr_mat print 'Simplifying matrix with ' + str(len(expr_mat)) + ' elements' for i, e in enumerate(expr_mat): sys.stdout.write('*') sys.stdout.flush() if (i + 1) % 50 == 0: sys.stdout.write(' ' + str(i + 1) + '\n') sys.stdout.flush() # print e expr_mat[i] = SymcaToolBox.maxima_factor(e, path_to) sys.stdout.write('\n') sys.stdout.flush() return expr_mat else: batch_string = ( 'stardisp:true;stringout("' + maxima_out_file + '",factor(' + str(expression) + '));') # print batch_string with open(maxima_in_file, 'w') as f: f.write(batch_string) config = ConfigReader.get_config() if config['platform'] == 'win32': maxima_command = [config['maxima_path'], '--batch=' + maxima_in_file] else: maxima_command = ['maxima', '--batch=' + maxima_in_file] dn = open(devnull, 'w') subprocess.call(maxima_command, stdin=dn, stdout=dn, stderr=dn) simplified_expression = '' with open(maxima_out_file) as f: for line in f: if line != '\n': simplified_expression = line[:-2] frac = fraction(sympify(simplified_expression)) # print frac[0].expand()/frac[1].expand() return frac[0].expand() / frac[1].expand()
def fix_expressions(cc_num, common_denom_expr, lmatrix, species_independent, species_dependent): fix_denom = SymcaToolBox.get_fix_denom( lmatrix, species_independent, species_dependent ) #print fix_denom cd_num, cd_denom = fraction(common_denom_expr) new_cc_num = cc_num[:, :] #print type(new_cc_num) for i, each in enumerate(new_cc_num): new_cc_num[i] = ((each * cd_denom) / fix_denom).expand() return new_cc_num, (cd_num / fix_denom).expand()
def _eval_expand_mul(self, deep=True, **hints): from sympy import fraction expr = self n, d = fraction(expr) if d is not S.One: expr = n / d._eval_expand_mul(deep=deep, **hints) if not expr.is_Mul: return expr._eval_expand_mul(deep=deep, **hints) plain, sums, rewrite = [], [], False for factor in expr.args: if deep: term = factor.expand(deep=deep, **hints) if term != factor: factor = term rewrite = True if factor.is_Add: sums.append(factor) rewrite = True else: if factor.is_commutative: plain.append(factor) else: Wrapper = Basic sums.append(Wrapper(factor)) if not rewrite: return expr else: plain = Mul(*plain) if sums: terms = Mul._expandsums(sums) args = [] for term in terms: t = Mul(plain, term) if t.is_Mul and any(a.is_Add for a in t.args): t = t._eval_expand_mul(deep=deep) args.append(t) return Add(*args) else: return plain
def _eval_expand_mul(self, **hints): from sympy import fraction, expand_mul # Handle things like 1/(x*(x + 1)), which are automatically converted # to 1/x*1/(x + 1) expr = self n, d = fraction(expr) if d.is_Mul: expr = n/d._eval_expand_mul(**hints) if not expr.is_Mul: return expand_mul(expr, deep=False) plain, sums, rewrite = [], [], False for factor in expr.args: if factor.is_Add: sums.append(factor) rewrite = True else: if factor.is_commutative: plain.append(factor) else: sums.append(Basic(factor)) # Wrapper if not rewrite: return expr else: plain = Mul(*plain) if sums: terms = Mul._expandsums(sums) args = [] for term in terms: t = Mul(plain, term) if t.is_Mul and any(a.is_Add for a in t.args): t = t._eval_expand_mul() args.append(t) return Add(*args) else: return plain
def test_radsimp(): r2=sqrt(2) r3=sqrt(3) r5=sqrt(5) r7=sqrt(7) assert radsimp(1/r2) == \ sqrt(2)/2 assert radsimp(1/(1 + r2)) == \ -1 + sqrt(2) assert radsimp(1/(r2 + r3)) == \ -sqrt(2) + sqrt(3) assert fraction(radsimp(1/(1 + r2 + r3))) == \ (-sqrt(6) + sqrt(2) + 2, 4) assert fraction(radsimp(1/(r2 + r3 + r5))) == \ (-sqrt(30) + 2*sqrt(3) + 3*sqrt(2), 12) assert fraction(radsimp(1/(1 + r2 + r3 + r5))) == \ (-34*sqrt(10) - 26*sqrt(15) - 55*sqrt(3) - 61*sqrt(2) + 14*sqrt(30) + 93 + 46*sqrt(6) + 53*sqrt(5), 71) assert fraction(radsimp(1/(r2 + r3 + r5 + r7))) == \ (-50*sqrt(42) - 133*sqrt(5) - 34*sqrt(70) - 145*sqrt(3) + 22*sqrt(105) + 185*sqrt(2) + 62*sqrt(30) + 135*sqrt(7), 215) z = radsimp(1/(1 + r2/3 + r3/5 + r5 + r7)) assert len((3616791619821680643598*z).args) == 16 assert radsimp(1/z) == 1/z assert radsimp(1/z, max_terms=20).expand() == 1 + r2/3 + r3/5 + r5 + r7 assert radsimp(1/(r2*3)) == \ sqrt(2)/6 assert radsimp(1/(r2*a + r3 + r5 + r7)) == 1/(r2*a + r3 + r5 + r7) assert radsimp(1/(r2*a + r2*b + r3 + r7)) == \ ((sqrt(42)*(a + b) + sqrt(3)*(-a**2 - 2*a*b - b**2 - 2) + sqrt(7)*(-a**2 - 2*a*b - b**2 + 2) + sqrt(2)*(a**3 + 3*a**2*b + 3*a*b**2 - 5*a + b**3 - 5*b))/ ((a**4 + 4*a**3*b + 6*a**2*b**2 - 10*a**2 + 4*a*b**3 - 20*a*b + b**4 - 10*b**2 + 4)))/2 assert radsimp(1/(r2*a + r2*b + r2*c + r2*d)) == \ (sqrt(2)/(a + b + c + d))/2 assert radsimp(1/(1 + r2*a + r2*b + r2*c + r2*d)) == \ ((sqrt(2)*(-a - b - c - d) + 1)/ (-2*a**2 - 4*a*b - 4*a*c - 4*a*d - 2*b**2 - 4*b*c - 4*b*d - 2*c**2 - 4*c*d - 2*d**2 + 1)) assert radsimp((y**2 - x)/(y - sqrt(x))) == \ sqrt(x) + y assert radsimp(-(y**2 - x)/(y - sqrt(x))) == \ -(sqrt(x) + y) assert radsimp(1/(1 - I + a*I)) == \ (I*(-a + 1) + 1)/(a**2 - 2*a + 2) assert radsimp(1/((-x + y)*(x - sqrt(y)))) == (x + sqrt(y))/((-x + y)*(x**2 - y)) e = (3 + 3*sqrt(2))*x*(3*x - 3*sqrt(y)) assert radsimp(e) == 9*x*(1 + sqrt(2))*(x - sqrt(y)) assert radsimp(1/e) == (-1 + sqrt(2))*(x + sqrt(y))/(9*x*(x**2 - y)) assert radsimp(1 + 1/(1 + sqrt(3))) == Mul(S(1)/2, 1 + sqrt(3), evaluate=False) A = symbols("A", commutative=False) assert radsimp(x**2 + sqrt(2)*x**2 - sqrt(2)*x*A) == x**2 + sqrt(2)*(x**2 - x*A) assert radsimp(1/sqrt(5 + 2 * sqrt(6))) == -sqrt(2) + sqrt(3) assert radsimp(1/sqrt(5 + 2 * sqrt(6))**3) == -11*sqrt(2) + 9*sqrt(3) # coverage not provided by above tests assert collect_const(2*sqrt(3) + 4*a*sqrt(5)) == Mul(2, (2*sqrt(5)*a + sqrt(3)), evaluate=False) assert collect_const(2*sqrt(3) + 4*a*sqrt(5), sqrt(3)) == 2*(2*sqrt(5)*a + sqrt(3)) assert collect_const(sqrt(2)*(1 + sqrt(2)) + sqrt(3) + x*sqrt(2)) == \ sqrt(2)*(x + 1 + sqrt(2)) + sqrt(3)
def test_fraction(): x, y, z = map(Symbol, 'xyz') assert fraction(Rational(1, 2)) == (1, 2) assert fraction(x) == (x, 1) assert fraction(1/x) == (1, x) assert fraction(x/y) == (x, y) assert fraction(x/2) == (x, 2) assert fraction(x*y/z) == (x*y, z) assert fraction(x/(y*z)) == (x, y*z) assert fraction(1/y**2) == (1, y**2) assert fraction(x/y**2) == (x, y**2) assert fraction((x**2+1)/y) == (x**2+1, y) assert fraction(x*(y+1)/y**7) == (x*(y+1), y**7) assert fraction(exp(-x), exact=True) == (exp(-x), 1)
## DC Gain dc_gain = simplify(res_simp).limit('s',0) print "" print "DC Gain:" pprint(dc_gain) print "" ## AC Transfer function tf = collect(res_simp,s) print "AC Transfer function:" pprint(tf) print "" ## Denominator of transfer function tf_denom = fraction(tf)[1] tf_denom = tf_denom.expand() print "Denominator of transfer function times R[1]:" pprint(tf_denom) print "" ## Poles tf_poles = solve(tf_denom,s) tf_poles = simplify(tf_poles) print "Poles of transfer function:" print tf_poles p1 = tf_poles # Need to exctract one pole p2 = tf_poles # Need to extract one pole pprint(p1) pprint(p2) print ""
def sym_rpoly(na=None, nb=None, nk=None, nterms=None): """Compute the R polynomial as defined above. Internally the construction of R is done symbolically. If the numerical variables (na, nb, nk) were supplied, these values are substituted at the end and a sympy.Poly object with numerical coefficients is returned. If (na, nb, nk) are not given, then nterms *must* be given, and a symbolic answer is returned. Parameters ---------- na : ndarray, optional Numerical array of 'a' coefficients. nb : ndarray, optional Numerical array of 'b' coefficients. k : float, optional Numerical value of k. nterms : int, optional. Number of terms. This is only used if na, nb and nk are *not* given, in which case a symbolic answer is returned with nterms total. Returns ------- poly : sympy.Poly instance A univariate polynomial in x. Examples -------- With only nterms, a symbolic polynomial is returned: >>> sym_rpoly(nterms=1) Poly(x**2 - k*x - b_0*k/a_0, x) But if numerical values are supplied, the output polynomial has numerical values: >>> sym_rpoly([2], [5], 3) Poly(x**2 - 3*x - 15/2, x) >>> sym_rpoly([1, 2], [4, 6], 1) Poly(x**3 + 3*x**2 - 7/2*x - 6, x) """ if na is None and nterms is None: raise ValueError('You must provide either arrays or nterms') if nterms is None: na = np.asarray(na) nb = np.asarray(nb) # We have input arrays, return numerical answer if na.ndim > 1: raise ValueError('Input arrays must be one-dimensional') nterms = na.shape mode = 'num' else: # We have only a length, return symbolic answer. mode = 'sym' # Create symbolic variables k, x = sym.symbols('k x') a = symarray(nterms, 'a') b = symarray(nterms, 'b') # Construct polynomial symbolically t = [ ai/(ai*x+bi) for (ai, bi) in zip(a,b)] P, Q = sym.fraction(sym.together(sum(t))) Rs = sym.Poly(x**2*P -k*Q, x) if mode == 'num': # Substitute coefficients for numerical values Rs = Rs.subs([(k, nk)] + zip(a, na) + zip(b, nb)) # Normalize Rs /= Rs.lead_coeff return Rs
L=getLagrangian(M,m2,gamma,alpha1,alpha2,psi,*A) '''L=L.subs({A[0]:0, A[3]:0}).doit() Axeqm=fieldEqn(L,A[2],M.x) Axeqm=Axeqm.subs(A[2],d).series(d,n=2).subs(sp.Order(d**2),0).subs(d,A[2]) Axeqm=(Axeqm/(M.x[0]**2*(M.x[0]**3-1))).ratsimp().collect(A[2]) Axeqm=sum(sp.simplify(e,ratio=1).collect(A[1]) for e in Axeqm.args) #Axeqm=Axeqm.subs({A[2]:d,A[2].diff(M.x[0]):d2,A[2].diff(M.x[0]):d3}).series(d) sp.pprint(Axeqm) totex.save(Axeqm.subs({psi:sp.Symbol('psi'),A[1]:sp.Symbol('phi'),A[2]:sp.Symbol('A_x')}),'Axeqm')''' L=L.subs({gamma:0,alpha1:0,alpha2:0,A[0]:0,A[3]:0}).doit() #psieqm=simpSum( sp.fraction((fieldEqn(L,psi,M.x)/2).together())[0].collect(psi) ) #psieqm=(fieldEqn(L,psi,M.x)/(-M.r**2*2*M.f)).expand().collect(psi) psieqm, phieqm, Axeqm=[sp.fraction(fieldEqn(L,f,M.x).together())[0].expand().collect(f) for f in [psi,A[1],A[2]]] t=sp.Dummy('t') hpsieqm=psieqm.subs(M.x[0],M.zh+t).simplify() hpsiexp=[hpsieqm.diff(t,deg).limit(t,0).subs(A[1].subs(M.x[0],M.zh),0) for deg in range(2)] sp.pprint( sp.solve(hpsiexp[1],psi.subs(M.x[0],M.zh))) #.diff(M.x[0]).subs(M.x[0],M.zh)) ) #phieqm=simpSum( (phieqm/(phieqm.subs(A[1].diff(M.x[0],2),d).diff(d))).together().ratsimp().collect(A[1]) ) #sol=sp.solve(phieqm.subs(A[1].diff(M.x[0],2),d),d) #sp.pprint(sol) #assert len(sol)==1 #fr=sp.fraction(sol[0]) #sp.pprint(fr[0].collect(A[1])/fr[1].collect(A[1])) if __name__=='__main__': sp.pprint(psieqm) sp.pprint(phieqm)
def design_z_filter_single_pole(filt_str, max_gain_freq): """ Finds the coefficients for a simple lowpass/highpass filter. This function just prints the coefficient values, besides the given filter equation and its power gain. There's 3 constraints used to find the coefficients: 1. The G value is defined by the max gain of 1 (0 dB) imposed at a specific frequency 2. The R value is defined by the 50% power cutoff frequency given in rad/sample. 3. Filter should be stable (-1 < R < 1) Parameters ---------- filt_str : Filter equation as a string using the G, R, w and z values. max_gain_freq : A value of zero (DC) or pi (Nyquist) to ensure the max gain as 1 (0 dB). Note ---- The R value is evaluated only at pi/4 rad/sample to find whether -1 < R < 1, and the max gain is assumed to be either 0 or pi, using other values might fail. """ print("H(z) = " + filt_str) # Avoids printing as "1/z" filt = sympify(filt_str, dict(G=G, R=R, w=w, z=z)) print() # Finds the power magnitude equation for the filter freq_resp = filt.subs(z, exp(I * w)) frr, fri = freq_resp.as_real_imag() power_resp = fcompose(expand_complex, cancel, trigsimp)(frr ** 2 + fri ** 2) pprint(Eq(Symbol("Power"), power_resp)) print() # Finds the G value given the max gain value of 1 at the DC or Nyquist # frequency. As exp(I*pi) is -1 and exp(I*0) is 1, we can use freq_resp # (without "abs") instead of power_resp. Gsolutions = factor(solve(Eq(freq_resp.subs(w, max_gain_freq), 1), G)) assert len(Gsolutions) == 1 pprint(Eq(G, Gsolutions[0])) print() # Finds the unconstrained R values for a given cutoff frequency power_resp_no_G = power_resp.subs(G, Gsolutions[0]) half_power_eq = Eq(power_resp_no_G, S.Half) Rsolutions = solve(half_power_eq, R) # Constraining -1 < R < 1 when w = pi/4 (although the constraint is general) Rsolutions_stable = [el for el in Rsolutions if -1 < el.subs(w, pi/4) < 1] assert len(Rsolutions_stable) == 1 # Constraining w to the [0;pi] range, so |sin(w)| = sin(w) Rsolution = Rsolutions_stable[0].subs(abs(sin(w)), sin(w)) pprint(Eq(R, Rsolution)) # More information about the pole (or -pole) print("\n ** Alternative way to write R **\n") if has_sqrt(Rsolution): x = Symbol("x") # A helper symbol xval = sum(el for el in Rsolution.args if not has_sqrt(el)) pprint(Eq(x, xval)) print() pprint(Eq(R, expand(Rsolution.subs(xval, x)))) else: # That's also what would be found in a bilinear transform with prewarping pprint(Eq(R, Rsolution.rewrite(tan).cancel())) # Not so nice numerically # See whether the R denominator can be zeroed for root in solve(fraction(Rsolution)[1], w): if 0 <= root <= pi: power_resp_r = fcompose(expand, cancel)(power_resp_no_G.subs(w, root)) Rsolutions_r = solve(Eq(power_resp_r, S.Half), R) assert len(Rsolutions_r) == 1 print("\nDenominator is zero for this value of " + pretty(w)) pprint(Eq(w, root)) pprint(Eq(R, Rsolutions_r[0]))
def test_radsimp(): r2 = sqrt(2) r3 = sqrt(3) r5 = sqrt(5) r7 = sqrt(7) assert fraction(radsimp(1/r2)) == (sqrt(2), 2) assert radsimp(1/(1 + r2)) == \ -1 + sqrt(2) assert radsimp(1/(r2 + r3)) == \ -sqrt(2) + sqrt(3) assert fraction(radsimp(1/(1 + r2 + r3))) == \ (-sqrt(6) + sqrt(2) + 2, 4) assert fraction(radsimp(1/(r2 + r3 + r5))) == \ (-sqrt(30) + 2*sqrt(3) + 3*sqrt(2), 12) assert fraction(radsimp(1/(1 + r2 + r3 + r5))) == ( (-34*sqrt(10) - 26*sqrt(15) - 55*sqrt(3) - 61*sqrt(2) + 14*sqrt(30) + 93 + 46*sqrt(6) + 53*sqrt(5), 71)) assert fraction(radsimp(1/(r2 + r3 + r5 + r7))) == ( (-50*sqrt(42) - 133*sqrt(5) - 34*sqrt(70) - 145*sqrt(3) + 22*sqrt(105) + 185*sqrt(2) + 62*sqrt(30) + 135*sqrt(7), 215)) z = radsimp(1/(1 + r2/3 + r3/5 + r5 + r7)) assert len((3616791619821680643598*z).args) == 16 assert radsimp(1/z) == 1/z assert radsimp(1/z, max_terms=20).expand() == 1 + r2/3 + r3/5 + r5 + r7 assert radsimp(1/(r2*3)) == \ sqrt(2)/6 assert radsimp(1/(r2*a + r3 + r5 + r7)) == ( (8*sqrt(2)*a**7 - 8*sqrt(7)*a**6 - 8*sqrt(5)*a**6 - 8*sqrt(3)*a**6 - 180*sqrt(2)*a**5 + 8*sqrt(30)*a**5 + 8*sqrt(42)*a**5 + 8*sqrt(70)*a**5 - 24*sqrt(105)*a**4 + 84*sqrt(3)*a**4 + 100*sqrt(5)*a**4 + 116*sqrt(7)*a**4 - 72*sqrt(70)*a**3 - 40*sqrt(42)*a**3 - 8*sqrt(30)*a**3 + 782*sqrt(2)*a**3 - 462*sqrt(3)*a**2 - 302*sqrt(7)*a**2 - 254*sqrt(5)*a**2 + 120*sqrt(105)*a**2 - 795*sqrt(2)*a - 62*sqrt(30)*a + 82*sqrt(42)*a + 98*sqrt(70)*a - 118*sqrt(105) + 59*sqrt(7) + 295*sqrt(5) + 531*sqrt(3))/(16*a**8 - 480*a**6 + 3128*a**4 - 6360*a**2 + 3481)) assert radsimp(1/(r2*a + r2*b + r3 + r7)) == ( (sqrt(2)*a*(a + b)**2 - 5*sqrt(2)*a + sqrt(42)*a + sqrt(2)*b*(a + b)**2 - 5*sqrt(2)*b + sqrt(42)*b - sqrt(7)*(a + b)**2 - sqrt(3)*(a + b)**2 - 2*sqrt(3) + 2*sqrt(7))/(2*a**4 + 8*a**3*b + 12*a**2*b**2 - 20*a**2 + 8*a*b**3 - 40*a*b + 2*b**4 - 20*b**2 + 8)) assert radsimp(1/(r2*a + r2*b + r2*c + r2*d)) == \ sqrt(2)/(2*a + 2*b + 2*c + 2*d) assert radsimp(1/(1 + r2*a + r2*b + r2*c + r2*d)) == ( (sqrt(2)*a + sqrt(2)*b + sqrt(2)*c + sqrt(2)*d - 1)/(2*a**2 + 4*a*b + 4*a*c + 4*a*d + 2*b**2 + 4*b*c + 4*b*d + 2*c**2 + 4*c*d + 2*d**2 - 1)) assert radsimp((y**2 - x)/(y - sqrt(x))) == \ sqrt(x) + y assert radsimp(-(y**2 - x)/(y - sqrt(x))) == \ -(sqrt(x) + y) assert radsimp(1/(1 - I + a*I)) == \ (-I*a + 1 + I)/(a**2 - 2*a + 2) assert radsimp(1/((-x + y)*(x - sqrt(y)))) == \ (-x - sqrt(y))/((x - y)*(x**2 - y)) e = (3 + 3*sqrt(2))*x*(3*x - 3*sqrt(y)) assert radsimp(e) == x*(3 + 3*sqrt(2))*(3*x - 3*sqrt(y)) assert radsimp(1/e) == ( (-9*x + 9*sqrt(2)*x - 9*sqrt(y) + 9*sqrt(2)*sqrt(y))/(9*x*(9*x**2 - 9*y))) assert radsimp(1 + 1/(1 + sqrt(3))) == \ Mul(S.Half, -1 + sqrt(3), evaluate=False) + 1 A = symbols("A", commutative=False) assert radsimp(x**2 + sqrt(2)*x**2 - sqrt(2)*x*A) == \ x**2 + sqrt(2)*x**2 - sqrt(2)*x*A assert radsimp(1/sqrt(5 + 2 * sqrt(6))) == -sqrt(2) + sqrt(3) assert radsimp(1/sqrt(5 + 2 * sqrt(6))**3) == -(-sqrt(3) + sqrt(2))**3 # issue 6532 assert fraction(radsimp(1/sqrt(x))) == (sqrt(x), x) assert fraction(radsimp(1/sqrt(2*x + 3))) == (sqrt(2*x + 3), 2*x + 3) assert fraction(radsimp(1/sqrt(2*(x + 3)))) == (sqrt(2*x + 6), 2*x + 6) # issue 5994 e = S('-(2 + 2*sqrt(2) + 4*2**(1/4))/' '(1 + 2**(3/4) + 3*2**(1/4) + 3*sqrt(2))') assert radsimp(e).expand() == -2*2**(S(3)/4) - 2*2**(S(1)/4) + 2 + 2*sqrt(2) # issue 5986 (modifications to radimp didn't initially recognize this so # the test is included here) assert radsimp(1/(-sqrt(5)/2 - S(1)/2 + (-sqrt(5)/2 - S(1)/2)**2)) == 1 # from issue 5934 eq = ( (-240*sqrt(2)*sqrt(sqrt(5) + 5)*sqrt(8*sqrt(5) + 40) - 360*sqrt(2)*sqrt(-8*sqrt(5) + 40)*sqrt(-sqrt(5) + 5) - 120*sqrt(10)*sqrt(-8*sqrt(5) + 40)*sqrt(-sqrt(5) + 5) + 120*sqrt(2)*sqrt(-sqrt(5) + 5)*sqrt(8*sqrt(5) + 40) + 120*sqrt(2)*sqrt(-8*sqrt(5) + 40)*sqrt(sqrt(5) + 5) + 120*sqrt(10)*sqrt(-sqrt(5) + 5)*sqrt(8*sqrt(5) + 40) + 120*sqrt(10)*sqrt(-8*sqrt(5) + 40)*sqrt(sqrt(5) + 5))/(-36000 - 7200*sqrt(5) + (12*sqrt(10)*sqrt(sqrt(5) + 5) + 24*sqrt(10)*sqrt(-sqrt(5) + 5))**2)) assert radsimp(eq) is S.NaN # it's 0/0 # work with normal form e = 1/sqrt(sqrt(7)/7 + 2*sqrt(2) + 3*sqrt(3) + 5*sqrt(5)) + 3 assert radsimp(e) == ( -sqrt(sqrt(7) + 14*sqrt(2) + 21*sqrt(3) + 35*sqrt(5))*(-11654899*sqrt(35) - 1577436*sqrt(210) - 1278438*sqrt(15) - 1346996*sqrt(10) + 1635060*sqrt(6) + 5709765 + 7539830*sqrt(14) + 8291415*sqrt(21))/1300423175 + 3) # obey power rules base = sqrt(3) - sqrt(2) assert radsimp(1/base**3) == (sqrt(3) + sqrt(2))**3 assert radsimp(1/(-base)**3) == -(sqrt(2) + sqrt(3))**3 assert radsimp(1/(-base)**x) == (-base)**(-x) assert radsimp(1/base**x) == (sqrt(2) + sqrt(3))**x assert radsimp(root(1/(-1 - sqrt(2)), -x)) == (-1)**(-1/x)*(1 + sqrt(2))**(1/x) # recurse e = cos(1/(1 + sqrt(2))) assert radsimp(e) == cos(-sqrt(2) + 1) assert radsimp(e/2) == cos(-sqrt(2) + 1)/2 assert radsimp(1/e) == 1/cos(-sqrt(2) + 1) assert radsimp(2/e) == 2/cos(-sqrt(2) + 1) assert fraction(radsimp(e/sqrt(x))) == (sqrt(x)*cos(-sqrt(2)+1), x) # test that symbolic denominators are not processed r = 1 + sqrt(2) assert radsimp(x/r, symbolic=False) == -x*(-sqrt(2) + 1) assert radsimp(x/(y + r), symbolic=False) == x/(y + 1 + sqrt(2)) assert radsimp(x/(y + r)/r, symbolic=False) == \ -x*(-sqrt(2) + 1)/(y + 1 + sqrt(2)) # issue 7408 eq = sqrt(x)/sqrt(y) assert radsimp(eq) == umul(sqrt(x), sqrt(y), 1/y) assert radsimp(eq, symbolic=False) == eq # issue 7498 assert radsimp(sqrt(x)/sqrt(y)**3) == umul(sqrt(x), sqrt(y**3), 1/y**3) # for coverage eq = sqrt(x)/y**2 assert radsimp(eq) == eq
def eqSimp(e): return sp.fraction(e.together())[0]
L=sp.sympify(load(open('cache/L')),dict(zip([str(s) for s in syms],syms))) except IOError: L=getLagrangian(M,m2,0,0,alpha2,psi,A,verbose=True) dump(str(L),open('cache/L','w')) L=L.subs(ass) dofs=reduce(lambda a,b:a+b,[[f, f.diff(M.x[0])] for f in fields]) #list of fields and derivatives dummies=[sp.Dummy('d'+str(i)) for i in range(len(dofs))] Le=L.subs(A[2],0).subs(zip(dofs, dummies)[::-1]).subs(M.x[1],0).doit() Lfun=sp.lambdify([M.x[0]]+varParams+dummies, Le) print('Calculating equations of motion...') eqm=[fieldEqn(L,f,M.x).subs(A[2],0).doit().simplify() for f in fields[:2]] d=sp.Dummy() eqm.append(series(fieldEqn(L,A[2],M.x).subs(A[2],d*Axf).doit(),d).subs(d,1).doit().simplify()) oeqm=eqm=[sp.fraction(e.cancel())[0] for e in eqm] fields[2]=fieldsF[3](M.x[0]) del A print('Solving indicial equations...') try: ind=load(open('cache/indicial')) except IOError: sing=[0,1] #singular points to do expansion around ind=[indicial(eqm[:2],fields[:2], M.x[0], z0=s,verbose=True) for s in sing] #get solutions to indicial equation ind[1]=[i for i in ind[1] if i[1]>0] #remove solutions not satisfying z=1 BC for i in range(len(sing)): #some lousy code to first solve without A, and then add A. Because small A lim indn=[] for j in range(len(ind[i])): ind2=indicial([eqm[2].subs([(fields[fi],M.x[0]**ind[i][j][fi]) for fi in range(2)])], fields[2:], M.x[0], z0=sing[i],verbose=True)
def test_fraction(): x, y, z = map(Symbol, 'xyz') A = Symbol('A', commutative=False) assert fraction(Rational(1, 2)) == (1, 2) assert fraction(x) == (x, 1) assert fraction(1/x) == (1, x) assert fraction(x/y) == (x, y) assert fraction(x/2) == (x, 2) assert fraction(x*y/z) == (x*y, z) assert fraction(x/(y*z)) == (x, y*z) assert fraction(1/y**2) == (1, y**2) assert fraction(x/y**2) == (x, y**2) assert fraction((x**2+1)/y) == (x**2+1, y) assert fraction(x*(y+1)/y**7) == (x*(y+1), y**7) assert fraction(exp(-x), exact=True) == (exp(-x), 1) assert fraction(x*A/y) == (x*A, y) assert fraction(x*A**-1/y) == (x*A**-1, y)
""" import numpy as np from sympy import fraction, Rational from time import time start_time = time() ll = [] for a in xrange(10, 100): for b in xrange(a + 1, 100): sa = str(a) sb = str(b) a_set = set(list(sa)) b_set = set(list(sb)) if len(a_set) == 2 and len(b_set) == 2: unn = a_set & b_set if unn: if list(unn)[0] != str(0): dup = list(unn)[0] stripa = float(sa.strip(dup)) stripb = float(sb.strip(dup)) if stripb != 0. and stripa != 0.: diff = stripa / stripb if diff == float(a) / float(b): ll.append((a, b)) arr = np.array(ll) ans = fraction(Rational(arr.prod(axis=0)[0], arr.prod(axis=0)[1]))[1] running_time = time() elapsed_time = running_time - start_time print 'Total Execution time is ', elapsed_time, 'seconds'
def get_roots(expr): """Given the transfer function ``expr``, returns ``poles, zeros``. """ num, den = sympy.fraction(expr) return sympy.solve(den, s), sympy.solve(num, s)
def get_roots(expr): num, den = sympy.fraction(expr) return sympy.solve(den, s), sympy.solve(num, s)
def _eval_subs(self, old, new): from sympy import sign, multiplicity from sympy.simplify.simplify import powdenest, fraction if not old.is_Mul: return None if old.args[0] == -1: return self._subs(-old, -new) def base_exp(a): # if I and -1 are in a Mul, they get both end up with # a -1 base (see issue 3322); all we want here are the # true Pow or exp separated into base and exponent if a.is_Pow or a.func is C.exp: return a.as_base_exp() return a, S.One def breakup(eq): """break up powers of eq when treated as a Mul: b**(Rational*e) -> b**e, Rational commutatives come back as a dictionary {b**e: Rational} noncommutatives come back as a list [(b**e, Rational)] """ (c, nc) = (defaultdict(int), list()) for a in Mul.make_args(eq): a = powdenest(a) (b, e) = base_exp(a) if e is not S.One: (co, _) = e.as_coeff_mul() b = Pow(b, e/co) e = co if a.is_commutative: c[b] += e else: nc.append([b, e]) return (c, nc) def rejoin(b, co): """ Put rational back with exponent; in general this is not ok, but since we took it from the exponent for analysis, it's ok to put it back. """ (b, e) = base_exp(b) return Pow(b, e*co) def ndiv(a, b): """if b divides a in an extractive way (like 1/4 divides 1/2 but not vice versa, and 2/5 does not divide 1/3) then return the integer number of times it divides, else return 0. """ if not b.q % a.q or not a.q % b.q: return int(a/b) return 0 # give Muls in the denominator a chance to be changed (see issue 2552) # rv will be the default return value rv = None n, d = fraction(self) if d is not S.One: self2 = n._subs(old, new)/d._subs(old, new) if not self2.is_Mul: return self2._subs(old, new) if self2 != self: self = rv = self2 # Now continue with regular substitution. # handle the leading coefficient and use it to decide if anything # should even be started; we always know where to find the Rational # so it's a quick test co_self = self.args[0] co_old = old.args[0] co_xmul = None if co_old.is_Rational and co_self.is_Rational: # if coeffs are the same there will be no updating to do # below after breakup() step; so skip (and keep co_xmul=None) if co_old != co_self: co_xmul = co_self.extract_multiplicatively(co_old) elif co_old.is_Rational: return rv # break self and old into factors (c, nc) = breakup(self) (old_c, old_nc) = breakup(old) # update the coefficients if we had an extraction # e.g. if co_self were 2*(3/35*x)**2 and co_old = 3/5 # then co_self in c is replaced by (3/5)**2 and co_residual # is 2*(1/7)**2 if co_xmul and co_xmul.is_Rational: n_old, d_old = co_old.as_numer_denom() n_self, d_self = co_self.as_numer_denom() def _multiplicity(p, n): p = abs(p) if p is S.One: return S.Infinity return multiplicity(p, abs(n)) mult = S(min(_multiplicity(n_old, n_self), _multiplicity(d_old, d_self))) c.pop(co_self) c[co_old] = mult co_residual = co_self/co_old**mult else: co_residual = 1 # do quick tests to see if we can't succeed ok = True if len(old_nc) > len(nc): # more non-commutative terms ok = False elif len(old_c) > len(c): # more commutative terms ok = False elif set(i[0] for i in old_nc).difference(set(i[0] for i in nc)): # unmatched non-commutative bases ok = False elif set(old_c).difference(set(c)): # unmatched commutative terms ok = False elif any(sign(c[b]) != sign(old_c[b]) for b in old_c): # differences in sign ok = False if not ok: return rv if not old_c: cdid = None else: rat = [] for (b, old_e) in old_c.items(): c_e = c[b] rat.append(ndiv(c_e, old_e)) if not rat[-1]: return rv cdid = min(rat) if not old_nc: ncdid = None for i in range(len(nc)): nc[i] = rejoin(*nc[i]) else: ncdid = 0 # number of nc replacements we did take = len(old_nc) # how much to look at each time limit = cdid or S.Infinity # max number that we can take failed = [] # failed terms will need subs if other terms pass i = 0 while limit and i + take <= len(nc): hit = False # the bases must be equivalent in succession, and # the powers must be extractively compatible on the # first and last factor but equal inbetween. rat = [] for j in range(take): if nc[i + j][0] != old_nc[j][0]: break elif j == 0: rat.append(ndiv(nc[i + j][1], old_nc[j][1])) elif j == take - 1: rat.append(ndiv(nc[i + j][1], old_nc[j][1])) elif nc[i + j][1] != old_nc[j][1]: break else: rat.append(1) j += 1 else: ndo = min(rat) if ndo: if take == 1: if cdid: ndo = min(cdid, ndo) nc[i] = Pow(new, ndo)*rejoin(nc[i][0], nc[i][1] - ndo*old_nc[0][1]) else: ndo = 1 # the left residual l = rejoin(nc[i][0], nc[i][1] - ndo* old_nc[0][1]) # eliminate all middle terms mid = new # the right residual (which may be the same as the middle if take == 2) ir = i + take - 1 r = (nc[ir][0], nc[ir][1] - ndo* old_nc[-1][1]) if r[1]: if i + take < len(nc): nc[i:i + take] = [l*mid, r] else: r = rejoin(*r) nc[i:i + take] = [l*mid*r] else: # there was nothing left on the right nc[i:i + take] = [l*mid] limit -= ndo ncdid += ndo hit = True if not hit: # do the subs on this failing factor failed.append(i) i += 1 else: if not ncdid: return rv # although we didn't fail, certain nc terms may have # failed so we rebuild them after attempting a partial # subs on them failed.extend(range(i, len(nc))) for i in failed: nc[i] = rejoin(*nc[i]).subs(old, new) # rebuild the expression if cdid is None: do = ncdid elif ncdid is None: do = cdid else: do = min(ncdid, cdid) margs = [] for b in c: if b in old_c: # calculate the new exponent e = c[b] - old_c[b]*do margs.append(rejoin(b, e)) else: margs.append(rejoin(b.subs(old, new), c[b])) if cdid and not ncdid: # in case we are replacing commutative with non-commutative, # we want the new term to come at the front just like the # rest of this routine margs = [Pow(new, cdid)] + margs return co_residual*Mul(*margs)*Mul(*nc)
def test_fraction(): x, y, z = map(Symbol, 'xyz') A = Symbol('A', commutative=False) assert fraction(Rational(1, 2)) == (1, 2) assert fraction(x) == (x, 1) assert fraction(1/x) == (1, x) assert fraction(x/y) == (x, y) assert fraction(x/2) == (x, 2) assert fraction(x*y/z) == (x*y, z) assert fraction(x/(y*z)) == (x, y*z) assert fraction(1/y**2) == (1, y**2) assert fraction(x/y**2) == (x, y**2) assert fraction((x**2 + 1)/y) == (x**2 + 1, y) assert fraction(x*(y + 1)/y**7) == (x*(y + 1), y**7) assert fraction(exp(-x), exact=True) == (exp(-x), 1) assert fraction((1/(x + y))/2, exact=True) == (1, Mul(2,(x + y), evaluate=False)) assert fraction(x*A/y) == (x*A, y) assert fraction(x*A**-1/y) == (x*A**-1, y) n = symbols('n', negative=True) assert fraction(exp(n)) == (1, exp(-n)) assert fraction(exp(-n)) == (exp(-n), 1) p = symbols('p', positive=True) assert fraction(exp(-p)*log(p), exact=True) == (exp(-p)*log(p), 1)
# ## Code to exit script. Used for debugging. # sys.exit() # ## HcS_Bandstop = simplify(HcS_Bandstop) print 'HcS_Bandstop', HcS_Bandstop # HcW_Bandstop = HcS_Bandstop.subs(s,1j*2.0*pi*s) # plot(abs(HcW_Bandstop),(s,0,50)) # bilinear = 2.0*f_sampling*(1.0 - x)/(1.0 + x) bilinear = (1.0 - x)/(1.0 + x) Hz = HcS_Bandstop.subs(s, bilinear) Hz = simplify(Hz) Hz = cancel(Hz) print 'Hz: ', Hz # print 'Numerator: ', fraction(Hz)[0] # print 'Denominator: ', fraction(Hz)[1] ax = Poly(fraction(Hz)[0], x) # Separating out the numerator ax = ax.all_coeffs() # Array of size [(order of ax) + 1] with ax[0] being coeff of x^n ax = list(reversed(ax)) # Reversing it so that ax[0] is coeff of order x^0 ay = Poly(fraction(Hz)[1], x) # Separating out the denominator ay = ay.all_coeffs() ay = list(reversed(ay)) norm_fac = ay[0] ax = [i/norm_fac for i in ax] ay = [i/norm_fac for i in ay] # print 'Length of ax: ', len(ax) # print 'Length of ay: ', len(ay) # # ax[i] and ay[i] are the coefficients of x[n-i] and y[n-i] respectively in the difference equation. # The difference equation is implemented by the function 'filter' on any specified x[n] # print 'Coefficients of numerator: ', ay seq_len = 512 # 32768
def denom( f ): return fraction( f )[1]
def get_roots(expr): num, den = sympy.fraction(expr) s = sympy.Symbol('s', complex=True) return sympy.solve(den, s), sympy.solve(num, s)