Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixing area coloring #2195

Merged
merged 23 commits into from
Jul 28, 2023
Merged
Show file tree
Hide file tree
Changes from 16 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
66 changes: 49 additions & 17 deletions src/ansys/mapdl/core/mapdl.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from warnings import warn
import weakref

from matplotlib.colors import to_rgba
import numpy as np
from numpy._typing import DTypeLike
from numpy.typing import NDArray
Expand Down Expand Up @@ -55,6 +56,7 @@
supress_logging,
wrap_point_SEL,
)
from ansys.mapdl.core.theme import PyMAPDL_cmap

if TYPE_CHECKING: # pragma: no cover
from ansys.mapdl.reader import Archive
Expand Down Expand Up @@ -905,7 +907,7 @@
from ansys.mapdl.core.mapdl_geometry import Geometry, LegacyGeometry

if self.legacy_geometry:
return LegacyGeometry

Check warning on line 910 in src/ansys/mapdl/core/mapdl.py

View check run for this annotation

Codecov / codecov/patch

src/ansys/mapdl/core/mapdl.py#L910

Added line #L910 was not covered by tests
else:
return Geometry(self)

Expand Down Expand Up @@ -1714,11 +1716,14 @@
show_line_numbering : bool, optional
Display line numbers when ``vtk=True``.

color_areas : np.array, optional
color_areas : Union[bool, str, np.array], optional
Only used when ``vtk=True``.
If ``color_areas`` is a bool, randomly color areas when ``True`` .
If ``color_areas`` is an array or list, it colors each area with
the RGB colors, specified in that array or list.
If ``color_areas`` is a bool, randomly color areas when ``True``.
If ``color_areas`` is a string, it must be a valid color string
which will be applied to all areas.
If ``color_areas`` is an array or list made of color names (str) or
the RGBa numbers ([R, G, B, transparency]), it colors each area with
the colors, specified in that array or list.

show_lines : bool, optional
Plot lines and areas. Change the thickness of the lines
Expand Down Expand Up @@ -1778,36 +1783,63 @@
meshes = []
labels = []

anums = np.unique(surf["entity_num"])

# individual surface isolation is quite slow, so just
# color individual areas
if color_areas:
# if isinstance(color_areas, np.ndarray) and len(or len(color_areas):
if (isinstance(color_areas, np.ndarray) and len(color_areas) > 1) or (
not isinstance(color_areas, np.ndarray) and color_areas
):
if isinstance(color_areas, bool):
anum = surf["entity_num"]
size_ = max(anum) + 1
# Because this is only going to be used for plotting purpuses, we don't need to allocate
size_ = len(anums)
# Because this is only going to be used for plotting
# purposes, we don't need to allocate
# a huge vector with random numbers (colours).
# By default `pyvista.DataSetMapper.set_scalars` `n_colors` argument is set to 256, so let
# do here the same.
# We will limit the number of randoms values (colours) to 256
# By default `pyvista.DataSetMapper.set_scalars` `n_colors`
# argument is set to 256, so let do here the same.
# We will limit the number of randoms values (colours)
# to 256.
#
# Link: https://docs.pyvista.org/api/plotting/_autosummary/pyvista.DataSetMapper.set_scalars.html#pyvista.DataSetMapper.set_scalars
size_ = min([256, size_])
# Generating a colour array,
# Size = number of areas.
# Values are random between 0 and min(256, number_areas)
area_color = np.random.choice(range(size_), size=(len(anum), 3))
colors = PyMAPDL_cmap(anums)

elif isinstance(color_areas, str):
# A color is provided as a string
colors = np.atleast_2d(np.array(to_rgba(color_areas)))

Check warning on line 1813 in src/ansys/mapdl/core/mapdl.py

View check run for this annotation

Codecov / codecov/patch

src/ansys/mapdl/core/mapdl.py#L1813

Added line #L1813 was not covered by tests

else:
if len(surf["entity_num"]) != len(color_areas):
if len(anums) != len(color_areas):
raise ValueError(
f"The length of the parameter array 'color_areas' should be the same as the number of areas."
"The length of the parameter array 'color_areas' "
"should be the same as the number of areas."
f"\nanums: {anums}"
f"\ncolor_areas: {color_areas}"
)
area_color = color_areas
meshes.append({"mesh": surf, "scalars": area_color})

if isinstance(color_areas[0], str):
colors = np.array([to_rgba(each) for each in color_areas])

