Skip to content

Commit

Permalink
Remove tight_layout and use constrained layout instead.
Browse files Browse the repository at this point in the history
Fix several issues with not passing figure kwargs in plot routines
Rebuild docs
  • Loading branch information
gb119 committed Dec 23, 2023
1 parent 8b32728 commit 770757d
Show file tree
Hide file tree
Showing 404 changed files with 154 additions and 135 deletions.
Empty file modified .buildinfo 100644 → 100755
Empty file.
Empty file modified .nojekyll 100644 → 100755
Empty file.
Empty file modified .prospector.yaml 100644 → 100755
Empty file.
Empty file modified COPYING 100644 → 100755
Empty file.
Empty file modified MANIFEST.in 100644 → 100755
Empty file.
11 changes: 2 additions & 9 deletions Stoner/Image/folders.py
Expand Up @@ -8,7 +8,7 @@
from copy import deepcopy, copy

import numpy as np
from matplotlib.pyplot import figure, Figure, subplot, tight_layout
from matplotlib.pyplot import figure, Figure, subplot
from PIL.TiffImagePlugin import ImageFileDirectory_v2
from PIL import Image

Expand Down Expand Up @@ -314,8 +314,6 @@ def montage(self, *args, **kargs):
Passed to matplotlib figure call.
plots_per_page(int):
maximum number of plots per figure.
tight_layout(dict or False):
If not False, arguments to pass to a call of :py:func:`matplotlib.pyplot.tight_layout`. Defaults to {}
Returns:
A list of :py:class:`matplotlib.pyplot.Axes` instances.
Expand All @@ -332,7 +330,6 @@ def montage(self, *args, **kargs):
plts = min(plts, len(self))

extra = kargs.pop("extra", lambda i, j, d: None)
tight = kargs.pop("tight_layout", {})

fig_num = kargs.pop("figure", getattr(self, "_figure", None))
if isinstance(fig_num, Figure):
Expand All @@ -344,7 +341,7 @@ def montage(self, *args, **kargs):
fig_num = fig_num.number

fig_args = getattr(self, "_fig_args", [])
fig_kargs = getattr(self, "_fig_kargs", {})
fig_kargs = getattr(self, "_fig_kargs", {"layout": "constrained"})
for arg in ("figsize", "dpi", "facecolor", "edgecolor", "frameon", "FigureClass"):
if arg in kargs:
fig_kargs[arg] = kargs.pop(arg)
Expand All @@ -363,8 +360,6 @@ def montage(self, *args, **kargs):
for i, d in enumerate(self):
plt_kargs = copy(kargs)
if i % plts == 0 and i != 0:
if isinstance(tight, dict):
tight_layout(**tight)
fig = figure(*fig_args, **fig_kargs)
fignum = fig.number
j = 1
Expand All @@ -381,8 +376,6 @@ def montage(self, *args, **kargs):
plt_kargs["title"] = kargs["title"](d)
ret.append(d.imshow(*args, **plt_kargs))
extra(i, j, d)
if isinstance(tight, dict):
tight_layout(**tight)
return ret

