-
Notifications
You must be signed in to change notification settings - Fork 4
/
icme_rate.py
3761 lines (2586 loc) · 132 KB
/
icme_rate.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
#!/usr/bin/env python
# coding: utf-8
# # ICME rate update plots
#
# adapted from
# https://github.com/helioforecast/Papers/tree/master/Moestl2020_PSP_rate
# makes a prediction of the ICME rate in solar cycle 25
#
# Main author: C. Moestl, IWF Graz, Austria; twitter @chrisoutofspace; https://github.com/cmoestl
#
# The sunspot numbers is automatically loaded from http://www.sidc.be/silso/DATA/SN_d_tot_V2.0.csv
#
# plots are saved to '/nas/helio/data/insitu_python/icme_rate_cycle_update'
#
# Convert this notebook to a script with:
#
# import os
#
# os.system('jupyter nbconvert --to script icme_rate.ipynb')
#
#
#
#
# ---
#
# **MIT LICENSE**
#
# Copyright 2020-2023, Christian Moestl
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the "Software"), to deal in the Software
# without restriction, including without limitation the rights to use, copy, modify,
# merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be included in all copies
# or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
# OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# In[1]:
#real time updates: icme_rate.py
#import matplotlib
#for server runs
#matplotlib.use('Agg')
##############!!!!for notebook use
#%matplotlib inline
#outputdirectory='results/icme_rate_cycle_update'
#for automatic updates
outputdirectory='/nas/helio/data/insitu_python/icme_rate_cycle_update'
#Convert this notebook to a script with:
#import os
#os.system('jupyter nbconvert --to script icme_rate.ipynb')
# In[2]:
from scipy import stats
import scipy.io
from matplotlib import cm
import sys
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
import datetime
from datetime import timedelta
import astropy.constants as const
from sunpy.time import parse_time
import sunpy.time
import time
import pickle
import seaborn as sns
import os
import urllib
import json
import warnings
import importlib
import heliopy.spice as spice
import heliopy.data.spice as spicedata
import astropy
import copy
#our own package
from heliocats import stats as hs
from heliocats import data as hd
#where the 6 in situ data files are located is read from input.py
#as data_path=....
from config import data_path
#reload again while debugging
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
#%matplotlib inline
#matplotlib.use('Qt5Agg')
#matplotlib.use('Agg')
#warnings.filterwarnings('ignore') # some numpy mean-of-empty-slice runtime warnings
########### make directories first time
resdir='results'
if os.path.isdir(resdir) == False: os.mkdir(resdir)
datadir='data'
if os.path.isdir(datadir) == False: os.mkdir(datadir)
if os.path.isdir(outputdirectory) == False: os.mkdir(outputdirectory)
#animdirectory='results/plots_rate/anim'
#if os.path.isdir(animdirectory) == False: os.mkdir(animdirectory)
#animdirectory2='results/plots_rate/anim2'
#if os.path.isdir(animdirectory2) == False: os.mkdir(animdirectory2)
plt.rcParams["figure.figsize"] = (15,8)
print('done')
# ## 1 Settings and load data
# In[3]:
plt.close('all')
print('icme_rate main program.')
print('Christian Moestl et al., IWF Graz, Austria')
#constants:
#solar radiusx
Rs_in_AU=float(const.R_sun/const.au)
#define AU in km
AU_in_km=const.au.value/1e3
#set for loading
load_data=1
get_new_sunspots=1
get_new_sunspots_ms=1
get_new_sunspots_mean=1
if load_data > 0:
print('load data (takes a minute or so)')
print('')
#####################
print('get RC ICME list')
#download richardson and cane list
rc_url='http://www.srl.caltech.edu/ACE/ASC/DATA/level3/icmetable2.htm'
try: urllib.request.urlretrieve(rc_url,data_path+'rc_list.htm')
except urllib.error.URLError as e:
print('Failed downloading ', rc_url,' ',e)
#read RC list into pandas dataframe
rc_dfull=pd.read_html(data_path+'rc_list.htm')
rc_df=rc_dfull[0]
##################
print('get sunspot number from SIDC')
#get daily sunspot number from SIDC
#http://www.sidc.be/silso/datafiles
#parameters
#http://www.sidc.be/silso/infosndtot
#daily sunspot number
if get_new_sunspots==1:
ssn=pd.read_csv('http://www.sidc.be/silso/DATA/SN_d_tot_V2.0.csv',sep=';',names=['year','month','day','year2','spot','stand','obs','prov'])
ssn_time=np.zeros(len(ssn))
for k in np.arange(len(ssn)):
ssn_time[k]=parse_time(str(ssn.year[k])+'-'+str(ssn.month[k])+'-'+str(ssn.day[k])).plot_date
print('time convert done')
ssn.insert(0,'time',ssn_time)
ssn.spot.loc[np.where(ssn.spot< 0)[0]]=np.nan
ssn.stand.loc[np.where(ssn.stand< 0)[0]]=np.nan
fileout='ssn.p'
pickle.dump(ssn, open(data_path+fileout, "wb"))
#also get preliminary data for current month for plotting
#does not work
#ssn_prelim_raw=pd.csv('http://www.sidc.be/silso/DATA/EISN/EISN_current.csv',sep=',',names=['year','month','day','year2','spot','stand','stat calc','stat avail'])
#download manually
ssn_prelim_url='http://www.sidc.be/silso/DATA/EISN/EISN_current.csv'
try: urllib.request.urlretrieve(ssn_prelim_url,'data/EISN_current.csv')
except urllib.error.URLError as e:
print('Failed downloading ', ssn_prelim_url,' ',e)
ssn_prelim_raw = np.loadtxt('data/EISN_current.csv', delimiter=',',usecols=(0,1,2,4,5))
ssn_p_int=ssn_prelim_raw.astype(int)
ssn_p=pd.DataFrame(ssn_p_int,columns=['year','month','day','spot','stand'])
ssn_p_time=np.zeros(len(ssn_p))
for k in np.arange(len(ssn_p)):
ssn_p_time[k]=parse_time(str(ssn_p.year[k])+'-'+str(ssn_p.month[k])+'-'+str(ssn_p.day[k])).plot_date
ssn_p.insert(0,'time',ssn_p_time)
ssn_p.spot.loc[np.where(ssn_p.spot< 0)[0]]=np.nan
ssn_p.stand.loc[np.where(ssn_p.stand< 0)[0]]=np.nan
fileout='ssn_prelim.p'
pickle.dump(ssn_p, open(data_path+fileout, "wb"))
if get_new_sunspots_ms==1:
#ssn_ms=pd.read_csv('data/SN_ms_tot_V2.0.csv',sep=';')
ssn_ms=pd.read_csv('http://www.sidc.be/silso/DATA/SN_ms_tot_V2.0.csv',sep=';',names=['year','month','year2','spot','stand','obs','check'])
ssn_ms_time=np.zeros(len(ssn_ms))
for k in np.arange(len(ssn_ms)):
ssn_ms_time[k]=parse_time(str(ssn_ms.year[k])+'-'+str(ssn_ms.month[k])+'-01').plot_date
#print(mdates.num2date(ssn_ms_time[k]))
#print(ssn_ms.spot[k])
print('time convert done')
ssn_ms.insert(0,'time',ssn_ms_time)
ssn_ms.spot.loc[np.where(ssn_ms.spot< 0)[0]]=np.nan
fileout='ssn_13ms.p'
pickle.dump(ssn_ms, open(data_path+fileout, "wb"))
if get_new_sunspots_mean==1:
ssn_m=pd.read_csv('http://www.sidc.be/silso/DATA/SN_m_tot_V2.0.csv',sep=';',names=['year','month','year2','spot','stand','obs','check'])
ssn_m_time=np.zeros(len(ssn_m))
for k in np.arange(len(ssn_m)):
ssn_m_time[k]=parse_time(str(ssn_m.year[k])+'-'+str(ssn_m.month[k])+'-01').plot_date
print('time convert done')
ssn_m.insert(0,'time',ssn_m_time)
ssn_m.spot.loc[np.where(ssn_m.spot< 0)[0]]=np.nan
fileout='ssn_m.p'
pickle.dump(ssn_m, open(data_path+fileout, "wb"))
file='ssn.p'
ssn=pickle.load(open(data_path+file, "rb"))
#make 13 month running mean
runmean_months=13.0
ssn_mean_13=hs.running_mean(ssn.spot,int(np.rint(30.42*runmean_months+1)))
ssn_std_13=hs.running_mean(ssn.stand,int(np.rint(30.42*runmean_months+1)))
ssn.insert(1,'spot_mean_13',ssn_mean_13)
ssn.insert(2,'spot_std_13',ssn_std_13)
print('SIDC sunspots done')
################## Spacecraft
#completed missions
filevex='vex_2007_2014_sceq_removed.p'
[vex,hvex]=pickle.load(open(data_path+filevex, 'rb' ) )
filevex='vex_2007_2014_sceq.p'
[vexnon,hvexnon]=pickle.load(open(data_path+filevex, 'rb' ) )
filemes='messenger_2007_2015_sceq_removed.p'
[mes,hmes]=pickle.load(open(data_path+filemes, 'rb' ) )
filemes='messenger_2007_2015_sceq.p'
[mesnon,hmesnon]=pickle.load(open(data_path+filemes, 'rb' ) )
filestb='stereob_2007_2014_sceq.p'
[stb,hstb]=pickle.load(open(data_path+filestb, "rb" ) )
fileuly='ulysses_1990_2009_rtn.p'
[uly,huly]=pickle.load(open(data_path+fileuly, "rb" ) )
##active mission
filemav='maven_2014_2018_removed_smoothed.p'
[mav,hmav]=pickle.load(open(data_path+filemav, 'rb' ) )
print('load and merge Wind data HEEQ')
#from HELCATS HEEQ until 2018 1 1 + new self-processed data with heliosat and hd.save_wind_data
filewin="wind_2007_2018_heeq_helcats.p"
[win1,hwin1]=pickle.load(open(data_path+filewin, "rb" ) )
#or use: filewin2="wind_2018_now_heeq.p"
filewin2="wind_2018_now_heeq.p"
[win2,hwin2]=pickle.load(open(data_path+filewin2, "rb" ) )
#merge Wind old and new data
#cut off HELCATS data at end of 2017, win2 begins exactly after this
win1=win1[np.where(win1.time < parse_time('2018-Jan-01 00:00').datetime)[0]]
#make array
win=np.zeros(np.size(win1.time)+np.size(win2.time),dtype=[('time',object),('bx', float),('by', float),\
('bz', float),('bt', float),('vt', float),('np', float),('tp', float),\
('x', float),('y', float),('z', float),\
('r', float),('lat', float),('lon', float)])
#convert to recarray
win = win.view(np.recarray)
win.time=np.hstack((win1.time,win2.time))
win.bx=np.hstack((win1.bx,win2.bx))
win.by=np.hstack((win1.by,win2.by))
win.bz=np.hstack((win1.bz,win2.bz))
win.bt=np.hstack((win1.bt,win2.bt))
win.vt=np.hstack((win1.vt,win2.vt))
win.np=np.hstack((win1.np,win2.np))
win.tp=np.hstack((win1.tp,win2.tp))
win.x=np.hstack((win1.x,win2.x))
win.y=np.hstack((win1.y,win2.y))
win.z=np.hstack((win1.z,win2.z))
win.r=np.hstack((win1.r,win2.r))
win.lon=np.hstack((win1.lon,win2.lon))
win.lat=np.hstack((win1.lat,win2.lat))
print('Wind merging done')
########### STA
print('load and merge STEREO-A data SCEQ') #yearly magplasma files from stereo science center, conversion to SCEQ
filesta1='stereoa_2007_2020_sceq.p'
sta1=pickle.load(open(data_path+filesta1, "rb" ) )
#beacon data
#filesta2="stereoa_2019_2020_sceq_beacon.p"
#filesta2='stereoa_2019_2020_sept_sceq_beacon.p'
#filesta2='stereoa_2019_now_sceq_beacon.p'
#filesta2="stereoa_2020_august_november_sceq_beacon.p"
filesta2='stereoa_2020_now_sceq_beacon.p'
[sta2,hsta2]=pickle.load(open(data_path+filesta2, "rb" ) )
#cutoff with end of science data
sta2=sta2[np.where(sta2.time >= parse_time('2020-Aug-01 00:00').datetime)[0]]
#make array
sta=np.zeros(np.size(sta1.time)+np.size(sta2.time),dtype=[('time',object),('bx', float),('by', float),\
('bz', float),('bt', float),('vt', float),('np', float),('tp', float),\
('x', float),('y', float),('z', float),\
('r', float),('lat', float),('lon', float)])
#convert to recarray
sta = sta.view(np.recarray)
sta.time=np.hstack((sta1.time,sta2.time))
sta.bx=np.hstack((sta1.bx,sta2.bx))
sta.by=np.hstack((sta1.by,sta2.by))
sta.bz=np.hstack((sta1.bz,sta2.bz))
sta.bt=np.hstack((sta1.bt,sta2.bt))
sta.vt=np.hstack((sta1.vt,sta2.vt))
sta.np=np.hstack((sta1.np,sta2.np))
sta.tp=np.hstack((sta1.tp,sta2.tp))
sta.x=np.hstack((sta1.x,sta2.x))
sta.y=np.hstack((sta1.y,sta2.y))
sta.z=np.hstack((sta1.z,sta2.z))
sta.r=np.hstack((sta1.r,sta2.r))
sta.lon=np.hstack((sta1.lon,sta2.lon))
sta.lat=np.hstack((sta1.lat,sta2.lat))
print('STA Merging done')
print('load PSP data SCEQ') #from heliosat, converted to SCEQ similar to STEREO-A/B
filepsp='psp_2018_2021_sceq.p'
[psp,hpsp]=pickle.load(open(data_path+filepsp, "rb" ) )
##############################################
print('load Bepi Colombo SCEQ')
filebepi='bepi_2019_2021_sceq.p'
bepi=pickle.load(open(data_path+filebepi, "rb" ) )
##############################################
print('load Solar Orbiter SCEQ')
filesolo='solo_2020_april_2021_sep_sceq.p'
solo=pickle.load(open(data_path+filesolo, "rb" ) )
#set all plasma data to NaN
solo.vt=np.nan
solo.np=np.nan
solo.tp=np.nan
fileomni='omni_1963_2020.p'
[omni,homni]=pickle.load(open(data_path+fileomni, "rb" ) )
print('load all data done')
# In[4]:
########### load ICMECAT v2.0, made with icmecat.py or ipynb
file='icmecat/HELIO4CAST_ICMECAT_v21_pandas.p'
print()
print('loaded ', file)
print()
print('Keys (parameters) in this pandas data frame are:')
[ic,h,p]=pickle.load(open(file, "rb" ) )
print(ic.keys())
print()
################### get indices of events for each spacecraft
mercury_orbit_insertion_time= parse_time('2011-03-18').datetime
#spacecraft near the 4 terrestrial planets
#get indices for Mercury after orbit insertion in March 2011
merci=np.where(np.logical_and(ic.sc_insitu =='MESSENGER', ic.icme_start_time > mercury_orbit_insertion_time))[0]
vexi=np.where(ic.sc_insitu == 'VEX')[:][0]
wini=np.where(ic.sc_insitu == 'Wind')[:][0]
mavi=np.where(ic.sc_insitu == 'MAVEN')[:][0]
#other spacecraft
#all MESSENGER events including cruise phase
mesi=np.where(ic.sc_insitu == 'MESSENGER')[:][0]
stbi=np.where(ic.sc_insitu == 'STEREO-B')[:][0]
ulyi=np.where(ic.sc_insitu == 'ULYSSES')[:][0]
pspi=np.where(ic.sc_insitu == 'PSP')[:][0]
soli=np.where(ic.sc_insitu == 'SolarOrbiter')[:][0]
beci=np.where(ic.sc_insitu == 'BepiColombo')[:][0]
stai=np.where(ic.sc_insitu == 'STEREO-A')[:][0]
############### set limits of solar minimum, rising/declining phase and solar maximum
# minimim maximum times as given by
#http://www.sidc.be/silso/cyclesmm
#24 2008 12 2.2 2014 04 116.4
solarmin=parse_time('2008-12-01').datetime
minstart=solarmin-datetime.timedelta(days=366*1.5)
minend=solarmin+datetime.timedelta(days=365)
minstart_num=parse_time(minstart).plot_date
minend_num=parse_time(minend).plot_date
solarmax=parse_time('2014-04-01').datetime
maxstart=solarmax-datetime.timedelta(days=365*3)
maxend=solarmax+datetime.timedelta(days=365/2)
maxstart_num=parse_time(maxstart).plot_date
maxend_num=parse_time(maxend).plot_date
#rising phase not used
# risestart=parse_time('2010-01-01').datetime
# riseend=parse_time('2011-06-30').datetime
# risestart_num=parse_time('2010-01-01').plot_date
# riseend_num=parse_time('2011-06-30').plot_date
# declstart=parse_time('2015-01-01').datetime
# declend=parse_time('2018-12-31').datetime
# declstart_num=parse_time('2015-01-01').plot_date
# declend_num=parse_time('2018-12-31').plot_date
############### extract events by limits of solar minimum and maximum
iall_min=np.where(np.logical_and(ic.icme_start_time > minstart,ic.icme_start_time < minend))[0]
#iall_rise=np.where(np.logical_and(ic.icme_start_time > risestart,ic.icme_start_time < riseend))[0]
iall_max=np.where(np.logical_and(ic.icme_start_time > maxstart,ic.icme_start_time < maxend))[0]
wini_min=iall_min[np.where(ic.sc_insitu[iall_min]=='Wind')]
#wini_rise=iall_rise[np.where(ic.sc_insitu[iall_rise]=='Wind')]
wini_max=iall_max[np.where(ic.sc_insitu[iall_max]=='Wind')]
pspi_min=iall_min[np.where(ic.sc_insitu[iall_min]=='PSP')]
#wini_rise=iall_rise[np.where(ic.sc_insitu[iall_rise]=='Wind')]
pspi_max=iall_max[np.where(ic.sc_insitu[iall_max]=='PSP')]
vexi_min=iall_min[np.where(ic.sc_insitu[iall_min]=='VEX')]
#vexi_rise=iall_rise[np.where(ic.sc_insitu[iall_rise]=='VEX')]
vexi_max=iall_max[np.where(ic.sc_insitu[iall_max]=='VEX')]
mesi_min=iall_min[np.where(ic.sc_insitu[iall_min]=='MESSENGER')]
#mesi_rise=iall_rise[np.where(ic.sc_insitu[iall_rise]=='MESSENGER')]
mesi_max=iall_max[np.where(ic.sc_insitu[iall_max]=='MESSENGER')]
stai_min=iall_min[np.where(ic.sc_insitu[iall_min]=='STEREO-A')]
#stai_rise=iall_rise[np.where(ic.sc_insitu[iall_rise]=='STEREO-A')]
stai_max=iall_max[np.where(ic.sc_insitu[iall_max]=='STEREO-A')]
stbi_min=iall_min[np.where(ic.sc_insitu[iall_min]=='STEREO-B')]
#stbi_rise=iall_rise[np.where(ic.sc_insitu[iall_rise]=='STEREO-B')]
stbi_max=iall_max[np.where(ic.sc_insitu[iall_max]=='STEREO-B')]
# select the events at Mercury extra after orbit insertion, note that no events available for solar minimum
merci_min=iall_min[np.where(np.logical_and(ic.sc_insitu[iall_min] =='MESSENGER',ic.icme_start_time[iall_min] > parse_time('2011-03-18').datetime))]
#merci_rise=iall_rise[np.where(np.logical_and(ic.sc_insitu[iall_rise] =='MESSENGER',ic.icme_start_time[iall_rise] > parse_time('2011-03-18').datetime))]
merci_max=iall_max[np.where(np.logical_and(ic.sc_insitu[iall_max] =='MESSENGER',ic.icme_start_time[iall_max] > parse_time('2011-03-18').datetime))]
print(len(ic))
print('done')
# In[5]:
ic
# ## 2 ICME rate for solar cycles 23/24 from the Heliophysics System Observatory (ICMECAT and Richardson and Cane)
# ### Check data days available each year for each planet or spacecraft
# In[6]:
######################## make bin for each year for yearly histograms
#define dates of January 1 from 2007 to end year
last_year=2022 #2022 means last date is 2021 Dec 31
years_jan_1_str=[str(i)+'-01-01' for i in np.arange(2007,last_year) ]
yearly_start_times=parse_time(years_jan_1_str).datetime
yearly_start_times_num=parse_time(years_jan_1_str).plot_date
#same for July 1 as middle of the year
years_jul_1_str=[str(i)+'-07-01' for i in np.arange(2007,last_year) ]
yearly_mid_times=parse_time(years_jul_1_str).datetime
yearly_mid_times_num=parse_time(years_jul_1_str).plot_date
#same for december 31
years_dec_31_str=[str(i)+'-12-31' for i in np.arange(2007,last_year) ]
yearly_end_times=parse_time(years_dec_31_str).datetime
yearly_end_times_num=parse_time(years_dec_31_str).plot_date
########### define arrays for total data days and fill with nan
total_data_days_yearly_win=np.zeros(np.size(yearly_mid_times))
total_data_days_yearly_win.fill(np.nan)
total_data_days_yearly_psp=np.zeros(np.size(yearly_mid_times))
total_data_days_yearly_psp.fill(np.nan)
total_data_days_yearly_solo=np.zeros(np.size(yearly_mid_times))
total_data_days_yearly_solo.fill(np.nan)
total_data_days_yearly_bepi=np.zeros(np.size(yearly_mid_times))
total_data_days_yearly_bepi.fill(np.nan)
total_data_days_yearly_sta=np.zeros(np.size(yearly_mid_times))
total_data_days_yearly_sta.fill(np.nan)
total_data_days_yearly_stb=np.zeros(np.size(yearly_mid_times))
total_data_days_yearly_stb.fill(np.nan)
total_data_days_yearly_mes=np.zeros(np.size(yearly_mid_times))
total_data_days_yearly_mes.fill(np.nan)
total_data_days_yearly_vex=np.zeros(np.size(yearly_mid_times))
total_data_days_yearly_vex.fill(np.nan)
total_data_days_yearly_mav=np.zeros(np.size(yearly_mid_times))
total_data_days_yearly_mav.fill(np.nan)
######################## go through each year and search for available data
#time is available for all dates, so there are no NaNs in time, thus need to search for all not NaNs in Btotal variable
for i in range(np.size(yearly_mid_times)):
print(yearly_start_times[i])
#get indices of Wind time for the current year
thisyear=np.where(np.logical_and((win.time > yearly_start_times[i]),(win.time < yearly_end_times[i])))[0]
#get np.size of available data for each year
datas=np.size(np.where(np.isnan(win.bt[thisyear])==False))
#wind is in 1 minute resolution until 31 Dec 2017, from 1 Jan 2018 its 2 minutes
min_in_days=1/(60*24)
if i > 10: min_in_days=1/(60*24)
#calculate available days from number of datapoints (each 1 minute)
#divided by number of minutes in 1 days
#this should only be the case if data is available this year, otherwise set to NaN
if datas > 0: total_data_days_yearly_win[i]=datas*min_in_days
#manual override because Wind data for 2018 and 2019 are heavily despiked
total_data_days_yearly_win[-4]=360
total_data_days_yearly_win[-3]=360
total_data_days_yearly_win[-2]=360
total_data_days_yearly_win[-1]=180
#all other data is in 1 min resolution
min_in_days=1/(60*24)
#for PSP
thisyear=np.where(np.logical_and((psp.time > yearly_start_times[i]),(psp.time < yearly_end_times[i])))[0]
datas=np.size(np.where(np.isnan(psp.bt[thisyear])==False))
if datas >0: total_data_days_yearly_psp[i]=datas*min_in_days
#for Bepi
thisyear=np.where(np.logical_and((bepi.time > yearly_start_times[i]),(bepi.time < yearly_end_times[i])))[0]
datas=np.size(np.where(np.isnan(bepi.bt[thisyear])==False))
if datas >0: total_data_days_yearly_bepi[i]=datas*min_in_days
#for solo
thisyear=np.where(np.logical_and((solo.time > yearly_start_times[i]),(solo.time < yearly_end_times[i])))[0]
datas=np.size(np.where(np.isnan(solo.bt[thisyear])==False))
if datas >0: total_data_days_yearly_solo[i]=datas*min_in_days
#same for STEREO-A
thisyear=np.where(np.logical_and((sta.time > yearly_start_times[i]),(sta.time < yearly_end_times[i])))[0]
datas=np.size(np.where(np.isnan(sta.bt[thisyear])==False))
if datas >0: total_data_days_yearly_sta[i]=datas*min_in_days
#same for STEREO-B
thisyear=np.where(np.logical_and((stb.time > yearly_start_times[i]),(stb.time < yearly_end_times[i])))[0]
datas=np.size(np.where(np.isnan(stb.bt[thisyear])==False))
if datas >0: total_data_days_yearly_stb[i]=datas*min_in_days
#same for MESSENGER
thisyear=np.where(np.logical_and((mesnon.time > yearly_start_times[i]),(mesnon.time < yearly_end_times[i])))
datas=np.size(np.where(np.isnan(mes.bt[thisyear])==False))
if datas >0: total_data_days_yearly_mes[i]=datas*min_in_days
#same for Mercury alone with non-removed dataset
#start with 2011
# if i == 4:
# thisyear=np.where(np.logical_and((mesnon.time > mercury_orbit_insertion_time),(mesnon.time < yearly_end_times[i])))[0]
# datas=np.size(np.where(np.isnan(mesnon.bt[thisyear])==False))
# if datas >0: total_data_days_yearly_merc[i]=datas*min_in_days
# #2012 onwards
# if i > 4:
# thisyear=np.where(np.logical_and((mesnon.time > yearly_start_times[i]),(mesnon.time < yearly_end_times[i])))
# datas=np.size(np.where(np.isnan(mesnon.bt[thisyear])==False))
# if datas >0: total_data_days_yearly_merc[i]=datas*min_in_days
#same for VEX
thisyear=np.where(np.logical_and((vexnon.time > yearly_start_times[i]),(vexnon.time < yearly_end_times[i])))[0]
datas=np.size(np.where(np.isnan(vexnon.bt[thisyear])==False))
if datas >0: total_data_days_yearly_vex[i]=datas*min_in_days
#for MAVEN different time resolution
thisyear=np.where(np.logical_and((mav.time > yearly_start_times[i]),(mav.time < yearly_end_times[i])))[0]
datas=np.size(np.where(np.isnan(mav.bt[thisyear])==False))
datas_ind=np.where(np.isnan(mav.bt[thisyear])==False)
#sum all time intervals for existing data points, but avoid counting gaps where diff is > 1 orbit (0.25 days)
alldiff=np.diff(parse_time(mav.time[datas_ind]).plot_date)
smalldiff_ind=np.where(alldiff <0.25)
if datas >0: total_data_days_yearly_mav[i]=np.sum(alldiff[smalldiff_ind])
print('Data days each year:')
print()
print('MESSENGER')
print(np.round(total_data_days_yearly_mes,1))
print()
print('VEX at Venus')
print(np.round(total_data_days_yearly_vex,1))
print()
print('STB')
print(np.round(total_data_days_yearly_stb,1))
print()
print('MAVEN')
print(np.round(total_data_days_yearly_mav,1))
print()
print()
print('Wind')
print(np.round(total_data_days_yearly_win,1))
print('STA')
print(np.round(total_data_days_yearly_sta,1))
print('PSP')
print(np.round(total_data_days_yearly_psp,1))
print('Bepi')
print(np.round(total_data_days_yearly_bepi,1))
print('Solar Orbiter')
print(np.round(total_data_days_yearly_solo,1))
print()
print('done')
# ### get yearly ICME rates at each spacecraft
# In[7]:
#define dates of January 1 from 2007 to 2022
years_jan_1_str_plus1=[str(i)+'-01-01' for i in np.arange(2007,last_year+1) ]
yearly_bin_edges=parse_time(years_jan_1_str_plus1).plot_date
#bin width in days
binweite=365/8
(histmes1, bin_edgesmes) = np.histogram(parse_time(ic.icme_start_time[mesi]).plot_date, yearly_bin_edges)
(histvex1, bin_edgesvex) = np.histogram(parse_time(ic.icme_start_time[vexi]).plot_date, yearly_bin_edges)
(histmav1, bin_edgesmav) = np.histogram(parse_time(ic.icme_start_time[mavi]).plot_date, yearly_bin_edges)
(histstb1, bin_edgesstb) = np.histogram(parse_time(ic.icme_start_time[stbi]).plot_date, yearly_bin_edges)
(histwin1, bin_edgeswin) = np.histogram(parse_time(ic.icme_start_time[wini]).plot_date, yearly_bin_edges)
(histsta1, bin_edgessta) = np.histogram(parse_time(ic.icme_start_time[stai]).plot_date, yearly_bin_edges)
(histpsp1, bin_edgespsp) = np.histogram(parse_time(ic.icme_start_time[pspi]).plot_date, yearly_bin_edges)
(histsolo1, bin_edgessolo) = np.histogram(parse_time(ic.icme_start_time[soli]).plot_date, yearly_bin_edges)
(histbepi1, bin_edgesbepi) = np.histogram(parse_time(ic.icme_start_time[beci]).plot_date, yearly_bin_edges)
binedges=bin_edgeswin
#normalize each dataset for data gaps, so correcting ICME rate for actual data availability
#note that for VEX and MESSENGER this was done with the non-removed datasets (vexnon, mesnon)
histvex=np.round(histvex1/total_data_days_yearly_vex*365.24,1)
histmes=np.round(histmes1/total_data_days_yearly_mes*365.24,1)
#ok for these spacecraft as continously in the solar wind and the MAVEN data set is made without orbit gaps
histsta=np.round(histsta1/total_data_days_yearly_sta*365.24,1)
#STA beacon data used in 2019 - set manually
histsta[-3]=13
#STA beacon data used in 2020 - set manually
histsta[-2]=10*4/3
histmav=np.round(histmav1/total_data_days_yearly_mav*365.24,1)
histmav[7]=np.nan #not enough data for 2014
histstb=np.round(histstb1/total_data_days_yearly_stb*365.24,1)
histwin=np.round(histwin1/total_data_days_yearly_win*365.24,1)
histpsp=np.round(histpsp1/total_data_days_yearly_psp*365.24,1)
histsolo=np.round(histsolo1/total_data_days_yearly_solo*365.24,1)
histbepi=np.round(histbepi1/total_data_days_yearly_bepi*365.24,1)
print('corrected ICME rates for years')
print(yearly_mid_times)
print('MESSENGER',histmes)
print('VEX',histvex)
print('Wind',histwin)
print('PSP',histpsp)
print('STA',histsta)
print('STB',histstb)
print('MAVEN',histmav)
sns.set_context("talk")
sns.set_style('darkgrid')
plt.figure(11,figsize=(12,6),dpi=60)
plt.ylabel('ICMEs per year, ICMECAT')
plt.plot(yearly_mid_times,histmes,'-',label='MESSENGER')
plt.plot(yearly_mid_times,histvex,'-',label='VEX')
plt.plot(yearly_mid_times,histwin,'-',label='Wind')
plt.plot(yearly_mid_times,histsta,'-',label='STA')
plt.plot(yearly_mid_times,histstb,'-',label='STB')
plt.plot(yearly_mid_times,histmav,'-',label='MAVEN')
plt.plot(yearly_mid_times,histpsp,'-',label='PSP')
plt.plot(yearly_mid_times,histsolo,'-',label='SolarOrbiter')
plt.plot(yearly_mid_times,histbepi,'-',label='BepiColombo')
plt.legend(loc=1,fontsize=10)
################### calculate general parameters
print()
print()
print('calculate ICME rate matrix std, mean, max, min')
#arrange icmecat rate data so each row contains std, mean, max, min
icrate=pd.DataFrame(np.zeros([len(yearly_mid_times),6]), columns=['year','std1', 'median1','mean1', 'max1', 'min1'] )
for i in np.arange(0,len(yearly_mid_times)):
icrate.at[i,'year']=yearly_mid_times_num[i]
icrate.at[i,'median1']=np.round(np.nanmedian([histwin[i],histvex[i],histsta[i],histstb[i],histmes[i],histmav[i],histpsp[i]]),1)
icrate.at[i,'mean1']=np.round(np.nanmean([histwin[i],histvex[i],histsta[i],histstb[i],histmes[i],histmav[i],histpsp[i]]),1)
icrate.at[i,'std1']=np.round(np.nanstd([histwin[i],histvex[i],histsta[i],histstb[i],histmes[i],histmav[i],histpsp[i]]),1)
icrate.at[i,'max1']=np.nanmax([histwin[i],histvex[i],histsta[i],histstb[i],histmes[i],histmav[i],histpsp[i]])
icrate.at[i,'min1']=np.nanmin([histwin[i],histvex[i],histsta[i],histstb[i],histmes[i],histmav[i],histpsp[i]])
#change matplotlib time before plotting
icrate_year2=icrate.year + mdates.date2num(np.datetime64('0000-12-31'))
plt.plot([icrate_year2,icrate_year2],[icrate.mean1-icrate.std1,icrate.mean1+icrate.std1],'-k',lw=0.5)
plt.plot(icrate_year2,icrate.mean1,'ok',markerfacecolor='white')
# icrate=pd.DataFrame(np.zeros([len(histvex)*6,3]), columns=['year','rate','sc'] )
# #write all icme rates into this array
# icrate.at[0:12,'rate']=histmes
# icrate.at[0:12,'year']=yearly_start_times_num
# icrate.at[0:12,'sc']='MESSENGER'
# icrate.at[13:25,'rate']=histvex
# icrate.at[13:25,'year']=yearly_start_times_num
# icrate.at[13:25,'sc']='VEX'
# icrate.at[26:38,'rate']=histwin
# icrate.at[26:38,'year']=yearly_start_times_num
# icrate.at[26:38,'sc']='Wind'
# icrate.at[39:51,'rate']=histvex
# icrate.at[39:51,'year']=yearly_start_times_num
# icrate.at[39:51,'sc']='STA'
# icrate.at[52:64,'rate']=histvex
# icrate.at[52:64,'year']=yearly_start_times_num
# icrate.at[52:64,'sc']='STB'
# icrate.at[65:77,'rate']=histvex
# icrate.at[65:77,'year']=yearly_start_times_num
# icrate.at[65:77,'sc']='MAVEN'
# sns.boxplot(x='year',y='rate',data=icrate)
icrate
# ### get Richardson and Cane ICME rate for comparison
# In[8]:
#convert times in dataframe from richardson and cane list to numpy array
r1=np.array(rc_df['Disturbance Y/M/D (UT) (a)'])
#to get ICME rate, go through all rows
rc_year=np.zeros(len(r1))
#extract string and check whether its a viable float and non nan:
for p in np.arange(0,len(r1)):
rc_yearstr=str(r1[p,0])
if hs.is_float(rc_yearstr[0:4]):
if np.isfinite(float(rc_yearstr[0:4])):
rc_year[p]=float(rc_yearstr[0:4]) #rc_year contains all ICME
rc_year.sort()
rc_icme_per_year=np.trim_zeros(rc_year)
#print(rc_year)
#plot check whats in this array
sns.set_style('darkgrid')
fig=plt.figure(12,figsize=(12,5),dpi=80)
ax11=sns.distplot(rc_icme_per_year,bins=24,kde=None)
plt.ylabel('ICMEs per year, RC list')
#count all full years from 1996-2021
bins_years=2022-1996
#get yearly ICME rate (use range to get correct numbers)
rc_rate_values=np.histogram(rc_icme_per_year,bins=bins_years,range=(1996,2022))[0]
rc_rate_time=np.histogram(rc_icme_per_year,bins=bins_years,range=(1996,2022))[1][0:-1]
print(rc_rate_values)
print(rc_rate_time)
years_jul_1_str_rc=[str(i)+'-07-01' for i in np.arange(1996,2021) ]
yearly_mid_times_rc=parse_time(years_jul_1_str_rc).datetime
yearly_mid_times_num_rc=parse_time(years_jul_1_str_rc).plot_date
print(yearly_mid_times_rc)
#plt.figure(2)
#plt.plot(yearly_mid_times_rc,rc_rate_values)
# ### **Figure 1** plot ICME frequency cycle 24
# In[9]:
sns.set_context("talk")
#sns.set_style('whitegrid',{'grid.linestyle': '--'})
sns.set_style("ticks",{'grid.linestyle': '--'})
fsize=15
fig=plt.figure(1,figsize=(12,10),dpi=80)
######################## Fig 1a - sc positions during ICMEs vs time
ax1 = plt.subplot(211)
msize=5
plt.plot_date(ic.icme_start_time[mesi],ic.mo_sc_heliodistance[mesi],fmt='o',color='coral',markersize=msize,label='MESSENGER')
plt.plot_date(ic.icme_start_time[vexi],ic.mo_sc_heliodistance[vexi],fmt='o',color='orange',markersize=msize,label='VEX')
plt.plot_date(ic.icme_start_time[wini],ic.mo_sc_heliodistance[wini],fmt='o',color='mediumseagreen',markersize=msize,label='Wind')
plt.plot_date(ic.icme_start_time[stai],ic.mo_sc_heliodistance[stai],fmt='o',color='red',markersize=msize,label='STEREO-A')
plt.plot_date(ic.icme_start_time[stbi],ic.mo_sc_heliodistance[stbi],fmt='o',color='royalblue',markersize=msize,label='STEREO-B')
plt.plot_date(ic.icme_start_time[mavi],ic.mo_sc_heliodistance[mavi],fmt='o',color='steelblue',markersize=msize,label='MAVEN')
plt.plot_date(ic.icme_start_time[pspi],ic.mo_sc_heliodistance[pspi],fmt='o',color='black',markersize=msize,label='PSP')
plt.plot_date(ic.icme_start_time[soli],ic.mo_sc_heliodistance[soli],'o',c='black',markerfacecolor='white', markersize=msize,label='Solar Orbiter')
plt.plot_date(ic.icme_start_time[beci],ic.mo_sc_heliodistance[beci],'s',c='darkblue',markerfacecolor='lightgrey', markersize=msize, label='BepiColombo')
plt.legend(loc='upper left',fontsize=10)
plt.ylabel('Heliocentric distance R [AU]',fontsize=fsize)
plt.xticks(yearly_start_times,fontsize=fsize)
#change matplotlib time before plotting
yearly_bin_edges2=yearly_bin_edges + mdates.date2num(np.datetime64('0000-12-31'))
plt.xlim(yearly_bin_edges2[0],yearly_bin_edges2[-1])
plt.ylim([0,1.7])
plt.yticks(np.arange(0,1.9,0.2),fontsize=fsize)
ax1.xaxis_date()
myformat = mdates.DateFormatter('%Y')
ax1.xaxis.set_major_formatter(myformat)
#grid for icme rate
for i in np.arange(0,2.0,0.2):
ax1.plot([datetime.datetime(2007,1,1),datetime.datetime(2024,1,1)],np.zeros(2)+i,linestyle='--',color='grey',alpha=0.5,lw=0.8,zorder=0)
for i in np.arange(0,14):
ax1.plot([yearly_start_times[i],yearly_start_times[i]],[0,2],linestyle='--',color='grey',alpha=0.5,lw=0.8,zorder=0)