コード例 #1
0
ファイル: elastica.py プロジェクト: swkeemink/elastica
def findcurve(psi1,psi2,n=3,nn_fit=4,nn_out=100):
    '''
    Function to find the elastica curve for start and end orientations
    psi1 and psi2. It finds the best curve across all directions from start
    and end, i.e. the direction independent elastica curve.
    
    Inputs
    ------------
    psi1,psi2: start and end orientations.
    n:     degree of estimation polynomial.
    nn:    number of points on the curve.
             - nn_fit: for fittin purposes
             - nn_out: for the output
    
    Outputs
    ------------
    Returns a tuple (s,psi). 
    s:   points on the curve.
    psi: curvature of the curve as a function of s.
    E:   curvature energy of the curve
    '''
    # 
    
    # define the starting conditions
    a0 = pl.zeros(n+1) 
    
    # Set a high energy: 
    E_best = 10000  
    
    # and predfine output curve
    s       = pl.linspace(0,1,nn_out) # points on the curve
    psi_out = pl.zeros(nn_out)        # curvature at points in curve
    
    
    # across all the start and end directions find the curve with the lowest energy    
    for dpsi1 in (-pl.pi,0,pl.pi):
        for dpsi2 in (-pl.pi,0,pl.pi):
            # For the starting variables,
            # the first two polygon variables can be estimated from the Sharon paper derivation
            # For different starting variables the solution can be hard to find            
            a0[-2] = 4*(   pl.arcsin(- (pl.sin(psi1+dpsi1)+ pl.sin(psi2+dpsi2))/4)    -(psi1+dpsi1+psi2+dpsi2)/2       )
            a0[-1] = 2*a0[-2]/pl.cos( (psi1+dpsi1+psi2+dpsi2)/2 + a0[-2]/4  )               
            
            # find the best variables to minimize the elastica energy
            fit = fsolve(errors,a0,args=(psi1+dpsi1,psi2+dpsi2,nn_fit))
    
            # find the curve and its derivative for the fitted variables
            a    = fit[:-1]
            psi  = Psi(a,s,psi1+dpsi1,psi2+dpsi2)
            dpsi = dPsi(a,s,psi1+dpsi1,psi2+dpsi2)
    
            # find the energy of this curve
            E = sum(dpsi**2)*s[1]
            
            # check against the lowest energy
            if E_best > E:
                E_best = E
                psi_out[:] = pl.copy(psi)    
    
    return (s,psi_out,E_best)
コード例 #2
0
ファイル: tools_glp.py プロジェクト: mabitbol/mapsim
def my_hor_to_eq(az, el, lat, lsts):
    dec = arcsin(sin(el) * sin(lat) + cos(el) * cos(lat) * cos(az))
    argument = (sin(el) - sin(lat) * sin(dec)) / (cos(lat) * cos(dec))
    argument = clip(argument, -1.0, 1.0)
    H = arccos(argument)
    flag = sin(az) > 0
    H[flag] = 2.0*pi - H[flag]
    ra = lsts - H
    ra %= 2*pi
    return ra,dec
コード例 #3
0
ファイル: create_rotation_file.py プロジェクト: espenhgn/LFPy
def det_rotationangles2(cell, segment1, segment2):
    """return rotationangles around x- and y-axis, so the line between two
    chosen segments is aligned in parallell to the z-axis, corrected to soma."""
    R = pl.sqrt(
        (cell.xmid[segment1] - cell.xmid[segment2]) ** 2
        + (cell.ymid[segment1] - cell.ymid[segment2]) ** 2
        + (cell.zmid[segment1] - cell.zmid[segment2]) ** 2
    )

    rot_x = pl.pi + pl.arctan2(cell.ymid[segment1] - cell.ymid[segment2], cell.zmid[segment1] - cell.zmid[segment2])
    rot_y = -pl.pi + pl.arcsin((cell.xmid[segment1] - cell.xmid[segment2]) / R)

    rotation = {"x": rot_x, "y": rot_y}
    return rotation
コード例 #4
0
ファイル: LidarBase.py プロジェクト: jianxingdong/Velodyne-3
 def _matrix2State(self, R, T):
     '''
     calculate euler angle from rotation matrix
     and form the vector state from angle and w_T_L
     '''
     if R[2,0]!=1 or R[2,0]!=-1:
         pitch=-pl.arcsin(R[2,0])#another solution is pi-pitch
         roll=pl.arctan2(R[2,1]/cos(pitch), R[2,2]/cos(pitch))
         yaw=pl.arctan2(R[1,0]/cos(pitch), R[0,0]/cos(pitch))
     else:
         yaw=0
         if R[2,0]==-1:
             pitch=pi/2
             roll=yaw+pl.arctan2(R[0,1],R[0,2])
         else:
             pitch=-pi/2
             roll=-yaw+pl.arctan2(-R[0,1],-R[0,2])
     
     state = pl.array([T[0],T[1],T[2],roll*RAD2DEG,pitch*RAD2DEG,yaw*RAD2DEG])
             
     return state
