File size: 16,050 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
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
"""
Synthetic isotropic dispersion dataset generator.
Builds isotropic Voigt-vs models from B-splines, validates them, runs CPS forward,
and returns Rayleigh phase + group dispersion for pretraining.
"""
from __future__ import annotations

import sys
from pathlib import Path
from typing import Optional, Tuple

import numpy as np

ISO_ROOT = Path(__file__).resolve().parent.parent
CPS_PARENT = Path("/data/tianmingteng/CPS_PROGRAM")  # kept for main script compat
PARENT_DIR = Path("/data/tianmingteng/Downloads/Script/TMT_ModelDesign")
sys.path.insert(0, str(PARENT_DIR))

# ---- FAST_SURF in-process forward (replaces CPS subprocess) -------------
FASTSURF_DIR = Path("/data/tianmingteng/fortran_API")
sys.path.insert(0, str(FASTSURF_DIR))
import fastsurf

DATAMAKER_ROOT = Path(__file__).resolve().parent
CRUST_BS_PATH = DATAMAKER_ROOT / "Crust_Bs_vs.txt"
MANTLE_BS_PATH = DATAMAKER_ROOT / "Mantle_Bs_vs.txt"
MINEOS_PREM_PATH = ISO_ROOT / "prem_noocean.txt"
CPS_WORK_ROOT = ISO_ROOT / "cps_work"
DEPTH_MAX = 200.0
SAMPLE_NUM = 101
PLOT_DEBUG = False#True
PERIODS = np.array([
    1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 11.0, 13.0, 15.0, 17.0, 19.0,
    22.0, 25.0, 28.0, 31.0, 32.0, 34.0, 37.0, 40.0, 43.0, 46.0, 49.0,
    52.0, 55.0, 60.0, 65.0, 70.0, 75.0, 80.0, 85.0, 90.0, 95.0, 100.0,
    #110.0, 120.0, 130.0, 140.0, 150.0, 160.0, 170.0, 180.0, 190.0, 200.0
], dtype=np.float64)

MOHO_MIN, MOHO_MAX = 7.0, 70.0
CRUST1_MIN, CRUST1_MAX = 2.2, 4.0
CRUST2_MIN, CRUST2_MAX = 3.0, 4.2
CRUST3_MIN, CRUST3_MAX = 3.5, 4.2
CRUST4_MIN, CRUST4_MAX = 3.8, 4.4
MANTLE1_MIN, MANTLE1_MAX = 4.0, 5.0
MANTLE2_MIN, MANTLE2_MAX = 4.0, 5.0
MANTLE3_MIN, MANTLE3_MAX = 4.0, 5.0
MANTLE4_MIN, MANTLE4_MAX = 4.0, 5.0
MANTLE5_MIN, MANTLE5_MAX = 4.0, 5.0


def B_spline(nBs: int, degBs: int, dep_start: float, dep_end: float, factor: int, npts: int):
    """Return an open-clamped B-spline basis evaluated on a regular grid.

    ``degBs`` is the mathematical polynomial degree: 1 is linear, 2 is
    quadratic, and 3 is cubic.  The previous implementation used only
    ``nBs + degBs`` knots, effectively treating this value as spline order;
    a cubic basis requires ``nBs + degBs + 1`` knots.
    """
    if nBs < degBs + 1:
        raise ValueError(
            f"degree {degBs} requires at least {degBs + 1} basis functions; "
            f"got {nBs}"
        )
    if npts < 2 or dep_end <= dep_start:
        raise ValueError("invalid B-spline sampling interval")

    n_internal = nBs - degBs - 1
    if n_internal > 0:
        n_intervals = n_internal + 1
        if factor <= 0:
            raise ValueError("factor must be positive")
        widths = factor ** np.arange(n_intervals, dtype=np.float64)
        cumulative = np.cumsum(widths)[:-1] / widths.sum()
        internal = dep_start + (dep_end - dep_start) * cumulative
    else:
        internal = np.empty(0, dtype=np.float64)

    knots = np.concatenate([
        np.full(degBs + 1, dep_start, dtype=np.float64),
        internal,
        np.full(degBs + 1, dep_end, dtype=np.float64),
    ])
    depth = np.linspace(dep_start, dep_end, npts, dtype=np.float64)

    # Cox-de Boor recursion, starting from piecewise-constant functions.
    work = np.zeros((len(knots) - 1, npts), dtype=np.float64)
    for i in range(len(knots) - 1):
        work[i, (depth >= knots[i]) & (depth < knots[i + 1])] = 1.0
    for degree in range(1, degBs + 1):
        updated = np.zeros_like(work)
        for i in range(len(knots) - degree - 1):
            left_denominator = knots[i + degree] - knots[i]
            right_denominator = knots[i + degree + 1] - knots[i + 1]
            if left_denominator > 0:
                updated[i] += ((depth - knots[i]) / left_denominator) * work[i]
            if right_denominator > 0:
                updated[i] += ((knots[i + degree + 1] - depth) /
                               right_denominator) * work[i + 1]
        work = updated

    basis = work[:nBs].T
    basis[-1, :] = 0.0
    basis[-1, -1] = 1.0
    return basis


