-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclasses.py
2440 lines (1987 loc) · 93.9 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 ([email protected])
"""
import sys
import os
import time
import pickle
import numpy as np
import astropy.units as u
import scipy.constants as con
import matplotlib.pylab as plt
from astropy.coordinates import SkyCoord
from astropy.io import fits
from scipy.spatial import ConvexHull
from scipy.integrate import dblquad, tplquad
from shutil import get_terminal_size
from matplotlib.colors import LogNorm
from RaJePy import logger
from RaJePy.maths import geometry as mgeom
from RaJePy.maths import physics as mphys
from RaJePy.plotting import functions as pfunc
from warnings import filterwarnings
filterwarnings("ignore", category=RuntimeWarning)
class JetModel:
"""
Class to handle physical model of an ionised jet from a young stellar object
"""
@classmethod
def load_model(cls, model_file):
"""
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
loaded = pickle.load(open(model_file, 'rb'))
# Create new JetModel class instance
new_jm = cls(loaded["params"])
# If fill factors/projected areas have been previously calculated,
# assign to new instance
if loaded['ffs'] is not None:
new_jm.fill_factor = loaded['ffs']
if loaded['areas'] is not None:
new_jm.areas = loaded['areas']
new_jm.time = loaded['time']
return new_jm
def __init__(self, params, verbose=True, log=None):
"""
Parameters
----------
params : dict
dictionary containing all necessary parameters for run of TORCH
verbose : bool
verbosity in terminal. True for verbosity, False for silence
"""
if isinstance(params, dict):
self._params = params
elif isinstance(params, str):
if not os.path.exists(params):
raise FileNotFoundError(params + " does not exist")
if os.path.dirname(params) not in sys.path:
sys.path.append(os.path.dirname(params))
jp = __import__(os.path.basename(params).strip('.py'))
self._params = jp.params
else:
raise TypeError("Supplied arg params must be dict or str")
# self._dcy = self.params['dcys']['model_dcy']
self._name = self.params['target']['name']
self._csize = self.params['grid']['c_size']
self._log = log
# Number of voxels in x, y, z
if self.params['grid']['l_z'] is not None:
nz = int(np.ceil(self.params['grid']['l_z'] / 2. *
self.params['target']['dist'] /
self.params['grid']['c_size']))
nx = int(np.ceil(mgeom.w_yz(0., nz + 1.,
self.params['geometry']['w_0'] /
self.params['grid']['c_size'],
self.params['geometry']['r_0'] /
self.params['grid']['c_size'],
self.params['geometry']['epsilon'])
)
)
ny = int(np.ceil(mgeom.w_xz(0., nz + 1.,
self.params['geometry']['w_0'] /
self.params['grid']['c_size'],
self.params['geometry']['r_0'] /
self.params['grid']['c_size'],
self.params['geometry']['epsilon'])
)
)
nx *= 2
ny *= 2
nz *= 2
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._nx = nx
self._ny = ny
self._nz = nz
self._ff = None
self._areas = None
self._grid = None
mlr = self.params['properties']['n_0'] * 1e6 * np.pi
mlr *= self.params['properties']['mu'] * mphys.atomic_mass("H")
mlr *= (self.params['geometry']['w_0'] * con.au) ** 2.
mlr *= self.params['properties']['v_0'] * 1e3 # kg/s
self._ss_jml = mlr
def func(jml):
def func2(t):
"Mass loss rate as function of time"
return jml # * (t / t)
return func2
self._jml_t = func(self._ss_jml)
self._ejections = {} # Record of any ejection events
for idx, ejn_t0 in enumerate(self.params['ejection']['t_0']):
self.add_ejection_event(ejn_t0 * con.year,
mlr * self.params['ejection']['chi'][idx],
self.params['ejection']['hl'][idx] *
con.year)
self._time = 0. * con.year
def __str__(self):
p = self.params
h = ['Parameter', 'Value']
d = [('epsilon', format(p['geometry']['epsilon'], '+.3f')),
('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_tau', format(p['power_laws']['q_tau'], '+.3f')),
('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'),
('i', format(p['geometry']['inc'], '+.1f') + ' deg'),
('theta', format(p['geometry']['pa'], '+.1f') + ' deg'),
('cross-section',
'exp' if p['geometry']['exp_cs'] else 'constant'),
('t_now', format(self.time / con.year, '+.3f') + ' yr')]
for idx, t_0 in enumerate(p['ejection']['t_0']):
d.append(("t0_" + str(idx + 1), format(t_0, '+.3f') + ' yr'))
d.append(("hl_" + str(idx + 1),
format(p['ejection']['hl'][idx], '.3f') + ' yr'))
d.append(("chi_" + str(idx + 1),
format(p['ejection']['chi'][idx], '.3f')))
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 = format('JET MODEL', '^' + str(tab_width)) + '\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 l in d:
s += delim + delim.join([format(l[0], '^' + str(col1_width)),
format(l[1], '^' + str(col2_width))]) + \
delim + '\n'
s += hline + '\n'
return s
@property
def time(self):
return self._time
@time.setter
def time(self, new_time):
self._time = new_time
@property
def jml_t(self):
return self._jml_t
@jml_t.setter
def jml_t(self, new_jml_t):
self._jml_t = new_jml_t
def add_ejection_event(self, t_0, peak_jml, half_life):
"""
Add ejection event in the form of a Gaussian ejection profile as a
function of time
Parameters
----------
t_0 : astropy.units.quantity.Quantity
Time of peak mass loss rate
peak_jml : astropy.units.quantity.Quantity
Highest jet mass loss rate of ejection burst
half_life : astropy.units.quantity.Quantity
Time for mass loss rate to halve during the burst
Returns
-------
None.
"""
def func(fnc, t_0, peak_jml, half_life):
"""
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):
"""Gaussian profiled ejection event"""
amp = peak_jml - self._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
self._jml_t = func(self._jml_t, t_0, peak_jml, half_life)
record = {'t_0': t_0, 'peak_jml': peak_jml, 'half_life': half_life}
self._ejections[str(len(self._ejections) + 1)] = record
@property
def grid(self):
if self._grid:
return self._grid
self._grid = np.meshgrid(np.linspace(-self.nx / 2 * self.csize,
(self.nx / 2 - 1.) * self.csize,
self.nx),
np.linspace(-self.ny / 2 * self.csize,
(self.ny / 2 - 1.) * self.csize,
self.ny),
np.linspace(-self.nz / 2 * self.csize,
(self.nz / 2 - 1.) * self.csize,
self.nz))
return self._grid
@grid.setter
def grid(self, new_grid):
self._grid = new_grid
@property
def fill_factor(self):
"""
Calculate the fraction of each of the grid's cells falling within the
jet
"""
if self._ff is not None:
return self._ff
# Set up coordinate grid in x, y, z for grid's 1st octant only due to
# assumption of reflective symmetry about x, y and z axes
xx, yy, zz = [_[int(self.ny / 2):,
int(self.nx / 2):,
int(self.nz / 2):] for _ in self.grid]
nvoxels = (self.nx / 2) * (self.ny / 2) * (self.nz / 2)
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']
eps = self.params['geometry']['epsilon']
cs = self.csize
w_0_cs = w_0 / cs
r_0_cs = r_0 / cs
def hfun_area(n_z):
def func(x):
"""
The upper boundary surface in z for area calculation
"""
return n_z + 1.
return func
def gfun_area(w_0, n_y, n_z, r_0, eps):
"""
The lower boundary curve in z for area calculation
"""
def func(x):
return np.max([r_0, n_z,
r_0 * w_0 ** (-1. / eps) *
(x ** 2. + n_y ** 2.) ** (1. / (2. * eps))])
return func
def hfun(w_0, n_y, n_z, r_0, eps):
"""
The upper boundary curve in y for volume calculation
"""
def func(x):
return np.min([np.sqrt(w_0 ** 2. *
((n_z + 1.) / r_0) ** (
2 * eps) - x ** 2.),
n_y + 1])
return func
def gfun(n_y):
def func(_):
"""
The lower boundary curve in y for volume calculation
"""
return n_y
return func
def rfun(n_z):
def func(_, __):
"""
The upper boundary surface in z for volume calculation
"""
return n_z + 1.
return func
def qfun(w_0, n_z, r_0, eps):
"""
The lower boundary surface in z for volume calculation
"""
def func(x, y):
return np.max([r_0 * w_0 ** (-1. / eps) *
(x ** 2. + y ** 2.) ** (1. / (2. * eps)),
r_0, n_z])
return func
ffs = np.zeros(np.shape(xx))
areas = np.zeros(np.shape(xx)) # Areas as projected on to the y-axis
count = 0
progress = -1
then = time.time()
for idxy, yplane in enumerate(zz):
for idxx, xrow in enumerate(yplane):
for idxz, z in enumerate(xrow):
count += 1
x, y = xx[idxy][idxx][idxz], yy[idxy][idxx][idxz]
verts = ((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))
verts_inside = []
for vert in verts:
zjet = mgeom.w_xy(vert[0], vert[1], w_0, r_0, eps)
if vert[2] > zjet:
verts_inside.append(True)
else:
verts_inside.append(False)
if sum(verts_inside) == 0:
continue
elif sum(verts_inside) == 8:
ff = 1.
area = 1.
else:
# Calculate tuple of possible intercept coordinates for
# every edge of the voxel
i = ((mgeom.w_yz(verts[0][1], verts[0][2],
w_0, r_0, eps),
verts[0][1],
verts[0][2]), # a
(verts[0][0],
mgeom.w_xz(verts[0][0], verts[0][2],
w_0, r_0, eps),
verts[0][2]), # b
(verts[0][0],
verts[0][1],
mgeom.w_xy(verts[0][0], verts[0][1],
w_0, r_0, eps)), # c
(verts[1][0],
mgeom.w_xz(verts[1][0], verts[1][2],
w_0, r_0, eps),
verts[1][2]), # d
(verts[1][0],
verts[1][1],
mgeom.w_xy(verts[1][0], verts[1][1],
w_0, r_0, eps)), # e
(mgeom.w_yz(verts[2][1], verts[2][2],
w_0, r_0, eps),
verts[2][1],
verts[2][2]), # f
(verts[2][0],
verts[2][1],
mgeom.w_xy(verts[2][0], verts[2][1],
w_0, r_0, eps)), # g
(verts[3][0],
verts[3][1],
mgeom.w_xy(verts[3][0], verts[3][1],
w_0, r_0, eps)), # h
(mgeom.w_yz(verts[4][1], verts[4][2],
w_0, r_0, eps),
verts[4][1],
verts[4][2]), # i
(verts[4][0],
mgeom.w_xz(verts[4][0], verts[4][2],
w_0, r_0, eps),
verts[4][2]), # j
(verts[5][0],
mgeom.w_xz(verts[5][0], verts[5][2],
w_0, r_0, eps),
verts[5][2]), # k
(mgeom.w_yz(verts[6][1], verts[6][2],
w_0, r_0, eps),
verts[6][1],
verts[6][2])) # l
# Determine which edges actually have an intercept with jet
# boundary
# NB - ^ is the bitwise operator XOR
mask = [verts_inside[0] ^ verts_inside[1],
verts_inside[0] ^ verts_inside[2],
verts_inside[0] ^ verts_inside[4],
verts_inside[1] ^ verts_inside[3],
verts_inside[1] ^ verts_inside[5],
verts_inside[2] ^ verts_inside[3],
verts_inside[2] ^ verts_inside[6],
verts_inside[3] ^ verts_inside[7],
verts_inside[4] ^ verts_inside[5],
verts_inside[4] ^ verts_inside[6],
verts_inside[5] ^ verts_inside[7],
verts_inside[6] ^ verts_inside[7]]
# Create array of coordinates defining the polygon's
# vertices lying within the jet boundary
ph_verts = np.append(
np.array(verts)[verts_inside].tolist(),
np.array(i)[mask].tolist(),
axis=0)
# Use scipy's ConvexHull's built in method to determine
# volume within jet boundary (MUST BE CONVEX POLYGON)
try:
ch_vol = ConvexHull(ph_verts)
ch_area = ConvexHull(ph_verts.T[::2].T)
ff = ch_vol.volume / cs ** 3.
area = ch_area.volume / cs ** 2.
except:
x /= cs
y /= cs
z /= cs
b = np.min([np.sqrt(w_0_cs ** 2. *
((z + 1.) / r_0_cs) **
(2. * eps) - y ** 2.),
x + 1.])
ff = tplquad(lambda z, y, x: 1.,
a=x, b=b,
gfun=gfun(y),
hfun=hfun(w_0_cs, y,
z, r_0_cs, eps),
qfun=qfun(w_0_cs, z,
r_0_cs, eps),
rfun=rfun(z))[0]
b_a = np.sqrt(w_0_cs ** 2. *
((z + 1.) /
r_0_cs) ** (2. * eps) - y ** 2.)
area = dblquad(lambda z, x: 1.,
a=x, b=np.min([b_a, x + 1.]),
gfun=gfun_area(w_0_cs, y, z, r_0_cs,
eps),
hfun=hfun_area(z))[0]
x *= cs
y *= cs
z *= cs
# Accurately calculate filling fractions for 5 base
# cell layers
if ((np.round(z / cs) - np.round(r_0_cs) < 5) and
(np.round(z / cs) - np.round(r_0_cs) > -1)):
x /= cs
y /= cs
z /= cs
# Volume
b = np.min([np.sqrt(w_0_cs ** 2. *
((z + 1.) / r_0_cs) **
(2. * eps) - y ** 2.),
x + 1.])
ff = tplquad(lambda z, y, x: 1.,
a=x, b=b,
gfun=gfun(y),
hfun=hfun(w_0_cs, y, z, r_0_cs, eps),
qfun=qfun(w_0_cs, z, r_0_cs, eps),
rfun=rfun(z))[0]
b_a = np.sqrt(w_0_cs ** 2. *
((z + 1.) / r_0_cs) **
(2. * eps) - y ** 2.)
area = dblquad(lambda z, x: 1.,
a=x, b=np.min([b_a, x + 1.]),
gfun=gfun_area(w_0_cs, y, z, r_0_cs,
eps),
hfun=hfun_area(z))[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)
rate = progress / t_sofar
s += time.strftime('%Hh%Mm%Ss left',
time.gmtime(
(100. - progress) / rate))
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)))
# Reflect in x, y and z axes
for ax in (0, 1, 2):
ffs = np.append(np.flip(ffs, axis=ax), ffs, axis=ax)
areas = np.append(np.flip(areas, axis=ax), areas, axis=ax)
# 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
@fill_factor.setter
def fill_factor(self, new_ffs):
self._ff = new_ffs
@property
def areas(self):
"""
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:
return self._areas
else:
self.fill_factor # Areas calculated as part of fill factors
return self._areas
@areas.setter
def areas(self, new_areas):
self._areas = new_areas
def save(self, filename):
ps = {'params': self._params,
'areas': None if self._areas is None else self.areas,
'ffs': None if self._ff is None else self.fill_factor,
'time': self.time}
pickle.dump(ps, open(filename, "wb"))
return None
@property
def mass(self):
if hasattr(self, '_m'):
return self._m * self.chi_xyz
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']
# mlr = self.params['properties']['n_0'] * 1e6 * np.pi
# mlr *= self.params['properties']['mu'] * mphys.atomic_mass("H")
# mlr *= (self.params['geometry']['w_0'] * con.au)**2.
# mlr *= self.params['properties']['v_0'] * 1e3 # kg/s
# Mass of slice with z-width == 1 full cell
mass_full_slice = self._ss_jml * (self.csize * con.au / # kg
(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 = np.where(self.fill_factor > 0, ms, np.NaN)
self.mass = ms
return self._m * self.chi_xyz
@mass.setter
def mass(self, new_ms):
self._m = new_ms * self.chi_xyz
@property
def chi_xyz(self):
"""
Chi factor (the burst factor) as a function of position.
"""
z = np.abs(self.grid[2] + 0.5 * self.csize)
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)
z *= con.au
a *= con.au
b *= con.au
def t_z(z):
"""
Time as a function of z. Defined purely for informative purposes
"""
r_0 = self.params['geometry']['r_0'] * con.au
v_0 = self.params['properties']['v_0'] * 1000
q_v = self.params['power_laws']['q_v']
return (r_0 ** q_v * z ** (1. - q_v) - r_0) / (v_0 * (1. - q_v))
def int_t_z(z):
"""
Integral of t_z defined above for use in average value finding
"""
r_0 = self.params['geometry']['r_0'] * con.au
v_0 = self.params['properties']['v_0'] * 1000.
q_v = self.params['power_laws']['q_v']
num = r_0 ** q_v * z ** (2. - q_v) + (q_v - 2.) * r_0 * z
den = v_0 * (q_v - 2.) * (q_v - 1.)
return num / den
av_ts = 1. / (b - a)
av_ts *= int_t_z(b) - int_t_z(a)
# So that times start at 0 at r_0 and to progress to current model time
av_ts = self.time - av_ts
av_ts = np.where(self.fill_factor > 0, av_ts, np.NaN)
av_chis = self._jml_t(av_ts) / self._ss_jml
return av_chis
@property
def number_density(self):
if hasattr(self, '_nd'):
return self._nd * self.chi_xyz
z = np.abs(self.grid[2] + 0.5 * self.csize)
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)
# Method 1, i.e. via Reynolds (1986) power-law for n(r) and
# averaging cell number density over z-axis extent of each cell. See
# https://www.math24.net/average-value-function/ for math
nd = self.params['properties']['n_0']
nd *= self.params['geometry']['r_0'] ** -self.params["power_laws"][
"q_n"]
nd *= (b ** (self.params["power_laws"]["q_n"] + 1) -
a ** (self.params["power_laws"]["q_n"] + 1))
nd /= self.params["power_laws"]["q_n"] + 1
nd /= self.csize
nd = np.where(self.fill_factor > 0, nd, np.NaN)
# nd = self.mass / (self.fill_factor * (jm.csize * con.au)**3.)
# nd /= self.params['properties']['mu'] * mphys.atomic_mass("H")
# nd /= 1e6 # m^-3 to cm^-3
self.number_density = np.nan_to_num(nd, nan=np.NaN, posinf=np.NaN,
neginf=np.NaN)
return self._nd * self.chi_xyz
@number_density.setter
def number_density(self, new_nds):
self._nd = new_nds
@property
def mass_density(self):
"""
Mass density in g cm^-3
"""
mean_m_particle = self.params['properties']['mu'] * \
mphys.atomic_mass("H")
return mean_m_particle * 1e3 * self.number_density
@property
def ion_fraction(self):
if hasattr(self, '_xi'):
return self._xi
z = np.abs(self.grid[2] + 0.5 * self.csize)
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)
# Averaging cell ionisation fraction over z-axis extent of each cell.
# See https://www.math24.net/average-value-function/ for math
xi = self.params['properties']['x_0']
xi *= self.params['geometry']['r_0'] ** -self.params["power_laws"][
"q_x"]
xi *= (b ** (self.params["power_laws"]["q_x"] + 1) -
a ** (self.params["power_laws"]["q_x"] + 1))
xi /= self.params["power_laws"]["q_x"] + 1
xi /= self.csize
xi = np.where(self.fill_factor > 0., xi, np.NaN)
self.ion_fraction = xi
return self._xi
@ion_fraction.setter
def ion_fraction(self, new_xis):
self._xi = new_xis
# @property
def emission_measure(self, savefits=False):
ems = (self.number_density * self.ion_fraction) ** 2. * \
(self.csize * con.au / con.parsec *
(self.fill_factor / self.areas))
from scipy.ndimage import rotate
ems = rotate(ems, axes=(2, 0), reshape=True, order=0, prefilter=False,
angle=90. - self.params['geometry']['inc'])
ems = rotate(ems, axes=(2, 1), reshape=True, order=0, prefilter=False,
angle=self.params['geometry']['pa'])
ems = np.nansum(ems, axis=0)
# self.emission_measure = ems
if savefits:
self.save_fits(ems.T, savefits, 'em')
return ems
# @emission_measure.setter
# def emission_measure(self, new_ems):
# self._em = new_ems
def optical_depth_ff(self, freq, savefits=False):
"""
Return free-free optical depth as viewed along the y-axis
Parameters
----------
freq : float
Frequency of observation (Hz).
savefits : bool, str
False or full path to save calculated optical depths as .fits file
Returns
-------
tau_ff : numpy.ndarray
Optical depths as viewed along y-axis.
"""
# Gaunt factors of van Hoof et al. (2014). Use if constant temperature
# as computation via this method across a grid takes too long
if self.params['power_laws']['q_T'] == 0.1241:
gff = mphys.gff(freq, self.params['properties']['T_0'])
# Equation 1 of Reynolds (1986) otherwise as an approximation
else:
gff = 11.95 * self.temperature ** 0.15 * freq ** -0.1
# Equation 1.26 and 5.19b of Rybicki and Lightman (cgs). Averaged
# path length through voxel is volume / projected area
tff = 0.018 * self.temperature ** -1.5 * freq ** -2. * \
(self.number_density * self.ion_fraction) ** 2. * \
(self.csize * con.au * 1e2 * \
(self.fill_factor / self.areas)) * gff
from scipy.ndimage import rotate
tff = rotate(tff, axes=(2, 0), reshape=True, order=0, prefilter=False,
angle=90. - self.params['geometry']['inc'])
tff = rotate(tff, axes=(2, 1), reshape=True, order=0, prefilter=False,
angle=self.params['geometry']['pa'])
tau_ff = np.nansum(tff, axis=0)
if savefits:
self.save_fits(tau_ff.T, savefits, 'tau', freq)
return tau_ff
def intensity_ff(self, freq):
"""
Radio intensity as viewed along x-axis (in W m^-2 Hz^-1 sr^-1)
"""
from scipy.ndimage import rotate
ts = rotate(self.temperature, axes=(2, 0), reshape=True, order=0,
prefilter=False,
angle=90. - self.params['geometry']['inc'])
ts = rotate(ts, axes=(2, 1), reshape=True, order=0, prefilter=False,
angle=self.params['geometry']['pa'])
T_b = np.nanmean(np.where(ts > 0., ts, np.NaN), axis=0) * \
(1. - np.exp(-self.optical_depth_ff(freq)))
ints = 2. * freq ** 2. * con.k * T_b / con.c ** 2.
return ints
def flux_ff(self, freq, savefits=False):
"""
Return flux (in Jy)
"""
ints = self.intensity_ff(freq)
fluxes = ints * np.tan((self.csize * con.au) /
(self.params["target"]["dist"] *
con.parsec)) ** 2. / 1e-26
if savefits:
self.save_fits(fluxes.T, savefits, 'flux', freq)
return fluxes
def save_fits(self, data, filename, image_type, freq=None):
"""
Save .fits file of input data
Parameters
----------
data : numpy.array
2-D numpy array of image data.
filename: str
Full path to save .fits image to
image_type : str
One of 'flux', 'tau' or 'em'. The type of image data saved.
freq : float
Radio frequency of image (ignored if image_type is 'em')
Returns
-------
None.
"""
if image_type not in ('flux', 'tau', 'em'):
raise ValueError("arg image_type must be one of 'flux', 'tau' or "
"'em'")
c = SkyCoord(self.params['target']['ra'],
self.params['target']['dec'],
unit=(u.hourangle, u.degree), frame='fk5')
csize_deg = np.degrees(np.arctan(self.csize * con.au /
(self.params['target']['dist'] *
con.parsec)))
hdu = fits.PrimaryHDU(np.array([data]))
hdul = fits.HDUList([hdu])
hdr = hdul[0].header
hdr['AUTHOR'] = 'S.J.D.Purser'
hdr['OBJECT'] = self.params['target']['name']
hdr['CTYPE1'] = 'RA---TAN'
hdr.comments['CTYPE1'] = 'x-coord type is RA Tan Gnomonic projection'
hdr['CTYPE2'] = 'DEC--TAN'
hdr.comments['CTYPE2'] = 'y-coord type is DEC Tan Gnomonic projection'
hdr['EQUINOX'] = 2000.
hdr.comments['EQUINOX'] = 'Equinox of coordinates'
hdr['CRPIX1'] = self.nx / 2 + 0.5
hdr.comments['CRPIX1'] = 'Reference pixel in RA'
hdr['CRPIX2'] = self.nz / 2 + 0.5
hdr.comments['CRPIX2'] = 'Reference pixel in DEC'
hdr['CRVAL1'] = c.ra.deg
hdr.comments['CRVAL1'] = 'Reference pixel value in RA (deg)'
hdr['CRVAL2'] = c.dec.deg
hdr.comments['CRVAL2'] = 'Reference pixel value in DEC (deg)'
hdr['CDELT1'] = -csize_deg
hdr.comments['CDELT1'] = 'Pixel increment in RA (deg)'
hdr['CDELT2'] = csize_deg
hdr.comments['CDELT2'] = 'Pixel size in DEC (deg)'
if image_type in ('flux', 'tau'):
hdr['CDELT3'] = 1.
hdr.comments['CDELT3'] = 'Frequency increment (Hz)'
hdr['CRPIX3'] = 0.5
hdr.comments['CRPIX3'] = 'Reference frequency (channel number)'
hdr['CRVAL3'] = freq
hdr.comments['CRVAL3'] = 'Reference frequency (Hz)'