Check warning on line 1825 in src/ansys/mapdl/core/mapdl.py

View check run for this annotation

Codecov / codecov/patch

src/ansys/mapdl/core/mapdl.py#L1824-L1825

Added lines #L1824 - L1825 were not covered by tests
else:
colors = color_areas

Check warning on line 1827 in src/ansys/mapdl/core/mapdl.py

View check run for this annotation

Codecov / codecov/patch

src/ansys/mapdl/core/mapdl.py#L1827

Added line #L1827 was not covered by tests

# mapping mapdl areas to pyvista mesh cells
def mapper(each):
if len(colors) == 1:
# for the case colors comes from string.
return colors[0]
return colors[each - 1]

Check warning on line 1834 in src/ansys/mapdl/core/mapdl.py

View check run for this annotation

Codecov / codecov/patch

src/ansys/mapdl/core/mapdl.py#L1834

Added line #L1834 was not covered by tests

colors_map = np.array(list(map(mapper, surf["entity_num"])))
meshes.append({"mesh": surf, "scalars": colors_map})

else:
meshes.append({"mesh": surf, "color": kwargs.get("color", "white")})

if show_area_numbering:
anums = np.unique(surf["entity_num"])
centers = []
for anum in anums:
area = surf.extract_cells(surf["entity_num"] == anum)
Expand All @@ -1821,7 +1853,7 @@
self.cm("__area__", "AREA", mute=True)
self.lsla("S", mute=True)

lines = self.geometry.get_lines()

Check warning on line 1856 in src/ansys/mapdl/core/mapdl.py

View check run for this annotation

Codecov / codecov/patch

src/ansys/mapdl/core/mapdl.py#L1856

Added line #L1856 was not covered by tests
self.cmsel("S", "__area__", "AREA", mute=True)

if show_lines:
Expand Down Expand Up @@ -1879,11 +1911,11 @@
self._parent().gfile(self._pixel_res, mute=True)

def __exit__(self, *args) -> None:
self._parent()._log.debug("Exiting in 'WithInterativePlotting' mode")
self._parent().show("close", mute=True)
if not self._parent()._png_mode:
self._parent().show("PNG", mute=True)
self._parent().gfile(self._pixel_res, mute=True)

Check warning on line 1918 in src/ansys/mapdl/core/mapdl.py

View check run for this annotation

Codecov / codecov/patch

src/ansys/mapdl/core/mapdl.py#L1914-L1918

Added lines #L1914 - L1918 were not covered by tests

def __exit__(self, *args) -> None:
self._parent()._log.debug("Exiting in 'WithInterativePlotting' mode")
Expand Down Expand Up @@ -2012,7 +2044,7 @@
)
return general_plotter([], [], [], **kwargs)

lines = self.geometry.get_lines()

Check warning on line 2047 in src/ansys/mapdl/core/mapdl.py

View check run for this annotation

Codecov / codecov/patch

src/ansys/mapdl/core/mapdl.py#L2047

Added line #L2047 was not covered by tests
meshes = [{"mesh": lines}]
if color_lines:
meshes[0]["scalars"] = np.random.random(lines.n_cells)
Expand Down Expand Up @@ -3605,7 +3637,7 @@
else: # pragma: no cover
self._log.error("Unable to find screenshot at %s", filename)
else:
self._log.error("Unable to find file in MAPDL command output.")

Check warning on line 3640 in src/ansys/mapdl/core/mapdl.py

View check run for this annotation

Codecov / codecov/patch

src/ansys/mapdl/core/mapdl.py#L3640

Added line #L3640 was not covered by tests

def _display_plot(self, filename: str) -> None:
"""Display the last generated plot (*.png) from MAPDL"""
Expand All @@ -3617,7 +3649,7 @@
# to avoid dependency here.
try:
__IPYTHON__
return True

Check warning on line 3652 in src/ansys/mapdl/core/mapdl.py

View check run for this annotation

Codecov / codecov/patch

src/ansys/mapdl/core/mapdl.py#L3652

Added line #L3652 was not covered by tests
except NameError: # pragma: no cover
return False

Expand All @@ -3631,10 +3663,10 @@
plt.show() # consider in-line plotting

if in_ipython():
self._log.debug("Using ipython")
from IPython.display import display

Check warning on line 3667 in src/ansys/mapdl/core/mapdl.py

View check run for this annotation

Codecov / codecov/patch

src/ansys/mapdl/core/mapdl.py#L3666-L3667

