Exemplo n.º 1
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()
Exemplo n.º 2
0
def getModel(system): 
    # check dependancy
    set_provided = set([equ[0] for equ in system]) 
    set_needed = set(reduce(lambda x, y: x+y, [equ[1] for equ in system])) 
# dependancy checking is not needed.
#   if not set_needed <= set_provided:
#       print 'Needed value is not provided.'
#       return None 
#   else:
#       print 'Dependancy test: pass.'

    # check valid
    rendered = []
    for equ in system:
        e = Equation(dict(equ[2]), equ[3].replace(':', '_'))
        var = [ele.replace(':', '_') for ele in [equ[0]]+equ[1]+['t'] ]
        eval_dict = dict(zip(var, [0.]*len(var)))
        eval_dict['__builtins__'] = None

        print '='*20
        try:
            testv = eval(e.render(), eval_dict, safe_dict)
            print 'Test pass:'******'\tValue(all 0):', testv
            rendered.append(e.render())
        except Exception, exp:
            print 'Test error:', e.render()
            print '\t', exp
            return None, None
Exemplo n.º 3
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()
Exemplo n.º 4
0
 def __str__(self):
     if self.terms == {}:
         return "Dimensionless"
     dummyEquation = Equation()
     dummyEquation.terms = self.terms
     dummyEquation.coefficient = 1
     return equationToString(dummyEquation)
Exemplo n.º 5
0
 def __str__(self):
     if self.terms == {}:
         return "Dimensionless"
     dummyEquation = Equation()
     dummyEquation.terms = self.terms
     dummyEquation.coefficient = 1
     return equationToString(dummyEquation)
 def test_substituteEquation(self):
     equation1 = Equation(1,4.0,{2:-2.0,3:2.0})
     equation2 = Equation(4,4.0,{1:-2.0,3:2.0})
     self.assertTrue(equation2.substituteEquation(equation1))   
     self.assertEquals(equation2.basicVar,4)
     self.assertEquals(equation2.bValue,-4.0)
     self.assertEquals(equation2.rhsDict[2],4.0)
     self.assertEquals(equation2.rhsDict[3],-2.0)
     self.assertEquals(len(equation2.rhsDict.keys()),2)
    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
Exemplo n.º 8
0
    def from_json(j):
        equations = list()
        for eq_j in j['equations']:
            equations.append(Equation.from_json(eq_j))

        solution = dict()
        for var, eq_j in j['solution'].iteritems():
            solution[Symbol(var)] = Equation.from_json(eq_j)

        return Template(equations, solution)
Exemplo n.º 9
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))
Exemplo n.º 10
0
    def test_addition(self):
        '''An addition operation should be valid

        1 + 2 = 3
        '''
        # a = 1, b = 2, operator = addition
        self.fake_numbers = [1, 2, 0] 

        eq = Equation(10, self.fakeRandom)

        self.assertTrue(eq.a is 1 and  eq.b is 2 and eq.operator is 0)
        self.assertTrue(eq.validate(3)) 
Exemplo n.º 11
0
    def test_subtraction1(self):
        '''A subtraction operation should be valid

        2-1 = 1
        '''
        # a = 2, b = 1, operator = subtraction
        self.fake_numbers = [2, 1, 1]

        eq = Equation(10, self.fakeRandom)

        self.assertTrue(eq.a is 2 and  eq.b is 1 and eq.operator is 1)
        self.assertTrue(eq.validate(1)) 
Exemplo n.º 12
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
Exemplo n.º 13
0
    def test_subtraction2(self):
        '''Subtraction should always be positive

        When the first random number generated is smaller than the second
        during a subtraction, the results should remain positive by swapping
        the two operands.
        ''' 
        # a = 1, b = 2, operator = subtraction
        self.fake_numbers = [2, 1, 1] 

        eq = Equation(10, self.fakeRandom)

        self.assertTrue(eq.a is 2 and  eq.b is 1 and eq.operator is 1)
        self.assertTrue(eq.validate(1)) 
