File size: 21,688 Bytes
0b6e827
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
#!/usr/bin/env python
"""Field-Scale Dataset Preview — NeurIPS-ready viewer for the 4-file sample.

Renders five publication-quality figures matching the manuscript's intro
figure style. Pure NumPy + Matplotlib + h5py + hdf5plugin.

Usage:

    pip install huggingface_hub h5py hdf5plugin numpy matplotlib scipy
    huggingface-cli download subsurfacegen/field-scale-dataset-preview \\
        --repo-type=dataset --local-dir=./preview_data
    python view_preview.py --plot all --input-dir ./preview_data --output-dir ./figs

Individual:
    python view_preview.py --plot cube       # 3D cutaway render of the volume
    python view_preview.py --plot orthogonal # 3 orthogonal slices w/ crosshairs
    python view_preview.py --plot slice      # 2D slice w/ source + streamer
    python view_preview.py --plot wavefield  # Wavefield panels w/ velocity bg
    python view_preview.py --plot gather     # Shot gather panels (Left/Middle/Right)
"""
from __future__ import annotations

import argparse
import sys
from pathlib import Path

# Optional: register HDF5 compression filters used by wavefield + gather files.
try:
    import hdf5plugin  # noqa: F401
except ImportError:
    print("WARNING: hdf5plugin not installed; wavefield + gather reads may fail. "
          "Install via: pip install hdf5plugin", flush=True)

import h5py
import matplotlib

matplotlib.use("Agg")
import matplotlib.colors as mcolors
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D  # noqa: F401  (registers projection)


# ---------------- Paper-figure constants ----------------

# Match render_shot_gather_clean / render_wavefield_panel_clean conventions.
GATHER_SOURCE_INDICES = (8, 32, 56)  # paper: SG_SOURCE_INDICES
GATHER_POSITION_NAMES = ("Left", "Middle", "Right")
GATHER_SOURCE_COLORS = ("#B87100", "#004A77", "#A00000")  # bronze/navy/burgundy

# Wavefield time panels (more than the paper's 3 to show fuller progression)
WAVEFIELD_FRAMES = [
    ("0.20 s", 14),    # Start (paper)
    ("1.00 s", 71),
    ("1.96 s", 140),   # Middle (paper)
    ("3.00 s", 214),
    ("4.00 s", 285),
    ("5.00 s", 357),   # End (paper)
]

# 3D orthogonal-slices configuration: which inline + crossline + depth slice
INLINE_INDEX = 507     # the inline that the 2D slice was extracted at
CROSSLINE_INDEX = 500  # mid-y by convention
DEPTH_INDEX_FRAC = 0.5  # mid-depth

# Velocity colormap (paper convention: TwoSlopeNorm + seismic)
VEL_VMIN, VEL_VCENTER, VEL_VMAX = 1500.0, 2300.0, 4500.0

# 3D-cube cutaway render config (matches cutaway_3d_d619_batch.py)
CUBE_VEL_VCENTER = 3100.0
CUBE_DEPTH_RANGE = (80, 619)
CUBE_CROSSLINE_RANGE = (150, 1000)
CUBE_INLINE_RANGE = (150, 1000)
CUBE_VIEW_ELEV = 20
CUBE_VIEW_AZIM = -115
CUBE_MAX_FACE_DIM = 350
DX_KM = 0.010

# NeurIPS-ready typography (apply globally so every figure is consistent)
plt.rcParams.update({
    "font.size": 14,
    "axes.titlesize": 16,
    "axes.labelsize": 14,
    "xtick.labelsize": 12,
    "ytick.labelsize": 12,
    "legend.fontsize": 12,
    "figure.titlesize": 18,
    "axes.titleweight": "bold",
    "figure.titleweight": "bold",
    "axes.linewidth": 1.4,
    "xtick.major.width": 1.2,
    "ytick.major.width": 1.2,
    "xtick.major.size": 5,
    "ytick.major.size": 5,
    "lines.linewidth": 1.6,
    "savefig.bbox": "tight",
    "savefig.dpi": 150,
})


# ---------------- helpers ----------------

def _vel_norm() -> mcolors.TwoSlopeNorm:
    return mcolors.TwoSlopeNorm(vmin=VEL_VMIN, vcenter=VEL_VCENTER, vmax=VEL_VMAX)


