Beispiel #1
0
def getStateVector(fileName):
    import orbitTools
    from scipy.interpolate import UnivariateSpline
    from scipy import interpolate
    import orbitProp as op
    import sys
    sys.path.append('../PythonScripts')
    import AtmosProfile as AP
    import matplotlib.pyplot as plt
    planetModel = 0

    omegaE = 2.*np.pi/(86164.0906)
    inputs = readInput(fileName)
    [lon0,lat0,h0] = inputs[0]
    thetag = inputs[10]
    ispList = inputs[9]
    
    [x0,y0,z0] = orbitTools.latlonalt2ECI(lat0,lon0,h0,thetag,planetModel)
    #SEZ2ECI(lat,lon,hs,Vsouth,Veast,Vzenith,inertial,thetag,planetModel)
    V0 = orbitTools.SEZ2ECI(lat0,lon0,h0,0,0,0,0,thetag,planetModel)
    Vx0 = V0[0]
    Vy0 = V0[1]
    Vz0 = V0[2]
    massList = inputs[1]
    m0Vec = massList[0]
    mfVec = massList[1]
    SrefList = inputs[2]
    MinfCDlist = inputs[3]
    CDList = inputs[4]
    atmosoption = inputs[5]
    atmoFile = inputs[6]
    timelist = inputs[7]
    thrustList = inputs[8]
    retTrajs = []
    #atmosoption = 2
    if atmosoption>0:
        print 'using given atmo data'
        altitudeList,densityMeanList,uMeanList,vMeanList,wMeanList,densitySDList,uSDList,vSDList,wSDList,nPoints= AP.readGramAtmos(atmoFile)
    else:
        
        altitudeList = [0]
        densityMeanList = [0]
        uMeanList = [0]
        vMeanList = [0]
        wMeanList = [0]
    
    densitylist = densityMeanList
    ulist = uMeanList
    vlist = vMeanList
    wlist = wMeanList
    dtinterval = inputs[12]
    
    cloption = 0
    cl = [0]
    loverd = 0
    minfcl = [1]
    geoptions = 1
    fileGE = 'trajProp'
    thrustoffangledeg =[0,0]
    mass_time_alt_opt = 1
    dtinterval = 0.01
    stateVectors = []
    for index in range(0,len(m0Vec)):
        mass = m0Vec[index]
        mf = mfVec[index]
        initialstate = [x0,y0,z0,Vx0,Vy0,Vz0]
        thrust = thrustList[index]
        Tx = thrust[0]
        Ty = thrust[1]
        Tz = thrust[2]

        timeVec = timelist[index]
        '''
        fTx = UnivariateSpline(timeVec,Tx)
        fTy = UnivariateSpline(timeVec,Ty)
        fTz = UnivariateSpline(timeVec,Tz)

        timeVec = np.linspace(timeVec[0],timeVec[-1],1000)
        Tx = fTx(timeVec)
        Ty = fTy(timeVec)
        Tz = fTz(timeVec)
        '''    
        cd0  = CDList[index]
        minfcd0 = MinfCDlist[index]
        sref = SrefList[index]
        fcd0 = UnivariateSpline(minfcd0,cd0)
        
        isp = ispList[index]
        
     
        minfcd = np.linspace(minfcd0[0],minfcd0[-1],100)
        cd = fcd0(minfcd)
        Tlist = np.array([Tx,Ty,Tz]).T#np.concatenate([[Tx],[Ty],[Tz]],axis=1)
      
        
        ndtinterval = int(np.ceil(2*timeVec[-1]/dtinterval))
        ntime = len(timeVec)
        #finalconditions,derivVals = op.propagate(initialstate,mass,mf,sref,minfcd,cd,cloption,minfcl,cl,loverd,atmosoption,altitudeList,densitylist,ulist,vlist,wlist,Tlist,timeVec,isp,geoptions,fileGE,planetModel,dtinterval,ndtinterval,thetag,1,ncd=len(minfcd),ncl=len(minfcl),ntime=ntime,nlist=len(altitudeList))
        
        #finalconditions,finalderivs = propagate(initialstate,mass,mass_time_alt_final,sref,minfcd,cd,cloption,minfcl,cl,loverd,atmosoption,altitudelist,densitylist,ulist,vlist,wlist,tlist,timelist,isp,geoptions,filename,planetmodel,dtinterval,ndtinterval,thetag,mass_time_alt_opt,thrustoffangledeg,ncd=len(minfcd),ncl=len(minfcl),ntime=shape(tlist,0),nlist=len(altitudelist))


        if index == len(m0Vec)-1:
            mass_time_alt_opt = 2
            fcond = timeVec[-1]
        else:
            fcond = mf
        finalconditions,finalderivs = op.propagate(initialstate,mass,fcond,sref,minfcd,cd,cloption,minfcl,cl,loverd,atmosoption,altitudeList,densitylist,ulist,vlist,wlist,Tlist,timeVec,isp,geoptions,fileGE+str(1+index),planetModel,dtinterval,ndtinterval,thetag,mass_time_alt_opt)
        
        newIndex = finalconditions[:,10]>=0.0
        newfinalConditions = finalconditions[newIndex,:]
        stateVectors.append(newfinalConditions)


        x0 = newfinalConditions[-1,0]
        y0 = newfinalConditions[-1,1]
        z0 = newfinalConditions[-1,2]
        Vx0 = newfinalConditions[-1,3]
        Vy0 = newfinalConditions[-1,4]
        Vz0 = newfinalConditions[-1,5]
        massCheck = newfinalConditions[-1,9]
        timeCheck = newfinalConditions[-1,7]
 
        thetag = thetag + omegaE*newfinalConditions[-1,10]
        retTrajs.append(newfinalConditions)
