|
1 | 1 | import os
|
| 2 | +from collections.abc import Sequence |
2 | 3 |
|
3 | 4 | import numpy as np
|
4 | 5 |
|
| 6 | +from yt.utilities import fortran_utils as fpu |
5 | 7 | from yt.utilities.io_handler import BaseParticleIOHandler
|
6 | 8 |
|
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 |
8 | 29 |
|
9 | 30 |
|
10 | 31 | class IOHandlerRockstarBinary(BaseParticleIOHandler):
|
11 | 32 | _dataset_type = "rockstar_binary"
|
12 | 33 |
|
13 | 34 | def __init__(self, *args, **kwargs):
|
14 | 35 | 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}") |
16 | 54 |
|
17 | 55 | def _read_fluid_selection(self, chunks, selector, fields, size):
|
18 | 56 | raise NotImplementedError
|
|
0 commit comments