ogstools package#

class ogstools.Execution[source]#

Bases: StorageBase

Configuration for OGS simulation execution parameters.

This class encapsulates all settings related to how an OGS simulation is executed, including parallelization, containerization, and logging options.

OGS binary / container selection

The ogs_path parameter accepts either:

  • A directory containing the OGS executable ("/path/to/bin").

  • A container image path or URL (.sif / .squashfs), in which case OGS is run inside the container as ogs.

Use pre-built container image URLs:

Execution(ogs_path=Execution.CONTAINER_PARALLEL_V6_5_7)

When ogs is not set, the executable is looked up via OGS_BIN_PATH and, if not defined, on PATH.

Site-wide defaults via OGS_EXECUTION_DEFAULTS

Point the environment variable to a YAML file (e.g. in .envrc, activate, or .bashrc) to set site-wide defaults:

export OGS_EXECUTION_DEFAULTS=/path/to/my_execution_defaults.yaml

A typical cluster defaults file:

ogs_path:    "/scratch/containers/ogs-6.5.7-petsc.squashfs"
mpi_wrapper: "srun --ntasks"
write_logs:  true

A typical developer defaults file:

ogs_path: "ogs/build/release/bin"

Initialize an Execution configuration.

Parameters:
  • interactive (bool) – If True, use interactive mode for stepwise control.

  • args (str | None) – Extra OGS command-line flags appended verbatim (see ogs --help for the full list). Useful flags: Example: "--write-prj --log-parallel".

  • mpi_wrapper (str | None) – MPI launcher prefix, e.g. "mpirun -np", "mpiexec -n", "srun --ntasks".

  • wrapper (str | None) – Generic command prefix prepended before the full command, e.g. "valgrind", "perf stat".

  • ogs_path (str | None) – Directory containing the OGS executable, or a container image path/URL (.sif / .squashfs). When not set, looked up via OGS_BIN_PATH or PATH.

  • mpi_ranks (int | None) – Number of MPI ranks. None = serial run.

  • omp_num_threads (int | None) – OpenMP threads per MPI rank. None = let OGS decide. See OpenMP parallelization.

  • ogs_asm_threads (int | None) –

    OGS assembly threads. None = let OGS decide. See OpenMP parallelization.

  • write_logs (bool) – If True, write OGS log output to a file.

  • log_level (str | None) – OGS log verbosity: none|error|warn|info|debug|all. None omits the -l flag (OGS default is info).

  • id (str | None) – Optional unique identifier for this execution config.

default: Execution#
CONTAINER_SERIAL = 'https://vip.s3.ufz.de/ogs/public/binaries/ogs6/6.5.7/ogs-6.5.7-serial.squashfs'#
CONTAINER_PARALLEL = 'https://vip.s3.ufz.de/ogs/public/binaries/ogs6/6.5.7/ogs-6.5.7-petsc.squashfs'#

Default Execution instance, created at import time via auto-detection.

Use this to inspect or share the default execution configuration without creating a new object each time.

Users can override the default for the entire session:

Execution.default = Execution(ogs_path="/path/to/bin")
__init__(interactive=False, args=None, mpi_wrapper='mpirun -np', wrapper=None, ogs_path=None, mpi_ranks=None, omp_num_threads=None, ogs_asm_threads=None, write_logs=True, log_level=None, id=None)[source]#

Initialize an Execution configuration.

Parameters:
  • interactive (bool) – If True, use interactive mode for stepwise control.

  • args (str | None) – Extra OGS command-line flags appended verbatim (see ogs --help for the full list). Useful flags: Example: "--write-prj --log-parallel".

  • mpi_wrapper (str | None) – MPI launcher prefix, e.g. "mpirun -np", "mpiexec -n", "srun --ntasks".

  • wrapper (str | None) – Generic command prefix prepended before the full command, e.g. "valgrind", "perf stat".

  • ogs_path (str | None) – Directory containing the OGS executable, or a container image path/URL (.sif / .squashfs). When not set, looked up via OGS_BIN_PATH or PATH.

  • mpi_ranks (int | None) – Number of MPI ranks. None = serial run.

  • omp_num_threads (int | None) –

    OpenMP threads per MPI rank. None = let OGS decide. See OpenMP parallelization.

  • ogs_asm_threads (int | None) –

    OGS assembly threads. None = let OGS decide. See OpenMP parallelization.

  • write_logs (bool) – If True, write OGS log output to a file.

  • log_level (str | None) – OGS log verbosity: none|error|warn|info|debug|all. None omits the -l flag (OGS default is info).

  • id (str | None) – Optional unique identifier for this execution config.

classmethod from_file(filepath)[source]#

Restore an Execution object from an execution.yaml file.

Parameters:

filepath (Path | str) – Path to execution.yaml file.

Return type:

Self

Returns:

Restored Execution instance.

Raises:

FileNotFoundError – If the specified file does not exist.

classmethod from_id(execution_id)[source]#

Load Execution from the user storage path using its ID. StorageBase.Userpath must be set.

Parameters:

execution_id (str) – The unique ID of the Execution to load.

Return type:

Self

Returns:

An Execution instance restored from disk.

save(target=None, overwrite=None, dry_run=False, archive=False, id=None)[source]#
Return type:

list[Path]

property env: dict[str, str]#

Process environment for OGS subprocess, with OMP/ASM thread vars injected.

property container_path: str | None#

Container reference for the active run, or None for native execution.

property container_prefix: str | None#

Container launch prefix, e.g. ‘apptainer exec /path/to.sif’, or None.

property cmd: str#

OGS invocation command without project file and meshes path.

classmethod from_default(file=None)[source]#

Create the default Execution instance.

If OGS_EXECUTION_DEFAULTS is set, load settings from that file and construct with those values. Otherwise use the empty constructor.

Return type:

Self

class ogstools.Log[source]#

Bases: object

Parser and analyzer for OGS simulation log files.

Parses OGS log files and provides methods to extract and analyze simulation data including convergence behavior, time step information, and simulation status.

Initialize a Log parser.

Parameters:

file (str | Path) – Path to the OGS log file to parse.

__init__(file)[source]#

Initialize a Log parser.

Parameters:

file (str | Path) – Path to the OGS log file to parse.

convergence_coupling_iteration()[source]#

Extract coupling iteration convergence data.

Return type:

DataFrame

Returns:

DataFrame with coupling iteration convergence information.

convergence_newton_iteration()[source]#

Extract Newton iteration convergence data.

Return type:

DataFrame

Returns:

DataFrame with Newton iteration convergence metrics (errors, residuals, convergence order).

simulation()[source]#

Extract overall simulation information.

Return type:

DataFrame

Returns:

DataFrame with simulation-level data.

simulation_termination()[source]#

Extract simulation termination information.

Return type:

DataFrame

Returns:

DataFrame with termination status and final state.

time_step()[source]#

Extract time step information.

Return type:

DataFrame

Returns:

DataFrame with time step data (model time, clock time, etc.).

