Example #1
0
def generateIonizationElectronData(E):
    vel = c * (1 - ((E / (eMass * c**2)) + 1)**(-2))**.5
    k = (2 * np.pi * TC._eCharge / (TC._eMass * vel * vel))
    omega = lambda gamma: -2 * (E - gamma) + (2 * E * (2 * E - gamma))**.5
    F = lambda a, b: a + b
    s = lambda a: (1 - 2 * a)**.5
    phi = lambda gamma: 1
    f = lambda gamma: 1
    M1 = lambda a, b: (np.log(
        ((b - a) * (1 - b + a) * (1 + a - s(a)) * (1 - a + s(a))) /
        (b * (1 - b) * (1 - a - s(a)) *
         (1 + a + s(a)))) / a) + (2 / (1 + a)) * (sci.special.ellipkinc(
             np.asin((1 + a - 2 * b) / (1 - a)),
             ((1 - a) /
              (1 + a))) - sci.special.ellipkinc(np.asin((s(a)) / (1 - a)),
                                                ((1 - a) / (1 + a))))
    M2 = lambda a, b: (np.log(
        ((b - a) * (1 - b + a)) /
        (b * (1 - b))) / a) + (2 / (1 + a)) * (sci.special.ellipkinc(
            np.asin((1 + a - 2 * b) / (1 - a)), ((1 - a) / (1 + a))))
    L = lambda a: (np.log(((1 + a - s(a)) * (1 - a + s(a))) / (
        (1 - a - s(a)) *
        (1 + a + s(a)))) / a) - (2 / (1 + a)) * (sci.special.ellipkinc(
            np.asin((s(a)) / (1 - a)), ((1 - a) / (1 + a))))
    MeanFreeIon = lambda gamma: k * f(gamma) * phi(gamma) * L(gamma / E) / E
    ion1 = lambda gamma: k * f(gamma) * phi(gamma) * M1()
    # print(M1(3,4))

    return
Example #2
0
def foo(d):
    ng = 1.56
    dn = 0.2
    no = (dn + 2*sqrt(-2*dn**2 + 9*ng**2))/6. - dn/2
    ne = (dn + 2*sqrt(-2*dn**2 + 9*ng**2))/6. + dn/2
    alpha = rad2deg(asin(1/ng*sin(deg2rad(20))))/2;
    wl0 = 940e-9
    k0 = 2*pi/wl0
    Kx = -2*k0*ng*sin(deg2rad(alpha))*cos(deg2rad(alpha))
    Kz = -2*k0*ng*sin(deg2rad(alpha))*sin(deg2rad(alpha))
    px = 2*pi/Kx
    pz = 2*pi/Kz

    thetas = np.linspace(-40, 40, 41)
    DERl = []
    DERr = []
    DETl = []
    DETr = []
    nn = 1
    lays = genGradient(PVG2, 10, 15e-6 , px, pz*2., pz*0.5, -1, no, ne)
    for theta in thetas:
        thetai = rad2deg(asin(sin(deg2rad(theta))/ng))
        rcwa = RCWA(ng, ng, lays, nn, [1, 1j], [1j, 1])
        derl, derr, detl, detr = rcwa.solve(0, thetai, wl0, 1, 1j)
        DETr.append(detr)

    DETr = array(DETr).T
    loss = np.sum(np.abs(DETr[nn-1]-1))
    return loss
Example #3
0
    def beta(self,m1,d,g=1.4,i=0):
        p=-(m1*m1+2.)/m1/m1-g*np.sin(d)*np.sin(d)
        q=(2.*m1*m1+1.)/ np.pow(m1,4.)+((g+1.)*(g+1.)/4.+
                                          (g-1.)/m1/m1)*np.sin(d)*np.sin(d)
        r=-np.cos(d)*np.cos(d)/np.pow(m1,4.)

        a=(3.*q-p*p)/3.
        b=(2.*p*p*p-9.*p*q+27.*r)/27.

        test=b*b/4.+a*a*a/27.

        if (test>0.0):
            return -1.0
        elif (test==0.0):
          x1=np.sqrt(-a/3.)
          x2=x1
          x3=2.*x1
          if(b>0.0):
            x1*=-1.
            x2*=-1.
            x3*=-1.

        if(test<0.0):
          phi=np.acos(np.sqrt(-27.*b*b/4./a/a/a))
          x1=2.*np.sqrt(-a/3.)*np.cos(phi/3.)
          x2=2.*np.sqrt(-a/3.)*np.cos(phi/3.+np.pi*2./3.)
          x3=2.*np.sqrt(-a/3.)*np.cos(phi/3.+np.pi*4./3.)
          if(b>0.0):
            x1*=-1.
            x2*=-1.
            x3*=-1.

        s1=x1-p/3.
        s2=x2-p/3.
        s3=x3-p/3.

        if(s1<s2 and s1<s3):
          t1=s2
          t2=s3
        elif(s2<s1 and s2<s3):
          t1=s1
          t2=s3
        else:
          t1=s1
          t2=s2

        b1=np.asin(np.sqrt(t1))
        b2=np.asin(np.sqrt(t2))

        betas=b1
        betaw=b2
        if(b2>b1):
          betas=b2
          betaw=b1

        if(i==0):
            return betaw
        if(i==1):
            return betas
def plotLensDistance(h):
    r = 0.15
    n1 = 1
    n2 = 1.5
    # h =  np.linspace(0, 0.05, 2000)
    a2= asin(n1/n2 * h/r)
    a1= asin(h/r)
    df = r*sin(a2)/sin(a1-a2)

    dx = r+df
    plt.plot(h,dx, "b")
def plotChromaticAbb(h, n2):
    r = 0.15
    n1 = 1
    # n2 = 1.5
    # h =  np.linspace(0, 0.05, 2000)
    a2= asin(n1/n2 * h/r)
    a1= asin(h/r)
    df = r*sin(a2)/sin(a1-a2)

    dx = r+df
    # plt.plot(n2,dx, "b")
    return dx
Example #6
0
def distance_haversine(a):
    """
    Calculate the great circle distance between two lists of 
    latitudes and longitudes of points 
    on the earth (specified in decimal degrees). 
    Haversine
    formula: 
        a = sin²(Δφ/2) + cos φ1 ⋅ cos φ2 ⋅ sin²(Δλ/2)
        c = 2 ⋅ atan2( √a, √(1−a) )
        d = R ⋅ c
    where   φ is latitude, λ is longitude, R is earth’s radius (mean radius = 6,371km);
            note that angles need to be in radians to pass to trig functions!
    """
    lat, lon = a 
    for p in zip(lat, lon):
        valpoint(p)
    R = 6371 # km - earths's radius
    # convert decimal degrees to radians 
    lat, lon = map(np.radians, [lat, lon])
    # haversine formula 
    dlon, dlat = np.diff(lon), np.diff(lat)
    print(dlon)
    np.insert(dlon, 0)
    np.insert(dlat, 0)
    f = np.sin(dlat/2)**2 + np.cos(lat) * np.cos(lat) * np.sin(dlon/2)**2
    c = 2 * np.asin(np.sqrt(f)) # 2 * np.atan2(np.sqrt(f), np.sqrt(1-f))
    d = R * c
    return d
