def solve(self): """ Shoot: compute initial momentum to satisfy BVP by solving nonlinear system """ print("Shoot: Solving with ",self.no_steps, "steps...") sys.stdout.flush() self._init_path() Pin=np.zeros(self.s0) # opt={} opt['xtol']=self.xtol opt['factor']=10 # start=timer() Pout=spo.root(self._objective, np.ravel(Pin), jac=self._Jacobian, options=opt) # if Pout['success']==False: print("Heavy artillery brought in...") sys.stdout.flush() P=Pout['x'].reshape(self.s0) opt['maxiter']=int(1e4) Pout=spo.root(self._objective, np.ravel(P), jac=self._Jacobian, method='lm', options=opt) end=timer() print("Run time %3.1f secs" % (end-start)) # print(Pout['message'], "Success=", Pout['success']) assert Pout['success'] P0=Pout['x'].reshape(self.s0) self.set_path(P0, self.landmarks[0,:,:]) return P0
def update_Psi(self): """Update the policy functions. Calculates S labor decision policy functions, and S-1 capital savings policy functions. Also calculates upper and lower bounds for a feasible region for each ability and age in the model. """ # Make Psi_n_S. for j in range(self.J): for i in range(self.grid_size): grid = self.Grid[-1,j,i] def get_n_S(n): return (self.w*self.e[j]*(self.w*self.e[j]*n+grid*(1+self.r))**-sigma -self.ellip_b*n**(self.ellip_up-1)*(1-n**self.ellip_up)**(1/self.ellip_up-1)) n_S, r = brentq(get_n_S, 0, 1, full_output=1) if r.converged!=1: print 'n_S did not converge!' self.Psi_n[-1,j,i] = n_S for s in range(self.S-2,-1,-1): for j in range(self.J): # Make Psi_n_S lb = -999 for j_ in range(self.J): psi_b = UnivariateSpline(self.Grid[s+1,j_], self.Psi_b[s+1,j_]) psi_n = UnivariateSpline(self.Grid[s+1,j_], self.Psi_n[s+1,j_]) def get_lb(b1): b2 = psi_b(b1) n1 = psi_n(b1) c1 = b1*(1+self.r)+self.w*self.e[j_]*n1-b2 return c1 guess = (-self.w*self.e[j_]*1.+psi_b(0))/(1+self.r) lb_, info, ier, mesg = fsolve(get_lb, guess, full_output=1) lb = np.max([lb,lb_]) if ier!=1: print s, j, j_, 'The lower bound wasn\'t calculated correctly.' self.lb = lb self.b0min = (lb-self.w*self.e[j]*0.)/(1+self.r)+1e-5 self.Grid[s,j] = np.linspace(self.b0min, self.b0max, self.grid_size) ub = self.Grid[s,j]*(1+self.r)+self.w*self.e[j]*1. self.ub = ub for i in range(self.grid_size): obj = lambda x: self.obj(x, self.Grid[s,j,i], s, j, i) jac = lambda x: self.jac(x, self.Grid[s,j,i], s, j, i) # print obj(((lb+ub[i])/2., self.Psi_n[s+1,j,i])) # print jac(((lb+ub[i])/2., self.Psi_n[s+1,j,i])) # print (lb+ub[i])/2, self.lb #TODO Fix feasible region #TODO Check root method for jacobian evaluation sol = root(obj, ((lb+ub[i])/2., self.Psi_n[s+1,j,i]), jac=jac) print sol.fun, sol.x, self.Psi_n[s+1,j,i] (self.Psi_b[s,j,i], self.Psi_n[s,j,i]), ier = sol.x, sol.success # self.Psi[s,j,i], info, ier, mesg = fsolve(obj, (lb+ub[i])/2., full_output=1) if ier!=1: sol = root(obj, ((lb+ub[i])/2., .9999999), jac=jac) print sol.fun, sol.x, self.Psi_n[s+1,j,i] (self.Psi_b[s,j,i], self.Psi_n[s,j,i]), ier = sol.x, sol.success print s, j, i, sol.message
def compute_dy_Z(self): ''' Computes linearization w/ respecto aggregate state. ''' global dZ_Z0 self.dZ_Z = np.eye(nZ) #right now assume nZ =1 def dy_Z(z_i): DFi = self.DF(z_i)[n:,:] df = self.df(z_i) DFhat_Zinv = np.linalg.inv(DFi[:,y] + DFi[:,e].dot(df) + DFi[:,v].dot(Ivy)*self.dZ_Z[0]) return DFhat_Zinv.dot(-DFi[:,Z]),DFhat_Zinv.dot(-DFi[:,Y]) DG = lambda z_i : self.DG(z_i)[nG:,:] def dY_Z(): A,B = lambda z_i : dy_Z(z_i)[0], lambda z_i : dy_Z(z_i)[1] temp1 = self.integrate( lambda z_i: DG(z_i)[:,y].dot(A(z_i)) + DG(z_i)[:,Z] ) temp2 = self.integrate( lambda z_i: DG(z_i)[:,y].dot(B(z_i)) + DG(z_i)[:,Y] ) return np.linalg.solve(temp2,-temp1) def residual(dZ_Z): self.dZ_Z = np.array([dZ_Z]) return (dY_Z()[:nZ]-dZ_Z).flatten() res = root(residual,dZ_Z0) if not res.success or res.x >= 1.: res = root(residual,np.array([1.])) if not res.success or res.x >= 1.: state = np.random.get_state() ni = 0 while True: if rank == 0: dY_Z0 = np.random.randn(nY*nZ) else: dY_Z0 = None dY_Z0 = comm.bcast(dY_Z0) res = root(lambda dY_Z:self.dY_Z_residual(dY_Z.reshape(nY,nZ)).flatten() ,dY_Z0) if res.success and res.x[0] < 1.: break else: ni += 1 if ni>10: raise "Could not find stable dZ_Z" np.random.set_state(state) self.dZ_Z = res.x.reshape(nY,nZ)[:nZ] dZ_Z0 = self.dZ_Z.flatten() else: self.dZ_Z = res.x.reshape(nZ,nZ) dZ_Z0 = res.x.reshape(nZ) #self.dZ_Z = root(residual,0.9*np.ones(1)).x.reshape(nZ,nZ) self.dY_Z = dY_Z() def compute_dy_Z(z_i): A,B = dy_Z(z_i) return A+B.dot(self.dY_Z) self.dy[Z] = dict_fun(compute_dy_Z)
def _get_damage( self ): damage_all = np.array( self.c_mask ) * 1. if self.Ll > 1e6: self.Ll = 1e6 if self.Lr > 1e6: self.Lr = 1e6 # print'w,Lmin,Lmax', self.w, self.Ll, self.Lr if self.w == 0.: damage = np.zeros_like( self.sorted_depsf[self.c_mask] ) self._x_arr = np.hstack( ( np.repeat( self.Ll, len( self.sorted_depsf ) ), 0, np.repeat( self.Lr, len( self.sorted_depsf ) ) ) ) self._epsm_arr = np.array( np.repeat( 1e-6, 1 + 2 * len( self.sorted_depsf ) ) ) self._epsf0_arr = np.repeat( 0, len( self.sorted_depsf ) ) # self.E_mtrx = self._E_mtrx_default() else: ff = t.clock() try: self.set_sfarr_to_defaults() damage = root( self.damage_residuum, damage_all[self.c_mask] * 0.2, method = 'excitingmixing', options = {'maxiter':100} ) # damage = root( self.damage_residuum, np.ones_like( self.sorted_depsf ) * 0.2 , # method = 'excitingmixing', options = {'maxiter':100} ) if np.any( damage.x < 0.0 ) or np.any( damage.x > 1.0 ): raise ValueError damage = damage.x except: print 'fast opt method does not converge: switched to a slower, robust method for this step' damage = root( self.damage_residuum, damage_all[self.c_mask] * 0.2, method = 'krylov' ) damage = damage.x damage_all[self.c_mask] = damage return damage_all
def findPolicies(self,K_): ''' Finds the solution to the policy equation ''' global z0_guess I,S = len(theta),len(P) if not self.PF == None: z0 = self.PF(K_) res = root(lambda z: self.policy_residuals(K_,z),z0) if not res.success: if not z0_guess == None and len(z0) == len(z0_guess): res = root(lambda z: self.policy_residuals(K_,z),z0_guess) if not res.success: return None else: return None z0_guess = res.x return res.x else: z0 = np.hstack((np.ones(2*I*S),np.zeros(2*(I-1)*S+S))) res = root(lambda z: self.policy_residuals_end(K_,z),z0) if not res.success: if not z0_guess == None: res = root(lambda z: self.policy_residuals_end(K_,z),z0_guess) if not res.success: return None else: return None z0_guess = res.x c1,ci,n1,ni,phi,xi,eta = getQuantities_end(res.x) return np.hstack((c1,ci.flatten(),n1,ni.flatten(),K_*np.ones(S),phi.flatten(),xi.flatten(),eta.flatten()))
def barrier_lowering(self): guess_r = -1e-9 warnings.filterwarnings('ignore') solution_l = root(self.field, guess_r) warnings.resetwarnings() if solution_l.success: r0_l = solution_l.x[0] delta_phi_l = abs(self.potential(r0_l)) print 'left:', r0_l, delta_phi_l else: r0_l = 0 delta_phi_l = 0 guess_r = 1e-9 warnings.filterwarnings('ignore') solution_r = root(self.field, guess_r) warnings.resetwarnings() if solution_r.success: r0_r = solution_r.x[0] delta_phi_r = abs(self.potential(r0_r)) print 'right:', r0_r, delta_phi_r else: r0_r = 0 delta_phi_r = 0 if r0_l == r0_r: r0 = np.array([r0_l]) delta_phi = np.array([delta_phi_l]) else: r0 = np.array([r0_l, r0_r]) delta_phi = np.array([delta_phi_l, delta_phi_r]) return delta_phi, r0
def test_tol_parameter(self): # Check that the minimize() tol= argument does something def func(z): x, y = z return np.array([x**3 - 1, y**3 - 1]) def dfunc(z): x, y = z return np.array([[3*x**2, 0], [0, 3*y**2]]) for method in ['hybr', 'lm', 'broyden1', 'broyden2', 'anderson', 'diagbroyden', 'krylov']: if method in ('linearmixing', 'excitingmixing'): # doesn't converge continue if method in ('hybr', 'lm'): jac = dfunc else: jac = None sol1 = root(func, [1.1,1.1], jac=jac, tol=1e-4, method=method) sol2 = root(func, [1.1,1.1], jac=jac, tol=0.5, method=method) msg = "%s: %s vs. %s" % (method, func(sol1.x), func(sol2.x)) assert_(sol1.success, msg) assert_(sol2.success, msg) assert_(abs(func(sol1.x)).max() < abs(func(sol2.x)).max(), msg)
def rapo(e): try: rs = [] for i in range(len(e)): E = e[i] if E**-1 > 0.2: rguess = 10*E**-1 elif E**-1 < 0.2: rguess = 0.01*E**-1 rresult = root(rapoimplicit,rguess,args=E) if rresult.success == True: rs.append(abs(rresult.x)) elif rresult.success == False: print 'Failed to evaluate rapo' print rresult.message rs.append(abs(rresult.x)) return array(rs) except (TypeError,AttributeError) as err: print err E = e if E**-1 > 0.2: rguess = 10*E**-1 elif E**-1 < 0.2: rguess = 0.01*E**-1 rresult = root(rapoimplicit,rguess,args=E) if rresult.success == True: return abs(rresult.x) elif rresult.success == False: print 'Failed to evaluate rapo' print rresult.message return abs(rresult.x)
def funcJc2(E,verbose): try: t = E.shape Jcs = [] problems = [] for i in range(len(E)): if E[i]**-1 > 0.4: rguess = 10*E[i]**-1 elif E[i]**-1 < 0.4: rguess = 0.01*E[i]**-1 rresult = root(Jc2implicit,rguess,args=(E[i],verbose)) rresult.x = abs(rresult.x) if rresult.success == True: Jcs.append(((10**Mencgood(log10(rresult.x))+model.Mnorm)*rresult.x)[0]) elif rresult.success == False: if verbose==True: print 'Failed to evaluate Jc2' print rresult.message Jcs.append(((10**Mencgood(log10(rresult.x))+model.Mnorm)*rresult.x)[0]) problems.append(i) return array(Jcs),problems except AttributeError: rresult = root(Jc2implicit,0.01*E[i]**-1,args=(E[i],verbose)) problem = [] rresult.x = abs(rresult.x) if rresult.success == True: Jc = ((10**Mencgood(log10(rresult.x))+model.Mnorm)*rresult.x)[0] elif rresult.success == False: if verbose==True: print 'Failed to evaluate Jc2' print rresult.message Jc = ((10**Mencgood(log10(rresult.x))+model.Mnorm)*rresult.x)[0] problem = [E] return Jc, problem
def rapo(E,prereqs): """ E - energy prereqs - a list containing the functional form of psi Returns the root of rapoimplicit. """ #trial and error provided this as a good way to find an initial guess if isinstance(E,(list,ndarray)): rresults = [] rguesses = zeros(len(E)) large = where(E**-1 > 0.2) small = where(E**-1 < 0.2) rguesses[small] += 0.01*E[small]**-1 rguesses[large] += 10*E[large]**-1 for i in range(len(E)): rresult = root(rapoimplicit,rguesses[i],args = (E[i],prereqs)) rresults.append(abs(rresult.x)) return array(rresults) elif isinstance(E,(float,int)): if E**-1 > 0.2: rguess = 10*E**-1 elif E**-1 < 0.2: rguess = 0.01*E**-1 rresult = root(rapoimplicit,rguess,args=(E,prereqs)) if rresult.success == True: return abs(rresult.x) elif rresult.success == False: print 'Failed to evaluate rapo' print rresult.message return abs(rresult.x)
def R_Rdot_grid(E, potential_params, nR=10, nRdot=10): z = 0. # find the min and max allowed R values f = lambda R: E - effective_potential(np.array([R,0.,0.,0.]),**potential_params) res1 = root(f, x0=1., options={'xtol': 1e-8}, tol=1e-8) res2 = root(f, x0=50., options={'xtol': 1e-8}, tol=1e-8) if not (res1.success and res2.success): raise ValueError("R Root finding failed.") minR = res1.x[0] + res1.x[0]/100. maxR = res2.x[0] - res2.x[0]/100. R_grid = np.linspace(minR, maxR, nR) logger.info("Min, max R for grid: {},{}".format(minR, maxR)) # now find the max allowed Rdot zvc = lambda R: -np.sqrt(2*(E - effective_potential(np.array([R,0.,0.,0.]), **potential_params))) res = minimize(zvc, x0=20., options={'xtol': 1e-8}, method='nelder-mead') if not res.success: raise ValueError("Rdot optimization failed.") maxRdot = -res.fun + res.fun/100. Rdot_grid = np.linspace(0., maxRdot, nRdot) # create a grid of initial conditions R,Rdot = map(np.ravel, np.meshgrid(R_grid, Rdot_grid)) # now throw out any point where Rdot > ZVC ix = Rdot < -zvc(R) return R[ix], Rdot[ix]
def find_root(fun, x0, method="hybr"): """Wrapper around SciPy's generic root finding algorithm to support complex numbers. SciPy's generic root finding algorithm (``scipy.optimize.root``) is not able to deal with functions returning and/or accepting arrays with complex numbers. This wrapped call will first convert all arrays of complex numbers into arrays of floats while splitting each complex number up into two floats. Parameters ---------- fun : :py:class:`callable` Complex function to find the root of x0 : :py:class:`numpy.ndarray` Initial guess. method : :py:class:`str` Root finding method to be used. See ``scipy.optimize.root`` for details. Returns ------- Same solution object as ``scipy.optimize.root`` but with ``x`` being converted back including complex numbers. Examples -------- from pypint.plugins.implicit_solvers.find_root import find_root import numpy fun = lambda x: (-1.0 + 1.0j) * x sol = find_root(fun, numpy.array([0.0])) """ assert_is_instance(x0, np.ndarray, descriptor="Initial Guess") assert_is_callable(fun, descriptor="Function to find root of") assert_is_instance(method, str, descriptor="Root finding method") _value_map = {} _transformed_size = 0 _transform_necessary = False for i in range(0, x0.size): if isinstance(x0[i], complex): _value_map[i] = [_transformed_size, _transformed_size + 1] _transformed_size += 2 _transform_necessary = True else: _value_map[i] = [_transformed_size] _transformed_size += 1 if _transform_necessary: _wrapped_func = \ lambda x_next: _transform_to_real(fun(_transform_to_complex(x_next, _value_map)), _value_map, _transformed_size) sol = root(fun=_wrapped_func, x0=_transform_to_real(x0, _value_map, _transformed_size), method=method) else: sol = root(fun=fun, x0=x0, method=method) if sol.success and _transform_necessary: sol.x = _transform_to_complex(sol.x, _value_map) return sol
def equilibrium(mass,cgZ,shape,w,verbose=None): obj_fun = lambda x: actions(mass,cgZ,np.array([x[0],x[1],0.]), np.array([0.,0.,x[2]]),shape,w) if verbose: sol = optim.root(obj_fun,np.array([0.,0.,0.]),method='krylov', callback=callbackfun) else: sol = optim.root(obj_fun,np.array([0.,0.,0.]),method='krylov') return tuple(sol.x)
def solveSteadyState(self): ''' Solve for the steady state ''' global Y0 res = root(self.SteadyStateRes,0.5*np.ones(nY)) if not res.success: res = root(self.SteadyStateRes,Y0) if not res.success: raise Exception('Could not find steady state') Y0 = res.x self.Y = res.x
def get_yield_stress(self, n): """ Gets the yield stress for a given direction Args: n (3x1 array-like): direction for which to find the yield stress """ # TODO: root finding could be more robust comp = root(self.get_stability_criteria, -1, args=n) tens = root(self.get_stability_criteria, 1, args=n) return (comp.x, tens.x)
def calculate(self, parameter_estimates = [1, 1, 1]): thermal_voltage_estimate = self.__thermal_voltage_estimate(parameter_estimates[2]) if self.number_of_iterations == None: solution = optimize.root(self.__function_of_three_equations, [parameter_estimates[0], parameter_estimates[1], thermal_voltage_estimate]) else: solution = optimize.root(self.__function_of_three_equations, [parameter_estimates[0], parameter_estimates[1], thermal_voltage_estimate], options={'maxfev': self.number_of_iterations}) self.series_resistance = solution.x[0] self.shunt_resistance = solution.x[1] self.thermal_voltage = solution.x[2] self.diode_quality_factor = self.__diode_quality_factor()
def funcJc2(E,prereqs): """ E - energy prereqs - a list containg the model class instance and functional forms of Menc and psi Returns circular angular momentum squared for orbit with energy E. """ model,Mencgood,psigood = prereqs #if E is in an array, cycle through elements and compute for each if isinstance(E,(list,ndarray)) == True: Jcs = [] problems = [] for i in range(len(E)): #trial and error produced this method of initial guess if E[i]**-1 > 0.4: rguess = 10*E[i]**-1 elif E[i]**-1 < 0.4: rguess = 0.01*E[i]**-1 rresult = root(Jc2implicit,rguess,args=(E[i],prereqs)) rresult.x = abs(rresult.x) #if rootfinder fails, write error message to file if rresult.success == True: Jcs.append(((10**Mencgood(log10(rresult.x))+model.Mnorm)*rresult.x)[0]) elif rresult.success == False: model.statfile.write('\nFailed to evaluate Jc2') model.statfile.write('\n{0}'.format(rresult.message)) Jcs.append(((10**Mencgood(log10(rresult.x))+model.Mnorm)*rresult.x)[0]) problems.append(i) return array(Jcs),problems elif isinstance(E,(float,int)) == True: #trial and error produced this method of initial guess if E**-1 > 0.4: rguess = 10*E**-1 elif E**-1 < 0.4: rguess = 0.01*E**-1 rresult = root(Jc2implicit,rguess,args=(E,prereqs)) problem = [] rresult.x = abs(rresult.x) #if rootfinder fails, write error message to file if rresult.success == True: Jc = ((10**Mencgood(log10(rresult.x))+model.Mnorm)*rresult.x)[0] elif rresult.success == False: model.statfile.write('\nFailed to evaluate Jc2') model.statfile.write('\n{0}'.format(rresult.message)) Jc = ((10**Mencgood(log10(rresult.x))+model.Mnorm)*rresult.x)[0] problem = [E] return Jc, problem
def solveLSmuTime0(mu,Para,b0): S = Para.P.shape[0] f = lambda z: LSResidualsTime0(z,mu,Para,b0) z_mu = root(f,0.5*np.ones(2*S)).x return z_mu[0:S],z_mu[S:2*S]
def find_first_best(self): ''' Find the first best allocation ''' Para = self.Para S,Theta,Uc,Un,G = self.S,self.Theta,Para.Uc,Para.Un,self.G def res(z): c = z[:S] n = z[S:] return np.hstack( [Theta*Uc(c,n)+Un(c,n), Theta*n - c - G] ) res = root(res,0.5*np.ones(2*S)) if not res.success: raise Exception('Could not find first best') self.cFB = res.x[:S] self.nFB = res.x[S:] IFB = Uc(self.cFB,self.nFB)*self.cFB + Un(self.cFB,self.nFB)*self.nFB self.xFB = np.linalg.solve(np.eye(S) - self.beta*self.Pi, IFB) self.zFB = {} for s in range(S): self.zFB[s] = np.hstack([self.cFB[s],self.nFB[s],self.xFB])
def _get_w_lst(self): '''evaluates the crack openings''' cb_lst = self.sorted_CB_lst for cb_i in cb_lst: cb_i.damage_switch = False CB_arr = np.array(cb_lst) def scalar_sigma_c(w, f): return f.get_sigma_c(w) vect_sigma_c = np.vectorize(scalar_sigma_c) res = [] def min_func(w_arr): w_arr = np.abs(w_arr) CB_sigmac_arr = vect_sigma_c(w_arr, CB_arr) residuum = np.hstack((CB_sigmac_arr[:-1] - CB_sigmac_arr[1:], self.W-np.sum(w_arr))) res.append(CB_sigmac_arr) return residuum opt_result = root(min_func, np.repeat(self.W/float(len(cb_lst)),len(cb_lst)), method='krylov', options={'maxiter':200}) # res = np.array(res) # if len(CB_arr) > 2: # for i in np.arange(res.shape[1] - 1): # plt.plot(res[:,i]) # plt.show() for cb_i in cb_lst: cb_i.damage_switch = True return np.abs(opt_result.x)
def solveLucasStockey_alt(x,Para): S = Para.P.shape[0] def LSres(z): beta = Para.beta c = z[0:S] mu = z[S:2*S] xi = z[2*S:3*S] l = (c+Para.g)/Para.theta xprime = np.zeros(S) for s in range(0,S): [cprime,lprime] = solveLSmu(mu[s],Para) Iprime = c*Para.U.uc(cprime,lprime,Para)+lprime*Para.U.ul(cprime,lprime,Para) xprime[s] = Para.P[0,:].dot( np.linalg.solve(np.eye(S)-(Para.beta*Para.P.T).T,Iprime)) uc = Para.U.uc(c,l,Para) ucc = Para.U.ucc(c,l,Para) ul = Para.U.ul(c,l,Para) ull = Para.U.ull(c,l,Para) res = np.zeros(3*S) Euc = Para.P[0,:].dot(uc) mu_ = Para.P[0,:].dot(uc*mu)/Euc res[0:S] = c*uc+l*ul+xprime-x*uc/(beta*Euc) res[S:2*S] = uc-mu*( c*ucc+uc )+x*ucc/(beta*Euc) * (mu-mu_)-xi res[2*S:3*S] = ul - mu*( l*ull+ul ) + Para.theta * xi return res z0 = [0.5]*S+[0]*2*S z_SL = root(LSres,z0).x cLS = z_SL[0:S] lLS = (cLS+Para.g)/Para.theta return cLS,lLS,Para.I(cLS,lLS)
def findBondSteadyState(Para): def xBondResidual(mu): c,l = solveLSmu(mu,Para) uc = Para.U.uc(c,l,Para) I = Para.I(c,l) Euc = Para.P[0,:].dot(uc) x= I/(uc/Euc-Para.beta) return x S = len(Para.P) if S == 2: def f(mu): x = xBondResidual(mu) return x[1]-x[0] else: def f(mu): x = xBondResidual(mu) xbar = Para.P[0,:].dot(x) return np.linalg.norm(x-xbar) muSS = root(f,0.0).x cSS,lSS = solveLSmu(muSS,Para) ucSS = Para.U.uc(cSS,lSS,Para) ISS = Para.I(cSS,lSS) EucSS = Para.P[0,:].dot(ucSS) xSS= ISS/(ucSS/EucSS-Para.beta) return muSS,cSS,lSS,xSS
def lake_problem(pollution_limit, b = 0.42, # decay rate for P in lake (0.42 = irreversible) q = 2.0, # recycling exponent mean = 0.02, # mean of natural inflows stdev = 0.001, # standard deviation of natural inflows alpha = 0.4, # utility from pollution delta = 0.98, # future utility discount rate nsamples = 100): # monte carlo sampling of natural inflows Pcrit = root(lambda x: x**q/(1+x**q) - b*x, 0.01, 1.5) nvars = len(pollution_limit) X = np.zeros((nvars,)) average_daily_P = np.zeros((nvars,)) decisions = np.array(pollution_limit) reliability = 0.0 for _ in range(nsamples): X[0] = 0.0 natural_inflows = np.random.lognormal( math.log(mean**2 / math.sqrt(stdev**2 + mean**2)), math.sqrt(math.log(1.0 + stdev**2 / mean**2)), size = nvars) for t in range(1,nvars): X[t] = (1-b)*X[t-1] + X[t-1]**q/(1+X[t-1]**q) + decisions[t-1] + natural_inflows[t-1] average_daily_P[t] += X[t]/float(nsamples) reliability += np.sum(X < Pcrit)/float(nsamples*nvars) max_P = np.max(average_daily_P) utility = np.sum(alpha*decisions*np.power(delta,np.arange(nvars))) inertia = np.sum(np.diff(decisions) > -0.02)/float(nvars-1) return (max_P, utility, inertia, reliability)
def time1_allocation(self,mu): ''' Computes optimal allocation for time t\geq 1 for a given \mu ''' Para = self.Para S,Theta,G,Uc,Ucc,Un,Unn = self.S,self.Theta,self.G,Para.Uc,Para.Ucc,Para.Un,Para.Unn def FOC(z): c = z[:S] n = z[S:2*S] Xi = z[2*S:] return np.hstack([ Uc(c,n) - mu*(Ucc(c,n)*c+Uc(c,n)) -Xi, #foc c Un(c,n) - mu*(Unn(c,n)*n+Un(c,n)) + Theta*Xi, #foc n Theta*n - c - G #resource constraint ]) #find the root of the FOC res = root(FOC,self.zFB) if not res.success: raise Exception('Could not find LS allocation.') z = res.x c,n,Xi = z[:S],z[S:2*S],z[2*S:] #now compute x I = Uc(c,n)*c + Un(c,n)*n x = np.linalg.solve(np.eye(S) - self.beta*self.Pi, I ) return c,n,x,Xi
def plot_reml(C_eta, sel, sel_label, ax, ax2, sigma_diag): coh_arr = np.linspace(0.00, 0.30, 16) reml_arr = reml(C_eta, coh_arr, sel, sel_label, ax2, sigma_diag) ax.plot(coh_arr, reml_arr, 'm+', label=sel_label) ax.set_xlabel(r'$\sigma_i$') ax.set_ylabel('REML') ax.set_xlim(-0.02,0.30) # Fit a polynomial to the points coeff=np.polyfit(coh_arr, reml_arr, 4) p=np.poly1d(coeff) coh_arr2=np.linspace(0.00, 0.20, 201) fit=p(coh_arr2) ax.plot(coh_arr2,fit) # Determine where the minumum occurs minimum=sp.fmin(p,0.1,disp=False) print "Miminum at %4.3f" % (minimum[0]) # The uncetainty occurs whwn the the REML increases by 1 - need to double check # To find where the the REML increases by 1, we look for the roots coeff=np.polyfit(coh_arr, reml_arr-p(minimum[0])-1, 4) p=np.poly1d(coeff) sol=sp.root(p,[0.0,0.2]) m=minimum[0] upper=sol.x[1]-m lower=m-sol.x[0] ax.plot(coh_arr2,fit,label="Min at %4.2f+%4.2f-%4.2f" % (m,upper,lower)) return
def newton_Bt ( psixy, Rxy, Btxy, Bpxy, pxy, hthe, mesh): #global psi, a, b MU = 4.e-7*numpy.pi s = numpy.shape(Rxy) nx = s[0] ny = s[1] axy = old_div(DDX(psixy, Rxy), Rxy) bxy = MU*DDX(psixy, pxy) - Bpxy*DDX(psixy, Bpxy*hthe)/hthe Btxy2 = numpy.zeros((nx, ny)) for i in range (ny) : psi = psixy[:,i] a = axy[:,i] b = bxy[:,i] print("Solving f for y=", i) sol=root(Bt_func, Btxy[:,i], args=(psi, a, b) ) Btxy2[:,i] = sol.x # Average f over flux surfaces fxy = surface_average(Btxy2*Rxy, mesh) return old_div(fxy, Rxy)
def solver_Kirch_DiodeV2Mod2DirectBranchmathath (x,b,c=None): """ [Реестровая] + двухступенчатый - сначала np solver, затем math solver :param x: :param b: :param c: :param npVersion: если true, то возвращает numpy-compatible результат первой ступени, иначе идёт дальше :return: """ global numnone global FT func = lambda y, x, b, c: [float(func_Kirch_DiodeV2Mod2DirectBranchmathath (y,x,b,c)[0])] solvinit=[0.001] try: solx=optimize.root(func, solvinit, args=(x,b,c), jac=dfdy, method='lm').x #solx=optimize.root(func, solvinit, args=(x,b,c), method='lm').x #solx=optimize.root(func, solvinit, args=(x,b,c), method='lm').x #http://stackoverflow.com/questions/2566412/find-nearest-value-in-numpy-array #http://codereview.stackexchange.com/questions/28207/is-this-the-fastest-way-to-find-the-closest-point-to-a-list-of-points-using-nump except BaseException as e: numnone+=1 print ("solver: ERROR first stage: "+e.__str__()) return [None] return solx
def prob4(): """Find the roots of the system [ -x + y + z ] [0] [ 1 + x^3 - y^2 + z^3 ] = [0] [ -2 - x^2 + y^2 + z^2 ] [0] Returns the values of x,y,z as an array. """ # Define the nonlinear system, its Jacobian, and the initial guess. def f(X): x,y,z = X return np.array([ -x + y + z, 1 + x**3 -y**2 + z**3, -2 -x**2 + y**2 + z**2 ]) def jacobian(X): x,y,z = X return np.array([ [ -1, 1, 1 ], [3*x**2, -2*y, 3*z**2], [ -2*x, 2*y, 2*z ] ]) x0 = np.array([0,0,0]) # Calculate the solution, check that it is a root, and return it. sol = opt.root(f, x0, jac=jacobian, method='hybr') assert np.allclose(np.zeros_like(sol.x), f(sol.x)), "FAILURE" return sol.x
def inference_cEWRGt(W, thresh): k = (W>0).sum(axis=0) # degrees s = W.sum(axis=0) # strength #from scipy.optimize import root from scipy.optimize import least_squares x0=np.concatenate([k,s])*1E-4 # initial solution # Initialize least squares from previous solution sollm = least_squares(lambda v: eq(v,thresh,k,s), x0=x0, bounds= (0,np.inf), method='trf', ftol=1E-8, xtol=1E-8, verbose=1) sollm = root(lambda z: eq(z,thresh,k,s), x0=x0, method='lm', options={'xtol':1E-30,'gtol':1E-30,'ftol':1E-30}, tol=1E-6) #print('Final cost', sollm['cost']) sollm = sollm['x'] n2 = int(len(sollm)//2) x,y = sollm[0:n2],sollm[n2:] return x, y
def mcmc_newton(J): mt,ns,sd=1000, 200,3 # mc-time(until equilibrium), #sample, sampling distance def genMCMC(x=[]): x0=[] l=len(x) for t in range(mt+ns*sd): for i in range(l): valu=(( x[(l+i-1)%l]+x[(i+1)%l] )) r=np.exp(-J*valu)/(np.exp(J*valu)+np.exp(-J*valu)) R=np.random.uniform(0,1) if(R<=r): x[i]=1 else: x[i]=-1 if(t>mt and t%3==0): if(len(x0)==0): x0=x else: x0=np.vstack((x0,x)) return x0.astype(int) def calcf(J,c,x=[[]]): a=[0,0] for i in range(100): y=x[i,:] b=f(J,y) a[0]+=b[0] a[1]+=b[1] m=a[1]/a[0] m=m-c#surch for zero point ot 'm-a0 ' return m x0=np.ones(d)# Initialize x=genMCMC(x0)# Generate mcmc-samples J0=root(calcf,0.1,(10,x)) print("J0=",J0) return J0
def getSol(startvals): solns = [] for i in range(len(startvals)): sol = root(getGradient, startvals[i], method='lm') solns.append(sol) return solns
def _calculate_momentum_distribution(self): """Calculate an approximation to the CDF of momentum magnitude. The purpose of this method is to calculate :member:_inv_cdf, a function giving a numerical approximation to the inverse cumulative distribution function of the magnitude of the momentum vector. This function can be used to perform inverse transform sampling to generate samples of the momentum. This method should be called before any sampling is performed. As implemented, it is called upon the first call to self.ask. Numerical integration of the momentum density is performed using the trapezoidal rule. """ # Calculate the value of p (momentum) corresponding to the maximum of # the pdf def logpdf_deriv(p): # logpdf_deriv(p) = 0 is the simplified form of d/dp(logpdf(p)) = 0 d = np.sqrt(self._mass * (self._n_parameters - 1)) \ * (p**2 + self._m2c2) ** 0.25 / np.sqrt(self._c * self._mass) \ - p return d p_max = root(logpdf_deriv, self._mass).x[0] # The initial integration grid goes from 0 to twice p_max, with 1000 # grid points max_value = 2 * p_max spacing = max_value / 1000 integration_accepted = False while not integration_accepted: # Evaluate the logpdf on a grid integration_grid = np.arange(min(1e-6, 0.5 * spacing), max_value, spacing) logpdf_values = self._momentum_logpdf(integration_grid) # Integrate using the trapezoidal rule # Note that the step size (and any other constants) can be ignored # here, as the CDF will be normalized after this calculation cdf = np.logaddexp.accumulate( np.logaddexp(logpdf_values[1:], logpdf_values[:-1])) # Normalize the CDF cdf = np.exp(cdf - cdf[-1]) # Adapt the integration grid if the result is inaccurate if np.diff(cdf)[-1] > 0.001 * max(np.diff(cdf)): # cdf is still increasing at the end max_value *= 2 spacing *= 2 elif max(np.diff(cdf)) > 1e-3: # cdf is changing too much, so a finer grid is required spacing /= 2 else: integration_accepted = True if max_value / spacing > self._max_integration_size: warnings.warn('Failed to approximate momentum distribution ' 'for given mass and speed of light. Samples of ' 'momentum may be inaccurate.') integration_accepted = True # Do a reverse interpolation to approximate inverse cdf inv_cdf = interp1d([0.0] + list(cdf), integration_grid) # Save the inverse cdf so that it can be used for sampling self._inv_cdf = inv_cdf
def SolveSteadySteate(self): ''' Newton Method to find the root of the steady state equation ''' self._solver = 'steady' if self._debug: self._logger.info('LLEsovler.SolveSteadySteate', 'Solving Steady State LLE with Python....') print('-' * 70) date = time.localtime() date = "{}-{:0>2}-{:0>2} ".format(date.tm_year, date.tm_mon, date.tm_mday) +\ "{:0>2}:{:0>2}:{:0>2}".format(date.tm_hour, date.tm_min, date.tm_sec) start = time.time() print(date) # -- CHeck Parity of the µ -- μ_sim = copy(self.sim['mu_sim']) ind = 0 if not μ_sim[0] == -μ_sim[1]: μ_sim = [-np.max(np.abs(μ_sim)), np.max(np.abs(μ_sim))] INFO = 'Not symmetric mode calculation -> switching to it with µ_sim = {}\n'.format( μ_sim) print(INFO) if self._debug: try: self._logger.info('LLEsovler.SolveSteadySteate', INFO) except: Info = ''.join([ self._greek[ii] if ii in self._greek.keys() else ii for ii in Info ]) self._logger.info('LLEsovler.SolveSteadySteate', INFO) dum = self.Analyze(mu_sim=μ_sim, plot=False, f=None) # -- setting up parameters -- β2 = self._analyze.β2 Pin = self.sim['Pin'] γ = self.res['gamma'] L = 2 * np.pi * self.res['R'] ω0 = self.sim['f_pmp'] * 2 * np.pi Q0 = self.res['Qi'] Qc = self.res['Qc'] tR = L * self.res['ng'] / self._c0 α = 1 / 2 * (ω0 / Q0 + ω0 / Qc) * tR θ = ω0 / Qc * tR δω = -self.sim['domega'] * tR nlc = -1j * γ * L μ = np.arange(μ_sim[0], μ_sim[1] + 1) pmp_ind = np.where(μ == 0)[0][0] ω = μ * 2 * np.pi / tR + ω0 ν = ω / (2 * np.pi) # -- setting up input power -- Ein = np.zeros(μ.size) Ein[pmp_ind] = np.sqrt(Pin) * μ.size Ein_couple = np.sqrt(θ) * Ein # -- Define Initial Guess -- sech = lambda x: 1 / np.cosh(x) η = δω / α # need to be fixed B0 = np.sqrt(2 * η) f = np.sqrt(θ * Pin * γ * L / α**3) φ0 = np.arccos(np.sqrt(8 * η) / np.pi / f) τ = np.linspace(-0.5, 0.5, μ.size) * tR Φ0 = f / η**2 - 1j * f / η ut0 = np.sqrt(α / γ / L) * (Φ0 + B0 * np.exp(1j * φ0) * sech(B0 * np.sqrt(α / (np.abs(β2) * L)) * τ)) Em0 = fft.fftshift(fft.fft(ut0)) x_init = np.concatenate((Em0.real, -Em0.imag)) # -- Define the Steady State LLE Equation -- φ = -α + 1j * δω - 1j * self.sim["dphi"] Em = lambda xx: xx[0:int(xx.shape[0] / 2)] + 1j * xx[int(xx.shape[0] / 2)] Ut = lambda xx: fft.ifft(Em(xx)) fm = lambda xx: φ * Em(xx) + nlc * fft.fft(np.abs(Ut(xx))**2 * Ut(xx) ) + Ein_couple fvec = lambda xx: np.concatenate((fm(xx).real, fm(xx).imag)) # -- Solver the Steady State -- out = optm.root(fvec, x_init, method='lm', jac=None, tol=1e-20) Ering = Em(out.x) / μ.size Ewg = Ein / μ.size - Ering * np.sqrt(θ) self.steady = {'Ering': Ering, 'Ewg': Ewg} if not pyType == 'jupyter': f, ax = plt.subplots(dpi=120) ax.plot(1e-12 * ν, 20 * np.log10(np.abs(Ering)), label='Ring') ax.plot(1e-12 * ν, 20 * np.log10(np.abs(Ewg)), label='Waveguide') ax.legend() f.show() return f, ax else: trace0 = go.Scatter(x=1e-12 * ν, y=20 * np.log10(np.abs(Ering)), mode='lines', name='Res. Power') trace1 = go.Scatter(x=1e-12 * ν, y=20 * np.log10(np.abs(Ewg)), mode='lines', name='Out Power') data = [trace0, trace1] layout = dict( xaxis=dict(title='Frequency (THz)'), yaxis=dict(title='Power (dBm)'), ) fig = go.Figure(data=data, layout=layout) iplot(fig) return fig
import numpy as np from scipy import optimize import sys fn1 = sys.argv[1] fn2 = sys.argv[2] w1 = np.loadtxt(fn1)[1][::-1] w2 = np.loadtxt(fn2)[1][::-1] model1 = np.poly1d(w1) model2 = np.poly1d(w2) def func(x): return model1(x) - model2(x) sol = optimize.root(func, x0=0) print(np.min(sol.x))
def runner(): ''' this function runs the cge model ''' # solve cge_system dist = 10 tpi_iter = 0 tpi_max_iter = 1000 tpi_tol = 1e-10 xi = 0.1 # pvec = pvec_init pvec = np.ones(len(ind) + len(h)) # Load data and parameters classes d = calibrate.model_data(sam, h, u, ind) p = calibrate.parameters(d, ind) R = d.R0 er = 1 Zbar = d.Z0 Ffbar = d.Ff0 Kdbar = d.Kd0 Qbar = d.Q0 pdbar = pvec[0:len(ind)] pm = firms.eqpm(er, d.pWm) while (dist > tpi_tol) & (tpi_iter < tpi_max_iter): tpi_iter += 1 cge_args = [p, d, ind, h, Zbar, Qbar, Kdbar, pdbar, Ffbar, R, er] print("initial guess = ", pvec) results = opt.root(cge.cge_system, pvec, args=cge_args, method='lm', tol=1e-5) pprime = results.x pyprime = pprime[0:len(ind)] pfprime = pprime[len(ind):len(ind) + len(h)] pyprime = Series(pyprime, index=list(ind)) pfprime = Series(pfprime, index=list(h)) pvec = pprime pe = firms.eqpe(er, d.pWe) pm = firms.eqpm(er, d.pWm) pq = firms.eqpq(pm, pdbar, p.taum, p.eta, p.deltam, p.deltad, p.gamma) pz = firms.eqpz(p.ay, p.ax, pyprime, pq) Kk = agg.eqKk(pfprime, Ffbar, R, p.lam, pq) Td = gov.eqTd(p.taud, pfprime, Ffbar) Trf = gov.eqTrf(p.tautr, pfprime, Ffbar) Kf = agg.eqKf(Kk, Kdbar) Fsh = firms.eqFsh(R, Kf, er) Sp = agg.eqSp(p.ssp, pfprime, Ffbar, Fsh, Trf) I = hh.eqI(pfprime, Ffbar, Sp, Td, Fsh, Trf) E = firms.eqE(p.theta, p.xie, p.tauz, p.phi, pz, pe, Zbar) D = firms.eqDex(p.theta, p.xid, p.tauz, p.phi, pz, pdbar, Zbar) M = firms.eqM(p.gamma, p.deltam, p.eta, Qbar, pq, pm, p.taum) Qprime = firms.eqQ(p.gamma, p.deltam, p.deltad, p.eta, M, D) pdprime = firms.eqpd(p.gamma, p.deltam, p.eta, Qprime, pq, D) Zprime = firms.eqZ(p.theta, p.xie, p.xid, p.phi, E, D) # Zprime = Zprime.iloc[0] Kdprime = agg.eqKd(d.g, Sp, p.lam, pq) Ffprime = d.Ff0 # Ffprime['CAP'] = R * d.Kk * (p.lam * pq).sum() / pf[1] Ffprime['CAP'] = R * Kk * (p.lam * pq).sum() / pfprime[1] dist = (((Zbar - Zprime) ** 2) ** (1 / 2)).sum() print('Distance at iteration ', tpi_iter, ' is ', dist) pdbar = xi * pdprime + (1 - xi) * pdbar Zbar = xi * Zprime + (1 - xi) * Zbar Kdbar = xi * Kdprime + (1 - xi) * Kdbar Qbar = xi * Qprime + (1 - xi) * Qbar Ffbar = xi * Ffprime + (1 - xi) * Ffbar Q = firms.eqQ(p.gamma, p.deltam, p.deltad, p.eta, M, D) print('Model solved, Q = ', Q) return Q
def findPropagationConstants(wl, indexProfile, tol=1e-9): ''' Find the propagation constants of a step index fiber by numerically finding the sollution of the scalar dispersion relation [1]_ [2]_. Parameters ---------- wl : float wavelength in microns. indexProfile: IndexProfile object object that contains data about the transverse index profile. Returns ------- modes : Modes object Object containing data about the modes. Note that it does not fill the transverse profiles, only the data about the propagation constants and the mode numbers. See Also -------- associateLPModeProfiles() Notes ----- .. [1] K. Okamoto, "Fundamentals of optical waveguides" Academic Press, 2006 .. [2] S. M. Popoff, "Modes of step index multimode fibers" http://wavefrontshaping.net/index.php/component/content/article/68-community/tutorials/multimode-fibers/118-modes-of-step-index-multimode-fibers ''' lbda = wl NA = indexProfile.NA a = indexProfile.a n1 = indexProfile.n1 logger.info( 'Finding the propagation constant of step index fiber by numerically solving the dispersion relation.' ) t0 = time.time() # Based on the dispersion relation,l eq. 3.74 # The normalized frequency, cf formula 3.20 of the book v = (2 * np.pi / lbda * NA * a) roots = [0] m = 0 modes = Modes() interval = np.arange(np.spacing(10), v - np.spacing(10), v * 1e-4) while (len(roots) > 0): def root_func(u): w = np.sqrt(v**2 - u**2) return jv(m, u) / (u * jv(m - 1, u)) + kn(m, w) / (w * kn(m - 1, w)) guesses = np.argwhere(np.abs(np.diff(np.sign(root_func(interval))))) froot = lambda x0: root(root_func, x0, tol=tol) sols = list(map(froot, interval[guesses])) roots = [s.x for s in sols if s.success] # remove solution outside the valid interval, round the solutions and remove duplicates roots = np.unique([ np.round(r / tol) * tol for r in roots if (r > 0 and r < v) ]).tolist() if (len(roots) > 0): degeneracy = 1 if m == 0 else 2 modes.betas = np.concatenate((modes.betas, [ np.sqrt((2 * np.pi / lbda * n1)**2 - (r / a)**2) for r in roots ] * degeneracy)) modes.u = np.concatenate((modes.u, roots * degeneracy)).tolist() modes.w = np.concatenate( (modes.w, [np.sqrt(v**2 - r**2) for r in roots] * degeneracy)).tolist() modes.number += len(roots) * degeneracy modes.m.extend([m] * len(roots) * degeneracy) modes.l.extend([x + 1 for x in range(len(roots))] * degeneracy) m += 1 logger.info("Found %g modes is %0.2f seconds." % (modes.number, time.time() - t0)) return modes
def implied_probabilities(odds: np.ndarray, method='basic', normalize=True): if (odds < 1).any(): return False # Prepare the list that will be returned. result = {'probabilities': -1, 'margin': -1} # Some useful quantities one_match = False try: n_matches = odds.shape[0] n_outcomes = odds.shape[1] except IndexError: one_match = True n_matches = 1 n_outcomes = odds.shape[0] # Inverted odds and margins inverted_odds = 1 / odds if not one_match: inverted_odds_sum = np.sum(inverted_odds, axis=1) inverted_odds_sum = inverted_odds_sum[:, None] else: inverted_odds_sum = np.sum(inverted_odds) result['margin'] = (inverted_odds_sum - 1) / ( inverted_odds_sum) # corrected margin definition if method == 'basic': result['probabilities'] = inverted_odds / inverted_odds_sum elif method == 'shin': zvalues = np.zeros(n_matches) # The proportion of insider trading. probs = np.zeros((n_matches, n_outcomes)) for ii in range(n_matches): try: resroot = root(shin_solvefor, 0, 0.4, args=inverted_odds[ii, ]) except Exception as exc: # print("Cannot convert odds to probs: " + ",".join(map(str, odds[ii]))) continue zvalues[ii] = resroot probs[ii, ] = shin_func(zz=resroot, io=inverted_odds[ii, ]) result['probabilities'] = probs result['zvalues'] = zvalues elif method == 'wpo': # Margin Weights Proportional to the Odds. # Method from the Wisdom of the Crowds pdf. fair_odds = (n_outcomes * odds) / (n_outcomes - (result['margin'] * odds)) result['probabilities'] = 1 / fair_odds result['specific_margins'] = (result['margin'] * fair_odds) / n_outcomes elif (method == 'or'): odds_ratios = np.zeros(n_matches) probs = np.zeros((n_matches, n_outcomes)) for ii in range(n_matches): try: resroot = root(or_solvefor, 0.05, 5, args=inverted_odds[ii, ]) except Exception as exc: # print("Cannot convert odds to probs: " + ",".join(map(str, odds[ii]))) continue odds_ratios[ii] = resroot probs[ii, ] = or_func(cc=resroot, io=inverted_odds[ii, ]) result['probabilities'] = probs result['odds_ratios'] = odds_ratios elif method == 'power': probs = np.zeros((n_matches, n_outcomes)) exponents = np.zeros(n_matches) for ii in range(n_matches): try: resroot = root(pwr_solvefor, 0.001, 1, args=inverted_odds[ii, ]) except Exception as exc: # print("Cannot convert odds to probs: " + ",".join(map(str, odds[ii]))) continue exponents[ii] = resroot probs[ii, ] = pwr_func(nn=resroot, io=inverted_odds[ii, ]) result['probabilities'] = probs result['exponents'] = exponents ## do a final normalization to make sure the probabilites ## sum to 1 without rounding errors. if normalize: norm = np.sum(result['probabilities'], axis=1)[:, None] np.warnings.filterwarnings( 'ignore') # division by zero (negative margin odds) try: result['probabilities'] = result['probabilities'] / norm except Warning: pass return result
# Compute norms HNorm = [ float(norm(H1)), float(norm(H2)), # Compute L2 vector norms float(norm(H3)), float(norm(H4)) ] # ... # Solve system of equations sol = root( LHS, initialGuess, args=(K, HNorm), method='lm', # Invoke solver using the options={ 'ftol': 1e-10, 'xtol': 1e-10, 'maxiter': 1000, # Levenberg-Marquardt 'eps': 1e-8, 'factor': 0.001 }) # Algorithm (aka LMA) # Print solution (coordinates) to screen print("Current position (x , y , z):") print("(%.5f , %.5f , %.5f)mm" % (sol.x[0] * 1000, sol.x[1] * 1000, -1 * sol.x[2] * 1000)) # Check if solution makes sense if (abs(sol.x[0] * 1000) > 500) or (abs(sol.x[1] * 1000) > 500) or (abs( sol.x[2] * 1000) > 500): initialGuess = findIG(Q_calcMag.get(
dens.append(rhoi) pi = rhoi * csi **2. """ rscale = Nr csi = np.sqrt(1.4e20 / rscale) vri = 1.1e10 * visc * rscale**(-1. / 2.) pi = 1.7e16 * macc_scale / (visc * mbh_scale) * rscale**(-5. / 2. + sadaf) omegai = 2.9e4 / (mbh_scale * rscale**(3. / 2.)) rhoi = pi / csi**2. hi = csi / omegai dens.append(rhoi) adaf_sol = op.root(main2.adaf_temp, 1e4, args=( rhoi, pi, )) Tmp.append(adaf_sol.x) alfsig2.append(np.log10(2. * dens[i] * hi * visc)) alfsig1.append(np.nan) else: Tmp.append(0) dens.append(0) alfsig1.append(np.nan) alfsig2.append(np.nan) #print(alfsig1)
def msgt_mix(rho1, rho2, Tsat, Psat, model, rho0='linear', z=20., n=20, ds=0.1, itmax=50, rho_tol=1e-3, full_output=False, root_method='lm', solver_opt=None): """ SGT for mixtures and beta != 0 (rho1, rho2, T, P) -> interfacial tension Parameters ---------- rho1 : float phase 1 density vector rho2 : float phase 2 density vector Tsat : float saturation temperature Psat : float saturation pressure model : object created with an EoS rho0 : string, array_like or TensionResult inital values to solve the BVP, avaialable options are 'linear' for linear density profiles, 'hyperbolic' for hyperbolic like density profiles. An array can also be supplied or a TensionResult of a previous calculation. z : float, optional initial interfacial lenght n : int, optional number points to solve density profiles ds : float, optional time variable integration delta itmax : int, optional maximun number of iterations foward on time rho_tol: float, optional desired tolerance for density profiles full_output : bool, optional wheter to outputs all calculation info root_method: string, optional Method used un SciPy's root function default 'lm', other options: 'krylov', 'hybr'. See SciPy documentation for more info solver_opt : dict, optional aditional solver options passed to SciPy solver Returns ------- ten : float interfacial tension between the phases """ z = 1. * z nc = model.nc # Dimensionless Variables Tfactor, Pfactor, rofactor, tenfactor, zfactor = model.sgt_adim(Tsat) Pad = Psat*Pfactor rho1a = rho1*rofactor rho2a = rho2*rofactor cij = model.ci(Tsat) cij /= cij[0, 0] dcij = np.linalg.det(cij) if np.isclose(dcij, 0): warning = 'Determinant of influence parameters matrix is: {}' raise Exception(warning.format(dcij)) temp_aux = model.temperature_aux(Tsat) # Chemical potential mu0 = model.muad_aux(rho1a, temp_aux) mu02 = model.muad_aux(rho2a, temp_aux) if not np.allclose(mu0, mu02): raise Exception('Not equilibria compositions, mu1 != mu2') # Nodes and weights of integration roots, weights = gauss(n) rootsf = np.hstack([0., roots, 1.]) # Coefficent matrix for derivatives A, B = colocAB(rootsf) # Initial profiles if isinstance(rho0, str): if rho0 == 'linear': # Linear Profile pend = (rho2a - rho1a) b = rho1a pfl = (np.outer(roots, pend) + b) ro_1 = (pfl.T).copy() rointer = (pfl.T).copy() elif rho0 == 'hyperbolic': # Hyperbolic profile inter = 8*roots - 4 thb = np.tanh(2*inter) pft = np.outer(thb, (rho2a-rho1a))/2 + (rho1a+rho2a)/2 rointer = pft.T ro_1 = rointer.copy() else: raise Exception('Initial density profile not known') elif isinstance(rho0, TensionResult): _z0 = rho0.z _ro0 = rho0.rho z = _z0[-1] rointer = interp1d(_z0, _ro0)(roots * z) rointer *= rofactor ro_1 = rointer.copy() elif isinstance(rho0, np.ndarray): # Check dimensiones if rho0.shape[0] == nc and rho0.shape[1] == n: rointer = rho0.copy() rointer *= rofactor ro_1 = rointer.copy() else: raise Exception('Shape of initial value must be nc x n') else: raise Exception('Initial density profile not known') zad = z*zfactor Ar = A/zad Br = B/zad**2 Binter = Br[1:-1, 1:-1] B0 = Br[1:-1, 0] B1 = Br[1:-1, -1] dro20 = np.outer(rho1a, B0) # cte dro21 = np.outer(rho2a, B1) # cte Ainter = Ar[1:-1, 1:-1] A0 = Ar[1:-1, 0] A1 = Ar[1:-1, -1] dro10 = np.outer(rho1a, A0) # cte dro11 = np.outer(rho2a, A1) # cte if root_method == 'lm' or root_method == 'hybr': if model.secondordersgt: fobj = dfobj_z_newton jac = True else: fobj = fobj_z_newton jac = None else: fobj = fobj_z_newton jac = None s = 0. for i in range(itmax): s += ds sol = root(fobj, rointer.flatten(), method='lm', jac=jac, args=(Binter, dro20, dro21, mu0, temp_aux, cij, n, ro_1, ds, nc, model), options=solver_opt) rointer = sol.x rointer = np.abs(rointer.reshape([nc, n])) error = np.linalg.norm(rointer - ro_1) if error < rho_tol: break ro_1 = rointer.copy() ds *= 1.3 dro = np.matmul(rointer, Ainter.T) dro += dro10 dro += dro11 suma = cmix_cy(dro, cij) dom = np.zeros(n) for k in range(n): dom[k] = model.dOm_aux(rointer[:, k], temp_aux, mu0, Pad) dom[dom < 0] = 0. intten = np.nan_to_num(np.sqrt(2*suma*dom)) ten = np.dot(intten, weights) ten *= zad ten *= tenfactor if full_output: znodes = z * rootsf ro = np.insert(rointer, 0, rho1a, axis=1) ro = np.insert(ro, n+1, rho2a, axis=1) ro /= rofactor fun_error = np.linalg.norm(sol.fun)/n/nc dictresult = {'tension': ten, 'rho': ro, 'z': znodes, 'GPT': np.hstack([0, dom, 0]), 'rho_error': error, 'fun_error': fun_error, 'iter': i, 'time': s, 'ds': ds} out = TensionResult(dictresult) return out return ten
def __init__( self, num_agents = 2, c_i = 1, a_minus_c_i = 1, a_0 = 0, mu = 0.25, delta = 0.95, m = 15, xi = 0.1, k = 1, max_steps=200, sessions=1, convergence=5, trainer_choice='DQN', supervisor=False, proportion_boost=1.0, use_pickle=False, path='', savefile='' ): super(BertrandCompetitionDiscreteEnv, self).__init__() self.num_agents = num_agents # Length of Memory self.k = k # Marginal Cost self.c_i = c_i # Number of Discrete Prices self.m = m # Product Quality Indexes a = np.array([c_i + a_minus_c_i] * num_agents) self.a = a # Product Quality Index: Outside Good self.a_0 = a_0 # Index of Horizontal Differentiation self.mu = mu ############################################################## # Nash Equilibrium Price def nash_func(p): ''' Derviative for demand function ''' denominator = np.exp(a_0 / mu) for i in range(num_agents): denominator += np.exp((a[i] - p[i]) / mu) function_list = [] for i in range(num_agents): term = np.exp((a[i] - p[i]) / mu) first_term = term / denominator second_term = (np.exp((2 * (a[i] - p[i])) / mu) * (-c_i + p[i])) / ((denominator ** 2) * mu) third_term = (term * (-c_i + p[i])) / (denominator * mu) function_list.append((p[i] - c_i) * (first_term + second_term - third_term)) return function_list # Finding root of derivative for demand function nash_sol = optimize.root(nash_func, [2] * num_agents) self.pN = nash_sol.x[0] print('Nash Price:', self.pN) # # Finding Nash Price by iteration # # Make sure this tries all possibilities # price_range = np.arange(0, 2.5, 0.01) # nash_temp = 0 # for i in price_range: # p = [i] * num_agents # first_player_profit = (i - c_i) * self.demand(self.a, p, self.mu, 0) # new_profit = [] # for j in price_range: # p[0] = j # new_profit.append((j - c_i) * self.demand(self.a, p, self.mu, 0)) # if first_player_profit >= np.max(new_profit): # nash_temp = i # self.pN = nash_temp # print('Nash Price:', self.pN) ############################################################################ # Monopoly Equilibrium Price def monopoly_func(p): return -(p[0] - c_i) * self.demand(self.a, p, self.mu, 0) monopoly_sol = optimize.minimize(monopoly_func, 0) self.pM = monopoly_sol.x[0] print('Monopoly Price:', self.pM) # # Finding Monopoly Price by iteration # # Make sure this tries all possibilities # price_range = np.arange(0, 2.5, 0.01) # monopoly_profit = [] # for i in price_range: # p = [i] * num_agents # monopoly_profit.append((i - c_i) * self.demand(self.a, p, self.mu, 0) * num_agents) # self.pM = price_range[np.argmax(monopoly_profit)] # print('Monopoly Price:', self.pM) ############################################################################### # Nash and Monopoly Profit # nash_profit = (self.pN - self.c_i) * self.demand(self.a, [self.pN, self.pN], self.mu, 0) # monopoly_profit = (self.pM - self.c_i) * self.demand(self.a, [self.pM, self.pM], self.mu, 0) # print('Nash Profit:', nash_profit) # print('Monopoly Profit:', monopoly_profit) ############################################################################### # Profit Gain Plot # val = [] # # x_range = np.linspace(self.pN-0.05, self.pM+0.05, 100) # x_range = np.arange(1.45, 2.00, 0.05) # for i in x_range: # profit = (i - self.c_i) * self.demand(self.a, [i, i], self.mu, 0) # profit_gain = (profit - nash_profit) / (monopoly_profit - nash_profit) # val.append(profit_gain) # print(i, profit, profit_gain) # plt.plot(x_range, val, c='k') # plt.axvline(x=self.pN, c='b', ls='--', label='Nash Price') # plt.axvline(x=self.pM, c='r', ls='--', label='Monopoly Price') # plt.xlabel('Price') # plt.ylabel('Profit Gain Δ') # plt.legend() # plt.savefig('profit_gain') ################################################################################ # MultiAgentEnv Action and Observation Space self.agents = ['agent_' + str(i) for i in range(num_agents)] self.observation_spaces = {} self.action_spaces = {} if k > 0: self.numeric_low = np.array([0] * (k * num_agents)) numeric_high = np.array([m] * (k * num_agents)) obs_space = Box(self.numeric_low, numeric_high, dtype=int) else: self.numeric_low = np.array([0] * num_agents) numeric_high = np.array([m] * num_agents) obs_space = Box(self.numeric_low, numeric_high, dtype=int) for agent in self.agents: self.observation_spaces[agent] = obs_space self.action_spaces[agent] = Discrete(m) if supervisor: self.observation_spaces['supervisor'] = obs_space self.action_spaces['supervisor'] = Discrete(num_agents) self.action_price_space = np.linspace(self.pN - xi * (self.pM - self.pN), self.pM + xi * (self.pM - self.pN), m) self.reward_range = (-float('inf'), float('inf')) self.current_step = None self.max_steps = max_steps self.sessions = sessions self.convergence = convergence self.convergence_counter = 0 self.trainer_choice = trainer_choice self.action_history = {} self.use_pickle = use_pickle self.supervisor = supervisor self.proportion_boost = proportion_boost self.path = path self.savefile = savefile # self.price_error = [[],[]] for agent in self.agents: if agent not in self.action_history: self.action_history[agent] = [self.action_spaces[agent].sample()] if supervisor: self.action_history['supervisor'] = [self.action_spaces['supervisor'].sample()] self.reset()
Ic5 = (2 * Ic / bjt['beta_1mA']) vbe5 = bjt['n'] * g51.VT * np.log( Ic5 / \ (bjt['Is'] * (1 + ((Vcc - Vbe)/abs(bjt['VA']))))) vce = Vbe + vbe5 vbe3 = bjt['n'] * g51.VT * np.log(Ic / \ (bjt['Is'] * ( 1 + (vce/abs(bjt['VA']))))) return vbe3 - Vbe Vcc = 5.0 Ic3 = 1e-3 f1_args = (pnp_2n3906, Ic3, Vcc) Vbe3 = optimize.root(f1, 0.6, args=f1_args).x[0] Ic5 = 2 * Ic3 / pnp_2n3906['beta_1mA'] Vce5 = Vcc - Vbe3 Vbe5 = eee51.bjt_find_vbe(Ic5, Vce5, \ pnp_2n3906['Is'], pnp_2n3906['n'], pnp_2n3906['VA']) Vce3 = Vbe3 + Vbe5 Vo1 = Vcc - Vce3 Ic1 = 1e-3 Vic = 1.8 def f1b(Vx, Ic1, Vo1, Vic, bjt): Vbe1 = eee51.bjt_find_vbe(Ic1, Vo1 - Vx, \
def transition_arc(self, Rstar0, vmin, vmax, angle, delta_v): """ lower transition arc function Args: Rstar0 (float) : initial R* vmin (float) : small v(Prandtle-Meyer angle) [deg] vmax (float) : large v(Prandtle-Meyer angle) [deg] angle (float) : rotate angle from Y* to y* [deg] delta_v (float) : interval Prandtle-Meyer angle [deg] """ kmin = 1 kmax = int((vmax - vmin) / delta_v) + 1 k = np.arange(kmin, kmax) xstar_l = np.zeros(k.size) ystar_l = np.zeros(k.size) xstar_l[-1] = 0 ystar_l[-1] = Rstar0 func_Rstar = 2 * np.radians(vmax) - np.pi / 2 * (np.sqrt( (self.gamma + 1) / (self.gamma - 1)) - 1) - np.radians(2 * (k - 1) * delta_v) def func(Rstar, func_Rstar_i): return 2 * self.chara_line(Rstar) - func_Rstar_i Rstar = np.zeros(func_Rstar.size) for (i, f_Rstar) in enumerate(func_Rstar): sol = optimize.root(func, Rstar0, args=(f_Rstar)) Rstar[i] = sol.x[0] fai_k = np.radians(vmax - vmin - (k - 1) * delta_v) xstar_k = -Rstar * np.sin(fai_k) ystar_k = Rstar * np.cos(fai_k) myu_k = -np.arcsin( np.sqrt(((self.gamma + 1) / 2) * Rstar**2 - (self.gamma - 1) / 2)) m_k = [] for (i, j) in enumerate(k[:-1]): m_k += [ np.tan((fai_k[i] + fai_k[j]) / 2 + (myu_k[i] + myu_k[j]) / 2) ] mbar_k = np.tan(fai_k[1:]) Xstar_l, Ystar_l = self.rotate(xstar_l[-1], ystar_l[-1], angle) x, y = [Xstar_l], [Ystar_l] xprev = 0 for i in range(kmax - kmin - 2, 0, -1): a = ystar_l[i + 1] - mbar_k[i] * xstar_l[i + 1] b = ystar_k[i] - m_k[i] * xstar_k[i] c = m_k[i] - mbar_k[i] xstar_l[i] = (a - b) / c ystar_l[i] = (m_k[i] * a - mbar_k[i] * b) / c if (angle > 0): xtemp = xstar_l[i] assert xtemp < xprev, "initial vu or vl must be changed" else: xtemp = -xstar_l[i] assert xtemp > xprev, "initial vu or v0 must be changed" Xstar_l, Ystar_l = self.rotate(xtemp, ystar_l[i], angle) x += [(Xstar_l)] y += [(Ystar_l)] xprev = xtemp return x, y
def calc_MB(self, *args, retnumrates=False): params, NT, Rstar = self.calc_params(*args) R, V, GB, Gt, Gd, Ntmax, Rt, Ges, NTw, eta, P, D = params # Steady state values t = 0 # dummy var. for rate eq. Nqp0, Nt0, Nw0 = root( self.rateeq, [NT, NT / 2, NTw], args=(t, params), tol=1e-12, jac=self.jac, method="hybr", ).x # M and B matrices M = np.array([ [ Gt * (Ntmax - Nt0) + (2 * Rstar * Nqp0 + 0.5 * Rt * Nt0) / V, -Gd - Gt * Nqp0 - Rt * Nqp0 / (2 * V), ], [ -Gt * (Ntmax - Nt0) + Rt * Nt0 / (2 * V), Gd + Gt * Nqp0 + Rt * Nqp0 / (2 * V), ], ]) B = np.array([ [ Gt * (Ntmax - Nt0) * Nqp0 + Gd * Nt0 + (4 * Rstar * (Nqp0**2 + NT**2) + 5 * Rt * Nt0 * Nqp0) / (2 * V), -Gt * (Ntmax - Nt0) * Nqp0 - Gd * Nt0 - Rt * Nqp0 * Nt0 / (2 * V), ], [ -Gt * (Ntmax - Nt0) * Nqp0 - Gd * Nt0 - Rt * Nqp0 * Nt0 / (2 * V), Gt * (Ntmax - Nt0) * Nqp0 + Gd * Nt0 + Rt * Nqp0 * Nt0 / (2 * V), ], ]) # M = np.array([[Gt*(Ntmax-Nt0)+2*Rstar*Nqp0/V+Rt*Nt0/(2*V),-Gd-Gt*Nqp0+Rt*Nqp0/(2*V)], # [-Gt*(Ntmax-Nt0)-Rt*Nt0/(2*V),Gd+Gt*Nqp0-Rt*Nqp0/(2*V)]]) # B = np.array([[Gt*(Ntmax-Nt0)*Nqp0+Gd*Nt0+4*Rstar*Nqp0**2/V+Rt*Nqp0*Nt0/(2*V), # -Gt*(Ntmax-Nt0)*Nqp0-Gd*Nt0-Rt*Nqp0*Nt0/(2*V)], # [-Gt*(Ntmax-Nt0)*Nqp0-Gd*Nt0-Rt*Nqp0*Nt0/(2*V), # Gt*(Ntmax-Nt0)*Nqp0+Gd*Nt0+5*Rt*Nqp0*Nt0/(2*V)]]) # M = np.array([[Gt*(Ntmax-Nt0)+2*Rstar*Nqp0/V+Rt*Nt0/(2*V),-Gd-Gt*Nqp0+Rt*Nqp0/(2*V)], # [-Gt*(Ntmax-Nt0)+Rt*Nt0/(2*V),Gd+Gt*Nt0+Rt*Nqp0/(2*V)]]) # B = np.array([[Gt*(Ntmax-Nt0)*Nqp0+Gd*Nt0+4*Rstar*Nqp0**2/V+Rt*Nqp0*Nt0/V, # -Gt*(Ntmax-Nt0)*Nqp0-Gd*Nt0], # [-Gt*(Ntmax-Nt0)*Nqp0-Gd*Nt0, # Gt*(Ntmax-Nt0)*Nqp0+Gd*Nt0+Rt*Nqp0*Nt0/V]]) if retnumrates: return ( M, B, { "NqpT": NT, "Nqp0": Nqp0, "Nt0": Nt0, "Nw0": Nw0 }, { "R*NqpT/2V": R * NT / (2 * V), "R*Nqp0/2V": R * Nqp0 / (2 * V), "Rt*Nt0/2V": Rt * Nt0 / (2 * V), "T*(Ntmax-Nt0)": Gt * (Ntmax - Nt0), "Gd": Gd, }, ) else: return M, B
def SteadyState(self): w = self.wbar A = 1. MP_shock = 1. G_shock = 1. etam = 1.0 S = 1.0 SA = S pi = 1. pstar = 1. # six equations in h, Y, H, q, J, u # guess Y, J, and Vn def g(X, Mode='Residuals'): Y, J, Vn = X #unpack h = ((1 - self.tau) * w * S * Y / (A * (Y - J)))**(1. / (1. + gamma)) M = ((A / mu - w) * h / psi_1 / upsilon)**(1 / psi_2) q = (M * Vn)**(1.0 / kappa) u = upsilon * (1 - q * M) / (q * M + upsilon * (1 - q * M)) H = 1 - u - (1 - upsilon) * (1 - u) # check Y, J, Vn Y2 = A * h * (1 - u) J2 = psi_1 * M**psi_2 * H Vn2 = (-log(self.b) - h**(1 + gamma) / (1 + gamma) + psy) / (1 - beta * (1 - upsilon) * (1 - kappa / (1 + kappa) * q * M)) if Mode.lower() == 'residuals': return np.array((Y2 - Y, J2 - J, Vn2 - Vn)) elif Mode.lower() == 'values': return Y, J, h, q, u, H, M, Vn else: raise Exception('Unrecognized value for Mode') sol = optimize.root(g, (Ycalib, Jcalib, Vncalib), jac=False) Y, J, h, q, u, H, M, Vn = g(sol.x, Mode='values') IP_Moments = self.IP.get_Moments(u, u, self.tau) ElogAlpha = (1 - delta) * IP_Moments[1] / delta EAlph = float(delta / (1.0 - (1.0 - delta) * IP_Moments[0])) EU = upsilon * (1 - q * M) I = 1.0 / (beta * ((1 - EU) + EU / self.b) * IP_Moments[2]) C = (Y - J) / (1 + chi) G = chi * C pB = Y / (1 - (1 - theta) / I) pA = pB MU = 1.0 / C dVndb = -1. / self.b / (1 - beta * (1 - upsilon) * (1 - q * M)) X = np.array((A, G_shock, EAlph, ElogAlpha, u, M, Vn, 0., 0., 0., 0., Y, G, Y, h, w, u, J, q, MU)) V = np.dot( np.linalg.inv( np.eye(len(iVRange)) - np.diag(self.Discounting(X).flatten())), self.PeriodUtility(X)) X[iVRange] = V.flatten() return X
def nonlinear_triangulation(kp1, kp2, K, R, T, matches): """ Here We Suppose the 1st Camera Coordination is the refence coordination input kp1: list of key points of first camera input kp2: list of key points of second camera input K : intrisic matrix of second camera input R : the rotation matrix of camera 2 related to camera 1 input C : the word coordinate of camera 1 related to camera 2 input matches: a list of DMatch between kp1 and kp2 output points3D: a list of 3D points after triangulation """ def make_target(p1_2d, p2_2d): def func(x): point_3d = np.array([x[0], x[1], x[2], 1]) RT = np.column_stack([np.eye(3), np.zeros((3, 1))]) P = np.dot(K, RT) RT_p = np.column_stack([R, T]) P_p = np.dot(K, RT_p) U = np.dot(P, np.array([x[0], x[1], x[2], 1])) U = point_normalize(U)[:-1] U_p = np.dot(P_p, np.array([x[0], x[1], x[2], 1])) U_p = point_normalize(U_p)[:-1] # f f = [np.sum(np.square(p1_2d - U) + np.square(p2_2d - U_p)), 0, 0] # df ??? def jacob(K, RC, p_2d, point_3d): f_x, f_y, c_x, c_y = K[0][0], K[1][1], K[0][2], K[1][2] r_0, r_1, r_2 = RC[0], RC[1], RC[2] u, v = p_2d[0], p_2d[1] A = f_x * r_0.dot(point_3d) + c_x * r_2.dot(point_3d) dA_dx = f_x * r_0[0] + c_x * r_2[0] dA_dy = f_x * r_0[1] + c_x * r_2[1] dA_dz = f_x * r_0[2] + c_x * r_2[2] B = r_2.dot(point_3d) dB_dx = r_2[0] dB_dy = r_2[1] dB_dz = r_2[2] C = f_y * r_1.dot(point_3d) + c_y * r_2.dot(point_3d) dC_dx = f_y * r_1[0] + c_y * r_2[0] dC_dy = f_y * r_1[1] + c_y * r_2[1] dC_dz = f_y * r_1[2] + c_y * r_2[2] df_dx = 2 * (u - A / B) * (-(dA_dx * B - A * dB_dx) / pow( B, 2)) + 2 * (v - C / B) * (-(dC_dx * B - C * dB_dx) / pow(B, 2)) df_dy = 2 * (u - A / B) * (-(dA_dy * B - A * dB_dy) / pow( B, 2)) + 2 * (v - C / B) * (-(dC_dy * B - C * dB_dy) / pow(B, 2)) df_dz = 2 * (u - A / B) * (-(dA_dz * B - A * dB_dz) / pow( B, 2)) + 2 * (v - C / B) * (-(dC_dz * B - C * dB_dz) / pow(B, 2)) return [df_dx, df_dy, df_dz] # for 1st cam [df_dx_1, df_dy_1, df_dz_1] = jacob(K, RT, p1_2d, point_3d) # for 2nd cam [df_dx_2, df_dy_2, df_dz_2] = jacob(K, RT_p, p2_2d, point_3d) df_dx = df_dx_1 + df_dx_2 df_dy = df_dy_1 + df_dy_2 df_dz = df_dz_1 + df_dz_2 df = np.array([[df_dx, df_dy, df_dz], [0, 0, 0], [0, 0, 0]]) return f, df return func ret = [] points3D_0 = linear_triangulation(kp1, kp2, K, R, T, matches) for match, point3D_0 in zip(matches, points3D_0): p1_idx = match.queryIdx p2_idx = match.trainIdx p_1, p_2 = kp1[p1_idx], kp2[p2_idx] u, v = p_1.pt u_p, v_p = p_2.pt func = make_target(np.array([u, v]), np.array([u_p, v_p])) # do unit test here def unit_test_func(dx, dy, dz): return x0, y0, z0 = 10., 20, 3.0 x, y, z = x0, y0, z0 f_0, df_0 = func([x, y, z]) print([x, y, z], f_0[0]) x, y, z = x0 + dx, y0 + dy, z0 + dz f_1, df_1 = func([x, y, z]) print([x, y, z], f_1[0]) x, y, z = x0 + dx / 2, y0 + dy / 2, z0 + dz / 2 f_2, df_2 = func([x, y, z]) print([x, y, z], f_2[0]) if dx > 0.000001: print("Estimated Dx:", df_2[0][0]) print("True Dx:", (f_1[0] - f_0[0]) / dx) if dy > 0.000001: print("Estimated Dy:", df_2[0][1]) print("True Dy:", (f_1[0] - f_0[0]) / dy) if dz > 0.000001: print("Estimated Dz:", df_2[0][2]) print("True Dz:", (f_1[0] - f_0[0]) / dz) #unit_test_func(0.001, 0, 0) #unit_test_func(0.0001, 0, 0) #unit_test_func(0.00001, 0, 0) #unit_test_func(0, 0.001, 0) #unit_test_func(0, 0.0001, 0) #unit_test_func(0, 0.00001, 0) #unit_test_func(0., 0, 0.01) #unit_test_func(0., 0, 0.001) #unit_test_func(0., 0, 0.0001) #print("-"*80) #print("Linear Optimized:", point3D_0) point3D_0[0] += 4 point3D_0[1] += 0 point3D_0[2] += 0 #print("Initial Value(Distorted) for Non-Linear Optimizer:", point3D_0) sol = root(func, [point3D_0[0], point3D_0[1], point3D_0[2]], jac=True, method='lm') #print("Non-Linear Optimized:", sol.x) ret.append(sol.x) return ret
def solve(self, circuit, initial_conditions, **kwargs): ndarray_initial_conditions = np.array(initial_conditions) self._solution = root(self._get_equations_error, ndarray_initial_conditions, args=circuit) return self._adapt_solution_to_solution_results()
h_se = h_r + h_cv alpha_s = h_se return alpha_s #传热方程组设立 def GB50264_delta_to_T_s(x): Q, T_1, T_2, T_s = x[0], x[1], x[2], x[3] return np.array([(T_0 - T_1) / (delta_1 / lamb(material_1, T_0, T_1)) - Q, (T_1 - T_2) / (delta_2 / lamb(material_2, T_1, T_2)) - Q, (T_2 - T_s) / (delta_3 / lamb(material_3, T_2, T_s)) - Q, (T_s - T_a) / (1 / alpha_s(T_s, T_a, v, H)) - Q]) #传热方程组求解 sol_root = root(GB50264_delta_to_T_s, [Q_max, T_1_assumption, T_2_assumption, T_s_assumption]) sol_fsolve = fsolve(GB50264_delta_to_T_s, [Q_max, T_1_assumption, T_2_assumption, T_s_assumption]) Q = sol_fsolve[0] T_1 = sol_fsolve[1] T_2 = sol_fsolve[2] T_s = sol_fsolve[3] #打印结果 print(">>>>>>>>>>> When the delta_1 delta_2 delta_3 is ", delta_1, delta_2, delta_3, " :") print(" delta_1 = ", delta_1) print(" delta_2 = ", delta_2) print(" delta_3 = ", delta_3) print(" lamb_1 = ", lamb(material_1, T_0, T_1)) print(" lamb_2 = ", lamb(material_2, T_1, T_2))
from scipy.optimize import root from math import pow def diff(x): return marketPrice - (1 + (c / x - 1) * (1 - pow((1 + x * dt), -(T / dt)))) T = 4 #time to maturity dt = 0.5 #the step time marketPrice = (106 + 21.125 / 32) / 100 #current market price c = 0.0675 #coupon rate sol = root(diff, 0.2) print(sol.x)
def calculate_consistent_initial_conditions(self, rhs, algebraic, y0_guess, jac=None): """ Calculate consistent initial conditions for the algebraic equations through root-finding Parameters ---------- rhs : method Function that takes in t and y and returns the value of the differential equations algebraic : method Function that takes in t and y and returns the value of the algebraic equations y0_guess : array-like Array of the user's guess for the initial conditions, used to initialise the root finding algorithm jac : method Function that takes in t and y and returns the value of the jacobian for the algebraic equations Returns ------- y0_consistent : array-like, same shape as y0_guess Initial conditions that are consistent with the algebraic equations (roots of the algebraic equations) """ pybamm.logger.info("Start calculating consistent initial conditions") # Split y0_guess into differential and algebraic len_rhs = rhs(0, y0_guess).shape[0] y0_diff, y0_alg_guess = np.split(y0_guess, [len_rhs]) def root_fun(y0_alg): "Evaluates algebraic using y0_diff (fixed) and y0_alg (changed by algo)" y0 = np.concatenate([y0_diff, y0_alg]) out = algebraic(0, y0) pybamm.logger.debug( "Evaluating algebraic equations at t=0, L2-norm is {}".format( np.linalg.norm(out))) return out if jac: if issparse(jac(0, y0_guess)): def jac_fn(y0_alg): """ Evaluates jacobian using y0_diff (fixed) and y0_alg (varying) """ y0 = np.concatenate([y0_diff, y0_alg]) return jac(0, y0)[:, len_rhs:].toarray() else: def jac_fn(y0_alg): """ Evaluates jacobian using y0_diff (fixed) and y0_alg (varying) """ y0 = np.concatenate([y0_diff, y0_alg]) return jac(0, y0)[:, len_rhs:] else: jac_fn = None # Find the values of y0_alg that are roots of the algebraic equations sol = optimize.root( root_fun, y0_alg_guess, jac=jac_fn, method=self.root_method, tol=self.root_tol, ) # Return full set of consistent initial conditions (y0_diff unchanged) y0_consistent = np.concatenate([y0_diff, sol.x]) if sol.success and np.all(sol.fun < self.root_tol * len(sol.x)): pybamm.logger.info( "Finish calculating consistent initial conditions") return y0_consistent elif not sol.success: raise pybamm.SolverError( "Could not find consistent initial conditions: {}".format( sol.message)) else: raise pybamm.SolverError(""" Could not find consistent initial conditions: solver terminated successfully, but maximum solution error ({}) above tolerance ({}) """.format(np.max(sol.fun), self.root_tol * len(sol.x)))
m.degrees(10) #в градусы m.inf * m.e * m.pi # бесконечность умножить на е и умножить на пи так же есть m.nan m1 = np.matrix([[1, 2, 3], [5, 5, 6]]) m2 = np.matrix([[3, 2], [4, 2], [1, 1]]) m1 * m2 import matplotlib.pyplot as plt x = np.arange(0.0, np.pi * 2.0, 0.1) # генерируем числа на интервале от нуля до 2пи с шагом 0.1 y1 = np.sin(x) #строим синус y2 = np.cos(x) #строим косинус plt.plot(x, y1, x, y2) # строим график синуса и косинуса plt.axis([ 0, 2 * np.pi, -1.1, 1.1 ]) # строим оси, (ось х начало,ось х конец, ось у начало, ось у конец ) plt.xlabel('$\\alpha, rad') plt.ylabel('f(x)') plt.legend(["sin", "cos"]) plt.show() def func(x): ''' x + 2cos(x) = 0 ''' return x + 2 * np.cos(x) sol = root(func, 0.3) print(sol.x)
NU = 50 Uls = linspace(0., 10., NU) dlt = 0.01 Ne = 100 Tmesh = linspace(1e-2, 5., NT) #Temperature kmesh = linspace(-pi, pi, Nk) #kmesh #Hubbard U.It is strange that U has to be so high(as 10) to have a magnetization at low temperature. #because the dos of paramagntic state at half filling is diverging(according to Mahan,Uc=0...) ekls = [] for kx in kmesh: for ky in kmesh: ekls.append(-2.0 * t * (cos(kx) + cos(ky))) #Band dispersion ekls = array(ekls) #DOS() nls = [0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6] for T in Tmesh: print T for n in nls: fmag = open("mag_neq" + str(n) + ".txt", 'w') print >> fmag, "#occupation n=", n, "T=", T print >> fmag, "#U,|m|,mu,sucess" for U in Uls: print "U=", U sol = optimize.root(selffuns, [n * U / 2., 10.0], args=(n, T, U), method="anderson") ##(mu,m) print >> fmag, U, abs(sol.x[1]), sol.x[0], sol.success if sol.success == 0: break print sol.success fmag.close()
def get_SS(bss_guess, args, graphs=False): ''' -------------------------------------------------------------------- Solve for the steady-state solution of the S-period-lived agent OG model with exogenous labor supply using one root finder in bvec -------------------------------------------------------------------- INPUTS: bss_guess = (S-1,) vector, initial guess for b_ss args = length 8 tuple, (nvec, beta, sigma, A, alpha, delta, SS_tol, SS_EulDiff) graphs = boolean, =True if output steady-state graphs OTHER FUNCTIONS AND FILES CALLED BY THIS FUNCTION: SS_EulErrs() aggr.get_K() aggr.get_L() aggr.get_Y() aggr.get_C() firms.get_r() firms.get_w() hh.get_cons() utils.print_time() get_ss_graphs() OBJECTS CREATED WITHIN FUNCTION: start_time = scalar > 0, clock time at beginning of program nvec = (S,) vector, exogenous lifetime labor supply n_s beta = scalar in (0,1), discount factor for each model per sigma = scalar > 0, coefficient of relative risk aversion A = scalar > 0, total factor productivity parameter in firms' production function alpha = scalar in (0,1), capital share of income delta = scalar in [0,1], model-period depreciation rate of capital SS_tol = scalar > 0, tolerance level for steady-state fsolve SS_EulDiff = Boolean, =True if want difference version of Euler errors beta*(1+r)*u'(c2) - u'(c1), =False if want ratio version [beta*(1+r)*u'(c2)]/[u'(c1)] - 1 b_args = length 7 tuple, args passed to opt.root(SS_EulErrs,...) results_b = results object, output from opt.root(SS_EulErrs,...) b_ss = (S-1,) vector, steady-state savings b_{s+1} K_ss = scalar > 0, steady-state aggregate capital stock Kss_cstr = boolean, =True if K_ss < epsilon L = scalar > 0, exogenous aggregate labor r_params = length 3 tuple, (A, alpha, delta) r_ss = scalar > 0, steady-state interest rate w_params = length 2 tuple, (A, alpha) w_ss = scalar > 0, steady-state wage c_args = length 3 tuple, (nvec, r_ss, w_ss) c_ss = (S,) vector, steady-state individual consumption c_s Y_params = length 2 tuple, (A, alpha) Y_ss = scalar > 0, steady-state aggregate output (GDP) C_ss = scalar > 0, steady-state aggregate consumption b_err_ss = (S-1,) vector, Euler errors associated with b_ss RCerr_ss = scalar, steady-state resource constraint error ss_time = scalar > 0, time elapsed during SS computation (in seconds) ss_output = length 10 dict, steady-state objects {b_ss, c_ss, w_ss, r_ss, K_ss, Y_ss, C_ss, b_err_ss, RCerr_ss, ss_time} FILES CREATED BY THIS FUNCTION: None RETURNS: ss_output -------------------------------------------------------------------- ''' start_time = time.clock() nvec, beta, sigma, A, alpha, delta, SS_tol, SS_EulDiff = args b_args = (nvec, beta, sigma, A, alpha, delta, SS_EulDiff) results_b = opt.root(SS_EulErrs, bss_guess, args=(b_args)) b_ss = results_b.x K_ss, Kss_cstr = aggr.get_K(b_ss) L = aggr.get_L(nvec) r_params = (A, alpha, delta) r_ss = firms.get_r(K_ss, L, r_params) w_params = (A, alpha) w_ss = firms.get_w(K_ss, L, w_params) c_args = (nvec, r_ss, w_ss) c_ss = hh.get_cons(b_ss, 0.0, c_args) Y_params = (A, alpha) Y_ss = aggr.get_Y(K_ss, L, Y_params) C_ss = aggr.get_C(c_ss) b_err_ss = results_b.fun RCerr_ss = Y_ss - C_ss - delta * K_ss ss_time = time.clock() - start_time ss_output = { 'b_ss': b_ss, 'c_ss': c_ss, 'w_ss': w_ss, 'r_ss': r_ss, 'K_ss': K_ss, 'Y_ss': Y_ss, 'C_ss': C_ss, 'b_err_ss': b_err_ss, 'RCerr_ss': RCerr_ss, 'ss_time': ss_time } print('b_ss is: ', b_ss) print('K_ss=', K_ss, ', r_ss=', r_ss, ', w_ss=', w_ss) print('Max. abs. savings Euler error is: ', np.absolute(b_err_ss).max()) print('Max. abs. resource constraint error is: ', np.absolute(RCerr_ss).max()) # Print SS computation time utils.print_time(ss_time, 'SS') if graphs: get_ss_graphs(c_ss, b_ss) return ss_output
return c def g(x): d,b=32,52 c=((2*np.cosh(x))**(d-1)+(2*np.sinh(x))**(d-1))/ ((2*np.cosh(x))**d+(2*np.sinh(x))**d)-b c= float(c) return c #####################INFERENCE########################## h_est,J_est=3,3 EMrepeat,thermAv=100,100 inference=np.ones(d) p=[0.0,0.0] for t in range(EMrepeat): #E-step GibbsSampling(100, h_est, J_est,inference,dameged)#SSE a,b=0,0 for i in range(thermAv): GibbsSampling(3,h_est,J_est,inference,dameged) a+=np.dot(inference,dameged)/d b+=xixj(inference) a/=thermAv b/=thermAv #M-step h_est=np.arctanh(a) p[0],p[1]=d,b #J_est=fsolve(f,1.0,args=p) p = np.array(p, dtype=np.float) J_est=root(g,0.1) print("#h_est=",h_est) GibbsSampling(100,h,J,original,dameged)
def guess_create(equations, guess, c_list, K_list): root_func = lambda X0: equations(X0, c_list, K_list) solution = root(root_func, guess, method='lm', tol=1e-10) return solution.x
f.write( "# N, mean_cd1_mast,mean_cd1,mean_ml,std_cd1mast/sqrtM,std_cd1/sqrtM,std_ml/sqrtM \n" ) for N in N_list: cd1_mast_list = np.zeros(M) cd1_list = np.zeros(M) ml_list = np.zeros(M) for m in range(M): set_data = mean_x(h0, N) m_model, m_data = 100, np.mean(set_data[1]) if (abs(m_data) != N): args_cd1_master = (set_data[1]) args_cd1 = (m_data, set_data[1]) args_ml = (m_data) sol_cd1_mast = optimize.root(eq_cd1_master, h_init, args=args_cd1_master).x[0] sol_cd1 = optimize.root(eq_cd1, h_init, args=args_cd1).x[0] sol_ml = optimize.root(eq_ml, h_init, args=args_ml).x[0] cd1_mast_list[m], cd1_list[m], ml_list[ m] = sol_cd1_mast, sol_cd1, sol_ml m_cd1_mas = abs(np.mean(cd1_mast_list)) - h0 m_cd1 = abs(np.mean(cd1_list)) - h0 m_ml = abs(np.mean(ml_list)) - h0 sqtM = np.sqrt(M) std_cd1_mas = np.std(cd1_mast_list) / sqtM std_cd1 = np.std(cd1_list) / sqtM std_ml = np.std(ml_list) / sqtM f.write( str(N) + " " + str(m_cd1_mas) + " " + str(std_cd1_mas) + " " + str(m_cd1) + " " + str(std_cd1) + " " + str(m_ml) +
(cs - k)**2 + k_arr[i + 1]**2) res.append(np.abs(wl - wk) * sigmaf) else: epsfl = epsf0l[i] + depsfl * cs - 2. * depsfl * l epsf0l.append(epsfl) epsfk = epsf0k[i] + depsfk * cs - 2. * depsfk * k epsf0k.append(epsfl) res.append((np.abs(epsfl) + np.abs(epsfk)) / 2. * Ef - sigmaf) wl = (epsfl - (cs - l) / 2. * depsfl) * 2. * (cs - l) wk = (epsfk - (cs - k) / 2. * depsfk) * 2. * (cs - k) res.append(np.abs(wl - wk) * sigmaf) return np.array(res) result = root(residuum, np.ones(N) * 4., method='krylov') print result.x print residuum(result.x) residuum([ 44.07025239, 1.97554396, 1.21636174, 2.98268599, 21.77892428, 4.60733681, 1.77084082, 2.9111265, ]) l1_arr = np.hstack((0.0, result.x[1:N / 2])) l2_arr = np.hstack((result.x[0], cs - l1_arr[1:]))
# MINIMA VELOCIDAD DE FLUIDIZACIÓN #Ecuacion de minima velocidad de fluidización #(1.75/(epsilon_mf**3*fi_s))*(((d_p*u_mf*rho_g)/mi_g)**2)+((150*(1-epsilon_mf))/(epsilon_mf**3*fi_s**2))*((d_p*u_mf*rho_g)/mi_g)=((d_p**3*rho_g*(rho_s-rho_g)*g)/mi_g**2) #Calculo epsilon_mf eta=g*(rho_s-rho_g) epsilon_mf=(0.586*fi_s**(-0.72))*(((mi_g**2)/(rho_g*eta*d_p**3))**0.029)*((rho_g/rho_s)**0.021) print('epsilon_mf=',epsilon_mf) #Resolución de la ecuación para hallar la velocidad minima de fluidizacion def f_u_mf(x_u_mf, epsilon_mf, fi_s, d_p, rho_g, mi_g): """ Resolución de la ecuación para hallar la velocidad minima de fluidizacion """ return (1.75/(epsilon_mf**3*fi_s))*(((d_p*x_u_mf*rho_g)/mi_g)**2)+((150*(1-epsilon_mf))/(epsilon_mf**3*fi_s**2))*((d_p*x_u_mf*rho_g)/mi_g)-((d_p**3*rho_g*(rho_s-rho_g)*g)/mi_g**2) u_mf=optimize.root(f_u_mf, 1, args=(epsilon_mf, fi_s, d_p, rho_g, mi_g)) u_mf=np.float_(u_mf.x) print ('u_mf (m/s) =',u_mf) # VELOCIDAD TERMINAL DE FLUIDIZACION d_p_prima=d_p*((rho_g*(rho_s-rho_g)*g)/(mi_g**2))**(1/3) u_t_prima=((18/d_p_prima**2)+((2.335-1.744*fi_s)/(d_p_prima**0.5)))**(-1) # Ecuación de velocidad terminal #u_t_prima=u_t*((rho_g**2)/(mi_g*(rho_s-rho_g)*g))**(1/3)
"""" README ====== This file contains Python codes. ====== """ """ General nonlinear solvers - with a solution """ import scipy.optimize as optimize y = lambda x: x**3 + 2.*x**2 - 5. dy = lambda x: 3.*x**2 + 4.*x print (optimize.fsolve(y, 5., fprime=dy)) print (optimize.root(y, 5.))
from scipy import optimize # Global optimization grid = (-10, 10, 0.1) xmin_global = optimize.brute(f, (grid, )) print("Global minima found %s" % xmin_global) # Constrain optimization xmin_local = optimize.fminbound(f, 0, 10) print("Local minimum found %s" % xmin_local) ############################################################ # Root finding ############################################################ root = optimize.root(f, 1) # our initial guess is 1 print("First root found %s" % root.x) root2 = optimize.root(f, -2.5) print("Second root found %s" % root2.x) ############################################################ # Plot function, minima, and roots ############################################################ import matplotlib.pyplot as plt fig = plt.figure(figsize=(6, 4)) ax = fig.add_subplot(111) # Plot the function ax.plot(x, f(x), 'b-', label="f(x)")