def get_adaptive_states(self): '''determine adaptive state ''' nprev = 0 self.data['resp_c'][nprev] = fsolve(self.steady, 0.) #find steady - state C #self.data['resp_c'][nprev] = 14.12579 #delete if rtbis is available self.data['stim'][nprev] = self.k['stim_prev'] self.data['resp_r'][nprev] = self.data['stim'][nprev] self.data['resp_e'][nprev] = self.data['resp_r'][nprev] self.data['beta'][nprev] = self.k['beta_0'] + self.k['g_ex0'] * self.data['resp_e'][nprev] self.data['resp_q'][nprev] = 1. / self.data['beta'][nprev] self.data['tau_x'][nprev] = self.data['resp_q'][nprev] * self.k['ratefrac'] self.data['gain_x'][nprev] = 1. / (1. + (self.k['a_c'] * self.data['resp_c'][nprev]) ** self.k['rnc']) self.data['resp_w'][nprev] = self.data['gain_x'][nprev] * self.data['resp_q'][nprev] self.data['resp_x'][nprev] = self.data['gain_x'][nprev] * self.data['resp_q'][nprev] self.data['resp_os'][nprev] = self.data['resp_x'][nprev] ** self.k['rnx'] self.data['resp_vc'][nprev] = (self.data['resp_os'][nprev] / self.k['a_is']) ** (1. / (1. + self.k['gamma_is'])) self.data['resp_is'][nprev] = self.data['resp_vc'][nprev] self.data['gain_is'][nprev] = self.data['resp_is'][nprev] ** self.k['gamma_is'] self.data['gain_i'][nprev] = self.k['a_is'] * self.data['gain_is'][nprev] self.data['resp_h0'][nprev] = self.data['resp_is'][nprev] self.data['gtau'] = (self.data['resp_h0'][nprev] / self.k['vh0']) ** self.k['rho'] #a_I in model self.data['gripmax'] = self.k['ripmax'] / self.data['gtau'] self.data['st_is'] = self.data['resp_is'][nprev] #transferred to steady_vs via common self.data['resp_vs'][nprev] = fsolve(self.steady_vs, -1.e3) #find steady - state V_s #self.data['resp_vs'][nprev] = - 12.92790 #delete if rtbis is available self.data['resp_ic'][nprev] = self.data['gripmax'] / (1. + np.exp( - (self.data['resp_vs'][nprev] - self.k['vk']) / self.k['vn'])) self.data['resp_tr'][nprev] = self.data['resp_ic'][nprev] self.data['resp_ih'][nprev] = self.data['resp_tr'][nprev] self.data['resp_h'][nprev] = self.data['resp_ih'][nprev]
def intersection(self,pos,vec): if vec[0] == 0: secpos0_front = pos[0] secpos0_back = pos[0] else: try: secpos0_front = fsolve(lambda x : self.frontsurface(x) - (vec[1]/vec[0]*(x-pos[0])+pos[1]),pos[0])[0] secpos0_back = fsolve(lambda x : self.backsurface(x) - (vec[1]/vec[0]*(x-pos[0])+pos[1]),[pos[0],pos[0],pos[0]])[0] except RuntimeWarning: return None if self.frontsurface(secpos0_front) - (vec[1]/vec[0]*(secpos0_front-pos[0])+pos[1]) > numerror: return None if self.backsurface(secpos0_back) - (vec[1]/vec[0]*(secpos0_back-pos[0])+pos[1]) > numerror: return None secpos_front = np.array([secpos0_front, self.frontsurface(secpos0_front)]) secpos_back = np.array([secpos0_back, self.backsurface(secpos0_back)]) # Check which section point lies "in front" of the ray k_front = vec[1]/(secpos_front-pos)[1] k_back = vec[1]/(secpos_back-pos)[1] #print k_front #print k_back #pl.plot if k_front > 0 and k_back < 0: secpos = secpos_front elif k_front < 0 and k_back > 0: secpos = secpos_back elif k_front < 0 and k_back < 0: return None else: # If both are possible, take the nearest if distance(secpos_front,pos) < distance(secpos_back,pos): secpos = secpos_front else: secpos = secpos_back return secpos
def __init__(self, k, H, c, h, x, rhof, rhos, L, ztop=0, sealevel=0): assert x <=0, "Input error: x must be less than zero" self.Linput = L # First find position without finite L, then use the specified L # This is a bit clunky, but may work ok SemiCoast.__init__(self, k, H, c, 0.001, rhof, rhos, inf, ztop, sealevel) assert h > self.hs, "Input error: inland head smaller than equivalent freshwater head at top of aquifer" self.givenx = x self.givenh = h # find gradient using log transform of grad to avoid negative values start = np.log((self.givenh - self.hs) / abs(x)) result = fsolve(self.findgrad, start, full_output=1) if result[2] == 1: self.grad = np.exp(result[0]) self.initialize() else: print('Error: gradient could not be found with fsolve when L=inf') # if self.tip() > self.Linput: self.L = self.Linput self.initialize() result = fsolve(self.findgrad, np.log(self.grad), full_output=1) if result[2] == 1: self.grad = np.exp(result[0]) self.initialize() else: print('Error: gradient could not be found with fsolve when L=inf')
def find(self,X): """returns the parametric coordinate that matches the given x location""" try: return array([fsolve(lambda f: self(f)[:,0][0] - x,[x/self.max_x,],xtol=1e-5) for x in X])[:,0] except TypeError: return fsolve(lambda f: self(f)[:,0] - X,[X/self.max_x,],xtol=1e-5)
def construct_shape_function(self, alpha=None, rc=None, eps=1e-10): """Build shape-function for compensation charge.""" self.alpha = alpha if self.alpha is None: if isinstance(rc, list): rc = min(rc) rc = 1.5 * rc def spillage(alpha): """Fraction of gaussian charge outside rc.""" x = alpha * rc**2 return 1 - erf(sqrt(x)) + 2 * sqrt(x / pi) * exp(-x) def f(alpha): return log(spillage(alpha)) - log(eps) if scipy_version < '0.8': self.alpha = fsolve(f, 7.0) else: self.alpha = fsolve(f, 7.0)[0] self.alpha = round(self.alpha, 1) self.log('Shape function: exp(-alpha*r^2), alpha=%.1f Bohr^-2' % self.alpha) self.ghat_g = (np.exp(-self.alpha * self.rgd.r_g**2) * (self.alpha / pi)**1.5)
def rayIntersect(self, ray): ''' Returns the first intersection of a ray with the surface in parametric form (u,v,t) if such a solution exists. Otherwise, returns None. ''' # display debug messages debug = False def system(params): ''' Returns the displacement from a point on the ray to a point on the surface. Requires 3 parameters: (u,v,t) ''' x = self.x(params[0], params[1]) - ray.x(params[2]) y = self.y(params[0], params[1]) - ray.y(params[2]) z = self.z(params[0], params[1]) - ray.z(params[2]) return (x, y, z) # make sure ori is a unit vector ray.ori = ray.ori / norm(ray.ori) # solve with guess at current ray position guess = (ray.pos[2] - self.base[2], atan2(ray.pos[1], ray.pos[0]), 0) X, infodict, ier, mesg = fsolve(system, guess, full_output=1) # @UnusedVariable # if solution found if ier == 1: # if solution is out of range if not ray.inRange(X[2]): # debug message if debug: print('Segment: first solution out of range. Trying again.') # ray can intersect at most twice, so create a second guess tsup = 2 * self.seglen pos = ray.getPoint(tsup) # a point really far away from current position guess = (pos[2] - self.base[2], atan2(pos[1], pos[0]), tsup) X, infodict, ier, mesg = fsolve(system, guess, full_output=1) # @UnusedVariable # return solution if exists result = None if(ier == 1): if not self.inRange(X[0], X[1]): if debug: print('Segment: final solution out of surface parameter range:') elif not ray.inRange(X[2]): if debug: print('Segment: final solution out of ray parameter range:') else: if debug: print('Segment: valid solution found:') result = X if debug: print(' [u,v,t] = '), X print(' [x,y,z] = '), self.getPoint(X[0], X[1]) # no solution found else: if debug: print('Segment: no solution found: '), mesg print(' [u,v,t] = '), X return result
def DirectSolve(self, y): """ Directly solve capital and labor supply given next two periods capitals y is given as -2, -3, ..., -60, i.e., through the next-to-last to the first """ if y >= -self.R: a1 = self.apath[y+1] if y == -2: a2 = 0 else: a2 = self.apath[y+2] def constraints(a): c0 = (1+self.r)*a + self.b - a1 c1 = (1+self.r)*a1 + self.b - a2 return self.uc(c0,0)-self.beta*self.uc(c1,0)*(1+self.r) a, n = fsolve(constraints, a1), 0 c = (1+self.r)*a + self.b - a1 else: a1 = self.apath[y+1] a2 = self.apath[y+2] if y == -(self.R+1): n1 = 0 c1 = (1+self.r)*a1 + self.b - a2 else: n1 = self.npath[y+1] c1 = (1+self.r)*a1 + (1-self.tau)*self.w*n1 - a2 def constraints((a0,n0)): c0 = (1+self.r)*a0 + (1-self.tau)*self.w*n0 - a1 return self.uc(c0,n0) - self.beta*self.uc(c1,n1)*(1+self.r),\ (1-self.tau)*self.w*self.uc(c0,n0) + self.un(c0,n0) a, n = fsolve(constraints,(a1,n1)) c = (1+self.r)*a + (1-self.tau)*self.w*n - a1 return a, n, c
def DirectSolve(self, y, p): """ analytically solve for capital and labor supply given next two periods capital. y is from -2 to -60, i.e., through the next-to-last to the first """ [r, w, tau, b] = p # print y, p.shape if y >= -self.R: a1 = self.apath[y+1] a2 = (0 if y == -2 else self.apath[y+2]) def foc(a): # FOC for the retired c0 = (1 + r[y])*a + b[y] - a1 c1 = (1 + r[y+1])*a1 + b[y+1] - a2 return self.uc(c0,0) - self.beta*self.uc(c1,0)*(1 + r[y+1]) a, n = fsolve(foc, a1), 0 c = (1 + r[y])*a + b[y] - a1 else: a1, a2 = self.apath[y+1], self.apath[y+2] if y == -(self.R+1): n1 = 0 c1 = (1 + r[y+1])*a1 + b[y+1] - a2 else: n1 = self.npath[y+1] c1 = (1 + r[y+1])*a1 + (1 - tau[y+1])*w[y+1]*n1 - a2 def foc((a0,n0)): # FOC for the workers c0 = (1 + r[y])*a0 + (1 - tau[y])*w[y]*n0 - a1 return self.uc(c0,n0) - self.beta*self.uc(c1,n1)*(1 + r[y+1]),\ (1 - tau[y])*w[y]*self.uc(c0,n0) + self.un(c0,n0) a, n = fsolve(foc,(a1,n1)) c = (1 + r[y])*a + (1 - tau[y])*w[y]*n - a1 return a, n, c
def FindSolution(n,l,m, Kmax,Za,Zb): R_start = 1.2 R_min = 0.6 R_max = 12 N_tot = 500 N1 = int((R_max-R_start)/(R_max-R_min)*N_tot) N2 = int((R_start-R_min)/(R_max-R_min)*N_tot) sol1=[] for iR in range(N1): R = R_start + iR/(N1-1.)*(R_max-R_start) BH = BaberHyller(m,Kmax,R,Za,Zb) if iR==0: (p,A) = (R*(Za+Zb)/(2.*n), -l*(l+1)) # He-atom for small R! (p,A)= optimize.fsolve(BH.F, [p,A], fprime=BH.D, full_output=0) Ene = -p**2*4/R**2 + 2./R sol1.append([R, Ene, p, A]) sol2=[] for iR in range(N2): R = R_start - (iR+1.)/N2*(R_start-R_min) BH = BaberHyller(m,Kmax,R,Za,Zb) if iR==0: (p,A) = (R*(Za+Zb)/(2.*n), -l*(l+1)) # He-atom for small R! (p,A)= optimize.fsolve(BH.F, [p,A], fprime=BH.D, full_output=0) Ene = -p**2*4/R**2 + 2./R if iR>0 : sol2.append([R, Ene, p, A]) sols = sol2[::-1]+sol1[:] return array(sols)
def get_masses(delta_m_squared_atm, delta_m_squared_sol, sum_masses, hierarchy): # any string containing letter 'n' will be considered as refering to normal hierarchy if 'n' in hierarchy.lower(): # Normal hierarchy massive neutrinos. Calculates the individual # neutrino masses from M_tot_NH and deletes M_tot_NH #delta_m_squared_atm=2.45e-3 #delta_m_squared_sol=7.50e-5 m1_func = lambda m1, M_tot, d_m_sq_atm, d_m_sq_sol: M_tot**2. + 0.5*d_m_sq_sol - d_m_sq_atm + m1**2. - 2.*M_tot*m1 - 2.*M_tot*(d_m_sq_sol+m1**2.)**0.5 + 2.*m1*(d_m_sq_sol+m1**2.)**0.5 m1,opt_output,success,output_message = fsolve(m1_func,sum_masses/3.,(sum_masses,delta_m_squared_atm,delta_m_squared_sol),full_output=True) m1 = m1[0] m2 = (delta_m_squared_sol + m1**2.)**0.5 m3 = (delta_m_squared_atm + 0.5*(m2**2. + m1**2.))**0.5 return m1,m2,m3 else: # Inverted hierarchy massive neutrinos. Calculates the individual # neutrino masses from M_tot_IH and deletes M_tot_IH #delta_m_squared_atm=-2.45e-3 #delta_m_squared_sol=7.50e-5 delta_m_squared_atm = -delta_m_squared_atm m1_func = lambda m1, M_tot, d_m_sq_atm, d_m_sq_sol: M_tot**2. + 0.5*d_m_sq_sol - d_m_sq_atm + m1**2. - 2.*M_tot*m1 - 2.*M_tot*(d_m_sq_sol+m1**2.)**0.5 + 2.*m1*(d_m_sq_sol+m1**2.)**0.5 m1,opt_output,success,output_message = fsolve(m1_func,sum_masses/3.,(sum_masses,delta_m_squared_atm,delta_m_squared_sol),full_output=True) m1 = m1[0] m2 = (delta_m_squared_sol + m1**2.)**0.5 m3 = (delta_m_squared_atm + 0.5*(m2**2. + m1**2.))**0.5 return m1,m2,m3
def _solve_beta(b, epsilon, n2, wl, beta_TE_guess, beta_TM_guess, verbose=False): """Solve the eigenvalue equations numerically""" # Output arrays beta_TE = N.zeros(b.shape, dtype=complex) beta_TM = N.zeros_like(beta_TE) for ix, width in enumerate(b): if verbose: print ix, if ix % 10 == 9: print " " # first TE beta_packed, _, ier, mesg = fsolve( ev_TE, pack_into_real(beta_TE_guess[ix]), args=(epsilon, n2, width, wl), full_output=True ) if ier != 1: print "For width={0} nm, no TE solution found: {1}".format(width * 1e9, mesg) beta_TE[ix] = N.nan else: beta_TE[ix] = unpack_into_complex(beta_packed)[0] # then TM beta_packed, _, ier, mesg = fsolve( ev_TM, pack_into_real(beta_TM_guess[ix]), args=(epsilon, n2, width, wl), full_output=True ) if ier != 1: print "For width={0} nm, no TM solution found: {1}".format(width * 1e9, mesg) beta_TM[ix] = N.nan else: beta_TM[ix] = unpack_into_complex(beta_packed)[0] return beta_TE, beta_TM
def solve(self, y=0, x0=0, return_y=False, **kwargs): """ Wrapper around :func:`scipy.optimize.fsolve`. Solves y=fit(x) for x. :param y: y-value :param x0: initial guess :param return_y: return x and fit(x) :returns: xval, yval :type y: float :type x0: float :type return_y: bool >>> fit = FitLinear([1, 2, 3], [4, 5, 6]) >>> xval, yval = fit.solve(y=0, x0=1.0) """ _kwargs = dict() _kwargs.update(**kwargs) if y == 0: x = _optimize.fsolve(self.__call__, x0, **_kwargs) else: f = lambda x : self.__call__(x) + y x = _optimize.fsolve(f, x0, **_kwargs) if return_y: return x[0], self(x[0]) return x[0]
def __call__(self,n,dt,Vessel1,Vessel2,Vessel3,ID): P1,Q1,A1,P2,Q2,A2,P3,Q3,A3 = self.P1,self.Q1,self.A1,self.P2,self.Q2,self.A2,self.P3,self.Q3,self.A3 I1,I2,I3= ID[1:4],ID[5:8],ID[9:12] z1,dz1,rho1,S1 = Vessel1['S'].Segment z2,dz2,rho2,S2 = Vessel2['S'].Segment z3,dz3,rho3,S3 = Vessel3['S'].Segment PQA1 = np.array([P1[I1[0]],Q1[I1[0]],A1[I1[0]]]) PQA2 = np.array([P2[I2[0]],Q2[I2[0]],A2[I2[0]]]) PQA3 = np.array([P3[I3[0]],Q3[I3[0]],A3[I3[0]]]) zi1 = z1[I1[0]] + I1[2]*S1.c_(rho1,A1[I1[0]],P1[I1[0]],I1[0])*dt zi2 = z2[I2[0]] + I2[2]*S2.c_(rho2,A2[I2[0]],P2[I2[0]],I2[0])*dt zi3 = z3[I3[0]] + I3[2]*S3.c_(rho3,A3[I3[0]],P3[I3[0]],I3[0])*dt du1 = np.array([np.interp(zi1,z1,P1),np.interp(zi1,z1,Q1),np.interp(zi1,z1,A1)])-PQA1 du2 = np.array([np.interp(zi2,z2,P2),np.interp(zi2,z2,Q2),np.interp(zi2,z2,A2)])-PQA2 du3 = np.array([np.interp(zi3,z3,P3),np.interp(zi3,z3,Q3),np.interp(zi3,z3,A3)])-PQA3 domega1 = np.dot(S1.L(PQA1,I1[0])[I1[1]],du1) domega2 = np.dot(S2.L(PQA2,I2[0])[I2[1]],du2) domega3 = np.dot(S3.L(PQA3,I3[0])[I3[1]],du3) x = [P1[I1[0]],Q1[I1[0]],A1[I1[0]],P2[I2[0]],Q2[I2[0]],A2[I2[0]],P3[I3[0]],Q3[I3[0]],A3[I3[0]]] if warningActivated == True: P1,Q1,A1,P2,Q2,A2,P3,Q3,A3 = fsolve(bifurcation_3,x,warning=warn,maxfev=maxfevfsolve,args=(PQA1,PQA2,PQA3,\ domega1,domega2,domega3,rho1,rho2,rho3,S1,S2,S3,I1,I2,I3)) else: P1,Q1,A1,P2,Q2,A2,P3,Q3,A3 = fsolve(bifurcation_3,x,args=(PQA1,PQA2,PQA3,\ domega1,domega2,domega3,rho1,rho2,rho3,S1,S2,S3,I1,I2,I3)) return P1,Q1,A1,P2,Q2,A2,P3,Q3,A3
def theta_infty(beta, xi, CRW=False): """ Asymptotic angle of bowshock. If choose CRW as True then use CRW solution for th_infty """ def f_infty(th, beta, xi): """ Function to be zeroed """ k = 2.0 / xi - 2 C = (k + 2 * (1 - beta)) / (k + 2) I = np.sqrt(np.pi) * gamma_func(0.5 * (k + 1)) / (4 * gamma_func(0.5 * k + 2)) D = np.pi + 2 * beta * I return th - C * np.tan(th) - D def f_CRW(th, beta): """ CRW implicit equation for th_infty """ return th - np.tan(th) - np.pi / (1.0 - beta) th_init = np.radians(91.0) if CRW: th_inf, infodict, ier, mesg = fsolve(f_CRW, th_init, args=(beta), full_output=True) else: th_inf, infodict, ier, mesg = fsolve(f_infty, th_init, args=(beta, xi), full_output=True) return th_inf
def f_colebrook(Re, eD): r"""Calculates friction factor `f` with Colebrook-White correlation (1939) .. math:: \frac{1}{\sqrt{f}}=-2\log\left(\frac{\epsilon/D}{3.7}+ \frac{2.51}{Re\sqrt{f}}\right) Parameters ------------ Re : float Reynolds number, [-] eD : float Relative roughness of a pipe, [-] Returns ------- f : float Friction factor, [-] Notes ----- This is the original, implicit expression, slowlest to solve """ fo = f_chen(Re, eD) if eD: f = fsolve(lambda x: 1/x**0.5+2.0*log10(eD/3.7+2.51/Re/x**0.5), fo) else: f = fsolve(lambda x: 1/x**0.5-2.0*log10(Re*x**0.5)+0.8, fo) return Dimensionless(f[0])
def get_agsne_lambdas(G, S, N, E, version = 'precise'): """Obtain the Lagrange multipliers lambda 1, beta (lambda 1 + lambda 2), lambda 3 for AGSNE. Two versions are available. For version = 'appox', estimations are obtained using Table 2 in Harte et al. 2015. For version = 'precise', estimations are obtained using S-16 to S-19 in Harte et al. 2015. """ lambda3 = G / (E - N) y1 = lambda x: x * np.log(x) - S / G # Here x is 1/lambda1 y2 = lambda x: x * np.log(x) - N / G # here x is 1 / beta inv_1 = fsolve(y1, 1)[0] inv_beta = fsolve(y2, 1)[0] if version == 'approx': out = [1/inv_1, 1/inv_beta, lambda3] else: # Try to provide a better initial guess by fixing lambda1 and solving for beta exp_1_approx = np.exp(-1/inv_1) Slist = np.arange(1, S + 1) #y3 = lambda x: np.sum(exp_1_approx ** Slist * np.log(1 / (1 - x ** Slist))) / np.sum(exp_1_approx ** Slist / Slist * np.log(1 / (1 - x ** Slist))) - S / G y3 = lambda x: np.sum((exp_1_approx * x) ** Slist / (1 - x ** Slist)) / np.sum(exp_1_approx ** Slist / Slist * np.log(1 / (1 - x ** Slist))) - N / G exp_beta_approx = bisect(y3, 10**-15, 1 - 10**-15) def lambdas(x): exp_1, exp_beta = x # The two elements are exp(-lambda1), and exp(-beta) f1 = np.sum(exp_1 ** Slist * np.log(1 / (1 - exp_beta ** Slist))) / np.sum(exp_1 ** Slist / Slist * np.log(1 / (1 - exp_beta ** Slist))) - S / G f2 = np.sum((exp_1 * exp_beta) ** Slist / (1 - exp_beta ** Slist)) / np.sum(exp_1 ** Slist / Slist * np.log(1 / (1 - exp_beta ** Slist))) - N / G return(f1, f2) exp_1, exp_beta = fsolve(lambdas, np.array((exp_1_approx, exp_beta_approx)), factor = 0.1, maxfev = 500) out = [-np.log(exp_1), -np.log(exp_beta), lambda3] return (out)
def pseudize_normalized(self, a_g, gc, l=0, points=3): """Construct normalized smooth continuation of a_g for g<gc. Same as pseudize() with also this constraint:: / 2 / 2 | dr b(r) = | dr a(r) / / """ b_g = self.pseudize(a_g, gc, l, points)[0] c_x = np.empty(points + 1) gc0 = gc // 2 x0 = b_g[gc0] r_g = self.r_g i = [gc0] + range(gc, gc + points) r_i = r_g[i] norm = self.integrate(a_g**2) def f(x): b_g[gc0] = x c_x[:] = np.polyfit(r_i**2, b_g[i] / r_i**l, points) b_g[:gc] = np.polyval(c_x, r_g[:gc]**2) * r_g[:gc]**l return self.integrate(b_g**2) - norm from scipy.optimize import fsolve fsolve(f, x0) return b_g, c_x[-1]
def analytic_sol(x): def elevation(x): z_b = zeros(len(x)) for i in range(len(x)): if (8.0 <= x[i] <= 12.0): z_b[i] = 0.2 - 0.05*(x[i]-10.0)**2.0 else: z_b[i] = 0.0 return z_b z = elevation(x) zM= max(z) def find_hM(hM): #to find the water height at the maxima of the bump return h_d**3 + (-q0**2/(2*g*hM**2)-hM-zM)*h_d**2 + q0**2/(2*g) hM = fsolve(find_hM, 0.5) def find_h(h): #to find the water height at every spatial point after hM is found return h**3 + (zb-q0**2/(2*g*hM**2)-hM-zM)*h**2 + q0**2/(2*g) h = zeros(len(x)) for i in range(len(x)): zb = z[i] #h[i] = fsolve(find_h, 1.0) if x[i] < 10: h[i] = fsolve(find_h, 1.0) else: h[i] = fsolve(find_h, 0.4) return h, z
def density(Tc,Pc,Z,Rc,P,T): Tr=T/Tc print P delta=1+(0.02*(1-.92*scipy.exp(-1000*scipy.absolute(1-Tr))-0.035*(Tr-1))*(Rc-1)) #print scipy.exp(-1000*scipy.absolute(1-Tr)) #print 'delta',delta delta=1+(0.02*-0.035*(Tr-1))*(Rc-1) a=.42748*R**2*Tc**2.5/Pc #print 'a', a b=(.08664*R*Tc/Pc)/delta #print 'b', b a=round(a,4) b=round (b,9) def eos(rho): f=P-(((rho*R*T)/(1-b*rho))-(a*rho**2/(T**.5*(1+b*rho)))) return f # Initial guess gas rho=P/(R*T) #print rho,1/rho rhog=fsolve(eos,rho) #print rhog,1/rhog #Initial guess liquid rl=1/b #print b #print rl,1/b rhol=fsolve(eos,rl) print rhol,1/rhol return rhog,rhol
def densities(p, S2, S1=S1, W=W): func = lambda x: pressure(x, S2, S1, W) - p rhomin, rhomax = stability_limits(S2, S1, W) rho1 = optimize.fsolve(func, rhomin-delta_rho)[0] rho2 = optimize.fsolve(func, 0.5*(rhomin+rhomax))[0] rho3 = optimize.fsolve(func, rhomax+delta_rho)[0] return rho1, rho2, rho3
def tangent(T, P_bar, Tc_1, Pc_bar_1, m_1, Tc_2, Pc_bar_2, m_2, Go1, Go2, plot=True): def Gmix(x): return dG_RT(T, P_bar, x, Tc_1, Pc_bar_1, m_1, Tc_2, Pc_bar_2, m_2, Go1, Go2) def d_Gmix(x): return deriv_dG_RT(T, P_bar, x, Tc_1, Pc_bar_1, m_1, Tc_2, Pc_bar_2, m_2, Go1, Go2) min_root = sc_o.fsolve(d_Gmix, 0.01) max_root = sc_o.fsolve(d_Gmix, 0.98) bnds = ((0.001, max_root[0]*0.8),(min_root[0]*1.1, 0.999)) init = [min_root[0]*1.1, 0.999] def resid(x_vect): xa, xb = x_vect m1 = d_Gmix(xa) m2 = d_Gmix(xb) lineslope = (Gmix(xa) - Gmix(xb))/(xa - xb) return [m1 - m2, m2 - lineslope] out = sc_o.fsolve(resid,init) return out
def get_profile(profile_fname, z0, D, uj, vj, wj, Tj, Sj, ua, T, F, sign_dp, H): """ Create and ambient profile dataset for an integral jet model simulation """ # Use mks units g = 9.81 rho_w = 1000. Pa = 101325. # Get the ambient density at the discharge from F (Assume water is # incompressible for these laboratory experiments) rho_j = seawater.density(Tj, Sj, 101325. + rho_w * g * z0) Vj = np.sqrt(uj**2 + vj**2 + wj**2) if F == 0.: rho_a = rho_j else: rho_a = rho_j / (1. - Vj**2 / (sign_dp * F**2 * D * g)) # Get the ambient stratification at the discharge from T if T == 0.: dpdz = 0. else: dpdz = sign_dp * (rho_a - rho_j) / (T * D) # Find the salinity at the discharge assuming the discharge temperature # matches the ambient temperature Ta = Tj def residual(Sa, rho, H): """ docstring for residual """ return rho - seawater.density(Ta, Sa, Pa + rho_w * g * H) Sa = fsolve(residual, 0., args=(rho_a, z0)) # Find the salinity at the top and bottom assuming linear stratification if dpdz == 0.: S0 = Sa SH = Sa else: rho_H = dpdz * (H - z0) + rho_a rho_0 = dpdz * (0.- z0) + rho_a # Use potential density to get the salinity SH = fsolve(residual, Sa, args=(rho_H, z0)) S0 = fsolve(residual, Sa, args=(rho_0, z0)) # Build the ambient data arrays z = np.array([0., H]) T = np.array([Ta, Ta]) S = np.array([S0, SH]) ua = np.array([ua, ua]) # Build the profile profile = build_profile(profile_fname, z, T, S, ua) # Return the ambient data return profile
def calculo(self): self.entrada = self.kwargs["entrada"] metodo = self.kwargs["metodo"] self.Pout = Pressure(self.kwargs["Pout"]) razon = self.kwargs["razon"] self.rendimientoCalculado = Dimensionless(self.kwargs["rendimiento"]) if self.kwargs["etapas"]: self.etapas = self.kwargs["etapas"] else: self.etapas = 1. self.power = Power(self.kwargs["trabajo"]) def f(Pout, rendimiento): W_ideal = self.__Wideal(Pout) power = W_ideal*self.entrada.caudalmasico.gs/rendimiento return power if metodo in [0, 3] or (metodo == 5 and self.Pout): if self.etapas == 1: razon = self.Pout.atm/self.entrada.P.atm else: razon = (self.Pout.atm/self.entrada.P.atm)**(1./self.etapas) elif metodo in [1, 4] or (metodo == 5 and razon): if self.etapas == 1: self.Pout = Pressure(self.entrada.P*razon) else: self.Pout = Pressure(razon**self.etapas*self.entrada.P) if metodo in [0, 1]: Wid = self.__Wideal(self.Pout.atm) power = Wid*self.entrada.caudalmasico.gs/self.rendimientoCalculado self.power = Power(power*self.etapas) elif metodo == 2: def funcion(P): return f(P, self.rendimientoCalculado)-self.power self.Pout = Pressure(fsolve(funcion, self.entrada.P+1)) if self.etapas == 1: razon = self.Pout/self.entrada.P else: razon = (self.Pout/self.entrada.P)**(1./self.etapas) elif metodo in [3, 4]: def funcion(rendimiento): return f(self.Pout.atm, rendimiento)-self.power self.rendimientoCalculado = Dimensionless(fsolve(funcion, 0.5)) elif metodo == 5: Wideal = self.__Wideal(self.Pout.atm) G = MassFlow(self.power*self.rendimientoCalculado/Wideal, "gs") self.Tout = self.__Tout(Wideal) self.entrada = self.entrada.clone(caudalMasico=G) Wideal = self.__Wideal(self.Pout.atm) self.Tout = Temperature(self.__Tout(Wideal)) self.salida = [self.entrada.clone(T=self.Tout, P=self.Pout)] self.razonCalculada = Dimensionless(self.Pout/self.entrada.P) self.deltaT = DeltaT(self.salida[0].T-self.entrada.T) self.deltaP = DeltaP(self.salida[0].P-self.entrada.P) self.cp_cv = self.entrada.Gas.cp_cv self.Pin = self.entrada.P self.Tin = self.entrada.T
def xMorse(En, a, V0): global lastx1 print ("Morse E = %s"%En) x0 = fsolve(lambda x: abs(EMorse(x, a, V0) - En)**2, x0=0.0) x1 = fsolve(lambda x: abs(EMorse(x, a, V0) - En)**2, x0=lastx1) lastx1 = x1 print x0, x1 return x0, x1
def findz(N, E, beta): z_0 = np.exp(beta * E[0]) func = lambda z: (np.sum(n_bose(E[1:], beta, z)) + z/(z_0-z) - N) #** 2. + (z > z_0) * 1000. * (z-z_0) z = opt.fsolve(func, z_0* N / (1 + N)) if z >= z_0: func = lambda z: (np.sum(n_bose(E[1:], beta, z_0)) + z/(z_0-z) - N) #** 2. + (z > z_0) * 1000. * (z-z_0) z = opt.fsolve(func, z_0*N / (1 + N)) return z
def test_Dfun_can_raise(self): func = lambda x: x - np.array([10]) def deriv_func(*args): raise ValueError('I raised') with assert_raises(ValueError, match='I raised'): optimize.fsolve(func, x0=[0], fprime=deriv_func)
def initialize(self): # Variables self.lab = sqrt(self.k * self.H * self.c) self.nu = (self.rhos - self.rhof) / self.rhof self.mu = self.grad * self.lab / self.H / self.nu # Case I or Case II if self.mu < sqrt(2 / 3): self.Loverlab = (18 * self.mu) ** (1 / 3) # Eq. 25 if self.Loverlab * self.lab <= self.L: self.case = 1 self.doverlab = (1 - (3 * self.mu ** 2 / 2) ** (2 / 3)) / ( 2 * self.mu) # Eq.28 self.phi0 = (3 * self.mu ** 2 / 2) ** (1 / 3) else: self.case = None else: self.Loverlab = sqrt(6) # Eq. 29 self.doverlab = log((self.mu + sqrt(self.mu ** 2 + 1 / 3)) / ( 1 + sqrt(2 / 3))) # Eq.38 if self.Loverlab * self.lab + self.doverlab * self.lab <= self.L: self.case = 2 self.phicoast = (1 - sqrt(2 / 3)) / 2 * exp(-self.doverlab) + \ (1 + sqrt(2 / 3)) / 2 * exp(self.doverlab) else: self.case = None if self.case is None: self.Lsoverlab = self.L / self.lab atr = fsolve(self.find_atr, 0.1) # Eq. 46 mutr = sqrt(2 * (1 + atr ** 3) / 3) # Eq. 47 if self.mu < mutr: self.case = 3 amax = (3 * self.mu ** 2 / 2) ** (1 / 3) rv = fsolve(self.find_a_case3, amax / 2, full_output=1) if rv[2] == 1: self.a = rv[0] self.phi0 = (3 * self.mu ** 2 / 2 - self.a ** 3) ** ( 1 / 3) # Eq. 48 #self.doverlab = (1 - (3 * self.mu ** 2 / 2) ** (2 / 3)) / ( #2 * self.mu) # Eq.28 self.doverlab = (1 - self.phi0 ** 2) / ( 2 * self.mu) # Eq.27 solved for u with phi=1 and phi0 else: print('Error: a was not found for case 3, mu was:' + str(self.mu)) else: self.case = 4 rv = brentq(self.find_doverlab_case4, 0, self.Lsoverlab, full_output=1) if rv[1].converged == 1: self.doverlab = rv[0] gamma0 = -tanh(self.doverlab) + self.mu / cosh( self.doverlab) # Eq.53 self.a = (3 * gamma0 ** 2 / 2 - 1) ** (1 / 3) # Eq.54 self.phicoast = 1.0 / cosh(self.doverlab) - self.mu * \ sinh(-self.doverlab) / cosh(self.doverlab) else: print('Error: doverlab was not found for case 4')
def J_r(self,x,y,z,vx,vy,vz): ### Peri- und Apocenter Suche noch verbessern, nicht min(rl)/max(rl) sondern irgendwie kleine bzw gro�e Werte finden abhaengig von r ### rmin=opt.fsolve(periapocenter,np.min(r)) #nicht min(rl) sondern einfach kleiner Wert weil ich es erst durch orbit integration weiss rmax=opt.fsolve(periapocenter,np.max(r)) #^-- 30. So kann man es durchaus auch machen (dann kannst du meine Kommentare 28., 26b. und 27. ignorieren. Allerdings waere es ja auch huebsch, eine Funktion zu haben, die von aussen aufgerufen werden kann und dir fuer einen gegebenen Stern pericenter und apocenter berechnet, unabhaengig von allem anderen. Hier kannst du die Funktion dann aufrufen. J_r=1/np.pi*intg.quad(j_rint,rmin,rmax)[0] return J_r
def qubit_extrema(self, c, I0, L, bias, C): """Calculates the extrema in a qubit potential. Returns the phases found by solving for dU/dphi = 0, starting with initial guesses phi = 0, phi = pi and phi = 2*pi. """ I0, L, bias, C = float(I0), float(L), float(bias), float(C) dU = self.qubit_dU(c, I0, L, bias, C) return array([fsolve(dU, 0), fsolve(dU, pi), fsolve(dU, 2*pi)])
def ComputeLibrationPoints(mu): # Inputs: mu = m2/M = (mass of smaller body) / (total mass) # In nondimensional units, r12 = 1, M = 1, Period/(2pi) = 1, G = 1 # Position of larger body along X axis: X1 = np.array([-mu, 0, 0]); # Position of smaller body along X axis: X2 = np.array([1.0-mu, 0, 0]); # Functions from notes from Brent Barbee's class ENAE601, 10/12/2011, and HW 4, 10/17/2011 def f_L1(x, mu): p = 1.0 - mu - x return (1.0 - mu)*(p**3.0)*(p**2.0 - 3.0*p + 3.0) - mu*(p**2.0 + p + 1.0)*(1.0 - p)**3.0 def f_L2(x, mu): p = mu - 1.0 + x return (1.0 - mu)*(p**3.0)*(p**2.0 + 3.0*p + 3.0) - mu*(p**2.0 + p + 1.0)*(1.0 - p)*(p + 1.0)**2.0 def f_L3(x, mu): p = -x - mu return (1.0 - mu)*(p**2.0 + p + 1.0)*(p - 1.0)*(p + 1.0)**2.0 + mu*(p**3.0)*(p**2.0 + 3.0*p + 3.0) # Find roots of the functions with fsolve, providing an initial guess l1 = fsolve(f_L1, 0.7, args=(mu,)); l2 = fsolve(f_L2, 1.2, args=(mu,)); l3 = fsolve(f_L3, -1.1, args=(mu,)); # L1 L1 = np.array([l1[0], 0.0, 0.0]); # L2 L2 = np.array([l2[0], 0.0, 0.0]); # L3 L3 = np.array([l3[0], 0.0, 0.0]); # L4 L4 = np.array([0.5 - mu, np.sqrt(3.0)/2.0, 0.0]); # L5 L5 = np.array([0.5 - mu, -np.sqrt(3.0)/2.0, 0.0]); return pd.Series({ "X1": X1, "X2": X2, "L1": L1, "L2": L2, "L3": L3, "L4": L4, "L5": L5})
def DISCON(avrSWAP_py, from_SC_py, to_SC_py): if logic.counter == 0: import globalDISCON import OBSERVER import yawerrmeas logic.counter = logic.counter + 1 elif logic.counter == 1: import globalDISCON1 as globalDISCON import OBSERVER1 as OBSERVER import yawerrmeas1 as yawerrmeas logic.counter = logic.counter + 1 elif logic.counter == 2: import globalDISCON2 as globalDISCON import OBSERVER2 as OBSERVER import yawerrmeas2 as yawerrmeas logic.counter = 0 #print("SIAMO ENTRATI IN DISCON.py") #print("from_SC_py in DISCON.py: ", from_SC_py) #print(avrSWAP_py[95], avrSWAP_py[26]) VS_RtGnSp = 121.6805 VS_SlPc = 10.00 VS_Rgn2K = 2.332287 VS_Rgn2Sp = 91.21091 VS_CtInSp = 70.16224 VS_RtPwr = 5296610.0 CornerFreq = 1.570796 #1.570796 PC_MaxPit = 1.570796 # ERA 1.570796 rad PC_DT = 0.000125 VS_DT = 0.000125 OnePlusEps = 1 + sys.float_info.epsilon VS_MaxTq = 47402.91 BlPitch = numpy.zeros(3) PitRate = numpy.zeros(3) VS_Rgn3MP = 0.01745329 PC_KK = 0.1099965 PC_KI = 0.008068634 PC_KP = 0.01882681 PC_RefSpd = 122.9096 VS_MaxRat = 15000.0 PC_MaxRat = 0.1396263 #0.1396263 YawSpr = 9.02832e9 YawDamp = 1.916e7 YawIn = 2.60789e6 kdYaw = 1e7 kpYaw = 5e7 kiYaw = 1e9 tauF = (1 / 3) * ((2 * numpy.pi) / 1.2671) Ts = 0.005 iStatus = int(round(avrSWAP_py[0])) NumBl = int(round(avrSWAP_py[60])) PC_MinPit = 0.0 #print("PC_MinPit in DISCON.py: ", PC_MinPit) #print("NumBl in DISCON.py: ", NumBl) #print("OnePLUSEps ", OnePlusEps) BlPitch[0] = min(max(avrSWAP_py[3], PC_MinPit), PC_MaxPit) BlPitch[1] = min(max(avrSWAP_py[32], PC_MinPit), PC_MaxPit) BlPitch[2] = min(max(avrSWAP_py[33], PC_MinPit), PC_MaxPit) GenSpeed = avrSWAP_py[19] HorWindV = avrSWAP_py[26] Time = avrSWAP_py[1] aviFAIL_py = 0 if iStatus == 0: globalDISCON.VS_SySp = VS_RtGnSp / (1.0 + 0.01 * VS_SlPc) globalDISCON.VS_Slope15 = (VS_Rgn2K * VS_Rgn2Sp * VS_Rgn2Sp) / (VS_Rgn2Sp - VS_CtInSp) globalDISCON.VS_Slope25 = (VS_RtPwr / VS_RtGnSp) / ( VS_RtGnSp - globalDISCON.VS_SySp) if VS_Rgn2K == 0: globalDISCON.VS_TrGnSp = globalDISCON.VS_SySp else: globalDISCON.VS_TrGnSp = (globalDISCON.VS_Slope25 - math.sqrt( globalDISCON.VS_Slope25 * (globalDISCON.VS_Slope25 - 4.0 * VS_Rgn2K * globalDISCON.VS_SySp))) / (2.0 * VS_Rgn2K) globalDISCON.GenSpeedF = GenSpeed globalDISCON.PitCom = BlPitch #print("PitCom: ", globalDISCON.PitCom) #print("BlPitch: ", BlPitch) GK = 1.0 / (1.0 + globalDISCON.PitCom[0] / PC_KK) globalDISCON.IntSpdErr = globalDISCON.PitCom[0] / (GK * PC_KI) globalDISCON.LastTime = Time globalDISCON.LastTimePC = Time - PC_DT globalDISCON.LastTimeVS = Time - VS_DT print("0") if iStatus >= 0 and aviFAIL_py >= 0: avrSWAP_py[35] = 0.0 avrSWAP_py[40] = 0.0 avrSWAP_py[45] = 0.0 avrSWAP_py[47] = 0.0 avrSWAP_py[64] = 0.0 avrSWAP_py[71] = 0.0 avrSWAP_py[78] = 0.0 avrSWAP_py[79] = 0.0 avrSWAP_py[80] = 0.0 Alpha = math.exp((globalDISCON.LastTime - Time) * CornerFreq) globalDISCON.GenSpeedF = ( 1.0 - Alpha) * GenSpeed + Alpha * globalDISCON.GenSpeedF ElapTime = Time - globalDISCON.LastTimeVS print("1 ", ElapTime) print("globalDISCON.LastTimeVS: ", globalDISCON.LastTimeVS) print("Time*OnePlusEps - globalDISCON.LastTimeVS: ", Time * OnePlusEps - globalDISCON.LastTimeVS) if (Time * OnePlusEps - globalDISCON.LastTimeVS) >= VS_DT: print("GenSPeedF: ", globalDISCON.GenSpeedF) print("PitCom: ", globalDISCON.PitCom[0]) if globalDISCON.GenSpeedF >= VS_RtGnSp or globalDISCON.PitCom[ 0] >= VS_Rgn3MP: GenTrq = VS_RtPwr / globalDISCON.GenSpeedF print("A") print("GenTrq: ", GenTrq) elif globalDISCON.GenSpeedF <= VS_CtInSp: GenTrq = 0.0 print("B") elif globalDISCON.GenSpeedF < VS_Rgn2Sp: GenTrq = globalDISCON.VS_Slope15 * (globalDISCON.GenSpeedF - VS_CtInSp) print("C") elif globalDISCON.GenSpeedF < globalDISCON.VS_TrGnSp: GenTrq = VS_Rgn2K * globalDISCON.GenSpeedF * globalDISCON.GenSpeedF print("D") else: GenTrq = globalDISCON.VS_Slope25 * (globalDISCON.GenSpeedF - globalDISCON.VS_SySp) print("E") GenTrq = min(GenTrq, VS_MaxTq) print("2: ", GenTrq) if iStatus == 0: globalDISCON.LastGenTrq = GenTrq TrqRate = (GenTrq - globalDISCON.LastGenTrq) / ElapTime TrqRate = min(max(TrqRate, -VS_MaxRat), VS_MaxRat) GenTrq = globalDISCON.LastGenTrq + TrqRate * ElapTime globalDISCON.LastTimeVS = Time globalDISCON.LastGenTrq = GenTrq print("3") avrSWAP_py[34] = 1.0 avrSWAP_py[55] = 0.0 avrSWAP_py[46] = globalDISCON.LastGenTrq print("Time ", Time) ElapTime = Time - globalDISCON.LastTimePC print("ELAP Time ", ElapTime) print("LASTTIMEPC Time ", globalDISCON.LastTimePC) if (Time * OnePlusEps - globalDISCON.LastTimePC) >= PC_DT: GK = 1.0 / (1.0 + globalDISCON.PitCom[0] / PC_KK) SpdErr = globalDISCON.GenSpeedF - PC_RefSpd globalDISCON.IntSpdErr = globalDISCON.IntSpdErr + SpdErr * ElapTime globalDISCON.IntSpdErr = min( max(globalDISCON.IntSpdErr, PC_MinPit / (GK * PC_KI)), PC_MaxPit / (GK * PC_KI)) PitComP = GK * PC_KP * SpdErr PitComI = GK * PC_KI * globalDISCON.IntSpdErr PitComT = PitComP + PitComI PitComT = min(max(PitComT, PC_MinPit), PC_MaxPit) for i in range(NumBl): PitRate[i] = (PitComT - BlPitch[i]) / ElapTime PitRate[i] = min(max(PitRate[i], -PC_MaxRat), PC_MaxRat) globalDISCON.PitCom[i] = BlPitch[i] + PitRate[i] * ElapTime globalDISCON.PitCom[i] = min( max(globalDISCON.PitCom[i], PC_MinPit), PC_MaxPit) globalDISCON.LastTimePC = Time print("4") #print("PitCom: ", globalDISCON.PitCom) avrSWAP_py[54] = 0.0 avrSWAP_py[41] = globalDISCON.PitCom[0] avrSWAP_py[42] = globalDISCON.PitCom[1] avrSWAP_py[43] = globalDISCON.PitCom[2] avrSWAP_py[44] = globalDISCON.PitCom[0] # COMMANDING YAW RATE globalDISCON.YawAngleGA = from_SC_py #if Time > 70.0: if logic.counter < 4: if Time > 40.0 and Time < 55.0: avrSWAP_py[ 28] = 1 # --> YAW CONTROL 0 = SPEED CONTROL, 1 = TORQUE CONTROL # SETTING POSITION TO BE REACHED AT 0.1 rad --> PI CONTROLLER ( I is INTEGRAL of 0.1rad in time) # avrSwap_py[23] --> YawRate Good for PID -- Derivative term if not numpy.isclose( abs(avrSWAP_py[36]), 0.174533) and globalDISCON.flagyaw == False: #if (not numpy.isclose(avrSWAP_py[36], globalDISCON.PosYawRef)) and (not numpy.isclose(avrSWAP_py[23], 0.0)) and globalDISCON.flag_yaw == False: #globalDISCON.IntYawRef = globalDISCON.IntYawRef + globalDISCON.PosYawRef * ElapTime #globalDISCON.IntYaw = globalDISCON.IntYaw + avrSWAP_py[36] * ElapTime #avrSWAP_py[47] = kpYaw * (globalDISCON.PosYawRef - avrSWAP_py[36]) + kiYaw * (globalDISCON.IntYawRef - globalDISCON.IntYaw) if abs(globalDISCON.PosYawRef) < 0.174533: globalDISCON.VelYawRef = 0.0349066 / 3 globalDISCON.PosYawRef = globalDISCON.PosYawRef + globalDISCON.VelYawRef * ElapTime else: if Time > 54.0: globalDISCON.flagyaw = True globalDISCON.VelYawRef = 0.0 avrSWAP_py[47] = kiYaw * ( globalDISCON.PosYawRef - avrSWAP_py[36]) + kpYaw * ( globalDISCON.VelYawRef - avrSWAP_py[23]) - YawDamp * avrSWAP_py[23] else: # HERE I CONSIDER PERTURBATIONS ABOUT THE NEW WORKING POSITION #globalDISCON.flagyaw = True globalDISCON.IntYawRef = globalDISCON.IntYawRef + globalDISCON.PosYawRef * ElapTime globalDISCON.IntYaw = globalDISCON.IntYaw + avrSWAP_py[ 36] * ElapTime avrSWAP_py[47] = -YawDamp * ( avrSWAP_py[23] - 0.0) - YawSpr * ( avrSWAP_py[36] - globalDISCON.PosYawRef ) + kpYaw * (globalDISCON.PosYawRef - avrSWAP_py[36] ) + kiYaw * (globalDISCON.IntYawRef - globalDISCON.IntYaw) else: avrSWAP_py[ 28] = 1 # --> YAW CONTROL 0 = SPEED CONTROL, 1 = TORQUE CONTROL # SETTING POSITION TO BE REACHED AT 0.1 rad --> PI CONTROLLER ( I is INTEGRAL of 0.1rad in time) globalDISCON.IntYawRef = globalDISCON.IntYawRef + globalDISCON.PosYawRef * ElapTime globalDISCON.IntYaw = globalDISCON.IntYaw + avrSWAP_py[ 36] * ElapTime avrSWAP_py[47] = -YawDamp * (avrSWAP_py[23] - 0.0) - YawSpr * ( avrSWAP_py[36] - globalDISCON.PosYawRef) + kpYaw * ( globalDISCON.PosYawRef - avrSWAP_py[36]) + kiYaw * ( globalDISCON.IntYawRef - globalDISCON.IntYaw) # avrSwap_py[23] --> YawRate Good for PID -- Derivative term if globalDISCON.counterY >= 2.0: avrSWAP_py[28] = 1 if not numpy.isclose( abs(avrSWAP_py[36]), abs(globalDISCON.PosYawRef - globalDISCON.PosFin) ) and globalDISCON.flagyaw == False: #if (not numpy.isclose(avrSWAP_py[36], globalDISCON.PosYawRef)) and (not numpy.isclose(avrSWAP_py[23], 0.0)) and globalDISCON.flag_yaw == False: #globalDISCON.IntYawRef = globalDISCON.IntYawRef + globalDISCON.PosYawRef * ElapTime #globalDISCON.IntYaw = globalDISCON.IntYaw + avrSWAP_py[36] * ElapTime #avrSWAP_py[47] = kpYaw * (globalDISCON.PosYawRef - avrSWAP_py[36]) + kiYaw * (globalDISCON.IntYawRef - globalDISCON.IntYaw) #if numpy.sign(globalDISCON.PosFin - globalDISCON.PosYawRef) == globalDISCON.signold: if abs(globalDISCON.PosYawRef - globalDISCON.PosFin) > 0.004: globalDISCON.VelYawRef = globalDISCON.signold * 0.0349066 / 3 globalDISCON.PosYawRef = globalDISCON.PosYawRef + globalDISCON.VelYawRef * ElapTime else: #if Time > 72.0: globalDISCON.flagyaw = True globalDISCON.VelYawRef = 0.0 avrSWAP_py[47] = kiYaw * ( globalDISCON.PosYawRef - avrSWAP_py[36] ) + kpYaw * (globalDISCON.VelYawRef - avrSWAP_py[23]) - YawDamp * avrSWAP_py[23] else: # HERE I CONSIDER PERTURBATIONS ABOUT THE NEW WORKING POSITION #globalDISCON.flagyaw = True globalDISCON.IntYawRef = globalDISCON.IntYawRef + globalDISCON.PosYawRef * ElapTime globalDISCON.IntYaw = globalDISCON.IntYaw + avrSWAP_py[ 36] * ElapTime avrSWAP_py[47] = -YawDamp * ( avrSWAP_py[23] - 0.0) - YawSpr * ( avrSWAP_py[36] - globalDISCON.PosYawRef ) + kpYaw * (globalDISCON.PosYawRef - avrSWAP_py[36]) + kiYaw * ( globalDISCON.IntYawRef - globalDISCON.IntYaw) #globalDISCON.signold = numpy.sign(globalDISCON.PosFin - globalDISCON.PosYawRef) print( "TOTAL TORQUE TERM PASSED TO SERVODYN FOR YAW CONTROL ----> ", avrSWAP_py[47]) '''if Time > 70.0 and Time < 85.0: avrSWAP_py[47] = 0.0349066/3 else: avrSWAP_py[47] = 0.0''' else: avrSWAP_py[28] = 0 #else: # avrSWAP_py[28] = 0 '''avrSWAP_py[28] = 0 # DOPO LEVALO avrSWAP_py[47] = 0.0''' # END OF COMMANDED YAW RATE ON TURBINE 1 #YAW LOGIC BLOCK globalDISCON.LastTime = Time print("globalDISCON.LastTime: ", globalDISCON.LastTime) # INPUTS FOR SUPERCONTROLLER to_SC_py = avrSWAP_py[14] # MEASURED POWER OUTPUT avrSWAP_py = numpy.append(avrSWAP_py, to_SC_py) to_SC_py = avrSWAP_py[36] # ACTUAL YAW ANGLE avrSWAP_py = numpy.append(avrSWAP_py, to_SC_py) # END OF SECTION # WIND SPEED OBSERVER SECTION file = open("Bl1outin.txt", "a+") file.write("%f, %f, %f \n" % (avrSWAP_py[29], avrSWAP_py[68], Time)) file.close() file = open("Bl2outin.txt", "a+") file.write("%f, %f, %f \n" % (avrSWAP_py[30], avrSWAP_py[69], Time)) file.close() file = open("Bl3outin.txt", "a+") file.write("%f, %f, %f \n" % (avrSWAP_py[31], avrSWAP_py[70], Time)) file.close() #file = open("Azimuth.txt","a+") #file.write("%f, %f, %f, %f \n" % (avrSWAP_py[59], avrSWAP_py[20], avrSWAP_py[26], Time)) #file.close() #if from_SC_py == 0: tmp = float(OBSERVER.tmp) #POSG acc = float(OBSERVER.acc) #POSR OBSERVER.y = avrSWAP_py[19] #print("tmp: ", OBSERVER.tmp) #print("acc: ", OBSERVER.acc) #print("y: ", OBSERVER.y) OBSERVER.Qg = avrSWAP_py[22] #print("Qg: ", avrSWAP_py[22]) if numpy.isclose(Time, 0.0): x0 = numpy.array([1.5, 120, 0, 0]) xsol = numpy.array([1.5, 120, 0, 0]) OBSERVER.xsol = xsol xppsolin = numpy.array([0, 0, 1.5, 120]) #print(xsol) Qasol = OBSERVER.Qacalc(xppsolin, xsol, float(OBSERVER.y), float(OBSERVER.tmp)) error = 0.0 errorposg = 0.0 errorposr = 0.0 errorwr = 0.0 errorwg = 0.0 pitch_obs = (avrSWAP_py[3] + avrSWAP_py[32] + avrSWAP_py[33]) * 180 / (3 * numpy.pi) if pitch_obs > 17.9: pitch_obs = 17.9 elif pitch_obs < -10: pitch_obs = -10 num = (2 * Qasol) / (numpy.pi * OBSERVER.rho * (xsol[0]**2) * (OBSERVER.R**5)) tsr_obs = optim.fsolve(OBSERVER.func_impl, 4.5, args=(num, pitch_obs)) vento_obs = xsol[0] * OBSERVER.R / tsr_obs file = open("EXSOL.txt", "a+") file.write("%f, %f, %f, %f, %f \n" % (xsol[0], xsol[1], xsol[2], xsol[3], Time)) file.close() file = open("Azimuth.txt", "a+") file.write("%f, %f, %f, %f \n" % (xsol[2], xsol[0], vento_obs, Time)) file.close() else: x0 = OBSERVER.xsol if numpy.isclose(ElapTime, 0.0): ElapTime = 0.005 #print(OBSERVER.xsolold) #input("ELAP TIME = 0.0 PROBLEM") ts = numpy.linspace(Time - ElapTime, Time, 2) xsol = odeint(OBSERVER.dx_dt, x0, ts, args=(float(OBSERVER.y), float(OBSERVER.tmp))) #print("SOL SHAPE: ", numpy.shape(xsol)) OBSERVER.xsol = xsol[-1, :] OBSERVER.xsolold = numpy.vstack((OBSERVER.xsolold, OBSERVER.xsol)) xppsolin = numpy.gradient(OBSERVER.xsolold, ElapTime, axis=0) #print("SOL: ", xsol) #print("XOLD: ", OBSERVER.xsolold) xppsol = OBSERVER.xpp(xsol[-1, :], float(OBSERVER.y), float(OBSERVER.tmp)) #print("INERTIA: ", xppsol) #print("INERTIA: ", xppsolin[-1,:]) Qasol = OBSERVER.Qacalc(xppsolin[-1, :], xsol[-1, :], float(OBSERVER.y), float(OBSERVER.tmp)) error = (Qasol - (avrSWAP_py[13] / avrSWAP_py[20])) / (avrSWAP_py[13] / avrSWAP_py[20]) errorposg = (OBSERVER.tmp - xsol[-1, 3]) / xsol[-1, 3] errorposr = (OBSERVER.acc - xsol[-1, 2]) / xsol[-1, 2] errorwr = (avrSWAP_py[20] - xsol[-1, 0]) / avrSWAP_py[20] errorwg = (avrSWAP_py[19] - xsol[-1, 1]) / avrSWAP_py[19] pitch_obs = (avrSWAP_py[3] + avrSWAP_py[32] + avrSWAP_py[33]) * 180 / (3 * numpy.pi) if pitch_obs > 17.9: pitch_obs = 17.9 elif pitch_obs < -10: pitch_obs = -10 num = (2 * Qasol) / (numpy.pi * OBSERVER.rho * (xsol[-1, 0]**2) * (OBSERVER.R**5)) tsr_obs = optim.fsolve(OBSERVER.func_impl, 4.5, args=(num, pitch_obs)) vento_obs = xsol[-1, 0] * OBSERVER.R / tsr_obs file = open("EXSOL.txt", "a+") file.write( "%f, %f, %f, %f, %f \n" % (xsol[-1, 0], xsol[-1, 1], xsol[-1, 2], xsol[-1, 3], Time)) file.close() file = open("Azimuth.txt", "a+") file.write("%f, %f, %f, %f \n" % (xsol[-1, 2], xsol[-1, 0], vento_obs, Time)) file.close() if vento_obs > 25: vento_obs = 25 elif vento_obs < 3: vento_obs = 3 file = open("Error.txt", "a+") file.write("%f, %f \n" % (error, Time)) file.close() file = open("ErrorPosg.txt", "a+") file.write("%f, %f \n" % (errorposg, Time)) file.close() file = open("ErrorPosr.txt", "a+") file.write("%f, %f \n" % (errorposr, Time)) file.close() file = open("ErrorWG.txt", "a+") file.write("%f, %f \n" % (errorwg, Time)) file.close() file = open("ErrorWR.txt", "a+") file.write("%f, %f \n" % (errorwr, Time)) file.close() file = open("EWR.txt", "a+") file.write("%f, %f \n" % (avrSWAP_py[20], Time)) file.close() file = open("EWG.txt", "a+") file.write("%f, %f \n" % (avrSWAP_py[19], Time)) file.close() file = open("EPOSG.txt", "a+") file.write("%f, %f \n" % (tmp, Time)) file.close() file = open("EPOSR.txt", "a+") file.write("%f, %f \n" % (acc, Time)) file.close() file = open("EPitch.txt", "a+") file.write("%f, %f, %f \n" % ((avrSWAP_py[3] + avrSWAP_py[32] + avrSWAP_py[33]) * 180 / (3 * numpy.pi), pitch_obs, Time)) file.close() file = open("EWIND.txt", "a+") file.write("%f, %f, %f \n" % (vento_obs, Time, HorWindV)) file.close() file = open("EQasol.txt", "a+") file.write("%f, %f \n" % (Qasol, Time)) file.close() file = open("ENum.txt", "a+") file.write("%f, %f \n" % (num, Time)) file.close() OBSERVER.tmp = float(avrSWAP_py[19] * ElapTime + tmp) OBSERVER.acc = float(avrSWAP_py[20] * ElapTime + acc) #print("ERROR: ", error) #print("Qa: ", Qasol) #print("Qareal: ", avrSWAP_py[13]/avrSWAP_py[20]) #print("POWER: ", avrSWAP_py[13]) #WIND YAW ERROR OBSERVER SECTION blmom1 = numpy.array([avrSWAP_py[29], avrSWAP_py[68]]) blmom2 = numpy.array([avrSWAP_py[30], avrSWAP_py[69]]) blmom3 = numpy.array([avrSWAP_py[31], avrSWAP_py[70]]) N = 1 if numpy.isclose(Time, 0.0): azimuth = numpy.array([ xsol[2], xsol[2] + 2 * numpy.pi / 3, xsol[2] + 4 * numpy.pi / 3 ]) wryaw = xsol[0] globalDISCON.wr_old = wryaw # (1/(2*tauF + Ts)) * ((2*tauF - Ts)*globalDISCON.m_out1f_old + Ts*(m_out1 + globalDISCON.m_out1_old)) globalDISCON.wrf_old = wryaw globalDISCON.azimuth_old = azimuth globalDISCON.azimuthf_old = azimuth m_out1 = 1 m_out2 = 0 m_out3 = 0 m_in1 = 1 m_in2 = 0 m_in3 = 0 yawerrmeas.bl1_old = blmom1 yawerrmeas.bl2_old = blmom2 yawerrmeas.bl3_old = blmom3 yawerrmeas.azimuth_old = azimuth[0] else: #azimuth = (1/(2*tauF + Ts)) * ((2*tauF - Ts)*globalDISCON.azimuthf_old + Ts*(numpy.array([xsol[-1,2], xsol[-1,2] + 2*numpy.pi/3, xsol[-1,2] + 4*numpy.pi/3]) + globalDISCON.azimuth_old)) #wryaw = (1/(2*tauF + Ts)) * ((2*tauF - Ts)*globalDISCON.wrf_old + Ts*(xsol[-1,0] + globalDISCON.wr_old)) azimuth = numpy.array([ xsol[-1, 2], xsol[-1, 2] + 2 * numpy.pi / 3, xsol[-1, 2] + 4 * numpy.pi / 3 ]) wryaw = xsol[-1, 0] globalDISCON.wr_old = xsol[-1, 0] globalDISCON.azimuth_old = numpy.array([ xsol[-1, 2], xsol[-1, 2] + 2 * numpy.pi / 3, xsol[-1, 2] + 4 * numpy.pi / 3 ]) globalDISCON.wrf_old = wryaw globalDISCON.azimuthf_old = azimuth yawerrmeas.bl1_old = numpy.vstack((yawerrmeas.bl1_old, blmom1)) yawerrmeas.bl2_old = numpy.vstack((yawerrmeas.bl2_old, blmom2)) yawerrmeas.bl3_old = numpy.vstack((yawerrmeas.bl3_old, blmom3)) yawerrmeas.azimuth_old = numpy.hstack( (yawerrmeas.azimuth_old, azimuth[0])) #if ((azimuth[0] - 2*N*numpy.pi) > yawerrmeas.azimuth_old[0]) and ((azimuth[0] - 2*N*numpy.pi) > yawerrmeas.azimuth_old[1]): inddel = numpy.where( yawerrmeas.azimuth_old < azimuth[0] - 2 * N * numpy.pi) #print("INDDEL: ", inddel[0]) if inddel[0].size > 1: #print(yawerrmeas.azimuth_old.size) yawerrmeas.bl1_old = numpy.delete(yawerrmeas.bl1_old, [inddel[0][:-2]], 0) yawerrmeas.bl2_old = numpy.delete(yawerrmeas.bl2_old, [inddel[0][:-2]], 0) yawerrmeas.bl3_old = numpy.delete(yawerrmeas.bl3_old, [inddel[0][:-2]], 0) yawerrmeas.azimuth_old = numpy.delete(yawerrmeas.azimuth_old, [inddel[0][:-2]], None) #print(yawerrmeas.azimuth_old.size) #print("DELETED OBJECT") ind = numpy.where( yawerrmeas.azimuth_old > azimuth[0] - 2 * N * numpy.pi) #print("IND: ", ind[0]) a = 0 if ind[0][0] == 0: ind[0][0] = 1 a = 1 blmom1into = numpy.interp(azimuth[0] - 2 * N * numpy.pi, [ yawerrmeas.azimuth_old[ind[0][0] - 1], yawerrmeas.azimuth_old[ind[0][0]] ], [ yawerrmeas.bl1_old[ind[0][0] - 1, 0], yawerrmeas.bl1_old[ind[0][0], 0] ]) blmom1inti = numpy.interp(azimuth[0] - 2 * N * numpy.pi, [ yawerrmeas.azimuth_old[ind[0][0] - 1], yawerrmeas.azimuth_old[ind[0][0]] ], [ yawerrmeas.bl1_old[ind[0][0] - 1, 1], yawerrmeas.bl1_old[ind[0][0], 1] ]) blmom2into = numpy.interp( azimuth[0] - 2 * N * numpy.pi + 2 * numpy.pi / 3, [ yawerrmeas.azimuth_old[ind[0][0] - 1] + 2 * numpy.pi / 3, yawerrmeas.azimuth_old[ind[0][0]] + 2 * numpy.pi / 3 ], [ yawerrmeas.bl2_old[ind[0][0] - 1, 0], yawerrmeas.bl2_old[ind[0][0], 0] ]) blmom2inti = numpy.interp( azimuth[0] - 2 * N * numpy.pi + 2 * numpy.pi / 3, [ yawerrmeas.azimuth_old[ind[0][0] - 1] + 2 * numpy.pi / 3, yawerrmeas.azimuth_old[ind[0][0]] + 2 * numpy.pi / 3 ], [ yawerrmeas.bl2_old[ind[0][0] - 1, 1], yawerrmeas.bl2_old[ind[0][0], 1] ]) blmom3into = numpy.interp( azimuth[0] - 2 * N * numpy.pi + 4 * numpy.pi / 3, [ yawerrmeas.azimuth_old[ind[0][0] - 1] + 4 * numpy.pi / 3, yawerrmeas.azimuth_old[ind[0][0]] + 4 * numpy.pi / 3 ], [ yawerrmeas.bl3_old[ind[0][0] - 1, 0], yawerrmeas.bl3_old[ind[0][0], 0] ]) blmom3inti = numpy.interp( azimuth[0] - 2 * N * numpy.pi + 4 * numpy.pi / 3, [ yawerrmeas.azimuth_old[ind[0][0] - 1] + 4 * numpy.pi / 3, yawerrmeas.azimuth_old[ind[0][0]] + 4 * numpy.pi / 3 ], [ yawerrmeas.bl3_old[ind[0][0] - 1, 1], yawerrmeas.bl3_old[ind[0][0], 1] ]) if a == 1: ind[0][0] = 0 mo10 = numpy.trapz( numpy.hstack((blmom1into, yawerrmeas.bl1_old[ind[0], 0])), x=numpy.hstack( (azimuth[0] - 2 * N * numpy.pi, yawerrmeas.azimuth_old[ind[0]]))) / (2 * N * numpy.pi) mo1c = numpy.trapz( numpy.multiply( numpy.hstack((blmom1into, yawerrmeas.bl1_old[ind[0], 0])), numpy.cos( numpy.hstack((azimuth[0] - 2 * N * numpy.pi, yawerrmeas.azimuth_old[ind[0]])))), x=numpy.hstack( (azimuth[0] - 2 * N * numpy.pi, yawerrmeas.azimuth_old[ind[0]]))) / (N * numpy.pi) mo1s = numpy.trapz( numpy.multiply( numpy.hstack((blmom1into, yawerrmeas.bl1_old[ind[0], 0])), numpy.sin( numpy.hstack((azimuth[0] - 2 * N * numpy.pi, yawerrmeas.azimuth_old[ind[0]])))), x=numpy.hstack( (azimuth[0] - 2 * N * numpy.pi, yawerrmeas.azimuth_old[ind[0]]))) / (N * numpy.pi) mi10 = numpy.trapz( numpy.hstack((blmom1inti, yawerrmeas.bl1_old[ind[0], 1])), x=numpy.hstack( (azimuth[0] - 2 * N * numpy.pi, yawerrmeas.azimuth_old[ind[0]]))) / (2 * N * numpy.pi) mi1c = numpy.trapz( numpy.multiply( numpy.hstack((blmom1inti, yawerrmeas.bl1_old[ind[0], 1])), numpy.cos( numpy.hstack((azimuth[0] - 2 * N * numpy.pi, yawerrmeas.azimuth_old[ind[0]])))), x=numpy.hstack( (azimuth[0] - 2 * N * numpy.pi, yawerrmeas.azimuth_old[ind[0]]))) / (N * numpy.pi) mi1s = numpy.trapz( numpy.multiply( numpy.hstack((blmom1inti, yawerrmeas.bl1_old[ind[0], 1])), numpy.sin( numpy.hstack((azimuth[0] - 2 * N * numpy.pi, yawerrmeas.azimuth_old[ind[0]])))), x=numpy.hstack( (azimuth[0] - 2 * N * numpy.pi, yawerrmeas.azimuth_old[ind[0]]))) / (N * numpy.pi) mo20 = numpy.trapz(numpy.hstack( (blmom2into, yawerrmeas.bl2_old[ind[0], 0])), x=numpy.hstack( (azimuth[0] - 2 * N * numpy.pi, yawerrmeas.azimuth_old[ind[0]])) + 2 * numpy.pi / 3) / (2 * N * numpy.pi) mo2c = numpy.trapz(numpy.multiply( numpy.hstack((blmom2into, yawerrmeas.bl2_old[ind[0], 0])), numpy.cos( numpy.hstack((azimuth[0] - 2 * N * numpy.pi, yawerrmeas.azimuth_old[ind[0]])) + 2 * numpy.pi / 3)), x=numpy.hstack( (azimuth[0] - 2 * N * numpy.pi, yawerrmeas.azimuth_old[ind[0]])) + 2 * numpy.pi / 3) / (N * numpy.pi) mo2s = numpy.trapz(numpy.multiply( numpy.hstack((blmom2into, yawerrmeas.bl2_old[ind[0], 0])), numpy.sin( numpy.hstack((azimuth[0] - 2 * N * numpy.pi, yawerrmeas.azimuth_old[ind[0]])) + 2 * numpy.pi / 3)), x=numpy.hstack( (azimuth[0] - 2 * N * numpy.pi, yawerrmeas.azimuth_old[ind[0]])) + 2 * numpy.pi / 3) / (N * numpy.pi) mi20 = numpy.trapz(numpy.hstack( (blmom2inti, yawerrmeas.bl2_old[ind[0], 1])), x=numpy.hstack( (azimuth[0] - 2 * N * numpy.pi, yawerrmeas.azimuth_old[ind[0]])) + 2 * numpy.pi / 3) / (2 * N * numpy.pi) mi2c = numpy.trapz(numpy.multiply( numpy.hstack((blmom2inti, yawerrmeas.bl2_old[ind[0], 1])), numpy.cos( numpy.hstack((azimuth[0] - 2 * N * numpy.pi, yawerrmeas.azimuth_old[ind[0]])) + 2 * numpy.pi / 3)), x=numpy.hstack( (azimuth[0] - 2 * N * numpy.pi, yawerrmeas.azimuth_old[ind[0]])) + 2 * numpy.pi / 3) / (N * numpy.pi) mi2s = numpy.trapz(numpy.multiply( numpy.hstack((blmom2inti, yawerrmeas.bl2_old[ind[0], 1])), numpy.sin( numpy.hstack((azimuth[0] - 2 * N * numpy.pi, yawerrmeas.azimuth_old[ind[0]])) + 2 * numpy.pi / 3)), x=numpy.hstack( (azimuth[0] - 2 * N * numpy.pi, yawerrmeas.azimuth_old[ind[0]])) + 2 * numpy.pi / 3) / (N * numpy.pi) mo30 = numpy.trapz(numpy.hstack( (blmom3into, yawerrmeas.bl3_old[ind[0], 0])), x=numpy.hstack( (azimuth[0] - 2 * N * numpy.pi, yawerrmeas.azimuth_old[ind[0]])) + 4 * numpy.pi / 3) / (2 * N * numpy.pi) mo3c = numpy.trapz(numpy.multiply( numpy.hstack((blmom3into, yawerrmeas.bl3_old[ind[0], 0])), numpy.cos( numpy.hstack((azimuth[0] - 2 * N * numpy.pi, yawerrmeas.azimuth_old[ind[0]])) + 4 * numpy.pi / 3)), x=numpy.hstack( (azimuth[0] - 2 * N * numpy.pi, yawerrmeas.azimuth_old[ind[0]])) + 4 * numpy.pi / 3) / (N * numpy.pi) mo3s = numpy.trapz(numpy.multiply( numpy.hstack((blmom3into, yawerrmeas.bl3_old[ind[0], 0])), numpy.sin( numpy.hstack((azimuth[0] - 2 * N * numpy.pi, yawerrmeas.azimuth_old[ind[0]])) + 4 * numpy.pi / 3)), x=numpy.hstack( (azimuth[0] - 2 * N * numpy.pi, yawerrmeas.azimuth_old[ind[0]])) + 4 * numpy.pi / 3) / (N * numpy.pi) mi30 = numpy.trapz(numpy.hstack( (blmom3inti, yawerrmeas.bl3_old[ind[0], 1])), x=numpy.hstack( (azimuth[0] - 2 * N * numpy.pi, yawerrmeas.azimuth_old[ind[0]])) + 4 * numpy.pi / 3) / (2 * N * numpy.pi) mi3c = numpy.trapz(numpy.multiply( numpy.hstack((blmom3inti, yawerrmeas.bl3_old[ind[0], 1])), numpy.cos( numpy.hstack((azimuth[0] - 2 * N * numpy.pi, yawerrmeas.azimuth_old[ind[0]])) + 4 * numpy.pi / 3)), x=numpy.hstack( (azimuth[0] - 2 * N * numpy.pi, yawerrmeas.azimuth_old[ind[0]])) + 4 * numpy.pi / 3) / (N * numpy.pi) mi3s = numpy.trapz(numpy.multiply( numpy.hstack((blmom3inti, yawerrmeas.bl3_old[ind[0], 1])), numpy.sin( numpy.hstack((azimuth[0] - 2 * N * numpy.pi, yawerrmeas.azimuth_old[ind[0]])) + 4 * numpy.pi / 3)), x=numpy.hstack( (azimuth[0] - 2 * N * numpy.pi, yawerrmeas.azimuth_old[ind[0]])) + 4 * numpy.pi / 3) / (N * numpy.pi) m_out1 = (mo10 + mo20 + mo30) / 3 m_out2 = (mo1c + mo2c + mo3c) / 3 m_out3 = (mo1s + mo2s + mo3s) / 3 m_in1 = (mi10 + mi20 + mi30) / 3 m_in2 = (mi1c + mi2c + mi3c) / 3 m_in3 = (mi1s + mi2s + mi3s) / 3 m_out1f = (1 / (2 * tauF + Ts)) * ( (2 * tauF - Ts) * globalDISCON.m_out1f_old + Ts * (m_out1 + globalDISCON.m_out1_old)) m_out2f = (1 / (2 * tauF + Ts)) * ( (2 * tauF - Ts) * globalDISCON.m_out2f_old + Ts * (m_out2 + globalDISCON.m_out2_old)) m_out3f = (1 / (2 * tauF + Ts)) * ( (2 * tauF - Ts) * globalDISCON.m_out3f_old + Ts * (m_out3 + globalDISCON.m_out3_old)) m_in1f = (1 / (2 * tauF + Ts)) * ( (2 * tauF - Ts) * globalDISCON.m_in1f_old + Ts * (m_in1 + globalDISCON.m_in1_old)) m_in2f = (1 / (2 * tauF + Ts)) * ( (2 * tauF - Ts) * globalDISCON.m_in2f_old + Ts * (m_in2 + globalDISCON.m_in2_old)) m_in3f = (1 / (2 * tauF + Ts)) * ( (2 * tauF - Ts) * globalDISCON.m_in3f_old + Ts * (m_in3 + globalDISCON.m_in3_old)) globalDISCON.m_out1f_old = m_out1f globalDISCON.m_out1_old = m_out1 globalDISCON.m_out2f_old = m_out2f globalDISCON.m_out2_old = m_out2 globalDISCON.m_out3f_old = m_out3f globalDISCON.m_out3_old = m_out3 globalDISCON.m_in1f_old = m_in1f globalDISCON.m_in1_old = m_in1 globalDISCON.m_in2f_old = m_in2f globalDISCON.m_in2_old = m_in2 globalDISCON.m_in3f_old = m_in3f globalDISCON.m_in3_old = m_in3 #m_yaw_u0 = numpy.array([m_out2/m_out1, m_out3/m_out1, m_in2/m_in1, m_in3/m_in1]) m_yaw_u0 = numpy.array([ m_out2f / m_out1f, m_out3f / m_out1f, m_in2f / m_in1f, m_in3f / m_in1f ]) m_yaw_k1 = numpy.array([1, m_out2, m_out3, m_in2, m_in3]) m_yaw = numpy.hstack((m_yaw_u0, m_yaw_k1)) Tmat = yawerrmeas.Tmat_int(vento_obs) #Tmat = yawerrmeas.Tmat_int(HorWindV) ris_yaw = numpy.dot(Tmat, m_yaw.transpose()) crosswind_NF = wryaw * yawerrmeas.R * ris_yaw[ 0] # VERSION WITHOUT YAW ANGLE #angyaw = numpy.arcsin(crosswind/vento_obs) #crosswind = vento_obs * math.sin(angyaw + avrSWAP_py[36]) vertshear = wryaw * yawerrmeas.R * ris_yaw[1] / vento_obs #vertshear = wryaw*yawerrmeas.R*ris_yaw[1]/HorWindV # FILTERING THE SIGNAL OF CROSS WIND WITH BUTTERWORTH 2nd ORDER FILTER #crosswind = (NNEXY.n1 * (globalDISCON.old_cw + globalDISCON.old2_cw + crosswind_NF) - NNEXY.n2 * globalDISCON.oldf_cw - NNEXY.n3 * globalDISCON.old2f_cw) / NNEXY.d1 crosswind = crosswind_NF if numpy.isclose(Time % 17.5, 0.0): globalDISCON.angyaw_old = globalDISCON.angyaw globalDISCON.angyaw = numpy.arctan(crosswind / vento_obs) if abs(globalDISCON.angyaw - globalDISCON.angyaw_old) < 0.035 and abs( globalDISCON.angyaw) > 0.07: globalDISCON.counterY = globalDISCON.counterY + 1.0 if globalDISCON.counterY >= 2.0: globalDISCON.PosFin = globalDISCON.PosYawRef + globalDISCON.angyaw #globalDISCON.VelYawRef = numpy.sign(globalDISCON.angyaw)*0.0349066/3 globalDISCON.flagyaw = False #globalDISCON.signold = numpy.sign(globalDISCON.PosFin - globalDISCON.PosYawRef) globalDISCON.signold = numpy.sign(globalDISCON.angyaw) else: globalDISCON.counterY = 0.0 file = open("EVALUE.txt", "a+") file.write("%f, %f, %f, %f, %f, %f, %f \n" % (globalDISCON.flagyaw, globalDISCON.PosFin, globalDISCON.VelYawRef, globalDISCON.counterY, globalDISCON.angyaw, globalDISCON.angyaw_old, Time)) file.close() #globalDISCON.oldf_cw = crosswind #globalDISCON.old2f_cw = globalDISCON.oldf_cw #globalDISCON.old_cw = crosswind_NF #globalDISCON.old2_cw = globalDISCON.old_cw #globalDISCON.old_cw = crosswind # YAW ERROR ESTIMATION WITH TRAINED FORWARD NEURAL NETWORK flagind = 0 if logic.counter == 1: toNN_in = numpy.hstack((m_yaw_u0, vento_obs)) #toNN = numpy.hstack((toNN, 0.0349066/3)) toNN = numpy.multiply(toNN_in, 1 / NNEX.normC.T) toNNY = numpy.multiply(toNN_in, 1 / NNEXY.normC.T) if toNN.any() > 1: ii = numpy.where(toNN >= 1) toNN[ii] = 1 flagind = 1 if toNNY.any() > 1: ii = numpy.where(toNNY >= 1) toNNY[ii] = 1 flagind = 1 if abs(avrSWAP_py[36]) > 0.02: crosswindNN_NF = NNEXY.NN.forward( toNNY) * vento_obs * NNEXY.normY else: crosswindNN_NF = NNEX.NN.forward( toNN) * vento_obs * NNEX.normY # VERSION WITHOUT YAW ANGLE #crosswindNN = (NNEXY.n1 * (NNEXY.old_cw + NNEXY.old2_cw + crosswindNN_NF) - NNEXY.n2 * NNEXY.oldf_cw - NNEXY.n3 * NNEXY.old2f_cw) / NNEXY.d1 crosswindNN = crosswindNN_NF #NNEXY.oldf_cw = crosswindNN #NNEXY.old2f_cw = NNEXY.oldf_cw #NNEXY.old_cw = crosswindNN_NF #NNEXY.old2_cw = NNEXY.old_cw globalDISCON.angyawNN = numpy.arctan(crosswindNN / vento_obs) else: crosswindNN = 0.0 file = open("ECROSS.txt", "a+") file.write("%f, %f, %f, %f, %f \n" % (crosswind, crosswindNN, flagind, vertshear, Time)) file.close() file = open("EAzimuth.txt", "a+") file.write("%f, %f, %f, %f \n" % (azimuth[0], azimuth[1], azimuth[2], Time)) file.close() file = open("EMOM.txt", "a+") file.write("%f, %f, %f, %f, %f, %f, %f \n" % (m_out1, m_out2, m_out3, m_in1, m_in2, m_in3, Time)) file.close() return avrSWAP_py
def pressureAfterOrifice(gamma, rho_o, a_o, P0, mdot, orificeThroatArea, P4_guess): return fsolve(lambda Pout: -mdot + eqn1544Helper( gamma, rho_o, a_o, P0, Pout) * orificeThroatArea, P4_guess) #eqn 15.44
def fugacities(self, gammas='calculate', K_vals='calculate'): """Returns fugacity values for each species. Parameters ---------- self, inherited from Class Notably, uses fluid_comp, temp, press, fO2 gammas: dict Optional. Fugacity coefficients. If gamma values are not passed, they will be calculated. Format: {'H2O': value, 'CO2': value, 'SO2': value, 'H2S': value} K_vals: dict Optional. Equilibrium constants of reaction. If K values are not passed, they will be calculated. Format: {'H2O': value, 'CO2': value, 'SO2': value, 'H2S': value} Returns ------- dict Fugacities of all species """ if isinstance(gammas,str): gammas = calc_gammas(self.temp, self.press, species="all") self.gammas = gammas if isinstance(K_vals,str): K_vals = calc_Ks(self.temp, species="all") XH2Otot = self.fluid_comp_molfrac["H2O"] XCO2tot = self.fluid_comp_molfrac["CO2"] XStot = self.fluid_comp_molfrac["S"] XHtot = XH2Otot * (0.6666) XStot = XStot XCtot = XCO2tot * (0.3333) B = gammas['H2'] P = self.press C = K_vals['H2O'] D = self.fO2 sD = sqrt(D) E = gammas['H2O'] F = K_vals['H2S'] G = gammas['H2S'] J = gammas['S2'] K = K_vals['SO2'] L = gammas['SO2'] M = K_vals['CO2'] N = gammas['CO2'] Q = gammas['CO'] # #FIRST calculate fH2 and fS2 using fsolve, two eqns; two unknowns (eqn 9 in Iacovino, 2015) # def equations(p): # fH2, fS2 = p # return ( # ( (fH2/(B*P)) + ((Rational(2.0) * C * fH2 * sD)/(Rational(3.0) * E * P)) + ((Rational(2.0) * F * fH2 * sqrt(abs(fS2)))/(Rational(3.0) * G * P)) - XHtot), # ( (fS2/(J * P)) + ((F * fH2 * sqrt(abs(fS2)))/(Rational(3.0) * G * P)) + ((K * D * sqrt(abs(fS2)))/(Rational(3.0) * L * P)) - XStot) # ) # fH2_a, fS2_a = fsolve(equations, (1, 1)) # fH2 = abs(fH2_a) # fS2 = abs(fS2_a) # #SECOND calculate fCO (eqn 10 in Iacovino, 2015) using sympy # fCO = symbols('fCO') #for sympy # # FIRST calculate fCO (eqn 10 in Iacovino, 2015) using sympy # if XCtot == 0: # fCO = 0 # else: # fCO = symbols('fCO') #for sympy # equation = (((K_vals['CO2'] * fCO * sD)/(Rational(3.0) * gammas['CO2'] * P)) + # ((fCO)/(Rational(2.0) * gammas['CO'] * P)) + # (()) - # XCtot) # fCO = solve(equation, fCO)[0] #newly implemented sympy way # FIRST calculate fH2, fS2, and fCO using fsolve, 3 eqns; 3 unknowns (extention of eqn 9 in Iacovino, 2015) def equations(p): fH2, fS2, fCO = p return ( ( (fH2/(B*P)) + ((Rational(2.0) * C * fH2 * sD)/(Rational(3.0) * E * P)) + ((Rational(2.0) * F * fH2 * sqrt(abs(fS2)))/(Rational(3.0) * G * P)) + ((Rational(4.0) * fCO * fH2**2)/(Rational(5.0) * K_vals['CH4'] * K_vals['H2O'] * sD * gammas['CH4'] * P)) - XHtot), ( (fS2/(J * P)) + ((F * fH2 * sqrt(abs(fS2)))/(Rational(3.0) * G * P)) + ((K * D * sqrt(abs(fS2)))/(Rational(3.0) * L * P)) - XStot), ( (fCO/(Rational(2.0) * gammas['CO'] * P)) + ((K_vals['CO2'] * fCO * sD)/(Rational(3.0) * gammas['CO2'] * P)) + ((fCO * fH2**2)/(Rational(5.0) * K_vals['CH4'] * K_vals['H2O'] * sD * gammas['CH4'] * P)) - XCtot) ) fH2_a, fS2_a, fCO_a = fsolve(equations, (P, P, P)) if XHtot == 0: fH2 = 0 else: fH2 = abs(fH2_a) if XStot == 0: fS2 = 0 else: fS2 = abs(fS2_a) if XCtot == 0: fCO = 0 else: fCO = abs(fCO_a) #THIRD calculate fCO2 using calc'd fCO and known fO2 value fCO2 = K_vals['CO2'] * fCO * sD #FOURTH calcualte fSO2 using calc'd fS2 and known fO2 value fSO2 = K_vals['SO2'] * sqrt(fS2) * D #FIFTH calculate fH2S using calc'd fH2 and fS2 values fH2S = K_vals['H2S'] * fH2 * sqrt(fS2) #SIXTH calculate fH2O using calc'd fH2 and knwn fO2 value fH2O = K_vals['H2O'] * sD * fH2 #SEVENTH (new for CH4!) calculate fCH4 using fCO2, fH2O, and known Keq value for reaction fCH4 = (fCO * fH2**3.0) / (K_vals['CH4'] * fH2O) #TODO raise exception if a fugacity is negative or zero. return {'CH4': fCH4, 'CO': fCO, 'CO2': fCO2, 'H2': fH2, 'H2O': fH2O, 'H2S': fH2S, 'O2': D, 'S2': fS2, 'SO2': fSO2}
import numpy as np from scipy.optimize import fsolve from scipy.optimize import minimize sqrt = np.emath.sqrt def f(x): d=5 #return ((2*np.cosh(x))**(d-1)+(2*np.sinh(x))**(d-1))/ ((2*np.cosh(x))**d+(2*np.sinh(x))**d) return (x-2.9)*(x-7.1) def f2(x,a): d=5 #return ((2*np.cosh(x))**(d-1)+(2*np.sinh(x))**(d-1))/ ((2*np.cosh(x))**d+(2*np.sinh(x))**d) return (x-2.9)*(x-a) x_newton = fsolve(f, 1.0) x_nelder_mead = minimize(f2,1.0,method="Nelder-Mead",args=(1.3)) x_powell = minimize(f, 1.0,method="Powell") x_cg = minimize(f, 1.0,method="CG") x_bfgs = minimize(f, 1.0,method="BFGS") #x_newtonCG = minimize(f, 1.0,method="Newton-CG") print("newton=",x_newton) print("nelder=",x_nelder_mead) print("powell=",x_powell) print("cgmeth=",x_cg) print("bfgsme=",x_bfgs) #print("newtCG=",x_newtonCG)
def plot(self, x1, x2, y, X, W, m, show=True): """ Plotting relevant graphs from the data and it's results from LDA. @param x1: feature data related to Class 1 @param x2: feature data related to Class 2 @param y: class labels of the data @param X: all feature data. @param W: weight vector from LDA on the dataset @param m: overall mean @param show: boolean to show the plots """ # Convenience variables L = len(X) L2 = np.count_nonzero(y) L1 = L - L2 X = X.T W0sq = W[0]**2 W1sq = W[1]**2 # Discriminant line equation x_1 = np.linspace(-5, 5) x_0 = (-W[1] / W[0]) * (x_1 - m[1]) + m[0] # Projection of X onto Discriminant (Transformed X) Xtr = np.zeros((2, L)) for i in range(L): Xtr[0][i] = ((W1sq * m[1] + W0sq * X[0][i]) + ((m[0] - X[1][i]) * W[0] * W[1])) / (W0sq + W1sq) Xtr[1][i] = (W[0] * (Xtr[0][i]) / W[1]) + X[1][i] ### Normal Distribution Curves ### # Standard deviation interval size k = 3.7 # Calculate points in lower dimension (here 1 and 2 are not features but classes) X1 = np.zeros(L1) X2 = np.zeros(L2) for i in range(L1): X1[i] = np.dot(W.T, x1[i]) for i in range(L2): X2[i] = np.dot(W.T, x2[i]) # Normal curve for X1 mu1 = np.mean(X1) sigma1 = np.std(X1) p1 = np.linspace(mu1 - k * sigma1, mu1 + k * sigma1) q1 = stats.norm.pdf(p1, mu1, sigma1) # Normal curve for X2 mu2 = np.mean(X2) sigma2 = np.std(X2) p2 = np.linspace(mu2 - k * sigma2, mu2 + k * sigma2) q2 = stats.norm.pdf(p2, mu2, sigma2) # Find the intersection point of distribution intersection_pt = fsolve( lambda x: stats.norm.pdf(x, mu1, sigma1) - stats.norm.pdf( x, mu2, sigma2), 0) if show: ### Plot ### grid = plt.GridSpec(3, 2) plt.subplot(grid[0:2, :]) plt.title("Scatter plot of data") clr = ['orange' if i == 0 else 'green' for i in y] clr_tr = ['red' if i == 0 else 'blue' for i in y] plt.scatter(X[0], X[1], marker='o', color=clr, alpha=0.75, label='Original data') plt.scatter(Xtr[0], Xtr[1], marker='.', color=clr_tr, label='Transformed data') plt.xlim(np.min(X[0]) - 0.1, np.max(X[0]) + 0.1) plt.ylim(np.min(X[1]) - 0.1, np.max(X[1]) + 0.1) plt.plot(x_1, x_0, color='k', label="Discriminant") plt.xlabel('Feature 1') plt.ylabel('Feature 2') plt.legend(loc='upper right') plt.subplot(grid[2, :]) plt.title("Normal curves") plt.plot(p1, q1, color='red', label="Class 1") plt.plot(p2, q2, color='blue', label="Class 2") plt.axvline(intersection_pt, color='g', ls='--', lw=0.75, label="Threshold =\n" + str(np.around(intersection_pt[0], decimals=3))) plt.legend(loc='upper right') plt.tight_layout() mng = plt.get_current_fig_manager() mng.window.showMaximized() plt.savefig('images/dataset_' + str(self.dataset) + '_lda.png') plt.show() return intersection_pt
from scipy.optimize import fsolve from matplotlib import pylab from pylab import * """ Use fsolve to find intersections of exp(x)-1 with cos(x) Note that need different guesses to find different intersections """ def f(x): return (exp(x) - 1) - cos(x) # use fsolve to solve exp(x)-1 - cos(x) = 0 guess = 2.0 print(fsolve(f, guess)) guess = -1.0 print(fsolve(f, guess)) guess = -5.0 print(fsolve(f, guess)) guess = 0.0 print(fsolve(f, guess)) guess = -10.0 print(fsolve(f, guess)) # plot the graph to see if we are correct x = linspace(-15, 1, 401) plot(x, exp(x) - 1, x, cos(x)) grid(b=1) show()
def fSolver(f, thetaGuess): func = lambda theta: f(theta, p1, p2, p3, L1, L2, L3, gamma, x1, x2, y2) # Aðferðin sem fsolve notar til að finna núllstöð: # https://www.math.utah.edu/software/minpack/minpack/hybrd.html thetaSol = scOpt.fsolve(func, thetaGuess) return thetaSol
def plot_fun(sdf, cur_line, lw): fignum = 1 # Charge plt.figure(fignum) fignum += 1 xvals = sdf['Vg'] yvals = sdf['gate_ns'] plt.semilogy(xvals, yvals, cur_line, linewidth=lw) plt.xlabel('Vg [V]') plt.ylabel('Gate ns [1/cm^2]') plt.grid(True) # Gate Capacitance plt.figure(fignum) fignum += 1 vvals = sdf['Vg'].values qvals = sdf['gate_ns'] # Interpolate onto sparse mesh for smoothing print('interpolating: vvals:', vvals.shape, ' qvals:', qvals.shape) #print sdf q_interpolator = sp_interp.interp1d(vvals, qvals, kind='cubic') v_i = np.linspace(vvals[0], vvals[-1], 10) q_i = q_interpolator(v_i) dV = v_i[1] - v_i[0] cvals = 1e6 * 1.6e-19 * np.gradient(q_i, dV) # Now interpolate back to original grid c_interpolator = sp_interp.interp1d(v_i, cvals, kind='cubic') cvals_final = c_interpolator(vvals) plt.plot(vvals, cvals_final, cur_line, linewidth=lw) plt.xlabel('Vg [V]') plt.ylabel('Gate Capacitance [uF/cm^2]') plt.grid(True) plt.ylim(ymin=0.0, ymax=3.5) # Gate Capacitance for total charge plt.figure(fignum) fignum += 1 vvals = sdf['Vg'].values qvals_tot = sdf['tot_charge'] * 1e14 # Interpolate onto sparse mesh for smoothing q_interpolator_tot = sp_interp.interp1d(vvals, qvals_tot, kind='cubic') v_i_tot = np.linspace(vvals[0], vvals[-1], 10) q_i_tot = q_interpolator_tot(v_i_tot) dV_tot = v_i[1] - v_i[0] cvals_tot = 1e6 * 1.6e-19 * np.gradient(q_i_tot, dV_tot) # Now interpolate back to original grid c_interpolator_tot = sp_interp.interp1d(v_i_tot, cvals_tot, kind='cubic') cvals_final_tot = c_interpolator_tot(vvals) if sdf['dev_type'].values[0] != 'fin': plt.plot(vvals, cvals_final_tot, cur_line, linewidth=lw) plt.xlabel('Vg [V]') plt.ylabel('Gate Capacitance [uF/cm]') plt.grid(True) plt.ylim(ymin=0.0, ymax=100) # Gate capacitance with Vt shift plt.figure(fignum) fignum += 1 xvals = sdf['Vg'].values dV = xvals[1] - xvals[0] qvals = sdf['gate_ns'] cvals = 1e6 * 1.6e-19 * np.gradient(qvals, dV) # Interpolant for capacitance #c_interp = sp_interp.interp1d(xvals, cvals) rhs = lambda x: c_interpolator(x) - 0.15 # Now find shift require to put cval=1.5 to Vg=0.0 v0 = -0.05 vf = optimize.fsolve(rhs, v0, xtol=1e-6) yvals = cvals_final plt.plot(vvals - vf, cvals_final, cur_line, linewidth=lw) plt.xlabel('Vg-Vt [V]') plt.ylabel('Gate Capacitance [uF/cm^2]') plt.grid(True) plt.ylim(ymin=0.0, ymax=3.5) # Charge with Vt shift plt.figure(fignum) fignum += 1 xvals = sdf['Vg'] yvals = sdf['gate_ns'] plt.plot(xvals - vf, yvals, cur_line, linewidth=lw) plt.xlabel('Vg-Vt [V]') plt.ylabel('Gate ns [1/cm^2]') plt.grid(True) # Charge with Vt shift plt.figure(fignum) fignum += 1 xvals = sdf['Vg'] yvals = sdf['charge_height'] plt.plot(xvals - vf, yvals, cur_line, linewidth=lw) plt.xlabel('Vg-Vt [V]') plt.ylabel('Charge / height') plt.grid(True) # Total Charge with Vt shift # Don't plot for FinFET plt.figure(fignum) fignum += 1 xvals = sdf['Vg'] yvals = 1e7 * sdf['tot_charge'] if sdf['dev_type'].values[0] != 'fin': plt.plot(xvals - vf, yvals, cur_line, linewidth=lw) plt.xlabel('Vg-Vt [V]') plt.ylabel('Total Charge [1/nm]') plt.grid(True) # Average Charge with Vt shift plt.figure(fignum) fignum += 1 xvals = sdf['Vg'] yvals = sdf['average_charge'] plt.plot(xvals - vf, yvals, cur_line, linewidth=lw) plt.xlabel('Vg-Vt [V]') plt.ylabel('Average Charge Conc. [1/cm^3]') plt.grid(True) # Delta2 Fraction vs Vg-Vt plt.figure(fignum) fignum += 1 xvals = sdf['Vg'] yvals = sdf['d2'] plt.plot(xvals - vf, yvals, cur_line, linewidth=lw) plt.xlabel('Vg-Vt, [V]') plt.ylabel('Delta 2 Fraction') plt.grid(True) # Delta2 Fraction vs sidewall charge plt.figure(fignum) fignum += 1 xvals = sdf['gate_ns'] yvals = sdf['d2'] plt.semilogx(xvals, yvals, cur_line, linewidth=lw) plt.xlabel('Gate ns [1/cm^2]') plt.ylabel('Delta 2 Fraction') plt.grid(True) plt.xlim(xmin=2e11, xmax=2e13) # Velocity vs. Vg-Vt plt.figure(fignum) fignum += 1 xvals = sdf['Vg'] yvals = sdf['vel'] plt.plot(xvals - vf, yvals, cur_line, linewidth=lw) plt.xlabel('Vg-Vt [V]') plt.ylabel('Injection Velocity [cm/s]') plt.grid(True) # Velocity vs. sidewall charge plt.figure(fignum) fignum += 1 xvals = sdf['gate_ns'] yvals = sdf['vel'] plt.semilogx(xvals, yvals, cur_line, linewidth=lw) plt.xlabel('Gate ns [1/cm^2]') plt.ylabel('Injection Velocity [cm/s]') plt.grid(True) plt.xlim(xmin=2e11, xmax=2e13) # Velocity vs. average charge conc. plt.figure(fignum) plt.tick_params(axis='x', which='minor') ax = plt.gca() #ax.set_yscale('log') plt.tick_params(axis='x', which='minor') ax.xaxis.set_minor_formatter(FormatStrFormatter("%.1f")) fignum += 1 xvals = sdf['average_charge'] yvals = sdf['vel'] plt.semilogx(xvals, yvals, cur_line, linewidth=lw) plt.xlabel('Average Charge Conc. [1/cm^3]') plt.ylabel('Injection Velocity [cm/s]') plt.grid(True) plt.xlim(xmin=2e18, xmax=2e20)
def get_pop_objs(E, S, T, min_yr, max_yr, curr_year, GraphDiag=True): ''' -------------------------------------------------------------------- This function produces the demographics objects to be used in the OG-USA model package. -------------------------------------------------------------------- INPUTS: E = integer >= 1, number of model periods in which agent is not economically active S = integer >= 3, number of model periods in which agent is economically active T = integer > 2*S, number of periods to be simulated in TPI min_yr = integer >= 0, age in years at which agents are born, minimum age max_yr = integer >= 4, age in years at which agents die with certainty, maximum age curr_year = integer >= 2016, current year for which analysis will begin GraphDiag = boolean, =True if want graphical output and printed diagnostics OTHER FUNCTIONS AND FILES CALLED BY THIS FUNCTION: get_fert() get_mort() get_imm_resid() utils.read_file() pop_rebin() immsolve() pop_data.csv OBJECTS CREATED WITHIN FUNCTION: age_per = (E+S,) vector, age in years at each period of life fert_rates = (E+S,) vector, fertility rates that correspond to each model period of life mort_rates = (E+S,) vector, mortality rates that correspond to each model period of life infmort_rate = scalar > 0, infant mortality rate from 2015 U.S. CIA World Factbook mort_rates_S = (S,) vector, mortality rates that correspond to each economically active model period of life imm_rates_orig = (E+S,) vector, immigration rates by age estimated as residuals from get_imm_resid() OMEGA_orig = (E+S, E+S) matrix, transition matrix for population distribution law of motion eigvalues = (E+S,) vector, eigenvalues of OMEGA matrix eigvectors = (E+S, E+S) matrix, matrix of eigenvectors of OMEGA where each column is the eigenvector that goes with the corresponding eigenvalue in eigvalues g_n_SS_orig = scalar, steady-state population growth rate, which is the largest real part of the eigenvalues eigvec_raw = (E+S,) vector, nonnormalized eigenvector corresponding to the largest real-part eigenvalue omega_SS_orig = (E+S,) vector, steady-state population distribution which is normalized eigvec_raw omega_path_orig = (E+S, T) matrix, time path of the population distribution from the current state to the steady- state cur_path = string, path in which calling file resides pop_file = string, path of population data source csv file pop_data = 101 x 5 DataFrame, Age, Pop2010, Pop2011, Pop2012, Pop2013, for ages 0 to 100 pop_data_samp = 100 x 5 DataFrame, Age, Pop2010, Pop2011, Pop2012, Pop2013, for ages 0 to 99 age_year_all = (100,) vector, ages by year from data, beg per=1 pop_2013 = (100,) vector, population for ages 0 to 99 in 2013 age_per_EpS = (E+S,) vector, period numbers 1 through E+S pop_2013_EpS = (E+S,) vector, population distribution by model periods E + S in levels pop_2013_pct = (E+S,) vector, 2013 population distribution in percentages pop_curr = (E+S,) vector, current-period population distribution in percentages data_year = integer, most recent year in data per = integer, index for period pop_next = (E+S,) vector, next-period population distribution imm_tol = scalar > 0, tolerance for fsolve in immsolve() fixper = ? omega_SSfx = ? imm_objs = ? imm_fulloutput = ? imm_rates_adj = ? imm_diagdict = ? omega_path_S = ? imm_rates_S = ? imm_rates_S_adj = ? RETURNS: omega_path_S.T, g_n_SS, omega_SSfx[-S:] / omega_SSfx[-S:].sum(), 1-mort_rates_S, mort_rates_S, g_n_path, imm_rates_mat -------------------------------------------------------------------- ''' # age_per = np.linspace(min_yr, max_yr, E+S) fert_rates = get_fert(E + S, min_yr, max_yr, graph=False) mort_rates, infmort_rate = get_mort(E + S, min_yr, max_yr, graph=False) mort_rates_S = mort_rates[-S:] imm_rates_orig = get_imm_resid(E + S, min_yr, max_yr, graph=False) OMEGA_orig = np.zeros((E + S, E + S)) OMEGA_orig[0, :] = ((1 - infmort_rate) * fert_rates + np.hstack( (imm_rates_orig[0], np.zeros(E + S - 1)))) OMEGA_orig[1:, :-1] += np.diag(1 - mort_rates[:-1]) OMEGA_orig[1:, 1:] += np.diag(imm_rates_orig[1:]) # Solve for steady-state population growth rate and steady-state # population distribution by age using eigenvalue and eigenvector # decomposition eigvalues, eigvectors = np.linalg.eig(OMEGA_orig) g_n_SS = (eigvalues[np.isreal(eigvalues)].real).max() - 1 eigvec_raw =\ eigvectors[:, (eigvalues[np.isreal(eigvalues)].real).argmax()].real omega_SS_orig = eigvec_raw / eigvec_raw.sum() # Generate time path of the nonstationary population distribution omega_path_lev = np.zeros((E + S, T + S)) cur_path = os.path.split(os.path.abspath(__file__))[0] pop_file = utils.read_file(cur_path, 'data/demographic/pop_data.csv') pop_data = pd.read_csv(pop_file, sep=',', thousands=',') pop_data_samp = pop_data[(pop_data['Age'] >= min_yr - 1) & (pop_data['Age'] <= max_yr - 1)] pop_2013 = np.array(pop_data_samp['2013'], dtype='f') # Generate the current population distribution given that E+S might # be less than max_yr-min_yr+1 age_per_EpS = np.arange(1, E + S + 1) pop_2013_EpS = pop_rebin(pop_2013, E + S) pop_2013_pct = pop_2013_EpS / pop_2013_EpS.sum() # Age most recent population data to the current year of analysis pop_curr = pop_2013_EpS.copy() data_year = 2013 pop_next = np.dot(OMEGA_orig, pop_curr) g_n_curr = ( (pop_next[-S:].sum() - pop_curr[-S:].sum()) / pop_curr[-S:].sum() ) # g_n in 2013 pop_past = pop_curr # assume 2012-2013 pop # Age the data to the current year for per in range(curr_year - data_year): pop_next = np.dot(OMEGA_orig, pop_curr) g_n_curr = ((pop_next[-S:].sum() - pop_curr[-S:].sum()) / pop_curr[-S:].sum()) pop_past = pop_curr pop_curr = pop_next # Generate time path of the population distribution omega_path_lev[:, 0] = pop_curr.copy() for per in range(1, T + S): pop_next = np.dot(OMEGA_orig, pop_curr) omega_path_lev[:, per] = pop_next.copy() pop_curr = pop_next.copy() # Force the population distribution after 1.5*S periods to be the # steady-state distribution by adjusting immigration rates, holding # constant mortality, fertility, and SS growth rates imm_tol = 1e-14 fixper = int(1.5 * S) omega_SSfx = (omega_path_lev[:, fixper] / omega_path_lev[:, fixper].sum()) imm_objs = (fert_rates, mort_rates, infmort_rate, omega_path_lev[:, fixper], g_n_SS) imm_fulloutput = opt.fsolve(immsolve, imm_rates_orig, args=(imm_objs), full_output=True, xtol=imm_tol) imm_rates_adj = imm_fulloutput[0] imm_diagdict = imm_fulloutput[1] omega_path_S = (omega_path_lev[-S:, :] / np.tile(omega_path_lev[-S:, :].sum(axis=0), (S, 1))) omega_path_S[:, fixper:] = \ np.tile(omega_path_S[:, fixper].reshape((S, 1)), (1, T + S - fixper)) g_n_path = np.zeros(T + S) g_n_path[0] = g_n_curr.copy() g_n_path[1:] = ((omega_path_lev[-S:, 1:].sum(axis=0) - omega_path_lev[-S:, :-1].sum(axis=0)) / omega_path_lev[-S:, :-1].sum(axis=0)) g_n_path[fixper + 1:] = g_n_SS omega_S_preTP = (pop_past.copy()[-S:]) / (pop_past.copy()[-S:].sum()) imm_rates_mat = np.hstack( (np.tile(np.reshape(imm_rates_orig[E:], (S, 1)), (1, fixper)), np.tile(np.reshape(imm_rates_adj[E:], (S, 1)), (1, T + S - fixper)))) if GraphDiag: # Check whether original SS population distribution is close to # the period-T population distribution omegaSSmaxdif = np.absolute(omega_SS_orig - (omega_path_lev[:, T] / omega_path_lev[:, T].sum())).max() if omegaSSmaxdif > 0.0003: print('POP. WARNING: Max. abs. dist. between original SS ' + "pop. dist'n and period-T pop. dist'n is greater than" + ' 0.0003. It is ' + str(omegaSSmaxdif) + '.') else: print('POP. SUCCESS: orig. SS pop. dist is very close to ' + "period-T pop. dist'n. The maximum absolute " + 'difference is ' + str(omegaSSmaxdif) + '.') # Plot the adjusted steady-state population distribution versus # the original population distribution. The difference should be # small omegaSSvTmaxdiff = np.absolute(omega_SS_orig - omega_SSfx).max() if omegaSSvTmaxdiff > 0.0003: print('POP. WARNING: The maximimum absolute difference ' + 'between any two corresponding points in the original' + ' and adjusted steady-state population ' + 'distributions is' + str(omegaSSvTmaxdiff) + ', ' + 'which is greater than 0.0003.') else: print('POP. SUCCESS: The maximum absolute difference ' + 'between any two corresponding points in the original' + ' and adjusted steady-state population ' + 'distributions is ' + str(omegaSSvTmaxdiff)) fig, ax = plt.subplots() plt.plot(age_per_EpS, omega_SS_orig, label="Original Dist'n") plt.plot(age_per_EpS, omega_SSfx, label="Fixed Dist'n") # for the minor ticks, use no labels; default NullFormatter minorLocator = MultipleLocator(1) ax.xaxis.set_minor_locator(minorLocator) plt.grid(b=True, which='major', color='0.65', linestyle='-') plt.title('Original steady-state population distribution vs. fixed', fontsize=20) plt.xlabel(r'Age $s$') plt.ylabel(r"Pop. dist'n $\omega_{s}$") plt.xlim((0, E + S + 1)) plt.legend(loc='upper right') # Create directory if OUTPUT directory does not already exist ''' ---------------------------------------------------------------- output_fldr = string, path of the OUTPUT folder from cur_path output_dir = string, total path of OUTPUT folder output_path = string, path of file name of figure to be saved ---------------------------------------------------------------- ''' cur_path = os.path.split(os.path.abspath(__file__))[0] output_fldr = 'OUTPUT/Demographics' output_dir = os.path.join(cur_path, output_fldr) if os.access(output_dir, os.F_OK) is False: os.makedirs(output_dir) output_path = os.path.join(output_dir, 'OrigVsFixSSpop') plt.savefig(output_path) plt.show() # Print whether or not the adjusted immigration rates solved the # zero condition immtol_solved = \ np.absolute(imm_diagdict['fvec'].max()) < imm_tol if immtol_solved: print('POP. SUCCESS: Adjusted immigration rates solved ' + 'with maximum absolute error of ' + str(np.absolute(imm_diagdict['fvec'].max())) + ', which is less than the tolerance of ' + str(imm_tol)) else: print('POP. WARNING: Adjusted immigration rates did not ' + 'solve. Maximum absolute error of ' + str(np.absolute(imm_diagdict['fvec'].max())) + ' is greater than the tolerance of ' + str(imm_tol)) # Test whether the steady-state growth rates implied by the # adjusted OMEGA matrix equals the steady-state growth rate of # the original OMEGA matrix OMEGA2 = np.zeros((E + S, E + S)) OMEGA2[0, :] = ((1 - infmort_rate) * fert_rates + np.hstack( (imm_rates_adj[0], np.zeros(E + S - 1)))) OMEGA2[1:, :-1] += np.diag(1 - mort_rates[:-1]) OMEGA2[1:, 1:] += np.diag(imm_rates_adj[1:]) eigvalues2, eigvectors2 = np.linalg.eig(OMEGA2) g_n_SS_adj = (eigvalues[np.isreal(eigvalues2)].real).max() - 1 if np.max(np.absolute(g_n_SS_adj - g_n_SS)) > 10**(-8): print('FAILURE: The steady-state population growth rate' + ' from adjusted OMEGA is different (diff is ' + str(g_n_SS_adj - g_n_SS) + ') than the steady-' + 'state population growth rate from the original' + ' OMEGA.') elif np.max(np.absolute(g_n_SS_adj - g_n_SS)) <= 10**(-8): print('SUCCESS: The steady-state population growth rate' + ' from adjusted OMEGA is close to (diff is ' + str(g_n_SS_adj - g_n_SS) + ') the steady-' + 'state population growth rate from the original' + ' OMEGA.') # Do another test of the adjusted immigration rates. Create the # new OMEGA matrix implied by the new immigration rates. Plug in # the adjusted steady-state population distribution. Hit is with # the new OMEGA transition matrix and it should return the new # steady-state population distribution omega_new = np.dot(OMEGA2, omega_SSfx) omega_errs = np.absolute(omega_new - omega_SSfx) print('The maximum absolute difference between the adjusted ' + 'steady-state population distribution and the ' + 'distribution generated by hitting the adjusted OMEGA ' + 'transition matrix is ' + str(omega_errs.max())) # Plot the original immigration rates versus the adjusted # immigration rates immratesmaxdiff = \ np.absolute(imm_rates_orig - imm_rates_adj).max() print('The maximum absolute distance between any two points ' + 'of the original immigration rates and adjusted ' + 'immigration rates is ' + str(immratesmaxdiff)) fig, ax = plt.subplots() plt.plot(age_per_EpS, imm_rates_orig, label='Original Imm. Rates') plt.plot(age_per_EpS, imm_rates_adj, label='Adj. Imm. Rates') # for the minor ticks, use no labels; default NullFormatter minorLocator = MultipleLocator(1) ax.xaxis.set_minor_locator(minorLocator) plt.grid(b=True, which='major', color='0.65', linestyle='-') plt.title('Original immigration rates vs. adjusted', fontsize=20) plt.xlabel(r'Age $s$') plt.ylabel(r'Imm. rates $i_{s}$') plt.xlim((0, E + S + 1)) plt.legend(loc='upper center') # Create directory if OUTPUT directory does not already exist output_path = os.path.join(output_dir, 'OrigVsAdjImm') plt.savefig(output_path) plt.show() # Plot population distributions for data_year, curr_year, # curr_year+20, omega_SSfx, and omega_SS_orig fig, ax = plt.subplots() plt.plot(age_per_EpS, pop_2013_pct, label='2013 pop.') plt.plot(age_per_EpS, (omega_path_lev[:, 0] / omega_path_lev[:, 0].sum()), label=str(curr_year) + ' pop.') plt.plot(age_per_EpS, (omega_path_lev[:, int(0.5 * S)] / omega_path_lev[:, int(0.5 * S)].sum()), label='T=' + str(int(0.5 * S)) + ' pop.') plt.plot(age_per_EpS, (omega_path_lev[:, int(S)] / omega_path_lev[:, int(S)].sum()), label='T=' + str(int(S)) + ' pop.') plt.plot(age_per_EpS, omega_SSfx, label='Adj. SS pop.') # for the minor ticks, use no labels; default NullFormatter minorLocator = MultipleLocator(1) ax.xaxis.set_minor_locator(minorLocator) plt.grid(b=True, which='major', color='0.65', linestyle='-') plt.title('Population distribution at points in time path', fontsize=20) plt.xlabel(r'Age $s$') plt.ylabel(r"Pop. dist'n $\omega_{s}$") plt.xlim((0, E + S + 1)) plt.legend(loc='lower left') # Create directory if OUTPUT directory does not already exist output_path = os.path.join(output_dir, 'PopDistPath') plt.savefig(output_path) plt.show() # return omega_path_S, g_n_SS, omega_SSfx, survival rates, # mort_rates_S, and g_n_path return (omega_path_S.T, g_n_SS, omega_SSfx[-S:] / omega_SSfx[-S:].sum(), 1 - mort_rates_S, mort_rates_S, g_n_path, imm_rates_mat.T, omega_S_preTP)
def size_suggestion(edge_occupation, size, threshold): beta = fsolve(zero_func, 1, args=(edge_occupation, size - 1, size)) new_size = -np.log(threshold) / beta new_size = int(np.ceil(new_size)) return new_size
def find_indifference_curve_numerical(self, u0=None): if u0 == None: u0 = self.u_ast x1 = [] x2 = [] # a. fix x1 x1_x1 = np.linspace(0, self.x1max, self.N) for x1_now in x1_x1: def target_for_x2(x2): with np.errstate(divide="ignore", invalid="ignore"): udiff = self.utility(x1_now, x2) - u0 return udiff x_A, _infodict_A, ier_A, _mesg_A = optimize.fsolve( target_for_x2, 0, full_output=True) x_B, _infodict_B, ier_B, _mesg_B = optimize.fsolve( target_for_x2, self.x2max, full_output=True) if ier_A == 1: x1.append(x1_now) x2.append(x_A[0]) else: x1.append(np.nan) x2.append(np.nan) if ier_B == 1 and np.abs(x_A[0] - x_B[0]) > 0.01: x1.append(x1_now) x2.append(x_B[0]) else: x1.append(np.nan) x2.append(np.nan) # b. fix x2 x2_x2 = np.linspace(0, self.x2max, self.N) for x2_now in x2_x2: def target_for_x1(x1): with np.errstate(divide="ignore", invalid="ignore"): udiff = self.utility(x1, x2_now) - u0 return udiff x_A, _infodict_A, ier_A, _mesg_A = optimize.fsolve( target_for_x1, 0, full_output=True) x_B, _infodict_B, ier_B, _mesg_B = optimize.fsolve( target_for_x1, self.x1max, full_output=True) if ier_A == 1: x1.append(x_A[0]) x2.append(x2_now) else: x1.append(np.nan) x2.append(np.nan) if ier_B == 1 and np.abs(x_A[0] - x_B[0]) > 0.01: x1.append(x_B[0]) x2.append(x2_now) else: x1.append(np.nan) x2.append(np.nan) # c. clean x1 = np.array(x1) x2 = np.array(x2) with np.errstate(divide="ignore", invalid="ignore"): u0s = self.utility(x1, x2) I = np.isclose(u0s, u0) x1 = x1[I] x2 = x2[I] # d. sort I = np.argsort(x1) x1 = x1[I] x2 = x2[I] return x1, x2
kappa_1 + np.sqrt(kappa_2) * x def GCVAR(x): """ :param x: x :return: cumulative function """ ans = norm.cdf(x) - kappa_3 / 6 * (norm.pdf(x) * (x**2 - 1)) - ( kappa_4 - 3) / 24 * (norm.pdf(x) * x * (x**2 - 3)) return ans - 0.999 init = np.array(1.3, dtype="float") ans = fsolve(GCVAR, init) kappa_1 + np.sqrt(kappa_2) * ans # The Pearson coefficients of skewness^2 and kurtosis beta_1 = kappa_3**2 beta_2 = kappa_4 # the lower bound omega_1 D = (3 + beta_2) * (16 * (beta_2**2) + 87 * beta_2 + 171) / 27 d = -1 + (7 + 2 * beta_2 + 2 * np.sqrt(D))**(1 / 3) - (2 * np.sqrt(D) - 7 - 2 * beta_2)**(1 / 3) omega_1 = 0.5 * (-1 + np.sqrt(d) + np.sqrt(4 / np.sqrt(d) - d - 3)) omega_0 = 0.5 * (8 + 4 * beta_1 + 4 * np.sqrt(4 * beta_1 + beta_1 ** 2)) ** (1 / 3) \ + 2 * (8 + 4 * beta_1 + 4 * np.sqrt(4 * beta_1 + beta_1 ** 2)) ** (-1 / 3) - 1 omega_min = max(omega_0, omega_1) # the upper bound omega_2 = np.sqrt(-1 + np.sqrt(2 * (beta_2 - 1)))
def olf_bulb_10(Nmitral, H_in, W_in, P_odor_in, dam): # Nmitral = 10 #number of mitral cells Ngranule = np.copy(Nmitral) #number of granule cells pg. 383 of Li/Hop Ndim = Nmitral + Ngranule #total number of cells t_inh = 25 # time when inhalation starts t_exh = 205 #time when exhalation starts finalt = 395 # end time of the cycle #y = zeros(ndim,1); Sx = 1.43 #Sx,Sx2,Sy,Sy2 are parameters for the activation functions Sx2 = 0.143 Sy = 2.86 #These are given in Li/Hopfield pg 382, slightly diff in her thesis Sy2 = 0.286 th = 1 #threshold for the activation function tau_exh = 33.3333 #Exhale time constant, pg. 382 of Li/Hop exh_rate = 1 / tau_exh alpha = .15 #decay rate for the neurons #Li/Hop have it as 1/7 or .142 on pg 383 P_odor0 = np.zeros((Nmitral, 1)) #odor pattern, no odor H0 = H_in #weight matrix: to mitral from granule W0 = W_in #weights: to granule from mitral Ib = np.ones((Nmitral, 1)) * .243 #initial external input to mitral cells Ic = np.ones( (Ngranule, 1)) * .1 #initial input to granule cells, these values are #given on pg 382 of Li/Hop signalflag = 1 # 0 for linear output, 1 for activation function noise = np.zeros((Ndim, 1)) #noise in inputs noiselevel = .00143 noisewidth = 7 #noise correlation time, given pg 383 Li/Hop as 9, but 7 in thesis lastnoise = np.zeros((Ndim, 1)) #initial time of last noise pule #****************************************************************************** #CALCULATE FIXED POINTS #Calculating equilibrium value with no input rest0 = np.zeros((Ndim, 1)) restequi = fsolve(lambda x: equi(x,Ndim,Nmitral,Sx,Sx2,Sy,Sy2,th,alpha,\ t_inh,H0,W0,P_odor0,Ib,Ic,dam),rest0) #about 20 ms to run this np.random.seed(seed=23) #init0 = restequi+np.random.rand(Ndim)*.00143 #initial conditions plus some noise #for no odor input init0 = restequi + np.random.rand( Ndim) * .00143 #initial conditions plus some noise #for no odor input np.random.seed() #Now calculate equilibrium value with odor input lastnoise = lastnoise + t_inh - noisewidth #initialize lastnoise value #But what is it for? to have some #kind of correlation in the noise #find eigenvalues of A to see if input produces oscillating signal xequi = fsolve(lambda x: equi(x,Ndim,Nmitral,Sx,Sx2,Sy,Sy2,th,alpha,\ t_inh,H0,W0,P_odor_in,Ib,Ic,dam),rest0) #equilibrium values with some input, about 20 ms to run #****************************************************************************** #CALCULATE A AND DETERMINE EXISTENCE OF OSCILLATIONS diffgy = celldiff(xequi[Nmitral:], Sy, Sy2, th) diffgx = celldiff(xequi[0:Nmitral], Sx, Sx2, th) H1 = np.dot(H0, diffgy) W1 = np.dot(W0, diffgx) #intermediate step in constructing A A = np.dot(H1, W1) #Construct A dA, vA = lin.eig(A) #about 20 ms to run this #Find eigenvalues of A diff = (1j) * (dA)**.5 - alpha #criteria for a growing oscillation negsum = -(1j) * (dA)**.5 - alpha #Same diff_re = np.real(diff) #Take the real part negsum_re = np.real(negsum) #do an argmax to return the eigenvalue that will cause the fastest growing oscillations #Then do a spectrograph to track the growth of the associated freq through time indices = np.where( diff_re > 0) #Find the indices where the criteria is met indices2 = np.where(negsum_re > 0) #eigenvalues that could lead to growing oscillations # candidates = np.append(np.real((dA[indices])**.5),np.real((dA[indices2])**.5)) largest = np.argmax(diff_re) check = np.size(indices) check2 = np.size(indices2) if check == 0 and check2 == 0: # print("No Odor Recognized") dominant_freq = 0 else: dominant_freq = np.real((dA[largest])**.5) / ( 2 * np.pi) #find frequency of the dominant mode #Divide by 2pi to get to cycles/ms # print("Odor detected. Eigenvalues:",dA[indices],dA[indices2],\ # "\nEigenvectors:",vA[indices],vA[indices2],\ # "\nDominant Frequency:",dominant_freq) #************************************************************************* #SOLVE DIFFERENTIAL EQUATIONS TO GET INPUT AND OUTPUTS AS FN'S OF t #differential equation to solve teval = np.r_[0:finalt] #solve the differential equation sol = solve_ivp(lambda t,y: diffeq(t,y,Nmitral,Ngranule,Ndim,lastnoise,\ noise,noisewidth,noiselevel, t_inh,t_exh,exh_rate,alpha,Sy,\ Sy2,Sx,Sx2,th,H0,W0,P_odor_in,Ic,Ib,dam),\ [0,395],init0,t_eval = teval,method = 'RK45') t = sol.t y = sol.y y = np.transpose(y) yout = np.copy(y) #convert signal into output signal given by the activation fn if signalflag == 1: for i in np.arange(np.size(t)): yout[i, :Nmitral] = cellout(y[i, :Nmitral], Sx, Sx2, th) yout[i, Nmitral:] = cellout(y[i, Nmitral:], Sy, Sy2, th) #solve diffeq for P_odor = 0 #first, reinitialize lastnoise & noise noise = np.zeros((Ndim, 1)) lastnoise = np.zeros((Ndim, 1)) lastnoise = lastnoise + t_inh - noisewidth sol0 = sol = solve_ivp(lambda t,y: diffeq(t,y,Nmitral,Ngranule,Ndim,lastnoise,\ noise,noisewidth,noiselevel, t_inh,t_exh,exh_rate,alpha,Sy,\ Sy2,Sx,Sx2,th,H0,W0,P_odor0,Ic,Ib,dam),\ [0,395],init0,t_eval = teval,method = 'RK45') y0 = sol0.y y0 = np.transpose(y0) y0out = np.copy(y0) #convert signal into output signal given by the activation fn if signalflag == 1: for i in np.arange(np.size(t)): y0out[i, :Nmitral] = cellout(y0[i, :Nmitral], Sx, Sx2, th) y0out[i, Nmitral:] = cellout(y0[i, Nmitral:], Sy, Sy2, th) #***************************************************************************** #SIGNAL PROCESSING #Filtering the signal - O_mean: Lowpass fitered signal, under 20 Hz #S_h: Highpass filtered signal, over 20 Hz fs = 1 / (.001 * (t[1] - t[0])) #sampling freq, converting from ms to sec f_c = 15 / fs # Cutoff freq at 20 Hz, written as a ratio of fc to sample freq flter = np.sinc(2 * f_c * (t - (finalt - 1) / 2)) * np.blackman(finalt) #creating the #windowed sinc filter #centered at the middle #of the time data flter = flter / np.sum(flter) #normalize hpflter = -np.copy(flter) hpflter[int( (finalt - 1) / 2)] += 1 #convert the LP filter into a HP filter Sh = np.zeros(np.shape(yout)) Sl = np.copy(Sh) Sl0 = np.copy(Sh) Sbp = np.copy(Sh) for i in np.arange(Ndim): Sh[:, i] = np.convolve(yout[:, i], hpflter, mode='same') Sl[:, i] = np.convolve(yout[:, i], flter, mode='same') Sl0[:, i] = np.convolve(y0out[:, i], flter, mode='same') #find the oscillation period Tosc (Tosc must be greater than 5 ms to exclude noise) Tosc0 = np.zeros(np.size(np.arange(5, 50))) for i in np.arange(5, 50): Sh_shifted = np.roll(Sh, i, axis=0) Tosc0[i - 5] = np.sum( np.diagonal( np.dot(np.transpose(Sh[:, :Nmitral]), Sh_shifted[:, :Nmitral]))) #That is, do the correlation matrix (time correlation), take the diagonal to #get the autocorrelations, and find the max Tosc = np.argmax(Tosc0) Tosc = Tosc + 5 f_c2 = 1000 * ( 1.3 / Tosc) / fs #Filter out components with frequencies higher than this #to get rid of noise effects in cross-correlation #times 1000 to get units right flter2 = np.sinc(2 * f_c2 * (t - (finalt - 1) / 2)) * np.blackman(finalt) flter2 = flter2 / np.sum(flter2) for i in np.arange(Ndim): Sbp[:, i] = np.convolve(Sh[:, i], flter2, mode='same') #CALCULATE THE DISTANCE MEASURES #calculate phase via cross-correlation with each cell phase = np.zeros(Nmitral) for i in np.arange(1, Nmitral): crosscor = signal.correlate(Sbp[:, 0], Sbp[:, i]) tdiff = np.argmax(crosscor) - (finalt - 1) phase[i] = tdiff / Tosc * 2 * np.pi #Problem with the method below is that it will only give values from 0 to pi #for i in np.arange(1,Nmitral): # phase[i]=np.arccos(np.dot(Sbp[:,0],Sbp[:,i])/(lin.norm(Sbp[:,0])*lin.norm(Sbp[:,i]))) OsciAmp = np.zeros(Nmitral) Oosci = np.copy(OsciAmp) * 0j Omean = np.zeros(Nmitral) for i in np.arange(Nmitral): OsciAmp[i] = np.sqrt( np.sum(Sh[125:250, i]**2) / np.size(Sh[125:250, i])) Oosci[i] = OsciAmp[i] * np.exp(1j * phase[i]) Omean[i] = np.average(Sl[:, i] - Sl0[:, i]) Omean = np.maximum(Omean, 0) Ooscibar = np.sqrt(np.dot( Oosci, np.conjugate(Oosci))) / Nmitral #can't just square b/c it's complex Omeanbar = np.sqrt(np.dot(Omean, Omean)) / Nmitral maxlam = np.max(np.abs(np.imag(np.sqrt(dA)))) return yout, y0out, Sh, t, OsciAmp, Omean, Oosci, Omeanbar, Ooscibar, dominant_freq, maxlam
def dblsigmoid_tpeak(center1, spread1, center2, spread2): derivative_dblsigmoid = ( lambda t: -exp(-(t-center1)/spread1)/spread1 / (1+exp(-(t-center1)/spread1))**2 + \ exp(-(t-center2)/spread2)/spread2 / (1+exp(-(t-center2)/spread2))**2 ) ## fsolve returns ndarray even for one value, return only the value return fsolve(derivative_dblsigmoid, (spread1 + spread2) / 2.0)[0]
import numpy as np import scipy as sp from scipy.optimize import fsolve import matplotlib.pyplot as plt N = 10 v = np.zeros(N) v0 = 2.0 vt = 25e-3 I0 = 1e-9 R = 1e3 def f(i) : return i - I0*(np.exp((v0 - i*R)/vt)-1) Id = fsolve(f, 1.6e-3) Vd = v0 - Id[0]*R print(Id[0]) print(Vd)
import time file_path = input('Podaj nazwe pliku z rozszerzeniem .csv znajdującego z w bieżącym folderze: ') t = pd.read_csv(file_path, header=None).values.flatten() alpha = float(input('Podaj dokładność: ')) start = time.time() range_t = np.arange(len(t)) b = np.sum(range_t*t) def j_m(x): return np.sum(1/(x - range_t)) - len(t)*np.sum(t)/(x*np.sum(t) - b) i = len(t) N_jm = fsolve(j_m, i, xtol=alpha) while not (N_jm > len(t) and N_jm < 1000): N_jm = fsolve(j_m, i, xtol=alpha) i+=1 phi_jm = len(t)/(N_jm*np.sum(t) - b) T_241_jm = 1/(phi_jm*(N_jm - len(t) + 1)) end_jm = time.time() - start start = time.time() T = np.sum(t*t) def s_w(x): return 2*len(t)/(x*T - np.sum(range_t*(t*t))) - 2*np.sum(1/((x - range_t)*T))
return (T * np.cos(T * mu) + (T - 1) * T * np.pi * np.sin(T * mu) / 2) * np.e**( (T - 1) * T * np.pi * mu / 2) # non-Gaussian case two asymptotics, above and belowe phase transition if stat == 'nG': if T > 0.5: return (np.log(2 * T - 1) * np.sin(mu) / np.pi + np.cos(mu)) * np.e**(mu * np.log(2 * T - 1) / np.pi) else: return (1 + mu * np.log(1 - 2 * T) / np.pi) * np.e**( mu * np.log(1 - 2 * T) / np.pi) first_zero = {'G': [], 'nG': []} second_max_pos = {'G': [], 'nG': []} second_max_value = {'G': [], 'nG': []} for stat in ['G', 'nG']: for i, T in enumerate(T_list): first_zero[stat].append(fsolve(V, SEARCH_ZERO, (T, stat))[0]) second_max_pos[stat].append( fsolve(D(V), SEARCH_SECOND_MAX, (T, stat))[0]) second_max_value[stat].append(V(second_max_pos[stat][i], T, stat)) print first_zero['G'] print first_zero['nG'] print second_max_value['G'] print second_max_value['nG']
fig, ax = plt.subplots(1, 1) # a, b = 2.30984964515, 0.62687954301 # mean, var, skew, kurt = beta.stats(a, b, moments='mvsk') secondsUntilStaging = 285 time = np.array(range(secondsUntilStaging + 1)) * 1. ''' Failure at time of launch''' # %% Failure on the pad # % Use a beta distribution, specify the mean and variance, solve for params mu = 15. / time[-1] dev = 5. / time[-1] # % Could add in some logic that if alpha is neg or nan, try a new guess funA = lambda a: ((a**2 * (1 / mu - 1)) / ((a / mu)**2 * (a / mu + 1)) - dev**2) alphaTemp = fsolve(funA, 10) betaTemp = alphaTemp * (1 / mu - 1) checkMean = alphaTemp / (alphaTemp + betaTemp) checkStd = sqrt(alphaTemp * betaTemp / ((alphaTemp + betaTemp)**2 * (alphaTemp + betaTemp + 1))) alphaPad = alphaTemp betaPad = betaTemp ''' Failure at First stage burnout''' mu = 75. / time[-1] dev = 5. / time[-1] funA = lambda a: ((a**2 * (1 / mu - 1)) / ((a / mu)**2 * (a / mu + 1)) - dev**2) alphaTemp = fsolve(funA, 50)
# Revision: none # Compiler: gcc # # Author: zt () # Organization: import scipy.optimize as opt import scipy.integrate as inte def f2(p): x, y = p return [(x - 5)**2 + (y - 5)**2 - 5**2, x**2 + (y - 10)**2 - 10**2] r1 = opt.fsolve(f2, [0, 0]) r2 = opt.fsolve(f2, [10, 10]) x1 = r1[0] x2 = r2[0] print(x1) print(x2) def ff1(x): return 2 * (5**2 - (x - 5)**2)**0.5 s1 = inte.quad(ff1, 0, x1) print(s1)
Cm = update_Cm(w,phi,T) Fo = update_Fo(w,k,rho,Cp,dt,dx) Fow = update_Fow(w,dt,dx) i=0 pbar=tqdm(total=sim_time) #set up a progress par # time loop while t <= sim_time: # update boundary conditions T[0] = Tleft T[-1] = Tleft +20 pv[0] = pvleft pv[-1]= pvleft +300 # solve the coupled, non-linear system result_array=fsolve(fc_coupled_HAM, np.hstack([T,pv]), args=(np.hstack([T,pv]), K, Fo, Fow, dt, rho, Cp, Cm, Lv)) # split the result into T and pv T_plus,pv_plus=result_array[0:n], result_array[n:] # compute phi phi=pv/fc_pvsat(T)*100 # compute water content w=fc_w_phi(phi) # do some storage for plotting if (int(t) % modulo_storage)==0 and t!=0: store_w.append(w[1:-1]*1000) store_phi.append(phi[1:-1]) store_T.append(T[1:-1])
# scipy_optimize from scipy.optimize import fsolve import math def equations(p): x, y = p return math.tan(x * y + 0.1) - x**2, 0.6 * x**2 + 2 * y**2 - 1 x, y = fsolve(equations, (1, 1)) print('Корни СУ: ', x, ',', y) # print(equations((x, y)))
def respeciate(self, fluid_comp, newP, input_type='wtpercent'): """Takes in a fluid of given composition and returns that fluid respeciated at a given pressure. Parameters ---------- self, inherited from Class fluid_comp: dict Dictionary of fluid composition with possible keys: CO, CO2, H2, H2O, H2S, O2, S2, SO2 newP: float Pressure at which to respeciate the fluid, in bars. input_type: str String defining whether fluid_comp is input as wt percent ("wtpercent"), mole percent ("molpercent"), or mole fraction ("molfrac"). Default is "wtpercent". Returns ------- dict Dictionary of fluid composition in mole fraction after respeciation. #TODO give other return type options. """ #Get some needed Class variables fugacities = self.fugacities gammas = calc_gammas(press=newP, temp=self.temp) Ks = self.Ks #Recalculate fO2 at new pressure logfO2_res = calc_logfO2_from_buffer(press=newP, temp=self.temp, buffer=self.fO2_buffer, delta=self.fO2_delta) self.fO2_res = 10**(logfO2_res) #Take any input type and convert to mole fraction if input_type == "wtpercent": fluid_comp = wtpercent_to_molfrac(fluid_comp) if input_type == "molpercent": fluid_comp = {k: v / 100.0 for k, v in fluid_comp.items()} if input_type == "molfrac": pass #Name some local variables for clarity in below equations. If a particular species is not passed, #it will be assigned a value of 0.0 if 'CO' in fluid_comp: CO = fluid_comp["CO"] else: CO = 0.0 if 'CO2' in fluid_comp: CO2 = fluid_comp["CO2"] else: CO2 = 0.0 if 'H2' in fluid_comp: H2 = fluid_comp["H2"] else: H2 = 0.0 if 'H2O' in fluid_comp: H2O = fluid_comp["H2O"] else: H2O = 0.0 if 'H2S' in fluid_comp: H2S = fluid_comp["H2S"] else: H2S = 0.0 if 'O2' in fluid_comp: O2 = fluid_comp["O2"] else: O2 = 0.0 if 'S2' in fluid_comp: S2 = fluid_comp["S2"] else: S2 = 0.0 if 'SO2' in fluid_comp: SO2 = fluid_comp["SO2"] else: SO2 = 0.0 XHtot = H2 + (0.666666)*H2O + (0.666666)*H2S XStot = S2 + (0.333333)*H2S + (0.333333)*SO2 XCtot = (0.333333)*CO2 + (0.5)*CO XOtot = O2 + (0.666666)*CO2 + (0.5)*CO + (0.333333)*H2O + (0.666666)*SO2 #FIRST calculate fH2 and fS2 using fsolve, two eqns; two unknowns (eqn 9 in Iacovino, 2015) #TODO - User might want the fO2 to be set by a buffer. If so, the fO2 used in the equation below must #be recalculated at 1 bar!!! #TODO - figure out how to do these two equations with two unknowns and set bounds that roots must be >0 #Used least_squares to do this in a similar implimentation in this very script, but I can't #figureo out how to get it to work with two equations instead of just one. #THIS IS IMPORTANT since right now it's a total non-mathematical flub. def equations(p): fH2, fS2 = p return ( ( (fH2/(self.gammas["H2"]*newP)) + ((Rational(2.0) * self.Ks["H2O"] * fH2 * sqrt(self.fO2_res))/(Rational(3.0) * self.gammas["H2O"] * newP)) + ((Rational(2.0) * self.Ks["H2S"] * fH2 * sqrt(abs(fS2)))/(Rational(3.0) * self.gammas["H2S"] * newP)) - XHtot), ( (fS2/(self.gammas["S2"] * newP)) + ((self.Ks["H2S"] * fH2 * sqrt(abs(fS2)))/(Rational(3.0) * self.gammas["H2S"] * newP)) + ((self.Ks["SO2"] * self.fO2_res * sqrt(abs(fS2)))/(Rational(3.0) * self.gammas["SO2"] * newP)) - XStot) ) fH2_a, fS2_a = fsolve(equations, (1, 1)) fH2 = abs(fH2_a) fS2 = abs(fS2_a) #res = least_squares(equations, (0.0001, 0.0001), bounds=((0.0, 0.0), (10.0, 10.0))) #fH2 = res.x[0] #fS2 = res.x[1] #SECOND calculate fCO (eqn 10 in Iacovino, 2015) fCO = symbols('fCO') #for sympy equation = (((Ks["CO2"] * fCO * sqrt(self.fO2_res))/(3.0 * gammas["CO2"] * newP)) + ((fCO)/(2.0 * gammas["CO"] * newP)) - XCtot) fCO = solve(equation, fCO)[0] #newly implemented sympy way # def fCO_func(fCO): # return (((Ks["CO2"] * fCO * sqrt(fugacities["O2"]))/(3 * gammas["CO2"] * newP)) + ((fCO)/(2 * gammas["CO"] * newP)) - XCtot) # fCO_array = least_squares(fCO_func, 0.001, bounds=(0, np.inf)) # fCO = fCO_array.x[0] #THIRD calculate fCO2 using calc'd fCO and known fO2 value fCO2 = self.Ks["CO2"] * fCO * sqrt(self.fO2_res) #FOURTH calcualte fSO2 using calc'd fS2 and known fO2 value fSO2 = self.Ks["SO2"] * sqrt(fS2) * self.fO2_res #FIFTH calculate fH2S using calc'd fH2 and fS2 values fH2S = self.Ks["H2S"] * fH2 * sqrt(fS2) #SIXTH calculate fH2O using calc'd fH2 and knwn fO2 value fH2O = self.Ks["H2O"] * sqrt(self.fO2_res) * fH2 new_fugacities = {"CO": fCO, "CO2": fCO2, "H2": fH2, "H2O": fH2O, "H2S": fH2S, "O2": self.fO2_res, "S2": fS2, "SO2": fSO2} self.new_fugacities = new_fugacities X_dict = {} for species in fluid_species_names: X = new_fugacities[species] / (gammas[species] * newP) X_dict[species] = X return {key: value/sum(X_dict.values()) for key,value in X_dict.items()}
rhoW = rhoB uTau = ReTau * muW / (rhoW * h) deltaNu = muW / (uTau * rhoW) TauW = uTau**2 * rhoB yPlusTrg = 0.8 def objective(yStretching): yGrid, dy = gridGen.GetGrid(config["Grid"]["origin"][1], 2.0 * h, config["Grid"]["yNum"], config["Grid"]["yType"], yStretching, False) return dy[1] / deltaNu - yPlusTrg yStretching, = fsolve(objective, 1.0) tNu = deltaNu**2 * rhoW / muW # Grid section config["Grid"]["xWidth"] = 8.0 * h * np.pi config["Grid"]["yWidth"] = 2.0 * h config["Grid"]["zWidth"] = 2.0 * h * np.pi config["Grid"]["yStretching"] = yStretching # Flow section config["Flow"]["initParams"][2] = uB config["Flow"]["turbForcing"]["RhoUbulk"] = rhoB * uB config["Flow"]["turbForcing"]["Forcing"] = TauW / h config["Integrator"]["maxTime"] = tNu * dTplus
x_n = x_0 t_n = 0.0 for i in range(N): u_n = vel(x_n) print(tr, t_n, x_n[0], x_n[1], x_n[2], u_n[0], u_n[1], u_n[2], file=fout, sep=',') if x_n[0] >= x_max: break dt = delta_s / np.linalg.norm(u_n) t_n += dt # Crank--Nicolson scheme x_n1 = x_n + u_n * dt x_n2 = fsolve(func, x_n1, args=(x_n, dt), fprime=funcjac) x_n = x_n2 if mesh.bounding_box_tree().compute_first_entity_collision( Point(x_n)) < mesh.num_cells(): # if x_n[2] <= z_min+eps or x_n[2] >= z_max-eps \ # or np.sqrt(x_n[0]**2 + x_n[1]**2) >= np.sqrt(x_max**2 + y_max**2)-eps: break print("\n\n", file=fout) fout.close()
# -*- coding: utf-8 -* # 求解非线性方程组2x1-x2^2=1,x1^2-x2=2 from scipy import integrate # 导入积分函数 from scipy.optimize import fsolve # 导入求解方程组的函数 def f(x): # 定义要求解的方程组 x1 = x[0] x2 = x[1] return [2 * x1 - x2**2 - 1, x1**2 - x2 - 2] result = fsolve(f, [1, 1]) # 输入初值[1, 1]并求解 print(result) # 输出结果,为array([ 1.91963957, 1.68501606]) # 数值积分 def g(x): # 定义被积函数 return (1 - x**2)**0.5 def h(x): return (1 - x**2) * 0.5 pi_2, err = integrate.quad(g, -1, 1) # 积分结果和误差 print(pi_2 * 2) # 由微积分知识知道积分结果为圆周率pi的一半 i, err = integrate.quad(h, -1, 1) print(i, err)
def funcv(x): """ System of equations to solve for. The input x has 2 elements, and the function returns two results. """ f0 = x[0]**3.0 + x[1] + 3.0 f1 = x[1] - 4.0 * x[0] return f0, f1 # Set a starting point for the solver x_guess = array((50.0, 10.0)) # Solve the equation using fsolve # x_guess is changed in place, so were going to make a copy... x_opt = optimize.fsolve(funcv, x_guess.copy()) print 'optimal x:', x_opt print 'optimal f(x):', funcv(x_opt) # Make some pretty plots to show the function space as well # as the solver starting point and the solution. # Create 2D arrays x and y and evaluate them so that we # can get the results for f0 and f1 in the system of equations. x, y = mgrid[-100:100:.5, -100:100:.5] f0, f1 = funcv((x, y)) # Set up a plot of f0 and f1 vs. x and y and show the # starting and ending point of the solver on each plot. pylab.figure(figsize=(14, 5)) pylab.subplot(1, 2, 1)
ax.legend(loc=9) #plt.tight_layout() plt.show() # The energy units from LAMMPS are in eV, and distances are given in # Angstroms. We need to convert the energies to Si to compute # elastic constants in GPa eV = 1.60217646e-19 #[eV] conv = eV * 1e30 #[eV*m # lattice parameter of the Cu unit cell (when eta = 0) ao = 3.615 # Using the second order polynomoial fit: # Compute the value for eta the gives the minimum energy p2_prime = np.polyder(p2) xo = fsolve(p2_prime, -0.05) print xo a = (1 + xo) * ao # relaxed lattic paramter print "relaxed lattice (2nd order) = ", a # Depending on how we are straining the copper unit cell we can now # relate the second derivative of the energy to the elastic constants. # For the case of a uniaxial tension we can relate C_11 to the energy k2 = p2_prime(0) # Compute Stiffness p2_2prime = np.polyder(p2_prime) k2 = p2_2prime(0) # Compute Stiffness print "stiffness (2nd order)", k2 k2 = conv * k2 / (a**3) # Convert to units of Pa print "stiffness (2nd order) %s [GPa]" % (k2 / (10**9)) # Using the third order polynomoial fit: # Compute the value for eta the gives the minimum energy
from scipy.stats import norm from scipy.optimize import fsolve print("p=", norm.cdf(6, 3, 5) - norm.cdf(2, 3, 5)) f=lambda c:norm.cdf(2*c,3,5)-norm.cdf(-3*c,3,5)-0.6 print("c=",fsolve(f,0))
#!/usr/bin/python from math import log10 from math import sqrt from scipy.optimize import fsolve def g(f): epsilon_D = 0.004 Re = 200000 return (1 / sqrt(f)) + 2 * log10(epsilon_D / 3.7 + 2.51 / (Re * sqrt(f))) f0 = 0.01 print fsolve(g, f0)
def animate(i, y1, y2, y3, y4, y5, y6, y7, y8, y9): start = time.time() global count # Read Resistance from multimeter val = float(Short_HW_4W()) x1 = dt.datetime.now().strftime('%H:%M:%S.%f') y1.append(val) # Limit y list to set number of items y1 = y1[-x_len:] # Update line with new Y values line1.set_ydata(y1) print(val) val2 = float(Long_HW_4W()) x2 = dt.datetime.now().strftime('%H:%M:%S.%f') y2.append(val2) y2 = y2[-x_len:] line2.set_ydata(y2) print(val2) val3 = float(FourWire(107, 115)) # Temp_Probe x3 = dt.datetime.now().strftime('%H:%M:%S.%f') Temp3 = fsolve(TempProbeSolve, 0, val3) y3.append(Temp3) y3 = y3[-x_len:] line3.set_ydata(y3) Relay.write("CLOS (@111)") val4 = float(Thermistor_4W(103)) # PT_6 x4 = dt.datetime.now().strftime('%H:%M:%S.%f') Temp4 = fsolve(ThermistorSolve, 0, val4) y4.append(Temp4) y4 = y4[-x_len:] line4.set_ydata(y4) Relay.write("OPEN (@190)") Relay.write("CLOS (@192)") val5 = float(Thermistor_4W(113)) # PT_1 x5 = dt.datetime.now().strftime('%H:%M:%S.%f') Temp5 = fsolve(ThermistorSolve, 0, val5) y5.append(Temp5) y5 = y5[-x_len:] line5.set_ydata(y5) val6 = float(Thermistor_4W(114)) # PT_2 x6 = dt.datetime.now().strftime('%H:%M:%S.%f') Temp6 = fsolve(ThermistorSolve, 0, val6) y6.append(Temp6) y6 = y6[-x_len:] line6.set_ydata(y6) val7 = float(Thermistor_4W(110)) # PT_3 x7 = dt.datetime.now().strftime('%H:%M:%S.%f') Temp7 = fsolve(ThermistorSolve, 0, val7) y7.append(Temp7) y7 = y7[-x_len:] line7.set_ydata(y7) val8 = float(Thermistor_4W(109)) # PT_4 PERCISE x8 = dt.datetime.now().strftime('%H:%M:%S.%f') Temp8 = fsolve(ThermistorSolveP, 0, val8) y8.append(Temp8) y8 = y8[-x_len:] line8.set_ydata(y8) val9 = float(Thermistor_4W(112)) # PT_5 x9 = dt.datetime.now().strftime('%H:%M:%S.%f') Temp9 = fsolve(ThermistorSolve, 0, val9) y9.append(Temp9) y9 = y9[-x_len:] line9.set_ydata(y9) Relay.write("OPEN (@111)") Relay.write("CLOS (@190)") Relay.write("OPEN (@192)") with open(filename, "a", newline='') as f: writer = csv.writer(f) writer.writerow([count, val, x1, val2, x2, val3, Temp3[0], x3, val4, Temp4[0], x4, val5, Temp5[0], x5, val6, Temp6[0], x6, val7, Temp7[0], x7, val8, Temp8[0], x8, val9, Temp9[0], x9]) count += 1 end = time.time() print(end - start) return line1, line2, line3, line4, line5, line6, line7, line8, line9,