def go_back(x,y,a=40,b=50,R_0 = 90,l=10,m=3,aa=0.0,q0=3.0,eps=.07): hit_divert = (x>b) inCORE = x<b stopevolve = hit_divert #eps = .2 C = ((2*m*l*a**2)/(R_0*q0*b**2))*eps def func(y_out): return (-y + y_out - C*(x/b)**(m-2) *np.cos(m*y_out))**2 def func2(y_out): return (-y_old + y_out + (2.0*np.pi/q) + aa*np.cos(y_out))**2 y_old = copy(y) y_old = (newton_krylov(func,y)) y_old = np.mod(y_old,2.0*np.pi) x_old = x + (m*b*C)/(m-1)*(x/b)**(m-1) *np.sin(m*y_old) q = q0*(x_old/a)**2 y_old2 = copy(y_old) y_old2 = (newton_krylov(func2,y_old)) #y_old2 = y_old - 2*np.pi/q #- aa*np.cos( y_old2 = np.mod(y_old2,2.0*np.pi) x_old2 = x_old*(1.0 -aa*np.sin(y_old2)) return x_old2,y_old2
def do_one_step(self, t, psi0, x0): """ Take one integration step. """ # Apply adjoint method f = lambda y: self.residue_adjoint(y, psi0, x0) b0 = so.newton_krylov(f, self.b, f_tol=1e-14) U0 = cayley_klein(self.half_time * b0) psi1 = apply_2by2(U0, psi0) x1 = hopf(psi1) # Apply direct method f = lambda y: self.residue_direct(y, psi1, x1) b1 = so.newton_krylov(f, b0, f_tol=1e-14) U1 = cayley_klein(self.half_time * b1) psi2 = apply_2by2(U1, psi1) x2 = hopf(psi2) self.b = b1 # Compute momentum map, if needed m = None if self.compute_momentum: m = self.compute_momentum_map_S3(psi0, psi1) return psi2, x2, m
def do_one_step(self, t, psi0, x0): callback = None if self.diagnostics: callback = self.diagnostics_logger f = lambda y: self.residue_mu_direct(y, psi0, x0) self.b = so.newton_krylov(f, self.b, f_tol=1e-14, callback=callback, verbose=False) U = cayley_klein(self.half_time*self.b) psi0 = apply_2by2(U, psi0) x0 = hopf(psi0) self.diagnostics_logger.store() f = lambda y: self.residue_mu_adjoint(y, psi0, x0) self.b = so.newton_krylov(f, self.b, f_tol=1e-14, callback=callback, verbose=False) U = cayley_klein(self.half_time * self.b) psi0 = apply_2by2(U, psi0) x0 = hopf(psi0) self.diagnostics_logger.store() return psi0, x0
def do_step(self, t, dt, uold, j=None): for i in range(self.stages): temp = uold + dt * sum( [self.A[i, m] * self.k[m] for m in range(i)]) try: self.k[i] = newton_krylov(f_root(t, dt, temp, self.rhs, self.A[i, i], self.c[i]), uold if i == 0 else self.k[i - 1], f_tol=1.e-10, f_rtol=1.e-10) except ValueError: self.k[i] = newton_krylov(f_root(t, dt, temp, self.rhs, self.A[i, i], self.c[i]), uold, f_tol=1.e-10, f_rtol=1.e-10) unew = uold + dt * sum( [self.b[i] * self.k[i] for i in range(self.stages)]) ulow = uold + dt * sum( [self.b_hat[i] * self.k[i] for i in range(self.stages)]) if j is not None: j_up, j_quad_est = self.do_quadrature(t, uold, dt, j, 1) return unew, unew - ulow, j_up, j_quad_est return unew, unew - ulow
def solve(self): self.time,self.u = self.dydt.createArray() print('Running Adams-Moulton (Implicit) 5th-ord') ## compute first fourth points using 4th order (classic) Runge Kutta for i in range(4): # using Backward Euler for the first point func = lambda up1 : up1 - self.u[i]-self.dt*self.f(self.time[i+1], up1) self.u[i+1] = newton_krylov(func , self.u[i] , f_tol = 10e-8) #for i in range(4): # k1 = self.dydt.f(self.time[i],self.u[i]) # k2 = self.dydt.f(self.time[i]+self.dt/2. , self.u[i]+ self.dt/2. *k1 ) # k3 = self.dydt.f(self.time[i]+self.dt/2. , self.u[i]+ self.dt/2. *k2 ) # k4 = self.dydt.f(self.time[i]+self.dt , self.u[i]+ self.dt *k3 ) # self.u[i+1] = self.u[i] + self.dt/6. * (k1 + 2*k2 + 2*k3 + k4) for i in range(4, len(self.time)-1): function = lambda up1 : - up1 + self.u[i] + self.dt/720. * ( 251. * self.f(self.time[i+1],up1) \ + 646. * self.f(self.time[i],self.u[i])\ - 264. * self.f(self.time[i-1],self.u[i-1])\ + 106. * self.f(self.time[i-2],self.u[i-2])\ - 19. * self.f(self.time[i-3],self.u[i-3])) self.u[i+1] = newton_krylov(function , self.u[i] , f_tol = 10e-12) print('... Done!') AdamsMoulton5th.solved = True if self.file != None: super().write2file() if self.save: return self.time,self.u def plot(self): if AdamsMoulton5th.solved: super().plot('Sys ODE solution using Adams-Moulton 5th order','time [s]','y(t)') else: print("Unsolved problem, call `solve` method before")
def do_one_step(self, t, X0): rho0 = vector_hatmap(X0, self.gamma) grad = self.gradient_hamiltonian(rho0) callback = None if self.diagnostics: callback = self.diagnostics_logger def optimization_function(rho1): s = grad + self.gradient_hamiltonian(rho1) res = np.empty((self.N, 3, 3)) for n in range(0, self.N): #g = linalg.expm(-self.h/2*s[n, :, :]) g = cayley(-self.h/4*s[n, :, :]).squeeze() res[n, :, :] = rho1[n, :, :] - Ad(g, rho0[n, :, :]) return res #d = Diagnostics() rho1 = newton_krylov(optimization_function, rho0, f_tol=1e-14, callback=callback) self.diagnostics_logger.store() #print d.n_current return vector_invhat(rho1, self.gamma)
def hidalgo_initial_guess(w, dtgaps): """ Returns the initial guess found in DOI: 10.1007/s10915-010-9426-6 NB: Only implemented in 1D """ dx = dxi[0] q = zeros([N + 1] * (ndim + 1) + [n]) qj = w # Set values at start of time step to WENO reconstruction for j in range(N + 1): # Loop over the time levels in the DG predictor dt = dtgaps[j] dqdxj = dot(derivs, qj) for i in range(N + 1): # Loop over spatial nodes at time level j qij = qj[i] dqdxij = dqdxj[i] J = dot(jacobian(qij, 0), dqdxij) Sj = source(qij) if superStiff: # If sources are very stiff, root must be found implicitly f = lambda X: X - qij + dt / dx * J - dt / 2 * (Sj + source(X)) q[j, i] = newton_krylov(f, qij, f_tol=TOL) else: q[j, i] = qij - dt / dx * J + dt * Sj qj = q[j] return q.reshape([NT, n])
def compute_inflow_angle(self, r, phi0=0.0): """Solve nonlinear inflow angle equation. Parameters ---------- r: float r / D parameter x0: float Initial condition Returns ------- float If NO convergence, returns np.nan """ # Fix section func = partial(self._residual, r=r) # try: phi = newton_krylov(func, phi0) # except Exception as ex: # print(ex) # phi = np.array(np.nan) return phi.item()
def solve(preconditioning=True): """Compute the solution""" count = [0] def residual(P): count[0] += 1 d2x = zeros_like(P) d2y = zeros_like(P) d2x[1:-1] = (P[2:] - 2 * P[1:-1] + P[:-2]) / hx / hx d2x[0] = (P[1] - 2 * P[0] + P_left) / hx / hx d2x[-1] = (P_right - 2 * P[-1] + P[-2]) / hx / hx d2y[:, 1:-1] = (P[:, 2:] - 2 * P[:, 1:-1] + P[:, :-2]) / hy / hy d2y[:, 0] = (P[:, 1] - 2 * P[:, 0] + P_bottom) / hy / hy d2y[:, -1] = (P_top - 2 * P[:, -1] + P[:, -2]) / hy / hy return d2x + d2y + 5 * cosh(P).mean()**2 # preconditioner if preconditioning: M = get_preconditioner() else: M = None # solve guess = zeros((nx, ny), float) sol = newton_krylov(residual, guess, verbose=1, inner_M=M) print 'Residual', abs(residual(sol)).max() print 'Evaluations', count[0] return sol
def root_find(self, w, Ww, dt, dX): """ Finds DG coefficients with Newton-Krylov, if iteration has failed """ q = self.initial_guess(self, w, dt, dX) def f(x): return dot(self.DG_U, x) - self.rhs(x, Ww, dt, dX) return newton_krylov(f, q, f_tol=self.tol, method='bicgstab')
def find_best_rotation_parameters(self, xi: np.ndarray, c: np.ndarray, session: tf.Session): guess = self._find_rotation_matrix_guess(xi, c, session) def loss_function(angles: np.ndarray): mr = session.run([self.RTM], feed_dict={ self.xi_input: xi, self.c: c, self.angles: angles })[0] mr = mr[:, 0, :] return np.array([ mr[0, 1] - mr[1, 0], mr[0, 2] - mr[2, 0], mr[2, 1] - mr[1, 2] ]) try: sol = newton_krylov(loss_function, guess, method='lgmres', verbose=0) except NoConvergence: return None return sol
def go_forward(x,y,a=40,b=50,R_0 = 90,l=10,m=3,aa=0.0,q0=3.0): hit_divert = (x>b) inCORE = x<b stopevolve = hit_divert eps = .2 C = ((2*m*l*a**2)/(R_0*q0*b**2))*eps x_new = x/(1-aa*np.sin(y)) q = q0*(x_new/a)**2 y_new = (y+ 2*np.pi/q + aa*np.cos(y)) y_new = np.mod(y_new,2*np.pi) def func(x_out): return (-x_new + x_out +(m*b*C)/(m-1)*(x_out/b)**(m-1) *np.sin(m*y_new))**2 x_new2 = (newton_krylov(func,x_new,method='gmres',maxiter=50)) y_new2 = (y_new - C*(x_new2/b)**(m-2) * np.cos(m*y_new)) #print 'xchange:', x_new2/x x_new = x_new2 y_new = np.mod(y_new2,2*np.pi) return x_new,y_new
def cn_implicit_builtin_solver(self, iterations=None): if iterations == None: iterations = self.N self.sol[0, :] = self.initial(self.xi) A_const = self.tridiag(self.r / 2, 1.0j - self.r, self.r / 2, self.M) B_const = self.tridiag(-self.r / 2, 1.0j + self.r, -self.r / 2, self.M) A_const[0, -1] = self.r / 2 A_const[-1, 0] = self.r / 2 B_const[0, -1] = -self.r / 2 B_const[-1, 0] = -self.r / 2 for i in range(0, iterations): abs_prev = np.absolute(self.sol[i, 0:-1]) B = 0.5 * self.lmbda * self.k * np.diag(abs_prev**2 + 0.0j, 0) B += B_const b = np.matmul(B, self.sol[i, 0:-1]) def F(U): folded_U = U[0:self.M] + 1.0j * U[self.M:] abs_next = np.absolute(folded_U) A = -0.5 * self.lmbda * self.k * np.diag(abs_next**2 + 0.0j, 0) A += A_const a = np.matmul(A, folded_U) return np.concatenate((np.real(a - b), np.imag(a - b)), axis=0) unfolded_U = np.concatenate( (np.real(self.sol[i, 0:-1]), np.imag(self.sol[i, 0:-1])), axis=0) opt = optimize.newton_krylov(F, unfolded_U, f_tol=1e-7) self.sol[i + 1, 0:-1] = opt[0:self.M] + 1.0j * np.real(opt[self.M:]) self.sol[:, -1] = self.sol[:, 0] return 0
def solve(preconditioning=True): """Compute the solution""" count = [0] def residual(P): count[0] += 1 d2x = zeros_like(P) d2y = zeros_like(P) d2x[1:-1] = (P[2:] - 2 * P[1:-1] + P[:-2]) / hx / hx d2x[0] = (P[1] - 2 * P[0] + P_left) / hx / hx d2x[-1] = (P_right - 2 * P[-1] + P[-2]) / hx / hx d2y[:, 1:-1] = (P[:, 2:] - 2 * P[:, 1:-1] + P[:, :-2]) / hy / hy d2y[:, 0] = (P[:, 1] - 2 * P[:, 0] + P_bottom) / hy / hy d2y[:, -1] = (P_top - 2 * P[:, -1] + P[:, -2]) / hy / hy return d2x + d2y + 5 * cosh(P).mean() ** 2 # preconditioner if preconditioning: M = get_preconditioner() else: M = None # solve guess = zeros((nx, ny), float) sol = newton_krylov(residual, guess, verbose=1, inner_M=M) print "Residual", abs(residual(sol)).max() print "Evaluations", count[0] return sol
def advanceSolImplicit_NK(main, MZ, eqns): old = np.zeros(np.shape(main.a0)) old[:] = main.a0[:] main.a0[:] = main.a.a[:] main.getRHS(main, eqns) R0 = np.zeros(np.shape(main.RHS)) R0[:] = main.RHS[:] def unsteadyResid(v): main.a.a[:] = np.reshape(v, np.shape(main.a.a)) main.getRHS(main, eqns) R1 = np.zeros(np.shape(main.RHS)) R1[:] = main.RHS[:] Resid = (v - main.a0.flatten()) - 0.5 * main.dt * (R0 + R1).flatten() return Resid def printnorm(x, r): ## Create Global residual data = main.comm.gather(np.linalg.norm(r)**2, root=0) if (main.mpi_rank == 0): Rstar_glob = 0. for j in range(0, main.num_processes): Rstar_glob += data[j] Rstar_glob = np.sqrt(Rstar_glob) for j in range(1, main.num_processes): main.comm.send(Rstar_glob, dest=j) else: Rstar_glob = main.comm.recv(source=0) if (Rstar_glob < 1e-9): if (main.mpi_rank == 0): print('Convergence Achieved, NL norm = ' + str(np.linalg.norm(Rstar_glob))) r[:] = 1e-100 else: if (main.mpi_rank == 0): print('NL norm = ' + str(np.linalg.norm(Rstar_glob))) #jac = BroydenFirst() #kjac = KrylovJacobian(inner_M=InverseJacobian(jac)) sol = newton_krylov(unsteadyResid, main.a.a.flatten(), iter=None, rdiff=None, method='gmres', inner_maxiter=40, inner_M=None, outer_k=10, verbose=4, maxiter=None, f_tol=1e-8, f_rtol=1e-8, x_tol=None, x_rtol=None, tol_norm=None, line_search='armijo', callback=printnorm) main.a.a = np.reshape(sol, np.shape(main.a.a)) main.a0[:] = np.reshape(sol, np.shape(main.a.a)) main.t += main.dt main.iteration += 1
def solve(self): x_fp = newton_krylov(self.rootOperator, self.x_0, maxiter = self.numberOfIterations, verbose=0, x_rtol=self.convergenceCriterion, method='lgmres', callback=self.iterationCounter) print "scipy Newton Krylov converged after" , self.iterationStep, "steps" #As a side effect, we calculate other intersting physical quantities based on the found fixpoint solution self.derivePhysicalQuantitiesFromFixpoint(x_fp) #Reset iteration counter in case solve is called various times (and class is not re-instantiated) self.iterationStep = 0
def M_main(self, z): #Main progenitor halo mass from Neistein 2006 M_0 = np.power(10, self.logM0) gamma = self.omega_m * self.h * np.exp( -self.omega_b * (1 + np.sqrt(2 * self.h) / self.omega_m)) return np.log10( self.omega_m / (gamma**3) * newton_krylov(self.F_inv1(z, self.z_0, M_0, gamma), 0.01))
def implicit_solve(self, next_x, func, method="unused", **kwargs): """A solver for the implicit equations. """ assert_is_instance(next_x, np.ndarray, descriptor="Initial Guess", checking_obj=self) assert_is_callable(func, descriptor="Function of RHS for Implicit Solver", checking_obj=self) sol = scop.newton_krylov(func, next_x.reshape(-1)) assert_is_instance(sol, np.ndarray, descriptor="Solution", checking_obj=self) return sol.reshape(self.dim_for_time_solver)
def Question1(): t0 = time() x = [1, 1] sol = newton_krylov(f, x) print(sol) t1 = time() times = t1 - t0 print(times)
def rhoBar(D, rhoL=0.4, rhoR=0.6, x=None, sigma=None, E=0, verbose=False): """ Calculate the steady state profile for a 1D system. D, sigma - Diffusion and mobility coefficients (must supply functions even if they are constant) rhoL, rhoR - boundary conditions. E - bulk field """ if x is None: x = np.linspace(0, 1) rho0 = rhoL * (1 - x) + rhoR * x + 0.02 rho0[0] = rhoL rho0[-1] = rhoR dx = np.gradient(x) residual = lambda rho: steadyStateEquation(rho, rhoL, rhoR, D, sigma, E, dx ) try: rhoBulk = opti.newton_krylov(residual, rho0[1:-1], method="gmres", x_rtol=1e-9, verbose=verbose) except opti.nonlin.NoConvergence: try: rhoBulk = opti.newton_krylov(residual, rho0[1:-1], method="lgmres", x_rtol=1e-9, verbose=verbose) except opti.nonlin.NoConvergence: try: rhoBulk = opti.anderson(residual, rho0[1:-1], x_rtol=1e-9, verbose=verbose) except opti.nonlin.NoConvergence: rhoBulk = opti.newton_krylov(residual, rho0[1:-1], method="gmres", x_rtol=1e-9, iter=15000, verbose=verbose) rho = rhoBulk rho = np.insert(rho, 0, rhoL) rho = np.append(rho, rhoR) return rho
def soil_temperature(g, meteo, temp_sky_eff, soil_label_prefix='other'): """Computes soil temperature Args: g: a multiscale tree graph object meteo (DataFrame): forcing meteorological variables t_sky_eff (float): [°C] effective sky temperature soil_label_prefix(str): prefix of soil nodes Returns: (double): [°C] soil temperature Notes: Heat loss into deeper soil layers is not considered. """ relative_humidity, atm_pressure, temp_air = [ float(meteo[x]) for x in ('hs', 'Pa', 'Tac') ] temp_sky_eff = utils.celsius_to_kelvin(temp_sky_eff) soil_nodes = [ g.node(vid) for vid in g.property('geometry') if g.node(vid).label.startswith(soil_label_prefix) ][0] temp_leaves = utils.celsius_to_kelvin( mean(list(g.property('Tlc').values()))) shortwave_inc = old_div(soil_nodes.Ei, (0.48 * 4.6)) # Ei not Eabs temp_soil = soil_nodes.Tsoil if 'Tsoil' in soil_nodes.properties( ) else temp_air def _SoilEnergyX(temp_soil): shortwave_abs = ( 1 - 0.25 ) * shortwave_inc # 0.25 is rough estimation of albedo of a bare soil longwave_net = e_soil * sigma * (1. * e_sky * temp_sky_eff**4 + 1. * e_leaf * temp_leaves**4 - temp_soil**4) latent_heat = old_div( -lambda_ * 0.06 * utils.vapor_pressure_deficit( temp_air, temp_soil, relative_humidity), atm_pressure) # 0.06 is gM from Bailey 2016 AFM 218-219:146-160 sensible_heat = -0.5 * Cp * utils.celsius_to_kelvin( temp_soil - temp_air) # 0.5 is gH from Bailey 2016 AFM 218-219:146-160 energy_balance = shortwave_abs + longwave_net + latent_heat + sensible_heat return energy_balance t_soil0 = utils.kelvin_to_celsius( optimize.newton_krylov(_SoilEnergyX, utils.celsius_to_kelvin(temp_soil))) soil_nodes.Tsoil = t_soil0 return t_soil0
def solves(): t0 = time.process_time() sol = newton_krylov(system,ainits,verbose=True,f_tol=1.0e-20,f_rtol=1.0e-10) print(sol) print(energy(sol)) t1 = time.process_time() print("Calculation time =",t1-t0,"seconds") print('\a') return sol
def direct_kinematics(self, theta1, theta2, eq_x0=[0, 0]): self.theta1 = theta1 self.theta2 = theta2 x1 = self.o1[0] + self.l1 * cos(self.theta1) y1 = self.o1[1] + self.l1 * sin(self.theta1) self.c1 = array([x1, y1]) x2 = self.o2[0] - self.l2 * cos(self.theta2) y2 = self.o2[1] + self.l2 * sin(self.theta2) self.c2 = array([x2, y2]) if self.NK_iter is None: sol = newton_krylov(self.crossing_circles_direct, eq_x0) else: sol = newton_krylov(self.crossing_circles_direct, eq_x0, iter=self.NK_iter) self.c3[0] = sol[0] self.c3[1] = sol[1] return self.c3
def Ksolves(): t0 = time.process_time() print("Calculating alphas with newton_krylov method") sol = newton_krylov(system, seeds, verbose=True, f_rtol=1e-10) # print("sol") print("Krylov method \n", sol) # print(energy(sol)) print("Krylov calculation time =", time.process_time() - t0, "seconds") print("\a") return sol
def solve(self, maxiter=2000, toler=1e-10, verbose=0, method='lgmres'): if self.get_unconnected_nodes(): self.status = Status.INVALID_SYSTEM_STATE return x0 = np.array([node.p for node in self.nodes()]) self.map_solution_to_nodes(x0) inner_M = IncompressibleSystem.LinearPreconditioner( len(self.nodes()), self) try: p = opt.newton_krylov(self.residual, x0, verbose=verbose, inner_M=inner_M, f_tol=toler, method=method, maxiter=maxiter, inner_maxiter=1, outer_k=3) except NoConvergence as e: # If iterations fail, restart using zeros try: x0 = np.zeros(len(self.nodes())) self.map_solution_to_nodes(x0) p = opt.newton_krylov(self.residual, x0, verbose=verbose, inner_M=inner_M, f_tol=toler, method=method, maxiter=maxiter) except NoConvergence as e: self.status = Status.NO_CONVERGENCE return except ValueError as e: self.status = Status.NAN_DETECTED self.map_solution_to_nodes(np.zeros(len(self.nodes()))) return self.status = Status.SOLVED self.map_solution_to_nodes(p)
def estimate(self, x0=None): if x0 is None: nvals = self.shape[0]*self.shape[1] x0 = np.zeros([nvals], dtype='complex') for k in range(nvals): x0[k] = np.complex(np.random.randn()*1e-2, np.random.randn()*1e-2) soln = newton_krylov(self.objective, x0, verbose=True) self.final_error = self.objective_lsq(soln) self.U = soln.reshape(self.shape)
def spectral(f_eval, t, y0, S, f_tol=NK_FTOL, y_approx=None, do_print=False, verbose=False): """ This function solves directly the spectral solution (Gauss collocation formulation). That is, this function solves .. math:: y - \\Delta{t}SF(y) = y_0 :param function f_eval: the derivative function :math:`y' = f(t,y)`. :param numpy.ndarray t: the time nodes over a time step :math:`\\Delta{t}` :param numpy.ndarray y0: the initial solutions length, size of the problem :param numpy.ndarray S: the spectral integration matrix :math:`S` :param float f_tol: the relative tolerance of the Newton-Krylov solver :param numpy.ndarray y_approx: the initial guess for the Newton-Krylov solver :param bool verbose: a flag for the built-in Newton-Krylov solver :return: the spectral solution :rtype: numpy.ndarray """ # start timing start = time.time() # the number of time nodes n_nodes = S.shape[1] # copy the initial condition [n_nodes x m] y0_vec = np.vstack([y0 for _ in range(n_nodes)]) # solve H(y) = y - SF(y) -y0_vec = 0 H = lambda y: spectral_root_finder(f_eval, t, y, y0_vec, S) # get the solution if y_approx is None: y_approx = y0_vec y = newton_krylov(H, y_approx, f_rtol=f_tol, verbose=verbose) #y = newton_krylov(H, y_approx, f_tol=f_tol, verbose=verbose) #y = root(H, y_approx, tol=f_tol, method='krylov').x #y = anderson(H, y_approx) # end timing end = time.time() if do_print: print_elapsed_time(start, end) return y
def solver(fobj, x0, lb=None, ub=None, options={}, method="lmmcp", jac="default", verbose=False): in_shape = x0.shape ffobj = lambda x: fobj(x.reshape(in_shape)).flatten() if not isinstance(jac, str): pp = np.prod(in_shape) def Dffobj(t): tt = t.reshape(in_shape) dval = jac(tt) return dval.reshape((pp, pp)) elif jac == "precise": from numdifftools import Jacobian Dffobj = Jacobian(ffobj) else: Dffobj = MyJacobian(ffobj) if method == "fsolve": import scipy.optimize as optimize factor = options.get("factor") factor = factor if factor else 1 [sol, infodict, ier, msg] = optimize.fsolve( ffobj, x0.flatten(), fprime=Dffobj, factor=factor, full_output=True, xtol=1e-10, epsfcn=1e-9 ) if ier != 1: print msg elif method == "anderson": import scipy.optimize as optimize sol = optimize.anderson(ffobj, x0.flatten()) elif method == "newton_krylov": import scipy.optimize as optimize sol = optimize.newton_krylov(ffobj, x0.flatten()) elif method == "lmmcp": from dolo.numeric.extern.lmmcp import lmmcp, Big if lb == None: lb = -Big * np.ones(len(x0.flatten())) else: lb = lb.flatten() if ub == None: ub = Big * np.ones(len(x0.flatten())) else: ub = ub.flatten() sol = lmmcp(ffobj, Dffobj, x0.flatten(), lb, ub, verbose=verbose, options=options) return sol.reshape(in_shape)
def solver(F, xin, f_tol): """ A function to solve F(x) = 0 :param F: The function F(x) = 0 to be solved :param xin: The initialisation of x :param f_tol: The precision of the solution :return: The solution """ x = newton_krylov(F, xin, f_tol=f_tol) return x
def inverse_kinematics(self, c3, eq1_x0=[0, 0], eq2_x0=[0, 0]): self.c3 = array(c3) if self.NK_iter is None: sol1 = newton_krylov(self.crossing_circles_inverse_c1, eq1_x0) else: sol1 = newton_krylov(self.crossing_circles_inverse_c1, eq1_x0, iter=self.NK_iter) self.c1[0] = sol1[0] self.c1[1] = sol1[1] if self.NK_iter is None: sol2 = newton_krylov(self.crossing_circles_inverse_c2, eq2_x0) else: sol2 = newton_krylov(self.crossing_circles_inverse_c2, eq2_x0, iter=self.NK_iter) self.c2[0] = sol2[0] self.c2[1] = sol2[1] self.theta1 = arctan2(self.c1[1] - self.o1[1], self.c1[0] - self.o1[0]) self.theta2 = arctan2(self.c2[1] - self.o2[1], self.c2[0] - self.o2[0]) return self.theta1, self.theta2
def nSG_solve(N, xa, xe, ta, te, dt, func_u0): h = (xe - xa) / (N + 1) x = np.arange(xa + h, xe + h / 2, h) u0 = func_u0(x) print l * dt / 2.0 t = [ta] while (ta < te): u0 = newton_krylov(lambda a: residual(a, u0, h, dt), u0) ta += dt t.append(ta) return u0, x, np.array(t)
def _odeint(func, ys, ts, dt, tmax, time_residual, target_error=None, time_adaptor=None, initialisation_actions=None, actions_after_timestep=None): if initialisation_actions is not None: ys, ts = initialisation_actions(func, ys, ts) # Main timestepping loop # ============================================================ while ts[-1] < tmax: t_np1 = ts[-1] + dt # Fill in the residual for calculating dydt and the previous time # and y values ready for the Newton solver. residual = lambda y_np1: time_residual(func, ts+[t_np1], ys+[y_np1]) # Try to solve the system, using the previous y as an initial # guess. If it fails reduce dt and try again. try: y_np1 = newton_krylov(residual, ys[-1], method='gmres') except sp.optimize.nonlin.NoConvergence: dt = scale_timestep(dt, None, None, None, scaling_function=failed_timestep_scaling) sys.stderr.write("Failed to converge, reducing time step.") continue # Execute any post-step actions requested (e.g. renormalisation, # simplified mid-point method update). if actions_after_timestep is not None: new_t_np1, new_y_np1 = actions_after_timestep( ts+[t_np1], ys+[y_np1]) # Note: we store the results in new variables so that we can # easily discard this step if it fails. else: new_t_np1, new_y_np1 = t_np1, y_np1 # Calculate the next value of dt if needed if time_adaptor is not None: try: dt = time_adaptor(ts+[new_t_np1], ys+[new_y_np1], target_error) # If the scaling factor is too small then don't store this # timestep, instead repeat it with the new step size. except FailedTimestepError, exception_data: dt = exception_data.new_dt continue # Update results storage (don't do this earlier in case the time # step fails). ys.append(new_y_np1) ts.append(new_t_np1)
def find_servo_angle(servo): """ Finds a servo angle via numerical soloution of inverse kinematic equations :param servo: which servo to solve :returns: servo angle in radians """ def servo_angle_inverse_kinematic_equations(alpha): equations = ( # close loop x (-1 * (transformed_platform_attatchment_points[servo])[0]) + (self.base_attatchment_points_bcs[servo])[0] - (self.servo_arm_length * np.sin(alpha) * np.sin(self.servo_pitch_angle) * np.cos(self.servo_angles[servo])) - (self.servo_arm_length * np.cos(alpha) * np.sin(self.servo_angles[servo])), # close loop y (-1 * (transformed_platform_attatchment_points[servo])[1]) + (self.base_attatchment_points_bcs[servo])[1] - (self.servo_arm_length * np.sin(alpha) * np.sin(self.servo_pitch_angle) * np.sin(self.servo_angles[servo])) + (self.servo_arm_length * np.cos(alpha) * np.cos(self.servo_angles[servo])), # close loop z (-1 * (transformed_platform_attatchment_points[servo])[2]) + (self.base_attatchment_points_bcs[servo])[2] + (self.servo_arm_length * np.sin(alpha) * np.cos(self.servo_pitch_angle)), # second arm length ) constraint = self.coupler_length**2 - equations[ 0]**2 - equations[1]**2 - equations[2]**2 return constraint if (self.servo_odd_even[servo] == -1): init_guess = np.pi else: init_guess = 0 alpha = newton_krylov(servo_angle_inverse_kinematic_equations, [init_guess])[0] #alpha = np.mod(alpha, 2 * np.pi) if (alpha < 0): alpha += 2 * np.pi return alpha
def solve(self): x_fp = newton_krylov(self.rootOperator, self.x_0, maxiter=self.numberOfIterations, verbose=0, x_rtol=self.convergenceCriterion, method='lgmres', callback=self.iterationCounter) print "scipy Newton Krylov converged after", self.iterationStep, "steps" #As a side effect, we calculate other intersting physical quantities based on the found fixpoint solution self.derivePhysicalQuantitiesFromFixpoint(x_fp) #Reset iteration counter in case solve is called various times (and class is not re-instantiated) self.iterationStep = 0
def solve_stat2(s, phi_ext, a_in, b_in, p0, f1, fp): Np = np.abs(p0)**2 omega_1 = 2*np.pi*f1 omega_2 = 2*np.pi*(fp-f1) freq, k, A, chi = s.f_k_A_chi(phi_ext) kappas = s.coupling_rates(phi_ext) omega_a = 2*pi*(freq[1] - A[1] - (chi[0, 1] + chi[2, 1] + chi[3, 1])/2 - chi[3, 1]*Np) omega_b = 2*pi*(freq[2] - A[2] - (chi[0, 2] + chi[1, 2] + chi[3, 2])/2 - chi[3, 2]*Np) delta_1, delta_2 = omega_1-omega_a, omega_2 - omega_b chim = s.three_waves_term(phi_ext) vect0 = np.array([np.real(a_in), np.imag(a_in), np.real(b_in), np.imag(b_in)]) a_inr = np.real(a_in) a_ini = np.imag(a_in) b_inr = np.real(b_in) b_ini = np.imag(b_in) def optimizer(vect): a2 = vect[0]**2 + vect[1]**2 b2 = vect[2]**2 + vect[3]**2 res = np.array([-(omega_1 - omega_a - A[1]/2*a2)*vect[1] - chim*p0*vect[3] - kappas[1]/2*vect[0] + np.sqrt(kappas[1])*a_inr, +(omega_1 - omega_a - A[1]/2*a2)*vect[0] - chim*p0*vect[2] - kappas[1]/2*vect[1] + np.sqrt(kappas[1])*a_ini, -(omega_2 - omega_b - A[2]/2*b2)*vect[3] - chim*p0*vect[1] - kappas[2]/2*vect[2] + np.sqrt(kappas[2])*b_inr, +(omega_2 - omega_b - A[2]/2*b2)*vect[2] - chim*p0*vect[0] - kappas[2]/2*vect[3] + np.sqrt(kappas[2])*b_ini]) return res sol = newton_krylov(optimizer, vect0/np.sqrt(kappas[1])) #jac = jaco(p0, delta_1, delta_2, A[1], A[2], chim, kappas[1], kappas[2], a_inr, a_ini, b_inr, b_ini)).x a_stat = sol[0] + 1j * sol[1] return (-a_in + np.sqrt(kappas[1])*a_stat)/a_in
def fit(self, **kwargs): """ Attempts to find the root of the residual of the differential equation for rho at all z, given the initial guess self.rho0 Uses a Newton's method with the Krylov approximation for the Jacobian (see scipy.optimize.newton_krylov) Parameters ---------- **kwargs : keyword arguments Additional arguments passed to the root finder [see scipy.optimize.newton_krylov] Returns ------- rho : array Dimensionless density, saves it to self.rho """ # Set up the default options options = {'maxiter': 150, 'verbose': False} for k, v in kwargs.iteritems(): options[k] = v # initial guess rho0 = self.rho0 # Find root try: rho = newton_krylov(self.residual, rho0, **options) except NoConvergence as err: # Assume it didn't converge because f_tol was too strict # Read exception print 'Didnt converge' rho = err.args[0] rho[rho < 0] = 0 # Normalize rho if self.rescale_rho: rho = self._rescale(rho) self.rho = rho self._setup_results()
def complex_fsolve(fun, psi0, **kwargs): """ Wrapper to solve complex-valued nonlinear equations using newton_krylov. (Workaround for a bug in scipy < 0.11) """ m, n = psi0.shape def real_fun(x): out = fun(x[:, :n] + 1j*x[:, n:]) return np.hstack([out.real, out.imag]) c_out = so.newton_krylov(real_fun, np.hstack([psi0.real, psi0.imag]), **kwargs) return c_out[:, :n] + 1j*c_out[:, n:]
def single_stat_solve(df, metric, tol, guesses): print("Solving Stat", metric) start = time.time() df_temp = df.copy() stat_to_solve = metric # This the stat we're solving for, e.g., 3PT% or rebounds/48 weight = weights[metric] # This is the denominator (all the stats are rate stats), so like 3PA or minutes played. df_temp = format_dataframe(df_temp, metric, metric) if stat_to_solve == "PM_48": bnds = [(0.1, 1.0), (-5000, 5000), (-5000, 5000)] else: bnds = [(0.1, 1.0), (0.001, 5000), (0.001, 5000)] solutions = {} solutions_rmse = {} print("Trying LBFGSB") decay_solve_lmbda = lambda x: decay_solve(x, df_temp, df_temp[stat_to_solve], weight) decay_solution_LBFGSB = newton_krylov(decay_solve_lmbda, guesses, f_tol=tol, method='lgmres') # decay_solution_LBFGSB = minimize(decay_solve, guesses, args=(df_temp, df_temp[stat_to_solve], weight), bounds=bnds, # method="L-BFGS-B", tol=tol) solutions_rmse["LBFGSB"] = decay_solution_LBFGSB.fun solutions["LBFGSB"] = decay_solution_LBFGSB winning_model = max(solutions_rmse.items(), key=operator.itemgetter(1))[0] print("Best model is : " + winning_model) decay_solution = solutions[winning_model] rmse = (decay_solution.fun / df_temp[weights[metric]].sum()) ** 0.5 print("RMSE is " + to_str(rmse)) beta = decay_solution.x[0] default_den = decay_solution.x[1] default_num = decay_solution.x[2] df_proj = df.copy() df_proj["denom_increment"] = df_temp["denom_increment"] df_proj["num_increment"] = df_temp["num_increment"] df_proj["x" + stat_to_solve] = df_proj.groupby('PLAYER_ID').apply(decay_method_rd, beta, default_den, default_num).reset_index(level=0, drop=True) regression_results = {} sol = [beta, default_den, default_num, decay_solution.fun, decay_solution.success, winning_model] regression_results[stat_to_solve] = sol regression_results_temp = pd.DataFrame.from_dict(regression_results, orient='index', columns=['beta', 'regressWeight', 'regressValue', 'square_error', 'success', 'model']) return regression_results_temp, df_proj["x" + stat_to_solve]
def solve_const_vert_Force(self): from scipy.optimize import newton_krylov # constants: c0 = 0.010 # const profile drag c2 = 0.01 # c2 * alpha**2 + c0 = cDpr cDpi = 0.01 # drag cooefficient of pilot rho = 1.2 mass = 90 g = 9.81 area = self.parametric_glider.shape.area cDl = self.obj.GliderInstance.lineset.get_normalized_drag() / area * 2 print(cDl) alpha = self.alpha cL = self.cL cDi = self.cDi cD_ges = (cDi + np.ones_like(alpha) * (cDpi + cDl + c0) + c2 * cL**2) def minimize(phi): return np.arctan(cD_ges / cL) - self.alpha + phi def gz(): return cL / cD_ges def vel(phi): return np.sqrt(2 * mass * g * np.cos(alpha - phi) / cL / rho / area) def find_zeros(x, y): sign = np.sign(y[0]) i = 1 while i < len(y): if sign != np.sign(y[i]): return x[i - 1] + (x[i - 1] - x[i]) * y[i - 1] / (y[i] - y[i - 1]) i += 1 if i > len(x): return phi = newton_krylov(minimize, np.ones_like(self.alpha)) a_p = [find_zeros(vel(phi), phi), find_zeros(gz(), phi)] canvas = MplCanvas() canvas.plot(vel(phi), gz()) canvas.plot(a_p[0], a_p[1], marker='o') canvas.plot() canvas.axes.grid() canvas.draw() canvas.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint) canvas.show()
def star_states_stiff(QL, QR, dt, MPL, MPR): PL = State(QL, MPL) PR = State(QR, MPR) x0 = zeros(42) x0[:21] = concatenate([QL, PL.Σ()[0], [PL.q()[0]]]) x0[21:] = concatenate([QR, PR.Σ()[0], [PR.q()[0]]]) def obj(x): return star_stepper_obj(x, QL, QR, dt, MPL, MPR) ret = newton_krylov(obj, x0).reshape([2, 21]) return ret[0, :17], ret[1, :17]
def _compute_increments(self, y, t, h, *args): """Computes the increments of one RK step.""" nu = self.rk_matrix.shape[0] increments = zeros((self.initial_value.size,nu)) for i in xrange(nu): increment = dot(increments[:,0:i], self.rk_matrix[i,0:i]) def func(x): arg1 = t + h * self.rk_nodes[i] arg2 = y + h * increment + h * self.rk_matrix[i,i] * x return self.function(arg1, arg2, *args) - x increments[:,i] = newton_krylov(func, y, method = 'gmres') return increments
def solve(self): """ solve a Poisson equation""" self.count = 0 self.sol = newton_krylov(self.poisson, self.guess, method='lgmres', verbose=1, x_tol=self.x_tol, maxiter=20, f_tol=self.f_tol, inner_M=self.M) # set initial guess for next iteration in C-V self.guess = self.sol # add boundaries self.sol = np.insert(self.sol, 0, self.V0) self.sol = np.append(self.sol, 0) self.F = (self.sol[0]-self.sol[1])/(self.z[0]-self.z[1]) self.nss = self.F*self.eps[0]/q0/1e4 self.Q = self.F*self.eps[0]/1e-2
def solve_const_vert_Force(self): from scipy.optimize import newton_krylov # constants: c0 = 0.010 # const profile drag c2 = 0.01 # c2 * alpha**2 + c0 = cDpr cDpi = 0.01 # drag cooefficient of pilot rho = 1.2 mass = 90 g = 9.81 area = self.ParametricGlider.shape.area cDl = self.obj.GliderInstance.lineset.get_normalized_drag() / area * 2 print(cDl) alpha = self.alpha cL = self.cL cDi = self.cDi cD_ges = (cDi + np.ones_like(alpha) * (cDpi + cDl + c0) + c2 * cL**2) def minimize(phi): return np.arctan(cD_ges / cL) - self.alpha + phi def gz(): return cL / cD_ges def vel(phi): return np.sqrt(2 * mass * g * np.cos(alpha - phi) / cL / rho / area) def find_zeros(x, y): sign = np.sign(y[0]) i = 1 while i < len(y): if sign != np.sign(y[i]): return x[i-1] + (x[i-1] - x[i]) * y[i-1] / (y[i] - y[i-1]) i += 1 if i > len(x): return phi = newton_krylov(minimize, np.ones_like(self.alpha)) a_p = [find_zeros(vel(phi), phi), find_zeros(gz(), phi)] canvas = MplCanvas() canvas.plot(vel(phi), gz()) canvas.plot(a_p[0], a_p[1], marker="o") canvas.plot() canvas.axes.grid() canvas.draw() canvas.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint) canvas.show()
def _compute_increments(self, y, t, h, *args): """Computes the increments of one RK step.""" nu = self.rk_matrix.shape[0] n = self.initial_value.size def func(x): stacked = zeros((n * nu)) for i in range(nu): pre_i = dot(x.reshape((nu, n)).T[:,0:i], self.rk_matrix[i,0:i]) post_i = dot(x.reshape((nu, n)).T[:,i+1:nu], self.rk_matrix[i,i+1:nu]) arg1 = t + h * self.rk_nodes[i] arg2 = y + h * (pre_i + post_i + self.rk_matrix[i,i] * x[n * i:n * (i + 1)]) stacked[n * i:n * (i + 1)] = self.function(arg1, arg2, *args) - x[n * i:n * (i + 1)] return stacked return newton_krylov(func, tile(y, nu), method = 'gmres').reshape((nu, n)).T
def get_corr_pred(self, eps, d_eps, sig, t_n, t_n1, alpha, q, kappa): # g = lambda k: 0.8 - 0.8 * np.exp(-k) # g = lambda k: 1. / (1 + np.exp(-2 * k + 6.)) n_e, n_ip, n_s = eps.shape D = np.zeros((n_e, n_ip, 3, 3)) D[:, :, 0, 0] = self.E_m D[:, :, 2, 2] = self.E_f sig_trial = sig[:, :, 1] / (1 - self.g(kappa)) + self.E_b * d_eps[:, :, 1] xi_trial = sig_trial - q f_trial = abs(xi_trial) - (self.sigma_y + self.A(alpha)) # f_trial = abs(xi_trial) - (self.sigma_y + self.K_bar * alpha) elas = f_trial <= 1e-8 plas = f_trial > 1e-8 d_sig = np.einsum('...st,...t->...s', D, d_eps) sig += d_sig f_n1 = lambda dgamma: (f_trial - self.E_b * dgamma - self.A( alpha + dgamma) + self.A(alpha)) * plas # try: d_gamma = newton_krylov(f_n1, np.zeros_like(f_trial)) d_gamma = d_gamma * plas # except: # print alpha # print self.sigma_y + self.A(alpha) # sys.exit() # Q = 0.1 # a = Q * self.E_b # b = 2 * alpha * Q - 2 * self.E_b # d_gamma = (-b + np.sqrt(b ** 2 - 4 * a * f_trial)) / 2 * a * plas # d_gamma = f_trial / (self.E_b + self.K_bar + self.H_bar) * plas alpha += d_gamma kappa += d_gamma q += d_gamma * self.H_bar * np.sign(xi_trial) w = self.g(kappa) sig_e = sig_trial - d_gamma * self.E_b * np.sign(xi_trial) sig[:, :, 1] = (1 - w) * sig_e aAaa = derivative(self.A, alpha, dx=1e-6) E_p = -np.sign(xi_trial) * self.E_b / (self.E_b + aAaa) * derivative(self.g, kappa, dx=1e-6) * sig_e \ + (1 - w) * self.E_b * aAaa / (self.E_b + aAaa) D[:, :, 1, 1] = (1 - w) * self.E_b * elas + E_p * plas return sig, D, alpha, q, kappa
def rn2rx(distpair_type: List, param1: List, param2: List, rnpair: float ) -> float: """ transforms value rn in a correlation matrix to values rx Parameters ---------- distpair_type : List a list containing parameter 1 and parameter 2's distribution type param1 : List a list containing statistical information about parameter 1 param2 : List a list containing statistical information about parameter 2 rnpair : float value containing rn from the correlation matrix Returns ------- rx : float the transformed rn value References ---------- .. [1] Razavi, S., & Gupta, H. V. (2016). A new framework for comprehensive, robust, and efficient global sensitivity analysis: 1. Theory. Water Resources Research, 52(1), 423-439. doi: 10.1002/2015WR017558 .. [2] Razavi, S., & Gupta, H. V. (2016). A new framework for comprehensive, robust, and efficient global sensitivity analysis: 1. Application. Water Resources Research, 52(1), 423-439. doi: 10.1002/2015WR017559 .. [3] Razavi, S., & Do, C. N. (2020). Correlation Effects? A Major but Often Neglected Component in Sensitivity and Uncertainty Analysis. Water Resources Research, 56(3). doi: /10.1029/2019WR025436 """ fun = lambda r: (rnpair - rx2rn(distpair_type, param1, param2, r)) # try to find point x where fun(x) = 0 try: rx = newton_krylov(F=fun, xin=rnpair, x_tol=1e-5) except: print("Function could not converge, fictive matrix was not computed") rx = rnpair return rx
def solve(reg, d, Jp): """Solve for the diffusion coefficient using non-linear solvers reg = Two region objects in a list d = Length between regions in cm Jp = Left boundary condition current """ phi0m, phi0p = reg[0].flx, reg[1].flx phi1m, phi1p = reg[0].rJ, reg[1].rJ n = phi0m.shape[0] #@PrintRes def residual(D): """Returns how close we are to convergence in each variable D = Two dimensional diffusion coefficient matrix. First column is left region, second is right region. """ Dm, Dp = np.diag(D[:n]), np.diag(D[n:]) logger.debug('Left region diffusion coefficient:\n%s', Dm) logger.debug('Right region diffusion coefficient:\n%s', Dp) Up = sqrtm(diag_inv(Dp).dot(reg[1].sigA)) Um = sqrtm(diag_inv(Dm).dot(reg[0].sigA)) Upi = np.linalg.inv(Up) Umi = np.linalg.inv(Um) logger.debug('Square root matrix error, left region:\n%s', Um.dot(Um) - diag_inv(Dm).dot(reg[0].sigA)) logger.debug('Square root matrix error, right region:\n%s', Up.dot(Up) - diag_inv(Dp).dot(reg[1].sigA)) Amm, Amp, Ap, exU, exUmm, exUmp = BCsolve(Up, Um, Dp, Dm, Jp, d) rm = 3.0 * Dm.dot(phi0m) - Dm.dot(d * exU.dot(Ap)) - phi1m rp = 3.0 * Dp.dot(phi0p) + Dp.dot(d * exU.dot(Ap)) - phi1p #rm = (3.0*Dm.dot( Umi.dot( exUmp.dot(Amp) - exUmm.dot(Amm) - Amp + Amm ) ) # - Dm.dot(d*exU.dot(Ap)) - phi1m) #rp = 3.0*Dp.dot( Upi.dot( exU.dot(Ap) ) ) + Dp.dot(d*exU.dot(Ap)) - phi1p return np.concatenate((rm, rp)) #Initial guess is phi1 / (3.0 * phi0) guess = np.concatenate( (np.divide(phi1m, phi0m) / 3.0, np.divide(phi1p, phi0p) / 3.0)) logger.info('starting nonlinear solver') sol = newton_krylov(residual, guess, method='lgmres', verbose=True) return sol
def get_alpha_beta(x0, y0): def F(P): Alpha = P[0] Beta = P[1] #x0 = 0.45 #y0 = 0.35 #X = Alpha**2 + Beta**2 - x0 #Y = Alpha**2 - Beta**2 - y0 #x = Alpha / (Alpha + Beta) #series = 1 / (1 + get_series(Alpha, Beta, x, total_it, 1)) #print series # approximate so that X and Y are zeros #X = (x**Alpha) * ((1 - x)**Beta) / (Alpha * beta_function(Alpha, Beta)) * series - x0 #Y = (x**(Alpha + 1)) * ((1 - x)**Beta) / ((Alpha + 1) * beta_function((Alpha + 1), Beta)) * series - y0 #X = ((Alpha/(Alpha+Beta))**Alpha) * ((1 - (Alpha/(Alpha+Beta)))**Beta) / (Alpha * beta_function(Alpha, Beta)) * (1 / (1 + get_series(Alpha, Beta, Alpha/(Alpha+Beta), total_it, 1))) - x0 #Y = ((Alpha/(Alpha+Beta))**(Alpha + 1)) * ((1 - (Alpha/(Alpha+Beta)))**Beta) / ((Alpha + 1) * beta_function((Alpha + 1), Beta)) * (1 / (1 + get_series(Alpha, Beta, Alpha/(Alpha+Beta), total_it, 1))) - y0 X = beta.cdf(float(Alpha) / (Alpha + Beta), Alpha, Beta) - x0 Y = beta.cdf(float(Alpha) / (Alpha + Beta), Alpha + 1, Beta) - y0 return [X, Y] guess = [10, 5] max_n = 1000 n = 1 while n < max_n: try: sol = newton_krylov(F, guess, method='lgmres', verbose=0, rdiff=0.1, maxiter=50) break except NoConvergence as e: guess = np.random.rand(2) * 10 + 0.1 print(guess) except ValueError as e: guess = np.random.rand(2) * 10 + 0.1 print(guess) n = n + 1 if n == max_n: print( "Error: the chosen value is not within the computation range. Please re-choose. Suggested value: 0.3 <= x, y <= 0.5, and x >= y" ) return [0, 0] else: return sol
def do_one_step(self, t, X0): callback = None if self.diagnostics: callback = self.diagnostics_logger def optimization_function(X1): return X1 - X0 - self.h*vortex_rhs(self.gamma,(X0+X1)/2,self.sigma) X1 = newton_krylov(optimization_function, X0, f_tol=1e-14, callback=callback) self.diagnostics_logger.store() # Project down to the sphere for k in xrange(0, X1.shape[0]): X1[k, :] /= LA.norm(X1[k, :]) return X1
def eqmstate(self, rwa = False): """ Approximates the equilibrium steady state of the Lindblad dynamics by evaluating the fixed point of the BBGKY dynamical equations. This is done by solving d\rho/dt = L(t)->\rho = 0 using the Newton-Krylov method. Usage: d = BBGKY_System_Eqm(Paramdata, MPI_COMMUNICATOR) eqm_state = d.eqmstate(rwa = False) Optional Parameters: rwa = Boolean. If set, then performs the dynamics in the rotated frame i.e. the instantaneous rest frame of the drive. Default False. Return value: Numpy array. Equilibrium state represented by the quantities np.array([sx, sy, sz, gxx, gxy, gxz, gyx, gyy, gyz, gzx, gzy, gzz]) where s's are blocks of spins of size N = Paramdata.latsize and the g's are NXN matrices of s-s connected correlations flattened in row major order. """ self.rwa = rwa N = self.latsize #Only have root do this, then broadcast if self.comm.rank == root: a = np.zeros((3,N)) a[2] = np.ones(N) c = np.zeros((3, 3, N, N)) init_state = np.concatenate((a.flatten(), c.flatten())) fixed_point = newton_krylov(\ lambda s:lindblad_bbgky_pywrap(\ s, ss_final_time, self), init_state,\ verbose=self.verbose) else: fixed_point = None fixed_point = self.comm.bcast(fixed_point, root=root) return fixed_point
nx, ny = 75, 75 hx, hy = 1./(nx-1), 1./(ny-1) P_left, P_right = 0, 0 P_top, P_bottom = 1, 0 def residual(P): d2x = zeros_like(P) d2y = zeros_like(P) d2x[1:-1] = (P[2:] - 2*P[1:-1] + P[:-2]) / hx/hx d2x[0] = (P[1] - 2*P[0] + P_left)/hx/hx d2x[-1] = (P_right - 2*P[-1] + P[-2])/hx/hx d2y[:,1:-1] = (P[:,2:] - 2*P[:,1:-1] + P[:,:-2])/hy/hy d2y[:,0] = (P[:,1] - 2*P[:,0] + P_bottom)/hy/hy d2y[:,-1] = (P_top - 2*P[:,-1] + P[:,-2])/hy/hy return d2x + d2y - 10*cosh(P).mean()**2 # solve guess = zeros((nx, ny), float) sol = newton_krylov(residual, guess, method='lgmres', verbose=1) print('Residual: %g' % abs(residual(sol)).max()) # visualize import matplotlib.pyplot as plt x, y = mgrid[0:1:(nx*1j), 0:1:(ny*1j)] plt.pcolor(x, y, sol) plt.colorbar() plt.show()
def StandardMap(x,y,L,k,q0,b=30.0,aa=0.0,eps=.3,m =3): print('b: ', b) #aa = -.00 B_0 = 1.0 #in tesla #b = 30 #minor rad R_0 = 90 #major rad #m = 3. #external mode l = 10 #coil width a= 40 beta = 2.0 mu = 1.0 beta_p = beta*(mu+1)/(beta+mu+1) hit_divert = (x>b) inCORE = x<b stopevolve = hit_divert x_new = (stopevolve == 0)*x/(1-aa*np.sin(y)) # q = (q0*(x_new/a)**2) #*(1 -(1 + beta_p * (x_new/a)**2)* # (1.0- (x_new/a)**2)*(a>x_new))**-1 xx = x_new/a nu = 2. q = q0*(xx**2)/(1-(1-xx)**(nu+1)) print('q: ', q.min(),q.max()) y_new = (stopevolve == 0)*(y+ 2*np.pi/q + aa*np.cos(y)) y_new = np.mod(y_new,2*np.pi) # #see "DIFFUSIVE TRANSPORT THROUGH A NONTWIST BARRIER IN TOKAMAKS" #eps = .3 print(m,l,a,R_0,q0,b,eps) C = ((2*m*l*a**2)/(1.0*R_0*q0*b**2))*eps print('C: ', C/eps) #eps is the ration between limited and plasma currents #need to find roots of this thin2g def func(x_out): return (-x_new + x_out +((m*b*C)/(m-1))*((x_out/b)**(m-1) )*np.sin(m*y_new))**2 x_new2 = copy(x_new) #x_new2 = (stopevolve == 0)* (newton_krylov(func,x_new2)) + (stopevolve)*x x_new2 = (stopevolve == 0)* (newton_krylov(func,x_new2,method='bicgstab')) + (stopevolve)*x #print (-x_new + x_new2 +(m*b*C)/(m-1)*((x_new2/b)**(m-1) )*np.sin(m*y_new))**2 y_new2 = (stopevolve == 0)*(y_new - C*(x_new2/b)**(m-2) * np.cos(m*y_new))+ (stopevolve)*y #print 'xchange:', x_new2/x print(x_new2,x) x_new = x_new2 y_new = np.mod(y_new2,2*np.pi) stay_inCORE = (x_new <b) #full_orbit = (new_inSOL & inSOL) == False #can visit SOL,but can't stay full_orbit = (stay_inCORE & inCORE) == True half_orbit = (stay_inCORE & inCORE) == True #ok, you hit the divertor #print new_inSOL + inSOL #q = q0 + x/(2*np.pi) L = L + (stopevolve ==0)*((full_orbit)*q *R_0* 2*np.pi)# + \ #half_orbit *100* 2*q* np.pi) #L = L +(full_orbit)# + .5*half_orbit return x_new,y_new,L
def solve_Nics(k0): Nics = numpy.array([-5]) for i in range(200): Nics = opt.newton_krylov(lambda N : (k0)**2 - 1e+04*fN(N),Nics) return Nics
def _nksolve(sys_func, r0, precision): return newton_krylov(sys_func, r0, x_tol=precision)
DHp = lambda N : +1.3887943864964e-16*N*(1.0*numpy.exp(N**2/2)**1.0 - 1.0)**(-0.5)*numpy.exp(N**2/2)**1.0/(1.0e-5*(1.0*numpy.exp(N**2/2)**1.0 - 1)**1.0 + 1.0e-5)**2 - 5.55517754598561e-21*N*(1.0*numpy.exp(N**2/2)**1.0 - 1.0)**0.5*numpy.exp(N**2/2)**1.0/(1.0e-5*(1.0*numpy.exp(N**2/2)**1.0 - 1)**1.0 + 1.0e-5)**3 n = lambda N : Heavi(N)*np(N) + Heavi(-N)*nm(N) DH = lambda N : Heavi(N)*DHp(N) + Heavi(-N)*DHm(N) f = open('evolve_hk_test_1.dat','w') a0 = 1e-05 n0 = numpy.exp(25) p = 1 k0 = numpy.exp(-25) Nics = numpy.array([-4]) for i in range(200): Nics = opt.newton_krylov(lambda N : (k0)**2 - 1e+04*fN(N),Nics) print 'Nics =', Nics print 'we have Nics' Nshss = numpy.array([5]) for i in range(200): Nshss = opt.newton_krylov(lambda N : (k0)**2 - 1e+06*fN(N),Nshss) print 'Nshss =', Nshss print 'we have Nshss' hk0 = numpy.zeros(1,dtype=complex) hk0.real = (((2.*k0)**(1./2))*A(Nics))**(-1.) Dhk0 = numpy.zeros(1,dtype=complex)
def rho_z(sigma, T, r, settings): """ rho,z = rho_z(...) Calculates rho(z) to maintain hydrostatic equilibrium in a thin disc. Assumes uniform temperature in the disc, and an infinite disc where rho can be treated (locally) as only a function of z. Only calculates for z>=0, since the density is assumed to be symmetric about z=0 The initial guess for rho (a gaussian) only really seems to work for Mstar >> Mdisc. Otherwise the solution can diverge violently. * NUMERICAL CALCULATION OF RHO(Z) * The calculation proceeds using several steps. 1) Make an initial guess for I, the integral of rho from z to inf. This is an error function 2) Modify length scale of the initial guess to minimize the residual for the differential equation governing I. Use this as the new initial guess. 3) Find the root I(z) for the differential equation governing I, with the boundary condition that I(0) = sigma/2 4) Set rho = -dI/dz 5) Find the root rho(z) for the diff. eq. governing rho. 6) In order to satisfy the BC on I, scale rho so that: Integral(rho) = I(0) 7) Repeat (5) and (6) until rho is rescaled by a factor closer to unity than rho_tol Steps 5-7 are done because the solution for I does not seem to satisfy the diff. eq. for rho very well. But doing it this way allows rho to satisfy the surface density profile * Arguments * sigma - The surface density at r __stdout__ T - the temperature at r r - The radius at which rho is being calculated. Should have units settings - ICobj settings (ie, ICobj.settings) * Output * Returns a 1D SimArray (see pynbody) of rho(z) and a 1D SimArray of z, with the same units as ICobj.settings.rho_calc.zmax """ # Parse settings rho_tol = settings.rho_calc.rho_tol nz = settings.rho_calc.nz zmax = settings.rho_calc.zmax m = settings.physical.m M = settings.physical.M # Physical constants kB = SimArray(1.0,'k') G = SimArray(1.0,'G') # Set up default units mass_unit = M.units length_unit = zmax.units r = (r.in_units(length_unit)).copy() # Initial conditions/physical parameters rho_int = 0.5*sigma.in_units(mass_unit/length_unit**2) # Integral of rho from 0 to inf a = (G*M*m/(kB*T)).in_units(length_unit) b = (2*np.pi*G*m/(kB*T)).in_units(length_unit/mass_unit) z0guess = np.sqrt(2*r*r*r/a).in_units(length_unit)# Est. scale height of disk z0_dummy = (2/(b*sigma)).in_units(length_unit) z = np.linspace(0.0,zmax,nz) dz = z[[1]]-z[[0]] # Echo parameters used print '***********************************************' print '* Calculating rho(z)' print '***********************************************' print 'sigma = {0} {1}'.format(sigma,sigma.units) print 'zmax = {0} {1}'.format(zmax,zmax.units) print 'r = {0} {1}'.format(r,r.units) print 'molecular mass = {0} {1}'.format(m,m.units) print 'Star mass = {0} {1}'.format(M,M.units) print 'Temperature = {0} {1}'.format(T,T.units) print '' print 'rho_tol = {0}'.format(rho_tol) print 'nz = {0}'.format(nz) print '***********************************************' print 'a = {0} {1}'.format(a,a.units) print 'b = {0} {1}'.format(b,b.units) print 'z0guess = {0} {1}'.format(z0guess,z0guess.units) print '***********************************************' print 'z0 (from sech^2) = {0} {1}'.format(z0_dummy,z0_dummy.units) # -------------------------------------------------------- # STRIP THE UNITS FROM EVERYTHING!!! # This has to be done because many of the scipy/numpy functions used cannot # handle pynbody units. Before returning z, rho, or anything else, the # Units must be re-introduced # -------------------------------------------------------- rho_int, a, b, z0guess, z0_dummy, z, dz, r, T, sigma \ = isaac.strip_units([rho_int, a, b, z0guess, z0_dummy, z, dz, r, T, sigma]) # -------------------------------------------------------- # Check sigma and T # -------------------------------------------------------- if sigma < 1e-100: warn('Sigma too small. setting rho = 0') rho0 = np.zeros(len(z)) # Set up units rho0 = isaac.set_units(rho0, mass_unit/length_unit**3) z = isaac.set_units(z, length_unit) return rho0, z if T > 1e100: warn('Temperature too large. Setting rho = 0') rho0 = np.zeros(len(z)) # Set up units rho0 = isaac.set_units(rho0, mass_unit/length_unit**3) z = isaac.set_units(z, length_unit) return rho0, z # ------------------------------------------------------------------- # FUNCTION DEFINITIONS # ------------------------------------------------------------------- def dI_dz(I_in): """ Finite difference approximation of dI/dz, assuming I is odd around I(0) """ I = I_in.copy() dI = np.zeros(len(I)) # Fourth order center differencing dI[0] = (-I[2] + 8*I[1] - 7*I[0])/(6*dz) dI[1] = (-I[3] + 8*I[2] - 6*I[0] - I[1])/(12*dz) dI[2:-2] = (-I[4:] + 8*I[3:-1] -8*I[1:-3] + I[0:-4])/(12*dz) # Second order backward differencing for right edge dI[-2:] = (3*I[-2:] -4*I[-3:-1] + I[-4:-2])/(2*dz) return dI def d2I_dz2(I_in): # Finite difference for d2I/dz2 assuming it is 0 at the origin I = I_in.copy() d2I = np.zeros(len(I)) # Boundary condition d2I[0] = 0 # Centered 4th order finite difference d2I[1] = (-I[3] + 16*I[2] - 30*I[1] + 16*I[0] -(2*I[0] - I[1]))/(12*dz**2) d2I[2:-2] = (-I[4:] + 16*I[3:-1] - 30*I[2:-2] + 16*I[1:-3] - I[0:-4])/(12*(dz**2)) # second order backward difference for right edge d2I[-2:] = (-2*I[-2:] + 5*I[-3:-1] -4*I[-4:-2] + I[-5:-3])/dz**2 return d2I def Ires(I_in): """ Calculate the residual for the differential equation governing I, the integral of rho from z to "infinity." """ # DEFINE INITIAL CONDITION: I = I_in.copy() I[0] = rho_int #I[-1] = 0.0 weight = 1.0 res = d2I_dz2(I) + dI_dz(I)*(a*z/((z**2 + r**2)**(1.5)) + 2*b*(I[0] - I)) return weight*res def drho_dz(rho_in): """ Fourth order, centered finite difference for d(rho)/dz, assumes that rho is an even function. The right-hand boundary is done using backward differencing """ rho = rho_in.copy() drho = np.zeros(len(rho)) drho[0] = 0.0 # defined by boundary condition, rho[0] = max(rho) drho[1] = (-rho[3] + 8*rho[2] - 8*rho[0] + rho[1])/(12*dz) drho[2:-2] = (-rho[4:] + 8*rho[3:-1] - 8*rho[1:-3] + rho[0:-4])/(12*dz) drho[-2:] = (3*rho[-2:] - 4*rho[-3:-1] + rho[-4:-2])/(2*dz) return drho def residual(rho_in): """ Estimate d(rho)/dz """ rho = rho_in.copy() # Estimate integral of rho I = np.zeros(len(rho)) I[1:] = nInt.cumtrapz(rho,z) # Estimate residual res = drho_dz(rho) + a*rho*z/((z**2 + r**2)**(1.5)) + 2*b*rho*I return res def erf_res(scale_size): testfct = rho_int*(1 - scipy.special.erf(z/scale_size)) return abs(Ires(testfct)).sum() pass # ------------------------------------------------------------------- # FIND RHO # ------------------------------------------------------------------- maxiter = 40 # Estimate the scale length of the error function z0 = opt.fminbound(erf_res,z0guess/100.0,5.0*z0guess) print 'Length scale guess: {0} {1}'.format(z0guess, length_unit) print 'Final length scale: {0} {1}'.format(z0, length_unit) # Begin by finding I, the integral of rho (from z to inf) # Assuming rho is gaussian, I is an error function guess = rho_int*(1 - scipy.special.erf(z/z0)) # Find the root of the differential equation for I f_tol = rho_int * 6e-6 try: Isol = opt.newton_krylov(Ires,guess,maxiter=maxiter,f_tol=f_tol) except NoConvergence: # Assume it didn't converge because f_tol was too strict # Read exception xepshun = sys.exc_info() # Extract rho from the exception Isol = xepshun[1][0] # rho is the negative derivative rho0 = -dI_dz(Isol) # Now apply the diff eq on rho for n in range(maxiter): print 'Iteration {0}'.format(n+1) f_tol = rho0.max() * 6e-6 try: rho0 = opt.newton_krylov(residual,rho0,maxiter=maxiter, f_tol=f_tol) except: # Assume it didn't converge because f_tol was too strict # Read exception xepshun = sys.exc_info() # Extract rho from the exception rho0 = xepshun[1][0] rho_scale = rho_int/nInt.cumtrapz(rho0,z)[-1] print 'Scaling rho by {0}'.format(rho_scale) rho0 = rho0*rho_scale if abs(1-rho_scale) < rho_tol - 1: break if n >= maxiter: print 'Warning: solution to rho did not converge for r = {0}'.format(r) # Re-introduce units rho0 = isaac.set_units(rho0, mass_unit/length_unit**3) z = isaac.set_units(z, length_unit) return SimArray(rho0,'Msol au**-3'), SimArray(z,'au')
def solver(self): def residual(self, variables): """Summary Args: variables (TYPE): Description Returns: TYPE: Description """ # All 5 unknowns (f, u, v, g, p, b, e) = variables deta = self.deta gsi = self.gsi nx = self.nx alpha = 3.0 / 2.0 * (gsi[nx] + gsi[nx-1]) / (gsi[nx] - gsi[nx-1]) if self.turbulent: self.turbulence() # array slicing for indices j and n # index j means [1:, ] in first array column # index j-1 means [:-1, ] in first array column # index n means [, 1] in second array column # index n-1 means [, 0] in second array column # boundary conditions at jet center (symmetry) f[0, :] = 0.0 v[0, :] = 0.0 p[0, :] = 0.0 # boundary conditions at jet outer boundary (ambient) u[-1, :] = 0.0 g[-1, :] = 0.0 # ODE: f' = u eq1 = 1.0/deta*(f[1:, 1] - f[:-1, 1]) - 0.5*(u[2:, 1] + u[1:-1, 1]) # ODE: u' = v eq2 = 1.0/deta*(u[1:, 1] - u[:-1, 1]) - 0.5*(v[2:, 1] + v[1:-1, 1]) # ODE: g' = p eq3 = 1.0/deta*(g[1:, 1] - g[:-1, 1]) - 0.5*(p[2:, 1] + p[1:-1, 1]) # PDE: Momentum eq4 = 1.0/deta * (b[1:, 1]*v[1:, 1] - b[:-1, 1]*v[:-1, 1]) + \ (1.0-alpha)*0.5*(u[1:, 1]**2 - u[:-1, 1]**2) + \ (1.0+alpha)*0.5*(f[1:, 1]*v[1:, 1] - f[:-1, 1]*v[:-1, 1]) + \ alpha*0.25*((v[1:, 0]+v[:-1, 0])*(f[1:, 1]+f[:-1, 1]) - (f[1:, 0]+f[:-1, 0])*(v[1:, 1]+v[:-1, 1])) + \ 1.0/deta * (b[1:, 0]*v[1:, 0] - b[:-1, 0]*v[:-1, 0]) + \ (1.0+alpha)*0.5*(u[1:, 0]**2 - u[:-1, 0]**2) + \ (1.0-alpha)*0.5*(f[1:, 0]*v[1:, 0] - f[:-1, 0]*v[:-1, 0]) # PDE: Energy eq5 = 1.0/deta * (e[1:, 1]*p[1:, 1] - e[:-1, 1]*p[:-1, 1]) + \ (1.0+alpha)*0.5*(f[1:, 1]*p[1:, 1] - f[:-1, 1]*p[:-1, 1]) - \ alpha*(0.5*(u[1:, 1]*g[1:, 1] + u[:-1, 1]*g[:-1, 1]) + 0.25*((u[1:, 0]+u[:-1, 0])*(g[1:, 1]+g[:-1, 1]) - (g[1:, 0]+g[:-1, 0])*(u[1:, 1]+u[:-1, 1]) + (p[1:, 1]+p[:-1, 1])*(f[1:, 0]+f[:-1, 0]) - (p[1:, 0]+p[:-1, 0])*(f[1:, 1]+f[:-1, 1]))) + \ 1.0/deta * (e[1:, 0]*p[1:, 0] - e[:-1, 0]*p[:-1, 0]) + \ (1.0-alpha)*0.5*(f[1:, 0]*p[1:, 0] - f[:-1, 0]*p[:-1, 0]) + \ alpha*0.5*(u[1:, 0]*u[1:, 0] - g[:-1, 0]*g[:-1, 0]) return [eq1, eq2, eq3, eq4, eq5] def log_iterations(x, f): """This function is called on every iteration as callback(x, f) where x is the current solution and f the corresponding residual. Args: x (TYPE): Description f (TYPE): Description Returns: TYPE: Description """ # current solution print x # current residual print f # run solver solution = opt.newton_krylov(residual, guess, method='lgmres', verbose=1, callback=log_iterations) return solution
(phi_wsa_v,theta_wsa_v,phi,theta,br1,v_wsa,n_wsa,T_wsa)=wsa.read('/Users/merkivg1/work/LFM-helio_2.0/WSA/fits/2010_2008_WSA_ADAPT/vel_201001032300R001_ans.fits',False) omega=2*pi/27.27 phi_prime=phi-omega*1. ind0=where(phi_prime>0)[0][0] phi_prime=roll(phi_prime,-ind0) phi_prime[phi_prime<0]+=2*pi import scipy from scipy.interpolate import interpolate br1_rolled=roll(br1,-ind0,axis=1) fbi = scipy.interpolate.RectBivariateSpline(theta,phi,br1_rolled,kx=1,ky=1) br1_new=fbi(theta,phi_prime) import poisson pois = poisson.poisson(theta,phi) pois.setRHS(br1_new - br0) guess=zeros_like(br1_new) sol = newton_krylov(pois.residual,guess, method='lgmres', verbose=1,f_rtol=1.e-6) #iter=100 print('Residual: %g' % abs(pois.residual(sol)).max()) figure();pcolormesh(sol);colorbar();title('Solution') # check curl Etheta = -1/sin(theta[:,None])*diff(sol,axis=1) Ephi = diff(sol,axis=0) figure();pcolormesh(Etheta);colorbar();title('Etheta') figure();pcolormesh(Ephi);colorbar();title('Ephi')
def MF_curves_temp(R_gen, n, b_or_lg_b_min, lg_b_max=None, steps=None, selected=None, nasymp=None, debug=False, usederiv=False, maxsteps=40, M_sw_solvers=500): ''' Numerically solves the MF equations of the many body master equation generated by the rate matrix R R - rate matrix lg_n_min - logarithm of minimum filling lg_n_max - logarithm of maximum filling ''' if not lg_b_max==None and not steps==None: beta = np.logspace(b_or_lg_b_min, lg_b_max, steps, endpoint=True) # filling factors else: beta = b_or_lg_b_min R = R_gen(beta[0]) M = np.shape(R)[0] curves = np.zeros((len(beta), M)) # matrix for numerical results if debug: print "Beginne Suchalgorithmus..." for i in xrange(len(beta)): if debug: print "M =", M, ",", i *100 /float(len(beta)), "%" red_state = 0 if i == 0: init = np.delete(np.ones(M) * n, red_state) else: if usederiv and i>1: deriv = (curves[i-1] - curves[i-2]) / (beta[i-1]-beta[i-2]) n_t = curves[i-1] + deriv * (beta[i]-beta[i-1]) #n_t *= n / np.sum(n_t) init = np.delete(n_t, red_state) else: init = beta[i-1] / beta[i] * init R = R_gen(beta[i]) print np.sum(R == 0) A = R - np.transpose(R) Rsum = R.sum(axis=0) if M < M_sw_solvers: init, info, ier, msg = fsolve(MF_equations_withA, init, args=(R, A, Rsum, M * n, red_state), fprime=MF_jac_withA, full_output=True) else: args=(R, M * n, red_state) func = lambda x: MF_equations(x, *args) try: init = newton_krylov(func, init, verbose=1, maxiter=500) ier = 1 except: ier = 0 n_t = n_bar(init, M * n, red_state) if (np.any(n_t < 0.) or ier != 1) and not i==0: print "Fehler: Erhoehe Schrittweite" steps = 4 mysuc = False bet_old = beta[i-1] oldinit = np.delete(curves[i-1], red_state) deriv = None while not mysuc: init = oldinit for bet_inter in np.logspace(np.log10(bet_old), np.log10(beta[i]), steps)[1:]: if steps > maxsteps: print "Erneuter Fehler, gebe auf..." n_t = np.zeros(M) mysuc = True break R = R_gen(bet_inter) if usederiv and deriv != None: init = init + deriv * (bet_inter-bet_old) else: init = bet_old / bet_inter * init if M < M_sw_solvers: init, info, ier, msg = fsolve(MF_equations, init, args=(R, M * n, red_state), fprime=MF_jac, full_output=True) mysuc = True else: args=(R, M * n, red_state) func = lambda x: MF_equations(x, *args) try: init = newton_krylov(func, init, verbose=1, maxiter=200) ier = 1 mysuc = True except: ier = 0 n_t = n_bar(init, M * n, red_state) if np.any(n_t < 0.) or ier != 1: print "Erneuter Fehler, erhoehe weiter Schrittweite..." steps += 4 mysuc = False break if usederiv: deriv = (init - oldinit) / (bet_inter-bet_old) oldinit = init bet_old = bet_inter if np.all(n_t >= 0.): curves[i] = n_t return beta, curves