示例#1
0
    def example2():

        from pyigrf.pyigrf import GetIGRF
        from scipy import arange, arcsin, rad2deg

        xlat = -11.95
        xlon = 283.13
        year = 2004.75
        altlim = [90, 500.]
        altstp = 10.

        altbins = arange(altlim[0], altlim[1] + altstp, altstp)

        for i in range(len(altbins)):

            bn, be, bd, xl, icode = GetIGRF(xlat, xlon, altbins[i], year)

            # Horizontal component
            bh = (bn**2 + be**2)**.5
            # Total component
            ba = (bn**2 + be**2 + bd**2)**.5
            # Dip angle
            dip = rad2deg(arcsin(bd / ba))
            # Declination angle
            dec = rad2deg(arcsin(be / bh))

            print(i, altbins[i], bn, be, bd, xl, icode)
            print(bh, ba, dip, dec)
            print('')
示例#2
0
def get_stroke_angle(t, f, amp, u, v, k, phase=0.5 * PI):
    """
    Stroke position function w/ J. Wang's shape parameter. The control input 
    u adds a asymmetric velicty to the stroke positon fuction, while the control
    input v adds changes the mean stroke position.

    Arguments:
        t     = array of time points (s)
        f     = flapping frequency (Hz)
        amp   = stroke amplitude 
        u     = control input, scalar or array
        v     = control input, s
        k     = shape parameter near 0 => sine wave, near 1=> sawtooth
    """
    f1 = f / (2 * u)
    f2 = 1 / (2 / f - 1 / f1)
    phi_A = amp / scipy.arcsin(k) * scipy.arcsin(
        k * scipy.sin(2 * PI * f1 * scipy.fmod(t, 1 / f) + phase))
    phi_B = amp / scipy.arcsin(k) * scipy.arcsin(
        k * scipy.sin(2 * PI * f2 * (1 / (2 * f2) - 1 /
                                     (2 * f1) + scipy.fmod(t, 1 / f)) + phase))
    phi = phi_A * (scipy.fmod(t, 1 / f) < 1 /
                   (2 * f1)) + phi_B * (scipy.fmod(t, 1 / f) >= 1 /
                                        (2 * f1)) + v
    return phi
示例#3
0
def dl_to_rphi_2d(d,l,degree=False,ro=1.,phio=0.):
    """
    NAME:

       dl_to_rphi_2d

    PURPOSE:

       convert Galactic longitude and distance to Galactocentric radius and azimuth

    INPUT:

       d - distance

       l - Galactic longitude [rad/deg if degree]

    KEYWORDS:

       degree= (False): l is in degrees rather than rad

       ro= (1) Galactocentric radius of the observer

       phio= (0) Galactocentric azimuth of the observer [rad/deg if degree]

    OUTPUT:

       (R,phi); phi in degree if degree

    HISTORY:

       2012-01-04 - Written - Bovy (IAS)

    """
    scalarOut, listOut= False, False
    if isinstance(d,(int,float)):
        d= sc.array([d])
        scalarOut= True
    elif isinstance(d,list):
        d= sc.array(d)
        listOut= True
    if isinstance(l,(int,float)):
        l= sc.array([l])
    elif isinstance(l,list):
        l= sc.array(l)
    if degree:
        l*= _DEGTORAD
    R= sc.sqrt(ro**2.+d**2.-2.*d*ro*sc.cos(l))
    phi= sc.arcsin(d/R*sc.sin(l))
    indx= (ro/sc.cos(l) < d)*(sc.cos(l) > 0.)
    phi[indx]= sc.pi-sc.arcsin(d[indx]/R[indx]*sc.sin(l[indx]))
    if degree:
        phi/= _DEGTORAD
    phi+= phio
    if scalarOut:
        return (R[0],phi[0])
    elif listOut:
        return (list(R),list(phi))
    else:
        return (R,phi)
示例#4
0
def rphi_to_dl_2d(R,phi,degree=False,ro=1.,phio=0.):
    """
    NAME:

       rphi_to_dl_2d

    PURPOSE:

       convert Galactocentric radius and azimuth to distance and Galactic longitude

    INPUT:

       R - Galactocentric radius

       phi - Galactocentric azimuth [rad/deg if degree]

    KEYWORDS:

       degree= (False): phi is in degrees rather than rad

       ro= (1) Galactocentric radius of the observer

       phio= (0) Galactocentric azimuth of the observer [rad/deg if degree]

    OUTPUT:

       (d,l); phi in degree if degree

    HISTORY:

       2012-01-04 - Written - Bovy (IAS)

    """
    scalarOut, listOut= False, False
    if isinstance(R,(int,float)):
        R= sc.array([R])
        scalarOut= True
    elif isinstance(R,list):
        R= sc.array(R)
        listOut= True
    if isinstance(phi,(int,float)):
        phi= sc.array([phi])
    elif isinstance(phi,list):
        phi= sc.array(phi)
    phi-= phio
    if degree:
        phi*= _DEGTORAD
    d= sc.sqrt(R**2.+ro**2.-2.*R*ro*sc.cos(phi))
    l= sc.arcsin(R/d*sc.sin(phi))
    indx= (ro/sc.cos(phi) < R)*(sc.cos(phi) > 0.)
    l[indx]= sc.pi-sc.arcsin(R[indx]/d[indx]*sc.sin(phi[indx]))
    if degree:
        l/= _DEGTORAD
    if scalarOut:
        return (d[0],l[0])
    elif listOut:
        return (list(d),list(l))
    else:
        return (d,l)
示例#5
0
def get_angle (sin_in, cos_in):
    """ Just use arctan2 - much more efficient"""
    if (sin_in >= 0.0 and cos_in >= 0.0):     out = sc.arcsin(sin_in)
    elif (sin_in >= 0.0 and cos_in < 0.0):    out = ma.pi-sc.arcsin(sin_in)
    elif (sin_in < 0.0 and cos_in < 0.0):     out = ma.pi-sc.arcsin(sin_in)
    elif (sin_in < 0.0 and cos_in >= 0.0):    out = 2.0*ma.pi + sc.arcsin(sin_in)
    else: out = float('nan')
    return out
示例#6
0
def euler_from_qarray(q,tol=0.499):
    """
    Get array of euler angles from array of quaternions. Note, array of euler angles 
    will be in columns of [heading,attitude,bank].

    Euler angle convention - similar to NASA standard airplane, but with y and z axes 
    swapped to conform with x3d. (in order of application)
        1.0 rotation about y-axis
        2.0 rotation about z-axis
        3.0 rotation about x-axis
    """
    qw = q[:,0]
    qx = q[:,1]
    qy = q[:,2]
    qz = q[:,3]

    head = scipy.zeros((q.shape[0],))
    atti = scipy.zeros((q.shape[0],))
    bank = scipy.zeros((q.shape[0],))

    test = qx*qy - qz*qw # test for north of south pole

    # Points not at north or south pole
    mask0 = scipy.logical_and(test <= tol, test >= -tol)
    qw_0 = qw[mask0]
    qx_0 = qx[mask0]
    qy_0 = qy[mask0]
    qz_0 = qz[mask0]
    head[mask0] = scipy.arctan2(2.0*qy_0*qw_0 - 2.0*qx_0*qz_0, 1.0 - 2.0*qy_0**2 - 2.0*qz_0**2)
    atti[mask0] = scipy.arcsin(2.0*qx_0*qy_0 + 2.0*qz_0*qw_0)
    bank[mask0] = scipy.arctan2(2.0*qx_0*qw_0 - 2.0*qy_0*qz_0, 1.0 - 2.0*qx_0**2 - 2.0*qz_0**2)

    # Points at north pole
    mask1 = test > tol
    qw_1 = qw[mask1]
    qx_1 = qx[mask1]
    qy_1 = qy[mask1]
    qz_1 = qz[mask1]
    head[mask1] = 2.0*scipy.arctan2(qx_1,qw_1)
    atti[mask1] = scipy.arcsin(2.0*qx_1*qy_1 + 2.0*qz_1*qw_1)
    bank[mask1] = scipy.zeros((qw_1.shape[0],))

    # Points at south pole
    mask2 = test < -tol
    qw_2 = qw[mask2]
    qx_2 = qx[mask2]
    qy_2 = qy[mask2]
    qz_2 = qz[mask2]
    head[mask2] = -2.0*scipy.arctan2(qx_2,qw_2)
    atti[mask2] = scipy.arcsin(2.0*qx_2*qy_2 + 2.0*qz_2*qw_2)
    bank[mask2] = scipy.zeros((qw_2.shape[0],))

    euler_angs = scipy.zeros((q.shape[0],3))
    euler_angs[:,0] = head
    euler_angs[:,1] = atti
    euler_angs[:,2] = bank
    return euler_angs
