Beispiel #1
0
 def arc_length_explain(self, start, stop, a_type = None,
                        explanation_type=None, preview = None):
     
     
     if a_type is None:
         a_type = self.a_type
         
     v = self.v_
     u = self.u
     
     start = sym.sympify(start)
     stop = sym.sympify(stop)
     
    
     if explanation_type is None:
         explanation_type = self.kwargs.get('explanation_type', 'simple')
     
     if preview is None:
         preview = self.kwargs.get('preview', False)  
    
     
     explanation = ArcLengthProb(path='arc_length/explanation', 
                 a_type = a_type, 
                 explanation_type = explanation_type,
                 preview = preview).explain()
                 
     explanation += """
         <p>
         For this problem the curve is $_C$_ is given by $_%s$_
         with the independent variable being $_%s$_ on the interval 
         $_[%s,%s]$_. So the arc length is
         $$s =\\int_{%s}^{%s} \sqrt{1+\\left(\\frac{d%s}{d%s}\\right)^2}\,d%s$$
         $$\\frac{d%s}{d%s} = %s = %s$$
         \\begin{align}
           \\sqrt{1 + \\left(%s\\right)^2} &= \\sqrt{%s} \\\\
             &= \sqrt{\\left(%s\\right)^2} = %s
         \\end{align}
         </p>
     """%tuple(map(lambda x: sym.latex(x).replace("\\log","\\ln"), 
                   [sym.Eq(v, self.v), u, start, stop, start, stop, 
                    v, u, u, v, u, 
                    self.Dv, self.dv, self.dv, 1 + (self.dv**2).expand(), 
                     self.ds, self.ds]))
     
     aa = [sym.latex(self.arc_length(start, stop,'integral')), 
           "\\left." + sym.latex(self.Ids).replace('\\log', '\\ln') +
           "\\right|_{%s=%s}^{%s=%s}"%(u, start, u, stop),
          sym.latex(self.arc_length(start, stop,'exact')).replace("\\log", "\\ln") + 
          '\\approx %.3f'%(self.arc_length(start, stop,'numeric'))]
     
     # Add self.numeric / self.anti 
     
     explanation += """
         <p>
         Thus the arclength is given by
         %s
         </p>
     """%(tools.align(*aa))
     #
     return explanation
Beispiel #2
0
    def __init__(self, name, unit_set):
        """
        Create a quantity in the given unit set. The name must be listed in the
        units_of_quantities dictionary."""
        self.name = name
        self.unit_set = unit_set

        self.unit_name = units_of_quantities[self.name]

        unit_expr = sm.sympify(self.unit_name)
        unit_expr = unit_expr.subs(derived_units)

        self.symbolic_value = sm.sympify(unit_expr)
        atoms = self.symbolic_value.atoms(sm.Symbol)
        self.def_units = [Unit(atom.name) for atom in atoms]

        self.def_names, self.def_units = self._get_dicts(self.def_units)
        self.names, self.units = self._get_dicts(self.unit_set)

        self.def_coef = float(self.symbolic_value.subs(self.def_names))

        coef_dict = {}
        for key, val in six.iteritems(self.def_units):
            coef_dict[val.name] = self.units[key].coef
        self.coef_dict = coef_dict
        
        self.raw_coef = float(self.symbolic_value.subs(self.coef_dict))
        self.coef = self.raw_coef / self.def_coef
Beispiel #3
0
def test_issue_7840():
    # daveknippers' example
    C393 = sympify( \
        'Piecewise((C391 - 1.65, C390 < 0.5), (Piecewise((C391 - 1.65, \
        C391 > 2.35), (C392, True)), True))'
    )
    C391 = sympify( \
        'Piecewise((2.05*C390**(-1.03), C390 < 0.5), (2.5*C390**(-0.625), True))'
    )
    C393 = C393.subs('C391',C391)
    # simple substitution
    sub = {}
    sub['C390'] = 0.703451854
    sub['C392'] = 1.01417794
    ss_answer = C393.subs(sub)
    # cse
    substitutions,new_eqn = cse(C393)
    for pair in substitutions:
        sub[pair[0].name] = pair[1].subs(sub)
    cse_answer = new_eqn[0].subs(sub)
    # both methods should be the same
    assert ss_answer == cse_answer

    # GitRay's example
    expr = sympify(
        "Piecewise((Symbol('ON'), Equality(Symbol('mode'), Symbol('ON'))), \
        (Piecewise((Piecewise((Symbol('OFF'), StrictLessThan(Symbol('x'), \
        Symbol('threshold'))), (Symbol('ON'), true)), Equality(Symbol('mode'), \
        Symbol('AUTO'))), (Symbol('OFF'), true)), true))"
    )
    substitutions, new_eqn = cse(expr)
    # this Piecewise should be exactly the same
    assert new_eqn[0] == expr
    # there should not be any replacements
    assert len(substitutions) < 1
Beispiel #4
0
 def arc_length(self, start, stop, q_type = None):
     """
     Parameters:
     ---------
     q_type:  string
         'exact', 'integral', 'numeric'
     start, stop: numeric/str
         These are the limits of integration
     """
     
     start = sym.sympify(start)
     stop = sym.sympify(stop)        
     
        
     
     if q_type is None:
         q_type = self.q_type        
     
     u = self.u
     I = sym.Integral(self.ds, (u, start, stop))
     
     if q_type == 'integral':
         return I
     elif q_type == 'exact':
         return I.doit()
     else:
         f = make_func(str(self.ds), func_params=(self.ind_var), func_type='numpy')
         value = mp.quad(f, [float(start.evalf()), float(stop.evalf())])
         return value
Beispiel #5
0
def test_product_basic():
    H, T = 'H', 'T'
    unit_line = Interval(0, 1)
    d6 = FiniteSet(1, 2, 3, 4, 5, 6)
    d4 = FiniteSet(1, 2, 3, 4)
    coin = FiniteSet(H, T)

    square = unit_line * unit_line

    assert (0, 0) in square
    assert 0 not in square
    assert (H, T) in coin ** 2
    assert (.5, .5, .5) in square * unit_line
    assert (H, 3, 3) in coin * d6* d6
    HH, TT = sympify(H), sympify(T)
    assert set(coin**2) == set(((HH, HH), (HH, TT), (TT, HH), (TT, TT)))

    assert (d4*d4).is_subset(d6*d6)

    assert square.complement(Interval(-oo, oo)*Interval(-oo, oo)) == Union(
        (Interval(-oo, 0, True, True) +
         Interval(1, oo, True, True))*Interval(-oo, oo),
         Interval(-oo, oo)*(Interval(-oo, 0, True, True) +
                  Interval(1, oo, True, True)))

    assert (Interval(-5, 5)**3).is_subset(Interval(-10, 10)**3)
    assert not (Interval(-10, 10)**3).is_subset(Interval(-5, 5)**3)
    assert not (Interval(-5, 5)**2).is_subset(Interval(-10, 10)**3)

    assert (Interval(.2, .5)*FiniteSet(.5)).is_subset(square)  # segment in square

    assert len(coin*coin*coin) == 8
    assert len(S.EmptySet*S.EmptySet) == 0
    assert len(S.EmptySet*coin) == 0
    raises(TypeError, lambda: len(coin*Interval(0, 2)))
def higher_order_diff(eqs, syms, order=2):
    '''Takes higher order derivatives of a list of equations w.r.t a list of paramters'''

    import numpy

    eqs = list([sympy.sympify(eq) for eq in eqs])
    syms = list([sympy.sympify(s) for s in syms])

    neq = len(eqs)
    p = len(syms)

    D = [numpy.array(eqs)]
    orders = []

    for i in range(1,order+1):

        par = D[i-1]
        mat = numpy.empty([neq] + [p]*i, dtype=object)   #.append( numpy.zeros(orders))
        for ind in non_decreasing_series(p,i):

            ind_parent = ind[:-1]
            k = ind[-1]

            for line in range(neq):

                ii = [line] + ind
                iid = [line] + ind_parent
                eeq = par[ tuple(iid) ]
                mat[tuple(ii)] = eeq.diff(syms[k])

        D.append(mat)

    return D
Beispiel #7
0
def test_nsimplify():
    x = Symbol("x")
    assert nsimplify(0) == 0
    assert nsimplify(-1) == -1
    assert nsimplify(1) == 1
    assert nsimplify(1+x) == 1+x
    assert nsimplify(2.7) == Rational(27, 10)
    assert nsimplify(1-GoldenRatio) == (1-sqrt(5))/2
    assert nsimplify((1+sqrt(5))/4, [GoldenRatio]) == GoldenRatio/2
    assert nsimplify(2/GoldenRatio, [GoldenRatio]) == 2*GoldenRatio - 2
    assert nsimplify(exp(5*pi*I/3, evaluate=False)) == sympify('1/2 - sqrt(3)*I/2')
    assert nsimplify(sin(3*pi/5, evaluate=False)) == sympify('sqrt(sqrt(5)/8 + 5/8)')
    assert nsimplify(sqrt(atan('1', evaluate=False))*(2+I), [pi]) == sqrt(pi) + sqrt(pi)/2*I
    assert nsimplify(2 + exp(2*atan('1/4')*I)) == sympify('49/17 + 8*I/17')
    assert nsimplify(pi, tolerance=0.01) == Rational(22, 7)
    assert nsimplify(pi, tolerance=0.001) == Rational(355, 113)
    assert nsimplify(0.33333, tolerance=1e-4) == Rational(1, 3)
    assert nsimplify(2.0**(1/3.), tolerance=0.001) == Rational(635, 504)
    assert nsimplify(2.0**(1/3.), tolerance=0.001, full=True) == 2**Rational(1, 3)
    assert nsimplify(x + .5, rational=True) == Rational(1, 2) + x
    assert nsimplify(1/.3 + x, rational=True) == Rational(10, 3) + x
    assert nsimplify(log(3).n(), rational=True) == \
           sympify('109861228866811/100000000000000')
    assert nsimplify(Float(0.272198261287950), [pi,log(2)]) == pi*log(2)/8
    assert nsimplify(Float(0.272198261287950).n(3), [pi,log(2)]) == \
        -pi/4 - log(2) + S(7)/4
    assert nsimplify(x/7.0) == x/7
    assert nsimplify(pi/1e2) == pi/100
    assert nsimplify(pi/1e2, rational=False) == pi/100.0
    assert nsimplify(pi/1e-7) == 10000000*pi