Exemplo n.º 14
0
def getModel(system, dependancy_check=True): 
    """
        :system: the equation system.

        Get the ODE model to simulate from system.
    """
    # check dependancy
    set_provided = set([equ[0] for equ in system]) 
    set_needed = set(reduce(lambda x, y: x+y, [equ[1] for equ in system], [])) 

    # dependancy checking is not needed.
    if dependancy_check:
        # the needed set is included in the provided set
        if not set_needed <= set_provided:
            auto = set_needed - set_provided
            for ele in list(auto):
                system.append([ele, [], [], '0'])
            # debug code
    #       print 'needed:', set_needed
    #       print 'provided:', set_provided
    #       print 'Needed value is not provided.'
    #       return None, 'Needed value is not provided.'
    #   else:
    #       print 'Dependancy test: pass.'

    # check valid
    rendered = []
    for equ in system:
        # e is the Equation object
        e = Equation(dict(equ[2]), equ[3].replace(':', '_'))
        # all the variables
        var = [ele.replace(':', '_') for ele in [equ[0]]+equ[1]+['t'] ]

        # the look-up table of variables
        eval_dict = dict(zip(var, [0.]*len(var)))
        eval_dict['__builtins__'] = None

        try:
            # try to evaluate the formula
            testv = eval(e.render(), eval_dict, safe_dict)
#           print 'Test pass:'******'\tValue(all 0):', testv
            rendered.append(e.render())
        except Exception, exp:
            print 'Test error:', equ
            msg = traceback.format_exc()
            #print '\t', exp.message
            print msg
            return None, msg, None
Exemplo n.º 15
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))
Exemplo n.º 16
0
 def extract_template(self):
     parsed_equations = [
         Equation.from_string(eq) for eq in self.labeled_example.equations
     ]
     self.template = Template.from_equations_and_nlp(
         parsed_equations, self.nlp)
     return self.template
Exemplo n.º 17
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)
Exemplo n.º 18
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
Exemplo n.º 19
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)
Exemplo n.º 20
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
Exemplo n.º 21
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
Exemplo n.º 22
0
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)
Exemplo n.º 23
0
    def _execute_step_if_new_input(self, equation):

        if self._last_input is None:
            return self._execute_step(equation)
        elif Equation.areEqual(self._last_input, equation):
            return self._execute_step(equation)
        else:
            return None
class Chromosome:
    UPPER_BOUND = 10
    LOWER_BOUND = -10

    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

    def fitness(self):
        n = len(self.points)
        sum = 0
        for point in self.points:
            yCalc = self.equation.substituteX(point.x)
            sum += (yCalc - point.y)**2
        return round(sum / n, 6)

    def generateRandom(self, size):
        coefficients = []
        for i in range(size):
            coefficients.append(
                round(random.uniform(self.LOWER_BOUND, self.UPPER_BOUND), 6))
        return coefficients

    def crossOver(self, parent):
        intHalfLength = int(random.random() * self.size) + 1
        childOne = Chromosome(
            coefficients=parent.coefficients[0:intHalfLength] +
            self.coefficients[intHalfLength - 1:])
        childTwo = Chromosome(coefficients=self.coefficients[0:intHalfLength] +
                              parent.coefficients[intHalfLength - 1:])
        childOne.points = self.points
        childTwo.points = self.points
        return childOne, childTwo

    def mutate(self, rate=0.5):
        if (random.random() < rate):
            randomIndex = int(random.randrange(self.size))
            gene = self.coefficients[randomIndex]
            rand = random.random()
            deltaLower = gene - self.LOWER_BOUND
            deltaUpper = self.UPPER_BOUND - gene
            delta = deltaLower if rand <= 0.5 else deltaUpper
            rand = random.random() * delta
            newGene = gene - rand if delta == deltaLower else gene + rand
            self.coefficients[randomIndex] = round(newGene, 6)

    def __str__(self):
        return ",".join(str(x) for x in self.coefficients)

    def __eq__(self, other):
        return self.fitness() == other.fitness()
