示例#1
0
文件: clue.py 项目: xjzhaang/CLUE
def rational_reconstruction_sage(a, m):
    """
    Rational number reconstruction implementation borrowed from Sage
    Input
      a and m are integers
    Output
      a "simple" rational number that is congruent a modulo m
    """
    a %= m
    if a == 0 or m == 0:
        return QQ(0, 1)
    if m < 0:
        m = -m
    if a < 0:
        a = m - a
    if a == 1:
        return QQ(1, 1)
    u = m
    v = a
    bnd = math.sqrt(m / 2)
    U = (1, 0, u)
    V = (0, 1, v)
    while abs(V[2]) >= bnd:
        q = U[2] // V[2]
        T = (U[0] - q * V[0], U[1] - q * V[1], U[2] - q * V[2])
        U = V
        V = T
    x = abs(V[1])
    y = V[2]
    if V[1] < 0:
        y *= -1
    if x <= bnd and gcd(x, y) == 1:
        return QQ(y, x)
    raise ValueError(f"Rational reconstruction of {a} (mod {m}) does not exist.")
示例#2
0
def test_SDM_mul():
    A = SDM({0: {0: ZZ(2)}}, (2, 2), ZZ)
    B = SDM({0: {0: ZZ(4)}}, (2, 2), ZZ)
    assert A * ZZ(2) == B
    assert ZZ(2) * A == B

    raises(TypeError, lambda: A * QQ(1, 2))
    raises(TypeError, lambda: QQ(1, 2) * A)
示例#3
0
def test_pickling_polys_polyclasses():
    from sympy.polys.polyclasses import DMP, DMF, ANP

    for c in (DMP, DMP([[ZZ(1)], [ZZ(2)], [ZZ(3)]], ZZ)):
        check(c)
    for c in (DMF, DMF(([ZZ(1), ZZ(2)], [ZZ(1), ZZ(3)]), ZZ)):
        check(c)
    for c in (ANP, ANP([QQ(1), QQ(2)], [QQ(1), QQ(2), QQ(3)], QQ)):
        check(c)
示例#4
0
def test_SDM_convert_to():
    A = SDM({0: {1: ZZ(1)}, 1: {0: ZZ(2), 1: ZZ(3)}}, (2, 2), ZZ)
    B = SDM({0: {1: QQ(1)}, 1: {0: QQ(2), 1: QQ(3)}}, (2, 2), QQ)
    C = A.convert_to(QQ)
    assert C == B
    assert C.domain == QQ

    D = A.convert_to(ZZ)
    assert D == A
    assert D.domain == ZZ
示例#5
0
def get_test_points():
    points=[IMat([QQ(3),QQ(0),QQ(0)]),IMat([QQ(2),QQ(2),QQ(0)]),IMat([QQ(-2),QQ(2),QQ(0)]),IMat([QQ(3,2),QQ(-3,2),QQ(2)]),IMat([QQ(3,2),QQ(3,2),QQ(2)]),IMat([QQ(-3,2),QQ(-3,2),QQ(2)]),IMat([QQ(-3,2),QQ(3,2),QQ(2)]),IMat([QQ(0),QQ(0),QQ(3)])]
    all_points=[]
    for p in points:
        all_points.append(p)
        all_points.append(-p)
    return all_points
示例#6
0
def to_rational(s):
    denom = 1
    extra_num = 1
    if ('E' in s) or ('e' in s):
        s, exp = re.split("[Ee]", s)
        if exp[0] == "-":
            denom = 10**(-int(exp))
        else:
            extra_num = 10**(int(exp))

    frac = s.split(".")
    if len(frac) == 1:
        return QQ(int(s) * extra_num, denom)
    return QQ(int(frac[0] + frac[1]) * extra_num, denom * 10**(len(frac[1])))