示例#7
0
def phase(theta_i, alpha, p, m):
    '''输入的theta 是角度不是弧度'''
    theta_i = np.array(theta_i)
    theta_i = theta_i * pi / 180
    if p != 0:
        theta_i[theta_i > real(arcsin(m))] = None

    #     costheta_r = np.sqrt(1 - np.sin(theta_i/m)**2)
    theta_r = real(arcsin(sin(theta_i) / m))  # 这里默认给出复数形式,取实数部分,

    return 2 * alpha * (cos(theta_i) - p * m * cos(theta_r))
示例#8
0
文件: quat.py 项目: buguen/minf
def matrixToEuler(m,order='Aerospace',inDegrees=True):
    if order == 'Aerospace' or order == 'ZYX':
        sp = -m[2,0]
        if sp < (1-EPS):
            if sp > (-1+EPS):
                p = arcsin(sp)
                r = arctan2(m[2,1],m[2,2])
                y = arctan2(m[1,0],m[0,0])
            else:
                p = -pi/2.
                r = 0
                y = pi-arctan2(-m[0,1],m[0,2])
        else:
            p = pi/2.
            y = arctan2(-m[0,1],m[0,2])
            r = 0
        
        if inDegrees:
            return degrees((y,p,r))
        else:
            return (y,p,r)
    elif order == 'BVH' or order == 'ZXY':
        sx = m[2,1]
        if sx < (1-EPS):
            if sx > (-1+EPS):
                x = arcsin(sx)
                z = arctan2(-m[0,1],m[1,1])
                y = arctan2(-m[2,0],m[2,2])
            else:
                x = -pi/2
                y = 0
                z = -arctan2(m[0,2],m[0,0])
        else:
            x = pi/2
            y = 0
            z = arctan2(m[0,2],m[0,0])
        if inDegrees:
            return degrees((z,x,y))
        else:
            return (z,x,y)

    elif order == "ZXZ":
        x = arccos(m[2,2])
        z2 = arctan2(m[2,0],m[2,1])
        z1 = arctan2(m[0,2],-m[1,2])
        if inDegrees:
            return degrees((z1,x,z2))
        else:
            return (z1,x,z2)
示例#9
0
def haversine(point1, point2, lon1=None, lat1=None, lon2=None, lat2=None):
    """

    Haversine function calculates distance (in miles) between two points in lat/long coordinates. See
    https://gis.stackexchange.com/questions/279109/calculate-distance-between-a-coordinate-and-a-county-in-geopandas

    :param point1: Shapely point. Long then lat.
    :param point2: Shapely point. Long then lat.
    :param lon1, lat1, lon2, lat2: Alternatively, supply the longitudes and lattitudes manually.
    :return: Distance in miles.
    """

    # Retrieve lat and long
    if lon1 is None or lat1 is None:
        lon1, lat1 = list(point1.coords[:][0][0:])
    if lon2 is None or lat2 is None:
        lon2, lat2 = list(point2.coords[:][0][0:])

    # convert decimal degrees to radians
    lon1, lat1, lon2, lat2 = map(scipy.radians, [lon1, lat1, lon2, lat2])

    # haversine formula
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    a = scipy.sin(dlat / 2)**2 + scipy.cos(lat1) * scipy.cos(lat2) * scipy.sin(
        dlon / 2)**2
    c = 2 * scipy.arcsin(scipy.sqrt(a))
    r = 3956  # Radius of earth in miles. Use 6371 for km
    return c * r
示例#10
0
def to_YPR(quaternion):
    q0, q1, q2, q3 = quaternion
    roll = sp.arctan2(2 * (q0 * q1 + q2 * q3), (q0**2 - q1**2 - q2**2 + q3**2))
    pitch = sp.arcsin(-2 * (q1 * q3 - q0 * q2))
    yaw = sp.arctan2(2 * (q1 * q2 + q0 * q3), (q0**2 + q1**2 - q2**2 - q3**2))

    return roll, pitch, yaw
示例#11
0
def example_theta():

    pol = 'TM'
    ncore = 2
    nclad = 1

    d = np.linspace(0.02, 3, 500)  # in units of high-index wavelength
    mmax = 3  # highest order of waveguide mode to consider (m = # of field antinodes)

    # Beta values of each waveguide mode for each slab thickness.  0th index is slab height, 1st index is mode.
    Thetas = np.zeros((len(d), mmax))

    for i, di in enumerate(d):
        Bs = getBetas(ncore, nclad, di, pol=pol, mmax=mmax)
        Thetas[i, :] = 90 - (getTheta(Bs, ncore) * 180 / pi)

    for m in range(mmax):
        plt.plot(Thetas[:, m], d)

    tb = sp.arctan(1 / ncore)
    plt.axvline(tb * 180 / pi, color='k', ls='--')

    tc = sp.arcsin(1 / ncore)
    plt.axvline(tc * 180 / pi, color='y', ls='--')

    plt.xlim(0, 90)

    plt.xlabel('Angle (degrees)')
    plt.ylabel(r'Height/$\lambda$')

    plt.show()
示例#12
0
def Finesse(d, pol='TM', m=1):

    R = Ref(d, pol=pol, mode=m)

    F = pi / (2 * sp.arcsin((1 - R) / (2 * R**0.5)))
    F = np.nan_to_num(F)
    return F
示例#13
0
    def get_bl(self, ra=None, dec=None):
        """
        http://scienceworld.wolfram.com/astronomy/GalacticCoordinates.html
        """
        if ra == None: ra = self.get_column("RA")
        if dec == None: dec = self.get_column("DEC")
        if type(ra) == float:
            ral = scipy.zeros(1)
            ral[0] = ra
            ra = ral
        if type(dec) == float:
            decl = scipy.zeros(1)
            decl[0] = dec
            dec = decl

        c62 = math.cos(62.6 * D2R)
        s62 = math.sin(62.6 * D2R)

        b = scipy.sin(dec * D2R) * c62
        b -= scipy.cos(dec * D2R) * scipy.sin((ra - 282.25) * D2R) * s62
        b = scipy.arcsin(b) * R2D

        cosb = scipy.cos(b * D2R)
        #l minus 33 degrees
        lm33 = (scipy.cos(dec * D2R) / cosb) * scipy.cos((ra - 282.25))
        l = scipy.arccos(lm33) * R2D + 33.0
        return b, l
示例#14
0
def representativeness_index_per_category(standardized_methods,
                                          standardized_lcis):
    """
    Calculates a Representativeness Index per impact category on one or many standardized LCI(s)

    :param pd.DataFrame standardized_methods:
        Dataframe constituted by one or many method(s) aggregated, ie. constituted by several columns representing
        impact categories
    :param pd.DataFrame standardized_lcis:
        LCI(s) data formatted with standardize_lci()
    :return:
        Representativeness index per impact category
    :rtype: pd.DataFrame
    """
    standardized_lcis.fillna(value=0, inplace=True)
    standardized_methods.fillna(value=0, inplace=True)

    # Checking substance flows (indexes) are the same between lci and method
    if all(standardized_methods.index == standardized_lcis.index):
        representativeness_index = pd.DataFrame(
            index=standardized_methods.columns,
            columns=standardized_lcis.columns)
        for i in range(0, representativeness_index.shape[0]):
            residuals = linalg.lstsq(
                sp.matrix(standardized_methods.iloc[:, i]).T,
                standardized_lcis)[1]
            representativeness_index.iloc[i, :] = sp.cos(
                sp.real(sp.arcsin(sp.sqrt(residuals)))).T

    else:
        raise Exception('Substance flows do not match between method and lci.')

    return representativeness_index
