Пример #1
0
    def gen(self, N=None, model=True):
        '''
        code generator

        '''
        source = self._json_dict["source"]
        if False in [x in self._json_dict["switches"] for x in source]:
            raise ErrorPrint("please check your json file")
        count = 0
        if N:
            s = ''
        while N if N else True:
            switcher = source[count % len(source)]
            switch = self._json_dict["switches"][switcher]
            coin_number = SyC(list(switch.keys()),
                              weights=[Fr(x) for x in list(switch.values())],
                              k=1)
            code = SyC(list(self._json_dict["models"][coin_number[0]].keys()),
                       weights=[
                           Fr(x) for x in list(self._json_dict["models"][
                               coin_number[0]].values())
                       ],
                       k=1)
            if model:
                print(code[0], end='')
                sys.stdout.flush()
            count += 1
            if N:
                s += code[0]
                N -= 1
                if N == 0: break

            time.sleep(0.2)
        return s
Пример #2
0
def parse_proc(proc_file=None, text=None):
    if proc_file is not None:
        infile = open(proc_file)
        text = infile.read()
    orig = text

    # Captures isolated numbers  and fractions.
    str_nums = re.findall(r'\d+[^\w}.\]]|\\frac{\d+}{\d+}', text)

    # Finds numbers in original text and determines what the fractions are.
    nums = []
    for s in str_nums:
        if '\\frac' in s:
            (num, denom) = tuple(re.findall(r'{(\d+)}', s))
            to_add = Fr(int(num), int(denom))
            nums.append(to_add)
            text = text.replace(s, "", 1)
        else:
            text = text.replace(s, s[-1], 1)
            nums.append(Fr(int(s[:-1])))

    # Replaces numbers in original with placeholders.
    for s in str_nums:
        orig = orig.replace(s, "%s") if '\\frac' in s else orig.replace(s, "%s"+s[-1])

    # Creates Proc object.
    proc = Proc(nums[0].numerator, nums[1].numerator, orig, nums)

    return proc
Пример #3
0
    def __bruteforce_seq(self, R: float, eps: float, InfoModel: dict) -> list:
        '''
            how elegant to find N-th extend seq really is a problem
            return list
        '''
        N_th = 1
        while N_th:
            r = []
            for i in range(2**N_th):
                itoHexSting = Utils.DecToHexString(i)
                # maybe is a fixed source without considered time
                if abs(-Lb(
                        Fr(InfoModel["1"])**itoHexSting.count("1") *
                        Fr(InfoModel["0"])**(N_th - itoHexSting.count("1"))) /
                       N_th - self.c_ent.calc()) < eps:
                    r.append(i)
            t = [Utils.DecToHexString(i) for i in r]
            prob = []
            for i in range(len(t)):
                prob.append(Utils.prod([Fr(InfoModel[x]) for x in t[i]]))
            if sum(prob) > 1 - (R - self.c_ent.calc()):

                return r
            else:
                N_th += 1
Пример #4
0
def arithmetic_combos(a, b):
    ans = set([a + b, a * b, a - b, b - a])
    if a != 0:
        ans.add(Fr(b, a))
    if b != 0:
        ans.add(Fr(a, b))
    return ans
Пример #5
0
 def setUp(self):
     self.exColumnVector = ra.RationalVector((10*np.random.rand(5,1)).astype(int))
     self.intMultiply1 = 5 * self.exColumnVector
     self.intMultiply2 = self.exColumnVector * 5
     self.fracMultiply1 = Fr(1,3) * self.exColumnVector
     self.fracMultiply2 = self.exColumnVector * Fr(1,3)
     self.floatMultiply1 = 0.5 * self.exColumnVector
     self.floatMultiply2 = self.exColumnVector * 0.5
Пример #6
0
 def setUp(self):
     self.exMatrix = ra.RationalMatrix((10*np.random.rand(5,5)).astype(int))
     self.intMultiply1 = 5 * self.exMatrix
     self.intMultiply2 = self.exMatrix * 5
     self.fracMultiply1 = Fr(1,3) * self.exMatrix
     self.fracMultiply2 = self.exMatrix * Fr(1,3)
     self.floatMultiply1 = 0.5 * self.exMatrix
     self.floatMultiply2 = self.exMatrix * 0.5
