Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from matplotlib.ticker import FormatStrFormatter, MaxNLocator

from core.object_components import SimulationResults
from core.utility.figures import figure_and_axes, finish_figure
from core.simulation_components.simulation_visualization.material_preview import ( # noqa: F401 (re-export)
plot_builder_materials,
)
Expand Down Expand Up @@ -636,7 +637,9 @@ def plot_cross_section_2D(
cmap: str = "coolwarm",
n_contours: int = 15,
resolution: int = 200,
) -> None:
axes: Optional[Sequence[plt.Axes]] = None,
show: bool = True,
) -> Tuple[plt.Figure, Sequence[plt.Axes]]:
"""
Slice var_name at two time steps on the same plane and plot them side by
side with matplotlib -- filled contours plus contour lines, sharing one
Expand Down Expand Up @@ -664,6 +667,10 @@ def plot_cross_section_2D(
T_bottom]-type background range, so a real but modest change can still
be subtle here -- see plot_cross_section_difference_2D for a version
that isolates just the change itself.

axes: two matplotlib axes (e.g. two subplots of a larger figure) to draw
the panels into instead of a new figure. show=False returns without
showing, so more can be added. Returns (fig, axes).
"""
times = sorted(sim.nodes_by_time.keys())
if not times:
Expand All @@ -686,7 +693,12 @@ def plot_cross_section_2D(
vmax = float(np.nanmax([np.nanmax(Za), np.nanmax(Zb)]))
levels = np.linspace(vmin, vmax, n_contours)

fig, axes = plt.subplots(1, 2, figsize=(12, 5), sharex=True, sharey=True)
if axes is None:
fig, axes = plt.subplots(1, 2, figsize=(12, 5), sharex=True, sharey=True)
else:
if len(axes) != 2:
raise ValueError(f"axes must be two axes, one per time step; got {len(axes)}.")
fig = axes[0].figure
last_cf = None
for ax, Z, t in zip(axes, (Za, Zb), (time_a, time_b)):
last_cf = ax.contourf(UG, VG, Z, levels=levels, cmap=cmap, vmin=vmin, vmax=vmax)
Expand All @@ -699,7 +711,9 @@ def plot_cross_section_2D(

fig.colorbar(last_cf, ax=axes, orientation="vertical", label=_variable_label(var_name), fraction=0.046, pad=0.04)
fig.suptitle(f"{_variable_label(var_name)} cross-section (origin={_format_point(origin)}, normal={_format_point(normal)}): initial vs final")
plt.show()
if show:
plt.show()
return fig, axes


def plot_cross_section_difference_2D(
Expand All @@ -712,7 +726,9 @@ def plot_cross_section_difference_2D(
cmap: str = "RdBu_r",
n_contours: int = 15,
resolution: int = 200,
) -> None:
ax: Optional[plt.Axes] = None,
show: bool = True,
) -> Tuple[plt.Figure, plt.Axes]:
"""
Single-panel 2D cross-section of value(time_b) - value(time_a) (default:
first/last saved step), diverging colormap symmetric around zero. Unlike
Expand All @@ -722,6 +738,9 @@ def plot_cross_section_difference_2D(
background out entirely and shows only what actually moved, so the
change's own spatial pattern (e.g. tracking a fold/unconformity) is not
competing visually with the dominant vertical gradient.

ax draws into existing axes instead of a new figure; show=False returns
without showing. Returns (fig, ax).
"""
times = sorted(sim.nodes_by_time.keys())
if not times:
Expand All @@ -746,7 +765,7 @@ def plot_cross_section_difference_2D(
max_abs = 1.0 # degenerate all-zero diff -- avoid a zero-width color range
levels = np.linspace(-max_abs, max_abs, n_contours)

fig, ax = plt.subplots(figsize=(7, 5))
fig, ax, own_figure = figure_and_axes(ax, figsize=(7, 5))
cf = ax.contourf(UG, VG, Z, levels=levels, cmap=cmap, vmin=-max_abs, vmax=max_abs)
cs = ax.contour(UG, VG, Z, levels=levels, colors="k", linewidths=0.5)
ax.clabel(cs, inline=True, fontsize=7, fmt="%.1f")
Expand All @@ -755,7 +774,8 @@ def plot_cross_section_difference_2D(
ax.set_aspect("equal")
fig.colorbar(cf, ax=ax, orientation="vertical", label=f"Δ {_variable_label(var_name)}", fraction=0.046, pad=0.04)
fig.suptitle(f"Δ {_variable_label(var_name)} cross-section (origin={_format_point(origin)}, normal={_format_point(normal)}): step {_time_step_index(sim, time_a)} -> step {_time_step_index(sim, time_b)}")
plt.show()
finish_figure(fig, own_figure, show, tight=False)
return fig, ax


# ----------------------------------------------------------------------
Expand All @@ -773,11 +793,16 @@ def plot_variable_along_line(
p0: Tuple[float, float, float],
p1: Tuple[float, float, float],
n_samples: int = 200,
) -> None:
ax: Optional[plt.Axes] = None,
show: bool = True,
) -> Tuple[plt.Figure, plt.Axes]:
"""
Sample var_name along the straight line from p0 to p1 at one time step
and plot it against distance along the line (via PyVista's own
pv.Line(...).sample(grid), which linearly interpolates from the mesh).

ax draws into existing axes (e.g. to compare several lines or time steps
in one plot); show=False returns without showing. Returns (fig, ax).
"""
_validate_saved_time(sim, time, "time")
var_name = _resolve_var_name(sim, time, var_name)
Expand All @@ -801,14 +826,14 @@ def plot_variable_along_line(
values = np.where(valid.reshape((-1,) + (1,) * (values.ndim - 1)), values, np.nan)
distances = sampled["Distance"]

plt.figure(figsize=(7, 4))
plt.plot(distances, values, "-k")
plt.xlabel("Distance along line")
plt.ylabel(_variable_label(var_name))
plt.title(f"{_variable_label(var_name)} along line at time step {_time_step_index(sim, time)}")
plt.grid(True)
plt.tight_layout()
plt.show()
fig, ax, own_figure = figure_and_axes(ax, figsize=(7, 4))
ax.plot(distances, values, "-k")
ax.set_xlabel("Distance along line")
ax.set_ylabel(_variable_label(var_name))
ax.set_title(f"{_variable_label(var_name)} along line at time step {_time_step_index(sim, time)}")
ax.grid(True)
finish_figure(fig, own_figure, show)
return fig, ax


def _sample_point_on_mesh(
Expand Down Expand Up @@ -862,12 +887,17 @@ def plot_variable_time_series(
decimals: int = 3,
time_step_start: Optional[int] = None,
time_step_end: Optional[int] = None,
) -> None:
ax: Optional[plt.Axes] = None,
Comment thread
javoha marked this conversation as resolved.
Resolved
show: bool = True,
) -> Tuple[plt.Figure, plt.Axes]:
"""
Sample var_name at a single point across every saved time step and plot
the time series. A point outside the mesh's bounds at a given step is
plotted as a gap (NaN) rather than raising, so one bad step doesn't
prevent seeing the rest of the series.

ax draws into existing axes (e.g. to compare several points in one plot);
show=False returns without showing. Returns (fig, ax).
"""
times = sorted(sim.nodes_by_time.keys())
if not times:
Expand Down Expand Up @@ -914,13 +944,13 @@ def plot_variable_time_series(
if np.all(np.isnan(values)):
raise ValueError(f"Point {_format_point(point)} lies outside the mesh ({_format_bounds(mesh.bounds)}).")

fig, ax = plt.subplots(figsize=(7, 4))
fig, ax, own_figure = figure_and_axes(ax, figsize=(7, 4))
ax.plot(range(start, end + 1), values, "-o", color="tab:red")
ax.set_xlabel("Time step")
ax.set_ylabel(_variable_label(var_name))
ax.set_title(f"{_variable_label(var_name)} at point {_format_point(point)} over time steps")
ax.grid(True)
ax.xaxis.set_major_locator(MaxNLocator(integer=True)) # steps are whole numbers
ax.yaxis.set_major_formatter(FormatStrFormatter(f"%.{decimals}f"))
plt.tight_layout()
plt.show()
finish_figure(fig, own_figure, show)
return fig, ax
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
OctreeGrid,
)
from core.structural_modeling_components.structural_modeling_utility.surface_mesh_gradients import normalize_vectors
from core.utility.figures import figure_and_axes, finish_figure
from core.structural_modeling_components.structural_objects.structural_objects import (
FaultFrame,
StructuralFrame,
Expand Down Expand Up @@ -528,7 +529,9 @@ def plot_structural_model_2D(
show_input_data: bool = True,
show_grid: bool = False,
title_suffix: str = "",
) -> None:
ax: Optional[plt.Axes] = None,
show: bool = True,
) -> Tuple[plt.Figure, plt.Axes]:
"""
2D slice plot of a structural model showing lithology block, scalar contours, and input data.

Expand All @@ -552,6 +555,17 @@ def plot_structural_model_2D(
grid, cells of different sizes on an octree.
title_suffix : str, default ""
Optional string appended to the plot title.
ax : matplotlib Axes, optional
Draw into these axes (e.g. one subplot of a larger figure) instead of
a new figure. The caller then arranges and shows the figure.
show : bool, default True
Show the figure. Pass False to add to the plot before showing it,
e.g. an image or extra lines drawn into the returned axes.

Returns
-------
(fig, ax)
The figure and the axes the section was drawn into.
"""
warnings.simplefilter("always", UserWarning)

Expand Down Expand Up @@ -591,7 +605,7 @@ def plot_structural_model_2D(
)
x_coords, y_coords = np.meshgrid(x, y, indexing='ij')

fig, ax = plt.subplots(figsize=(10, 6))
fig, ax, own_figure = figure_and_axes(ax, figsize=(10, 6))

# ---- lithology (optional) ----
if show_result:
Expand Down Expand Up @@ -703,8 +717,8 @@ def plot_structural_model_2D(
ax.set_xlim(extent[0], extent[1])
ax.set_ylim(extent[2], extent[3])

plt.tight_layout()
plt.show()
finish_figure(fig, own_figure, show)
return fig, ax


def plot_fault_model_3D(
Expand Down Expand Up @@ -997,7 +1011,9 @@ def plot_fault_model_2D(
show_input_data: bool = True,
show_fault_contours: bool = True,
show_grid: bool = False,
) -> None:
ax: Optional[plt.Axes] = None,
show: bool = True,
) -> Tuple[plt.Figure, plt.Axes]:
"""
2D slice plot for a FaultFrame.

Expand All @@ -1014,6 +1030,10 @@ def plot_fault_model_2D(
Extent is computed from the cell-center coordinates with half-cell padding,
so imshow/contour align properly. On an octree, ``index`` and the centers
refer to the finest resolution.

``ax`` draws into existing axes (e.g. a subplot) instead of a new figure;
``show=False`` returns without showing, so more can be added to the plot.
Returns ``(fig, ax)``.
"""

assert axis in ("x", "y", "z"), "Axis must be 'x', 'y', or 'z'."
Expand Down Expand Up @@ -1065,7 +1085,7 @@ def plot_fault_model_2D(
UserWarning,
)

fig, ax = plt.subplots(figsize=(10, 6))
fig, ax, own_figure = figure_and_axes(ax, figsize=(10, 6))

# ---------------------------
# RESULTS: domain map
Expand All @@ -1091,7 +1111,7 @@ def plot_fault_model_2D(
norm=norm,
alpha=1.0,
)
cbar = plt.colorbar(im, ax=ax, ticks=domain_values)
cbar = fig.colorbar(im, ax=ax, ticks=domain_values)
cbar.set_label("Fault Domain")

if show_grid:
Expand Down Expand Up @@ -1198,5 +1218,5 @@ def plot_fault_model_2D(
ax.set_xlim(extent[0], extent[1])
ax.set_ylim(extent[2], extent[3])

plt.tight_layout()
plt.show()
finish_figure(fig, own_figure, show)
return fig, ax
26 changes: 26 additions & 0 deletions core/utility/figures.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
"""Shared figure handling of the 2D (matplotlib) plots.

Every 2D plot can draw into existing axes (``ax``, e.g. one subplot of a
larger figure) and can skip showing the figure (``show=False``), so callers
can add to it, such as an outcrop photo below a model section. The plots
return their figure and axes.
"""
from typing import Optional, Tuple

import matplotlib.pyplot as plt


def figure_and_axes(ax: Optional[plt.Axes], figsize: Tuple[float, float]) -> Tuple[plt.Figure, plt.Axes, bool]:
"""The given axes and their figure, or a new figure; the flag says whether the figure is new."""
if ax is None:
fig, ax = plt.subplots(figsize=figsize)
return fig, ax, True
return ax.figure, ax, False


def finish_figure(fig: plt.Figure, own_figure: bool, show: bool, tight: bool = True) -> None:
"""Lay out a figure the plot created itself (a caller's figure is the caller's to arrange) and show it."""
if own_figure and tight:
fig.tight_layout()
if show:
plt.show()
13 changes: 13 additions & 0 deletions docs/components/simulation/Manual_simulation.md
Original file line number Diff line number Diff line change
Expand Up @@ -1091,6 +1091,17 @@ The relevant parameters in the codebase are:
- **`n_contours`** *(default: `15`)*: Number of contour levels.
- **`resolution`** *(default: `200`)*: Resolution of the interpolated
2D grid used for plotting.
- **`axes`** *(optional, Python only)*: Two matplotlib axes to draw the
two panels into, e.g. subplots of a larger figure. Default `None`
(a new figure).
- **`show`** *(optional, Python only, default: `True`)*: Show the
figure. Set `False` to add to the plot first.

The function returns `(fig, axes)`. All 2D simulation plots
(`plot_cross_section_difference_2D`, `plot_variable_along_line`,
`plot_variable_time_series`) take `ax` (one axes) and `show` the same
way and return `(fig, ax)`, so several of them can share one figure, for
example temperature logs of several time steps in one plot.

The Workbench inspector shows axis-aligned sections, like the structural
2D plots: choose the **`axis`** (x, y or z) and a **`position`** along it
Expand Down Expand Up @@ -1263,6 +1274,8 @@ The relevant parameters are:
- **`n_contours`** *(default: `15`)*: Number of contour levels.
- **`resolution`** *(default: `200`)*: Resolution of the
interpolated 2D grid.
- **`ax`**, **`show`** *(optional)*: Draw into existing axes / skip
showing, as for `plot_cross_section_2D`; returns `(fig, ax)`.

Example call in the codebase:

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -335,11 +335,25 @@ plot_structural_model_3D(structural_model_result.structural_frame, mesh_type="ma
- **`show_input_data`** *(optional)*: Overlay input surface points and orientation arrows. Default `True`.
- **`show_grid`** *(optional)*: Outline the grid cells the slice cuts — uniform voxels on a Regular Grid, cells of different sizes on an Octree Grid. Default `False`.
- **`title_suffix`** *(optional)*: Text appended to the plot title. Default `""`.
- **`ax`** *(optional, Python only)*: Matplotlib axes to draw into, e.g. one subplot of a larger figure, instead of a new figure. You then arrange and show the figure yourself. Default `None`.
- **`show`** *(optional, Python only)*: Show the figure. Set `False` to add to the plot first. Default `True`.

The Workbench version exposes `axis` (a choice of x, y or z), `index` (empty = the mid-point) and `show_grid`; the other options keep their defaults.
The function returns the figure and the axes, `(fig, ax)`. The Workbench version exposes `axis` (a choice of x, y or z), `index` (empty = the mid-point) and `show_grid`; the other options keep their defaults.

```python
plot_structural_model_2D(structural_model_result.structural_frame, axis="x", index=20)

# Draw the section on top of an outcrop photo (image extent in model coordinates)
fig, ax = plot_structural_model_2D(structural_model_result.structural_frame, show=False)
ax.imshow(outcrop_image, extent=[0, 50, 0, 35], alpha=0.5)
plt.show()

# Compare two models side by side
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 5))
plot_structural_model_2D(result_rbf.structural_frame, ax=ax1, show=False)
plot_structural_model_2D(result_kriging.structural_frame, ax=ax2, show=False)
plt.tight_layout()
plt.show()
```

### Inspect the fault model
Expand Down Expand Up @@ -383,6 +397,7 @@ plot_fault_model_3D(fault_model_result.fault_frame, show_domain_map=True, domain
- **`show_input_data`** *(optional)*: Plot input surface points, if available. Default `True`.
- **`show_fault_contours`** *(optional)*: Overlay fault isolines. Default `True`.
- **`show_grid`** *(optional)*: Outline the grid cells the slice cuts, as in `plot_structural_model_2D`. Default `False`.
- **`ax`**, **`show`** *(optional, Python only)*: As in `plot_structural_model_2D`; the function returns `(fig, ax)`.

The Workbench version exposes `axis` (a choice of x, y or z), `index` (empty = the mid-point) and `show_grid`, as in `Plot Model Result 2D`.

Expand Down
Loading