示例#1
0
 def __str__(self):
     if self.terms == {}:
         return "Dimensionless"
     dummyEquation = Equation()
     dummyEquation.terms = self.terms
     dummyEquation.coefficient = 1
     return equationToString(dummyEquation)
示例#2
0
    def set_table(self, X, Y, n):
        self.__X = copy.copy(X)
        self.__Y = copy.copy(Y)
        self.__n = n

        A_elems = []
        B_elems = []

        for k in range(n + 1):
            for i in range(n + 1):
                coef = 0

                for x in X:
                    coef += x**(k + i)

                A_elems.append(coef)

            b = 0

            for x, y in zip(X, Y):
                b += y * x**k

            B_elems.append(b)

        A = Matrix(n + 1, elems=A_elems)
        B = Matrix(n + 1, 1, B_elems)

        self.A = A
        self.B = B

        eq = Equation(A, B)

        self.__a = eq.analytic_solution().to_list()
示例#3
0
def ordered_question_list(lhs, rhs):
    """take the lhs and rhs and produce an ordered list of questions"""
    result = []
    for l_n in lhs:
        for r_n in rhs:
            result.append(Equation(l_n, OPERATION, r_n))
    return result
示例#4
0
    def parse_equation(string):
        assert type(string) == str

        tokenized = Tokenizer.tokenize(string)
        if not(Parser.is_equation(tokenized)):
            raise ParserException('Input to parse_equation is not an equation: {}'.format(str(tokenized)))

        lhs = list()
        rhs = list()
        before_equals = True
        for token in tokenized:
            if before_equals:
                if token.token_type == TokenType.EQUALS:
                    before_equals = False
                else:
                    lhs.append(token)
            else:
                rhs.append(token)

        assert len(lhs) > 0
        assert len(rhs) > 0

        lhs = Parser(lhs).parse()
        rhs = Parser(rhs).parse()
        return Equation(lhs, rhs)
示例#5
0
def generate_equation_2d():

    terms = []
    for i in range(4):
        for j in range(4):
            terms.append(Term(1, (i, j)))
    return Equation(*terms)
示例#6
0
def parse_system(eqs):
    '''
        Parse an array of lin dif eq, and create the corresponding n-dimensional equation X' = AX + O(E)
    '''
    system_vars, system = [], {}
    for eq in eqs:
        e = parse_equation(eq)
        if e['var'] not in system_vars:
            system_vars.append(e['var'])
        for v in e['params']:
            if v not in system_vars:
                system_vars.append(v)
        system[e['var']] = e

    system_mat, system_error = [], []
    for v in system_vars:
        eq_line = []
        for p in system_vars:
            if p in system[v]['params']:
                eq_line.append(system[v]['params'][p])
            else:
                eq_line.append(0)
        system_mat.append(eq_line)
        system_error.append(system[v]['error'].toList())

    return Equation(np.transpose(np.array(system_vars)), np.array(system_mat),
                    np.array(system_error))
示例#7
0
def solve_equ(input):
    input = re.sub(r'\s+', ' ', input)
    solution = 'Equation: {}\n'.format(input)
    input = re.sub(r'\s+', '', input)
    input = input.replace('+-', '-')
    input = input.replace('-+', '-')
    input = input.replace('--', '+')
    input = input.replace('++', '+')

    # Check the count of equal sign
    equals_count = input.count('=')
    if equals_count != 1:
        return 'Wrong format: found {} equal signs'.format(equals_count)

    # Simplify both terms of the equation
    equation = Equation(input)
    if not equation.check_terms():
        return 'Wrong format: check that you properly formatted the equation'
    if not equation.get_reduced_form():
        return ('Reduced form: 0 * X^0 = 0\n' + 'Polynomial degree: 0\n' +
                'All real numbers are solution')

    solution += 'Reduced form: {}= 0\n'.format(equation.reduced_form)
    solution += 'Polynomial degree: {}\n'.format(equation.get_degree())
    # Check degree
    if equation.degree > 2:
        return (re.sub(r'\.0 ', ' ', solution) +
                'The polynomial degree is stricly greater than 2' +
                ', sorry I can\'t solve it.')
    elif equation.degree == 0:
        return re.sub(r'\.0 ', ' ', solution) + 'Equation is invalid'

    solution += equation.solve()
    return re.sub(r'\.0 ', ' ', solution)