Пример #7
0
 def test_inverse(self):
     invM = ra.inv(self.exMatrix)
     self.assertEqual(invM.value[1,2], Fr(63, 3800))
     self.assertEqual(invM.value[1,4], Fr(-99, 3800))
     self.assertEqual(invM.value[3,3], Fr(1))
     self.assertEqual(invM.value[0,3], Fr(0))
     self.assertEqual(type(invM.value[1,4]), Fr)
     self.assertEqual(type(invM), ra.RationalMatrix)
     self.assertEqual(invM.value.shape, (5, 5))
def bernoli_man(n):
    if (n == 1):
        return Fr(-1, 2)
    A = [0] * (n + 1)
    for x in range(n + 1):
        A[x] = Fr(1, 1 + x)
        for j in range(x, 0, -1):
            A[j - 1] = j * (A[j - 1] - A[j])
    return A[0]
Пример #9
0
def split(v):
    mx = Fr(v.x, 2)
    my = Fr(v.y, 2)
    qx = Fr(v.x, 4)
    qy = Fr(v.y, 4)
    nx = mx - qy
    ny = my - qx
    v1 = vector(nx, ny)
    v2 = vector(v.x - nx, v.y - ny)
    return v1, v2
Пример #10
0
 def setUp(self):
     self.exMatrix = ra.RationalMatrix((10*np.random.rand(5,5)).astype(int))
     self.exMatrix2 = ra.RationalMatrix((10*np.random.rand(5,5)).astype(int))
     self.matAdd1 = self.exMatrix + self.exMatrix2
     self.matAdd2 = self.exMatrix2 + self.exMatrix
     self.intAdd1 = 5 + self.exMatrix
     self.intAdd2 = self.exMatrix + 5
     self.fracAdd1 = Fr(1,3) + self.exMatrix
     self.fracAdd2 = self.exMatrix + Fr(1,3)
     self.floatAdd1 = 0.5 + self.exMatrix
     self.floatAdd2 = self.exMatrix + 0.5
Пример #11
0
 def test_inverse_matmul(self):
     invM = ra.inv(self.exMatrix)
     I1 = invM @ self.exMatrix
     I2 = self.exMatrix @ invM
     
     myEqual = lambda x,y: all(x.value.flat == y.value.flat)
     self.assertTrue(myEqual(I1, I2))
     self.assertEqual(I1.value[2,2], Fr(1))
     self.assertEqual(I1.value[1,2], Fr(0))
     self.assertEqual(type(I1.value[1,4]), Fr)
     self.assertEqual(type(I1), ra.RationalMatrix)
     self.assertEqual(I1.value.shape, (5, 5))
Пример #12
0
 def calc(self):
     '''
         calc entropy of seq
         return H
     '''
     if not self.__probcheck(self.__pl):
         raise ProbError("sum of prob !=1")
     if isinstance(self.__pl, list):
         return sum([-(Fr(i) * Lb(Fr(i))) for i in self.__pl])
     elif isinstance(self.__pl, dict):
         return sum(
             [-(Fr(i) * Lb(Fr(i))) for i in list(self.__pl.values())])
Пример #13
0
 def test_value(self):
     self.assertEqual(self.mulMM.value[1,4], Fr(33,35))
     self.assertEqual(self.mulMM.value[1,3], Fr(0))
     self.assertEqual(self.mulMC.value[1], Fr(9,20))
     self.assertEqual(self.mulMC.value[3], Fr(0))
     self.assertEqual(self.mulCR.value[2,2], Fr(15,28))
     self.assertEqual(self.mulCR.value[2,3], Fr(0))
     self.assertEqual(self.mulRM.value[0][4], Fr(55,49))
     self.assertEqual(self.mulRM.value[0][3], Fr(0))
     self.assertEqual(self.mulRC.value[0], Fr(15,28))
