Single Element Test#

Open a project, create a Single Element Test working copy of a soil layer, configure it, run a strain-controlled test, and confirm the live profile layer is unchanged.

  1"""
  2Single Element Test workflow using the installed rsseismic package.
  3
  4Requires a running RSSeismic scripting server and a project that can use
  5Single Element Test (Nonlinear analysis + Lumped Mass solver). Mean-profile
  6layers are not supported.
  7
  8Strain values are in percent (%), matching the Single Element Test dialog.
  9
 10  python examples/example_single_element_test.py "E:\\path\\to\\project.rsseismicfile"
 11  python examples/example_single_element_test.py --port 60058 --layer-id <GUID> project.rsseismicfile
 12"""
 13
 14from __future__ import annotations
 15
 16import argparse
 17import os
 18import sys
 19
 20from rsseismic import RSSeismicApplication, StrainPathSegment
 21from rsseismic._client import DEFAULT_SCRIPTING_PORT
 22from rsseismic.enums import AnalysisMode, SolverType
 23
 24
 25def _ensure_element_test_settings(model) -> None:
 26    """Ensure Nonlinear analysis and Lumped Mass solver for Single Element Test."""
 27    settings = model.ProjectSettings
 28    analysis_mode = settings.getAnalysisMethod()
 29    solver_type = settings.getSolverType()
 30
 31    if analysis_mode != AnalysisMode.Nonlinear:
 32        print(f"Setting analysis mode: {analysis_mode.value} -> Nonlinear")
 33        settings.setAnalysisMethod(AnalysisMode.Nonlinear)
 34    else:
 35        print(f"Analysis mode: {analysis_mode.value}")
 36
 37    if solver_type != SolverType.LumpedMassModel:
 38        print(f"Setting solver type: {solver_type.value} -> LumpedMassModel")
 39        settings.setSolverType(SolverType.LumpedMassModel)
 40    else:
 41        print(f"Solver type: {solver_type.value}")
 42
 43
 44def _resolve_layer(model, layer_id: str | None, profile_name: str):
 45    if layer_id:
 46        return model.Profiles.getSoilLayer(layer_id)
 47
 48    layers = (
 49        model.Profiles.listSoilLayers(profile_name)
 50        if profile_name
 51        else model.Profiles.listActiveSoilLayers()
 52    )
 53    if not layers:
 54        raise RuntimeError("Project has no soil layers to test.")
 55    return model.Profiles.getSoilLayer(layers[0].layerID)
 56
 57
 58def run_single_element_test_workflow(
 59    project_path: str,
 60    port: int = DEFAULT_SCRIPTING_PORT,
 61    layer_id: str | None = None,
 62    profile_name: str = "",
 63) -> None:
 64    """
 65    Open a project, create a Single Element Test working copy, run, and verify
 66    the live profile layer is unchanged.
 67
 68    Project settings may be adjusted in memory (Nonlinear + Lumped Mass) for the
 69    session. The project file is closed without saving.
 70    """
 71    project_path = os.path.abspath(project_path.strip())
 72    if not os.path.isfile(project_path):
 73        raise FileNotFoundError(f"Project file not found: {project_path}")
 74
 75    app = RSSeismicApplication(port=port)
 76    model = None
 77
 78    try:
 79        app.ping()
 80        model = app.openFile(project_path)
 81
 82        active = model.Profiles.getActiveProfile()
 83        print(f"Opened project. Active profile: {active.profileName}")
 84
 85        _ensure_element_test_settings(model)
 86
 87        layer = _resolve_layer(model, layer_id, profile_name)
 88        live_thickness = layer.getThickness()
 89        live_ref_strain = layer.getRefStrain()
 90        live_unit_weight = layer.getUnitWeight()
 91        print(
 92            f"Source layer: {layer.layerId} "
 93            f"(thickness={live_thickness}, refStrain={live_ref_strain}, "
 94            f"unitWeight={live_unit_weight})"
 95        )
 96
 97        strain_path = [
 98            StrainPathSegment(startingStrain=0.0, endingStrain=0.1, increments=20),
 99            (0.1, 0.0, 20),
100        ]
101
102        with layer.createElementTestLayer(profileName=profile_name) as test:
103            print(f"Created element test layer: {test.elementTestLayerId}")
104            if test.profileName:
105                print(f"  profile: {test.profileName}")
106
107            # Configure the working copy only — not the live profile layer.
108            original_test_ref_strain = test.getRefStrain()
109            tuned_ref_strain = original_test_ref_strain * 1.1 if original_test_ref_strain else 0.05
110            test.setRefStrain(tuned_ref_strain)
111            print(
112                f"Working-copy ref strain: {original_test_ref_strain} -> {test.getRefStrain()}"
113            )
114
115            dataframe = test.runSingleElementTest(strainPath=strain_path)
116            print(
117                f"First run: {len(dataframe)} row(s), columns={list(dataframe.columns)}"
118            )
119            units = dataframe.attrs.get("column_units")
120            if units:
121                print(f"Column units: {units}")
122            print(dataframe.head().to_string(index=False))
123
124            # Re-run on the same working copy to show the session is reusable.
125            dataframe_again = test.runSingleElementTest(
126                strainPath=[(0.0, 0.05, 10), (0.05, 0.0, 10)],
127                enableDissipation=False,
128            )
129            print(f"Second run: {len(dataframe_again)} row(s)")
130
131            if dataframe.empty or dataframe_again.empty:
132                raise RuntimeError("Single Element Test returned an empty DataFrame.")
133
134        # Live profile layer must be unchanged by configure/run/close.
135        if layer.getThickness() != live_thickness:
136            raise RuntimeError("Live layer thickness changed after element test.")
137        if layer.getRefStrain() != live_ref_strain:
138            raise RuntimeError("Live layer reference strain changed after element test.")
139        if layer.getUnitWeight() != live_unit_weight:
140            raise RuntimeError("Live layer unit weight changed after element test.")
141
142        print("Live profile layer unchanged. Single Element Test workflow succeeded.")
143    finally:
144        if model is not None:
145            model.close(saveProject=False)
146        app.close()
147
148
149def parse_args() -> argparse.Namespace:
150    parser = argparse.ArgumentParser(
151        description=(
152            "Open a project, run Single Element Test on a soil-layer working copy, "
153            "and verify the live layer is not modified."
154        )
155    )
156    parser.add_argument(
157        "project",
158        help="Absolute path to a .rsseismicfile",
159    )
160    parser.add_argument(
161        "--port",
162        "-p",
163        type=int,
164        default=int(os.environ.get("RSSEISMIC_SCRIPTING_PORT", DEFAULT_SCRIPTING_PORT)),
165        help=f"gRPC port (default: {DEFAULT_SCRIPTING_PORT}, or RSSEISMIC_SCRIPTING_PORT env)",
166    )
167    parser.add_argument(
168        "--layer-id",
169        default="",
170        metavar="GUID",
171        help="Soil layer GUID to test. Default: first layer on the active (or --profile) profile.",
172    )
173    parser.add_argument(
174        "--profile",
175        default="",
176        metavar="NAME",
177        help="Profile name that owns the layer. Leave empty to use the active profile.",
178    )
179    return parser.parse_args()
180
181
182def main() -> int:
183    args = parse_args()
184    try:
185        run_single_element_test_workflow(
186            args.project,
187            port=args.port,
188            layer_id=args.layer_id or None,
189            profile_name=args.profile,
190        )
191    except Exception as ex:
192        print(f"Single Element Test workflow failed: {ex}", file=sys.stderr)
193        return 1
194
195    print("Workflow finished.")
196    return 0
197
198
199if __name__ == "__main__":
200    raise SystemExit(main())