Tutorial 4 — NSHMP motions and FEM auto-profile project#

Motion selection (GMDB / NSHMP or user-defined spectrum), FEM project setup, optional automatic profile generation from a template project, compute, and result plots.

Requires: GMDB credentials for the motion-selection steps; NumPy and Matplotlib.

Download inputs (place under examples/Tutorial_4/Inputs/):

User-defined target spectrum (--target-source file; default path tests/resources/target_spectrum_example.txt):

For --randomize, provide an auto-profile template — see examples/Tutorial_4/template/README.md or tests/resources/Test_Auto_Profile.rsseismicfile.

Run from the repository root:

python examples/Tutorial_4/Tutorial_4_e2e.py --username USER --password PASS
   1"""
   2Tutorial 4 — NSHMP motions → FEM project → compute → plots (standalone script).
   3
   4Workflow: Steps 2–8 motions, Step 9 FEM build, Step 10 compute, Steps 11–12 plots.
   5See section headers below. ``--randomize`` needs ``Tutorial_4/template/README.md``.
   6
   7  cd examples\\Tutorial_4
   8
   9  python Tutorial_4_e2e.py ^
  10    --username YOUR_GMDB_USER ^
  11    --password YOUR_GMDB_PASS
  12"""
  13
  14from __future__ import annotations
  15
  16import argparse
  17import csv
  18import math
  19import os
  20import re
  21import sqlite3
  22import sys
  23from dataclasses import dataclass, field
  24
  25import matplotlib
  26import matplotlib.pyplot as plt
  27import numpy as np
  28
  29try:
  30    from rsseismic import (
  31        AmplitudeScalingParams,
  32        DatabaseSearchFilters,
  33        DoubleRange,
  34        GroundMotionDatabase,
  35        NshmpAnnualFrequencyOfExceedance,
  36        NshmpHazardModel,
  37        NshmpTargetSpectraModel,
  38        RecordSelectionParams,
  39        RSSeismicApplication,
  40        TargetSpectra,
  41        UnitSystem,
  42        UserDefinedTargetSpectraModel,
  43        logger,
  44    )
  45    from rsseismic._client import DEFAULT_SCRIPTING_PORT
  46    from rsseismic.exceptions import ScriptingError
  47except ImportError as ex:
  48    missing = getattr(ex, "name", str(ex))
  49    print(
  50        "This script needs a current RSSeismicScripting install.\n\n"
  51        f"Import failed: {missing}\n\n"
  52        "From the repo root:\n"
  53        "  python -m pip install --force-reinstall .\n",
  54        file=sys.stderr,
  55    )
  56    raise SystemExit(1) from ex
  57
  58# =============================================================================
  59# STEP 1 — Configuration
  60# =============================================================================
  61
  62_TUTORIAL_ROOT = os.path.dirname(os.path.abspath(__file__))
  63_EXAMPLES_DIR = os.path.dirname(_TUTORIAL_ROOT)
  64_INPUT_DIR = os.path.join(_TUTORIAL_ROOT, "Inputs")
  65
  66MEAN_PROFILE_CSV = os.path.join(_INPUT_DIR, "mean_profile_layers.csv")
  67PROFILE_GEN_SETTINGS_CSV = os.path.join(_INPUT_DIR, "profile_generation_settings.csv")
  68MOTION_DIR = os.path.join(_TUTORIAL_ROOT, "Motions")
  69OUTPUT_PROJECT_DIR = os.path.join(_TUTORIAL_ROOT, "projects")
  70OUTPUT_PLOT_DIR = os.path.join(_TUTORIAL_ROOT, "plots")
  71PROJECT_PATH = os.path.join(OUTPUT_PROJECT_DIR, "tutorial_4_fem.rsseismicfile")
  72DEFAULT_TEMPLATE_PATH = os.path.join(
  73    _TUTORIAL_ROOT, "template", "tutorial_4_auto_profile.rsseismicfile",
  74)
  75SCRIPTING_PORT = int(os.environ.get("RSSEISMIC_SCRIPTING_PORT", DEFAULT_SCRIPTING_PORT))
  76NSHMP_LATITUDE, NSHMP_LONGITUDE = 33.953, -118.339
  77NSHMP_HAZARD_MODEL = NshmpHazardModel.CONTERMINOUS_US_2018
  78NSHMP_VS30 = 760
  79NSHMP_AFE = NshmpAnnualFrequencyOfExceedance.AFE_2475
  80NSHMP_TRUNCATE = NSHMP_MAXDIR = None
  81TARGET_SPECTRUM_FILE = os.path.normpath(
  82    os.path.join(_EXAMPLES_DIR, "..", "tests", "resources", "target_spectrum_example.txt")
  83)
  84COMPUTE_TIMEOUT = float(os.environ.get("RSSEISMIC_COMPUTE_TIMEOUT_SECONDS", "7200"))
  85GENERATE_PROFILES_TIMEOUT = float(
  86    os.environ.get("RSSEISMIC_GENERATE_PROFILES_TIMEOUT_SECONDS", "3600")
  87)
  88_FEM_DOUBLE_PROPERTIES: tuple[tuple[str, str], ...] = (
  89    ("poissons_ratio", "PoissonRatio"),
  90    ("a0_fem", "a0_FEM"),
  91    ("a1_fem", "a1_FEM"),
  92    ("a2_fem", "a2_FEM"),
  93    ("b_exp", "b_exp"),
  94    ("A0_volumetric", "A0_VolumetricResponse"),
  95    ("eta_dsr", "Eta_dsr"),
  96    ("permeability_fem", "Permeability_FEM"),
  97    ("porosity_fem", "Porosity_FEM"),
  98)
  99
 100def step(number: int | str, title: str) -> None:
 101    print(f"Step {number} — {title}")
 102
 103
 104def default_target_spectrum_file(examples_dir: str) -> str:
 105    return os.path.normpath(
 106        os.path.join(examples_dir, "..", "tests", "resources", "target_spectrum_example.txt")
 107    )
 108
 109
 110# Motion matching, NSHMP parsing, db3 post-processing (defaults shared by tutorials)
 111
 112DATABASE = GroundMotionDatabase.GMDB
 113TARGET_SOURCE = "nshmp"
 114
 115_NSHMP_HAZARD_MODEL_CHOICES = {model.name: model for model in NshmpHazardModel}
 116_NSHMP_AFE_CHOICES = {afe.name: afe for afe in NshmpAnnualFrequencyOfExceedance}
 117
 118MAGNITUDE_MIN = 6.0
 119MAGNITUDE_MAX = 8.0
 120RRUP_KM_MAX = 50.0
 121NUM_GROUND_MOTIONS = 11
 122SCALING_DAMPING = 0.05
 123SCALING_TOLERANCE_PERCENT = 10.0
 124AMPLITUDE_T1_S = 0.01
 125AMPLITUDE_T2_S = 10.0
 126PREVIEW_SEARCH_MAX_RESULTS = 10
 127
 128MATCH_PLOT_FILENAME = "match_to_target_spectra.png"
 129
 130DB3_FILENAME = "deepsoilout.db3"
 131MOTION_FOLDER_PREFIX = "Motion_"
 132RS_LAYER_INDEX = 1
 133
 134_MATCH_INDIVIDUAL = dict(color="silver", linewidth=0.8, alpha=0.45)
 135_MATCH_TARGET = dict(color="crimson", linewidth=2.0, label="Target spectrum")
 136_MATCH_ENSEMBLE = dict(color="black", linewidth=1.8, label=r"$\mu_{\ln}$ of geometric-mean Sa")
 137
 138_MOTION_UI_CONFLICT_HINT = """
 139Motion library update failed (ObservableCollection / CollectionChanged).
 140
 141Try:
 142  1. ``--launch-rsseismic`` and run before opening the Motion tab.
 143  2. Close Motion Manager / Motion tab, then re-run from Step 6.
 144  3. ``--motions-only`` to validate NSHMP + save without building projects.
 145"""
 146
 147DATABASE_CHOICES = {
 148    "GMDB": GroundMotionDatabase.GMDB,
 149    "ESM": GroundMotionDatabase.ESM,
 150}
 151
 152
 153def database_from_cli_choice(label: str) -> GroundMotionDatabase:
 154    return DATABASE_CHOICES[label.strip().upper()]
 155
 156
 157def _database_label(database: GroundMotionDatabase) -> str:
 158    return "ESM" if database == GroundMotionDatabase.ESM else database.name
 159
 160
 161def _is_motion_ui_collection_conflict(error: BaseException) -> bool:
 162    text = str(error)
 163    return "ObservableCollection" in text or "CollectionChanged" in text
 164
 165
 166# =============================================================================
 167# STEP 2 — Connect to RSSeismic
 168# =============================================================================
 169
 170
 171def connect_app(port: int) -> RSSeismicApplication:
 172    """Open the scripting client and verify the server responds (Step 2)."""
 173    app = RSSeismicApplication(port=port)
 174    app.ping()
 175    return app
 176
 177
 178# =============================================================================
 179# STEPS 3–7 — Motions (NSHMP + automatic selection)
 180# =============================================================================
 181
 182
 183def _motion_directory_registered(directories: list[str], output_directory: str) -> bool:
 184    target = os.path.normcase(os.path.abspath(output_directory))
 185    return any(os.path.normcase(os.path.abspath(path)) == target for path in directories)
 186
 187
 188def prepare_motion_output_directory(app: RSSeismicApplication, output_directory: str) -> str:
 189    output_directory = os.path.normpath(os.path.abspath(output_directory))
 190    os.makedirs(output_directory, exist_ok=True)
 191
 192    model = app.newProject()
 193    try:
 194        directories = model.Motions.listMotionDirectories()
 195        if _motion_directory_registered(directories, output_directory):
 196            print(f"  Motion folder already registered:\n    {output_directory}")
 197            return output_directory
 198
 199        print(f"  Registering motion folder:\n    {output_directory}")
 200        updated = model.Motions.addMotionDirectory(output_directory)
 201        if not _motion_directory_registered(updated, output_directory):
 202            raise RuntimeError(
 203                f"Could not register motion directory: {output_directory}\n"
 204                "Add it manually under RSSeismic Preferences → Motions."
 205            )
 206    finally:
 207        model.close(saveProject=False)
 208
 209    return output_directory
 210
 211
 212def _build_search_filters(
 213    magnitude_min: float,
 214    magnitude_max: float,
 215    rrup_km_max: float,
 216) -> DatabaseSearchFilters:
 217    return DatabaseSearchFilters(
 218        magnitude=DoubleRange(min=magnitude_min, max=magnitude_max),
 219        rrupKm=DoubleRange(max=rrup_km_max),
 220    )
 221
 222
 223@dataclass(frozen=True)
 224class NshmpSiteParameters:
 225    latitude: float
 226    longitude: float
 227    hazard_model: NshmpHazardModel | None = None
 228    vs30: int | None = None
 229    annual_frequency_of_exceedance: NshmpAnnualFrequencyOfExceedance | None = None
 230    truncate: bool | None = None
 231    maxdir: bool | None = None
 232
 233
 234def _parse_nshmp_hazard_model(name: str) -> NshmpHazardModel | None:
 235    key = name.strip().upper()
 236    if not key or key == "DEFAULT":
 237        return None
 238    try:
 239        return _NSHMP_HAZARD_MODEL_CHOICES[key]
 240    except KeyError as ex:
 241        options = ", ".join(sorted(_NSHMP_HAZARD_MODEL_CHOICES))
 242        raise ValueError(f"Unknown NSHMP hazard model '{name}'. Choose: {options}") from ex
 243
 244
 245def _parse_nshmp_afe(name: str) -> NshmpAnnualFrequencyOfExceedance | None:
 246    key = name.strip().upper()
 247    if not key or key == "DEFAULT":
 248        return None
 249    try:
 250        return _NSHMP_AFE_CHOICES[key]
 251    except KeyError as ex:
 252        options = ", ".join(sorted(_NSHMP_AFE_CHOICES))
 253        raise ValueError(f"Unknown NSHMP AFE '{name}'. Choose: {options}") from ex
 254
 255
 256def _build_nshmp_target_spectra_model(params: NshmpSiteParameters) -> NshmpTargetSpectraModel:
 257    return NshmpTargetSpectraModel(
 258        latitude=params.latitude,
 259        longitude=params.longitude,
 260        hazardModel=params.hazard_model,
 261        vs30=params.vs30,
 262        annualFrequencyOfExceedance=params.annual_frequency_of_exceedance,
 263        truncate=params.truncate,
 264        maxdir=params.maxdir,
 265    )
 266
 267
 268def _describe_nshmp_parameters(params: NshmpSiteParameters) -> str:
 269    def _label(value, default_text: str) -> str:
 270        return default_text if value is None else str(value)
 271
 272    return (
 273        f"lat={params.latitude}, lon={params.longitude}, "
 274        f"model={_label(params.hazard_model, 'server default')}, "
 275        f"Vs30={_label(params.vs30, 'server default')}, "
 276        f"AFE={_label(params.annual_frequency_of_exceedance, 'server default')}, "
 277        f"truncate={_label(params.truncate, 'server default')}, "
 278        f"maxdir={_label(params.maxdir, 'server default')}"
 279    )
 280
 281
 282def resolve_target_spectra(
 283    library,
 284    target_source: str,
 285    target_file: str,
 286    *,
 287    nshmp: NshmpSiteParameters,
 288) -> TargetSpectra:
 289    source = target_source.strip().lower()
 290    if source == "file":
 291        path = os.path.normpath(target_file)
 292        if not os.path.isfile(path):
 293            raise FileNotFoundError(f"Target spectrum file not found: {path}")
 294        print(f"  Loading user-defined target from:\n    {path}")
 295        return library.getTargetSpectra(UserDefinedTargetSpectraModel(filePath=path))
 296
 297    if source == "nshmp":
 298        print("  Querying NSHMP Dynamic Hazard Curves...")
 299        print(f"  {_describe_nshmp_parameters(nshmp)}")
 300        return library.getTargetSpectra(_build_nshmp_target_spectra_model(nshmp))
 301
 302    raise ValueError(f"Unknown target source '{target_source}'. Use 'file' or 'nshmp'.")
 303
 304
 305def run_motion_selection_steps(
 306    app: RSSeismicApplication,
 307    *,
 308    motion_dir: str,
 309    database: GroundMotionDatabase,
 310    username: str,
 311    password: str,
 312    target_source: str,
 313    target_file: str,
 314    nshmp: NshmpSiteParameters,
 315    preview_max_results: int | None,
 316    overwrite: bool,
 317    plot_dir: str | None,
 318) -> TargetSpectra | None:
 319    if database == GroundMotionDatabase.CESMD:
 320        raise ValueError("Automatic selection supports GMDB and ESM only.")
 321    if not password.strip():
 322        raise ValueError("Database password is required.")
 323
 324    filters = _build_search_filters(MAGNITUDE_MIN, MAGNITUDE_MAX, RRUP_KM_MAX)
 325    selection = RecordSelectionParams(
 326        nGm=NUM_GROUND_MOTIONS,
 327        damping=SCALING_DAMPING,
 328        tolPercent=SCALING_TOLERANCE_PERCENT,
 329        isScaled=True,
 330    )
 331    amplitude = AmplitudeScalingParams(t1=AMPLITUDE_T1_S, t2=AMPLITUDE_T2_S)
 332    library = app.MotionLibrary
 333
 334    step(3, "Prepare motion output folder")
 335    motion_dir = prepare_motion_output_directory(app, motion_dir)
 336
 337    db_label = _database_label(database)
 338    step(4, f"Database: {db_label}")
 339    library.authenticateDatabase(database=database, username=username, password=password)
 340
 341    print("  Preview database search")
 342    preview = library.searchDatabaseRecords(
 343        database=database,
 344        filters=filters,
 345        maxResults=preview_max_results,
 346    )
 347    print(f"  Records returned: {len(preview)}")
 348    for record in preview[:5]:
 349        print(
 350            f"    {record.id}  M={record.magnitude}  Rrup={record.rrupKm:.1f} km  "
 351            f"sta={record.station}"
 352        )
 353    if len(preview) > 5:
 354        print(f"    ... and {len(preview) - 5} more")
 355
 356    step(
 357        5,
 358        "Target spectra (NSHMP Dynamic Hazard Curves)"
 359        if target_source.strip().lower() == "nshmp"
 360        else "Target spectra",
 361    )
 362    target = resolve_target_spectra(
 363        library, target_source, target_file, nshmp=nshmp,
 364    )
 365    if not target.points:
 366        raise RuntimeError("Target spectra returned no period–Sa points.")
 367    print(f"  {len(target.points)} period–Sa point(s).")
 368
 369    step(6, "Automatic record selection and save")
 370    print(
 371        "  Avoid opening the Motion tab before this step completes "
 372        "(or use --launch-rsseismic)."
 373    )
 374    try:
 375        result = library.matchToTargetSpectraAutomatic(
 376            database=database,
 377            filters=filters,
 378            targetSpectra=target,
 379            outputDirectory=motion_dir,
 380            selection=selection,
 381            amplitude=amplitude,
 382            overwrite=overwrite,
 383        )
 384    except ScriptingError as ex:
 385        if _is_motion_ui_collection_conflict(ex):
 386            print(_MOTION_UI_CONFLICT_HINT, file=sys.stderr)
 387        raise
 388
 389    print(f"  Saved {len(result.savedMotionNames)} motion component(s) under:\n    {motion_dir}")
 390    for name in result.savedMotionNames[:8]:
 391        print(f"    {name}")
 392    if len(result.savedMotionNames) > 8:
 393        print(f"    ... and {len(result.savedMotionNames) - 8} more")
 394
 395    if plot_dir is not None and result.savedMotionNames:
 396        step(7, "Plot target vs scaled geometric-mean spectra")
 397        period_arrays, sa_arrays = collect_geometric_mean_spectra(
 398            library, motion_dir, list(result.savedMotionNames),
 399        )
 400        if period_arrays:
 401            plot_path = os.path.join(os.path.abspath(plot_dir), MATCH_PLOT_FILENAME)
 402            plot_match_to_target_spectra(target, period_arrays, sa_arrays, plot_path)
 403            print(f"  Saved: {plot_path}")
 404        else:
 405            logger.warning("  No pair spectra available for match plot.")
 406
 407    return target
 408
 409
 410_SCALE_FACTOR_SUFFIX = re.compile(r"_SF=[0-9.+\-eE]+$")
 411
 412
 413def _strip_scale_factor_suffix(motion_name: str) -> str:
 414    return _SCALE_FACTOR_SUFFIX.sub("", motion_name)
 415
 416
 417def _shared_prefix_from_motion_name(motion_name: str) -> str | None:
 418    stem = _strip_scale_factor_suffix(motion_name)
 419    split_at = stem.rfind("_")
 420    if split_at <= 0:
 421        return None
 422    return stem[:split_at]
 423
 424
 425def _group_saved_motion_pairs(saved_motion_names: list[str]) -> list[tuple[str, str]]:
 426    buckets: dict[str, list[str]] = {}
 427    for motion_name in saved_motion_names:
 428        prefix = _shared_prefix_from_motion_name(motion_name)
 429        if prefix is None:
 430            continue
 431        buckets.setdefault(prefix, []).append(motion_name)
 432
 433    pairs: list[tuple[str, str]] = []
 434    for prefix, names in buckets.items():
 435        unique_names = sorted(set(names))
 436        if len(unique_names) == 2:
 437            pairs.append((unique_names[0], unique_names[1]))
 438    return pairs
 439
 440
 441def _pick_sa_column(spectral_df) -> str:
 442    for column in ("FrequencyDomain", "GeometricMeanSa", "Duhamel", "Newmark"):
 443        if column in spectral_df.columns:
 444            return column
 445    candidates = [col for col in spectral_df.columns if col != "Period"]
 446    if not candidates:
 447        raise ValueError(f"No spectral acceleration column in {list(spectral_df.columns)}")
 448    return candidates[0]
 449
 450
 451def _geometric_mean_spectrum_from_motion_names(
 452    library,
 453    h1_name: str,
 454    h2_name: str,
 455) -> tuple[np.ndarray, np.ndarray]:
 456    _, spec_h1 = library.getMotion(h1_name).getSpectralData()
 457    _, spec_h2 = library.getMotion(h2_name).getSpectralData()
 458    sa_column = _pick_sa_column(spec_h1)
 459
 460    period_h1 = spec_h1["Period"].values.astype(float)
 461    sa_h1 = spec_h1[sa_column].values.astype(float)
 462    period_h2 = spec_h2["Period"].values.astype(float)
 463    sa_h2 = spec_h2[sa_column].values.astype(float)
 464
 465    mask_h1 = np.isfinite(period_h1) & np.isfinite(sa_h1) & (period_h1 > 0) & (sa_h1 > 0)
 466    mask_h2 = np.isfinite(period_h2) & np.isfinite(sa_h2) & (period_h2 > 0) & (sa_h2 > 0)
 467    period_h1, sa_h1 = period_h1[mask_h1], sa_h1[mask_h1]
 468    period_h2, sa_h2 = period_h2[mask_h2], sa_h2[mask_h2]
 469
 470    order_h2 = np.argsort(period_h2)
 471    period_h2, sa_h2 = period_h2[order_h2], sa_h2[order_h2]
 472    sa_h2_on_h1 = np.interp(period_h1, period_h2, sa_h2, left=np.nan, right=np.nan)
 473    valid = np.isfinite(sa_h2_on_h1)
 474    period = period_h1[valid]
 475    geo_sa = np.sqrt(sa_h1[valid] * sa_h2_on_h1[valid])
 476    return period, geo_sa
 477
 478
 479def collect_geometric_mean_spectra(
 480    library,
 481    output_directory: str,
 482    saved_motion_names: list[str],
 483) -> tuple[list[np.ndarray], list[np.ndarray]]:
 484    periods_list: list[np.ndarray] = []
 485    sa_list: list[np.ndarray] = []
 486
 487    pairs = _group_saved_motion_pairs(saved_motion_names)
 488    if not pairs:
 489        discovered = library.discoverMotionPairsInFolder(output_directory)
 490        pairs = [(pair.motionH1Name, pair.motionH2Name) for pair in discovered.allPairs]
 491
 492    for h1_name, h2_name in pairs:
 493        try:
 494            period, geo_sa = _geometric_mean_spectrum_from_motion_names(
 495                library, h1_name, h2_name,
 496            )
 497        except Exception as ex:
 498            logger.warning("  Skipping pair for plot: %s", ex)
 499            continue
 500        if period.size:
 501            periods_list.append(period)
 502            sa_list.append(geo_sa)
 503
 504    return periods_list, sa_list
 505
 506
 507def _log_mean_spectrum(
 508    period_arrays: list[np.ndarray],
 509    sa_arrays: list[np.ndarray],
 510    common_periods: np.ndarray,
 511) -> np.ndarray:
 512    cx = np.log(common_periods)
 513    matrix = np.full((len(common_periods), len(period_arrays)), np.nan)
 514    for j, (periods, sa_values) in enumerate(zip(period_arrays, sa_arrays)):
 515        order = np.argsort(periods)
 516        xp = np.log(np.clip(periods[order], 1e-300, None))
 517        matrix[:, j] = np.interp(cx, xp, sa_values[order], left=np.nan, right=np.nan)
 518
 519    with np.errstate(divide="ignore", invalid="ignore"):
 520        ln_mean = np.nanmean(np.log(matrix), axis=1)
 521    return np.exp(ln_mean)
 522
 523
 524def plot_match_to_target_spectra(
 525    target: TargetSpectra,
 526    period_arrays: list[np.ndarray],
 527    sa_arrays: list[np.ndarray],
 528    plot_path: str,
 529) -> None:
 530    target_periods = np.array([point.period for point in target.points], dtype=float)
 531    target_sa = np.array([point.sa for point in target.points], dtype=float)
 532    target_mask = (
 533        np.isfinite(target_periods)
 534        & np.isfinite(target_sa)
 535        & (target_periods > 0)
 536        & (target_sa > 0)
 537    )
 538    target_periods = target_periods[target_mask]
 539    target_sa = target_sa[target_mask]
 540
 541    period_grid = np.sort(
 542        np.unique(np.concatenate([target_periods, period_arrays[0][period_arrays[0] > 0]]))
 543    )
 544    ensemble_sa = _log_mean_spectrum(period_arrays, sa_arrays, period_grid)
 545
 546    fig, ax = plt.subplots(figsize=(6, 4.5))
 547    for periods, sa_values in zip(period_arrays, sa_arrays):
 548        ax.semilogx(periods, sa_values, **_MATCH_INDIVIDUAL)
 549    ax.semilogx(period_grid, ensemble_sa, **_MATCH_ENSEMBLE)
 550    ax.semilogx(target_periods, target_sa, **_MATCH_TARGET)
 551    ax.set_xscale("log")
 552    ax.set_yscale("linear")
 553    ax.set_xlabel("Period (s)")
 554    ax.set_ylabel("Spectral acceleration (g)")
 555    ax.legend(frameon=False)
 556    ax.grid(True, which="both", alpha=0.3)
 557    fig.tight_layout()
 558
 559    os.makedirs(os.path.dirname(plot_path) or ".", exist_ok=True)
 560    fig.savefig(plot_path, dpi=150, bbox_inches="tight")
 561    plt.close(fig)
 562
 563
 564# =============================================================================
 565# STEP 8 — Resolve motion names (component motions; pairs handled in Step 9)
 566# =============================================================================
 567
 568
 569def _motion_file_in_directory(file_path: str, motion_dir: str) -> bool:
 570    file_abs = os.path.normcase(os.path.abspath(file_path))
 571    dir_abs = os.path.normcase(os.path.abspath(motion_dir))
 572    return file_abs == dir_abs or file_abs.startswith(dir_abs + os.sep)
 573
 574
 575def resolve_motion_names(model, motion_dir: str) -> list[str]:
 576    motion_dir = os.path.normpath(motion_dir)
 577    model.Motions.addMotionDirectory(motion_dir)
 578    model.Motions.refreshMotionsList()
 579
 580    all_motions = model.Motions.listMotions()
 581    target_names = [
 582        motion.name for motion in all_motions
 583        if _motion_file_in_directory(motion.filePath, motion_dir)
 584    ]
 585    if not target_names:
 586        raise RuntimeError(
 587            f"No motions found under {motion_dir}. "
 588            "Run without --skip-motions first, or check the folder."
 589        )
 590    model.Motions.setMotionSelection(target_names, selectOnlyListed=True)
 591    return target_names
 592
 593
 594# =============================================================================
 595# STEPS 11–12 — Read db3 from disk and aggregate plots
 596# =============================================================================
 597
 598
 599def compute_results_root(project_path: str) -> str:
 600    project_path = os.path.normpath(project_path)
 601    project_dir = os.path.dirname(project_path)
 602    stem = os.path.splitext(os.path.basename(project_path))[0]
 603    return os.path.join(project_dir, stem)
 604
 605
 606def iter_deepsoilout_db3(results_root: str):
 607    if not os.path.isdir(results_root):
 608        return
 609
 610    for profile_folder in sorted(os.listdir(results_root)):
 611        profile_dir = os.path.join(results_root, profile_folder)
 612        if not os.path.isdir(profile_dir):
 613            continue
 614        for motion_folder in sorted(os.listdir(profile_dir)):
 615            if not motion_folder.startswith(MOTION_FOLDER_PREFIX):
 616                continue
 617            db3_path = os.path.join(profile_dir, motion_folder, DB3_FILENAME)
 618            if os.path.isfile(db3_path):
 619                motion_label = motion_folder[len(MOTION_FOLDER_PREFIX):]
 620                yield profile_folder, motion_label, db3_path
 621
 622
 623def read_standard_db3(db3_path: str, rs_layer_index: int = RS_LAYER_INDEX) -> tuple[
 624    np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray,
 625]:
 626    rs_column = f"LAYER{rs_layer_index}_RS"
 627    with sqlite3.connect(db3_path) as conn:
 628        rs_rows = conn.execute(
 629            f"SELECT PERIOD, {rs_column} FROM RESPONSE_SPECTRA"
 630        ).fetchall()
 631        profile_rows = conn.execute(
 632            "SELECT DEPTH_LAYER_MID, MAX_STRAIN, PGA_TOTAL FROM PROFILES"
 633        ).fetchall()
 634
 635    periods = np.array([row[0] for row in rs_rows], dtype=float)
 636    rs_values = np.array([row[1] for row in rs_rows], dtype=float)
 637    depths = np.array([row[0] for row in profile_rows], dtype=float)
 638    strains = np.array([row[1] for row in profile_rows], dtype=float)
 639    pga_values = np.array([row[2] for row in profile_rows], dtype=float)
 640    return periods, rs_values, depths, strains, pga_values
 641
 642
 643@dataclass
 644class AggregatedSamples:
 645    rs_periods: list[np.ndarray] = field(default_factory=list)
 646    rs_values: list[np.ndarray] = field(default_factory=list)
 647    strain_depths: list[np.ndarray] = field(default_factory=list)
 648    strain_values: list[np.ndarray] = field(default_factory=list)
 649    pga_depths: list[np.ndarray] = field(default_factory=list)
 650    pga_values: list[np.ndarray] = field(default_factory=list)
 651    rs_units: dict[str, str] = field(default_factory=dict)
 652    depth_units: dict[str, str] = field(default_factory=dict)
 653    pga_units: dict[str, str] = field(default_factory=dict)
 654
 655
 656def collect_results_from_disk(project_paths: list[str]) -> AggregatedSamples:
 657    samples = AggregatedSamples()
 658    samples.rs_units = {"period": "s", "rs": "g"}
 659    samples.depth_units = {"depth": "m"}
 660    samples.pga_units = {"pga": "g"}
 661
 662    for project_path in project_paths:
 663        results_root = compute_results_root(project_path)
 664        for _profile_folder, _motion_label, db3_path in iter_deepsoilout_db3(results_root):
 665            periods, rs_values, depths, strains, pga_values = read_standard_db3(db3_path)
 666            samples.rs_periods.append(periods)
 667            samples.rs_values.append(rs_values)
 668            samples.strain_depths.append(depths)
 669            samples.strain_values.append(strains)
 670            samples.pga_depths.append(depths)
 671            samples.pga_values.append(pga_values)
 672
 673    return samples
 674
 675
 676matplotlib.rcParams.update({
 677    "font.family": "Times New Roman",
 678    "font.size": 12,
 679    "axes.labelsize": 12,
 680    "legend.fontsize": 12,
 681    "xtick.labelsize": 12,
 682    "ytick.labelsize": 12,
 683})
 684_ANALYSIS_INDIVIDUAL = dict(color="silver", linewidth=0.7, alpha=0.65, marker="o", markersize=3)
 685_ANALYSIS_MEAN = dict(color="black", linewidth=1.5, marker="o", markersize=4)
 686_ANALYSIS_BOUND = dict(color="black", linewidth=1.0, linestyle="--", marker="o", markersize=3)
 687
 688
 689def strain_to_percent(strain: np.ndarray) -> np.ndarray:
 690    return strain.astype(float) * 100.0
 691
 692
 693def log_mean_std(
 694    x_arrays: list[np.ndarray],
 695    y_arrays: list[np.ndarray],
 696    common_x: np.ndarray,
 697    *,
 698    log_x: bool = False,
 699    log_y: bool = True,
 700) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
 701    n_pts = len(common_x)
 702    n_samp = len(x_arrays)
 703    matrix = np.full((n_pts, n_samp), np.nan)
 704
 705    cx = np.log(common_x) if log_x else common_x
 706    for j, (x, y) in enumerate(zip(x_arrays, y_arrays)):
 707        order = np.argsort(x)
 708        xs, ys = x[order], y[order]
 709        xj = np.log(np.clip(xs, 1e-300, None)) if log_x else xs
 710        matrix[:, j] = np.interp(cx, xj, ys)
 711
 712    valid = np.isfinite(matrix) & (matrix > 0)
 713    if log_y:
 714        with np.errstate(divide="ignore", invalid="ignore"):
 715            ln_mat = np.where(valid, np.log(matrix), np.nan)
 716            mu = np.nanmean(ln_mat, axis=1)
 717            sigma = np.nanstd(ln_mat, axis=1, ddof=1)
 718        return np.exp(mu), np.exp(mu + sigma), np.exp(mu - sigma)
 719
 720    mu = np.nanmean(matrix, axis=1)
 721    sigma = np.nanstd(matrix, axis=1, ddof=1)
 722    return mu, mu + sigma, mu - sigma
 723
 724
 725def aggregate_by_layer_index(
 726    depth_arrays: list[np.ndarray],
 727    value_arrays: list[np.ndarray],
 728    *,
 729    log_y: bool = True,
 730) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
 731    max_layers = max(len(d) for d in depth_arrays)
 732    mean_depths: list[float] = []
 733    val_means: list[float] = []
 734    val_uppers: list[float] = []
 735    val_lowers: list[float] = []
 736
 737    for layer_idx in range(max_layers):
 738        depths: list[float] = []
 739        values: list[float] = []
 740        for depth_arr, value_arr in zip(depth_arrays, value_arrays):
 741            if layer_idx < len(depth_arr):
 742                depths.append(float(depth_arr[layer_idx]))
 743                values.append(float(value_arr[layer_idx]))
 744        if not values:
 745            continue
 746
 747        values_arr = np.array(values, dtype=float)
 748        if log_y:
 749            positive = values_arr[values_arr > 0]
 750            if positive.size == 0:
 751                continue
 752            ln_vals = np.log(positive)
 753            mu = float(np.mean(ln_vals))
 754            sigma = float(np.std(ln_vals, ddof=1)) if positive.size > 1 else 0.0
 755            val_means.append(math.exp(mu))
 756            val_uppers.append(math.exp(mu + sigma))
 757            val_lowers.append(math.exp(mu - sigma))
 758        else:
 759            mu = float(np.mean(values_arr))
 760            sigma = float(np.std(values_arr, ddof=1)) if values_arr.size > 1 else 0.0
 761            val_means.append(mu)
 762            val_uppers.append(mu + sigma)
 763            val_lowers.append(mu - sigma)
 764        mean_depths.append(float(np.mean(depths)))
 765
 766    return (
 767        np.array(mean_depths),
 768        np.array(val_means),
 769        np.array(val_uppers),
 770        np.array(val_lowers),
 771    )
 772
 773
 774def _sorted_layer_profile(values: np.ndarray, depths: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
 775    order = np.argsort(depths)
 776    return values[order], depths[order]
 777
 778
 779def plot_aggregated(samples: AggregatedSamples, output_dir: str) -> None:
 780    if not samples.rs_periods:
 781        raise RuntimeError(
 782            "No deepsoilout.db3 samples found. Run batch compute first or check project paths."
 783        )
 784
 785    n = len(samples.rs_periods)
 786    step(12, f"Plot aggregates ({n} project × motion sample(s))")
 787
 788    period_unit = samples.rs_units.get("period", "s")
 789    rs_unit = samples.rs_units.get("rs", "g")
 790    depth_unit = samples.depth_units.get("depth", "m")
 791    pga_unit = samples.pga_units.get("pga", "g")
 792
 793    period_grid = np.sort(samples.rs_periods[0][samples.rs_periods[0] > 0])
 794    rs_mean, rs_upper, rs_lower = log_mean_std(
 795        samples.rs_periods, samples.rs_values, period_grid, log_x=True, log_y=True,
 796    )
 797
 798    fig1, ax1 = plt.subplots(figsize=(5, 4.5))
 799    for xp, yp in zip(samples.rs_periods, samples.rs_values):
 800        ax1.semilogx(xp, yp, **_ANALYSIS_INDIVIDUAL)
 801    ax1.semilogx(period_grid, rs_mean, label=r"$\mu_{\ln}$", **_ANALYSIS_MEAN)
 802    ax1.semilogx(period_grid, rs_upper, label=r"$\mu_{\ln} \pm \sigma_{\ln}$", **_ANALYSIS_BOUND)
 803    ax1.semilogx(period_grid, rs_lower, **_ANALYSIS_BOUND)
 804    ax1.set_xscale("log")
 805    ax1.set_yscale("linear")
 806    ax1.set_xlabel(f"Period ({period_unit})")
 807    ax1.set_ylabel(f"Spectral Acceleration ({rs_unit})")
 808    ax1.legend(frameon=False)
 809    ax1.grid(True, which="both", alpha=0.3)
 810    fig1.tight_layout()
 811
 812    strain_pct_samples = [strain_to_percent(v) for v in samples.strain_values]
 813    s_depths, s_mean, s_upper, s_lower = aggregate_by_layer_index(
 814        samples.strain_depths, strain_pct_samples, log_y=True,
 815    )
 816
 817    fig2, ax2 = plt.subplots(figsize=(4, 5.5))
 818    for strain_pct, depths in zip(strain_pct_samples, samples.strain_depths):
 819        xs, ys = _sorted_layer_profile(strain_pct, depths)
 820        ax2.plot(xs, ys, **_ANALYSIS_INDIVIDUAL)
 821    ax2.plot(s_mean, s_depths, label=r"$\mu_{\ln}$", **_ANALYSIS_MEAN)
 822    ax2.plot(s_upper, s_depths, label=r"$\mu_{\ln} \pm \sigma_{\ln}$", **_ANALYSIS_BOUND)
 823    ax2.plot(s_lower, s_depths, **_ANALYSIS_BOUND)
 824    ax2.set_xlabel("Max Shear Strain (%)")
 825    ax2.set_ylabel(f"Depth ({depth_unit})")
 826    ax2.invert_yaxis()
 827    ax2.legend(frameon=False)
 828    ax2.grid(True, which="major", alpha=0.3)
 829    fig2.tight_layout()
 830
 831    p_depths, p_mean, p_upper, p_lower = aggregate_by_layer_index(
 832        samples.pga_depths, samples.pga_values, log_y=True,
 833    )
 834
 835    fig3, ax3 = plt.subplots(figsize=(4, 5.5))
 836    for pga, depths in zip(samples.pga_values, samples.pga_depths):
 837        xs, ys = _sorted_layer_profile(pga, depths)
 838        ax3.plot(xs, ys, **_ANALYSIS_INDIVIDUAL)
 839    ax3.plot(p_mean, p_depths, label=r"$\mu_{\ln}$", **_ANALYSIS_MEAN)
 840    ax3.plot(p_upper, p_depths, label=r"$\mu_{\ln} \pm \sigma_{\ln}$", **_ANALYSIS_BOUND)
 841    ax3.plot(p_lower, p_depths, **_ANALYSIS_BOUND)
 842    ax3.set_xlabel(f"PGA ({pga_unit})")
 843    ax3.set_ylabel(f"Depth ({depth_unit})")
 844    ax3.invert_yaxis()
 845    ax3.legend(frameon=False)
 846    ax3.grid(True, which="major", alpha=0.3)
 847    fig3.tight_layout()
 848
 849    os.makedirs(output_dir, exist_ok=True)
 850    for fig, name in [
 851        (fig1, "response_spectra.png"),
 852        (fig2, "max_strain_profile.png"),
 853        (fig3, "pga_profile.png"),
 854    ]:
 855        path = os.path.join(output_dir, name)
 856        fig.savefig(path, dpi=150, bbox_inches="tight")
 857        print(f"  Saved: {path}")
 858        plt.close(fig)
 859
 860# =============================================================================
 861# STEP 9 — CSV inputs (mean profile and generation settings)
 862# =============================================================================
 863
 864
 865@dataclass
 866class MeanProfileLayerRow:
 867    below_water_table: int
 868    thickness_m: float
 869    unit_weight: float
 870    vs_m_s: float
 871    shear_strength_kPa: float
 872    soil_type: str
 873    curve_model: str
 874    reduction_factor_formulation: str
 875    ocr: float
 876    k0: float
 877    n: float
 878    pi: float
 879    fem_values: dict[str, float] = field(default_factory=dict)
 880
 881
 882def _cell(row: dict[str, str], key: str) -> str:
 883    return row.get(key, "").strip()
 884
 885
 886def _optional_float(row: dict[str, str], key: str) -> float | None:
 887    text = _cell(row, key)
 888    if not text:
 889        return None
 890    return float(text)
 891
 892
 893def load_mean_profile_rows(csv_path: str) -> list[MeanProfileLayerRow]:
 894    csv_path = os.path.normpath(csv_path)
 895    with open(csv_path, newline="", encoding="utf-8-sig") as handle:
 896        data_lines = [
 897            line for line in handle
 898            if line.strip() and not line.lstrip().startswith("#")
 899        ]
 900        reader = csv.DictReader(data_lines)
 901        rows: list[MeanProfileLayerRow] = []
 902        for raw in reader:
 903            if not any(_cell(raw, key) for key in raw):
 904                continue
 905            fem: dict[str, float] = {}
 906            for csv_key, _ in _FEM_DOUBLE_PROPERTIES:
 907                value = _optional_float(raw, csv_key)
 908                if value is not None:
 909                    fem[csv_key] = value
 910            rows.append(MeanProfileLayerRow(
 911                below_water_table=int(float(_cell(raw, "below_water_table") or "0")),
 912                thickness_m=float(_cell(raw, "thickness_m")),
 913                unit_weight=float(_cell(raw, "unit_weight")),
 914                vs_m_s=float(_cell(raw, "vs_m_s")),
 915                shear_strength_kPa=float(_cell(raw, "shear_strength_kPa")),
 916                soil_type=_cell(raw, "soil_type"),
 917                curve_model=_cell(raw, "curve_model"),
 918                reduction_factor_formulation=_cell(raw, "reduction_factor_formulation"),
 919                ocr=float(_cell(raw, "OCR") or "1"),
 920                k0=float(_cell(raw, "K0") or "0.5"),
 921                n=float(_cell(raw, "N") or "0"),
 922                pi=float(_cell(raw, "PI") or "0"),
 923                fem_values=fem,
 924            ))
 925    return rows
 926
 927
 928def _parse_bool(text: str) -> bool:
 929    return text.strip().lower() in ("1", "true", "yes", "on")
 930
 931
 932def load_profile_generation_settings(csv_path: str) -> dict[str, str]:
 933    csv_path = os.path.normpath(csv_path)
 934    settings: dict[str, str] = {}
 935    with open(csv_path, newline="", encoding="utf-8-sig") as handle:
 936        reader = csv.DictReader(
 937            line for line in handle
 938            if line.strip() and not line.lstrip().startswith("#")
 939        )
 940        for row in reader:
 941            key = _cell(row, "setting")
 942            value = _cell(row, "value")
 943            if key:
 944                settings[key] = value
 945    return settings
 946
 947
 948def mrdf_fitting_procedure(formulation: str) -> str | None:
 949    if formulation in ("None", "", "none"):
 950        return None
 951    if formulation == "MRDF_Darendeli":
 952        return "MRDF_Derendeli"
 953    return "MRDF_UIUC"
 954
 955
 956def _apply_fem_properties(layer_data, fem_values: dict[str, float]) -> None:
 957    for csv_key, prop_key in _FEM_DOUBLE_PROPERTIES:
 958        value = fem_values.get(csv_key)
 959        if value is not None:
 960            layer_data.setDoubleProperty(prop_key, value)
 961
 962
 963# =============================================================================
 964# STEP 9 (continued) — FEM project build — FEM + mean profile + generateProfiles
 965# =============================================================================
 966
 967
 968def _try_set_project_bool(data, property_name: str, value: bool) -> bool:
 969    """Set a ProjectSettings flag; return False if this RSSeismic build has no such property."""
 970    try:
 971        data.setBoolValue(property_name, value)
 972        return True
 973    except Exception as ex:
 974        logger.warning("ProjectSettings.%s not applied: %s", property_name, ex)
 975        return False
 976
 977
 978def _set_complimentary_analyses(ps, data) -> None:
 979    """Enable complementary EL + NL total-stress runs (RPC names vary by RSSeismic version)."""
 980    if hasattr(ps, "setComplimentaryAnalysisEquivalentLinear"):
 981        try:
 982            ps.setComplimentaryAnalysisEquivalentLinear(True)
 983            ps.setComplimentaryAnalysisNonlinearTotalStressTimeDomain(True)
 984            return
 985        except Exception as ex:
 986            logger.warning("Complimentary analysis via ProjectSettings API failed: %s", ex)
 987
 988    if not _try_set_project_bool(data, "equivalentLinear", True):
 989        _try_set_project_bool(data, "complimentaryAnalysisEquivalentLinear", True)
 990    if not _try_set_project_bool(data, "nonlinearTotalStress", True):
 991        _try_set_project_bool(
 992            data,
 993            "complimentaryAnalysisNonlinearTotalStressTimeDomain",
 994            True,
 995        )
 996
 997
 998def _auto_profile_template_candidates(explicit: str | None = None) -> list[str]:
 999    paths: list[str] = []
1000    if explicit:
1001        paths.append(os.path.normpath(explicit))
1002    env_path = os.environ.get("RSSEISMIC_AUTO_PROFILE_TEMPLATE", "").strip()
1003    if env_path:
1004        paths.append(os.path.normpath(env_path))
1005    paths.extend([
1006        os.path.normpath(DEFAULT_TEMPLATE_PATH),
1007        os.path.normpath(os.path.join(
1008            _EXAMPLES_DIR, "..", "tests", "resources", "Test_Auto_Profile.rsseismicfile",
1009        )),
1010    ])
1011    seen: set[str] = set()
1012    unique: list[str] = []
1013    for path in paths:
1014        key = os.path.normcase(path)
1015        if key not in seen:
1016            seen.add(key)
1017            unique.append(path)
1018    return unique
1019
1020
1021def discover_auto_profile_template(explicit: str | None = None) -> str | None:
1022    for path in _auto_profile_template_candidates(explicit):
1023        if os.path.isfile(path):
1024            return path
1025    return None
1026
1027
1028_RANDOMIZE_REQUIRES_TEMPLATE = (
1029    "No auto-profile template .rsseismicfile found. See Tutorial_4/template/README.md "
1030    "or set RSSEISMIC_AUTO_PROFILE_TEMPLATE. Without --randomize, use the single-profile CSV path."
1031)
1032
1033
1034def configure_fem_project_settings(model, *, automatic_profile_generation: bool) -> None:
1035    ps = model.ProjectSettings
1036    ps.changeUnitSystem(UnitSystem.Metric)
1037    data = ps.Data
1038    if hasattr(ps, "setAutomaticProfileGeneration"):
1039        ps.setAutomaticProfileGeneration(automatic_profile_generation)
1040    else:
1041        data.setBoolValue("automaticProfileGeneration", automatic_profile_generation)
1042    data.setEnumValue("analysisMode", "Nonlinear")
1043    data.setEnumValue("solverType", "FiniteElementMethod")
1044    data.setEnumValue("defaultSoilModel", "GQ_H")
1045    data.setEnumValue("hystereticFormulation", "NonMasing")
1046    data.setEnumValue("inputMotionConfiguration", "BiDirectional")
1047    # FEM volumetric/PWP layer props require both (server-enforced).
1048    if hasattr(ps, "setGenerateExcessPWP"):
1049        ps.setGenerateExcessPWP(True)
1050        ps.setEnableDissipation(True)
1051    else:
1052        data.setBoolValue("generateExcessPWP", True)
1053        data.setBoolValue("enableDissipation", True)
1054    _set_complimentary_analyses(ps, data)
1055    if automatic_profile_generation:
1056        _try_set_project_bool(data, "multipleProfiles", True)
1057
1058
1059def _ensure_mean_layer_count(mean, target_count: int) -> None:
1060    """Resize mean-profile stack (append/delete) so layer count matches the CSV."""
1061    layers = mean.listSoilLayers()
1062    while len(layers) > target_count:
1063        mean.deleteLayer(layers[-1].layerID)
1064        layers = mean.listSoilLayers()
1065    while len(layers) < target_count:
1066        mean.appendLayers(1)
1067        layers = mean.listSoilLayers()
1068
1069
1070def _set_mean_layer_shear_strength(layer, thickness_m: float, strength_kpa: float) -> None:
1071    """
1072    ``generateProfiles`` validates mean strata: shear strength must be > 0.
1073
1074    Uses ``MeanProfileSoilLayer`` (Constant_Value, else vary-with-depth table). Linear/Yee
1075    mean layers reject scalar GQ/H strength — vary-with-depth is attempted second.
1076    """
1077    if strength_kpa <= 0:
1078        raise ValueError(f"CSV shear_strength_kPa must be > 0 (got {strength_kpa}).")
1079
1080    thickness = max(thickness_m, 1e-6)
1081    last_error: Exception | None = None
1082
1083    for variation in ("Constant_Value", "Vary_With_Depth"):
1084        try:
1085            layer.setShearStrengthVariation(variation)
1086            if variation == "Constant_Value":
1087                layer.setShearStrength(strength_kpa)
1088            else:
1089                layer.setShearStrengthValues([(0.0, strength_kpa), (thickness, strength_kpa)])
1090            return
1091        except Exception as ex:
1092            last_error = ex
1093            continue
1094
1095    raise ScriptingError(
1096        "Could not set mean-profile shear strength for generateProfiles validation. "
1097        f"Last error: {last_error}"
1098    ) from last_error
1099
1100
1101def populate_mean_profile_from_csv(model, rows: list[MeanProfileLayerRow]) -> None:
1102    """
1103    Mean template for ``generateProfiles()`` (see ``MeanProfileSoilLayer`` / server validation).
1104
1105    Scripting: thickness, unit weight, Vs, shear strength. Reference curves / FEM / GQ-H
1106    layer fields are applied on ``model.Profiles`` after generation (Tutorial 2 path).
1107    """
1108    mean = model.MeanProfile
1109    _ensure_mean_layer_count(mean, len(rows))
1110
1111    any_below_wt = any(row.below_water_table for row in rows)
1112    if any_below_wt:
1113        model.ProjectSettings.Data.setBoolValue("applyWaterTable", True)
1114
1115    for summary, spec in zip(mean.listSoilLayers(), rows):
1116        layer = mean.getSoilLayer(summary.layerID)
1117        layer.setShearWaveVelocityVariation("Constant_Value")
1118        layer.setThickness(spec.thickness_m)
1119        layer.setUnitWeight(spec.unit_weight)
1120        layer.setShearWaveVelocity(spec.vs_m_s)
1121        _set_mean_layer_shear_strength(layer, spec.thickness_m, spec.shear_strength_kPa)
1122
1123
1124def apply_gqh_csv_to_active_profile(
1125    model,
1126    rows: list[MeanProfileLayerRow],
1127    *,
1128    apply_vs_from_csv: bool,
1129    apply_thickness_from_csv: bool,
1130) -> None:
1131    """Tutorial 2-style layer setup on ``model.Profiles`` (after ``generateProfiles``)."""
1132    layer_summaries = model.Profiles.listActiveSoilLayers()
1133    if len(layer_summaries) != len(rows):
1134        logger.warning(
1135            "Active profile layer count (%s) != CSV rows (%s); applying min count.",
1136            len(layer_summaries),
1137            len(rows),
1138        )
1139    for summary, spec in zip(layer_summaries, rows):
1140        layer = model.Profiles.getSoilLayer(summary.layerID)
1141        layer.setSoilModel("GQ_H")
1142        if apply_thickness_from_csv:
1143            layer.setThickness(spec.thickness_m)
1144        layer.setUnitWeight(spec.unit_weight)
1145        if apply_vs_from_csv:
1146            layer.Data.setDoubleProperty("ShearWaveVelocity", spec.vs_m_s)
1147        layer.Data.setDoubleProperty("ShearStrength", spec.shear_strength_kPa)
1148        _apply_fem_properties(layer.Data, spec.fem_values)
1149
1150        ref = layer.ReferenceCurve
1151        ref.setSoilType(spec.soil_type)
1152        ref.setCurveModel(spec.curve_model)
1153        ref.setOCR(spec.ocr)
1154        ref.setKo(spec.k0)
1155        ref.setN(spec.n)
1156        ref.setPI(spec.pi)
1157        ref.generateReferenceCurve()
1158
1159        fit_proc = mrdf_fitting_procedure(spec.reduction_factor_formulation)
1160        if fit_proc is not None:
1161            layer.Curve.runCurveFit(fit_proc)
1162
1163
1164def apply_profile_generation_settings(model, settings: dict[str, str]) -> tuple[int, bool, bool]:
1165    """Configure ``ProfileGenerationSettings`` from the settings CSV (see API getters)."""
1166    gen = model.ProfileGenerationSettings
1167    num_profiles = int(settings.get("num_profiles", "5"))
1168    gen.setProfilesToGenerate(num_profiles)
1169
1170    velocity_rand = _parse_bool(settings.get("velocity_randomization", "false"))
1171    thickness_rand = _parse_bool(settings.get("thickness_randomization", "false"))
1172    gen.setVelocityRandomization(velocity_rand)
1173    gen.setThicknessRandomization(thickness_rand)
1174    if "dynamic_curve_randomization" in settings:
1175        gen.setDynamicCurveRandomization(_parse_bool(settings["dynamic_curve_randomization"]))
1176    if method := settings.get("velocity_input_method", "").strip():
1177        gen.setVelocityInputMethod(method)
1178
1179    _GEN_FLOAT_MAP: tuple[tuple[str, str], ...] = (
1180        ("velocity_rand_sigma", "setSigma"),
1181        ("velocity_rand_h0", "setH0"),
1182        ("velocity_rand_b", "setB"),
1183        ("velocity_rand_delta", "setDelta"),
1184        ("velocity_rand_rho0", "setRho0"),
1185        ("velocity_rand_rho200", "setRho200"),
1186        ("thickness_rand_c1", "setC1"),
1187        ("thickness_rand_c2", "setC2"),
1188        ("thickness_rand_c3", "setC3"),
1189        ("maximum_frequency", "setMaximumFrequency"),
1190    )
1191    for csv_key, setter_name in _GEN_FLOAT_MAP:
1192        if csv_key not in settings:
1193            continue
1194        value = float(settings[csv_key])
1195        getattr(gen, setter_name)(value)
1196
1197    return num_profiles, velocity_rand, thickness_rand
1198
1199
1200def run_generate_profiles_workflow(
1201    model,
1202    *,
1203    seed: int,
1204    settings: dict[str, str],
1205):
1206    """Same sequence as ``examples/example_auto_profile_workflow.py`` (reset → generate)."""
1207    if not model.ProjectSettings.Data.getBoolValue("automaticProfileGeneration"):
1208        raise ScriptingError(
1209            "automaticProfileGeneration is off. Use a template project or "
1210            "configure_fem_project_settings() before generateProfiles()."
1211        )
1212
1213    model.resetGeneratedProfiles()
1214    resolved_seed = seed or int(settings.get("seed", "0") or "0")
1215    print(f"  generateProfiles(seed={resolved_seed}) …")
1216    result = model.generateProfiles(seed=resolved_seed, timeout=GENERATE_PROFILES_TIMEOUT)
1217    if not result.ok:
1218        detail = result.errorMessage or "generateProfiles failed."
1219        if result.validationErrors:
1220            detail = f"{detail}\n" + "\n".join(f"  - {e}" for e in result.validationErrors)
1221        raise ScriptingError(detail)
1222    return result
1223
1224
1225def _ensure_active_profile_layer_count(model, row_count: int) -> None:
1226    existing = model.Profiles.listActiveSoilLayers()
1227    need = row_count - len(existing)
1228    if need > 0:
1229        model.SoilLayers.appendLayers(need)
1230    elif need < 0:
1231        raise RuntimeError(
1232            f"Active profile has {len(existing)} layers but CSV defines {row_count}."
1233        )
1234
1235
1236def _path_under_directory(file_path: str, directory: str) -> bool:
1237    file_abs = os.path.normcase(os.path.abspath(file_path))
1238    dir_abs = os.path.normcase(os.path.abspath(directory))
1239    return file_abs == dir_abs or file_abs.startswith(dir_abs + os.sep)
1240
1241
1242def resolve_motion_pairs(model, motion_dir: str) -> list[str]:
1243    """Select every motion pair under ``motion_dir`` (bi-directional FEM)."""
1244    motion_dir = os.path.normpath(os.path.abspath(motion_dir))
1245    if not os.path.isdir(motion_dir):
1246        raise FileNotFoundError(f"Motion folder not found: {motion_dir}")
1247
1248    model.Motions.addMotionDirectory(motion_dir)
1249    model.Motions.refreshMotionsList()
1250
1251    pairs = model.Motions.listMotionPairs()
1252    if not pairs:
1253        raise RuntimeError(
1254            f"No motion pairs in project library under {motion_dir}. "
1255            "Run the motion-selection phase first or check paired EW/NS files."
1256        )
1257
1258    # Prefer server directory selection (matches RSSeismic Motion UI "select all in folder").
1259    model.Motions.selectAllMotionsInDirectory(motion_dir)
1260
1261    selected_ids = [
1262        pair.pairId for pair in model.Motions.listMotionPairs() if pair.isSelected
1263    ]
1264    if not selected_ids:
1265        # Fallback: explicit pair ids whose H1/H2 paths lie under motion_dir.
1266        selected_ids = [
1267            pair.pairId
1268            for pair in pairs
1269            if _path_under_directory(pair.motionH1FilePath, motion_dir)
1270            and _path_under_directory(pair.motionH2FilePath, motion_dir)
1271        ]
1272        if selected_ids:
1273            model.Motions.setMotionPairSelection(selected_ids, selectOnlyListed=True)
1274
1275    if not selected_ids:
1276        raise RuntimeError(
1277            f"No motion pairs selected under {motion_dir}. "
1278            f"Library has {len(pairs)} pair(s); check paths vs Tutorial_4/Motions."
1279        )
1280
1281    print(f"  Selected {len(selected_ids)} motion pair(s) under {motion_dir}")
1282    return selected_ids
1283
1284
1285def build_fem_single_profile_project(
1286    app: RSSeismicApplication,
1287    motion_dir: str,
1288) -> str:
1289    """FEM + bi-directional motions; one ``Profiles`` stack from CSV (Tutorial 2-style)."""
1290    if not os.path.isfile(MEAN_PROFILE_CSV):
1291        raise FileNotFoundError(f"Missing layer CSV: {MEAN_PROFILE_CSV}")
1292
1293    os.makedirs(OUTPUT_PROJECT_DIR, exist_ok=True)
1294    layer_rows = load_mean_profile_rows(MEAN_PROFILE_CSV)
1295
1296    print("  New FEM project — single profile from CSV (no generateProfiles)")
1297    model = app.newProject()
1298    configure_fem_project_settings(model, automatic_profile_generation=False)
1299    _try_set_project_bool(model.ProjectSettings.Data, "multipleProfiles", False)
1300
1301    profiles = model.Profiles.listProfiles()
1302    profile_name = profiles[0].name if profiles else "Profile 1"
1303    model.Profiles.setActiveProfile(profile_name)
1304    _ensure_active_profile_layer_count(model, len(layer_rows))
1305    apply_gqh_csv_to_active_profile(
1306        model,
1307        layer_rows,
1308        apply_vs_from_csv=True,
1309        apply_thickness_from_csv=True,
1310    )
1311
1312    resolve_motion_pairs(model, motion_dir)
1313    model.saveAs(PROJECT_PATH)
1314    model.save()
1315    model.close(saveProject=False)
1316    return os.path.normpath(PROJECT_PATH)
1317
1318
1319def build_fem_randomized_project(
1320    app: RSSeismicApplication,
1321    motion_dir: str,
1322    *,
1323    template_path: str | None,
1324    generate_seed: int = 0,
1325) -> str:
1326    """Mean profile + ProfileGenerationSettings + generateProfiles (requires saved template)."""
1327    if not os.path.isfile(MEAN_PROFILE_CSV):
1328        raise FileNotFoundError(f"Missing mean profile CSV: {MEAN_PROFILE_CSV}")
1329    if not os.path.isfile(PROFILE_GEN_SETTINGS_CSV):
1330        raise FileNotFoundError(f"Missing settings CSV: {PROFILE_GEN_SETTINGS_CSV}")
1331
1332    resolved = discover_auto_profile_template(template_path)
1333    if resolved is None:
1334        searched = "\n".join(f"  - {path}" for path in _auto_profile_template_candidates(template_path))
1335        raise FileNotFoundError(
1336            f"No auto-profile template .rsseismicfile found.\nSearched:\n{searched}\n\n{_RANDOMIZE_REQUIRES_TEMPLATE}"
1337        )
1338
1339    os.makedirs(OUTPUT_PROJECT_DIR, exist_ok=True)
1340    gen_settings = load_profile_generation_settings(PROFILE_GEN_SETTINGS_CSV)
1341    layer_rows = load_mean_profile_rows(MEAN_PROFILE_CSV)
1342
1343    print(f"  Open auto-profile template: {os.path.basename(resolved)}")
1344    model = app.openFile(resolved)
1345    configure_fem_project_settings(model, automatic_profile_generation=True)
1346
1347    print(f"  Mean profile from {os.path.basename(MEAN_PROFILE_CSV)}")
1348    populate_mean_profile_from_csv(model, layer_rows)
1349
1350    num_profiles, velocity_rand, thickness_rand = apply_profile_generation_settings(
1351        model, gen_settings,
1352    )
1353    print(
1354        f"  ProfileGenerationSettings: num_profiles={num_profiles}, "
1355        f"velocity_randomization={velocity_rand}, thickness_randomization={thickness_rand}"
1356    )
1357
1358    generate_result = run_generate_profiles_workflow(
1359        model,
1360        seed=generate_seed,
1361        settings=gen_settings,
1362    )
1363    print(
1364        f"  Generated {generate_result.profileCount} profile(s): "
1365        f"{', '.join(generate_result.profileNames)}"
1366    )
1367
1368    apply_vs = not velocity_rand
1369    apply_thickness = not thickness_rand
1370    for profile_name in generate_result.profileNames:
1371        print(f"  Layer CSV → {profile_name}")
1372        model.Profiles.setActiveProfile(profile_name)
1373        apply_gqh_csv_to_active_profile(
1374            model,
1375            layer_rows,
1376            apply_vs_from_csv=apply_vs,
1377            apply_thickness_from_csv=apply_thickness,
1378        )
1379
1380    resolve_motion_pairs(model, motion_dir)
1381    model.saveAs(PROJECT_PATH)
1382    model.save()
1383    model.close(saveProject=False)
1384    return os.path.normpath(PROJECT_PATH)
1385
1386
1387# =============================================================================
1388# STEP 10 — Run compute for each profile
1389# =============================================================================
1390
1391
1392def run_compute_all_profiles(
1393    app: RSSeismicApplication,
1394    project_path: str,
1395    motion_dir: str,
1396    *,
1397    timeout: float | None,
1398) -> None:
1399    model = app.openFile(project_path)
1400    try:
1401        resolve_motion_pairs(model, motion_dir)
1402        profile_names = [p.name for p in model.Profiles.listProfiles()]
1403        print(f"  Computing {len(profile_names)} profile(s) in {os.path.basename(project_path)}")
1404        for index, profile_name in enumerate(profile_names, start=1):
1405            print(f"    [{index}/{len(profile_names)}] {profile_name}")
1406            model.Profiles.setActiveProfile(profile_name)
1407            result = model.runCompute(timeout=timeout)
1408            if not result.success:
1409                raise ScriptingError(
1410                    result.errorMessage or f"runCompute failed for {profile_name}."
1411                )
1412            if result.partialSuccess:
1413                raise ScriptingError(
1414                    f"runCompute partial success for {profile_name}:\n{result.errorMessage}"
1415                )
1416        model.save()
1417    finally:
1418        model.close(saveProject=False)
1419
1420        model.close(saveProject=False)
1421
1422def parse_args() -> argparse.Namespace:
1423    """Command-line flags for motions, FEM build mode, and partial runs."""
1424    parser = argparse.ArgumentParser(description="Tutorial 4: NSHMP motions → FEM → compute.")
1425    parser.add_argument("--port", "-p", type=int, default=SCRIPTING_PORT)
1426    parser.add_argument("--username", help="GMDB/ESM username (required unless --results-only).")
1427    parser.add_argument("--password", help="GMDB/ESM password.")
1428    parser.add_argument(
1429        "--database",
1430        "-d",
1431        default=_database_label(DATABASE),
1432        choices=sorted(DATABASE_CHOICES.keys()),
1433    )
1434    parser.add_argument("--target-source", choices=("file", "nshmp"), default=TARGET_SOURCE)
1435    parser.add_argument("--target-file", default=TARGET_SPECTRUM_FILE)
1436    parser.add_argument("--latitude", type=float, default=NSHMP_LATITUDE)
1437    parser.add_argument("--longitude", type=float, default=NSHMP_LONGITUDE)
1438    parser.add_argument(
1439        "--nshmp-model",
1440        default=NSHMP_HAZARD_MODEL.name if NSHMP_HAZARD_MODEL is not None else "DEFAULT",
1441    )
1442    parser.add_argument("--nshmp-vs30", type=int, default=NSHMP_VS30 if NSHMP_VS30 is not None else 0)
1443    parser.add_argument(
1444        "--nshmp-afe",
1445        default=NSHMP_AFE.name if NSHMP_AFE is not None else "DEFAULT",
1446    )
1447    parser.add_argument("--nshmp-truncate", action="store_true")
1448    parser.add_argument("--nshmp-maxdir", action="store_true")
1449    parser.add_argument("--preview-max-results", type=int, default=PREVIEW_SEARCH_MAX_RESULTS)
1450    parser.add_argument("--overwrite", action="store_true")
1451    parser.add_argument("--motion-dir", default=MOTION_DIR)
1452    parser.add_argument("--plot-dir", default=OUTPUT_PLOT_DIR)
1453    parser.add_argument("--no-match-plot", action="store_true")
1454    parser.add_argument("--launch-rsseismic", action="store_true")
1455    parser.add_argument("--rsseismic-exe", default="")
1456    parser.add_argument("--skip-motions", action="store_true")
1457    parser.add_argument("--motions-only", action="store_true")
1458    parser.add_argument("--results-only", action="store_true")
1459    parser.add_argument("--generate-seed", type=int, default=0)
1460    parser.add_argument("--randomize", action="store_true")
1461    parser.add_argument("--template", default=None)
1462    parser.add_argument("--skip-build", action="store_true")
1463    parser.add_argument("--skip-compute", action="store_true")
1464    return parser.parse_args()
1465
1466
1467def nshmp_params_from_args(args: argparse.Namespace) -> NshmpSiteParameters:
1468    return NshmpSiteParameters(
1469        latitude=args.latitude,
1470        longitude=args.longitude,
1471        hazard_model=_parse_nshmp_hazard_model(args.nshmp_model),
1472        vs30=args.nshmp_vs30 if args.nshmp_vs30 > 0 else None,
1473        annual_frequency_of_exceedance=_parse_nshmp_afe(args.nshmp_afe),
1474        truncate=True if args.nshmp_truncate else NSHMP_TRUNCATE,
1475        maxdir=True if args.nshmp_maxdir else NSHMP_MAXDIR,
1476    )
1477
1478
1479def main() -> int:
1480    args = parse_args()
1481
1482    if args.results_only:
1483        if not os.path.isfile(PROJECT_PATH):
1484            print(f"No project at {PROJECT_PATH}; run the full workflow first.", file=sys.stderr)
1485            return 1
1486        try:
1487            step(11, "Read deepsoilout.db3 from disk")
1488            samples = collect_results_from_disk([PROJECT_PATH])
1489            plot_aggregated(samples, args.plot_dir)
1490        except Exception as ex:
1491            print(f"Results post-processing failed: {ex}", file=sys.stderr)
1492            return 1
1493        print("\nTutorial 4 post-processing finished.")
1494        return 0
1495
1496    if not args.username or not args.password:
1497        print("--username and --password are required (unless --results-only).", file=sys.stderr)
1498        return 1
1499
1500    preview_cap: int | None = args.preview_max_results
1501    if preview_cap is not None and preview_cap <= 0:
1502        preview_cap = None
1503
1504    nshmp_params = nshmp_params_from_args(args)
1505    motion_dir = os.path.normpath(os.path.abspath(args.motion_dir))
1506    plot_dir = None if args.no_match_plot else args.plot_dir
1507    database = database_from_cli_choice(args.database)
1508
1509    try:
1510        if args.launch_rsseismic:
1511            print("Launching RSSeismic...")
1512            launch_kwargs: dict = {"port": args.port}
1513            if args.rsseismic_exe.strip():
1514                launch_kwargs["overridePathToExecutable"] = args.rsseismic_exe.strip()
1515            RSSeismicApplication.startApplication(**launch_kwargs)
1516
1517        step(2, "Connect to RSSeismic scripting server")
1518        app = connect_app(args.port)
1519
1520        if not args.skip_motions:
1521            run_motion_selection_steps(
1522                app,
1523                motion_dir=motion_dir,
1524                database=database,
1525                username=args.username,
1526                password=args.password,
1527                target_source=args.target_source,
1528                target_file=args.target_file,
1529                nshmp=nshmp_params,
1530                preview_max_results=preview_cap,
1531                overwrite=args.overwrite,
1532                plot_dir=plot_dir,
1533            )
1534        else:
1535            print("Steps 3–7 — Skipped (--skip-motions)")
1536
1537        if args.motions_only:
1538            app.close()
1539            print("\nTutorial 4 motions-only run finished.")
1540            return 0
1541
1542        if args.skip_build:
1543            project_path = os.path.normpath(PROJECT_PATH)
1544            if not os.path.isfile(project_path):
1545                print(f"--skip-build: project not found: {project_path}", file=sys.stderr)
1546                return 1
1547            step(9, f"Skipped (--skip-build); using {os.path.basename(project_path)}")
1548        elif args.randomize:
1549            step(9, "Build FEM project (mean profile + generateProfiles)")
1550            project_path = build_fem_randomized_project(
1551                app, motion_dir, template_path=args.template, generate_seed=args.generate_seed,
1552            )
1553            print(f"  Saved: {project_path}")
1554        else:
1555            step(9, "Build FEM project (single profile from CSV)")
1556            project_path = build_fem_single_profile_project(app, motion_dir)
1557            print(f"  Saved: {project_path}")
1558
1559        if args.skip_compute:
1560            app.close()
1561            print("\nTutorial 4 finished (project built; compute skipped).")
1562            return 0
1563
1564        step(10, "Run compute (each profile)")
1565        run_compute_all_profiles(app, project_path, motion_dir, timeout=COMPUTE_TIMEOUT)
1566        app.close()
1567
1568        step(11, "Read deepsoilout.db3 from disk")
1569        samples = collect_results_from_disk([project_path])
1570        plot_aggregated(samples, args.plot_dir)
1571
1572    except Exception as ex:
1573        print(f"Tutorial 4 failed: {ex}", file=sys.stderr)
1574        if _is_motion_ui_collection_conflict(ex):
1575            print(_MOTION_UI_CONFLICT_HINT, file=sys.stderr)
1576        return 1
1577
1578    print("\nTutorial 4 end-to-end run finished.")
1579    return 0
1580
1581
1582if __name__ == "__main__":
1583    raise SystemExit(main())
1584