-
Notifications
You must be signed in to change notification settings - Fork 17
/
huxt_inputs.py
1694 lines (1310 loc) · 65 KB
/
huxt_inputs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import datetime
import os
import urllib
import ssl
import copy
import astropy.units as u
from astropy.io import fits
from astropy.time import Time
import httplib2
import numpy as np
from pyhdf.SD import SD, SDC
import h5py
from scipy.io import netcdf, readsav
from scipy import interpolate
from sunpy.coordinates import sun
from sunpy.net import Fido
from sunpy.net import attrs
from sunpy.timeseries import TimeSeries
import requests
import pandas as pd
from dtaidistance import dtw
import huxt as H
def get_MAS_boundary_conditions(cr=np.NaN, observatory='', runtype='', runnumber='', masres=''):
"""
A function to grab the solar wind speed (Vr) and radial magnetic field (Br) boundary conditions from MHDweb.
An order of preference for observatories is given in the function.
Checks first if the data already exists in the HUXt boundary condition folder.
Args:
cr: Integer Carrington rotation number
observatory: String name of preferred observatory (e.g., 'hmi','mdi','solis',
'gong','mwo','wso','kpo'). Empty if no preference and automatically selected.
runtype: String name of preferred MAS run type (e.g., 'mas','mast','masp').
Empty if no preference and automatically selected
runnumber: String Name of preferred MAS run number (e.g., '0101','0201').
Empty if no preference and automatically selected
masres: String, specify the resolution of the MAS model run through 'high' or 'medium'.
Returns:
flag: Integer, 1 = successful download. 0 = files exist, -1 = no file found.
"""
assert (np.isnan(cr) == False)
# The order of preference for different MAS run results
overwrite = False
if not masres:
masres_order = ['high', 'medium']
else:
masres_order = [str(masres)]
overwrite = True # If the user wants a specific observatory, overwrite what's already downloaded
if not observatory:
observatories_order = ['hmi', 'mdi', 'solis', 'gong', 'mwo', 'wso', 'kpo']
else:
observatories_order = [str(observatory)]
overwrite = True # If the user wants a specific observatory, overwrite what's already downloaded
if not runtype:
runtype_order = ['masp', 'mas', 'mast']
else:
runtype_order = [str(runtype)]
overwrite = True
if not runnumber:
runnumber_order = ['0201', '0101']
else:
runnumber_order = [str(runnumber)]
overwrite = True
# Get the HUXt boundary condition directory
dirs = H._setup_dirs_()
_boundary_dir_ = dirs['boundary_conditions']
# Example URL: http://www.predsci.com/data/runs/cr2010-medium/mdi_mas_mas_std_0101/helio/br_r0.hdf
# heliomas_url_front = 'https://shadow.predsci.com/data/runs/cr'
heliomas_url_front = 'http://www.predsci.com/data/runs/cr'
heliomas_url_end = '_r0.hdf'
vrfilename = 'HelioMAS_CR' + str(int(cr)) + '_vr' + heliomas_url_end
brfilename = 'HelioMAS_CR' + str(int(cr)) + '_br' + heliomas_url_end
if (os.path.exists(os.path.join(_boundary_dir_, brfilename)) is False or
os.path.exists(os.path.join(_boundary_dir_, vrfilename)) is False or
overwrite is True): # Check if the files already exist
# Search MHDweb for a HelioMAS run, in order of preference
h = httplib2.Http(disable_ssl_certificate_validation=False)
foundfile = False
urlbase = None
for res in masres_order:
for masob in observatories_order:
for masrun in runtype_order:
for masnum in runnumber_order:
urlbase = (heliomas_url_front + str(int(cr)) + '-' +
res + '/' + masob + '_' +
masrun + '_mas_std_' + masnum + '/helio/')
url = urlbase + 'br' + heliomas_url_end
# See if this br file exists
resp = h.request(url, 'HEAD')
if int(resp[0]['status']) < 400:
foundfile = True
# Exit all the loops - clumsy, but works
if foundfile:
break
if foundfile:
break
if foundfile:
break
if foundfile:
break
if foundfile is False:
print('No data available for given CR and observatory preferences')
return -1
# Download the vr and br files
ssl._create_default_https_context = ssl._create_unverified_context
print('Downloading from: ', urlbase)
urllib.request.urlretrieve(urlbase + 'br' + heliomas_url_end,
os.path.join(_boundary_dir_, brfilename))
urllib.request.urlretrieve(urlbase + 'vr' + heliomas_url_end,
os.path.join(_boundary_dir_, vrfilename))
return 1
else:
print('Files already exist for CR' + str(int(cr)))
return 0
def read_MAS_vr_br(cr):
"""
A function to read in the MAS boundary conditions for a given CR
Args:
cr: Integer Carrington rotation number
Returns:
MAS_vr: Solar wind speed at 30rS, np.array in units of km/s.
MAS_vr_Xa: Carrington longitude of Vr map, np.array in units of rad.
MAS_vr_Xm: Latitude of Vr as angle down from N pole, np.array in units of rad.
MAS_br: Radial magnetic field at 30rS, dimensionless np.array.
MAS_br_Xa: Carrington longitude of Br map, np.array in units of rad.
MAS_br_Xm: Latitude of Br as angle down from N pole, np.array in units of rad.
"""
# Get the boundary condition directory
dirs = H._setup_dirs_()
_boundary_dir_ = dirs['boundary_conditions']
# Create the filenames
heliomas_url_end = '_r0.hdf'
vrfilename = 'HelioMAS_CR' + str(int(cr)) + '_vr' + heliomas_url_end
brfilename = 'HelioMAS_CR' + str(int(cr)) + '_br' + heliomas_url_end
filepath = os.path.join(_boundary_dir_, vrfilename)
assert os.path.exists(filepath)
file = SD(filepath, SDC.READ)
sds_obj = file.select('fakeDim0') # select sds
MAS_vr_Xa = sds_obj.get() # get sds data
sds_obj = file.select('fakeDim1') # select sds
MAS_vr_Xm = sds_obj.get() # get sds data
sds_obj = file.select('Data-Set-2') # select sds
MAS_vr = sds_obj.get() # get sds data
# Convert from model to physicsal units
MAS_vr = MAS_vr * 481.0 * u.km / u.s
MAS_vr_Xa = MAS_vr_Xa * u.rad
MAS_vr_Xm = MAS_vr_Xm * u.rad
filepath = os.path.join(_boundary_dir_, brfilename)
assert os.path.exists(filepath)
file = SD(filepath, SDC.READ)
sds_obj = file.select('fakeDim0') # select sds
MAS_br_Xa = sds_obj.get() # get sds data
sds_obj = file.select('fakeDim1') # select sds
MAS_br_Xm = sds_obj.get() # get sds data
sds_obj = file.select('Data-Set-2') # select sds
MAS_br = sds_obj.get() # get sds data
MAS_br_Xa = MAS_br_Xa * u.rad
MAS_br_Xm = MAS_br_Xm * u.rad
return MAS_vr, MAS_vr_Xa, MAS_vr_Xm, MAS_br, MAS_br_Xa, MAS_br_Xm
def get_MAS_long_profile(cr, lat=0.0 * u.deg):
"""
Function to download, read and process MAS output to provide a longitude profile at a specified latitude of the
solar wind speed for use as boundary conditions in HUXt.
Args:
cr: Integer Carrington rotation number
lat: Latitude at which to extract the longitudinal profile, measure up from the equator. Float with units of deg
Returns:
vr_in: Solar wind speed as a function of Carrington longitude at solar equator.
Interpolated to HUXt longitudinal resolution. np.array (NDIM = 1) in units of km/s
"""
assert (np.isnan(cr) == False and cr > 0)
assert (lat >= -90.0 * u.deg)
assert (lat <= 90.0 * u.deg)
# Convert angle from equator to angle down from N pole
ang_from_N_pole = np.pi / 2 - (lat.to(u.rad)).value
# Check the data exist, if not, download them
flag = get_MAS_boundary_conditions(cr)
assert (flag > -1)
# Read the HelioMAS data
MAS_vr, MAS_vr_Xa, MAS_vr_Xm, MAS_br, MAS_br_Xa, MAS_br_Xm = read_MAS_vr_br(cr)
# Extract the value at the given latitude
vr = np.ones(len(MAS_vr_Xa))
for i in range(0, len(MAS_vr_Xa)):
vr[i] = np.interp(ang_from_N_pole, MAS_vr_Xm.value, MAS_vr[i][:].value)
return vr * u.km / u.s
def get_MAS_br_long_profile(cr, lat=0.0 * u.deg):
"""
Function to download, read and process MAS output to provide a longitude profile at a specified latitude of the Br
for use as boundary conditions in HUXt.
Args:
cr: Integer Carrington rotation number
lat: Latitude at which to extract the longitudinal profile, measure up from equator. Float with units of deg
Returns:
br_in: Br as a function of Carrington longitude at solar equator.
Interpolated to HUXt longitudinal resolution. np.array (NDIM = 1)
"""
assert (np.isnan(cr) == False and cr > 0)
assert (lat >= -90.0 * u.deg)
assert (lat <= 90.0 * u.deg)
# Convert angle from equator to angle down from N pole
ang_from_N_pole = np.pi / 2 - (lat.to(u.rad)).value
# Check the data exist, if not, download them
flag = get_MAS_boundary_conditions(cr)
assert (flag > -1)
# Read the HelioMAS data
MAS_vr, MAS_vr_Xa, MAS_vr_Xm, MAS_br, MAS_br_Xa, MAS_br_Xm = read_MAS_vr_br(cr)
# Extract the value at the given latitude
br = np.ones(len(MAS_br_Xa))
for i in range(0, len(MAS_br_Xa)):
br[i] = np.interp(ang_from_N_pole, MAS_br_Xm.value, MAS_br[i][:])
return br
def get_MAS_vr_map(cr):
"""
A function to download, read and process MAS output to provide HUXt boundary conditions as lat-long maps, along with
angle from the equator for the maps.
Maps returned in native resolution, not HUXt resolution.
Args:
cr: Integer, Carrington rotation number
Returns:
vr_map: Solar wind speed as a Carrington longitude-latitude map. np.array with units of km/s
vr_lats: The latitudes for the Vr map, relative to the equator. np.array with units of radians
vr_longs: The Carrington longitudes for the Vr map, np.array with units of radians
"""
assert (np.isnan(cr) == False and cr > 0)
# Check the data exist, if not, download them
flag = get_MAS_boundary_conditions(cr)
if flag < 0:
return -1, -1, -1
# Read the HelioMAS data
MAS_vr, MAS_vr_Xa, MAS_vr_Xm, MAS_br, MAS_br_Xa, MAS_br_Xm = read_MAS_vr_br(cr)
vr_map = MAS_vr
# Convert the lat angles from N-pole to equator centred
vr_lats = (np.pi / 2) * u.rad - MAS_vr_Xm
# Flip lats, so they're increasing in value
vr_lats = np.flipud(vr_lats)
vr_map = np.fliplr(vr_map)
vr_longs = MAS_vr_Xa
return vr_map.T, vr_longs, vr_lats
def get_MAS_br_map(cr):
"""
A function to download, read and process MAS output to provide HUXt boundary
conditions as lat-long maps, along with angle from equator for the maps.
Maps returned in native resolution, not HUXt resolution.
Args:
cr: Integer, Carrington rotation number
Returns:
vr_map: Solar wind speed as a Carrington longitude-latitude map. np.array with units of km/s
vr_lats: The latitudes for the Vr map, relative to the equator. np.array with units of radians
vr_longs: The Carrington longitudes for the Vr map, np.array with units of radians
"""
assert (np.isnan(cr) == False and cr > 0)
# Check the data exist, if not, download them
flag = get_MAS_boundary_conditions(cr)
if flag < 0:
return -1, -1, -1
# Read the HelioMAS data
MAS_vr, MAS_vr_Xa, MAS_vr_Xm, MAS_br, MAS_br_Xa, MAS_br_Xm = read_MAS_vr_br(cr)
br_map = MAS_br
# Convert the lat angles from N-pole to equator centred
br_lats = (np.pi / 2) * u.rad - MAS_br_Xm
# Flip lats, so they're increasing in value
br_lats = np.flipud(br_lats)
br_map = np.fliplr(br_map)
br_longs = MAS_br_Xa
return br_map.T, br_longs, br_lats
@u.quantity_input(v_outer=u.km / u.s)
@u.quantity_input(r_outer=u.solRad)
@u.quantity_input(lon_outer=u.rad)
@u.quantity_input(r_inner=u.solRad)
def map_v_inwards(v_orig, r_orig, lon_orig, r_new):
"""
Function to map v from r_orig (in rs) to r_inner (in rs) accounting for
residual acceleration, but neglecting stream interactions.
Args:
v_orig: Solar wind speed at original radial distance. Units of km/s.
r_orig: Radial distance at original radial distance. Units of km.
lon_orig: Carrington longitude at original distance. Units of rad
r_new: Radial distance at new radial distance. Units of km.
Returns:
v_new: Solar wind speed mapped from r_orig to r_new. Units of km/s.
lon_new: Carrington longitude at r_new. Units of rad.
"""
# Get the acceleration parameters
constants = H.huxt_constants()
alpha = constants['alpha'] # Scale parameter for residual SW acceleration
rH = constants['r_accel'].to(u.kilometer).value # Spatial scale parameter for residual SW acceleration
Tsyn = constants['synodic_period'].to(u.s).value
r_orig = r_orig.to(u.km).value
r_new = r_new.to(u.km).value
r_0 = (30 * u.solRad).to(u.km).value
# Compute the 30 rS speed
v0 = v_orig.value / (1 + alpha * (1 - np.exp(-(r_orig - r_0) / rH)))
# comppute new speed
vnew = v0 * (1 + alpha * (1 - np.exp(-(r_new - r_0) / rH)))
# Compute the transit time from the new to old inner boundary heights (i.e., integrate equations 3 and 4 wrt to r)
A = v0 + alpha * v0
term1 = rH * np.log(A * np.exp(r_orig / rH) - alpha * v0 * np.exp(r_new / rH)) / A
term2 = rH * np.log(A * np.exp(r_new / rH) - alpha * v0 * np.exp(r_new / rH)) / A
T_integral = term1 - term2
# Work out the longitudinal shift
phi_new = H._zerototwopi_(lon_orig.value + (T_integral / Tsyn) * 2 * np.pi)
return vnew * u.km / u.s, phi_new * u.rad
@u.quantity_input(v_orig=u.km / u.s)
@u.quantity_input(r_orig=u.solRad)
@u.quantity_input(r_inner=u.solRad)
def map_v_boundary_inwards(v_orig, r_orig, r_new, b_orig=np.nan):
"""
Function to map a longitudinal V series from r_outer (in rs) to r_inner (in rs)
accounting for residual acceleration, but neglecting stream interactions.
Series returned on input grid
Args:
v_orig: Solar wind speed as function of long at outer radial boundary. Units of km/s.
r_orig: Radial distance at original radial boundary. Units of km.
r_new: Radial distance at new radial boundary. Units of km.
b_orig: b_r to be optionally mapped using the same time/long delay as v
Returns:
v_new: Solar wind speed as function of long mapped from r_orig to r_new. Units of km/s.
b_new: (if b_orig input). B_r as a function of long.
"""
# Compute the longitude grid from the length of the v_orig input variable
nv = len(v_orig)
dlon = 2 * np.pi / nv
lon = np.arange(dlon / 2, 2 * np.pi - dlon / 2 + dlon / 10, dlon) * u.rad
# Map each point in to a new speed and longitude
v0, phis_new = map_v_inwards(v_orig, r_orig, lon, r_new)
# Interpolate the mapped speeds back onto the regular Carr long grid,
# making boundaries periodic
v_new = np.interp(lon, phis_new, v0, period=2 * np.pi)
if np.isfinite(b_orig).any():
b_new = np.interp(lon, phis_new, b_orig, period=2 * np.pi)
return v_new, b_new
else:
return v_new
@u.quantity_input(v_map=u.km / u.s)
@u.quantity_input(v_map_lat=u.rad)
@u.quantity_input(v_map_long=u.rad)
@u.quantity_input(r_outer=u.solRad)
@u.quantity_input(r_inner=u.solRad)
def map_vmap_inwards(v_map, v_map_lat, v_map_long, r_orig, r_new, b_map=np.nan):
"""
Function to map a V Carrington map from r_orig (in rs) to r_new (in rs), accounting for acceleration, but ignoring
stream interaction.
Map returned on input coord system, not HUXT resolution.
Args:
v_map: Solar wind speed Carrington map at original radial boundary. np.array with units of km/s.
v_map_lat: Latitude (from the equator) of v_map positions. np.array with units of radians
v_map_long: Carrington longitude of v_map positions. np.array with units of radians
r_orig: Radial distance at original radial boundary. np.array with units of km.
r_new: Radial distance at new radial boundary. np.array with units of km.
b_map: b_r to be optionally mapped using the same time/long delay as v. assumed to be on same grid
Returns:
v_map_new: Solar wind speed map at r_inner. np.array with units of km/s.
b_map_new: (if b_orig input). B_r as a function of long.
"""
# Check the dimensions
assert (len(v_map_lat) == len(v_map[:, 1]))
assert (len(v_map_long) == len(v_map[1, :]))
v_map_new = np.ones((len(v_map_lat), len(v_map_long)))
b_map_new = np.ones((len(v_map_lat), len(v_map_long)))
for ilat in range(0, len(v_map_lat)):
# Map each point in to a new speed and longitude
v0, phis_new = map_v_inwards(v_map[ilat, :], r_orig, v_map_long, r_new)
# Interpolate the mapped speeds back onto the regular Carr long grid,
# making boundaries periodic * u.km/u.s
v_map_new[ilat, :] = np.interp(v_map_long.value,
phis_new.value, v0.value, period=2 * np.pi)
# check if b_pol needs mapping
if np.isfinite(b_map).any():
# check teh b abd v maps are the same dimensions
assert (v_map.shape == b_map.shape)
b_map_new[ilat, :] = np.interp(v_map_long.value,
phis_new.value, b_map[ilat, :], period=2 * np.pi)
if np.isfinite(b_map).any():
return v_map_new * u.km / u.s, b_map_new
else:
return v_map_new * u.km / u.s
def get_PFSS_maps(filepath):
"""
A function to load, read and process PFSSpy output to provide HUXt boundary conditions as lat-long maps, along with
angle from the equator for the maps.
Maps returned in native resolution, not HUXt resolution.
Maps are not transformed - make sure the PFSS maps are Carrington maps
Args:
filepath: String, The filepath for the PFSSpy .nc file
Returns:
vr_map: np.array, Solar wind speed as a Carrington longitude-latitude map. In km/s
vr_lats: np.array, The latitudes for the Vr map, in radians from the equator
vr_longs: np.array, The Carrington longitudes for the Vr map, in radians
br_map: np.array, Br as a Carrington longitude-latitude map. Dimensionless
br_lats: np.array, The latitudes for the Br map, in radians from the equator
br_longs: np.array, The Carrington longitudes for the Br map, in radians
"""
assert os.path.exists(filepath)
nc = netcdf.netcdf_file(filepath, 'r', mmap=False)
br_map = nc.variables['br'][:]
vr_map = nc.variables['vr'][:] * u.km / u.s
phi = nc.variables['ph'][:]
cotheta = nc.variables['cos(th)'][:]
nc.close()
phi = phi * u.rad
theta = (np.pi / 2 - np.arccos(cotheta)) * u.rad
vr_lats = theta[:, 0]
br_lats = vr_lats
vr_longs = phi[0, :]
br_longs = vr_longs
return vr_map, vr_longs, vr_lats, br_map, br_longs, br_lats
def get_CorTom_vr_map(filepath):
"""
A function to load, read and process CorTom density output to provide HUXt V boundary conditions as lat-long maps.
Maps returned in native resolution, not HUXt resolution.
Maps are not transformed - make sure the CorTom maps are Carrington maps
Args:
filepath: String, The filepath for the CorTom.txt file
Returns:
vr_map: np.array, Solar wind speed as a Carrington longitude-latitude map. In km/s
vr_lats: np.array, The latitudes for the Vr map, in radians from trhe equator
vr_longs: np.array, The Carrington longitudes for the Vr map, in radians
phi: meshgrid og longitudes
theta: mesh grid of latitudes
"""
cortom_data = readsav(filepath)
vr_map = copy.copy(cortom_data['velocity'])
vr_colat = copy.copy(cortom_data['colat_rad'])
vr_longs = copy.copy(cortom_data['lon_rad'])
vr_lats = (np.pi/2 - vr_colat) * u.rad
# Flip so south pole at bottom
vr_lats = np.flipud(vr_lats)
vr_map = np.flipud(vr_map)
return vr_map*u.km/u.s, vr_longs*u.rad, vr_lats*u.rad
def get_WSA_maps(filepath):
"""
A function to load, read and process WSA FITS maps from the UK Met Office to provide HUXt boundary conditions as
lat-long maps, along with angle from the equator for the maps.
Maps returned in native resolution, not HUXt resolution.
Maps are transformed to Carrington maps
Args:
filepath: String, The filepath for the WSA file
Returns:
vr_map: Solar wind speed as a Carrington longitude-latitude map. np.array in units of km/s.
vr_lats: The latitudes for the Vr map, in radians from the equator. np.array in units of radians.
vr_longs: The Carrington longitudes for the Vr map. np.array in units of radians.
br_map: Br as a Carrington longitude-latitude map. Dimensionless np.array.
br_lats: The latitudes for the Br map, in radians from the equator. np.array in units of radians.
br_longs: The Carrington longitudes for the Br map, in radians. np.array in units of radians.
cr: Integer, Carrington rotation number
"""
assert os.path.exists(filepath)
hdul = fits.open(filepath)
keys = hdul[0].header
assert 'CARROT' in keys
cr_num = hdul[0].header['CARROT']
# different versions of WSA data have different keywords?
if 'GRID' in keys:
dgrid = hdul[0].header['GRID'] * np.pi / 180
else:
assert 'LONSTEP' in keys
dgrid = hdul[0].header['LONSTEP'] * np.pi / 180
# The map edge longitude is given by the CARRLONG variable.
# This is 60 degrees from Central meridian (i.e. Earth Carrington longitude)
carrlong = _zerototwopi_((hdul[0].header['CARRLONG']) * np.pi / 180)
data = hdul[0].data
br_map_fits = data[0, :, :]
vr_map_fits = data[1, :, :]
hdul.close()
# compute the Carrington map grids
vr_long_edges = np.arange(0, 2 * np.pi + 0.00001, dgrid)
vr_long_centres = (vr_long_edges[1:] + vr_long_edges[:-1]) / 2
vr_lat_edges = np.arange(-np.pi / 2, np.pi / 2 + 0.00001, dgrid)
vr_lat_centres = (vr_lat_edges[1:] + vr_lat_edges[:-1]) / 2
br_long_edges = np.arange(0, 2 * np.pi + 0.00001, dgrid)
br_long_centres = (br_long_edges[1:] + br_long_edges[:-1]) / 2
br_lat_edges = np.arange(-np.pi / 2, np.pi / 2 + 0.00001, dgrid)
br_lat_centres = (br_lat_edges[1:] + br_lat_edges[:-1]) / 2
vr_longs = vr_long_centres * u.rad
vr_lats = vr_lat_centres * u.rad
br_longs = br_long_centres * u.rad
br_lats = br_lat_centres * u.rad
# rotate the maps so they are in the Carrington frame
vr_map = np.empty(vr_map_fits.shape)
br_map = np.empty(br_map_fits.shape)
for nlat in range(0, len(vr_lat_centres)):
interp = interpolate.interp1d(_zerototwopi_(vr_long_centres + carrlong),
vr_map_fits[nlat, :], kind="nearest",
fill_value="extrapolate")
vr_map[nlat, :] = interp(vr_long_centres)
for nlat in range(0, len(br_lat_centres)):
interp = interpolate.interp1d(_zerototwopi_(br_long_centres + carrlong),
br_map_fits[nlat, :], kind="nearest",
fill_value="extrapolate")
br_map[nlat, :] = interp(br_long_centres)
vr_map = vr_map * u.km / u.s
return vr_map, vr_longs, vr_lats, br_map, br_longs, br_lats, cr_num
def get_WSA_long_profile(filepath, lat=0.0 * u.deg):
"""
Function to read and process WSA output to provide a longitude profile at a specified latitude
of the solar wind speed for use as boundary conditions in HUXt.
Args:
filepath: A complete path to the WSA data file
lat: Latitude at which to extract the longitudinal profile, measure up from equator. Float with units of deg
Returns:
vr_in: Solar wind speed as a function of Carrington longitude at solar equator.
Interpolated to the default HUXt longitudinal grid. np.array (NDIM = 1) in units of km/s
"""
assert (lat >= -90.0 * u.deg)
assert (lat <= 90.0 * u.deg)
assert (os.path.isfile(filepath))
vr_map, lon_map, lat_map, br_map, br_lon, br_lat, cr_num = get_WSA_maps(filepath)
# Extract the value at the given latitude
vr = np.zeros(lon_map.shape)
for i in range(lon_map.size):
vr[i] = np.interp(lat.to(u.rad).value, lat_map.to(u.rad).value, vr_map[:, i].value)
return vr * u.km / u.s
def get_WSA_br_long_profile(filepath, lat=0.0 * u.deg):
"""
Function to read and process WSA output to provide a longitude profile at a specified latitude
of the HMF polarity for use as boundary conditions in HUXt.
Args:
filepath: A complete path to the WSA data file
lat: Latitude at which to extract the longitudinal profile, measure up from equator. Float with units of deg
Returns:
vr_in: Solar wind speed as a function of Carrington longitude at solar equator.
Interpolated to the default HUXt longitudinal grid. np.array (NDIM = 1) in units of km/s
"""
assert (lat >= -90.0 * u.deg)
assert (lat <= 90.0 * u.deg)
assert (os.path.isfile(filepath))
vr_map, lon_map, lat_map, br_map, br_lon, br_lat, cr_num = get_WSA_maps(filepath)
# Extract the value at the given latitude
br = np.zeros(lon_map.shape)
for i in range(lon_map.size):
br[i] = np.interp(lat.to(u.rad).value, lat_map.to(u.rad).value, br_map[:, i])
return br
def get_PFSS_long_profile(filepath, lat=0.0 * u.deg):
"""
Function to read and process PFSS output to provide a longitude profile at a specified latitude
of the solar wind speed for use as boundary conditions in HUXt.
Args:
filepath: A complete path to the PFSS data file
lat: Latitude at which to extract the longitudinal profile, measure up from equator. Float with units of deg
Returns:
vr_in: Solar wind speed as a function of Carrington longitude at solar equator.
Interpolated to the default HUXt longitudinal grid. np.array (NDIM = 1) in units of km/s
"""
assert (lat >= -90.0 * u.deg)
assert (lat <= 90.0 * u.deg)
assert (os.path.isfile(filepath))
vr_map, lon_map, lat_map, br_map, br_lon, br_lat = get_PFSS_maps(filepath)
# Extract the value at the given latitude
vr = np.zeros(lon_map.shape)
for i in range(lon_map.size):
vr[i] = np.interp(lat.to(u.rad).value, lat_map.to(u.rad).value, vr_map[:, i].value)
return vr * u.km / u.s
def get_CorTom_long_profile(filepath, lat=0.0 * u.deg):
"""
Function to read and process CorTom (Coronal Tomography) output to provide a longitude profile at a specified
latitude of the solar wind speed for use as boundary conditions in HUXt.
Args:
filepath: A complete path to the CorTom data file
lat: Latitude at which to extract the longitudinal profile, measure up from equator. Float with units of deg
Returns:
vr_in: Solar wind speed as a function of Carrington longitude at solar equator.
Interpolated to the default HUXt longitudinal grid. np.array (NDIM = 1) in units of km/s
"""
assert (lat >= -90.0 * u.deg)
assert (lat <= 90.0 * u.deg)
assert (os.path.isfile(filepath))
vr_map, lon_map, lat_map = get_CorTom_vr_map(filepath)
# Extract the value at the given latitude
vr = np.zeros(lon_map.shape)
for i in range(lon_map.size):
vr[i] = np.interp(lat.to(u.rad).value, lat_map.value, vr_map[:, i].value)
return vr * u.km / u.s
def getMetOfficeWSAandCone(startdate, enddate, datadir=''):
"""Downloads the most recent WSA output and coneCME files for a given time window from the Met Office system.
Requires an API key to be set as a system environment variable saves wsa and cone files to datadir, which defaults
to the current directory. UTC date format is "%Y-%m-%dT%H:%M:%S". Outputs the filepaths to the WSA and cone files.
Args:
startdate : A DATETIME object representing the start of the download window
enddate : A DATETIME object representing the end of the download window,
normally the current forecast date
datadir : Optional argument if a non-default download location is needed
Returns:
success : True if both cone and wsa files were successfullly downloaded
wsafilepath: filepath for the WSA output
conefilepath: filepath for the cone CME file
model_time : time-stamp of the associated enlil run
"""
version = 'v1'
api_key = os.getenv("API_KEY")
url_base = "https://gateway.api-management.metoffice.cloud/swx_swimmr_s4/1.0"
startdatestr = startdate.strftime("%Y-%m-%dT%H:%M:%S")
enddatestr = enddate.strftime("%Y-%m-%dT%H:%M:%S")
request_url = url_base + "/" + version + "/data/swc-enlil-wsa?from=" + startdatestr + "&to=" + enddatestr
response = requests.get(request_url, headers={"accept": "application/json", "apikey": api_key})
success = False
wsafilepath = ''
conefilepath = ''
model_time = ''
if response.status_code == 200:
# Convert to json
js = response.json()
nfiles = len(js['data'])
# get the latest file
i = nfiles - 1
found_wsa = False
found_cone = False
# start with the most recent file and work back in time
while i > 0:
model_time = js['data'][i]['model_run_time']
wsa_file_name = js['data'][i]['gong_file']
cone_file_name = js['data'][i]['cone_file']
wsa_file_url = url_base + "/" + version + "/" + wsa_file_name
cone_file_url = url_base + "/" + version + "/" + cone_file_name
if not found_wsa:
response_wsa = requests.get(wsa_file_url, headers={"apikey": api_key})
if response_wsa.status_code == 200:
wsafilepath = os.path.join(datadir, wsa_file_name)
open(wsafilepath, "wb").write(response_wsa.content)
found_wsa = True
if not found_cone:
response_cone = requests.get(cone_file_url, headers={"apikey": api_key})
if response_cone.status_code == 200:
conefilepath = os.path.join(datadir, cone_file_name)
open(conefilepath, "wb").write(response_cone.content)
found_cone = True
i = i - 1
if found_wsa and found_cone:
success = True
break
return success, wsafilepath, conefilepath, model_time
def get_omni(starttime, endtime):
"""
A function to grab and process the OMNI COHO1HR data using FIDO
Args:
starttime : datetime for start of requested interval
endtime : datetime for start of requested interval
Returns:
omni: Dataframe of the OMNI timeseries
"""
trange = attrs.Time(starttime, endtime)
dataset = attrs.cdaweb.Dataset('OMNI_COHO1HR_MERGED_MAG_PLASMA')
result = Fido.search(trange, dataset)
downloaded_files = Fido.fetch(result)
# Import the OMNI data
data = TimeSeries(downloaded_files, concatenate=True)
omni = data.to_dataframe()
del data
# # Set invalid data points to NaN
id_bad = omni['V'] == 9999.0
omni.loc[id_bad, 'V'] = np.NaN
#create a BX_GSE field that is expected by some HUXt fucntions
omni['BX_GSE'] = -omni['BR']
# create a datetime column
omni['datetime'] = omni.index
#reset the index
omni = omni.reset_index()
return omni
def datetime2huxtinputs(dt):
"""
A function to convert a datetime into the relevant Carrington rotation number and longitude
for initialising a HUXt run.
Args:
dt : A DATETIME object representing the time of interest.
Returns:
cr : The Carrington rotation number as an Integer
cr_lon_init : The Carrington longitude of Earth at the given datetime, as a float, with units of u.rad
"""
def remainder(cr_frac):
if np.isscalar(cr_frac):
return int(np.floor(cr_frac))
else:
return np.floor(cr_frac).astype(int)
cr_frac = sun.carrington_rotation_number(dt)
cr = remainder(cr_frac)
cr_lon_init = 2 * np.pi * (1 - (cr_frac - cr)) * u.rad
return cr, cr_lon_init
def import_cone2bc_parameters(filename):
"""
Convert a cone2bc.in file (for inserting cone cmes into ENLIL) into a dictionary of CME parameters.
Assumes all cone2bc files have the same structure, except for the number of cone cmes.
Args:
filename: Path to the cone2bc.in file to convert.
Returns:
cmes: A dictionary of the cone cme parameters.
"""
with open(filename, 'r') as file:
data = file.readlines()
# Get the number of cmes.
n_cme = int(data[13].split('=')[1].split(',')[0])
if n_cme == 0:
print('Warning: No CMEs in conefile: ' + filename)
return {}
# Pull out the rows corresponding to the CME parameters
cme_sub = data[14:-3].copy()
# Extract the unique keys describing the CME parameters, excluding CME number.
keys = []
for i, d in enumerate(cme_sub):
k = d.split('=')[0].split('(')[0].strip()
if k not in keys:
keys.append(k)
# Build an empty dictionary to store the parameters of each CME. Set the CME key to be the
# number of the CME in the cone2bc file (counting from 1 to N).
cmes = {i + 1: {k: {} for k in keys} for i in range(n_cme)}
# Loop the CME parameters and bin into the dictionary
for i, d in enumerate(cme_sub):
parts = d.strip().split('=')
param_name = parts[0].split('(')[0]
cme_id = int(parts[0].split('(')[1].split(')')[0])
param_val = parts[1].split(',')[0]
if param_name == 'ldates':
param_val = param_val.strip("'")
else:
if param_val == '.': #I presume this is short hand for zero?
param_val='0.0'
param_val = float(param_val)
cmes[cme_id][param_name] = param_val
return cmes
def ConeFile_to_ConeCME_list(model, filepath):
"""
A function to produce a list of ConeCMEs for input to HUXt derived from a cone2bc.in file, as is used with
to input Cone CMEs into Enlil. Assumes CME height of 21.5 rS
Args:
model: A HUXt instance.
filepath: The path to the relevant cone2bc.in file.
returns:
cme_list: A list of ConeCME instances.
"""
cme_params = import_cone2bc_parameters(filepath)
cme_list = []
for cme_id, cme_val in cme_params.items():
# CME initialisation date
t_cme = Time(cme_val['ldates'])
# CME initialisation relative to model initialisation, in days
dt_cme = (t_cme - model.time_init).jd * u.day
# Get lon, lat and speed
lon = cme_val['lon'] * u.deg
lat = cme_val['lat'] * u.deg
speed = cme_val['vcld'] * u.km / u.s
# Get full angular width, cone2bc specifies angular half width under rmajor
wid = 2 * cme_val['rmajor'] * u.deg
# Set the initial height to be 21.5 rS, the default for WSA
iheight = 21.5 * u.solRad
# Thickness must be computed from CME cone initial radius and the xcld parameter,
# which specifies the relative elongation of the cloud, 1=spherical,
# 2=middle twice as long as cone radius e.g.
# compute initial radius of the cone
radius = np.abs(model.r[0] * np.tan(wid / 2.0)) # eqn on line 162 in ConeCME class
# Thickness determined from xcld and radius
thick = 5 * u.solRad # (1.0 - cme_val['xcld']) * radius
cme = H.ConeCME(t_launch=dt_cme, longitude=lon, latitude=lat,
width=wid, v=speed, thickness=thick, initial_height=iheight)
cme_list.append(cme)
# sort the CME list into chronological order
launch_times = np.ones(len(cme_list))
for i, cme in enumerate(cme_list):
launch_times[i] = cme.t_launch.value
id_sort = np.argsort(launch_times)
cme_list = [cme_list[i] for i in id_sort]
return cme_list
def ConeFile_to_ConeCME_list_time(filepath, time):
"""
Simple wrapper for ConeFile_to_ConeCME_list so that dummy model is not needed
Args:
filepath: Full filepath to a ConeFile of Cone CME parameters
time: The UTC time to initialise HUXt with.
Returns:
cme_list: A list of ConeCME objects that correspond CMEs in a ConeFile
"""
cr, cr_lon_init = datetime2huxtinputs(time)
dummymodel = H.HUXt(v_boundary=np.ones(128) * 400 * (u.km / u.s), simtime=1 * u.day, cr_num=cr,
cr_lon_init=cr_lon_init,
lon_out=0.0 * u.deg, r_min=21.5 * u.solRad)
cme_list = ConeFile_to_ConeCME_list(dummymodel, filepath)
return cme_list