Example #7
0
 def __call__(self, photon):
     """Returns the reflectivity of the coating for the incident photon."""
     
     if isinstance(self.reflectivity, Spectrum):
         return self.reflectivity.value(photon.wavelength)
         
     elif isinstance(self.reflectivity, AngularSpectrum):
         # DJF 8/5/2010
         # 
         # The internal incident angle (substate-coating) will not correspond to the same value of 
         # reflectivity as for the same angle and the external interface (air-coatings) because the 
         # refraction angle into the material will be different. We need to apply a correction factor
         # to account for this effect (see Farrell PhD Thesis, p.129, 2009)
         #
         # If the previous containing object's (i.e. this will be the substate for an internal 
         # collision, or air if an external collision) has a refractive index higher than air
         # (n_air = photon.scene.bounds.material.refractive_index) then the correction is applied,
         # else the photon must be heading into an external interface and no correction is needed.
         #
         if photon.previous_container.material.refractive_index > photon.scene.bounds.material.refractive_index:
             # Hitting internal interface, therefore apply correction to angle
             n_substrate = photon.previous_container.material.refractive_index
             n_environment = photon.scene.bounds.material.refractive_index
             rads = np.asin(n_substrate/n_environment * sin( angle(normal, photon.direction) ))
         else:
             rads = angle(normal, photon.direction)
             
         return self.reflectivity.value(photon.wavelength, rads)
         
     else:
         # Assume it's a number
         return self.reflectivity
Example #8
0
 def deflections(self, xin, yin):
     from numpy import ones, arctan as atan, arctanh as atanh
     from math import cos, sin, pi
     from numpy import arcsin as asin, arcsinh as asinh
     x, y = self.align_coords(xin, yin)
     q = self.q
     if q == 1.:
         q = 1. - 1e-7  # Avoid divide-by-zero errors
     eps = (1. - q**2)**0.5
     if self.eta == 1.:
         # SIE models
         r = (x**2 + y**2)**0.5
         r[r == 0.] = 1e-9
         xout = self.b * asinh(eps * x / q / r) * q**0.5 / eps
         yout = self.b * asin(eps * y / r) * q**0.5 / eps
     else:
         from powerlaw import powerlawdeflections as pld
         b, eta = self.b, self.eta
         s = 1e-7
         if x.ndim > 1:
             yout, xout = pld(-1 * y.ravel(), x.ravel(), b, eta, s, q)
             xout, yout = xout.reshape(x.shape), -1 * yout.reshape(y.shape)
         else:
             yout, xout = pld(-1 * y, x, b, eta, s, q)
             yout = -1 * yout
     theta = -(self.theta - pi / 2.)
     ctheta = cos(theta)
     stheta = sin(theta)
     x = xout * ctheta + yout * stheta
     y = yout * ctheta - xout * stheta
     return x, y
Example #9
0
def angle(q, wavelength):
    '''
    calculate angle given Q and wavelength
    q - wavevector (A^-1)
    wavelength -  wavelength of radiation (Angstrom)
    '''
    return  np.asin(q / 4. / np.pi * wavelength) * 180 / np.pi
Example #10
0
    def __call__(self, photon):
        """Returns the reflectivity of the coating for the incident photon."""

        if isinstance(self.reflectivity, Spectrum):
            return self.reflectivity.value(photon.wavelength)

        elif isinstance(self.reflectivity, AngularSpectrum):
            # DJF 8/5/2010
            #
            # The internal incident angle (substate-coating) will not correspond to the same value of
            # reflectivity as for the same angle and the external interface (air-coatings) because the
            # refraction angle into the material will be different. We need to apply a correction factor
            # to account for this effect (see Farrell PhD Thesis, p.129, 2009)
            #
            # If the previous containing object's (i.e. this will be the substate for an internal
            # collision, or air if an external collision) has a refractive index higher than air
            # (n_air = photon.scene.bounds.material.refractive_index) then the correction is applied,
            # else the photon must be heading into an external interface and no correction is needed.
            #
            if photon.previous_container.material.refractive_index > photon.scene.bounds.material.refractive_index:
                # Hitting internal interface, therefore apply correction to angle
                n_substrate = photon.previous_container.material.refractive_index
                n_environment = photon.scene.bounds.material.refractive_index
                rads = np.asin(n_substrate / n_environment *
                               sin(angle(normal, photon.direction)))
            else:
                rads = angle(normal, photon.direction)

            return self.reflectivity.value(photon.wavelength, rads)

        else:
            # Assume it's a number
            return self.reflectivity
    def pixel2A(self, position = None):
        """
        Convert pixel index to wavelength
        (This works only for the Si CCD already installed on the spectrometer.)
        
        :param position: Position of the spectrometer (Angtroms). If omited, use current one.
        :type position: float
        :returns: Wavelength of each pixels
        :rtype: numpy array        
        """
        if position is None:
            position = self._query('posi?')

        # Parametres prit integralement de la version Matlab 
        #        dv = 2.341131e-001;
        #        fact = 1.812402816604375e-004;
        # Parametres ajustes sur des mesures sur le pic Ne @ 6929.4673 
        dv = 0.19583658
        fact = 1.812402816604375e-004  # Fixe
        dispersion = 1e7 / 3.6e6 * np.cos(np.asin(fact*position/2)+dv/2) / 50

        a = position - dispersion * 670
        x = np.arange(1340)
        x = a + dispersion * x
        #x = claser - 1e8 / x / n_air
        return x
Example #12
0
 def deflections(self, xin, yin):
     from numpy import ones, arctan as atan, arctanh as atanh
     from math import cos, sin, pi
     from numpy import arcsin as asin, arcsinh as asinh
     x, y = self.align_coords(xin, yin)
     q = self.q
     if q == 1.:
         q = 1. - 1e-7  # Avoid divide-by-zero errors
     eps = (1. - q**2)**0.5
     if self.eta == 1.:
         # SIE models
         r = (x**2 + y**2)**0.5
         r[r == 0.] = 1e-9
         xout = self.b * asinh(eps * x / q / r) * q**0.5 / eps
         yout = self.b * asin(eps * y / r) * q**0.5 / eps
     else:
         from powerlaw import powerlawdeflections as pld
         b, eta = self.b, self.eta
         s = 1e-7
         if x.ndim > 1:
             yout, xout = pld(-1 * y.ravel(), x.ravel(), b, eta, s, q)
             xout, yout = xout.reshape(x.shape), -1 * yout.reshape(y.shape)
         else:
             yout, xout = pld(-1 * y, x, b, eta, s, q)
             yout = -1 * yout
     theta = -(self.theta - pi / 2.)
     ctheta = cos(theta)
     stheta = sin(theta)
     x = xout * ctheta + yout * stheta
     y = yout * ctheta - xout * stheta
     return x, y
def action_asin():
    Showtemplabel.delete(0, END);
    Showlabel.delete(0, END)
  
    Showtemplabel.config(fg='yellow', bg='#8dad96')
    Showtemplabel.insert(0, 'asin');
    Showtemplabel.place(relx=0.5, rely=0.5, anchor='center')

    ans = "0"

    Showlabel.insert(0, ans);
    Showlabel.place(relx=0.5, rely=0.6, anchor='center')

    num1 = Numberentry1.get();
    if(is_number(num1)==True):
        num1 = casting(num1)
        ans = str(np.asin(num1))
        Showtemplabel.delete(0, END);
        Showlabel.delete(0, END)

        Showtemplabel.config(fg='yellow', bg='#8dad96')
        Showtemplabel.insert(0, 'sin_-1');
        Showtemplabel.place(relx=0.5, rely=0.5, anchor='center')

        Showlabel.insert(0, ans);
        Showlabel.place(relx=0.5, rely=0.6, anchor='center')
    else:
        messagebox.showerror("Error", "Enter a Valid number\ne.g. 123, 0.123, .123, -0.123, 123.456")
