python类simplify()的实例源码

test_matrices.py 文件源码 项目:Python-iBeacon-Scan 作者: NikNitro 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def test_pinv():
    # Pseudoinverse of an invertible matrix is the inverse.
    A1 = Matrix([[a, b], [c, d]])
    assert simplify(A1.pinv()) == simplify(A1.inv())
    # Test the four properties of the pseudoinverse for various matrices.
    As = [Matrix([[13, 104], [2212, 3], [-3, 5]]),
          Matrix([[1, 7, 9], [11, 17, 19]]),
          Matrix([a, b])]
    for A in As:
        A_pinv = A.pinv()
        AAp = A * A_pinv
        ApA = A_pinv * A
        assert simplify(AAp * A) == A
        assert simplify(ApA * A_pinv) == A_pinv
        assert AAp.H == AAp
        assert ApA.H == ApA
manualintegrate.py 文件源码 项目:Python-iBeacon-Scan 作者: NikNitro 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def power_rule(integral):
    integrand, symbol = integral
    base, exp = integrand.as_base_exp()

    if symbol not in exp.free_symbols and isinstance(base, sympy.Symbol):
        if sympy.simplify(exp + 1) == 0:
            return ReciprocalRule(base, integrand, symbol)
        return PowerRule(base, exp, integrand, symbol)
    elif symbol not in base.free_symbols and isinstance(exp, sympy.Symbol):
        rule = ExpRule(base, exp, integrand, symbol)

        if fuzzy_not(sympy.log(base).is_zero):
            return rule
        elif sympy.log(base).is_zero:
            return ConstantRule(1, 1, symbol)

        return PiecewiseRule([
            (ConstantRule(1, 1, symbol), sympy.Eq(sympy.log(base), 0)),
            (rule, True)
        ], integrand, symbol)
plane.py 文件源码 项目:Python-iBeacon-Scan 作者: NikNitro 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def equals(self, o):
        """
        Returns True if self and o are the same mathematical entities.

        Examples
        ========

        >>> from sympy import Plane, Point3D
        >>> a = Plane(Point3D(1, 2, 3), normal_vector=(1, 1, 1))
        >>> b = Plane(Point3D(1, 2, 3), normal_vector=(2, 2, 2))
        >>> c = Plane(Point3D(1, 2, 3), normal_vector=(-1, 4, 6))
        >>> a.equals(a)
        True
        >>> a.equals(b)
        True
        >>> a.equals(c)
        False
        """
        if isinstance(o, Plane):
            a = self.equation()
            b = o.equation()
            return simplify(a / b).is_constant()
        else:
            return False
algorithmic_math.py 文件源码 项目:tensor2tensor 作者: tensorflow 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def generate_algebra_simplify_sample(vlist, ops, min_depth, max_depth):
  """Randomly generate an algebra simplify dataset sample.

  Given an input expression, produce the simplified expression.

  See go/symbolic-math-dataset.

  Args:
    vlist: Variable list. List of chars that can be used in the expression.
    ops: List of ExprOp instances. The allowed operators for the expression.
    min_depth: Expression trees will not have a smaller depth than this. 0 means
        there is just a variable. 1 means there is one operation.
    max_depth: Expression trees will not have a larger depth than this. To make
        all trees have the same depth, set this equal to `min_depth`.

  Returns:
    sample: String representation of the input.
    target: String representation of the solution.
  """
  depth = random.randrange(min_depth, max_depth + 1)
  expr = random_expr(depth, vlist, ops)

  sample = str(expr)
  target = format_sympy_expr(sympy.simplify(sample))
  return sample, target
algorithmic_math_test.py 文件源码 项目:tensor2tensor 作者: tensorflow 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def testAlgebraInverse(self):
    dataset_objects = algorithmic_math.math_dataset_init(26)
    counter = 0
    for d in algorithmic_math.algebra_inverse(26, 0, 3, 10):
      counter += 1
      decoded_input = dataset_objects.int_decoder(d["inputs"])
      solve_var, expression = decoded_input.split(":")
      lhs, rhs = expression.split("=")

      # Solve for the solve-var.
      result = sympy.solve("%s-(%s)" % (lhs, rhs), solve_var)
      target_expression = dataset_objects.int_decoder(d["targets"])

      # Check that the target and sympy's solutions are equivalent.
      self.assertEqual(
          0, sympy.simplify(str(result[0]) + "-(%s)" % target_expression))
    self.assertEqual(counter, 10)