コード例 #5
0
ファイル: TOPPopenravepy.py プロジェクト: quangounet/TOPP
def AnglesFromRot(R):
    # Hypothesis 1
    h2a = arcsin(R[0, 2])
    cos2 = cos(h2a)
    if abs(cos2) < 1e-8:
        cos2 += 1e-8
    h1a = arctan2(-R[1, 2] / cos2, R[2, 2] / cos2)
    h3a = arctan2(-R[0, 1] / cos2, R[0, 0] / cos2)
    # Hypothesis 2
    h2b = pi - h2a
    cos2 = cos(h2b)
    if abs(cos2) < 1e-8:
        cos2 += 1e-8
    h1b = arctan2(-R[1, 2] / cos2, R[2, 2] / cos2)
    h3b = arctan2(-R[0, 1] / cos2, R[0, 0] / cos2)
    # Testing
    resa = abs(sum(R - RotFromAngles([h1a, h2a, h3a])))
    resb = abs(sum(R - RotFromAngles([h1b, h2b, h3b])))
    if resa < resb:
        return [h1a, h2a, h3a]
    else:
        return [h1b, h2b, h3b]
コード例 #6
0
ファイル: create_route.py プロジェクト: ELSA-Project/ELSA-ABM
from collections import Counter 
import pylab as pl
import random as rd
import math as mt
from shapely.geometry import LineString

from igraph import *

from datetime import datetime,timedelta

gall = lambda x: [6371000.*pl.pi*x[1]/(180.*pl.sqrt(2)), 6371000.*pl.sqrt(2)*pl.sin(pl.pi*(x[0]/180.))]
invgall = lambda x: [(180./pl.pi)*pl.arcsin(x[1]/(6371000.*pl.sqrt(2))) , x[0]*180*pl.sqrt(2)/(6371000.*pl.pi)]
to_str = lambda x: str(x[0][0])+' '+str(x[0][1])
dist = lambda x: pl.sqrt( (x[0][0]-x[1][0])**2 + (x[0][1]-x[1][1])**2 )
to_coord = lambda z: gall([float(z.split(' ')[0]),float(z.split(' ')[1])])
pday = lambda x:  datetime.strftime(x,"%Y-%m-%d")

def select_heigths(th):
	coin=rd.choice(['up','down','both'])
	if coin=='up' : th.sort()
	if coin=='down': th.sort(reverse=True)
	if coin=='both':
		a=th[:len(th)/2]
		a.sort()
		b=th[len(th)/2:]
		b.sort(reverse=True)
		th=a+b
	return th

def rettifica(route,Eff,D,soglia):
コード例 #7
0
ファイル: sacm211.py プロジェクト: SDK/sacm
dec = float(source[source['target'] ==True]['dec'].unique()[0])

geo = pd.merge(antenna,station, left_on='stationId', right_on = 'stationId', how = 'inner')
geo['pos'] = geo.apply(lambda x: arrayParser(x['position'],1) , axis = 1 )
geo['lat'], geo['lon'], geo['alt'] = zip(*geo.apply(lambda x: gh.turn_xyz_into_llh(float(x.pos[0]),float(x.pos[1]),float(x.pos[2]), 'wgs84'),axis=1))
field['ra'],field['dec'] = zip(*field.apply(lambda x: arrayParser(x['referenceDir'],2)[0], axis = 1))


correctedList = list()
correctedList.append((ra,dec,0))
for i in pointing.query('go == True').rowNum.values:
    row  = rows[i]
    dRA,dDec = [[float(str(p[0]).replace('rad','').replace(',','.')),float(str(p[1]).replace('rad','').replace(',','.'))] for p in row.sourceOffset() ][row.numSample()/2]
    Pl = [pl.cos(dRA)*pl.cos(dDec), pl.sin(dRA)*pl.cos(dDec), pl.sin(dDec)]
    Ps = rot(Pl, ra, dec)
    correctedList.append((pl.arctan2(Ps[1], Ps[0]) % (2.*pl.pi),  pl.arcsin(Ps[2]), i))

correctedAll = pd.DataFrame(correctedList, columns=['ra','dec', 'row'])
corrected = correctedAll[['ra','dec']]
corrected['series'] = 'Corrected (Pointing)'

