Example #1
0
 def _annotate(self, root, weights={}):
     '''Actually annotates d-DNNF with weights'''
     if(str(root.label)[0] == 'A'):
         root.weight = mpq('1')
         for ch in root.children: #can perform IBCP for conditioning               
             root.weight *= self._annotate(ch, weights=weights)
         return root.weight
     elif(str(root.label)[0] == 'O'):
         root.weight = self._annotate(root.children[0], weights=weights) + self._annotate(root.children[1], weights=weights)
         return root.weight
     else:
         try:
             int(root.label)
             if weights and abs(int(root.label)) in weights:
                 if int(root.label) > 0:
                     root.weight = weights[int(root.label)]
                 else:
                     root.weight = mpq('1')-weights[abs(int(root.label))]
             else:
                 root.weight = mpq('0.5')
         except:
             if (str(root.label)[0] == 'F'):
                 root.weight = 0
             elif (str(root.label)[0] == 'T'):                    
                 root.weight = 1
         return root.weight
Example #2
0
def f_lkFiqn(l, k, i, n):
    '''
    This function computes the values of the easy basis f_lk(F_i (q_n)) 
        (level 1 of SG) based on the Splines on Fractals paper.

    Args:
        l, k, i, n: correspond to the indices mentioned in the preceding 
            paragraph.

    Returns:
        values of the easy basis f_lk(F_i (q_n))
    '''
    # Finds the values of pi and qi from the recursion
    arr = big_recursion(l)
    p1 = copy.deepcopy(arr[2, l])
    q1 = copy.deepcopy(arr[3, l])

    # Find the values of easy basis from (5.2) of splines paper
    if i == n and i == k:
        return int(l == 0)
    if i == k and i != n:
        return gm.mpq(p1, (5**l))
    if i == n and i != k:
        return 0
    if k == n and k != i:
        return gm.mpq(p1, (5**l))

    return gm.mpq(q1, (5**l))
Example #3
0
 def annotate(self,root, weights = None):
     '''Computes Model Counts'''
     if(str(root.label)[0] == 'A'):
         root.weight = mpq('1')
         for ch in root.children: #can perform IBCP for conditioning               
             root.weight *= self.annotate(ch, weights=weights)
         return root.weight
     elif(str(root.label)[0] == 'O'):
         root.weight = self.annotate(root.children[0], weights=weights) + self.annotate(root.children[1], weights=weights)
         return root.weight
     else:
         try:
             int(root.label)
             if weights and abs(int(root.label)) in weights:
                 if int(root.label) > 0:
                     root.weight = weights[int(root.label)]
                 else:
                     root.weight = mpq('1')-weights[abs(int(root.label))]
             else:
                 root.weight = mpq('0.5')
         except:
             if (str(root.label)[0] == 'F'):
                 root.weight = 0
             elif (str(root.label)[0] == 'T'):                    
                 root.weight = 1
         return root.weight
Example #4
0
 def __mul__(lhs,rhs):
     if isinstance(rhs,(Number,type(mpz(0)),type(mpq(0,1)))):
         ret = DPolynomial(lhs.Nvar , lhs.Nweight , lhs.weightMat)
         if rhs==0:return ret
         for (m,c) in lhs.coeffs.items():
              ret.coeffs[m] = c*rhs
              ret.weights[m] = lhs.weights[m]
         ret._normalized = False
         return ret
     elif isinstance(lhs,(Number,type(mpz(0)),type(mpq(0,1)))):
         ret = DPolynomial(rhs.Nvar , rhs.Nweight , rhs.weightMat)
         if lhs==0:return ret
         for (m,c) in rhs.coeffs.items():
              ret.coeffs[m] = c*lhs
              ret.weights[m] = rhs.weights[m]
         ret._normalized = False
         return ret
     else:
         ret = DPolynomial(lhs.Nvar , lhs.Nweight , lhs.weightMat)
         for (m1,c1) in lhs.coeffs.items():
            if c1==0:continue
            for (m2,c2) in rhs.coeffs.items():
              if c2==0:continue
              m3 = iadd(m1,m2)
              ret.coeffs[m3] = ret.coeffs.get(m3,0) + (c1*c2)
              ret.weights[m3] = iadd(lhs.weights[m1] , rhs.weights[m2])
     return ret.normalize()
def calculate_babai_optimal_basis():
    """
    Calculate the Babai optimal basis for the zero decomposition lattice L (see Definition 1 of the FourQ paper).
    :return: B = [b1, b2, b3, b4]
    """

    # Note that int(V/r) will give the wrong result, the same applies to math.floor() and round()
    alpha = V // r  # due to V = 0 mod r, which gives alpha = V /r \in Z
    b1 = [
        16 * (-60 * alpha + 13 * r - 10), 4 * (-10 * alpha - 3 * r + 12),
        4 * (-15 * alpha + 5 * r - 13), -13 * alpha - 6 * r + 3
    ]
    b2 = [32 * (5 * alpha - r), -8, 8, 2 * alpha + r]
    b3 = [
        16 * (80 * alpha - 15 * r + 18), 4 * (18 * alpha - 3 * r - 16),
        4 * (-15 * alpha - 9 * r + 15), 15 * alpha + 8 * r + 3
    ]
    b4 = [
        16 * (-360 * alpha + 77 * r + 42), 4 * (42 * alpha + 17 * r + 72),
        4 * (85 * alpha - 21 * r - 77), (-77 * alpha - 36 * r - 17)
    ]

    b1 = list(map(lambda x: mpq(x, 224), b1))
    b2 = list(map(lambda x: mpq(x, 8), b2))
    b3 = list(map(lambda x: mpq(x, 224), b3))
    b4 = list(map(lambda x: mpq(x, 448), b4))

    result = [b1, b2, b3, b4]

    # Compare with expected results (taken from curve4Q on Github)
    expected_results = [basis1, basis2, basis3, basis4]
    for bi, exp_bi in zip(result, expected_results):
        for bij, exp_bij in zip(bi, exp_bi):
            assert int(bij) == exp_bij
    return result
