Skip to content

Commit

Permalink
Merge branch 'main' into fix/plot-twice
Browse files Browse the repository at this point in the history
  • Loading branch information
germa89 committed Jun 27, 2023
2 parents 840d345 + f94ae09 commit 423e301
Show file tree
Hide file tree
Showing 6 changed files with 122 additions and 38 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/dependabot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ jobs:
steps:
- uses: marcoroth/dependabot-bump-together-action@main
with:
dependencies: ansys-api-mapdl, vtk, ansys-corba, ansys-dpf-core, ansys-mapdl-reader, ansys-platform-instancemanagement, ansys-sphinx-theme, pyansys-tools-report, platformdirs, autopep8, click, imageio-ffmpeg, imageio, importlib-metadata, jupyter_sphinx, jupyterlab, matplotlib, numpy, numpydoc, pandas, pexpect, plotly, protobuf, pyiges, pypandoc, pytest-cov, pytest-rerunfailures, pytest-sphinx, pytest, pythreejs, pyvista, scipy, setuptools, sphinx-autobuild, sphinx-autodoc-typehints, sphinx-copybutton, sphinx-gallery, sphinx-notfound-page, sphinxcontrib-websupport, sphinxemoji, tqdm, wheel
dependencies: ansys-api-mapdl, vtk, ansys-corba, ansys-dpf-core, ansys-mapdl-reader, ansys-platform-instancemanagement, ansys-sphinx-theme, pyansys-tools-report, platformdirs, autopep8, click, imageio-ffmpeg, imageio, importlib-metadata, jupyter_sphinx, jupyterlab, matplotlib, numpy, numpydoc, pandas, pexpect, plotly, protobuf, pyiges, pypandoc, pytest-cov, pytest-rerunfailures, pytest-sphinx, pytest, pythreejs, pyvista, scipy, setuptools, sphinx-autobuild, sphinx-copybutton, sphinx-gallery, sphinx-notfound-page, sphinxcontrib-websupport, sphinxemoji, tqdm, wheel #sphinx-autodoc-typehints
package_managers: pip
directory: /
branch: main
Expand Down
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,9 @@ tests = [
"ansys-dpf-core==0.8.1",
"autopep8==2.0.2",
"matplotlib==3.7.1",
"scipy==1.10.1",
"scipy==1.11.0",
"pandas==2.0.2",
"pytest==7.3.2",
"pytest==7.4.0",
"pytest-cov==4.1.0",
"pyvista==0.39.1",
"pyansys-tools-report==0.5.0",
Expand Down
2 changes: 1 addition & 1 deletion src/ansys/mapdl/core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@

# Per contract with Sphinx-Gallery, this method must be available at top level
try:
from pyvista.utilities.sphinx_gallery import _get_sg_image_scraper
import pyvista

_HAS_PYVISTA = True
except ModuleNotFoundError: # pragma: no cover
Expand Down
109 changes: 79 additions & 30 deletions src/ansys/mapdl/core/mapdl.py
Original file line number Diff line number Diff line change
Expand Up @@ -1813,7 +1813,7 @@ def __init__(self, parent: "_MapdlCore", pixel_res: int) -> None:
def __enter__(self) -> None:
self._parent()._log.debug("Entering in 'WithInterativePlotting' mode")

if not self._parent()._has_matplotlib:
if not self._parent()._has_matplotlib: # pragma: no cover
raise ImportError(
"Install matplotlib to display plots from MAPDL ,"
"from Python. Otherwise, plot with vtk with:\n"
Expand All @@ -1824,6 +1824,13 @@ def __enter__(self) -> None:
self._parent().show("PNG", mute=True)
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)

def __exit__(self, *args) -> None:
self._parent()._log.debug("Exiting in 'WithInterativePlotting' mode")
self._parent().show("close", mute=True)
Expand Down Expand Up @@ -3027,7 +3034,12 @@ def run(self, command, write_to_log=True, mute=None, **kwargs) -> str:

if short_cmd in PLOT_COMMANDS:
self._log.debug("It is a plot command.")
return self._display_plot(self._response)
plot_path = self._get_plot_name(text)
save_fig = kwargs.get("savefig", False)
if save_fig:
self._download_plot(plot_path, save_fig)
else:
return self._display_plot(plot_path)

return self._response

Expand Down Expand Up @@ -3504,18 +3516,8 @@ def _get_array(
else:
return array

def _display_plot(self, text):
"""Display the last generated plot (*.png) from MAPDL"""

def in_ipython():
# from scooby.in_ipython
# to avoid dependency here.
try:
__IPYTHON__
return True
except NameError:
return False

def _get_plot_name(self, text: str) -> str:
""" "Obtain the plot filename. It also downloads it if in remote session."""
self._log.debug(text)
png_found = PNG_IS_WRITTEN_TO_FILE.findall(text)

Expand All @@ -3524,31 +3526,78 @@ def in_ipython():
self.show("CLOSE", mute=True)
# self.show("PNG", mute=True)

import matplotlib.image as mpimg
import matplotlib.pyplot as plt

filename = self._screenshot_path()
self._log.debug(f"Screenshot at: {filename}")

if os.path.isfile(filename):
self._log.debug("A screenshot file has been found.")
img = mpimg.imread(filename)
plt.imshow(img)
plt.axis("off")
if self._show_matplotlib_figures: # pragma: no cover
self._log.debug("Using Matplotlib to plot")
plt.show() # consider in-line plotting
if in_ipython():
self._log.debug("Using ipython")
from IPython.display import display

display(plt.gcf())

return filename
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.")

def _display_plot(self, filename: str) -> None:
"""Display the last generated plot (*.png) from MAPDL"""
import matplotlib.image as mpimg
import matplotlib.pyplot as plt

def in_ipython():
# from scooby.in_ipython
# to avoid dependency here.
try:
__IPYTHON__
return True
except NameError: # pragma: no cover
return False

self._log.debug("A screenshot file has been found.")
img = mpimg.imread(filename)
plt.imshow(img)
plt.axis("off")

if self._show_matplotlib_figures: # pragma: no cover
self._log.debug("Using Matplotlib to plot")
plt.show() # consider in-line plotting

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

display(plt.gcf())

def _download_plot(self, filename: str, plot_name: str) -> None:
"""Copy the temporary download plot to the working directory."""
if isinstance(plot_name, str):
provided = True
path_ = pathlib.Path(plot_name)
plot_name = path_.name
plot_stem = path_.stem
plot_ext = path_.suffix
plot_path = str(path_.parent)
if not plot_path or plot_path == ".":
plot_path = os.getcwd()

elif isinstance(plot_name, bool):
provided = False
plot_name = "plot.png"
plot_stem = "plot"
plot_ext = ".png"
plot_path = os.getcwd()
else: # pragma: no cover
raise ValueError("Only booleans and str are allowed.")

id_ = 0
plot_path_ = os.path.join(plot_path, plot_name)
while os.path.exists(plot_path_) and not provided:
id_ += 1
plot_path_ = os.path.join(plot_path, f"{plot_stem}_{id_}{plot_ext}")
else:
copyfile(filename, plot_path_)

self._log.debug(
f"Copy plot file from temp directory to working directory as: {plot_path}"
)

def _screenshot_path(self):
"""Return last filename based on the current jobname"""
filenames = glob.glob(os.path.join(self.directory, f"{self.jobname}*.png"))
Expand Down
5 changes: 1 addition & 4 deletions src/ansys/mapdl/core/mapdl_geometry.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,7 @@ def merge_polydata(items):
"""Merge list of polydata or unstructured grids"""

# lazy import here for faster module loading
try:
from pyvista._vtk import vtkAppendPolyData
except:
from vtk import vtkAppendPolyData
from vtkmodules.vtkFiltersCore import vtkAppendPolyData

afilter = vtkAppendPolyData()
for item in items:
Expand Down
38 changes: 38 additions & 0 deletions tests/test_mapdl.py
Original file line number Diff line number Diff line change
Expand Up @@ -1984,6 +1984,44 @@ def test_download_results_non_local(mapdl, cube_solve):
assert isinstance(mapdl.result, Result)


def test_download_file_with_vkt_false(mapdl, cube_solve, tmpdir):
# Testing basic behaviour
mapdl.eplot(vtk=False, savefig="myfile.png")
assert os.path.exists("myfile.png")
ti_m = os.path.getmtime("myfile.png")

# Testing overwriting
mapdl.eplot(vtk=False, savefig="myfile.png")
assert not os.path.exists("myfile_1.png")
assert os.path.getmtime("myfile.png") != ti_m # file has been modified.

os.remove("myfile.png")

# Testing no extension
mapdl.eplot(vtk=False, savefig="myfile")
assert os.path.exists("myfile")
os.remove("myfile")

# Testing update name when file exists.
mapdl.eplot(vtk=False, savefig=True)
assert os.path.exists("plot.png")

mapdl.eplot(vtk=False, savefig=True)
assert os.path.exists("plot_1.png")

os.remove("plot.png")
os.remove("plot_1.png")

# Testing full path for downloading
plot_ = os.path.join(tmpdir, "myplot.png")
mapdl.eplot(vtk=False, savefig=plot_)
assert os.path.exists(plot_)

plot_ = os.path.join(tmpdir, "myplot")
mapdl.eplot(vtk=False, savefig=plot_)
assert os.path.exists(plot_)


def test_plots_no_vtk(mapdl):
mapdl.kplot(vtk=False)
mapdl.lplot(vtk=False)
Expand Down

0 comments on commit 423e301

Please sign in to comment.