observed = field[field['target'] == True][['fieldId','ra','dec']]
observed.ra = observed.ra.astype(float)
observed.dec = observed.dec.astype(float)
observed = observed.loc[observed['fieldId'].isin(bar) ]
observed = observed.reset_index(drop=True)
corrected = corrected.drop_duplicates()
corrected = corrected.reset_index(drop=True)
cat = SkyCoord(observed.ra.values * u.rad, observed.dec.values * u.rad, frame='icrs')
cat2 = SkyCoord(corrected.ra.values * u.rad, corrected.dec.values *u.rad, frame='icrs')
match, separ, dist = cat2.match_to_catalog_sky(cat)
コード例 #8
0
ファイル: celestial.py プロジェクト: voneiden/ksp-toolkit
 def initFromStateVectors(self,epoch,pV,vV):
     self.epoch = epoch
     
     # 1) Calculate auxilary vector h
     hV = cross(pV,vV)
     
     
     # 2) Normalize position,velocity, specific angular momentum, calculate radial velocity 
     
     p = linalg.norm(pV)
     v = linalg.norm(vV)
     h = linalg.norm(hV)
     print "H:",h
     radv = pV.dot(vV) / p
     hVu = hV / h
     pVu = pV / p
     nV = cross(array([0,0,1]),hV)
     n = linalg.norm(nV)
     if n == 0:
         nVu = array([0,0,0])
     else:
         nVu = nV/n
     # 3) Calculate inclination
     #self.i = arccos(hV[2]/h)
     self.i = arcsin(linalg.norm(cross(array([0,0,1]),hVu)))
     print "i1",self.i
     print "RADVEL",radv
     self.i = arccos(array([0,0,1]).dot(hV)/h)
     #if radv < 0:
     #    self.i = PI2 - self.i 
     print "i2",self.i
     # 4) Calculate node line
     
     
     # 5) Calculate longitude of ascending node = right ascension of ascending node
     '''
     if self.i == 0:
         self.lan=0
     elif nV[1] >= 0:
         self.lan = arccos(nV[0] / n)
     else:
         self.lan = PI2 - arccos(nV[0] / n)
     '''
     
     if self.i == 0:
         self.lan = 0
     else:
         self.lan = arcsin(cross(array([1,0,0]),nVu).dot(array([0,0,1])))
         print "lan1",self.lan
         self.lan = arccos(array([1,0,0]).dot(nV)/n)
         if nV[1] < 0:
             self.lan = PI2-self.lan
         print "lan2",self.lan
     
     # 6) Eccentricity vector
     #eV = (1.0 / self.ref.mu)*((v**2 - (self.ref.mu / p))*pV - radv*vV)
     #eV2 = (1.0 / self.ref.mu) * ( hV - self.ref.mu * (pV/p))
     #eV3 = hV/self.ref.mu - (pV/p)
     
     # Source: cdeagle
     eV = cross(vV,hV)/self.ref.mu - pVu
     #print "eV1:",eV,linalg.norm(eV)
     #print "eV2:",eV2,linalg.norm(eV2)
     #print "eV3:",eV3,linalg.norm(eV3)
     print "eV3:",eV,linalg.norm(eV)
     self._e = linalg.norm(eV)
     #eVu = eV / self.e
     
     print "h",h
     print "u",self.ref.mu
     print "v",v
     print "r",p
     
     print "alte:",sqrt(1+(h**2/self.ref.mu**2)*(v**2-(2*self.ref.mu)/p)**2)
     # 7) Argument of perigree
     '''
     if self.e == 0:
         self.aop = 0
     elif self.i == 0:
       self.aop = arccos(eV[0] / self.e)  
     elif eV[2] >= 0:
         print "AOP AOP AOP"
         #self.aop = arccos(nV.dot(eV) / (n*self.e))
         print cross(nV,eV).dot(hV)
         self.aop = arcsin(cross(nVu,eVu).dot(hVu))
         #self.aop = arccos(n*self.e)
     else:
         self.aop = PI2 - arccos(nV.dot(eV) / (n*self.e))
     '''
     #CDEagle method
     # TODO CHECK how KSP handles this. 
     if self.e == 0:
         self.aop = 0
     elif self.i == 0 and self.e != 0:            
         #self.aop = arccos(eV[0] / self.e)
         #self.aop = arctan2(eV[1],eV[0])
         self.aop = arccos(array([1,0,0]).dot(eV) / self.e)
         print eV
         if eV[2] < 0:
             #self.aop = -self.aop
             self.aop = PI2-self.aop
         
         #print "BOOM",eV
         #if eV[2] < 0:
         #    print "BAM NIGGA"
         #    self.aop = PI2 - self.aop
     elif self.i == 0 and self.e == 0:
         #raise AttributeError("Perfectly circular orbits are not supported atm")
         self.aop = 0
     else:
         #self.aop = arcsin(cross(nVu,eVu).dot(hVu))
         self.aop = arccos(nV.dot(eV)/(n*self.e))
         if eV[2] < 0:
             self.aop = PI2-self.aop
     
     # 8) Semi major axis
     aE = v**2/2.0 - self.ref.mu / p
     self._a = -self.ref.mu / (2*aE)
     print "Old method for semi-major",self.a
     self._a = h**2 / (self.ref.mu * (1-self.e**2))
     print "New method for semi-major",self.a  
     #if self.e > 1:
     #    self._a = h**2 / (self.ref.mu * (self.e**2 - 1))
     
     if self.e == 0:
         if self.i == 0: #TODO update document to this
             print "JEA JEA JEA JEA"*10
             
             ta = arccos(array([1,0,0]).dot(pV) / p)
             if pV[1] < 0: # Vallado pg. 111
                 ta = PI2 - ta
         else: #TODO VERIFY THIS CASE
             ta = arccos((nV.dot(pV))/(n*p))
             if pV[2] < 0: # Vallado pg. 110
                 ta = PI2 - ta
         E = ta
         self.M0 = E
           
     elif self.e < 1:
         # 9) True anomaly, eccentric anomaly and mean anomaly
         if radv >= 0:
             ta = arccos((eV / self.e).dot(pV/p))
         else:
             ta = PI2 - arccos((eV / self.e).dot(pV/p))
         
         
         E = arccos((self.e+cos(ta))/(1+ self.e*cos(ta)))
         if radv < 0:
             E = PI2 - E
     
         self.M0 = E - self.e * sin(E)
         
     elif self.e > 1:
         # 9) Hyperbolic True anomaly, eccentric anomaly and mean anomaly
         # http://scienceworld.wolfram.com/physics/HyperbolicOrbit.html
         V = arccos((abs(self.a)*(self.e**2 - 1)) /(self.e * p) - 1/self.e)
         ta = arccos((eV / self.e).dot(pV/p))
         
         if radv < 0: #TODO: Should affect F too?
             # Negative = heading towards periapsis
             print "PI2"
             V = PI2 - V
             ta = PI2-ta
         print "V",V
         print "TA",ta
         # http://www.bogan.ca/orbits/kepler/orbteqtn.html In you I trust
         # Hyperbolic eccentric anomaly
         cosV = cos(V)
         F = arccosh((self.e+cosV)/(1+self.e*cosV))
         if radv < 0:
             F = -F
         F2 = arcsinh((sqrt(self.e-1)*sin(V))/(1+self.e*cos(V)))
         ##F1 = F2
         print "F1:",F
         print "F2:",F2
         self.M0 = self.e * sinh(F) - F
         
     
  
     
     
     self.h = h
     
     print "Semi-major:",self.a
     print "Eccentricity:",self.e
     print "Inclination:",degrees(self.i),"deg"
     print "LAN:",degrees(self.lan),"deg"
     print "AoP:",degrees(self.aop),"deg"
     print "Mean anomaly:",self.M0
     print "Specific angular momentum:",self.h
     if self.e < 1:
         print "Eccentric anomaly",E
         print "True anomaly",ta
     else:
         print "Hyperbolic eccentric anomaly",F
         print "Hyperbolic true anomaly",degrees(V)
         
     print "Distance from object:",p
     print "Velocity:",v