Beispiel #8
0
def _minpoly_exp(ex, x):
    """
    Returns the minimal polynomial of ``exp(ex)``
    """
    c, a = ex.args[0].as_coeff_Mul()
    p = sympify(c.p)
    q = sympify(c.q)
    if a == I*pi:
        if c.is_rational:
            if c.p == 1 or c.p == -1:
                if q == 3:
                    return x**2 - x + 1
                if q == 4:
                    return x**4 + 1
                if q == 6:
                    return x**4 - x**2 + 1
                if q == 8:
                    return x**8 + 1
                if q == 9:
                    return x**6 - x**3 + 1
                if q == 10:
                    return x**8 - x**6 + x**4 - x**2 + 1
                if q.is_prime:
                    s = 0
                    for i in range(q):
                        s += (-x)**i
                    return s

            # x**(2*q) = product(factors)
            factors = [cyclotomic_poly(i, x) for i in divisors(2*q)]
            mp = _choose_factor(factors, x, ex)
            return mp
        else:
            raise NotAlgebraic("%s doesn't seem to be an algebraic element" % ex)
    raise NotAlgebraic("%s doesn't seem to be an algebraic element" % ex)
Beispiel #9
0
def field_isomorphism(a, b, **args):
    """Construct an isomorphism between two number fields. """
    a, b = sympify(a), sympify(b)

    if not a.is_AlgebraicNumber:
        a = AlgebraicNumber(a)

    if not b.is_AlgebraicNumber:
        b = AlgebraicNumber(b)

    if a == b:
        return a.coeffs()

    n = a.minpoly.degree()
    m = b.minpoly.degree()

    if n == 1:
        return [a.root]

    if m % n != 0:
        return None

    if args.get('fast', True):
        try:
            result = field_isomorphism_pslq(a, b)

            if result is not None:
                return result
        except NotImplementedError:
            pass

    return field_isomorphism_factor(a, b)
Beispiel #10
0
def _divide_constriant(s, symbols, cons_index, cons_dict, cons_import):
    # Creates a CustomConstraint of the form `CustomConstraint(lambda a, x: FreeQ(a, x))`
    lambda_symbols = list(set(get_free_symbols(s, symbols, [])))
    r = generate_sympy_from_parsed(s)
    r = sympify(r, locals={"Or": Function("Or"), "And": Function("And"), "Not":Function("Not")})
    if r.has(Function('MatchQ')):
        match_res = set_matchq_in_constraint(s, cons_index)
        res = match_res[1]
        res += '\n        return {}'.format(rubi_printer(sympify(generate_sympy_from_parsed(match_res[0]), locals={"Or": Function("Or"), "And": Function("And"), "Not":Function("Not")}), sympy_integers = True))

    elif contains_diff_return_type(s):
        res = '        try:\n            return {}\n        except (TypeError, AttributeError):\n            return False'.format(rubi_printer(r, sympy_integers=True))
    else:
        res = '        return {}'.format(rubi_printer(r, sympy_integers=True))

    # First it checks if a constraint is already present in `cons_dict`, If yes, use it else create a new one.
    if not res in cons_dict.values():
        cons_index += 1
        cons = '\n    def cons_f{}({}):\n'.format(cons_index, ', '.join(lambda_symbols))
        if 'x' in lambda_symbols:
            cons += '        if isinstance(x, (int, Integer, float, Float)):\n            return False\n'
        cons += res
        cons += '\n\n    cons{} = CustomConstraint({})\n'.format(cons_index, 'cons_f{}'.format(cons_index))
        cons_name = 'cons{}'.format(cons_index)
        cons_dict[cons_name] = res
    else:
        cons = ''
        cons_name = next(key for key, value in cons_dict.items() if value == res)

    if cons_name not in cons_import:
        cons_import.append(cons_name)
    return (cons_name, cons, cons_index)
Beispiel #11
0
def test_product_basic():
    H,T = 'H', 'T'
    unit_line = Interval(0,1)
    d6 = FiniteSet(1,2,3,4,5,6)
    d4 = FiniteSet(1,2,3,4)
    coin = FiniteSet(H, T)

    square = unit_line * unit_line

    assert (0,0) in square
    assert 0 not in square
    assert (H, T) in coin ** 2
    assert (.5,.5,.5) in square * unit_line
    assert (H, 3, 3) in coin * d6* d6
    HH, TT = sympify(H), sympify(T)
    assert set(coin**2) == set(((HH, HH), (HH, TT), (TT, HH), (TT, TT)))

    assert (d6*d6).subset(d4*d4)

    inf, neginf = S.Infinity, S.NegativeInfinity
    assert square.complement == Union(
       Interval(0,1) * (Interval(neginf,0,True,True)+Interval(1,inf,True,True)),
       (Interval(neginf,0,True,True)+Interval(1,inf,True,True))*Interval(0,1),
       ((Interval(neginf,0,True,True) + Interval(1,inf, True, True))
                * (Interval(neginf,0,True,True) + Interval(1,inf, True,True))))

    assert (Interval(-10,10)**3).subset(Interval(-5,5)**3)
    assert not (Interval(-5,5)**3).subset(Interval(-10,10)**3)
    assert not (Interval(-10,10)**2).subset(Interval(-5,5)**3)

    assert square.subset(Interval(.2,.5)*FiniteSet(.5)) # segment in square
Beispiel #12
0
def transverse_magnification(si, so):
    """

    Calculates the transverse magnification, which is the ratio of the
    image size to the object size.

    Parameters
    ==========
    so: sympifiable
    Lens-object distance

    si: sympifiable
    Lens-image distance

    Example
    =======
    >>> from sympy.physics.optics import transverse_magnification
    >>> transverse_magnification(30, 15)
    -2

    """

    si = sympify(si)
    so = sympify(so)

    return (-(si/so))
Beispiel #13
0
 def check_output(self, want, got, optionflags):
     if IGNORE_OUTPUT & optionflags:
         return True
     # When writing tests we sometimes want to assure ourselves that the
     # results are _not_ equal
     wanted_tf = not (NOT_EQUAL & optionflags)
     # Strip dtype
     if IGNORE_DTYPE & optionflags:
         want = ignore_dtype(want)
         got = ignore_dtype(got)
     # Strip array repr from got and want if requested
     if STRIP_ARRAY_REPR & optionflags:
         # STRIP_ARRAY_REPR only matches for a line containing *only* an
         # array repr.  Use IGNORE_DTYPE to ignore a dtype specifier embedded
         # within a more complex line.
         want = strip_array_repr(want)
         got = strip_array_repr(got)
     # If testing floating point, round to required number of digits
     if optionflags & (FP_4DP | FP_6DP):
         if optionflags & FP_4DP:
             dp = 4
         elif optionflags & FP_6DP:
             dp = 6
         want = round_numbers(want, dp)
         got = round_numbers(got, dp)
     # Are the strings equal when run through sympy?
     if SYMPY_EQUAL & optionflags:
         from sympy import sympify
         res = sympify(want) == sympify(got)
         return res == wanted_tf
     # Pass tests through two-pass numpy checker
     res = NumpyOutputChecker.check_output(self, want, got, optionflags)
     # Return True if we wanted True and got True, or if we wanted False and
     # got False
     return res == wanted_tf
Beispiel #14
0
    def _generic_mul(q1, q2):

        q1 = sympify(q1)
        q2 = sympify(q2)

        # None is a Quaternion:
        if not isinstance(q1, Quaternion) and not isinstance(q2, Quaternion):
            return q1 * q2

        # If q1 is a number or a sympy expression instead of a quaternion
        if not isinstance(q1, Quaternion):
            if q2.real_field:
                if q1.is_complex:
                    return q2 * Quaternion(re(q1), im(q1), 0, 0)
                else:
                    return Mul(q1, q2)
            else:
                return Quaternion(q1 * q2.a, q1 * q2.b, q1 * q2.c, q1 * q2.d)


        # If q2 is a number or a sympy expression instead of a quaternion
        if not isinstance(q2, Quaternion):
            if q1.real_field:
                if q2.is_complex:
                    return q1 * Quaternion(re(q2), im(q2), 0, 0)
                else:
                    return Mul(q1, q2)
            else:
                return Quaternion(q2 * q1.a, q2 * q1.b, q2 * q1.c, q2 * q1.d)

        return Quaternion(-q1.b*q2.b - q1.c*q2.c - q1.d*q2.d + q1.a*q2.a,
                          q1.b*q2.a + q1.c*q2.d - q1.d*q2.c + q1.a*q2.b,
                          -q1.b*q2.d + q1.c*q2.a + q1.d*q2.b + q1.a*q2.c,
                          q1.b*q2.c - q1.c*q2.b + q1.d*q2.a + q1.a * q2.d)
Beispiel #15
0
def hyperfocal_distance(f, N, c):
    """

    Parameters
    ==========
    f: sympifiable
    Focal length of a given lens

    N: sympifiable
    F-number of a given lens

    c: sympifiable
    Circle of Confusion (CoC) of a given image format

    Example
    =======
    >>> from sympy.physics.optics import hyperfocal_distance
    >>> from sympy.abc import f, N, c
    >>> round(hyperfocal_distance(f = 0.5, N = 8, c = 0.0033), 2)
    9.47
    """

    f = sympify(f)
    N = sympify(N)
    c = sympify(c)

    return (1/(N * c))*(f**2)
 def __init__(
         self,
         amplitude,
         frequency=None,
         phase=S.Zero,
         time_period=None,
         n=Symbol('n')):
     frequency = sympify(frequency)
     amplitude = sympify(amplitude)
     phase = sympify(phase)
     time_period = sympify(time_period)
     n = sympify(n)
     self._frequency = frequency
     self._amplitude = amplitude
     self._phase = phase
     self._time_period = time_period
     self._n = n
     if time_period is not None:
         self._frequency = 1/self._time_period
     if frequency is not None:
         self._time_period = 1/self._frequency
         if time_period is not None:
             if frequency != 1/time_period:
                 raise ValueError("frequency and time_period should be consistent.")
     if frequency is None and time_period is None:
         raise ValueError("Either frequency or time period is needed.")