algorithmic_math_test.py 文件源码 项目:tensor2tensor 作者: tensorflow 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def testCalculusIntegrate(self):
    dataset_objects = algorithmic_math.math_dataset_init(
        8, digits=5, functions={"log": "L"})
    counter = 0
    for d in algorithmic_math.calculus_integrate(8, 0, 3, 10):
      counter += 1
      decoded_input = dataset_objects.int_decoder(d["inputs"])
      var, expression = decoded_input.split(":")
      target = dataset_objects.int_decoder(d["targets"])

      for fn_name, fn_char in six.iteritems(dataset_objects.functions):
        target = target.replace(fn_char, fn_name)

      # Take the derivative of the target.
      derivative = str(sympy.diff(target, var))

      # Check that the derivative of the integral equals the input.
      self.assertEqual(0, sympy.simplify("%s-(%s)" % (expression, derivative)))
    self.assertEqual(counter, 10)
schemes.py 文件源码 项目:orthopy 作者: nschloe 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def _gauss_from_coefficients_sympy(alpha, beta):
    assert isinstance(alpha[0], sympy.Rational)
    # Construct the triadiagonal matrix [sqrt(beta), alpha, sqrt(beta)]
    A = _sympy_tridiag(alpha, [sympy.sqrt(bta) for bta in beta])

    # Extract points and weights from eigenproblem
    x = []
    w = []
    for item in A.eigenvects():
        val, multiplicity, vec = item
        assert multiplicity == 1
        assert len(vec) == 1
        vec = vec[0]
        x.append(val)
        norm2 = sum([v**2 for v in vec])
        # simplifiction takes really long
        # w.append(sympy.simplify(beta[0] * vec[0]**2 / norm2))
        w.append(beta[0] * vec[0]**2 / norm2)
    # sort by x
    order = sorted(range(len(x)), key=lambda i: x[i])
    x = [x[i] for i in order]
    w = [w[i] for i in order]
    return x, w
test_sphere_sph.py 文件源码 项目:orthopy 作者: nschloe 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def test_normality(n=3):
    '''Make sure that the polynomials are normal.
    '''
    polar = sympy.Symbol('theta', real=True)
    azimuthal = sympy.Symbol('phi', real=True)
    tree = numpy.concatenate(
            orthopy.sphere.sph_tree(
                n, polar, azimuthal, normalization='quantum mechanic',
                symbolic=True
                ))

    for val in tree:
        integrand = sympy.simplify(
            val * sympy.conjugate(val) * sympy.sin(polar)
            )
        assert sympy.integrate(
            integrand,
            (azimuthal, 0, 2*pi), (polar, 0, pi)
            ) == 1
    return
test_sphere_sph.py 文件源码 项目:orthopy 作者: nschloe 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def test_orthogonality(normalization, n=4):
    polar = sympy.Symbol('theta', real=True)
    azimuthal = sympy.Symbol('phi', real=True)
    tree = numpy.concatenate(
            orthopy.sphere.sph_tree(
                n, polar, azimuthal, normalization=normalization,
                symbolic=True
                ))
    vals = tree * sympy.conjugate(numpy.roll(tree, 1, axis=0))

    for val in vals:
        integrand = sympy.simplify(val * sympy.sin(polar))
        assert sympy.integrate(
            integrand,
            (azimuthal, 0, 2*pi), (polar, 0, pi)
            ) == 0
    return
test_reduction.py 文件源码 项目:crnpy 作者: etonello 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def eqs_match(origeqs, origspecies, removed, neweqs, newspecies, debug = False):
    """Check that the original equations match the new equations after
    replacing the species with the expression in removed."""
    origeqsdict = dict((origspecies[s], origeqs[s]) for s in range(len(origspecies)))
    replaceeqs = {}
    for s in origeqsdict:
        e = origeqsdict[s]
        for i in range(len(removed)): e = e.subs(removed[i][0], removed[i][1])
        e.simplify()
        replaceeqs[s] = e
    neweqsdict = dict((newspecies[s], neweqs[s]) for s in range(len(newspecies)))

    if debug:
        for s in newspecies: print("{}: {}".format(s, replaceeqs[s] - neweqsdict[s]).simplify())

    return sum((replaceeqs[s] - neweqsdict[s]).simplify() != 0 for s in newspecies)