Beispiel #2
0
def generateRandomMultiTrajMalFunc(missionList,tLaunchDesired,dt,timeMalfunc,deltatfail,TOffset,ThrustOffsetAngDegMalFunc,atmProfile):
    # this function generates entire trajectories
    import numpy as np
    #calculating ECI coordinates for launch 
    import orbitTools # library for coordinate transformation
    import orbitProp as op # trajectory propagation routine
    import data2GE
    import copy
    
    
    if len(atmProfile)>0:
        atmosoption =1
        [altitudelist,densitylist,ulist,vlist,wlist] = atmProfile
    else:
        atmosoption = 0
        densitylist = [0]
        ulist = [0]
        vlist = [0]
        wlist = [0]
        altitudelist = [0]
    
    mission0 = missionList[0]# getting mission parameters for current mission
    omegaE = getAngVelEarth(mission0)# planet's angular velocity
    retList = []
    
    latitude,longitude,height = latlonaltFromMission(mission0)
    
    planetmodel = 0# 0 for Circ ...1 for ellipt
    trajList,thetag0 = interpolateTrajectories(missionList,tLaunchDesired,dt)
    
    r0 = orbitTools.latlonalt2ECI(latitude,longitude,height,thetag0,planetmodel)
    Rearth = getRfromMission(mission0)
    omega = getAngVelEarth(mission0)    
    
    nEvents = getNumberOfStages(mission0)
    cloption = 1
    cl = 0.
    minfcl = [1]
    loverd = 0.0
    
    geoptions = 0
    
    dtinterval = dt
    
    ndtinterval = 20000
    fileList = []
    currentTime = 0.0
    retList= []
    malFuncBool = False
    for indexEvent in range(nEvents):
        ThrustOffsetAngDeg= [0,0]#ThrustOffsetAngDegMalFunc

        if indexEvent ==0 : #first stage...setting initial conditions for rest of cases
            
            [vS0,vE0,vZ0] = [0,0,0] # initial velocity in SEZ frame
            inertial = 0
            thetag = copy.deepcopy(thetag0)
            # inertial = 1. input velocities are inertial velocities in SEZ frame
            # inertial =0. input velocities are local velocities (earth rotation not accounted)
            #Veci0 = orbitTools.SEZ2ECI(latitude,longitude,r0,vS0,vE0,vZ0,inertial,thetag)
            Veci0 = orbitTools.SEZ2ECI(latitude,longitude,height,vS0,vE0,vZ0,inertial,thetag,planetmodel)
            initialstate = np.array([r0[0],r0[1],r0[2],Veci0[0],Veci0[1],Veci0[2]])
        m0,Fmax,isp,minfcd,cd,sref = vehicleParamFromMission(mission0,indexEvent)
        massf = getFinalMassFromMission(mission0,indexEvent)# m0[-1]        
        Fmax = TOffset*Fmax
        etaMin = getEtaMinFromMission(mission0,indexEvent)
        filename = 'pTraj'+str(indexEvent)+'.txt'
        fileList.append(filename)
        if etaMin>=0:
            
            propOption = 1
            currTraj = trajList[indexEvent]
            [indexEvent,tfit,uxFit,uyFit,uzFit,etaFit] = currTraj
            # ensuring that unit vector is actually a unit vector (due to interpolation)
            
            uMag = (uxFit**2 + uyFit**2 + uzFit**2)**.5
            uxetaFit = np.array([etaFit*uxFit/uMag]).T
            uyetaFit = np.array([etaFit*uyFit/uMag]).T
            uzetaFit = np.array([etaFit*uzFit/uMag]).T
            uetaMat = np.concatenate((uxetaFit,uyetaFit,uzetaFit),1)
            Fmat = Fmax*uetaMat 
            timelist = tfit
            propCond = massf
            ntime = len(timelist)
            
            
            
            finalconditions,finalderivs = op.propagate(initialstate, m0, propCond,sref,minfcd,cd,cloption, minfcl,cl,loverd,atmosoption, altitudelist,densitylist,ulist,vlist ,wlist,Fmat,timelist,isp,geoptions,filename,planetmodel,dtinterval,ndtinterval,thetag,propOption,ThrustOffsetAngDeg,ncd=len(minfcd),ncl=len(minfcl),ntime=ntime,nlist=len(altitudelist))
            
            tfTemp = fixPropagateResultsGetTime(finalconditions)
            
            if timeMalfunc<=tfTemp[-1]:
   
                geoptions=0
                #print 'TOff',ThrustOffsetAngDegMalFunc
                finalconditions,finalderivs = malFunc.propagate(initialstate,m0,propCond,sref,minfcd,cd,cloption,minfcl,cl,loverd,atmosoption,altitudelist,densitylist,ulist,vlist,wlist,Fmat,timeMalfunc,deltatfail,timelist,isp,geoptions,filename,planetmodel,dtinterval,ndtinterval,thetag,propOption,ThrustOffsetAngDegMalFunc)
                malFuncBool = True
                
            xc,yc,zc,Vxc,Vyc,Vzc,mc,tc,newfinalConditions = fixPropagateResults(finalconditions)
            #print 'FC',newfinalConditions[-1]

            #print 'new',newfinalConditions[-1]
            # print 'tc',tc,currentTime


            tc = tc + currentTime
            initialstate = np.array([xc[-1],yc[-1],zc[-1],Vxc[-1],Vyc[-1],Vzc[-1]])
            mass0 = mc[-1]   
            
            currentTime = tc[-1] # updating time
            thetagVector = omegaE*tc + thetag0
            thetag = omegaE*currentTime + thetag0 # updating thetag for next event



        
        elif etaMin<0:
            
            propOption = 2
            currTraj = trajList[indexEvent]
            [indexEvent,tffit] = currTraj
            dtlocal = tffit/5.
            Tmax = 0.0
            uetaMat = np.array([[1,1,1]])
            Fmat = Fmax*uetaMat 
            timelist = [tffit]
            propCond = tffit
            ntime = len(timelist)
            
            
            
            finalconditions,finalderivs = op.propagate(initialstate, mass0, propCond,sref,minfcd,cd,cloption, minfcl,cl,loverd,atmosoption, altitudelist,densitylist,ulist,vlist ,wlist,Fmat,timelist,isp,geoptions,filename,planetmodel,dtlocal,ndtinterval,thetag,propOption,ThrustOffsetAngDeg,ncd=len(minfcd),ncl=len(minfcl),ntime=ntime,nlist=len(altitudelist))
            
            xc,yc,zc,Vxc,Vyc,Vzc,mc,tc,newfinalConditions = fixPropagateResults(finalconditions)
            tc = tc + currentTime
            
            
            mass0 = mc[-1]   
            currentTime = tc[-1] # updating time
            thetagVector = omegaE*tc + thetag0
            thetag = omegaE*currentTime + thetag0# updating thetag for next event
        
    
        

        retList.append([xc,yc,zc,Vxc,Vyc,Vzc,mc,tc,thetagVector,indexEvent])
        if malFuncBool==True:
            break

    return retList