示例#8
0
def main():

    # User input
    while True:
        try:
            a = int(
                input(
                    'What is the "a" value of your equation? (in standard form):\n'
                ))
            b = int(input('"b" value? (in standard form):\n'))
            c = int(input('"c" value? (in standard form):\n'))
            break

        except:
            pass

    # Equation class
    equation = Equation((a, b, c))

    standard_form = equation.get_standard_form()
    vertex_form = equation.get_vertex_form()
    a, b, c = equation.values
    x1, x2 = equation.get_zeros()
    x, y = equation.get_vertex()

    print("""
    [+] Standard Form = {}\n
    [+] Vertex Form = {}\n
    [+] 1st zero/root = {}\n
    [+] 2nd zero/root = {}\n
    [+] Vertex = {}\n
    [+] AOS: x = {}""".format(standard_form, vertex_form, x1, x2, (x, y), x))

    graph(equation)
示例#9
0
    def __implicit(self, middle_coefs, A_borders, B_borders):
        Ut = self.__get_first_two_layaers()

        for k in range(2, self.n_t_steps):
            t = k * self.t_step

            sqr_x_step = self.x_step**2

            A_coefs = A_borders[0]

            u_prev = Ut[-1]

            B_coefs = [B_borders[0](u_prev, t)]

            A_coefs += middle_coefs.A * (self.n_x_steps - 2)

            B_coefs += [
                middle_coefs.B_functor(u_prev, Ut[-2], j)
                for j in range(1, self.n_x_steps - 1)
            ]

            A_coefs.extend(A_borders[1])

            B_coefs.append(B_borders[1](u_prev, t))

            A = TriDiagonalMatrix(self.n_x_steps, A_coefs)
            B = Matrix(self.n_x_steps, 1, elems=B_coefs)

            u_curr = Equation(A, B).sweep_method().to_list()

            Ut.append(u_curr)

        return Ut
示例#10
0
def practice():  #doesnt work
    print('Welcome to the chemical equation practice tool.')
    f = open('samples.txt', 'r')
    samples_list = []
    print('Enter a number between 1 and 5 to fetch a problem to solve')
    sample_search = input()
    for row in f:
        (k, v) = row.split(':', 1)
        if k == sample_search:
            print(v)
            unbalanced = v
            print(
                'Try to balance this equation. Your answer\nshould look something like this\n2H2 + O2 = 2H2O '
            )
            attempt = input()
            equation = Equation(v)
            correct = equation.balance()
            if correct == attempt:
                print('Well done! That is the correct answer!')
                print(
                    'Would you like to try another problem? Enter 1 for yes 2 for no.'
                )
                answer = input()
                if answer == '1':
                    practice()
                if answer == 2:
                    print('Thanks for practicing!')
                    input()
            if equation != attempt:
                print(
                    'Oops... that isn\'t correct.. But heres the correct one...'
                )
                print(correct)

    f.close()
示例#11
0
def get_fn(l, var):
    eq = Equation()
    var = [""] + var
    for i in range(len(var)):
        if var[i] == "" and i != 0:
            continue
        eq += EqElement(-l[i].calc(), {var[i]: 1})
    return eq
示例#12
0
    def apply(self, equation):
        assert isinstance(equation, Equation)
        assert self.is_applicable_to(equation)

        assert len(equation.lhs.arguments) == 2
        operand = equation.lhs.arguments[1]
        lhs = equation.lhs.arguments[0]
        rhs = Operation(self._inverse_type, [equation.rhs, operand])
        return Equation(lhs, rhs)