def bernoulli_number(n):
    if n < 50:
        return bernoli_man(n)
    elif (n - 1) % 2 == 0:
        return 0
    else:
        K = Decimal(2 * (n) * factorial(n)) / (2 * math.pi)**n
        primes = prime_sve(n + 1)
        #d is sum of primes
        d = Decimal(1)
        for p in primes:
            if n % (p - 1) == 0:
                d *= p

        N = math.ceil((K * d)**(1.0 / (n - 1)))
        z = 1

        for p in primes:
            if p <= N:
                z *= 1 / (1 - 1 / (p)**n)

        a = (-1)**(n / 2 + 1) * Decimal((d * K * z))

        a = a.to_integral_exact(rounding=ROUND_HALF_EVEN)

        if a == 0:
            a = (-1)**(n / 2 + 1)
        #print(a)
        #print(d)
        return Fr(a / d)
Пример #15
0
def bernoulli(n):
    A = [0] * (n + 1)
    for m in range(n + 1):
        A[m] = Fr(1, m + 1)
        for j in range(m, 0, -1):
            A[j - 1] = j * (A[j - 1] - A[j])
    return A[0]  # (which is Bn)
Пример #16
0
 def bernoulli(self, params):
     A = [0] * (int(params[0]) + 1)
     for m in range(int(params[0]) + 1):
         A[m] = Fr(1, m + 1)
         for j in range(m, 0, -1):
             A[j - 1] = j * (A[j - 1] - A[j])
     return A[0]
Пример #17
0
 def bernoulli2():  # Function taken online to calculate Bernouli sequence
     A, m = [], 0
     while True:
         A.append(Fr(1, m + 1))
         for j in range(m, 0, -1):
             A[j - 1] = j * (A[j - 1] - A[j])
         yield A[0]  # (which is Bm)
         m += 1
Пример #18
0
def bernoulli2():
    A, m = [], 0
    while True:
        A.append(Fr(1, m+1))
        for j in range(m, 0, -1):
          A[j-1] = j*(A[j-1] - A[j])
        yield A[0] 
        m += 1
Пример #19
0
def rat(x, tol):
    """Rational fraction approximation.

    Calculate A and B such that:

    .. math::

      x = \\frac{A}{B} + \\epsilon

    where:

    .. math::

        |\\epsilon| < tol


    .. note:: A, B are of type 'int'
    """
    return Fr(float(x)).limit_denominator(int(1 / float(tol))).numerator, \
        Fr(float(x)).limit_denominator(int(1 / float(tol))).denominator
Пример #20
0
def magnus_coefficients():
    from fractions import Fraction as Fr

    A, m = [], 0
    fct = 1
    while True:
        A.append(Fr(1, m + 1))
        for j in range(m, 0, -1):
            A[j - 1] = j * (A[j - 1] - A[j])
        yield (-1 if m == 1 else +1) * A[0] / fct  # (which is Bm)
        m += 1
        fct *= m
Пример #21
0
 def setUp(self):
     self.exRowVector = ra.RationalVector((10*np.random.rand(1,5)).astype(int))
     self.exRowVector2 = ra.RationalVector((10*np.random.rand(1,5)).astype(int))
     self.exColumnVector = ra.RationalVector((10*np.random.rand(5,1)).astype(int))
     self.exColumnVector2 = ra.RationalVector((10*np.random.rand(5,1)).astype(int))
     
     self.rowVecAdd1 = self.exRowVector + self.exRowVector2
     self.rowVecAdd2 = self.exRowVector2 + self.exRowVector
     self.colVecAdd1 = self.exColumnVector + self.exColumnVector2
     self.colVecAdd2 = self.exColumnVector2 + self.exColumnVector
     self.intRowAdd1 = 5 + self.exRowVector
     self.intRowAdd2 = self.exRowVector + 5
     self.fracRowAdd1 = Fr(1,3) + self.exRowVector
     self.fracRowAdd2 = self.exRowVector + Fr(1,3)
     self.floatRowAdd1 = 0.5 + self.exRowVector
     self.floatRowAdd2 = self.exRowVector + 0.5
     self.intColAdd1 = 5 + self.exColumnVector
     self.intColAdd2 = self.exColumnVector + 5
     self.fracColAdd1 = Fr(1,3) + self.exColumnVector
     self.fracColAdd2 = self.exColumnVector + Fr(1,3)
     self.floatColAdd1 = 0.5 + self.exColumnVector
     self.floatColAdd2 = self.exColumnVector + 0.5
