Skip to content

Commit 166e726

Browse files
committed
Merge branch 'Cookie' of github.com:diffpy/diffpy.srmise into Cookie
2 parents 73b25a8 + edaa35d commit 166e726

20 files changed

+121
-146
lines changed

devutils/prep.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88

99
__basedir__ = os.getcwdu()
1010

11+
from numpy.compat import unicode
12+
1113
# Example imports
1214

1315

@@ -86,7 +88,7 @@ def rm(directory, filerestr):
8688
rm("../doc/examples/output", r"known_dG.*\.pwa")
8789
rm("../doc/examples/output", r"unknown_dG.*\.pwa")
8890

89-
### Testing examples
91+
# Testing examples
9092
examples = Test()
9193
test_names = [
9294
"extract_single_peak",
@@ -108,7 +110,7 @@ def rm(directory, filerestr):
108110

109111
examples.report()
110112

111-
### Convert output of example files to Unix-style endlines for sdist.
113+
# Convert output of example files to Unix-style endlines for sdist.
112114
if os.linesep != "\n":
113115
print("==== Scrubbing Endlines ====")
114116
# All *.srmise and *.pwa files in examples directory.

diffpy/srmise/applications/extract.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,8 @@
1111
#
1212
##############################################################################
1313

14-
from optparse import OptionGroup, OptionParser
14+
import textwrap
15+
from optparse import IndentedHelpFormatter, OptionGroup, OptionParser
1516

1617
import matplotlib.pyplot as plt
1718
import numpy as np
@@ -539,7 +540,6 @@ def main():
539540
cov = None
540541
if options.performextraction:
541542
cov = ext.extract()
542-
out = ext.extracted
543543

544544
if options.savefile is not None:
545545
try:
@@ -591,13 +591,10 @@ def parsepars(mp, parseq):
591591
return mp.actualize(pars, "internal", free=free)
592592

593593

594-
### Class to preserve newlines in optparse
594+
# Class to preserve newlines in optparse
595595
# Borrowed, with minor changes, from
596596
# http://groups.google.com/group/comp.lang.python/browse_frm/thread/6df6e6b541a15bc2/09f28e26af0699b1
597597

598-
import textwrap
599-
from optparse import IndentedHelpFormatter
600-
601598

602599
class IndentedHelpFormatterWithNL(IndentedHelpFormatter):
603600
def _format_text(self, text):
@@ -652,7 +649,7 @@ def format_option(self, option):
652649
return "".join(result)
653650

654651

655-
### End class
652+
# End class
656653

657654
if __name__ == "__main__":
658655
main()

diffpy/srmise/applications/plot.py

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@
1919
import mpl_toolkits.axisartist as AA
2020
import numpy as np
2121
from matplotlib.ticker import MultipleLocator
22-
from mpl_toolkits.axes_grid1 import make_axes_locatable
2322
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
2423

2524
from diffpy.srmise import PDFPeakExtraction, PeakStability
@@ -107,7 +106,6 @@ def comparepositions(ppe, ip=None, **kwds):
107106
plt.plot(xe, ye, "g", lw=1.5, **ep_style)
108107

109108
if ip is not None:
110-
yb = (base, base)
111109
plt.axhline(base, linestyle=":", color="k")
112110
ax.yaxis.set_ticks([base + 0.5 * yideal, base + 0.5 * yext])
113111
ax.yaxis.set_ticklabels([yideal_label, yext_label])
@@ -134,7 +132,7 @@ def comparepositions(ppe, ip=None, **kwds):
134132

135133

136134
def dgseries(stability, **kwds):
137-
ax = kwds.get("ax", plt.gca())
135+
kwds.get("ax", plt.gca())
138136
dg_style = kwds.get("dg_style", default_dg_style)
139137

140138
scale = kwds.get("scale", 1.0)
@@ -222,7 +220,7 @@ def makeplot(ppe_or_stability, ip=None, **kwds):
222220
bottom_offset = kwds.get("bottom_offset", 3.0)
223221

224222
# Style options
225-
dg_style = kwds.get("dg_style", default_dg_style)
223+
kwds.get("dg_style", default_dg_style)
226224
gobs_style = kwds.get("gobs_style", default_gobs_style)
227225
gfit_style = kwds.get("gfit_style", default_gfit_style)
228226
gind_style = kwds.get("gind_style", default_gind_style)
@@ -240,7 +238,7 @@ def makeplot(ppe_or_stability, ip=None, **kwds):
240238
# Other options
241239
datalabel = kwds.get("datalabel", None)
242240
dgformatstr = kwds.get("dgformatstr", r"$\delta$g=%f")
243-
dgformatpost = kwds.get("dgformatpost", None) # ->userfunction(string)
241+
kwds.get("dgformatpost", None) # ->userfunction(string)
244242
show_fit = kwds.get("show_fit", True)
245243
show_individual = kwds.get("show_individual", True)
246244
fill_individual = kwds.get("fill_individual", True)
@@ -532,7 +530,6 @@ def on_draw(event):
532530

533531
def readcompare(filename):
534532
"""Returns a list of distances read from filename, otherwise None."""
535-
from diffpy.srmise.srmiseerrors import SrMiseDataFormatError, SrMiseFileError
536533

537534
# TODO: Make this safer
538535
try:
@@ -551,7 +548,7 @@ def readcompare(filename):
551548
try:
552549
for line in datastring.split("\n"):
553550
distances.append(float(line))
554-
except (ValueError, IndexError) as err:
551+
except (ValueError, IndexError):
555552
print("Could not read distances from '%s'. Ignoring file." % filename)
556553

557554
if len(distances) == 0:
@@ -620,7 +617,7 @@ def main():
620617
distances = readcompare(opts.compare)
621618

622619
setfigformat(figsize=(6.0, 4.0))
623-
figdict = makeplot(toplot, distances)
620+
makeplot(toplot, distances)
624621
if opts.output:
625622
plt.savefig(opts.output, format=opts.format, dpi=600)
626623
if opts.show:

diffpy/srmise/basefunction.py

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,7 @@
1919
import numpy as np
2020
from numpy.compat import unicode
2121

22-
from diffpy.srmise.modelparts import ModelPart, ModelParts
23-
from diffpy.srmise.srmiseerrors import *
22+
from diffpy.srmise.srmiseerrors import SrMiseDataFormatError
2423

2524
logger = logging.getLogger("diffpy.srmise")
2625

@@ -120,7 +119,7 @@ def __init__(
120119
emsg = "Argument default_formats must specify 'default_input' " + "and 'default_output' as keys."
121120
raise ValueError(emsg)
122121
for f in self.default_formats.values():
123-
if not f in self.parformats:
122+
if f not in self.parformats:
124123
emsg = "Keys of argument default_formats must map to a " + "value within argument parformats."
125124
raise ValueError()
126125

@@ -140,7 +139,7 @@ def __init__(
140139
pass
141140
return
142141

143-
#### "Virtual" class methods ####
142+
# "Virtual" class methods ####
144143

145144
def actualize(self, *args, **kwds):
146145
"""Create ModelPart instance of self with given parameters. ("Virtual" method)"""
@@ -172,7 +171,7 @@ def _valueraw(self, *args, **kwds):
172171
emsg = "_valueraw must() be implemented in a BaseFunction subclass."
173172
raise NotImplementedError(emsg)
174173

175-
#### Class methods ####
174+
# Class methods ####
176175

177176
def jacobian(self, p, r, rng=None):
178177
"""Calculate jacobian of p, possibly restricted by range.
@@ -228,9 +227,9 @@ def transform_derivatives(self, pars, in_format=None, out_format=None):
228227
elif out_format == "default_input":
229228
out_format = self.default_formats["default_input"]
230229

231-
if not in_format in self.parformats:
230+
if in_format not in self.parformats:
232231
raise ValueError("Argument 'in_format' must be one of %s." % self.parformats)
233-
if not out_format in self.parformats:
232+
if out_format not in self.parformats:
234233
raise ValueError("Argument 'out_format' must be one of %s." % self.parformats)
235234
if in_format == out_format:
236235
return np.identity(self.npars)
@@ -263,9 +262,9 @@ def transform_parameters(self, pars, in_format=None, out_format=None):
263262
elif out_format == "default_input":
264263
out_format = self.default_formats["default_input"]
265264

266-
if not in_format in self.parformats:
265+
if in_format not in self.parformats:
267266
raise ValueError("Argument 'in_format' must be one of %s." % self.parformats)
268-
if not out_format in self.parformats:
267+
if out_format not in self.parformats:
269268
raise ValueError("Argument 'out_format' must be one of %s." % self.parformats)
270269
# if in_format == out_format:
271270
# return pars
@@ -335,7 +334,7 @@ def writestr(self, baselist):
335334
"""
336335
if self.base is not None and self.base not in baselist:
337336
emsg = "baselist does not include this BaseFunction's base function."
338-
raise ValueError("emsg")
337+
raise ValueError(emsg)
339338
lines = []
340339
# Write function type
341340
lines.append("function=%s" % repr(self.__class__.__name__))

diffpy/srmise/baselines/arbitrary.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,8 @@
1313

1414
import logging
1515

16-
import matplotlib.pyplot as plt
1716
import numpy as np
1817

19-
import diffpy.srmise.srmiselog
2018
from diffpy.srmise.baselines import Polynomial
2119
from diffpy.srmise.baselines.base import BaselineFunction
2220
from diffpy.srmise.srmiseerrors import SrMiseEstimationError
@@ -97,7 +95,7 @@ def __init__(self, npars, valuef, jacobianf=None, estimatef=None, Cache=None):
9795
metadict["estimatef"] = (estimatef, repr)
9896
BaselineFunction.__init__(self, parameterdict, formats, default_formats, metadict, None, Cache)
9997

100-
#### Methods required by BaselineFunction ####
98+
# Methods required by BaselineFunction ####
10199

102100
def estimate_parameters(self, r, y):
103101
"""Estimate parameters for data baseline.
@@ -133,7 +131,7 @@ def _jacobianraw(self, pars, r, free):
133131
needed. True for evaluation, False for no evaluation."""
134132
nfree = None
135133
if self.jacobianf is None:
136-
nfree = (pars == True).sum()
134+
nfree = (pars is True).sum()
137135
if nfree != 0:
138136
emsg = "No jacobian routine provided to Arbitrary."
139137
raise NotImplementedError(emsg)

diffpy/srmise/baselines/base.py

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,9 @@
1515

1616
import numpy as np
1717

18-
import diffpy.srmise.srmiselog
1918
from diffpy.srmise.basefunction import BaseFunction
2019
from diffpy.srmise.modelparts import ModelPart
21-
from diffpy.srmise.srmiseerrors import *
20+
from diffpy.srmise.srmiseerrors import SrMiseDataFormatError
2221

2322
logger = logging.getLogger("diffpy.srmise")
2423

@@ -85,9 +84,9 @@ def __init__(
8584
evaluations."""
8685
BaseFunction.__init__(self, parameterdict, parformats, default_formats, metadict, base, Cache)
8786

88-
#### "Virtual" class methods ####
87+
# "Virtual" class methods ####
8988

90-
#### Methods required by BaseFunction ####
89+
# Methods required by BaseFunction ####
9190

9291
def actualize(
9392
self,
@@ -136,17 +135,16 @@ def factory(baselinestr, ownerlist):
136135
baselinestr: string representing Baseline
137136
ownerlist: List of BaseFunctions that owner is in
138137
"""
139-
from numpy import array
140138

141139
data = baselinestr.strip().splitlines()
142140

143141
# dictionary of parameters
144142
pdict = {}
145143
for d in data:
146-
l = d.split("=", 1)
147-
if len(l) == 2:
144+
result = d.split("=", 1)
145+
if len(result) == 2:
148146
try:
149-
pdict[l[0]] = eval(l[1])
147+
pdict[result[0]] = eval(result[1])
150148
except Exception:
151149
emsg = "Invalid parameter: %s" % d
152150
raise SrMiseDataFormatError(emsg)
@@ -169,10 +167,8 @@ def factory(baselinestr, ownerlist):
169167
# simple test code
170168
if __name__ == "__main__":
171169

172-
import matplotlib.pyplot as plt
173170
from numpy.random import randn
174171

175-
from diffpy.srmise.modelcluster import ModelCluster
176172
from diffpy.srmise.modelevaluators import AICc
177173
from diffpy.srmise.peaks import GaussianOverR, Peaks
178174

diffpy/srmise/baselines/fromsequence.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,9 @@
1313

1414
import logging
1515

16-
import matplotlib.pyplot as plt
1716
import numpy as np
1817
import scipy.interpolate as spi
1918

20-
import diffpy.srmise.srmiselog
2119
from diffpy.srmise.baselines.base import BaselineFunction
2220

2321
logger = logging.getLogger("diffpy.srmise")
@@ -80,7 +78,7 @@ def __init__(self, *args, **kwds):
8078
metadict["y"] = (y, self.xyrepr)
8179
BaselineFunction.__init__(self, parameterdict, formats, default_formats, metadict, None, Cache=None)
8280

83-
#### Methods required by BaselineFunction ####
81+
# Methods required by BaselineFunction ####
8482

8583
def estimate_parameters(self, r, y):
8684
"""Return empty numpy array.
@@ -151,7 +149,7 @@ def _valueraw(self, pars, r):
151149
[r[0], r[-1]],
152150
[self.minx, self.maxx],
153151
)
154-
except (IndexError, TypeError) as e:
152+
except (IndexError, TypeError):
155153
if r < self.minx or r > self.maxx:
156154
logger.warn(
157155
"Warning: Evaluating interpolating function at %s, outside safe range of %s.",
@@ -169,7 +167,7 @@ def xyrepr(self, var):
169167

170168
def readxy(self, filename):
171169
""" """
172-
from diffpy.srmise.srmiseerrors import SrMiseDataFormatError, SrMiseFileError
170+
from diffpy.srmise.srmiseerrors import SrMiseDataFormatError
173171

174172
# TODO: Make this safer
175173
try:

diffpy/srmise/baselines/nanospherical.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,9 @@
1313

1414
import logging
1515

16-
import matplotlib.pyplot as plt
1716
import numpy as np
1817

19-
import diffpy.srmise.srmiselog
2018
from diffpy.srmise.baselines.base import BaselineFunction
21-
from diffpy.srmise.srmiseerrors import SrMiseEstimationError
2219

2320
logger = logging.getLogger("diffpy.srmise")
2421

@@ -54,7 +51,7 @@ def __init__(self, Cache=None):
5451
metadict = {}
5552
BaselineFunction.__init__(self, parameterdict, formats, default_formats, metadict, None, Cache)
5653

57-
#### Methods required by BaselineFunction ####
54+
# Methods required by BaselineFunction ####
5855

5956
# def estimate_parameters(self, r, y):
6057
# """Estimate parameters for spherical baseline. (Not implemented!)
@@ -90,7 +87,7 @@ def _jacobianraw(self, pars, r, free):
9087
emsg = "Argument free must have " + str(self.npars) + " elements."
9188
raise ValueError(emsg)
9289
jacobian = [None for p in range(self.npars)]
93-
if (free == False).sum() == self.npars:
90+
if (free is False).sum() == self.npars:
9491
return jacobian
9592

9693
if np.isscalar(r):
@@ -123,7 +120,7 @@ def _jacobianrawscale(self, pars, r):
123120
pars[1] = radius
124121
r - sequence or scalar over which pars is evaluated.
125122
"""
126-
s = np.abs(pars[0])
123+
np.abs(pars[0])
127124
R = np.abs(pars[1])
128125
rdivR = r / R
129126
# From abs'(s) in derivative, which is equivalent to sign(s) except at 0 where it

0 commit comments

Comments
 (0)