DispSAC / training_data /python_codes /finalize_synthetic_dataset.py
MintonTian's picture
Upload 26 files
3116550 verified
Raw History Blame Contribute Delete
7.7 kB
#!/usr/bin/env python3
"""Build the training/test layout used by the 1_100_36 datasets."""
from __future__ import annotations
import argparse
import shutil
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt # noqa: E402
import numpy as np # noqa: E402
SCRIPT_DIR = Path(__file__).resolve().parent
DEPTH_MAX_KM = 200.0
PROFILE_POINTS = 101
TEST_FRACTION = 0.001
DEBUG_PLOTS = 32
def _save_features(path: Path, values: np.ndarray) -> None:
"""Save compressed features with the same ``data`` key as the reference."""
np.savez_compressed(path, data=values)
def _save_raw_labels(path: Path, values: np.ndarray) -> None:
np.savetxt(path, values, fmt=["%.3f"] + ["%.4f"] * 9)
def _interpolate_basis(basis: np.ndarray, normalized_depth: np.ndarray) -> np.ndarray:
position = np.clip(normalized_depth, 0.0, 1.0) * (basis.shape[0] - 1)
lower = np.floor(position).astype(int)
upper = np.minimum(lower + 1, basis.shape[0] - 1)
weight = position - lower
return basis[lower] * (1.0 - weight[:, None]) + basis[upper] * weight[:, None]
def _profile_from_label(
label: np.ndarray,
crust_basis: np.ndarray,
mantle_basis: np.ndarray,
) -> tuple[np.ndarray, np.ndarray]:
moho = label[0]
depth = np.linspace(0.0, DEPTH_MAX_KM, PROFILE_POINTS)
velocity = np.empty_like(depth)
crust = depth < moho
crust_weights = _interpolate_basis(crust_basis, depth[crust] / moho)
mantle_weights = _interpolate_basis(
mantle_basis,
(depth[~crust] - moho) / (DEPTH_MAX_KM - moho),
)
velocity[crust] = crust_weights @ label[1:5]
velocity[~crust] = mantle_weights @ label[5:10]
return depth, velocity
def _write_debug_plots(
output_dir: Path,
features: np.ndarray,
labels: np.ndarray,
crust_basis: np.ndarray,
mantle_basis: np.ndarray,
) -> None:
png_dir = output_dir / "pngfolder"
png_dir.mkdir(exist_ok=True)
for sample_index in range(min(DEBUG_PLOTS, len(labels))):
depth, velocity = _profile_from_label(
labels[sample_index], crust_basis, mantle_basis
)
dispersion = features[sample_index]
fig, axes = plt.subplots(1, 2, figsize=(10, 5))
axes[0].plot(velocity, depth, "b-", label="Vs")
axes[0].set_ylim(DEPTH_MAX_KM, 0.0)
axes[0].set_xlim(2.0, 6.0)
axes[0].axhline(labels[sample_index, 0], color="k", ls=":", alpha=0.7)
axes[0].set_xlabel("Vs (km/s)")
axes[0].set_ylabel("Depth (km)")
axes[0].set_title("Isotropic Vs")
axes[0].legend()
axes[1].plot(dispersion[:, 0], dispersion[:, 1], "b-", label="Rayleigh phase")
axes[1].plot(dispersion[:, 0], dispersion[:, 2], "r--", label="Rayleigh group")
axes[1].set_xlabel("Period (s)")
axes[1].set_ylabel("Velocity (km/s)")
axes[1].set_title("Rayleigh dispersion")
axes[1].legend()
fig.tight_layout()
fig.savefig(png_dir / f"debug_0_{sample_index}.png", dpi=100)
plt.close(fig)
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("dataset_dir", type=Path)
parser.add_argument("--expected-samples", type=int, default=50_000)
parser.add_argument("--seed", type=int, default=20260909)
args = parser.parse_args()
output_dir = args.dataset_dir.expanduser().resolve()
feature_path = output_dir / "pretrain_features.npz"
label_path = output_dir / "pretrain_labels.txt"
if not feature_path.is_file() or not label_path.is_file():
raise FileNotFoundError("generated pretrain feature/label files are missing")
with np.load(feature_path) as archive:
if archive.files != ["data"]:
raise ValueError(f"unexpected NPZ keys: {archive.files}")
features = np.asarray(archive["data"], dtype=np.float64)
labels = np.loadtxt(label_path, dtype=np.float64)
labels = np.atleast_2d(labels)
expected_shape = (args.expected_samples, 36, 3)
if features.shape != expected_shape:
raise ValueError(f"expected feature shape {expected_shape}, got {features.shape}")
if labels.shape != (args.expected_samples, 10):
raise ValueError(
f"expected label shape {(args.expected_samples, 10)}, got {labels.shape}"
)
if not np.all(np.isfinite(features)) or not np.all(np.isfinite(labels)):
raise ValueError("generated dataset contains non-finite values")
if np.any(features[:, :, 1:] <= 0.0):
raise ValueError("generated dataset contains non-positive dispersion values")
crust_basis = np.loadtxt(SCRIPT_DIR / "Crust_Bs_vs.txt")
mantle_basis = np.loadtxt(SCRIPT_DIR / "Mantle_Bs_vs.txt")
if crust_basis.shape != (21, 4) or mantle_basis.shape != (80, 5):
raise ValueError(
f"unexpected basis shapes: crust={crust_basis.shape}, mantle={mantle_basis.shape}"
)
if not np.allclose(crust_basis.sum(axis=1), 1.0, atol=1.0e-12):
raise ValueError("crust basis does not form a partition of unity")
if not np.allclose(mantle_basis.sum(axis=1), 1.0, atol=1.0e-12):
raise ValueError("mantle basis does not form a partition of unity")
for filename in (
"Crust_Bs_vs.txt",
"Mantle_Bs_vs.txt",
"bspline_bases_vertical.png",
):
shutil.copy2(SCRIPT_DIR / filename, output_dir / filename)
label_max = labels.max(axis=0)
if np.any(label_max <= 0.0):
raise ValueError("label maxima must be positive")
labels_norm = labels / label_max
np.savetxt(output_dir / "pretrain_labels_max.txt", label_max, fmt="%.18e")
rng = np.random.default_rng(args.seed)
shuffle_index = rng.permutation(len(labels))
shuffled_features = features[shuffle_index]
shuffled_labels = labels[shuffle_index]
shuffled_labels_norm = labels_norm[shuffle_index]
total_dir = output_dir / "total"
train_dir = output_dir / "train_valid"
test_dir = output_dir / "test"
for directory in (total_dir, train_dir, test_dir):
directory.mkdir(exist_ok=True)
_save_features(total_dir / "pretrain_features.npz", features)
_save_features(total_dir / "pretrain_features_shuffle.npz", shuffled_features)
shutil.copy2(label_path, total_dir / "pretrain_labels.txt")
np.savetxt(total_dir / "pretrain_labels_norm.txt", labels_norm, fmt="%.18e")
_save_raw_labels(total_dir / "pretrain_labels_shuffle.txt", shuffled_labels)
np.savetxt(
total_dir / "pretrain_labels_norm_shuffle.txt",
shuffled_labels_norm,
fmt="%.18e",
)
np.savetxt(
total_dir / "pretrain_shuffle_index.txt", shuffle_index, fmt="%d"
)
test_count = max(1, int(round(len(labels) * TEST_FRACTION)))
test_slice = slice(0, test_count)
train_slice = slice(test_count, None)
_save_features(test_dir / "pretrain_features.npz", shuffled_features[test_slice])
_save_raw_labels(test_dir / "pretrain_labels.txt", shuffled_labels[test_slice])
np.savetxt(
test_dir / "pretrain_labels_norm.txt",
shuffled_labels_norm[test_slice],
fmt="%.18e",
)
_save_features(train_dir / "pretrain_features.npz", shuffled_features[train_slice])
_save_raw_labels(train_dir / "pretrain_labels.txt", shuffled_labels[train_slice])
np.savetxt(
train_dir / "pretrain_labels_norm.txt",
shuffled_labels_norm[train_slice],
fmt="%.18e",
)
_write_debug_plots(output_dir, features, labels, crust_basis, mantle_basis)
print(f"Finalized {len(labels)} samples in {output_dir}")
print(f"train_valid={len(labels) - test_count}, test={test_count}")
if __name__ == "__main__":
main()