示例#7
0
 def evaluate_stack(s):
     op = s.pop()
     if op == "unary -":
         return -evaluate_stack(s)
     if op in "+-*/":
         # note: operands are pushed onto the stack in reverse order
         op2 = evaluate_stack(s)
         op1 = evaluate_stack(s)
         if op == "+":
             if op1.size < op2.size:
                 op1, op2 = op2, op1
             op1 += op2
             return op1
         if op == "-":
             op1 -= op2
             return op1
         if op == "*":
             return op1 * op2
         if op == "/":
             raise NotImplementedError
     if op == "^" or op == "**":
         exp = int(s.pop())
         base = evaluate_stack(s)
         return base.exp(exp)
     if re.match(r"^[+-]?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?$", op):
         return SparsePolynomial.from_const(to_rational(op), varnames)
     return SparsePolynomial(varnames, QQ, {((var_ind_map[op], 1),): QQ(1)})
示例#8
0
def parse_reactions(lines, varnames):
    """
    Input: lines with reactions, each reaction of the form "reactants -> products, rate" and varnames
    Output: the list of corresponding equations
    """
    raw_reactions = []
    var_to_ind = {v: i for i, v in enumerate(varnames)}
    for l in lines:
        if "," not in l:
            continue
        reaction, rate = separate_reation_rate(l)
        lhs, rhs = reaction.split("->")
        raw_reactions.append((lhs.strip(), rhs.strip(), rate.strip()))

    eqs = {v: SparsePolynomial(varnames, QQ) for v in varnames}
    for lhs, rhs, rate in raw_reactions:
        rate_poly = SparsePolynomial.from_string(rate, varnames, var_to_ind)
        ldict = species_to_multiset(lhs)
        rdict = species_to_multiset(rhs)
        monomial = tuple((var_to_ind[v], mult) for v, mult in ldict.items())
        reaction_poly = rate_poly * SparsePolynomial(varnames, QQ,
                                                     {monomial: QQ(1)})
        for v, mult in rdict.items():
            eqs[v] += reaction_poly * mult
        for v, mult in ldict.items():
            eqs[v] += reaction_poly * (-mult)
    return [eqs[v] for v in varnames]
示例#9
0
def test_SDM_lu():
    A = SDM({0: {0: QQ(1), 1: QQ(2)}, 1: {0: QQ(3), 1: QQ(4)}}, (2, 2), QQ)
    L = SDM({0: {0: QQ(1)}, 1: {0: QQ(3), 1: QQ(1)}}, (2, 2), QQ)
    #U = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(-2)}}, (2, 2), QQ)
    #swaps = []
    # This doesn't quite work. U has some nonzero elements in the lower part.
    #assert A.lu() == (L, U, swaps)
    assert A.lu()[0] == L
示例#10
0
def test_SDM_inv():
    A = SDM({0: {0: QQ(1), 1: QQ(2)}, 1: {0: QQ(3), 1: QQ(4)}}, (2, 2), QQ)
    B = SDM({
        0: {
            0: QQ(-2),
            1: QQ(1)
        },
        1: {
            0: QQ(3, 2),
            1: QQ(-1, 2)
        }
    }, (2, 2), QQ)
    assert A.inv() == B
示例#11
0
def test_PrimeIdeal_reduce():
    k = QQ.alg_field_from_poly(Poly(x**3 + x**2 - 2 * x + 8))
    Zk = k.maximal_order()
    P = k.primes_above(2)
    frp = P[2]

    # reduce_element
    a = Zk.parent(to_col([23, 20, 11]), denom=6)
    a_bar_expected = Zk.parent(to_col([11, 5, 2]), denom=6)
    a_bar = frp.reduce_element(a)
    assert a_bar == a_bar_expected

    # reduce_ANP
    a = k([QQ(11, 6), QQ(20, 6), QQ(23, 6)])
    a_bar_expected = k([QQ(2, 6), QQ(5, 6), QQ(11, 6)])
    a_bar = frp.reduce_ANP(a)
    assert a_bar == a_bar_expected

    # reduce_alg_num
    a = k.to_alg_num(a)
    a_bar_expected = k.to_alg_num(a_bar_expected)
    a_bar = frp.reduce_alg_num(a)
    assert a_bar == a_bar_expected