def find_word(message):
    words = re.findall("\w+", message.lower())
    result = []
    table = [[0] * len(words) for i in range(len(words))]
    for i, w1 in enumerate(words):
        coefficents = []
        for j, w2 in enumerate(words):
            coef = Fr(0)
            if i == j:
                continue
            coef += 10 * ((w1[0] == w2[0]) + (w1[-1] == w2[-1]))
            coef += (Fr(min(len(w1), len(w2))) / Fr(max(len(w1), len(w2)))) * 30
            coef += (Fr(len(set(w1).intersection(w2))) / Fr(len(set(w1 + w2)))) * 50
            table[i][j] = coef
            coefficents.append(coef)
        result.append((w1, sum(coefficents) / len(coefficents)))
    # print(dict((w, float(f)) for w, f in result))
    ztable = zip(*table)
    for i, row in enumerate(table):
        print(words[i], [round(float(el), 3) for el in row])
    print([sum(round(float(el), 3) for el in col) for col in ztable])
    return max(result, key=lambda x: (round(x[1], 8), words.index(x[0]))), dict((w, float(f)) for w, f in result)
Пример #23
0
 def bernoulli(self, params):
     t1 = time.time()
     A = [0] * (int(params[0]) + 1)
     for m in range(int(params[0]) + 1):
         A[m] = Fr(1, m + 1)
         for j in range(m, 0, -1):
             A[j - 1] = j * (A[j - 1] - A[j])
     t2 = time.time()
     exectime = t2 - t1
     self.logger.info(
         "===============================    execution time for Bernoulli with parameter  "
         + str(params) + " is:  " + str(exectime))
     return A[0]
def BernoulliNumber(n):
    """
  Generate Bernoulli number
  @param n:  interger (0,1,2,...)
  """
    from fractions import Fraction as Fr
    if n == 1: return -0.5
    A = [0] * (n + 1)
    for m in range(n + 1):
        A[m] = Fr(1, m + 1)
        for j in range(m, 0, -1):
            A[j - 1] = j * (A[j - 1] - A[j])
    return A[0].numerator * 1. / A[0].denominator  # (which is Bn)
def bernoulli(n):
    """
    Calculate the nth Bernoulli number.
    Input:
        n (an integer):  The index of the Bernoulli number to be calculated.
    Output:
        A[0] (a fraction): The nth Bernoulli number.
    Algorithm taken from the following website, unmodified:
    https://rosettacode.org/wiki/Bernoulli_numbers#Python
    """
    A = [0] * (n + 1)
    for m in range(n + 1):
        A[m] = Fr(1, m + 1)
        for j in range(m, 0, -1):
            A[j - 1] = j * (A[j - 1] - A[j])
    return A[0]  # (which is Bn)
Пример #26
0
    def __probcheck(self, infomodel) -> bool:
        """
            Normalization detection
            input:infomodel- src of info
            output: bool
                True:sum=1
                False:other reason
        """
        num = 0
        value_list = infomodel
        if isinstance(infomodel, dict):
            value_list = list(infomodel.values())

        for v in value_list:
            num += float(Fr(v))
        if not num or num != 1.0:
            return False
        return True
Пример #27
0
def main():
#    print(get_general_give_only("proc1.tex", "proc2.tex"))
    
    # [Fr(5), Fr(4), Fr(5), Fr(4), Fr(3, 8), Fr(4), Fr(3, 8), Fr(5, 8), 
    # Fr(1), Fr(1, 2), Fr(1, 2), Fr(2), Fr(2), Fr(5, 8), Fr(2), Fr(1), 
    # Fr(1, 2), Fr(2), Fr(3, 8)] 
    t = time.time()
