ogstools package#
- class ogstools.Execution[source]#
Bases:
StorageBaseConfiguration 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_pathparameter 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 asogs.
Use pre-built container image URLs:
Execution(ogs_path=Execution.CONTAINER_PARALLEL_V6_5_7)
When
ogsis not set, the executable is looked up viaOGS_BIN_PATHand, if not defined, on PATH.Site-wide defaults via
OGS_EXECUTION_DEFAULTSPoint 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 (seeogs --helpfor 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 viaOGS_BIN_PATHor 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.Noneomits the-lflag (OGS default isinfo).id (
str|None) – Optional unique identifier for this execution config.
- 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
Executioninstance, 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 (seeogs --helpfor 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 viaOGS_BIN_PATHor 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.Noneomits the-lflag (OGS default isinfo).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:
- 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.
- 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
Nonefor native execution.
- class ogstools.Log[source]#
Bases:
objectParser 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.
- convergence_coupling_iteration()[source]#
Extract coupling iteration convergence data.
- Return type:
- Returns:
DataFrame with coupling iteration convergence information.
- convergence_newton_iteration()[source]#
Extract Newton iteration convergence data.
- Return type:
- Returns:
DataFrame with Newton iteration convergence metrics (errors, residuals, convergence order).
- simulation()[source]#
Extract overall simulation information.
- Return type:
- Returns:
DataFrame with simulation-level data.
- simulation_termination()[source]#
Extract simulation termination information.
- Return type:
- Returns:
DataFrame with termination status and final state.
- time_step()[source]#
Extract time step information.
- Return type:
- 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”: residualx_metric (
Literal['time_step','model_time']) – x_axis representation: - “time_step”: timestep number - “model_time”: simulation timekwargs (
Any) – Additional arguments passed to heatmap function (seeheatmap()).
- Return type:
- 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 timekwargs (
Any) – Additional arguments passed to heatmap function. Default scale is limited to 0-2 for meaningful data.
- Return type:
- Returns:
A matplotlib Figure with the convergence order heatmap.
- class ogstools.MaterialManager[source]#
Bases:
objectManager for material definitions loaded from a repository of YAML files.
A MaterialManager can be constructed in two ways:
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.
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.
- 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:
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:
objectRepresents 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.processmust 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.
- get_by_id(material_id)[source]#
Lookup a Medium by its material ID.
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:
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.
- class ogstools.MeshSeries[source]#
Bases:
Sequence[UnstructuredGrid],StorageBaseA 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:
- 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:
- 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:
- resample_temporal(timevalues)[source]#
Return a new MeshSeries interpolated to the given timevalues.
- Return type:
- probe(points, data_name=None, interp_method='linear')[source]#
Create a new MeshSeries by probing points on an existing MeshSeries.
- Parameters:
- Return type:
- Returns:
A MeshSeries (Pointcloud) containing the probed data.
- aggregate_temporal(variable, func)[source]#
Aggregate data over all timesteps using a specified function.
- Parameters:
- Return type:
- Returns:
A mesh with aggregated data according to the given function.
- closest_timestep(timevalue)[source]#
Return the corresponding timestep from a timevalue.
- Return type:
- 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
- mesh_interp(timevalue, lazy_eval=True)[source]#
Return the temporal interpolated mesh for a given timevalue.
- Return type:
- 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:
- 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.
- time_of_min(variable)[source]#
Returns a Mesh with the time of the variable minimum as data.
- Return type:
- time_of_max(variable)[source]#
Returns a Mesh with the time of the variable maximum as data.
- Return type:
- aggregate_spatial(variable, func)[source]#
Aggregate data over domain per timestep using a specified function.
- 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:
- 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:
- 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)time_logscale (
bool) – Should log-scaling be applied to the time-axis?fig (
Figure|None) – matplotlib figure to use for plotting.cbar (
bool) – If True, adds a colorbar.
- Return type:
- 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:
- 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(…)
- 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:
- 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.MeshSeriesobjects.Returns
Trueif they match within the tolerances, otherwiseFalse.- 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) – IfTrue, mesh topology is only verified for the first timestep, otherwise, topology is checked at every timestep.atol (
float) – Absolute tolerance.strict (
bool) – Raises anAssertionError, if mismatch.
- Return type:
- extract(index, preference='points')[source]#
Extract a subset of the domain by point or cell indices.
- save(target=None, deep=True, ascii=False, overwrite=None, dry_run=False, archive=False, id=None)[source]#
- class ogstools.Meshes[source]#
Bases:
MutableMapping,StorageBaseOGS 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
- add_partitions(value)[source]#
Add partition counts, keeping the list sorted and deduplicated.
- Return type:
- 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:
- classmethod from_files(filepaths, domain_key='domain')[source]#
Initialize a Meshes object from a Sequence of existing files.
- 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 datadim (
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 messagesmeshname (
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_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 meshthreshold_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.
- 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:
- 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:
- 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
- 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.
- rename_subdomains_legacy()[source]#
Add to the name physical_group to restore legacy convention
- Return type:
- 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:
- Return type:
- 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 = 2domain_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:
- 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:
- 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:
- class ogstools.Model[source]#
Bases:
StorageBaseA 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:
ValueError – If meshes cannot be found or located automatically.
FileNotFoundError – If specified paths do not exist.
- __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:
ValueError – If meshes cannot be found or located automatically.
FileNotFoundError – If specified paths do not exist.
- 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.Modelobject 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 theogstools.Modelto load.- Return type:
ogstools.Model
- Returns:
A
ogstools.Modelinstance 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:
- 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:
- Return type:
ogstools.Simulation
- Returns:
A
ogstools.Simulationobject 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:
- Return type:
- Returns:
A SimulationController for managing the simulation.
- plot_constraints(**kwargs)[source]#
Plot the meshes with annotated boundary conditions and source terms.
keyword arguments: see
contourf()- Return type:
- class ogstools.Project[source]#
Bases:
StorageBaseClass 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 fileoutput_file (
str|Path|None) – Filename of the output project fileoutput_dir (
str|Path) – Directory of the simulation outputlogfile (
str|Path) – Filename into which the log is writtenverbose (
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 fileoutput_file (
str|Path|None) – Filename of the output project fileoutput_dir (
str|Path) – Directory of the simulation outputlogfile (
str|Path) – Filename into which the log is writtenverbose (
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
- 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.
- 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:
- Return type:
- 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.
- 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:
- Return type:
- replace_text(value, xpath='.', occurrence=-1)[source]#
General method for replacing text between opening and closing tags.
- replace_block_by_include(xpath='./', filename='include.xml', occurrence=0)[source]#
General method for replacing a block by an include.
- replace_parameter(name='', parametertype='', taglist=None, textlist=None)[source]#
Replacing parametertypes and values.
- replace_phase_property_value(mediumid=0, phase='AqueousLiquid', component=None, name='', value=0, propertytype='Constant', valuetag='value')[source]#
Replaces properties in medium phases.
- Parameters:
- Return type:
- replace_medium_property_value(mediumid=0, name='', value=0, propertytype='Constant', valuetag='value')[source]#
Replaces properties in medium (not belonging to any phase).
- set(**args)[source]#
Sets directly a uniquely defined property. List of properties is given in the dictionary below.
- Return type:
- 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 ogspath (
Path|None) – Path of the directory in which the ogs executable can be found. Ifcontainer_pathis given: Path to the directory in which the Apptainer executable can be found.args (
Any|None) – additional arguments for the ogs executablecontainer_path (
Path|str|None) – Path of the OGS container file.write_logs (
bool) – set False to omit loggingwrite_prj_to_pvd – write the prj file as a comment in the pvd
background (
bool) – Run the simulation in a background process
- Return type:
- 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:
- 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.
- write_property_latextable(latexfile=Path('property_dataframe.tex'), mediamapping=None, float_format='{:.2e}')[source]#
Write material properties to disc as latex table.
- 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.
- constraints()[source]#
Creates a dict of boundary conditions and source terms.
Structured in the following way: {meshname: {process_variable_name: [constraint_data]}}
- class ogstools.Simulation[source]#
Bases:
StorageBaseA 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) – Theogstools.Modelused 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 theogstools.Simulationto load.- Return type:
Self- Returns:
A
ogstools.Simulationinstance 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.Simulationinstance loaded from the folder.- Raises:
FileNotFoundError – If required components are not found.
- __init__(model, result)[source]#
Initialize a Simulation object.
- Parameters:
model (
Model) – Theogstools.Modelused 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 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 theogstools.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:
- 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_initialandt_end(optionallyinitial_dt). - Explicit-times mode: usetimevaluesonly.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_displacementis True, displacement initial conditions are set to zero.restart_suffixis appended to the output prefix.t_initial/t_endandtimevaluesmust 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:
- Returns:
None
Subpackages#
- ogstools.core namespace
- Submodules
- ogstools.feflowlib package
- ogstools.gmsh_tools package
- ogstools.logparser package
analysis_convergence_coupling_iteration()analysis_convergence_newton_iteration()analysis_simulation()analysis_simulation_termination()analysis_time_step()convergence_order_per_ts_iteration()errors_per_ts_iteration()fill_ogs_context()model_and_clock_time()ogs_regexes()parse_file()plot_convergence()plot_convergence_order()read_version()time_step_vs_iterations()time_step_vs_step_size_and_time()- Submodules
- ogstools.logparser.common_ogs_analyses module
pre_post_check()analysis_time_step()analysis_simulation()analysis_convergence_newton_iteration()analysis_convergence_coupling_iteration()time_step_vs_iterations()time_step_vs_step_size_and_time()errors_per_ts_iteration()convergence_order_per_ts_iteration()model_and_clock_time()analysis_simulation_termination()fill()fill_ogs_context()
- ogstools.logparser.log module
- ogstools.logparser.log_file_handler module
- ogstools.logparser.log_parser module
- ogstools.logparser.plots module
- ogstools.logparser.regexes module
LogInfoTerminationWarningTypeErrorTypeCriticalTypeMPIProcessNoRankOutputOGSVersionLogOGSVersionLog2StepStatusContextTimeStepContextTimeStepProcessContextTimeStepProcessIterationContextAssemblyTimeTimeStepEndIterationStartIterationEndCouplingIterationStartCouplingIterationEndTimeStepStartTimeStepOutputTimeSolvingProcessStartSolvingProcessEndTimeStepSolutionTimeCoupledSchemeTimeStepFinishedTimeDirichletTimeLinearSolverTimeMeshReadTimeSimulationExecutionTimeSimulationExecutionTimeFailedSimulationAbortComponentConvergenceCriterionTimeStepConvergenceCriterionCouplingIterationConvergenceGenericCodePointPhaseFieldEnergyVarErrorMessageCriticalMessageWarningMessageSimulationStartTimeSimulationEndTimeSimulationEndTimeFailedogs_regexes()new_regexes()
- ogstools.logparser.common_ogs_analyses module
- ogstools.materiallib package
- ogstools.mesh package
check_datatypes()depth()difference()difference_matrix()difference_pairwise()from_simulator()ip_data_threshold()ip_metadata()node_reordering()read()save()to_ip_mesh()to_ip_point_cloud()validate()- Subpackages
- Submodules
- ogstools.meshes package
- ogstools.meshseries package
- ogstools.msh2vtu package
- ogstools.ogs6py package
- Submodules
- ogstools.ogs6py.build_tree module
- ogstools.ogs6py.curves module
- ogstools.ogs6py.display module
- ogstools.ogs6py.geo module
- ogstools.ogs6py.linsolvers module
- ogstools.ogs6py.local_coordinate_system module
- ogstools.ogs6py.media module
- ogstools.ogs6py.mesh module
- ogstools.ogs6py.nonlinsolvers module
- ogstools.ogs6py.parameters module
- ogstools.ogs6py.processes module
- ogstools.ogs6py.processvars module
- ogstools.ogs6py.project module
- ogstools.ogs6py.project_media_importer module
- ogstools.ogs6py.properties module
- ogstools.ogs6py.python_script module
- ogstools.ogs6py.timeloop module
- Submodules
- ogstools.physics package
- ogstools.plot package
animate()compute_levels()contourf()contourf_pv()heatmap()line()quiver()shape_on_top()streamlines()subplot()- Submodules
- ogstools.plot.animation module
- ogstools.plot.contourplots module
- ogstools.plot.contourplots_pv module
- ogstools.plot.features module
- ogstools.plot.heatmaps module
- ogstools.plot.levels module
- ogstools.plot.lineplots module
- ogstools.plot.plot_setup module
- ogstools.plot.plot_setup_defaults module
- ogstools.plot.shared module
- ogstools.plot.utils module
- ogstools.plot.vectorplots module
- ogstools.studies package
- ogstools.variables package
MatrixMatrix.__getitem__()Matrix.to_polar()Matrix.magnitudeMatrix.traceMatrix.eigenvaluesMatrix.eigenvectorsMatrix.detMatrix.invariant_1Matrix.invariant_2Matrix.invariant_3Matrix.tensor_meanMatrix.hydrostatic_componentMatrix.deviatorMatrix.deviator_invariant_1Matrix.deviator_invariant_2Matrix.deviator_invariant_3Matrix.octahedral_shearMatrix.von_MisesMatrix.qp_ratio
ScalarVariableVariable.__init__()Variable.data_nameVariable.data_unitVariable.output_unitVariable.output_nameVariable.symbolVariable.maskVariable.func()Variable.mesh_dependentVariable.process_with_unitsVariable.cmapVariable.bilinear_cmapVariable.categoricVariable.colorVariable.type_nameVariable.replace()Variable.from_variable()Variable.find()Variable.transform()Variable.get_output_unitVariable.minVariable.maxVariable.meanVariable.medianVariable.sumVariable.stdVariable.varVariable.differenceVariable.abs_errorVariable.rel_errorVariable.anasolVariable.is_mask()Variable.get_mask()Variable.magnitudeVariable.mask_used()Variable.get_label()
Vector- Submodules
- ogstools.variables.custom_colormaps module
- ogstools.variables.matrix module
- ogstools.variables.mesh_dependent module
- ogstools.variables.tensor_math module
identity()sym_tensor_to_mat()mat_to_sym_tensor()trace()matrix_trace()eigenvalues()eigenvectors()det()frobenius_norm()invariant_1()invariant_2()invariant_3()mean()effective_pressure()hydrostatic_component()deviator()deviator_invariant_1()deviator_invariant_2()deviator_invariant_3()octahedral_shear()von_mises()qp_ratio()to_polar()
- ogstools.variables.unit_registry module
- ogstools.variables.variable module
- ogstools.variables.vector module
- ogstools.workflow package