示例#13
0
    def __calc_next(self, u_prev, k, stage_k, A_coefs, calc_B, A_coefs_border,
                    calc_B_border, order, exceptions):
        if order == 1:
            ordered = [self.N2, self.N1]
            h = self.h2
            u_cur = [[] for _ in range(self.N1)]
        elif order == 2:
            ordered = [self.N1, self.N2]
            h = self.h1
            u_cur = []
        else:
            raise NotImplementedError

        shift = int(bool(exceptions))

        for i in range(shift, ordered[0] - shift):
            A = list(A_coefs_border[0])
            B = [calc_B_border[0](h * i, self.dt * stage_k)]

            for j in range(1, ordered[1] - 1):
                A.extend(A_coefs)
                B.append(calc_B(u_prev, i, j, k))

            A.extend(A_coefs_border[1])
            B.append(calc_B_border[1](h * i, self.dt * stage_k))

            A = TriDiagonalMatrix(ordered[1], A)
            B = Matrix(ordered[1], 1, B)

            solution = Equation(A, B).sweep_method().to_list()

            if order == 1:
                for i, el in enumerate(solution):
                    u_cur[i].append(el)
            else:
                u_cur.append(solution)

        if exceptions:
            if order == 1:
                for i, el in enumerate(u_cur):
                    begin = exceptions[0](el, i, stage_k)
                    end = exceptions[1](el, i, stage_k)
                    el.insert(0, begin)
                    el.append(end)
            else:
                begin = []
                end = []

                for j in range(len(u_cur[0])):
                    begin.append(exceptions[0](u_cur[0], j, stage_k))
                    end.append(exceptions[1](u_cur[-1], j, stage_k))

                u_cur.insert(0, begin)
                u_cur.append(end)

        return u_cur
示例#14
0
def main():
    if len(sys.argv) == 1:
        error("Missing input")
    eq = Equation(sys.argv[1])
    eq.parse_equation()
    eq.powers_right = eq.create_dict(resolve_rpn(create_rpn(eq.tokens_right)))
    eq.powers_left = eq.create_dict(resolve_rpn(create_rpn(eq.tokens_left)))
    eq.reduce_equation()
    eq.print_reduced_equation()
    eq.solve_equation()
    def __init__(self, size=0, coefficients=0, points=[]):
        if coefficients == 0:
            self.coefficients = self.generateRandom(size)
            self.size = size
        else:
            self.coefficients = coefficients
            self.size = len(coefficients)

        self.equation = Equation(self.coefficients)
        self.points = points
示例#16
0
    def test_equation(self):

        two = Operation(OperationType.POSITIVE(), [Variable(2)])
        negative_x = Operation(OperationType.NEGATIVE(), [Variable('x')])
        lhs = Operation(OperationType.TIMES(), [two, negative_x])

        rhs = Variable(3.1415)

        eq = Equation(lhs, rhs)

        verify(str(eq), self.reporter)
示例#17
0
    def test_equation_cancellation_with_negative(self):

        lhs = Parser(Tokenizer.tokenize('x + -4')).parse()
        rhs = Parser(Tokenizer.tokenize('y')).parse()
        equation = Equation(lhs, rhs)

        addition_cancellation = EquationCancellation(OperationType.PLUS(),
                                                     OperationType.MINUS())

        self.assertTrue(addition_cancellation.is_applicable_to(equation))
        result = addition_cancellation.apply(equation)
        verify(str(result), self.reporter)
示例#18
0
    def test_equation_cancellation_is_applicable(self):

        lhs = Parser(Tokenizer.tokenize('x + 4')).parse()
        rhs = Parser(Tokenizer.tokenize('y')).parse()
        equation = Equation(lhs, rhs)

        addition_cancellation = EquationCancellation(OperationType.PLUS(),
                                                     OperationType.MINUS())

        self.assertTrue(addition_cancellation.is_applicable_to(equation))
        flipped = equation.flip()
        self.assertFalse(addition_cancellation.is_applicable_to(flipped))
示例#19
0
    def test_equation_cancellation(self):

        lhs = Parser(Tokenizer.tokenize('x * 4')).parse()
        rhs = Parser(Tokenizer.tokenize('y')).parse()
        equation = Equation(lhs, rhs)

        multiplication_cancellation = EquationCancellation(
            OperationType.TIMES(), OperationType.DIVIDE())

        self.assertTrue(multiplication_cancellation.is_applicable_to(equation))
        result = multiplication_cancellation.apply(equation)
        verify(str(result), self.reporter)