Beispiel #17
0
def declare_functions():
    
    Expression("create_preMPF", sympify("k9/(1 + k31*OBS_p53)"))
    Expression("Hill_Mdm2", sympify("k24*OBS_Int^n / (k_m^n + OBS_Int^n)"))
    Expression("create_intermediate", sympify("k27*OBS_p53/ (1 + k26*OBS_p53*OBS_Mdm2)"))
    Expression("sig_deg", sympify("Deg_0 - k_deg*(signal-signal_damp)"))
    Expression("kdamp_DDS0", sympify("k_damp*DDS_0"))
Beispiel #18
0
def brewster_angle(medium1, medium2):
    """
    This function calculates the Brewster's angle of incidence to Medium 2 from
    Medium 1 in radians.

    Parameters
    ==========

    medium 1 : Medium or sympifiable
        Refractive index of Medium 1
    medium 2 : Medium or sympifiable
        Refractive index of Medium 1

    Examples
    ========

    >>> from sympy.physics.optics import brewster_angle
    >>> brewster_angle(1, 1.33)
    0.926093295503462

    """

    if isinstance(medium1, Medium):
        n1 = medium1.refractive_index
    else:
        n1 = sympify(medium1)

    if isinstance(medium2, Medium):
        n2 = medium2.refractive_index
    else:
        n2 = sympify(medium2)

    return atan2(n2, n1)
Beispiel #19
0
def eval_graph(evaluator, variable):
    from sympy.plotting.plot import LineOver1DRangeSeries
    func = evaluator.eval("input_evaluated")

    free_symbols = sympy.sympify(func).free_symbols
    if len(free_symbols) != 1 or variable not in free_symbols:
        raise ValueError("Cannot graph function of multiple variables")

    try:
        series = LineOver1DRangeSeries(func, (variable, -10, 10), nb_of_points=200)
        # returns a list of [[x,y], [next_x, next_y]] pairs
        series = series.get_segments()
    except TypeError:
        raise ValueError("Cannot graph function")

    xvalues = []
    yvalues = []
    for point in series:
        xvalues.append(point[0][0])
        yvalues.append(point[0][1])
    xvalues.append(series[-1][1][0])
    yvalues.append(series[-1][1][1])
    return {
        'function': sympy.jscode(sympy.sympify(func)),
        'variable': repr(variable),
        'xvalues': json.dumps(xvalues),
        'yvalues': json.dumps(yvalues)
    }
def daubechis(N):
	# make polynomial
	q_y = [sm.binomial(N-1+k,k) for k in reversed(range(N))]

	# get polynomial roots y[k]
	y = sm.mp.polyroots(q_y, maxsteps=200, extraprec=64)

	z = []
	for yk in y:
		# subustitute y = -1/4z + 1/2 - 1/4/z to factor f(y) = y - y[k]
		f = [sm.mpf('-1/4'), sm.mpf('1/2') - yk, sm.mpf('-1/4')]

		# get polynomial roots z[k]
		z += sm.mp.polyroots(f)

	# make polynomial using the roots within unit circle
	h0z = sm.sqrt('2')
	for zk in z:
		if sm.fabs(zk) < 1:
			h0z *= sympy.sympify('(z-zk)/(1-zk)').subs('zk',zk)

	# adapt vanising moments
	hz = (sympy.sympify('(1+z)/2')**N*h0z).expand()

	# get scaling coefficients
	return [sympy.re(hz.coeff('z',k)) for k in reversed(range(N*2))]
 def __init__(self, cu,cv,la,mu):
   x, y = sympy.symbols('x y')
   self.cu=cu
   self.cv=cv
   self.L=la
   self.M=mu
   self.u=sympy.sympify(cu)
   self.v=sympy.sympify(cv)
   self.fu=eval("lambda x,y: numpy.array(["+cu[0]+","+cu[1]+"])")
   self.fv=eval("lambda x,y: numpy.array(["+cv[0]+","+cv[1]+"])")
   if self.u[0].is_polynomial(x,y) and self.u[1].is_polynomial(x,y):
     D0=sympy.polys.Poly(self.u[0],x,y).as_dict()
     D1=sympy.polys.Poly(self.u[1],x,y).as_dict()
     self.du=max(max(numpy.sum(list(D0.keys()),axis=1)),max(numpy.sum(list(D1.keys()),axis=1)))
   else:
     self.du=-1
   if self.v[0].is_polynomial(x,y) and self.v[1].is_polynomial(x,y):
     D0=sympy.polys.Poly(self.v[0],x,y).as_dict()
     D1=sympy.polys.Poly(self.v[1],x,y).as_dict()
     self.dv=max(max(numpy.sum(list(D0.keys()),axis=1)),max(numpy.sum(list(D1.keys()),axis=1)))
   else:
     self.dv=-1
   H=Hooke(self.L,self.M)
   gU=Gamma(self.u)
   gV=Gamma(self.v)
   self.I=sympy.integrate(sympy.integrate(gV.T*H*gU,(x,0,1)),(y,0,1))[0,0]
Beispiel #22
0
 def test_anonymous_expression_operators(self):
     result = Expression('a + b')  # Arbitrary starting expression
     expr_iter = cycle(anonymous_expressions)
     for op in self.ops:
         if op in uniary_ops:
             ss_result = op(result.rhs)
             ee_result = op(result)
             op_str = ("{}({})".format(op.__name__, result))
         else:
             expr = next(expr_iter)
             if op in div_ops and expr.rhs == sympify(0.0):
                 expr = sympify(0.1)
             ss_result = op(result.rhs, expr.rhs)
             ee_result = op(result, expr)
             es_result = op(result, expr.rhs)
             se_result = op(result.rhs, expr)
             op_str = ("{}({}, {})".format(op.__name__, result, expr))
             self.assertEqual(
                 es_result, ss_result,
                 op_str + " not equal between Expression and sympy")
             self.assertEqual(
                 se_result, ss_result,
                 "{} not equal between Expression ({}) and sympy ({})"
                 .format(op_str, se_result, ss_result))
             self.assertIsInstance(es_result, SympyBaseClass,
                                   op_str + " did not return a Expression")
             self.assertIsInstance(se_result, SympyBaseClass,
                                   op_str + " did not return a Expression")
         self.assertEqual(
             ee_result, ss_result,
             "{} not equal between Expression ({}) and sympy ({})"
             .format(op_str, ee_result, ss_result))
         self.assertIsInstance(ee_result, SympyBaseClass,
                               op_str + " did not return a Expression")
         result = Expression(ee_result)
Beispiel #23
0
def sympify(arg, real=False, positive=None, cache=True):
    """Create a sympy expression."""

    if isinstance(arg, (sym.symbol.Symbol, sym.symbol.Expr)):
        return arg

    # Why doesn't sympy do this?
    if isinstance(arg, complex):
        re = sym.sympify(arg.real, rational=True)
        im = sym.sympify(arg.imag, rational=True)
        if im == 1.0:
            arg = re + sym.I
        else:
            arg = re + sym.I * im
        return arg

    if isinstance(arg, str):
        # Sympy considers E1 to be the generalized exponential integral.
        # N is for numerical evaluation.
        if symbol_pattern.match(arg) is not None:
            return symbol(arg, real=real, positive=positive, cache=cache)

        match = symbol_pattern2.match(arg)
        if match is not None:
            # Convert R_{out} to R_out for sympy to recognise.
            arg = match.groups()[0] + match.groups()[1]
            return symbol(arg, real=True)

        # Perhaps have dictionary of functions and their replacements?
        arg = arg.replace('u(t', 'Heaviside(t')
        arg = arg.replace('delta(t', 'DiracDelta(t')

    return sym.sympify(arg, rational=True, locals=symbols)
Beispiel #24
0
    def __new__(cls, q0, q1, q2, q3):
        q0 = sympify(q0)
        q1 = sympify(q1)
        q2 = sympify(q2)
        q3 = sympify(q3)
        parent_orient = (Matrix([[q0 ** 2 + q1 ** 2 - q2 ** 2 -
                                  q3 ** 2,
                                  2 * (q1 * q2 - q0 * q3),
                                  2 * (q0 * q2 + q1 * q3)],
                                 [2 * (q1 * q2 + q0 * q3),
                                  q0 ** 2 - q1 ** 2 +
                                  q2 ** 2 - q3 ** 2,
                                  2 * (q2 * q3 - q0 * q1)],
                                 [2 * (q1 * q3 - q0 * q2),
                                  2 * (q0 * q1 + q2 * q3),
                                  q0 ** 2 - q1 ** 2 -
                                  q2 ** 2 + q3 ** 2]]))
        parent_orient = parent_orient.T

        obj = super(QuaternionOrienter, cls).__new__(cls, q0, q1, q2, q3)
        obj._q0 = q0
        obj._q1 = q1
        obj._q2 = q2
        obj._q3 = q3
        obj._parent_orient = parent_orient

        return obj
Beispiel #25
0
def Ruvws_from_file(filePath):
    """
    Generates nested lists where each list entry contains a again a list.
    The first entry is the Ruvw vector and the second is a list which contains all variables names that have this Ruvw vector.
    Input file must be formatted like:
    0,0,0
    variableName
    variableName
    filePath ... string location to the file which conatins the Ruvw relations
    returns ... list[np.array,list[string]] the information on all Ruvws
    """
    with open(filePath) as file:
        content = file.readlines()
    allRuvw = []
    entries = []
    r = None

    for line in content:
        if ',' in line:
            allRuvw.append([r,entries]) # if it is the first occurence, a dummy entry will be generated
            # Parsing Ruvw
            r = line.split(',')
            r = np.array([sp.sympify(r[0]).evalf(), sp.sympify(r[1]).evalf(), sp.sympify(r[2]).evalf()])
            entries = []
        else:
            entries.append(line.strip())
    # applying the last entry
    allRuvw.append([r,entries])

    del allRuvw[0] # first one is a dummy entry
    return allRuvw
