Ejemplo n.º 1
0
def RV_model(THETA, time, kplanets):
    modelo = 0.0
    #sp.seterr(all=='raise')
    if kplanets == 0:
        return 0.0
    for i in range(kplanets):
        P, As, Ac, S, C = THETA[5 * i:5 * (i + 1)]
        #P, As, Ac, ecc, w = THETA[5*i:5*(i+1)]
        A = As**2 + Ac**2
        ecc = S**2 + C**2

        phase = sp.arccos(Ac / (A**0.5))
        w = sp.arccos(C / (ecc**0.5))  # longitude of periastron

        ### test
        if S < 0:
            w = 2 * sp.pi - sp.arccos(C / (ecc**0.5))
        if As < 0:
            phase = 2 * sp.pi - sp.arccos(Ac / (A**0.5))

        ###
        #  sp.seterr(all='raise') # DEL
        per = sp.exp(P)
        freq = 2. * sp.pi / per
        M = freq * time + phase  # mean anomaly
        E = sp.array([MarkleyKESolver().getE(m, ecc)
                      for m in M])  # eccentric anomaly
        f = (sp.arctan(
            ((1. + ecc)**0.5 / (1. - ecc)**0.5) * sp.tan(E / 2.)) * 2.
             )  # true anomaly
        modelo += A * (sp.cos(f + w) + ecc * sp.cos(w))
    return modelo
Ejemplo n.º 2
0
def henshin(thetas, kplanets):
    for i in range(kplanets):
        Pk = thetas[:, i * 5]
        Ask = thetas[:, i * 5 + 1]
        Ack = thetas[:, i * 5 + 2]
        Sk = thetas[:, i * 5 + 3]
        Ck = thetas[:, i * 5 + 4]

        Ak = Ask**2 + Ack**2
        Phasek = sp.arccos(Ack / (Ak**0.5))

        ecck = Sk**2 + Ck**2
        wk = sp.arccos(Ck / (ecck**0.5))
        for j in range(len(Sk)):
            if Sk[j] < 0:
                wk[j] = 2 * sp.pi - sp.arccos(Ck[j] / (ecck[j]**0.5))
            if Ask[j] < 0:
                Phasek[j] = 2 * sp.pi - sp.arccos(Ack[j] / (Ak[j]**0.5))

        thetas[:, i * 5] = sp.exp(Pk)
        thetas[:, i * 5 + 1] = Ak
        thetas[:, i * 5 + 2] = Phasek
        thetas[:, i * 5 + 3] = ecck
        thetas[:, i * 5 + 4] = wk
    return thetas
Ejemplo n.º 3
0
def nano_henshin_hou(thetas, kplanets, tags, fixed_values, anticoor):
    t2 = sp.ones_like(thetas)
    for i in range(kplanets):
        if tags[i][0]:
            t2[i * 5] = sp.exp(thetas[i * 5])
            print('changed period! (devs note)')
        if tags[i][1]:
            Ask = thetas[i * 5 + 1]
            Ack = thetas[i * 5 + 2]
            Ak = Ask**2 + Ack**2
            Phasek = sp.where(Ask >= 0, sp.arccos(Ack / (Ak**0.5)),
                              2 * sp.pi - sp.arccos(Ack / (Ak**0.5)))
            t2[i * 5 + 1] = Ak
            t2[i * 5 + 2] = Phasek
            print('changed amplitude! (devs note)')
        if tags[i][2]:
            Sk = thetas[i * 5 + 3]
            Ck = thetas[i * 5 + 4]
            ecck = Sk**2 + Ck**2
            wk = sp.where(Sk >= 0, sp.arccos(Ck / (ecck**0.5)),
                          2 * sp.pi - sp.arccos(Ck / (ecck**0.5)))
            t2[i * 5 + 3] = ecck
            t2[i * 5 + 4] = wk
            print('changed eccentricity! (devs note)')
    for i in range(len(thetas))[5 * kplanets:]:
        t2[i] = thetas[i]
    return thetas
Ejemplo n.º 4
0
def overlap(x, xdown, y, ydown, r, alpha):
    overlap_fraction = np.zeros(np.size(x))
    for i in range(0, np.size(x)):
        #define dx as the upstream x coordinate - the downstream x coordinate then rotate according to wind direction
        dx = xdown - x[i]
        #define dy as the upstream y coordinate - the downstream y coordinate then rotate according to wind direction
        dy = ydown - y[i]
        R = r + dx * alpha  #The radius of the wake depending how far it is from the turbine
        A = r**2 * np.pi  #The area of the turbine

        if dx > 0:
            if np.abs(dy) <= R - r:
                overlap_fraction[
                    i] = 1  #if the turbine is completely in the wake, overlap is 1, or 100%
            elif np.abs(dy) >= R + r:
                overlap_fraction[
                    i] = 0  #if none of it touches the wake, the overlap is 0
            else:
                #if part is in and part is out of the wake, the overlap fraction is defied by the overlap area/rotor area
                overlap_area = r**2. * sp.arccos(
                    (dy**2. + r**2. - R**2.) /
                    (2.0 * dy * r)) + R**2. * sp.arccos(
                        (dy**2. + R**2. - r**2.) /
                        (2.0 * dy * R)) - 0.5 * sp.sqrt(
                            (-dy + r + R) * (dy + r - R) * (dy - r + R) *
                            (dy + r + R))
                overlap_fraction[i] = overlap_area / A
        else:
            overlap_fraction[
                i] = 0  #turbines cannot be affected by any wakes that start downstream from them

    # print overlap_fraction
    return overlap_fraction  #retrun the n x n matrix of how each turbine is affected by all of the others
Ejemplo n.º 5
0
def wahre_Anom(planet, t=0, t0=0):
    """Wahre Anomalie wird aus exzentrischer Anomalie berechnet,
	Fallunterscheidung bei E => 180° und E <= 180°."""
    E = ex_Anom(planet, t)
    eps = planet["numEx"]
    if (E >= 0 and E <= sc.pi):
        return sc.arccos((sc.cos(E) - eps) / (1 - eps * sc.cos(E)))
    else:
        return 2 * sc.pi - sc.arccos((sc.cos(E) - eps) / (1 - eps * sc.cos(E)))
Ejemplo n.º 6
0
def s2d_angular(s):
    if s.shape == (1, 1):
        # DPX: to prevent the stupid scipy to collapse the array into scalar
        d = np.array([[np.float64(scipy.arccos(s) / np.pi)]])
    elif s.shape == (1, ):
        d = np.array([np.float64(scipy.arccos(s) / np.pi)])
    else:
        # costly in time (half of the time)
        d = np.float64(scipy.arccos(s) / np.pi)
    return d
Ejemplo n.º 7
0
 def _ang2vert_eq(nside, theta, phi, z):
     a = 4. / 3. / nside
     b = 8. / 3. / sc.pi
     deltaZ = a
     deltaPhi = a / b
     out = []
     out.append([sc.arccos(z + deltaZ / 2), phi])
     out.append([theta, phi - deltaPhi / 2.])
     out.append([sc.arccos(z - deltaZ / 2), phi])
     out.append([theta, phi + deltaPhi / 2.])
     return sc.array(out)