def stddev(self, weights=None, _box=False, _metadata="first"):
Expand Down
Empty file modified Stoner/Image/tessdata/eng.traineddata 100644 → 100755
Empty file.
Empty file modified Stoner/Image/tessdata/equ.traineddata 100644 → 100755
Empty file.
Empty file modified Stoner/Image/tessdata/kerr-patterns.txt 100644 → 100755
Empty file.
3 changes: 2 additions & 1 deletion Stoner/analysis/filtering.py
Expand Up @@ -85,7 +85,7 @@ def SG_Filter(

ddata = savgol_filter(data, window_length=points, polyorder=poly, deriv=order, mode="interp")
if isinstance(pad, bool) and pad:
offset = int(np.ceil(points * order**2 / 8))
offset = int(np.ceil(points * (order + 1) ** 2 / 8))
padv = np.mean(ddata[:, offset:-offset], axis=1)
pad = np.ones((ddata.shape[0], offset))
for ix, v in enumerate(padv):
Expand Down Expand Up @@ -478,6 +478,7 @@ def make_bins(self, xcol, bins, mode="lin", **kargs):
if mode.lower().startswith("lin"):
bin_centres = (bin_start + bin_stop) / 2.0
elif mode.lower().startswith("log"):
bin_start = np.where(bin_start <= 0, 1e-9, bin_start)
bin_centres = np.exp(np.log(bin_start) + np.log(bin_stop) / 2.0)
else:
raise ValueError(f"mode should be either lin(ear) or log(arthimitc) not {mode}")
Expand Down
8 changes: 4 additions & 4 deletions Stoner/analysis/fitting/models/magnetism.py
Expand Up @@ -267,15 +267,15 @@ class BlochLawThin(Model):
"""

def __init__(self, *args, **kwargs):
"""Setup the model."""
"""Initialise the model."""
super().__init__(self.blochs_law_thinfilm, *args, **kwargs)
self.set_param_hint("g", vary=False, value=2.0)
self.set_param_hint("A", vary=True, min=0)
self.set_param_hint("Ms", vary=True, min=0)
self.prefactor = gamma(1.5) * zeta(1.5) / (4 * np.pi**2)

def blochs_law_thinfilm(self, T, D, Bz, S, v_ws, a, nz):
"""Thin film version of Blopch's Law.
r"""Thin film version of Blopch's Law.
Parameters:
T (array):
Expand Down Expand Up @@ -310,7 +310,6 @@ def blochs_law_thinfilm(self, T, D, Bz, S, v_ws, a, nz):
ln\left[1-\exp\left( -\frac{1}{k_B T}\left(g\mu_B B_z+D\left(\frac{m \pi}{a(n_z-1)}\right)^2
\right)\right) \right]`
"""

kz_sum = sum(
np.log(1.0 - np.exp(-(D * (m * np.pi / ((nz - 1) * a)) ** 2 + Bz) / (k * T))) for m in range(0, nz - 1)
)
Expand Down Expand Up @@ -346,7 +345,8 @@ def guess(self, data, x=None, **kwargs):
r"""Guess some starting values.
M_s is taken as half the difference of the range of thew M data,
we can find m/T from the susceptibility :math:`chi= M_s \mu_o m / kT`,"""
we can find m/T from the susceptibility :math:`chi= M_s \mu_o m / kT`
"""
M_s = (np.max(data) - np.min(data)) / 2.0
if x is not None:
d = np.sort(np.row_stack((x, data)))
Expand Down
6 changes: 0 additions & 6 deletions Stoner/compat.py
Expand Up @@ -4,7 +4,6 @@
"str2bytes",
"bytes2str",
"get_filedialog",
"getargspec",
"string_types",
"path_types",
"int_types",
Expand Down Expand Up @@ -68,11 +67,6 @@
from re import Pattern as _pattern_type # pylint: disable = E0611


def getargspec(*args, **kargs):
"""Wrap for getargspec for Python V3."""
return getfullargspec(*args, **kargs)[:4]


def get_func_params(func):
"""Get the parameters for a function."""
sig = signature(func)
Expand Down
10 changes: 2 additions & 8 deletions Stoner/folders/mixins.py
Expand Up @@ -13,7 +13,7 @@

from numpy import mean, std, array, append, any as np_any, floor, sqrt, ceil
from numpy.ma import masked_invalid
from matplotlib.pyplot import figure, tight_layout, subplots
from matplotlib.pyplot import figure, subplots

from Stoner.tools import isiterable, make_Data
from ..compat import string_types, get_filedialog, _pattern_type, makedirs, path_types
Expand Down Expand Up @@ -683,8 +683,6 @@ def plot(self, *args, **kargs):
Passed to matplotlib figure call.
plots_per_page(int):
maximum number of plots per figure.
tight_layout(dict or False):
If not False, arguments to pass to a call of :py:func:`matplotlib.pyplot.tight_layout`. Defaults to {}
Returns:
A list of :py:class:`matplotlib.pyplot.Axes` instances.
Expand All @@ -705,7 +703,6 @@ def plot(self, *args, **kargs):
self[i] = make_Data(d)

extra = kargs.pop("extra", lambda i, j, d: None)
tight = kargs.pop("tight_layout", {})

fig_args = getattr(self, "_fig_args", [])
fig_kargs = getattr(self, "_fig_kargs", {})
Expand All @@ -721,21 +718,18 @@ def plot(self, *args, **kargs):
fignum = fig.number
for i, d in enumerate(self):
if i % plts == 0 and i != 0:
if isinstance(tight, dict):
tight_layout(**tight)
fig, axs = subplots(plt_x, plt_y, *fig_args, **fig_kargs)
fignum = fig.number
j = 0
else:
j += 1
fig = figure(fignum)
kargs["fig"] = fig
kargs["figure"] = fig
kargs["ax"] = axs.ravel()[j]
ret.append(d.plot(*args, **kargs))
extra(i, j, d)
for n in range(j + 1, plt_x * plt_y):
axs.ravel()[n].remove()
tight_layout()
return ret


Expand Down
30 changes: 21 additions & 9 deletions Stoner/formats/generic.py
Expand Up @@ -8,6 +8,24 @@
import re
from collections.abc import Mapping
import sys
import logging

import PIL
import numpy as np

from ..Core import DataFile
from ..compat import str2bytes, Hyperspy_ok, hs, hsload
from ..core.exceptions import StonerLoadError
from ..tools.file import FileManager


class _refuse_log(logging.Filter):

"""Refuse to log all records."""

def filter(self, record):
"""Do not log anything."""
return False


@contextlib.contextmanager
Expand All @@ -16,20 +34,14 @@ def catch_sysout(*args):
stdout, stderr = sys.stdout, sys.stderr
out = io.StringIO()
sys.stdout, sys.stderr = out, out
logger = logging.getLogger("hyperspy.io")
logger.addFilter(_refuse_log)
yield None
logger.removeFilter(_refuse_log)
sys.stdout, sys.stderr = stdout, stderr
return


import PIL
import numpy as np

from ..Core import DataFile
from ..compat import str2bytes, Hyperspy_ok, hs, hsload
from ..core.exceptions import StonerLoadError
from ..tools.file import FileManager


def _delim_detect(line):
"""Detect a delimiter in a line.
Expand Down
Empty file modified Stoner/plot/__init__.py 100644 → 100755
Empty file.

0 comments on commit 770757d

Please sign in to comment.