Tutorial 2 — batch projects from CSV profiles#
Build five GQ/H projects from CSV layer definitions, batch-compute them against motions
from the RSSeismic motion folder, then read deepsoilout.db3 files and aggregate
response plots with Matplotlib.
Requires: RSSeismic scripting server; NumPy and Matplotlib in your Python environment.
Input CSVs live under examples/Tutorial_2/Inputs/ (one file per case). Column layout:
layer,thickness_m,unit_weight,vs_m_s,shear_strength_kPa,soil_type,curve_model,reduction_factor_formulation,ref_params
1,5,20,200.0,35,Sand,Darendeli_2001,MRDF_UIUC,Ko=0.46;PI=0
2,5,20,225.0,105.1,Sand,Darendeli_2001,MRDF_UIUC,Ko=0.46;PI=0
Download inputs (place under examples/Tutorial_2/Inputs/ next to the script):
Run from the repository root:
python examples/Tutorial_2/Scripting-Tutorial_2.py
1"""
2Workflow
3--------
4 Step 0 Import libraries
5 Step 1 Configuration (5 CSV → project paths, motion folder, batch settings)
6 Step 2 Connect to RSSeismic
7 Step 3 Resolve motion names (all motions under MOTION_DIR)
8 Step 4 Build 5 project files from CSV (single Profile 1, MRDF fit, save)
9 Step 5 Batch compute all projects with the same motion selection
10 Step 6 Read deepsoilout.db3 from disk (no scripting API — RSSeismic can be closed)
11 Step 7 Aggregate and write PNG plots
12
13Steps 1–5 require the RSSeismic scripting server. Steps 6–7 are pure Python and can
14even be run later on another machine that only has the project/result folders.
15
16CSV columns: thickness_m, unit_weight, vs_m_s, shear_strength_kPa, soil_type,
17curve_model, reduction_factor_formulation, ref_params (optional)
18Sample CSVs : profile_01.csv … profile_05.csv in Inputs/ (see Step 1)
19
20Run from the repo root:
21
22 python examples/Tutorial_2/Scripting-Tutorial_2.py
23"""
24
25# =============================================================================
26# STEP 0 — Import libraries
27# =============================================================================
28from __future__ import annotations
29import csv
30import math
31import os
32import sqlite3
33from dataclasses import dataclass, field
34
35import matplotlib
36import matplotlib.pyplot as plt
37import numpy as np
38
39from rsseismic import RSSeismicApplication, UnitSystem
40
41# =============================================================================
42# STEP 1 — Configuration
43# =============================================================================
44
45_TUTORIAL_ROOT = os.path.dirname(os.path.abspath(__file__))
46SCRIPTING_PORT = 60058
47PROFILE_NAME = "Profile 1"
48
49CSV_DIR = os.path.join(_TUTORIAL_ROOT, "Inputs")
50OUTPUT_PROJECT_DIR = os.path.join(_TUTORIAL_ROOT, "projects")
51OUTPUT_PLOT_DIR = os.path.join(_TUTORIAL_ROOT, "plots")
52
53PROJECT_CASES: list[tuple[str, str, str]] = [
54 (
55 f"case_{index:02d}",
56 os.path.join(CSV_DIR, f"profile_{index:02d}.csv"),
57 os.path.join(OUTPUT_PROJECT_DIR, f"gqh_case_{index:02d}.rsseismicfile"),
58 )
59 for index in range(1, 6)
60]
61
62MOTION_DIR = r"C:\Program Files\Rocscience\RSSeismic\Resources\InputMotions"
63MOTION_NAMES: list[str] = []
64
65PARALLEL_DEGREE = 2
66MAX_CONCURRENT_ANALYSES: int | None = None
67COMPUTE_TIMEOUT: float | None = 7200
68CONTINUE_ON_ERROR = True
69
70
71# =============================================================================
72# STEP 2 — Connect to RSSeismic
73# =============================================================================
74
75def connect_app() -> RSSeismicApplication:
76 app = RSSeismicApplication(port=SCRIPTING_PORT)
77 app.ping()
78 return app
79
80
81# =============================================================================
82# STEP 3 — Resolve motion names
83# =============================================================================
84
85def _motion_file_in_directory(file_path: str, motion_dir: str) -> bool:
86 file_abs = os.path.normcase(os.path.abspath(file_path))
87 dir_abs = os.path.normcase(os.path.abspath(motion_dir))
88 return file_abs == dir_abs or file_abs.startswith(dir_abs + os.sep)
89
90
91def resolve_motion_names(model) -> list[str]:
92 motion_dir = os.path.normpath(MOTION_DIR)
93 model.Motions.addMotionDirectory(motion_dir)
94 model.Motions.refreshMotionsList()
95
96 all_motions = model.Motions.listMotions()
97 if MOTION_NAMES:
98 model.Motions.setMotionSelection(MOTION_NAMES, selectOnlyListed=True)
99 return list(MOTION_NAMES)
100
101 target_names = [
102 motion.name for motion in all_motions
103 if _motion_file_in_directory(motion.filePath, motion_dir)
104 ]
105 model.Motions.setMotionSelection(target_names, selectOnlyListed=True)
106 return target_names
107
108
109# =============================================================================
110# STEP 4 — Build project files from CSV
111# =============================================================================
112
113@dataclass
114class ProfileLayerRow:
115 thickness_m: float
116 unit_weight: float
117 vs_m_s: float
118 shear_strength_kPa: float
119 soil_type: str
120 curve_model: str
121 reduction_factor_formulation: str
122 ref_params: dict[str, str] = field(default_factory=dict)
123
124
125def _cell(row: dict[str, str], key: str) -> str:
126 return row.get(key, "").strip()
127
128
129def _require_float(row: dict[str, str], key: str) -> float:
130 return float(_cell(row, key))
131
132
133def parse_key_value_params(text: str) -> dict[str, str]:
134 if not text.strip():
135 return {}
136 params: dict[str, str] = {}
137 for part in text.split(";"):
138 part = part.strip()
139 if not part:
140 continue
141 key, _, value = part.partition("=")
142 key, value = key.strip(), value.strip()
143 if key and value:
144 params[key] = value
145 return params
146
147
148def apply_scalar_params(accessor, params: dict[str, str]) -> None:
149 for key, value in params.items():
150 accessor.setDoubleProperty(key, float(value))
151
152
153def load_profile_rows(csv_path: str) -> list[ProfileLayerRow]:
154 csv_path = os.path.normpath(csv_path)
155 with open(csv_path, newline="", encoding="utf-8-sig") as handle:
156 data_lines = [
157 line for line in handle
158 if line.strip() and not line.lstrip().startswith("#")
159 ]
160 reader = csv.DictReader(data_lines)
161
162 rows: list[ProfileLayerRow] = []
163 for raw in reader:
164 if not any(_cell(raw, key) for key in raw):
165 continue
166
167 rows.append(ProfileLayerRow(
168 thickness_m=_require_float(raw, "thickness_m"),
169 unit_weight=_require_float(raw, "unit_weight"),
170 vs_m_s=_require_float(raw, "vs_m_s"),
171 shear_strength_kPa=_require_float(raw, "shear_strength_kPa"),
172 soil_type=_cell(raw, "soil_type"),
173 curve_model=_cell(raw, "curve_model"),
174 reduction_factor_formulation=_cell(raw, "reduction_factor_formulation"),
175 ref_params=parse_key_value_params(_cell(raw, "ref_params")),
176 ))
177
178 return rows
179
180
181def mrdf_fitting_procedure(formulation: str) -> str | None:
182 if formulation == "None":
183 return None
184 if formulation == "MRDF_Darendeli":
185 return "MRDF_Derendeli"
186 return "MRDF_UIUC"
187
188
189def configure_project_settings(model) -> None:
190 model.ProjectSettings.changeUnitSystem(UnitSystem.Metric)
191 model.ProjectSettings.Data.setBoolValue("automaticProfileGeneration", False)
192 model.ProjectSettings.Data.setEnumValue("analysisMode", "Nonlinear")
193 model.ProjectSettings.Data.setEnumValue("defaultSoilModel", "GQ_H")
194 model.ProjectSettings.Data.setEnumValue("hystereticFormulation", "NonMasing")
195
196
197def build_profile_from_csv(model, csv_path: str, profile_name: str = PROFILE_NAME) -> None:
198 rows = load_profile_rows(csv_path)
199 model.Profiles.setActiveProfile(profile_name)
200
201 existing = model.Profiles.listActiveSoilLayers()
202 need = len(rows) - len(existing)
203 if need > 0:
204 model.SoilLayers.appendLayers(need)
205
206 for summary, spec in zip(model.Profiles.listActiveSoilLayers(), rows):
207 layer = model.Profiles.getSoilLayer(summary.layerID)
208
209 layer.setSoilModel("GQ_H")
210 layer.setThickness(spec.thickness_m)
211 layer.setUnitWeight(spec.unit_weight)
212 layer.Data.setDoubleProperty("ShearWaveVelocity", spec.vs_m_s)
213 layer.Data.setDoubleProperty("ShearStrength", spec.shear_strength_kPa)
214
215 ref = layer.ReferenceCurve
216 ref.setSoilType(spec.soil_type)
217 ref.setCurveModel(spec.curve_model)
218 apply_scalar_params(ref.Data, spec.ref_params)
219
220 ref.generateReferenceCurve()
221 fit_proc = mrdf_fitting_procedure(spec.reduction_factor_formulation)
222 if fit_proc is not None:
223 layer.Curve.runCurveFit(fit_proc)
224
225
226def build_all_projects(app: RSSeismicApplication, motion_names: list[str]) -> list[str]:
227 os.makedirs(OUTPUT_PROJECT_DIR, exist_ok=True)
228 project_paths: list[str] = []
229
230 for _, csv_path, project_path in PROJECT_CASES:
231 model = app.newProject()
232 configure_project_settings(model)
233 build_profile_from_csv(model, csv_path)
234 resolve_motion_names(model)
235 model.Motions.setMotionSelection(motion_names, selectOnlyListed=True)
236 model.saveAs(project_path)
237 model.close(saveProject=False)
238 project_paths.append(os.path.normpath(project_path))
239
240 return project_paths
241
242
243# =============================================================================
244# STEP 5 — Batch compute
245# =============================================================================
246
247def run_batch_compute(app: RSSeismicApplication, project_paths: list[str], motion_names: list[str]):
248 batch_result = app.runBatchCompute(
249 project_paths,
250 motion_names=motion_names,
251 parallel_degree=PARALLEL_DEGREE,
252 max_concurrent_analyses=MAX_CONCURRENT_ANALYSES,
253 timeout=COMPUTE_TIMEOUT,
254 close_save_project=False,
255 continue_on_error=CONTINUE_ON_ERROR,
256 )
257
258 ok = sum(1 for job in batch_result.results if job.success and not job.partial_success)
259 partial = sum(1 for job in batch_result.results if job.success and job.partial_success)
260 failed = sum(1 for job in batch_result.results if not job.success)
261 print()
262 print("=" * 70)
263 print(f" Batch complete — {len(batch_result.results)} project(s)")
264 print(f" Full success : {ok} Partial : {partial} Failed : {failed}")
265 print("=" * 70)
266 for job in batch_result.results:
267 name = os.path.basename(job.file_path)
268 status = "OK" if job.success and not job.partial_success else (
269 "PARTIAL" if job.success else "FAILED"
270 )
271 print(f" [{status:7s}] {name}")
272 if job.error_message:
273 print(f" {job.error_message}")
274 print()
275
276 return batch_result
277
278
279# =============================================================================
280# STEP 6 — Read results from disk
281# =============================================================================
282
283DB3_FILENAME = "deepsoilout.db3"
284MOTION_FOLDER_PREFIX = "Motion_"
285RS_LAYER_INDEX = 1
286
287
288def compute_results_root(project_path: str) -> str:
289 project_path = os.path.normpath(project_path)
290 project_dir = os.path.dirname(project_path)
291 stem = os.path.splitext(os.path.basename(project_path))[0]
292 return os.path.join(project_dir, stem)
293
294
295def iter_deepsoilout_db3(results_root: str):
296 if not os.path.isdir(results_root):
297 return
298
299 for profile_folder in sorted(os.listdir(results_root)):
300 profile_dir = os.path.join(results_root, profile_folder)
301 if not os.path.isdir(profile_dir):
302 continue
303 for motion_folder in sorted(os.listdir(profile_dir)):
304 if not motion_folder.startswith(MOTION_FOLDER_PREFIX):
305 continue
306 db3_path = os.path.join(profile_dir, motion_folder, DB3_FILENAME)
307 if os.path.isfile(db3_path):
308 motion_label = motion_folder[len(MOTION_FOLDER_PREFIX):]
309 yield profile_folder, motion_label, db3_path
310
311
312def read_standard_db3(db3_path: str, rs_layer_index: int = RS_LAYER_INDEX) -> tuple[
313 np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray,
314]:
315 rs_column = f"LAYER{rs_layer_index}_RS"
316 with sqlite3.connect(db3_path) as conn:
317 rs_rows = conn.execute(
318 f"SELECT PERIOD, {rs_column} FROM RESPONSE_SPECTRA"
319 ).fetchall()
320 profile_rows = conn.execute(
321 "SELECT DEPTH_LAYER_MID, MAX_STRAIN, PGA_TOTAL FROM PROFILES"
322 ).fetchall()
323
324 periods = np.array([row[0] for row in rs_rows], dtype=float)
325 rs_values = np.array([row[1] for row in rs_rows], dtype=float)
326 depths = np.array([row[0] for row in profile_rows], dtype=float)
327 strains = np.array([row[1] for row in profile_rows], dtype=float)
328 pga_values = np.array([row[2] for row in profile_rows], dtype=float)
329 return periods, rs_values, depths, strains, pga_values
330
331
332@dataclass
333class AggregatedSamples:
334 rs_periods: list[np.ndarray] = field(default_factory=list)
335 rs_values: list[np.ndarray] = field(default_factory=list)
336 strain_depths: list[np.ndarray] = field(default_factory=list)
337 strain_values: list[np.ndarray] = field(default_factory=list)
338 pga_depths: list[np.ndarray] = field(default_factory=list)
339 pga_values: list[np.ndarray] = field(default_factory=list)
340 rs_units: dict[str, str] = field(default_factory=dict)
341 depth_units: dict[str, str] = field(default_factory=dict)
342 pga_units: dict[str, str] = field(default_factory=dict)
343
344
345def collect_results_from_disk(project_paths: list[str]) -> AggregatedSamples:
346 samples = AggregatedSamples()
347 samples.rs_units = {"period": "s", "rs": "g"}
348 samples.depth_units = {"depth": "m"}
349 samples.pga_units = {"pga": "g"}
350
351 allowed_motions: set[str] | None = None
352 if MOTION_NAMES:
353 allowed_motions = set(MOTION_NAMES)
354
355 for project_path in project_paths:
356 results_root = compute_results_root(project_path)
357 for profile_folder, motion_label, db3_path in iter_deepsoilout_db3(results_root):
358 if allowed_motions and motion_label not in allowed_motions:
359 continue
360
361 periods, rs_values, depths, strains, pga_values = read_standard_db3(db3_path)
362 samples.rs_periods.append(periods)
363 samples.rs_values.append(rs_values)
364 samples.strain_depths.append(depths)
365 samples.strain_values.append(strains)
366 samples.pga_depths.append(depths)
367 samples.pga_values.append(pga_values)
368
369 return samples
370
371
372# =============================================================================
373# STEP 7 — Aggregate and plot
374# =============================================================================
375
376matplotlib.rcParams.update({
377 "font.family": "Times New Roman",
378 "font.size": 12,
379 "axes.labelsize": 12,
380 "legend.fontsize": 12,
381 "xtick.labelsize": 12,
382 "ytick.labelsize": 12,
383})
384_INDIVIDUAL = dict(color="silver", linewidth=0.7, alpha=0.65, marker="o", markersize=3)
385_MEAN = dict(color="black", linewidth=1.5, marker="o", markersize=4)
386_BOUND = dict(color="black", linewidth=1.0, linestyle="--", marker="o", markersize=3)
387
388
389def strain_to_percent(strain: np.ndarray) -> np.ndarray:
390 return strain.astype(float) * 100.0
391
392
393def log_mean_std(
394 x_arrays: list[np.ndarray],
395 y_arrays: list[np.ndarray],
396 common_x: np.ndarray,
397 *,
398 log_x: bool = False,
399 log_y: bool = True,
400) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
401 n_pts = len(common_x)
402 n_samp = len(x_arrays)
403 matrix = np.full((n_pts, n_samp), np.nan)
404
405 cx = np.log(common_x) if log_x else common_x
406 for j, (x, y) in enumerate(zip(x_arrays, y_arrays)):
407 order = np.argsort(x)
408 xs, ys = x[order], y[order]
409 xj = np.log(np.clip(xs, 1e-300, None)) if log_x else xs
410 matrix[:, j] = np.interp(cx, xj, ys)
411
412 valid = np.isfinite(matrix) & (matrix > 0)
413 if log_y:
414 with np.errstate(divide="ignore", invalid="ignore"):
415 ln_mat = np.where(valid, np.log(matrix), np.nan)
416 mu = np.nanmean(ln_mat, axis=1)
417 sigma = np.nanstd(ln_mat, axis=1, ddof=1)
418 return np.exp(mu), np.exp(mu + sigma), np.exp(mu - sigma)
419
420 mu = np.nanmean(matrix, axis=1)
421 sigma = np.nanstd(matrix, axis=1, ddof=1)
422 return mu, mu + sigma, mu - sigma
423
424
425def aggregate_by_layer_index(
426 depth_arrays: list[np.ndarray],
427 value_arrays: list[np.ndarray],
428 *,
429 log_y: bool = True,
430) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
431 max_layers = max(len(d) for d in depth_arrays)
432 mean_depths: list[float] = []
433 val_means: list[float] = []
434 val_uppers: list[float] = []
435 val_lowers: list[float] = []
436
437 for layer_idx in range(max_layers):
438 depths: list[float] = []
439 values: list[float] = []
440 for depth_arr, value_arr in zip(depth_arrays, value_arrays):
441 if layer_idx < len(depth_arr):
442 depths.append(float(depth_arr[layer_idx]))
443 values.append(float(value_arr[layer_idx]))
444 if not values:
445 continue
446
447 values_arr = np.array(values, dtype=float)
448 if log_y:
449 positive = values_arr[values_arr > 0]
450 if positive.size == 0:
451 continue
452 ln_vals = np.log(positive)
453 mu = float(np.mean(ln_vals))
454 sigma = float(np.std(ln_vals, ddof=1)) if positive.size > 1 else 0.0
455 val_means.append(math.exp(mu))
456 val_uppers.append(math.exp(mu + sigma))
457 val_lowers.append(math.exp(mu - sigma))
458 else:
459 mu = float(np.mean(values_arr))
460 sigma = float(np.std(values_arr, ddof=1)) if values_arr.size > 1 else 0.0
461 val_means.append(mu)
462 val_uppers.append(mu + sigma)
463 val_lowers.append(mu - sigma)
464 mean_depths.append(float(np.mean(depths)))
465
466 return (
467 np.array(mean_depths),
468 np.array(val_means),
469 np.array(val_uppers),
470 np.array(val_lowers),
471 )
472
473
474def _sorted_layer_profile(values: np.ndarray, depths: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
475 order = np.argsort(depths)
476 return values[order], depths[order]
477
478
479def plot_aggregated(samples: AggregatedSamples, output_dir: str) -> None:
480 n = len(samples.rs_periods)
481 print(f"Total samples (project × motion pairs): {n}")
482
483 period_unit = samples.rs_units.get("period", "s")
484 rs_unit = samples.rs_units.get("rs", "g")
485 depth_unit = samples.depth_units.get("depth", "m")
486 pga_unit = samples.pga_units.get("pga", "g")
487
488 period_grid = np.sort(samples.rs_periods[0][samples.rs_periods[0] > 0])
489 rs_mean, rs_upper, rs_lower = log_mean_std(
490 samples.rs_periods, samples.rs_values, period_grid, log_x=True, log_y=True,
491 )
492
493 fig1, ax1 = plt.subplots(figsize=(5, 4.5))
494 for xp, yp in zip(samples.rs_periods, samples.rs_values):
495 ax1.semilogx(xp, yp, **_INDIVIDUAL)
496 ax1.semilogx(period_grid, rs_mean, label=r"$\mu_{\ln}$", **_MEAN)
497 ax1.semilogx(period_grid, rs_upper, label=r"$\mu_{\ln} \pm \sigma_{\ln}$", **_BOUND)
498 ax1.semilogx(period_grid, rs_lower, **_BOUND)
499 ax1.set_xscale("log")
500 ax1.set_yscale("linear")
501 ax1.set_xlabel(f"Period ({period_unit})")
502 ax1.set_ylabel(f"Spectral Acceleration ({rs_unit})")
503 ax1.legend(frameon=False)
504 ax1.grid(True, which="both", alpha=0.3)
505 fig1.tight_layout()
506
507 strain_pct_samples = [strain_to_percent(v) for v in samples.strain_values]
508 s_depths, s_mean, s_upper, s_lower = aggregate_by_layer_index(
509 samples.strain_depths, strain_pct_samples, log_y=True,
510 )
511
512 fig2, ax2 = plt.subplots(figsize=(4, 5.5))
513 for strain_pct, depths in zip(strain_pct_samples, samples.strain_depths):
514 xs, ys = _sorted_layer_profile(strain_pct, depths)
515 ax2.plot(xs, ys, **_INDIVIDUAL)
516 ax2.plot(s_mean, s_depths, label=r"$\mu_{\ln}$", **_MEAN)
517 ax2.plot(s_upper, s_depths, label=r"$\mu_{\ln} \pm \sigma_{\ln}$", **_BOUND)
518 ax2.plot(s_lower, s_depths, **_BOUND)
519 ax2.set_xlabel("Max Shear Strain (%)")
520 ax2.set_ylabel(f"Depth ({depth_unit})")
521 ax2.invert_yaxis()
522 ax2.legend(frameon=False)
523 ax2.grid(True, which="major", alpha=0.3)
524 fig2.tight_layout()
525
526 p_depths, p_mean, p_upper, p_lower = aggregate_by_layer_index(
527 samples.pga_depths, samples.pga_values, log_y=True,
528 )
529
530 fig3, ax3 = plt.subplots(figsize=(4, 5.5))
531 for pga, depths in zip(samples.pga_values, samples.pga_depths):
532 xs, ys = _sorted_layer_profile(pga, depths)
533 ax3.plot(xs, ys, **_INDIVIDUAL)
534 ax3.plot(p_mean, p_depths, label=r"$\mu_{\ln}$", **_MEAN)
535 ax3.plot(p_upper, p_depths, label=r"$\mu_{\ln} \pm \sigma_{\ln}$", **_BOUND)
536 ax3.plot(p_lower, p_depths, **_BOUND)
537 ax3.set_xlabel(f"PGA ({pga_unit})")
538 ax3.set_ylabel(f"Depth ({depth_unit})")
539 ax3.invert_yaxis()
540 ax3.legend(frameon=False)
541 ax3.grid(True, which="major", alpha=0.3)
542 fig3.tight_layout()
543
544 os.makedirs(output_dir, exist_ok=True)
545 for fig, name in [
546 (fig1, "response_spectra.png"),
547 (fig2, "max_strain_profile.png"),
548 (fig3, "pga_profile.png"),
549 ]:
550 path = os.path.join(output_dir, name)
551 fig.savefig(path, dpi=150, bbox_inches="tight")
552 print(f"Saved: {path}")
553 plt.close(fig)
554
555
556# =============================================================================
557# Main — run Steps 2–7
558# =============================================================================
559
560def main() -> None:
561 app = connect_app()
562
563 # Step 3 — Resolve motion names once
564 probe = app.newProject()
565 motion_names = resolve_motion_names(probe)
566 probe.close(saveProject=False)
567
568 # Step 4 — Build and save all projects
569 project_paths = build_all_projects(app, motion_names)
570
571 # Step 5 — Batch compute
572 run_batch_compute(app, project_paths, motion_names)
573 app.close()
574
575 # Step 6 — Read results from disk
576 samples = collect_results_from_disk(project_paths)
577
578 # Step 7 — Aggregate and plot
579 plot_aggregated(samples, OUTPUT_PLOT_DIR)
580
581
582if __name__ == "__main__":
583 main()