Esempio n. 1
0
def geomag_lat(alt, start_time, conv_module):
    ''' Calculates the geomagnetic lattitude data at the given alt (altitude) 
        and start_time. This function uses either Spacepy or aacgmv2 to convert 
        between geographic and geomagnetic coordinates. The moduel used to 
        convert coordinates can be selected by setting the conv_module. Make
        sure to use all lowercase for converting module. Keep in mind SpacePy 
        for some reason is not able to use 2020 data. '''
    arr = np.zeros((181, 360))
    geo_lat = np.zeros((5, 360))
    for j in range(360):
        for i in range(181):
            # Altitude is given in meters but Spacepy uses kilometers.
            coordinates = coords.Coords([alt / 1000, i - 90, j - 180], \
                                'GEO', 'sph')
            # For some reason, 2020 data could not be used.
            if conv_module == 'spacepy':
                coordinates.ticks = Ticktock(['2019-07-17T17:51:15'], 'ISO')
                arr[i][j] = coordinates.convert('MAG', 'sph').lati
            elif conv_module == 'aacgmv2':
                arr[i][j] = (np.array(aacgmv2.get_aacgm_coord(i - 90, j - 180,\
                    int(alt / 1000), start_time)))[0]
            else:
                print("Error: coordinate conversion module is invalid.\n\
                    Please choose between:\n  spacepy\n  aacgmv2\n\
                    Please use all lowercase.")
                exit()
    for j in range(360):
        for i in range(5):
            geo_lat[i, j] = closest(arr[:, j], 30 * i - 60) - 90
    return geo_lat
Esempio n. 2
0
def calc_Lvals(year):

    counts_file = "/home/wyatt/Documents/SAMPEX/bounce/correlation/data/accepted_" + str(
        year) + ".csv"
    times = pd.read_csv(counts_file,
                        header=None,
                        names=["Burst", "Time"],
                        usecols=[0, 1])
    times['Time'] = pd.to_datetime(times['Time'])
    times = times.set_index('Burst')
    irb_L_list = []
    samp_L_list = []
    indices = times.index.drop_duplicates()
    for ind in indices:
        print(ind)
        start = times.loc[ind].iloc[0]["Time"]
        end = times.loc[ind].iloc[-1]["Time"]
        dataObj = sp.OrbitData(date=start)
        orbitInfo = dataObj.read_time_range(
            pd.to_datetime(start),
            pd.to_datetime(end),
            parameters=['GEI_X', 'GEI_Y', 'GEI_Z', 'L_Shell'])

        X = (orbitInfo['GEI_X'].to_numpy() / Re)[0]
        Y = (orbitInfo['GEI_Y'].to_numpy() / Re)[0]
        Z = (orbitInfo['GEI_Z'].to_numpy() / Re)[0]
        position = np.array([X, Y, Z])
        ticks = Ticktock(start)
        coords = spc.Coords(position, 'GEI', 'car')
        irb_Lstar = irb.get_Lstar(ticks, coords, extMag=magField)
        irb_Lstar = irb_Lstar['Lm'][0]
        samp_Lstar = orbitInfo['L_Shell'].to_numpy()[0]
        irb_L_list.append(irb_Lstar[0])
        samp_L_list.append(samp_Lstar)
    return irb_L_list, samp_L_list
Esempio n. 3
0
 def test_coords(self):
     """Coords should create and do simple conversions"""
     np.testing.assert_equal([1,1], self.cvals.x)
     np.testing.assert_equal([2,2], self.cvals.y)
     np.testing.assert_equal([4,2], self.cvals.z)
     self.cvals.ticks = Ticktock(['2002-02-02T12:00:00', '2002-02-02T12:00:00'], 'ISO') # add ticktock
     newcoord = self.cvals.convert('GSM', 'sph')
Esempio n. 4
0
    def _bounce_period(self, times, energy=1):
        """
        calculates electron bounce period at edge of loss cone
        energy in MeV
        """
        start = times[0]
        end = times[-1]
        dataObj = sp.OrbitData(date=start)
        orbitInfo = dataObj.read_time_range(
            pd.to_datetime(start),
            pd.to_datetime(end),
            parameters=['GEI_X', 'GEI_Y', 'GEI_Z', 'L_Shell', 'GEO_Lat'])

        X = (orbitInfo['GEI_X'].to_numpy() / self.Re)[0]
        Y = (orbitInfo['GEI_Y'].to_numpy() / self.Re)[0]
        Z = (orbitInfo['GEI_Z'].to_numpy() / self.Re)[0]
        position = np.array([X, Y, Z])
        ticks = Ticktock(times[0])
        coords = spc.Coords(position, 'GEI', 'car')

        #something bad is happening with IRBEM, the L values are crazy for a lot of
        #these places, so for now I'll use sampex's provided L vals
        Lstar = irb.get_Lstar(ticks, coords, extMag='0')
        Lstar = abs(Lstar['Lm'][0])

        # Lstar = orbitInfo['L_Shell'].to_numpy()[0]
        self.Lstar = Lstar
        loss_cone = self._find_loss_cone(coords, ticks)  #in degrees
        period = 5.62 * 10**(-2) * Lstar / np.sqrt(energy) * (
            1 - .43 * np.sin(np.deg2rad(loss_cone)))
        return period[0]
Esempio n. 5
0
def geotomag(lat,lon,alt,plot_date):
    #call with altitude in kilometers and lat/lon in degrees 
    Re=6371.0 #mean Earth radius in kilometers
    #setup the geographic coordinate object with altitude in earth radii 
    cvals = coord.Coords([np.float(alt+Re)/Re, np.float(lat), np.float(lon)], 'GEO', 'sph',['Re','deg','deg'])
    #set time epoch for coordinates:
    cvals.ticks=Ticktock([plot_date.isoformat()], 'ISO')
    #return the magnetic coords in the same units as the geographic:
    return cvals.convert('MAG','sph')
Esempio n. 6
0
def GSE2GSM(year, month, day, hour, min, sec, GSE_XYZ):
    # 功能:GSM坐标系->GSE坐标系
    coord = Coords(GSE_XYZ, 'GSE', 'car')
    date_time = datetime.datetime(year, month, day, hour, min, sec)
    date_time_str = date_time.strftime('%Y-%m-%dT%H:%M:%S')
    coord.ticks = Ticktock(date_time_str, 'ISO')
    coord_new = coord.convert('GSM', 'car')
    GSM_XYZ = coord_new.data[0]
    return GSM_XYZ
