def execute(self, context): # x=Asin(at+delta ),y=Bsin(bt) if self.waveA == 'sine': xstring = ssine(self.amplitude_A, self.period_A, phase_shift=self.shift) elif self.waveA == 'triangle': xstring = str(triangle(100, self.period_A, self.amplitude_A)) if self.waveB == 'sine': ystring = ssine(self.amplitude_B, self.period_B) elif self.waveB == 'triangle': ystring = str(triangle(100, self.period_B, self.amplitude_B)) print("x= " + str(xstring)) print("y= " + str(ystring)) x = Expression(xstring, ["t"]) # make equation from string y = Expression(ystring, ["t"]) # make equation from string # build function to be passed to create parametric curve () def f(t, offset: float = 0.0): c = (x(t), y(t), 0) return c parametric.create_parametric_curve(f, offset=0.0, min=self.mint, max=self.maxt, use_cubic=True, iterations=self.iteration) return {'FINISHED'}
def execute(self, context): #x=Asin(at+delta ),y=Bsin(bt) xstring = str(round(self.amplitude_A, 6)) + "*sin((2*pi/" + str( round(self.period_A, 6)) + ")*(t+" + str(round(self.shift, 6)) + "))" ystring = str(round(self.amplitude_B, 6)) + "*sin((2*pi/" + str( round(self.period_B, 6)) + ")*(t))" print("x= " + str(xstring)) print("y= " + str(ystring)) x = Expression(xstring, ["t"]) #make equation from string y = Expression(ystring, ["t"]) #make equation from string #build function to be passed to create parametric curve () def f(t, offset: float = 0.0): c = (x(t), y(t), 0) return c parametric.create_parametric_curve(f, offset=0.0, min=self.mint, max=self.maxt, use_cubic=True, iterations=self.iteration) return {'FINISHED'}
def leftandrighthandconstraints(self): eqcons = [] desstateandcontrol = [] descon = self.viabilityproblem.constraints() j = 0 for thing in self.viabilityproblem.stateconstraintparameterabbreviation( ): for i in range(len(descon)): descon[i] = descon[i].replace( thing, self.stateconstraintparametervalues.split(",")[j]) j = j + 1 params = self.viabilityproblem.stateabbreviation() for i in range(len(descon)): desconsplitted = descon[i].split("<=") if (len(desconsplitted) == 2): eqcons.append([ Expression(desconsplitted[0], params), Expression(desconsplitted[1], params) ]) else: desconsplitted = descon[i].split(">=") if (len(desconsplitted) == 2): eqcons.append([ Expression(desconsplitted[1], params), Expression(desconsplitted[0], params) ]) return eqcons
def read_range(): a_raw, b_raw = limits[0].text(), limits[1].text() try: a_eval = Expression(a_raw)() b_eval = Expression(b_raw)() return a_eval, b_eval except: return 2 * (None, )
def testCall(self): for n in xrange(-784323,294924,6831): if n < 0: hexstr = hex(n)[3:] prefix = "-0x" else: hexstr = hex(n)[2:] prefix = "0x" self.assertEqual(Expression(prefix + hexstr)(),n) self.assertEqual(Expression(prefix + hexstr.upper())(),n)
def execute(self, context): r = round(self.r, 6) R = round(self.R, 6) d = round(self.d, 6) Rmr = round(R - r, 6) # R-r Rpr = round(R + r, 6) # R +r Rpror = round(Rpr / r, 6) # (R+r)/r Rmror = round(Rmr / r, 6) # (R-r)/r maxangle = 2 * math.pi * ( (np.lcm(round(self.R * 1000), round(self.r * 1000)) / (R * 1000))) if self.typecurve == "hypo": xstring = str(Rmr) + "*cos(t)+" + str(d) + "*cos(" + str( Rmror) + "*t)" ystring = str(Rmr) + "*sin(t)-" + str(d) + "*sin(" + str( Rmror) + "*t)" else: xstring = str(Rpr) + "*cos(t)-" + str(d) + "*cos(" + str( Rpror) + "*t)" ystring = str(Rpr) + "*sin(t)-" + str(d) + "*sin(" + str( Rpror) + "*t)" zstring = '(' + str(round( self.dip, 6)) + '*(sqrt(((' + xstring + ')**2)+((' + ystring + ')**2))))' print("x= " + str(xstring)) print("y= " + str(ystring)) print("z= " + str(zstring)) print("maxangle " + str(maxangle)) x = Expression(xstring, ["t"]) # make equation from string y = Expression(ystring, ["t"]) # make equation from string z = Expression(zstring, ["t"]) # make equation from string # build function to be passed to create parametric curve () def f(t, offset: float = 0.0): c = (x(t), y(t), z(t)) return c iter = int(maxangle * 10) if iter > 10000: # do not calculate more than 10000 points print("limiting calculatons to 10000 points") iter = 10000 parametric.create_parametric_curve(f, offset=0.0, min=0, max=maxangle, use_cubic=True, iterations=iter) return {'FINISHED'}
def get_senes_scale(): results = {} senes = parse_senes() for res, val in senes.items(): if res in ['W', 'Y']: results[res] = Expression("%f*%f^(-((abs(z)-%f)^2)/(2*(%f^2)))" % (val['e0'], e_, val['zmid'], val['n']), argorder=['z']) else: results[res] = Expression("%f/(1+((abs(z)/%f)^%f))" % (val['e0'], val['zmid'], val['n']), argorder=['z']) results['C'] = Expression('0*z', argorder=['z']) return results
def evaluateHelper(self, addr, iter): with self.mutex: if addr not in self.cells: return 0 cell = self.cells[addr] if cell.getType() == 'formula' and iter >= 0: new_formula = cell.getFormula() if 'AVERAGE' in new_formula: new_formula = self.avg_function(cell, iter - 1) if 'SUM' in new_formula: new_formula = self.sum_function(cell, iter - 1) if 'COUNTIF' in new_formula: new_formula = self.count_if(cell, iter - 1) cell.setCellValue(new_formula) if is_number(cell.getValue()): return float(cell.getValue()) else: return str(cell.getValue()) if 'IF' in new_formula: new_formula = self.if_function(cell, iter - 1) cell.setCellValue(new_formula) if is_number(cell.getValue()): return float(cell.getValue()) else: return str(cell.getValue()) expCells = parseFormula(new_formula) # [A1,B2] a1:b2 x expCellsForFormula = expCells[:] # duplicate if len(expCells) != 0: formulFunction = Expression(new_formula, expCellsForFormula) else: formulFunction = Expression(new_formula) evaluatedCells = [] for i in range(0, len(expCells)): evaluatedCells += [ self.evaluateHelper(expCells[i], iter - 1) ] cell.setCellValue(formulFunction(*evaluatedCells)) if is_number(cell.getValue()): return float(cell.getValue()) else: return str(cell.getValue()) elif iter < 0: return 0 else: if is_number(cell.getValue()): return float(cell.getValue()) else: return str(cell.getValue())
def risolvi_espressione(self): try: espressione = Expression(self.text()) self.setText(str(espressione())) except: print("errore nella risoluzione della espressione. Assicurarsi che sia scritta in modo corretto senza caratteri estranei.") self.setText("")
def get_elazar_scale(): resutls = {} for res, val in MakeHydrophobicityGrade().items(): resutls[res] = Expression("%f*z^4+%f*z^3+%f*z^2+%f*z+%f" % (val[0], val[1], val[2], val[3], val[4]), argorder=['z']) return resutls
def execute(self, context): #z=Asin(B(x+C))+D zstring = str(round(self.offset, 6)) + "+" + str( round(self.amplitude, 6)) + "*sin((2*pi/" + str( round(self.period, 6)) + ")*(t+" + str(round(self.shift, 6)) + "))" print(zstring) e = Expression(zstring, ["t"]) #make equation from string #build function to be passed to create parametric curve () def f(t, offset: float = 0.0): if self.axis == "XY": c = (e(t), t, 0) elif self.axis == "YX": c = (t, e(t), 0) elif self.axis == "ZX": c = (t, 0, e(t)) elif self.axis == "ZY": c = (0, t, e(t)) return c parametric.create_parametric_curve(f, offset=0.0, min=self.mint, max=self.maxt, use_cubic=True, iterations=self.iteration) return {'FINISHED'}
def read_expression(): expr_raw = text.text() try: expr_eval = Expression(expr_raw, ['x']) return expr_eval except: return None
def reactionCustom(self, reactionInfo, metaboliteConcentrationsDict, enzymeConcentrationsDict): enzymeConcArray = [ enzymeConcentrationsDict[reactionInfo["enzymeIDs"][0]] ].asNumber(COUNTS_UNITS / VOLUME_UNITS) customParameters = reactionInfo["customParameters"] customParameterVariables = reactionInfo["customParameterVariables"] customParameterConstants = reactionInfo[ "customParameterConstantValues"] equationString = reactionInfo["customRateEquation"] parameterDefinitionArray = reactionInfo["customParameters"] parametersArray = customParameterConstants for customParameter in customParameters[len(customParameterConstants ):]: variable = customParameterVariables[customParameter] if variable in enzymeConcentrationsDict: parametersArray.append( enzymeConcentrationsDict[variable].asNumber(COUNTS_UNITS / VOLUME_UNITS)) elif variable in metaboliteConcentrationsDict: parametersArray.append( metaboliteConcentrationsDict[variable].asNumber( COUNTS_UNITS / VOLUME_UNITS)) assert (len(parametersArray) == len(parameterDefinitionArray)) customRateLaw = Expression(equationString, parameterDefinitionArray) return (COUNTS_UNITS / TIME_UNITS / VOLUME_UNITS) * customRateLaw(*parametersArray)
def milne(func, fix, X, Y, des, nom, stop, exact): expr = Expression(func, ["y", "x"]) F = [0.0, 0.0, 0.0, 0.0, 0.0] YC=[0.0] h = X[1] - X[0] for i in range(4): F[i] = round(expr(float(Y[i]), float(X[i])), fix) yp = round(Y[0] + ((4 * h / 3) * (2 * F[3] - F[2] + 2 * F[1])), fix) yc = yp YC[0] = yc for i in range(nom): bef = yc yc = round(Y[2] + ((h / 3) * (F[2] + 4 * F[3] + 2 * expr(float(yc), float(des)))), fix) sc = yc - bef YC.append(yc) if sc > (0.5 * (10 ** (2 - stop))) : break relative_error = float((exact - yc) * 100 / exact) relative_error=abs(relative_error) return yp, YC, relative_error
def math(self, equation): result = Expression(equation[0]) try: result() return result() except Exception as e: return "Invalid Expression"
def sne_fd_1(fstr, x0, tol, graf): """Evalua una funcion dependiente de X para asi encontrar una aproximacion de una de sus raices. Recuperado de "Steffensen type methods for solving nonlinear equations" ecuacion 4 Autores "Alicia Cordero, José L. Hueso, Eulalia Martínez, Juan R. Torregrosa" Retorna una lista donde sus elementos son el x aproximado y la cantidad de iteraciones necesarias para cumplir con la tolerancia dada parametros: fstr: funcion dependdiente de x a la cual se le quiere encontrar sus ceros x0: valor inicial para empezar a calcular las iteraciones tol: tolerancia aceptable para finalizar el metodo graf: parametro para indicar si se quiere generar la grafica ejemplo: sne_fd_1('sin(x)**2-x**2+1', 5, 0.00000000001, 1) """ try: f = Expression(fstr, ["x"]) except ValueError: return 'Syntaxis de la funcion incorrecta' yn = x0 - ((2 * f(x0)**2) / ((f(x0 + f(x0))) - (f(x0 - f(x0))))) xn = x0 - ((2 * f(x0)**2) / ((f(x0 + f(x0))) - (f(x0 - f(x0))))) * ((f(yn) - f(x0)) / (2 * f(yn) - f(x0))) itera = 0 xAx = [] yAx = [] while (abs(f(xn)) >= tol): xAx += [itera] yAx += [abs(f(xn))] try: denominador1 = 1 / (f(xn + f(xn)) - f(xn - f(xn))) denominador1 = denominador1**(-1) except ValueError: break yn = xn - ((2 * f(xn)**2) / denominador1) try: denominador2 = 1 / (2 * f(yn) - f(xn)) denominador2 = denominador2**(-1) except ValueError: break xn = xn - ((2 * f(xn)**2) / denominador1) * ( (f(yn) - f(xn)) / denominador2) itera += 1 if (graf): print(xAx) print(yAx) plt.plot(xAx, yAx) plt.title('Comportamiento del metodo de ODF para ' + fstr) plt.xlabel('iteraciones') plt.ylabel('|f(Xaprox)|') plt.grid(True) plt.show() return [xn, itera] else: return [xn, itera]
def body(exp, x0, e, N): global con con = exp count = 0 for element in con: check = con[count - 1] if element == 'x' and count > 0 and check.isdigit(): con = re.sub(r"\b{}\b".format(check + element), check + '*' + element, con) count += 1 E = math.exp(1) for element in con: if element == 'E': con = re.sub(r"\b{}\b".format(element), str(E), con) count = 0 for element in con: check = con[count - 1] if element == 'x' and count > 0 and check == ')': con = re.sub(r"\b{}\b".format(re.escape(check + element)), check + '*' + element, con) count += 1 print(con) global f f = Expression(con, ["x"]) CallNewtonRaphson(x0, e, N)
def milne(func, fix, X, Y, des, nom, stop): expr = Expression(func, ["y", "x"]) f = [0.0, 0.0, 0.0, 0.0, 0.0] yc = [0.0] # virtual array to put numbers of Yc in it h = X[1] - X[0] # calculating thee step size for i in range(4): f[i] = round(expr(float(Y[i]), float(X[i])), fix) # filling the F array yp = round(Y[0] + ((4 * h / 3) * (2 * f[3] - f[2] + 2 * f[1])), fix) # Yp yC = yp # initial value of yc which is = Yp yc[0] = yC yclist = ["Yc(initial) = " + str(yp)] # this is Y corrected string # it is viewed as "at i = none, Yc(initial) = ..., at i = 0, Yc(0) = ..., etc,) # it is returned as the list of iterations for i in range(nom): yC = round( Y[2] + ((h / 3) * (f[2] + 4 * f[3] + 2 * expr(float(yC), float(des)))), fix) yc.append(yC) RE = abs(float(((yc[i] - yC) / yC) * 100)) yclist.append("at i = " + str(i) + ", Yc(" + str(i) + ") = " + str(yC) + " " + "Relative error = " + str(RE) + " %") if (RE <= stop): break return RE, yc[-1], yclist
def execute(self, context): # z=Asin(B(x+C))+D if self.wave == 'sine': zstring = ssine(self.amplitude, self.period, dc_offset=self.offset, phase_shift=self.shift) if self.beatperiod != 0: zstring += "+" + ssine(self.amplitude, self.period + self.beatperiod, dc_offset=self.offset, phase_shift=self.shift) elif self.wave == 'triangle': #build triangle wave from fourier series zstring = str(round(self.offset, 6)) + "+(" + str( triangle(80, self.period, self.amplitude)) + ")" if self.beatperiod != 0: zstring += '+' + str( triangle(80, self.period + self.beatperiod, self.amplitude)) elif self.wave == 'cycloid': zstring = "abs(" + ssine(self.amplitude, self.period, dc_offset=self.offset, phase_shift=self.shift) + ")" elif self.wave == 'invcycloid': zstring = "-1*abs(" + ssine(self.amplitude, self.period, dc_offset=self.offset, phase_shift=self.shift) + ")" print(zstring) e = Expression(zstring, ["t"]) # make equation from string # build function to be passed to create parametric curve () def f(t, offset: float = 0.0, angle_offset: float = 0.0): if self.axis == "XY": c = (e(t + angle_offset) + offset, t, 0) elif self.axis == "YX": c = (t, e(t + angle_offset) + offset, 0) elif self.axis == "ZX": c = (t, offset, e(t + angle_offset)) elif self.axis == "ZY": c = (offset, t, e(t + angle_offset)) return c for i in range(self.wave_amount): angle_off = self.wave_angle_offset * self.period * i / (2 * math.pi) parametric.create_parametric_curve(f, offset=self.wave_distance * i, min=self.mint, max=self.maxt, use_cubic=True, iterations=self.iteration, angle_offset=angle_off) return {'FINISHED'}
def __init__(self, expr, lower, upper): #Herunder bliver objektet lavet i init funktionen til differentialregning self.fn = Expression(expr, "x") self.lowerBound = lower self.upperBound = upper # Disse nedenstående værdier bruger vi til at plotte med rigtig mellemrum, da disse værdier ikke bliver ændret. self.lowerBoundKOPI = lower self.upperBoundKOPI = upper
def eval_expression(expression, x=''): """Evaluates provided expressions""" print(expression) print(x) fn = Expression(expression) if x != '': print(fn(x)) else: print(fn)
def single_integration(a, b, n, roun): exp = input('Enter the expression in term of x: ') f1 = Expression(exp, ["x"]) h = (a - b) / n value = h * (f1(a) + f1(b)) / 2 for i in range(1, n): value += h * f1(b + i * h) value = round(value, roun) print('The integration is %f' % value)
def testCall(self): for n in xrange(-784323,294924,6831): if n < 0: binstr = bin(n)[3:] prefix = "-0b" else: binstr = bin(n)[2:] prefix = "0b" self.assertEqual(Expression(prefix + binstr)(),n)
def _build_equation_expression(cfg_expression, eq_stat_names): params_list = [] for eindex in range(0, len(eq_stat_names)): eq_stat_name = eq_stat_names[eindex] param_name = "param" + str(eindex) cfg_expression = cfg_expression.replace(eq_stat_name, param_name, 1) params_list.append(param_name) return Expression(cfg_expression, params_list)
def _build_expression(key, default_value, errors, **kwargs): _expression = lambda x, y: 100 _equation = parse_option(key, str, default_value, errors, **kwargs) try: _expression = Expression(_equation) _expression(surprise=0, loss=0) except (TypeError, IndexError, ZeroDivisionError) as te: errors.append(PropertyError(key, str(te))) return _expression
def set(self, func_str, l_bound, r_bound, step_num, epsilon): self.func_str = func_str self.args = [] self.l_bound = l_bound self.r_bound = r_bound self.step_num = step_num self.epsilon = epsilon self.func = Expression(func_str, self.args) random.seed(73)
def enter_funtion(): global function clear() print(f'current function: {function}') backup = function function = Expression(input('Enter new expression in terms of x: '), ['x']) try: assert str(function) except AssertionError: function = backup
def read_range(*prompts): ''' Read the range for the independent variable (x) ''' range_final = [] for prompt in prompts: # Parse and save input range_eval = read_input(' ' + prompt, lambda t: Expression(t)()) range_final.append(range_eval) return range_final
def run(): fields_not_empty = function.get() and epsilon.get() and method.get() and upper_limit.get() and lower_limit.get() and iterations.get() print(function.get()) fun = Expression(function.get(),["x"]) if method.get() == "bisection" and fields_not_empty: draw_bisection(fun,int(lower_limit.get()), int(upper_limit.get()), float(epsilon.get()), int(iterations.get())) elif method.get() =="dichotomy" and fields_not_empty: draw_dichotomy(fun, int(lower_limit.get()), int(upper_limit.get()), float(epsilon.get()), int(iterations.get())) else: messagebox.showerror("Error!", "Failure! At Least one of the entries is empty!")
async def calc(self, ctx, eq): """ Call this command followed by the equation with no spaces """ try: xn = Expression(eq) await ctx.send(eq) await ctx.send('= ' + str(xn())) except Exception as e: # print(e) await ctx.send("Invalid Computation")