-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFRoDO.py
1549 lines (1273 loc) · 66.9 KB
/
FRoDO.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
# FRoDO.py
# Flux Rope Detection and Organization
'''
This set of modules is the Flux Rope Detection and Organization (FRoDO) code.
For ease of use, it can be executed directly from the command line with python3 FRoDO.py
For all additional details, consult the aptly named README file.
'''
# Import libraries
import matplotlib
matplotlib.use('Agg')
from matplotlib.pyplot import *
from matplotlib import gridspec
from matplotlib.transforms import Affine2D
from matplotlib.projections import PolarAxes
from mpl_toolkits.axisartist import angle_helper
from mpl_toolkits.axisartist.grid_finder import MaxNLocator
from mpl_toolkits.axisartist.floating_axes import GridHelperCurveLinear, FloatingSubplot
import mpl_toolkits.axisartist.floating_axes as floating_axes
import b_sim_netcdf
import os
import glob
import shutil
import re
import datetime
import pickle
import pandas as pd
import numpy as np
from numpy import pi
import scipy
import scipy.stats
from scipy.io import netcdf
from sunpy.physics.differential_rotation import diff_rot
import astropy.units as u
import configparser
# Read parameters from a configuration file
config = configparser.ConfigParser()
config.read('config.cfg')
datdir = config['paths']['datdir']
bdatprefix = config['paths']['bdatprefix']
adatprefix = config['paths']['adatprefix']
outdir = config['paths']['outdir']
frdim = np.array([np.int(config['array']['nlat']), np.int(config['array']['nlon'])])
maxlat = np.double(config['array']['maxlat'])
ref_sthresh = np.double(config['thresholds']['ref_sthresh'])
ref_ethresh = np.double(config['thresholds']['ref_ethresh'])
ref_bavg = np.double(config['thresholds']['ref_bavg'])
ref_havg = np.double(config['thresholds']['ref_havg'])
def prep():
'''
Computes magnetic vector potential values in the deVore gauge from input magnetic field data.
'''
# A quick announcement
print('Prepping input data...')
# Import prep libraries
from compA import compA
# Generate a list of files to search through
files = glob.glob(datdir+bdatprefix+'*.nc')
files.sort()
# Cycle through input data
for file in files:
# Extract the file frame string
frmstr = re.split(bdatprefix+'|\.', file)[-2]
# Compute and store magnetic vector potential
compA.compa(frmstr, datdir, bdatprefix, adatprefix)
def FRoDO():
'''
Detects and organizes time histories for magnetic flux ropes.
'''
# A quick announcement
print('Running FRoDO flux rope detection...')
# Remove any existing files
if os.path.exists(outdir) : shutil.rmtree(outdir)
# Create output directories if needed
if not os.path.exists(outdir) : os.mkdir(outdir)
if not os.path.exists(outdir + 'hist/') : os.mkdir(outdir + 'hist/')
# Generate a list of files to search through
bfrm_list = glob.glob(datdir + bdatprefix + '*.nc')
bfrm_list.sort()
afrm_list = glob.glob(datdir + adatprefix + '*.nc')
afrm_list.sort()
nfrm = len(bfrm_list)
# Define arrays to store surface maps
frmap = np.zeros(frdim, dtype=np.int16)
frcmap = np.zeros(frdim, dtype=np.int16)
frhlcy = np.zeros(frdim, dtype=np.double)
frrext = np.zeros(frdim, dtype=np.double)
br0 = np.zeros(frdim, dtype=np.double)
# Define an empty array of times
tarr = []
# Define a pixel area array (note the use of a sine latitude grid here)
rsun = 6.957e10
pix_area = 2. * np.pi * rsun**2 * (np.cos((90-maxlat)*np.pi/180.) - np.cos((90+maxlat)*np.pi/180.)) / (frdim[0] * frdim[1])
pix_area_pol = 4. * np.pi * rsun**2 / (frdim[0] * frdim[1])
# Define arrays for the storage of flux rope time histories
fr_area = np.array([np.nan])
fr_time = np.array([np.nan])
fr_dur = np.array([np.nan])
fr_mhlcy = np.array([np.nan])
fr_nhlcy = np.array([np.nan])
fr_sflux = np.array([np.nan])
fr_uflux = np.array([np.nan])
fr_mlat = np.array([np.nan])
fr_rext = np.array([np.nan])
fr_mrext = np.array([np.nan])
frh_area = list([np.nan])
frh_time = list([np.nan])
frh_mhlcy = list([np.nan])
frh_nhlcy = list([np.nan])
frh_sflux = list([np.nan])
frh_uflux = list([np.nan])
frh_rext = list([np.nan])
frh_mrext = list([np.nan])
# Define arrays to store threshold levels
sthreshs = np.zeros(nfrm, dtype=np.double)
ethreshs = np.zeros(nfrm, dtype=np.double)
# Define some loop counting information
dcount = 0
prntend = '\r'
# Begin cycling through time frames
for cfrm in bfrm_list:
# Define some timing
time0 = datetime.datetime.now()
csfrm = re.split(bdatprefix+'|\.', cfrm)[-2]
# Read magnetic field data into memory
b = b_sim_netcdf.SphB_sim(datdir + bdatprefix + csfrm + '.nc', datdir + adatprefix + csfrm + '.nc', 128,128,128)
d = netcdf.netcdf_file(datdir + bdatprefix + csfrm + '.nc', 'r')
r = d.variables['r'][:].copy()
th = d.variables['th'][:].copy()
ph = d.variables['ph'][:].copy()
br = d.variables['br'][:,:,:].copy()
bth = d.variables['bth'][:,:,:].copy()
bph = d.variables['bph'][:,:,:].copy()
cdate = d.date
ctarr = datetime.datetime.strptime(bytes.decode(cdate),"%Y%b%d_%H%M")
cjuld = np.double(ctarr.toordinal()+1721425.0)
tarr.append(ctarr)
d.close()
# Read vector magnetic potential data into memory
d = netcdf.netcdf_file(datdir + adatprefix + csfrm + '.nc', 'r')
ar = d.variables['ar'][:,:,:].copy()
ath = d.variables['ath'][:,:,:].copy()
aph = d.variables['aph'][:,:,:].copy()
d.close()
# Define some coordinate information
lons, lats = np.meshgrid(ph*360./(2*pi), th*360./(2*pi)-90.)
frlon = np.linspace((2*pi/(2*frdim[1])), (2*pi)-(2*pi/(2*frdim[1])), num=frdim[1], dtype=np.double)
frlat = np.linspace(-np.sin(maxlat*np.pi/180.)+(1/(2*frdim[0])), np.sin(maxlat*np.pi/180.)-(1/(2*frdim[0])), num=frdim[0], dtype=np.double)
frlat_pol = np.linspace(-1+(1/(2*frdim[0])), 1-(1/(2*frdim[0])), num=frdim[0], dtype=np.double)
frlat_edge = frlat - abs(frlat[0] - frlat[1])/2.
frlon_edge = frlon - abs(frlon[0] - frlon[1])/2.
# Interpolate the magnetic field array to the output grid
f0b = scipy.interpolate.interp2d(lons[0,:]*2*pi/360, np.sin(lats[:,0]*2*pi/360), np.rot90(br[:,:,0]), kind='cubic')
br0 = f0b(frlon, frlat)
br0_pol = f0b(frlon, frlat_pol)
# Trace a uniform set of fieldlines for detection
afl_r = np.zeros(frdim[0]*frdim[1])+1.0
afl_ph, afl_th = np.meshgrid(frlon, frlat)
afl_th = np.ndarray.flatten(afl_th)
afl_ph = np.ndarray.flatten(afl_ph)
afl_th = np.arcsin(-1*afl_th)+(pi/2)
hlcy, fl = b.fieldlines_hlcy(afl_r, afl_th, afl_ph)
# Begin by computing mappings of fieldline helicity and radial extent
frhlcy[:,:] = 0
frrext[:,:] = 0
for ifl in np.arange(len(hlcy)):
alfpr1 = fl[ifl][0][0]
alfpr2 = fl[ifl][0][-1]
alfpth1 = np.sin(fl[ifl][1][0] + pi/2)
alfpth2 = np.sin(fl[ifl][1][-1] + pi/2)
alfpph1 = fl[ifl][2][0]
alfpph2 = fl[ifl][2][-1]
alg1 = fl[ifl][0][0] < 1.2
alg2 = fl[ifl][0][-1] < 1.2
flrext = fl[ifl][0].max()
why1 = np.where((frlat_edge < alfpth1) & np.roll((frlat_edge > alfpth1),-1))[0]
whx1 = np.where((frlon_edge < alfpph1) & np.roll((frlon_edge > alfpph1),-1))[0]
why2 = np.where((frlat_edge < alfpth2) & np.roll((frlat_edge > alfpth2),-1))[0]
whx2 = np.where((frlon_edge < alfpph2) & np.roll((frlon_edge > alfpph2),-1))[0]
if (len(whx1 == 1))&(len(why1) == 1)&(alg1):
if abs(frhlcy[why1, whx1]) < abs(hlcy[ifl]):
frhlcy[why1, whx1] = hlcy[ifl]
if abs(frrext[why1, whx1]) < flrext:
frrext[why1, whx1] = flrext
if (len(whx2 == 1))&(len(why2) == 1)&(alg2):
if abs(frhlcy[why2, whx2]) < abs(hlcy[ifl]):
frhlcy[why2, whx2] = hlcy[ifl]
if abs(frrext[why2, whx2]) < flrext:
frrext[why2, whx2] = flrext
# Begin the process of seeding flux rope footprints within this mapping
havg = abs(frhlcy).mean()
sthresh = (havg / ref_havg) * ref_sthresh
ethresh = (havg / ref_havg) * ref_ethresh
sthreshs[dcount] = sthresh
ethreshs[dcount] = ethresh
# Compute a set of core footprint regions
sdfp = abs(frhlcy) > sthresh
s = [[1,1,1],[1,1,1],[1,1,1]]
sdfp_lab = (scipy.ndimage.label(sdfp, s))[0]
for j in np.arange(sdfp_lab.max())+1:
wharr = np.where(sdfp_lab == j)
if len(wharr[0]) < 10:
sdfp_lab[wharr] = 0
sdfp_lab = (scipy.ndimage.label(sdfp_lab != 0, s))[0]
# Compute a set of extent footprint regions
expfp = abs(frhlcy) > ethresh
expfp_lab = (scipy.ndimage.label(expfp, s))[0]
for j in np.arange(expfp_lab.max())+1:
wharr = np.where(expfp_lab == j)
if len(wharr[0]) < 10:
expfp_lab[wharr] = 0
# Merge the core and extent regions
fp_lab = np.zeros([len(frlat), len(frlon)], dtype='int32')
for fri in np.arange(sdfp_lab.max())+1:
fp_lab[np.where(expfp_lab == expfp_lab[np.where(sdfp_lab == fri)][0])] = 1
# Separate adjacent regions with opposite sign of helicity
frpos_lab = (scipy.ndimage.label((fp_lab!=0)*frhlcy>0, s))[0]
for j in np.arange(frpos_lab.max())+1:
wharr = np.where(frpos_lab == j)
if len(wharr[0]) < 10:
frpos_lab[wharr] = 0
frpos_lab = (scipy.ndimage.label(frpos_lab != 0, s))[0]
frneg_lab = (scipy.ndimage.label((fp_lab!=0)*frhlcy<0, s))[0]
for j in np.arange(frneg_lab.max())+1:
wharr = np.where(frneg_lab == j)
if len(wharr[0]) < 10:
frneg_lab[wharr] = 0
frneg_lab = (scipy.ndimage.label(frneg_lab != 0, s))[0]
frmap[:,:] = (frpos_lab+frneg_lab.max())*(frpos_lab!=0) + frneg_lab
# Compute a pixel shift amount to account for differential rotation
if dcount == 0:
dtime = 1
else:
dtime0 = tarr[dcount] - tarr[dcount - 1]
dtime = dtime0.days + (dtime0.seconds / 86400.)
drot = diff_rot(dtime * u.day, np.arcsin(frlat)*180/pi * u.deg, rot_type='snodgrass')
drot = drot - drot.max()
drot = np.array(np.around((drot/u.deg * 180/pi) * (frlon[1]-frlon[0]))).astype(np.int)
frnlab = np.zeros(frdim, dtype=np.int16)
# Compare flux rope maps with prior times to label histories
if dcount != 0:
frlab = np.copy(frmap)
for r in np.arange(frdim[0]):
frmap0[r,:] = np.roll(frmap0[r,:], drot[r])
frhlcy0[r,:] = np.roll(frhlcy0[r,:], drot[r])
# Label and iterate through flux rope footprint regions
#for fr in np.arange(frlab.max())+1:
for fr in np.unique(frlab):
if fr != 0:
frwhr = np.where(frlab == fr)
frarr = frmap0[frwhr]
hlcyarr0 = frhlcy0[frwhr]
hlcyarr1 = frhlcy[frwhr]
hlcycheck = (np.sign(hlcyarr0.mean()) * np.sign(hlcyarr1.mean())) == 1
frsts = scipy.stats.mode(frarr)
if (float(frsts[1][0]) / len(frarr) > 0.5) & (hlcycheck) & (frsts[0][0] != 0):
frnlab[frwhr] = frsts[0][0]
else:
frnlab[frwhr] = regmx + 1
regmx = regmx + 1
if frnlab.max() != 0 : regmx = frnlab.max()
frmap = np.copy(frnlab)
else:
regmx = frmap.max()
# Record some statistics
for frcur in np.unique(frmap[frmap!=0]):
# Output location information
frwhr = np.where(frmap == frcur)
if len(fr_area) <= frcur:
fr_area = np.append(fr_area, len(frwhr[0]) * pix_area)
fr_time = np.append(fr_time, dcount)
fr_mlat = np.append(fr_mlat, np.mean(frlat[frwhr[0]]))
fr_dur = np.append(fr_dur, dtime)
fr_mhlcy = np.append(fr_mhlcy, (frhlcy[frwhr] * np.abs(br0[frwhr]) * rsun**2 * pix_area).mean())
fr_nhlcy = np.append(fr_nhlcy, (frhlcy[frwhr] * np.abs(br0[frwhr]) * rsun**2 * pix_area).sum())
fr_sflux = np.append(fr_sflux, (br0[frwhr] * pix_area).sum())
fr_uflux = np.append(fr_uflux, abs(br0[frwhr] * pix_area).sum())
fr_rext = np.append(fr_rext, frrext[frwhr].mean())
fr_mrext = np.append(fr_mrext, frrext[frwhr].max())
frh_area.append(np.array([len(frwhr[0]) * pix_area]))
frh_time.append(np.array([dcount]))
frh_mhlcy.append(np.array([(frhlcy[frwhr] * np.abs(br0[frwhr]) * rsun**2 * pix_area).mean()]))
frh_nhlcy.append(np.array([(frhlcy[frwhr] * np.abs(br0[frwhr]) * rsun**2 * pix_area).sum()]))
frh_sflux.append(np.array([(br0[frwhr] * pix_area).sum()]))
frh_uflux.append(np.array([abs(br0[frwhr] * pix_area).sum()]))
frh_rext.append(np.array([frrext[frwhr].mean()]))
frh_mrext.append(np.array([frrext[frwhr].max()]))
else:
cflux = abs(br0[frwhr] * pix_area).sum()
fr_dur[frcur] = fr_dur[frcur] + dtime
frh_area[frcur] = np.append(frh_area[frcur], len(frwhr[0]) * pix_area)
frh_time[frcur] = np.append(frh_time[frcur], dcount)
frh_mhlcy[frcur] = np.append(frh_mhlcy[frcur], (frhlcy[frwhr] * np.abs(br0[frwhr]) * rsun**2 * pix_area).mean())
frh_nhlcy[frcur] = np.append(frh_nhlcy[frcur], (frhlcy[frwhr] * np.abs(br0[frwhr]) * rsun**2 * pix_area).sum())
frh_sflux[frcur] = np.append(frh_sflux[frcur], (br0[frwhr] * pix_area).sum())
frh_uflux[frcur] = np.append(frh_uflux[frcur], abs(br0[frwhr] * pix_area).sum())
frh_rext[frcur] = np.append(frh_rext[frcur], frrext[frwhr].mean())
frh_mrext[frcur] = np.append(frh_mrext[frcur], frrext[frwhr].max())
if fr_uflux[frcur] < cflux:
fr_area[frcur] = len(frwhr[0]) * pix_area
fr_time[frcur] = dcount
fr_mlat[frcur] = np.mean(frlat[frwhr[0]])
fr_mhlcy[frcur] = (frhlcy[frwhr] * np.abs(br0[frwhr]) * rsun**2 * pix_area).mean()
fr_nhlcy[frcur] = (frhlcy[frwhr] * np.abs(br0[frwhr]) * rsun**2 * pix_area).sum()
fr_sflux[frcur] = (br0[frwhr] * pix_area).sum()
fr_uflux[frcur] = abs(br0[frwhr] * pix_area).sum()
fr_rext[frcur] = frrext[frwhr].mean()
fr_mrext[frcur] = frrext[frwhr].max()
# Calculate footprint connectivity, and an index of flux rope fieldlines
#frcmap = np.zeros(frdim, dtype=np.int32)
#fr_fl = np.zeros(len(fl))
#for ifl in np.arange(len(hlcy)):
# alfpr1 = fl[ifl][0][0]
# alfpr2 = fl[ifl][0][-1]
# alfpth1 = np.sin(fl[ifl][1][0] + pi/2)
# alfpth2 = np.sin(fl[ifl][1][-1] + pi/2)
# alfpph1 = fl[ifl][2][0]
# alfpph2 = fl[ifl][2][-1]
#
# alg1 = fl[ifl][0][0] < 1.2
# alg2 = fl[ifl][0][-1] < 1.2
#
# why1 = np.where((frlat_edge < alfpth1) & np.roll((frlat_edge > alfpth1),-1))[0]
# whx1 = np.where((frlon_edge < alfpph1) & np.roll((frlon_edge > alfpph1),-1))[0]
# why2 = np.where((frlat_edge < alfpth2) & np.roll((frlat_edge > alfpth2),-1))[0]
# whx2 = np.where((frlon_edge < alfpph2) & np.roll((frlon_edge > alfpph2),-1))[0]
#
# ## Map out the pixel connectivity
# if (len(whx1 == 1))&(len(why1) == 1)&(frmap[why1,whx1] != 0):
# if (len(whx2 == 1))&(len(why2) == 1):
# frcmap[why1,whx1] = frmap[why2[0], whx2[0]]
# fr_fl[ifl] = frmap[why1, whx1]
# if (len(whx2 == 1))&(len(why2) == 1)&(frmap[why2,whx2] != 0):
# if (len(whx1 == 1))&(len(why1) == 1):
# frcmap[why2,whx2] = frmap[why1[0], whx1[0]]
# fr_fl[ifl] = frmap[why2, whx2]
# Store flux rope and helicity mapping for future use
frmap0 = np.copy(frmap)
frhlcy0 = np.copy(frhlcy)
# Output appropriate arrays to disk
outfile = netcdf.netcdf_file(outdir + 'fr-' + csfrm + '.nc', 'w')
outfile.history = 'FRoDO flux rope data'
outfile.createDimension('lat', frdim[0])
outfile.createDimension('lon', frdim[1])
out_frmap = outfile.createVariable('frmap', np.int16, ('lat', 'lon'))
out_frmap[:] = frmap
out_frmap.units = 'Flux rope footprint label (unitless)'
#out_frcmap = outfile.createVariable('frcmap', np.int16, ('lat', 'lon'))
#out_frcmap[:] = frcmap
#out_frcmap.units= 'Flux rope footprint connectivity label (unitless)'
out_frhlcy = outfile.createVariable('frhlcy', np.double, ('lat', 'lon'))
out_frhlcy[:] = frhlcy
out_frhlcy.units = 'Field line cumulative helicity map (Mx cm^-2)'
out_frrext = outfile.createVariable('frrext', np.double, ('lat', 'lon'))
out_frrext[:] = frrext
out_frrext.units = 'Field line maximum radial extent (R_sun)'
out_br0 = outfile.createVariable('br0', np.double, ('lat', 'lon'))
out_br0[:] = br0
out_br0.units = 'Radial magnetic flux density at 1.0 R_sun (G)'
out_br0_pol = outfile.createVariable('br0_pol', np.double, ('lat', 'lon'))
out_br0_pol[:] = br0_pol
out_br0_pol.units = 'Radial magnetic flux density at 1.0 R_sun (G)'
out_lat = outfile.createVariable('lat', np.float32, ('lat',))
out_lat[:] = frlat
out_lon = outfile.createVariable('lon', np.float32, ('lon',))
out_lon[:] = frlon
outfile.close()
# Diagnostic readouts!
time1 = datetime.datetime.now()
if dcount == 0:
timedel = (time1 - time0)
else:
timedel = ((time1 - time0) + timedel) / 2
timeeta = (nfrm - (dcount+1)) * timedel + time1
if dcount == (len(bfrm_list) - 1) : prntend = '\n'
print('Frame ' + '%05.f'%(dcount+1) + ' / ' + '%05.f'%nfrm + ' - ' + str(timedel) + 's - ETA ' + str(timeeta), end=prntend)
# Advance the timing index
dcount = dcount + 1
# Create a filter to map those flux ropes that meet the radial extent criteria
dtarr = tarr - np.roll(tarr,1)
dtarr[0] = datetime.timedelta(1)
for i in np.arange(len(dtarr)): dtarr[i] = dtarr[i].days
fr_hdrext = np.zeros(len(fr_dur), dtype=np.double)
for fri in np.arange(1,len(fr_dur)):
fr_hdrext[fri] = dtarr[(np.where(frh_rext[fri] > 1.5)[0])].sum()
fr_rfrg = np.where((fr_hdrext[1:] / fr_dur[1:]) < 0.5)[0] + 1
# Create a filter to remove flux ropes with less than a single day of time history
fr_dfrg = np.where((fr_dur[1:] > 1) & (np.isfinite(fr_dur[1:])))[0]+1
# Merge these into a single filtered index
fr_frg = np.intersect1d(fr_rfrg, fr_dfrg)
# Begin output to file
# Output compatible data to a single netcdf archive
outfile = netcdf.netcdf_file(outdir + 'hist/fr-hist.nc', 'w')
outfile.history = 'FRoDO flux rope histories'
outfile.createDimension('frnum', len(fr_time))
outfile.createDimension('frgnum', len(fr_frg))
outfile.createDimension('time', len(bfrm_list))
out_fr_frg = outfile.createVariable('fr_frg', np.int32, ('frgnum',))
out_fr_frg[:] = fr_frg
out_fr_frg.units = 'Filtered list of flux rope identifiers'
out_ethreshs = outfile.createVariable('ethreshs', np.double, ('time',))
out_ethreshs[:] = ethreshs
out_ethreshs.units = 'Detection extent threshold values'
out_sthreshs = outfile.createVariable('sthreshs', np.double, ('time',))
out_sthreshs[:] = sthreshs
out_sthreshs.units = 'Detection core threshold values'
out_fr_area = outfile.createVariable('fr_area', np.double, ('frnum',))
out_fr_area[:] = fr_area
out_fr_area.units = 'Footprint area (cm^2)'
out_fr_time = outfile.createVariable('fr_time', np.double, ('frnum',))
out_fr_time[:] = fr_time
out_fr_time.units = 'Flux rope timing frame ()'
out_fr_dur = outfile.createVariable('fr_dur', np.double, ('frnum',))
out_fr_dur[:] = fr_dur
out_fr_dur.units = 'Duration (days)'
out_fr_mhlcy = outfile.createVariable('fr_mhlcy', np.double, ('frnum',))
out_fr_mhlcy[:] = fr_mhlcy
out_fr_mhlcy.units = 'Footprint mean helicity (Mx^2)'
out_fr_nhlcy = outfile.createVariable('fr_nhlcy', np.double, ('frnum',))
out_fr_nhlcy[:] = fr_nhlcy
out_fr_nhlcy.units = 'Footprint net helicity magnitude (Mx^2)'
out_fr_sflux = outfile.createVariable('fr_sflux', np.double, ('frnum',))
out_fr_sflux[:] = fr_sflux
out_fr_sflux.units = 'Footprint signed magnetic flux (Mx)'
out_fr_uflux = outfile.createVariable('fr_uflux', np.double, ('frnum',))
out_fr_uflux[:] = fr_uflux
out_fr_uflux.units = 'Footprint unsigned magnetic flux (Mx)'
out_fr_rext = outfile.createVariable('fr_rext', np.double, ('frnum',))
out_fr_rext[:] = fr_rext
out_fr_rext.units = 'Mean radial extent (R_sun)'
out_fr_mrext = outfile.createVariable('fr_mrext', np.double, ('frnum',))
out_fr_mrext[:] = fr_mrext
out_fr_mrext.units = 'Maximum radial extent (R_sun)'
out_fr_mlat = outfile.createVariable('fr_mlat', np.double, ('frnum',))
out_fr_mlat[:] = fr_mlat
out_fr_mlat.units = ''
outfile.close()
# Output any completed time-series variables
np.save(outdir + '/hist/fr-tarr.npy', tarr)
outfile = open(outdir + '/hist/h-frh-area.pkl', 'wb')
pickle.dump(frh_area, outfile)
outfile.close()
outfile = open(outdir + '/hist/h-frh-time.pkl', 'wb')
pickle.dump(frh_time, outfile)
outfile.close()
outfile = open(outdir + '/hist/h-frh-mhlcy.pkl', 'wb')
pickle.dump(frh_mhlcy, outfile)
outfile.close()
outfile = open(outdir + '/hist/h-frh-nhlcy.pkl', 'wb')
pickle.dump(frh_nhlcy, outfile)
outfile.close()
outfile = open(outdir + '/hist/h-frh-sflux.pkl', 'wb')
pickle.dump(frh_sflux, outfile)
outfile.close()
outfile = open(outdir + '/hist/h-frh-uflux.pkl', 'wb')
pickle.dump(frh_uflux, outfile)
outfile.close()
outfile = open(outdir + '/hist/h-frh-rext.pkl', 'wb')
pickle.dump(frh_rext, outfile)
outfile.close()
outfile = open(outdir + '/hist/h-frh-mrext.pkl', 'wb')
pickle.dump(frh_mrext, outfile)
outfile.close()
def erupt():
'''
Detects and flags erupting flux rope signatures.
'''
# A quick announcement
print('Running FRoDO flux rope eruption detection...')
# Generate a list of files to search through
bfrm_list = glob.glob(datdir + bdatprefix + '*.nc')
bfrm_list.sort()
afrm_list = glob.glob(datdir + adatprefix + '*.nc')
afrm_list.sort()
nfrm = len(bfrm_list)
# Initialize arrays for storage
tarr = []
fr_elab = np.array([])
fr_efpt = np.array([])
fr_etarr = np.array([])
phfl0 = np.zeros(frdim[0]*frdim[1],dtype=np.double)
thfl0 = np.zeros(frdim[0]*frdim[1],dtype=np.double)
rfl0 = np.zeros(frdim[0]*frdim[1],dtype=np.double)
phfl1 = np.zeros(frdim[0]*frdim[1],dtype=np.double)
thfl1 = np.zeros(frdim[0]*frdim[1],dtype=np.double)
rfl1 = np.zeros(frdim[0]*frdim[1],dtype=np.double)
# Begin cycling through these frames
dcount = 0
prntend = '\r'
for cfrm in bfrm_list:
# Define some timing
time0 = datetime.datetime.now()
csfrm = re.split(bdatprefix+'|\.', cfrm)[-2]
# Read original data into memory
b = b_sim_netcdf.SphB_sim(datdir + bdatprefix + csfrm + '.nc', datdir + adatprefix + csfrm + '.nc', 128,128,128)
d = netcdf.netcdf_file(datdir + bdatprefix + csfrm + '.nc', 'r')
r = d.variables['r'][:].copy()
th = d.variables['th'][:].copy()
ph = d.variables['ph'][:].copy()
br = d.variables['br'][:,:,:].copy()
bth = d.variables['bth'][:,:,:].copy()
bph = d.variables['bph'][:,:,:].copy()
cdate = d.date
ctarr = datetime.datetime.strptime(bytes.decode(cdate),"%Y%b%d_%H%M")
cjuld = np.double(ctarr.toordinal()+1721425.0)
tarr.append(ctarr)
# Close netCDF files
d.close()
# Read processed data into memory
d = netcdf.netcdf_file(outdir + 'fr-' + csfrm + '.nc', 'r')
frhlcy = d.variables['frhlcy'][:,:].copy()
frmap = d.variables['frmap'][:,:].copy()
d.close()
# Read the previous timeframe into memory for comparison
if dcount != 0:
d = netcdf.netcdf_file(outdir + 'fr-' + csfrm1 + '.nc', 'r')
frmap0 = d.variables['frmap'][:,:].copy()
d.close()
# Define some coordinate information
lons, lats = np.meshgrid(ph*360./(2*pi), th*360./(2*pi)-90.)
frlon = np.linspace((2*pi/(2*frdim[1])), (2*pi)-(2*pi/(2*frdim[1])), num=frdim[1], dtype=np.double)
frlat = np.linspace(-np.sin(maxlat*np.pi/180.)+(1/(2*frdim[0])), np.sin(maxlat*np.pi/180.)-(1/(2*frdim[0])), num=frdim[0], dtype=np.double)
frlat_pol = np.linspace(-1+(1/(2*frdim[0])), 1-(1/(2*frdim[0])), num=frdim[0], dtype=np.double)
frlat_wcell = abs(frlat[0] - frlat[1])
frlon_wcell = abs(frlon[0] - frlon[1])
frlat_edge = frlat - abs(frlat[0] - frlat[1])/2.
frlon_edge = frlon - abs(frlon[0] - frlon[1])/2.
# Interpolate some of this data to the output grid
bh_intarr = np.rot90((bth[:,:,-1]**2 + bph[:,:,-1]**2)**(0.5))
f0bh = scipy.interpolate.interp2d(lons[0,:]*2*pi/360, np.sin(lats[:,0]*2*pi/360), bh_intarr, kind='cubic')
bht = f0bh(frlon, frlat)
bht_pol = f0bh(frlon, frlat_pol)
# Trace a set of fieldlines down from the simulation upper boundary
afl_r = np.zeros(frdim[0]*frdim[1])+2.5
afl_ph, afl_th = np.meshgrid(frlon, frlat)
afl_th = np.ndarray.flatten(afl_th)
afl_ph = np.ndarray.flatten(afl_ph)
afl_th = np.arcsin(-1*afl_th)+(pi/2)
hlcy, fl = b.fieldlines_hlcy(afl_r, afl_th, afl_ph)
## Generate an array of field-line helicity
hlcy_tb = np.zeros([frdim[0], frdim[1]], dtype='float64')
for fl_ind in np.arange(len(hlcy)):
alfpr1 = fl[fl_ind][0][0]
alfpr2 = fl[fl_ind][0][-1]
alfpth1 = np.sin(fl[fl_ind][1][0] + pi/2)
alfpth2 = np.sin(fl[fl_ind][1][-1] + pi/2)
alfpph1 = fl[fl_ind][2][0]
alfpph2 = fl[fl_ind][2][-1]
alg1 = fl[fl_ind][0][0] > 2.4
alg2 = fl[fl_ind][0][-1] > 2.4
why1 = np.where((frlat_edge < alfpth1) & np.roll((frlat_edge > alfpth1),-1))[0]
whx1 = np.where((frlon_edge < alfpph1) & np.roll((frlon_edge > alfpph1),-1))[0]
why2 = np.where((frlat_edge < alfpth2) & np.roll((frlat_edge > alfpth2),-1))[0]
whx2 = np.where((frlon_edge < alfpph2) & np.roll((frlon_edge > alfpph2),-1))[0]
if (len(whx1 == 1))&(len(why1) == 1)&(alg1):
if abs(hlcy_tb[why1, whx1]) < abs(hlcy[fl_ind]):
hlcy_tb[why1, whx1] = hlcy[fl_ind]
if (len(whx2 == 1))&(len(why2) == 1)&(alg2):
if abs(hlcy_tb[why2, whx2]) < abs(hlcy[fl_ind]):
hlcy_tb[why2, whx2] = hlcy[fl_ind]
# Compute a few parameters for thresholding
bavg = abs(bht).mean()
havg = abs(frhlcy).mean()
shthresh = (havg / 0.26648107322354925) * 1.00
ehthresh = (havg / 0.26648107322354925) * 0.70
sbthresh = (bavg / 0.027634660528377285) * 0.30
ebthresh = (bavg / 0.027634660528377285) * 0.10
# Sort out regions with a reasonable overlap of horizontal magnetic field and helicity
regb = scipy.ndimage.label(bht > ebthresh)[0]
# Filter out small regions
for r in np.arange(regb.max())+1:
wregb = np.where(regb == r)
if len(wregb[0]) < 100:
regb[wregb] = 0
if abs(hlcy_tb[wregb]).max() < ehthresh:
regb[wregb] = 0
# Relabel regions
regb = scipy.ndimage.label(regb!=0)[0]
# Grab a mapping of fieldline start/end points
for fli in np.arange(len(fl)):
phfl0[fli] = fl[fli][2][0]
phfl1[fli] = fl[fli][2][-1]
thfl0[fli] = fl[fli][1][0]
thfl1[fli] = fl[fli][1][-1]
rfl0[fli] = fl[fli][0][0]
rfl1[fli] = fl[fli][0][-1]
# Define a list of fieldlines that fall within this region
regls0 = np.array([], dtype=np.int)
regls1 = np.array([], dtype=np.int)
regfl0 = np.array([], dtype=np.int)
regfl1 = np.array([], dtype=np.int)
# Alternatively, define a set of fieldlines just by grabbing the line intersecting closest to the cell center
# Find the corresponding fieldlines contained within, and trace back to origins
for r in np.arange(regb.max())+1:
wregb = np.where(regb == r)
for rci in np.arange(len(wregb[0])):
rlat = wregb[0][rci]
rlon = wregb[1][rci]
fltb0 = np.where(rfl0 > 2.4)
fltb1 = np.where(rfl1 > 2.4)
londff0 = abs(phfl0[fltb0] - frlon[rlon])
latdff0 = abs(thfl0[fltb0] - (np.arcsin(-1*frlat[rlat])+(pi/2)))
londff1 = abs(phfl1[fltb1] - frlon[rlon])
latdff1 = abs(thfl1[fltb1] - (np.arcsin(-1*frlat[rlat])+(pi/2)))
# Note that this 'distance' approximation computed here is only for comparison. A true distance calculation could be substituted here, when consolidating codes together.
fldist0 = np.sqrt(londff0**2 + latdff0**2)
fldist1 = np.sqrt(londff1**2 + latdff1**2)
wmd0 = np.where(fldist0 == np.min(fldist0))[0]
wmd1 = np.where(fldist1 == np.min(fldist1))[0]
if ((londff0[wmd0] < frlon_wcell) & (latdff0[wmd0] < frlat_wcell)):
regls0 = np.append(regls0,r)
regfl0 = np.append(regfl0, np.where(phfl0 == phfl0[fltb0][wmd0])[0][0])
#regfl0 = np.append(regfl0, np.where(phfl0 == phfl0[fltb0][where(fldist0 == mindist0)])[0][0])
# Go ahead here and assign this value to the cell below? Will need to compute coordinates?
if ((londff1[wmd1] < frlon_wcell) & (latdff1[wmd1] < frlat_wcell)):
regls1 = np.append(regls1,r)
regfl1 = np.append(regfl1, np.where(phfl1 == phfl1[fltb1][wmd1])[0][0])
#regfl1 = np.append(regfl1, np.where(phfl1 == phfl1[fltb1][where(fldist1 == mindist1)])[0][0])
# To find corresponding footpoint locations, simply invert the indicies and check for radius value
# Create a linked map at 1R_sun to contain footprints of erupting flux ropes
regbb = np.zeros([frdim[0], frdim[1]], dtype=np.double)
regc = 0
for fl_ind in regfl0:
alfpr1 = fl[fl_ind][0][0]
alfpr2 = fl[fl_ind][0][-1]
alfpth1 = np.sin(fl[fl_ind][1][0] + pi/2)
alfpth2 = np.sin(fl[fl_ind][1][-1] + pi/2)
alfpph1 = fl[fl_ind][2][0]
alfpph2 = fl[fl_ind][2][-1]
alg1 = fl[fl_ind][0][0] < 1.2
alg2 = fl[fl_ind][0][-1] < 1.2
if alg1:
why1 = np.where((frlat_edge < alfpth1) & np.roll((frlat_edge > alfpth1),-1))[0]
whx1 = np.where((frlon_edge < alfpph1) & np.roll((frlon_edge > alfpph1),-1))[0]
if (len(whx1) == 1)&(len(why1) == 1)&(alg1):
regbb[why1, whx1] = regls0[regc]
if alg2:
why2 = np.where((frlat_edge < alfpth2) & np.roll((frlat_edge > alfpth2),-1))[0]
whx2 = np.where((frlon_edge < alfpph2) & np.roll((frlon_edge > alfpph2),-1))[0]
if (len(whx2) == 1)&(len(why2) == 1)&(alg2):
regbb[why2, whx2] = regls0[regc]
regc = regc + 1
regc = 0
for fl_ind in regfl1:
alfpr1 = fl[fl_ind][0][0]
alfpr2 = fl[fl_ind][0][-1]
alfpth1 = np.sin(fl[fl_ind][1][0] + pi/2)
alfpth2 = np.sin(fl[fl_ind][1][-1] + pi/2)
alfpph1 = fl[fl_ind][2][0]
alfpph2 = fl[fl_ind][2][-1]
alg1 = fl[fl_ind][0][0] < 1.2
alg2 = fl[fl_ind][0][-1] < 1.2
if alg1:
why1 = np.where((frlat_edge < alfpth1) & np.roll((frlat_edge > alfpth1),-1))[0]
whx1 = np.where((frlon_edge < alfpph1) & np.roll((frlon_edge > alfpph1),-1))[0]
if (len(whx1) == 1)&(len(why1) == 1)&(alg1):
regbb[why1, whx1] = regls1[regc]
if alg2:
why2 = np.where((frlat_edge < alfpth2) & np.roll((frlat_edge > alfpth2),-1))[0]
whx2 = np.where((frlon_edge < alfpph2) & np.roll((frlon_edge > alfpph2),-1))[0]
if (len(whx2) == 1)&(len(why2) == 1)&(alg2):
regbb[why2, whx2] = regls1[regc]
regc = regc + 1
# Compute a pixel shift amount to account for differential rotation
if dcount == 0:
dtime = 1
else:
dtime0 = tarr[dcount] - tarr[dcount - 1]
dtime = dtime0.days + (dtime0.seconds / 86400.)
drot = diff_rot(dtime * u.day, np.arcsin(frlat)*180/pi * u.deg, rot_type='snodgrass')
drot = drot - drot.max()
drot = np.array(np.around((drot/u.deg * 180/pi) * (frlon[1]-frlon[0]))).astype(np.int)
# Begin comparison with detected flux rope footprints
# Compute arrays storing the locations of flux rope footprints
fpreg = np.array([])
fpwhr = list([])
if dcount == 0:
for fr in np.unique(frmap):
if fr != 0:
fpreg = np.append(fpreg,fr)
fpwhr.append(np.where(frmap == fr))
else:
for r in np.arange(frdim[0]):
frmap0[r,:] = np.roll(frmap0[r,:], drot[r])
for fr in np.unique(frmap0):
if fr != 0:
fpreg = np.append(fpreg,fr)
fpwhr.append(np.where(frmap == fr))
# Run through this set and compare for overlap
for fr in np.arange(regb.max())+1:
frwhr = np.where(regb == fr)
frwhrbb = np.where(regbb == fr)
fpmaxarea = 0.
fpmaxarea_reg = 0.
# Run through and compare overlap with full flux rope dataset
for ifpfr in np.arange(len(fpreg)):
xlap = np.in1d(fpwhr[ifpfr][1], frwhrbb[1])
ylap = np.in1d(fpwhr[ifpfr][0], frwhrbb[0])
plap = np.where(xlap & ylap)[0]
if (len(plap) != 0) & (len(np.where(np.in1d(fr_elab, int(fpreg[ifpfr])))[0]) == 0):
fr_elab = np.append(fr_elab, int(fpreg[ifpfr]))
if len(fpwhr[ifpfr][1]) > fpmaxarea:
fpmaxarea = len(fpwhr[ifpfr][1])
fpmaxarea_reg = int(fpreg[ifpfr])
if (fpmaxarea_reg != 0):
fr_etarr = np.append(fr_etarr, dcount)
fr_efpt = np.append(fr_efpt, fpmaxarea_reg)
# Diagnostic readouts!
time1 = datetime.datetime.now()
if dcount == 0:
timedel = (time1 - time0)
else:
timedel = ((time1 - time0) + timedel) / 2
timeeta = (nfrm - (dcount+1)) * timedel + time1
if dcount == (len(bfrm_list) - 1) : prntend = '\n'
print('Frame ' + '%05.f'%(dcount+1) + ' / ' + '%05.f'%nfrm + ' - ' + str(timedel) + 's - ETA ' + str(timeeta), end=prntend)
# Save the current timestamp
csfrm1 = csfrm
# Advance the timing index
dcount = dcount + 1
# Save this data to file
outfile = netcdf.netcdf_file(outdir + 'hist/fr-elab.nc', 'w')
outfile.history = 'FRoDO flux rope eruption labels'
outfile.createDimension('frenum', len(fr_elab))
out_fr_elab = outfile.createVariable('fr_elab', np.int32, ('frenum',))
out_fr_elab[:] = fr_elab
out_fr_elab.units = 'Labels of erupting flux ropes ()'
out_fr_efpt = outfile.createVariable('fr_efpt', np.int32, ('frenum',))
out_fr_efpt[:] = fr_efpt
out_fr_efpt.units = 'Labels of erupting flux rope footprints ()'
out_fr_etarr = outfile.createVariable('fr_etarr', np.int32, ('frenum',))
out_fr_etarr[:] = fr_etarr
out_fr_etarr.units = 'Erupting flux rope time references ()'
outfile.close()
def plot():
'''
Creates a standard set of plot outputs for detected flux ropes.
'''
# A quick announcement
print('Running plotting routines...')
# Define color tables
import palettable
cols = (palettable.colorbrewer.get_map('Paired', 'Qualitative', 12)).mpl_colors
# Define some plotting parameters
fscale = 1.0 # Relative figure scale
fnapp = '' # Label to append to plot filename
defcol = 'k' # Default primary color
defcol2 = cols[5] # Default secondary color
erptcol = '#ff7f0e' # Erupting plotting color
erptcmap = 'Oranges' # Erupting color map
nerptcol = '#1f77B4' # Non-erupting plotting color
nerptcmap = 'Blues' # Non-erupting color map
legfsz = 8 # Legend font size
gsize = 1e20 # Butterfly glyph scaling size
# Remove any existing files
if os.path.exists('plt') : shutil.rmtree('plt')
# Create output directories if needed
if not os.path.exists('plt') : os.mkdir('plt')
# Define a quick pre-built function for radial plotting
# Reverse-engineered from a matplotlib example script
def setup_polaraxis(fig, rect, radlim):
"""
Sometimes, things like axis_direction need to be adjusted.
"""
# rotate a bit for better orientation
tr_rotate = Affine2D().translate(90, 0)
# scale degree to radians
tr_scale = Affine2D().scale(np.pi/180., 1.)
tr = tr_rotate + tr_scale + PolarAxes.PolarTransform()
grid_locator1 = angle_helper.LocatorHMS(8)
tick_formatter1 = angle_helper.FormatterHMS()
grid_locator2 = MaxNLocator(3)
ra0, ra1 = -90, 90
cz0, cz1 = 0, radlim
grid_helper = floating_axes.GridHelperCurveLinear(
tr, extremes=(ra0, ra1, cz0, cz1),
grid_locator1=grid_locator1,
grid_locator2=grid_locator2,
tick_formatter1=None,
tick_formatter2=None)
ax1 = floating_axes.FloatingSubplot(fig, rect, grid_helper=grid_helper)
fig.add_subplot(ax1)
# adjust axis
ax1.axis["left"].set_axis_direction("bottom")
ax1.axis["right"].set_axis_direction("top")
ax1.axis["bottom"].set_visible(False)
ax1.axis["top"].set_axis_direction("bottom")
ax1.axis["top"].toggle(ticklabels=True, label=True)
ax1.axis["top"].major_ticklabels.set_axis_direction("top")
ax1.axis["top"].label.set_axis_direction("top")
ax1.axis["left"].label.set_text('Number [bin$^{-1}$]')
ax1.axis["top"].label.set_text(r'$\theta$ [degrees]')
# create a parasite axes whose transData in RA, cz
aux_ax = ax1.get_aux_axes(tr)
aux_ax.patch = ax1.patch # for aux_ax to have a clip path as in ax
ax1.patch.zorder = 0.9 # but this has a side effect that the patch is
# drawn twice, and possibly over some other
# artists. So, we decrease the zorder a bit to
# prevent this.
return ax1, aux_ax
# Read time histories
d = netcdf.netcdf_file(outdir + 'hist/fr-hist.nc', 'r')
fr_frg = d.variables['fr_frg'][:].copy()
fr_area = d.variables['fr_area'][:].copy()
fr_time = d.variables['fr_time'][:].copy()
fr_dur = d.variables['fr_dur'][:].copy()
fr_mhlcy = d.variables['fr_mhlcy'][:].copy()
fr_nhlcy = d.variables['fr_nhlcy'][:].copy()
fr_sflux = d.variables['fr_sflux'][:].copy()
fr_uflux = d.variables['fr_uflux'][:].copy()
fr_rext = d.variables['fr_rext'][:].copy()
fr_mrext = d.variables['fr_mrext'][:].copy()
fr_mlat = d.variables['fr_mlat'][:].copy()
d.close()
tarr = np.load(outdir + '/hist/fr-tarr.npy')
infile = open(outdir + '/hist/h-frh-area.pkl', 'rb')
frh_area = pickle.load(infile)
infile.close()
infile = open(outdir + '/hist/h-frh-time.pkl', 'rb')