Ejemplo n.º 8
0
	def _ang2vert_eq(nside,theta,phi,z):
		a= 4./3./nside
		b= 8./3./sc.pi
		deltaZ= a
		deltaPhi= a/b
		out= []
		out.append([sc.arccos(z+deltaZ/2),phi])
		out.append([theta,phi-deltaPhi/2.])
		out.append([sc.arccos(z-deltaZ/2),phi])
		out.append([theta,phi+deltaPhi/2.])
		return sc.array(out)
Ejemplo n.º 9
0
	def _xsys2ang(xs,ys):
		if sc.fabs(ys) <= sc.pi/4.:
			return [sc.arccos(8./3./sc.pi*ys),xs]
		else:
			xt= (xs % (sc.pi/2.))
			fabsys= sc.fabs(ys)
			theta= sc.arccos((1.-1./3.*(2.-4.*fabsys/sc.pi)**2.)*ys/fabsys)
			if fabsys == sc.pi/2.:
				phi= xs-fabsys+sc.pi/4.
			else:
				phi= xs-(fabsys-sc.pi/4.)/(fabsys-sc.pi/2.)*(xt-sc.pi/4.) 
			return [theta % (sc.pi+0.0000000001),phi % (2.*sc.pi)] #Hack
Ejemplo n.º 10
0
def rext_calc(df, lat=float):
    """
    Function to calculate extraterrestrial radiation output in J/m2/day
    Ref:http://www.fao.org/docrep/x0490e/x0490e07.htm

    :param df: dataframe with datetime index
    :param lat: latitude (negative for Southern hemisphere)
    :return: Rext (J/m2)
    """
    # set solar constant [MJ m^-2 min^-1]
    s = 0.0820
    #convert latitude [degrees] to radians
    latrad = lat * math.pi / 180.0
    #have to add in function for calculating single value here
    # extract date, month, year from index
    date = pd.DatetimeIndex(df.index).day
    month = pd.DatetimeIndex(df.index).month
    year = pd.DatetimeIndex(df.index).year
    doy = met.date2doy(dd=date, mm=month,
                       yyyy=year)  # create day of year(1-366) acc to date
    l = sp.size(doy)
    if l < 2:
        dt = 0.409 * math.sin(2 * math.pi / 365 * doy - 1.39)
        ws = sp.arccos(-math.tan(latrad) * math.tan(dt))
        j = 2 * math.pi / 365.25 * doy
        dr = 1.0 + 0.03344 * math.cos(j - 0.048869)
        rext = s * 86400 / math.pi * dr * (
            ws * math.sin(latrad) * math.sin(dt) +
            math.sin(ws) * math.cos(latrad) * math.cos(dt))
    #Create dummy output arrays sp refers to scipy
    else:
        rext = sp.zeros(l)
        dt = sp.zeros(l)
        ws = sp.zeros(l)
        j = sp.zeros(l)
        dr = sp.zeros(l)
        #calculate Rext
        for i in range(0, l):
            #Calculate solar decimation dt(d in FAO) [rad]
            dt[i] = 0.409 * math.sin(2 * math.pi / 365 * doy[i] - 1.39)
            #calculate sunset hour angle [rad]
            ws[i] = sp.arccos(-math.tan(latrad) * math.tan(dt[i]))
            # calculate day angle j [radians]
            j[i] = 2 * math.pi / 365.25 * doy[i]
            # calculate relative distance to sun
            dr[i] = 1.0 + 0.03344 * math.cos(j[i] - 0.048869)
            #calculate Rext dt = d(FAO) and latrad = j(FAO)
            rext[i] = (s * 86400.0 / math.pi) * dr[i] * (
                ws[i] * math.sin(latrad) * math.sin(dt[i]) +
                math.sin(ws[i]) * math.cos(latrad) * math.cos(dt[i]))

    rext = sp.array(rext) * 1000000
    return rext
Ejemplo n.º 11
0
def array_angles(array_list, acute = False):
    """
    given the two arrays of directions, return there angles
    can be set to return the acute angles
    """
    from scipy import arccos, pi
    # use dot product to calculate the angles
    if acute:
        return [arccos(abs(np.dot(array_list[0][i], array_list[1][i])) / (norm(array_list[0][i]) \
                * norm(array_list[1][i]))) / pi * 180 for i in range(len(array_list[0]))]
    else:
        return [arccos(np.dot(array_list[0][i], array_list[1][i]) / (norm(array_list[0][i]) \
                * norm(array_list[1][i]))) / pi * 180 for i in range(len(array_list[0]))]
Ejemplo n.º 12
0
def W_Anom(planet,t=0,t0=0):
    """Wahre Anomalie"""
    E = ex_Anom(planet,t,t0)
    eps = Planet[planet]["numEx"] #Zur besseren Lesbarkeit
    
    if (E >= 0 and E <= sc.pi):
        return sc.arccos((sc.cos(E) - eps) / (1 - eps*sc.cos(E)))
        
    elif (E >= sc.pi and E <= 2*sc.pi):
        return 2*sc.pi - sc.arccos((sc.cos(E) - eps) / (1 - eps*sc.cos(E)))
            
    else: 
        return 0 #Außerhalb der Intervalle nicht definiert
Ejemplo n.º 13
0
 def _xsys2ang(xs, ys):
     if sc.fabs(ys) <= sc.pi / 4.:
         return [sc.arccos(8. / 3. / sc.pi * ys), xs]
     else:
         xt = (xs % (sc.pi / 2.))
         fabsys = sc.fabs(ys)
         theta = sc.arccos(
             (1. - 1. / 3. * (2. - 4. * fabsys / sc.pi)**2.) * ys / fabsys)
         if fabsys == sc.pi / 2.:
             phi = xs - fabsys + sc.pi / 4.
         else:
             phi = xs - (fabsys - sc.pi / 4.) / (fabsys - sc.pi / 2.) * (
                 xt - sc.pi / 4.)
         return [theta % (sc.pi + 0.0000000001), phi % (2. * sc.pi)]  #Hack
Ejemplo n.º 14
0
def XyzToPol(coordxy):
    """ converti les coordonnees carthesiennes d'un point (x,y,z) en coordonnees polaires (r,azi,incli)"""
    x, y, z = coordxy[0], coordxy[1], coordxy[2]
    r = scipy.sqrt(x * x + y * y + z * z)
    if r == 0:
        incli = 0
    else:
        incli = scipy.arcsin(z / r)
    if (x == 0 and y == 0):
        azi = 0
    elif (y >= 0):
        azi = scipy.arccos(x / scipy.sqrt(x * x + y * y))
    else:
        azi = -scipy.arccos(x / scipy.sqrt(x * x + y * y))
    return scipy.array([r, azi, incli])