Example #14
0
def ecef2aer(obs_lla, ecef_sat, ecef_obs):
    """
    :Ref: Geometric Reference Systems in Geodesy by Christopher Jekeli, Ohio State University, August 2016
        https://kb.osu.edu/bitstream/handle/1811/77986/Geom_Ref_Sys_Geodesy_2016.pdf?sequence=1&isAllowed=y
    :param obs_lla: observations in lat, lon, height (deg, deg, m)
    :param ecef_sat:
    :return: array[azimuth, elevation, slant]
    """

    lat, lon = obs_lla[0], obs_lla[1]  # phi, lambda

    trans_uvw_ecef = array(
        [[-sin(lat) * cos(lon), -sin(lon),
          cos(lat) * cos(lon)],
         [-sin(lat) * sin(lon),
          cos(lon), cos(lat) * sin(lon)], [cos(lat), 0,
                                           sin(lat)]])  # (eq 2.153)
    delta_ecef = ecef_sat - ecef_obs  # (eq 2.149)
    R_enz = trans_uvw_ecef.T @ delta_ecef  # (eq 2.153)
    r = sqrt(sum(delta_ecef**2))  # (eq 2.156)
    az = atan2(R_enz[1], (R_enz[0]))  # (eq 2.154)
    if az < 0:
        az = az + 2 * pi
    el = asin(R_enz[2] / r)  # (eq 2.155)
    aer = array([az, el, r])
    return aer
Example #15
0
 def __inverse_2D(self, x, y):
     l1 = self.link_lengths[0]
     l2 = self.link_lengths[1]
     L = np.sqrt(x**2 + y**2)
     psi = np.asin(x / L)
     phi = np.acos((l1**2 + l2**2 - L**2) / (2 * l1 * l))
     return [th1, th2]
Example #16
0
def euclidian_dist_to_angular_dist(dist, r=1):
    """
    The inverse of angular_dist_to_euclidian_dist.

    Parameters
    ----------
    dist: array-like or scalar
        Euclidian distance in the same units as r
    r: scalar (optional)
        The radius of the sphere that you're projecting onto.  Default
        is 1.

    Returns
    -------
    angular_separation: numpy array or scalar (matches input)
       Angular separation in degrees that corresponds to the Euclidean
       distance(s)
    """

    #If it's an array, make sure that it's a numpy array so that nothing
    #weird happens in the vector operations
    try:
        n_dists = len(dist)
    except TypeError:
        n_dists = 1
    else:
        dist = np.array(dist)

    #Return the distance
    return 180./np.pi * 2. * np.asin(dist/(2.*r))
Example #17
0
def quaternion_to_euler(quat):
    # https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles
    # Needs to be checked for correctness given openGL coordinate system
    q0, q1, q2, q3 = quat
    phi = np.atan2(2*(q0*q1 + q2*q3), 1-2*(q1**2 + q2**2))
    theta = np.asin(2*(q0*q2 - q3*q1))
    psi = np.atan2(2*(q0*q3 + q1*q2), 1 - 2*(q2**2 + q3**2))
    return phi, theta, psi
Example #18
0
def radec2azel(ra_deg: float,
               dec_deg: float,
               lat_deg: float,
               lon_deg: float,
               time: datetime,
               usevallado: bool = True) -> Tuple[float, float]:
    """
    converts right ascension, declination to azimuth, elevation

    Parameters
    ----------

    ra_deg : float
        right ascension to target [degrees]

    dec_deg : float
        declination to target [degrees]

    lat_deg : float
        observer WGS84 latitude [degrees]

    lon_deg : float
        observer WGS84 longitude [degrees]

    time : datetime.datetime
        time of observation

    Results
    -------

    az_deg : float
        azimuth clockwise from north to point [degrees]

    el_deg : float
        elevation above horizon to point [degrees]


    from D. Vallado "Fundamentals of Astrodynamics and Applications "
       4th Edition Ch. 4.4 pg. 266-268
    """
    if abs(lat_deg) > 90:
        raise ValueError("-90 <= lat <= 90")

    ra = radians(ra_deg)
    dec = radians(dec_deg)
    lat = radians(lat_deg)
    lon = radians(lon_deg)

    lst = datetime2sidereal(time, lon)  # RADIANS
    # %% Eq. 4-11 p. 267 LOCAL HOUR ANGLE
    lha = lst - ra
    # %% #Eq. 4-12 p. 267
    el = asin(sin(lat) * sin(dec) + cos(lat) * cos(dec) * cos(lha))
    # %% combine Eq. 4-13 and 4-14 p. 268
    az = atan2(-sin(lha) * cos(dec) / cos(el),
               (sin(dec) - sin(el) * sin(lat)) / (cos(el) * cos(lat)))

    return degrees(az) % 360.0, degrees(el)
Example #19
0
def QL2T(Q=None,L=None):
    """
    Compute angle from Q and wavelength.

    T = asin( |Q| L / 4 pi )

    Returns T in degrees.
    """
    return degrees(asin(abs(Q) * L / (4*pi)))
Example #20
0
def QL2T(Q=None, L=None):
    """
    Compute angle from Q and wavelength.

    T = asin( |Q| L / 4 pi )

    Returns T in degrees.
    """
    return degrees(asin(abs(Q) * L / (4 * pi)))
Example #21
0
def PW91k_paramke(s, k):

    A = k[0] @ s * np.asin(k[4] * s)
    B = (k[1] - k[2] @ np.exp(-k[3] @ s**2)) * s**2
    C = k[5] @ s**4

    F = (1 + A + B) / (1 + A + C)

    return F
Example #22
0
def cart_2_flight_elements(cart):
    """ Return flight elements from cartesian coordinates.

    Parameters
    ----------

    cart: float array
      Cartesian coordinates
 
    Returns
    -------

    flight_elem: float array
      Flight elements

    """

    flight_elem = np.zeros(6)

    #position and velocity magnitude
    r = np.sqrt(cart[0]**2+cart[1]**2+cart[2]**2)
    v = np.sqrt(cart[3]**2+cart[4]**2+cart[5]**2)

    #right ascension (alpha)
    alpha = np.acos(cart[0]/np.sqrt(cart[0]**2+cart[1]**2))
    
    #declination (delta)    
    delta = np.asin(cart[2]/r)

    #matrice to transform a vector in the SEZ system
    m = np.zeros(3,3)
    m[0,0] = np.cos(alpha)*np.cos(delta)
    m[0,1] = np.sin(alpha)*np.cos(delta)
    m[0,2] = -np.sin(delta)
    m[1,0] = -np.sin(alpha)
    m[1,1] = np.cos(alpha)
    m[1,2] = 0.0    
    m[1,0] = np.sin(delta)*np.cos(alpha)
    m[1,1] = np.sin(alpha)*np.sin(delta)
    m[1,2] = np.cos(delta)
    v_sez = m*cart[3:5]

    #flight-path angle from the local horizontal
    phi = np.acos(v_sez[2]/v)
    
    #azimut (beta)
    beta = np.acos(-v_sez[0]/np.sqrt(v_sez[0]**2+v_sez[1]**2))
    
    flight_elem[0] = r 
    flight_elem[1] = v
    flight_elem[2] = alpha   
    flight_elem[3] = delta
    flight_elem[4] = phi
    flight_elem[5] = beta   

    return flight_elem
