示例#1
0
	def TacC2_calc(k=None,p=None,fDc=None,fMag=None,a=None,*args,**kwargs):
		C=fDc
		M=fMag
		s21=np.sinh(k * (1 - a))
		s20=np.cosh(k * (1 - a))
		s19=4 * M * k * p ** 2 * s21
		s18=4 * M * k ** 2 * p ** 2 * s20
		s17=4 * C * k ** 3
		s16=2 * k ** 4 * p
		s15=k - 2 * a * k
		s14=8 * C * a * p ** 3
		s13=2 * C * k * p ** 3
		s12=4 * C * k * p ** 2
		s11=4 * C * k ** 2 * p
		s10=8 * C * a * k ** 2 * p
		s9=4 * M * a * k * p ** 3
		s8=2 * k ** 2 * p ** 3
		s7=4 * C * p ** 3
		s6=4 * M * k ** 2 * p
		s5=8 * C * k ** 2
		s4=8 * C * p ** 2
		s3=4 * M * k * p ** 2
		s2=2 * C * k ** 2 * p ** 2
		s1=4 * M * a * k ** 2 * p ** 2
		line1=(s1 + s2) * np.cos(a * p) * np.cosh(a * k) + (s3 - s12 - s17) * np.cos(a * p) * np.sinh(k) + (- s12 - s3) * np.cos(a * p) * np.sinh(a * k) + (- 2 * M * k ** 2 * p ** 2 + s5 + s4) * np.cos(a * p) * np.cosh(k)
		line2=(2 * C * k ** 2 * p ** 2 * s20 - s4 - 4 * C * k * p ** 2 * s21 - s19 - s5 + s18 - 2 * M * k ** 2 * p ** 2 * np.cosh(s15) - 4 * M * a * k ** 2 * p ** 2 * s20) * np.cos(a * p) + (s6 - s7) * np.sin(a * p) * np.cosh(a * k)
		line3=(s13 + 2 * C * k ** 3 * p + 2 * M * k * p ** 3 + 4 * M * k ** 3 * p - 4 * C * a * k * p ** 3 - 4 * C * a * k ** 3 * p - s9 - 4 * M * a * k ** 3 * p) * np.sin(a * p) * np.sinh(k) + (s13 + s9) * np.sin(a * p) * np.sinh(a * k)
		line4=(s14 - s7 - s11 - s6 + s10) * np.sin(a * p) * np.cosh(k) + (s7 + 4 * C * p ** 3 * s20 - s14 + s11 + s6 - s10 - 4 * M * k ** 2 * p * s20 - 2 * C * k * p ** 3 * s21 - 4 * M * k * p ** 3 * s21 + 2 * M * k * p ** 3 * np.sinh(s15) + 4 * M * a * k * p ** 3 * s21) * np.sin(a * p)
		line5=(s17 + 8 * C * k * p ** 2 + s3) * np.sinh(k) - s3 * np.sinh(a * k) + (s1 - s4 - s2 - 4 * M * k ** 2 * p ** 2 - s5) * np.cosh(k) + s5 + s4 - s2 - s19 + s18 - s1
		denom=(k ** 5 * p + k ** 3 * p ** 3) * np.sinh(k) + (- s16 - s8) * np.cosh(k) + s16 + s8
		TacC2=(line1 + line2 + line3 + line4 + line5) / denom
		return TacC2
示例#2
0
    def _get_mean(self, sites, C, ln_y_ref, exp1, exp2, v1):
        """
        Add site effects to an intensity.

        Implements eq. 5
        """
        # we do not support estimating of basin depth and instead
        # rely on it being available (since we require it).
        z1pt0 = sites.z1pt0

        # we consider random variables being zero since we want
        # to find the exact mean value.
        eta = epsilon = 0

        ln_y = (
            # first line of eq. 13b
            ln_y_ref + C['phi1'] *
            np.log(np.clip(sites.vs30, -np.inf, v1) / 1130)
            # second line
            + C['phi2'] * (exp1 - exp2)
            * np.log((np.exp(ln_y_ref) + C['phi4']) / C['phi4'])
            # third line
            + C['phi5']
            * (1.0 - 1.0 / np.cosh(
                C['phi6'] * (z1pt0 - C['phi7']).clip(0, np.inf)))
            + C['phi8'] / np.cosh(0.15 * (z1pt0 - 15).clip(0, np.inf))
            # fourth line
            + eta + epsilon
        )

        return ln_y
示例#3
0
    def computeNextCom(self,p0,x0=[[0,0] , [0,0]],t=0.05):
        px=p0[0]
        py=p0[1]
        '''Compute COM at time  (t  < durrationOfStep*(1-alpha)  ) This function is 
        usefull for MPC implementation '''
        
        #TODO check  t  < durrationOfStep*(1-alpha)  
        w2= self.g/self.h
        w = np.sqrt(w2)
        durrationOfStep = self.durrationOfStep   
        x0_x=np.matrix([[x0[0][0]],
                        [x0[0][1]]])

        x0_y=np.matrix([[x0[1][0]],
                        [x0[1][1]]])
        
        c0_x  =x0_x[0,0]
        c0_y  =x0_y[0,0]
        d_c0_x=x0_x[1,0]
        d_c0_y=x0_y[1,0]

        c_x   =     (c0_x -px) * np.cosh(w*t) + (d_c0_x/w) * np.sinh(w*t)+px
        d_c_x = w*(c0_x -px) * np.sinh(w*t) +     d_c0_x * np.cosh(w*t) 
        c_y   =     (c0_y -py) * np.cosh(w*t) + (d_c0_y/w) * np.sinh(w*t)+py
        d_c_y = w*(c0_y -py) * np.sinh(w*t) +     d_c0_y * np.cosh(w*t) 

        return [c_x , c_y , d_c_x , d_c_y]
示例#4
0
文件: waves.py 项目: ewquon/pylib
def _fenton1985_dispersion_step(w,k,H,d):
    """ Solve eqn 23 in Fenton1985, assuming no mean current (i.e., c_E = 0) using Newton's method.
    NOTE: This approach was found to be numerically unstable unless a relaxation factor was applied at each iteration; however this required > 100 iterations for convergence in the cases tested. 
    """
    kd = k*d
    S = 1./np.cosh(2*kd)
    C0 = np.tanh(kd)**0.5
    dC0 = d/(2*C0*np.cosh(kd)**2)
    C2expr = (2.+7.*S**2)/(4.*(1.-S)**2)
    C2 = C0 * C2expr
    t2kd = np.tanh(2*kd)
    dC2 = \
            dC0 * C2expr \
            + C0 *( -7.*d*t2kd*S**2/(1.-S)**2 - d*t2kd*(7*S**2+2.)*S/(1.-S)**3 )
    C4expr = (4. + 32.*S - 116.*S**2 - 400.*S**3 - 71.*S**4 + 146.*S**5) / (32*(1.-S)**5)
    C4 = C0 * C4expr
    dC4 = \
            dC0 * C4expr \
            + C0 * ( -1460*d*t2kd*S**5 + 568*d*t2kd*S**4 \
                + 2400*d*t2kd*S**3 + 464*d*t2kd*S**2 - 64*d*t2kd*S ) / (32*(1.-S)**5) \
            - C0 * ( 5*d*t2kd*S*(146*S**5-71*S**4-400*S**3-116*S**2+32*S+4) ) \
                    / (16*(1.-S)**6)
    kH_2 = k*H/2.
    F = -w/(g*k)**0.5 + C0 + kH_2**2*C2 + kH_2**4*C4
    J = dC0 + H*kH_2*C2 + kH_2**2*dC2 + 2*H*kH_2**3*C4 + kH_2**4*dC4

    if DEBUG:
        print ' C0:',C0
        print ' C2:',C2
        print ' C4:',C4
        print 'dC0:',dC0
        print 'dC2:',dC2
        print 'dC4:',dC4
    return F,J
示例#5
0
    def test_abcd_lossy_line(self):
        '''
        Lossy transmission line of characteristic impedance Z0, length l
        and propagation constant gamma = alpha + j beta

        ○---------○

        ○---------○

        has ABCD matrix of the form:

        [ cosh(gamma l)       Z0 sinh(gamma l) ]
        [ 1/Z0 sinh(gamma l)  cosh(gamma l) ]
        '''
        l = 5.0
        z0 = 30.0
        alpha = 0.5
        beta = 2.0
        lossy_media = DefinedGammaZ0(
            frequency=Frequency(1, 100, 21, 'GHz'),
            gamma=alpha + 1j*beta,
            z0=z0
            )
        ntw = lossy_media.line(d=l, unit='m', z0=z0)
        gamma = lossy_media.gamma
        npy.testing.assert_array_almost_equal(ntw.a[:,0,0], npy.cosh(gamma*l))
        npy.testing.assert_array_almost_equal(ntw.a[:,0,1], z0*npy.sinh(gamma*l))
        npy.testing.assert_array_almost_equal(ntw.a[:,1,0], 1.0/z0*npy.sinh(gamma*l))
        npy.testing.assert_array_almost_equal(ntw.a[:,1,1], npy.cosh(gamma*l))
示例#6
0
	def unScaled():
		# Set up grid and two-soliton initial data:
		x = (2.*np.pi/N)*np.arange(-N/2,N/2).reshape(N,1)
		A, B = 25., 16.
		A_shift, B_shift = 2., 1.
		y0 = (3.*A**2.*np.cosh(.5*(A*(x+2.)))**(-2.) + 3*B**2.*np.cosh(.5*(B*(x+1.)))**(-2.)).reshape(N,)
		k = np.concatenate(( np.arange(0,N/2) ,
							 np.array([0])	,
							 np.arange(-N/2+1,0,1)	)).reshape(N,)
		ik3 = 1j*k**3.

		def F_unscaled(t,u):
			out = -.5*1j*k*fft(ifft(u,axis=0)**2.,axis=0)  + ik3* u
			return out


		tmax = .006
		dt = .01*N**(-2.)
		nmax = int(round(tmax/dt))
		nplt = int(np.floor((tmax/25.)/dt))
		y0 = fft(y0,axis=0)
		T,Y = RK4(F_unscaled, y0, t0=0, t1=tmax, n=nmax)

		udata, tdata = np.real(ifft(y0,axis=0)).reshape(N,1), np.array(0.).reshape(1,1)
		for n in range(1,nmax+1):
			if np.mod(n,nplt) == 0:
				t = n*dt
				u = np.real( ifft(Y[n], axis=0) ).reshape(N,1)
				udata = np.concatenate((udata,np.nan_to_num(u)),axis=1)
				tdata = np.concatenate((tdata,np.array(t).reshape(1,1)),axis=1)

		return x, tdata, udata