Ejemplo n.º 15
0
def rext_calc(df, lat=float):
    """
    Function to calculate extraterrestrial radiation output in J/m2/day
    Ref:http://www.fao.org/docrep/x0490e/x0490e07.htm

    :param df: dataframe with datetime index
    :param lat: latitude (negative for Southern hemisphere)
    :return: Rext (J/m2)
    """
    # set solar constant [MJ m^-2 min^-1]
    s = 0.08166
    #convert latitude [degrees] to radians
    latrad = lat*math.pi / 180.0
    #have to add in function for calculating single value here
    # extract date, month, year from index
    date = pd.DatetimeIndex(df.index).day
    month = pd.DatetimeIndex(df.index).month
    year = pd.DatetimeIndex(df.index).year
    doy = met.date2doy(dd=date, mm=month, yyyy=year)  # create day of year(1-366) acc to date
    l = sp.size(doy)
    if l < 2:
        dt = 0.409 * math.sin(2 * math.pi / 365 * doy - 1.39)
        ws = sp.arccos(-math.tan(latrad) * math.tan(dt))
        j = 2 * math.pi / 365.25 * doy
        dr = 1.0 + 0.03344 * math.cos(j - 0.048869)
        rext = s * 1440 / math.pi * dr * (ws * math.sin(latrad) * math.sin(dt) + math.sin(ws) * math.cos(latrad) * math.cos(dt))
    #Create dummy output arrays sp refers to scipy
    else:
        rext = sp.zeros(l)
        dt = sp.zeros(l)
        ws = sp.zeros(l)
        j = sp.zeros(l)
        dr = sp.zeros(l)
        #calculate Rext
        for i in range(0, l):
            #Calculate solar decimation dt(d in FAO) [rad]
            dt[i] = 0.409 * math.sin(2 * math.pi / 365 * doy[i] - 1.39)
            #calculate sunset hour angle [rad]
            ws[i] = sp.arccos(-math.tan(latrad) * math.tan(dt[i]))
            # calculate day angle j [radians]
            j[i] = 2 * math.pi / 365.25 * doy[i]
            # calculate relative distance to sun
            dr[i] = 1.0 + 0.03344 * math.cos(j[i] - 0.048869)
            #calculate Rext dt = d(FAO) and latrad = j(FAO)
            rext[i] = (s * 1440.0 / math.pi) * dr[i] * (ws[i] * math.sin(latrad) * math.sin(dt[i]) + math.sin(ws[i])* math.cos(latrad) * math.cos(dt[i]))

    rext = sp.array(rext) * 1000000
    return rext
Ejemplo n.º 16
0
def overlap(x, xdown, y, ydown, z, zdown, r, rdown, alpha):
    overlap_fraction = np.zeros(np.size(x))
    for i in range(0, np.size(x)):
        #define dx as the upstream x coordinate - the downstream x coordinate then rotate according to wind direction
        dx = xdown - x[i]
        #define dy as the upstream y coordinate - the downstream y coordinate then rotate according to wind direction
        dy = abs(ydown - y[i])
        dz = abs(zdown - z[i])
        d = sp.sqrt(dy**2.+dz**2.)
        R = r[i]+dx*alpha #The radius of the wake depending how far it is from the turbine
        A = rdown**2*pi #The area of the turbine
        if dx > 0:
            #if d <= R-rdown:
            #    overlap_fraction[i] = 1 #if the turbine is completely in the wake, overlap is 1, or 100%
            if d == 0:
                print "Area of turbine: ", A
                print "Area of wake: ", pi*R**2
                if A <= pi*R**2:
                    overlap_fraction[i] = 1.
                else: 
                    overlap_fraction[i] = pi*R**2/A
            elif d >= R+rdown:
                overlap_fraction[i] = 0 #if none of it touches the wake, the overlap is 0
            else:
                #if part is in and part is out of the wake, the overlap fraction is defied by the overlap area/rotor area
                overlap_area = rdown**2.*sp.arccos((d**2.+rdown**2.-R**2.)/(2.0*d*rdown))+R**2.*sp.arccos((d**2.+R**2.-rdown**2.)/(2.0*d*R))-0.5*sp.sqrt((-d+rdown+R)*(d+rdown-R)*(d-rdown+R)*(d+rdown+R))
                overlap_fraction[i] = overlap_area/A
        else:
            overlap_fraction[i] = 0 #turbines cannot be affected by any wakes that start downstream from them

    # print overlap_fraction
    print overlap_fraction
    return overlap_fraction #retrun the n x n matrix of how each turbine is affected by all of the others
Ejemplo n.º 17
0
 def __new__(self, nbinaries=1e6):
     arr = sp.ones(nbinaries, dtype=[(name, 'f8') for name in ['period', 'mass_ratio', 'eccentricity', 'phase', 'theta', 'inclination']])
     arr['eccentricity'] = 0.
     arr['phase'] = sp.rand(nbinaries)
     arr['theta'] = sp.rand(nbinaries) * 2 * sp.pi
     arr['inclination'] = sp.arccos(sp.rand(nbinaries) * 2. - 1.)
     return arr.view(OrbitalParameters)
Ejemplo n.º 18
0
    def integrand(z):
        """
        Determine the integrand for calculating the apparent elevation angle.
        :param z: The altitude (km).
        :return: The integrand.
        """

        # Effective radius of the Earth (km)
        re = 6378.137

        # Standard values
        a = 0.000315
        b = 0.1361

        # Refractive index and derivative as a function of altitude
        n_z = 1. + a * exp(-b * z)
        np_z = -(a * b * exp(-b * z))

        # Refractive index at the given height
        n_h = 1. + a * exp(-b * height)

        tan_phi = tan(
            arccos(((re + height) * n_h) / ((re + z) * n_z) *
                   cos(radians(theta_true))))

        return np_z / (n_z * tan_phi)
Ejemplo n.º 19
0
def vec2polar(vec):
    '''transform a vector to polar axis.'''
    r = np.linalg.norm(vec, axis=-1, keepdims=True)
    theta = np.arccos(vec[..., 2:3] / r)
    phi = np.arctan2(vec[..., 1:2], vec[..., :1])
    res = np.concatenate([r, theta, phi], axis=-1)
    return res
Ejemplo n.º 20
0
def resolve_tri(A,B,a,b,up=True):
    AB=A-B
    c=l.norm(AB)
    aa=s.arctan2(AB[1],AB[0])
    bb=s.arccos((b**2+c**2-a**2)/(2*b*c))
    if up: return B+b*s.array((s.cos(aa+bb),s.sin(aa+bb)))
    else: return B+b*s.array((s.cos(aa-bb),s.sin(aa-bb)))
def create_map(parameters,thetas,phis,vrs):
    
    
    pix = hp.ang2pix(parameters.nside,thetas,phis)
    number_of_pixels = hp.nside2npix(parameters.nside)
    vrmap = sp.ones(number_of_pixels)*parameters.badval
    
#    pdb.set_trace()
    vrs = sp.array(vrs)
    vrs_mean_of_repeated_pixels = copy.copy(vrs)
    for p in set(pix):
        vrs_mean_of_repeated_pixels[pix == p] = sp.mean(vrs[pix == p])
    
    vrmap[pix] = vrs_mean_of_repeated_pixels

