Esempio n. 1
1
def newton(fn=0, fp=0, x=0.1, mn=0):
    t = time()
    test = 0
    if not fn and not fp:
        from scipy.misc import derivative

        func = input("equation(use x as unknown):")
        fn = lambda x: eval(func)
        fp = lambda x: derivative(fn, x)
        print("div")
    elif not fp:
        from scipy.misc import derivative

        fp = lambda x: derivative(fn, x)
    if mn:
        while fn(x, mn) != 0:
            if fp(x, mn) == 0:
                x += 1
                print("error")
                test += 1
                print(test)
                break
            x, lastx = x - (fn(x, mn) / fp(x, mn)), x
    else:
        while fn(x) != 0 or rerr > 10 ** -12:
            x, lastx = x - (fn(x) / fp(x)), x
            rerr = abs(lastx - x) / x
    return x
Esempio n. 2
1
		def fisher(theta, i, j = None):
			"""
			Fisher information using the first order derivative

			:param theta: the theta of the density
			:param i: The ith component of the diagonal of the fisher information matrix will be returned (if j is None)
			:param j: The i,j th component of the fisher information matrix will be returned
			"""

			#Bring it in a form that we can derive
			fh = lambda ti, t0, tn, x: np.log(self.density(x, list(t0) + [ti] + list(tn)))

			# The derivative
			f_d_theta_i = lambda x: derivative(fh, theta[i], dx=1e-5, n=1, args=(theta[0:i], theta[i + 1:], x))

			if j is not None:
				f_d_theta_j = lambda x: derivative(fh, theta[j], dx=1e-5, n=1, args=(theta[0:j], theta[j + 1:], x))
				f = lambda x: np.float128(0) if fabs(self.density(x, theta)) < 1e-5 else f_d_theta_i(x) * f_d_theta_j(x) * self.density(x, theta)
			else:
				# The function to integrate
				f = lambda x: np.float128(0) if fabs(self.density(x, theta)) < 1e-5 else f_d_theta_i(x) ** 2 * self.density(x, theta)


			#First order
			result = integrate(f, self.support)
			return result
    def eval_function(self, individual, radius, representatives):
        distanceSum = 0.001+sum([self.share_function(self.distance(individual, r), 1, radius) for r in representatives])
        # print "distanceSum: %s" % distanceSum
        calcWithY = partial(self.function_object.calculateWithXY, individual[0])
        calcWithX = partial(self.function_object.calculateWithYX, individual[1])
        derivY = abs(misc.derivative(calcWithY, individual[1], dx=1e-6))
        derivX = abs(misc.derivative(calcWithX, individual[0], dx=1e-6))

        return self.function_object.calculate(individual)/distanceSum, distanceSum*derivX, distanceSum*derivY
Esempio n. 4
0
def solarAzimuth(_day, _hour = None):
    """Solar azimuth in radians"""  
    def cos_azmth(_hourAngle):
        """Definition of the cosine of the azimuth replacing the altitude by 
        it formula"""
        return (np.sin(np.arcsin(np.cos(latitude)*np.cos(declination(_day,radianes))* \
        np.cos(_hourAngle)+np.sin(latitude)*np.sin(declination(_day,radianes))))*np.sin(latitude)- \
        np.sin(declination(_day,radianes))) \
        / (np.cos(np.arcsin(np.cos(latitude)*np.cos(declination(_day,radianes))* \
        np.cos(_hourAngle)+np.sin(latitude)*np.sin(declination(_day,radianes))))*np.cos(latitude))

    if _hour is None:
        for i in range(np.size(hourAngle)):
            derivada[i] = sc.derivative(cos_azmth,hourAngle[i],dx=1e-6)
            _signo = -np.sign(derivada[i])
            azimuth[i] =_signo * np.arccos(cos_azmth(hourAngle[i]))
            azimuth_deg[i] = azimuth[i]*180/np.pi
            
    else:
         _hourAngle = (12-int(_hour))*np.pi/12
         _derivada = sc.derivative(cos_azmth,_hourAngle,dx=1e-6)
         _signo = - np.sign(_derivada)
         if cos_azmth(_hourAngle) > 1:
             _azimuth = _signo * np.arccos(1) * 180 / np.pi
         else:
             _azimuth = _signo * np.arccos(cos_azmth(_hourAngle)) * 180 / np.pi
         return _azimuth
    
    return
Esempio n. 5
0
def calc_curvature(func, d_point=0):
    #曲率半径、曲率を求める
    #曲率が大きいほど関数の曲がり具合が大きい

    dx1 = scmisc.derivative(func, d_point, n=1, dx=1e-6) #dxを指定しないとダメ
    dx2 = scmisc.derivative(func, d_point, n=2, dx=1e-6)
    R = (1.0 + (dx1**2.0))**(3.0/2.0) / np.fabs(dx2) #曲率半径
    curvature_of_func = 1.0 / R

    return curvature_of_func
Esempio n. 6
0
def C_Meng(T, Tc, Pc, D, B):
    r"""Calculate the 3rd virial coefficient using the Meng-Duan-Li correlation

    Parameters
    ----------
    T : float
        Temperature [K]
    Tc : float
        Critical temperature [K]
    Pc : float
        Critical pressure
    D : float
        dipole moment [debye]
    B : list
        Second virial coefficient tuple with B, ∂B/∂T, ∂²B/∂T²

    Returns
    -------
    C : float
        Third virial coefficient [m⁶/mol²]
    C1 : float
        T(∂C/∂T) [m⁶/mol²]
    C2 : float
        T²(∂²C/∂T²) [m⁶/mol²]

    Examples
    --------
    Selected date from Table 2, pag 74 for neon

    >>> from lib.mEoS import Ne
    >>> D = Ne.momentoDipolar.Debye
    >>> B = B_Meng(273.15, Ne.Tc, Ne.Pc, Ne.f_acent, D)
    >>> "%.2f" % (C_Meng(273.15, Ne.Tc, Ne.Pc, D, B)[0]*1e-5)
    '0.24'

    References
    ----------
    [7]_ Meng, L., Duan, Y.Y. Li, L. Correations for Second and Third Virial
        Coefficients of Pure Fluids. Fluid Phase Equilibria 226 (2004) 109-120
    """
    mur = D**2*Pc/1.01325/Tc**2

    def f(T, *args):
        B = args[-1]
        Br = B*Pc/R/Tc
        Tr = T/Tc
        f0 = 1094.051 - 3334.145/Tr**0.1 + 3389.848/Tr**0.2 - 1149.58/Tr**0.3
        f1 = (2.0243-0.85902/Tr)*1e-10
        return 5.476e-3 + (Br-0.0936)**2*(f0+mur**4*f1)

    C = f(T, B[0])
    C1 = derivative(f, T, n=1, args=(T, B[1]))
    C2 = derivative(f, T, n=2, args=(T, B[2]))

    return C, C1, C2
Esempio n. 7
0
    def from_system(cls, system, z0=None, zd0=None, zdd0=None,
                    perturbation=None):
        """
        Linearise ``system`` about the point ``z0``, ``zd0``, ``zdd0``.

        If the linearisation point is not given, the current positions and
        velocities of the system, and zero acceleration, are assumed.
        """
        if perturbation is None:
            perturbation = 1e-3  # could have a better default
        assert perturbation > 0

        def _prepare_initial_values(zx, default):
            if zx is None:
                return default
            elif zx is 0:
                return 0 * default
            elif isinstance(zx, dict):
                return _create_strain_array(system, zx)
            else:
                return zx

        f = len(system.qd.dofs)  # number of DOFs
        z0 = _prepare_initial_values(z0, system.q.dofs[:])
        zd0 = _prepare_initial_values(zd0, system.qd.dofs[:])
        zdd0 = _prepare_initial_values(zdd0, zeros(len(system.q.dofs)))

        #def Q_func(zdd, i):
        #    self.q [self.iFreeDOF] = z0
        #    self.qd[self.iFreeDOF] = zd0
        #    return self.eval_reduced_system(hi(zdd0,zdd,i))

        def one(n, i):
            y = np.zeros(n)
            y[i] = 1
            return y

        def perturb(x, i, n):
            """
            Calculate the system residue when the i'th DOF is perturbed by
            x, referring to derivative n (0=z, 1=zd, 2=zdd)
            """
            args = [z0, zd0, zdd0]
            args[n] = args[n] + x * one(len(args[n]), i)
            return system_residue(system, *args)

        h = perturbation
        M = array([derivative(perturb, 0, h, args=(i, 2)) for i in range(f)]).T
        C = array([derivative(perturb, 0, h, args=(i, 1)) for i in range(f)]).T
        K = array([derivative(perturb, 0, h, args=(i, 0)) for i in range(f)]).T
        system.q.dofs[:] = z0
        system.qd.dofs[:] = zd0
        system.update_kinematics()

        return cls(M, C, K, z0, zd0, zdd0)
Esempio n. 8
0
    def gruneisen_parameter(self, temperature, volume):
        """
        Slater-gamma formulation(the default):
            gruneisen paramter = - d log(theta)/ d log(V)
                               = - ( 1/6 + 0.5 d log(B)/ d log(V) )
                               = - (1/6 + 0.5 V/B dB/dV),
                                    where dB/dV = d^2E/dV^2 + V * d^3E/dV^3

        Mie-gruneisen formulation:
            Eq(31) in doi.org/10.1016/j.comphy.2003.12.001
            Eq(7) in Blanco et. al. Joumal of Molecular Structure (Theochem)
                368 (1996) 245-255
            Also se J.P. Poirier, Introduction to the Physics of the Earth’s
                Interior, 2nd ed. (Cambridge University Press, Cambridge,
                2000) Eq(3.53)

        Args:
            temperature (float): temperature in K
            volume (float): in Ang^3

        Returns:
            float: unitless
        """
        if isinstance(self.eos, PolynomialEOS):
            p = np.poly1d(self.eos.eos_params)
            # first derivative of energy at 0K wrt volume evaluated at the
            # given volume, in eV/Ang^3
            dEdV = np.polyder(p, 1)(volume)
            # second derivative of energy at 0K wrt volume evaluated at the
            # given volume, in eV/Ang^6
            d2EdV2 = np.polyder(p, 2)(volume)
            # third derivative of energy at 0K wrt volume evaluated at the
            # given volume, in eV/Ang^9
            d3EdV3 = np.polyder(p, 3)(volume)
        else:
            func = self.ev_eos_fit.func
            dEdV = derivative(func, volume, dx=1e-3)
            d2EdV2 = derivative(func, volume, dx=1e-3, n=2, order=5)
            d3EdV3 = derivative(func, volume, dx=1e-3, n=3, order=7)

        # Mie-gruneisen formulation
        if self.use_mie_gruneisen:
            p0 = dEdV
            return (self.gpa_to_ev_ang * volume *
                    (self.pressure + p0 / self.gpa_to_ev_ang) /
                    self.vibrational_internal_energy(temperature, volume))

        # Slater-gamma formulation
        # first derivative of bulk modulus wrt volume, eV/Ang^6
        dBdV = d2EdV2 + d3EdV3 * volume
        return -(1./6. + 0.5 * volume * dBdV /
                 FloatWithUnit(self.ev_eos_fit.b0_GPa, "GPa").to("eV ang^-3"))