KineticLawIdentifier.py 文件源码 项目:libSigNetSim 作者: vincent-noel 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def getReversibleRates(self, formula):

        t_forward = None
        t_backward = None
        formula = simplify(formula)
        # print formula
        # If we had an addition
        if formula.func == SympyAdd:
            # print srepr(formula)
            # And one of the terms
            for arg in formula.args:

                # is *(-1)
                if arg.func == SympyMul:
                    if (arg.args[0] == SympyInteger(-1)
                        or arg.args[1] == SympyInteger(-1)):
                        t_backward = arg*SympyInteger(-1)
        else:
            return (formula,SympyInteger(0))

        t_forward = SympyAdd(formula, t_backward)

        return (t_forward, t_backward)
KineticLaw.py 文件源码 项目:libSigNetSim 作者: vincent-noel 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def setHill(self, parameters):

        t_reactants = self.getReactantsFormula()
        t_modifiers = self.getModifiersFormula()

        t_kcat = parameters[0].symbol.getInternalMathFormula()
        t_kd = parameters[1].symbol.getInternalMathFormula()
        t_n = parameters[2].symbol.getInternalMathFormula()

        t_r_pow = t_reactants**t_n
        t_formula = t_kcat*t_modifiers*t_r_pow/(t_r_pow + t_kd)

        if len(self.reaction.listOfReactants) > 0:
            first_reactant = self.reaction.listOfReactants[0].getSpecies()
            if not first_reactant.hasOnlySubstanceUnits:
                t_formula *= first_reactant.getCompartment().symbol.getInternalMathFormula()

        elif len(self.reaction.listOfModifiers) > 0:
            first_modifier = self.reaction.listOfModifiers[0].getSpecies()
            if not first_modifier.hasOnlySubstanceUnits:
                t_formula *= first_modifier.getCompartment().symbol.getInternalMathFormula()

        self.__definition.setInternalMathFormula(simplify(t_formula))
wincnn.py 文件源码 项目:wincnn 作者: andravin 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def filterVerify(n, r, AT, G, BT):

    alpha = n+r-1

    di = IndexedBase('d')
    gi = IndexedBase('g')
    d = Matrix(alpha, 1, lambda i,j: di[i])
    g = Matrix(r, 1, lambda i,j: gi[i])

    V = BT*d
    U = G*g
    M = U.multiply_elementwise(V)
    Y = simplify(AT*M)

    return Y
wincnn.py 文件源码 项目:wincnn 作者: andravin 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def convolutionVerify(n, r, B, G, A):

    di = IndexedBase('d')
    gi = IndexedBase('g')

    d = Matrix(n, 1, lambda i,j: di[i])
    g = Matrix(r, 1, lambda i,j: gi[i])

    V = A*d
    U = G*g
    M = U.multiply_elementwise(V)
    Y = simplify(B*M)

    return Y
test_hyperexpand.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_shifted_sum():
    from sympy import simplify
    assert simplify(hyperexpand(z**4*hyper([2], [3, S('3/2')], -z**2))) \
        == z*sin(2*z) + (-z**2 + S.Half)*cos(2*z) - S.Half
test_hyperexpand.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_formulae():
    from sympy.simplify.hyperexpand import FormulaCollection
    formulae = FormulaCollection().formulae
    for formula in formulae:
        h = formula.func(formula.z)
        rep = {}
        for n, sym in enumerate(formula.symbols):
            rep[sym] = randcplx(n)

        # NOTE hyperexpand returns truly branched functions. We know we are
        #      on the main sheet, but numerical evaluation can still go wrong
        #      (e.g. if exp_polar cannot be evalf'd).
        #      Just replace all exp_polar by exp, this usually works.

        # first test if the closed-form is actually correct
        h = h.subs(rep)
        closed_form = formula.closed_form.subs(rep).rewrite('nonrepsmall')
        z = formula.z
        assert tn(h, closed_form.replace(exp_polar, exp), z)

        # now test the computed matrix
        cl = (formula.C * formula.B)[0].subs(rep).rewrite('nonrepsmall')
        assert tn(closed_form.replace(
            exp_polar, exp), cl.replace(exp_polar, exp), z)
        deriv1 = z*formula.B.applyfunc(lambda t: t.rewrite(
            'nonrepsmall')).diff(z)
        deriv2 = formula.M * formula.B
        for d1, d2 in zip(deriv1, deriv2):
            assert tn(d1.subs(rep).replace(exp_polar, exp),
                      d2.subs(rep).rewrite('nonrepsmall').replace(exp_polar, exp), z)