#    pdb.set_trace()    
    theta_max = sp.arccos(1-2*parameters.skyfraction)
    pix_all = sp.array(range(number_of_pixels))
    pix_unseen = pix_all[hp.pix2ang(parameters.nside,pix_all)[0]>theta_max]
    vrmap[pix_unseen] = parameters.unseen

    empty_pixels = number_of_pixels-len(set(pix))
    print "The number of empty pixels inside the survey is", empty_pixels
    print "The corresponds to a fraction of", empty_pixels/number_of_pixels
    print "The number of pixels outside survey is", len(pix_unseen)
#    pdb.set_trace()
    return vrmap
Ejemplo n.º 22
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
Ejemplo n.º 23
0
def besselFourierKernel(m, zero, rho):
    """ Function kernel for the bessel Fourier method inversion
    
    Uses the mathematical formulation laid out in L. Wang and R. Granetz,
    Review of Scientific Instruments, 62, p.842, 1991. This generates
    the necessary weighting for a given chord in bessel/fourier space
    for a given tangency radius rho. There should be little reason to
    use this function unless modified and generating a new inversion
    scheme utilizing this kernel.

    Args:
        m: geometry Object with reference origin

        zero: geometry Object with reference origin
        
        rho: normalized tangency radius

    Returns:
        numpy array: Vector points from pt1 to pt2.
    
    """

    # I SHOULD TRY AND VECTORIZE THIS AS MUCH AS POSSIBLE
    jprime = (scipy.special.jn(m + 1, zero) - scipy.special.jn(m - 1, zero))
    return jprime * scipy.integrate.quad(
        _beam.bessel_fourier_kernel, 0, scipy.arccos(rho),
        args=(m, zero, rho))[0]
def correct_z_orientation(accelerations, angular_velocities, stationary_times):
    """ Use gravity vector direction to align reference frame to correct z-axis

    Assumes the car is stationary for the first 10000 times and the gravity haven't been removed

    :param accelerations: 3xn numpy array angular velocities
    :param angular_velocities: 3xn numpy array angular velocities
    :param stationary_times: list of tuples (start,end)
    :return: numpy arrays: rotated accelerations, rotated angular velocities
    """

    # get value of g in all stationary times
    g = np.mean(np.concatenate([
        accelerations[:, stationary_time[0]:stationary_time[1]]
        for stationary_time in stationary_times
    ],
                               axis=1),
                axis=1)

    def align_from_g_vector(accelerations, angular_velocities, g):
        g_norm = norm(g)
        u = cross(g, (0, 0, 1))
        # rotation axis
        u_unit = u / norm(u)
        # rotate angle
        theta = arccos(dot(g, (0, 0, 1)) / g_norm)
        print("rotating vectors of " + str(np.rad2deg(theta)) +
              " degrees align to z")
        rotator = np.exp(quaternion(*(theta * u_unit)) / 2)
        rotated_accelerations = np.array([
            (rotator * quaternion(*acceleration_vector) *
             ~rotator).components[1:]
            for acceleration_vector in accelerations.T
        ])
        rotated_angular_velocities = np.array([
            (rotator * quaternion(*angular_velocity) * ~rotator).components[1:]
            for angular_velocity in angular_velocities.T
        ])
        return rotated_accelerations.T, rotated_angular_velocities.T

    accelerations, angular_velocities = align_from_g_vector(
        accelerations, angular_velocities, g)

    # for the remaining stationary times
    for stationary_time in stationary_times[1:]:
        # calculate bad align angle
        g = accelerations[:,
                          stationary_time[0]:stationary_time[1]].mean(axis=1)
        bad_align_angle = arccos(dot(g, (0, 0, 1)) / norm(g))
        # if the bad align angle is greater than 2 degrees
        if bad_align_angle > np.deg2rad(10):
            # print a warning
            import warnings
            message = " \n Found additional bad z axis of {} degrees alignment at time {} , " \
                      "realigning from now  \n".format(np.rad2deg(bad_align_angle), stationary_time[0])
            warnings.warn(message)
            # re-align
            accelerations, angular_velocities = align_from_g_vector(
                accelerations, angular_velocities, g)
    return accelerations, angular_velocities
Ejemplo n.º 25
0
def add_geometric_edge_properties(G):
    """ Adds angle to cortical surface (in degrees), cortical depth, volume and
    cross section to each edge in the graph.
    INPUT: G:  Vascular graph in iGraph format.
    OUTPUT: None - the vascular graph G is modified in place.
    """
           
    depth = []
    angle = []
    crossSection = [] 
    volume = []

    ez = array([0,0,1])
    
    for edge in G.es:         
        
        a = G.vs[edge.source]['r']
        b = G.vs[edge.target]['r']
        v = a-b    
        depth.append((a[2]+b[2])/2.0)
        
        theta=arccos(dot(v,ez)/norm(v))/2/pi*360
        if theta > 90:
            theta = 180-theta
        angle.append(theta)
    
        crossSection.append(np.pi * edge['diameter']**2. / 4.)
        volume.append(crossSection[-1] * edge['length'])
    
    
    G.es['depth'] = depth
    G.es['angle'] = angle
    G.es['volume'] = volume
    G.es['crossSection'] = crossSection 
Ejemplo n.º 26
0
def Rz_to_uv(R,z,delta=1.):
    """
    NAME:

       Rz_to_uv

    PURPOSE:

       calculate prolate confocal u and v coordinates from R,z, and delta

    INPUT:

       R - radius

       z - height

       delta= focus

    OUTPUT:

       (u,v)

    HISTORY:

       2012-11-27 - Written - Bovy (IAS)

    """
    coshu, cosv= Rz_to_coshucosv(R,z,delta)
    u= sc.arccosh(coshu)
    v= sc.arccos(cosv)
    return (u,v)
Ejemplo n.º 27
0
def pd_output(p, m, alpha):
    N = 500
    PD = np.zeros(N)

    if p == 1:
        theta_end = def2sca(theta_def(90, p, m), p)
        theta = np.linspace(1e-10, theta_end - 1e-10, N)
        theta_range = theta_end
    else:
        ths_end = arccos(np.sqrt((m**2 - 1) / (p**2 - 1))) * 180 / pi  # 彩虹角位置
        theta_end = def2sca(theta_def(ths_end, p, m), p)
        theta = np.linspace(theta_end + 1e-10, 180, N)
        theta_range = 180 - theta_end

    print(theta_end)

    dtheta = theta_range / (N - 1)
    i = 0
    for ths in theta:
        # result = find_theta_i(ths, p, m, error=1e-12)
        pd = phase_diff(ths, alpha, 0, p, m)
        PD[i] = pd
        i += 1

    # 输出: 散射角,相位差, 散射角, 相位差频率
    return (theta, PD, theta[1:], abs(diff(PD)) / (2 * pi * dtheta))
