Skip to content

Commit 48169d6

Browse files
authored
Merge pull request #98 from JaxLang/main
Updates from tool feedback session
2 parents d2efeab + 17c0430 commit 48169d6

File tree

2 files changed

+74
-84
lines changed

2 files changed

+74
-84
lines changed

SEP_Spatial-Distribution.ipynb

Lines changed: 20 additions & 37 deletions
Large diffs are not rendered by default.

spatial_analysis/__init__.py

Lines changed: 54 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -102,13 +102,14 @@ def __init__(self, dates, filepaths, **kwargs):
102102
self.end = dates[1]
103103
self.channels = {}
104104
self.channel_labels = {}
105+
self.energy_range_label = ""
105106
self.resampling = ""
106107

107108
if 'flare_loc' in kwargs.keys():
108109
self.flare_loc = kwargs['flare_loc']
109110
self.reference = kwargs['flare_loc'][0] # Using the longitude as the ref point
110111
else:
111-
self.flare_loc = [None, None]
112+
self.flare_loc = [np.nan, np.nan]
112113
self.reference = np.nan
113114

114115
out_path = f"{filepaths[0]}{os.sep}SEP_{dates[0].strftime('%d%b%Y')}"
@@ -172,15 +173,13 @@ def _load_solarmach_loop(self): # Step 5.1 or 6.2 or 7.1
172173
"""Download the solarmach data for the time period."""
173174
if np.isnan(self.reference):
174175
self._get_reference_point()
175-
try:
176-
self.sm_data = solarmach_loop(observers = self.spacecraft_list,
177-
dates = [self.start, self.end],
178-
data_path = self.out_path,
179-
resampling = self.resampling,
180-
source_loc = self.reference,
181-
vsw_list = self.vsw_list)
182-
except Exception as e:
183-
print(f"Warning: Could not load solarmach data: {e}")
176+
177+
self.sm_data = solarmach_loop(observers = self.spacecraft_list,
178+
dates = [self.start, self.end],
179+
data_path = self.out_path,
180+
resampling = self.resampling,
181+
source_loc = self.reference,
182+
vsw_list = self.vsw_list)
184183

185184
# Merge the sc data to the sm data
186185
if len(self.sc_data_ic) != 0:
@@ -205,11 +204,24 @@ def load_spacecraft_data(self, channels, resampling): # Step 2
205204
self.resampling = resampling
206205
self.spacecraft_list = list(channels.keys())
207206

207+
full_energy_range = [np.nan, np.nan]
208208
for sc in (self.spacecraft_list):
209-
try:
210-
self.sc_data[sc], self.channel_labels[sc] = load_sc_data(sc, self.channels, [self.start, self.end], self.raw_path, self.resampling)
211-
except Exception as e:
212-
print(f"Warning: Could not load data for {sc}: {e}")
209+
self.sc_data[sc], self.channel_labels[sc] = load_sc_data(sc, self.channels, [self.start, self.end], self.raw_path, self.resampling)
210+
211+
# Collecting the full energy range
212+
lbl_tmp = (self.channel_labels[sc]).split('-')
213+
s_tmp = float(lbl_tmp[0])
214+
e_tmp = float( (lbl_tmp[1]).split(' M')[0])
215+
if np.isnan(full_energy_range[0]):
216+
full_energy_range[0] = s_tmp
217+
full_energy_range[1] = e_tmp
218+
else:
219+
if (s_tmp < full_energy_range[0]):
220+
full_energy_range[0] = s_tmp
221+
if (e_tmp > full_energy_range[1]):
222+
full_energy_range[1] = e_tmp
223+
self.energy_range_label = f"{full_energy_range[0]:.1f}-{full_energy_range[1]:.1f} MeV"
224+
213225
print("Data loading complete.")
214226

215227

@@ -257,10 +269,8 @@ def background_subtract(self, background_window=[], perform_process=True): # Ste
257269

258270

259271
for sc in self.spacecraft_list:
260-
try:
261-
self.sc_data_bg[sc] = background_subtracting(self.sc_data.get(sc), background_window)
262-
except Exception as e:
263-
print(f"Warning: Could not background subtract for {sc}: {e}")
272+
self.sc_data_bg[sc] = background_subtracting(self.sc_data.get(sc), background_window)
273+
264274
print("Background subtraction function complete.")
265275
else:
266276
for sc in self.spacecraft_list:
@@ -282,10 +292,8 @@ def intercalibrate(self, intercalibration_factors, perform_process=True): # Step
282292

283293
if perform_process:
284294
for sc in self.spacecraft_list:
285-
try:
286-
self.sc_data_ic[sc] = intercalibration_calculation(self.sc_data_bg.get(sc), intercalibration_factors[sc])
287-
except Exception as e:
288-
print(f"Warning: Could not intercalibrate for {sc}: {e}")
295+
self.sc_data_ic[sc] = intercalibration_calculation(self.sc_data_bg.get(sc), intercalibration_factors[sc])
296+
289297
print("Intercalibration function complete.")
290298
else:
291299
for sc in self.spacecraft_list:
@@ -314,10 +322,8 @@ def radial_scale(self, radial_scaling_factors, perform_process=True): # Step 5
314322