#    print(find_proc(5, 4, Fr(3,8), 2)) 
#    print(find_proc(9, 4, Fr(7,16), 2))
#    print(find_proc(11, 6, Fr(7,18), 2))
#    print(find_proc(7, 3, Fr(5,12), 1))
#    print(find_proc(8, 3, Fr(4,9), 1))
#    print(find_proc(13, 10, Fr(7,20), 4))
    print(find_proc(31, 13, Fr(21,52), 3)) #466 seconds to <1 second!!
#    print(find_proc(21, 5, Fr(7,15), 2))
#    print(find_proc(34, 15, Fr(13,30), 7))
#    print(find_proc(32, 13, Fr(5,13), 6))
#    print(find_proc(59, 33, Fr(40,99), 16))
    
    print(time.time() - t)
Пример #28
0
 def test_lu_decomposition(self):
     L, U, P = ra.lu(self.exMatrix)
     self.assertEqual(L.value[4,2], Fr(3, 71))
     self.assertEqual(L.value[2,4], Fr(0))
     self.assertEqual(U.value[4,4], Fr(760, 497))
     self.assertEqual(U.value[2,4], Fr(1))
     self.assertEqual(U.value[2,1], Fr(0))
     self.assertEqual(P.value[4,2], Fr(1))
     self.assertEqual(P.value[4,3], Fr(0))
     
     self.assertEqual(type(L.value[1,4]), Fr)
     self.assertEqual(type(L), ra.RationalMatrix)
     self.assertEqual(L.value.shape, (5, 5))
     self.assertEqual(type(U.value[1,4]), Fr)
     self.assertEqual(type(U), ra.RationalMatrix)
     self.assertEqual(U.value.shape, (5, 5))
     self.assertEqual(type(P.value[1,4]), Fr)
     self.assertEqual(type(P), ra.RationalMatrix)
     self.assertEqual(P.value.shape, (5, 5))
Пример #29
0
 def setUp(self):
     self.exMatrix = ra.RationalMatrix(np.zeros((5,5)).astype(int))
     self.exMatrix.value[2,4] = Fr(11,7)
     self.exMatrix.value[1,2] = Fr(3,5)
     
     self.exColumnVector = ra.RationalVector(np.zeros((5,1)).astype(int))
     self.exColumnVector.value[2] = Fr(3,4)
     self.exColumnVector.value[4] = Fr(9,2)
     
     self.exRowVector = ra.RationalVector(np.zeros((1,5)).astype(int))
     self.exRowVector.value[0][2] = Fr(5,7)
     self.exRowVector.value[0][0] = Fr(9,2)
     
     self.mulMM = self.exMatrix @ self.exMatrix
     self.mulMC = self.exMatrix @ self.exColumnVector
     self.mulCR = self.exColumnVector @ self.exRowVector
     self.mulRM = self.exRowVector @ self.exMatrix
     self.mulRC = self.exRowVector @ self.exColumnVector
Пример #30
0
def countPossibilities(start, stop):
    if start == stop:
        return set([start])

    #memoize results, don't repeat work
    if (start, stop) in answers: 
        return answers[(start, stop)]

    currentAnswer = set()
    for index in xrange(start, stop):
        frontSet = countPossibilities(start,index)
        backSet  = countPossibilities(index+1,stop)
        for a in frontSet: #For each pair a,b try all four possible actions.
            for b in backSet:
                currentAnswer.add(a+b)
                currentAnswer.add(a-b)
                currentAnswer.add(a*b)
                if b != 0:
                    currentAnswer.add(Fr(a,b))

    #Don't forget the possibility of turnDigListIntoIntenating digits.
    currentAnswer.add(turnDigListIntoInt(range(start,stop+1))) 
    answers[(start,stop)] = currentAnswer
    return answers[(start,stop)]