Ejemplo n.º 28
0
def dotties():
    data = fi.read_data("../sgrnorth_paper/planefit_results.txt", ",")
    planes = []
    for i in range(6):
        planes.append(data[i, :])
    #for plane in planes:  print plane
    dots = sc.zeros((6, 6))
    for i in range(6):
        for j in range(6):
            dots[i, j] = (sc.arccos(planes[i][0] * planes[j][0] +
                                    planes[i][1] * planes[j][1] +
                                    planes[i][2] * planes[j][2])) * deg
    print dots
    print
    errors = sc.zeros((6, 6))
    for i in range(6):
        for j in range(6):
            dotty = planes[i][0] * planes[j][0] + planes[i][1] * planes[j][
                1] + planes[i][2] * planes[j][2]
            factor = -1.0 / sc.sqrt(1 - dotty * dotty)
            print factor
            errors[i, j] = factor * (
                planes[j][0] * planes[i][4] + planes[i][0] * planes[j][4] +
                planes[j][1] * planes[i][5] + planes[i][1] * planes[j][5] +
                planes[j][2] * planes[i][6] +
                planes[i][2] * planes[j][6]) * deg
            #if i==3 and j==5:  print dotty
    print errors
    Sgr = [14.655645800014774, 2.2704309216189817, -5.8873772610912614]
    print "# - dist to Sgr Core:"
    for plane in planes:
        print (Sgr[0]*plane[0] + Sgr[1]*plane[1] + Sgr[2]*plane[2] + plane[3]), \
        (Sgr[0]*plane[4] + Sgr[1]*plane[5] + Sgr[2]*plane[6] + plane[7])
Ejemplo n.º 29
0
def pos2Ray(pos, tokamak, angle=None, eps=1e-6):
    r"""Take in GENIE pos vectors and convert it into TRIPPy rays
    
    Args:
        pos: 4 element tuple or 4x scipy-array
            Each pos is assembled into points of (R1,Z1,RT,phi)

        tokamak: 
            Tokamak object in which the pos vectors are defined.
            
    Returns:
        Ray: Ray object or typle of ray objects.
        
    """

    r1 = scipy.array(pos[0])
    z1 = scipy.array(pos[1])
    rt = scipy.array(pos[2])
    phi = scipy.array(pos[3])

    zt = z1 - scipy.tan(phi) * scipy.sqrt(r1**2 - rt**2)
    angle2 = scipy.arccos(old_div(rt, r1))

    if angle is None:
        angle = scipy.zeros(r1.shape)

    pt1 = geometry.Point((r1, angle, z1), tokamak)
    pt2 = geometry.Point((rt, angle + angle2, zt), tokamak)

    output = Ray(pt1, pt2)
    output.norm.s[-1] = eps
    tokamak.trace(output)
    return output
Ejemplo n.º 30
0
def besselFourierKernel(m, zero, rho):
    """ Function kernel for the bessel Fourier method inversion
    
    Uses the mathematical formulation laid out in L. Wang and R. Granetz,
    Review of Scientific Instruments, 62, p.842, 1991. This generates
    the necessary weighting for a given chord in bessel/fourier space
    for a given tangency radius rho. There should be little reason to
    use this function unless modified and generating a new inversion
    scheme utilizing this kernel.

    Args:
        m: geometry Object with reference origin

        zero: geometry Object with reference origin
        
        rho: normalized tangency radius

    Returns:
        numpy array: Vector points from pt1 to pt2.
    
    """


    # I SHOULD TRY AND VECTORIZE THIS AS MUCH AS POSSIBLE
    jprime = (scipy.special.jn(m+1, zero) - scipy.special.jn(m-1, zero))
    return jprime*scipy.integrate.quad(_beam.bessel_fourier_kernel,
                                       0,
                                       scipy.arccos(rho),
                                       args = (m, zero, rho))[0]
Ejemplo n.º 31
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)
Ejemplo n.º 32
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
Ejemplo n.º 33
0
    def __calc_laplacian(self):
        numDims                 = self.polygons.shape[0];
        numPoints               = self.points.shape[1];
        numPolygons             = self.polygons.shape[1];

        sparseMatrix            = csr_matrix((numPoints, numPoints));

        for i in range(0, numDims):
            i1                  = (i + 0)%3;
            i2                  = (i + 1)%3;
            i3                  = (i + 2)%3;

            distP2P1            = self.points[:, self.polygons[i2, :]] - self.points[:, self.polygons[i1, :]];
            distP3P1            = self.points[:, self.polygons[i3, :]] - self.points[:, self.polygons[i1, :]];

            distP2P1            = distP2P1 / repmat(sqrt((distP2P1**2).sum(0)), 3, 1);
            distP3P1            = distP3P1 / repmat(sqrt((distP3P1**2).sum(0)), 3, 1);

            angles              = arccos((distP2P1 * distP3P1).sum(0));

            iterData1           = csr_matrix((1/tan(angles), 
                                                    (self.polygons[i2,:], 
                                                     self.polygons[i3,:])), 
                                                    shape=(numPoints, numPoints));

            iterData2           = csr_matrix((1/tan(angles), (self.polygons[i3,:], self.polygons[i2,:])), shape=(numPoints, numPoints));

            sparseMatrix        = sparseMatrix + iterData1 + iterData2;

        diagonal                = sparseMatrix.sum(0);
        diagonalSparse          = spdiags(diagonal, 0, numPoints, numPoints);
        self.__laplacian        = diagonalSparse - sparseMatrix;
Ejemplo n.º 34
0
def young(phase,
          sigma_sg,
          sigma_sl,
          surface_tension='pore.surface_tension',
          **kwargs):
    r'''
    Calculate contact angle using Young's equation
    
    Notes
    -----
    Young's equation is: sigma_lg*Cos(theta)=sigma_sg - sigma_sl
    where
    sigma_lg is the liquid-gas surface tension [N/m]
    sigma_sg is the solid-gas surface tension [N/m]
    sigma_sl is the solid-liquid interfacial tension [J/m^2]
    theta is the Young contact angle [rad]
           
    '''
    if surface_tension.split('.')[0] == 'pore':
        sigma = phase[surface_tension]
        sigma = phase.interpolate_data(data=sigma)
    else:
        sigma = phase[surface_tension]
    theta = sp.arccos((sigma_sg - sigma_sl) / phase[surface_tension])
    theta = sp.rad2deg(theta)
    return theta
Ejemplo n.º 35
0
def geo_dist(P,Q):

    # Make sure these are valid distributions
    assert all(np.isreal(P))
    assert all(P >= 0)
    assert any(P > 0)
    assert all(np.isreal(Q))
    assert all(Q >= 0)
    assert any(Q > 0)

    # Enforce proper normalization
    P_prob = P/sp.sum(P) 
    Q_prob = Q/sp.sum(Q) 

    # Return geodistance. arccos can behave badly if argument
    # is too close to one, so prepare for this
    try:
        dist = 2*sp.arccos(sp.sum(sp.sqrt(P_prob*Q_prob)))
        assert np.isreal(dist)
    except:
        if sp.sum(sp.sqrt(P_prob*Q_prob)) > 1 - TINY_FLOAT32:
            dist = 0
        else:
            raise
    return dist