def _build_bspline_basis(n_bs: int, n_pts: int, dep_start: float, dep_end: float) -> np.ndarray:
    basis = B_spline(nBs=n_bs, degBs=3, dep_start=dep_start, dep_end=dep_end, factor=1, npts=n_pts)
    basis = np.asarray(basis, dtype=float)
    if basis.ndim == 1:
        basis = basis.reshape(n_pts, n_bs)
    return basis


def load_basis() -> Tuple[np.ndarray, np.ndarray]:
    if CRUST_BS_PATH.is_file():
        try:
            cbs = np.loadtxt(CRUST_BS_PATH)
        except Exception:
            cbs = _build_bspline_basis(4, 21, 0.0, 1.0)
    else:
        cbs = _build_bspline_basis(4, 21, 0.0, 1.0)
        np.savetxt(CRUST_BS_PATH, cbs)
    if MANTLE_BS_PATH.is_file():
        try:
            mbs = np.loadtxt(MANTLE_BS_PATH)
        except Exception:
            mbs = _build_bspline_basis(5, 80, 0.0, 1.0)
    else:
        mbs = _build_bspline_basis(5, 80, 0.0, 1.0)
        np.savetxt(MANTLE_BS_PATH, mbs)
    if cbs.ndim == 1:
        cbs = cbs.reshape(-1, 4)
    if mbs.ndim == 1:
        mbs = mbs.reshape(-1, 5)
    return cbs, mbs


def bs_eval(cbs: np.ndarray, mbs: np.ndarray, moho: float, v_crust: np.ndarray, v_mantle: np.ndarray, depth_km: np.ndarray):
    vs = np.zeros_like(depth_km, dtype=float)
    layer_type = np.zeros_like(depth_km, dtype=np.int8)
    crust_mask = depth_km < moho
    mantle_mask = ~crust_mask
    layer_type[mantle_mask] = 1
    if np.any(crust_mask):
        d_c = depth_km[crust_mask]
        t = np.clip(d_c / (moho + 1e-9), 0, 1) * (len(cbs) - 1)
        lo = np.floor(t).astype(int)
        hi = np.minimum(lo + 1, len(cbs) - 1)
        wh = t - lo
        wl = 1 - wh
        for i, (ilo, ihi, wlo, whi) in enumerate(zip(lo, hi, wl, wh)):
            r = wlo * cbs[ilo] + whi * cbs[ihi]
            vs[np.where(crust_mask)[0][i]] = np.dot(r, v_crust)
    if np.any(mantle_mask):
        d_m = depth_km[mantle_mask]
        span = DEPTH_MAX - moho + 1e-9
        t = np.clip((d_m - moho) / span, 0, 1) * (len(mbs) - 1)
        lo = np.floor(t).astype(int)
        hi = np.minimum(lo + 1, len(mbs) - 1)
        wh = t - lo
        wl = 1 - wh
        for i, (ilo, ihi, wlo, whi) in enumerate(zip(lo, hi, wl, wh)):
            r = wlo * mbs[ilo] + whi * mbs[ihi]
            vs[np.where(mantle_mask)[0][i]] = np.dot(r, v_mantle)
    return vs, layer_type


def sample_params():
    moho = np.random.uniform(MOHO_MIN, MOHO_MAX)
    v_crust = np.array([
        np.random.uniform(CRUST1_MIN, CRUST1_MAX),
        np.random.uniform(CRUST2_MIN, CRUST2_MAX),
        np.random.uniform(CRUST3_MIN, CRUST3_MAX),
        np.random.uniform(CRUST4_MIN, CRUST4_MAX),
    ], dtype=float)
    v_mantle = np.array([
        np.random.uniform(MANTLE1_MIN, MANTLE1_MAX),
        np.random.uniform(MANTLE2_MIN, MANTLE2_MAX),
        np.random.uniform(MANTLE3_MIN, MANTLE3_MAX),
        np.random.uniform(MANTLE4_MIN, MANTLE4_MAX),
        np.random.uniform(MANTLE5_MIN, MANTLE5_MAX),
    ], dtype=float)
    return moho, v_crust, v_mantle


