File size: 7,702 Bytes
3116550 | 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 | #!/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()
|