Ejemplo n.º 36
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)
Ejemplo n.º 37
0
def young(phase,
          sigma_sg,
          sigma_sl,
          surface_tension='pore.surface_tension',
          **kwargs):
    r'''
    Calculate contact angle using Young's equation
    
    Notes
    -----
    Young's equation is: sigma_lg*Cos(theta)=sigma_sg - sigma_sl
    where
    sigma_lg is the liquid-gas surface tension [N/m]
    sigma_sg is the solid-gas surface tension [N/m]
    sigma_sl is the solid-liquid interfacial tension [J/m^2]
    theta is the Young contact angle [rad]
           
    '''
    if surface_tension.split('.')[0] == 'pore':
        sigma = phase[surface_tension]
        sigma = phase.interpolate_data(data=sigma)
    else:
        sigma = phase[surface_tension]
    theta = sp.arccos((sigma_sg - sigma_sl)/phase[surface_tension])
    theta = sp.rad2deg(theta)
    return theta
Ejemplo n.º 38
0
def pos2Ray(pos, tokamak, angle=None, eps=1e-6):
    r"""Take in GENIE pos vectors and convert it into TRIPPy rays
    
    Args:
        pos: 4 element tuple or 4x scipy-array
            Each pos is assembled into points of (R1,Z1,RT,phi)

        tokamak: 
            Tokamak object in which the pos vectors are defined.
            
    Returns:
        Ray: Ray object or typle of ray objects.
        
    """

    r1 = scipy.array(pos[0])
    z1 = scipy.array(pos[1])
    rt = scipy.array(pos[2])
    phi = scipy.array(pos[3])

    zt = z1 - scipy.tan(phi)*scipy.sqrt(r1**2 - rt**2)
    angle2  = scipy.arccos(rt/r1)

    if angle is None:
        angle = scipy.zeros(r1.shape)

    pt1 = geometry.Point((r1,angle,z1),tokamak)
    pt2 = geometry.Point((rt,angle+angle2,zt),tokamak)

    output = Ray(pt1,pt2)
    output.norm.s[-1] = eps
    tokamak.trace(output)
    return output
Ejemplo n.º 39
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
Ejemplo n.º 40
0
def dotties():
    data = fi.read_data("../sgrnorth_paper/planefit_results.txt", ",")
    planes = []
    for i in range(6):
        planes.append(data[i,:])
    #for plane in planes:  print plane
    dots = sc.zeros((6,6))
    for i in range(6):
        for j in range(6):
            dots[i,j] = (sc.arccos(planes[i][0]*planes[j][0] + planes[i][1]*planes[j][1]
                                   + planes[i][2]*planes[j][2]))*deg
    print dots
    print
    errors = sc.zeros((6,6))
    for i in range(6):
        for j in range(6):
            dotty = planes[i][0]*planes[j][0]+planes[i][1]*planes[j][1]+planes[i][2]*planes[j][2]
            factor = -1.0 / sc.sqrt(1 - dotty*dotty)
            print factor
            errors[i,j] = factor*(planes[j][0]*planes[i][4] + planes[i][0]*planes[j][4] +
                                  planes[j][1]*planes[i][5] + planes[i][1]*planes[j][5] +
                                  planes[j][2]*planes[i][6] + planes[i][2]*planes[j][6])*deg
            #if i==3 and j==5:  print dotty
    print errors
    Sgr = [14.655645800014774, 2.2704309216189817, -5.8873772610912614]
    print "# - dist to Sgr Core:"
    for plane in planes:
        print (Sgr[0]*plane[0] + Sgr[1]*plane[1] + Sgr[2]*plane[2] + plane[3]), \
        (Sgr[0]*plane[4] + Sgr[1]*plane[5] + Sgr[2]*plane[6] + plane[7])
Ejemplo n.º 41
0
def add_geometric_edge_properties(G):
    """ Adds angle to cortical surface (in degrees), cortical depth, volume and
    cross section to each edge in the graph.
    INPUT: G:  Vascular graph in iGraph format.
    OUTPUT: None - the vascular graph G is modified in place.
    """

    depth = []
    angle = []
    crossSection = []
    volume = []

    ez = array([0, 0, 1])

    for edge in G.es:

        a = G.vs[edge.source]['r']
        b = G.vs[edge.target]['r']
        v = a - b
        depth.append((a[2] + b[2]) / 2.0)

        theta = arccos(dot(v, ez) / norm(v)) / 2 / pi * 360
        if theta > 90:
            theta = 180 - theta
        angle.append(theta)

        crossSection.append(np.pi * edge['diameter']**2. / 4.)
        volume.append(crossSection[-1] * edge['length'])

    G.es['depth'] = depth
    G.es['angle'] = angle
    G.es['volume'] = volume
    G.es['crossSection'] = crossSection
Ejemplo n.º 42
0
Archivo: wcs.py Proyecto: 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
Ejemplo n.º 43
0
def compute_amono_analytic(x1, x2, leaf_temperature, vpd, gammax, rd, psi, model='misson',
                           g0=0.019, rbt=2. / 3., ca=400., m0=5.278, psi0=-0.1,
                           d0_leuning=30., steepness_tuzet=1.85):
    """Computes the gross CO2 assimilation rate analytically.

    Args:
        x1 (float): Vcmax or J/4.
        x2 (float): KmC(1+O/KmO) or 2 gamma_asterisk
        leaf_temperature (float): [°C] leaf temperature
        vpd (float): [kPa] leaf-to-air vapor pressure deficit
        gammax (float): [ubar] CO2 compensation point
        rd (float): [umol m-2 s-1] mitochondrial respiration rate in the light
        psi (float): [MPa] bulk water potential of the leaf
        model (str): stomatal conductance reduction model, one of 'misson','tuzet', 'linear' or 'vpd'
        g0 (float): [umol m-2 s-1] residual stomatal conductance to CO2
        rbt (float): [m2 s ubar umol-1] combined turbulance and boundary layer resistance to CO2
        ca (float): [ubar] CO2 partial pressure of the air
        m0 (float): [umol mmol-1] maximum slope An/gs (absence of water deficit), see :func:`fvpd_3`
        psi0 (float): [MPa] critical thershold for water potential, see :func:`fvpd_3`
        d0_leuning (float): [kPa-1] shape parameter, see :func:`fvpd_3`
        steepness_tuzet (float): [MPa-1] shape parameter, see :func:`fvpd_3`

    Returns:
        (float): [umolCO2 m-2 s-1] gross CO2 assimilation rate

    References:
        Evers et al. 2010.
            Simulation of wheat growth and development based on organ-level photosynthesis and assimilate allocation.
            Journal of Experimental Botany 61, 2203 – 2216.

    Notes:
        A is called 'mono' since it is calculated for either of RuBisco- or e transport-limited phases.
        The net A (An) is calculated using the function 'compute_an_analytic'

    """

    f_vpd = fvpd_3(model, vpd, psi, psi_crit=psi0, m0=m0, steepness_tuzet=steepness_tuzet, d0_leuning=d0_leuning)

    cube_a = g0 * (x2 + gammax) + (g0 / mesophyll_conductance(leaf_temperature) + f_vpd) * (x1 - rd)
    cube_b = utils.cmol2cpa(leaf_temperature, ca) * (x1 - rd) - gammax * x1 - rd * x2
    cube_c = utils.cmol2cpa(leaf_temperature, ca) + x2 + (1. / mesophyll_conductance(leaf_temperature) + rbt) * (
            x1 - rd)
    cube_d = x2 + gammax + (x1 - rd) / mesophyll_conductance(leaf_temperature)
    cube_e = 1. / mesophyll_conductance(leaf_temperature) + (g0 / mesophyll_conductance(leaf_temperature) + f_vpd) * (
            1. / mesophyll_conductance(leaf_temperature) + rbt)
    cube_p = -(cube_d + (x1 - rd) / mesophyll_conductance(leaf_temperature) + cube_a * (
            1. / mesophyll_conductance(leaf_temperature) + rbt) + (
                       g0 / mesophyll_conductance(leaf_temperature) + f_vpd) * cube_c) / cube_e
    cube_q = (cube_d * (x1 - rd) + cube_a * cube_c + (
            g0 / mesophyll_conductance(leaf_temperature) + f_vpd) * cube_b) / cube_e
    cube_r = -(cube_a * cube_b / cube_e)
    cube_Q = (cube_p ** 2. - 3. * cube_q) / 9.
    cube_R = (2. * cube_p ** 3. - 9. * cube_p * cube_q + 27. * cube_r) / 54.
    cube_xi = arccos(max(-1., min(1., cube_R / sqrt(cube_Q ** 3.))))

    a_mono = -2. * sqrt(cube_Q) * cos(cube_xi / 3.) - cube_p / 3.

    return a_mono
