-
Notifications
You must be signed in to change notification settings - Fork 45
Implementation of matplotlib
backend for criterion_plot()
#599
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
Open
r3kste
wants to merge
4
commits into
optimagic-dev:main
Choose a base branch
from
r3kste:backend_plotting
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
e187294
Implement matplotlib backend for criterion plot
r3kste 0159fe6
Refactor plotting backend structure and remove PlotConfig class.
r3kste e167b49
Make matplotlib an optional dependency and minor refactor for clarity.
r3kste f15d982
Enhance availability check for backends. Fix issues with matplotlib i…
r3kste File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,145 @@ | ||
import abc | ||
from typing import Any | ||
|
||
import plotly.express as px | ||
import plotly.graph_objects as go | ||
|
||
from optimagic.config import IS_MATPLOTLIB_INSTALLED | ||
from optimagic.exceptions import InvalidPlottingBackendError, NotInstalledError | ||
from optimagic.visualization.plotting_utilities import LineData | ||
|
||
if IS_MATPLOTLIB_INSTALLED: | ||
import matplotlib as mpl | ||
import matplotlib.pyplot as plt | ||
|
||
# Handle the case where matplotlib is used in notebooks (inline backend) | ||
# to ensure that interactive mode is disabled to avoid double plotting. | ||
# (See: https://github.com/matplotlib/matplotlib/issues/26221) | ||
if mpl.get_backend() == "module://matplotlib_inline.backend_inline": | ||
plt.install_repl_displayhook() | ||
plt.ioff() | ||
|
||
|
||
class PlotBackend(abc.ABC): | ||
is_available: bool | ||
default_template: str | ||
|
||
@classmethod | ||
@abc.abstractmethod | ||
def get_default_palette(cls) -> list: | ||
pass | ||
|
||
@abc.abstractmethod | ||
def __init__(self, template: str | None): | ||
if template is None: | ||
template = self.default_template | ||
|
||
self.template = template | ||
self.figure: Any = None | ||
|
||
@abc.abstractmethod | ||
def add_lines(self, lines: list[LineData]) -> None: | ||
pass | ||
|
||
@abc.abstractmethod | ||
def set_labels(self, xlabel: str | None = None, ylabel: str | None = None) -> None: | ||
pass | ||
|
||
@abc.abstractmethod | ||
def set_legend_properties(self, legend_properties: dict[str, Any]) -> None: | ||
pass | ||
|
||
|
||
class PlotlyBackend(PlotBackend): | ||
is_available: bool = True | ||
default_template: str = "simple_white" | ||
|
||
@classmethod | ||
def get_default_palette(cls) -> list: | ||
return px.colors.qualitative.Set2 | ||
|
||
def __init__(self, template: str | None): | ||
super().__init__(template) | ||
self._fig = go.Figure() | ||
self._fig.update_layout(template=self.template) | ||
self.figure = self._fig | ||
|
||
def add_lines(self, lines: list[LineData]) -> None: | ||
for line in lines: | ||
trace = go.Scatter( | ||
x=line.x, | ||
y=line.y, | ||
name=line.name, | ||
mode="lines", | ||
line_color=line.color, | ||
showlegend=line.show_in_legend, | ||
connectgaps=True, | ||
) | ||
self._fig.add_trace(trace) | ||
|
||
def set_labels(self, xlabel: str | None = None, ylabel: str | None = None) -> None: | ||
self._fig.update_layout(xaxis_title_text=xlabel, yaxis_title_text=ylabel) | ||
|
||
def set_legend_properties(self, legend_properties: dict[str, Any]) -> None: | ||
self._fig.update_layout(legend=legend_properties) | ||
|
||
|
||
class MatplotlibBackend(PlotBackend): | ||
is_available: bool = IS_MATPLOTLIB_INSTALLED | ||
default_template: str = "default" | ||
|
||
@classmethod | ||
def get_default_palette(cls) -> list: | ||
return [mpl.colormaps["Set2"](i) for i in range(mpl.colormaps["Set2"].N)] | ||
|
||
def __init__(self, template: str | None): | ||
super().__init__(template) | ||
plt.style.use(self.template) | ||
self._fig, self._ax = plt.subplots() | ||
self.figure = self._fig | ||
|
||
def add_lines(self, lines: list[LineData]) -> None: | ||
for line in lines: | ||
self._ax.plot( | ||
line.x, | ||
line.y, | ||
color=line.color, | ||
label=line.name if line.show_in_legend else None, | ||
) | ||
|
||
def set_labels(self, xlabel: str | None = None, ylabel: str | None = None) -> None: | ||
self._ax.set(xlabel=xlabel, ylabel=ylabel) | ||
|
||
def set_legend_properties(self, legend_properties: dict[str, Any]) -> None: | ||
self._ax.legend(**legend_properties) | ||
|
||
|
||
PLOT_BACKEND_CLASSES = { | ||
"plotly": PlotlyBackend, | ||
"matplotlib": MatplotlibBackend, | ||
} | ||
|
||
|
||
def get_plot_backend_class(backend_name: str) -> type[PlotBackend]: | ||
if backend_name not in PLOT_BACKEND_CLASSES: | ||
msg = ( | ||
f"Invalid backend name '{backend_name}'. " | ||
f"Supported backends are: {', '.join(PLOT_BACKEND_CLASSES.keys())}." | ||
) | ||
raise InvalidPlottingBackendError(msg) | ||
|
||
return _get_backend_if_installed(backend_name) | ||
|
||
|
||
def _get_backend_if_installed(backend_name: str) -> type[PlotBackend]: | ||
plot_cls = PLOT_BACKEND_CLASSES[backend_name] | ||
|
||
if not plot_cls.is_available: | ||
msg = ( | ||
f"The '{backend_name}' backend is not installed. " | ||
f"Install the package using either 'pip install {backend_name}' or " | ||
f"'conda install -c conda-forge {backend_name}'" | ||
) | ||
raise NotInstalledError(msg) | ||
|
||
return plot_cls |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.