Add Twente legacy and migrated custom-field loading helpers
Browse filesFiles changed (2)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239# SPDX-License-Identifier: Apache-2.0"""Collision-safe custom-key migration followed by a verified zea resave.
Only source notation is encoded in the replacement names. In particular,``bubble_initial_r0`` preserves R0 separately from the source's distinct r0."""from __future__ import annotations
import argparseimport hashlibimport itertoolsimport jsonimport mathimport osfrom pathlib import Pathimport reimport shutilimport tempfile
import hdf5plugin # Register the source and destination compression filters.import h5pyimport numpy as np
CUSTOM_NAME_MAP = { "bubble_R0": "bubble_initial_r0", "bubble_p_dB": "bubble_p_db", **{f"track_{i}_pulse_A": f"track_{i}_pulse_a" for i in range(12)},}LEGACY_NAME_ATTRIBUTE = "source_custom_name"SNAKE_CASE = re.compile(r"^[a-z_][a-z0-9_]*$")
def canonicalize_custom_names(custom): """Return canonical keys for old or new files without merging collisions.""" result = dict(custom) for old, new in CUSTOM_NAME_MAP.items(): if old in result: if new in result: raise ValueError(f"Both legacy {old!r} and canonical {new!r} exist") result[new] = result.pop(old) return result
def sha256(path): digest = hashlib.sha256() with open(path, "rb") as stream: for block in iter(lambda: stream.read(8*1024**2), b""): digest.update(block) return digest.hexdigest()
def mapped_path(path): if path.startswith("custom/"): return "custom/" + CUSTOM_NAME_MAP.get(path[7:], path[7:]) return path
def object_paths(file): paths, seen = [], set() def walk(group): for key in group: if not isinstance(group.get(key, getlink=True), h5py.HardLink): raise ValueError("External/soft links are not supported") obj = group[key] address = h5py.h5o.get_info(obj.id).addr if address in seen: raise ValueError("Aliased objects are not supported") seen.add(address) path = obj.name.lstrip("/") paths.append(path) if isinstance(obj, h5py.Group): walk(obj) elif obj.external or obj.is_virtual or h5py.check_dtype(ref=obj.dtype): raise ValueError("External, virtual, and reference datasets are not supported") elif obj.shape is None: raise ValueError("Null datasets are not supported") walk(file) return sorted(paths)
def planned_renames(file): if "custom" not in file or not isinstance(file["custom"], h5py.Group): raise ValueError("Expected Twente custom group") names = set(file["custom"]) if "bubble_r0" not in names or not names.intersection({"bubble_R0", "bubble_initial_r0"}): raise ValueError("Expected distinct source R0 and r0 fields") plan = {} for name in names: target = CUSTOM_NAME_MAP.get(name, name) if not SNAKE_CASE.fullmatch(target): raise ValueError(f"Unrecognized non-snake-case custom key: {name!r}") if target != name: if target in names: raise ValueError(f"Rename collision: {name!r} -> {target!r}") plan["custom/" + name] = "custom/" + target for path in object_paths(file): if path.startswith("custom/"): for segment in mapped_path(path).split("/"): if not SNAKE_CASE.fullmatch(segment): raise ValueError(f"Unrecognized non-snake-case custom path: {path!r}") obj = file[path] for key in obj.attrs: if h5py.check_dtype(ref=obj.attrs.get_id(key).dtype): raise ValueError("Reference attributes are not supported") return plan
def equal(a, b): a, b = np.asarray(a), np.asarray(b) if a.shape != b.shape: return False if a.dtype.kind in "fc" and b.dtype.kind in "fc": return np.array_equal(a, b, equal_nan=True) return np.array_equal(a, b)
def blocks(shape, itemsize, budget=16*1024**2): if not shape: yield () return if not all(shape): return tile = list(shape) while math.prod(tile)*max(itemsize, 8) > budget: axis = max(range(len(tile)), key=tile.__getitem__) tile[axis] = (tile[axis]+1)//2 for start in itertools.product(*(range(0, n, t) for n, t in zip(shape, tile))): yield tuple(slice(s, min(s+t, n)) for s, t, n in zip(start, tile, shape))
def validate_migration(source, output): """Check every dataset value and attribute, allowing only declared renames.""" with h5py.File(source, "r") as a, h5py.File(output, "r") as b: plan = planned_renames(a) left, right = object_paths(a), object_paths(b) if sorted(mapped_path(p) for p in left) != right: raise ValueError("Object inventory changed beyond the explicit name mapping") if str(b.attrs.get("zea_version")) != "0.1.6": raise ValueError("Output must be written by zea 0.1.6") datasets = 0 for path in ["/"] + left: x, y = a[path], b[mapped_path(path)] if type(x) is not type(y): raise ValueError(f"Object type changed: {path}") if isinstance(x, h5py.Dataset): if x.shape != y.shape or x.dtype != y.dtype: raise ValueError(f"Shape or dtype changed: {path}") for block in blocks(x.shape, x.dtype.itemsize): old, new = np.asarray(x[block]), np.asarray(y[block]) same = equal(old, new) if old.dtype.hasobject else old.tobytes() == new.tobytes() if not same: raise ValueError(f"Dataset values changed: {path}") datasets += 1 expected = set(x.attrs) if path in plan: expected.add(LEGACY_NAME_ATTRIBUTE) if y.attrs.get(LEGACY_NAME_ATTRIBUTE) != path.split("/")[-1]: raise ValueError(f"Missing original-name provenance: {path}") if set(y.attrs) != expected: raise ValueError(f"Attribute inventory changed: {path}") for key in x.attrs: if path == "/" and key == "zea_version": continue if not equal(x.attrs[key], y.attrs[key]): raise ValueError(f"Attribute changed: {path}@{key}") return dict(differences=[], all_dataset_values_checked=True, datasets_checked=datasets, allowed_changes=[dict(path=p, new_path=q, category="user_approved_custom_rename") for p, q in sorted(plan.items())])
def restore_attributes(source, output, plan): # zea regenerates standard attributes; retain the original scientific metadata. with h5py.File(source, "r") as a, h5py.File(output, "r+") as b: paths = object_paths(a) if sorted(mapped_path(p) for p in paths) != object_paths(b): raise ValueError("Resave changed the object inventory") for path in ["/"] + paths: x, y = a[path], b[mapped_path(path)] for key in list(y.attrs): if not (path == "/" and key == "zea_version"): del y.attrs[key] for key in x.attrs: if path == "/" and key == "zea_version": continue aid = x.attrs.get_id(key) if h5py.check_dtype(ref=aid.dtype): raise ValueError("Reference attributes are not supported") y.attrs.create(key, x.attrs[key], dtype=aid.dtype, shape=aid.shape) if path in plan: if LEGACY_NAME_ATTRIBUTE in y.attrs: if y.attrs[LEGACY_NAME_ATTRIBUTE] != path.split("/")[-1]: raise ValueError("Conflicting original-name provenance") else: y.attrs[LEGACY_NAME_ATTRIBUTE] = path.split("/")[-1]
def resave_file(source, output, *, _writer=None): """Copy/rename/resave/verify one full file; never modify the source.""" source, output = Path(source), Path(output) if source.resolve() == output.resolve() or output.exists(): raise ValueError("Output must be a new path distinct from the source") with h5py.File(source, "r") as f: plan = planned_renames(f) source_sha = sha256(source) if _writer is None: from importlib.metadata import version if version("zea") != "0.1.6": raise RuntimeError("This migration requires zea 0.1.6") from zea.data.file_operations import resave _writer = resave output.parent.mkdir(parents=True, exist_ok=True) with tempfile.TemporaryDirectory(prefix=".twente-resave-", dir=output.parent) as directory: renamed = Path(directory) / "renamed-input.hdf5" candidate = Path(directory) / "candidate.hdf5" shutil.copyfile(source, renamed) with h5py.File(renamed, "r+") as f: for old, new in plan.items(): f.move(old, new) _writer(renamed, candidate) restore_attributes(source, candidate, plan) result = validate_migration(source, candidate) if sha256(source) != source_sha: raise ValueError("Source changed during migration") # A hard link publishes the verified file without overwriting a raced output. os.link(candidate, output) return result
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("input", type=Path) parser.add_argument("output", type=Path) args = parser.parse_args() os.environ.update(CUDA_VISIBLE_DEVICES="", KERAS_BACKEND="numpy", JAX_PLATFORMS="cpu") print(json.dumps(resave_file(args.input, args.output), indent=2))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247# SPDX-License-Identifier: Apache-2.0"""Reconstruction loading, coordinate, plotting, and ground-truth helpers."""
from __future__ import annotations
from pathlib import Pathfrom typing import Any
import numpy as np
def custom_map(file: Any, track_index: int = 0) -> dict[str, np.ndarray]: """Return canonical custom names and resolve track-specific pulse metadata.
Both legacy and migrated files are supported. R0 and r0 remain distinct; ambiguous legacy/canonical duplicates are rejected rather than overwritten. """
from migrate_custom_names import canonicalize_custom_names
custom = canonicalize_custom_names( {element.name: np.asarray(element.data) for element in file.custom} ) prefix = f"track_{track_index}_" for key, value in tuple(custom.items()): if key.startswith(prefix): custom[key.removeprefix(prefix)] = value return custom
def t_peak_override(custom: dict[str, np.ndarray]) -> np.ndarray: """Return the selected track's finite beamforming peak-time override."""
if "t_peak" not in custom: raise KeyError("HDF5 file is missing required custom field t_peak") t_peak = float(np.asarray(custom["t_peak"]).reshape(-1)[0]) if not np.isfinite(t_peak): raise ValueError("HDF5 custom field t_peak must be finite") return np.asarray([t_peak], dtype=np.float32)
def load_hdf5(path: str | Path, num_frames: int = 1, track_index: int = 0, ) -> tuple[Any, Any, Any, dict[str, np.ndarray]]: """Load one Zea acquisition and its custom elements."""
import zea
file = zea.File(str(path)) if track_index < 0 or track_index >= len(file.tracks): file.close() raise IndexError( f"track_index {track_index} is outside [0, {len(file.tracks) - 1}]" ) track = file.tracks[track_index] parameters = track.load_parameters() data = track.data.raw_data[:num_frames, parameters.selected_transmits, ...] return file, parameters, data, custom_map(file, track_index=track_index)
def run_bmode( path: str | Path, config_path: str | Path, num_frames: int = 1, track_index: int = 0, dynamic_range: tuple[float, float] = (-30.0, 0.0), xlims_cm: tuple[float, float] | None = (-1.5, 1.5),) -> tuple[Any, Any, np.ndarray, dict[str, np.ndarray]]: """Run the configured Zea pipeline and return the image plus acquisition data.
``xlims_cm`` controls the lateral field of view used by the DAS beamformer. Zea expects these limits in metres, while this public helper uses centimetres to match the plotted image axes. """
import keras import zea
file, parameters, data, custom = load_hdf5( path, num_frames=num_frames, track_index=track_index ) config = zea.Config.from_path(str(config_path)) parameters.dynamic_range = tuple(dynamic_range) if xlims_cm is not None: x_min_cm, x_max_cm = xlims_cm if not x_min_cm < x_max_cm: raise ValueError("xlims_cm must be ordered as (minimum, maximum)") parameters.update(xlims=(x_min_cm * 1e-2, x_max_cm * 1e-2)) pipeline = zea.Pipeline.from_config(config) inputs = pipeline.prepare_parameters( parameters, t_peak=t_peak_override(custom) ) inputs = {pipeline.key: data, **inputs} image = keras.ops.convert_to_numpy(pipeline(**inputs)[pipeline.output_key]) image = np.asarray(keras.ops.squeeze(image)) image = np.asarray( zea.display.to_8bit( image, dynamic_range=parameters.dynamic_range)) return file, parameters, image, custom
def image_extent_cm(parameters: Any, custom: dict[str, np.ndarray], image_shape: tuple[int, int], xlims_cm: tuple[float, float] | None = None, ) -> tuple[float, float, float, float]: """Calculate an x/z extent in centimeters for an image-shaped array."""
height, width = image_shape[-2:] domain_width = float(np.asarray(custom.get("domain_width", np.nan)).reshape(-1)[0]) domain_depth = float(np.asarray(custom.get("domain_depth", np.nan)).reshape(-1)[0]) if not np.isfinite(domain_width): geometry = np.asarray(parameters.probe_geometry) domain_width = float(np.max(geometry[:, 0]) - np.min(geometry[:, 0])) if not np.isfinite(domain_depth): domain_depth = float(parameters.sound_speed) * \ image_shape[-2] / (2.0 * float(parameters.sampling_frequency)) if xlims_cm is None: x_extent_cm = (-0.5 * domain_width * 100.0, 0.5 * domain_width * 100.0) else: x_extent_cm = tuple(float(value) for value in xlims_cm) if not x_extent_cm[0] < x_extent_cm[1]: raise ValueError("xlims_cm must be ordered as (minimum, maximum)") return (*x_extent_cm, 0.0, domain_depth * 100.0)
def bubble_coordinates_cm( custom: dict[str, np.ndarray]) -> tuple[np.ndarray, np.ndarray]: """Return finite bubble x/z coordinates in centimeters."""
if "bubble_x" not in custom or "bubble_z" not in custom: return np.empty(0, dtype=np.float32), np.empty(0, dtype=np.float32) x = np.asarray(custom["bubble_x"], dtype=np.float32).reshape(-1) z = np.asarray(custom["bubble_z"], dtype=np.float32).reshape(-1) valid = np.isfinite(x) & np.isfinite(z) return x[valid] * 100.0, z[valid] * 100.0
def plot_bmode( image: np.ndarray, extent_cm: tuple[float, float, float, float], output: str | Path, bubble_x_cm: np.ndarray | None = None, bubble_z_cm: np.ndarray | None = None, show_bubbles: bool = True, title: str | None = None,) -> None: """Save a B-mode image with centimeter axes and optional GT bubbles."""
import matplotlib.pyplot as plt
image = np.asarray(image) if image.ndim != 2: raise ValueError(f"Expected a 2-D B-mode image, got shape {image.shape}")
x_min, x_max, z_min, z_max = extent_cm fig, ax = plt.subplots(figsize=(5, 12), constrained_layout=True) ax.imshow( image, cmap="gray", origin="upper", aspect="auto", extent=(x_min, x_max, z_max, z_min), interpolation="nearest", vmin=0, vmax=255, ) if show_bubbles and bubble_x_cm is not None and bubble_z_cm is not None: ax.scatter( bubble_x_cm, bubble_z_cm, facecolors="none", edgecolors="red", linewidths=0.8, s=28, label="Bubble ground truth", ) ax.legend(loc="upper right") ax.set_xlabel("Lateral position x [cm]") ax.set_ylabel("Depth z [cm]") if title: ax.set_title(title) ax.set_xlim(x_min, x_max) ax.set_ylim(z_max, z_min) fig.savefig(output, dpi=150) plt.close(fig)
def plot_gt_label( label: np.ndarray, extent_cm: tuple[float, float, float, float], output: str | Path, title: str | None = None,) -> None: """Save a ground-truth label with the same physical axes as B-mode."""
import matplotlib.pyplot as plt
x_min, x_max, z_min, z_max = extent_cm fig, ax = plt.subplots(figsize=(5, 12), constrained_layout=True) ax.imshow( label, cmap="gray", origin="upper", aspect="auto", extent=(x_min, x_max, z_max, z_min), interpolation="nearest", vmin=0.0, vmax=1.0, ) ax.set_xlabel("Lateral position x [cm]") ax.set_ylabel("Depth z [cm]") if title: ax.set_title(title) ax.set_xlim(x_min, x_max) ax.set_ylim(z_max, z_min) fig.savefig(output, dpi=150) plt.close(fig)
def bubble_label( image_shape: tuple[int, int], extent_cm: tuple[float, float, float, float], bubble_x_cm: np.ndarray, bubble_z_cm: np.ndarray,) -> np.ndarray: """Create a hard binary bubble label image."""
height, width = image_shape x_min, x_max, z_min, z_max = extent_cm label = np.zeros((height, width), dtype=np.float32) x_pixels = (bubble_x_cm - x_min) / (x_max - x_min) * (width - 1) z_pixels = (bubble_z_cm - z_min) / (z_max - z_min) * (height - 1) x_pixels = np.rint(x_pixels).astype(int) z_pixels = np.rint(z_pixels).astype(int) valid = (x_pixels >= 0) & (x_pixels < width) & (z_pixels >= 0) & (z_pixels < height) label[z_pixels[valid], x_pixels[valid]] = 1.0 return labeltwente-microbubblesim/migrate_custom_names.pyAdded+239
twente-microbubblesim/utils.pyAdded+247