test_hyperexpand.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_meijerg_formulae():
    from sympy.simplify.hyperexpand import MeijerFormulaCollection
    formulae = MeijerFormulaCollection().formulae
    for sig in formulae:
        for formula in formulae[sig]:
            g = meijerg(formula.func.an, formula.func.ap,
                        formula.func.bm, formula.func.bq,
                        formula.z)
            rep = {}
            for sym in formula.symbols:
                rep[sym] = randcplx()

            # first test if the closed-form is actually correct
            g = g.subs(rep)
            closed_form = formula.closed_form.subs(rep)
            z = formula.z
            assert tn(g, closed_form, z)
            #print closed_form

            # now test the computed matrix
            cl = (formula.C * formula.B)[0].subs(rep)
            assert tn(closed_form, cl, z)
            deriv1 = z*formula.B.diff(z)
            deriv2 = formula.M * formula.B
            for d1, d2 in zip(deriv1, deriv2):
                assert tn(d1.subs(rep), d2.subs(rep), z)
test_hyperexpand.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def test_Mod1_behavior():
    from sympy import Symbol, simplify, lowergamma
    n = Symbol('n', integer=True)
    # Note: this should not hang.
    assert simplify(hyperexpand(meijerg([1], [], [n + 1], [0], z))) == \
        lowergamma(n + 1, z)
test_gosper.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def test_gosper_sum_AeqB_part1():
    f1a = n**4
    f1b = n**3*2**n
    f1c = 1/(n**2 + sqrt(5)*n - 1)
    f1d = n**4*4**n/binomial(2*n, n)
    f1e = factorial(3*n)/(factorial(n)*factorial(n + 1)*factorial(n + 2)*27**n)
    f1f = binomial(2*n, n)**2/((n + 1)*4**(2*n))
    f1g = (4*n - 1)*binomial(2*n, n)**2/((2*n - 1)**2*4**(2*n))
    f1h = n*factorial(n - S(1)/2)**2/factorial(n + 1)**2

    g1a = m*(m + 1)*(2*m + 1)*(3*m**2 + 3*m - 1)/30
    g1b = 26 + 2**(m + 1)*(m**3 - 3*m**2 + 9*m - 13)
    g1c = (m + 1)*(m*(m**2 - 7*m + 3)*sqrt(5) - (
        3*m**3 - 7*m**2 + 19*m - 6))/(2*m**3*sqrt(5) + m**4 + 5*m**2 - 1)/6
    g1d = -S(2)/231 + 2*4**m*(m + 1)*(63*m**4 + 112*m**3 + 18*m**2 -
             22*m + 3)/(693*binomial(2*m, m))
    g1e = -S(9)/2 + (81*m**2 + 261*m + 200)*factorial(
        3*m + 2)/(40*27**m*factorial(m)*factorial(m + 1)*factorial(m + 2))
    g1f = (2*m + 1)**2*binomial(2*m, m)**2/(4**(2*m)*(m + 1))
    g1g = -binomial(2*m, m)**2/4**(2*m)
    g1h = 4*pi -(2*m + 1)**2*(3*m + 4)*factorial(m - S(1)/2)**2/factorial(m + 1)**2

    g = gosper_sum(f1a, (n, 0, m))
    assert g is not None and simplify(g - g1a) == 0
    g = gosper_sum(f1b, (n, 0, m))
    assert g is not None and simplify(g - g1b) == 0
    g = gosper_sum(f1c, (n, 0, m))
    assert g is not None and simplify(g - g1c) == 0
    g = gosper_sum(f1d, (n, 0, m))
    assert g is not None and simplify(g - g1d) == 0
    g = gosper_sum(f1e, (n, 0, m))
    assert g is not None and simplify(g - g1e) == 0
    g = gosper_sum(f1f, (n, 0, m))
    assert g is not None and simplify(g - g1f) == 0
    g = gosper_sum(f1g, (n, 0, m))
    assert g is not None and simplify(g - g1g) == 0
    g = gosper_sum(f1h, (n, 0, m))
    # need to call rewrite(gamma) here because we have terms involving
    # factorial(1/2)
    assert g is not None and simplify(g - g1h).rewrite(gamma) == 0
test_gosper.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def test_gosper_nan():
    a = Symbol('a', positive=True)
    b = Symbol('b', positive=True)
    n = Symbol('n', integer=True)
    m = Symbol('m', integer=True)
    f2d = n*(n + a + b)*a**n*b**n/(factorial(n + a)*factorial(n + b))
    g2d = 1/(factorial(a - 1)*factorial(
        b - 1)) - a**(m + 1)*b**(m + 1)/(factorial(a + m)*factorial(b + m))
    g = gosper_sum(f2d, (n, 0, m))
    assert simplify(g - g2d) == 0


问题


面经


文章

微信
公众号

扫码关注公众号