Skip to content

Commit

Permalink
Fixes to make tests run on Python 3.5 (issue 1)
Browse files Browse the repository at this point in the history
  • Loading branch information
gb119 committed Oct 17, 2016
1 parent 01774c0 commit 09005cb
Show file tree
Hide file tree
Showing 5 changed files with 73 additions and 23 deletions.
8 changes: 5 additions & 3 deletions Stoner/Analysis.py
Expand Up @@ -94,8 +94,9 @@ def _threshold(threshold, data, rising=True, falling=False):

intr=interp1d(index,data.ravel()-threshold,kind="cubic")
roots=[]
for ix,x in enumerate(sdat):
if expr(x) and ix>0 and ix<len(data)-1: # There's a root somewhere here !
for ix in range(sdat.shape[0]):
x=sdat[ix]
if expr(x): # There's a root somewhere here !
try:
roots.append(newton(intr,ix))
except ValueError: # fell off the end here
Expand Down Expand Up @@ -257,6 +258,7 @@ def SG_Filter(self, col=None, points=15, poly=1, order=0, result=None, replace=F
User guide section :ref:`smoothing_guide`
"""
from Stoner.Util import ordinal
points=int(round(points))
if points % 2 == 0: #Ensure window length is odd
points += 1
if col is None:
Expand Down Expand Up @@ -702,7 +704,7 @@ def curve_fit(self, func, xcol=None, ycol=None, p0=None, sigma=None, **kargs):
kargs["full_output"] = True

_=self._col_args(xcol=xcol,ycol=ycol,yerr=sigma,scalar=False)

xcol,ycol,sigma=_.xcol,_.ycol,_.yerr

working = self.search(xcol, bounds)
Expand Down
12 changes: 7 additions & 5 deletions Stoner/Core.py
Expand Up @@ -353,7 +353,7 @@ def __call__(self, *args, **kargs):
for i, v in enumerate(list(value)):
if v.lower() not in "xyzedfuvw.-":
raise ValueError("Set as column element is invalid: {}".format(v))
if v != "-":
if v != "-" and i<len(self.setas):
self.setas[i] = v.lower()
else:
raise ValueError("Set as column string ended with a number")
Expand Down Expand Up @@ -1079,7 +1079,7 @@ def __getitem__(self,ix):
"""

#Is this goign to be a single row ?
single_row=isinstance(ix,int) or (isinstance(ix,tuple) and isinstance(ix[0],int))
single_row=isinstance(ix,int) or (isinstance(ix,tuple) and len(ix)>0 and isinstance(ix[0],int))
#If the index is a single string type, then build a column accessing index
if isinstance(ix,string_types):
if self.ndim>1:
Expand All @@ -1088,15 +1088,17 @@ def __getitem__(self,ix):
ix=(self._setas.find_col(ix),)
if isinstance(ix,(int,slice)):
ix=(ix,)
elif isinstance(ix,tuple) and isinstance(ix[-1],string_types): # index still has a string type in it
elif isinstance(ix,tuple) and len(ix)>0 and isinstance(ix[-1],string_types): # index still has a string type in it
ix=list(ix)
ix[-1]=self._setas.find_col(ix[-1])
ix=tuple(ix)
elif isinstance(ix,tuple) and isinstance(ix[0],string_types): # oops! backwards indexing
elif isinstance(ix,tuple) and len(ix)>0 and isinstance(ix[0],string_types): # oops! backwards indexing
c=ix[0]
ix=list(ix[1:])
ix.append(self._setas.find_col(c))
ix=tuple(ix)
elif isinstance(ix,list): # indexing with a list in here
ix=(ix,)

# Now can index with our constructed multidimesnional indexer
ret=super(DataArray,self).__getitem__(ix)
Expand Down Expand Up @@ -1137,7 +1139,7 @@ def __getitem__(self,ix):
ret.i=self.i[ix[0]]
else: #This is a single element?
ret.i=self.i
if not single_row:
if not single_row and len(ix)>0:
ret.name=self.column_headers[ix[-1]]
return ret

Expand Down
24 changes: 10 additions & 14 deletions Stoner/Util.py
Expand Up @@ -37,6 +37,7 @@ def _up_down(data):
for d in f[grp][1:]:
ret[i]=ret[i]+d
ret[i].sort(data.setas._get_cols('xcol'))
ret[i].setas=data.setas.clone
return ret


Expand Down Expand Up @@ -166,12 +167,11 @@ def split_up_down(data, col=None, folder=None):
"""
if col is None:
col = data.setas["x"]
a = _AF_(data)
width = len(a) / 10
width = len(data) / 10
if width % 2 == 0: # Ensure the window for Satvisky Golay filter is odd
width += 1
peaks = list(a.peaks(col, width,xcol=False, peaks=True, troughs=False))
troughs = list(a.peaks(col, width, xcol=False, peaks=False, troughs=True))
peaks = list(data.peaks(col, width,xcol=False, peaks=True, troughs=False))
troughs = list(data.peaks(col, width, xcol=False, peaks=False, troughs=True))
if len(peaks) > 0 and len(troughs) > 0: #Ok more than up down here
order = peaks[0] < troughs[0]
elif len(peaks) > 0: #Rise then fall
Expand All @@ -180,7 +180,7 @@ def split_up_down(data, col=None, folder=None):
order = False
else: #No peaks or troughs so just return a single rising
return ([data], [])
splits = [0, len(a)]
splits = [0, len(data)]
splits.extend(peaks)
splits.extend(troughs)
splits.sort()
Expand Down Expand Up @@ -348,7 +348,7 @@ def hysteresis_correct(data, **kargs):
#Get xcol and ycols from kargs if specified
xc = kargs.pop("xcol",data.find_col(data.setas["x"]))
yc = kargs.pop("ycol",data.find_col(data.setas["y"]))
setas=data.setas
setas=data.setas.clone
setas[xc]="x"
setas[yc]="y"
data.setas=setas
Expand Down Expand Up @@ -385,6 +385,8 @@ def hysteresis_correct(data, **kargs):
Ms=array([p1[0],p2[0]])
Ms=list(Ms-mean(Ms))



data["Ms"] = Ms #mean(Ms)
data["Ms Error"] = perr[0]/2
data["Offset Moment"] = pm[0]
Expand All @@ -406,6 +408,7 @@ def hysteresis_correct(data, **kargs):
m_sat=[p1[0]+perr[0],p2[0]-perr[0]]
Mr=[None,None]
Mr_err=[None,None]

for i,(d,sat) in enumerate(zip([up,down],m_sat)):
hc=d.threshold(0.,all_vals=True,rising=True,falling=True) # Get the Hc value
Hc[i]=mean(hc)
Expand Down Expand Up @@ -438,14 +441,7 @@ def hysteresis_correct(data, **kargs):
i = argmax(bh)
data["BH_Max"] = max(bh)
data["BH_Max_H"] = data.x[i]
mr1 = data.threshold(0.0, col=xc, xcol=yc, rising=True, falling=False)
mr2 = data.threshold(0.0, col=xc, xcol=yc, rising=False, falling=True)

data["Remenance"] = abs((mr2 - mr1) / 2)

h_sat_data = data.search(data.setas["y"], lambda x, r: low_m <= x <= high_m)[:, xc]
if len(h_sat_data)>0:
data["H_sat"] = (min(h_sat_data), max(h_sat_data))

data["Area"] = data.integrate()
return cls(data)
return cls(data)
2 changes: 1 addition & 1 deletion Stoner/__init__.py
Expand Up @@ -10,6 +10,6 @@
from .Util import Data
from Stoner.Folders import DataFolder

__version_info__ = ('0', '6', '3')
__version_info__ = ('0', '6', '4')
__version__ = '.'.join(__version_info__)

50 changes: 50 additions & 0 deletions tests/Stoner/test_Util.py
@@ -0,0 +1,50 @@
# -*- coding: utf-8 -*-
"""
Test_Util.py
Created on Mon Jul 18 14:13:39 2016
@author: phygbu
"""


import unittest
import sys
import os.path as path
import os
import numpy as np
import re
from Stoner.compat import *
import Stoner.Util as SU

from Stoner import Data

pth=path.dirname(__file__)
pth=path.realpath(path.join(pth,"../../"))
sys.path.insert(0,pth)

def is_2tuple(x):
"""Return tru if x is a length two tuple of floats."""
return isinstance(x,tuple) and len(x)==2 and isinstance(x[0],float) and isinstance(x[1],float)


class Utils_test(unittest.TestCase):

"""Path to sample Data File"""
datadir=path.join(pth,"sample-data")

def setUp(self):
pass

def test_hysteresis(self):
"""Test the hysteresis analysis code."""
x=SU.hysteresis_correct(path.join(pth,"./sample-data/QD-SQUID-VSM.dat"))
self.assertTrue("Hc" in x and "Area" in x and
"Hsat" in x and "BH_Max" in x and
"BH_Max_H" in x,"Hystersis loop analysis keys not present.")

self.assertTrue(is_2tuple(x["Hc"]) and x["Hc"][0]+578<1.0,"Failed to find correct Hc in a SQUID loop")
self.assertTrue(isinstance(x["Area"],float) and 0.0136<x["Area"]<0.0137,"Incorrect calculation of area under loop")

if __name__=="__main__": # Run some tests manually to allow debugging
test=Utils_test("test_hysteresis")
test.setUp()
test.test_hysteresis()

0 comments on commit 09005cb

Please sign in to comment.