def chainPoints(hh, dd, aa, numberOfPoints) :
    """Generate numberOfPoints points (x,y) along a hanging chain from -dd 
    to dd, given parameter aa. Return lists of x values and y values, each of 
    length numberOfPoints."""
    xs = np.linspace(-dd,dd,numberOfPoints) # [m] x location of points
    ys = aa * np.cosh(xs/aa) + (hh - aa * np.cosh(dd / aa)) # [m] y locations
    return xs, ys
 def height(self,x,t):
     xi = x[0] - self.C*(t-1.0) #offsetting start time
     eta = self.A1/(np.cosh(self.B*xi))**2 + self.A2/(np.cosh(self.B*xi))**4
     # inflowHeightMean already added in wavetank.py
     #        
     # NOTE: x[0] is a vector here for verification only!
     return eta
示例#9
0
def Kw_gelenk_kik(E, A, I, l, u, w):
    """dyn. Steifigkeit Gelenk an k

    :E: @todo
    :A: @todo
    :I: @todo
    :l: @todo
    :u: @todo
    :w: @todo
    :returns: @todo

    """
    lam = l * (u * w**2 / E / I) ** (1/4)
    eps = l * np.sqrt(u * w**2 / E / A)

    o1 = (np.cosh(lam) + np.cos(lam)) / 2
    o2 = (np.sinh(lam) + np.sin(lam)) / 2
    o3 = (np.cosh(lam) - np.cos(lam)) / 2
    o4 = (np.sinh(lam) - np.sin(lam)) / 2

    kik = np.matrix([[E*A/l * eps/np.tan(eps), 0, 0],
                     [0, E*I*lam**3/l**3 * (o1**2 - o2*o4)/(o2*o3 - o1*o4), 0],
                     [0, 0, 0]])

    return kik
示例#10
0
 def pressure(self,x,t):
     """ Gives linearized pressured with P_atm = 0 """
     g = (0.0,0.0,-9.81)
     z = x[2] - self.h        
     p = self.rho_0*(-g[2])*self.A* np.cosh(self.kappa*(z+self.h))/np.cosh(self.kappa*self.h) * \
         np.exp(1j*(self.k[0]*x[0]+self.k[1]*x[1] - self.omega*t))
     return np.real(p)
示例#11
0
    def velocity_u(self,x,t):
        """ Defines a linearized solution to the potential flow
            model in two dimensions (x,y,z) for finite depth,
            as well as, deep and shllow water limits, for slowly
            varying regular wavetrains.

            .. todo:: implement deep & shallow water limits. """
        theta =  self.k[0]*x[0] - self.omega*t # ~ NOTE: x[0] is a vector here!
        dtheta = self.diff*theta
        z = x[2] - self.h
        u = np.zeros(x[0].shape)

        # Finite Depth (0 < kh < infty)
        for i in range(self.N):
            diffPos = (1+self.diff*(i+1))
            diffNeg = (1-self.diff*(i+1))
            u = u + (-self.g[2]*diffPos*self.k[0]*self.A / (diffPos*self.omega)) * \
                np.cosh(diffPos*self.k[0]*(z+self.h))/np.cosh(diffPos*self.k[0]*self.h) * \
                np.exp(1j*(i+1)*(theta+(i+1)*dtheta)) + \
                (-self.g[2]*diffNeg*self.k[0]*self.A / (diffNeg*self.omega)) * \
                np.cosh(diffNeg*self.k[0]*(z+self.h))/np.cosh(diffNeg*self.k[0]*self.h) * \
                np.exp(1j*(i+1)*(theta-(i+1)*dtheta))
        # Deep water (kh >> 1)
        # ... TODO
                 
        # Shallow water (kh << 1)
        # ... TODO

        return np.real(u)
示例#12
0
文件: nle.py 项目: aasgreen/race-num
def u2n(n,y,z,lam,gam,beta):
    #return (beta*fn(n) + c3(n,lam,gam,beta)*np.cosh(kn(n)/lam*y)+c4(n,lam,gam,beta)*np.sinh(kn(n)/lam*y))*np.cos(kn(n)*z)
    top = (beta-beta/np.cosh( kn(n)/lam*gam ) -1.)
    bot = (1-beta*np.tanh( -kn(n)/lam )*np.tanh( kn(n)/lam*gam ) )

    return ( fn(n)*(beta + (top/bot)*( np.cosh( kn(n)*(y/lam) )*( 1+(1-beta)*(bot/top) ) + 
        beta*np.tanh( -kn(n)/lam)*np.sinh( kn(n)*(y/lam) ) )  ) )
def grad(data, QofI='U_avg'):
    M = data.shape[0]

    mu = data[:, 0].reshape((M, 1))
    rho = data[:, 1].reshape((M, 1))
    dpdx = data[:, 2].reshape((M, 1))
    eta = data[:, 3].reshape((M, 1))
    B0 = data[:, 4].reshape((M, 1))

    Ha = B0 / np.sqrt(eta * mu)
    mu0 = 1.0

    if (QofI == 'U_avg'):
        df_dmu = -dpdx * (np.sqrt(eta * mu) / np.tanh(Ha) -
                          B0 / np.sinh(Ha)**2) / (2 * B0 * mu**2)
        df_drho = np.random.uniform(1.0e-8, 1.0e-10, (M, 1))
        df_ddpdx = -(eta * mu - Ha * eta * mu / np.tanh(Ha)) / (mu * B0**2)
        df_deta = -dpdx * (2 * eta * mu - Ha * eta * mu / np.tanh(Ha) -
                           (B0 / np.sinh(Ha))**2) / (2 * eta * mu * B0**2)
        df_dB0 = -dpdx * (-2 * eta * mu + Ha * eta * mu / np.tanh(Ha) +
                          (B0 / np.sinh(Ha))**2) / (mu * B0**3)
    elif (QofI == 'B_ind'):
        df_dmu = -dpdx * mu0 * (np.sqrt(eta * mu) * np.sinh(Ha) - B0) / (
            4 * mu * (B0 * np.cosh(Ha / 2))**2)
        df_drho = np.random.uniform(1.0e-8, 1.0e-10, (M, 1))
        df_ddpdx = mu0 * (B0 - 2 * np.sqrt(eta * mu) * np.tanh(Ha / 2)) / (
            2 * B0**2)
        df_deta = -dpdx * mu0 * (np.sqrt(eta * mu) * np.sinh(Ha) - B0) / (
            4 * eta * (B0 * np.cosh(Ha / 2))**2)
        df_dB0 = -dpdx * mu0 * (B0 + B0 / np.cosh(Ha / 2)**2 - 4 * np.sqrt(
            eta * mu) * np.tanh(Ha / 2)) / (2 * B0**3)

    return np.concatenate((df_dmu, df_drho, df_ddpdx, df_deta, df_dB0), axis=1)
示例#14
0
def CoshXCoshY(data=None, args=None, eqInstance=None, NameOrValueFlag=0):
    if NameOrValueFlag: # name used by cache, must be distinct
        return sys._getframe().f_code.co_name
    try:
        return numpy.cosh(data[0]) * numpy.cosh(data[1])
    except:
        return 1.0E300 * numpy.ones_like(data[0])
示例#15
0
 def pressure(self,x,t):
     """ Gives linearized pressured with P_atm = 0 """
     g = (0.0,0.0,-9.81)
     z = x[2] - self.h
     p = self.rho_0*g[2]*self.A* np.cosh(self.k[0]*(z+self.h))/np.cosh(self.k[0]*self.h) \
         * np.exp(1j*self.theta(x,t))
     return np.real(p)
示例#16
0
    def fgrad_y_psi(self, y, psi, return_covar_chain = False):
        """
        gradient of f w.r.t to y and psi

        returns: NxIx3 tensor of partial derivatives

        """

        # 1. exponentiate the a and b (positive!)
        mpsi = psi.copy()
        w, s, r, d = self.fgrad_y(y, psi, return_precalc = True)

        gradients = np.zeros((y.shape[0], y.shape[1], len(mpsi), 3))
        for i in range(len(mpsi)):
            a,b,c = mpsi[i]
            gradients[:,:,i,0] = (b*(1.0/np.cosh(s[i]))**2).T
            gradients[:,:,i,1] = a*(d[i] - 2.0*s[i]*r[i]*(1.0/np.cosh(s[i]))**2).T
            gradients[:,:,i,2] = (-2.0*a*(b**2)*r[i]*((1.0/np.cosh(s[i]))**2)).T


        if return_covar_chain:
            covar_grad_chain = np.zeros((y.shape[0], y.shape[1], len(mpsi), 3))

            for i in range(len(mpsi)):
                a,b,c = mpsi[i]
                covar_grad_chain[:, :, i, 0] = (r[i]).T
                covar_grad_chain[:, :, i, 1] = (a*(y + c) * ((1.0/np.cosh(s[i]))**2).T)
                covar_grad_chain[:, :, i, 2] = a*b*((1.0/np.cosh(s[i]))**2).T

            return gradients, covar_grad_chain

        return gradients