示例#12
0
def test_rref_solve():
    x, y, z = Dummy('x'), Dummy('y'), Dummy('z')

    assert rref_solve(
        [[QQ(25), QQ(15), QQ(-5)], [QQ(15), QQ(18), QQ(0)],
         [QQ(-5), QQ(0), QQ(11)]], [[x], [y], [z]],
        [[QQ(2)], [QQ(3)], [QQ(1)]], QQ) == [[QQ(-1, 225)], [QQ(23, 135)],
                                             [QQ(4, 45)]]
示例#13
0
def test_SDM_rref():
    eye2 = SDM({0: {0: QQ(1)}, 1: {1: QQ(1)}}, (2, 2), QQ)

    A = SDM({0: {0: QQ(1), 1: QQ(2)}, 1: {0: QQ(3), 1: QQ(4)}}, (2, 2), QQ)
    assert A.rref() == (eye2, [0, 1])

    A = SDM({0: {0: QQ(1)}, 1: {0: QQ(3), 1: QQ(4)}}, (2, 2), QQ)
    assert A.rref() == (eye2, [0, 1])

    A = SDM({0: {1: QQ(2)}, 1: {0: QQ(3), 1: QQ(4)}}, (2, 2), QQ)
    assert A.rref() == (eye2, [0, 1])

    A = SDM(
        {
            0: {
                0: QQ(1),
                1: QQ(2),
                2: QQ(3)
            },
            1: {
                0: QQ(4),
                1: QQ(5),
                2: QQ(6)
            },
            2: {
                0: QQ(7),
                1: QQ(8),
                2: QQ(9)
            }
        }, (3, 3), QQ)
    Arref = SDM({
        0: {
            0: QQ(1),
            2: QQ(-1)
        },
        1: {
            1: QQ(1),
            2: QQ(2)
        }
    }, (3, 3), QQ)
    assert A.rref() == (Arref, [0, 1])

    A = SDM(
        {
            0: {
                0: QQ(1),
                1: QQ(2),
                3: QQ(1)
            },
            1: {
                0: QQ(1),
                1: QQ(1),
                2: QQ(9)
            }
        }, (2, 4), QQ)
    Arref = SDM(
        {
            0: {
                0: QQ(1),
                2: QQ(18),
                3: QQ(-1)
            },
            1: {
                1: QQ(1),
                2: QQ(-9),
                3: QQ(1)
            }
        }, (2, 4), QQ)
    assert A.rref() == (Arref, [0, 1])

    A = SDM(
        {
            0: {
                0: QQ(1),
                1: QQ(1),
                2: QQ(1)
            },
            1: {
                0: QQ(1),
                1: QQ(2),
                2: QQ(2)
            }
        }, (2, 3), QQ)
    Arref = SDM({0: {0: QQ(1, 1)}, 1: {1: QQ(1, 1), 2: QQ(1, 1)}}, (2, 3), QQ)
    assert A.rref() == (Arref, [0, 1])
示例#14
0
def test_rref_solve():
    x, y, z = Dummy("x"), Dummy("y"), Dummy("z")

    assert rref_solve(
        [[QQ(25), QQ(15), QQ(-5)], [QQ(15), QQ(18), QQ(0)],
         [QQ(-5), QQ(0), QQ(11)]],
        [[x], [y], [z]],
        [[QQ(2)], [QQ(3)], [QQ(1)]],
        QQ,
    ) == [[QQ(-1, 225)], [QQ(23, 135)], [QQ(4, 45)]]
示例#15
0
def test_SDM_lu_solve():
    A = SDM({0: {0: QQ(1), 1: QQ(2)}, 1: {0: QQ(3), 1: QQ(4)}}, (2, 2), QQ)
    b = SDM({0: {0: QQ(1)}, 1: {0: QQ(2)}}, (2, 1), QQ)
    x = SDM({1: {0: QQ(1, 2)}}, (2, 1), QQ)
    assert A.matmul(x) == b
    assert A.lu_solve(b) == x