Added lines #L3666 - L3667 were not covered by tests

display(plt.gcf())

Check warning on line 3669 in src/ansys/mapdl/core/mapdl.py

View check run for this annotation

Codecov / codecov/patch

src/ansys/mapdl/core/mapdl.py#L3669

Added line #L3669 was not covered by tests

def _download_plot(self, filename: str, plot_name: str) -> None:
"""Copy the temporary download plot to the working directory."""
Expand Down
17 changes: 16 additions & 1 deletion src/ansys/mapdl/core/plotting.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
"""Plotting helper for MAPDL using pyvista"""
from typing import Any, Optional
from warnings import warn

import numpy as np
from numpy.typing import NDArray

from ansys.mapdl.core import _HAS_PYVISTA
from ansys.mapdl.core.misc import get_bounding_box, unique_rows
Expand Down Expand Up @@ -420,9 +422,21 @@ def _general_plotter(
)

for mesh in meshes:
scalars: Optional[NDArray[Any]] = mesh.get("scalars")

if (
"scalars" in mesh
and scalars.ndim == 2
and (scalars.shape[1] == 3 or scalars.shape[1] == 4)
):
# for the case we are using scalars for plotting
rgb = True
else:
rgb = False

plotter.add_mesh(
mesh["mesh"],
scalars=mesh.get("scalars"),
scalars=scalars,
scalar_bar_args=scalar_bar_args,
color=mesh.get("color", color),
style=mesh.get("style", style),
Expand All @@ -442,6 +456,7 @@ def _general_plotter(
cmap=cmap,
render_points_as_spheres=render_points_as_spheres,
render_lines_as_tubes=render_lines_as_tubes,
rgb=rgb,
**add_mesh_kwargs,
)

Expand Down
2 changes: 1 addition & 1 deletion src/ansys/mapdl/core/theme.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@

try: # new in pyvista 0.40
from pyvista.themes import Theme
except ImportError:
from pyvista.themes import DefaultTheme as Theme

Check warning on line 13 in src/ansys/mapdl/core/theme.py

View check run for this annotation

Codecov / codecov/patch

src/ansys/mapdl/core/theme.py#L12-L13

Added lines #L12 - L13 were not covered by tests

base_class = Theme

Expand Down Expand Up @@ -40,7 +40,7 @@
/ 255
)

PyMAPDL_cmap = ListedColormap(MAPDL_colorbar)
PyMAPDL_cmap: ListedColormap = ListedColormap(MAPDL_colorbar, name="PyMAPDL", N=255)


class MapdlTheme(base_class):
Expand Down
39 changes: 39 additions & 0 deletions tests/test_plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -569,6 +569,45 @@ def test_vsel_iterable(mapdl, make_block):
)


def test_color_areas(mapdl, make_block):
pl = mapdl.aplot(vtk=True, color_areas=True, return_plotter=True)
germa89 marked this conversation as resolved.
Show resolved Hide resolved


# This is to remind us that the pl.mesh does not return data for all meshes in CICD.
@pytest.mark.xfail
def test_color_areas_fail(mapdl, make_block):
pl = mapdl.aplot(vtk=True, color_areas=True, return_plotter=True)
assert len(np.unique(pl.mesh.cell_data["Data"], axis=0)) == mapdl.geometry.n_area
germa89 marked this conversation as resolved.
Show resolved Hide resolved


@skip_no_xserver
@pytest.mark.parametrize(
"color_areas",
[
["red", "green", "blue", "yellow", "white", "purple"],
[
[255, 255, 255],
[255, 255, 0],
[255, 0, 0],
[0, 255, 0],
[0, 255, 255],
[0, 0, 0],
],
255
* np.array([[1, 1, 1], [1, 1, 0], [1, 0, 0], [0, 1, 0], [0, 1, 1], [0, 0, 0]]),
],
)
def test_color_areas_individual(mapdl, make_block, color_areas):
pl = mapdl.aplot(vtk=True, color_areas=color_areas, return_plotter=True)
assert len(np.unique(pl.mesh.cell_data["Data"], axis=0)) == len(color_areas)


def test_color_areas_error(mapdl, make_block):
color_areas = ["red", "green", "blue"]
with pytest.raises(ValueError):
mapdl.aplot(vtk=True, color_areas=color_areas)


def test_WithInterativePlotting(mapdl, make_block):
mapdl.eplot(vtk=False)
jobname = mapdl.jobname.upper()
Expand Down
Loading