Example #6
0
def beta_array(max_order):
    '''
    Calculates the array of beta_j up to some order

    Args:
        max_order: Maximum order of j to be calculated (should be >= 1)

    Returns: 
        beta_arr: np.array of length (max_order+1) containing the first 
        values of beta up to beta_{max_order}.
    '''

    # alpha's are used in the calculation of beta, so we first calculate
    #   these
    alpha_arr = alpha_array(max_order+2)

    # initialize values of beta_arr
    beta_arr = zeros_gm(max_order + 1, 1)
    beta_arr[0] = gm.mpq(-1,2)

    for j in range(1, max_order+1):
        for l in range(j):
            beta_arr[j] = beta_arr[j] + (3 * (5 ** (j-l)) -
                            5 ** (l + 1) + 6) * alpha_arr[j-l] * beta_arr[l]
        beta_arr[j] = beta_arr[j] * gm.mpq(2 , (15 * (5 ** j - 1)))

    return beta_arr[:, 0]
Example #7
0
def prob(squares, initial_pos):
    rbound = len(squares) - 1
    max_step = len(SEQUENCE) - 1
    q = collections.deque()
    q.append((0, initial_pos, mpq(1)))
    total_prob = mpq(0)
    while q:
        step, pos, p = q.popleft()
        if (squares[pos] and SEQUENCE[step] == "P") or (
            not squares[pos] and SEQUENCE[step] == "N"
        ):
            p *= mpq(2, 3)
        else:
            p *= mpq(1, 3)
        if step == max_step:
            total_prob += p
            continue
        step += 1
        if pos == 0:
            q.append((step, 1, p))
        elif pos == rbound:
            q.append((step, pos - 1, p))
        else:
            p *= mpq(1, 2)
            q.append((step, pos + 1, p))
            q.append((step, pos - 1, p))
    return total_prob
Example #8
0
def square(x, n):
    k = 1
    while k > 0:
        y = gmpy2.sqrt((mpq(x) + mpq(k))**2 - mpq(n))
        if gmpy2.is_integer(y):
            return y, k
        else:
            k += 1
Example #9
0
def __lp_av_score_fct(i, l):
    # l-th root of i
    # l=1 ... Approval Voting
    # l=\infty ... Chamberlin-Courant
    if i == 1:
        return 1
    else:
        return i**mpq(1, l) - (i - 1)**mpq(1, l)
Example #10
0
    def test_default_time_from_fraction(self):
        # assert mocking did no permanent damage
        self.assertIs(gmpy2.mpq, qutypes.TimeType)

        t = qutypes.time_from_fraction(43, 12)
        # your challenge: find a better way
        mpq_type = type(gmpy2.mpq())
        self.assertIsInstance(t, mpq_type)
        self.assertEqual(t, gmpy2.mpq(43, 12))
Example #11
0
def find_d(totient, coprime):
    k = 1
    k = mpq(k)
    d = 2.9
    d = mpq(d)
    while d % 1 != 0:
        d = ((k * totient) + 1) / coprime
        k += 1
    return d
Example #12
0
    def test_default_time_from_float(self):
        # assert mocking did no permanent damage
        self.assertIs(gmpy2.mpq, qutypes.TimeType)

        self.assertEqual(qutypes.time_from_float(123 / 931),
                         gmpy2.mpq(123, 931))

        self.assertEqual(qutypes.time_from_float(1000000 / 1000001, 1e-5),
                         gmpy2.mpq(1))
Example #13
0
def cf2f(cf):
  '''
  Continued fraction to fraction
  '''
  f = g.mpq(0,1)
  for x in reversed(cf):
    try:
      f = 1 / (f+x)
    except ZeroDivisionError:
      return g.mpq(0, 1)
  return 1/f
Example #14
0
def allPrimesDevergesSum():
    from Primes import Primes
    p = Primes()
    primeList = p.getPrimesList(2,10000000)
    import gmpy2
    pInv = gmpy2.mpq(0,1)
    for prime in primeList:
        pInv += gmpy2.mpq(1, prime)
        m = gmpy2.mpfr(pInv)
        print("On prime ", prime, " summ is ", str(m))
        if m > 3:
            break
Example #15
0
def normalizeWeights(weights):
    '''
    Normalizes the weights
    Assumes that either weights defines all positive literal weights between 0 and 1 or
    defines weights for both positive and negative literals.
    '''
    for key in weights:
        if -1*key in weights:
            if key>0:
                weights[key] = mpq(Fraction(weights[key]))/(mpq(Fraction(weights[key])) + mpq(Fraction(weights[key*-1])))
                del weights[-1*key]
            else:
                weights[-1*key] = mpq(Fraction(-1*key))/(mpq(Fraction(weights[key])) + mpq(Fraction(weights[key*-1])))
                del weights[key]
