添加项目文件。
This commit is contained in:
@@ -0,0 +1,403 @@
|
||||
#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;
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
#ifndef PEAKFINDER_H
|
||||
#define PEAKFINDER_H
|
||||
|
||||
#include <QObject>
|
||||
#include <QVector>
|
||||
#include <QString>
|
||||
#include <QList>
|
||||
#include <cmath>
|
||||
#include <algorithm>
|
||||
|
||||
class PeakFinder : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
|
||||
struct Options {
|
||||
double ToleranceNm; // 允许的波长误差 nm
|
||||
bool UseGaussianFit; // 是否使用高斯拟合
|
||||
int SmoothingWindow; // 滤波窗口大小
|
||||
double MinProminence; // 最小突起高度
|
||||
int MinWidthPixels; // 最小宽度像素
|
||||
bool UseSecondDerivative; // 是否使用二阶导数
|
||||
double MinCurvature; // 最小曲率
|
||||
double HalfMaxFraction; // 半最大高度比例
|
||||
double MaxSkewRatio; // 最大偏斜比
|
||||
|
||||
// 添加构造函数来提供默认值
|
||||
Options() :
|
||||
ToleranceNm(0.5),
|
||||
UseGaussianFit(false),
|
||||
SmoothingWindow(5),
|
||||
MinProminence(0),
|
||||
MinWidthPixels(2),
|
||||
UseSecondDerivative(true),
|
||||
MinCurvature(0),
|
||||
HalfMaxFraction(0.5),
|
||||
MaxSkewRatio(6.0)
|
||||
{}
|
||||
};
|
||||
// 元素目标
|
||||
struct ElementTarget {
|
||||
QString name;
|
||||
QVector<double> characteristicWavelengthsNm;
|
||||
};
|
||||
// 峰值信息
|
||||
struct PeakInfo {
|
||||
double wavelengthNm = 0;
|
||||
double intensity = 0;
|
||||
double fwhmNm = 0;
|
||||
double area = 0;
|
||||
QString elementName;
|
||||
double targetWavelengthNm = 0;
|
||||
bool matched = false;
|
||||
};
|
||||
// 峰值检测结果
|
||||
struct PeakDetectionResult {
|
||||
QList<PeakInfo> peaks;
|
||||
QVector<QString> warnings;
|
||||
};
|
||||
// 检测峰值
|
||||
static PeakDetectionResult DetectPeaks(
|
||||
const QVector<float>& wavelengthsNm,
|
||||
const QVector<float>& intensities,
|
||||
const QVector<ElementTarget>& targets,
|
||||
const Options& options = Options()
|
||||
);
|
||||
// 计算信噪比
|
||||
static double computeSNR(const QVector<double>& y, int peakStart, int peakEnd,
|
||||
int bgStart, int bgEnd, double epsilon = 1e-9);
|
||||
|
||||
private:
|
||||
// 辅助函数, 用于计算基线修正
|
||||
static QVector<float> baselineCorrect(const QVector<float>& y, int window);
|
||||
// 辅助函数, 用于计算移动平均
|
||||
static QVector<float> movingAverage(const QVector<float>& y, int w);
|
||||
// 辅助函数, 用于计算二阶导数
|
||||
static QVector<float> secondDerivative(const QVector<float>& y);
|
||||
// 辅助函数, 用于查找局部极大值
|
||||
static QList<PeakInfo> findLocalMaxima(const QVector<float>& w, const QVector<float>& y,
|
||||
const QVector<float>& y2, QPair<int, int> window,
|
||||
const Options& options);
|
||||
// 辅助函数, 用于插值计算峰值位置
|
||||
static double interpolateX(const QVector<float>& w, int i, double delta);
|
||||
// 辅助函数, 用于插值计算峰值高度
|
||||
static double interpolateY(const QVector<float>& y, int i, double delta);
|
||||
// 辅助函数, 用于扫描半宽度左侧
|
||||
static double scanHalfWidthLeft(const QVector<float>& w, const QVector<float>& y,
|
||||
int iPeak, double half);
|
||||
// 辅助函数, 用于扫描半宽度右侧
|
||||
static double scanHalfWidthRight(const QVector<float>& w, const QVector<float>& y,
|
||||
int iPeak, double half);
|
||||
// 辅助函数, 用于扫描局部谷值左侧
|
||||
static float scanLocalValleyLeft(const QVector<float>& y, int iPeak);
|
||||
// 辅助函数, 用于扫描局部谷值右侧
|
||||
static float scanLocalValleyRight(const QVector<float>& y, int iPeak);
|
||||
// 辅助函数, 用于计算像素数
|
||||
static int countLeftPixelsAbove(const QVector<float>& y, int iPeak, double thr);
|
||||
// 辅助函数, 用于计算像素数
|
||||
static int countRightPixelsAbove(const QVector<float>& y, int iPeak, double thr);
|
||||
// 辅助函数, 用于计算峰面积
|
||||
static double integrateAroundPeak(const QVector<float>& w, const QVector<float>& y,
|
||||
int iPeak, double threshold);
|
||||
// 辅助函数, 用于查找数组中的下界索引
|
||||
static int lowerBound(const QVector<float>& arr, float value);
|
||||
// 辅助函数, 用于查找数组中的上界索引
|
||||
static int upperBound(const QVector<float>& arr, float value);
|
||||
// 辅助函数, 用于计算数组的中位数
|
||||
static double median(QVector<double> values);
|
||||
};
|
||||
|
||||
#endif // PEAKFINDER_H
|
||||
Reference in New Issue
Block a user