Skip to content

Commit

Permalink
Adjust for testing against Python 3.11 and scipy 1.10 and current sci…
Browse files Browse the repository at this point in the history
…kit-image
  • Loading branch information
gb119 committed Sep 30, 2023
1 parent 8be143e commit f701f55
Show file tree
Hide file tree
Showing 30 changed files with 47 additions and 71 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/run-tests-action.yaml
Expand Up @@ -10,7 +10,7 @@ jobs:
strategy:
fail-fast: false
matrix:
python-version: ["3.7","3.8","3.9", "3.10", 3.11]
python-version: ["3.7","3.8","3.9", "3.10", "3.11"]
os: ["ubuntu-latest"]
steps:
- name: Check out repository code
Expand Down
2 changes: 1 addition & 1 deletion Makefile
Expand Up @@ -14,7 +14,7 @@ clean:
- find -name '__pycache__' -exec rm -rf {} \;

test:
pytest -n `python -c 'import os;print(min(12,os.cpu_count()))'`
pytest -n `python -c 'import os;print(min(8,os.cpu_count()))'`

test-single:
pytest --pdb
Expand Down
1 change: 0 additions & 1 deletion Stoner/Core.py
Expand Up @@ -789,7 +789,6 @@ def _repr_table_(self, fmt="rst"):
for ic, c in enumerate(interesting):
if c >= 0:
if shorten[0]:

col_out = np.where(self.mask[: r // 2 - 1, c], "#####", self.data[: r // 2 - 1, c].astype(str))
outp[1 : r // 2, ic + 1] = col_out
col_out = np.where(self.mask[-r // 2 :, c], "#####", self.data[-r // 2 :, c].astype(str))
Expand Down
3 changes: 0 additions & 3 deletions Stoner/Image/core.py
Expand Up @@ -25,7 +25,6 @@
morphology,
segmentation,
transform,
viewer,
)

from ..core.base import typeHintedDict, metadataObject
Expand Down Expand Up @@ -146,7 +145,6 @@ def copy_into(source: "ImageFile", dest: "ImageFile") -> "ImageFile":
morphology,
segmentation,
transform,
viewer,
]
)
@class_modifier([ndi], transpose=True)
Expand Down Expand Up @@ -688,7 +686,6 @@ def __delitem__(self, index):
morphology,
segmentation,
transform,
viewer,
],
adaptor=image_file_adaptor,
)
Expand Down
8 changes: 0 additions & 8 deletions Stoner/Image/folders.py
Expand Up @@ -7,7 +7,6 @@
from json import loads, dumps
from copy import deepcopy, copy

from skimage.viewer import CollectionViewer
import numpy as np
from matplotlib.pyplot import figure, Figure, subplot, tight_layout
from PIL.TiffImagePlugin import ImageFileDirectory_v2
Expand Down Expand Up @@ -234,7 +233,6 @@ def from_tiff(cls, filename, **kargs):
with Image.open(filename, "r") as img:
tags = img.tag_v2
if 270 in tags:

try:
userdata = loads(tags[270])
typ = userdata.get("type", cls.__name__)
Expand Down Expand Up @@ -481,12 +479,6 @@ def to_tiff(self, filename):
imlist[0].save(tiffname, save_all=True, append_images=imlist[1:], tiffinfo=ifd)
return self

def view(self):
"""Create a matplotlib animated view of the contents."""
cv = CollectionViewer(list(self.images))
cv.show()
return cv


class ImageFolder(ImageFolderMixin, DiskBasedFolderMixin, baseFolder):

Expand Down
2 changes: 1 addition & 1 deletion Stoner/__init__.py
Expand Up @@ -35,7 +35,7 @@
Options = _Options()


__version_info__ = ("0", "10", "6")
__version_info__ = ("0", "10", "7")
__version__ = ".".join(__version_info__)

__homepath__ = pathlib.Path(__file__).parent.resolve()
Expand Down
3 changes: 0 additions & 3 deletions Stoner/analysis/fitting/mixins.py
Expand Up @@ -528,7 +528,6 @@ def annotate_fit(self, model, x=None, y=None, z=None, text_only=False, **kargs):
raise RuntimeError(f"model should be either an lmfit.Model or a callable function, not a {type(model)}")

if prefix is not None:

if isinstance(prefix, (list, tuple)):
prefix = prefix[0]

Expand Down Expand Up @@ -605,7 +604,6 @@ def _get_curve_fit_data(self, xcol, ycol, bounds, sigma):
xdat = working[:, self.find_col(xcol)]

for i, yc in enumerate(ycol):

if isinstance(yc, index_types):
ydat = working[:, self.find_col(yc)]
elif isinstance(yc, np.ndarray) and yc.ndim == 1 and len(yc) == len(self):
Expand Down Expand Up @@ -1172,7 +1170,6 @@ def _func(x, *beta):
retvals = []
i = None
for i, ydat in enumerate(ydata):

