Match ground motions to target spectra#
Script the Motion Manager wizard Match ground motions to target spectra. Scaled motions are written into a folder listed under RSSeismic Preferences → Motions (same rules as convert / database import).
The example supports both wizard paths:
Manual
Discover H1/H2 pairs under a folder (and subfolders).
Select pairs (
selectAllor specific pair ids).Load target spectra (here: a user-defined period–Sa text file via
getTargetSpectra(UserDefinedTargetSpectraModel(...)); REXEL and NSHMP models work the same way).Call
matchToTargetSpectraManualwith amplitude scaling parameters.
Automatic (GMDB or ESM only; CESMD is not supported)
authenticateDatabasefor the session.Load target spectra.
Call
matchToTargetSpectraAutomaticwith search filters and optionalRecordSelectionParams(wizard knobs:nGm, damping, tolerance,isScaled,maxCandidates,defaultSigmaLn). Period window and scale-factor bounds come fromAmplitudeScalingParams.
Note
Pair discovery returns an empty selection. Always select / selectAll
before Manual match. For Automatic, authenticate first (same as search/import).
1"""
2Match ground motions to a target spectrum (Motion Manager wizard scripting).
3
4Mirrors Preferences → Motions → "Match ground motions to target spectra".
5
6Two modes (same as the wizard):
7
8 Manual
9 1. Discover H1/H2 pairs in a folder
10 2. Select which pairs to use
11 3. Load or build target spectra
12 4. Amplitude-scale selected pairs into a Motion Manager folder
13
14 Automatic (GMDB or ESM only — not CESMD)
15 1. Authenticate to the database
16 2. Provide search filters + optional selection knobs
17 3. Load or build target spectra
18 4. Record selection + scaling into a Motion Manager folder
19
20``outputDirectory`` must already be listed in RSSeismic Preferences → Motions.
21
22Examples:
23
24 # Manual — user-defined spectrum file + all pairs in a folder
25 python examples/example_match_to_target_spectra.py manual ^
26 --output-dir "D:\\Motions\\Library" ^
27 --pairs-folder "D:\\RawPairs" ^
28 --target-file "D:\\spectra\\design_sa.txt"
29
30 # Manual — only specific pair ids
31 python examples/example_match_to_target_spectra.py manual ^
32 --output-dir "D:\\Motions\\Library" ^
33 --pairs-folder "D:\\RawPairs" ^
34 --target-file "D:\\spectra\\design_sa.txt" ^
35 --pair-ids EventA EventB
36
37 # Automatic — GMDB selection against a spectrum file
38 python examples/example_match_to_target_spectra.py automatic ^
39 --output-dir "D:\\Motions\\Library" ^
40 --target-file "D:\\spectra\\design_sa.txt" ^
41 --database GMDB --username USER --password PASS ^
42 --magnitude-min 6 --magnitude-max 8 --n-gm 11
43"""
44
45from __future__ import annotations
46
47import argparse
48import os
49import sys
50
51from rsseismic import (
52 AmplitudeScalingParams,
53 DatabaseSearchFilters,
54 DoubleRange,
55 GroundMotionDatabase,
56 RecordSelectionParams,
57 RSSeismicApplication,
58 UserDefinedTargetSpectraModel,
59)
60from rsseismic._client import DEFAULT_SCRIPTING_PORT
61
62_DATABASE_CHOICES = {
63 "GMDB": GroundMotionDatabase.GMDB,
64 "ESM": GroundMotionDatabase.ESM,
65}
66
67
68def _parse_database(name: str) -> GroundMotionDatabase:
69 key = name.strip().upper()
70 if key not in _DATABASE_CHOICES:
71 raise ValueError(f"Unknown database '{name}'. Use GMDB or ESM (Automatic does not support CESMD).")
72 return _DATABASE_CHOICES[key]
73
74
75def _print_match_result(label: str, result) -> None:
76 print(f"\n{label}")
77 print(f" Saved motions ({len(result.savedMotionNames)}):")
78 for name in result.savedMotionNames:
79 print(f" {name}")
80 if result.failedPairIds:
81 print(f" Failed pair ids: {result.failedPairIds}")
82 if result.scaleFactors:
83 print(" Scale factors:")
84 for item in result.scaleFactors:
85 print(f" {item.pairId}: {item.scaleFactor:.4f}")
86
87
88def run_manual(
89 output_dir: str,
90 pairs_folder: str,
91 target_file: str,
92 port: int,
93 pair_ids: list[str] | None,
94 overwrite: bool,
95 t1: float,
96 t2: float,
97) -> None:
98 output_dir = os.path.abspath(output_dir)
99 pairs_folder = os.path.abspath(pairs_folder)
100 target_file = os.path.abspath(target_file)
101
102 if not os.path.isdir(output_dir):
103 raise ValueError(f"output-dir is not a folder: {output_dir}")
104 if not os.path.isdir(pairs_folder):
105 raise ValueError(f"pairs-folder is not a folder: {pairs_folder}")
106 if not os.path.isfile(target_file):
107 raise ValueError(f"target-file not found: {target_file}")
108
109 app = RSSeismicApplication(port=port)
110 try:
111 app.ping()
112 library = app.MotionLibrary
113
114 # Step 1 — discover pairs (same idea as the wizard Manual pick list)
115 print(f"1) Discovering motion pairs under {pairs_folder}...")
116 discovered = library.discoverMotionPairsInFolder(pairs_folder)
117 print(f" Found {len(discovered.allPairs)} pair(s).")
118 for pair in discovered.allPairs:
119 print(f" {pair.pairId}: {pair.motionH1Name} / {pair.motionH2Name}")
120 if not discovered.allPairs:
121 print(" Nothing to scale.")
122 return
123
124 # Step 2 — select pairs (selection starts empty)
125 if pair_ids:
126 print(f"2) Selecting pair id(s): {', '.join(pair_ids)}")
127 discovered.select(pair_ids)
128 else:
129 print("2) Selecting all discovered pairs...")
130 discovered.selectAll()
131 print(f" Selected {len(discovered.selectedPairs)} pair(s).")
132
133 # Step 3 — target spectra (user-defined file; REXEL/NSHMP also work via getTargetSpectra)
134 print(f"3) Loading target spectra from {target_file}...")
135 target = library.getTargetSpectra(UserDefinedTargetSpectraModel(filePath=target_file))
136 print(f" {len(target.points)} period–Sa point(s).")
137
138 # Step 4 — amplitude match into a preference folder
139 print(f"4) Matching selected pairs into {output_dir}...")
140 result = library.matchToTargetSpectraManual(
141 targetSpectra=target,
142 pairs=discovered.selectedPairs,
143 outputDirectory=output_dir,
144 amplitude=AmplitudeScalingParams(t1=t1, t2=t2),
145 overwrite=overwrite,
146 )
147 _print_match_result("Manual match result", result)
148 finally:
149 app.close()
150
151
152def run_automatic(
153 output_dir: str,
154 target_file: str,
155 database: GroundMotionDatabase,
156 username: str,
157 password: str,
158 port: int,
159 overwrite: bool,
160 magnitude_min: float,
161 magnitude_max: float,
162 n_gm: int,
163 t1: float,
164 t2: float,
165) -> None:
166 output_dir = os.path.abspath(output_dir)
167 target_file = os.path.abspath(target_file)
168
169 if not os.path.isdir(output_dir):
170 raise ValueError(f"output-dir is not a folder: {output_dir}")
171 if not os.path.isfile(target_file):
172 raise ValueError(f"target-file not found: {target_file}")
173 if not password.strip():
174 raise ValueError("--password is required for GMDB and ESM.")
175
176 db_label = "ESM" if database == GroundMotionDatabase.ESM else database.name
177 app = RSSeismicApplication(port=port)
178 try:
179 app.ping()
180 library = app.MotionLibrary
181
182 # Step 1 — authenticate (required before Automatic / search / import)
183 print(f"1) Authenticating with {db_label}...")
184 library.authenticateDatabase(
185 database=database,
186 username=username,
187 password=password,
188 )
189
190 # Step 2 — target spectra
191 print(f"2) Loading target spectra from {target_file}...")
192 target = library.getTargetSpectra(UserDefinedTargetSpectraModel(filePath=target_file))
193 print(f" {len(target.points)} period–Sa point(s).")
194
195 # Step 3 — filters + selection knobs (wizard Automatic panel)
196 filters = DatabaseSearchFilters(
197 magnitude=DoubleRange(min=magnitude_min, max=magnitude_max),
198 )
199 selection = RecordSelectionParams(nGm=n_gm)
200 print(
201 f"3) Running Automatic selection on {db_label} "
202 f"(magnitude {magnitude_min}–{magnitude_max}, nGm={n_gm})..."
203 )
204
205 # Step 4 — select + scale into preference folder
206 result = library.matchToTargetSpectraAutomatic(
207 database=database,
208 filters=filters,
209 targetSpectra=target,
210 outputDirectory=output_dir,
211 selection=selection,
212 amplitude=AmplitudeScalingParams(t1=t1, t2=t2),
213 overwrite=overwrite,
214 )
215 _print_match_result("Automatic match result", result)
216 finally:
217 app.close()
218
219
220def parse_args() -> argparse.Namespace:
221 parser = argparse.ArgumentParser(
222 description="Match ground motions to target spectra (Manual or Automatic).",
223 )
224 parser.add_argument(
225 "mode",
226 choices=("manual", "automatic"),
227 help="Wizard path: manual (folder pairs) or automatic (GMDB/ESM selection).",
228 )
229 parser.add_argument(
230 "--output-dir",
231 "-o",
232 required=True,
233 help="Motion Manager preference folder (Preferences → Motions).",
234 )
235 parser.add_argument(
236 "--target-file",
237 "-t",
238 required=True,
239 help="User-defined target spectrum text file (period and Sa columns).",
240 )
241 parser.add_argument(
242 "--pairs-folder",
243 help="Folder of H1/H2 motion files (Manual mode; scanned with subfolders).",
244 )
245 parser.add_argument(
246 "--pair-ids",
247 nargs="+",
248 default=[],
249 help="Optional Manual pair ids to select (default: select all discovered pairs).",
250 )
251 parser.add_argument(
252 "--database",
253 "-d",
254 default="GMDB",
255 choices=sorted(_DATABASE_CHOICES.keys()),
256 help="Automatic mode database (GMDB or ESM; default: GMDB).",
257 )
258 parser.add_argument(
259 "--username",
260 "-u",
261 default="",
262 help="Database username (Automatic mode).",
263 )
264 parser.add_argument(
265 "--password",
266 "-w",
267 default="",
268 help="Database password (Automatic mode).",
269 )
270 parser.add_argument(
271 "--magnitude-min",
272 type=float,
273 default=6.0,
274 help="Automatic search: minimum magnitude (default: 6.0).",
275 )
276 parser.add_argument(
277 "--magnitude-max",
278 type=float,
279 default=8.0,
280 help="Automatic search: maximum magnitude (default: 8.0).",
281 )
282 parser.add_argument(
283 "--n-gm",
284 type=int,
285 default=11,
286 help="Automatic: number of ground motions to select (default: 11).",
287 )
288 parser.add_argument(
289 "--t1",
290 type=float,
291 default=0.01,
292 help="Amplitude scaling period window start, seconds (default: 0.01).",
293 )
294 parser.add_argument(
295 "--t2",
296 type=float,
297 default=10.0,
298 help="Amplitude scaling period window end, seconds (default: 10).",
299 )
300 parser.add_argument(
301 "--overwrite",
302 action="store_true",
303 help="Overwrite existing library motions with the same name.",
304 )
305 parser.add_argument(
306 "--port",
307 "-p",
308 type=int,
309 default=int(os.environ.get("RSSEISMIC_SCRIPTING_PORT", DEFAULT_SCRIPTING_PORT)),
310 help=f"gRPC port (default: {DEFAULT_SCRIPTING_PORT}, or RSSEISMIC_SCRIPTING_PORT)",
311 )
312 return parser.parse_args()
313
314
315def main() -> int:
316 args = parse_args()
317 try:
318 if args.mode == "manual":
319 if not args.pairs_folder:
320 raise ValueError("Manual mode requires --pairs-folder.")
321 run_manual(
322 output_dir=args.output_dir,
323 pairs_folder=args.pairs_folder,
324 target_file=args.target_file,
325 port=args.port,
326 pair_ids=args.pair_ids or None,
327 overwrite=args.overwrite,
328 t1=args.t1,
329 t2=args.t2,
330 )
331 else:
332 if not args.username.strip():
333 raise ValueError("Automatic mode requires --username.")
334 run_automatic(
335 output_dir=args.output_dir,
336 target_file=args.target_file,
337 database=_parse_database(args.database),
338 username=args.username,
339 password=args.password,
340 port=args.port,
341 overwrite=args.overwrite,
342 magnitude_min=args.magnitude_min,
343 magnitude_max=args.magnitude_max,
344 n_gm=args.n_gm,
345 t1=args.t1,
346 t2=args.t2,
347 )
348 except Exception as ex:
349 print(f"Example failed: {ex}", file=sys.stderr)
350 return 1
351 print("\nMatch to target spectra example finished.")
352 return 0
353
354
355if __name__ == "__main__":
356 raise SystemExit(main())