示例#15
0
文件: shapes.py 项目: atkm/thesis
def rayshape_old(self, A, d, n):
    # We'll get 4n+4 points, but there are duplicates at the four corners.
    # So, total = 4n
    rad = sp.sqrt(A/sp.pi) # the radius of the base circle
    angle = sp.arcsin(1/(sp.sqrt(2) * (1+d))) # each quadrant isn't -pi/4 < theta < pi/4. A bit less than that.
    base = sp.linspace(-angle, angle, n+1) # split up a quarter of the circumference to n pieces (omitting the point at pi/4)
    C1 = []
    for arg in base:
        x = -d + (rad+d)*sp.cos(arg)
        y = (rad+d)*sp.sin(arg)
        C1.append((x,y))
    # Construct C3, which is the image of C1 by rotation by pi.
    C3 = []
    for pt in C1:
        C3.append((-pt[0] , -pt[1]))
    # Now construct C2
    base = sp.linspace(sp.pi/2 - angle, sp.pi/2 + angle, n+1) # split up a quarter of the circumference to n pieces
    C2 = []
    for arg in base:
        x = (rad+d)*sp.cos(arg)
        y = -d + (rad+d)*sp.sin(arg)
        C2.append((x,y))
    # Construct C4 from C2 by applying rotation by pi.
    C4 = []
    for pt in C2:
        C4.append((-pt[0] , -pt[1]))
 
    return sp.vstack((C1, C2, C3, C4)) 
示例#16
0
def rect_to_cyl(X,Y,Z):
    """
    NAME:

       rect_to_cyl

    PURPOSE:

       convert from rectangular to cylindrical coordinates

    INPUT:

       X, Y, Z - rectangular coordinates

    OUTPUT:

       [:,3] R,phi,z

    HISTORY:

       2010-09-24 - Written - Bovy (NYU)

    """
    R= sc.sqrt(X**2.+Y**2.)
    phi= sc.arcsin(Y/R)
    if isinstance(X,float) and X < 0.:
        phi= m.pi-phi
    elif isinstance(X,sc.ndarray):
        phi[(X < 0.)]= m.pi-phi[(X < 0.)]
    return (R,phi,Z)
def example_Attenuation():
	
	ncore = 2
	nclad = 1
	nsub  = 1
	
	d     = np.linspace(0.02,3,100)
	angle = np.linspace(0.02,pi/2.,100)
	
	tc = arcsin(nclad/ncore)
	
	a = np.array([Attenuation(x,ncore,nclad,nsub,y,pol='TM') for x in d for y in angle])
	
	a = a.reshape(len(d),len(angle))
	
	ext = [np.amin(angle)*180/pi,np.amax(angle)*180/pi,np.amin(d),np.amax(d)]
	plt.imshow(a.real,interpolation='nearest',origin='lower',extent=ext,aspect='auto',vmax=2000)
	plt.colorbar()
	plt.axvline(tc*180/pi,color='w',ls=':')
	
	plt.figure()
	plt.imshow(a.imag,interpolation='nearest',origin='lower',extent=ext,aspect='auto',vmax=2000)
	plt.colorbar()

	plt.show()
示例#18
0
def elaz2radec_lst(el, az, lst, lat = 38.43312) :
    """DO NOT USE THIS ROUTINE FOR ANTHING THAT NEEDS TO BE RIGHT.  IT DOES NOT
    CORRECT FOR PRECESSION.

    Calculates the Ra and Dec from elavation, aximuth, LST and Latitude.

    This function is vectorized with numpy so should be fast.  Standart numpy
    broadcasting should also work.

    All angles in degrees, lst in seconds. Latitude defaults to GBT.
    """

    # Convert everything to radians.
    el = sp.radians(el)
    az = sp.radians(az)
    lst = sp.array(lst, dtype = float)*2*sp.pi/86400
    lat = sp.radians(lat)
    # Calculate dec.
    dec = sp.arcsin(sp.sin(el)*sp.sin(lat) +
                    sp.cos(el)*sp.cos(lat)*sp.cos(az))
    # Calculate the hour angle
    ha = sp.arccos((sp.sin(el) - sp.sin(lat)*sp.sin(dec)) /
                   (sp.cos(lat)*sp.cos(dec)))
    ra = sp.degrees(lst - ha) % 360

    return ra, sp.degrees(dec)
示例#19
0
def get_stripe_points(mu_lim, nu_lim, r_lim, number=1):  #GC checked
    mu = np.random.uniform(low=mu_lim[0], high=mu_lim[1], size=number)
    u, w = np.random.uniform(size=number), np.random.uniform(size=number)
    nu = sc.arcsin(u * (sc.sin(nu_lim[1]) - sc.sin(nu_lim[0])) +
                   sc.sin(nu_lim[0]))
    r = r_lim[1] * (w**(1. / 3.))
    return (mu, nu, r)
示例#20
0
文件: nomad.py 项目: reilastro/nomad
    def get_bl(self,ra=None,dec=None):
        """
        http://scienceworld.wolfram.com/astronomy/GalacticCoordinates.html
        """
        if ra==None: ra=self.get_column("RA")
        if dec==None: dec=self.get_column("DEC")
        if type(ra)==float: 
            ral=scipy.zeros(1)
            ral[0]=ra
            ra=ral
        if type(dec)==float: 
            decl=scipy.zeros(1)
            decl[0]=dec
            dec=decl

        c62=math.cos(62.6*D2R)
        s62=math.sin(62.6*D2R)
        
        b=scipy.sin(dec*D2R)*c62
        b-=scipy.cos(dec*D2R)*scipy.sin((ra-282.25)*D2R)*s62
        b=scipy.arcsin(b)*R2D
        
        cosb=scipy.cos(b*D2R)
        #l minus 33 degrees
        lm33=(scipy.cos(dec*D2R)/cosb)*scipy.cos((ra-282.25))
        l=scipy.arccos(lm33)*R2D+33.0
        return b,l
示例#21
0
def compute_and_plot(ax, n2):
    xlist1    = np.linspace(-1, 0, 100)
    xlist2    = np.linspace( 0, 1, 100) # cover the transmitted region
    ylist_i   = np.linspace(-1, 0, 100)
    ylist_r   = np.linspace( 0, 1, 100)
    ylist     = np.linspace(-1, 1, 100)
    x1, y1_i  = np.meshgrid(xlist1, ylist_i)
    x1, y1_r  = np.meshgrid(xlist1, ylist_r)
    x2, y2    = np.meshgrid(xlist2, ylist)
    th1       = sp.arcsin(n2/n1)
    # Incident wave
    Z1_i      = np.cos(k1*(x1*np.cos(th1) + y1_i*np.sin(th1)))
    Z1_r      = np.cos(k1*(x1*np.cos(th1) - y1_r*np.sin(th1)))
    # Reflected wave
    Z2        = (2*n1*np.cos(th1)/(n1*np.cos(th1)+1j*sp.sqrt(n1**2*np.sin(th1)**2-1))).real*np.exp(-x2)* \
          np.cos(k1*y2*np.sin(th1))  # Pulled from Griffiths Electrodynamics 4th ed.
    L = np.linspace(-1.0, 0, 50)
    plt.plot(L, -np.sin(th1)/np.cos(th1)*L, color='red')
    plt.plot(L, np.sin(th1)/np.cos(th1)*L, color='red')
    plt.vlines(0, -1, 1, colors='k')

    incident  = plt.contourf(x1, y1_i, Z1_i)
    reflected = plt.contourf(x1, y1_r, Z1_r)
    plt.colorbar(incident)
    transmitted = plt.contourf(x2, y2, Z2)
