def ex_spectra(plot=True): """Download THEMIS data and create a plot.""" # Delete any existing pytplot variables pytplot.del_data() # Download THEMIS data for 2015-12-31 # pyspedas.load_data('themis', ['2015-12-31'], ['tha'], 'state', 'l1') # pyspedas.load_data('themis', ['2015-12-31'], ['tha'], 'sst', 'l2') time_range = ['2015-12-31 00:00:00', '2015-12-31 23:59:59'] pyspedas.themis.state(probe='a', trange=time_range) pyspedas.themis.sst(probe='a', trange=time_range, varnames=['tha_psif_en_eflux']) # Specify options pytplot.ylim('tha_pos', -23000.0, 81000.0) pytplot.ylim('tha_psif_en_eflux', 10000.0, 4000000.0) pytplot.options('tha_psif_en_eflux', 'colormap', 'jet') pytplot.tplot_options('title', 'tha 2015-12-31') # Plot line and spectrogram if plot: pytplot.tplot(['tha_pos', 'tha_psif_en_eflux']) # Return 1 as indication that the example finished without problems. return 1
def ex_create(): # Delete any existing pytplot variables pytplot.del_data() # Create a sin wave plot a = list(range(0, 101)) b = [2.0 / 100.0 * numpy.pi * s for s in a] c = pyspedas.time_float('2017-01-01') x = list() y = list() for i in range(len(b)): x.append(c + 60.0 / (2 * numpy.pi) * 60.0 * b[i]) y.append(1000.0 * numpy.sin(b[i])) # Store data pytplot.store_data('sinx', data={'x': x, 'y': y}) # Apply tclip pyspedas.tclip('sinx', -800.0, 800.0) # Remove NaN values pyspedas.tdeflag('sinx-clip') # Interpolate pyspedas.tinterpol(['sinx-clip-deflag'], ['sinx'], 'quadratic') # Plot pytplot.ylim('sinx', -1100.0, 1100.0) pytplot.ylim('sinx-clip', -1100.0, 1100.0) pytplot.ylim('sinx-clip-deflag', -1100.0, 1100.0) pytplot.ylim('sinx-clip-deflag-itrp', -1100.0, 1100.0) pytplot.tplot_options('title', 'Interpolation example') pytplot.tplot( ['sinx', 'sinx-clip', 'sinx-clip-deflag', 'sinx-clip-deflag-itrp'])
def ex_gmag(plot=True): """Demonstrate how to use gmag functions.""" # Delete any existing pytplot variables pytplot.del_data() # Define a time rage as a list trange = ['2015-12-31', '2015-12-31'] # Get a list of EPO gmag stations sites = pyspedas.themis.ground.gmag.gmag_list('epo') # Download gmag files and load data into pytplot variables pyspedas.themis.gmag(sites=sites, trange=trange) # Get a list of loaded sites sites_loaded = pyspedas.tnames() # Subtract mean values pyspedas.subtract_average(sites_loaded, '') # Download AE index data # pyspedas.load_data('gmag', time_list, ['idx'], '', '') pyspedas.themis.gmag(sites='idx', trange=trange) # Plot sites_loaded = pytplot.tplot_names() pytplot.tplot_options('title', 'EPO GMAG 2015-12-31') if plot: pytplot.tplot(sites_loaded) # Return 1 as indication that the example finished without problems. return 1
def ex_spikes(plot=True): """Load GMAG data and show how to remove spikes.""" # Delete any existing pytplot variables. pytplot.del_data() # Define a time rage as a list trange = ['2007-03-23', '2007-03-23'] # Download gmag files and load data into pytplot variables. sites = ['ccnv'] var = 'thg_mag_ccnv' pyspedas.themis.gmag(sites=sites, trange=trange, varnames=[var]) pytplot.tplot_options('title', 'GMAG data, thg_mag_ccnv 2007-03-23') # Add spikes to data. data = pytplot.data_quants[var].values dlen = len(data) for i in range(1, 16): s = (1 if random.random() < 0.5 else -1) p1 = int(i * dlen / 16) data[p1, 0] = s * i * 40000 data[p1 + 2000, 1] = s * i * 30000 data[p1 + 4000, 2] = s * i * 20000 pytplot.data_quants[var].values = data # Clean spikes. clean_spikes(var, sub_avg=True) # Plot all variables. if plot: pytplot.tplot(pytplot.tplot_names()) # Return 1 as indication that the example finished without problems. return 1
def ex_avg(plot=True): """Load GMAG data and average over 5 min intervals.""" # Delete any existing pytplot variables. pytplot.del_data() # Define a time rage as a list trange = ['2007-03-23', '2007-03-23'] # Download gmag files and load data into pytplot variables. sites = ['ccnv'] var = 'thg_mag_ccnv' pyspedas.themis.gmag(sites=sites, trange=trange, varnames=[var]) pytplot.tplot_options('title', 'GMAG data, thg_mag_ccnv 2007-03-23') pyspedas.subtract_average(var, median=1) var += '-m' # Five minute average using time dt. avg_data(var, dt=5 * 60.) # Five minute average using width (number of measurements). # Each measurement is 0.5 sec. avg_data(var, width=5 * 60. * 2., new_names=var + '-avg2') # Plot. if plot: pytplot.tplot([var, var + '-avg', var + '-avg2']) # Return 1 as indication that the example finished without problems. return 1
def ex_cotrans(): """Transform state data for THEMIS from GEI to GSE. Load position and velocity from THEMIS. Transform the coordinates to GSE and plot. Notes ----- IDL SPEDAS contains a more extended example: thm_crib_contrans.pro """ trange = ['2007-06-23/00:00:00', '2007-06-23/23:59:59'] probe = 'a' pos_in = "tha_pos" pos_out = "tha_pos_gse" vel_in = "tha_vel" vel_out = "tha_vel_gse" pyspedas.themis.state(probe=probe, trange=trange, time_clip=True, varnames=[pos_in, vel_in]) # Coordinate transformation. cotrans(name_in=pos_in, name_out=pos_out, coord_in="gei", coord_out="gse") cotrans(name_in=vel_in, name_out=vel_out, coord_in="gei", coord_out="gse") # Plot. pytplot.tplot_options('title', 'Themis pos and vel in GEI and GSE') pytplot.options(pos_in, 'ytitle', pos_in) pytplot.options(pos_out, 'ytitle', pos_out) pytplot.options(vel_in, 'ytitle', vel_in) pytplot.options(vel_out, 'ytitle', vel_out) pytplot.tplot([pos_in, vel_in, pos_out, vel_out]) # Return 1 as indication that the example finished without problems. return 1
def ex_spectra(): # Delete any existing pytplot variables pytplot.del_data() # Download THEMIS data for 2015-12-31 pyspedas.load_data('themis', ['2015-12-31'], ['tha'], 'sst', 'l2') # Specify options pytplot.tplot_options('title', 'tha_psif_en_eflux 2015-12-31') pytplot.ylim('tha_psif_en_eflux', 10000.0, 10000000.0) pytplot.options('tha_psif_en_eflux', 'colormap', 'viridis') # Plot spectrogram pytplot.tplot(['tha_psif_en_eflux'])
def ex_omni(): # Print the installed version of pyspedas pyspedas.version() # Delete any existing pytplot variables pytplot.del_data() # Download OMNI data for 2015-12-31 pyspedas.load_data('omni', ['2015-12-31 00:00:00', '2016-01-01 23:59:59'], '', '', '1min') # Plot pytplot.tplot_options('title', 'OMNI flow_speed 2015-12-31 to 2016-01-01') pytplot.tplot(['flow_speed'])
def ex_omni(): # Delete any existing pytplot variables pytplot.del_data() # Download OMNI data for 2015-12-31 trange = ['2015-12-31 00:00:00', '2015-12-31 23:59:59'] pyspedas.omni.load(trange=trange, datatype='1min') # Plot pytplot.tplot_options('title', 'OMNI flow_speed 2015-12-31') pytplot.tplot(['flow_speed']) # Return 1 as indication that the example finished without problems. return 1
def ex_gmag(): # Delete any existing pytplot variables pytplot.del_data() # Define list of dates time_list = ['2015-12-31'] # Get a list of EPO gmag stations sites = pyspedas.gmag_list(group='epo') # Download gmag files and load data into pytplot variables pyspedas.load_data('gmag', time_list, sites, '', '') # Get a list of loaded sites sites_loaded = pyspedas.tplot_names() # Subtact mean values pyspedas.subtract_average(sites_loaded, '') # Download AE index data pyspedas.load_data('gmag', time_list, ['idx'], '', '') # Plot sites_loaded = pyspedas.tplot_names() pytplot.tplot_options('title', 'EPO GMAG 2015-12-31') pytplot.tplot(sites_loaded)
def ex_create(plot=True): """Show how to create and plot pytplot variables.""" # Delete any existing pytplot variables pytplot.del_data() # Create a sin wave plot a = list(range(0, 101)) b = [2.0 / 100.0 * numpy.pi * s for s in a] c = time_float('2017-01-01') x = list() y = list() for i in range(len(b)): x.append(c + 60.0 / (2 * numpy.pi) * 60.0 * b[i]) y.append(1000.0 * numpy.sin(b[i])) # Store data pytplot.store_data('sinx', data={'x': x, 'y': y}) # Apply yclip pyspedas.yclip('sinx', -800.0, 800.0) # Remove NaN values pyspedas.tdeflag('sinx-clip') # Interpolate pyspedas.tinterpol(['sinx-clip-deflag'], 'sinx', 'quadratic') # Plot pytplot.ylim('sinx', -1100.0, 1100.0) pytplot.ylim('sinx-clip', -1100.0, 1100.0) pytplot.ylim('sinx-clip-deflag', -1100.0, 1100.0) pytplot.ylim('sinx-clip-deflag-itrp', -1100.0, 1100.0) pytplot.tplot_options('title', 'Interpolation example') if plot: pytplot.tplot( ['sinx', 'sinx-clip', 'sinx-clip-deflag', 'sinx-clip-deflag-itrp']) # Return 1 as indication that the example finished without problems. return 1
def ex_basic(): # Delete any existing pytplot variables pytplot.del_data() # Download THEMIS state data for 2015-12-31 time_range = ['2015-12-31 00:00:00', '2016-01-01 12:00:00'] pyspedas.load_data('themis', time_range, ['tha'], 'state', 'l1') # Get data into python variables alldata = pytplot.get_data("tha_pos") time = alldata[0] data = alldata[1] # Store a new pytplot variable pytplot.store_data("tha_position", data={'x': time, 'y': data}) # Define the y-axis limits pytplot.ylim('tha_pos', -23000.0, 81000.0) pytplot.ylim('tha_position', -23000.0, 81000.0) pytplot.ylim('tha_vel', -8.0, 12.0) # Give a title to the plot and labels for the y-axis panels. pytplot.tplot_options('title', 'tha position and velocity, 2015-12-31') pytplot.options('tha_pos', 'ytitle', 'Position') pytplot.options('tha_new_vel', 'ytitle', 'Velocity') # Plot position and velocity using the pyqtgraph library (default) pytplot.tplot(["tha_pos", "tha_position", "tha_vel"])
def ex_avg(plot=False): """Load GMAG data and average over 5 min intervals.""" # Delete any existing pytplot variables pytplot.del_data() # Define a time rage as a list trange = ['2007-03-23', '2007-03-23'] # Download gmag files and load data into pytplot variables sites = ['ccnv'] var = 'thg_mag_ccnv' pyspedas.themis.gmag(sites=sites, trange=trange, varnames=[var]) pytplot.tplot_options('title', 'GMAG data, thg_mag_ccnv 2007-03-23') pyspedas.subtract_average(var, median=1) var += '-m' # Five minute average avg_data(var, width=5 * 60) if plot: pytplot.tplot([var, var + '-avg']) # Return 1 as indication that the example finished without problems. return 1
def ex_basic(plot=True): """Download and plot THEMIS data.""" # Delete any existing pytplot variables pytplot.del_data() # Download THEMIS state data for 2015-12-31 time_range = ['2015-12-31 00:00:00', '2016-01-01 12:00:00'] pyspedas.themis.state(probe='a', trange=time_range, time_clip=True) # Get data into python variables alldata = pytplot.get_data("tha_pos") time = alldata[0] data = alldata[1] # Here we could work on the data before saving a new tplot variable. # Store a new pytplot variable pytplot.store_data("tha_position", data={'x': time, 'y': data}) # Define the y-axis limits pytplot.ylim('tha_pos', -23000.0, 81000.0) pytplot.ylim('tha_position', -23000.0, 81000.0) pytplot.ylim('tha_vel', -8.0, 12.0) # Give a title to the plot and labels for the y-axis panels. pytplot.tplot_options('title', 'tha position and velocity, 2015-12-31') pytplot.options('tha_pos', 'ytitle', 'Position') pytplot.options('tha_vel', 'ytitle', 'Velocity') # Plot position and velocity using the pyqtgraph library (default) if plot: pytplot.tplot(["tha_pos", "tha_position", "tha_vel"]) # Plot position and velocity using the bokeh library # pytplot.tplot(["tha_pos", "tha_position", "tha_vel"], bokeh=True) # Return 1 as indication that the example finished without problems. return 1
def ex_dsl2gse(plot=True): """Run dsl2gse.""" time_range = ['2017-03-23 00:00:00', '2017-03-23 23:59:59'] pyspedas.themis.state(probe='a', trange=time_range, get_support_data=True, varnames=['tha_spinras', 'tha_spindec']) pyspedas.themis.fgm(probe='a', trange=time_range, varnames=['tha_fgl_dsl']) dsl2gse('tha_fgl_dsl', 'tha_spinras', 'tha_spindec', 'tha_fgl_gse') # Get the third component only d_in = pytplot.get_data('tha_fgl_dsl') pytplot.store_data('z_dsl', data={'x': d_in[0], 'y': d_in[1][:, 2]}) d_out = pytplot.get_data('tha_fgl_gse') pytplot.store_data('z_gse', data={'x': d_out[0], 'y': d_out[1][:, 2]}) # Plot pytplot.tplot_options('title', 'tha_fgl DSL and GSE, 2017-03-23') if plot: pytplot.tplot(['tha_fgl_dsl', 'tha_fgl_gse', 'z_dsl', 'z_gse']) # Return 1 as indication that the example finished without problems. return 1
def occultation(iuvs, sameplot=True, orbit_num=None, species=None, log=False, title='IUVS Occultation Observations', qt=True): retrieval_names_to_plot = [] retrieval_legend_names = [] dplot = 0 if not isinstance(species, builtins.list): species = [species] if not isinstance(orbit_num, builtins.list): orbit_num = [orbit_num] if orbit_num != [None]: restrict_orbit = True else: restrict_orbit = False if species != [None]: restrict_species = True else: restrict_species = False xmin = [] xmax = [] for orbit in iuvs: for obs in orbit: if obs.lower()[0:-1] == 'occultation': if restrict_orbit and int( orbit[obs]['orbit_number']) not in orbit_num: continue x = np.array(orbit[obs]['retrieval']['ALTITUDE']) for var in orbit[obs]['retrieval']: if var.lower() != "altitude": if restrict_species and var not in species: continue if not np.isnan(orbit[obs]['retrieval'][var]).all(): xmin.append(np.min(x)) xmax.append(np.max(x)) retrieval_names_to_plot.append( obs + '_retrieval_' + var + '_' + str(orbit[obs]['orbit_number'])) retrieval_legend_names.append( 'Orbit ' + str(orbit[obs]['orbit_number']) + ' ' + var + ' retrieval') data = np.array(orbit[obs]['retrieval'][var]) alts = x[~np.isnan(data)] data = data[~np.isnan(data)] pytplot.store_data(retrieval_names_to_plot[dplot], data={ 'x': alts, 'y': data }) pytplot.options(retrieval_names_to_plot[dplot], 'alt', 1) dplot += 1 if dplot == 0: print( "There is no occultation retrieval data in the given IUVS variable" ) return list_of_plots = [] if sameplot: pytplot.store_data('occultation_retrieval', data=retrieval_names_to_plot) list_of_plots.append('occultation_retrieval') pytplot.options('occultation_retrieval', 'alt', 1) if log: pytplot.options('occultation_retrieval', 'ylog', 1) pytplot.options('occultation_retrieval', 'legend_names', retrieval_legend_names) else: i = 0 for d in retrieval_names_to_plot: list_of_plots.append(d) pytplot.options(d, 'ytitle', retrieval_legend_names[i]) if log: pytplot.options(d, 'ylog', 1) i += 1 i = 0 pytplot.tplot_options('alt_range', [np.min(xmin), np.max(xmax)]) pytplot.tplot_options('title', title) pytplot.tplot_options('wsize', [1000, 400 * len(list_of_plots)]) pytplot.tplot(list_of_plots, bokeh=not qt) pytplot.del_data(list_of_plots) return
# In that case, we will get an error message that the remote file does not exist # for that GMAG station. load_data('gmag', time_range, sites, '', '') #################################################################################### # Print the names of the loaded GMAG sites. sites_loaded = tplot_names() #################################################################################### # Subtract the average values for these sites. subtract_average(sites_loaded, '') #################################################################################### # Download AE index data. load_data('gmag', time_range, ['idx'], '', '') #################################################################################### # Get a list of all the loaded GMAG sites plus the AE index data. sites_loaded = tplot_names() #################################################################################### # Plot GMAG and AE index data. # Use the bokeh library - the plots will appear in the web browser. tplot_options('title', 'EPO GMAG 2015-12-31') tplot(sites_loaded, bokeh=True) #################################################################################### # Note: The HTML web page for this example may be missing the plots but this is a # limitation of the platform for this particular gallery - # if you run the python code locally, the plots will appear.
time = alldata[0] data = alldata[1] #################################################################################### # After working with the data, we can store a new pytplot variable. # We can also store our own data in the pytplot object. store_data("tha_new_vel", data={'x': time, 'y': data}) #################################################################################### # Preparing for the plots, we define the y-axis limits for the two panels. ylim('tha_pos', -23000.0, 81000.0) ylim('tha_new_vel', -8.0, 12.0) #################################################################################### # We give a title to the plot and labels for the y-axis panels. tplot_options('title', 'THEMIS tha position and velocity, 2015-12-31') options('tha_pos', 'ytitle', 'Position') options('tha_new_vel', 'ytitle', 'Velocity') #################################################################################### # We plot the position and the velocity using the pyqtgraph library (the default). tplot(["tha_pos", "tha_new_vel"]) #################################################################################### # A new window will open, containing the following plot: # # .. image:: http://themis.ssl.berkeley.edu/images/pyspedas_demo1.png # :alt: Themis tha position and velocity # ####################################################################################
def plot(kp, parameter=None, time=None, errors=None, SamePlot=True, list=False, title='', qt=True): ''' Plot the provided data as a time series. For now, do not accept any error bar information. If time is not provided plot entire data set. Input: kp: insitu kp data structure/dictionary read from file(s) Time: Two-element list of strings or integers indicating the range of Time to be plotted. At present, there are no checks on whether provided Times are within provided data Parameter: The parameter(s) to be plotted. Can be provided as integers (by index) or strings (by name: inst.obs). If a single parameter is provided, it must be an int or str. If several are provided it must be a list. A list may contain a mixture of data types. Errors: **Not Yet Implemented** Will be the Parameter(s) to use for the generation of error bars in the created plots. Since each inst.obs *may* define its own unique useage of the 'quality flag', this will be a parameter-dependent determination, requiring an add'l routine. SamePlot: if True, put all curves on same axes if False, generate new axes for each plot SubPlot: if True, stack plots with common x axis if False and nplots > 1, make several distinct plots Output: None -> Generates plot(s) as requested. But since there is no plot object returned, can not alter any plot subsequently (yet) ToDo: Provide mechanism for calculating and plotting error bars ''' if list: x = param_list(kp) for param in x: print(param) return #Check for orbit num rather than time string if isinstance(time, builtins.list): if isinstance(time[0], int): time = orbit_time(time[0], time[1]) elif isinstance(time, int): time = orbit_time(time) # Check existence of parameter if parameter == None: print("Must provide an index (or name) for param to be plotted.") return # Store instrument and observation of parameter(s) in lists inst = [] obs = [] if type(parameter) is int or type(parameter) is str: a, b = get_inst_obs_labels(kp, parameter) inst.append(a) obs.append(b) nparam = 1 else: nparam = len(parameter) for param in parameter: a, b = get_inst_obs_labels(kp, param) inst.append(a) obs.append(b) inst_obs = builtins.list(zip(inst, obs)) # Cycle through the parameters, plotting each according to # the given keywords # iplot = 1 # subplot indexes on 1 y_list = [] legend_names = [] for inst_temp, obs_temp in inst_obs: # First, generate the dependent array from data y = kp[inst_temp][obs_temp] if SamePlot: y_list.append(y) legend_names.append(obs_temp) else: pytplot.store_data(obs_temp, data={'x': kp['Time'], 'y': y}) # Add descriptive plot title pytplot.options(obs_temp, 'ytitle', '%s.%s' % (inst, obs)) # Increment plot number iplot = iplot + 1 if time is not None: pytplot.xlim(time[0], time[1]) if SamePlot: pytplot_name = ''.join(legend_names) result = pd.concat(y_list, axis=1, join_axes=[y_list[0].index]) pytplot.store_data(pytplot_name, data={'x': kp['Time'], 'y': result}) pytplot.options(pytplot_name, 'legend_names', legend_names) pytplot.tplot_options('title', title) pytplot.tplot_options('wsize', [1000, 300]) pytplot.tplot(pytplot_name, bokeh=not qt) pytplot.del_data(pytplot_name) else: pytplot.tplot_options('title', title) pytplot.tplot_options('wsize', [1000, 300 * (iplot - 1)]) pytplot.tplot(obs, bokeh=not qt) pytplot.del_data(obs) return
def map2d(kp, parameter=None, time=None, list=False, subsolar=False, mso=False, basemap=None, alpha=None, title='MAVEN Mars', qt=True, exec_qt=True): ''' Produces a 2D map of Mars, either in the planetocentric or MSO coordinate system, with the MAVEN orbital projection and a variety of basemaps. Spacecraft orbital path may be colored by a given insitu KP data value Parameters: kp : dict insitu kp data structure/dictionary read from file(s) parameter : list of str/int The parameter(s) to be plotted. Can be provided as integers (by index) or strings (by name: inst.obs). If a single parameter is provided, it must be an int or str. If several are provided it must be a list. A list may contain a mixture of data types. time : list of str Two-element list of strings or integers indicating the range of Time to be plotted. At present, there are no checks on whether provided Times are within provided data color_table : str Specifies color table to use for plotting subsolar : bool Plot path of subsolar point mso : bool Plot using MSO map projection map_limit : list Set the bounding box on the map in lat/lon coordinates [x0,y0,x1,y1] basemap : str Name of the basemap on which the spacecraft data with be overlaid. Choices are • ‘mdim’: Mars Digital Image Model • ‘mola’: Mars Topography (color) • ‘mola_bw’: Mars Topography (black and white) • ‘mag’: Mars Crustal Magnetism • ‘<dir_path>/file.png’: User-defined basemap sameplot : bool if True, put all curves on same axes if False, generate new axes for each plot list : bool Lists all Key Parameters instead of plotting title : str The Title to give the plot ylog : bool Displays the log of the y axis qt : bool If true, plots with qt. Else creates an HTML page with bokeh. exec_qt : bool If False, does not run the event loop for pyqtgraph. Returns : None Examples: >>> # Plot spacecraft altitude along MAVEN surface orbital track. >>> pydivide.map2d(insitu, 'spacecraft.altitude') >>> # Plot spacecraft altitude along MAVEN surface orbital track using MOLA altimetry basemap; plot subsolar point path. >>> pydivide.map2d(insitu, 'spacecraft.altitude', basemap='mola', subsolar=True) ''' if list: x = param_list(kp) for param in x: print(param) return # Check for orbit num rather than time string if isinstance(time, builtins.list): if isinstance(time[0], int): time = orbit_time(time[0], time[1]) elif isinstance(time, int): time = orbit_time(time) # Check existence of parameter if parameter is None: print("Must provide an index (or name) for param to be plotted.") return # Store instrument and observation of parameter(s) in lists inst = [] obs = [] if type(parameter) is int or type(parameter) is str: a, b = get_inst_obs_labels(kp, parameter) inst.append(a) obs.append(b) nparam = 1 else: nparam = len(parameter) for param in parameter: a, b = get_inst_obs_labels(kp, param) inst.append(a) obs.append(b) inst_obs = builtins.list(zip(inst, obs)) # Check the time variable if time is not None: kp = range_select(kp, time) # Generate the altitude array if mso: x = kp['SPACECRAFT']['MSO_X'].values y = kp['SPACECRAFT']['MSO_Y'].values z = kp['SPACECRAFT']['MSO_Z'].values r = np.sqrt((x**2) + (y**2) + (z**2)) lat = (90 - np.arccos(z / r) * (180 / math.pi)) lon = (np.arctan2(y, x) * (180 / math.pi)) + 180 else: lon = kp['SPACECRAFT']['SUB_SC_LONGITUDE'] lat = kp['SPACECRAFT']['SUB_SC_LATITUDE'] alt = kp['SPACECRAFT']['ALTITUDE'] # Cycle through the parameters, plotting each according to # the given keywords names_to_plot = [] iplot = 0 # subplot indexes on 1 for inst, obs in inst_obs: # # First, generate the dependent array from data y = kp[inst][obs] if subsolar and not mso: pytplot.store_data('sc_lon', data={'x': kp['Time'], 'y': lon}) pytplot.store_data('sc_lat', data={'x': kp['Time'], 'y': lat}) pytplot.store_data('%s.%s' % (inst, obs), data={ 'x': kp['Time'], 'y': y }) pytplot.options('%s.%s' % (inst, obs), 'link', ['lon', 'sc_lon']) pytplot.options('%s.%s' % (inst, obs), 'link', ['lat', 'sc_lat']) pytplot.options('%s.%s' % (inst, obs), 'map', 1) pytplot.store_data( 'ss_lon', data={ 'x': kp['Time'], 'y': kp['SPACECRAFT']['SUBSOLAR_POINT_GEO_LONGITUDE'] }) pytplot.store_data( 'ss_lat', data={ 'x': kp['Time'], 'y': kp['SPACECRAFT']['SUBSOLAR_POINT_GEO_LATITUDE'] }) pytplot.store_data('subsolar', data={'x': kp['Time'], 'y': alt}) pytplot.options('subsolar', 'link', ['lon', 'ss_lon']) pytplot.options('subsolar', 'link', ['lat', 'ss_lat']) pytplot.options('subsolar', 'map', 1) names_to_plot.append('%s.%s.%s' % (inst, obs, 'subsolar')) pytplot.store_data(names_to_plot[iplot], data=['%s.%s' % (inst, obs), 'subsolar']) pytplot.options(names_to_plot[iplot], 'map', 1) pytplot.options(names_to_plot[iplot], 'colormap', ['magma', 'yellow']) else: names_to_plot.append('%s.%s' % (inst, obs)) pytplot.store_data('sc_lon', data={'x': kp['Time'], 'y': lon}) pytplot.store_data('sc_lat', data={'x': kp['Time'], 'y': lat}) pytplot.store_data(names_to_plot[iplot], data={ 'x': kp['Time'], 'y': y }) pytplot.options(names_to_plot[iplot], 'link', ['lon', 'sc_lon']) pytplot.options(names_to_plot[iplot], 'link', ['lat', 'sc_lat']) pytplot.options(names_to_plot[iplot], 'map', 1) if basemap: if basemap == 'mola': map_file = os.path.join(os.path.dirname(__file__), 'basemaps', 'MOLA_color_2500x1250.jpg') elif basemap == 'mola_bw': map_file = os.path.join(os.path.dirname(__file__), 'basemaps', 'MOLA_BW_2500x1250.jpg') elif basemap == 'mdim': map_file = os.path.join(os.path.dirname(__file__), 'basemaps', 'MDIM_2500x1250.jpg') elif basemap == 'elevation': map_file = os.path.join(os.path.dirname(__file__), 'basemaps', 'MarsElevation_2500x1250.jpg') elif basemap == 'mag': map_file = os.path.join(os.path.dirname(__file__), 'basemaps', 'MAG_Connerny_2005.jpg') else: map_file = basemap pytplot.options(names_to_plot[iplot], 'basemap', map_file) if alpha: pytplot.options(names_to_plot[iplot], 'alpha', alpha) iplot += 1 pytplot.tplot_options('title', title) pytplot.tplot_options('wsize', [1000, 500 * iplot]) pytplot.tplot(names_to_plot, bokeh=not qt, exec_qt=exec_qt) pytplot.del_data('ss_lon') pytplot.del_data('ss_lat') pytplot.del_data('sc_lon') pytplot.del_data('sc_lat') pytplot.del_data(names_to_plot) return
def altplot(kp, parameter=None, time=None, errors=None, sameplot=True, list=False, title='Altitude Plot', ylog=False, qt=True): ''' Plot the provided data plotted against spacecraft altitude. If time is not provided plot entire data set. Parameters: kp : dict insitu kp data structure/dictionary read from file(s) parameter : list of str/int The parameter(s) to be plotted. Can be provided as integers (by index) or strings (by name: inst.obs). If a single parameter is provided, it must be an int or str. If several are provided it must be a list. A list may contain a mixture of data types. time : list of str Two-element list of strings or integers indicating the range of Time to be plotted. At present, there are no checks on whether provided Times are within provided data sameplot : bool if True, put all curves on same axes if False, generate new axes for each plot list : bool Lists all Key Parameters instead of plotting title : str The Title to give the plot ylog : bool Displays the log of the y axis qt : bool If true, plots with qt. Else creates an HTML page with bokeh. Returns: None Examples: >>> # Plot LPW.ELECTRON_DENSITY against spacecraft altitude. >>> pydivide.altplot(insitu, parameter=['LPW.ELECTRON_DENSITY','MAG.MSO_Y'], qt=False, ylog=True) ''' if list: x = param_list(kp) for param in x: print(param) return # Check for orbit num rather than time string if isinstance(time, builtins.list): if isinstance(time[0], int): time = orbit_time(time[0], time[1]) elif isinstance(time, int): time = orbit_time(time) # Check existence of parameter if parameter is None: print("Must provide an index (or name) for param to be plotted.") return # Store instrument and observation of parameter(s) in lists inst = [] obs = [] if type(parameter) is int or type(parameter) is str: a, b = get_inst_obs_labels(kp, parameter) inst.append(a) obs.append(b) else: for param in parameter: a, b = get_inst_obs_labels(kp, param) inst.append(a) obs.append(b) inst_obs = builtins.list(zip(inst, obs)) # Check the time variable if time is not None: kp = range_select(kp, time) # Generate the altitude array z = [] index = 0 for i in kp['TimeString']: z.append(kp['SPACECRAFT']['ALTITUDE'][index]) index += 1 pytplot.store_data('sc_alt', data={'x': kp['Time'], 'y': z}) # Cycle through the parameters, plotting each according to # the given keywords names_to_plot = [] legend_names = [] iplot = 0 # subplot indexes on 1 for inst, obs in inst_obs: # First, generate the dependent array from data y = [] index = 0 for i in kp['TimeString']: y.append(kp[inst][obs][index]) index += 1 names_to_plot.append('%s.%s' % (inst, obs)) legend_names.append(obs) pytplot.store_data(names_to_plot[iplot], data={ 'x': kp['Time'], 'y': y }) pytplot.options(names_to_plot[iplot], 'link', ['alt', 'sc_alt']) pytplot.options(names_to_plot[iplot], 'alt', 1) pytplot.options(names_to_plot[iplot], 'ylog', ylog) iplot += 1 if sameplot: pytplot_name = ','.join(legend_names) pytplot.store_data(pytplot_name, data=names_to_plot) pytplot.options(pytplot_name, 'alt', 1) pytplot.options(pytplot_name, 'ylog', ylog) pytplot.options(pytplot_name, 'legend_names', legend_names) pytplot.tplot_options('title', title) pytplot.tplot_options('wsize', [1000, 300]) pytplot.tplot(pytplot_name, bokeh=not qt) pytplot.del_data(pytplot_name) else: pytplot.tplot_options('title', title) pytplot.tplot_options('wsize', [1000, 300 * (iplot - 1)]) pytplot.tplot(names_to_plot, bokeh=not qt) pytplot.del_data(names_to_plot) return
pytplot.options('swia_vel', 'thick', 4) # Y-axis Label pytplot.options('swia_vel', 'ytitle', 'speed (km/s)') # Vertical Plot Bounds pytplot.options('SEP_1_ION', 'yrange', [5, 5000]) # Panel Size pytplot.options(['mag', 'swia_den', 'swia_vel'], 'panel_size', 0.5) ############################################################################## # Tplot Options # ------------- # pytplot.tplot_options('option', 'option_value') can be used to change plotting options for the tplot routine. # These control options affect all panels in a plot. # Title pytplot.tplot_options('title', 'All Plots') # Window Size pytplot.tplot_options('wsize', [800, 800]) # Adding a region of interest (ROI) # pytplot will add a ROI (indicated by two vertical red lines, with grey shading in between) # to all plot via specifying the 'roi' option pytplot.tplot_options('roi', ['2016-06-20 11:12:24', '2016-06-20 14:12:00']) # Another option available in tplot_options is to specify the number of seconds with consecutive nan # values allowed before no interpolation should occur pytplot.tplot_options('data_gap', 80) ############################################################################## # Displaying data using tplot # ---------------------------
def occultation(iuvs, sameplot=True, orbit_num=None, species=None, log=False, title='IUVS Occultation Observations', qt=True, exec_qt=True): ''' Plot IUVS Stellar Occultation data against spacecraft altitude. Parameters: iuvs : dict iuvs kp data structure/dictionary read from file(s) orbit_num : list of int The orbit numbers to plot from the IUVS data structure species: list of str The species to plot. Values can be "CO2", "O2", "O3", and "Temp." sameplot : bool if True, put all curves on same axes if False, generate new axes for each plot list : bool Lists all Key Parameters instead of plotting title : str The Title to give the plot ylog : bool Displays the log of the y axis qt : bool If true, plots with qt. Else creates an HTML page with bokeh. exec_qt : bool If False, does not run the event loop for pyqtgraph. Returns : None Examples: >>> # Plot CO2 density vs spacecraft altitude. >>> insitu, iuvs = pydivide.read(input_time=['2016-01-01', '2016-01-31']) >>> pydivide.occultation(iuvs, log=True, species=['CO2'], qt=False) ''' retrieval_names_to_plot = [] retrieval_legend_names = [] dplot = 0 if not isinstance(species, builtins.list): species = [species] if not isinstance(orbit_num, builtins.list): orbit_num = [orbit_num] if orbit_num != [None]: restrict_orbit = True else: restrict_orbit = False if species != [None]: restrict_species = True else: restrict_species = False xmin = [] xmax = [] for orbit in iuvs: for obs in orbit: if obs.lower()[0:-1] == 'occultation': if restrict_orbit and int( orbit[obs]['orbit_number']) not in orbit_num: continue x = np.array(orbit[obs]['retrieval']['ALTITUDE']) for var in orbit[obs]['retrieval']: if var.lower() != "altitude": if restrict_species and var not in species: continue if not np.isnan(orbit[obs]['retrieval'][var]).all(): xmin.append(np.min(x)) xmax.append(np.max(x)) retrieval_names_to_plot.append( obs + '_retrieval_' + var + '_' + str(orbit[obs]['orbit_number'])) retrieval_legend_names.append( 'Orbit ' + str(orbit[obs]['orbit_number']) + ' ' + var + ' retrieval') data = np.array(orbit[obs]['retrieval'][var]) alts = x[~np.isnan(data)] data = data[~np.isnan(data)] fake_times = np.arange(len(alts)) pytplot.store_data(retrieval_names_to_plot[dplot], data={ 'x': fake_times, 'y': data }) pytplot.store_data(retrieval_names_to_plot[dplot] + "_alt", data={ 'x': fake_times, 'y': alts }) pytplot.options( retrieval_names_to_plot[dplot], 'link', [ 'alt', retrieval_names_to_plot[dplot] + '_alt' ]) pytplot.options(retrieval_names_to_plot[dplot], 'alt', 1) dplot += 1 if dplot == 0: print( "There is no occultation retrieval data in the given IUVS variable" ) return list_of_plots = [] if sameplot: pytplot.store_data('occultation_retrieval', data=retrieval_names_to_plot) list_of_plots.append('occultation_retrieval') pytplot.options('occultation_retrieval', 'alt', 1) if log: pytplot.options('occultation_retrieval', 'ylog', 1) pytplot.options('occultation_retrieval', 'legend_names', retrieval_legend_names) else: i = 0 for d in retrieval_names_to_plot: list_of_plots.append(d) pytplot.options(d, 'ytitle', retrieval_legend_names[i]) if log: pytplot.options(d, 'ylog', 1) i += 1 i = 0 pytplot.tplot_options('alt_range', [np.min(xmin), np.max(xmax)]) pytplot.tplot_options('title', title) pytplot.tplot_options('wsize', [1000, 400 * len(list_of_plots)]) pytplot.tplot(list_of_plots, bokeh=not qt, exec_qt=exec_qt, window_name='PYIDIVDE_Occultation_Plot') pytplot.del_data(list_of_plots) return
def plot(kp, parameter=None, time=None, errors=None, sameplot=True, list=False, title='', qt=True, exec_qt=True, log=False): ''' Plot time-series data from insitu data structure. Parameters: kp : dict insitu kp data structure/dictionary read from file(s) parameter : list of str/int The parameter(s) to be plotted. Can be provided as integers (by index) or strings (by name: inst.obs). If a single parameter is provided, it must be an int or str. If several are provided it must be a list. A list may contain a mixture of data types. time : list of str Two-element list of strings or integers indicating the range of Time to be plotted. At present, there are no checks on whether provided Times are within provided data sameplot : bool if True, put all curves on same axes if False, generate new axes for each plot list : bool Lists all Key Parameters instead of plotting title : str The Title to give the plot qt : bool If true, plots with qt. Else creates an HTML page with bokeh. exec_qt : bool If False, does not run the event loop for pyqtgraph. Returns : None Examples: >>> # Plot SWIA H+ density. >>> pydivide.plot(insitu,parameter='swia.hplus_density') >>> # Plot SWIA H+ density and altitude in the same window. >>> pydivide.plot(insitu,parameter=['swia.hplus_density', 'spacecraft.altitude'],sameplot=True) ''' if list: x = param_list(kp) for param in x: print(param) return # Check for orbit num rather than time string if isinstance(time, builtins.list): if isinstance(time[0], int): time = orbit_time(time[0], time[1]) elif isinstance(time, int): time = orbit_time(time) # Check existence of parameter if parameter is None: print("Must provide an index (or name) for param to be plotted.") return # Store instrument and observation of parameter(s) in lists inst = [] obs = [] if type(parameter) is int or type(parameter) is str: a, b = get_inst_obs_labels(kp, parameter) inst.append(a.upper()) obs.append(b.upper()) nparam = 1 else: nparam = len(parameter) for param in parameter: a, b = get_inst_obs_labels(kp, param) inst.append(a.upper()) obs.append(b.upper()) inst_obs = builtins.list(zip(inst, obs)) # Cycle through the parameters, plotting each according to # the given keywords # iplot = 1 # subplot indexes on 1 legend_names = [] y_list = pydivide.tplot_varcreate(kp, instruments=inst, observations=obs) for inst_temp, obs_temp in inst_obs: legend_names.append(obs_temp) iplot += 1 if time is not None: pytplot.xlim(time[0], time[1]) if sameplot: pytplot_name = ''.join(legend_names) pytplot.store_data(pytplot_name, data=y_list) pytplot.options(pytplot_name, 'legend_names', legend_names) pytplot.options(pytplot_name, 'ylog', log) pytplot.link(pytplot_name, "mvn_kp::spacecraft::altitude", link_type='alt') pytplot.link(pytplot_name, "mvn_kp::spacecraft::mso_x", link_type='x') pytplot.link(pytplot_name, "mvn_kp::spacecraft::mso_y", link_type='y') pytplot.link(pytplot_name, "mvn_kp::spacecraft::mso_z", link_type='z') pytplot.link(pytplot_name, "mvn_kp::spacecraft::geo_x", link_type='geo_x') pytplot.link(pytplot_name, "mvn_kp::spacecraft::geo_y", link_type='geo_y') pytplot.link(pytplot_name, "mvn_kp::spacecraft::geo_z", link_type='geo_z') pytplot.link(pytplot_name, "mvn_kp::spacecraft::sub_sc_longitude", link_type='lon') pytplot.link(pytplot_name, "mvn_kp::spacecraft::sub_sc_latitude", link_type='lat') pytplot.tplot_options('title', title) pytplot.tplot_options('wsize', [1000, 300]) pytplot.tplot(pytplot_name, bokeh=not qt, exec_qt=exec_qt, window_name='PYDIVIDE_PLOT') else: pytplot.tplot_options('title', title) pytplot.tplot_options('wsize', [1000, 300 * (iplot - 1)]) pytplot.tplot(y_list, bokeh=not qt, exec_qt=exec_qt, window_name='PYDIVIDE_PLOT') return
def periapse(iuvs, sameplot=True, density=True, radiance=True, orbit_num=None, species=None, obs_num=None, log=False, title='IUVS Periapse Observations', qt=True, exec_qt=True): ''' Plot IUVS Limb Scan data against spacecraft altitude. Parameters: iuvs : dict iuvs kp data structure/dictionary read from file(s) orbit_num : list of int The orbit numbers to plot from the IUVS data structure species : list of str The species to plot. Values can be Density - CO2, CO2+, O, N2, C, N, H Radiance - CO2pUVD, CO, H, O_1304, O_1356, O_2972, C_1561, C_1657, N_1493, N2, NO radiance : bool If true, plots the radiance density : bool If true, plots the density sameplot : bool if True, put all curves on same axes if False, generate new axes for each plot title : str The Title to give the plot ylog : bool Displays the log of the y axis qt : bool If true, plots with qt. Else creates an HTML page with bokeh. exec_qt : bool If False, does not run the event loop for pyqtgraph. Returns : None Examples: >>> # Plot CO2 density vs spacecraft altitude. >>> insitu, iuvs = pydivide.read(input_time=['2016-02-01', '2016-02-28']) >>> pydivide.periapse(iuvs, species='CO', orbit_num=2726, log=True, density=False, radiance=True, qt=False) ''' density_names_to_plot = [] density_legend_names = [] dplot = 0 radiance_names_to_plot = [] radiance_legend_names = [] rplot = 0 if not isinstance(species, builtins.list): species = [species] if not isinstance(orbit_num, builtins.list): orbit_num = [orbit_num] if not isinstance(obs_num, builtins.list): obs_num = [obs_num] if orbit_num != [None]: restrict_orbit = True else: restrict_orbit = False if species != [None]: restrict_species = True else: restrict_species = False if obs_num != [None]: restrict_obs = True else: restrict_obs = False xmin = [] xmax = [] for orbit in iuvs: for obs in orbit: if obs.lower()[0:-1] == 'periapse': if restrict_obs and int(obs[-1]) not in obs_num: continue if restrict_orbit and int( orbit[obs]['orbit_number']) not in orbit_num: continue if density: x = np.array(orbit[obs]['density']['ALTITUDE']) for var in orbit[obs]['density']: if var.lower() != "altitude": if restrict_species and var not in species: continue if not np.isnan(orbit[obs]['density'][var]).all(): xmin.append(np.min(x)) xmax.append(np.max(x)) density_names_to_plot.append( obs + '_density_' + var + '_' + str(orbit[obs]['orbit_number'])) density_legend_names.append( 'Orbit ' + str(orbit[obs]['orbit_number']) + ' observation ' + str(obs[-1]) + ' ' + var + ' density') data = np.array(orbit[obs]['density'][var]) alts = x[~np.isnan(data)] data = data[~np.isnan(data)] fake_times = np.arange(len(alts)) pytplot.store_data( density_names_to_plot[dplot], data={ 'x': fake_times, 'y': data }) pytplot.store_data( density_names_to_plot[dplot] + '_alt', data={ 'x': fake_times, 'y': alts }) pytplot.options( density_names_to_plot[dplot], 'link', [ 'alt', density_names_to_plot[dplot] + '_alt' ]) pytplot.options(density_names_to_plot[dplot], 'alt', 1) dplot += 1 if radiance: x = np.array(orbit[obs]['radiance']['ALTITUDE']) for var in orbit[obs]['radiance']: if var.lower() != "altitude": if restrict_species and var not in species: continue if not np.isnan(orbit[obs]['radiance'][var]).all(): xmin.append(np.min(x)) xmax.append(np.max(x)) radiance_names_to_plot.append( obs + '_radiance_' + var + '_' + str(orbit[obs]['orbit_number'])) radiance_legend_names.append( 'Orbit ' + str(orbit[obs]['orbit_number']) + ' observation ' + str(obs[-1]) + ' ' + var + ' radiance') data = np.array(orbit[obs]['radiance'][var]) alts = x[~np.isnan(data)] data = data[~np.isnan(data)] fake_times = np.arange(len(alts)) pytplot.store_data( radiance_names_to_plot[rplot], data={ 'x': fake_times, 'y': data }) pytplot.store_data( radiance_names_to_plot[rplot] + '_alt', data={ 'x': fake_times, 'y': alts }) pytplot.options( radiance_names_to_plot[rplot], 'link', [ 'alt', radiance_names_to_plot[rplot] + "_alt" ]) pytplot.options(radiance_names_to_plot[rplot], 'alt', 1) rplot += 1 if radiance and rplot == 0: print("There is no periapse radiance data in the given IUVS variable") radiance = False if density and dplot == 0: print("There is no periapse density data in the given IUVS variable") density = False list_of_plots = [] if sameplot: if density: pytplot.store_data('periapse_density', data=density_names_to_plot) list_of_plots.append('periapse_density') pytplot.options('periapse_density', 'alt', 1) if log: pytplot.options('periapse_density', 'ylog', 1) pytplot.options('periapse_density', 'legend_names', density_legend_names) if radiance: pytplot.store_data('periapse_radiance', data=radiance_names_to_plot) list_of_plots.append('periapse_radiance') pytplot.options('periapse_radiance', 'alt', 1) if log: pytplot.options('periapse_radiance', 'ylog', 1) pytplot.options('periapse_radiance', 'legend_names', radiance_legend_names) else: i = 0 for d in density_names_to_plot: list_of_plots.append(d) pytplot.options(d, 'ytitle', density_legend_names[i]) if log: pytplot.options(d, 'ylog', 1) i += 1 i = 0 for r in radiance_names_to_plot: list_of_plots.append(r) pytplot.options(r, 'ytitle', radiance_legend_names[i]) if log: pytplot.options(r, 'ylog', 1) i += 1 pytplot.tplot_options('alt_range', [np.min(xmin), np.max(xmax)]) pytplot.tplot_options('title', title) pytplot.tplot_options('wsize', [1000, 400 * len(list_of_plots)]) pytplot.tplot(list_of_plots, bokeh=not qt, exec_qt=exec_qt, window_name='PYIDIVDE_Periapse_Plot') pytplot.del_data(list_of_plots) return
def corona(iuvs, sameplot=True, density=True, radiance=True, orbit_num=None, species=None, log=False, title='IUVS Corona Observations', qt=True): density_names_to_plot = [] density_legend_names = [] dplot = 0 radiance_names_to_plot = [] radiance_legend_names = [] rplot = 0 if not isinstance(species, builtins.list): species = [species] if not isinstance(orbit_num, builtins.list): orbit_num = [orbit_num] if orbit_num != [None]: restrict_orbit = True else: restrict_orbit = False if species != [None]: restrict_species = True else: restrict_species = False xmin = [] xmax = [] for orbit in iuvs: for obs in orbit: if obs.lower() == 'corona_lores_high': if restrict_orbit and int( orbit[obs]['orbit_number']) not in orbit_num: continue if density: x = np.array(orbit[obs]['density']['ALTITUDE']) for var in orbit[obs]['density']: if var.lower() != "altitude": if restrict_species and var not in species: continue if not np.isnan(orbit[obs]['density'][var]).all(): xmin.append(np.min(x)) xmax.append(np.max(x)) density_names_to_plot.append( obs + '_density_' + var + '_' + str(orbit[obs]['orbit_number'])) density_legend_names.append( 'Orbit ' + str(orbit[obs]['orbit_number']) + ' ' + var + ' density') data = np.array(orbit[obs]['density'][var]) alts = x[~np.isnan(data)] data = data[~np.isnan(data)] fake_times = np.arange(len(alts)) pytplot.store_data( density_names_to_plot[dplot], data={ 'x': fake_times, 'y': data }) pytplot.store_data( density_names_to_plot[dplot] + "_alt", data={ 'x': fake_times, 'y': alts }) pytplot.options( density_names_to_plot[dplot], "link", [ 'alt', density_names_to_plot[dplot] + "_alt" ]) pytplot.options(density_names_to_plot[dplot], 'alt', 1) pytplot.options(density_names_to_plot[dplot], 'alt', 1) dplot += 1 if radiance: x = np.array(orbit[obs]['radiance']['ALTITUDE']) for var in orbit[obs]['radiance']: if var.lower() != "altitude": if restrict_species and var not in species: continue if not np.isnan(orbit[obs]['radiance'][var]).all(): xmin.append(np.min(x)) xmax.append(np.max(x)) radiance_names_to_plot.append( obs + '_radiance_' + var + '_' + str(orbit['corona_lores_high'] ['orbit_number'])) radiance_legend_names.append( 'Orbit ' + str(orbit[obs]['orbit_number']) + ' ' + var + ' radiance') data = np.array(orbit[obs]['radiance'][var]) alts = x[~np.isnan(data)] data = data[~np.isnan(data)] fake_times = np.arange(len(alts)) pytplot.store_data( radiance_names_to_plot[rplot], data={ 'x': fake_times, 'y': data }) pytplot.store_data( radiance_names_to_plot[rplot] + "_alt", data={ 'x': fake_times, 'y': alts }) pytplot.options( radiance_names_to_plot[rplot], "link", [ 'alt', radiance_names_to_plot[rplot] + "_alt" ]) pytplot.options(radiance_names_to_plot[rplot], 'alt', 1) rplot += 1 if radiance and rplot == 0: print("There is no corona radiance data in the given IUVS variable") radiance = False if density and dplot == 0: print("There is no corona density data in the given IUVS variable") density = False list_of_plots = [] if sameplot: if density: pytplot.store_data('corona_lores_high_density', data=density_names_to_plot) list_of_plots.append('corona_lores_high_density') pytplot.options('corona_lores_high_density', 'alt', 1) if log: pytplot.options('corona_lores_high_density', 'ylog', 1) pytplot.options('corona_lores_high_density', 'legend_names', density_legend_names) if radiance: pytplot.store_data('corona_lores_high_radiance', data=radiance_names_to_plot) list_of_plots.append('corona_lores_high_radiance') pytplot.options('corona_lores_high_radiance', 'alt', 1) if log: pytplot.options('corona_lores_high_radiance', 'ylog', 1) pytplot.options('corona_lores_high_radiance', 'legend_names', radiance_legend_names) else: i = 0 for d in density_names_to_plot: list_of_plots.append(d) pytplot.options(d, 'ytitle', density_legend_names[i]) if log: pytplot.options(d, 'ylog', 1) i += 1 i = 0 for r in radiance_names_to_plot: list_of_plots.append(r) pytplot.options(r, 'ytitle', radiance_legend_names[i]) if log: pytplot.options(r, 'ylog', 1) i += 1 pytplot.tplot_options('alt_range', [np.min(xmin), np.max(xmax)]) pytplot.tplot_options('title', title) pytplot.tplot_options('wsize', [1000, 400 * len(list_of_plots)]) pytplot.tplot(list_of_plots, bokeh=not qt) pytplot.del_data(list_of_plots) return
def altplot(kp, parameter=None, time=None, errors=None, SamePlot=True, list=False, title='Altitude Plot', qt=True): ''' Plot the provided data plotted against spacecraft altitude. For now, do not accept any error bar information. If time is not provided plot entire data set. Input: kp: insitu kp data structure/dictionary read from file(s) Time: Two-element list of strings or integers indicating the range of Time to be plotted. At present, there are no checks on whether provided Times are within provided data Parameter: The parameter(s) to be plotted. Can be provided as integers (by index) or strings (by name: inst.obs). If a single parameter is provided, it must be an int or str. If several are provided it must be a list. A list may contain a mixture of data types. Errors: **Not Yet Implemented** Will be the Parameter(s) to use for the generation of error bars in the created plots. Since each inst.obs *may* define its own unique useage of the 'quality flag', this will be a parameter-dependent determination, requiring an add'l routine. SamePlot: if True, put all curves on same axes if False, generate new axes for each plot SubPlot: if True, stack plots with common x axis if False and nplots > 1, make several distinct plots Output: None -> Generates plot(s) as requested. But since there is no plot object returned, can not alter any plot subsequently (yet) ToDo: Provide mechanism for calculating and plotting error bars Return plot object(s) for subsequent editing? ''' if list: x = param_list(kp) for param in x: print(param) return #Check for orbit num rather than time string if isinstance(time, builtins.list): if isinstance(time[0], int): time = orbit_time(time[0], time[1]) elif isinstance(time, int): time = orbit_time(time) # Check existence of parameter if parameter == None: print("Must provide an index (or name) for param to be plotted.") return # Store instrument and observation of parameter(s) in lists inst = [] obs = [] if type(parameter) is int or type(parameter) is str: a, b = get_inst_obs_labels(kp, parameter) inst.append(a) obs.append(b) else: for param in parameter: a, b = get_inst_obs_labels(kp, param) inst.append(a) obs.append(b) inst_obs = builtins.list(zip(inst, obs)) # Check the time variable if time != None: kp = range_select(kp, time) # Generate the altitude array z = [] index = 0 for i in kp['TimeString']: z.append(kp['SPACECRAFT']['ALTITUDE'][index]) index = index + 1 pytplot.store_data('sc_alt', data={'x': kp['Time'], 'y': z}) # Cycle through the parameters, plotting each according to # the given keywords # names_to_plot = [] legend_names = [] iplot = 0 # subplot indexes on 1 for inst, obs in inst_obs: # # First, generate the dependent array from data y = [] index = 0 for i in kp['TimeString']: y.append(kp[inst][obs][index]) index = index + 1 names_to_plot.append('%s.%s' % (inst, obs)) legend_names.append(obs) pytplot.store_data(names_to_plot[iplot], data={ 'x': kp['Time'], 'y': y }) pytplot.options(names_to_plot[iplot], 'link', ['alt', 'sc_alt']) pytplot.options(names_to_plot[iplot], 'alt', 1) iplot = iplot + 1 if SamePlot: pytplot_name = ','.join(legend_names) pytplot.store_data(pytplot_name, data=names_to_plot) pytplot.options(pytplot_name, 'alt', 1) pytplot.options(pytplot_name, 'legend_names', legend_names) pytplot.tplot_options('title', title) pytplot.tplot_options('wsize', [1000, 300]) pytplot.tplot(pytplot_name, bokeh=not qt) pytplot.del_data(pytplot_name) else: pytplot.tplot_options('title', title) pytplot.tplot_options('wsize', [1000, 300 * (iplot - 1)]) pytplot.tplot(names_to_plot, bokeh=not qt) pytplot.del_data(names_to_plot) return
def standards(kp, list_plots=False, all_plots=False, euv=False, mag_mso=False, mag_geo=False, mag_cone=False, mag_dir=False, ngims_neutral=False, ngims_ions=False, eph_angle=False, eph_geo=False, eph_mso=False, swea=False, sep_ion=False, sep_electron=False, wave=False, plasma_den=False, plasma_temp=False, swia_h_vel=False, static_h_vel=False, static_o2_vel=False, static_flux=False, static_energy=False, sun_bar=False, solar_wind=False, ionosphere=False, sc_pot=False, altitude=False, title='Standard Plots', qt=True): ''' Generate all or a subset of 25 standardized plots, created from insitu KP data on the MAVEN SDC website Parameters: kp : dict insitu kp data structure/dictionary read from file(s) mag_mso: bool magnetic field, MSO coordinates mag_geo: bool magnetic field, geographic coordinates mag_cone: bool magnetic clock and cone angles, MSO coordinates mag_dir: bool magnetic field, radial/horizontal/northward/eastward components ngims_neutral: bool neutral atmospheric component densities ngims_ions: bool ionized atmospheric component densities eph_angle: bool spacecraft ephemeris information eph_geo: bool spacecraft position, geographic coordinates eph_mso: bool spacecraft position, MSO coordinates swea: bool electron parallel/anti-parallel fluxes sep_ion: bool ion energy flux sep_electron: bool electron energy flux wave: bool electric field wave power plasma_den: bool plasma density plasma_temp: bool plasma temperature swia_h_vel: bool H+ flow velocity, SWIA MSO coordinates static_h_vel: bool H+ flow velocity, STATIC MSO coordinates static_o2_vel: bool O2+ flow velocity, STATIC MSO coordinates static_flux: bool H+/He++ and pick-up ion omni-directional flux static_energy: bool H+/He++ and pick-up ion characteristic energy sun_bar: bool MAVEN sunlight indicator solar_wind: bool solar wind dynamic pressure ionosphere: bool electron spectrum shape parameter altitude: bool spacecraft altitude sc_pot: bool spacecraft potential list : bool Lists all Key Parameters instead of plotting title : str The Title to give the plot qt : bool If true, plots with qt. Else creates an HTML page with bokeh. exec_qt : bool If False, does not run the event loop for pyqtgraph. Returns : None Examples : >>> # Solar Orbital coordinates (x, y, z, magnitude), standard spacecraft ephemeris >>> # information (sub-spacecraft lat/lon, subsolar lat/lon, local solar time, solar >>> # zenith angle, Mars season) >>> # omni-directional flux. >>> insitu,iuvs = pydivide.read(input_time=['2017-06-19','2017-06-20']) >>> pydivide.standards(insitu, mag_mso=True, eph_angle=True, title='Example Title') ''' main_title = title if all_plots: euv = True mag_mso = True mag_geo = True mag_cone = True mag_dir = True ngims_neutral = True ngims_ions = True eph_angle = True eph_geo = True eph_mso = True swea = True sep_ion = True sep_electron = True wave = True plasma_den = True plasma_temp = True swia_h_vel = True static_h_vel = True static_o2_vel = True static_flux = True static_energy = True sun_bar = True solar_wind = True ionosphere = True sc_pot = True if list_plots: print("all: Generate all 25 plots") print("euv: EUV irradiance in each of three bands") print("mag_mso: Magnetic field, MSO coordinates") print("mag_geo: Magnetic field, Geographic coordinates") print("mag_cone: Magnetic clock and cone angles, MSO coordinates") print("mag_dir: Magnetic field: radial, horizontal, northward, and eastward components") print("ngims_neutral: Neutral atmospheric component densities") print("ngims_ions: Ionized atmospheric component densities") print("eph_angle: Spacecraft ephemeris information") print("eph_geo: Spacecraft position in geographic coordinates") print("eph_mso: Spacecraft position in MSO coordinates") print("swea: electron parallel/anti-parallel fluxes") print("sep_ion: Ion Energy fluxes") print("sep_electron: Electron Energy fluxes") print("wave: Electric field wave power") print("plasma_den: Plasma densities") print("plasma_temp: Plasma Temperatures") print("swia_h_vel: H+ Flow velocity in MSO coordinates from SWIA") print("static_h_vel: H+ flow velocity in MSO coordinates from STATIC") print("static_o2_vel: O2+ flow velocity in MSO coords from STATIC") print("static_flux: H+/He++ and Pick-up Ion omni-directional fluxes") print("static_energy: H+/He++ and Pick-up Ion characteristic energies") print("sun_bar: Indication of whether MAVEn is in sunlight") print("solar_wind: solar wind dynamic pressure") print("ionosphere: Electron Spectrum shape parameter") print("sc_pot: Spacecraft potential") return # Set up the plots to be underneath each other max_num_plots = sum([euv, mag_mso, mag_geo, mag_cone, mag_dir, ngims_neutral, ngims_ions, eph_angle, eph_geo, eph_mso, swea, sep_ion, sep_electron, wave, plasma_den, plasma_temp, swia_h_vel, static_h_vel, static_o2_vel, static_flux, static_energy, sun_bar, solar_wind, ionosphere, sc_pot]) if max_num_plots == 0: print("Please specify a plot to generate.") return # The number plot we're plotting in the figure current_plot_number = 0 names_to_plot = [] pytplot.xlim(float(kp['Time'][0]), float(kp['Time'][-1])) if euv: title = "EUV" try: if 'EUV' not in kp.keys(): raise Exception("NoDataException") euv_dataframe = kp['EUV'].loc[:, [param_dict['EUV Irradiance Lyman-alpha'], param_dict['EUV Irradiance 17-22 nm'], param_dict['EUV Irradiance 0.1-7.0 nm']]] pytplot.store_data(title, data={'x': kp['Time'], 'y': euv_dataframe}) pytplot.options(title, 'legend_names', ['EUV Irradiance Lyman-alpha', 'EUV Irradiance 17-22 nm', 'EUV Irradiance 0.1-7.0 nm']) names_to_plot.append(title) current_plot_number += 1 except Exception as x: if str(x) == "NoDataException": print("EUV is not in the Key Parameter Data Structure, " + title + " will not be plotted") if mag_mso: title = "MAG MSO" try: if 'MAG' not in kp.keys(): raise Exception("NoDataException") mag_mso_dataframe = kp['MAG'].loc[:, [param_dict['Magnetic Field MSO X'], param_dict['Magnetic Field MSO Y'], param_dict['Magnetic Field MSO Z']]] mag_mso_dataframe['Magnetic Field Magnitude MSO'] = ((kp['MAG'][param_dict['Magnetic Field MSO X']] * kp['MAG'][param_dict['Magnetic Field MSO X']]) + (kp['MAG'][param_dict['Magnetic Field MSO Y']] * kp['MAG'][param_dict['Magnetic Field MSO Y']]) + (kp['MAG'][param_dict['Magnetic Field MSO Z']] * kp['MAG'][param_dict['Magnetic Field MSO Z']])).apply( math.sqrt) pytplot.store_data(title, data={'x': kp['Time'], 'y': mag_mso_dataframe}) pytplot.options(title, 'legend_names', ['Magnetic Field MSO X', 'Magnetic Field MSO Y', 'Magnetic Field MSO Z', 'Magnetic Field Magnitude MSO']) names_to_plot.append(title) current_plot_number += 1 except Exception as x: if str(x) == "NoDataException": print("MAG is not in the Key Parameter Data Structure, " + title + " will not be plotted") if mag_geo: title = "MAG GEO" try: if 'MAG' not in kp.keys(): raise Exception("NoDataException") mag_geo_dataframe = kp['MAG'].loc[:, [param_dict['Magnetic Field GEO X'], param_dict['Magnetic Field GEO Y'], param_dict['Magnetic Field GEO Z']]] mag_geo_dataframe['Magnetic Field Magnitude GEO'] = ((kp['MAG'][param_dict['Magnetic Field GEO X']] * kp['MAG'][param_dict['Magnetic Field GEO X']]) + (kp['MAG'][param_dict['Magnetic Field GEO Y']] * kp['MAG'][param_dict['Magnetic Field GEO Y']]) + (kp['MAG'][param_dict['Magnetic Field GEO Z']] * kp['MAG'][param_dict['Magnetic Field GEO Z']])).apply( math.sqrt) pytplot.store_data(title, data={'x': kp['Time'], 'y': mag_geo_dataframe}) pytplot.options(title, 'legend_names', ['Magnetic Field GEO X', 'Magnetic Field GEO Y', 'Magnetic Field GEO Z', 'Magnetic Field Magnitude GEO']) names_to_plot.append(title) current_plot_number += 1 except Exception as x: if str(x) == "NoDataException": print("MAG is not in the Key Parameter Data Structure, " + title + " will not be plotted") if mag_cone: title = "MAG Cone" try: if 'MAG' not in kp.keys(): raise Exception("NoDataException") # Note, this plot ends up different from the IDL version, because of the way IDL calculates arctans. # Important, or not? mag_cone_dataframe_temp = kp['MAG'].loc[:, [param_dict['Magnetic Field MSO X'], param_dict['Magnetic Field MSO Y'], param_dict['Magnetic Field MSO Z']]] mag_cone_dataframe_temp['Clock Angle'] = (mag_cone_dataframe_temp[param_dict['Magnetic Field MSO X']] / mag_cone_dataframe_temp[param_dict['Magnetic Field MSO Y']] ).apply(math.atan) * 57.295776 mag_cone_dataframe_temp['Cone Angle'] = \ ((mag_cone_dataframe_temp[param_dict['Magnetic Field MSO X']].apply(abs)) / (((kp['MAG'][param_dict['Magnetic Field MSO X']] * kp['MAG'][param_dict['Magnetic Field MSO X']]) + (kp['MAG'][param_dict['Magnetic Field MSO Y']] * kp['MAG'][param_dict['Magnetic Field MSO Y']]) + (kp['MAG'][param_dict['Magnetic Field MSO Z']] * kp['MAG'][param_dict['Magnetic Field MSO Z']])).apply(math.sqrt))).apply(math.acos) * 57.295776 mag_cone_dataframe = mag_cone_dataframe_temp.loc[:, ['Clock Angle', 'Cone Angle']] pytplot.store_data(title, data={'x': kp['Time'], 'y': mag_cone_dataframe}) pytplot.options(title, 'legend_names', ['Magnetic Clock Angle', 'Magnetic Cone Angle']) names_to_plot.append(title) current_plot_number += 1 except Exception as x: if str(x) == "NoDataException": print("MAG is not in the Key Parameter Data Structure, " + title + " will not be plotted") if mag_dir: title = "MAG Direction" try: if 'MAG' not in kp.keys(): raise Exception("NoDataException") clat = (kp['SPACECRAFT']['SUB_SC_LATITUDE'] * 3.14159265 / 180).apply(math.cos) slat = (kp['SPACECRAFT']['SUB_SC_LATITUDE'] * 3.14159265 / 180).apply(math.sin) clon = (kp['SPACECRAFT']['SUB_SC_LONGITUDE'] * 3.14159265 / 180).apply(math.cos) slon = (kp['SPACECRAFT']['SUB_SC_LONGITUDE'] * 3.14159265 / 180).apply(math.sin) mag_rad_series = (kp['MAG'][param_dict['Magnetic Field GEO X']] * clon * clat) + \ (kp['MAG'][param_dict['Magnetic Field GEO Y']] * slon * clat) + \ (kp['MAG'][param_dict['Magnetic Field GEO Z']] * slat) mag_dir_dataframe = mag_rad_series.to_frame(name='Radial') mag_dir_dataframe['Eastward'] = (kp['MAG'][param_dict['Magnetic Field GEO X']] * slon * -1) + \ (kp['MAG'][param_dict['Magnetic Field GEO Y']] * clon) mag_dir_dataframe['Northward'] = (kp['MAG'][param_dict['Magnetic Field GEO X']] * clon * slat * -1) + \ (kp['MAG'][param_dict['Magnetic Field GEO Y']] * slon * slat * -1) + \ (kp['MAG'][param_dict['Magnetic Field GEO Z']] * clat) pytplot.store_data(title, data={'x': kp['Time'], 'y': mag_dir_dataframe}) pytplot.options(title, 'legend_names', ['Radial', 'Eastward', 'Northward']) names_to_plot.append(title) current_plot_number += 1 except Exception as x: if str(x) == "NoDataException": print("MAG is not in the Key Parameter Data Structure, " + title + " will not be plotted") if ngims_neutral: title = "NGIMS Neutrals" try: if 'NGIMS' not in kp.keys(): raise Exception("NoDataException") ngims_neutrals_dataframe = kp['NGIMS'].loc[:, [param_dict['Density He'], param_dict['Density O'], param_dict['Density CO'], param_dict['Density N2'], param_dict['Density NO'], param_dict['Density Ar'], param_dict['Density CO2']]] pytplot.store_data(title, data={'x': kp['Time'], 'y': ngims_neutrals_dataframe}) pytplot.options(title, 'legend_names', ['Density He', 'Density O', 'Density CO', 'Density N2', 'Density NO', 'Density Ar', 'Density CO2']) pytplot.options(title, 'ylog', 1) names_to_plot.append(title) current_plot_number += 1 except Exception as x: if str(x) == "NoDataException": print("NGIMS is not in the Key Parameter Data Structure, " + title + " will not be plotted") if ngims_ions: title = "NGIMS IONS" try: if 'NGIMS' not in kp.keys(): raise Exception("NoDataException") ngims_ion_dataframe = kp['NGIMS'].loc[:, [param_dict['Density 32+'], param_dict['Density 44+'], param_dict['Density 30+'], param_dict['Density 16+'], param_dict['Density 28+'], param_dict['Density 12+'], param_dict['Density 17+'], param_dict['Density 14+']]] pytplot.store_data(title, data={'x': kp['Time'], 'y': ngims_ion_dataframe}) pytplot.options(title, 'legend_names', ['Density 32+', 'Density 44+', 'Density 30+', 'Density 16+', 'Density 28+', 'Density 12+', 'Density 17+', 'Density 14+']) pytplot.options(title, 'ylog', 1) names_to_plot.append(title) current_plot_number += 1 except Exception as x: if str(x) == "NoDataException": print("NGIMS is not in the Key Parameter Data Structure, " + title + " will not be plotted") if eph_angle: title = "Spacecraft Ephemeris Information" try: if 'SPACECRAFT' not in kp.keys(): raise Exception("NoDataException") # This plot makes no sense. Why is Local Time plotted here, when it is not a measurement in degrees? # Why is Mars season/Subsolar Latitude plotted when they are essentially straight lines? sc_eph_dataframe = kp['SPACECRAFT'].loc[:, ['SUB_SC_LONGITUDE', 'SUB_SC_LATITUDE', 'SZA', 'LOCAL_TIME', 'MARS_SEASON', 'SUBSOLAR_POINT_GEO_LONGITUDE', 'SUBSOLAR_POINT_GEO_LATITUDE']] pytplot.store_data(title, data={'x': kp['Time'], 'y': sc_eph_dataframe}) pytplot.options(title, 'legend_names', ['GEO Longitude', 'GEO Latitude', 'Solar Zenith Angle', 'Local Time', 'Mars Season (Ls)', 'Subsolar Point GEO Longitude', 'Subsolar Point GEO Latitude']) names_to_plot.append(title) current_plot_number += 1 except Exception as x: if str(x) == "NoDataException": print("SPACECRAFT is not in the Key Parameter Data Structure, " + title + " will not be plotted") if eph_geo: title = "Spacecraft positon in GEO Coordinates" try: if 'SPACECRAFT' not in kp.keys(): raise Exception("NoDataException") sc_pos_dataframe = kp['SPACECRAFT'].loc[:, ['GEO_X', 'GEO_Y', 'GEO_Z', 'ALTITUDE']] pytplot.store_data(title, data={'x': kp['Time'], 'y': sc_pos_dataframe}) pytplot.options(title, 'legend_names', ['GEO X', 'GEO Y', 'GEO Z', 'Altitude Aeroid']) names_to_plot.append(title) current_plot_number += 1 except Exception as x: if str(x) == "NoDataException": print("SPACECRAFT is not in the Key Parameter Data Structure, " + title + " will not be plotted") if eph_mso: title = "Spacecraft positon in MSO Coordinates" try: if 'SPACECRAFT' not in kp.keys(): raise Exception("NoDataException") sc_pos_mso_dataframe = kp['SPACECRAFT'].loc[:, 'MSO_X', 'MSO_Y', 'MSO_Z', 'ALTITUDE'] pytplot.store_data(title, data={'x': kp['Time'], 'y': sc_pos_mso_dataframe}) pytplot.options(title, 'legend_names', ['MSO X', 'MSO Y', 'MSO Z', 'Altitude Aeroid']) names_to_plot.append(title) current_plot_number += 1 except Exception as x: if str(x) == "NoDataException": print("LPW is not in the Key Parameter Data Structure, " + title + " will not be plotted") if swea: title = "SWEA" try: if 'SWEA' not in kp.keys(): raise Exception("NoDataException") swea_dataframe = kp['SWEA'].loc[:, [param_dict['Flux, e- Parallel (5-100 ev)'], param_dict['Flux, e- Parallel (100-500 ev)'], param_dict['Flux, e- Parallel (500-1000 ev)'], param_dict['Flux, e- Anti-par (5-100 ev)'], param_dict['Flux, e- Anti-par (100-500 ev)'], param_dict['Flux, e- Anti-par (500-1000 ev)'], param_dict['Electron Spectrum Shape']]] pytplot.store_data(title, data={'x': kp['Time'], 'y': swea_dataframe}) pytplot.options(title, 'legend_names', ['Flux, e- Parallel (5-100 ev)', 'Flux, e- Parallel (100-500 ev)', 'Flux, e- Parallel (500-1000 ev)', 'Flux, e- Anti-par (5-100 ev)', 'Flux, e- Anti-par (100-500 ev)', 'Flux, e- Anti-par (500-1000 ev)', 'Electron Spectrum Shape']) names_to_plot.append(title) current_plot_number += 1 except Exception as x: if str(x) == "NoDataException": print("SWEA is not in the Key Parameter Data Structure, " + title + " will not be plotted") if sep_ion: title = "SEP Ions" try: if 'SEP' not in kp.keys(): raise Exception("NoDataException") # Need to fill in the NaNs as zero, otherwise the Sum will equal all Nans sep_ion_dataframe = kp['SEP'].loc[:, [param_dict['Ion Flux FOV 1 F'], param_dict['Ion Flux FOV 1 R'], param_dict['Ion Flux FOV 2 F'], param_dict['Ion Flux FOV 2 R']]].fillna(0) sep_ion_dataframe['Sum'] = sep_ion_dataframe[param_dict['Ion Flux FOV 1 F']] + \ sep_ion_dataframe[param_dict['Ion Flux FOV 1 R']] + \ sep_ion_dataframe[param_dict['Ion Flux FOV 2 F']] + \ sep_ion_dataframe[param_dict['Ion Flux FOV 2 R']] pytplot.store_data(title, data={'x': kp['Time'], 'y': sep_ion_dataframe}) pytplot.options(title, 'legend_names', ['Ion Flux FOV 1 F', 'Ion Flux FOV 1 R', 'Ion Flux FOV 2 F', 'Ion Flux FOV 2 R', 'Sum']) names_to_plot.append(title) current_plot_number += 1 except Exception as x: if str(x) == "NoDataException": print("SEP is not in the Key Parameter Data Structure, " + title + " will not be plotted") if sep_electron: title = "SEP Electrons" try: if 'SEP' not in kp.keys(): raise Exception("NoDataException") sep_electron_dataframe = kp['SEP'].loc[:, [param_dict['Electron Flux FOV 1 F'], param_dict['Electron Flux FOV 1 R'], param_dict['Electron Flux FOV 2 F'], param_dict['Electron Flux FOV 2 R']]].fillna(0) sep_electron_dataframe['Sum'] = sep_electron_dataframe[param_dict['Electron Flux FOV 1 F']] + \ sep_electron_dataframe[param_dict['Electron Flux FOV 1 R']] + \ sep_electron_dataframe[param_dict['Electron Flux FOV 2 F']] + \ sep_electron_dataframe[param_dict['Electron Flux FOV 2 R']] pytplot.store_data(title, data={'x': kp['Time'], 'y': sep_electron_dataframe}) pytplot.options(title, 'legend_names', ['Electron Flux FOV 1 F', 'Electron Flux FOV 1 R', 'Electron Flux FOV 2 F', 'Electron Flux FOV 2 R', 'Sum']) names_to_plot.append(title) current_plot_number += 1 except Exception as x: if str(x) == "NoDataException": print("SEP is not in the Key Parameter Data Structure, " + title + " will not be plotted") if wave: title = "E-Field" try: if 'LPW' not in kp.keys(): raise Exception("NoDataException") wave_dataframe = kp['LPW'].loc[:, [param_dict['E-field Power 2-100 Hz'], param_dict['E-field Power 100-800 Hz'], param_dict['E-field Power 0.8-1.0 Mhz']]] wave_dataframe['RMS Deviation'] = kp['MAG'].loc[:, [param_dict['Magnetic Field RMS Dev']]] pytplot.store_data(title, data={'x': kp['Time'], 'y': wave_dataframe}) pytplot.options(title, 'legend_names', ['E-field Power 2-100 Hz', 'E-field Power 100-800 Hz', 'E-field Power 0.8-1.0 Mhz', 'RMS Deviation']) pytplot.options(title, 'ylog', 1) names_to_plot.append(title) current_plot_number += 1 except Exception as x: if str(x) == "NoDataException": print("LPW is not in the Key Parameter Data Structure, " + title + " will not be plotted") if plasma_den: title = "Plasma Density" try: if 'SWIA' not in kp.keys() or 'STATIC' not in kp.keys() or 'LPW' not in kp.keys() \ or 'SWEA' not in kp.keys(): raise Exception("NoDataException") plasma_den_dataframe = kp['STATIC'].loc[:, [param_dict['H+ Density'], param_dict['O+ Density'], param_dict['O2+ Density']]] plasma_den_dataframe['SWIA H+ Density'] = kp['SWIA'].loc[:, [param_dict['H+ Density']]] plasma_den_dataframe['Solar Wind Electron Density'] = \ kp['SWEA'].loc[:, [param_dict['Solar Wind Electron Density']]] plasma_den_dataframe['Electron Density'] = kp['LPW'].loc[:, param_dict[['Electron Density']]] pytplot.store_data(title, data={'x': kp['Time'], 'y': plasma_den_dataframe}) pytplot.options(title, 'legend_names', ['H+ Density', 'O+ Density', 'O2+ Density', 'SWIA H+ Density', 'Solar Wind Electron Density', 'Electron Density']) pytplot.options(title, 'ylog', 1) names_to_plot.append(title) current_plot_number += 1 except Exception as x: if str(x) == "NoDataException": print("One or all of SWIA/STATIC/LPW/SWEA are not in the Key Parameter Data Structure, " + title + " will not be plotted") if plasma_temp: title = "Plasma Temperature" try: if 'SWIA' not in kp.keys() or 'STATIC' not in kp.keys() or 'LPW' not in kp.keys() \ or 'SWEA' not in kp.keys(): raise Exception("NoDataException") plasma_temp_dataframe = kp['STATIC'].loc[:, [param_dict['H+ Temperature'], param_dict['O+ Temperature'], param_dict['O2+ Temperature']]] plasma_temp_dataframe['SWIA H+ Temperature'] = kp['SWIA'].loc[:, [param_dict['H+ Temperature']]] plasma_temp_dataframe['Solar Wind Electron Temperature'] = \ kp['SWEA'].loc[:, [param_dict['Solar Wind Electron Temperature']]] plasma_temp_dataframe['Electron Temperature'] = kp['LPW'].loc[:, [param_dict['Electron Temperature']]] pytplot.store_data(title, data={'x': kp['Time'], 'y': plasma_temp_dataframe}) pytplot.options(title, 'legend_names', ['H+ Temperature', 'O+ Temperature', 'O2+ Temperature', 'SWIA H+ Temperature', 'Solar Wind Electron Temperature', 'Electron Temperature']) pytplot.options(title, 'ylog', 1) names_to_plot.append(title) current_plot_number += 1 except Exception as x: if str(x) == "NoDataException": print("One or all of SWIA/STATIC/LPW/SWEA are not in the Key Parameter Data Structure, " + title + " will not be plotted") if swia_h_vel: title = "SWIA H+ Velocity" try: if 'SWIA' not in kp.keys(): raise Exception("NoDataException") swia_h_vel_dataframe = kp['SWIA'].loc[:, [param_dict['H+ Flow Velocity MSO X'], param_dict['H+ Flow Velocity MSO Y'], param_dict['H+ Flow Velocity MSO Z']]] swia_h_vel_dataframe['Magnitude'] = ((kp['SWIA'][param_dict['H+ Flow Velocity MSO X']] * kp['SWIA'][param_dict['H+ Flow Velocity MSO X']]) + (kp['SWIA'][param_dict['H+ Flow Velocity MSO Y']] * kp['SWIA'][param_dict['H+ Flow Velocity MSO Y']]) + (kp['SWIA'][param_dict['H+ Flow Velocity MSO Z']] * kp['SWIA'][param_dict['H+ Flow Velocity MSO Z']])).apply(math.sqrt) pytplot.store_data(title, data={'x': kp['Time'], 'y': swia_h_vel_dataframe}) pytplot.options(title, 'legend_names', ['H+ Flow Velocity MSO X', 'H+ Flow Velocity MSO Y', 'H+ Flow Velocity MSO Z', 'Magnitude']) names_to_plot.append(title) current_plot_number += 1 except Exception as x: if str(x) == "NoDataException": print("SWIA is not in the Key Parameter Data Structure, " + title + " will not be plotted") if static_h_vel: title = "STATIC H+ Velocity" try: if 'STATIC' not in kp.keys(): raise Exception("NoDataException") # This is more like a direction, not a velocity. The values are between 0 and 1. static_h_vel_dataframe = kp['STATIC'].loc[:, [param_dict['H+ Direction MSO X'], param_dict['H+ Direction MSO Y'], param_dict['H+ Direction MSO Z']]] static_h_vel_dataframe['Magnitude'] = ((kp['STATIC'][param_dict['H+ Direction MSO X']] * kp['STATIC'][param_dict['H+ Direction MSO X']]) + (kp['STATIC'][param_dict['H+ Direction MSO Y']] * kp['STATIC'][param_dict['H+ Direction MSO Y']]) + (kp['STATIC'][param_dict['H+ Direction MSO Z']] * kp['STATIC'][param_dict['H+ Direction MSO Z']])).apply(math.sqrt) pytplot.store_data(title, data={'x': kp['Time'], 'y': static_h_vel_dataframe}) pytplot.options(title, 'legend_names', ['H+ Direction MSO X', 'H+ Direction MSO Y', 'H+ Direction MSO Z', 'Magnitude']) names_to_plot.append(title) current_plot_number += 1 except Exception as x: if str(x) == "NoDataException": print("STATIC is not in the Key Parameter Data Structure, " + title + " will not be plotted") if static_o2_vel: title = "STATIC O2+ Velocity" try: if 'STATIC' not in kp.keys(): raise Exception("NoDataException") static_o2_vel_dataframe = kp['STATIC'].loc[:, [param_dict['O2+ Flow Velocity MSO X'], param_dict['O2+ Flow Velocity MSO Y'], param_dict['O2+ Flow Velocity MSO Z']]] static_o2_vel_dataframe['Magnitude'] = ((kp['STATIC'][param_dict['O2+ Flow Velocity MSO X']] * kp['STATIC'][param_dict['O2+ Flow Velocity MSO X']]) + (kp['STATIC'][param_dict['O2+ Flow Velocity MSO Y']] * kp['STATIC'][param_dict['O2+ Flow Velocity MSO Y']]) + (kp['STATIC'][param_dict['O2+ Flow Velocity MSO Z']] * kp['STATIC'][param_dict['O2+ Flow Velocity MSO Z']])).apply( math.sqrt) pytplot.store_data(title, data={'x': kp['Time'], 'y': static_o2_vel_dataframe}) pytplot.options(title, 'legend_names', ['O2+ Flow Velocity MSO X', 'O2+ Flow Velocity MSO Y', 'O2+ Flow Velocity MSO Z', 'Magnitude']) names_to_plot.append(title) current_plot_number += 1 except Exception as x: if str(x) == "NoDataException": print("STATIC is not in the Key Parameter Data Structure, " + title + " will not be plotted") if static_flux: title = "STATIC Flux" try: if 'STATIC' not in kp.keys(): raise Exception("NoDataException") # In the IDL Toolkit, it only plots O2PLUS_FLOW_VELOCITY_MSO_X/Y. I'm assuming this is incorrect. # I have no idea what the right values to plot are. current_plot_number += 1 except Exception as x: if str(x) == "NoDataException": print("STATIC is not in the Key Parameter Data Structure, " + title + " will not be plotted") if static_energy: title = "STATIC Characteristic Energies" try: if 'STATIC' not in kp.keys(): raise Exception("NoDataException") sta_char_eng_dataframe = kp['STATIC'].loc[:, [param_dict['H+ Energy'], param_dict['He++ Energy'], param_dict['O+ Energy'], param_dict['O2+ Energy']]] pytplot.store_data(title, data={'x': kp['Time'], 'y': sta_char_eng_dataframe}) pytplot.options(title, 'legend_names', ['H+ Energy', 'He++ Energy', 'O+ Energy', 'O2+ Energy']) pytplot.options(title, 'ylog', 1) names_to_plot.append(title) current_plot_number += 1 except Exception as x: if str(x) == "NoDataException": print("STATIC is not in the Key Parameter Data Structure, " + title + " will not be plotted") if sun_bar: title = "Sunbar" try: if 'SPACECRAFT' not in kp.keys(): raise Exception("NoDataException") # Shows whether or not MAVEN is in the sun # 1 if True # 0 if False # Could there be a more efficient way of doing this? radius_mars = 3396.0 sun_bar_series = ((kp['SPACECRAFT']['MSO_Y'] * kp['SPACECRAFT']['MSO_Y']) + (kp['SPACECRAFT']['MSO_Z'] * kp['SPACECRAFT']['MSO_Z'])).apply(math.sqrt) sun_bar_series.name = "Sunlit/Eclipsed" index = 0 for mso_x in kp['SPACECRAFT']['MSO_X']: if mso_x < 0: if sun_bar_series[index] < radius_mars: sun_bar_series[index] = 0 else: sun_bar_series[index] = 1 else: sun_bar_series[index] = 1 index += 1 pytplot.store_data(title, data={'x': kp['Time'], 'y': sun_bar_series}) pytplot.ylim(title, -0.1, 1.1) names_to_plot.append(title) current_plot_number = current_plot_number + 1 except Exception as x: if str(x) == "NoDataException": print("SPACECRAFT is not in the Key Parameter Data Structure, " + title + " will not be plotted") if solar_wind: title = "Solar Wind" try: if 'SWIA' not in kp.keys(): raise Exception("NoDataException") solar_wind_dataframe = kp['SWIA'].loc[:, [param_dict['Solar Wind Dynamic Pressure']]] pytplot.store_data(title, data={'x': kp['Time'], 'y': solar_wind_dataframe}) pytplot.options(title, 'ylog', 1) names_to_plot.append(title) current_plot_number += 1 except Exception as x: if str(x) == "NoDataException": print("SWIA is not in the Key Parameter Data Structure, " + title + " will not be plotted") if ionosphere: title = "Ionosphere" try: if 'SWEA' not in kp.keys(): raise Exception("NoDataException") # Need to convert to float first, not sure why it is not already ionosphere_dataframe = kp['SWEA'].loc[:, [param_dict['Electron Spectrum Shape']]] ionosphere_dataframe['Electron Spectrum Shape'] = \ ionosphere_dataframe[param_dict['Electron Spectrum Shape']].apply(float) pytplot.store_data(title, data={'x': kp['Time'], 'y': ionosphere_dataframe}) pytplot.options(title, 'ylog', 1) names_to_plot.append(title) current_plot_number += 1 except Exception as x: if str(x) == "NoDataException": print("SWEA is not in the Key Parameter Data Structure, " + title + " will not be plotted") if sc_pot: title = "Spacecraft Potential" try: if 'LPW' not in kp.keys(): raise Exception("NoDataException") sc_pot_dataframe = kp['LPW'].loc[:, [param_dict['Spacecraft Potential']]] pytplot.store_data(title, data={'x': kp['Time'], 'y': sc_pot_dataframe}) names_to_plot.append(title) current_plot_number += 1 except Exception as x: if str(x) == "NoDataException": print("LPW is not in the Key Parameter Data Structure, " + title + " will not be plotted") if altitude: title = "Spacecraft Altitude" try: altitude_dataframe = kp['SPACECRAFT'].loc[:, ['ALTITUDE']] pytplot.store_data(title, data={'x': kp['Time'], 'y': altitude_dataframe}) names_to_plot.append(title) current_plot_number += 1 except Exception as x: if str(x) == "NoDataException": print("LPW is not in the Key Parameter Data Structure, " + title + " will not be plotted") # Show the plot pytplot.tplot_options('wsize', [1000, 300 * current_plot_number]) pytplot.tplot_options('title', main_title) pytplot.tplot(names_to_plot, bokeh=not qt) pytplot.del_data(names_to_plot) return
def map2d(kp, parameter=None, time=None, list=False, color_table=None, subsolar=False, mso=False, map_limit=None, basemap=None, alpha=None, title='MAVEN Mars', qt=True): if list: x = param_list(kp) for param in x: print(param) return #Check for orbit num rather than time string if isinstance(time, builtins.list): if isinstance(time[0], int): time = orbit_time(time[0], time[1]) elif isinstance(time, int): time = orbit_time(time) # Check existence of parameter if parameter == None: print("Must provide an index (or name) for param to be plotted.") return # Store instrument and observation of parameter(s) in lists inst = [] obs = [] if type(parameter) is int or type(parameter) is str: a, b = get_inst_obs_labels(kp, parameter) inst.append(a) obs.append(b) nparam = 1 else: nparam = len(parameter) for param in parameter: a, b = get_inst_obs_labels(kp, param) inst.append(a) obs.append(b) inst_obs = builtins.list(zip(inst, obs)) # Check the time variable if time != None: kp = range_select(kp, time) # Generate the altitude array if mso: x = kp['SPACECRAFT']['MSO_X'].as_matrix() y = kp['SPACECRAFT']['MSO_Y'].as_matrix() z = kp['SPACECRAFT']['MSO_Z'].as_matrix() r = np.sqrt((x**2) + (y**2) + (z**2)) lat = (90 - np.arccos(z / r) * (180 / math.pi)) lon = (np.arctan2(y, x) * (180 / math.pi)) + 180 else: lon = kp['SPACECRAFT']['SUB_SC_LONGITUDE'] lat = kp['SPACECRAFT']['SUB_SC_LATITUDE'] alt = kp['SPACECRAFT']['ALTITUDE'] # Cycle through the parameters, plotting each according to # the given keywords # names_to_plot = [] iplot = 0 # subplot indexes on 1 for inst, obs in inst_obs: # # First, generate the dependent array from data y = kp[inst][obs] if subsolar and mso == False: pytplot.store_data('sc_lon', data={'x': kp['Time'], 'y': lon}) pytplot.store_data('sc_lat', data={'x': kp['Time'], 'y': lat}) pytplot.store_data('%s.%s' % (inst, obs), data={ 'x': kp['Time'], 'y': y }) pytplot.options('%s.%s' % (inst, obs), 'link', ['lon', 'sc_lon']) pytplot.options('%s.%s' % (inst, obs), 'link', ['lat', 'sc_lat']) pytplot.options('%s.%s' % (inst, obs), 'map', 1) pytplot.store_data( 'ss_lon', data={ 'x': kp['Time'], 'y': kp['SPACECRAFT']['SUBSOLAR_POINT_GEO_LONGITUDE'] }) pytplot.store_data( 'ss_lat', data={ 'x': kp['Time'], 'y': kp['SPACECRAFT']['SUBSOLAR_POINT_GEO_LATITUDE'] }) pytplot.store_data('subsolar', data={'x': kp['Time'], 'y': alt}) pytplot.options('subsolar', 'link', ['lon', 'ss_lon']) pytplot.options('subsolar', 'link', ['lat', 'ss_lat']) pytplot.options('subsolar', 'map', 1) names_to_plot.append('%s.%s.%s' % (inst, obs, 'subsolar')) pytplot.store_data(names_to_plot[iplot], data=['%s.%s' % (inst, obs), 'subsolar']) pytplot.options(names_to_plot[iplot], 'map', 1) pytplot.options(names_to_plot[iplot], 'colormap', ['magma', 'yellow']) else: names_to_plot.append('%s.%s' % (inst, obs)) pytplot.store_data('sc_lon', data={'x': kp['Time'], 'y': lon}) pytplot.store_data('sc_lat', data={'x': kp['Time'], 'y': lat}) pytplot.store_data(names_to_plot[iplot], data={ 'x': kp['Time'], 'y': y }) pytplot.options(names_to_plot[iplot], 'link', ['lon', 'sc_lon']) pytplot.options(names_to_plot[iplot], 'link', ['lat', 'sc_lat']) pytplot.options(names_to_plot[iplot], 'map', 1) if basemap: if basemap == 'mola': map_file = os.path.join(os.path.dirname(__file__), 'basemaps', 'MOLA_color_2500x1250.jpg') elif basemap == 'mola_bw': map_file = os.path.join(os.path.dirname(__file__), 'basemaps', 'MOLA_BW_2500x1250.jpg') elif basemap == 'mdim': map_file = os.path.join(os.path.dirname(__file__), 'basemaps', 'MDIM_2500x1250.jpg') elif basemap == 'elevation': map_file = os.path.join(os.path.dirname(__file__), 'basemaps', 'MarsElevation_2500x1250.jpg') elif basemap == 'mag': map_file = os.path.join(os.path.dirname(__file__), 'basemaps', 'MAG_Connerny_2005.jpg') else: map_file = basemap pytplot.options(names_to_plot[iplot], 'basemap', map_file) if alpha: pytplot.options(names_to_plot[iplot], 'alpha', alpha) iplot = iplot + 1 pytplot.tplot_options('title', title) pytplot.tplot_options('wsize', [1000, 500 * (iplot)]) pytplot.tplot(names_to_plot, bokeh=not qt) pytplot.del_data('ss_lon') pytplot.del_data('ss_lat') pytplot.del_data('sc_lon') pytplot.del_data('sc_lat') pytplot.del_data(names_to_plot) return