def get_gamma_keq_terms(mod, sympy_terms):
    model_map = pysces.ModelMap(mod)  # model map to get substrates, products
    # and parameters for each reaction

    messages = {}
    gamma_keq_terms = {}
    for name, terms in sympy_terms.iteritems():
        reaction_map = getattr(model_map, name)

        substrates = [sympify(substrate) for substrate in
                      reaction_map.hasSubstrates()]

        products = [sympify(product) for product in reaction_map.hasProducts()]

        if len(terms) == 2:  # condition for reversible reactions
            # make sure negative term is second in term list
            terms = sort_terms(terms)
            # divide pos term by neg term and factorise
            expressions = (-terms[0] / terms[1]).factor()
            # get substrate, product and keq terms (and strategy)
            st, pt, keq, _ = get_st_pt_keq(expressions, substrates,
                                                 products)
            if all([st, pt, keq]):
                gamma_keq_terms[name] = pt / (keq*st)
                messages[name] = 'successful generation of gamma/keq term'
            else:
                messages[name] = 'generation of gamma/keq term failed'

    return gamma_keq_terms, messages
 def __init__(self, name=None, mult=None, num=None, den=None, repeats=None):
     if mult == 1:
         mult = '1'
     if den == 1: 
         den = '1'
     if num == 1:
         num = '1'
     self.den = den
     self.mult = mult
     self.num = num
     self.name = name
     self.denvariables = sorted(set(re.findall(FINDVARIABLES, den)))
     self.numvariables = sorted(set(re.findall(FINDVARIABLES, num)))
     self.denominator_eq = sympy.sympify(den)
     self.numerator_eq = sympy.sympify(num)
     self.denominator = sympy.lambdify(self.denvariables, self.denominator_eq)
     self.numerator = sympy.lambdify(self.numvariables, self.numerator_eq)
     self.repeats = None
     if type(mult) == list:
         self.multvariables = sorted(set([variable for x in self.mult for variable in x.variables]))
         self.multiplier_eq = [str(x) for x in self.mult]
         self.multiplier = mult
     else:
         self.multvariables = sorted(set(re.findall(FINDVARIABLES, mult)))
         self.multiplier_eq = sympy.sympify(mult)
         self.multiplier = sympy.lambdify(self.multvariables, self.multiplier_eq)
     self.variables = self.denvariables + self.numvariables + self.multvariables
Beispiel #28
0
def get_sympified(instance):
    if hasattr(instance, 'iteritems'):
	return dict([(k,sympify(v)) for k,v in instance.iteritems()])
    elif hasattr(instance, '__iter__'):
	return [sympify(x) for x in instance]
    else:
	NotImplemented
Beispiel #29
0
def arctan_rule(integral):
    integrand, symbol = integral
    base, exp = integrand.as_base_exp()

    if sympy.simplify(exp + 1) == 0:
        a = sympy.Wild('a', exclude=[symbol])
        b = sympy.Wild('b', exclude=[symbol])
        match = base.match(a + b*symbol**2)
        if match:
            a, b = match[a], match[b]
            if ((isinstance(a, sympy.Number) and a < 0) or (isinstance(b, sympy.Number) and b < 0)):
                return
            if (sympy.ask(sympy.Q.negative(a) | sympy.Q.negative(b) | sympy.Q.is_true(a <= 0) | sympy.Q.is_true(b <= 0))):
                return
            #   /    dx       1  /   dx             1   /     dx                |                     |    1     1         /   du
            #  | --------- = -- | -------------- = --  | -------------------- = | sqrt(b/a)x = u      | =  -- ----------  | -------
            # /  a + bx^2    a /   1  + (b/a)x^2   a  /   1 + (sqrt(b/a)x)^2    | dx = du / sqrt(b/a) |    a   sqrt(b/a) /  1 + u^2
            if a == 1 and b == 1:
                return ArctanRule(integrand, symbol)
            if a == b:
                    constant = 1 / a
                    integrand_ = 1 / (1 + symbol**2)
                    substep = ArctanRule(integrand_, symbol)
                    return ConstantTimesRule(constant, integrand_, substep, integrand, symbol)
            u_var = new_symbol_(symbol)
            u_func = sympy.sqrt(sympy.sympify(b) / a) * symbol
            integrand_ = 1 / (1 + u_func**2)
            constant = 1 / sympy.sqrt(sympy.sympify(b) / a)
            substituted = 1 / (1 + u_var**2)
            substep = ArctanRule(substituted, u_var)
            substep = ConstantTimesRule(constant, substituted, substep, constant*substituted, u_var)
            substep = URule(u_var, u_func, constant, substep, constant*substituted, integrand_, symbol)
            return ConstantTimesRule(1/a, integrand_, substep, integrand, symbol)
def Conditional(cond, true_value, false_value):
    """
    Declares a conditional

    Arguments
    ---------
    cond : A conditional
        The conditional which should be evaluated
    true_value : Any model expression
        Model expression for a true evaluation of the conditional
    false_value : Any model expression
        Model expression for a false evaluation of the conditional
    """
    cond = sp.sympify(cond)

    from sympy.core.relational import Equality, Relational
    from sympy.logic.boolalg import Boolean

    # If the conditional is a bool it is already evaluated
    if isinstance(cond, bool):
        return true_value if cond else false_value

    if not isinstance(cond, (Relational, Boolean)):
        raise type_error("Cond %s is of type %s, but must be a Relational" \
                         " or Boolean." % (cond, type(cond)))

    return sp.functions.Piecewise((true_value, cond), (false_value, sp.sympify(True)),
                                  evaluate=True)
Beispiel #31
0
def NS(e, n=15, **options):
    return sstr(sympify(e).evalf(n, **options), full_prec=True)
Beispiel #32
0
    def _generic_mul(q1, q2):
        """Generic multiplication.

        Parameters
        ==========

        q1 : Quaternion or symbol
        q2 : Quaternion or symbol

        It's important to note that if neither q1 nor q2 is a Quaternion,
        this function simply returns q1 * q2.

        Returns
        =======

        Quaternion
            The resultant quaternion after multiplying q1 and q2

        Examples
        ========

        >>> from sympy.algebras.quaternion import Quaternion
        >>> from sympy import Symbol
        >>> q1 = Quaternion(1, 2, 3, 4)
        >>> q2 = Quaternion(5, 6, 7, 8)
        >>> Quaternion._generic_mul(q1, q2)
        (-60) + 12*i + 30*j + 24*k
        >>> Quaternion._generic_mul(q1, 2)
        2 + 4*i + 6*j + 8*k
        >>> x = Symbol('x', real = True)
        >>> Quaternion._generic_mul(q1, x)
        x + 2*x*i + 3*x*j + 4*x*k

        Quaternions over complex fields :

        >>> from sympy.algebras.quaternion import Quaternion
        >>> from sympy import I
        >>> q3 = Quaternion(3 + 4*I, 2 + 5*I, 0, 7 + 8*I, real_field = False)
        >>> Quaternion._generic_mul(q3, 2 + 3*I)
        (2 + 3*I)*(3 + 4*I) + (2 + 3*I)*(2 + 5*I)*i + 0*j + (2 + 3*I)*(7 + 8*I)*k
        """
        q1 = sympify(q1)
        q2 = sympify(q2)

        # None is a Quaternion:
        if not isinstance(q1, Quaternion) and not isinstance(q2, Quaternion):
            return q1 * q2

        # If q1 is a number or a sympy expression instead of a quaternion
        if not isinstance(q1, Quaternion):
            if q2.real_field and q1.is_complex:
                return Quaternion(re(q1), im(q1), 0, 0) * q2
            elif q1.is_commutative:
                return Quaternion(q1 * q2.a, q1 * q2.b, q1 * q2.c, q1 * q2.d)
            else:
                raise ValueError(
                    "Only commutative expressions can be multiplied with a Quaternion."
                )

        # If q2 is a number or a sympy expression instead of a quaternion
        if not isinstance(q2, Quaternion):
            if q1.real_field and q2.is_complex:
                return q1 * Quaternion(re(q2), im(q2), 0, 0)
            elif q2.is_commutative:
                return Quaternion(q2 * q1.a, q2 * q1.b, q2 * q1.c, q2 * q1.d)
            else:
                raise ValueError(
                    "Only commutative expressions can be multiplied with a Quaternion."
                )

        return Quaternion(
            -q1.b * q2.b - q1.c * q2.c - q1.d * q2.d + q1.a * q2.a,
            q1.b * q2.a + q1.c * q2.d - q1.d * q2.c + q1.a * q2.b,
            -q1.b * q2.d + q1.c * q2.a + q1.d * q2.b + q1.a * q2.c,
            q1.b * q2.c - q1.c * q2.b + q1.d * q2.a + q1.a * q2.d)
Beispiel #33
0
 def __rtruediv__(self, other):
     return sympify(other) * self**-1
Beispiel #34
0
 def __truediv__(self, other):
     return self * sympify(other)**-1
Beispiel #35
0
def test_issue_9448():
    tmp = sympify(
        "1/(1 - (-1)**(2/3) - (-1)**(1/3)) + 1/(1 + (-1)**(2/3) + (-1)**(1/3))"
    )
    assert nsimplify(tmp) == S.Half