示例#17
0
    def fgrad_y_psi(self, y, psi, return_covar_chain = False):
        """
        gradient of f w.r.t to y and psi

        returns: NxIx4 tensor of partial derivatives

        """

        mpsi = psi.copy()
        mpsi = mpsi[:self.num_parameters-1].reshape(self.n_terms, 3)

        w, s, r, d = self.fgrad_y(y, psi, return_precalc = True)

        gradients = np.zeros((y.shape[0], y.shape[1], len(mpsi), 4))
        for i in range(len(mpsi)):
            a,b,c  = mpsi[i]
            gradients[:,:,i,0] = (b*(1.0/np.cosh(s[i]))**2).T
            gradients[:,:,i,1] = a*(d[i] - 2.0*s[i]*r[i]*(1.0/np.cosh(s[i]))**2).T
            gradients[:,:,i,2] = (-2.0*a*(b**2)*r[i]*((1.0/np.cosh(s[i]))**2)).T
        gradients[:,:,0,3] = 1.0

        if return_covar_chain:
            covar_grad_chain = np.zeros((y.shape[0], y.shape[1], len(mpsi), 4))

            for i in range(len(mpsi)):
                a,b,c = mpsi[i]
                covar_grad_chain[:, :, i, 0] = (r[i]).T
                covar_grad_chain[:, :, i, 1] = (a*(y + c) * ((1.0/np.cosh(s[i]))**2).T)
                covar_grad_chain[:, :, i, 2] = a*b*((1.0/np.cosh(s[i]))**2).T
            covar_grad_chain[:, :, 0, 3] = y

            return gradients, covar_grad_chain

        return gradients
示例#18
0
def stretching(sc, Vstretching, theta_s, theta_b):
    """
    Computes S-coordinates
    INPUT:
        sc           : normalized levels           [ndarray]
        Vstretching  : ROMS stretching algorithm   [int]
        theta_s      :                             [int] 
        theta_b      :                             [int]
        hc           :                             [int]
    """
    if Vstretching == 1:
        # Song and Haidvogel, 1994
        cff1 = 1.  / np.sinh(theta_s)
        cff2 = 0.5 / np.tanh(0.5*theta_s)
        C = (1.-theta_b) * cff1 * np.sinh(theta_s * sc) + \
            theta_b * (cff2 * np.tanh( theta_s * (sc + 0.5) ) - 0.5)
        return C

    if Vstretching == 4:
        # A. Shchepetkin (UCLA-ROMS, 2010) double vertical stretching function
        if theta_s > 0:
            Csur = ( 1.0 - np.cosh(theta_s*sc) ) / ( np.cosh(theta_s) -1.0 )
        else:
            Csur = -sc**2

        if theta_b > 0:
            Cbot = ( np.exp(theta_b*Csur)-1.0 ) / ( 1.0-np.exp(-theta_b) )
            return Cbot
        else:
            return Csur    
示例#19
0
文件: graph.py 项目: horoshenkih/rgg
def cosh_d(v1, v2):
    r1, phi1 = list(v1)[:2]
    r2, phi2 = list(v2)[:2]

    return max(
        1.0, np.cosh(r1) * np.cosh(r2) - np.sinh(r1) * np.sinh(r2) * np.cos(phi1 - phi2)
    )  # Python precision issues
    def transform(self, X, y=None):
        """Apply approximate feature map to X.

        Parameters
        ----------
        X: array-like, shape (n_samples, n_features)

        Returns
        -------
        X_new: array-like, shape (n_samples, n_features * (2n + 1))
        """

        X = array2d(X)
        # check if X has zeros. Doesn't play well with np.log.
        if (X <= 0).any():
            raise ValueError("Entries of X must be strictly positive.")
        X_new = []
        # zeroth component
        # 1/cosh = sech
        X_new.append(np.sqrt(X * self.sample_interval / np.cosh(0)))

        log_step = self.sample_interval * np.log(X)
        step = 2 * X * self.sample_interval

        for j in xrange(1, self.sample_steps):
            factor = np.sqrt(step / np.cosh(np.pi * j * self.sample_interval))
            X_new.append(factor * np.cos(j * log_step))
            X_new.append(factor * np.sin(j * log_step))
        return np.hstack(X_new)
示例#21
0
    def _get_ln_y_ref(self, rup, dists, C):
        """
        Get an intensity on a reference soil.

        Implements eq. 13a.
        """
        # reverse faulting flag
        Frv = 1. if 30 <= rup.rake <= 150 else 0.
        # normal faulting flag
        Fnm = 1. if -120 <= rup.rake <= -60 else 0.
        # hanging wall flag

        Fhw = np.zeros_like(dists.rx)
        idx = np.nonzero(dists.rx >= 0.)
        Fhw[idx] = 1.

        # a part in eq. 11
        mag_test1 = np.cosh(2. * max(rup.mag - 4.5, 0))

        # centered DPP
        centered_dpp = self._get_centered_cdpp(dists)
        # centered_ztor
        centered_ztor = self._get_centered_ztor(rup, Frv)
        #

        ln_y_ref = (
            # first part of eq. 11
            C['c1']
            + (C['c1a'] + C['c1c'] / mag_test1) * Frv
            + (C['c1b'] + C['c1d'] / mag_test1) * Fnm
            + (C['c7'] + C['c7b'] / mag_test1) * centered_ztor
            + (C['c11'] + C['c11b'] / mag_test1) *
            np.cos(math.radians(rup.dip)) ** 2
            # second part
            + C['c2'] * (rup.mag - 6)
            + ((C['c2'] - C['c3']) / C['cn'])
            * np.log(1 + np.exp(C['cn'] * (C['cm'] - rup.mag)))
            # third part
            + C['c4']
            * np.log(dists.rrup + C['c5']
                     * np.cosh(C['c6'] * max(rup.mag - C['chm'], 0)))
            + (C['c4a'] - C['c4'])
            * np.log(np.sqrt(dists.rrup ** 2 + C['crb'] ** 2))
            # forth part
            + (C['cg1'] + C['cg2'] / (np.cosh(max(rup.mag - C['cg3'], 0))))
            * dists.rrup
            # fifth part
            + C['c8'] * np.fmax(1 - (np.fmax(dists.rrup - 40,
                                np.zeros_like(dists)) / 30.),
                                np.zeros_like(dists))[0]
            * min(max(rup.mag - 5.5, 0) / 0.8, 1.0)
            * np.exp(-1 * C['c8a'] * (rup.mag - C['c8b']) ** 2) * centered_dpp
            # sixth part
            + C['c9'] * Fhw * np.cos(math.radians(rup.dip)) *
            (C['c9a'] + (1 - C['c9a']) * np.tanh(dists.rx / C['c9b']))
            * (1 - np.sqrt(dists.rjb ** 2 + rup.ztor ** 2)
               / (dists.rrup + 1.0))
        )

        return ln_y_ref
示例#22
0
def regression_test(U, X, N, comm, rank, L, FST, ST, U0, U_hat0,**kw):
    Ha = config.Ha
    u_exact = ( cosh(Ha) - cosh(Ha*X[0,:,0,0]))/(cosh(Ha) - 1.0)
    if rank == 0:
        print "Time %2.5f Error %2.12e" %(config.t, linalg.norm(u_exact-U[1,:,0,0],inf))
        plt.plot(X[0,:,0,0], U[1,:,0,0], X[0,:,0,0], u_exact,'*r')
        plt.show()
示例#23
0
def init(U, U_hat, X, FST, ST, SN, t=0.):
    Ha = config.Ha
    B_strength = config.B_strength
    for i in range(U.shape[1]):
        x = X[0, i, 0, 0]
        for j in range(U.shape[2]):
            y = X[1, i, j, 0]
            u = 0. 
            v = (cosh(Ha)-cosh(Ha*x))/(cosh(Ha)-1.0)
            Bx = (sinh(Ha*x)-Ha*x*cosh(Ha))/(Ha**2*cosh(Ha))
            By = B_strength
            U[0, i, j, :] = u
            U[1, i, j, :] = v
            U[3, i, j, :] = Bx
            U[4, i, j, :] = By
    U[2] = 0
    U[5] = 0
    for i in range(6):
        if i<3:
            U_hat[i] = FST.fst(U[i], U_hat[i], ST)
        else:
            U_hat[i] = FST.fst(U[i], U_hat[i], SN)
        
    for i in range(6):
        if i<3:
            U[i] = FST.ifst(U_hat[i], U[i], ST)
        else:
            U[i] = FST.ifst(U_hat[i], U[i], SN)
            
    for i in range(6):
        if i<3:
            U_hat[i] = FST.fst(U[i], U_hat[i], ST)
        else:
            U_hat[i] = FST.fst(U[i], U_hat[i], SN)
示例#24
0
文件: KLJPA.py 项目: edumur/paramp
    def reflection_theory(self, f):
        """
        Return the theoretical reflection of the taper.
        As a theoreticalk result this reflection doesn't take into account the
        impedance of the LJPA.

        Parameters
        ----------
        f : float, np.ndarray
            Frequency in GHz.
        """

        v = (self.beta(f)*self.l)**2. - self.A()**2.

        if type(f) is float:
            if v < 0:
                c = np.cosh(np.sqrt(self.A()**2. - (self.beta(f)*self.l)**2.))
            else:
                c = np.cos(np.sqrt((self.beta(f)*self.l)**2. - self.A()**2.))
        else:
            c = np.ones_like(v)
            c[v<0] = np.cosh(np.sqrt(self.A()**2. - (self.beta(f[v<0])*self.l)**2.))
            c[v>0] = np.cos(np.sqrt((self.beta(f[v>0])*self.l)**2. - self.A()**2.))

        return self.gm*np.exp(-1j*self.beta(f)*self.l)*c
