Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions news/fix-single-peak.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
**Added:**

* <news item>

**Changed:**

* <news item>

**Deprecated:**

* <news item>

**Removed:**

* <news item>

**Fixed:**

* Fixed extracting single peak with `py2` legacy cleanup

**Security:**

* <news item>
24 changes: 21 additions & 3 deletions src/diffpy/srmise/applications/extract.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,21 @@
import numpy as np


def _baseline_namespace():
"""Return the baseline classes supported by the CLI."""
from diffpy.srmise.baselines.arbitrary import Arbitrary
from diffpy.srmise.baselines.fromsequence import FromSequence
from diffpy.srmise.baselines.nanospherical import NanoSpherical
from diffpy.srmise.baselines.polynomial import Polynomial

return {
"Arbitrary": Arbitrary,
"FromSequence": FromSequence,
"NanoSpherical": NanoSpherical,
"Polynomial": Polynomial,
}


def main():
"""Default SrMise entry-point."""

Expand Down Expand Up @@ -483,10 +498,13 @@ def main():

bl = NanoSpherical()
options.baseline = parsepars(bl, options.bspherical)

elif options.baseline is not None:
try:
options.baseline = eval("baselines." + options.baseline)

options.baseline = eval(
options.baseline,
{"__builtins__": {}},
_baseline_namespace(),
)
except Exception as err:
print(err)
print("Could not create baseline '%s'. Exiting." % options.baseline)
Expand Down
8 changes: 4 additions & 4 deletions src/diffpy/srmise/dataclusters.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ def __next__(self):
self.lastcluster_idx = nearest_cluster[0] + 1
self.clusters = np.insert(
self.clusters,
int(self.lastcluster_idx),
self.lastcluster_idx,
[test_idx, test_idx],
0,
)
Expand Down Expand Up @@ -289,7 +289,7 @@ def find_nearest_cluster(self, idx):
return None

flat_idx = clusters_flat.searchsorted(idx)
near_idx = flat_idx / 2
near_idx = flat_idx // 2

if flat_idx == len(clusters_flat):
# test_idx is right of the last cluster
Expand All @@ -304,8 +304,8 @@ def find_nearest_cluster(self, idx):
# Calculate which of the two nearest clusters is closer
distances = np.array(
[
self.x[idx] - self.x[self.clusters[int(near_idx) - 1, 1]],
self.x[idx] - self.x[self.clusters[int(near_idx), 0]],
self.x[idx] - self.x[self.clusters[near_idx - 1, 1]],
self.x[idx] - self.x[self.clusters[near_idx, 0]],
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is to revert the incorrect fix done on summer 2024.

]
)
if distances[0] < np.abs(distances[1]):
Expand Down
2 changes: 1 addition & 1 deletion src/diffpy/srmise/modelcluster.py
Original file line number Diff line number Diff line change
Expand Up @@ -1174,7 +1174,7 @@ def cleanfit(self):
pos = np.array([p["position"] for p in self.model])
left_idx = pos.searchsorted(self.r_cluster[0])
right_idx = pos.searchsorted(self.r_cluster[-1])
outside_idx = range(0, left_idx)
outside_idx = list(range(0, left_idx))
outside_idx.extend(range(right_idx, len(self.model)))
# inside_idx = range(left_idx, right_idx)

Expand Down
4 changes: 2 additions & 2 deletions src/diffpy/srmise/modelevaluators/aic.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ def evaluate(self, fit, count_fixed=False, kshift=0):
if self.chisq is None:
self.chisq = self.chi_squared(fit.value(), fit.y_cluster, fit.error_cluster)

self.stat = self.chisq + self.parpenalty(k, n)
self.stat = self.chisq + self.parpenalty(k)
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is needed, otherwise, it would have a unneeded positional argument, Moreover, since we are doing AIC, we don't need n here by the AIC formula.


return self.stat

Expand Down Expand Up @@ -169,7 +169,7 @@ def growth_justified(self, fit, k_prime):
logger.warning("AIC.growth_justified(): too few data to evaluate quality reliably.")
n = self.minpoints(k_actual)

penalty = self.parpenalty(k_test, n) - self.parpenalty(k_actual, n)
penalty = self.parpenalty(k_test) - self.parpenalty(k_actual)

return penalty < self.chisq

Expand Down
8 changes: 4 additions & 4 deletions src/diffpy/srmise/modelevaluators/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def __lt__(self, other):
assert self.method == other.method # Comparison between same types required
assert self.stat is not None and other.stat is not None # The statistic must already be calculated

if self.higher_is_better is not None:
if self.higher_is_better:
return self.stat < other.stat
else:
return other.stat < self.stat
Expand All @@ -87,7 +87,7 @@ def __le__(self, other):
assert self.method == other.method # Comparison between same types required
assert self.stat is not None and other.stat is not None # The statistic must already be calculated

if self.higher_is_better is not None:
if self.higher_is_better:
return self.stat <= other.stat
else:
return other.stat <= self.stat
Expand All @@ -114,7 +114,7 @@ def __gt__(self, other):
assert self.method == other.method # Comparison between same types required
assert self.stat is not None and other.stat is not None # The statistic must already be calculated

if self.higher_is_better is not None:
if self.higher_is_better:
return self.stat > other.stat
else:
return other.stat > self.stat
Expand All @@ -125,7 +125,7 @@ def __ge__(self, other):
assert self.method == other.method # Comparison between same types required
assert self.stat is not None and other.stat is not None # The statistic must already be calculated