Example #16
0
def main():
    T_distribution = {i: mpq(1, 4) for i in range(1, 5)}
    C_distribution = calculate_sum_distribution(6, T_distribution)
    O_distribution = calculate_sum_distribution(8, C_distribution)
    D_distribution = calculate_sum_distribution(12, O_distribution)
    var = float(calculate_sum_variance(20, D_distribution))
    print(f"{var:.4f}")
Example #17
0
def _get_seq_of_edges_to_add(avg_deg):
    aux = gm.mpq(avg_deg)
    seq_len = int(min(aux.numerator, aux.denominator))
    seq_val = int(max(aux.numerator, aux.denominator) / seq_len)
    edges_seq = [seq_val for i in range(seq_len)]
    edges_seq[0] += 1
    return edges_seq
Example #18
0
def solve(groups):
    times = []
    for D, H, M in groups:
        arrival = M * gmpy2.mpq(360-D, 360)
        period = M
        times.append((arrival, period))
    times.sort()

    if len(times) <= 1:
        return 0
    # print(times)

    min_encounters = float('inf')
    for i, (arrival, period) in enumerate(times):
        # print(arrival, period)
        num_encounters = 0
        for j, (a, p) in enumerate(times):
            if i == j:
                continue
            if a > arrival:
                num_encounters += 1
            else:
                tm = (arrival - a) / p
                # print(a, p, "=>", tm)
                q, r = gmpy2.f_divmod(tm.numerator, tm.denominator)
                num_encounters += q
                if r == 0:
                    # If they're slower and arrive at the same time,
                    # we don't encounter them.
                    if p > period:
                        num_encounters -= 1
            # print("encounters:", num_encounters)
        if num_encounters < min_encounters:
            min_encounters = num_encounters
    return min_encounters
Example #19
0
    def test_is_methods(self):
        self.assertFalse(is_pysmt_fraction(4))
        self.assertTrue(is_pysmt_fraction(Fraction(4)))

        self.assertFalse(is_pysmt_integer(4.0))
        self.assertTrue(is_pysmt_integer(Integer(4)))

        self.assertTrue(is_python_integer(int(2)))
        if PY2:
            self.assertTrue(is_python_integer(long(2)))
        if HAS_GMPY:
            from gmpy2 import mpz
            self.assertTrue(is_python_integer(mpz(1)))

        if HAS_GMPY:
            from gmpy2 import mpz, mpq
            self.assertTrue(is_python_rational(mpz(1)))
            self.assertTrue(is_python_rational(mpq(1)))
        if PY2:
            self.assertTrue(is_python_rational(long(1)))

        self.assertTrue(is_python_rational(pyFraction(5)))
        self.assertTrue(is_python_rational(3))

        self.assertTrue(is_python_boolean(True))
        self.assertTrue(is_python_boolean(False))
Example #20
0
def test_parse():
    A, m, d = reader('data/arrangement.ine')
    assert m == 4
    assert d == 3
    A1 = [[3, -1, -1], [-1, 1, 0], [-1, 0, 1], [3, -2, 0]]
    A1 = [[mpq(a) for a in ai] for ai in A1]
    assert A == A1
Example #21
0
def fetchWeights(weightFile):
    '''either specify all positive literal weights between 0 and 1 or
    specify weights for both positive and negative literals.'''
    data = open(weightFile).read()
    lines = data.strip().split("\n")
    weights = {}
    for line in lines:
        if int(line.split(',')[0])*(-1) in weights:
            if int(line.split(',')[0]) > 0:
                weights[int(line.split(',')[0])] = mpq(Fraction(line.split(',')[1]))/(weights.pop(int(line.split(',')[0])*(-1), None)+mpq(Fraction(line.split(',')[1])))
            else:
                weights[int(line.split(',')[0])*(-1)] = weights[int(line.split(',')[0])*(-1)]/(weights[int(line.split(',')[0])*(-1)]+mpq(Fraction(line.split(',')[1])))
        else:
            weights[int(line.split(',')[0])] = mpq(Fraction(line.split(',')[1]))
    #print(weights)
    return weights
Example #22
0
    def test_real(self):
        """Create Real using different constant types."""
        from fractions import Fraction as pyFraction
        from pysmt.constants import HAS_GMPY

        v1 = (1, 2)
        v2 = 0.5
        v3 = pyFraction(1, 2)
        v4 = Fraction(1, 2)

        c1 = self.mgr.Real(v1)
        c2 = self.mgr.Real(v2)
        c3 = self.mgr.Real(v3)
        c4 = self.mgr.Real(v4)

        self.assertIs(c1, c2)
        self.assertIs(c2, c3)
        self.assertIs(c3, c4)

        if HAS_GMPY:
            from gmpy2 import mpq, mpz
            v5 = (mpz(1), mpz(2))
            v6 = mpq(1, 2)

            c5 = self.mgr.Real(v5)
            c6 = self.mgr.Real(v6)
            self.assertIs(c4, c5)
            self.assertIs(c5, c6)