Example #23
0
def azel2radec(az_deg: float,
               el_deg: float,
               lat_deg: float,
               lon_deg: float,
               time: datetime,
               usevallado: bool = True) -> Tuple[float, float]:
    """
    converts azimuth, elevation to right ascension, declination

    Parameters
    ----------

    az_deg : float
        azimuth (clockwise) to point [degrees]

    el_deg : float
        elevation above horizon to point [degrees]

    lat_deg : float
        observer WGS84 latitude [degrees]

    lon_deg : float
        observer WGS84 longitude [degrees]

    time : datetime.datetime
        time of observation

    Results
    -------

    ra_deg : float
        right ascension to target [degrees]

    dec_deg : float
        declination of target [degrees]

    from D.Vallado Fundamentals of Astrodynamics and Applications
    p.258-259
    """

    if abs(lat_deg) > 90:
        raise ValueError("-90 <= lat <= 90")

    az = radians(az_deg)
    el = radians(el_deg)
    lat = radians(lat_deg)
    lon = radians(lon_deg)
    # %% Vallado "algorithm 28" p 268
    dec = asin(sin(el) * sin(lat) + cos(el) * cos(lat) * cos(az))

    lha = atan2(-(sin(az) * cos(el)) / cos(dec),
                (sin(el) - sin(lat) * sin(dec)) / (cos(dec) * cos(lat)))

    lst = datetime2sidereal(time, lon)  # lon, ra in RADIANS
    """ by definition right ascension [0, 360) degrees """
    return degrees(lst - lha) % 360, degrees(dec)
Example #24
0
 def ang_rel2abs_2(self, ang):
     my_ang = ang
     output = 0
     while my_ang > self.ang_const:
         output += np.pi
         my_ang -= 2 * self.ang_const
     while my_ang < -self.ang_const:
         output -= np.pi
         my_ang += 2 * self.ang_const
     return output + np.asin(my_ang / self.ang_const)
Example #25
0
def HaversineFormula(lat1,lon1,lat2,lon2):
    lat1 = lat1*pi/180.0
    lon1 = lon1*pi/180.0
    lat2 = lat2*pi/180.0
    lon2 = lon2*pi/180.0
    dlat = lat2-lat1
    dlon = lon2-lon1
    h = hav(dlat) + cos(lat1)*cos(lat2)*hav(dlon)
    d = 2*R*asin(h**0.5)
    return d
Example #26
0
def asin(*args, **kw):
    arg0 = args[0]
    if isinstance(arg0, (int, float, long)):
        return _math.asin(*args,**kw)
    elif isinstance(arg0, complex):
        return _cmath.asin(*args,**kw)
    elif isinstance(arg0, _sympy.Basic):
        return _sympy.asin(*args,**kw)
    else:
        return _numpy.asin(*args,**kw)
Example #27
0
def QL2T(Q=None,L=None):
    r"""
    Compute angle from $Q$ (|1/Ang|) and wavelength (|Ang|).

    .. math::

        \theta = \sin^{-1}( |Q| \lambda / 4 \pi )

    Returns $\theta$\ |deg|.
    """
    Q,L = asarray(Q,'d'), asarray(L,'d')
    return degrees(asin(abs(Q) * L / (4*pi)))
Example #28
0
def quaternion_to_euler(x, y, z, w):
    t0 = +2.0 * (w * x + y * z)
    t1 = +1.0 - 2.0 * (x * x + y * y)
    roll = np.atan2(t0, t1)
    t2 = +2.0 * (w * y - z * x)
    t2 = +1.0 if t2 > +1.0 else t2
    t2 = -1.0 if t2 < -1.0 else t2
    pitch = np.asin(t2)
    t3 = +2.0 * (w * z + x * y)
    t4 = +1.0 - 2.0 * (y * y + z * z)
    yaw = np.atan2(t3, t4)
    return yaw, pitch, roll
Example #29
0
def solar_declination(ls=None):
    """Returns the solar declination"""
    if ls is None:
        ls= Mars_Ls()
    ls1 = ls * np.pi/180.

    if use_numpy:
        dec = np.arcsin(0.42565 * np.sin(ls1)) + 0.25*(np.pi/180) * np.sin(ls1)
    else:
        dec = np.asin(0.42565 * np.sin(ls1)) + 0.25*(np.pi/180) * np.sin(ls1)
    dec = dec * 180. / np.pi
    return dec
Example #30
0
def QL2T(Q=None, L=None):
    r"""
    Compute angle from $Q$ (|1/Ang|) and wavelength (|Ang|).

    .. math::

        \theta = \sin^{-1}( |Q| \lambda / 4 \pi )

    Returns $\theta$\ |deg|.
    """
    Q, L = asarray(Q, 'd'), asarray(L, 'd')
    return degrees(asin(abs(Q) * L / (4*pi)))
def DCM2Euler321(C):
    """
    C2Euler321

        Q = C2Euler321(C) translates the 3x3 direction cosine matrix
        C into the corresponding (3-2-1) Euler angle set.
    """
    q = np.zeros(3)
    q[0] = np.atan2(C[0, 1], C[0, 0])
    q[1] = np.asin(-C[0, 2])
    q[2] = np.atan2(C[1, 2], C[2, 2])
    return q
Example #32
0
    def deflections(self, xin, yin, d=1):
        b = self.b * d
        from numpy import ones, arctan as atan, arctanh as atanh
        from math import cos, sin, pi
        from numpy import arcsin as asin, arcsinh as asinh
        x, y = self.align_coords(xin, yin, False)
        q = self.q
        if q == 1.:
            q = 1. - 1e-7  # Avoid divide-by-zero errors
        eps = (1. - q**2)**0.5
        if self.eta == 1.:
            # SIE models
            r = (x**2 + y**2)**0.5
            r[r == 0.] = 1e-9
            #            xout = self.b*asinh(eps*x/q/r)*q**0.5/eps
            #            yout = self.b*asin(eps*y/r)*q**0.5/eps
            xout = b * asinh(eps * y / q / r) * q**0.5 / eps
            yout = b * asin(eps * -x / r) * q**0.5 / eps
            xout, yout = -yout, xout
            x, y = self.align_coords(xout, yout, False, revert=True)
            return x - self.x, y - self.y

            theta = 2 - self.theta  #-(self.theta - pi/2.)
            ctheta = cos(theta)
            stheta = sin(theta)
            x = xout * ctheta + yout * stheta
            y = yout * ctheta - xout * stheta
            return x, y
        else:
            from powerlaw import powerlawdeflections as pld
            b, eta = b, self.eta
            s = 1e-4
            if x.ndim > 1:
                #                yout,xout = pld(-1*y.ravel(),x.ravel(),b,eta,s,q)
                #                xout,yout = xout.reshape(x.shape),-1*yout.reshape(y.shape)
                xout, yout = pld(x.ravel(), y.ravel(), b, eta, s, q)
                xout, yout = xout.reshape(x.shape), yout.reshape(y.shape)
            else:
                xout, yout = pld(x, y, b, eta, s, q)


#                yout,xout = pld(-1*y,x,b,eta,s,q)
#                yout = -1*yout
#        theta = -(self.theta - pi/2.)
#        ctheta = cos(theta)
#        stheta = sin(theta)
#        x = xout*ctheta+yout*stheta
#        y = yout*ctheta-xout*stheta
#        return x,y
        x, y = self.align_coords(xout, yout, False, revert=True)
        return x - self.x, y - self.y