コード例 #9
0
 def calcCrossSectionNodes(self):
     '''
     @brief: find the (x,y) nodal locations in the tire cross section, where
         x is the longitudinal (forward), y is the lateral dirs.
     Appends:
         _OA_nodes: number of nodes in arc OA
         _th_incr: last rotation along arc OA
         _r_AB:  if set XYoffsets for AB, we'll be finding the radius,
         _phi0: the angle of the last node in the swept arc OA
         _AB_nodes: number of nodes in arc AB
         _phi_incr: increment of the sweep angle along arc AB
         _xOA, _yOA, _xAB, _yAB: the nodal locations
         
     '''
     w = self._w_tire
     ys = self._ds
     
     # *** OA ***
     OA_ymax = w/2.0  # how far in the y-dir does section OA extend?
     OA_rad = self._r_OA          # radius for OA curve
     OA_x_offset = self._r_tire - OA_rad    # if we change the radius of the circle swept, need
                                 # to move center of circle when finding coords
     OA_nodes = int(OA_ymax / ys) + 1
     self._OA_nodes = OA_nodes
     self._xOA = py.zeros((2,OA_nodes))
     self._yOA = py.zeros((2,OA_nodes))
     th = th_old = th_incr = 0.0    # rotation angle
     # just move each node over ys in the x-dir
     for i in range(0, OA_nodes):
         self._yOA[0,i] = ys * i     # right side of curve
         self._yOA[1,i] = -ys * i    # left side of curve
         th_old = th
         th = py.arcsin(ys*i / OA_rad)   # find theta based on y_i
         th_incr = th - th_old       # theta increment, this step
         self._xOA[0,i] = self._xOA[1,i] = OA_x_offset + OA_rad*py.cos(th) # x is also on the circle
     
     # keep the last th_incr, for plotting
     self._th_incr = th_incr
     # *** AB ***
     # this is how I usually do it, but use the input XY offset for AB instead
     if(self._useABoffset):
         # AB_y_off = w/2.0 / 2.0  # essentially the CM of circle that defines AB, use as offsets
         AB_y_off = self._AB_y_off            
         # AB_x_off = r - w/2.0
         AB_x_off = self._AB_x_off
         AB_rad = py.sqrt((self._yOA[0,OA_nodes-1]-AB_y_off)**2 + (self._xOA[0,OA_nodes-1]-AB_x_off)**2)  # new radius of curve to sweep, AB
         self._r_AB = AB_rad     # set the AB_rad, now that we know it
         phi0 = py.arcsin((self._yOA[0,OA_nodes-1]-AB_y_off) / AB_rad)
         self._phi0 = phi0
         arc_len = AB_rad*(self._sw_sweep_ang - phi0)
         AB_nodes = int( arc_len / ys )
         self._AB_nodes = AB_nodes
         self._xAB = py.zeros((2,AB_nodes))
         self._yAB = py.zeros((2,AB_nodes))
         # angle increment based on sweeping about 20% past 90 degrees from x-plane
         phi_incr = (self._sw_sweep_ang - phi0) / AB_nodes  
         self._phi_incr = phi_incr
         for j in range(0,AB_nodes):
             # don't re-do first node on arc, we're starting from last swept OA node
             phi_j = phi0 + (1+j)*phi_incr
             self._yAB[0,j] = AB_y_off + AB_rad * py.sin(phi_j)
             self._yAB[1,j] = -AB_y_off - AB_rad * py.sin(phi_j)
             self._xAB[0,j] = self._xAB[1,j] = AB_x_off + AB_rad * py.cos(phi_j)
     # I'll figure this out later
     else:
         arg = 2
