From 5fccf2c20b9c2e6e757898d8f00f52837ccdb558 Mon Sep 17 00:00:00 2001 From: FZill Date: Fri, 6 Sep 2024 11:54:32 +0200 Subject: [PATCH 1/2] naming conventions, ogs6py API --- .../plot_C_feflowlib_2layers_model.py | 4 +- .../plot_D_feflowlib_CT_simulation.py | 21 ++-- .../plot_E_feflowlib_H_simulation.py | 24 ++-- .../plot_F_feflowlib_HT_simulation.py | 31 +++-- docs/examples/howto_plot/plot_animation.py | 14 +-- .../examples/howto_plot/plot_aspect_ratios.py | 24 ++-- docs/examples/howto_plot/plot_contourf_2d.py | 20 +-- docs/examples/howto_plot/plot_contourf_3d.py | 10 +- .../howto_plot/plot_observation_points.py | 6 +- docs/examples/howto_plot/plot_shared_axes.py | 14 +-- docs/examples/howto_plot/plot_timeslice.py | 4 +- .../howto_plot/plot_with_custom_fig_ax.py | 16 +-- .../howto_postprocessing/plot_aggregate.py | 6 +- .../plot_calculate_diff.py | 10 +- .../plot_convergence_study_nuclear_decay.py | 23 ++-- ...onvergence_study_steady_state_diffusion.py | 17 ++- .../howto_postprocessing/plot_ipdata.py | 19 ++- .../plot_sample_mesh_line.py | 22 ++-- .../howto_postprocessing/plot_variables.py | 20 +-- .../howto_preprocessing/plot_remeshing.py | 10 +- docs/examples/howto_prjfile/plot_creation.py | 83 ++++++------- .../howto_prjfile/plot_manipulation.py | 36 +++--- .../howto_quickstart/plot_solid_mechanics.py | 32 ++--- docs/user-guide/ogs6py.md | 1 + ogstools/__init__.py | 1 + ogstools/examples/ogs6py/example_THM.py | 114 +++++++++--------- ogstools/feflowlib/_cli.py | 10 +- ogstools/feflowlib/templates.py | 104 ++++++++-------- ogstools/feflowlib/tools.py | 28 ++--- ogstools/ogs6py/__init__.py | 4 +- ogstools/ogs6py/{ogs.py => project.py} | 34 +++--- ogstools/ogs6py/properties.py | 6 +- tests/test_feflowlib.py | 38 +++--- tests/test_meshlib.py | 103 ++++++++-------- tests/test_ogs6py.py | 62 +++++----- tests/test_plot.py | 88 +++++++------- tests/test_studies_convergence.py | 8 +- 37 files changed, 528 insertions(+), 539 deletions(-) rename ogstools/ogs6py/{ogs.py => project.py} (98%) diff --git a/docs/examples/howto_conversions/plot_C_feflowlib_2layers_model.py b/docs/examples/howto_conversions/plot_C_feflowlib_2layers_model.py index 2c8ee75c..351cbc6d 100644 --- a/docs/examples/howto_conversions/plot_C_feflowlib_2layers_model.py +++ b/docs/examples/howto_conversions/plot_C_feflowlib_2layers_model.py @@ -11,7 +11,7 @@ # 1. Let us convert only the points and cells at first. import ifm_contrib as ifm -import ogstools as ot +import ogstools as ogs from ogstools.examples import feflow_model_2layers from ogstools.feflowlib import ( convert_geometry_mesh, @@ -36,4 +36,4 @@ pv_mesh.save("2layers_model.vtu") # %% # 4. Use the ogstools plotting functionalities. -fig = ot.plot.contourf(pv_mesh.slice("z"), "P_HEAD") +fig = ogs.plot.contourf(pv_mesh.slice("z"), "P_HEAD") diff --git a/docs/examples/howto_conversions/plot_D_feflowlib_CT_simulation.py b/docs/examples/howto_conversions/plot_D_feflowlib_CT_simulation.py index 84655e3e..eea96efc 100644 --- a/docs/examples/howto_conversions/plot_D_feflowlib_CT_simulation.py +++ b/docs/examples/howto_conversions/plot_D_feflowlib_CT_simulation.py @@ -17,7 +17,7 @@ import matplotlib.pyplot as plt import numpy as np -import ogstools as ot +import ogstools as ogs from ogstools.examples import feflow_model_2D_CT_t_560 from ogstools.feflowlib import ( component_transport, @@ -28,9 +28,8 @@ write_point_boundary_conditions, ) from ogstools.meshlib import Mesh -from ogstools.ogs6py import ogs -ot.plot.setup.show_element_edges = True +ogs.plot.setup.show_element_edges = True # %% # 1. Load a FEFLOW model (.fem) as a FEFLOW document, convert and save it. More details on # how the conversion function works can be found here: :py:mod:`ogstools.feflowlib.convert_properties_mesh`. @@ -41,7 +40,7 @@ feflow_mesh_file = temp_dir / "2D_CT_model.vtu" feflow_pv_mesh.save(feflow_mesh_file) -feflow_concentration = ot.variables.Scalar( +feflow_concentration = ogs.variables.Scalar( data_name="single_species_P_CONC", output_name="concentration", data_unit="mg/l", @@ -49,7 +48,7 @@ ) # The original mesh is clipped to focus on the relevant part of it, where concentration is larger # than 1e-9 mg/l. The rest of the mesh has concentration values of 0. -ot.plot.contourf( +ogs.plot.contourf( feflow_pv_mesh.clip_scalar( scalars="single_species_P_CONC", invert=False, value=1.0e-9 ), @@ -62,12 +61,12 @@ # %% # 3. Setup a prj-file (see: :py:mod:`ogstools.feflowlib.setup_prj_file`) to run a OGS-simulation. path_prjfile = feflow_mesh_file.with_suffix(".prj") -prjfile = ogs.OGS(PROJECT_FILE=path_prjfile) +prj = ogs.Project(output_file=path_prjfile) species = get_species(feflow_pv_mesh) CT_model = component_transport( saving_path=temp_dir / "sim_2D_CT_model", species=species, - model=prjfile, + prj=prj, dimension=2, fixed_out_times=[48384000], initial_time=0, @@ -96,7 +95,7 @@ model.run_model(logfile=temp_dir / "out.log") # %% # 5. Read the results along a line on the upper edge of the mesh parallel to the x-axis and plot them. -ms = ot.MeshSeries(temp_dir / "sim_2D_CT_model.pvd") +ms = ogs.MeshSeries(temp_dir / "sim_2D_CT_model.pvd") # Read the last timestep: ogs_sim_res = ms.mesh(ms.timesteps[-1]) """ @@ -109,7 +108,7 @@ fig, ax = plt.subplots(1, 1, figsize=(7, 5)) ogs_sim_res.plot_linesample( "dist", - ot.variables.Scalar( + ogs.variables.Scalar( data_name="single_species", output_name="concentration", data_unit="mg/l", @@ -145,7 +144,7 @@ ogs_sim_res["concentration_difference"] = ( feflow_pv_mesh["single_species_P_CONC"] - ogs_sim_res["single_species"] ) -concentration_difference = ot.variables.Scalar( +concentration_difference = ogs.variables.Scalar( data_name="concentration_difference", output_name="concentration", data_unit="mg/l", @@ -154,7 +153,7 @@ bounds = [0.038, 0.045, 0, 0.01, 0, 0] -ot.plot.contourf( +ogs.plot.contourf( ogs_sim_res.clip_box(bounds, invert=False), concentration_difference, ) diff --git a/docs/examples/howto_conversions/plot_E_feflowlib_H_simulation.py b/docs/examples/howto_conversions/plot_E_feflowlib_H_simulation.py index 17c2b577..16fb39ae 100644 --- a/docs/examples/howto_conversions/plot_E_feflowlib_H_simulation.py +++ b/docs/examples/howto_conversions/plot_E_feflowlib_H_simulation.py @@ -18,7 +18,7 @@ import numpy as np import pyvista as pv -import ogstools as ot +import ogstools as ogs from ogstools.examples import feflow_model_box_Neumann from ogstools.feflowlib import ( convert_properties_mesh, @@ -30,7 +30,6 @@ extract_point_boundary_conditions, get_material_properties, ) -from ogstools.ogs6py import ogs # %% # 1. Load a FEFLOW model (.fem) as a FEFLOW document, convert and save it. More details on @@ -70,12 +69,9 @@ # %% # 3. Setup a prj-file (see: :py:mod:`ogstools.feflowlib.setup_prj_file`) to run a OGS-simulation. path_prjfile = feflow_mesh_file.with_suffix(".prj") -prjfile = ogs.OGS(PROJECT_FILE=path_prjfile) +prj = ogs.Project(output_file=path_prjfile) # Get the template prj-file configurations for a steady state diffusion process -ssd_model = steady_state_diffusion( - temp_dir / "sim_boxNeumann", - prjfile, -) +ssd_model = steady_state_diffusion(temp_dir / "sim_boxNeumann", prj) # Include the mesh specific configurations to the template. model = setup_prj_file( bulk_mesh_path=feflow_mesh_file, @@ -94,7 +90,7 @@ model.run_model(logfile=temp_dir / "out.log") # %% # 5. Read the results and plot them. -ms = ot.MeshSeries(temp_dir / "sim_boxNeumann.pvd") +ms = ogs.MeshSeries(temp_dir / "sim_boxNeumann.pvd") # Read the last timestep: ogs_sim_res = ms.mesh(ms.timesteps[-1]) """ @@ -110,8 +106,10 @@ ) # %% # 5.1 Plot the hydraulic head simulated in OGS with :py:mod:`ogstools.plot.contourf`. -head = ot.variables.Scalar(data_name="HEAD_OGS", data_unit="m", output_unit="m") -fig = ot.plot.contourf(ogs_sim_res.slice(normal="z", origin=[50, 50, 0]), head) +head = ogs.variables.Scalar( + data_name="HEAD_OGS", data_unit="m", output_unit="m" +) +fig = ogs.plot.contourf(ogs_sim_res.slice(normal="z", origin=[50, 50, 0]), head) # %% @@ -128,17 +126,17 @@ # %% # 6.1 Plot the differences in the hydraulic head with :py:mod:`ogstools.plot.contourf`. # Slices are taken along the z-axis. -diff_head = ot.variables.Scalar( +diff_head = ogs.variables.Scalar( data_name="diff_HEAD", data_unit="m", output_unit="m" ) slices = np.reshape(list(pyvista_mesh.slice_along_axis(n=4, axis="z")), (2, 2)) -fig = ot.plot.contourf(slices, diff_head) +fig = ogs.plot.contourf(slices, diff_head) for ax, slice in zip(fig.axes, np.ravel(slices), strict=False): ax.set_title(f"z = {slice.center[2]:.1f} {ms.spatial_output_unit}") # %% # Slices are taken along the y-axis. slices = np.reshape(list(pyvista_mesh.slice_along_axis(n=4, axis="y")), (2, 2)) -fig = ot.plot.contourf(slices, diff_head) +fig = ogs.plot.contourf(slices, diff_head) for ax, slice in zip(fig.axes, np.ravel(slices), strict=False): ax.set_title(f"y = {slice.center[1]:.1f} {ms.spatial_output_unit}") diff --git a/docs/examples/howto_conversions/plot_F_feflowlib_HT_simulation.py b/docs/examples/howto_conversions/plot_F_feflowlib_HT_simulation.py index 2bb60bd8..56e35fee 100644 --- a/docs/examples/howto_conversions/plot_F_feflowlib_HT_simulation.py +++ b/docs/examples/howto_conversions/plot_F_feflowlib_HT_simulation.py @@ -16,7 +16,7 @@ import ifm_contrib as ifm import pyvista as pv -import ogstools as ot +import ogstools as ogs from ogstools.examples import feflow_model_2D_HT_model from ogstools.feflowlib import ( convert_properties_mesh, @@ -27,15 +27,14 @@ extract_point_boundary_conditions, get_material_properties_of_HT_model, ) -from ogstools.ogs6py import ogs # %% # 1. Load a FEFLOW model (.fem) as a FEFLOW document, convert and save it. More details on # how the conversion function works can be found here: :py:mod:`ogstools.feflowlib.convert_properties_mesh`. feflow_model = ifm.loadDocument(str(feflow_model_2D_HT_model)) feflow_pv_mesh = convert_properties_mesh(feflow_model) -feflow_temperature = ot.variables.temperature.replace(data_name="P_TEMP") -ot.plot.contourf(feflow_pv_mesh, feflow_temperature) +feflow_temperature = ogs.variables.temperature.replace(data_name="P_TEMP") +ogs.plot.contourf(feflow_pv_mesh, feflow_temperature) temp_dir = Path(tempfile.mkdtemp("feflow_test_simulation")) feflow_mesh_file = temp_dir / "2D_HT_model.vtu" @@ -55,9 +54,9 @@ # %% # 3. Setup a prj-file (see: :py:mod:`ogstools.feflowlib.setup_prj_file`) to run a OGS-simulation. path_prjfile = feflow_mesh_file.with_suffix(".prj") -prjfile = ogs.OGS(PROJECT_FILE=path_prjfile) +prj = ogs.Project(output_file=path_prjfile) # Get the template prj-file configurations for a hydro thermal process. -HT_model = hydro_thermal(temp_dir / "sim_2D_HT_model", prjfile, dimension=2) +HT_model = hydro_thermal(temp_dir / "sim_2D_HT_model", prj, dimension=2) # Include the mesh specific configurations to the template. model = setup_prj_file( bulk_mesh_path=feflow_mesh_file, @@ -76,7 +75,7 @@ model.run_model(logfile=temp_dir / "out.log") # %% # 5. Read the results and plot them. -ms = ot.MeshSeries(temp_dir / "sim_2D_HT_model.pvd") +ms = ogs.MeshSeries(temp_dir / "sim_2D_HT_model.pvd") # Read the last timestep: ogs_sim_res = ms.mesh(ms.timesteps[-1]) """ @@ -86,28 +85,28 @@ ) """ # Plot the hydraulic head/height, which was simulated in OGS. -hydraulic_head = ot.variables.Scalar( +hydraulic_head = ogs.variables.Scalar( data_name="HEAD_OGS", data_unit="m", output_unit="m" ) -ot.plot.contourf(ogs_sim_res, hydraulic_head) +ogs.plot.contourf(ogs_sim_res, hydraulic_head) # %% # Plot the temperature, which was simulated in OGS. -ot.plot.contourf(ogs_sim_res, ot.variables.temperature) +ogs.plot.contourf(ogs_sim_res, ogs.variables.temperature) # %% # 6. Plot the difference between the FEFLOW and OGS simulation. feflow_pv_mesh["HEAD"] = feflow_pv_mesh["P_HEAD"] ogs_sim_res["HEAD"] = ogs_sim_res["HEAD_OGS"] # Plot differences in hydraulic head/height. -diff_mesh = ot.meshlib.difference(feflow_pv_mesh, ogs_sim_res, "HEAD") -hydraulic_head_diff = ot.variables.Scalar( +diff_mesh = ogs.meshlib.difference(feflow_pv_mesh, ogs_sim_res, "HEAD") +hydraulic_head_diff = ogs.variables.Scalar( data_name="HEAD_difference", data_unit="m", output_unit="m" ) -ot.plot.contourf(diff_mesh, hydraulic_head_diff) +ogs.plot.contourf(diff_mesh, hydraulic_head_diff) # %% feflow_pv_mesh["temperature"] = feflow_pv_mesh["P_TEMP"] # Plot differences in temperature. -diff_mesh = ot.meshlib.difference( - feflow_pv_mesh, ogs_sim_res, ot.variables.temperature +diff_mesh = ogs.meshlib.difference( + feflow_pv_mesh, ogs_sim_res, ogs.variables.temperature ) -ot.plot.contourf(diff_mesh, ot.variables.temperature.difference) +ogs.plot.contourf(diff_mesh, ogs.variables.temperature.difference) diff --git a/docs/examples/howto_plot/plot_animation.py b/docs/examples/howto_plot/plot_animation.py index 127902e2..54f7f71e 100644 --- a/docs/examples/howto_plot/plot_animation.py +++ b/docs/examples/howto_plot/plot_animation.py @@ -13,7 +13,7 @@ import matplotlib.pyplot as plt import numpy as np -import ogstools as ot +import ogstools as ogs from ogstools import examples mesh_series = examples.load_meshseries_CT_2D_XDMF() @@ -34,9 +34,9 @@ # Let's use fixed scale limits to prevent rescaling during the animation. # %% -ot.plot.setup.vmin = 0 -ot.plot.setup.vmax = 100 -ot.plot.setup.dpi = 50 +ogs.plot.setup.vmin = 0 +ogs.plot.setup.vmax = 100 +ogs.plot.setup.dpi = 50 # %% [markdown] # You can choose which timesteps to render by passing either an int array @@ -58,7 +58,7 @@ # `plot_func` which can apply custom formatting and / or plotting. -def mesh_func(mesh: ot.Mesh) -> ot.Mesh: +def mesh_func(mesh: ogs.Mesh) -> ogs.Mesh: "Clip the left half of the mesh." return mesh.clip("-x", [0, 0, 0]) @@ -70,7 +70,7 @@ def plot_func(ax: plt.Axes, timevalue: float) -> None: # %% anim = mesh_series.animate( - ot.variables.saturation, + ogs.variables.saturation, timevalues, mesh_func=mesh_func, plot_func=plot_func, @@ -81,7 +81,7 @@ def plot_func(ax: plt.Axes, timevalue: float) -> None: # # .. code-block:: python # -# ot.plot.utils.save_animation(anim, "Saturation", fps=5) +# ogs.plot.utils.save_animation(anim, "Saturation", fps=5) # # sphinx_gallery_start_ignore diff --git a/docs/examples/howto_plot/plot_aspect_ratios.py b/docs/examples/howto_plot/plot_aspect_ratios.py index 319ed1cf..638d66fe 100644 --- a/docs/examples/howto_plot/plot_aspect_ratios.py +++ b/docs/examples/howto_plot/plot_aspect_ratios.py @@ -15,10 +15,10 @@ import numpy as np import pyvista as pv -import ogstools as ot +import ogstools as ogs -print(f"{ot.plot.setup.min_ax_aspect=}") -print(f"{ot.plot.setup.max_ax_aspect=}") +print(f"{ogs.plot.setup.min_ax_aspect=}") +print(f"{ogs.plot.setup.max_ax_aspect=}") # sphinx_gallery_start_ignore @@ -44,19 +44,19 @@ def custom_mesh(dx: float, dy: float): # proportions. # %% -fig = ot.plot.contourf(custom_mesh(np.pi * 2, np.pi), "example") +fig = ogs.plot.contourf(custom_mesh(np.pi * 2, np.pi), "example") # %% [markdown] # This one would be too wide and thus and gets compressed to fit the maximum # aspect ratio. # %% -fig = ot.plot.contourf(custom_mesh(np.pi * 4, np.pi), "example") +fig = ogs.plot.contourf(custom_mesh(np.pi * 4, np.pi), "example") # %% [markdown] # When plotting multiple meshes together, this applies to each subplot. # So here each subplot has true proportions again since each one fits the limits. # %% -fig = ot.plot.contourf( +fig = ogs.plot.contourf( [custom_mesh(np.pi * 2, np.pi), custom_mesh(np.pi * 2, np.pi)], "example" ) # %% [markdown] @@ -64,12 +64,12 @@ def custom_mesh(dx: float, dy: float): # ratio. # %% -fig = ot.plot.contourf(custom_mesh(np.pi, np.pi * 3), "example") +fig = ogs.plot.contourf(custom_mesh(np.pi, np.pi * 3), "example") # %% [markdown] # The same is true here: # %% -fig = ot.plot.contourf( +fig = ogs.plot.contourf( [custom_mesh(np.pi, np.pi * 3), custom_mesh(np.pi, np.pi * 3)], "example" ) @@ -79,12 +79,12 @@ def custom_mesh(dx: float, dy: float): # very wide figure. # %% -ot.plot.setup.min_ax_aspect = None -ot.plot.setup.max_ax_aspect = None -fig = ot.plot.contourf(custom_mesh(np.pi * 3, np.pi), "example") +ogs.plot.setup.min_ax_aspect = None +ogs.plot.setup.max_ax_aspect = None +fig = ogs.plot.contourf(custom_mesh(np.pi * 3, np.pi), "example") # %% [markdown] # And in this case we get a very tall figure. # %% -fig = ot.plot.contourf(custom_mesh(np.pi, np.pi * 3), "example") +fig = ogs.plot.contourf(custom_mesh(np.pi, np.pi * 3), "example") diff --git a/docs/examples/howto_plot/plot_contourf_2d.py b/docs/examples/howto_plot/plot_contourf_2d.py index a990e866..3549ccce 100644 --- a/docs/examples/howto_plot/plot_contourf_2d.py +++ b/docs/examples/howto_plot/plot_contourf_2d.py @@ -13,10 +13,10 @@ """ # %% -import ogstools as ot +import ogstools as ogs from ogstools import examples -ot.plot.setup.material_names = {i + 1: f"Layer {i+1}" for i in range(26)} +ogs.plot.setup.material_names = {i + 1: f"Layer {i+1}" for i in range(26)} mesh = examples.load_meshseries_THM_2D_PVD().mesh(1) # %% [markdown] @@ -24,12 +24,12 @@ # # .. code-block:: python # -# mesh_series = ot.MeshSeries("filepath/filename_pvd_or_xdmf") +# mesh_series = ogs.MeshSeries("filepath/filename_pvd_or_xdmf") # # %% First, let's plot the material ids (cell_data). Per default in # the setup, this will automatically show the element edges. -fig = mesh.plot_contourf(ot.variables.material_id) +fig = mesh.plot_contourf(ogs.variables.material_id) # %% [markdown] # Now, let's plot the temperature field (point_data) at the first timestep. @@ -37,35 +37,35 @@ # data as Kelvin and converts them to degrees Celsius. # %% -fig = mesh.plot_contourf(ot.variables.temperature, show_max=True) +fig = mesh.plot_contourf(ogs.variables.temperature, show_max=True) # %% [markdown] # We can also plot components of vector variables: # %% fig = mesh.plot_contourf( - ot.variables.displacement[0], show_min=True, show_max=True + ogs.variables.displacement[0], show_min=True, show_max=True ) # %% fig = mesh.plot_contourf( - ot.variables.displacement[1], show_max=True, show_edges=True + ogs.variables.displacement[1], show_max=True, show_edges=True ) # %% [markdown] # This example has hydraulically deactivated subdomains: # %% -fig = mesh.plot_contourf(ot.variables.pressure.get_mask(), fontsize=40) +fig = mesh.plot_contourf(ogs.variables.pressure.get_mask(), fontsize=40) # %% [markdown] # Let's plot the fluid velocity field. # %% -fig = mesh.plot_contourf(ot.variables.velocity, show_region_bounds=False) +fig = mesh.plot_contourf(ogs.variables.velocity, show_region_bounds=False) # %% [markdown] # Let's plot it again, this time log-scaled. # %% -fig = mesh.plot_contourf(ot.variables.velocity, log_scaled=True, vmin=-8) +fig = mesh.plot_contourf(ogs.variables.velocity, log_scaled=True, vmin=-8) diff --git a/docs/examples/howto_plot/plot_contourf_3d.py b/docs/examples/howto_plot/plot_contourf_3d.py index 6450744f..f21ea7e0 100644 --- a/docs/examples/howto_plot/plot_contourf_3d.py +++ b/docs/examples/howto_plot/plot_contourf_3d.py @@ -16,10 +16,10 @@ import numpy as np from pyvista import examples -import ogstools as ot +import ogstools as ogs mesh = examples.load_channels() -data = ot.variables.Scalar("facies", categoric=True) +data = ogs.variables.Scalar("facies", categoric=True) mesh.plot(cmap="bwr") @@ -27,7 +27,7 @@ # Let's create multiple slices along the z axis and plot them in a 2 by 2 grid. slices = np.reshape(list(mesh.slice_along_axis(n=4, axis="z")), (2, 2)) -fig = ot.plot.contourf(slices, data) +fig = ogs.plot.contourf(slices, data) for ax, slice in zip(fig.axes, np.ravel(slices), strict=False): ax.set_title(f"z = {slice.center[2]:.1f}") @@ -35,7 +35,7 @@ # We can also slice along the y-axis and plot the meshes in one row. slices = np.reshape(mesh.slice_along_axis(n=3, axis="y"), (1, -1)) -fig = ot.plot.contourf(slices, data) +fig = ogs.plot.contourf(slices, data) for ax, slice in zip(fig.axes, np.ravel(slices), strict=False): ax.set_title(f"y = {slice.center[1]:.1f}") @@ -43,4 +43,4 @@ # Arbitrary oriented slices are also possible. They get projected to the # cardinal plane, from which they have the least rotational offset. -fig = ot.plot.contourf(mesh.slice([1, -2, 0]), data) +fig = ogs.plot.contourf(mesh.slice([1, -2, 0]), data) diff --git a/docs/examples/howto_plot/plot_observation_points.py b/docs/examples/howto_plot/plot_observation_points.py index 94b326e0..213d9555 100644 --- a/docs/examples/howto_plot/plot_observation_points.py +++ b/docs/examples/howto_plot/plot_observation_points.py @@ -24,11 +24,11 @@ import matplotlib.pyplot as plt import numpy as np -import ogstools as ot +import ogstools as ogs from ogstools import examples mesh_series = examples.load_meshseries_CT_2D_XDMF() -si = ot.variables.saturation +si = ogs.variables.saturation # %% [markdown] # To read your own data as a mesh series you can do: @@ -60,7 +60,7 @@ # And now probe the points and the values over time: # %%, -labels = [f"{i}: {label}" for i, label in enumerate(ot.plot.utils.justified_labels(points))] +labels = [f"{i}: {label}" for i, label in enumerate(ogs.plot.utils.justified_labels(points))] fig = mesh_series.plot_probe( points=points[:4], variable=si, time_unit="a", labels=labels[:4] ) diff --git a/docs/examples/howto_plot/plot_shared_axes.py b/docs/examples/howto_plot/plot_shared_axes.py index 9832cf34..8789bfb8 100644 --- a/docs/examples/howto_plot/plot_shared_axes.py +++ b/docs/examples/howto_plot/plot_shared_axes.py @@ -12,20 +12,20 @@ # Import packages, load example data set and define often used variables. import matplotlib.pyplot as plt -import ogstools as ot +import ogstools as ogs from ogstools import examples meshseries = examples.load_meshseries_THM_2D_PVD() mesh_0 = meshseries.mesh(0) mesh_1 = meshseries.mesh(1) -variable = ot.variables.temperature +variable = ogs.variables.temperature # %% # If you pass multiple meshes to :py:func:`ogstools.plot.contourf` # by default both x and y axes will shared. Thus, only the outer axes get # axes labels and tick label. -fig = ot.plot.contourf([mesh_0, mesh_1], variable) +fig = ogs.plot.contourf([mesh_0, mesh_1], variable) # %% # On user defined figure and axis the axis belonging to specific subplot has to @@ -34,10 +34,10 @@ fig, axs = plt.subplots(2, 2, figsize=(40, 17), sharex=True, sharey=True) diff_a = mesh_0.difference(mesh_1, variable) diff_b = mesh_1.difference(mesh_0, variable) -ot.plot.contourf(mesh_0, variable, fig=fig, ax=axs[0][0]) -ot.plot.contourf(mesh_1, variable, fig=fig, ax=axs[1][0]) -ot.plot.contourf(diff_a, variable, fig=fig, ax=axs[0][1]) -ot.plot.contourf(diff_b, variable, fig=fig, ax=axs[1][1]) +ogs.plot.contourf(mesh_0, variable, fig=fig, ax=axs[0][0]) +ogs.plot.contourf(mesh_1, variable, fig=fig, ax=axs[1][0]) +ogs.plot.contourf(diff_a, variable, fig=fig, ax=axs[0][1]) +ogs.plot.contourf(diff_b, variable, fig=fig, ax=axs[1][1]) fig.tight_layout() plt.show() diff --git a/docs/examples/howto_plot/plot_timeslice.py b/docs/examples/howto_plot/plot_timeslice.py index 33f3c211..72ea6c48 100644 --- a/docs/examples/howto_plot/plot_timeslice.py +++ b/docs/examples/howto_plot/plot_timeslice.py @@ -18,11 +18,11 @@ # vertical, horizontal and diagonal. import numpy as np -import ogstools as ot +import ogstools as ogs from ogstools import examples mesh_series = examples.load_meshseries_CT_2D_XDMF() -si = ot.variables.saturation +si = ogs.variables.saturation points_vert = np.linspace([25, 0, -75], [25, 0, 75], num=100) points_hori = np.linspace([0, 0, 60], [150, 0, 60], num=100) points_diag = np.linspace([25, 0, 75], [100, 0, 0], num=100) diff --git a/docs/examples/howto_plot/plot_with_custom_fig_ax.py b/docs/examples/howto_plot/plot_with_custom_fig_ax.py index 15706060..3230a068 100644 --- a/docs/examples/howto_plot/plot_with_custom_fig_ax.py +++ b/docs/examples/howto_plot/plot_with_custom_fig_ax.py @@ -12,12 +12,12 @@ # %% import matplotlib.pyplot as plt -import ogstools as ot +import ogstools as ogs from ogstools import examples meshseries = examples.load_meshseries_THM_2D_PVD() -ot.plot.setup.combined_colorbar = False +ogs.plot.setup.combined_colorbar = False # %% [markdown] # Compare different variables @@ -28,8 +28,8 @@ # same figure: fig, ax = plt.subplots(2, 1, figsize=(15, 15)) -meshseries.mesh(0).plot_contourf(ot.variables.temperature, fig=fig, ax=ax[0]) -meshseries.mesh(1).plot_contourf(ot.variables.displacement, fig=fig, ax=ax[1]) +meshseries.mesh(0).plot_contourf(ogs.variables.temperature, fig=fig, ax=ax[0]) +meshseries.mesh(1).plot_contourf(ogs.variables.displacement, fig=fig, ax=ax[1]) fig.tight_layout() # %% [markdown] @@ -43,14 +43,14 @@ fig, ax = plt.subplots(3, 1, figsize=(20, 30)) -meshseries.mesh(0).plot_contourf(ot.variables.temperature, fig=fig, ax=ax[0]) -meshseries.mesh(1).plot_contourf(ot.variables.temperature, fig=fig, ax=ax[1]) +meshseries.mesh(0).plot_contourf(ogs.variables.temperature, fig=fig, ax=ax[0]) +meshseries.mesh(1).plot_contourf(ogs.variables.temperature, fig=fig, ax=ax[1]) diff_mesh = meshseries.mesh(1).difference( - meshseries.mesh(0), ot.variables.temperature + meshseries.mesh(0), ogs.variables.temperature ) -diff_mesh.plot_contourf(ot.variables.temperature, fig=fig, ax=ax[2]) +diff_mesh.plot_contourf(ogs.variables.temperature, fig=fig, ax=ax[2]) ax[0].set_title(r"$T(\mathrm{t}_{0})$") ax[1].set_title(r"$T(\mathrm{t}_{end})$") ax[2].set_title(r"$T(\mathrm{t}_{end})$-$T(\mathrm{t}_{0})$") diff --git a/docs/examples/howto_postprocessing/plot_aggregate.py b/docs/examples/howto_postprocessing/plot_aggregate.py index 1094f11e..393c4266 100644 --- a/docs/examples/howto_postprocessing/plot_aggregate.py +++ b/docs/examples/howto_postprocessing/plot_aggregate.py @@ -14,11 +14,11 @@ """ # %% -import ogstools as ot +import ogstools as ogs from ogstools import examples mesh_series = examples.load_meshseries_CT_2D_XDMF() -saturation = ot.variables.saturation +saturation = ogs.variables.saturation # %% [markdown] # To read your own data as a mesh series you can do: @@ -52,7 +52,7 @@ # %% mesh = mesh_series.time_of_max(saturation) -fig = mesh.plot_contourf(ot.variables.Scalar("max_Saturation_time", "s", "a")) +fig = mesh.plot_contourf(ogs.variables.Scalar("max_Saturation_time", "s", "a")) # %% [markdown] # Likewise we can calculate and visualize the variance of the saturation: diff --git a/docs/examples/howto_postprocessing/plot_calculate_diff.py b/docs/examples/howto_postprocessing/plot_calculate_diff.py index 7cb725e2..fd562f28 100644 --- a/docs/examples/howto_postprocessing/plot_calculate_diff.py +++ b/docs/examples/howto_postprocessing/plot_calculate_diff.py @@ -16,10 +16,10 @@ # sphinx_gallery_end_ignore -import ogstools as ot +import ogstools as ogs from ogstools import examples -variable = ot.variables.temperature +variable = ogs.variables.temperature # %% # Introduction @@ -88,7 +88,7 @@ meshes_1 = [mesh1] * 3 meshes_2 = [mesh2] * 3 -mesh_diff_pair_wise = ot.meshlib.difference_pairwise( +mesh_diff_pair_wise = ogs.meshlib.difference_pairwise( meshes_1, meshes_2, variable ) @@ -124,7 +124,7 @@ mesh_list = [mesh1, mesh2, mesh1, mesh2] -mesh_diff_matrix = ot.meshlib.difference_matrix(mesh_list, variable=variable) +mesh_diff_matrix = ogs.meshlib.difference_matrix(mesh_list, variable=variable) # %% print(f"Length of mesh_list1: {len(mesh_list)}") @@ -161,7 +161,7 @@ mesh_list_matrix_1 = [mesh1, mesh2, mesh1] mesh_list_matrix_2 = [mesh2, mesh1] -mesh_diff_matrix = ot.meshlib.difference_matrix( +mesh_diff_matrix = ogs.meshlib.difference_matrix( mesh_list_matrix_1, mesh_list_matrix_2, variable ) diff --git a/docs/examples/howto_postprocessing/plot_convergence_study_nuclear_decay.py b/docs/examples/howto_postprocessing/plot_convergence_study_nuclear_decay.py index 9f31a8ad..3f92ca21 100644 --- a/docs/examples/howto_postprocessing/plot_convergence_study_nuclear_decay.py +++ b/docs/examples/howto_postprocessing/plot_convergence_study_nuclear_decay.py @@ -37,9 +37,8 @@ from IPython.display import HTML from scipy.constants import Julian_year as sec_per_yr -import ogstools as ot +import ogstools as ogs from ogstools import examples, meshlib, msh2vtu, physics, studies, workflow -from ogstools.ogs6py import ogs temp_dir = Path(mkdtemp(prefix="nuclear_decay")) @@ -64,14 +63,16 @@ # %% for dt, n_cells in zip(time_step_sizes, edge_cells, strict=False): - ot.meshlib.rect(lengths=100.0, n_edge_cells=[n_cells, 1], out_name=msh_path) + ogs.meshlib.rect( + lengths=100.0, n_edge_cells=[n_cells, 1], out_name=msh_path + ) _ = msh2vtu.msh2vtu(msh_path, output_path=temp_dir, log_level="ERROR") - model = ogs.OGS(PROJECT_FILE=temp_dir / "default.prj", INPUT_FILE=prj_path) - model.replace_text(str(dt * sec_per_yr), ".//delta_t") - model.replace_text(prefix.format(dt), ".//prefix") - model.write_input() - model.run_model(write_logs=False, args=ogs_args) + prj = ogs.Project(output_file=temp_dir / "default.prj", input_file=prj_path) + prj.replace_text(str(dt * sec_per_yr), ".//delta_t") + prj.replace_text(prefix.format(dt), ".//prefix") + prj.write_input() + prj.run_model(write_logs=False, args=ogs_args) sim_results += [temp_dir / (prefix.format(dt) + "_rect_domain.xdmf")] # %% plotting: @@ -86,12 +87,12 @@ ax2.plot(time, heat, lw=2, label="reference", color="k") for sim_result, dt in zip(sim_results, time_step_sizes, strict=False): - mesh_series = ot.MeshSeries(sim_result) + mesh_series = ogs.MeshSeries(sim_result) results = {"heat_flux": [], "temperature": []} for ts in mesh_series.timesteps: mesh = mesh_series.mesh(ts) results["temperature"] += [np.max(mesh.point_data["temperature"])] - max_T = ot.variables.temperature.transform(results["temperature"]) + max_T = ogs.variables.temperature.transform(results["temperature"]) # times 2 due to symmetry, area of repo, to kW results["heat_flux"] += [np.max(mesh.point_data["heat_flux"][:, 0])] tv = np.asarray(mesh_series.timevalues("a")) @@ -160,7 +161,7 @@ # %% mesh_series = [meshlib.MeshSeries(sim_result) for sim_result in sim_results] evolution_metrics = studies.convergence.convergence_metrics_evolution( - mesh_series, ot.variables.temperature, units=["s", "yrs"] + mesh_series, ogs.variables.temperature, units=["s", "yrs"] ) # %% [markdown] diff --git a/docs/examples/howto_postprocessing/plot_convergence_study_steady_state_diffusion.py b/docs/examples/howto_postprocessing/plot_convergence_study_steady_state_diffusion.py index 123202d7..3ee21ea8 100644 --- a/docs/examples/howto_postprocessing/plot_convergence_study_steady_state_diffusion.py +++ b/docs/examples/howto_postprocessing/plot_convergence_study_steady_state_diffusion.py @@ -36,9 +36,8 @@ from IPython.display import HTML -import ogstools as ot +import ogstools as ogs from ogstools import examples, msh2vtu, variables, workflow -from ogstools.ogs6py import ogs from ogstools.studies import convergence temp_dir = Path(mkdtemp(suffix="steady_state_diffusion")) @@ -56,14 +55,14 @@ edge_cells = [2**i for i in range(refinements)] for n_edge_cells in edge_cells: msh_path = temp_dir / "square.msh" - ot.meshlib.gmsh_meshing.rect( + ogs.meshlib.gmsh_meshing.rect( n_edge_cells=n_edge_cells, structured_grid=True, out_name=msh_path ) msh2vtu.msh2vtu(filename=msh_path, output_path=temp_dir, log_level="ERROR") - model = ogs.OGS( - PROJECT_FILE=temp_dir / "default.prj", - INPUT_FILE=examples.prj_steady_state_diffusion, + model = ogs.Project( + output_file=temp_dir / "default.prj", + input_file=examples.prj_steady_state_diffusion, ) prefix = "steady_state_diffusion_" + str(n_edge_cells) model.replace_text(prefix, ".//prefix") @@ -78,10 +77,10 @@ # %% analytical_solution_path = temp_dir / "analytical_solution.vtu" solution = examples.analytical_diffusion( - ot.MeshSeries(result_paths[-1]).mesh(0) + ogs.MeshSeries(result_paths[-1]).mesh(0) ) -ot.plot.setup.show_element_edges = True -fig = ot.plot.contourf(solution, variables.hydraulic_head) +ogs.plot.setup.show_element_edges = True +fig = ogs.plot.contourf(solution, variables.hydraulic_head) solution.save(analytical_solution_path) # %% [markdown] diff --git a/docs/examples/howto_postprocessing/plot_ipdata.py b/docs/examples/howto_postprocessing/plot_ipdata.py index 37e17acb..3b620d94 100644 --- a/docs/examples/howto_postprocessing/plot_ipdata.py +++ b/docs/examples/howto_postprocessing/plot_ipdata.py @@ -20,16 +20,15 @@ from pathlib import Path from tempfile import mkdtemp -import ogstools as ot +import ogstools as ogs from ogstools import examples from ogstools.meshlib.gmsh_meshing import rect from ogstools.msh2vtu import msh2vtu -from ogstools.ogs6py import ogs -ot.plot.setup.dpi = 75 -ot.plot.setup.show_element_edges = True +ogs.plot.setup.dpi = 75 +ogs.plot.setup.show_element_edges = True -sigma_ip = ot.variables.stress.replace( +sigma_ip = ogs.variables.stress.replace( data_name="sigma_ip", output_name="IP_stress" ) @@ -48,18 +47,18 @@ def simulate_and_plot(elem_order: int, quads: bool, intpt_order: int): ) msh2vtu(mesh_path, tmp_dir, log_level="ERROR") - model = ogs.OGS( - PROJECT_FILE=tmp_dir / "default.prj", - INPUT_FILE=examples.prj_mechanics, + model = ogs.Project( + output_file=tmp_dir / "default.prj", + input_file=examples.prj_mechanics, ) model.replace_text(intpt_order, xpath=".//integration_order") model.write_input() model.run_model(write_logs=True, args=f"-m {tmp_dir} -o {tmp_dir}") - mesh = ot.MeshSeries(tmp_dir / "mesh.pvd").mesh(-1) + mesh = ogs.MeshSeries(tmp_dir / "mesh.pvd").mesh(-1) int_pts = mesh.to_ip_point_cloud() ip_mesh = mesh.to_ip_mesh() - fig = mesh.plot_contourf(ot.variables.stress) + fig = mesh.plot_contourf(ogs.variables.stress) fig.axes[0].scatter( int_pts.points[:, 0], int_pts.points[:, 1], color="k", s=10 ) diff --git a/docs/examples/howto_postprocessing/plot_sample_mesh_line.py b/docs/examples/howto_postprocessing/plot_sample_mesh_line.py index 21a59f95..e0864b20 100644 --- a/docs/examples/howto_postprocessing/plot_sample_mesh_line.py +++ b/docs/examples/howto_postprocessing/plot_sample_mesh_line.py @@ -9,7 +9,7 @@ import matplotlib.pyplot as plt import numpy as np -import ogstools as ot +import ogstools as ogs from ogstools import examples # %% [markdown] @@ -24,7 +24,7 @@ profile_HT = np.array([[4, 2, 0], [4, 18, 0]]) # %% -mesh_sp, mesh_kp = ot.meshlib.sample_polyline( +mesh_sp, mesh_kp = ogs.meshlib.sample_polyline( mesh, ["pressure", "temperature"], profile_HT ) @@ -64,9 +64,9 @@ ax=ax_twinx, fontsize=15, ) -ot.plot.utils.color_twin_axes( +ogs.plot.utils.color_twin_axes( [ax, ax_twinx], - [ot.variables.pressure.color, ot.variables.temperature.color], + [ogs.variables.pressure.color, ogs.variables.temperature.color], ) fig.tight_layout() @@ -76,7 +76,7 @@ # We can see it in the following example using the Darcy velocity: # %% -mesh_sp, mesh_kp = ot.meshlib.sample_polyline( +mesh_sp, mesh_kp = ogs.meshlib.sample_polyline( mesh, "darcy_velocity", profile_HT ) @@ -106,8 +106,8 @@ mesh = examples.load_meshseries_CT_2D_XDMF().mesh(11) # %% -mesh_sp, mesh_kp = ot.meshlib.sample_polyline( - mesh, ot.variables.saturation, profile_CT +mesh_sp, mesh_kp = ogs.meshlib.sample_polyline( + mesh, ogs.variables.saturation, profile_CT ) # %% [markdown] @@ -124,7 +124,7 @@ # %% fig, ax = mesh.plot_linesample_contourf( - ot.variables.saturation, profile_CT, resolution=100 + ogs.variables.saturation, profile_CT, resolution=100 ) # %% [markdown] @@ -159,9 +159,9 @@ mesh = examples.load_meshseries_THM_2D_PVD().mesh(-1) # %% -ms_THM_sp, dist_at_knot = ot.meshlib.sample_polyline( +ms_THM_sp, dist_at_knot = ogs.meshlib.sample_polyline( mesh, - [ot.variables.pressure, ot.variables.temperature], + [ogs.variables.pressure, ogs.variables.temperature], profile_THM, resolution=100, ) @@ -202,7 +202,7 @@ # %% # plt.rcdefaults() fig, ax = mesh.plot_linesample_contourf( - [ot.variables.pressure, ot.variables.temperature], + [ogs.variables.pressure, ogs.variables.temperature], profile_THM, resolution=100, ) diff --git a/docs/examples/howto_postprocessing/plot_variables.py b/docs/examples/howto_postprocessing/plot_variables.py index 74d6b1ba..27397b08 100644 --- a/docs/examples/howto_postprocessing/plot_variables.py +++ b/docs/examples/howto_postprocessing/plot_variables.py @@ -10,10 +10,10 @@ """ # %% -import ogstools as ot +import ogstools as ogs from ogstools import examples -ot.variables.get_dataframe() +ogs.variables.get_dataframe() # %% [markdown] # Scalar, Vector and Matrix inherit from the class Variable with its @@ -22,21 +22,21 @@ # applies a function if specified. In this case we convert from K to °C: # %% -ot.variables.temperature.transform(273.15, strip_unit=False) +ogs.variables.temperature.transform(273.15, strip_unit=False) # %% [markdown] # You can also create your own variables by creating a Scalar, Vector or Matrix # variable. The following doesn't do any unit conversion. # %% -custom_temperature = ot.variables.Scalar( +custom_temperature = ogs.variables.Scalar( data_name="temperature", data_unit="K", output_unit="K" ) custom_temperature.transform(273.15, strip_unit=False) # %% [markdown] # Or use existing presets as a template and replace some parameters: -custom_temperature = ot.variables.temperature.replace(output_unit="°F") +custom_temperature = ogs.variables.temperature.replace(output_unit="°F") custom_temperature.transform(273.15, strip_unit=False) # %% [markdown] @@ -47,10 +47,10 @@ # length 4 [xx, yy, zz, xy] or 6 [xx, yy, zz, xy, yz, xz]. # %% -ot.variables.displacement[1].transform([0.01, 0.02, 0.03], strip_unit=False) +ogs.variables.displacement[1].transform([0.01, 0.02, 0.03], strip_unit=False) # %% -ot.variables.strain["xx"].transform( +ogs.variables.strain["xx"].transform( [0.01, 0.02, 0.03, 0.04, 0.05, 0.06], strip_unit=False ) @@ -58,7 +58,7 @@ # Magnitude of a 2D displacement vector: # %% -ot.variables.displacement.magnitude.transform([0.03, 0.04], strip_unit=False) +ogs.variables.displacement.magnitude.transform([0.03, 0.04], strip_unit=False) # %% [markdown] # We suggest specifying the variables and their transformations once. @@ -67,8 +67,8 @@ # task of processing the data (e.g. calculate the von Mises stress): # %% -fig = ot.plot.contourf( - examples.load_mesh_mechanics_2D(), ot.variables.stress.von_Mises +fig = ogs.plot.contourf( + examples.load_mesh_mechanics_2D(), ogs.variables.stress.von_Mises ) # %% [markdown] diff --git a/docs/examples/howto_preprocessing/plot_remeshing.py b/docs/examples/howto_preprocessing/plot_remeshing.py index 59e3fe4a..5611573c 100644 --- a/docs/examples/howto_preprocessing/plot_remeshing.py +++ b/docs/examples/howto_preprocessing/plot_remeshing.py @@ -21,7 +21,7 @@ from pathlib import Path from tempfile import mkdtemp -import ogstools as ot +import ogstools as ogs from ogstools import examples from ogstools.msh2vtu import msh2vtu @@ -29,7 +29,7 @@ # %% This is our example mesh which we want to discretize with triangle # elements. -fig = mesh.plot_contourf(ot.variables.material_id) +fig = mesh.plot_contourf(ogs.variables.material_id) # %% [markdown] # Here, we do the remeshing and use msh2vtu to convert the resulting msh file to @@ -39,7 +39,7 @@ mesh = examples.load_meshseries_THM_2D_PVD().mesh(1) temp_dir = Path(mkdtemp()) msh_path = temp_dir / "tri_mesh.msh" -ot.meshlib.gmsh_meshing.remesh_with_triangle(mesh, msh_path) +ogs.meshlib.gmsh_meshing.remesh_with_triangle(mesh, msh_path) msh2vtu(msh_path, temp_dir, reindex=False, log_level="ERROR") -mesh = ot.Mesh(temp_dir / "tri_mesh_domain.vtu") -fig = mesh.plot_contourf(ot.variables.material_id) +mesh = ogs.Mesh(temp_dir / "tri_mesh_domain.vtu") +fig = mesh.plot_contourf(ogs.variables.material_id) diff --git a/docs/examples/howto_prjfile/plot_creation.py b/docs/examples/howto_prjfile/plot_creation.py index f49295a5..3fc0c0f9 100644 --- a/docs/examples/howto_prjfile/plot_creation.py +++ b/docs/examples/howto_prjfile/plot_creation.py @@ -11,39 +11,40 @@ """ # %% -# 1. Initialize the ogs6py object: +# Initialize the ogs6py object: +import tempfile +from pathlib import Path -from ogstools.definitions import EXAMPLES_DIR -from ogstools.ogs6py import ogs +import ogstools as ogs -model = ogs.OGS(PROJECT_FILE=EXAMPLES_DIR / "prj/simple_mechanics.prj") +prj = ogs.Project( + output_file=Path(tempfile.mkdtemp) / "prj/simple_mechanics.prj" +) # %% -# 2. Define geometry and/or meshes: -model.geometry.add_geometry(filename="square_1x1.gml") -model.mesh.add_mesh(filename="square_1x1_quad_1e2.vtu") +# Define geometry and/or meshes: +prj.geometry.add_geometry(filename="square_1x1.gml") +prj.mesh.add_mesh(filename="square_1x1_quad_1e2.vtu") # %% -# 3. Set process and provide process related data: -model.processes.set_process( +# Set process and provide process related data: +prj.processes.set_process( name="SD", type="SMALL_DEFORMATION", integration_order="2", specific_body_force="0 0", ) -model.processes.set_constitutive_relation( +prj.processes.set_constitutive_relation( type="LinearElasticIsotropic", youngs_modulus="E", poissons_ratio="nu" ) -model.processes.add_process_variable( +prj.processes.add_process_variable( process_variable="process_variable", process_variable_name="displacement" ) -model.processes.add_secondary_variable( - internal_name="sigma", output_name="sigma" -) +prj.processes.add_secondary_variable(internal_name="sigma", output_name="sigma") # %% -# 4. Define time stepping and output cycles: -model.time_loop.add_process( +# Define time stepping and output cycles: +prj.time_loop.add_process( process="SD", nonlinear_solver_name="basic_newton", convergence_type="DeltaX", @@ -51,7 +52,7 @@ abstol="1e-15", time_discretization="BackwardEuler", ) -model.time_loop.set_stepping( +prj.time_loop.set_stepping( process="SD", type="FixedTimeStepping", t_initial="0", @@ -59,7 +60,7 @@ repeat="4", delta_t="0.25", ) -model.time_loop.add_output( +prj.time_loop.add_output( type="VTK", prefix="blubb", repeat="1", @@ -67,7 +68,7 @@ variables=["displacement", "sigma"], ) -model.media.add_property( +prj.media.add_property( medium_id="0", phase_type="Solid", name="density", @@ -76,25 +77,25 @@ ) # %% -# 5. Define parameters needed for material properties and BC: -model.parameters.add_parameter(name="E", type="Constant", value="1") -model.parameters.add_parameter(name="nu", type="Constant", value="0.3") -model.parameters.add_parameter(name="rho_sr", type="Constant", value="1") -model.parameters.add_parameter( +# Define parameters needed for material properties and BC: +prj.parameters.add_parameter(name="E", type="Constant", value="1") +prj.parameters.add_parameter(name="nu", type="Constant", value="0.3") +prj.parameters.add_parameter(name="rho_sr", type="Constant", value="1") +prj.parameters.add_parameter( name="displacement0", type="Constant", values="0 0" ) -model.parameters.add_parameter(name="dirichlet0", type="Constant", value="0") -model.parameters.add_parameter(name="dirichlet1", type="Constant", value="0.05") +prj.parameters.add_parameter(name="dirichlet0", type="Constant", value="0") +prj.parameters.add_parameter(name="dirichlet1", type="Constant", value="0.05") # %% -# 6. Set initial and boundary conditions: -model.process_variables.set_ic( +# Set initial and boundary conditions: +prj.process_variables.set_ic( process_variable_name="displacement", components="2", order="1", initial_condition="displacement0", ) -model.process_variables.add_bc( +prj.process_variables.add_bc( process_variable_name="displacement", geometrical_set="square_1x1_geometry", geometry="left", @@ -102,7 +103,7 @@ component="0", parameter="dirichlet0", ) -model.process_variables.add_bc( +prj.process_variables.add_bc( process_variable_name="displacement", geometrical_set="square_1x1_geometry", geometry="bottom", @@ -110,7 +111,7 @@ component="1", parameter="dirichlet0", ) -model.process_variables.add_bc( +prj.process_variables.add_bc( process_variable_name="displacement", geometrical_set="square_1x1_geometry", geometry="top", @@ -120,14 +121,14 @@ ) # %% -# 7. Set linear and nonlinear solver(s): -model.nonlinear_solvers.add_non_lin_solver( +# Set linear and nonlinear solver(s): +prj.nonlinear_solvers.add_non_lin_solver( name="basic_newton", type="Newton", max_iter="4", linear_solver="general_linear_solver", ) -model.linear_solvers.add_lin_solver( +prj.linear_solvers.add_lin_solver( name="general_linear_solver", kind="lis", solver_type="cg", @@ -135,7 +136,7 @@ max_iteration_step="10000", error_tolerance="1e-16", ) -model.linear_solvers.add_lin_solver( +prj.linear_solvers.add_lin_solver( name="general_linear_solver", kind="eigen", solver_type="CG", @@ -143,7 +144,7 @@ max_iteration_step="10000", error_tolerance="1e-16", ) -model.linear_solvers.add_lin_solver( +prj.linear_solvers.add_lin_solver( name="general_linear_solver", kind="petsc", prefix="sd", @@ -154,13 +155,13 @@ ) # %% -# 7. Write project file to disc: -model.write_input() +# Write project file to disc: +prj.write_input() # %% -# 8. Execute file and pipe output to logfile out.log: -model.run_model(logfile="out.log") +# Execute file and pipe output to logfile out.log: +prj.run_model(logfile="out.log") # %% [markdown] -# 9. If the desired OGS version is not in PATH, a separate path containing the OGS binary can be specified. +# If the desired OGS version is not in PATH, a separate path containing the OGS binary can be specified. # `model.run_model(path="~/github/ogs/build_mkl/bin")` diff --git a/docs/examples/howto_prjfile/plot_manipulation.py b/docs/examples/howto_prjfile/plot_manipulation.py index 073aa5d4..67c1526c 100644 --- a/docs/examples/howto_prjfile/plot_manipulation.py +++ b/docs/examples/howto_prjfile/plot_manipulation.py @@ -9,35 +9,39 @@ """ # %% -# 1. Initialize the ogs6py object: +# Initialize the ogs6py object: +import ogstools as ogs from ogstools.definitions import EXAMPLES_DIR -from ogstools.ogs6py import ogs -Es = [1, 2, 3] +youngs_moduli = [1, 2, 3] filename = EXAMPLES_DIR / "prj/simple_mechanics.prj" -for E in Es: - model = ogs.OGS(INPUT_FILE=filename, PROJECT_FILE=filename) - model.replace_parameter_value(name="E", value=E) - model.replace_text("out_E=" + str(E), xpath="./time_loop/output/prefix") - model.write_input() - model.run_model() +for youngs_modulus in youngs_moduli: + prj = ogs.Project(input_file=filename, output_file=filename) + prj.replace_parameter_value(name="E", value=youngs_modulus) + prj.replace_text( + f"out_E={youngs_modulus}", xpath="./time_loop/output/prefix" + ) + prj.write_input() + prj.run_model() # %% -# 2. Instead of the `replace_parameter` method, the more general `replace_text` method +# Instead of the `replace_parameter` method, the more general `replace_text` method # can also be used to replace the young modulus in this example: -model.replace_text(E, xpath="./parameters/parameter[name='E']/value") +prj.replace_text(youngs_modulus, xpath="./parameters/parameter[name='E']/value") # %% -# 3. The Young's modulus in this file can also be accessed through 0'th occurrence of the place addressed by the xpath -model.replace_text(E, xpath="./parameters/parameter/value", occurrence=0) +# The Young's modulus in this file can also be accessed through 0'th occurrence of the place addressed by the xpath +prj.replace_text( + youngs_modulus, xpath="./parameters/parameter/value", occurrence=0 +) # %% -# 4. The density can also be changed: -model.replace_phase_property_value( +# The density can also be changed: +prj.replace_phase_property_value( mediumid=0, phase="Solid", name="density", value="42" ) # %% [markdown] -# 5. For MPL (Material Property Library) based processes, like TH2M or Thermo-Richards-Mechanics, +# For MPL (Material Property Library) based processes, like TH2M or Thermo-Richards-Mechanics, # there exist specific functions to set phase and medium properties: e.g.:, # `model.replace_medium_property_value(mediumid=0, name="porosity", value="0.24")` diff --git a/docs/examples/howto_quickstart/plot_solid_mechanics.py b/docs/examples/howto_quickstart/plot_solid_mechanics.py index 12d7bad1..920dfa31 100644 --- a/docs/examples/howto_quickstart/plot_solid_mechanics.py +++ b/docs/examples/howto_quickstart/plot_solid_mechanics.py @@ -21,11 +21,11 @@ # sphinx_gallery_end_ignore -import ogstools as ot +import ogstools as ogs from ogstools import examples mesh = examples.load_mesh_mechanics_2D() -fig = mesh.plot_contourf(ot.variables.displacement) +fig = mesh.plot_contourf(ogs.variables.displacement) # %% [markdown] # Tensor components @@ -33,8 +33,8 @@ # We can inspect the stress (or strain) tensor components by indexing. # %% -fig = mesh.plot_contourf(ot.variables.stress["xx"]) -fig = mesh.plot_contourf(ot.variables.stress["xy"]) +fig = mesh.plot_contourf(ogs.variables.stress["xx"]) +fig = mesh.plot_contourf(ogs.variables.stress["xy"]) # %% [markdown] # Principal stresses @@ -45,16 +45,16 @@ # compressive principal stress. # %% -eigvecs = ot.variables.stress.eigenvectors -fig = mesh.plot_contourf(variable=ot.variables.stress.eigenvalues[0]) +eigvecs = ogs.variables.stress.eigenvectors +fig = mesh.plot_contourf(variable=ogs.variables.stress.eigenvalues[0]) mesh.plot_quiver(ax=fig.axes[0], variable=eigvecs[0], glyph_type="line") # %% -fig = mesh.plot_contourf(variable=ot.variables.stress.eigenvalues[1]) +fig = mesh.plot_contourf(variable=ogs.variables.stress.eigenvalues[1]) mesh.plot_quiver(ax=fig.axes[0], variable=eigvecs[1], glyph_type="line") # %% -fig = mesh.plot_contourf(variable=ot.variables.stress.eigenvalues[2]) +fig = mesh.plot_contourf(variable=ogs.variables.stress.eigenvalues[2]) mesh.plot_quiver(ax=fig.axes[0], variable=eigvecs[2], glyph_type="line") # %% [markdown] @@ -63,7 +63,7 @@ # see: :py:func:`ogstools.variables.tensor_math.mean` # %% -fig = mesh.plot_contourf(ot.variables.stress.mean) +fig = mesh.plot_contourf(ogs.variables.stress.mean) # %% [markdown] # Von Mises stress @@ -71,7 +71,7 @@ # see: :py:func:`ogstools.variables.tensor_math.von_mises` # %% -fig = mesh.plot_contourf(ot.variables.stress.von_Mises) +fig = mesh.plot_contourf(ogs.variables.stress.von_Mises) # %% [markdown] # octahedral shear stress @@ -79,7 +79,7 @@ # see: :py:func:`ogstools.variables.tensor_math.octahedral_shear` # %% -fig = mesh.plot_contourf(ot.variables.stress.octahedral_shear) +fig = mesh.plot_contourf(ogs.variables.stress.octahedral_shear) # %% [markdown] # Integrity criteria @@ -96,7 +96,7 @@ # %% mesh["pressure"] = mesh.p_fluid() -fig = mesh.plot_contourf(ot.variables.pressure) +fig = mesh.plot_contourf(ogs.variables.pressure) # %% [markdown] # But since this assumes that the top of the model is equal to the ground @@ -107,7 +107,7 @@ mesh["depth"] = mesh.depth(use_coords=True) fig = mesh.plot_contourf("depth") mesh["pressure"] = mesh.p_fluid() -fig = mesh.plot_contourf(ot.variables.pressure) +fig = mesh.plot_contourf(ogs.variables.pressure) # %% [markdown] # Dilantancy criterion @@ -115,8 +115,8 @@ # see: :py:func:`ogstools.variables.mesh_dependent.dilatancy_critescu` # %% -fig = mesh.plot_contourf(ot.variables.dilatancy_critescu_tot) -fig = mesh.plot_contourf(ot.variables.dilatancy_critescu_eff) +fig = mesh.plot_contourf(ogs.variables.dilatancy_critescu_tot) +fig = mesh.plot_contourf(ogs.variables.dilatancy_critescu_eff) # %% [markdown] # Fluid pressure criterion @@ -124,4 +124,4 @@ # see: :py:func:`ogstools.variables.mesh_dependent.fluid_pressure_criterion` # %% -fig = mesh.plot_contourf(ot.variables.fluid_pressure_crit) +fig = mesh.plot_contourf(ogs.variables.fluid_pressure_crit) diff --git a/docs/user-guide/ogs6py.md b/docs/user-guide/ogs6py.md index 6114f703..104f7a0b 100644 --- a/docs/user-guide/ogs6py.md +++ b/docs/user-guide/ogs6py.md @@ -6,6 +6,7 @@ ogs6py is a Python-API for the OpenGeoSys finite element software. Its main functionalities include creating and altering OGS6 input files, as well as executing OGS. The package allows you to automate OGS-workflows in Python via Jupyter or just plain Python scripts. This enables the user to create parameter plans and to execute them in parallel. +API: [](../reference/ogstools.ogs6py.rst). # Features diff --git a/ogstools/__init__.py b/ogstools/__init__.py index 62838efd..12d57b4a 100644 --- a/ogstools/__init__.py +++ b/ogstools/__init__.py @@ -16,6 +16,7 @@ try: from . import plot, variables from .meshlib import Mesh, MeshSeries # noqa: F401 + from .ogs6py import Project # noqa: F401 except ImportError as e: print(f"Warning: Failed to import the following libraries: {e.name}") diff --git a/ogstools/examples/ogs6py/example_THM.py b/ogstools/examples/ogs6py/example_THM.py index ef0fb719..0295419d 100644 --- a/ogstools/examples/ogs6py/example_THM.py +++ b/ogstools/examples/ogs6py/example_THM.py @@ -1,50 +1,48 @@ -from ogstools.ogs6py import OGS +import ogstools as ogs # if MKL set vars vars script should be executed before OGS -# model = OGS(PROJECT_FILE="thm_test.prj", MKL=True, OMP_NUM_THREADS=4) -model = OGS(PROJECT_FILE="thm_test.prj", OMP_NUM_THREADS=4) -model.geometry.add_geometry(filename="square_1x1_thm.gml") -model.mesh.add_mesh(filename="quarter_002_2nd.vtu", axially_symmetric="true") -model.processes.set_process( +# prj = ogs.Project(output_file="thm_test.prj", MKL=True, OMP_NUM_THREADS=4) +prj = ogs.Project(output_file="thm_test.prj", OMP_NUM_THREADS=4) +prj.geometry.add_geometry(filename="square_1x1_thm.gml") +prj.mesh.add_mesh(filename="quarter_002_2nd.vtu", axially_symmetric="true") +prj.processes.set_process( name="THERMO_HYDRO_MECHANICS", type="THERMO_HYDRO_MECHANICS", integration_order="4", dimension="2", specific_body_force="0 0", ) -model.processes.set_constitutive_relation( +prj.processes.set_constitutive_relation( type="LinearElasticIsotropic", youngs_modulus="E", poissons_ratio="nu" ) -model.processes.add_process_variable( +prj.processes.add_process_variable( process_variable="displacement", process_variable_name="displacement" ) -model.processes.add_process_variable( +prj.processes.add_process_variable( process_variable="pressure", process_variable_name="pressure" ) -model.processes.add_process_variable( +prj.processes.add_process_variable( process_variable="temperature", process_variable_name="temperature" ) -model.processes.add_secondary_variable( - internal_name="sigma", output_name="sigma" -) -model.processes.add_secondary_variable( +prj.processes.add_secondary_variable(internal_name="sigma", output_name="sigma") +prj.processes.add_secondary_variable( internal_name="epsilon", output_name="epsilon" ) -model.media.add_property( +prj.media.add_property( medium_id="0", phase_type="AqueousLiquid", name="specific_heat_capacity", type="Constant", value="4280.0", ) -model.media.add_property( +prj.media.add_property( medium_id="0", phase_type="AqueousLiquid", name="thermal_conductivity", type="Constant", value="0.6", ) -model.media.add_property( +prj.media.add_property( medium_id="0", phase_type="AqueousLiquid", name="density", @@ -74,70 +72,70 @@ # "expression":0.0}, # "phase_pressure": { # "expression": 0.0}}) -model.media.add_property( +prj.media.add_property( medium_id="0", phase_type="AqueousLiquid", name="thermal_expansivity", type="Constant", value="4.0e-4", ) -model.media.add_property( +prj.media.add_property( medium_id="0", phase_type="AqueousLiquid", name="viscosity", type="Constant", value="1.e-3", ) -model.media.add_property( +prj.media.add_property( medium_id="0", name="permeability", type="Constant", value="2e-20 0 0 2e-20" ) -model.media.add_property( +prj.media.add_property( medium_id="0", name="porosity", type="Constant", value="0.16" ) -model.media.add_property( +prj.media.add_property( medium_id="0", phase_type="Solid", name="storage", type="Constant", value="0.0", ) -model.media.add_property( +prj.media.add_property( medium_id="0", phase_type="Solid", name="density", type="Constant", value="2290", ) -model.media.add_property( +prj.media.add_property( medium_id="0", phase_type="Solid", name="thermal_conductivity", type="Constant", value="1.838", ) -model.media.add_property( +prj.media.add_property( medium_id="0", phase_type="Solid", name="specific_heat_capacity", type="Constant", value="917.654", ) -model.media.add_property( +prj.media.add_property( medium_id="0", name="biot_coefficient", type="Constant", value="1.0" ) -model.media.add_property( +prj.media.add_property( medium_id="0", phase_type="Solid", name="thermal_expansivity", type="Constant", value="1.5e-5", ) -model.media.add_property( +prj.media.add_property( medium_id="0", name="thermal_conductivity", type="EffectiveThermalConductivityPorosityMixing", ) -model.time_loop.add_process( +prj.time_loop.add_process( process="THERMO_HYDRO_MECHANICS", nonlinear_solver_name="basic_newton", convergence_type="PerComponentDeltaX", @@ -145,7 +143,7 @@ abstols="1e-5 1e-5 1e-5 1e-5", time_discretization="BackwardEuler", ) -model.time_loop.set_stepping( +prj.time_loop.set_stepping( process="THERMO_HYDRO_MECHANICS", type="FixedTimeStepping", t_initial="0", @@ -153,7 +151,7 @@ repeat="10", delta_t="5000", ) -model.time_loop.add_output( +prj.time_loop.add_output( type="VTK", prefix="blubb", repeat="1", @@ -161,43 +159,43 @@ variables=["displacement", "pressure", "temperature", "sigma", "epsilon"], fixed_output_times=[1, 2, 3], ) -model.time_loop.add_time_stepping_pair( +prj.time_loop.add_time_stepping_pair( process="THERMO_HYDRO_MECHANICS", repeat="15", delta_t="32" ) -model.time_loop.add_output_pair(repeat="12", each_steps="11") -model.parameters.add_parameter(name="E", type="Constant", value="5000000000") -model.parameters.add_parameter(name="nu", type="Constant", value="0.3") -model.parameters.add_parameter(name="T0", type="Constant", value="273.15") -model.parameters.add_parameter( +prj.time_loop.add_output_pair(repeat="12", each_steps="11") +prj.parameters.add_parameter(name="E", type="Constant", value="5000000000") +prj.parameters.add_parameter(name="nu", type="Constant", value="0.3") +prj.parameters.add_parameter(name="T0", type="Constant", value="273.15") +prj.parameters.add_parameter( name="displacement0", type="Constant", values="0 0" ) -model.parameters.add_parameter(name="pressure_ic", type="Constant", value="0") -model.parameters.add_parameter(name="dirichlet0", type="Constant", value="0") -model.parameters.add_parameter(name="Neumann0", type="Constant", value="0.0") -model.parameters.add_parameter( +prj.parameters.add_parameter(name="pressure_ic", type="Constant", value="0") +prj.parameters.add_parameter(name="dirichlet0", type="Constant", value="0") +prj.parameters.add_parameter(name="Neumann0", type="Constant", value="0.0") +prj.parameters.add_parameter( name="temperature_ic", type="Constant", value="273.15" ) -model.parameters.add_parameter( +prj.parameters.add_parameter( name="pressure_bc_left", type="Constant", value="0" ) -model.parameters.add_parameter( +prj.parameters.add_parameter( name="temperature_bc_left", type="Constant", value="273.15" ) -model.parameters.add_parameter( +prj.parameters.add_parameter( name="temperature_source_term", type="Constant", value="150" ) -model.curves.add_curve( +prj.curves.add_curve( name="time_curve", coords=[0.0, 1e6, 1.1e6, 5e6], values=[1.0, 1.0, 2.0, 2.0], ) -model.process_variables.set_ic( +prj.process_variables.set_ic( process_variable_name="displacement", components="2", order="2", initial_condition="displacement0", ) -model.process_variables.add_bc( +prj.process_variables.add_bc( process_variable_name="displacement", geometrical_set="square_1x1_geometry", geometry="left", @@ -205,7 +203,7 @@ component="0", parameter="dirichlet0", ) -model.process_variables.add_bc( +prj.process_variables.add_bc( process_variable_name="displacement", geometrical_set="square_1x1_geometry", geometry="bottom", @@ -213,13 +211,13 @@ component="1", parameter="dirichlet0", ) -model.process_variables.set_ic( +prj.process_variables.set_ic( process_variable_name="pressure", components="1", order="1", initial_condition="pressure_ic", ) -model.process_variables.add_bc( +prj.process_variables.add_bc( process_variable_name="pressure", geometrical_set="square_1x1_geometry", geometry="out", @@ -227,13 +225,13 @@ component="0", parameter="pressure_bc_left", ) -model.process_variables.set_ic( +prj.process_variables.set_ic( process_variable_name="temperature", components="1", order="1", initial_condition="temperature_ic", ) -model.process_variables.add_bc( +prj.process_variables.add_bc( process_variable_name="temperature", geometrical_set="square_1x1_geometry", geometry="out", @@ -241,20 +239,20 @@ component="0", parameter="temperature_bc_left", ) -model.process_variables.add_st( +prj.process_variables.add_st( process_variable_name="temperature", geometrical_set="square_1x1_geometry", geometry="center", type="Nodal", parameter="temperature_source_term", ) -model.nonlinear_solvers.add_non_lin_solver( +prj.nonlinear_solvers.add_non_lin_solver( name="basic_newton", type="Newton", max_iter="50", linear_solver="general_linear_solver", ) -model.linear_solvers.add_lin_solver( +prj.linear_solvers.add_lin_solver( name="general_linear_solver", kind="lis", solver_type="bicgstab", @@ -262,7 +260,7 @@ max_iteration_step="10000", error_tolerance="1e-16", ) -model.linear_solvers.add_lin_solver( +prj.linear_solvers.add_lin_solver( name="general_linear_solver", kind="eigen", solver_type="SparseLU", @@ -271,7 +269,7 @@ error_tolerance="1e-8", scaling="1", ) -model.linear_solvers.add_lin_solver( +prj.linear_solvers.add_lin_solver( name="general_linear_solver", kind="petsc", prefix="sd", @@ -280,5 +278,5 @@ max_iteration_step="10000", error_tolerance="1e-16", ) -model.write_input() +prj.write_input() # model.run_model(logfile="out_thm.log") diff --git a/ogstools/feflowlib/_cli.py b/ogstools/feflowlib/_cli.py index 9ba63d79..ca590d6f 100644 --- a/ogstools/feflowlib/_cli.py +++ b/ogstools/feflowlib/_cli.py @@ -34,7 +34,7 @@ write_mesh_of_combined_properties, write_point_boundary_conditions, ) -from ogstools.ogs6py import ogs +from ogstools.ogs6py import Project parser = ArgumentParser( description="This tool converts FEFLOW binary files to VTK format.", @@ -179,20 +179,20 @@ def feflow_converter(input: str, output: str, case: str, BC: str) -> int: if "steady_state_diffusion" in case: template_model = steady_state_diffusion( Path(Path(output).stem), - ogs.OGS(PROJECT_FILE=Path(output).with_suffix(".prj")), + Project(output_file=Path(output).with_suffix(".prj")), ) process = "steady state diffusion" elif "liquid_flow" in case: template_model = liquid_flow( Path(Path(output).stem), - ogs.OGS(PROJECT_FILE=Path(output).with_suffix(".prj")), + Project(output_file=Path(output).with_suffix(".prj")), dimension=doc.getNumberOfDimensions(), ) process = "liquid flow" elif "hydro_thermal" in case: template_model = hydro_thermal( Path(Path(output).stem), - ogs.OGS(PROJECT_FILE=Path(output).with_suffix(".prj")), + Project(output_file=Path(output).with_suffix(".prj")), dimension=doc.getNumberOfDimensions(), ) process = "hydro thermal" @@ -200,7 +200,7 @@ def feflow_converter(input: str, output: str, case: str, BC: str) -> int: template_model = component_transport( Path(Path(output).stem), species, - ogs.OGS(PROJECT_FILE=Path(output).with_suffix(".prj")), + Project(output_file=Path(output).with_suffix(".prj")), dimension=doc.getNumberOfDimensions(), ) process = "component transport" diff --git a/ogstools/feflowlib/templates.py b/ogstools/feflowlib/templates.py index 181810c6..c239b4ed 100644 --- a/ogstools/feflowlib/templates.py +++ b/ogstools/feflowlib/templates.py @@ -5,23 +5,23 @@ # from pathlib import Path -from ogstools.ogs6py import ogs +from ogstools.ogs6py import Project -def steady_state_diffusion(saving_path: Path, model: ogs.OGS) -> ogs.OGS: +def steady_state_diffusion(saving_path: Path, prj: Project) -> Project: """ A template for a steady state diffusion process to be simulated in ogs. :param saving_path: path of ogs simulation results - :param model: ogs model, which shall be used with the template + :param prj: ogs project, which shall be used with the template """ - model.processes.set_process( + prj.processes.set_process( name="SteadyStateDiffusion", type="STEADY_STATE_DIFFUSION", integration_order=2, ) - model.processes.add_secondary_variable("darcy_velocity", "v") - model.time_loop.add_process( + prj.processes.add_secondary_variable("darcy_velocity", "v") + prj.time_loop.add_process( process="SteadyStateDiffusion", nonlinear_solver_name="basic_picard", convergence_type="DeltaX", @@ -29,7 +29,7 @@ def steady_state_diffusion(saving_path: Path, model: ogs.OGS) -> ogs.OGS: abstol="1e-15", time_discretization="BackwardEuler", ) - model.time_loop.set_stepping( + prj.time_loop.set_stepping( process="SteadyStateDiffusion", type="SingleStep", t_initial="0", @@ -37,20 +37,20 @@ def steady_state_diffusion(saving_path: Path, model: ogs.OGS) -> ogs.OGS: repeat="1", delta_t="0.25", ) - model.time_loop.add_output( + prj.time_loop.add_output( type="VTK", prefix=str(saving_path), repeat="1", each_steps="1", variables=[], ) - model.nonlinear_solvers.add_non_lin_solver( + prj.nonlinear_solvers.add_non_lin_solver( name="basic_picard", type="Picard", max_iter="10", linear_solver="general_linear_solver", ) - model.linear_solvers.add_lin_solver( + prj.linear_solvers.add_lin_solver( name="general_linear_solver", kind="lis", solver_type="cg", @@ -58,7 +58,7 @@ def steady_state_diffusion(saving_path: Path, model: ogs.OGS) -> ogs.OGS: max_iteration_step="100000", error_tolerance="1e-6", ) - model.linear_solvers.add_lin_solver( + prj.linear_solvers.add_lin_solver( name="general_linear_solver", kind="eigen", solver_type="CG", @@ -66,7 +66,7 @@ def steady_state_diffusion(saving_path: Path, model: ogs.OGS) -> ogs.OGS: max_iteration_step="100000", error_tolerance="1e-6", ) - model.linear_solvers.add_lin_solver( + prj.linear_solvers.add_lin_solver( name="general_linear_solver", kind="petsc", prefix="sd", @@ -75,17 +75,15 @@ def steady_state_diffusion(saving_path: Path, model: ogs.OGS) -> ogs.OGS: max_iteration_step="10000", error_tolerance="1e-16", ) - return model + return prj -def liquid_flow( - saving_path: Path, model: ogs.OGS, dimension: int = 3 -) -> ogs.OGS: +def liquid_flow(saving_path: Path, prj: Project, dimension: int = 3) -> Project: """ A template for a steady liquid flow process to be simulated in ogs. :param saving_path: path of ogs simulation results - :param model: ogs model, which shall be used with the template + :param prj: ogs project, which shall be used with the template :param dimension: True, if the model is 2 dimensional. """ # FEFLOW uses hydraulic HEAD instead of pressure as primary variable, @@ -100,15 +98,15 @@ def liquid_flow( gravity = "0 0 0" else: ValueError("Dimension can be either 1,2 or 3.") - model.processes.set_process( + prj.processes.set_process( name="LiquidFlow", type="LIQUID_FLOW", integration_order=2, specific_body_force=gravity, linear="true", ) - model.processes.add_secondary_variable("darcy_velocity", "v") - model.time_loop.add_process( + prj.processes.add_secondary_variable("darcy_velocity", "v") + prj.time_loop.add_process( process="LiquidFlow", nonlinear_solver_name="basic_picard", convergence_type="DeltaX", @@ -116,7 +114,7 @@ def liquid_flow( abstol="1e-10", time_discretization="BackwardEuler", ) - model.time_loop.set_stepping( + prj.time_loop.set_stepping( process="LiquidFlow", type="FixedTimeStepping", t_initial="0", @@ -124,20 +122,20 @@ def liquid_flow( repeat="1", delta_t="1", ) - model.time_loop.add_output( + prj.time_loop.add_output( type="VTK", prefix=str(saving_path), repeat="1", each_steps="1", variables=[], ) - model.nonlinear_solvers.add_non_lin_solver( + prj.nonlinear_solvers.add_non_lin_solver( name="basic_picard", type="Picard", max_iter="10", linear_solver="general_linear_solver", ) - model.linear_solvers.add_lin_solver( + prj.linear_solvers.add_lin_solver( name="general_linear_solver", kind="lis", solver_type="cg", @@ -145,7 +143,7 @@ def liquid_flow( max_iteration_step="10000", error_tolerance="1e-20", ) - model.linear_solvers.add_lin_solver( + prj.linear_solvers.add_lin_solver( name="general_linear_solver", kind="eigen", solver_type="CG", @@ -153,7 +151,7 @@ def liquid_flow( max_iteration_step="100000", error_tolerance="1e-20", ) - model.linear_solvers.add_lin_solver( + prj.linear_solvers.add_lin_solver( name="general_linear_solver", kind="petsc", prefix="lf", @@ -162,25 +160,25 @@ def liquid_flow( max_iteration_step="10000", error_tolerance="1e-16", ) - return model + return prj def component_transport( saving_path: Path, species: list, - model: ogs.OGS, + prj: Project, dimension: int = 3, fixed_out_times: list | None = None, time_stepping: list | None = None, initial_time: int = 1, end_time: int = 1, -) -> ogs.OGS: +) -> Project: """ A template for component transport process to be simulated in ogs. :param saving_path: path of ogs simulation results :param species: - :param model: ogs model, which shall be used with the template + :param prj: ogs project, which shall be used with the template :param dimension: True, if the model is 2 dimensional. :param time_stepping: List of how often a time step should be repeated and its time. :param initial_time: Beginning of the simulation time. @@ -194,7 +192,7 @@ def component_transport( gravity = "0 0 0" else: ValueError("Dimension can be either 1,2 or 3.") - model.processes.set_process( + prj.processes.set_process( name="CT", type="ComponentTransport", coupling_scheme="staggered", @@ -203,7 +201,7 @@ def component_transport( ) output_variables = species + ["HEAD_OGS"] fixed_out_times = [end_time] if fixed_out_times is None else fixed_out_times - model.time_loop.add_output( + prj.time_loop.add_output( type="VTK", prefix=str(saving_path), variables=output_variables, @@ -211,13 +209,13 @@ def component_transport( each_steps=end_time, fixed_output_times=fixed_out_times, ) - model.nonlinear_solvers.add_non_lin_solver( + prj.nonlinear_solvers.add_non_lin_solver( name="basic_picard", type="Picard", max_iter="10", linear_solver="general_linear_solver", ) - model.linear_solvers.add_lin_solver( + prj.linear_solvers.add_lin_solver( name="general_linear_solver", kind="lis", solver_type="bicgstab", @@ -225,7 +223,7 @@ def component_transport( max_iteration_step="10000", error_tolerance="1e-10", ) - model.linear_solvers.add_lin_solver( + prj.linear_solvers.add_lin_solver( name="general_linear_solver", kind="eigen", solver_type="CG", @@ -233,7 +231,7 @@ def component_transport( max_iteration_step="100000", error_tolerance="1e-20", ) - model.linear_solvers.add_lin_solver( + prj.linear_solvers.add_lin_solver( name="general_linear_solver", kind="petsc", prefix="ct", @@ -244,7 +242,7 @@ def component_transport( ) for _i in range(len(species) + 1): - model.time_loop.add_process( + prj.time_loop.add_process( process="CT", nonlinear_solver_name="basic_picard", convergence_type="DeltaX", @@ -255,7 +253,7 @@ def component_transport( if time_stepping is None: time_stepping = [(1, 1)] - model.time_loop.set_stepping( + prj.time_loop.set_stepping( process="CT", type="FixedTimeStepping", t_initial=initial_time, @@ -265,20 +263,20 @@ def component_transport( ) for time_step in time_stepping[1:]: - model.time_loop.add_time_stepping_pair( + prj.time_loop.add_time_stepping_pair( repeat=time_step[0], delta_t=time_step[1], process="CT" ) - return model + return prj def hydro_thermal( - saving_path: Path, model: ogs.OGS, dimension: int = 3 -) -> ogs.OGS: + saving_path: Path, prj: Project, dimension: int = 3 +) -> Project: """ A template for a hydro-thermal process to be simulated in ogs. :param saving_path: path of ogs simulation results - :param model: ogs model, which shall be used with the template + :param prj: ogs project, which shall be used with the template :param dimension: to known if the model is 2D or not """ if dimension == 1: @@ -289,14 +287,14 @@ def hydro_thermal( gravity = "0 0 0" else: ValueError("Dimension can be either 1,2 or 3.") - model.processes.set_process( + prj.processes.set_process( name="HydroThermal", type="HT", integration_order=3, specific_body_force=gravity, ) - model.processes.add_secondary_variable("darcy_velocity", "v") - model.time_loop.add_process( + prj.processes.add_secondary_variable("darcy_velocity", "v") + prj.time_loop.add_process( process="HydroThermal", nonlinear_solver_name="basic_picard", convergence_type="DeltaX", @@ -304,7 +302,7 @@ def hydro_thermal( abstol="1e-16", time_discretization="BackwardEuler", ) - model.time_loop.set_stepping( + prj.time_loop.set_stepping( process="HydroThermal", type="FixedTimeStepping", t_initial="0", @@ -312,25 +310,25 @@ def hydro_thermal( repeat="1", delta_t="1e10", ) - model.time_loop.add_time_stepping_pair( + prj.time_loop.add_time_stepping_pair( process="HydroThermal", repeat="1", delta_t="1e10", ) - model.time_loop.add_output( + prj.time_loop.add_output( type="VTK", prefix=str(saving_path), repeat="1", each_steps="1", variables=[], ) - model.nonlinear_solvers.add_non_lin_solver( + prj.nonlinear_solvers.add_non_lin_solver( name="basic_picard", type="Picard", max_iter="100", linear_solver="general_linear_solver", ) - model.linear_solvers.add_lin_solver( + prj.linear_solvers.add_lin_solver( name="general_linear_solver", kind="lis", solver_type="bicgstab", @@ -338,10 +336,10 @@ def hydro_thermal( max_iteration_step="10000", error_tolerance="1e-20", ) - model.linear_solvers.add_lin_solver( + prj.linear_solvers.add_lin_solver( name="general_linear_solver", kind="eigen", solver_type="SparseLU", scaling="true", ) - return model + return prj diff --git a/ogstools/feflowlib/tools.py b/ogstools/feflowlib/tools.py index b5974817..2f00f67d 100644 --- a/ogstools/feflowlib/tools.py +++ b/ogstools/feflowlib/tools.py @@ -15,7 +15,7 @@ import pyvista as pv from typing_extensions import NotRequired, Unpack -from ogstools.ogs6py import ogs +from ogstools.ogs6py import Project # log configuration logger = log.getLogger(__name__) @@ -376,7 +376,7 @@ def get_species(mesh: pv.UnstructuredGrid) -> list: def _add_species_to_prj_file( - xpath: str, parameter_dict: dict, species_list: list, model: ogs.OGS + xpath: str, parameter_dict: dict, species_list: list, model: Project ) -> None: """ Adds the entries needed in the prj-file for components/species. Since in ogs6py no @@ -421,7 +421,7 @@ def _add_species_to_prj_file( def _add_global_process_coupling_CT( - model: ogs.OGS, species: list, max_iter: int = 1, rel_tol: float = 1e-10 + model: Project, species: list, max_iter: int = 1, rel_tol: float = 1e-10 ) -> None: """ Add the section of the prj-file that defines the global process coupling @@ -514,8 +514,8 @@ def write_mesh_of_combined_properties( def materials_in_steady_state_diffusion( material_properties: dict, - model: ogs.OGS, -) -> ogs.OGS: + model: Project, +) -> Project: """ Create the section for material properties for steady state diffusion processes in the prj-file. @@ -558,8 +558,8 @@ def materials_in_steady_state_diffusion( def materials_in_liquid_flow( material_properties: dict, - model: ogs.OGS, -) -> ogs.OGS: + model: Project, +) -> Project: """ Create the section for material properties in liquid flow processes in the prj-file. @@ -628,8 +628,8 @@ def materials_in_liquid_flow( def materials_in_HT( material_properties: dict, - model: ogs.OGS, -) -> ogs.OGS: + model: Project, +) -> Project: """ Create the section for material properties for HT processes in the prj-file. @@ -749,8 +749,8 @@ def materials_in_HT( def materials_in_CT( material_properties: dict, species_list: list, - model: ogs.OGS, -) -> ogs.OGS: + model: Project, +) -> Project: """ Create the section for material properties for CT (component transport) processes in the prj-file. @@ -859,7 +859,7 @@ def materials_in_CT( class RequestParams(TypedDict): - model: NotRequired[ogs.OGS] + model: NotRequired[Project] species_list: NotRequired[list | None] max_iter: NotRequired[int] rel_tol: NotRequired[float] @@ -871,7 +871,7 @@ def setup_prj_file( material_properties: dict, process: str, **kwargs: Unpack[RequestParams], -) -> ogs.OGS: +) -> Project: """ Sets up a prj-file for ogs simulations using ogs6py. @@ -900,7 +900,7 @@ def setup_prj_file( rel_tol = kwargs.get("rel_tol", 1e-10) prjfile = bulk_mesh_path.with_suffix(".prj") if model is None: - model = ogs.OGS(PROJECT_FILE=prjfile) + model = Project(output_file=prjfile) BC_type_dict = { "_BC_": "Dirichlet", diff --git a/ogstools/ogs6py/__init__.py b/ogstools/ogs6py/__init__.py index 4b3ecfdc..4eda6c00 100644 --- a/ogstools/ogs6py/__init__.py +++ b/ogstools/ogs6py/__init__.py @@ -6,6 +6,6 @@ # Author: Joerg Buchwald (Helmholtz Centre for Environmental Research GmbH - UFZ) -from .ogs import OGS +from .project import Project -__all__ = ["OGS"] +__all__ = ["Project"] diff --git a/ogstools/ogs6py/ogs.py b/ogstools/ogs6py/project.py similarity index 98% rename from ogstools/ogs6py/ogs.py rename to ogstools/ogs6py/project.py index 88f5df00..08dfa2c5 100644 --- a/ogstools/ogs6py/ogs.py +++ b/ogstools/ogs6py/project.py @@ -46,23 +46,23 @@ ) -class OGS: - """Class for an OGS6 model. +class Project: + """Class for handling an OGS6 project. - In this class everything for an OGS6 model can be specified. + In this class everything for an OGS6 project can be specified. Parameters ---------- - PROJECT_FILE : `str`, optional + output_file : `str`, optional Filename of the output project file Default: default.prj - INPUT_FILE : `str`, optional + input_file : `str`, optional Filename of the input project file - XMLSTRING : `str`,optional + xml_string : `str`,optional String containing the XML tree OMP_NUM_THREADS : `int`, optional Sets the environmentvariable before OGS execution to restrict number of OMP Threads - VERBOSE : `bool`, optional + verbose : `bool`, optional Default: False """ @@ -75,19 +75,19 @@ def __init__(self, **args: Any) -> None: self.include_files: list[Path] = [] self.add_includes: list[dict[str, str]] = [] self.output_dir: Path = Path() # default -> current dir - self.verbose: bool = args.get("VERBOSE", False) + self.verbose: bool = args.get("verbose", False) self.threads: int = args.get("OMP_NUM_THREADS", None) self.asm_threads: int = args.get("OGS_ASM_THREADS", self.threads) self.inputfile: Path | None = None self.folder: Path = Path() - if "PROJECT_FILE" in args: - self.prjfile = Path(args["PROJECT_FILE"]) + if "output_file" in args: + self.prjfile = Path(args["output_file"]) else: - print("PROJECT_FILE for output not given. Calling it default.prj.") + print("output_file not given. Calling it default.prj.") self.prjfile = Path("default.prj") - if "INPUT_FILE" in args: - input_file = Path(args["INPUT_FILE"]) + if "input_file" in args: + input_file = Path(args["input_file"]) if input_file.is_file(): self.inputfile = input_file self.folder = input_file.parent @@ -95,7 +95,7 @@ def __init__(self, **args: Any) -> None: if self.verbose is True: display.Display(self.tree) else: - msg = f"Input project file {args['INPUT_FILE']} not found." + msg = f"Input project file {args['input_file']} not found." raise FileNotFoundError(msg) else: self.inputfile = None @@ -103,8 +103,8 @@ def __init__(self, **args: Any) -> None: parse = ET.XMLParser(remove_blank_text=True, huge_tree=True) tree_string = ET.tostring(self.root, pretty_print=True) self.tree = ET.ElementTree(ET.fromstring(tree_string, parser=parse)) - if "XMLSTRING" in args: - root = ET.fromstring(args["XMLSTRING"]) + if "xml_string" in args: + root = ET.fromstring(args["xml_string"]) self.tree = ET.ElementTree(root) self.geometry = geo.Geo(self.tree) self.mesh = mesh.Mesh(self.tree) @@ -845,7 +845,7 @@ def run_model( ) -> None: """Command to run OGS. - Runs OGS with the project file specified as PROJECT_FILE. + Runs OGS with the project file specified as output_file. Parameters ---------- diff --git a/ogstools/ogs6py/properties.py b/ogstools/ogs6py/properties.py index 38a81907..b9c18344 100644 --- a/ogstools/ogs6py/properties.py +++ b/ogstools/ogs6py/properties.py @@ -10,7 +10,7 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: - from ogstools.ogs6py.ogs import OGS + from ogstools.ogs6py import Project from collections.abc import Generator from dataclasses import dataclass, field @@ -174,7 +174,7 @@ def __iter__(self) -> Generator: def _expand_tensors( - obj: OGS, + obj: Project, numofmedia: int, multidim_prop: dict[Any, Any], root: ET.Element, @@ -209,7 +209,7 @@ def _expand_tensors( def _expand_van_genuchten( - obj: OGS, numofmedia: int, root: ET.Element, location: str + obj: Project, numofmedia: int, root: ET.Element, location: str ) -> None: for medium_id in range(numofmedia): medium = obj._get_medium_pointer(root, medium_id) diff --git a/tests/test_feflowlib.py b/tests/test_feflowlib.py index b6d984c1..c4b85a0a 100644 --- a/tests/test_feflowlib.py +++ b/tests/test_feflowlib.py @@ -8,7 +8,7 @@ import pyvista as pv from ogstools import examples -from ogstools.ogs6py import ogs +from ogstools.ogs6py import Project pytest.importorskip("ifm") @@ -60,7 +60,7 @@ def test_neumann_ogs_steady_state_diffusion(self): prjfile = self.temp_dir / "boxNeumann_test.prj" ssd_model = steady_state_diffusion( self.temp_dir / "sim_boxNeumann", - ogs.OGS(PROJECT_FILE=prjfile), + Project(output_file=prjfile), ) model = setup_prj_file( self.vtu_path, @@ -91,7 +91,7 @@ def test_neumann_ogs_liquid_flow(self): prjfile = self.temp_dir / "boxNeumann_test.prj" lqf_model = liquid_flow( self.temp_dir / "sim_boxNeumann", - ogs.OGS(PROJECT_FILE=prjfile), + Project(output_file=prjfile), ) model = setup_prj_file( self.vtu_path, @@ -136,7 +136,7 @@ def test_robin_ogs_steady_state_diffusion(self): prjfile = self.temp_dir / "boxRobin_test.prj" ssd_model = steady_state_diffusion( str(self.temp_dir / "sim_boxRobin"), - ogs.OGS(PROJECT_FILE=prjfile), + Project(output_file=prjfile), ) model = setup_prj_file( self.vtu_path, @@ -167,7 +167,7 @@ def test_robin_ogs_liquid_flow(self): prjfile = self.temp_dir / "boxRobin_test.prj" lqf_model = liquid_flow( str(self.temp_dir / "sim_boxRobin"), - ogs.OGS(PROJECT_FILE=prjfile), + Project(output_file=prjfile), ) model = setup_prj_file( self.vtu_path, @@ -212,7 +212,7 @@ def test_well_ogs_steady_state_diffusion(self): prjfile = self.temp_dir / "boxWell_test.prj" ssd_model = steady_state_diffusion( str(self.temp_dir / "sim_boxWell"), - ogs.OGS(PROJECT_FILE=prjfile), + Project(output_file=prjfile), ) model = setup_prj_file( self.vtu_path, @@ -242,7 +242,7 @@ def test_well_ogs_liquid_flow(self): prjfile = self.temp_dir / "boxWell_test.prj" lqf_model = liquid_flow( str(self.temp_dir / "sim_boxWell"), - ogs.OGS(PROJECT_FILE=prjfile), + Project(output_file=prjfile), ) model = setup_prj_file( self.vtu_path, @@ -415,20 +415,20 @@ def test_dirichlet_toymodel_ogs_ht(self): if self.pv_mesh.celltypes[0] in [5, 9]: dimension = 2 prjfile = self.temp_dir / "HT_Dirichlet.prj" - model = hydro_thermal( + prj = hydro_thermal( str(self.temp_dir / "sim_HT_Dirichlet"), - ogs.OGS(PROJECT_FILE=prjfile), + Project(output_file=prjfile), dimension, ) - model = setup_prj_file( + prj = setup_prj_file( self.vtu_path, self.pv_mesh, get_material_properties_of_HT_model(self.pv_mesh), "hydro thermal", - model=model, + model=prj, ) - model.write_input(prjfile) - model.run_model(logfile=str(self.temp_dir / "out.log")) + prj.write_input(prjfile) + prj.run_model(logfile=str(self.temp_dir / "out.log")) # Compare ogs simulation with FEFLOW simulation ogs_sim_res = pv.read( str( @@ -469,10 +469,10 @@ def test_2_d_line_ct(self): prjfile = self.temp_dir / "CT_2D_line.prj" species = get_species(self.pv_mesh_560) - model = component_transport( + prj = component_transport( self.temp_dir / "CT_2D_line", species, - ogs.OGS(PROJECT_FILE=prjfile), + Project(output_file=prjfile), dimension, fixed_out_times=[ 2419200, @@ -485,18 +485,18 @@ def test_2_d_line_ct(self): zip([10] * 8, [8.64 * 10**i for i in range(8)], strict=False) ), ) - model = setup_prj_file( + prj = setup_prj_file( self.temp_dir / "CT_2D_line.vtu", self.pv_mesh_560, get_material_properties_of_CT_model(self.pv_mesh_560), "component transport", species_list=species, - model=model, + model=prj, max_iter=6, rel_tol=1e-14, ) - model.write_input(prjfile) - model.run_model(logfile=str(self.temp_dir / "out.log")) + prj.write_input(prjfile) + prj.run_model(logfile=str(self.temp_dir / "out.log")) # Compare ogs simulation with FEFLOW simulation ogs_sim_res_560 = pv.read( str(self.temp_dir / "CT_2D_line_ts_67_t_48384000.000000.vtu") diff --git a/tests/test_meshlib.py b/tests/test_meshlib.py index d206572c..35ce33ed 100644 --- a/tests/test_meshlib.py +++ b/tests/test_meshlib.py @@ -7,10 +7,9 @@ import pytest from pyvista import SolidSphere, UnstructuredGrid -import ogstools as ot +import ogstools as ogs from ogstools import examples from ogstools.msh2vtu import msh2vtu -from ogstools.ogs6py import ogs class TestUtils: @@ -79,7 +78,7 @@ def test_all_types(self): pvd = examples.load_meshseries_THM_2D_PVD() xdmf = examples.load_meshseries_HT_2D_XDMF() with pytest.raises(TypeError): - ot.MeshSeries( + ogs.MeshSeries( __file__, match="Can only read 'pvd', 'xdmf' or 'vtu' files." ) @@ -119,7 +118,7 @@ def test_aggregate_time_of_limit(self): def test_time_aggregate_mesh_dependent(self): "Test aggregation of mesh_dependent variable on meshseries." mesh_series = examples.load_meshseries_THM_2D_PVD() - prop = ot.variables.dilatancy_alkan + prop = ogs.variables.dilatancy_alkan agg_mesh = mesh_series.aggregate_over_time(prop, "max") assert not np.any(np.isnan(agg_mesh[prop.output_name + "_max"])) agg_mesh = mesh_series.time_of_max(prop) @@ -162,46 +161,46 @@ def test_plot_probe(self): """Test creation of probe plots.""" meshseries = examples.load_meshseries_THM_2D_PVD() points = meshseries.mesh(0).center - meshseries.plot_probe(points, ot.variables.temperature) + meshseries.plot_probe(points, ogs.variables.temperature) points = meshseries.mesh(0).points[[0, -1]] - meshseries.plot_probe(points, ot.variables.temperature) - meshseries.plot_probe(points, ot.variables.velocity) - meshseries.plot_probe(points, ot.variables.stress) - meshseries.plot_probe(points, ot.variables.stress.von_Mises) + meshseries.plot_probe(points, ogs.variables.temperature) + meshseries.plot_probe(points, ogs.variables.velocity) + meshseries.plot_probe(points, ogs.variables.stress) + meshseries.plot_probe(points, ogs.variables.stress.von_Mises) mesh_series = examples.load_meshseries_HT_2D_XDMF() points = mesh_series.mesh(0).center - meshseries.plot_probe(points, ot.variables.temperature) - meshseries.plot_probe(points, ot.variables.velocity) + meshseries.plot_probe(points, ogs.variables.temperature) + meshseries.plot_probe(points, ogs.variables.velocity) def test_diff_two_meshes(self): meshseries = examples.load_meshseries_THM_2D_PVD() mesh1 = meshseries.mesh(0) mesh2 = meshseries.mesh(-1) - mesh_diff = ot.meshlib.difference(mesh1, mesh2, "temperature") - mesh_diff = ot.meshlib.difference( - mesh1, mesh2, ot.variables.temperature + mesh_diff = ogs.meshlib.difference(mesh1, mesh2, "temperature") + mesh_diff = ogs.meshlib.difference( + mesh1, mesh2, ogs.variables.temperature ) assert isinstance(mesh_diff, UnstructuredGrid) - mesh_diff = ot.meshlib.difference(mesh1, mesh2) + mesh_diff = ogs.meshlib.difference(mesh1, mesh2) def test_diff_pairwise(self): n = 5 meshseries = examples.load_meshseries_THM_2D_PVD() meshes1 = [meshseries.mesh(0)] * n meshes2 = [meshseries.mesh(-1)] * n - meshes_diff = ot.meshlib.difference_pairwise( - meshes1, meshes2, ot.variables.temperature + meshes_diff = ogs.meshlib.difference_pairwise( + meshes1, meshes2, ogs.variables.temperature ) assert isinstance(meshes_diff, np.ndarray) assert len(meshes_diff) == n - meshes_diff = ot.meshlib.difference_pairwise(meshes1, meshes2) + meshes_diff = ogs.meshlib.difference_pairwise(meshes1, meshes2) def test_diff_matrix_single(self): meshseries = examples.load_meshseries_THM_2D_PVD() meshes1 = [meshseries.mesh(0), meshseries.mesh(-1)] - meshes_diff = ot.meshlib.difference_matrix( - meshes1, variable=ot.variables.temperature + meshes_diff = ogs.meshlib.difference_matrix( + meshes1, variable=ogs.variables.temperature ) assert isinstance(meshes_diff, np.ndarray) @@ -210,21 +209,21 @@ def test_diff_matrix_single(self): len(meshes1), ) - meshes_diff = ot.meshlib.difference_matrix(meshes1) + meshes_diff = ogs.meshlib.difference_matrix(meshes1) def test_diff_matrix_unequal(self): meshseries = examples.load_meshseries_THM_2D_PVD() meshes1 = [meshseries.mesh(0), meshseries.mesh(-1)] meshes2 = [meshseries.mesh(0), meshseries.mesh(-1), meshseries.mesh(-1)] - meshes_diff = ot.meshlib.difference_matrix( - meshes1, meshes2, ot.variables.temperature + meshes_diff = ogs.meshlib.difference_matrix( + meshes1, meshes2, ogs.variables.temperature ) assert isinstance(meshes_diff, np.ndarray) assert meshes_diff.shape == ( len(meshes1), len(meshes2), ) - meshes_diff = ot.meshlib.difference_matrix(meshes1, meshes2) + meshes_diff = ogs.meshlib.difference_matrix(meshes1, meshes2) def test_depth_2D(self): mesh = examples.load_mesh_mechanics_2D() @@ -235,7 +234,7 @@ def test_depth_2D(self): assert np.all(mesh["depth"] < -mesh.points[..., 1]) def test_depth_3D(self): - mesh = ot.Mesh(SolidSphere(100, center=(0, 0, -101))) + mesh = ogs.Mesh(SolidSphere(100, center=(0, 0, -101))) mesh["depth"] = mesh.depth(use_coords=True) assert np.all(mesh["depth"] == -mesh.points[..., -1]) mesh["depth"] = mesh.depth() @@ -249,7 +248,7 @@ def test_interp_points(self): [100, -300, 6700], ] ) - profile_points = ot.meshlib.interp_points(profile, resolution=100) + profile_points = ogs.meshlib.interp_points(profile, resolution=100) assert isinstance(profile_points, np.ndarray) # Check first point assert (profile_points[0, :] == profile[0, :]).all() @@ -260,15 +259,15 @@ def test_interp_points(self): def test_distance_in_segments(self): profile = np.array([[0, 0, 0], [1, 0, 0], [2, 0, 0]]) - profile_points = ot.meshlib.interp_points(profile, resolution=9) - dist_in_seg = ot.meshlib.distance_in_segments(profile, profile_points) + profile_points = ogs.meshlib.interp_points(profile, resolution=9) + dist_in_seg = ogs.meshlib.distance_in_segments(profile, profile_points) assert len(np.where(dist_in_seg == 0)[0]) == 2 assert len(np.where(dist_in_seg == 1)[0]) == 1 def test_distance_in_profile(self): profile = np.array([[0, 0, 0], [1, 0, 0], [2, 0, 0]]) - profile_points = ot.meshlib.interp_points(profile, resolution=9) - dist_in_seg = ot.meshlib.distance_in_profile(profile_points) + profile_points = ogs.meshlib.interp_points(profile, resolution=9) + dist_in_seg = ogs.meshlib.distance_in_profile(profile_points) # Check if distance is increasing assert np.all(np.diff(dist_in_seg) > 0) # Check if distances at the beginning and end of profile are correct @@ -278,7 +277,7 @@ def test_distance_in_profile(self): def test_sample_over_polyline_single_segment(self): ms = examples.load_meshseries_HT_2D_XDMF() profile = np.array([[4, 2, 0], [4, 18, 0]]) - ms_sp, _ = ot.meshlib.sample_polyline( + ms_sp, _ = ogs.meshlib.sample_polyline( ms.mesh(-1), ["pressure", "temperature"], profile, @@ -302,13 +301,13 @@ def test_sample_over_polyline_multi_segment(self): [910, -590, 6700], ] ) - ms_sp, _ = ot.meshlib.sample_polyline( + ms_sp, _ = ogs.meshlib.sample_polyline( ms.mesh(1), - ot.variables.temperature, + ogs.variables.temperature, profile, resolution=10, ) - data = ms_sp[ot.variables.temperature.data_name].to_numpy() + data = ms_sp[ogs.variables.temperature.data_name].to_numpy() assert not np.any(np.isnan(data)) assert (np.abs(data) > np.zeros_like(data)).all() # output should be in Celsius @@ -318,7 +317,7 @@ def test_sample_over_polyline_multi_segment(self): def test_sample_over_polyline_single_segment_vec_prop(self): ms = examples.load_meshseries_HT_2D_XDMF() profile = np.array([[4, 2, 0], [4, 18, 0]]) - ms_sp, _ = ot.meshlib.sample_polyline( + ms_sp, _ = ogs.meshlib.sample_polyline( ms.mesh(-1), "darcy_velocity", profile, @@ -339,12 +338,12 @@ def test_ip_mesh(self): tmp_path = Path(mkdtemp()) mesh_path = Path(tmp_path) / "mesh.msh" - sigma_ip = ot.variables.stress.replace(data_name="sigma_ip") + sigma_ip = ogs.variables.stress.replace(data_name="sigma_ip") def run_and_check( elem_order: int, quads: bool, intpt_order: int, mixed: bool = False ): - ot.meshlib.gmsh_meshing.rect( + ogs.meshlib.gmsh_meshing.rect( n_edge_cells=6, n_layers=2, structured_grid=quads, @@ -355,16 +354,16 @@ def run_and_check( ) msh2vtu(mesh_path, tmp_path, reindex=True, log_level="ERROR") - model = ogs.OGS( - PROJECT_FILE=tmp_path / "default.prj", - INPUT_FILE=examples.prj_mechanics, + model = ogs.Project( + output_file=tmp_path / "default.prj", + input_file=examples.prj_mechanics, ) model.replace_text(intpt_order, xpath=".//integration_order") model.write_input() model.run_model( write_logs=True, args=f"-m {tmp_path} -o {tmp_path}" ) - meshseries = ot.MeshSeries(tmp_path / "mesh.pvd") + meshseries = ogs.MeshSeries(tmp_path / "mesh.pvd") int_pts = meshseries.mesh(-1).to_ip_point_cloud() ip_ms = meshseries.ip_tesselated() ip_mesh = ip_ms.mesh(-1) @@ -390,36 +389,36 @@ def run_and_check( run_and_check(elem_order=1, quads=False, intpt_order=2, mixed=True) def test_reader(self): - assert isinstance(examples.load_meshseries_THM_2D_PVD(), ot.MeshSeries) - assert isinstance(ot.MeshSeries(examples.elder_xdmf), ot.MeshSeries) - assert isinstance(ot.Mesh.read(examples.mechanics_vtu), ot.Mesh) - assert isinstance(ot.Mesh.read(examples.test_shapefile), ot.Mesh) + assert isinstance(examples.load_meshseries_THM_2D_PVD(), ogs.MeshSeries) + assert isinstance(ogs.MeshSeries(examples.elder_xdmf), ogs.MeshSeries) + assert isinstance(ogs.Mesh.read(examples.mechanics_vtu), ogs.Mesh) + assert isinstance(ogs.Mesh.read(examples.test_shapefile), ogs.Mesh) def test_xdmf_quadratic(self): "Test reading of quadratic elements in xdmf." tmp_path = Path(mkdtemp()) mesh_path = Path(tmp_path) / "mesh.msh" - ot.meshlib.gmsh_meshing.rect( + ogs.meshlib.gmsh_meshing.rect( n_edge_cells=6, structured_grid=False, order=2, out_name=mesh_path ) msh2vtu(mesh_path, tmp_path, reindex=True, log_level="ERROR") - model = ogs.OGS( - PROJECT_FILE=tmp_path / "default.prj", - INPUT_FILE=examples.prj_mechanics, + model = ogs.Project( + output_file=tmp_path / "default.prj", + input_file=examples.prj_mechanics, ) model.replace_text("4", xpath=".//integration_order") model.replace_text("XDMF", xpath="./time_loop/output/type") model.write_input() model.run_model(write_logs=True, args=f"-m {tmp_path} -o {tmp_path}") - mesh = ot.MeshSeries(tmp_path / "mesh_mesh_domain.xdmf").mesh(-1) - assert not np.any(np.isnan(ot.variables.stress.transform(mesh))) + mesh = ogs.MeshSeries(tmp_path / "mesh_mesh_domain.xdmf").mesh(-1) + assert not np.any(np.isnan(ogs.variables.stress.transform(mesh))) def test_remesh_with_tri(self): mesh = examples.load_meshseries_THM_2D_PVD().mesh(1) temp_dir = Path(mkdtemp()) msh_path = temp_dir / "tri_mesh.msh" - ot.meshlib.gmsh_meshing.remesh_with_triangle(mesh, msh_path) + ogs.meshlib.gmsh_meshing.remesh_with_triangle(mesh, msh_path) assert ( msh2vtu(msh_path, temp_dir, reindex=False, log_level="ERROR") == 0 ) diff --git a/tests/test_ogs6py.py b/tests/test_ogs6py.py index 37c47873..5125cbb0 100644 --- a/tests/test_ogs6py.py +++ b/tests/test_ogs6py.py @@ -11,7 +11,6 @@ import pytest from lxml import etree as ET -from ogstools import ogs6py from ogstools.examples import ( prj_beier_sandbox, prj_beier_sandbox_ref, @@ -32,6 +31,7 @@ prj_tunnel_trm, prj_tunnel_trm_withincludes, ) +from ogstools.ogs6py import Project def log_types(records): @@ -46,8 +46,8 @@ def log_types(records): class TestiOGS: def test_buildfromscratch(self) -> NoReturn: - model = ogs6py.OGS( - PROJECT_FILE="tunnel_ogs6py.prj", MKL=True, OMP_NUM_THREADS=4 + model = Project( + output_file="tunnel_ogs6py.prj", MKL=True, OMP_NUM_THREADS=4 ) model.mesh.add_mesh( filename="Decovalex-0-simplified-plain-with-p0-plain.vtu" @@ -811,9 +811,7 @@ def test_buildfromscratch(self) -> NoReturn: assert line == lines_ref[i] def test_buildfromscratch_bhe(self) -> NoReturn: - model = ogs6py.OGS( - PROJECT_FILE="HeatTransportBHE_ogs6py.prj", MKL=False - ) + model = Project(output_file="HeatTransportBHE_ogs6py.prj", MKL=False) model.mesh.add_mesh(filename="bhe_mesh.vtu") model.mesh.add_mesh(filename="bhe_mesh_inflowsf.vtu") model.mesh.add_mesh(filename="bhe_mesh_bottomsf.vtu") @@ -1116,7 +1114,7 @@ def test_buildfromscratch_bhe(self) -> NoReturn: def test_replace_text(self) -> NoReturn: prjfile = "tunnel_ogs6py_replace.prj" - model = ogs6py.OGS(INPUT_FILE=prj_tunnel_trm, PROJECT_FILE=prjfile) + model = Project(input_file=prj_tunnel_trm, output_file=prjfile) model.replace_text("tunnel_replace", xpath="./time_loop/output/prefix") model.write_input() root = ET.parse(prjfile) @@ -1125,10 +1123,10 @@ def test_replace_text(self) -> NoReturn: def test_timedependenthet_param(self) -> NoReturn: prjfile = "timedephetparam.prj" - model = ogs6py.OGS( - INPUT_FILE=prj_time_dep_het_param, - PROJECT_FILE=prjfile, - VERBOSE=True, + model = Project( + input_file=prj_time_dep_het_param, + output_file=prjfile, + verbose=True, ) model.parameters.add_parameter( name="kappa1", type="Function", expression="1.e-12" @@ -1173,7 +1171,7 @@ def test_timedependenthet_param(self) -> NoReturn: def test_python_st(self) -> NoReturn: prjfile = "python_st.prj" - model = ogs6py.OGS(INPUT_FILE=prj_beier_sandbox, PROJECT_FILE=prjfile) + model = Project(input_file=prj_beier_sandbox, output_file=prjfile) model.geometry.add_geometry("beier_sandbox.gml") model.python_script.set_pyscript("simulationX_test.py") model.write_input() @@ -1192,9 +1190,7 @@ def test_python_st(self) -> NoReturn: def test_robin_bc(self) -> NoReturn: prjfile = "robin_bc.prj" - model = ogs6py.OGS( - INPUT_FILE=prj_square_1e4_robin, PROJECT_FILE=prjfile - ) + model = Project(input_file=prj_square_1e4_robin, output_file=prjfile) model.process_variables.add_bc( process_variable_name="temperature", geometrical_set="square_1x1_geometry", @@ -1219,7 +1215,7 @@ def test_robin_bc(self) -> NoReturn: def test_staggered(self) -> NoReturn: prjfile = "staggered.prj" - model = ogs6py.OGS(INPUT_FILE=prj_staggered, PROJECT_FILE=prjfile) + model = Project(input_file=prj_staggered, output_file=prjfile) model.processes.set_process( name="HM", type="HYDRO_MECHANICS", @@ -1286,9 +1282,7 @@ def test_staggered(self) -> NoReturn: def test_PID_controller(self) -> NoReturn: prjfile = "pid_timestepping.prj" - model = ogs6py.OGS( - INPUT_FILE=prj_pid_timestepping, PROJECT_FILE=prjfile - ) + model = Project(input_file=prj_pid_timestepping, output_file=prjfile) model.media.add_property( medium_id="0", name="relative_permeability", @@ -1324,9 +1318,7 @@ def test_PID_controller(self) -> NoReturn: def test_deactivate_replace(self) -> NoReturn: prjfile = "deactivate_replace.prj" - model = ogs6py.OGS( - INPUT_FILE=prj_pid_timestepping, PROJECT_FILE=prjfile - ) + model = Project(input_file=prj_pid_timestepping, output_file=prjfile) model.deactivate_property("viscosity", phase="AqueousLiquid") model.deactivate_parameter("p0") model.replace_parameter( @@ -1352,7 +1344,7 @@ def test_deactivate_replace(self) -> NoReturn: def test_empty_replace(self) -> NoReturn: inputfile = Path(prj_tunnel_trm) prjfile = Path("tunnel_ogs6py_empty_replace.prj") - model = ogs6py.OGS(INPUT_FILE=inputfile, PROJECT_FILE=prjfile) + model = Project(input_file=inputfile, output_file=prjfile) model.write_input() with inputfile.open("rb") as f: lines = f.readlines() @@ -1369,7 +1361,7 @@ def test_empty_replace(self) -> NoReturn: def test_replace_phase_property(self) -> NoReturn: prjfile = "tunnel_ogs6py_replace.prj" - model = ogs6py.OGS(INPUT_FILE=prj_tunnel_trm, PROJECT_FILE=prjfile) + model = Project(input_file=prj_tunnel_trm, output_file=prjfile) model.replace_phase_property_value( mediumid=0, phase="Solid", name="thermal_expansivity", value=5 ) @@ -1382,7 +1374,7 @@ def test_replace_phase_property(self) -> NoReturn: def test_replace_medium_property(self) -> NoReturn: prjfile = "tunnel_ogs6py_replace.prj" - model = ogs6py.OGS(INPUT_FILE=prj_tunnel_trm, PROJECT_FILE=prjfile) + model = Project(input_file=prj_tunnel_trm, output_file=prjfile) model.replace_medium_property_value( mediumid=0, name="porosity", value=42 ) @@ -1395,7 +1387,7 @@ def test_replace_medium_property(self) -> NoReturn: def test_replace_parameter(self) -> NoReturn: prjfile = "tunnel_ogs6py_replace.prj" - model = ogs6py.OGS(INPUT_FILE=prj_tunnel_trm, PROJECT_FILE=prjfile) + model = Project(input_file=prj_tunnel_trm, output_file=prjfile) model.replace_parameter_value(name="E", value=32) model.write_input() root = ET.parse(prjfile) @@ -1404,7 +1396,7 @@ def test_replace_parameter(self) -> NoReturn: def test_replace_mesh(self) -> NoReturn: prjfile = "tunnel_ogs6py_replacemesh.prj" - model = ogs6py.OGS(INPUT_FILE=prj_tunnel_trm, PROJECT_FILE=prjfile) + model = Project(input_file=prj_tunnel_trm, output_file=prjfile) model.replace_mesh( oldmesh="tunnel_inner.vtu", newmesh="tunnel_inner_new.vtu" ) @@ -1432,7 +1424,7 @@ def test_replace_mesh(self) -> NoReturn: def test_add_entry(self) -> NoReturn: prjfile = "tunnel_ogs6py_add_entry.prj" - model = ogs6py.OGS(INPUT_FILE=prj_tunnel_trm, PROJECT_FILE=prjfile) + model = Project(input_file=prj_tunnel_trm, output_file=prjfile) model.add_element(tag="geometry", parent_xpath=".", text="geometry.gml") model.write_input() root = ET.parse(prjfile) @@ -1441,7 +1433,7 @@ def test_add_entry(self) -> NoReturn: def test_add_block(self) -> NoReturn: prjfile = "tunnel_ogs6py_add_block.prj" - model = ogs6py.OGS(INPUT_FILE="tunnel_ogs6py.prj", PROJECT_FILE=prjfile) + model = Project(input_file="tunnel_ogs6py.prj", output_file=prjfile) model.add_block( "parameter", parent_xpath="./parameters", @@ -1455,7 +1447,7 @@ def test_add_block(self) -> NoReturn: def test_remove_element(self) -> NoReturn: prjfile = "tunnel_ogs6py_remove_element.prj" - model = ogs6py.OGS(INPUT_FILE=prj_tunnel_trm, PROJECT_FILE=prjfile) + model = Project(input_file=prj_tunnel_trm, output_file=prjfile) model.remove_element(xpath="./parameters/parameter[name='E']") model.write_input() root = ET.parse(prjfile) @@ -1464,7 +1456,7 @@ def test_remove_element(self) -> NoReturn: def test_replace_block_by_include(self) -> NoReturn: prjfile = "tunnel_ogs6py_solid_inc.prj" - model = ogs6py.OGS(INPUT_FILE=prj_tunnel_trm, PROJECT_FILE=prjfile) + model = Project(input_file=prj_tunnel_trm, output_file=prjfile) model.replace_block_by_include( xpath="./media/medium/phases/phase[type='Solid']", filename="solid.xml", @@ -1496,7 +1488,7 @@ def test_replace_block_by_include(self) -> NoReturn: assert line == lines_ref[i] def test_property_dataframe(self) -> NoReturn: - model = ogs6py.OGS(INPUT_FILE=prj_tunnel_trm) + model = Project(input_file=prj_tunnel_trm) p_df = model.property_dataframe() assert p_df.shape[0] == 12 assert p_df.shape[1] == 5 @@ -1515,8 +1507,8 @@ def test_property_dataframe(self) -> NoReturn: def test_replace_property_in_include(self) -> NoReturn: prjfile = "tunnel_ogs6py_includetest.prj" - model = ogs6py.OGS( - INPUT_FILE=prj_tunnel_trm_withincludes, PROJECT_FILE=prjfile + model = Project( + input_file=prj_tunnel_trm_withincludes, output_file=prjfile ) model.replace_phase_property_value( mediumid=0, phase="Solid", name="thermal_expansivity", value=1e-3 @@ -1557,7 +1549,7 @@ def test_model_run(self) -> NoReturn: sing_dir = tempfile.TemporaryDirectory() # case: path is not a dir - model = ogs6py.OGS(INPUT_FILE=prjfile, PROJECT_FILE=prjfile) + model = Project(input_file=prjfile, output_file=prjfile) with pytest.raises( RuntimeError, match=r"The specified path is not a directory.*" ): diff --git a/tests/test_plot.py b/tests/test_plot.py index 58a05298..4ca2e3fc 100644 --- a/tests/test_plot.py +++ b/tests/test_plot.py @@ -8,7 +8,7 @@ import pytest from pyvista import examples as pv_examples -import ogstools as ot +import ogstools as ogs from ogstools import examples from ogstools.plot import utils @@ -33,30 +33,30 @@ def test_pyvista_offscreen(self): def test_levels(self): """Test levels calculation.""" assert_allclose( - ot.plot.compute_levels(0.5, 10.1, 10), [0.5, *range(1, 11), 10.1] + ogs.plot.compute_levels(0.5, 10.1, 10), [0.5, *range(1, 11), 10.1] ) assert_allclose( - ot.plot.compute_levels(293, 350, 10), [293, *range(295, 355, 5)] + ogs.plot.compute_levels(293, 350, 10), [293, *range(295, 355, 5)] ) assert_allclose( - ot.plot.compute_levels(1e-3, 1.2, 5), + ogs.plot.compute_levels(1e-3, 1.2, 5), [1e-3, *np.arange(0.2, 1.4, 0.2)], ) assert_allclose( - ot.plot.compute_levels(1e5, 9e6, 20), + ogs.plot.compute_levels(1e5, 9e6, 20), [1e5, *np.arange(5e5, 9.5e6, 5e5)], ) assert_allclose( - ot.plot.compute_levels(1, 40, 20), [1, *range(2, 42, 2)] + ogs.plot.compute_levels(1, 40, 20), [1, *range(2, 42, 2)] ) - assert_allclose(ot.plot.compute_levels(0.0, 0.0, 10), [0.0, 0.0]) - assert_allclose(ot.plot.compute_levels(1e9, 1e9, 10), [1e9, 1e9]) + assert_allclose(ogs.plot.compute_levels(0.0, 0.0, 10), [0.0, 0.0]) + assert_allclose(ogs.plot.compute_levels(1e9, 1e9, 10), [1e9, 1e9]) def test_ticklabels(self): def compare(lower, upper, precision, ref_labels, ref_offset=None): - labels, offset = ot.plot.contourplots.get_ticklabels( + labels, offset = ogs.plot.contourplots.get_ticklabels( np.asarray( - ot.plot.compute_levels(lower, upper, n_ticks=precision) + ogs.plot.compute_levels(lower, upper, n_ticks=precision) ) ) assert np.all(labels == ref_labels) @@ -108,24 +108,24 @@ def test_justified_labels(self): def test_missing_data(self): """Test missing data in mesh.""" mesh = pv_examples.load_uniform() - pytest.raises(KeyError, ot.plot.contourf, mesh, "missing_data") + pytest.raises(KeyError, ogs.plot.contourf, mesh, "missing_data") def test_plot_2_d(self): """Test creation of 2D plots.""" - ot.plot.setup.reset() - ot.plot.setup.material_names = { + ogs.plot.setup.reset() + ogs.plot.setup.material_names = { i + 1: f"Layer {i+1}" for i in range(26) } meshseries = examples.load_meshseries_THM_2D_PVD() mesh = meshseries.mesh(1) - mesh.plot_contourf(ot.variables.material_id) - mesh.plot_contourf(ot.variables.temperature) - mesh.plot_contourf(ot.variables.Scalar("pressure_active")) - ot.plot.contourf( - mesh.threshold((1, 3), "MaterialIDs"), ot.variables.velocity + mesh.plot_contourf(ogs.variables.material_id) + mesh.plot_contourf(ogs.variables.temperature) + mesh.plot_contourf(ogs.variables.Scalar("pressure_active")) + ogs.plot.contourf( + mesh.threshold((1, 3), "MaterialIDs"), ogs.variables.velocity ) - fig = mesh.plot_contourf(ot.variables.displacement[0]) - ot.plot.shape_on_top( + fig = mesh.plot_contourf(ogs.variables.displacement[0]) + ogs.plot.shape_on_top( fig.axes[0], mesh, lambda x: min(max(0, 0.1 * (x - 3)), 100) ) plt.close() @@ -139,10 +139,10 @@ def test_diff_plots(self): "temperature_difference" ) for prop in [ - ot.variables.temperature, - ot.variables.displacement, - ot.variables.stress, - ot.variables.stress.von_Mises, + ogs.variables.temperature, + ogs.variables.displacement, + ogs.variables.stress, + ogs.variables.stress.von_Mises, ]: mesh1.difference(mesh0, prop).plot_contourf(prop) plt.close() @@ -152,27 +152,27 @@ def test_user_defined_ax(self): meshseries = examples.load_meshseries_THM_2D_PVD() fig, ax = plt.subplots(3, 1, figsize=(40, 30)) meshseries.mesh(0).plot_contourf( - ot.variables.temperature, fig=fig, ax=ax[0] + ogs.variables.temperature, fig=fig, ax=ax[0] ) meshseries.mesh(1).plot_contourf( - ot.variables.temperature, fig=fig, ax=ax[1] + ogs.variables.temperature, fig=fig, ax=ax[1] ) diff_mesh = meshseries.mesh(0).difference( - meshseries.mesh(1), ot.variables.temperature + meshseries.mesh(1), ogs.variables.temperature ) - diff_mesh.plot_contourf(ot.variables.temperature, fig=fig, ax=ax[2]) + diff_mesh.plot_contourf(ogs.variables.temperature, fig=fig, ax=ax[2]) plt.close() def test_user_defined_ax_two_variables(self): """Test creating plot with subfigures and user provided ax with different values plotted""" meshseries = examples.load_meshseries_THM_2D_PVD() - ot.plot.setup.combined_colorbar = False + ogs.plot.setup.combined_colorbar = False fig, ax = plt.subplots(2, 1, figsize=(40, 20)) meshseries.mesh(0).plot_contourf( - ot.variables.temperature, fig=fig, ax=ax[0] + ogs.variables.temperature, fig=fig, ax=ax[0] ) meshseries.mesh(1).plot_contourf( - ot.variables.displacement, fig=fig, ax=ax[1] + ogs.variables.displacement, fig=fig, ax=ax[1] ) fig.suptitle("Test user defined ax") plt.close() @@ -180,11 +180,11 @@ def test_user_defined_ax_two_variables(self): def test_user_defined_fig(self): """Test creating plot with subfigures and user provided fig""" meshseries = examples.load_meshseries_THM_2D_PVD() - ot.plot.setup.combined_colorbar = False + ogs.plot.setup.combined_colorbar = False fig, ax = plt.subplots(2, 1, figsize=(40, 20)) - ot.plot.contourf( + ogs.plot.contourf( [meshseries.mesh(0), meshseries.mesh(1)], - ot.variables.temperature, + ogs.variables.temperature, fig=fig, ) fig.suptitle("Test user defined fig") @@ -203,7 +203,7 @@ def test_animation(self): meshseries = examples.load_meshseries_THM_2D_PVD() timevalues = np.linspace(0, meshseries.timevalues()[-1], num=3) anim = meshseries.animate( - ot.variables.temperature, + ogs.variables.temperature, timevalues, mesh_func=lambda mesh: mesh.clip("x"), plot_func=lambda ax, t: ax.set_title(str(t)), @@ -215,7 +215,7 @@ def test_save_animation(self): """Test saving of an animation.""" meshseries = examples.load_meshseries_THM_2D_PVD() timevalues = np.linspace(0, meshseries.timevalues()[-1], num=3) - anim = meshseries.animate(ot.variables.temperature, timevalues) + anim = meshseries.animate(ogs.variables.temperature, timevalues) if not utils.save_animation(anim, mkstemp()[1], 5): pytest.skip("Saving animation failed.") plt.close() @@ -223,10 +223,10 @@ def test_save_animation(self): def test_plot_3_d(self): """Test creation of slice plots for 3D mesh.""" mesh = pv_examples.load_uniform() - ot.plot.contourf(mesh.slice((1, 1, 0)), "Spatial Point Data") + ogs.plot.contourf(mesh.slice((1, 1, 0)), "Spatial Point Data") meshes = np.reshape(mesh.slice_along_axis(4, "x"), (2, 2)) - ot.plot.contourf(meshes, "Spatial Point Data") - ot.plot.contourf(mesh.slice([1, -2, 0]), "Spatial Point Data") + ogs.plot.contourf(meshes, "Spatial Point Data") + ogs.plot.contourf(mesh.slice([1, -2, 0]), "Spatial Point Data") plt.close() def test_streamlines(self): @@ -238,8 +238,8 @@ def test_streamlines(self): for axis in ["x", "y", "z", [1, 1, 0]]: ax: plt.Axes fig, ax = plt.subplots() - i_grid, j_grid, u, v, lw = ot.plot.vectorplots._vectorfield( - mesh.slice(axis), ot.variables.velocity + i_grid, j_grid, u, v, lw = ogs.plot.vectorplots._vectorfield( + mesh.slice(axis), ogs.variables.velocity ) for vals in [i_grid, j_grid, u, v, lw]: assert not np.all(np.isnan(vals)) @@ -251,13 +251,13 @@ def test_streamlines(self): def test_xdmf(self): """Test creation of 2D plots from xdmf data.""" mesh = examples.load_meshseries_CT_2D_XDMF().mesh(0) - mesh.plot_contourf(ot.variables.saturation) + mesh.plot_contourf(ogs.variables.saturation) plt.close() def test_xdmf_with_slices(self): """Test creation of 2D plots from xdmf data.""" mesh = examples.load_meshseries_HT_2D_XDMF().mesh(0) - mesh.plot_contourf(ot.variables.pressure) + mesh.plot_contourf(ogs.variables.pressure) plt.close() def test_lineplot(self): @@ -287,7 +287,7 @@ def test_plot_profile(self): ms_CT = examples.load_meshseries_CT_2D_XDMF() profile_CT = np.array([[47.0, 1.17, 72.0], [-4.5, 1.17, -59.0]]) fig, ax = ms_CT.mesh(11).plot_linesample_contourf( - ot.variables.saturation, + ogs.variables.saturation, profile_CT, resolution=100, plot_nodal_pts=True, diff --git a/tests/test_studies_convergence.py b/tests/test_studies_convergence.py index 9c719509..200b6d25 100644 --- a/tests/test_studies_convergence.py +++ b/tests/test_studies_convergence.py @@ -9,7 +9,7 @@ from ogstools.examples import analytical_diffusion, prj_steady_state_diffusion from ogstools.meshlib import MeshSeries, gmsh_meshing from ogstools.msh2vtu import msh2vtu -from ogstools.ogs6py import ogs +from ogstools.ogs6py import Project from ogstools.studies import convergence from ogstools.variables import Scalar @@ -29,9 +29,9 @@ def test_steady_state_diffusion(self): out_name=msh_path, ) msh2vtu(filename=msh_path, output_path=temp_dir, log_level="ERROR") - model = ogs.OGS( - PROJECT_FILE=temp_dir / "default.prj", - INPUT_FILE=prj_steady_state_diffusion, + model = Project( + output_file=temp_dir / "default.prj", + input_file=prj_steady_state_diffusion, ) prefix = "steady_state_diffusion_" + str(n_edge_cells) model.replace_text(prefix, ".//prefix") From 6b0d1caed9965d4692b711158297834d2dbc6a9b Mon Sep 17 00:00:00 2001 From: FZill Date: Fri, 6 Sep 2024 11:54:32 +0200 Subject: [PATCH 2/2] [test] shapemeshing test use np.isclose --- docs/examples/howto_prjfile/plot_creation.py | 7 ++-- tests/test_shapefile_meshing.py | 36 ++++++++++---------- 2 files changed, 20 insertions(+), 23 deletions(-) diff --git a/docs/examples/howto_prjfile/plot_creation.py b/docs/examples/howto_prjfile/plot_creation.py index 3fc0c0f9..795eab64 100644 --- a/docs/examples/howto_prjfile/plot_creation.py +++ b/docs/examples/howto_prjfile/plot_creation.py @@ -12,14 +12,11 @@ # %% # Initialize the ogs6py object: -import tempfile -from pathlib import Path import ogstools as ogs +from ogstools.definitions import EXAMPLES_DIR -prj = ogs.Project( - output_file=Path(tempfile.mkdtemp) / "prj/simple_mechanics.prj" -) +prj = ogs.Project(output_file=EXAMPLES_DIR / "prj" / "mechanics_new.prj") # %% # Define geometry and/or meshes: diff --git a/tests/test_shapefile_meshing.py b/tests/test_shapefile_meshing.py index 4822e1d2..83d78da7 100644 --- a/tests/test_shapefile_meshing.py +++ b/tests/test_shapefile_meshing.py @@ -1,8 +1,10 @@ import subprocess from tempfile import mkdtemp -import ogstools.meshlib as ml +import numpy as np + from ogstools.examples import circle_shapefile, test_shapefile +from ogstools.meshlib import Mesh, read_shape def test_cli(): @@ -15,18 +17,16 @@ def test_cli(): class TestShapeFileMeshing: def test_default(self): - pyvista_mesh = ml.read_shape( - test_shapefile - ) # simplify_false, mesh_generator_triangle - assert pyvista_mesh.n_points > 233000 - assert pyvista_mesh.n_points < 234000 - assert pyvista_mesh.n_cells > 344000 - assert pyvista_mesh.n_points < 345000 + # simplify_false, mesh_generator_triangle + pyvista_mesh = read_shape(test_shapefile) + + assert np.isclose(pyvista_mesh.n_points, 233465, rtol=0.05) + assert np.isclose(pyvista_mesh.n_cells, 344431, rtol=0.05) # Same for simplified mesh. def test_simplify(self): - mesh_simplify = ml.read_shape(test_shapefile, simplify=True) - mesh_orignal = ml.read_shape(test_shapefile, simplify=False) + mesh_simplify = read_shape(test_shapefile, simplify=True) + mesh_orignal = read_shape(test_shapefile, simplify=False) assert mesh_simplify.n_points > 0 assert mesh_simplify.n_cells > 0 @@ -34,10 +34,10 @@ def test_simplify(self): assert mesh_simplify.n_points < mesh_orignal.n_points assert mesh_simplify.n_cells < mesh_orignal.n_cells - mesh_simplify_finer = ml.read_shape( + mesh_simplify_finer = read_shape( test_shapefile, simplify=True, cellsize=2000 ) - mesh_simplify_coarser = ml.read_shape( + mesh_simplify_coarser = read_shape( test_shapefile, simplify=True, cellsize=10000 ) @@ -47,11 +47,11 @@ def test_simplify(self): assert mesh_simplify_coarser.n_points < mesh_simplify.n_points assert mesh_simplify.n_points < mesh_simplify_finer.n_points - def test_simpify_gmsh(self): - mesh_simplify = ml.read_shape( + def test_simplify_gmsh(self): + mesh_simplify = read_shape( circle_shapefile, simplify=True, mesh_generator="gmsh" ) - mesh_original = ml.read_shape( + mesh_original = read_shape( circle_shapefile, simplify=False, mesh_generator="gmsh" ) @@ -59,9 +59,9 @@ def test_simpify_gmsh(self): assert mesh_simplify.n_cells < mesh_original.n_cells def test_meshclass_reading(self): - ogs_mesh = ml.Mesh.read(circle_shapefile) - ogs_mesh_special = ml.Mesh.read_shape(circle_shapefile) - pyvista_mesh = ml.read_shape(circle_shapefile) + ogs_mesh = Mesh.read(circle_shapefile) + ogs_mesh_special = Mesh.read_shape(circle_shapefile) + pyvista_mesh = read_shape(circle_shapefile) assert pyvista_mesh.n_points == ogs_mesh.n_points assert pyvista_mesh.n_cells == ogs_mesh.n_cells assert pyvista_mesh.n_points == ogs_mesh_special.n_points