Example #23
0
 def _smt_query(self, s, constraints):
     self.stats.smt += 1
     if not self.cvc4: # Use z3
         if s.check() == z3.sat:
             self.stats.sat += 1
             # Build and return a Solution instance
             hole_values = self.holes_from_model(s.model())
             soln = self.sketch.partial_evaluate(*hole_values)
             # Make sure the synthesized program is consistent with constraints
             self.sanity_check(soln, constraints)
             return SMTSolution(prog=soln, holes=hole_values)
         else: # unsat
             self.stats.unsat += 1
             self.extract_unsat_core(s.unsat_core(), constraints)
             return None
     else: # Use cvc4
         model,core = cvc4_query_from_z3(s, list(self.Holes._fields), ['p' + str(i) for i in range(len(constraints))])
         if model is not None: # sat
             assert core is None
             self.stats.sat += 1
             hole_values = self.Holes(**{attr : mpq(*model[attr]) for attr in model})
             soln = self.sketch.partial_evaluate(*hole_values)
             # Make sure the synthesized program is consistent with constraints
             self.sanity_check(soln, constraints)
             return SMTSolution(prog=soln, holes=hole_values)
         elif core is not None: # unsat
             assert model is None
             self.stats.unsat += 1
             self.extract_unsat_core(core, constraints)
             return None
         else:
             assert False
Example #24
0
    def test_is_methods(self):
        from fractions import Fraction as pyFraction

        self.assertFalse(is_pysmt_fraction(4))
        self.assertTrue(is_pysmt_fraction(Fraction(4)))

        self.assertFalse(is_pysmt_integer(4.0))
        self.assertTrue(is_pysmt_integer(Integer(4)))

        self.assertTrue(is_python_integer(int(2)))
        if PY2:
            self.assertTrue(is_python_integer(long(2)))
        if HAS_GMPY:
            from gmpy2 import mpz
            self.assertTrue(is_python_integer(mpz(1)))

        if HAS_GMPY:
            from gmpy2 import mpz, mpq
            self.assertTrue(is_python_rational(mpz(1)))
            self.assertTrue(is_python_rational(mpq(1)))
        if PY2:
            self.assertTrue(is_python_rational(long(1)))

        self.assertTrue(is_python_rational(pyFraction(5)))
        self.assertTrue(is_python_rational(3))

        self.assertTrue(is_python_boolean(True))
        self.assertTrue(is_python_boolean(False))
Example #25
0
    def test_real(self):
        """Create Real using different constant types."""
        from fractions import Fraction as pyFraction
        from pysmt.constants import HAS_GMPY

        v1 = (1,2)
        v2 = 0.5
        v3 = pyFraction(1,2)
        v4 = Fraction(1,2)

        c1 = self.mgr.Real(v1)
        c2 = self.mgr.Real(v2)
        c3 = self.mgr.Real(v3)
        c4 = self.mgr.Real(v4)

        self.assertIs(c1, c2)
        self.assertIs(c2, c3)
        self.assertIs(c3, c4)

        if HAS_GMPY:
            from gmpy2 import mpq, mpz
            v5 = (mpz(1), mpz(2))
            v6 = mpq(1,2)

            c5 = self.mgr.Real(v5)
            c6 = self.mgr.Real(v6)
            self.assertIs(c4, c5)
            self.assertIs(c5, c6)
Example #26
0
def tau_array(max_order):
    '''
    Calculates the array of tau_j up to some order (this is 
    originally called t in the Calculus paper)

    Args:
        max_order: Maximum order of j to be calculated (should be >= 1)

    Returns: 
        tau_arr: np.array of length (max_order+1) containing the first 
        values of tau up to tau_{max_order}.

    '''

    tau_arr = zeros_gm(max_order + 1, 1)
    tau_arr[0] = gm.mpq(-1, 2)

    alpha_arr = alpha_array(max_order+1)
    beta_arr = beta_array(max_order)

    for j in range(1, max_order + 1):
        res = beta_arr[j]
        for l in range(j):
            res -= 6*alpha_arr[j+1-l]*tau_arr[l]
        tau_arr[j] = res
    return tau_arr
Example #27
0
def make_hilbert(dim=5):
    return [
        [
            gmpy2.mpq(1, i+j+1)
            for j in range(dim)
        ]
        for i in range(dim)
    ]
Example #28
0
    def ReKeyGen(self, PP, sk_s, pk_b):
        g_k = PP['g_k']
        k = self.k
        g_tk = pk_b**k
        g_sk = g_k**sk_s
        rk_sb = gmpy2.mpq(g_tk, g_sk)

        return rk_sb
Example #29
0
def find_phi(N):
    factors = factorize(N)
    if factors is None:
        return None
    phi = gmpy2.mpq(N)
    for f in factors:
        phi = phi * (1 - 1 / f[0])
    return phi
Example #30
0
 def to_python(self, value):
     if value is None:
         return value
     try:
         return mpq(value)
     except (TypeError, ValueError):
         msg = self.error_messages['invalid'] % str(value)
         raise exceptions.ValidationError(msg)
Example #31
0
def _convergent(coeffs):
    """Compute the convergent of 'coeffs'."""
    f = gmpy2.mpq(0, 1)
    for x in reversed(coeffs):
        try:
            f = 1 / (f + x)
        except ZeroDivisionError:
            return f
    return 1 / f
Example #32
0
def test_sympify_gmpy():
    if HAS_GMPY:
        import gmpy2 as gmpy

        value = sympify(gmpy.mpz(1000001))
        assert value == Integer(1000001) and type(value) is Integer

        value = sympify(gmpy.mpq(101, 127))
        assert value == Rational(101, 127) and type(value) is Rational