if isinstance(sigma, np.ndarray) and sigma.shape[0] > 1:
if sigma.shape[0] == len(ycol):
s = sigma[i]
Expand Down
1 change: 0 additions & 1 deletion Stoner/analysis/fitting/models/__init__.py
Expand Up @@ -95,7 +95,6 @@ def hinter(**kwargs):
"""

class _ModelDecorator(Model):

__doc__ = model_func.__doc__

def __init__(self, *args, **kargs):
Expand Down
4 changes: 0 additions & 4 deletions Stoner/analysis/fitting/models/generic.py
Expand Up @@ -117,7 +117,6 @@ class Linear(_Linear):


class Quadratic(_Quadratic):

r"""A Simple quadratic fitting function.
Args:
Expand All @@ -139,7 +138,6 @@ class Quadratic(_Quadratic):


class PowerLaw(_PowerLaw):

r"""Power Law Fitting Equation.
Args:
Expand All @@ -160,7 +158,6 @@ class PowerLaw(_PowerLaw):


class StretchedExp(Model):

r"""A stretched exponential fuinction.
Args:
Expand Down Expand Up @@ -199,7 +196,6 @@ def guess(self, data, x=None, **kwargs):


class Lorentzian_diff(Model):

r"""Provides a lmfit Model rerprenting the differential form of a Lorentzian Peak.
Args:
Expand Down
6 changes: 0 additions & 6 deletions Stoner/analysis/fitting/models/magnetism.py
Expand Up @@ -155,7 +155,6 @@ def fmr_power(H, H_res, Delta_H, K_1, K_2):


class BlochLaw(Model):

r"""Bloch's law for spontaneous magnetism at low temperatures.
Args:
Expand Down Expand Up @@ -242,7 +241,6 @@ def guess(self, data, x=None, **kwargs):


class BlochLawThin(Model):

r"""Bloch's law for spontaneous magnetism at low temperatures - thin film version.
Args:
Expand Down Expand Up @@ -320,7 +318,6 @@ def blochs_law_thinfilm(self, T, D, Bz, S, v_ws, a, nz):


class Langevin(Model):

r"""The Langevin function for paramagnetic M-H loops.
Args:
Expand Down Expand Up @@ -367,7 +364,6 @@ def guess(self, data, x=None, **kwargs):


class KittelEquation(Model):

r"""Kittel Equation for finding ferromagnetic resonance peak in frequency with field.
Args:
Expand Down Expand Up @@ -412,7 +408,6 @@ def guess(self, data, x=None, **kwargs):


class Inverse_Kittel(Model):

r"""Kittel Equation for finding ferromagnetic resonance peak in frequency with field.
Args:
Expand Down Expand Up @@ -453,7 +448,6 @@ def guess(self, data, x=None, **kwargs):


class FMR_Power(Model):

r"""Combine a Lorentzian and differential Lorenztion peak as measured in an FMR experiment.
Args:
Expand Down
13 changes: 9 additions & 4 deletions Stoner/analysis/fitting/models/superconductivity.py
Expand Up @@ -138,7 +138,15 @@ def strijkers(V, omega, delta, P, Z):
:include-source:
:outname: strijkers_func
"""
return _strijkers_core(V, omega, delta, P, Z)
if isinstance(V, np.ma.MaskedArray):
mask = V.mask
V = np.array(V)
else:
mask = False
ret = _strijkers_core(V, omega, delta, P, Z)
ret = np.ma.MaskedArray(ret)
ret.mask = mask
return ret


def rsj_noiseless(I, Ic_p, Ic_n, Rn, V_offset):
Expand Down Expand Up @@ -349,7 +357,6 @@ def guess(self, data, **kwargs): # pylint: disable=unused-argument


class RSJ_Noiseless(Model):

r"""Implement a simple noiseless RSJ model.
Args:
Expand Down Expand Up @@ -403,7 +410,6 @@ def guess(self, data, **kwargs):


class RSJ_Simple(Model):

r"""Implements a simple noiseless symmetric RSJ model.
Args:
Expand Down Expand Up @@ -456,7 +462,6 @@ def guess(self, data, **kwargs):


class Ic_B_Airy(Model):

r"""Critical Current for a round Josepshon Junction wrt to Field.
Args:
Expand Down
4 changes: 0 additions & 4 deletions Stoner/analysis/fitting/models/thermal.py
Expand Up @@ -122,7 +122,6 @@ def vftEquation(x, A, DE, x_0):


class Arrhenius(Model):

r"""Arrhenius Equation without T dependendent prefactor.
Args:
Expand Down Expand Up @@ -160,7 +159,6 @@ def guess(self, data, x=None, **kwargs):


class NDimArrhenius(Model):

r"""Arrhenius Equation without T dependendent prefactor for various dimensions.
Args:
Expand Down Expand Up @@ -199,7 +197,6 @@ def guess(self, data, x=None, **kwargs):


class ModArrhenius(Model):

r"""Arrhenius Equation with a variable T power dependent prefactor.
Args:
Expand Down Expand Up @@ -238,7 +235,6 @@ def guess(self, data, x=None, **kwargs):


class VFTEquation(Model):