示例#22
0
文件: wcs.py 项目: MCTwo/CodeCDF
def pix2sky(header,x,y):
	hdr_info = parse_header(header)
	x0 = x-hdr_info[1][0]+1.	# Plus 1 python->image
	y0 = y-hdr_info[1][1]+1.
	x0 = x0.astype(scipy.float64)
	y0 = y0.astype(scipy.float64)
	x = hdr_info[2][0,0]*x0 + hdr_info[2][0,1]*y0
	y = hdr_info[2][1,0]*x0 + hdr_info[2][1,1]*y0
	if hdr_info[3]=="DEC":
		a = x.copy()
		x = y.copy()
		y = a.copy()
		ra0 = hdr_info[0][1]
		dec0 = hdr_info[0][0]/raddeg
	else:
		ra0 = hdr_info[0][0]
		dec0 = hdr_info[0][1]/raddeg
	if hdr_info[5]=="TAN":
		r_theta = scipy.sqrt(x*x+y*y)/raddeg
		theta = arctan(1./r_theta)
		phi = arctan2(x,-1.*y)
	elif hdr_info[5]=="SIN":
		r_theta = scipy.sqrt(x*x+y*y)/raddeg
		theta = arccos(r_theta)
		phi = artan2(x,-1.*y)
	ra = ra0 + raddeg*arctan2(-1.*cos(theta)*sin(phi-pi),
				   sin(theta)*cos(dec0)-cos(theta)*sin(dec0)*cos(phi-pi))
	dec = raddeg*arcsin(sin(theta)*sin(dec0)+cos(theta)*cos(dec0)*cos(phi-pi))

	return ra,dec
示例#23
0
def xyz2longlat(x,y,z):
    """ converts cartesian x,y,z coordinates into spherical longitude and latitude """
    r = sc.sqrt(x*x + y*y + z*z)
    long = sc.arctan2(y,x)
    d = sc.sqrt(x*x + y*y)
    lat = sc.arcsin(z/r)
    return long*deg, lat*deg, r
示例#24
0
def pix2sky(header,x,y):
	hdr_info = parse_header(header)
	x0 = x-hdr_info[1][0]+1.	# Plus 1 python->image
	y0 = y-hdr_info[1][1]+1.
	x0 = x0.astype(scipy.float64)
	y0 = y0.astype(scipy.float64)
	x = hdr_info[2][0,0]*x0 + hdr_info[2][0,1]*y0
	y = hdr_info[2][1,0]*x0 + hdr_info[2][1,1]*y0
	if hdr_info[3]=="DEC":
		a = x.copy()
		x = y.copy()
		y = a.copy()
		ra0 = hdr_info[0][1]
		dec0 = hdr_info[0][0]/raddeg
	else:
		ra0 = hdr_info[0][0]
		dec0 = hdr_info[0][1]/raddeg
	if hdr_info[5]=="TAN":
		r_theta = scipy.sqrt(x*x+y*y)/raddeg
		theta = arctan(1./r_theta)
		phi = arctan2(x,-1.*y)
	elif hdr_info[5]=="SIN":
		r_theta = scipy.sqrt(x*x+y*y)/raddeg
		theta = arccos(r_theta)
		phi = artan2(x,-1.*y)
	ra = ra0 + raddeg*arctan2(-1.*cos(theta)*sin(phi-pi),
				   sin(theta)*cos(dec0)-cos(theta)*sin(dec0)*cos(phi-pi))
	dec = raddeg*arcsin(sin(theta)*sin(dec0)+cos(theta)*cos(dec0)*cos(phi-pi))

	return ra,dec
示例#25
0
def cartesian_to_sky(position, wrap=True, degree=True):
    """Transform cartesian coordinates into distance, RA, Dec.

	Parameters
	----------
	position : array of shape (N,3)
		position in cartesian coordinates.
	wrap : bool, optional
		whether to wrap ra into [0,2*pi]
	degree : bool, optional
		whether RA, Dec are in degree (True) or radian (False).

	Returns
	-------
	dist : array
		distance.
	ra : array
		RA.
	dec : array
		Dec.

	"""
    dist = distance(position)
    ra = scipy.arctan2(position[:, 1], position[:, 0])
    if wrap: ra %= 2. * constants.pi
    dec = scipy.arcsin(position[:, 2] / dist)
    if degree: return dist, ra / constants.degree, dec / constants.degree
    return dist, ra, dec
示例#26
0
    def __init__(self,
                 rarange=[0., 360.],
                 decrange=[-90., 90.],
                 nbar=None,
                 rng=None,
                 seed=None,
                 RA='RA',
                 DEC='DEC',
                 wrap=True,
                 **attrs):

        area = 4 * constants.pi * (rarange[1] -
                                   rarange[0]) / 360. / constants.degree**2
        if rng is None: rng = scipy.random.RandomState(seed=seed)
        self.rng = rng
        size = rng.poisson(nbar * area)
        ra = rng.uniform(low=rarange[0], high=rarange[1], size=size)
        dec = scipy.arcsin(1. - rng.uniform(low=0, high=1, size=size) *
                           2.) / constants.degree
        mask = (dec >= decrange[0]) & (dec <= decrange[1])
        ra = ra[mask]
        dec = dec[mask]
        if wrap: ra %= 360.
        super(RandomSkyCatalogue, self).__init__(columns={
            RA: ra,
            DEC: dec
        },
                                                 seed=seed,
                                                 size=size,
                                                 nbar=nbar,
                                                 **attrs)
示例#27
0
def elaz2radec_lst(el, az, lst, lat=38.43312):
    """DO NOT USE THIS ROUTINE FOR ANTHING THAT NEEDS TO BE RIGHT.  IT DOES NOT
    CORRECT FOR PRECESSION.

    Calculates the Ra and Dec from elavation, aximuth, LST and Latitude.

    This function is vectorized with numpy so should be fast.  Standart numpy
    broadcasting should also work.

    All angles in degrees, lst in seconds. Latitude defaults to GBT.
    """

    # Convert everything to radians.
    el = sp.radians(el)
    az = sp.radians(az)
    lst = sp.array(lst, dtype=float) * 2 * sp.pi / 86400
    lat = sp.radians(lat)
    # Calculate dec.
    dec = sp.arcsin(
        sp.sin(el) * sp.sin(lat) + sp.cos(el) * sp.cos(lat) * sp.cos(az))
    # Calculate the hour angle
    ha = sp.arccos(
        (sp.sin(el) - sp.sin(lat) * sp.sin(dec)) / (sp.cos(lat) * sp.cos(dec)))
    ra = sp.degrees(lst - ha) % 360

    return ra, sp.degrees(dec)
示例#28
0
文件: gid.py 项目: isaxs/pynx
def FhklDWBA4(x,y,z,h,k,l=None,occ=None,alphai=0.2,alphaf=None,substrate=None,wavelength=1.0,e_par=0.,e_perp=1.0,gpu_name="CPU",use_fractionnal=True,language="OpenCL",cl_platform="",separate_paths=False):
  """
  Calculate the grazing-incidence X-ray scattered intensity taking into account
  4 scattering paths, for a nanostructure object located above a given substrate.
  The 5th path is the scattering from the substrate, assumed to be below the
  interface at z=0.
  
  x,y,z: coordinates of the atoms in fractionnal coordinates (relative to the 
         substrate unit cell)- if use_fractionnal==False, these should be given in Angstroems
  h,k,l: reciprocal space coordinates. If use_fractionnal==False, these should be given
         in inverse Angstroems (multiplied by 2pi - physicist 'k' convention, |k|=4pisin(theta)/lambda,
         i.e. these correspond to k_x,k_y,k_z).
  alphai, alphaf: incident and outgoing angles, in radians
  substrate: the substrate material, as a pynx.gid.Crystal object - this will be used
             to calculate the material refraction index.
  wavelength: in Angstroems
  e_par,e_perp: percentage of polarisation parallel and perpendicular to the incident plane
  use_fractionnal: if True (the default), then coordinates for atoms and reciprocal
                   space are given relatively to the unit cell, otherwise in Angstroems
                   and 2pi*inverse Angstroems.
  
  Note: Either l *OR* alphaf must be supplied - it is assumed that the lattice
  coordinates are such that the [001] direction is perpendicular to the surface.
  """
  nrj=W2E(wavelength)
  if use_fractionnal: 
    c=substrate.uc.parameters()[2]
    s_fact=1.0
  else: 
    c=2*pi
    s_fact=1/c
  if alphaf==None:
    # alphaf, computed from l: l.c* = (sin(alpha_f) + sin(alpha_i))/wavelength
    alphaf=scipy.arcsin(l/c*wavelength-scipy.sin(alphai))

  # Incident wave
  w=Wave(alphai,e_par,e_perp,nrj)
  dw=DistortedWave(None,substrate,w)
  # Reflected wave after the dot
  w1=Wave(alphaf,e_par,e_perp,nrj)
  dw1=DistortedWave(None,substrate,w1)

  # First path, direct diffraction
  l=c*scipy.sin(alphaf+alphai)/wavelength
  f1=gpu.Fhkl_thread(h*s_fact,k*s_fact,l*s_fact,x,y,z,occ=occ,gpu_name=gpu_name,language=language,cl_platform=cl_platform)[0]

  # Second path, reflection before
  l=c*scipy.sin(alphaf-alphai)/wavelength
  f2=gpu.Fhkl_thread(h*s_fact,k*s_fact,l*s_fact,x,y,z,occ=occ,gpu_name=gpu_name,language=language,cl_platform=cl_platform)[0]*dw.Riy

  # Third path, reflection after dot
  l=c*scipy.sin(-alphaf+alphai)/wavelength
  f3=gpu.Fhkl_thread(h*s_fact,k*s_fact,l*s_fact,x,y,z,occ=occ,gpu_name=gpu_name,language=language,cl_platform=cl_platform)[0]*dw1.Riy

  # Fourth path, reflection before and after dot
  l=c*scipy.sin(-alphaf-alphai)/wavelength
  f4=gpu.Fhkl_thread(h*s_fact,k*s_fact,l*s_fact,x,y,z,occ=occ,gpu_name=gpu_name,language=language,cl_platform=cl_platform)[0]*dw.Riy*dw1.Riy
  if separate_paths: return f1,f2,f3,f4
  return f1+f2+f3+f4
