Tutorial 3 — NSHMP, motions, seven profiles, batch compute#

Full workflow: GMDB authentication, target spectra (NSHMP or a user-defined file), automatic motion selection, seven GQ/H projects from CSV inputs, batch compute, and post-processing plots.

Requires: GMDB credentials; RSSeismic scripting; NumPy and Matplotlib.

Download profile CSVs (place under examples/Tutorial_3/Inputs/):

Default user-defined target spectrum when using --target-source file (repo default path tests/resources/target_spectrum_example.txt; copy beside the tutorial or pass --target-file):

Run from the repository root:

python examples/Tutorial_3/Tutorial_3_e2e.py --username USER --password PASS
   1"""
   2Tutorial 3 — NSHMP → motions → seven GQ/H projects → batch compute → plots.
   3
   4Standalone: ``rsseismic`` + NumPy + Matplotlib only. Run from this folder (``examples/Tutorial_3/``).
   5
   6Workflow: Steps 0–12 (see section headers in this file).
   7
   8  cd examples\\Tutorial_3
   9
  10  python Tutorial_3_e2e.py ^
  11    --username YOUR_GMDB_USER ^
  12    --password YOUR_GMDB_PASS
  13"""
  14
  15from __future__ import annotations
  16
  17import argparse
  18import csv
  19import math
  20import os
  21import re
  22import sqlite3
  23import sys
  24from dataclasses import dataclass, field
  25
  26import matplotlib
  27import matplotlib.pyplot as plt
  28import numpy as np
  29
  30try:
  31    from rsseismic import (
  32        AmplitudeScalingParams,
  33        DatabaseSearchFilters,
  34        DoubleRange,
  35        GroundMotionDatabase,
  36        NshmpAnnualFrequencyOfExceedance,
  37        NshmpHazardModel,
  38        NshmpTargetSpectraModel,
  39        RecordSelectionParams,
  40        RSSeismicApplication,
  41        TargetSpectra,
  42        UnitSystem,
  43        UserDefinedTargetSpectraModel,
  44        logger,
  45    )
  46    from rsseismic._client import DEFAULT_SCRIPTING_PORT
  47    from rsseismic.exceptions import ScriptingError
  48except ImportError as ex:
  49    missing = getattr(ex, "name", str(ex))
  50    print(
  51        "This script needs a current RSSeismicScripting install.\n\n"
  52        f"Import failed: {missing}\n\n"
  53        "From the repo root:\n"
  54        "  python -m pip install --force-reinstall .\n",
  55        file=sys.stderr,
  56    )
  57    raise SystemExit(1) from ex
  58
  59# =============================================================================
  60# STEP 1 — Configuration (paths, NSHMP site, batch settings)
  61# =============================================================================
  62
  63_TUTORIAL_ROOT = os.path.dirname(os.path.abspath(__file__))
  64_EXAMPLES_DIR = os.path.dirname(_TUTORIAL_ROOT)
  65
  66SCRIPTING_PORT = int(os.environ.get("RSSEISMIC_SCRIPTING_PORT", DEFAULT_SCRIPTING_PORT))
  67PROFILE_NAME = "Profile 1"
  68CSV_DIR = os.path.join(_TUTORIAL_ROOT, "Inputs")
  69NUM_PROFILE_CASES = 7
  70OUTPUT_PROJECT_DIR = os.path.join(_TUTORIAL_ROOT, "projects")
  71OUTPUT_PLOT_DIR = os.path.join(_TUTORIAL_ROOT, "plots")
  72MOTION_DIR = os.path.join(_TUTORIAL_ROOT, "Motions")
  73TARGET_SPECTRUM_FILE = os.path.normpath(
  74    os.path.join(_EXAMPLES_DIR, "..", "tests", "resources", "target_spectrum_example.txt")
  75)
  76PROJECT_CASES = [
  77    (f"case_{i:02d}", os.path.join(CSV_DIR, f"profile_{i:02d}.csv"),
  78     os.path.join(OUTPUT_PROJECT_DIR, f"gqh_case_{i:02d}.rsseismicfile"))
  79    for i in range(1, NUM_PROFILE_CASES + 1)
  80]
  81NSHMP_LATITUDE, NSHMP_LONGITUDE = 37.7749, -122.4194
  82NSHMP_HAZARD_MODEL = NshmpHazardModel.CONTERMINOUS_US_2018
  83NSHMP_VS30 = 760
  84NSHMP_AFE = NshmpAnnualFrequencyOfExceedance.AFE_2475
  85NSHMP_TRUNCATE = NSHMP_MAXDIR = None
  86PARALLEL_DEGREE = 2
  87MAX_CONCURRENT_ANALYSES = None
  88COMPUTE_TIMEOUT = 7200
  89CONTINUE_ON_ERROR = True
  90
  91def step(number: int | str, title: str) -> None:
  92    print(f"Step {number} — {title}")
  93
  94
  95def default_target_spectrum_file(examples_dir: str) -> str:
  96    return os.path.normpath(
  97        os.path.join(examples_dir, "..", "tests", "resources", "target_spectrum_example.txt")
  98    )
  99
 100
 101# Motion matching, NSHMP parsing, db3 post-processing (defaults shared by tutorials)
 102
 103DATABASE = GroundMotionDatabase.GMDB
 104TARGET_SOURCE = "nshmp"
 105
 106_NSHMP_HAZARD_MODEL_CHOICES = {model.name: model for model in NshmpHazardModel}
 107_NSHMP_AFE_CHOICES = {afe.name: afe for afe in NshmpAnnualFrequencyOfExceedance}
 108
 109MAGNITUDE_MIN = 6.0
 110MAGNITUDE_MAX = 8.0
 111RRUP_KM_MAX = 50.0
 112NUM_GROUND_MOTIONS = 11
 113SCALING_DAMPING = 0.05
 114SCALING_TOLERANCE_PERCENT = 10.0
 115AMPLITUDE_T1_S = 0.01
 116AMPLITUDE_T2_S = 10.0
 117PREVIEW_SEARCH_MAX_RESULTS = 10
 118
 119MATCH_PLOT_FILENAME = "match_to_target_spectra.png"
 120
 121DB3_FILENAME = "deepsoilout.db3"
 122MOTION_FOLDER_PREFIX = "Motion_"
 123RS_LAYER_INDEX = 1
 124
 125_MATCH_INDIVIDUAL = dict(color="silver", linewidth=0.8, alpha=0.45)
 126_MATCH_TARGET = dict(color="crimson", linewidth=2.0, label="Target spectrum")
 127_MATCH_ENSEMBLE = dict(color="black", linewidth=1.8, label=r"$\mu_{\ln}$ of geometric-mean Sa")
 128
 129_MOTION_UI_CONFLICT_HINT = """
 130Motion library update failed (ObservableCollection / CollectionChanged).
 131
 132Try:
 133  1. ``--launch-rsseismic`` and run before opening the Motion tab.
 134  2. Close Motion Manager / Motion tab, then re-run from Step 6.
 135  3. ``--motions-only`` to validate NSHMP + save without building projects.
 136"""
 137
 138DATABASE_CHOICES = {
 139    "GMDB": GroundMotionDatabase.GMDB,
 140    "ESM": GroundMotionDatabase.ESM,
 141}
 142
 143
 144def database_from_cli_choice(label: str) -> GroundMotionDatabase:
 145    return DATABASE_CHOICES[label.strip().upper()]
 146
 147
 148def _database_label(database: GroundMotionDatabase) -> str:
 149    return "ESM" if database == GroundMotionDatabase.ESM else database.name
 150
 151
 152def _is_motion_ui_collection_conflict(error: BaseException) -> bool:
 153    text = str(error)
 154    return "ObservableCollection" in text or "CollectionChanged" in text
 155
 156
 157# =============================================================================
 158# STEP 2 — Connect to RSSeismic
 159# =============================================================================
 160
 161
 162def connect_app(port: int) -> RSSeismicApplication:
 163    """Open the scripting client and verify the server responds (Step 2)."""
 164    app = RSSeismicApplication(port=port)
 165    app.ping()
 166    return app
 167
 168
 169# =============================================================================
 170# STEPS 3–7 — Motions (NSHMP + automatic selection)
 171# =============================================================================
 172
 173
 174def _motion_directory_registered(directories: list[str], output_directory: str) -> bool:
 175    target = os.path.normcase(os.path.abspath(output_directory))
 176    return any(os.path.normcase(os.path.abspath(path)) == target for path in directories)
 177
 178
 179def prepare_motion_output_directory(app: RSSeismicApplication, output_directory: str) -> str:
 180    output_directory = os.path.normpath(os.path.abspath(output_directory))
 181    os.makedirs(output_directory, exist_ok=True)
 182
 183    model = app.newProject()
 184    try:
 185        directories = model.Motions.listMotionDirectories()
 186        if _motion_directory_registered(directories, output_directory):
 187            print(f"  Motion folder already registered:\n    {output_directory}")
 188            return output_directory
 189
 190        print(f"  Registering motion folder:\n    {output_directory}")
 191        updated = model.Motions.addMotionDirectory(output_directory)
 192        if not _motion_directory_registered(updated, output_directory):
 193            raise RuntimeError(
 194                f"Could not register motion directory: {output_directory}\n"
 195                "Add it manually under RSSeismic Preferences → Motions."
 196            )
 197    finally:
 198        model.close(saveProject=False)
 199
 200    return output_directory
 201
 202
 203def _build_search_filters(
 204    magnitude_min: float,
 205    magnitude_max: float,
 206    rrup_km_max: float,
 207) -> DatabaseSearchFilters:
 208    return DatabaseSearchFilters(
 209        magnitude=DoubleRange(min=magnitude_min, max=magnitude_max),
 210        rrupKm=DoubleRange(max=rrup_km_max),
 211    )
 212
 213
 214@dataclass(frozen=True)
 215class NshmpSiteParameters:
 216    latitude: float
 217    longitude: float
 218    hazard_model: NshmpHazardModel | None = None
 219    vs30: int | None = None
 220    annual_frequency_of_exceedance: NshmpAnnualFrequencyOfExceedance | None = None
 221    truncate: bool | None = None
 222    maxdir: bool | None = None
 223
 224
 225def _parse_nshmp_hazard_model(name: str) -> NshmpHazardModel | None:
 226    key = name.strip().upper()
 227    if not key or key == "DEFAULT":
 228        return None
 229    try:
 230        return _NSHMP_HAZARD_MODEL_CHOICES[key]
 231    except KeyError as ex:
 232        options = ", ".join(sorted(_NSHMP_HAZARD_MODEL_CHOICES))
 233        raise ValueError(f"Unknown NSHMP hazard model '{name}'. Choose: {options}") from ex
 234
 235
 236def _parse_nshmp_afe(name: str) -> NshmpAnnualFrequencyOfExceedance | None:
 237    key = name.strip().upper()
 238    if not key or key == "DEFAULT":
 239        return None
 240    try:
 241        return _NSHMP_AFE_CHOICES[key]
 242    except KeyError as ex:
 243        options = ", ".join(sorted(_NSHMP_AFE_CHOICES))
 244        raise ValueError(f"Unknown NSHMP AFE '{name}'. Choose: {options}") from ex
 245
 246
 247def _build_nshmp_target_spectra_model(params: NshmpSiteParameters) -> NshmpTargetSpectraModel:
 248    return NshmpTargetSpectraModel(
 249        latitude=params.latitude,
 250        longitude=params.longitude,
 251        hazardModel=params.hazard_model,
 252        vs30=params.vs30,
 253        annualFrequencyOfExceedance=params.annual_frequency_of_exceedance,
 254        truncate=params.truncate,
 255        maxdir=params.maxdir,
 256    )
 257
 258
 259def _describe_nshmp_parameters(params: NshmpSiteParameters) -> str:
 260    def _label(value, default_text: str) -> str:
 261        return default_text if value is None else str(value)
 262
 263    return (
 264        f"lat={params.latitude}, lon={params.longitude}, "
 265        f"model={_label(params.hazard_model, 'server default')}, "
 266        f"Vs30={_label(params.vs30, 'server default')}, "
 267        f"AFE={_label(params.annual_frequency_of_exceedance, 'server default')}, "
 268        f"truncate={_label(params.truncate, 'server default')}, "
 269        f"maxdir={_label(params.maxdir, 'server default')}"
 270    )
 271
 272
 273def resolve_target_spectra(
 274    library,
 275    target_source: str,
 276    target_file: str,
 277    *,
 278    nshmp: NshmpSiteParameters,
 279) -> TargetSpectra:
 280    source = target_source.strip().lower()
 281    if source == "file":
 282        path = os.path.normpath(target_file)
 283        if not os.path.isfile(path):
 284            raise FileNotFoundError(f"Target spectrum file not found: {path}")
 285        print(f"  Loading user-defined target from:\n    {path}")
 286        return library.getTargetSpectra(UserDefinedTargetSpectraModel(filePath=path))
 287
 288    if source == "nshmp":
 289        print("  Querying NSHMP Dynamic Hazard Curves...")
 290        print(f"  {_describe_nshmp_parameters(nshmp)}")
 291        return library.getTargetSpectra(_build_nshmp_target_spectra_model(nshmp))
 292
 293    raise ValueError(f"Unknown target source '{target_source}'. Use 'file' or 'nshmp'.")
 294
 295
 296def run_motion_selection_steps(
 297    app: RSSeismicApplication,
 298    *,
 299    motion_dir: str,
 300    database: GroundMotionDatabase,
 301    username: str,
 302    password: str,
 303    target_source: str,
 304    target_file: str,
 305    nshmp: NshmpSiteParameters,
 306    preview_max_results: int | None,
 307    overwrite: bool,
 308    plot_dir: str | None,
 309) -> TargetSpectra | None:
 310    if database == GroundMotionDatabase.CESMD:
 311        raise ValueError("Automatic selection supports GMDB and ESM only.")
 312    if not password.strip():
 313        raise ValueError("Database password is required.")
 314
 315    filters = _build_search_filters(MAGNITUDE_MIN, MAGNITUDE_MAX, RRUP_KM_MAX)
 316    selection = RecordSelectionParams(
 317        nGm=NUM_GROUND_MOTIONS,
 318        damping=SCALING_DAMPING,
 319        tolPercent=SCALING_TOLERANCE_PERCENT,
 320        isScaled=True,
 321    )
 322    amplitude = AmplitudeScalingParams(t1=AMPLITUDE_T1_S, t2=AMPLITUDE_T2_S)
 323    library = app.MotionLibrary
 324
 325    step(3, "Prepare motion output folder")
 326    motion_dir = prepare_motion_output_directory(app, motion_dir)
 327
 328    db_label = _database_label(database)
 329    step(4, f"Database: {db_label}")
 330    library.authenticateDatabase(database=database, username=username, password=password)
 331
 332    print("  Preview database search")
 333    preview = library.searchDatabaseRecords(
 334        database=database,
 335        filters=filters,
 336        maxResults=preview_max_results,
 337    )
 338    print(f"  Records returned: {len(preview)}")
 339    for record in preview[:5]:
 340        print(
 341            f"    {record.id}  M={record.magnitude}  Rrup={record.rrupKm:.1f} km  "
 342            f"sta={record.station}"
 343        )
 344    if len(preview) > 5:
 345        print(f"    ... and {len(preview) - 5} more")
 346
 347    step(
 348        5,
 349        "Target spectra (NSHMP Dynamic Hazard Curves)"
 350        if target_source.strip().lower() == "nshmp"
 351        else "Target spectra",
 352    )
 353    target = resolve_target_spectra(
 354        library, target_source, target_file, nshmp=nshmp,
 355    )
 356    if not target.points:
 357        raise RuntimeError("Target spectra returned no period–Sa points.")
 358    print(f"  {len(target.points)} period–Sa point(s).")
 359
 360    step(6, "Automatic record selection and save")
 361    print(
 362        "  Avoid opening the Motion tab before this step completes "
 363        "(or use --launch-rsseismic)."
 364    )
 365    try:
 366        result = library.matchToTargetSpectraAutomatic(
 367            database=database,
 368            filters=filters,
 369            targetSpectra=target,
 370            outputDirectory=motion_dir,
 371            selection=selection,
 372            amplitude=amplitude,
 373            overwrite=overwrite,
 374        )
 375    except ScriptingError as ex:
 376        if _is_motion_ui_collection_conflict(ex):
 377            print(_MOTION_UI_CONFLICT_HINT, file=sys.stderr)
 378        raise
 379
 380    print(f"  Saved {len(result.savedMotionNames)} motion component(s) under:\n    {motion_dir}")
 381    for name in result.savedMotionNames[:8]:
 382        print(f"    {name}")
 383    if len(result.savedMotionNames) > 8:
 384        print(f"    ... and {len(result.savedMotionNames) - 8} more")
 385
 386    if plot_dir is not None and result.savedMotionNames:
 387        step(7, "Plot target vs scaled geometric-mean spectra")
 388        period_arrays, sa_arrays = collect_geometric_mean_spectra(
 389            library, motion_dir, list(result.savedMotionNames),
 390        )
 391        if period_arrays:
 392            plot_path = os.path.join(os.path.abspath(plot_dir), MATCH_PLOT_FILENAME)
 393            plot_match_to_target_spectra(target, period_arrays, sa_arrays, plot_path)
 394            print(f"  Saved: {plot_path}")
 395        else:
 396            logger.warning("  No pair spectra available for match plot.")
 397
 398    return target
 399
 400
 401_SCALE_FACTOR_SUFFIX = re.compile(r"_SF=[0-9.+\-eE]+$")
 402
 403
 404def _strip_scale_factor_suffix(motion_name: str) -> str:
 405    return _SCALE_FACTOR_SUFFIX.sub("", motion_name)
 406
 407
 408def _shared_prefix_from_motion_name(motion_name: str) -> str | None:
 409    stem = _strip_scale_factor_suffix(motion_name)
 410    split_at = stem.rfind("_")
 411    if split_at <= 0:
 412        return None
 413    return stem[:split_at]
 414
 415
 416def _group_saved_motion_pairs(saved_motion_names: list[str]) -> list[tuple[str, str]]:
 417    buckets: dict[str, list[str]] = {}
 418    for motion_name in saved_motion_names:
 419        prefix = _shared_prefix_from_motion_name(motion_name)
 420        if prefix is None:
 421            continue
 422        buckets.setdefault(prefix, []).append(motion_name)
 423
 424    pairs: list[tuple[str, str]] = []
 425    for prefix, names in buckets.items():
 426        unique_names = sorted(set(names))
 427        if len(unique_names) == 2:
 428            pairs.append((unique_names[0], unique_names[1]))
 429    return pairs
 430
 431
 432def _pick_sa_column(spectral_df) -> str:
 433    for column in ("FrequencyDomain", "GeometricMeanSa", "Duhamel", "Newmark"):
 434        if column in spectral_df.columns:
 435            return column
 436    candidates = [col for col in spectral_df.columns if col != "Period"]
 437    if not candidates:
 438        raise ValueError(f"No spectral acceleration column in {list(spectral_df.columns)}")
 439    return candidates[0]
 440
 441
 442def _geometric_mean_spectrum_from_motion_names(
 443    library,
 444    h1_name: str,
 445    h2_name: str,
 446) -> tuple[np.ndarray, np.ndarray]:
 447    _, spec_h1 = library.getMotion(h1_name).getSpectralData()
 448    _, spec_h2 = library.getMotion(h2_name).getSpectralData()
 449    sa_column = _pick_sa_column(spec_h1)
 450
 451    period_h1 = spec_h1["Period"].values.astype(float)
 452    sa_h1 = spec_h1[sa_column].values.astype(float)
 453    period_h2 = spec_h2["Period"].values.astype(float)
 454    sa_h2 = spec_h2[sa_column].values.astype(float)
 455
 456    mask_h1 = np.isfinite(period_h1) & np.isfinite(sa_h1) & (period_h1 > 0) & (sa_h1 > 0)
 457    mask_h2 = np.isfinite(period_h2) & np.isfinite(sa_h2) & (period_h2 > 0) & (sa_h2 > 0)
 458    period_h1, sa_h1 = period_h1[mask_h1], sa_h1[mask_h1]
 459    period_h2, sa_h2 = period_h2[mask_h2], sa_h2[mask_h2]
 460
 461    order_h2 = np.argsort(period_h2)
 462    period_h2, sa_h2 = period_h2[order_h2], sa_h2[order_h2]
 463    sa_h2_on_h1 = np.interp(period_h1, period_h2, sa_h2, left=np.nan, right=np.nan)
 464    valid = np.isfinite(sa_h2_on_h1)
 465    period = period_h1[valid]
 466    geo_sa = np.sqrt(sa_h1[valid] * sa_h2_on_h1[valid])
 467    return period, geo_sa
 468
 469
 470def collect_geometric_mean_spectra(
 471    library,
 472    output_directory: str,
 473    saved_motion_names: list[str],
 474) -> tuple[list[np.ndarray], list[np.ndarray]]:
 475    periods_list: list[np.ndarray] = []
 476    sa_list: list[np.ndarray] = []
 477
 478    pairs = _group_saved_motion_pairs(saved_motion_names)
 479    if not pairs:
 480        discovered = library.discoverMotionPairsInFolder(output_directory)
 481        pairs = [(pair.motionH1Name, pair.motionH2Name) for pair in discovered.allPairs]
 482
 483    for h1_name, h2_name in pairs:
 484        try:
 485            period, geo_sa = _geometric_mean_spectrum_from_motion_names(
 486                library, h1_name, h2_name,
 487            )
 488        except Exception as ex:
 489            logger.warning("  Skipping pair for plot: %s", ex)
 490            continue
 491        if period.size:
 492            periods_list.append(period)
 493            sa_list.append(geo_sa)
 494
 495    return periods_list, sa_list
 496
 497
 498def _log_mean_spectrum(
 499    period_arrays: list[np.ndarray],
 500    sa_arrays: list[np.ndarray],
 501    common_periods: np.ndarray,
 502) -> np.ndarray:
 503    cx = np.log(common_periods)
 504    matrix = np.full((len(common_periods), len(period_arrays)), np.nan)
 505    for j, (periods, sa_values) in enumerate(zip(period_arrays, sa_arrays)):
 506        order = np.argsort(periods)
 507        xp = np.log(np.clip(periods[order], 1e-300, None))
 508        matrix[:, j] = np.interp(cx, xp, sa_values[order], left=np.nan, right=np.nan)
 509
 510    with np.errstate(divide="ignore", invalid="ignore"):
 511        ln_mean = np.nanmean(np.log(matrix), axis=1)
 512    return np.exp(ln_mean)
 513
 514
 515def plot_match_to_target_spectra(
 516    target: TargetSpectra,
 517    period_arrays: list[np.ndarray],
 518    sa_arrays: list[np.ndarray],
 519    plot_path: str,
 520) -> None:
 521    target_periods = np.array([point.period for point in target.points], dtype=float)
 522    target_sa = np.array([point.sa for point in target.points], dtype=float)
 523    target_mask = (
 524        np.isfinite(target_periods)
 525        & np.isfinite(target_sa)
 526        & (target_periods > 0)
 527        & (target_sa > 0)
 528    )
 529    target_periods = target_periods[target_mask]
 530    target_sa = target_sa[target_mask]
 531
 532    period_grid = np.sort(
 533        np.unique(np.concatenate([target_periods, period_arrays[0][period_arrays[0] > 0]]))
 534    )
 535    ensemble_sa = _log_mean_spectrum(period_arrays, sa_arrays, period_grid)
 536
 537    fig, ax = plt.subplots(figsize=(6, 4.5))
 538    for periods, sa_values in zip(period_arrays, sa_arrays):
 539        ax.semilogx(periods, sa_values, **_MATCH_INDIVIDUAL)
 540    ax.semilogx(period_grid, ensemble_sa, **_MATCH_ENSEMBLE)
 541    ax.semilogx(target_periods, target_sa, **_MATCH_TARGET)
 542    ax.set_xscale("log")
 543    ax.set_yscale("linear")
 544    ax.set_xlabel("Period (s)")
 545    ax.set_ylabel("Spectral acceleration (g)")
 546    ax.legend(frameon=False)
 547    ax.grid(True, which="both", alpha=0.3)
 548    fig.tight_layout()
 549
 550    os.makedirs(os.path.dirname(plot_path) or ".", exist_ok=True)
 551    fig.savefig(plot_path, dpi=150, bbox_inches="tight")
 552    plt.close(fig)
 553
 554
 555# =============================================================================
 556# STEP 8 — Resolve motion names for project build
 557# =============================================================================
 558
 559
 560def _motion_file_in_directory(file_path: str, motion_dir: str) -> bool:
 561    file_abs = os.path.normcase(os.path.abspath(file_path))
 562    dir_abs = os.path.normcase(os.path.abspath(motion_dir))
 563    return file_abs == dir_abs or file_abs.startswith(dir_abs + os.sep)
 564
 565
 566def resolve_motion_names(model, motion_dir: str) -> list[str]:
 567    motion_dir = os.path.normpath(motion_dir)
 568    model.Motions.addMotionDirectory(motion_dir)
 569    model.Motions.refreshMotionsList()
 570
 571    all_motions = model.Motions.listMotions()
 572    target_names = [
 573        motion.name for motion in all_motions
 574        if _motion_file_in_directory(motion.filePath, motion_dir)
 575    ]
 576    if not target_names:
 577        raise RuntimeError(
 578            f"No motions found under {motion_dir}. "
 579            "Run without --skip-motions first, or check the folder."
 580        )
 581    model.Motions.setMotionSelection(target_names, selectOnlyListed=True)
 582    return target_names
 583
 584
 585# =============================================================================
 586# STEPS 11–12 — Read db3 from disk and aggregate plots
 587# =============================================================================
 588
 589
 590def compute_results_root(project_path: str) -> str:
 591    project_path = os.path.normpath(project_path)
 592    project_dir = os.path.dirname(project_path)
 593    stem = os.path.splitext(os.path.basename(project_path))[0]
 594    return os.path.join(project_dir, stem)
 595
 596
 597def iter_deepsoilout_db3(results_root: str):
 598    if not os.path.isdir(results_root):
 599        return
 600
 601    for profile_folder in sorted(os.listdir(results_root)):
 602        profile_dir = os.path.join(results_root, profile_folder)
 603        if not os.path.isdir(profile_dir):
 604            continue
 605        for motion_folder in sorted(os.listdir(profile_dir)):
 606            if not motion_folder.startswith(MOTION_FOLDER_PREFIX):
 607                continue
 608            db3_path = os.path.join(profile_dir, motion_folder, DB3_FILENAME)
 609            if os.path.isfile(db3_path):
 610                motion_label = motion_folder[len(MOTION_FOLDER_PREFIX):]
 611                yield profile_folder, motion_label, db3_path
 612
 613
 614def read_standard_db3(db3_path: str, rs_layer_index: int = RS_LAYER_INDEX) -> tuple[
 615    np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray,
 616]:
 617    rs_column = f"LAYER{rs_layer_index}_RS"
 618    with sqlite3.connect(db3_path) as conn:
 619        rs_rows = conn.execute(
 620            f"SELECT PERIOD, {rs_column} FROM RESPONSE_SPECTRA"
 621        ).fetchall()
 622        profile_rows = conn.execute(
 623            "SELECT DEPTH_LAYER_MID, MAX_STRAIN, PGA_TOTAL FROM PROFILES"
 624        ).fetchall()
 625
 626    periods = np.array([row[0] for row in rs_rows], dtype=float)
 627    rs_values = np.array([row[1] for row in rs_rows], dtype=float)
 628    depths = np.array([row[0] for row in profile_rows], dtype=float)
 629    strains = np.array([row[1] for row in profile_rows], dtype=float)
 630    pga_values = np.array([row[2] for row in profile_rows], dtype=float)
 631    return periods, rs_values, depths, strains, pga_values
 632
 633
 634@dataclass
 635class AggregatedSamples:
 636    rs_periods: list[np.ndarray] = field(default_factory=list)
 637    rs_values: list[np.ndarray] = field(default_factory=list)
 638    strain_depths: list[np.ndarray] = field(default_factory=list)
 639    strain_values: list[np.ndarray] = field(default_factory=list)
 640    pga_depths: list[np.ndarray] = field(default_factory=list)
 641    pga_values: list[np.ndarray] = field(default_factory=list)
 642    rs_units: dict[str, str] = field(default_factory=dict)
 643    depth_units: dict[str, str] = field(default_factory=dict)
 644    pga_units: dict[str, str] = field(default_factory=dict)
 645
 646
 647def collect_results_from_disk(project_paths: list[str]) -> AggregatedSamples:
 648    samples = AggregatedSamples()
 649    samples.rs_units = {"period": "s", "rs": "g"}
 650    samples.depth_units = {"depth": "m"}
 651    samples.pga_units = {"pga": "g"}
 652
 653    for project_path in project_paths:
 654        results_root = compute_results_root(project_path)
 655        for _profile_folder, _motion_label, db3_path in iter_deepsoilout_db3(results_root):
 656            periods, rs_values, depths, strains, pga_values = read_standard_db3(db3_path)
 657            samples.rs_periods.append(periods)
 658            samples.rs_values.append(rs_values)
 659            samples.strain_depths.append(depths)
 660            samples.strain_values.append(strains)
 661            samples.pga_depths.append(depths)
 662            samples.pga_values.append(pga_values)
 663
 664    return samples
 665
 666
 667matplotlib.rcParams.update({
 668    "font.family": "Times New Roman",
 669    "font.size": 12,
 670    "axes.labelsize": 12,
 671    "legend.fontsize": 12,
 672    "xtick.labelsize": 12,
 673    "ytick.labelsize": 12,
 674})
 675_ANALYSIS_INDIVIDUAL = dict(color="silver", linewidth=0.7, alpha=0.65, marker="o", markersize=3)
 676_ANALYSIS_MEAN = dict(color="black", linewidth=1.5, marker="o", markersize=4)
 677_ANALYSIS_BOUND = dict(color="black", linewidth=1.0, linestyle="--", marker="o", markersize=3)
 678
 679
 680def strain_to_percent(strain: np.ndarray) -> np.ndarray:
 681    return strain.astype(float) * 100.0
 682
 683
 684def log_mean_std(
 685    x_arrays: list[np.ndarray],
 686    y_arrays: list[np.ndarray],
 687    common_x: np.ndarray,
 688    *,
 689    log_x: bool = False,
 690    log_y: bool = True,
 691) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
 692    n_pts = len(common_x)
 693    n_samp = len(x_arrays)
 694    matrix = np.full((n_pts, n_samp), np.nan)
 695
 696    cx = np.log(common_x) if log_x else common_x
 697    for j, (x, y) in enumerate(zip(x_arrays, y_arrays)):
 698        order = np.argsort(x)
 699        xs, ys = x[order], y[order]
 700        xj = np.log(np.clip(xs, 1e-300, None)) if log_x else xs
 701        matrix[:, j] = np.interp(cx, xj, ys)
 702
 703    valid = np.isfinite(matrix) & (matrix > 0)
 704    if log_y:
 705        with np.errstate(divide="ignore", invalid="ignore"):
 706            ln_mat = np.where(valid, np.log(matrix), np.nan)
 707            mu = np.nanmean(ln_mat, axis=1)
 708            sigma = np.nanstd(ln_mat, axis=1, ddof=1)
 709        return np.exp(mu), np.exp(mu + sigma), np.exp(mu - sigma)
 710
 711    mu = np.nanmean(matrix, axis=1)
 712    sigma = np.nanstd(matrix, axis=1, ddof=1)
 713    return mu, mu + sigma, mu - sigma
 714
 715
 716def aggregate_by_layer_index(
 717    depth_arrays: list[np.ndarray],
 718    value_arrays: list[np.ndarray],
 719    *,
 720    log_y: bool = True,
 721) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
 722    max_layers = max(len(d) for d in depth_arrays)
 723    mean_depths: list[float] = []
 724    val_means: list[float] = []
 725    val_uppers: list[float] = []
 726    val_lowers: list[float] = []
 727
 728    for layer_idx in range(max_layers):
 729        depths: list[float] = []
 730        values: list[float] = []
 731        for depth_arr, value_arr in zip(depth_arrays, value_arrays):
 732            if layer_idx < len(depth_arr):
 733                depths.append(float(depth_arr[layer_idx]))
 734                values.append(float(value_arr[layer_idx]))
 735        if not values:
 736            continue
 737
 738        values_arr = np.array(values, dtype=float)
 739        if log_y:
 740            positive = values_arr[values_arr > 0]
 741            if positive.size == 0:
 742                continue
 743            ln_vals = np.log(positive)
 744            mu = float(np.mean(ln_vals))
 745            sigma = float(np.std(ln_vals, ddof=1)) if positive.size > 1 else 0.0
 746            val_means.append(math.exp(mu))
 747            val_uppers.append(math.exp(mu + sigma))
 748            val_lowers.append(math.exp(mu - sigma))
 749        else:
 750            mu = float(np.mean(values_arr))
 751            sigma = float(np.std(values_arr, ddof=1)) if values_arr.size > 1 else 0.0
 752            val_means.append(mu)
 753            val_uppers.append(mu + sigma)
 754            val_lowers.append(mu - sigma)
 755        mean_depths.append(float(np.mean(depths)))
 756
 757    return (
 758        np.array(mean_depths),
 759        np.array(val_means),
 760        np.array(val_uppers),
 761        np.array(val_lowers),
 762    )
 763
 764
 765def _sorted_layer_profile(values: np.ndarray, depths: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
 766    order = np.argsort(depths)
 767    return values[order], depths[order]
 768
 769
 770def plot_aggregated(samples: AggregatedSamples, output_dir: str) -> None:
 771    if not samples.rs_periods:
 772        raise RuntimeError(
 773            "No deepsoilout.db3 samples found. Run batch compute first or check project paths."
 774        )
 775
 776    n = len(samples.rs_periods)
 777    step(12, f"Plot aggregates ({n} project × motion sample(s))")
 778
 779    period_unit = samples.rs_units.get("period", "s")
 780    rs_unit = samples.rs_units.get("rs", "g")
 781    depth_unit = samples.depth_units.get("depth", "m")
 782    pga_unit = samples.pga_units.get("pga", "g")
 783
 784    period_grid = np.sort(samples.rs_periods[0][samples.rs_periods[0] > 0])
 785    rs_mean, rs_upper, rs_lower = log_mean_std(
 786        samples.rs_periods, samples.rs_values, period_grid, log_x=True, log_y=True,
 787    )
 788
 789    fig1, ax1 = plt.subplots(figsize=(5, 4.5))
 790    for xp, yp in zip(samples.rs_periods, samples.rs_values):
 791        ax1.semilogx(xp, yp, **_ANALYSIS_INDIVIDUAL)
 792    ax1.semilogx(period_grid, rs_mean, label=r"$\mu_{\ln}$", **_ANALYSIS_MEAN)
 793    ax1.semilogx(period_grid, rs_upper, label=r"$\mu_{\ln} \pm \sigma_{\ln}$", **_ANALYSIS_BOUND)
 794    ax1.semilogx(period_grid, rs_lower, **_ANALYSIS_BOUND)
 795    ax1.set_xscale("log")
 796    ax1.set_yscale("linear")
 797    ax1.set_xlabel(f"Period ({period_unit})")
 798    ax1.set_ylabel(f"Spectral Acceleration ({rs_unit})")
 799    ax1.legend(frameon=False)
 800    ax1.grid(True, which="both", alpha=0.3)
 801    fig1.tight_layout()
 802
 803    strain_pct_samples = [strain_to_percent(v) for v in samples.strain_values]
 804    s_depths, s_mean, s_upper, s_lower = aggregate_by_layer_index(
 805        samples.strain_depths, strain_pct_samples, log_y=True,
 806    )
 807
 808    fig2, ax2 = plt.subplots(figsize=(4, 5.5))
 809    for strain_pct, depths in zip(strain_pct_samples, samples.strain_depths):
 810        xs, ys = _sorted_layer_profile(strain_pct, depths)
 811        ax2.plot(xs, ys, **_ANALYSIS_INDIVIDUAL)
 812    ax2.plot(s_mean, s_depths, label=r"$\mu_{\ln}$", **_ANALYSIS_MEAN)
 813    ax2.plot(s_upper, s_depths, label=r"$\mu_{\ln} \pm \sigma_{\ln}$", **_ANALYSIS_BOUND)
 814    ax2.plot(s_lower, s_depths, **_ANALYSIS_BOUND)
 815    ax2.set_xlabel("Max Shear Strain (%)")
 816    ax2.set_ylabel(f"Depth ({depth_unit})")
 817    ax2.invert_yaxis()
 818    ax2.legend(frameon=False)
 819    ax2.grid(True, which="major", alpha=0.3)
 820    fig2.tight_layout()
 821
 822    p_depths, p_mean, p_upper, p_lower = aggregate_by_layer_index(
 823        samples.pga_depths, samples.pga_values, log_y=True,
 824    )
 825
 826    fig3, ax3 = plt.subplots(figsize=(4, 5.5))
 827    for pga, depths in zip(samples.pga_values, samples.pga_depths):
 828        xs, ys = _sorted_layer_profile(pga, depths)
 829        ax3.plot(xs, ys, **_ANALYSIS_INDIVIDUAL)
 830    ax3.plot(p_mean, p_depths, label=r"$\mu_{\ln}$", **_ANALYSIS_MEAN)
 831    ax3.plot(p_upper, p_depths, label=r"$\mu_{\ln} \pm \sigma_{\ln}$", **_ANALYSIS_BOUND)
 832    ax3.plot(p_lower, p_depths, **_ANALYSIS_BOUND)
 833    ax3.set_xlabel(f"PGA ({pga_unit})")
 834    ax3.set_ylabel(f"Depth ({depth_unit})")
 835    ax3.invert_yaxis()
 836    ax3.legend(frameon=False)
 837    ax3.grid(True, which="major", alpha=0.3)
 838    fig3.tight_layout()
 839
 840    os.makedirs(output_dir, exist_ok=True)
 841    for fig, name in [
 842        (fig1, "response_spectra.png"),
 843        (fig2, "max_strain_profile.png"),
 844        (fig3, "pga_profile.png"),
 845    ]:
 846        path = os.path.join(output_dir, name)
 847        fig.savefig(path, dpi=150, bbox_inches="tight")
 848        print(f"  Saved: {path}")
 849        plt.close(fig)
 850
 851# STEP 9 — Build seven projects from profile CSV
 852# =============================================================================
 853
 854
 855@dataclass
 856class ProfileLayerRow:
 857    thickness_m: float
 858    unit_weight: float
 859    vs_m_s: float
 860    shear_strength_kPa: float
 861    soil_type: str
 862    curve_model: str
 863    reduction_factor_formulation: str
 864    ref_params: dict[str, str] = field(default_factory=dict)
 865
 866
 867def _cell(row: dict[str, str], key: str) -> str:
 868    return row.get(key, "").strip()
 869
 870
 871def _require_float(row: dict[str, str], key: str) -> float:
 872    return float(_cell(row, key))
 873
 874
 875def parse_key_value_params(text: str) -> dict[str, str]:
 876    if not text.strip():
 877        return {}
 878    params: dict[str, str] = {}
 879    for part in text.split(";"):
 880        part = part.strip()
 881        if not part:
 882            continue
 883        key, _, value = part.partition("=")
 884        key, value = key.strip(), value.strip()
 885        if key and value:
 886            params[key] = value
 887    return params
 888
 889
 890def apply_scalar_params(accessor, params: dict[str, str]) -> None:
 891    for key, value in params.items():
 892        accessor.setDoubleProperty(key, float(value))
 893
 894
 895def load_profile_rows(csv_path: str) -> list[ProfileLayerRow]:
 896    csv_path = os.path.normpath(csv_path)
 897    with open(csv_path, newline="", encoding="utf-8-sig") as handle:
 898        data_lines = [
 899            line for line in handle
 900            if line.strip() and not line.lstrip().startswith("#")
 901        ]
 902        reader = csv.DictReader(data_lines)
 903        rows: list[ProfileLayerRow] = []
 904        for raw in reader:
 905            if not any(_cell(raw, key) for key in raw):
 906                continue
 907            rows.append(ProfileLayerRow(
 908                thickness_m=_require_float(raw, "thickness_m"),
 909                unit_weight=_require_float(raw, "unit_weight"),
 910                vs_m_s=_require_float(raw, "vs_m_s"),
 911                shear_strength_kPa=_require_float(raw, "shear_strength_kPa"),
 912                soil_type=_cell(raw, "soil_type"),
 913                curve_model=_cell(raw, "curve_model"),
 914                reduction_factor_formulation=_cell(raw, "reduction_factor_formulation"),
 915                ref_params=parse_key_value_params(_cell(raw, "ref_params")),
 916            ))
 917    return rows
 918
 919
 920def mrdf_fitting_procedure(formulation: str) -> str | None:
 921    if formulation == "None":
 922        return None
 923    if formulation == "MRDF_Darendeli":
 924        return "MRDF_Derendeli"
 925    return "MRDF_UIUC"
 926
 927
 928def configure_project_settings(model) -> None:
 929    model.ProjectSettings.changeUnitSystem(UnitSystem.Metric)
 930    model.ProjectSettings.Data.setBoolValue("automaticProfileGeneration", False)
 931    model.ProjectSettings.Data.setEnumValue("analysisMode", "Nonlinear")
 932    model.ProjectSettings.Data.setEnumValue("defaultSoilModel", "GQ_H")
 933    model.ProjectSettings.Data.setEnumValue("hystereticFormulation", "NonMasing")
 934
 935
 936def build_profile_from_csv(model, csv_path: str, profile_name: str = PROFILE_NAME) -> None:
 937    rows = load_profile_rows(csv_path)
 938    model.Profiles.setActiveProfile(profile_name)
 939
 940    existing = model.Profiles.listActiveSoilLayers()
 941    need = len(rows) - len(existing)
 942    if need > 0:
 943        model.SoilLayers.appendLayers(need)
 944
 945    for summary, spec in zip(model.Profiles.listActiveSoilLayers(), rows):
 946        layer = model.Profiles.getSoilLayer(summary.layerID)
 947        layer.setSoilModel("GQ_H")
 948        layer.setThickness(spec.thickness_m)
 949        layer.setUnitWeight(spec.unit_weight)
 950        layer.Data.setDoubleProperty("ShearWaveVelocity", spec.vs_m_s)
 951        layer.Data.setDoubleProperty("ShearStrength", spec.shear_strength_kPa)
 952
 953        ref = layer.ReferenceCurve
 954        ref.setSoilType(spec.soil_type)
 955        ref.setCurveModel(spec.curve_model)
 956        apply_scalar_params(ref.Data, spec.ref_params)
 957        ref.generateReferenceCurve()
 958
 959        fit_proc = mrdf_fitting_procedure(spec.reduction_factor_formulation)
 960        if fit_proc is not None:
 961            layer.Curve.runCurveFit(fit_proc)
 962
 963
 964def build_all_projects(
 965    app: RSSeismicApplication,
 966    motion_names: list[str],
 967    motion_dir: str,
 968) -> list[str]:
 969    os.makedirs(OUTPUT_PROJECT_DIR, exist_ok=True)
 970    project_paths: list[str] = []
 971
 972    for case_id, csv_path, project_path in PROJECT_CASES:
 973        if not os.path.isfile(csv_path):
 974            raise FileNotFoundError(f"Missing profile CSV for {case_id}: {csv_path}")
 975
 976        print(f"  Building {case_id} → {os.path.basename(project_path)}")
 977        model = app.newProject()
 978        configure_project_settings(model)
 979        build_profile_from_csv(model, csv_path)
 980        resolve_motion_names(model, motion_dir)
 981        model.Motions.setMotionSelection(motion_names, selectOnlyListed=True)
 982        model.saveAs(project_path)
 983        model.close(saveProject=False)
 984        project_paths.append(os.path.normpath(project_path))
 985
 986    return project_paths
 987
 988
 989def default_project_paths() -> list[str]:
 990    return [os.path.normpath(project_path) for _, _, project_path in PROJECT_CASES]
 991
 992
 993# =============================================================================
 994# STEP 10 — Batch compute
 995# =============================================================================
 996
 997
 998def run_batch_compute(
 999    app: RSSeismicApplication,
1000    project_paths: list[str],
1001    motion_names: list[str],
1002) -> None:
1003    batch_result = app.runBatchCompute(
1004        project_paths,
1005        motion_names=motion_names,
1006        parallel_degree=PARALLEL_DEGREE,
1007        max_concurrent_analyses=MAX_CONCURRENT_ANALYSES,
1008        timeout=COMPUTE_TIMEOUT,
1009        close_save_project=False,
1010        continue_on_error=CONTINUE_ON_ERROR,
1011    )
1012
1013    ok = sum(1 for job in batch_result.results if job.success and not job.partial_success)
1014    partial = sum(1 for job in batch_result.results if job.success and job.partial_success)
1015    failed = sum(1 for job in batch_result.results if not job.success)
1016    print()
1017    print("=" * 70)
1018    print(f"  Batch complete — {len(batch_result.results)} project(s)")
1019    print(f"  Full success : {ok}   Partial : {partial}   Failed : {failed}")
1020    print("=" * 70)
1021    for job in batch_result.results:
1022        name = os.path.basename(job.file_path)
1023        status = "OK" if job.success and not job.partial_success else (
1024            "PARTIAL" if job.success else "FAILED"
1025        )
1026        print(f"  [{status:7s}]  {name}")
1027        if job.error_message:
1028            print(f"             {job.error_message}")
1029    print()
1030
1031def parse_args() -> argparse.Namespace:
1032    """Define command-line flags for partial runs and NSHMP/motion options."""
1033    parser = argparse.ArgumentParser(
1034        description="Tutorial 3: NSHMP target spectra to motions to batch GQ/H analysis.",
1035    )
1036    parser.add_argument("--port", "-p", type=int, default=SCRIPTING_PORT)
1037    parser.add_argument("--username", help="GMDB/ESM username (required unless --results-only).")
1038    parser.add_argument("--password", help="GMDB/ESM password.")
1039    parser.add_argument(
1040        "--database",
1041        "-d",
1042        default=_database_label(DATABASE),
1043        choices=sorted(DATABASE_CHOICES.keys()),
1044    )
1045    parser.add_argument("--target-source", choices=("file", "nshmp"), default=TARGET_SOURCE)
1046    parser.add_argument("--target-file", default=TARGET_SPECTRUM_FILE)
1047    parser.add_argument("--latitude", type=float, default=NSHMP_LATITUDE)
1048    parser.add_argument("--longitude", type=float, default=NSHMP_LONGITUDE)
1049    parser.add_argument(
1050        "--nshmp-model",
1051        default=NSHMP_HAZARD_MODEL.name if NSHMP_HAZARD_MODEL is not None else "DEFAULT",
1052    )
1053    parser.add_argument("--nshmp-vs30", type=int, default=NSHMP_VS30 if NSHMP_VS30 is not None else 0)
1054    parser.add_argument(
1055        "--nshmp-afe",
1056        default=NSHMP_AFE.name if NSHMP_AFE is not None else "DEFAULT",
1057    )
1058    parser.add_argument("--nshmp-truncate", action="store_true")
1059    parser.add_argument("--nshmp-maxdir", action="store_true")
1060    parser.add_argument("--preview-max-results", type=int, default=PREVIEW_SEARCH_MAX_RESULTS)
1061    parser.add_argument("--overwrite", action="store_true")
1062    parser.add_argument("--motion-dir", default=MOTION_DIR)
1063    parser.add_argument("--plot-dir", default=OUTPUT_PLOT_DIR)
1064    parser.add_argument("--no-match-plot", action="store_true")
1065    parser.add_argument("--launch-rsseismic", action="store_true")
1066    parser.add_argument("--rsseismic-exe", default="")
1067    parser.add_argument("--skip-motions", action="store_true", help="Skip Steps 3–7.")
1068    parser.add_argument("--motions-only", action="store_true", help="Run Steps 3–7 only.")
1069    parser.add_argument("--results-only", action="store_true", help="Steps 11–12 only.")
1070    parser.add_argument("--skip-compute", action="store_true", help="Build projects; skip Step 10.")
1071    return parser.parse_args()
1072
1073
1074def nshmp_params_from_args(args: argparse.Namespace) -> NshmpSiteParameters:
1075    """Map CLI NSHMP flags to ``NshmpSiteParameters`` for Step 5."""
1076    return NshmpSiteParameters(
1077        latitude=args.latitude,
1078        longitude=args.longitude,
1079        hazard_model=_parse_nshmp_hazard_model(args.nshmp_model),
1080        vs30=args.nshmp_vs30 if args.nshmp_vs30 > 0 else None,
1081        annual_frequency_of_exceedance=_parse_nshmp_afe(args.nshmp_afe),
1082        truncate=True if args.nshmp_truncate else NSHMP_TRUNCATE,
1083        maxdir=True if args.nshmp_maxdir else NSHMP_MAXDIR,
1084    )
1085
1086
1087def main() -> int:
1088    """Run Tutorial 3 end-to-end (or a subset via CLI flags)."""
1089    args = parse_args()
1090
1091    if args.results_only:
1092        try:
1093            step(11, "Read deepsoilout.db3 from disk")
1094            samples = collect_results_from_disk(default_project_paths())
1095            plot_aggregated(samples, OUTPUT_PLOT_DIR)
1096        except Exception as ex:
1097            print(f"Results post-processing failed: {ex}", file=sys.stderr)
1098            return 1
1099        print("\nTutorial 3 post-processing finished.")
1100        return 0
1101
1102    if not args.username or not args.password:
1103        print("--username and --password are required (unless --results-only).", file=sys.stderr)
1104        return 1
1105
1106    preview_cap: int | None = args.preview_max_results
1107    if preview_cap is not None and preview_cap <= 0:
1108        preview_cap = None
1109
1110    nshmp_params = nshmp_params_from_args(args)
1111    motion_dir = os.path.normpath(os.path.abspath(args.motion_dir))
1112    plot_dir = None if args.no_match_plot else args.plot_dir
1113    database = database_from_cli_choice(args.database)
1114
1115    try:
1116        if args.launch_rsseismic:
1117            print("Launching RSSeismic...")
1118            launch_kwargs: dict = {"port": args.port}
1119            if args.rsseismic_exe.strip():
1120                launch_kwargs["overridePathToExecutable"] = args.rsseismic_exe.strip()
1121            RSSeismicApplication.startApplication(**launch_kwargs)
1122
1123        step(2, "Connect to RSSeismic scripting server")
1124        app = connect_app(args.port)
1125
1126        if not args.skip_motions:
1127            run_motion_selection_steps(
1128                app,
1129                motion_dir=motion_dir,
1130                database=database,
1131                username=args.username,
1132                password=args.password,
1133                target_source=args.target_source,
1134                target_file=args.target_file,
1135                nshmp=nshmp_params,
1136                preview_max_results=preview_cap,
1137                overwrite=args.overwrite,
1138                plot_dir=plot_dir,
1139            )
1140        else:
1141            print("Steps 3–7 — Skipped (--skip-motions)")
1142
1143        if args.motions_only:
1144            app.close()
1145            print("\nTutorial 3 motions-only run finished.")
1146            return 0
1147
1148        step(8, "Resolve motion names")
1149        probe = app.newProject()
1150        motion_names = resolve_motion_names(probe, motion_dir)
1151        probe.close(saveProject=False)
1152        print(f"  Selected {len(motion_names)} motion(s) from tutorial folder.")
1153
1154        step(9, "Build seven projects from CSV")
1155        project_paths = build_all_projects(app, motion_names, motion_dir)
1156
1157        if args.skip_compute:
1158            app.close()
1159            print("\nTutorial 3 finished (projects built; compute skipped).")
1160            return 0
1161
1162        step(10, "Batch compute")
1163        run_batch_compute(app, project_paths, motion_names)
1164        app.close()
1165
1166        step(11, "Read deepsoilout.db3 from disk")
1167        samples = collect_results_from_disk(project_paths)
1168        plot_aggregated(samples, OUTPUT_PLOT_DIR)
1169
1170    except Exception as ex:
1171        print(f"Tutorial 3 failed: {ex}", file=sys.stderr)
1172        if _is_motion_ui_collection_conflict(ex):
1173            print(_MOTION_UI_CONFLICT_HINT, file=sys.stderr)
1174        return 1
1175
1176    print("\nTutorial 3 end-to-end run finished.")
1177    return 0
1178
1179
1180if __name__ == "__main__":
1181    raise SystemExit(main())