Example #33
0
def moon_rst_altitude(r):
    """ Returnn the standard altitude of the Moon.

    Arguments:
      - `r` : Distance between the centers of the Earth and Moon, in km.

    Returns:
      - Standard altitude in radians.

    """
    # horizontal parallax
    parallax = np.asin(earth_equ_radius / r)

    return 0.7275 * parallax + standard_rst_altitude
Example #34
0
def solar_declination(ls=None):
    """Returns the solar declination"""
    if ls is None:
        ls = Mars_Ls()
    ls1 = ls * np.pi / 180.

    if use_numpy:
        dec = np.arcsin(
            0.42565 * np.sin(ls1)) + 0.25 * (np.pi / 180) * np.sin(ls1)
    else:
        dec = np.asin(
            0.42565 * np.sin(ls1)) + 0.25 * (np.pi / 180) * np.sin(ls1)
    dec = dec * 180. / np.pi
    return dec
Example #35
0
    def evaluate(self, xOrig):
        """
        Calculates and returns RV curve according to current model parameters.

        .. note:: The units of the model RV curve are **stellar-radii per second**.

        Parameters
        ----------
        xOrig : array
            The time stamps at which to calculate the model RV curve.
            Note that the orbit period and central transit time are used
            to convert time into "true anomaly".
        """
        x = self.trueAnomaly(xOrig)
        Xp = self.Xp(x)
        Zp = self.Zp(x)
        rho = self.rho(Xp, Zp)
        etap = self.etap(Xp, Zp)
        zeta = self.zeta(etap)
        x0 = self.x0(etap)
        xc = self.xc(zeta, x0)

        # dphase is the phase difference between the primary transit and the time points
        # It is used to exclude the secondary transit from the calculations
        dphase = np.abs((xOrig - self["T0"]) / self["P"])
        dphase = np.minimum(dphase - np.floor(dphase),
                            np.abs(dphase - np.floor(dphase) - 1))

        y = np.zeros(len(x))
        indi = np.where(
            np.logical_and(rho < (1.0 - self["gamma"]), dphase < 0.25))[0]

        y[indi] = Xp[indi] * self["Omega"] * sin(self["Is"]) * self["gamma"]**2 * \
            (1.0 - self["epsilon"] * (1.0 - self.W2(rho[indi]))) / \
            (1.0 - self["gamma"]**2 - self["epsilon"] * (1. /
                                                         3. - self["gamma"]**2 * (1.0 - self.W1(rho[indi]))))

        indi = np.where(
            np.logical_and(
                np.logical_and(rho >= 1. - self["gamma"],
                               rho < 1.0 + self["gamma"]), dphase < 0.25))[0]
        z0 = self.z0(etap, indi)

        y[indi] = (Xp[indi] * self["Omega"] * sin(self["Is"]) * (
            (1.0 - self["epsilon"]) * (-z0[indi] * zeta[indi] + self["gamma"]**2 * acos(zeta[indi] / self["gamma"])) +
            (self["epsilon"] / (1.0 + etap[indi])) * self.W4(x0[indi], zeta[indi], xc[indi], etap[indi]))) / \
            (pi * (1. - 1.0 / 3.0 * self["epsilon"]) - (1.0 - self["epsilon"]) * (asin(z0[indi]) - (1. + etap[indi]) * z0[indi] +
                                                                                  self["gamma"]**2 * acos(zeta[indi] / self["gamma"])) - self["epsilon"] * self.W3(x0[indi], zeta[indi], xc[indi], etap[indi]))

        return y
Example #36
0
def fitsh_projection_do_inverse_matrix_coord(mproj, x, y):

    z = 1.0 - x**2 - y**2
    z = -np.sqrt(z)

    px = mproj[0, 0] * x + mproj[1, 0] * y + mproj[2, 0] * z
    py = mproj[0, 1] * x + mproj[1, 1] * y + mproj[2, 1] * z
    pz = mproj[0, 2] * x + mproj[1, 2] * y + mproj[2, 2] * z

    rde = np.asin(pz) * 180.0 / np.pi
    rra = np.atan2(py, px) * 180.0 / np.pi
    if rra < 0.0:
        rra = rra + 360.0

    return [rra, rdec]
Example #37
0
    def evaluate(self, xOrig):
        """
        Calculates and returns RV curve according to current model parameters.

        .. note:: The units of the model RV curve are **stellar-radii per second**.

        Parameters
        ----------
        xOrig : array
            The time stamps at which to calculate the model RV curve.
            Note that the orbit period and central transit time are used
            to convert time into "true anomaly".
        """
        self._setkepellpars()
        # In coordinate system with observer in -z axis
        pos = self._ke.xyzPos(xOrig)
        # Use coordinate used by Ohta (looking into -y direction)
        Xp = -pos[::, 0]
        Zp = pos[::, 1]
        Yp = pos[::, 2]

        rho = RmcL.rho(self, Xp, Zp)
        etap = RmcL.etap(self, Xp, Zp)
        zeta = RmcL.zeta(self, etap)
        x0 = RmcL.x0(self, etap)
        xc = RmcL.xc(self, zeta, x0)

        # Planet in front of star
        y = np.zeros_like(xOrig)
        indi = np.where((Yp < 0) & (rho < (1.0 - self["gamma"])))[0]

        y[indi] = Xp[indi] * self["Omega"] * sin(self["Is"]) * self["gamma"]**2 * \
            (1.0 - self["epsilon"] * (1.0 - RmcL.W2(self, rho[indi]))) / \
            (1.0 - self["gamma"]**2 - self["epsilon"] * (1. /
                                                         3. - self["gamma"]**2 * (1.0 - RmcL.W1(self, rho[indi]))))

        indi = np.where((rho >= 1. - self["gamma"])
                        & (rho < 1.0 + self["gamma"]) & (Yp < 0))[0]
        z0 = RmcL.z0(self, etap, indi)

        y[indi] = (Xp[indi] * self["Omega"] * sin(self["Is"]) * (
            (1.0 - self["epsilon"]) * (-z0[indi] * zeta[indi] + self["gamma"]**2 * acos(zeta[indi] / self["gamma"])) +
            (self["epsilon"] / (1.0 + etap[indi])) * RmcL.W4(self, x0[indi], zeta[indi], xc[indi], etap[indi]))) / \
            (pi * (1. - 1.0 / 3.0 * self["epsilon"]) - (1.0 - self["epsilon"]) * (asin(z0[indi]) - (1. + etap[indi]) * z0[indi] +
                                                                                  self["gamma"]**2 * acos(zeta[indi] / self["gamma"])) - \
                                                                                  self["epsilon"] * RmcL.W3(self, x0[indi], zeta[indi], xc[indi], etap[indi]))

        return y
Example #38
0
def randLonLat( n=1, lon1=-180.0, lon2=180.0, lat1=-90.0, lat2=90.0 ):
    """
    Get n random lon/lat points in degrees
    """
    # deg/radian conversion
    D2R=pi/180.0
    R2D=1/D2R

    # get lons
    lons = lon1 + (lon2-lon1)*NPR.rand( n, 1 )

    # correct for area and get rand lat
    z1, z2 = sin( D2R*lat1 ) , sin( R2D*lat2 )
    lats = R2D*asin( z1 + (z2-z1)*NPR.rand( n,1 ) )
    
    return (lons, lats)