plot_convergence(metric='dx', x_metric='time_step', **kwargs)[source]#

Create a heatmap of the nonlinear solver convergence data.

Visualizes convergence behavior across time steps and iterations. Per default uses logarithmic scaling.

Parameters:
  • metric (Literal['dx', 'dx_x', 'x']) – Which metric to plot. Options: - “dx”: absolute error - “dx_x”: relative error - “x”: residual

  • x_metric (Literal['time_step', 'model_time']) – x_axis representation: - “time_step”: timestep number - “model_time”: simulation time

  • kwargs (Any) – Additional arguments passed to heatmap function (see heatmap()).

Return type:

Figure

Returns:

A matplotlib Figure with the convergence heatmap.

plot_convergence_order(n=3, x_metric='time_step', **kwargs)[source]#

Create a heatmap of the nonlinear solver convergence order.

Estimates and visualizes the convergence order across iterations. Only iterations i >= n are assigned a convergence order.

Parameters:
  • n (Literal[3, 4]) – Number of error values to use for estimating convergence order (3 or 4).

  • x_metric (Literal['time_step', 'model_time']) – x_axis representation: - “time_step”: timestep number - “model_time”: simulation time

  • kwargs (Any) – Additional arguments passed to heatmap function. Default scale is limited to 0-2 for meaningful data.

Return type:

Figure

Returns:

A matplotlib Figure with the convergence order heatmap.

class ogstools.MaterialManager[source]#

Bases: object

Manager for material definitions loaded from a repository of YAML files.

A MaterialManager can be constructed in two ways:

  1. From a repository directory (default): If no materials are provided, all YAML files in the given data_dir are parsed into Material objects and stored in materials_db.

  2. From pre-filtered materials: If a dictionary of Material objects is passed via materials, the manager is created directly from these. This is typically used internally when creating filtered views.

Once constructed, a MaterialManager can: - provide access to the stored materials

  • filter materials according to a process schema, subdomain mapping, and/or fluid assignments

  • represent the filtered material set as a new MaterialManager.

Initialize a MaterialManager instance.

Parameters#

data_dirPath | str | None

Directory containing the repository of material YAML files. Defaults to defs.MATERIALS_DIR. Only used if no materials are passed.

materialsdict[str, Material] | None

Pre-loaded material dictionary. If None, materials are loaded from the repository directory. If provided, these materials are used as-is without accessing the repository (commonly from filtering).

subdomain_idsdict[str, int] | None

Mapping of subdomain names to material IDs.

processstr | None

Process type used for filtering, if applicable.

Notes#

  • If materials is None, the instance represents the full material repository loaded from the given directory.

  • If materials is provided, the instance represents a filtered view and does not perform any additional repository access.

__init__(data_dir=None, materials=None, subdomain_ids=None, process=None)[source]#

Initialize a MaterialManager instance.

Parameters#

data_dirPath | str | None

Directory containing the repository of material YAML files. Defaults to defs.MATERIALS_DIR. Only used if no materials are passed.

materialsdict[str, Material] | None

Pre-loaded material dictionary. If None, materials are loaded from the repository directory. If provided, these materials are used as-is without accessing the repository (commonly from filtering).

subdomain_idsdict[str, int] | None

Mapping of subdomain names to material IDs.

processstr | None

Process type used for filtering, if applicable.

Notes#

  • If materials is None, the instance represents the full material repository loaded from the given directory.

  • If materials is provided, the instance represents a filtered view and does not perform any additional repository access.

set_material(file_path)[source]#

Write a material entry based of one yaml file.

Return type:

None

get_material(name)[source]#

Retrieve a material from the repository by name.

Return type:

Material

filter(process, subdomains, fluids=None)[source]#

Create a filtered view of the materials for a given process.

Filtering is based on: - a process schema, - subdomain assignments (mapping subdomain names to one or more material IDs), - optional fluid phase materials.

Return type:

MaterialManager

Parameters#

processstr

The process name to filter by.

subdomainslist[dict[str, Any]]

A list of dictionaries, each containing the material name, a subdomain name, and one or more material IDs.

fluidsdict[str, str] | None

A dictionary mapping phase types to material names.

Returns#

MaterialManager

A new MaterialManager instance containing only the filtered materials. This new instance does not access the repository; it reuses the already loaded Material objects.

class ogstools.MediaSet[source]#

Bases: object

Represents a collection of Medium objects (solids or fluids) for a given process.

MediaSet are constructed from a filtered MaterialManager, i.e. after process schemas, subdomain assignments, and fluid materials have already been applied.

Provides: - Dictionary-like access (__getitem__, keys(), values(), items()). - Iteration over all Medium instances. - Lookup by name or by material ID.

Notes#

This class requires that the input MaterialManager has already been filtered for a specific process (filtered_db.process must not be None).

Create a MediaSet collection from a filtered MaterialManager.

Parameters#

filtered_dbMaterialManager

A MaterialManager instance that has been filtered for a specific process and contains subdomain IDs and fluids.

Raises#

ValueError

If filtered_db.process is None (i.e. unfiltered manager), or if any Medium fails validation.

__init__(filtered_db)[source]#

Create a MediaSet collection from a filtered MaterialManager.

Parameters#

filtered_dbMaterialManager

A MaterialManager instance that has been filtered for a specific process and contains subdomain IDs and fluids.

Raises#

ValueError

If filtered_db.process is None (i.e. unfiltered manager), or if any Medium fails validation.

__getitem__(key)[source]#

Retrieve a Medium by its subdomain name.

Return type:

Medium

keys()[source]#

Return the list of subdomain names (keys).

Return type:

list[str]

values()[source]#

Return the list of Medium objects (values).

Return type:

list[Medium]

items()[source]#

Return (name, Medium) pairs like dict.items().

Return type:

list[tuple[str, Medium]]

to_dict()[source]#

Return the mapping of subdomain names to Medium objects.

Return type:

dict[str, Medium]

get_by_id(material_id)[source]#

Lookup a Medium by its material ID.

Return type:

Medium | None

Parameters#

material_idint

The material_id assigned to a subdomain.

Returns#

Medium | None

The Medium object with the given ID, or None if not found.

classmethod from_project(prj, process)[source]#

Reconstruct a Media collection from an OGS6py Project.

Return type:

MediaSet

Parameters#

prjProject

An OGS6py Project instance containing <media> definitions.

processstr

The process type to which these media belong.

Raises#

NotImplementedError

This functionality is not implemented yet.

validate()[source]#

Validate all Medium objects.

Return type:

bool

Returns#

bool

True if all Medium objects are valid, otherwise raises ValueError.

validate_medium(medium)[source]#

Validate a single Medium.

Return type:

bool

Parameters#

mediumMedium

The Medium object to validate.

Returns#

bool

True if valid.

Raises#

ValueError

If the Medium fails validation.

class ogstools.MeshSeries[source]#

Bases: Sequence[UnstructuredGrid], StorageBase

