Run conditions in parallel

Run one RIFLEX model three times over different sea states, concurrently, then compare the results. The model is a simple beam under tension, and the three runs vary the significant wave height Hs and the peak period Tp:

Case Hs [m] Tp [s]

Hs=2.0_Tp=5.0

2.0

5.0

Hs=3.0_Tp=6.0

3.0

6.0

Hs=4.0_Tp=7.0

4.0

7.0

1. Run it

Set SRE_EXE to the SIMA Runtime Engine executable, then, from the examples/ folder:

python riflex/run_parallel/run_parallel.py

It writes summary.txt and plots/ under output/run_parallel/.

2. Set up the runs

Each case is one run_condition call. The same stask is imported every time and the case’s values override the task variables, so one model serves all three runs:

res = sima.run_condition(
    ws,
    stask=stask,
    task="SimpleBeam",
    condition="Initial",
    run_type="dynamic",
    variables={"Hs": 2.0, "Tp": 5.0},
    results_dir=result_folder,
)

Each case runs in its own working directory so the three do not collide. results_dir copies the results out, which lets the working directory be thrown away afterwards; leave it out and the results are read where they lie.

3. Read the results

Each case is post-processed on its own thread as soon as it finishes.

def _process_single(res, case_name):
    signal = res.run.signal(f"{ELEMENT}/Axial force")

The runs finish out of order, so these lines appear out of order too:

   Hs=3, Tp=6         peak axial force      1,997,205 N
   Hs=4, Tp=7         peak axial force      1,997,643 N
   Hs=2, Tp=5         peak axial force      1,995,760 N

Once every case is done, a second pass compares them and prints statistics for the axial force in element 1:

-- axial force in element_1 --------------------------------------------
   sea state                      min             max            mean           std
   Hs=2, Tp=5               1,994,714       1,995,760       1,995,126           179
   Hs=3, Tp=6               1,994,085       1,997,205       1,995,345           522
   Hs=4, Tp=7               1,993,327       1,997,643       1,995,364           886
   values in N, 1000 samples at dt=0.1 s

4. Plots

The plotting helpers take signals rather than arrays, so every axis label is name [unit] from the signal itself.

Axial force over time, one curve per sea state

At this scale the curves sit on top of each other. The peaks differ by less than 0.1 %, which a shared axis hides, hence the second figure.

Peak axial force per sea state

5. Source code

run_parallel.py
"""Run Parallel Conditions.

This example demonstrates running multiple SIMA conditions in parallel with different input parameters.
It also shows how to post-process results from multiple runs, first in each run and then in the main thread after all runs are completed.

The example uses a Riflex task to analyze a simple beam with different wave conditions.

After each run, its maximum axial force is reported.
After all runs are completed, a summary file is created with the maximum axial force for each run and the overall maximum.

Environment variable `SRE_EXE` is used to point to the sre executable of SIMA if exe is not provided directly in _create_run.
"""

import os
import shutil
from pathlib import Path
from utils import plotting
from utils.runner import run_multiple
from simapy.results import open_results, ResultSet


#: The element both post-processing steps look at.
ELEMENT = "Dynamic/BeamLine/segment_1/element_1"


def _create_run(output_folder: Path, stask: Path, variables: dict):
    """Create a run configuration for a single run with SIMA.

    Args:
        output_folder (Path): Base directory where all outputs will be stored
        stask (Path): Path to the SIMA task file (.stask) to be executed
        variables (dict): Dictionary of input variables and their values (e.g., {"Hs": 2.0, "Tp": 5.0})

    Returns:
        dict: Run configuration: name, workspace, condition, variables and post-processing
    """
    case_name = "_".join([f"{key}={value}" for key, value in variables.items()])
    ws = output_folder / "tmp" / case_name
    result_folder = output_folder / "results" / case_name
    if result_folder.exists():
        shutil.rmtree(result_folder, ignore_errors=True)

    def post(res):
        """Report on this case as soon as it finishes."""
        _process_single(res, case_name)
        shutil.copy(ws / "sima.log", result_folder)

    return {
        "name": case_name,
        # Provide the path to SRE executable if not set in environment SRE_EXE
        "exe": None,
        "ws": ws,
        "stask": stask,
        "task": "SimpleBeam",
        "condition": "Initial",
        "run_type": "dynamic",
        "variables": variables,
        # Copying the results out lets the workspace be discarded afterwards.
        "results_dir": result_folder,
        "postprocess": post,
    }