Ejemplo n.º 44
0
    def __xor__(self, data):
        try:
            x = sp.array([d.xcart for d in data])
            y = sp.array([d.ycart for d in data])
            z = sp.array([d.zcart for d in data])
            ra = sp.array([d.ra for d in data])
            dec = sp.array([d.dec for d in data])

            cos = x * self.xcart + y * self.ycart + z * self.zcart
            w = cos >= 1.
            if w.sum() > 1:
                print('WARNING: {} pairs have cosinus>=1.'.format(w.sum()))
                cos[w] = 1.
            w = cos <= -1.
            if w.sum() > 1:
                print('WARNING: {} pairs have cosinus<=-1.'.format(w.sum()))
                cos[w] = -1.
            angl = sp.arccos(cos)

            w = (sp.absolute(ra - self.ra) < constants.small_angle_cut_off) & (
                sp.absolute(dec - self.dec) < constants.small_angle_cut_off)
            if w.sum() != 0:
                angl[w] = sp.sqrt((dec[w] - self.dec)**2 +
                                  (self.cosdec * (ra[w] - self.ra))**2)
        except:
            x = data.xcart
            y = data.ycart
            z = data.zcart
            ra = data.ra
            dec = data.dec

            cos = x * self.xcart + y * self.ycart + z * self.zcart
            if cos >= 1.:
                print('WARNING: 1 pair has cosinus>=1.')
                cos = 1.
            elif cos <= -1.:
                print('WARNING: 1 pair has cosinus<=-1.')
                cos = -1.
            angl = sp.arccos(cos)
            if (sp.absolute(ra - self.ra) < constants.small_angle_cut_off) & (
                    sp.absolute(dec - self.dec) <
                    constants.small_angle_cut_off):
                angl = sp.sqrt((dec - self.dec)**2 + (self.cosdec *
                                                      (ra - self.ra))**2)
        return angl
Ejemplo n.º 45
0
def aoa_diff_rad(aoa_a, aoa_b):
    """
    Calculate the difference between two angles of arrival, in radians.
    """
    # Prepend radius 1 and convert to cartesian.
    cart_a = sph2cart((1, ) + tuple(aoa_a))
    cart_b = sph2cart((1, ) + tuple(aoa_b))
    # Property of dot product between vectors.
    return sp.arccos(sp.dot(cart_a, cart_b))
Ejemplo n.º 46
0
def random_3D_direction():
    phi = sp.random.uniform(0, sp.pi * 2)
    cos_theta = sp.random.uniform(-1, 1)
    theta = sp.arccos(cos_theta)
    sin_theta = sp.sin(theta)
    x = sin_theta * sp.cos(phi)
    y = sin_theta * sp.sin(phi)
    z = cos_theta
    return sp.array([x, y, z])
Ejemplo n.º 47
0
def aoa_diff_rad(aoa_a,aoa_b):
    """
    Calculate the difference between two angles of arrival, in radians.
    """
    # Prepend radius 1 and convert to cartesian.
    cart_a = sph2cart( (1,) + tuple(aoa_a) )
    cart_b = sph2cart( (1,) + tuple(aoa_b) )
    # Property of dot product between vectors.
    return sp.arccos(sp.dot(cart_a,cart_b))
def guess_initial_parameters(mean, phi0, omega):
    mean_max = mean.max()
    mean_min = mean.min()
    offset = (mean_max + mean_min)/2.
    amplitude = (mean_max - mean_min)/2.
    if phi0 is None or omega is None:
        y = mean-offset
        y2 = savgol_filter(y, 11, 1, mode="nearest")
        if phi0 is None:
            cos_phi0 = clip(y2[0]/amplitude, -1., 1.)
            if y2[1] > y2[0]:
                phi0 = -arccos(cos_phi0)
            else:
                phi0 = arccos(cos_phi0)
        if omega is None:
            zero_crossings = scipy.where(scipy.diff(scipy.sign(y2)))[0]
            omega = pi/scipy.average(scipy.diff(zero_crossings))
    return offset, amplitude, phi0, omega
Ejemplo n.º 49
0
Archivo: quat.py Proyecto: buguen/minf
 def errorAngle(actual,estimate):        
     error = actual*estimate.conjugate()
     error.normalise()
     # Cast error to float so that we can deal with fixed point numbers
     # throws an error otherwise
     eAngle = degrees(2*arccos(float(error.w)))
     
     eAngle = abs(eAngle - 360) if eAngle > 180 else eAngle
     return eAngle
Ejemplo n.º 50
0
Archivo: quat.py Proyecto: buguen/minf
    def asAxisAndAngle(self):
        axis = array([nan,nan,nan])
        angle = 2*arccos(self.w)
        if angle != 0:
            s = sqrt(1 - self.w**2)
            axis[0] = self.x / s
            axis[1] = self.y / s
            axis[2] = self.z / s

        return axis, angle
Ejemplo n.º 51
0
Archivo: mesh.py Proyecto: zimoun/mtf
 def tosph(self):
     x, y, z = self.coord
     rho = self.norm()
     if sp.absolute(x) < 1e-8:
         if y >= 0:
             theta = sp.pi/2
         else:
             theta = 3*sp.pi/2
     else:
         theta = sp.arctan(y/x)
     phi = sp.arccos(z/rho)
     return rho, theta, phi
