Files
2026-11-06 14:45:09 +08:00

404 lines
13 KiB
C++

#include "PeakFinder.h"
#include <QDebug>
#include <algorithm>
#include <functional>
PeakFinder::PeakDetectionResult PeakFinder::DetectPeaks(const QVector<float>& wavelengthsNm,
const QVector<float>& intensities, const QVector<ElementTarget>& targets, const Options& options)
{
PeakDetectionResult result;
if (wavelengthsNm.isEmpty() || intensities.isEmpty() ||
wavelengthsNm.size() != intensities.size())
{
result.warnings.append("光谱数据为空或长度不匹配");
return result;
}
// Baseline correction (simple rolling min + smoothing)
auto corrected = baselineCorrect(intensities, std::max(11, options.SmoothingWindow * 3));
// Precompute second derivative for peak finding
auto secondDeriv = secondDerivative(corrected);
// Build quick index for wavelength -> index via binary search
int n = wavelengthsNm.size();
if (targets.isEmpty()) {
// If no targets provided, detect general peaks across spectrum
auto genericPeaks = findLocalMaxima(wavelengthsNm, corrected, secondDeriv,
QPair<int, int>(-1, -1), options);
result.peaks = genericPeaks;
return result;
}
for (const auto& t : targets) {
for (auto tw : t.characteristicWavelengthsNm) {
double wmin = tw - options.ToleranceNm;
double wmax = tw + options.ToleranceNm;
int i0 = lowerBound(wavelengthsNm, static_cast<float>(wmin));
int i1 = upperBound(wavelengthsNm, static_cast<float>(wmax));
i0 = std::max(0, i0);
i1 = std::min(n - 1, i1);
if (i1 <= i0) {
result.warnings.append(QString("[%1] %2nm 未在容差范围内找到数据窗口")
.arg(t.name).arg(tw, 0, 'f', 3));
continue;
}
auto peaks = findLocalMaxima(wavelengthsNm, corrected, secondDeriv,
QPair<int, int>(i0, i1), options);
if (peaks.isEmpty()) {
result.warnings.append(QString("[%1] 未检测到 %2nm 特征峰")
.arg(t.name).arg(tw, 0, 'f', 3));
} else {
for (auto& p : peaks) {
p.elementName = t.name;
p.targetWavelengthNm = tw;
p.matched = std::abs(p.wavelengthNm - tw) <= options.ToleranceNm;
}
result.peaks.append(peaks);
}
}
}
return result;
}
QList<PeakFinder::PeakInfo> PeakFinder::findLocalMaxima(const QVector<float>& w,
const QVector<float>& y,
const QVector<float>& y2,
QPair<int, int> window,
const Options& options)
{
QList<PeakInfo> peaks;
int start = (window.first >= 0) ? window.first : 1;
int end = (window.second >= 0) ? window.second : (y.size() - 2);
// Simple local maxima detection and refinement
for (int i = start; i <= end; i++) {
float ym1 = y[i - 1];
float yi = y[i];
float yp1 = y[i + 1];
if (yi > ym1 && yi >= yp1) { // local max
// Robust prominence using local valley scan on both sides
float leftValley = scanLocalValleyLeft(y, i);
float rightValley = scanLocalValleyRight(y, i);
float localBase = std::max(leftValley, rightValley);
float prominence = yi - localBase;
if (options.MinProminence > 0 && prominence < options.MinProminence)
continue;
// Enforce negative curvature if enabled
if (options.UseSecondDerivative) {
float curv = (i >= 1 && i < y2.size() - 1) ? -y2[i] : 0.0f;
if (curv < static_cast<float>(options.MinCurvature))
continue;
}
// Quadratic interpolation for sub-sample peak position
double denom = (ym1 - 2 * yi + yp1);
double delta = (std::abs(denom) < 1e-9) ? 0 : 0.5 * (ym1 - yp1) / denom;
int iPeak = i;
double xPeakNm = interpolateX(w, iPeak, delta);
double yPeak = interpolateY(y, iPeak, delta);
// Estimate FWHM by scanning HalfMaxFraction crossings
double half = yPeak * options.HalfMaxFraction;
double wlLeft = scanHalfWidthLeft(w, y, iPeak, half);
double wlRight = scanHalfWidthRight(w, y, iPeak, half);
double fwhm = (wlRight > wlLeft && wlLeft > 0) ? (wlRight - wlLeft) : 0;
// Width checks in pixels and skew ratio
int leftPx = countLeftPixelsAbove(y, iPeak, half);
int rightPx = countRightPixelsAbove(y, iPeak, half);
int widthPx = leftPx + rightPx;
if (widthPx < options.MinWidthPixels)
continue; // reject narrow noise spikes
double skewRatio = (rightPx > 0 && leftPx > 0) ?
(std::max(rightPx, leftPx) / static_cast<double>(std::max(1, std::min(rightPx, leftPx)))) :
options.MaxSkewRatio;
if (skewRatio > options.MaxSkewRatio)
continue; // highly skewed slopes likely false
// Area estimate: trapezoidal around peak until it drops below 10% of peak
double area = integrateAroundPeak(w, y, iPeak, yPeak * 0.1);
PeakInfo peak;
peak.wavelengthNm = xPeakNm;
peak.intensity = yPeak;
peak.fwhmNm = fwhm;
peak.area = area;
peak.matched = false;
peaks.append(peak);
}
}
return peaks;
}
double PeakFinder::interpolateX(const QVector<float>& w, int i, double delta)
{
// linear interpolation in wavelength grid around i + delta (delta in [-0.5,0.5])
int i0 = std::max(0, std::min(w.size() - 2, i));
double x0 = w[i0];
double x1 = w[i0 + 1];
return x0 + (x1 - x0) * delta;
}
double PeakFinder::interpolateY(const QVector<float>& y, int i, double delta)
{
// quadratic interpolation
double ym1 = y[i - 1];
double yi = y[i];
double yp1 = y[i + 1];
return yi - 0.25 * (ym1 - yp1) * delta; // approximation
}
double PeakFinder::scanHalfWidthLeft(const QVector<float>& w, const QVector<float>& y,
int iPeak, double half)
{
double crossing = -1;
for (int i = iPeak; i > 0; i--) {
if (y[i] < half) {
// linear interpolate between i and i+1
double t = (half - y[i]) / (y[i + 1] - y[i]);
crossing = w[i] + (w[i + 1] - w[i]) * t;
break;
}
}
return crossing;
}
double PeakFinder::scanHalfWidthRight(const QVector<float>& w, const QVector<float>& y,
int iPeak, double half)
{
double crossing = -1;
for (int i = iPeak; i < y.size() - 1; i++) {
if (y[i] < half) {
double t = (half - y[i - 1]) / (y[i] - y[i - 1]);
crossing = w[i - 1] + (w[i] - w[i - 1]) * t;
break;
}
}
return crossing;
}
float PeakFinder::scanLocalValleyLeft(const QVector<float>& y, int iPeak)
{
float valley = y[iPeak];
float last = y[iPeak];
for (int i = iPeak - 1; i >= 0; i--) {
float yi = y[i];
valley = std::min(valley, yi);
// stop when trend reverses (start rising again)
if (yi > last) break;
last = yi;
}
return valley;
}
float PeakFinder::scanLocalValleyRight(const QVector<float>& y, int iPeak)
{
float valley = y[iPeak];
float last = y[iPeak];
for (int i = iPeak + 1; i < y.size(); i++) {
float yi = y[i];
valley = std::min(valley, yi);
if (yi > last) break; // trend reverses
last = yi;
}
return valley;
}
int PeakFinder::countLeftPixelsAbove(const QVector<float>& y, int iPeak, double thr)
{
int c = 0;
for (int i = iPeak; i >= 0 && y[i] >= thr; i--) c++;
return std::max(0, c - 1);
}
int PeakFinder::countRightPixelsAbove(const QVector<float>& y, int iPeak, double thr)
{
int c = 0;
for (int i = iPeak; i < y.size() && y[i] >= thr; i++) c++;
return std::max(0, c - 1);
}
double PeakFinder::integrateAroundPeak(const QVector<float>& w, const QVector<float>& y,
int iPeak, double threshold)
{
int i0 = iPeak, i1 = iPeak;
while (i0 > 0 && y[i0] > threshold) i0--;
while (i1 < y.size() - 1 && y[i1] > threshold) i1++;
double area = 0;
for (int i = std::max(0, i0); i < std::min(y.size() - 1, i1); i++) {
double dx = w[i + 1] - w[i];
area += 0.5 * (y[i] + y[i + 1]) * dx;
}
return area;
}
QVector<float> PeakFinder::baselineCorrect(const QVector<float>& y, int window)
{
// rolling minimum followed by moving average smoothing
int n = y.size();
QVector<float> baseline(n);
int hw = std::max(1, window / 2);
for (int i = 0; i < n; i++) {
int i0 = std::max(0, i - hw);
int i1 = std::min(n - 1, i + hw);
float m = std::numeric_limits<float>::max();
for (int j = i0; j <= i1; j++)
m = std::min(m, y[j]);
baseline[i] = m;
}
QVector<float> corrected(n);
for (int i = 0; i < n; i++)
corrected[i] = std::max(0.0f, y[i] - baseline[i]);
if (window > 1) {
corrected = movingAverage(corrected, std::max(3, window / 2));
}
return corrected;
}
QVector<float> PeakFinder::movingAverage(const QVector<float>& y, int w)
{
int n = y.size();
QVector<float> outy(n);
int hw = std::max(1, w / 2);
for (int i = 0; i < n; i++) {
int i0 = std::max(0, i - hw);
int i1 = std::min(n - 1, i + hw);
double sum = 0;
int cnt = 0;
for (int j = i0; j <= i1; j++) {
sum += y[j];
cnt++;
}
outy[i] = static_cast<float>(sum / std::max(1, cnt));
}
return outy;
}
QVector<float> PeakFinder::secondDerivative(const QVector<float>& y)
{
int n = y.size();
QVector<float> y2(n);
if (n < 3) return y2;
y2[0] = 0;
y2[n - 1] = 0;
for (int i = 1; i < n - 1; i++)
y2[i] = y[i - 1] - 2 * y[i] + y[i + 1];
return y2;
}
int PeakFinder::lowerBound(const QVector<float>& arr, float value)
{
int l = 0, r = arr.size();
while (l < r) {
int m = (l + r) / 2;
if (arr[m] < value)
l = m + 1;
else
r = m;
}
return l;
}
int PeakFinder::upperBound(const QVector<float>& arr, float value)
{
int l = 0, r = arr.size();
while (l < r) {
int m = (l + r) / 2;
if (arr[m] <= value)
l = m + 1;
else
r = m;
}
return l;
}
double PeakFinder::median(QVector<double> values)
{
if (values.isEmpty())
return std::numeric_limits<double>::quiet_NaN();
std::sort(values.begin(), values.end());
int n = values.size();
if (n % 2 == 1)
return values[n / 2];
return 0.5 * (values[n / 2 - 1] + values[n / 2]);
}
double PeakFinder::computeSNR(const QVector<double>& y, int peakStart, int peakEnd,
int bgStart, int bgEnd, double epsilon)
{
if (y.isEmpty())
throw std::invalid_argument("光谱数组为空");
int n = y.size();
if (peakStart < 0 || peakEnd > n || peakStart >= peakEnd)
throw std::out_of_range("峰区间索引不合法");
if (bgStart < 0 || bgEnd > n || bgStart >= bgEnd)
throw std::out_of_range("背景区间索引不合法");
int peakCount = peakEnd - peakStart;
int bgCount = bgEnd - bgStart;
if (peakCount < 1)
throw std::invalid_argument("峰区间长度不足");
if (bgCount < 2)
throw std::invalid_argument("背景区间长度不足");
// Filter valid values
QVector<double> peakValues, bgValues;
for (int i = peakStart; i < peakEnd; i++) {
if (!std::isnan(y[i]) && !std::isinf(y[i]))
peakValues.append(y[i]);
}
for (int i = bgStart; i < bgEnd; i++) {
if (!std::isnan(y[i]) && !std::isinf(y[i]))
bgValues.append(y[i]);
}
if (peakValues.isEmpty() || bgValues.size() < 2)
return std::numeric_limits<double>::quiet_NaN();
double signal = *std::max_element(peakValues.begin(), peakValues.end());
double bgMean = std::accumulate(bgValues.begin(), bgValues.end(), 0.0) / bgValues.size();
double medianVal = median(bgValues);
double bgVar = 0;
for (auto v : bgValues)
bgVar += std::pow(v - medianVal, 2);
bgVar /= bgValues.size();
double bgStd = std::sqrt(std::max(0.0, bgVar));
// Debug output
qDebug() << "signal=" << signal << ", bgMean=" << bgMean << ", bgStd=" << bgStd;
double denom = std::max(bgStd, epsilon);
return (signal - bgMean) / denom;
}