示例#25
0
def intxfxcoshcurve(x, m):
    # measured in x direction (towards point end of curve) from zero
    # equation for the integral of xf(x)
    intxfx = ( 1/( np.cosh( m*np.pi )-1))*((( np.cosh( m*np.pi )-( m*np.pi )*np.sinh( m*np.pi ))/(( m*np.pi )**2))+(( 1/2 )*np.cosh( m*np.pi ))-( 1/(( m*np.pi )**2 )))
    # multiply calculated intxfx by actual dimension in x direction
    intxfx = x*intxfx
    return intxfx
    def process(self, specificLoudness):

        # convolution with weighting function
        self.smoothSpecificLoudness = np.zeros(specificLoudness.shape)
        nFilters = specificLoudness.shape[0]
        for ear in range(2):
            self.smoothSpecificLoudness[:, ear] = \
                np.convolve(
                    self.fullGaussian, specificLoudness[:, ear]
                )[nFilters-1:-nFilters+1]

        # Gain computation
        self.smoothSpecificLoudness[self.smoothSpecificLoudness < 1e-12] = \
            1e-12
        inhibLeft = \
            2.0 / (1 + (1.0 / np.cosh(
                self.smoothSpecificLoudness[:, 1] /
                self.smoothSpecificLoudness[:, 0]
            )) ** 1.5978)
        inhibRight = 2.0 / (1 + (1.0 / np.cosh(
            self.smoothSpecificLoudness[:, 0] /
            self.smoothSpecificLoudness[:, 1]
        )) ** 1.5978)

        # Apply gains to original specific loudness
        self.inhibitedSpecificLoudness = specificLoudness.copy()
        self.inhibitedSpecificLoudness[:, 0] /= inhibLeft
        self.inhibitedSpecificLoudness[:, 1] /= inhibRight
示例#27
0
def get_ind_potential(mesh,num,amp,omeg,depth,wk): 
    '''
       for cylinder in indefinite water ???
    '''
    import numpy as np
    from dutwav.analytical import bj
    from scipy.special import jv
    mesh.nodes[1]
    g=9.801
    res={}
    for i in range(num):
        x=mesh.nodes[i+1][0]
        y=mesh.nodes[i+1][1]
        z=mesh.nodes[i+1][2]
        theta = np.arctan2(y,x)
        r=np.sqrt(x**2+y**2)
        tmp=0.
        for m in range(10):
            eps=2.
            if m==0:
                eps=1.
            tp=-1j*g*amp/omeg
            tp=tp*np.cosh(wk*(z+depth))/np.cosh(wk*depth)
            tp=tp*eps*(1j)**m*bj(wk*r,m)*np.cos(m*theta)
            # tp=tp*eps*(1j)**m*jv(m,wk*r)*np.cos(m*theta)
            tmp+=tp
        res[i+1]=tmp
    return res
示例#28
0
def update(rank, X, U, P, N, comm, L, **kw):
    
    Ha = config.Ha
    if config.tstep % config.compute_energy == 0: 
        u_exact = ( cosh(Ha) - cosh(Ha*X[0,:,0,0]))/(cosh(Ha) - 1.0)
        if rank == 0:
            print "Time %2.5f Error %2.12e" %(config.t, linalg.norm(u_exact-U[1,:,0,0],inf))
示例#29
0
def N2sol(t,z,b2,gamma, t0):
    """
    complete field for the N=2 soliton
    """
    p01 = np.abs(b2) / gamma / t0**2
    ld = t0**2 / np.abs(b2)  
    return np.sqrt(p01) * 4 * (np.cosh(3*t/t0) + 3 * np.exp(1.0j * 4 * z/ld ) * np.cosh(t/t0)) / (np.cosh(4*t/t0)+4*np.cosh(2*t/t0)+ 3*np.cos(4*z/ld)) * np.exp( 1.0j * z/ld /2.)  
示例#30
0
def bipartivity_exact(G, focal=None):
    G_MAT=NX.to_numpy_matrix(G) # Convert NX network to adjacency matrix
    ei,ev=N.linalg.eig(G_MAT)   # Calculate eigenvalues abd eigenvectors

    SC_even=0       # Sum of the contributions from even closed walks in G
    SC_all=0        # Sum of the contributions of all closed walks in G

    if focal is None:
        ''' Formulas described on page 2
        First code block calculates bipartivity of G globally'''
        for j in range(0,G.number_of_nodes()):
            SC_even=SC_even+N.cosh(ei[j].real)
            SC_all=SC_all+N.e**(ei[j].real)
        # Proportion of even closed walks over all closed walks
        B=SC_even/SC_all    
    else:
        # If focal node is passed as str, or object
        if focal is not int:
            n=G.nodes()
            focal=n.index(focal)
        '''Second code block calculates contibution of 'focal' to bipartivity'''
        for j in range(0,G.number_of_nodes()):
            SC_even=SC_even+((ev[focal,j].real)**2)*(N.cosh(ei[j].real))
            SC_all=SC_all+((ev[focal,j].real)**2)*(N.e**(ei[j].real))
            
        B=SC_even/SC_all    # Proportion of even CW for focal node, ie how much
                            # the focal node contributes to bipartivity.
    return B
示例#31
0
    def hyperbola(self, p1, p2, toa1, toa2):
        '''
        calculates the asymptotes of hyperbola that represents equidifference
        curves for time of arrival (TDOA) for two points.

        input:
               p1,p2           location in the form (lat,lon)
               toa1,toa2       timestamp in seconds

        return:
               (x1,y1,x2,y2)   x & y coordinates of asymptotes 1 & 2
        '''

        if DEBUG:
            print "p1: ", p1
            print "p2: ", p2
            print "toa1: ", repr(toa1)
            print "toa2: ", repr(toa2)
            print "type(toa1): ", type(toa1)
            print "type(toa2): ", type(toa2)
        x1 = p1[0]
        y1 = p1[1]

        x2 = p2[0]
        y2 = p2[1]

        # angle between two locations and 'horizontal'
        alpha = np.arctan((y2 - y1) / (x2 - x1))
        if DEBUG:
            print "alpha: ", alpha

        # approx. midpoint between two locations
        midpoint = self.midpoint(p1, p2)
        x_0 = midpoint[0]
        y_0 = midpoint[1]

        # 3) determine hyperbola asymptotes
        a = (0.5) * self.speed_of_light * (np.abs(toa1 - toa2)) / (60 * 1852)
        distance = self.distance(p1, p2) / (60 * 1852)
        b = np.sqrt((distance / 2.0)**2 - a**2)
        asymp_slope = (b / a, -b / a)

        # hyperbolas
        t = np.linspace(-np.pi, np.pi, 100)
        print 'type(t): ', type(t)
        # t = np.linspace(-2,2,100)

        dd = self.speed_of_light * ((toa1 - toa2)) / (60 * 1852)
        if x1 < x2:
            if DEBUG:
                print "x1 < x2"
                print "dd: ", dd
            if dd < 0:
                if DEBUG:
                    print "dd < 0"
                x_hyperbola = -a * np.cosh(t)
                y_hyperbola = b * np.sinh(t)
            else:  # dd > 0
                if DEBUG:
                    print "dd > 0"
                x_hyperbola = a * np.cosh(t)
                y_hyperbola = b * np.sinh(t)
        else:  # x1 > x2
            if DEBUG:
                print "x1 > x2"
                print "dd: ", dd
            if dd > 0:
                if DEBUG:
                    print "dd > 0"
                x_hyperbola = -a * np.cosh(t)
                y_hyperbola = b * np.sinh(t)
            else:  # dd < 0:
                if DEBUG:
                    print "dd < 0"
                x_hyperbola = a * np.cosh(t)
                y_hyperbola = b * np.sinh(t)

        x_hyperbola_p = x_hyperbola * np.cos(alpha) - y_hyperbola * np.sin(
            alpha) + x_0
        y_hyperbola_p = x_hyperbola * np.sin(alpha) + y_hyperbola * np.cos(
            alpha) + y_0

        #plt.plot(x_hyperbola_p,y_hyperbola_p)

        return (x_hyperbola_p, y_hyperbola_p)
示例#32
0
import numpy as np
import matplotlib.pyplot as plt
import math
import time
import argparse

sigmoid = (lambda x: 1. / (1 + np.exp(-x)), lambda x: x * (1. - x))

relu = (lambda x: np.maximum(0, x), lambda x: 1. * (x > 0))

tanh = (lambda x: np.tanh(x), lambda x: (1. / np.cosh(x))**2)


class NeuralNetwork:
    def __init__(self, x, y, activation1, activation2, eta=0.1, layer_size=4):
        self.input = x
        input_size = self.input.shape[1]
        self.weights1 = np.random.rand(layer_size, input_size)
        self.weights2 = np.random.rand(1, layer_size)
        self.y = y
        self.output = np.zeros(self.y.shape)
        self.eta = eta
        self.activation1, self.activation_derivative1 = activation1
        self.activation2, self.activation_derivative2 = activation2

    def feedforward(self):
        self.layer1 = self.activation1(np.dot(self.input, self.weights1.T))
        self.output = self.activation2(np.dot(self.layer1, self.weights2.T))

    def backprop(self):
        delta2 = (self.y - self.output) * \
示例#33
0
def sech(x):
    """Hyperbolic secant"""
    return 1 / np.cosh(x)
示例#34
0
def sechsoln(xspace, t, kappa):
    return 1 / np.sqrt(2) * kappa * 1 / np.cosh(kappa * xspace) * np.exp(
        1j * kappa**2 * t)