Exemplo n.º 25
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)
Exemplo n.º 26
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
Exemplo n.º 27
0
def run_balance():
    """
    Runs the chemical equation balance algorithm
    """
    print('=================================================')
    print(
        'Introduce ecuacion quimica con elementos dentro de \nparentesis seguido por numero de atomos:'
    )
    print('Ejemplo: (H)2 + (O)2 = (H)2(O)1')
    user_input = input('>>> ')
    try:
        equation = Equation(user_input)
        print('Ecuacion balanceada: ' + equation.balance())
        sleep(3)
        run_balance()
    except IndexError:
        print('Input invalido...')
        sleep(3)
        run_balance()
Exemplo n.º 28
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()
Exemplo n.º 29
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()
Exemplo n.º 30
0
    async def stoichiometry(self, ctx, element, unknown_element, known_mass: float, mmA: float, mmB: float, *, eq):
        equation = Equation(eq)
        balanced_equation = equation.balance()
        split = balanced_equation.split(' = ')
        left = split[0]
        right = split[1]
        left_components = left.split(' + ')
        right_components = right.split(' + ')
        left_coefs = {}
        right_coefs = {}
        lis = []
        lis2 = []
        u = 0
        u2 = 0
        p = lambda x: enumerate(x)
        o  = list(p(left_components))
        o2  = list(p(right_components))
        for i in range(len(o)):
            lis.append(o[u][0])
            u += 1
        for i in range(len(o2)):
            lis2.append(o[u2][0])
            u2 += 1
        for x in lis:
            if x >= 0:
                left_coefs[left_components[x][1:len(left_components[x]) + 1]] = left_components[x][0]
        for x2 in lis2:
            if x2 >= 0:
                right_coefs[right_components[x2][1:len(right_components[x2]) + 1]] = right_components[x2][0]


        if element in left_coefs.keys(): coefA = int(left_coefs[element])
        elif element in right_coefs.keys(): coefA = int(right_coefs[element])
        else: await ctx.send(left_coefs)

        if unknown_element in left_coefs.keys(): coefB = int(left_coefs[unknown_element])
        elif unknown_element + " " in right_coefs.keys(): coefB = int(right_coefs[unknown_element + ' '])
        else: await ctx.send(right_coefs)

        # Calculation

        mass_to_mass = (known_mass * coefB) * (mmB) / (mmA * coefA)
        await ctx.send(f'{round(mass_to_mass, 2)} grams of {unknown_element}')
Exemplo n.º 31
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)
Exemplo n.º 32
0
    def __init__(self, mesh, unit_length):
        self.mesh = mesh
        self.unit_length = unit_length
        self.S1 = df.FunctionSpace(mesh, "CG", 1)
        self.S3 = df.VectorFunctionSpace(mesh, "CG", 1, dim=3)

        self.alpha = Field(self.S1, name="alpha")
        self.dmdt = Field(self.S3, name="dmdt")
        self.H = Field(self.S3, name="H")  # TODO: connect effective field to H
        self.m = Field(self.S3, name="m")
        self.Ms = Field(self.S1, name="Ms")
        self.pins = []  # TODO: connect pins to instant code

        self.effective_field = EffectiveField(self.m, self.Ms,
                                              self.unit_length)

        self.eq = Equation(self.m.as_vector(), self.H.as_vector(),
                           self.dmdt.as_vector())
        self.eq.set_alpha(self.alpha.as_vector())
        self.eq.set_gamma(consts.gamma)
        self.eq.set_saturation_magnetisation(self.Ms.as_vector())
