Import boreholes from RSLog#
Create a blank project, list RSLog projects and boreholes from a JSON export
or an authenticated RSLog account, import selected test holes as profiles,
then save a .rsseismicfile you can open in RSSeismic to inspect the result.
File source uses the Imperial fixture under tests/resources/ by default
(no login). Account source requires --company, --username, and
--password. The script prefers boreholes that already have a drilling
groundwater depth (or piezometer measurements) and imports them with the
default water table applied.
python examples/example_rslog_import.py --source file
python examples/example_rslog_import.py --source account --company COMPANY --username USER --password PASS
1"""
2Import RSLog boreholes into a new RSSeismic project (JSON file or account).
3
4Requires a running RSSeismic scripting server. Creates a blank project, lists
5projects/boreholes from the chosen source, imports selected holes as profiles,
6then saves a ``.rsseismicfile`` you can open in RSSeismic to inspect.
7
8File source (no login; uses the Imperial fixture under tests/resources by default):
9
10 python examples/example_rslog_import.py --source file
11 python examples/example_rslog_import.py --source file --json "D:\\path\\export.json" --output "D:\\out\\rslog.rsseismicfile"
12
13Account source (authenticate once, then list/import):
14
15 python examples/example_rslog_import.py --source account --company rocscience --username USER --password PASS
16"""
17
18from __future__ import annotations
19
20import argparse
21import os
22import sys
23
24from rsseismic import (
25 MultiProfilePolicy,
26 ProfileMergeMode,
27 RSLogBoreholeImportSpec,
28 RSLogBoreholeInfo,
29 RSLogGroundwaterSelection,
30 RSLogProjectInfo,
31 RSSeismicApplication,
32 UnitMismatchPolicy,
33)
34from rsseismic._client import DEFAULT_SCRIPTING_PORT
35
36_REPO_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
37_DEFAULT_JSON = os.path.join(
38 _REPO_ROOT,
39 "tests",
40 "resources",
41 "RSLog Example Project #1 (Imperial).json",
42)
43_DEFAULT_OUTPUT = os.path.join(
44 os.path.dirname(os.path.abspath(__file__)),
45 "output",
46 "rslog_import_example.rsseismicfile",
47)
48
49
50def _has_valid_water_table(borehole: RSLogBoreholeInfo) -> bool:
51 depth = borehole.defaultDrillingGroundwaterDepth
52 if depth is not None and depth >= 0:
53 return True
54 return any(p.groundwaterMeasurementCount > 0 for p in borehole.piezometers)
55
56
57def _water_table_label(borehole: RSLogBoreholeInfo) -> str:
58 depth = borehole.defaultDrillingGroundwaterDepth
59 if depth is not None and depth >= 0:
60 return f"drilling GW depth={depth}"
61 piezometers = [p for p in borehole.piezometers if p.groundwaterMeasurementCount > 0]
62 if piezometers:
63 counts = ", ".join(
64 f"{p.number or p.id}:{p.groundwaterMeasurementCount}" for p in piezometers
65 )
66 return f"piezometer measurements ({counts})"
67 return "no water table"
68
69
70def _find_project_with_water_table_boreholes(
71 app: RSSeismicApplication,
72 projects: list[RSLogProjectInfo],
73 list_kwargs: dict,
74 max_boreholes: int,
75) -> tuple[RSLogProjectInfo, list[RSLogBoreholeInfo]]:
76 best_project: RSLogProjectInfo | None = None
77 best_boreholes: list[RSLogBoreholeInfo] = []
78
79 for project in projects:
80 if project.totalTestHoles <= 0:
81 continue
82 boreholes = app.RSLog.listBoreholes(project.id, **list_kwargs)
83 with_water = [b for b in boreholes if _has_valid_water_table(b)]
84 if len(with_water) >= max_boreholes:
85 return project, with_water[:max_boreholes]
86 if len(with_water) > len(best_boreholes):
87 best_project = project
88 best_boreholes = with_water
89
90 if best_project is None or not best_boreholes:
91 raise RuntimeError(
92 "No RSLog borehole with a valid water table was found "
93 "(drilling groundwater depth or piezometer measurements)."
94 )
95 return best_project, best_boreholes
96
97
98def run_rslog_import_example(
99 source: str,
100 output_path: str,
101 port: int = DEFAULT_SCRIPTING_PORT,
102 json_file: str = "",
103 company: str = "",
104 username: str = "",
105 password: str = "",
106 server: str = "",
107 max_boreholes: int = 2,
108) -> None:
109 if max_boreholes < 1:
110 raise ValueError("--max-boreholes must be at least 1")
111
112 source_key = source.strip().lower()
113 if source_key not in ("file", "account"):
114 raise ValueError("--source must be 'file' or 'account'")
115
116 output_path = os.path.abspath(output_path)
117 os.makedirs(os.path.dirname(output_path), exist_ok=True)
118
119 json_file_path: str | None = None
120 if source_key == "file":
121 json_file_path = os.path.abspath(json_file or _DEFAULT_JSON)
122 if not os.path.isfile(json_file_path):
123 raise ValueError(f"JSON fixture not found: {json_file_path}")
124 else:
125 if not company.strip() or not username.strip() or not password.strip():
126 raise ValueError(
127 "--company, --username, and --password are required for --source account"
128 )
129
130 app = RSSeismicApplication(port=port)
131 model = None
132 try:
133 app.ping()
134
135 if source_key == "account":
136 print(f"Authenticating with RSLog ({company.strip()} / {username.strip()})...")
137 auth = app.RSLog.authenticate(
138 company.strip(),
139 username.strip(),
140 password.strip(),
141 server=server.strip(),
142 )
143 if auth.twoFactorRequired:
144 raise RuntimeError(
145 "Two-factor authentication is required for this account. "
146 "Complete 2FA in the RSSeismic UI, or use an account without 2FA."
147 )
148
149 print("Creating blank project...")
150 model = app.newProject()
151
152 list_kwargs: dict = {}
153 if json_file_path is not None:
154 list_kwargs["jsonFilePath"] = json_file_path
155
156 print("Listing RSLog projects...")
157 projects = app.RSLog.listProjects(**list_kwargs)
158 if not projects:
159 raise RuntimeError("No RSLog projects returned from the selected source.")
160
161 print("Selecting boreholes with a valid water table...")
162 project, selected = _find_project_with_water_table_boreholes(
163 app,
164 projects,
165 list_kwargs,
166 max_boreholes,
167 )
168 if len(selected) < max_boreholes:
169 print(
170 f"Only {len(selected)} borehole(s) with a water table were found "
171 f"(requested {max_boreholes})."
172 )
173
174 print(
175 f"Using project: {project.name!r} "
176 f"(id={project.id}, isMetric={project.isMetric}, "
177 f"totalTestHoles={project.totalTestHoles})"
178 )
179 for borehole in selected:
180 print(
181 f" {borehole.name!r} id={borehole.id} "
182 f"layers={borehole.stratigraphyLayerCount} samples={borehole.sampleCount} "
183 f"{_water_table_label(borehole)}"
184 )
185
186 print(f"Importing {len(selected)} borehole(s) with default water table...")
187 result = app.RSLog.importBoreholes(
188 model,
189 project.id,
190 [
191 RSLogBoreholeImportSpec(
192 boreholeId=b.id,
193 groundwater=RSLogGroundwaterSelection(useDefault=True),
194 )
195 for b in selected
196 ],
197 jsonFilePath=json_file_path,
198 unitMismatchPolicy=UnitMismatchPolicy.KEEP_PROJECT,
199 multiProfilePolicy=MultiProfilePolicy.ENABLE_IF_NEEDED,
200 profileMergeMode=ProfileMergeMode.REPLACE_ALL,
201 )
202
203 if result.failedBoreholeIds:
204 print(f"Failed borehole ids: {result.failedBoreholeIds}")
205 if result.warnings:
206 for warning in result.warnings:
207 print(f"Warning: {warning}")
208
209 print(f"Imported profiles: {result.importedProfileNames}")
210 for profile in model.Profiles.listProfiles():
211 print(
212 f" profile {profile.name!r} layers={profile.layerCount} "
213 f"thickness={profile.totalThickness} active={profile.isActive}"
214 )
215
216 print(f"Saving project to {output_path}...")
217 model.saveAs(output_path)
218 print("Open that file in RSSeismic to inspect the imported profiles.")
219 finally:
220 if model is not None:
221 try:
222 model.close(saveProject=False)
223 except Exception:
224 pass
225 app.close()
226
227
228def parse_args() -> argparse.Namespace:
229 parser = argparse.ArgumentParser(
230 description="Import RSLog boreholes (file or account) and save a project for inspection.",
231 )
232 parser.add_argument(
233 "--source",
234 choices=("file", "account"),
235 default="file",
236 help="Import source: local JSON export or authenticated RSLog account (default: file).",
237 )
238 parser.add_argument(
239 "--json",
240 default="",
241 help=f"Path to RSLog JSON export (file source). Default: {_DEFAULT_JSON}",
242 )
243 parser.add_argument(
244 "--company",
245 default="",
246 help="RSLog company (account source).",
247 )
248 parser.add_argument(
249 "--username",
250 "-u",
251 default="",
252 help="RSLog username (account source).",
253 )
254 parser.add_argument(
255 "--password",
256 "-w",
257 default="",
258 help="RSLog password (account source).",
259 )
260 parser.add_argument(
261 "--server",
262 default="",
263 help="Optional RSLog server override (account source; empty = default).",
264 )
265 parser.add_argument(
266 "--max-boreholes",
267 type=int,
268 default=2,
269 help="Maximum boreholes to import (default: 2).",
270 )
271 parser.add_argument(
272 "--output",
273 "-o",
274 default=_DEFAULT_OUTPUT,
275 help=f"Output .rsseismicfile path (default: {_DEFAULT_OUTPUT})",
276 )
277 parser.add_argument(
278 "--port",
279 "-p",
280 type=int,
281 default=int(os.environ.get("RSSEISMIC_SCRIPTING_PORT", DEFAULT_SCRIPTING_PORT)),
282 help=f"gRPC port (default: {DEFAULT_SCRIPTING_PORT}, or RSSEISMIC_SCRIPTING_PORT)",
283 )
284 return parser.parse_args()
285
286
287def main() -> int:
288 args = parse_args()
289 try:
290 run_rslog_import_example(
291 source=args.source,
292 output_path=args.output,
293 port=args.port,
294 json_file=args.json,
295 company=args.company,
296 username=args.username,
297 password=args.password,
298 server=args.server,
299 max_boreholes=args.max_boreholes,
300 )
301 except Exception as ex:
302 print(f"Example failed: {ex}", file=sys.stderr)
303 return 1
304 print("\nRSLog import example finished.")
305 return 0
306
307
308if __name__ == "__main__":
309 raise SystemExit(main())