def undefined_integral(self):
        temp = list()
        for x in self.terms:
            if np.equal(x.exponent, 0):
                temp.append(Term(x.coefficient, x.exponent + 1))
            else:
                a = np.divide(x.coefficient, x.coefficient + 1)
                temp.append(Term(a, x.exponent + 1))
        temp.append('C')

        return self.terms
Example #2
0
 def Term(self):
     if self.peek().type == "LBRACK":
         self.expect("LBRACK")
         # Parse a list of identifiers
         list_terms = self.List()
         self.expect("RBRACK")
         return Term(list_terms=list_terms)
     else:
         t = self.advance()
         self.info("Parsed a term of type {} and value {}".format(
             t.type, t.value))
         return Term(type=t.type, term=t.value)
Example #3
0
 def parse(self):
     self.term = Term()
     self.term.parse()
     if TokList.checkTok('PLUS'):
         TokList.nextToken()
         self.plusOrMinus = '+'
         self.expr = Expr()
         self.expr.parse()
     elif TokList.checkTok('MINUS'):
         TokList.nextToken()
         self.plusOrMinus = '-'
         self.expr = Expr()
         self.expr.parse()
Example #4
0
    def add_dummy_nodes(layers, links, terms):
        """
        this method adds dummy nodes to the layered graph, a connection is
        replaced by dummy nodes when the connection spans multiple layers.

            :param list layers: list of layers where the first item is the
                top most layer and then continues down.
            :param list links: list of all links in the graph.
            :param dict terms: a dictionary where the key is a term and the
                value is an object containing all information on that term.

            :return tuple: (links, layers, terms)
                WHERE
                list links is a list of all links in the graph.
                list layers is a list of lists containing all layers.
                dict terms is a dictionary containing all term objects.
        """

        id_count, new_terms, new_links, old_links = 0, {}, [], []
        term_layers = EdgeFix.make_layer_dict(layers)
        for index, (parent, child, connection) in enumerate(links):
            if child != "Root" and parent != "Root":
                layer_delta = term_layers[parent] - term_layers[child]
                if layer_delta > 1:
                    old_links.append((parent, child, connection))
                    temp_parent, current_layer = parent, term_layers[parent] - 1
                    for dummy_index in range(layer_delta - 1):
                        id = "DUMMY:{}".format(id_count)
                        dummynode = Term()
                        dummynode.p.add((temp_parent, connection))
                        dummynode.y = term_layers[parent] - dummy_index - 1
                        layers[len(layers) - current_layer - 1].append(id)
                        if dummy_index == 0:
                            terms[temp_parent].c.remove((child, connection))
                            terms[temp_parent].c.add((id, connection))
                        else:
                            terms[temp_parent].c.add((id, connection))
                        terms[id] = dummynode
                        new_links.append((temp_parent, id, connection))
                        temp_parent = id
                        id_count += 1
                        current_layer -= 1
                    terms[temp_parent].c.add((child, "NA"))
                    new_links.append((temp_parent, child, "NA"))
        for link in old_links:
            links.discard(link)
        for link in new_links:
            links.add(link)
        return links, layers, terms
Example #5
0
    def addTerm(self, term):
        coefficient = 0.0
        exponent = 0

        if '+' in term and '-' in term:
            term = term.replace('+', "")

        if 'x' not in term:
            coefficient = float(term)
            exponent = 0

        elif '^' not in term:
            try:
                coefficient = float(term[0:term.index('x')])
            except:
                coefficient = 1
            exponent = 1

        else:
            try:
                coefficient = float(term[0:term.index('x')])
            except:
                coefficient = 1
            exponent = int(term[term.index('^') + 1:])

        if coefficient != 0:
            self.mylist.append(Term(coefficient, exponent))
Example #6
0
    def parse_term(cls, term):
        """ Parse a string into a Term object """
        #
        # tests the term for syntactical errors
        # then cleans up the string
        # if it is a compound term like 3x^2 it first expands that to 3*x^2
        # then parses 3 and x^2 separately, then simplifies it to a single term.
        #

        if isinstance(term, Term): return term

        cls.test_term(term)
        term = cls.clean_up(term)
        terms = cls.separate(term, "*/()")

        while "(" in terms:
            start, end = cls.get_parentheses_location(terms)
            result = cls.parse_term("".join(terms[start + 1:end]))
            terms = cls.list_replace(terms, start, end, result)

        if len(terms) == 1:
            term = terms[0]
            if number_pattern.fullmatch(term):
                # its a number
                return Term(Number(float(term)), [], [])
            elif term in delimiters:
                # it is an operator or parenthesis
                return term
            elif "^" in term:
                # it was not a Number, operator, or parenthesis.
                # it is something of the form (var)^(exponent)
                return Term(Number(1), [Symbol(term[0])],
                            [Number(float(term[term.rfind("^") + 1:]))])
            else:
                # it is just a single variable such as "x" or "y"
                return Term(Number(1), [Symbol(term)], [Number(1)])
        else:
            # it is not possible for recursion depth to exceed 2 here.
            terms = [cls.parse_term(t) for t in terms]

        while "*" in terms or "/" in terms:
            index = cls.list_index(terms, ["*", "/"])
            # ^^ this will be the first occurence of an operator.
            terms = cls.list_substitute(terms, index)

        return terms[0]
