"""Iso surface helpers.
Example usage:
.. code-block:: python
>>> import os
>>> import fieldview as fv
>>> data_dir = os.path.join(fv.home, "examples", "f18")
>>> ds = fv.data.load_plot3d(
... os.path.join(data_dir, "f18i9b_g_bin"),
... os.path.join(data_dir, "f18i9b_q_bin"),
... )
>>> iso = fv.vis.create_iso(ds, iso_func="Density (Q1)")
"""
from __future__ import annotations
import os
from collections.abc import Mapping
from typing import cast
from .. import _core
from .. import constant
from .._core_utils import _core_call
from .._base import (
SurfaceBase,
_flatten_colormap,
_flatten_legend_options,
_flatten_scalar_minmax,
_flatten_vector_options,
_prefix_payload,
_surface_coloring_mode,
)
from ..data import (
Dataset,
IntegrationResult,
_integrate_partial_surface,
_resolve_dataset_or_current,
)
from ..exceptions import InvalidArgumentError, InvalidDatasetError
from ..utils import (
Colormap,
CuttingPlane,
Legend,
Range,
RangedValue,
ScalarMinMax,
VectorOptions,
_coerce_float,
_coerce_pathlike_str,
_bind_ranged_value,
_normalize_ranged_value_from_values,
)
__all__: list[str] = ["Iso", "create_iso"]
def _range_from_iso_state(state: dict[str, object]) -> RangedValue:
return _normalize_ranged_value_from_values(
min_value=_coerce_float(state["min"]),
max_value=_coerce_float(state["max"]),
abs_min=None
if state.get("abs_min") is None
else _coerce_float(state["abs_min"]),
abs_max=None
if state.get("abs_max") is None
else _coerce_float(state["abs_max"]),
current=_coerce_float(state["current"]),
)
def _make_iso_value_range(parent: "Iso") -> RangedValue:
def get_state() -> dict[str, object]:
iso_value = parent._state().get("iso_value")
if isinstance(iso_value, dict):
return cast(dict[str, object], iso_value)
raise RuntimeError("iso surface state is missing iso_value")
def set_state(**kwargs: object) -> None:
_core_call(_core.iso_surf_set_iso_value, parent._phigs_obj, **kwargs)
return _bind_ranged_value(
get_state=get_state,
set_state=set_state,
cast=_coerce_float,
)
[docs]
class Iso(SurfaceBase):
"""Iso surface wrapper.
.. code-block:: python
>>> import os
>>> import fieldview as fv
>>> data_dir = os.path.join(fv.home, "examples", "f18")
>>> ds = fv.data.load_plot3d(
... os.path.join(data_dir, "f18i9b_g_bin"),
... os.path.join(data_dir, "f18i9b_q_bin"),
... )
>>> iso = fv.vis.create_iso(ds, iso_func="Density (Q1)")
>>> iso.coloring = fv.constant.Coloring.SCALAR
>>> iso.iso_value.value = 0.8
"""
_core_prefix = "iso_surf"
__slots__ = ("_dataset", "_iso_value")
def __init__(
self, phigs_obj: int, dataset_id: int, dataset: Dataset | None = None
) -> None:
"""Create an iso-surface wrapper around an existing host object.
Args:
phigs_obj: Host PHIGS object identifier for the iso surface.
dataset_id: Host dataset identifier backing the surface.
dataset: Optional live :class:`Dataset` wrapper for function lookup
and validation.
"""
super().__init__(phigs_obj, dataset_id)
self._dataset = dataset
self._iso_value = _make_iso_value_range(self)
def _require_dataset(self) -> Dataset:
dataset = self._dataset
if dataset is None:
raise InvalidDatasetError("iso surface is missing a dataset reference")
dataset._ensure_valid()
return dataset
def _lookup_function_id(
self, name: str, mapping: dict[str, int], label: str
) -> int:
if not isinstance(name, str):
raise InvalidArgumentError(f"{label} function name must be a string")
needle = name.strip()
if not needle:
raise InvalidArgumentError(f"{label} function name cannot be empty")
needle_lower = needle.lower()
for func_name, func_id in mapping.items():
if func_name.lower() == needle_lower:
return func_id
raise InvalidArgumentError(f"{label} function not found: {needle}")
[docs]
def integrate_partial_surface(
self,
point: object,
tolerance: float | None = None,
) -> IntegrationResult | None:
"""Integrate the connected partial region containing *point*.
Returns ``None`` when *point* does not isolate a partial region on the
current iso surface.
Args:
point: XYZ point used to identify the connected partial region.
tolerance: Optional coordinate tolerance used while locating the
partial region.
Example usage:
.. code-block:: python
>>> import os
>>> import fieldview as fv
>>> data_dir = os.path.join(fv.home, "examples", "f18")
>>> ds = fv.data.load_plot3d(
... os.path.join(data_dir, "f18i9b_g_bin"),
... os.path.join(data_dir, "f18i9b_q_bin"),
... )
>>> probe = fv.data.probe_ijk((2, 3, 4), grid=1, dataset=ds)
>>> iso = fv.vis.create_iso(ds, iso_func=probe.scalar.func)
>>> iso.scalar_func = probe.scalar.func
>>> iso.iso_value.value = probe.scalar.value
>>> result = iso.integrate_partial_surface(tuple(probe.point))
"""
return _integrate_partial_surface(self, point, tolerance)
@property
def iso_value(self) -> RangedValue:
"""`RangedValue`: Iso value range controller.
Example usage:
.. code-block:: python
>>> iso = fv.vis.create_iso(ds, iso_func=ds.scalar_functions[0])
>>> iso.iso_value.value = 0.8
"""
return self._iso_value
@property
def iso_func(self) -> str | CuttingPlane | None:
"""`str | CuttingPlane | None`: Iso function selection.
Example usage:
.. code-block:: python
>>> iso = fv.vis.create_iso(ds, iso_func=ds.scalar_functions[0])
>>> iso.iso_func = ds.scalar_functions[1]
"""
name = self._state().get("iso_func", "")
if not name:
return None
if str(name).strip().lower() == "cutting plane":
return self.cutting_plane
return str(name)
@iso_func.setter
def iso_func(self, value: str | CuttingPlane | dict[str, object]) -> None:
if isinstance(value, str):
dataset = self._require_dataset()
func_id = self._lookup_function_id(
value, dataset._scalar_function_ids, "iso"
)
_core_call(_core.iso_surf_set_iso_func, self._phigs_obj, func_id)
return
payload = value.to_payload() if isinstance(value, CuttingPlane) else dict(value)
_core_call(_core.iso_surf_set_cutting_plane, self._phigs_obj, payload)
@property
def cutting_plane(self) -> CuttingPlane:
"""`CuttingPlane`: Current cutting-plane definition.
Example usage:
.. code-block:: python
>>> iso = fv.vis.create_iso(ds, iso_func=ds.scalar_functions[0])
>>> iso.cutting_plane = fv.utils.CuttingPlane.point_and_normal((0, 0, 0), (1, 0, 0))
"""
payload = self._state().get("cutting_plane")
if isinstance(payload, dict):
return CuttingPlane.from_payload(cast(dict[str, object], payload))
raise InvalidArgumentError("iso surface is not using a cutting plane")
@cutting_plane.setter
def cutting_plane(self, value: CuttingPlane | dict[str, object]) -> None:
payload = value.to_payload() if isinstance(value, CuttingPlane) else dict(value)
_core_call(_core.iso_surf_set_cutting_plane, self._phigs_obj, payload)
@property
def scalar_func(self) -> str | None:
"""`str | None`: Selected scalar function name.
Example usage:
.. code-block:: python
>>> iso = fv.vis.create_iso(ds, iso_func=ds.scalar_functions[0])
>>> iso.scalar_func = ds.scalar_functions[0]
"""
name = self._state().get("scalar_func", "")
return str(name) if name else None
@scalar_func.setter
def scalar_func(self, value: str) -> None:
dataset = self._require_dataset()
func_id = self._lookup_function_id(
value, dataset._scalar_function_ids, "scalar"
)
_core_call(_core.iso_surf_set_scalar_func, self._phigs_obj, func_id)
@property
def vector_func(self) -> str | None:
"""`str | None`: Selected vector function name.
Example usage:
.. code-block:: python
>>> iso = fv.vis.create_iso(ds, iso_func=ds.scalar_functions[0])
>>> iso.vector_func = ds.vector_functions[0]
"""
name = self._state().get("vector_func", "")
return str(name) if name else None
@vector_func.setter
def vector_func(self, value: str) -> None:
dataset = self._require_dataset()
func_id = self._lookup_function_id(
value, dataset._vector_function_ids, "vector"
)
_core_call(_core.iso_surf_set_vector_func, self._phigs_obj, func_id)
@property
def threshold_func(self) -> str | None:
"""`str | None`: Selected threshold function name.
Example usage:
.. code-block:: python
>>> iso = fv.vis.create_iso(ds, iso_func=ds.scalar_functions[0])
>>> iso.threshold_func = ds.scalar_functions[0]
"""
name = self._state().get("threshold_func", "")
return str(name) if name else None
@threshold_func.setter
def threshold_func(self, value: str) -> None:
dataset = self._require_dataset()
func_id = self._lookup_function_id(
value, dataset._scalar_function_ids, "threshold"
)
_core_call(_core.iso_surf_set_threshold_func, self._phigs_obj, func_id)
@property
def threshold(self) -> bool:
"""`bool`: Threshold enabled state.
Example usage:
.. code-block:: python
>>> iso = fv.vis.create_iso(ds, iso_func=ds.scalar_functions[0])
>>> iso.threshold = True
"""
return bool(self._state().get("threshold", False))
@threshold.setter
def threshold(self, value: bool) -> None:
_core_call(_core.iso_surf_set_threshold, self._phigs_obj, bool(value))
@property
def threshold_range(self) -> Range:
"""`Range`: Threshold min/max range.
Example usage:
.. code-block:: python
>>> iso = fv.vis.create_iso(ds, iso_func=ds.scalar_functions[0])
>>> iso.threshold_range = fv.Range(min=0.2, max=0.8)
"""
state = self._state()
return Range(
min=_coerce_float(state.get("threshold_min", 0.0)),
max=_coerce_float(state.get("threshold_max", 0.0)),
)
@threshold_range.setter
def threshold_range(self, value: Range) -> None:
if not isinstance(value, Range):
raise InvalidArgumentError("threshold_range must be a Range")
if value.min is None or value.max is None:
raise InvalidArgumentError("threshold_range must define both min and max")
if value.min > value.max:
raise InvalidArgumentError("threshold_range min must be <= max")
_core_call(
_core.iso_surf_set_threshold_range, self._phigs_obj, value.min, value.max
)
@property
def transparency(self) -> float:
"""`float`: Transparency (0.0-1.0).
Example usage:
.. code-block:: python
>>> iso = fv.vis.create_iso(ds, iso_func=ds.scalar_functions[0])
>>> iso.transparency = 0.35
"""
return _coerce_float(self._state().get("transparency", 0.0))
@transparency.setter
def transparency(self, value: float) -> None:
_core_call(_core.iso_surf_set_transparency, self._phigs_obj, float(value))
@property
def contours(self) -> constant.ContourColoring:
"""`ContourColoring`: Contour line coloring.
Example usage:
.. code-block:: python
>>> iso = fv.vis.create_iso(ds, iso_func=ds.scalar_functions[0])
>>> iso.contours = fv.constant.ContourColoring.SCALAR
"""
return constant.ContourColoring(
str(
self._state().get("contours", constant.ContourColoring.NONE.value)
).lower()
)
@contours.setter
def contours(self, value: constant.ContourColoring | str) -> None:
contours = (
value.value if isinstance(value, constant.ContourColoring) else str(value)
)
_core_call(_core.iso_surf_set_contours, self._phigs_obj, contours)
@property
def show_mesh(self) -> bool:
"""`bool`: Mesh overlay visibility.
Example usage:
.. code-block:: python
>>> iso = fv.vis.create_iso(ds, iso_func=ds.scalar_functions[0])
>>> iso.show_mesh = True
"""
return bool(self._state().get("show_mesh", False))
@show_mesh.setter
def show_mesh(self, value: bool) -> None:
_core_call(_core.iso_surf_set_show_mesh, self._phigs_obj, bool(value))
@property
def unrolled(self) -> bool:
"""`bool`: Unrolled display state.
Example usage:
.. code-block:: python
>>> iso = fv.vis.create_iso(ds, iso_func=ds.scalar_functions[0])
>>> iso.unrolled = True
"""
return bool(self._state().get("unrolled", False))
@unrolled.setter
def unrolled(self, value: bool) -> None:
_core_call(_core.iso_surf_set_unrolled, self._phigs_obj, bool(value))
@property
def vector_options(self) -> VectorOptions:
"""`VectorOptions`: Vector display options.
Example usage:
.. code-block:: python
>>> iso = fv.vis.create_iso(ds, iso_func=ds.scalar_functions[0])
>>> opts = iso.vector_options
>>> opts.scale = 1.2
"""
return self._get_vector_options()
@vector_options.setter
def vector_options(self, value: VectorOptions | dict[str, object]) -> None:
self._set_vector_options(value)
@property
def scalar_minmax(self) -> ScalarMinMax:
"""`ScalarMinMax`: Scalar min/max options.
Example usage:
.. code-block:: python
>>> iso = fv.vis.create_iso(ds, iso_func=ds.scalar_functions[0])
>>> smm = iso.scalar_minmax
>>> smm.show = True
"""
return self._get_scalar_minmax()
@scalar_minmax.setter
def scalar_minmax(self, value: ScalarMinMax | dict[str, object]) -> None:
self._set_scalar_minmax(value)
@property
def sweep_steps(self) -> int:
"""`int`: Sweep step count.
Example usage:
.. code-block:: python
>>> iso = fv.vis.create_iso(ds, iso_func=ds.scalar_functions[0])
>>> iso.sweep_steps = 25
"""
steps = self._state().get("sweep_steps")
if steps is None:
return 25
if isinstance(steps, int) and not isinstance(steps, bool):
return steps
raise RuntimeError("iso surface state has invalid sweep_steps")
@sweep_steps.setter
def sweep_steps(self, value: int) -> None:
steps = int(value)
if steps < 1 or steps > 999:
raise InvalidArgumentError("sweep_steps must be in range 1-999")
_core_call(_core.iso_surf_set_sweep_steps, self._phigs_obj, steps)
[docs]
def sweep(
self,
cycles: int = 1,
output_file: str | os.PathLike[str] | None = None,
direction: constant.SweepDirection | None = None,
) -> None:
"""Sweep the iso surface and optionally write frames to a file.
Args:
cycles: Number of sweep cycles to run.
output_file: Optional movie or frame output path.
direction: Optional sweep direction mode.
Example usage:
.. code-block:: python
>>> import os
>>> import fieldview as fv
>>> data_dir = os.path.join(fv.home, "examples", "f18")
>>> ds = fv.data.load_plot3d(
... os.path.join(data_dir, "f18i9b_g_bin"),
... os.path.join(data_dir, "f18i9b_q_bin"),
... )
>>> iso = fv.vis.create_iso(ds, iso_func="Density (Q1)")
>>> iso.sweep(2, "/tmp/iso_sweep.mp4", fv.constant.SweepDirection.BOUNCE)
Notes:
``output_file`` must use ``.png``, ``.mp4``, or ``.avi``.
"""
if not isinstance(cycles, int):
raise InvalidArgumentError("cycles must be an integer")
if cycles <= 0:
raise InvalidArgumentError("cycles must be positive")
direction_value: str | None = None
if direction is not None:
if not isinstance(direction, constant.SweepDirection):
raise InvalidArgumentError(
"direction must be a constant.SweepDirection"
)
direction_value = direction.value
if output_file is None:
if direction_value is None:
_core_call(_core.iso_surf_sweep, self._phigs_obj, cycles)
else:
_core_call(
_core.iso_surf_sweep, self._phigs_obj, cycles, None, direction_value
)
return
output_file = _coerce_pathlike_str(output_file, "output_file")
if not output_file.strip():
raise InvalidArgumentError("output_file cannot be empty")
if direction_value is None:
_core_call(_core.iso_surf_sweep, self._phigs_obj, cycles, output_file)
else:
_core_call(
_core.iso_surf_sweep,
self._phigs_obj,
cycles,
output_file,
direction_value,
)
[docs]
def export(self, filename: str | os.PathLike[str], format: str = "txt") -> None:
"""Export this iso surface to a text file.
Args:
filename: Destination export path.
format: Export format string. Only ``txt`` is currently supported.
Example usage:
.. code-block:: python
>>> import os
>>> import fieldview as fv
>>> data_dir = os.path.join(fv.home, "examples", "f18")
>>> ds = fv.data.load_plot3d(
... os.path.join(data_dir, "f18i9b_g_bin"),
... os.path.join(data_dir, "f18i9b_q_bin"),
... )
>>> iso = fv.vis.create_iso(ds, iso_func="Density (Q1)")
>>> iso.export("/tmp/iso_surface.txt", format="txt")
"""
filename = _coerce_pathlike_str(filename, "filename")
if not filename.strip():
raise InvalidArgumentError("filename cannot be empty")
if not isinstance(format, str):
raise InvalidArgumentError("format must be a string")
fmt = format.strip().lower()
if fmt == "text":
fmt = "txt"
if fmt != "txt":
raise InvalidArgumentError("format must be txt")
_core_call(_core.iso_surf_export, self._phigs_obj, filename, fmt)
[docs]
def modify(
self,
*,
iso_func: str | CuttingPlane | dict[str, object] | None = None,
iso_value: RangedValue | None = None,
cutting_plane: CuttingPlane | dict[str, object] | None = None,
coloring: constant.Coloring | str | None = None,
geometric_color: constant.GeometricColor | int | None = None,
display_type: constant.DisplayType | str | None = None,
line_type: constant.LineType | str | None = None,
contours: constant.ContourColoring | str | None = None,
show_mesh: bool | None = None,
unrolled: bool | None = None,
visibility: bool | None = None,
transparency: float | None = None,
scalar_func: str | None = None,
vector_func: str | None = None,
threshold: bool | None = None,
threshold_func: str | None = None,
threshold_range: Range | None = None,
vector_options: VectorOptions | None = None,
scalar_minmax: ScalarMinMax | None = None,
colormap: Colormap | None = None,
legend: Legend | None = None,
sweep_steps: int | None = None,
) -> None:
"""Modify multiple iso-surface properties atomically.
Args:
iso_func: Iso function name, cutting plane, or cutting-plane
payload dict.
iso_value: Optional iso-value ranged-value controller.
cutting_plane: Optional cutting-plane override.
coloring: Coloring mode for the iso surface.
geometric_color: Geometric color id used when geometric coloring is
active.
display_type: Surface display type.
line_type: Line style used for wireframe-capable display modes.
contours: Contour coloring mode.
show_mesh: Whether the mesh overlay is shown.
unrolled: Whether unrolled display is enabled.
visibility: Whether the iso surface is visible.
transparency: Surface transparency amount.
scalar_func: Scalar function name used for scalar coloring.
vector_func: Vector function name used for vector display modes.
threshold: Whether thresholding is enabled.
threshold_func: Scalar function name used for thresholding.
threshold_range: Threshold value range.
vector_options: Vector display options.
scalar_minmax: Scalar min/max annotation options.
colormap: Scalar colormap options.
legend: Legend options.
sweep_steps: Sweep step count.
Example usage:
.. code-block:: python
>>> import os
>>> import fieldview as fv
>>> data_dir = os.path.join(fv.home, "examples", "f18")
>>> ds = fv.data.load_plot3d(
... os.path.join(data_dir, "f18i9b_g_bin"),
... os.path.join(data_dir, "f18i9b_q_bin"),
... )
>>> iso = fv.vis.create_iso(ds, iso_func="Density (Q1)")
>>> iso.modify(visibility=False, transparency=0.25)
"""
kwargs = {
"iso_func": iso_func,
"iso_value": iso_value,
"cutting_plane": cutting_plane,
"coloring": coloring,
"geometric_color": geometric_color,
"display_type": display_type,
"line_type": line_type,
"contours": contours,
"show_mesh": show_mesh,
"unrolled": unrolled,
"visibility": visibility,
"transparency": transparency,
"scalar_func": scalar_func,
"vector_func": vector_func,
"threshold": threshold,
"threshold_func": threshold_func,
"threshold_range": threshold_range,
"vector_options": vector_options,
"scalar_minmax": scalar_minmax,
"colormap": colormap,
"legend": legend,
"sweep_steps": sweep_steps,
}
if not any(value is not None for value in kwargs.values()):
raise InvalidArgumentError("modify requires at least one property")
payload = self._build_modify_payload(kwargs)
_core_call(_core.iso_surf_modify, self._phigs_obj, payload)
def _build_modify_payload(self, kwargs: Mapping[str, object]) -> dict[str, object]:
payload: dict[str, object] = {}
iso_func = kwargs.get("iso_func")
if iso_func is not None:
if isinstance(iso_func, str):
dataset = self._require_dataset()
payload["iso_func_id"] = self._lookup_function_id(
iso_func, dataset._scalar_function_ids, "iso"
)
elif isinstance(iso_func, CuttingPlane):
payload["cutting_plane"] = iso_func.to_payload()
elif isinstance(iso_func, dict):
payload["cutting_plane"] = dict(cast(dict[str, object], iso_func))
else:
raise InvalidArgumentError(
"iso_func must be a string, CuttingPlane, or dict"
)
iso_value = kwargs.get("iso_value")
if iso_value is not None:
if isinstance(iso_value, RangedValue):
range_payload = iso_value.to_payload()
else:
raise InvalidArgumentError("iso_value must be a RangedValue")
if "min" in range_payload:
payload["iso_value_min"] = float(range_payload["min"])
if "max" in range_payload:
payload["iso_value_max"] = float(range_payload["max"])
if "current" in range_payload:
payload["iso_value_current"] = float(range_payload["current"])
cutting_plane = kwargs.get("cutting_plane")
if cutting_plane is not None:
if isinstance(cutting_plane, CuttingPlane):
payload["cutting_plane"] = cutting_plane.to_payload()
elif isinstance(cutting_plane, dict):
payload["cutting_plane"] = dict(cast(dict[str, object], cutting_plane))
else:
raise InvalidArgumentError(
"cutting_plane must be a CuttingPlane or dict"
)
coloring = kwargs.get("coloring")
if coloring is not None:
mode = _surface_coloring_mode(
cast(constant.Coloring | str, coloring),
surface_name="iso surfaces",
)
payload["coloring"] = mode
geometric_color = kwargs.get("geometric_color")
if geometric_color is not None:
if not isinstance(geometric_color, (constant.GeometricColor, int)):
raise InvalidArgumentError(
"geometric_color must be a constant.GeometricColor or int"
)
payload["geometric_color"] = int(geometric_color)
display_type = kwargs.get("display_type")
if display_type is not None:
payload["display_type"] = (
display_type.value
if isinstance(display_type, constant.DisplayType)
else str(display_type)
)
line_type = kwargs.get("line_type")
if line_type is not None:
payload["line_type"] = (
line_type.value
if isinstance(line_type, constant.LineType)
else str(line_type)
)
contours = kwargs.get("contours")
if contours is not None:
payload["contours"] = (
contours.value
if isinstance(contours, constant.ContourColoring)
else str(contours)
)
show_mesh = kwargs.get("show_mesh")
if show_mesh is not None:
payload["show_mesh"] = bool(show_mesh)
unrolled = kwargs.get("unrolled")
if unrolled is not None:
payload["unrolled"] = bool(unrolled)
visibility = kwargs.get("visibility")
if visibility is not None:
payload["visibility"] = bool(visibility)
transparency = kwargs.get("transparency")
if transparency is not None:
payload["transparency"] = _coerce_float(transparency)
scalar_func = kwargs.get("scalar_func")
if scalar_func is not None:
if not isinstance(scalar_func, str):
raise InvalidArgumentError("scalar_func must be a string")
dataset = self._require_dataset()
payload["scalar_func_id"] = self._lookup_function_id(
scalar_func,
dataset._scalar_function_ids,
"scalar",
)
vector_func = kwargs.get("vector_func")
if vector_func is not None:
if not isinstance(vector_func, str):
raise InvalidArgumentError("vector_func must be a string")
dataset = self._require_dataset()
payload["vector_func_id"] = self._lookup_function_id(
vector_func,
dataset._vector_function_ids,
"vector",
)
threshold = kwargs.get("threshold")
if threshold is not None:
payload["threshold"] = bool(threshold)
threshold_func = kwargs.get("threshold_func")
if threshold_func is not None:
if not isinstance(threshold_func, str):
raise InvalidArgumentError("threshold_func must be a string")
dataset = self._require_dataset()
payload["threshold_func_id"] = self._lookup_function_id(
threshold_func,
dataset._scalar_function_ids,
"threshold",
)
threshold_range = kwargs.get("threshold_range")
if threshold_range is not None:
if not isinstance(threshold_range, Range):
raise InvalidArgumentError("threshold_range must be a Range")
if threshold_range.min is None or threshold_range.max is None:
raise InvalidArgumentError(
"threshold_range must define both min and max"
)
if threshold_range.min > threshold_range.max:
raise InvalidArgumentError("threshold_range min must be <= max")
payload["threshold_min"] = float(threshold_range.min)
payload["threshold_max"] = float(threshold_range.max)
vector_options = kwargs.get("vector_options")
if vector_options is not None:
if isinstance(vector_options, VectorOptions):
payload.update(
_prefix_payload(
"vector_", _flatten_vector_options(vector_options.to_payload())
)
)
elif isinstance(vector_options, dict):
payload.update(
_prefix_payload(
"vector_",
_flatten_vector_options(
cast(dict[str, object], vector_options)
),
)
)
else:
raise InvalidArgumentError(
"vector_options must be a VectorOptions or dict"
)
scalar_minmax = kwargs.get("scalar_minmax")
if scalar_minmax is not None:
scalar_minmax_payload: dict[str, object]
scalar_minmax_show: bool | None
if isinstance(scalar_minmax, ScalarMinMax):
scalar_minmax_payload = scalar_minmax.to_payload()
scalar_minmax_show = scalar_minmax.show
elif isinstance(scalar_minmax, dict):
scalar_minmax_payload, scalar_minmax_show = _flatten_scalar_minmax(
cast(dict[str, object], scalar_minmax)
)
else:
raise InvalidArgumentError(
"scalar_minmax must be a ScalarMinMax or dict"
)
payload.update(_prefix_payload("scalar_minmax_", scalar_minmax_payload))
if scalar_minmax_show is not None:
payload["scalar_minmax_show"] = bool(scalar_minmax_show)
colormap = kwargs.get("colormap")
if colormap is not None:
if isinstance(colormap, Colormap):
payload.update(
_prefix_payload(
"scalar_colormap_", _flatten_colormap(colormap.to_payload())
)
)
elif isinstance(colormap, dict):
payload.update(
_prefix_payload(
"scalar_colormap_",
_flatten_colormap(cast(dict[str, object], colormap)),
)
)
else:
raise InvalidArgumentError("colormap must be a Colormap or dict")
legend = kwargs.get("legend")
if legend is not None:
if isinstance(legend, Legend):
payload.update(
_prefix_payload(
"legend_", _flatten_legend_options(legend.to_payload())
)
)
elif isinstance(legend, dict):
payload.update(
_prefix_payload(
"legend_",
_flatten_legend_options(cast(dict[str, object], legend)),
)
)
else:
raise InvalidArgumentError("legend must be a Legend or dict")
if kwargs.get("sweep_steps") is not None:
sweep_steps = kwargs["sweep_steps"]
if not isinstance(sweep_steps, int):
raise InvalidArgumentError("sweep_steps must be an int")
payload["sweep_steps"] = int(sweep_steps)
return payload
def _copy_create_kwargs(self) -> dict[str, object]:
iso_func = self.iso_func
state = self._state()
coloring = str(state.get("coloring", constant.Coloring.GEOMETRIC.value)).lower()
copy_coloring = coloring if coloring != "vector" else None
display_type = self.display_type
threshold_range = self.threshold_range
iso_state = state.get("iso_value")
if not isinstance(iso_state, dict):
raise RuntimeError("iso surface state is missing iso_value")
payload: dict[str, object] = {
"iso_func": iso_func,
"iso_value": _range_from_iso_state(cast(dict[str, object], iso_state)),
"cutting_plane": self.cutting_plane
if isinstance(iso_func, CuttingPlane)
else None,
"geometric_color": self.geometric_color,
"display_type": display_type,
"line_type": self.line_type,
"contours": self.contours,
"show_mesh": self.show_mesh,
"unrolled": self.unrolled,
"visibility": self.visibility,
"transparency": self.transparency,
"scalar_func": self.scalar_func,
"vector_func": self.vector_func,
"threshold": self.threshold,
"threshold_func": self.threshold_func,
"threshold_range": Range(
_coerce_float(threshold_range.min),
_coerce_float(threshold_range.max),
),
"sweep_steps": self.sweep_steps,
}
if copy_coloring is not None:
payload["coloring"] = copy_coloring
vector_payload = _copy_vector_options_payload(
self.vector_options.copy(), display_type
)
if vector_payload:
payload["vector_options"] = VectorOptions.from_payload(vector_payload)
if copy_coloring == constant.Coloring.SCALAR.value:
payload["scalar_minmax"] = self.scalar_minmax.copy()
payload["colormap"] = self.colormap.copy()
legend = self.legend.copy()
if bool(legend.show):
payload["legend"] = legend
return payload
[docs]
def copy(self) -> "Iso":
"""Return a new iso surface with the same settings.
Example usage:
.. code-block:: python
>>> import os
>>> import fieldview as fv
>>> data_dir = os.path.join(fv.home, "examples", "f18")
>>> ds = fv.data.load_plot3d(
... os.path.join(data_dir, "f18i9b_g_bin"),
... os.path.join(data_dir, "f18i9b_q_bin"),
... )
>>> iso = fv.vis.create_iso(ds, iso_func="Density (Q1)")
>>> copy_obj = iso.copy()
"""
dataset = self._require_dataset()
kwargs = self._copy_create_kwargs()
return create_iso(
dataset,
iso_func=cast(str | CuttingPlane | dict[str, object], kwargs["iso_func"]),
iso_value=cast(RangedValue | None, kwargs.get("iso_value")),
cutting_plane=cast(
CuttingPlane | dict[str, object] | None,
kwargs.get("cutting_plane"),
),
coloring=cast(constant.Coloring | str | None, kwargs.get("coloring")),
geometric_color=cast(
constant.GeometricColor | int | None,
kwargs.get("geometric_color"),
),
display_type=cast(
constant.DisplayType | str | None, kwargs.get("display_type")
),
line_type=cast(constant.LineType | str | None, kwargs.get("line_type")),
contours=cast(
constant.ContourColoring | str | None, kwargs.get("contours")
),
show_mesh=cast(bool | None, kwargs.get("show_mesh")),
unrolled=cast(bool | None, kwargs.get("unrolled")),
visibility=cast(bool | None, kwargs.get("visibility")),
transparency=cast(float | None, kwargs.get("transparency")),
scalar_func=cast(str | None, kwargs.get("scalar_func")),
vector_func=cast(str | None, kwargs.get("vector_func")),
threshold=cast(bool | None, kwargs.get("threshold")),
threshold_func=cast(str | None, kwargs.get("threshold_func")),
threshold_range=cast(Range | None, kwargs.get("threshold_range")),
vector_options=cast(VectorOptions | None, kwargs.get("vector_options")),
scalar_minmax=cast(ScalarMinMax | None, kwargs.get("scalar_minmax")),
colormap=cast(Colormap | None, kwargs.get("colormap")),
legend=cast(Legend | None, kwargs.get("legend")),
sweep_steps=cast(int | None, kwargs.get("sweep_steps")),
)
[docs]
def delete(self) -> None:
"""Delete this iso surface.
Example usage:
.. code-block:: python
>>> import os
>>> import fieldview as fv
>>> data_dir = os.path.join(fv.home, "examples", "f18")
>>> ds = fv.data.load_plot3d(
... os.path.join(data_dir, "f18i9b_g_bin"),
... os.path.join(data_dir, "f18i9b_q_bin"),
... )
>>> iso = fv.vis.create_iso(ds, iso_func="Density (Q1)")
>>> iso.delete()
"""
self._delete_surface(_core.iso_surf_delete)
def _copy_vector_options_payload(
options: VectorOptions,
display_type: constant.DisplayType | str,
) -> dict[str, object]:
display_value = (
display_type.value
if isinstance(display_type, constant.DisplayType)
else str(display_type)
)
if display_value != constant.DisplayType.VECTORS.value:
return {}
payload = options.to_payload()
shaft_type = payload.get("shaft_type")
if isinstance(shaft_type, constant.VectorShaftType):
shaft_type = shaft_type.value
if str(shaft_type) != constant.VectorShaftType.CURVED.value:
payload.pop("time_limit", None)
payload.pop("display_type", None)
payload.pop("animate", None)
if not bool(payload.get("uniform_sampling", False)):
payload.pop("x_samples", None)
payload.pop("y_samples", None)
payload.pop("z_samples", None)
payload.pop("r_samples", None)
payload.pop("t_samples", None)
if not bool(payload.get("skip", False)):
payload.pop("skip_value", None)
return payload
[docs]
def create_iso(
dataset: Dataset | None = None,
*,
iso_func: str | CuttingPlane | dict[str, object],
iso_value: RangedValue | None = None,
cutting_plane: CuttingPlane | dict[str, object] | None = None,
coloring: constant.Coloring | str | None = None,
geometric_color: constant.GeometricColor | int | None = None,
display_type: constant.DisplayType | str | None = None,
line_type: constant.LineType | str | None = None,
contours: constant.ContourColoring | str | None = None,
show_mesh: bool | None = None,
unrolled: bool | None = None,
visibility: bool | None = None,
transparency: float | None = None,
scalar_func: str | None = None,
vector_func: str | None = None,
threshold: bool | None = None,
threshold_func: str | None = None,
threshold_range: Range | None = None,
vector_options: VectorOptions | None = None,
scalar_minmax: ScalarMinMax | None = None,
colormap: Colormap | None = None,
legend: Legend | None = None,
sweep_steps: int | None = None,
) -> Iso:
"""Create an iso surface for the given dataset.
Args:
dataset: Dataset to attach the new iso surface to. When omitted, the
current dataset is used.
iso_func: Iso function name, cutting plane, or cutting-plane payload
dict.
iso_value: Optional iso-value ranged-value controller.
cutting_plane: Optional cutting-plane override.
coloring: Coloring mode for the iso surface.
geometric_color: Geometric color id used when geometric coloring is
active.
display_type: Surface display type.
line_type: Line style used for wireframe-capable display modes.
contours: Contour coloring mode.
show_mesh: Whether the mesh overlay is shown.
unrolled: Whether unrolled display is enabled.
visibility: Whether the new iso surface is initially visible.
transparency: Surface transparency amount.
scalar_func: Scalar function name used for scalar coloring.
vector_func: Vector function name used for vector display modes.
threshold: Whether thresholding is enabled.
threshold_func: Scalar function name used for thresholding.
threshold_range: Threshold value range.
vector_options: Vector display options.
scalar_minmax: Scalar min/max annotation options.
colormap: Scalar colormap options.
legend: Legend options.
sweep_steps: Sweep step count.
Example usage:
.. code-block:: python
>>> import os
>>> import fieldview as fv
>>> data_dir = os.path.join(fv.home, "examples", "f18")
>>> ds = fv.data.load_plot3d(
... os.path.join(data_dir, "f18i9b_g_bin"),
... os.path.join(data_dir, "f18i9b_q_bin"),
... )
>>> iso_value = fv.RangedValue(value=0.8)
>>> iso = fv.vis.create_iso(ds, iso_func="Density (Q1)", iso_value=iso_value)
"""
dataset = _resolve_dataset_or_current(dataset)
if isinstance(iso_func, CuttingPlane):
create_iso_func: str | dict[str, object] = iso_func.to_payload()
elif isinstance(iso_func, str):
if not iso_func.strip():
raise InvalidArgumentError("iso_func cannot be empty")
create_iso_func = iso_func
elif isinstance(iso_func, dict):
create_iso_func = dict(iso_func)
else:
raise InvalidArgumentError("iso_func must be a string, CuttingPlane, or dict")
has_modifications = any(
value is not None
for value in (
iso_value,
cutting_plane,
coloring,
geometric_color,
display_type,
line_type,
contours,
show_mesh,
unrolled,
visibility,
transparency,
scalar_func,
vector_func,
threshold,
threshold_func,
threshold_range,
vector_options,
scalar_minmax,
colormap,
legend,
sweep_steps,
)
)
phigs_obj = _core_call(
_core.iso_surf_create, dataset.dataset_id, create_iso_func, has_modifications
)
iso = Iso(phigs_obj, dataset.dataset_id, dataset)
if has_modifications:
try:
iso.modify(
iso_value=iso_value,
cutting_plane=cutting_plane,
coloring=coloring,
geometric_color=geometric_color,
display_type=display_type,
line_type=line_type,
contours=contours,
show_mesh=show_mesh,
unrolled=unrolled,
visibility=visibility,
transparency=transparency,
scalar_func=scalar_func,
vector_func=vector_func,
threshold=threshold,
threshold_func=threshold_func,
threshold_range=threshold_range,
vector_options=vector_options,
scalar_minmax=scalar_minmax,
colormap=colormap,
legend=legend,
sweep_steps=sweep_steps,
)
except Exception:
_core_call(_core.iso_surf_delete, phigs_obj)
raise
return iso