A wrapper around pyvista and meshio for reading of pvd and xdmf timeseries.

Initialize a MeshSeries object

Note:

If given as a single string, the data is read in SI units i.e. in seconds and meters and converted to the given units. If given as a tuple, the first str corresponds to the data_unit, the second to the output_unit. E.g.: ot.MeshSeries(filepath, "km", ("a", "d")) would read in the spatial data in meters and convert to kilometers and read in the timevalues in years and convert to days.

__init__(filepath=None, spatial_unit='m', time_unit='s', id=None)[source]#

Initialize a MeshSeries object

Note:

If given as a single string, the data is read in SI units i.e. in seconds and meters and converted to the given units. If given as a tuple, the first str corresponds to the data_unit, the second to the output_unit. E.g.: ot.MeshSeries(filepath, "km", ("a", "d")) would read in the spatial data in meters and convert to kilometers and read in the timevalues in years and convert to days.

classmethod from_data(meshes, timevalues, spatial_unit='m', time_unit='s')[source]#

Create a MeshSeries from a list of meshes and timevalues.

Return type:

MeshSeries

classmethod from_id(meshseries_id)[source]#

Load MeshSeries from the user storage path using its ID. StorageBase.Userpath must be set.

Parameters:

meshseries_id (str) – The unique ID of the MeshSeries to load.

Return type:

MeshSeries

Returns:

A MeshSeries instance restored from disk.

extend(mesh_series)[source]#

Extends self with mesh_series. If the last element of the mesh series is within epsilon to the first element of mesh_series to extend, the duplicate element is removed

Return type:

None

resample_temporal(timevalues)[source]#

Return a new MeshSeries interpolated to the given timevalues.

Return type:

MeshSeries

probe(points, data_name=None, interp_method='linear')[source]#

Create a new MeshSeries by probing points on an existing MeshSeries.

Parameters:
  • points (ndarray) – The points at which to probe.

  • data_name (str | Variable | list[str | Variable] | None) – Data to extract. If None, use all point data.

  • interp_method (Literal['nearest', 'linear']) – The interpolation method to use.

Return type:

MeshSeries

Returns:

A MeshSeries (Pointcloud) containing the probed data.

interpolate(mesh, data_name=None)[source]#

Create a new MeshSeries by spatial interpolation.

Parameters:
Return type:

MeshSeries

Returns:

A spatially interpolated MeshSeries.

__getitem__(index)[source]#
Return type:

Any

items()[source]#

Returns zipped tuples of timevalues and meshes.

Return type:

Sequence[tuple[float, UnstructuredGrid]]

aggregate_temporal(variable, func)[source]#

Aggregate data over all timesteps using a specified function.

Parameters:
  • variable (Variable | str) – The mesh variable to be aggregated.

  • func (Callable) – The aggregation function to apply. E.g. np.min, np.max, np.mean, np.median, np.sum, np.std, np.var

Return type:

UnstructuredGrid

Returns:

A mesh with aggregated data according to the given function.

clear_cache()[source]#
Return type:

None

closest_timestep(timevalue)[source]#

Return the corresponding timestep from a timevalue.

Return type:

int

closest_timevalue(timevalue)[source]#

Return the closest timevalue to a timevalue.

Return type:

float

ip_tesselated()[source]#

Create a new MeshSeries from integration point tessellation.

Return type:

MeshSeries

mesh(timestep, lazy_eval=True)[source]#

Returns the mesh at the given timestep.

Return type:

UnstructuredGrid

rawdata_file()[source]#

Checks, if working with the raw data is possible. For example, OGS Simulation results with XDMF support efficient raw data access via h5py

Return type:

Path | None

Returns:

The location of the file containing the raw data. If it does not support efficient read (e.g., no efficient slicing), it returns None.

mesh_interp(timevalue, lazy_eval=True)[source]#

Return the temporal interpolated mesh for a given timevalue.

Return type:

UnstructuredGrid

property timevalues: ndarray#

Return the timevalues.

property timesteps: list#

Return the OGS simulation timesteps of the timeseries data. Not to be confused with timevalues which returns a list of times usually given in time units.

values(variable)[source]#

Get the data in the MeshSeries for all timesteps.

Adheres to time slicing via __getitem__ and an applied pyvista filter via transform if the applied filter produced ‘vtkOriginalPointIds’ or ‘vtkOriginalCellIds’ (e.g. clip(…, crinkle=True), extract_cells(…), threshold(…).)

Parameters:

variable (str | Variable | list[str | Variable]) – Data to read/process from the MeshSeries. Can also be a list of str or Variable.

Return type:

ndarray | list[ndarray]

Returns:

A numpy array of shape (n_timesteps, n_points/c_cells). If given an argument of type Variable is given, its transform function is applied on the data. If a list of str or Variable is given, a list of the individual values is returned.

property point_data: DataDict#

Useful for reading or setting point_data for the entire meshseries.

property cell_data: DataDict#

Useful for reading or setting cell_data for the entire meshseries.

property field_data: DataDict#

Useful for reading or setting field_data for the entire meshseries.

time_of_min(variable)[source]#

Returns a Mesh with the time of the variable minimum as data.

Return type:

UnstructuredGrid

time_of_max(variable)[source]#

Returns a Mesh with the time of the variable maximum as data.

Return type:

UnstructuredGrid

aggregate_spatial(variable, func)[source]#

Aggregate data over domain per timestep using a specified function.

Parameters:
  • variable (Variable | str) – The mesh variable to be aggregated.

  • func (Callable) – The aggregation function to apply. E.g. np.min, np.max, np.mean, np.median, np.sum, np.std, np.var

Return type:

ndarray

Returns:

A numpy array with aggregated data.

probe_values(points, data_name, interp_method='linear')[source]#

Return the sampled data of the MeshSeries at observation points.

Similar to probe() but returns the data directly instead of creating a new MeshSeries.

Parameters:
  • points (ndarray | list) – The observation points to sample at.

  • data_name (str | Variable | list[str | Variable]) – Data to sample. If provided as a Variable, the output will transformed accordingly. Can also be a list of str or Variable.

  • interp_method (Literal['nearest', 'linear']) – Interpolation method, defaults to linear

Return type:

ndarray | list[ndarray]

Returns:

numpy array/s of interpolated data at observation points with the following shape:

  • multiple points: (n_timesteps, n_points, [n_components])

  • single points: (n_timesteps, [n_components])

If data_name is a list, a corresponding list of arrays is returned.

plot_line(var1=None, var2=None, ax=None, sort=True, outer_legend=False, **kwargs)#

Plot some data of a (1D) dataset.

You can pass “x”, “y” or “z” to either of x_var or y_var to specify which spatial dimension should be used for the corresponding axis. By passing “time” the timevalues will be use for this axis. You can also pass two data variables for a phase plot. if no value is given, automatic detection of spatial axis is tried.