Beispiel #3
0
def generateTraj(missionList,atmProfile,nProp):
    #import sys
    #sys.path.append('../../../safetyAssessmentTool/DebrisPropagation/SourceCode')
    
    import numpy as np
    import orbitProp as op
    from scipy.io import loadmat
    from scipy.interpolate import UnivariateSpline
    from scipy import interpolate
    import AtmosProfile as AP
    import data2GoogleEarth as GE
    import copy
    #import 
    
    altitudelist,densityMeanList,uMeanList,vMeanList,wMeanList,densitySDList,uSDList,vSDList,wSDList,nlist = atmProfile
    
    planetmodel = 0 # 0 for spherical planet
    
    #missionList = loadmat(trajectoryFile)['missionList']
    
    cloption = 1
    cl = 0.
    minfcl = [1]
    loverd = 0.0
    atmosoption = 2

    geoptions = 0
    dtinterval = 1 # [sec]
    indval = 0
    
    stages = getNumberOfStages(missionList[0])
    # iterating through each optimal trajectory
    retTrajs = [[0]*stages for i in range(len(missionList)*nProp)]
    #exit()
    for index in range(len(missionList)):
        
        filename = 'debrisTrash'+str(index)
        mission = missionList[index]# getting mission parameters for current mission
        omegaE = getAngVelEarth(mission)

        for randindex in range(nProp):
            stateVectors = []
            densitylist, ulist,vlist,wlist = AP.generateAtmosProfile(densityMeanList,uMeanList,vMeanList,wMeanList,densitySDList,uSDList,vSDList,wSDList)
            fileNameGE = 'TrajProp'+str(indval) + '.kml'
            indval = indval + 1
            for staging in range(stages):
                # setting initial condition

                if staging ==0: # working with first stage
                    xM,yM,zM,VxM,VyM,VzM,ux,uy,uz,timeM,mc,eta,thetag = nominalTrajFromMission(mission,staging)
                    initialstate = np.array([xM[0],yM[0],zM[0],VxM[0],VyM[0],VzM[0]])

                    offset =  1.0*np.random.uniform(.95,1.05)
                
                else : 
                    xM,yM,zM,VxM,VyM,VzM,ux,uy,uz,timeM,mc,eta,thetag = nominalTrajFromMission(mission,staging)

                    thetag = thetag + omegaE*t[-1]
                    offset = 1.0*np.random.uniform(.95,1.05)
                    initialstate = np.array([x[-1],y[-1],z[-1],Vx[-1],Vy[-1],Vz[-1]])

                mf = mc[-1]
                m0,Fmax,isp,minfcd,cd,sref = vehicleParamFromMission(mission,eventIndex)
                Fmax = Fmax*offset
            
                time = time - time[0] # shifting time
                timeVec = np.linspace(time0[0],time0[-1],1000) 
            
            
                fcd = UnivariateSpline(minfcd,cd)
                f*x = interpolate.interp1d(time,ux)
                fuy = interpolate.interp1d(time,uy)
                fuz = interpolate.interp1d(time,uz)
                feta = interpolate.interp1d(time,eta)
                
                uxN = f*x(timeVec)
                uyN = fuy(timeVec)
                uzN = fuz(timeVec)
                etaN = feta(timeVec)
                minfcdN = np.linspace(minfcd[0],minfcd[-1],100)
                cdN = fcd(minfcdN)
                Fx = np.array([Fmax*etaN*uxN]).T
                Fy = np.array([Fmax*etaN*uyN]).T
                Fz = np.array([Fmax*etaN*uzN]).T
                Farray = np.concatenate([Fx,Fy,Fz],axis=1)
                ndtinterval = int(np.ceil(2.*timelist[-1]/dtinterval))
                ntime = len(timelist)
                finalconditions,derivVals = op.propagate(initialstate,m0,mf,sref,minfcdN,cdN,cloption,minfcl,cl,loverd,atmosoption,altitudelist,densitylist,ulist,vlist,wlist,Farray,timelist,isp,geoptions,filename,planetmodel,dtinterval,ndtinterval,thetag,1,ncd=len(minfcd),ncl=len(minfcl),ntime=ntime,nlist=len(altitudelist))
                
                x,y,z,Vx,Vy,Vz,m,t,newfinalConditions = fixPropagateResults(finalconditions)
                stateVectors.append(newfinalConditions)
                retTrajs[indval-1][staging] = newfinalConditions

    return retTrajs