def is_valid_model(vs: np.ndarray, depth: np.ndarray, moho: float) -> Tuple[bool, str]:
    """
    Validate isotropic Vs profile using the Vs-only subset of the CPS rules.
    Returns (valid, reason).
    """
    # ── 1. Basic sanity ──────────────────────────────────────────────────────
    if (vs < 0.5).any():
        return False, "velocity < 0.5"
    if (depth < 0).any():
        return False, "negative depth"
    if abs(depth[-1] - DEPTH_MAX) > 1e-3:
        return False, "depth max mismatch"
    if (np.diff(depth) <= 0).any():
        return False, "non-increasing depth"

    # ── 2. Basement floor ────────────────────────────────────────────────────
    if vs[-1] < 4.0:
        return False, "basement vs < 4.0"

    # ── 3. VP/VS sanity ───────────────────────────────────────────────────────
    vp = (0.9409 + 2.0947 * vs
          - 0.8206 * vs**2
          + 0.2683 * vs**3
          - 0.0251 * vs**4)
    vpvs = vp / vs
    # if (vpvs < 1.50).any() or (vpvs > 2.10).any():
    if (vpvs < 1.50).any() or (vpvs > 2.6).any():
        return False, "VP/VS out of range"

    # ── 4. Crust monotonicity ────────────────────────────────────────────────
    crust_mask = depth < moho
    if crust_mask.sum() > 1:
        vs_c = vs[crust_mask]
        if np.any(np.diff(vs_c) < 0.0):
            return False, "crust vs decreases"

    # ── 5. Moho jump ─────────────────────────────────────────────────────────
    moho_idx = np.argmin(np.abs(depth - moho))
    if 0 < moho_idx < len(depth) - 1:
        jump_vs = vs[moho_idx + 1] - vs[moho_idx - 1]
        if jump_vs < 0:
            return False, "negative jump at Moho"
        if jump_vs > 2.0:
            return False, "jump > 2.0 at Moho"
        if vs[moho_idx - 1] < 2.5:
            return False, "vs too low just above Moho"

    # ── 6. Mantle smoothness ────────────────────────────────────────────────
    mantle_mask = depth >= moho
    if mantle_mask.sum() > 3:
        vs_m = vs[mantle_mask]
        d_m = depth[mantle_mask]

        # Reject sharp corners / kinks by limiting local slope changes.
        # This catches profiles where the mantle bends abruptly at a single depth.
        first_grad = np.gradient(vs_m, d_m)
        second_grad = np.gradient(first_grad, d_m)

        max_slope = np.max(np.abs(first_grad))
        max_slope_change = np.max(np.abs(np.diff(first_grad))) if first_grad.size > 1 else 0.0
        max_curvature = np.max(np.abs(second_grad))
        
        if max_slope > 0.1: #0.18:#US0.12526 #0.03:
            return False, f"mantle slope too sharp ({max_slope:.3f})"
        if max_slope_change > 0.001:#0.055: #US:0.05189 #0.005:
            return False, f"mantle slope changes too abruptly ({max_slope_change:.4f})"
        if max_curvature > 0.12: #US:0.029810000000000336 #0.0015:
            return False, f"mantle curvature too sharp ({max_curvature:.4f})"

        # Keep a mild low-variation check for very long mantle sections.
        if mantle_mask.sum() > 20 and np.std(vs_m) > 0.1: #0.18: #US0.167  #0.06:
            return False, "mantle vs varies too little"

    # ── 7. Global velocity gradient ──────────────────────────────────────────
    if (vs > 5.5).any():
        return False, "velocity > 5.5 km/s somewhere"

    return True, "ok"


def build_label(moho: float, v_crust: np.ndarray, v_mantle: np.ndarray) -> str:
    vc = " ".join(f"{v:.4f}" for v in v_crust)
    vm = " ".join(f"{v:.4f}" for v in v_mantle)
    return f"{moho:.3f} {vc} {vm}\n"


def empirical_equation(vs):
	vp = 1.73 * vs
	rho = 1.6612 * vs - 0.4721 * vs**2 + 0.0671 * vs**3 - 0.0043 * vs**4 + 0.000106 * vs**5
	return vp, rho