def euler_beam_modes(n=10, bctype=3, npoints=2001,
                     beamparams=np.array([7.31e10, 8.4375e-09,
                                          2747.0, 4.5e-04, 0.4])):
    """Mode shapes and natural frequencies of Euler-Bernoulli beam.

    Parameters
    ----------
    n: int, numpy array
        highest mode number or array of mode numbers to return
    bctype: int
        bctype = 1 free-free
        bctype = 2 clamped-free
        bctype = 3 clamped-pinned
        bctype = 4 clamped-sliding
        bctype = 5 clamped-clamped
        bctype = 6 pinned-pinned
    beamparams: numpy array
        E, I, rho, A, L,
        Young's modulus, second moment of area, density, cross section area,
        length of beam
    npoints: int
        number of points for returned mode shape array

    Returns
    -------
    omega_n: numpy array
        array of natural frequencies
    x: numpy array
        x coordinate
    U: numpy array
        mass normalized mode shape

    Examples
    --------
    >>> import matplotlib.pyplot as plt
    >>> import vibration_toolbox as vtb
    >>> omega_n, x, U = vtb.euler_beam_modes(n=1)
    >>> plt.figure()
    <matplotlib.figure...>
    >>> plt.plot(x,U)
    [<matplotlib.lines.Line2D object at ...>]
    >>> plt.xlabel('x (m)')
    <matplotlib.text.Text object at ...>
    >>> plt.ylabel('Displacement (m)')
    <matplotlib.text.Text object at ...>
    >>> plt.title('Mode 1')
    <matplotlib.text.Text object at ...>
    >>> plt.grid('on')
    """

    E = beamparams[0]
    I = beamparams[1]
    rho = beamparams[2]
    A = beamparams[3]
    L = beamparams[4]
    if isinstance(n, int):
        ln = n
        n = np.arange(n) + 1
    else:
        ln = len(n)

    # len=[0:(1/(npoints-1)):1]';  %Normalized length of the beam
    x_normed = np.linspace(0, 1, npoints, endpoint=True)
    x = x_normed * L
    # Determine natural frequencies and mode shapes depending on the
    # boundary condition.
    # Mass simplification. The following was arange_(1,length_(n)).reshape(-1)
    mode_num_range = np.arange(0, ln)
    Bnl = np.empty(ln)
    w = np.empty(ln)
    U = np.empty([npoints, ln])

    if bctype == 1:
        desc = 'Free-Free '
        Bnllow = np.array((0, 0, 4.73004074486, 7.8532046241,
                           10.995607838, 14.1371654913, 17.2787596574))
        for i in mode_num_range:
            if n[i] > 7:
                Bnl[i] = (2 * n[i] - 3) * np.pi / 2
            else:
                Bnl[i] = Bnllow[i]
        for i in mode_num_range:
            if n[i] == 1:
                w[i] = 0
                U[:, i] = 1 + x_normed * 0
            elif n[i] == 2:
                w[i] = 0
                U[:, i] = x_normed - 0.5
            else:
                sig = (np.cosh(Bnl[i]) - np.cos(Bnl[i])) / \
                      (np.sinh(Bnl[i]) - np.sin(Bnl[i]))
                w[i] = (Bnl[i] ** 2) * np.sqrt(E * I / (rho * A * L ** 4))
                b = Bnl[i] * x_normed
                U[:, i] = np.cosh(b) + np.cos(b) - sig * \
                    (np.sinh(b) + np.sin(b))
    elif bctype == 2:
        desc = 'Clamped-Free '
        Bnllow = np.array((1.88, 4.69, 7.85, 10.99, 14.14))
        for i in mode_num_range:
            if n[i] > 4:
                Bnl[i] = (2 * n[i] - 1) * np.pi / 2
            else:
                Bnl[i] = Bnllow[i]

        for i in mode_num_range:
            sig = (np.sinh(Bnl[i]) - np.sin(Bnl[i])) / \
                  (np.cosh(Bnl[i]) - np.cos(Bnl[i]))
            w[i] = (Bnl[i] ** 2) * np.sqrt(E * I / (rho * A * L ** 4))
            b = Bnl[i] * x_normed
            # plt.plot(x,(sp.cosh(b) - sp.cos(b) -
            # sig * (sp.sinh(b) - sp.sin(b))))
            U[:, i] = np.cosh(b) - np.cos(b) - sig * (np.sinh(b) - np.sin(b))

    elif bctype == 3:
        desc = 'Clamped-Pinned '
        Bnllow = np.array((3.93, 7.07, 10.21, 13.35, 16.49))
        for i in mode_num_range:
            if n[i] > 4:
                Bnl[i] = (4 * n[i] + 1) * np.pi / 4
            else:
                Bnl[i] = Bnllow[i]
        for i in mode_num_range:
            sig = (np.cosh(Bnl[i]) - np.cos(Bnl[i])) / \
                  (np.sinh(Bnl[i]) - np.sin(Bnl[i]))
            w[i] = (Bnl[i] ** 2) * np.sqrt(E * I / (rho * A * L ** 4))
            b = Bnl[i] * x_normed
            U[:, i] = np.cosh(b) - np.cos(b) - sig * (np.sinh(b) - np.sin(b))
    elif bctype == 4:
        desc = 'Clamped-Sliding '
        Bnllow = np.array((2.37, 5.5, 8.64, 11.78, 14.92))
        for i in mode_num_range:
            if n[i] > 4:
                Bnl[i] = (4 * n[i] - 1) * np.pi / 4
            else:
                Bnl[i] = Bnllow[i]
        for i in mode_num_range:
            sig = (np.sinh(Bnl[i]) + np.sin(Bnl[i])) / \
                  (np.cosh(Bnl[i]) - np.cos(Bnl[i]))
            w[i] = (Bnl[i] ** 2) * np.sqrt(E * I / (rho * A * L ** 4))
            b = Bnl[i] * x_normed
            U[:, i] = np.cosh(b) - np.cos(b) - sig * (np.sinh(b) - np.sin(b))
    elif bctype == 5:
        desc = 'Clamped-Clamped '
        Bnllow = np.array((4.73, 7.85, 11, 14.14, 17.28))
        for i in mode_num_range:
            if n[i] > 4:
                Bnl[i] = (2 * n[i] + 1) * np.pi / 2
            else:
                Bnl[i] = Bnllow[i]
        for i in mode_num_range:
            sig = (np.cosh(Bnl[i]) - np.cos(Bnl[i])) / \
                  (np.sinh(Bnl[i]) - np.sin(Bnl[i]))
            w[i] = (Bnl[i] ** 2) * np.sqrt(E * I / (rho * A * L ** 4))
            b = Bnl[i] * x_normed
            U[:, i] = np.cosh(b) - np.cos(b) - sig * (np.sinh(b) - np.sin(b))
    elif bctype == 6:
        desc = 'Pinned-Pinned '
        for i in mode_num_range:
            Bnl[i] = n[i] * np.pi
            w[i] = (Bnl[i] ** 2) * np.sqrt(E * I / (rho * A * L ** 4))
            U[:, i] = np.sin(Bnl[i] * x_normed)

    # Mass Normalization of mode shapes
    for i in mode_num_range:
        U[:, i] = U[:, i] / np.sqrt(np.dot(U[:, i], U[:, i]) * rho * A * L)

    omega_n = w
    return omega_n, x, U
示例#36
0
 def coth(x):
     return np.cosh(x) / np.sinh(x)
def d_tanh(data):
    return 1 / (np.cosh(data))**2
示例#38
0
 def kernel(k, a=a, b=b):
     if k:
         return sinh(a * k) / cosh(b * k)
     return 0
    if 25 in pids:
        #print "Higgs"
        for pin in range(0, branchParticle.GetEntriesFast()):
            #for pin in range(0, 20):
            part = branchParticle.At(pin)
            if (abs(part.PID) == 24 and part.Status == 22):
                wpart.SetPtEtaPhiE(part.PT, part.Eta, part.Phi, part.E)

    # No higgs event
    else:
        print "No Higgs!"

    for etrenrty in range(0, branchTrack.GetEntriesFast()):
        eterm = branchTrack.At(etrenrty)
        temp.SetPtEtaPhiE(eterm.PT, eterm.Eta, eterm.Phi,
                          eterm.PT * np.cosh(eterm.Eta))
        vectors.append((temp.E(), temp.Px(), temp.Py(), temp.Pz()))

    for pentry in range(0, branchPhoton.GetEntriesFast()):
        pterm = branchPhoton.At(pentry)
        temp.SetPtEtaPhiE(pterm.ET, pterm.Eta, pterm.Phi, pterm.E)
        vectors.append((temp.E(), temp.Px(), temp.Py(), temp.Pz()))

    for nentry in range(0, branchNeutral.GetEntriesFast()):
        nterm = branchNeutral.At(nentry)
        temp.SetPtEtaPhiE(nterm.ET, nterm.Eta, nterm.Phi, nterm.E)
        vectors.append((temp.E(), temp.Px(), temp.Py(), temp.Pz()))

    vects = np.asarray(vectors,
                       dtype=np.dtype([('E', 'f8'), ('px', 'f8'), ('py', 'f8'),
                                       ('pz', 'f8')]))
示例#40
0
 def kernel(k, a=a, b=b):
     return cosh(a * k) / cosh(b * k)
示例#41
0
def tanh_fn(x): #domain -1 - 1
	return np.sinh( x ) / np.cosh( x )