def _process_single(res: ResultSet, case_name: str):
    """Report the peak axial force from a single run, as soon as it finishes.

    Args:
        res: The `ResultSet` for this run
        case_name (str): The case this run is, used only if it carries no variables
    """
    signal = res.run.signal(f"{ELEMENT}/Axial force")
    print(f"   {_sea_state(res) or case_name:18} peak axial force "
          f"{signal.y.max():>14,.0f} {signal.unit}")


def _process_multiple(runs: list[dict], output_folder: Path):
    """Compare the runs, and report and plot what the sweep did."""
    # Read each result folder back, this time with all three runs in hand.
    cases = [open_results(run["results_dir"]) for run in runs]

    # What each run is and which files it was read from.
    print()
    print(f"-- {len(cases)} runs, one folder each " + "-" * 40)
    for case in cases:
        read = [s for s in case.sources if s.signals]
        files = ", ".join(f"{s.file} ({s.signals})" for s in read)
        print(f"   {case.description.condition:20} {_sea_state(case):18} {files}")

    # The same signal from every run, side by side.
    axial = [case.run.signal(f"{ELEMENT}/Axial force") for case in cases]
    print("\n-- axial force in element_1 " + "-" * 44)
    print(f"   {'sea state':18}{'min':>16}{'max':>16}{'mean':>16}{'std':>14}")
    for case, signal in zip(cases, axial):
        y = signal.y
        print(f"   {_sea_state(case):18}{y.min():>16,.0f}{y.max():>16,.0f}"
              f"{y.mean():>16,.0f}{y.std():>14,.0f}")
    print(f"   values in {axial[0].unit}, {len(axial[0])} samples at "
          f"dt={axial[0].xdelta:g} {axial[0].xunit}")

    # One figure for the curves, one for the peaks alone.
    labels = [_sea_state(case) for case in cases]
    plots = output_folder / "plots"
    written = [
        plotting.curves(axial, plots, "Axial force in element_1, one curve per sea state",
                        "axial_force", labels=labels, y_name="Axial force"),
        plotting.bars(labels, [s.y.max() for s in axial], plots,
                      "Peak axial force per sea state", "axial_force_peaks",
                      axial[0].unit, "Peak axial force"),
    ]

    # The peak per run and the overall peak, for whatever reads this next.
    summary_file = output_folder / "summary.txt"
    with open(summary_file, "w", encoding="utf-8") as summary:
        for case, signal in zip(cases, axial):
            summary.write(f"{case.description.condition}: {signal.y.max()}\n")
        summary.write(f"Max force: {max(s.y.max() for s in axial)}\n")

    print()
    for path in [summary_file, *written]:
        print(f"   wrote {path.relative_to(output_folder)}")


def _sea_state(case) -> str:
    """A case label from the values that run used, not from its folder name."""
    v = case.description.variables
    return ", ".join(f"{n}={v[n].value:g}" for n in ("Hs", "Tp") if n in v)


if __name__ == "__main__":
    here = Path(__file__).parent.absolute()
    examples_root = (here / "../..").resolve()
    output_folder = examples_root / "output" / "run_parallel"
    input_folder = examples_root / "input"

    # Flag for cleanup, will remove working folders if True
    cleanup = True

    if cleanup:
        shutil.rmtree(output_folder, ignore_errors=True)
    os.makedirs(output_folder, exist_ok=True)

    stask = input_folder / "riflex" / "simple_beam.stask"

    # Prepare runs before sending them to the executor
    runs = [
        _create_run(output_folder, stask, {"Hs": 2.0, "Tp": 5.0}),
        _create_run(output_folder, stask, {"Hs": 3.0, "Tp": 6.0}),
        _create_run(output_folder, stask, {"Hs": 4.0, "Tp": 7.0}),
    ]

    completed = run_multiple(runs)

    # Then postprocess after all are done
    if completed:
        _process_multiple(completed, output_folder)

    if cleanup:
        shutil.rmtree(output_folder / "tmp", ignore_errors=True)

    if len(completed) < len(runs):
        raise SystemExit(f"{len(runs) - len(completed)} of {len(runs)} runs failed")