Example #39
0
def uvw2aer(uvw):
    """
    :param uvw:
    :return: array[azimuth, elevation, slant]
    """
    # Ref: Geometric Reference Systems in Geodesy by Christopher Jekeli, Ohio State University, August 2016
    # https://kb.osu.edu/bitstream/handle/1811/77986/Geom_Ref_Sys_Geodesy_2016.pdf?sequence=1&isAllowed=y
    # 2.2.2 Local Terrestrial Coordinates defined u, v, w
    u, v, w = uvw
    r = sqrt(sum(uvw**2))  # (eq 2.156)
    az = atan2(v, u)  # (eq 2.154)
    if az < 0:
        az = az + tau
    el = asin(w / r)  # (eq 2.155)
    aer = array([az, el, r])
    return aer
Example #40
0
def randLonLat(n=1, lon1=-180.0, lon2=180.0, lat1=-90.0, lat2=90.0):
    """
    Get n random lon/lat points in degrees
    """
    # deg/radian conversion
    D2R = pi / 180.0
    R2D = 1 / D2R

    # get lons
    lons = lon1 + (lon2 - lon1) * NPR.rand(n, 1)

    # correct for area and get rand lat
    z1, z2 = sin(D2R * lat1), sin(R2D * lat2)
    lats = R2D * asin(z1 + (z2 - z1) * NPR.rand(n, 1))

    return (lons, lats)
Example #41
0
def azel_from_ecef(pos, ref):
    """Returns the azimuth and elevation between two ECEF points"""

    # Calculate the vector from the reference point in the local North, East,
    # Down frame of the reference point. */
    ned = ned_from_ecef(pos - ref, pos, ref)

    az = np.atan2(ned[1], ned[0])
    # atan2 returns angle in range [-pi, pi], usually azimuth is defined in the
    # range [0, 2pi]. */
    if (az < 0):
        az += 2 * np.pi

    el = np.asin(-ned[2] / np.linalg.norm(ned))

    return az, el
Example #42
0
 def oop_calc(i,j,k,l):
     label = atomLabel[i] + str(i+1) + "-" + atomLabel[j] + str(j+1) + "-" + atomLabel[k] + str(k+1) + "-" + atomLabel[l] + str(l+1)
     v_kl = np.array([float(xCoord[k]) - float(xCoord[l]),float(yCoord[k]) - float(yCoord[l]),float(zCoord[k]) - float(zCoord[l])])
     v_ki = np.array([float(xCoord[k]) - float(xCoord[i]),float(yCoord[k]) - float(yCoord[i]),float(zCoord[k]) - float(zCoord[i])])
     v_kj = np.array([float(xCoord[k]) - float(xCoord[j]),float(yCoord[k]) - float(yCoord[j]),float(zCoord[k]) - float(zCoord[j])])
     e_kl = np.divide(v_kl,np.linalg.norm(v_kl))
     e_ki = np.divide(v_ki,np.linalg.norm(v_ki))
     e_kj = np.divide(v_kj,np.linalg.norm(v_kj))
     theta_jkl = np.arccos(np.dot(e_kj,e_kl))
     a = np.dot(np.cross(e_kj,e_kl),e_ki)
     b = np.sin(theta_jkl)
     sin_theta = a/b
     theta = (180.0/np.pi)*np.asin(round(sin_theta,5))
     oop.append(theta)
     oopLabel.append(label)
     return(oopLabel,oop)
Example #43
0
def haversine(lon1, lat1, lon2, lat2, earth_radius):
    """
        Great circle distance between two points using Haversine formula
        modified from Michael Dunn's answer on Stack Overflow:
        http://stackoverflow.com/questions/4913349/haversine-formula-in-python-bearing-and-distance-between-two-gps-points
        Answer specified in decimal degrees.
        """
    # convert decimal degrees to radians
    lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2])

    # haversine formula
    delt_lon = lon2 - lon1
    delt_lat = lat2 - lat1
    a = np.sin(delt_lat/2)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(delt_lon/2)**2
    c = 2 * earth_radius * np.asin(np.sqrt(a))

    return c
Example #44
0
  def evaluate(self, xOrig):
    """
      Calculates and returns RV curve according to current model parameters.
      
      .. note:: The units of the model RV curve are **stellar-radii per second**.
      
      Parameters
      ----------
      xOrig : array
          The time stamps at which to calculate the model RV curve.
          Note that the orbit period and central transit time are used
          to convert time into "true anomaly".
    """
    x = self.trueAnomaly(xOrig)
    Xp = self.Xp(x)
    Zp = self.Zp(x)
    rho = self.rho(Xp, Zp)
    etap = self.etap(Xp, Zp)
    zeta = self.zeta(etap)
    x0 = self.x0(etap)
    xc = self.xc(zeta, x0)

    # dphase is the phase difference between the primary transit and the time points
    # It is used to exclude the secondary transit from the calculations 
    dphase = numpy.abs((xOrig-self["T0"])/self["P"])
    dphase = numpy.minimum( dphase-numpy.floor(dphase), numpy.abs(dphase-numpy.floor(dphase)-1))

    y = numpy.zeros(len(x))
    indi = numpy.where(numpy.logical_and(rho < (1.0-self["gamma"]), dphase < 0.25))[0]

    y[indi] = Xp[indi]*self["Omega"]*sin(self["Is"])* self["gamma"]**2 * \
        (1.0 - self["epsilon"]*(1.0 - self.W2(rho[indi]))) / \
        (1.0 - self["gamma"]**2 - self["epsilon"]*(1./3. - self["gamma"]**2*(1.0-self.W1(rho[indi]))))
    
    indi = numpy.where(numpy.logical_and( \
                numpy.logical_and(rho >= 1.-self["gamma"], rho < 1.0+self["gamma"]), dphase < 0.25))[0]
    z0 = self.z0(etap, indi)
    
    y[indi] = (Xp[indi]*self["Omega"]*sin(self["Is"])*( \
        (1.0-self["epsilon"]) * (-z0[indi]*zeta[indi] + self["gamma"]**2*acos(zeta[indi]/self["gamma"])) + \
        (self["epsilon"]/(1.0+etap[indi]))*self.W4(x0[indi], zeta[indi], xc[indi], etap[indi]))) / \
        (pi*(1.-1.0/3.0*self["epsilon"]) - (1.0-self["epsilon"]) * (asin(z0[indi])-(1.+etap[indi])*z0[indi] + \
        self["gamma"]**2*acos(zeta[indi]/self["gamma"])) - self["epsilon"]*self.W3(x0[indi], zeta[indi], xc[indi], etap[indi]))

    return y
Example #45
0
 def trace(self, photon, normal, free_pathlength):
     """Move the photon one Monte-Carlo step forward by considering material reflections."""
     
     # Absorption is not defined for this material (we assume dielectrics)
     # Therefore is random number is less than reflectivty: photon reflected.
     
     if isinstance(self.reflectivity, Spectrum):
         R = self.reflectivity.value(photon.wavelength)
     if isinstance(self.reflectivity, AngularSpectrum):
         # DJF 8/5/2010
         # 
         # The internal incident angle (substate-coating) will not correspond to the same value of 
         # reflectivity as for the same angle and the external interface (air-coatings) because the 
         # refraction angle into the material will be different. We need to apply a correction factor
         # to account for this effect (see Farrell PhD Thesis, p.129, 2009)
         #
         # If the previous containing object's (i.e. this will be the substate for an internal 
         # collision, or air if an external collision) has a refractive index higher than air
         # (n_air = photon.scene.bounds.material.refractive_index) then the correction is applied,
         # else the photon must be heading into an external interface and no correction is needed.
         #
         if photon.previous_container.material.refractive_index > photon.scene.bounds.material.refractive_index:
             # Hitting internal interface, therefore apply correction to angle
             n_substrate = photon.previous_container.material.refractive_index
             n_environment = photon.scene.bounds.material.refractive_index
             rads = np.asin(n_substrate/n_environment * sin( angle(normal, photon.direction) ))
         else:
             rads = angle(normal, photon.direction)
             
         R = self.reflectivity.value(photon.wavelength, rads)
     else:
         R = self.reflectivity
     
     rn = np.random.uniform()
     if rn < R:
         # Reflected
         photon.direction = reflect_vector(normal, photon.direction)
     else:
         photon.position = photon.position + free_pathlength * photon.direction
     return photon