示例#16
0
def test_SDM_nullspace():
    A = SDM({0: {0: QQ(1), 1: QQ(1)}}, (2, 2), QQ)
    assert A.nullspace()[0] == SDM({0: {0: QQ(-1), 1: QQ(1)}}, (1, 2), QQ)
示例#17
0
def test_SDM_det():
    A = SDM({0: {0: QQ(1), 1: QQ(2)}, 1: {0: QQ(3), 1: QQ(4)}}, (2, 2), QQ)
    assert A.det() == QQ(-2)
示例#18
0
    specialization_lumped = [dot_product(specialization, var) for var in new_vars]
    lumped_polys_values = [evalp(p, specialization_lumped) for p in lumped_system]

    assert(polys_values_lumped == lumped_polys_values)
    print(test_name + ": lumping is correct")
        
###############################################

if __name__ == "__main__":
    # Example 1
    R = sympy.polys.rings.vring(["x0", "x1", "x2"], QQ)
    polys = [x0**2 + x1 + x2, x2, x1]
    lumping = do_lumping(polys, [x0], print_reduction=False, initial_conditions={"x0" : 1, "x1" : 2, "x2" : 5})
    check_lumping("Example 1", polys, lumping, 2)
    assert lumping["new_ic"] == [QQ(1), QQ(7)]

    # Example 2
    polys = [x1**2 + 4 * x1 * x2 + 4 * x2**2, x1 + 2 * x0**2, x2 - x0**2]
    lumping = do_lumping(polys, [x0], print_reduction=False)
    check_lumping("Example 2", polys, lumping, 2)

    # PP for n = 2
    system = read_system("e2.ode") 
    lumping = do_lumping(
            system["equations"],
            [SparsePolynomial.from_string("S0", system["variables"])], 
            print_reduction=False
    )
    check_lumping("PP for n = 2", system["equations"], lumping, 12)
    
示例#19
0
 def var_from_string(vname, varnames):
     i = varnames.index(vname)
     return SparsePolynomial(varnames, QQ, {((i, 1), ) : QQ(1)})
示例#20
0
def test_LU_solve():
    x, y, z = Dummy('x'), Dummy('y'), Dummy('z')

    assert LU_solve(
        [[QQ(2), QQ(-1), QQ(-2)], [QQ(-4), QQ(6), QQ(3)],
         [QQ(-4), QQ(-2), QQ(8)]], [[x], [y], [z]],
        [[QQ(-1)], [QQ(13)], [QQ(-6)]], QQ) == [[QQ(2, 1)], [QQ(3, 1)],
                                                [QQ(1, 1)]]
示例#21
0
文件: test_sdm.py 项目: thorek1/sympy
def test_SDM_ones():
    A = SDM.ones((1, 2), QQ)
    assert A.domain == QQ
    assert A.shape == (1, 2)
    assert dict(A) == {0: {0: QQ(1), 1: QQ(1)}}
示例#22
0
def test_LU_solve():
    x, y, z = Dummy("x"), Dummy("y"), Dummy("z")

    assert LU_solve(
        [[QQ(2), QQ(-1), QQ(-2)], [QQ(-4), QQ(6), QQ(3)],
         [QQ(-4), QQ(-2), QQ(8)]],
        [[x], [y], [z]],
        [[QQ(-1)], [QQ(13)], [QQ(-6)]],
        QQ,
    ) == [[QQ(2, 1)], [QQ(3, 1)], [QQ(1, 1)]]
