Skip to content

Commit 62a722c

Browse files
authored
Merge pull request #4997 from cphyc/autodetect-rockstar-format
Autodetect rockstar format
2 parents 82ac140 + 945f008 commit 62a722c

File tree

1 file changed

+40
-2
lines changed
  • yt/frontends/rockstar

1 file changed

+40
-2
lines changed

yt/frontends/rockstar/io.py

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,56 @@
11
import os
2+
from collections.abc import Sequence
23

34
import numpy as np
45

6+
from yt.utilities import fortran_utils as fpu
57
from yt.utilities.io_handler import BaseParticleIOHandler
68

7-
from .definitions import halo_dts
9+
from .definitions import halo_dts, header_dt
10+
11+
12+
def _can_load_with_format(
13+
filename: str, header_fmt: Sequence[tuple[str, int, str]], halo_format: np.dtype
14+
) -> bool:
15+
with open(filename, "rb") as f:
16+
header = fpu.read_cattrs(f, header_fmt, "=")
17+
Nhalos = header["num_halos"]
18+
Nparttot = header["num_particles"]
19+
halos = np.fromfile(f, dtype=halo_format, count=Nhalos)
20+
21+
# Make sure all masses are > 0
22+
if np.any(halos["particle_mass"] <= 0):
23+
return False
24+
# Make sure number of particles sums to expected value
25+
if halos["num_p"].sum() != Nparttot:
26+
return False
27+
28+
return True
829

930

1031
class IOHandlerRockstarBinary(BaseParticleIOHandler):
1132
_dataset_type = "rockstar_binary"
1233

1334
def __init__(self, *args, **kwargs):
1435
super().__init__(*args, **kwargs)
15-
self._halo_dt = halo_dts[self.ds.parameters["format_revision"]]
36+
self._halo_dt = self.detect_rockstar_format(
37+
self.ds.filename,
38+
self.ds.parameters["format_revision"],
39+
)
40+
41+
@staticmethod
42+
def detect_rockstar_format(
43+
filename: str,
44+
guess: int,
45+
) -> np.dtype:
46+
revisions: list[int] = list(halo_dts.keys())
47+
if guess in revisions:
48+
revisions.pop(revisions.index(guess))
49+
revisions = [guess] + revisions
50+
for revision in revisions:
51+
if _can_load_with_format(filename, header_dt, halo_dts[revision]):
52+
return halo_dts[revision]
53+
raise RuntimeError(f"Could not detect Rockstar format for file {filename}")
1654

1755
def _read_fluid_selection(self, chunks, selector, fields, size):
1856
raise NotImplementedError

0 commit comments

Comments
 (0)