Skip to content
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: 1 addition & 1 deletion docs/examples/debyemodel.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
import numpy
from gaussianrecipe import scipyOptimize

from diffpy.srfit.fitbase import (
from diffpy.srfit import (
FitContribution,
FitRecipe,
FitResults,
Expand Down
2 changes: 1 addition & 1 deletion docs/examples/debyemodelII.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@

from debyemodel import makeRecipe, scipyOptimize

from diffpy.srfit.fitbase import FitRecipe, FitResults
from diffpy.srfit import FitRecipe, FitResults

######
# Example Code
Expand Down
2 changes: 1 addition & 1 deletion docs/examples/gaussiangenerator.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@

from numpy import exp

from diffpy.srfit.fitbase import (
from diffpy.srfit import (
FitContribution,
FitRecipe,
Profile,
Expand Down
2 changes: 1 addition & 1 deletion docs/examples/gaussianrecipe.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@

from pathlib import Path

from diffpy.srfit.fitbase import (
from diffpy.srfit import (
FitContribution,
FitRecipe,
FitResults,
Expand Down
2 changes: 1 addition & 1 deletion docs/examples/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

from pathlib import Path

from diffpy.srfit.fitbase import (
from diffpy.srfit import (
FitContribution,
FitRecipe,
FitResults,
Expand Down
2 changes: 1 addition & 1 deletion docs/examples/simplerecipe.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

from pathlib import Path

from diffpy.srfit.fitbase import SimpleRecipe
from diffpy.srfit import SimpleRecipe

######
# Example Code
Expand Down
2 changes: 1 addition & 1 deletion docs/examples/threedoublepeaks.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

import numpy

from diffpy.srfit.fitbase import (
from diffpy.srfit import (
FitContribution,
FitRecipe,
FitResults,
Expand Down
26 changes: 26 additions & 0 deletions news/export-fitbase-api.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
**Added:**

* The public ``fitbase`` classes can now be imported directly from
``diffpy.srfit``, for example ``from diffpy.srfit import FitRecipe``.

**Changed:**

* Importing ``diffpy.srfit`` no longer imports ``matplotlib.pyplot`` or
changes the global matplotlib style. ``FitRecipe.plot_recipe`` still uses
the ``bg-style`` stylesheet, but only for the figures it creates.

**Deprecated:**

* <news item>

**Removed:**

* <news item>

**Fixed:**

* <news item>

**Security:**

* <news item>
26 changes: 26 additions & 0 deletions src/diffpy/srfit/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,32 @@
##############################################################################
"""Generalized code base for modeling problems."""

__all__ = [
"Calculator",
"FitContribution",
"FitHook",
"FitRecipe",
"FitResults",
"PlotFitHook",
"Profile",
"ProfileGenerator",
"ProfileParser",
"SimpleRecipe",
]

from diffpy.srfit.fitbase import (
Calculator,
FitContribution,
FitHook,
FitRecipe,
FitResults,
PlotFitHook,
Profile,
ProfileGenerator,
ProfileParser,
SimpleRecipe,
)

# package version
from diffpy.srfit.version import __version__ # noqa

Expand Down
206 changes: 105 additions & 101 deletions src/diffpy/srfit/fitbase/fitrecipe.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,6 @@
from collections import OrderedDict
from pathlib import Path

import matplotlib.pyplot as plt
from bg_mpl_stylesheets.styles import all_styles
from numpy import array, concatenate, dot, sqrt

import diffpy.srfit.util.inpututils as utils
Expand All @@ -49,8 +47,6 @@
from diffpy.srfit.util.tagmanager import TagManager
from diffpy.utils._deprecator import build_deprecation_message, deprecated

plt.style.use(all_styles["bg-style"])

base = "diffpy.srfit.fitbase.FitRecipe"
removal_version = "4.0.0"
addcontrib_dep_msg = build_deprecation_message(
Expand Down Expand Up @@ -1695,107 +1691,115 @@ def plot_recipe(self, ax=None, return_fig=False, **kwargs):
"No contributions found in recipe. "
"Add contributions before plotting."
)
import matplotlib.pyplot as plt
from bg_mpl_stylesheets.styles import all_styles

figures = []
axes_list = []
shared_axes = ax is not None and len(self._contributions) > 1
for name, contrib in self._contributions.items():
profile = contrib.profile
x = profile.x
yobs = profile.y
ycalc = profile.ycalc
show_fit = plot_params["show_fit"]
show_diff = plot_params["show_diff"]
if ycalc is None:
if show_fit or show_diff:
print(
f"Contribution '{name}' has no calculated values "
"(ycalc is None). "
"Only observed data will be plotted."
with plt.style.context(all_styles["bg-style"]):
for name, contrib in self._contributions.items():
profile = contrib.profile
x = profile.x
yobs = profile.y
ycalc = profile.ycalc
show_fit = plot_params["show_fit"]
show_diff = plot_params["show_diff"]
if ycalc is None:
if show_fit or show_diff:
print(
f"Contribution '{name}' has no calculated values "
"(ycalc is None). "
"Only observed data will be plotted."
)
show_fit = False
show_diff = False
else:
diff = yobs - ycalc
y_min = min(yobs.min(), ycalc.min())
y_max = max(yobs.max(), ycalc.max())
y_range = y_max - y_min
base_offset = y_min - 0.1 * y_range
offset = base_offset * plot_params["offset_scale"]
if ax is None:
fig = plt.figure(figsize=plot_params["figsize"])
current_ax = fig.add_subplot(111)
else:
current_ax = ax
fig = current_ax.figure
if plot_params["show_observed"]:
current_ax.plot(
x,
yobs,
plot_params["data_style"],
label=self._format_plot_label(
plot_params["data_label"], name, shared_axes
),
color=plot_params["data_color"],
markersize=plot_params["markersize"],
alpha=plot_params["alpha"],
)
show_fit = False
show_diff = False
else:
diff = yobs - ycalc
y_min = min(yobs.min(), ycalc.min())
y_max = max(yobs.max(), ycalc.max())
y_range = y_max - y_min
base_offset = y_min - 0.1 * y_range
offset = base_offset * plot_params["offset_scale"]
if ax is None:
fig = plt.figure(figsize=plot_params["figsize"])
current_ax = fig.add_subplot(111)
else:
current_ax = ax
fig = current_ax.figure
if plot_params["show_observed"]:
current_ax.plot(
x,
yobs,
plot_params["data_style"],
label=self._format_plot_label(
plot_params["data_label"], name, shared_axes
),
color=plot_params["data_color"],
markersize=plot_params["markersize"],
alpha=plot_params["alpha"],
)
if show_fit:
current_ax.plot(
x,
ycalc,
plot_params["fit_style"],
label=self._format_plot_label(
plot_params["fit_label"], name, shared_axes
),
color=plot_params["fit_color"],
linewidth=plot_params["linewidth"],
alpha=plot_params["alpha"],
)
if show_diff:
current_ax.plot(
x,
diff + offset,
plot_params["diff_style"],
label=self._format_plot_label(
plot_params["diff_label"], name, shared_axes
),
color=plot_params["diff_color"],
linewidth=plot_params["linewidth"],
alpha=plot_params["alpha"],
)
current_ax.axhline(
offset,
color="black",
)
meta = getattr(profile, "meta", None)
if meta:
self._set_axes_labels_from_metadata(meta, plot_params)
if plot_params["xlabel"] is not None:
current_ax.set_xlabel(plot_params["xlabel"])
if plot_params["ylabel"] is not None:
current_ax.set_ylabel(plot_params["ylabel"])
if plot_params["title"] is not None:
current_ax.set_title(
self._format_plot_label(plot_params["title"], name, False)
)
elif ax is None:
current_ax.set_title(name)
if plot_params["legend"]:
current_ax.legend(loc=plot_params["legend_loc"], frameon=True)
if plot_params["grid"]:
current_ax.grid(True)
if (
plot_params["xmin"] is not None
or plot_params["xmax"] is not None
):
current_ax.set_xlim(
left=plot_params["xmin"], right=plot_params["xmax"]
)
fig.tight_layout()
figures.append(fig)
axes_list.append(current_ax)
if plot_params["show"] and ax is None:
plt.show()
if show_fit:
current_ax.plot(
x,
ycalc,
plot_params["fit_style"],
label=self._format_plot_label(
plot_params["fit_label"], name, shared_axes
),
color=plot_params["fit_color"],
linewidth=plot_params["linewidth"],
alpha=plot_params["alpha"],
)
if show_diff:
current_ax.plot(
x,
diff + offset,
plot_params["diff_style"],
label=self._format_plot_label(
plot_params["diff_label"], name, shared_axes
),
color=plot_params["diff_color"],
linewidth=plot_params["linewidth"],
alpha=plot_params["alpha"],
)
current_ax.axhline(
offset,
color="black",
)
meta = getattr(profile, "meta", None)
if meta:
self._set_axes_labels_from_metadata(meta, plot_params)
if plot_params["xlabel"] is not None:
current_ax.set_xlabel(plot_params["xlabel"])
if plot_params["ylabel"] is not None:
current_ax.set_ylabel(plot_params["ylabel"])
if plot_params["title"] is not None:
current_ax.set_title(
self._format_plot_label(
plot_params["title"], name, False
)
)
elif ax is None:
current_ax.set_title(name)
if plot_params["legend"]:
current_ax.legend(
loc=plot_params["legend_loc"], frameon=True
)
if plot_params["grid"]:
current_ax.grid(True)
if (
plot_params["xmin"] is not None
or plot_params["xmax"] is not None
):
current_ax.set_xlim(
left=plot_params["xmin"], right=plot_params["xmax"]
)
fig.tight_layout()
figures.append(fig)
axes_list.append(current_ax)
if plot_params["show"] and ax is None:
plt.show()
if return_fig:
if len(figures) == 1:
return figures[0], axes_list[0]
Expand Down
2 changes: 1 addition & 1 deletion tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from numpy import linspace, pi, sin

import diffpy.srfit.equation.literals as literals
from diffpy.srfit.fitbase import FitContribution, FitRecipe, Profile
from diffpy.srfit import FitContribution, FitRecipe, Profile

logger = logging.getLogger(__name__)

Expand Down
4 changes: 1 addition & 3 deletions tests/test_contribution.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,9 @@
import pytest
from numpy import arange, array_equal, dot, sin

from diffpy.srfit import FitContribution, Profile, ProfileGenerator
from diffpy.srfit.exceptions import SrFitError
from diffpy.srfit.fitbase.fitcontribution import FitContribution
from diffpy.srfit.fitbase.parameter import Parameter
from diffpy.srfit.fitbase.profile import Profile
from diffpy.srfit.fitbase.profilegenerator import ProfileGenerator


class TestContribution(unittest.TestCase):
Expand Down
Loading
Loading