Skip to content

Commit e46ac63

Browse files
committed
fix: fix load single peak in py3 support
1 parent fb49c4d commit e46ac63

8 files changed

Lines changed: 110 additions & 21 deletions

File tree

news/fix-single-peak.rst

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
**Added:**
2+
3+
* <news item>
4+
5+
**Changed:**
6+
7+
* <news item>
8+
9+
**Deprecated:**
10+
11+
* <news item>
12+
13+
**Removed:**
14+
15+
* <news item>
16+
17+
**Fixed:**
18+
19+
* Fixed extracting single peak with `py2` legacy cleanup
20+
21+
**Security:**
22+
23+
* <news item>

src/diffpy/srmise/applications/extract.py

Lines changed: 70 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,63 @@
1818
import numpy as np
1919

2020

21+
def _resolve_cli_expression(expression, namespace):
22+
"""Resolve a CLI expression against an explicit namespace.
23+
24+
Parameters
25+
----------
26+
expression : str
27+
The user-supplied CLI expression.
28+
namespace : dict
29+
The explicit namespace allowed during evaluation.
30+
31+
Returns
32+
-------
33+
object
34+
The resolved class or instance.
35+
"""
36+
return eval(expression, {"__builtins__": {}}, namespace)
37+
38+
39+
def _baseline_namespace():
40+
"""Return the baseline classes supported by the CLI."""
41+
from diffpy.srmise.baselines.arbitrary import Arbitrary
42+
from diffpy.srmise.baselines.fromsequence import FromSequence
43+
from diffpy.srmise.baselines.nanospherical import NanoSpherical
44+
from diffpy.srmise.baselines.polynomial import Polynomial
45+
46+
return {
47+
"Arbitrary": Arbitrary,
48+
"FromSequence": FromSequence,
49+
"NanoSpherical": NanoSpherical,
50+
"Polynomial": Polynomial,
51+
}
52+
53+
54+
def _peakfunction_namespace():
55+
"""Return the peak-function classes supported by the CLI."""
56+
from diffpy.srmise.peaks.gaussian import Gaussian
57+
from diffpy.srmise.peaks.gaussianoverr import GaussianOverR
58+
from diffpy.srmise.peaks.terminationripples import TerminationRipples
59+
60+
return {
61+
"Gaussian": Gaussian,
62+
"GaussianOverR": GaussianOverR,
63+
"TerminationRipples": TerminationRipples,
64+
}
65+
66+
67+
def _modelevaluator_namespace():
68+
"""Return the model evaluators supported by the CLI."""
69+
from diffpy.srmise.modelevaluators.aic import AIC
70+
from diffpy.srmise.modelevaluators.aicc import AICc
71+
72+
return {
73+
"AIC": AIC,
74+
"AICc": AICc,
75+
}
76+
77+
2178
def main():
2279
"""Default SrMise entry-point."""
2380

@@ -433,15 +490,21 @@ def main():
433490

434491
if options.peakfunction:
435492
try:
436-
options.peakfunction = eval("peaks." + options.peakfunction)
493+
options.peakfunction = _resolve_cli_expression(
494+
options.peakfunction,
495+
_peakfunction_namespace(),
496+
)
437497
except Exception as err:
438498
print(err)
439499
print("Could not create peak function '%s'. Exiting." % options.peakfunction)
440500
return
441501

442502
if options.modelevaluator:
443503
try:
444-
options.modelevaluator = eval("modelevaluators." + options.modelevaluator)
504+
options.modelevaluator = _resolve_cli_expression(
505+
options.modelevaluator,
506+
_modelevaluator_namespace(),
507+
)
445508
except Exception as err:
446509
print(err)
447510
print("Could not find ModelEvaluator '%s'. Exiting." % options.modelevaluator)
@@ -483,10 +546,12 @@ def main():
483546

484547
bl = NanoSpherical()
485548
options.baseline = parsepars(bl, options.bspherical)
486-
549+
elif options.baseline:
487550
try:
488-
options.baseline = eval("baselines." + options.baseline)
489-
551+
options.baseline = _resolve_cli_expression(
552+
options.baseline,
553+
_baseline_namespace(),
554+
)
490555
except Exception as err:
491556
print(err)
492557
print("Could not create baseline '%s'. Exiting." % options.baseline)

src/diffpy/srmise/dataclusters.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -206,19 +206,19 @@ def __next__(self):
206206

