File size: 6,831 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
"""
Parallel synthetic isotropic dispersion dataset generator.
Generates random B-spline isotropic Vs models, validates them, runs CPS forward,
and saves Rayleigh phase + group dispersion to final_data/.
"""
from __future__ import annotations

import argparse
import os
import sys
import time
import traceback
from concurrent.futures import ProcessPoolExecutor, as_completed
from pathlib import Path

import numpy as np

ISO_ROOT = Path(__file__).resolve().parent
os.chdir(ISO_ROOT)
sys.path.insert(0, str(ISO_ROOT))
from synthetic_iso_generator import generate_one_sample, CPS_PARENT, PLOT_DEBUG, PERIODS

FINAL_DATA = ISO_ROOT / "final_data"
FEATURE_FILE = FINAL_DATA / "pretrain_features.npz"
LABEL_FILE = FINAL_DATA / "pretrain_labels.txt"
FEATURE_CHECKPOINT = FINAL_DATA / "pretrain_features_checkpoint.npz"
LABEL_CHECKPOINT = FINAL_DATA / "pretrain_labels_checkpoint.txt"
ERROR_FILE = FINAL_DATA / "synthetic_iso_errors.npy"
FEATURE_MEMMAP = FINAL_DATA / "CSEM2.0_pretrain_features_memmap.dat"

DISP_SHAPE = (len(PERIODS), 3)
MAX_WORKERS = 96
CHECKPOINT_EVERY_N_WORKERS = 10
CHECKPOINT_EVERY_SECONDS = 3600
DEFAULT_N_SAMPLES = 50000


def _log(msg: str) -> None:
    print(msg, flush=True)


def worker_generate_samples(args: tuple[int, int, str, bool]):
    worker_id, n_per_worker, cps_path, plot_debug = args
    seed = (int(time.time_ns() % (2**32)) ^ (os.getpid() << 16) ^ worker_id) & 0xFFFFFFFF
    np.random.seed(seed)
    results = []
    for i in range(n_per_worker):
        out = generate_one_sample(worker_id, i, cps_path, plot_debug)
        if out is not None:
            results.append(out)
    return worker_id, results


def _save_checkpoint_streaming(
    features_memmap: np.memmap,
    sample_idx: int,
    label_path: Path,
    feature_checkpoint: Path,
    label_checkpoint: Path,
) -> None:
    if sample_idx <= 0:
        return
    try:
        np.savez(feature_checkpoint, data=features_memmap[:sample_idx])
        if label_path.exists():
            import shutil
            shutil.copy2(label_path, label_checkpoint)
    except Exception as e:
        _log(f"Checkpoint save failed: {e}")


def main():
    parser = argparse.ArgumentParser(description="Generate synthetic isotropic dispersion datasets")
    parser.add_argument("--n", type=int, default=DEFAULT_N_SAMPLES)
    parser.add_argument("--cores", type=int, default=MAX_WORKERS)
    parser.add_argument("--plot-debug", action="store_true")
    parser.add_argument("--cps-path", type=str, default=CPS_PARENT)
    parser.add_argument(
        "--output-dir",
        type=Path,
        default=FINAL_DATA,
        help="Directory for the generated feature, label, checkpoint, and error files",
    )
    parser.add_argument("--dry-run", action="store_true")
    args = parser.parse_args()

    output_dir = args.output_dir.expanduser().resolve()
    feature_file = output_dir / FEATURE_FILE.name
    label_file = output_dir / LABEL_FILE.name
    feature_checkpoint = output_dir / FEATURE_CHECKPOINT.name
    label_checkpoint = output_dir / LABEL_CHECKPOINT.name
    error_file = output_dir / ERROR_FILE.name
    feature_memmap_file = output_dir / FEATURE_MEMMAP.name
    output_dir.mkdir(parents=True, exist_ok=True)
    n_total = args.n
    n_workers = min(args.cores, n_total)
    n_per_worker = (n_total + n_workers - 1) // n_workers

    _log(f"Generating {n_total} synthetic samples using {n_workers} workers")
    _log(f"Output: {output_dir}")
    _log(f"CPS path: {args.cps_path}")

    worker_args = [(w, n_per_worker, args.cps_path, args.plot_debug or PLOT_DEBUG) for w in range(n_workers)]
    # args.dry_run = True
    if args.dry_run:
        for worker_id, n_per_worker, cps_path, plot_debug in worker_args:
            worker_generate_samples((worker_id, n_per_worker, cps_path, plot_debug))
        _log("Dry run finished (no files written).")
        return 0

    n_periods, n_cols = DISP_SHAPE
    features_memmap = np.memmap(str(feature_memmap_file), dtype=np.float64, mode="w+", shape=(n_total, n_periods, n_cols))
    sample_idx = 0
    last_checkpoint_time = time.time()
    workers_done_since_checkpoint = 0
    errors = []

    with open(label_file, "w") as label_f:
        t0 = time.time()
        with ProcessPoolExecutor(max_workers=n_workers) as exe:
            futures = {exe.submit(worker_generate_samples, a): a[0] for a in worker_args}
            for fut in as_completed(futures):
                wid = futures[fut]
                try:
                    _, samples = fut.result()
                    for disp, label in samples:
                        if sample_idx >= n_total:
                            break
                        features_memmap[sample_idx] = np.asarray(disp).reshape(DISP_SHAPE)
                        label_f.write(label)
                        label_f.flush()
                        sample_idx += 1
                    workers_done_since_checkpoint += 1
                    _log(f"Worker {wid}: +{len(samples)} samples (total {sample_idx})")
                except Exception as e:
                    errors.append({"worker": wid, "error": repr(e), "tb": traceback.format_exc()})
                    _log(f"Worker {wid} failed: {e}")
                now = time.time()
                if sample_idx > 0 and (workers_done_since_checkpoint >= CHECKPOINT_EVERY_N_WORKERS or (now - last_checkpoint_time) >= CHECKPOINT_EVERY_SECONDS):
                    _save_checkpoint_streaming(
                        features_memmap,
                        sample_idx,
                        label_file,
                        feature_checkpoint,
                        label_checkpoint,
                    )
                    workers_done_since_checkpoint = 0
                    last_checkpoint_time = now
                    _log(f"  [checkpoint] {sample_idx} samples -> {FEATURE_CHECKPOINT.name}")

    elapsed = time.time() - t0
    if sample_idx == 0:
        _log("No valid samples generated.")
        if errors:
            np.save(error_file, np.array(errors, dtype=object))
        return 1

    np.savez(feature_file, data=features_memmap[:sample_idx])
    del features_memmap
    if feature_memmap_file.exists():
        try:
            feature_memmap_file.unlink()
        except OSError:
            pass
    for p in (feature_checkpoint, label_checkpoint):
        if p.exists():
            try:
                p.unlink()
            except OSError:
                pass
    _log(f"Saved {sample_idx} samples in {elapsed:.1f} s")
    if errors:
        np.save(error_file, np.array(errors, dtype=object))
    return 0


if __name__ == "__main__":
    try:
        sys.exit(main())
    except Exception as e:
        print(traceback.format_exc(), file=sys.stderr, flush=True)
        print(f"Fatal error: {e}", file=sys.stderr, flush=True)
        sys.exit(1)