Example #7
0
 def add_to_index(self, words, doc_id):
     for sw in words:
         if sw in self.dictionary.keys():
             self.dictionary[sw].freq += 1
         else:
             self.dictionary[sw] = Term()
             self.dictionary[sw].freq = 1
             self.dictionary[sw].name = sw
         self.dictionary[sw].addToPostList(doc_id)
Example #8
0
    def derivative(self):
        derivative = ""
        for term in self.mylist:
            if term.getExponent() != 0:
                derivedTerm = Term(term.getCoefficient() * term.getExponent(),
                                   term.getExponent() - 1)
                if term != self.mylist[0]:
                    derivative += "+"
                derivative += str(derivedTerm)

        return derivative
    def fix(self):
        self.terms = sorted(self.terms, key=lambda l: l.exponent, reverse=True)

        temporary = self.sumDegree()
        i = 0

        for x in self.terms:
            if x.coefficient is not 0:
                temporary.append(Term(x.coefficient, x.exponent))
        self.terms = temporary
        return self.terms
Example #10
0
    def indefiniteIntegral(self):
        integral = ""
        for term in self.mylist:
            n = int(term.getExponent() + 1)
            integratedTerm = Term(term.getCoefficient() / n, n)
            if term != self.mylist[0]:
                integral += '+'
            integral += str(integratedTerm)

        integral += "+C"

        return integral
Example #11
0
 def __init__(self, **kwargs):
     """
     Arguments:
         {[float]} -- a list of numbers that correspond to coefficients
         {[Term]}
     """
     if "coefficients" in kwargs:
         # each term's power corresponds to its position in the list of coefficients
         # e.g. the constant is the leftmost elemenent, so its index is 0, and 0 is also the power of the constant term
         self._terms = [Term(coefficient, int(power))
                        for (power, coefficient) in enumerate(kwargs["coefficients"])]
     elif "terms" in kwargs:
         self._terms = kwargs["terms"]
     else:
         self._terms = []
Example #12
0
 def Calc(self):
     symbols = ["PLUS", "MINUS", "TIMES", "DIVIDE"]
     o1 = self.advance()
     if (self.peek().type in symbols):
         operands = []
         operators = []
         operands.append(o1)
         while (self.peek().type in symbols):
             operator = self.advance()
             o2 = self.advance()
             operands.append(o2)
             operators.append(operator)
         return Calc(operands=operands, operators=operators)
     else:
         return Term(type=o1.type, term=o1.value)
Example #13
0
 def term_frame(self, items):
     t = Term(items[0])
     for something in items[2:]:
         clause, eol = something.children
         if clause and type(clause) == tuple:
             tag, v, *vs = clause
             if vs:
                 t.add(tag, (v, *vs))
             else:
                 t.add(tag, v)
     return t
    def sumDegree(self):
        temporary_term = None
        result = self.terms
        newList = []
        i = 1
        while i < len(result):
            a = result[i - 1]
            b = result[i]

            if (a.exponent is b.exponent):
                newList.append(Term(a.coefficient + b.coefficient, a.exponent))
            else:
                newList.append(b)
            i = i + 1

        self.terms = newList
        return self.terms
Example #15
0
def ut_01():
    e1 = Expression()
    e2 = Expression()

    a1 = [Term(10, 1), Term(-20, 2), Term(30, -3)]
    a2 = [Term(5, 1), Term(6, 2), Term(7, -3)]

    e1.set_exp(a1)
    e2.set_exp(a2)

    e3 = e1 + e2
    e3.print2()
Example #16
0
    def findCommonTerms(self, l):
        polynomial = ""
        for i in range(0, len(l)):
            j = i + 1
            while (i < len(l) - 1
                   and l[i].getExponent() == l[j].getExponent()):
                modifiedTerm = Term(
                    l[i].getCoefficient() + l[j].getCoefficient(),
                    l[i].getExponent())
                l[i] = modifiedTerm
                l.remove(j)

            if l[i] != l[0]:
                polynomial += '+'
            polynomial += str(l[i])

            if (len(polynomial) != 0):
                return polynomial
            else:
                return "0.00"
    def add(self, other):
        temp = list()
        result = list()

        for element in other.terms:
            temp.append(element)

        for x, y in zip(temp, self.terms):
            temp1, tempo1 = x.coefficient, y.coefficient
            if temp1 is tempo1:
                newTerm = Term(x.coefficient + y.coefficient, x.exponent)
                temp.append(newTerm)
            elif x.exponent > y.exponent:
                temp.append(x)
            elif x is 'C' or y is 'C':
                pass
            else:
                temp.append(y)

        self.terms = temp
        return self.terms
