def solve_with_broyden_mixing(self, alpha, broyden_param): if self.dmft_param["occup_method"] == "broyden": def F(Delta_in, mu): if verbose(): print("(Broyden) Setting mu to %.18f" % mu) self.set_mu(mu) Delta_out = self.dmft_step(Delta_in) occup_factor = self.dmft_param.get("occup_factor", 1.0) return Delta_out - Delta_in, occup_factor * ( self.occupancy_goal - self.occupancy) npF = lambda x: wrap(*F(*unwrap(x, self.S, scalar=True)) ) # unpack the tuples xin = wrap(self.Delta, self.mu) else: def F(Delta): return self.dmft_step(Delta) - Delta npF = lambda x: bgf_to_nparray(F(nparray_to_bgf(x, self.S))) xin = bgf_to_nparray(self.Delta) bp = { "reduction_method": "svd", "max_rank": 20, "f_tol": 1e-99 } # Loop forever (small f_tol!) bp.update(broyden_param) optimize.broyden1(npF, xin, alpha=alpha, verbose=verbose(), **bp) raise Converged("broyden1() converged")
def solve(n): h = 1.0 / (n + 1) starting_guess = np.array([i * h for i in range(0, n + 2)]) ''' Using finite difference, we have: (1/h**2)*(u_{i + 1} + u_{i - 1} - 2u_i) = 10u_i^3 + 3u_i + (ih)**2 i = 1, 2, 3, ... n u_0 = 0 u_{n + 1} = 0 Hence, given x \in R^{n + 2}, we're finding the root to the above system of equations ''' def f(x): ''' x: ''' ans = np.zeros(n + 2) ans[0] = x[0] ans[-1] = x[-1] for i in range(1, n + 1): ans[i] = ((n + 1)**2) * (x[i + 1] + x[i - 1] - 2 * x[i]) + \ - 10 * (x[i]**3) - 3 * x[i] - (i * h)**2 return ans sol = broyden1(f, starting_guess, f_tol=EPS) return sol
def solve(self): """Solve the selfconsistent problem""" return self.iterate() # first iteration def r2z(v): # convert real to complex n = v.shape[0] // 2 return v[0:n] + 1j * v[n:2 * n] def z2r(v): # convert complex to real return np.concatenate([v.real, v.imag]) def fopt(cij): # function to return the error self.cij = r2z(cij) # store this vector self.cij2v() # update the v vectors self.iterate() # do an iteration print(self.cij) self.v2cij() # convert the v to cij return z2r(self.cij) - cij cij = optimize.broyden1(fopt, z2r(self.cij), f_tol=1e-8, max_rank=10) # cij = optimize.fsolve(fopt,z2r(self.cij),xtol=1e-8) # cij = optimize.anderson(fopt,z2r(self.cij),f_tol=1e-6,w0=0.1) # cij = optimize.newton_krylov(fopt,z2r(self.cij),f_tol=1e-6,outer_k=8) self.cij = cij self.cij2v() # update
def Solve(self): '''Determine the stellar Zanstra temperature from a nebular H or He emission line flux and the stellar flux density. ''' guess = 5.e+4 return op.broyden1(self.Func, guess)
def siglog_normal_init_guess(self, reg_pnts_array, pos_traj): """ get initial guess from registration points for the parameters of siglognormal model """ def make_sigma_equation(reg_pnts): """ input is a series of registration points t1 - t5 though only t1, t3, t5 are useful """ def sigma_estimator(sigma): #do float here, otherwise the second term will be ZERO!! return ((np.exp(-sigma**2+3*sigma) - 1) / (np.exp(sigma*6) - 1) - float(reg_pnts[2] - reg_pnts[0]) / (reg_pnts[4] - reg_pnts[0])) #return (np.exp(sigma**2) - 1) / (np.exp(6*sigma**2) - 1) - (reg_pnts[2] - reg_pnts[0]) / (reg_pnts[4] - reg_pnts[0]) return sigma_estimator init_guess = [] vel_profile=self.get_vel_profile(pos_traj)/self.dt for reg_pnts in reg_pnts_array: #make an estimator for sigma sig_est_func = make_sigma_equation(reg_pnts) #solve it init_sigma = (reg_pnts[4] - reg_pnts[0])/2*self.dt #<hyin/Dec-24-2014> solving the equation is still not clear and the results seem not right #more investigation is needed to know the derivation of the equation, e.g., how the units are consistent... #currently, use an even more simple heuristics... sig_sln = sciopt.broyden1(sig_est_func, init_sigma, f_tol=1e-14) #try direct nonlinear optimization, note the returned function is modified with square #see sigma_estimator above #sig_sln = sciopt.fminbound(sig_est_func, 0, init_sigma*3) #search between (0, 3*init_sigma) #print sig_sln, sig_est_func(sig_sln) sig = sig_sln #only need scalar value #sig = init_sigma if sig <= 0: #will this happen? #this will happen when actual mode locates on the right side of 'Gaussian mean' #lognormal distribution is asymmetrical in regards of mode, but does it always distribute more mass on left side? #(okay, i know it's long tail, more mass means some more slopeness when going up) sig = np.abs(sig) a_array = np.array([3*sig, 1.5*sig**2+sig*np.sqrt(0.25*sig**2+1), sig**2, 1.5*sig**2-sig*np.sqrt(0.25*sig**2+1), -3*sig]) #estimate mu mu_1 = np.log((reg_pnts[2]-reg_pnts[0])*self.dt/(np.exp(-a_array[2])-np.exp(-a_array[0]))) mu_2 = np.log((reg_pnts[4]-reg_pnts[0])*self.dt/(np.exp(-a_array[4])-np.exp(-a_array[0]))) mu = (mu_1 + mu_2)/2 #estimate D D_array = np.array([np.sqrt(np.pi*2)*vel_profile[i]*np.exp(mu)*sig *np.exp((a_array[i]**2/(2*sig**2)-a_array[i])) for i in range(len(a_array))]) D = np.average(D_array) #estimate t0 t0_array = np.array([reg_pnts[i]*self.dt - np.exp(mu)*np.exp(-a_array[i]) for i in range(len(a_array))]) t0 = np.average(t0_array) theta_s, theta_e = self.siglog_normal_init_ang_guess((D, t0, mu, sig), pos_traj, reg_pnts) #add init_guess.append((D, t0, mu, sig, theta_s, theta_e)) return init_guess
def _fetch_ic(x0, dx0, system, func, eps=0.001): if isinstance(x0, list): assert len(x0) == len(system.state_vars) X0 = np.array(x0, dtype=np.float64) elif isinstance(x0, dict): X0 = np.array([np.NaN for _ in system.state_vars], dtype=np.float64) for k, v in x0.items(): *_, idx = str(k).split('_') idx = int(idx) X0[idx] = v elif isinstance(x0, (int, float, complex)) and len(system.state_vars) == 1: X0 = np.array([x0], dtype=np.float64) elif isinstance(x0, np.ndarray) and x0.shape == (len(system.state_vars), ): X0 = x0 else: raise ModelException(f"Invalid Initial Conditions: {x0}") if dx0: DX0 = np.array(dx0, dtype=np.float64) else: DX0 = np.zeros(X0.shape, dtype=np.float64) # if we don't have consistent initial conditions; find them if we can # fail if we can't f = lambda y: func(y, X0, 0, 0) if np.linalg.norm(f(DX0)) > eps: DX0 = broyden1(f, DX0) if np.linalg.norm(f(DX0)) > 0.001: raise ModelException(f"Inconsistent initial conditions: " f"Could not find dx0 for the given x0 {x0}") return X0, DX0
def method_of_moments_estimator(sequence=None, attributes=None, cache=None): """ Simple Method-of-Moments Estimator to estimate D (Haas et al, 1995) can be optimised (training rate, stopping value) d = d_moments(l - e^(-n))/d_moments) solve for d_moments in d = d_moments(l - e^(-n))/d_moments) :param sequence: sample sequence of integers :type sequence: array of ints :param attributes: dictionary with keys as the unique elements and values as counts of those elements :type attributes: dictionary where keys can be any type, values must be integers :param cache: argument used by median methods to avoid recomputation of variables :type cache: dictionary with 4 elements {"n":no_elements,"d":no_unique_elements,"attr": attribute_counts, "freq":frequency_dictionary} :return: estimated distinct count :rtype: float """ if sequence is None and attributes is None and cache is None: raise Exception( "Must provide a sequence, or a dictionary of attribute counts ") if cache is not None: n, d, frequency_dictionary = cache["n"], cache["d"], cache["freq"] elif sequence is not None: n, d, _, frequency_dictionary = precompute_from_seq(sequence) else: n, d, _, frequency_dictionary = precompute_from_attr(attributes) if n == d: return _compute_birthday_problem_probability(d) def diff_eqn(D): return D * (1 - np.exp((-n / D))) - d warnings.filterwarnings('ignore') try: d_moments_1 = float(broyden1(diff_eqn, d)) except Exception as e: print(e) d_moments_1 = 1000000000000000000000000 try: d_moments_2 = float(broyden2(diff_eqn, d)) except: d_moments_2 = 1000000000000000000000000 warnings.resetwarnings() result = min(d_moments_1, d_moments_2) if result == 1000000000000000000000000: return d else: return result
def WO_Model_con2(u): x_guess = np.ones((5, 1)) * 0.2 WO_f_model = functools.partial(WO_nonlinear_f_model, u) x_solved = broyden1(WO_f_model, x_guess, f_tol=1e-12) # calculating con1 con2 = x_solved[4, 0] - 0.08 return -con2
def __init__(self, sb, sf): self.L = (sb + sf) * 1.0 self.f = sb / self.L try: self.h = opt.broyden1(self.totalLengthSolver, [1], f_tol=.0001)[0] except: self.h = 0 self.x = self.f self.y = 0 else: try: self.x = opt.broyden1(self.partialLengthSolver, [0.25 + ((self.f > 0.5) * 0.5)], f_tol=0.001)[0] self.y = self.h * (1.0 - 4.0 * (self.x - 0.5)**2.0) except: self.x = .5 self.y = self.h
def finda(u,lookup=True): if lookup: import pickle as pk with open('au_lookup') as f: a,ul=pk.load(f) for j,uu in enumerate(ul): if uu>u: break if j>0: return a[j-1] else: return a[0] f=mua(u) if u==0.5: return 0.0 if u<.5: return broyden1(f,-10) return broyden1(f,10)
def SolveLambdaSystem(self, prec=1e-14): # x = optimize.broyden1(self.LambdaSystem, [0.00001,0.00001], f_tol=prec) x = optimize.broyden1(self.LambdaSystem, [self.lh[0], self.lh[1]], f_tol=prec) self.l = x self.SetMatrix() self.MatrixExponent() p0 = dot(self.MET, self.P0[0]) p1 = dot(self.MET, self.P0[1]) return [x, [p0, p1]]
def givePayOff(self, user, v): # returns the maximum pay-off of a user together with the effort needed for this maximum pay-off given the user's cost funciton, value of a badge, and the corresponding standard of that badge # pi(n) = v * p_win - c(n) = v * (1 - F(alpha - n)) - c(n) # solving the equation "v * f(alpha - n) - c'(n) = 0" gives you the effort that maximizes the pay-off F = pdf(self.pdf, v, self.standard, user, 0) effort = broyden1(F, 1) # print(effort) payOff = v * (1 - self.cdf(self.standard - effort)) - user.cost(effort) # print(1 - norm.cdf(self.standard - effort)) # iprint(payOff) return payOff, effort
def __call__(self): """Cumulative radiant energy at FSGP, savefig.""" self.pin = self.Pin(self.time(), self.track.location, clear) self.pin *= (self.pin >= 0) self.E_in = cuml_integral_left(self.pin, self.time()) self.E_total = self.car.E_0 + self.E_in[-1] self.P_avg = self.E_total / self.time.total() print(str(self.E_total) + " J") print(str(self.time.total()) + " s") print(str(self.P_avg) + " W") v = broyden1(lambda v: self.Pout(v, clear) - self.P_avg, 10) return v
def compute_ss(self, guess=None, method='fsolve', options={}): '''Attempts to solve for the steady state of the model. Args: guess: (Pandas Series, Numpy array, or list) An initial guess for the steady state solution. The result is highly sensisitve to the intial guess chosen, so be careful. If the guess is a Numpy ndarray or a list then the elements must be ordered to conform with self.names['variables']. method: (str) The function from the Scipy library to use. Your choices are: a. root b. fsolve (default) c. broyden1 d. broyden2 options: (dict) A dictionary of optional arguments to pass to the numerical solver. Check out the Scipy documentation to see the options available for each routine: http://docs.scipy.org/doc/scipy/reference/optimize.html Returns: None Attributes: ss: (Pandas Series) Steady state values of endogenous variables ''' if guess is None: guess = np.ones(self.n_vars) else: if isinstance(guess, pd.Series): guess = guess[self.names['variables']] # Create function for nonlinear solver def ss_fun(variables): variables = pd.Series(variables, index=self.names['variables']) return self.equilibrium_fun(variables, variables, self.parameters) if method == 'fsolve': steady_state = fsolve(ss_fun, guess, **options) elif method == 'root': steady_state = root(ss_fun, guess, **options)['x'] elif method == 'broyden1': steady_state = broyden1(ss_fun, guess, **options) elif method == 'broyden2': steady_state = broyden2(ss_fun, guess, **options) # Add ss attribute self.ss = pd.Series(steady_state, index=self.names['variables'])
def getDensityAltitude_exact(rho): """ Solves the ISA equations to determine the equivalent density Parameters ---------- rho : float, kg/m^3 atmospheric density """ def _f(h): atm=ISAtmosphere_simple(h) return atm.density-rho from scipy import optimize alt=optimize.broyden1(_f,0.0) return alt
def convert_inputs(mx, vx, rtype): ''' inputs: mx, vx, rtype: see attr class: mean, relative std, random variable type KEEP CONSISTENT UNITS (cm^2, m^2 , N, kN etc) -------------------------------------------- outputs: (loc,scale) or (scale,s --for ln), see scipy.stats package converts the input variables according to their rtype to a parameter form so that they keep the same mx and vx if putting the converts as parameters in the scipy.stats package ''' if rtype == "n": loc = mx scale = vx * abs(mx) return (loc, scale) elif rtype == "ln": def f(s): return (math.sqrt( (math.exp(s**2) - 1) * math.exp(2 * (math.log(mx) - (s**2) / 2.0) + s**2)) - vx * mx) s = float( broyden1(f, [0.5], f_tol=mx * 1e-13)) ##was fixed 13 -> but relatively makes more sense scale = float(math.log(mx) - (s**2) / 2.0) return (scale, s) elif rtype == "g": scale = float(math.sqrt(((((vx * mx)**2) * 6) / (math.pi**2)))) #beta loc = float(mx - (euler_mascheroni * scale)) return (loc, scale) elif rtype == "e": loc = mx - mx * vx scale = mx * vx return (loc, scale) elif rtype == "u": loc = mx scale = vx return (loc, scale) else: return ("rtype not found")
def __solver__(self, p): p.xk = p.x0.copy() p.fk = asfarray(max(abs(p.f(p.x0)))).flatten() p.iterfcn() if p.istop: p.xf, p.ff = p.xk, p.fk return try: xf = broyden1(p.f, p.x0, iter = p.maxIter) except: return p.xk = p.xf = asfarray(xf) p.fk = p.ff = asfarray(max(abs(p.f(xf)))).flatten() p.istop = 1000 p.iterfcn()
def broyden_solver(scf): """Broyden solver for selfconsistency""" scf.mixing = 1.0 # perfect mixing scf.iterate() # do one iteration x0 = scf.cij # get the array with expectation values def fun(x): # function to solve scf.cij = x # impose those expectation values scf.cij2v() # update mean field scf.iterate() # perform an iteration return scf.cij - x # difference with respect to input from scipy.optimize import broyden1,broyden2,anderson # x = anderson(fun,x0) x = broyden1(fun,x0,f_tol=1e-7) # broyden solver scf.cij = x # impose those expectation values scf.cij2v() # update mean field scf.iterate() # perform an iteration return scf # return scf
def calibrate(cls, n, q, vol, r, iterations=100): ''' n: number of periods q: upward probability vol: volatility r: spot rate ''' def error(drift): rates = BDTrate(n, drift, vol) spot_rates = CashPricing(n, q, rates).get_spot_rates() error = spot_rates - r return error initial_guess = np.repeat(.05, n) drift = broyden1(error, initial_guess, iter=iterations) exp_error = (error(drift)**2).sum() return cls(n, drift, vol), exp_error
def WO_Model_obj(u): x_guess = np.ones((5, 1)) * 0.2 WO_f_model = functools.partial(WO_nonlinear_f_model, u) x_solved = broyden1(WO_f_model, x_guess, f_tol=1e-12) # definitions Fa = 1.8275 Fb = u[0] Fr = Fa + Fb # calculating objective obj = -(1043.38 * x_solved[3, 0] * Fr + 20.92 * x_solved[2, 0] * Fr - 79.23 * Fa - 118.34 * Fb) return obj
def __solver__(self, p): p.xk = p.x0.copy() p.fk = asfarray(max(abs(p.f(p.x0)))).flatten() p.iterfcn() if p.istop: p.xf, p.ff = p.xk, p.fk return try: xf = broyden1(p.f, p.x0, iter=p.maxIter) except: return p.xk = p.xf = asfarray(xf) p.fk = p.ff = asfarray(max(abs(p.f(xf)))).flatten() p.istop = 1000 p.iterfcn()
def __call__(self, acf): assert abs(acf[0] - 1.0) < 1e-10, "First element of ACF should be 1.0" # Maps provided ACF of sample series into corresponding white noise process ACF acf = np.asarray(acf) acf = acf[1:] # discard acf(0) = 1 n = acf.shape[0] m = self._cj.shape[0] acf = acf.reshape((n, )) def F(x): A = np.vander(x, m + 1, increasing=True)[:, 1:m + 1] # discard unit column Ac = np.dot(A, self._cj) return acf - Ac x0 = np.random.randn(n).reshape((n, )) normal_acf = sci_opt.broyden1(F, x0, f_tol=1e-8, maxiter=100) normal_acf = normal_acf.reshape((n, 1)) return np.vstack((np.ones((1, 1)), normal_acf))
def bootstrap(nom_t, mat_t, cp_y_t, pv_t): size=len(mat_t) b_zc_r=np.zeros(size) def p_except_last(pv,cf,mat,val,r): return pv + cf*np.exp(-mat*r) - val for i in range(size): cf_vect, mat_vect, zc_vect = cf_mat_zc_for_year(b_f,b_cp_y[i],b_mat[i],b_nom[i],mat_t, b_zc_r) idx=len(cf_vect)-1 pv= price(cf_vect[:idx],zc_vect[:idx],mat_vect[:idx]) H=partial(p_except_last, pv, cf_vect[idx], mat_vect[idx], pv_t[i]) b_zc_r[i]= sco.broyden1(H,0.05) return b_zc_r
def peri_apo_to_random_w0(pericenter, apocenter, potential, frac_r_start=None): def _func(E, L, r): return 2 * (E - potential.value([r, 0, 0.]).value) - L**2 / r**2 def f(p): E, L = p return np.array([_func(E, L, apocenter), _func(E, L, pericenter)]) if frac_r_start is None: frac_r_start = np.random.uniform() r_start = frac_r_start * (apocenter - pericenter) + pericenter E0 = 0.5 * 0.2**2 + potential.value([(apocenter + pericenter) / 2., 0, 0 ]).value[0] L0 = 0.2 * r_start E, L = so.broyden1(f, [E0, L0]) _rdot = np.sqrt(2 * (E - potential.value([r_start, 0, 0.]).value[0]) - L**2 / r_start**2) w0 = gd.CartesianPhaseSpacePosition(pos=[r_start, 0., 0] * u.kpc, vel=[_rdot, L / r_start, 0.] * u.kpc / u.Myr) T = 2 * np.pi * r_start / (L / r_start) logger.debug("Period: {}".format(T)) # sample a random rotation matrix q = gc.Quaternion.random() random_R = q.rotation_matrix # now rotate by random rotation matrix new_pos = random_R.dot(w0.pos) new_vel = random_R.dot(w0.vel) w0 = gd.CartesianPhaseSpacePosition(pos=new_pos, vel=new_vel) orbit = potential.integrate_orbit(w0, dt=1., nsteps=10000) logger.debug( "Desired (peri,apo): ({:.1f},{:.1f}), estimated (peri,apo): ({:.1f},{:.1f})" .format(pericenter, apocenter, orbit.pericenter(), orbit.apocenter())) return w0, T
def calibrate(cls, n, q, vol, market_spot_rates, iterations=200): """ Calibrates the optimal drift for the given market spot rates Initializes the model from the corresponding optimal drift and vol Parameters: ---------- n: int The number of periods q: float The probability of rates going upward in the binomial model vol: scalar / np.array The volatility for the model market_spot_rates: np.array The current spot rates for n periods to be used for optimization max_iter: int The number of iterations for which the optimization function should run Returns: ------- (BDTRate, error): Returns a tuple of BDTRate instance calibrated from the given parameters and the squared error in the result. """ def error(drift): rates = BDTRate(n, drift, vol) spot_rates = CashPricing(n, q, rates).get_spot_rates() error = spot_rates - market_spot_rates return error initial_guess = np.repeat(0.05, n) drift = broyden1(error, initial_guess, iter=iterations) exp_error = (error(drift)**2).sum() return cls(n, drift, vol), exp_error
def find_t(self): # find t to obtain user-set fractional mass within rs if self.f is None: self.t = 1. else: self.set_t0() F = lambda t: self.frac_mass_within_rs(t) - self.f try: self.t = sopt.broyden1(F, self.t0).item() except sopt.nonlin.NoConvergence: # if the Broyden method fails, print warning and set f=None and t=1 print( '****************************************************************************' ) print( ' WARNING: could not set f=%.3e. Setting f=None and t=1.' % self.f) print( '****************************************************************************' ) self.f = None self.t = 1.
def plot_convergence(): """Compare convergence of Newton's method, Broyden's method, and function iteration.""" def f(x): fval = np.exp(x) - 1 # Log x values in list x_values. x_values.append(x) return fval def get_log_error(x): return np.log10(np.abs(x)).flatten() # Newton's Method. x_values = [] _ = newton(f, 2) error_newton = get_log_error(x_values) # Broyden's Method. x_values = [] _ = broyden1(f, 2) error_broyden = get_log_error(x_values) # Function iteration. x_values = [] _ = fixed_point(f, 2, xtol=1e-4) error_funcit = get_log_error(x_values) # Plot results. plt.figure(figsize=(10, 5)) plt.plot(error_newton, label="Newton's Method") plt.plot(error_broyden, label="Broyden's Method") plt.plot(error_funcit, label="Function Iteration") plt.title(r"Convergence rates for $f(x)= exp(x)-1$ with $x_0=2$") plt.xlabel("Iteration") plt.ylabel("Log10 Error") plt.xlim(0, 50) plt.ylim(-6, 2) plt.legend()
def mu_p_q(L12, L23, L13): """ Calcula los valores de mu, p y q por fuerza bruta """ def equations(params): mu, p, q = params eqs = [mu*L12 - p + np.sin(p), mu*L23 - q + np.sin(q), mu*L13 - p - q + np.sin(p + q) ] return eqs res_mu0, res_p0, res_q0 = np.array([0.01, 0.01, 0.01]) for mu0 in np.arange(0.01, 5, 0.01): try: for p0 in np.arange(0.01, 10, 0.01): for q0 in np.arange(0.01, 10, 0.01): mu1, p1, q1 = broyden1(equations, (mu0, p0, q0)) res_mu, res_p, res_q = equations((mu1, p1, q1)) if (abs(np.array([res_mu, res_p, res_q])) < abs(np.array([res_mu0, res_p0, res_q0]))).all()\ and mu1 > 0.0001: res_mu0, res_p0, res_q0 = res_mu, res_p, res_q mu, p, q = mu1, p1, q1 except: continue try: return np.array([mu, p, q]) except: print(mu1, p1, q1) raise ValueError("No se encontraron valores para mu, p, q")
def aplicarMetodosNL(f, x, y): try: print("Resultado con la funcion fsolve = {}".format( optimize.fsolve(f, [x, y], xtol=10**(-6)))) except Exception as e: print("El metodo fsolve no converge") try: print("Resultado mediante el metodo de Newton-Krylov = {}".format( optimize.newton_krylov(f, [x, y], x_tol=10**(-6)))) except Exception as e: print("El metodo de Newton-Krylov no converge") try: print("Resultado mediante el metodo de Broyden 1 = {}".format( optimize.broyden1(f, [x, y], x_tol=2**(-16)))) except Exception as e: print("El metodo de Broyden 1 no converge") try: print("Resultado mediante el metodo de Broyden 2 = {}".format( optimize.broyden2(f, [x, y], x_tol=2**(-50)))) except Exception as e: print("El metodo de Broyden 2 no converge")
def chi_squared_limit(k, P): """ Find the P-percent certainty limit of the chi-squared distribution INPUTS ------ k: int number of dimensions of the distribution P: float certainty of the distrubtion, in percents RETURNS ------- limit: float limit of the distribution """ def CDF(x): return chi2.cdf(x, k) - P / 100. limit = broyden1(CDF, k, f_tol=1e-10) return limit
def solve(self): """Solve the selfconsistent problem""" return self.iterate() # first iteration def r2z(v): # convert real to complex n = v.shape[0]//2 return v[0:n] + 1j*v[n:2*n] def z2r(v): # convert complex to real return np.concatenate([v.real,v.imag]) def fopt(cij): # function to return the error self.cij = r2z(cij) # store this vector self.cij2v() # update the v vectors self.iterate() # do an iteration print(self.cij) self.v2cij() # convert the v to cij return z2r(self.cij)-cij cij = optimize.broyden1(fopt,z2r(self.cij),f_tol=1e-8,max_rank=10) # cij = optimize.fsolve(fopt,z2r(self.cij),xtol=1e-8) # cij = optimize.anderson(fopt,z2r(self.cij),f_tol=1e-6,w0=0.1) # cij = optimize.newton_krylov(fopt,z2r(self.cij),f_tol=1e-6,outer_k=8) self.cij = cij self.cij2v() # update
def peri_apo_to_random_w0(pericenter, apocenter, potential, frac_r_start=None): def _func(E, L, r): return 2*(E - potential.value([r,0,0.]).value) - L**2/r**2 def f(p): E,L = p return np.array([_func(E,L,apocenter), _func(E,L,pericenter)]) if frac_r_start is None: frac_r_start = np.random.uniform() r_start = frac_r_start * (apocenter - pericenter) + pericenter E0 = 0.5*0.2**2 + potential.value([(apocenter+pericenter)/2.,0,0]).value[0] L0 = 0.2 * r_start E,L = so.broyden1(f, [E0, L0]) _rdot = np.sqrt(2*(E-potential.value([r_start,0,0.]).value[0]) - L**2/r_start**2) w0 = gd.CartesianPhaseSpacePosition(pos=[r_start,0.,0]*u.kpc, vel=[_rdot, L/r_start, 0.]*u.kpc/u.Myr) T = 2*np.pi*r_start / (L/r_start) logger.debug("Period: {}".format(T)) # sample a random rotation matrix q = gc.Quaternion.random() random_R = q.rotation_matrix # now rotate by random rotation matrix new_pos = random_R.dot(w0.pos) new_vel = random_R.dot(w0.vel) w0 = gd.CartesianPhaseSpacePosition(pos=new_pos, vel=new_vel) orbit = potential.integrate_orbit(w0, dt=1., nsteps=10000) logger.debug("Desired (peri,apo): ({:.1f},{:.1f}), estimated (peri,apo): ({:.1f},{:.1f})" .format(pericenter, apocenter, orbit.pericenter(), orbit.apocenter())) return w0,T
def cycloid(A, B, n = 100): """ Generates n uniformly spaced sample points of an inverted cycloid between points A and B. """ x0, y0 = A x1, y1 = B m = (y0 - y1) / (x1 - x0) def f(t): """ Objective function for Broyden solver """ return np.abs((1- np.cos(t)) / (t - np.sin(t)) - m) # find theta at B using a Broyden solver t = broyden1(f, [3.])[0] # now compute a a = (y1 - y0) / (1- np.cos(t)) X,Y =[],[] # get sample points by varying theta for i in np.linspace(0, t, n): x = x0 - a*(i - np.sin(i)) y = y0 + a*(1- np.cos(i)) X.append(x) Y.append(y) x,y = np.array(X),np.array(Y) # now resample the points uniformly in x X = np.linspace(x.min(), x.max(), x.size) Y = np.interp(X, x, y) return X, Y
t = linspace(0, 5, 10000) N, infodict = odeint(f, x0, t, full_output=True) # print(infodict['message']) N_rabbits, N_foxes = [], [] for x, y in N: N_rabbits.append(x) N_foxes.append(y) plt.figure('Task 4') plt.subplot(1, 2, 1) curves = plt.plot(t, N_rabbits, t, N_foxes) plt.grid() x_n1 = broyden1(f, [10, 10]) # or you can just wolfram your equation values = linspace(0.5, 2, 150) vcolors = plt.cm.autumn_r(linspace(0.7, 1, len(values))) plt.subplot(1, 2, 2) # trajectories for v, col in zip(values, vcolors): P0 = [E * v for E in x_n1] P = odeint(f, P0, t) plt.plot(P[:, 0], P[:, 1], lw=0.1 * v, color=col, label='P0=(%.f, %.f)' % (P0[0], P0[1]))
def expected_only(strategy_one, strategy_two, payoff_matrix, continuation_probability, mistake_probability, epsilon): """ Compute the expected value of the payoff in an iterated prisoners dilemma using only the expected game length terms This takes an approximate approach to computing the expected payoff by only considerining the terms that arise from games with length equal to the expected game length """ # Compute the expected number of rounds expected_rounds = math.floor(1 / (1 - continuation_probability)) # Set up a function that we can solve for the maximum number of mistakes above the threshold def max_mistakes(n): term = (continuation_probability ** (expected_rounds - 1)) * (1 - continuation_probability) term = term * ((1 - mistake_probability) ** (2 * expected_rounds - n)) term = term * (mistake_probability ** n) return term # Solve for the maximum number of allowable mistakes max_mistakes = broyden1(lambda x: max_mistakes(x) - epsilon, 0) # Take the floor max_mistakes = math.floor(max_mistakes) # Set up an initial HistoryFrame initial_frame = HistoryFrame([], [], 0) # Add this to a frame list frame_list = [initial_frame] # Create strategy objects that we will use player_one = strategy_one(payoff_matrix.C, payoff_matrix.D) player_two = strategy_two(payoff_matrix.C, payoff_matrix.D) # Loop until we've got the right length of history for _ in range(expected_rounds): # We want to pull each value out of the frame_list and put the new values into a new list new_frame_list = [] for frame in frame_list: # Load the histories into some strategy objects player_one.history = frame.player_one_history player_two.history = frame.player_two_history # Compute the next moves player_one_move = player_one.next_move(player_two.history) player_two_move = player_two.next_move(player_one.history) # Create a new frame with the no-mistake moves new_frame_list.append(HistoryFrame(player_one.history + [player_one_move], player_two.history + [player_two_move], frame.mistakes)) # Make mistakes if we haven't made enough yet if frame.mistakes != max_mistakes: # Make one mistake new_frame_list.append(HistoryFrame(player_one.history + [player_one.opposite(player_one_move)], player_two.history + [player_two_move], frame.mistakes + 1)) # Make the other mistake new_frame_list.append(HistoryFrame(player_one.history + [player_one_move], player_two.history + [player_two.opposite(player_two_move)], frame.mistakes + 1)) # See if we can make two mistakes if frame.mistakes + 2 <= max_mistakes: # Add the frame to the list with both mistakes new_frame_list.append(HistoryFrame(player_one.history + [player_one.opposite(player_one_move)], player_two.history + [player_two.opposite(player_two_move)], frame.mistakes + 2)) # Load the new frames into the old list frame_list = new_frame_list # Now we should have a list that contains all of the correct length games with upto the maximum number of mistakes # Now we loop through each case, compute the total payoff and multiply by the coefficient # Set up variables to hold the expected payoff player_one_expected_payoff = 0 player_two_expected_payoff = 0 # We want the game length portion of the coefficient, since this wont change game_length_coefficient = (continuation_probability ** (expected_rounds - 1)) * (1 - continuation_probability) for frame in frame_list: # Figure out the total payoff player_one_payoff = 0 player_two_payoff = 0 # Loop over the history, adding the payoff each time for player_one_move, player_two_move in zip(frame.player_one_history, frame.player_two_history): payoff = payoff_matrix.payoff(player_one_move, player_two_move) player_one_payoff += payoff[0] player_two_payoff += payoff[1] # Compute the coefficient for the number of mistakes mistake_coefficient = ((1 - mistake_probability) ** (2 * expected_rounds - frame.mistakes)) * (mistake_probability ** frame.mistakes) # Finally, multiply each player's payoff by the two coefficients and add to the total player_one_expected_payoff += player_one_payoff * game_length_coefficient * mistake_coefficient player_two_expected_payoff += player_two_payoff * game_length_coefficient * mistake_coefficient # Return the results return player_one_expected_payoff, player_two_expected_payoff
def calculateRate(amount, total_repayment): from scipy.optimize import broyden1 monthly=total_repayment/36 # monthly repayment rate for 36 month loan # solve for interest rate: monthly = rate/12 * amount / (1-(1+rate/12)^(-36)) rate=broyden1(lambda r: monthly-r/12*amount/(1-(1+r/12)**(-36)), 0.05, f_tol=1e-8) return rate
def PolynomialFit(x, y, anchors=None, avgrange=0, order=2, indf=None, verbose=True): """ Returns a fitted polynomial. Two scenarios are supported: 1) A set of anchors is given, where the polynomial is being pinned. Then the degree equals the amount of anchors given minus 1. The y-values for the pins can be averaged over a given range. if no anchors are given, the following applies: 2) An order of the polynomial is given and the polynomial is fitted accordingly. Optionally, a fit range can be given via a masked array ``indf``. inputs: x : array of independent values y : array of dependent values Optional: anchors : a set of x-positions where the polynomial shall be pinned to the given curve. avgrange : float a range in which the given curve will be averaged to calculate the pin position. order : int sets the order of the polynomial for fit. ignored if anchors is not None indf : boolean array, same length as x and y a mask for x and y to choose a range for fit. """ if anchors is None: N = order + 1 func = lambda x, *v: sum([v[i]*x**(N - 1 - i) for i in reversed(range(N))]) ind = ~np.isnan(y) if indf is not None: ind *= indf start = [1] start.extend((N-1)*[0]) popt, pcov = optimize.curve_fit(func, x[ind], y[ind], p0=start) if verbose: print(popt) poly = func(x, *popt) else: if avgrange==0: indizes = [abs(xi - x).argmin() for xi in anchors] else: indizes = [(x > xi - avgrange)*(x < xi + avgrange) for xi in anchors] #print sum(indizes).any() anchors = np.array([x[ind].mean() for ind in indizes]) yi = np.array([y[ind].mean() for ind in indizes]) #print anchors, yi N = len(indizes) v0 = [0.] * (N - 1) + [1.] res = lambda v: sum([v[i]*anchors**(N - 1 - i) for i in range(N)]) - yi vopt = optimize.broyden1(res, v0) poly = sum([vopt[i]*x**(N - 1 - i) for i in range(N)]) if verbose: print(vopt) return poly
def get_dg0_from_metal(): Hd = np.sqrt(delta/(stokes+delta)) dgguess = metal/Hd #print("dgguess=",dgguess) sol = broyden1(metallicity_error,[dgguess],f_tol=1e-16) return sol[0]
XTest = np.array([[1], [4], [10]]) # Set Orientation (all zero is pointing straigt to wall) 3-2-1 yaw = 125; pitch = 40; roll =15; zTest = np.array([[0],[0],[-1]]); # point towards wall R = getRotMatrix(['z', 'y', 'x'], [np.radians(yaw), np.radians(pitch), np.radians(roll)]) VATest = np.dot(R,zTest); VBTest = np.dot(np.dot(R,getRotMatrix(['y'],[np.radians(angle1)])),zTest) VCTest0 = np.dot(np.dot(np.dot(R,getRotMatrix(['z'],[np.radians(-30*np.cos(np.radians(angle2)))])),getRotMatrix(['x'],[np.radians(-angle2)])),VATest) tic = time.clock() VCTest0 = np.array([[.03],[-.06],[-.06]]) VCTest = fsolve(laserf,VCTest0) VCTest2 = broyden1(laserf,VCTest0) toc = time.clock() print(toc-tic) VCTest = VCTest print(VCTest) #forcing VCTest to be what matlab found it to be VCTest = np.array([[.3992],[-.6751],[-.6656]]) VCTest = VCTest/norm(VCTest) print('forcing VCtest to match matlab...') print(VCTest) Aa = np.array([[1, 0, VATest[0]], [0, 1, VATest[1]], [0, 0, VATest[2]]]);
eqs = [mu*L12 - p + np.sin(p), mu*L23 - q + np.sin(q), mu*L13 - p - q + np.sin(p + q) ] return eqs mu1, p1, q1 = np.array([0.03, 1.2, 1.]) res_mu0, res_p0, res_q0 = np.array([0.01, 0.01, 0.01]) for mu0 in np.arange(0.01, 0.08, 0.01): try: for p0 in np.arange(1, 2, 0.1): for q0 in np.arange(1, 2, 0.1): mu1, p1, q1 = broyden1(equations, (mu0, p0, q0)) res_mu, res_p, res_q = equations((mu1, p1, q1)) if (abs(np.array([res_mu, res_p, res_q])) < abs(np.array([res_mu0, res_p0, res_q0]))).all(): res_mu0, res_p0, res_q0 = res_mu, res_p, res_q mu, p, q = mu1, p1, q1 except: continue print(mu, p, q)
def loop_fit(indirizzo, lim_current_inf, sup_current): data= genfromtxt(indirizzo) ydata = data[:,1] xdata = data[:,0] sigmay = 0.05 sigmax = 0.0003 p0lin = [2] p0exp = [2, 0.005, 20] #g_0, pcov_lin = optimize.curve_fit(linfit, xdata[:argmax(ydata>=lim_current_inf)], ydata[:argmax(ydata>=lim_current_inf)], p0lin, sigmay) g_0, pcov_lin = optimize.curve_fit(linexp, xdata[:argmax(ydata>=lim_current_inf)], ydata[:argmax(ydata>=lim_current_inf)], p0exp, sigmay) g_0 = g_0[0] pcov_lin = pcov_lin[0][0] g_var = sqrt(pcov_lin) #print('g0: ', g_0, '+-', g_var[0][0]) p0_loop = [20, 0.005, 2] val_g = False val_B = False val_is = False val_Rs = False j = 0 while val_g==False or val_B==False or val_is==False or val_Rs==False: #print(val_g==False & val_B==False & val_is==False & val_Rs==False) #step 2: jun_cur = ydata - g_0*xdata #step 3: p_loop, pcov_loop = optimize.curve_fit(tension_junc, abs(jun_cur[argmax(jun_cur>=sup_current):]), xdata[argmax(jun_cur>=sup_current):], p0_loop, sigmax) #p_loop, pcov_loop = optimize.curve_fit(tension_junc, abs(jun_cur), xdata, p0_loop, sigmax) loop_var = sqrt(pcov_loop.diagonal()) #step 4: zero_func = lambda x: tension_junc_abs(x, p_loop[1], p_loop[0], p_loop[2]) #jun_cur_1 = optimize.fsolve(fitsolve, jun_cur, (p_loop[1], p_loop[0], p_loop[2], xdata) ) jun_cur_1 = optimize.broyden1(zero_func, jun_cur) jun_cur_10 = optimize.broyden2(zero_func, jun_cur[100], x_rtol=1) print(len(jun_cur_1), len(xdata)) #step 5: tot_cur = g_0*xdata + jun_cur_1 print(len(tot_cur[:argmax(tot_cur>=1000)])) print(jun_cur_10) #step 6: delta_g, delta_g_pcov = optimize.curve_fit(linfit, xdata[:argmax(tot_cur>=lim_current_inf)], ydata[:argmax(tot_cur>=lim_current_inf)]-tot_cur[:argmax(tot_cur>=lim_current_inf)], g_0, sigmay) g_1 = g_0 + delta_g #check della convergenza if abs(g_1 - g_0) <= abs(delta_g): val_g = True elif abs(g_1 - g_0) <= 10**(-6): val_g = True if abs(p_loop[0] - p0_loop[0]) <= abs(loop_var[0]): val_B = True #print(val_B) #print(abs(p_loop[0] - p0_loop[0]) - abs(loop_var[0])) if abs(p_loop[1] - p0_loop[1]) <= abs(loop_var[1])/100: val_is = True if abs(p_loop[2] - p0_loop[2]) <= abs(loop_var[2])/100: val_Rs = True print(val_g, val_B, val_is, val_Rs) #ridefinizione delle variabili print('B: ', p_loop[0], '+-', loop_var[0], ' I_s: ', p_loop[1], '+-', loop_var[1], ' R_s: ', p_loop[2], '+-', loop_var[2], 'G:', g_1[0], '+-', delta_g[0]) deltaIj = jun_cur_1 - jun_cur g_0 = g_1 p0_loop = p_loop j = j +1 #print(j) #plot(xdata, ydata-tot_cur) #show() grid() yscale('log') rc('font', size=16) title(r"Caratteristica I-V T=%s° - fit"%(data[:,2][1]), size=14.5) xlabel('Tensione V [V]') ylabel(r'Corrente I [$\mu $ A]') ylim(0.02, 10000) lim_err = 2300 plot(xdata, current_v(xdata, p_loop[1], p_loop[0], p_loop[2]*10**(-6), jun_cur_1, g_0), color='blue', linewidth = 1.5) errorbar(xdata[:argmax(ydata>=lim_err)], current_v(xdata, p_loop[1], p_loop[0], p_loop[2]*10**(-6), jun_cur_1, g_0)[:argmax(ydata>=lim_err)], prop_error(xdata,sigmax,p_loop[1],loop_var[1],p_loop[0],loop_var[0], p_loop[2], loop_var[2],g_1[0],delta_g[0],jun_cur_1,deltaIj)[:argmax(ydata>=lim_err)], sigmax, linestyle='None', color="blue") errorbar(xdata, ydata, sigmay, sigmax, linestyle='None', marker='o', markersize=1, color="red") B = r'B: $ %s \pm %s \, [V^{-1}] $'%(round(p_loop[0], 2), round(loop_var[0], 2)) I_s = r'$I_{S}$: $ %s \pm %s \, [nA] $'%(round(p_loop[1]*10**3, 2), round(loop_var[1]*10**3, 2)) R_s = r'$R_{S}$: $ %s \pm %s \, [\Omega] $'%(round(p_loop[2], 2), round(loop_var[2], 2)) G = r'G: $ %s \pm %s \, [\mu S]$ '%(round(g_1[0], 2), round(delta_g[0], 2)) text(0.45, 10, B, family='serif', style='italic', size=15) text(0.45, 3, I_s, family='serif', style='italic', size=15) text(0.45, 1, R_s, family='serif', style='italic', size=15) text(0.45, 0.3, G, family='serif', style='italic', size=15) #savefig('%s.png'%(indirizzo), dpi=400) show()
def get_dg0_from_metal(): Hd = np.sqrt(delta0 / (st0 + delta0)) dgguess = metal / Hd sol = broyden1(metallicity_error, [dgguess], f_tol=1e-16) return sol[0]
return bal def ofwh_balance(f): ff2 = (1-f[0])*x[6]*(1-f[1]) ff11 = f[0] ff12 = (1-f[0])*(1-x[6]) ff7 = (1-f[0])*x[6]*f[1] e_in = ff2*h[2]+ff11*h[11]+ff7*h[7]+ff12*h[12] e_out = h[3] bal = e_in - e_out return bal def wrapped_function(f): return [np.abs(reheater_balance(f)), np.abs(ofwh_balance(f))] f =opt.broyden1(wrapped_function,[0.1,0.1]) # f now holds a vector of flow fractions. # f[0] corresponds to f1 on the given schematic # f[1] corresponds to f2 on the given schematic print "Flow fractions [f1,f2] = ",f # calculate specific work of the turbines and pumps w_mcp = (1-f[0])*x[6]*(1-f[1])*(h[1] - h[2]) w_mfp = h[3] - h[4] w_hpt = (1-f[0])*(h[5] - h[6]) w_lpt = (1-f[0])*x[6]*(1-f[1])*(h[8] - h[9]) w_net = w_mcp + w_mfp + w_hpt + w_lpt