Skip to content

Commit

Permalink
Squashing more code style issues
Browse files Browse the repository at this point in the history
  • Loading branch information
gb119 committed Aug 10, 2019
1 parent 5038450 commit 8184f46
Show file tree
Hide file tree
Showing 14 changed files with 161 additions and 151 deletions.
3 changes: 1 addition & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,10 @@ install:
# - conda install --yes scikit-image
# Hyperspy is now an optional dependency for 3.6 onwards
- if [[ "$TRAVIS_PYTHON_VERSION" == "3.7" ]] || [[ "$TRAVIS_PYTHON_VERSION" == "3.6" ]] ; then
conda install --yes -c conda-forge hyperspy;
conda install --yes -c conda-forge hyperspy;
fi
# Now we unistall the stable stoner - use force to stop downgrading packages!
- conda remove --yes --force stoner
- pip install opencv_python
- pip install coveralls
- pip install .

Expand Down
12 changes: 6 additions & 6 deletions Stoner/Core.py
Original file line number Diff line number Diff line change
Expand Up @@ -1610,17 +1610,17 @@ def __search_index(self, xcol, value, accuracy):
if isinstance(value, (int_types, float)):
ix = _np_.less_equal(_np_.abs(self.data[:, x] - value), accuracy)
elif isinstance(value, tuple) and len(value) == 2:
(l, u) = (min(value), max(value))
l -= accuracy
(low, u) = (min(value), max(value))
low -= accuracy
u += accuracy
v = self.data[:, x]
l = _np_.ones_like(v) * l
low = _np_.ones_like(v) * low
u = _np_.ones_like(v) * u
ix = _np_.logical_and(v > l, v <= u)
ix = _np_.logical_and(v > low, v <= u)
elif isinstance(value, (list, _np_.ndarray)):
ix = _np_.zeros(len(self), dtype=bool)
for v in value:
ix = _np_.logical_or(ix, self.__search_index(xcol, v), accuracy)
ix = _np_.logical_or(ix, self.__search_index(xcol, v, accuracy))
elif callable(value):
ix = _np_.array([value(r[x], r) for r in self], dtype=bool)
else:
Expand Down Expand Up @@ -2168,7 +2168,7 @@ def find_col(self, col, force_list=False):
"""
return self.data._setas.find_col(col, force_list)

def get(self, item, default=None):
def get(self, item, default=None): # pylint: disalbe=arguments-differ
"""A wrapper around __get_item__ that handles missing keys by returning None.
This is useful for the :py:class:`Stoner.Folder.DataFolder` class.
Expand Down
1 change: 1 addition & 0 deletions Stoner/Fit.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,7 @@ def guesser(cls, func):

@wraps(func)
def guess_proxy(self, *args, **kargs):
"""A magic proxy call around a function to guess initial prameters."""
guesses = func(*args, **kargs)
pars = {x: y for x, y in zip(self.param_names, guesses)}
pars = self.make_params(**pars)
Expand Down
8 changes: 8 additions & 0 deletions Stoner/Image/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,7 @@ def __array_finalize__(self, obj):
super(ImageArray, self).__array_finalize__(obj)

def __array_prepare__(self, arr, context=None):
"""Support the numpy machinery for subclassing ndarray."""
return super(ImageArray, self).__array_prepare__(arr, context)

def __array_wrap__(self, out_arr, context=None):
Expand Down Expand Up @@ -346,6 +347,7 @@ def _load_npy(cls, filename, **kargs):

@classmethod
def _load_png(cls, filename, **kargs):
"""Create a new ImageArray from a png file."""
with Image.open(filename, "r") as img:
image = np.asarray(img).view(cls)
# Since skimage.img_as_float() looks at the dtype of the array when mapping ranges, it's important to make
Expand All @@ -369,6 +371,7 @@ def _load_png(cls, filename, **kargs):

@classmethod
def _load_tiff(cls, filename, **kargs):
"""Create a new ImageArray from a tiff file."""
metadict = typeHintedDict({})
with Image.open(filename, "r") as img:
image = np.asarray(img)
Expand Down Expand Up @@ -475,6 +478,7 @@ def aspect(self):

@property
def centre(self):
"""Return the coordinates of the centre of the image."""
return tuple(np.array(self.shape) / 2.0)

@property
Expand Down Expand Up @@ -649,6 +653,7 @@ def _func_generator(self, workingfunc):

@wraps(workingfunc)
def gen_func(*args, **kwargs):
"""Wrapped magic proxy function call."""
transpose = getattr(workingfunc, "transpose", False)
if transpose:
change = self.clone.T
Expand Down Expand Up @@ -1543,6 +1548,9 @@ def square(self, r, c, w, angle=0.0, shape=None, value=1.0):


class MaskProxy(object):

"""Provides a wrapper to support manipulating the image mask easily."""

@property
def _IA(self):
"""Get the underliying image data."""
Expand Down
1 change: 1 addition & 0 deletions Stoner/analysis/fitting/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
"""Provides additional functionality for doing curve fitting to data."""
__all__ = ["odr_Model", "FittingMixin"]
from .mixins import odr_Model, FittingMixin
11 changes: 10 additions & 1 deletion Stoner/analysis/fitting/mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -1030,7 +1030,16 @@ def _func(x, *beta):
pguess = func.guess
else:
pguess = None
except:
except (
ArithmeticError,
AttributeError,
LookupError,
RuntimeError,
NameError,
OSError,
TypeError,
ValueError,
):
pguess = None
p0 = kargs.pop("p0", pguess)
elif callable(func):
Expand Down
7 changes: 4 additions & 3 deletions Stoner/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@
from os import getcwd, path, mkdir

