Page MenuHomec4science

scipy_engine_base.py
No OneTemporary

File Metadata

Created
Wed, May 22, 07:04

scipy_engine_base.py

# Copyright (C) 2018-2020 by the RROMPy authors
#
# This file is part of RROMPy.
#
# RROMPy is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# RROMPy is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with RROMPy. If not, see <http://www.gnu.org/licenses/>.
#
import numpy as np
from matplotlib import pyplot as plt
from .hfengine_base import HFEngineBase
from rrompy.utilities.base.types import Np1D, strLst, List, Tuple, FigHandle
from rrompy.utilities.base.data_structures import purgeList, getNewFilename
from rrompy.utilities.exception_manager import RROMPyException
from rrompy.utilities.parallel import masterCore, bcast
__all__ = ['ScipyEngineBase', 'ScipyEngineBaseTensorized']
def checknports(eng) -> int:
if not hasattr(eng, "nports"):
raise RROMPyException(("Engine.nports should be assigned before using "
"tensorized plotting functionalities."))
return eng.nports
class ScipyEngineBase(HFEngineBase):
"""Generic solver for parametric matricial problems."""
def plot(self, u:Np1D, warping : List[callable] = None,
is_state : bool = False, name : str = "u", save : str = None,
what : strLst = 'all', forceNewFile : bool = True,
saveFormat : str = "eps", saveDPI : int = 100, show : bool = True,
colorMap : str = "jet", pyplotArgs : dict = {},
**figspecs) -> Tuple[FigHandle, str]:
"""
Do some nice plots of the complex-valued function with given dofs.
Args:
u: numpy complex array with function dofs.
name(optional): Name to be shown as title of the plots. Defaults to
'u'.
is_state(optional): whether given u is value before multiplication
by c. Defaults to False.
save(optional): Where to save plot(s). Defaults to None, i.e. no
saving.
what(optional): Which plots to do. If list, can contain 'ABS',
'PHASE', 'REAL', 'IMAG'. If str, same plus wildcard 'ALL'.
Defaults to 'ALL'.
forceNewFile(optional): Whether to create new output file.
saveFormat(optional): Format for saved plot(s). Defaults to "eps".
saveDPI(optional): DPI for saved plot(s). Defaults to 100.
show(optional): Whether to show figure. Defaults to True.
colorMap(optional): Pyplot colormap. Defaults to 'jet'.
pyplotArgs(optional): Optional arguments for pyplot.
figspecs(optional key args): Optional arguments for matplotlib
figure creation.
Returns:
Output filename and figure handle.
"""
if isinstance(what, (str,)):
if what.upper() == 'ALL':
what = ['ABS', 'PHASE', 'REAL', 'IMAG']
else:
what = [what]
what = purgeList(what, ['ABS', 'PHASE', 'REAL', 'IMAG'],
listname = self.name() + ".what", baselevel = 1)
if len(what) == 0: return
out = None
if masterCore():
if 'figsize' not in figspecs.keys():
figspecs['figsize'] = plt.figaspect(1. / len(what))
idxs = np.arange(len(u))
if warping is not None:
idxs = warping[0](idxs)
subplotidx = 0
fig = plt.figure(**figspecs)
plt.set_cmap(colorMap)
if 'ABS' in what:
subplotidx = subplotidx + 1
ax = fig.add_subplot(1, len(what), subplotidx)
ax.plot(idxs, np.abs(u), **pyplotArgs)
ax.set_title("|{0}|".format(name))
if 'PHASE' in what:
subplotidx = subplotidx + 1
ax = fig.add_subplot(1, len(what), subplotidx)
ax.plot(idxs, np.angle(u), **pyplotArgs)
ax.set_title("phase({0})".format(name))
if 'REAL' in what:
subplotidx = subplotidx + 1
ax = fig.add_subplot(1, len(what), subplotidx)
ax.plot(idxs, np.real(u), **pyplotArgs)
ax.set_title("Re({0})".format(name))
if 'IMAG' in what:
subplotidx = subplotidx + 1
ax = fig.add_subplot(1, len(what), subplotidx)
ax.plot(idxs, np.imag(u), **pyplotArgs)
ax.set_title("Im({0})".format(name))
plt.tight_layout()
if save is not None:
save = save.strip()
if forceNewFile:
fileOut = getNewFilename("{}_fig_".format(save),
saveFormat)
else:
fileOut = "{}_fig.{}".format(save, saveFormat)
fig.savefig(fileOut, format = saveFormat, dpi = saveDPI)
else: fileOut = None
if show: plt.show()
out = fig if fileOut is None else (fig, fileOut)
return bcast(out)
class ScipyEngineBaseTensorized(ScipyEngineBase):
"""The number of tensorized dimensions should be assigned to nports."""
def plot(self, u:Np1D, *args, **kwargs) -> Tuple[FigHandle, str]:
return super().plot(u.reshape(-1, checknports(self)), *args, **kwargs)

Event Timeline