Esempio n. 7
0
    def test_to_skycoord_with_ticks(self):
        self.cvals.ticks = Ticktock(['2002-02-02T12:00:00', '2002-02-02T12:00:00'], 'ISO') # add ticktock

        sc = self.cvals.to_skycoord()

        assert isinstance(sc, astropy.coordinates.SkyCoord)
        assert sc.frame.name == 'itrs'

        # Check that the data was loaded correctly
        sc_data = sc.cartesian.xyz.to('m').value.T
        np.testing.assert_allclose(sc_data, self.cvals.data * self.cvals.Re, rtol=1e-10)

        # Check that the time was loaded correctly
        np.testing.assert_allclose((sc.obstime - self.cvals.ticks.APT).to('s').value, 0)
Esempio n. 8
0
    def test_to_skycoord_with_ticks_and_conversion(self):
        self.cvals.ticks = Ticktock(['2002-02-02T12:00:00', '2002-02-02T12:00:00'], 'ISO') # add ticktock

        # Convert to a frame other than GEO before calling to_skycoord()
        non_geo = self.cvals.convert('GSE', 'sph')

        sc = non_geo.to_skycoord()

        assert isinstance(sc, astropy.coordinates.SkyCoord)
        assert sc.frame.name == 'itrs'

        # Check that the data converts back correctly
        sc_data = sc.cartesian.xyz.to('m').value.T
        np.testing.assert_allclose(sc_data, self.cvals.data * self.cvals.Re, rtol=1e-10)

        # Check that the time was loaded correctly
        np.testing.assert_allclose((sc.obstime - self.cvals.ticks.APT).to('s').value, 0)
Esempio n. 9
0
def getSmOrbit():
    """
    reads in the x,y,z coordinates (originally in GSE)
    converts them to x,y,z in SM
    """
    # df = pd.read_csv('01_Jan_2019.csv')
    df = pd.read_csv('oct_65_2019.csv')
    t = df['DefaultSC.A1ModJulian'] + 29999.5
    x = df['DefaultSC.gse.X']
    y = df['DefaultSC.gse.Y']
    z = df['DefaultSC.gse.Z']
    cvals = coord.Coords([[i, j, k] for i, j, k in zip(x, y, z)], 'GSE', 'car')

    # okay so the correct "ticks" are getting set
    cvals.ticks = Ticktock(t, 'MJD')
    sm = cvals.convert('SM', 'car')
    return sm
Esempio n. 10
0
def ComputeLshell(inTime, c1, c2, c3, inCoordName, inCoordType):
    """
    This function uses spacepy to compute L shell and MLT from given time and position values.
    It uses the IRBEM library to do the calculations.
    
    INPUTS:
    inTime:       array:  time in UTC timestamp
    c1:           array:  x, alt
    c2:           array:  y, lat
    c3:           array:  z, lon
    inCoordName:  string: GDZ, GEO, GSM, GSE, SM, GEI, MAG, SPH, RLL
    inCoordType:  string: car, sph
    
    OUTPUT:
    c1:       array:  Lm
    c2:       array:  Lstar
    c3:       array:  MLT
    """

    # Start timer
    tic = time.perf_counter()
    #print("Starting ...")

    #pack position arrays in desired format
    sat_track = [[c1[i], c2[i], c3[i]] for i in range(len(c1))]

    #convert utc_ts to spacepy time strings
    @np.vectorize
    def ts_to_spacepystr(ts):
        return dt.strftime(dt.utcfromtimestamp(int(ts)), '%Y-%m-%dT%H:%M:%S')

    #perform coordinate conversion
    cvals = Coords(sat_track, inCoordName, inCoordType)
    tt = Ticktock(ts_to_spacepystr(inTime), 'ISO')

    qq = get_Lstar(tt, cvals)
    Lm = abs(np.reshape(qq['Lm'], -1))
    Lstar = abs(np.reshape(qq['Lstar'], -1))
    MLT = qq['MLT']

    toc = time.perf_counter()
    print('Computed Lm,lstar,MLT in', "{:0.4f}".format(toc - tic),
          'seconds for', len(inTime), ' positions.')

    return Lm, Lstar, MLT
