def solveFor(lTokens, rTokens, wrtVar): """Solve the input equation wrt to selected variable 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 availableOperations {list} -- list of operations token_string {string} -- final result in string animation {list} -- list of equation solving progress comments {list} -- list of solution steps """ lTokens, rTokens, availableOperations, token_string, animation, comments = simplifyEquation( lTokens, rTokens) lTokens, rTokens, animNew, commentsNew = solveTokens( lTokens, rTokens, wrtVar) tokenToStringBuilder = copy.deepcopy(lTokens) tokenToStringBuilder.append(EqualTo()) tokenToStringBuilder.extend(rTokens) token_string = tokensToString(tokenToStringBuilder) animation.extend(animNew) comments.extend(commentsNew) return lTokens, rTokens, availableOperations, token_string, animation, comments
def preprocessCheckPolynomial(lTokens, rTokens): """Checks if given equation is a polynomial and returns degree Arguments: lTokens {list} -- list of function tokens rTokens {list} -- list of function tokens Returns: bool -- if polynomial or not int -- degree of polynomial (-1 if bool is False) """ from visma.simplify.simplify import simplifyEquation # Circular import lTokens, rTokens, _, _, _, _ = simplifyEquation(lTokens, rTokens) lVariables = getVariables(lTokens) rVariables = getVariables(rTokens) for token in lTokens: if isinstance(token, Binary): if token.value in ['*', '/']: return False, -1 for token in rTokens: if isinstance(token, Binary): if token.value in ['*', '/']: return False, -1 # OPTIMIZE if len(lVariables) == 1 and len(rVariables) == 1: if isIntegerPower(lTokens, lVariables[0]) and isIntegerPower(rTokens, rVariables[0]): if lVariables[0] == rVariables[0]: return True, max(highestPower(lTokens, lVariables[0]), highestPower(rTokens, rVariables[0])) elif len(lVariables) == 1 and len(rVariables) == 0: if isIntegerPower(lTokens, lVariables[0]): return True, highestPower(lTokens, lVariables[0]) elif len(lVariables) == 0 and len(rVariables) == 1: if isIntegerPower(rTokens, rVariables[0]): return True, highestPower(lTokens, lVariables[0]) return False, -1
def quickSimplify(workspace): """Dynamic simplifier for simplifying expression as it is being typed Arguments: workspace {QtWidgets.QWidget} -- main layout Returns: qSolution/log {string} -- quick solution or error log enableInteraction {bool} -- if False disables 'visma'(interaction) button """ # FIXME: Crashes for some cases. Find and fix. logger.setLogName('qsolver') logger.setLevel(0) qSolution = "" strIn = workspace.textedit.toPlainText() cleanInput = removeSpaces(strIn) if ';' in cleanInput: return "", True, True terms = getTerms(cleanInput) normalizedTerms = normalize(terms) symTokens = tokenizeSymbols(normalizedTerms) normalizedTerms, symTokens = removeUnary(normalizedTerms, symTokens) if checkEquation(normalizedTerms, symTokens) is True and strIn != "": if symTokens and symTokens[-1] is not False: tokens = getToken(normalizedTerms, symTokens) tokens = tokens.tokens lhs, rhs = getLHSandRHS(tokens) _, solutionType = checkTypes(lhs, rhs) lhs, rhs = getLHSandRHS(tokens) if solutionType == 'expression': _, _, _, equationTokens, _ = simplify(tokens) qSolution = r'$ ' + '= \ ' else: _, _, _, _, equationTokens, _ = simplifyEquation(lhs, rhs) qSolution = r'$ ' + '\Rightarrow \ ' qSolution += tokensToLatex(equationTokens[-1]) + ' $' # workspace.eqToks = equationTokens # plot(workspace) return qSolution, True, False elif symTokens: log = "Invalid Expression" workspace.logBox.append(logger.error(log)) return log, False, _ else: log = "" workspace.logBox.append(logger.error(log)) return log, False, _ else: log = "" if strIn != "": _, log = checkEquation(normalizedTerms, symTokens) workspace.logBox.append(logger.error(log)) return log, False, _
def quickSimplify(workspace): """Dynamic simplifier for simplifying expression as it is being typed Arguments: workspace {QtWidgets.QWidget} -- main layout Returns: qSolution/log {string} -- quick solution or error log """ # FIXME: Crashes for some cases. Find and fix. qSolution = "" input = workspace.textedit.toPlainText() cleanInput = removeSpaces(input) terms = getTerms(cleanInput) normalizedTerms = normalize(terms) symTokens = tokenizeSymbols(normalizedTerms) terms, symTokens = removeUnary(normalizedTerms, symTokens) if checkEquation(normalizedTerms, symTokens) is True and input != "": if symTokens[-1] is not False: tokens = getToken(normalizedTerms, symTokens) tokens = tokens.tokens lhs, rhs = getLHSandRHS(tokens) _, solutionType = checkTypes(lhs, rhs) if solutionType == 'expression': _, _, _, equationTokens, _ = simplify(tokens) qSolution = r'$ ' + '= \ ' else: _, _, _, _, equationTokens, _ = simplifyEquation(lhs, rhs) qSolution = r'$ ' + '\Rightarrow \ ' qSolution += tokensToLatex(equationTokens[-1]) + ' $' # workspace.eqToks = equationTokens # plot(workspace) return qSolution else: log = "Invalid Expression" return log else: log = "" if input != "": _, log = checkEquation(normalizedTerms, symTokens) return log
def calluser(): availableOperations = [] tokenString = '' equationTokens = [] self.resultOut = True if name == 'addition': if self.solutionType == 'expression': self.tokens, availableOperations, tokenString, equationTokens, comments = addition( self.tokens, True) else: self.lTokens, self.rTokens, availableOperations, tokenString, equationTokens, comments = additionEquation( self.lTokens, self.rTokens, True) elif name == 'subtraction': if self.solutionType == 'expression': self.tokens, availableOperations, tokenString, equationTokens, comments = subtraction( self.tokens, True) else: self.lTokens, self.rTokens, availableOperations, tokenString, equationTokens, comments = subtractionEquation( self.lTokens, self.rTokens, True) elif name == 'multiplication': if self.solutionType == 'expression': self.tokens, availableOperations, tokenString, equationTokens, comments = multiplication( self.tokens, True) else: self.lTokens, self.rTokens, availableOperations, tokenString, equationTokens, comments = multiplicationEquation( self.lTokens, self.rTokens, True) elif name == 'division': if self.solutionType == 'expression': self.tokens, availableOperations, tokenString, equationTokens, comments = division( self.tokens, True) else: self.lTokens, self.rTokens, availableOperations, tokenString, equationTokens, comments = divisionEquation( self.lTokens, self.rTokens, True) elif name == 'simplify': if self.solutionType == 'expression': self.tokens, availableOperations, tokenString, equationTokens, comments = simplify( self.tokens) else: self.lTokens, self.rTokens, availableOperations, tokenString, equationTokens, comments = simplifyEquation( self.lTokens, self.rTokens) elif name == 'factorize': self.tokens, availableOperations, tokenString, equationTokens, comments = factorize( self.tokens) elif name == 'find roots': self.lTokens, self.rTokens, availableOperations, tokenString, equationTokens, comments = quadraticRoots( self.lTokens, self.rTokens) elif name == 'solve': lhs, rhs = getLHSandRHS(self.tokens) variables = getVariables(lhs, rhs) self.wrtVariableButtons(variables, name) self.resultOut = False elif name == 'integrate': lhs, rhs = getLHSandRHS(self.tokens) variables = getVariables(lhs, rhs) self.wrtVariableButtons(variables, name) self.resultOut = False elif name == 'differentiate': lhs, rhs = getLHSandRHS(self.tokens) variables = getVariables(lhs, rhs) self.wrtVariableButtons(variables, name) self.resultOut = False if self.resultOut: self.eqToks = equationTokens self.output = resultLatex(name, equationTokens, comments) if len(availableOperations) == 0: self.clearButtons() else: self.refreshButtons(availableOperations) if self.mode == 'normal': self.textedit.setText(tokenString) elif self.mode == 'interaction': cursor = self.textedit.textCursor() cursor.insertText(tokenString) if self.showStepByStep is True: showSteps(self) if self.showPlotter is True: plot(self)
def commandExec(command): operation = command.split('(', 1)[0] inputEquation = command.split('(', 1)[1][:-1] if ',' in inputEquation: varName = inputEquation.split(',')[1] inputEquation = inputEquation.split(',')[0] lhs = [] rhs = [] solutionType = '' lTokens = [] rTokens = [] equationTokens = [] comments = [] tokens = tokenizer(inputEquation) lhs, rhs = getLHSandRHS(tokens) lTokens = lhs rTokens = rhs _, solutionType = checkTypes(lhs, rhs) if operation == 'simplify': if solutionType == 'expression': tokens, _, _, equationTokens, comments = simplify(tokens) else: lTokens, rTokens, _, _, equationTokens, comments = simplifyEquation( lTokens, rTokens) elif operation == 'addition': if solutionType == 'expression': tokens, _, _, equationTokens, comments = addition(tokens, True) else: lTokens, rTokens, _, _, equationTokens, comments = additionEquation( lTokens, rTokens, True) elif operation == 'subtraction': if solutionType == 'expression': tokens, _, _, equationTokens, comments = subtraction(tokens, True) else: lTokens, rTokens, _, _, equationTokens, comments = subtractionEquation( lTokens, rTokens, True) elif operation == 'multiplication': if solutionType == 'expression': tokens, _, _, equationTokens, comments = multiplication( tokens, True) else: lTokens, rTokens, _, _, equationTokens, comments = multiplicationEquation( lTokens, rTokens, True) elif operation == 'division': if solutionType == 'expression': tokens, _, _, equationTokens, comments = division(tokens, True) else: lTokens, rTokens, _, _, equationTokens, comments = divisionEquation( lTokens, rTokens, True) elif operation == 'simplify': if solutionType == 'expression': tokens, _, _, equationTokens, comments = simplify(tokens) else: lTokens, rTokens, _, _, equationTokens, comments = simplifyEquation( lTokens, rTokens) elif operation == 'factorize': tokens, _, _, equationTokens, comments = factorize(tokens) elif operation == 'find-roots': lTokens, rTokens, _, _, equationTokens, comments = quadraticRoots( lTokens, rTokens) elif operation == 'solve': lhs, rhs = getLHSandRHS(tokens) lTokens, rTokens, _, _, equationTokens, comments = solveFor( lTokens, rTokens, varName) elif operation == 'integrate': lhs, rhs = getLHSandRHS(tokens) lTokens, _, _, equationTokens, comments = integrate(lTokens, varName) elif operation == 'differentiate': lhs, rhs = getLHSandRHS(tokens) lTokens, _, _, equationTokens, comments = differentiate( lTokens, varName) printOnCLI(equationTokens, operation, comments)
def cubicRoots(lTokens, rTokens): '''Used to get roots of a cubic equation This functions also translates roots {list} into final result of solution Argument: lTokens {list} -- list of LHS tokens rTokens {list} -- list of RHS tokens Returns: lTokens {list} -- list of LHS tokens rTokens {list} -- list of RHS tokens {empty list} token_string {string} -- final result stored in a string animation {list} -- list of equation solving process comments {list} -- list of comments in equation solving process ''' from visma.solvers.polynomial.roots import getCoefficients animations = [] comments = [] lTokens, rTokens, _, token_string, animNew1, commentNew1 = simplifyEquation( lTokens, rTokens) animations.extend(animNew1) comments.extend(commentNew1) if len(rTokens) > 0: lTokens, rTokens = moveRTokensToLTokens(lTokens, rTokens) coeffs = getCoefficients(lTokens, rTokens, 3) var = getVariables(lTokens) roots, animNew2, commentNew2 = getRootsCubic(coeffs) animations.extend(animNew2) comments.extend(commentNew2) tokens1 = [] expression1 = Expression(coefficient=1, power=3) variable = Variable(1, var[0], 1) tokens1.append(variable) if roots[0][1] == 0: binary = Binary() if roots[0][0] < 0: roots[0][0] *= -1 binary.value = '+' else: binary.value = '-' tokens1.append(binary) constant = Constant(round(roots[0][0], ROUNDOFF), 1) tokens1.append(constant) expression1.tokens = tokens1 lTokens = [expression1, Binary('*')] if len(roots) > 1: expression1.power = 1 for _, root in enumerate(roots[1:]): tokens2 = [] expression2 = Expression(coefficient=1, power=1) variable = Variable(1, var[0], 1) tokens2.append(variable) binary = Binary() if root[1] == 0: if root[0] < 0: root[0] *= -1 binary.value = '+' else: binary.value = '-' tokens2.append(binary) constant = Constant(round(root[0], ROUNDOFF), 1) tokens2.append(constant) else: binary.value = '-' tokens2.append(binary) expressionResult = Expression(coefficient=1, power=1) tokensResult = [] real = Constant(round(root[0], ROUNDOFF), 1) tokensResult.append(real) imaginary = Constant(round(root[1], ROUNDOFF), 1) if imaginary.value < 0: tokensResult.append(Minus()) imaginary.value = abs(imaginary.value) tokensResult.append(imaginary) else: tokensResult.extend([Plus(), imaginary]) sqrt = Sqrt(Constant(2, 1), Constant(-1, 1)) tokensResult.append(Binary('*')) tokensResult.append(sqrt) expressionResult.tokens = tokensResult tokens2.append(expressionResult) expression2.tokens = tokens2 lTokens.extend([expression2, Binary('*')]) lTokens.pop() rTokens = [Zero()] tokenToStringBuilder = copy.deepcopy(lTokens) tokLen = len(lTokens) equalTo = Binary() equalTo.scope = [tokLen] equalTo.value = '=' tokenToStringBuilder.append(equalTo) tokenToStringBuilder.extend(rTokens) token_string = tokensToString(tokenToStringBuilder) animations.append(copy.deepcopy(tokenToStringBuilder)) comments.append([]) return lTokens, rTokens, [], token_string, animations, comments
def calluser(): availableOperations = [] tokenString = '' equationTokens = [] self.resultOut = True if not self.matrix: """ This part handles the cases when VisMa is NOT dealing with matrices. Boolean flags used in code below: simul -- {True} when VisMa is dealing with simultaneous equations & {False} in all other cases """ if name == 'addition': if self.solutionType == 'expression': self.tokens, availableOperations, tokenString, equationTokens, comments = addition( self.tokens, True) else: self.lTokens, self.rTokens, availableOperations, tokenString, equationTokens, comments = additionEquation( self.lTokens, self.rTokens, True) elif name == 'subtraction': if self.solutionType == 'expression': self.tokens, availableOperations, tokenString, equationTokens, comments = subtraction( self.tokens, True) else: self.lTokens, self.rTokens, availableOperations, tokenString, equationTokens, comments = subtractionEquation( self.lTokens, self.rTokens, True) elif name == 'multiplication': if self.solutionType == 'expression': self.tokens, availableOperations, tokenString, equationTokens, comments = multiplication( self.tokens, True) else: self.lTokens, self.rTokens, availableOperations, tokenString, equationTokens, comments = multiplicationEquation( self.lTokens, self.rTokens, True) elif name == 'division': if self.solutionType == 'expression': self.tokens, availableOperations, tokenString, equationTokens, comments = division( self.tokens, True) else: self.lTokens, self.rTokens, availableOperations, tokenString, equationTokens, comments = divisionEquation( self.lTokens, self.rTokens, True) elif name == 'simplify': if self.solutionType == 'expression': self.tokens, availableOperations, tokenString, equationTokens, comments = simplify(self.tokens) else: self.lTokens, self.rTokens, availableOperations, tokenString, equationTokens, comments = simplifyEquation(self.lTokens, self.rTokens) elif name == 'factorize': self.tokens, availableOperations, tokenString, equationTokens, comments = factorize(self.tokens) elif name == 'find roots': self.lTokens, self.rTokens, availableOperations, tokenString, equationTokens, comments = rootFinder(self.lTokens, self.rTokens) elif name == 'solve': if not self.simul: lhs, rhs = getLHSandRHS(self.tokens) variables = getVariables(lhs, rhs) else: variables = getVariableSim(self.tokens) self.wrtVariableButtons(variables, name) self.resultOut = False elif name == 'factorial': self.tokens, availableOperations, tokenString, equationTokens, comments = factorial(self.tokens) elif name == 'combination': nTokens = self.tokens[0] rTokens = self.tokens[1] self.tokens, _, _, equationTokens, comments = combination(nTokens, rTokens) elif name == 'permutation': nTokens = self.tokens[0] rTokens = self.tokens[1] self.tokens, _, _, equationTokens, comments = permutation(nTokens, rTokens) elif name == 'integrate': lhs, rhs = getLHSandRHS(self.tokens) variables = getVariables(lhs, rhs) self.wrtVariableButtons(variables, name) self.resultOut = False elif name == 'differentiate': lhs, rhs = getLHSandRHS(self.tokens) variables = getVariables(lhs, rhs) self.wrtVariableButtons(variables, name) self.resultOut = False else: """ This part handles the cases when VisMa is dealing with matrices. Boolean flags used in code below: dualOperand -- {True} when the matrix operations require two operands (used in operations like addition, subtraction etc) nonMatrixResult -- {True} when the result after performing operations on the Matrix is not a Matrix (in operations like Determinant, Trace etc.) scalarOperations -- {True} when one of the operand in a scalar (used in operations like Scalar Addition, Scalar Subtraction etc.) """ # TODO: use latex tools like /amsmath for displaying matrices if self.dualOperandMatrix: Matrix1_copy = copy.deepcopy(self.Matrix1) Matrix2_copy = copy.deepcopy(self.Matrix2) else: Matrix0_copy = copy.deepcopy(self.Matrix0) if name == 'Addition': MatrixResult = addMatrix(self.Matrix1, self.Matrix2) elif name == 'Subtraction': MatrixResult = subMatrix(self.Matrix1, self.Matrix2) elif name == 'Multiply': MatrixResult = multiplyMatrix(self.Matrix1, self.Matrix2) elif name == 'Simplify': MatrixResult = simplifyMatrix(self.Matrix0) elif name == 'Trace': sqMatrix = SquareMat() sqMatrix.value = self.Matrix0.value result = sqMatrix.traceMat() elif name == 'Determinant': sqMatrix = SquareMat() sqMatrix.value = self.Matrix0.value result = sqMatrix.determinant() elif name == 'Inverse': sqMatrix = SquareMat() sqMatrix.value = self.Matrix0.value MatrixResult = SquareMat() MatrixResult = sqMatrix.inverse() if name in ['Addition', 'Subtraction', 'Multiply']: self.dualOperandMatrix = True else: self.dualOperandMatrix = False if name in ['Determinant', 'Trace']: self.nonMatrixResult = True else: self.nonMatrixResult = False if self.resultOut: if not self.matrix: self.eqToks = equationTokens self.output = resultLatex(equationTokens, name, comments, self.solutionType) if (mathError(self.eqToks[-1])): self.output += 'Math Error: LHS not equal to RHS' + '\n' if len(availableOperations) == 0: self.clearButtons() else: self.refreshButtons(availableOperations) if self.mode == 'normal': self.textedit.setText(tokenString) elif self.mode == 'interaction': cursor = self.textedit.textCursor() cursor.insertText(tokenString) if self.showStepByStep is True: showSteps(self) if self.showPlotter is True: plot(self) else: if self.dualOperandMatrix: if not self.scalarOperationsMatrix: self.output = resultMatrixStringLatex(operation=name, operand1=Matrix1_copy, operand2=Matrix2_copy, result=MatrixResult) else: # TODO: Implement Scalar Matrices operations. pass # finalCLIstring = resultMatrix_Latex(operation=name, operand1=scalarTokens_copy, operand2=Matrix2_copy, result=MatrixResult) else: if self.nonMatrixResult: self.output = resultMatrixStringLatex(operation=name, operand1=Matrix0_copy, nonMatrixResult=True, result=result) else: self.output = resultMatrixStringLatex(operation=name, operand1=Matrix0_copy, result=MatrixResult) if self.mode == 'normal': self.textedit.setText(tokenString) elif self.mode == 'interaction': cursor = self.textedit.textCursor() cursor.insertText(tokenString) if self.showStepByStep is True: showSteps(self)
def quadraticRoots(lTokens, rTokens): '''Used to get quadratic roots of an equation Argument: lTokens {list} -- list of LHS tokens rTokens {list} -- list of RHS tokens Returns: lTokens {list} -- list of LHS tokens rTokens {list} -- list of RHS tokens {empty list} token_string {string} -- final result stored in a string animation {list} -- list of equation solving process comments {list} -- list of comments in equation solving process ''' from visma.solvers.polynomial.roots import getCoefficients animations = [] comments = [] lTokens, rTokens, _, token_string, animNew1, commentNew1 = simplifyEquation(lTokens, rTokens) animations.extend(animNew1) comments.extend(commentNew1) if len(rTokens) > 0: lTokens, rTokens = moveRTokensToLTokens(lTokens, rTokens) coeffs = getCoefficients(lTokens, rTokens, 2) var = getVariables(lTokens) roots, animNew2, commentNew2 = getRootsQuadratic(coeffs) animations.extend(animNew2) comments.extend(commentNew2) if len(roots) == 1: tokens = [] expression = Expression(coefficient=1, power=2) variable = Variable(1, var[0], 1) tokens.append(variable) binary = Binary() if roots[0] < 0: roots[0] *= -1 binary.value = '+' else: binary.value = '-' tokens.append(binary) constant = Constant(round(roots[0], ROUNDOFF), 1) tokens.append(constant) expression.tokens = tokens lTokens = [expression] elif len(roots) == 2: tokens = [] expression = Expression(coefficient=1, power=1) variable = Variable(1, var[0], 1) tokens.append(variable) binary = Binary() if roots[0] < 0: roots[0] *= -1 binary.value = '+' else: binary.value = '-' tokens.append(binary) constant = Constant(round(roots[0], ROUNDOFF), 1) tokens.append(constant) expression.tokens = tokens tokens2 = [] expression2 = Expression(coefficient=1, power=1) tokens2.append(variable) binary2 = Binary() if roots[1] < 0: roots[1] *= -1 binary2.value = '+' else: binary2.value = '-' tokens2.append(binary2) constant2 = Constant(round(roots[1], ROUNDOFF), 1) tokens2.append(constant2) expression2.tokens = tokens2 binary3 = Binary() binary3.value = '*' lTokens = [expression, binary3, expression2] elif len(roots) == 3: binary4 = Binary() if roots[0] < 0: roots[0] *= -1 binary4.value = '+' else: binary4.value = '-' constant3 = Constant(round(roots[0], ROUNDOFF), 1) binary5 = Binary() binary5.value = '*' constant2 = Constant(round(roots[2], ROUNDOFF), 1) tokens = [] expression = Expression(coefficient=1, power=1) variable = Variable(1, var[0], 1) tokens.extend([variable, binary4, constant3]) binary = Binary() binary.value = '+' tokens.extend([binary, constant2, binary5]) constant = Constant(round(roots[1], ROUNDOFF), 1) sqrt = Sqrt(Constant(2, 1), constant) tokens.append(sqrt) expression.tokens = tokens tokens2 = [] expression2 = Expression(coefficient=1, power=1) variable2 = Variable(1, var[0], 1) tokens2.extend([variable2, binary4, constant3]) binary2 = Binary() binary2.value = '-' tokens2.extend([binary2, constant2, binary5, sqrt]) expression2.tokens = tokens2 binary3 = Binary() binary3.value = '*' lTokens = [expression, binary3, expression2] zero = Zero() rTokens = [zero] comments.append([]) tokenToStringBuilder = copy.deepcopy(lTokens) tokLen = len(lTokens) equalTo = Binary() equalTo.scope = [tokLen] equalTo.value = '=' tokenToStringBuilder.append(equalTo) tokenToStringBuilder.extend(rTokens) animations.append(copy.deepcopy(tokenToStringBuilder)) token_string = tokensToString(tokenToStringBuilder) return lTokens, rTokens, [], token_string, animations, comments
def commandExec(command): operation = command.split('(', 1)[0] inputEquation = command.split('(', 1)[1][:-1] matrix = False # True when matrices operations are present in the code. if operation[0:4] == 'mat_': matrix = True if not matrix: """ This part handles the cases when VisMa is NOT dealing with matrices. Boolean flags used in code below: simul -- {True} when VisMa is dealing with simultaneous equations & {False} in all other cases """ varName = None if ',' in inputEquation: varName = inputEquation.split(',')[1] varName = "".join(varName.split()) inputEquation = inputEquation.split(',')[0] simul = False # True when simultaneous equation is present if (inputEquation.count(';') == 2) and (operation == 'solve'): simul = True afterSplit = inputEquation.split(';') eqStr1 = afterSplit[0] eqStr2 = afterSplit[1] eqStr3 = afterSplit[2] lhs = [] rhs = [] solutionType = '' lTokens = [] rTokens = [] equationTokens = [] comments = [] if simul: tokens = [tokenizer(eqStr1), tokenizer(eqStr2), tokenizer(eqStr3)] else: tokens = tokenizer(inputEquation) if '=' in inputEquation: lhs, rhs = getLHSandRHS(tokens) lTokens = lhs rTokens = rhs _, solutionType = checkTypes(lhs, rhs) else: solutionType = 'expression' lhs, rhs = getLHSandRHS(tokens) lTokens = lhs rTokens = rhs if operation == 'plot': app = QApplication(sys.argv) App(tokens) sys.exit(app.exec_()) elif operation == 'simplify': if solutionType == 'expression': tokens, _, _, equationTokens, comments = simplify(tokens) else: lTokens, rTokens, _, _, equationTokens, comments = simplifyEquation( lTokens, rTokens) elif operation == 'addition': if solutionType == 'expression': tokens, _, _, equationTokens, comments = addition(tokens, True) else: lTokens, rTokens, _, _, equationTokens, comments = additionEquation( lTokens, rTokens, True) elif operation == 'subtraction': if solutionType == 'expression': tokens, _, _, equationTokens, comments = subtraction( tokens, True) else: lTokens, rTokens, _, _, equationTokens, comments = subtractionEquation( lTokens, rTokens, True) elif operation == 'multiplication': if solutionType == 'expression': tokens, _, _, equationTokens, comments = multiplication( tokens, True) else: lTokens, rTokens, _, _, equationTokens, comments = multiplicationEquation( lTokens, rTokens, True) elif operation == 'division': if solutionType == 'expression': tokens, _, _, equationTokens, comments = division(tokens, True) else: lTokens, rTokens, _, _, equationTokens, comments = divisionEquation( lTokens, rTokens, True) elif operation == 'factorize': tokens, _, _, equationTokens, comments = factorize(tokens) elif operation == 'find-roots': lTokens, rTokens, _, _, equationTokens, comments = rootFinder( lTokens, rTokens) elif operation == 'solve': if simul: if varName is not None: _, equationTokens, comments = simulSolver( tokens[0], tokens[1], tokens[2], varName) else: _, equationTokens, comments = simulSolver( tokens[0], tokens[1], tokens[2]) solutionType = equationTokens else: lhs, rhs = getLHSandRHS(tokens) lTokens, rTokens, _, _, equationTokens, comments = solveFor( lTokens, rTokens, varName) elif operation == 'factorial': tokens, _, _, equationTokens, comments = factorial(tokens) elif operation == 'combination': n = tokenizer(inputEquation) r = tokenizer(varName) tokens, _, _, equationTokens, comments = combination(n, r) elif operation == 'permutation': n = tokenizer(inputEquation) r = tokenizer(varName) tokens, _, _, equationTokens, comments = permutation(n, r) elif operation == 'integrate': lhs, rhs = getLHSandRHS(tokens) lTokens, _, _, equationTokens, comments = integrate( lTokens, varName) elif operation == 'differentiate': lhs, rhs = getLHSandRHS(tokens) lTokens, _, _, equationTokens, comments = differentiate( lTokens, varName) if operation != 'plot': # FIXME: when either plotting window or GUI window is opened from CLI and after it is closed entire CLI exits, it would be better if it is avoided final_string = resultStringCLI(equationTokens, operation, comments, solutionType, simul) print(final_string) else: """ This part handles the cases when VisMa is dealing with matrices. Boolean flags used in code below: dualOperand -- {True} when the matrix operations require two operands (used in operations like addition, subtraction etc) nonMatrixResult -- {True} when the result after performing operations on the Matrix is not a Matrix (in operations like Determinant, Trace etc.) scalarOperations -- {True} when one of the operand in a scalar (used in operations like Scalar Addition, Scalar Subtraction etc.) """ operation = operation[4:] dualOperand = False nonMatrixResult = False scalarOperations = False if ', ' in inputEquation: dualOperand = True [inputEquation1, inputEquation2] = inputEquation.split(', ') if '[' in inputEquation1: inputEquation1 = inputEquation1[1:][:-1] inputEquation1 = inputEquation1.split('; ') matrixOperand1 = [] for row in inputEquation1: row1 = row.split(' ') for i, _ in enumerate(row1): row1[i] = tokenizer(row1[i]) matrixOperand1.append(row1) Matrix1 = Matrix() Matrix1.value = matrixOperand1 inputEquation2 = inputEquation2[1:][:-1] inputEquation2 = inputEquation2.split('; ') matrixOperand2 = [] for row in inputEquation2: row1 = row.split(' ') for i, _ in enumerate(row1): row1[i] = tokenizer(row1[i]) matrixOperand2.append(row1) Matrix2 = Matrix() Matrix2.value = matrixOperand2 Matrix1_copy = copy.deepcopy(Matrix1) Matrix2_copy = copy.deepcopy(Matrix2) else: scalarOperations = True scalar = inputEquation1 scalarTokens = scalar # scalarTokens = tokenizer(scalar) inputEquation2 = inputEquation2[1:][:-1] inputEquation2 = inputEquation2.split('; ') matrixOperand2 = [] for row in inputEquation2: row1 = row.split(' ') for i, _ in enumerate(row1): row1[i] = tokenizer(row1[i]) matrixOperand2.append(row1) Matrix2 = Matrix() Matrix2.value = matrixOperand2 scalarTokens_copy = copy.deepcopy(scalarTokens) Matrix2_copy = copy.deepcopy(Matrix2) else: inputEquation = inputEquation[1:][:-1] inputEquation = inputEquation.split('; ') matrixOperand = [] for row in inputEquation: row1 = row.split(' ') for i, _ in enumerate(row1): row1[i] = tokenizer(row1[i]) matrixOperand.append(row1) Matrix0 = Matrix() Matrix0.value = matrixOperand Matrix0_copy = copy.deepcopy(Matrix0) if operation == 'simplify': MatrixResult = simplifyMatrix(Matrix0) elif operation == 'add': MatrixResult = addMatrix(Matrix1, Matrix2) elif operation == 'sub': MatrixResult = subMatrix(Matrix1, Matrix2) elif operation == 'mult': MatrixResult = multiplyMatrix(Matrix1, Matrix2) elif operation == 'determinant': nonMatrixResult = True sqMatrix = SquareMat() sqMatrix.value = Matrix0.value result = sqMatrix.determinant() elif operation == 'trace': nonMatrixResult = True sqMatrix = SquareMat() sqMatrix.value = Matrix0.value result = sqMatrix.traceMat() elif operation == 'inverse': sqMatrix = SquareMat() sqMatrix.value = Matrix0.value MatrixResult = SquareMat() MatrixResult = sqMatrix.inverse() finalCLIstring = '' if dualOperand: if not scalarOperations: finalCLIstring = resultMatrixString(operation=operation, operand1=Matrix1_copy, operand2=Matrix2_copy, result=MatrixResult) else: finalCLIstring = resultMatrixString(operation=operation, operand1=scalarTokens_copy, operand2=Matrix2_copy, result=MatrixResult) else: if nonMatrixResult: finalCLIstring = resultMatrixString(operation=operation, operand1=Matrix0_copy, nonMatrixResult=True, result=result) else: finalCLIstring = resultMatrixString(operation=operation, operand1=Matrix0_copy, result=MatrixResult) print(finalCLIstring)