forked from jchelly/SOAP
-
Notifications
You must be signed in to change notification settings - Fork 3
/
read_subfind.py
318 lines (251 loc) · 10.4 KB
/
read_subfind.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
#!/bin/env python
import os
import numpy as np
import h5py
import unyt
import virgo.mpi.util
import virgo.mpi.parallel_hdf5 as phdf5
def locate_files(basename):
"""
Generate format strings for Gadget-4 snapshot and fof_subhalo_tab files,
given the path to a snapshot file without the trailing .N.hdf5.
Assumes we have a filenames along the lines of
snapdir_XXX/snap_basename_XXX.0.hdf5
...
groups_XXX/fof_subhalo_tab_XXX.0.hdf5
...
"""
snap_format_string = basename + ".%(file_nr)d.hdf5"
# Check that the first snapshot file exists
snap_file = snap_format_string % {"file_nr": 0}
if not (os.path.exists(snap_file)):
raise IOError("Snapshot file does not exist: " + snap_file)
# Find the base directory
topdir = os.path.dirname(os.path.dirname(snap_file))
# Get the snapshot number from the filename
snap_nr = int(basename[-3:])
# Make format string for halo filenames
group_format_string = (
f"{topdir}/groups_{snap_nr:03d}/fof_subhalo_tab_{snap_nr:03d}"
+ ".%(file_nr)d.hdf5"
)
# Check group file exists
group_file = group_format_string % {"file_nr": 0}
if not (os.path.exists(group_file)):
raise IOError("Group file does not exist: " + group_file)
return snap_format_string, group_format_string
def read_gadget4_groupnr(basename):
"""
Read particle IDs and group numbers from Gadget-4 output.
basename should be the name of a group sorted snapshot file without the
trailing .N.hdf5.
"""
from mpi4py import MPI
comm = MPI.COMM_WORLD
comm_rank = comm.Get_rank()
comm_size = comm.Get_size()
# Locate the snapshot and fof_subhalo_tab files
if comm_rank == 0:
snap_format_string, group_format_string = locate_files(basename)
else:
snap_format_string = None
group_format_string = None
snap_format_string, group_format_string = comm.bcast(
(snap_format_string, group_format_string)
)
# Check what particle types we have
if comm_rank == 0:
snap_file = snap_format_string % {"file_nr": 0}
with h5py.File(snap_file, "r") as infile:
numpart_total = infile["Header"].attrs["NumPart_Total"]
type_nrs = np.arange(len(numpart_total), dtype=int)
type_nrs = type_nrs[numpart_total > 0]
else:
type_nrs = None
type_nrs = comm.bcast(type_nrs)
# Read in the sorted particle IDs from the snapshot
particle_ids = {}
snap = phdf5.MultiFile(
snap_format_string, file_nr_attr=("Header", "NumFilesPerSnapshot")
)
for type_nr in type_nrs:
particle_ids[type_nr] = snap.read(f"PartType{type_nr}/ParticleIDs")
# Read in the group lengths and offsets
subtab = phdf5.MultiFile(group_format_string, file_nr_attr=("Header", "NumFiles"))
suboffset_type, sublen_type = subtab.read(
("Subhalo/SubhaloOffsetType", "Subhalo/SubhaloLenType"), unpack=True
)
# Compute group index for each particle ID
particle_grnr = {}
for type_nr in type_nrs:
particle_grnr[type_nr] = virgo.mpi.util.group_index_from_length_and_offset(
np.ascontiguousarray(sublen_type[:, type_nr]),
np.ascontiguousarray(suboffset_type[:, type_nr]),
len(particle_ids[type_nr]),
return_rank=False,
comm=comm,
)
# Concatenate and return arrays
all_grnr = []
all_ids = []
for type_nr in type_nrs:
all_grnr.append(particle_grnr[type_nr])
all_ids.append(particle_ids[type_nr])
local_nr_halos = suboffset_type.shape[0]
total_nr_halos = comm.allreduce(local_nr_halos)
return total_nr_halos, np.concatenate(all_ids), np.concatenate(all_grnr)
def read_gadget4_catalogue(comm, basename, a_unit, registry, boxsize):
"""
Read in the Gadget-4 halo catalogue, distributed over communicator comm.
comm - communicator to distribute catalogue over
basename - HBTPlus SubSnap filename without the .N suffix
a_unit - unyt a factor
registry - unyt unit registry
boxsize - box size as a unyt quantity
Returns a dict of unyt arrays with the halo properies.
Arrays which must always be returned:
index - index of each halo in the input catalogue
cofp - (N,3) array with centre to use for SO calculations
search_radius - initial search radius which includes all member particles
is_central - integer 1 for centrals, 0 for satellites
nr_bound_part - number of bound particles in each halo
Any other arrays will be passed through to the output ONLY IF they are
documented in property_table.py.
"""
comm_size = comm.Get_size()
comm_rank = comm.Get_rank()
# Get SWIFT's definition of physical and comoving Mpc units
swift_pmpc = unyt.Unit("swift_mpc", registry=registry)
swift_cmpc = unyt.Unit(a_unit * swift_pmpc, registry=registry)
swift_msun = unyt.Unit("swift_msun", registry=registry)
# Get expansion factor as a float
a = a_unit.base_value
# Locate the snapshot and fof_subhalo_tab files
if comm_rank == 0:
snap_format_string, group_format_string = locate_files(basename)
else:
snap_format_string = None
group_format_string = None
snap_format_string, group_format_string = comm.bcast(
(snap_format_string, group_format_string)
)
# Get Gadget-4 unit information (only need lengths here)
with h5py.File(group_format_string % {"file_nr": 0}, "r") as subtab:
length_cgs = float(subtab["Parameters"].attrs["UnitLength_in_cm"])
hubble = float(subtab["Parameters"].attrs["Hubble"])
hubbleparam = float(subtab["Parameters"].attrs["HubbleParam"])
# Gadget-4 can be set up to use no-h units. Wont try to support that here.
# Hubble=100 means Gadget is using 1/h units with h given by HubbleParam.
if hubble != 100.0:
raise ValueError("Runs with Hubble != 100.0 not supported")
# Read halo properties we need
datasets = (
"Subhalo/SubhaloPos",
"Subhalo/SubhaloHalfmassRad",
"Subhalo/SubhaloRankInGr",
"Subhalo/SubhaloLen",
"Subhalo/SubhaloGroupNr",
)
subtab = phdf5.MultiFile(group_format_string, file_nr_attr=("Header", "NumFiles"))
data = subtab.read(datasets)
# Assign indexes to the subhalos
nr_local_halos = len(data["Subhalo/SubhaloLen"])
local_offset = comm.scan(nr_local_halos) - nr_local_halos
index = np.arange(nr_local_halos, dtype=int) + local_offset
index = unyt.unyt_array(
index, dtype=int, units=unyt.dimensionless, registry=registry
)
# Get length unit conversion (ignoring any a factors and assuming Gadget uses 1/h units)
gadget_length_unit = length_cgs * unyt.cm / hubbleparam
length_conversion = (gadget_length_unit / swift_pmpc).to(unyt.dimensionless)
# Get position in comoving Mpc, assuming input position from Gadget is comoving
cofp = data["Subhalo/SubhaloPos"] * length_conversion * swift_cmpc
# Store central halo flag
is_central = np.where(data["Subhalo/SubhaloRankInGr"] == 0, 1, 0)
is_central = unyt.unyt_array(
is_central, dtype=int, units=unyt.dimensionless, registry=registry
)
# Store number of bound particles in each halo
nr_bound_part = unyt.unyt_array(
data["Subhalo/SubhaloLen"],
dtype=int,
units=unyt.dimensionless,
registry=registry,
)
# Store FOF group ID of this halo
group_nr = unyt.unyt_array(
data["Subhalo/SubhaloGroupNr"],
dtype=int,
units=unyt.dimensionless,
registry=registry,
)
# Store initial search radius (TODO: check this is still in physical units, unlike the position)
search_radius = (
data["Subhalo/SubhaloHalfmassRad"] * length_conversion * swift_pmpc
) # different units from cofm, not a typo!
local_halo = {
"cofp": cofp,
"index": index,
"search_radius": search_radius,
"is_central": is_central,
"nr_bound_part": nr_bound_part,
"GroupNr": group_nr,
}
for name in local_halo:
local_halo[name] = unyt.unyt_array(local_halo[name], registry=registry)
return local_halo
def test_read_gadget4_groupnr(basename):
"""
Read in Gadget-4 group numbers and compute the number of particles
in each group. This is then compared with the input catalogue as a
sanity check on the group membershp files.
"""
from mpi4py import MPI
comm = MPI.COMM_WORLD
comm_rank = comm.Get_rank()
comm_size = comm.Get_size()
n_halo, ids, grnr = read_gadget4_groupnr(basename)
del ids # Don't need the particle IDs
# Find maximum group number
max_grnr = comm.allreduce(np.amax(grnr), op=MPI.MAX)
nr_groups_from_grnr = max_grnr + 1
if comm_rank == 0:
print(f"Number of groups from membership files = {nr_groups_from_grnr}")
# Discard particles in no group
keep = grnr >= 0
grnr = grnr[keep]
# Compute group sizes
import virgo.mpi.parallel_sort as psort
nbound_from_grnr = psort.parallel_bincount(grnr, comm=comm)
# Locate the snapshot and fof_subhalo_tab files
if comm_rank == 0:
snap_format_string, group_format_string = locate_files(basename)
else:
snap_format_string = None
group_format_string = None
snap_format_string, group_format_string = comm.bcast(
(snap_format_string, group_format_string)
)
# Read group sizes from the group catalogue
subtab = phdf5.MultiFile(group_format_string, file_nr_attr=("Header", "NumFiles"))
nbound_from_subtab = subtab.read("Subhalo/SubhaloLen")
# Find number of groups in the subfind output
nr_groups_from_subtab = comm.allreduce(len(nbound_from_subtab))
if comm_rank == 0:
print(f"Number of groups from fof_subhalo_tab = {nr_groups_from_subtab}")
if nr_groups_from_subtab != nr_groups_from_grnr:
print("Number of groups does not agree!")
comm.Abort(1)
# Ensure nbound arrays are partitioned the same way
nr_per_rank = comm.allgather(len(nbound_from_subtab))
nbound_from_grnr = psort.repartition(
nbound_from_grnr, ndesired=nr_per_rank, comm=comm
)
# Compare
nr_different = comm.allreduce(np.sum(nbound_from_grnr != nbound_from_subtab))
if comm_rank == 0:
print(f"Number of group sizes which differ = {nr_different} (should be 0!)")
if __name__ == "__main__":
import sys
basename = sys.argv[1]
test_read_gadget4_groupnr(basename)