def _wf_alpha_cmap() -> mcolors.ListedColormap:
    """Seismic with alpha proportional to |v|; tiny values become transparent."""
    base = matplotlib.colormaps["seismic"](np.linspace(0, 1, 256))
    t = np.linspace(-1.0, 1.0, 256)
    alphas = np.clip(np.abs(t) * 1.6, 0.0, 1.0)
    alphas[np.abs(t) < 0.04] = 0.0
    base[:, 3] = alphas
    return mcolors.ListedColormap(base, name="seismic_alpha")


def _load_h5_dataset(path: Path, key: str) -> tuple[np.ndarray, dict]:
    with h5py.File(path, "r") as f:
        ds = f[key]
        data = ds[...]
        attrs = {}
        for k, v in ds.attrs.items():
            attrs[k] = v.decode() if isinstance(v, bytes) else v
        for k, v in f.attrs.items():
            attrs[f"root.{k}"] = v.decode() if isinstance(v, bytes) else v
    return data, attrs


def _save(fig, output_dir: Path, name: str):
    output_dir.mkdir(parents=True, exist_ok=True)
    out = output_dir / name
    fig.savefig(out, dpi=150)
    plt.close(fig)
    print(f"  wrote {out}")


def _block_mean(arr: np.ndarray, max_dim: int) -> np.ndarray:
    h, w = arr.shape
    bh = max(1, int(np.ceil(h / max_dim)))
    bw = max(1, int(np.ceil(w / max_dim)))
    if bh == 1 and bw == 1:
        return arr.astype(np.float32, copy=False)
    h2 = (h // bh) * bh
    w2 = (w // bw) * bw
    return (arr[:h2, :w2].astype(np.float32, copy=False)
            .reshape(h2 // bh, bh, w2 // bw, bw).mean(axis=(1, 3)))


# ---------------- 3D cube cutaway (paper render_cube style) ----------------

def plot_3d_cube_cutaway(input_dir: Path, output_dir: Path):
    p = input_dir / "models/gom_d619/gom_151_sos.h5"
    print(f"Loading 3D volume for cutaway: {p}")
    with h5py.File(p, "r") as fh:
        vol = np.asarray(fh["velocity"][...], dtype=np.float32)
    nz, ny, nx = vol.shape
    print(f"  shape (nz, ny, nx) = ({nz}, {ny}, {nx})")
    norm = mcolors.TwoSlopeNorm(vmin=VEL_VMIN, vcenter=CUBE_VEL_VCENTER, vmax=VEL_VMAX)
    cmap = plt.get_cmap("seismic")

    # Take the cutaway sub-volume (top + 2 sides shaved per paper config)
    z0, z1 = CUBE_DEPTH_RANGE
    y0, y1 = CUBE_CROSSLINE_RANGE
    x0, x1 = CUBE_INLINE_RANGE
    raw_faces = {
        "top":    vol[z0,         y0:y1, x0:x1],
        "bottom": vol[z1 - 1,     y0:y1, x0:x1],
        "left":   vol[z0:z1,      y0:y1, x0],
        "right":  vol[z0:z1,      y0:y1, x1 - 1],
        "front":  vol[z0:z1,      y0,    x0:x1],
        "back":   vol[z0:z1,      y1 - 1, x0:x1],
    }
    faces = {k: _block_mean(v, CUBE_MAX_FACE_DIM) for k, v in raw_faces.items()}
    del vol

    x_km_lim = (x0 * DX_KM, (x1 - 1) * DX_KM)
    y_km_lim = (y0 * DX_KM, (y1 - 1) * DX_KM)
    z_km_lim = (z0 * DX_KM, (z1 - 1) * DX_KM)

    def coords(face_shape, a_lim, b_lim):
        nh, nw = face_shape
        aa = np.linspace(a_lim[0], a_lim[1], nh)
        bb = np.linspace(b_lim[0], b_lim[1], nw)
        A, B = np.meshgrid(aa, bb, indexing="ij")
        return A, B

    fig = plt.figure(figsize=(10, 9))
    ax = fig.add_subplot(111, projection="3d")
    ax.set_facecolor("white")
    surf_kw = dict(shade=False, rstride=1, cstride=1, linewidth=0,
                   antialiased=False, rasterized=True)

    Y, X = coords(faces["top"].shape, y_km_lim, x_km_lim)
    ax.plot_surface(X, Y, np.full_like(X, z_km_lim[0]),
                    facecolors=cmap(norm(faces["top"])), **surf_kw)
    Y, X = coords(faces["bottom"].shape, y_km_lim, x_km_lim)
    ax.plot_surface(X, Y, np.full_like(X, z_km_lim[1]),
                    facecolors=cmap(norm(faces["bottom"])), **surf_kw)
    Z2, Y2 = coords(faces["left"].shape, z_km_lim, y_km_lim)
    ax.plot_surface(np.full_like(Y2, x_km_lim[0]), Y2, Z2,
                    facecolors=cmap(norm(faces["left"])), **surf_kw)
    Z2, Y2 = coords(faces["right"].shape, z_km_lim, y_km_lim)
    ax.plot_surface(np.full_like(Y2, x_km_lim[1]), Y2, Z2,
                    facecolors=cmap(norm(faces["right"])), **surf_kw)
    Z3, X3 = coords(faces["front"].shape, z_km_lim, x_km_lim)
    ax.plot_surface(X3, np.full_like(X3, y_km_lim[0]), Z3,
                    facecolors=cmap(norm(faces["front"])), **surf_kw)
    Z3, X3 = coords(faces["back"].shape, z_km_lim, x_km_lim)
    ax.plot_surface(X3, np.full_like(X3, y_km_lim[1]), Z3,
                    facecolors=cmap(norm(faces["back"])), **surf_kw)

    ax.set_xlim(*x_km_lim); ax.set_ylim(*y_km_lim); ax.set_zlim(*z_km_lim)
    ax.invert_zaxis()
    ax.set_box_aspect((1, 1, 1))
    ax.view_init(elev=CUBE_VIEW_ELEV, azim=CUBE_VIEW_AZIM)
    ax.set_xticks([]); ax.set_yticks([]); ax.set_zticks([])
    for pane in (ax.xaxis.pane, ax.yaxis.pane, ax.zaxis.pane):
        pane.set_facecolor((1, 1, 1, 0)); pane.set_edgecolor((1, 1, 1, 0))
    ax.set_title("3D SOS-smoothed velocity volume (cutaway)\n"
                 "gom_151_sos.h5  —  Gulf of Mexico realization",
                 pad=18)
    # Manual colorbar
    sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
    sm.set_array([])
    cbar = fig.colorbar(sm, ax=ax, shrink=0.55, pad=0.05, aspect=20)
    cbar.set_label("velocity (m/s)", fontsize=14)
    cbar.ax.tick_params(labelsize=12)
    _save(fig, output_dir, "model_3d_cube_cutaway.png")


# ---------------- 3D orthogonal slices with crosshairs ----------------

def plot_3d_orthogonal_slices(input_dir: Path, output_dir: Path):
    p = input_dir / "models/gom_d619/gom_151_sos.h5"
    print(f"Loading 3D volume: {p}")
    vol, _ = _load_h5_dataset(p, "velocity")
    nz, ny, nx = vol.shape
    mid_z = int(round(nz * DEPTH_INDEX_FRAC))
    print(f"  shape (nz, ny, nx) = ({nz}, {ny}, {nx})")
    print(f"  inline_idx={INLINE_INDEX}, crossline_idx={CROSSLINE_INDEX}, depth_idx={mid_z}")

    norm = _vel_norm()
    crosshair_kw = dict(color="red", linestyle="--", linewidth=2.0,
                        alpha=0.95, dashes=(4, 3))

    fig, axes = plt.subplots(1, 3, figsize=(20, 6.5),
                             gridspec_kw={"wspace": 0.25})

    # Panel 1: inline slice (depth × x).  Crossline + depth slices appear as crosshair.
    inline = vol[:, INLINE_INDEX, :]
    im = axes[0].imshow(inline, aspect="auto", cmap="seismic", norm=norm,
                        extent=[0, nx, nz, 0], interpolation="lanczos")
    axes[0].set_title(f"Inline {INLINE_INDEX}\n(the 2D slice file)")
    axes[0].set_xlabel("crossline x (sample)")
    axes[0].set_ylabel("depth (sample)")
    axes[0].axvline(CROSSLINE_INDEX, **crosshair_kw)  # where crossline panel cuts
    axes[0].axhline(mid_z, **crosshair_kw)            # where depth panel cuts

    # Panel 2: crossline slice (depth × y).  Inline + depth slices as crosshair.
    cross = vol[:, :, CROSSLINE_INDEX]
    axes[1].imshow(cross, aspect="auto", cmap="seismic", norm=norm,
                   extent=[0, ny, nz, 0], interpolation="lanczos")
    axes[1].set_title(f"Crossline at x={CROSSLINE_INDEX}")
    axes[1].set_xlabel("inline y (sample)")
    axes[1].set_ylabel("depth (sample)")
    axes[1].axvline(INLINE_INDEX, **crosshair_kw)  # where inline panel cuts
    axes[1].axhline(mid_z, **crosshair_kw)         # where depth panel cuts

    # Panel 3: depth slice (y × x).  Inline + crossline cuts as crosshair.
    depth = vol[mid_z, :, :]
    axes[2].imshow(depth, aspect="auto", cmap="seismic", norm=norm,
                   extent=[0, nx, ny, 0], interpolation="lanczos")
    axes[2].set_title(f"Depth slice at z={mid_z}")
    axes[2].set_xlabel("crossline x (sample)")
    axes[2].set_ylabel("inline y (sample)")
    axes[2].axhline(INLINE_INDEX, **crosshair_kw)    # where inline panel cuts
    axes[2].axvline(CROSSLINE_INDEX, **crosshair_kw) # where crossline panel cuts

    # Colorbar with key above it explaining the dashed lines.
    cbar_ax = fig.add_axes([0.92, 0.13, 0.013, 0.66])
    cbar = fig.colorbar(im, cax=cbar_ax)
    cbar.set_label("velocity (m/s)", fontsize=14)
    cbar.ax.tick_params(labelsize=12)
    # Compact key just above the colorbar
    fig.text(0.926, 0.85,
             "‒‒ red dashed:\nlocations of\nother 2 panels",
             fontsize=11, color="red", weight="bold",
             ha="left", va="bottom")

    fig.suptitle("3D SOS volume — orthogonal slices through gom_151_sos.h5",
                 y=0.98)
    _save(fig, output_dir, "model_3d_orthogonal_slices.png")


# ---------------- 2D slice with source + streamer geometry ----------------

def plot_2d_slice(input_dir: Path, output_dir: Path):
    """2D velocity slice with seismic cmap, streamer + source geometry overlay."""
    p = input_dir / "slices/slice_gom_151_il_0507.h5"
    print(f"Loading 2D slice: {p}")
    sl, _ = _load_h5_dataset(p, "velocity")
    nz, nx = sl.shape
    print(f"  shape (nz, nx) = ({nz}, {nx})")

    # Physical extent (10 m grid spacing)
    extent = (0.0, nx * 0.01, nz * 0.01, 0.0)
    norm = _vel_norm()

    fig, ax = plt.subplots(1, 1, figsize=(13, 5.8))
    im = ax.imshow(sl, cmap="seismic", norm=norm,
                   extent=extent, aspect="auto", interpolation="lanczos")
    ax.set_xlabel("horizontal x (km)")
    ax.set_ylabel("depth z (km)")
    ax.set_title("2D velocity slice  —  slice_gom_151_il_0507.h5  (inline 507 of gom_151)")

    # Streamer (1000 receivers @ 10 m depth, 10 m horizontal spacing,
    # standard 0.5 km edge margin per the simulation config).
    rec_z_km = 0.01
    rec_x_km = np.linspace(0.6, 9.4, 1000)
    rec_x_show = rec_x_km[::25]
    ax.scatter(rec_x_show, np.full_like(rec_x_show, rec_z_km),
               marker="v", s=24, c="black", edgecolors="white",
               linewidths=0.4, zorder=10, label="receivers (every 25th)")

    # Source for the wavefield panel (paper figure)
    ax.scatter([4.958], [rec_z_km], marker="*", s=460,
               c="gold", edgecolors="black", linewidths=1.2,
               zorder=11, label="wavefield source @ x=4.958 km")
    ax.legend(loc="upper right", framealpha=0.92)
    cbar = fig.colorbar(im, ax=ax, pad=0.01, shrink=0.95)
    cbar.set_label("velocity (m/s)")
    _save(fig, output_dir, "slice_2d_velocity.png")


# ---------------- Wavefield panels (paper render style) ----------------

def plot_wavefield(input_dir: Path, output_dir: Path,
                   frames: list[tuple[str, int]] = WAVEFIELD_FRAMES):
    """Wavefield time progression with the velocity model drawn behind."""
    p = input_dir / "wavefields/5s/3-6Hz/wavefield_gom_151_il_0507_srchorizontal4.958km.h5"
    print(f"Loading wavefield: {p}")
    wf, _ = _load_h5_dataset(p, "wavefield")
    print(f"  wavefield shape (nt, _, _) = {wf.shape}")
    # Background velocity slice (loaded for the underlay)
    vp = input_dir / "slices/slice_gom_151_il_0507.h5"
    vel, _ = _load_h5_dataset(vp, "velocity")
    print(f"  velocity background shape (nz, nx) = {vel.shape}")

    extent = (0.0, 10.0, 6.19, 0.0)
    src_x_km = 4.958
    wf_cmap = _wf_alpha_cmap()

    n = len(frames)
    ncols = 3
    nrows = int(np.ceil(n / ncols))
    fig, axes = plt.subplots(nrows, ncols, figsize=(6.5 * ncols, 4.8 * nrows),
                             gridspec_kw={"wspace": 0.18, "hspace": 0.30})
    axes = np.atleast_2d(axes).flatten()

    for idx, (label, frame_idx) in enumerate(frames):
        ax = axes[idx]
        frame_idx = max(0, min(frame_idx, wf.shape[0] - 1))
        # Wavefield is stored (nt, nx, nz) where nx=1000, nz=619 (devito
        # convention).  Transpose to (nz, nx) so it aligns with the velocity
        # slice (nz=619, nx=1000) when overlaid on the same physical extent.
        wf_frame = wf[frame_idx].T
        # Underlay velocity model in gray, alpha 0.40
        ax.imshow(vel, cmap="gray", alpha=0.40, extent=extent,
                  aspect="auto", interpolation="nearest",
                  vmin=float(vel.min()), vmax=float(vel.max()))
        # Wavefield with seismic-alpha cmap (transparent near 0)
        clip = float(np.percentile(np.abs(wf_frame), 99.5))
        if clip <= 0:
            clip = float(np.abs(wf_frame).max() + 1e-12)
        ax.imshow(wf_frame, cmap=wf_cmap,
                  norm=mcolors.Normalize(-clip, clip),
                  extent=extent, aspect="auto", interpolation="nearest")
        # Source marker
        ax.scatter([src_x_km], [0.0], marker="*", s=320, c="gold",
                   edgecolors="black", linewidths=1.2, zorder=10)
        ax.set_xlim(0, 10); ax.set_ylim(6.19, 0)
        ax.set_xlabel("horizontal x (km)")
        ax.set_ylabel("depth z (km)")
        ax.set_title(f"t = {label}", fontsize=15)

    for j in range(n, len(axes)):
        axes[j].set_visible(False)

    fig.suptitle("Wavefield time progression  —  3-6 Hz, source @ x=4.958 km\n"
                 "(velocity model in grayscale; wavefield amplitude in red/blue)",
                 y=1.00, fontsize=17)
    _save(fig, output_dir, "wavefield_time_progression.png")


# ---------------- Shot gather (paper render style) ----------------

def plot_shot_gather(input_dir: Path, output_dir: Path,
                     source_indices=GATHER_SOURCE_INDICES,
                     position_names=GATHER_POSITION_NAMES,
                     source_colors=GATHER_SOURCE_COLORS):
    """1x4 layout: velocity model with color-coded source positions (left)
    + 3 shot-gather panels (Left/Middle/Right matching paper figure)."""
    p_gather = input_dir / "shot_gathers/8s/3-25Hz/shot_gather_cube_gom_151_il_0507.h5"
    p_slice = input_dir / "slices/slice_gom_151_il_0507.h5"
    print(f"Loading shot-gather cube: {p_gather}")
    cube, gather_attrs = _load_h5_dataset(p_gather, "shot_gather_cube")
    n_src, nt, n_rec = cube.shape
    print(f"  shape (n_src, nt, n_rec) = ({n_src}, {nt}, {n_rec})")
    print(f"Loading velocity slice for geometry panel: {p_slice}")
    vel, _ = _load_h5_dataset(p_slice, "velocity")

    # Source x-positions in km from the gather cube's flat attr (length 64).
    src_x_all = np.asarray(gather_attrs.get("source_horizontal_km", []), dtype=float)
    if src_x_all.size != n_src:
        # Fall back: linear sample if attr missing/wrong length
        src_x_all = np.linspace(0.6, 9.4, n_src)
    rec_z_km = float(gather_attrs.get("receiver_depth_km", 0.01))

    delta_t_stored = 14e-3
    total_s = nt * delta_t_stored

    # 1 x 4 grid:  velocity panel (wider so it stays roughly square)
    # then three gather panels.
    fig, axes = plt.subplots(
        1, 4,
        figsize=(26, 6.8),
        gridspec_kw={"width_ratios": [1.55, 1.0, 1.0, 1.0], "wspace": 0.22},
    )

    # ----- Panel 0: velocity model with source positions overlay -----
    ax0 = axes[0]
    extent_vel = (0.0, 10.0, 6.19, 0.0)
    ax0.imshow(vel, cmap="seismic", norm=_vel_norm(),
               extent=extent_vel, aspect="auto", interpolation="lanczos")
    # Streamer (1000 receivers @ 10 m depth, every 25th shown)
    rec_x_all = np.linspace(0.6, 9.4, 1000)
    rec_x_show = rec_x_all[::25]
    ax0.scatter(rec_x_show, np.full_like(rec_x_show, rec_z_km),
                marker="v", s=22, c="black", edgecolors="white",
                linewidths=0.4, zorder=10, label="receivers (every 25th)")
    # Highlight the 3 chosen sources at their actual horizontal_km
    for sidx, color, name in zip(source_indices, source_colors, position_names):
        sx = float(src_x_all[sidx])
        ax0.scatter([sx], [rec_z_km], marker="*", s=520,
                    c=color, edgecolors="black", linewidths=1.4, zorder=11,
                    label=f"{name}  (idx {sidx}, x={sx:.2f} km)")
    ax0.set_xlim(0, 10); ax0.set_ylim(6.19, 0)
    ax0.set_xlabel("horizontal x (km)")
    ax0.set_ylabel("depth z (km)")
    ax0.set_title("Source positions on the velocity model", fontsize=15)
    ax0.legend(loc="lower right", framealpha=0.92, fontsize=10)

    # ----- Panels 1-3: gathers -----
    clip = float(np.percentile(np.abs(cube), 97.0))
    if clip <= 0:
        clip = float(np.abs(cube).max() + 1e-12)
    for ax, sidx, label, color in zip(axes[1:], source_indices,
                                      position_names, source_colors):
        sidx = max(0, min(sidx, n_src - 1))
        gather = cube[sidx]
        ax.imshow(gather, cmap="seismic", vmin=-clip, vmax=clip,
                  aspect="auto", interpolation="lanczos",
                  extent=[0, n_rec, total_s, 0])
        ax.set_xlabel("receiver index")
        ax.set_ylabel("time (s)")
        for s in ax.spines.values():
            s.set_color(color); s.set_linewidth(2.4)
        ax.set_title(f"{label}  (source idx {sidx})",
                     color=color, fontweight="bold", fontsize=15)

    fig.suptitle("Shot-gather panels  —  3-25 Hz, 64-source cube  "
                 "(velocity model on left shows the 3 source positions; matches manuscript intro figure)",
                 y=1.02, fontsize=17)
    _save(fig, output_dir, "shot_gather_panels.png")


# ---------------- main ----------------

def main():
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--input-dir", type=Path, default=Path("./preview_data"),
                    help="Dir holding the 4 h5 files. Default: ./preview_data")
    ap.add_argument("--output-dir", type=Path, default=Path("./figs"),
                    help="Where to save PNGs. Default: ./figs")
    ap.add_argument("--plot",
                    choices=("cube", "orthogonal", "slice", "wavefield", "gather", "all"),
                    default="all", help="Which figure to render. Default: all")
    args = ap.parse_args()

    if not args.input_dir.exists():
        sys.exit(f"--input-dir does not exist: {args.input_dir}")

    plots = ("cube", "orthogonal", "slice", "wavefield", "gather") \
        if args.plot == "all" else (args.plot,)
    for p in plots:
        if p == "cube": plot_3d_cube_cutaway(args.input_dir, args.output_dir)
        elif p == "orthogonal": plot_3d_orthogonal_slices(args.input_dir, args.output_dir)
        elif p == "slice": plot_2d_slice(args.input_dir, args.output_dir)
        elif p == "wavefield": plot_wavefield(args.input_dir, args.output_dir)
        elif p == "gather": plot_shot_gather(args.input_dir, args.output_dir)
    print(f"\nDone. PNGs in {args.output_dir}/")


if __name__ == "__main__":
    main()