| 1 |
"""These are private methods we keep out of plotting.py to simplify the module.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import operator |
| 6 |
from typing import TYPE_CHECKING |
| 7 |
|
| 8 |
import numpy as np |
| 9 |
|
| 10 |
from pyvista._deprecate_positional_args import _deprecate_positional_args |
| 11 |
from pyvista._warn_external import warn_external |
| 12 |
from pyvista.core.utilities.arrays import get_array |
| 13 |
from pyvista.core.utilities.misc import assert_empty_kwargs |
| 14 |
|
| 15 |
from .colors import Color |
| 16 |
from .opts import InterpolationType |
| 17 |
from .tools import opacity_transfer_function |
| 18 |
|
| 19 |
if TYPE_CHECKING: |
| 20 |
from pyvista.core._typing_core import NumpyArray |
| 21 |
from pyvista.core.dataset import DataSet |
| 22 |
from pyvista.core.utilities.arrays import CellLiteral |
| 23 |
from pyvista.core.utilities.arrays import PointLiteral |
| 24 |
|
| 25 |
|
| 26 |
def _resolve_scalars_field( |
| 27 |
scalars: NumpyArray[float], |
| 28 |
mesh: DataSet, |
| 29 |
preference: PointLiteral | CellLiteral, |
| 30 |
) -> PointLiteral | CellLiteral: |
| 31 |
"""Decide whether raw numpy ``scalars`` attach to points or cells. |
| 32 |
|
| 33 |
Matches by length. When both dimensions coincide (``n_points == |
| 34 |
n_cells``), falls back to ``preference``. |
| 35 |
|
| 36 |
Parameters |
| 37 |
---------- |
| 38 |
scalars : numpy.ndarray |
| 39 |
Array whose first axis length determines the association. |
| 40 |
|
| 41 |
mesh : pyvista.DataSet |
| 42 |
Mesh to match against. |
| 43 |
|
| 44 |
preference : str |
| 45 |
``'point'`` or ``'cell'``. Used to break ties when the array |
| 46 |
length matches both dimensions. |
| 47 |
|
| 48 |
Returns |
| 49 |
------- |
| 50 |
str |
| 51 |
Either ``'point'`` or ``'cell'``. |
| 52 |
|
| 53 |
Raises |
| 54 |
------ |
| 55 |
ValueError |
| 56 |
If the array length matches neither ``n_points`` nor |
| 57 |
``n_cells``. Without this check the array would silently be |
| 58 |
dropped and fail cryptically downstream. |
| 59 |
|
| 60 |
""" |
| 61 |
matches_points = scalars.shape[0] == mesh.n_points |
| 62 |
matches_cells = scalars.shape[0] == mesh.n_cells |
| 63 |
if matches_points and matches_cells: |
| 64 |
return preference |
| 65 |
if matches_points: |
| 66 |
return 'point' |
| 67 |
if matches_cells: |
| 68 |
return 'cell' |
| 69 |
msg = ( |
| 70 |
f'Length of scalars array ({scalars.shape[0]}) must match either the ' |
| 71 |
f'number of points ({mesh.n_points}) or cells ({mesh.n_cells}) in the mesh.' |
| 72 |
) |
| 73 |
raise ValueError(msg) |
| 74 |
|
| 75 |
|
| 76 |
def reduce_component_scalars( |
| 77 |
scalars: NumpyArray[float], |
| 78 |
scalars_name: str, |
| 79 |
component: int | None, |
| 80 |
) -> tuple[NumpyArray[float], str]: |
| 81 |
"""Reduce a 2D scalar array to 1D by magnitude or component index. |
| 82 |
|
| 83 |
Produces the derived array and synthesized name (``{name}-normed`` for |
| 84 |
magnitude or ``{name}-{component}`` for a component pick) that |
| 85 |
:meth:`DataSetMapper.set_scalars` and smooth-shading pre-processing |
| 86 |
both rely on. Keeping this in one place prevents the two call sites |
| 87 |
from drifting on naming or bounds checks. |
| 88 |
|
| 89 |
Parameters |
| 90 |
---------- |
| 91 |
scalars : numpy.ndarray |
| 92 |
2D scalar array of shape ``(n, k)``. |
| 93 |
|
| 94 |
scalars_name : str |
| 95 |
Base name of the input array. |
| 96 |
|
| 97 |
component : int | None |
| 98 |
Component index to extract, or ``None`` for vector magnitude. |
| 99 |
|
| 100 |
Returns |
| 101 |
------- |
| 102 |
reduced : numpy.ndarray |
| 103 |
1D array of shape ``(n,)``. |
| 104 |
|
| 105 |
derived_name : str |
| 106 |
Synthesized name carrying the reduction semantics. |
| 107 |
|
| 108 |
Raises |
| 109 |
------ |
| 110 |
TypeError |
| 111 |
If ``component`` is neither ``None`` nor an integer. |
| 112 |
|
| 113 |
ValueError |
| 114 |
If ``component`` is outside ``[0, scalars.shape[1])``. |
| 115 |
|
| 116 |
""" |
| 117 |
if component is None: |
| 118 |
return np.linalg.norm(scalars, axis=1), f'{scalars_name}-normed' |
| 119 |
try: |
| 120 |
component_index = operator.index(component) |
| 121 |
except TypeError: |
| 122 |
msg = 'component must be None or an integer.' |
| 123 |
raise TypeError(msg) from None |
| 124 |
if not 0 <= component_index < scalars.shape[1]: |
| 125 |
msg = ( |
| 126 |
'component must be nonnegative and less than the ' |
| 127 |
f'dimensionality of the scalars array: {scalars.shape[1]}' |
| 128 |
) |
| 129 |
raise ValueError(msg) |
| 130 |
return np.array(scalars[:, component_index]), f'{scalars_name}-{component_index}' |
| 131 |
|
| 132 |
|
| 133 |
def _stamp_raw_numpy_scalars( # noqa: PLR0917 |
| 134 |
mesh: DataSet, |
| 135 |
scalars: NumpyArray[float], |
| 136 |
scalars_name: str, |
| 137 |
preference: PointLiteral | CellLiteral, |
| 138 |
) -> tuple[str, PointLiteral | CellLiteral]: |
| 139 |
"""Attach a raw numpy scalars array to ``mesh`` under a unique name. |
| 140 |
|
| 141 |
Called from :meth:`Plotter.add_mesh` when the user passes a raw |
| 142 |
numpy array rather than a named array. Stamping the array on the |
| 143 |
mesh lets downstream pipeline stages (e.g. smooth-shading surface |
| 144 |
extraction) carry it forward, and lets callers later mutate the |
| 145 |
array via ``mesh[name] = ...`` to drive re-renders. |
| 146 |
|
| 147 |
Parameters |
| 148 |
---------- |
| 149 |
mesh : pyvista.DataSet |
| 150 |
Mesh to mutate. |
| 151 |
|
| 152 |
scalars : numpy.ndarray |
| 153 |
Raw numpy array whose first axis matches ``n_points`` or |
| 154 |
``n_cells``. |
| 155 |
|
| 156 |
scalars_name : str |
| 157 |
Base name to use. A unique suffix is added if the name is |
| 158 |
already in use. |
| 159 |
|
| 160 |
preference : str |
| 161 |
Disambiguator when the array length matches both dimensions. |
| 162 |
|
| 163 |
Returns |
| 164 |
------- |
| 165 |
scalars_name : str |
| 166 |
The name actually used (possibly suffixed for uniqueness). |
| 167 |
|
| 168 |
preference : str |
| 169 |
The resolved field association, ``'point'`` or ``'cell'``. |
| 170 |
|
| 171 |
""" |
| 172 |
scalars_name = _get_generated_scalars_name(mesh, scalars_name) |
| 173 |
preference = _resolve_scalars_field(scalars, mesh, preference) |
| 174 |
if preference == 'point': |
| 175 |
mesh.point_data.set_array(scalars, scalars_name, deep_copy=False) |
| 176 |
else: |
| 177 |
mesh.cell_data.set_array(scalars, scalars_name, deep_copy=False) |
| 178 |
return scalars_name, preference |
| 179 |
|
| 180 |
|
| 181 |
def _reduce_multicomponent_scalars_on_mesh( # noqa: PLR0917 |
| 182 |
mesh: DataSet, |
| 183 |
scalars: NumpyArray[float], |
| 184 |
scalars_name: str, |
| 185 |
component: int | None, |
| 186 |
preference: PointLiteral | CellLiteral, |
| 187 |
) -> tuple[NumpyArray[float], str, PointLiteral | CellLiteral]: |
| 188 |
"""Reduce 2D scalars to 1D and stamp the derived array on ``mesh``. |
| 189 |
|
| 190 |
Smooth-shading pre-processing cannot defer this reduction to |
| 191 |
:meth:`DataSetMapper.set_scalars`: each ``SmoothShadingAlgorithm`` |
| 192 |
``RequestData`` ``ShallowCopy`` overwrites the mapper's cached |
| 193 |
dataset, wiping any derived array the mapper stamped there. Doing |
| 194 |
the reduction on the user's mesh *before* the pipeline runs means |
| 195 |
the derived array survives surface extraction via the normal data |
| 196 |
propagation path. |
| 197 |
|
| 198 |
Parameters |
| 199 |
---------- |
| 200 |
mesh : pyvista.DataSet |
| 201 |
Mesh to mutate. |
| 202 |
|
| 203 |
scalars : numpy.ndarray |
| 204 |
2D scalar array. |
| 205 |
|
| 206 |
scalars_name : str |
| 207 |
Base name for the derived array. |
| 208 |
|
| 209 |
component : int | None |
| 210 |
Component index or ``None`` for magnitude. |
| 211 |
|
| 212 |
preference : str |
| 213 |
Disambiguator when the array length matches both dimensions. |
| 214 |
|
| 215 |
Returns |
| 216 |
------- |
| 217 |
scalars : numpy.ndarray |
| 218 |
1D derived array. |
| 219 |
|
| 220 |
scalars_name : str |
| 221 |
Synthesized derived name (``{base}-normed`` or ``{base}-{i}``, |
| 222 |
possibly further suffixed for uniqueness). |
| 223 |
|
| 224 |
preference : str |
| 225 |
Resolved field association. |
| 226 |
|
| 227 |
""" |
| 228 |
preference = _resolve_scalars_field(scalars, mesh, preference) |
| 229 |
# Reduce first so the derived suffix (``-normed`` or ``-<i>``) is |
| 230 |
# applied to the user-provided base name before any uniqueness check. |
| 231 |
# Otherwise ``vec`` -> ``vec-1`` (uniquify collision with existing |
| 232 |
# ``vec``) -> ``vec-1-1`` (reduction), which is ugly and surprising. |
| 233 |
scalars, scalars_name = reduce_component_scalars(scalars, scalars_name, component) |
| 234 |
scalars_name = _get_generated_scalars_name(mesh, scalars_name) |
| 235 |
if preference == 'point': |
| 236 |
mesh.point_data.set_array(scalars, scalars_name, deep_copy=False) |
| 237 |
else: |
| 238 |
mesh.cell_data.set_array(scalars, scalars_name, deep_copy=False) |
| 239 |
return scalars, scalars_name, preference |
| 240 |
|
| 241 |
|
| 242 |
def _remap_scalars_through_topology_change( # noqa: PLR0917 |
| 243 |
mesh: DataSet, |
| 244 |
scalars: NumpyArray[float], |
| 245 |
original_scalar_name: str | None, |
| 246 |
preference: PointLiteral | CellLiteral, |
| 247 |
input_n_points: int, |
| 248 |
) -> NumpyArray[float]: |
| 249 |
"""Re-resolve ``scalars`` after smooth shading changes topology. |
| 250 |
|
| 251 |
Surface extraction and/or sharp-edge splitting may drop cells or |
| 252 |
duplicate vertices. This helper picks up the re-indexed values |
| 253 |
from the post-pipeline mesh so they line up with the data the |
| 254 |
mapper will consume. |
| 255 |
|
| 256 |
Parameters |
| 257 |
---------- |
| 258 |
mesh : pyvista.DataSet |
| 259 |
Post-pipeline mesh. |
| 260 |
|
| 261 |
scalars : numpy.ndarray |
| 262 |
Pre-pipeline scalars array. |
| 263 |
|
| 264 |
original_scalar_name : str | None |
| 265 |
If set, the array is resolved by name on ``mesh``. When |
| 266 |
``None`` (raw numpy + upstream vtkAlgorithm input), the |
| 267 |
``vtkOriginalPointIds`` tracker is used to remap point-length |
| 268 |
scalars. |
| 269 |
|
| 270 |
preference : str |
| 271 |
Field association for name lookup. |
| 272 |
|
| 273 |
input_n_points : int |
| 274 |
Number of points in the pre-pipeline mesh, used to detect |
| 275 |
point-length scalars for tracker-based remap. |
| 276 |
|
| 277 |
Returns |
| 278 |
------- |
| 279 |
numpy.ndarray |
| 280 |
Scalars sized to the post-pipeline mesh. The input is returned |
| 281 |
unchanged if no remap is possible. |
| 282 |
|
| 283 |
""" |
| 284 |
# Local import to avoid a top-level circular import: algorithms imports |
| 285 |
# from core, core imports from plotting indirectly for Actor types. |
| 286 |
from .utilities.algorithms import SmoothShadingAlgorithm # noqa: PLC0415 |
| 287 |
|
| 288 |
if original_scalar_name is not None: |
| 289 |
resolved = get_array(mesh, original_scalar_name, preference=preference, err=False) |
| 290 |
if resolved is not None: |
| 291 |
return resolved |
| 292 |
return scalars |
| 293 |
|
| 294 |
tracker_name = SmoothShadingAlgorithm.ORIGINAL_POINT_IDS_NAME |
| 295 |
if tracker_name in mesh.point_data and scalars.shape[0] == input_n_points: |
| 296 |
tracker = np.asarray(mesh.point_data[tracker_name]) |
| 297 |
return np.asarray(scalars)[tracker] |
| 298 |
return scalars |
| 299 |
|
| 300 |
|
| 301 |
def _get_generated_scalars_name(mesh: DataSet, base_name: str) -> str: |
| 302 |
"""Return a unique generated scalars name for a mesh. |
| 303 |
|
| 304 |
Picks ``base_name`` if free on ``point_data``, ``cell_data``, and |
| 305 |
``field_data``; otherwise appends a numeric suffix. |
| 306 |
""" |
| 307 |
import itertools # noqa: PLC0415 |
| 308 |
|
| 309 |
def _is_free(name: str) -> bool: |
| 310 |
return ( |
| 311 |
name not in mesh.point_data |
| 312 |
and name not in mesh.cell_data |
| 313 |
and name not in mesh.field_data |
| 314 |
) |
| 315 |
|
| 316 |
if _is_free(base_name): |
| 317 |
return base_name |
| 318 |
return next(f'{base_name}-{i}' for i in itertools.count(1) if _is_free(f'{base_name}-{i}')) |
| 319 |
|
| 320 |
|
| 321 |
@_deprecate_positional_args |
| 322 |
def process_opacity(mesh, opacity, preference, n_colors, scalars, use_transparency): # noqa: PLR0917 |
| 323 |
"""Process opacity. |
| 324 |
|
| 325 |
This function accepts an opacity string or array and always |
| 326 |
returns an array that can be applied to a dataset for plotting. |
| 327 |
|
| 328 |
Parameters |
| 329 |
---------- |
| 330 |
mesh : pyvista.DataSet |
| 331 |
Dataset to process the opacity for. |
| 332 |
|
| 333 |
opacity : str, sequence |
| 334 |
String or array. If string, can be a ``str`` name of a |
| 335 |
predefined mapping such as ``'linear'``, ``'geom'``, |
| 336 |
``'sigmoid'``, ``'sigmoid3-10'``, or the key of a cell or |
| 337 |
point data array. |
| 338 |
|
| 339 |
preference : str |
| 340 |
When ``mesh.n_points == mesh.n_cells``, this parameter |
| 341 |
sets how the scalars will be mapped to the mesh. If |
| 342 |
``'point'``, causes the scalars will be associated with |
| 343 |
the mesh points. Can be either ``'point'`` or |
| 344 |
``'cell'``. |
| 345 |
|
| 346 |
n_colors : int |
| 347 |
Number of colors to use when displaying the opacity. |
| 348 |
|
| 349 |
scalars : numpy.ndarray |
| 350 |
Dataset scalars. |
| 351 |
|
| 352 |
use_transparency : bool |
| 353 |
Invert the opacity mappings and make the values correspond |
| 354 |
to transparency. |
| 355 |
|
| 356 |
Returns |
| 357 |
------- |
| 358 |
custom_opac : bool |
| 359 |
If using custom opacity. |
| 360 |
|
| 361 |
opacity : numpy.ndarray |
| 362 |
Array containing the opacity. |
| 363 |
|
| 364 |
""" |
| 365 |
custom_opac = False |
| 366 |
if isinstance(opacity, str): |
| 367 |
try: |
| 368 |
# Get array from mesh |
| 369 |
opacity = get_array(mesh, opacity, preference=preference, err=True) |
| 370 |
if np.any(opacity > 1): |
| 371 |
warn_external('Opacity scalars contain values over 1') # pragma: no cover |
| 372 |
if np.any(opacity < 0): |
| 373 |
warn_external('Opacity scalars contain values less than 0') # pragma: no cover |
| 374 |
custom_opac = True |
| 375 |
except KeyError: |
| 376 |
# Or get opacity transfer function (e.g. "linear") |
| 377 |
opacity = opacity_transfer_function(opacity, n_colors) |
| 378 |
else: |
| 379 |
if scalars.shape[0] != opacity.shape[0]: |
| 380 |
msg = 'Opacity array and scalars array must have the same number of elements.' |
| 381 |
raise ValueError(msg) |
| 382 |
elif isinstance(opacity, (np.ndarray, list, tuple)): |
| 383 |
opacity = np.asanyarray(opacity) |
| 384 |
if opacity.shape[0] in [mesh.n_cells, mesh.n_points]: |
| 385 |
# User could pass an array of opacities for every point/cell |
| 386 |
custom_opac = True |
| 387 |
else: |
| 388 |
opacity = opacity_transfer_function(opacity, n_colors) |
| 389 |
|
| 390 |
if use_transparency: |
| 391 |
if np.max(opacity) <= 1.0: |
| 392 |
opacity = 1 - opacity |
| 393 |
elif isinstance(opacity, np.ndarray): |
| 394 |
opacity = 255 - opacity |
| 395 |
|
| 396 |
return custom_opac, opacity |
| 397 |
|
| 398 |
|
| 399 |
def _common_arg_parser( |
| 400 |
*, |
| 401 |
dataset, |
| 402 |
theme, |
| 403 |
n_colors, |
| 404 |
scalar_bar_args, |
| 405 |
split_sharp_edges, |
| 406 |
show_scalar_bar, |
| 407 |
render_points_as_spheres, |
| 408 |
point_shape, |
| 409 |
smooth_shading, |
| 410 |
pbr, |
| 411 |
clim, |
| 412 |
cmap, |
| 413 |
culling, |
| 414 |
name, |
| 415 |
nan_color, |
| 416 |
nan_opacity, |
| 417 |
texture, |
| 418 |
rgb, |
| 419 |
style, |
| 420 |
remove_existing_actor=None, |
| 421 |
**kwargs, |
| 422 |
): |
| 423 |
"""Parse arguments in common between add_volume, composite, and mesh.""" |
| 424 |
# supported aliases |
| 425 |
clim = kwargs.pop('rng', clim) |
| 426 |
cmap = kwargs.pop('colormap', cmap) |
| 427 |
culling = kwargs.pop('backface_culling', culling) |
| 428 |
rgb = kwargs.pop('rgba', rgb) |
| 429 |
vertex_color = kwargs.pop('vertex_color', theme.edge_color) |
| 430 |
vertex_style = kwargs.pop('vertex_style', 'points') |
| 431 |
vertex_opacity = kwargs.pop('vertex_opacity', 1.0) |
| 432 |
|
| 433 |
# Support aliases for 'back', 'front', or 'none'. Consider deprecating |
| 434 |
if culling is False: |
| 435 |
culling = 'none' |
| 436 |
elif culling in ['b', 'backface', True]: |
| 437 |
culling = 'back' |
| 438 |
elif culling in ['f', 'frontface']: |
| 439 |
culling = 'front' |
| 440 |
|
| 441 |
if show_scalar_bar is None: |
| 442 |
# use theme unless plotting RGB |
| 443 |
_default = theme.show_scalar_bar or scalar_bar_args |
| 444 |
show_scalar_bar = False if rgb else _default |
| 445 |
# Avoid mutating input |
| 446 |
scalar_bar_args = {'n_colors': n_colors} if scalar_bar_args is None else scalar_bar_args.copy() |
| 447 |
|
| 448 |
# theme based parameters |
| 449 |
if split_sharp_edges is None: |
| 450 |
split_sharp_edges = theme.split_sharp_edges |
| 451 |
feature_angle = kwargs.pop('feature_angle', theme.sharp_edges_feature_angle) |
| 452 |
if render_points_as_spheres is None: |
| 453 |
if style == 'points_gaussian': |
| 454 |
render_points_as_spheres = False |
| 455 |
else: |
| 456 |
render_points_as_spheres = theme.render_points_as_spheres |
| 457 |
|
| 458 |
if point_shape is None: |
| 459 |
point_shape = theme.point_shape |
| 460 |
|
| 461 |
if point_shape is not None and render_points_as_spheres: |
| 462 |
warn_external( |
| 463 |
f'point_shape={point_shape!r} requires render_points_as_spheres=False. ' |
| 464 |
'Disabling render_points_as_spheres.', |
| 465 |
) |
| 466 |
render_points_as_spheres = False |
| 467 |
|
| 468 |
if smooth_shading is None: |
| 469 |
smooth_shading = True if pbr else theme.smooth_shading |
| 470 |
|
| 471 |
if name is None: |
| 472 |
name = f'{type(dataset).__name__}({dataset.memory_address})' |
| 473 |
# Default to False when no name is provided |
| 474 |
if remove_existing_actor is None: # pragma: no cover |
| 475 |
remove_existing_actor = False |
| 476 |
# Default to True when a name is provided (for backwards compatibility) |
| 477 |
elif remove_existing_actor is None: |
| 478 |
remove_existing_actor = True |
| 479 |
|
| 480 |
nan_color = Color(nan_color, opacity=nan_opacity, default_color=theme.nan_color) |
| 481 |
|
| 482 |
if texture is False: |
| 483 |
texture = None |
| 484 |
|
| 485 |
# allow directly specifying interpolation (potential future feature) |
| 486 |
if 'interpolation' in kwargs: |
| 487 |
interpolation = kwargs.pop('interpolation') # pragma: no cover: |
| 488 |
elif pbr: |
| 489 |
interpolation = InterpolationType.PBR |
| 490 |
elif smooth_shading: |
| 491 |
interpolation = InterpolationType.PHONG |
| 492 |
else: |
| 493 |
interpolation = theme.lighting_params.interpolation |
| 494 |
|
| 495 |
if 'scalar' in kwargs: |
| 496 |
msg = '`scalar` is an invalid keyword argument. Perhaps you mean `scalars` with an s?' |
| 497 |
raise TypeError(msg) |
| 498 |
|
| 499 |
assert_empty_kwargs(**kwargs) |
| 500 |
return ( |
| 501 |
scalar_bar_args, |
| 502 |
split_sharp_edges, |
| 503 |
show_scalar_bar, |
| 504 |
feature_angle, |
| 505 |
render_points_as_spheres, |
| 506 |
point_shape, |
| 507 |
smooth_shading, |
| 508 |
clim, |
| 509 |
cmap, |
| 510 |
culling, |
| 511 |
name, |
| 512 |
nan_color, |
| 513 |
texture, |
| 514 |
rgb, |
| 515 |
interpolation, |
| 516 |
remove_existing_actor, |
| 517 |
vertex_color, |
| 518 |
vertex_style, |
| 519 |
vertex_opacity, |
| 520 |
) |