コード例 #10
0
ファイル: lambert.py プロジェクト: voneiden/ksp-toolkit
def lambert(r1vec,r2vec,tf,m,muC):
# original documentation:
# ·············································
#
# This routine implements a new algorithm that solves Lambert's problem. The
# algorithm has two major characteristics that makes it favorable to other
# existing ones.
#
# 1) It describes the generic orbit solution of the boundary condition
# problem through the variable X=log(1+cos(alpha/2)). By doing so the
# graph of the time of flight become defined in the entire real axis and
# resembles a straight line. Convergence is granted within few iterations
# for all the possible geometries (except, of course, when the transfer
# angle is zero). When multiple revolutions are considered the variable is
# X=tan(cos(alpha/2)*pi/2).
#
# 2) Once the orbit has been determined in the plane, this routine
# evaluates the velocity vectors at the two points in a way that is not
# singular for the transfer angle approaching to pi (Lagrange coefficient
# based methods are numerically not well suited for this purpose).
#
# As a result Lambert's problem is solved (with multiple revolutions
# being accounted for) with the same computational effort for all
# possible geometries. The case of near 180 transfers is also solved
# efficiently.
#
#  We note here that even when the transfer angle is exactly equal to pi
# the algorithm does solve the problem in the plane (it finds X), but it
# is not able to evaluate the plane in which the orbit lies. A solution
# to this would be to provide the direction of the plane containing the
# transfer orbit from outside. This has not been implemented in this
# routine since such a direction would depend on which application the
# transfer is going to be used in.
#
# please report bugs to [email protected]    
#
# adjusted documentation:
# ·······················
#
# By default, the short-way solution is computed. The long way solution
# may be requested by giving a negative value to the corresponding
# time-of-flight [tf].
#
# For problems with |m| > 0, there are generally two solutions. By
# default, the right branch solution will be returned. The left branch
# may be requested by giving a negative value to the corresponding
# number of complete revolutions [m].

# Authors
# .·`·.·`·.·`·.·`·.·`·.·`·.·`·.·`·.·`·.·`·.·`·.·`·.·`·.·`·.·`·.
# Name       : Dr. Dario Izzo
# E-mail     : [email protected]
# Affiliation: ESA / Advanced Concepts Team (ACT)

# Made readible and optimized for speed by Rody P.S. Oldenhuis
# Code available in MGA.M on   http://www.esa.int/gsp/ACT/inf/op/globopt.htm

# last edited 12/Dec/2009