315323
if perform_process:
316324
for sc in self.spacecraft_list:
317-
try:
318-
self.sc_data_rs[sc] = radial_scaling_calculation(self.sc_data_ic.get(sc), radial_scaling_factors)
319-
except Exception as e:
320-
print(f"Warning: Could not radial scale for {sc}: {e}")
325+
self.sc_data_rs[sc] = radial_scaling_calculation(self.sc_data_ic.get(sc), radial_scaling_factors)
326+
321327
print("Radial Scaling function complete.")
322328
else:
323329
for sc in self.spacecraft_list:
@@ -379,7 +385,7 @@ def plot_peak_fits(self, window_length=10): # Step 6
379385
print("Please run '*.load_spacecraft_data() first.")
380386
else:
381387
self._get_peak_fits(scdata, window_length=window_length)
382-
plot_peak_intensity(scdata, self.out_path, self.start, self.peak_data)
388+
plot_peak_intensity(scdata, self.out_path, self.start, self.peak_data, self.energy_range_label)
383389

384390
def _get_reference_point(self):
385391
"""Function to find a reference point for the Gaussian calculations.
@@ -399,20 +405,18 @@ def calc_Gaussian_fit(self): # Step 7
399405

400406
if len(self.peak_data) == 0:
401407
self._get_peak_fits()
402-
try:
403-
self.sc_data_rs['Gauss'] = fit_gauss_curves_to_data(self.sc_data_rs, self.out_path, self.reference, self.flare_loc, self.peak_data)
404-
except Exception as e:
405-
print(f"Warning: Could not calculate Gaussian fit: {e}")
408+
409+
self.sc_data_rs['Gauss'] = fit_gauss_curves_to_data(self.sc_data_rs, self.out_path, self.reference, self.flare_loc, self.peak_data, self.energy_range_label)
410+
411+
print(f"Calculations for Gaussian curves complete.")
406412

407413
# Final Results
408414
def plot_Gauss_results(self): # Step 8
409415
if len(self.sc_data_rs.get('Gauss')) == 0:
410416
self.calc_Gaussian_fit()
411417

412-
try:
413-
plot_gauss_fits_timeseries(self.sc_data_rs, self.out_path, self.start, self.reference, self.channel_labels, self.flare_loc)
414-
except Exception as e:
415-
print(f"Warning: Could not plot figure: {e}")
418+
plot_gauss_fits_timeseries(self.sc_data_rs, self.out_path, self.start, self.reference, self.channel_labels, self.flare_loc)
419+
416420

417421
def save_df_to_csv(self, label=''):
418422
"""Allows the user to save the observational data and Gaussian calculations
@@ -440,7 +444,7 @@ def plot_simple_curve_at_timestep(self, timestep):
440444
calculated."""
441445

442446
# Add check for timestep data type
443-
plot_one_timestep_curve(self.sc_data_rs, self.out_path, timestep, self.channel_labels, self.flare_loc, self.reference)
447+
plot_one_timestep_curve(self.sc_data_rs, self.out_path, timestep, self.channel_labels, self.flare_loc, self.reference, self.energy_range_label)
444448

445449

446450

@@ -1123,7 +1127,7 @@ def odr_gauss_fit(dict_1timestep, prev_results={'A': np.nan, 'X0': np.nan, 'sigm
11231127
'A err': float(out.sd_beta[0]), 'X0 err': float(out.sd_beta[1]), 'sigma err': float(out.sd_beta[2]),
11241128
'res': float(out.res_var)}
11251129

1126-
def fit_gauss_curves_to_data(sc_dict, data_path, reference, flare_loc, peak_data):
1130+
def fit_gauss_curves_to_data(sc_dict, data_path, reference, flare_loc, peak_data, energy_range_label):
11271131
"""Read in the full df, calculate the curve at each timestep, save the results to new columns."""
11281132
# Create a folder to save the gaussian timestep figures in
11291133
try:
@@ -1171,7 +1175,7 @@ def fit_gauss_curves_to_data(sc_dict, data_path, reference, flare_loc, peak_data
11711175

11721176
# Plot the fit for this timestep
11731177
if not np.isnan(x).any() and not np.isnan(gauss_results['X0']):
1174-
plot_curve_and_timeseries(gauss_results, timestep_dict, sc_dict, data_path+f'Gauss_fits{os.sep}', i, reference, flare_loc)
1178+
plot_curve_and_timeseries(gauss_results, timestep_dict, sc_dict, data_path+f'Gauss_fits{os.sep}', i, reference, flare_loc, energy_range_label)
11751179

11761180
prev_gauss = gauss_results
11771181

@@ -1234,7 +1238,10 @@ def plot_timeseries_result(sc_dict, data_path, dates, channel_labels, background
12341238
mrkr = marker_settings[sc]
12351239

12361240
# Show the event start time
1237-
ax[n].axvline(x=dates[0], color='k', linestyle='dashed', linewidth=0.5)
1241+
if n == 0:
1242+
ax[n].axvline(x=dates[0], color='k', linestyle='dashed', linewidth=0.5, label=f"Event start at: {dates[0].strftime('%H:%M %d %b, %Y')}")
1243+
else:
1244+
ax[n].axvline(x=dates[0], color='k', linestyle='dashed', linewidth=0.5)
12381245

12391246
# Show the background window
12401247
if len(background_window) > 1:
@@ -1309,7 +1316,7 @@ def find_peak_intensity(sc_dict, data_path, date, window_length=10):
13091316

13101317
return peak_data_results
13111318

1312-
def plot_peak_intensity(sc_dict, data_path, date, peak_data_results):
1319+
def plot_peak_intensity(sc_dict, data_path, date, peak_data_results, energy_range_label):
13131320
"""Plotting the results of the find_peak_intensity function."""
13141321

13151322
# Plot
@@ -1325,8 +1332,8 @@ def plot_peak_intensity(sc_dict, data_path, date, peak_data_results):
13251332
gauss_ax.set_xlabel('Footprint Longitude')
13261333
tseries_ax.set_xlabel('Time & Date')
13271334

1328-
# Add a text box with the energy and species - JAX: NEEDS TO BE ADAPTABLE
1329-
box_obj = AnchoredText('Peak Fits\n14 MeV Protons',
1335+
# Add a text box with the energy and species
1336+
box_obj = AnchoredText(f'Peak Fits\n{energy_range_label} Protons',
13301337
frameon=True, loc='lower right', pad=0.5, prop={'size':9})
13311338
plt.setp(box_obj.patch, facecolor='grey', alpha=0.9)
13321339
tseries_ax.add_artist(box_obj)
@@ -1413,7 +1420,7 @@ def log_gauss_error_range_calc(x_arr, y_arr, peak_fit):
14131420
return y_err
14141421

14151422

1416-
def plot_curve_and_timeseries(gauss_values, sc_df, full_df, data_path, timestep, reference, flare_loc):
1423+
def plot_curve_and_timeseries(gauss_values, sc_df, full_df, data_path, timestep, reference, flare_loc, energy_range_label):
14171424
"""Plotting two subplots, left the fitted gaussian curve, right the time series."""
14181425

14191426
ylimits = [1e5, 1e-5]
@@ -1440,7 +1447,7 @@ def plot_curve_and_timeseries(gauss_values, sc_df, full_df, data_path, timestep,
14401447
tseries_ax.set_xlabel('Time & Date')
14411448

14421449
# Add a text box with the energy and species
1443-
box_obj = AnchoredText('14 MeV Protons\n'+timestep.strftime("%H:%M %d %b %Y"),
1450+
box_obj = AnchoredText(f'{energy_range_label} Protons\n'+timestep.strftime("%H:%M %d %b %Y"),
14441451
frameon=True, loc='lower right', pad=0.5, prop={'size':9})
14451452
plt.setp(box_obj.patch, facecolor='grey', alpha=0.9)
14461453
tseries_ax.add_artist(box_obj)
@@ -1506,13 +1513,13 @@ def plot_curve_and_timeseries(gauss_values, sc_df, full_df, data_path, timestep,
15061513
plt.close("all")
15071514

15081515

1509-
def plot_one_timestep_curve(sc_dict, data_path, timestep, channel_labels, flare_loc, reference, **kwargs):
1516+
def plot_one_timestep_curve(sc_dict, data_path, timestep, channel_labels, flare_loc, reference, energy_range_label, **kwargs):
15101517
"""Plots only the curve at the given timestep."""
15111518
fig, ax = plt.subplots(1,1, figsize=[3,3], dpi=300)
15121519

15131520
# ax.set_title(timestep.strftime("%H:%M UTC - %d %b, %Y"), pad=5, loc='left')
1514-
box_obj1 = AnchoredText(timestep.strftime("%H:%M UTC\n%d %b, %Y"), frameon=True,
1515-
loc='lower right', pad=0.5, prop={'size':7.5})
1521+
box_obj1 = AnchoredText(timestep.strftime("%H:%M UTC\n%d %b, %Y")+f"\n{energy_range_label} protons",
1522+
frameon=True, loc='lower right', pad=0.5, prop={'size':7.5})
15161523
box_obj1.txt._text.set_ha('right')
15171524
box_obj1.txt._text.set_multialignment('right')
15181525
plt.setp(box_obj1.patch, facecolor='lemonchiffon', alpha=0.9)

0 commit comments

Comments
 (0)