>>> line(ms, ot.variables.temperature)          # temperature over time
>>> line(ms, ot.variables.temperature, "time")  # time over temperature
>>> line(ms, "pressure", "temperature")     # temperature over pressure
>>> line(mesh, ot.variables.temperature)    # temperature over x, y or z
>>> line(mesh, "y", "temperature")          # temperature over y
>>> line(mesh, ot.variables.pressure, "y")  # y over pressure
>>> line(mesh)  # z=const: y over x, y=const: z over x, x=const: z over y
Parameters:
  • var1 (str | Variable | None) – Variable for the x-axis if var2 is given else for y-axis.

  • var2 (str | Variable | None) – Variable for the y-axis if var1 is given.

  • ax (Axes | None) – The matplotlib axis to use for plotting, if None a new figure will be created.

  • sort (bool) – Automatically sort the values along the dimension of the mesh with the largest extent (only for pointclouds).

Outer_legend:

Draw legend to the right next to the plot area. By default False (legend stays inside). User can pass a tuple of two floats (x, y), which will be passed to bbox_to_anchor parameter in matplotlib legend call. True will pass the default values (1.05, 1.0).

Return type:

Figure | None

Keyword Arguments:
  • figsize: figure size (default=[16, 10])

  • dpi: resolution of the figure

  • color: color of the line

  • linewidth: width of the line

  • linestyle: style of the line

  • label: label in the legend

  • grid: if True, show grid

  • monospace: if True, the legend uses a monospace font

  • loc: location of the legend (default=”upper right”)

  • clip_on: If True, clip the output to stay within the Axes.

    (default=False)

  • all other kwargs get passed to matplotlib’s plot function

Note:

Using loc=”best” will take a long time, if you plot lines on top of a contourplot, as matplotlib is calculating the best position against all the underlying cells.

plot_time_slice(x, y, variable, time_logscale=False, fig=None, ax=None, cbar=True, **kwargs)[source]#

Create a heatmap for a variable over time and space.

Parameters:
  • x (Literal['x', 'y', 'z', 'time']) – What to display on the x-axis (x, y, z or time)

  • y (Literal['x', 'y', 'z', 'time']) – What to display on the y-axis (x, y, z or time)

  • variable (str | Variable) – The variable to be visualized.

  • time_logscale (bool) – Should log-scaling be applied to the time-axis?

  • fig (Figure | None) – matplotlib figure to use for plotting.

  • ax (Axes | None) – matplotlib axis to use for plotting.

  • cbar (bool) – If True, adds a colorbar.

Return type:

Figure | None

Keyword Arguments:
  • cb_labelsize: colorbar labelsize

  • cb_loc: colorbar location (‘left’ or ‘right’)

  • cb_pad: colorbar padding

  • cmap: colormap

  • vmin: minimum value for colorbar

  • vmax: maximum value for colorbar

  • num_levels: number of levels for colorbar

  • figsize: figure size

  • dpi: resolution

  • log_scaled: logarithmic scaling

property mesh_func: Callable[[UnstructuredGrid], UnstructuredGrid]#

Returns stored transformation function or identity if not given.

transform(mesh_func=lambda mesh: ...)[source]#

Apply a transformation function to the underlying mesh.

Parameters:

mesh_func (Callable[[UnstructuredGrid], UnstructuredGrid]) – A function which expects to read a mesh and return a mesh. Useful for slicing / clipping / thresholding.

Return type:

MeshSeries

Returns:

A deep copy of this MeshSeries with transformed meshes.

scale(spatial=1.0, time=1.0)[source]#

Scale the spatial coordinates and timevalues.

Useful to convert to other units, e.g. “m” to “km” or “s” to “a”. Converts from SI units (i.e. ‘m’ and ‘s’) to the given arguments. Does not create a copy, but modifies the calling object. If you want to have a scaled version without changing the original do

ms_scaled = ms.copy().scale(…)

Parameters:
  • spatial (int | float | str) – Float factor or str for target unit.

  • time (int | float | str) – Float factor or str for target unit.

Return type:

MeshSeries

Returns:

The scaled MeshSeries.

classmethod difference(ms_a, ms_b, variable=None)[source]#

Compute difference of variables between the two MeshSeries instances from which this method is called and a second MeshSeries instance passed as method parameter. Returns new instance of MeshSeries: ms = ms_a - ms_b

Parameters:
  • ms_a (MeshSeries) – The mesh from which data is to be subtracted.

  • ms_b (MeshSeries) – The mesh whose data is to be subtracted.

  • variable (Variable | str | None) – The variable of interest. If not given, all point and cell_data will be processed raw.

Return type:

MeshSeries

Returns:

MeshSeries containing the difference of variable` or of all datasets between both MeshSeries.

static compare(ms_a, ms_b, variable=None, point_data=True, cell_data=True, field_data=True, fast_compare=False, atol=0.0, *, strict=False)[source]#

Method to compare two ot.MeshSeries objects.

Returns True if they match within the tolerances, otherwise False.

Parameters:
  • ms_a (MeshSeries) – The reference base MeshSeries for comparison.

  • ms_b (MeshSeries) – The MeshSeries to compare against the reference.

  • variable (Variable | str | None) – The variable of interest. If not given, all point, cell and field data will be processed.

  • point_data (bool) – Compare all point data if variable is None.

  • cell_data (bool) – Compare all cell data if variable is None.

  • field_data (bool) – Compare all field data if variable is None.

  • fast_compare (bool) – If True, mesh topology is only verified for the first timestep, otherwise, topology is checked at every timestep.

  • atol (float) – Absolute tolerance.

  • strict (bool) – Raises an AssertionError, if mismatch.

Return type:

bool

extract(index, preference='points')[source]#

Extract a subset of the domain by point or cell indices.

Parameters:
  • index (slice | int | ndarray | list) – Indices of points or cells to extract.

  • preference (Literal['points', 'cells']) – Selected entities.

Return type:

MeshSeries

Returns:

A MeshSeries with the selected domain subset.

save(target=None, deep=True, ascii=False, overwrite=None, dry_run=False, archive=False, id=None)[source]#
Return type:

list[Path]

remove_array(name, data_type='field', skip_last=False)[source]#

Removes an array from all time slices of the mesh series.

Parameters:
  • name (str) – Array name

  • data_type (str) – Data type of the array. Could be either field, cell or point

  • skip_last (bool) – Skips the last time slice (e.g. for restart purposes).

Return type:

None

class ogstools.Meshes[source]#

Bases: MutableMapping, StorageBase

OGS input mesh. Refers to prj - file section <meshes>

Initialize a Meshes object.

Parameters:

meshes (dict[str, UnstructuredGrid]) – List of Mesh objects (pyvista UnstructuredGrid) The first mesh is the domain mesh. All following meshes represent subdomains, and their points must align with points on the domain mesh. If needed, the domain mesh itself can also be added again as a subdomain.

Returns:

A Meshes object

__init__(meshes, id=None)[source]#

Initialize a Meshes object.

Parameters:

meshes (dict[str, UnstructuredGrid]) – List of Mesh objects (pyvista UnstructuredGrid) The first mesh is the domain mesh. All following meshes represent subdomains, and their points must align with points on the domain mesh. If needed, the domain mesh itself can also be added again as a subdomain.

Returns:

A Meshes object

Return type:

None

property num_partitions: list[int]#
add_partitions(value)[source]#

Add partition counts, keeping the list sorted and deduplicated.

Return type:

None

classmethod from_folder(filepath)[source]#

Create a Meshes object from a folder of already save Meshes. Reverse of .save. It need a meta.yaml file in the specified folder.

Return type:

Meshes

__getitem__(key)[source]#
Return type:

UnstructuredGrid

classmethod from_files(filepaths, domain_key='domain')[source]#

Initialize a Meshes object from a Sequence of existing files.

Parameters:
  • filepaths (Sequence[str | Path]) – Sequence of Mesh files (.vtu) The first mesh is the domain mesh. All following meshes represent subdomains, and their points must align with points on the domain mesh.

  • domain_key (str) – String which is only in the domain filepath

Return type:

Self

classmethod from_file(meta_file)[source]#

Restore a Meshes object from a meta.yaml file.

Parameters:

meta_file (str | Path) – Path to the meta.yaml file written by Meshes.save()

Return type:

Self

Returns:

A restored Meshes object

classmethod from_id(meshes_id)[source]#

Load Meshes from the user storage path using its ID. Storage.UserPath must be set

Parameters:

meshes_id (str) – The unique ID of the Meshes object to load.

Return type:

Self

Returns:

A Meshes instance restored from disk.

classmethod from_gmsh(filename, dim=0, reindex=True, log=True, meshname='domain')[source]#

Generates pyvista unstructured grids from a gmsh mesh (.msh).

Extracts domain-, boundary- and physical group-submeshes.

Parameters:
  • filename (Path) – Gmsh mesh file (.msh) as input data

  • dim (int | Sequence[int]) – Spatial dimension (1, 2 or 3), trying automatic detection, if not given. If multiple dimensions are provided, all elements of these dimensions are embedded in the resulting domain mesh.

  • reindex (bool) – Physical groups / regions / Material IDs to be renumbered consecutively beginning with zero.

  • log (bool) – If False, silence log messages

  • meshname (str) – The name of the domain mesh and used as a prefix for subdomain meshes.

Return type:

Self

Returns:

A dictionary of names and corresponding meshes

classmethod from_yaml(geometry_file)[source]#
Return type:

Self

classmethod from_mesh(mesh, threshold_angle=15.0, domain_name='domain')[source]#

Create Meshes by extract boundaries of domain mesh.

The provided mesh must be already conforming to OGS standards.

Parameters:
  • mesh (UnstructuredGrid) – The domain mesh

  • threshold_angle (float | None) – If None, the boundary will be split by the assumption of vertical lateral boundaries. Otherwise it represents the angle (in degrees) between neighbouring elements which - if exceeded - determines the corners of the boundary mesh.

  • domain_name (str) – The name of the domain mesh.

Return type:

Self

Returns:

A Meshes object.

add_gml_subdomains(domain_path, gml_path, out_dir=None, tolerance=1e-12)[source]#

Add Meshes from geometry definition in the gml file to subdomains.

Parameters:
  • gml_file – Path to the gml file.

  • out_dir (Path | None) – Where to write the gml meshes (default: gml dir)

  • tolerance (float) – search length for node search algorithm

Return type:

None

sort()[source]#

Sort the subdomains alphanumerically.

Return type:

None

save(target=None, overwrite=None, dry_run=False, archive=False, id=None, **kwargs)[source]#

Save all meshes. If num_partitions is specified (e.g. obj.num_partition = [2,3]) is also create partitioned meshes for each partition.

This function will perform identifySubdomains, if not yet been done.

Parameters:
  • target (Path | str | None) – Optional path to the folder where meshes should be saved. If None, a temporary folder will be used.

  • overwrite (bool | None) – If True, existing mesh files will be overwritten. If False, an error is raised if any file already exists.

  • dry_run (bool) – If True: Writes no files, but returns the list of files expected to be created If False: Writes files and returns the list of created files.

  • archive (bool) – If True: The folder specified by path contains no symlinks. It copies all referenced data (which might take time and space).

  • id (str | None) – Optional identifier. Mutually exclusive with path.

Return type:

list[Path]

Returns:

A list of Paths pointing to the saved mesh files (including files for partitions).

validate(strict=True)[source]#

Validate all meshes for conformity with OGS requirements.

Meshes must be saved before validation can be performed.

Parameters:

strict (bool) – If True, raise a UserWarning if validation fails.

Return type:

bool

Returns:

True if all meshes pass validation, False otherwise.

Raises:

ValueError – If meshes have not been saved yet.

property domain: UnstructuredGrid#

Get the domain mesh.

By convention, the domain mesh is the first mesh in the dictionary of meshes when the Meshes object was constructed. The domain mesh is expected to be constant. e.g. Do not: myobject.domain = pv.Sphere()

Returns:

The domain mesh

property domain_name: str#

Get the name of the domain mesh.

By convention, the domain mesh is the first mesh in the dictionary of meshes when the Meshes object was constructed.

Returns:

The name of the domain mesh

property subdomains: dict[str, UnstructuredGrid]#

Get the subdomain meshes.

By convention, all meshes except the first one are considered subdomains. This returns a list of those subdomain meshes.

Returns:

A dictionary of {name: Mesh} for all subdomains

identify_subdomain(include_domain=False)[source]#
Return type:

None

rename_subdomains(rename_map)[source]#

Rename subdomain meshes according to the provided mapping.

Parameters:

rename_map (dict[str, str]) – A dictionary mapping old subdomain names -> new names. e.g. {‘left’:’subdomain_left’}

Return type:

None

modify_names(prefix='', suffix='')[source]#

Add prefix and/or suffix to names of meshes. Separators (underscore, etc.) have to be provided by user as part of prefix and/or suffix parameters.

Parameters:
  • prefix (str) – Prefix to be added at the beginning of the mesh name

  • suffix (str) – Suffix to be added after the mesh name

Return type:

None

rename_subdomains_legacy()[source]#

Add to the name physical_group to restore legacy convention

Return type:

None

static create_metis(domain_file, output_path, dry_run=False)[source]#

Creates a metis files. This file is needed to partition the OGS input mesh (for parallel OGS compution) using the OGS cmd line tool partmesh.

Parameters:
  • domain_file (Path | str) – A Path to existing domain mesh file (.vtu extension)

  • output – A Path to existing folder. Here the resulting metis file will be stored (.mesh)

  • dry_run (bool) – If True: Metis file is not written If False: Metis file is written

Return type:

Path

Returns:

Path to the generated metis file.

static create_partitioning(num_partitions, domain_file, subdomain_files, metis_file=None, dry_run=False)[source]#

Creates a subfolder in the metis_file’ folder. Puts .bin files into this folder that are needed as input files for running OGS parallel (MPI). Wrapper around command line tool partmesh, adding file checks, dry-run option, normalized behaviour for partition == 1 Only use this function directly when you want to bypass creating the Meshes object (e.g. files for domain and subdomains are already present)

Parameters:
  • num_partitions (int) – List of integers or a single integer that indicate the number of partitions similar to the OGS binary tool partmesh. The serial mesh will always be generated Example 1: num_partitions = [1,2,4,8,16] Example 2: num_partitions = 2

  • domain_file (Path | str) – A Path to existing domain mesh file (.vtu extension)

  • subdomain_files (Sequence[Path | str]) – A list of Path to existing subdomain files (.vtu extensions)

  • metis_file (Path | str | None) – A Path to existing metis partitioned file (.mesh extension).

  • dry_run (bool) – If True: Writes no files, but returns the list of files expected to be created If False: Writes files and returns the list of created files

Return type:

list[Path]

Returns:

A list of Paths pointing to the saved mesh files, if num_partitions are given (also just [1]), then it returns A dict, with keys representing the number of partitions and values A list of Paths (like above)

plot(**kwargs)[source]#

Plot the domain mesh and the subdomains.

keyword arguments: see ogstools.plot.contourf()

Return type:

Figure

remove_material(mat_id, tolerance=1e-12)[source]#

Remove material from meshes and update integration point data.

Parameters:
  • mat_id (int | Sequence[int]) – MaterialID/s to be removed from domain, subdomain elements, which only belonged to this material are also removed. If given as a sequence, then it must be of length 2 and all ids in between are removed.

  • tolerance (float) – Absolute distance threshold to check if subdomain nodes still have a corresponding domain node after removal of the designated material.

Return type:

None

class ogstools.Model[source]#

Bases: StorageBase

A complete OGS model combining project file, meshes, and execution settings.

The Model class integrates all components needed to run an OGS simulation: - A project file (prj) defining the simulation setup - Meshes required by the simulation - Execution parameters (parallelization, logging, etc.)

Models can be created from individual components, loaded from disk, or initialized from existing folder structures following OGSTools conventions.

Initialize a Model object.

Parameters:
  • project (Project | Path | str) – Project object or path to a .prj file. If a path is given, the Project will be loaded from that file.

  • meshes (Meshes | Path | str | None) – Meshes object or path to a folder containing mesh files. If None, attempts to locate meshes in standard locations relative to the project file (same folder or ‘meshes’ subfolder).

  • execution (Execution | Path | str | None) – Execution object or path to an execution.yaml file. If None, creates a default Execution configuration.

  • id (str | None) – Optional unique identifier for this model.

Raises:
__init__(project, meshes=None, execution=None, id=None)[source]#

Initialize a Model object.

Parameters:
  • project (Project | Path | str) – Project object or path to a .prj file. If a path is given, the Project will be loaded from that file.

  • meshes (Meshes | Path | str | None) – Meshes object or path to a folder containing mesh files. If None, attempts to locate meshes in standard locations relative to the project file (same folder or ‘meshes’ subfolder).

  • execution (Execution | Path | str | None) – Execution object or path to an execution.yaml file. If None, creates a default Execution configuration.

  • id (str | None) – Optional unique identifier for this model.

Raises:
classmethod from_folder(folder)[source]#

Initialize a Model from a folder following OGSTools conventions.

Expects the folder structure created by Model.save(): - project/: Subfolder containing project.prj and associated files - meshes/: Subfolder containing mesh files - execution.yaml: Execution configuration

Parameters:

folder (Path | str) – Path to the folder containing the model files.

Return type:

ogstools.Model

Returns:

A ogstools.Model object initialized from the folder contents.

Raises:

FileNotFoundError – If required files are not found in the folder.

classmethod from_id(model_id)[source]#

Load a Model from the user storage path using its ID.

Parameters:

model_id (str) – The unique ID of the ogstools.Model to load.

Return type:

ogstools.Model

Returns:

A ogstools.Model instance with Project and Meshes loaded from disk.

save(target=None, overwrite=None, dry_run=False, archive=False, id=None)[source]#

Save the Model to disk, including Project, Meshes, and Execution config.

Creates a folder structure containing: - project/: Subfolder with project.prj and associated files - meshes/: Subfolder with mesh files - execution.yaml: Execution configuration

By default, uses symlinks for efficiency. Use archive=True to create a standalone copy with all data materialized.

Parameters:
  • target (Path | str | None) – Path to the folder where the model should be saved. If None, uses a default location based on the model ID.

  • overwrite (bool | None) – If True, existing files are overwritten. If False, raises an error if files already exist.

  • dry_run (bool) – If True, simulates the save without writing files, but returns the list of files that would be created.

  • archive (bool) – If True, materializes all symlinks by copying referenced data (may be time and space intensive).

  • id (str | None) – Optional identifier. Mutually exclusive with target.

Return type:

list[Path]

Returns:

List of Paths to saved files (including meshes, project, and execution configuration).

run(target=None, overwrite=None, id=None)[source]#

Run a simulation to completion and wait for it to finish.

This is a convenience method that starts the simulation and blocks until it completes. For stepwise control, use start() instead.

Parameters:
  • target (Path | str | None) – Optional path for the resulting Simulation. If None, uses a default location.

  • overwrite (bool | None) – If True, overwrite existing output directory.

  • id (str | None) – Optional identifier for the resulting Simulation.

Return type:

ogstools.Simulation

Returns:

A ogstools.Simulation object containing the completed simulation results and metadata.

controller(sim_output=None, dry_run=False, overwrite=None)[source]#

Start a simulation and return a controller for execution management.

The type of controller returned depends on the execution configuration:

  • OGSInteractiveController: Allows stepwise control (execute_time_step, inspect intermediate results) when execution.interactive is True

  • OGSNativeController: Runs to completion when execution.interactive is False

Parameters:
  • sim_output (Path | str | None) – Optional path where simulation should be written. If None, uses a default location.

  • dry_run (bool) – If True, prints the command that would be executed but does not actually run the simulation.

Return type:

SimulationController

Returns:

A SimulationController for managing the simulation.

property cmd: str#

Get the full OGS command (without output path).

plot_constraints(**kwargs)[source]#

Plot the meshes with annotated boundary conditions and source terms.

keyword arguments: see contourf()

Return type:

Figure

class ogstools.Project[source]#

Bases: StorageBase

Class for handling an OGS6 project.

In this class everything for an OGS6 project can be specified.

Create a new Project instance.

Parameters:
  • input_file (str | Path | None) – Filename of the input project file

  • output_file (str | Path | None) – Filename of the output project file

  • output_dir (str | Path) – Directory of the simulation output

  • logfile (str | Path) – Filename into which the log is written

  • xml_string (str | None) – String containing the XML tree

  • verbose (bool) – If True, show verbose output

Optional Keyword Arguments:
  • OMP_NUM_THREADS: int, sets the environment variable before OGS

    execution to restrict number of OMP Threads

  • OGS_ASM_THREADS: int, sets the environment variable before OGS

    execution to restrict number of OMP Threads

__init__(input_file=None, output_file=None, output_dir=Path(), logfile='out.log', verbose=False, xml_string=None, id=None, **kwargs)[source]#

Create a new Project instance.

Parameters:
  • input_file (str | Path | None) – Filename of the input project file

  • output_file (str | Path | None) – Filename of the output project file

  • output_dir (str | Path) – Directory of the simulation output

  • logfile (str | Path) – Filename into which the log is written

  • xml_string (str | None) – String containing the XML tree

  • verbose (bool) – If True, show verbose output

Optional Keyword Arguments:
  • OMP_NUM_THREADS: int, sets the environment variable before OGS

    execution to restrict number of OMP Threads

  • OGS_ASM_THREADS: int, sets the environment variable before OGS

    execution to restrict number of OMP Threads

property prjfile: Path#

Get the path to the project file, following the current target.

classmethod from_folder(folder)[source]#

Load Project from a folder containing a default.prj file.

Parameters:

folder (Path | str) – Path to the project folder.

Return type:

Self

Returns:

A Project instance loaded from the folder.

classmethod from_id(project_id)[source]#

Load Project from the user storage path using its ID. StorageBase.Userpath must be set.

Parameters:

project_id (str) – The unique ID of the Project to load.

Return type:

Self

Returns:

A Project instance restored from disk.

dependencies(include_meshes=True, include_python_file=True, include_xml_includes=True)[source]#
Return type:

list[Path]

static dependencies_of_file(input_file, mesh_dir=None, check=False, include_meshes=True, include_python_file=True, include_xml_includes=True)[source]#

Searches a (partial) project file for included files (e.g. xml snippets, meshes (vtu,gml), python scripts) Can be used before constructing a Project object (static function).

Parameters:
  • input_file (str | Path) – Path to the prj-file

  • mesh_dir (str | Path | None) – Optional directory used to resolve referenced mesh files. If omitted, mesh paths is interpreted to be in same folder as input_file.

  • check (bool) – If True, assert that all collected files exist on disk

Return type:

list[Path]

Returns:

A list of dependency file paths (order-preserving, de-duplicated).

Raises:

AssertionError – If check=True and at least one referenced file is missing.

add_element(parent_xpath='./', tag=None, text=None, attrib_list=None, attrib_value_list=None)[source]#

General method to add an Entry.

An element is a single tag containing ‘text’, attributes and anttribute values.

Parameters:
  • parent_xpath (str) – XPath of the parent tag

  • tag (str | None) – tag name

  • text (str | int | float | None) – content

  • attrib_list (list[str] | None) – list of attribute keywords

  • attrib_value_list (list[str] | None) – list of values of the attribute keywords

Return type:

None

add_include(parent_xpath='./', file='')[source]#

Add include element.

Parameters:
  • parent_xpath (str) – XPath of the parent tag

  • file (str) – file name

Return type:

None

add_block(blocktag, block_attrib=None, parent_xpath='./', taglist=None, textlist=None)[source]#

General method to add a Block.

A block consists of an enclosing tag containing a number of subtags retaining a key-value structure.

Parameters:
  • blocktag (str) – name of the enclosing tag

  • block_attrib (Any | None) – attributes belonging to the blocktag

  • parent_xpath (str) – XPath of the parent tag

  • taglist (list[str] | None) – list of strings containing the keys

  • textlist (list[Any] | None) – list retaining the corresponding values

Return type:

None

deactivate_property(name, mediumid=0, phase=None)[source]#

Replaces MPL properties by a comment.

Parameters:
  • mediumid (int) – id of the medium

  • phase (str | None) – name of the phase

  • name (str) – property name

Return type:

None

deactivate_parameter(name)[source]#

Replaces parameters by a comment.

Parameters:

name (str) – property name

Return type:

None

remove_element(xpath, tag=None, text=None)[source]#

Removes an element.

Parameters:
Return type:

None

replace_text(value, xpath='.', occurrence=-1)[source]#

General method for replacing text between opening and closing tags.

Parameters:
  • value (str | int | float) – Text

  • xpath (str) – XPath of the tag

  • occurrence (int) – Easy way to address nonunique XPath addresses by their occurrence from the top of the XML file

Return type:

None

replace_block_by_include(xpath='./', filename='include.xml', occurrence=0)[source]#

General method for replacing a block by an include.

Parameters:
  • xpath (str) – XPath of the tag

  • filename (str) – name of the include file

  • occurrence (int) – Addresses nonunique XPath by their occurrence

Return type:

None

replace_mesh(oldmesh, newmesh)[source]#

Method to replace meshes.

Parameters:
Return type:

None

replace_parameter(name='', parametertype='', taglist=None, textlist=None)[source]#

Replacing parametertypes and values.

Parameters:
  • name (str) – parametername

  • parametertype (str) – parametertype

  • taglist (list[str] | None) – list of tags needed for parameter spec

  • textlist (list[str] | None) – values of parameter

Return type:

None

replace_parameter_value(name='', value=0, valuetag='value')[source]#

Replacing parameter values.

Parameters:
  • name (str) – parametername

  • value (int | float | str) – value

  • parametertype – parameter type

  • valuetag (str) – name of the tag containing the value, e.g., values

Return type:

None

replace_phase_property_value(mediumid=0, phase='AqueousLiquid', component=None, name='', value=0, propertytype='Constant', valuetag='value')[source]#

Replaces properties in medium phases.

Parameters:
  • mediumid (int) – id of the medium

  • phase (str) – name of the phase

  • component (str | None) – name of the component

  • name (str) – property name

  • value (int | float | str) – value

  • propertytype (str) – type of the property

  • valuetag (str) – name of the tag containing the value, e.g., values

Return type:

None

replace_medium_property_value(mediumid=0, name='', value=0, propertytype='Constant', valuetag='value')[source]#

Replaces properties in medium (not belonging to any phase).

Parameters:
  • mediumid (int) – id of the medium

  • name (str) – property name

  • value (int | float | str) – value

  • propertytype (str) – type of the property

  • valuetag (str) – name of the tag containing the value, e.g., values

Return type:

None

set(**args)[source]#

Sets directly a uniquely defined property. List of properties is given in the dictionary below.

Return type:

None

meshseries_file()[source]#
Return type:

Path

run_model(logfile=Path('out.log'), path=None, args=None, container_path=None, wrapper=None, write_logs=True, background=False)[source]#

Command to run OGS.

Runs OGS with the project file specified as output_file.

Parameters:
  • logfile (Path | None) – Name of the file to write STDOUT of ogs

  • path (Path | None) – Path of the directory in which the ogs executable can be found. If container_path is given: Path to the directory in which the Apptainer executable can be found.

  • args (Any | None) – additional arguments for the ogs executable

  • container_path (Path | str | None) – Path of the OGS container file.

  • wrapper (Any | None) – add a wrapper command. E.g. mpirun

  • write_logs (bool) – set False to omit logging

  • write_prj_to_pvd – write the prj file as a comment in the pvd

  • background (bool) – Run the simulation in a background process

Return type:

Popen

write_input(prjfile_path=None, keep_includes=False)[source]#

Writes the projectfile to disk.

Parameters:
  • prjfile_path (None | Path | str) – Path to write the project file to. If not specified, the initialised path is used.

  • keep_includes (bool)

Return type:

None

save(target=None, overwrite=None, dry_run=False, archive=False, keep_includes=False, id=None)[source]#

Saves the project file and referenced files (except meshes)

Parameters:
  • target (Path | str | None) – Optional path to the project folder. If None, a temporary folder will be used.

  • overwrite (bool | None) – If True, existing prj file(s) will be overwritten. If False, an error is raised if any file already exists.

  • dry_run (bool) – If True: Writes no files, but returns the list of files expected to be created If False: Writes files and returns the list of created files.

  • archive (bool) – If True: The folder specified by path contains no symlinks. It copies all referenced data (which might take time and space).

  • id (str | None) – Optional identifier. Mutually exclusive with target.

Return type:

list[Path]

Returns:

A list of Paths pointing to the saved prj file(s)

property_dataframe(mediamapping=None)[source]#

Returns a dataframe containing most properties defined in the Material Property (MPL) section of the input file.

Parameters:

mediamapping (dict[int, str] | None)

Return type:

DataFrame

write_property_latextable(latexfile=Path('property_dataframe.tex'), mediamapping=None, float_format='{:.2e}')[source]#

Write material properties to disc as latex table.

Parameters:
Return type:

None

set_media(media_set)[source]#

Public API: import MediaSet into this Project.

Return type:

None

meshpaths(mesh_dir=None)[source]#

Returns the filepaths to the given meshes in the Project.

This does not include meshes defined via a .gml file.

Parameters:

mesh_dir (Path | None) – Path to the meshes directory (default: input dir)

Return type:

list[Path]

param_value_expression(param_name)[source]#

Return the text of the parameter value/s or expression.

Parameters:

param_name (str) – Name of the parameter whose value is returned.

Return type:

str

constraints()[source]#

Creates a dict of boundary conditions and source terms.

Structured in the following way: {meshname: {process_variable_name: [constraint_data]}}

Return type:

dict[str, dict[str, list]]

constraints_labels()[source]#

Formatted information about boundary conditions and source terms.

Return type:

dict[str, str]

Returns:

Formatted str of constraints per meshname.

Example output:

{
    "domain": "domain:\n  $T$=-8./3600*t+277.15\n  $p$=0",
    "bottom": "bottom:\n  $u$$_y$=0",
    "left": "left:\n  $u$$_x$=0",
}
class ogstools.Simulation[source]#

Bases: StorageBase

A completed or ongoing OGS simulation with associated model and results.

Combines a Model (project setup) with Results (output data) and provides convenient access to simulation outputs like mesh series and log files. Simulations can be saved, loaded, and analyzed after completion.

Initialize a Simulation object.

Parameters:
  • model (Model) – The ogstools.Model used for this simulation.

  • result (Result) – The Result object containing simulation output.

Status#

alias of SimulationStatus

classmethod from_id(simulation_id)[source]#

Load a Simulation from the user storage path using its ID.

Parameters:

simulation_id (str) – The unique identifier of the ogstools.Simulation to load.

Return type:

Self

Returns:

A ogstools.Simulation instance restored from disk.

Raises:

FileNotFoundError – If no simulation with the given ID exists.

classmethod from_folder(sim_folder)[source]#

Load a Simulation from a folder following OGSTools conventions.

Expects the folder structure created by Simulation.save(): - model/: Subfolder containing the Model - result/: Subfolder containing simulation results

Parameters:

sim_folder (Path | str) – Path to the folder containing the simulation.

Return type:

Self

Returns:

A ogstools.Simulation instance loaded from the folder.

Raises:

FileNotFoundError – If required components are not found.

__init__(model, result)[source]#

Initialize a Simulation object.

Parameters:
  • model (Model) – The ogstools.Model used for this simulation.

  • result (Result) – The Result object containing simulation output.

property status: SimulationStatus#

Get the current simulation status from the return code file.

Reads the returncode file written by the simulation controller to determine if the simulation completed successfully or with an error.

Returns:

SimulationStatus enum value (running, done, error, or unknown).

property status_str: str#

Get a human-readable status description of the simulation.

Includes information about completion status and result availability.

Returns:

String describing the simulation state.

property cmd: str#

Get the full command used to run the simulation.

property log_file: Path#

Get the absolute path to the log file.

property log: Log#

Access the parsed log file of this simulation.

Lazily loads and parses the log file on first access.

Returns:

A Log object for querying simulation log data.

property meshseries_file: Path#

Get the path to the mesh series output file.

Returns:

Path to the mesh series file (pvd, xdmf, etc.).

property meshseries: MeshSeries#

Access the mesh series of this simulation.

Lazily loads the mesh series on first access.

Returns:

A MeshSeries containing the simulation results.

save(target=None, overwrite=None, dry_run=False, archive=False, id=None)[source]#

Save the Simulation to disk, including Model and Result.

Creates a folder structure containing: - model/: The Model (project, meshes, execution config) - result/: The simulation results

Parameters:
  • target (Path | str | None) – Path to save the ogstools.Simulation. If None, uses a default location.

  • overwrite (bool | None) – If True, overwrite existing files. Defaults to False.

  • dry_run (bool) – If True, simulate save without writing files.

  • archive (bool) – If True, materialize all symlinks by copying data.

  • id (str | None) – Optional identifier. Mutually exclusive with target.

Return type:

list[Path]

Returns:

List of Paths to saved files.

restart(restart_suffix='_restart', zero_displacement=False, initialize_porosity_from_medium_property=False, *, t_initial=None, t_end=None, initial_dt=None, timevalues=None)[source]#

Prepares the PRJ file for a restart run.

Supports two mutually exclusive modes: - Time-range mode: use t_initial and t_end (optionally initial_dt). - Explicit-times mode: use timevalues only.

The method reads the last written time step from the PVD referenced in the PRJ and updates initial conditions, output prefix, and time control blocks accordingly. If zero_displacement is True, displacement initial conditions are set to zero. restart_suffix is appended to the output prefix.

t_initial/t_end and timevalues must not be used together. All time-scheme control arguments are keyword-only.

Parameters:
  • restart_suffix (str) – appended to the output prefix. Default: “_restart”

  • zero_displacement (bool) – set displacement initial conditions to zero. Default is False.

  • t_initial (float | None) – restart interval start time (time-range mode)

  • t_end (float | None) – restart interval end time (time-range mode)

  • initial_dt (float | None) – initial time step (time-range mode)

  • timevalues (list | None) – explicit list of restart times (explicit-times mode)

Return type:

Model

Returns:

None

Subpackages#

Submodules#