-
Notifications
You must be signed in to change notification settings - Fork 3
/
gps_particle_data.py
1851 lines (1368 loc) · 69.2 KB
/
gps_particle_data.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
# For me (Ubuntu) I needed to install the wget module (details are here: https://ubuntuforums.org/showthread.php?t=2287729)
import wget
import os
import numpy as np
import time
import json
import sys
import math
import re
from io import StringIO
from datetime import datetime, timedelta
from itertools import compress
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
from urllib2 import urlopen
from mpl_toolkits.basemap import Basemap
import aacgmv2
def daterange(start_date, end_date):
for n in range(int ((end_date - start_date).days)):
yield start_date + timedelta(days=n*0.25);
#====================================================================================================
#
# This class holds all of the data and functions associated with a single data file
#
#
#====================================================================================================
class gps_particle_datafile():
# Variables in the data class
def __init__(self,filepath, sat_number):
# Generate the basepath and filename
self.satellite_number = sat_number;
# self.basepath = self.folder_path();
self.data_filename = filepath;
self.data = self.webread();
# Create the JSON header file
# self.json_filename = self.create_json();
#==============================================================================
# def __init__(self,sat_number,day,month,year):
#
# self.satellite_number = sat_number;
# self.day = day;
# self.month = month;
#
# if(year>1990):
# self.date = datetime(year,month,day);
# self.year = year-2000;
#
# if((year>20) and (year<1990)):
# self.date = datetime(year+1900,month,day);
# self.year = year;
# elif((year<20) and (year<1990)):
# self.date = datetime(year+2000,month,day);
# self.year = year;
#
# # Generate the basepath and filename
# self.basepath = self.folder_path();
# self.data_filename = self.file_path();
# self.fail_load=False;
#
# # Check if the file is available locally in this folder?
# exist_test = os.path.isfile(self.data_filename);
# if(not exist_test):
# # No it's been downloaded so download it
# print ' - Downloading ' + self.data_filename;
# if(self.download()):
# self.fail_load=True;
# return;
# else:
# print ' - File ' + self.data_filename + ' already exists ';
#
# if(not self.fail_load):
#
# # Create the JSON header file
# self.json_filename = self.create_json();
#
# # Read the data from the file
# self.data = self.read();
#
# # self.summary.print_summary();
# # print self.get_next_datecode();
# # print self.get_last_date();
#
#==============================================================================
# Returns the end time of the data file
def get_last_date(self):
# Get the decimal days
doys = self.data['decimal_day'];
# Check if the file goes over a new year boundary
new_year = any(doys>365);
if(new_year):
start_of_year = datetime(self.year+1,1,1);
else:
start_of_year = datetime(self.year,1,1);
# The end of the file ns41_041226 looks strange at the end as decimal days go negative?!?!?
# So we take the largest index and start to
max_index = np.argmax(doys)
if(max_index==len(doys)-1):
return start_of_year + timedelta(days=float(doys[-1]));
else:
# Handle the strange end of file decimal days here...
doy = doys[max_index];
new_index = max_index+1;
while((doy>0) and (new_index<len(doys))):
doy = doys[new_index];
new_index += 1;
if(new_index!=len(doys)):# Something wierd has happened to the decimal days
return start_of_year + timedelta(days=float(doys[new_index-2]));
else:
return start_of_year + timedelta(days=float(doys[-1]));
def get_next_datecode(self):
newdate = self.get_last_date();
# newdate = start_of_year + timedelta(days=float(doy));
return str(newdate.year).zfill(2) + str(newdate.month).zfill(2) + str(newdate.day).zfill(2);
# Return a string with the path to the data on the web
def folder_path(self):
# Add check on whether the satellite number is sensible here.
# The data web address
base = 'https://www.ngdc.noaa.gov/stp/space-weather/satellite-data/satellite-systems/gps/data/'
return base + 'ns' + str(self.satellite_number) + '/';
# To unit test this function
# fpath = folder_path(41,07,01,01);
# print('Folder path is : ', fpath);
# Return a string with the path to the filename on the web
def file_path(self):
# Add input checks here (e.g. is the day less than 31?)
# Datafile version number
version_number = 'v1.03';# Check whether this varies between the satellite datasets?
# Create the filename
return 'ns' + str(self.satellite_number) + '_' + str(self.year).zfill(2) + str(self.month).zfill(2) + str(self.day).zfill(2) + '_' + version_number + '.ascii';
# To unit test this function
# filepath = file_path(41,07,01,01);
# print('File path is : ', filepath);
# Helper function to find the file size
def file_size(self,fname):
statinfo = os.stat(fname)
return statinfo.st_size
# Function to download the selected data
def download(self):
# Download file
wget_file = wget.download(self.basepath+self.data_filename);
# Check if we've downloaded the 404 notice or actual data
fs = self.file_size(self.data_filename);#This throws an error when wget hasn't finished
if(fs<10000):
print(' - Check the filename as the returned file appears too small');
print(' - ... deleting file');
os.remove(self.data_filename);
return 1;
else:
return 0;
# Unit test : This should download a 404 (not found) file and then delete it (done = 1)
#done = download_data(41,01,01,01);
#print(done);
# Unit test : This should download an actual data file (done = 0)
#done = download_data(41,07,01,01);
#print(done);
def webread(self):
text = urlopen(self.data_filename).read();
self.raw_data = text.split('\n');
# Creates a file header to store info about columns for one iteration
self.json_filename = self.data_filename[-23:-6] + '.json';
# Opens a file for the JSON header
header = open(self.json_filename, "w+")
# The number of header lines
header_line_number = 0;
for i,line in enumerate(text.split('\n')):
if(i>4):
if line.startswith('#'):
if(i>header_line_number):
header_line_number = i;
li = line.strip('#');
header.write(li+str('\n'));
header.close();
# Update self.raw_data as a float array of dimensions Ndata_points by Nparameters
data_array = np.array([]);
for i,line in enumerate(self.raw_data):
if(i>header_line_number):# The data is from here on
newrow = line.split();
if(i==header_line_number+1):
data_array = np.asarray(newrow);
else:
if(len(newrow)>0):
data_array = np.vstack([data_array, newrow]);
self.raw_data = data_array.astype(np.float);
# Open up the json file
head = json.load(open(self.json_filename)); #load header file
# print ' - Reading file : ' + self.data_filename;
variables = {};
for x, value in head.items():
i = value['START_COLUMN']
j = i + value['DIMENSION'][0]
variables.update({x: self.raw_data[ : , i : j] for column in head});
return variables;
# return self.json_filename;
# Loads a data file using information from the JSON header file
def read(self):
# Open up the json file
head = json.load(open(self.json_filename)); #load header file
f = np.loadtxt(self.data_filename); #use numpy library to create arrays
print ' - Reading file ' + self.data_filename;
variables = {};
for x, value in head.items():
i = value['START_COLUMN']
j = i + value['DIMENSION'][0]
variables.update({x: f[ : , i : j] for column in head});
# print variables;
return variables;
# Unit test : Loads the data and prints it
# data_filename = file_path(41,07,01,01);
# data = load_data(create_json_header(data_filename),data_filename)
# print(data);
# Creates a JSON header from the datafile
def create_json(self):
# Opens up the datafile
log = open(self.data_filename, 'r');
reading = log.readlines()[5:];
# Creates a file header to store info about columns for one iteration
self.json_filename = self.data_filename[:-6] + '.json';
header = open(self.json_filename, "w+")
for line in reading:
if line.startswith('#'):
li = line.strip('#')
header.write(li)
header.close()
return self.json_filename;
# Unit test : Creates a JSON file corresponding to the .ascii file
# filename = file_path(41,07,01,01);
# create_json_header(filename);# Should see a JSON file in the directory now
#====================================================================================================
#
# This class is holds all of the data and functions associated with a single satellite
#
#====================================================================================================
class gps_satellite_data():
def __init__ (self,satellite_number,start_date,end_date):
self.save_disk_space = True;# Deletes the downloaded file once the data has been loaded into this data structure
# Create a list of datasets
self.dataset = [];
self.start_date = start_date;
self.end_date = end_date;
self.satellite_number=satellite_number;
self.filenames = self.get_datafiles_in_date();
if(self.filenames==list()):
self.empty = True;
return;
else:
self.empty = False;
print;
print '====================================';
print 'Loading data for satellite ', self.satellite_number;
base = 'https://www.ngdc.noaa.gov/stp/space-weather/satellite-data/satellite-systems/gps/data/';
folder_path = base + 'ns' + str(self.satellite_number) + '/';
# Load each file
for f in self.filenames:
# Open the particular file
full_file_path = folder_path+f;
print 'File : ' + full_file_path;
# Append the first datafile into the list
self.dataset.append(gps_particle_datafile(full_file_path, self.satellite_number));
def get_datefile_list(self):
base = 'https://www.ngdc.noaa.gov/stp/space-weather/satellite-data/satellite-systems/gps/data/'
folder_path = base + 'ns' + str(self.satellite_number) + '/';
urlpath = urlopen(folder_path);
files = urlpath.read().decode('utf-8');
start_file_positions = re.finditer('ns' + str(self.satellite_number), files);
# end_file_positions = re.finditer('.ascii', files);
# Search for the filenames
filelist=[];
for m in start_file_positions:
filename = files[m.start():m.start()+23];
filelist.append(filename);
return filelist[1::2];
def get_datafiles_in_date(self):
filelist = self.get_datefile_list();
cut_list = [];
for f in filelist:
year = int(f[5:7])+2000;
month = int(f[7:9]);
day = int(f[9:11]);
d = datetime(year,month,day);
if ( (d >= self.start_date ) and (d <= self.end_date) ):
cut_list.append(f);
return cut_list;
def get_next_datafile(self):
# Get the next file's datecode
new_date_code = self.dataset[-1].get_next_datecode()
# Read the next file - Load the new data
year = int(new_date_code[0:2]);
month = int(new_date_code[2:4]);
day = int(new_date_code[4:6]);
self.dataset.append(gps_particle_datafile(self.satellite_number,day,month,year));
# Check that we were able to load it
if(self.dataset[-1].fail_load):
del self.dataset[-1];# Failed to load so remove it from the list
return 1;
else:
return 0;
#==============================================================================
# # Get the current size of the dataset list
# curr_len = len(self.dataset);
#
# # Get the first and last day of the current datafile
# first_day = int(math.ceil(self.dataset[-1].summary.min_decimal_day));
# last_day = int(math.ceil(self.dataset[-1].summary.max_decimal_day));
#
# # For the 2004-2005 new year, the decimal day goes negative
# # across the end of year boundary ... need to investigate why this is?
# if(last_day<0):
# last_day = 1+int(math.ceil(np.max(self.dataset[-1].data["decimal_day"])));
#
# # print first_day;
# # print last_day;
#
# # Convert the decimal day to month and the day
# epoch = datetime(2000+self.current_year - 1, 12, 31);
# result = epoch + timedelta(days=last_day);
#
# # print result;
# # self.dataset[-1].summary.print_summary();
#
# # Find the new month and day
# self.current_day = result.day;
# self.current_month = result.month;
# if(first_day>last_day):
# self.current_year = self.current_year + 1;
# else:
# self.current_year = result.year-2000;
#
# # Load the new data
# self.dataset.append(gps_particle_datafile(self.satellite_number,self.current_day,self.current_month,self.current_year));
#
# # Delete the file if this flag is set
# if(self.save_disk_space):
# print 'Saving disk space, deleting file : ', self.dataset[-1].data_filename;
# os.remove(self.dataset[-1].data_filename);
#
# if(curr_len==len(self.dataset)):
# return 1;
# else:
# return 0;
#
# # UNIT TEST:
# # This loads the first datafile
# # satellite_data = gps_satellite_data(41,16,12,01);
# # This loads all of the data for the single satellite
# # while(satellite_data.get_next_datafile()==0):
# # print;
#
#==============================================================================
# This holds the data associated with an event (e.g. earthquake)
class event():
def __init__(self,name):
self.name = name;
# Geographic latitude and longitude
self.data = dict();
self.first_set=True;
def show_line(self,axes, x_axis_units = 'decimal_year'):
if(not hasattr(self, 'date')):
print 'Date property not set.';
return;
else:
if(x_axis_units=='decimal_year'):
d = self.date;
dec_year = (float(d.strftime("%j"))-1) / 366 + float(d.strftime("%Y"));
ylims = axes.get_ylim();
plt.plot([dec_year,dec_year],ylims,'k--');
if(x_axis_units=='datetime'):
d = self.date;
ylims = axes.get_ylim();
plt.plot([d,d],plt.gca().get_ylim(),'k--');
def add_data(self,name,value):
self.data[name] = value;
def add_date(self,datetime_in):
self.date = datetime_in;
self.add_data("year",datetime_in.year);
def add_date(self,mins,hh,dd,mm,yy):
# Save in a date structure
if(yy<2000):
self.date = datetime(day=dd,month=mm,year=2000+yy,hour=hh,minute=mins);
self.add_data("year",2000+yy);
startOfThisYear = datetime(year=yy+2000, month=1, day=1);
startOfNextYear = datetime(year=yy+2000+1, month=1, day=1);
else:
self.date = datetime(day=dd,month=mm,year=yy,hour=hh,minute=mins);
self.add_data("year",yy);
startOfThisYear = datetime(year=yy, month=1, day=1);
startOfNextYear = datetime(year=yy+1, month=1, day=1);
# print self.date;
year = self.date.year
# secs_so_far = float((self.date - startOfThisYear).seconds);
# secs_in_year = float((startOfNextYear-startOfThisYear).seconds);
# print secs_so_far;
decimal_day = float((self.date - startOfThisYear).days) + (float(hh)/24.0) + (float(mins)/(24.0*60.0));
# print decimal_day;
self.add_data("decimal_day",decimal_day);
self.add_data("datetime",self.date);
# Save decimal year too
# days_in_year = float((startOfNextYear-startOfThisYear).days);
# print days_in_year;
# year_fraction = decimal_day/days_in_year;
# self.add_data("decimal_year",2000+yy+year_fraction);
# self.add_data("decimal_year",fraction+yy+2000);
# ayear = (datetime(year=2000+yy+1,month=1,day=1)-datetime(year=2000+yy,month=1,day=1)).total_seconds();
# td = (datetime(day=dd,month=mm,year=2000+yy,hour=hh,minute=mins) - datetime(year=2000+yy,month=1,day=1)).total_seconds();
# self.add_data("Decimal_",yy);
# print td/ayear
# print year_elapsed.year
# A basic class to search for earthquakes...
class earthquake_search:
def __init__(self,startdate,enddate,min_magnitude=0,min_lat=-90,max_lat=90,min_lon=-180,max_lon=180):
self.information_text = self.get_earthquake_information(startdate,enddate,min_magnitude,min_lat,max_lat,min_lon,max_lon);
self.earthquake_information = self.parse_result(self.information_text);
def get_lat_lon(self):
lats = (self.earthquake_information[:,2]);
lons = (self.earthquake_information[:,3]);
return (lats.astype(np.float),lons.astype(np.float));
def get_magnitude(self):
return self.earthquake_information[:,4];
def get_datetimes(self):
datetimes = list();
timestamps = self.earthquake_information;
for ts in timestamps:
t = ts[1];
year = int(t[0:4]);
month = int(t[5:7]);
day = int(t[8:10]);
hour = int(t[11:13]);
mins = int(t[14:16]);
secs = int(t[17:19]);
dt = datetime(year,month,day,hour,mins,secs);
datetimes.append(dt);
return datetimes;
# Calculate the L-shell parameters
def get_L_shells(self, altitude_EM_capture_by_flux_tube_in_km):
"""
Convert geographic latitude to geomagnetic latitude
See Aleksandrin et al, "High-energy charged particle bursts in the near-Earth space as earthquake precursors", Annales Geophysicae (2003) 21: 597-602
The altitude of EQ L-shell should be the altitude of the EM wave coupling to the flux tube, estimated to be 300km
"""
[lat,lon] = self.get_lat_lon();
mlats=[];
mlons=[];
L_shells=[];
for i,la in enumerate(lat):
[mlat,mlon] = aacgmv2.convert(lat[i], lon[i],altitude_EM_capture_by_flux_tube_in_km);
r_Re = (6371.0+altitude_EM_capture_by_flux_tube_in_km)/6371.0;
L_shells.append(r_Re/(math.cos((math.pi/180.0)*mlat)*math.cos((math.pi/180.0)*mlat)));
return np.asarray(L_shells);
def get_events(self):
events = list();
for ee in self.earthquake_information:
this_event = event(ee[-1]);
# Get the date information
t = ee[1];
year = int(t[0:4]);
month = int(t[5:7]);
day = int(t[8:10]);
hour = int(t[11:13]);
mins = int(t[14:16]);
secs = int(t[17:19]);
this_event.add_date(mins,hour,day,month,year);
# Get the lat lon
this_event.add_data("Geographic_Latitude",float(ee[2]));
this_event.add_data("Geographic_Longitude",float(ee[3]));
events.append(this_event);
return events;
def get_earthquake_information(self,startdate,enddate,min_magnitude=0,min_lat=-90,max_lat=90,min_lon=-90,max_lon=90):
base_string = 'https://earthquake.usgs.gov/fdsnws/event/1/query?format=text&starttime=';
mid_string = '&endtime=';
mag_string = '&minmagnitude=';
min_lon_string = '&minlongitude=';
max_lon_string = '&maxlongitude=';
min_lat_string = '&minlatitude=';
max_lat_string = '&maxlatitude=';
# Construct string
# e.g. https://earthquake.usgs.gov/fdsnws/event/1/count?starttime=2014-01-01&endtime=2014-01-02
start_time_string = startdate.strftime('%y-%m-%d') + 'T' + str(startdate.hour).zfill(2) + ':' + str(startdate.minute).zfill(2) + ':' + str(startdate.second).zfill(2);
end_time_string = enddate.strftime('%y-%m-%d') + 'T' + str(enddate.hour).zfill(2) + ':' + str(enddate.minute).zfill(2) + ':' + str(enddate.second).zfill(2);
url_string = base_string + start_time_string + mid_string + end_time_string + mag_string + str(min_magnitude) + min_lon_string + str(min_lon) + max_lon_string + str(max_lon) + min_lat_string + str(min_lat) + max_lat_string + str(max_lat);
# print url_string;
self.information_text = urlopen(url_string).read();
self.earthquake_information = self.parse_result(self.information_text)
return self.information_text;
# This function was copied from http://qingkaikong.blogspot.co.uk/2016/02/query-usgs-catalog-online-and-plot.html
def parse_result(self,inputText):
'''
Function to parse the requested earthquake events data from USGS, and save it into numpy array
'''
event_id = []
origin_time = []
evla = []
evlo = []
evdp = []
mag = []
mag_type = []
EventLocationName = []
for i, item in enumerate(inputText.split('\n')[0:-1]):
if i < 1:
# skip the header
continue
try:
splited = item.split('|')
event_id.append(splited[0])
origin_time.append(splited[1])
evla.append(splited[2])
evlo.append(splited[3])
evdp.append(splited[4])
mag.append(splited[10])
mag_type.append(splited[9])
EventLocationName.append(splited[-1])
except:
# just in case there are some wrong data in the catlog
print item
print 'Skip wrong data or there is something wrong'
return np.c_[event_id, origin_time, evla, evlo, mag, mag_type, EventLocationName]
class satellite_data_plot:
def __init__(self):
self.x_axis_data='decimal_days';
self.marker_colour = 'b';
self.marker_size = 3;
def daterange(start_date, end_date, step_in_days):
days_range = np.arange(0,(end_date - start_date).days, step_in_days)
for n in days_range:
yield start_date + timedelta(days=n);
def get_counts(self,
output_data,
satellite_label = 'ns41',
data_channel = 0,
keyvarname = 'rate_proton_measured'):
meas_period = np.asarray(output_data[satellite_label]['collection_interval']);
rate = np.asarray(output_data[satellite_label][keyvarname])[:,data_channel];
return np.multiply(meas_period,rate);
def get_signal_to_background_ratio(self,
output_data,
satellite_label = 'ns41',
data_channel = 0,
keyvarname = 'rate_proton_measured'):
signal = np.asarray(output_data[satellite_label][keyvarname])[:,data_channel];
if('proton' in keyvarname):
bkgname = 'proton_background';
if('electron' in keyvarname):
bkgname = 'electron_background';
background = np.asarray(output_data[satellite_label][bkgname])[:,data_channel];
return np.divide(signal,background);
def get_signal_to_stddev_ratio(self,
output_data,
satellite_label = 'ns41',
data_channel = 0,
keyvarname = 'proton'):
signal = np.asarray(output_data[satellite_label][keyvarname])[:,data_channel];
if('proton' in keyvarname):
bkgname = 'proton_background';
if('electron' in keyvarname):
bkgname = 'electron_background';
stddev_bkg = np.asarray(math.sqrt(output_data[satellite_label][bkgname][:,data_channel]));
return np.divide(signal,stddev_bkg);
def get_li_ma_significance(self,
output_data,
on_startdate,
on_enddate,
off_startdate,
off_enddate,
satellite_label = 'ns41',
keyvarname = 'rate_proton_measured',
data_channel = 0):
# First get the number of particles
counts = self.get_counts(output_data, satellite_label, data_channel,keyvarname);
# Calculate the on and off counts
on_date_cuts = self.get_date_cuts(counts,on_startdate,on_enddate);
on_counts = sum(counts[on_date_cuts]);
off_date_cuts = self.get_date_cuts(counts,off_startdate,off_enddate);
off_counts = sum(counts[off_date_cuts]);
# Find the ratio of the time periods
alpha = (on_enddate - on_startdate).total_seconds()/(off_enddate - off_startdate).total_seconds();
# Return the significance
num1 = (1+alpha)*on_counts;
den1 = alpha*(on_counts + off_counts);
num2 = (1+alpha)*off_counts;
den2 = on_counts + off_counts;
S = math.sqrt(2)*math.sqrt( on_counts * math.log(num1/den1) + off_counts*math.log(num2/den2) );
return S;
def plot_li_ma(self,
fig_no,
axes,
output_data,
satellite_label='ns41',
keyvarname = 'rate_proton_measured',
data_channel = 0,
startdate=datetime(1990,1,1),
enddate=datetime(2017,1,1),
on_off_period_days = 1,
Lmin = 0, Lmax = 100):
# Loop over the range of days, with
for this_date in self.daterange(startdate,enddate,on_off_period_days):
print this_date;
#==============================================================================
# Simply plots the data given the date and L-shell cuts
#==============================================================================
def plot_channels(self,fig_no,axes,output_data,
satellite_label='ns41',
keyvarname = 'rate_proton_measured',
data_channel = 0,
startdate=datetime(1990,1,1),enddate=datetime(2017,1,1),
Lmin = 0, Lmax = 100):
fig = plt.figure(fig_no);
colour = ['red', 'blue', 'green', 'magenta', 'navy', 'aqua', 'orange', 'yellow' , 'lime', 'peru', 'slategrey', 'teal', 'maroon', 'mediumspringgreen', 'red']
# The x-axis data
x = np.asarray(output_data[satellite_label]['datetime']);
# x = self.daterange(startdate,enddate,0.25);
# The signal data
y = np.asarray(output_data[satellite_label][keyvarname])[:,data_channel];
# Get the date cuts
this_data = np.squeeze(np.asarray(output_data[satellite_label]["datetime"]));
date_cuts = self.get_date_cuts(this_data,startdate,enddate);
# And the L shell cuts
Lshell_data = np.squeeze(np.asarray(output_data[satellite_label]["L_shell"]));
Lshell_cuts = self.get_Lshell_cuts(Lshell_data,Lmin,Lmax);
# Make sure none of the data has been dropped
dropped = np.squeeze(np.asarray(output_data[satellite_label]["dropped_data"]));
dropped_cuts = self.get_dropped_data_cuts(dropped);
data_cuts = (date_cuts & Lshell_cuts & dropped_cuts );
plt.plot(x[data_cuts],y[data_cuts],'o-',color=self.marker_colour);#,s=self.marker_size);
# axes.legend(loc = 'upper left');
plt.xlabel('Date');
plt.xticks(rotation=50);
plt.ylabel((keyvarname.replace("_", " ")).title());
plt.xlim(startdate,enddate);
def get_date_cuts(self,datetimes,startdate,enddate):
date_cuts=[];
for idate in datetimes:
date_cuts.append( (idate>startdate) and (idate<enddate) );
return np.asarray(date_cuts);
def get_Lshell_cuts(self,Lshells,Lmin,Lmax):
Lshell_cuts=[];
for iL in Lshells:
Lshell_cuts.append( (iL>Lmin) and (iL<Lmax) );
return np.asarray(Lshell_cuts);
def get_dropped_data_cuts(self,dropped):
dropped_cuts=[];
for d in dropped:
dropped_cuts.append( d == 0 );
return np.asarray(dropped_cuts);
class satellite_map_plot:
def __init__(self):
# miller projection
self.map_plot = Basemap(projection='mill',llcrnrlon=60,llcrnrlat=-60, urcrnrlon=150, urcrnrlat=60)
# plot coastlines, draw label meridians and parallels.
self.map_plot.drawcoastlines()
self.map_plot.drawmapboundary(fill_color='aqua')
self.map_plot.drawcountries(color='0.4')
self.map_plot.fillcontinents(color='coral',lake_color='aqua')
self.map_plot.drawmapboundary(fill_color='0.8')
self.map_plot.drawparallels(np.arange(-90,90,30),labels=[1,0,0,0]);
self.map_plot.drawmeridians(np.arange(self.map_plot.lonmin,self.map_plot.lonmax+30,60),labels=[0,0,0,1]);
# Formatting parameters
# - For the events
self.marker_scale=1.0;
self.marker_colour='b';
self.inner_colour='r';
self.outer_colour='g';
self.data_keyname='';
self.label_lat = -87.5;
self.label_lon = -80;
def plot_event_on_map(self,fig_no,events):
plt.figure(fig_no);
# fill continents 'coral' (with zorder=0), color wet areas 'aqua'
# shade the night areas, with alpha transparency so the
# map shows through. Use current time in UTC.
date = datetime.utcnow()
for e in events:
# Plot the Earthquake event on the map
lon = np.squeeze(np.asarray(e.data["Geographic_Longitude"]));
lat = np.squeeze(np.asarray(e.data["Geographic_Latitude"]));
# print lat,lon
x,y = self.map_plot(lon,lat);
self.map_plot.scatter(x,y,s=300*self.marker_scale,marker='o',color=self.outer_colour,alpha=0.50,zorder=5);
self.map_plot.scatter(x,y,s=50*self.marker_scale,marker='o',color=self.inner_colour,alpha=0.5,zorder=5);
self.map_plot.scatter(x,y,s=1000*self.marker_scale,marker='x',color='k',alpha=1,zorder=5);
def signal_heatmap(self,output_data,fig_no, axes, keyvarname = 'rate_proton_measured',
data_channel = 0,
satellite_labels=['ns41'],startdate=datetime(1990,1,1),enddate=datetime(2017,1,1), Lmin = 0, Lmax = 100):
fig = plt.figure(fig_no);
# Get the output data by satellite
# output_data = self.get_selected_data_by_satellite();
xs=[];
ys=[];
zs=[];
for sat in satellite_labels:
# Get the lat and long
sat_lat,sat_lon = self.get_lat_long(output_data, sat);
xs1,ys1 = self.map_plot(sat_lon,sat_lat);
# Get the date cuts
this_data = np.squeeze(np.asarray(output_data[sat]["datetime"]));
date_cuts = self.get_date_cuts(this_data,startdate,enddate);
# And the L shell cuts
Lshell_data = np.squeeze(np.asarray(output_data[sat]["L_shell"]));
Lshell_cuts = self.get_Lshell_cuts(Lshell_data,Lmin,Lmax);
# Make sure none of the data has been dropped
dropped = np.squeeze(np.asarray(output_data[sat]["dropped_data"]));
dropped_cuts = self.get_dropped_data_cuts(dropped);
data_cuts = (date_cuts & Lshell_cuts & dropped_cuts );
# Get the colour data
signal_data = np.squeeze(np.asarray(output_data[sat][keyvarname]));
signal_data = signal_data[:,int(data_channel)];
xs1 = np.ravel(xs1[data_cuts]);
ys1 = np.ravel(ys1[data_cuts]);
zs1 = np.ravel(signal_data[data_cuts]);
for x in xs1:
xs.append(x);
for y in ys1:
ys.append(y);
for z in zs1:
zs.append(z);
xs = np.asarray(xs);
ys = np.asarray(ys);
zs = np.asarray(zs);
xmin = xs.min()
xmax = xs.max()
ymin = ys.min()
ymax = ys.max()
gridsize=60;
hb = plt.hexbin(xs, ys, C=zs, gridsize=gridsize, marginals=True, cmap=plt.cm.PuRd, zorder=100);
cb = fig.colorbar(hb, ax=axes)
cb.set_label('Satellite Visits')
#==============================================================================
# # http://bagrow.com/dsv/heatmap_basemap.html
# def signal_heatmap(self,output_data):
#
#
# # ######################################################################
# # bin the epicenters (adapted from
# # http://stackoverflow.com/questions/11507575/basemap-and-density-plots)
#
# # compute appropriate bins to chop up the data:
# db = 1 # bin padding
# lon_bins = np.linspace(min(lons)-db, max(lons)+db, 10+1) # 10 bins
# lat_bins = np.linspace(min(lats)-db, max(lats)+db, 13+1) # 13 bins
#
# density, _, _ = np.histogram2d(lats, lons, [lat_bins, lon_bins])
#
# # Turn the lon/lat of the bins into 2 dimensional arrays ready
# # for conversion into projected coordinates
# lon_bins_2d, lat_bins_2d = np.meshgrid(lon_bins, lat_bins)
#
# # convert the bin mesh to map coordinates:
# xs, ys = m(lon_bins_2d, lat_bins_2d) # will be plotted using pcolormesh
# # ######################################################################
#
#==============================================================================
def show_satellite_label(self,fig_no, output_data, satellite_label='ns41'):
if(self.label_lon < -90):
self.label_lon+=360;
# sat_lat,sat_lon = self.get_lat_long(output_data, satellite_label);
xs,ys = self.map_plot(self.label_lon,self.label_lat);