utils/plotting.py
"""Plot helpers for the parallel run analysis.

These take `Signal` objects rather than arrays, so every axis label is
``name [unit]`` from the signal itself. PNGs are written with a non-interactive
backend, so it works headless and in CI.
"""

from __future__ import annotations

from pathlib import Path
from typing import Iterable, Sequence

import matplotlib

matplotlib.use("Agg")

import matplotlib.pyplot as plt  # noqa: E402  the backend must be set first

from simapy.results import Signal  # noqa: E402

plt.rcParams.update({
    "figure.dpi": 120,
    "savefig.dpi": 120,
    "savefig.bbox": "tight",
    "font.size": 9,
    "axes.grid": True,
    "grid.alpha": 0.3,
    "axes.spines.top": False,
    "axes.spines.right": False,
    "legend.frameon": False,
})


def label(signal: Signal, name: str | None = None) -> str:
    """``name [unit]``, the unit taken from the signal.

    ``name`` defaults to the signal's own; an empty one leaves just the unit.
    Empty units are dropped.
    """
    return _with_unit(signal.name if name is None else name, signal.unit)


def x_label(signal: Signal, name: str | None = None) -> str:
    """The x-axis equivalent: seconds are Time, metres Line length, else just the unit."""
    if name is None:
        name = {"s": "Time", "m": "Line length"}.get(signal.xunit, "")
    return _with_unit(name, signal.xunit)


def _with_unit(text: str, unit: str | None) -> str:
    if not unit or unit == "-":
        return text
    return f"{text} [{unit}]" if text else f"[{unit}]"


def save(fig, folder: Path, name: str) -> Path:
    """Write to ``<folder>/<name>.png`` and return the path."""
    folder.mkdir(parents=True, exist_ok=True)
    path = folder / f"{name}.png"
    fig.savefig(path)
    plt.close(fig)
    return path


def curves(
    signals: Sequence[Signal],
    folder: Path,
    title: str,
    name: str,
    labels: Sequence[str] | None = None,
    x_name: str | None = None,
    y_name: str | None = None,
) -> Path:
    """Several signals sharing an axis, on one set of axes."""
    fig, ax = plt.subplots(figsize=(7.5, 4))
    for index, signal in enumerate(signals):
        text = labels[index] if labels else signal.name
        ax.plot(signal.x, signal.y, linewidth=1.2, label=text)
    first = signals[0]
    ax.set_xlabel(x_label(first, x_name))
    ax.set_ylabel(label(first, y_name or _shared_name(signals)))
    ax.set_title(title)
    if len(signals) > 1 or labels:
        ax.legend()
    return save(fig, folder, name)


def bars(
    names: Sequence[str],
    values: Sequence[float],
    folder: Path,
    title: str,
    name: str,
    value_unit: str,
    value_name: str = "value",
) -> Path:
    """One number per case, when the comparison matters more than the curve."""
    fig, ax = plt.subplots(figsize=(7.5, 0.5 * len(names) + 2))
    positions = range(len(names))
    ax.barh(list(positions), list(values), height=0.6)
    ax.set_yticks(list(positions), list(names))
    ax.set_xlabel(f"{value_name} [{value_unit}]" if value_unit else value_name)
    ax.set_title(title)
    ax.invert_yaxis()
    span = max(values) - min(values)
    for position, value in zip(positions, values):
        ax.text(value + span * 0.02 if span else value, position,
                f"{value:,.0f}", va="center", fontsize=8)
    ax.set_xlim(right=max(values) + (span if span else max(values) * 0.1) * 0.25)
    return save(fig, folder, name)


def _shared_name(signals: Iterable[Signal]) -> str:
    """A y-axis name for several signals: the common one, or just the unit."""
    names = {s.name for s in signals}
    return names.pop() if len(names) == 1 else ""