-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcme_stats_parker.py
2615 lines (1604 loc) · 86 KB
/
cme_stats_parker.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
# cme_stats_parker.py
#
# analyses HELCATS ICMECAT data for EGU 2018 poster on CME statistics
# Author: C. Moestl, Space Research Institute IWF Graz, Austria
# last update: February 2018
from scipy import stats
import scipy.io
from matplotlib import cm
import sys
import matplotlib
import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
import sunpy.time
import time
import pickle
import seaborn as sns
def getcat(filename):
print('reading CAT')
cat=scipy.io.readsav(filename, verbose='true')
print('done CAT')
return cat
def decode_array(bytearrin):
#for decoding the strings from the IDL .sav file to a list of python strings, not bytes
#make list of python lists with arbitrary length
bytearrout= ['' for x in range(len(bytearrin))]
for i in range(0,len(bytearrin)-1):
bytearrout[i]=bytearrin[i].decode()
#has to be np array so to be used with numpy "where"
bytearrout=np.array(bytearrout)
return bytearrout
def time_to_num_cat(time_in):
#for time conversion from catalogue .sav to numerical time
#this for 1-minute data or lower time resolution
#for all catalogues
#time_in is the time in format: 2007-11-17T07:20:00 or 2007-11-17T07:20Z
#for times help see:
#http://docs.sunpy.org/en/latest/guide/time.html
#http://matplotlib.org/examples/pylab_examples/date_demo2.html
j=0
#time_str=np.empty(np.size(time_in),dtype='S19')
time_str= ['' for x in range(len(time_in))]
#=np.chararray(np.size(time_in),itemsize=19)
time_num=np.zeros(np.size(time_in))
for i in time_in:
#convert from bytes (output of scipy.readsav) to string
time_str[j]=time_in[j][0:16].decode()+':00'
year=int(time_str[j][0:4])
time_str[j]
#convert time to sunpy friendly time and to matplotlibdatetime
#only for valid times so 9999 in year is not converted
#pdb.set_trace()
if year < 2100:
time_num[j]=mdates.date2num(sunpy.time.parse_time(time_str[j]))
j=j+1
#the date format in matplotlib is e.g. 735202.67569444
#this is time in days since 0001-01-01 UTC, plus 1.
#return time_num which is already an array and convert the list of strings to an array
return time_num, np.array(time_str)
def IDL_time_to_num(time_in):
#convert IDL time to matplotlib datetime
time_num=np.zeros(np.size(time_in))
for ii in np.arange(0,np.size(time_in)):
time_num[ii]=mdates.date2num(sunpy.time.parse_time(time_in[ii]))
return time_num
def gaussian(x, amp, mu, sig):
return amp * exp(-(x-cen)**2 /wid)
#define global variables from OMNI2 dataset
#see http://omniweb.gsfc.nasa.gov/html/ow_data.html
dataset=473376;
#global Variables
spot=np.zeros(dataset)
btot=np.zeros(dataset) #floating points
bx=np.zeros(dataset) #floating points
by=np.zeros(dataset) #floating points
bz=np.zeros(dataset) #floating points
bzgsm=np.zeros(dataset) #floating points
bygsm=np.zeros(dataset) #floating points
speed=np.zeros(dataset) #floating points
speedx=np.zeros(dataset) #floating points
speed_phi=np.zeros(dataset) #floating points
speed_theta=np.zeros(dataset) #floating points
dst=np.zeros(dataset) #float
kp=np.zeros(dataset) #float
den=np.zeros(dataset) #float
pdyn=np.zeros(dataset) #float
year=np.zeros(dataset)
day=np.zeros(dataset)
hour=np.zeros(dataset)
t=np.zeros(dataset) #index time
times1=np.zeros(dataset) #datetime time
def convertomnitime():
#http://docs.sunpy.org/en/latest/guide/time.html
#http://matplotlib.org/examples/pylab_examples/date_demo2.html
print('convert time start')
for index in range(0,dataset):
#first to datetimeobject
timedum=datetime.datetime(int(year[index]), 1, 1) + datetime.timedelta(day[index] - 1) +datetime.timedelta(hours=hour[index])
#then to matlibplot dateformat:
times1[index] = matplotlib.dates.date2num(timedum)
#print time
#print year[index], day[index], hour[index]
print('convert time done') #for time conversion
def getomnidata():
#statt NaN waere besser linear interpolieren
#lese file ein:
#FORMAT(2I4,I3,I5,2I3,2I4,14F6.1,F9.0,F6.1,F6.0,2F6.1,F6.3,F6.2, F9.0,F6.1,F6.0,2F6.1,F6.3,2F7.2,F6.1,I3,I4,I6,I5,F10.2,5F9.2,I3,I4,2F6.1,2I6,F5.1)
#1963 1 0 1771 99 99 999 999 999.9 999.9 999.9 999.9 999.9 999.9 999.9 999.9 999.9 999.9 999.9 999.9 999.9 999.9 9999999. 999.9 9999. 999.9 999.9 9.999 99.99 9999999. 999.9 9999. 999.9 999.9 9.999 999.99 999.99 999.9 7 23 -6 119 999999.99 99999.99 99999.99 99999.99 99999.99 99999.99 0 3 999.9 999.9 99999 99999 99.9
j=0
print('start reading variables from file')
with open('/Users/chris/python/data/omni_data/omni2_all_years.dat') as f:
for line in f:
line = line.split() # to deal with blank
#print line #41 is Dst index, in nT
dst[j]=line[40]
kp[j]=line[38]
if dst[j] == 99999: dst[j]=np.NaN
#40 is sunspot number
spot[j]=line[39]
#if spot[j] == 999: spot[j]=NaN
#25 is bulkspeed F6.0, in km/s
speed[j]=line[24]
if speed[j] == 9999: speed[j]=np.NaN
#get speed angles F6.1
speed_phi[j]=line[25]
if speed_phi[j] == 999.9: speed_phi[j]=np.NaN
speed_theta[j]=line[26]
if speed_theta[j] == 999.9: speed_theta[j]=np.NaN
#convert speed to GSE x see OMNI website footnote
speedx[j] = - speed[j] * np.cos(np.radians(speed_theta[j])) * np.cos(np.radians(speed_phi[j]))
#9 is total B F6.1 also fill ist 999.9, in nT
btot[j]=line[9]
if btot[j] == 999.9: btot[j]=np.NaN
#GSE components from 13 to 15, so 12 to 14 index, in nT
bx[j]=line[12]
if bx[j] == 999.9: bx[j]=np.NaN
by[j]=line[13]
if by[j] == 999.9: by[j]=np.NaN
bz[j]=line[14]
if bz[j] == 999.9: bz[j]=np.NaN
#GSM
bygsm[j]=line[15]
if bygsm[j] == 999.9: bygsm[j]=np.NaN
bzgsm[j]=line[16]
if bzgsm[j] == 999.9: bzgsm[j]=np.NaN
#24 in file, index 23 proton density /ccm
den[j]=line[23]
if den[j] == 999.9: den[j]=np.NaN
#29 in file, index 28 Pdyn, F6.2, fill values sind 99.99, in nPa
pdyn[j]=line[28]
if pdyn[j] == 99.99: pdyn[j]=np.NaN
year[j]=line[0]
day[j]=line[1]
hour[j]=line[2]
j=j+1
print('done reading variables from file')
print(j, ' datapoints') #for reading data from OMNI file
######################################################
#main program
plt.close('all')
print('Start catpy main program. Analyses and plots for ICME duration and planetary (Mars!) impacts')
#getomnidata()
#convertomnitime()
#-------------------------------------------------------- get cats
#filename_arrcat='ALLCATS/HELCATS_ARRCAT_v6.sav'
#a=getcat(filename_arrcat)
filename_icmecat='ALLCATS/HELCATS_ICMECAT_v11_SCEQ.sav'
i=getcat(filename_icmecat)
#filename_linkcat='ALLCATS/HELCATS_LINKCAT_v10.sav'
#l=getcat(filename_linkcat)
#now this is a structured array
#access each element of the array see http://docs.scipy.org/doc/numpy/user/basics.rec.html
#access variables
#i.icmecat['id']
#look at contained variables
#print(a.arrcat.dtype)
#print(i.icmecat.dtype)
#get spacecraft and planet positions
pos=getcat('../catpy/DATACAT/positions_2007_2018_HEEQ_6hours.sav')
pos_time_num=time_to_num_cat(pos.time)[0]
#---------------------------- get all parameters from ICMECAT
iid=i.icmecat['id']
#need to decode all strings
iid=decode_array(iid)
isc=i.icmecat['sc_insitu'] #string
isc=decode_array(isc)
icme_start_time=i.icmecat['ICME_START_TIME']
[icme_start_time_num,icme_start_time_str]=time_to_num_cat(icme_start_time)
mo_start_time=i.icmecat['MO_START_TIME']
[mo_start_time_num,mo_start_time_str]=time_to_num_cat(mo_start_time)
mo_end_time=i.icmecat['MO_END_TIME']
[mo_end_time_num,mo_end_time_str]=time_to_num_cat(mo_end_time)
icme_end_time=i.icmecat['ICME_END_TIME']
[icme_end_time_num,icme_end_time_str]=time_to_num_cat(icme_end_time)
sc_heliodistance=i.icmecat['SC_HELIODISTANCE']
sc_long_heeq=i.icmecat['SC_LONG_HEEQ']
sc_lat_heeq=i.icmecat['SC_LAT_HEEQ']
mo_bmax=i.icmecat['MO_BMAX']
mo_bmean=i.icmecat['MO_BMEAN']
mo_bstd=i.icmecat['MO_BSTD']
mo_bzmean=i.icmecat['MO_BZMEAN']
mo_bzmin=i.icmecat['MO_BZMIN']
mo_duration=i.icmecat['MO_DURATION']
mo_mva_axis_long=i.icmecat['MO_MVA_AXIS_LONG']
mo_mva_axis_lat=i.icmecat['MO_MVA_AXIS_LAT']
mo_mva_ratio=i.icmecat['MO_MVA_RATIO']
sheath_speed=i.icmecat['SHEATH_SPEED']
sheath_speed_std=i.icmecat['SHEATH_SPEED_STD']
mo_speed=i.icmecat['MO_SPEED']
mo_speed_st=i.icmecat['MO_SPEED_STD']
sheath_density=i.icmecat['SHEATH_DENSITY']
sheath_density_std=i.icmecat['SHEATH_DENSITY_STD']
mo_density=i.icmecat['MO_DENSITY']
mo_density_std=i.icmecat['MO_DENSITY_STD']
sheath_temperature=i.icmecat['SHEATH_TEMPERATURE']
sheath_temperature_std=i.icmecat['SHEATH_TEMPERATURE_STD']
mo_temperature=i.icmecat['MO_TEMPERATURE']
mo_temperature_std=i.icmecat['MO_TEMPERATURE_STD']
#get indices of events in different spacecraft
ivexind=np.where(isc == 'VEX')
istaind=np.where(isc == 'STEREO-A')
istbind=np.where(isc == 'STEREO-B')
iwinind=np.where(isc == 'Wind')
imesind=np.where(isc == 'MESSENGER')
iulyind=np.where(isc == 'ULYSSES')
imavind=np.where(isc == 'MAVEN')
#take MESSENGER only at Mercury, only events after orbit insertion
imercind=np.where(np.logical_and(isc =='MESSENGER',icme_start_time_num > mdates.date2num(sunpy.time.parse_time('2011-03-18'))))
#limits of solar minimum, rising phase and solar maximum
minstart=mdates.date2num(sunpy.time.parse_time('2007-01-01'))
minend=mdates.date2num(sunpy.time.parse_time('2009-12-31'))
risestart=mdates.date2num(sunpy.time.parse_time('2010-01-01'))
riseend=mdates.date2num(sunpy.time.parse_time('2011-06-30'))
maxstart=mdates.date2num(sunpy.time.parse_time('2011-07-01'))
maxend=mdates.date2num(sunpy.time.parse_time('2014-12-31'))
#extract events by limits of solar min, rising, max, too few events for MAVEN and Ulysses
iallind_min=np.where(np.logical_and(icme_start_time_num > minstart,icme_start_time_num < minend))[0]
iallind_rise=np.where(np.logical_and(icme_start_time_num > risestart,icme_start_time_num < riseend))[0]
iallind_max=np.where(np.logical_and(icme_start_time_num > maxstart,icme_start_time_num < maxend))[0]
iwinind_min=iallind_min[np.where(isc[iallind_min]=='Wind')]
iwinind_rise=iallind_rise[np.where(isc[iallind_rise]=='Wind')]
iwinind_max=iallind_max[np.where(isc[iallind_max]=='Wind')]
ivexind_min=iallind_min[np.where(isc[iallind_min]=='VEX')]
ivexind_rise=iallind_rise[np.where(isc[iallind_rise]=='VEX')]
ivexind_max=iallind_max[np.where(isc[iallind_max]=='VEX')]
imesind_min=iallind_min[np.where(isc[iallind_min]=='MESSENGER')]
imesind_rise=iallind_rise[np.where(isc[iallind_rise]=='MESSENGER')]
imesind_max=iallind_max[np.where(isc[iallind_max]=='MESSENGER')]
istaind_min=iallind_min[np.where(isc[iallind_min]=='STEREO-A')]
istaind_rise=iallind_rise[np.where(isc[iallind_rise]=='STEREO-A')]
istaind_max=iallind_max[np.where(isc[iallind_max]=='STEREO-A')]
istbind_min=iallind_min[np.where(isc[iallind_min]=='STEREO-B')]
istbind_rise=iallind_rise[np.where(isc[iallind_rise]=='STEREO-B')]
istbind_max=iallind_max[np.where(isc[iallind_max]=='STEREO-B')]
Rs_in_AU=7e5/149.5e6
###################################################################################
##################### (1) DURATION PLOT and linear fit ############################
sns.set_context("talk")
#sns.set_style("darkgrid")
sns.set_style("ticks",{'grid.linestyle': '--'})
fig=plt.figure(1,figsize=(12,11 ))
fsize=15
ax1 = plt.subplot2grid((2,1), (0, 0))
xfit=np.linspace(0,2,1000)
icme_durations=(mo_end_time_num-icme_start_time_num)*24 #hours
#make linear fits - no forcing through origin
durfit=np.polyfit(sc_heliodistance,icme_durations,1)
durfitmin=np.polyfit(sc_heliodistance[iallind_min],icme_durations[iallind_min],1)
durfitrise=np.polyfit(sc_heliodistance[iallind_rise],icme_durations[iallind_rise],1)
durfitmax=np.polyfit(sc_heliodistance[iallind_max],icme_durations[iallind_max],1)
#force through origin, fit with y=kx
scx=sc_heliodistance[:,np.newaxis]
durfit_f, _, _, _ =np.linalg.lstsq(scx,icme_durations)
scx=sc_heliodistance[iallind_min][:,np.newaxis]
durfitmin_f, _, _, _ =np.linalg.lstsq(scx,icme_durations[iallind_min])
scx=sc_heliodistance[iallind_rise][:,np.newaxis]
durfitrise_f, _, _, _ =np.linalg.lstsq(scx,icme_durations[iallind_rise])
scx=sc_heliodistance[iallind_max][:,np.newaxis]
durfitmax_f, _, _, _ =np.linalg.lstsq(scx,icme_durations[iallind_max])
#this is similar to D=durfit[0]*xfit+durfit[1]
durfitall=np.poly1d(durfit)
durfitmin=np.poly1d(durfitmin)
durfitrise=np.poly1d(durfitrise)
durfitmax=np.poly1d(durfitmax)
#make the y axis for the fits forced through the origin
ydurfitall_f=durfit_f*xfit
ydurfitmin_f=durfitmin_f*xfit
ydurfitrise_f=durfitrise_f*xfit
ydurfitmax_f=durfitmax_f*xfit
#for fit plotting
print('ICME duration linear function: D[hours]={:.2f}r[AU]+{:.2f}'.format(durfit[0],durfit[1]))
plt.plot(sc_heliodistance,icme_durations,'o',color='blue',markersize=5, alpha=0.3,label='D')
#plt.plot(sc_heliodistance[iallind_min],icme_durations[iallind_min],'o',color='dimgrey',markersize=3, alpha=0.4,label='D min')
#plt.plot(sc_heliodistance[iallind_rise],icme_durations[iallind_rise],'o',color='grey',markersize=3, alpha=0.7,label='D rise')
#plt.plot(sc_heliodistance[iallind_max],icme_durations[iallind_max],'o',color='black',markersize=3, alpha=0.8,label='D max')
#plot fits
plt.plot(xfit,ydurfitall_f,'-',color='blue', lw=2.5, alpha=0.9,label='fit')
plt.plot(xfit,ydurfitmin_f,'--',color='black', lw=2, alpha=0.9,label='min fit')
plt.plot(xfit,ydurfitrise_f,'-.',color='black', lw=2, alpha=0.9,label='rise fit')
plt.plot(xfit,ydurfitmax_f,'-',color='black', lw=2, alpha=0.9,label='max fit')
#these don't go through the origin
#plt.plot(xfit,durfitall(xfit),'-',color='blue', lw=2.5, alpha=0.9,label='fit')
#plt.plot(xfit,durfitmin(xfit),'--',color='black', lw=2, alpha=0.9,label='min fit')
#plt.plot(xfit,durfitrise(xfit),'-.',color='black', lw=2, alpha=0.9,label='rise fit')
#plt.plot(xfit,durfitmax(xfit),'-',color='black', lw=2, alpha=0.9,label='max fit')
plt.annotate('overall: D[h]={:.2f} R[AU] '.format(durfit_f[0]),xy=(0.1,60),fontsize=11)
plt.annotate('minimum: D[h]={:.2f} R[AU] '.format(durfitmin_f[0]),xy=(0.1,55),fontsize=11)
plt.annotate('rising phase: D[h]={:.2f} R[AU]'.format(durfitrise_f[0]),xy=(0.1,50),fontsize=11)
plt.annotate('maximum: D[h]={:.2f} R[AU]'.format(durfitmax_f[0]),xy=(0.1,45),fontsize=11)
#plt.annotate('overall: D[h]={:.2f} R[AU] + {:.2f}'.format(durfitall[0],durfitall[1]),xy=(0.1,120),fontsize=12)
#plt.annotate('minimum: D[h]={:.2f} R[AU] + {:.2f}'.format(durfitmin[0],durfitmin[1]),xy=(0.1,100),fontsize=12)
#plt.annotate('rising phase: D[h]={:.2f} R[AU] + {:.2f}'.format(durfitrise[0],durfitrise[1]),xy=(0.1,80),fontsize=12)
#plt.annotate('maximum: D[h]={:.2f} R[AU] + {:.2f}'.format(durfitmax[0],durfitmax[1]),xy=(0.1,60),fontsize=12)
#planet limits
plt.axvspan(np.min(pos.mars[0]),np.max(pos.mars[0]), color='orangered', alpha=0.2)
plt.axvspan(np.min(pos.mercury[0]),np.max(pos.mercury[0]), color='darkgrey', alpha=0.2)
plt.axvspan(np.min(pos.venus[0]),np.max(pos.venus[0]), color='orange', alpha=0.2)
plt.axvspan(np.min(pos.earth[0]),np.max(pos.earth[0]), color='mediumseagreen', alpha=0.2)
plt.axvspan(0.044,0.3,color='magenta', alpha=0.2)
plt.annotate('Mars', xy=(1.5,65), ha='center',fontsize=fsize)
plt.annotate('PSP', xy=(0.11,65), ha='center',fontsize=fsize)
plt.annotate('Mercury', xy=(0.38,65), ha='center',fontsize=fsize)
plt.annotate('Venus', xy=(0.72,65), ha='center',fontsize=fsize)
plt.annotate('Earth', xy=(1,65), ha='center',fontsize=fsize)
ax1.set_xticks(np.arange(0,2,0.2))
plt.xlim(0,max(sc_heliodistance)+0.3)
#plt.ylim(0,max(icme_durations)+30)
plt.ylim(0,70)
plt.legend(loc=4,fontsize=fsize-1)
plt.xlabel('Heliocentric distance R [AU]',fontsize=fsize)
plt.ylabel('ICME duration D [hours]',fontsize=fsize)
plt.yticks(fontsize=fsize)
plt.xticks(fontsize=fsize)
#plt.grid()
print('results for durations and distance for PSP from 0.04 to 0.3 AU')
print('all fits')
psp_dist=np.where(np.logical_and(xfit < 0.3, xfit > 0.04))
#psp_durs=durfitall(xfit[psp_dist])
psp_durs=durfit_f*xfit[psp_dist]
pspdur_mean=np.mean(psp_durs)
pspdur_std=np.std(psp_durs)
pspdur_min=np.min(psp_durs)
pspdur_max=np.max(psp_durs)
print('Parker predicted durations from 0.044 to 0.3 AU: mean +/ std, min, max')
print(pspdur_mean, ' +/- ',pspdur_std)
print(pspdur_min, ' to ',pspdur_max)
print('min fits')
#psp_dursmin=durfitmin(xfit[psp_dist])
psp_dursmin=durfitmin_f*xfit[psp_dist]
np.mean(psp_dursmin)
np.min(psp_dursmin)
np.max(psp_dursmin)
print('rise fits')
#psp_dursrise=durfitrise(xfit[psp_dist])
psp_dursrise=durfitrise_f*xfit[psp_dist]
np.mean(psp_dursrise)
np.min(psp_dursrise)
np.max(psp_dursrise)
print('max fits')
psp_dursmax=durfitmax_f*xfit[psp_dist]
np.mean(psp_dursmax)
np.min(psp_dursmax)
np.max(psp_dursmax)
############# plot 2 vs time
#exclude STEREO for better visibility
#plt.plot_date(icme_start_time_num[istbind],np.log10(mo_bmean[istbind]),'o',color='royalblue',markersize=markers,linestyle='-',linewidth=linew)
#plt.plot_date(icme_start_time_num[istaind],np.log10(mo_bmean[istaind]),'o',color='red',markersize=markers,linestyle='-',linewidth=linew)
#Wind
tfit=mdates.date2num(sunpy.time.parse_time('2009-04-01'))+np.arange(0,365*10)
t0=mdates.date2num(sunpy.time.parse_time('2009-01-01'))
#is a gaussian better?
#sigma=1000
#bfitmax=30
#mu=mdates.date2num(sunpy.time.parse_time('2013-01-01'))
#ygauss=1/(sigma*np.sqrt(2*np.pi))*np.exp(-((xfit-mu)**2)/(2*sigma**2) )
#normalize with 1/max(ygauss)
#plt.plot_date(xfit, ygauss*1/max(ygauss)*bfitmax,'o',color='mediumseagreen',linestyle='-',markersize=0, label='Earth fit')
#or is this better, like sunspot cycle?
#Hathaway 2015 equation 6 page 40
#average cycle sunspot number
A=100 #amplitude ##195 for sunspot
b=100*12 #56*12 for months to days
c=0.8
#4 free parameters A, b, c, t0
Fwind=A*(((tfit-t0)/b)**3) * 1/(np.exp((((tfit-t0)/b)**2))-c)
#plt.plot_date(tfit, Fwind,'o',color='mediumseagreen',linestyle='-',markersize=0, label='Earth fit')
#xaxis: 10 years, daily data point
xfit2=mdates.date2num(sunpy.time.parse_time('2007-01-01'))+np.arange(0,365*10)
#MESSENGER
sigma=1000
bfitmax=10
mu=mdates.date2num(sunpy.time.parse_time('2013-01-01'))
ygauss=1/(sigma*np.sqrt(2*np.pi))*np.exp(-((xfit2-mu)**2)/(2*sigma**2) )
#normalize with 1/max(ygauss)
#plt.plot_date(xfit, ygauss*1/max(ygauss)*bfitmax,'o',color='darkgrey',linestyle='-',markersize=0, label='Mercury fit')
#VEX
#inital guess
sigma=1000
bfitmax=20
mu=mdates.date2num(sunpy.time.parse_time('2013-01-01'))
ygauss=1/(sigma*np.sqrt(2*np.pi))*np.exp(-((xfit2-mu)**2)/(2*sigma**2) )
#normalize with 1/max(ygauss)
#plt.plot_date(xfit2, ygauss*1/max(ygauss)*bfitmax,'o',color='orange',linestyle='-',markersize=0, label='Venus fit')
#for Mars: reconstruct likely parameters if sigma is quite similar for all fits, take mean of those sigmas and adjust bfitmax as function of distance with power law)
#plot reconstructed function for Mars
bfitmax=40
#plt.plot_date(xfit2, Fwind,'o',color='steelblue',linestyle='--',markersize=0, label='Mars reconstr.')
#####plot
ax2 = plt.subplot2grid((2,1), (1, 0))
markers=6
linew=0
ax2.plot_date(icme_start_time_num[imesind],icme_durations[imesind],'o',color='darkgrey',markersize=markers,linestyle='-',linewidth=linew,label='MESSENGER')
ax2.plot_date(icme_start_time_num[ivexind],icme_durations[ivexind],'o',color='orange',markersize=markers,linestyle='-',linewidth=linew, label='Venus')
ax2.plot_date(icme_start_time_num[iwinind],icme_durations[iwinind],'o',color='mediumseagreen',markersize=markers, linestyle='-', linewidth=linew, label='Earth')
ax2.plot_date(icme_start_time_num[imavind],icme_durations[imavind],'o',color='steelblue',markersize=markers,linestyle='-',linewidth=linew, label='Mars')
#ax3 = ax2.twinx()
#ax3.plot_date(times1, spot, '-', color='black', alpha=0.5)
#ax3.set_ylabel('Sunspot number')
#limits solar min/rise/max, and means as horizontal lines for each sub interval
vlevel=60
plt.axvspan(minstart,minend, color='green', alpha=0.1)
plt.annotate('solar minimum',xy=(minstart+(minend-minstart)/2,vlevel),color='black', ha='center')
plt.annotate('<',xy=(minstart+10,vlevel),ha='left')
plt.annotate('>',xy=(minend-10,vlevel),ha='right')
plt.plot_date( [minstart,minend], [np.mean(icme_durations[iwinind_min]),np.mean(icme_durations[iwinind_min])], color='mediumseagreen', linestyle='-',markersize=0 )
plt.plot_date( [minstart,minend], [np.mean(icme_durations[ivexind_min]),np.mean(icme_durations[ivexind_min])], color='orange', linestyle='-', markersize=0)
plt.plot_date( [minstart,minend], [np.mean(icme_durations[imesind_min]),np.mean(icme_durations[imesind_min])], color='darkgrey', linestyle='-', markersize=0)
plt.axvspan(risestart,riseend, color='yellow', alpha=0.1)
plt.annotate('rising phase',xy=(risestart+(riseend-risestart)/2,vlevel),color='black', ha='center')
plt.annotate('<',xy=(risestart+10,vlevel),ha='left')
plt.annotate('>',xy=(riseend-10,vlevel),ha='right')
plt.plot_date( [risestart,riseend], [np.mean(icme_durations[iwinind_rise]),np.mean(icme_durations[iwinind_rise])], color='mediumseagreen', linestyle='-',markersize=0 )
plt.plot_date( [risestart,riseend], [np.mean(icme_durations[ivexind_rise]),np.mean(icme_durations[ivexind_rise])], color='orange', linestyle='-', markersize=0)
plt.plot_date( [risestart,riseend], [np.mean(icme_durations[imesind_rise]),np.mean(icme_durations[imesind_rise])], color='darkgrey', linestyle='-', markersize=0)
plt.axvspan(maxstart,maxend, color='red', alpha=0.1)
plt.annotate('solar maximum',xy=(maxstart+(maxend-maxstart)/2,vlevel),color='black', ha='center')
plt.annotate('<',xy=(maxstart+10,vlevel),ha='left')
plt.annotate('>',xy=(maxend,vlevel),ha='right')
plt.plot_date( [maxstart,maxend], [np.mean(icme_durations[iwinind_max]),np.mean(icme_durations[iwinind_max])], color='mediumseagreen', linestyle='-',markersize=0 )
plt.plot_date( [maxstart,maxend], [np.mean(icme_durations[ivexind_max]),np.mean(icme_durations[ivexind_max])], color='orange', linestyle='-', markersize=0)
plt.plot_date( [maxstart,maxend], [np.mean(icme_durations[imesind_max]),np.mean(icme_durations[imesind_max])], color='darkgrey', linestyle='-', markersize=0)
plt.ylim(0,70)
plt.xlim(mdates.date2num(sunpy.time.parse_time('2007-01-01')), mdates.date2num(sunpy.time.parse_time('2016-12-31')))
plt.ylabel('ICME duration D [hours]',fontsize=fsize)
plt.xlabel('year',fontsize=fsize)
plt.tight_layout()
plt.yticks(fontsize=fsize)
plt.xticks(fontsize=fsize)
plt.legend(loc=4,fontsize=fsize-1)
#panel labels
plt.figtext(0.01,0.98,'a',color='black', fontsize=fsize, ha='left',fontweight='bold')
plt.figtext(0.01,0.485,'b',color='black', fontsize=fsize, ha='left',fontweight='bold')
plt.show()
plt.savefig('plots_psp/icme_durations_distance_time_parker.pdf', dpi=300)
plt.savefig('plots_psp/icme_durations_distance_time_parker.png', dpi=300)
#results on durations
#################################################
#D
#
# print()
# print()
# print('--------------------------------------------------')
# print()
# print()
#
# print('DURATION ')
#
# print()
# print('MESSENGER +/-')
# print(round(np.mean(icme_durations[imercind]),1))
# print(round(np.std(icme_durations[imercind]),1))
#
# #print('min')
# #np.mean(icme_durations[imercind][imercind_min])
# #np.std(icme_durations[imercind][imercind_min])
# print('rise')
# print(round(np.mean(icme_durations[imesind][imercind_rise]),1))
# print(round(np.std(icme_durations[imercind][imercind_rise]),1))
# print('max')
# print(round(np.mean(icme_durations[imercind][imercind_max]),1))
# print(round(np.std(icme_durations[imercind][imercind_max]),1))
#
#
# print()
# print('Venus')
# print(round(np.mean(icme_durations[ivexind]),1))
# print(round(np.std(icme_durations[ivexind]),1))
# print('min')
# print(round(np.mean(icme_durations[ivexind][ivexind_min]),1))
# print(round(np.std(icme_durations[ivexind][ivexind_min]),1))
# print('rise')
# print(round(np.mean(icme_durations[ivexind][ivexind_rise]),1))
# print(round(np.std(icme_durations[ivexind][ivexind_rise]),1))
# print('max')
# print(round(np.mean(icme_durations[ivexind][ivexind_max]),1))
# print(round(np.std(icme_durations[ivexind][ivexind_max]),1))
#
# print()
# print('Earth')
# print(round(np.mean(icme_durations[iwinind]),1))
# print(round(np.std(icme_durations[iwinind]),1))
# print('min')
# print(round(np.mean(icme_durations[iwinind][iwinind_min]),1))
# print(round(np.std(icme_durations[iwinind][iwinind_min]),1))
# print('rise')
# print(round(np.mean(icme_durations[iwinind][iwinind_rise]),1))
# print(round(np.std(icme_durations[iwinind][iwinind_rise]),1))
# print('max')
# print(round(np.mean(icme_durations[iwinind][iwinind_max]),1))
# print(round(np.std(icme_durations[iwinind][iwinind_max]),1))
#
# print()
#
#
# #only declining phase
# print('MAVEN')
# print(round(np.mean(icme_durations[imavind]),1))
# print(round(np.std(icme_durations[imavind]),1))
#
#
#
#
#
#
#
#
###################################################################################
##################### (2) Bfield plot ICMECAT ############################
#-------------------------------------------------------------- Bfield plot
sns.set_context("talk")
#sns.set_style("darkgrid")
sns.set_style("ticks",{'grid.linestyle': '--'})
fig=plt.figure(2,figsize=(12,12 ))
#fig=plt.figure(2,figsize=(12,6 ))
fsize=15
ax1 = plt.subplot2grid((2,2), (0, 0))
#ax1 = plt.subplot2grid((1,2), (0, 0))
xfit=np.linspace(0,2,1000)
#power law fits for all events
bmaxfit=np.polyfit(np.log10(sc_heliodistance),np.log10(mo_bmax),1)
b=10**bmaxfit[1]
bmaxfitfun=b*(xfit**bmaxfit[0])
print('exponent for bmax fit:', bmaxfit[0])
bmeanfit=np.polyfit(np.log10(sc_heliodistance),np.log10(mo_bmean),1)
b=10**bmeanfit[1]
bmeanfitfun=b*(xfit**bmeanfit[0])
print('exponent for bmean fit:', bmeanfit[0])
################ dont take next 3 fits too seriously -> too few events for other distances during min for example (only VEX/Wind)
##fit with only minimum events
bmeanfit_min=np.polyfit(np.log10(sc_heliodistance[iallind_min]),np.log10(mo_bmean[iallind_min]),1)
bmeanfitfun_min=(10**bmeanfit_min[1])*(xfit**bmeanfit_min[0])
print('exponent for bmean_min fit:', bmeanfit_min[0])
##fit with only rising events
bmeanfit_rise=np.polyfit(np.log10(sc_heliodistance[iallind_rise]),np.log10(mo_bmean[iallind_rise]),1)
bmeanfitfun_rise=(10**bmeanfit_rise[1])*(xfit**bmeanfit_rise[0])
print('exponent for bmean_rise fit:', bmeanfit_rise[0])
##fit with only maximum events
bmeanfit_max=np.polyfit(np.log10(sc_heliodistance[iallind_max]),np.log10(mo_bmean[iallind_max]),1)
bmeanfitfun_max=(10**bmeanfit_max[1])*(xfit**bmeanfit_max[0])
print('exponent for bmean_max fit:', bmeanfit_max[0])
plt.plot(sc_heliodistance,mo_bmean,'o',color='black',markersize=5, alpha=0.7,label='$\mathregular{<B>}$')
plt.plot(xfit,bmeanfitfun,'-',color='black', lw=2, alpha=0.7,label='$\mathregular{<B> \\ fit}$')
plt.plot(sc_heliodistance,mo_bmax,'o',color='dodgerblue',markersize=5, alpha=0.7,label='$\mathregular{B_{max}}$')
plt.plot(xfit,bmaxfitfun,'-',color='dodgerblue', lw=2, alpha=0.7,label='$\mathregular{B_{max} \\ fit}$')
plt.text(1.1,120,'$\mathregular{<B> [nT]= 8.9 R[AU]^{-1.68}}$', fontsize=10)
plt.text(1.1,100,'$\mathregular{B_{max} [nT]= 12.3 R[AU]^{-1.73}}$', fontsize=10)
#plt.annotate('$Bmax[nT]={:.1f} R[AU]^{:.2f} $'.format(10**bmeanfit[1],bmeanfit[0]),xy=(0.9,80),fontsize=9)
#plt.annotate('$\mathregular{<B>}$: B[nT]={:.1f} R[AU]^{:.2f} '.format(bmeanfit[0],10**bmeanfit[1]),xy=(0.1,60),fontsize=11)
#plt.annotate('$\mathregular{B_{max}}$: B[nT]={:.1f} R[AU]^{:.2f} '.format(bmaxfit[0],10**bmaxfit[1]),xy=(0.1,60),fontsize=11)
#mars limits
plt.axvspan(np.min(pos.mars[0]),np.max(pos.mars[0]), color='orangered', alpha=0.2)
#plt.figtext(0.8,0.8,'Mars',color='orangered')
plt.axvspan(np.min(pos.mercury[0]),np.max(pos.mercury[0]), color='darkgrey', alpha=0.2)
#plt.figtext(0.25,0.8,'Mercury',color='darkgrey')
plt.axvspan(np.min(pos.venus[0]),np.max(pos.venus[0]), color='orange', alpha=0.2)
#plt.figtext(0.42,0.8,'Venus',color='orange')
plt.axvspan(np.min(pos.earth[0]),np.max(pos.earth[0]), color='mediumseagreen', alpha=0.2)
#plt.figtext(0.6,0.8,'Earth',color='mediumseagreen')
#solar probe plus 10 to 36 Rs close approaches
Rs_in_AU=7e5/149.5e6
plt.axvspan(Rs_in_AU*10,Rs_in_AU*36,color='magenta', alpha=0.2)
#plt.figtext(0.65,0.2,' D[h]={:.2f} R[AU] + {:.2f}'.format(durfit[0],durfit[1]))
plt.xlim(0,1.8)
plt.ylim(0,max(mo_bmax)+20)
plt.legend(loc=1,fontsize=fsize)
plt.xlabel('Heliocentric distance R [AU]',fontsize=fsize)
plt.ylabel('Magnetic field in MO B [nT]',fontsize=fsize)
plt.yticks(fontsize=fsize)
plt.xticks(fontsize=fsize)
#plt.grid()
######################## logarithmic plot with Sun
#for the bmean fit, append one value for the coronal field at 0.007 AU for 1.5 Rs with 1 Gauss or 10^5 nT
#or better
#patsourakos georgoulis 2016: 0.03 G for 10 Rs #10^5 nT is 1 Gauss
mo_bmean_sun=np.append(mo_bmean,10**5*0.03)
mo_bmax_sun=np.append(mo_bmax,10**5*0.03)
sc_heliodistance_sun=np.append(sc_heliodistance,10*Rs_in_AU)
ax3 = plt.subplot2grid((2,2), (0, 1))
bmeanfit_sun=np.polyfit(np.log10(sc_heliodistance_sun),np.log10(mo_bmean_sun),1)
b=10**bmeanfit_sun[1]
bmeanfitfun_sun=b*(xfit**bmeanfit_sun[0])
print('exponent for bmean fit sun:', bmeanfit_sun[0])
bmaxfit_sun=np.polyfit(np.log10(sc_heliodistance_sun),np.log10(mo_bmax_sun),1)
b=10**bmaxfit_sun[1]
bmaxfitfun_sun=b*(xfit**bmaxfit_sun[0])
print('exponent for bmean fit sun:', bmaxfit_sun[0])
plt.plot(sc_heliodistance_sun,np.log10(mo_bmean_sun),'o',color='black',markersize=5, alpha=0.7,label='$\mathregular{<B>}$')
plt.plot(xfit,np.log10(bmeanfitfun_sun),'-',color='black', lw=2, alpha=0.7,label='$\mathregular{<B> fit}$')
plt.plot(xfit,np.log10(bmaxfitfun_sun),'-',color='dodgerblue', lw=2, alpha=0.7,label='$\mathregular{B_{max} fit}$')
plt.ylim(0,6)
plt.text(1.1,3,'$\mathregular{<B> [nT]= 8.9 R[AU]^{-1.70}}$', fontsize=10)
plt.text(1.1,2.5,'$\mathregular{B_{max} [nT]= 12.3 R[AU]^{-1.79}}$', fontsize=10)
ax3.annotate('Mars', xy=(1.5,4), ha='center',fontsize=fsize-2)
ax3.annotate('PSP', xy=(0.12,4), ha='center',fontsize=fsize-2)
ax3.annotate('Mercury', xy=(0.38,4), ha='center',fontsize=fsize-2)
ax3.annotate('Venus', xy=(0.72,4), ha='center',fontsize=fsize-2)
ax3.annotate('Earth', xy=(1,4), ha='center',fontsize=fsize-2)
plt.legend(loc=1,fontsize=fsize)
plt.xlabel('Heliocentric distance R [AU]',fontsize=fsize)
plt.ylabel('Magnetic field in MO log(B) [nT]',fontsize=fsize)
plt.yticks(fontsize=fsize)
plt.xticks(fontsize=fsize)
#mars limits
plt.axvspan(np.min(pos.mars[0]),np.max(pos.mars[0]), color='orangered', alpha=0.2)
#plt.figtext(0.8,0.8,'Mars',color='orangered')
plt.axvspan(np.min(pos.mercury[0]),np.max(pos.mercury[0]), color='darkgrey', alpha=0.2)
#plt.figtext(0.25,0.8,'Mercury',color='darkgrey')
plt.axvspan(np.min(pos.venus[0]),np.max(pos.venus[0]), color='orange', alpha=0.2)
#plt.figtext(0.42,0.8,'Venus',color='orange')
plt.axvspan(np.min(pos.earth[0]),np.max(pos.earth[0]), color='mediumseagreen', alpha=0.2)
#plt.figtext(0.6,0.8,'Earth',color='mediumseagreen')
plt.xlim(0,1.8)
#PSP from 0.044 AU to 0.3 AU unknown territory
plt.axvspan(0.044,0.3, color='magenta', alpha=0.2)
#panel labels
plt.figtext(0.03,0.96,'a',color='black', fontsize=fsize, ha='left',fontweight='bold')
plt.figtext(0.515,0.96,'b',color='black', fontsize=fsize, ha='left',fontweight='bold')
plt.figtext(0.03,0.49,'c',color='black', fontsize=fsize, ha='left',fontweight='bold')
#sns.despine()
#plt.tight_layout()
print('results for bmean in MO and distance for PSP from 0.04 to 0.3 AU')
print('all fits')
psp_dist=np.where(np.logical_and(xfit < 0.3, xfit > 0.04))
#calculate function only with psp_dist values
psp_b=10**bmeanfit_sun[1]*(xfit[psp_dist]**bmeanfit_sun[0])
pspbmean_mean=np.mean(psp_b)
pspbmean_std=np.std(psp_b)
pspbmean_min=np.min(psp_b)
pspbmean_max=np.max(psp_b)
print('Parker predicted mean field in MO from 0.044 to 0.3 AU: mean +/ std, min, max')
print(pspbmean_mean, ' +/- ',pspbmean_std)
print(pspbmean_min, ' to ',pspbmean_max)
print('results for bmean in MO and distance for PSP from 0.04 to 0.3 AU')
print('all fits')
psp_dist=np.where(np.logical_and(xfit < 0.3, xfit > 0.04))
#calculate function only with psp_dist values
psp_b=10**bmaxfit_sun[1]*(xfit[psp_dist]**bmaxfit_sun[0])
pspbmax_mean=np.mean(psp_b)
pspbmax_std=np.std(psp_b)
pspbmax_min=np.min(psp_b)
pspbmax_max=np.max(psp_b)
print('Parker predicted max field in MO from 0.044 to 0.3 AU: mean +/ std, min, max')
print(pspbmax_mean, ' +/- ',pspbmax_std)
print(pspbmax_min, ' to ',pspbmax_max)