示例#29
0
def sin_seq(A = 1.0, f = 1.0, T = 1.0, delta = 0.1):
    t = 0.0
    events = []
    # Note use of round() to compensate for floating-point arithmetic errors
    # that lead to inexact results.
    while t <= T:
        v = delta * floor(round(A*sin(2*pi*f*t) / delta,10))
        events += [(t, v)]
        tm = fmod(abs(t), 0.5/f)
        if tm < 0.25/f:
            vq = delta * (floor(round(A*sin(2*pi*f*tm) / delta,10)) + 1.0)
            dt = arcsin(vq/A)/(2*pi*f) - tm
        else:
            vq = delta * (floor(round(A*sin(2*pi*f*tm) / delta,10)) - 1.0)
            dt = (pi - arcsin(vq/A))/(2*pi*f) - tm             
        t += dt
    return array(events)
示例#30
0
def _arcsin_sqrt_transform(values):
    a = sp.array(values)
    if min(a) < 0 or max(a) > 1:
        logger.debug('Some values are outside of range [0,1], hence skipping transformation!')
        return None
    else:
        vals = sp.arcsin(sp.sqrt(a))
    return vals
示例#31
0
 def azimuth(self, date):
     dec = self.declination(date)
     ha = self.hour_angle(date)
     az = sp.arcsin(sp.cos(dec) * sp.sin(ha) / sp.cos(self.elevation(date)))
     if (sp.cos(ha) >= (sp.tan(dec) / sp.tan(self.lat))):
         return az
     else:
         return (sp.pi - az)
示例#32
0
def theta_def(theta_i, p, m):
    '''输入的theta 是度数不是弧度,得到的是偏转角'''
    theta_i = theta_i * pi / 180
    theta_r = arcsin(sin(theta_i) / m)
    ths = (2 * p * theta_r - 2 * theta_i - (p - 1) * pi)
    ths = real(ths)
    res = ths * 180 / pi
    return res
示例#33
0
 def test_healpix_sphere(self):    
     # Sphere parameters.
     R = 5
     # Expected outputs of healpix_sphere() applied to inputs.
     sigma_a = sqrt(3 - 3*sin(a[1]))
     ha = (pi/4*(1 - sigma_a), pi/4*(2 - sigma_a))  
     hb = (ha[0], -ha[1])
     healpix_sphere_outputs = [
         (0, 0), 
         (0, pi/4), 
         (0, -pi/4), 
         (pi/2, 0), 
         (-pi/2, 0), 
         (-pi, 0),
         (-3*pi/4, pi/2), 
         (-3*pi/4, -pi/2), 
         ha, 
         hb
     ]        
     healpix_sphere_outputs = [tuple(R*array(p)) for p in 
                               healpix_sphere_outputs]       
     
     # Forward projection should be correct on test points.
     f = Proj(proj='healpix', R=R)
     given = inputs
     get = [f(*p, radians=True) for p in given]
     expect = healpix_sphere_outputs
     # Fuzz to allow for rounding errors:
     error = 1e-12
     print
     print '='*80
     print 'HEALPix forward projection, sphere with radius R = %s' % R
     print 'input (radians) / expected output (meters) / received output'
     print '='*80
     for i in range(len(get)):
         print given[i], expect[i], get[i] 
         self.assertTrue(rel_err(get[i], expect[i]) < error)
      
     # Inverse of projection of a point p should yield p.
     given = get
     get = [f(*q, radians=True, inverse=True) for q in given]
     expect = inputs
     print '='*80
     print 'HEALPix inverse projection, sphere with radius R = %s' % R
     print 'input (meters) / expected output (radians) / received output'
     print '='*80
     for i in range(len(get)):
         print given[i], expect[i], get[i]         
         self.assertTrue(rel_err(get[i], expect[i]) < error)
         
     # Inverse projection of p below should return longitude of -pi.
     # Previously, it was returning a number slightly less than pi
     # because of a rounding error, which got magnified by
     # wrap_longitude()
     p = R*array((-7*pi/8, 3*pi/8))
     get = f(*p, radians=True, inverse=True)
     expect = (-pi, arcsin(1 - 1.0/12))   
     self.assertTrue(rel_err(get, expect) < error)
示例#34
0
文件: phenotype.py 项目: timeu/PyGWAS
 def _arcsin_sqrt_transform(self, verbose=False):
     a = sp.array(self.values)
     if min(a) < 0 or max(a) > 1:
         log.debug('Some values are outside of range [0,1], hence skipping transformation!')
         return False
     else:
         vals = sp.arcsin(sp.sqrt(a))
     self._perform_transform(vals,"arcsin")
     return True
示例#35
0
def law_xyz2sgr_gal(X, Y, Z, Xsun=dsun):
    """ From the Law sgr transformation code:  http://www.astro.virginia.edu/~srm4n/Sgr/code.html
    // Transform positions from standard left handed Galactocentric XYZ to  [RIGHT-HANDED]
    // the Galactocentric Sgr system (lambda=0 at the Galactic plane)
    // Input must be in kpc of the form X Y Z
    // Output is in kpc and degrees, of the form X_Sgr,GC Y_Sgr,GC Z_Sgr,GC d_GC lambda_GC beta_GC
    // Note that d is distance from Galactic Center"""
    radpdeg = 3.141592653589793 / 180.0
    #// Define the Euler angles
    phi = (180 + 3.75) * radpdeg
    theta = (90 - 13.46) * radpdeg
    psiGC = (180 + 21.604399) * radpdeg
    #// Rotation angle of phiGC past 180degrees is a useful number
    ang = 21.604399 * radpdeg
    #// Note that the plane does not actually include the G.C., although it is close
    xcenter = -8.5227
    ycenter = -0.3460
    zcenter = -0.0828
    #// Define the rotation matrix from the Euler angles
    GCrot11 = sc.cos(psiGC) * sc.cos(phi) - sc.cos(theta) * sc.sin(
        phi) * sc.sin(psiGC)
    GCrot12 = sc.cos(psiGC) * sc.sin(phi) + sc.cos(theta) * sc.cos(
        phi) * sc.sin(psiGC)
    GCrot13 = sc.sin(psiGC) * sc.sin(theta)
    GCrot21 = -sc.sin(psiGC) * sc.cos(phi) - sc.cos(theta) * sc.sin(
        phi) * sc.cos(psiGC)
    GCrot22 = -sc.sin(psiGC) * sc.sin(phi) + sc.cos(theta) * sc.cos(
        phi) * sc.cos(psiGC)
    GCrot23 = sc.cos(psiGC) * sc.sin(theta)
    GCrot31 = sc.sin(theta) * sc.sin(phi)
    GCrot32 = -sc.sin(theta) * sc.cos(phi)
    GCrot33 = sc.cos(theta)
    #X = -X  #// Make the input system right-handed  ALREADY IS
    X = X + Xsun  #// Transform the input system to heliocentric right handed coordinates
    #// Calculate Z,distance in the SgrGC system
    Temp = GCrot11 * (X + xcenter) + GCrot12 * (Y - ycenter) + GCrot13 * (
        Z - zcenter)
    Temp2 = GCrot21 * (X + xcenter) + GCrot22 * (Y - ycenter) + GCrot23 * (
        Z - zcenter)
    Zs = GCrot31 * (X + xcenter) + GCrot32 * (Y - ycenter) + GCrot33 * (
        Z - zcenter)
    d = sc.sqrt(Temp * Temp + Temp2 * Temp2 + Zs * Zs)
    Zs = -Zs
    #// Calculate the angular coordinates lambdaGC,betaGC
    Temp3 = sc.arctan2(Temp2, Temp) / radpdeg
    if (Temp3 < 0.0): Temp3 = Temp3 + 360.0
    Temp3 = Temp3 + ang / radpdeg
    if (Temp3 > 360.0): Temp3 = Temp3 - 360.0
    lam = Temp3
    beta = sc.arcsin(
        Zs / sc.sqrt(Temp * Temp + Temp2 * Temp2 + Zs * Zs)) / radpdeg
    #// Calculate X,Y in the SgrGC system
    Xs = Temp * sc.cos(ang) - Temp2 * sc.sin(ang)
    Ys = Temp * sc.sin(ang) + Temp2 * sc.cos(ang)
    r = sc.sqrt(Xs * Xs + Ys * Ys + Zs + Zs)
    return Xs, Ys, Zs, lam, beta, r