示例#20
0
    def __build_func__(self):
        X = self.__X
        Y = self.__Y

        h = [X[i] - X[i - 1] for i in range(1, len(X))]

        A_elems = [2 * (h[0] + h[1]), h[1]]
        B_elems = [3 * ((Y[2] - Y[1]) / h[1] - (Y[1] - Y[0]) / h[0])]

        for i in range(2, len(h) - 1):
            A_elems.append(h[i - 1])
            A_elems.append(2 * (h[i - 1] + h[i]))
            A_elems.append(h[i])

            B_elems.append(3 * ((Y[i + 1] - Y[i]) / h[i] -
                                (Y[i] - Y[i - 1]) / h[i - 1]))

        A_elems.append(h[-2])
        A_elems.append(2 * (h[-2] + h[-1]))

        B_elems.append(3 * ((Y[-1] - Y[-2]) / h[-1] - (Y[-2] - Y[-3]) / h[-2]))

        triA = TriDiagonalMatrix(len(h) - 1, A_elems)
        B = Matrix(len(h) - 1, 1, B_elems)

        self.triA = triA
        self.B = B

        tri_equation = Equation(triA, B)
        tri_solution = tri_equation.sweep_method()

        a = Y[:-1]

        c = [0]
        c.extend(tri_solution.to_list())

        b = []
        d = []
        for i in range(len(h) - 1):
            b.append((Y[i + 1] - Y[i]) / h[i] - 1 / 3 * h[i] *
                     (c[i + 1] + 2 * c[i]))

            d.append((c[i + 1] - c[i]) / 3 / h[i])

        b.append((Y[-1] - Y[-2]) / h[-1] - 2 / 3 * h[-1] * c[-1])

        d.append(-c[-1] / 3 / h[-1])

        self.__a = a
        self.__b = b
        self.__c = c
        self.__d = d
示例#21
0
 def apply_function(equation):
     if equation.lhs.operation_type.arity == 0:
         equation = equation.flip()
     if (equation.rhs.operation_type.arity
             == 0) and (equation.rhs.operation_type.symbol == '0'):
         homogenized = equation.lhs
     else:
         homogenized = Operation(OperationType.MINUS(),
                                 [equation.lhs, equation.rhs])
     collected = CollectedTerms.try_parse_expression(homogenized)
     if collected is None:
         return equation
     collected = collected.as_expression
     return Equation(collected, Operation(Variable(0)))
示例#22
0
def main():
  #Initialisation des variables
  hypothese = ['A','B','D']
  systeme = [Equation(['A','B'], 'X'), Equation(['C','E','D'], 'F'),Equation(['X','D'], 'Z')]
  
  #Affichage de l'hypothèse initiale
  print('Hypothèse initiale: ' + str(hypothese))
    
  #Pour chaque H de Hypothèses faire
  for h in hypothese: 
    
    #Pour chaque equation E de S faire
    for e in systeme:
      #Si H appartient à premisse de E alors supprimer H de premisse de E fsi
      if h in e.premisse:
        e.premisse.remove(h)

      #Si vide(premisse de E) alors ajouter conclusion de E à Hypothese fsi
      if e.premisse == [] and e.conclusion not in hypothese:
        hypothese.append(e.conclusion)    
  
  #Affichage de l'hypothèse finale
  print('Hypothèse finale:   ' + str(hypothese))
示例#23
0
    def solve(cls, equations):
        unified, unknowns = cls.unify_unknowns(equations)
        # At this point all substitution is finished so simplify() is safe
        simplified = [cls.simplify(eq.full) for eq in unified]
        sol_set = linsolve(simplified, unknowns)
        if sol_set.is_EmptySet:
            return None

        # The output of linsolve is either empty set or a set of size 1
        raw_sol = list(sol_set)[0]
        sol = dict()
        for i, u in enumerate(unknowns):
            sol[u] = Equation(raw_sol[i])

        return sol
