-
Notifications
You must be signed in to change notification settings - Fork 1
/
classes.py
3336 lines (2853 loc) · 132 KB
/
classes.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Defines the following classes:
- JetModel: Handles all radiative transfer and physical calculations of
physical jet model grid.
- ModelRun: Handles all interactions with CASA and execution of a full run
- Pointing (deprecated)
- PoitingScheme (deprecated)
@author: Simon Purser (simonp2207@gmail.com)
"""
import sys
import os
import time
import pickle
from typing import Union, Callable, List, Tuple, Dict
import numpy.typing as npt
import numpy as np
import tabulate
import astropy.units as u
import scipy.constants as con
from astropy.coordinates import SkyCoord
from astropy.io import fits
from matplotlib.colors import LogNorm
from RaJePy import logger
from RaJePy import _config as cfg
from RaJePy.maths import geometry as mgeom
from RaJePy.maths import physics as mphys
from RaJePy.maths import rrls as mrrl
from RaJePy.miscellaneous import functions as miscf
from RaJePy.plotting import functions as pfunc
from warnings import filterwarnings
filterwarnings("ignore", category=RuntimeWarning)
# noinspection PyCallingNonCallable
class JetModel:
"""
Class to handle physical model of an ionised jet from a young stellar object
"""
_arr_indexing = 'ij' # numpy.meshgrid indexing type
@classmethod
def load_model(cls, model_file: str) -> "JetModel":
"""
Loads model from a saved state (pickled file)
Parameters
----------
cls : JetModel
DESCRIPTION.
model_file : str
Full path to saved model file.
Returns
-------
new_jm : JetModel
Instance of JetModel to work with.
"""
# Get the model parameters from the saved model file
model_file = os.path.expanduser(model_file)
loaded = pickle.load(open(model_file, 'rb'))
# Create new JetModel class instance
if 'log' in loaded:
new_jm = cls(loaded["params"], log=loaded['log'])
else:
dcy_ = os.path.expanduser('~')
new_jm = cls(loaded["params"],
log=logger.Log(dcy_ + os.sep + 'temp.log'))
# If fill factors/projected areas have been previously calculated,
# assign to new instance
if loaded['ffs'] is not None:
new_jm._ff = loaded['ffs']
if loaded['areas'] is not None:
new_jm._areas = loaded['areas']
new_jm.time = loaded['time']
return new_jm
@staticmethod
def lz_to_grid_dims(params: Dict) -> Tuple[int, int, int]:
cs_au = params["grid"]["c_size"]
i_rads = np.radians(params["geometry"]["inc"])
pa_rads = np.radians(params["geometry"]["pa"])
l_xz_au = params['grid']['l_z'] * params['target']['dist']
xmax_au = l_xz_au * np.sin(pa_rads)
ymax_au = l_xz_au * np.tan(1.571 - i_rads)
zmax_au = l_xz_au * np.cos(pa_rads)
rmax_au, _, __ = mgeom.xyz_to_rwp(xmax_au, ymax_au, zmax_au,
params["geometry"]["inc"],
params["geometry"]["pa"])
wmax_au = mgeom.w_r(rmax_au,
params["geometry"]["w_0"],
params["geometry"]["mod_r_0"],
params["geometry"]["r_0"],
params["geometry"]["epsilon"])
wmax_cells = int(np.ceil(np.abs(wmax_au / cs_au)))
nx = int(np.ceil(np.abs(xmax_au / cs_au)))
ny = int(np.ceil(np.abs(ymax_au / cs_au)))
nz = int(np.ceil(np.abs(zmax_au / cs_au)))
# Make sure jet's width within cell grid. Especially pertinent if
# inclination or position angles are 0, 90, 180 or 270 deg
nx, ny, nz = [n + 2 * wmax_cells for n in (nx, ny, nz)]
# Enforce even number of cells in x, y and z dimensions
nx, ny, nz = [_ if _ % 2 == 0 else _ + 1 for _ in (nx, ny, nz)]
return nx, ny, nz
@staticmethod
def py_to_dict(py_file: str) -> Dict:
"""
Convert .py file (full path as str) containing relevant model parameters
to dict
"""
if not os.path.exists(py_file):
raise FileNotFoundError(py_file + " does not exist")
if os.path.dirname(py_file) not in sys.path:
sys.path.append(os.path.dirname(py_file))
jp = __import__(os.path.basename(py_file).rstrip('.py'))
err = miscf.check_model_params(jp.params)
if err is not None:
raise err
sys.path.remove(os.path.dirname(py_file))
return jp.params
def __init__(self, params: Union[dict, str],
log: Union[None, logger.Log] = None):
"""
Parameters
----------
params : dict
dictionary containing all necessary parameters to describe
physical jet model
log: logger.Log
Log instance to handle all log messages
"""
# Import jet parameters
if isinstance(params, dict):
self._params = params
elif isinstance(params, str):
self._params = JetModel.py_to_dict(params)
else:
raise TypeError("Supplied arg params must be dict or file path ("
"str)")
self._name = self.params['target']['name']
self._csize = self.params['grid']['c_size']
# Automatically calculated parameters
mr0 = mgeom.mod_r_0(self._params['geometry']['opang'],
self._params['geometry']['epsilon'],
self._params['geometry']['w_0'])
q_n = mphys.q_n(self._params["geometry"]["epsilon"],
self._params["power_laws"]["q_v"])
q_tau = mphys.q_tau(self._params["geometry"]["epsilon"],
self._params["power_laws"]["q_x"],
q_n,
self._params["power_laws"]["q_T"])
self._params["geometry"]["mod_r_0"] = mr0
self._params["power_laws"]["q_n"] = q_n
self._params["power_laws"]["q_tau"] = q_tau
if log is not None:
self._log = log
else:
self._log = logger.Log(os.path.expanduser('~') + os.sep +
'temp.log', verbose=True)
# Determine number of cells in x, y, and z-directions
if self.params['grid']['l_z'] is not None:
nx, ny, nz = JetModel.lz_to_grid_dims(self.params)
self.log.add_entry("INFO",
'For a (bipolar) jet length of {:.1f}", cell '
'size of {:.2f}au and distance of {:.0f}pc, a '
'grid size of (n_x, n_y, n_z) = ({}, {}, {}) '
'voxels is calculated'
''.format(self.params['grid']['l_z'],
self.params["grid"]["c_size"],
self.params["target"]["dist"],
nx, ny, nz))
else:
# Enforce even number of cells in every direction
nx = (self.params['grid']['n_x'] + 1) // 2 * 2
ny = (self.params['grid']['n_y'] + 1) // 2 * 2
nz = (self.params['grid']['n_z'] + 1) // 2 * 2
self.params['grid']['n_x'] = nx
self.params['grid']['n_y'] = ny
self.params['grid']['n_z'] = nz
self._nx = nx # number of cells in x
self._ny = ny # number of cells in y
self._nz = nz # number of cells in z
# Create necessary class-instance attributes for all necessary grids
self._ff = None # cell fill factors
self._areas = None # cell projected areas along y-axis
self._idxs = None # Grid of cell indices
self._grid = None # grid of cell-centre positions
self._rwp = None # Grid of cells' centroids' r, w, p coordinates
self._rreff = None # grid of cell-centre r_eff-coordinates
self._ts = None # grid of cell-material times since launch
self._m = None # grid of cell-masses
self._nd = None # grid of cell number densities
self._xi = None # grid of cell ionisation fractions
self._temp = None # grid of cell temperatures
self._v = None # 3-tuple of cell x, y and z velocity components
self._ss_jml_rb_frac = self.params["properties"]["mlr_rj"] / \
self.params["properties"]["mlr_bj"]
self._ss_jml_bj = self.params["properties"]["mlr_bj"]
self._ss_jml_bj *= 1.989e30 / con.year
self._ss_jml_rj = self._ss_jml_bj * self._ss_jml_rb_frac
n_0 = mphys.n_0_from_mlr(self.params["properties"]["mlr_bj"],
self.params["properties"]["v_0"],
self.params["geometry"]["w_0"],
self.params["properties"]["mu"],
self.params["power_laws"]["q^d_n"],
self.params["power_laws"]["q^d_v"],
self.params["target"]["R_1"],
self.params["target"]["R_2"])
self.params["properties"]["n_0"] = n_0
# For asymmetry
self._jml_t_bj = lambda t: self._ss_jml_bj
self._jml_t_rj = lambda t: self._ss_jml_rj
self._ejections = {} # Record of any ejection events
for idx, ejn_t0 in enumerate(self.params['ejection']['t_0']):
which = self.params['ejection']['which'][idx]
if 'R' in which:
self.add_ejection_event(
ejn_t0 * con.year,
self._ss_jml_rj * self.params['ejection']['chi'][idx],
self.params['ejection']['hl'][idx] * con.year,
which='R'
)
if 'B' in which:
self.add_ejection_event(
ejn_t0 * con.year,
self._ss_jml_bj * self.params['ejection']['chi'][idx],
self.params['ejection']['hl'][idx] * con.year,
which='B'
)
self._time = 0. * con.year # Current time in jet model
def __str__(self) -> str:
p = self.params
h = ['Parameter', 'Value']
d = [('epsilon', format(p['geometry']['epsilon'], '+.3f')),
('opang', format(p['geometry']['opang'], '+.0f') + ' deg'),
('q_v', format(p['power_laws']['q_v'], '+.3f')),
('q_T', format(p['power_laws']['q_T'], '+.3f')),
('q_x', format(p['power_laws']['q_x'], '+.3f')),
('q_n', format(p['power_laws']['q_n'], '+.3f')),
('q^d_v', format(p['power_laws']['q^d_v'], '+.3f')),
('q^d_T', format(p['power_laws']['q^d_T'], '+.3f')),
('q^d_x', format(p['power_laws']['q^d_x'], '+.3f')),
('q^d_n', format(p['power_laws']['q^d_n'], '+.3f')),
('q_tau', format(p['power_laws']['q_tau'], '+.3f')),
('cell', format(p['grid']['c_size'], '.1f') + ' au'),
('w_0', format(p['geometry']['w_0'], '.2f') + ' au'),
('r_0', format(p['geometry']['r_0'], '.2f') + ' au'),
('v_0', format(p['properties']['v_0'], '.0f') + ' km/s'),
('x_0', format(p['properties']['x_0'], '.3f')),
('n_0', format(p['properties']['n_0'], '.3e') + ' cm^-3'),
('T_0', format(p['properties']['T_0'], '.0e') + ' K'),
('f_R2B', format(self._ss_jml_rb_frac, '.2e')),
('i', format(p['geometry']['inc'], '+.1f') + ' deg'),
('theta', format(p['geometry']['pa'], '+.1f') + ' deg'),
('D', format(p['target']['dist'], '+.0f') + ' pc'),
('M*', format(p['target']['M_star'], '+.1f') + ' Msol'),
('R_1', format(p['target']['R_1'], '+.1f') + ' au'),
('R_2', format(p['target']['R_2'], '+.1f') + ' au')]
# Add current model time if relevant (i.e. bursts are included)
if len(p['ejection']['t_0']) > 0:
d.append(('t_now', format(self.time / con.year, '+.3f') + ' yr'))
col1_width = max(map(len, [h[0]] + list(list(zip(*d))[0]))) + 2
col2_width = max(map(len, [h[1]] + list(list(zip(*d))[1]))) + 2
tab_width = col1_width + col2_width + 3
hline = tab_width * '-'
delim = '|'
s = hline + '\n'
s += '/' + format('JET MODEL', '^' + str(tab_width - 2)) + '/\n'
s += hline + '\n'
s += delim + delim.join([format(h[0], '^' + str(col1_width)),
format(h[1], '^' + str(col2_width))]) + delim
s += '\n' + hline + '\n'
for line_ in d:
s += delim + \
delim.join([format(line_[0], '^' + str(col1_width)),
format(line_[1], '^' + str(col2_width))]) + \
delim + '\n'
s += hline + '\n'
# Burst information below
hb = ['t_0', 'FWHM', 'chi']
units = ['[yr]', '[yr]', '']
db = []
for idx, t in enumerate(p["ejection"]["t_0"]):
db.append((format(t, '.2f'),
format(p["ejection"]["hl"][idx], '.2f'),
format(p["ejection"]["chi"][idx], '.2f')))
s += '/' + format('BURSTS', '^' + str(tab_width - 2)) + '/\n'
s += hline + '\n'
if len(db) == 0:
s += delim + format(' None ',
'-^' + str(tab_width - 2)) + delim + '\n'
s += hline + '\n'
return s
bcol1_w = bcol2_w = bcol3_w = (tab_width - 4) // 3
if (tab_width - 4) % 3 > 0:
bcol1_w += 1
if (tab_width - 4) % 3 == 2:
bcol2_w += 1
# Burst header and units
for line_ in (hb, units):
s += delim + delim.join([format(line_[0], '^' + str(bcol1_w)),
format(line_[1], '^' + str(bcol2_w)),
format(line_[2], '^' + str(bcol3_w))]) + \
delim + '\n'
s += hline + '\n'
# Burst(s) information
for line_ in db:
s += delim + delim.join([format(line_[0], '^' + str(bcol1_w)),
format(line_[1], '^' + str(bcol2_w)),
format(line_[2], '^' + str(bcol3_w))]) + \
delim + '\n'
s += hline + '\n'
return s
@property
def los_axis(self) -> int:
"""Which numpy axis lies parallel to the observer's line-of-sight"""
if self._arr_indexing == 'ij':
return 1
elif self._arr_indexing == 'xy':
return 0
else:
raise ValueError("Unknown numpy array indexing "
f"({self._arr_indexing})")
@property
def time(self) -> float:
"""Model time in seconds"""
return self._time
@time.setter
def time(self, new_time: float):
self._time = new_time
def jml_t(self, which: str) -> Callable[[Union[float, np.ndarray]],
Union[float, np.ndarray]]:
"""Callable for red jet-mass loss rate as a function of time, which is
the callable's sole arg. [kg/s]"""
def func(which):
def inner_func(t):
jml = 0.
if 'R' in which:
jml += self._jml_t_rj(t)
if 'B' in which:
jml += self._jml_t_bj(t)
return jml
return inner_func
return func(which)
def add_ejection_event(self, t_0: float, peak_jml: float, half_life: float,
which: str):
"""
Add ejection event in the form of a Gaussian ejection profile as a
function of time
Parameters
----------
t_0
Time of peak mass loss rate [s]
peak_jml
Highest jet mass loss rate of ejection burst [kg/s]
half_life
Time for mass loss rate to halve during the burst [s]
which
Which jet to apply ejection burst to. Must be either 'B' or 'R' for
the blue or red jet, respectively
Returns
-------
None.
"""
assert which in ('R', 'B')
def func(fnc: Callable[[float], float], _t_0: float, _peak_jml: float,
_half_life: float) -> Callable[[float], float]:
"""
Parameters
----------
fnc : Time dependent function giving current jet mass loss rate
_t_0 : Time of peak of burst
_peak_jml : Peak of burst's jet mass loss rate
_half_life : FWHM of burst
Returns
-------
Factory function returning function describing new time dependent
mass loss rate incorporating input burst
"""
def func2(t: float) -> float:
"""Gaussian profiled ejection event"""
ss_jml = self._ss_jml_bj if which == 'B' else self._ss_jml_rj
amp = _peak_jml - ss_jml
sigma = _half_life * 2. / (2. * np.sqrt(2. * np.log(2.)))
return fnc(t) + amp * np.exp(-(t - _t_0) ** 2. /
(2. * sigma ** 2.))
return func2
if 'R' in which.upper():
self._jml_t_rj = func(self._jml_t_rj, t_0, peak_jml, half_life)
elif 'B' in which.upper():
self._jml_t_bj = func(self._jml_t_bj, t_0, peak_jml, half_life)
else:
raise ValueError('Help!')
record = {'t_0': t_0, 'peak_jml': peak_jml, 'half_life': half_life,
'which': which}
self._ejections[str(len(self._ejections) + 1)] = record
@property
def indices(self) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
if self._idxs:
return self._idxs
self._idxs = tuple(np.meshgrid(np.arange(self.nx),
np.arange(self.ny),
np.arange(self.nz),
indexing=self._arr_indexing))
return self._idxs
@property
def ix(self) -> np.ndarray:
return self.indices[0]
@property
def iy(self) -> np.ndarray:
return self.indices[1]
@property
def iz(self) -> np.ndarray:
return self.indices[2]
@property
def grid(self) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""
Array of cell grid cartesian coordinates (in au) of shape (nx, ny, nz).
Coordinates are of the bottom, left, front cell corners in au.
"""
if self._grid:
return self._grid
self._grid = (self.csize * (self.ix - self.nx // 2),
self.csize * (self.iy - self.ny // 2),
self.csize * (self.iz - self.nz // 2))
return self._grid
@property
def xx(self) -> np.ndarray:
return self.grid[0]
@property
def yy(self) -> np.ndarray:
return self.grid[1]
@property
def zz(self) -> np.ndarray:
return self.grid[2]
@property
def grid_rwp(self) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Grid of cells' centroids' r, w, p coordinates in au"""
if self._rwp:
return self._rwp
self._rwp = mgeom.xyz_to_rwp(self.xx + self.csize / 2.,
self.yy + self.csize / 2.,
self.zz + self.csize / 2.,
self.params["geometry"]["inc"],
self.params["geometry"]["pa"])
return self._rwp
@property
def rr(self) -> np.ndarray:
"""Grid of cells' centroids' r coordinates in au"""
return self.grid_rwp[0]
@property
def ww(self) -> np.ndarray:
"""Grid of cells' centroids' w coordinates in au"""
return self.grid_rwp[1]
@property
def pp(self) -> np.ndarray:
"""Grid of cells' centroids' phi coordinates in radians"""
return self.grid_rwp[2]
@property
def rreff(self) -> np.ndarray:
"""Grid of cells' centroids' effective accretion disc radii in au"""
if self._rreff is not None:
return self._rreff
self._rreff = mgeom.r_eff(self.ww, self.params["target"]["R_1"],
self.params["target"]["R_2"],
self.params['geometry']['w_0'],
np.abs(self.rr),
self.params['geometry']['mod_r_0'],
self.params['geometry']['r_0'],
self.params["geometry"]["epsilon"])
return self._rreff
@property
def xs(self) -> np.ndarray:
return self.grid[0][0][::, 0]
@property
def ys(self) -> np.ndarray:
return self.grid[1][::, 0][::, 0]
@property
def zs(self) -> np.ndarray:
return self.grid[2][0][0]
@property
def fill_factor(self) -> np.ndarray:
"""
Calculate the fraction of each of the grid's cells falling within the
jet's hard boundary define by w(r) (see RaJePy.maths.geometry.w_r
method), or 'fill factors'
"""
if self._ff is not None:
return self._ff
# TODO: Have disabled grid reflection due to correction of
# mgeom.xyz_to_rwp method to handle inclinations and position angles in
# the astronomically correct sense. Therefore, need to propagate these
# changes into the reflection logic at some point, for efficiency
# # Establish reflective symmetries present, if any, to reduce
# # computation time by reflection of coordinates/ffs/areas about
# # relevant axes
# refl_sym_x = False # Reflective symmetry about x-axis?
# refl_sym_y = False # Reflective symmetry about y-axis?
# refl_sym_z = False # Reflective symmetry about z-axis?
# refl_axes = [] # List holding reflected axes for use with np arrays
#
# if self.params["geometry"]["inc"] == 90.:
# if self.params["geometry"]["pa"] == 0.:
# refl_sym_x = refl_sym_y = refl_sym_z = True
# refl_axes = [0, 1, 2]
# else:
# refl_sym_y = True
# refl_axes = [1]
# else:
# if self.params["geometry"]["pa"] == 0.:
# refl_sym_x = True
# refl_axes = [0]
#
# # Set up coordinate grids in x, y, z based upon axial reflective
# # symmetries present given the provided inclination and position angle
# if any((refl_sym_x, refl_sym_y, refl_sym_z)):
# if all((refl_sym_x, refl_sym_y, refl_sym_z)):
# xx, yy, zz = [_[int(self.nx / 2):,
# int(self.ny / 2):,
# int(self.nz / 2):] for _ in self.grid]
# else:
# if refl_sym_x:
# xx, yy, zz = [_[int(self.nx / 2):, :, :]
# for _ in self.grid]
# elif refl_sym_y:
# xx, yy, zz = [_[:, int(self.ny / 2):, :]
# for _ in self.grid]
# else:
# err_msg = u"Grid symmetry not understood for i = {:.0f}" \
# u"\u00B0 and \u03B8={:.0f}\u00B0"
# err_msg = err_msg.format(self.params["geometry"]["inc"],
# self.params["geometry"]["pa"])
# raise ValueError(err_msg)
#
# else:
# xx, yy, zz = self.grid
# xx, yy, zz = self.grid
if self.log:
self._log.add_entry(mtype="INFO",
entry="Calculating cells' fill "
"factors/projected areas")
else:
print("INFO: Calculating cells' fill factors/projected areas")
# Assign to local variables for readability
w_0 = self.params['geometry']['w_0']
r_0 = self.params['geometry']['r_0']
mod_r_0 = self.params['geometry']['mod_r_0']
eps = self.params['geometry']['epsilon']
inc = self.params['geometry']['inc']
pa = self.params['geometry']['pa']
cs = self.csize
ffs = np.zeros(np.shape(self.xx))
areas = np.zeros(
np.shape(self.xx)) # Areas as projected on to the y-axis
# diag = np.sqrt(cs ** 2. * 3.) # Diagonal dimensions of cells (au)
# nvoxels = np.prod(np.shape(self.xx))
# count = 0
# progress = -1
then = time.time()
n_verts_inside = np.zeros(np.shape(self.xx), dtype=int)
verts = ((0., 0., 0.), (cs, 0., 0.), (0., cs, 0.), (cs, cs, 0.),
(0., 0., cs), (cs, 0., cs), (0., cs, cs), (cs, cs, cs))
for dx, dy, dz in verts:
rv, wv = mgeom.xyz_to_rwp(self.xx + dx, self.yy + dy,
self.zz + dz, inc, pa)[:2]
wrv = mgeom.w_r(rv, w_0, mod_r_0, r_0, eps)
n_verts_inside = np.where((wrv >= wv) & (np.abs(rv) >= r_0),
n_verts_inside + 1, n_verts_inside)
ffs = np.where(n_verts_inside == 8, 1.0, ffs)
ffs = np.where((0 < n_verts_inside) & (n_verts_inside < 8), 0.5, ffs)
areas = np.where(0 < n_verts_inside, 1.0, areas)
# for idxy, yplane in enumerate(self.zz):
# for idxx, xrow in enumerate(yplane):
# for idxz, z in enumerate(xrow):
# count += 1
# # Does the cell definitely lie outside of the jet
# # boundary? Yes if w-coordinate is more than the cells'
# # full diagonal dimension away from the jet's width at
# # the cells' r-coordinate
# wr = mgeom.w_r(self.rr[idxy][idxx][idxz],
# w_0, mod_r_0, r_0, eps) # Removed
# # np.abs(r) here
# if (self.ww[idxy][idxx][idxz] - 0.5 * diag) > wr:
# continue
#
# # Voxel blfc coordinate
# x, y = (self.xx[idxy][idxx][idxz],
# self.yy[idxy][idxx][idxz])
#
# # Voxel's vertices' coordinates
# verts = np.array([(x, y, z), (x + cs, y, z),
# (x, y + cs, z), (x + cs, y + cs, z),
# (x, y, z + cs), (x + cs, y, z + cs),
# (x, y + cs, z + cs),
# (x + cs, y + cs, z + cs)])
#
# # Cell-vertices' r, w and phi coordinates
# rv, wv, pv = mgeom.xyz_to_rwp(verts[::, 0], verts[::, 1],
# verts[::, 2], inc, pa)
# wr = mgeom.w_r(rv, w_0, mod_r_0, r_0, eps) # Removed
# # np.abs(r)
# # here
# verts_inside = (wv <= wr) & (np.abs(rv) >= r_0)
#
# if np.sum(verts_inside) == 8:
# ff = 1.
# area = 1.
# elif np.sum(verts_inside) == 0:
# continue
# else:
# # TODO: Cells at base of jet need to accommodate for
# # r_0 properly. Value of 0.5 for ff and area will
# # not do
# # Take average values for fill factor/projected areas
# ff = .5
# area = 1.0
#
# ffs[idxy][idxx][idxz] = ff
# areas[idxy][idxx][idxz] = area
#
# # Progress bar
# new_progress = int(count / nvoxels * 100) #
# if new_progress > progress:
# progress = new_progress
# pblen = get_terminal_size().columns - 1
# pblen -= 16 # 16 non-varying characters
# s = '[' + ('=' * (int(progress / 100 * pblen) - 1)) + \
# ('>' if int(progress / 100 * pblen) > 0 else '') + \
# (' ' * int(pblen - int(progress / 100 * pblen))) + ']'
# # s += format(int(progress), '3') + '% complete'
# if progress != 0.:
# t_sofar = (time.time() - then)
# try:
# rate = progress / t_sofar
# secs_left = (100. - progress) / rate
# s += time.strftime('%Hh%Mm%Ss left',
# time.gmtime(secs_left))
# except ZeroDivisionError:
# s += ' h m s left'
# else:
# s += ' h m s left'
# print('\r' + s, end='' if progress < 100 else '\n')
now = time.time()
if self.log:
self.log.add_entry(mtype="INFO",
entry=time.strftime('Finished in %Hh%Mm%Ss',
time.gmtime(now - then)))
else:
print(time.strftime('INFO: Finished in %Hh%Mm%Ss',
time.gmtime(now - then)))
# TODO: Have disabled grid reflection due to correction of
# mgeom.xyz_to_rwp method to handle inclinations and position angles in
# the astronomically correct sense. Therefore, need to propagate these
# changes into the reflection logic at some point, for efficiency
# # Reflect in x, y and z axes
# for axis in refl_axes:
# ffs = np.append(np.flip(ffs, axis=axis), ffs, axis=axis)
# areas = np.append(np.flip(areas, axis=axis), areas, axis=axis)
# Included as there are some, presumed floating point errors giving
# fill factors of ~1e-15 on occasion
ffs = np.where(ffs > 1e-6, ffs, np.NaN)
areas = np.where(areas > 1e-6, areas, np.NaN)
self._ff = ffs
self._areas = areas
return self._ff
@property
def areas(self) -> Union[None, np.ndarray]:
"""
Areas of jet-filled portion of cells as projected on to the y-axis
(hopefully, custom orientations will address this so area is as
projected on to a surface whose normal points to the observer)
"""
# if "_areas" in self.__dict__.keys() and self._areas is not None:
if self._areas is not None:
return self._areas
_ = self.fill_factor # Areas calculated as part of fill factors
return self._areas
# @property
# def mass(self) -> np.ndarray:
# if self._m is not None:
# return self._m
#
# w_0 = self.params['geometry']['w_0'] / self.params['grid']['c_size']
# r_0 = self.params['geometry']['r_0'] / self.params['grid']['c_size']
# eps = self.params['geometry']['epsilon']
#
# # Mass of slice with z-width == 1 full cell
# mass_full_slice = (self._ss_jml_bj *
# (self.csize * con.au /
# (self.params['properties']['v_0'] * 1e3)))
#
# ms = np.zeros(np.shape(self.fill_factor))
# constant = np.pi * w_0 ** 2. / ((2. * eps + 1.) * r_0 ** (2. * eps))
#
# for idz, z in enumerate(self.grid[2][0][0] / self.csize):
# z = np.round(z)
# n_z = int(np.min(np.abs([z, z + 1])))
# if n_z > r_0:
# vol_zlayer = constant * ((n_z + 1.) ** (2. * eps + 1) -
# (n_z + 0.) ** (2. * eps + 1))
# mass_slice = mass_full_slice
# elif (n_z + 1) >= r_0:
# vol_zlayer = constant * ((n_z + 1.) ** (2. * eps + 1) -
# r_0 ** (2. * eps + 1))
# mass_slice = mass_full_slice * (n_z + 1. - r_0)
# else:
# # vol_zlayer = 0.
# # mass_slice = 0.
# continue
#
# ffs_zlayer = self.fill_factor[:, :, idz]
# m_cell = mass_slice / vol_zlayer # kg / cell
# ms_zlayer = ffs_zlayer * m_cell
#
# ms[:, :, idz] = ms_zlayer
#
# ms = (self.number_density * (self.csize * con.au * 1e2) ** 3. *
# self.params['properties']['mu'] * mphys.atomic_mass('H') *
# self.fill_factor)
#
# ms = np.where(self.fill_factor > 0, ms, np.NaN)
# self._m = ms
#
# return self._m
#
# @mass.setter
# def mass(self, new_ms: np.ndarray):
# self._m = new_ms
@property
def ts(self) -> np.ndarray:
"""
Time from launch of material in cell compared to current model time in
seconds
"""
if self._ts is not None:
return self.time - self._ts
r_0 = self.params['geometry']['r_0']
r = np.abs(self.rr)
r = np.where((r < r_0) & ((r + self.csize / 2.) >= r_0),
(r_0 + r + self.csize / 2.) / 2., r)
ts = mgeom.t_rw(r, self.ww, self.params) * con.year
self.ts = ts
return self.ts
@ts.setter
def ts(self, new_ts: np.ndarray):
self._ts = new_ts
@property
def chi_xyz(self) -> np.ndarray:
"""
Chi factor (the burst factor) as a function of position.
"""
chi_xyz = np.where(self.rr < 0,
self._jml_t_rj(self.ts) / self._ss_jml_rj,
self._jml_t_bj(self.ts) / self._ss_jml_bj)
return chi_xyz
@property
def number_density(self) -> np.ndarray:
if self._nd is not None:
return self._nd * self.chi_xyz
r1 = self.params["target"]["R_1"]
mr0 = self.params['geometry']['mod_r_0']
r0 = self.params['geometry']['r_0']
q_n = self.params["power_laws"]["q_n"]
q_nd = self.params["power_laws"]["q^d_n"]
n_0 = self.params["properties"]["n_0"]
r = np.abs(self.rr)
r = np.where((r < r0) & ((r + self.csize / 2.) >= r0),
(r0 + r + self.csize / 2.) / 2., r)
# nd = n_0 * mgeom.rho(self.rr, r0, mr0) ** q_n * \
# (self.rreff / r1) ** q_nd
nd = mgeom.cell_value(n_0, mgeom.rho(r, r0, mr0), self.rreff,
r1, q_n, q_nd)
nd = np.where(self.fill_factor > 0, nd, np.NaN)
nd = np.where(nd == 0, np.NaN, nd)
# For asymmetric mass loss
nd = np.where(self.rr < 0, nd * self._ss_jml_rb_frac, nd)
self._nd = np.nan_to_num(nd, nan=np.NaN, posinf=np.NaN, neginf=np.NaN)
return self.number_density
@property
def mass_density(self) -> np.ndarray:
"""
Mass density in g cm^-3
"""
av_m_particle = self.params['properties']['mu'] * mphys.atomic_mass("H")
return av_m_particle * 1e3 * self.number_density # g cm^-3
@property
def ion_fraction(self) -> np.ndarray:
if self._xi is not None:
return self._xi
r_1 = self.params["target"]["R_1"]
mod_r_0 = self.params['geometry']['mod_r_0']
r_0 = self.params['geometry']['r_0']
q_x = self.params["power_laws"]["q_x"]
q_xd = self.params["power_laws"]["q^d_x"]
x_0 = self.params["properties"]["x_0"]
r = np.abs(self.rr)
r = np.where((r < r_0) & ((r + self.csize / 2.) >= r_0),
(r_0 + r + self.csize / 2.) / 2., r)
# xi = x_0 * mgeom.rho(r, r_0, mod_r_0) ** q_x * \
# (self.rreff / r_1) ** q_xd
xi = mgeom.cell_value(x_0, mgeom.rho(r, r_0, mod_r_0), self.rreff,
r_1, q_x, q_xd)
xi = np.where(self.fill_factor > 0, xi, np.NaN)
xi = np.where(xi == 0, np.NaN, xi)
self.ion_fraction = np.nan_to_num(xi, nan=np.NaN, posinf=np.NaN,
neginf=np.NaN)
return self.ion_fraction
@ion_fraction.setter
def ion_fraction(self, new_xis: np.ndarray):
self._xi = new_xis
@property
def temperature(self) -> np.ndarray:
"""
Temperature (in Kelvin)
"""
if self._temp is not None:
return self._temp
r_1 = self.params["target"]["R_1"]
mod_r_0 = self.params['geometry']['mod_r_0']
r_0 = self.params['geometry']['r_0']
q_t = self.params["power_laws"]["q_T"]
q_td = self.params["power_laws"]["q^d_T"]
temp_0 = self.params["properties"]["T_0"]
r = np.abs(self.rr) * con.au * 1e2
r = np.where((r < r_0) & ((r + self.csize / 2.) >= r_0),
(r_0 + r + self.csize / 2.) / 2., r)
temp = mgeom.cell_value(temp_0, mgeom.rho(r, r_0, mod_r_0), self.rreff,
r_1, q_t, q_td)
temp = np.where(self.fill_factor > 0, temp, np.NaN)
temp = np.where(temp == 0, np.NaN, temp)
self.temperature = np.nan_to_num(temp, nan=np.NaN, posinf=np.NaN,
neginf=np.NaN)
return self.temperature
# z = np.abs(self.rr)
# a = z - 0.5 * self.csize
# b = z + 0.5 * self.csize
#
# a = np.where(b <= self.params['geometry']['r_0'], np.NaN, a)
# b = np.where(b <= self.params['geometry']['r_0'], np.NaN, b)
#
# a = np.where(a <= self.params['geometry']['r_0'],
# self.params['geometry']['r_0'], a)
#
# def indefinite_integral(z):
# num_p1 = self.params['properties']['T_0'] * \
# self.params["geometry"]["mod_r_0"]
# num_p2 = ((z + self.params["geometry"]["mod_r_0"] -
# self.params["geometry"]["r_0"]) /
# (self.params["geometry"]["mod_r_0"]))
# num_p2 = num_p2 ** (self.params["power_laws"]["q_T"] + 1.)
# den = self.params["power_laws"]["q_T"] + 1.
# return num_p1 * num_p2 / den
#
# ts = indefinite_integral(b) - indefinite_integral(a)
# ts /= b - a
# ts = np.where(self.fill_factor > 0., ts, np.NaN)
# self.temperature = ts
#
# return self.temperature
@temperature.setter
def temperature(self, new_ts: np.ndarray):
self._temp = new_ts