Example #46
0
def quat2euler(r, i, j, k):
    """
    Converts a quaternion to Euler angles

    @type r: float
    @param r: Real part of quaternion

    @type i: float
    @param i: Imaginary i part of quaternion

    @type j: float
    @param j: Imaginary j part of quaternion

    @type k: float
    @param k: Imaginary k part of quaternion

    @rtype: tuple
    @return: (phi, theta, psi) Euler angles
        phi - (float) Roll angle in radians
        theta - (float) Pitch angle in radians
        psi - (float) Yaw angle in radians

    """

    r = float(r)
    i = float(i)
    j = float(j)
    k = float(k)

    if not np.isclose(np.array(np.sqrt(r*r+i*i+j*j+k*k)), 1.0):
        raise Exception("Invalid argument:\n" + \
                str(r) + " " + str(i) + " " + str(j) + " " + str(k) + \
                "\n" + "Valid types: norm of [r i j k] = 1")

    phi = atan2(2*(r*i + j*k), 1 - 2*(i**2 + j**2))
    theta = asin(2*(r*j - k*i))
    psi = atan2(2*(r*k + i*j), 1 - 2*(j**2 + k**2))

    return (phi, theta, psi)
Example #47
0
 def caustic(self):
     if self.eta != 1:
         return None, None
     from numpy import ones, arctan as atan, arctanh as atanh
     from numpy import cos, sin, pi, linspace
     from numpy import arcsin as asin, arcsinh as asinh
     q = self.q
     if q == 1.:
         q = 1. - 1e-7  # Avoid divide-by-zero errors
     eps = (1. - q**2)**0.5
     theta = linspace(0, 2 * pi, 5000)
     ctheta = cos(theta)
     stheta = sin(theta)
     delta = (ctheta**2 + q**2 * stheta**2)**0.5
     xout = ctheta * q**0.5 / delta - asinh(eps * ctheta / q) * q**0.5 / eps
     yout = stheta * q**0.5 / delta - asin(eps * stheta) * q**0.5 / eps
     xout, yout = xout * self.b, yout * self.b
     theta = -(self.theta - pi / 2.)
     ctheta = cos(theta)
     stheta = sin(theta)
     x = xout * ctheta + yout * stheta
     y = yout * ctheta - xout * stheta
     return x + self.x, y + self.y
Example #48
0
def dist2GC(cLon1, cLat1, cLon2, cLat2, lonArray, latArray, units="km"):
    """
    Calculate the distance between an array of points and the great circle
    joining two (other) points.
    All input values are in degrees.
    By default returns distance in km, other units specified by the
    'units' kwarg.

    Based on a cross-track error formulation from:
    http://williams.best.vwh.net/avform.htm#XTE
    """

    # Calculate distance and bearing from first point to array of points:
    dist_ = gridLatLonDist(cLon1, cLat1, lonArray, latArray, units="rad")
    bear_ = gridLatLonBear(cLon1, cLat1, lonArray, latArray)

    #bearing of the cyclone:
    cyc_bear_ = latLon2Azi([cLon1, cLon2], [cLat1, cLat2])

    dist2GC_ = np.asin(np.sin(dist_) * np.sin(bear_ - cyc_bear_))

    distance = metutils.convert(dist2GC_, "rad", units)
    return distance
Example #49
0
def Rswd(DEM, Lat, Trans, DOY, Time):
   """ Potential Radiation Equator model
   (c) O. van Dam, UU, Tropenbos-Guyana
   Version 5, June 2000
   NOTE: Copyright: This program is free to use provided·
         you refer to the manualfor citation.
         Do not distribute without prior approval of the author.
         Manual and additional info: [email protected]

   -----------------------------------------------------
                   Model for calculation
               incoming potential light energy
   -----------------------------------------------------
   
   DEM Input Digital Elevation Model (spatial)
   Lat Latitude in decimal degrees (non-spatia)
   Trans Transmissivity tau (Gates, 1980) (non-spatial)
   DOY Day of Year (non-spatial)
   Time Time in hours (non-spatial)"""
   
   # constants
   pi       = 3.1415          # pi
   Sc       = 1367.0          # Solar constant (Gates, 1980) [W/m2]

   SlopMap = scalar(atan(slope(DEM)))
   AspMap  = scalar(aspect(DEM)) # aspect [deg]
   AtmPcor = ((288.0-0.0065*DEM)/288.0)**5.256 # atmospheric pressure correction [-]

   # Solar geometry
   # ----------------------------
   # SolDec  :declination sun per day  between +23 & -23 [deg]
   # HourAng :hour angle [-] of sun during day
   # SolAlt  :solar altitude [deg], height of sun above horizon
   SolDec  = -23.4*cos(360.0*(DOY+10.0)/365.0)
   HourAng = 15.0*(Time-12.01)
   SolAlt  = scalar(asin(scalar(sin(Lat)*sin(SolDec)+cos(Lat)*cos(SolDec)*cos(HourAng))))

   # Solar azimuth
   # ----------------------------
   # SolAzi  :angle solar beams to N-S axes earth [deg]
   SolAzi = scalar(acos((sin(SolDec)*cos(Lat)-cos(SolDec)*sin(Lat)*cos(HourAng))/cos(SolAlt)))
   SolAzi = ifthenelse(Time <= 12.0, SolAzi, 360.0 - SolAzi)
   # Additonal extra correction by R.Sluiter, Aug '99
   #SolAzi = ifthenelse(SolAzi > 89.994 and SolAzi < 90.0, 90.0, SolAzi)
   #SolAzi = ifthenelse(SolAzi > 269.994 and SolAzi < 270.0, 270.0, SolAzi)

   SolAzi = ifthenelse(np.logical_and(SolAzi > 89.994, SolAzi < 90.0), 90.0, SolAzi)
   SolAzi = ifthenelse(np.logical_and(SolAzi > 269.994, SolAzi < 270.0), 270.0, SolAzi)

   # Surface azimuth
   # ----------------------------
   # cosIncident :cosine of angle of incident; angle solar beams to angle surface
   cosIncident = sin(SolAlt)*cos(SlopMap)+cos(SolAlt)*sin(SlopMap)*cos(SolAzi-AspMap)

   # Critical angle sun
   # ----------------------------
   # HoriAng  :tan maximum angle over DEM in direction sun, 0 if neg·
   # CritSun  :tan of maximum angle in direction solar beams
   # Shade    :cell in sun 1, in shade 0
   #HoriAng   = horizontan(DEM,directional(SolAzi))
   HoriAng   = scalar(0.3)
   HoriAng   = ifthenelse(HoriAng < 0.0, scalar(0.0), HoriAng)
   CritSun   = ifthenelse(SolAlt > 90.0, scalar(0.0), scalar(atan(HoriAng)))
   Shade   = ifthenelse(SolAlt > CritSun, scalar(1), scalar(0))
   
   # Radiation outer atmosphere
   # ----------------------------
   OpCorr = Trans**((sqrt(1229.0+(614.0*sin(SolAlt))**2.0)-614.0*sin(SolAlt))*AtmPcor)     # correction for air masses [-]·
   Sout   = Sc*(1.0+0.034*cos(360.0*DOY/365.0)) # radiation outer atmosphere [W/m2]
   Snor   = Sout*OpCorr                    # rad on surface normal to the beam [W/m2]

   # Radiation at DEM
   # ----------------------------
   # Sdir   :direct sunlight on a horizontal surface [W/m2] if no shade
   # Sdiff  :diffuse light [W/m2] for shade and no shade
   # Stot   :total incomming light Sdir+Sdiff [W/m2] at Hour
   # PotRad :avg of Stot(Hour) and Stot(Hour-HourStep)
   Sdir   = ifthenelse(Snor*cosIncident*Shade < 0.0, 0.0, Snor*cosIncident*Shade)
   Sdiff  = ifthenelse(Sout*(0.271-0.294*OpCorr)*sin(SolAlt) < 0.0, 0.0, Sout*(0.271-0.294*OpCorr)*sin(SolAlt))
   #Rswd  = Sdir + Sdiff                                         # Rad [W/m2]
   Rswd = Snor
   return Rswd