Ejemplo n.º 52
0
def As_The_Cockey_Flies(lat0, lon0, lat, lon):
    # Algorithm from GA website
    # Uses spherical geometry (rather than a projection)
    # to calculate epicentral distance
    lat = lat[:, newaxis]
    lon = lon[:, newaxis]
    L1 = lat0 * (pi / 180)
    L2 = lat * (pi / 180)
    DG = (lon - lon0) * (pi / 180)
    D = 1.852 * 60 * 180 / pi * \
        arccos(sin(L1) * sin(L2) + cos(L1) * cos(L2) * cos(DG))
    return D
Ejemplo n.º 53
0
def cosine_distance(x, y):
    assert (x.dtype == np.float64 and y.dtype == np.float64) or (
        x.dtype == np.float32 and y.dtype == np.float32)
    x2 = np.sqrt(np.sum(x ** 2, axis=1))
    y2 = np.sqrt(np.sum(y ** 2, axis=1))
    ix = x2 == 0.
    iy = y2 == 0.
    d = np.dot(x, y.T) / (np.outer(x2, y2))
    # DPX: to prevent the stupid scipy to collapse the array into scalar
    if d.shape == (1, 1):
        d = np.array([[np.float64(scipy.arccos(d[0,0]) / np.pi)]])
    else:
        # costly in time (half of the time), so check if really useful for dtw
        d = np.float64(scipy.arccos(d) / np.pi)

    d[ix, :] = 1.
    d[:, iy] = 1.
    for i in np.where(ix)[0]:
        d[i, iy] = 0.
    assert np.all(d >= 0)
    return d
Ejemplo n.º 54
0
 def set_orientation(self, value):
     if isinstance(value, (list, N.ndarray)):
         value = N.asarray(value)
         # find quaternion for rotation
         n = N.cross([0, 0, 1], unit_vector(value[:3]))
         phi = N.arccos(N.dot([0, 0, 1], unit_vector(value[:3])))
         self._orientation = quaternion_about_axis(phi, n)
     elif value is True:
         # random orientation
         self._orientation = random_quaternion()
     else:
         # other stuff goes no orientation
         self._orientation = False
Ejemplo n.º 55
0
def angle(Vec1, Vec2):
    """Returns angle between two vectors.

    Args:
        Vec1: Vec Object

        Vec2: Vec Object

    Returns:
        angle in radians :math:`[0,\pi]` seperating the two vectors
        on the plane defined by the two.
     
    """
    return scipy.arccos((Vec1 * Vec2)/(Vec1.s * Vec2.s)) 
Ejemplo n.º 56
0
Archivo: quat.py Proyecto: 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)
Ejemplo n.º 57
0
 def __contact_greensfunction(self, ind_contact, node_i, node_j, E):
     """calculates the value of the transverse mode's square at the point
     of the contact_node, essentially sin(pi)sin(pi) multiplied with
     appropriate amplitude and constats """
     from scipy import arccos, exp, sin, pi, sqrt
     length = (ind_contact.shape[1]-1.0)
     amplitude = 1/sqrt(length)
     mode_energy = self.p.hbar**2 * pi**2/(2*self.mass * (length*self.a)**2)
     #Amplitude = 1
     ka = arccos(1-(E+mode_energy-self.band_bottom)/(2*self.t0))
     Phase = exp(1j*ka)
     xi_i = amplitude * sin(pi * node_i/length)
     xi_j = amplitude * sin(pi * node_j/length)
     greensfunction =xi_j * xi_i *  Phase
     return greensfunction
Ejemplo n.º 58
0
 def SelectParticlesInCone(self,x,y,z,OpeningAngle):
     Theta = scipy.arccos((self.x*x+self.y*y+self.z*z) / scipy.sqrt(x**2+y**2+z**2) / scipy.sqrt(self.x**2+self.y**2+self.z**2))
     GoodIds = scipy.where(Theta<OpeningAngle)
     self.x = self.x[GoodIds]
     self.y = self.y[GoodIds]
     self.z = self.z[GoodIds]
     self.vx = self.vx[GoodIds]
     self.vy = self.vy[GoodIds]
     self.vz = self.vz[GoodIds]
     self.m = self.m[GoodIds]
     self.ID = self.ID[GoodIds]
     if self.V != None:
         self.V = self.V[GoodIds]
     self.NPartTotal = len(self.x)
     self.NPart = [0,len(self.x),0,0,0,0]
Ejemplo n.º 59
0
def cs_dist(
        trains, smoothing_filter, sampling_rate,
        filter_area_fraction=sigproc.default_kernel_area_fraction):
    """ Calculates the Cauchy-Schwarz distance between two spike trains given
    a smoothing filter.

    Let :math:`v_a(t)` and :math:`v_b(t)` with :math:`t \\in \\mathcal{T}` be
    the spike trains convolved with some smoothing filter and :math:`V(a, b)
    = \\int_{\\mathcal{T}} v_a(t) v_b(t) dt`. Then, the Cauchy-Schwarz distance
    of the spike trains is defined as :math:`d_{CS}(a, b) = \\arccos \\frac{V(a,
    b)^2}{V(a, a) V(b, b)}`.

    The Cauchy-Schwarz distance is closely related to the Schreiber et al.
    similarity measure :math:`S_S` by :math:`d_{CS} = \\arccos S_S^2`

    This function numerically convolves the spike trains with the smoothing
    filter which can be quite slow and inaccurate. If the analytical result of
    the autocorrelation of the smoothing filter is known, one can use
    :func:`schreiber_similarity` for a more efficient and precise calculation.

    Further information can be found in *Paiva, A. R. C., Park, I., & Principe,
    J. (2010). Inner products for representation and learning in the spike
    train domain. Statistical Signal Processing for Neuroscience and
    Neurotechnology, Academic Press, New York.*

    :param sequence trains: Sequence of :class:`neo.core.SpikeTrain` objects of
        which the distance will be calculated pairwise.
    :param smoothing_filter: Smoothing filter to be convolved with the spike
        trains.
    :type smoothing_filter: :class:`.signal_processing.Kernel`
    :param sampling_rate: The sampling rate which will be used to bin
        the spike trains as inverse time scalar.
    :type sampling_rate: Quantity scalar
    :param float filter_area_fraction: A value between 0 and 1 which controls
        the interval over which the smoothing filter will be discretized. At
        least the given fraction of the complete smoothing filter area will be
        covered. Higher values can lead to more accurate results (besides the
        sampling rate).
    :returns: Matrix containing the Cauchy-Schwarz distance of all pairs of
        spike trains
    :rtype: 2-D array
    """

    inner = st_inner(
        trains, trains, smoothing_filter, sampling_rate, filter_area_fraction)
    return sp.arccos(
        inner ** 2 / sp.diag(inner) / sp.atleast_2d(sp.diag(inner)).T)