示例#23
0
def test_round_two():
    # Poly must be monic, irreducible, and over ZZ:
    raises(ValueError, lambda: round_two(Poly(3 * x**2 + 1)))
    raises(ValueError, lambda: round_two(Poly(x**2 - 1)))
    raises(ValueError, lambda: round_two(Poly(x**2 + QQ(1, 2))))

    # Test on many fields:
    cases = (
        # A couple of cyclotomic fields:
        (cyclotomic_poly(5), DomainMatrix.eye(4, QQ), 125),
        (cyclotomic_poly(7), DomainMatrix.eye(6, QQ), -16807),
        # A couple of quadratic fields (one 1 mod 4, one 3 mod 4):
        (x**2 - 5, DM([[1, (1, 2)], [0, (1, 2)]], QQ), 5),
        (x**2 - 7, DM([[1, 0], [0, 1]], QQ), 28),
        # Dedekind's example of a field with 2 as essential disc divisor:
        (x**3 + x**2 - 2 * x + 8,
         DM([[1, 0, 0], [0, 1, 0], [0, (1, 2), (1, 2)]],
            QQ).transpose(), -503),
        # A bunch of cubics with various forms for F -- all of these require
        # second or third enlargements. (Five of them require a third, while the rest require just a second.)
        # F = 2^2
        (x**3 + 3 * x**2 - 4 * x + 4,
         DM([((1, 2), (1, 4), (1, 4)), (0, (1, 2), (1, 2)), (0, 0, 1)],
            QQ).transpose(), -83),
        # F = 2^2 * 3
        (x**3 + 3 * x**2 + 3 * x - 3,
         DM([((1, 2), 0, (1, 2)), (0, 1, 0), (0, 0, 1)],
            QQ).transpose(), -108),
        # F = 2^3
        (x**3 + 5 * x**2 - x + 3,
         DM([((1, 4), 0, (3, 4)), (0, (1, 2), (1, 2)), (0, 0, 1)],
            QQ).transpose(), -31),
        # F = 2^2 * 5
        (x**3 + 5 * x**2 - 5 * x - 5,
         DM([((1, 2), 0, (1, 2)), (0, 1, 0), (0, 0, 1)],
            QQ).transpose(), 1300),
        # F = 3^2
        (x**3 + 3 * x**2 + 5,
         DM([((1, 3), (1, 3), (1, 3)), (0, 1, 0), (0, 0, 1)],
            QQ).transpose(), -135),
        # F = 3^3
        (x**3 + 6 * x**2 + 3 * x - 1,
         DM([((1, 3), (1, 3), (1, 3)), (0, 1, 0), (0, 0, 1)],
            QQ).transpose(), 81),
        # F = 2^2 * 3^2
        (x**3 + 6 * x**2 + 4,
         DM([((1, 3), (2, 3), (1, 3)), (0, 1, 0), (0, 0, (1, 2))],
            QQ).transpose(), -108),
        # F = 2^3 * 7
        (x**3 + 7 * x**2 + 7 * x - 7,
         DM([((1, 4), 0, (3, 4)), (0, (1, 2), (1, 2)), (0, 0, 1)],
            QQ).transpose(), 49),
        # F = 2^2 * 13
        (x**3 + 7 * x**2 - x + 5,
         DM([((1, 2), 0, (1, 2)), (0, 1, 0), (0, 0, 1)],
            QQ).transpose(), -2028),
        # F = 2^4
        (x**3 + 7 * x**2 - 5 * x + 5,
         DM([((1, 4), 0, (3, 4)), (0, (1, 2), (1, 2)), (0, 0, 1)],
            QQ).transpose(), -140),
        # F = 5^2
        (x**3 + 4 * x**2 - 3 * x + 7,
         DM([((1, 5), (4, 5), (4, 5)), (0, 1, 0), (0, 0, 1)],
            QQ).transpose(), -175),
        # F = 7^2
        (x**3 + 8 * x**2 + 5 * x - 1,
         DM([((1, 7), (6, 7), (2, 7)), (0, 1, 0), (0, 0, 1)],
            QQ).transpose(), 49),
        # F = 2 * 5 * 7
        (x**3 + 8 * x**2 - 2 * x + 6, DM([(1, 0, 0), (0, 1, 0), (0, 0, 1)],
                                         QQ).transpose(), -14700),
        # F = 2^2 * 3 * 5
        (x**3 + 6 * x**2 - 3 * x + 8,
         DM([(1, 0, 0), (0, (1, 4), (1, 4)), (0, 0, 1)],
            QQ).transpose(), -675),
        # F = 2 * 3^2 * 7
        (x**3 + 9 * x**2 + 6 * x - 8,
         DM([(1, 0, 0), (0, (1, 2), (1, 2)), (0, 0, 1)],
            QQ).transpose(), 3969),
        # F = 2^2 * 3^2 * 7
        (x**3 + 15 * x**2 - 9 * x + 13,
         DM([((1, 6), (1, 3), (1, 6)), (0, 1, 0), (0, 0, 1)],
            QQ).transpose(), -5292),
    )
    for f, B_exp, d_exp in cases:
        K = QQ.algebraic_field((f, theta))
        B = K.maximal_order().QQ_matrix
        d = K.discriminant()
        assert d == d_exp
        # The computed basis need not equal the expected one, but their quotient
        # must be unimodular:
        assert (B.inv() * B_exp).det()**2 == 1
