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
def get_Bmodel(self): ''' Calculating theoretical B from models in IRBEMpy (spacepy) based on lat, long and alt. Nothing more compleicated should be neccecary ''' print ' Calculating Bmodel ' if self.range_set_done == True: print ''' Warning! You have changed the range. The Bmodel will not fully do so too. Show caution''' y = np.array([self.alt, self.lat, self.lon]) y = np.ndarray.transpose( y) #getting the right dimensions for get_Bfield y = coord.Coords(np.array(y), 'GDZ', 'sph') launch_realtimeTAI = var.launch_TAI + self.t_pos T = spacepy.time.Ticktock(launch_realtimeTAI, 'TAI') T = T.UTC t = spacepy.time.Ticktock(T, 'UTC') getB = spacepy.irbempy.get_Bfield(t, y, extMag='0') print ' get_Bfield ran. ' self.Bmodel = getB['Blocal'] print ' Ran Bmodel. Dumping to file cause it takes TIME Give it a name.' spec_name = 'testing' #str(raw_input(' * = ')) np.save(var.dataname_Bmodel_raw + spec_name, getB) return None
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
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]
def runPAdungey(quality): #test for range of pitch angles ticks = spt.tickrange('2002-04-18', '2002-04-19', 1) loci = spc.Coords([[-4, 0, 0], [-5, 0, 0]], 'SM', 'car') vals = [] for pp in range(1, 91): dum = lgmpy.get_Lstar(loci.data[1], ticks.UTC[1], alpha=pp, coord_system='SM', Bfield='Lgm_B_Dungey', extended_out=True, LstarQuality=quality) try: vals.extend(dum[pp]['Lstar']) except (IndexError, TypeError): #get_Lstar returns a 0-D nan in some cases... vals.extend([dum[pp]['Lstar'].tolist()]) fig = plt.figure() expect = dungeyLeq(tb.hypot(loci.data[1])) #print(expect) plt.plot(100 * (dm.dmarray(vals) - expect) / expect, drawstyle='steps-mid') plt.ylim([-0.01, 0.01]) plt.xlabel('Pitch Angle') plt.ylabel('100*(L* - L*$_{exp}$)/L*$_{exp}$') plt.title('Dungey model [-5,0,0]$_{SM}$' + '; Quality ({0})'.format(str(quality))) figname = 'MagEphem_Dungey_test_q{0}'.format( str(quality)) #'LGM_L*_vs_PA_cdip_q{0}'.format(str(quality)) plt.savefig(''.join([figname, '.png']), dpi=300) plt.savefig(''.join([figname, '.pdf']))
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')
def getLm(self, alpha=[90], model='T89'): """Calculate McIlwain L for the imported AE9/AP9 run and add to object """ import spacepy.irbempy as ib ticks = spt.Ticktock(self['Epoch']) loci = spc.Coords(self['Coords'], self['Coords'].attrs['COORD_SYS'], 'car') loci.ticks = ticks retvals = ib.get_Lm(ticks, loci, alpha, extMag=model) self['Lm'] = dm.dmarray(retvals['Lm'].squeeze(), attrs={'MODEL': model})
def GSE2GSM_MFI(MFI): MFIGSE=np.vstack((MFI["BX"][:],MFI["BY"][:],MFI["BZ"][:])) SM = spc.Coords(MFIGSE.T,'GSE','car') SM.ticks = spt.Ticktock(MFI["EPOCH"][:],'ISO') SM = SM.convert('GSM','car') x=SM.data.T[0] y=SM.data.T[1] z=SM.data.T[2] MFI["BX"]=x MFI["BY"]=y MFI["BZ"]=z return MFI
def GSE2GSM_FPE(FPE): FPEGSE=np.vstack((FPE["GSEX"][:],FPE["GSEY"][:],FPE["GSEZ"][:])) SM = spc.Coords(FPEGSE.T,'GSE','car') SM.ticks = spt.Ticktock(FPE["EPOCH"][:],'ISO') SM = SM.convert('GSM','car') x=SM.data.T[0] y=SM.data.T[1] z=SM.data.T[2] FPE["GSEX"]=x FPE["GSEY"]=y FPE["GSEZ"]=z return FPE
def get_bfield_irbem(x, dtime, bmodel, extfield): pos = spc.Coords([x[0], x[1], x[2]], 'GEO', 'car') tv = spt.Ticktock(dtime) B = irbem.get_Bfield(tv, pos, extMag=extfield, options=[1, 0, 0, 0, bmodel], omnivals=None) Bmag = B['Blocal'] return Bmag
def get_kvec2(lon, lat, alt, ephtimes=None, tx_lon=-75.552, tx_lat=45.403, tx_alt=.07): """ Uses cartesian coordinates (GEO XYZ) to get absolute direction vector between two (lon, lat, alt) points. *** PARAMS *** lon (float or array): longitude of point(s) from transmitter lat (float or array): latitude of point(s) from transmitter altitude (float or array): altitude of point(s) from transmitter [tx_lon] (float): longitude of transmitter [deg] [tx_lat] (float): latitude of transmitter [deg] [tx_alt] (float): altitude of transmitter [km] *** RETURNS *** kv (float or array): vector(s) from transmitter to input point(s) """ import spacepy.coordinates as coord import spacepy.time as tm import datetime as dt b = coord.Coords([[alt + EARTH_RAD, lat, lon]],'GEO','sph') a = coord.Coords([[tx_alt + EARTH_RAD, tx_lat, tx_lon]], 'GEO', 'sph') if ephtimes is None: b.ticks = tm.Ticktock(dt.datetime.now()) # because it doesnt matter a.ticks = tm.Ticktock(dt.datetime.now()) # because it doesnt matter else: times = ephems_to_datetime(ephtimes) b.ticks = tm.Ticktock(times) a.ticks = tm.Ticktock(times) b = b.convert('GEO','car') a = a.convert('GEO','car') kv = (b.data - a.data)[0] kv = kv/np.linalg.norm(kv) logging.info("get_kvecs2 result: ", kv) return kv
def B_dir_3D(t, x, dtime, bmodel, extfield, direction): # p0 must be in GEO car in RE # dtime must be a datetime object pos = spc.Coords([x[0], x[1], x[2]], 'GEO', 'car') tv = spt.Ticktock(dtime) B = irbem.get_Bfield(tv, pos, extMag=extfield, options=[1, 0, 0, 0, bmodel], omnivals=None) Bmags = direction * B['Bvec'] / B['Blocal'] return [Bmags[0][0], Bmags[0][1], Bmags[0][2]]
def GSE2GSM_B(MFI): """ GSE转GSM函数 输入:字典格式数据 输出:np.ndarray格式数据 """ GSM = np.zeros((3, len(MFI["BZ"]))) for i in range(GSM.shape[1]): SM = spc.Coords([[MFI["BX"][i], MFI["BY"][i], MFI["BZ"][i]]], 'GSE', 'car') SM.ticks = spt.Ticktock(MFI["EPOCH"][i], 'ISO') SM = SM.convert('GSM', 'car') GSM[0][i] = SM.data[0][0] GSM[1][i] = SM.data[0][1] GSM[2][i] = SM.data[0][2] return GSM
def GSE2GSM(FPE): """ GSE转GSM函数 输入:字典格式数据 输出:np.ndarray格式数据 """ GSM = np.zeros((3, FPE["X_GSE"].shape[0])) for i in range(GSM.shape[1]): SM = spc.Coords([[FPE["X_GSE"][i], FPE["Y_GSE"][i], FPE["Z_GSE"][i]]], 'GSE', 'car') SM.ticks = spt.Ticktock(FPE["EPOCH"][i], 'ISO') SM = SM.convert('GSM', 'car') GSM[0][i] = SM.data[0][0] GSM[1][i] = SM.data[0][1] GSM[2][i] = SM.data[0][2] return GSM
def L_para(T_E): L1 = parser.get('mission_parameters', 'TLE_Line1') L2 = parser.get('mission_parameters', 'TLE_Line2') satellite = twoline2rv(L1, L2, wgs72) position, velocity = satellite.propagate(T_E[0], T_E[1], T_E[2], T_E[3], T_E[4], T_E[5]) Re = [(x / 6371.2) for x in position] spaco = spc.Coords(Re, 'GEI', 'car') spaco.ticks = spt.Ticktock([T_E[6]], 'ISO') q = [90] # q=spaco.convert('SM','sph') #default value of 90 is used as it returns the most data-points, other values of q have more instances when the value returned is NaN # q=q.data[0][1] L = ir.get_Lm(spaco.ticks, spaco, q, extMag='T01STORM', intMag='IGRF') return satellite.alta * 6371, satellite.altp * 6371, math.degrees( satellite.inclo), L.items()[2][1][0][0]
def getTilt(t): """ gets the dipole tilt and adds it to the tsyganenko cusp model almost a direct copy of J. niehof's code This also somewhat necessitates that we do the rest of the analysis in the GSM frame t = the pandas list of times (I'm assuming MJD for this use case) """ t = spt.Ticktock(t, 'MJD') c_sm = coord.Coords([[0, 0, 1.0]] * len(t), 'SM', 'car') c_sm.ticks = t # convert to gsm c_gsm = c_sm.convert('GSM', 'car') # i set this to be negative as an experiment. return np.rad2deg(np.arctan2(c_gsm.x, c_gsm.z)) #changed from x,z to z,x
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
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
def plot_cluster(stime, etime, ax_c_B=None,ax_c_Btheta=None, ylim_c_B=[-60, 60],ylim_c_theta=[-180, 180], marker='.', linestyle='--', markersize=2, ylabel_fontsize=9, zero_line=True, interpolation_method=None, drop_na=False): # read data date_parser = lambda x: pd.datetime.strptime(x, '%d-%m-%Y %H:%M:%S.%f') #date_parser = lambda x, y: pd.datetime.strptime(" ".join([str(x), str(y)]), '%d-%m-%Y %H:%M:%S.%f') # reading the data into pandas' DataFrame object date_fname_dict = {"20020318" : "C3_CP_FGM_SPIN_31086.txt", "20030214" : "C1_CP_FGM_SPIN_21206.txt", "20040325" : "C3_CP_FGM_SPIN_3152599.txt", "20060306" : "C3_CP_FGM_SPIN_31759.txt"} fname = "./data/" + date_fname_dict[stime.strftime("%Y%m%d")] date_srows_dict = {"20020318" : 114, "20030214" : 127, "20040325" : 114, "20060306" : 114} srows = range(date_srows_dict[stime.strftime("%Y%m%d")]) df_c1 = pd.read_csv(fname, index_col=0, skipinitialspace=True, delim_whitespace=True, skiprows=srows, header=None, parse_dates={'datetime': [0,1]}, date_parser=date_parser, error_bad_lines=False) df_c1.columns = ["B", "BX_GSE", "BY_GSE", "BZ_GSE", "X_GSE", "Y_GSE", "Z_GSE"] # select the period of interest df_c1 = df_c1.loc[stime:etime,] # convert Bfield data from GSE to GSM import spacepy.coordinates as spc import spacepy.time as spt import numpy as np GSE_array = np.array([df_c1.BX_GSE.tolist(), df_c1.BY_GSE.tolist(), df_c1.BZ_GSE.tolist()]) GSE_array = GSE_array.transpose() GSE_position = spc.Coords(GSE_array, "GSE", "car") GSE_position.ticks = spt.Ticktock(df_c1.index.to_pydatetime(), "UTC") GSM_position = GSE_position.convert("GSM", "car") df_c1.loc[:, "BX_GSM"] = GSM_position.x df_c1.loc[:, "BY_GSM"] = GSM_position.y df_c1.loc[:, "BZ_GSM"] = GSM_position.z df_c1.loc[:, 'Bt'] = np.sqrt((df_c1.BY_GSM ** 2 + df_c1.BZ_GSM ** 2)) # clock angle df_c1.loc[:, 'theta_Bt'] = np.degrees(np.arctan2(df_c1.BY_GSM, df_c1.BZ_GSM)) def my_func(row): clmn = "theta_Bt" if clmn in row.keys(): row[clmn] = row[clmn] % 360 #if row[clmn] > 270: # row[clmn] = row[clmn] - 360 return row if stime.strftime("%Y%m%d") == "20060306": df_c1.apply(my_func, axis=1) if drop_na: df_c1.dropna(how='any', inplace=True) if interpolation_method is not None: df_c1.fillna(method=interpolation_method, inplace=True) # plot cluster Bfield data if ax_c_B is not None: ax_c_B.plot_date(df_c1.index.to_pydatetime(), df_c1.BX_GSM, color='k', marker=marker, linestyle=linestyle, markersize=markersize) ax_c_B.plot_date(df_c1.index.to_pydatetime(), df_c1.BY_GSM, color='g', marker=marker, linestyle=linestyle, markersize=markersize) ax_c_B.plot_date(df_c1.index.to_pydatetime(), df_c1.BZ_GSM, color='r', marker=marker, linestyle=linestyle, markersize=markersize) lns = ax_c_B.get_lines() ax_c_B.legend(lns,['Bx', 'By', 'Bz'], frameon=False, bbox_to_anchor=(0.98, 0.5), loc='center left', fontsize='medium') #ax_c_B.legend(lns,['Bx', 'By', 'Bz'], frameon=False, fontsize='small', mode='expand') ax_c_B.set_ylabel('B_gsm\n'+"(nT)", fontsize=ylabel_fontsize) ax_c_B.set_ylim([ylim_c_B[0], ylim_c_B[1]]) ax_c_B.locator_params(axis='y', nbins=4) if zero_line: ax_c_B.axhline(y=0, color='r', linewidth=0.30, linestyle='--') # plot cluster Bfield clock angle if ax_c_Btheta is not None: ax_c_Btheta.plot_date(df_c1.index.to_pydatetime(), df_c1.theta_Bt, color='r', marker=marker, linestyle=linestyle, markersize=markersize) #ax_c_Btheta.set_ylabel(r'$\theta$ [deg]', fontsize=ylabel_fontsize) ax_c_Btheta.set_ylabel('IMF Clock Angle\n'+r"$(^\circ)$", fontsize=ylabel_fontsize) ax_c_Btheta.set_ylim([ylim_c_theta[0], ylim_c_theta[1]]) ax_c_Btheta.locator_params(axis='y', nbins=4) # add extra ytick labels #poss1 = np.append(ax_c_Btheta.yaxis.get_majorticklocs(), ax_c_Btheta.yaxis.get_minorticklocs()) poss1 = ax_c_Btheta.yaxis.get_majorticklocs() poss1 = np.append(poss1, [-180, -90, 90, 180]) poss1 = np.delete(poss1, [0, 1, 3, 4]) ax_c_Btheta.yaxis.set_ticks(poss1) # draw horizontal lines if zero_line: ax_c_Btheta.axhline(y=0, color='r', linewidth=0.30, linestyle='--') ninety_line = True if ninety_line: ax_c_Btheta.axhline(y=90, color='r', linewidth=0.30, linestyle='--') ax_c_Btheta.axhline(y=-90, color='r', linewidth=0.30, linestyle='--')
def test_slice(self): expected = spc.Coords([1, 2, 4], 'GEO', 'car') np.testing.assert_equal(expected.data, self.cvals[0].data)
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)
def setUp(self): #super(tFunctionTests, self).setUp() try: self.cvals = spc.Coords([[1, 2, 4], [1, 2, 2]], 'GEO', 'car') except ImportError: pass #tests will fail, but won't bring down the entire suite
def test_append(self): c2 = spc.Coords([[6, 7, 8], [9, 10, 11]], 'GEO', 'car') actual = self.cvals.append(c2) expected = [[1, 2, 4], [1, 2, 2], [6, 7, 8], [9, 10, 11]] np.testing.assert_equal(expected, actual.data.tolist())
By = np.zeros(1440) Bz = np.zeros(1440) XGSE = np.zeros(1440) YGSE = np.zeros(1440) 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
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
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
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
def plotSummary(self, timerange=None, coord_sys=None, fig_target=None, spec=False, orbit_params=(False, True), **kwargs): """Generate summary plot of AE9/AP9/SPM data loaded spec : if True, plot spectrogram instead of flux/fluence lineplot, requires 'ecol' keyword """ if timerange: if isinstance(timerange, spt.Ticktock): t1 = timerange.UTC[0] t2 = timerange.UTC[-1] elif isinstance(timerange[0], dt.datetime): t1 = timerange[0] t2 = timerange[-1] else: raise TypeError('Incorrect data type provided for timerange') # now select subset i_use = tb.tOverlapHalf([t1, t2], self['Epoch']) t_use = self['Epoch'][i_use] c_use = self['Coords'][i_use] f_use = self[self.attrs['varname']][i_use, ...] else: t_use = self['Epoch'] c_use = self['Coords'] f_use = self[self.attrs['varname']] if coord_sys and (coord_sys.upper() != c_use.attrs['COORD_SYS']): # TODO: We assume cartesian, make flexible so can take spherical cx = spc.Coords(c_use, c_use.attrs['COORD_SYS'], 'car') cx.ticks = spt.Ticktock(t_use) cx = cx.convert(coord_sys.upper(), 'car').data else: coord_sys = c_use.attrs['COORD_SYS'] cx = c_use sys_subs = r'$_{' + coord_sys + r'}$' splot.style('spacepy') if orbit_params[0]: landscape = orbit_params[1] locs = [121, 122] if landscape else [211, 212] else: locs = [223, 224] landscape = True if fig_target: fig, ax1 = splot.set_target(fig_target, loc=locs[0]) else: fig, ax1 = splot.set_target(fig_target, figsize=(8, 8), loc=locs[0]) fig, ax2 = splot.set_target(fig, loc=locs[1]) ax1 = self._makeOrbitAxis(cx[:, 0], cx[:, 1], ax1) ax2 = self._makeOrbitAxis(cx[:, 0], cx[:, 2], ax2) if landscape: ax1.set_xlabel('X{0} [{1}]'.format(sys_subs, self['Coords'].attrs['UNITS'])) ax2.set_xlabel('X{0} [{1}]'.format(sys_subs, self['Coords'].attrs['UNITS'])) ax1.set_ylabel('Y{0} [{1}]'.format(sys_subs, self['Coords'].attrs['UNITS'])) ax2.set_ylabel('Z{0} [{1}]'.format(sys_subs, self['Coords'].attrs['UNITS'])) ax1xl, ax1yl, ax2xl, ax2yl = ax1.get_xlim(), ax1.get_ylim( ), ax2.get_xlim(), ax2.get_ylim() maxabslim = np.max(np.abs([ax1xl, ax1yl, ax2xl, ax2yl])) if np.abs((ax1.get_xlim()[1] - ax1.get_xlim()[0])) < 1: refpt = maxabslim ax1.set_xlim([-1.25 * refpt, 1.25 * refpt]) ax1.set_ylim(ax1.get_xlim()) refpt = ax2.get_xlim()[0] ax2.set_xlim([-1.25 * refpt, 1.25 * refpt]) ax2.set_ylim(ax1.get_xlim()) else: ax1.set_xlim([-maxabslim, maxabslim]) ax1.set_ylim([-maxabslim, maxabslim]) ax2.set_xlim([-maxabslim, maxabslim]) ax2.set_ylim(ax2.get_xlim()) ax1.invert_yaxis() ax1.invert_xaxis() ax2.invert_xaxis() ax1.set_aspect('equal') ax2.set_aspect('equal') if not orbit_params[0]: ax3 = splot.plt.subplot2grid((2, 2), (0, 0), colspan=2) if not spec: l3 = ax3.semilogy(t_use, f_use) ylab = '{0} ['.format(self.attrs['varname']) + re.sub( '(\^[\d|-]*)+', _grp2mathmode, self[self.attrs['varname']].attrs['UNITS']) + ']' ax3.set_ylabel(ylab) for ll, nn in zip(l3, self['Energy']): ll.set_label('{0} {1}'.format( nn, self['Energy'].attrs['UNITS'])) ncol = len(self['Energy']) // 2 if len( self['Energy']) <= 6 else 3 leg = ax3.legend(loc='center', bbox_to_anchor=(0.5, 1), ncol=ncol, frameon=True, framealpha=0.5) lims3 = ax3.get_ylim() newupper = 10**(np.log10(lims3[0]) + (np.log10(lims3[1] / lims3[0]) * 1.125)) ax3.set_ylim([lims3[0], newupper]) splot.applySmartTimeTicks(ax3, t_use) fig.tight_layout() pos3 = ax3.get_position() ax3.set_position( [pos3.x0, pos3.y0, pos3.width, pos3.height * 0.8]) # fig.suptitle('{model_type}\n'.format(**self.attrs) + # '{0} - {1}'.format(t_use[0].isoformat()[:19], t_use[-1].isoformat()[:19])) else: if timerange: raise NotImplementedError( 'Time range selection not yet implemented for spectrograms' ) pos3 = ax3.get_position() ax3.set_position( [pos3.x0, pos3.y0, pos3.width, pos3.height * 0.9]) ecol = kwargs['ecol'] if 'ecol' in kwargs else 0 ax3 = self.plotSpectrogram(target=ax3, ecol=ecol) splot.plt.subplots_adjust(wspace=0.3) pos1 = ax1.get_position() ax1.set_position([pos3.x0, pos1.y0, pos1.width, pos1.height]) splot.revert_style() return fig
launch_alt = (R_E + 2000.)*1e3 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')
Ne_xz[np.isnan(Ne_xz)] = 0 Ne_yz = d_yz['Ns'][0, :, :, :].squeeze().T * 1e-6 Ne_yz[np.isnan(Ne_yz)] = 0 px = np.linspace(-10, 10, 200) py = np.linspace(-10, 10, 200) 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 -------------------