def run_fastsurf_forward(vs: np.ndarray, depth: np.ndarray,
                         period: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
    """
    Run in-process FAST_SURF forward modelling (Rayleigh-wave).

    Uses the Herrmann FAST_SURF Fortran routine via f2py (fastsurf.fs_ray).
    Physics is identical to CPS — same propagator, same Biswas-1972
    earth-flattening — but runs in-process with no subprocess overhead.

    Group velocity is derived from the validated phase via
    U = c / (1 + (T/c)·dc/dT).
    """
    period = np.asarray(period, dtype=np.float64).reshape(-1)

    # Build thickness from depth grid
    thickness = np.diff(np.r_[0.0, depth]).astype(float)
    thickness = np.where(thickness <= 0.0, 0.001, thickness)  # avoid zero-thickness layers

    # Compute VP and rho from Vs via empirical equations
    vs_arr = vs.astype(float)
    vp, rho = empirical_equation(vs_arr)

    nlay = len(thickness)
    # Append halfspace layer (thk=0) — replicates the CPS 9999 line
    thk_f = np.zeros(nlay + 1, dtype=np.float32)
    thk_f[:nlay] = thickness.astype(np.float32, copy=False)
    vp_f = np.zeros(nlay + 1, dtype=np.float32)
    vp_f[:nlay] = vp.astype(np.float32, copy=False)
    vp_f[nlay] = vp_f[nlay - 1]
    vs_f = np.zeros(nlay + 1, dtype=np.float32)
    vs_f[:nlay] = vs_arr.astype(np.float32, copy=False)
    vs_f[nlay] = vs_f[nlay - 1]
    rho_f = np.zeros(nlay + 1, dtype=np.float32)
    rho_f[:nlay] = rho.astype(np.float32, copy=False)
    rho_f[nlay] = rho_f[nlay - 1]
    qs_f = np.full(nlay + 1, 600.0, dtype=np.float32)

    try:
        cphase, _ugr_ignored, _zh = fastsurf.fs_ray(
            vp_f, vs_f, rho_f, thk_f, qs_f,
            period.astype(np.float32, copy=False),
        )
    except Exception:
        z = np.zeros(period.size, dtype=np.float32)
        return z, z

    cphase = np.asarray(cphase, dtype=np.float64).reshape(-1)
    cphase[~np.isfinite(cphase) | (cphase <= 0.0)] = 0.0

    # Group from validated phase via U = c / (1 + (T/c)·dc/dT)
    ugroup = np.zeros_like(cphase)
    valid = cphase > 0.0
    if valid.sum() >= 3:
        pv = period.astype(np.float64)[valid]
        cv = cphase[valid]
        order = np.argsort(pv)
        dcdT = np.gradient(cv[order], pv[order])
        u_s = cv[order] / (1.0 + (pv[order] / cv[order]) * dcdT)
        u = np.empty_like(cv)
        u[order] = u_s
        ugroup[valid] = u
    ugroup[~np.isfinite(ugroup) | (ugroup <= 0.0)] = 0.0

    return cphase, ugroup


def generate_one_sample(worker_id: int, sample_id: int, cps_path: str | None = None, plot_debug: bool = False) -> Optional[Tuple[np.ndarray, str]]:
    cbs, mbs = load_basis()
    for _ in range(10000):
        moho, v_crust, v_mantle = sample_params()
        depth = np.linspace(0, DEPTH_MAX, SAMPLE_NUM)
        vs, layer_type = bs_eval(cbs, mbs, moho, v_crust, v_mantle, depth)
        valid, _ = is_valid_model(vs, depth, moho)
        if not valid:
            continue
        try:
            phase, group = run_fastsurf_forward(vs, depth, PERIODS)
            disp = np.stack([PERIODS, phase, group], axis=1)[np.newaxis, :, :]
            label = build_label(moho, v_crust, v_mantle)

            if plot_debug and worker_id == 0:
                try:
                    import matplotlib
                    matplotlib.use("Agg")
                    import matplotlib.pyplot as plt
                    fig, ax = plt.subplots(1, 2, figsize=(10, 5))

                    ax[0].plot(vs, depth, "b-", label="Vs")
                    ax[0].set_ylim(DEPTH_MAX, 0)
                    ax[0].set_xlim(2, 6)
                    ax[0].axhline(moho, color="k", ls=":", alpha=0.7)
                    ax[0].legend()
                    ax[0].set_xlabel("Vs (km/s)")
                    ax[0].set_ylabel("Depth (km)")
                    ax[0].set_title("Isotropic Vs")

                    ax[1].plot(disp[0, :, 0], disp[0, :, 1], "b-", label="Rayleigh phase")
                    ax[1].plot(disp[0, :, 0], disp[0, :, 2], "r--", label="Rayleigh group")
                    ax[1].set_xlabel("Period (s)")
                    ax[1].set_ylabel("Velocity (km/s)")
                    ax[1].legend()
                    ax[1].set_title("Rayleigh dispersion")

                    png = ISO_ROOT / "pngfolder" / f"debug_{worker_id}_{sample_id}.png"
                    png.parent.mkdir(parents=True, exist_ok=True)
                    plt.tight_layout()
                    plt.savefig(png, dpi=100)
                    plt.close()
                except Exception:
                    pass

            return disp, label
        except Exception:
            continue
    return None