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

using PNG by default for plots. #2205

Merged
merged 7 commits into from
Jul 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions doc/source/api/mapdl.rst
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@
Mapdl.input_strings
Mapdl.set_log_level
Mapdl.version
Mapdl.use_vtk
Mapdl.file_type_for_plots


Constants
Expand Down
62 changes: 62 additions & 0 deletions src/ansys/mapdl/core/mapdl.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,12 @@

DEBUG_LEVELS = Literal["DEBUG", "INFO", "WARNING", "ERROR"]

VALID_DEVICES = ["PNG", "TIFF", "VRML", "TERM", "CLOSE"]
VALID_DEVICES_LITERAL = Literal[tuple(["PNG", "TIFF", "VRML", "TERM", "CLOSE"])]

VALID_FILE_TYPE_FOR_PLOT = VALID_DEVICES.copy()
VALID_FILE_TYPE_FOR_PLOT.remove("CLOSE")
VALID_FILE_TYPE_FOR_PLOT_LITERAL = Literal[tuple(VALID_FILE_TYPE_FOR_PLOT)]

_PERMITTED_ERRORS = [
r"(\*\*\* ERROR \*\*\*).*(?:[\r\n]+.*)+highly distorted.",
Expand Down Expand Up @@ -204,6 +210,7 @@
log_file: Union[bool, str] = False,
local: bool = True,
print_com: bool = False,
file_type_for_plots: VALID_FILE_TYPE_FOR_PLOT_LITERAL = "PNG",
**start_parm,
):
"""Initialize connection with MAPDL."""
Expand All @@ -222,6 +229,8 @@
self._launched: bool = False
self._stderr = None
self._stdout = None
self._file_type_for_plots = file_type_for_plots
self._default_file_type_for_plots = file_type_for_plots

if _HAS_PYVISTA:
if use_vtk is not None: # pragma: no cover
Expand Down Expand Up @@ -331,6 +340,48 @@
"""Return true if using console to connect to the MAPDL instance."""
return self._mode == "console"

@property
def file_type_for_plots(self):
"""Returns the current file type for plotting."""
return self._file_type_for_plots

@file_type_for_plots.setter
def file_type_for_plots(self, value: VALID_DEVICES_LITERAL):
"""Modify the current file type for plotting."""
if isinstance(value, str) and value.upper() in VALID_DEVICES:
self._run(
f"/show, {value.upper()}"
) # To avoid recursion we need to use _run.
self._file_type_for_plots = value.upper()
else:
raise ValueError(f"'{value}' is not allowed as file output for plots.")

@property
def default_file_type_for_plots(self):
"""Default file type for plots.

Use when device is not properly set, for instance when the device is closed."""
return self._default_file_type_for_plots

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

View check run for this annotation

Codecov / codecov/patch

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

Added line #L364 was not covered by tests

@default_file_type_for_plots.setter
def default_file_type_for_plots(self, value: VALID_FILE_TYPE_FOR_PLOT_LITERAL):
"""Set default file type for plots.

Used when device is not properly set, for instance when the device is closed."""
if not isinstance(value, str) and value.upper() not in VALID_FILE_TYPE_FOR_PLOT:
raise ValueError(f"'{value}' is not allowed as file output for plots.")
return self._default_file_type_for_plots

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

View check run for this annotation

Codecov / codecov/patch

src/ansys/mapdl/core/mapdl.py#L371-L373

Added lines #L371 - L373 were not covered by tests

@property
def use_vtk(self):
"""Returns if using VTK by default or not."""
return self._use_vtk

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

View check run for this annotation

Codecov / codecov/patch

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

Added line #L378 was not covered by tests

@use_vtk.setter
def use_vtk(self, value: bool):
"""Set VTK to be used by default or not."""
self._use_vtk = value

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

View check run for this annotation

Codecov / codecov/patch

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

Added line #L383 was not covered by tests

def _wrap_listing_functions(self):
# Wrapping LISTING FUNCTIONS.
def wrap_listing_function(func):
Expand Down Expand Up @@ -905,7 +956,7 @@
from ansys.mapdl.core.mapdl_geometry import Geometry, LegacyGeometry

if self.legacy_geometry:
return LegacyGeometry

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

View check run for this annotation

Codecov / codecov/patch

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

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

Expand Down Expand Up @@ -1780,7 +1831,7 @@

# individual surface isolation is quite slow, so just
# color individual areas
if color_areas:

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
if isinstance(color_areas, bool):
anum = surf["entity_num"]
size_ = max(anum) + 1
Expand Down Expand Up @@ -1821,7 +1872,7 @@
self.cm("__area__", "AREA", mute=True)
self.lsla("S", mute=True)

lines = self.geometry.get_lines()

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

View check run for this annotation

Codecov / codecov/patch

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

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

if show_lines:
Expand Down Expand Up @@ -1878,13 +1929,20 @@
self._parent().show("PNG", mute=True)
self._parent().gfile(self._pixel_res, mute=True)

self.previous_device = self._parent().file_type_for_plots

if self._parent().file_type_for_plots not in ["PNG", "TIFF", "PNG", "VRML"]:
self._parent().show(self._parent().default_file_type_for_plots)

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

View check run for this annotation

Codecov / codecov/patch

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

Added line #L1935 was not covered by tests

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 1942 in src/ansys/mapdl/core/mapdl.py

View check run for this annotation

Codecov / codecov/patch

src/ansys/mapdl/core/mapdl.py#L1938-L1942

Added lines #L1938 - L1942 were not covered by tests

self._parent().file_type_for_plots = self.previous_device

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

View check run for this annotation