r"""Vogel-Flucher-Tammann (VFT) Equation without T dependendent prefactor.
Args:
Expand Down
10 changes: 10 additions & 0 deletions Stoner/compat.py
Expand Up @@ -88,6 +88,16 @@ def get_func_params(func):
int_types = (int,)
path_types = (str, PurePath)

##### Monkey patch numpy for removed attributes as a compatibiliyu hack
if not hasattr(np, "float"):
np.float = float

if not hasattr(np, "bool"):
np.bool = bool

if not hasattr(np, "str"):
np.str = str


def str2bytes(data):
"""Encode a unicode string into UTF-8."""
Expand Down
1 change: 0 additions & 1 deletion Stoner/core/array.py
Expand Up @@ -19,7 +19,6 @@


class DataArray(ma.MaskedArray):

r"""A sub class of :py:class:`numpy.ma.MaskedArray` with a copy of the setas attribute to allow indexing by name.
Attributes:
Expand Down
16 changes: 5 additions & 11 deletions Stoner/core/base.py
Expand Up @@ -432,7 +432,7 @@ def __mungevalue(self, typ: str, value: Any) -> Any:
ret = None
if typ == "Invalid Type": # Short circuit here
return repr(value)
for (regexp, valuetype) in self.__tests:
for regexp, valuetype in self.__tests:
matched = regexp.search(typ)
if matched is not None:
if isinstance(valuetype, _evaluatable):
Expand All @@ -450,18 +450,12 @@ def __mungevalue(self, typ: str, value: Any) -> Any:
if isinstance(ret, datetime.datetime):
break # Alreadu a datetime object
try:
ret = literal_eval(value)
ret = parser.parse(value)
except ValueError:
ret = str(ret)
if isinstance(ret, datetime.datetime):
break # Got us a datetime object now
elif isinstance(ret, string_types): # try parsing as a string now
try:
ret = _parse_date(ret)
break
except (ValueError, OverflowError):
pass # fall back
ret = datetime.datetime(1970, 1, 1) # unparsable time
ret = literal_eval(value)
except ValueError:
ret = str(value)
break
else:
ret = valuetype(value)
Expand Down
2 changes: 1 addition & 1 deletion Stoner/core/setas.py
Expand Up @@ -745,7 +745,7 @@ def to_dict(self):
If multiple columns are assigned to the same type, then the column names are
returned as a list. If column headers are duplicated"""
ret = dict()
for (k, ch) in zip(self._setas, self._unique_headers):
for k, ch in zip(self._setas, self._unique_headers):
if k != ".":
if k in ret:
ret[k].append(ch)
Expand Down
4 changes: 1 addition & 3 deletions Stoner/folders/mixins.py
Expand Up @@ -328,7 +328,7 @@ def fetch(self):
With multiprocess enabled this will parallel load the contents of the folder into memory.
"""
p, imap = get_pool()
for (f, name) in imap(
for f, name in imap(
partial(_loader, loader=self.loader, typ=self._type, directory=self.directory), self.not_loaded
):
self.__setter__(
Expand Down Expand Up @@ -527,7 +527,6 @@ def extract(self, *metadata, **kargs):
metadata = args

def _extractor(group, _, metadata):

results = group.type()
results.metadata = group[0].metadata
headers = []
Expand Down Expand Up @@ -752,7 +751,6 @@ class DataFolder(DataMethodsMixin, DiskBasedFolderMixin, baseFolder):
"""

def __init__(self, *args, **kargs):

self.type = kargs.pop("type", make_Data(None))
super().__init__(*args, **kargs)

Expand Down
1 change: 0 additions & 1 deletion Stoner/formats/attocube.py
Expand Up @@ -371,7 +371,6 @@ def to_hdf5(self, filename=None):
mode = "r+" if path.exists(filename) else "w"
self.filename = filename
with HDFFileManager(self.filename, mode=mode) as f:

f.attrs["type"] = type(self).__name__
f.attrs["module"] = type(self).__module__
f.attrs["scan_no"] = self.scan_no
Expand Down
2 changes: 1 addition & 1 deletion Stoner/formats/instruments.py
Expand Up @@ -67,7 +67,7 @@ def _load(self, filename=None, *args, **kargs):
"Number of Breakpoints",
]:
raise Core.StonerLoadError("Header did not contain recognised keys.")
for (k, v) in zip(keys, vals):
for k, v in zip(keys, vals):
v = v.split()[0]
self.metadata[k] = string_to_type(v)
headers = bytes2str(next(data)).strip().split()
Expand Down
1 change: 0 additions & 1 deletion Stoner/formats/maximus.py
Expand Up @@ -518,7 +518,6 @@ def _read_pointscan(files, header):


if __name__ == "__main__":

# Test by reading all files
for infile in Path(".").glob("*.hdr"):
hdr, data, dims = read_scan(infile.stem)
1 change: 0 additions & 1 deletion Stoner/plot/core.py
Expand Up @@ -73,7 +73,6 @@ def __mpl3DQuiver(x_coord, y_coord, z_coord, u_comp, v_comp, w_comp, **kargs):


class PlotMixin:

r"""A mixin class that works with :py:class:`Stoner.Core.DataFile` to add additional plotting functionality.
Args:
Expand Down

0 comments on commit f701f55

Please sign in to comment.