Skip to content

Commit 09005cb

Browse files
committed
Fixes to make tests run on Python 3.5 (issue 1)
1 parent 01774c0 commit 09005cb

5 files changed

Lines changed: 73 additions & 23 deletions

File tree

Stoner/Analysis.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -94,8 +94,9 @@ def _threshold(threshold, data, rising=True, falling=False):
9494

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

704706
_=self._col_args(xcol=xcol,ycol=ycol,yerr=sigma,scalar=False)
705-
707+
706708
xcol,ycol,sigma=_.xcol,_.ycol,_.yerr
707709

708710
working = self.search(xcol, bounds)

Stoner/Core.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -353,7 +353,7 @@ def __call__(self, *args, **kargs):
353353
for i, v in enumerate(list(value)):
354354
if v.lower() not in "xyzedfuvw.-":
355355
raise ValueError("Set as column element is invalid: {}".format(v))
356-
if v != "-":
356+
if v != "-" and i<len(self.setas):
357357
self.setas[i] = v.lower()
358358
else:
359359
raise ValueError("Set as column string ended with a number")
@@ -1079,7 +1079,7 @@ def __getitem__(self,ix):
10791079
"""
10801080

10811081
#Is this goign to be a single row ?
1082-
single_row=isinstance(ix,int) or (isinstance(ix,tuple) and isinstance(ix[0],int))
1082+
single_row=isinstance(ix,int) or (isinstance(ix,tuple) and len(ix)>0 and isinstance(ix[0],int))
10831083
#If the index is a single string type, then build a column accessing index
10841084
if isinstance(ix,string_types):
10851085
if self.ndim>1:
@@ -1088,15 +1088,17 @@ def __getitem__(self,ix):
10881088
ix=(self._setas.find_col(ix),)
10891089
if isinstance(ix,(int,slice)):
10901090
ix=(ix,)
1091-
elif isinstance(ix,tuple) and isinstance(ix[-1],string_types): # index still has a string type in it
1091+
elif isinstance(ix,tuple) and len(ix)>0 and isinstance(ix[-1],string_types): # index still has a string type in it
10921092
ix=list(ix)
10931093
ix[-1]=self._setas.find_col(ix[-1])
10941094
ix=tuple(ix)
1095-
elif isinstance(ix,tuple) and isinstance(ix[0],string_types): # oops! backwards indexing
1095+
elif isinstance(ix,tuple) and len(ix)>0 and isinstance(ix[0],string_types): # oops! backwards indexing
10961096
c=ix[0]
10971097
ix=list(ix[1:])
10981098
ix.append(self._setas.find_col(c))
10991099
ix=tuple(ix)
1100+
elif isinstance(ix,list): # indexing with a list in here
1101+
ix=(ix,)
11001102

11011103
# Now can index with our constructed multidimesnional indexer
11021104
ret=super(DataArray,self).__getitem__(ix)
@@ -1137,7 +1139,7 @@ def __getitem__(self,ix):
11371139
ret.i=self.i[ix[0]]
11381140
else: #This is a single element?
11391141
ret.i=self.i
1140-
if not single_row:
1142+
if not single_row and len(ix)>0:
11411143
ret.name=self.column_headers[ix[-1]]
11421144
return ret
11431145

Stoner/Util.py

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ def _up_down(data):
3737
for d in f[grp][1:]:
3838
ret[i]=ret[i]+d
3939
ret[i].sort(data.setas._get_cols('xcol'))
40+
ret[i].setas=data.setas.clone
4041
return ret
4142

4243

@@ -166,12 +167,11 @@ def split_up_down(data, col=None, folder=None):
166167
"""
167168
if col is None:
168169
col = data.setas["x"]
169-
a = _AF_(data)
170-
width = len(a) / 10
170+
width = len(data) / 10
171171
if width % 2 == 0: # Ensure the window for Satvisky Golay filter is odd
172172
width += 1
173-
peaks = list(a.peaks(col, width,xcol=False, peaks=True, troughs=False))
174-
troughs = list(a.peaks(col, width, xcol=False, peaks=False, troughs=True))
173+
peaks = list(data.peaks(col, width,xcol=False, peaks=True, troughs=False))
174+
troughs = list(data.peaks(col, width, xcol=False, peaks=False, troughs=True))
175175
if len(peaks) > 0 and len(troughs) > 0: #Ok more than up down here
176176
order = peaks[0] < troughs[0]
177177
elif len(peaks) > 0: #Rise then fall
@@ -180,7 +180,7 @@ def split_up_down(data, col=None, folder=None):
180180
order = False
181181
else: #No peaks or troughs so just return a single rising
182182
return ([data], [])
183-
splits = [0, len(a)]
183+
splits = [0, len(data)]
184184
splits.extend(peaks)
185185
splits.extend(troughs)
186186
splits.sort()
@@ -348,7 +348,7 @@ def hysteresis_correct(data, **kargs):
348348
#Get xcol and ycols from kargs if specified
349349
xc = kargs.pop("xcol",data.find_col(data.setas["x"]))
350350
yc = kargs.pop("ycol",data.find_col(data.setas["y"]))
351-
setas=data.setas
351+
setas=data.setas.clone
352352
setas[xc]="x"
353353
setas[yc]="y"
354354
data.setas=setas
@@ -385,6 +385,8 @@ def hysteresis_correct(data, **kargs):
385385
Ms=array([p1[0],p2[0]])
386386
Ms=list(Ms-mean(Ms))
387387