Codecov / codecov/patch

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

Added line #L1944 was not covered by tests

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

lines = self.geometry.get_lines()

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

View check run for this annotation

Codecov / codecov/patch

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

Added line #L2073 was not covered by tests
meshes = [{"mesh": lines}]
if color_lines:
meshes[0]["scalars"] = np.random.random(lines.n_cells)
Expand Down Expand Up @@ -3039,6 +3097,10 @@
# https://github.com/pyansys/pymapdl/issues/380
command = "/CLE,NOSTART"

# Tracking output device
if command[:4].upper() == "/SHO":
self._file_type_for_plots = command.split(",")[1].upper()

# Invalid commands silently ignored.
cmd_ = command.split(",")[0].upper()
if cmd_ in INVAL_COMMANDS_SILENT:
Expand Down Expand Up @@ -3605,7 +3667,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 3670 in src/ansys/mapdl/core/mapdl.py

View check run for this annotation

Codecov / codecov/patch

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

Added line #L3670 was not covered by tests

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

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

View check run for this annotation

Codecov / codecov/patch

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

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

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

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

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

View check run for this annotation

Codecov / codecov/patch

src/ansys/mapdl/core/mapdl.py#L3696-L3697

Added lines #L3696 - L3697 were not covered by tests

display(plt.gcf())

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

View check run for this annotation

Codecov / codecov/patch

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

Added line #L3699 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
7 changes: 7 additions & 0 deletions src/ansys/mapdl/core/mapdl_grpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,11 @@
PyPIM. This instance will be deleted when calling
:func:`Mapdl.exit <ansys.mapdl.core.Mapdl.exit>`.

file_type_for_plots: ["PNG", "TIFF", "PNG", "VRML", "TERM"], Optional
Change the default file type for plots using ``/SHOW``, by
default it is ``PNG``.


Examples
--------
Connect to an instance of MAPDL already running on locally on the
Expand Down Expand Up @@ -867,6 +872,8 @@
with self.run_as_routine("POST26"):
self.numvar(200, mute=True)

self.show(self._file_type_for_plots)

def _reset_cache(self):
"""Reset cached items."""
if self._mesh_rep is not None:
Expand Down Expand Up @@ -2190,7 +2197,7 @@

else: # remote session
if recursive:
warn(

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

View check run for this annotation

Codecov / codecov/patch

src/ansys/mapdl/core/mapdl_grpc.py#L2200

Added line #L2200 was not covered by tests
"The 'recursive' parameter is ignored if the session is non-local."
)
return self._download_from_remote(
Expand Down Expand Up @@ -2282,7 +2289,7 @@

elif isinstance(files, list):
if not all([isinstance(each, str) for each in files]):
raise ValueError(

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

View check run for this annotation

Codecov / codecov/patch

src/ansys/mapdl/core/mapdl_grpc.py#L2292

Added line #L2292 was not covered by tests
"The parameter `'files'` can be a list or tuple, but it should only contain strings."
)
list_files = []
Expand All @@ -2290,7 +2297,7 @@
list_files.extend(self._validate_files(each, extension=extension))

else:
raise ValueError(

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

View check run for this annotation

Codecov / codecov/patch

src/ansys/mapdl/core/mapdl_grpc.py#L2300

Added line #L2300 was not covered by tests
f"The `file` parameter type ({type(files)}) is not supported."
"Only strings, tuple of strings or list of strings are allowed."
)
Expand All @@ -2310,7 +2317,7 @@
) -> List[str]:
if extension is not None:
if not isinstance(extension, str):
raise TypeError(f"The extension {extension} must be a string.")

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

View check run for this annotation

Codecov / codecov/patch

src/ansys/mapdl/core/mapdl_grpc.py#L2320

Added line #L2320 was not covered by tests

if not extension.startswith("."):
extension = "." + extension
Expand Down Expand Up @@ -2811,7 +2818,7 @@
if not error_file:
return None

if self._local:

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

View check run for this annotation

Codecov / codecov/patch

src/ansys/mapdl/core/mapdl_grpc.py#L2821

Added line #L2821 was not covered by tests
return open(os.path.join(self.directory, error_file)).read()
elif self._exited:
raise MapdlExitedError(
Expand Down Expand Up @@ -3016,7 +3023,7 @@
fname = self._get_file_path(fname, kwargs.get("progress_bar", False))
file_, ext_, _ = self._decompose_fname(fname)
if self._local:
return self._file(filename=fname, **kwargs)

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

View check run for this annotation

Codecov / codecov/patch

src/ansys/mapdl/core/mapdl_grpc.py#L3026

Added line #L3026 was not covered by tests
else:
return self._file(filename=file_, extension=ext_)

Expand Down
22 changes: 22 additions & 0 deletions tests/test_plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -593,3 +593,25 @@ def filtering(file_name):

# cleaning
os.remove(last_png)


def test_file_type_for_plots(mapdl):
assert mapdl.file_type_for_plots in ["PNG", "TIFF", "PNG", "VRML", "TERM", "CLOSE"]

mapdl.file_type_for_plots = "TIFF"
assert mapdl.file_type_for_plots == "TIFF"

with pytest.raises(ValueError):
mapdl.file_type_for_plots = "asdf"

mapdl.default_plot_file_type = "PNG"
n_files_ending_png_before = len(
[each for each in mapdl.list_files() if each.endswith(".png")]
)

mapdl.eplot(vtk=False)
n_files_ending_png_after = len(
[each for each in mapdl.list_files() if each.endswith(".png")]
)

assert n_files_ending_png_before + 1 == n_files_ending_png_after
Loading