Exemplo n.º 33
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)
Exemplo n.º 34
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)
Exemplo n.º 35
0
class TestEquation(unittest.TestCase):
	def setUp(self): # metoda ktora sluzy do inicjalizacji zmiennych
		self.eq_no_result=Equation(1,2,3)
		self.eq_one_result = Equation(1,2,1)
		self.eq_two_result = Equation(1,-2,-15)
		self.eq_zero_all = Equation(0,0,0)

	def testNoResult(self):#metoda do testowania czy nasza klasa dziala poprawnie jak nie ma wynikow	
		wynik = self.eq_no_result.solve()
		self.assertEqual(wynik, None)
		
	def testOneResult(self):#metoda do tesotwania czy nasz klasa dziala poprawnie jak jest jedno rozwiaznaie
		wynik = self.eq_one_result.solve()
		self.assertEqual(wynik, -1)

	def testTwoResult(self):#
		wynik = self.eq_two_result.solve()
		self.assertEqual(wynik,(-3,5))

	def testZeroArgs(self):
		self.assertEqual(True, True)
Exemplo n.º 36
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)
Exemplo n.º 37
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)
 def test_exitVarRebalance(self):
     equation = Equation(1,4.0,{2:-2.0,3:2.0})
     self.assertTrue(equation.exitVarRebalance(2))
     self.assertEquals(equation.basicVar,2)
     self.assertEquals(equation.bValue,2.0)
     self.assertEquals(equation.rhsDict[1],-0.5)
     self.assertEquals(equation.rhsDict[3],1.0)
     self.assertFalse(equation.exitVarRebalance(2))
     
     equation = Equation(4,0.0,{3:0.0,6:-1.0,2:1.0,7:3.0}) 
     equation.exitVarRebalance(6)
     self.assertTrue(Equation.equals(equation,Equation(6,0.0,{3:0.0,4:-1.0,2:1.0,7:3.0})))
Exemplo n.º 39
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))
Exemplo n.º 40
0
        def getter(self):
            from equation import Equation

            return Equation.by_ids(self.lib.equation_lib.values())
    def test_valueOfEntryZeroCoeff(self):
        eq = Equation(6,0.0,{2:-1.0,4:0.0,5:-2.0,7:0.0})

        self.assertIsNone(eq.valueOfEntry(4))
Exemplo n.º 42
0
	def setUp(self): # metoda ktora sluzy do inicjalizacji zmiennych
		self.eq_no_result=Equation(1,2,3)
		self.eq_one_result = Equation(1,2,1)
		self.eq_two_result = Equation(1,-2,-15)
		self.eq_zero_all = Equation(0,0,0)
 def setUp(self):
     self.equation = Equation(1,4.6,{2:-5.7,3:5.7}) 
 def test_equationEqualsTrue(self):
     self.assertTrue(Equation.equals(Equation(1,4.0,{2:-2.0,3:2.0}),Equation(1,4.0,{2:-2.0,3:2.0})))
     self.assertTrue(Equation.equals(Equation(1,4.0,{3:2.0}),Equation(1,4.0,{3:2.0})))
     self.assertTrue(Equation.equals(Equation(1,4.0,{4:0.0,3:2.0}),Equation(1,4.0,{3:2.0})))
 def test_equationEqualsFalse(self):
     self.assertFalse(Equation.equals(Equation(1,4.0,{6:-2.0,3:2.0}),Equation(1,4.0,{2:-2.0,3:2.0})))
     self.assertFalse(Equation.equals(Equation(1,4.0,{2:0.0,3:2.0}),Equation(1,4.0,{2:-2.0,3:2.0})))
