Skip to content

Commit 155a85d

Browse files
committed
finish parenthesizing print statements
1 parent c28b97b commit 155a85d

File tree

9 files changed

+606
-476
lines changed

9 files changed

+606
-476
lines changed

devutils/prep.py

Lines changed: 23 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -18,20 +18,21 @@ def __init__(self):
1818

1919
def test(self, call, *args, **kwds):
2020
m = sys.modules[call.__module__]
21-
testname = m.__name__+'.'+call.__name__
21+
testname = m.__name__ + "." + call.__name__
2222
path = os.path.dirname(m.__file__)
2323
os.chdir(path)
2424
try:
2525
call(*args, **kwds)
26-
self.messages.append("%s: success" %testname)
27-
except Exception, e:
28-
self.messages.append("%s: error, details below.\n%s" %(testname, e))
26+
self.messages.append("%s: success" % testname)
27+
except Exception as e:
28+
self.messages.append("%s: error, details below.\n%s" % (testname, e))
2929
finally:
3030
os.chdir(__basedir__)
3131

3232
def report(self):
33-
print '==== Results of Tests ===='
34-
print '\n'.join(self.messages)
33+
print("==== Results of Tests ====")
34+
print("\n".join(self.messages))
35+
3536

3637
def scrubeol(directory, filerestr):
3738
"""Use unix-style endlines for files in directory matched by regex string.
@@ -50,11 +51,11 @@ def scrubeol(directory, filerestr):
5051
text = unicode(original.read())
5152
original.close()
5253

53-
updated = io.open(f, 'w', newline='\n')
54+
updated = io.open(f, "w", newline="\n")
5455
updated.write(text)
5556
updated.close()
5657

57-
print "Updated %s to unix-style endlines." %f
58+
print("Updated %s to unix-style endlines." % f)
5859

5960

6061
def rm(directory, filerestr):
@@ -72,14 +73,13 @@ def rm(directory, filerestr):
7273
for f in files:
7374
os.remove(f)
7475

75-
print "Deleted %s." %f
76-
76+
print("Deleted %s." % f)
7777

7878

7979
if __name__ == "__main__":
8080

8181
# Temporarily add examples to path
82-
lib_path = os.path.abspath(os.path.join('..','doc','examples'))
82+
lib_path = os.path.abspath(os.path.join("..", "doc", "examples"))
8383
sys.path.append(lib_path)
8484

8585
# Delete existing files that don't necessarily have a fixed name.
@@ -88,14 +88,16 @@ def rm(directory, filerestr):
8888

8989
### Testing examples
9090
examples = Test()
91-
test_names = ["extract_single_peak",
92-
"parameter_summary",
93-
"fit_initial",
94-
"query_results",
95-
"multimodel_known_dG1",
96-
"multimodel_known_dG2",
97-
"multimodel_unknown_dG1",
98-
"multimodel_unknown_dG2"]
91+
test_names = [
92+
"extract_single_peak",
93+
"parameter_summary",
94+
"fit_initial",
95+
"query_results",
96+
"multimodel_known_dG1",
97+
"multimodel_known_dG2",
98+
"multimodel_unknown_dG1",
99+
"multimodel_unknown_dG2",
100+
]
99101

100102
test_modules = []
101103
for test in test_names:
@@ -107,7 +109,7 @@ def rm(directory, filerestr):
107109
examples.report()
108110

109111
### Convert output of example files to Unix-style endlines for sdist.
110-
if os.linesep != '\n':
111-
print"==== Scrubbing Endlines ===="
112+
if os.linesep != "\n":
113+
print("==== Scrubbing Endlines ====")
112114
# All *.srmise and *.pwa files in examples directory.
113115
scrubeol("../doc/examples/output", r".*(\.srmise|\.pwa)")

diffpy/srmise/peaks/base.py

Lines changed: 47 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222

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

25+
2526
class PeakFunction(BaseFunction):
2627
"""Base class for functions which represent peaks.
2728
@@ -60,7 +61,15 @@ class PeakFunction(BaseFunction):
6061
transform_parameters()
6162
"""
6263

63-
def __init__(self, parameterdict, parformats, default_formats, metadict, base=None, Cache=None):
64+
def __init__(
65+
self,
66+
parameterdict,
67+
parformats,
68+
default_formats,
69+
metadict,
70+
base=None,
71+
Cache=None,
72+
):
6473
"""Set parameterdict defined by subclass
6574
6675
parameterdict: A dictionary mapping string keys to their index in a
@@ -82,24 +91,31 @@ def __init__(self, parameterdict, parformats, default_formats, metadict, base=No
8291
raise ValueError(emsg)
8392
BaseFunction.__init__(self, parameterdict, parformats, default_formats, metadict, base, Cache)
8493

85-
8694
#### "Virtual" class methods ####
8795

8896
def scale_at(self, peak, x, scale):
8997
emsg = "scale_at must be implemented in a PeakFunction subclass."
9098
raise NotImplementedError(emsg)
9199

92-
93100
#### Methods required by BaseFunction ####
94101

95-
def actualize(self, pars, in_format="default_input", free=None, removable=True, static_owner=False):
102+
def actualize(
103+
self,
104+
pars,
105+
in_format="default_input",
106+
free=None,
107+
removable=True,
108+
static_owner=False,
109+
):
96110
converted = self.transform_parameters(pars, in_format, out_format="internal")
97111
return Peak(self, converted, free, removable, static_owner)
98112

99113
def getmodule(self):
100114
return __name__
101115

102-
#end of class PeakFunction
116+
117+
# end of class PeakFunction
118+
103119

104120
class Peaks(ModelParts):
105121
"""A collection for Peak objects."""
@@ -110,12 +126,12 @@ def __init__(self, *args, **kwds):
110126

111127
def argsort(self, key="position"):
112128
"""Return sequence of indices which sort peaks in order specified by key."""
113-
keypars=np.array([p[key] for p in self])
129+
keypars = np.array([p[key] for p in self])
114130
# In normal use the peaks will already be sorted, so check for it.
115-
sorted=True
116-
for i in range(len(keypars)-1):
117-
if keypars[i] > keypars[i+1]:
118-
sorted=False
131+
sorted = True
132+
for i in range(len(keypars) - 1):
133+
if keypars[i] > keypars[i + 1]:
134+
sorted = False
119135
break
120136
if not sorted:
121137
return keypars.argsort().tolist()
@@ -142,14 +158,14 @@ def match_at(self, x, y):
142158
orig = self.copy()
143159

144160
try:
145-
scale = y/height
161+
scale = y / height
146162

147163
# First attempt at scaling peaks. Record which peaks, if any,
148164
# were not scaled in case a second attempt is required.
149165
scaled = []
150166
all_scaled = True
151167
any_scaled = False
152-
fixed_height = 0.
168+
fixed_height = 0.0
153169
for peak in self:
154170
scaled.append(peak.scale_at(x, scale))
155171
all_scaled = all_scaled and scaled[-1]
@@ -161,27 +177,29 @@ def match_at(self, x, y):
161177
if not all_scaled and fixed_height < y and fixed_height < height:
162178
self[:] = orig[:]
163179
any_scaled = False
164-
scale = (y - fixed_height)/(height - fixed_height)
180+
scale = (y - fixed_height) / (height - fixed_height)
165181
for peak, s in (self, scaled):
166182
if s:
167183
# "or" is short-circuited, so scale_at() must be first
168184
# to guarantee it is called.
169185
any_scaled = peak.scale_at(x, scale) or any_scaled
170-
except Exception, e:
186+
except Exception as e:
171187
logger.debug("An exception prevented matching -- %s", e)
172188
self[:] = orig[:]
173189
return False
174190
return any_scaled
175191

176192
def sort(self, key="position"):
177193
"""Sort peaks in order specified by key."""
178-
keypars=np.array([p[key] for p in self])
194+
keypars = np.array([p[key] for p in self])
179195
order = keypars.argsort()
180196
self[:] = [self[idx] for idx in order]
181197
return
182198

199+
183200
# End of class Peaks
184201

202+
185203
class Peak(ModelPart):
186204
"""Represents a single peak associated with a PeakFunction subclass."""
187205

@@ -225,7 +243,7 @@ def scale_at(self, x, scale):
225243

226244
try:
227245
adj_pars = self._owner.scale_at(self.pars, x, scale)
228-
except SrMiseScalingError, err:
246+
except SrMiseScalingError as err:
229247
logger.debug("Cannot scale peak:", err)
230248
return False
231249

@@ -256,10 +274,10 @@ def factory(peakstr, ownerlist):
256274
try:
257275
pdict[l[0]] = eval(l[1])
258276
except Exception:
259-
emsg = ("Invalid parameter: %s" %d)
277+
emsg = "Invalid parameter: %s" % d
260278
raise SrMiseDataFormatError(emsg)
261279
else:
262-
emsg = ("Invalid parameter: %s" %d)
280+
emsg = "Invalid parameter: %s" % d
263281
raise SrMiseDataFormatError(emsg)
264282

265283
# Correctly initialize the base function, if one exists.
@@ -271,10 +289,11 @@ def factory(peakstr, ownerlist):
271289

272290
return Peak(**pdict)
273291

292+
274293
# End of class Peak
275294

276295
# simple test code
277-
if __name__ == '__main__':
296+
if __name__ == "__main__":
278297

279298
import matplotlib.pyplot as plt
280299
from numpy.random import randn
@@ -283,26 +302,26 @@ def factory(peakstr, ownerlist):
283302
from diffpy.srmise.modelevaluators import AICc
284303
from diffpy.srmise.peaks import GaussianOverR
285304

286-
res = .01
287-
r = np.arange(2,4,res)
288-
err = np.ones(len(r)) #default unknown errors
289-
pf = GaussianOverR(.7)
305+
res = 0.01
306+
r = np.arange(2, 4, res)
307+
err = np.ones(len(r)) # default unknown errors
308+
pf = GaussianOverR(0.7)
290309
evaluator = AICc()
291310

292-
pars = [[3, .2, 10], [3.5, .2, 10]]
311+
pars = [[3, 0.2, 10], [3.5, 0.2, 10]]
293312
ideal_peaks = Peaks([pf.actualize(p, "pwa") for p in pars])
294-
y = ideal_peaks.value(r) + .1*randn(len(r))
313+
y = ideal_peaks.value(r) + 0.1 * randn(len(r))
295314

296-
guesspars = [[2.7, .15, 5], [3.7, .3, 5]]
315+
guesspars = [[2.7, 0.15, 5], [3.7, 0.3, 5]]
297316
guess_peaks = Peaks([pf.actualize(p, "pwa") for p in guesspars])
298317
cluster = ModelCluster(guess_peaks, r, y, err, None, AICc, [pf])
299318

300319
qual1 = cluster.quality()
301-
print qual1.stat
320+
print(qual1.stat)
302321
cluster.fit()
303322
yfit = cluster.calc()
304323
qual2 = cluster.quality()
305-
print qual2.stat
324+
print(qual2.stat)
306325

307326
plt.figure(1)
308327
plt.plot(r, y, r, yfit)

0 commit comments

Comments
 (0)