Import records from GMDB / CESMD / ESM#

Authenticate once for the scripting session, then search an external ground-motion database and import selected records into the Motion Manager library. outputDirectory must be a folder listed in RSSeismic Preferences → Motions.

Use --database GMDB, CESMD, or ESM. CESMD uses an email username and does not require a password; GMDB and ESM require both. Pass full DatabaseRecordInfo objects from search into import (download fields differ by database; search results already include what import needs).

DatabaseSearchFilters exposes the wizard-visible filter union for all three databases (unused fields for a DB are ignored). Option-list values are strings; multi-select networks and similar fields use comma-separated codes (for example \"CI,NP\"). PGA filters are in g. Dates are yyyy-MM-dd. GMDB enums are typed as ProcessingType, MagnitudeType, and EventType. Pass maxResults to searchDatabaseRecords (or --max-results in the example) to cap returned hits; --max-records still controls how many of those hits are imported.

Note

GroundMotionDatabase.ESM is the public name for the Engineering Strong-Motion database. On the wire it maps to the server enum value historically named FDSN.

  1"""
  2Search GMDB / CESMD / ESM and import selected records into the Motion Manager library.
  3
  4Requires a running RSSeismic scripting server. No project file is needed.
  5``outputDirectory`` must be one of the Motion Manager preference folders
  6(RSSeismic Preferences → Motions).
  7
  8Authenticate once per database for the scripting session, then search/import
  9without credentials on those calls.
 10
 11  python examples/example_import_database_records.py --output-dir "D:\\Motions" --database GMDB --username USER --password PASS
 12  python examples/example_import_database_records.py --output-dir "D:\\Motions" --database CESMD --username email@example.com --max-results 20 --max-records 3
 13  python examples/example_import_database_records.py --output-dir "D:\\Motions" --database ESM --username email@example.com --password PASS --network-code IV --overwrite
 14"""
 15
 16from __future__ import annotations
 17
 18import argparse
 19import os
 20import sys
 21
 22from rsseismic import (
 23    DatabaseSearchFilters,
 24    DoubleRange,
 25    GroundMotionDatabase,
 26    ProcessingType,
 27    RSSeismicApplication,
 28)
 29from rsseismic._client import DEFAULT_SCRIPTING_PORT
 30
 31_DATABASE_CHOICES = {
 32    "GMDB": GroundMotionDatabase.GMDB,
 33    "CESMD": GroundMotionDatabase.CESMD,
 34    "ESM": GroundMotionDatabase.ESM,
 35}
 36
 37
 38def _parse_database(name: str) -> GroundMotionDatabase:
 39    key = name.strip().upper()
 40    if key not in _DATABASE_CHOICES:
 41        raise ValueError(f"Unknown database '{name}'. Use GMDB, CESMD, or ESM.")
 42    return _DATABASE_CHOICES[key]
 43
 44
 45def run_import_example(
 46    output_dir: str,
 47    database: GroundMotionDatabase,
 48    username: str,
 49    password: str,
 50    port: int = DEFAULT_SCRIPTING_PORT,
 51    max_results: int | None = None,
 52    max_records: int = 5,
 53    overwrite: bool = False,
 54    magnitude_min: float = 6.0,
 55    magnitude_max: float = 8.0,
 56    network_code: str = "",
 57) -> None:
 58    output_dir = os.path.abspath(output_dir)
 59    if not os.path.isdir(output_dir):
 60        raise ValueError(f"output-dir is not a folder: {output_dir}")
 61    if max_records < 1:
 62        raise ValueError("--max-records must be at least 1")
 63    if max_results is not None and max_results < 1:
 64        raise ValueError("--max-results must be at least 1 when set")
 65    if database != GroundMotionDatabase.CESMD and not password.strip():
 66        raise ValueError("--password is required for GMDB and ESM (optional for CESMD).")
 67
 68    db_label = "ESM" if database == GroundMotionDatabase.ESM else database.name
 69    app = RSSeismicApplication(port=port)
 70    try:
 71        app.ping()
 72        library = app.MotionLibrary
 73
 74        print(f"Authenticating with {db_label}...")
 75        library.authenticateDatabase(
 76            database=database,
 77            username=username,
 78            password=password,
 79        )
 80
 81        filters = DatabaseSearchFilters(
 82            magnitude=DoubleRange(min=magnitude_min, max=magnitude_max),
 83            networkCode=network_code.strip(),
 84            # GMDB-only enum example (ignored on CESMD/ESM):
 85            processingType=(
 86                ProcessingType.MANUAL if database == GroundMotionDatabase.GMDB else None
 87            ),
 88        )
 89        print(
 90            f"Searching {db_label} (magnitude {magnitude_min}–{magnitude_max}"
 91            + (f", network={network_code}" if network_code.strip() else "")
 92            + ")..."
 93        )
 94        records = library.searchDatabaseRecords(
 95            database=database,
 96            filters=filters,
 97            maxResults=max_results,
 98        )
 99        print(f"Found {len(records)} record(s).")
100        if not records:
101            return
102
103        selected = records[:max_records]
104        for record in selected:
105            print(
106                f"  {record.id}  {record.eventName}  station={record.station}  "
107                f"M={record.magnitude}  PGA_H1={record.maxAccelH1G} g"
108            )
109
110        print(f"\nImporting {len(selected)} record(s) into {output_dir}...")
111        result = library.importDatabaseRecords(
112            database=database,
113            outputDirectory=output_dir,
114            records=selected,
115            overwrite=overwrite,
116        )
117        print(f"Imported: {result.importedMotionNames}")
118        if result.failedRecordIds:
119            print(f"Failed:   {result.failedRecordIds}")
120    finally:
121        app.close()
122
123
124def parse_args() -> argparse.Namespace:
125    parser = argparse.ArgumentParser(
126        description="Search GMDB/CESMD/ESM and import records into Motion Manager."
127    )
128    parser.add_argument(
129        "--output-dir",
130        "-o",
131        required=True,
132        help="Motion Manager preference folder.",
133    )
134    parser.add_argument(
135        "--database",
136        "-d",
137        default="GMDB",
138        choices=sorted(_DATABASE_CHOICES.keys()),
139        help="External database (default: GMDB).",
140    )
141    parser.add_argument(
142        "--username",
143        "-u",
144        required=True,
145        help="Database username (email for CESMD/ESM).",
146    )
147    parser.add_argument(
148        "--password",
149        "-w",
150        default="",
151        help="Database password (required for GMDB/ESM; optional for CESMD).",
152    )
153    parser.add_argument(
154        "--max-results",
155        type=int,
156        default=None,
157        help="Optional server-side cap on search hits (omit = no truncate).",
158    )
159    parser.add_argument(
160        "--max-records",
161        type=int,
162        default=5,
163        help="Maximum number of returned hits to import (default: 5).",
164    )
165    parser.add_argument(
166        "--magnitude-min",
167        type=float,
168        default=6.0,
169        help="Minimum magnitude filter (default: 6.0).",
170    )
171    parser.add_argument(
172        "--magnitude-max",
173        type=float,
174        default=8.0,
175        help="Maximum magnitude filter (default: 8.0).",
176    )
177    parser.add_argument(
178        "--network-code",
179        default="",
180        help='Optional network code filter (CESMD/ESM multi: "CI,NP").',
181    )
182    parser.add_argument(
183        "--overwrite",
184        action="store_true",
185        help="Overwrite existing library motions with the same name.",
186    )
187    parser.add_argument(
188        "--port",
189        "-p",
190        type=int,
191        default=int(os.environ.get("RSSEISMIC_SCRIPTING_PORT", DEFAULT_SCRIPTING_PORT)),
192        help=f"gRPC port (default: {DEFAULT_SCRIPTING_PORT}, or RSSEISMIC_SCRIPTING_PORT)",
193    )
194    return parser.parse_args()
195
196
197def main() -> int:
198    args = parse_args()
199    try:
200        run_import_example(
201            output_dir=args.output_dir,
202            database=_parse_database(args.database),
203            username=args.username,
204            password=args.password,
205            port=args.port,
206            max_results=args.max_results,
207            max_records=args.max_records,
208            overwrite=args.overwrite,
209            magnitude_min=args.magnitude_min,
210            magnitude_max=args.magnitude_max,
211            network_code=args.network_code,
212        )
213    except Exception as ex:
214        print(f"Example failed: {ex}", file=sys.stderr)
215        return 1
216    print("\nImport database records example finished.")
217    return 0
218
219
220if __name__ == "__main__":
221    raise SystemExit(main())