def eval(self,E,L,logSigmaR=0.,logsigmaR2=0.): """ NAME: eval PURPOSE: evaluate the distribution function INPUT: E - energy (/vo^2) L - angular momentun (/ro/vo) OUTPUT: DF(E,L) HISTORY: 2010-05-09 - Written - Bovy (NYU) """ #Calculate RL,LL, OmegaL if self._beta == 0.: xL= L logECLE= sc.log(-sc.log(xL)-0.5+E) else: #non-flat rotation curve xL= L**(1./(self._beta+1.)) logECLE= sc.log(-0.5*(1./self._beta+1.)*xL**(2.*self._beta)+E) if xL < 0.: #We must remove counter-rotating mass return 0. if self._correct: correction= self._corr.correct(xL,log=True) else: correction= sc.zeros(2) SRE2= self.targetSigma2(xL,log=True)+correction[1] return sc.exp(logsigmaR2-SRE2+self.targetSurfacemass(xL,log=True)-logSigmaR-sc.exp(logECLE-SRE2)+correction[0])
def FuMass(self,t): """ time = array of values where to calculate the Fu etal model """ am = self.t_alpham * self.t_alpham bn = self.t_betan * self.t_betan # P1: # matrix: alpha --> # time # | # | # v # p1 = scipy.exp( -self.D1 * outer( t, am ) ) / am # P2: # matrix: beta --> # time # | # | # v # p2 = scipy.exp( -self.D2 * outer( t, bn ) ) / bn s1 = sum(p1,axis=1) s2 = sum(p2,axis=1) return( 1.0-8.0*s1*s2 )
def _Psat(Tdb): """ ASHRAE Fundamentals Handbook pag 1.2 eq. 4 input: Dry bulb temperature, K return: Saturation pressure, Pa """ if 173.15 <= Tdb < 273.15: C1 = -5674.5359 C2 = 6.3925247 C3 = -0.009677843 C4 = 0.00000062215701 C5 = 2.0747825E-09 C6 = -9.484024E-13 C7 = 4.1635019 pws = exp(C1/Tdb + C2 + C3*Tdb + C4*Tdb**2 + C5*Tdb**3 + C6*Tdb**4 + C7*log(Tdb)) elif 273.15 <= Tdb <= 473.15: C8 = -5800.2206 C9 = 1.3914993 C10 = -0.048640239 C11 = 0.000041764768 C12 = -0.000000014452093 C13 = 6.5459673 pws = exp(C8/Tdb + C9 + C10*Tdb + C11*Tdb**2 + C12*Tdb**3 + C13*log(Tdb)) else: raise NotImplementedError("Incoming out of bound") return pws
def lnmixgaussian(x, params): """ NAME: lnmixgaussian PURPOSE: returns the log of a mixture of two two-dimensional gaussian INPUT: x - 2D point to evaluate the Gaussian at params - mean and variances ([mean_array,inverse variance matrix, mean_array, inverse variance, amp1]) OUTPUT: log N(mean,var) HISTORY: 2009-10-30 - Written - Bovy (NYU) """ return sc.log( params[4] / 2.0 / sc.pi * sc.sqrt(linalg.det(params[1])) * sc.exp(-0.5 * sc.dot(x - params[0], sc.dot(params[1], x - params[0]))) + (1.0 - params[4]) / 2.0 / sc.pi * sc.sqrt(linalg.det(params[3])) * sc.exp(-0.5 * sc.dot(x - params[2], sc.dot(params[3], x - params[2]))) )
def coste(self, *args, **kwargs): """ material: 0 - Carbon steel 1 - Stainless steel 316 2 - Stainless steel 304 3 - Stainless steel 347 4 - Nickel 5 - Monel 6 - Inconel 7 - Zirconium 8 - Titanium 9 - Brick and rubber or brick and polyester-lined steel 10 - Rubber or lead-lined steel 11 - Polyester, fiberglass-reinforced 12 - Aluminum 13 - Copper 14 - Concrete """ self._indicesCoste(*args) self.material=kwargs["material"] V=self.Volumen.galUS Fm=[1., 2.7, 2.4, 3.0, 3.5, 3.3, 3.8, 11.0, 11.0, 2.75, 1.9, 0.32, 2.7, 2.3, 0.55][self.material] if V<=21000: C=Fm*exp(2.631+1.3673*log(V)-0.06309*log(V)**2) else: C=Fm*exp(11.662+0.6104*log(V)-0.04536*log(V)**2) self.C_adq=Currency(C*self.Current_index/self.Base_index) self.C_inst=Currency(self.C_adq*self.f_install)
def evaluate_at(self, grid, component=None, prefactor=False): r"""Evaluate the Hagedorn wavepacket :math:`\Psi` at the given nodes :math:`\gamma`. :param grid: The grid :math:\Gamma` containing the nodes :math:`\gamma`. :type grid: A class having a :py:meth:`get_nodes(...)` method. :param component: The index :math:`i` of a single component :math:`\Phi_i` to evaluate. (Defaults to ``None`` for evaluating all components.) :param prefactor: Whether to include a factor of :math:`\frac{1}{\sqrt{\det(Q)}}`. :type prefactor: bool, default is ``False``. :return: A list of arrays or a single array containing the values of the :math:`\Phi_i` at the nodes :math:`\gamma`. """ if component is not None: # Avoid the expensive evaluation of unused other bases q, p, Q, P, S = self._Pis[component] phase = exp(1.0j * S / self._eps**2) basis = self.evaluate_basis_at(grid, component=component, prefactor=prefactor) values = phase * sum(self._coefficients[component] * basis, axis=0) else: values = [] for index in xrange(self._number_components): q, p, Q, P, S = self._Pis[index] phase = exp(1.0j * S / self._eps**2) basis = self.evaluate_basis_at(grid, component=index, prefactor=prefactor) values.append( phase * sum(self._coefficients[index] * basis, axis=0) ) return values
def gabor2d(gsw, gsh, gx0, gy0, wfreq, worient, wphase, shape): """ Generate a gabor 2d array Inputs: gsw -- standard deviation of the gaussian envelope (width) gsh -- standard deviation of the gaussian envelope (height) gx0 -- x indice of center of the gaussian envelope gy0 -- y indice of center of the gaussian envelope wfreq -- frequency of the 2d wave worient -- orientation of the 2d wave wphase -- phase of the 2d wave shape -- shape tuple (height, width) Outputs: gabor -- 2d gabor with zero-mean and unit-variance """ height, width = shape y, x = N.mgrid[0:height, 0:width] X = x * N.cos(worient) * wfreq Y = y * N.sin(worient) * wfreq env = N.exp( -.5 * ( ((x-gx0)**2./gsw**2.) + ((y-gy0)**2./gsh**2.) ) ) wave = N.exp( 1j*(2*N.pi*(X+Y) + wphase) ) gabor = N.real(env * wave) gabor -= gabor.mean() gabor /= fastnorm(gabor) return gabor
def Chung(fluid,network,propname,Vc,MW,acentric,kappa,dipole,**params): r""" Uses Chung et al. model to estimate viscosity for gases with low pressure(not near the critical pressure) from first principles at conditions of interest Parameters ---------- Vc : float, array_like Critical volume of the component (m3/mol) MW : float, array_like Molecular weight of the component (kg/mol) acentric : float, array_like Acentric factor of the component kappa : float, array_like Special correction for highly polar substances dipole :float, array_like Dipole moment (C.m) """ T = network.get_pore_data(phase=fluid,prop='temperature') Tc = fluid.get_pore_data(prop = 'Tc') Tr= T/Tc Tstar = 1.2593*Tr A = 1.161415 B = 0.14874 C = 0.52487 D = 0.77320 E = 2.16178 F = 2.43787 sigma = (A*(Tstar)**(-B)) + C*(sp.exp(-D*Tstar)) + E*(sp.exp(-F*Tstar)) dipole_r = 131.3*(dipole*2.997e29)/((Vc*1e6)*Tc)**0.5 f = 1-0.2756*acentric + 0.059035*(dipole_r**4) + kappa value = 40.785*f*(MW*1e3*T)**0.5/((Vc*1e6)**(2/3)*sigma)*1e-7 network.set_pore_data(phase=fluid,prop=propname,data=value)
def morlet(M, w=5.0, s=1.0, complete=True): """ Complex Morlet wavelet. Parameters ---------- M : int Length of the wavelet. w : float, optional Omega0. Default is 5 s : float, optional Scaling factor, windowed from ``-s*2*pi`` to ``+s*2*pi``. Default is 1. complete : bool, optional Whether to use the complete or the standard version. Returns ------- morlet : (M,) ndarray See Also -------- scipy.signal.gausspulse Notes ----- The standard version:: pi**-0.25 * exp(1j*w*x) * exp(-0.5*(x**2)) This commonly used wavelet is often referred to simply as the Morlet wavelet. Note that this simplified version can cause admissibility problems at low values of `w`. The complete version:: pi**-0.25 * (exp(1j*w*x) - exp(-0.5*(w**2))) * exp(-0.5*(x**2)) This version has a correction term to improve admissibility. For `w` greater than 5, the correction term is negligible. Note that the energy of the return wavelet is not normalised according to `s`. The fundamental frequency of this wavelet in Hz is given by ``f = 2*s*w*r / M`` where `r` is the sampling rate. Note: This function was created before `cwt` and is not compatible with it. """ x = linspace(-s * 2 * pi, s * 2 * pi, M) output = exp(1j * w * x) if complete: output -= exp(-0.5 * (w**2)) output *= exp(-0.5 * (x**2)) * pi**(-0.25) return output
def _Efficiency(self): Gas = self.kwargs["entradaGas"] Liquido = self.kwargs["entradaLiquido"] rhoS = Gas.solido.rho muG = Gas.Gas.mu rhoL = Liquido.Liquido.rho rendimiento_fraccional = [] if self.kwargs["modelo_rendimiento"] == 0: # Modelo de Johnstone (1954) l = sqrt(pi/8)*Gas.Gas.mu/0.4987445/sqrt(Gas.Gas.rho*Gas.P) for dp in Gas.solido.diametros: Kn = l/dp*2 C = Cunningham(l, Kn) kp = C*rhoS*dp**2*self.Vg/9/Gas.Gas.mu/self.dd penetration = exp(-self.k*self.R*kp**0.5) rendimiento_fraccional.append(1-penetration) elif self.kwargs["modelo_rendimiento"] == 1: # Modelo de Calvert (1972) l = sqrt(pi/8)*muG/0.4987445/sqrt(Gas.Gas.rho*Gas.P) for dp in Gas.solido.diametros: Kn = l/dp*2 C = Cunningham(l, Kn) kp = C*rhoS*dp**2*self.Vg/9/muG/self.dd b = (-0.7-kp*self.f+1.4*log((kp*self.f+0.7)/0.7)+0.49 / (0.7+kp*self.f)) penetration = exp(self.R*self.Vg*rhoL*self.dd/55/muG*b/kp) if penetration > 1: penetration = 1 elif penetration < 0: penetration = 0 rendimiento_fraccional.append(1-penetration) return rendimiento_fraccional
def rekernel(self): dcontrol = self.control[ord('d')] econtrol = self.control[ord('e')] rcontrol = self.control[ord('r')] radius = rcontrol.val dvalue = dcontrol.val evalue = econtrol.val rmax = rcontrol.limit[2] if self.rlast != radius: inner, outer = float(radius-1), float(radius) shape = (self.edge, self.edge) self.radii = list(product(arange(-rmax,rmax+1,1.0), repeat=2)) self.radii = array([sqrt(x*x+y*y) for x,y in self.radii]).reshape(shape) if True: self.negative = -exp(-dvalue*(self.radii-outer)**2) self.positive = +exp(-dvalue*(self.radii-inner)**2) else: self.radii = around(self.radii) self.negative = zeros((self.edge,self.edge),dtype=float) self.negative[self.radii == outer] = -1.0 self.positive = zeros(shape,dtype=float) self.positive[self.radii == inner] = +1.0 self.negative /= fabs(self.negative.sum()) self.positive /= fabs(self.positive.sum()) self.kernel = self.negative + self.positive self.rlast = radius if self.elast != evalue: self.gauss = exp(-evalue * self.radii**2) self.gauss /= self.gauss.sum() self.elast = evalue
def f(self,xarr,t): x0dot = -self.coef*pl.exp(-self.k*(1.0+abs(xarr[3]-1.0)))*pl.sin(self.w*t-self.k*xarr[2]) x1dot = pl.sign(xarr[3]-1.0)*self.coef*pl.exp(-self.k*(1.0+abs(xarr[3]-1.0)))*pl.cos(self.w*t-self.k*xarr[2]) -\ pl.sign(xarr[3]-1.0)*9.8 x2dot = xarr[0] x3dot = xarr[1] return [x0dot,x1dot,x2dot,x3dot]
def Alfa(Tr, m, f_acent, EOS="SRK", alfa=None): """Diferentes expresiónes de cálculo de la alfa de la ecuaciones de estado de SRK y PR alfa: Indica el método de cálculo de alfa 0 - Original 1 - Boston Mathias 2 - Twu 3 - Doridon Boston, J.F.; Mathias, P.M. Phase Equilibria in a Third-Generation Process Simulator. Proc. 2nd. Int. Conf. On Phase Equilibria and Fluid Properties in the Chemical Process Industries, Berlin, Germany 17.-21.3.1980, p. 823. """ if not alfa: Config=config.getMainWindowConfig() alfa=Config.getint("Thermo","Alfa") if alfa==2: #Función alfa de Twu et Alt. if EOS=="PR": if Tr>1: L0=0.401219 M0=4.963075 N0=-0.2 L1=0.024655 M1=1.248088 N1=-8. else: L0=0.125283 M0=0.911807 N0=1.948153 L1=0.511614 M1=0.784054 N1=2.812522 else: if Tr>1: L0=0.441411 M0=6.500018 N0=-0.2 L1=0.032580 M1=1.289098 N1=-8. else: L0=0.141599 M0=0.919422 N0=2.496441 L1=0.500315 M1=0.799457 N1=3.29179 alfa0=Tr**(N0*(M0-1))*exp(L0*(1-Tr**(N0*M0))) alfa1=Tr**(N1*(M1-1))*exp(L1*(1-Tr**(N1*M1))) alfa=alfa0+f_acent*(alfa1-alfa0) elif alfa==3: if f_acent<0.4: m=0.418+1.58*f_acent-0.58*f_acent**2 else: m=0.212+2.2*f_acent-0.831*f_acent**2 alfa=exp(m*(1-Tr)) elif alfa==1 and Tr>1: d=1.+m/2. c=1.-1./d alfa=exp(c*(1-Tr**d))**2 else: alfa=(1+m*(1-Tr**0.5))**2 return alfa
def evaluate_at(self, grid, component=None, prefactor=False): r"""Evaluate the Hagedorn wavepacket :math:`\Psi` at the given nodes :math:`\gamma`. :param grid: The grid :math:`\Gamma` containing the nodes :math:`\gamma`. :type grid: A class having a :py:meth:`get_nodes(...)` method. :param component: The index :math:`i` of a single component :math:`\Phi_i` to evaluate. (Defaults to ``None`` for evaluating all components.) :param prefactor: Whether to include a factor of :math:`\frac{1}{\sqrt{\det(Q)}}`. :type prefactor: Boolean, default is ``False``. :return: A list of arrays or a single array containing the values of the :math:`\Phi_i` at the nodes :math:`\gamma`. """ Pis = self.get_parameters(component=component, aslist=True) if component is not None: phase = exp(1.0j * Pis[component][4] / self._eps**2) values = phase * self.slim_recursion(grid, component, prefactor=prefactor) else: values = [] for component in range(self._number_components): # Note: This is very inefficient! We may evaluate the same basis functions multiple # times. But as long as we don't know that the basis shapes are true subsets # of the largest one, we can not evaluate just all functions in this # maximal set. # TODO: Find more efficient way to do this phase = exp(1.0j * Pis[component][4] / self._eps**2) values.append(phase * self.slim_recursion(grid, component, prefactor=prefactor)) return values
def f_Refl_Thin_Film_fit(Data): strain = Data[0] DW = Data[1] dat = Data[2] wl = dat[0] N = dat[2] phi = dat[3] t_l = dat[4] thB_S = dat[6] G = dat[7] F0 = dat[8] FH = dat[9] FmH = dat[10] th = dat[19] thB = thB_S - strain * tan(thB_S) # angle de Bragg dans chaque lamelle eta = 0 res = 0 n = 1 while (n <= N): g0 = sin(thB[n] - phi) # gamma 0 gH = -sin(thB[n] + phi) # gamma H b = g0 / gH T = pi * G * ((FH[n]*FmH[n])**0.5) * t_l * DW[n] / (wl * (abs(g0*gH)**0.5)) eta = (-b*(th-thB[n])*sin(2*thB_S) - 0.5*G*F0[n]*(1-b)) / ((abs(b)**0.5) * G * DW[n] * (FH[n]*FmH[n])**0.5) S1 = (res - eta + (eta*eta-1)**0.5)*exp(-1j*T*(eta*eta-1)**0.5) S2 = (res - eta - (eta*eta-1)**0.5)*exp(1j*T*(eta*eta-1)**0.5) res = (eta + ((eta*eta-1)**0.5) * ((S1+S2)/(S1-S2))) n += 1 return res
def _visco0(self, rho, T, fase=None, coef=False): Visco0 = lambda T: -0.135311743/log(T) + 1.00347841 + \ 1.20654649*log(T) - 0.149564551*log(T)**2 + 0.0125208416*log(T)**3 def ViscoE(T, rho): x = log(T) B = -47.5295259/x+87.6799309-42.0741589*x+8.33128289*x**2-0.589252385*x**3 C = 547.309267/x-904.870586+431.404928*x-81.4504854*x**2+5.37005733*x**3 D = -1684.39324/x+3331.08630-1632.19172*x+308.804413*x**2-20.2936367*x**3 return rho.gcc*B+rho.gcc**2*C+rho.gcc**3*D if T < 100: # Section 4.2.1 for 3.5 < T < 100 no = Visco0(T) ne = ViscoE(T, rho) n = exp(no+ne) else: # Section 4.2.1 for T > 100 no = 196*T**0.71938*exp(12.451/T-295.67/T**2-4.1249) ne = exp(Visco0(T)+ViscoE(T, rho))-exp(Visco0(T)+ViscoE(T, unidades.Density(0))) n = no+ne if coef: return ne else: return unidades.Viscosity(n*1e-6, "P")
def _mur(self, rho, T, fase): # Modified friction theory for residual viscosity contribution Gamma = self.Tc/T psi1 = exp(Gamma) # Eq 15 psi2 = exp(Gamma**2) # Eq 16 a = [68.9659e-6, -22.0494e-6, -42.6126e-6] b = [153.406e-6, 8.45198e-6, -113.967e-6] A = [0.78238e-9, -0.64717e-9, 1.39066e-9] B = [-9.75792e-9, -3.19303e-9, 12.4263e-9] ka = (a[0] + a[1]*psi1 + a[2]*psi2) * Gamma # Eq 11 kr = (b[0] + b[1]*psi1 + b[2]*psi2) * Gamma # Eq 12 kaa = (A[0] + A[1]*psi1 + A[2]*psi2) * Gamma # Eq 13 krr = (B[0] + B[1]*psi1 + B[2]*psi2) * Gamma # Eq 14 # All parameteres has pressure units of bar Patt = -fase.IntP.bar Prep = T*fase.dpdT_rho.barK Pid = rho*self.R*self.T/1e5 delPr = Prep-Pid # Eq 5 mur = kr*delPr + ka*Patt + krr*Prep**2 + kaa*Patt**2 return mur*1e3
def _visco3(self, rho, T, fase=None): # Zero-Density viscosity muo = self._Visco0(T) # Gas-phase viscosity # Table 8 ti = [1, 2, 7] ei = [3.6350734e-3, 7.209997e-5, 3.00306e-20] mug = 0 for t, e in zip(ti, ei): mug += e*rho**t # Eq 67 # Liquid-phase viscosity B = 18.56+0.014*T # Eq 71 Vo = 7.41e-4-3.3e-7*T # Eq 72 mul = 1/B/(1/rho-Vo) # Eq 70 # Critical enhancement Not implemented muc = 0 # Eq 74, parameters rhos = 467.689 Ts = 302 Z = 1 # Eq 76 mu = muo + mug/(1+exp(-Z*(T-Ts))) + \ mug/(1+exp(Z*(T-Ts)))/(1+exp(Z*(rho-rhos))) + \ (mul-muo)/(1+exp(Z*(T-Ts)))/(1+exp(-Z*(rho-rhos))) + muc return unidades.Viscosity(mu, "muPas")
def fmin_lm_log_params(m, params, *args, **kwargs): """ Minimize the cost of a model using Levenberg-Marquadt in terms of log parameters. The *args and **kwargs represent additional parmeters that will be passed to the optimization algorithm. For your convenience, the docstring of that function is appended below: """ Nres = len(m.residuals) def func(log_params): try: return m.res_log_params(log_params) except Utility.SloppyCellException: logger.warn('Exception in cost evaluation. Cost set to inf.') return [scipy.inf] * Nres jac = lambda lp: scipy.asarray(m.jacobian_log_params_sens(lp)) sln = lmopt.fmin_lm(f=func, x0=scipy.log(params), fprime=jac, *args, **kwargs) if isinstance(params, KeyedList): pout = params.copy() pout.update(scipy.exp(sln)) return pout else: return scipy.exp(sln)
def _ThCondCritical(self, rho, T, fase): # Custom Critical enhancement # The paper use a diferent rhoc value to the EoS rhoc = 235 t = abs(T-405.4)/405.4 dPT = 1e5*(2.18-0.12/exp(17.8*t)) nb = 1e-5*(2.6+1.6*t) DL = 1.2*Boltzmann*T**2/6/pi/nb/(1.34e-10/t**0.63*(1+t**0.5)) * \ dPT**2 * 0.423e-8/t**1.24*(1+t**0.5/0.7) # Add correction for entire range of temperature, Eq 10 DL *= exp(-36*t**2) X = 0.61*rhoc+16.5*log(t) if rho > 0.6*rhoc: # Eq 11 DL *= X**2/(X**2+(rho-0.96*rhoc)**2) else: # Eq 14 DL = X**2/(X**2+(0.6*rhoc-0.96*rhoc)**2) DL *= rho**2/(0.6*rhoc)**2 return DL
def computeOpenMaxProbability(openmax_fc8, openmax_score_u): """ Convert the scores in probability value using openmax Input: --------------- openmax_fc8 : modified FC8 layer from Weibull based computation openmax_score_u : degree Output: --------------- modified_scores : probability values modified using OpenMax framework, by incorporating degree of uncertainity/openness for a given class """ prob_scores, prob_unknowns = [], [] for channel in range(NCHANNELS): channel_scores, channel_unknowns = [], [] for category in range(NCLASSES): channel_scores += [sp.exp(openmax_fc8[channel, category])] total_denominator = sp.sum(sp.exp(openmax_fc8[channel, :])) + sp.exp(sp.sum(openmax_score_u[channel, :])) prob_scores += [channel_scores/total_denominator ] prob_unknowns += [sp.exp(sp.sum(openmax_score_u[channel, :]))/total_denominator] prob_scores = sp.asarray(prob_scores) prob_unknowns = sp.asarray(prob_unknowns) scores = sp.mean(prob_scores, axis = 0) unknowns = sp.mean(prob_unknowns, axis=0) modified_scores = scores.tolist() + [unknowns] assert len(modified_scores) == 1001 return modified_scores
def superimpose (cavityD,cavityU,par1,par2): if (par2 == 0) : return (sp.cos(par1*sp.pi)*cavityD[:] + 1j*sp.sin(par1*sp.pi)*cavityU[:])*sp.exp(-1j*par1*sp.pi) elif (par2 == 1) : return sp.exp(-1j*par1*sp.pi)*cavityD else : return cavityD
def _thermo0(self, rho, T, fase): GT = [-2.903423528e5, 4.680624952e5, -1.8954783215e5, -4.8262235392e3, 2.243409372e4, -6.6206354818e3, 8.9937717078e2, -6.0559143718e1, 1.6370306422] lo = 0 for i in range(-3, 6): lo += GT[i+3]*T**(i/3.) tita = (rho.gcc-0.221)/0.221 j = [0, -1.304503323e1, 1.8214616599e1, 9.903022496e3, 7.420521631e2, -3.0083271933e-1, 9.6456068829e1, 1.350256962e4] l1 = exp(j[1]+j[4]/T)*(exp(rho.gcc**0.1*(j[2]+j[3]/self.T**1.5)+tita*rho.gcc**0.5*(j[5]+j[6]/T+j[7]/T**2))-1.) lc = 0 # FIXME: no sale # deltarho=(self.rho/self.M-0.221)/0.221 # deltaT=(self.T-282.34)/282.34 # xkt=(1.0/self.rho/self.M/self.derivative("P", "rho", "T")*1e3)**0.5 # b=abs(deltarho)/abs(deltaT)**1.19 # xts=(self.rho/self.M)**2*xkt*5.039/.221**2 # g=xts*abs(deltaT)**1.19 # xi=0.69/(b**2*5.039/g/Boltzmann/282.34)**0.5 # f=exp(-18.66*deltaT**2-4.25*deltarho**4) # c=(self.M/self.rho.gcc/Avogadro/Boltzmann/self.T)**0.5 # lc=c*Boltzmann*self.T**2/6.0/pi/self.mu.muPas/xi*self.dpdT**2*self.kappa**0.5*f # print lo, l1 return unidades.ThermalConductivity(lo+l1+lc, "mWmK")
def gamma(xAg): rA=3.19;rB=2.11 qA=2.4;qB=1.97 qAdash=2.4;qBdash=0.89 aAB=242.53;aBA=-75.13 p11=(xAg*rA/(xAg*rA+xBg*rB)) p12=(xBg*rB/(xAg*rA+xBg*rB)) p1=scipy.array([p11,p12]) t11=(xAg*qA/(xAg*qA+xBg*qB)) t12=(xBg*qB/(xAg*qA+xBg*qB)) t1=scipy.array([t11,t12]) t21=(xAg*qAdash/(xAg*qAdash+xBg*qBdash)) t22=(xBg*qBdash/(xAg*qAdash+xBg*qBdash)) t2=scipy.array([t21,t22]) tAB=scipy.exp(-aAB/Tg) tBA=scipy.exp(-aBA/Tg) t=scipy.array([tAB,tBA]) z=10 l11=((z/2)*(rA-qA))-(rA-1) l12=((z/2)*(rB-qB))-(rB-1) l1=scipy.array([l11,l12]) gamma1=scipy.exp((scipy.log(p1[0]/xAg))+(z*qA*scipy.log(t1[0]/p1[0])/2)+(p1[1]*(l1[0]-(rA*l1[1]/rB)))-(qAdash*scipy.log(t2[0]+t2[1]*t[1]))+(t2[1]*qAdash*((t[1]/(t2[0]+t2[1]*t[1]))-(t[0]/(t2[1]+t2[0]*t[0]))))) gamma2=scipy.exp((scipy.log(p1[1]/xBg))+(z*qB*scipy.log(t1[1]/p1[1])/2)+(p1[0]*(l1[1]-(rB*l1[0]/rA)))-(qBdash*scipy.log(t2[1]+t2[0]*t[0]))+(t2[0]*qBdash*((t[0]/(t2[1]+t2[0]*t[0]))-(t[1]/(t2[0]+t2[1]*t[1]))))) gamma=scipy.array([gamma1,gamma2]) return gamma
def test_time_integration(): dt = 0.01 tmax = 1 def check_time_integration(res, y0, exact): ts, ys = time_integrate(res, y0, dt, tmax) exacts = [exact(t) for t in ts] print(ts, ys, exacts) utils.assert_list_almost_equal(ys, exacts, 1e-3) tests = [ (lambda t, y, dy: y - dy, 1.0, lambda t: array(exp(t))), (lambda t, y, dy: y + dy, 1.0, lambda t: array(exp(-t))), ( lambda t, y, dy: array([-0.1 * sin(t), y[1]]) - dy, array([0.1 * cos(0.0), exp(0.0)]), lambda t: array([0.1 * cos(t), exp(t)]), ), ] for r, y0, exact in tests: yield check_time_integration, r, y0, exact
def time_plot(m=10, c=1, k=100, x0=1, v0=-1, max_time=100): t, x, v, zeta, omega, omega_d, A = free_response( m, c, k, x0, v0, max_time) fig = plt.figure() fig.suptitle('Displacement vs Time') ax = fig.add_subplot(111) ax.set_xlabel('Time') ax.set_ylabel('Displacement') ax.grid('on') ax.plot(t, x) if zeta < 1: ax.plot(t, A * sp.exp(-zeta * omega * t), '--', t, -A * sp.exp(-zeta * omega * t), '--g', linewidth=1) tmin, tmax, xmin, xmax = ax.axis() ax.text(.75 * tmax, .95 * (xmax - xmin) + xmin, '$\omega$ = %0.2f rad/sec' % (omega)) ax.text(.75 * tmax, .90 * (xmax - xmin) + xmin, '$\zeta$ = %0.2f' % (zeta)) ax.text(.75 * tmax, .85 * (xmax - xmin) + xmin, '$\omega_d$ = %0.2f rad/sec' % (omega_d)) else: tmin, tmax, xmin, xmax = ax.axis() ax.text(.75 * tmax, .95 * (xmax - xmin) + xmin, '$\zeta$ = %0.2f' % (zeta)) ax.text(.75 * tmax, .90 * (xmax - xmin) + xmin, '$\lambda_1$ = %0.2f' % (zeta * omega - omega * (zeta ** 2 - 1))) ax.text(.75 * tmax, .85 * (xmax - xmin) + xmin, '$\lambda_2$ = %0.2f' % (zeta * omega + omega * (zeta ** 2 - 1)))
def molar_conc(mole_fraction,ihenry_k,temp,excess_air,altitude_meters,salinity): '''Converts mole fraction to moles per liter water.''' barometric_pressure = exp(-(altitude_meters/8300)) vapor_pressure_h2o = exp(24.4543 - 67.4509*(100/temp) - 4.8489*log(temp/100) - 0.000544*salinity) return (ihenry_k*mole_fraction*(barometric_pressure - vapor_pressure_h2o) + (excess_air*mole_fraction)/22414)
def objective(pars,Z,ycovar): """The objective function""" bcost= pars[0] t= pars[1] Pb= pars[2] Xb= pars[3] Yb= pars[4] Zb= sc.array([Xb,Yb]) Vb1= sc.exp(pars[5]) Vb2= sc.exp(pars[6]) corr= pars[7] V= sc.array([[Vb1,sc.sqrt(Vb1*Vb2)*corr],[sc.sqrt(Vb1*Vb2)*corr,Vb2]]) v= sc.array([-sc.sin(t),sc.cos(t)]) if Pb < 0. or Pb > 1.: return -sc.finfo(sc.dtype(sc.float64)).max if corr < -1. or corr > 1.: return -sc.finfo(sc.dtype(sc.float64)).max delta= sc.dot(v,Z.T)-bcost sigma2= sc.dot(v,sc.dot(ycovar,v)) ndata= Z.shape[0] detVycovar= sc.zeros(ndata) deltaOUT= sc.zeros(ndata) for ii in range(ndata): detVycovar[ii]= m.sqrt(linalg.det(V+ycovar[:,ii,:])) deltaOUT[ii]= sc.dot(Z[ii,:]-Zb,sc.dot(linalg.inv(V+ycovar[:,ii,:]),Z[ii,:]-Zb)) return sc.sum(sc.log((1.-Pb)/sc.sqrt(2.*m.pi*sigma2)* sc.exp(-0.5*delta**2./sigma2) +Pb/2./m.pi/detVycovar *sc.exp(-0.5*deltaOUT)))
def diff_gauss_kern(size = 2, sigmA = 0.9, sigmB = 1., ratio = 1.): """ Returns a normalized 2D kernel of a gaussian difference """ x, y = sp.mgrid[-size:size+1, -size:size+1] sigmA = float(sigmA**2) sigmB = float(sigmB**2) g = sp.exp( -(x**2 + y**2) / sigmA ) - ratio * sp.exp( -(x**2 + y**2) / sigmB ) return g / abs(g.sum())
def dbexpl(p): t=arange(0,100,20.) #if (p['par1']) < 0.5: if (p['par1']+p['par3']) < 0.25: asdf y = (p['par1']*exp(-p['par2']*t) + p['par3']*exp(-p['par4']*t)) return y
def alpha_m(V): return 0.1 * (V + 40.0) / (1.0 - sp.exp(-(V + 40.0) / 10.0)) def beta_m(V): return 4.0 * sp.exp(-(V + 65.0) / 18.0)
def daisy(img, step=4, radius=15, rings=3, histograms=8, orientations=8, normalization='l1', sigmas=None, ring_radii=None, visualize=False): '''Extract DAISY feature descriptors densely for the given image. DAISY is a feature descriptor similar to SIFT formulated in a way that allows for fast dense extraction. Typically, this is practical for bag-of-features image representations. The implementation follows Tola et al. [1]_ but deviate on the following points: * Histogram bin contribution are smoothed with a circular Gaussian window over the tonal range (the angular range). * The sigma values of the spatial Gaussian smoothing in this code do not match the sigma values in the original code by Tola et al. [2]_. In their code, spatial smoothing is applied to both the input image and the center histogram. However, this smoothing is not documented in [1]_ and, therefore, it is omitted. Parameters ---------- img : (M, N) array Input image (greyscale). step : int, optional Distance between descriptor sampling points. radius : int, optional Radius (in pixels) of the outermost ring. rings : int, optional Number of rings. histograms : int, optional Number of histograms sampled per ring. orientations : int, optional Number of orientations (bins) per histogram. normalization : [ 'l1' | 'l2' | 'daisy' | 'off' ], optional How to normalize the descriptors * 'l1': L1-normalization of each descriptor. * 'l2': L2-normalization of each descriptor. * 'daisy': L2-normalization of individual histograms. * 'off': Disable normalization. sigmas : 1D array of float, optional Standard deviation of spatial Gaussian smoothing for the center histogram and for each ring of histograms. The array of sigmas should be sorted from the center and out. I.e. the first sigma value defines the spatial smoothing of the center histogram and the last sigma value defines the spatial smoothing of the outermost ring. Specifying sigmas overrides the following parameter. ``rings = len(sigmas) - 1`` ring_radii : 1D array of int, optional Radius (in pixels) for each ring. Specifying ring_radii overrides the following two parameters. ``rings = len(ring_radii)`` ``radius = ring_radii[-1]`` If both sigmas and ring_radii are given, they must satisfy the following predicate since no radius is needed for the center histogram. ``len(ring_radii) == len(sigmas) + 1`` visualize : bool, optional Generate a visualization of the DAISY descriptors Returns ------- descs : array Grid of DAISY descriptors for the given image as an array dimensionality (P, Q, R) where ``P = ceil((M - radius*2) / step)`` ``Q = ceil((N - radius*2) / step)`` ``R = (rings * histograms + 1) * orientations`` descs_img : (M, N, 3) array (only if visualize==True) Visualization of the DAISY descriptors. References ---------- .. [1] Tola et al. "Daisy: An efficient dense descriptor applied to wide- baseline stereo." Pattern Analysis and Machine Intelligence, IEEE Transactions on 32.5 (2010): 815-830. .. [2] http://cvlab.epfl.ch/software/daisy ''' assert_nD(img, 2, 'img') img = img_as_float(img) # Validate parameters. if sigmas is not None and ring_radii is not None \ and len(sigmas) - 1 != len(ring_radii): raise ValueError('`len(sigmas)-1 != len(ring_radii)`') if ring_radii is not None: rings = len(ring_radii) radius = ring_radii[-1] if sigmas is not None: rings = len(sigmas) - 1 if sigmas is None: sigmas = [radius * (i + 1) / float(2 * rings) for i in range(rings)] if ring_radii is None: ring_radii = [radius * (i + 1) / float(rings) for i in range(rings)] if normalization not in ['l1', 'l2', 'daisy', 'off']: raise ValueError('Invalid normalization method.') # Compute image derivatives. dx = np.zeros(img.shape) dy = np.zeros(img.shape) dx[:, :-1] = np.diff(img, n=1, axis=1) dy[:-1, :] = np.diff(img, n=1, axis=0) # Compute gradient orientation and magnitude and their contribution # to the histograms. grad_mag = sqrt(dx**2 + dy**2) grad_ori = arctan2(dy, dx) orientation_kappa = orientations / pi orientation_angles = [ 2 * o * pi / orientations - pi for o in range(orientations) ] hist = np.empty((orientations, ) + img.shape, dtype=float) for i, o in enumerate(orientation_angles): # Weigh bin contribution by the circular normal distribution hist[i, :, :] = exp(orientation_kappa * cos(grad_ori - o)) # Weigh bin contribution by the gradient magnitude hist[i, :, :] = np.multiply(hist[i, :, :], grad_mag) # Smooth orientation histograms for the center and all rings. sigmas = [sigmas[0]] + sigmas hist_smooth = np.empty((rings + 1, ) + hist.shape, dtype=float) for i in range(rings + 1): for j in range(orientations): hist_smooth[i, j, :, :] = gaussian_filter(hist[j, :, :], sigma=sigmas[i]) # Assemble descriptor grid. theta = [2 * pi * j / histograms for j in range(histograms)] desc_dims = (rings * histograms + 1) * orientations descs = np.empty( (desc_dims, img.shape[0] - 2 * radius, img.shape[1] - 2 * radius)) descs[:orientations, :, :] = hist_smooth[0, :, radius:-radius, radius:-radius] idx = orientations for i in range(rings): for j in range(histograms): y_min = radius + int(round(ring_radii[i] * sin(theta[j]))) y_max = descs.shape[1] + y_min x_min = radius + int(round(ring_radii[i] * cos(theta[j]))) x_max = descs.shape[2] + x_min descs[idx:idx + orientations, :, :] = hist_smooth[i + 1, :, y_min:y_max, x_min:x_max] idx += orientations descs = descs[:, ::step, ::step] descs = descs.swapaxes(0, 1).swapaxes(1, 2) # Normalize descriptors. if normalization != 'off': descs += 1e-10 if normalization == 'l1': descs /= np.sum(descs, axis=2)[:, :, np.newaxis] elif normalization == 'l2': descs /= sqrt(np.sum(descs**2, axis=2))[:, :, np.newaxis] elif normalization == 'daisy': for i in range(0, desc_dims, orientations): norms = sqrt(np.sum(descs[:, :, i:i + orientations]**2, axis=2)) descs[:, :, i:i + orientations] /= norms[:, :, np.newaxis] if visualize: descs_img = gray2rgb(img) for i in range(descs.shape[0]): for j in range(descs.shape[1]): # Draw center histogram sigma color = [1, 0, 0] desc_y = i * step + radius desc_x = j * step + radius rows, cols, val = draw.circle_perimeter_aa( desc_y, desc_x, int(sigmas[0])) draw.set_color(descs_img, (rows, cols), color, alpha=val) max_bin = np.max(descs[i, j, :]) for o_num, o in enumerate(orientation_angles): # Draw center histogram bins bin_size = descs[i, j, o_num] / max_bin dy = sigmas[0] * bin_size * sin(o) dx = sigmas[0] * bin_size * cos(o) rows, cols, val = draw.line_aa(desc_y, desc_x, int(desc_y + dy), int(desc_x + dx)) draw.set_color(descs_img, (rows, cols), color, alpha=val) for r_num, r in enumerate(ring_radii): color_offset = float(1 + r_num) / rings color = (1 - color_offset, 1, color_offset) for t_num, t in enumerate(theta): # Draw ring histogram sigmas hist_y = desc_y + int(round(r * sin(t))) hist_x = desc_x + int(round(r * cos(t))) rows, cols, val = draw.circle_perimeter_aa( hist_y, hist_x, int(sigmas[r_num + 1])) draw.set_color(descs_img, (rows, cols), color, alpha=val) for o_num, o in enumerate(orientation_angles): # Draw histogram bins bin_size = descs[i, j, orientations + r_num * histograms * orientations + t_num * orientations + o_num] bin_size /= max_bin dy = sigmas[r_num + 1] * bin_size * sin(o) dx = sigmas[r_num + 1] * bin_size * cos(o) rows, cols, val = draw.line_aa( hist_y, hist_x, int(hist_y + dy), int(hist_x + dx)) draw.set_color(descs_img, (rows, cols), color, alpha=val) return descs, descs_img else: return descs
def beta_n(V): return 0.125 * sp.exp(-(V + 65) / 80.0) # Membrane currents (in uA/cm^2) # Sodium (Na = element name) def I_Na(V, m, h): return g_Na * m ** 3 * h * (V - E_Na)
def alpha_n(V): return 0.01 * (V + 55.0) / (1.0 - sp.exp(-(V + 55.0) / 10.0)) def beta_n(V): return 0.125 * sp.exp(-(V + 65) / 80.0)
def beta_h(V): return 1.0 / (1.0 + sp.exp(-(V + 35.0) / 10.0)) def alpha_n(V): return 0.01 * (V + 55.0) / (1.0 - sp.exp(-(V + 55.0) / 10.0))
def alpha_h(V): return 0.07 * sp.exp(-(V + 65.0) / 20.0) def beta_h(V): return 1.0 / (1.0 + sp.exp(-(V + 35.0) / 10.0))
def beta_m(V): return 4.0 * sp.exp(-(V + 65.0) / 18.0) def alpha_h(V): return 0.07 * sp.exp(-(V + 65.0) / 20.0)
def __init__(self, T, P, mezcla): self.T=unidades.Temperature(T) self.P=unidades.Pressure(P, "atm") self.componente=mezcla.componente self.fraccion=mezcla.fraccion zci=[] Vci=[] for componente in self.componente: zci.append(0.2905-0.085*componente.f_acent) Vci.append(zci[-1]*R_atml*componente.Tc/componente.Pc.atm) sumaV1=sumaV2=sumaV3=sumaT1=sumaT2=sumaT3=0 for i, componente in enumerate(self.componente): sumaV1+=self.fraccion[i]*Vci[i] sumaV2+=self.fraccion[i]*Vci[i]**(2./3) sumaV3+=self.fraccion[i]*Vci[i]**(1./3) sumaT1+=self.fraccion[i]*Vci[i]*componente.Tc sumaT2+=self.fraccion[i]*Vci[i]**(2./3)*componente.Tc**(1./2) sumaT3+=self.fraccion[i]*Vci[i]**(1./3)*componente.Tc**(1./2) Vmc=(sumaV1+3*sumaV2*sumaV3)/4. Tmc=(sumaT1+3*sumaT2*sumaT3)/4/Vmc Pmc=(0.2905-0.085*mezcla.f_acent)*R_atml*Tmc/Vmc Tr=T/Tmc Pr=P/Pmc b1=0.1181193, 0.2026579 b2=0.265728, 0.331511 b3=0.154790, 0.027655 b4=0.030323, 0.203488 c1=0.0236744, 0.0313385 c2=0.0186984, 0.0503618 c3=0.0, 0.016901 c4=0.042724, 0.041577 d1=0.155488e-4, 0.48736e-4 d2=0.623689e-4, 0.0740336e-4 beta=0.65392, 1.226 gamma=0.060167, 0.03754 Bo=b1[0]-b2[0]/Tr-b3[0]/Tr**2-b4[0]/Tr**3 Co=c1[0]-c2[0]/Tr+c3[0]/Tr**3 Do=d1[0]+d2[0]/Tr Vr=lambda V: 1+Bo/V+Co/V**2+Do/V**5+c4[0]/Tr**3/V**2*(beta[0]+gamma[0]/V**2)*exp(-gamma[0]/V**2)-Pr*V/Tr Bh=b1[1]-b2[1]/Tr-b3[1]/Tr**2-b4[1]/Tr**3 Ch=c1[1]-c2[1]/Tr+c3[1]/Tr**3 Dh=d1[1]+d2[1]/Tr Vrh=lambda V: 1+Bh/V+Ch/V**2+Dh/V**5+c4[1]/Tr**3/V**2*(beta[1]+gamma[1]/V**2)*exp(-gamma[1]/V**2)-Pr*V/Tr #Usamos SRK para estimar los volumenes de ambas fases usados como valores iniciales en la iteración srk=SRK(T, P, mezcla) Z_srk=srk.Z Vgo=Z_srk[0]*R_atml*T/P Vlo=Z_srk[1]*R_atml*T/P vr0v=fsolve(Vr, Vgo) vrhv=fsolve(Vrh, Vgo) vr0l=fsolve(Vr, Vlo) vrhl=fsolve(Vrh, Vlo) z0l=Pr*vr0l/Tr zhl=Pr*vrhl/Tr z0v=Pr*vr0v/Tr zhv=Pr*vrhv/Tr self.Z=r_[z0v+mezcla.f_acent/factor_acentrico_octano*(zhv-z0v), z0l+mezcla.f_acent/factor_acentrico_octano*(zhl-z0l)] self.V=self.Z*R_atml*self.T/self.P.atm #mol/l E=c4[0]/(2*Tr**3*gamma[0])*(beta[0]+1-(beta[0]+1+gamma[0]/vr0v**2)*exp(-gamma[0]/vr0v**2)) H0=-Tr*(z0v-1-(b2[0]+2*b3[0]/Tr+3*b4[0]/Tr**2)/Tr/vr0v-c2[0]/Tr/2/vr0v**2+d2[0]/5/Tr/vr0v**5+3*E) E=c4[1]/(2*Tr**3*gamma[1])*(beta[1]+1-(beta[1]+1+gamma[1]/vrhv**2)*exp(-gamma[1]/vrhv**2)) Hh=-Tr*(zhv-1-(b2[1]+2*b3[1]/Tr+3*b4[1]/Tr**2)/Tr/vrhv-(c2[1]-3*c3[1]/Tr**2)/Tr/2/vrhv**2+d2[1]/5/Tr/vrhv**5+3*E) Hv=H0+mezcla.f_acent/factor_acentrico_octano*(Hh-H0) E=c4[0]/(2*Tr**3*gamma[0])*(beta[0]+1-(beta[0]+1+gamma[0]/vr0l**2)*exp(-gamma[0]/vr0l**2)) H0=-Tr*(z0l-1-(b2[0]+2*b3[0]/Tr+3*b4[0]/Tr**2)/Tr/vr0l-c2[0]/Tr/2/vr0l**2+d2[0]/5/Tr/vr0l**5+3*E) E=c4[1]/(2*Tr**3*gamma[1])*(beta[1]+1-(beta[1]+1+gamma[1]/vrhl**2)*exp(-gamma[1]/vrhl**2)) Hh=-Tr*(zhl-1-(b2[1]+2*b3[1]/Tr+3*b4[1]/Tr**2)/Tr/vrhl-(c2[1]-3*c3[1]/Tr**2)/Tr/2/vrhl**2+d2[1]/5/Tr/vrhl**5+3*E) Hl=H0+mezcla.f_acent/factor_acentrico_octano*(Hh-H0) self.H_exc=r_[Hv, Hl] self.x, self.xi, self.yi, self.Ki=srk._Flash()
def B_IglesiasSilva(T, Tc, Pc, Vc, w, D): r"""Calculate the 2nd virial coefficient using the Iglesias-Silva Hall correlation .. math:: \frac{B}{b_o} = \left(\frac{T_B}{T}\right)^{0.2} \left[1-\left(\frac{T_B}{T}\right)^{0.8}\right] \left[\frac{B_c} {b_o\left(\left(T_B/T_C\right)^{0.2}-\left(T_B/T_C\right)\right)} \right]^{\left(T_c/T\right)^n} .. math:: \frac{B_C}{V_C} = -1.1747 - 0.3668\omega - 0.00061\mu_R .. math:: n = 1.4187 + 1.2058\omega .. math:: \frac{b_o}{V_C} = 0.1368 - 0.4791\omega + 13.81\left(T_B/T_C\right)^2 \exp\left(-1.95T_B/T_C\right) .. math:: \frac{T_B}{T_C} = 2.0525 + 0.6428\exp\left(-3.6167\omega\right) Parameters ---------- T : float Temperature [K] Tc : float Critical temperature [K] Pc : float Critical pressure, [Pa] Vc : float Critical specific volume, [m³/mol] w : float Acentric factor [-] D : float dipole moment [debye] Returns ------- B : float Second virial coefficient [m³/mol] B1 : float T(∂B/∂T) [m³/mol] B2 : float T²(∂²B/∂T²) [m³/mol] Examples -------- Selected date from Table 2, pag 74 for neon >>> from lib.mEoS import Ne >>> Vc = Ne.M/Ne.rhoc >>> D = Ne.momentoDipolar.Debye >>> "%0.4f" % B_IglesiasSilva(262, Ne.Tc, Ne.Pc, Vc, Ne.f_acent, D)[0] '0.0102' References ---------- [6]_ Iglesias-Silva, G.A., Hall K.R. An Equation for Prediction and/or Correlation of Second Virial Coefficients. Ind. Eng. Chem. Res. 40(8) (2001) 1968-1974 """ # Reduced dipole moment muR = 1e5 * D**2 * Pc / 101325 / Tc**2 TB = Tc * (2.0525 + 0.6428 * exp(-3.6167 * w)) # Eq 19 n = 1.4187 + 1.2058 * w # Eq 14 bo = Vc * (0.1368 - 0.4791 * w + 13.81 * (TB / Tc)**2 * exp(-1.95 * TB / Tc)) # Eq 15 Bc = Vc * (-1.1747 - 0.3668 * w - 0.00061 * muR) def f(T): # Eq 12 return bo*(TB/T)**.2 * (1-(TB/T)**.8) * \ (Bc/bo/((TB/Tc)**.2-TB/Tc))**((Tc/T)**n) B = f(T) B1 = derivative(f, T, n=1) B2 = derivative(f, T, n=2) return B, B1, B2
def reduce_result(self, loss_cv, k_values, delta_values, strategy, output_prefix, best_delta_for_k, label="mse", create_pdf=True): """ turn cross-validation results into results """ #self.run_once() #Don't need and saves time # average over splits average_loss = np.array(loss_cv).mean(axis=0) #average_loss = np.vstack(loss_cv).mean(axis=0) best_ln_delta_interp, best_obj_interp, best_delta_interp = (None, None, None) # reconstruct results if strategy == "lmm_full_cv": # save cv scores if output_prefix != None: split_idx = ["mean"] * len(k_values) for idx in xrange(len(loss_cv)): split_idx.extend([idx] * loss_cv[idx].shape[0]) stacked_result = np.vstack(loss_cv) stacked_result = np.vstack((average_loss, stacked_result)) out_fn = output_prefix + "_" + label + ".csv" cols = pd.MultiIndex.from_arrays( [split_idx, k_values * (self.num_folds + 1)], names=['split_id', 'k_value']) df = pd.DataFrame(stacked_result, columns=delta_values, index=cols) util.create_directory_if_necessary(out_fn) df.to_csv(out_fn) # make sure delta is not at the boundary for any k assert average_loss.shape[0] == len(k_values) for k_idx in xrange(average_loss.shape[0]): tmp_idx = np.argmin(average_loss[k_idx]) if tmp_idx == 0 or tmp_idx == len(delta_values) - 1: logging.warn( "(select by %s): ln_delta for k=%i is at the boundary (idx=%i) of defined delta grid" % (label, k_values[k_idx], tmp_idx)) best_k_idx, best_delta_idx = np.unravel_index( average_loss.argmin(), average_loss.shape) best_k, best_delta = k_values[best_k_idx], delta_values[ best_delta_idx] best_obj = average_loss[best_k_idx, best_delta_idx] best_ln_delta = np.log(best_delta) best_str = "best: k=%i, ln_d=%.1f, obj=%.2f" % ( best_k, best_ln_delta, best_obj) # fit parabola to 3 points in logspace if self.interpolate_delta: if best_delta_idx != 0 and best_delta_idx != len( delta_values) - 1: log_deltas = [ np.log(d) for d in delta_values[best_delta_idx - 1:best_delta_idx + 2] ] error_3pt = average_loss[best_k_idx, best_delta_idx - 1:best_delta_idx + 2] best_ln_delta_interp, best_obj_interp = self.fit_parabola( log_deltas, error_3pt, output_prefix=None) best_delta_interp = sp.exp(best_ln_delta_interp) best_str += ", ln_d_interp=%.2f" % (best_ln_delta_interp) logging.info("best interpolated ln_delta {0}".format( best_ln_delta_interp)) else: logging.warn( "(select by %s): best ln_delta for all k is at the boundary (idx=%i) of search grid, please consider a larger grid" % (label, best_delta_idx)) #if output_prefix != None: #create a size-zero file so that the cluster will aways have something to copy #plot_fn=output_prefix+"_parabola.pdf" #util.create_directory_if_necessary(plot_fn) #open(plot_fn, "w").close() # save cv scores if create_pdf and (output_prefix != None): # visualize results import matplotlib matplotlib.use( 'Agg', warn=False ) #This lets it work even on machines without graphics displays import pylab pylab.figure() ax = pylab.subplot(111) try: for delta_idx, delta in enumerate(delta_values): ln_delta = sp.log(delta) ax.semilogx(k_values, average_loss[:, delta_idx], "-x", label="ln_d=%.1f" % (ln_delta)) # Shrink current axis by 20% box = ax.get_position() ax.set_position( [box.x0, box.y0, box.width * 0.8, box.height]) #TODO: this assumes the k_values are sorted: pylab.ylim(ymax=average_loss[0].max() + abs(average_loss[0].max()) * 0.05) if k_values[0] != 0: logging.warn("Expect the first k value to be zero" ) #!!move this change earlier for i in xrange(len(k_values)): if k_values[i] == 0: ax.axhline(average_loss[i].max(), color='green') mymin = average_loss.min() mymax = average_loss[i].max() diff = (mymax - mymin) * 0.05 pylab.ylim([mymin - diff, mymax + diff]) # Put a legend to the right of the current axis ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) pylab.title(best_str) pylab.ylabel(label) pylab.xlabel("k") pylab.grid(True) #pylab.show() except: pass xval_fn = output_prefix + "_xval_%s.pdf" % label util.create_directory_if_necessary(xval_fn) pylab.savefig(xval_fn) elif strategy == "insample_cv": best_k_idx = average_loss.argmin() best_k = k_values[best_k_idx] best_obj = average_loss[best_k_idx] # check if unique over folds delta_array = np.array(best_delta_for_k) unique_deltas_for_k = set(delta_array[:, best_k_idx]) if len(unique_deltas_for_k) > 1: logging.warn("ambiguous choice of delta for k: {0} {1}".format( best_k, unique_deltas_for_k)) best_delta = np.median(delta_array[:, best_k_idx]) best_str = "best k=%i, best delta=%.2f" % (best_k, best_delta) logging.info(best_str) if output_prefix != None: split_idx = ["mean"] * len(k_values) for idx in xrange(len(loss_cv)): split_idx.extend([idx] * loss_cv[idx].shape[0]) stacked_result = np.vstack(loss_cv) stacked_result = np.vstack((average_loss, stacked_result)) out_fn = output_prefix + "_" + label + ".csv" cols = pd.MultiIndex.from_arrays( [split_idx, k_values * (self.num_folds + 1)], names=['split_id', 'k_value']) print "Christoph: bug, this is a quick fix that runs but may write out wrong results" df = pd.DataFrame(stacked_result.flatten()[:, None], columns=[label], index=cols) util.create_directory_if_necessary(out_fn) df.to_csv(out_fn) if create_pdf and (output_prefix != None): # visualize results import matplotlib matplotlib.use( 'Agg', warn=False ) #This lets it work even on machines without graphics displays import pylab pylab.figure() ax = pylab.subplot(111) try: ax.semilogx(k_values, average_loss, "-x", label="loo") # shrink current axis by 20% box = ax.get_position() #TODO: this assumes the k_values are sorted: ax.set_position( [box.x0, box.y0, box.width * 0.8, box.height]) pylab.ylim(ymax=average_loss[0].max() + abs(average_loss[0].max()) * 0.05) if k_values[0] != 0: logging.warn("Expect the first k value to be zero" ) #!!move this change earlier for i in xrange(len(k_values)): if k_values[i] == 0: ax.axhline(average_loss[i].max(), color='green') mymin = average_loss.min() mymax = average_loss[i].max() diff = (mymax - mymin) * 0.05 pylab.ylim([mymin - diff, mymax + diff]) # Put a legend to the right of the current axis ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) pylab.title(best_str) pylab.ylabel(label) pylab.xlabel("k") pylab.grid(True) except: pass plot_fn = output_prefix + "_xval_%s.pdf" % label util.create_directory_if_necessary(plot_fn) pylab.savefig(plot_fn) else: raise NotImplementedError(strategy) return best_k, best_delta, best_obj, best_delta_interp, best_obj_interp
detunings + offset_c + i, rabi_c) response = response / len(inhomogeneous) fig, ax = plt.subplots(nrows=3, ncols=1) fig.subplots_adjust(hspace=1) ax[0].plot(detunings / 1e6, single_reponse.real, label="real") ax[0].plot(detunings / 1e6, single_reponse.imag, label="imag") ax[0].axhline(0, color='black', linewidth=0.5) ax[0].axvline(0, color='black', linewidth=0.5) ax[0].set_xlabel("Detuning (MHz)") ax[0].set_ylabel("Susceptibility") ax[0].set_title("Single Atom Susceptibility") ax[0].legend() ax[1].plot(detunings / 1e6, response.real, label="real") ax[1].plot(detunings / 1e6, response.imag, label="imag") ax[1].set_xlabel("Detuning (kHz)") ax[1].set_ylabel("Amplitude (arb. units)") ax[1].axhline(0, color='black', linewidth=1) ax[1].axvline(0, color='black', linewidth=1) ax[1].set_title("Inhomogeneously Broadened Susceptibility") ax[1].legend() ax[2].plot(detunings / 1e6, sp.exp(2 * sp.pi * response.imag * 0.1 / 527e-9)) ax[2].set_xlabel("Detuning (kHz)") ax[2].set_ylabel("Transmission (%)") ax[2].axhline(0, color='black', linewidth=1) ax[2].axvline(0, color='black', linewidth=1) ax[2].set_title("Inhomogeneously Broadened Absorption") plt.show()
def gaussian(x, a, mu, sigma): return a * sp.exp(-.5 * ((x - mu) / sigma)**2.)
def safeExp(x): """ Bounded range for the exponential function (won't rpoduce inf or NaN). """ return exp(clip(x, -500, 500))
def burned_back(freq): sigma = 500e3 return 1 / sp.sqrt(2 * sp.pi * sigma**2) * sp.exp(-freq**2 / (2 * sigma**2))
def newpdf(s): p = dot(invA.T, (s - self.x)) return exp(-0.5 * dot(p, p)) / newDetFactorSigma
email : [email protected] [email protected] """ import p4f import scipy as sp import matplotlib.pyplot as plt # s = 10 x = 10 r = 0.05 sigma = 0.2 T = 3. / 12. n = 2 q = 0 # q is dividend yield deltaT = T / n # step u = sp.exp(sigma * sp.sqrt(deltaT)) d = 1 / u a = sp.exp((r - q) * deltaT) p = (a - d) / (u - d) s_dollar = 'S=$' c_dollar = 'c=$' p2 = round(p, 2) plt.figtext( 0.15, 0.91, 'Note: x=' + str(x) + ', r=' + str(r) + ', deltaT=' + str(deltaT) + ',p=' + str(p2)) plt.figtext(0.35, 0.61, 'p') plt.figtext(0.65, 0.76, 'p') plt.figtext(0.65, 0.43, 'p') plt.figtext(0.35, 0.36, '1-p') plt.figtext(0.65, 0.53, '1-p') plt.figtext(0.65, 0.21, '1-p')
def fishnet(x, is_sparse, irs, pcs, y, weights, offset, parm, nobs, nvars, jd, vp, cl, ne, nx, nlam, flmin, ulam, thresh, isd, intr, maxit, family): # load shared fortran library glmlib = loadGlmLib() if scipy.any(y < 0): raise ValueError('negative responses not permitted for Poisson family') if len(offset) == 0: offset = y * 0 is_offset = False else: is_offset = True # now convert types and allocate memory before calling # glmnet fortran library ###################################### # --------- PROCESS INPUTS ----------- ###################################### # force inputs into fortran order and scipy float64 copyFlag = False x = x.astype(dtype=scipy.float64, order='F', copy=copyFlag) irs = irs.astype(dtype=scipy.int32, order='F', copy=copyFlag) pcs = pcs.astype(dtype=scipy.int32, order='F', copy=copyFlag) y = y.astype(dtype=scipy.float64, order='F', copy=copyFlag) weights = weights.astype(dtype=scipy.float64, order='F', copy=copyFlag) offset = offset.astype(dtype=scipy.float64, order='F', copy=copyFlag) jd = jd.astype(dtype=scipy.int32, order='F', copy=copyFlag) vp = vp.astype(dtype=scipy.float64, order='F', copy=copyFlag) cl = cl.astype(dtype=scipy.float64, order='F', copy=copyFlag) ulam = ulam.astype(dtype=scipy.float64, order='F', copy=copyFlag) ###################################### # --------- ALLOCATE OUTPUTS --------- ###################################### # lmu lmu = -1 lmu_r = ctypes.c_int(lmu) # a0 a0 = scipy.zeros([nlam], dtype=scipy.float64) a0 = a0.astype(dtype=scipy.float64, order='F', copy=False) a0_r = a0.ctypes.data_as(ctypes.POINTER(ctypes.c_double)) # ca ca = scipy.zeros([nx, nlam], dtype=scipy.float64) ca = ca.astype(dtype=scipy.float64, order='F', copy=False) ca_r = ca.ctypes.data_as(ctypes.POINTER(ctypes.c_double)) # ia ia = -1 * scipy.ones([nx], dtype=scipy.int32) ia = ia.astype(dtype=scipy.int32, order='F', copy=False) ia_r = ia.ctypes.data_as(ctypes.POINTER(ctypes.c_int)) # nin nin = -1 * scipy.ones([nlam], dtype=scipy.int32) nin = nin.astype(dtype=scipy.int32, order='F', copy=False) nin_r = nin.ctypes.data_as(ctypes.POINTER(ctypes.c_int)) # dev dev = -1 * scipy.ones([nlam], dtype=scipy.float64) dev = dev.astype(dtype=scipy.float64, order='F', copy=False) dev_r = dev.ctypes.data_as(ctypes.POINTER(ctypes.c_double)) # alm alm = -1 * scipy.ones([nlam], dtype=scipy.float64) alm = alm.astype(dtype=scipy.float64, order='F', copy=False) alm_r = alm.ctypes.data_as(ctypes.POINTER(ctypes.c_double)) # nlp nlp = -1 nlp_r = ctypes.c_int(nlp) # jerr jerr = -1 jerr_r = ctypes.c_int(jerr) # dev0 dev0 = -1 dev0_r = ctypes.c_double(dev0) # ################################### # main glmnet fortran caller # ################################### if is_sparse: # sparse lognet glmlib.spfishnet_( ctypes.byref(ctypes.c_double(parm)), ctypes.byref(ctypes.c_int(nobs)), ctypes.byref(ctypes.c_int(nvars)), x.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), pcs.ctypes.data_as(ctypes.POINTER(ctypes.c_int)), irs.ctypes.data_as(ctypes.POINTER(ctypes.c_int)), y.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), offset.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), weights.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), jd.ctypes.data_as(ctypes.POINTER(ctypes.c_int)), vp.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), cl.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), ctypes.byref(ctypes.c_int(ne)), ctypes.byref(ctypes.c_int(nx)), ctypes.byref(ctypes.c_int(nlam)), ctypes.byref(ctypes.c_double(flmin)), ulam.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), ctypes.byref(ctypes.c_double(thresh)), ctypes.byref(ctypes.c_int(isd)), ctypes.byref(ctypes.c_int(intr)), ctypes.byref(ctypes.c_int(maxit)), ctypes.byref(lmu_r), a0_r, ca_r, ia_r, nin_r, ctypes.byref(dev0_r), dev_r, alm_r, ctypes.byref(nlp_r), ctypes.byref(jerr_r)) else: glmlib.fishnet_( ctypes.byref(ctypes.c_double(parm)), ctypes.byref(ctypes.c_int(nobs)), ctypes.byref(ctypes.c_int(nvars)), x.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), y.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), offset.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), weights.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), jd.ctypes.data_as(ctypes.POINTER(ctypes.c_int)), vp.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), cl.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), ctypes.byref(ctypes.c_int(ne)), ctypes.byref(ctypes.c_int(nx)), ctypes.byref(ctypes.c_int(nlam)), ctypes.byref(ctypes.c_double(flmin)), ulam.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), ctypes.byref(ctypes.c_double(thresh)), ctypes.byref(ctypes.c_int(isd)), ctypes.byref(ctypes.c_int(intr)), ctypes.byref(ctypes.c_int(maxit)), ctypes.byref(lmu_r), a0_r, ca_r, ia_r, nin_r, ctypes.byref(dev0_r), dev_r, alm_r, ctypes.byref(nlp_r), ctypes.byref(jerr_r)) # ################################### # post process results # ################################### # check for error if (jerr_r.value > 0): raise ValueError("Fatal glmnet error in library call : error code = ", jerr_r.value) elif (jerr_r.value < 0): print("Warning: Non-fatal error in glmnet library call: error code = ", jerr_r.value) print("Check results for accuracy. Partial or no results returned.") # clip output to correct sizes lmu = lmu_r.value a0 = a0[0:lmu] ca = ca[0:nx, 0:lmu] ia = ia[0:nx] nin = nin[0:lmu] dev = dev[0:lmu] alm = alm[0:lmu] # ninmax ninmax = max(nin) # fix first value of alm (from inf to correct value) if ulam[0] == 0.0: t1 = scipy.log(alm[1]) t2 = scipy.log(alm[2]) alm[0] = scipy.exp(2 * t1 - t2) # create return fit dictionary dd = scipy.array([nvars, lmu], dtype=scipy.integer) if ninmax > 0: ca = ca[0:ninmax, :] df = scipy.sum(scipy.absolute(ca) > 0, axis=0) ja = ia[0:ninmax] - 1 # ia is 1-indexed in fortran oja = scipy.argsort(ja) ja1 = ja[oja] beta = scipy.zeros([nvars, lmu], dtype=scipy.float64) beta[ja1, :] = ca[oja, :] else: beta = scipy.zeros([nvars, lmu], dtype=scipy.float64) df = scipy.zeros([1, lmu], dtype=scipy.float64) fit = dict() fit['a0'] = a0 fit['beta'] = beta fit['dev'] = dev fit['nulldev'] = dev0_r.value fit['df'] = df fit['lambdau'] = alm fit['npasses'] = nlp_r.value fit['jerr'] = jerr_r.value fit['dim'] = dd fit['offset'] = is_offset fit['class'] = 'fishnet' # ################################### # return to caller # ################################### return fit
def simpleMultivariateNormalPdf(z, detFactorSigma): """ Assuming z has been transformed to a mean of zero and an identity matrix of covariances. Needs to provide the determinant of the factorized (real) covariance matrix. """ dim = len(z) return exp(-0.5 * dot(z, z)) / (power(2.0 * pi, dim / 2.) * detFactorSigma)
def kern(b): k_sigma = 1.0 # kernel standard deviation pairwise_sq_dists = squareform(pdist(b.reshape(-1, 1), "sqeuclidean")) # pylint: disable=invalid-unary-operand-type k = scipy.exp(-pairwise_sq_dists / k_sigma**2) return k
def oldpdf(s): p = dot(oldInvA.T, (s - oldX)) return exp(-0.5 * dot(p, p)) / oldDetFactorSigma
def cost_log_params(self, log_params): """ Return the cost given the logarithm of the input parameters """ return self.cost(scipy.exp(log_params))
def Pvap(self, T): [C1, C2, C3, C4, C5] = self.constPvap p = C1 + C2 / T + C3 * sc.log(T) + C4 * T**C5 return sc.exp(p)
def gaus(self,x, a, x0, sigma): return a * exp(-(x - x0) ** 2 / (2 * sigma ** 2))
def periodic_cost_log_params(self, log_params): """ Return the cost of periodic curve fit given the logarithm of the input parameters """ return self.periodic_cost(scipy.exp(log_params))
def w_mvf_cdf(x): return (sp.exp(self.k * np.array(x, ndmin=1)) - sp.exp(-self.k)) / (self.k * self._ck)
def res_log_params(self, log_params): """ Return the residual values given the logarithm of the parameters """ return self.res(scipy.exp(log_params))
def backgroundFunction(x, par): return par[0] * exp(-par[1] * x) + par[2] + par[3] * x
def w_mvf_inv_cdf(x): return sp.log( sp.exp(-self.k) + self.k * self._ck * np.array(x, ndmin=1)) / self.k
Q_star1_vals = deft_1d(xis, xint, alpha=1, G=G, verbose=False)(xs) Q_star2_vals = deft_1d(xis, xint, alpha=2, G=G, verbose=False)(xs) Q_star3_vals = deft_1d(xis, xint, alpha=3, G=G, verbose=False)(xs) # Perform GKDE denstiy estimation gkde = gaussian_kde(xis) Q_gkde_vals = gkde(xs) / sum(gkde(xs) * dx) # Perform GMM denstiy estimation using BIC max_K = 10 bic_values = sp.zeros([max_K]) Qs_gmm = sp.zeros([max_K, plot_grid_size]) for k in sp.arange(1, max_K + 1): gmm = mixture.GMM(int(k)) gmm.fit(xis) Qgmm = lambda (x): sp.exp(gmm.score(x)) / sum( sp.exp(gmm.score(xs)) * dx) Qs_gmm[k - 1, :] = Qgmm(xs) / sum(Qgmm(xs) * dx) bic_values[k - 1] = gmm.bic(sp.array(xis)) # Choose distribution with lowest BIC i_best = sp.argmin(bic_values) Q_gmm_vals = Qs_gmm[i_best, :] # Compute distances dists[trial_num, 0, i] = geo_dist(Q_true_vals, Q_star1_vals, dx) dists[trial_num, 1, i] = geo_dist(Q_true_vals, Q_star2_vals, dx) dists[trial_num, 2, i] = geo_dist(Q_true_vals, Q_star3_vals, dx) dists[trial_num, 3, i] = geo_dist(Q_true_vals, Q_gmm_vals, dx) dists[trial_num, 4, i] = geo_dist(Q_true_vals, Q_gkde_vals, dx)
def w_mvf_pdf(x): return sp.exp(np.array(x, ndmin=1) * self.k) / self._ck