-
Notifications
You must be signed in to change notification settings - Fork 6
/
__init__.py
2594 lines (2030 loc) · 113 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import copy
import os
import datetime
import warnings
import matplotlib.pyplot as plt
import matplotlib.colors as cl
import numpy as np
import pandas as pd
import astropy.units as u
import astropy.constants as const
from sunpy.coordinates import get_horizons_coord
from matplotlib import rcParams
from matplotlib.dates import DateFormatter
from matplotlib.ticker import ScalarFormatter
from matplotlib.offsetbox import AnchoredText
from seppy.loader.psp import calc_av_en_flux_PSP_EPIHI, calc_av_en_flux_PSP_EPILO, psp_isois_load
from seppy.loader.soho import calc_av_en_flux_ERNE, soho_load
from seppy.loader.solo import epd_load
from seppy.loader.stereo import calc_av_en_flux_HET as calc_av_en_flux_ST_HET
from seppy.loader.stereo import calc_av_en_flux_SEPT, stereo_load
from seppy.loader.wind import wind3dp_load
from seppy.util import bepi_sixs_load, calc_av_en_flux_sixs, custom_warning, flux2series, resample_df
# This is to get rid of this specific warning:
# /home/user/xyz/serpentine/notebooks/sep_analysis_tools/read_swaves.py:96: UserWarning: The input coordinates to pcolormesh are interpreted as
# cell centers, but are not monotonically increasing or decreasing. This may lead to incorrectly calculated cell edges, in which
# case, please supply explicit cell edges to pcolormesh.
# colormesh = ax.pcolormesh( time_arr, freq[::-1], data_arr[::-1], vmin = 0, vmax = 0.5*np.max(data_arr), cmap = 'inferno' )
warnings.filterwarnings(action="ignore",
message="The input coordinates to pcolormesh are interpreted as cell centers, but are not monotonically increasing or \
decreasing. This may lead to incorrectly calculated cell edges, in which case, please supply explicit cell edges to pcolormesh.",
category=UserWarning)
class Event:
def __init__(self, start_date, end_date, spacecraft, sensor,
species, data_level, data_path, viewing=None, radio_spacecraft=None,
threshold=None):
if spacecraft == "Solar Orbiter":
spacecraft = "solo"
if spacecraft == "STEREO-A":
spacecraft = "sta"
if spacecraft == "STEREO-B":
spacecraft = "stb"
if sensor in ["ERNE-HED"]:
sensor = "ERNE"
if species in ("protons", "ions"):
species = 'p'
if species in ("electrons", "electron"):
species = 'e'
self.start_date = start_date
self.end_date = end_date
self.spacecraft = spacecraft.lower()
self.sensor = sensor.lower()
self.species = species.lower()
self.data_level = data_level.lower()
self.data_path = data_path + os.sep
self.threshold = threshold
self.radio_spacecraft = radio_spacecraft # this is a 2-tuple, e.g., ("ahead", "STEREO-A")
self.viewing = viewing
self.radio_files = None
# placeholding class attributes
self.flux_series = None
self.onset_stats = None
self.onset_found = None
self.onset = None
self.peak_flux = None
self.peak_time = None
self.fig = None
self.bg_mean = None
self.output = {"flux_series": self.flux_series,
"onset_stats": self.onset_stats,
"onset_found": self.onset_found,
"onset": self.onset,
"peak_flux": self.peak_flux,
"peak_time": self.peak_time,
"fig": self.fig,
"bg_mean": self.bg_mean
}
# I think it could be worth considering to run self.choose_data(viewing) when the object is created,
# because now it has to be run inside self.print_energies() to make sure that either
# self.current_df, self.current_df_i or self.current_df_e exists, because print_energies() needs column
# names from the dataframe.
self.load_all_viewing()
# # Check that the data that was loaded is valid. If not, give a warning.
self.validate_data()
# Download radio cdf files ONLY if asked to
if self.radio_spacecraft is not None:
from seppy.tools.swaves import get_swaves
self.radio_files = get_swaves(start_date, end_date)
def validate_data(self):
"""
Provide an error msg if this object is initialized with a combination that yields invalid data products.
"""
# SolO/STEP data before 22 Oct 2021 is not supported yet for non-'Pixel averaged' viewing
warn_mess_step_pixels_old = "SolO/STEP data is not included yet for individual Pixels for dates preceding Oct 22, 2021. Only 'Pixel averaged' is supported."
if self.spacecraft == "solo" and self.sensor == "step":
if self.start_date < pd.to_datetime("2021-10-22").date():
if not self.viewing == 'Pixel averaged':
# when 'viewing' is undefined, only give a warning; if it's wrong defined, abort with warning
if not self.viewing:
# warnings.warn(message=warn_mess_step_pixels_old)
custom_warning(message=warn_mess_step_pixels_old)
else:
raise Warning(warn_mess_step_pixels_old)
# Electron data for SolO/STEP is removed for now (Feb 2024, JG)
if self.spacecraft == "solo" and self.sensor == "step" and self.species.lower()[0] == 'e':
raise Warning("SolO/STEP electron data is not implemented yet!")
def update_onset_attributes(self, flux_series, onset_stats, onset_found, peak_flux, peak_time, fig, bg_mean):
"""
Method to update onset-related attributes, that are None by default and only have values after analyse() has been run.
"""
self.flux_series = flux_series
self.onset_stats = onset_stats
self.onset_found = onset_found
self.onset = onset_stats[-1]
self.peak_flux = peak_flux
self.peak_time = peak_time
self.fig = fig
self.bg_mean = bg_mean
# also remember to update the dictionary, it won't update automatically
self.output = {"flux_series": self.flux_series,
"onset_stats": self.onset_stats,
"onset_found": self.onset_found,
"onset": self.onset,
"peak_flux": self.peak_flux,
"peak_time": self.peak_time,
"fig": self.fig,
"bg_mean": self.bg_mean
}
def update_viewing(self, viewing):
if self.spacecraft != "wind":
self.viewing = viewing
else:
# Wind/3DP viewing directions are omnidirectional, section 0, section 1... section n.
# This catches the number or the word if omnidirectional
try:
self.viewing = viewing.split(" ")[-1]
# AttributeError is cause by initializing Event with spacecraft='Wind' and viewing=None
except AttributeError:
self.viewing = '0' # A placeholder viewing that should not cause any trouble
# I suggest we at some point erase the arguments ´spacecraft´ and ´threshold´ due to them not being used.
# `viewing` and `autodownload` are actually the only necessary input variables for this function, the rest
# are class attributes, and should probably be cleaned up at some point
def load_data(self, spacecraft, sensor, viewing, data_level,
autodownload=True, threshold=None):
if self.spacecraft == 'solo':
if self.sensor in ("ept", "het"):
df_i, df_e, meta = epd_load(sensor=sensor,
viewing=viewing,
level=data_level,
startdate=self.start_date,
enddate=self.end_date,
path=self.data_path,
autodownload=autodownload)
# self.update_viewing(viewing) Why is viewing updated here?
return df_i, df_e, meta
elif self.sensor == "step":
df, meta = epd_load(sensor=sensor,
viewing="None",
level=data_level,
startdate=self.start_date,
enddate=self.end_date,
path=self.data_path,
autodownload=autodownload)
# self.update_viewing(viewing) Why is viewing updated here?
return df, meta
if self.spacecraft[:2].lower() == 'st':
if self.sensor == 'sept':
if self.species in ["p", "i"]:
df_i, channels_dict_df_i = stereo_load(instrument=self.sensor,
startdate=self.start_date,
enddate=self.end_date,
spacecraft=self.spacecraft,
# sept_species=self.species,
sept_species='p',
sept_viewing=viewing,
resample=None,
pos_timestamp="center",
path=self.data_path)
df_e, channels_dict_df_e = [], []
self.update_viewing(viewing)
return df_i, df_e, channels_dict_df_i, channels_dict_df_e
if self.species == "e":
df_e, channels_dict_df_e = stereo_load(instrument=self.sensor,
startdate=self.start_date,
enddate=self.end_date,
spacecraft=self.spacecraft,
# sept_species=self.species,
sept_species='e',
sept_viewing=viewing,
resample=None,
pos_timestamp="center",
path=self.data_path)
df_i, channels_dict_df_i = [], []
self.update_viewing(viewing)
return df_i, df_e, channels_dict_df_i, channels_dict_df_e
if self.sensor == 'het':
df, meta = stereo_load(instrument=self.sensor,
startdate=self.start_date,
enddate=self.end_date,
spacecraft=self.spacecraft,
resample=None,
pos_timestamp="center",
path=self.data_path)
self.update_viewing(viewing)
return df, meta
if self.spacecraft.lower() == 'soho':
if self.sensor == 'erne':
df, meta = soho_load(dataset="SOHO_ERNE-HED_L2-1MIN",
startdate=self.start_date,
enddate=self.end_date,
path=self.data_path,
resample=None,
pos_timestamp="center")
self.update_viewing(viewing)
return df, meta
if self.sensor == 'ephin':
df, meta = soho_load(dataset="SOHO_COSTEP-EPHIN_L2-1MIN",
startdate=self.start_date,
enddate=self.end_date,
path=self.data_path,
resample=None,
pos_timestamp="center")
self.update_viewing(viewing)
return df, meta
if self.sensor in ("ephin-5", "ephin-15"):
dataset = "ephin_flux_2020-2022.csv"
if os.path.isfile(f"{self.data_path}{dataset}"):
df = pd.read_csv(f"{self.data_path}{dataset}", index_col="date", parse_dates=True)
# set electron flux to nan if the ratio of proton-proxy counts to correspondning electron counts is >0.1
df['E5'][df['p_proxy (1.80-2.00 MeV)']/df['0.45-0.50 MeV (E5)'] >= 0.1] = np.nan
df['E15'][df['p_proxy (1.80-2.00 MeV)']/df['0.70-1.10 MeV (E15)'] >= 0.1] = np.nan
else:
raise Warning(f"File {dataset} not found at {self.data_path}! Please verify that 'data_path' is correct.")
meta = {"E5": "0.45 - 0.50 MeV",
"E15": "0.70 - 1.10 MeV"}
# TODO:
# - add resample_df here?
# - add pos_timestamp here
self.update_viewing(viewing)
return df, meta
if self.spacecraft.lower() == 'wind':
# In Wind's case we have to retrieve the original viewing before updating, because
# otherwise viewing = 'None' will mess up everything down the road
viewing = self.viewing
if self.sensor == '3dp':
df_i, meta_i = wind3dp_load(dataset="WI_SOPD_3DP",
startdate=self.start_date,
enddate=self.end_date,
resample=None,
multi_index=False,
path=self.data_path,
threshold=self.threshold)
df_e, meta_e = wind3dp_load(dataset="WI_SFPD_3DP",
startdate=self.start_date,
enddate=self.end_date,
resample=None,
multi_index=False,
path=self.data_path,
threshold=self.threshold)
df_omni_i, meta_omni_i = wind3dp_load(dataset="WI_SOSP_3DP",
startdate=self.start_date,
enddate=self.end_date,
resample=None,
multi_index=False,
path=self.data_path,
threshold=self.threshold)
df_omni_e, meta_omni_e = wind3dp_load(dataset="WI_SFSP_3DP",
startdate=self.start_date,
enddate=self.end_date,
resample=None,
multi_index=False,
path=self.data_path,
threshold=self.threshold)
self.update_viewing(viewing)
return df_omni_i, df_omni_e, df_i, df_e, meta_i, meta_e
if self.spacecraft.lower() == 'psp':
if self.sensor.lower() == 'isois-epihi':
df, meta = psp_isois_load(dataset='PSP_ISOIS-EPIHI_L2-HET-RATES60',
startdate=self.start_date,
enddate=self.end_date,
path=self.data_path,
resample=None)
self.update_viewing(viewing)
return df, meta
if self.sensor.lower() == 'isois-epilo':
df, meta = psp_isois_load(dataset='PSP_ISOIS-EPILO_L2-PE',
startdate=self.start_date,
enddate=self.end_date,
path=self.data_path,
resample=None,
epilo_channel='F',
epilo_threshold=self.threshold)
self.update_viewing(viewing)
return df, meta
if self.spacecraft.lower() == 'bepi':
df, meta = bepi_sixs_load(startdate=self.start_date,
enddate=self.end_date,
side=viewing,
path=self.data_path,
pos_timestamp='center')
df_i = df[[f"P{i}" for i in range(1, 10)]]
df_e = df[[f"E{i}" for i in range(1, 8)]]
return df_i, df_e, meta
def load_all_viewing(self):
if self.spacecraft == 'solo':
if self.sensor in ['het', 'ept']:
self.df_i_sun, self.df_e_sun, self.energies_sun =\
self.load_data(self.spacecraft, self.sensor,
'sun', self.data_level)
self.df_i_asun, self.df_e_asun, self.energies_asun =\
self.load_data(self.spacecraft, self.sensor,
'asun', self.data_level)
self.df_i_north, self.df_e_north, self.energies_north =\
self.load_data(self.spacecraft, self.sensor,
'north', self.data_level)
self.df_i_south, self.df_e_south, self.energies_south =\
self.load_data(self.spacecraft, self.sensor,
'south', self.data_level)
elif self.sensor == 'step':
self.df_step, self.energies_step =\
self.load_data(self.spacecraft, self.sensor, self.viewing,
self.data_level)
if self.spacecraft[:2].lower() == 'st':
if self.sensor == 'sept':
self.df_i_sun, self.df_e_sun, self.energies_i_sun, self.energies_e_sun =\
self.load_data(self.spacecraft, self.sensor,
'sun', self.data_level)
self.df_i_asun, self.df_e_asun, self.energies_i_asun, self.energies_e_asun =\
self.load_data(self.spacecraft, self.sensor,
'asun', self.data_level)
self.df_i_north, self.df_e_north, self.energies_i_north, self.energies_e_north =\
self.load_data(self.spacecraft, self.sensor,
'north', self.data_level)
self.df_i_south, self.df_e_south, self.energies_i_south, self.energies_e_south =\
self.load_data(self.spacecraft, self.sensor,
'south', self.data_level)
elif self.sensor == 'het':
self.df_het, self.meta_het =\
self.load_data(self.spacecraft, self.sensor, 'None',
self.data_level)
self.current_df_i = self.df_het.filter(like='Proton')
self.current_df_e = self.df_het.filter(like='Electron')
self.current_energies = self.meta_het
if self.spacecraft.lower() == 'soho':
if self.sensor.lower() == 'erne':
self.df, self.meta =\
self.load_data(self.spacecraft, self.sensor, 'None',
self.data_level)
self.current_df_i = self.df.filter(like='PH_')
# self.current_df_e = self.df.filter(like='Electron')
self.current_energies = self.meta
if self.sensor.lower() == 'ephin':
self.df, self.meta =\
self.load_data(self.spacecraft, self.sensor, 'None',
self.data_level)
self.current_df_e = self.df.filter(like='E')
self.current_energies = self.meta
if self.sensor.lower() in ("ephin-5", "ephin-15"):
self.df, self.meta =\
self.load_data(self.spacecraft, self.sensor, 'None',
self.data_level)
self.current_df_e = self.df
self.current_energies = self.meta
if self.spacecraft.lower() == 'wind':
if self.sensor.lower() == '3dp':
self.df_omni_i, self.df_omni_e, self.df_i, self.df_e, self.meta_i, self.meta_e = \
self.load_data(self.spacecraft, self.sensor, 'None', self.data_level, threshold=self.threshold)
# self.df_i = self.df_i.filter(like='FLUX')
# self.df_e = self.df_e.filter(like='FLUX')
self.current_i_energies = self.meta_i
self.current_e_energies = self.meta_e
if self.spacecraft.lower() == 'psp':
if self.sensor.lower() == 'isois-epihi':
# Note: load_data(viewing='all') doesn't really has an effect, but for PSP/ISOIS-EPIHI all viewings are always loaded anyhow.
self.df, self.meta = self.load_data(self.spacecraft, self.sensor, 'all', self.data_level)
self.df_e = self.df.filter(like='Electrons_Rate_')
self.current_e_energies = self.meta
self.df_i = self.df.filter(like='H_Flux_')
self.current_i_energies = self.meta
if self.sensor.lower() == 'isois-epilo':
# Note: load_data(viewing='all') doesn't really has an effect, but for PSP/ISOIS-EPILO all viewings are always loaded anyhow.
self.df, self.meta = self.load_data(self.spacecraft, self.sensor, 'all', self.data_level, threshold=self.threshold)
self.df_e = self.df.filter(like='Electron_CountRate_')
self.current_e_energies = self.meta
# protons not yet included in PSP/ISOIS-EPILO dataset
# self.df_i = self.df.filter(like='H_Flux_')
# self.current_i_energies = self.meta
if self.spacecraft.lower() == 'bepi':
self.df_i_0, self.df_e_0, self.energies_0 =\
self.load_data(self.spacecraft, self.sensor, viewing='0', data_level='None')
self.df_i_1, self.df_e_1, self.energies_1 =\
self.load_data(self.spacecraft, self.sensor, viewing='1', data_level='None')
self.df_i_2, self.df_e_2, self.energies_2 =\
self.load_data(self.spacecraft, self.sensor, viewing='2', data_level='None')
# side 3 and 4 should not be used for SIXS, but they can be activated by uncommenting the following lines
# self.df_i_3, self.df_e_3, self.energies_3 =\
# self.load_data(self.spacecraft, self.sensor, viewing='3', data_level='None')
# self.df_i_4, self.df_e_4, self.energies_4 =\
# self.load_data(self.spacecraft, self.sensor, viewing='4', data_level='None')
def choose_data(self, viewing):
self.update_viewing(viewing)
if self.spacecraft == 'solo':
if not viewing:
raise Exception("For this operation, the instrument's 'viewing' direction must be defined in the call of 'Event'!")
elif viewing == 'sun':
self.current_df_i = self.df_i_sun
self.current_df_e = self.df_e_sun
self.current_energies = self.energies_sun
elif viewing == 'asun':
self.current_df_i = self.df_i_asun
self.current_df_e = self.df_e_asun
self.current_energies = self.energies_asun
elif viewing == 'north':
self.current_df_i = self.df_i_north
self.current_df_e = self.df_e_north
self.current_energies = self.energies_north
elif viewing == 'south':
self.current_df_i = self.df_i_south
self.current_df_e = self.df_e_south
self.current_energies = self.energies_south
elif "Pixel" in viewing:
# All viewings are contained in the same dataframe, choose the pixel (viewing) here
pixel = self.viewing.split(' ')[1]
# Pixel info is in format NN in the dataframe, 1 -> 01 while 12 -> 12
if len(pixel) == 1:
pixel = f"0{pixel}"
# Pixel length more than 2 means "averaged" -> called "Avg" in the dataframe
elif len(pixel) > 2:
pixel = "Avg"
self.current_df_i = self.df_step[[col for col in self.df_step.columns if f"Magnet_{pixel}_Flux" in col]]
self.current_df_e = self.df_step[[col for col in self.df_step.columns if f"Electron_{pixel}_Flux" in col]]
self.current_energies = self.energies_step
if self.spacecraft[:2].lower() == 'st':
if self.sensor == 'sept':
if viewing == 'sun':
self.current_df_i = self.df_i_sun
self.current_df_e = self.df_e_sun
self.current_i_energies = self.energies_i_sun
self.current_e_energies = self.energies_e_sun
elif viewing == 'asun':
self.current_df_i = self.df_i_asun
self.current_df_e = self.df_e_asun
self.current_i_energies = self.energies_i_asun
self.current_e_energies = self.energies_e_asun
elif viewing == 'north':
self.current_df_i = self.df_i_north
self.current_df_e = self.df_e_north
self.current_i_energies = self.energies_i_north
self.current_e_energies = self.energies_e_north
elif viewing == 'south':
self.current_df_i = self.df_i_south
self.current_df_e = self.df_e_south
self.current_i_energies = self.energies_i_south
self.current_e_energies = self.energies_e_south
if self.spacecraft.lower() == 'wind':
if self.sensor.lower() == '3dp':
# The sectored data has a little different column names
if self.viewing == "omnidirectional":
col_list_i = [col for col in self.df_omni_i.columns if "FLUX" in col]
col_list_e = [col for col in self.df_omni_e.columns if "FLUX" in col]
self.current_df_i = self.df_omni_i[col_list_i]
self.current_df_e = self.df_omni_e[col_list_e]
else:
col_list_i = [col for col in self.df_i.columns if col.endswith(str(self.viewing)) and "FLUX" in col]
col_list_e = [col for col in self.df_e.columns if col.endswith(str(self.viewing)) and "FLUX" in col]
self.current_df_i = self.df_i[col_list_i]
self.current_df_e = self.df_e[col_list_e]
if self.spacecraft.lower() == 'psp':
if self.sensor.lower() == 'isois-epihi':
# viewing = 'A' or 'B'
self.current_df_e = self.df_e[self.df_e.columns[self.df_e.columns.str.startswith(viewing.upper())]]
self.current_df_i = self.df_i[self.df_i.columns[self.df_i.columns.str.startswith(viewing.upper())]]
if self.sensor.lower() == 'isois-epilo':
# viewing = '0' to '7'
self.current_df_e = self.df_e[self.df_e.columns[self.df_e.columns.str.endswith(viewing)]]
# Probably just a temporary thing, but cut all channels without a corresponding energy range string in them to avoid problems with
# dynamic spectrum. Magic number 12 is the amount of channels that have a corresponding energy description.
col_list = [col for col in self.current_df_e.columns if int(col.split('_')[3][1:])<12]
self.current_df_e = self.current_df_e[col_list]
# protons not yet included in PSP/ISOIS-EPILO dataset
# self.current_df_i = self.df_i[self.df_i.columns[self.df_i.columns.str.endswith(viewing)]]
if self.spacecraft.lower() == 'bepi':
if viewing == '0':
self.current_df_i = self.df_i_0
self.current_df_e = self.df_e_0
self.current_energies = self.energies_0
elif viewing == '1':
self.current_df_i = self.df_i_1
self.current_df_e = self.df_e_1
self.current_energies = self.energies_1
elif viewing == '2':
self.current_df_i = self.df_i_2
self.current_df_e = self.df_e_2
self.current_energies = self.energies_2
# side 3 and 4 should not be used for SIXS, but they can be activated by uncommenting the following lines
# elif(viewing == '3'):
# self.current_df_i = self.df_i_3
# self.current_df_e = self.df_e_3
# self.current_energies = self.energies_3
# elif(viewing == '4'):
# self.current_df_i = self.df_i_4
# self.current_df_e = self.df_e_4
# self.current_energies = self.energies_4
def calc_av_en_flux_HET(self, df, energies, en_channel):
"""This function averages the flux of several
energy channels of SolO/HET into a combined energy channel
channel numbers counted from 0
Parameters
----------
df : pd.DataFrame DataFrame containing HET data
DataFrame containing HET data
energies : dict
Energy dict returned from epd_loader (from Jan)
en_channel : int or list
energy channel or list with first and last channel to be used
species : string
'e', 'electrons', 'p', 'i', 'protons', 'ions'
Returns
-------
pd.DataFrame
flux_out: contains channel-averaged flux
Raises
------
Exception
[description]
"""
species = self.species
try:
if species not in ['e', 'electrons', 'p', 'protons', 'H']:
raise ValueError("species not defined. Must by one of 'e',\
'electrons', 'p', 'protons', 'H'")
except ValueError as error:
print(repr(error))
raise
if species in ['e', 'electrons']:
en_str = energies['Electron_Bins_Text']
bins_width = 'Electron_Bins_Width'
flux_key = 'Electron_Flux'
if species in ['p', 'protons', 'H']:
en_str = energies['H_Bins_Text']
bins_width = 'H_Bins_Width'
flux_key = 'H_Flux'
if flux_key not in df.keys():
flux_key = 'H_Flux'
if type(en_channel) == list:
# An IndexError here is caused by invalid channel choice
try:
en_channel_string = en_str[en_channel[0]][0].split()[0] + ' - '\
+ en_str[en_channel[-1]][0].split()[2] + ' ' +\
en_str[en_channel[-1]][0].split()[3]
except IndexError:
raise Exception(f"{en_channel} is an invalid channel or a combination of channels!")
if len(en_channel) > 2:
raise Exception('en_channel must have len 2 or less!')
if len(en_channel) == 2:
DE = energies[bins_width]
for bins in np.arange(en_channel[0], en_channel[-1] + 1):
if bins == en_channel[0]:
I_all = df[flux_key].values[:, bins] * DE[bins]
else:
I_all = I_all + df[flux_key].values[:, bins] * DE[bins]
DE_total = np.sum(DE[(en_channel[0]):(en_channel[-1] + 1)])
flux_av_en = pd.Series(I_all/DE_total, index=df.index)
flux_out = pd.DataFrame({'flux': flux_av_en}, index=df.index)
else:
en_channel = en_channel[0]
flux_out = pd.DataFrame({'flux':
df[flux_key].values[:, en_channel]},
index=df.index)
else:
flux_out = pd.DataFrame({'flux':
df[flux_key].values[:, en_channel]},
index=df.index)
en_channel_string = en_str[en_channel]
return flux_out, en_channel_string
def calc_av_en_flux_EPT(self, df, energies, en_channel):
"""This function averages the flux of several energy
channels of EPT into a combined energy channel
channel numbers counted from 0
Parameters
----------
df : pd.DataFrame DataFrame containing EPT data
DataFrame containing EPT data
energies : dict
Energy dict returned from epd_loader (from Jan)
en_channel : int or list
energy channel number(s) to be used
species : string
'e', 'electrons', 'p', 'i', 'protons', 'ions'
Returns
-------
pd.DataFrame
flux_out: contains channel-averaged flux
Raises
------
Exception
[description]
"""
species = self.species
try:
if species not in ['e', 'electrons', 'p', 'i', 'protons', 'ions']:
raise ValueError("species not defined. Must by one of 'e',"
"'electrons', 'p', 'i', 'protons', 'ions'")
except ValueError as error:
print(repr(error))
raise
if species in ['e', 'electrons']:
bins_width = 'Electron_Bins_Width'
flux_key = 'Electron_Flux'
en_str = energies['Electron_Bins_Text']
if species in ['p', 'i', 'protons', 'ions']:
bins_width = 'Ion_Bins_Width'
flux_key = 'Ion_Flux'
en_str = energies['Ion_Bins_Text']
if flux_key not in df.keys():
flux_key = 'H_Flux'
if type(en_channel) == list:
# An IndexError here is caused by invalid channel choice
try:
en_channel_string = en_str[en_channel[0]][0].split()[0] + ' - '\
+ en_str[en_channel[-1]][0].split()[2] + ' '\
+ en_str[en_channel[-1]][0].split()[3]
except IndexError:
raise Exception(f"{en_channel} is an invalid channel or a combination of channels!")
if len(en_channel) > 2:
raise Exception('en_channel must have len 2 or less!')
if len(en_channel) == 2:
DE = energies[bins_width]
for bins in np.arange(en_channel[0], en_channel[-1]+1):
if bins == en_channel[0]:
I_all = df[flux_key].values[:, bins] * DE[bins]
else:
I_all = I_all + df[flux_key].values[:, bins] * DE[bins]
DE_total = np.sum(DE[(en_channel[0]):(en_channel[-1]+1)])
flux_av_en = pd.Series(I_all/DE_total, index=df.index)
flux_out = pd.DataFrame({'flux': flux_av_en}, index=df.index)
else:
en_channel = en_channel[0]
flux_out = pd.DataFrame({'flux':
df[flux_key].values[:, en_channel]},
index=df.index)
else:
flux_out = pd.DataFrame({'flux':
df[flux_key].values[:, en_channel]},
index=df.index)
en_channel_string = en_str[en_channel]
return flux_out, en_channel_string
def print_info(self, title, info):
title_string = "##### >" + title + "< #####"
print(title_string)
print(info)
print('#'*len(title_string) + '\n')
def mean_value(self, tb_start, tb_end, flux_series):
"""
This function calculates the classical mean of the background period
which is used in the onset analysis.
"""
# replace date_series with the resampled version
date = flux_series.index
background = flux_series.loc[(date >= tb_start) & (date < tb_end)]
mean_value = np.nanmean(background)
sigma = np.nanstd(background)
return [mean_value, sigma]
def onset_determination(self, ma_sigma, flux_series, cusum_window, bg_end_time):
flux_series = flux_series[bg_end_time:]
# assert date and the starting index of the averaging process
date = flux_series.index
ma = ma_sigma[0]
sigma = ma_sigma[1]
md = ma + self.x_sigma*sigma
# k may get really big if sigma is large in comparison to mean
try:
k = (md-ma)/(np.log(md)-np.log(ma))
k_round = round(k/sigma)
except ValueError:
# First ValueError I encountered was due to ma=md=2.0 -> k = "0/0"
k_round = 1
# choose h, the variable dictating the "hastiness" of onset alert
if k < 1.0:
h = 1
else:
h = 2
alert = 0
cusum = np.zeros(len(flux_series))
norm_channel = np.zeros(len(flux_series))
# set the onset as default to be NaT (Not a Date)
onset_time = pd.NaT
for i in range(1, len(cusum)):
# normalize the observed flux
norm_channel[i] = (flux_series.iloc[i]-ma)/sigma
# calculate the value for ith cusum entry
cusum[i] = max(0, norm_channel[i] - k_round + cusum[i-1])
# check if cusum[i] is above threshold h,
# if it is -> increment alert
if cusum[i] > h:
alert = alert + 1
else:
alert = 0
# cusum_window(default:30) subsequent increments to alert
# means that the onset was found
if alert == cusum_window:
onset_time = date[i - alert]
break
# ma = mu_a = background average
# md = mu_d = background average + 2*sigma
# k_round = integer value of k, that is the reference value to
# poisson cumulative sum
# h = 1 or 2,describes the hastiness of onset alert
# onset_time = the time of the onset
# S = the cusum function
return [ma, md, k_round, norm_channel, cusum, onset_time]
def onset_analysis(self, df_flux, windowstart, windowlen, windowrange, channels_dict,
channel='flux', cusum_window=30, yscale='log',
ylim=None, xlim=None):
self.print_info("Energy channels", channels_dict)
spacecraft = self.spacecraft.upper()
sensor = self.sensor.upper()
color_dict = {
'onset_time': '#e41a1c',
'bg_mean': '#e41a1c',
'flux_peak': '#1a1682',
'bg': '#de8585'
}
if self.spacecraft == 'solo':
flux_series = df_flux[channel]
if self.spacecraft[:2].lower() == 'st':
flux_series = df_flux # [channel]'
if self.spacecraft.lower() == 'soho':
flux_series = df_flux # [channel]
if self.spacecraft.lower() == 'wind':
flux_series = df_flux # [channel]
if self.spacecraft.lower() == 'psp':
flux_series = df_flux[channel]
if self.spacecraft.lower() == 'bepi':
flux_series = df_flux # [channel]
date = flux_series.index
if ylim is None:
ylim = [np.nanmin(flux_series[flux_series > 0]/2),
np.nanmax(flux_series) * 3]
# windowrange is by default None, and then we define the start and stop with integer hours
if windowrange is None:
# dates for start and end of the averaging processes
avg_start = date[0] + datetime.timedelta(hours=windowstart)
# ending time is starting time + a given timedelta in hours
avg_end = avg_start + datetime.timedelta(hours=windowlen)
else:
avg_start, avg_end = windowrange[0], windowrange[1]
if xlim is None:
xlim = [date[0], date[-1]]
else:
df_flux = df_flux[xlim[0]:xlim[-1]]
# onset not yet found
onset_found = False
background_stats = self.mean_value(avg_start, avg_end, flux_series)
onset_stats =\
self.onset_determination(background_stats, flux_series,
cusum_window, avg_end)
if not isinstance(onset_stats[-1], pd._libs.tslibs.nattype.NaTType):
onset_found = True
if self.spacecraft == 'solo':
df_flux_peak = df_flux[df_flux[channel] == df_flux[channel].max()]
if self.spacecraft[:2].lower() == 'st':
df_flux_peak = df_flux[df_flux == df_flux.max()]
if self.spacecraft == 'soho':
df_flux_peak = df_flux[df_flux == df_flux.max()]
if self.spacecraft == 'wind':
df_flux_peak = df_flux[df_flux == df_flux.max()]
if self.spacecraft == 'psp':
# df_flux_peak = df_flux[df_flux == df_flux.max()]
df_flux_peak = df_flux[df_flux[channel] == df_flux[channel].max()]
if self.spacecraft == 'bepi':
df_flux_peak = df_flux[df_flux == df_flux.max()]
# df_flux_peak = df_flux[df_flux[channel] == df_flux[channel].max()]
self.print_info("Flux peak", df_flux_peak)