示例#36
0
def sky2pix(header,ra,dec):
	hdr_info = parse_header(header)
	if scipy.isscalar(ra):
		ra /= raddeg
		dec /= raddeg
	else:
		ra = ra.astype(scipy.float64)/raddeg
		dec = dec.astype(scipy.float64)/raddeg
	if hdr_info[3]=="DEC":
		ra0 = hdr_info[0][1]/raddeg
		dec0 = hdr_info[0][0]/raddeg
	else:
		ra0 = hdr_info[0][0]/raddeg
		dec0 = hdr_info[0][1]/raddeg

	phi = pi + arctan2(-1*cos(dec)*sin(ra-ra0),sin(dec)*cos(dec0)-cos(dec)*sin(dec0)*cos(ra-ra0))
	argtheta = sin(dec)*sin(dec0)+cos(dec)*cos(dec0)*cos(ra-ra0)
	if scipy.isscalar(argtheta):
		theta = arcsin(argtheta)
	else:
		argtheta[argtheta>1.] = 1.
		theta = arcsin(argtheta)

	if hdr_info[5]=="TAN":
		r_theta = raddeg/tan(theta)
		x = r_theta*sin(phi)
		y = -1.*r_theta*cos(phi)
	elif hdr_info[5]=="SIN":
		r_theta = raddeg*cos(theta)
		x = r_theta*sin(phi)
		y = -1.*r_theta*cos(phi)
	if hdr_info[3]=="DEC":
		a = x.copy()
		x = y.copy()
		y = a.copy()
	inv = linalg.inv(hdr_info[2])
	x0 = inv[0,0]*x + inv[0,1]*y
	y0 = inv[1,0]*x + inv[1,1]*y

	x = x0+hdr_info[1][0]-1
	y = y0+hdr_info[1][1]-1

	return x,y
示例#37
0
文件: wcs.py 项目: MCTwo/CodeCDF
def sky2pix(header,ra,dec):
	hdr_info = parse_header(header)
	if scipy.isscalar(ra):
		ra /= raddeg
		dec /= raddeg
	else:
		ra = ra.astype(scipy.float64)/raddeg
		dec = dec.astype(scipy.float64)/raddeg
	if hdr_info[3]=="DEC":
		ra0 = hdr_info[0][1]/raddeg
		dec0 = hdr_info[0][0]/raddeg
	else:
		ra0 = hdr_info[0][0]/raddeg
		dec0 = hdr_info[0][1]/raddeg

	phi = pi + arctan2(-1*cos(dec)*sin(ra-ra0),sin(dec)*cos(dec0)-cos(dec)*sin(dec0)*cos(ra-ra0))
	argtheta = sin(dec)*sin(dec0)+cos(dec)*cos(dec0)*cos(ra-ra0)
	if scipy.isscalar(argtheta):
		theta = arcsin(argtheta)
	else:
		argtheta[argtheta>1.] = 1.
		theta = arcsin(argtheta)

	if hdr_info[5]=="TAN":
		r_theta = raddeg/tan(theta)
		x = r_theta*sin(phi)
		y = -1.*r_theta*cos(phi)
	elif hdr_info[5]=="SIN":
		r_theta = raddeg*cos(theta)
		x = r_theta*sin(phi)
		y = -1.*r_theta*cos(phi)
	if hdr_info[3]=="DEC":
		a = x.copy()
		x = y.copy()
		y = a.copy()
	inv = linalg.inv(hdr_info[2])
	x0 = inv[0,0]*x + inv[0,1]*y
	y0 = inv[1,0]*x + inv[1,1]*y

	x = x0+hdr_info[1][0]-1
	y = y0+hdr_info[1][1]-1

	return x,y
 def OnSomethingChanged(self):
     nOne = self.sldRIOne.value() / 100
     nTwo = self.sldRITwo.value() / 100
     incAng = self.sldIncAng.value()
     refrAng = 180.0 / pi * arcsin(nOne * sin(pi / 180.0 * incAng) / nTwo)
     if isinstance(refrAng, complex):
         self.edtRefrAng.setText('Total Internal Reflection')
     else:
         self.edtRefrAng.setText(str('%5.3f' % (refrAng)))
     self.loCanvas.drawPlot(nOne, nTwo, incAng)
示例#39
0
def cart2sphere(coordlist):

    X_vec = coordlist[:,0]
    Y_vec = coordlist[:,1]
    Z_vec = coordlist[:,2]
    R_vec = sp.sqrt(X_vec**2+Y_vec**2+Z_vec**2)
    Az_vec = np.degrees(sp.arctan2(X_vec,Y_vec))
    El_vec = np.degrees(sp.arcsin(Z_vec/R_vec))
    sp_coords = sp.array([R_vec,Az_vec,El_vec]).transpose()
    return sp_coords
示例#40
0
def list_snell(n_list, th_0):
    """
    return list of angle theta in each layer based on angle th_0 in layer 0,
    using Snell's law. n_list is index of refraction of each layer. Note that
    "angles" may be complex!!
    """
    #Important that the arcsin here is scipy.arcsin, not numpy.arcsin!! (They
    #give different results e.g. for arcsin(2).)
    #Use real_if_close because e.g. arcsin(2 + 1e-17j) is very different from
    #arcsin(2) due to branch cut
    return sp.arcsin(np.real_if_close(n_list[0] * np.sin(th_0) / n_list))
示例#41
0
def snell(n_1, n_2, th_1):
    """
    return angle theta in layer 2 with refractive index n_2, assuming
    it has angle th_1 in layer with refractive index n_1. Use Snell's law. Note
    that "angles" may be complex!!
    """
    #Important that the arcsin here is scipy.arcsin, not numpy.arcsin!! (They
    #give different results e.g. for arcsin(2).)
    #Use real_if_close because e.g. arcsin(2 + 1e-17j) is very different from
    #arcsin(2) due to branch cut
    return sp.arcsin(np.real_if_close(n_1 * np.sin(th_1) / n_2))
示例#42
0
def list_snell(n_list,th_0):
    """
    return list of angle theta in each layer based on angle th_0 in layer 0,
    using Snell's law. n_list is index of refraction of each layer. Note that
    "angles" may be complex!!
    """
    #Important that the arcsin here is scipy.arcsin, not numpy.arcsin!! (They
    #give different results e.g. for arcsin(2).)
    #Use real_if_close because e.g. arcsin(2 + 1e-17j) is very different from
    #arcsin(2) due to branch cut
    return sp.arcsin(np.real_if_close((n_list[:,0]*np.sin(th_0))[:,None] / n_list))
