File size: 4,000 Bytes
55b0cc0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
own_das_reconstruct.py — reconstruct one rotation frame of an acquisition with
the authors' ORIGINAL in-plane DAS beamformer (sim/beamform.py of the generation
codebase, vendored below as `das_planewave`), independent of the zea pipeline.

Produced for reviewer verification (Tristan, 2026-07-17): the same frame of the
same acquisition is also reconstructed with the package's reconstruct.py (zea
Pipeline: demodulate -> delay_and_sum -> envelope -> normalize -> log-compress);
comparing the two PNGs confirms the raw RF channel data is correct and intended.

Only numpy / scipy / h5py / matplotlib are needed (no zea).

Usage:
    python own_das_reconstruct.py [--input ../data/coarse_pitch_0p3__point_z080_r4.hdf5]
"""
import argparse
import os
from pathlib import Path

import h5py
import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import hilbert

HERE = Path(__file__).parent
DEFAULT_INPUT = HERE.parent / "data" / "coarse_pitch_0p3__point_z080_r4.hdf5"


def das_planewave(rf, t0, xe, c, fs, z_mm, x_mm, apod=True):
    """Vectorized in-plane DAS for one normal plane-wave transmit
    (verbatim logic of the authors' sim/beamform.py).

    rf: (n_ax, n_el) channel data; xe: (n_el,) element x positions [m].
    Returns beamformed image (nz, nx)."""
    n_ax, n_el = rf.shape
    xg = x_mm * 1e-3
    zg = z_mm * 1e-3
    win = np.hanning(n_el) if apod else np.ones(n_el)

    X = xg[None, :, None]
    Z = zg[:, None, None]
    XE = xe[None, None, :]
    delay = (Z + np.sqrt((X - XE) ** 2 + Z**2)) / c        # (nz, nx, n_el)
    idx = np.round((delay - t0) * fs).astype(np.int64)
    ok = (idx >= 0) & (idx < n_ax)
    idx_c = np.clip(idx, 0, n_ax - 1)
    el = np.arange(n_el)[None, None, :]
    gathered = rf[idx_c, el] * ok * win[None, None, :]
    return gathered.sum(axis=2)


def main():
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument("--input", type=Path, default=DEFAULT_INPUT)
    ap.add_argument("--output", type=Path, default=None)
    ap.add_argument("--frame-index", type=int, default=None)
    args = ap.parse_args()

    with h5py.File(args.input, "r") as f:
        scan = f["tracks/track_0/scan"]
        fs = float(scan["sampling_frequency"][()])
        c = float(scan["sound_speed"][()])
        t0 = float(np.asarray(scan["initial_times"]).ravel()[0])
        xe = np.asarray(f["probe/probe_geometry"])[:, 0]     # element x [m]
        rot_deg = np.degrees(np.asarray(f["metadata/probe_pose/rotation"])[:, 2])
        raw = f["tracks/track_0/data/raw_data"]              # (n_fr, 1, n_ax, n_el, 1)
        frame = args.frame_index
        if frame is None:  # same default as reconstruct.py: ~90 deg rotation magnitude
            frame = int(np.argmin(np.abs(np.abs(rot_deg) - 90.0)))
        rf = np.asarray(raw[frame, 0, :, :, 0], dtype=np.float64)

    n_ax = rf.shape[0]
    dz = c / (2 * fs) * 1e3                                  # mm per RF sample
    z_max_mm = (t0 + n_ax / fs) * c / 2 * 1e3
    z_mm = np.arange(0.0, z_max_mm, dz)
    x_mm = xe * 1e3                                          # one beam per element

    img = das_planewave(rf, t0, xe, c, fs, z_mm, x_mm)
    env = np.abs(hilbert(img, axis=0))
    env /= env.max()
    bmode_db = 20 * np.log10(env + 1e-12)

    out = args.output or HERE / (args.input.stem + "__own_das.png")
    fig, ax = plt.subplots(figsize=(5, 8))
    im = ax.imshow(bmode_db, cmap="gray", vmin=-40, vmax=0, aspect="equal",
                   extent=[x_mm[0], x_mm[-1], z_mm[-1], z_mm[0]])
    ax.set_xlabel("lateral [mm]")
    ax.set_ylabel("depth [mm]")
    ax.set_title(f"{args.input.name}\nauthors' own DAS (sim/beamform.py), "
                 f"frame {frame} ({rot_deg[frame]:.0f}°), DR −40 dB")
    fig.colorbar(im, ax=ax, label="dB")
    fig.tight_layout()
    fig.savefig(out, dpi=150)
    print(f"frame {frame} @ {rot_deg[frame]:.1f} deg  ->  {out}")


if __name__ == "__main__":
    main()