This repository has been archived by the owner on Jan 18, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
epd_loader.py
852 lines (730 loc) · 32.9 KB
/
epd_loader.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
import datetime
import glob
import itertools
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
import re
import sys
import urllib.request
from pathlib import Path
from heliopy.data.util import cdf2df
from urllib.error import HTTPError
import cdflib
###############################################################################
"""
Example code that loads low latency (ll) electron and proton (+alphas) fluxes
(and errors) for 'ept' 'north' telescope from Apr 15 2021 to Apr 16 2021 into
two Pandas dataframes (one for protons & alphas, one for electrons). In general
available are 'sun', 'asun', 'north', and 'south' viewing directions for 'ept'
and 'het' telescopes of SolO/EPD.
from epd_loader import *
df_protons, df_electrons, energies = \
read_epd_cdf('ept', 'north', 'll', 20210415, 20210416,
path='/home/userxyz/solo/data/')
# plot protons and alphas
ax = df_protons.plot(logy=True, subplots=True, figsize=(20,60))
plt.show()
# plot electrons
ax = df_electrons.plot(logy=True, subplots=True, figsize=(20,60))
plt.show()
"""
"""
Example code that loads level 2 (l2) electron and proton (+alphas) fluxes
(and errors) for 'het' 'sun' telescope from Aug 20 2020 to Aug 20 2020 into
two Pandas dataframes (one for protons & alphas, one for electrons).
from epd_loader import *
df_protons, df_electrons, energies = \
read_epd_cdf('het', 'sun', 'l2', 20200820, 20200821,
path='/home/userxyz/solo/data/')
# plot protons and alphas
ax = df_protons.plot(logy=True, subplots=True, figsize=(20,60))
plt.show()
# plot electrons
ax = df_electrons.plot(logy=True, subplots=True, figsize=(20,60))
plt.show()
"""
"""
Level 2 data can be downloaded from http://soar.esac.esa.int/soar/ using
epd_l2_download(). Following example downloads 'ept' 'north' telescope data for
Aug 20 2020 (downloads 1 file/day per call).
epd_l2_download(20200820, '/home/userxyz/solo/data/l2/epd/ept/', 'ept', 'north')
epd_ll_download() provides the same functionality for low latency data.
"""
###############################################################################
def check_duplicates(filelist, verbose=True):
"""
Checks for duplicate file entries in filelist (that are only different by
version number). Returns filelist with duplicates removed.
"""
for _, g in itertools.groupby(filelist, lambda f: f.split('_')[:-1]):
dups = list(g)
if len(dups) > 1:
dups.sort()
if verbose:
print('')
print('WARNING: Following data files are duplicates with ' +
'different version numbers:')
for i in dups:
print(i)
if verbose:
print('')
print('Removing following files from filelist that will be read: ')
for n in range(len(dups)-1):
print(dups[n])
filelist.remove(dups[n])
if verbose:
print('You might want to delete these files in order to get rid ' +
'of this message.')
return filelist
def get_filename_url(cd):
"""
Get download filename for a url from content-disposition
"""
if not cd:
return None
fname = re.findall('filename=(.+)', cd)
if len(fname) == 0:
return None
return fname[0][1:-1]
def load_tqdm(verbose=True):
"""
Tries to load tqdm package for displaying download progress.
Return True or False, depending of success state.
If not available, returns False.
"""
try:
from tqdm import tqdm
class DownloadProgressBar(tqdm):
def update_to(self, b=1, bsize=1, tsize=None):
if tsize is not None:
self.total = tsize
self.update(b * bsize - self.n)
def download_url(url, output_path):
with DownloadProgressBar(unit='B', unit_scale=True, miniters=1,
desc=output_path.split('/')[-1]) as t:
urllib.request.urlretrieve(url, filename=output_path,
reporthook=t.update_to)
tqdm_available = True
except ModuleNotFoundError:
if verbose:
print("Module tqdm not installed, won't show progress bar.")
tqdm_available = False
download_url = None
return tqdm_available, download_url
def get_epd_filelist(sensor, level, startdate, enddate, path,
filenames_only=False):
"""
INPUT:
sensor: 'ept' or 'het'
level: 'll', 'l2'
startdate, enddate: YYYYMMDD
path: directory in which the data is located;
e.g. '/home/gieseler/uni/solo/data/l2/epd/ept/'
filenames_only: if True only give the filenames, not the full path
RETURNS:
Dictionary with four entries for 'sun', 'asun', 'north', 'south';
each containing a list of files matching selection criteria.
"""
if level == 'll':
l_str = 'LL02'
t_str = 'T??????-????????T??????'
if level == 'l2':
l_str = 'L2'
t_str = ''
filelist_sun = []
filelist_asun = []
filelist_north = []
filelist_south = []
for i in range(startdate, enddate+1):
filelist_sun = filelist_sun + \
glob.glob(path+'solo_'+l_str+'_epd-'+sensor+'-sun-rates_' +
str(i) + t_str + '_V*.cdf')
filelist_asun = filelist_asun + \
glob.glob(path+'solo_'+l_str+'_epd-'+sensor+'-asun-rates_' +
str(i) + t_str + '_V*.cdf')
filelist_north = filelist_north + \
glob.glob(path+'solo_'+l_str+'_epd-'+sensor+'-north-rates_' +
str(i) + t_str + '_V*.cdf')
filelist_south = filelist_south + \
glob.glob(path+'solo_'+l_str+'_epd-'+sensor+'-south-rates_' +
str(i) + t_str + '_V*.cdf')
if filenames_only:
filelist_sun = [os.path.basename(x) for x in filelist_sun]
filelist_asun = [os.path.basename(x) for x in filelist_asun]
filelist_north = [os.path.basename(x) for x in filelist_north]
filelist_south = [os.path.basename(x) for x in filelist_south]
filelist = {
'sun': filelist_sun,
'asun': filelist_asun,
'north': filelist_north,
'south': filelist_south
}
return filelist
def get_step_filelist(level, startdate, enddate, path,
filenames_only=False):
"""
INPUT:
level: 'll', 'l2'
startdate, enddate: YYYYMMDD
path: directory in which the data is located;
e.g. '/home/gieseler/uni/solo/data/l2/epd/step/'
filenames_only: if True only give the filenames, not the full path
RETURNS:
List of files matching selection criteria.
"""
sensor = 'step'
if level == 'll':
l_str = 'LL02'
t_str = 'T??????-????????T??????'
if level == 'l2':
l_str = 'L2'
t_str = ''
filelist = []
for i in range(startdate, enddate+1):
filelist = filelist + \
glob.glob(path+'solo_'+l_str+'_epd-'+sensor+'-rates_' +
str(i) + t_str + '_V*.cdf')
if filenames_only:
filelist = [os.path.basename(x) for x in filelist]
return filelist
def epd_ll_download(date, path, sensor, viewing=None):
"""
Download EPD low latency data from http://soar.esac.esa.int/soar
One file/day per call.
Note: for sensor 'step' the 'viewing' parameter is necessary, but it
Example:
epd_ll_download(20210415,
'/home/userxyz/solo/data/low_latency/epd/ept/',
'ept', 'north')
epd_ll_download(20200820,
'/home/userxyz/solo/data/low_latency/epd/step/',
'step')
"""
# try loading tqdm for download progress display
tqdm_available, download_url = load_tqdm(verbose=True)
# get list of available data files, obtain corresponding start & end time
fl = get_available_soar_files(date, date, sensor, 'll')
# try:
if sensor.lower() == 'step':
stime = 'T'+fl[0].split('T')[1].split('-')[0]
etime = 'T'+fl[0].split('T')[2].split('_')[0]
url = 'http://soar.esac.esa.int/soar-sl-tap/data?' + \
'retrieval_type=LAST_PRODUCT&data_item_id=solo_LL02_epd-' + \
sensor.lower()+'-rates_'+str(date) + \
stime+'-'+str(date+1)+etime+'&product_type=LOW_LATENCY'
else:
stime = 'T'+fl[0].split('T')[1].split('-')[0] # fl[0][-32:-25]
etime = 'T'+fl[0].split('T')[2].split('_')[0] # fl[0][-16:-9]
url = 'http://soar.esac.esa.int/soar-sl-tap/data?' + \
'retrieval_type=LAST_PRODUCT&data_item_id=solo_LL02_epd-' + \
sensor.lower()+'-'+viewing.lower()+'-rates_'+str(date) + \
stime+'-'+str(date+1)+etime+'&product_type=LOW_LATENCY'
# Get filename from url
file_name = get_filename_url(
urllib.request.urlopen(url).headers['Content-Disposition'])
if tqdm_available:
download_url(url, path+file_name)
else:
urllib.request.urlretrieve(url, path+file_name)
return path+file_name
def epd_l2_download(date, path, sensor, viewing=None):
"""
Download EPD level 2 data from http://soar.esac.esa.int/soar
One file/day per call.
Example:
epd_l2_download(20200820,
'/home/userxyz/solo/data/l2/epd/ept/',
'ept', 'north')
epd_l2_download(20200820,
'/home/userxyz/solo/data/l2/epd/step/',
'step')
"""
# try loading tqdm for download progress display
tqdm_available, download_url = load_tqdm(verbose=True)
if sensor.lower() == 'step':
url = 'http://soar.esac.esa.int/soar-sl-tap/data?' + \
'retrieval_type=LAST_PRODUCT&data_item_id=solo_L2_epd-' + \
sensor.lower()+'-rates_'+str(date) + \
'&product_type=SCIENCE'
else:
url = 'http://soar.esac.esa.int/soar-sl-tap/data?' + \
'retrieval_type=LAST_PRODUCT&data_item_id=solo_L2_epd-' + \
sensor.lower()+'-'+viewing.lower()+'-rates_'+str(date) + \
'&product_type=SCIENCE'
# Get filename from url
file_name = get_filename_url(
urllib.request.urlopen(url).headers['Content-Disposition'])
if tqdm_available:
download_url(url, path+file_name)
else:
urllib.request.urlretrieve(url, path+file_name)
return path+file_name
def get_available_soar_files(startdate, enddate, sensor, level='l2'):
"""
Checks SOAR database for available files in date range for give sensor and
data level. Returns list of file names.
"""
from astropy.io.votable import parse_single_table
# add 1 day to enddate to better work with SOAR's API
# enddate = (pd.to_datetime(str(enddate))+
# pd.to_timedelta('1d')).strftime('%Y%m%d')
sy = str(startdate)[0:4]
sm = str(startdate)[4:6]
sd = str(startdate)[6:8]
ey = str(enddate)[0:4]
em = str(enddate)[4:6]
ed = str(enddate)[6:8]
if level.lower() == 'l2':
p_level = 'L2' # "processing_level"
# data_type = 'v_sc_data_item'
if level.lower() == 'll':
p_level = 'LL02' # "processing_level"
# data_type = 'v_ll_data_item'
data_type = 'v_public_files'
url = "http://soar.esac.esa.int/soar-sl-tap/tap/sync?REQUEST=doQuery&" + \
"LANG=ADQL&retrieval_type=LAST_PRODUCT&FORMAT=votable_plain&" + \
"QUERY=SELECT+*+FROM+"+data_type + \
"+WHERE+(instrument='EPD')+AND+((begin_time%3E%3D'"+sy+"-"+sm + \
"-"+sd+"+00:00:00')+AND+(begin_time%3C%3D'"+ey+"-"+em+"-"+ed + \
"+01:00:00'))"
filelist = urllib.request.urlretrieve(url)
# open VO table, convert to astropy table, convert to pandas dataframe
df = parse_single_table(filelist[0]).to_table().to_pandas()
# convert bytestrings to unicode, from stackoverflow.com/a/67051068/2336056
for col, dtype in df.dtypes.items():
if dtype == np.object: # Only process object columns.
# decode, or return original value if decode return Nan
df[col] = df[col].str.decode('utf-8').fillna(df[col])
# remove duplicates with older version number
df = df.sort_values('file_name')
df.drop_duplicates(subset=['item_id'], keep='last', inplace=True)
# only use data level wanted; i.e., 'LL' or 'L2'
df = df[df['processing_level'] == p_level]
# list filenames for given telescope (e.g., 'HET')
# filelist = df['filename'][df['sensor'] == sensor.upper()].sort_values()
filelist = [s for s in df['file_name'].values if sensor.lower() in s]
# list filenames for 'rates' type (i.e., remove 'hcad')
filelist = [s for s in filelist if "rates" in s]
# filelist.sort()
if len(filelist) == 0:
print('No corresponding data found at SOAR!')
return filelist
def autodownload_cdf(startdate, enddate, sensor, level, path):
"""
Uses get_available_soar_files() to check which files for selection criteria
are available online. Compares with locally available files at 'path', and
downloads missing files to 'path' using epd_l*_download()
"""
fls = get_available_soar_files(startdate, enddate, sensor, level)
for i in fls:
my_file = Path(path)/i
if not my_file.is_file():
print(i+' MISSING => DOWNLOADING...')
tdate = int(i.split('_')[3].split('T')[0])
tview = i.split('-')[2]
if level.lower() == 'll':
# print(sensor, tview, tdate, path)
_ = epd_ll_download(date=tdate, path=path, sensor=sensor,
viewing=tview)
if level.lower() == 'l2':
# print(sensor, tview, tdate, path)
_ = epd_l2_download(date=tdate, path=path, sensor=sensor,
viewing=tview)
return
##################################################
def epd_load(sensor, level, startdate, enddate=None, viewing=None, path=None,
autodownload=False):
"""
INPUT:
sensor: 'ept', 'het', or 'step' (string)
level: 'll' or 'l2' (string)
startdate,
enddate: YYYYMMDD, e.g., 20210415 (integer)
(if no enddate is given, 'enddate = startdate' will be set)
viewing: 'sun', 'asun', 'north', or 'south'; not needed for STEP (string)
path: directory in which Solar Orbiter data is/should be organized;
e.g. '/home/userxyz/solo/data/' (string)
autodownload: if True will try to download missing data files from SOAR
RETURNS:
For EPT & HET:
1. Pandas dataframe with proton fluxes and errors (for EPT also
alpha particles) in 'particles / (s cm^2 sr MeV)'
2. Pandas dataframe with electron fluxes and errors in
'particles / (s cm^2 sr MeV)'
3. Dictionary with energy information for all particles:
- String with energy channel info
- Value of lower energy bin edge in MeV
- Value of energy bin width in MeV
For STEP:
1. Pandas dataframe with fluxes and errors in
'particles / (s cm^2 sr MeV)'
2. Dictionary with energy information for all particles:
- String with energy channel info
- Value of lower energy bin edge in MeV
- Value of energy bin width in MeV
"""
if sensor.lower() == 'step':
datadf, energies_dict = \
read_step_cdf(level, startdate, enddate, path, autodownload)
return datadf, energies_dict
if sensor.lower() == 'ept' or sensor.lower() == 'het':
if viewing is None:
raise Exception("EPT and HET need a telescope 'viewing' "+
"direction! No data read!")
df_epd_p = []
df_epd_e = []
energies_dict = []
else:
df_epd_p, df_epd_e, energies_dict = \
read_epd_cdf(sensor, viewing, level, startdate, enddate, path,
autodownload)
return df_epd_p, df_epd_e, energies_dict
def read_epd_cdf(sensor, viewing, level, startdate, enddate=None, path=None,
autodownload=False):
"""
INPUT:
sensor: 'ept' or 'het' (string)
viewing: 'sun', 'asun', 'north', or 'south' (string)
level: 'll' or 'l2' (string)
startdate,
enddate: YYYYMMDD, e.g., 20210415 (integer)
(if no enddate is given, 'enddate = startdate' will be set)
path: directory in which Solar Orbiter data is/should be organized;
e.g. '/home/gieseler/uni/solo/data/' (string)
autodownload: if True will try to download missing data files from SOAR
RETURNS:
1. Pandas dataframe with proton fluxes and errors (for EPT also alpha
particles) in 'particles / (s cm^2 sr MeV)'
2. Pandas dataframe with electron fluxes and errors in
'particles / (s cm^2 sr MeV)'
3. Dictionary with energy information for all particles:
- String with energy channel info
- Value of lower energy bin edge in MeV
- Value of energy bin width in MeV
"""
# if no path to data directory is given, use the current directory
if path is None:
path = os.getcwd()
# select sub-directory for corresponding sensor (EPT, HET)
if level.lower() == 'll':
path = Path(path)/'low_latency'/'epd'/sensor.lower()
if level.lower() == 'l2':
path = Path(path)/'l2'/'epd'/sensor.lower()
# add a OS-specific '/' to end end of 'path'
path = f'{path}{os.sep}'
# if no 'enddate' is given, get data only for single day of 'startdate'
if enddate is None:
enddate = startdate
# if autodownload, check online available files and download if not locally
if autodownload:
autodownload_cdf(startdate, enddate, sensor.lower(), level.lower(),
path)
# get list of local files for date range
filelist = get_epd_filelist(sensor.lower(), level.lower(), startdate,
enddate, path=path)[viewing.lower()]
# check for duplicate files with different version numbers and remove them
filelist = check_duplicates(filelist, verbose=True)
if len(filelist) == 0:
raise Exception('WARNING: No corresponding data files found! '+
'Try different settings, path or autodownload.')
df_epd_p = []
df_epd_e = []
energies_dict = []
else:
""" <-- get column names of dataframe """
if sensor.lower() == 'ept':
if level.lower() == 'll':
protons = 'Prot'
electrons = 'Ele'
e_epoch = 'EPOCH'
if level.lower() == 'l2':
protons = 'Ion'
electrons = 'Electron'
e_epoch = 'EPOCH_1'
if sensor.lower() == 'het':
if level.lower() == 'll':
protons = 'H'
electrons = 'Ele'
e_epoch = 'EPOCH'
if level.lower() == 'l2':
protons = 'H' # EPOCH
electrons = 'Electron' # EPOCH_4, QUALITY_FLAG_4
e_epoch = 'EPOCH_4'
# load cdf files
t_cdf_file = cdflib.CDF(filelist[0])
df_p = cdf2df(t_cdf_file, "EPOCH")
df_e = cdf2df(t_cdf_file, e_epoch)
if len(filelist) > 1:
for f in filelist[1:]:
t_cdf_file = cdflib.CDF(f)
t_df_p = cdf2df(t_cdf_file, "EPOCH")
t_df_e = cdf2df(t_cdf_file, e_epoch)
df_p = pd.concat([df_p, t_df_p])
df_e = pd.concat([df_e, t_df_e])
# p intensities:
flux_p_channels = \
[protons+f'_Flux_{i}' for i in
range(t_cdf_file.varinq(protons+f'_Flux')['Dim_Sizes'][0])]
# p errors:
if level.lower() == 'll':
flux_sigma_p_channels = \
[protons+f'_Flux_Sigma_{i}' for i in
range(t_cdf_file.varinq(protons+f'_Flux')['Dim_Sizes'][0])]
if level.lower() == 'l2':
flux_sigma_p_channels = \
[protons+f'_Uncertainty_{i}' for i in
range(t_cdf_file.varinq(protons+f'_Flux')['Dim_Sizes'][0])]
# p rates:
rate_p_channels = \
[protons+f'_Rate_{i}' for i in
range(t_cdf_file.varinq(protons+f'_Rate')['Dim_Sizes'][0])]
if sensor.lower() == 'ept':
# alpha intensities:
flux_a_channels = \
[f'Alpha_Flux_{i}' for i in
range(t_cdf_file.varinq("Alpha_Flux")['Dim_Sizes'][0])]
# alpha errors:
if level.lower() == 'll':
flux_sigma_a_channels = \
[f'Alpha_Flux_Sigma_{i}' for i in
range(t_cdf_file.varinq("Alpha_Flux")['Dim_Sizes'][0])]
if level.lower() == 'l2':
flux_sigma_a_channels = \
[f'Alpha_Uncertainty_{i}' for i in
range(t_cdf_file.varinq("Alpha_Flux")['Dim_Sizes'][0])]
# alpha rates:
rate_a_channels = \
[f'Alpha_Rate_{i}' for i in
range(t_cdf_file.varinq("Alpha_Rate")['Dim_Sizes'][0])]
# e intensities:
flux_e_channels = \
[electrons+f'_Flux_{i}' for i in
range(t_cdf_file.varinq(electrons+f'_Flux')['Dim_Sizes'][0])]
# e errors:
if level.lower() == 'll':
flux_sigma_e_channels = \
[f'Ele_Flux_Sigma_{i}' for i in
range(t_cdf_file.varinq(electrons+f'_Flux')['Dim_Sizes'][0])]
if level.lower() == 'l2':
flux_sigma_e_channels = \
[f'Electron_Uncertainty_{i}' for i in
range(t_cdf_file.varinq(electrons+f'_Flux')['Dim_Sizes'][0])]
# e rates:
rate_e_channels = \
[electrons+f'_Rate_{i}' for i in
range(t_cdf_file.varinq(electrons+f'_Rate')['Dim_Sizes'][0])]
if level.lower() == 'l2':
if sensor.lower() == 'het':
df_epd_p = pd.concat(
[df_p[flux_p_channels], df_p[flux_sigma_p_channels],
df_p[rate_p_channels], df_p['DELTA_EPOCH'],
df_p['QUALITY_FLAG'], df_p['QUALITY_BITMASK']],
axis=1,
keys=['H_Flux', 'H_Uncertainty', 'H_Rate',
'DELTA_EPOCH', 'QUALITY_FLAG', 'QUALITY_BITMASK'])
df_epd_e = pd.concat([df_e[flux_e_channels],
df_e[flux_sigma_e_channels],
df_e[rate_e_channels],
df_e['DELTA_EPOCH_4'],
df_e['QUALITY_FLAG_4'],
df_e['QUALITY_BITMASK_4']], axis=1,
keys=['Electron_Flux',
'Electron_Uncertainty',
'Electron_Rate',
'DELTA_EPOCH_4',
'QUALITY_FLAG_4',
'QUALITY_BITMASK_4'])
if sensor.lower() == 'ept':
df_epd_p = pd.concat(
[df_p[flux_p_channels], df_p[flux_sigma_p_channels],
df_p[rate_p_channels], df_p[flux_a_channels],
df_p[flux_sigma_a_channels], df_p[rate_a_channels],
df_p['DELTA_EPOCH'], df_p['QUALITY_FLAG'],
df_p['QUALITY_BITMASK']],
axis=1,
keys=['Ion_Flux', 'Ion_Uncertainty', 'Ion_Rate',
'Alpha_Flux', 'Alpha_Uncertainty', 'Alpha_Rate',
'DELTA_EPOCH', 'QUALITY_FLAG', 'QUALITY_BITMASK'])
df_epd_e = pd.concat([df_e[flux_e_channels],
df_e[flux_sigma_e_channels],
df_e[rate_e_channels],
df_e['DELTA_EPOCH_1'],
df_e['QUALITY_FLAG_1'],
df_e['QUALITY_BITMASK_1']], axis=1,
keys=['Electron_Flux',
'Electron_Uncertainty',
'Electron_Rate',
'DELTA_EPOCH_1',
'QUALITY_FLAG_1',
'QUALITY_BITMASK_1'])
if level.lower() == 'll':
if sensor.lower() == 'het':
df_epd_p = pd.concat(
[df_p[flux_p_channels], df_p[flux_sigma_p_channels]],
axis=1, keys=['H_Flux', 'H_Uncertainty', 'QUALITY_FLAG'])
if sensor.lower() == 'ept':
df_epd_p = pd.concat(
[df_p[flux_p_channels], df_p[flux_sigma_p_channels],
df_p[flux_a_channels], df_p[flux_sigma_a_channels],
df_p['QUALITY_FLAG']],
axis=1, keys=['Ion_Flux', 'Ion_Uncertainty',
'Alpha_Flux', 'Alpha_Uncertainty',
'QUALITY_FLAG'])
df_epd_e = pd.concat([df_e[flux_e_channels],
df_e[flux_sigma_e_channels],
df_e['QUALITY_FLAG']], axis=1,
keys=['Electron_Flux',
'Electron_Uncertainty',
'QUALITY_FLAG'])
# replace FILLVALUES in dataframes with np.nan
# t_cdf_file.varattsget("Ion_Flux")["FILLVAL"][0] = -1e+31
# same for l2 & ll and het & ept and e, p/ion, alpha
df_epd_p = df_epd_p.replace(-1e+31, np.nan)
df_epd_e = df_epd_e.replace(-1e+31, np.nan)
# NB: t_cdf_file.varinq('Ion_Flux')['Pad'][0] = -1e+30
energies_dict = {
protons+"_Bins_Text":
t_cdf_file.varget(protons+'_Bins_Text'),
protons+"_Bins_Low_Energy":
t_cdf_file.varget(protons+'_Bins_Low_Energy'),
protons+"_Bins_Width":
t_cdf_file.varget(protons+'_Bins_Width'),
electrons+"_Bins_Text":
t_cdf_file.varget(electrons+'_Bins_Text'),
electrons+"_Bins_Low_Energy":
t_cdf_file.varget(electrons+'_Bins_Low_Energy'),
electrons+"_Bins_Width":
t_cdf_file.varget(electrons+'_Bins_Width')
}
if sensor.lower() == 'ept':
energies_dict["Alpha_Bins_Text"] = \
t_cdf_file.varget('Alpha_Bins_Text')
energies_dict["Alpha_Bins_Low_Energy"] = \
t_cdf_file.varget('Alpha_Bins_Low_Energy')
energies_dict["Alpha_Bins_Width"] = \
t_cdf_file.varget('Alpha_Bins_Width')
'''
Careful if adding more species - they might have different EPOCH
dependencies and cannot easily be put in the same dataframe!
'''
return df_epd_p, df_epd_e, energies_dict
def read_step_cdf(level, startdate, enddate=None, path=None,
autodownload=False):
"""
INPUT:
level: 'll' or 'l2' (string)
startdate,
enddate: YYYYMMDD, e.g., 20210415 (integer)
(if no enddate is given, 'enddate = startdate' will be set)
path: directory in which Solar Orbiter data is/should be organized;
e.g. '/home/gieseler/uni/solo/data/' (string)
autodownload: if True will try to download missing data files from SOAR
RETURNS:
1. Pandas dataframe with fluxes and errors in 'particles / (s cm^2 sr MeV)'
2. Dictionary with energy information for all particles:
- String with energy channel info
- Value of lower energy bin edge in MeV
- Value of energy bin width in MeV
"""
sensor = 'step'
# if no path to data directory is given, use the current directory
if path is None:
path = os.getcwd()
# select sub-directory for corresponding sensor (in this case just 'step')
if level.lower() == 'll':
path = Path(path)/'low_latency'/'epd'/sensor.lower()
if level.lower() == 'l2':
path = Path(path)/'l2'/'epd'/sensor.lower()
# add a OS-specific '/' to end end of 'path'
path = f'{path}{os.sep}'
# if no 'enddate' is given, get data only for single day of 'startdate'
if enddate is None:
enddate = startdate
# if True, check online available files and download if not locally present
if autodownload:
autodownload_cdf(startdate, enddate, sensor.lower(), level.lower(),
path)
# get list of local files for date range
filelist = get_step_filelist(level.lower(), startdate, enddate, path=path)
# check for duplicate files with different version numbers and remove them
filelist = check_duplicates(filelist, verbose=True)
if len(filelist) == 0:
raise Exception('WARNING: No corresponding data files found! '+
'Try different settings, path or autodownload.')
datadf = []
energies_dict = []
else:
all_cdf = []
for file in filelist:
all_cdf.append(cdflib.cdfread.CDF(file))
if level == 'l2':
param_list = ['Integral_Flux', 'Magnet_Flux', 'Integral_Rate',
'Magnet_Rate', 'Magnet_Uncertainty',
'Integral_Uncertainty']
#set up the dictionary:
energies_dict = \
{"Bins_Text": all_cdf[0]['Bins_Text'],
"Bins_Low_Energy": all_cdf[0]['Bins_Low_Energy'],
"Bins_Width": all_cdf[0]['Bins_Width'],
"Sector_Bins_Text": all_cdf[0]['Sector_Bins_Text'],
"Sector_Bins_Low_Energy": all_cdf[0]['Sector_Bins_Low_Energy'],
"Sector_Bins_Width": all_cdf[0]['Sector_Bins_Width']
}
if level == 'll':
param_list = ['Integral_Flux', 'Ion_Flux', 'Integral_Flux_Sigma',
'Ion_Flux_Sigma']
#set up the dictionary:
energies_dict = \
{"Integral_Bins_Text": all_cdf[0]['Integral_Bins_Text'],
"Integral_Bins_Low_Energy": all_cdf[0]['Integral_Bins_Low_Energy'],
"Integral_Bins_Width": all_cdf[0]['Integral_Bins_Width'],
"Ion_Bins_Text": all_cdf[0]['Ion_Bins_Text'],
"Ion_Bins_Low_Energy": all_cdf[0]['Ion_Bins_Low_Energy'],
"Ion_Bins_Width": all_cdf[0]['Ion_Bins_Width']
}
df_list = []
for cdffile in all_cdf:
col_list = []
for key in param_list:
try:
col_list.append(pd.DataFrame(cdffile[key],
index=cdffile['EPOCH']))
except TypeError:
print(' ')
print("WARNING: Gap in dataframe due to missing cdf file.")
break
try:
temp_df = pd.concat(col_list, axis=1, keys=param_list)
df_list.append(temp_df)
except ValueError:
continue
datadf = pd.concat(df_list)
# transform the index of the dataframe into pd_datetime
# notice the transform alldata.index -> np.int_ so that encode()
# understands the format
datetimes = cdflib.cdfepoch.encode(np.int_(datadf.index))
datadf.index = pd.to_datetime(datetimes)
#Finally make sure that bad values are set to nan:
datadf = datadf.replace(-1e+31, np.nan)
'''
Careful if adding more species - they might have different EPOCH
dependencies and cannot easily be put in the same dataframe!
'''
return datadf, energies_dict
"""
# Example codes for testing:
df_protons, df_electrons, energies = epd_load(sensor='het', viewing='sun', level='ll',
startdate=20210416, enddate=20210417, path='/home/gieseler/uni/solo/data', autodownload=True)
df_protons, df_electrons, energies = epd_load(sensor='ept', viewing='sun', level='ll',
startdate=20210416, enddate=20210417, path='/home/gieseler/uni/solo/data', autodownload=True)
df_protons, energies = epd_load(sensor='step', level='ll',
startdate=20210416, enddate=20210417, path='/home/gieseler/uni/solo/data', autodownload=True)
df_protons, df_electrons, energies = epd_load(sensor='het', viewing='sun', level='l2',
startdate=20200820, enddate=20200821, path='/home/gieseler/uni/solo/data', autodownload=True)
df_protons, df_electrons, energies = epd_load(sensor='ept', viewing='sun', level='l2',
startdate=20200820, enddate=20200821, path='/home/gieseler/uni/solo/data', autodownload=True)
df_protons, energies = epd_load(sensor='step', level='l2',
startdate=20200820, enddate=20200821, path='/home/gieseler/uni/solo/data', autodownload=True)
"""