# ADJUSTED FOR EML-COMPILATION 24/Dec/2009
    
    # initial values        
    tol = 1e-12
    bad = False
    days = 1

    # work with non-dimensional units
    r1 = norm(r1vec) #sqrt(r1vec*r1vec.');  r1vec = r1vec/r1;
    r1vec = r1vec / r1
    r2vec = r2vec / r1
    
    V = sqrt(muC/r1)     
    T = r1/V              
    tf= tf*days/T # also transform to seconds

    # relevant geometry parameters (non dimensional)
    mr2vec = norm(r2vec)
    # make 100# sure it's in (-1 <= dth <= +1)
    dth = arccos( max(-1, min(1, (r1vec.dot(r2vec)/mr2vec))))  
    
        
    # decide whether to use the left or right branch (for multi-revolution
    # problems), and the long- or short way    
    leftbranch = sign(m)
    longway = sign(tf)
    m = abs(m)
    tf = abs(tf)
    if (longway < 0):
        dth = 2*pi - dth  

    # derived quantities        
    c      = sqrt(1.0 + mr2vec**2 - 2*mr2vec*cos(dth)) # non-dimensional chord
    s      = (1.0 + mr2vec + c)/2.0                    # non-dimensional semi-perimeter
    a_min  = s/2.0                              # minimum energy ellipse semi major axis
    Lambda = sqrt(mr2vec)*cos(dth/2.0)/s              # lambda parameter (from BATTIN's book)

    crossprd = cross(r1vec,r2vec)

    mcr       = norm(crossprd)           # magnitues thereof
    nrmunit   = crossprd/mcr                        # unit vector thereof
    
    # Initial values
    # ·························································

    # ELMEX requires this variable to be declared OUTSIDE the IF-statement
    logt = log(tf); # avoid re-computing the same value
    
    # single revolution (1 solution)
    if (m == 0):

        # initial values        
        inn1 = -0.5233      # first initial guess
        inn2 = +0.5233      # second initial guess
        x1   = log(1 + inn1)# transformed first initial guess
        x2   = log(1 + inn2)# transformed first second guess

        # multiple revolutions (0, 1 or 2 solutions)
        # the returned soltuion depends on the sign of [m]
    else:          
        # select initial values
        if (leftbranch < 0):
            inn1 = -0.5234 # first initial guess, left branch
            inn2 = -0.2234 # second initial guess, left branch
        else:
            inn1 = +0.7234 # first initial guess, right branch
            inn2 = +0.5234 # second initial guess, right branch
        x1 = tan(inn1*pi/2)# transformed first initial guess
        x2 = tan(inn2*pi/2)# transformed first second guess
    

    # since (inn1, inn2) < 0, initial estimate is always ellipse
    xx   = array([inn1, inn2])
    aa = a_min/(1 - xx**2)
    
    bbeta = longway * 2*arcsin(sqrt((s-c)/2./aa))
    # make 100.4% sure it's in (-1 <= xx <= +1)
    if xx[0] > 1: xx[0] = 1
    if xx[0] < -1: xx[0] = -1
    if xx[1] > 1: xx[1] = 1
    if xx[1] < -1: xx[1] = -1
    aalfa = 2*arccos( xx )

    # evaluate the time of flight via Lagrange expression
    y12  = aa*sqrt(aa)*((aalfa - sin(aalfa)) - (bbeta-sin(bbeta)) + 2*pi*m)

    # initial estimates for y
    if m == 0:
        y1 = log(y12[0]) - logt
        y2 = log(y12[1]) - logt
    else:
        y1 = y12[0] - tf
        y2 = y12[1] - tf
    

    # Solve for x
    # ·························································
    
    # Newton-Raphson iterations
    # NOTE - the number of iterations will go to infinity in case
    # m > 0  and there is no solution. Start the other routine in 
    # that case
    
    err = 1e99  
    iterations = 0
    xnew = 0
    while (err > tol):
        # increment number of iterations
        iterations += 1
        # new x
        xnew = (x1*y2 - y1*x2) / (y2-y1);
        # copy-pasted code (for performance)
        if m == 0:
            x = exp(xnew) - 1
        else:
            x = arctan(xnew)*2/pi
            
        a = a_min/(1 - x**2);
        if (x < 1): # ellipse
            beta = longway * 2*arcsin(sqrt((s-c)/2/a))
            # make 100.4% sure it's in (-1 <= xx <= +1)
            alfa = 2*arccos( max(-1, min(1, x)) )
        else: # hyperbola
            alfa = 2*arccosh(x);
            beta = longway * 2*arcsinh(sqrt((s-c)/(-2*a)))
        
        # evaluate the time of flight via Lagrange expression
        if (a > 0):
            tof = a*sqrt(a)*((alfa - sin(alfa)) - (beta-sin(beta)) + 2*pi*m)
        else:
            tof = -a*sqrt(-a)*((sinh(alfa) - alfa) - (sinh(beta) - beta))
        
        # new value of y
        if m ==0:
            ynew = log(tof) - logt
        else:
            ynew = tof - tf
        # save previous and current values for the next iterarion
        # (prevents getting stuck between two values)
        x1 = x2;  x2 = xnew;
        y1 = y2;  y2 = ynew;
        # update error
        err = abs(x1 - xnew);
        # escape clause
        if (iterations > 15):
            bad = True 
            break
    
    
  
    
    # If the Newton-Raphson scheme failed, try to solve the problem
    # with the other Lambert targeter. 
    if bad:
        # NOTE: use the original, UN-normalized quantities
        #[V1, V2, extremal_distances, exitflag] = ...
        #    lambert_high_LancasterBlanchard(r1vec*r1, r2vec*r1, longway*tf*T, leftbranch*m, muC);
        print "FAILZ0r"
        return
    
    
    # convert converged value of x
    if m==0:
        x = exp(xnew) - 1
    else:
        x = arctan(xnew)*2/pi
    
    #{
    #      The solution has been evaluated in terms of log(x+1) or tan(x*pi/2), we
    #      now need the conic. As for transfer angles near to pi the Lagrange-
    #      coefficients technique goes singular (dg approaches a zero/zero that is
    #      numerically bad) we here use a different technique for those cases. When
    #      the transfer angle is exactly equal to pi, then the ih unit vector is not
    #      determined. The remaining equations, though, are still valid.
    #}

    # Solution for the semi-major axis
    a = a_min/(1-x**2);

    # Calculate psi
    if (x < 1): # ellipse
        beta = longway * 2*arcsin(sqrt((s-c)/2/a))
        # make 100.4# sure it's in (-1 <= xx <= +1)
        alfa = 2*arccos( max(-1, min(1, x)) )
        psi  = (alfa-beta)/2
        eta2 = 2*a*sin(psi)**2/s
        eta  = sqrt(eta2);
    else:       # hyperbola
        beta = longway * 2*arcsinh(sqrt((c-s)/2/a))
        alfa = 2*arccosh(x)
        psi  = (alfa-beta)/2
        eta2 = -2*a*sinh(psi)**2/s
        eta  = sqrt(eta2)
    

    # unit of the normalized normal vector
    ih = longway * nrmunit;

    # unit vector for normalized [r2vec]
    r2n = r2vec/mr2vec;

    # cross-products
    # don't use cross() (emlmex() would try to compile it, and this way it
    # also does not create any additional overhead)
    #crsprd1 = [ih(2)*r1vec(3)-ih(3)*r1vec(2),...
    #           ih(3)*r1vec(1)-ih(1)*r1vec(3),...
    #           ih(1)*r1vec(2)-ih(2)*r1vec(1)];    
    crsprd1 = cross(ih,r1vec)
    #crsprd2 = [ih(2)*r2n(3)-ih(3)*r2n(2),...
    #           ih(3)*r2n(1)-ih(1)*r2n(3),...
    #           ih(1)*r2n(2)-ih(2)*r2n(1)];
    crsprd2 = cross(ih,r2n)

    # radial and tangential directions for departure velocity
    Vr1 = 1/eta/sqrt(a_min) * (2*Lambda*a_min - Lambda - x*eta)
    Vt1 = sqrt(mr2vec/a_min/eta2 * sin(dth/2)**2)

    # radial and tangential directions for arrival velocity
    Vt2 = Vt1/mr2vec
    Vr2 = (Vt1 - Vt2)/tan(dth/2) - Vr1
    
    # terminal velocities
    V1 = (Vr1*r1vec + Vt1*crsprd1)*V
    V2 = (Vr2*r2n + Vt2*crsprd2)*V
    
    # exitflag
    #exitflag = 1 # (success)
    #print "V1:",V1
    #print "V2:",V2
    return V1,V2