Beispiel #36
0
def test_nsimplify():
    x = Symbol("x")
    assert nsimplify(0) == 0
    assert nsimplify(-1) == -1
    assert nsimplify(1) == 1
    assert nsimplify(1 + x) == 1 + x
    assert nsimplify(2.7) == Rational(27, 10)
    assert nsimplify(1 - GoldenRatio) == (1 - sqrt(5)) / 2
    assert nsimplify((1 + sqrt(5)) / 4, [GoldenRatio]) == GoldenRatio / 2
    assert nsimplify(2 / GoldenRatio, [GoldenRatio]) == 2 * GoldenRatio - 2
    assert nsimplify(exp(pi*I*Rational(5, 3), evaluate=False)) == \
        sympify('1/2 - sqrt(3)*I/2')
    assert nsimplify(sin(pi*Rational(3, 5), evaluate=False)) == \
        sympify('sqrt(sqrt(5)/8 + 5/8)')
    assert nsimplify(sqrt(atan('1', evaluate=False))*(2 + I), [pi]) == \
        sqrt(pi) + sqrt(pi)/2*I
    assert nsimplify(2 + exp(2 * atan('1/4') * I)) == sympify('49/17 + 8*I/17')
    assert nsimplify(pi, tolerance=0.01) == Rational(22, 7)
    assert nsimplify(pi, tolerance=0.001) == Rational(355, 113)
    assert nsimplify(0.33333, tolerance=1e-4) == Rational(1, 3)
    assert nsimplify(2.0**(1 / 3.), tolerance=0.001) == Rational(635, 504)
    assert nsimplify(2.0**(1/3.), tolerance=0.001, full=True) == \
        2**Rational(1, 3)
    assert nsimplify(x + .5, rational=True) == S.Half + x
    assert nsimplify(1 / .3 + x, rational=True) == Rational(10, 3) + x
    assert nsimplify(log(3).n(), rational=True) == \
        sympify('109861228866811/100000000000000')
    assert nsimplify(Float(0.272198261287950), [pi, log(2)]) == pi * log(2) / 8
    assert nsimplify(Float(0.272198261287950).n(3), [pi, log(2)]) == \
        -pi/4 - log(2) + Rational(7, 4)
    assert nsimplify(x / 7.0) == x / 7
    assert nsimplify(pi / 1e2) == pi / 100
    assert nsimplify(pi / 1e2, rational=False) == pi / 100.0
    assert nsimplify(pi / 1e-7) == 10000000 * pi
    assert not nsimplify(
        factor(-3.0 * z**2 * (z**2)**(-2.5) + 3 * (z**2)**(-1.5))).atoms(Float)
    e = x**0.0
    assert e.is_Pow and nsimplify(x**0.0) == 1
    assert nsimplify(3.333333, tolerance=0.1, rational=True) == Rational(10, 3)
    assert nsimplify(3.333333, tolerance=0.01,
                     rational=True) == Rational(10, 3)
    assert nsimplify(3.666666, tolerance=0.1, rational=True) == Rational(11, 3)
    assert nsimplify(3.666666, tolerance=0.01,
                     rational=True) == Rational(11, 3)
    assert nsimplify(33, tolerance=10, rational=True) == Rational(33)
    assert nsimplify(33.33, tolerance=10, rational=True) == Rational(30)
    assert nsimplify(37.76, tolerance=10, rational=True) == Rational(40)
    assert nsimplify(-203.1) == Rational(-2031, 10)
    assert nsimplify(.2, tolerance=0) == Rational(1, 5)
    assert nsimplify(-.2, tolerance=0) == Rational(-1, 5)
    assert nsimplify(.2222, tolerance=0) == Rational(1111, 5000)
    assert nsimplify(-.2222, tolerance=0) == Rational(-1111, 5000)
    # issue 7211, PR 4112
    assert nsimplify(S(2e-8)) == Rational(1, 50000000)
    # issue 7322 direct test
    assert nsimplify(1e-42, rational=True) != 0
    # issue 10336
    inf = Float('inf')
    infs = (-oo, oo, inf, -inf)
    for zi in infs:
        ans = sign(zi) * oo
        assert nsimplify(zi) == ans
        assert nsimplify(zi + x) == x + ans

    assert nsimplify(0.33333333, rational=True,
                     rational_conversion='exact') == Rational(0.33333333)

    # Make sure nsimplify on expressions uses full precision
    assert nsimplify(
        pi.evalf(100) * x,
        rational_conversion='exact').evalf(100) == pi.evalf(100) * x
Beispiel #37
0
def test_simplify_expr():
    x, y, z, k, n, m, w, s, A = symbols('x,y,z,k,n,m,w,s,A')
    f = Function('f')

    assert all(simplify(tmp) == tmp for tmp in [I, E, oo, x, -x, -oo, -E, -I])

    e = 1 / x + 1 / y
    assert e != (x + y) / (x * y)
    assert simplify(e) == (x + y) / (x * y)

    e = A**2 * s**4 / (4 * pi * k * m**3)
    assert simplify(e) == e

    e = (4 + 4 * x - 2 * (2 + 2 * x)) / (2 + 2 * x)
    assert simplify(e) == 0

    e = (-4 * x * y**2 - 2 * y**3 - 2 * x**2 * y) / (x + y)**2
    assert simplify(e) == -2 * y

    e = -x - y - (x + y)**(-1) * y**2 + (x + y)**(-1) * x**2
    assert simplify(e) == -2 * y

    e = (x + x * y) / x
    assert simplify(e) == 1 + y

    e = (f(x) + y * f(x)) / f(x)
    assert simplify(e) == 1 + y

    e = (2 * (1 / n - cos(n * pi) / n)) / pi
    assert simplify(e) == (-cos(pi * n) + 1) / (pi * n) * 2

    e = integrate(1 / (x**3 + 1), x).diff(x)
    assert simplify(e) == 1 / (x**3 + 1)

    e = integrate(x / (x**2 + 3 * x + 1), x).diff(x)
    assert simplify(e) == x / (x**2 + 3 * x + 1)

    f = Symbol('f')
    A = Matrix([[2 * k - m * w**2, -k], [-k, k - m * w**2]]).inv()
    assert simplify((A * Matrix([0, f]))[1] - (-f * (2 * k - m * w**2) /
                                               (k**2 - (k - m * w**2) *
                                                (2 * k - m * w**2)))) == 0

    f = -x + y / (z + t) + z * x / (z + t) + z * a / (z + t) + t * x / (z + t)
    assert simplify(f) == (y + a * z) / (z + t)

    # issue 10347
    expr = -x * (y**2 - 1) * (
        2 * y**2 * (x**2 - 1) / (a * (x**2 - y**2)**2) + (x**2 - 1) /
        (a * (x**2 - y**2))) / (a * (x**2 - y**2)) + x * (
            -2 * x**2 * sqrt(-x**2 * y**2 + x**2 + y**2 - 1) * sin(z) /
            (a * (x**2 - y**2)**2) -
            x**2 * sqrt(-x**2 * y**2 + x**2 + y**2 - 1) * sin(z) /
            (a * (x**2 - 1) * (x**2 - y**2)) +
            (x**2 * sqrt((-x**2 + 1) * (y**2 - 1)) *
             sqrt(-x**2 * y**2 + x**2 + y**2 - 1) * sin(z) / (x**2 - 1) + sqrt(
                 (-x**2 + 1) * (y**2 - 1)) *
             (x * (-x * y**2 + x) / sqrt(-x**2 * y**2 + x**2 + y**2 - 1) +
              sqrt(-x**2 * y**2 + x**2 + y**2 - 1)) * sin(z)) / (a * sqrt(
                  (-x**2 + 1) * (y**2 - 1)) * (x**2 - y**2))
        ) * sqrt(-x**2 * y**2 + x**2 + y**2 - 1) * sin(z) / (
            a * (x**2 - y**2)) + x * (
                -2 * x**2 * sqrt(-x**2 * y**2 + x**2 + y**2 - 1) * cos(z) /
                (a * (x**2 - y**2)**2) -
                x**2 * sqrt(-x**2 * y**2 + x**2 + y**2 - 1) * cos(z) /
                (a * (x**2 - 1) * (x**2 - y**2)) +
                (x**2 * sqrt((-x**2 + 1) *
                             (y**2 - 1)) * sqrt(-x**2 * y**2 + x**2 + y**2 - 1)
                 * cos(z) / (x**2 - 1) + x * sqrt(
                     (-x**2 + 1) * (y**2 - 1)) * (-x * y**2 + x) * cos(z) /
                 sqrt(-x**2 * y**2 + x**2 + y**2 - 1) + sqrt(
                     (-x**2 + 1) *
                     (y**2 - 1)) * sqrt(-x**2 * y**2 + x**2 + y**2 - 1) *
                 cos(z)) / (a * sqrt((-x**2 + 1) * (y**2 - 1)) * (x**2 - y**2))
            ) * sqrt(-x**2 * y**2 + x**2 + y**2 - 1) * cos(z) / (
                a *
                (x**2 - y**2)) - y * sqrt((-x**2 + 1) * (y**2 - 1)) * (
                    -x * y * sqrt(-x**2 * y**2 + x**2 + y**2 - 1) * sin(z) /
                    (a * (x**2 - y**2) *
                     (y**2 - 1)) +
                    2 * x * y * sqrt(-x**2 * y**2 + x**2 + y**2 - 1) * sin(z) /
                    (a * (x**2 - y**2)**2) +
                    (x * y * sqrt((-x**2 + 1) * (y**2 - 1)) *
                     sqrt(-x**2 * y**2 + x**2 + y**2 - 1) * sin(z) /
                     (y**2 - 1) + x * sqrt(
                         (-x**2 + 1) * (y**2 - 1)) * (-x**2 * y + y) * sin(z) /
                     sqrt(-x**2 * y**2 + x**2 + y**2 - 1)) / (a * sqrt(
                         (-x**2 + 1) * (y**2 - 1)) * (x**2 - y**2))
                ) * sin(z) / (a * (x**2 - y**2)) + y * (x**2 - 1) * (
                    -2 * x * y *
                    (x**2 - 1) /
                    (a * (x**2 - y**2)**2) + 2 * x * y / (a * (x**2 - y**2))
                ) / (a *
                     (x**2 - y**2)) + y * (x**2 - 1) * (y**2 - 1) * (
                         -x * y * sqrt(-x**2 * y**2 + x**2 + y**2 - 1) *
                         cos(z) / (a * (x**2 - y**2) *
                                   (y**2 - 1)) + 2 * x * y *
                         sqrt(-x**2 * y**2 + x**2 + y**2 - 1) * cos(z) /
                         (a *
                          (x**2 - y**2)**2) +
                         (x * y * sqrt((-x**2 + 1) * (y**2 - 1)) *
                          sqrt(-x**2 * y**2 + x**2 + y**2 - 1) * cos(z) /
                          (y**2 - 1) + x * sqrt(
                              (-x**2 + 1) * (y**2 - 1)) * (-x**2 * y + y) *
                          cos(z) / sqrt(-x**2 * y**2 + x**2 + y**2 - 1)) /
                         (a * sqrt((-x**2 + 1) * (y**2 - 1)) *
                          (x**2 - y**2))) * cos(z) / (a * sqrt(
                              (-x**2 + 1) *
                              (y**2 - 1)) * (x**2 - y**2)) - x * sqrt(
                                  (-x**2 + 1) * (y**2 - 1)
                              ) * sqrt(-x**2 * y**2 + x**2 + y**2 - 1) * sin(
                                  z)**2 / (a**2 * (x**2 - 1) * (x**2 - y**2) *
                                           (y**2 - 1)) - x * sqrt(
                                               (-x**2 + 1) *
                                               (y**2 - 1)) * sqrt(
                                                   -x**2 * y**2 + x**2 + y**2 -
                                                   1) * cos(z)**2 / (
                                                       a**2 * (x**2 - 1) *
                                                       (x**2 - y**2) *
                                                       (y**2 - 1))
    assert simplify(expr) == 2 * x / (a**2 * (x**2 - y**2))

    #issue 17631
    assert simplify('((-1/2)*Boole(True)*Boole(False)-1)*Boole(True)') == \
            Mul(sympify('(2 + Boole(True)*Boole(False))'), sympify('-Boole(True)/2'))

    A, B = symbols('A,B', commutative=False)

    assert simplify(A * B - B * A) == A * B - B * A
    assert simplify(A / (1 + y / x)) == x * A / (x + y)
    assert simplify(A * (1 / x + 1 / y)) == A / x + A / y  #(x + y)*A/(x*y)

    assert simplify(log(2) + log(3)) == log(6)
    assert simplify(log(2 * x) - log(2)) == log(x)

    assert simplify(hyper([], [], x)) == exp(x)