def radius_of_curvature(theta, func_R, *args_for_func_R):
    """Returns R_c = (R^2 + R'^2)^{3/2} / |R^2 + 2 R'^2 - R R''| 

Uses numerical differentiation.  NOT RECOMMENDED SINCE NOT ACCURATE ON
THE AXIS.  Use `axis_Rc` instead.

    """
    R = func_R(theta, *args_for_func_R)
    dR = derivative(func_R, theta,
                    dx=DX_FOR_NUMERICAL_DERIVATIVE, args=args_for_func_R)
    d2R = derivative(func_R, theta, n=2,
                     dx=DX_FOR_NUMERICAL_DERIVATIVE, args=args_for_func_R)
    return (R**2 + dR**2)**1.5 / np.abs(R**2 + 2*dR**2 - R*d2R)
Esempio n. 10
0
def derivative_check(x,popt,left,right):
	if len(left)==0 or len(right)==0:
		return True
	if len(left)==1 or len(right)==1:
		return True
	maxlx=np.max(left[:,0])
	minlx=np.min(left[:,0])
	maxly=np.max(left[:,1])
	minly=np.min(left[:,1])
	maxrx=np.max(right[:,0])
	minrx=np.min(right[:,0])
	maxry=np.max(right[:,1])
	minry=np.min(right[:,1])
	t1=-1
	t2=-1
	pend1=[]
	pend2=[]
	pend1.append(deriv.derivative(fu,minlx,n=1,args=popt))
	pend1.append(deriv.derivative(fu,maxlx,n=1,args=popt))
	pend1.append(deriv.derivative(fu,minrx,n=1,args=popt))
	pend1.append(deriv.derivative(fu,maxrx,n=1,args=popt))
	sign=pend1[0]
	for i in pend1:
		if i<0:
			return False
	pend1=[]
	pend1.append(deriv.derivative(fu,minlx,n=2,args=popt))
	pend1.append(deriv.derivative(fu,maxlx,n=2,args=popt))
	pend1.append(deriv.derivative(fu,minrx,n=2,args=popt))
	pend1.append(deriv.derivative(fu,maxrx,n=2,args=popt))
	sign=pend1[0]
	for i in pend1:
		if (sign>0 and i<0) or (sign<0 and i>0):
			return False
	return True
Esempio n. 11
0
def C_Orbey_Vera(T, Tc, Pc, w):
    """Calculate the third virial coefficient using the Orbey-Vera correlation

    Parameters
    ----------
    T : float
        Temperature [K]
    Tc : float
        Critical temperature [K]
    Pc : float
        Critical pressure
    w : float
        Acentric factor [-]

    Returns
    -------
    C : float
        Third virial coefficient [m⁶/mol²]
    C1 : float
        T(∂C/∂T) [m⁶/mol²]
    C2 : float
        T²(∂²C/∂T²) [m⁶/mol²]

    Examples
    --------
    Selected points from Table 2 of paper

    >>> from lib.mEoS.Benzene import Benzene as Bz
    >>> "%.1f" % (C_Orbey_Vera(0.877*Bz.Tc, Bz.Tc, Bz.Pc, Bz.f_acent)[0]*1e9)
    '41.5'
    >>> "%.1f" % (C_Orbey_Vera(1.019*Bz.Tc, Bz.Tc, Bz.Pc, Bz.f_acent)[0]*1e9)
    '35.8'

    References
    ----------
    [4]_ Orbey, H., Vera, J.H.: Correlation for the third virial coefficient
        using Tc, Pc and ω as parameters, AIChE Journal 29, 107 (1983)
    """
    def f(T):
        Tr = T/Tc
        g0 = 0.01407+0.02432/Tr**2.8-0.00313/Tr**10.5
        g1 = -0.02676+0.0177/Tr**2.8+0.04/Tr**3-0.003/Tr**6-0.00228/Tr**10.5
        g = g0+w*g1
        return g*R**2*Tc**2/Pc**2

    C = f(T)
    C1 = derivative(f, T, n=1)
    C2 = derivative(f, T, n=2)

    return C, C1, C2
Esempio n. 12
0
def test_fuzz_dPsat_dT():
    from thermo import eos
    eos_list = list(eos.__all__); eos_list.remove('GCEOS')
    eos_list.remove('ALPHA_FUNCTIONS'); eos_list.remove('eos_list')
    eos_list.remove('GCEOS_DUMMY')
    
    Tc = 507.6
    Pc = 3025000
    omega = 0.2975
    
    e = PR(T=400, P=1E5, Tc=507.6, Pc=3025000, omega=0.2975)
    dPsats_dT_expect = [938.7777925283981, 10287.225576267781, 38814.74676693623]
    assert_allclose([e.dPsat_dT(300), e.dPsat_dT(400), e.dPsat_dT(500)], dPsats_dT_expect)
    
    # Hammer the derivatives for each EOS in a wide range; most are really 
    # accurate. There's an error around the transition between polynomials 
    # though - to be expected; the derivatives are discontinuous there.
    dPsats_derivative = []
    dPsats_analytical = []
    for eos in range(len(eos_list)):
        for T in np.linspace(0.2*Tc, Tc*.999, 50):
            e = globals()[eos_list[eos]](Tc=Tc, Pc=Pc, omega=omega, T=T, P=1E5)
            anal = e.dPsat_dT(T)
            numer = derivative(e.Psat, T, order=9)
            dPsats_analytical.append(anal)
            dPsats_derivative.append(numer)
    assert allclose_variable(dPsats_derivative, dPsats_analytical, limits=[.02, .06], rtols=[1E-5, 1E-7])
Esempio n. 13
0
def test_EQ116_more():
    # T derivative
    coeffs = (647.096, 17.863, 58.606, -95.396, 213.89, -141.26)
    diff_1T = derivative(EQ116, 50,  dx=1E-3, order=21, args=coeffs)
    diff_1T_analytical = EQ116(50., *coeffs, order=1)
    assert_allclose(diff_1T, diff_1T_analytical, rtol=1E-3)
    assert_allclose(diff_1T_analytical, 0.020379262711650914)
    
    # Integral
    int_50 = EQ116(50., *coeffs, order=-1) 
    int_20 = EQ116(20., *coeffs, order=-1)
    numerical_1T = quad(EQ116, 20, 50, args=coeffs)[0]
    assert_allclose(int_50 - int_20, numerical_1T)
    assert_allclose(int_50 - int_20, 1636.962423782701)
    
    # Integral over T
    T_int_50 = EQ116(50., *coeffs, order=-1j)
    T_int_20 = EQ116(20., *coeffs, order=-1j)
    
    to_int = lambda T :EQ116(T, *coeffs)/T
    numerical_1_over_T = quad(to_int, 20, 50)[0]
    assert_allclose(T_int_50 - T_int_20, numerical_1_over_T)
    assert_allclose(T_int_50 - T_int_20, 49.95109104018752)
    
    with pytest.raises(Exception):
        EQ116(20., *coeffs, order=1E100)
def func_first_derivative(x):
    value = 1.
### START YOUR CODE HERE ###
    value = misc.derivative(func,x,1e-5);

#### END YOUR CODE HERE ####
    return value
def func_2nd_derivative_numerical(x):
    value = 1.
### START YOUR CODE HERE ###
    value = misc.derivative(func,x,1e-5,2);

#### END YOUR CODE HERE ####
    return value
Esempio n. 16
0
def ACM(Cf,i):
	
    q=d.a_3-d.a_4
    #L=(Cf/111.)
    #e_0=((d.a_7*L**2.)/(L**2.+d.a_9))
    g_c=(((np.abs(float(d.phi_d[i])))**(d.a_10))/(0.5*float(d.T_range[i])+d.a_6*float(d.R_tot[i])))
    #p=np.exp(d.a_8*float(d.T_max[i]))*((d.a_1*d.N*L)/g_c)
    #C_i=(0.5*(d.d.C_a+q-p+np.np.sqrt((d.d.C_a+q-p)**2.-4.*(d.d.C_a*q-p*d.a_3))))
    delta=(-0.408*np.cos(((360.*(float(d.D[i])+10.)*np.pi)/(365.*180.))))
    s=(24.*np.arccos((-np.tan(d.bigdelta)*np.tan(delta)))/np.pi)
    psi=np.exp(d.a_8*float(d.T_max[i]))*((d.a_1*d.N)/(g_c*111.))
    a=np.exp(d.a_8*float(d.T_max[i]))*((d.a_1*d.N)/(g_c*111.))
    phi=d.a_7*float(d.I[i])*g_c
    I=float(d.I[i])
	
    def GPPfunc(Cf):
        GPP=.5*phi*Cf**2*(d.C_a-q+psi*Cf-np.sqrt((d.C_a+q-psi*Cf)**2-4.*(d.C_a*q-d.a_3*psi*Cf)))*(d.a_2*s+d.a_5)/(I*d.a_7*Cf**2+.5*g_c*(Cf**2+d.a_9*111.**2)*(d.C_a-q+psi*Cf-np.sqrt((d.C_a+q-psi*Cf)**2-4.*(d.C_a*q-d.a_3*psi*Cf))))        
        return GPP 

    def GPPdifffunc(Cf):
        GPP_diff=(((2.*(d.a_2*s+d.a_5))*(-49284.*q*d.a_9*psi*Cf+49284.*psi*Cf*d.a_3*d.a_9-49284.*d.C_a*d.a_9*q+24642.*psi**2*Cf**2*d.a_9+24642.*d.a_9*d.C_a**2+24642.*d.a_9*q**2)*phi*Cf*g_c+(2.*I)*(d.a_2*s+d.a_5)*psi*Cf**4*d.a_7*phi)*np.sqrt(psi**2*Cf**2+(-2.*d.C_a-2.*q+4.*d.a_3)*psi*Cf+d.C_a**2-2.*d.C_a*q+q**2)+(-(49284.*(d.a_2*s+d.a_5))*psi**3*d.a_9*phi*Cf**4+(2.*(d.a_2*s+d.a_5))*(24642.*d.C_a-98568.*d.a_3+73926.*q)*phi*psi**2*d.a_9*Cf**3+(2.*(d.a_2*s+d.a_5))*(-98568.*d.a_3*d.C_a+98568.*d.a_3*q+49284.*d.C_a*q-73926.*q**2+24642.*d.C_a**2)*phi*psi*d.a_9*Cf**2+(2.*(d.a_2*s+d.a_5))*(-73926.*d.C_a*q**2-24642.*d.C_a**3+24642.*q**3+73926.*d.C_a**2*q)*phi*d.a_9*Cf)*g_c-(2.*I)*(d.a_2*s+d.a_5)*psi**2*d.a_7*phi*Cf**5+(2.*(d.a_2*s+d.a_5))*((1.*I)*q*d.a_7+(1.*I)*d.C_a*d.a_7-(2.*I)*d.a_3*d.a_7)*phi*psi*Cf**4)/(np.sqrt(psi**2*Cf**2+(-2.*d.C_a-2.*q+4.*d.a_3)*psi*Cf+d.C_a**2-2.*d.C_a*q+q**2)*((2.*I)*d.a_7*Cf**2+g_c*Cf**2*d.C_a-1.*g_c*Cf**2*q+g_c*Cf**3*psi-1.*g_c*Cf**2*np.sqrt(psi**2*Cf**2+(-2.*d.C_a-2.*q+4.*d.a_3)*psi*Cf+d.C_a**2-2.*d.C_a*q+q**2)+12321.*g_c*d.a_9*d.C_a-12321.*g_c*d.a_9*q+12321.*g_c*d.a_9*psi*Cf-12321.*g_c*d.a_9*np.sqrt(psi**2*Cf**2+(-2.*d.C_a-2.*q+4.*d.a_3)*psi*Cf+d.C_a**2-2.*d.C_a*q+q**2))**2)    
        return GPP_diff
		
    GPP = GPPfunc(Cf)
    GPP_diff=  GPPdifffunc(Cf)
    GPP_diff2 = misc.derivative(GPPfunc,Cf) 
    return GPP, GPP_diff #, GPP_diff2
