def get_init_eql_stock(C11: float, C12: float, p1: float, r11: float, r22: float, K22: float, K11: float, c2: float, b: float) -> Tuple[float]: x = sym.symbols('x', positive=True) y = sym.symbols('y', positive=True) f = sym.Eq(x*(C11/c2) - (p1/c2)*(x**2) + r11*x*(1-(x/K11)) + b*(y/K22) - b*(x/K11)) # - x)?? g = sym.Eq(y*(C12/c2) - (p1/c2)*(y**2) + r22*y*(1-(y/K22)) - b*(y/K22) + b*(x/K11)) # - y)?? eqlNDCStocks = sym.nonlinsolve([f, g], [x, y]) eqlNDCStocks = [x for x in eqlNDCStocks if x[0] > 0 and x[1] > 0] if len(eqlNDCStocks) == 1: X0 = eqlNDCStocks[0] else: sys.exit(('Not exactly one positive, real answer ' 'to equilibrium stock condition equations.')) return X0[0], X0[1]
def fonc_points(self): """ Finds all the points that satisfy the First-Order Necessary Condition assuming that all the points are interior. This means that we need to solve the equation Df(x*)=0 for x* """ return sy.nonlinsolve(self._jacobian, tuple(self._x))
def plug_in(self, symbol_values): """ Given a set of symbol_values, plugs the values into the model and returns a dictionary of outputs representing the result of plugging in the symbol_values. symbol_values must contain a valid set of inputs as indicated in the connections method. Args: symbol_values (dict<str,float>): Mapping from string symbol to float value, giving inputs. Returns: (dict<str,float>) mapping from string symbol to float value giving result of applying the model to the given inputs. """ # Define sympy equations for the model if not self.equations: raise ValueError('Please implement the _evaluate ' 'method for the {} model.'.format(self.name)) eqns = [parse_expr(eq) for eq in self.equations] eqns = [eqn.subs(symbol_values) for eqn in eqns] # Generate outputs from the sympy equations. possible_outputs = set() for eqn in eqns: possible_outputs = possible_outputs.union(eqn.free_symbols) outputs = {} for possible_output in possible_outputs: solutions = sp.nonlinsolve(eqns, possible_output) # taking first solution only, and only asking for one output symbol # so know length of output tuple for solutions will be 1 solution = list(solutions)[0][0] if not isinstance(solution, sp.EmptySet): outputs[str(possible_output)] = sp.N(solution) return outputs
def solve_lagrangian(self): num_constraints = len(self._constraints) # Define a lambda symbol for each constraint lambda_names = tuple([('lambda%s' % i) for i in range(1, num_constraints + 1)]) lambdas = sy.symbols(lambda_names) lambda_vec = sy.Matrix(lambdas) # Define constraints as vector H = sy.Matrix(self._constraints) # Formulate the Lagrangian function l l = self._f - lambda_vec.T * H # Find the gradient of the Lagrangian function # with respect to all parameters all_params = tuple(self._x) + lambdas Dl = l.jacobian(all_params) # Solve it with respect to all the parameters result = sy.nonlinsolve(Dl, all_params) # Remove the lambda value from the results points = [tup[0:-num_constraints] for tup in list(result)] lambdas = [tup[-num_constraints:] for tup in list(result)] return points, lambdas
def solutionC(): X1, X2 = sy.symbols('X1,X2', nonzero=True) f1 = X1 / 10 - X2**3 - X1 * X2**2 - X1**2 * X2 - X2 - X1**3 f2 = X1 + X2 / 10 + X1 * X2**2 + X1**3 - X2**3 - X1**2 * X2 F = sy.Matrix([f1, f2]) J = F.jacobian([X1, X2]) M11, M12, M21, M22 = sy.symbols('M11,M12,M21,M22', positive=True, real=True) M = sy.Matrix([[M11, M12], [M21, M22]]) Mdot = J * M f3 = Mdot[0] f4 = Mdot[1] f5 = Mdot[2] f6 = Mdot[3] print(J) print( sy.nonlinsolve((f1, f2, f3, f4, f5, f6), (X1, X2, M11, M12, M21, M22))) tmp = f5.subs([(X1, 0.1), (X2, -0.1)]) print(tmp) #reduce_rational_inequalities([[ # ((sy.Poly(tmp),0), '<')]],(M11,M21)) solution = sy.solve(tmp < 0, M11) print(solution)
def first_point_model(): x, y = sympy.symbols('x y') #x=d1,y=L n = float(2) p0 = float(-35.0) d0 = float(0.6) s1 = float(0.002014) s2 = float(0.0009455) s3 = float(0.3127) PA = float(-47.8) PB = float(-53) d = float(2) f = [ p0 - 10 * n * sympy.log(x / d0, 10) - s1 * sympy.root( (180 / sympy.pi) * sympy.atan(y / x), 2) - s2 * (180 / sympy.pi) * sympy.atan(y / x) - s3 - 10 * n * sympy.log(sympy.sqrt(sympy.root(x, 2) + sympy.root(y, 2)) / x, 10) - PA, p0 - 10 * n * sympy.log((d - x) / d0, 10) - s1 * sympy.root( (180 / math.pi) * sympy.atan(y / (d - x)), 2) - s2 * (180 / sympy.pi) * sympy.atan(y / (d - x)) - s3 - 10 * n * sympy.log( sympy.sqrt(sympy.root((d - x), 2) + sympy.root(y, 2)) / (d - x), 10) - PB ] p = sympy.expand(f[0]) print(p) q = sympy.expand(f[1]) print(q) result = sympy.nonlinsolve([p, q], [x, y]) # result=fsolve(f,[1,1]) print(result) return result
def Tmat(self, Am): A = sp.Matrix(Am) eis = self.eigs(Am) M, N = A.shape Xi = sp.symarray('x', M) listd = [sp.symbols('x_{}'.format(i)) for i in range(M)] llist = [sp.symbols('x_{}'.format(i)) for i in range(M - 1)] T = [] realss = [] comps = [] imagine = bool(False) count = 0 for i in eis: II = sp.eye(M) Ad = A - i * II AA = sp.matrix2numpy(Ad * sp.Matrix(Xi)) AAf = self.flatten(AA) ss = sp.nonlinsolve(AAf, llist) Xvec = list( ss.args[0].subs({listd[-1]: 1.00}) ) # One is used by default but may be wrong in certain situations for iss in Xvec: indexx = Xvec.index(iss) Xvec[indexx] = sp.simplify(iss) XXvec = [] for ii, jb in enumerate(Xvec): vall = jb Xvec[ii] = vall vali = sp.re(vall) valj = sp.im(vall) realss.append(vali) comps.append(valj) if valj != 0.0: imagine = bool(True) if imagine == True: count += 1 realss.insert(len(realss), 1) comps.insert(len(comps), 0) if count % 2 == 0 and imagine == False: T.append(realss[:]) realss.clear() comps.clear() elif count % 2 != 0 and imagine == True: T.append(realss[:]) realss.clear() comps.clear() elif count % 2 == 0 and imagine == True: T.append(comps[:]) realss.clear() comps.clear() Xvec.clear() XXvec.clear() T_matrix = self.Tt(T) for i in range(len(T_matrix)): for j in range(len(T_matrix[0])): ijval = float("{:.25f}".format(T_matrix[i][j])) T_matrix[i][j] = ijval TI_matrix = self.inv(T_matrix) return T_matrix, TI_matrix
def getRotAng(X, Z): ''' determines most likely rotated ellipse based on cartesian projections. BE CAREFUL THERE ARE 2 VALID SOLNS ''' #Eqn of ellipse = ((x-h)**2)/a**2 + ((y-k)**2)/b**2 = 1 #loop through different angles and find volume of each ellipse # constrained by: center at 0,0 and two points # as func of cross and angle (specified in param sweep) numAngles = 20 #how many angles to sweep through to find best rotation theta = np.linspace(0, np.pi, numAngles) bestArea = 0 bestAng = 0 bestMajor = 0 bestMinor = 0 i = 0 #count var for ang in theta: x, z, a, b = symbols('x z a b', real=True) #eqn of ellipse expr = (x**2 - 0) / (a**2) + (z**2 - 0) / (b**2) - 1 #x and z coords of cross rotated by theta xp = np.array([X * np.cos(theta), X * np.sin(theta)]) #x' zp = np.array([-Z * np.sin(theta), Z * np.cos(theta)]) #z' #plug in values of first point x' expr1 = expr.subs({x: xp[0, i], z: xp[1, i]}) # print(expr1) #plug in values of second point z' expr2 = expr.subs({x: zp[0, i], z: zp[1, i]}) # print(expr2) #solve system of equations #TODO - stop this from returning complex numbers coeff = nonlinsolve([expr1, expr2], [a, b]) # print(coeff) # print(coeff.args[0]) #shows values of a and b for each angle #whatever angle produes ell of largest volume will be the answer (or pi - that since there will always be 2 solutions?) try: #get area of ellipse represented by above equation major = coeff.args[0][0] minor = coeff.args[0][1] area = np.pi * major * minor if area > bestArea: bestArea = area bestAng = ang bestMinor = minor bestMajor = major except: pass i += 1 return (bestAng, bestMajor, bestMinor)
def classic_method(f): df = [diff(f, i) for i in VARS] sol = nonlinsolve(df, VARS) gesian = to_mat([diff(i, j) for j in VARS] for i in df) full_gesian = calc(gesian, list(sol)[0]) minors, pos_def, neg_def = check_posneg_def(full_gesian) return df, sol, gesian, full_gesian, minors, pos_def, neg_def, calc( f, list(sol)[0])
def Tmat(self, Am, eis): A = sp.Matrix(Am) M, N = np.array(Am).shape Xi = sp.symarray('x',M) listd = [sp.symbols('x_{}'.format(i)) for i in range(M)] llist = [sp.symbols('x_{}'.format(i)) for i in range(M-1)] T = [] realss = [] comps = [] imagine = bool(False) count = 0 for i in eis: II = sp.eye(M) Ad = A - i*II AA = sp.matrix2numpy(Ad*sp.Matrix(Xi)) AAf = flatten(AA) ss = sp.nonlinsolve(AAf, *llist) # print(ss) Xvec = list(sp.simplify(ss.args[0].subs({listd[-1] : -1.0}))) for iss in Xvec: indexx = Xvec.index(iss) Xvec[indexx] = sp.simplify(iss) XXvec = [] for ii,jb in enumerate(Xvec): vall = jb*1.0 Xvec[ii] = vall vali = sp.re(vall) valj = sp.im(vall) realss.append(vali) comps.append(valj) if valj != 0.0: imagine = bool(True) if imagine == True: count += 1 realss.insert(len(realss), 1) comps.insert(len(comps), 0) if count % 2 == 0 and imagine == False: T.append(realss[:]) realss.clear() comps.clear() elif count % 2 != 0 and imagine == True: T.append(realss[:]) realss.clear() comps.clear() elif count % 2 == 0 and imagine == True: T.append(comps[:]) realss.clear() comps.clear() Xvec.clear() XXvec.clear() Tfixed = np.array(T, dtype=float).T Tinv = sc.linalg.inv(Tfixed) return Tfixed, Tinv
def calculate_prior(metric1, val1, metric2, val2, metric3, val3, weight): sym_met = get_metric_dictionary()['symbolic'] equation_system = [ n - weight, sym_met[metric1] - val1, sym_met[metric2] - val2, sym_met[metric3] - val3 ] # use sympy to solve for cm_entries (which corresponds to the prior) cm_entries_values = sympy.nonlinsolve(equation_system, cm_elements) # indeces must be clear, properly format as pd.Series prior = pd.Series(cm_entries_values.args[0], index=symbol_order) return prior
def nonlinsolve_it(system, solve_for, result_type='list'): ''' To solve nonlinear equations use sympy.nonlinsolve(system, variables) similar to sympy.linsolve For nonlinear system, an infinitely many solution means it has POSITIVE DIMENSIONAL SYSTEM buggy : not generalized for more than one unknown ''' sol = list(nonlinsolve(system, solve_for)) solution_list = [sol[0][0], sol[0][1]] if result_type == 'list': return solution_list if result_type == 'dict': solution_dict = dict(zip(solve_for, solution_list)) return solution_dict if result_type == 'raw': return nonlinsolve(system, solve_for)
def solve_equation(lati, lon, alt, rsrp): x_1, x_2, x_3 = sy.symbols("x_1 x_2 x_3") eq = [] for i in range(0, len(lati)): lng, lat = map(radians, [lon[i], lati[i]]) # 经纬度转换成弧度 distance = round( sqrt((2 * asin( sqrt((sin((x_1 - lat) / 2)**2 + cos(x_2) * cos(lat) * sin( (x_2 - lng) / 2)**2))) * 6371 * 1000) ^ 2 + (alt2 - alt1) ^ 2) / 1000, 3) eq = np.append(43 - 20 * (math.log(distance, 10)) - 20 * (math.log(2000, 10)) + 27.55 - rsrp[i]) result = sy.nonlinsolve(eq, [x_1, x_2, x_3]) print(result)
def _update_for_minimisation_using_solve(self, x_k): func = self._f x = func.func_args() jacob_at_x_k = func.gradient_at(x_k) hess_at_x_k = func.hessian_at(x_k) delta_x = x - x_k # Setup system of equation system_equation = hess_at_x_k * delta_x + jacob_at_x_k # Solve it the system of equations result = sy.nonlinsolve(system_equation, list(x)) # Convert from set to vector res_vector = sy.Matrix(list(result)[0]) return x_k - res_vector
def produce_valid_solutions(): for C_val in np.geomspace(start=200e-15, stop=10e-12, num=5): for R_val in np.geomspace(start=1, stop=10e6, num=5): # TODO: is the right approach to solve for equality of the magnitude of the poles? sym_pole_subs = [ p.subs({ C: C_val, R: R_val }) for p in sym_poles ] sol = sp.nonlinsolve( [ sym_pole_subs[0] - des_poles[0], sym_pole_subs[1] - des_poles[1], #sym_pole_subs[0] * sym_pole_subs[1] - desired_filter.to_zpk().K ], [gm]) print(sol)
def permutate(arr, available): out = [] solveFor = [] bad = [" ", "*", "/", "+", "-", "(", ")"] for char in available: if findVar(arr[0], char, bad) or findVar(arr[1], char, bad): solveFor.append(char) for char in solveFor: try: print("Solving", arr, "for", char) yeeet = list( iter( nonlinsolve([parse_expr("-".join([arr[1], arr[0]]))], (parse_expr(char))))) try: while len(yeeet) == 1: yeeet = list(iter(yeeet[0])) raise except: try: while len(yeeet) > 1: yeeet = yeeet[0] except: pass for i in yeeet: temp = str(i) temp = temp.replace(",", "") out.append([char, temp]) print([char, temp]) except SyntaxError: print(f"Failed to solve {arr} for {char}.") # final = [char,list(nonlinsolve([parse_expr("-".join([arr[1],arr[0]]))],(parse_expr(char))))[0][0]] # print(final) # out.append(final) return out
def resolverSistemaNL(ecuations, variables): #variablesEcuacion = [] #for variable in variables: arregloExpresiones = [] arregloIncognitas = [] if (len(variables) > 4): print("Cantidad de incognitas invalida") return for i in range(0, len(variables)): variables[i] = Symbol(variables[i]) print(variables[i]) print(variables) for ecuation in ecuations: arregloExpresiones.append(sympy.sympify(ecuation)) result = nonlinsolve(arregloExpresiones, variables) arregloSalida = [ str(result.args[0][i]) for i in range(0, len(arregloExpresiones)) ] #print(arregloSalida) return arregloSalida
def _calc_integration_constants(self, solution): ret_expr = solution lin_eqs = [] constants = self._produce_integr_constants_list() for curr_bcs in self.bcs: # type: hamTask.BoundaryCondition a_new_lin_eq = solution.diff(x, curr_bcs.fx_order) a_new_lin_eq = a_new_lin_eq.subs({x: curr_bcs.x}) lin_eqs.append(a_new_lin_eq) assert len(constants) == len(lin_eqs) try: ans = linsolve(lin_eqs, constants) except ValueError: ham_error('HAM_ERROR_CRITICAL', 'CRITICAL__ASSERT_NOT_REACHED') ans = nonlinsolve(lin_eqs, constants) if isinstance(ans, FiniteSet): vals_lex = {} ans = (list(ans))[0] for i in range(len(ans)): vals_lex[constants[i]] = ans[i] ret_expr = solution.subs(vals_lex) elif isinstance(ans, EmptySet): self.sympy_solved = False return ret_expr
'x_0 y_0 y_1 x_1 phi_0 phi_x phi_y') phixx, phiyy = sym.symbols('phi_xx phi_yy') x2, y2 = sym.symbols('x2 y2') trial_function = (1 - x**2) * (1 - y**2) #2. Set up The Element Parameters ax, bx, ay, by, c = sym.symbols('a_x b_x a_y b_y c') #This creates the template element by approximating it as a plane. eq1 = sym.Eq(phi0, ax * x0**2 + bx * x0 + ay * y0**2 + by * y0 + c) eq2 = sym.Eq(phix, ax * x1**2 + bx * x1 + ay * y0**2 + by * y0 + c) eq3 = sym.Eq(phixx, ax * x2**2 + bx * x2 + ay * y0**2 + by * y0 + c) eq4 = sym.Eq(phiy, ax * x0**2 + bx * x0 + ay * y1**2 + by * y1 + c) eq5 = sym.Eq(phiyy, ax * x0**2 + bx * x0 + ay * y2**2 + by * y2 + c) result = sym.nonlinsolve([eq1, eq2, eq3, eq4, eq5], [ax, ay, bx, by, c]) # print(sym.latex(result)) phi_final = result.args[0][0] * x**2 + result.args[0][1] * y**2 + result.args[ 0][2] * x + result.args[0][3] * y + result.args[0][4] phi_solve_vars = [phi0, phix, phixx, phiy, phiyy] phi_poly = sym.Poly(phi_final, phi_solve_vars) # print(sym.latex(phi_poly.as_expr())) interpolation_functions = [ phi_poly.as_expr().coeff(val) for val in phi_solve_vars ]
K = np.array([0.060, 0.12, 0.22, 0.40, 0.69, 0.98, 1.3]) / C_0**n_A X = np.array(1 / T).reshape((-1, 1)) Y = np.log(K) model = LinearRegression().fit(X, Y) A = np.exp(model.intercept_) E_A = model.coef_ * -R print('Activation Energy:', E_A[0], ' J/mol') x = np.arange(0, 80, 0.1) + 273.15 y = A * np.exp(-E_A / (R * x)) plt.plot(T, K, 'o', color='black') plt.plot(x, y) plt.title('Problem 02') plt.xlabel('Temperature (K)') plt.ylabel('Rate Constant (m/s)') plt.show() # Problem 3 Part E r, q_A, q_B = sp.symbols('r, q_A, q_B') k, k_A, C_A, k_B, C_B = sp.symbols('k, k_A, C_A, k_B, C_B') eqns = [k_A * C_A * (1 - q_A - q_B) - 1 / k_A * q_A - r, \ k_B * C_B * (1 - q_A - q_B) - 2 * r, \ k * q_A * q_B - r] sol = sp.nonlinsolve(eqns, r, q_A, q_B) sp.pprint(sol.args[1], use_unicode=True)
def findMetaVals(angle,subMaterial): """Inputs""" #phaseShifts = [-150, -90, -30, 30, 90, #150] # The desired phase shift we want. Real world angle shift of antenna waves # phaseShifts= [-90] #The desired phase shift we want. Real world angle shift of antenna waves period = (2.998e8 / 10.5e9) / np.sin(np.deg2rad(angle)) num_cells = round(period / 5.1e-3) print(num_cells) phaseShifts = list(np.arange(-150,210, 360 / num_cells)) freq = 10.5e9 # for 10 GHz atenna, can be altered inputAngle = 0 outputAngle = -angle polarization = 'TM' # can be either TM or TE """Inputs""" """constants""" pi = math.pi j = 1j Z0 = 120 * pi """constants""" """Substrate Constants""" L = 1.52e-3 # subtrate thickness constant specific to substrate substratePermit = 3 # relative permeativity of RO3003 if (subMaterial=="Rogers RO3010"): L = 1.28e-3 substratePermit = 10.2 if(subMaterial=="Rogers RO3003"): L = 1.52e-3 # subtrate thickness constant specific to substrate substratePermit = 3 # relative permeativity of RO3003 """Substrate Constants""" """Physical Constants""" e0 = 8.85e-12 # Permittivity of free space (epsilon-not) c0 = 1 / sqrt(4 * pi * 1e-7 * e0) # Velocity of light in free space (air or vaccum) """Physical Constants""" """bondply constants""" Lbp = 0.076e-3 # Bondply thickness constant specific to substrate bondplyPermit = 2.94 # Bondply permeativity betabp = sqrt(bondplyPermit) * 2 * pi / (c0 / freq) # wavenumber in the substrate for bondply Zcbp = Z0 / sqrt(bondplyPermit) # characteristic impedance for bondply """bondply constants""" if not useLookup: poptop, popmid, popbot = curveFit.curveFit(subMaterial) if polarization == 'TM': ZL = Z0 * cosd(outputAngle) ZS = Z0 * cosd(inputAngle) elif polarization == 'TE': ZL = Z0 / cosd(outputAngle) ZS = Z0 / cosd(inputAngle) c0 = 1 / sqrt(4 * pi * 1e-7 * 8.85 * 1e-12) # velocity of light in free space (air or vaccum) beta = sqrt(substratePermit) * 2 * pi / (c0 / freq) # wavenumber in the substrate Zc = Z0 / sqrt( substratePermit) # Note that due to the presence of dielectric constant, the characteristic impedance of the substrate is different than Z0. # Calculating the ABCD Parameters of the impedance sheets # Defining three symbols in MATLAB. Note that Y1, Y2, and Y3 are ADMITTANCES, NOT impedances # using sympy6 for matrix ops, good documentation online cols=["im","wid","length","trace","UCnum"] dfout= pd.DataFrame(columns=cols) for c,phicurr in enumerate(phaseShifts): Y1,Y2,Y3 = sp.symbols("Y1, Y2, Y3") T1= sp.Matrix([[1,0],[Y1,1]]) T3= sp.Matrix([[1,0],[Y2,1]]) T5= sp.Matrix([[1,0],[Y3,1]]) T4= sp.Matrix([[cos(beta*L),j*Zc*sin(beta*L)],[j*sin(beta*L)/Zc,cos(beta*L)]]) T2 = T4 bondply = sp.Matrix([[cos(betabp*Lbp), j*Zcbp*sin(betabp*Lbp)], [j*sin(betabp*Lbp)/Zcbp, cos(betabp*Lbp)]]) T = T1 * T2 *bondply* T3 * T4 * T5 ; phi= -phicurr Z11 = -j * ZS * cotd(phi) Z12 = -j * sqrt(ZS * ZL) / sind(phi) Z21 = Z12 # this is due to the reciprocity. Z22 = -j * ZL * cotd(phi) Z=sp.Matrix([[Z11,Z12],[Z21,Z22]]) A = Z11/Z21 B = Z.det()/Z21 C = 1/Z21 D = Z22/Z21 eqns=sp.Matrix([A==T[0,0],B==T[0,1],D==T[1,1]]) eq1=Eq(A-T[0,0]) eq2=Eq(B-T[0,1]) eq3=Eq(D-T[1,1]) sol=sp.nonlinsolve((eq1,eq2,eq3),(Y1,Y2,Y3)) (Y1,Y2,Y3)=next(iter(sol)) Y1=Y1.evalf() Y2=Y2.evalf() Y3=Y3.evalf() ObtainedZ1 = 1/Y1 # this is the inverse of Y1. Therefore, it is Z1. ObtainedZ2 = 1/Y2 # this is the inverse of Y2. Therefore, it is Z2. ObtainedZ3 = 1/Y3 # this is the inverse of Y2. Therefore it is Z3. solutionstatement= "The Solutions for Z1,Z2,Z3 are:Z1:%s,Z2:%s,Z3:%s" % (ObtainedZ1 ,ObtainedZ2 ,ObtainedZ3) if(useLookup): # if we want to use the lookup table widthz1, lengthz1 = lookup_lw.LookupLW(subMaterial,-ObtainedZ1 * j, 'top') widthz2, lengthz2 = lookup_lw.LookupLW(subMaterial, -ObtainedZ2 * j, 'mid') widthz3, lengthz3 = lookup_lw.LookupLW(subMaterial,-ObtainedZ3 * j, 'bot') else: # if we want to estimate widthz1,lengthz1=curveFit.findUnknowns(-ObtainedZ1*j,'top',poptop) widthz2,lengthz2=curveFit.findUnknowns(-ObtainedZ2*j,'mid',popmid) widthz3,lengthz3=curveFit.findUnknowns(-ObtainedZ3*j,'bot',popbot) dfjson="" lenwidstatement= "The Solutions for Z1,Z2,Z3 are:Z1: width-%s,length-%s,Z2:width-%s,length%s,Z3:width-%s,length-%s" % (widthz1,lengthz1,widthz2,lengthz2,widthz3,lengthz3) dfout=dfout.append(pd.DataFrame([[round(-ObtainedZ1*j,5),round(widthz1,5),round(lengthz1,5),"top","UC"+str(c+1)]],columns=cols),ignore_index=True) dfout=dfout.append(pd.DataFrame([[round(-ObtainedZ2*j,5),round(widthz2,5),round(lengthz2,5),"mid","UC"+str(c+1)]],columns=cols),ignore_index=True) dfout=dfout.append(pd.DataFrame([[round(-ObtainedZ3*j,5),round(widthz3,5),round(lengthz3,5),"bot","UC"+str(c+1)]],columns=cols),ignore_index=True) dfjson=dfout.to_json(orient='records') return dfout,dfjson
import sympy a, u, v = sympy.symbols("a u v") eq1 = u**2 - 2 * v**2 - a**2 eq2 = u + v - 2.0 # using real value to force numerical evaluation eq3 = a**2 - 2 * a - u sols = sympy.nonlinsolve([eq1, eq2, eq3], [a, u, v]) # sols is finite set, we will iterate over its elements for sol in sols: print("sol = ", sol)
import sympy as sp from equations import * eqs = sp.nonlinsolve([vr_p, vs_p, vv_p, vc_p, wr_p, ws_p, wv_p, wc_p], [vr, wr, vs, ws, vv, wv, vc, wc]) print(eqs)
import sympy as sy import scipy from scipy.integrate import odeint import numpy as np import matplotlib.pyplot as plt x,y=sy.symbols('x,y',function=True) mu,t=sy.symbols('mu,t',real=True) eq1=mu*x+y-x**2 eq2=-x+mu*y+2*x**2 system=sy.Matrix([eq1,eq2]) b=sy.Matrix([0,0]) fixedPoints=list(sy.nonlinsolve(system,[x,y])) print(fixedPoints[0]) Y=sy.Matrix([x,y]) M=system.jacobian(Y) test=M.subs(x,fixedPoints[1][0]) #delta=test.det() eigen1=list(test.eigenvals()) print(eigen1)
mdf.write('Let: $$\\omega_{\\xi1} = ' + spltx(K_Drc_factor) + ' \\qquad ' + '\\omega_{\\xi2} = ' + spltx(K_Drc_add) + ' = ' + spltx(K_Drc_add.subs(ricatti_vals)) + ' \\qquad ' + '\\omega_{\\xi3} = ' + spltx(K_Prc_add) + ' = ' + spltx(K_Prc_add.subs(ricatti_vals)) + '$$\n\n') mdf.write('We would like to use $\\omega_{\\xi1}$, $\\omega_{\\xi2}$ and ' '$\\omega_{\\xi3}$ to choose the derivative, proportional and ' 'integral gains of the regulated and controlled degrees of ' 'freedom. Therefore, we solve these equations ' 'for $\\omega_{uc}$, $\\omega_{1c}$ and $\\omega_{3c}$:\n\n') w_uc_eq, w_1c_eq, w_3c_eq = next(iter(sp.nonlinsolve([ w_xi1 - K_Drc_factor.subs(ricatti_vals), w_xi2 - K_Drc_add.subs(ricatti_vals), w_xi3 - K_Prc_add.subs(ricatti_vals) ], [ w_uc, w_1c, w_3c ]))) mdf.write('$$\\omega_{uc} = ' + spltx(w_uc_eq) + ' \\qquad ' + '\\omega_{1c} = ' + spltx(w_1c_eq) + ' \\qquad ' + '\\omega_{3c} = ' + spltx(w_3c_eq) + '$$\n\n') mdf.write('All values must be real, thus $\\omega_{\\xi1} > 0$ must hold. ' 'Another important constraint is that ' '$\\omega_{\\xi2}^2 > 2 \\omega_{\\xi3}$. ' 'Note that this constraint is trivial if ' '$\\omega_{\\xi3} < 0$.\n\n') mdf.write('Note that $\\omega_{\\xi1}$, $\\omega_{\\xi2}$ and ' '$\\omega_{\\xi3}$ have been chosen such that the effective '
x,y = sy.symbols('x y') sy.init_printing(use_unicode=True) #%% Define Function f = x**4+y**2-x*y # function 2 from Stanford #f = 4*x + 2*y - x**2 -3*y**2 f df_dy = sy.diff(f,y) df_dx = sy.diff(f,x) df_dx #%% Find critical points cr =sy.nonlinsolve([df_dx,df_dy],[x,y]) print('critical points',cr) cr #%% build hessian e = sy.hessian(f,[x,y]) e #%% Find eigenvalues for each of the critical points for c in cr : xv = c[0] yv = c[1] print('Critical point : \n\tx : {} \n\ty : {}'.format(xv.evalf(),yv.evalf())) eigs = list(e.subs({x:xv,y:yv}).eigenvals().keys()) if eigs[0] > 0 and eigs[1] > 0 : print('Concave up') elif eigs[0] < 0 and eigs[1] < 0 :
eq_1 = Eq(x**2 + y, 0) eq_2 = Eq(x - y, 2) print("eq_1:") pprint(eq_1) print("----------1---------") print("eq_2:") pprint(eq_2) print("----------2---------") #Since one of the equations is nonlinear, we should use nonlinsolve. solution = nonlinsolve([eq_1, eq_2], (x, y)) #The type of solution is <class 'sympy.sets.sets.FiniteSet'> print("solution:") pprint(solution) print("----------3---------") solution = list(solution) #convert the solution into a list print("solution:") pprint(solution) print("----------4---------") solution = solution[0] #The type of solution is <class 'sympy.core.containers.Tuple'> print("solution:")
eq1 = (sum_Ti - Ti_si - Ti_Cli) eq2 = (sum_H - H_m - Ti_Cli) #- Fe3V) eq3 = (sumFe - Fe2_m - Fe3V) # I am wondering if there are other reactions we could write to help combine some of these other equations #K = (H_m ^ 2 * Fe2_m ^ 2 * Ti_si)/(Ti_Cli * {2Fe3_m + V_m}) eqk = sympy.Eq((H_m**2 * Fe2_m**2 * Ti_si) / (Ti_Cli * Fe3V), K) # %% # %% # %% sympy.solve([eq1, eq2, eq3, eqk], [Ti_si, Ti_Cli, Fe3V, Fe2_m], exclude=[sum_H, sum_Ti, sumFe, K], dict=True) # %% sympy.nonlinsolve([eq1, eq2, eq3, eqk], [Ti_si, Ti_Cli, Fe3V, Fe2_m]) # %% # %% # %% # %% # %% eq = sympy.solve(eq1_new, Ti_si) eqk_new = eqk_new.subs(Ti_si, eq[0]) sympy.solve(eqk_new, H_m) # this returns an empty list. I am not sure why? sympy.nonlinsolve([eq1, eqk, eq2], [Ti_si, Ti_Cli])
def _prepare_triple_flash_approx(use_cache=CFG['use_cache']): """Solve the combination of FLASH images analytically.""" cache_filepath = os.path.join(PATH['cache'], 'flash_triple_approx.cache') if not os.path.isfile(cache_filepath) or not use_cache: print('Solving Triple FLASH Approx equations. May take some time.') print('Caching results: {}'.format(use_cache)) s, m0, fa, tr, t1, te, t2s, eta_fa, eta_m0 = sym.symbols( 's m0 fa tr t1 te t2s eta_fa eta_m0', positive=True) s1, s2, s3, tr1, tr2, tr3, fa1, fa2, fa3 = sym.symbols( 's1, s2, s3, tr1 tr2 tr3 fa1 fa2 fa3', positive=True) n = sym.symbols('n') eq = sym.Eq(s, sym_signal(m0, fa, tr, t1, te, t2s, eta_fa, eta_m0)) eq_1 = eq.subs({s: s1, fa: fa1, tr: tr1}) eq_2 = eq.subs({s: s2, fa: fa2, tr: tr2}) eq_3 = eq.subs({s: s3, fa: fa3, tr: tr3}) def ratio_expr(x): return x[0] / x[1] eq_r21 = _eq_expr(eq_2, eq_1, expr=ratio_expr).expand().trigsimp() eq_r31 = _eq_expr(eq_3, eq_1, expr=ratio_expr).expand().trigsimp() # tr1, tr2, tr3 << t1 approximation # fa1, fa2, fa3 ~ 0 approximation print('\n', 'Approx: Small FA, Short TR') eq_ar21_ = eq_r21.copy() for tr_ in tr1, tr2, tr3: eq_ar21_ = eq_ar21_.subs( sym.exp(-tr_ / t1), sym.exp(-tr_ / t1).series(tr_ / t1, n=2).removeO()) for fa_ in fa1, fa2, fa3: for fa_expr in (sym.sin(eta_fa * fa_), sym.cos(eta_fa * fa_)): eq_ar21_ = eq_ar21_.subs( fa_expr, fa_expr.series(eta_fa * fa_, n=3).removeO()) eq_ar31_ = eq_r31.copy() for tr_ in tr1, tr2, tr3: eq_ar31_ = eq_ar31_.subs( sym.exp(-tr_ / t1), sym.exp(-tr_ / t1).series(tr_ / t1, n=2).removeO()) for fa_ in fa1, fa2, fa3: for fa_expr in (sym.sin(eta_fa * fa_), sym.cos(eta_fa * fa_)): eq_ar31_ = eq_ar31_.subs( fa_expr, fa_expr.series(eta_fa * fa_, n=3).removeO()) print(eq_ar21_) print(eq_ar31_) result = sym.nonlinsolve((eq_ar21_, eq_ar31_), (t1, eta_fa)) for j, exprs in enumerate(result): print() print('solution: ', j + 1) for name, expr in zip(('t1', 'eta_fa'), exprs): print(name) print(expr) t1_ = tuple(exprs[0] for exprs in result) eta_fa_ = tuple(exprs[1] for exprs in result) pickles = (s, m0, fa, tr, t1, te, t2s, eta_fa, eta_m0, s1, s2, s3, tr1, tr2, tr3, fa1, fa2, fa3, t1_, eta_fa_) with open(cache_filepath, 'wb') as cache_file: pickle.dump(pickles, cache_file) else: with open(cache_filepath, 'rb') as cache_file: pickles = pickle.load(cache_file) print(pickles)
def generator(equations, available): output = [] temp = [] # print("before:",equations) for arr in equations: temp.extend(permutate(arr, available)) for d in range(len(temp) - 1, -1, -1): for eq in range(len(equations) - 1, -1, -1): # print(equations[eq], temp[d]) if equations[eq][0] == temp[d][0] and equations[eq][1] == temp[ d][1]: temp.pop(d) d -= 1 equations.extend(temp) # print("after:",equations) for p in equations: loc = [] for l in range(len(equations)): if equations[l][0] == p[0] and [equations[l][1], p[1] ] not in output: if equations[l][0] in available and p[0] in available: loc.append(l) for m in range(len(loc) - 1): if [equations[loc[m]][1], equations[loc[m + 1]][1]] not in output: numVars = 0 for k in available: if k in equations[loc[m]][1] + equations[loc[m + 1]][1]: solveFor = k numVars += 1 if numVars == 1: garit = [ k, str( list( nonlinsolve([ " - ".join([ equations[loc[m]][1], equations[loc[m + 1]][1] ]) ], (parse_expr(solveFor))))[0][0]) ] if "complexes" in garit[1].lower() or "emptyset" in garit[ 1].lower() or "conditionset" in garit[1].lower(): break else: garit = [equations[loc[m]][1], equations[loc[m + 1]][1]] output.append(garit) # print(equations) temp = [] # print("before:",equations) for arr in output: temp.extend(permutate(arr, available)) # print("temp:",temp) for d in range(len(temp) - 1, -1, -1): for eq in range(len(output) - 1, -1, -1): # print(d) if len(output) > 0 and len(temp) > 0: pass # print(output[eq],temp[d]) # if output[eq][0] == temp[d][0] and output[eq][1] == temp[d][1]: # # print("pop!") # print("popping",temp[d]) # temp.pop(d) # # print(temp) # d-=1 equations.extend(temp) # print("after:",equations) equations.reverse() # print(equations) for i in range(len(equations) - 1, -1, -1): # print("testing 0:",equations[i]) if equations[i][1] == "0": # print("0:",equations[i]) equations.pop(i) return equations