if self.higher_is_better is not None:
if self.higher_is_better:
return self.stat >= other.stat
else:
return other.stat >= self.stat
Expand Down
5 changes: 3 additions & 2 deletions src/diffpy/srmise/modelparts.py
Original file line number Diff line number Diff line change
Expand Up @@ -430,8 +430,9 @@ def __getitem__(self, index):
if isinstance(index, tuple) and len(index) == 2:
start, end = index
return self.__class__(super().__getitem__(slice(start, end)))
else:
return super().__getitem__(index)
if isinstance(index, slice):
return self.__class__(super().__getitem__(index))
return super().__getitem__(index)

def transform(self, in_format="internal", out_format="internal"):
"""Transforms format of parameters in this modelpart.
Expand Down
10 changes: 5 additions & 5 deletions src/diffpy/srmise/pdfpeakextraction.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ def defaultvars(self, *args):

# Enable "dg" as alias for "effective_dy"
if "dg" in args and "effective_dy" not in args:
nargs.add("effective_dy")
nargs.append("effective_dy")
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Now, we have nargs as a list, so we need append method here


# Set other defaults
PeakExtraction.defaultvars(self, *nargs)
Expand Down Expand Up @@ -888,9 +888,9 @@ def writepwastr(self, comments):
# Generate parameter labels from the baseline function's parameterdict
blf = self.extracted.baseline.owner()
if blf.npars > 0:
parlbl = blf.parameterdict.keys()
paridx = np.array(blf.parameterdict.values()).argsort()
lines.append("# " + " ".join([str(parlbl[i]) for i in paridx]))
parlbl = list(blf.parameterdict.keys())
paridx = np.array(list(blf.parameterdict.values())).argsort()
lines.append("# " + " ".join(str(parlbl[i]) for i in paridx))
blpars = " ".join([str(p) for p in self.extracted.baseline.pars])
else:
blpars = "(no parameters)"
Expand Down Expand Up @@ -1000,7 +1000,7 @@ def find_qmax(r, y, showgraphs=False):
new_y = resample(r, y, new_r)
new_dr = (new_r[-1] - r[0]) / (len(new_r) - 1)

yfft = np.imag(np.fft.fft(new_y))[: len(new_y) / 2]
yfft = np.imag(np.fft.fft(new_y))[: len(new_y) // 2]
Copy link
Copy Markdown
Contributor Author

@stevenhua0320 stevenhua0320 Apr 9, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In py2 it doesn't matter but in py3, since the slicing number must be an integer, so it must be // to get an integer value.


d_ratio = stdratio(yfft)

Expand Down
4 changes: 2 additions & 2 deletions src/diffpy/srmise/peakextraction.py
Original file line number Diff line number Diff line change
Expand Up @@ -969,7 +969,7 @@ def extract_single(self, recursion_depth=1):
# near_peaks: array containing the indices of two nearest peaks on either side of border_x
# other_peaks: all the other peaks in full_cluster
# left_data, right_data: indices defining the extent of the "interpeak range" for x, etc.
near_peaks = np.array([], dtype=np.int)
near_peaks = np.array([], dtype=np.int64)

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

# interpeak range goes from peak to peak of next nearest peaks, although their contributions
# to the data are still removed.
Expand Down
4 changes: 2 additions & 2 deletions src/diffpy/srmise/peaks/gaussian.py
Original file line number Diff line number Diff line change
Expand Up @@ -464,12 +464,12 @@ def max(self, pars):

guesspars = [[2.7, 0.15, 5], [3.7, 0.3, 5]]
guess_peaks = Peaks([pf.actualize(p, "pwa") for p in guesspars])
cluster = ModelCluster(guess_peaks, r, y, err, None, AICc, [pf])
cluster = ModelCluster(guess_peaks, None, r, y, err, None, AICc, [pf])

qual1 = cluster.quality()
print(qual1.stat)
cluster.fit()
yfit = cluster.calc()
yfit = cluster.value()
qual2 = cluster.quality()
print(qual2.stat)

Expand Down
4 changes: 2 additions & 2 deletions src/diffpy/srmise/peaks/gaussianoverr.py
Original file line number Diff line number Diff line change
Expand Up @@ -534,12 +534,12 @@ def max(self, pars):

guesspars = [[2.7, 0.15, 5], [3.7, 0.3, 5]]
guess_peaks = Peaks([pf.actualize(p, "pwa") for p in guesspars])
cluster = ModelCluster(guess_peaks, r, y, err, None, AICc, [pf])
cluster = ModelCluster(guess_peaks, None, r, y, err, None, AICc, [pf])

qual1 = cluster.quality()
print(qual1.stat)
cluster.fit()
yfit = cluster.calc()
yfit = cluster.value()
qual2 = cluster.quality()
print(qual2.stat)

Expand Down
6 changes: 3 additions & 3 deletions src/diffpy/srmise/peaks/terminationripples.py
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,7 @@ def value(self, peak, r, rng=None):
# issues is difficult to determine without detailed knowledge
# of the underlying function.
dr = (r[-1] - r[0]) / (len(r) - 1)
segments = np.ceil(dr / dr_super)
segments = int(np.ceil(dr / dr_super))
dr_segmented = dr / segments

rpart = r[rng]
Expand Down Expand Up @@ -416,12 +416,12 @@ def extend_grid(self, r, dr):

guesspars = [[2.7, 0.15, 5], [3.7, 0.3, 5]]
guess_peaks = Peaks([pf2.actualize(p, "pwa") for p in guesspars])
cluster = ModelCluster(guess_peaks, r, y_ripple, err, None, AICc, [pf2])
cluster = ModelCluster(guess_peaks, None, r, y_ripple, err, None, AICc, [pf2])

qual1 = cluster.quality()
print(qual1.stat)
cluster.fit()
yfit = cluster.calc()
yfit = cluster.value()
qual2 = cluster.quality()
print(qual2.stat)

Expand Down
Loading