def __mul__(self, other): """Multiplies two matrices Arguments: self {visma.matrix.structure.Matrix} -- matrix token other {visma.matrix.structure.Matrix} -- matrix token Returns: matPro {visma.matrix.structure.Matrix} -- product matrix token Note: Make mulitplyCheck before calling multiplyMatrix Not commutative """ matPro = Matrix() matPro.empty([self.dim[0], other.dim[1]]) for i in range(self.dim[0]): for j in range(other.dim[1]): for k in range(self.dim[1]): if matPro.value[i][j] != []: matPro.value[i][j].append(Binary('+')) if len(self.value[i][k]) != 1: matPro.value[i][j].append(Expression(self.value[i][k])) else: matPro.value[i][j].extend(self.value[i][k]) matPro.value[i][j].append(Binary('*')) if len(other.value[k][j]) != 1: matPro.value[i][j].append(Expression( other.value[k][j])) else: matPro.value[i][j].extend(other.value[k][j]) from visma.matrix.operations import simplifyMatrix matPro = simplifyMatrix(matPro) return matPro
def multiplyMatrix(matA, matB): """Multiplies two matrices Arguments: matA {visma.matrix.structure.Matrix} -- matrix token matB {visma.matrix.structure.Matrix} -- matrix token Returns: matPro {visma.matrix.structure.Matrix} -- product matrix token Note: Make mulitplyCheck before calling multiplyMatrix Not commutative """ matPro = Matrix() matPro.empty([matA.dim[0], matB.dim[1]]) for i in range(matA.dim[0]): for j in range(matB.dim[1]): for k in range(matA.dim[1]): if matPro.value[i][j] != []: matPro.value[i][j].append(Binary('+')) if len(matA.value[i][k]) != 1: matPro.value[i][j].append(Expression(matA.value[i][k])) else: matPro.value[i][j].extend(matA.value[i][k]) matPro.value[i][j].append(Binary('*')) if len(matB.value[k][j]) != 1: matPro.value[i][j].append(Expression(matB.value[k][j])) else: matPro.value[i][j].extend(matB.value[k][j]) matPro = simplifyMatrix(matPro) return matPro
def __mul__(self, other): if isinstance(other, Cotangent): result = Expression() result.coefficient = self.coefficient * other.coefficient c = copy.deepcopy(self) d = copy.deepcopy(other) result.tokens.extend([c, Multiply(), d]) return result
def differentiate(self, wrtVar): term1 = Constant(-1, 1, 1) term2 = copy.deepcopy(self) term2.__class__ = Sine term2.value = 'sin' result = Expression() result.tokens = [term1, Multiply(), term2] return result
def integrate(self, wrtVar=None): term1 = Constant(-1, 1, 1) term2 = copy.deepcopy(self) term2.__class__ = Cosine term2.value = 'cos' term2.coefficient = 1 result = Expression() result.tokens = [term1, Multiply(), term2] return result
def differentiate(self, wrtVar): term1 = Constant(-1, 1, 1) term2 = copy.deepcopy(self) term2.__class__ = Cosecant term2.value = 'csc' term2.coefficient = 1 term2.power = 2 result = Expression() result.tokens = [term1, Multiply(), term2] return result
def integrate(self, wrtVar): term1 = Constant(-1, 1, 1) term2 = NaturalLog() term3 = Cosine() term3.operand = self.operand term2.operand = term3 term2.power = 1 term2.coefficient = 1 result = Expression() result.tokens = [term1, Multiply(), term2] return result
def differentiate(self, wrtVar): term1 = Constant(-1, 1, 1) term2 = Cosecant() term2.operand = self.operand term2.coefficient = 1 term3 = Cotangent() term3.operand = self.operand term3.coefficient = 1 result = Expression() result.tokens = [term1, Multiply(), term2, Multiply(), term3] return result
def integrate(self, wrtVar): resultTerm = NaturalLog() term3 = Secant() term3.operand = self.operand term4 = Tangent() term4.operand = self.operand inExpression = Expression() inExpression.tokens = [term3, Plus(), term4] resultTerm.operand = inExpression resultTerm.power = 1 resultTerm.coefficient = 1 return resultTerm
def factorizeTokens(tokens): coeffs, var = getPolyCoeffs(tokens) gcf, roots, polynomial = factor(coeffs) if roots != []: tokens = [] comment = "The real roots of the above polynomial are " for root in roots: comment += r"$" + str(root) + "\ ,\ " + r"$" if gcf != 1: tokens.append(Constant(float(gcf))) tokens.append(Multiply()) for root in roots: expression = Expression() expression.tokens.append(Variable(1, var, 1)) if root > 0: expression.tokens.append(Minus()) expression.tokens.append(Constant(float(root))) elif root < 0: expression.tokens.append(Plus()) expression.tokens.append(Constant(float(-root))) tokens.append(expression) tokens.append(Multiply()) if polynomial != [1]: expression = Expression() degree = len(polynomial) - 1 for i, coeff in enumerate(polynomial): if i == degree: if coeff > 0: expression.tokens.append(Plus()) expression.tokens.append(Constant(float(coeff))) elif coeff < 0: expression.tokens.append(Minus()) expression.tokens.append(Constant(float(-coeff))) elif coeff > 0: expression.tokens.append(Plus()) expression.tokens.append(Variable(coeff, var, degree - i)) elif coeff < 0: expression.tokens.append(Minus()) expression.tokens.append(Variable(-coeff, var, degree - i)) if isinstance(expression.tokens[0], Plus): expression.tokens.pop(0) tokens.append(expression) else: tokens.pop() else: comment = None animation = [tokens] comments = [comment] return tokens, animation, comments
def __truediv__(self, other): from visma.functions.constant import Constant if isinstance(other, Variable) or isinstance(other, Constant): self = self * (other**Constant(-1, 1, 1)) return self elif isinstance(other, Expression): expression = Expression() self.coefficient /= other.coefficient other.power *= -1 expression.tokens = [self] expression.tokens.extend([Multiply(), other]) self = expression return expression
def __sub__(self, other): from visma.functions.constant import Constant if isinstance(other, Variable): otherValueSorted = sorted(other.value) selfValueSorted = sorted(self.value) if (other.power == self.power) & (selfValueSorted == otherValueSorted): self = self + Constant(-1, 1, 1) * other return self else: expression = Expression() expression.tokens = [self] expression.tokens.extend([Minus(), other]) self = expression return expression elif isinstance(other, Constant): if other.isZero(): return self expression = Expression() expression.tokens = [self] expression.tokens.extend([Minus(), other]) self = expression return expression elif isinstance(other, Expression): expression = Expression() expression.tokens = [self] for i, token in enumerate(other.tokens): if isinstance(token, Variable): tokenValueSorted = sorted(token.value) selfValueSorted = sorted(self.value) if (token.power == self.power) & (tokenValueSorted == selfValueSorted): if other.tokens[i - 1].value == '+' or (i == 0): self.coefficient -= other.tokens[i].coefficient elif other.tokens[i - 1].value == '-': self.coefficient += other.tokens[i].coefficient else: if other.tokens[i - 1].value == '+' or i == 0: expression.tokens.extend([Plus(), Variable(token)]) elif other.tokens[i - 1].value == '-': expression.tokens.extend( [Minus(), Variable(token)]) elif not isinstance(token, Binary): if other.tokens[i - 1].value == '+' or (i == 0): expression.tokens.extend([Minus(), token]) elif other.tokens[i - 1].value == '-': expression.tokens.extend([Plus(), token]) expression.tokens[0] = self self = expression return expression
def __sub__(self, other): if isinstance(other, Constant): self = self + Constant(-1, 1, 1) * other return self elif isinstance(other, Variable): if self.value == 0: other.coefficient *= -1 return other expression = Expression() expression.tokens = [self] expression.tokens.extend([Minus(), other]) elif isinstance(other, Expression): expression = Expression() expression.tokens = [self] if other.power == 1: coeff = other.coefficient for i, token in enumerate(other.tokens): print(expression, " ", type(token), other.tokens[i-1]) if isinstance(token, Constant): if other.tokens[i-1].value == '+' or i == 0: expression.tokens[0] = Constant(self.calculate() - token.calculate()*coeff) elif other.tokens[i-1].value == '-': expression.tokens[0] = Constant(self.calculate() + token.calculate()*coeff) elif isinstance(token, Variable): if other.tokens[i-1].value == '+' or i == 0: expression.tokens.extend([Minus(), Variable(token)]) elif other.tokens[i-1].value == '-': expression.tokens.extend([Plus(), Variable(token)]) else: expression.tokens.extend([Minus(), other]) self = expression return expression
def differentiationProductRule(tokens, wrtVar): resultTokens = [] for i in range(0, len(tokens), 2): currentDiff = Expression() currentDiffTokens, _, _, _, _ = differentiate([tokens[i]], wrtVar) currentDiff.tokens = currentDiffTokens tempTokens = copy.deepcopy(tokens) tempTokens[i] = currentDiff resultTokens.extend(tempTokens) resultTokens.append(Plus()) resultTokens.pop() token_string = tokensToString(resultTokens) # TODO: Make simplify module to simplify expressions involving Trigonometric Expressions (to some extent) # resultTokens, _, token_string, _, _ = simplify(resultTokens) return tokens, [], token_string, [], []
def test_substitute(): init_tok = getTokens("x") subs_tok = getTokens("2") tok_list = getTokens("3zx^2 + x^3 + 5x") assert tokensToString(substitute(init_tok, subs_tok, tok_list)) == "12.0z + 8.0 + 10.0" init_tok = getTokens("2x") subs_tok = getTokens("4yz^2") tok_list = getTokens("3 + 2x + zx^4 + 3xyz") assert tokensToString(substitute(init_tok, subs_tok, tok_list)) == "3.0 + 4.0yz^(2.0) + 16.0z^(9.0)y^(4.0) + 6.0y^(2.0)z^(3.0)" init_tok = getTokens("4x^2") subs_tok = getTokens("9yz") tok_list = getTokens("2x + zx^3 + 3xyz") assert tokensToString(substitute(init_tok, subs_tok, tok_list)) == "3.0y^(0.5)z^(0.5) + 3.375z^(2.5)y^(1.5) + 4.5y^(1.5)z^(1.5)" init_tok = getTokens("2xy^3") subs_tok = getTokens("4z") tok_list = getTokens("3 + 2xy^3 + z + 3x^(2)y^(6)z") assert tokensToString(substitute(init_tok, subs_tok, tok_list)) == "3.0 + 4.0z + z + 12.0z^(3.0)" init_tok = getTokens("5x") subs_tok = Expression(getTokens("y + 2")) tok_list = getTokens("3 + 4x + 2xy^3 + 3x^(2)y^(3)z") assert tokensToString(substitute(init_tok, subs_tok, tok_list)) == "3.0 + 0.8*(y + 2.0) + (0.4y^(3.0) * (y + 2.0)) + (0.12y^(3.0)z * (y + 2.0)^(2.0))"
def scalarSub(const, mat): """ Subtracts constant terms with Matrix Arguments: const {string}--- constant value mat {visma.matrix.structure.Matrix} -- matrix token Returns: matRes {visma.matrix.structure.Matrix} -- subtracted matrix token Note: This scalar addition follows the following equation {mat} - {lambda}{identity mat} """ matRes = Matrix() matRes.empty([mat.dim[0], mat.dim[1]]) for i in range(mat.dim[0]): for j in range(mat.dim[1]): if i != j: matRes.value[i][j].extend(mat.value[i][j]) else: if len(mat.value[i][j]) != 1: matRes.value[i][j].append(Expression(mat.value[i][j])) else: matRes.value[i][j].extend(mat.value[i][j]) matRes.value[i][j].append(Binary('-')) matRes.value[i][j].append(Constant(int(const))) matRes = simplifyMatrix(matRes) return matRes
def scalarDiv(const, mat): """Divides constant terms with Matrix Arguments: const {string}--- constant value mat {visma.matrix.structure.Matrix} -- matrix token Returns: matRes {visma.matrix.structure.Matrix} -- result matrix token """ if const != 0: matRes = Matrix() matRes.empty([mat.dim[0], mat.dim[1]]) for i in range(mat.dim[0]): for j in range(mat.dim[1]): if len(mat.value[i][j]) != 1: matRes.value[i][j].append(Expression(mat.value[i][j])) else: matRes.value[i][j].extend(mat.value[i][j]) matRes.value[i][j].append(Binary('/')) matRes.value[i][j].append(Constant(int(const))) matRes = simplifyMatrix(matRes) return matRes else: logger.error("ZeroDivisionError: Cannot divide matrix by zero")
def differentiateTokens(funclist, wrtVar): """Differentiates given tokens wrt given variable Arguments: funclist {list} -- list of function tokens wrtVar {string} -- with respect to variable Returns: diffFunc {list} -- list of differentiated tokens animNew {list} -- equation tokens for step-by-step commentsNew {list} -- comments for step-by-step """ diffFunc = [] animNew = [] commentsNew = ["Differentiating with respect to " + r"$" + wrtVar + r"$" + "\n"] for func in funclist: if isinstance(func, Operator): diffFunc.append(func) else: newExpression = Expression() newfunc = [] while(isinstance(func, Function)): commentsNew[0] += r"$" + "\\frac{d}{d" + wrtVar + "} ( " + func.__str__() + ")" + r"$" funcCopy = copy.deepcopy(func) if wrtVar in funcCopy.functionOf(): if isinstance(funcCopy, Trigonometric) or isinstance(funcCopy, Logarithm) or isinstance(funcCopy, Variable) or isinstance(funcCopy, Exponential): funcCopy = funcCopy.differentiate(wrtVar) newfunc.append(funcCopy) commentsNew[0] += r"$" + r"= " + funcCopy.__str__() + r"\ ;\ " + r"$" else: funcCopy = Zero() newfunc.append(funcCopy) commentsNew[0] += r"$" + r"= " + funcCopy.__str__() + r"\ ;\ " + r"$" newfunc.append(Multiply()) if func.operand is None: break else: func = func.operand if isinstance(func, Constant): diffFunc = Zero() break newfunc.pop() newExpression.tokens = newfunc diffFunc.extend([newExpression]) animNew.extend(diffFunc) return diffFunc, animNew, commentsNew
def test_isTokenInToken(): varA = getTokens("x^3") varB = getTokens("xy^2") varC = Expression(getTokens("1 + w + x")) varD = Expression(getTokens("w + y")) assert isTokenInToken(varA, varB) assert isTokenInToken(varA, varC) assert not isTokenInToken(varA, varD) varA = getTokens("xy^2") varB = getTokens("x^(2)y^(4)z") varC = getTokens("yx^0.5") varD = getTokens("xy^(3)z") varE = getTokens("2") assert isTokenInToken(varA, varB) assert isTokenInToken(varA, varC) assert not isTokenInToken(varA, varD) assert not isTokenInToken(varA, varE)
def integrate(self, wrtVar): if wrtVar not in self.value: self.value.append(wrtVar) self.power.append(1) else: for i, val in enumerate(self.value): if val == 'wrtVar': break if self.power[i] == -1: self.power.pop(i) self.value.pop(i) expression = Expression() expression.tokens = [self] variable = Variable(1, 'wrtVar', 1) expression.tokens.append(Logarithm(variable)) self.__class__ = Expression self = expression else: self.coefficient /= self.power[i] + 1 self.power[i] += 1
def inverse(self, rToken, wrtVar): l2rVar = Variable() for i, var in enumerate(self.value): if var != wrtVar: l2rVar.value.append(self.value.pop(i)) l2rVar.power.append(self.power.pop(i)) if l2rVar.value != []: rToken = Expression([rToken, Divide(), l2rVar]) rToken.coefficient /= (self.coefficient)**(1 / self.power[0]) rToken.power /= self.power[0] self.coefficient = 1 self.power[0] = 1 comment = "Therefore, " + r"$" + wrtVar + r"$" + " can be written as:" return self, rToken, comment
def substituteTokens(initTok, subsTok, givenTok): """Substitute initTok with subsTok in a givenTok. For example: substitute x(initTok) with wyz^2(subsTok) in xyz(givenTok) i.e. final_tok will be wy^2z^3 Arguments: initTok {functions.structure.Function} -- token to be substituted subsTok {functions.structure.Function} -- substitute token givenTok {functions.structure.Function} -- given token Returns: givenTok {functions.structure.Function} -- given token after substitution """ if isinstance(givenTok, Variable): if isinstance(initTok, Variable): power = getPowerRatio(initTok, givenTok) if isinstance(subsTok, Constant): givenTok = removeValues(initTok, givenTok) if len(givenTok.value) == 0: givenTok = Constant( (subsTok.value**power) * givenTok.coefficient) else: givenTok.coefficient *= subsTok.value**power elif isinstance(subsTok, Variable): givenTok.coefficient /= initTok.coefficient**power givenTok.coefficient *= subsTok.coefficient**power givenTok = replaceValues(initTok, subsTok, givenTok, power) elif isinstance(subsTok, Expression): subs_copy = copy.deepcopy(subsTok) givenTok.coefficient /= initTok.coefficient**power givenTok.coefficient *= subs_copy.coefficient**power subs_copy.coefficient = 1 subs_copy.power = power givenTok = removeValues(initTok, givenTok) if len(givenTok.value) == 0: subs_copy.coefficient = givenTok.coefficient givenTok = subs_copy else: givenTok = Expression([givenTok, Multiply(), subs_copy]) elif isinstance(givenTok, Expression): substitute(initTok, subsTok, Expression.toklist) return givenTok
def __mul__(self, other): from visma.io.checks import isNumber from visma.functions.constant import Constant if isinstance(other, Variable): for j, var in enumerate(other.value): found = False for k, var2 in enumerate(self.value): self.coefficient *= other.coefficient if var == var2: if isNumber(other.power[j]) and isNumber( self.power[k]): self.power[k] += other.power[j] if self.power[k] == 0: del self.power[k] del self.value[k] found = True break if not found: self.value.append(other.value[j]) self.power.append(other.power[j]) if len(self.value) == 0: result = Constant(self.coefficient) result.scope = self.scope result.power = 1 result.value = self.coefficient self = result return self elif isinstance(other, Constant): self.coefficient *= other.calculate() return self elif isinstance(other, Expression): result = Expression() for _, token in enumerate(other.tokens): if isinstance(token, Variable) or isinstance(token, Constant): c = copy.deepcopy(self) result.tokens.extend([c * token]) else: result.tokens.extend([token]) return result
def integrate(self, wrtVar): term1 = Constant(-1, 1, 1) term2 = NaturalLog() result = Expression() term3 = Cosecant() term3.operand = self.operand term4 = Cotangent() term4.operand = self.operand inExpression = Expression() inExpression.tokens = [term3, Plus(), term4] term2.operand = inExpression term2.power = 1 term2.coefficient = 1 result.tokens = [term1, Multiply(), term2] return result
def funcInverse(lTokens, rTokens, wrtVar): """Applies inverse of funtion of wrtVar to RHS Arguments: lTokens {list} -- LHS tokens list rTokens {list} -- RHS tokens list wrtVar {string} -- variable to be solved Returns: lTokens {list} -- LHS tokens list rTokens {list} -- RHS tokens list animation {list} -- list of equation solving progress comments {list} -- list of solution steps """ if len(lTokens) == 1: rExpr = Expression() rExpr.tokens.extend(rTokens) lToken, rToken, comment = lTokens[0].inverse(rExpr, wrtVar) animation = copy.deepcopy(lTokens) animation.append(EqualTo()) animation.append(rToken) return [lToken], [rToken], animation, [comment]
def __add__(self, other): if isinstance(other, Constant): if self.before == '-': result = Constant(self.calculate() - other.calculate(), self.power) else: result = Constant(self.calculate() + other.calculate(), self.power) self.value = result.value if result.value == 0 and result.power == 0: result.value = 1 result.power = 1 result.scope = self.scope result.value = result.calculate() return result elif self.isZero(): return other elif other.isZero(): return self elif isinstance(other, Expression): if other.power == 1 and other.coefficient == 1: constFound = False for i, var in enumerate(other.tokens): if isinstance(var, Constant): if other.tokens[i-1].value == '+' or i == 0: other.tokens[i] = self + var elif other.tokens[i-1].value == '-': other.tokens[i-1] = self - var constFound = True break if not constFound: other.tokens.extend([Plus(), self]) return other else: pass self.value = self.calculate() self.power = 1 self.coefficient = 1 exprAdd = Expression([self, Plus(), other]) # Make an Expression and assign the Tokens attribute with the Constant and the Other Variable, Trig. function,...etc. return exprAdd
def scalarMult(const, mat): """Multiplies constant terms with Matrix Arguments: const {string}--- constant value mat {visma.matrix.structure.Matrix} -- matrix token Returns: matRes {visma.matrix.structure.Matrix} -- product matrix token """ matRes = Matrix() matRes.empty([mat.dim[0], mat.dim[1]]) for i in range(mat.dim[0]): for j in range(mat.dim[1]): if len(mat.value[i][j]) != 1: matRes.value[i][j].append(Expression(mat.value[i][j])) else: matRes.value[i][j].extend(mat.value[i][j]) matRes.value[i][j].append(Binary('*')) matRes.value[i][j].append(Constant(int(const))) matRes = simplifyMatrix(matRes) return matRes
def test_Constant(): # Tests for Calculus operations for Constant Class. constant1 = Constant(10) assert constant1.__str__() == "{10}" constant1.differentiate() assert constant1.value == 0 constant2 = Constant(5, 2) constant2.integrate('x') assert isinstance(constant2, Variable) assert constant2.__str__() == "25{x}" # Tests for Add/Sub operations (using Overloading) for Constant Class. constant4 = Constant(2, 2) constant5 = Constant(7) constant3 = constant4 - constant5 assert constant3.__str__() == "{-3}" constant4 = Constant(7, 2) constant0 = Constant(5) constant6 = constant4 - constant3 - constant5 + constant0 assert constant6.__str__() == "{50}" constant0 = Constant(5, 2, 2) constant2 = constant0 variable0 = Variable(5, 'X', 3) summation0 = constant0 - variable0 + constant2 assert summation0.__str__() == "{({100}-5{X}^{3})}" constant0 = Constant(5, 2, 2) constant2 = constant0 variable0 = Variable(5, 'X', 3) summation0 = constant0 + variable0 + constant2 assert summation0.__str__() == "{({100}+5{X}^{3})}" var1 = Variable(3, 'x', 3) const1 = Constant(5) expr1 = Expression([var1, Minus(), const1]) constant2 = Constant(2, 2) sub1 = constant2 - expr1 assert sub1.__str__() == "{({9}-3{x}^{3})}" constant1 = Constant(2) constant2 = Constant(7) constant3 = constant1 + constant2 assert constant3.__str__() == "{9}" constant1 = Constant(2) constant2 = Constant(7) constant3 = constant1 - constant2 assert constant3.__str__() == "{-5}" constant1 = Constant(5) variable1 = Variable(5, 'x', 3) summation = constant1 + variable1 assert summation.__str__() == "{({5}+5{x}^{3})}" constant1 = Constant(5) variable1 = Variable(5, 'x', 3) summation = constant1 - variable1 assert summation.__str__() == "{({5}-5{x}^{3})}" # Tests for Add/Sub operations (using Overloading) for Constant Class. constant0 = Constant(0, 2) constant1 = Constant(5) mul1 = constant0 * constant1 assert mul1.calculate() == 0 mul1 = constant1 * constant0 assert mul1.calculate() == 0 mul1 = constant1 * constant1 + constant0 * constant1 + constant0 * constant1 assert mul1.calculate() == 25 constant1 = Constant(5, 2) constant2 = Constant(4, 2) variable0 = Variable(3, 'X', 3) mul3 = constant1 * (constant2 + variable0) assert mul3.__str__() == "{({400}+75{X}^{3})}" constant1 = Constant(5, 2) constant2 = Constant(4, 2) variable0 = Variable(3, 'X', 3) mul3 = constant1 / (constant2 + variable0) assert mul3.__str__() == "{25}*{({16}+3{X}^{3})}^{-1}" constant1 = Constant(5) constant2 = Constant(4) div1 = constant1 / constant2 assert div1.__str__() == "{1.25}" constant1 = Constant(3, 2) constant2 = Constant(4, 2) variable0 = Variable(3, 'X', 3) mul3 = constant1 - constant1 / (constant2 / variable0 + constant1) assert mul3.__str__( ) == "{({9}-{9}*{(5.333333333333333{X}^{-3}+{9})}^{-1})}" constant1 = Constant(2, 2) constant2 = Constant(2, 2) mul3 = constant1**constant2 assert mul3.__str__() == "{256}" constant1 = Constant(5) constant2 = Constant(5) summation = constant1 * constant2 assert summation.__str__() == "{25}" constant1 = Constant(5) variable1 = Variable(5, 'x', 3) exp1 = Expression([constant1, Plus(), variable1]) constant2 = Constant(10) summation = constant2 + exp1 assert summation.__str__() == "{({15}+5{x}^{3})}" constant1 = Constant(5) variable1 = Variable(5, 'x', 3) exp1 = Expression([constant1, Plus(), variable1]) constant2 = Constant(10) summation = constant2 - exp1 assert summation.__str__() == "{({5}-5{x}^{3})}" constant1 = Constant(5) variable1 = Variable(5, 'x', 3) exp1 = Expression([constant1, Plus(), variable1]) constant2 = Constant(10) summation = exp1 - constant2 assert summation.__str__() == "{({-5}+5{x}^{3})}" constant1 = Constant(5) variable1 = Variable(5, 'x', 3) summation = constant1 * variable1 assert summation.__str__() == "25{x}^{3}" constant1 = Constant(5) variable1 = Variable(5, 'x', 3) exp1 = Expression([constant1, Plus(), variable1]) constant2 = Constant(10) summation = constant2 * exp1 assert summation.__str__() == "{({50}+50{x}^{3})}" constant1 = Constant(5) constant2 = Constant(5) summation = constant1 / constant2 assert summation.__str__() == "{1.0}" constant1 = Constant(5) variable1 = Variable(5, 'x', 3) summation = constant1 / variable1 assert summation.__str__() == "{x}^{-3}" constant1 = Constant(5) variable1 = Variable(5, 'x', 3) exp1 = Expression([constant1, Plus(), variable1]) constant2 = Constant(10) summation = constant2 / exp1 assert summation.__str__() == "{10}*{({5}+5{x}^{3})}^{-1}" constant1 = Constant(5) variable1 = Variable(5, 'x', 3) exp1 = Expression([constant1, Plus(), variable1]) constant2 = Constant(10) summation = exp1 / constant2 assert summation.__str__() == "{({0.5}+0.5{x}^{3})}"
def test_Variable(): variable1 = Variable(2, 'x', 3) assert variable1.__str__() == "2{x}^{3}" variable1, _ = variable1.integrate('x') assert variable1.__str__() == "0.5{x}^{4}" constant = Constant(3) variable = Variable(2, 'x', 3) add = variable + constant assert add.__str__() == "{(2{x}^{3}+{3})}" variable1 = Variable(2, 'x', 3) variable2 = Variable(4, 'x', 3) add1 = variable1 + variable2 assert add1.__str__() == "6{x}^{3}" variable1 = Variable(2, 'x', 3) constant = Constant(3) exp1 = Expression([variable1, Plus(), constant]) variable2 = Variable(4, 'x', 3) add2 = variable2 + exp1 assert add2.__str__() == "{(6{x}^{3}+{3})}" variable1 = Variable(2, 'x', 3) constant = Constant(3) exp1 = variable1 + constant variable2 = Variable(4, 'x', 3) add2 = variable2 - exp1 assert add2.__str__() == "{(2{x}^{3}-{3})}" variable1 = Variable(2, 'x', 3) constant = Constant(3) exp1 = Expression([variable1, Plus(), constant]) variable2 = Variable(4, 'x', 3) add2 = exp1 - variable2 assert add2.__str__() == "{(-2{x}^{3}+{3})}" constant = Constant(3) variable = Variable(2, 'x', 3) add = variable - constant assert add.__str__() == "{(2{x}^{3}-{3})}" variable1 = Variable(2, 'x', 3) variable2 = Variable(4, 'x', 3) variable3 = Variable(2, 'x', 4) variable4 = Variable(2, 'x', 3) add1 = variable1 - variable2 add2 = variable3 - variable4 assert add1.__str__() == "-2{x}^{3}" assert add2.__str__() == "{(2{x}^{4}-2{x}^{3})}" constant = Constant(3) variable = Variable(2, 'x', 3) add = variable * constant assert add.__str__() == "6{x}^{3}" variable1 = Variable(2, 'x', 3) variable2 = Variable(4, 'x', 3) add2 = variable1 * variable2 assert add2.__str__() == "8{x}^{6}" variable1 = Variable(2, 'x', 3) variable2 = Variable(4, 'y', 3) add2 = variable1 * variable2 assert add2.__str__() == "8{x}^{3}{y}^{3}" variable1 = Variable(2, 'x', 3) variable2 = Variable(4, 'y', 4) add1 = variable1 / variable2 assert add1.__str__() == "0.5{x}^{3}{y}^{-4}" variable1 = Variable(2, 'x', 3) constant = Constant(3) exp1 = variable1 - constant variable2 = Variable(4, 'x', 3) add2 = variable2 / exp1 assert add2.__str__() == "{(4.0{x}^{3}*{(2{x}^{3}-{3})}^{-1})}" variable1 = Variable(2, 'x', 3) constant = Constant(3) exp1 = variable1 - constant variable2 = Variable(4, 'x', 3) add2 = variable2 * exp1 assert add2.__str__() == "{(8{x}^{6}-12{x}^{3})}" variable1 = Variable(2, 'x', 3) constant1 = Constant(3) exp1 = variable1 - constant1 variable2 = Variable(4, 'x', 3) constant2 = Constant(4) exp2 = variable2 - constant2 add2 = exp1 * exp2 assert add2.__str__() == "{({(8{x}^{6}-8{x}^{3})}-{(12{x}^{3}-{12})})}" variable2 = Variable(3, 'x', -1) variable2, _ = variable2.integrate('x') assert tokensToString(variable2) == '3 * log(x)'
def inverse(self): """Calculates the inverse of the matrix using Gauss-Jordan Elimination Arguments: matrix {visma.matrix.structure.Matrix} -- matrix token Returns: inv {visma.matrix.structure.Matrix} -- result matrix token """ from visma.simplify.simplify import simplify from visma.io.tokenize import tokenizer from visma.io.parser import tokensToString if tokensToString(self.determinant()) == "0": return -1 self.dim[0] = len(self.value) self.dim[1] = len(self.value[0]) n = self.dim[0] mat = Matrix() mat.empty([n, 2 * n]) for i in range(0, n): for j in range(0, 2 * n): if j < n: mat.value[i][j] = self.value[i][j] else: mat.value[i][j] = [] for i in range(0, n): for j in range(n, 2 * n): if j == (i + n): mat.value[i][j].extend(tokenizer('1')) else: mat.value[i][j].extend(tokenizer("0")) for i in range(n - 1, 0, -1): if mat.value[i - 1][0][0].value < mat.value[i][0][0].value: for j in range(0, 2 * n): temp = mat.value[i][j] mat.value[i][j] = mat.value[i - 1][j] mat.value[i - 1][j] = temp for i in range(0, n): for j in range(0, n): if j != i: temp = [] if len(mat.value[j][i]) != 1: temp.append(Expression(mat.value[j][i])) else: temp.extend(mat.value[j][i]) temp.append(Binary('/')) if len(mat.value[i][i]) != 1: temp.append(Expression(mat.value[i][i])) else: temp.extend(mat.value[i][i]) temp, _, _, _, _ = simplify(temp) for k in range(0, 2 * n): t = [] if mat.value[i][k][0].value != 0: if len(mat.value[i][k]) != 1: t.append(Expression(mat.value[i][k])) else: t.extend(mat.value[i][k]) t.append(Binary('*')) if len(temp) != 1: t.append(Expression(temp)) else: t.extend(temp) t, _, _, _, _ = simplify(t) mat.value[j][k].append(Binary('-')) if len(t) != 1: mat.value[j][k].append(Expression(t)) else: mat.value[j][k].extend(t) mat.value[j][k], _, _, _, _ = simplify( mat.value[j][k]) for i in range(0, n): temp = [] temp.extend(mat.value[i][i]) for j in range(0, 2 * n): if mat.value[i][j][0].value != 0: mat.value[i][j].append(Binary('/')) mat.value[i][j].extend(temp) mat.value[i][j], _, _, _, _ = simplify(mat.value[i][j]) inv = SquareMat() inv.empty([n, n]) for i in range(0, n): for j in range(n, 2 * n): inv.value[i][j - n] = mat.value[i][j] return inv