示例#24
0
文件: test_sdm.py 项目: thorek1/sympy
def test_SDM_particular():
    A = SDM({0: {0: QQ(1)}}, (2, 2), QQ)
    Apart = SDM.zeros((1, 2), QQ)
    assert A.particular() == Apart
示例#25
0
def parse_reactions(lines, varnames, parser = "sympy"):
    """
    Input: lines with reactions, each reaction of the form "reactants -> products, rate" and varnames
    Output: the list of corresponding equations
    """
    raw_reactions = []
    # var_to_ind = {v : i for i, v in enumerate(varnames)}
    # var_to_sym = {v : symbols(v) for v in varnames}  
    var_dict = _var_dict(tuple(varnames), parser)
    for l in lines:
        if "," not in l:
            continue
        reaction, rate = separate_reation_rate(l)
        lhs, rhs = reaction.split("->")
        raw_reactions.append((lhs.strip(), rhs.strip(), rate.strip()))

    # eqs = {v : SparsePolynomial(varnames, QQ) for v in varnames}
    # eqs = {v : RationalFunction(SparsePolynomial(varnames, QQ), SparsePolynomial.from_const(1, varnames)) for v in varnames}
    # eqs = {v : parse_expr("0", var_to_sym) for v in varnames}
    eqs = {v : _parse("0", varnames, parser) for v in varnames}
    i = 0
    for lhs, rhs, rate in raw_reactions:
        logging.debug(f"Next reaction {i} out of {len(raw_reactions)}")
        i += 1
        # rate_poly = SparsePolynomial.from_string(rate, varnames, var_to_ind)
        # rate_poly = RationalFunction.from_string(rate, varnames, var_to_ind)
        # rate_poly = parse_expr(rate.replace("^", "**"), var_to_sym, transformations=__transformations_parser)
        rate_poly = _parse(rate, varnames, parser)
        ldict = species_to_multiset(lhs)
        rdict = species_to_multiset(rhs)
        # monomial = tuple((var_to_ind[v], mult) for v, mult in ldict.items())
        if(parser == "sympy"):
            monomial = reduce(lambda p,q : p*q, [var_dict[v]**mult for v, mult in ldict.items()])
        elif(parser in ("polynomial", "rational")):
            monomial = SparsePolynomial(varnames, QQ, {tuple((var_dict[v], mult) for v, mult in ldict.items()) : QQ(1)})
        else:
            raise NotImplementedError(f"Parser {parser} not implemented")
        
        # reaction_poly = rate_poly * SparsePolynomial(varnames, QQ, {monomial : QQ(1)})
        reaction_poly = rate_poly * monomial
        for v, mult in rdict.items():
            eqs[v] += reaction_poly * mult
        for v, mult in ldict.items():
            eqs[v] += reaction_poly * (-mult)

    return [eqs[v] for v in varnames]