-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdbm_functions.py
More file actions
executable file
·1853 lines (1568 loc) · 58.7 KB
/
dbm_functions.py
File metadata and controls
executable file
·1853 lines (1568 loc) · 58.7 KB
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
"""
dbm_functions: import function to perform DBM simulation
Author: Ronish Mugatwala
E-mail: ronish.mugatwala@edu.unige.it
Github: astronish16
Updates:
19th June 2024: new project structure.
1st July 2025: Function optimazation and use 1D function in 2D as much as possible to avoid self repetation.
28th July 2025: Parallelization in PDBM calculation and clear visulization for RVT plot as showing min amd max could be misleading. Adopted percentiles 10%-90% range.
"""
# Numeric imports
import sys
from icecream import ic
import numpy as np
import scipy as sc
import scipy.stats as sts
from scipy.optimize import newton
from astroquery.jplhorizons import Horizons
from astropy.time import Time
import astropy.units as u
import ephem
import seaborn as sns
import matplotlib.pyplot as plt
from datetime import datetime, date, timedelta
from io import BytesIO
from PIL import Image
# setup plot
# Set up plotting
plt.style.use("ggplot")
sns.set_palette("tab10")
# Function to show plots stored in memory
def show_plots(plot_image):
"""
Function show plots saved in memory
Args:
plot_image (BytesIO object):
Returns:
None
"""
img = Image.open(plot_image)
plt.imshow(img)
plt.axis("off")
plt.show()
return None
# Some Lists and Array for automization purposes
Inner_Planets = ["Mercury", "Venus", "Earth", "Mars"]
Outer_Planets = ["Jupiter", "Saturn", "Uranus", "Neptune"]
Space_Crafts = [
"Messenger",
"VEX",
"PSP",
"SolO",
"BepiCol",
"Spitzer",
"Wind",
"ST-A",
"ST-B",
"Kepler",
"Ulysses",
"MSL",
"Maven",
"Juno",
]
objects_list = Inner_Planets + Outer_Planets + Space_Crafts
# Function required to find DBM solution
def func(t, r0, r1, v0, gamma, w):
"""_summary_
Args:
t (_float_): time
r0 (_float_): initial postion of CME (km)
r1 (_float_): target position (km)
v0 (_float_): speed of CME at r0 (km/s)
gamma (_float_): drag parameter (km-1) (typically: 0.2e-7)
w (_float_): solar wind speed (km/s)
Returns:
_type_: _description_
"""
if v0 >= w:
gamma = gamma
else:
# only possible contion is v0<w.
gamma = -1 * gamma
p1 = 1 + gamma * (v0 - w) * t
y = -r1 + r0 + w * t + (np.log(p1) / gamma)
y1 = w + ((v0 - w) / p1)
return y, y1
# Wrapper function for y and y1.
"""
It is necessary for the DBM function.
If other solution is there then it need to be find.
calleable function can enhance the performance
"""
def func_y(t, r0, r1, v0, gamma, w):
y, _ = func(t, r0, r1, v0, gamma, w)
return y
def func_y1(t, r0, r1, v0, gamma, w):
_, y1 = func(t, r0, r1, v0, gamma, w)
return y1
# Wrapper function to get W and gamma.
def auto_w_gamma_func(PDBM, wind_type, N):
"""
This function generates the value of solar wind speed when auto_dbm is True.
PDF used in this function is from Mugatwala_et_al_2024.
Args:
N (int): Number of ensemble
PDBM (bool): Choice for PDBM. [True, False]
wind_type (str): Choice for solar wind type. ["Slow","Fast"]
Returns:
w_array, gamma_array if PDBM is set to True otherwise provides median value for w and gamma.
"""
if wind_type == "Slow":
w_array = np.clip(sts.norm.rvs(370.530847, 88.585045 / 3.0, size=N), 1, 1000)
else:
w_array = np.clip(sts.norm.rvs(579.057905, 67.870776 / 3.0, size=N), 1, 1000)
gamma_array = np.clip(
sts.lognorm.rvs(
0.6518007540612114 / 2.0,
-2.2727287735377082e-08,
9.425812152200486e-08,
size=N,
),
1.0e-09,
3.0e-7,
)
ic(
np.max(gamma_array),
np.mean(gamma_array),
np.median(gamma_array),
np.std(gamma_array),
)
if PDBM:
return w_array, gamma_array
else:
w_median = np.nanmedian(w_array)
gamma_median = np.nanmedian(gamma_array)
return w_median, gamma_median
# Function to plot RVT plot for DBM
def RV(t, r0, v0, gamma, w):
"""
Calculte the distance and speed under DBM approximation.
Args:
t (float): time at which r and v are supposed to calculate.
r0 (float): initial position (km)
v0 (float): speed at r0 (km/s)
gamma (float): drag parameter (km-1) [~0.2e-7]
w (float): solar wind speed (km/s) [~400]
Returns:
r,v (float,float): distance and speed at time t (km.km/s)
"""
gamma_signed = np.where(v0 >= w, gamma, -gamma)
p1 = 1 + gamma_signed * (v0 - w) * t
r = r0 + w * t + (np.log(p1) / gamma_signed)
v = w + ((v0 - w) / p1)
return r, v
def DBM_RVT_plot(time_utc, TT, r0, v0, gamma, w, r_target, tdate):
"""
Make distance-speed-time (R-V-T) plot for a point of interest on CME leading edge.
Units on plot canvas: R [Solar radii], V[km/s], T[date]
Args:
time_utc (datetime object): time when CME is at r0
TT (float): Transit time [hrs]
r0 (float): initial position of CME [km]
v0 (float): speed at r0 [km/s]
gamma (float):
w (float): _description_
r_target (float): target distanec [AU]
tdate (datetime object): CME arrival time
Returns:
RVT plot as BytesIO object
"""
dt = 3600 # unit is second
t_ary = np.arange(0, TT * 1.1 * 3600, 80)
Time = [time_utc + timedelta(seconds=i) for i in t_ary]
R, V = RV(t_ary, r0, v0, gamma, w)
R = (R * u.km).to(u.R_sun).value
r_target = (r_target * u.au).to(u.R_sun).value
fig, ax1 = plt.subplots(figsize=(12, 8))
plt.grid()
color = "tab:red"
ax1.set_xlabel("time (UTC date hour)", fontsize=17)
ax1.set_ylabel("R (solar radius)", color=color, fontsize=17)
ax1.plot(Time, R, color=color, label="Distance")
ax1.axvline(tdate, linestyle="--", color="black", label="Arrival Time")
ax1.axhline(r_target, label=f"R_target = {r_target:.2f}")
ax1.tick_params(axis="y", labelcolor=color, labelsize=17)
ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis
color = "tab:cyan"
# we already handled the x-label with ax1
ax2.set_ylabel("V (km/s)", color=color, fontsize=17)
ax2.plot(Time, V, color=color, label="Speed")
ax2.tick_params(axis="y", labelcolor=color, labelsize=17)
fig.tight_layout() # otherwise the right y-label is slightly clipped
lines_1, labels_1 = ax1.get_legend_handles_labels()
lines_2, labels_2 = ax2.get_legend_handles_labels()
lines = lines_1 + lines_2
labels = labels_1 + labels_2
ax1.legend(lines, labels, fontsize=17, loc=3)
plt.grid(True)
plt.title("R-V-T Plot")
# Save the plot to an in-memory buffer
buffer = BytesIO()
plt.savefig(buffer, format="png", dpi=300, bbox_inches="tight")
buffer.seek(0) # Move to the start of the buffer
plt.close() # Close the plot to free resources
return buffer
def PDBM_RVT_plot(
time_utc, TT_array, r0, v0_array, gamma_array, w_array, r_target, tdate
):
"""
Same purpose as @DBM_RVT_plot. Few inputs are changed to accomodate PDBM output, while rest remains the same.
Args:
TT_array (np.array): Transit time array
v0_array (np.array): Initial speed array
gamma_array (np.array):
w_array (np.array):
"""
TT = np.nanmedian(TT_array)
t_ary = np.arange(0, TT * 1.1 * 3600, 80)
Time = [time_utc + timedelta(seconds=i) for i in t_ary]
i_array = np.arange(0, len(v0_array), 1)
R_matrix = np.zeros((len(v0_array), len(t_ary)))
V_matrix = np.zeros((len(v0_array), len(t_ary)))
for v0, w, g, i in zip(v0_array, w_array, gamma_array, i_array):
y, y1 = RV(t_ary, r0, v0, g, w)
y = (y * u.km).to(u.R_sun).value
R_matrix[i] = y
V_matrix[i] = y1
r_target = (r_target * u.au).to(u.R_sun).value
R_median = np.nanmedian(R_matrix, axis=0)
V_median = np.nanmedian(V_matrix, axis=0)
R_p10 = np.nanpercentile(R_matrix, 10, axis=0)
R_p90 = np.nanpercentile(R_matrix, 90, axis=0)
R_q25 = np.nanpercentile(R_matrix, 25, axis=0)
R_q75 = np.nanpercentile(R_matrix, 75, axis=0)
R_max = np.max(R_matrix, axis=0)
R_min = np.min(R_matrix, axis=0)
V_max = np.max(V_matrix, axis=0)
V_min = np.min(V_matrix, axis=0)
V_p10 = np.nanpercentile(V_matrix, 10, axis=0)
V_p90 = np.nanpercentile(V_matrix, 90, axis=0)
V_q25 = np.nanpercentile(V_matrix, 25, axis=0)
V_q75 = np.nanpercentile(V_matrix, 75, axis=0)
# ic(V_max)
# ic(V_min)
fig, ax1 = plt.subplots(figsize=(10, 6))
plt.grid()
color = "tab:red"
ax1.set_xlabel("time (UTC date hour)", fontsize=17)
ax1.set_ylabel("R (solar radius)", color=color, fontsize=17)
ax1.plot(Time, R_median, color=color, label="Distance")
ax1.fill_between(Time, R_q25, R_q75, alpha=0.40, linewidth=0, color=color)
ax1.fill_between(Time, R_p10, R_p90, alpha=0.25, linewidth=0, color=color)
ax1.fill_between(Time, R_max, R_min, alpha=0.15, linewidth=0, color=color)
ax1.axvline(tdate, linestyle="--", color="black", label="Arrival Time")
ax1.axhline(r_target, label=f"R_target = {r_target:.2f}")
ax1.tick_params(axis="y", labelcolor=color)
ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis
color = "tab:cyan"
# we already handled the x-label with ax1
ax2.set_ylabel("V (km/s)", color=color, fontsize=17)
ax2.plot(Time, V_median, color=color, label="Speed")
ax2.fill_between(Time, V_q25, V_q75, alpha=0.4, linewidth=0, color=color)
ax2.fill_between(Time, V_p10, V_p90, alpha=0.25, linewidth=0, color=color)
ax2.fill_between(Time, V_max, V_min, alpha=0.15, linewidth=0, color=color)
ax2.tick_params(axis="y", labelcolor=color)
fig.tight_layout() # otherwise the right y-label is slightly clipped
lines_1, labels_1 = ax1.get_legend_handles_labels()
lines_2, labels_2 = ax2.get_legend_handles_labels()
lines = lines_1 + lines_2
labels = labels_1 + labels_2
ax1.legend(lines, labels, fontsize=17, loc=3)
plt.grid(True)
plt.title("R-V-T Plot")
# Save the plot to an in-memory buffer
buffer = BytesIO()
plt.savefig(buffer, format="png", dpi=300, bbox_inches="tight")
buffer.seek(0) # Move to the start of the buffer
plt.close() # Close the plot to free resources
return buffer
def TT_plot(T):
"""
Function to plot transit time distribution when PDBM calculations are performed.
Args:
T (np.array): Transit time array
Returns:
ByteIO object
"""
mean = np.nanmean(T)
median = np.nanmedian(T)
plt.hist(T, bins=50, density=True)
plt.xlim(np.nanmin(T), np.nanmax(T))
plt.axvline(mean, color="red", label=f"Mean: {mean:.2f} hr ")
plt.axvline(median, color="black", label=f"Median: {median:.2f} hr ")
plt.title("Transit Time Distribution")
plt.xlabel("Transit Time (hrs)")
plt.xlim(0, np.nanmax(T))
plt.legend(fontsize=14)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
# Save the plot to an in-memory buffer
buffer = BytesIO()
plt.savefig(buffer, format="png", dpi=300, bbox_inches="tight")
buffer.seek(0) # Move to the start of the buffer
plt.close() # Close the plot to free resources
return buffer
def V_plot(V):
"""
Function to plot transit speed distribution when PDBM calculations are performed.
Args:
V (np.array): Transit speed array
Returns:
ByteIO object
"""
mean = np.nanmean(V)
median = np.nanmedian(V)
plt.hist(V, bins=50, density=True)
plt.xlim(np.nanmin(V), np.nanmax(V))
plt.axvline(mean, color="red", label=f"Mean: {mean:.2f} km/s ")
plt.axvline(median, color="black", label=f"Median: {median:.2f} km/s ")
plt.title("Arrival Speed Distribution")
plt.xlabel("Arrival Speed (km/s)")
plt.legend(fontsize=14)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
# Save the plot to an in-memory buffer
buffer = BytesIO()
plt.savefig(buffer, format="png", dpi=300, bbox_inches="tight")
buffer.seek(0) # Move to the start of the buffer
plt.close() # Close the plot to free resources
return buffer
"""
-------------------------------------------------------------------------------
__ _______ ___.______ ___ _______ .______ .___ ___.
/_ | | \ / /| _ \ \ \ | \ | _ \ | \/ |
| | | .--. | | | | |_) | | || .--. || |_) | | \ / |
| | | | | | | | | ___/ | || | | || _ < | |\/| |
| | | '--' | | | | | | || '--' || |_) | | | | |
|_| |_______/ | | | _| | ||_______/ |______/ |__| |__|
\__\ /__/
-------------------------------------------------------------------------------
"""
# Function to find DBM solution.
"""
This function provides transist time and impact speed
of CME under DBM approximation
"""
def DBM(r0, r1, v0, gamma, w):
"""
This is main function to determine the transit time and speed of CME under DBM approximation.
Args:
r0 (float): initial position (km)
r1 (float): target distance (km)
v0 (float): speed at r0 (km/s)
gamma (float): drag parameter (km-1) [~0.2e-7]
w (float): solar wind speed (km/s) [~400]
Returns:
t1 (float) : transit time of CME (hrs)
v1 (float) : transit speed of CME (km/s)
"""
t1 = newton(
func=func_y,
fprime=func_y1,
x0=30 * 3600,
args=[r0, r1, v0, gamma, w],
disp=False,
maxiter=30,
)
dv = v0 - w
p1 = 1 + (gamma * np.abs(dv) * t1)
v1 = w + (dv / p1)
# Transit time is in hours and impact speed is in km/s.
return t1 / 3600.0, v1
def PDBM(r0, dr0, r1, v0, dv0, gamma_array, wind_array, dt0, N):
"""
This function perform PDBM calculations.
Args:
r0 (float): initial position (km)
dr0 (float): uncertainity in r0 (km)
r1 (float): target distance (km)
v0 (float): speed at r0 (km/s)
dv0 (floar): uncertainity in v0 (km/s)
gamma_array (list / numpy array): collection of gamma values either from PDF or manual
wind_array (list / numpy array ): collection of w values
dt0 (float): uncertainity in t0 (s)
N (int): number of ensembels
Returns:
TT_array (numpy array): collection of transit time (values are in hours)
V_array (numpy array): collection of transit speed (values are in km/s)
V0_array (numpy array): collection of v0 used in calculation.
"""
r0_array = np.random.normal(r0, dr0 / 3.0, N)
v0_array = np.random.normal(v0, dv0 / 3.0, N)
r1_array = np.random.normal(
r1, 0.05 * r1 / 3.0, N
) # including 5% error in the target distace
t0_array = np.random.normal(0, dt0 / (60.0 * 3), N)
# Arrays to store Output
TT_array = np.zeros_like(r0_array)
V_array = np.zeros_like(r0_array)
for i in range(0, N):
TT_array[i], V_array[i] = DBM(
r0_array[i], r1_array[i], v0_array[i], gamma_array[i], wind_array[i]
)
TT_array[i] = TT_array[i] + t0_array[i]
return TT_array, V_array, v0_array
# Function for 2D DBM
"""
.------------------------------------------------------------------.
| ,---. ,------. ,-.,------.,-. ,------. ,-----. ,--. ,--.|
|'.-. \| .-. \ / .'| .--. '. \| .-. \ | |) /_| `.' ||
| .-' .'| | \ : | | | '--' || | | \ :| .-. \ |'.'| ||
|/ '-.| '--' / | | | | --' | | '--' /| '--' / | | ||
|'-----'`-------' \ '.`--' .' /`-------' `------'`--' `--'|
| `-' `-' |
'------------------------------------------------------------------'
"""
"""
while moving to 2D version of model,one has to consider two important variable.
(1) CME Propagation Direction
(2) Target longitude.
The absolute difference of these two quantity is called alpha.
Also, CME propagation direction has been measured with respect to the Earth in cone geometry.
Therefore, we also need to consider coordinate system.
"""
# Correction in central meridian as per Heliocentric Ecliptic coordinate system.
"""
We are doing this because we are using JPL Horiozn for ephemeris to determine target information.
In JPL Horizon Heliocentric ecliptic coordinate system is used so position of Earth is not Fixed.
While in cone model Heliocentric Stonyhurst coordinate system is used where Sun-Earth line is always
correspond to the 0$^o$ longitude.
"""
def Phi_Correction(phi_cme, time_utc):
"""
Args:
phi_cme (float): central meridian of CME [deg]
time_utc (datetime object): time correspond to r0
Return:
phi_corrected (float): corrected central meridian of CME
"""
earth = ephem.Sun()
earth.compute(time_utc)
phi_corrected = np.rad2deg(np.deg2rad(phi_cme) + earth.hlon)
return phi_corrected
"""
For 2D cone, There are 3 possiblities (see Schwenn et al, 2005)
(1) ICME leading edge is concentric arc with solar surface. keyword: ["CC", "Concentric Cone"]
The application of this geometry is same as 1D DBM.
(2) ICME leading edge is semi circle. keyword: [""IC", "Ice-Cream Cone"]
This geometry looks like a ice cream cone
(3) ICME leading edge is circular arc and tangentially connect to the ICME legs. keyword: ["TC", "Tangential Cone"]
Application of this geometry is bit difficult.
"""
"""
When we consider a geometry, possiblity of two different type of evolution is arise.
(1) Self Similar Expansion: CME maintain it's shape during propagation. keyword: ["SSE", "Self-Similar Expansion"]
(2) Flattening Cone Evolution: Each and every point on CME edge follows DBM. keyword: ["FCE", "Flattening Cone Evolution"]
For more detailed informatio: Check the documantation.
"""
# Function to calculate speed and distance at alpha angle
# ICE Cream Cone only
def IC_RV_alpha(omega, alpha, r0, v0):
"""
Provides ditance and speed of CME point located at angle alpha under Ice-Cream cone approximation.
Args:
omega (float): half angular windth of cone [deg]
alpha (float): interested angle on CME leading edge
r0 (float): CME apex position
v0 (float): CME apex speed
Returns:
r01,v01 (float): distance and speed of CME point at angle alpha.
"""
omega = np.deg2rad(omega)
alpha = np.deg2rad(alpha)
# tan_omega = np.tan(omega)
# sin_alpha = np.sin(alpha)
# cos_alpha = np.cos(alpha)
# sqrt_term = np.sqrt(tan_omega**2 - sin_alpha**2)
# factor = (cos_alpha + sqrt_term) / (1 + tan_omega)
# # ic(factor)
r01 = (
r0
* (np.cos(alpha) + ((np.tan(omega)) ** 2 - (np.sin(alpha)) ** 2) ** 0.5)
/ (1 + np.tan(omega))
)
v01 = (
v0
* (np.cos(alpha) + ((np.tan(omega)) ** 2 - (np.sin(alpha)) ** 2) ** 0.5)
/ (1 + np.tan(omega))
)
# r01 = r0 * factor
# v01 = v0 * factor
return r01, v01
def IC_R_alpha_inv(omega, alpha, r1):
"""
This function determines the CME apex distance from distance of alpha element under Ice-Cream Cone approximation.
Args:
omega (float): half angular width of CME cone
alpha (float): angular seperation of considered element from the apex
r1 (float): distance of considered element on CME leading edge.
Returns:
r1_apex (float): distance of CME apex point
"""
omega = np.deg2rad(omega)
alpha = np.deg2rad(alpha)
r1_apex = (
r1
* (1 + np.tan(omega))
/ ((np.cos(alpha)) + (((np.tan(omega)) ** 2.0 - (np.sin(alpha)) ** 2.0) ** 0.5))
)
return r1_apex
def TC_RV_alpha(omega, alpha, r0, v0):
"""
same as @IC_RV_alpha but consider tangential cone.
"""
omega = np.deg2rad(omega)
alpha = np.deg2rad(alpha)
r01 = (
r0
* (np.cos(alpha) + ((np.sin(omega)) ** 2 - (np.sin(alpha)) ** 2) ** 0.5)
/ (1 + np.sin(omega))
)
v01 = (
v0
* (np.cos(alpha) + ((np.sin(omega)) ** 2 - (np.sin(alpha)) ** 2) ** 0.5)
/ (1 + np.sin(omega))
)
return r01, v01
def TC_R_alpha_inv(omega, alpha, r1):
"""
same as @IC_R_alpha_inv but consider tangential cone.
"""
omega = np.deg2rad(omega)
alpha = np.deg2rad(alpha)
r1_apex = (
r1
* (1 + np.sin(omega))
/ ((np.cos(alpha)) + (((np.sin(omega)) ** 2.0 - (np.sin(alpha)) ** 2.0) ** 0.5))
)
return r1_apex
def DBM_2D_RVT_plot(
time_utc,
TT,
r0,
v0,
gamma,
w,
r_target,
tdate,
omega,
phi_cme,
phi_target,
cone_geometry,
kinematic,
):
"""
Same functionality as @DBM_RVT_plot but for 2D.
Majority of inputs and output are same. Few are added for 2D consideration.
Args:
omega (float): half angular width of CME [deg]
phi_cme (float): central meridian of CME [deg]
phi_target (float): logitude of target [deg]
cone_geometry (str): type of cone
kinematic (str): kinematic approach for CME propagation.
Raises:
ValueError: unknown cone geometry during SSE
ValueError: unknown cone geometry during FCE
ValueError: unknown kinematic approach
Optimization over functions:
DBM_2D_RVT_IC_SSE_plot,
DBM_2D_RVT_TC_SSE_plot,
DBM_2D_RVT_IC_FCE_plot,
DBM_2D_RVT_TC_FCE_plot
"""
alpha = np.abs(phi_target - phi_cme)
t_ary = np.arange(0, TT * 1.1 * 3600, 80)
Time = [time_utc + timedelta(seconds=i) for i in t_ary]
r_target = (r_target * u.au).to(u.R_sun).value
# This is main part to define which kind of initial transformation has to be used.
if kinematic in ["SSE", "Self-Similar Expansion"]:
R, V = RV(t_ary, r0, v0, gamma, w)
R = (R * u.km).to(u.R_sun).value
if cone_geometry in ["IC", "Ice-Cream Cone"]:
R_ary, V_ary = IC_RV_alpha(omega, alpha, R, V)
elif cone_geometry in ["TC", "Tangential Cone"]:
R_ary, V_ary = TC_RV_alpha(omega, alpha, R, V)
elif cone_geometry in ["CC", "Concentric Cone"]:
R_ary = R.copy()
V_ary = V.copy()
# ic(R_ary, V_ary)
else:
raise ValueError(f"Unknown Cone Geometry: {cone_geometry}")
elif kinematic in ["FCE", "Flattening Cone Evolution"]:
if cone_geometry in ["IC", "Ice-Cream Cone"]:
R0_a, V0_a = IC_RV_alpha(omega, alpha, r0, v0)
elif cone_geometry in ["TC", "Tangential Cone"]:
R0_a, V0_a = TC_RV_alpha(omega, alpha, r0, v0)
elif cone_geometry in ["CC", "Concentric Cone"]:
R0_a, V0_a = r0, v0
else:
raise ValueError(f"Unknown Cone Geometry: {cone_geometry}")
R, V = RV(t_ary, R0_a, V0_a, gamma, w)
R_ary, V_ary = (R * u.km).to(u.R_sun).value, V
else:
raise ValueError(f"Unknown Kinematic Approach: {kinematic}")
fig, ax1 = plt.subplots(figsize=(10, 6))
plt.grid()
color_dist = "tab:red"
color_speed = "tab:cyan"
ax1.set_xlabel("time (UTC date hour)", fontsize=17)
ax1.set_ylabel("R (solar radius)", color=color_dist, fontsize=17)
ax1.plot(Time, R_ary, color=color_dist, label="Distance")
ax1.axvline(tdate, linestyle="--", color="black", label="Arrival Time")
ax1.axhline(r_target, label=f"R_target = {r_target:.2f}")
ax1.tick_params(axis="y", labelcolor=color_dist)
ax2 = ax1.twinx()
ax2.set_ylabel("V (km/s)", color=color_speed, fontsize=17)
ax2.plot(Time, V_ary, color=color_speed, label="Speed")
ax2.tick_params(axis="y", labelcolor=color_speed)
fig.tight_layout()
# Combine legends
lines_1, labels_1 = ax1.get_legend_handles_labels()
lines_2, labels_2 = ax2.get_legend_handles_labels()
ax1.legend(
lines_1 + lines_2,
labels_1 + labels_2,
fontsize=17,
)
plt.grid(True)
plt.title("2D RVT Plot", fontsize=17)
plt.tight_layout()
# Save to buffer
buffer = BytesIO()
plt.savefig(buffer, format="png", dpi=300, bbox_inches="tight")
buffer.seek(0)
plt.close()
return buffer
def PDBM_2D_RVT_plot(
time_utc,
TT_array,
r0,
v0_array,
gamma_array,
w_array,
r_target,
tdate,
omega_array,
phi_cme_array,
phi_target,
cone_geometry,
kinematic,
):
"""
same application DBM_2D_RVT_plot but for probabilistic case.
Inputs are changed to accomodate the PDBM results.
Args:
TT_array (np.array): transit time array
v0_array (np.array): initial speed array
gamma_array (np.array):
w_array (np.array):
omega_array (np.array): half angular width array
phi_cme_array (np.array): CME central meridian array
"""
TT = np.nanmedian(TT_array)
# ic(r0)
t_ary = np.arange(0, TT * 1.1 * 3600, 80)
# ic(t_ary / 3600)
Time = [time_utc + timedelta(seconds=i) for i in t_ary]
r_target = (r_target * u.au).to(u.R_sun).value
alpha_array = np.abs(phi_cme_array - phi_target)
# ic(alpha_array)
# ic(omega_array)
# ic(v0_array)
# ic(gamma_array)
# ensure each alpha[i] ≤ omega_array[i]
# alpha_array = np.minimum(alpha_array, omega_array)
i_array = np.arange(0, len(v0_array), 1)
R_matrix = np.zeros((len(v0_array), len(t_ary)))
V_matrix = np.zeros((len(v0_array), len(t_ary)))
# This is main part to define which kind of initial transformation has to be used.
if kinematic in ["SSE", "Self-Similar Expansion"]:
for v0, w, g, omeg, alph, i in zip(
v0_array, w_array, gamma_array, omega_array, alpha_array, i_array
):
# ic(v0, w, g, omeg, alph)
R, V = RV(t_ary, r0, v0, g, w)
R = (R * u.km).to(u.R_sun).value
# ic(V)
if cone_geometry in ["IC", "Ice-Cream Cone"]:
R_ary, V_ary = IC_RV_alpha(omeg, alph, R, V)
# ic(V_ary)
elif cone_geometry in ["TC", "Tangential Cone"]:
R_ary, V_ary = TC_RV_alpha(omeg, alph, R, V)
elif cone_geometry in ["CC", "Concentric Cone"]:
R_ary = R.copy()
V_ary = V.copy()
# ic(V_ary)
else:
raise ValueError(f"Unknown Cone Geometry: {cone_geometry}")
R_matrix[i], V_matrix[i] = R_ary, V_ary
# ic(i, v0, np.round(V[:5], 1), np.round(V_ary[:5], 1))
elif kinematic in ["FCE", "Flattening Cone Evolution"]:
for v0, w, g, omeg, alph, i in zip(
v0_array, w_array, gamma_array, omega_array, alpha_array, i_array
):
if cone_geometry in ["IC", "Ice-Cream Cone"]:
R0_a, V0_a = IC_RV_alpha(omeg, alph, r0, v0)
elif cone_geometry in ["TC", "Tangential Cone"]:
R0_a, V0_a = TC_RV_alpha(omeg, alph, r0, v0)
elif cone_geometry in ["CC", "Concentric Cone"]:
R0_a, V0_a = r0, v0
else:
raise ValueError(f"Unknown Cone Geometry: {cone_geometry}")
R, V = RV(t_ary, R0_a, V0_a, g, w)
R_ary, V_ary = (R * u.km).to(u.R_sun).value, V
R_matrix[i], V_matrix[i] = R_ary, V_ary
else:
raise ValueError(f"Unknown Kinematic Approach: {kinematic}")
R_median = np.nanmedian(R_matrix, axis=0)
V_median = np.nanmedian(V_matrix, axis=0)
R_p10 = np.nanpercentile(R_matrix, 10, axis=0)
R_p90 = np.nanpercentile(R_matrix, 90, axis=0)
R_q25 = np.nanpercentile(R_matrix, 25, axis=0)
R_q75 = np.nanpercentile(R_matrix, 75, axis=0)
R_max = np.max(R_matrix, axis=0)
R_min = np.min(R_matrix, axis=0)
V_max = np.max(V_matrix, axis=0)
V_min = np.min(V_matrix, axis=0)
V_p10 = np.nanpercentile(V_matrix, 10, axis=0)
V_p90 = np.nanpercentile(V_matrix, 90, axis=0)
V_q25 = np.nanpercentile(V_matrix, 25, axis=0)
V_q75 = np.nanpercentile(V_matrix, 75, axis=0)
fig, ax1 = plt.subplots(figsize=(10, 6))
color_dist = "tab:red"
color_speed = "tab:cyan"
ax1.set_xlabel("time (UTC date hour)", fontsize=17)
ax1.set_ylabel("R (solar radius)", color=color_dist, fontsize=17)
ax1.plot(Time, R_median, color=color_dist, label="Distance")
ax1.fill_between(Time, R_q25, R_q75, alpha=0.40, linewidth=0, color=color_dist)
ax1.fill_between(Time, R_p10, R_p90, alpha=0.25, linewidth=0, color=color_dist)
ax1.fill_between(Time, R_min, R_max, alpha=0.15, linewidth=0, color=color_dist)
ax1.axvline(tdate, linestyle="--", color="black", label="Arrival Time")
ax1.axhline(r_target, label=f"R_target = {r_target:.2f}")
ax1.tick_params(axis="y", labelcolor=color_dist)
ax1.grid(True)
ax2 = ax1.twinx()
ax2.grid(False)
ax2.set_ylabel("V (km/s)", color=color_speed, fontsize=17)
ax2.plot(Time, V_median, color=color_speed, label="Speed")
ax2.fill_between(Time, V_q25, V_q75, alpha=0.4, linewidth=0, color=color_speed)
ax2.fill_between(Time, V_p10, V_p90, alpha=0.25, linewidth=0, color=color_speed)
ax2.fill_between(Time, V_min, V_max, alpha=0.15, linewidth=0, color=color_speed)
ax2.tick_params(axis="y", labelcolor=color_speed)
fig.tight_layout()
# Combine legends
lines_1, labels_1 = ax1.get_legend_handles_labels()
lines_2, labels_2 = ax2.get_legend_handles_labels()
ax1.legend(
lines_1 + lines_2,
labels_1 + labels_2,
fontsize=17,
)
plt.title("2D RVT Plot", fontsize=17)
plt.tight_layout()
# Save to buffer
buffer = BytesIO()
plt.savefig(buffer, format="png", dpi=300, bbox_inches="tight")
buffer.seek(0)
plt.close()
return buffer
# def DBM_2D_RVT_IC_SSE_plot(
# time_utc, TT, r0, v0, gamma, w, r_target, tdate, omega, alpha
# ):
# t_ary = np.arange(0, TT * 1.1 * 3600, 80)
# Time = [time_utc + timedelta(seconds=i) for i in t_ary]
# R, V = RV(t_ary, r0, v0, gamma, w)
# R = (R * u.km).to(u.R_sun).value
# r_target = (r_target * u.au).to(u.R_sun).value
# R_ary, V_ary = IC_RV_alpha(omega, alpha, R, V)
# plt.style.use("seaborn-v0_8-darkgrid")
# fig, ax1 = plt.subplots(figsize=(10, 6))
# plt.grid()
# color = "tab:red"
# ax1.set_xlabel("time (UTC date hour)", fontsize=17)
# ax1.set_ylabel("R (solar radius)", color=color, fontsize=17)
# ax1.plot(Time, R_ary, color=color, label="Distance")
# ax1.axvline(tdate, linestyle="--", color="black", label="Arrival Time")
# ax1.axhline(r_target, label=f"R_target = {r_target:.2f}")
# ax1.tick_params(axis="y", labelcolor=color)
# ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis
# color = "tab:cyan"
# # we already handled the x-label with ax1
# ax2.set_ylabel("V (km/s)", color=color, fontsize=17)
# ax2.plot(Time, V_ary, color=color, label="Speed")
# ax2.tick_params(axis="y", labelcolor=color)
# fig.tight_layout() # otherwise the right y-label is slightly clipped
# lines_1, labels_1 = ax1.get_legend_handles_labels()
# lines_2, labels_2 = ax2.get_legend_handles_labels()
# lines = lines_1 + lines_2
# labels = labels_1 + labels_2
# ax1.legend(lines, labels, fontsize=17, loc=3)
# plt.grid(True)
# # Save the plot to an in-memory buffer
# buffer = BytesIO()
# plt.savefig(buffer, format="png")
# buffer.seek(0) # Move to the start of the buffer
# plt.close() # Close the plot to free resources
# return buffer
# def DBM_2D_RVT_IC_FCE_plot(
# time_utc, TT, r0, v0, gamma, w, r_target, tdate, omega, alpha
# ):
# t_ary = np.arange(0, TT * 1.1 * 3600, 80)
# Time = [time_utc + timedelta(seconds=i) for i in t_ary]
# R0_a, V0_a = IC_RV_alpha(omega, alpha, r0, v0)
# R, V = RV(t_ary, R0_a, V0_a, gamma, w)
# R = (R * u.km).to(u.R_sun).value
# r_target = (r_target * u.au).to(u.R_sun).value
# plt.style.use("seaborn-v0_8-darkgrid")
# fig, ax1 = plt.subplots(figsize=(10, 6))
# plt.grid()
# color = "tab:red"
# ax1.set_xlabel("time (UTC date hour)", fontsize=17)
# ax1.set_ylabel("R (solar radius)", color=color, fontsize=17)
# ax1.plot(Time, R, color=color, label="Distance")
# ax1.axvline(tdate, linestyle="--", color="black", label="Arrival Time")
# ax1.axhline(r_target, label=f"R_target = {r_target:.2f}")
# ax1.tick_params(axis="y", labelcolor=color)
# ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis
# color = "tab:cyan"
# # we already handled the x-label with ax1