コード例 #11
0
ファイル: fixSACM211.py プロジェクト: SDK/sacm
    ra = float(groups[groups['target'] ==True]['ra'].unique()[0])
    if ra < 0:
        ra = ra * -1.
    dec = float(groups[groups['target'] ==True]['dec'].unique()[0])

    correctedList.append((ra,dec,0))
    for i in pointing.query('go == "%s"'%name).rowNum.values:
        row  = rows[i]
        dRA,dDec = [[p[0].get(),p[1].get()] for p in row.sourceOffset() ][row.numSample()/2]
    #    if dRA == 0. or dDec == 0.:
    #        print "no Offset positions in the Pointing Table"
    #        print "Is this EB a MultiSource?"
    #        sys.exit(1)
        Pl = [pl.cos(dRA)*pl.cos(dDec), pl.sin(dRA)*pl.cos(dDec), pl.sin(dDec)]
        Ps = rot(Pl, ra, dec)
        correctedList.append((pl.arctan2(Ps[1], Ps[0]) % (2.*pl.pi),  pl.arcsin(Ps[2]), i))

correctedAll = pd.DataFrame(correctedList, columns=['ra','dec', 'row'])
corrected = correctedAll[['ra','dec']]
corrected['series'] = 'Corrected (Pointing.bin)'
corrected = corrected.drop_duplicates()
corrected = corrected.reset_index(drop=True)