def generateRandomMultiTrajMalFunc(missionList,tLaunchDesired,dt,timeMalfunc,deltatfail,TOffset,ThrustOffsetAngDegMalFunc,atmProfile):
    # this function generates entire trajectories
    import numpy as np
    #calculating ECI coordinates for launch 
    import orbitTools # library for coordinate transformation
    import orbitProp as op # trajectory propagation routine
    import data2GE
    import copy
    
    
    if len(atmProfile)>0:
        atmosoption =1
        [altitudelist,densitylist,ulist,vlist,wlist] = atmProfile
    else:
        atmosoption = 0
        densitylist = [0]
        ulist = [0]
        vlist = [0]
        wlist = [0]
        altitudelist = [0]
    
    mission0 = missionList[0]# getting mission parameters for current mission
    omegaE = getAngVelEarth(mission0)# planet's angular velocity
    retList = []
    
    latitude,longitude,height = latlonaltFromMission(mission0)
    
    planetmodel = 0# 0 for Circ ...1 for ellipt
    trajList,thetag0 = interpolateTrajectories(missionList,tLaunchDesired,dt)
    
    r0 = orbitTools.latlonalt2ECI(latitude,longitude,height,thetag0,planetmodel)
    Rearth = getRfromMission(mission0)
    omega = getAngVelEarth(mission0)    
    
    nEvents = getNumberOfStages(mission0)
    cloption = 1
    cl = 0.
    minfcl = [1]
    loverd = 0.0
    
    geoptions = 0
    
    dtinterval = dt
    
    ndtinterval = 20000
    fileList = []
    currentTime = 0.0
    retList= []
    malFuncBool = False
    for indexEvent in range(nEvents):
        ThrustOffsetAngDeg= [0,0]#ThrustOffsetAngDegMalFunc

        if indexEvent ==0 : #first stage...setting initial conditions for rest of cases
            
            [vS0,vE0,vZ0] = [0,0,0] # initial velocity in SEZ frame
            inertial = 0
            thetag = copy.deepcopy(thetag0)
            # inertial = 1. input velocities are inertial velocities in SEZ frame
            # inertial =0. input velocities are local velocities (earth rotation not accounted)
            #Veci0 = orbitTools.SEZ2ECI(latitude,longitude,r0,vS0,vE0,vZ0,inertial,thetag)
            Veci0 = orbitTools.SEZ2ECI(latitude,longitude,height,vS0,vE0,vZ0,inertial,thetag,planetmodel)
            initialstate = np.array([r0[0],r0[1],r0[2],Veci0[0],Veci0[1],Veci0[2]])
        m0,Fmax,isp,minfcd,cd,sref = vehicleParamFromMission(mission0,indexEvent)
        massf = getFinalMassFromMission(mission0,indexEvent)# m0[-1]        
        Fmax = TOffset*Fmax
        etaMin = getEtaMinFromMission(mission0,indexEvent)
        filename = 'pTraj'+str(indexEvent)+'.txt'
        fileList.append(filename)
        if etaMin>=0:
            
            propOption = 1
            currTraj = trajList[indexEvent]
            [indexEvent,tfit,uxFit,uyFit,uzFit,etaFit] = currTraj
            # ensuring that unit vector is actually a unit vector (due to interpolation)
            
            uMag = (uxFit**2 + uyFit**2 + uzFit**2)**.5
            uxetaFit = np.array([etaFit*uxFit/uMag]).T
            uyetaFit = np.array([etaFit*uyFit/uMag]).T
            uzetaFit = np.array([etaFit*uzFit/uMag]).T
            uetaMat = np.concatenate((uxetaFit,uyetaFit,uzetaFit),1)
            Fmat = Fmax*uetaMat 
            timelist = tfit
            propCond = massf
            ntime = len(timelist)
            
            
            # letting vehicle propagate until propOption is reached (final mass from input parameter from SPOT!! not from propagated trajectory or desired time). 
            finalconditions,finalderivs = op.propagate(initialstate, m0, propCond,sref,minfcd,cd,cloption, minfcl,cl,loverd,atmosoption, altitudelist,densitylist,ulist,vlist ,wlist,Fmat,timelist,isp,geoptions,filename,planetmodel,dtinterval,ndtinterval,thetag,propOption,ThrustOffsetAngDeg,ncd=len(minfcd),ncl=len(minfcl),ntime=ntime,nlist=len(altitudelist))
            
            tfTemp = fixPropagateResultsGetTime(finalconditions)
        
            if (timeMalfunc - currentTime )<=tfTemp[-1]:
   
                geoptions=0
                #print 'TOff',ThrustOffsetAngDegMalFunc

                timeMalfuncLocal = timeMalfunc -currentTime
                finalconditions,finalderivs = malFunc.propagate(initialstate,m0,propCond,sref,minfcd,cd,cloption,minfcl,cl,loverd,atmosoption,altitudelist,densitylist,ulist,vlist,wlist,Fmat,timeMalfuncLocal,deltatfail,timelist,isp,geoptions,filename,planetmodel,dtinterval,ndtinterval,thetag,propOption,ThrustOffsetAngDegMalFunc)
                malFuncBool = True
                
            xc,yc,zc,Vxc,Vyc,Vzc,mc,tc,newfinalConditions = fixPropagateResults(finalconditions)
            #print 'FC',newfinalConditions[-1]

            #print 'new',newfinalConditions[-1]
            # print 'tc',tc,currentTime

            #print 'tc',tc[0],tc[-1]
            tc = tc + currentTime
            initialstate = np.array([xc[-1],yc[-1],zc[-1],Vxc[-1],Vyc[-1],Vzc[-1]])
            mass0 = mc[-1]   
            
            currentTime = tc[-1] # updating time
            #print 'Current',currentTime,tc[-1]
            thetagVector = omegaE*tc + thetag0
            thetag = omegaE*currentTime + thetag0 # updating thetag for next event



        
        elif etaMin<0:
            
            propOption = 2
            currTraj = trajList[indexEvent]
            [indexEvent,tffit] = currTraj
            dtlocal = tffit/5.
            Tmax = 0.0
            uetaMat = np.array([[1,1,1]])
            Fmat = Fmax*uetaMat 
            timelist = [tffit]
            propCond = tffit
            ntime = len(timelist)
            
            
            
            finalconditions,finalderivs = op.propagate(initialstate, mass0, propCond,sref,minfcd,cd,cloption, minfcl,cl,loverd,atmosoption, altitudelist,densitylist,ulist,vlist ,wlist,Fmat,timelist,isp,geoptions,filename,planetmodel,dtlocal,ndtinterval,thetag,propOption,ThrustOffsetAngDeg,ncd=len(minfcd),ncl=len(minfcl),ntime=ntime,nlist=len(altitudelist))
            
            xc,yc,zc,Vxc,Vyc,Vzc,mc,tc,newfinalConditions = fixPropagateResults(finalconditions)
            tc = tc + currentTime
            
            
            mass0 = mc[-1]   
            currentTime = tc[-1] # updating time
            thetagVector = omegaE*tc + thetag0
            thetag = omegaE*currentTime + thetag0# updating thetag for next event

    
        

        retList.append([xc,yc,zc,Vxc,Vyc,Vzc,mc,tc,thetagVector,indexEvent])
        if malFuncBool==True:
            break

    #print 'tt', timelist[-1],currentTime,timeMalfunc
    if (timelist[-1] + currentTime - tc[-1])< timeMalfunc:
        print 'Warning when propagating malfunction turns. Failure time seems to be greater than thrust profile time bounds' 
    return retList
