tristan-deep Claude Opus 5 commited on
Commit
0fde458
·
1 Parent(s): cce1ebb

Remove the Python helpers from twente-microbubblesim

Browse files

The corpus ships data cards and pipeline recipes, not code, and these two were
the only helper modules in it. migrate_custom_names.py was a one-off patch that
has already run, and utils.py belongs next to the reconstruction script in the
OpenH-RF repo, where it still lives.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

twente-microbubblesim/migrate_custom_names.py DELETED
@@ -1,239 +0,0 @@
1
- # SPDX-License-Identifier: Apache-2.0
2
- """Collision-safe custom-key migration followed by a verified zea resave.
3
-
4
- Only source notation is encoded in the replacement names. In particular,
5
- ``bubble_initial_r0`` preserves R0 separately from the source's distinct r0.
6
- """
7
- from __future__ import annotations
8
-
9
- import argparse
10
- import hashlib
11
- import itertools
12
- import json
13
- import math
14
- import os
15
- from pathlib import Path
16
- import re
17
- import shutil
18
- import tempfile
19
-
20
- import hdf5plugin # Register the source and destination compression filters.
21
- import h5py
22
- import numpy as np
23
-
24
- CUSTOM_NAME_MAP = {
25
- "bubble_R0": "bubble_initial_r0",
26
- "bubble_p_dB": "bubble_p_db",
27
- **{f"track_{i}_pulse_A": f"track_{i}_pulse_a" for i in range(12)},
28
- }
29
- LEGACY_NAME_ATTRIBUTE = "source_custom_name"
30
- SNAKE_CASE = re.compile(r"^[a-z_][a-z0-9_]*$")
31
-
32
-
33
- def canonicalize_custom_names(custom):
34
- """Return canonical keys for old or new files without merging collisions."""
35
- result = dict(custom)
36
- for old, new in CUSTOM_NAME_MAP.items():
37
- if old in result:
38
- if new in result:
39
- raise ValueError(f"Both legacy {old!r} and canonical {new!r} exist")
40
- result[new] = result.pop(old)
41
- return result
42
-
43
-
44
- def sha256(path):
45
- digest = hashlib.sha256()
46
- with open(path, "rb") as stream:
47
- for block in iter(lambda: stream.read(8*1024**2), b""):
48
- digest.update(block)
49
- return digest.hexdigest()
50
-
51
-
52
- def mapped_path(path):
53
- if path.startswith("custom/"):
54
- return "custom/" + CUSTOM_NAME_MAP.get(path[7:], path[7:])
55
- return path
56
-
57
-
58
- def object_paths(file):
59
- paths, seen = [], set()
60
- def walk(group):
61
- for key in group:
62
- if not isinstance(group.get(key, getlink=True), h5py.HardLink):
63
- raise ValueError("External/soft links are not supported")
64
- obj = group[key]
65
- address = h5py.h5o.get_info(obj.id).addr
66
- if address in seen:
67
- raise ValueError("Aliased objects are not supported")
68
- seen.add(address)
69
- path = obj.name.lstrip("/")
70
- paths.append(path)
71
- if isinstance(obj, h5py.Group):
72
- walk(obj)
73
- elif obj.external or obj.is_virtual or h5py.check_dtype(ref=obj.dtype):
74
- raise ValueError("External, virtual, and reference datasets are not supported")
75
- elif obj.shape is None:
76
- raise ValueError("Null datasets are not supported")
77
- walk(file)
78
- return sorted(paths)
79
-
80
-
81
- def planned_renames(file):
82
- if "custom" not in file or not isinstance(file["custom"], h5py.Group):
83
- raise ValueError("Expected Twente custom group")
84
- names = set(file["custom"])
85
- if "bubble_r0" not in names or not names.intersection({"bubble_R0", "bubble_initial_r0"}):
86
- raise ValueError("Expected distinct source R0 and r0 fields")
87
- plan = {}
88
- for name in names:
89
- target = CUSTOM_NAME_MAP.get(name, name)
90
- if not SNAKE_CASE.fullmatch(target):
91
- raise ValueError(f"Unrecognized non-snake-case custom key: {name!r}")
92
- if target != name:
93
- if target in names:
94
- raise ValueError(f"Rename collision: {name!r} -> {target!r}")
95
- plan["custom/" + name] = "custom/" + target
96
- for path in object_paths(file):
97
- if path.startswith("custom/"):
98
- for segment in mapped_path(path).split("/"):
99
- if not SNAKE_CASE.fullmatch(segment):
100
- raise ValueError(f"Unrecognized non-snake-case custom path: {path!r}")
101
- obj = file[path]
102
- for key in obj.attrs:
103
- if h5py.check_dtype(ref=obj.attrs.get_id(key).dtype):
104
- raise ValueError("Reference attributes are not supported")
105
- return plan
106
-
107
-
108
- def equal(a, b):
109
- a, b = np.asarray(a), np.asarray(b)
110
- if a.shape != b.shape:
111
- return False
112
- if a.dtype.kind in "fc" and b.dtype.kind in "fc":
113
- return np.array_equal(a, b, equal_nan=True)
114
- return np.array_equal(a, b)
115
-
116
-
117
- def blocks(shape, itemsize, budget=16*1024**2):
118
- if not shape:
119
- yield ()
120
- return
121
- if not all(shape):
122
- return
123
- tile = list(shape)
124
- while math.prod(tile)*max(itemsize, 8) > budget:
125
- axis = max(range(len(tile)), key=tile.__getitem__)
126
- tile[axis] = (tile[axis]+1)//2
127
- for start in itertools.product(*(range(0, n, t) for n, t in zip(shape, tile))):
128
- yield tuple(slice(s, min(s+t, n)) for s, t, n in zip(start, tile, shape))
129
-
130
-
131
- def validate_migration(source, output):
132
- """Check every dataset value and attribute, allowing only declared renames."""
133
- with h5py.File(source, "r") as a, h5py.File(output, "r") as b:
134
- plan = planned_renames(a)
135
- left, right = object_paths(a), object_paths(b)
136
- if sorted(mapped_path(p) for p in left) != right:
137
- raise ValueError("Object inventory changed beyond the explicit name mapping")
138
- if str(b.attrs.get("zea_version")) != "0.1.6":
139
- raise ValueError("Output must be written by zea 0.1.6")
140
- datasets = 0
141
- for path in ["/"] + left:
142
- x, y = a[path], b[mapped_path(path)]
143
- if type(x) is not type(y):
144
- raise ValueError(f"Object type changed: {path}")
145
- if isinstance(x, h5py.Dataset):
146
- if x.shape != y.shape or x.dtype != y.dtype:
147
- raise ValueError(f"Shape or dtype changed: {path}")
148
- for block in blocks(x.shape, x.dtype.itemsize):
149
- old, new = np.asarray(x[block]), np.asarray(y[block])
150
- same = equal(old, new) if old.dtype.hasobject else old.tobytes() == new.tobytes()
151
- if not same:
152
- raise ValueError(f"Dataset values changed: {path}")
153
- datasets += 1
154
- expected = set(x.attrs)
155
- if path in plan:
156
- expected.add(LEGACY_NAME_ATTRIBUTE)
157
- if y.attrs.get(LEGACY_NAME_ATTRIBUTE) != path.split("/")[-1]:
158
- raise ValueError(f"Missing original-name provenance: {path}")
159
- if set(y.attrs) != expected:
160
- raise ValueError(f"Attribute inventory changed: {path}")
161
- for key in x.attrs:
162
- if path == "/" and key == "zea_version":
163
- continue
164
- if not equal(x.attrs[key], y.attrs[key]):
165
- raise ValueError(f"Attribute changed: {path}@{key}")
166
- return dict(differences=[], all_dataset_values_checked=True, datasets_checked=datasets,
167
- allowed_changes=[dict(path=p, new_path=q, category="user_approved_custom_rename")
168
- for p, q in sorted(plan.items())])
169
-
170
-
171
- def restore_attributes(source, output, plan):
172
- # zea regenerates standard attributes; retain the original scientific metadata.
173
- with h5py.File(source, "r") as a, h5py.File(output, "r+") as b:
174
- paths = object_paths(a)
175
- if sorted(mapped_path(p) for p in paths) != object_paths(b):
176
- raise ValueError("Resave changed the object inventory")
177
- for path in ["/"] + paths:
178
- x, y = a[path], b[mapped_path(path)]
179
- for key in list(y.attrs):
180
- if not (path == "/" and key == "zea_version"):
181
- del y.attrs[key]
182
- for key in x.attrs:
183
- if path == "/" and key == "zea_version":
184
- continue
185
- aid = x.attrs.get_id(key)
186
- if h5py.check_dtype(ref=aid.dtype):
187
- raise ValueError("Reference attributes are not supported")
188
- y.attrs.create(key, x.attrs[key], dtype=aid.dtype, shape=aid.shape)
189
- if path in plan:
190
- if LEGACY_NAME_ATTRIBUTE in y.attrs:
191
- if y.attrs[LEGACY_NAME_ATTRIBUTE] != path.split("/")[-1]:
192
- raise ValueError("Conflicting original-name provenance")
193
- else:
194
- y.attrs[LEGACY_NAME_ATTRIBUTE] = path.split("/")[-1]
195
-
196
-
197
- def resave_file(source, output, *, _writer=None):
198
- """Copy/rename/resave/verify one full file; never modify the source."""
199
- source, output = Path(source), Path(output)
200
- if source.resolve() == output.resolve() or output.exists():
201
- raise ValueError("Output must be a new path distinct from the source")
202
- with h5py.File(source, "r") as f:
203
- plan = planned_renames(f)
204
- source_sha = sha256(source)
205
- if _writer is None:
206
- from importlib.metadata import version
207
- if version("zea") != "0.1.6":
208
- raise RuntimeError("This migration requires zea 0.1.6")
209
- from zea.data.file_operations import resave
210
- _writer = resave
211
- output.parent.mkdir(parents=True, exist_ok=True)
212
- with tempfile.TemporaryDirectory(prefix=".twente-resave-", dir=output.parent) as directory:
213
- renamed = Path(directory) / "renamed-input.hdf5"
214
- candidate = Path(directory) / "candidate.hdf5"
215
- shutil.copyfile(source, renamed)
216
- with h5py.File(renamed, "r+") as f:
217
- for old, new in plan.items():
218
- f.move(old, new)
219
- _writer(renamed, candidate)
220
- restore_attributes(source, candidate, plan)
221
- result = validate_migration(source, candidate)
222
- if sha256(source) != source_sha:
223
- raise ValueError("Source changed during migration")
224
- # A hard link publishes the verified file without overwriting a raced output.
225
- os.link(candidate, output)
226
- return result
227
-
228
-
229
- def main():
230
- parser = argparse.ArgumentParser(description=__doc__)
231
- parser.add_argument("input", type=Path)
232
- parser.add_argument("output", type=Path)
233
- args = parser.parse_args()
234
- os.environ.update(CUDA_VISIBLE_DEVICES="", KERAS_BACKEND="numpy", JAX_PLATFORMS="cpu")
235
- print(json.dumps(resave_file(args.input, args.output), indent=2))
236
-
237
-
238
- if __name__ == "__main__":
239
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
twente-microbubblesim/utils.py DELETED
@@ -1,247 +0,0 @@
1
- # SPDX-License-Identifier: Apache-2.0
2
- """Reconstruction loading, coordinate, plotting, and ground-truth helpers."""
3
-
4
- from __future__ import annotations
5
-
6
- from pathlib import Path
7
- from typing import Any
8
-
9
- import numpy as np
10
-
11
-
12
- def custom_map(file: Any, track_index: int = 0) -> dict[str, np.ndarray]:
13
- """Return canonical custom names and resolve track-specific pulse metadata.
14
-
15
- Both legacy and migrated files are supported. R0 and r0 remain distinct;
16
- ambiguous legacy/canonical duplicates are rejected rather than overwritten.
17
- """
18
-
19
- from migrate_custom_names import canonicalize_custom_names
20
-
21
- custom = canonicalize_custom_names(
22
- {element.name: np.asarray(element.data) for element in file.custom}
23
- )
24
- prefix = f"track_{track_index}_"
25
- for key, value in tuple(custom.items()):
26
- if key.startswith(prefix):
27
- custom[key.removeprefix(prefix)] = value
28
- return custom
29
-
30
-
31
- def t_peak_override(custom: dict[str, np.ndarray]) -> np.ndarray:
32
- """Return the selected track's finite beamforming peak-time override."""
33
-
34
- if "t_peak" not in custom:
35
- raise KeyError("HDF5 file is missing required custom field t_peak")
36
- t_peak = float(np.asarray(custom["t_peak"]).reshape(-1)[0])
37
- if not np.isfinite(t_peak):
38
- raise ValueError("HDF5 custom field t_peak must be finite")
39
- return np.asarray([t_peak], dtype=np.float32)
40
-
41
-
42
- def load_hdf5(path: str | Path,
43
- num_frames: int = 1,
44
- track_index: int = 0,
45
- ) -> tuple[Any, Any, Any, dict[str, np.ndarray]]:
46
- """Load one Zea acquisition and its custom elements."""
47
-
48
- import zea
49
-
50
- file = zea.File(str(path))
51
- if track_index < 0 or track_index >= len(file.tracks):
52
- file.close()
53
- raise IndexError(
54
- f"track_index {track_index} is outside [0, {len(file.tracks) - 1}]"
55
- )
56
- track = file.tracks[track_index]
57
- parameters = track.load_parameters()
58
- data = track.data.raw_data[:num_frames, parameters.selected_transmits, ...]
59
- return file, parameters, data, custom_map(file, track_index=track_index)
60
-
61
-
62
-
63
- def run_bmode(
64
- path: str | Path,
65
- config_path: str | Path,
66
- num_frames: int = 1,
67
- track_index: int = 0,
68
- dynamic_range: tuple[float, float] = (-30.0, 0.0),
69
- xlims_cm: tuple[float, float] | None = (-1.5, 1.5),
70
- ) -> tuple[Any, Any, np.ndarray, dict[str, np.ndarray]]:
71
- """Run the configured Zea pipeline and return the image plus acquisition data.
72
-
73
- ``xlims_cm`` controls the lateral field of view used by the DAS
74
- beamformer. Zea expects these limits in metres, while this public helper
75
- uses centimetres to match the plotted image axes.
76
- """
77
-
78
- import keras
79
- import zea
80
-
81
- file, parameters, data, custom = load_hdf5(
82
- path, num_frames=num_frames, track_index=track_index
83
- )
84
- config = zea.Config.from_path(str(config_path))
85
- parameters.dynamic_range = tuple(dynamic_range)
86
- if xlims_cm is not None:
87
- x_min_cm, x_max_cm = xlims_cm
88
- if not x_min_cm < x_max_cm:
89
- raise ValueError("xlims_cm must be ordered as (minimum, maximum)")
90
- parameters.update(xlims=(x_min_cm * 1e-2, x_max_cm * 1e-2))
91
- pipeline = zea.Pipeline.from_config(config)
92
- inputs = pipeline.prepare_parameters(
93
- parameters, t_peak=t_peak_override(custom)
94
- )
95
- inputs = {pipeline.key: data, **inputs}
96
- image = keras.ops.convert_to_numpy(pipeline(**inputs)[pipeline.output_key])
97
- image = np.asarray(keras.ops.squeeze(image))
98
- image = np.asarray(
99
- zea.display.to_8bit(
100
- image,
101
- dynamic_range=parameters.dynamic_range))
102
- return file, parameters, image, custom
103
-
104
-
105
- def image_extent_cm(parameters: Any,
106
- custom: dict[str,
107
- np.ndarray],
108
- image_shape: tuple[int,
109
- int],
110
- xlims_cm: tuple[float, float] | None = None,
111
- ) -> tuple[float,
112
- float,
113
- float,
114
- float]:
115
- """Calculate an x/z extent in centimeters for an image-shaped array."""
116
-
117
- height, width = image_shape[-2:]
118
- domain_width = float(np.asarray(custom.get("domain_width", np.nan)).reshape(-1)[0])
119
- domain_depth = float(np.asarray(custom.get("domain_depth", np.nan)).reshape(-1)[0])
120
- if not np.isfinite(domain_width):
121
- geometry = np.asarray(parameters.probe_geometry)
122
- domain_width = float(np.max(geometry[:, 0]) - np.min(geometry[:, 0]))
123
- if not np.isfinite(domain_depth):
124
- domain_depth = float(parameters.sound_speed) * \
125
- image_shape[-2] / (2.0 * float(parameters.sampling_frequency))
126
- if xlims_cm is None:
127
- x_extent_cm = (-0.5 * domain_width * 100.0,
128
- 0.5 * domain_width * 100.0)
129
- else:
130
- x_extent_cm = tuple(float(value) for value in xlims_cm)
131
- if not x_extent_cm[0] < x_extent_cm[1]:
132
- raise ValueError("xlims_cm must be ordered as (minimum, maximum)")
133
- return (*x_extent_cm, 0.0, domain_depth * 100.0)
134
-
135
-
136
- def bubble_coordinates_cm(
137
- custom: dict[str, np.ndarray]) -> tuple[np.ndarray, np.ndarray]:
138
- """Return finite bubble x/z coordinates in centimeters."""
139
-
140
- if "bubble_x" not in custom or "bubble_z" not in custom:
141
- return np.empty(0, dtype=np.float32), np.empty(0, dtype=np.float32)
142
- x = np.asarray(custom["bubble_x"], dtype=np.float32).reshape(-1)
143
- z = np.asarray(custom["bubble_z"], dtype=np.float32).reshape(-1)
144
- valid = np.isfinite(x) & np.isfinite(z)
145
- return x[valid] * 100.0, z[valid] * 100.0
146
-
147
-
148
- def plot_bmode(
149
- image: np.ndarray,
150
- extent_cm: tuple[float, float, float, float],
151
- output: str | Path,
152
- bubble_x_cm: np.ndarray | None = None,
153
- bubble_z_cm: np.ndarray | None = None,
154
- show_bubbles: bool = True,
155
- title: str | None = None,
156
- ) -> None:
157
- """Save a B-mode image with centimeter axes and optional GT bubbles."""
158
-
159
- import matplotlib.pyplot as plt
160
-
161
- image = np.asarray(image)
162
- if image.ndim != 2:
163
- raise ValueError(f"Expected a 2-D B-mode image, got shape {image.shape}")
164
-
165
- x_min, x_max, z_min, z_max = extent_cm
166
- fig, ax = plt.subplots(figsize=(5, 12), constrained_layout=True)
167
- ax.imshow(
168
- image,
169
- cmap="gray",
170
- origin="upper",
171
- aspect="auto",
172
- extent=(x_min, x_max, z_max, z_min),
173
- interpolation="nearest",
174
- vmin=0,
175
- vmax=255,
176
- )
177
- if show_bubbles and bubble_x_cm is not None and bubble_z_cm is not None:
178
- ax.scatter(
179
- bubble_x_cm,
180
- bubble_z_cm,
181
- facecolors="none",
182
- edgecolors="red",
183
- linewidths=0.8,
184
- s=28,
185
- label="Bubble ground truth",
186
- )
187
- ax.legend(loc="upper right")
188
- ax.set_xlabel("Lateral position x [cm]")
189
- ax.set_ylabel("Depth z [cm]")
190
- if title:
191
- ax.set_title(title)
192
- ax.set_xlim(x_min, x_max)
193
- ax.set_ylim(z_max, z_min)
194
- fig.savefig(output, dpi=150)
195
- plt.close(fig)
196
-
197
-
198
- def plot_gt_label(
199
- label: np.ndarray,
200
- extent_cm: tuple[float, float, float, float],
201
- output: str | Path,
202
- title: str | None = None,
203
- ) -> None:
204
- """Save a ground-truth label with the same physical axes as B-mode."""
205
-
206
- import matplotlib.pyplot as plt
207
-
208
- x_min, x_max, z_min, z_max = extent_cm
209
- fig, ax = plt.subplots(figsize=(5, 12), constrained_layout=True)
210
- ax.imshow(
211
- label,
212
- cmap="gray",
213
- origin="upper",
214
- aspect="auto",
215
- extent=(x_min, x_max, z_max, z_min),
216
- interpolation="nearest",
217
- vmin=0.0,
218
- vmax=1.0,
219
- )
220
- ax.set_xlabel("Lateral position x [cm]")
221
- ax.set_ylabel("Depth z [cm]")
222
- if title:
223
- ax.set_title(title)
224
- ax.set_xlim(x_min, x_max)
225
- ax.set_ylim(z_max, z_min)
226
- fig.savefig(output, dpi=150)
227
- plt.close(fig)
228
-
229
-
230
- def bubble_label(
231
- image_shape: tuple[int, int],
232
- extent_cm: tuple[float, float, float, float],
233
- bubble_x_cm: np.ndarray,
234
- bubble_z_cm: np.ndarray,
235
- ) -> np.ndarray:
236
- """Create a hard binary bubble label image."""
237
-
238
- height, width = image_shape
239
- x_min, x_max, z_min, z_max = extent_cm
240
- label = np.zeros((height, width), dtype=np.float32)
241
- x_pixels = (bubble_x_cm - x_min) / (x_max - x_min) * (width - 1)
242
- z_pixels = (bubble_z_cm - z_min) / (z_max - z_min) * (height - 1)
243
- x_pixels = np.rint(x_pixels).astype(int)
244
- z_pixels = np.rint(z_pixels).astype(int)
245
- valid = (x_pixels >= 0) & (x_pixels < width) & (z_pixels >= 0) & (z_pixels < height)
246
- label[z_pixels[valid], x_pixels[valid]] = 1.0
247
- return label