EnergySpectrumAnalyer/src/EnergyCountPeakFitView/EnergyCountPeakFitView.cpp

608 lines
23 KiB
C++
Raw Normal View History

#define NOMINMAX
//#include <locale>
#include <vector>
#include <algorithm>
#include "EnergyCountPeakFitView.h"
#include "CustomQwtPlot.h"
#include "csv.h"
#include <GlobalDefine.h>
#include <QHBoxLayout>
#include <QMenu>
#include <QwtLegend>
#include <QwtPlotCanvas>
#include <QwtPlotCurve>
#include <QwtPlotMarker>
#include <QwtScaleMap>
#include <QwtText>
#include <QDialog>
#include <QPushButton>
#include <QCheckBox>
#include <QwtScaleDiv>
#include <QFileInfo>
2026-04-15 18:17:16 +08:00
#include "PlotRectItem.h"
#include <QInputDialog>
#include <QDebug>
EnergyCountPeakFitView::EnergyCountPeakFitView(QWidget *parent)
: MeasureAnalysisView { parent }
{
this->setViewType(PlotFrame);
QHBoxLayout* layout = new QHBoxLayout(this);
this->_plot = new CustomQwtPlot(this);
layout->addWidget(this->_plot);
setupPlot();
this->_menu = new QMenu(this);
setupMenu();
}
EnergyCountPeakFitView::~EnergyCountPeakFitView()
{
LOG_DEBUG(QStringLiteral(u"%1析构.").arg(this->GetViewName()));
2026-04-15 18:17:16 +08:00
delete _rubberBand;
clearAllSelectionRects();
clearFitCurves();
}
void EnergyCountPeakFitView::InitViewWorkspace(const QString &project_name)
{
Q_UNUSED(project_name);
}
void EnergyCountPeakFitView::SetAnalyzeDataFilename(const QMap<QString, QVariant> &data_files_set)
{
if ( !data_files_set.isEmpty() ) {
const QString& data_name = data_files_set.firstKey();
const QString& data_filename = data_files_set.first().toString();
if (QFileInfo(data_filename).exists()) {
loadDataFromFile(data_name, data_filename);
}
}
}
void EnergyCountPeakFitView::setupPlot()
{
_plot->setCanvasBackground(Qt::white);
QwtPlotCanvas* canvas = qobject_cast<QwtPlotCanvas*>(_plot->canvas());
canvas->setFrameStyle(QFrame::NoFrame);
QFont font = this->font();
font.setBold(false);
QwtText energy_label = QStringLiteral(u"能量(KeV)");
energy_label.setFont(font);
QwtText count_label = QStringLiteral(u"计数");
count_label.setFont(font);
_plot->setAxisTitle(QwtPlot::xBottom, energy_label);
_plot->setAxisTitle(QwtPlot::yLeft, count_label);
// set axis auto scale
_plot->setAxisAutoScale(QwtPlot::xBottom, true);
_plot->setAxisAutoScale(QwtPlot::yLeft, true);
_plot->enableAxis(QwtPlot::xBottom);
_plot->enableAxis(QwtPlot::yLeft);
// 设置QWT图例
// QwtLegend* legend = new QwtLegend();
// legend->setDefaultItemMode(QwtLegendData::ReadOnly);
// _plot->insertLegend(legend, QwtPlot::RightLegend);
_plot->SetAxisDragScale(QwtPlot::xBottom, true);
2026-04-15 18:17:16 +08:00
_data_selector = new CustomQwtPlotXaxisSelector(_plot->canvas());
_data_selector->setEnabled(false);
2026-04-15 18:17:16 +08:00
// 启用鼠标追踪,并安装事件过滤器
_plot->canvas()->setMouseTracking(true);
_plot->canvas()->installEventFilter(this);
}
void EnergyCountPeakFitView::setupMenu()
{
this->setContextMenuPolicy(Qt::CustomContextMenu);
connect(this, &EnergyCountPeakFitView::customContextMenuRequested, [this](const QPoint& pos) {
this->_menu->exec(this->mapToGlobal(pos));
});
QAction* action_plot_reset = this->_menu->addAction(QStringLiteral(u"还原"));
action_plot_reset->setObjectName("plot_reset");
connect(action_plot_reset, &QAction::triggered, [this]() {
this->_plot->ResetPlot();
});
this->_menu->addSeparator();
QAction* action_set_curve_show = this->_menu->addAction(QStringLiteral(u"选择曲线"));
action_set_curve_show->setObjectName("curve_show_setting");
connect(action_set_curve_show, &QAction::triggered, this, &EnergyCountPeakFitView::onActionCurveShowSetting);
QAction* action_plot_config = this->_menu->addAction(QStringLiteral(u"图表配置"));
action_plot_config->setObjectName("plot_config");
connect(action_plot_config, &QAction::triggered, this, &EnergyCountPeakFitView::onActionPlotConfigure);
2026-04-15 18:17:16 +08:00
this->_menu->addSeparator();
QAction* action_clear_rect = this->_menu->addAction(QStringLiteral(u"清除框选标记"));
connect(action_clear_rect, &QAction::triggered, this, &EnergyCountPeakFitView::clearAllSelectionRects);
this->_menu->addSeparator();
QAction* action_select_algorithm = this->_menu->addAction(QStringLiteral(u"选择拟合算法"));
QAction* action_clear_fit = this->_menu->addAction(QStringLiteral(u"清除拟合曲线"));
connect(action_clear_fit, &QAction::triggered, this, &EnergyCountPeakFitView::clearFitCurves);
2026-04-15 18:17:16 +08:00
QAction* action_hint = this->_menu->addAction(QStringLiteral(u"框选提示:按住 Ctrl 键并拖动左键"));
action_hint->setEnabled(false);
}
void EnergyCountPeakFitView::loadDataFromFile(const QString &data_name, const QString &filename)
{
std::string address_str = QString(QStringLiteral(u"能量(KeV)")).toStdString();
std::string count_str = QString(QStringLiteral(u"计数")).toStdString();
io::CSVReader<
2,
io::trim_chars<' ', '\t'>,
io::double_quote_escape<',', '"'>,
io::throw_on_overflow,
io::empty_line_comment>
reader(QStrToSysPath(filename));
reader.read_header(io::ignore_extra_column, address_str, count_str);
double energy;
unsigned long long energy_count;
QVector<double> x, y;
while (reader.read_row(energy, energy_count)) {
x.push_back(energy);
y.push_back(energy_count);
}
// 绘制曲线
QwtPlotCurve* curve = new QwtPlotCurve(data_name);
curve->setSamples(x, y);
_plot->AddCurve(curve);
}
void EnergyCountPeakFitView::onActionCurveShowSetting()
{
if (!_curve_show_setting_dlg) {
_curve_show_setting_dlg = new QDialog(this, Qt::Dialog | Qt::WindowCloseButtonHint);
_curve_show_setting_dlg->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
_curve_show_setting_dlg->setSizeGripEnabled(false);
_curve_show_setting_dlg->setWindowTitle(QString(QStringLiteral(u"选择%1曲线显示").arg(this->_plot->title().text())));
_curve_show_setting_dlg->setWindowModality(Qt::WindowModal);
_curve_show_setting_dlg->setModal(false);
QVBoxLayout* layout = new QVBoxLayout(_curve_show_setting_dlg);
QStringList curve_name_list;
for (QwtPlotCurve* curve : this->_plot->GetCurveList()) {
curve_name_list.append(curve->title().text());
}
// 自动计算多列排布
int num_columns = std::sqrt(this->_plot->GetCurveList().size());
if (num_columns == 0)
num_columns = 1;
QVBoxLayout* checkbox_layout = new QVBoxLayout();
QHBoxLayout* checkbox_column_layout = new QHBoxLayout();
QMap<QwtPlotCurve*, QCheckBox*> curve_checkbox_map;
auto addCurveToLayout = [&](const QString& curve_name){
QwtPlotCurve* curve = this->_plot->GetCurve(curve_name);
QCheckBox* check_box = new QCheckBox(curve->title().text());
check_box->setChecked(curve->isVisible());
checkbox_column_layout->addWidget(check_box);
connect(check_box, &QCheckBox::stateChanged, [curve](int state) {
curve->setVisible(state == Qt::Checked);
curve->plot()->replot();
});
curve_checkbox_map[curve] = check_box;
if (checkbox_column_layout->count() >= num_columns) {
checkbox_layout->addLayout(checkbox_column_layout);
checkbox_column_layout = new QHBoxLayout();
}
};
for (const QString& ch_name : curve_name_list) {
addCurveToLayout(ch_name);
}
if (checkbox_column_layout->count() < num_columns) {
checkbox_column_layout->addStretch();
}
checkbox_layout->addLayout(checkbox_column_layout);
// 全选和反选
auto curveCheckboxUpdate = [this, curve_checkbox_map]() {
for (QwtPlotCurve* curve : this->_plot->GetCurveList()) {
curve_checkbox_map[curve]->setChecked(curve->isVisible());
}
};
QHBoxLayout* button_layout = new QHBoxLayout();
QPushButton* btn_all_select = new QPushButton(QString(QStringLiteral(u"全选")));
connect(btn_all_select, &QPushButton::clicked, [this, curveCheckboxUpdate]() {
for (QwtPlotCurve* curve : this->_plot->GetCurveList()) {
curve->setVisible(true);
}
curveCheckboxUpdate();
this->_plot->replot();
});
button_layout->addWidget(btn_all_select);
QPushButton* btn_reserve_select = new QPushButton(QString(QStringLiteral(u"反选")));
connect(btn_reserve_select, &QPushButton::clicked, [this, curveCheckboxUpdate]() {
for (QwtPlotCurve* curve : this->_plot->GetCurveList()) {
curve->setVisible(!curve->isVisible());
}
curveCheckboxUpdate();
this->_plot->replot();
});
button_layout->addWidget(btn_reserve_select);
layout->addLayout(button_layout);
layout->addLayout(checkbox_layout);
}
_curve_show_setting_dlg->show();
}
void EnergyCountPeakFitView::onActionPlotConfigure()
{
2026-04-15 18:17:16 +08:00
}
void EnergyCountPeakFitView::clearAllSelectionRects()
{
for (PlotRectItem* item : _selectionRectItems) {
if (item) {
item->detach();
delete item;
}
}
_selectionRectItems.clear();
_plot->replot();
}
bool EnergyCountPeakFitView::eventFilter(QObject* watched, QEvent* event)
{
if (watched == _plot->canvas()) {
QMouseEvent* me = static_cast<QMouseEvent*>(event);
// 按下 Ctrl+左键 开始框选
if (event->type() == QEvent::MouseButtonPress &&
me->button() == Qt::LeftButton &&
(me->modifiers() & Qt::ControlModifier)) {
startSelection(me->pos());
2026-04-15 18:17:16 +08:00
return true;
}
// 移动时更新橡皮筋
else if (event->type() == QEvent::MouseMove && _isSelecting) {
updateSelection(me->pos());
return true;
}
// 释放左键完成框选
else if (event->type() == QEvent::MouseButtonRelease &&
me->button() == Qt::LeftButton && _isSelecting) {
finishSelection();
clearAllSelectionRects();
2026-04-15 18:17:16 +08:00
return true;
}
}
return MeasureAnalysisView::eventFilter(watched, event);
}
void EnergyCountPeakFitView::startSelection(const QPoint& pos)
{
_isSelecting = true;
_selectionStart = pos;
2026-04-15 18:17:16 +08:00
if (!_rubberBand) {
_rubberBand = new QRubberBand(QRubberBand::Rectangle, _plot->canvas());
}
int canvasHeight = _plot->canvas()->height();
// 初始矩形宽度为0高度为画布全高
_rubberBand->setGeometry(QRect(_selectionStart.x(), 0, 0, canvasHeight));
_rubberBand->show();
2026-04-15 18:17:16 +08:00
}
void EnergyCountPeakFitView::updateSelection(const QPoint& pos)
{
if (!_rubberBand) return;
int canvasHeight = _plot->canvas()->height();
int x1 = _selectionStart.x();
int x2 = pos.x();
int left = qMin(x1, x2);
int width = qAbs(x1 - x2);
_rubberBand->setGeometry(QRect(left, 0, width, canvasHeight));
2026-04-15 18:17:16 +08:00
}
void EnergyCountPeakFitView::finishSelection()
{
if (_rubberBand)
{
QRect finalRect = _rubberBand->geometry();
_rubberBand->hide();
if (finalRect.width() > 2) {
const QwtScaleMap xMap = _plot->canvasMap(QwtPlot::xBottom);
double xMin = xMap.invTransform(finalRect.left());
double xMax = xMap.invTransform(finalRect.right());
if (xMin > xMax) std::swap(xMin, xMax);
double yMin = _plot->axisScaleDiv(QwtPlot::yLeft).lowerBound();
double yMax = _plot->axisScaleDiv(QwtPlot::yLeft).upperBound();
QRectF plotRect(xMin, yMin, xMax - xMin, yMax - yMin);
addSelectionRect(plotRect);
// 获取曲线数据
QList<QwtPlotCurve*> curves = _plot->GetCurveList();
if (!curves.isEmpty()) {
QwtPlotCurve* originalCurve = curves.first();
QVector<double> origX, origY;
for (size_t i = 0; i < originalCurve->dataSize(); ++i) {
origX.push_back(originalCurve->sample(i).x());
origY.push_back(originalCurve->sample(i).y());
}
QVector<double> roiX, roiY;
for (int i = 0; i < origX.size(); ++i) {
if (origX[i] >= xMin && origX[i] <= xMax) {
roiX.push_back(origX[i]);
roiY.push_back(origY[i]);
}
}
if (roiX.size() >= 3) {
QStringList algorithms;
algorithms << QStringLiteral(u"光子峰拟合算法");
bool ok = false;
QString selected = QInputDialog::getItem(this,
QStringLiteral(u"选择拟合算法"),
QStringLiteral(u"请选择用于当前框选区域的峰拟合算法:"),
algorithms,
0,
false,
&ok);
if (ok && selected == QStringLiteral(u"光子峰拟合算法")) {
arma::vec armaRoiX(roiX.size()), armaRoiY(roiY.size());
for (int i = 0; i < roiX.size(); ++i) {
armaRoiX(i) = roiX[i];
armaRoiY(i) = roiY[i];
}
// 1. 自动估算默认初始参数(基于整个 ROI或取第一个峰
arma::vec defaultP0;
bool defaultValid = false;
try {
defaultP0 = EstimatePhotonPeakModelInitialParams(armaRoiX, armaRoiY);
defaultValid = true;
} catch (...) {
// 估算失败,使用硬编码默认值
}
if (!defaultValid) {
double midEnergy = (roiX.first() + roiX.last()) / 2.0;
defaultP0 = {100.0, 2.0, 50.0, 2.0, 10.0, midEnergy};
}
// 2. 弹出参数设置对话框
FitParams defaultParams;
defaultParams.A = defaultP0(0);
defaultParams.delt = defaultP0(1);
defaultParams.H = defaultP0(2);
defaultParams.W = defaultP0(3);
defaultParams.C = defaultP0(4);
defaultParams.P = defaultP0(5);
PeakFitParamsDialog paramDlg(defaultParams, this);
if (paramDlg.exec() != QDialog::Accepted)
return; // 用户取消
FitParams userParams = paramDlg.getParams();
arma::vec userP0 = {userParams.A, userParams.delt, userParams.H,
userParams.W, userParams.C, userParams.P};
// 3. 执行拟合(曲线自动添加到主图)
QList<PeakFitResult> results = performPeakFitting(roiX, roiY, &userP0);
if (results.isEmpty()) {
qDebug()<< QStringLiteral(u"拟合结果:") << QStringLiteral(u"未检测到有效峰或拟合失败。");
} else {
// QMessageBox::information(this, "拟合结果", QString("成功拟合 %1 个峰,曲线已显示在图区。").arg(results.size()));
for (const auto& r : results) {
qDebug() << QStringLiteral(u"峰中心= %1 keV, FWHM= %2, 面积= %3")
.arg(r.center).arg(r.fwhm).arg(r.area);
}
}
}
} else {
qDebug() << QStringLiteral(u"框选区域内数据点不足3个无法拟合。");
}
}
}
}
_isSelecting = false;
}
2026-04-15 18:17:16 +08:00
void EnergyCountPeakFitView::addSelectionRect(const QRectF &plotRect)
{
PlotRectItem* rectItem = new PlotRectItem("Selection");
rectItem->setAxes(QwtPlot::xBottom, QwtPlot::yLeft);
rectItem->setRect(plotRect);
rectItem->attach(_plot);
_selectionRectItems.append(rectItem);
_plot->replot();
}
QList<PeakFitResult> EnergyCountPeakFitView::performPeakFitting(const QVector<double> &x, const QVector<double> &y, const arma::vec* userP0)
{
// 清除之前的拟合曲线(每次拟合全新绘制)
// clearFitCurves();
QList<PeakFitResult> results;
if (x.size() != y.size() || x.size() < 3)
{
qDebug() << QStringLiteral(u"数据长度不足");
return results;
}
// 转换为 Armadillo 向量
arma::vec armaX(x.size()), armaY(y.size());
for (int i = 0; i < x.size(); ++i) {
armaX(i) = x[i];
armaY(i) = y[i];
}
const int step_w = 20;
if (armaY.n_elem < step_w) {
qDebug() << QStringLiteral(u"ROI 数据点太少,跳过寻峰。");
return results;
}
if (arma::all(armaY == 0)) {
qDebug() << QStringLiteral(u"ROI 计数全为零,跳过寻峰。");
return results;
}
// 构建两列矩阵:第一列为能量,第二列为计数
arma::mat spec_data(armaX.n_rows, 2);
spec_data.col(0) = armaX;
spec_data.col(1) = armaY;
FindPeaksBySvd peakFinder;
std::vector<FindPeaksBySvd::PeakInfo> peaks;
try {
peaks = peakFinder.FindPeaks(spec_data, step_w);
} catch (const std::string& s) {
qDebug() << QStringLiteral(u"FindPeaks 异常:") << s.c_str();
return results;
} catch (const std::exception& e) {
qDebug() << QStringLiteral(u"FindPeaks 异常:") << e.what();
return results;
} catch (...) {
qDebug() << QStringLiteral(u"FindPeaks 未知异常");
return results;
}
if (peaks.empty()) {
qDebug() << QStringLiteral(u"未检测到峰。");
return results;
}
const double fitRangeEnergy = 15.0;
for (const auto& pinfo : peaks) {
int idxCenter = pinfo.pos;
if (idxCenter < 0 || idxCenter >= x.size())
continue;
double centerEnergy = armaX(idxCenter);
// 提取局部数据
QVector<double> localX, localY;
for (int i = 0; i < x.size(); ++i) {
if (x[i] >= centerEnergy - fitRangeEnergy && x[i] <= centerEnergy + fitRangeEnergy) {
localX.push_back(x[i]);
localY.push_back(y[i]);
}
}
if (localX.size() < 5) {
qDebug() << QStringLiteral(u"局部数据点不足5跳过峰 at") << centerEnergy;
continue;
}
arma::vec xLocal(localX.size()), yLocal(localY.size());
for (int i = 0; i < localX.size(); ++i) {
xLocal(i) = localX[i];
yLocal(i) = localY[i];
}
2026-04-15 18:17:16 +08:00
arma::vec p0;
if (userP0 && userP0->n_elem == 6) {
p0 = *userP0; // 使用用户提供的初值
} else {
try {
p0 = EstimatePhotonPeakModelInitialParams(xLocal, yLocal);
} catch (...) {
qDebug() << QStringLiteral(u"初始参数估算失败,跳过峰 at") << centerEnergy;
continue;
2026-04-15 18:17:16 +08:00
}
}
arma::vec p_fit;
try {
p_fit = NolinearLeastSquaresCurveFit::Lsqcurvefit(PhotonPeakModel, xLocal, yLocal, p0);
} catch (const std::exception& e) {
qDebug() << QStringLiteral(u"拟合失败:") << e.what();
continue;
}
double sigma = p_fit(1);
double fwhm = sigma * 2.355;
AdaptiveSimpsonIntegrate::FitFunction fitFunc;
fitFunc.A = p_fit(0);
fitFunc.delt= p_fit(1);
fitFunc.H = p_fit(2);
fitFunc.W = p_fit(3);
fitFunc.C = p_fit(4);
fitFunc.P = p_fit(5);
double lower = fitFunc.P - 3.0 * fitFunc.delt;
double upper = fitFunc.P + 3.0 * fitFunc.delt;
double area = AdaptiveSimpsonIntegrate::integrate(fitFunc, lower, upper);
PeakFitResult result;
result.center = p_fit(5);
result.amplitude = p_fit(0);
result.sigma = p_fit(1);
result.fwhm = fwhm;
result.area = area;
result.baseline = p_fit(4);
result.sigmoidH = p_fit(2);
result.sigmoidW = p_fit(3);
// result.localX = localX; // 保存局部数据,备用
// result.localY = localY;
// 绘制拟合曲线到主图
double xMinPlot = result.center - 3 * result.sigma;
double xMaxPlot = result.center + 3 * result.sigma;
xMinPlot = qMax(xMinPlot, localX.first());
xMaxPlot = qMin(xMaxPlot, localX.last());
QString curveName = QStringLiteral(u"Fit_%1keV").arg(result.center, 0, 'f', 2);
QwtPlotCurve* fitCurve = createFitCurve(result, xMinPlot, xMaxPlot, curveName);
_fitCurves.append(fitCurve);
results.append(result);
2026-04-15 18:17:16 +08:00
}
_plot->replot(); // 刷新显示拟合曲线
return results;
2026-04-15 18:17:16 +08:00
}
QwtPlotCurve *EnergyCountPeakFitView::createFitCurve(const PeakFitResult &result, double xMin, double xMax, const QString &name)
2026-04-15 18:17:16 +08:00
{
const int numPoints = 200;
QVector<double> xs, ys;
double step = (xMax - xMin) / (numPoints - 1);
arma::vec p(6);
p(0) = result.amplitude;
p(1) = result.sigma;
p(2) = result.sigmoidH;
p(3) = result.sigmoidW;
p(4) = result.baseline;
p(5) = result.center;
for (int i = 0; i < numPoints; ++i) {
double x = xMin + i * step;
xs.append(x);
double y = PhotonPeakModel(x, p);
ys.append(y);
}
2026-04-15 18:17:16 +08:00
QwtPlotCurve* curve = new QwtPlotCurve(name);
curve->setSamples(xs, ys);
curve->setPen(QPen(Qt::blue, 2));
curve->attach(_plot);
return curve;
2026-04-15 18:17:16 +08:00
}
void EnergyCountPeakFitView::clearFitCurves()
2026-04-15 18:17:16 +08:00
{
for (QwtPlotCurve* curve : _fitCurves) {
curve->detach();
delete curve;
}
_fitCurves.clear();
_plot->replot();
2026-04-15 18:17:16 +08:00
}