示例#43
0
def snell(n_1, n_2, th_1):
    """
    Return angle theta in layer 2 with refractive index n_2, assuming
    it has angle th_1 in layer with refractive index n_1. Use Snell's law. Note
    that "angles" may be complex!!
    """
    # Important that the arcsin here is scipy.arcsin, not numpy.arcsin!! (They
    # give different results e.g. for arcsin(2).)
    # Use real_if_close because e.g. arcsin(2 + 1e-17j) is very different from
    # arcsin(2) due to branch cut
    return sp.arcsin(np.real_if_close(n_1 * np.sin(th_1) / n_2))
示例#44
0
def cart2sphere(coordlist):
    r2d = 180.0/sp.pi
    d2r = sp.pi/180.0
    
    X_vec = coordlist[:,0]
    Y_vec = coordlist[:,1]
    Z_vec = coordlist[:,2]
    R_vec = sp.sqrt(X_vec**2+Y_vec**2+Z_vec**2)
    Az_vec = sp.arctan2(X_vec,Y_vec)*r2d
    El_vec = sp.arcsin(Z_vec/R_vec)*r2d
    sp_coords = sp.array([R_vec,Az_vec,El_vec]).transpose()
    return sp_coords
示例#45
0
def snell(n_1,n_2,th_1):
    """
    return angle theta in layer 2 with refractive index n_2, assuming
    it has angle th_1 in layer with refractive index n_1. Use Snell's law. Note
    that "angles" may be complex!!
    """
    #Important that the arcsin here is scipy.arcsin, not numpy.arcsin! (They
    #give different results e.g. for arcsin(2).)
    th_2_guess = sp.arcsin(n_1*np.sin(th_1) / n_2)
    if is_forward_angle(n_2, th_2_guess):
        return th_2_guess
    else:
        return pi - th_2_guess
示例#46
0
def lbToEq (l_deg, b_deg):   
    """ Converts galactic l,b in to Equatorial ra, dec; from Binney and Merrifield, p. 31;  
    l, b must be arrays of same shape"""
    l, b = (l_deg*rad), (b_deg*rad)
    # Conversion Code
    t = lCP - l
    dec = sc.arcsin(sc.sin(decGP)*sc.sin(b) + sc.cos(decGP)*sc.cos(b)*sc.cos(t) )
    r = sc.arctan2( (sc.cos(b)*sc.sin(t)),
                    ( (sc.cos(decGP)*sc.sin(b)) - (sc.sin(decGP)*sc.cos(b)*sc.cos(t)))  )
    if type(r) != type(arr):  r = sc.array([r])
    for i in range(len(r)):
        r[i] = angle_bounds((r[i] + raGP)*deg)
    return r, (dec*deg)
示例#47
0
def EqTolb (ra_deg, dec_deg):
    """ Converts equatorial ra, dec, into galactic l,b;  from Binney and Merrifield, p. 31
    following the method of http://star-www.st-and.ac.uk/~spd3/Teaching/AS3013/programs/radec2lb.f90
    NOT QUITE - I use arctan2 method instead"""
    ra, dec = (ra_deg*rad), (dec_deg*rad)
    # Conversion Code
    r = (ra - raGP)
    b = sc.arcsin( sc.sin(decGP)*sc.sin(dec) + sc.cos(decGP)*sc.cos(dec)*sc.cos(r) )
    t = sc.arctan2((sc.cos(dec)*sc.sin(r)),
                   (sc.cos(decGP)*sc.sin(dec) - sc.sin(decGP)*sc.cos(dec)*sc.cos(r)) )
    l = (lCP - t)
    b, l = angle_bounds2((b*deg), (l*deg))
    return l, b
示例#48
0
文件: utils.py 项目: gevero/py_matrix
def T_ps_rl(m_t_ps,theta_0,n_0,n_s):
    '''Utility to compute transmittance for p,s and right.left
    circular polarization

    Parameters
    ----------
    'm_t_ps' = ps transmission matrix

    Returns
    -------
    'a dictionary' = {'T_p':T_p, #transmittances
                      'T_s':T_s,
                      'T_l':T_l,
                      'T_r':T_r
                      'A_p':-np.log10(T_p), #absorbances
                      'A_s':-np.log10(T_s),
                      'A_r':-np.log10(T_r),
                      'A_l':-np.log10(T_l)}
    '''

    # extracting values from the matrix
    t_pp = m_t_ps[0,0]
    t_ps = m_t_ps[0,1]
    t_sp = m_t_ps[1,0]
    t_ss = m_t_ps[1,1]

    # calculating the transmittance
    theta_s = sp.arcsin(np.real_if_close(np.sin(theta_0)*n_0/n_s))
    norm = (np.real(n_s*np.conj(np.cos(theta_s))) /
            np.real(n_0*np.conj(np.cos(theta_0))))
    T_p = norm*(np.abs(t_pp)**2 + np.abs(t_sp)**2)
    T_s = norm*(np.abs(t_ss)**2 + np.abs(t_ps)**2)
    T_r = 0.5*norm*(np.abs(t_pp)**2 + np.abs(t_ss)**2 +
                    np.abs(t_sp)**2 + np.abs(t_ps)**2 +
                    2.0*np.real(1j*t_pp*np.conj(t_ps)) +
                    2.0*np.real(1j*t_sp*np.conj(t_ss)))
    T_l = 0.5*norm*(np.abs(t_pp)**2 + np.abs(t_ss)**2 +
                    np.abs(t_sp)**2 + np.abs(t_ps)**2 -
                    2.0*np.real(1j*t_pp*np.conj(t_ps)) -
                    2.0*np.real(1j*t_sp*np.conj(t_ss)))

    out_dict = {'T_p':T_p,
                'T_s':T_s,
                'T_l':T_l,
                'T_r':T_r,
                'A_p':-np.log10(T_p),
                'A_s':-np.log10(T_s),
                'A_r':-np.log10(T_r),
                'A_l':-np.log10(T_l)}

    return out_dict
示例#49
0
def purcell(physics,
            network,
            geometry,
            fluid,
            propname,
            r_toroid,
            pore_surface_tension='surface_tension',
            pore_contact_angle='contact_angle',
            throat_diameter='diameter',
            **params):
    r"""
    Computes the throat capillary entry pressure assuming the throat is a toroid.

    Parameters
    ----------
    network : OpenPNM Network Object
        The network on which to apply the calculation
    sigma : float, array_like
        Surface tension of the invading/defending fluid pair.  Units must be consistent with the throat size values, but SI is encouraged.
    theta : float, array_like
        Contact angle formed by a droplet of the invading fluid and solid surface, measured through the defending fluid phase.  Angle must be given in degrees.
    r_toroid : float or array_like
        The radius of the solid

    Notes
    -----
    This approach accounts for the converging-diverging nature of many throat types.  Advancing the meniscus beyond the apex of the toroid requires an increase in capillary pressure beyond that for a cylindical tube of the same radius. The details of this equation are described by Mason and Morrow [1]_, and explored by Gostick [2]_ in the context of a pore network model.

    References
    ----------

    .. [1] G. Mason, N. R. Morrow, Effect of contact angle on capillary displacement curvatures in pore throats formed by spheres. J. Colloid Interface Sci. 168, 130 (1994).
    .. [2] J. Gostick, Random pore network modeling of fibrous PEMFC gas diffusion media using Voronoi and Delaunay tessellations. J. Electrochem. Soc. 160, F731 (2013).

    """
    #This seesm to work, but I wrote it quickly and lost track of the degree-radians conversions
    """TODO:
    Triple check the accuracy of this equation
    """
    sigma = network.get_pore_data(phase=fluid,prop=pore_surface_tension)
    sigma = network.interpolate_throat_data(sigma)
    theta = network.get_pore_data(phase=fluid,prop=pore_contact_angle)
    theta = network.interpolate_throat_data(theta)
    r = network.get_throat_data(prop=throat_diameter)/2
    R = r_toroid
    alpha = theta - 180 + sp.arcsin(sp.sin(sp.radians(theta)/(1+r/R)))
    value = (-2*sigma/r)*(sp.cos(sp.radians(theta - alpha))/(1 + R/r*(1-sp.cos(sp.radians(alpha)))))
    mask = network.get_throat_indices(geometry)
    network.set_throat_data(phase=fluid,prop=propname,data=value[mask],locations=geometry)
