| |
| """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 |
|
|
| |
| try: |
| import hdf5plugin |
| 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 |
|
|
|
|
| |
|
|
| |
| GATHER_SOURCE_INDICES = (8, 32, 56) |
| GATHER_POSITION_NAMES = ("Left", "Middle", "Right") |
| GATHER_SOURCE_COLORS = ("#B87100", "#004A77", "#A00000") |
|
|
| |
| WAVEFIELD_FRAMES = [ |
| ("0.20 s", 14), |
| ("1.00 s", 71), |
| ("1.96 s", 140), |
| ("3.00 s", 214), |
| ("4.00 s", 285), |
| ("5.00 s", 357), |
| ] |
|
|
| |
| INLINE_INDEX = 507 |
| CROSSLINE_INDEX = 500 |
| DEPTH_INDEX_FRAC = 0.5 |
|
|
| |
| VEL_VMIN, VEL_VCENTER, VEL_VMAX = 1500.0, 2300.0, 4500.0 |
|
|
| |
| 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 |
|
|
| |
| 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, |
| }) |
|
|
|
|
| |
|
|
| 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))) |
|
|
|
|
| |
|
|
| 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") |
|
|
| |
| 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) |
| |
| 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") |
|
|
|
|
| |
|
|
| 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}) |
|
|
| |
| 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) |
| axes[0].axhline(mid_z, **crosshair_kw) |
|
|
| |
| 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) |
| axes[1].axhline(mid_z, **crosshair_kw) |
|
|
| |
| 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) |
| axes[2].axvline(CROSSLINE_INDEX, **crosshair_kw) |
|
|
| |
| 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) |
| |
| 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") |
|
|
|
|
| |
|
|
| 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})") |
|
|
| |
| 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)") |
|
|
| |
| |
| 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)") |
|
|
| |
| 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") |
|
|
|
|
| |
|
|
| 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}") |
| |
| 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)) |
| |
| |
| |
| wf_frame = wf[frame_idx].T |
| |
| ax.imshow(vel, cmap="gray", alpha=0.40, extent=extent, |
| aspect="auto", interpolation="nearest", |
| vmin=float(vel.min()), vmax=float(vel.max())) |
| |
| 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") |
| |
| 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") |
|
|
|
|
| |
|
|
| 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") |
|
|
| |
| src_x_all = np.asarray(gather_attrs.get("source_horizontal_km", []), dtype=float) |
| if src_x_all.size != n_src: |
| |
| 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 |
|
|
| |
| |
| 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}, |
| ) |
|
|
| |
| 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") |
| |
| 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)") |
| |
| 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) |
|
|
| |
| 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") |
|
|
|
|
| |
|
|
| 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() |
|
|