class EquationTestCase(unittest.TestCase):

    def setUp(self):
        self.equation = Equation(1,4.6,{2:-5.7,3:5.7}) 

    def test_equation(self):
        self.assertIsNotNone(self.equation)
    
    def test_copy(self):
        copyEquation= self.equation.copy()
        self.assertNotEquals(self.equation,copyEquation)
    
    def test_copyIntensive(self):
        copyEquation= self.equation.copy()
        self.assertEquals(self.equation.basicVar,copyEquation.basicVar)
        self.assertEquals(self.equation.bValue,copyEquation.bValue)
        self.assertEquals(self.equation.rhsDict,copyEquation.rhsDict)
        self.assertNotEquals(id(self.equation.rhsDict),id(copyEquation.rhsDict))
    
    def test_valueOfEntry(self):
        equation = Equation(1,4.0,{2:-2.0,3:2.0})
        self.assertEquals(equation.valueOfEntry(2),2.0)
        self.assertEquals(equation.valueOfEntry(3),-2.0)
    
    def test_valueOfEntryInvalidEntry(self):
        self.assertIsNone(self.equation.valueOfEntry(9))
         
    def test_valueOfEntryZeroCoeff(self):
        eq = Equation(6,0.0,{2:-1.0,4:0.0,5:-2.0,7:0.0})

        self.assertIsNone(eq.valueOfEntry(4))
     
    def test_exitVarRebalanceInvalidIndex(self):
        self.assertFalse(self.equation.exitVarRebalance(103))

    def test_exitVarRebalanceInvalidCoeff(self):
        self.equation.rhsDict[103] = 0.0
        self.assertFalse(self.equation.exitVarRebalance(103))
    
    def test_exitVarRebalance(self):
        equation = Equation(1,4.0,{2:-2.0,3:2.0})
        self.assertTrue(equation.exitVarRebalance(2))
        self.assertEquals(equation.basicVar,2)
        self.assertEquals(equation.bValue,2.0)
        self.assertEquals(equation.rhsDict[1],-0.5)
        self.assertEquals(equation.rhsDict[3],1.0)
        self.assertFalse(equation.exitVarRebalance(2))
        
        equation = Equation(4,0.0,{3:0.0,6:-1.0,2:1.0,7:3.0}) 
        equation.exitVarRebalance(6)
        self.assertTrue(Equation.equals(equation,Equation(6,0.0,{3:0.0,4:-1.0,2:1.0,7:3.0})))
        
    def test_substituteEquationNone(self):
        self.assertFalse(self.equation.substituteEquation(None))
    
    def test_substituteEquationZeroCoeff(self):
        equation1 = Equation(1,4.0,{2:-2.0,3:2.0})
        equation2 = Equation(4,4.0,{1:0.0,3:2.0})
        self.assertTrue(equation2.substituteEquation(equation1)) 

    def test_substituteEquation(self):
        equation1 = Equation(1,4.0,{2:-2.0,3:2.0})
        equation2 = Equation(4,4.0,{1:-2.0,3:2.0})
        self.assertTrue(equation2.substituteEquation(equation1))   
        self.assertEquals(equation2.basicVar,4)
        self.assertEquals(equation2.bValue,-4.0)
        self.assertEquals(equation2.rhsDict[2],4.0)
        self.assertEquals(equation2.rhsDict[3],-2.0)
        self.assertEquals(len(equation2.rhsDict.keys()),2)

    def test_equationEqualsTrue(self):
        self.assertTrue(Equation.equals(Equation(1,4.0,{2:-2.0,3:2.0}),Equation(1,4.0,{2:-2.0,3:2.0})))
        self.assertTrue(Equation.equals(Equation(1,4.0,{3:2.0}),Equation(1,4.0,{3:2.0})))
        self.assertTrue(Equation.equals(Equation(1,4.0,{4:0.0,3:2.0}),Equation(1,4.0,{3:2.0})))

    def test_equationEqualsFalse(self):
        self.assertFalse(Equation.equals(Equation(1,4.0,{6:-2.0,3:2.0}),Equation(1,4.0,{2:-2.0,3:2.0})))
        self.assertFalse(Equation.equals(Equation(1,4.0,{2:0.0,3:2.0}),Equation(1,4.0,{2:-2.0,3:2.0})))
 def test_substituteEquationZeroCoeff(self):
     equation1 = Equation(1,4.0,{2:-2.0,3:2.0})
     equation2 = Equation(4,4.0,{1:0.0,3:2.0})
     self.assertTrue(equation2.substituteEquation(equation1)) 
 def test_valueOfEntry(self):
     equation = Equation(1,4.0,{2:-2.0,3:2.0})
     self.assertEquals(equation.valueOfEntry(2),2.0)
     self.assertEquals(equation.valueOfEntry(3),-2.0)