Beispiel #38
0
 def domain(self):
     return SingleContinuousDomain(sympify(self.symbol), self.set)
Beispiel #39
0
def gen_lobatto(max_order):
    assert max_order > 2

    x = sm.symbols('x')

    lobs = [0, 1]
    lobs[0] = (1 - x) / 2
    lobs[1] = (1 + x) / 2

    dlobs = [lob.diff('x') for lob in lobs]

    legs = [sm.legendre(0, 'y')]
    clegs = [sm.ccode(legs[0])]
    dlegs = [sm.legendre(0, 'y').diff('y')]
    cdlegs = [sm.ccode(dlegs[0])]

    clobs = [sm.ccode(lob) for lob in lobs]
    cdlobs = [sm.ccode(dlob) for dlob in dlobs]

    denoms = []  # for lobs.

    for ii in range(2, max_order + 1):
        coef = sm.sympify('sqrt(2 * (2 * %s - 1)) / 2' % ii)
        leg = sm.legendre(ii - 1, 'y')

        pleg = leg.as_poly()
        coefs = pleg.all_coeffs()
        denom = max(sm.denom(val) for val in coefs)

        cleg = sm.ccode(sm.horner(leg * denom) / denom)

        dleg = leg.diff('y')
        cdleg = sm.ccode(sm.horner(dleg * denom) / denom)

        lob = sm.simplify(coef * sm.integrate(leg, ('y', -1, x)))
        lobnc = sm.simplify(sm.integrate(leg, ('y', -1, x)))

        plobnc = lobnc.as_poly()
        coefs = plobnc.all_coeffs()
        denom = sm.denom(coef) * max(sm.denom(val) for val in coefs)

        clob = sm.ccode(sm.horner(lob * denom) / denom)

        dlob = lob.diff('x')
        cdlob = sm.ccode(sm.horner(dlob * denom) / denom)

        legs.append(leg)
        clegs.append(cleg)
        dlegs.append(dleg)
        cdlegs.append(cdleg)
        lobs.append(lob)
        clobs.append(clob)
        dlobs.append(dlob)
        cdlobs.append(cdlob)
        denoms.append(denom)

    coef = sm.sympify('sqrt(2 * (2 * %s - 1)) / 2' % (max_order + 1))
    leg = sm.legendre(max_order, 'y')

    pleg = leg.as_poly()
    coefs = pleg.all_coeffs()
    denom = max(sm.denom(val) for val in coefs)

    cleg = sm.ccode(sm.horner(leg * denom) / denom)

    dleg = leg.diff('y')
    cdleg = sm.ccode(sm.horner(dleg * denom) / denom)

    legs.append(leg)
    clegs.append(cleg)
    dlegs.append(dleg)
    cdlegs.append(cdleg)

    kerns = []
    ckerns = []
    dkerns = []
    cdkerns = []
    for ii, lob in enumerate(lobs[2:]):
        kern = sm.simplify(lob / (lobs[0] * lobs[1]))
        dkern = kern.diff('x')

        denom = denoms[ii] / 4
        ckern = sm.ccode(sm.horner(kern * denom) / denom)
        cdkern = sm.ccode(sm.horner(dkern * denom) / denom)

        kerns.append(kern)
        ckerns.append(ckern)
        dkerns.append(dkern)
        cdkerns.append(cdkern)

    return (legs, clegs, dlegs, cdlegs, lobs, clobs, dlobs, cdlobs, kerns,
            ckerns, dkerns, cdkerns, denoms)
Beispiel #40
0
def mathematica(s):
    return sympify(parse(s))
Beispiel #41
0
def NS(e, n=15, **options):
    return str(sympify(e).evalf(n, **options))
Beispiel #42
0
SI = States()
SI.name = ['X', 'Y', 'Psi', 'Psidot', 'V', 'Vdot']
numStates = 6
SI.states = numStates * [None]

#### TESTING PURPOSES
Stest = States()
Stest.states = 10 * [0]

lf = 1.3314298821150170049065764033003
lr = 1.5185105279655697341212317041936
#base = [30.6286298219,-96.4821284934]

#### LINEARIZE EQUATIONS USING JACOBIAN
sym.init_printing(use_latex=True)
myvarsF = sym.sympify('x(t), y(t), psi(t), diff(psi(t),t), v(t), diff(v(t),t)')
myvarsG = sym.sympify('delta_f(t), a(t)')
bet = sym.sympify('atan(l_r/(l_f+l_r)*tan(delta_f(t)))')
f1 = sym.sympify('v(t)*cos(psi(t)+bet)')  # xdot
f1 = f1.subs({'bet': bet})
f2 = sym.sympify('v(t)*sin(psi(t)+bet)')  # ydot
f2 = f2.subs({'bet': bet})
f3 = sym.sympify('v(t)/l_r*sin(bet)')  # psidot
f3 = f3.subs({'bet': bet})  #substitute bet expression
f4 = sym.diff(f3, sym.symbols('t'))  #psidotdot
f4 = f4.subs({'bet': bet})  #sub bet expression
f5 = sym.sympify('a(t)')  #vdot
f6 = f5.diff('t')  #vdotdot
J = sym.Matrix([f1, f2, f3, f4, f5, f6])  #define vector-valued function
F = J.jacobian(myvarsF)  # Perform jacobiam wrt to myvars
G = J.jacobian(myvarsG)
Beispiel #43
0
    def __new__(cls, mat):
        mat = sympify(mat)

        return Basic.__new__(cls, mat)
Beispiel #44
0
# The Derivative  of a function y = f(x) expresses the rate of change in the dependent variable
# y with respect to the independent variable , x. It's denoted as either f'x or dy/dx.

#Derivative Calculator
from sympy import Symbol, Derivative, sympify, pprint
from sympy.core.sympify import SympifyError


def derivative(f, var):
    var = Symbol(var)
    d = Derivative(f, var).doit()
    pprint(d)


if __name__ == '__main__':
    f = input('Enter a function: ')
    var = input('Enter the variable to diffrentiate with respect to: ')
    try:
        f = sympify(f)
    except SympifyError:
        print('Invalid input')
    else:
        derivative(f, var)
def residue(expr, x, x0):
    """
    Finds the residue of ``expr`` at the point x=x0.

    The residue is defined as the coefficient of 1/(x-x0) in the power series
    expansion about x=x0.

    Examples
    ========

    >>> from sympy import Symbol, residue, sin
    >>> x = Symbol("x")
    >>> residue(1/x, x, 0)
    1
    >>> residue(1/x**2, x, 0)
    0
    >>> residue(2/sin(x), x, 0)
    2

    This function is essential for the Residue Theorem [1].

    References
    ==========

    1. http://en.wikipedia.org/wiki/Residue_theorem
    """
    # The current implementation uses series expansion to
    # calculate it. A more general implementation is explained in
    # the section 5.6 of the Bronstein's book {M. Bronstein:
    # Symbolic Integration I, Springer Verlag (2005)}. For purely
    # rational functions, the algorithm is much easier. See
    # sections 2.4, 2.5, and 2.7 (this section actually gives an
    # algorithm for computing any Laurent series coefficient for
    # a rational function). The theory in section 2.4 will help to
    # understand why the resultant works in the general algorithm.
    # For the definition of a resultant, see section 1.4 (and any
    # previous sections for more review).

    from sympy import collect, Mul, Order, S
    expr = sympify(expr)
    if x0 != 0:
        expr = expr.subs(x, x + x0)
    for n in [0, 1, 2, 4, 8, 16, 32]:
        if n == 0:
            s = expr.series(x, n=0)
        else:
            s = expr.nseries(x, n=n)
        if not s.has(Order) or s.getn() >= 0:
            break
    s = collect(s.removeO(), x)
    if s.is_Add:
        args = s.args
    else:
        args = [s]
    res = S(0)
    for arg in args:
        c, m = arg.as_coeff_mul(x)
        m = Mul(*m)
        if not (m == 1 or m == x or (m.is_Pow and m.exp.is_Integer)):
            raise NotImplementedError('term of unexpected form: %s' % m)
        if m == 1 / x:
            res += c
    return res
Beispiel #46
0
 def _calculate_price_expression(self, price_expr, context):
     local_context = {}
     for p in context.keys():
         local_context[p] = context[p]
     p = sympy.sympify(price_expr, locals=local_context)
     return Decimal(float(p))
Beispiel #47
0
def convertir_numero(valor):
    return lambdify((), sympify(valor))()
Beispiel #48
0
    check_arg(old, sp.Basic, 1)
    check_arg(new, sp.Basic, 2)

    for ind, (old0, new0) in enumerate(subs):
        if old0 == old:
            subs.pop(ind)
            break
    subs.append((old, new))


# Create a sympy evaulation namespace
sp_namespace = {}
sp_namespace.update((name, op) for name, op in sp.functions.__dict__.items() \
                    if name[0] != "_")
sp_namespace["Conditional"] = Conditional
sp_namespace["ContinuousConditional"] = ContinuousConditional
sp_namespace.update((name, op) for name, op in _relational.__dict__.items() \
                    if name in ["Eq", "Ne", "Gt", "Ge", "Lt", "Le"])