Example #33
0
def test_sympify_gmpy():
    if HAS_GMPY:
        import gmpy2 as gmpy

        value = sympify(gmpy.mpz(1000001))
        assert value == Integer(1000001) and type(value) is Integer

        value = sympify(gmpy.mpq(101, 127))
        assert value == Rational(101, 127) and type(value) is Rational
Example #34
0
def pi():
    # https://web.archive.org/web/20150627225748/http://en.literateprograms.org/Pi_with_the_BBP_formula_%28Python%29
    x = 0
    n = 1
    while 1:
        p = mpq((120 * n - 89) * n + 16,
                (((512 * n - 1024) * n + 712) * n - 206) * n + 21)
        x = mod1(16 * x + p)
        n += 1
        yield int(16 * x)
Example #35
0
def norm_f_jk(addr, j, k):
    '''
    This function calculates the value of the normal derivative of the 
        easy basis partial_{n}f_jk at a point on SG addressed by addr. 

    Args:
        j, k: indices mentioned in preceding paragraph.
        addr: address of evaluation point F_w(q_n) given as a string of 
            digits whose first digit is i and whose following digits are 
            those in w.

    Returns:
        value of partial_{n}f_jk(F_w(q_n))
    '''

    # Finds the values of pi and qi from the recursion
    arr = big_recursion(j)
    a1 = copy.deepcopy(arr[0, j - 1])
    b1 = copy.deepcopy(arr[1, j - 1])

    # Base case: partial_{n}f_jk(q_i)
    if len(addr) == 1:
        if (j == 0) and (int(addr[0]) == k):
            return 2
        elif (j == 0) and (int(addr[0]) != k):
            return -1
        elif (j != 0) and (int(addr[0]) == k):
            return a1
        else:
            return b1

    # Inductive case
    last = int(addr[-1])
    addr = addr[:-1]
    outer_sum = 0
    for l in range(j + 1):
        inner_sum = 0
        for n in range(3):
            inner_sum += f_lkFiqn(j - l, k, last, n) * norm_f_jk(addr, l, n)
        inner_sum *= (gm.mpq(1, 5))**l
        outer_sum += inner_sum
    outer_sum *= gm.mpq(5, 3)
    return outer_sum
Example #36
0
 def annotate(self,root, weights = None, maximum=False, minimum=False):
     '''Computes Model Counts'''
     if(str(root.label)[0] == 'A'):
         root.weight = mpq('1')
         for ch in root.children: #can perform IBCP for conditioning
             root.weight *= self.annotate(ch, weights=weights, maximum=maximum, minimum=minimum)
         return root.weight
     elif(str(root.label)[0] == 'O'):
         self.annotate(root.children[0], weights=weights, maximum=maximum, minimum=minimum)
         self.annotate(root.children[1], weights=weights, maximum=maximum, minimum=minimum)
         if (maximum and root.children[0].weight >= root.children[1].weight):
             print("Hey")
             root.weight = root.children[0].weight
             root.children[1].weight = 0 #This will help in sampling
         elif (maximum and root.children[0].weight < root.children[1].weight):
             root.weight = root.children[1].weight
             root.children[0].weight = 0 #This will help in sampling
         elif (minimum and root.children[0].weight <= root.children[1].weight):
             root.weight = root.children[0].weight
             root.children[1].weight = 0 #This will help in sampling
         elif (minimum and root.children[0].weight > root.children[1].weight):
             root.weight = root.children[1].weight
             root.children[0].weight = 0 #This will help in sampling
         else: #This is normal case
             root.weight = root.children[0].weight + root.children[1].weight
         return root.weight
     else:
         try:
             int(root.label)
             if weights and abs(int(root.label)) in weights:
                 if int(root.label) > 0:
                     root.weight = weights[int(root.label)]
                 else:
                     root.weight = mpq('1')-weights[abs(int(root.label))]
             else:
                 root.weight = mpq('0.5')
         except:
             if (str(root.label)[0] == 'F'):
                 root.weight = 0
             elif (str(root.label)[0] == 'T'):
                 root.weight = 1
         return root.weight
Example #37
0
 def __sub__(lhs,rhs):
     ret = DExpression(lhs.Nvar)
     ret.coeffs = copy.deepcopy(lhs.coeffs)
     if isinstance(rhs,DExpression):
         assert(lhs.Nvar==rhs.Nvar)
         for (m,c) in rhs.coeffs.items():
             ret.coeffs[m] = ret.coeffs.get(m,0)-c
     elif isinstance(rhs,(Number,type(mpz(0)),type(mpq(0,1)))):
         ret.coeffs[0] -= rhs
         ret._simplified = lhs._simplified
     return ret.simplify()
Example #38
0
 def __eq__(lhs,rhs):
     if isinstance(rhs,DExpression):
         lhs.simplify()
         rhs.simplify()
         if len(lhs.coeffs)!=len(rhs.coeffs):return False
         for (m,c) in lhs.coeffs.items():
             if not m in rhs.coeffs or rhs.coeffs[m]!=c:return False
         return True
     elif isinstance(rhs,(Number,type(mpz(0)),type(mpq(0,1)))):
         return (list(lhs.coeffs.keys())==[0] and lhs.coeffs[0]==rhs)
     else:
         return False