def generateRandomMultiTraj(missionList,tLaunchDesired,dt,atmProfile=[],TOffset = 1.0,ThrustOffsetAngDeg=[0,0]):
    # this function generates entire trajectories
    import numpy as np
    #calculating ECI coordinates for launch 
    import orbitTools # library for coordinate transformation
    import orbitProp as op # trajectory propagation routine
    import data2GE
    import copy
    
    if len(atmProfile)>0:
        atmosoption =2
        [altitudelist,densitylist,ulist,vlist,wlist] = atmProfile
    else:
        atmosoption = 0
        densitylist = [0]
        ulist = [0]
        vlist = [0]
        wlist = [0]
        altitudelist = [0]
    
    mission0 = missionList[0]# getting mission parameters for current mission
    omegaE = getAngVelEarth(mission0)# planet's angular velocity
    retList = []
    
    latitude,longitude,height = latlonaltFromMission(mission0)

    planetmodel = 0# 0 for Circ ...1 for ellipt
    trajList,thetag0 = interpolateTrajectories(missionList,tLaunchDesired,dt)
    
    r0 = orbitTools.latlonalt2ECI(latitude,longitude,height,thetag0,planetmodel)
    Rearth = getRfromMission(mission0)
    omega = getAngVelEarth(mission0)    

    nEvents = getNumberOfStages(mission0)
    cloption = 1
    cl = 0.
    minfcl = [1]
    loverd = 0.0
    
    geoptions = 0
    
    dtinterval = dt
    
    ndtinterval = 20000
    fileList = []
    currentTime = 0.0
    retList= []
    for indexEvent in range(nEvents):
        if indexEvent ==0 : #first stage...setting initial conditions for rest of cases
            
            [vS0,vE0,vZ0] = [0,0,0] # initial velocity in SEZ frame
            inertial = 0
            thetag = copy.deepcopy(thetag0)
            # inertial = 1. input velocities are inertial velocities in SEZ frame
            # inertial =0. input velocities are local velocities (earth rotation not accounted)
            #Veci0 = orbitTools.SEZ2ECI(latitude,longitude,r0,vS0,vE0,vZ0,inertial,thetag)
            Veci0 = orbitTools.SEZ2ECI(latitude,longitude,height,vS0,vE0,vZ0,inertial,thetag,planetmodel)
            initialstate = np.array([r0[0],r0[1],r0[2],Veci0[0],Veci0[1],Veci0[2]])
        m0,Fmax,isp,minfcd,cd,sref = vehicleParamFromMission(mission0,indexEvent)
        
        massf = getFinalMassFromMission(mission0,indexEvent)# m0[-1]        
        Fmax = TOffset*Fmax
        etaMin = getEtaMinFromMission(mission0,indexEvent)
        filename = 'pTraj'+str(indexEvent)+'.txt'
        fileList.append(filename)
        if etaMin>=0:
            
            propOption = 1
            currTraj = trajList[indexEvent]
            [indexEvent,tfit,uxFit,uyFit,uzFit,etaFit] = currTraj
            # ensuring that unit vector is actually a unit vector (due to interpolation)
          
            uMag = (uxFit**2 + uyFit**2 + uzFit**2)**.5
            uxetaFit = np.array([etaFit*uxFit/uMag]).T
            uyetaFit = np.array([etaFit*uyFit/uMag]).T
            uzetaFit = np.array([etaFit*uzFit/uMag]).T
            uetaMat = np.concatenate((uxetaFit,uyetaFit,uzetaFit),1)
            Fmat = Fmax*uetaMat 
            timelist = tfit
            propCond = massf
            ntime = len(timelist)
            

            
            
            finalconditions,finalderivs = op.propagate(initialstate, m0, propCond,sref,minfcd,cd,cloption, minfcl,cl,loverd,atmosoption, altitudelist,densitylist,ulist,vlist ,wlist,Fmat,timelist,isp,geoptions,filename,planetmodel,dtinterval,ndtinterval,thetag,propOption,ThrustOffsetAngDeg,ncd=len(minfcd),ncl=len(minfcl),ntime=ntime,nlist=len(altitudelist))
            newIndex = finalconditions[:,10]>=0.0
            newfinalConditions = finalconditions[newIndex,:]
            # updating parameters for propagation in next stage
            xc = newfinalConditions[:,0]
            yc = newfinalConditions[:,1]
            zc = newfinalConditions[:,2]
            Vxc = newfinalConditions[:,3]
            Vyc = newfinalConditions[:,4]
            Vzc = newfinalConditions[:,5]      
            mc = newfinalConditions[:,9]
            tc = newfinalConditions[:,10] + currentTime
            initialstate = np.array([xc[-1],yc[-1],zc[-1],Vxc[-1],Vyc[-1],Vzc[-1]])
            mass0 = mc[-1]   
            
            currentTime = tc[-1] # updating time
            thetagVector = omegaE*tc + thetag0
            thetag = omegaE*currentTime + thetag0 # updating thetag for next event
        
        elif etaMin<0:
            
            propOption = 2
            currTraj = trajList[indexEvent]
            [indexEvent,tffit] = currTraj
            dtlocal = tffit/5.
            Tmax = 0.0
            uetaMat = np.array([[1,1,1]])
            Fmat = Fmax*uetaMat 
            timelist = [tffit]
            propCond = tffit
            ntime = len(timelist)
            
            
            
            finalconditions,finalderivs = op.propagate(initialstate, mass0, propCond,sref,minfcd,cd,cloption, minfcl,cl,loverd,atmosoption, altitudelist,densitylist,ulist,vlist ,wlist,Fmat,timelist,isp,geoptions,filename,planetmodel,dtlocal,ndtinterval,thetag,propOption,ThrustOffsetAngDeg,ncd=len(minfcd),ncl=len(minfcl),ntime=ntime,nlist=len(altitudelist))
            
            xc,yc,zc,Vxc,Vyc,Vzc,mc,tc,newfinalConditions = fixPropagateResults(finalconditions)
            
            tc = tc + currentTime


            mass0 = mc[-1]   
            currentTime = tc[-1] # updating time
            thetagVector = omegaE*tc + thetag0
            thetag = omegaE*currentTime + thetag0# updating thetag for next event
        
        retList.append([xc,yc,zc,Vxc,Vyc,Vzc,mc,tc,thetagVector,indexEvent])
    return retList