Example #50
0
           'Clarke 1866' : 6378206.4,
           'Bessel 1841' : 6377397.155,
           'International 1924' : 6378388,
           'Krasovsky 1940' : 6378245,
           'GRS80' : 6378137,
           'WGS84' : 6378137,
           }.get(elip, 6371000)

rlat = omapy
rlon = omapx

#R = select_earth_radius(ellipsoid)
sr = osr.SpatialReference()
sr.ImportFromWkt(img_prj)
R = sr.GetSemiMajor()
# to determine if projected
sr.IsProjected() # return 1 if True
# to determine if geographic
sr.IsGeographic() # return 1 if True

d = shadow_length

rlat2 = numpy.asin( numpy.sin(rlat)*numpy.cos(d/R) + numpy.cos(rlat)*numpy.sin(d/R)*numpy.cos(to_azi) )

rlon2 = rlon + numpy.atan2(numpy.sin(to_azi)*numpy.sin(d/R)*numpy.cos(rlat),numpy.cos(d/R)-numpy.sin(rlat)*numpy.sin(rlat))

rlat2 = numpy.deg2rad(rlat2)
rlon2 = numpy.deg2rad(rlon2)


Example #51
0
         returns [Lat2,Lon2]
         """
    lat1=((lat1deg)/180*pi)
    lon1=((lon1deg)/180*pi)
     #thetadeg is bearing in degrees, convet to radians
    theta=(thetadeg)/180*pi
    #print theta
    
    # Radius of the earth a=equatorial radius, b=polar radius
    a=6378.137e3; 
    b=6356.7523e3;
    phi=lat1
    R=sqrt( ( pow(pow(a,2)*cos(phi),2) + pow(pow(b,2)*sin(phi),2) )/( pow(a*cos(phi),2) + pow(b*sin(phi),2) ))
    #R=6371e3

    lat2 = (asin(sin(lat1)*cos(d/R) + cos(lat1)*sin(d/R)*cos(theta)) )
    #print lat2
    lat2deg = lat2/pi*180
    lon2 = (lon1 + atan2(sin(theta)*sin(d/R)*cos(lat1), cos(d/R)-sin(lat1)*sin(lat2)) )
    #print lon2
    #lon2 = (lon1 + atan2( cos(d/R)-sin(lat1)*sin(lat2), sin(theta)*sin(d/R)*cos(lat1) ))
    lon2deg = lon2/pi*180
    return([lat2deg, lon2deg])
    #%52deg58'52?N, 000deg53'15?E

#Generates one point for a circle?\
def genCirclePoint(centreLat, centreLon, circleAngle, circleRadius, circleAlt):
    """
    Gen coordinates for a circle point
    expect decimal lat longs
    returns one point as string?
Example #52
0
def tilde_w(w, dt):
    return (2./dt)*asin(w*dt/2.)
Example #53
0
 def g(self, x, e, g, x0):
   result = (1.0-x**2) * asin(sqrt((g**2-(x-1.0-e)**2)/(1.0-x**2))) + \
      sqrt(2.0*(1.0+e)*(x0-x)*(g**2-(x-1.0-e)**2))
   return result
Example #54
0
    def __init__(self, h, T=None, L=None, thetao=None, Ho=None, lat=None):
        self.T = np.asarray(T, dtype=np.float)
        self.L = np.asarray(L, dtype=np.float)
        self.Ho = np.asarray(Ho, dtype=np.float)
        self.lat = np.asarray(lat, dtype=np.float)
        self.thetao = np.asarray(thetao, dtype=np.float)

        if isinstance(h, str):
            if L is not None:
                if h == 'deep':
                    self.h = self.L / 2.
                elif h == 'shallow':
                    self.h = self.L * 0.05
        else:
            self.h = np.asarray(h, dtype=np.float)

        if lat is None:
            g = 9.81  # Default gravity.
        else:
            g = gsw.grav(lat, p=0)

        if L is None:
            self.omega = 2 * np.pi / self.T
            self.Lo = (g * self.T ** 2) / 2 / np.pi
            # Returns wavenumber of the gravity wave dispersion relation using
            # newtons method. The initial guess is shallow water wavenumber.
            self.k = self.omega / np.sqrt(g)
            # TODO: May change to,
            # self.k = self.w ** 2 / (g * np.sqrt(self.w ** 2 * self.h / g))
            f = g * self.k * np.tanh(self.k * self.h) - self.omega ** 2

            while np.abs(f.max()) > 1e-10:
                dfdk = (g * self.k * self.h * (1 / (np.cosh(self.k * self.h)))
                        ** 2 + g * np.tanh(self.k * self.h))
                self.k = self.k - f / dfdk
                # FIXME:
                f = g * self.k * np.tanh(self.k * self.h) - self.omega ** 2

            self.L = 2 * np.pi / self.k
            if isinstance(h, str):
                if h == 'deep':
                    self.h = self.L / 2.
                elif h == 'shallow':
                    self.h = self.L * 0.05
        else:
            self.Lo = self.L / np.tanh(2 * np.pi * self.h / self.L)
            self.k = 2 * np.pi / self.L
            self.T = np.sqrt(2 * np.pi * self.Lo / g)
            self.omega = 2 * np.pi / self.T

        self.hoL = self.h / self.L
        self.hoLo = self.h / self.Lo
        self.C = self.omega / self.k  # or L / T
        self.Co = self.Lo / self.T
        self.G = 2 * self.k * self.h / np.sinh(2 * self.k * self.h)
        self.n = (1 + self.G) / 2
        self.Cg = self.n * self.C
        self.Ks = np.sqrt(1 / (1 + self.G) / np.tanh(self.k * self.h))

        if thetao is None:
            self.theta = np.NaN
            self.Kr = np.NaN
        if thetao is not None:
            self.theta = np.rad2deg(np.asin(self.C / self.Co *
                                            np.sin(np.deg2rad(self.thetao))))
            self.Kr = np.sqrt(np.cos(np.deg2rad(self.thetao)) /
                              np.cos(np.deg2rad(self.theta)))

        if Ho is None:
            self.H = np.NaN
        if Ho is not None:
            self.H = self.Ho * self.Ks * self.Kr