示例#42
0
def BEMT(J, P_D, BA_ratio, N_blades, chord, relative_pitch_distribution,
         lift_curve_slope, root_thickness):
    '''
    Main Blade Element Momentum Theory Function. Uses algorithm form referenced
    book.
    
    Parameters
    ----------
    
    J: float
        advance ratio
    P_D: float
        pitch diameter ratio at 0.7 radius
    BA_ratio: float
            blade area ratio
    N_blades: int
            number of blades
    chord: array of floats
        chord of blade at different radial positions
    relative_pitch_distribution: array of float
        pitch distribution at radial positions relative to pitch distibution at
        x_R = 0.7
    lift_curve_slope: float
                lift curve slope of blade
    root_thickness: float
                thickness at blade root
    
    Returns
    -------
    Total_Thrust: float
                total thrust coefficient along blade
    Total_Torque: float
                total torque coefficient along blade
    Open_eta: float
            open water efficiency
    '''
    assert J <= 1.1 and J >= 0.3, ' Advance ratio must be between 0.3 and 1.1 \
    but has value {}'.format(J)
    assert P_D >= J + 0.03 and P_D >= 0.6 and P_D <= 1.2, 'Pitch/Diameter Ratio at \
    0.7R is outside limits for this J value'

    assert BA_ratio >= 0.4 and BA_ratio <= 0.8, ' Blade area ratio is out limits.\
    Must be between 0.4 and 0.8 but has value {}'.format(BA_ratio)
    assert N_blades >= 3 and N_blades <= 5, 'Number of blades must be between 3 \
and 5 but is of value {}'.format(N_blades)
    assert type(
        J
    ) == np.float or np.float64, 'J is not of type float but is of type {}'.format(
        type(J))
    assert type(
        P_D
    ) == np.float or np.float64, 'P_D is not of type float but is of type {}'.format(
        type(P_D))
    assert type(
        BA_ratio
    ) == np.float or np.float64, 'BA_ratio is not of type float but is of type {}'.format(
        type(BA_ratio))
    assert type(
        N_blades
    ) == int, 'N_blades is not of type int but is of type {}'.format(
        type(N_blades))
    assert type(
        chord
    ) == np.array or np.ndarray, 'chord is not of type array but is of type {}'.format(
        type(chord))
    assert type(
        relative_pitch_distribution
    ) == np.array or np.ndarray, 'relative_pitch_distribution is not of type array but is of type {}'.format(
        type(relative_pitch_distribution))
    assert type(
        lift_curve_slope
    ) == np.float or np.float64, 'lift_curve_slope is not of type float but is of type {}'.format(
        type(lift_curve_slope))
    assert type(
        root_thickness
    ) == np.float or np.float64, 'root_thickness is not of type float but is of type {}'.format(
        type(root_thickness))
    # create arrays
    x_R = np.zeros_like(chord)
    phi_plus_alhpa = np.zeros_like(chord)
    tan_psi = np.zeros_like(chord)
    local_P_D = np.zeros_like(chord)
    K_series = np.zeros_like(chord)
    chord_diameter = np.zeros_like(chord)
    thickness_chord = np.zeros_like(chord)
    KT_dx = np.zeros_like(chord)
    Cl = np.zeros_like(chord)
    Cd = np.zeros_like(chord)
    KQ_dx = np.zeros_like(chord)
    phi = np.zeros_like(chord)
    alpha = np.zeros_like(chord)
    K2 = np.zeros_like(chord)
    MC = np.zeros_like(chord)
    MT = np.zeros_like(chord)
    CC = np.zeros_like(chord)

    LI = 0.8 * 12.67
    LM = 0.8 * 11.3
    VV = 0
    for i in range(1, 9):
        # calculate local pitch
        local_P_D[i] = P_D * relative_pitch_distribution[i]
        # set value of x_R for each element
        x_R[i] = (i + 1) / 10
        # compute chord/diameter from blade geometry
        chord_diameter[i] = chord[i] * BA_ratio * 4.0 / (N_blades * 0.5)
        # compute Nc/D for later use
        Nc_D = N_blades * chord_diameter[i]
        # thickness distribution from rootthickness
        thickness_distribution = root_thickness - (root_thickness *
                                                   0.935) * x_R[i]
        # thickness/chord
        thickness_chord[i] = thickness_distribution / chord_diameter[i]
        # set initial angle of attack to 0
        alpha[i] = 0.0
        # set number of alpha iterations to 0
        alpha_iterations = 0
        # set convergence flag to 0
        alpha_converge = 0
        # start of alpha convergenc loop
        while alpha_iterations < 2000 and alpha_converge == 0:
            alpha_iterations += 1
            # calculate tan of inflow angle
            tan_psi[i] = J / (np.pi * x_R[i])
            # induced flow angle plus angle of attack
            phi_plus_alhpa[i] = np.arctan2(local_P_D[i], (np.pi * x_R[i]))
            # inflow angle
            phi[i] = phi_plus_alhpa[i] - alpha[i]
            # ideal efficieny
            eta_ideal = tan_psi[i] / np.tan(phi[i])
            # initially set efficiency to ideal
            eta = 0.9 * eta_ideal
            gamma = 0.0  # zero for ideal efficiency
            KF = np.tan(phi[i]) * x_R[i]
            # Goldstein Correction
            SF = N_blades / (2.0 * np.tan(phi[i]) * x_R[i]) - 0.5
            F1 = np.cosh(SF)
            F2 = np.cosh(SF * x_R[i])
            F3 = F2 / F1
            F4 = np.arccos(F3)
            K = 2.0 * F4 / np.pi
            # store factor in array
            K_series[i] = K
            # set number of efficiency iterations to 0
            eta_iterations = 0
            eta_converge = 0
            while eta_iterations < 2000 and eta_converge == 0:
                # axial inflow factor
                a = (1 - eta_ideal) / (eta_ideal + (tan_psi[i]**2) / eta)
                # local thrust coefficient
                KT_dx[i] = np.pi * (J**2) * x_R[i] * K * a * (1 + a)
                # circumferential inflow factor (a')
                a_p = 1 - eta_ideal * (1 + a)
                # lift coefficient
                Cl[i] = KT_dx[i]/(((np.pi**2)/4)*(N_blades*chord_diameter[i])*(x_R[i]**2)*((1-a_p)**2) \
                       * (1/np.cos(phi[i]))*(1-np.tan(phi[i])*np.tan(gamma)))

                # compute drag coefficient from angle of attack and geometry
                F6 = 0.0107 + (alpha[i] + 1.0) * (-0.0015 + alpha[i] *
                                                  (0.0015 + 0.000965 *
                                                   (alpha[i] - 1.0)))
                F7 = -0.03833 + (alpha[i] + 1.0) * (0.0133 + alpha[i] *
                                                    (-0.015 - 0.01166 *
                                                     (alpha[i] - 1.0)))
                F8 = 0.8193 + (alpha[i] + 1.0) * (-0.0138 + alpha[i] *
                                                  (0.0903 + 0.079 *
                                                   (alpha[i] - 1.0)))
                F9 = -3.076 + (alpha[i] + 1.0) * (-0.0728 + alpha[i] *
                                                  (-0.3162 - 0.2437 *
                                                   (alpha[i] - 1.0)))
                Cd[i] = F6 + thickness_chord[i] * (
                    F7 + (thickness_chord[i] - 0.06) *
                    (F8 + F9 * (thickness_chord[i] - 0.12)))

                # update gamma
                gamma = np.arctan2(Cd[i], Cl[i])
                # compute efficieny
                eta_calculated = tan_psi[i] / (np.tan((phi[i] + gamma)))
                eta_iterations += 1
                if np.abs(eta_calculated - eta) < 0.001:
                    # if old efficieny = new efficiency
                    # set convergence flag to 1 to stop iteration
                    eta_converge = 1
                    # camber correction
                    # geometric
                    K2[1] = 1.0 + 2.857 * (BA_ratio - 0.4) * (
                        BA_ratio - 0.6) * (BA_ratio - 0.9)
                    K2[2] = 1.19 + (BA_ratio - 0.4) * (BA_ratio - 0.6) * (
                        0.267 + (BA_ratio - 0.9) * 0.1665)
                    K2[3] = 1.3 + (BA_ratio -
                                   0.4) * (0.1 + (BA_ratio - 0.6) *
                                           (1 + (BA_ratio - 0.9) * 0.43))
                    K2[4] = 1.54 + (BA_ratio - 0.4) * (0.15 +
                                                       (BA_ratio - 0.6) *
                                                       (1.1 + 0.286 *
                                                        (BA_ratio - 0.9)))
                    K2[5] = 1.67 + (BA_ratio -
                                    0.4) * (0.55 + (BA_ratio - 0.6) *
                                            (0.1667 +
                                             (BA_ratio - 0.9) * 2.9465))
                    K2[6] = 1.8 + (BA_ratio -
                                   0.4) * (0.75 + (BA_ratio - 0.6) *
                                           (0.3 + (BA_ratio - 0.9) * 2.835))
                    K2[7] = 1.8 + (BA_ratio -
                                   0.4) * (1.0 + (BA_ratio - 0.6) *
                                           (1.333 + (BA_ratio - 0.9) * 1.905))
                    K2[8] = 1.75 + (BA_ratio -
                                    0.4) * (1.25 + (BA_ratio - 0.6) *
                                            (1.5 + (BA_ratio - 0.9) * 3.55))
                    # from camber correction curves
                    # KF is lambda from goldstein correction
                    U1 = -0.65 * KF * KF + 1.1 * KF + 0.664
                    U2 = (0.85 + (KF - 0.3) * (-4.0 + (KF - 0.4) *
                                               (15.42 - 47.95 * (KF - 0.5))))
                    U2 = -0.09 + (KF - 0.2) * U2
                    U3 = (1.375 + (KF - 0.3) * (-3.75 + (KF - 0.4) *
                                                (20.85 - 75.7875 *
                                                 (KF - 0.5))))
                    U3 = -0.2 + (KF - 0.2) * U3
                    K1 = U1 + (BA_ratio - 0.4) * (U2 + U3 * (BA_ratio - 0.8))
                    # camber correction
                    CC[i] = K1 * K2[i]

                    # compute angle of attack using camber correction
                    # MC = camber/chord
                    # MT = camber/thickness
                    # multiply by pi/180 as lift curve slope is degrees
                    if VV == 1:
                        MC[i] = MT[i] * thickness_chord[i]
                        alpha_calculated = (CC[i] * Cl[i] / LI -
                                            MC[i]) * LM / 0.1097 + (
                                                MC[i] * LI / lift_curve_slope)

                    elif VV == 5:
                        MC[i] = 0.5 * thickness_chord[i]
                        alpha_calculated = (CC[i] * Cl[i] / LI -
                                            MC[i]) * LM / 0.1097 + (
                                                Cl[i] / lift_curve_slope)
                        alpha_calculated = alpha_calculated * np.pi / 180
                        MT[i] = MC[i] / thickness_chord[i]

                    else:
                        alpha_calculated = Cl[i] / lift_curve_slope
                        alpha_calculated = alpha_calculated * np.pi / 180
                        MC[i] = Cl[i] / LI
                        MC[i] = MC[i] * CC[i]

                        if MC[i] < (0.5 * thickness_chord[i]):
                            MT[i] = MC[i] / thickness_chord[i]

                        else:
                            VV = 5
                            MC[i] = 0.5 * thickness_chord[i]
                            alpha_calculated = (CC[i] * Cl[i] / LI -
                                                MC[i]) * LM / 0.1097 + (
                                                    Cl[i] / lift_curve_slope)
                            alpha_calculated = alpha_calculated * np.pi / 180
                            MT[i] = MC[i] / thickness_chord[i]
                else:
                    # set the new efficiency to calculated efficiency
                    eta = eta_calculated

            if np.abs((alpha_calculated - alpha[i]) / alpha_calculated) < 0.1:
                # compute local torque coefficient
                KQ_dx[i] = 4.935 * J * (x_R[i]**3) * K * a_p * (1 + a)
                # set convergence flag to 1 to stop iteration
                alpha_converge = 1
            else:
                alpha[i] = (alpha_calculated + alpha[i]) / 2.0

    # set tip coefficients to 0
    x_R[9] = 1.0
    KT_dx[9] = 0.0
    KQ_dx[9] = 0.0
    K_series[9] = 0.0
    local_P_D[9] = local_P_D[8]
    alpha[9] = alpha[8]

    print(KT_dx)
    # Integrate over blade to compute total coefficients. Using simpsons rule
    Total_Thrust = (KT_dx[1] + 2.0 * (KT_dx[3] + KT_dx[5] + KT_dx[7]) + 4.0 *
                    (KT_dx[2] + KT_dx[4] + KT_dx[6] + KT_dx[8]))
    Total_Thrust = 0.1 * Total_Thrust / 3.0
    Total_Torque = (KQ_dx[1] + 2.0 * (KQ_dx[3] + KQ_dx[5] + KQ_dx[7]) + 4.0 *
                    (KQ_dx[2] + KQ_dx[4] + KQ_dx[6] + KQ_dx[8]))
    Total_Torque = (0.1 * Total_Torque) / 3.0
    # open water efficiency
    Open_eta = (J * Total_Thrust) / (2.0 * 3.1416 * Total_Torque)

    return Total_Thrust, Total_Torque, Open_eta
