| 1 |
"""Module containing useful plotting tools.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
from enum import Enum |
| 6 |
import os |
| 7 |
import platform |
| 8 |
from subprocess import PIPE |
| 9 |
from subprocess import Popen |
| 10 |
from subprocess import TimeoutExpired |
| 11 |
|
| 12 |
import numpy as np |
| 13 |
|
| 14 |
import pyvista as pv |
| 15 |
from pyvista import _vtk |
| 16 |
from pyvista._deprecate_positional_args import _deprecate_positional_args |
| 17 |
|
| 18 |
from .colors import Color |
| 19 |
|
| 20 |
|
| 21 |
class FONTS(Enum): |
| 22 |
"""Font families available to PyVista.""" |
| 23 |
|
| 24 |
arial = _vtk.VTK_ARIAL |
| 25 |
courier = _vtk.VTK_COURIER |
| 26 |
times = _vtk.VTK_TIMES |
| 27 |
|
| 28 |
|
| 29 |
# Track render window support and plotting |
| 30 |
SUPPORTS_OPENGL = None |
| 31 |
SUPPORTS_PLOTTING = None |
| 32 |
|
| 33 |
|
| 34 |
def supports_open_gl(): |
| 35 |
"""Return if the system supports OpenGL. |
| 36 |
|
| 37 |
This function checks if the system supports OpenGL by creating a VTK render |
| 38 |
window and querying its OpenGL support. |
| 39 |
|
| 40 |
Returns |
| 41 |
------- |
| 42 |
bool |
| 43 |
``True`` if the system supports OpenGL, ``False`` otherwise. |
| 44 |
|
| 45 |
""" |
| 46 |
global SUPPORTS_OPENGL # noqa: PLW0603 |
| 47 |
if SUPPORTS_OPENGL is None: |
| 48 |
ren_win = _vtk.vtkRenderWindow() |
| 49 |
ren_win.SetOffScreenRendering(True) |
| 50 |
if hasattr(ren_win, 'SetConnectContextToNSView'): |
| 51 |
ren_win.SetConnectContextToNSView(False) |
| 52 |
SUPPORTS_OPENGL = bool(ren_win.SupportsOpenGL()) |
| 53 |
return SUPPORTS_OPENGL |
| 54 |
|
| 55 |
|
| 56 |
def _system_supports_plotting() -> bool: # noqa: PLR0911 |
| 57 |
"""Check if the environment supports plotting on Windows, Linux, or Mac OS. |
| 58 |
|
| 59 |
Returns |
| 60 |
------- |
| 61 |
system_supports_plotting : bool |
| 62 |
``True`` when system supports plotting. |
| 63 |
|
| 64 |
""" |
| 65 |
if os.environ.get('ALLOW_PLOTTING', '').lower() == 'true': |
| 66 |
return True |
| 67 |
|
| 68 |
# Windows case |
| 69 |
if os.name == 'nt': |
| 70 |
# actually have to check here. Somewhat expensive. |
| 71 |
return supports_open_gl() |
| 72 |
|
| 73 |
# mac case |
| 74 |
if platform.system() == 'Darwin': |
| 75 |
# check if finder available |
| 76 |
proc = Popen(['pgrep', '-qx', 'Finder'], stdout=PIPE, stderr=PIPE, encoding='utf8') |
| 77 |
try: |
| 78 |
proc.communicate(timeout=10) |
| 79 |
except TimeoutExpired: |
| 80 |
return False |
| 81 |
if proc.returncode == 0: |
| 82 |
return True |
| 83 |
|
| 84 |
# display variable set, likely available |
| 85 |
return 'DISPLAY' in os.environ |
| 86 |
|
| 87 |
# Linux case |
| 88 |
if os.environ.get('WAYLAND_DISPLAY'): # pragma: no cover |
| 89 |
return True |
| 90 |
|
| 91 |
try: |
| 92 |
proc = Popen(['xset', '-q'], stdout=PIPE, stderr=PIPE, encoding='utf8') |
| 93 |
proc.communicate(timeout=10) |
| 94 |
except (OSError, TimeoutExpired): # pragma: no cover |
| 95 |
# possible we have EGL support |
| 96 |
return supports_open_gl() |
| 97 |
else: # pragma: no cover |
| 98 |
return proc.returncode == 0 |
| 99 |
|
| 100 |
|
| 101 |
def system_supports_plotting() -> bool: |
| 102 |
"""Check if the environment supports plotting. |
| 103 |
|
| 104 |
Returns |
| 105 |
------- |
| 106 |
bool |
| 107 |
``True`` when system supports plotting. |
| 108 |
|
| 109 |
""" |
| 110 |
global SUPPORTS_PLOTTING # noqa: PLW0603 |
| 111 |
if SUPPORTS_PLOTTING is None: |
| 112 |
SUPPORTS_PLOTTING = _system_supports_plotting() |
| 113 |
|
| 114 |
# always use the cached response |
| 115 |
return SUPPORTS_PLOTTING |
| 116 |
|
| 117 |
|
| 118 |
def _update_axes_label_color(axes_actor, color=None): |
| 119 |
"""Set the axes label color (internal helper).""" |
| 120 |
color = Color(color, default_color=pv.global_theme.font.color) |
| 121 |
if isinstance(axes_actor, _vtk.vtkAxesActor): |
| 122 |
prop_x = axes_actor.GetXAxisCaptionActor2D().GetCaptionTextProperty() |
| 123 |
prop_y = axes_actor.GetYAxisCaptionActor2D().GetCaptionTextProperty() |
| 124 |
prop_z = axes_actor.GetZAxisCaptionActor2D().GetCaptionTextProperty() |
| 125 |
for prop in [prop_x, prop_y, prop_z]: |
| 126 |
prop.SetColor(color.float_rgb) |
| 127 |
prop.SetShadow(False) |
| 128 |
elif isinstance(axes_actor, _vtk.vtkAnnotatedCubeActor): |
| 129 |
axes_actor.GetTextEdgesProperty().SetColor(color.float_rgb) |
| 130 |
|
| 131 |
|
| 132 |
@_deprecate_positional_args |
| 133 |
def create_axes_marker( # noqa: PLR0917 |
| 134 |
label_color=None, |
| 135 |
x_color=None, |
| 136 |
y_color=None, |
| 137 |
z_color=None, |
| 138 |
xlabel='X', |
| 139 |
ylabel='Y', |
| 140 |
zlabel='Z', |
| 141 |
labels_off: bool = False, # noqa: FBT001, FBT002 |
| 142 |
line_width=2, |
| 143 |
cone_radius=0.4, |
| 144 |
shaft_length=0.8, |
| 145 |
tip_length=0.2, |
| 146 |
ambient=0.5, |
| 147 |
label_size=(0.25, 0.1), |
| 148 |
) -> _vtk.vtkAxesActor: |
| 149 |
"""Create an axis actor. |
| 150 |
|
| 151 |
Parameters |
| 152 |
---------- |
| 153 |
label_color : ColorLike, optional |
| 154 |
Color of the label text. |
| 155 |
|
| 156 |
x_color : ColorLike, optional |
| 157 |
Color of the x-axis text. |
| 158 |
|
| 159 |
y_color : ColorLike, optional |
| 160 |
Color of the y-axis text. |
| 161 |
|
| 162 |
z_color : ColorLike, optional |
| 163 |
Color of the z-axis text. |
| 164 |
|
| 165 |
xlabel : str, default: "X" |
| 166 |
Text used for the x-axis. |
| 167 |
|
| 168 |
ylabel : str, default: "Y" |
| 169 |
Text used for the y-axis. |
| 170 |
|
| 171 |
zlabel : str, default: "Z" |
| 172 |
Text used for the z-axis. |
| 173 |
|
| 174 |
labels_off : bool, default: False |
| 175 |
Enable or disable the text labels for the axes. |
| 176 |
|
| 177 |
line_width : float, default: 2 |
| 178 |
The width of the marker lines. |
| 179 |
|
| 180 |
cone_radius : float, default: 0.4 |
| 181 |
The radius of the axes arrow tips. |
| 182 |
|
| 183 |
shaft_length : float, default: 0.8 |
| 184 |
The length of the axes arrow shafts. |
| 185 |
|
| 186 |
tip_length : float, default: 0.2 |
| 187 |
Length of the tip. |
| 188 |
|
| 189 |
ambient : float, default: 0.5 |
| 190 |
The ambient of the axes arrows. Value should be between 0 and 1. |
| 191 |
|
| 192 |
label_size : sequence[float], default: (0.25, 0.1) |
| 193 |
The width and height of the axes label actors. Values should be between |
| 194 |
0 and 1. For example ``(0.2, 0.1)``. |
| 195 |
|
| 196 |
Returns |
| 197 |
------- |
| 198 |
:vtk:`vtkAxesActor` |
| 199 |
Axes actor. |
| 200 |
|
| 201 |
Examples |
| 202 |
-------- |
| 203 |
Create the default axes marker. |
| 204 |
|
| 205 |
>>> import pyvista as pv |
| 206 |
>>> marker = pv.create_axes_marker() |
| 207 |
>>> pl = pv.Plotter() |
| 208 |
>>> _ = pl.add_actor(marker) |
| 209 |
>>> pl.show() |
| 210 |
|
| 211 |
Create an axes marker at the origin with custom colors and axis labels. |
| 212 |
|
| 213 |
>>> import pyvista as pv |
| 214 |
>>> marker = pv.create_axes_marker( |
| 215 |
... line_width=4, |
| 216 |
... ambient=0.0, |
| 217 |
... x_color='#378df0', |
| 218 |
... y_color='#ab2e5d', |
| 219 |
... z_color='#f7fb9a', |
| 220 |
... xlabel='X Axis', |
| 221 |
... ylabel='Y Axis', |
| 222 |
... zlabel='Z Axis', |
| 223 |
... label_size=(0.1, 0.1), |
| 224 |
... ) |
| 225 |
>>> pl = pv.Plotter() |
| 226 |
>>> _ = pl.add_actor(marker) |
| 227 |
>>> pl.show() |
| 228 |
|
| 229 |
""" |
| 230 |
x_color = Color(x_color, default_color=pv.global_theme.axes.x_color) |
| 231 |
y_color = Color(y_color, default_color=pv.global_theme.axes.y_color) |
| 232 |
z_color = Color(z_color, default_color=pv.global_theme.axes.z_color) |
| 233 |
axes_actor = _vtk.vtkAxesActor() |
| 234 |
axes_actor.GetXAxisShaftProperty().SetColor(x_color.float_rgb) |
| 235 |
axes_actor.GetXAxisTipProperty().SetColor(x_color.float_rgb) |
| 236 |
axes_actor.GetYAxisShaftProperty().SetColor(y_color.float_rgb) |
| 237 |
axes_actor.GetYAxisTipProperty().SetColor(y_color.float_rgb) |
| 238 |
axes_actor.GetZAxisShaftProperty().SetColor(z_color.float_rgb) |
| 239 |
axes_actor.GetZAxisTipProperty().SetColor(z_color.float_rgb) |
| 240 |
# Set labels |
| 241 |
axes_actor.SetXAxisLabelText(xlabel) |
| 242 |
axes_actor.SetYAxisLabelText(ylabel) |
| 243 |
axes_actor.SetZAxisLabelText(zlabel) |
| 244 |
if labels_off: |
| 245 |
axes_actor.AxisLabelsOff() |
| 246 |
# Set Line width |
| 247 |
axes_actor.GetXAxisShaftProperty().SetLineWidth(line_width) |
| 248 |
axes_actor.GetYAxisShaftProperty().SetLineWidth(line_width) |
| 249 |
axes_actor.GetZAxisShaftProperty().SetLineWidth(line_width) |
| 250 |
|
| 251 |
axes_actor.SetConeRadius(cone_radius) |
| 252 |
axes_actor.SetNormalizedShaftLength([shaft_length] * 3) |
| 253 |
axes_actor.SetNormalizedTipLength([tip_length] * 3) |
| 254 |
axes_actor.GetXAxisShaftProperty().SetAmbient(ambient) |
| 255 |
axes_actor.GetYAxisShaftProperty().SetAmbient(ambient) |
| 256 |
axes_actor.GetZAxisShaftProperty().SetAmbient(ambient) |
| 257 |
axes_actor.GetXAxisTipProperty().SetAmbient(ambient) |
| 258 |
axes_actor.GetYAxisTipProperty().SetAmbient(ambient) |
| 259 |
axes_actor.GetZAxisTipProperty().SetAmbient(ambient) |
| 260 |
|
| 261 |
for label_actor in [ |
| 262 |
axes_actor.GetXAxisCaptionActor2D(), |
| 263 |
axes_actor.GetYAxisCaptionActor2D(), |
| 264 |
axes_actor.GetZAxisCaptionActor2D(), |
| 265 |
]: |
| 266 |
label_actor.SetWidth(label_size[0]) |
| 267 |
label_actor.SetHeight(label_size[1]) |
| 268 |
|
| 269 |
_update_axes_label_color(axes_actor, label_color) |
| 270 |
|
| 271 |
return axes_actor |
| 272 |
|
| 273 |
|
| 274 |
@_deprecate_positional_args |
| 275 |
def create_axes_orientation_box( # noqa: PLR0917 |
| 276 |
line_width=1, |
| 277 |
text_scale=0.366667, |
| 278 |
edge_color='black', |
| 279 |
x_color=None, |
| 280 |
y_color=None, |
| 281 |
z_color=None, |
| 282 |
xlabel='X', |
| 283 |
ylabel='Y', |
| 284 |
zlabel='Z', |
| 285 |
x_face_color='red', |
| 286 |
y_face_color='green', |
| 287 |
z_face_color='blue', |
| 288 |
color_box: bool = False, # noqa: FBT001, FBT002 |
| 289 |
label_color=None, |
| 290 |
labels_off: bool = False, # noqa: FBT001, FBT002 |
| 291 |
opacity=0.5, |
| 292 |
show_text_edges: bool = False, # noqa: FBT001, FBT002 |
| 293 |
): |
| 294 |
"""Create a Box axes orientation widget with labels. |
| 295 |
|
| 296 |
Parameters |
| 297 |
---------- |
| 298 |
line_width : float, optional |
| 299 |
The width of the marker lines. |
| 300 |
|
| 301 |
text_scale : float, optional |
| 302 |
Size of the text relative to the faces. |
| 303 |
|
| 304 |
edge_color : ColorLike, optional |
| 305 |
Color of the edges. |
| 306 |
|
| 307 |
x_color : ColorLike, optional |
| 308 |
Color of the x-axis text. |
| 309 |
|
| 310 |
y_color : ColorLike, optional |
| 311 |
Color of the y-axis text. |
| 312 |
|
| 313 |
z_color : ColorLike, optional |
| 314 |
Color of the z-axis text. |
| 315 |
|
| 316 |
xlabel : str, optional |
| 317 |
Text used for the x-axis. |
| 318 |
|
| 319 |
ylabel : str, optional |
| 320 |
Text used for the y-axis. |
| 321 |
|
| 322 |
zlabel : str, optional |
| 323 |
Text used for the z-axis. |
| 324 |
|
| 325 |
x_face_color : ColorLike, optional |
| 326 |
Color used for the x-axis arrow. Defaults to theme axes |
| 327 |
parameters. |
| 328 |
|
| 329 |
y_face_color : ColorLike, optional |
| 330 |
Color used for the y-axis arrow. Defaults to theme axes |
| 331 |
parameters. |
| 332 |
|
| 333 |
z_face_color : ColorLike, optional |
| 334 |
Color used for the z-axis arrow. Defaults to theme axes |
| 335 |
parameters. |
| 336 |
|
| 337 |
color_box : bool, optional |
| 338 |
Enable or disable the face colors. Otherwise, box is white. |
| 339 |
|
| 340 |
label_color : ColorLike, optional |
| 341 |
Color of the labels. |
| 342 |
|
| 343 |
labels_off : bool, optional |
| 344 |
Enable or disable the text labels for the axes. |
| 345 |
|
| 346 |
opacity : float, optional |
| 347 |
Opacity in the range of ``[0, 1]`` of the orientation box. |
| 348 |
|
| 349 |
show_text_edges : bool, optional |
| 350 |
Enable or disable drawing the vector text edges. |
| 351 |
|
| 352 |
Returns |
| 353 |
------- |
| 354 |
:vtk:`vtkAnnotatedCubeActor` |
| 355 |
Annotated cube actor. |
| 356 |
|
| 357 |
Examples |
| 358 |
-------- |
| 359 |
Create and plot an orientation box |
| 360 |
|
| 361 |
>>> import pyvista as pv |
| 362 |
>>> actor = pv.create_axes_orientation_box( |
| 363 |
... line_width=1, |
| 364 |
... text_scale=0.53, |
| 365 |
... edge_color='black', |
| 366 |
... x_color='k', |
| 367 |
... y_color=None, |
| 368 |
... z_color=None, |
| 369 |
... xlabel='X', |
| 370 |
... ylabel='Y', |
| 371 |
... zlabel='Z', |
| 372 |
... color_box=False, |
| 373 |
... labels_off=False, |
| 374 |
... opacity=1.0, |
| 375 |
... ) |
| 376 |
>>> pl = pv.Plotter() |
| 377 |
>>> _ = pl.add_actor(actor) |
| 378 |
>>> pl.show() |
| 379 |
|
| 380 |
""" |
| 381 |
x_color = Color(x_color, default_color=pv.global_theme.axes.x_color) |
| 382 |
y_color = Color(y_color, default_color=pv.global_theme.axes.y_color) |
| 383 |
z_color = Color(z_color, default_color=pv.global_theme.axes.z_color) |
| 384 |
edge_color = Color(edge_color, default_color=pv.global_theme.edge_color) |
| 385 |
x_face_color = Color(x_face_color) |
| 386 |
y_face_color = Color(y_face_color) |
| 387 |
z_face_color = Color(z_face_color) |
| 388 |
axes_actor = _vtk.vtkAnnotatedCubeActor() |
| 389 |
axes_actor.SetFaceTextScale(text_scale) |
| 390 |
if xlabel is not None: |
| 391 |
axes_actor.SetXPlusFaceText(f'+{xlabel}') |
| 392 |
axes_actor.SetXMinusFaceText(f'-{xlabel}') |
| 393 |
if ylabel is not None: |
| 394 |
axes_actor.SetYPlusFaceText(f'+{ylabel}') |
| 395 |
axes_actor.SetYMinusFaceText(f'-{ylabel}') |
| 396 |
if zlabel is not None: |
| 397 |
axes_actor.SetZPlusFaceText(f'+{zlabel}') |
| 398 |
axes_actor.SetZMinusFaceText(f'-{zlabel}') |
| 399 |
axes_actor.SetFaceTextVisibility(not labels_off) |
| 400 |
axes_actor.SetTextEdgesVisibility(show_text_edges) |
| 401 |
# https://github.com/pyvista/pyvista/pull/5382 |
| 402 |
# axes_actor.GetTextEdgesProperty().SetColor(edge_color.float_rgb) |
| 403 |
axes_actor.GetTextEdgesProperty().SetLineWidth(line_width) |
| 404 |
axes_actor.GetXPlusFaceProperty().SetColor(x_color.float_rgb) |
| 405 |
axes_actor.GetXMinusFaceProperty().SetColor(x_color.float_rgb) |
| 406 |
axes_actor.GetYPlusFaceProperty().SetColor(y_color.float_rgb) |
| 407 |
axes_actor.GetYMinusFaceProperty().SetColor(y_color.float_rgb) |
| 408 |
axes_actor.GetZPlusFaceProperty().SetColor(z_color.float_rgb) |
| 409 |
axes_actor.GetZMinusFaceProperty().SetColor(z_color.float_rgb) |
| 410 |
|
| 411 |
axes_actor.GetCubeProperty().SetOpacity(opacity) |
| 412 |
axes_actor.GetCubeProperty().SetEdgeColor(edge_color.float_rgb) |
| 413 |
axes_actor.GetCubeProperty().SetEdgeVisibility(True) |
| 414 |
axes_actor.GetCubeProperty().BackfaceCullingOn() |
| 415 |
if opacity < 1.0: |
| 416 |
# Hide the text edges |
| 417 |
axes_actor.GetTextEdgesProperty().SetOpacity(0) |
| 418 |
|
| 419 |
if color_box: |
| 420 |
# Hide the cube so we can color each face |
| 421 |
axes_actor.GetCubeProperty().SetOpacity(0) |
| 422 |
axes_actor.GetCubeProperty().SetEdgeVisibility(False) |
| 423 |
|
| 424 |
cube = pv.Cube() |
| 425 |
cube.clear_data() # remove normals |
| 426 |
face_colors = np.array( |
| 427 |
[ |
| 428 |
x_face_color.int_rgb, |
| 429 |
x_face_color.int_rgb, |
| 430 |
y_face_color.int_rgb, |
| 431 |
y_face_color.int_rgb, |
| 432 |
z_face_color.int_rgb, |
| 433 |
z_face_color.int_rgb, |
| 434 |
], |
| 435 |
np.uint8, |
| 436 |
) |
| 437 |
cube.cell_data['face_colors'] = face_colors |
| 438 |
|
| 439 |
cube_mapper = _vtk.vtkPolyDataMapper() |
| 440 |
cube_mapper.SetInputData(cube) |
| 441 |
cube_mapper.SetColorModeToDirectScalars() |
| 442 |
cube_mapper.Update() |
| 443 |
|
| 444 |
cube_actor = pv.Actor(mapper=cube_mapper) |
| 445 |
cube_actor.prop.culling = 'back' |
| 446 |
cube_actor.prop.opacity = opacity |
| 447 |
|
| 448 |
prop_assembly = _vtk.vtkPropAssembly() |
| 449 |
prop_assembly.AddPart(axes_actor) |
| 450 |
prop_assembly.AddPart(cube_actor) |
| 451 |
actor = prop_assembly |
| 452 |
else: |
| 453 |
actor = axes_actor # type: ignore[assignment] |
| 454 |
|
| 455 |
_update_axes_label_color(actor, label_color) |
| 456 |
|
| 457 |
return actor |
| 458 |
|
| 459 |
|
| 460 |
def create_north_arrow(): |
| 461 |
"""Create a north arrow mesh. |
| 462 |
|
| 463 |
.. versionadded:: 0.44.0 |
| 464 |
|
| 465 |
Returns |
| 466 |
------- |
| 467 |
pyvista.PolyData |
| 468 |
North arrow mesh. |
| 469 |
|
| 470 |
""" |
| 471 |
points = np.array( |
| 472 |
[ |
| 473 |
[0.0, 5.0, 0.0], |
| 474 |
[-2.0, 0.0, 0.0], |
| 475 |
[0.0, 1.5, 0.0], |
| 476 |
[2.0, 0.0, 0.0], |
| 477 |
[0.0, 5.0, 1.0], |
| 478 |
[-2.0, 0.0, 1.0], |
| 479 |
[0.0, 1.5, 1.0], |
| 480 |
[2.0, 0.0, 1.0], |
| 481 |
], |
| 482 |
) |
| 483 |
faces = np.array( |
| 484 |
[ |
| 485 |
4, |
| 486 |
3, |
| 487 |
7, |
| 488 |
4, |
| 489 |
0, |
| 490 |
4, |
| 491 |
2, |
| 492 |
6, |
| 493 |
7, |
| 494 |
3, |
| 495 |
4, |
| 496 |
1, |
| 497 |
5, |
| 498 |
6, |
| 499 |
2, |
| 500 |
4, |
| 501 |
0, |
| 502 |
4, |
| 503 |
5, |
| 504 |
1, |
| 505 |
4, |
| 506 |
0, |
| 507 |
1, |
| 508 |
2, |
| 509 |
3, |
| 510 |
4, |
| 511 |
4, |
| 512 |
7, |
| 513 |
6, |
| 514 |
5, |
| 515 |
], |
| 516 |
) |
| 517 |
return pv.PolyData(points, faces) |
| 518 |
|
| 519 |
|
| 520 |
def normalize(x, minimum=None, maximum=None): |
| 521 |
"""Normalize the given value between [minimum, maximum]. |
| 522 |
|
| 523 |
Parameters |
| 524 |
---------- |
| 525 |
x : numpy.ndarray |
| 526 |
The array of values to normalize. |
| 527 |
minimum : float, optional |
| 528 |
The minimum value to which ``x`` should be normalized. If not specified, |
| 529 |
the minimum value in ``x`` will be used. |
| 530 |
maximum : float, optional |
| 531 |
The maximum value to which ``x`` should be normalized. If not specified, |
| 532 |
the maximum value in ``x`` will be used. |
| 533 |
|
| 534 |
Returns |
| 535 |
------- |
| 536 |
numpy.ndarray |
| 537 |
The normalized array of values, where the values are scaled to the |
| 538 |
range ``[minimum, maximum]``. |
| 539 |
|
| 540 |
""" |
| 541 |
if minimum is None: |
| 542 |
minimum = np.nanmin(x) |
| 543 |
if maximum is None: |
| 544 |
maximum = np.nanmax(x) |
| 545 |
return (x - minimum) / (maximum - minimum) |
| 546 |
|
| 547 |
|
| 548 |
@_deprecate_positional_args(allowed=['mapping', 'n_colors']) |
| 549 |
def opacity_transfer_function( # noqa: PLR0917 |
| 550 |
mapping, |
| 551 |
n_colors, |
| 552 |
interpolate: bool = True, # noqa: FBT001, FBT002 |
| 553 |
kind='linear', |
| 554 |
): |
| 555 |
"""Get the opacity transfer function for a mapping. |
| 556 |
|
| 557 |
These values will map on to a scalar bar range and thus the number of |
| 558 |
colors (``n_colors``) must correspond to the number of colors in the color |
| 559 |
mapping that these opacities are associated to. |
| 560 |
|
| 561 |
If interpolating, ``scipy.interpolate.interp1d`` is used if available, |
| 562 |
otherwise ``np.interp`` is used. The ``kind`` argument controls the kind of |
| 563 |
interpolation for ``interp1d``. |
| 564 |
|
| 565 |
This returns the opacity range from 0 to 255, where 0 is totally |
| 566 |
transparent and 255 is totally opaque. |
| 567 |
|
| 568 |
The equation to create the sigmoid mapping is: ``1 / (1 + exp(-x))`` where |
| 569 |
``x`` is the range from ``-a`` to ``+a`` and ``a`` is the value given in |
| 570 |
the ``mapping`` string. Default is ``a=10`` for 'sigmoid' mapping. |
| 571 |
|
| 572 |
Parameters |
| 573 |
---------- |
| 574 |
mapping : list[float] | str |
| 575 |
The opacity mapping to use. Can be a ``str`` name of a predefined |
| 576 |
mapping including ``'linear'``, ``'geom'``, ``'sigmoid'``, |
| 577 |
``'sigmoid_1-10,15,20'``, and ``foreground``. Append an ``'_r'`` to any |
| 578 |
of those names (except ``foreground``) to reverse that mapping. |
| 579 |
The mapping can also be a custom user-defined array/list of values |
| 580 |
that will be interpolated across the ``n_color`` range. |
| 581 |
|
| 582 |
n_colors : int |
| 583 |
The number of colors that the opacities must be mapped to. |
| 584 |
|
| 585 |
interpolate : bool |
| 586 |
Flag on whether or not to interpolate the opacity mapping for all |
| 587 |
colors. |
| 588 |
|
| 589 |
kind : str |
| 590 |
The interpolation kind if ``interpolate`` is ``True`` and ``scipy`` |
| 591 |
is available. If ``scipy`` is not available, linear interpolation |
| 592 |
is always used. Options are: |
| 593 |
|
| 594 |
- ``'linear'`` |
| 595 |
- ``'nearest'`` |
| 596 |
- ``'zero'`` |
| 597 |
- ``'slinear'`` |
| 598 |
- ``'quadratic'`` |
| 599 |
- ``'cubic'`` |
| 600 |
- ``'previous'`` |
| 601 |
- ``'next'`` |
| 602 |
|
| 603 |
.. versionchanged:: 0.46 |
| 604 |
|
| 605 |
Linear interpolation is now always used by default. Previously, |
| 606 |
quadratic interpolation was used if ``scipy`` was installed. |
| 607 |
|
| 608 |
Returns |
| 609 |
------- |
| 610 |
numpy.ndarray |
| 611 |
Array of ``numpy.uint8`` values ``n_colors`` long containing the |
| 612 |
[0-255] opacity mapping values. |
| 613 |
|
| 614 |
Examples |
| 615 |
-------- |
| 616 |
>>> import pyvista as pv |
| 617 |
>>> # Fetch the `sigmoid` mapping between 0 and 255 |
| 618 |
>>> tf = pv.opacity_transfer_function('sigmoid', 256) |
| 619 |
>>> # Fetch the `geom_r` mapping between 0 and 1 |
| 620 |
>>> tf = pv.opacity_transfer_function('geom_r', 256).astype(float) / 255.0 |
| 621 |
>>> # Interpolate a user defined opacity mapping |
| 622 |
>>> opacity = [0, 0.2, 0.9, 0.6, 0.3] |
| 623 |
>>> tf = pv.opacity_transfer_function(opacity, 256) |
| 624 |
|
| 625 |
""" |
| 626 |
sigmoid = lambda x: np.array(1 / (1 + np.exp(-x)) * 255, dtype=np.uint8) |
| 627 |
transfer_func = { |
| 628 |
'linear': np.linspace(0, 255, n_colors, dtype=np.uint8), |
| 629 |
'geom': np.geomspace(1e-6, 255, n_colors, dtype=np.uint8), |
| 630 |
'geom_r': np.geomspace(255, 1e-6, n_colors, dtype=np.uint8), |
| 631 |
'sigmoid': sigmoid(np.linspace(-10.0, 10.0, n_colors)), |
| 632 |
'sigmoid_1': sigmoid(np.linspace(-1.0, 1.0, n_colors)), |
| 633 |
'sigmoid_2': sigmoid(np.linspace(-2.0, 2.0, n_colors)), |
| 634 |
'sigmoid_3': sigmoid(np.linspace(-3.0, 3.0, n_colors)), |
| 635 |
'sigmoid_4': sigmoid(np.linspace(-4.0, 4.0, n_colors)), |
| 636 |
'sigmoid_5': sigmoid(np.linspace(-5.0, 5.0, n_colors)), |
| 637 |
'sigmoid_6': sigmoid(np.linspace(-6.0, 6.0, n_colors)), |
| 638 |
'sigmoid_7': sigmoid(np.linspace(-7.0, 7.0, n_colors)), |
| 639 |
'sigmoid_8': sigmoid(np.linspace(-8.0, 8.0, n_colors)), |
| 640 |
'sigmoid_9': sigmoid(np.linspace(-9.0, 9.0, n_colors)), |
| 641 |
'sigmoid_10': sigmoid(np.linspace(-10.0, 10.0, n_colors)), |
| 642 |
'sigmoid_15': sigmoid(np.linspace(-15.0, 15.0, n_colors)), |
| 643 |
'sigmoid_20': sigmoid(np.linspace(-20.0, 20.0, n_colors)), |
| 644 |
'foreground': np.hstack((0, [255] * (n_colors - 1))).astype(np.uint8), |
| 645 |
} |
| 646 |
transfer_func['linear_r'] = transfer_func['linear'][::-1] |
| 647 |
transfer_func['sigmoid_r'] = transfer_func['sigmoid'][::-1] |
| 648 |
for i in range(3, 11): |
| 649 |
k = f'sigmoid_{i}' |
| 650 |
rk = f'{k}_r' |
| 651 |
transfer_func[rk] = transfer_func[k][::-1] |
| 652 |
if isinstance(mapping, str): |
| 653 |
try: |
| 654 |
return transfer_func[mapping] |
| 655 |
except KeyError: |
| 656 |
msg = ( |
| 657 |
f'Opacity transfer function ({mapping}) unknown. ' |
| 658 |
f'Valid options: {list(transfer_func.keys())}' |
| 659 |
) |
| 660 |
raise ValueError(msg) from None |
| 661 |
elif isinstance(mapping, (np.ndarray, list, tuple)): |
| 662 |
mapping = np.array(mapping) |
| 663 |
if mapping.size == n_colors: |
| 664 |
# User could pass transfer function ready for lookup table |
| 665 |
pass |
| 666 |
elif mapping.size < n_colors: |
| 667 |
# User pass custom transfer function to be linearly interpolated |
| 668 |
if np.max(mapping) > 1.0 or np.min(mapping) < 0.0: |
| 669 |
mapping = normalize(mapping) |
| 670 |
# Interpolate transfer function to match lookup table |
| 671 |
xo = np.linspace(0, n_colors, len(mapping), dtype=np.int_) |
| 672 |
xx = np.linspace(0, n_colors, n_colors, dtype=np.int_) |
| 673 |
try: |
| 674 |
if not interpolate: |
| 675 |
msg = 'No interpolation.' |
| 676 |
raise ValueError(msg) |
| 677 |
from scipy.interpolate import interp1d # noqa: PLC0415 |
| 678 |
|
| 679 |
f = interp1d(xo, mapping, kind=kind) |
| 680 |
vals = f(xx) |
| 681 |
vals[vals < 0] = 0.0 |
| 682 |
vals[vals > 1.0] = 1.0 |
| 683 |
mapping = (vals * 255.0).astype(np.uint8) |
| 684 |
|
| 685 |
except (ImportError, ValueError): |
| 686 |
# Otherwise use simple linear interp |
| 687 |
mapping = (np.interp(xx, xo, mapping) * 255).astype(np.uint8) |
| 688 |
else: |
| 689 |
msg = ( |
| 690 |
f'Transfer function cannot have more values than `n_colors`. ' |
| 691 |
f'This has {mapping.size} elements' |
| 692 |
) |
| 693 |
raise RuntimeError(msg) |
| 694 |
return mapping |
| 695 |
msg = f'Transfer function type ({type(mapping)}) not understood' |
| 696 |
raise TypeError(msg) |
| 697 |
|
| 698 |
|
| 699 |
def parse_font_family(font_family: str) -> int: |
| 700 |
"""Check and validate the given font family name. |
| 701 |
|
| 702 |
Parameters |
| 703 |
---------- |
| 704 |
font_family : str |
| 705 |
Font family name to validate. Must be one of the font names defined in |
| 706 |
the ``FONTS`` enum class. |
| 707 |
|
| 708 |
Returns |
| 709 |
------- |
| 710 |
int |
| 711 |
Corresponding integer value of the valid font family name in the |
| 712 |
``FONTS`` enum class. |
| 713 |
|
| 714 |
Raises |
| 715 |
------ |
| 716 |
ValueError |
| 717 |
If the font_family is not one of the defined font names in the ``FONTS`` |
| 718 |
enum class. |
| 719 |
|
| 720 |
""" |
| 721 |
font_family = font_family.lower() |
| 722 |
fonts = [font.name for font in FONTS] |
| 723 |
if font_family not in fonts: |
| 724 |
msg = f'Font must one of the following:\n{", ".join(fonts)}' |
| 725 |
raise ValueError(msg) |
| 726 |
return FONTS[font_family].value |
| 727 |
|
| 728 |
|
| 729 |
def check_math_text_support() -> bool: # pragma: no cover |
| 730 |
"""Raise a DeprecationError as this has been moved. |
| 731 |
|
| 732 |
Returns |
| 733 |
------- |
| 734 |
bool |
| 735 |
Returns False for compatibility. |
| 736 |
|
| 737 |
""" |
| 738 |
from pyvista.core.errors import DeprecationError # noqa: PLC0415 |
| 739 |
|
| 740 |
# Deprecated on v0.47.0, estimated removal on v0.50.0 |
| 741 |
msg = '`check_math_text_support` is now imported from `pyvista.report`' |
| 742 |
DeprecationError(msg) |
| 743 |
|
| 744 |
return False |
| 745 |
|
| 746 |
|
| 747 |
def check_matplotlib_vtk_compatibility() -> bool: # pragma: no cover |
| 748 |
"""Raise a DeprecationError as this has been moved. |
| 749 |
|
| 750 |
Returns |
| 751 |
------- |
| 752 |
bool |
| 753 |
Returns False for compatibility. |
| 754 |
|
| 755 |
""" |
| 756 |
from pyvista.core.errors import DeprecationError # noqa: PLC0415 |
| 757 |
|
| 758 |
# Deprecated on v0.47.0, estimated removal on v0.50.0 |
| 759 |
msg = '`check_matplotlib_vtk_compatibility` is now imported from `pyvista.report`' |
| 760 |
DeprecationError(msg) |
| 761 |
return False # returning bool for compatibility |