Example #39
0
 def __add__(lhs , rhs):
     ret = copy.deepcopy(lhs)
     ret._normalized = False
     if isinstance(rhs,(Number,type(mpz(0)),type(mpq(0,1)))):
         m = tuple([0]*lhs.Nvar)
         ret.coeffs[m] = ret.coeffs.get(m,0)+rhs
         ret.weights[m] = tuple([0]*lhs.Nweight)
     elif isinstance(rhs,DPolynomial):
         for (m,c) in rhs.coeffs.items():
             ret.coeffs[m] = ret.coeffs.get(m,0)+c
             ret.weights[m] = rhs.weights[m]
     return ret.normalize()
Example #40
0
 def __mul__(lhs,rhs):
     ret = DExpression(lhs.Nvar)
     if isinstance(rhs,DExpression):
         assert(lhs.Nvar==rhs.Nvar)
         for (m1,c1) in lhs.coeffs.items():
            for (m2,c2) in rhs.coeffs.items():
                c3 = c1*c2
                m3 = im_mul(m1 , m2 , ret.Nvar)
                ret.coeffs[m3] = ret.coeffs.get(m3,0)+c3
     elif isinstance(rhs,(Number,type(mpz(0)),type(mpq(0,1)))):
         for m1 in lhs.coeffs.keys():
             ret.coeffs[m1] = lhs.coeffs[m1]*rhs
     return ret.simplify()
Example #41
0
 def __eq__(lhs , rhs):
     lhs.normalize()
     if isinstance(rhs,DPolynomial):
         rhs.normalize()
         if len(lhs.coeffs)!=len(rhs.coeffs):return False
         if lhs.Nvar!=rhs.Nvar:return False
         for m,c in lhs.coeffs.items():
             if c!=rhs.coeffs.get(m,0):return False
         return True
     elif isinstance(rhs,(Number,type(mpz(0)),type(mpq(0,1)))):
         if len(lhs.coeffs)>1:
             return False
         if len(lhs.coeffs)==0:return (rhs==0)
         m,c = list(lhs.coeffs.items())[0]
         if c==rhs and all([x==0 for x in m]):return True
         return False
# partial unit test for gmpy2 mpq functionality
# relies on Tim Peters' "doctest.py" test-driver
r'''
>>> dir(a)
['__abs__', '__add__', '__bool__', '__class__', '__delattr__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__int__', '__le__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__pos__', '__pow__', '__radd__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__rpow__', '__rsub__', '__rtruediv__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', 'binary', 'denominator', 'digits', 'numerator']
>>>
'''

import gmpy2 as _g, doctest,sys
import fractions
F=fractions.Fraction

__test__={}
a=_g.mpq('123/456')
b=_g.mpq('789/123')
af=F(123,456)
bf=F(789,123)