示例#24
0
文件: main.py 项目: nbeny/ComputorV1
def main(argv):
    EquationString = Equation()
    print('__________________________________________')
    print('                             ________     |\\\\     V0.1  DoctorDJO')
    print('                            |License |    | \\\\')
    print('  _____                     |equation|    |  \\\\')
    print(' |     |  (((        .--.   |________|    |')
    print(' |DrDJO| ~OvO~ __   (////)                |       The only possibility of calcul is \'+\' and \'-\'.')
    print(' |     | ( _ )|==|   \\__/                 |       * is accepted but will apply an error or a power of.')
    print(' |o    |  \\_/ |_(|  /    \\   _______      |')
    print(' |     | //|\\\\   \\\\//|  |\\\\  |__o__|      |')
    print(' |   __|//\\_/\\\\ __\\/ |__|//  |__o__|      |')
    print(' |  |==""//=\\\\""====|||||)   |__o__|      |')
    print('_|__||_|_||_||_____||||||____|__o__|_____ |')
    print('    ||  (_) (_)    ||||||                 \\')
    print('    []             [(_)(_)')
    print('')
    if (len(argv) == 1):
        EquationString.String = input("Entrez une equation: ")
#        print (EquationString.String)
    elif (len(argv) == 2) :
        EquationString.String = argv[1]
#        print (EquationString.String)
    else :
        print("usage:   python ./main.py")
        print("         python ./main.py [equation]")
        print("         python ./main.py [file.test]")
        return -1
    
    if (EquationString.String[len(EquationString.String) - 1]  == 't' and
        EquationString.String[len(EquationString.String) - 2]  == 's' and
        EquationString.String[len(EquationString.String) - 3]  == 'e' and
        EquationString.String[len(EquationString.String) - 4]  == 't' and
        EquationString.String[len(EquationString.String) - 5]  == '.'):
        path = EquationString.String
        try:
            with open(path) as end:
                for line in end:
                    print(line.rstrip())
                    EquationString.String = line.rstrip()
                    ParseString(EquationString)
                    print("")
        except:
            print("Error: file not found!")
    else:
        ParseString(EquationString)
def parseInput(choice):
    if DEBUG and type(choice) != str:
        print(
            f"parseInput recived a {type(choice)} instead of a string. Choice is {choice}"
        )
        print(_cmd)

    # is an equation
    if re.search(r"[-][>]", choice):
        print(choice + ' was determined to be an equation') if DEBUG else ''
        return Equation(choice)

    # is an element
    elif re.search(r'([A-Z][a-z]$)|([A-Z]$)', choice) and (
            choice.title() in ELEMENTS) and not re.search(r'[+]', choice) and (
                choice.lower() not in ('opt', 'option', 'options')):
        print(choice + ' was determined to be an element.') if DEBUG else ''
        if choice.islower():
            choice = choice.title()
        return Element(choice)

    # is a compound --- and (choice.lower() != ('opt' or 'option' or 'options')
    elif re.search(
            r"([A-Z][a-z]\d\d$)|([A-Z][a-z]\d$)|([A-Z][a-z]$)|([A-Z]\d\d$)|([A-Z]\d$)|([A-Z][A-Z]$)",
            choice) and (choice.lower() not in ('opt', 'option', 'options')):
        print(choice + ' was determined to be a compound.') if DEBUG else ''
        return Compound(choice)

    elif choice.title() in elementFullNames:
        print(choice + ' was determined to be in the elements dictionary.'
              ) if DEBUG else ''
        return Element(dict(zip(elementFullNames, ELEMENTS))[choice.title()])

    elif choice.upper() in ('q', 'quit', 'done', 'finish', 'finished', 'exit'):
        print(choice + ' was determined to be a quit signal.') if DEBUG else ''
        exit(0)

    elif choice.lower() in ('opt', 'option', 'options'):
        print(choice +
              ' was determined to be an options signal.') if DEBUG else ''
        return -1

    else:
        print(choice + ' wasn\'t determined to be anything recognizable.'
              ) if DEBUG else ''
        print("Sorry, I don't know what to do with that.")