示例#43
0
 def g_derivative(self, x):
     cosh2 = (np.cosh(self.beta * x))**2
     return self.beta / cosh2
def select_events(events, apply_exclusive=True):

    selections_ = []
    counts_ = []

    selections_.append("All")
    counts_.append(len(events))

    msk_2muons = (events.nMuonCand >= 2)
    events_2muons = events[msk_2muons]

    dphi = events_2muons.MuonCand.phi[:, 0] - events_2muons.MuonCand.phi[:, 1]

    dphi = np.where(dphi >= scipy.constants.pi, dphi - 2 * scipy.constants.pi,
                    dphi)
    dphi = np.where(dphi < -scipy.constants.pi, dphi + 2 * scipy.constants.pi,
                    dphi)
    acopl = 1. - np.abs(dphi) / scipy.constants.pi

    events_2muons["Acopl"] = acopl

    m1 = events_2muons.MuonCand[:, 0]
    m2 = events_2muons.MuonCand[:, 1]

    invariant_mass = np.sqrt(
        2 * m1.pt * m2.pt *
        (np.cosh(m1.eta - m2.eta) - np.cos(m1.phi - m2.phi)))

    events_2muons["InvMass"] = invariant_mass

    energy_com = 13000.
    xi_mumu_plus = (1. / energy_com) * (m1.pt * np.exp(m1.eta) +
                                        m2.pt * np.exp(m2.eta))
    xi_mumu_minus = (1. / energy_com) * (m1.pt * np.exp(-m1.eta) +
                                         m2.pt * np.exp(-m2.eta))

    events_2muons["XiMuMuPlus"] = xi_mumu_plus
    events_2muons["XiMuMuMinus"] = xi_mumu_minus

    pfCands_ = events_2muons.PfCand

    pfCands_["dR_0"] = np.sqrt(
        (pfCands_.eta - events_2muons.MuonCand.eta[:, 0])**2 +
        (pfCands_.phi - events_2muons.MuonCand.phi[:, 0])**2)
    pfCands_["dR_1"] = np.sqrt(
        (pfCands_.eta - events_2muons.MuonCand.eta[:, 1])**2 +
        (pfCands_.phi - events_2muons.MuonCand.phi[:, 1])**2)

    pfCands_sel1_ = pfCands_[pfCands_.fromPV == 3.0]
    pfCands_sel2_ = pfCands_sel1_[pfCands_sel1_.dR_0 > 0.3]
    pfCands_sel3_ = pfCands_sel2_[pfCands_sel2_.dR_1 > 0.3]
    events_2muons["nExtraPfCandPV3"] = ak.num(pfCands_sel3_)

    msk_muon = (np.array(events_2muons.MuonCand.pt[:, 0] >= 50.)
                & np.array(events_2muons.MuonCand.pt[:, 1] >= 50.)
                & np.array(events_2muons.MuonCand.istight[:, 0] == 1)
                & np.array(events_2muons.MuonCand.istight[:, 1] == 1)
                & np.array((events_2muons.MuonCand.charge[:, 0] *
                            events_2muons.MuonCand.charge[:, 1]) == -1))
    selections_.append("Muon")
    counts_.append(np.sum(msk_muon))

    msk_vtx = msk_muon & (np.array(
        np.abs(events_2muons.PrimVertexCand.z[:, 0]) <= 15.) & np.array(
            np.abs(events_2muons.MuonCand.vtxz[:, 0] -
                   events_2muons.PrimVertexCand.z[:, 0]) <= 0.02) & np.array(
                       np.abs(events_2muons.MuonCand.vtxz[:, 1] -
                              events_2muons.PrimVertexCand.z[:, 0]) <= 0.02))
    selections_.append("Vertex")
    counts_.append(np.sum(msk_vtx))

    events_sel = None
    if apply_exclusive:
        msk_excl = msk_vtx & (np.array(events_2muons["InvMass"] >= 110.)
                              & np.array(events_2muons["Acopl"] <= 0.009) &
                              np.array(events_2muons["nExtraPfCandPV3"] <= 1))
        selections_.append("Exclusive")
        counts_.append(np.sum(msk_excl))

        events_sel = events_2muons[msk_excl]
    else:
        events_sel = events_2muons[msk_vtx]

    selections_ = np.array(selections_)
    counts_ = np.array(counts_)

    return (events_sel, selections_, counts_)
示例#45
0
def np_func(x, y):
    return np.sinh(x) + np.cosh(y)
示例#46
0
        x,y = x_split[j],y_split[j]

        # initial guesses
        x_tail,y_tail = x[1:treshold], y[1:treshold]
        slope, intercept = np.polyfit(x_tail,y_tail,1)

        p0 = [max(y),0.1,x[np.argmin(np.abs(x))],slope]
        lower = [0,0.01,-100,0.9*p0[3]]
        upper = [1.1*p0[0],100,100,1.1*p0[3]]

        popt, pcov = curve_fit(hysteresis,x,y,p0=p0,maxfev=10000,bounds=[lower,upper])
        fit_params.append(popt),fit_errors.append(np.diag(pcov))

        # error calculation
        dA = lambda x: np.tanh(popt[1]*(x-popt[2]))
        dB = lambda x: popt[0]*(x-popt[2])/np.cosh(popt[1]*(x-popt[2]))**2
        dC = lambda x: -popt[0]*popt[1]/np.cosh(popt[1]*(x-popt[2]))**2
        dD = lambda x: x

        grad, dH = np.array([[dA(x),dB(x),dC(x),dD(x)] for x in X]), np.zeros_like(X)
        for k,x_val in enumerate(X):
            dH[k] += np.sqrt(grad[k].T @ pcov @ grad[k])

    A, A_err = 0.5*(fit_params[0][0]+fit_params[1][0]), 0.5*np.sqrt(fit_errors[0][0]**2+fit_errors[1][0]**2)
    B, B_err = 0.5*(fit_params[0][1]+fit_params[1][1]), 0.5*np.sqrt(fit_errors[0][1]**2+fit_errors[1][1]**2)
    C, C_err = 0.5*(fit_params[0][2]-fit_params[1][2]), 0.5*np.sqrt(fit_errors[0][2]**2+fit_errors[1][2]**2)
    D, D_err = 0.5*(fit_params[0][3]+fit_params[1][3]), 0.5*np.sqrt(fit_errors[0][3]**2+fit_errors[1][3]**2)


    print(f"SI {temperature} degreecelsius & SI {A:.4f}pm{A_err:.4f} millidegree & SI {B*1e3:.4f}pm{B_err*1e3:.4f} permillioersted \
    & SI {C:.2f}pm{C_err:.2f} oersted & SI {D*1e3:.2f}pm{D_err*1e3:.2f} microdegreeperoersted")
 def derivative_activation(self, z):
     return (np.cosh(z))**(-2)
示例#48
0
 def _stats(self, lambda_):
     mu = 1 / expm1(lambda_)
     var = exp(-lambda_) / (expm1(-lambda_))**2
     g1 = 2 * cosh(lambda_ / 2.0)
     g2 = 4 + 2 * cosh(lambda_)
     return mu, var, g1, g2