示例#50
0
 def arcsin_sqrt_transform(self, pid, verbose=False):
     a = sp.array(self.phen_dict[pid]["values"])
     if min(a) < 0 or max(a) > 1:
         if verbose:
             print "Some values are outside of range [0,1], hence skipping transformation!"
         return False
     else:
         vals = sp.arcsin(sp.sqrt(a))
     if not self.phen_dict[pid]["transformation"]:
         self.phen_dict[pid]["raw_values"] = self.phen_dict[pid]["values"]
         self.phen_dict[pid]["transformation"] = "arcsin_sqrt"
     else:
         self.phen_dict[pid]["transformation"] = "arcsin_sqrt(" + self.phen_dict[pid]["transformation"] + ")"
     self.phen_dict[pid]["values"] = vals.tolist()
     return True
示例#51
0
 def arcsin_sqrt_transform(self, pid, verbose=False):
     a = sp.array(self.phen_dict[pid]['values'])
     if min(a) < 0 or max(a) > 1:
         if verbose:
             print 'Some values are outside of range [0,1], hence skipping transformation!'
         return False
     else:
         vals = sp.arcsin(sp.sqrt(a))
     if not self.phen_dict[pid]['transformation']:
         self.phen_dict[pid]['raw_values'] = self.phen_dict[pid]['values']
         self.phen_dict[pid]['transformation'] = 'arcsin_sqrt'
     else:
         self.phen_dict[pid]['transformation'] = 'arcsin_sqrt(' + self.phen_dict[pid]['transformation'] + ')'
     self.phen_dict[pid]['values'] = vals.tolist()
     return True
示例#52
0
def rotmat_from_u2v(u,v):
    """
    Return the rotation matrix associated with rotation of vector u onto vector v. Euler-Rodrigues formula.
    """
    u, v = u / LA.norm(u), v / LA.norm(v)
    axis = sp.cross(u,v)
    theta = sp.arcsin(LA.norm(axis))
    axis = axis/LA.norm(axis) # math.sqrt(np.dot(axis, axis))
    a = sp.cos(theta/2)
    b, c, d = -axis * sp.sin(theta/2)
    aa, bb, cc, dd = a*a, b*b, c*c, d*d
    bc, ad, ac, ab, bd, cd = b*c, a*d, a*c, a*b, b*d, c*d
    return np.array([[aa+bb-cc-dd, 2*(bc+ad), 2*(bd-ac)],
                     [2*(bc-ad), aa+cc-bb-dd, 2*(cd+ab)],
                     [2*(bd+ac), 2*(cd-ab), aa+dd-bb-cc]])
示例#53
0
def law_xyz2sgr_gal(X,Y,Z, Xsun=dsun):
    """ From the Law sgr transformation code:  http://www.astro.virginia.edu/~srm4n/Sgr/code.html
    // Transform positions from standard left handed Galactocentric XYZ to  [RIGHT-HANDED]
    // the Galactocentric Sgr system (lambda=0 at the Galactic plane)
    // Input must be in kpc of the form X Y Z
    // Output is in kpc and degrees, of the form X_Sgr,GC Y_Sgr,GC Z_Sgr,GC d_GC lambda_GC beta_GC
    // Note that d is distance from Galactic Center"""
    radpdeg = 3.141592653589793/180.0
    #// Define the Euler angles
    phi = (180+3.75)*radpdeg
    theta = (90-13.46)*radpdeg
    psiGC = (180+21.604399)*radpdeg
    #// Rotation angle of phiGC past 180degrees is a useful number
    ang = 21.604399*radpdeg
    #// Note that the plane does not actually include the G.C., although it is close
    xcenter = -8.5227
    ycenter = -0.3460
    zcenter = -0.0828
    #// Define the rotation matrix from the Euler angles
    GCrot11 = sc.cos(psiGC)*sc.cos(phi)-sc.cos(theta)*sc.sin(phi)*sc.sin(psiGC)
    GCrot12 = sc.cos(psiGC)*sc.sin(phi)+sc.cos(theta)*sc.cos(phi)*sc.sin(psiGC)
    GCrot13 = sc.sin(psiGC)*sc.sin(theta)
    GCrot21 = -sc.sin(psiGC)*sc.cos(phi)-sc.cos(theta)*sc.sin(phi)*sc.cos(psiGC)
    GCrot22 = -sc.sin(psiGC)*sc.sin(phi)+sc.cos(theta)*sc.cos(phi)*sc.cos(psiGC)
    GCrot23 = sc.cos(psiGC)*sc.sin(theta)
    GCrot31 = sc.sin(theta)*sc.sin(phi)
    GCrot32 = -sc.sin(theta)*sc.cos(phi)
    GCrot33 = sc.cos(theta)
    #X = -X  #// Make the input system right-handed  ALREADY IS
    X = X + Xsun  #// Transform the input system to heliocentric right handed coordinates
    #// Calculate Z,distance in the SgrGC system
    Temp=GCrot11*(X+xcenter)+GCrot12*(Y-ycenter)+GCrot13*(Z-zcenter)
    Temp2=GCrot21*(X+xcenter)+GCrot22*(Y-ycenter)+GCrot23*(Z-zcenter)
    Zs=GCrot31*(X+xcenter)+GCrot32*(Y-ycenter)+GCrot33*(Z-zcenter)
    d=sc.sqrt(Temp*Temp+Temp2*Temp2+Zs*Zs)
    Zs=-Zs;
    #// Calculate the angular coordinates lambdaGC,betaGC
    Temp3 = sc.arctan2(Temp2,Temp)/radpdeg;
    if (Temp3 < 0.0): Temp3 = Temp3 + 360.0
    Temp3 = Temp3 + ang/radpdeg
    if (Temp3 > 360.0): Temp3 = Temp3 - 360.0
    lam = Temp3
    beta = sc.arcsin(Zs/sc.sqrt(Temp*Temp+Temp2*Temp2+Zs*Zs))/radpdeg
    #// Calculate X,Y in the SgrGC system
    Xs=Temp*sc.cos(ang) - Temp2*sc.sin(ang)
    Ys=Temp*sc.sin(ang) + Temp2*sc.cos(ang)
    r = sc.sqrt(Xs*Xs + Ys*Ys + Zs+Zs)
    return Xs, Ys, Zs, lam, beta, r
示例#54
0
def list_snell(n_list,th_0):
    """
    return list of angle theta in each layer based on angle th_0 in layer 0,
    using Snell's law. n_list is index of refraction of each layer. Note that
    "angles" may be complex!!
    """
    #Important that the arcsin here is scipy.arcsin, not numpy.arcsin! (They
    #give different results e.g. for arcsin(2).)
    angles = sp.arcsin(n_list[0]*np.sin(th_0) / n_list)
    # the first and last entry need to be the forward angle (the intermediate
    # layers don't matter, see https://arxiv.org/abs/1603.02720 Section 5)
    if not is_forward_angle(n_list[0], angles[0]):
        angles[0] = pi - angles[0]
    if not is_forward_angle(n_list[-1], angles[-1]):
        angles[-1] = pi - angles[-1]
    return angles
示例#55
0
def GCToEq (mu_deg, nu_deg, wedge):  # produces lists....  ROTATE
    """ Converts Stripe mu, nu into equatorial ra, dec.  Called 'atGCToEq' in at SurveyGeometry.c"""
    node = (surveyCenterRa - 90.0)*rad
    eta = get_eta(wedge)
    inc = (surveyCenterDec + eta)*rad
    mu, nu = (mu_deg*rad), (nu_deg*rad)
    # Rotation
    x2 = sc.cos(mu - node)*sc.cos(nu)
    y2 = sc.sin(mu - node)*sc.cos(nu)
    z2 = sc.sin(nu)
    x1 = x2
    y1 = y2*sc.cos(inc) - z2*sc.sin(inc)
    z1 = y2*sc.sin(inc) + z2*sc.cos(inc)
    ra = sc.arctan2(y1,x1) + node
    dec = sc.arcsin(z1)
    dec, ra = angle_bounds2((dec*deg),(ra*deg))
    return ra, dec