forked from jchelly/SOAP
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathSO_properties.py
4197 lines (3764 loc) · 150 KB
/
SO_properties.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
#!/bin/env python
"""
SO_properties.py
Halo properties within spherical overdensities. These include
all particles within a radius that is set by the halo density
profile and some threshold density.
Just like the other HaloProperty implementations, the calculation of the
properties is done lazily: only calculations that are actually needed are
performed. A fully documented explanation can be found in
aperture_properties.py.
Apart from the usual halo property calculations, this file also
contains the spherical overdensity radius calculation, which is
somewhat more involved than simply using a fixed aperture.
Contrary to the other halo types, spherical overdensities are only
calculated for central halos. SO properties are also only calculated if
an SO radius could be determined.
"""
import numpy as np
import unyt
from scipy.optimize import brentq
from halo_properties import HaloProperty, SearchRadiusTooSmallError
from kinematic_properties import (
get_angular_momentum,
get_angular_momentum_and_kappa_corot,
get_vmax,
get_inertia_tensor,
)
from recently_heated_gas_filter import RecentlyHeatedGasFilter
from property_table import PropertyTable
from dataset_names import mass_dataset
from lazy_properties import lazy_property
from category_filter import CategoryFilter
from parameter_file import ParameterFile
from snapshot_datasets import SnapshotDatasets
from swift_cells import SWIFTCellGrid
from typing import Tuple, Dict, List
from numpy.typing import NDArray
def cumulative_mass_intersection(r: float, rho_dim: float, slope_dim: float) -> float:
"""
Function used to find the intersection of the cumulative mass curve at fixed
mean density, and the actual cumulative mass as obtained from linear
interpolation on a cumulative mass profile.
The equation we want to solve is:
4*pi/3*rho * r^3 - (M2-M1)/(r2-r1) * r + (M2-M1)/(r2-r1)*r1 - M1 = 0
Since all quantities have units and scipy cannot handle those, we actually
solve
4*pi/3*rho_d * u^3 - S_d * u + S_d - 1 = 0,
with
rho_d = rho * r1**3 / M1
S_d = (M2-M1)/(r2-r1) * (r1/M1)
The result then needs to be multiplied with r1 to get the intersection radius
Parameters:
- r: float
Dimensionless radius variable.
- rho_dim: float
Dimensionless density variable.
- slope_dim: float
Dimensionless slope variable.
Returns the value of the intersection equation for the given r (and using
the given rho_dim and slope_dim boundary conditions).
"""
return 4.0 * np.pi / 3.0 * rho_dim * r ** 3 - slope_dim * r + slope_dim - 1.0
def find_SO_radius_and_mass(
ordered_radius: unyt.unyt_array,
density: unyt.unyt_array,
cumulative_mass: unyt.unyt_array,
reference_density: unyt.unyt_quantity,
) -> Tuple[unyt.unyt_quantity, unyt.unyt_quantity, unyt.unyt_quantity]:
"""
Find the radius and mass of an SO from the ordered density and cumulative
mass profiles.
The profiles are constructed by sorting the particles within the spherical
region and then summing their masses in that order (assigning the full
mass of the particle to the particle's radius). The density for every radius
is then computed by dividing the cumulative mass profile by the volume of a
sphere with that radius.
The SO radius is defined as the radius at which the density profile dips
below the given reference density. Unfortunately, real density profiles
are noisy and can sometimes fluctuate around the threshold. We therefore
define the SO radius as the first radius for which this happens, at machine
precision.
If no particles are below the threshold, then we raise an error and force an
increase of the search radius.
If all particles are below the threshold, we assume that the cumulative
mass profile of the halo is linear out to the radius of the first particle,
and then use the corresponding density profile to find the intersection.
In all other cases, we find the actual SO radius by assuming a linear
cumulative mass profile in the bin where the density dips below the
threshold, and intersecting the corresponding density profile with the
threshold. This approach requires a root finding algorithm and does not
yield exactly the same result as linear interpolation in r-log(rho) space
for the same bin (which is for example used by VELOCIraptor). It however
guarantees that the SO mass we find is contained within the intersecting
bin, which would otherwise not necessarily be true (especially if the
intersecting bin is relatively wide). We could also interpolate both the
radius and mass, but then the mean density of the SO would not necessarily
match the target density, which is also weird.
Parameters:
- ordered_radius: unyt.unyt_array
Sorted radius of the particles.
- density: unyt.unyt_array
Density of the particles (also sorted on radius).
- cumulative_mass: unyt.unyt_array
Cumulative mass profile of the particles (also sorted on radius).
- reference_density: unyt.unyt_quantity
Target threshold density.
Returns the radius, mass and volume of the sphere where the density
reaches the target value.
Throws a SearchRadiusTooSmallError if the intersection point is outside
the range of the particles that were passed on.
Throws a RuntimeError if the intersection point is outside the range and
the current search radius is larger than 20 Mpc.
"""
# Compute a mask that marks particles above the threshold. We do this
# exactly once.
above_mask = density > reference_density
if above_mask[0]:
# Get the complementary mask of particles below the threshold.
# By using the complementary, we avoid any ambiguity about '>' vs '<='
below_mask = ~above_mask
# Find smallest radius where the density is below the threshold
i = np.argmax(below_mask)
if i == 0:
# There are no particles below the threshold
# We need to increase the search radius
if ordered_radius[-1] > 20.0 * unyt.Mpc:
raise RuntimeError(
"Cannot find SO radius, but search radius is already larger than 20 Mpc!"
)
raise SearchRadiusTooSmallError(
"SO radius multiple estimate was too small!"
)
else:
# all non-zero radius particles are below the threshold
# we linearly interpolate the mass from 0 to the particle radius
# and determine the radius at which this interpolation matches the
# target density
# This is simply the solution of
# 4*pi/3*r^3*rho = M[0]/r[0]*r
# Note that if masses are allowed to be negative, the first cumulative
# mass value could be negative. We make sure to avoid this problem
ipos = 0
while ipos < len(cumulative_mass) and cumulative_mass[ipos] < 0.0:
ipos += 1
if ipos == len(cumulative_mass):
raise RuntimeError("Should never happen!")
SO_r = np.sqrt(
0.75
* cumulative_mass[ipos]
/ (np.pi * ordered_radius[ipos] * reference_density)
)
SO_mass = cumulative_mass[ipos] * SO_r / ordered_radius[ipos]
return SO_r, SO_mass, 4.0 * np.pi / 3.0 * SO_r ** 3
# We now have the intersecting interval. Get the limits.
r1 = ordered_radius[i - 1]
r2 = ordered_radius[i]
M1 = cumulative_mass[i - 1]
M2 = cumulative_mass[i]
# deal with the pathological case where r1==r2
# we also need an interval where the density intersects
while r1 == r2 or (above_mask[i - 1] == above_mask[i]):
i += 1
# if we run out of 'i', we need to increase the search radius
if i >= len(density):
if ordered_radius[-1] > 20.0 * unyt.Mpc:
raise RuntimeError(
"Cannot find SO radius, but search radius is already larger than 20 Mpc!"
)
raise SearchRadiusTooSmallError(
"SO radius multiple estimate was too small!"
)
# take the next interval
r1 = r2
r2 = ordered_radius[i]
M1 = M2
M2 = cumulative_mass[i]
# compute the dimensionless quantities that enter the intersection equation
# remember, we are simply solving
# 4*pi/3*r^3*rho = M1 + (M2-M1)/(r2-r1)*(r-r1)
rho_dim = reference_density * r1 ** 3 / M1
slope_dim = (M2 - M1) / (r2 - r1) * (r1 / M1)
SO_r = r1 * brentq(
cumulative_mass_intersection, 1.0, r2 / r1, args=(rho_dim, slope_dim)
)
SO_volume = 4.0 / 3.0 * np.pi * SO_r ** 3
# compute the SO mass by requiring that the mean density in the SO is the
# target density
SO_mass = SO_volume * reference_density
return SO_r, SO_mass, SO_volume
class SOParticleData:
"""
Halo calculation class.
All properties we want to compute are implemented as lazy methods of this
class.
Note that unlike other halo properties that use apertures, SO calculations
only require a single mask, since they are always inclusive.
That said, we still require a types==PartTypeX mask
(see aperture_properties.py) to access some arrays that have been
precomputed for all particles.
Note that SOs are the only halo types that can include neutrino particles
(these are never bound to a subhalo). They are however only included in
the spherical overdensity radius calculation and in the calculation of
neutrino specific properties (i.e. neutrino masses), and are not taken into
account for other properties, like the total particle mass, velocity
dispersion...
"""
def __init__(
self,
input_halo: Dict,
data: Dict,
types_present: List[str],
recently_heated_gas_filter: RecentlyHeatedGasFilter,
observer_position: unyt.unyt_array,
snapshot_datasets: SnapshotDatasets,
core_excision_fraction: float,
softening_of_parttype: unyt.unyt_array,
virial_definition: bool,
search_radius: unyt.unyt_quantity,
cosmology: dict,
):
"""
Constructor.
Parameters:
- input_halo: Dict
Dictionary containing properties of the halo read from the VR catalogue.
- data: Dict
Dictionary containing particle data.
- types_present: List
List of all particle types (e.g. 'PartType0') that are present in the data
dictionary.
- recently_heated_gas_filter: RecentlyHeatedGasFilter
Filter used to mask out gas particles that were recently heated by
AGN feedback.
- observer_position: unyt.unyt_array
Position of an observer, used to determine the observer direction for
Doppler B calculations.
- snapshot_datasets: SnapshotDatasets
Object containing metadata about the datasets in the snapshot, like
appropriate aliases and column names.
- core_excision_fraction: float
Ignore particles within a sphere of core_excision_fraction * SORadius
when calculating CoreExcision properties
- softening_of_parttype: unyt.unyt_array
Softening length of each particle types
- virial_definition: bool
Whether to calculate the properties that are only valid for virial SO
definitions
- search_radius: unyt.unyt_quantity
Current search radius. Particles are guaranteed to be included up to
this radius.
- cosmology: dict
Cosmological parameters required for SO calculation
"""
self.input_halo = input_halo
self.data = data
self.has_neutrinos = "PartType6" in data
self.types_present = types_present
self.recently_heated_gas_filter = recently_heated_gas_filter
self.observer_position = observer_position
self.snapshot_datasets = snapshot_datasets
self.core_excision_fraction = core_excision_fraction
self.softening_of_parttype = softening_of_parttype
self.virial_definition = virial_definition
self.search_radius = search_radius
self.cosmology = cosmology
self.compute_basics()
def get_dataset(self, name: str) -> unyt.unyt_array:
"""
Local wrapper for SnapshotDatasets.get_dataset().
"""
return self.snapshot_datasets.get_dataset(name, self.data)
def compute_basics(self):
"""
Compute some properties that are always needed, regardless of which
properties we actually want to compute.
"""
self.centre = self.input_halo["cofp"]
self.index = self.input_halo["index"]
# Make an array of particle masses, radii and positions
mass = []
radius = []
position = []
velocity = []
types = []
groupnr = []
fofid = []
softening = []
for ptype in self.types_present:
if ptype == "PartType6":
# add neutrinos separately, since we need to treat them
# differently
continue
mass.append(self.get_dataset(f"{ptype}/{mass_dataset(ptype)}"))
pos = self.get_dataset(f"{ptype}/Coordinates") - self.centre[None, :]
position.append(pos)
r = np.sqrt(np.sum(pos ** 2, axis=1))
radius.append(r)
velocity.append(self.get_dataset(f"{ptype}/Velocities"))
typearr = int(ptype[-1]) * np.ones(r.shape, dtype=np.int32)
types.append(typearr)
groupnr.append(self.get_dataset(f"{ptype}/GroupNr_bound"))
fofid.append(self.get_dataset(f"{ptype}/FOFGroupIDs"))
s = np.ones(r.shape, dtype=np.float64) * self.softening_of_parttype[ptype]
softening.append(s)
self.mass = np.concatenate(mass)
self.radius = np.concatenate(radius)
self.position = np.concatenate(position)
self.velocity = np.concatenate(velocity)
self.types = np.concatenate(types)
self.groupnr = np.concatenate(groupnr)
self.fofid = np.concatenate(fofid)
self.softening = np.concatenate(softening)
def compute_SO_radius_and_mass(
self, reference_density: unyt.unyt_quantity, physical_radius: unyt.unyt_quantity
) -> bool:
"""
Compute the SO radius from the density profile of the particles.
Adds the contribution from neutrinos (if present) to the masses and
radii. Sorts the particles by radius and computes the cumulative mass
profile. Calls find_SO_radius_and_mass(), unless a radius multiple is
used as aperture radius.
Parameters:
- reference_density: unyt.unyt_quantity
Threshold density value that determines the SO radius.
- physical_radius: unyt.unyt_quantity
Physical radius that determines the SO radius in case a radius
multiple is used (e.g. 5xR500_crit).
Returns True if an SO radius was found, i.e. when both SO_radius and
SO_mass are non-zero.
Rethrows any SearchRadiusTooSmallError thrown by find_SO_radius_and_mass().
"""
# add neutrinos
if self.has_neutrinos:
numass = self.get_dataset("PartType6/Masses") * self.get_dataset(
"PartType6/Weights"
)
pos = self.get_dataset("PartType6/Coordinates") - self.centre[None, :]
nur = np.sqrt(np.sum(pos ** 2, axis=1))
self.nu_mass = numass
self.nu_radius = nur
self.nu_softening = (
np.ones_like(nur) * self.softening_of_parttype["PartType6"]
)
all_mass = np.concatenate([self.mass, numass / unyt.dimensionless])
all_r = np.concatenate([self.radius, nur])
else:
all_mass = self.mass
all_r = self.radius
# Sort by radius
order = np.argsort(all_r)
ordered_radius = all_r[order]
cumulative_mass = np.cumsum(all_mass[order], dtype=np.float64).astype(
self.mass.dtype
)
# add mean neutrino mass
cumulative_mass += (
self.cosmology["nu_density"] * 4.0 / 3.0 * np.pi * ordered_radius ** 3
)
# Determine FOF ID of object using the central non-neutrino particle
non_neutrino_order = order[order < self.radius.shape[0]]
fofid = self.fofid[non_neutrino_order[0]]
# Compute density within radius of each particle.
# Will need to skip any at zero radius.
# Note that because of the definition of the centre of potential, the first
# particle *should* be at r=0. We need to manually exclude it, in case round
# off error places it at a very small non-zero radius.
nskip = max(1, np.argmax(ordered_radius > 0.0 * ordered_radius.units))
ordered_radius = ordered_radius[nskip:]
cumulative_mass = cumulative_mass[nskip:]
nr_parts = len(ordered_radius)
density = cumulative_mass / (4.0 / 3.0 * np.pi * ordered_radius ** 3)
# Check if we ever reach the density threshold
if reference_density > 0:
if nr_parts > 0:
try:
self.SO_r, self.SO_mass, self.SO_volume = find_SO_radius_and_mass(
ordered_radius, density, cumulative_mass, reference_density
)
except SearchRadiusTooSmallError:
raise SearchRadiusTooSmallError("SO radius multiple was too small!")
else:
self.SO_volume = 0 * ordered_radius.units ** 3
elif physical_radius > 0:
self.SO_r = physical_radius
self.SO_volume = 4.0 * np.pi / 3.0 * self.SO_r ** 3
if nr_parts > 0:
# find the enclosed mass using interpolation
outside_radius = ordered_radius > self.SO_r
if not np.any(outside_radius):
# all particles are within the radius, we cannot interpolate
self.SO_mass = cumulative_mass[-1]
else:
i = np.argmax(outside_radius)
if i == 0:
# we only have particles in the centre, so we cannot interpolate
self.SO_mass = cumulative_mass[i]
else:
r1 = ordered_radius[i - 1]
r2 = ordered_radius[i]
M1 = cumulative_mass[i - 1]
M2 = cumulative_mass[i]
self.SO_mass = M1 + (self.SO_r - r1) / (r2 - r1) * (M2 - M1)
# check if we were successful. We only compute SO properties if we
# have both a radius and mass (the mass criterion covers the case where
# the radius is set to a physical size but we have no mass nonetheless)
SO_exists = self.SO_r > 0 and self.SO_mass > 0
# figure out which particles in the list are bound to a halo that is not the
# central halo
self.is_bound_to_satellite = (
(self.groupnr >= 0) & (self.groupnr != self.index) & (self.fofid == fofid)
)
self.is_bound_to_external = (
(self.groupnr >= 0) & (self.groupnr != self.index) & (self.fofid != fofid)
)
if SO_exists:
# Calculate DMO mass fraction found at SO_r
# This is used when computing concentration_dmo
dm_r = self.radius[self.types == 1]
dm_m = self.mass[self.types == 1]
order = np.argsort(dm_r)
ordered_dm_r = dm_r[order]
outside_radius = ordered_dm_r > self.SO_r
self.dm_missed_mass = 0 * self.mass.units
if np.any(outside_radius):
i = np.argmax(outside_radius)
if i != 0: # We have DM particles inside the SO radius
r1 = ordered_dm_r[i - 1]
r2 = ordered_dm_r[i]
self.dm_missed_mass = (self.SO_r - r1) / (r2 - r1) * dm_m[order][i]
# Removing particles outside SO radius
self.all_selection = self.radius < self.SO_r
self.gas_selection = self.radius[self.types == 0] < self.SO_r
self.dm_selection = self.radius[self.types == 1] < self.SO_r
self.star_selection = self.radius[self.types == 4] < self.SO_r
self.bh_selection = self.radius[self.types == 5] < self.SO_r
# Save particles outside SO radius for inertia tensor calculations
self.surrounding_mass = self.mass[np.logical_not(self.all_selection)]
self.surrounding_position = self.position[
np.logical_not(self.all_selection)
]
self.surrounding_types = self.types[np.logical_not(self.all_selection)]
self.mass = self.mass[self.all_selection]
self.radius = self.radius[self.all_selection]
self.position = self.position[self.all_selection]
self.velocity = self.velocity[self.all_selection]
self.types = self.types[self.all_selection]
self.is_bound_to_satellite = self.is_bound_to_satellite[self.all_selection]
self.is_bound_to_external = self.is_bound_to_external[self.all_selection]
self.softening = self.softening[self.all_selection]
if self.has_neutrinos:
self.nu_selection = self.nu_radius < self.SO_r
self.nu_mass = self.nu_mass[self.nu_selection]
self.nu_radius = self.nu_radius[self.nu_selection]
self.nu_softening = self.nu_softening[self.nu_selection]
return SO_exists
@property
def r(self) -> unyt.unyt_quantity:
"""
SO radius.
"""
return self.SO_r
@property
def Mtot(self) -> unyt.unyt_quantity:
"""
SO mass. Unlike other halo types, this is not simply the sum of all the
particle masses, but the extrapolated cumulative mass up to the SO
radius (i.e. SO_mass = 4*pi/3 * SO_radius**3 * SO_density).
"""
return self.SO_mass
@lazy_property
def Mtotpart(self) -> unyt.unyt_quantity:
"""
Total particle mass of all particles in the SO radius.
This is the equivalent of the total mass for other halo types.
"""
return self.mass.sum()
@lazy_property
def mass_fraction(self) -> unyt.unyt_array:
"""
Fractional mass of all particles.
Used to avoid numerical overflow in calculations like
com = (mass * position).sum() / Mtot
by rewriting it as
com = ((mass / Mtot) * position).sum()
= (mass_fraction * position).sum()
This is more accurate, since the mass fractions are numbers
of the order of 1e-5 or so, while the masses themselves can be much
larger, if expressed in the wrong units (and that is up to unyt).
"""
# note that we cannot divide by mSO here, since that was based on an interpolation
return self.mass / self.Mtotpart
@lazy_property
def com(self) -> unyt.unyt_array:
"""
Centre of mass of all particles in the spherical overdensity.
"""
return (self.mass_fraction[:, None] * self.position).sum(axis=0) + self.centre
@lazy_property
def vcom(self) -> unyt.unyt_array:
"""
Centre of mass velocity of all particles in the spherical overdensity.
"""
return (self.mass_fraction[:, None] * self.velocity).sum(axis=0)
@lazy_property
def Vmax_soft(self):
"""
Maximum circular velocity of the halo.
Particles are set to have minimum radius equal to their softening length.
This includes contributions from all particle types.
"""
if self.Mtotpart == 0:
return None
if not hasattr(self, "vmax_soft"):
soft_r = np.maximum(self.softening, self.radius)
self.r_vmax_soft, self.vmax_soft = get_vmax(self.mass, soft_r)
return self.vmax_soft
@lazy_property
def spin_parameter(self) -> unyt.unyt_quantity:
"""
Spin parameter of all particles in the spherical overdensity.
Computed as in Bullock et al. (2021):
lambda = |Ltot| / (sqrt(2) * M * v_max * R)
"""
if self.Mtotpart == 0:
return None
if self.Vmax_soft > 0:
vrel = self.velocity - self.vcom[None, :]
Ltot = np.linalg.norm(
(self.mass[:, None] * np.cross(self.position, vrel)).sum(axis=0)
)
return Ltot / (np.sqrt(2.0) * self.Mtotpart * self.SO_r * self.Vmax_soft)
return None
@lazy_property
def TotalInertiaTensor(self) -> unyt.unyt_array:
"""
Inertia tensor of the total mass distribution.
Computed iteratively using an ellipsoid with volume equal to that of
a sphere with radius SORadius.
"""
if self.Mtotpart == 0:
return None
mass = np.concatenate([self.mass, self.surrounding_mass], axis=0)
position = np.concatenate([self.position, self.surrounding_position], axis=0)
return get_inertia_tensor(
mass, position, self.SO_r, search_radius=self.search_radius
)
@lazy_property
def TotalInertiaTensorReduced(self) -> unyt.unyt_array:
"""
Reduced inertia tensor of the total mass distribution.
Computed iteratively using an ellipsoid with volume equal to that of
a sphere with radius SORadius.
"""
if self.Mtotpart == 0:
return None
mass = np.concatenate([self.mass, self.surrounding_mass], axis=0)
position = np.concatenate([self.position, self.surrounding_position], axis=0)
return get_inertia_tensor(
mass, position, self.SO_r, search_radius=self.search_radius, reduced=True
)
@lazy_property
def TotalInertiaTensorNoniterative(self) -> unyt.unyt_array:
"""
Inertia tensor of the total mass distribution.
Computed using all particles within the SORadius.
"""
if self.Mtotpart == 0:
return None
return get_inertia_tensor(self.mass, self.position, self.SO_r, max_iterations=1)
@lazy_property
def TotalInertiaTensorReducedNoniterative(self) -> unyt.unyt_array:
"""
Reduced inertia tensor of the total mass distribution.
Computed using all particles within the SORadius.
"""
if self.Mtotpart == 0:
return None
return get_inertia_tensor(
self.mass, self.position, self.SO_r, reduced=True, max_iterations=1
)
@lazy_property
def Mfrac_satellites(self) -> unyt.unyt_quantity:
"""
Mass fraction contributed by particles that are bound to subhalos other
than the main subhalo. Excludes particles from hostless subhalos and
from subhalos in other FOF groups.
Note that this function is only called when we are guaranteed to have
an SO, so we do not need to check SO_mass > 0.
"""
return self.mass[self.is_bound_to_satellite].sum() / self.SO_mass
@lazy_property
def Mfrac_external(self) -> unyt.unyt_quantity:
"""
Mass fraction contributed by particles that are bound to subhalos, but
are outside this FOF group. Includes particles from hostless subhalos.
"""
return self.mass[self.is_bound_to_external].sum() / self.SO_mass
@lazy_property
def gas_masses(self) -> unyt.unyt_array:
"""
Masses of gas particles.
"""
return self.mass[self.types == 0]
@lazy_property
def gas_pos(self) -> unyt.unyt_array:
"""
Positions of gas particles.
"""
return self.position[self.types == 0]
@lazy_property
def gas_vel(self) -> unyt.unyt_array:
"""
Velocities of gas particles.
"""
return self.velocity[self.types == 0]
@lazy_property
def Mgas(self) -> unyt.unyt_quantity:
"""
Total mass of gas within the spherical overdensity.
"""
return self.gas_masses.sum()
@lazy_property
def gas_mass_fraction(self) -> unyt.unyt_array:
"""
Mass fractions of gas particles.
See mass_fraction() for the rationale behind this property.
"""
if self.Mgas == 0:
return None
return self.gas_masses / self.Mgas
@lazy_property
def com_gas(self) -> unyt.unyt_array:
"""
Centre of mass of gas particles.
"""
if self.Mgas == 0:
return None
return (self.gas_mass_fraction[:, None] * self.gas_pos).sum(
axis=0
) + self.centre
@lazy_property
def vcom_gas(self) -> unyt.unyt_array:
"""
Centre of mass velocity of gas particles.
"""
if self.Mgas == 0:
return None
return (self.gas_mass_fraction[:, None] * self.gas_vel).sum(axis=0)
def compute_Lgas_props(self):
"""
Auxiliary function used to compute Lgas related properties.
We use this function instead of a single property since it is cheaper
to compute Lgas and Mcountrot_gas together.
"""
(
self.internal_Lgas,
_,
self.internal_Mcountrot_gas,
) = get_angular_momentum_and_kappa_corot(
self.gas_masses,
self.gas_pos,
self.gas_vel,
ref_velocity=self.vcom_gas,
do_counterrot_mass=True,
)
@lazy_property
def Lgas(self) -> unyt.unyt_array:
"""
Total angular momentum of gas particles.
Calls compute_Lgas_props() if needed.
"""
if self.Mgas == 0:
return None
if not hasattr(self, "internal_Lgas"):
self.compute_Lgas_props()
return self.internal_Lgas
@lazy_property
def DtoTgas(self) -> unyt.unyt_quantity:
"""
Disc to total mass ratio of gas.
Calls compute_Lgas_props() if needed.
"""
if self.Mgas == 0:
return None
if not hasattr(self, "internal_Mcountrot_gas"):
self.compute_Lgas_props()
return 1.0 - 2.0 * self.internal_Mcountrot_gas / self.Mgas
def gas_inertia_tensor(self, **kwargs) -> unyt.unyt_array:
"""
Helper function for calculating gas inertia tensors
"""
surrounding_mass = self.surrounding_mass[self.surrounding_types == 0]
surrounding_position = self.surrounding_position[self.surrounding_types == 0]
mass = np.concatenate([self.gas_masses, surrounding_mass], axis=0)
position = np.concatenate([self.gas_pos, surrounding_position], axis=0)
return get_inertia_tensor(
mass, position, self.SO_r, search_radius=self.search_radius, **kwargs
)
@lazy_property
def GasInertiaTensor(self) -> unyt.unyt_array:
"""
Inertia tensor of the gas mass distribution.
Computed iteratively using an ellipsoid with volume equal to that of
a sphere with radius SORadius.
"""
if self.Mgas == 0:
return None
return self.gas_inertia_tensor()
@lazy_property
def GasInertiaTensorReduced(self) -> unyt.unyt_array:
"""
Reduced inertia tensor of the gas mass distribution.
Computed iteratively using an ellipsoid with volume equal to that of
a sphere with radius SORadius.
"""
if self.Mgas == 0:
return None
return self.gas_inertia_tensor(reduced=True)
@lazy_property
def GasInertiaTensorNoniterative(self) -> unyt.unyt_array:
"""
Inertia tensor of the gas mass distribution.
Computed using all particles within the SORadius.
"""
if self.Mgas == 0:
return None
return get_inertia_tensor(
self.gas_masses, self.gas_pos, self.SO_r, max_iterations=1
)
@lazy_property
def GasInertiaTensorReducedNoniterative(self) -> unyt.unyt_array:
"""
Reduced inertia tensor of the gas mass distribution.
Computed using all particles within the SORadius.
"""
if self.Mgas == 0:
return None
return get_inertia_tensor(
self.gas_masses, self.gas_pos, self.SO_r, reduced=True, max_iterations=1
)
@lazy_property
def dm_masses(self) -> unyt.unyt_array:
"""
Masses of dark matter particles.
"""
return self.mass[self.types == 1]
@lazy_property
def dm_pos(self) -> unyt.unyt_array:
"""
Positions of dark matter particles.
"""
return self.position[self.types == 1]
@lazy_property
def dm_vel(self) -> unyt.unyt_array:
"""
Velocities of dark matter particles.
"""
return self.velocity[self.types == 1]
@lazy_property
def Mdm(self) -> unyt.unyt_quantity:
"""
Total mass of dark matter particles in the spherical overdensity.
"""
return self.dm_masses.sum()
@lazy_property
def dm_mass_fraction(self) -> unyt.unyt_array:
"""
Mass fractions of dark matter particles.
See mass_fractions() for the rationale behind this property.
"""
if self.Mdm == 0:
return None
return self.dm_masses / self.Mdm
@lazy_property
def vcom_dm(self) -> unyt.unyt_array:
"""
Centre of mass velocity of dark matter particles in the spherical overdensity.
"""
if self.Mdm == 0:
return None
return (self.dm_mass_fraction[:, None] * self.dm_vel).sum(axis=0)
@lazy_property
def Ldm(self) -> unyt.unyt_array:
"""
Total angular momentum of dark matter particles.
"""
if self.Mdm == 0:
return None
return get_angular_momentum(
self.dm_masses, self.dm_pos, self.dm_vel, ref_velocity=self.vcom_dm
)
def dm_inertia_tensor(self, **kwargs) -> unyt.unyt_array:
"""
Helper function for calculating dm inertia tensors
"""
surrounding_mass = self.surrounding_mass[self.surrounding_types == 1]
surrounding_position = self.surrounding_position[self.surrounding_types == 1]
mass = np.concatenate([self.dm_masses, surrounding_mass], axis=0)
position = np.concatenate([self.dm_pos, surrounding_position], axis=0)
return get_inertia_tensor(
mass, position, self.SO_r, search_radius=self.search_radius, **kwargs
)
@lazy_property
def DarkMatterInertiaTensor(self) -> unyt.unyt_array:
"""
Inertia tensor of the dark matter mass distribution.
Computed iteratively using an ellipsoid with volume equal to that of
a sphere with radius SORadius.
"""
if self.Mdm == 0:
return None
return self.dm_inertia_tensor()
@lazy_property
def DarkMatterInertiaTensorReduced(self) -> unyt.unyt_array:
"""
Reduced inertia tensor of the dark matter mass distribution.
Computed iteratively using an ellipsoid with volume equal to that of
a sphere with radius SORadius.
"""
if self.Mdm == 0:
return None
return self.dm_inertia_tensor(reduced=True)
@lazy_property
def DarkMatterInertiaTensorNoniterative(self) -> unyt.unyt_array:
"""
Inertia tensor of the dark matter mass distribution.
Computed using all particles within the SORadius.
"""
if self.Mdm == 0:
return None
return get_inertia_tensor(
self.dm_masses, self.dm_pos, self.SO_r, max_iterations=1
)
@lazy_property
def DarkMatterInertiaTensorReducedNoniterative(self) -> unyt.unyt_array:
"""
Reduced inertia tensor of the dark matter mass distribution.
Computed using all particles within the SORadius.
"""
if self.Mdm == 0:
return None
return get_inertia_tensor(
self.dm_masses, self.dm_pos, self.SO_r, reduced=True, max_iterations=1
)
@lazy_property
def star_masses(self) -> unyt.unyt_array:
"""
Masses of star particles.
"""
return self.mass[self.types == 4]
@lazy_property
def star_pos(self) -> unyt.unyt_array:
"""
Positions of star particles.
"""
return self.position[self.types == 4]
@lazy_property
def star_vel(self) -> unyt.unyt_array:
"""
Velocities of star particles.
"""
return self.velocity[self.types == 4]
@lazy_property
def Mstar(self) -> unyt.unyt_quantity:
"""
Total mass of star particles in the spherical overdensity.
"""
return self.star_masses.sum()
@lazy_property
def star_mass_fraction(self) -> unyt.unyt_array:
"""
Mass fractions of star particles.
See mass_fractions() for the rationale behind this property.
"""
if self.Mstar == 0:
return None
return self.star_masses / self.Mstar
@lazy_property
def com_star(self) -> unyt.unyt_array:
"""
Centre of mass of star particles.
"""
if self.Mstar == 0:
return None
return (self.star_mass_fraction[:, None] * self.star_pos).sum(
axis=0
) + self.centre
@lazy_property
def vcom_star(self) -> unyt.unyt_array:
"""