def generateTraj(missionList,atmProfile,nProp):
    #import sys
    #sys.path.append('../../../safetyAssessmentTool/DebrisPropagation/SourceCode')
    
    import numpy as np
    import orbitProp as op
    from scipy.io import loadmat
    from scipy.interpolate import UnivariateSpline
    from scipy import interpolate
    import AtmosProfile as AP
    import data2GoogleEarth as GE
    import copy
    #import 
    
    altitudelist,densityMeanList,uMeanList,vMeanList,wMeanList,densitySDList,uSDList,vSDList,wSDList,nlist = atmProfile
    
    planetmodel = 0 # 0 for spherical planet
    
    #missionList = loadmat(trajectoryFile)['missionList']
    
    cloption = 1
    cl = 0.
    minfcl = [1]
    loverd = 0.0
    atmosoption = 2

    geoptions = 0
    dtinterval = 1 # [sec]
    indval = 0
    
    stages = getNumberOfStages(missionList[0])
    # iterating through each optimal trajectory
    retTrajs = [[0]*stages for i in range(len(missionList)*nProp)]
    #exit()
    for index in range(len(missionList)):
        
        filename = 'debrisTrash'+str(index)
        mission = missionList[index]# getting mission parameters for current mission
        omegaE = getAngVelEarth(mission)

        for randindex in range(nProp):
            stateVectors = []
            densitylist, ulist,vlist,wlist = AP.generateAtmosProfile(densityMeanList,uMeanList,vMeanList,wMeanList,densitySDList,uSDList,vSDList,wSDList)
            fileNameGE = 'TrajProp'+str(indval) + '.kml'
            indval = indval + 1
            for staging in range(stages):
                # setting initial condition

                if staging ==0: # working with first stage
                    xM,yM,zM,VxM,VyM,VzM,ux,uy,uz,timeM,mc,eta,thetag = nominalTrajFromMission(mission,staging)
                    initialstate = np.array([xM[0],yM[0],zM[0],VxM[0],VyM[0],VzM[0]])

                    offset =  1.0*np.random.uniform(.95,1.05)
                
                else : 
                    xM,yM,zM,VxM,VyM,VzM,ux,uy,uz,timeM,mc,eta,thetag = nominalTrajFromMission(mission,staging)

                    thetag = thetag + omegaE*t[-1]
                    offset = 1.0*np.random.uniform(.95,1.05)
                    initialstate = np.array([x[-1],y[-1],z[-1],Vx[-1],Vy[-1],Vz[-1]])

                mf = mc[-1]
                m0,Fmax,isp,minfcd,cd,sref = vehicleParamFromMission(mission,eventIndex)
                Fmax = Fmax*offset
            
                time = time - time[0] # shifting time
                timeVec = np.linspace(time0[0],time0[-1],1000) 
            
            
                fcd = UnivariateSpline(minfcd,cd)
                f*x = interpolate.interp1d(time,ux)
                fuy = interpolate.interp1d(time,uy)
                fuz = interpolate.interp1d(time,uz)
                feta = interpolate.interp1d(time,eta)
                
                uxN = f*x(timeVec)
                uyN = fuy(timeVec)
                uzN = fuz(timeVec)
                etaN = feta(timeVec)
                minfcdN = np.linspace(minfcd[0],minfcd[-1],100)
                cdN = fcd(minfcdN)
                Fx = np.array([Fmax*etaN*uxN]).T
                Fy = np.array([Fmax*etaN*uyN]).T
                Fz = np.array([Fmax*etaN*uzN]).T
                Farray = np.concatenate([Fx,Fy,Fz],axis=1)
                ndtinterval = int(np.ceil(2.*timelist[-1]/dtinterval))
                ntime = len(timelist)
                finalconditions,derivVals = op.propagate(initialstate,m0,mf,sref,minfcdN,cdN,cloption,minfcl,cl,loverd,atmosoption,altitudelist,densitylist,ulist,vlist,wlist,Farray,timelist,isp,geoptions,filename,planetmodel,dtinterval,ndtinterval,thetag,1,ncd=len(minfcd),ncl=len(minfcl),ntime=ntime,nlist=len(altitudelist))
                
                x,y,z,Vx,Vy,Vz,m,t,newfinalConditions = fixPropagateResults(finalconditions)
                stateVectors.append(newfinalConditions)
                retTrajs[indval-1][staging] = newfinalConditions

    return retTrajs