-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoperational_sep_quantities.py
1729 lines (1538 loc) · 77.3 KB
/
operational_sep_quantities.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 matplotlib.pyplot as plt
import math
import numpy as np
import sys
#import urllib2
import re
import calendar
import datetime
import argparse
from datetime import timedelta
import os
import wget
from calendar import monthrange
import urllib.request
import csv
from dateutil.parser import parse
import scipy.integrate
from numpy import exp
import array as arr
__version__ = "0.4"
__author__ = "Katie Whitman"
__maintainer__ = "Katie Whitman"
__email__ = "[email protected]"
#CHANGES in 0.4: allows users to specify user model or experiment name for
#output files
#CHANGES in 0.4: user passes filename through an argument if selects "user" for
#experiment rather than setting filename at the top of the code
#See full program description in all_program_info() below
datapath = 'data'
outpath = 'output'
badval = -1 #bad data points will be set to this value; must be negative
######FOR USER DATA SETS######
#(expect the first column contains date in YYYY-MM-DD HH:MM:SS format)
#Identify columns containing fluxes you want to analyze
user_col = arr.array('i',[1,2,3,4,5,6])
#DELIMETER between columns; for whitespace separating columns, use " " or ""
user_delim = ","
#DEFINE ENERGY BINS associated with user file and columns specified above as:
# [[Elow1,Ehigh1],[Elow2,Ehigh2],[Elow3,Ehigh3],etc]
#Use -1 in the second edge of the bin to specify integral channel (infinity):
# [[Elow1,-1],[Elow2,-1],[Elow3,-1],etc]
user_energy_bins = [[300,-1],[100,-1],[60,-1],[50,-1],[30,-1],[10,-1]]
############################
#FILENAME(s) containing user input fluxes - WILL BE SET THROUGH ARGUMENT
#Can be list of files that are continuous in time
# e.g. user_fname = ["file1.txt","file2.txt"]
user_fname = ['tmp.txt']
def all_program_info(): #only for documentation purposes
"""This program will calculate various useful pieces of operational
information about SEP events from GOES-08, -10, -11, -12, -13, -14, -15
data and the SEPEM (RSDv2) dataset.
SEP event values are always calculated for threshold definitions:
>10 MeV exceeds 10 pfu
>100 MeV exceed 1 pfu
The user may add an additional threshold through the command line.
This program will check if data is already present in a 'data' directory. If
not, GOES data will be automatically downloaded from NOAA ftp site. SEPEM
(RSDv2) data must be downloaded by the user and unzipped inside the 'data'
directory. Because the SEPEM data set is so large (every 5 minutes from 1974
to 2015), the program will break up the data into yearly files for faster
reading.
The values calculated here are important for space radiation operations:
Onset time, i.e. time to cross thresholds
Peak intensity
Time of peak intensity
Rise time (onset to peak)
End time, i.e. fall below 0.85*threshold for 3 points (15 mins for GOES)
Duration
Event-integrated fluences
User may choose differential proton fluxes (e.g. [MeV s sr cm^2]^-1) or
integral fluxes (e.g. [s sr cm^2]^-1). The program has no internal checks or
requirements on units - EXCEPT FOR THE THRESHOLD DEFINITIONS OF >10, 10
and >100, 1. If you change those thresholds in the main program accordingly,
you should be able to use other units. Also, all of the plots and messages
refer to MeV, pfu, and cm.
If a previous event is ongoing and the specified time period starts with a
threshold already crossed, you may try to set the --DetectPreviousEvent
flag. If the flux drops below threshold before the next event starts, the
program will identify the second event. This will only work if the
threshold is already crossed for the very first time in your specified
time period, and if the flux drops below threshold before the next event
starts.
RUN CODE FROM COMMAND LINE (put on one line), e.g.:
python3 operational_sep_quantities.py --StartDate 2012-05-17
--EndDate '2012-05-19 12:00:00' --Experiment GOES-13
--FluxType integral --showplot
RUN CODE FROM COMMAND FOR USER DATA SET (put on one line), e.g.:
python3 operational_sep_quantities.py --StartDate 2012-05-17
--EndDate '2012-05-19 12:00:00' --Experiment user --ModelName MyModel
--UserFile MyFluxes.txt --FluxType integral --showplot
RUN CODE IMPORTED INTO ANOTHER PYTHON PROGRAM, e.g.:
import operational_sep_quantities as sep
start_date = '2012-05-17'
end_date = '2012-05-19 12:00:00'
experiment = 'GOES-13'
flux_type = 'integral'
model_name = '' #if experiment is user, set model_name to describe data set
user_file = '' #if experiment is user, specify filename containing fluxes
showplot = True #Turn to False if don't want to see plots
detect_prev_event = True #Helps if previous event causes high intensities
threshold = '100,1' #default; modify to add a threshold to 10,10 and 100,1
sep.run_all(start_date, end_date, experiment, flux_type, model_name,
user_file, showplot, detect_prev_event, threshold)
Set the desired directory locations for the data and output at the beginning
of the program in datapath and outpath. Defaults are 'data' and 'output'.
In order to calculate the fluence, the program determines time_resolution
(seconds) from two (fairly random) data points at the start of the SEP
event. GOES and SEPEM data sets have a time resolution of 5 minutes. If the
user wishes to use a data set with measurements at irregular times, then the
subroutine calculate_fluence should be modified.
OUTPUT: This program outputs 3 to 4 files, 1 per defined threshold plus
a summary file containing all of the values calculated for each threshold.
A file named as e.g. fluence_GOES-13_differential_gt10_2012_3_7.csv contains
the event-integrated fluence for each energy channel using the specified
threshold (gt10) to determine start and stop times.
A file named as e.g. sep_values_GOES-13_differential_2012_3_7.csv contains
start time, peak flux, etc, for each of the defined thresholds.
Added functionality to ouput the >10 MeV and >100 MeV time series for the
date range input by the user. If the original data were integral fluxes,
then the output files simply contain the >10 and >100 MeV time series from
the input files. If the original data were differential fluxes, then the
estimated >10 and >100 MeV fluxes are output as time series.
USER INPUT DATA SETS: Users may input their own data set. For example, if an
SEP modeler would like to feed their own intensity time series into this
code and calculate all values in exactly the same way they were calculated
for data, it is possible to do that. Fluxes should be in units of
1/[MeV cm^2 s sr] or 1/[cm^2 s sr] and energy channels in MeV for the plot
labels to be correct. You can use any units, as long as you are consistent
with energy units in energy channel/bin definition and in fluxes and you
MODIFY THE THRESHOLD VALUES TO REFLECT YOUR UNITS. You may then want to
modify plot labels accordingly if not using MeV and cm.
NOTE: The first column in your flux file is assumed to be time in format
YYYY-MM-DD HH:MM:SS. IMPORTANT FORMATTING!!
NOTE: The flux file may contain header lines that start with a hash #,
including blank lines.
NOTE: Any bad or missing fluxes must be indicated by a negative value.
NOTE: Put your flux file into the "datapath" directory.
NOTE: Please use only differential or integral channels. Please do not mix
them. You may have one integral channel in the last bin, as this is the way
HEPAD works and the code has been written to include that HEPAD >700 MeV
bin along with lower differential channels.
USER VARIABLES: The user must modify the following variables at the very
top of the code (around line 30):
user_col - identify columns in your file containing fluxes to analyze;
even if your delimeter is white space, consider the date-time
column as one single column. SET AT TOP OF CODE.
user_delim - delimeter between columns, e.g. " " or "," Use " " for
any amount of whitespace. SET AT TOP OF CODE.
user_energy_bins - define your energy bins at the top of the code in the
variable user_energy_bins. Follow the format in the subroutine
define_energy_bins. SET AT TOP OF CODE.
user_fname - specify the name of the file containing the fluxes
through an argument in the command line. --UserFile The
user_fname variable will be updated with that filename. ARGUMENT
time_resolution - will be calculated using two time points in your file;
if you have irregular time measurements, calculate_fluence()
must be modified/rewritten. AUTOMATICALLY DETERMINED.
"""
def check_paths():
"""Check that the paths that hold the data and output exist. If not, create.
"""
print('Checking that paths exist: ' + datapath + ' and ' + outpath)
if not os.path.isdir(datapath):
print('check_paths: Directory containing fluxes, ' + datapath +
', does not exist. Creating.')
os.mkdir(datapath);
if not os.path.isdir(outpath):
print('check_paths: Directory to store output information, ' + outpath
+ ', does not exist. Creating.')
os.mkdir(outpath);
def make_yearly_files(filename):
"""Convert a large data set into yearly files."""
print('Breaking up the SEPEM data into yearly data files. (This could '
+ 'take a while, but you will not have to do it again.)')
fnamebase = filename.replace('.csv','') #if csv file
fnamebase = fnamebase.replace('.txt','') #if txt file
with open(datapath + '/' + filename) as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
has_header = csv.Sniffer().has_header(csvfile.readline())
if has_header:
next(readCSV) # Skip single header row.
ncol = len(next(readCSV))
csvfile.seek(0) #back to beginning of file
if has_header:
header = csvfile.readline() # save header row.
check_year = 0
for row in readCSV:
date = datetime.datetime.strptime(row[0][0:18],
"%Y-%m-%d %H:%M:%S")
year = date.year
if check_year != year:
if check_year != 0:
outfile.close()
outfname = fnamebase + '_' + str(year) + '.csv'
outfile = open(datapath + '/' + outfname,'w+')
check_year = year
if check_year == 0:
outfname = fnamebase + '_' + str(year) + '.csv'
outfile = open(datapath + '/' + outfname,'w+')
if has_header:
outfile.write(header)
check_year = year
outfile.write(','.join(row))
outfile.write('\n')
outfile.close()
csvfile.close()
return
def check_data(startdate, enddate, experiment, flux_type):
"""Check that the files containing the data are in the data directory. If
the files for the requested dates aren't present, they will be
downloaded from the NOAA website. For SEPEM (RSDv2) data, if missing,
the program prints the URL from which the data can be downloaded and
unzipped manually.
The RSDv2 data set is very large and takes a long time to read as a
single file. This program will generate files containing fluxes for
each year for faster reading.
"""
print('Checking that the requested data is present on your computer.')
styear = startdate.year
stmonth = startdate.month
stday = startdate.day
endyear = enddate.year
endmonth = enddate.month
endday = enddate.day
#Array of filenames that contain the data requested by the User
filenames1 = [] #SEPEM, eps, or epead
filenames2 = [] #hepad
filenames_orien = [] #orientation flag for GOES-13+
#If user wants to use own input file (filename defined at top of code)
if experiment == "user":
nuser = len(user_fname)
for i in range(nuser):
exists = os.path.isfile(datapath + '/' + user_fname[i])
if exists:
filenames1.append(user_fname[i])
if not exists:
sys.exit("You have selected to read a user-input input file "
"with filename " + datapath + '/' + user_fname[i]
+ ". This file is not found! Exiting.")
return filenames1, filenames2, filenames_orien
#SEPEM data set is continuous, but too long; prefer yearly files
#Check if user has yearly files; if not:
#check if user has original SEPEM, then create yearly files
#Otherwise alert user to download data set and try again
if (experiment == "SEPEM"):
year = styear
while (year <= endyear):
fname = 'SEPEM_H_reference_' + str(year) + '.csv'
exists = os.path.isfile(datapath + '/' + fname)
if exists:
filenames1.append(fname)
year = year + 1
if not exists:
full_exists = os.path.isfile(datapath
+ '/SEPEM_H_reference.txt')
if not full_exists:
sys.exit("Please download and unzip the RSDv2 data set."
" You may download the file at"
" http://sepem.eu/help/SEPEM_RDS_v2-00.zip for full "
"fluxes or http://sepem.eu/help/SEPEM_RDS_v2-00.zip "
"for ESA background-subtracted fluxes.")
if full_exists:
#Break up SEPEM data set into yearly files
print('The SEPEM (RSDv2) is more tractable when breaking'
+ ' into yearly data files. Producing yearly files.')
make_yearly_files('SEPEM_H_reference.txt')
year = styear
return filenames1, filenames2, filenames_orien
#GOES data is stored in monthly data files
get_years = []
get_months = []
test_year = styear
test_month = stmonth
test_date = datetime.datetime(year=test_year, month=test_month, day=1)
while (test_date <= enddate):
get_years.append(test_year)
get_months.append(test_month)
test_month = test_month + 1
if (test_month > 12):
test_month = 1
test_year = test_year + 1
test_date = datetime.datetime(year=test_year, month=test_month, day=1)
NFILES = len(get_months) #number of data files to download
#Set correct file prefix for data files
if experiment == "GOES-08":
prefix1 = 'g08_eps_5m_'
prefix2 = 'g08_hepad_5m_'
satellite = 'goes08'
if experiment == "GOES-10":
prefix1 = 'g10_eps_5m_'
prefix2 = 'g10_hepad_5m_'
satellite = 'goes10'
if experiment == "GOES-11":
prefix1 = 'g11_eps_5m_'
prefix2 = 'g11_hepad_5m_'
satellite = 'goes11'
if experiment == "GOES-12":
prefix1 = 'g12_eps_5m_'
prefix2 = 'g12_hepad_5m_'
satellite = 'goes12'
if experiment == "GOES-13":
prefix2 = 'g13_hepad_ap_5m_'
prefix_orien = 'g13_epead_orientation_flag_1m_'
satellite = 'goes13'
if flux_type == "differential":
prefix1 = 'g13_epead_p17ew_5m_'
if flux_type == "integral":
prefix1 = 'g13_epead_cpflux_5m_'
if experiment == "GOES-14":
prefix2 = 'g14_hepad_ap_5m_'
prefix_orien = 'g14_epead_orientation_flag_1m_'
satellite = 'goes14'
if flux_type == "differential":
prefix1 = 'g14_epead_p17ew_5m_'
if flux_type == "integral":
prefix1 = 'g14_epead_cpflux_5m_'
if experiment == "GOES-15":
prefix2 = 'g15_hepad_ap_5m_'
prefix_orien = 'g15_epead_orientation_flag_1m_'
satellite = 'goes15'
if flux_type == "differential":
prefix1 = 'g15_epead_p17ew_5m_'
if flux_type == "integral":
prefix1 = 'g15_epead_cpflux_5m_'
#for every month that data is required, check if file is present or
#needs to be downloaded.
for i in range(NFILES):
year = get_years[i]
month = get_months[i]
last_day = calendar.monthrange(year,month)[1]
date_suffix = '%i%02i01_%i%02i%02i' % (year,month,year,month,
last_day)
fname1 = prefix1 + date_suffix + '.csv'
exists1 = os.path.isfile(datapath + '/' + fname1)
fname2 = prefix2 + date_suffix + '.csv'
exists2 = os.path.isfile(datapath + '/' + fname2)
if (experiment == "GOES-13" or experiment == "GOES-14"
or experiment == "GOES-15"):
fname_orien = prefix_orien + date_suffix + '_v1.0.0.csv'
exists_orien = os.path.isfile(datapath + '/' + fname_orien)
filenames_orien.append(fname_orien)
filenames1.append(fname1)
filenames2.append(fname2)
if not exists1: #download file if not found on your computer
url = ('https://satdat.ngdc.noaa.gov/sem/goes/data/avg/' +
'%i/%02i/%s/csv/%s' % (year,month,satellite,fname1))
print('Downloading GOES data: ' + url)
try:
urllib.request.urlopen(url)
wget.download(url, datapath + '/' + fname1)
except urllib.request.HTTPError:
sys.exit("Cannot access file at " + url +
". Please check that selected spacecraft covers date range.")
if not exists2: #download file if not found on your computer
url = ('https://satdat.ngdc.noaa.gov/sem/goes/data/avg/' +
'%i/%02i/%s/csv/%s' % (year,month,satellite,fname2))
print('Downloading GOES data: ' + url)
try:
urllib.request.urlopen(url)
wget.download(url, datapath + '/' + fname2)
except urllib.request.HTTPError:
sys.exit("Cannot access file at " + url +
". Please check that selected spacecraft covers date range.")
if (experiment == "GOES-13" or experiment == "GOES-14"
or experiment == "GOES-15"):
if not exists_orien: #download file if not found on your computer
url = ('https://satdat.ngdc.noaa.gov/sem/goes/data/avg/' +
'%i/%02i/%s/csv/%s' % (year,month,satellite,fname_orien))
print('Downloading GOES data: ' + url)
try:
urllib.request.urlopen(url)
wget.download(url, datapath + '/' + fname_orien)
except urllib.request.HTTPError:
sys.exit("Cannot access orientation file at " + url +
". Please check that selected spacecraft covers date range.")
return filenames1, filenames2, filenames_orien
def find_goes_data_dimensions(filename):
"""Input open csv file of GOES data. Identifies the start of the data by
searching for the string 'data:', then returns the number of header
rows and data rows present in the file.
"""
with open(datapath + '/' + filename) as csvfile:
#GOES data has very large headers; figure out where the data
#starts inside the file and skip the required number of lines
nhead = 0
for line in csvfile:
nhead = nhead + 1
if 'data:' in line: #location of line before column headers
break
nhead = nhead + 1 #account for column header line
csvfile.readline() #proceed to column header line
readCSV = csv.reader(csvfile, delimiter=',')
nrow = len(csvfile.readlines()) #count lines of data
#print('\nThere are ' + str(nhead) + ' header lines and '
# + str(nrow) + ' rows of data in ' + filename)
csvfile.close()
return nhead, nrow
def get_west_detector(filename, dates):
"""For GOES-13+, identify which detector is facing west from the
orientation flag files. Get an orientation for each data point.
EPEAD orientation flag. 0: A/W faces East and B/E faces West.
1: A/W faces West and B/E faces East. 2: yaw-flip in progress.
"""
nhead, nrow = find_goes_data_dimensions(filename)
orien_dates = []
orientation = []
with open(datapath + '/' + filename) as orienfile:
#GOES data has very large headers; figure out where the data
#starts inside the file and skip the required number of lines
readCSV = csv.reader(orienfile, delimiter=',')
for k in range(nhead):
next(readCSV) #to line with column headers
for row in readCSV:
date = datetime.datetime.strptime(row[0][0:18],
"%Y-%m-%d %H:%M:%S")
orien_dates.append(date)
orientation.append(float(row[1]))
orienfile.close()
#orientation data is in 1 minute intervals while flux data is in 5
#minute intervals. Identify W facing detector for flux times.
#Assume that time stamps match every 5 minutes.
date_index = 0
west_detector = []
for i in range(nrow):
if orien_dates[i] == dates[date_index]:
if orientation[i] == 0:
west_detector.append("B")
if orientation[i] == 1:
west_detector.append("A")
if orientation[i] == 2:
west_detector.append("Flip")
date_index = date_index + 1
if date_index == len(dates):
break
#print('There were ' + str(len(dates)) + ' input dates and there are ' +
# str(len(west_detector)) + ' detector orientations.')
return west_detector
def read_in_files(experiment, flux_type, filenames1, filenames2,
filenames_orien):
"""Read in the appropriate data files with the correct format. Return an
array with dates and fluxes. Bad flux values (any negative flux) are set
to -1. Format is defined to work with the files downloaded directly from
NOAA or the RSDv2 (SEPEM) website as is.
The fluxes output for the GOES-13+ satellites are always from the
westward-facing detector (A or B) by referring to the orientation flags
provided in the associated orientation file. Data taken during a yaw
flip (orientation flag = 2) are excluded and fluxes are set to -1.
Note that the EPS detectors on GOES-08 and -12 face westward. The
EPS detector on GOES-10 faces eastward. GOES-11 is a spinning satellite.
"""
print('Reading in data files for ' + experiment + '.')
NFILES = len(filenames1)
if experiment == "SEPEM":
for i in range(NFILES):
print('Reading in file ' + datapath + '/' + filenames1[i])
with open(datapath + '/' + filenames1[i]) as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
has_header = csv.Sniffer().has_header(csvfile.readline())
if has_header:
next(readCSV) # Skip single header row.
ncol = len(next(readCSV))
csvfile.seek(0) #back to beginning of file
if has_header:
next(readCSV) # Skip header row.
nrow = len(csvfile.readlines())
#print('There are ' + str(ncol) + ' columns and ' + str(nrow) +
# ' rows of data in ' + filenames1[i])
#Define arrays that hold dates and fluxes
dates = []
fluxes = np.zeros(shape=(ncol-1,nrow))
csvfile.seek(0) #back to beginning of file
if has_header:
next(readCSV) # Skip header row.
count = 0
for row in readCSV:
date = datetime.datetime.strptime(row[0][0:18],
"%Y-%m-%d %H:%M:%S")
dates.append(date)
for j in range(1,ncol):
flux = float(row[j])
if flux < 0:
flux = badval
fluxes[j-1][count] = flux
count = count + 1
#If reading in multiple files, then combine all data into one array
#SEPEM currently only has one file, but making generalized
if i==0:
all_fluxes = fluxes
all_dates = dates
else:
all_fluxes = np.concatenate((all_fluxes,fluxes),axis=1)
all_dates = all_dates + dates
return all_dates, all_fluxes
#All GOES data
if experiment != "SEPEM":
if (experiment == "GOES-08" or experiment == "GOES-10" or
experiment == "GOES-11" or experiment == "GOES-12"):
if flux_type == "differential":
columns = [18,19,20,21,22,23] #eps
hepad_columns = [1,2,3,4]
if flux_type == "integral":
columns = [25,26,27,28,29,30] #eps
hepad_columns = [4]
if (experiment == "GOES-13" or experiment == "GOES-14" or
experiment == "GOES-15"):
if flux_type == "differential":
#CORRECTED CHANNELS
columns = [16,24,32,40,48,56] #epead, default A detector
columnsB = [12,20,28,36,44,52] #epead, B detector
hepad_columns = [9,12,15,18]
#UNCORRECTED CHANNELS
#columns = [15,23,31,39,47,55] #epead, default A detector
#columnsB = [11,19,27,35,43,51] #epead, B detector
if flux_type == "integral":
#ONLY CORRECTED CHANNELS AVAILABLE
columns = [18,20,22,24,26,28] #epead, default A detector
columnsB = [4,6,8,10,12,14] #epead, B detector
hepad_columns = [18]
ncol = len(columns)
nhcol = len(hepad_columns)
totcol = ncol + nhcol
#Read in fluxes from files
for i in range(NFILES):
#FIRST set of files for lower energy eps or epead
nhead, nrow = find_goes_data_dimensions(filenames1[i])
dates = []
fluxes = np.zeros(shape=(totcol,nrow))
print('Reading in file ' + datapath + '/' + filenames1[i])
with open(datapath + '/' + filenames1[i]) as csvfile:
#GOES data has very large headers; figure out where the data
#starts inside the file and skip the required number of lines
readCSV = csv.reader(csvfile, delimiter=',')
for k in range(nhead):
next(readCSV) #to start of data
#Get dates first; need dates to identify spacecraft orientation
#for GOES-13+
for row in readCSV:
date = datetime.datetime.strptime(row[0][0:18],
"%Y-%m-%d %H:%M:%S")
dates.append(date)
if (experiment == "GOES-13" or experiment == "GOES-14"
or experiment == "GOES-15"):
west_detector = get_west_detector(filenames_orien[i], dates)
#Go back and get fluxes
count = 0
csvfile.seek(0)
for k in range(nhead):
next(readCSV) #to start of data
for row in readCSV:
for j in range(ncol):
flux = float(row[columns[j]])
#Account for orientation
if (experiment == "GOES-13" or experiment == "GOES-14"
or experiment == "GOES-15"):
if west_detector[count] == "B":
flux = float(row[columnsB[j]])
if west_detector[count] == "Flip":
flux = badval
if flux < 0:
flux = badval
fluxes[j][count] = flux
count = count + 1
csvfile.close()
#SECOND set of files for higher energy hepad
nhead, nrow = find_goes_data_dimensions(filenames2[i])
with open(datapath + '/' + filenames2[i]) as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
for k in range(nhead):
next(readCSV) #to start of data
count = 0
for row in readCSV:
for j in range(nhcol):
flux = float(row[hepad_columns[j]])
if flux < 0:
flux = badval
fluxes[ncol+j][count] = flux
count = count + 1
csvfile.close()
#If reading in multiple files, then combine all data into one array
if i==0:
all_fluxes = fluxes
all_dates = dates
else:
all_fluxes = np.concatenate((all_fluxes,fluxes),axis=1)
all_dates = all_dates + dates
return all_dates, all_fluxes
def read_in_user_files(filenames1):
"""Read in file containing flux time profile information that was
specified by the user.
The first column MUST contain the date in YYYY-MM-DD HH:MM:SS
format. The remaining flux columns to be read in are specified by the
user in the variable user_col at the very beginning of this program.
The date column should always be considered column 0, even if you used
whitespace as your delimeter. The code will consider the date format
YYYY-MM-DD HH:MM:SS as one column even though it contains whitespace.
Any number of header lines are allowed, but they must be indicated by #
at the very beginning, including empty lines.
Be sure to add the energy bins associated with your flux columns in the
subroutine define_energy_bins under the "user" is statement.
"""
print('Reading in user-specified files.')
NFILES = len(filenames1)
ncol = len(user_col) #include column for date
for i in range(NFILES):
with open(datapath + '/' + filenames1[i]) as csvfile:
#Count header lines indicated by hash #
nhead = 0
for line in csvfile:
line = line.lstrip()
if line[0] == "#":
nhead = nhead + 1
else:
break
#number of lines containing data
nrow = len(csvfile.readlines())+1
#Define arrays that hold dates and fluxes
dates = []
fluxes = np.zeros(shape=(ncol,nrow))
csvfile.seek(0) #back to beginning of file
for k in range(nhead):
csvfile.readline() # Skip header rows.
if user_delim == " " or user_delim == "":
for j in range(len(user_col)):
#date takes two columns if separated by whitespace
#adjust the user input columns to account for this
user_col[j] = user_col[j] + 1
count = 0
for line in csvfile:
if line == " " or line == "":
continue
if user_delim == " " or user_delim == "":
row = line.split()
str_date = row[0][0:10] + ' ' + row[1][0:8]
if user_delim != " " and user_delim != "":
row = line.split(user_delim)
str_date = row[0][0:18]
date = datetime.datetime.strptime(str_date,
"%Y-%m-%d %H:%M:%S")
dates.append(date)
for j in range(len(user_col)):
# print("Read in flux for column " + str(user_col[j]) + ': '
# + str(date) + ' ' + row[user_col[j]])
flux = float(row[user_col[j]])
if flux < 0:
flux = badval
fluxes[j][count] = flux
count = count + 1
#If reading in multiple files, then combine all data into one array
#SEPEM currently only has one file, but making generalized
if i==0:
all_fluxes = fluxes
all_dates = dates
else:
all_fluxes = np.concatenate((all_fluxes,fluxes),axis=1)
all_dates = all_dates + dates
return all_dates, all_fluxes
def define_energy_bins(experiment,flux_type):
"""Define the energy bins for the selected spacecraft or data set.
If the user inputs their own file, they must set the user_energy_bins
variable at the top of the code.
"""
#use corrected proton flux for GOES eps or epead; include hepad
#-1 indicates infinity ([700, -1] means all particles above 700 MeV)
if experiment == "SEPEM":
energy_bins = [[5.00,7.23],[7.23,10.46],[10.46,15.12],[15.12,21.87],
[21.87,31.62],[31.62,45.73],[45.73,66.13],
[66.13,95.64],[95.64,138.3],[138.3,200.0],
[200.0,289.2]]
if (flux_type == "integral" and experiment != "SEPEM"):
energy_bins = [[5.0,-1],[10.0,-1],[30.0,-1],
[50.0,-1],[60.0,-1],[100.0,-1],[700.0,-1]]
if (experiment == "GOES-08" or experiment == "GOES-10" or
experiment == "GOES-11" or experiment == "GOES-12"):
if (flux_type == "differential"):
#files named e.g. g08_eps_5m_yyyymmdd_yyyymmdd.csv
energy_bins = [[4.0,9.0],[9.0,15.0],[15.0,44.0],
[40.0,80.0],[80.0,165.0],[165.0,500.0],
[350.0,420.0],[420.0,510.0],[510.0,700.0],
[700.0,-1]]
if (experiment == "GOES-13" or experiment == "GOES-14" or
experiment == "GOES-15"):
if (flux_type == "differential"):
energy_bins = [[4.2,8.7],[8.7,14.5],[15.0,40.0],
[38.0,82.0],[84.0,200.0],[110.0,900.0],
[330.0,420.0],[420.0,510.0],[510.0,700.0],
[700.0,-1]]
if experiment == "user":
#modify to match your energy bins or integral channels
#use -1 in the second edge of the bin for integral channel (infinity)
energy_bins = user_energy_bins
return energy_bins
def extract_date_range(startdate,enddate,all_dates,all_fluxes):
"""Extract fluxes only for the dates in the range specified by the user."""
print('Extracting fluxes for dates: ' + str(startdate) + ' to '
+ str(enddate))
ndates = len(all_dates)
nst = 0
nend = 0
for i in range(ndates):
if all_dates[i] <= startdate:
nst = i
if all_dates[i] <= enddate:
nend = i
nend = min(nend+1, ndates) #adjust to include nend in date range
dates = all_dates[nst:nend]
fluxes = all_fluxes[:,nst:nend]
return dates, fluxes
def do_interpolation(i,dates,flux):
"""If bad fluxes (flux < 0) are found in the data, find the first prior
data point and the first following data point that have good flux values.
Perform linear interpolation in time:
F(t) = F1 + (t - t1)*(F2 - F1)/(t2 - t1)
This subroutine does the calculation for a single instance of bad data
that corresponds to array index i.
"""
ndates = len(dates)
#search for first previous good value prior to the gap
for j in range(i,-1,-1):
if flux[j] != badval:
preflux = flux[j]
predate = dates[j]
print('The first good value previous to gap is on '
+ str(dates[j]) + ' with value ' + str(flux[j]))
break
if j == 0:
sys.exit('There is a data gap at the beginning of the '
'selected time period. Program cannot estimate '
'flux in data gap.')
#search for first previous good value after to the gap
for j in range(i,ndates-1):
if flux[j] != badval:
postflux = flux[j]
postdate = dates[j]
print('The first good value after to gap is on '
+ str(dates[j]) + ' with value ' + str(flux[j]))
break
if j == ndates-1:
sys.exit('There is a data gap up to the end of the '
'selected time period. Program cannot estimate '
'flux in data gap.')
interp_flux = preflux + (dates[i] - predate).total_seconds()\
*(postflux - preflux)/(postdate - predate).total_seconds()
print('Filling gap at time ' + str(dates[i])
+ ' with interpolated flux ' + str(interp_flux))
return interp_flux
def check_for_bad_data(dates,fluxes,energy_bins):
"""Search the data for bad values (flux < 0) and fill the missing data with
an estimate flux found by performing a linear interpolation with time,
using the good flux values immediately surrounding the data gap.
"""
print('Checking for bad data values and filling with linear interpolation '
+ 'with time.')
ndates = len(dates)
nbins = len(energy_bins)
for j in range(ndates): #flux at each time
for i in range(nbins):
if fluxes[i,j] < 0: #bad data
#estimate flux with interpolation in time
print()
print('There is a data gap for time ' + str(dates[j])
+ ' and energy ' + str(energy_bins[i][0]) + ' - '
+ str(energy_bins[i][1]) + ' MeV.'
+ ' Filling in missing value with linear '
+ 'interpolation in time.')
interp_flux = do_interpolation(j,dates,fluxes[i,:])
fluxes[i,j] = interp_flux
print('Finished checking for bad data.')
print()
return fluxes
def from_differential_to_integral_flux(experiment, min_energy, energy_bins,
fluxes):
"""If user selected differential fluxes, convert to integral fluxes to
caluculate operational threshold crossings (>10 MeV protons exceed 10
pfu, >100 MeV protons exceed 1 pfu).
Assume that the measured fluxes correspond to the center of the energy
bin and use power law interpolation to extrapolate integral fluxes
above user input min_energy.
The intent is to calculate >10 MeV and >100 MeV fluxes, but leaving
flexibility for user to define the minimum energy for the integral flux.
An integral flux will be provided for each timestamp (e.g. every 5 mins).
"""
print('Converting differential flux to integral flux for >'
+ str(min_energy) + 'MeV.')
nbins = len(energy_bins)
nflux = len(fluxes[0])
#Check requested min_energy inside data energy range
if min_energy < energy_bins[0][0] or min_energy >= energy_bins[nbins-1][0]:
sys.exit('The selected minimum energy ' + str(min_energy) + ' to create'
' integral fluxes is outside of the range of the data: '
+ str(energy_bins[0][0]) + ' - ' + str(energy_bins[nbins-1][0]))
#Calculate bin center in log space for each energy bin
bin_center = []
for i in range(nbins):
if energy_bins[i][1] != -1:
centerE = math.sqrt(energy_bins[i][0]*energy_bins[i][1])
else:
centerE = -1
bin_center.append(centerE)
#The highest energy EPEAD bin overlaps with all of the HEPAD bins
#For this reason, excluding the highest energy EPEAD bin in
#integral flux estimation, 110 - 900 MeV
if (experiment == "GOES-13" or experiment == "GOES-14" or
experiment == "GOES-15"):
remove_bin = -1
for i in range(nbins):
if energy_bins[i][0] == 110 and energy_bins[i][1] == 900:
remove_bin = i
if remove_bin == -1:
sys.exit("Attempting to remove 110 - 900 MeV bin for "
+ experiment + '. Cannot locate bin. Please check '
'define_energy_bins to see if GOES-13 to GOES-15 bins '
'include 110 - 900 MeV. if not please comment out this '
'section in from_differential_to_integral_flux.')
fluxes = np.delete(fluxes,remove_bin,0)
energy_bins = np.delete(energy_bins,remove_bin,0)
bin_center = np.delete(bin_center,remove_bin,0)
nbins = nbins-1
#integrate by power law interpolation; assume spectrum the shape of a
#power law from one bin center to the next. This accounts for the case
#where the minimum energy falls inside of a bin or there are overlapping
#energy bins or gaps between bins.
#An energy bin value of -1 (e.g. [700,-1]) indicates infinity - already an
#integral channel. This happens for HEPAD. If the integral channel is the
#last channel, then the flux will be added. If it is a middle bin, it will
#be skipped.
integral_fluxes = []
integral_fluxes_check = []
for j in range(nflux): #flux at each time
sum_flux = 0
ninc = 0 #number of energy bins included in integral flux estimate
for i in range(nbins-1):
if bin_center[i+1] < min_energy:
continue
else:
if energy_bins[i][1] == -1 or energy_bins[i+1][1] == -1:
#bin is already an integral flux, e.g. last HEPAD bin
continue
if fluxes[i,j] < 0 or fluxes[i+1,j] < 0: #bad data
sys.exit('Bad flux data value found for bin ' + str(i) + ','
+ str(j) + '. This should not happen. '
+ 'Did you call check_for_bad_data() first?')
if fluxes[i,j] == 0 and fluxes[i+1,j] == 0: #add 0 flux
ninc = ninc + 1
continue
F1 = fluxes[i,j]
F2 = fluxes[i+1,j]
if fluxes[i,j] == 0: #sub very small value for interpolation
F1 = 1e-15
if fluxes[i+1,j] == 0:
F2 = 1e-15
logF1 = np.log(F1)
logF2 = np.log(F2)
logE1 = np.log(bin_center[i])
logE2 = np.log(bin_center[i+1])
endE = bin_center[i+1]
f = lambda x:exp(logF1
+ (np.log(x)-logE1)*(logF2-logF1)/(logE2-logE1))
startE = max(bin_center[i],min_energy)
fint = scipy.integrate.quad(f,startE,endE)
sum_flux = sum_flux + fint[0]
ninc = ninc + 1
#if last bin is integral, add (HEPAD)
if energy_bins[nbins-1][1] == -1 and fluxes[nbins-1,j] >= 0:
sum_flux = sum_flux + fluxes[nbins-1,j]
ninc = ninc + 1
if ninc == 0:
sum_flux = -1
integral_fluxes.append(sum_flux)
return integral_fluxes
def extract_integral_fluxes(fluxes, experiment, flux_type, flux_thresholds,
energy_thresholds, energy_bins):
"""Select or create the integral fluxes that correspond to the desired
energy thresholds.
If the user selected differential fluxes, then the
differential fluxes will be converted to integral fluxes with the
minimum energy defined by the set energy thresholds.