示例#49
0
def w2k(w, theta=0.0, h=inf, g=9.81, count_limit=100):
    '''
    Translates from frequency to wave number
      using the dispersion relation

    Parameters
    ----------
    w : array-like
        angular frequency [rad/s].
    theta : array-like, optional
        direction [rad].
    h : real scalar, optional
        water depth [m].
    g : real scalar or array-like of size 2.
        constant of gravity [m/s**2] or 3D normalizing constant

    Returns
    -------
    k1, k2 : ndarray
        wave numbers [rad/m] along dimension 1 and 2.

    Description
    -----------
    Uses Newton Raphson method to find the wave number k in the dispersion
    relation
        w**2= g*k*tanh(k*h).
    The solution k(w) => k1 = k(w)*cos(theta)
                         k2 = k(w)*sin(theta)
    The size of k1,k2 is the common shape of w and theta according to numpy
    broadcasting rules. If w or theta is scalar it functions as a constant
    matrix of the same shape as the other.

    Example
    -------
    >>> import pylab as plb
    >>> import wafo.wave_theory.dispersion_relation as wsd
    >>> w = plb.linspace(0,3);
    >>> h = plb.plot(w,w2k(w)[0])
    >>> wsd.w2k(range(4))[0]
    array([ 0.        ,  0.1019368 ,  0.4077472 ,  0.91743119])
    >>> wsd.w2k(range(4),h=20)[0]
    array([ 0.        ,  0.10503601,  0.40774726,  0.91743119])

    >>> plb.close('all')

    See also
    --------
    k2w
    '''
    wi, th, hi, gi = atleast_1d(w, theta, h, g)

    if wi.size == 0:
        return zeros_like(wi)

    k = 1.0 * sign(wi) * wi**2.0 / gi[0]  # deep water
    if (hi > 10.**25).all():
        k2 = k * sin(th) * gi[0] / gi[-1]  # size np x nf
        k1 = k * cos(th)
        return k1, k2

    if gi.size > 1:
        raise ValueError('Finite depth in combination with 3D normalization' +
                         ' (len(g)=2) is not implemented yet.')

    find = flatnonzero
    eps = finfo(float).eps

    oshape = k.shape
    wi, k, hi = wi.ravel(), k.ravel(), hi.ravel()

    # Newton's Method
    # Permit no more than count_limit iterations.
    hi = hi * ones_like(k)
    hn = zeros_like(k)
    ix = find((wi < 0) | (0 < wi))

    # Break out of the iteration loop for three reasons:
    #  1) the last update is very small (compared to x)
    #  2) the last update is very small (compared to sqrt(eps))
    #  3) There are more than 100 iterations. This should NEVER happen.
    count = 0
    while (ix.size > 0 and count < count_limit):
        ki = k[ix]
        kh = ki * hi[ix]
        hn[ix] = (ki * tanh(kh) - wi[ix] ** 2.0 / gi) / \
            (tanh(kh) + kh / (cosh(kh) ** 2.0))
        knew = ki - hn[ix]
        # Make sure that the current guess is not zero.
        # When Newton's Method suggests steps that lead to zero guesses
        # take a step 9/10ths of the way to zero:
        ksmall = find(abs(knew) == 0)
        if ksmall.size > 0:
            knew[ksmall] = ki[ksmall] / 10.0
            hn[ix[ksmall]] = ki[ksmall] - knew[ksmall]

        k[ix] = knew
        # disp(['Iteration ',num2str(count),'  Number of points left:  '
        # num2str(length(ix)) ]),

        ix = find((abs(hn) > sqrt(eps) * abs(k)) * abs(hn) > sqrt(eps))
        count += 1

    if count == count_limit:
        warnings.warn('W2K did not converge. The maximum error in the ' +
                      'last step was: %13.8f' % max(hn[ix]))

    k.shape = oshape

    k2 = k * sin(th)
    k1 = k * cos(th)
    return k1, k2
 def getBeta(y):
     return -(4 * (H**2) * P) / (L * (pi**3)) * np.sum(
         (-1)**((n - 1) / 2) / (n**3) * (1 - np.cosh(
             (n * pi * y) / H) / np.cosh((n * pi * W) / (2 * H))),
         axis=0)
示例#51
0
class SinhFunction(Function):
    VJP_ALL = [
        lambda g, ans, x: g * np.cosh(x)
    ]
示例#52
0
                    # Select site to change, coordinate, and up or down
                    site = np.random.randint(0, size, (1, 3))[0]
                    coord = np.random.randint(0, 3)
                    e_coord = [1, 0, 0] if coord == 0 else [
                        0, 1, 0
                    ] if coord == 1 else [0, 0, 1]
                    change = np.random.randint(0, 2)
                    change = -1 if change == 0 else 1

                    # change in energy from site change
                    delta_e = energy_diff(lattice, site,
                                          np.array(e_coord) * change)
                    #print(delta_e)

                    # transition probability
                    prob = 1 / 2 * 1. / np.cosh(delta_e * beta / 2) * np.exp(
                        beta / 2)
                    if (prob > np.random.random()):
                        #print("TRANSITIONING")
                        #print(prob)
                        lattice[site[0]][site[1]][site[2]][coord] += change
                        acc += 1

                    # calculation of ground state occupancy
                    #gsoccupancy = sum(np.shape(~lattice.any(axis=3))) / num_atoms
                    gsoccupancy = np.count_nonzero(
                        np.sum(lattice, axis=3) == 0)
                    gs_occ.append(gsoccupancy / num_atoms)
                    # generates array of Booleans (True if it exists in ground state,
                    # False otherwise)
                    # and sums for ground state occupancy
def Pt(U0, E, L, betac, gamma_sqc):
    """return tunneling probability for square barrier"""
    return 1/ (np.cosh(betac * L)**2 + gamma_sqc * np.sinh(betac * L)**2)
示例#54
0
def sech2(x):
    return np.cosh(x)**-2
示例#55
0
def np_hyperbolic():
    print(np.sinh(np.pi / 2))
    print(np.cosh(np.array([np.pi / 2, np.pi / 3, np.pi / 4, np.pi / 5])))
    print(np.arcsinh(1.0))
    print(np.arctanh(np.array([0.1, 0.2, 0.5])))
示例#56
0
class TanhFunction(Function):
    VJP_ALL = [
        lambda g, ans, x: g / np.cosh(x) ** 2
    ]
示例#57
0
 def test_backward_derivative_sinh(self):
     # Compute the derivative of a function using a backward difference scheme
     # And a backward scheme will only look below x0.
     dsinh = nd.Derivative(np.sinh, method='backward')
     small = np.abs(dsinh(0.0) - np.cosh(0.0)) < dsinh.error_estimate
     self.assertTrue(small)
示例#58
0
 def __call__(self,phases,log10_ens=3):
     e,gamma,loc = self._make_p(log10_ens)
     z = TWOPI*(phases-loc)
     # NB -- numpy call not as efficient as math.sinh etc.
     # but this allows easy inheritance for the energy-dependence
     return np.sinh(gamma)/(np.cosh(gamma)-np.cos(z))
示例#59
0
     signal.append(0)
     #print 'jet#:',ijet,'etacenter:',event.JetAK8_ETA[ijet],'phicenter',event.JetAK8_PHI[ijet]
     #print len(event.CaloTower_ETA)
 for calo in range(len(event.CaloTower_ET)):
     etadistance = int(
         abs(event.CaloTower_ETA[calo] - etacenter) / .0714 + .5)
     phidistance = int(
         abs(event.CaloTower_PHI[calo] - phicenter) / (m.pi / 44) + .5)
     # E=event.CaloTower_ETA[calo]-etacenter
     #P= event.CaloTower_PHI[calo]-phicenter
     #count+=1
     if (etacenter >= event.CaloTower_ETA[calo]
             and phicenter >= event.CaloTower_PHI[calo]) and (
                 etadistance <= 12 and phidistance <= 12):
         Jetarray[12 - etadistance][
             12 - phidistance] += event.CaloTower_ET[calo] / np.cosh(
                 event.CaloTower_ETA[calo])
         #print event.CaloTower_ET[calo]/np.cosh(event.CaloTower_ETA[calo),
         #print event.CaloTower_ET[calo]/np.cosh(event.CaloTower_ETA[calo])
     elif (etacenter >= event.CaloTower_ETA[calo]
           and phicenter < event.CaloTower_PHI[calo]) and (
               etadistance <= 12 and phidistance <= 12):
         Jetarray[12 - etadistance][
             12 + phidistance] += event.CaloTower_ET[calo] / np.cosh(
                 event.CaloTower_ETA[calo])
         #continue
     elif (etacenter < event.CaloTower_ETA[calo]
           and phicenter >= event.CaloTower_PHI[calo]) and (
               etadistance <= 12 and phidistance <= 12):
         Jetarray[12 + etadistance][
             12 - phidistance] += event.CaloTower_ET[calo] / np.cosh(
                 event.CaloTower_ETA[calo])
示例#60
0
def _smear_particles(particles, energy_resolutions, pt_resolutions,
                     eta_resolutions, phi_resolutions):
    """ Applies smearing function to particles of one event """

    # No smearing if any argument is None
    if energy_resolutions is None or pt_resolutions is None or eta_resolutions is None or phi_resolutions is None:
        return particles

    smeared_particles = []

    for particle in particles:
        pdgid = particle.pdgid

        if (pdgid not in six.iterkeys(energy_resolutions)
                or pdgid not in six.iterkeys(pt_resolutions)
                or pdgid not in six.iterkeys(eta_resolutions)
                or pdgid not in six.iterkeys(phi_resolutions)):
            continue

        if None in energy_resolutions[pdgid] and None in pt_resolutions[pdgid]:
            raise RuntimeError(
                "Cannot derive both pT and energy from on-shell conditions!")

        # Minimum energy and pT
        m = particle.m
        min_e = 0.0
        if None in pt_resolutions[pdgid]:
            min_e = m
        min_pt = 0.0

        # Smear four-momenta
        e = None
        if None not in energy_resolutions[pdgid]:
            e = min_e - 1.0
            while e <= min_e:
                e = _smear_variable(particle.e, energy_resolutions, pdgid)
        pt = None
        if None not in pt_resolutions[pdgid]:
            pt = min_pt - 1.0
            while pt <= min_pt:
                pt = _smear_variable(particle.pt, pt_resolutions, pdgid)
        eta = _smear_variable(particle.eta, eta_resolutions, pdgid)
        phi = _smear_variable(particle.phi(), phi_resolutions, pdgid)
        while phi > 2.0 * np.pi:
            phi -= 2.0 * np.pi
        while phi < 0.0:
            phi += 2.0 * np.pi

        # Construct particle
        smeared_particle = MadMinerParticle()

        if None in energy_resolutions[pdgid]:
            # Calculate E from on-shell conditions
            smeared_particle.setptetaphim(pt, eta, phi, particle.m)

        elif None in pt_resolutions[pdgid]:
            # Calculate pT from on-shell conditions
            if e > m:
                pt = (e**2 - m**2)**0.5 / np.cosh(eta)
            else:
                pt = 0.0
            smeared_particle.setptetaphie(pt, eta, phi, e)

        else:
            # Everything smeared manually
            smeared_particle.setptetaphie(pt, eta, phi, e)

        # PDG id (also sets charge)
        smeared_particle.set_pdgid(pdgid)

        smeared_particles.append(smeared_particle)

    return smeared_particles