Skip to content

Commit 71e52e5

Browse files
authored
Merge pull request #70 from Sparks29032/update_tests
Fixed some pytest compatibility issues
2 parents bde243d + 2ce008f commit 71e52e5

File tree

11 files changed

+92
-32
lines changed

11 files changed

+92
-32
lines changed

diffpy/pdfmorph/log.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
plog = logging.getLogger('diffpy.pdfmorph')
2727

2828

29-
def setVerbosity(vb):
29+
def set_verbosity(vb):
3030
'''Set verbosity of the pdfmorph logger.
3131
3232
vb -- integer or one of ('debug', 'info', 'warning', 'error') strings

diffpy/pdfmorph/pdfmorph_api.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,7 @@ def pdfmorph(
152152
Examples
153153
--------
154154
# morphing (xobj, yobj) pair to (xref, yref) pair with scaling
155-
from diffpy.pdfmorph import pdfmorph, morph_default_config, plot_morph
155+
from diffpy.pdfmorph.pdfmorph_api import pdfmorph, morph_default_config, plot_morph
156156
157157
morph_cfg = morph_default_config(scale=1.01)
158158
morph_rv_dict = pdfmorph(xobj, yobj, xref, yref, **morph_cfg)
@@ -203,7 +203,7 @@ def pdfmorph(
203203
if pearson:
204204
refiner.residual = refiner._pearson
205205
if add_pearson:
206-
refiner.residual = refiner._addpearson
206+
refiner.residual = refiner._add_pearson
207207
# execute morphing
208208
if refpars and refine:
209209
# This works better when we adjust scale and smear first.
@@ -220,7 +220,7 @@ def pdfmorph(
220220

221221
# summary
222222
rw = tools.getRw(chain)
223-
pcc = tools.getPearson(chain)
223+
pcc = tools.get_pearson(chain)
224224
# restore rgrid
225225
chain[0] = morphs.Morph()
226226
chain(xobj, yobj, xref, yref)

diffpy/pdfmorph/pdfmorphapp.py

Lines changed: 25 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
import diffpy.pdfmorph.refine as refine
2929

3030

31-
def createOptionParser():
31+
def create_option_parser():
3232
import optparse
3333

3434
class CustomParser(optparse.OptionParser):
@@ -48,6 +48,7 @@ def custom_error(self, msg):
4848
[
4949
"%prog [options] FILE1 FILE2",
5050
"Manipulate and compare PDFs.",
51+
"Use --help for help.",
5152
]
5253
),
5354
epilog="Please report bugs to diffpy-dev@googlegroups.com.",
@@ -189,19 +190,23 @@ def custom_error(self, msg):
189190
group.add_option(
190191
'--mag', type="float", help="Magnify plot curves beyond MAGLIM by MAG."
191192
)
193+
group.add_option(
194+
'--lwidth', type="float", help="Line thickness of plotted curves."
195+
)
192196

193197
# Defaults
194198
parser.set_defaults(plot=True)
195199
parser.set_defaults(refine=True)
196200
parser.set_defaults(pearson=False)
197201
parser.set_defaults(addpearson=False)
198202
parser.set_defaults(mag=5)
203+
parser.set_defaults(lwidth=1.5)
199204

200205
return parser
201206

202207

203208
def main():
204-
parser = createOptionParser()
209+
parser = create_option_parser()
205210
(opts, pargs) = parser.parse_args()
206211

207212
if len(pargs) != 2:
@@ -253,31 +258,39 @@ def main():
253258
if opts.baselineslope is None:
254259
refpars.append("baselineslope")
255260
config["baselineslope"] = -0.5
261+
262+
def nn_value(val, name):
263+
if val < 0:
264+
negative_value_warning = f"\n# Negative value for {name} given. Using absolute value instead."
265+
print(negative_value_warning)
266+
return -val
267+
return val
268+
256269
## Size
257270
radii = [opts.radius, opts.pradius]
258271
nrad = 2 - radii.count(None)
259272
if nrad == 1:
260273
radii.remove(None)
261-
config["radius"] = radii[0]
274+
config["radius"] = nn_value(radii[0], "radius or pradius")
262275
chain.append(morphs.MorphSphere())
263276
refpars.append("radius")
264277
elif nrad == 2:
265-
config["radius"] = radii[0]
278+
config["radius"] = nn_value(radii[0], "radius")
266279
refpars.append("radius")
267-
config["pradius"] = radii[1]
280+
config["pradius"] = nn_value(radii[1], "pradius")
268281
refpars.append("pradius")
269282
chain.append(morphs.MorphSpheroid())
270283
iradii = [opts.iradius, opts.ipradius]
271284
inrad = 2 - iradii.count(None)
272285
if inrad == 1:
273286
iradii.remove(None)
274-
config["iradius"] = iradii[0]
287+
config["iradius"] = nn_value(iradii[0], "iradius or ipradius")
275288
chain.append(morphs.MorphISphere())
276289
refpars.append("iradius")
277290
elif inrad == 2:
278-
config["iradius"] = iradii[0]
291+
config["iradius"] = nn_value(iradii[0], "iradius")
279292
refpars.append("iradius")
280-
config["ipradius"] = iradii[1]
293+
config["ipradius"] = nn_value(iradii[1], "ipradius")
281294
refpars.append("ipradius")
282295
chain.append(morphs.MorphISpheroid())
283296

@@ -297,7 +310,7 @@ def main():
297310
if opts.pearson:
298311
refiner.residual = refiner._pearson
299312
if opts.addpearson:
300-
refiner.residual = refiner._addpearson
313+
refiner.residual = refiner._add_pearson
301314
if opts.refine and refpars:
302315
try:
303316
# This works better when we adjust scale and smear first.
@@ -319,7 +332,7 @@ def main():
319332

320333
# Get Rw for the morph range
321334
rw = tools.getRw(chain)
322-
pcc = tools.getPearson(chain)
335+
pcc = tools.get_pearson(chain)
323336
# Replace the MorphRGrid with Morph identity
324337
chain[0] = morphs.Morph()
325338
chain(xobj, yobj, xref, yref)
@@ -376,8 +389,9 @@ def main():
376389
pmax = opts.pmax if opts.pmax is not None else opts.rmax
377390
maglim = opts.maglim
378391
mag = opts.mag
392+
l_width = opts.lwidth
379393
pdfplot.comparePDFs(
380-
pairlist, labels, rmin=pmin, rmax=pmax, maglim=maglim, mag=mag, rw=rw
394+
pairlist, labels, rmin=pmin, rmax=pmax, maglim=maglim, mag=mag, rw=rw, l_width=l_width
381395
)
382396

383397
return

diffpy/pdfmorph/pdfplot.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ def plotPDFs(pairlist, labels=None, offset='auto', rmin=None, rmax=None):
4343
if labels is None:
4444
labels = []
4545
if offset == 'auto':
46-
offset = _findOffset(pairlist)
46+
offset = _find_offset(pairlist)
4747

4848
gap = len(pairlist) - len(labels)
4949
labels = list(labels)
@@ -74,6 +74,7 @@ def comparePDFs(
7474
mag=5,
7575
rw=None,
7676
legend=True,
77+
l_width=1.5,
7778
):
7879
"""Plot two PDFs on top of each other and difference curve.
7980
@@ -96,7 +97,6 @@ def comparePDFs(
9697
line. The difference curve will be in green and offset for clarity.
9798
9899
"""
99-
100100
if labels is None:
101101
labels = [2]
102102
labeldata = None
@@ -111,7 +111,7 @@ def comparePDFs(
111111
rvmin = max(rfit[0], rdat[0])
112112
rvmin = rmin or rvmin
113113
rvmax = min(rfit[-1], rdat[-1])
114-
rvmax = rmax or rfit[-1]
114+
rvmax = rmax or rvmax
115115

116116
gap = 2 - len(labels)
117117
labels = list(labels)
@@ -162,12 +162,12 @@ def comparePDFs(
162162
fig.add_axes(axes)
163163
plt.minorticks_on()
164164

165-
plt.plot(rdat, grdat, label=labeldata)
166-
plt.plot(rfit, grfit, label=labelfit)
167-
plt.plot(rdat, offset * numpy.ones_like(diff), color='black')
165+
plt.plot(rdat, grdat, linewidth=l_width, label=labeldata)
166+
plt.plot(rfit, grfit, linewidth=l_width, label=labelfit)
167+
plt.plot(rdat, offset * numpy.ones_like(diff), linewidth=3, color='black')
168168

169169
diff += offset
170-
plt.plot(rdat, diff, label=labeldiff)
170+
plt.plot(rdat, diff, linewidth=l_width, label=labeldiff)
171171

172172
if maglim is not None:
173173
# Add a line for the magnification cutoff
@@ -232,7 +232,7 @@ def truncatePDFs(r, gr, rmin=None, rmax=None):
232232
return r, gr
233233

234234

235-
def _findOffset(pairlist):
235+
def _find_offset(pairlist):
236236
"""Find an optimal offset between PDFs."""
237237
maxlist = [max(p[1]) for p in pairlist]
238238
minlist = [min(p[1]) for p in pairlist]

diffpy/pdfmorph/refine.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -56,15 +56,15 @@ def __init__(self, chain, xobj, yobj, xref, yref):
5656
self.residual = self._residual
5757
return
5858

59-
def _updateChain(self, pvals):
59+
def _update_chain(self, pvals):
6060
"""Update the parameters in the chain."""
6161
pairs = zip(self.pars, pvals)
6262
self.chain.config.update(pairs)
6363
return
6464

6565
def _residual(self, pvals):
6666
"""Standard vector residual."""
67-
self._updateChain(pvals)
67+
self._update_chain(pvals)
6868
_xobj, _yobj, _xref, _yref = self.chain(
6969
self.xobj, self.yobj, self.xref, self.yref
7070
)
@@ -78,14 +78,14 @@ def _pearson(self, pvals):
7878
We seek to minimize this, which occurrs when the correlation is the
7979
largest.
8080
"""
81-
self._updateChain(pvals)
81+
self._update_chain(pvals)
8282
_xobj, _yobj, _xref, _yref = self.chain(
8383
self.xobj, self.yobj, self.xref, self.yref
8484
)
8585
pcc, pval = pearsonr(_yobj, _yref)
8686
return ones_like(_xobj) * exp(-pcc)
8787

88-
def _addpearson(self, pvals):
88+
def _add_pearson(self, pvals):
8989
"""Refine both the pearson and residual."""
9090
res1 = self._residual(pvals)
9191
res2 = self._pearson(pvals)

diffpy/pdfmorph/tests/__init__.py

Whitespace-only changes.

diffpy/pdfmorph/tests/run.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
##############################################################################
1515

1616
"""Convenience module for executing all unit tests with
17-
python -m diffpy.structure.tests.run
17+
python -m diffpy.morphs.tests.run
1818
"""
1919

2020

diffpy/pdfmorph/tests/test_morph_func.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1-
import pytest
1+
#!/usr/bin/env python
2+
3+
24
import numpy as np
3-
from diffpy.pdfmorph import pdfmorph, morph_default_config
5+
from diffpy.pdfmorph.pdfmorph_api import pdfmorph, morph_default_config
46
from diffpy.pdfmorph.tests.test_morphstretch import heaviside
57

68

diffpy/pdfmorph/tests/test_parser.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
#!/usr/bin/env python
2+
3+
4+
import unittest
5+
from diffpy.pdfmorph.pdfmorphapp import create_option_parser
6+
7+
8+
class TestCreateOptionParser(unittest.TestCase):
9+
def setUp(self):
10+
self.parser = create_option_parser()
11+
return
12+
13+
# Check numerical inputs parsed correctly into parser
14+
def test_parser_numerical(self):
15+
renamed_dests = {"slope": "baselineslope"}
16+
17+
# Check values parsed correctly
18+
n_names = ["--rmin", "--rmax", "--scale", "--smear", "--stretch", "--slope", "--qdamp"]
19+
n_values = ["2.5", "40", "2.1", "-0.8", "0.0000005", "-0.0000005", ".00000003"]
20+
n_names.extend(["--radius", "--pradius", "--iradius", "--ipradius", "--pmin", "--pmax"])
21+
n_values.extend(["+0.5", "-0.2", "+.3", "-.1", "2.5", "40"])
22+
n_names.extend(["--lwidth", "--maglim", "--mag"])
23+
n_values.extend(["1.6", "50", "5"])
24+
n_total = len(n_names)
25+
n_input = []
26+
for idx in range(n_total):
27+
n_input.append(n_names[idx])
28+
n_input.append(n_values[idx])
29+
n_input.append("leftover") # One leftover
30+
n_opts, n_args = self.parser.parse_args(n_input)
31+
n_opts_dict = vars(n_opts)
32+
for idx in range(n_total):
33+
n_parsed_name = n_names[idx][2:]
34+
n_parsed_val = n_opts_dict.get(n_parsed_name)
35+
if n_parsed_val is None:
36+
assert n_parsed_name in renamed_dests # Ensure .get() failed due to destination renaming
37+
n_parsed_name = renamed_dests.get(n_parsed_name)
38+
n_parsed_val = n_opts_dict.get(n_parsed_name)
39+
assert isinstance(n_parsed_val, float) # Check if is float
40+
assert n_parsed_val == float(n_values[idx]) # Check correct value parsed
41+
assert len(n_args) == 1 # Check one leftover

diffpy/pdfmorph/tests/test_plot_morph.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
1+
#!/usr/bin/env python
2+
3+
14
import numpy as np
25
import matplotlib as mpl
36
import matplotlib.pyplot as plt
4-
from diffpy.pdfmorph import pdfmorph, morph_default_config, plot_morph
7+
from diffpy.pdfmorph.pdfmorph_api import pdfmorph, morph_default_config, plot_morph
58
from diffpy.pdfmorph.tests.test_morphstretch import heaviside
69

710

diffpy/pdfmorph/tools.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ def getRw(chain):
8888
return rw
8989

9090

91-
def getPearson(chain):
91+
def get_pearson(chain):
9292
from scipy.stats import pearsonr
9393

9494
xobj, yobj, xref, yref = chain.xyallout

0 commit comments

Comments
 (0)