388+
389+
388390
data["Ms"] = Ms #mean(Ms)
389391
data["Ms Error"] = perr[0]/2
390392
data["Offset Moment"] = pm[0]
@@ -406,6 +408,7 @@ def hysteresis_correct(data, **kargs):
406408
m_sat=[p1[0]+perr[0],p2[0]-perr[0]]
407409
Mr=[None,None]
408410
Mr_err=[None,None]
411+
409412
for i,(d,sat) in enumerate(zip([up,down],m_sat)):
410413
hc=d.threshold(0.,all_vals=True,rising=True,falling=True) # Get the Hc value
411414
Hc[i]=mean(hc)
@@ -438,14 +441,7 @@ def hysteresis_correct(data, **kargs):
438441
i = argmax(bh)
439442
data["BH_Max"] = max(bh)
440443
data["BH_Max_H"] = data.x[i]
441-
mr1 = data.threshold(0.0, col=xc, xcol=yc, rising=True, falling=False)
442-
mr2 = data.threshold(0.0, col=xc, xcol=yc, rising=False, falling=True)
443-
444-
data["Remenance"] = abs((mr2 - mr1) / 2)
445-
446-
h_sat_data = data.search(data.setas["y"], lambda x, r: low_m <= x <= high_m)[:, xc]
447-
if len(h_sat_data)>0:
448-
data["H_sat"] = (min(h_sat_data), max(h_sat_data))
449444

450445
data["Area"] = data.integrate()
451446
return cls(data)
447+
return cls(data)

Stoner/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,6 @@
1010
from .Util import Data
1111
from Stoner.Folders import DataFolder
1212

13-
__version_info__ = ('0', '6', '3')
13+
__version_info__ = ('0', '6', '4')
1414
__version__ = '.'.join(__version_info__)
1515

tests/Stoner/test_Util.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
Test_Util.py
4+
Created on Mon Jul 18 14:13:39 2016
5+
@author: phygbu
6+
"""
7+
8+
9+
import unittest
10+
import sys
11+
import os.path as path
12+
import os
13+
import numpy as np
14+
import re
15+
from Stoner.compat import *
16+
import Stoner.Util as SU
17+
18+
from Stoner import Data
19+
20+
pth=path.dirname(__file__)
21+
pth=path.realpath(path.join(pth,"../../"))
22+
sys.path.insert(0,pth)
23+
24+
def is_2tuple(x):
25+
"""Return tru if x is a length two tuple of floats."""
26+
return isinstance(x,tuple) and len(x)==2 and isinstance(x[0],float) and isinstance(x[1],float)
27+
28+
29+
class Utils_test(unittest.TestCase):
30+
31+
"""Path to sample Data File"""
32+
datadir=path.join(pth,"sample-data")
33+
34+
def setUp(self):
35+
pass
36+
37+
def test_hysteresis(self):
38+
"""Test the hysteresis analysis code."""
39+
x=SU.hysteresis_correct(path.join(pth,"./sample-data/QD-SQUID-VSM.dat"))
40+
self.assertTrue("Hc" in x and "Area" in x and
41+
"Hsat" in x and "BH_Max" in x and
42+
"BH_Max_H" in x,"Hystersis loop analysis keys not present.")
43+
44+
self.assertTrue(is_2tuple(x["Hc"]) and x["Hc"][0]+578<1.0,"Failed to find correct Hc in a SQUID loop")
45+
self.assertTrue(isinstance(x["Area"],float) and 0.0136<x["Area"]<0.0137,"Incorrect calculation of area under loop")
46+
47+
if __name__=="__main__": # Run some tests manually to allow debugging
48+
test=Utils_test("test_hysteresis")
49+
test.setUp()
50+
test.test_hysteresis()

0 commit comments

Comments
 (0)