Esempio n. 17
0
def test_fuzz_dV_dP_and_d2V_dP2_derivatives():
    from thermo import eos
    eos_list = list(eos.__all__); eos_list.remove('GCEOS')
    eos_list.remove('ALPHA_FUNCTIONS'); eos_list.remove('VDW')
    
    phase_extensions = {True: '_l', False: '_g'}
    derivative_bases_dV_dP = {0:'V', 1:'dV_dP', 2:'d2V_dP2'}
    
    def dV_dP(P, T, eos, order=0, phase=True, Tc=507.6, Pc=3025000., omega=0.2975):
        eos = globals()[eos_list[eos]](Tc=Tc, Pc=Pc, omega=omega, T=T, P=P)
        phase_base = phase_extensions[phase]
        attr = derivative_bases_dV_dP[order]+phase_base
        return getattr(eos, attr)
    
    
    x, y = [], []
    for eos in range(len(eos_list)):
        for T in np.linspace(.1, 1000, 50):
            for P in np.logspace(np.log10(3E4), np.log10(1E6), 50):
                T, P = float(T), float(P)
                for phase in [True, False]:
                    for order in [1, 2]:
                        try:
                            # If dV_dx_phase doesn't exist, will simply abort and continue the loop
                            numer = derivative(dV_dP, P, dx=15., args=(T, eos, order-1, phase))
                            ana = dV_dP(T=T, P=P, eos=eos, order=order, phase=phase)
                        except:
                            continue
                        x.append(numer)
                        y.append(ana)
    assert allclose_variable(x, y, limits=[.02, .04, .04, .05, .15, .45, .95],
                            rtols=[1E-2, 1E-3, 1E-4, 1E-5, 1E-6, 1E-7, 1E-9])
Esempio n. 18
0
def test_EQ104_more():
    # T derivative
    coeffs = (0.02222, -26.38, -16750000, -3.894E19, 3.133E21)
    diff_1T = derivative(EQ104, 250,  dx=1E-3, order=21, args=coeffs)
    diff_1T_analytical = EQ104(250., *coeffs, order=1)
    assert_allclose(diff_1T, diff_1T_analytical, rtol=1E-3)
    assert_allclose(diff_1T, 0.0653824814073)
    
    # Integral
    int_250 = EQ104(250., *coeffs, order=-1) 
    int_220 = EQ104(220., *coeffs, order=-1)
    numerical_1T = quad(EQ104, 220, 250, args=coeffs)[0]
    assert_allclose(int_250 - int_220, numerical_1T)
    assert_allclose(int_250 - int_220, -127.91851427119406)
    
#     Integral over T
    T_int_250 = EQ104(250., *coeffs, order=-1j)
    T_int_220 = EQ104(220., *coeffs, order=-1j)
    
    to_int = lambda T :EQ104(T, *coeffs)/T
    numerical_1_over_T = quad(to_int, 220, 250)[0]
    assert_allclose(T_int_250 - T_int_220, numerical_1_over_T)
    assert_allclose(T_int_250 - T_int_220, -0.5494851210308727)

    with pytest.raises(Exception):
        EQ104(20., *coeffs, order=1E100)
Esempio n. 19
0
 def simulateGamma(self, assetPrices):
     opt=copy.copy(self.option)
     mechanism=self.mechanism
     
     plotDf=pd.DataFrame(np.zeros([len(assetPrices), 3]), columns=['AssetPrice', 'DA_Gamma', 'BLS_Gamma'])
     plotDf['AssetPrice']=assetPrices.values
     
     def optPrice(assetPrice):
         opt.S0=assetPrice
         orders=self.traders.getOrders(opt, self.numOrders)
         orders=mechanism.clearOrders(orders)
         
         return mechanism.getPrice(orders)
     
     for i, p in enumerate(assetPrices.values):
         plotDf.ix[i]['DA_Gamma']=derivative(optPrice, x0=p,dx=20, n=2)
         
         opt.S0=p            
         plotDf.ix[i]['BLS_Gamma']=opt.gamma()
         
         print plotDf.ix[i]['DA_Gamma'], plotDf.ix[i]['BLS_Gamma']
         
         print i
  
     return plotDf
Esempio n. 20
0
  def _testCompareToExplicitDerivative(self, dtype):
    """Compare to the explicit reparameterization derivative.

    Verifies that the computed derivative satisfies
    dsample / dalpha = d igammainv(alpha, u) / dalpha,
    where u = igamma(alpha, sample).

    Args:
      dtype: TensorFlow dtype to perform the computations in.
    """
    delta = 1e-3
    np_dtype = dtype.as_numpy_dtype
    try:
      from scipy import misc  # pylint: disable=g-import-not-at-top
      from scipy import special  # pylint: disable=g-import-not-at-top

      alpha_val = np.logspace(-2, 3, dtype=np_dtype)
      alpha = constant_op.constant(alpha_val)
      sample = random_ops.random_gamma([], alpha, np_dtype(1.0), dtype=dtype)
      actual = gradients_impl.gradients(sample, alpha)[0]

      (sample_val, actual_val) = self.evaluate((sample, actual))

      u = special.gammainc(alpha_val, sample_val)
      expected_val = misc.derivative(
          lambda alpha_prime: special.gammaincinv(alpha_prime, u),
          alpha_val, dx=delta * alpha_val)

      self.assertAllClose(actual_val, expected_val, rtol=1e-3, atol=1e-3)
    except ImportError as e:
      tf_logging.warn("Cannot use special functions in a test: %s" % str(e))
Esempio n. 21
0
def ACM(Cf,i):
	
    q=d.a_3-d.a_4
    L=(Cf/111.)
    e_0=((d.a_7*L**2)/(L**2+d.a_9))
    g_c=((np.abs(float(d.phi_d)))**(d.a_10))/(0.5*float(max(dat.ta_fill[(dat.jd==d.D[i])]-min(dat.ta_fill[(dat.jd==d.D[i])])+d.a_6*float(d.R_tot))))
    p=(((d.a_1*d.N*L)/g_c)*np.exp(d.a_8*float(max(dat.ta_fill[(dat.jd==d.D[i])]))))
    C_i=(0.5*(d.C_a+q-p+np.sqrt((d.C_a+q-p)**2-4*(d.C_a*q-p*d.a_3))))
    delta=(-0.408*np.cos(((360*(float(d.D[i])+10)*np.pi)/(365*180))))
    s=(24*np.arccos((-np.tan(d.bigdelta)*np.tan(delta)))/np.pi)
	
    def GPPfunc(Cf):
		
        #L=(Cf/111.)
        #e_0=((d.a_7*L**2)/(L**2+d.a_9))
        #GPP=((e_0*float(d.I[i])*g_c*(d.C_a-C_i)*(d.a_2*s+d.a_5))/(e_0*float(d.I[i])+g_c*(d.C_a-C_i))) #0.2*float(d.I[i])*(1-np.exp(-0.5*Cf/111.))
        #GPP_diff=((2*float(d.I[i])*d.a_7*d.a_9*((111.0*g_c*(d.C_a-C_i))**2)*(d.a_2*s+d.a_5)*Cf)/(((g_c*(d.C_a-C_i)+d.a_7*float(d.I[i]))*Cf**2+d.a_9*(111.0**2)*g_c*(d.C_a-C_i))**2))  #(0.2*0.5*float(d.I[i])/111.)*np.exp(-0.5*Cf/111.)
        GPP= (d.a_7*(Cf**2)*float(d.I[i])*g_c*(d.C_a-C_i)*(d.a_2*s+d.a_5))/((d.a_7*float(d.I[i])+g_c*(d.C_a-C_i))*(Cf**2)+d.a_9*(111.**2)*g_c*(d.C_a-C_i))
        
        return GPP 

    def GPPdifffunc(Cf):
		
        GPP_diff=(24642.*float(d.I[i])*d.a_7*Cf*(g_c**2)*((d.C_a-C_i)**2)*(d.a_2*s+d.a_5)*d.a_9)/((Cf**2+12321.*d.a_9)*(d.C_a-C_i)*g_c+float(d.I[i])*d.a_7*Cf**2)**2 #(2*Cf*float(d.I[i])*d.a_7*d.a_9*(111.**2)*(g_c**2)*((d.C_a-C_i)**2)*(d.a_2*s+d.a_5))/((d.a_7*float(d.I[i])+g_c*(d.C_a-C_i))*(Cf**2)+d.a_9*(111.**2)*g_c*(d.C_a-C_i))**2
        
        return GPP_diff
		
    GPP = GPPfunc(Cf)
    GPP_diff=  GPPdifffunc(Cf)
    GPP_diff2 = misc.derivative(GPPfunc,Cf) 
    return GPP, GPP_diff
Esempio n. 22
0
    def get_corr_pred(self, eps, d_eps, sig, t_n, t_n1, alpha, q, kappa):
        #         g = lambda k: 0.8 - 0.8 * np.exp(-k)
        #         g = lambda k: 1. / (1 + np.exp(-2 * k + 6.))
        n_e, n_ip, n_s = eps.shape
        D = np.zeros((n_e, n_ip, 3, 3))
        D[:, :, 0, 0] = self.E_m
        D[:, :, 2, 2] = self.E_f
        sig_trial = sig[:, :, 1]/(1-self.g(kappa)) + self.E_b * d_eps[:,:, 1]
        xi_trial = sig_trial - q
        f_trial = abs(xi_trial) - (self.sigma_y + self.K_bar * alpha)
        elas = f_trial <= 1e-8
        plas = f_trial > 1e-8
        d_sig = np.einsum('...st,...t->...s', D, d_eps)
        sig += d_sig

        d_gamma = f_trial / (self.E_b + self.K_bar + self.H_bar) * plas
        alpha += d_gamma
        kappa += d_gamma
        q += d_gamma * self.H_bar * np.sign(xi_trial)
        w = self.g(kappa)

        sig_e = sig_trial - d_gamma * self.E_b * np.sign(xi_trial)
        sig[:, :, 1] = (1-w)*sig_e

        E_p = -self.E_b / (self.E_b + self.K_bar + self.H_bar) * derivative(self.g, kappa, dx=1e-6) * sig_e \
            + (1 - w) * self.E_b * (self.K_bar + self.H_bar) / \
            (self.E_b + self.K_bar + self.H_bar)

        D[:, :, 1, 1] = (1-w)*self.E_b*elas + E_p*plas

        return sig, D, alpha, q, kappa
