-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreate_radmc3d_input.py
3565 lines (2923 loc) · 212 KB
/
create_radmc3d_input.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import numpy as np
import tables
import sys
import struct
import os
#sys.path.append('/mnt/home/nroy/rt-pipeline-tools')
sys.path.append('~/galaxy-mock-obs-pipeline/rt-pipeline-tools')
from mpi4py import MPI
import read_chimes as rc
import compute_raga15 as r15
import compute_depletion as depl
import sys
sys.path.append('ext-lib/pfh_python')
import gadget as g
from gizmopy.load_fire_snap import load_fire_snap
from gizmopy.load_from_snapshot import load_from_snapshot
parameters = {"infile" : None, # Input snapshot file
"species_file" : None, # CHIMES species to include on the AMR grid
"SB99_dir" : None, # Directory containing the Starburst99 spectra
"n_cell_base" : 16, # size of base grid (in x, y and z)
"max_part_per_cell" : 8, # Max number of particles in a cell
"refinement_scheme" : 0, # 0 - Refine on gas; 1 - refine on gas + stars
# "box_size" : 1.0, # Total size of the AMR grid, in code units
"centre_x" : 0.0, # Position of the centre in the x direction
"centre_y" : 0.0, # Position of the centre in the y direction
"centre_z" : 0.0, # Position of the centre in the z direction
"dust_model" : "DC16", # DC16 - De Cia+ 2016 depletion, constant - constant dust-to-metals ratio
"dust_thresh" : 1.0e6, # Exclude dust at gas temperatures above this threshold
"b_turb" : 7.1, # Turbulent doppler width (km s^-1)
"include_H_level_pop" : 1, # If set to 1, write out H level populations for Halpha and Hbeta
"unit_density" : 6.771194847794874e-22, # Convert code units -> g cm^-3
"unit_time_Myr" : 977.8943899409334, # Convert code units -> Myr
"cosmo_flag" : 0, # 0 - non-cosmological (Type 2 and 3 are also stars),
# 1 - cosmological (NOTE: not yet fully implemented) #niranjan: now implemented.
"use_eqm_abundances" : 0, # 0 - use non-eq abundance array, 1 - use eqm abundances.
"adaptive_domain_decomposition" : 0, # 0 - Equal domain sizes, 2 - adaptive domain sizes
"automatic_domain_decomposition" : 1, # 0 - Manual, 1 - Automatic
"initial_domain_spacing" : 0, # 0 - uniform spacing, 1 - concentrated in the centre
"N_chunk_x" : 1, # Number of chunks in the x-direction for manual decomposition
"N_chunk_y" : 1, # Number of chunks in the y-direction for manual decomposition
"N_chunk_z" : 1, # Number of chunks in the z-direction for manual decomposition
"include_stars" : 0, # 0 - ignore stars; 1 - include stars
"N_age_bins" : 9, # Specifies how many stellar age bins to include, starting from the youngest
"N_age_bins_refine" : 8, # How many stellar age bins to refine on, if refinement_scheme == 1
"smooth_stars" : 1, # Smooth stars if this flag is set to 1.
"star_hsml_file" : None, # File containing the stellar smoothing lengths.
"max_star_hsml" : 0.1, # Max star hsml, in code units. If < 0, do not impose a maximum.
"max_velocity" : -1.0, # If positive, limit the maximum velocities of gas particles to be no greater than this value in x, y and z (in code units).
"verbose_log_files" : 0, # Set to 1 to write out log files from each MPI task.
"ChimesOutputFile" : None, #niranjan: when Chimes data is not abailable with the simulation
"Multifiles" : 1 , #niranjan: In case of FIRE like simulations with multifile snapshots}
"Rotate_to_faceon" : 0, #niranjan: If the face on version of galaxy is wanted
"Subtract_CoMvelocity" : 1 } #niranjan: If want to subtract velocity of the center of mass of the galaxy
# Defines the stellar age bins, as used with CHIMES.
# Note that we have also included >1 Gyr as an
# additional age bin.
log_stellar_age_Myr_bin_max = np.array([0.0, 0.2, 0.4, 0.6, 0.8, 1.0, 2.0, 3.0, 10.0])
def read_parameters(infile):
fd = open(infile, "r")
for line in fd:
if len(line.strip()) < 1:
continue
elif line.strip()[0] == "#":
continue
else:
values = line.split()
if values[0] in parameters:
try:
parameters[values[0]] = eval(values[1])
except:
parameters[values[0]] = values[1]
else:
raise KeyError("Parameter %s not recognised. Aborting" % (values[0], ))
fd.close()
dust_to_gas_saturated = depl.compute_dust_to_gas_ratio(1000.0, 1)
dust_to_gas_graphite = 2.34311e-3 # At solar metallicity (0.0129) and full depletion
dust_to_gas_silicate = 3.96089e-3 # At solar metallicity (0.0129) and full depletion
def cubic_spline_low(x, h):
return (8.0 / (np.pi * (h ** 3.0))) * (1.0 - (6.0 * (x ** 2.0)) + (6.0 * (x ** 3.0)))
def cubic_spline_hi(x, h):
return (8.0 / (np.pi * (h ** 3.0))) * 2.0 * ((1.0 - x) ** 3.0)
def cubic_spline(x, h):
if x < 0.5:
return cubic_spline_low(x, h)
elif x < 1.0:
return cubic_spline_hi(x, h)
else:
return 0.0
# This routine takes an integer, decomposes it into
# all combinations of three factors, then selects the
# three with the minimum range. We use these to decompose
# the base grid between MPI tasks.
def decompose_3d_factors(x):
factor_list= []
range_list = []
for i in range(1, x + 1):
if x % i == 0:
y = x // i
for j in range(1, y + 1):
if y % j == 0:
z = y // j
r = max([i, j, z]) - min([i, j ,z])
factor_list.append([i, j, z])
range_list.append(r)
factor_list = np.array(factor_list)
range_list = np.array(range_list)
ind_sort = range_list.argsort()
return factor_list[ind_sort][0]
def write_task_log(task_no, message):
try:
log_file = "log_task_%d.txt" % (task_no, )
fd = open(log_file, "a")
fd.write(message)
fd.write("\n")
fd.close()
except OSError:
print("OS error when writing task log file. Continuing.")
sys.stdout.flush()
return
def hubble_z(redshift, h=0.702, Omega0=0.272, OmegaLambda=0.728): #niranjan: from daa_python library
# return Hubble factor in 1/sec for a given redshift
HUBBLE = 3.2407789e-18 #in h/sec
ascale = 1. / ( 1. + redshift )
hubble_a = HUBBLE * h * np.sqrt( Omega0 / ascale**3 + (1. - Omega0 - OmegaLambda) / ascale**2 + OmegaLambda ) # in 1/sec !!
return hubble_a
class node():
def __init__(self, parent_node, N_species, emitter_flag_list, atomic_mass_list):
if parent_node == 0:
self.parent_node = parent_node
self.level = 1
else:
self.parent_node = parent_node
self.level = parent_node.level + 1
self.pos = np.zeros(3)
self.width = 0
self.N_part = 0
self.N_star_part = 0 # Only includes star particles in age bins that we refine the AMR grid on.
self.daughter_nodes = 0
self.leaf = 0 # Set to 1 if this cell has no daughter nodes.
self.N_species = N_species
self.emitter_flag_list = emitter_flag_list
self.atomic_mass_list = atomic_mass_list
# Ion abundances
self.species = np.zeros(N_species, dtype = np.float64)
# Ion-weighted temperatures
self.temperature_species = np.zeros(N_species, dtype = np.float64)
#nHtot --> overall gas density, not specific to any species #niranjan
self.nHtot = 0.0
#temperature --> overall gas temperature, not specific to any species #niranjan
self.temperature = 0.0
#mass --> gas mass in cells, #niranjan
self.mass = 0.0
#velocity --> velocity in cells, #niranjan
self.velocity = np.zeros((1,3), dtype = np.float)
self.momentum = np.zeros((1,3), dtype = np.float) #niranjan
# Ion-weighted nH
self.nH_species = np.zeros(N_species, dtype = np.float64)
# Ion-weighted velocities
self.velocity_species = np.zeros((N_species, 3), dtype = np.float64)
# Dust density
self.rho_dust = 0.0
# Stellar densities
self.rho_star = np.zeros(parameters["N_age_bins"], dtype = np.float64)
# H level populations, for recombination lines
# Using Osterbrock & Ferland (2006)
self.H_level_pop_OF06 = np.zeros((2, 3), dtype = np.float64)
# Using Raga et al. (2015)
self.HII_level_pop_R15 = np.zeros((2, 3), dtype = np.float64)
self.HI_level_pop_R15 = np.zeros((2, 3), dtype = np.float64)
def write_restart_node(self, fd):
buf = struct.pack("3i", self.leaf, self.N_part, self.N_star_part)
fd.write(buf)
buf = struct.pack("4d", self.pos[0], self.pos[1], self.pos[2], self.width)
fd.write(buf)
if self.leaf == 0:
for k in range(2):
for j in range(2):
for i in range(2):
self.daughter_nodes[i, j, k].write_restart_node(fd)
return
def read_restart_node(self, fd):
buf = fd.read(3 * 4)
data = struct.unpack("3i", buf)
self.leaf = data[0]
self.N_part = data[1]
self.N_star_part = data[2]
buf = fd.read(4 * 8)
data = struct.unpack("4d", buf)
self.pos[0] = data[0]
self.pos[1] = data[1]
self.pos[2] = data[2]
self.width = data[3]
if self.leaf == 0:
self.daughter_nodes = np.ndarray((2, 2, 2), dtype = np.object)
for k in range(2):
for j in range(2):
for i in range(2):
self.daughter_nodes[i, j, k] = node(self, self.N_species, self.emitter_flag_list, self.atomic_mass_list)
self.daughter_nodes[i, j, k].read_restart_node(fd)
return
def write_restart_densities(self, fd):
if self.leaf == 1:
for idx in range(self.N_species):
buf = struct.pack("6f", self.species[idx],
self.temperature_species[idx],
self.nH_species[idx],
self.velocity_species[idx, 0],
self.velocity_species[idx, 1],
self.velocity_species[idx, 2])
fd.write(buf)
buf = struct.pack("f", self.rho_dust)
fd.write(buf)
# buf = struct.pack("f", self.nHtot) #niranjan: writing global density
# fd.write(buf)
# buf = struct.pack("f", self.temperature) #niranjan: writing global density
# fd.write(buf)
for idx in range(parameters["N_age_bins"]):
buf = struct.pack("f", self.rho_star[idx])
fd.write(buf)
for idx_x in range(2):
for idx_y in range(3):
buf = struct.pack("3f", self.H_level_pop_OF06[idx_x, idx_y], self.HII_level_pop_R15[idx_x, idx_y], self.HI_level_pop_R15[idx_x, idx_y])
fd.write(buf)
else:
for k in range(2):
for j in range(2):
for i in range(2):
self.daughter_nodes[i, j, k].write_restart_densities(fd)
return
def read_restart_densities(self, fd):
if self.leaf == 1:
for idx in range(self.N_species):
buf = fd.read(7 * 4)
data = struct.unpack("6f", buf)
self.species[idx] = data[0]
self.temperature_species[idx] = data[1]
self.nH_species[idx] = data[2]
self.velocity_species[idx, 0] = data[3]
self.velocity_species[idx, 1] = data[4]
self.velocity_species[idx, 2] = data[5]
buf = fd.read(4)
data = struct.unpack("f", buf)
self.rho_dust = data[0]
#buf = fd.read(4) #niranjan
#data = struct.unpack("f", buf)
#self.nHtot = data[0]
#buf = fd.read(4) #niranjan
#data = struct.unpack("f", buf)
#self.temperature = data[0]
for idx in range(parameters["N_age_bins"]):
buf = fd.read(4)
data = struct.unpack("f", buf)
self.rho_star[idx] = data[0]
for idx_x in range(2):
for idx_y in range(3):
buf = fd.read(3 * 4)
data = struct.unpack("3f", buf)
self.H_level_pop_OF06[idx_x, idx_y] = data[0]
self.HII_level_pop_R15[idx_x, idx_y] = data[1]
self.HI_level_pop_R15[idx_x, idx_y] = data[2]
else:
for k in range(2):
for j in range(2):
for i in range(2):
self.daughter_nodes[i, j, k].read_restart_densities(fd)
return
def find_particles(self, particle_coords, particle_star_coords):
# This routine finds the indices of all particles in
# particle_coords that are within this cell
x_min = self.pos[0] - (self.width / 2.0)
x_max = self.pos[0] + (self.width / 2.0)
y_min = self.pos[1] - (self.width / 2.0)
y_max = self.pos[1] + (self.width / 2.0)
z_min = self.pos[2] - (self.width / 2.0)
z_max = self.pos[2] + (self.width / 2.0)
part_ind = ((particle_coords[:, 0] > x_min) & (particle_coords[:, 0] < x_max) &
(particle_coords[:, 1] > y_min) & (particle_coords[:, 1] < y_max) &
(particle_coords[:, 2] > z_min) & (particle_coords[:, 2] < z_max))
self.N_part = len(particle_coords[part_ind, 0])
if parameters["refinement_scheme"] == 1:
part_ind_star = ((particle_star_coords[:, 0] > x_min) & (particle_star_coords[:, 0] < x_max) &
(particle_star_coords[:, 1] > y_min) & (particle_star_coords[:, 1] < y_max) &
(particle_star_coords[:, 2] > z_min) & (particle_star_coords[:, 2] < z_max))
self.N_star_part = len(particle_star_coords[part_ind_star, 0])
else:
part_ind_star = None
return part_ind, part_ind_star
def compute_cell_densities(self,
particle_coords,
particle_hsml,
particle_mass,
particle_mass_species,
particle_temperature,
particle_velocity,
particle_metallicity,
particle_nH,
particle_nHtot, #niranjan 2024
sum_wk):
# Performs an SPH interpolation of gas densities onto the
# centre of this cell.
if self.leaf == 1:
relative_pos = self.pos - particle_coords
ind_smooth = ((relative_pos[:, 0] > -particle_hsml) &
(relative_pos[:, 0] < particle_hsml) &
(relative_pos[:, 1] > -particle_hsml) &
(relative_pos[:, 1] < particle_hsml) &
(relative_pos[:, 2] > -particle_hsml) &
(relative_pos[:, 2] < particle_hsml))
radii = np.sqrt(((relative_pos[ind_smooth, 0]) ** 2.0) +
((relative_pos[ind_smooth, 1]) ** 2.0) +
((relative_pos[ind_smooth, 2]) ** 2.0))
hsml_smooth = particle_hsml[ind_smooth]
radii /= hsml_smooth
sum_wk_smooth = sum_wk[ind_smooth]
mass_smooth = particle_mass[ind_smooth]
species_smooth = particle_mass_species[ind_smooth]
T_smooth = particle_temperature[ind_smooth]
vel_smooth = particle_velocity[ind_smooth]
Z_smooth = particle_metallicity[ind_smooth]
nH_smooth = particle_nH[ind_smooth]
nHtot_smooth = particle_nHtot[ind_smooth] #niranjan 2024
ind_r = (radii < 1.0)
radii_r = radii[ind_r]
hsml_r = hsml_smooth[ind_r]
sum_wk_r = sum_wk_smooth[ind_r]
mass_r = mass_smooth[ind_r]
species_r = species_smooth[ind_r]
T_r = T_smooth[ind_r]
vel_r = vel_smooth[ind_r]
Z_r = Z_smooth[ind_r]
nH_r = nH_smooth[ind_r]
nHtot_r = nHtot_smooth[ind_r] #niranjan 2024
wk = np.zeros(len(mass_r), dtype = np.float64)
ind_low = (radii_r < 0.5)
wk[ind_low] += cubic_spline_low(radii_r[ind_low], hsml_r[ind_low])
ind_hi = (radii_r >= 0.5)
wk[ind_hi] += cubic_spline_hi(radii_r[ind_hi], hsml_r[ind_hi])
self.species += np.sum(species_r.transpose() * wk / sum_wk_r, axis = 1) # Msol
self.temperature_species += np.sum(species_r.transpose() * T_r * wk / sum_wk_r, axis = 1)
self.nH_species += np.sum(species_r.transpose() * nH_r * wk / sum_wk_r, axis = 1)
self.mass += np.sum(mass_r * wk / sum_wk_r) #niranjan
#self.nHtot += np.sum(nHtot_r * wk / sum_wk_r) #niranjan
self.temperature += np.sum(mass_r * T_r * wk / sum_wk_r) #niranjan
#self.temperature += np.sum(T_r * wk / sum_wk_r) #niranjan: removing mass weight for testing purposes
self.temperature /= self.mass #niranjan
#niranjan: adding the following six lines to calculate the velocity in each cell not weighted by the different species.
self.momentum[:,0] += np.sum(mass_r * vel_r[:,0] * wk / sum_wk_r)
self.momentum[:,1] += np.sum(mass_r * vel_r[:,1] * wk / sum_wk_r)
self.momentum[:,2] += np.sum(mass_r * vel_r[:,2] * wk / sum_wk_r)
self.velocity[:,0] = self.momentum[:,0] / self.mass
self.velocity[:,1] = self.momentum[:,1] / self.mass
self.velocity[:,2] = self.momentum[:,2] / self.mass
msun_cgs = 1.988409870698051e+33
kpc_cgs = 3.0856775814913673e+21
protonmass_cgs = 1.67262192369e-24
self.nHtot = self.mass * (msun_cgs / kpc_cgs**3 / protonmass_cgs)/ (self.width ** 3.0) #cm^-3 #niranajn: dividing mass by volume to get density nH
self.velocity_species[:, 0] += np.sum(species_r.transpose() * vel_r[:, 0] * wk / sum_wk_r, axis = 1)
self.velocity_species[:, 1] += np.sum(species_r.transpose() * vel_r[:, 1] * wk / sum_wk_r, axis = 1)
self.velocity_species[:, 2] += np.sum(species_r.transpose() * vel_r[:, 2] * wk / sum_wk_r, axis = 1)
for i in range(len(mass_r)):
if parameters["dust_model"] == "DC16":
if T_r[i] < parameters["dust_thresh"]:
self.rho_dust += (depl.compute_dust_to_gas_ratio(nH_r[i], 1) / dust_to_gas_saturated) * (Z_r[i] / 0.0129) * mass_r[i] * wk[i] / sum_wk_r[i] # Msol
elif parameters["dust_model"] == "constant":
self.rho_dust += (Z_r[i] / 0.0129) * mass_r[i] * wk[i] / sum_wk_r[i] # Msol
for j in range(self.N_species):
if self.species[j] > 0.0:
self.temperature_species[j] /= self.species[j]
self.nH_species[j] /= self.species[j]
self.velocity_species[j, :] /= self.species[j]
# Convert from masses to densities.
self.species /= (self.width ** 3.0) # Msol kpc^-3
self.rho_dust /= (self.width ** 3.0) # Msol kpc^-3
else:
for k in range(2):
for j in range(2):
for i in range(2):
relative_pos = self.daughter_nodes[i, j, k].pos - particle_coords
overlap_size = particle_hsml + (self.daughter_nodes[i, j, k].width / 2.0)
ind_smooth = ((relative_pos[:, 0] > -overlap_size) &
(relative_pos[:, 0] < overlap_size) &
(relative_pos[:, 1] > -overlap_size) &
(relative_pos[:, 1] < overlap_size) &
(relative_pos[:, 2] > -overlap_size) &
(relative_pos[:, 2] < overlap_size))
self.daughter_nodes[i, j, k].compute_cell_densities(particle_coords[ind_smooth],
particle_hsml[ind_smooth],
particle_mass[ind_smooth],
particle_mass_species[ind_smooth],
particle_temperature[ind_smooth],
particle_velocity[ind_smooth],
particle_metallicity[ind_smooth],
particle_nH[ind_smooth],
particle_nHtot[ind_smooth], #niranjan 2024
sum_wk[ind_smooth])
def compute_cell_stellar_densities(self, particle_star_coords, particle_star_mass, age_index):
# Places star particles into the cell as point particles (i.e. no SPH smoothing)
if self.leaf == 1:
ind_cell = ((particle_star_coords[:, 0] > (self.pos[0] - (self.width / 2.0))) &
(particle_star_coords[:, 0] < (self.pos[0] + (self.width / 2.0))) &
(particle_star_coords[:, 1] > (self.pos[1] - (self.width / 2.0))) &
(particle_star_coords[:, 1] < (self.pos[1] + (self.width / 2.0))) &
(particle_star_coords[:, 2] > (self.pos[2] - (self.width / 2.0))) &
(particle_star_coords[:, 2] < (self.pos[2] + (self.width / 2.0))))
self.rho_star[age_index] += sum(particle_star_mass[ind_cell]) / (self.width ** 3.0) # Msol kpc^-3
else:
for k in range(2):
for j in range(2):
for i in range(2):
self.daughter_nodes[i, j, k].compute_cell_stellar_densities(particle_star_coords, particle_star_mass, age_index)
def compute_cell_smoothed_stellar_densities(self,
particle_star_coords,
particle_star_hsml,
particle_star_mass,
sum_wk_star,
age_index):
# Performs an SPH interpolation of stellar densities onto the
# centre of this cell.
if self.leaf == 1:
# We only pass particles within
# the smoothing kernel to this routine.
relative_pos = self.pos - particle_star_coords
ind_smooth = ((relative_pos[:, 0] > -particle_star_hsml) &
(relative_pos[:, 0] < particle_star_hsml) &
(relative_pos[:, 1] > -particle_star_hsml) &
(relative_pos[:, 1] < particle_star_hsml) &
(relative_pos[:, 2] > -particle_star_hsml) &
(relative_pos[:, 2] < particle_star_hsml))
radii = np.sqrt(((relative_pos[ind_smooth, 0]) ** 2.0) +
((relative_pos[ind_smooth, 1]) ** 2.0) +
((relative_pos[ind_smooth, 2]) ** 2.0))
hsml_smooth = particle_star_hsml[ind_smooth]
sum_wk_smooth = sum_wk_star[ind_smooth]
mass_smooth = particle_star_mass[ind_smooth]
radii /= hsml_smooth
ind_r = (radii < 1.0)
radii_r = radii[ind_r]
hsml_r = hsml_smooth[ind_r]
sum_wk_r = sum_wk_smooth[ind_r]
mass_r = mass_smooth[ind_r]
wk = np.zeros(len(mass_r), dtype = np.float64)
ind_low = (radii_r < 0.5)
wk[ind_low] += cubic_spline_low(radii_r[ind_low], hsml_r[ind_low])
ind_hi = (radii_r >= 0.5)
wk[ind_hi] += cubic_spline_hi(radii_r[ind_hi], hsml_r[ind_hi])
self.rho_star[age_index] += np.sum(mass_r * wk / sum_wk_r) # Msol
# Convert from mass to density.
self.rho_star[age_index] /= (self.width ** 3.0) # Msol kpc^-3
else:
for k in range(2):
for j in range(2):
for i in range(2):
relative_pos = self.daughter_nodes[i, j, k].pos - particle_star_coords
overlap_size = particle_star_hsml + (self.daughter_nodes[i, j, k].width / 2.0)
ind_smooth = ((relative_pos[:, 0] > -overlap_size) &
(relative_pos[:, 0] < overlap_size) &
(relative_pos[:, 1] > -overlap_size) &
(relative_pos[:, 1] < overlap_size) &
(relative_pos[:, 2] > -overlap_size) &
(relative_pos[:, 2] < overlap_size))
self.daughter_nodes[i, j, k].compute_cell_smoothed_stellar_densities(particle_star_coords[ind_smooth],
particle_star_hsml[ind_smooth],
particle_star_mass[ind_smooth],
sum_wk_star[ind_smooth], age_index)
def compute_kernel_weights(self, particle_coords, particle_hsml):
# Computes the kernel weights of all particles that overlap
# with this cell. These will be used to compute sum_wk_i.
if self.leaf == 1:
relative_pos = self.pos - particle_coords
ind_smooth = ((relative_pos[:, 0] > -particle_hsml) &
(relative_pos[:, 0] < particle_hsml) &
(relative_pos[:, 1] > -particle_hsml) &
(relative_pos[:, 1] < particle_hsml) &
(relative_pos[:, 2] > -particle_hsml) &
(relative_pos[:, 2] < particle_hsml))
radii = np.sqrt(((relative_pos[ind_smooth, 0]) ** 2.0) +
((relative_pos[ind_smooth, 1]) ** 2.0) +
((relative_pos[ind_smooth, 2]) ** 2.0))
hsml_smooth = particle_hsml[ind_smooth]
radii /= hsml_smooth
wk_outputs = np.zeros(len(particle_coords), dtype = np.float64)
wk_smooth = np.zeros(len(radii), dtype = np.float64)
ind_low = (radii < 0.5)
wk_smooth[ind_low] += cubic_spline_low(radii[ind_low], hsml_smooth[ind_low])
ind_hi = ((radii >= 0.5) & (radii < 1.0))
wk_smooth[ind_hi] += cubic_spline_hi(radii[ind_hi], hsml_smooth[ind_hi])
wk_outputs[ind_smooth] += wk_smooth
return wk_outputs
else:
wk_outputs = np.zeros(len(particle_coords), dtype = np.float64)
for k in range(2):
for j in range(2):
for i in range(2):
relative_pos = self.daughter_nodes[i, j, k].pos - particle_coords
overlap_size = particle_hsml + (self.daughter_nodes[i, j, k].width / 2.0)
ind_smooth = ((relative_pos[:, 0] > -overlap_size) &
(relative_pos[:, 0] < overlap_size) &
(relative_pos[:, 1] > -overlap_size) &
(relative_pos[:, 1] < overlap_size) &
(relative_pos[:, 2] > -overlap_size) &
(relative_pos[:, 2] < overlap_size))
wk_outputs[ind_smooth] += self.daughter_nodes[i, j, k].compute_kernel_weights(particle_coords[ind_smooth], particle_hsml[ind_smooth])
return wk_outputs
def split_cells(self, particle_coords, particle_star_coords):
# If the number of particles in this cell exceeds the
# threshold, it is divided into 8 daughter cells. This
# routine is then recursively called on them as well,
# to continue splitting the cells until the criterion
# is met.
if (self.N_part > parameters["max_part_per_cell"]) or (self.N_star_part > parameters["max_part_per_cell"] and parameters["refinement_scheme"] == 1):
self.daughter_nodes = np.ndarray((2, 2, 2), dtype = np.object)
for k in range(2):
for j in range(2):
for i in range(2):
self.daughter_nodes[i, j, k] = node(self, self.N_species, self.emitter_flag_list, self.atomic_mass_list)
self.daughter_nodes[i, j, k].width = self.width / 2.0
self.daughter_nodes[i, j, k].pos[0] = self.pos[0] - (self.width / 4.0) + (i * self.width / 2.0)
self.daughter_nodes[i, j, k].pos[1] = self.pos[1] - (self.width / 4.0) + (j * self.width / 2.0)
self.daughter_nodes[i, j, k].pos[2] = self.pos[2] - (self.width / 4.0) + (k * self.width / 2.0)
part_ind, part_ind_star = self.daughter_nodes[i, j, k].find_particles(particle_coords, particle_star_coords)
self.daughter_nodes[i, j, k].split_cells(particle_coords[part_ind, :], particle_star_coords[part_ind_star, :])
del part_ind
del part_ind_star
else:
self.leaf = 1
def determine_levels(self):
# Walks through the tree and adds up leaves and
# branches, and determines the max level
if self.leaf == 1:
return self.level, 0, 1
else:
max_level = 1
n_branch = 1
n_leaf = 0
for k in range(2):
for j in range(2):
for i in range(2):
next_level, next_branch, next_leaf = self.daughter_nodes[i, j, k].determine_levels()
n_branch += next_branch
n_leaf += next_leaf
if next_level > max_level:
max_level = next_level
return max_level, n_branch, n_leaf
def compute_total_species_mass(self, species_index):
volume = self.width ** 3.0 # kpc^3
if self.leaf == 1:
return self.species[species_index] * volume # Msol
else:
branch_species = 0.0
for k in range(2):
for j in range(2):
for i in range(2):
branch_species += self.daughter_nodes[i, j, k].compute_total_species_mass(species_index)
return branch_species
def compute_total_stellar_mass(self, age_index):
volume = self.width ** 3.0 # kpc^3
if self.leaf == 1:
return self.rho_star[age_index] * volume # Msol
else:
branch_mass = 0.0
for k in range(2):
for j in range(2):
for i in range(2):
branch_mass += self.daughter_nodes[i, j, k].compute_total_stellar_mass(age_index)
return branch_mass
def compute_H_level_populations(self, elec_index, HI_index, HII_index):
# These aren't the real level populations.
# Instead, we create a 3-level atom, and
# set the n=3 level population to give the
# required H-alpha or H-beta emissivity.
# We then put the rest of it in n=1.
# NOTE: The RADMC-3D levelpop input files
# need the level populations in units of
# cm^-3, i.e. these are the densities of
# hydrogen in the given level, and not
# relative fractions.
if self.leaf == 1:
ne = self.species[elec_index] # Msol kpc^-3
nHI = self.species[HI_index] # Msol kpc^-3
nHII = self.species[HII_index] # Msol kpc^-3
ne *= 6.77119485e-32 / (self.atomic_mass_list[elec_index] * 1.6726218e-24) # Converts to cm^-3
nHI *= 6.77119485e-32 / (self.atomic_mass_list[HI_index] * 1.6726218e-24) # Converts to cm^-3
nHII *= 6.77119485e-32 / (self.atomic_mass_list[HII_index] * 1.6726218e-24) # Converts to cm^-3
T_HI = self.temperature_species[HI_index]
T_HII = self.temperature_species[HII_index]
h_nu_alpha = 3.0301602666779086e-12 # erg
h_nu_beta = 4.090713693193314e-12 # erg
A_alpha = 6.46e7 # s^-1
A_beta = 2.06e7 # s^-1
# First, using Osterbrock & Ferland (2006).
# H-alpha
if T_HII > 0.0:
rec_alpha_OF06 = 7.86e-14 * ((T_HII / 1.0e4) ** -1.0) # cm^3 s^-1
else:
rec_alpha_OF06 = 0.0
self.H_level_pop_OF06[0, 2] = nHII * ne * rec_alpha_OF06 / A_alpha
self.H_level_pop_OF06[0, 0] = nHII - self.H_level_pop_OF06[0, 2]
# H-beta
if T_HII > 0.0:
rec_beta_OF06 = 3.67e-14 * ((T_HII / 1.0e4) ** -0.91) # cm^3 s^-1
else:
rec_beta_OF06 = 0.0
self.H_level_pop_OF06[1, 2] = nHII * ne * rec_beta_OF06 / A_beta
self.H_level_pop_OF06[1, 0] = nHII - self.H_level_pop_OF06[1, 2]
# Raga et al. (2015): recombination of HII
if T_HII > 0.0:
HII_rec_alpha_R15 = r15.raga15_Halpha_rec_caseB(T_HII) / h_nu_alpha # cm^3 s^-1
HII_rec_beta_R15 = r15.raga15_Hbeta_rec_caseB(T_HII) / h_nu_beta # cm^3 s^-1
else:
HII_rec_alpha_R15 = 0.0
HII_rec_beta_R15 = 0.0
self.HII_level_pop_R15[0, 2] = ne * nHII * HII_rec_alpha_R15 / A_alpha
self.HII_level_pop_R15[0, 0] = nHII - self.HII_level_pop_R15[0, 2]
self.HII_level_pop_R15[1, 2] = ne * nHII * HII_rec_beta_R15 / A_beta
self.HII_level_pop_R15[1, 0] = nHII - self.HII_level_pop_R15[1, 2]
# Raga et al. (2015): collisional excitation of HI
if T_HI > 0.0:
HI_col_alpha_R15 = r15.raga15_Halpha_col_caseB(T_HI) / h_nu_alpha # cm^3 s^-1
HI_col_beta_R15 = r15.raga15_Hbeta_col_caseB(T_HI) / h_nu_beta # cm^3 s^-1
else:
HI_col_alpha_R15 = 0.0
HI_col_beta_R15 = 0.0
self.HI_level_pop_R15[0, 2] = ne * nHI * HI_col_alpha_R15 / A_alpha
self.HI_level_pop_R15[0, 0] = nHI - self.HI_level_pop_R15[0, 2]
self.HI_level_pop_R15[1, 2] = ne * nHI * HI_col_beta_R15 / A_beta
self.HI_level_pop_R15[1, 0] = nHI - self.HI_level_pop_R15[1, 2]
else:
for k in range(2):
for j in range(2):
for i in range(2):
self.daughter_nodes[i, j, k].compute_H_level_populations(elec_index, HI_index, HII_index)
def walk_cells(self, species_file_list, T_file_list, nH_file_list, vel_file_list, turb_file, vol_file, nHtot_file, temperature_file, velocity_file): #niranjan: adding nHtot_file, temperature_file, velocity file that are not weighted by the different species
if self.leaf == 1:
emitter_index = 0
for i in range(self.N_species):
buf = struct.pack("d", self.species[i] * 6.77119485e-32 / (self.atomic_mass_list[i] * 1.6726218e-24)) # Converts to mol cm^-3
species_file_list[i].write(buf)
species_file_list[i].flush()
if self.emitter_flag_list[i] == 1:
# If an ion is absent from a cell, the corresponding T, nH and velocity will be zero.
# We should set a minimum to the temperature, to avoid any problems.
buf = struct.pack("d", max(self.temperature_species[i], 10.0)) # K
T_file_list[emitter_index].write(buf)
T_file_list[emitter_index].flush()
buf = struct.pack("d", self.nH_species[i]) # cm^-3
nH_file_list[emitter_index].write(buf)
nH_file_list[emitter_index].flush()
buf = struct.pack("3d", self.velocity_species[i, 0] * 1.0e5, self.velocity_species[i, 1] * 1.0e5, self.velocity_species[i, 2] * 1.0e5) # cm s^-1
vel_file_list[emitter_index].write(buf)
vel_file_list[emitter_index].flush()
emitter_index += 1
# Assume a constant microturbulence width b everywhere.
buf = struct.pack("d", parameters["b_turb"] * 1.0e5) # cm s^-1
turb_file.write(buf)
turb_file.flush()
#vol_file.write("%.6e \n" % (self.width ** 3.0, )) # kpc^3
#vol_file.flush()
#nirnjan: adding overall cell density as a binary file
buf = struct.pack("d", self.nHtot)
nHtot_file.write(buf)
nHtot_file.flush()
#nHtot_file.write("%.6e \n" % (self.nHtot, )) #cm^-3 #niranjan
#nHtot_file.flush()
#niranjan: adding velocity of the cells that's not species weighted
buf = struct.pack("3d", self.velocity[:,0] * 1.0e5, self.velocity[:,1] * 1.0e5, self.velocity[:,2] * 1.0e5) # cm s^-1
velocity_file.write(buf)
velocity_file.flush()
vol_file.write("%.6e \n" % (self.width ** 3.0, )) # kpc^3
vol_file.flush()
#niranjan: saving mass-weighted cell temperature data as binary file
buf = struct.pack("d", self.temperature) # K
temperature_file.write(buf)
temperature_file.flush()
else:
for k in range(2):
for j in range(2):
for i in range(2):
self.daughter_nodes[i, j, k].walk_cells(species_file_list, T_file_list, nH_file_list, vel_file_list, turb_file, vol_file, nHtot_file, temperature_file, velocity_file) #niranjan: adding nHtot_file, temperature_file
def walk_cells_dust(self, dust_file, dust_T_file, dust_species):
if self.leaf == 1:
if dust_species == 0:
# Graphite density
buf = struct.pack("d", self.rho_dust * dust_to_gas_graphite * 6.77119485e-32) # Converts to g cm^-3
elif dust_species == 1:
# Silicate density
buf = struct.pack("d", self.rho_dust * dust_to_gas_silicate * 6.77119485e-32) # Converts to g cm^-3
else:
print("ERROR: dust_species %d not recognised." % (dust_species, ))
sys.stdout.flush()
return
dust_file.write(buf)
dust_T_file.write("0.0 \n")
else:
for k in range(2):
for j in range(2):
for i in range(2):
self.daughter_nodes[i, j, k].walk_cells_dust(dust_file, dust_T_file, dust_species)
def walk_cells_stars(self, star_file, age_index):
if self.leaf == 1:
buf = struct.pack("d", self.rho_star[age_index] * 6.77119485e-32) # Converts to g cm^-3
star_file.write(buf)
else:
for k in range(2):
for j in range(2):
for i in range(2):
self.daughter_nodes[i, j, k].walk_cells_stars(star_file, age_index)
def walk_cells_H_level_pop(self, pop_file_OF06, pop_file_R15_HII, pop_file_R15_HI, line_index):
if self.leaf == 1:
line = "%.6e %.6e %.6e \n" % (self.H_level_pop_OF06[line_index, 0], self.H_level_pop_OF06[line_index, 1], self.H_level_pop_OF06[line_index, 2])
pop_file_OF06.write(line)
line = "%.6e %.6e %.6e \n" % (self.HII_level_pop_R15[line_index, 0], self.HII_level_pop_R15[line_index, 1], self.HII_level_pop_R15[line_index, 2])
pop_file_R15_HII.write(line)
line = "%.6e %.6e %.6e \n" % (self.HI_level_pop_R15[line_index, 0], self.HI_level_pop_R15[line_index, 1], self.HI_level_pop_R15[line_index, 2])
pop_file_R15_HI.write(line)
else:
for k in range(2):
for j in range(2):
for i in range(2):
self.daughter_nodes[i, j, k].walk_cells_H_level_pop(pop_file_OF06, pop_file_R15_HII, pop_file_R15_HI, line_index)
def determine_amr_grid(self, amr_file):
if self.leaf == 1:
amr_file.write("0 \n")
else:
amr_file.write("1 \n")
for k in range(2):
for j in range(2):
for i in range(2):
k_index = k
self.daughter_nodes[i, j, k_index].determine_amr_grid(amr_file)
def write_headers(amr_file,
species_file_list,
T_file_list,
nH_file_list,
vel_file_list,
turb_file,
dust_file,
dust_T_file,
star_file,
grid_array_arg,
grid_width,
level_max,
branch_max,
leaf_max):
iformat = 1
precis = 8
nrcells = leaf_max
nrspec = 2
nr_star_spec = parameters["N_age_bins"]
amr_file.write(u"1 \n") # iformat
amr_file.write(u"1 \n") # grid style
amr_file.write(u"0 \n") # coord system
amr_file.write(u"0 \n") # grid info
amr_file.write(u"1 1 1 \n") # incl x, y, z
output_line = u"%d %d %d \n" % (parameters["n_cell_base"], parameters["n_cell_base"], parameters["n_cell_base"])
amr_file.write(output_line)
leaf_branch_max = leaf_max + branch_max
output_line = u"%d %d %d \n" % (level_max, leaf_branch_max, leaf_branch_max)
amr_file.write(output_line)
grid_array = grid_array_arg.copy()
grid_array -= grid_width / 2.0
grid_array -= grid_array[0]
grid_array *= 3.086e21 # cm
grid_width *= 3.086e21 # cm
for i in grid_array:
output_line = u"%.6e " % (i, )
amr_file.write(output_line)
output_line = u"%.6e \n" % (grid_array[-1] + grid_width, )
amr_file.write(output_line)
for i in grid_array:
output_line = u"%.6e " % (i, )
amr_file.write(output_line)
output_line = u"%.6e \n" % (grid_array[-1] + grid_width, )
amr_file.write(output_line)
for i in grid_array:
output_line = u"%.6e " % (i, )
amr_file.write(output_line)
output_line = u"%.6e \n" % (grid_array[-1] + grid_width, )
amr_file.write(output_line)
for my_file in species_file_list:
buf = struct.pack("3l", iformat, precis, nrcells)
my_file.write(buf)
for my_file in T_file_list:
buf = struct.pack("3l", iformat, precis, nrcells)
my_file.write(buf)
for my_file in nH_file_list:
buf = struct.pack("3l", iformat, precis, nrcells)
my_file.write(buf)
for my_file in vel_file_list:
buf = struct.pack("3l", iformat, precis, nrcells)
my_file.write(buf)
buf = struct.pack("3l", iformat, precis, nrcells)
turb_file.write(buf)
buf = struct.pack("4l", iformat, precis, nrcells, nrspec)
dust_file.write(buf)
dust_T_file.write("1 \n")
dust_T_file.write("%d \n" % (nrcells, ))
dust_T_file.write("%d \n" % (nrspec, ))
if parameters["include_stars"] == 1:
buf = struct.pack("4l", iformat, precis, nrcells, nr_star_spec)
star_file.write(buf)
def write_restart_domain(task_id, data_int):
filename = "restart_domain_%d" % (task_id, )
fd = open(filename, "wb")
for arr in data_int:
for idx in range(len(arr)):
buf = struct.pack("i", arr[idx])
fd.write(buf)
fd.close()
def read_restart_domain(task_id, N_task, N_chunk):
filename = "restart_domain_%d" % (task_id, )
fd = open(filename, "rb")
output_list = []
for idx in range(6):
buf = fd.read(N_task * 4)
output_list.append(np.array(struct.unpack("%di" % (N_task, ), buf)))
for idx in range(3):
for i in range(2):