207207
if np.abs(nearest_cluster[1]) <= self.res:
208208
# Add to an existing cluster
209-
self.lastcluster_idx = nearest_cluster[0]
210-
if test_idx < self.clusters[nearest_cluster[0], 0]:
211-
self.clusters[nearest_cluster[0], 0] = test_idx
209+
self.lastcluster_idx = int(nearest_cluster[0])
210+
if test_idx < self.clusters[int(nearest_cluster[0]), 0]:
211+
self.clusters[int(nearest_cluster[0]), 0] = test_idx
212212
else:
213-
self.clusters[nearest_cluster[0], 1] = test_idx
213+
self.clusters[int(nearest_cluster[0]), 1] = test_idx
214214
else:
215215
# Make a new cluster
216216
if nearest_cluster[1] < 0:
217217
# Insert left of nearest cluster
218-
self.lastcluster_idx = nearest_cluster[0]
218+
self.lastcluster_idx = int(nearest_cluster[0])
219219
else:
220220
# insert right of nearest cluster
221-
self.lastcluster_idx = nearest_cluster[0] + 1
221+
self.lastcluster_idx = int(nearest_cluster[0]) + 1
222222
self.clusters = np.insert(
223223
self.clusters,
224224
int(self.lastcluster_idx),

src/diffpy/srmise/modelcluster.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1174,7 +1174,7 @@ def cleanfit(self):
11741174
pos = np.array([p["position"] for p in self.model])
11751175
left_idx = pos.searchsorted(self.r_cluster[0])
11761176
right_idx = pos.searchsorted(self.r_cluster[-1])
1177-
outside_idx = range(0, left_idx)
1177+
outside_idx = list(range(0, left_idx))
11781178
outside_idx.extend(range(right_idx, len(self.model)))
11791179
# inside_idx = range(left_idx, right_idx)
11801180

@@ -1538,8 +1538,8 @@ def prune(self):
15381538
# Create model with ith peak removed, and distant peaks effectively fixed
15391539
lo = max(i - peak_range, 0)
15401540
hi = min(i + peak_range + 1, len(best_model))
1541-
check_models[i] = best_model[lo:i].copy()
1542-
check_models[i].extend(best_model[i + 1 : hi].copy())
1541+
check_models[i] = type(best_model)(best_model[lo:i]).copy()
1542+
check_models[i].extend(type(best_model)(best_model[i + 1: hi]).copy())
15431543
prune_mc.model = check_models[i]
15441544

15451545
msg = [

src/diffpy/srmise/modelevaluators/aic.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ def minpoints(self, npars):
106106

107107
return 1
108108

109-
def parpenalty(self, k):
109+
def parpenalty(self, k, n=None):
110110
"""Returns the cost for adding k parameters to the current model
111111
cluster.
112112

src/diffpy/srmise/modelparts.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -430,8 +430,9 @@ def __getitem__(self, index):
430430
if isinstance(index, tuple) and len(index) == 2:
431431
start, end = index
432432
return self.__class__(super().__getitem__(slice(start, end)))
433-
else:
434-
return super().__getitem__(index)
433+
if isinstance(index, slice):
434+
return self.__class__(super().__getitem__(index))
435+
return super().__getitem__(index)
435436

436437
def transform(self, in_format="internal", out_format="internal"):
437438
"""Transforms format of parameters in this modelpart.

src/diffpy/srmise/peakextraction.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -905,7 +905,7 @@ def extract_single(self, recursion_depth=1):
905905
)
906906
else:
907907
# Update an existing cluster
908-
mclusters[step.lastcluster_idx].change_slice(step.cut(step.lastcluster_idx))
908+
mclusters[int(step.lastcluster_idx)].change_slice(step.cut(step.lastcluster_idx))
909909

910910
# Find newly adjacent clusters
911911
adjacent = step.find_adjacent_clusters().ravel()
@@ -969,7 +969,7 @@ def extract_single(self, recursion_depth=1):
969969
# near_peaks: array containing the indices of two nearest peaks on either side of border_x
970970
# other_peaks: all the other peaks in full_cluster
971971
# left_data, right_data: indices defining the extent of the "interpeak range" for x, etc.
972-
near_peaks = np.array([], dtype=np.int)
972+
near_peaks = np.array([], dtype=np.int64)
973973

974974
# interpeak range goes from peak to peak of next nearest peaks, although their contributions
975975
# to the data are still removed.
@@ -1122,7 +1122,7 @@ def extract_single(self, recursion_depth=1):
11221122
# near_peaks: array containing the indices of two nearest peaks on either side of border_x
11231123
# other_peaks: all the other peaks in new_cluster
11241124
# left_data, right_data: indices defining the extent of the "interpeak range" for x, etc.
1125-
near_peaks = np.array([], dtype=np.int)
1125+
near_peaks = np.array([], dtype=np.int64)
11261126

11271127
# interpeak range goes from peak to peak of next nearest peaks, although their contributions
11281128
# to the data are still removed.

src/diffpy/srmise/peaks/terminationripples.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -316,7 +316,7 @@ def value(self, peak, r, rng=None):
316316
# issues is difficult to determine without detailed knowledge
317317
# of the underlying function.
318318
dr = (r[-1] - r[0]) / (len(r) - 1)
319-
segments = np.ceil(dr / dr_super)
319+
segments = int(np.ceil(dr / dr_super))
320320
dr_segmented = dr / segments
321321

322322
rpart = r[rng]

0 commit comments

Comments
 (0)