Skip to content

Commit a4221ff

Browse files
lint check & change to python3 & pre-commit check (#19)
* lint check & change to python3 & pre-commit check * [pre-commit.ci] auto fixes from pre-commit hooks --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 5684c18 commit a4221ff

File tree

4 files changed

+181
-149
lines changed

4 files changed

+181
-149
lines changed

Diff for: diffpy/srmise/baselines/nanospherical.py

+67-52
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@
2222

2323
logger = logging.getLogger("diffpy.srmise")
2424

25-
class NanoSpherical (BaselineFunction):
25+
26+
class NanoSpherical(BaselineFunction):
2627
"""Methods for evaluation of baseline of spherical nanoparticle of uniform density.
2728
2829
Allowed formats are
@@ -47,29 +48,31 @@ def __init__(self, Cache=None):
4748
evaluations.
4849
"""
4950
# Define parameterdict
50-
parameterdict = {'scale':0, 'radius':1}
51-
formats = ['internal']
52-
default_formats = {'default_input':'internal', 'default_output':'internal'}
51+
parameterdict = {"scale": 0, "radius": 1}
52+
formats = ["internal"]
53+
default_formats = {"default_input": "internal", "default_output": "internal"}
5354
metadict = {}
54-
BaselineFunction.__init__(self, parameterdict, formats, default_formats, metadict, None, Cache)
55+
BaselineFunction.__init__(
56+
self, parameterdict, formats, default_formats, metadict, None, Cache
57+
)
5558

5659
#### Methods required by BaselineFunction ####
5760

58-
# def estimate_parameters(self, r, y):
59-
# """Estimate parameters for spherical baseline. (Not implemented!)
60-
#
61-
# Parameters
62-
# r - array along r from which to estimate
63-
# y - array along y from which to estimate
64-
#
65-
# Returns Numpy array of parameters in the default internal format.
66-
# Raises NotImplementedError if estimation is not implemented for this
67-
# degree, or SrMiseEstimationError if parameters cannot be estimated for
68-
# any other reason.
69-
# """
70-
# if len(r) != len(y):
71-
# emsg = "Arrays r, y must have equal length."
72-
# raise ValueError(emsg)
61+
# def estimate_parameters(self, r, y):
62+
# """Estimate parameters for spherical baseline. (Not implemented!)
63+
#
64+
# Parameters
65+
# r - array along r from which to estimate
66+
# y - array along y from which to estimate
67+
#
68+
# Returns Numpy array of parameters in the default internal format.
69+
# Raises NotImplementedError if estimation is not implemented for this
70+
# degree, or SrMiseEstimationError if parameters cannot be estimated for
71+
# any other reason.
72+
# """
73+
# if len(r) != len(y):
74+
# emsg = "Arrays r, y must have equal length."
75+
# raise ValueError(emsg)
7376

7477
def _jacobianraw(self, pars, r, free):
7578
"""Return the Jacobian of the spherical baseline.
@@ -83,22 +86,26 @@ def _jacobianraw(self, pars, r, free):
8386
needed. True for evaluation, False for no evaluation.
8487
"""
8588
if len(pars) != self.npars:
86-
emsg = "Argument pars must have "+str(self.npars)+" elements."
89+
emsg = "Argument pars must have " + str(self.npars) + " elements."
8790
raise ValueError(emsg)
8891
if len(free) != self.npars:
89-
emsg = "Argument free must have "+str(self.npars)+" elements."
92+
emsg = "Argument free must have " + str(self.npars) + " elements."
9093
raise ValueError(emsg)
9194
jacobian = [None for p in range(self.npars)]
9295
if (free == False).sum() == self.npars:
9396
return jacobian
9497

9598
if np.isscalar(r):
96-
if r <= 0. or r >= 2.*pars[1]:
97-
if free[0]: jacobian[0] = 0.
98-
if free[1]: jacobian[1] = 0.
99+
if r <= 0.0 or r >= 2.0 * pars[1]:
100+
if free[0]:
101+
jacobian[0] = 0.0
102+
if free[1]:
103+
jacobian[1] = 0.0
99104
else:
100-
if free[0]: jacobian[0] = self._jacobianrawscale(pars, r)
101-
if free[1]: jacobian[1] = self._jacobianrawradius(pars, r)
105+
if free[0]:
106+
jacobian[0] = self._jacobianrawscale(pars, r)
107+
if free[1]:
108+
jacobian[1] = self._jacobianrawradius(pars, r)
102109
else:
103110
s = self._getdomain(pars, r)
104111
if free[0]:
@@ -120,12 +127,12 @@ def _jacobianrawscale(self, pars, r):
120127
"""
121128
s = np.abs(pars[0])
122129
R = np.abs(pars[1])
123-
rdivR = r/R
130+
rdivR = r / R
124131
# From abs'(s) in derivative, which is equivalent to sign(s) except at 0 where it
125132
# is undefined. Since s=0 is equivalent to the absence of a nanoparticle, sign will
126133
# be fine.
127134
sign = np.sign(pars[1])
128-
return -sign*r*(1-(3./4.)*rdivR+(1./16.)*rdivR**3)
135+
return -sign * r * (1 - (3.0 / 4.0) * rdivR + (1.0 / 16.0) * rdivR**3)
129136

130137
def _jacobianrawradius(self, pars, r):
131138
"""Return partial Jacobian wrt radius without bounds checking.
@@ -141,7 +148,7 @@ def _jacobianrawradius(self, pars, r):
141148
# From abs'(R) in derivative, which is equivalent to sign(R) except at 0 where it
142149
# is undefined. Since R=0 is a singularity anyway, sign will be fine.
143150
sign = np.sign(pars[1])
144-
return sign*s*(3*r**2*(r**2-4*R**2))/(16*R**4)
151+
return sign * s * (3 * r**2 * (r**2 - 4 * R**2)) / (16 * R**4)
145152

146153
def _transform_parametersraw(self, pars, in_format, out_format):
147154
"""Convert parameter values from in_format to out_format.
@@ -162,15 +169,17 @@ def _transform_parametersraw(self, pars, in_format, out_format):
162169
temp[0] = np.abs(temp[0])
163170
temp[1] = np.abs(temp[1])
164171
else:
165-
raise ValueError("Argument 'in_format' must be one of %s." \
166-
% self.parformats)
172+
raise ValueError(
173+
"Argument 'in_format' must be one of %s." % self.parformats
174+
)
167175

168176
# Convert to specified output format from "internal" format.
169177
if out_format == "internal":
170178
pass
171179
else:
172-
raise ValueError("Argument 'out_format' must be one of %s." \
173-
% self.parformats)
180+
raise ValueError(
181+
"Argument 'out_format' must be one of %s." % self.parformats
182+
)
174183
return temp
175184

176185
def _valueraw(self, pars, r):
@@ -185,11 +194,11 @@ def _valueraw(self, pars, r):
185194
r - sequence or scalar over which pars is evaluated.
186195
"""
187196
if len(pars) != self.npars:
188-
emsg = "Argument pars must have "+str(self.npars)+" elements."
197+
emsg = "Argument pars must have " + str(self.npars) + " elements."
189198
raise ValueError(emsg)
190199
if np.isscalar(r):
191-
if r <= 0. or r >= 2.*pars[1]:
192-
return 0.
200+
if r <= 0.0 or r >= 2.0 * pars[1]:
201+
return 0.0
193202
else:
194203
return self._valueraw2(pars, r)
195204
else:
@@ -209,38 +218,44 @@ def _valueraw2(self, pars, r):
209218
"""
210219
s = np.abs(pars[0])
211220
R = np.abs(pars[1])
212-
rdivR = r/R
213-
return -s*r*(1-(3./4.)*rdivR+(1./16.)*rdivR**3)
221+
rdivR = r / R
222+
return -s * r * (1 - (3.0 / 4.0) * rdivR + (1.0 / 16.0) * rdivR**3)
214223

215224
def _getdomain(self, pars, r):
216225
"""Return slice object for which r > 0 and r < twice the radius"""
217-
low = r.searchsorted(0., side='right')
218-
high = r.searchsorted(2.*pars[1], side='left')
226+
low = r.searchsorted(0.0, side="right")
227+
high = r.searchsorted(2.0 * pars[1], side="left")
219228
return slice(low, high)
220229

221230
def getmodule(self):
222231
return __name__
223232

224-
#end of class NanoSpherical
233+
234+
# end of class NanoSpherical
225235

226236
# simple test code
227-
if __name__ == '__main__':
237+
if __name__ == "__main__":
228238

229239
f = NanoSpherical()
230240
r = np.arange(-5, 10)
231-
pars = np.array([-1., 7.])
241+
pars = np.array([-1.0, 7.0])
232242
free = np.array([False, True])
233-
print "Testing nanoparticle spherical baseline"
234-
print "Scale: %f, Radius: %f" %(pars[0], pars[1])
235-
print "-----------------------------------------"
243+
print("Testing nanoparticle spherical baseline")
244+
print("Scale: %f, Radius: %f" % (pars[0], pars[1]))
245+
print("-----------------------------------------")
236246
val = f._valueraw(pars, r)
237-
jac = f._jacobianraw(pars, r, free)
238-
outjac = [j if j is not None else [None]*len(r) for j in jac]
239-
print "r".center(10), "value".center(10), "jac(scale)".center(10), "jac(radius)".center(10)
247+
jac = f._jacobianraw(pars, r, free)
248+
outjac = [j if j is not None else [None] * len(r) for j in jac]
249+
print(
250+
"r".center(10),
251+
"value".center(10),
252+
"jac(scale)".center(10),
253+
"jac(radius)".center(10),
254+
)
240255
for tup in zip(r, val, *outjac):
241256
for t in tup:
242257
if t is None:
243-
print ("%s" %None).ljust(10),
258+
print("%s" % None).ljust(10),
244259
else:
245-
print ("% .3g" %t).ljust(10),
260+
print("% .3g" % t).ljust(10),
246261
print

Diff for: diffpy/srmise/baselines/polynomial.py

+51-42
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@
2222

2323
logger = logging.getLogger("diffpy.srmise")
2424

25-
class Polynomial (BaselineFunction):
25+
26+
class Polynomial(BaselineFunction):
2627
"""Methods for evaluation and parameter estimation of a polynomial baseline."""
2728

2829
def __init__(self, degree, Cache=None):
@@ -41,17 +42,19 @@ def __init__(self, degree, Cache=None):
4142
emsg = "Argument degree must be an integer."
4243
raise ValueError(emsg)
4344
if self.degree < 0:
44-
self.degree = -1 # interpreted as negative infinity
45+
self.degree = -1 # interpreted as negative infinity
4546
# Define parameterdict
4647
# e.g. {"a_0":3, "a_1":2, "a_2":1, "a_3":0} if degree is 3.
4748
parameterdict = {}
48-
for d in range(self.degree+1):
49-
parameterdict["a_"+str(d)] = self.degree - d
50-
formats = ['internal']
51-
default_formats = {'default_input':'internal', 'default_output':'internal'}
49+
for d in range(self.degree + 1):
50+
parameterdict["a_" + str(d)] = self.degree - d
51+
formats = ["internal"]
52+
default_formats = {"default_input": "internal", "default_output": "internal"}
5253
metadict = {}
5354
metadict["degree"] = (degree, repr)
54-
BaselineFunction.__init__(self, parameterdict, formats, default_formats, metadict, None, Cache)
55+
BaselineFunction.__init__(
56+
self, parameterdict, formats, default_formats, metadict, None, Cache
57+
)
5558

5659
#### Methods required by BaselineFunction ####
5760

@@ -81,7 +84,7 @@ def estimate_parameters(self, r, y):
8184
return np.array([])
8285

8386
if self.degree == 0:
84-
return np.array([0.])
87+
return np.array([0.0])
8588

8689
if self.degree == 1:
8790
# Estimate degree=1 baseline.
@@ -90,15 +93,16 @@ def estimate_parameters(self, r, y):
9093
# lies above the baseline.
9194
# TODO: Make this more sophisticated.
9295
try:
93-
cut = np.max([len(y)/10, 1])
96+
cut = np.max([len(y) / 10, 1])
9497
cut_idx = y.argsort()[:cut]
9598

9699
import numpy.linalg as la
100+
97101
A = np.array([r[cut_idx]]).T
98102
slope = la.lstsq(A, y[cut_idx])[0][0]
99-
return np.array([slope, 0.])
100-
except Exception, e:
101-
emsg = "Error during estimation -- "+str(e)
103+
return np.array([slope, 0.0])
104+
except Exception as e:
105+
emsg = "Error during estimation -- " + str(e)
102106
raise
103107
raise SrMiseEstimationError(emsg)
104108

@@ -116,10 +120,10 @@ def _jacobianraw(self, pars, r, free):
116120
needed. True for evaluation, False for no evaluation.
117121
"""
118122
if len(pars) != self.npars:
119-
emsg = "Argument pars must have "+str(self.npars)+" elements."
123+
emsg = "Argument pars must have " + str(self.npars) + " elements."
120124
raise ValueError(emsg)
121125
if len(free) != self.npars:
122-
emsg = "Argument free must have "+str(self.npars)+" elements."
126+
emsg = "Argument free must have " + str(self.npars) + " elements."
123127
raise ValueError(emsg)
124128
jacobian = [None for p in range(self.npars)]
125129
if (free == False).sum() == self.npars:
@@ -148,15 +152,17 @@ def _transform_parametersraw(self, pars, in_format, out_format):
148152
if in_format == "internal":
149153
pass
150154
else:
151-
raise ValueError("Argument 'in_format' must be one of %s." \
152-
% self.parformats)
155+
raise ValueError(
156+
"Argument 'in_format' must be one of %s." % self.parformats
157+
)
153158

154159
# Convert to specified output format from "internal" format.
155160
if out_format == "internal":
156161
pass
157162
else:
158-
raise ValueError("Argument 'out_format' must be one of %s." \
159-
% self.parformats)
163+
raise ValueError(
164+
"Argument 'out_format' must be one of %s." % self.parformats
165+
)
160166
return temp
161167

162168
def _valueraw(self, pars, r):
@@ -171,51 +177,54 @@ def _valueraw(self, pars, r):
171177
If degree is negative infinity, pars is an empty sequence.
172178
r: sequence or scalar over which pars is evaluated"""
173179
if len(pars) != self.npars:
174-
emsg = "Argument pars must have "+str(self.npars)+" elements."
180+
emsg = "Argument pars must have " + str(self.npars) + " elements."
175181
raise ValueError(emsg)
176182
return np.polyval(pars, r)
177183

178184
def getmodule(self):
179185
return __name__
180186

181-
#end of class Polynomial
187+
188+
# end of class Polynomial
182189

183190
# simple test code
184-
if __name__ == '__main__':
191+
if __name__ == "__main__":
185192

186193
# Test polynomial of degree 3
187-
print "Testing degree 3 polynomial"
188-
print "---------------------------"
189-
f = Polynomial(degree = 3)
194+
print("Testing degree 3 polynomial")
195+
print("---------------------------")
196+
f = Polynomial(degree=3)
190197
r = np.arange(5)
191198
pars = np.array([3, 0, 1, 2])
192199
free = np.array([True, False, True, True])
193200
val = f._valueraw(pars, r)
194-
jac = f._jacobianraw(pars, r, free)
195-
print "Value:\n", val
196-
print "Jacobian: "
197-
for j in jac: print " %s" %j
201+
jac = f._jacobianraw(pars, r, free)
202+
print("Value:\n", val)
203+
print("Jacobian: ")
204+
for j in jac:
205+
print(" %s" % j)
198206

199207
# Test polynomial of degree -oo
200-
print "\nTesting degree -oo polynomial (== 0)"
201-
print "------------------------------------"
202-
f = Polynomial(degree = -1)
208+
print("\nTesting degree -oo polynomial (== 0)")
209+
print("------------------------------------")
210+
f = Polynomial(degree=-1)
203211
r = np.arange(5)
204212
pars = np.array([])
205213
free = np.array([])
206214
val = f._valueraw(pars, r)
207-
jac = f._jacobianraw(pars, r, free)
208-
print "Value:\n", val
209-
print "Jacobian: "
210-
for j in jac: print " %s" %j
215+
jac = f._jacobianraw(pars, r, free)
216+
print("Value:\n", val)
217+
print("Jacobian: ")
218+
for j in jac:
219+
print(" %s" % j)
211220

212221
# Test linear estimation
213-
print "\nTesting linear baseline estimation"
214-
print "------------------------------------"
215-
f = Polynomial(degree = 1)
222+
print("\nTesting linear baseline estimation")
223+
print("------------------------------------")
224+
f = Polynomial(degree=1)
216225
pars = np.array([1, 0])
217-
r = np.arange(0, 10, .1)
218-
y = -r + 10*np.exp(-(r-5)**2) + np.random.rand(len(r))
226+
r = np.arange(0, 10, 0.1)
227+
y = -r + 10 * np.exp(-((r - 5) ** 2)) + np.random.rand(len(r))
219228
est = f.estimate_parameters(r, y)
220-
print "Actual baseline: ", np.array([-1, 0.])
221-
print "Estimated baseline: ", est
229+
print("Actual baseline: ", np.array([-1, 0.0]))
230+
print("Estimated baseline: ", est)

0 commit comments

Comments
 (0)