sp_namespace.update((name, getattr(sp, name)) for name in ["And", "Or"])
sp_namespace["pi"] = sp.numbers.pi
sp_namespace["E"] = sp.numbers.E

sp_namespace["one"] = sp.sympify(1)
sp_namespace["two"] = sp.sympify(2)
sp_namespace["three"] = sp.sympify(3)
sp_namespace["four"] = sp.sympify(4)
sp_namespace["five"] = sp.sympify(5)
sp_namespace["ten"] = sp.sympify(10)

__all__ = [_name for _name in globals().keys() if _name[0] != "_"]
Beispiel #49
0
 def _eval_power(self, other):
     other = sympify(other)
     return Dimension(self.name**other)
Beispiel #50
0
    def __init__(self, name, abbrev, exponent, base=sympify(10)):

        self.name = name
        self.abbrev = abbrev

        self.factor = base**exponent
Beispiel #51
0
def split_expression(expr):
    '''
    Split an expression into a part containing the function ``f`` and another
    one containing the function ``g``. Returns a tuple of the two expressions
    (as sympy expressions).
    
    Parameters
    ----------
    expr : str
        An expression containing references to functions ``f`` and ``g``.    
    
    Returns
    -------
    (non_stochastic, stochastic) : tuple of sympy expressions
        A pair of expressions representing the non-stochastic (containing
        function-independent terms and terms involving ``f``) and the
        stochastic part of the expression (terms involving ``g`` and/or ``dW``).
    
    Examples
    --------
    >>> split_expression('dt * __f(__x, __t)')
    (dt*__f(__x, __t), None)
    >>> split_expression('dt * __f(__x, __t) + __dW * __g(__x, __t)')
    (dt*__f(__x, __t), __dW*__g(__x, __t))
    >>> split_expression('1/(2*dt**.5)*(__g_support - __g(__x, __t))*(__dW**2)')
    (0, __dW**2*__g_support*dt**(-0.5)/2 - __dW**2*dt**(-0.5)*__g(__x, __t)/2)
    '''

    f = SYMBOLS['__f']
    g = SYMBOLS['__g']
    dW = SYMBOLS['__dW']
    # Arguments of the f and g functions
    x_f = sympy.Wild('x_f', exclude=[f, g], real=True)
    t_f = sympy.Wild('t_f', exclude=[f, g], real=True)
    x_g = sympy.Wild('x_g', exclude=[f, g], real=True)
    t_g = sympy.Wild('t_g', exclude=[f, g], real=True)

    # Reorder the expression so that f(x,t) and g(x,t) are factored out
    sympy_expr = sympy.sympify(expr, locals=SYMBOLS).expand()
    sympy_expr = sympy.collect(sympy_expr, f(x_f, t_f))
    sympy_expr = sympy.collect(sympy_expr, g(x_g, t_g))

    # Constant part, contains neither f, g nor dW
    independent = sympy.Wild('independent', exclude=[f, g, dW], real=True)
    # The exponent of the random number
    dW_exponent = sympy.Wild('dW_exponent', exclude=[f, g, dW, 0], real=True)
    # The factor for the random number, not containing the g function
    independent_dW = sympy.Wild('independent_dW',
                                exclude=[f, g, dW],
                                real=True)
    # The factor for the f function
    f_factor = sympy.Wild('f_factor', exclude=[f, g], real=True)
    # The factor for the g function
    g_factor = sympy.Wild('g_factor', exclude=[f, g], real=True)

    match_expr = (independent + f_factor * f(x_f, t_f) +
                  independent_dW * dW**dW_exponent + g_factor * g(x_g, t_g))
    matches = sympy_expr.match(match_expr)

    if matches is None:
        raise ValueError(('Expression "%s" in the state updater description '
                          'could not be parsed.' % sympy_expr))

    # Non-stochastic part
    if x_f in matches:
        # Includes the f function
        non_stochastic = matches[independent] + (matches[f_factor] *
                                                 f(matches[x_f], matches[t_f]))
    else:
        # Does not include f, might be 0
        non_stochastic = matches[independent]

    # Stochastic part
    if independent_dW in matches and matches[independent_dW] != 0:
        # includes a random variable term with a non-zero factor
        stochastic = (matches[g_factor] * g(matches[x_g], matches[t_g]) +
                      matches[independent_dW] * dW**matches[dW_exponent])
    elif x_g in matches:
        # Does not include a random variable but the g function
        stochastic = matches[g_factor] * g(matches[x_g], matches[t_g])
    else:
        # Contains neither random variable nor g function --> empty
        stochastic = None

    return (non_stochastic, stochastic)