observed = field[field['target'] == True][['fieldId','ra','dec']]
observed.ra = observed.ra.astype(float)
observed.dec = observed.dec.astype(float)
observed['ra'] = observed.apply(lambda x: x['ra']*-1. if x['ra'] < 0.0 else x['ra'], axis = 1)
observed = observed.loc[observed['fieldId'].isin(fullbar) ]
observed = observed.reset_index(drop=True)
observed['series'] = 'Field.xml'
コード例 #12
0
ファイル: phot.py プロジェクト: jmint52/iancode
def lmcextinct(ra, dec, **kw):
    """Use the Zaritsky & Harris (ZH) map to get A_V extinction in the LMC.

    INPUT:
       ra  -- decimal degrees of right ascension
       dec -- decimal degrees of declination

    OPTIONAL INPUT:
       method='griddata'  /'nearest'  -- interpolation method
       map='both' /'hot'/'cool'       -- Which ZH map to use
       hot='lmc_hotav.fits'           -- filename of hot map
       cool='lmc_coolav.fits'         -- filename of cool map
       null=0.0                       -- "no data" value in map
       verbose=False / True           -- print out some spam and eggs

    EXAMPLE:
       ra = hms('05:51:56.6')
       dec = dms('-66:25:08.5')
       lmcextinct(ra, dec)
       
    If their map returns null, interpolate from the surroundings.

    Note that these calculations are definitely _not_ optimized.

    SEE ALSO:
       hms, dms"""

    # 2009-02-15 22:11 IJC: Created and tested.


    try:
        from astropy.io import fits as pyfits
    except:
        import pyfits
    
    from matplotlib.mlab import griddata
    from pylab import meshgrid, arange, array, sqrt, cos, sin, arctan2, arcsin

    ra = array([ra]).copy().ravel()
    dec = array([dec]).copy().ravel()

    defaults = dict(method='griddata', map='hot', hot='lmc_hotav_clean2.fits', 
                    cool='lmc_coolav.fits', null=0.0, verbose=False)

    for key in defaults:
        if (not kw.has_key(key)):
            kw[key] = defaults[key]
    
    if kw['map']=='both':
        kw['map'] = 'hot'
        ret1 = lmcextinct(ra, dec, **kw)
        kw['map'] = 'cool'
        ret2 = lmcextinct(ra, dec, **kw)
        return (ret1, ret2)
    else:
        map = kw[kw['map']]

    verbose = kw['verbose']

    avmap = pyfits.getdata(map)
    avhdr = pyfits.getheader(map)
    
    nx = avhdr['naxis1']
    ny = avhdr['naxis2']
    cx = avhdr['crpix1']
    cy = avhdr['crpix2']
    x0 = avhdr['crval1']
    y0 = avhdr['crval2']
    dx = avhdr['cd1_1']
    dy = avhdr['cd2_2']

    xx,yy = meshgrid(arange(nx),arange(ny))
    
    goodind = (avmap<>kw['null'])

    # I don't know how the following WCS calculation works, but it
    # does -- thank you, Calabretta & Greisen 2002!
    d2r = pi/180.

    phi = arctan2( xx-cx+1, yy-cy+1) + pi
    theta = arctan2(1./(d2r*dy), sqrt((yy-cy)**2 + (xx-cx)**2))
    mapdec = arcsin(sin(theta)*sin(y0*d2r) - cos(theta)*cos(phi)*cos(y0*d2r))/d2r
    mapra = arcsin(cos(theta) * sin(phi) / cos(mapdec*d2r))/d2r + x0

    if kw['method']=='griddata':
        ragood = mapra[goodind]
        decgood = mapdec[goodind]
        avgood = avmap[goodind]

    if verbose>0:
        print 'ra.shape>>' + str(ra.shape)
    
    # TBD: Vectorize this calculation; an interpolative solution
    # should exist.
    avlist = []
    for ii in range(len(ra)):
        if verbose>0:
            print 'ra, dec>>' + str((ra[ii], dec[ii]))
        if kw['method']=='nearest':
            distmap = (mapra-ra[ii])**2 + (mapdec-dec[ii])**2
            # If multiple values are equally near, average them:
            val = avmap[distmap==distmap.min()].mean()
            avlist.append(val)
        elif kw['method']=='griddata':
            avlist.append(griddata(ragood, decgood, avgood, array([ra[ii]]), array([dec[ii]])))
        else:
            print "Invalid method specified!"
            avlist.append(-1)
        
 
    return avlist
コード例 #13
0
 def asEuler(self):
     q1, q2, q3, q4 = self.q
     yaw = atan2(2*q2*q3-2*q1*q4, 2*q1*q1+2*q2*q2-1) ##Yaw, psi, Euler[0]     
     pitch = -arcsin(2*q2*q4+2*q1*q3)  ##Pitch, theta        
     roll = atan2(2*q3*q4-2*q1*q2, 2*q1*q1+2*q4*q4-1) ##Roll, phi
     return (roll, pitch, yaw)
コード例 #14
0
ファイル: myVisualisation.py プロジェクト: 6y6yKa/AHRS
 def asEuler(self): 
         qw, qx, qy, qz = self.q
         head = atan2(2*qy*qw-2*qx*qz, 1-2*qy*qy-2*qz*qz)  
         att = arcsin(2*qx*qy+2*qz*qw)
         bank = atan(2*qx*qw-2*qy*qz, 1-2*qx*qx-2*qz*qz)
         return (head, att, bank)
コード例 #15
0
def lossCone( fieldRatio = 2.0 ):
	return 1.0/pylab.arcsin( pylab.sqrt( fieldRatio ) )