示例#26
0
    def generalize_numbers(cls, equations, nlp):
        numbers = nlp.numbers()
        numbers = list({d['number'] for d in numbers})
        new_equations = [eq.full for eq in equations]

        # TODO(Eric): question 6158 should give 24.0 the same
        #             number slot in each equation
        count = 0
        for num in numbers:
            for i, eq in enumerate(new_equations):
                if eq.has(num):
                    slot = Symbol('n_{}'.format(count))
                    count += 1
                    new_equations[i] = cls.no_eval_replace(new_equations[i],
                                                           num,
                                                           slot)

        return [Equation(eq) for eq in new_equations]
示例#27
0
    def on_validate(self):
        unification = Unification([])
        self.terms_table_holder.setPlainText('')

        for left_input, right_input in zip(self.ops_left_inputs,
                                           self.ops_right_inputs):
            if not left_input.text() or not right_input.text():
                self.terms_table_holder.insertPlainText(
                    '---------------------------------------------------\n' +
                    'Attention!! Une partie vide est détectée, donc celle l\'équation est ignorée.\n'
                    + '---------------------------------------------------\n')
                continue

            liste_gauche = Analyse.analyse_lexical(left_input.text())
            liste_droite = Analyse.analyse_lexical(right_input.text())

            liste_gauche = Analyse.termes_separateur(liste_gauche)
            liste_droite = Analyse.termes_separateur(liste_droite)

            liste_gauche = Analyse.analyse_syntaxique(liste_gauche)
            liste_droite = Analyse.analyse_syntaxique(liste_droite)

            if len(liste_gauche) != len(liste_droite):
                self.terms_table_holder.insertPlainText(
                    '---------------------------------------------------\n' +
                    'Attention!! La partie gauche et partie droite n\'avons pas le même nombre des termes'
                    + ', donc le nombre minimum est gardé.\n' +
                    '---------------------------------------------------\n')

            liste_min = min(len(liste_gauche), len(liste_droite))

            for gauche, droite in zip(liste_gauche[:liste_min],
                                      liste_droite[:liste_min]):
                equation = Equation(gauche, droite)
                unification.equations.append(equation)

            self.terms_table_holder.insertPlainText(
                '---------------------------------------------------\n'
                '1er partie: ----------\n' +
                (Terme.terms_table(liste_gauche) or '<Pas des termes>\n') +
                '2eme partie: ----------\n' +
                (Terme.terms_table(liste_droite) or '<Pas des termes>\n'))

        self.unification_holder.setPlainText(unification.moteur_unification())
示例#28
0
    def unify_unknowns(cls, equations):
        replacements = dict()
        for eq in equations:
            for s in eq.symbols:
                splits = str(s).split('_')
                if splits[0] != 'u':
                    continue

                replacements[s] = Symbol('u_{}'.format(splits[1]))

        new_equations = [eq.full for eq in equations]
        for i in range(len(new_equations)):
            for old, new in replacements.iteritems():
                new_equations[i] = cls.no_eval_replace(new_equations[i],
                                                       old,
                                                       new)

        return ([Equation(eq) for eq in new_equations],
                list(set(replacements.values())))
示例#29
0
def run_balance():
    #prompts user to input a chemical equation and gives them correct format
    print('=================================================')
    print(
        'Insert chemical equation with elements in parentheses followed by the number of atoms:'
    )
    print('Example: (H)2 + (O)2 = (H)2(O)1')
    user_input = input('>>> ')
    #checks to see if the input matches the correct format and runs the balancing function
    try:
        equation = Equation(user_input)
        print('Balanced equation: ' + equation.balance())
        sleep(3)
        run_balance()
    #if input is not correctly formated then it will return as invalid input and ask the player again
    except IndexError:
        print('Invalid input...')
        sleep(3)
        run_balance()
示例#30
0
def run_balance():
    """
    Runs the chemical equation balance algorithm
    """
    print('=================================================')
    print(
        'Insert chemical equation with elements in\nparentheses followed by the number of atoms:'
    )
    print('Example: (H)2 + (O)2 = (H)2(O)1')
    user_input = input('>>> ')
    try:
        equation = Equation(user_input)
        print('Balanced equation: ' + equation.balance())
        sleep(3)
        run_balance()
    except IndexError:
        print('Invalid input...')
        sleep(3)
        run_balance()