Beispiel #52
0
def graficar(expr, intervalo, metodo, particiones):
    expr = sympify(expr, evaluate=False)
    func = lambdify(abc.x, expr)
    particiones = convertir_numero(particiones)
    intervalo = a, b = list(
        sorted([convertir_numero(limite) for limite in intervalo]))

    fig, ax = plt.subplots()

    def establecer_interfaz():
        # Establecer título
        fig.canvas.set_window_title('{}, {}'.format(expr, intervalo))
        # Escribir función
        plt.text((a + b) / 2,
                 func((a + b) / 2),
                 '${}$'.format(latex(expr)),
                 horizontalalignment='center',
                 fontsize=20)

    def graficar_funcion():
        x = np.arange(a, b, 0.001)
        y = func(x)
        plt.plot(x, y, '#FE4A49')

    def graficar_trapecio():
        x = np.linspace(a, b, particiones + 1)
        y = func(x)
        puntos = list(zip(x, y))

        for i in range(particiones):
            x1, _ = puntos[i]
            x2, _ = puntos[i + 1]
            vertices = [(x1, 0), puntos[i], puntos[i + 1], (x2, 0)]
            poligono = Polygon(vertices,
                               facecolor='#F26430' if i %
                               2 == 0 else '#F48055',
                               edgecolor='#F26430')
            ax.add_patch(poligono)

    def graficar_simpson():
        def graficar_parabola(p1, p2, p3, obscuro):
            inicio = p1[0]
            fin = p3[0]

            func = parabola_puntos(p1, p2, p3)
            x = np.arange(inicio, fin, 0.001)
            y = func(x)

            vertices = [(inicio, 0)] + list(zip(x, y)) + [(fin, 0)]
            poligono = Polygon(vertices,
                               facecolor='#009FB7' if obscuro else '#7FC0CA',
                               edgecolor='#009FB7')
            ax.add_patch(poligono)

        x = np.linspace(a, b, particiones + 1)
        y = func(x)
        puntos = list(zip(x, y))

        for i in range(particiones // 2):
            graficar_parabola(puntos[2 * i], puntos[2 * i + 1],
                              puntos[2 * i + 2], i % 2 == 0)

    def graficar_area_bajo_curva():
        x = np.arange(a, b, 0.001)
        y = func(x)

        vertices = [(a, 0)] + list(zip(x, y)) + [(b, 0)]
        poligono = Polygon(vertices, facecolor='#009FB7', edgecolor='#009FB7')
        ax.add_patch(poligono)

    establecer_interfaz()
    graficar_funcion()
    if particiones > 1000:
        graficar_area_bajo_curva()
    else:
        if metodo == 'trapecio':
            graficar_trapecio()
        else:
            graficar_simpson()

    plt.show()
 def print_cooling(self, assign_to):
     eq = sympy.sympify("0")
     for term in self.cooling_actions:
         eq += self.cooling_actions[term].equation
     return ccode(eq, assign_to = assign_to)
Beispiel #54
0
 def prob_of(self, elem):
     elem = sympify(elem)
     density = self._density
     if isinstance(list(density.keys())[0], FiniteSet):
         return density.get(elem, S.Zero)
     return density.get(tuple(elem)[0][1], S.Zero)
Beispiel #55
0
import matplotlib.pyplot as plt
import math
import matplotlib as mpl
import numpy as np
import sympy
from sympy.abc import x
from sympy import sin, cos, pi

x1 = np.arange(-10, 9, 0.01)  # start,stop,step
y1 = sympy.sympify(-(x**3) / (x - 9))
y1 = sympy.lambdify(x, y1, 'numpy')

x2 = np.arange(4, 10, 0.01)
y2 = sympy.sympify(-1 / (x - 4) + 2)
y2 = sympy.lambdify(x, y2, 'numpy')

plt.grid(True)
plt.axhline(y=0, lw=1, color='black')
plt.axvline(x=0, lw=1, color='black')
plt.xticks(np.arange(-100, 100, 1))
plt.yticks(np.arange(-100, 100, 1))

plot_y1 = y1(x1)
plot_y2 = y2(x2)

plt.plot(x1, plot_y1, color='black', linewidth=1)
plt.plot(x2, plot_y2, color='black', linewidth=1)

plt.ylim(-10, 10)
plt.xlim(-10, 10)
Beispiel #56
0
def _Complement__new__ (cls, a, b, evaluate = True): # sets.Complement patched to sympify args
	if evaluate:
		return Complement.reduce (sympify (a), sympify (b))

	return Basic.__new__ (cls, a, b)
def primitive_element(extension, x=None, **args):
    """Construct a common number field for all extensions. """
    if not extension:
        raise ValueError("can't compute primitive element for empty extension")

    if x is not None:
        x, cls = sympify(x), Poly
    else:
        x, cls = Dummy('x'), PurePoly
    if not args.get('ex', False):
        extension = [ AlgebraicNumber(ext, gen=x) for ext in extension ]

        g, coeffs = extension[0].minpoly.replace(x), [1]

        for ext in extension[1:]:
            s, _, g = sqf_norm(g, x, extension=ext)
            coeffs = [ s*c for c in coeffs ] + [1]

        if not args.get('polys', False):
            return g.as_expr(), coeffs
        else:
            return cls(g), coeffs

    generator = numbered_symbols('y', cls=Dummy)

    F, Y = [], []

    for ext in extension:
        y = next(generator)

        if ext.is_Poly:
            if ext.is_univariate:
                f = ext.as_expr(y)
            else:
                raise ValueError("expected minimal polynomial, got %s" % ext)
        else:
            f = minpoly(ext, y)

        F.append(f)
        Y.append(y)

    coeffs_generator = args.get('coeffs', _coeffs_generator)

    for coeffs in coeffs_generator(len(Y)):
        f = x - sum([ c*y for c, y in zip(coeffs, Y)])
        G = groebner(F + [f], Y + [x], order='lex', field=True)

        H, g = G[:-1], cls(G[-1], x, domain='QQ')

        for i, (h, y) in enumerate(zip(H, Y)):
            try:
                H[i] = Poly(y - h, x,
                            domain='QQ').all_coeffs()  # XXX: composite=False
            except CoercionFailed:  # pragma: no cover
                break  # G is not a triangular set
        else:
            break
    else:  # pragma: no cover
        raise RuntimeError("run out of coefficient configurations")

    _, g = g.clear_denoms()

    if not args.get('polys', False):
        return g.as_expr(), coeffs, H
    else:
        return g, coeffs, H
 def species_total(self, species):
     eq = sympy.sympify("0")
     for rn, rxn in sorted(self.reactions.items()):
         eq += rxn.species_equation(species)
     return eq
def minimal_polynomial(ex, x=None, **args):
    """
    Computes the minimal polynomial of an algebraic element.

    Parameters
    ==========

    ex : algebraic element expression
    x : independent variable of the minimal polynomial

    Options
    =======

    compose : if ``True`` ``_minpoly_compose`` is used, if ``False`` the ``groebner`` algorithm
    polys : if ``True`` returns a ``Poly`` object
    domain : ground domain

    Notes
    =====

    By default ``compose=True``, the minimal polynomial of the subexpressions of ``ex``
    are computed, then the arithmetic operations on them are performed using the resultant
    and factorization.
    If ``compose=False``, a bottom-up algorithm is used with ``groebner``.
    The default algorithm stalls less frequently.

    If no ground domain is given, it will be generated automatically from the expression.

    Examples
    ========

    >>> from sympy import minimal_polynomial, sqrt, solve, QQ
    >>> from sympy.abc import x, y

    >>> minimal_polynomial(sqrt(2), x)
    x**2 - 2
    >>> minimal_polynomial(sqrt(2), x, domain=QQ.algebraic_field(sqrt(2)))
    x - sqrt(2)
    >>> minimal_polynomial(sqrt(2) + sqrt(3), x)
    x**4 - 10*x**2 + 1
    >>> minimal_polynomial(solve(x**3 + x + 3)[0], x)
    x**3 + x + 3
    >>> minimal_polynomial(sqrt(y), x)
    x**2 - y

    """
    from sympy.polys.polytools import degree
    from sympy.polys.domains import FractionField
    from sympy.core.basic import preorder_traversal

    compose = args.get('compose', True)
    polys = args.get('polys', False)
    dom = args.get('domain', None)

    ex = sympify(ex)
    for expr in preorder_traversal(ex):
        if expr.is_AlgebraicNumber:
            compose = False
            break

    if x is not None:
        x, cls = sympify(x), Poly
    else:
        x, cls = Dummy('x'), PurePoly

    if not dom:
        dom = FractionField(QQ, list(ex.free_symbols)) if ex.free_symbols else QQ
    if hasattr(dom, 'symbols') and x in dom.symbols:
        raise GeneratorsError("the variable %s is an element of the ground domain %s" % (x, dom))

    if compose:
        result = _minpoly_compose(ex, x, dom)
        result = result.primitive()[1]
        c = result.coeff(x**degree(result, x))
        if c.is_negative:
            result = expand_mul(-result)
        return cls(result, x, field=True) if polys else result.collect(x)

    if not dom.is_QQ:
        raise NotImplementedError("groebner method only works for QQ")

    result = _minpoly_groebner(ex, x, cls)
    return cls(result, x, field=True) if polys else result.collect(x)
Beispiel #60
0
def test_linearize_rolling_disc_kane():
    # Symbols for time and constant parameters
    t, r, m, g, v = symbols("t r m g v")

    # Configuration variables and their time derivatives
    q1, q2, q3, q4, q5, q6 = q = dynamicsymbols("q1:7")
    q1d, q2d, q3d, q4d, q5d, q6d = qd = [qi.diff(t) for qi in q]

    # Generalized speeds and their time derivatives
    u = dynamicsymbols("u:6")
    u1, u2, u3, u4, u5, u6 = u = dynamicsymbols("u1:7")
    u1d, u2d, u3d, u4d, u5d, u6d = [ui.diff(t) for ui in u]

    # Reference frames
    N = ReferenceFrame("N")  # Inertial frame
    NO = Point("NO")  # Inertial origin
    A = N.orientnew("A", "Axis", [q1, N.z])  # Yaw intermediate frame
    B = A.orientnew("B", "Axis", [q2, A.x])  # Lean intermediate frame
    C = B.orientnew("C", "Axis", [q3, B.y])  # Disc fixed frame
    CO = NO.locatenew("CO", q4 * N.x + q5 * N.y + q6 * N.z)  # Disc center

    # Disc angular velocity in N expressed using time derivatives of coordinates
    w_c_n_qd = C.ang_vel_in(N)
    w_b_n_qd = B.ang_vel_in(N)

    # Inertial angular velocity and angular acceleration of disc fixed frame
    C.set_ang_vel(N, u1 * B.x + u2 * B.y + u3 * B.z)

    # Disc center velocity in N expressed using time derivatives of coordinates
    v_co_n_qd = CO.pos_from(NO).dt(N)

    # Disc center velocity in N expressed using generalized speeds
    CO.set_vel(N, u4 * C.x + u5 * C.y + u6 * C.z)

    # Disc Ground Contact Point
    P = CO.locatenew("P", r * B.z)
    P.v2pt_theory(CO, N, C)

    # Configuration constraint
    f_c = Matrix([q6 - dot(CO.pos_from(P), N.z)])

    # Velocity level constraints
    f_v = Matrix([dot(P.vel(N), uv) for uv in C])

    # Kinematic differential equations
    kindiffs = Matrix(
        [dot(w_c_n_qd - C.ang_vel_in(N), uv) for uv in B]
        + [dot(v_co_n_qd - CO.vel(N), uv) for uv in N]
    )
    qdots = solve(kindiffs, qd)

    # Set angular velocity of remaining frames
    B.set_ang_vel(N, w_b_n_qd.subs(qdots))
    C.set_ang_acc(N, C.ang_vel_in(N).dt(B) + cross(B.ang_vel_in(N), C.ang_vel_in(N)))

    # Active forces
    F_CO = m * g * A.z

    # Create inertia dyadic of disc C about point CO
    I = (m * r ** 2) / 4
    J = (m * r ** 2) / 2
    I_C_CO = inertia(C, I, J, I)

    Disc = RigidBody("Disc", CO, C, m, (I_C_CO, CO))
    BL = [Disc]
    FL = [(CO, F_CO)]
    KM = KanesMethod(
        N,
        [q1, q2, q3, q4, q5],
        [u1, u2, u3],
        kd_eqs=kindiffs,
        q_dependent=[q6],
        configuration_constraints=f_c,
        u_dependent=[u4, u5, u6],
        velocity_constraints=f_v,
    )
    with warns_deprecated_sympy():
        (fr, fr_star) = KM.kanes_equations(FL, BL)

    # Test generalized form equations
    linearizer = KM.to_linearizer()
    assert linearizer.f_c == f_c
    assert linearizer.f_v == f_v
    assert linearizer.f_a == f_v.diff(t).subs(KM.kindiffdict())
    sol = solve(linearizer.f_0 + linearizer.f_1, qd)
    for qi in qdots.keys():
        assert sol[qi] == qdots[qi]
    assert simplify(linearizer.f_2 + linearizer.f_3 - fr - fr_star) == Matrix([0, 0, 0])

    # Perform the linearization
    # Precomputed operating point
    q_op = {q6: -r * cos(q2)}
    u_op = {
        u1: 0,
        u2: sin(q2) * q1d + q3d,
        u3: cos(q2) * q1d,
        u4: -r * (sin(q2) * q1d + q3d) * cos(q3),
        u5: 0,
        u6: -r * (sin(q2) * q1d + q3d) * sin(q3),
    }
    qd_op = {
        q2d: 0,
        q4d: -r * (sin(q2) * q1d + q3d) * cos(q1),
        q5d: -r * (sin(q2) * q1d + q3d) * sin(q1),
        q6d: 0,
    }
    ud_op = {
        u1d: 4 * g * sin(q2) / (5 * r)
        + sin(2 * q2) * q1d ** 2 / 2
        + 6 * cos(q2) * q1d * q3d / 5,
        u2d: 0,
        u3d: 0,
        u4d: r * (sin(q2) * sin(q3) * q1d * q3d + sin(q3) * q3d ** 2),
        u5d: r
        * (
            4 * g * sin(q2) / (5 * r)
            + sin(2 * q2) * q1d ** 2 / 2
            + 6 * cos(q2) * q1d * q3d / 5
        ),
        u6d: -r * (sin(q2) * cos(q3) * q1d * q3d + cos(q3) * q3d ** 2),
    }

    A, B = linearizer.linearize(
        op_point=[q_op, u_op, qd_op, ud_op], A_and_B=True, simplify=True
    )

    upright_nominal = {q1d: 0, q2: 0, m: 1, r: 1, g: 1}

    # Precomputed solution
    A_sol = Matrix(
        [
            [0, 0, 0, 0, 0, 0, 0, 1],
            [0, 0, 0, 0, 0, 1, 0, 0],
            [0, 0, 0, 0, 0, 0, 1, 0],
            [sin(q1) * q3d, 0, 0, 0, 0, -sin(q1), -cos(q1), 0],
            [-cos(q1) * q3d, 0, 0, 0, 0, cos(q1), -sin(q1), 0],
            [0, Rational(4, 5), 0, 0, 0, 0, 0, 6 * q3d / 5],
            [0, 0, 0, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 0, -2 * q3d, 0, 0],
        ]
    )
    B_sol = Matrix([])

    # Check that linearization is correct
    assert A.subs(upright_nominal) == A_sol
    assert B.subs(upright_nominal) == B_sol

    # Check eigenvalues at critical speed are all zero:
    assert sympify(A.subs(upright_nominal).subs(q3d, 1 / sqrt(3))).eigenvals() == {0: 8}