Esempio n. 23
0
    def simulateDeltaWithTime(self, timeSteps):
        opt=copy.copy(self.option)
        spotPrice=copy.copy(opt.S0)
        mechanism=self.mechanism
        
        plotDf=pd.DataFrame(np.zeros([len(timeSteps), 3]), columns=['TimeToMaturity', 'DA_Delta', 'BLS_Delta'])
        plotDf['TimeToMaturity']=timeSteps
        
        def optPrice(assetPrice):
            opt.S0=assetPrice

            orders=self.traders.getOrders(opt, self.numOrders)
            orders=mechanism.clearOrders(orders)
       
            return mechanism.getPrice(orders)
        
        for i, p in enumerate(timeSteps):
            opt.T=p            
            plotDf.ix[i]['DA_Delta']=derivative(optPrice, x0=spotPrice, dx=20)
            
            opt.S0=spotPrice
            plotDf.ix[i]['BLS_Delta']=opt.delta()
            
            print i
     
        return plotDf
 def core_energy_balance(self, T_cmb, core_flux):
     pc = self.params.core
     core_surface_area = self.outer_surface_area
     if self.params.source == 'Stevenson_1983' :
         inner_core_surface_area = np.power(self.inner_core_radius(T_cmb), 2.0) * 4. * np.pi
         dRi_dTcmb = 0.
         try:
             dRi_dTcmb = derivative( self.inner_core_radius, T_cmb, dx=1.0)
         except ValueError:
             pass
     elif self.params.source == 'Driscoll_2014' :
         dRi_dTcmb = 0.
         inner_core_surface_area = 0.
         # Eqn 29 & 30 from the Driscoll_2014 paper. Note that Eqn 32 in the paper has an error and the form in the code is correct
         sqrt_term_num = (pc.Dn/self.params.R_c0)**2.*np.log(pc.TFe/T_cmb) - 1.
         sqrt_term_den = 2.*(1. - 1./(3.*pc.gamma_c))*(pc.Dn/pc.DFe)**2. - 1.
         if sqrt_term_num/sqrt_term_den > 0 :
             R_ic = self.params.R_c0*np.sqrt(sqrt_term_num/sqrt_term_den)
             print('\n\n R_ic={0:.3f}'.format(R_ic/1e3))
             inner_core_surface_area = np.power(R_ic, 2.0) * 4. * np.pi
             dRi_dTcmb = -1.*((self.params.R_c0/2./T_cmb)*(pc.Dn/self.params.R_c0)**2.)/(sqrt_term_num*sqrt_term_den)
     else :
         raise ValueError('parameter class is not recognized')
     # print('\n\n ratio={0:.1f}'.format(inner_core_surface_area/core_surface_area))
     thermal_energy_change = pc.rho*pc.C*self.volume*pc.mu
     latent_heat = -pc.L_Eg * pc.rho * inner_core_surface_area * dRi_dTcmb
     dTdt = -core_flux * core_surface_area / (thermal_energy_change-latent_heat)
     dTdt = -core_flux * core_surface_area / (thermal_energy_change)
     return dTdt
Esempio n. 25
0
    def fitBinCuts(self):
        print("INFO: Fit bin edges iteratively")
        self.splines =[lambda x: 0.5]*21
        fitboundaries = lambda n: [-0.001,-1.5+np.sqrt(n)*0.1]
        converged = True
        for n in range(2,16):
            scan_c = np.logspace(*fitboundaries(n))
            roots = []
            guess = min(0.095 * n,0.95)
            scan_copy = []
            for c in scan_c:

                x_0_p = guess * c

                d_sign_dx = lambda x: derivative(lambda y: self.signN(y,c,n),x,dx=0.0001*c)
                opt = optimize.root(d_sign_dx,x_0_p)
                x_0 = opt.x[0]
                if opt.success and 0 < x_0 < c:
                    guess = x_0/c
                    roots.append(x_0)
                    scan_copy.append(c)
                else:
                    print "root not found" 
                    
            try:
                q = UnivariateSpline(np.log10(scan_copy[::-1]),np.log10(np.array(roots)[::-1]),s=0.0001)
                self.splines[n] = q
                print "parameters for n="+str(n)+" found"
            except:
                print "ERROR: fit failed"
                converged = False
                break

        return converged
    def diff2(self, i, j):
        """
        N.diff2(i,j)

        Mixed second derivative. Differentiates wrt both indices.
        """

        old_val = copy(self[j])

        if not self.stochastic_indices[i][0] in self.stochastic_indices[j][0].moral_neighbors:
            return 0.

        def diff_for_diff(val):
            self[j] = val
            return self.diff(i)

        d = derivative(
            func=diff_for_diff,
            x0=old_val,
            dx=self.eps[j],
            n=1,
            order=self.diff_order)

        self[j] = old_val
        return d
Esempio n. 27
0
File: helpers.py Progetto: adrn/gala
def partial_derivative(func, point, dim_ix=0, **kwargs):
    xyz = np.array(point, copy=True)

    def wraps(a):
        xyz[dim_ix] = a
        return func(xyz)
    return derivative(wraps, point[dim_ix], **kwargs)
Esempio n. 28
0
 def testDerivative2(self):
     conec = [(1, 3), (2, 3), (0, 3), \
              (1, 4), (0, 4), \
              (3, 4), (4, 5), (0, 5),
              (4, 6), (3, 6), (5, 6) ]
     net = ffnet(conec)
     y1n, y2n = net.derivative([1, 1])[0]
     from scipy.misc import derivative
     def func1(x):
         return net([x, 1])[0]
     def func2(x):
         return net([1, x])[0]
     y1 = derivative(func1, 1, dx=0.001)
     y2 = derivative(func2, 1, dx=0.001)
     self.assertAlmostEqual(y1n, y1, 7)
     self.assertAlmostEqual(y2n, y2, 7)
Esempio n. 29
0
	def sigma(self, theta, observations=None, n=1):
		"""
		Estimate the quality of the MLE.

		:param theta: The parameters theta of the density
		:param observations: A list of observation vectors
		:param n: Number of observations
		:return: The variances corresponding to the maximum likelihood estimates of theta (quality of the estimation) as 1-d array (i.e. diagonal of the cov matrix)

		.. note:: Either the observations vector or n have to be provided.
		"""
		l2d = []
		if observations is not None:
			n = 1
			func = self._get_nll_func(observations)
			for i in range(len(theta)):
				#Bring it in a form that we can derive
				f = lambda ti, t0, tn: func(list(t0) + [ti] + list(tn))
				l2d.append(derivative(f, theta[i], dx=1e-5, n=2, args=(theta[0:i], theta[i + 1:])))
		else:
			#Fisher Information
			for i in range(len(theta)):
				fisher = self.get_fisher_function()
				result = fisher(theta, i)

				l2d.append(result)

		return 1.0 / np.sqrt(np.array(l2d) * n)
Esempio n. 30
0
def test_EQ127_more():
    # T derivative
    coeffs = (3.3258E4, 3.6199E4, 1.2057E3, 1.5373E7, 3.2122E3, -1.5318E7, 3.2122E3)
    diff_1T = derivative(EQ127, 50,  dx=1E-3, order=21, args=coeffs)
    diff_1T_analytical = EQ127(50., *coeffs, order=1)
    assert_allclose(diff_1T, diff_1T_analytical, rtol=1E-3)
    assert_allclose(diff_1T, 0.000313581049006, rtol=1E-4)
    
    # Integral
    int_50 = EQ127(50., *coeffs, order=-1) 
    int_20 = EQ127(20., *coeffs, order=-1)
    numerical_1T = quad(EQ127, 20, 50, args=coeffs)[0]
    assert_allclose(int_50 - int_20, numerical_1T)
    assert_allclose(numerical_1T, 997740.00147014)
    
    # Integral over T
    T_int_50 = EQ127(50., *coeffs, order=-1j)
    T_int_20 = EQ127(20., *coeffs, order=-1j)
    
    to_int = lambda T :EQ127(T, *coeffs)/T
    numerical_1_over_T = quad(to_int, 20, 50)[0]
    assert_allclose(T_int_50 - T_int_20, numerical_1_over_T)
    assert_allclose(T_int_50 - T_int_20, 30473.9971912935)

    with pytest.raises(Exception):
        EQ127(20., *coeffs, order=1E100)
