API reference#
ogstools package#
- 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.
- get_material(name)[source]#
Retrieve a material from the repository by name.
- Return type:
Material | None
- 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.
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.
- Return type:
- 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.
- 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.
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.
- Return type:
Medium | None
- classmethod from_project(prj, process)[source]#
Reconstruct a Media collection from an OGS6py Project.
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.
- Return type:
- class ogstools.MeshSeries[source]#
Bases:
Sequence[UnstructuredGrid]A wrapper around pyvista and meshio for reading of pvd and xdmf timeseries.
Initialize a MeshSeries object
- param filepath:
Path to the PVD or XDMF file.
- param spatial_unit:
Unit/s of the mesh points. See note.
- param time_unit:
Unit/s of the timevalues. See note.
- returns:
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')[source]#
Initialize a MeshSeries object
- param filepath:
Path to the PVD or XDMF file.
- param spatial_unit:
Unit/s of the mesh points. See note.
- param time_unit:
Unit/s of the timevalues. See note.
- returns:
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:
- 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
- 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:
- Returns:
A MeshSeries (Pointcloud) containing the probed data.
- Return type:
- interpolate(mesh, data_name=None)[source]#
Create a new MeshSeries by spatial interpolation.
- Parameters:
- Returns:
A spatially interpolated MeshSeries.
- Return type:
- copy(deep=True)[source]#
Create a copy of MeshSeries object. Deep copy is the default.
- Parameters:
deep (bool) – switch to choose between deep (default) and shallow (self.copy(deep=False)) copy.
- Returns:
Copy of self.
- Return type:
- __getitem__(index: int) UnstructuredGrid[source]#
- __getitem__(index: slice | Sequence) MeshSeries
- __getitem__(index: str) ndarray
- 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
- Returns:
A mesh with aggregated data according to the given function.
- Return type:
UnstructuredGrid
- 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
- 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
- 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.
- Return type:
Path | 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: str | Variable) ndarray[source]#
- values(variable: list[str | Variable]) list[ndarray]
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 – Data to read/process from the MeshSeries. Can also be a list of str or Variable.
- 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:
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
- Returns:
A numpy array with aggregated data.
- Return type:
ndarray
- 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
- 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.
- Return type:
ndarray | list[ndarray]
- 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.
- Returns:
A deep copy of this MeshSeries with transformed meshes.
- Return type:
- 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.
- Parameters:
spatial (int | float | str) – Float factor or str for target unit.
time (int | float | str) – Float factor or str for target unit.
- Returns:
None.
- Return type:
None
- 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.
- Returns:
MeshSeries containing the difference of variable` or of all datasets between both MeshSeries.
- Return type:
- static compare(ms_a, ms_b, variable=None, point_data=True, cell_data=True, field_data=True, 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 and cell data will be processed.
point_data (bool) – Compare all point data if variable is None. Default is
True.cell_data (bool) – Compare all cell data if variable is None. Default is
True.field_data (bool) – Compare all field data if variable is None. Default is
True.atol (float) – Absolute tolerance. Default is
0.0.strict (bool) – Raises an
AssertionError, if mismatch. Default isFalse.
- 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.
- Returns:
A MeshSeries with the selected domain subset.
- Return type:
- save(filename, deep=True, ascii=False)[source]#
Save mesh series to disk.
- Parameters:
filename (str) – Filename to save the series to. Extension specifies the file type. Currently only PVD is supported.
deep (bool) – Specifies whether VTU/H5 files should be written.
ascii (bool) – Specifies if ascii or binary format should be used, defaults to binary (False) - True for ascii.
- 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).
- class ogstools.Meshes[source]#
Bases:
MutableMappingOGS input mesh. Refers to prj - file section <meshes>
- Initialize a Meshes object.
- param meshes:
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)[source]#
- Initialize a Meshes object.
- param meshes:
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
- classmethod from_files(filepaths)[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.
- Return type:
Self
- 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.
- Returns:
A dictionary of names and corresponding meshes
- Return type:
Self
- classmethod from_mesh(mesh, threshold_angle=15.0, domain_name='domain')[source]#
Extract 1D boundaries of a 2D mesh.
- Parameters:
mesh (UnstructuredGrid) – The 2D domain
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.
- Returns:
A Meshes object.
- Return type:
Self
- 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
- 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
- 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’}
- 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
- Returns:
Path to the generated metis file.
- Return type:
Path
- 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
- 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)
- Return type:
list[Path]
- save(meshes_path=None, overwrite=False, num_partitions=None, dry_run=False)[source]#
Save all meshes.
This function will perform identifySubdomains, if not yet been done.
- Parameters:
meshes_path (Path | str | None) – Optional path to the directory where meshes should be saved. It must already exist (will not be created). If None, a temporary directory will be used.
overwrite (bool) – If True, existing mesh files will be overwritten. If False, an error is raised if any file already exists.
num_partitions (int | Sequence[int] | None) – 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
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
- 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)
- Return type:
list[Path] | dict[int, list[Path]]
- 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.
- class ogstools.Project[source]#
Bases:
objectClass for handling an OGS6 project.
In this class everything for an OGS6 project can be specified.
Create a new Project instance.
- Parameters:
input_file – Filename of the input project file
output_file – Filename of the output project file
output_dir – Directory of the simulation output
logfile – Filename into which the log is written
xml_string – String containing the XML tree
verbose – 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='default.prj', output_dir=Path(), logfile='out.log', verbose=False, xml_string=None, **kwargs)[source]#
Create a new Project instance.
- Parameters:
input_file (Path | str | None) – Filename of the input project file
output_file (str | Path) – 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
- static dependencies(input_file, mesh_dir=None, check=False)[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 (Path | str | 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
- Returns:
A list of dependency file paths (order-preserving, de-duplicated).
- Raises:
AssertionError – If check=True and at least one referenced file is missing.
- Return type:
list[Path]
- 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
- add_include(parent_xpath='./', file='')[source]#
Add include element.
- Parameters:
parent_xpath (str) – XPath of the parent tag
file (str) – file name
- 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
- 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
- deactivate_parameter(name)[source]#
Replaces parameters by a comment.
- Parameters:
name (str) – property name
- remove_element(xpath, tag=None, text=None)[source]#
Removes an element.
- Parameters:
xpath (str)
tag (str | None)
text (str | None)
- replace_text(value, xpath='.', occurrence=-1)[source]#
General method for replacing text between opening and closing tags.
- Parameters:
value (str | int) – 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
- 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 occurece
- replace_mesh(oldmesh, newmesh)[source]#
Method to replace meshes.
- Parameters:
oldmesh (str)
newmesh (str)
- 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
- replace_parameter_value(name='', value=0, valuetag='value')[source]#
Replacing parameter values.
- Parameters:
name (str) – parametername
value (int) – value
parametertype – parameter type
valuetag (str) – name of the tag containing the value, e.g., 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:
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) – value
propertytype (str) – type of the property
valuetag (str) – name of the tag containing the value, e.g., values
- 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) – value
propertytype (str) – type of the property
valuetag (str) – name of the tag containing the value, e.g., values
- set(**args)[source]#
Sets directly a uniquely defined property. List of properties is given in the dictory below.
- restart(restart_suffix='_restart', t_initial=None, t_end=None, zero_displacement=False)[source]#
Prepares the project file for a restart.
Takes the last time step from the PVD file mentioned in the PRJ file. Sets initial conditions accordingly.
- Parameters:
restart_suffix (str) – suffix by which the output prefix is appended
t_initial (float | None) – first time step, takes the last from previous simulation if None
t_end (float | None) – last time step, the same as in previous run if None
zero_displacement (bool) – sets the initial displacement to zero if True
- run_model(logfile=Path('out.log'), path=None, args=None, container_path=None, wrapper=None, write_logs=True, write_prj_to_pvd=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_pathis given: Path to the directory in which the Singularity 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 (bool) – write the prj file as a comment in the pvd
background (bool) – Run the simulation in a background process
- property status: str#
- Returns string:
describes the status of the model execution.
- terminate_run()[source]#
Aborts simulation if it is running.
- Returns bool:
True if the run was terminated successfully, False otherwise.
- Return type:
bool
- write_input(prjfile_path=None, keep_includes=False)[source]#
Writes the projectfile to disk.
- Parameters:
prjfile_path (Path | None) – Path to write the project file to. If not specified, the initialised path is used.
keep_includes (bool)
- 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:
latexfile (Path)
mediamapping (dict[int, str] | None)
float_format (str)
- gml_filepath(mesh_dir=None)[source]#
Returns the filepath gml file if given in the Project.
- Parameters:
mesh_dir (Path | None) – Path to the meshes directory (default: input dir)
- Return type:
Path | 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.
- Returns:
Formatted str of constraints per meshname.
- Return type:
dict[str, str]
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", }
- plot_constraints(mesh_dir=None, **kwargs)[source]#
Plot the meshes with annotated boundary conditions and source terms.
keyword arguments: see
contourf()- Return type:
Figure
- ogstools.cli(check=False)[source]#
Allows access to ogs binary tools via python and performs checks to see if OGS is installed correctly.
- Parameters:
check (bool) – If True, verify that OGS is available on PATH and warn if multiple versions are found.
- Return type:
Any
Example cli().vtkdiff(“file1.vtu”, “file2.vtu”)
- Returns:
A CLI object that supports ogs command line tools.
- Return type:
Any
- ogstools.status(verbose=False)[source]#
- Checks if OGS is installed correctly. It prints detailed error message if OGS is not installed correctly.
- param verbose:
If verbose is True it prints always the status of related environment variables. (OGS_BIN_PATH, PATH, virtual environment)
- Returns:
True if OGS is installed correctly, False otherwise.
- Return type:
bool
Subpackages#
- 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()- 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()errors_per_ts_iteration()convergence_order_per_ts_iteration()model_and_clock_time()analysis_simulation_termination()fill()fill_ogs_context()
- 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
depth()difference()difference_matrix()difference_pairwise()from_simulator()ip_data_threshold()ip_metadata()p_fluid()read()save()to_ip_mesh()to_ip_point_cloud()- Subpackages
- Submodules
- ogstools.meshes package
MeshesMeshes.__init__()Meshes.__getitem__()Meshes.from_files()Meshes.from_gmsh()Meshes.from_yaml()Meshes.from_mesh()Meshes.add_gml_subdomains()Meshes.sort()Meshes.domainMeshes.domain_nameMeshes.subdomainsMeshes.identify_subdomain()Meshes.rename_subdomains()Meshes.rename_subdomains_legacy()Meshes.create_metis()Meshes.create_partitioning()Meshes.save()Meshes.plot()Meshes.remove_material()
- Submodules
- ogstools.meshseries package
MeshSeriesMeshSeries.__init__()MeshSeries.from_data()MeshSeries.extend()MeshSeries.resample_temporal()MeshSeries.probe()MeshSeries.interpolate()MeshSeries.copy()MeshSeries.__getitem__()MeshSeries.items()MeshSeries.aggregate_temporal()MeshSeries.clear_cache()MeshSeries.closest_timestep()MeshSeries.closest_timevalue()MeshSeries.ip_tesselated()MeshSeries.mesh()MeshSeries.rawdata_file()MeshSeries.mesh_interp()MeshSeries.timevaluesMeshSeries.timestepsMeshSeries.values()MeshSeries.point_dataMeshSeries.cell_dataMeshSeries.field_dataMeshSeries.time_of_min()MeshSeries.time_of_max()MeshSeries.aggregate_spatial()MeshSeries.probe_values()MeshSeries.plot_line()MeshSeries.plot_time_slice()MeshSeries.mesh_funcMeshSeries.transform()MeshSeries.scale()MeshSeries.difference()MeshSeries.compare()MeshSeries.extract()MeshSeries.save()MeshSeries.remove_array()
- Submodules
- ogstools.msh2vtu package
- ogstools.ogs6py package
ProjectProject.__init__()Project.dependencies()Project.add_element()Project.add_include()Project.add_block()Project.deactivate_property()Project.deactivate_parameter()Project.remove_element()Project.replace_text()Project.replace_block_by_include()Project.replace_mesh()Project.replace_parameter()Project.replace_parameter_value()Project.replace_phase_property_value()Project.replace_medium_property_value()Project.set()Project.restart()Project.run_model()Project.statusProject.terminate_run()Project.write_input()Project.property_dataframe()Project.write_property_latextable()Project.set_media()Project.gml_filepath()Project.meshpaths()Project.param_value_expression()Project.constraints()Project.constraints_labels()Project.plot_constraints()
- 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
- 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.simulation package
- 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