def get_func_params(func):
"""Get Function parameter names from signature."""
ret = []
for arg in getargspec(func)[0][1:]:
ret.append(arg)
Expand Down Expand Up @@ -197,12 +198,12 @@ def _access_check(fn, mode):
files = [cmd]

seen = set()
for dir in path:
normdir = os.path.normcase(dir)
for _dir in path:
normdir = os.path.normcase(_dir)
if not normdir in seen:
seen.add(normdir)
for thefile in files:
name = os.path.join(dir, thefile)
name = os.path.join(_dir, thefile)
if _access_check(name, mode):
return name
return None
Expand Down
37 changes: 15 additions & 22 deletions Stoner/core/setas.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

from ..compat import string_types, int_types, index_types, _pattern_type
from ..tools import _attribute_store, isiterable, typedList, islike_list
from .utils import decode_string

from collections import MutableMapping, Mapping

Expand Down Expand Up @@ -117,18 +118,6 @@ def __init__(self, row=False, bless=None):
},
} # xyzuvw

def _decode_string(self, value):
"""Expands a string of column assignments, replacing numbers with repeated characters."""
pattern = re.compile("(([0-9]+)(x|y|z|d|e|f|u|v|w|\.|\-))")
while True:
res = pattern.search(value)
if res is None:
break
(total, count, code) = res.groups()
count = int(count)
value = value.replace(total, code * count, 1)
return value

def _prepare_call(self, args, kargs):
"""Extract a value to be used to evaluate the setas attribute during a call."""
reset = kargs.pop("reset", True)
Expand All @@ -140,7 +129,7 @@ def _prepare_call(self, args, kargs):
if isinstance(value, string_types): # expand the number-code combos in value
if reset:
self.setas = []
value = self._decode_string(value)
value = decode_string(value)
elif isinstance(value, setas):
if value is not self:
value = value.setas
Expand Down Expand Up @@ -358,7 +347,7 @@ def __eq__(self, other):
"""Checks to see if this is the same object, or has the same headers and the same setas values."""
ret = False
if isinstance(other, string_types): # Expand strings and convert to list
other = [c for c in self._decode_string(other)]
other = [c for c in decode_string(other)]
if not isinstance(other, setas): # Ok, need to check whether items match
if isiterable(other) and len(other) <= self._size:
for m in self.setas[len(other) :]: # Check that if other is short we don't have assignments there
Expand All @@ -367,8 +356,7 @@ def __eq__(self, other):
for o, m in zip(other, self.setas):
if o != m: # Look for mis-matched assignments
return False
else:
return True
return True
else: # If other is longer then we can't matchj
return False
elif id(self) == id(other):
Expand Down Expand Up @@ -644,7 +632,7 @@ def clear(self):
"""
self.unset()

def get(self, name, default=None):
def get(self, name, default=None): # pylint: disalbe=arguments-differ
"""Implement a get method."""
try:
return self[name]
Expand All @@ -669,7 +657,7 @@ def items(self):
for k, v in zip(self._unique_headers, self.setas):
yield k, v

def pop(self, name, default=None):
def pop(self, name, default=None): # pylint: disalbe=arguments-differ
"""Implement a get method."""
try:
ret = self[name]
Expand All @@ -689,7 +677,7 @@ def popitem(self):
return (c, v)
raise KeyError("No columns set in setas!")

def setdefault(self, name, default=None):
def setdefault(self, name, default=None): # pylint: disalbe=arguments-differ
"""Implement a setdefault method."""
try:
return self[name]
Expand Down Expand Up @@ -717,12 +705,17 @@ def unset(self, what=None):
else:
self -= what

def update(self, other):
def update(self, other=(), **kwds):
"""Replace any assignments in self with assignments from other."""
if isinstance(other, setas):
other = other.to_dict()
elif not isinstance(other, dict):
raise TypeError("setas.update requires a dictionary not a {}".format(type(other)))
elif isinstance(other, tuple) and len(other) == 0:
other = kwds
else:
try:
other = dict(other)
except (ValueError, TypeError):
raise TypeError("setas.update requires a dictionary not a {}".format(type(other)))
vals = list(other.values())
keys = list(other.keys())
for k in "xyzuvwdef":
Expand Down
16 changes: 15 additions & 1 deletion Stoner/core/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@
# -*- coding: utf-8 -*-
"""Utility functions to support :py:mod:`Stoner.Core`."""

__all__ = ["copy_into", "itersubclasses", "tab_delimited"]
__all__ = ["copy_into", "itersubclasses", "tab_delimited", "decode_string"]

import copy
import csv
import re


def copy_into(source, dest):
Expand Down Expand Up @@ -80,3 +81,16 @@ def itersubclasses(cls, _seen=None):
yield sub
for sub in itersubclasses(sub, _seen):
yield sub


def decode_string(value):
"""Expands a string of column assignments, replacing numbers with repeated characters."""
pattern = re.compile(r"(([0-9]+)(x|y|z|d|e|f|u|v|w|\.|\-))")
while True:
res = pattern.search(value)
if res is None:
break
(total, count, code) = res.groups()
count = int(count)
value = value.replace(total, code * count, 1)
return value

0 comments on commit 8184f46

Please sign in to comment.