Esempio n. 31
0
    def eta_q(self, eigenval):
        nu = self.nu()

        f = lambda x: m.whitw((1 - nu) / 2, x / 2, 1 / (2 * self.b))
        return complex(-derivative(f, eigenval, dx=1e-12))
    def lltscale(scale, y, loc, df):
        return np.log(stats.t.pdf(y, df, loc=loc, scale=scale))

    def llnorm(y, loc, scale):
        return np.log(stats.norm.pdf(y, loc=loc, scale=scale))

    def llnormloc(loc, y, scale):
        return np.log(stats.norm.pdf(y, loc=loc, scale=scale))

    def llnormscale(scale, y, loc):
        return np.log(stats.norm.pdf(y, loc=loc, scale=scale))

    if verbose:
        print('\ngradient of t')
        print(misc.derivative(llt, 1, dx=1e-6, n=1, args=(0, 1, 10), order=3))
        print('t ', locscale_grad(1, 0, 1, tstd_dlldy, 10))
        print('ts', locscale_grad(1, 0, 1, ts_dlldy, 10))
        print(
            misc.derivative(llt, 1.5, dx=1e-10, n=1, args=(0, 1, 20),
                            order=3), )
        print('ts', locscale_grad(1.5, 0, 1, ts_dlldy, 20))
        print(
            misc.derivative(llt, 1.5, dx=1e-10, n=1, args=(0, 2, 20),
                            order=3), )
        print('ts', locscale_grad(1.5, 0, 2, ts_dlldy, 20))
        print(
            misc.derivative(llt, 1.5, dx=1e-10, n=1, args=(1, 2, 20),
                            order=3), )
        print('ts', locscale_grad(1.5, 1, 2, ts_dlldy, 20))
        print(
Esempio n. 33
0
def r1(x):  #r' function (derivative)
    return derivative(r, x)  #gradient method for attaining derivatives
Esempio n. 34
0
 def expected_grad(s, c, r):
   u = sp_special.gammainc(c, s * r)
   delta = 1e-4
   return sp_misc.derivative(
       lambda x: sp_special.gammaincinv(x, u), c, dx=delta * c) / r
Esempio n. 35
0
# use the displayed result from part a to directly calculate the true acceleration
# specify the acceleration
def ax_ref(t):
    return np.exp(-1.0*np.asarray(t))
def ay_ref(t):
    return -18.0*np.cos(3.0*np.asarray(t))
at_ref = np.sqrt(np.add(np.square(ax_ref(tspan)),np.square(ay_ref(tspan))))

# use the numpy and scipy numerical method derivative() to calculate the derivative
# specify the position function
def rx(t):
    return np.exp(np.divide(-t,T1))
def ry(t):
    return np.multiply(2.0,np.cos(np.divide(t,T2)))
# calculate the derivative of pos function rx and ry, and return the acceleration function
a = lambda t:np.sqrt(np.add(np.square(derivative(rx,t,dx=1e-5,n=2)), np.square(derivative(ry,t,dx=1e-5,n=2))))
# calculate the acceleration across the time span
for t_index in np.arange(dt):
    at[t_index] = a(tspan[t_index])
#plot the absolute acceleration
fig = plt.figure(figsize = (15,10))
ax = fig.add_subplot(1,1,1)
for tick in ax.xaxis.get_major_ticks():
    tick.label.set_fontsize(25) 
for tick in ax.yaxis.get_major_ticks():
    tick.label.set_fontsize(25) 
plt.plot(tspan,at_ref,'r-')
plt.xlabel('Time(s)',fontsize=30)
plt.ylabel('Acceleration Magnitude',fontsize=30)
plt.title('Direct Method Using Accleration Expression',fontsize=30)
print('Plotting the acceleration plot...')
Esempio n. 36
0
        def dy_dt_func(t, Y):

            dy_dt = np.zeros(len(Y))

            svp = f.svp_liq(Y[ITEMP])
            svp_ice = f.svp_ice(Y[ITEMP])

            # vapour mixing ratio
            WV = c.eps * Y[IRH_ICE] * svp / (Y[IPRESS_ICE] - svp)
            # liquid mixing ratio
            WL = sum(YLIQ[IND1:IND2] * YLIQ[0:IND1])
            # ice mixing ratio
            WI = sum(Y[IND1:IND2] * Y[0:IND1])

            Cpm = c.CP + WV * c.CPV + WL * c.CPW + WI * c.CPI

            # RH with respect to ice
            RH_ICE = WV / (c.eps * svp_ice / (Y[IPRESS_ICE] - svp_ice))
            # ------------------------- growth rate of ice --------------------------
            RH_EQ = 1e0  # from ACPIM, FPARCELCOLD - MICROPHYSICS.f90

            CAP = f.CAPACITANCE01(Y[0:IND1], np.exp(Y[IND2:IND3]))

            growth_rate = f.ICEGROWTHRATE(Y[ITEMP_ICE], Y[IPRESS_ICE],
                                          RH_ICE, RH_EQ, Y[0:IND1],
                                          np.exp(Y[IND2:IND3]), CAP)
            growth_rate[np.isnan(growth_rate)] = 0  # get rid of nans
            growth_rate = np.where(Y[IND1:IND2] < 1e-6, 0.0, growth_rate)

            # Mass of water condensing
            dy_dt[:IND1] = growth_rate

            #---------------------------aspect ratio---------------------------------------
            DELTA_RHO = c.eps * svp / (Y[IPRESS_ICE] - svp)
            DELTA_RHOI = c.eps * svp_ice / (Y[IPRESS_ICE] - svp_ice)
            DELTA_RHO = Y[IRH_ICE] * DELTA_RHO - DELTA_RHOI
            DELTA_RHO = DELTA_RHO * Y[IPRESS_ICE] / Y[ITEMP_ICE] / c.RA

            RHO_DEP = f.DEP_DENSITY(DELTA_RHO, Y[ITEMP_ICE])

            # this is the rate of change of LOG of the aspect ratio
            dy_dt[IND2:IND3] = (dy_dt[0:IND1] *
                                ((f.INHERENTGROWTH(Y[ITEMP_ICE]) - 1) /
                                 (f.INHERENTGROWTH(Y[ITEMP_ICE]) + 2)) /
                                (Y[0:IND1] * c.rhoi * RHO_DEP))
            #------------------------------------------------------------------------------
            # Change in vapour content
            dwv_dt = -1 * sum(Y[IND1:IND2] * dy_dt[0:IND1])

            # change in water vapour mixing ratio
            DRI = -1 * dwv_dt

            dy_dt[ITEMP_ICE] = 0.0  #+c.LS/Cpm*DRI

            # if n.Simulation_type.lower() == 'parcel':
            #     dy_dt[ITEMP_ICE]=dy_dt[ITEMP_ICE] + c.LS/Cpm*DRI
            #---------------------------RH change------------------------------------------

            dy_dt[IRH_ICE] = (Y[IPRESS_ICE] - svp) * svp * dwv_dt

            dy_dt[IRH_ICE] = (
                dy_dt[IRH_ICE] - WV * Y[IPRESS_ICE] *
                derivative(f.svp_liq, Y[ITEMP_ICE], dx=1.0) * dy_dt[ITEMP_ICE])
            dy_dt[IRH_ICE] = dy_dt[IRH_ICE] / (c.eps * svp**2)
            #------------------------------------------------------------------------------
            return dy_dt
Esempio n. 37
0
 def partial_derivative(self,func,var=0,point=[]):
     args = point[:]
     def wraps(x):
         args[var] = x
         return func(*args)
     return derivative(wraps,point[var],dx=1e-6)
Esempio n. 38
0
 def xi_p(self, eigenval):
     nu = self.nu()
     func = lambda x: m.whitw((1 - nu) / 2, complex(0, x / 2), 1 / (2 * self.b))
     return complex(derivative(func, eigenval, dx=1e-12))
Esempio n. 39
0
ub = min(rcv_time_ctp[-1], rcv_time_orw[-1])
x = np.arange(lb, ub, 0.1)

ax1 = fig.add_subplot(3, 1, 1)
ax1.plot(rcv_time_ctp, rcv_num_ctp, lw=2, color='b', label='CTP_Receive')
ax1.plot(send_time_ctp, send_num_ctp, 'b--', lw=2, label='CTP_Send')
ax1.plot(rcv_time_orw, rcv_num_orw, lw=2, color='g', label='ORW_Receive')
ax1.plot(send_time_orw, send_num_orw, 'g--', lw=2, label='ORW_Send')
ax1.legend(prop={'size': 6})
#create interpolate curves so that we can use same x axis
f_ctp = interp1d(rcv_time_ctp, rcv_num_ctp)
f_orw = interp1d(rcv_time_orw, rcv_num_orw)

#calculate derivative using interpolated result get from above
xp = np.arange(lb + 1.1, ub - 1.1, 1)
drcv_ctp = derivative(f_ctp, xp, dx=1, n=1)
drcv_orw = derivative(f_orw, xp, dx=1, n=1)
ax2 = fig.add_subplot(3, 1, 2)
ax2.plot(xp, drcv_ctp, label='CTP_Throughput')
ax2.plot(xp, drcv_orw, label='ORW_Throughput')
ax2.legend()

if result['lim']:
    ax3 = fig.add_subplot(3, 1, 3)
    ax3.plot(die_time_orw, die_num_SN_orw, 'b--', label='SN_orw')
    ax3.plot(die_time_orw, die_num_RL_orw, 'r--', label='RL_orw')
    ax3.plot(die_time_orw, die_num_LF_orw, 'g--', label='LF_orw')
    ax3.plot(die_time_ctp, die_num_SN_ctp, color='b', label='SN_ctp')
    ax3.plot(die_time_ctp, die_num_RL_ctp, color='r', label='RL_ctp')
    ax3.plot(die_time_ctp, die_num_LF_ctp, color='g', label='LF_ctp')
Esempio n. 40
0
def fDerivative(x):
    return derivative(f, x)
Esempio n. 41
0
def gDerivative(x):
    return derivative(g, x)
Esempio n. 42
0
import numpy as np
import matplotlib.pyplot as pp
from scipy.misc import derivative


def f(x):
    return x * x * x + x * x - 4 * x + 4


x = np.arange(-10, 10.25, 0.25)
yy = derivative(f, x, dx=1e-6)
y = f(x)
y_maximo = max(y)
index_max = np.argmax(y)
x_maximo = x[index_max]
y_minimo = min(y)
index_min = np.argmin(y)
x_ext = []
y_ext = []
x_minimo = x[index_min]
x_ext.append(x_minimo)
x_ext.append(x_maximo)
y_ext.append(y_minimo)
y_ext.append(y_maximo)
#print (x_minimo,y_minimo,x_maximo,y_maximo)
pp.grid()
pp.ylabel('y', fontsize=16)
pp.xlabel('x', fontsize=16)
pp.scatter(x, y, color='black', label='función')
pp.scatter(x, yy, color='red', label='derivada')
pp.scatter(x_ext, y_ext, color='green', label='puntos extremos')
Esempio n. 43
0
def d_f(x):
    return derivative(f, x)
Esempio n. 44
0
# [5] f(sigma)
# [6] dn/dm:        [h^4/(Mpc^3*M_sun)]
# [7] dn/dlnm:      [h^3/Mpc^3]
# [8] dn/dlog10m:   [h^3/Mpc^3]
# [9] n(>m):        [h^3/Mpc^3]
# [11] rho(>m):     [M_sun*h^2/Mpc^3]
# [11] rho(<m):     [M_sun*h^2/Mpc^3]
# [12] Lbox(N=1):   [Mpc/h]
#"D:\data\MultiDark\PK_DM_CLASS\hmf_highz_medz_lowz_planck\mVector_z_0.09.txt"
#R, M, sigma = n.loadtxt(join(dir, "Pk_DM_CLASS", "MD_z"+str(z0[ int(index) - 1])+"_Msigma.dat"),unpack=True)
# converts to M200c
M = DATA[0]
sigma = DATA[1]
m2sigma = interp1d(M, sigma)
toderive = interp1d(n.log(M), DATA[2])
dlnsigdm = interp1d(M[10:-10], derivative(toderive, n.log(M[10:-10])))

mass = M[10:-10]
jac = dlnsigdm(mass)
sig = m2sigma(mass)
counts = frho(sig) * jac / mass * 1e9

volumes = 10**n.arange(5, 13.1, 0.1)
mass100 = n.ones_like(volumes) * -1
mass10k = n.ones_like(volumes) * -1
mass1M = n.ones_like(volumes) * -1
for ii, volume in enumerate(volumes):  # = 1e9
    counts = frho(sig) * jac / mass * volume
    counts_c = n.array([n.sum(counts[jj:]) for jj in range(len(counts))])
    c2m = interp1d(counts_c, n.log10(mass))
    print ii, n.min(counts_c), n.max(counts_c)
Esempio n. 45
0
 def deriv_rad_pre(z_pre, theta, z_cut):
     this_rad = lambda z: rad_pre(z, theta, z_cut)
     this_drad = derivative(this_rad, z_pre, dx=z_pre * 1e-5)
     return this_drad
Esempio n. 46
0
 def slopeIntCal(x):
     return misc.derivative(intCal, x, dx=0.01)
Esempio n. 47
0
 def deriv_rad_sub(c_sub, beta):
     this_rad = lambda c, beta: rad_sub(c, beta)
     this_drad = derivative(this_rad, csub, dx=csub * 1e-5)
     return this_drad
Esempio n. 48
0
def solve_using_Newtons(guess, FUN, tolerance):

    #Set up max iteration
    max_iteration = 1000
    iteration_index = 0

    #Find the value of FUN based on guess
    x_n = guess
    f_n = FUN(guess)
    df_n = derivative(FUN, x_n, dx=1e-6)

    #Set up lists to hold iteration data
    x_list = []
    y_list = []
    deriv_list = []

    #Iterations to find the best solution within given tolerance
    while abs(f_n) > tolerance and iteration_index <= max_iteration:
        x_list.append(x_n)
        y_list.append(f_n)
        deriv_list.append(df_n)

        #Generate new x to check for solution
        x_n = x_n - (f_n / df_n)
        f_n = FUN(x_n)
        df_n = derivative(FUN, x_n, dx=1e-6)
        #update the iteration index
        iteration_index += 1

        if iteration_index > max_iteration:
            print("Unable to converge")
            return None

    # Loop breaks when a solution within tolerance is found
    # Save the last iteration, which is also the final solution
    x_list.append(x_n)
    y_list.append(f_n)

    # Create plot showing iteration

    # Graphing the function
    x_seq = np.arange(min(x_list) - 1, max(x_list) + 1, 0.1)
    y_seq = []
    for x in x_seq:
        y_seq.append(FUN(x))
    plt.plot(x_seq, y_seq, lw=2)

    # Add points of iteration
    plt.plot(x_list, y_list, "g^")

    # Add point of the final solution
    plt.plot(x_list[len(x_list) - 1], y_list[len(y_list) - 1], "bs")
    # Add the initial point
    plt.plot(x_list[0], y_list[0], "r^")

    # Add line segments of each iterations
    for i in np.arange(1, len(x_list) - 1, 1):
        plt.plot([x_list[i - 1], x_list[i]], [y_list[i - 1], 0], lw=1)
        plt.plot([x_list[i], x_list[i]], [0, y_list[i]], '--')

    plt.show()
    return x_n
Esempio n. 49
0
def FSM():
    global _numTrajectoryPoints
    global _jointsControlData
    global _jointsList
    global PRINT_DEBUG

    # Params for inspection of performance (temp)
    global x_pedal_record
    global y_pedal_record
    global _pedalTrajectoryRight
    initialTrajectoryPoint = 0
    pastInitialTrajectoryPoint = False

    global PEDAL_SINGLE_ROTATION_DURATION
    global _pedalAngularVelocity

    INIT = "INIT"
    PEDAL = "PEDAL"
    UPDATE_PARAMETERS = "UPDATE_PARAMETERS"

    runFSM = True
    currState = INIT
    currTrajectoryPoint = None
    prevTrajectoryPoint = None

    startTime = 0.0
    endTime = 0.0
    currTime = 0.0
    prevTime = 0.0

    ros_right_hip_publisher = rospy.Publisher(
        '/joint_hip_right/joint_hip_right/target', Float32, queue_size=2)
    ros_right_knee_publisher = rospy.Publisher(
        '/joint_knee_right/joint_knee_right/target', Float32, queue_size=2)
    ros_right_ankle_publisher = rospy.Publisher(
        '/joint_foot_right/joint_foot_right/target', Float32, queue_size=2)

    ros_left_hip_publisher = rospy.Publisher(
        '/joint_hip_left/joint_hip_left/target', Float32, queue_size=2)
    ros_left_knee_publisher = rospy.Publisher(
        '/joint_knee_left/joint_knee_left/target', Float32, queue_size=2)
    ros_left_ankle_publisher = rospy.Publisher(
        '/joint_foot_left/joint_foot_left/target', Float32, queue_size=2)

    while runFSM:

        ##############################################
        if currState == INIT:
            ##############################################

            importJointTrajectoryRecord()
            setPedalSingleRotationDuration(PEDAL_SINGLE_ROTATION_DURATION)
            setPedalAngularVelocity()
            interpolateAllJointPositions()

            # printInterpolatedFunctions()

            # Find starting point on the trajectory

            currState = PEDAL

        ##############################################
        if currState == PEDAL:
            ##############################################

            # Initialize state
            if currTrajectoryPoint == None:
                currTrajectoryPoint = _trajectoryStartingPoint
                prevTrajectoryPoint = currTrajectoryPoint
                initialTrajectoryPoint = currTrajectoryPoint
            if startTime == 0.0:
                startTime = time.time()
            if endTime == 0.0:
                endTime = startTime + _trajectoryPointDuration
            if prevTime == 0.0:
                prevTime = time.time()

            currPedalPosXY = getPositionRightFoot()
            x_pedal_record.append(currPedalPosXY[0])
            y_pedal_record.append(currPedalPosXY[1])

            if currTrajectoryPoint == initialTrajectoryPoint and pastInitialTrajectoryPoint:
                print(len(_pedalTrajectoryRight))
                print("Reached starting point")
                for pedal_pos in _pedalTrajectoryRight:
                    plt.plot(pedal_pos[0], pedal_pos[1], '*')
                plt.plot(x_pedal_record, y_pedal_record)
                plt.show()
                pastInitialTrajectoryPoint = False

            # Regulate update frequency
            currTime = time.time()
            while float(float(currTime) -
                        float(prevTime)) < (1 / CONTROLLER_FREQUENCY):
                time.sleep(1)
                currPedalPosXY = getPositionRightFoot()
                x_pedal_record.append(currPedalPosXY[0])
                y_pedal_record.append(currPedalPosXY[1])
                currTime = time.time()
            prevTime = currTime

            # Check if trajectory point reached and act accordingly
            if PRINT_DEBUG:
                print("Distance to target: Right foot %0.5f, left foot %0.5f" %
                      (getDistance(getPositionRightFoot(),
                                   _pedalTrajectoryRight[currTrajectoryPoint]),
                       getDistance(getPositionLeftFoot(),
                                   _pedalTrajectoryLeft[currTrajectoryPoint])),
                      end='\r')

            if (getDistance(getPositionRightFoot(),
                            _pedalTrajectoryRight[currTrajectoryPoint]) <=
                    PEDAL_POSITION_ERROR_TOLERANCE
                    and getDistance(getPositionLeftFoot(),
                                    _pedalTrajectoryLeft[currTrajectoryPoint])
                    <= PEDAL_POSITION_ERROR_TOLERANCE and currTime >= endTime):
                pastInitialTrajectoryPoint = True
                prevTrajectoryPoint = currTrajectoryPoint
                if currTrajectoryPoint < (_numTrajectoryPoints - 1):
                    currTrajectoryPoint += 1
                elif currTrajectoryPoint >= (_numTrajectoryPoints - 1):
                    currTrajectoryPoint = 0
                if PRINT_DEBUG:
                    print("UPDATING TRAJECTORY POINT. NEW POINT: %s" %
                          currTrajectoryPoint)
                startTime = time.time()
                endTime = startTime + _trajectoryPointDuration
                for thisJointName in _jointsList:
                    _jointsControlData[thisJointName]["pos_error_integral"] = 0

            # Iterate through joints and update setpoints
            for thisJointName in _jointsList:

                rightSide = False
                leftSide = False

                thisJointPositionGoalpoint = None
                prevJointPositionGoalpoint = None
                if thisJointName == RIGHT_HIP_JOINT:
                    thisJointPositionGoalpoint = _hipTrajectoryRight[
                        currTrajectoryPoint]
                    prevJointPositionGoalpoint = _hipTrajectoryRight[
                        prevTrajectoryPoint]
                    rightSide = True
                elif thisJointName == RIGHT_KNEE_JOINT:
                    thisJointPositionGoalpoint = _kneeTrajectoryRight[
                        currTrajectoryPoint]
                    prevJointPositionGoalpoint = _kneeTrajectoryRight[
                        prevTrajectoryPoint]
                    rightSide = True
                elif thisJointName == RIGHT_ANKLE_JOINT:
                    thisJointPositionGoalpoint = _ankleTrajectoryRight[
                        currTrajectoryPoint]
                    prevJointPositionGoalpoint = _ankleTrajectoryRight[
                        prevTrajectoryPoint]
                    rightSide = True
                elif thisJointName == LEFT_HIP_JOINT:
                    thisJointPositionGoalpoint = _hipTrajectoryLeft[
                        currTrajectoryPoint]
                    prevJointPositionGoalpoint = _hipTrajectoryLeft[
                        prevTrajectoryPoint]
                    leftSide = True
                elif thisJointName == LEFT_KNEE_JOINT:
                    thisJointPositionGoalpoint = _kneeTrajectoryLeft[
                        currTrajectoryPoint]
                    prevJointPositionGoalpoint = _kneeTrajectoryLeft[
                        prevTrajectoryPoint]
                    leftSide = True
                elif thisJointName == LEFT_ANKLE_JOINT:
                    thisJointPositionGoalpoint = _ankleTrajectoryLeft[
                        currTrajectoryPoint]
                    prevJointPositionGoalpoint = _ankleTrajectoryLeft[
                        prevTrajectoryPoint]
                    leftSide = True

                thisJointVelocitySetpoint = None
                # USE DERIVATIVE OF INTERPOLATED JOINT ANGLE FUNCTION
                if rightSide:
                    # currGoalPedalAngle = _pedalTrajectoryRight[currTrajectoryPoint] + (time.time() - startTime)*_pedalAngularVelocity
                    # currPedalError = currGoalPedalAngle - getCurrentAngle(getPositionRightFoot())
                    timeSpent = (time.time() - startTime)
                    if timeSpent > endTime - startTime:
                        timeSpent = endTime - startTime
                    currGoalJointAngle = prevJointPositionGoalpoint + timeSpent * _pedalAngularVelocity
                    currJointError = currGoalJointAngle - getJointPosition(
                        thisJointName)
                    if abs(currJointError) > JOINT_TRAJECTORY_ERROR_TOLERANCE:
                        thisJointVelocitySetpoint = _jointsControlData[
                            thisJointName]["param_p"] * currJointError
                    else:
                        thisJointVelocitySetpoint = derivative(
                            func=_jointsControlData[thisJointName]
                            ["pos_function"],
                            x0=float(getCurrentAngle(getPositionRightFoot())),
                            dx=1e-6) * _pedalAngularVelocity
                elif leftSide:
                    currGoalJointAngle = prevJointPositionGoalpoint + (
                        time.time() - startTime) * _pedalAngularVelocity
                    currJointError = currGoalJointAngle - getJointPosition(
                        thisJointName)
                    if abs(currJointError) > JOINT_TRAJECTORY_ERROR_TOLERANCE:
                        thisJointVelocitySetpoint = _jointsControlData[
                            thisJointName]["param_p"] * currJointError
                    else:
                        thisJointVelocitySetpoint = derivative(
                            func=_jointsControlData[thisJointName]
                            ["pos_function"],
                            x0=float(getCurrentAngle(getPositionLeftFoot())),
                            dx=1e-6) * _pedalAngularVelocity

                thisJointVelocitySetpoint = checkOutputLimits(
                    thisJointVelocitySetpoint)
                # thisJointVelocitySetpoint = thisJointVelocitySetpoint*(-1)

                # print("Velocity setpoint for ", thisJointName, ": ", thisJointVelocitySetpoint)

                if thisJointName == RIGHT_HIP_JOINT:
                    ros_right_hip_publisher.publish(thisJointVelocitySetpoint)
                elif thisJointName == RIGHT_KNEE_JOINT:
                    ros_right_knee_publisher.publish(thisJointVelocitySetpoint)
                elif thisJointName == RIGHT_ANKLE_JOINT:
                    ros_right_ankle_publisher.publish(
                        thisJointVelocitySetpoint)
                elif thisJointName == LEFT_HIP_JOINT:
                    ros_left_hip_publisher.publish(thisJointVelocitySetpoint)
                elif thisJointName == LEFT_KNEE_JOINT:
                    ros_left_knee_publisher.publish(thisJointVelocitySetpoint)
                elif thisJointName == LEFT_ANKLE_JOINT:
                    ros_left_ankle_publisher.publish(thisJointVelocitySetpoint)

        ##############################################
        # if currState == UPDATE_PARAMETERS:
        ##############################################

        # Reload trajectory and PID parameters

    return 1
Esempio n. 50
0
 def deriv_rad_crit_sub(c_sub, theta):
     this_rad = lambda c: rad_crit_sub(c, theta)
     this_drad = derivative(this_rad, c_sub, dx=c_sub * 1e-5)
     return this_drad
Esempio n. 51
0
def w_kernel(coef_aer, coef_ray, tray, taer, ex=0, res=0.03, pressure=1013.25):
    import acolite as ac
    import numpy as np
    from scipy.misc import derivative

    # Construct the the weighted cumulative function
    def fun_grad(r, pressure=1013.25):
        fa = ac.adjacency.acstar3.pred_annular_cdf(
            r, coef_aer, pressure=1)  # aerosol cdf only at normal pressure
        fr = ac.adjacency.acstar3.pred_annular_cdf(
            r, coef_ray, pressure=pressure /
            1013.25)  # normalize pressure to pred_annular_cdf
        ft = (tray * fr + taer * fa) / (tray + taer)
        if type(ft) is np.ndarray:
            ft[np.isnan(ft)] = 0
        else:
            if np.isnan(ft): ft = 0
        return (ft)

    ## if ex == 0 optimize for 60% of diffuse transmittance
    if ex == 0:
        import scipy.optimize

        ## function to optimize
        def of(x, percentage=0.6):
            if type(x) != np.ndarray:
                x = np.asarray([x])
            return (abs(fun_grad(x) - percentage))

        ex = scipy.optimize.brent(of)[0]
        print('Optimized ex: {:.2f}km'.format(ex))

    if ex < (res + res / 2):
        print("Radial extent has to be equal of larger than res+res/2")

    ## some np manipulation to get the xy grid
    ## there are probably better functions - but hard to find with no internet :-D
    xvec = np.arange(res / 2, ex, res)
    xvec = np.hstack((-1 * np.flip(xvec), xvec))
    xvec = xvec.reshape(len(xvec), 1)
    xvec = np.tile(xvec, (1, len(xvec)))

    ## in fact xvec is yvec and xvec needs to be turned
    yvec = xvec * 1
    xvec = np.rot90(xvec)

    ## don't flatten now - we can keep 2D
    if False:
        yvec = yvec.flatten()
        xvec = xvec.flatten()

    ## in km
    rm = np.sqrt(np.power(xvec, 2) + np.power(yvec, 2))

    ##
    wm = derivative(fun_grad, rm, dx=0.001) / 2 / np.pi / rm
    wm = wm[1:, ] + wm[:-1, ]
    wm = wm[:, 1:] + wm[:, :-1]
    wm = (res)**2 * wm / 4

    ## recompute center point weight
    rgt = np.sqrt((res)**2 / np.pi)
    xx, yy = np.where(wm == np.nanmax(wm))
    wm[xx, yy] = fun_grad(np.asarray([rgt]))

    return (wm, ex)
Esempio n. 52
0
def get_processed_flow(time,
                       rawflow,
                       fs,
                       SmoothingParam,
                       smoothflag=True,
                       plotflag=False):
    """
    % Inputs:
    %           time:           time signal    
    %           flow:            flow signal
    %           fs:             sampling rate
    %           SmoothParam:    smoothing parameters used to fitting the flow
    %                           shape, set between 0.85 to 0.95, the lower the
    %                           value, the smoother the signal.
    %           smoothflag:     set to 1 if use low pass filter
    %           plotflag:       plot graphs
    """
    # Diagnostic Stuff
    print('num points in time = ', len(time))
    print('num points in flow = ', len(rawflow))

    ## Step 1: Smooth the data
    if smoothflag:
        lf = 2.0  #cutoff frequency (Hz)
        flow = zerophase_lowpass(rawflow, lf, fs)
    else:
        flow = rawflow

    # remove mean
    flow = flow - np.mean(flow)

    ## Step 2: fit a spline to the flow data
    # Fit a spline through the smoothed data
    flow_model = interpolate.UnivariateSpline(time, flow, s=0)

    ## Step 3: Get the second derivative
    d2 = derivative(flow_model, x0=time, n=2, dx=15 / fs)

    ## Step 4: Find the peaks
    i_peaks = breath_detect_coarse(flow, fs, plotflag=False)
    if len(i_peaks >= 2):
        ## Step 5: Loop through the peaks
        i_valleys = []  #valleys
        i_infl_points = []  #inflection points
        for i in range(len(i_peaks) - 1):
            # get the range of the indices between current peak and next peak (ie peak-to-peak = pp)
            if i < len(i_peaks):
                i_range_pp = np.arange(i_peaks[i], i_peaks[i + 1])
                #print(f'looking at peak {i} at index {i_peaks[i]} and time {time[i_peaks[i]]}')
                #print(f'Index range = {i_range_pp}')
            else:
                i_range_pp = np.arange(i_peaks[i], len(flow))

            # 5a - find the minimum of the flow between the peak and next peak
            i_valley = i_range_pp[np.argmin(flow[i_range_pp])]
            #print(f'found valley at index {i_valley} and time {time[i_valley]}')
            i_valleys.append(i_valley)

            # 5b - find the maximum of the 2nd derivative between the valley and the peak
            # but only look between a certain min and max percentage of the breath
            min_pct = 0.5
            max_pct = 0.9
            len_range = i_range_pp[-1] - i_valley

            i_range_vp = np.arange(i_valley + int(min_pct * len_range),
                                   i_valley + int(max_pct * len_range))
            #print(f'found valley at index {i_valley} and time {time[i_valley]}')

            i_infl_point = i_range_vp[np.argmax(d2[i_range_vp])]
            i_infl_points.append(i_infl_point)

        ## Step 6: Fit a spline through the first and last points and all the inflection points
        i_to_fit = [0] + i_infl_points + [len(flow) - 1]
        vol = np.cumsum(flow) / fs
        drift_model = interpolate.interp1d(time[i_to_fit],
                                           vol[i_to_fit],
                                           kind='cubic')
        vol_drift = drift_model(time)

        vol_corr = vol - vol_drift

        ## Step 7: Get the last tidal volume
        i_since_last_breath = np.arange(i_infl_points[-1], len(flow))

        print(
            f'index of last inflection point is: {i_infl_points[-1]}, and the most recent index is {len(flow)})'
        )
        vol_last_peak = np.max(vol_corr[i_since_last_breath])
        i_last_peak = i_since_last_breath[np.argmax(
            vol_corr[i_since_last_breath])]
        print('Last Breath VT = %0.2f L' % vol_last_peak)

        if plotflag:
            plt.figure(figsize=(10, 10))
            plt.subplot(3, 1, 1)
            plt.title('On-the-fly Tidal Volume Correction', fontsize=24)
            plt.plot(time, rawflow, label='Raw Flow Signal')
            plt.plot(time, flow, label='Smoothed Flow Signal')
            plt.plot(time[i_peaks],
                     flow[i_peaks],
                     'g^',
                     label='Peak Exhalation')
            plt.plot(time[i_valleys],
                     flow[i_valleys],
                     'ro',
                     label='Peak Inhalation')
            plt.plot(time[i_infl_points],
                     flow[i_infl_points],
                     'k*',
                     label='Start of Breath')
            plt.ylabel('Flow (L/s)', fontsize=14)
            plt.grid('on')
            plt.legend()

            plt.subplot(3, 1, 2)
            plt.plot(time, d2, label='Second Derivative')
            plt.plot(time[i_infl_points],
                     d2[i_infl_points],
                     'k*',
                     label='Start of Breath')
            plt.ylabel('Second Derivative of Flow', fontsize=14)
            plt.grid('on')
            plt.legend()

            plt.subplot(3, 1, 3)
            plt.plot(time, vol_corr, label='Corrected Volume')
            plt.plot(time[i_infl_points],
                     vol_corr[i_infl_points],
                     'k*',
                     label='Start of Breath')
            plt.plot(time[i_last_peak],
                     vol_corr[i_last_peak],
                     'g^',
                     label='Last VT = %0.2f L' % vol_last_peak)
            plt.plot(time[i_since_last_breath],
                     vol_corr[i_since_last_breath],
                     label='Last Breath')
            plt.xlabel('time (s)', fontsize=14)
            plt.ylabel('Tidal Volume (L)', fontsize=14)
            plt.legend()
            plt.grid('on')

            plt.tight_layout()
    else:
        i_valleys = []
        i_infl_points = []
        vol_last_peak = []
        vol_corr = np.cumsum(flow) / fs
    return i_peaks, i_valleys, i_infl_points, vol_last_peak, flow, vol_corr
Esempio n. 53
0
        variance = a + np.dot(np.dot(phi_new[i, :].transpose(), S),
                              phi_new[i, :].transpose())
        var.append(variance)
    return f, var


a = 0.1  # noise variance
b = 1
m = 4  # order of polynormial bases
# generate 11 data points D(x,y) of equally spaced samples x[0, 3], t are noisy observations of sinc function
x = np.arange(0, 3.1, 0.3)
t = np.sinc(x) + np.random.normal(0, a, len(x))

# generate 5 derivative data points Dd(xd,yd) equally spaced samples x[0, 3], t are noisy observations of derivative sinc function
xd = np.arange(0.1, 3.1, 0.72)
td = derivative(np.sinc, xd) + np.random.normal(0, a, len(xd))

# generate 100 equally spaced points between x[0,3]
x_new = np.arange(0, 3.0, 0.03)

phi = Phi(x, m)
phid = Phid(xd, m)
phid_new = Phid(x_new, m)
phi_new = Phi(x_new, m)

# maximum likelihood prediction of f' using D(x,y)
fd1_ML = ML_f(phi, t, phid_new)
td1_ML = ML_f(phi, t, phid)
std1_ML = np.sqrt(np.average(np.absolute(td1_ML - td)))

# maximum likelihood prediction of f' using D(x,y) and Dd(xd, yd)
 def D_int_halo_z(self, z):
     """ Derivative of star formation rate integral over halo mass function
     """
     return derivative(lambda z: self.int_halo(self.f_star, z),
                       x0=z,
                       dx=z * 1e-2)
Esempio n. 55
0
def grad(d, arr):
    x = arr[0]
    y = arr[1]
    dd1 = lambda a: d([a, y])
    dd2 = lambda b: d([x, b])
    return np.array([derivative(dd1, x), derivative(dd2, y)])
Esempio n. 56
0
 def hE_T(T):
     to_diff = lambda T: gE_T(T) / T
     return -derivative(to_diff, T, dx=1E-5, order=7) * T**2
Esempio n. 57
0
        def dy_dt_func(t, Y):

            dy_dt = np.zeros(len(Y))

            # add condensed semi-vol mass into bins
            if n.SV_flag:
                MBIN2[-1 * n.n_sv:, :] = np.reshape(Y[INDSV1:INDSV2],
                                                    [n.n_sv, nbins * nmodes])
            # calculate saturation vapour pressure over liquid
            svp1 = f.svp_liq(Y[ITEMP])
            # saturation ratio
            SL = svp1 * Y[IRH] / (Y[IPRESS] - svp1)
            SL = (SL * Y[IPRESS] / (1 + SL)) / svp1

            # water vapour mixing ratio
            WV = c.eps * Y[IRH] * svp1 / (Y[IPRESS] - svp1)
            WL = np.sum(Y[IND1:IND2] * Y[:IND1])  # LIQUID MIXING RATIO
            WI = np.sum(YICE[IND1:IND2] * YICE[:IND1])  # ice mixing ratio
            RM = c.RA + WV * c.RV

            CPM = c.CP + WV * c.CPV + WL * c.CPW + WI * c.CPI

            if simulation_type.lower() == 'chamber':
                # CHAMBER MODEL - pressure change
                dy_dt[IPRESS] = -100 * PRESS1 * PRESS2 * np.exp(-PRESS2 *
                                                                (time + t))
            elif simulation_type.lower() == 'parcel':
                # adiabatic parcel
                dy_dt[IPRESS] = -Y[IPRESS] / RM / Y[
                    ITEMP] * c.g * w  #! HYDROSTATIC EQUATION
            else:
                print('simulation type unknown')
                return

    # ----------------------------change in vapour content: -----------------------
    # 1. equilibruim size of particles
            if n.kappa_flag:
                #if n.SV_flag:
                # need to recalc kappa taking into acount the condensed semi-vols
                Kappa = np.sum(
                    (MBIN2[:, :] / RHOBIN2[:, :]) * KAPPABIN2[:, :],
                    axis=0) / np.sum(MBIN2[:, :] / RHOBIN2[:, :], axis=0)
                #  print(Kappa)
                #  print(MBIN2/RHOBIN2)
                KK01 = f.kk01(Y[0:IND1], Y[ITEMP], MBIN2, RHOBIN2, Kappa)

            else:
                KK01 = f.K01(Y[0:IND1], Y[ITEMP], MBIN2, n.n_sv, RHOBIN2,
                             NUBIN2, MOLWBIN2)

        #  print(KK01[0])
            Dw = KK01[2]  # wet diameter
            RHOAT = KK01[1]  # density of particles inc water and aerosol mass
            RH_EQ = KK01[0]  # equilibrium RH
            #  print(MBIN2/MOLWBIN2)
            # 2. growth rate of particles, Jacobson p455
            # rate of change of radius
            growth_rate = f.DROPGROWTHRATE(Y[ITEMP], Y[IPRESS], SL, RH_EQ,
                                           RHOAT, Dw)
            growth_rate[np.isnan(growth_rate)] = 0  # get rid of nans
            growth_rate = np.where(Y[IND1:IND2] < 1e-9, 0.0, growth_rate)

            # 3. Mass of water condensing
            # change in mass of water per particle
            dy_dt[:IND1] = (np.pi * RHOAT * Dw**2) * growth_rate

            # 4. Change in vapour content
            # change in water vapour mixing ratio
            dwv_dt = -1 * np.sum(
                Y[IND1:IND2] *
                dy_dt[:IND1])  # change to np.sum for speed  # mass
            # -----------------------------------------------------------------------------

            if simulation_type.lower() == 'chamber':
                # CHAMBER MODEL - temperature change
                dy_dt[ITEMP] = -Temp1 * Temp2 * np.exp(-Temp2 * (time + t))
            elif simulation_type.lower() == 'parcel':
                # adiabatic parcel
                dy_dt[ITEMP] = RM / Y[IPRESS] * dy_dt[IPRESS] * Y[
                    ITEMP] / CPM  # TEMPERATURE CHANGE: EXPANSION
                dy_dt[ITEMP] = dy_dt[ITEMP] - c.LV / CPM * dwv_dt
            else:
                print('simulation type unknown')
                return

    # --------------------------------RH change------------------------------------
            dy_dt[IRH] = svp1 * dwv_dt * (Y[IPRESS] - svp1)
            dy_dt[IRH] = dy_dt[IRH] + svp1 * WV * dy_dt[IPRESS]
            dy_dt[IRH] = (
                dy_dt[IRH] - WV * Y[IPRESS] *
                derivative(f.svp_liq, Y[ITEMP], dx=1.0) * dy_dt[ITEMP])
            dy_dt[IRH] = dy_dt[IRH] / (c.eps * svp1**2)
            # -----------------------------------------------------------------------------

            # ------------------------------ SEMI-VOLATILES -------------------------------
            if n.SV_flag:
                #      SV_mass = np.reshape(Y[INDSV1:INDSV2],[n.n_sv,n.nmodes*n.nbins])
                #     SV_mass = np.where(SV_mass == 0.0,1e-30,SV_mass)
                #    MBIN2[n.n_sv*-1:,:] = SV_mass

                RH_EQ_SV = f.K01SV(Y[:IND1], Y[ITEMP], MBIN2, n.n_sv, RHOBIN2,
                                   NUBIN2, MOLWBIN2)

                RH_EQ = RH_EQ_SV[0]
                RHOAT = RH_EQ_SV[1]
                DW = RH_EQ_SV[2]

                SVP_ORG = f.SVP_GASES(n.semi_vols, Y[ITEMP],
                                      n.n_sv)  #C-C equation

                #RH_ORG = [x*Y[IPRESS]/c.RA/Y[ITEMP] for x in Y[IRH_SV]]
                RH_ORG = [x for x in Y[IRH_SV]]
                RH_ORG = [(x / c.aerosol_dict[key][0]) * c.R * Y[ITEMP]
                          for x, key in zip(RH_ORG, n.semi_vols[:n.n_sv])
                          ]  # just for n_sv keys in dictionary
                RH_ORG = [RH_ORG[x] / SVP_ORG[x] for x in range(n.n_sv)]

                dy_dt[INDSV1:INDSV2] = f.SVGROWTHRATE(Y[ITEMP], Y[IPRESS],
                                                      SVP_ORG, RH_ORG, RH_EQ,
                                                      DW, n.n_sv, n.nbins,
                                                      n.nmodes, MOLWBIN2)

                dy_dt[IRH_SV] = -np.sum(np.reshape(
                    dy_dt[INDSV1:INDSV2], [n.n_sv, IND1]) * Y[IND1:IND2],
                                        axis=1)  #see line 137

            return dy_dt
Esempio n. 58
0
def df(num):
    return derivative(f, num)
Esempio n. 59
0
def d_f_3(x):
    return round(derivative(f_3, x, dx=1e-3))
Esempio n. 60
0
def test_SimpleHDRModel_nomarg_gradients():

    for k in range(NREPEAT):
        nbins_perdim = np.random.randint(10, 60)
        ncols = np.random.randint(1, 3)
        nobj = np.random.randint(10, 100)
        varpi_fracerror, mags_fracerror = np.random.uniform(0.01, 0.02, 2)

        model = SimpleHRDModel_nomarg()
        nbins, binamps, binmus, binsigs = model.draw_bins(nbins_perdim, ncols)
        absmags, colors, distances =\
            model.draw_properties(binamps, binmus, binsigs, nobj)
        varpi, varpi_err, obsmags, obsmags_err, obscolors, obscolors_err =\
            model.draw_data(absmags, colors, distances,
                            varpi_fracerror, mags_fracerror)

        model.set_data(binmus, binsigs, varpi, varpi_err, obsmags, obsmags_err,
                       obscolors, obscolors_err)

        x = model.combine_params(absmags, distances, colors, binamps)
        absmag_grad, distances_grad, colors_grad, binamps_grad =\
            model.strip_params(model.log_posterior_gradients(x))

        for i in range(nbins):

            def f(d):
                binamps2 = 1 * binamps
                binamps2[i] = d
                x = model.combine_params(absmags, distances, colors, binamps2)
                return model.log_posterior(x)

            binamps_grad2 = derivative(f,
                                       binamps[i],
                                       dx=0.001 * binamps[i],
                                       order=7)
            np.testing.assert_allclose(binamps_grad2,
                                       binamps_grad[i],
                                       rtol=relative_accuracy)

        for i in range(nobj):

            def f(d):
                absmags2 = 1 * absmags
                absmags2[i] = d
                x = model.combine_params(absmags2, distances, colors, binamps)
                return model.log_posterior(x)

            absmag_grad2 = derivative(f,
                                      absmags[i],
                                      dx=0.001 * absmags[i],
                                      order=5)
            np.testing.assert_allclose(absmag_grad2,
                                       absmag_grad[i],
                                       rtol=relative_accuracy)

            def f(d):
                distances2 = 1 * distances
                distances2[i] = d
                x = model.combine_params(absmags, distances2, colors, binamps)
                return model.log_posterior(x)

            distances_grad2 = derivative(f,
                                         distances[i],
                                         dx=0.001 * distances[i],
                                         order=5)
            np.testing.assert_allclose(distances_grad2,
                                       distances_grad[i],
                                       rtol=relative_accuracy)

            for j in range(ncols):

                def f(d):
                    colors2 = 1 * colors
                    colors2[i, j] = d
                    x = model.combine_params(absmags, distances, colors2,
                                             binamps)
                    return model.log_posterior(x)

                colors_grad2 = derivative(f,
                                          colors[i, j],
                                          dx=0.001 * colors[i, j],
                                          order=5)
                np.testing.assert_allclose(colors_grad2,
                                           colors_grad[i, j],
                                           rtol=relative_accuracy)