def run(str_test): """" for bonus degree 3 print("------- voir si le degre de l'eqaution < 3 si oui resoudre l'equation si non exit---------------") """ temp = Equation(0, 0) expression = temp.prepare_expression(str_test) if (len(expression[0]) and len(expression[1])): expression_minim_tab = temp.minimize_expression(expression) min_equation = temp.get_min_expression(expression_minim_tab) power_max = temp.get_max_power_equation(expression_minim_tab) print("Reduced form : {0}".format(min_equation)) print("Polynomial degree : {0}".format(power_max)) if (power_max > 2): print( "The Polynomial degree is stricly greater than 2, I can't solve" ) exit(0) elif power_max == 2: temp.solve_second(expression_minim_tab) elif power_max == 1: temp.solve_first(expression_minim_tab) elif power_max == 0: if expression_minim_tab: print("There's no solution !!") else: print("All the X ∈ ℝ are the sollution !!") else: print( "Wrong format: Usage Python3 '[aX2 + bX + c = 0]' / a,b,c are double " )
def plusAndMinus(self, equation): resultPlusAndMinus = [] difficultyPlusAndMinus = 0 if equation.plusIndexList != []: # 找到所有可以进行Plus操作的Char的Index for index in equation.plusIndexList: for plusChar in plusTable[equation.str[index]]: # 对每个可以进行Plus操作的Char,用其所有可以变成的Char进行替换,生成新的Equation newPlusEquation = Equation( self.replace_char(equation.str, plusChar, index)) if newPlusEquation.minusIndexList != []: # 在新的等式中,找到所有可以进行Minus操作的Char的Index for newIndex in newPlusEquation.minusIndexList: # 为减少重复,要求这里的Index与之前不同 if newIndex != index: # 对每个可以进行Minus操作的Char,用其所有可以变成的Char进行替换,生成新的Equation for minusChar in minusTable[ newPlusEquation.str[newIndex]]: newEquation = Equation( self.replace_char( newPlusEquation.str, minusChar, newIndex)) if DEBUG_MODE: print("plusAndMinus: ", newEquation.str, end="") if newEquation.checkRight(): print(" Save!") else: print(" Drop") # 如果正确,加入结果List if newEquation.checkRight(): resultPlusAndMinus.append(newEquation) difficultyPlusAndMinus += 1 return difficultyPlusAndMinus, resultPlusAndMinus
def metaAndMeta(self, equation): resultMetaAndMeta = [] difficultyMetaAndMeta = 0 if equation.metaIndexList != []: for index in equation.metaIndexList: for metaChar in metaTable[equation.str[index]]: newMetaEquation = Equation( self.replace_char(equation.str, metaChar, index)) if newMetaEquation.metaIndexList != []: for newMetaIndex in newMetaEquation.metaIndexList: if newMetaIndex != index: for newMetaChar in metaTable[ newMetaEquation.str[newMetaIndex]]: newEquation = Equation( self.replace_char( newMetaEquation.str, newMetaChar, newMetaIndex)) if DEBUG_MODE: print("metaAndMeta: ", newEquation.str, end="") if newEquation.checkRight(): print(" Save!") else: print(" Drop") if newEquation.checkRight(): resultMetaAndMeta.append(newEquation) difficultyMetaAndMeta += 1 return difficultyMetaAndMeta, resultMetaAndMeta
def plusTwoAndMinusTwo(self, equation): resultPlusTwoAndMinusTwo = [] difficultyPlusTwoAndMinusTwo = 0 if equation.plusTwoIndexList != []: for index in equation.plusTwoIndexList: for plusTwoChar in plusTwoTable[equation.str[index]]: newPlusTwoEquation = Equation( self.replace_char(equation.str, plusTwoChar, index)) if newPlusTwoEquation.minusTwoIndexList != []: for newIndex in newPlusTwoEquation.minusTwoIndexList: if newIndex != index: for minusTwoChar in minusTwoTable[ newPlusTwoEquation.str[newIndex]]: newEquation = Equation( self.replace_char( newPlusTwoEquation.str, minusTwoChar, newIndex)) if DEBUG_MODE: print("plusTwoAndMinusTwo: ", newEquation.str, end="") if newEquation.checkRight(): print(" Save!") else: print(" Drop") if newEquation.checkRight(): resultPlusTwoAndMinusTwo.append( newEquation) difficultyPlusTwoAndMinusTwo += 1 return difficultyPlusTwoAndMinusTwo, resultPlusTwoAndMinusTwo
def subFunc(El,p): # print 'Now '+str(p) for i in range(len(El)-1): e1 = Equation.equate(El[p[i]],El[p[i+1]]) Equation.simplify(e1) print 'Elinated and Simplified: '+e1.show() print 'Before :- \n '+' '.join([t.show()+'\n' for t in El])
def metaMinusAndPlus(self, equation): resultMetaMinusAndPlus = [] difficultyMetaMinusAndPlus = 0 if equation.metaMinusIndexList != []: for index in equation.metaMinusIndexList: for metaMinusChar in metaMinusTable[equation.str[index]]: newMetaMinusEquation = Equation( self.replace_char(equation.str, metaMinusChar, index)) if newMetaMinusEquation.plusIndexList != []: for newIndex in newMetaMinusEquation.plusIndexList: if newIndex != index: for plusChar in plusTable[ newMetaMinusEquation.str[newIndex]]: newEquation = Equation( self.replace_char( newMetaMinusEquation.str, plusChar, newIndex)) if DEBUG_MODE: print("metaMinusAndPlus: ", newEquation.str, end="") if newEquation.checkRight(): print(" Save!") else: print(" Drop") if newEquation.checkRight(): resultMetaMinusAndPlus.append( newEquation) difficultyMetaMinusAndPlus += 1 return difficultyMetaMinusAndPlus, resultMetaMinusAndPlus
def solve(e): if len(e.lN)>1 or len(e.rN)>1: print 'Can not Solve!' return 2 # Cannpt solve. if len(e.lN[0].mono) >1 or len(e.rN[0].mono)>1: print 'Contains variables!' return 2 #print str(e.lN[0].cof)+ ' ' +str(e.lN[0].mono) + ' '+ e.comp if e.lN[0].mono == [0]: if e.lN[0].cof<0: Equation.scalarmult(-1,e.rN) e.switch() if e.comp =='<=': if e.rN[0].cof == 0: return False return 0 <= e.rN[0].cof if e.comp =='>=': return 0 >= e.rN[0].cof if e.comp =='=': if e.rN[0].cof == 0: return False return 0 == e.rN[0].cof else: if e.comp =='<=': return e.lN[0].cof <= e.rN[0].cof if e.comp =='>=': return e.lN[0].cof >= e.rN[0].cof if e.comp =='=': return e.lN[0].cof == e.rN[0].cof
def space2OneAndMinusTwo(self, equation): resultSpace2OneAndMinusTwo = [] difficultySpace2OneAndMinusTwo = 0 if equation.space2OneIndexList != []: for index in equation.space2OneIndexList: newSpace2OneEquation = Equation( self.insert_char(equation.str, "1", index)) if newSpace2OneEquation.minusTwoIndexList != []: for newIndex in newSpace2OneEquation.minusTwoIndexList: if newIndex != index: for minusTwoChar in minusTwoTable[ newSpace2OneEquation.str[newIndex]]: newEquation = Equation( self.replace_char(newSpace2OneEquation.str, minusTwoChar, newIndex)) if DEBUG_MODE: print("space2OneAndMinusTwo: ", newEquation.str, end="") if newEquation.checkRight(): print(" Save!") else: print(" Drop") if newEquation.checkRight(): resultSpace2OneAndMinusTwo.append( newEquation) difficultySpace2OneAndMinusTwo += 1 return difficultySpace2OneAndMinusTwo, resultSpace2OneAndMinusTwo
def eli_permutation(E,L): if L ==[]: return elemination.solveE(E) else: #E = copy.deepcopy(E1) x=L[0] L=L[1:] if elemination.validEq(x,E)!=1: print 'Incorrect order of elimination!' return True #print 'Trying to eliminate Variable x'+str(x)+' from the Equation system :::::::' E0=[] E1=[] E2=[] i=0 while i < len(E): e=E[i] if elemination.validVar(x,e) ==1: e1= Equation.seperate(e,x) if e1.comp == '>=': E0.append(e1) E.remove(e) else: if e1.comp == '=': E1.append(e1) E.remove(e) else: if e1.comp == '<=': E2.append(e1) E.remove(e) else: i=i+1 else: i=i+1 #print 'Before Call E0 :- \n '+' '.join([t.show()+'\n' for t in E0]) #print 'Before Call E1 :- \n '+' '.join([t.show()+'\n' for t in E1]) #print 'Before Call E2:-\n '+' '.join([t.show()+'\n' for t in E2]) # The Permutation for p1 in Equation.permutations(range(len(E0))): for p2 in Equation.permutations(range(len(E2))): P=[p1,p2] En = elemination.subFunc2(E0,E1,E2,P) Ec = copy.deepcopy(E) L1 = copy.deepcopy(L) Ec.extend(En) #print 'Permutation '+ str(P) #print 'Ec\n'+''.join([t.show()+'\n' for t in Ec]) #print 'E\n'+''.join([t.show()+'\n' for t in E]) ans = eli_permutation(Ec,L1) #print 'After Call E0 :- \n '+' '.join([t.show()+'\n' for t in E0]) #print 'After Call E1 :- \n '+' '.join([t.show()+'\n' for t in E1]) #print 'After Call E2:-\n '+' '.join([t.show()+'\n' for t in E2]) #print 'ANSWER TO THE Next BRANCH '+str(ans) if ans != False: print 'Before\n'+''.join([t.show()+'\n' for t in Ec]) return True return False
def checkFunction_math(self, raw): """ Returns whether a string contains a valid mathematical expression :param raw: string which contains mathematical expression :return: boolean """ try: f = eq.Expression(raw, ['x', 'A', 'B']) # TODO: need a better method for checking if functions are valid than a simple point evaluation # although this works in most cases most of the time it seems. f(x=0, A=0, B=0) # Value and Type errors are thrown when the string can't be converted to a function via Equation library except TypeError: logging.error( "Attempted to parse text that is not a function, or with improperly labelled parameters" ) return False # TODO: It would be nice to automatically detect any parameters, regardless of if they are labelled A or B, and # Zero division errors are still functions, i.e. 1/x except ZeroDivisionError: logging.warning( "Function defined which is unbounded at the origin") return True else: return True
def eliminateS(x,E): if validEq(x,E)!=1: return else: E1=[] i=0 while i<len(E): if validVar(x,E[i])==1: E1.append(Equation.seperate(E[i],x)) E.remove(E[i]) else: i=i+1 for i in range(0,len(E1)-1,1): e = Equation.equate(E1[i],E1[i+1]) Equation.simplify(e) E.append(e) return
def metaTwo(self, equation): resultMetaTwo = [] difficultyMetaTwo = 0 if equation.metaTwoIndexList != []: for index in equation.metaTwoIndexList: for metaTwoChar in metaTwoTable[equation.str[index]]: newEquation = Equation( self.replace_char(equation.str, metaTwoChar, index)) if DEBUG_MODE: print("metaTwo: ", newEquation.str, end="") if newEquation.checkRight(): print(" Save!") else: print(" Drop") if newEquation.checkRight(): resultMetaTwo.append(newEquation) difficultyMetaTwo += 1 return difficultyMetaTwo, resultMetaTwo
def fitnessfunction(): s = input("Enter the equation you want to find minimum for:") f = Equation.Expression(s, ["x", "y"]) range = [] s = list(map(int, input("Enter range of values [a,b] for x:").split())) range.append(s) s = list(map(int, input("Enter range of values [a,b] for y:").split())) range.append(s) return [f, range]
def main(): n = input("Enter number of row.") n = int(n) matrix_a = read_matrix(n) print("Enter result vector:") vector_result = read_vector(n) if vector_result == False: print("Number of element should be : ", n) return matrix_x = Equation.solve_equation(matrix_a, vector_result)
def calculateGraphs(self): self.equations = [] for eq in self.logic.getGraphs(): equation = Equation(eq[0], eq[1]) self.equations.append(equation) for i in range(len(self.equations)): self.equations[i].calculate_points(self.window[0], self.window[1], 0.5) self.pointsToPixels()
def evaluate(self, value): # f could be defined as a class attribute but would require storing the Expression object in memory. # by declaring it locally it is thrown away and we only need store the text it is derived from. # This saves memory overhead at the cost of run-time performance in evaluating functions try: f = eq.Expression(self.raw, ["x", "A", "B"]) result = f(x=value, A=self.A, B=self.B) except ValueError: logging.error("Failed to evaluate function call") return None else: return result
def eliminateA(x,E): if validEq(x,E)!=1: return 0 E0=[] E1=[] E2=[] i=0 while i < len(E): e=E[i] if validVar(x,e) ==1: e1= Equation.seperate(e,x) if e1.comp == '>=': E0.append(e1) E.remove(e) else: if e1.comp == '=': E1.append(e1) E.remove(e) else: if e1.comp == '<=': E2.append(e1) E.remove(e) else: i=i+1 else: i=i+1 #print 'Here\n' +' '.join([t.show()+'\n' for t in E]) print 'Before Call E0 :- \n '+' '.join([t.show()+'\n' for t in E0]) print 'Before Call E1 :- \n '+' '.join([t.show()+'\n' for t in E1]) print 'Before Call E2:-\n '+' '.join([t.show()+'\n' for t in E2]) # for p1 in Equation.permutations(range(len(E0))): # for p2 in Equation.permutations(range(len(E2))): # Make the permutation and handle non-determinism L =[range(len(E0)),range(len(E2))] En = subFunc2(E0,E1,E2,L) print 'New equations :- \n '+' '.join([t.show()+'\n' for t in En]) E.extend(En) print 'Modified E :- \n '+' '.join([t.show()+'\n' for t in E]) return 1
def ternary(self, compound, limits): """ generate a search list for the ternary compound """ vars = compound.vars eqs = [ Equation.Expression(ele.comp, compound.vars) for ele in compound.elements ] eles = [ele.name for ele in compound.elements] composition_format = "{:.2f}".join(eles) + "{:.2f}" concentrations = np.stack(list(tri_grid(self.n, *limits)), axis=0) formula = [composition_format.format(*row) for row in concentrations] fake_df = pd.DataFrame({ "formula": formula, "x": concentrations[:, 0], "y": concentrations[:, 1], "z": concentrations[:, 2] }) return self.generate(fake_df)
def get_equation( self, **kwargs ): #retrieves the coefficient and power values from the data (best fit equation) print("yes") for name, value in kwargs.items( ): #sets the corresponding keyword argument (in this case it may be type information or base; this shall later be used to speed up the process) setattr(self, name, value) try: self.base #attempts to see if a base value has been provided except AttributeError: self.base = len( self.x_coords ) - 1 #utilises best fit 'count of coordinates' to increase the accuracy or provide a possible equation which fits all coords print(self.base) self.equation_values = Differentiation.equation_obtain( self.y_coords, self.x_coords, self.category, self.base, 0) #returned values of coefficients and coordinates in tuples print("Equation:", self.equation_values) self.equation = Equation.Equation(self.equation_values) print(self.equation.equation)
def subFunc2(El,Ee,Eg,L): En =[] p=L[0] p2=L[1] if len(El)>1: for i in range(len(El)-1): e1 = Equation.equateR(El[p[i]].rN,El[p[i]].rD,El[p[i+1]].rN,El[p[i+1]].rD,'<=') Equation.simplify(e1) En.append(e1) if Ee != [] and p!=[]: ee = Ee[0] e1 = Equation.equateR(El[p[-1]].rN,El[p[-1]].rD,ee.rN,ee.rD,'<=') Equation.simplify(e1) En.append(e1) if Ee!= []: for i in range(len(Ee)-1): e1 = Equation.equateR(Ee[i].rN,Ee[i].rD,Ee[i+1].rN,Ee[i+1].rD,'=') Equation.simplify(e1) En.append(e1) if Ee == [] and p!=[] and p2!=[]: e1 = Equation.equateR(El[p[-1]].rN,El[p[-1]].rD,Eg[p2[0]].rN,Eg[p2[0]].rD,'<=') Equation.simplify(e1) En.append(e1) if Eg!=[] and Ee !=[]: ee = Ee[-1] e1 = Equation.equateR(ee.rN,ee.rD,Eg[p2[0]].rN,Eg[p2[0]].rD,'<=') Equation.simplify(e1) En.append(e1) if len(Eg)>1: for i in range(len(Eg)-1): e1 = Equation.equateR(Eg[p2[i]].rN,Eg[p2[i]].rD,Eg[p2[i+1]].rN,Eg[p2[i+1]].rD,'<=') Equation.simplify(e1) En.append(e1) return En
import matplotlib.pyplot as plt import numpy as np from scipy.integrate import odeint # This import is needed to modify the way figure behaves from mpl_toolkits.mplot3d import Axes3D Axes3D from sklearn import manifold, datasets from Simulator import Simulator from PoincareMapper import PoincareMapper import Equation import math from SymbolicDynamics import * # Create data eq = Equation.Lorentz() sim = Simulator(eq) data = sim.states(duration=200, split=0.01) # max modified 850 data = data[1000:] data = sim.interpolateCurve()[1000:] # Create modified data r = np.sqrt(np.square(data[:, 0]) + np.square(data[:, 1])) dataMod = np.zeros(np.shape(data)) dataMod[:, 0] = (np.square(data[:, 0]) - np.square(data[:, 1])) / r dataMod[:, 1] = 2 * data[:, 0] * data[:, 1] / r dataMod[:, 2] = data[:, 2] # Plot original # Compute return maps
print 'Before\n'+''.join([t.show()+'\n' for t in E]) L = [6,4,3,2,1] ''' #eliminateA(6,E) ##print 'Finanly\n'+' '.join([t.show()+'\n ' for t in E]) #eliminateA(4,E) #eli_permutation(E,L) #E.append(eq3o) ##print 'Finanly\n'+' '.join([t.show()+'\n ' for t in E]) ##print 'Solving ' + E[6].show()+ ' : ' + str(solve(E[6])) ##print 'SOLVE : '+str(elemination.solveE(E[-1:])) ''' n = Equation.Eq([Equation.Term(1,[1]),o],'<=',[Equation.Term(0.7,[])]) #print n.show() E =[n,eq1l] #print 'Finanly\n'+''.join([t.show()+'\n' for t in E]) m0 = Equation.seperate(n,1) m1 = Equation.seperate(eq1l,1) #print m0.show() #print m1.show() m2 = Equation.equateR(m0.rN,m0.rD,m1.rN,m1.rD,'<=') Equation.simplify(m2)
def _calculate(self, x: str): # re_parser = '([^\(;]*\(.*?\)|[^;]*) ?; ?' # regex_split = ";(?!(?:[^(]*\([^)]*\))*[^()]*\))" x = x.strip() splitexp = "[*+%/^-](?!(?:[^(]*\([^)]*\))*[^()]*\))" x_exprs = re.split(splitexp, x) x_ops = re.findall(splitexp, x) splitops = SpreadSheet._split_ops(x) x_exprs = splitops[0] x_ops = splitops[1] if len(x_exprs) > 1 and not [i in x for i in ["<", "=", ">"]].count(True): for i, e in enumerate(x_exprs): x_exprs[i] = str(self._calculate(e)) i = 1 for op in x_ops: x_exprs.insert(i, op) i = i + 2 x = "".join(x_exprs) if x.startswith("ABS("): x = x[4:-1] x = SpreadSheet._calculate(self, x) assert isinstance(x, (int, float)) return math.fabs(x) elif x.startswith("FLOOR("): x = x[6:-1] x = SpreadSheet._calculate(self, x) assert isinstance(x, (int, float)) return math.floor(x) elif x.startswith("CEILING("): x = x[8:-1] x = SpreadSheet._calculate(self, x) assert isinstance(x, (int, float)) return math.ceil(x) elif x.startswith("SIN("): x = x[4:-1] x = SpreadSheet._calculate(self, x) assert isinstance(x, (int, float)) return math.sin(x) elif x.startswith("COS("): x = x[4:-1] x = SpreadSheet._calculate(self, x) assert isinstance(x, (int, float)) return math.cos(x) elif x.startswith("TAN("): x = x[4:-1] x = SpreadSheet._calculate(self, x) assert isinstance(x, (int, float)) return math.tan(x) elif x.startswith("LOG("): x = x[4:-1] args_ = SpreadSheet._split_semicolon(x) assert 1 <= len(args_) <= 2 x = args_[0] if len(args_) == 2: y = args_[1] else: y = "10" x, y = SpreadSheet._calculate(self, x),\ SpreadSheet._calculate(self, y) assert isinstance(x and y, (int, float)) return math.log(x, y) elif x.startswith("POW("): x = x[4:-1] args_ = SpreadSheet._split_semicolon(x) assert len(args_) == 2 x = args_[0] y = args_[1] x, y = SpreadSheet._calculate(self, x),\ SpreadSheet._calculate(self, y) assert isinstance(x and y, (int, float)) return math.pow(x, y) elif x.startswith("IF("): x = x[3:-1] args_ = SpreadSheet._split_semicolon(x) assert len(args_) == 3 x = args_[0] if x.__contains__('(') and not x.startswith('('): x = SpreadSheet._split_if(x) x1 = x[0] x2 = x[2] x1 = SpreadSheet._calculate(self, x1) x2 = SpreadSheet._calculate(self, x2) x = str(x1) + x[1] + str(x2) y = args_[1] z = args_[2] x = SpreadSheet._calculate(self, x) if x: state = SpreadSheet._calculate(self, y) else: state = SpreadSheet._calculate(self, z) if state == 1: state = "TRUE" elif state == 0: state = "FALSE" return state elif x.startswith("SUM("): x = x[4:-1] args_ = SpreadSheet._split_semicolon(x) sum_ = 0 for arg in args_: arg = SpreadSheet._calculate(self, arg) assert isinstance(arg, (int, float, tuple)) if isinstance(arg, tuple): for i in range(arg[0][0], arg[1][0] + 1): for j in range(arg[0][1], arg[1][1] + 1): y = self._getcellat(i, j).getvalue() assert isinstance(y, (int, float)) sum_ += y else: sum_ += arg return sum_ elif x.startswith("COUNTIF("): x = x[8:-1] args_ = SpreadSheet._split_semicolon(x) assert len(args_) == 2 x = args_[0] y = args_[1] x, y = SpreadSheet._calculate(self, x),\ SpreadSheet._calculate(self, y) assert isinstance(x, tuple) and len(x) == 2 count = 0 for i in range(x[0][0], x[1][0] + 1): for j in range(x[0][1], x[1][1] + 1): if self._getcellat(i, j).getvalue() == y: count += 1 return count elif x.startswith("AVERAGE("): x = x[8:-1] args_ = SpreadSheet._split_semicolon(x) sum_ = 0 count = 0 for arg in args_: arg = SpreadSheet._calculate(self, arg) assert isinstance(arg, (int, float, tuple)) if isinstance(arg, tuple): for i in range(arg[0][0], arg[1][0] + 1): for j in range(arg[0][1], arg[1][1] + 1): y = self._getcellat(i, j).getvalue() assert isinstance(y, (int, float)) sum_ += y count += 1 else: sum_ += arg count += 1 avg = sum_ / max(count, 1) # float("%.3f" % avg) return round(avg, 3) else: try: return float(x) except ValueError: pass if x.startswith(("'", '"')) and x.endswith(("'", '"')): return x[1:-1] elif x.__contains__(":"): return SpreadSheet.parserangeaddr(x) else: if x.startswith("(") and x.endswith(")"): x = x[1:-1] eqstr = x eq = re.sub("[A-Z]+[0-9]+", lambda m: self._convert(m), eqstr) eq = eq.replace("SIN(", "sin(") eq = eq.replace("COS(", "cos(") eq = eq.replace("TAN(", "tan(") eq = eq.replace("ABS(", "abs(") return Equation.Expression(eq)()
import Equation from Simulator import Simulator from DimensionalityFinder import DimensionalityFinder import matplotlib.pyplot as plt import math import numpy as np from scipy.integrate import odeint from scipy.integrate import solve_ivp eq = Equation.Fitz() sim = Simulator(eq) # data = sim.states(duration=100, split = 0.01) # 40 -> 1.369, 400 -> 1.497 state0 = [0.01, 0.01, 0.01, 0.01] t = np.linspace(0, 10000, 50000) # sim = Simulator(eq) # # data = sim.states(duration = 300011, split = 0.25) # data = sim.interpolateCurve()[10000:] # print(data.shape) n = 2 a = [-0.025794, -0.025794] b = [0.0065, 0.0135] c = [0.02, 0.02] k = 0.128 A = [[0, 1], [1, 0]] def f(state, t): x = state[0:n] y = state[n:2 * n] # unpack the state vector
def read(Lines, CheckSemantics, Verbose): if Verbose > -1: print 'Parsing equations..' seen = set([]) eqs = {} Size = len(Lines) # parse equations for i, line in enumerate(Lines): line = line.strip() if not line: continue name, eq = line.split(':') name, value = name.split('=') name = name.strip() value = int(value) eq = eq.strip() if not name in eqs: eqs[name] = {} if value in eqs[name]: print ' **error: two equations for', name, '=', value, ':' print ' ', eq print ' ', eqs[name][value] raise Exception if Verbose > 1: print '\rParsing "%s=%i" ' % (name, value), sys.stdout.flush() eqs[name][value] = Equation.parse(eq) # enforce each variable has an equation for name in eqs: for val in eqs[name]: if val: for v in eqs[name][val].variables(): if not v in eqs: print ' **error: %s is not defined.' % v print ' ', 'Appears in "%s"' % str( eqs[name][val]) raise Exception # enforce one equation for every activity Size = len(eqs) for j, name in enumerate(eqs): # missing equations if len(eqs[name]) != max(eqs[name]) + 1: # exactly 1 equation missing if len(eqs[name]) == max(eqs[name]): k = [ i for i in range(max(eqs[name]) + 1) if not i in eqs[name] ] k = k.pop() conjunction = [ str(e) for e in eqs[name].values() if str(e) != '0' ] # all e satisfy e=0 if not conjunction: eq = '1' # exists e with e=1 elif '1' in conjunction: # must be unique! if not len(conjunction) == 1: print ' **error: the equations of', name, 'are not disjoint :' print ' ', ', '.join(conjunction) raise Exception eq = '0' # exists non-trivial e else: eq = '&'.join(['!(%s)' % c for c in conjunction]) eqs[name][k] = Equation.parse(eq) if Verbose > 1: print '\rParsing "%s=%i" ' % (name, k), sys.stdout.flush() # more than one equation missing else: print ' **error:', name, ' is not well defined:' for val in eqs[name]: print ' ', name, '=', val, ':', eqs[name][val] raise Exception if len(eqs[name]) != max(eqs[name]) + 1: print ' **error:', name, ' is not well defined:' for val in eqs[name]: print ' ', name, '=', val, ':', eqs[name][val] raise Exception # enforce that exactly one equation is true in every state if CheckSemantics: dependencies = set([]) for val in eqs[name]: dependencies.update(eqs[name][val].variables()) dependencies = sorted(list(dependencies)) Max = [] for n in dependencies: Max.append(max(eqs[n])) if Verbose > 1: print '\rChecking %i/%i. "%s" ' % (j + 1, Size, name), sys.stdout.flush() check(name, eqs[name].values(), dependencies, Max) if Verbose > 0: print return eqs
P=[p1,p2] En = el.subFunc2(E0,E1,E2,P) Ec = copy.deepcopy(E) L1 = copy.deepcopy(L) Ec.extend(En) ans = eli_perm_para(Ec,L1) if ans: print 'Before\n'+''.join([t.show()+'\n' for t in Ec]) return True return False o = Equation.Term(1,[0]) l = Equation.Term(1,[]) t = Equation.Term(0.5,[6,Equation.newVar(),Equation.newVar(),Equation.newVar()]) t1 = Equation.Term(0.4,[]) t2 = Equation.Term(0.3,[1,2,3]) nl=Equation.Term(1,[1,2]) n2=Equation.Term(0.8,[1,2,4]) eq1 = Equation.Eq([t,nl],'<=',[Equation.Term(0.7,[])]) # 0.5 x1 x2 x3 x6 + x1 x2 <= 0.7 eq2 = Equation.Eq([nl,t2],'<=',[t1]) # x1 x2 + 0.3 x1 x2 x3 <= 0.4 eq3 = Equation.Eq([n2 , t2],'>=',[o]) # 0.8 x1 x2 x4 + 0.3 x1 x2 x3 > 0 eq4 = Equation.Eq([Equation.Term(1,[3]),Equation.Term(1,[4])],'=',[l]) # x3 + x4 = 1 eq3o = Equation.Eq([Equation.Term(1,[3])],'>=',[o]) # x3 >=0 eq3l = Equation.Eq([Equation.Term(1,[3])],'<=',[l]) # x3 <=1 #eq2o = Equation.Eq([Equation.Term(1,[2])],'>=',[o]) # x2 >=0 eq2o = Equation.Eq([Equation.Term(1,[2])],'>=',[Equation.Term(0.9,[])])
def eli_perm_para(E,L): if L ==[]: return el.solveE(E) else: #E = copy.deepcopy(E1) x=L[0] L=L[1:] if el.validEq(x,E)!=1: print 'Incorrect order of elimination!' return True #print 'Trying to eliminate Variable x'+str(x)+' from the Equation system :::::::' E0=[] E1=[] E2=[] i=0 while i < len(E): e=E[i] if el.validVar(x,e) ==1: e1= Equation.seperate(e,x) if e1.comp == '>=': E0.append(e1) E.remove(e) else: if e1.comp == '=': E1.append(e1) E.remove(e) else: if e1.comp == '<=': E2.append(e1) E.remove(e) else: i=i+1 else: i=i+1 #print 'Before Call E0 :- \n '+' '.join([t.show()+'\n' for t in E0]) #print 'Before Call E1 :- \n '+' '.join([t.show()+'\n' for t in E1]) #print 'Before Call E2:-\n '+' '.join([t.show()+'\n' for t in E2]) # The Permutation if (len(E0) >3 or len(E2)>3) and len(L)>3: K=[] for p1 in Equation.permutations(range(len(E0))): for p2 in Equation.permutations(range(len(E2))): K.append([p1,p2]) pool= mp.Pool() result = [pool.apply(complete_para, arg =(E,L,E0,E1,E2,P)) for P in K] for r in result: if r : return True for p1 in Equation.permutations(range(len(E0))): for p2 in Equation.permutations(range(len(E2))): P=[p1,p2] En = el.subFunc2(E0,E1,E2,P) Ec = copy.deepcopy(E) L1 = copy.deepcopy(L) Ec.extend(En) ans = eli_perm_para(Ec,L1) if ans: print 'Before\n'+''.join([t.show()+'\n' for t in Ec]) return True return False
def read( Lines, CheckSemantics, Verbose ): if Verbose>-1: print 'Parsing equations..' seen = set([]) eqs = {} Size = len(Lines) # parse equations for i, line in enumerate(Lines): line = line.strip() if not line: continue name, eq = line.split(':') name,value = name.split('=') name=name.strip() value=int(value) eq = eq.strip() if not name in eqs: eqs[name] = {} if value in eqs[name]: print ' **error: two equations for',name,'=',value,':' print ' ',eq print ' ',eqs[name][value] raise Exception if Verbose>1: print '\rParsing "%s=%i" '%(name,value), sys.stdout.flush() eqs[name][value] = Equation.parse( eq ) # enforce each variable has an equation for name in eqs: for val in eqs[name]: if val: for v in eqs[name][val].variables(): if not v in eqs: print ' **error: %s is not defined.'%v print ' ','Appears in "%s"'%str(eqs[name][val]) raise Exception # enforce one equation for every activity Size = len(eqs) for j,name in enumerate(eqs): # missing equations if len(eqs[name])!=max(eqs[name])+1: # exactly 1 equation missing if len(eqs[name])==max(eqs[name]): k = [i for i in range(max(eqs[name])+1) if not i in eqs[name]] k = k.pop() conjunction = [str(e) for e in eqs[name].values() if str(e)!='0'] # all e satisfy e=0 if not conjunction: eq = '1' # exists e with e=1 elif '1' in conjunction: # must be unique! if not len(conjunction)==1: print ' **error: the equations of', name, 'are not disjoint :' print ' ',', '.join(conjunction) raise Exception eq = '0' # exists non-trivial e else: eq = '&'.join(['!(%s)'%c for c in conjunction]) eqs[name][k] = Equation.parse( eq ) if Verbose>1: print '\rParsing "%s=%i" '%(name,k), sys.stdout.flush() # more than one equation missing else: print ' **error:',name,' is not well defined:' for val in eqs[name]: print ' ',name,'=',val,':',eqs[name][val] raise Exception if len(eqs[name])!=max(eqs[name])+1: print ' **error:',name,' is not well defined:' for val in eqs[name]: print ' ',name,'=',val,':',eqs[name][val] raise Exception # enforce that exactly one equation is true in every state if CheckSemantics: dependencies = set([]) for val in eqs[name]: dependencies.update( eqs[name][val].variables() ) dependencies = sorted(list(dependencies)) Max = [] for n in dependencies: Max.append( max(eqs[n]) ) if Verbose>1: print '\rChecking %i/%i. "%s" '%(j+1,Size,name), sys.stdout.flush() check( name, eqs[name].values(), dependencies, Max ) if Verbose>0: print return eqs
# based on https://scikit-learn.org/dev/auto_examples/manifold/plot_swissroll.html#sphx-glr-auto-examples-manifold-plot-swissroll-py # This import is needed to modify the way figure behaves from mpl_toolkits.mplot3d import Axes3D Axes3D from sklearn import manifold, datasets from Simulator import Simulator from PoincareMapper import PoincareMapper import Equation import math #---------------------------------------------------------------------- # eq = Equation.Rossler() sim = Simulator(eq) # angles = np.linspace(0,2*np.pi,100) angles = np.linspace(0, 2 * np.pi, 50) # angles = [5.3] newData = True if newData: print("Integrating data") # data = sim.states(duration=500) data = sim.states(duration=2400, split=0.01) # max modified 850 data = data[1000:] data = sim.interpolateCurve()[1000:] print("Computing LLE embedding of data")
# IMPLIED. IN NO EVENT WILL THE AUTHOR BE HELD LIABLE FOR ANY DAMAGES ARISING FROM # THE USE OF THIS SOURCE-CODE. USE AT YOUR OWN RISK. from Equation import * EQUATION_ORDER = [ 'Pixel-Size', 'DISPARITY', 'ERROR DISPARITY', ] EQUATION_DATA = { 'Pixel-Size': { 'DATA': Equation('PixelSize = SensorLength / NumPixel ', [ EquationSymbol(name='PixelSize', min=1, max=20, value=17, unit=u'µm', factor=1e-6, isResult=True), EquationSymbol(name='SensorLength', min=1, max=50, value=17.408, unit='mm', factor=1e-3), EquationSymbol(name='NumPixel', min=600, max=2048, value=1024, unit='px'), ]) }, 'DISPARITY': { 'DATA': Equation('Disparity = (Focal * 1/PixelSize) * Base / Distance', [ EquationSymbol(name='Distance', min=5, max=50, value=6, unit='m'), EquationSymbol(name='Disparity', min=0, max=160, value=64, unit='px', isResult=True), EquationSymbol(name='Base', min=1, max=200, value=40, unit='cm', factor=1e-2), EquationSymbol(name='Focal', min=1, max=30, value=15, unit='mm', factor=1e-3), EquationSymbol(name='PixelSize', min=1, max=20, value=17, unit=u'µm', factor=1e-6, extern='Pixel-Size'), ]) }, 'ERROR DISPARITY': { 'DATA': Equation('DistanceError = (Focal * 1/PixelSize) * Base / Disparity - (Focal * 1/PixelSize) * Base / (Disparity + AccuracyFactor*1./16)', [ EquationSymbol(name='DistanceError', min=0, max=100, value=5, unit='m', factor=1, isResult=True),