__test__['compat']=\
r'''
>>> a==af
True
>>> af==a
True
>>> a < af
False
>>> a <= af
True
>>> a > af
False
>>> a >= af
Example #43
0
def test_dup_ff_div_gmpy2():
    try:
        from gmpy2 import mpq
    except ImportError:
        return

    from sympy.polys.domains import GMPYRationalField
    K = GMPYRationalField()

    f = [mpq(1,3), mpq(3,2)]
    g = [mpq(2,1)]
    assert dmp_ff_div(f, g, 0, K) == ([mpq(1,6), mpq(3,4)], [])

    f = [mpq(1,2), mpq(1,3), mpq(1,4), mpq(1,5)]
    g = [mpq(-1,1), mpq(1,1), mpq(-1,1)]
    assert dmp_ff_div(f, g, 0, K) == ([mpq(-1,2), mpq(-5,6)], [mpq(7,12), mpq(-19,30)])
Example #44
0
import gmpy2
import fractions

import sys
try:
    m = sys.hash_info.modulus
except NameError:
    print("new-style hash is not supported")
    sys.exit(0)

for s in [0, m//2, m, m*2, m*m, 7, 13, 19, 87907, 79797, 44*44]:
    for i in range(-10,10):
        for k in [-1, 1, 7, 11, -(2**15), 2**16, 2**30, 2**31, 2**32, 2**33, 2**61, -(2**62), 2**63, 2**64]:
            val = k*(s + i)
            assert hash(val) == hash(gmpy2.mpz(val)), (val, hash(val), hash(gmpy2.mpz(val)))

print("hash tests for integer values passed")

for d in [1, -2, 3, -47, m, m*2, 324, 797080, -979]:
    for s in [0, m//2, m, m*2, m*m]:
        for i in range(-10,10):
            for k in [-1, 1, 7, 11, -(2**15), 2**16, 2**30, 2**31, 2**32, 2**33, 2**61, -(2**62), 2**63, 2**64, 131313164, -4643131646131346460964347]:
                val = k*(s + i)
                if val:
                    assert hash(fractions.Fraction(d,val)) == hash(gmpy2.mpq(d,val)), (d,val,hash(fractions.Fraction(d,val)),hash(gmpy.mpq(d,val)))
                if d:
                    assert hash(fractions.Fraction(val,d)) == hash(gmpy2.mpq(val,d)), (val,d,hash(fractions.Fraction(val,d)),hash(gmpy.mpq(val,d)))


print("hash tests for rational values passed")
Example #45
0
def dnc_nf(p , _G , zflag=False):
    def tip(p):
       return max(p.coeffs.keys())
    if len(p.coeffs)==1:return p
    h,cx = nc_p2zp(p)
    r = DExpression(p.Nvar)
    Nvar = p.Nvar
    G = [p.simplify() for p in _G if p!=0]
    HMG = [(p , tip(p)) for p in G]
    while True:
       m = tip(h)
       if m==0:
           r.coeffs[m] = mpq(h.coeffs[m] , cx)
           break
       c_h = h.coeffs[m]
       if c_h==0:
           del h.coeffs[m]
           continue
       for (p1,m1) in HMG:
           if m<m1:continue
           if m==m1:
               if zflag:
                  c_ptip = p1.coeffs[m1]
                  c_g = gcd(c_ptip , c_h)
                  if c_g<0:c_g = -c_g
                  c_h //= c_g
                  c_ptip //= c_g
                  for m3 in h.coeffs:h.coeffs[m3] *= c_ptip
                  for m3 in p1.coeffs:
                      h.coeffs[m3] = h.coeffs.get(m3,0) - c_h*p1.coeffs[m3]
                  cx *= c_ptip
               else:
                  ct = mpq((c_h.numerator)*(p1.coeffs[m1].denominator) , (c_h.denominator)*(p1.coeffs[m1].numerator))
                  assert(ct*p1.coeffs[m1]==c_h),(ct,c_h,p1.coeffs[m1])
                  h -= p1*ct
               assert(h.coeffs.get(m,0)==0),(h.coeffs,m,p1.coeffs,zflag)
               break
           rem = im_div_with_deg(m , m1 , Nvar)
           if rem!=None:
              c_ptip = p1.coeffs[m1]
              um,vm,udeg,vdeg = rem
              if zflag:
                 c_g = gcd(c_ptip , c_h)
                 if c_g<0:c_g = -c_g
                 c_h //= c_g
                 c_ptip //= c_g
                 cx *= c_ptip
                 if c_ptip!=1:
                    for m3 in h.coeffs:
                        h.coeffs[m3] *= c_ptip
                 for (m2,c2) in p1.coeffs.items():
                     deg2 = ideg(m2 , Nvar)
                     pu,pc,pv = Nvar**udeg,Nvar**deg2,Nvar**vdeg
                     m3 = pv*(m2-(pc-1)//(Nvar-1))+(vm-(pv-1)//(Nvar-1))
                     m3 = (pu*pc*pv-1)//(Nvar-1) + (pc*pv)*(um-(pu-1)//(Nvar-1)) + m3
                     c4 = h.coeffs.get(m3,0) - c_h*c2
                     if c4!=0 or m3==0:
                        h.coeffs[m3] = c4
                     elif m3 in h.coeffs:
                        del h.coeffs[m3]
              else:
                 for (m2,c2) in p1.coeffs.items():
                    deg2 = ideg(m2 , Nvar)
                    pu,pc,pv = Nvar**udeg,Nvar**deg2,Nvar**vdeg
                    m3 = pv*(m2-(pc-1)//(Nvar-1))+(vm-(pv-1)//(Nvar-1))
                    m3 = (pu*pc*pv-1)//(Nvar-1) + (pc*pv)*(um-(pu-1)//(Nvar-1)) + m3
                    #assert(m3==im_mul(um , im_mul(m2, vm,Nvar) , Nvar)),(m2,um,vm,m3)
                    ct = mpq(c_h*c2 , c_ptip)
                    c4 = h.coeffs.get(m3,0) - ct
                    assert(ct*c_ptip==c_h*c2)
                    if c4!=0 or m3==0:
                        h.coeffs[m3] = c4
                    elif m3 in h.coeffs:
                        del h.coeffs[m3]
              #assert(im_mul(um , im_mul(m1,vm,Nvar),Nvar)==m)
              #assert(tip(h)<m),(tip(h),m)
              break
       else:
           del h.coeffs[m]
           r.coeffs[m] = mpq(c_h,cx)
    r.coeffs = dict([(k,Fraction(int(v.numerator),int(v.denominator))) for (k,v) in r.coeffs.items()])
    return r
Example #46
0
 def __rmul__(rhs,lhs):
     if isinstance(lhs,DExpression):
         return (lhs*rhs)
     elif isinstance(lhs,(Number,type(mpz(0)),type(mpq(0,1)))):
         return (rhs*lhs)
Example #47
0
 def __div__(lhs,rhs):
     if isinstance(rhs,(Number,type(mpz(0)),type(mpq(0,1)))):
        return lhs*Fraction(1,rhs)
     else:
        assert(False),("invalid division {0}/{1}".format(str(lhs),str(rhs)))
Example #48
0
 def __rsub__(rhs,lhs):
     if isinstance(lhs,DExpression):
         return (lhs-rhs)
     elif isinstance(lhs,(Number,type(mpz(0)),type(mpq(0,1)))):
         return (-rhs+lhs)
Example #49
0
 def mp2py(r):
     if isinstance(r,Number):
        return r
     elif isinstance(r,(type(mpz(0)),type(mpq(0,1)))):
        return Fraction(int(r.numerator) , int(r.denominator))
# relies on Tim Peters' "doctest.py" test-driver
r"""
>>> filter(lambda x: not x.startswith('__'), dir(f))
['as_integer_ratio', 'as_mantissa_exp', 'as_simple_fraction', 'conjugate', 'digits', 'imag', 'is_integer', 'precision', 'rc', 'real']
>>>
"""
try:
    import decimal as _d
except ImportError:
    _d = None

import gmpy2 as _g, doctest, sys

__test__ = {}
f = _g.mpfr("123.456")
q = _g.mpq("789123/1000")
z = _g.mpz("234")
if _d:
    d = _d.Decimal("12.34")

__test__[
    "elemop"
] = r"""
>>> print _g.mpz(23) == _d.Decimal(23)
True
>>> print _g.mpz(d)
12
>>> print _g.mpq(d)
617/50
>>> print _g.mpfr(d)
12.34
Example #51
0
def dp_nf(p , G , zflag=False):
    if not zflag and cgb!=None:
       h,c0 = p2zp(p)
       r_coeffs,r_weights = cgb.cx_dp_nf(h , G)
       r = DPolynomial(p.Nvar , p.Nweight , p.weightMat)
       r.coeffs = r_coeffs
       r.weights = r_weights
       r.coeffs = dict([(k,Fraction(int(val.numerator),int(val.denominator*c0))) for (k,val) in r_coeffs.items()])
       return r
    def tdeg(p):
        return max([sum(m) for m in p.coeffs.keys()])
    h,c0 = p2zp(p)
    Nweight = p.Nweight
    r = DPolynomial(h.Nvar , h.Nweight , h.weightMat)
    HMG = [(p.normalize() , p.tip , tdeg(p)) for p in G if p!=0]
    if h==0:return r
    while True:
        h._tip = None
        m = h.tip
        if len(h.coeffs)==0:break
        c_h = h.coeffs[m]
        if c_h==0:
            del h.coeffs[m]
            del h.weights[m]
            continue
        deg_m = sum(m)
        if deg_m==0:
            r.coeffs[m] = c_h
            r.weights[m] = h.weights[m]
            break
        for (p1,m1,tdeg1) in HMG:
            if tdeg1>deg_m:continue
            rem = idiv(m,m1)
            if rem==None:continue
            w_rem = isub(h.weights[m] , p1.weights[m1])
            c1 = p1.coeffs[m1]
            if zflag:
               c_g = gcd(c1 , c_h)
               if c_g<0:c_g = -c_g
               c_h //= c_g
               c1 //= c_g
               if c1!=1:
                  for m3 in h.coeffs:
                     h.coeffs[m3] *= c1
               for (m2,c2) in p1.coeffs.items():
                  m3 = iadd(rem , m2)
                  c4 = (c2*c_h)
                  if not m3 in h.weights:
                     h.weights[m3] = iadd(p1.weights[m2] , w_rem)
                     h.coeffs[m3] = -c4
                  elif h.coeffs[m3]==c4:
                     del h.coeffs[m3]
                     del h.weights[m3]
                  else:
                     h.coeffs[m3] = h.coeffs[m3] - c4
               if c1!=1:
                  for m3 in r.coeffs:
                     r.coeffs[m3] *= c1
            else:  #-- inefficient
               mx = DPolynomial(h.Nvar , h.Nweight , h.weightMat)
               cx = mpq(c_h.numerator*c1.denominator,c1.numerator*c_h.denominator)
               assert(c1*cx==c_h)
               mx.coeffs[rem] = cx
               mx.weights[rem] = w_rem
               h = h - mx*p1
            break
        else:
            del h.coeffs[m]
            r.weights[m] = h.weights[m]
            del h.weights[m]
            r.coeffs[m] = c_h
    r.coeffs = dict([(k,Fraction(int(val.numerator),int(val.denominator))) for (k,val) in r.coeffs.items()])
    return r
# partial unit test for gmpy/decimal interoperability
# relies on Tim Peters' "doctest.py" test-driver
r'''
>>> dir(f)
['__abs__', '__add__', '__bool__', '__ceil__', '__class__', '__delattr__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__int__', '__le__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__pos__', '__pow__', '__radd__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__rpow__', '__rsub__', '__rtruediv__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', 'binary', 'conjugate', 'digits', 'imag', 'is_inf', 'is_integer', 'is_lessgreater', 'is_nan', 'is_number', 'is_regular', 'is_signed', 'is_unordered', 'is_zero', 'precision', 'rc', 'real']
>>>
'''
try: import decimal as _d
except ImportError: _d = None

import gmpy2 as _g, doctest, sys
__test__={}
f=_g.mpfr('123.456')
q=_g.mpq('789123/1000')
z=_g.mpz('234')
if _d:
    d=_d.Decimal('12.34')
    fd=_d.Decimal('123.456')
    qd=_d.Decimal('789.123')
    zd=_d.Decimal('234')

__test__['compat']=\
r'''
>>> f == fd
True
>>> fd == f
True
>>> q == qd
True
>>> qd == q
True
Example #53
0
except ImportError as ex:
    if ENV_USE_GMPY is True:
        raise PysmtImportError(str(ex))

if ENV_USE_GMPY is False:
    # Explicitely disable GMPY
    USE_GMPY = False
elif ENV_USE_GMPY is True:
    # Explicitely enable GMPY
    USE_GMPY = True
else:
    # Enable GMPY if they are available
    USE_GMPY = HAS_GMPY

if HAS_GMPY:
    mpq_type = type(mpq(1, 2))
    mpz_type = type(mpz(1))
else:
    mpq_type = None
    mpz_type = None

#
# Fractions using GMPY2
#

from fractions import Fraction as pyFraction

if USE_GMPY:
    Fraction = mpq
else:
    Fraction = pyFraction
Example #54
0
def mpq_from_mpf(value):
    if hasattr(value, 'as_integer_ratio'):
        return mpq(*value.as_integer_ratio())
    raise NotImplementedError