def parse_eval(val):
	equals = val.index("=")
	og = val
	past_equals = False
	right = brackets_only(val)
	left = brackets_only(val, reverse=True)

	res = ""
	non_terms = ["(", ")", "+", "-", "*", "/", " "]
	i = 0
	lv = len(right)
	terms = []
	while i < lv:
		let = right[i]
		if let not in non_terms:
			j = i + 1 if i < lv - 1 else -1
			next_let = right[j] if j >= 0 else None
			t = let
			print("let: {let}, next_let: {nl}".format(let=let, nl=next_let))
			if next_let is not None and next_let not in non_terms:
				k = j
				while k < lv - 1:
					letter = right[k]
					if letter in non_terms:
						break
					t += letter
					k += 1
					i += 1
					print("Loop\nk: {k}\nlv: {lv}\nletter: {letter}".format(k=k, lv=lv, letter=letter))
			terms.append((i - len(t) + 1, Term(t, None)))
		i += 1


	print("ORIGINAL VAL:\n\t<{0}>\nRIGHT:\n\t<{1}>\nLEFT:\n\t<{2}>\nCALCULATED TERMS\n\t{3}".format(og, right, left, terms))
	e = left + str(eval(right))
	print("EVALUATED TO: <{0}>".format(e))
	return e
Example #19
0
class Expr:
    def __init__(self):
        self.term = None
        self.expr = None
        self.plusOrMinus = ''
    #Parsing for Expression that checks for plus, minus, or no calculations
    def parse(self):
        self.term = Term()
        self.term.parse()
        if TokList.checkTok('PLUS'):
            TokList.nextToken()
            self.plusOrMinus = '+'
            self.expr = Expr()
            self.expr.parse()
        elif TokList.checkTok('MINUS'):
            TokList.nextToken()
            self.plusOrMinus = '-'
            self.expr = Expr()
            self.expr.parse()
    #Simple print statement
    def print(self):
        self.term.print()
        if '+' in self.plusOrMinus:
            print(self.plusOrMinus, end='')
            self.expr.print()
        elif '-' in self.plusOrMinus:
            print(self.plusOrMinus, end='')
            self.expr.print()
    #Simple execute statement that returns a value based on parsing
    def exec(self):
        if not self.plusOrMinus:
            return self.term.exec()
        elif '+' in self.plusOrMinus:
            return self.term.exec() + self.expr.exec()
        elif '-' in self.plusOrMinus:
            return self.term.exec() - self.expr.exec()
        for i in Vec.dim_range((0,0),self.grid_dims):
            if i not in self.grid:
                self.grid[i] = Conduit()
                self.grid[i].coords = i

        self.grid_col_widths = {}
        self.grid_row_heights = {}

        for x in range(self.grid_dims.x):
            self.grid_col_widths[x] = pipe(
                range(self.grid_dims.y),
                Map(lambda y: self.grid[x,y].dims.x),
                max
            )
        for y in range(self.grid_dims.y):
            self.grid_row_heights[y] = pipe(
                range(self.grid_dims.x),
                Map(lambda x: self.grid[x,y].dims.y),
                max
            )

        for item in self.grid.values():
            item.dims.x = self.grid_col_widths[item.coords.x]
            item.dims.y = self.grid_row_heights[item.coords.y]

term = Term()
graph = Graph()
graph.populate_from_file("test_graph.graph")
graph.render()
    def termFromString(self, string):

        string_tokentizer = string.split("+")
        for x in string_tokentizer:
            temp = Term(0, 0).fromString(x)
            self.terms.append(temp)
Example #22
0
def test_term_1():
    #TEST 1 - PRINT_E
    obj = Term(2)
    obj.print_e()  #EXPECTED: "Degree: 2"
    print("\n")
Example #23
0
def test_term_2():
    #TEST 2 - PRINT_E
    obj = Term(3)
    obj.print_e()  #EXPECTED: "Degree: 3"
    print("\n")
Example #24
0
 def __init__(self, terms, filename=None):
     self.terms = terms
     self.termsdis = []
     for term in terms:
         self.termsdis.append(Term(term))
     self.disambiguate()
Example #25
0
 def add_term(self, degree):
     term = Term(degree)
     self.regressor.append(term)
 def print(self, term: Term, pos: Vec):
     term.write_here(self.pos+Vec(2,2), self.label)