Esempio n. 11
0
                ZGSE = np.zeros(1440)
                for igp in range(1440):
                    # next step here is to do this all in pandas
                    ctime = rng[ic]
                    year = ctime.year
                    day = dt1.timetuple()[7]  # day number in year
                    hour = ctime.hour
                    minute = ctime.minute
                    second = ctime.second
                    # now apply each coordinate system

                    cvals = coord.Coords([[GEOX[igp], GEOY[igp], GEOZ[igp]]],
                                         'GEO', 'car')
                    bcvals = coord.Coords(
                        [[GEOBx[igp], GEOBy[igp], GEOBz[igp]]], 'GEO', 'car')
                    cvals.ticks = Ticktock([ctime], 'UTC')
                    bcvals.ticks = Ticktock([ctime], 'UTC')
                    new_coord = cvals.convert(desired_coords[ic], 'car')
                    newB_coord = bcvals.convert(desired_coords[ic], 'car')
                    XGSE[igp] = new_coord.x
                    YGSE[igp] = new_coord.y
                    ZGSE[igp] = new_coord.z
                    Bx[igp] = newB_coord.x
                    By[igp] = newB_coord.y
                    Bz[igp] = newB_coord.z

            #
            # now we have the interpolated pressures... get the Kp, L, and MLT
            # from HOPE Ephemeris
            #
            os.chdir('/Users/loisks/Desktop/liemohn10/loisks/EMPHEMERIS_' +
Esempio n. 12
0
cols = ['Rate1', 'Rate2', 'Rate3', 'Rate4', 'GEI_X', 'GEI_Y', 'GEI_Z', 'A11', 'A21', 'A31', 'A12', 'A22', 'A32', 'A13', 'A23', 'A33']

data = pd.read_csv('/home/wyatt/Documents/SAMPEX/generated_Data/burst_Jan93.csv',header=None,index_col=0,names=cols)
data2 = pd.read_csv('/home/wyatt/Documents/SAMPEX/generated_Data/burst_Feb93.csv',header=None,index_col=0,names=cols)
data3 = pd.read_csv('/home/wyatt/Documents/SAMPEX/generated_Data/burst_Mar93.csv',header=None,index_col=0,names=cols)
data = data.append(data2)
data = data.append(data3)
data = data.loc[~data.index.duplicated(keep='first')]
length = len(data.index.values)
times = data.index
print(length)
X = data['GEI_X'].to_numpy() / Re
Y = data['GEI_Y'].to_numpy() / Re
Z = data['GEI_Z'].to_numpy() / Re
position = np.stack((X,Y,Z),axis=1)
ticks = Ticktock(times)
coords = spc.Coords(position,'GEI','car')

#find B based on position
bField = irb.get_Bfield(ticks,coords,extMag='T89')
Field_GEO = bField['Bvec'] #b field comes out in xyz
#convert to GEIcar, because the direction cosines take GEI to body fixed
Field_GEO_coords = spc.Coords(Field_GEO,'GEO','car')
Field_GEO_coords.ticks = Ticktock(times)
Field_GEI = irb.coord_trans(Field_GEO_coords,'GEI','car')
Field_Mag = bField['Blocal']
#rotate b to body fixed
BX = Field_GEI[:,0]
BY = Field_GEI[:,1]
BZ = Field_GEI[:,2]
Esempio n. 13
0
freqs    = np.array([1000, 1100]) 

inp_w = 2.0*np.pi*freqs


lats, lons, ws = np.meshgrid(inp_lats, inp_lons, inp_w)
lats = lats.flatten()
lons = lons.flatten()
ws   = ws.flatten()
alts = launch_alt*np.ones_like(lats)


# Create spacepy coordinate structures
inp_coords = coord.Coords(zip(alts, lats, lons), 'GEO', 'sph', units=['m','deg','deg'])
inp_coords.ticks = Ticktock(np.tile(ray_datenum, len(inp_coords))) # add ticks

# Write ray header file (for WIPP code):
# Should I really be doing this here? Feels a little sloppy but oh well
# Format is:
# H (index) (yr) (day of year) (sec in day) (radius) (lat) (lon) (ang. frequency)
f = open(ray_header, 'w+')
for ind, (pos0, w0) in enumerate(zip(inp_coords.data, ws)):
    f.write('H %d %d %d %d %d %d %d %d\n'%(ind + 1, ray_datenum.year, ray_datenum.timetuple().tm_yday, milliseconds_day*1e-3,
                                        pos0[0], pos0[1], pos0[2], w0))



# Rotate to SM cartesian coordinates
inp_coords = inp_coords.convert('SM','car')
N = len(inp_coords)
Esempio n. 14
0
def Plot4Dcar(variable_name, sat_time, sat_lat, sat_lon, sat_z, result, result_units, 
           plot_file, sat_zunits='km', plot_close=True, plot_sampling=4000):
    '''make a 3D heat map of result in cartesian coords, with same time-series plots'''
    
    from spacepy import coordinates as coord
    from spacepy.time import Ticktock
    from astropy.constants import R_earth
    

    #turn off interactive commands based on backend in use
    if mpl.get_backend() in ['agg','pdf','ps','svg','pgf','cairo']:
        int_off = True
        plt.ioff()  
        #print('non-interactive mode ', mpl.get_backend())
    else:
        int_off = False
        #print('interactive mode ', mpl.get_backend())
    
    #Reduce number of data points for 4D plot only
    i, n = 0, len(sat_time)  #still can't handle size representation, so no s
    while n > plot_sampling: 
        i += 1
        n = len(sat_time)/i
    if i==0: i=1
    #s = 2.5**((sat_time-np.min(sat_time))/(np.max(sat_time)-np.min(sat_time))*4+1) #doesn't show
    
    #convert coordinates to cartesian, height => r in R_E, utc_ts->strings
    sat_track = [[(h*1000.+R_earth.value)/R_earth.value, lat, lon] \
                 for h, lat, lon in zip(sat_z,sat_lat,sat_lon)]
    @np.vectorize
    def ts_to_spacepystr(ts):
        return datetime.strftime(datetime.utcfromtimestamp(ts), '%Y-%m-%dT%H:%M:%S')
    coord_ticks = ts_to_spacepystr(sat_time)
    
    #perform coordinate conversion
    cvals = coord.Coords(sat_track, 'GEO', 'sph', units=['Re', 'deg', 'deg']) 
    cvals.ticks = Ticktock(coord_ticks, 'ISO')
    x, y, z = cvals.convert('GEO','car').data.T*R_earth.value/1000.  #converts to r, lat, lon 
    
    #make 4D plot, result=color
    fig = plt.figure(figsize=(10,8))
    fig.tight_layout()
    ax = fig.add_subplot(projection='3d')  #add size = time
    ax.xaxis.set_major_locator(MaxNLocator(5)) 
    ax.yaxis.set_major_locator(MaxNLocator(5)) 
    ax.zaxis.set_major_locator(MaxNLocator(5)) 
    p = ax.scatter(x[::i], y[::i], z[::i], result[::i], 
                   c=result[::i], cmap='viridis')  #works!
    ax.set_xlabel('x_GEO [km]', labelpad=15)
    ax.set_ylabel('y_GEO [km]', labelpad=15)
    ax.set_zlabel('z_GEO [km]', labelpad=15)
    cbar = fig.colorbar(p, pad=0.1)  #add label and units to colorbar
    cbar.set_label(variable_name+' ['+result_units+']', rotation=90, labelpad=25)
    try:  #remove pre-existing file if it exists
        os.remove(plot_file+variable_name+'_3Dheatcar.png')
    except:
        pass
    plt.savefig(plot_file+variable_name+'_3Dheatcar.png')
    if not int_off:  #only include if in interactive mode
        if plot_close: plt.close()
        
    #plot result, lon, lat, ilev as 'time' series
    fig, axs = plt.subplots(4, figsize=(10,7))
    axs[0].plot(sat_time,result, 'black')
    axs[0].set_ylabel('Interpolated \n'+variable_name+' \n['+result_units+']', labelpad=10)
    axs[0].set_xticks([])
    axs[1].plot(sat_time,x, 'black')
    axs[1].set_ylabel('x_GEO [km]', labelpad=10)
    axs[1].set_xticks([])
    axs[2].plot(sat_time,y, 'black')
    axs[2].set_ylabel('y_GEO [km]', labelpad=10)
    axs[2].set_xticks([])
    axs[3].xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y\n%H:%M:%S'))
    axs[3].xaxis.set_major_locator(MaxNLocator(5))     
    axs[3].plot([datetime.utcfromtimestamp(t) for t in sat_time], z, 'black')
    axs[3].set_ylabel('z_GEO [km]')
    axs[3].set_xlabel('Satellite Time [UTC]', labelpad=10)   #add datetime for x axis
    try:  #remove pre-existing file if it exists
        os.remove(plot_file+variable_name+'_1Dlinescar.png')
    except:
        pass
    plt.savefig(plot_file+variable_name+'_1Dlinescar.png')
    if not int_off:  #only include if in interactive mode
        if plot_close: plt.close()
    return
Esempio n. 15
0
def ConvertCoord(inTime, c1, c2, c3, inCoord, inType, outCoord, outType):
    """
    This function uses spacepy to convert time and position arrays from one coordinate system to another.
    It will correct obvious errors in the return units, but may not catch all incorrect values.
    
    INPUTS:
    inTime:   array:  time in UTC timestamp
    c1:       array:  x, lon
    c2:       array:  y, lat
    c3:       array:  z, alt
    inCoord:  string: GDZ, GEO, GSM, GSE, SM, GEI, MAG, SPH, RLL
    inType:   string: car, sph
    outCoord: string: GDZ, GEO, GSM, GSE, SM, GEI, MAG, SPH, RLL
    outType:  string: car, sph
    
    OUTPUT:
    c1:       array:  x, alt
    c2:       array:  y, lat
    c3:       array:  z, lon
    units:    array:  [unit_c1, unit_c2, unit_c3]  (for example ['km','deg','deg'] or ['R_E','R_E','R_E'])
    """

    # Start timer
    tic = time.perf_counter()
    #print("Starting ...")

    #pack position arrays in desired format
    if inType == "sph":
        # Need to reorder Kamodo arrays to be consistent with spacepy
        sat_track = [[c3[i], c2[i], c1[i]] for i in range(len(c1))]
    else:
        sat_track = [[c1[i], c2[i], c3[i]] for i in range(len(c1))]

    #convert utc_ts to spacepy time strings
    @np.vectorize
    def ts_to_spacepystr(ts):
        return dt.strftime(dt.utcfromtimestamp(int(ts)), '%Y-%m-%dT%H:%M:%S')

    #perform coordinate conversion
    cvals = Coords(sat_track, inCoord, inType)
    tt = Ticktock(ts_to_spacepystr(inTime), 'ISO')
    cvals.ticks = tt
    newC = cvals.convert(outCoord, outType)
    if outType == "sph":
        # Need to reorder Kamodo arrays to be consistent with spacepy
        zz, yy, xx = newC.data.T
    else:
        xx, yy, zz = newC.data.T

    outUnits = newC.units
    if outType == "sph":
        # Need to reorder Kamodo arrays to be consistent with spacepy
        outUnits.reverse()

    #fix spacepy bug in returned units
    if outType == 'sph':
        #check altitude for spherical return units
        if max(zz) > 300.:
            if outUnits[2] != 'km':
                #print(' -changing return alt units from',outUnits[2],'to km')
                outUnits[2] = 'km'
        elif min(zz) < 100.:
            if outUnits[2] != 'Re':
                #print(' -changing return alt units from',outUnits[2],'to Re')
                outUnits[2] = 'Re'
        #else leave as it is
    else:
        #check cartesian position return units
        rr = np.sqrt(xx**2 + yy**2 + zz**2)
        if max(rr) > 300.:
            if outUnits[0] != 'km':
                #print(' -changing spacepy return position units from',outUnits[0],'to km')
                outUnits[0] = 'km'
                outUnits[1] = 'km'
                outUnits[2] = 'km'
        elif min(rr) < 100.:
            if outUnits[0] != 'Re':
                #print(' -changing spacepy return position units from',outUnits[0],'to Re')
                outUnits[0] = 'Re'
                outUnits[1] = 'Re'
                outUnits[2] = 'Re'
        #else leave as it is

    #change unit Re to R_E for recognition in Kamodo
    for i in range(len(outUnits)):
        if outUnits[i] == 'Re':
            outUnits[i] = 'R_E'

    toc = time.perf_counter()
    print('Converted from ', inCoord, inType, 'to:', outCoord, outType,
          outUnits, 'in', "{:0.4f}".format(toc - tic), 'seconds.')

    return xx, yy, zz, outUnits
Esempio n. 16
0
    # Some debug information (useful when adding new sats):
    if args.debug:
        print('\tCDF Variables:')
        print(cdf)

    # Perform coordinate conversion:
    if args.coord == sats[s]['coord']:
        xyz = cdf[sats[s]['var']][...]
    else:
        if args.verbose:
            print(f"\tRotating from {sats[s]['coord']} to {args.coord}...")
        xyz_file = Coords(cdf[sats[s]['var']][...],
                          sats[s]['coord'],
                          'car',
                          ticks=Ticktock(cdf[sats[s]['time']][...]))
        xyz = xyz_file.convert(args.coord, 'car').data

    # Convert to satellite orbit object:
    if args.verbose: print(f'\tConverting to SWMF input file...')
    out = SatOrbit()
    out['time'] = cdf[sats[s]['time']][...]
    out['xyz'] = xyz.transpose()

    # Convert units:
    if sats[s]['units'] == 'km':
        out['xyz'] /= 6371

    # Add attributes to file:
    out.attrs['file'] = f'{s}.sat'
    out.attrs['coor'] = sats[s]['coord']
Esempio n. 17
0
        flashtime = dt.datetime(2001, 1, 1, 0, 0, 0)
        R_E = 6371e3  # Radius of earth in meters
        D2R = (np.pi / 180.0)

        # Convert to geographic coordinates for plotting:
        rays = []
        for r in rf:
            tmp_coords = coord.Coords(zip(r['pos'].x, r['pos'].y, r['pos'].z),
                                      'SM',
                                      'car',
                                      units=['m', 'm', 'm'])
            tvec_datetime = [
                flashtime + dt.timedelta(seconds=s) for s in r['time']
            ]
            tmp_coords.ticks = Ticktock(tvec_datetime)  # add ticks
            #     tmp_coords = tmp_coords.convert('MAG','car')
            tmp_coords.sim_time = r['time']

            rays.append(tmp_coords)

        #     derp = tmp_coords[0]
        #     derp = derp.convert('MAG','sph')
        #     print derp

        # -------- 2D Plots -------------------
        fig, ax = plt.subplots(1, 3)

        # ax[0].set_aspect("equal")
        # ax[1].set_aspect("equal")
        # ax[2].set_aspect("equal")
print("output directory:",ray_out_dir)
if not os.path.exists(ray_out_dir):
	os.mkdir(ray_out_dir)




# ------ Write the ray input file ---

ray_inpfile  = os.path.join(project_root,"ray_inpfile.txt")

f = open(ray_inpfile,'w')

# --- Rotate to SM using spacepy coordinate transform ---
tmp_coords = coord.Coords((inp_alt, inp_lat, inp_lon),'MAG','sph',units=['m','deg','deg'])
tmp_coords.ticks = Ticktock(ray_datenum) # add ticks
pos0 = tmp_coords.convert('SM','car')

pos0 = np.array([1,0,1])
pos0 = pos0/np.linalg.norm(pos0)
pos0*= inp_alt
        
if launch_direction is 'field-aligned':
    dir0 = np.zeros(3)                # Field aligned (set in raytracer)
else:
    dir0 = np.array([pos0.x, pos0.y, pos0.z])/np.linalg.norm(pos0)    # radial outward



w0   = freq*2.0*np.pi
# f.write('%1.15e %1.15e %1.15e %1.15e %1.15e %1.15e %1.15e\n'%(pos0.x, pos0.y, pos0.z, dir0[0], dir0[1], dir0[2], w0))
Esempio n. 19
0
    GSMarray.append([bx[i], timeseries[:, 1][i], timeseries[:, 2][i]])
    timelist.append(start_time + i * timedelta(seconds=60))
    i += 1

#turn the B vector and the magentometer location into spacepy Coords objects
location_geo = Coords(location, 'GEO', 'sph')
GSM = Coords(GSMarray, 'GSM', 'car')

#turn the timelist into a spacepy Ticktock object
#record the components of the B vector and generate the timelist
while i < len(bx):
    GSMarray.append([bx[i], timeseries[:, 1][i], timeseries[:, 2][i]])
    timelist.append(start_time + i * timedelta(seconds=60))
    i += 1

GSM.ticks = Ticktock(timelist, 'UTC')
location_geo.ticks = Ticktock(timelist, 'UTC')

#convert to SM coordinate system
middle_step = GSM.convert(
    'GEO', 'car'
)  #spacepy won't let me convert directly to SM coordinates for whatever reason
SM = middle_step.convert('SM', 'car')
locationSM = location_geo.convert('SM', 'car')

maglon = []  #keep track of magnetic longitude
i = 0  #reset counter variable

#find magnetic longitude
while i < len(locationSM):
    maglon.append(float(np.arctan2(locationSM[i].y, locationSM[i].x)))
Esempio n. 20
0
from mpl_toolkits.mplot3d import Axes3D
#df = pd.read_csv('simpleorbit.csv')
df = pd.read_csv('01_Jan_2019.csv')
# df = pd.read_csv('Jan65.txt')
print(df.tail())
# i THINK this is what i need to get into the regular mjd timeframe
t = df['DefaultSC.A1ModJulian'] + 29999.5
#t = np.asarray(t)
#print(type(t))
x = df['DefaultSC.gse.X']
y = df['DefaultSC.gse.Y']
z = df['DefaultSC.gse.Z']
cvals = coord.Coords([[i, j, k] for i, j, k in zip(x, y, z)], 'GSE', 'car')

# i'm pretty sure this serves zero purpose
cvals.x = x
cvals.y = y
cvals.z = z
cvals.ticks = Ticktock(t, 'MJD')
sm = cvals.convert('SM', 'car')
# gsm = cvals.convert('GEO', 'car')
# need to memorize how to do coordinates and time in spacepy

fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot(cvals.x, cvals.y, cvals.z, label='orbit')
# ax.plot(sm.x, sm.y, sm.z, label='sm orbit')
# ax.plot(gsm.x, gsm.y, gsm.z, label='gsm orbit')
ax.legend()
plt.show()
Esempio n. 21
0
def getColorMap(filename):
    """
    reads in a bunch of different data files and outputs the 
    colormap 
    """
    df = pd.read_csv(filename)
    # df = pd.read_csv(pathname+'65_year.csv')
    # df = pd.read_csv(pathname+'Jan65.csv')
    # df = pd.read_csv(pathname+'Jan80.csv')
    # df = pd.read_csv(pathname+'Jul65.csv')
    # df = pd.read_csv(pathname+'Jul90.csv')
    GMAT_MJD_OFFSET = 29999.5
    t = df['DefaultSC.A1ModJulian'] + GMAT_MJD_OFFSET
    x = df['DefaultSC.gse.X']
    y = df['DefaultSC.gse.Y']
    z = df['DefaultSC.gse.Z']

    spacecraft = coord.Coords([[i, j, k] for i, j, k in zip(x, y, z)], 'GSE',
                              'car')
    spacecraft.ticks = Ticktock(t, 'MJD')
    # originally SM
    spacecraft = spacecraft.convert('SM', 'car')
    points = 10000
    # this figure validates what I already expected
    # fig = plt.figure()
    # ax = fig.add_subplot(111,projection='3d')
    # ax.plot(spacecraft.x[:points],spacecraft.y[:points],spacecraft.z[:points])
    # plt.title('SM Orbit')
    # ax.set_xlabel('x')
    # ax.set_ylabel('y')
    # ax.set_zlabel('z')
    # plt.show()

    # okay i've looked at a couple of orbits from the GSE point of view and
    # i now think that it's okay for a zero inclined orbit WRT to the earth
    # equator to be inclined WRT to the ecliptic, but like holy moley
    # these orbits are confusing sometimes.

    # In[3]:

    # goal, plot PHI on the same plot
    xc, yc, zc = tsyg.orbitalCuspLocation(spacecraft, t)
    # originally 'SM'
    cusp_location = coord.Coords([[i, j, k] for i, j, k in zip(xc, yc, zc)],
                                 'SM', 'sph')  # changed
    cusp_location.ticks = Ticktock(t, 'MJD')
    # cusp_location = cusp_location.convert('SM','car')

    # fig = plt.figure()
    # ax = fig.add_subplot(111,projection='3d')
    # if I just want to :points
    # ax.plot(spacecraft.x[:points],spacecraft.y[:points],spacecraft.z[:points])
    # ax.plot(cusp_location.x[:points], cusp_location.y[:points],cusp_location.z[:points])

    # if I want EVERYTHING
    # ax.plot(spacecraft.x,spacecraft.y, spacecraft.z)
    # ax.scatter(cusp_location.x, cusp_location.y,cusp_location.z)
    # plt.title('SM Orbit and Corresponding Cusp Location')
    # ax.set_xlabel('x')
    # ax.set_ylabel('y')
    # ax.set_zlabel('z')
    # ax.set_xlim3d(-earth_radius_ax, earth_radius_ax)
    # ax.set_ylim3d(-earth_radius_ax, earth_radius_ax)
    # ax.set_zlim3d(-earth_radius_ax, earth_radius_ax)
    # plt.show()
    # plt.plot(cusp_location.x,cusp_location.y)
    # plt.show()

    # In[4]:

    # plt.plot(spacecraft.x,spacecraft.z)
    # plt.plot(cusp_location.x,cusp_location.z)
    # plt.xlim([-0.5*earth_radius_ax, earth_radius_ax])
    # plt.ylim([-0.5*earth_radius_ax, earth_radius_ax])
    # plt.xlabel('x')
    # plt.ylabel('z')
    # plt.title('xz plane of the cusp model')
    # plt.show()

    # In[5]:

    # the working configuration is 'SM'
    spacecraft_sph = spacecraft.convert('GSM', 'sph')
    cusp_location_sph = cusp_location.convert('GSM', 'sph')

    # In[6]:

    # making the plots
    points = 10000  # len(spacecraft_sph.ticks.MJD)
    lowBound = 0  # 156000
    highBound = points  # 166000
    # plt.plot(spacecraft_sph.ticks.MJD[lowBound:highBound],spacecraft_sph.lati[lowBound:highBound],label='sc')
    # i was doing 90 - cusp location?
    # plt.plot(cusp_location_sph.ticks.MJD[lowBound:highBound],90-cusp_location_sph.lati[lowBound:highBound],label='cusp')
    # plt.legend()
    # plt.xlabel('mjd ticks')
    # plt.ylabel('sm latitude')
    # plt.title('mjd ticks vs sm latitude (cusp and spacecraft)')
    # plt.show()

    # plt.plot(spacecraft_sph.ticks.MJD[lowBound:highBound], spacecraft_sph.long[lowBound:highBound],label='sc')
    # plt.plot(cusp_location_sph.ticks.MJD[lowBound:highBound],cusp_location_sph.long[lowBound:highBound],label='cusp')
    # plt.show()

    # modlat = 90 - cusp_location_sph.lati
    modlat = cusp_location_sph.lati
    print("LATITUDE IN CUSP LOCATION OBJECT", modlat)

    # In[7]:

    # count it up
    count = []
    c = 0
    for satlat, cusplat, satlon, cusplon in zip(spacecraft_sph.lati, modlat,
                                                spacecraft_sph.long,
                                                cusp_location_sph.long):
        # 0<cusplon<180 i think i need a way to ensure that I'm looking at the dayside
        # bear in mind that these bounds WILL ONLY WORK in earth - sun line centered coordinate systems
        if abs(satlat - cusplat) <= 2 and abs(
                satlon - cusplon) <= 2:  #earlier using 4 and 4
            # right now i'm using +/- 2 deg for the latitude,
            # and +/- 2 deg for the longitude
            c += 1
            count.append(c)
        else:
            count.append(c)

    # plt.plot(spacecraft_sph.ticks.MJD, count)
    # plt.xlabel('MJD tick')
    # plt.ylabel('cusp crossings')
    # plt.title('Cusp Crossings vs. MJD ticks')
    #plt.xlim([58700, 58800])
    # plt.show()
    print("final crossings count = ", c)

    # mean latitude of the cusp
    print("mean sm lat of cusp",
          90 - sum(cusp_location_sph.lati) / len(cusp_location_sph.lati))
    print("mean sm lon of cusp",
          sum(cusp_location_sph.long) / len(cusp_location_sph.long))

    # In[8]:

    # lets' see if we can check the psi function before 1pm
    r = 1.127
    psi = tsyg.getTilt(t)
    psi = np.asarray(psi)
    phic = tsyg.getPhi_c(r, psi)
    # plt.plot(phic)
    # plt.title('plot of phi_c for troubleshooting')
    # plt.show()

    # show the date in UTC
    print("UTC date", spacecraft_sph.ticks.UTC)
    return c
Esempio n. 22
0
        #plt.show()
        #plt.close()

        # NOW find the closest point and the index to the next one, point NORTH
        dist = [
            np.sqrt((r_step[0] - b_pt[0])**2 + (r_step[1] - b_pt[1])**2 +
                    (r_step[2] - b_pt[2])**2) for b_pt in bline_final
        ]
        dist = np.array(dist)
        smallest_difference_index = dist.argmin()
        closest_element = bline_final[smallest_difference_index]
        nclosest_element = bline_final[smallest_difference_index - 1]

        # grab mlat real quick
        cvals = coord.Coords([closest_element], 'SM', 'car')
        cvals.ticks = Ticktock([ray_datenum], 'ISO')  # add ticks
        B_mag = cvals.convert('MAG', 'sph')
        mlat = B_mag.lati
        mlats.append(mlat)

        # finally, take normal
        Bunit = np.array(nclosest_element) - np.array(closest_element)
        Bunit = Bunit / np.linalg.norm(Bunit)

        # translate then rotate??
        #d = (Bunit[0]*closest_element[0] + Bunit[1]*closest_element[1] + Bunit[2]*closest_element[2])

        # another quick check -- north or south???
        #fig = plt.figure()
        #ax = plt.axes(projection='3d')
        #ax.scatter(T_repackx,T_repacky,T_repackz)
def SatelliteTrajectory(server,
                        dataset,
                        parameters,
                        start,
                        stop,
                        plot_dir='',
                        plot_close=True,
                        plot_sampling=5000,
                        verbose=False):
    '''Retrieve and return satellite trajectory from HAPI/CDAWeb
    Examples of server, dataset, parameters, start, and stop are:
   
    #example parameters to get data from hapi client
    server     = 'http://hapi-server.org/servers/SSCWeb/hapi'
    dataset    = 'grace1'
    parameters = 'X_GEO,Y_GEO,Z_GEO,X_GSE,Y_GSE,Z_GSE'
    start      = '2012-07-07T00:00:00'
    stop       = '2012-07-08T00:00:00'
    
    #example parameters to get data from cda web
    server2 = 'https://cdaweb.gsfc.nasa.gov/hapi'
    dataset2 = 'GE_K0_MGF'
    parameters2 = 'IB_vector,POS'
    start2      = '2008-07-11T00:00:00'
    stop2       = '2008-07-13T00:00:00'
    
    '''
    #retrieve satellite trajectory
    hapi = HAPI(server, dataset, parameters, start, stop, verbose=verbose)
    satellite_dict = {'sat_time': hapi.tsarray}

    #choose a coordinate type from satellite data
    coord_type_list = [
        'GDZ', 'GEO', 'GSM', 'GSE', 'SM', 'GEI', 'MAG', 'SPH', 'RLL'
    ]  #list allowed by spacepy
    coord_type = None
    for key in hapi.coords.keys():
        if hapi.coords[key]['size'] == 3 and key in coord_type_list:
            coord_type = key
            break  #stop at first coordinate that is already in grouped point format
    if coord_type is None:  # if no coordinates are already in grouped point format
        for key in hapi.coords.keys():
            if key in coord_type_list:
                coord_type = key  #select first one that is allowed
                break

    #get coordinate data grouped into a list of points and list of units
    if hapi.coords[coord_type]['size'] == 1:
        x_name, y_name, z_name = hapi.coords[coord_type]['x'], hapi.coords[
            coord_type]['y'], hapi.coords[coord_type]['z']
        coord_data = [[x, y, z] for x, y, z in zip(
            hapi.variables[x_name]['data'], hapi.variables[y_name]['data'],
            hapi.variables[z_name]['data'])]

        coord_units = [
            hapi.variables[name]['units'] for name in [x_name, y_name, z_name]
        ]
        coord_units = ['Re' if i == 'R_E' else i for i in coord_units]
    else:  #assume data is already in a list of points format
        coord_data = hapi.variables[hapi.coords[coord_type]['x']]['data']
        if hapi.variables[hapi.coords[coord_type]['x']]['units'] == 'R_E':
            coord_units = ['Re', 'Re', 'Re']
        elif hapi.variables[hapi.coords[coord_type]['x']]['units'] == 'km':
            coord_units = ['km', 'km', 'km']
    if 'deg' in coord_units: carsph = 'sph'
    else: carsph = 'car'
    if verbose:
        test = np.array(coord_data)
        print(test.shape, coord_type, coord_units, carsph)
        for i in [0, 1, 2]:
            print(i, min(test[:, i]), max(test[:, i]))

    #convert datetime objects into ISO strings for coordinate conversion
    @np.vectorize
    def dt_to_str(dt_object):
        return dt_object.strftime('%Y-%m-%dT%H:%M:%S')

    coord_ticks = dt_to_str(hapi.dtarray)

    #convert coordinates into spherical GEO using spacepy
    cvals = coord.Coords(coord_data, coord_type, carsph, units=coord_units)
    cvals.ticks = Ticktock(coord_ticks, 'ISO')
    newvals = cvals.convert('GEO', 'sph')  #converts to r, lat, lon
    if verbose: print(newvals.units)
    newcoord_data = newvals.data.T
    if newvals.units[0] == 'km':
        satellite_dict['sat_height'] = newcoord_data[0] - R_earth.value / 1000.
    elif newvals.units[0] == 'm':
        satellite_dict['sat_height'] = (newcoord_data[0] -
                                        R_earth.value) / 1000.
    elif newvals.units[0] == 'Re':
        satellite_dict['sat_height'] = (
            newcoord_data[0] -
            1.) * R_earth.value / 1000.  #convert to alt in km
    satellite_dict['sat_lat'], satellite_dict['sat_lon'] = newcoord_data[
        1], newcoord_data[2] + 180.
    satellite_units = {
        'sat_time': 's',
        'sat_height': 'km',
        'sat_lat': 'deg',
        'sat_lon': 'deg'
    }

    #collect list of coordinate variables to ignore in next step
    coord_list = list(
        np.ravel(
            np.array([[
                hapi.coords[key]['x'], hapi.coords[key]['y'],
                hapi.coords[key]['z']
            ] for key in hapi.coords.keys()])))

    #collect other requested variables and return
    var_list = [key for key in hapi.variables.keys() if key not in coord_list]
    for item in var_list:
        satellite_dict[item] = hapi.variables[item]['data']
        satellite_units[item] = hapi.variables[item]['units']

    #generate plot if desired
    if plot_dir != '':
        if not os.path.isdir(plot_dir + 'Plots/'):
            os.mkdir(plot_dir + 'Plots/')
        FPlot.Plot4D('Time',
                     satellite_dict['sat_time'],
                     satellite_dict['sat_lat'],
                     satellite_dict['sat_lon'],
                     satellite_dict['sat_height'],
                     satellite_dict['sat_time'],
                     's',
                     plot_dir + 'Plots/SatelliteTrajectory',
                     'km',
                     plot_close=plot_close,
                     plot_sampling=plot_sampling)

    print(f'Attribute/Key names of return dictionary: {satellite_dict.keys()}')
    print(f'Units of variables are: {satellite_units}')

    return satellite_dict
Esempio n. 24
0
def getColorMapSimple(filename):
    df = pd.read_csv(filename)
    GMAT_MJD_OFFSET = 29999.5
    t = df['DefaultSC.A1ModJulian'] + GMAT_MJD_OFFSET
    x = df['DefaultSC.gse.X']
    y = df['DefaultSC.gse.Y']
    z = df['DefaultSC.gse.Z']

    # adding interpolation
    tStart = t[0]
    tEnd = t[len(t) - 1]
    tInterval = (t[1] - t[0]) / 10
    t_0 = t
    t = np.arange(tStart, tEnd, tInterval)
    x = np.interp(t, t_0, x)
    y = np.interp(t, t_0, y)
    z = np.interp(t, t_0, z)

    #
    xa = np.array(x)
    ya = np.array(y)
    za = np.array(z)
    print(za)
    ta = np.array(t)

    spacecraft = coord.Coords([[i, j, k] for i, j, k in zip(x, y, z)], 'GSE',
                              'car')
    spacecraft.ticks = Ticktock(t, 'MJD')
    spacecraft = spacecraft.convert('SM', 'car')
    points = 10000
    # this figure validates what I already expected
    # fig = plt.figure()
    # ax = fig.add_subplot(111,projection='3d')
    # ax.plot(spacecraft.x[:points],spacecraft.y[:points],spacecraft.z[:points])
    # plt.title('SM Orbit')
    # ax.set_xlabel('x')
    # ax.set_ylabel('y')
    # ax.set_zlabel('z')
    # plt.show()

    # In[3]:

    # this is the part where I actually do it

    phi_0 = 0.24

    psi = tsyg.getTilt(t)

    # dude if i made a parthenthetical error like this ill be really sad

    # plt.plot(spacecraft.ticks.MJD, 90 - (phi_0 + psi))
    # plt.show()

    # In[4]:

    r = np.sqrt(xa**2 + ya**2 + za**2) / Re
    print("r equals to", r)
    psi = np.deg2rad(psi)
    psi = np.array(psi)
    phi_0 = 0.24
    alpha1 = 0.1287
    alpha2 = 0.0314
    phi_1 = phi_0 - (alpha1 * psi + alpha2 * psi**2)

    phi_c = np.rad2deg(
        np.arcsin(
            (np.sqrt(r)) / (np.sqrt(r + (1 / np.sin(phi_1))**2 - 1)))) + psi
    #phi = 90-(phi+psi)
    lat = 90 - phi_c
    lon = np.array(np.zeros(len(spacecraft.ticks.MJD)))
    print(lon)
    # plt.plot(t,lat)
    # plt.title('Cusp Latitude vs. MJD day')
    # plt.xlabel('MJD Day')
    # plt.ylabel('Cusp Lat, Deg')
    # plt.show()

    # In[5]:

    # LATITUDE

    #working config SM
    spacecraft_sm = spacecraft.convert('GSM', 'sph')
    # plt.plot(spacecraft_sm.ticks.MJD, spacecraft_sm.lati)
    # plt.plot(spacecraft_sm.ticks.MJD, lat)
    # plt.title('Spacecraft Lat and Cusp Latitude vs MJD time')
    # plt.show()

    # In[6]:

    # LONGITUDE

    # try to avoid using the [:points] way except for spot checking
    # kind of interested in a macro effect

    # plt.plot(spacecraft_sm.ticks.MJD, spacecraft_sm.long)
    # plt.plot(spacecraft_sm.ticks.MJD, lon)
    # plt.title('Spacecraft and Cusp Longitude vs. Time')
    # plt.show()

    # In[7]:

    count = []
    region = []
    c = 0
    for satlat, cusplat, satlon, cusplon in zip(spacecraft_sm.lati, lat,
                                                spacecraft_sm.long, lon):
        # 0<=cusplon<180
        if abs(satlat - cusplat) <= 2 and abs(satlon - cusplon) <= 2:
            # right now i'm using +/- 2 deg for the latitude,
            # and +/- 2 deg for the longitude
            # c+=1
            region.append(1)
        else:
            region.append(0)

    for x, x1 in zip(region, region[1:]):
        if x == 0 and x1 == 1:
            c += 1
        else:
            pass

    # plt.plot(spacecraft_sm.ticks.MJD, count)
    # plt.xlabel('MJD tick')
    # plt.ylabel('cusp crossings')
    # plt.title('Cusp Crossings vs. MJD ticks')
    #plt.xlim([58700, 58800])
    # plt.show()
    print("cusp crossings", c)
    return c
Esempio n. 25
0
 def test_slice_with_ticks(self):
     self.cvals.ticks = Ticktock(
         ['2002-02-02T12:00:00', '2002-02-02T12:00:00'], 'ISO')
     expected = spc.Coords([1, 2, 4], 'GEO', 'car')
     np.testing.assert_equal(expected.data, self.cvals[0].data)
Esempio n. 26
0
    phi_c = getPhi_c(r)
    print(phi_c)
    plt.plot(r0, phi_c)
    plt.title('r vs phi_c')
    plt.show()
    x, y, z = tsygCyl2Car(phi_c, r)

    cvals = coord.Coords([[i, j, k] for i, j, k in zip(x, y, z)], 'SM', 'car')

    starttime = pd.Timestamp('2019-01-01T12:00:00')
    endtime = pd.Timestamp('2020-01-01T12:00:00')
    t = np.linspace(starttime.value, endtime.value, len(x))
    print("length of t", t)

    # just increment julian days
    cvals.ticks = Ticktock([58484 + i for i in range(0, 365)], 'MJD')
    cvals_gse = cvals.convert('GSE', 'car')
    cvals_geo = cvals.convert('GEO', 'car')
    # setting arbitrary times is something i just need to know how to do
    sm = getSmOrbit()

    # comment the next two out for the 'original' plot
    sm = sm.convert('GEO', 'car')
    cvals = cvals.convert('GEO', 'car')
    ax = plt.subplot(111, projection='3d')
    # ax.plot(x,y,z,label='glorious cusp vector')

    # make unit vectors,mainly because i only care about pointing direction
    ax.plot(sm.x, sm.y, sm.z, label='sm orbit')
    ax.plot(cvals.x, cvals.y, cvals.z, 'g', label='sm cusp vector')
    # ax.plot(cvals_gse.x,cvals_gse.y,cvals_gse.z,label='gse cusp vector')