From 111f4965791ff9e6a7baae40291006aaa54717e5 Mon Sep 17 00:00:00 2001 From: lvjunjie Date: Thu, 15 Oct 2026 16:33:36 +0800 Subject: [PATCH] =?UTF-8?q?feat(nmNum):=20=E5=A2=9E=E5=8A=A0=E6=95=A3?= =?UTF-8?q?=E7=82=B9=E5=9B=BE=E5=92=8C=E7=9B=B4=E6=96=B9=E5=9B=BE=E9=80=89?= =?UTF-8?q?=E9=A1=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 直方图上方新增按钮,支持查看误差与调整分箱数。 - 散点图独立弹窗,显示参数、误差和基准方块。 - 支持阈值拖动、右键重置和参数悬停提示。 --- .../nmCalculationDllPebiSolverTask.h | 3 + Include/nmNum/nmSubWnd/nmSubWndMain.h | 3 + Include/nmNum/nmSubWxs/nmWxSensitive.h | 42 ++ .../nmCalculationDllPebiSolverTask.cpp | 7 + Src/nmNum/nmSubWnd/nmSubWndMain.cpp | 82 +++- Src/nmNum/nmSubWxs/nmWxSensitive.cpp | 361 +++++++++++++++++- 6 files changed, 473 insertions(+), 25 deletions(-) diff --git a/Include/nmNum/nmCalculation/nmCalculationDllPebiSolverTask.h b/Include/nmNum/nmCalculation/nmCalculationDllPebiSolverTask.h index c583686b..cb928a0b 100644 --- a/Include/nmNum/nmCalculation/nmCalculationDllPebiSolverTask.h +++ b/Include/nmNum/nmCalculation/nmCalculationDllPebiSolverTask.h @@ -131,6 +131,9 @@ class NMCALCULATION_EXPORT nmCalculationDllPebiSolverTask : public QThread { QSharedPointer getSensitivityBatchResult() const; /** @brief 线程结束后判断全部组合是否处理完成,单组失败不影响此标记。 */ bool wasSensitivityBatchCompleted() const; + // 基准模型与采样模型共用压力误差口径,返回 -1 表示无有效误差。 + static double calculatePressureRmse(const QVector >& measured, + const QVector >& simulated); private: /** @brief 仅复制目标井求解的值快照,不登记或访问实时管理器。 */ diff --git a/Include/nmNum/nmSubWnd/nmSubWndMain.h b/Include/nmNum/nmSubWnd/nmSubWndMain.h index bcb7e686..66caf7df 100644 --- a/Include/nmNum/nmSubWnd/nmSubWndMain.h +++ b/Include/nmNum/nmSubWnd/nmSubWndMain.h @@ -171,6 +171,9 @@ class NM_SUB_WND_EXPORT nmSubWndMain : public iSubWndBaseFit { void onSensitiveShowClicked(); /** @brief 刷新主界面的误差直方图,修改分箱数时复用当前批次结果。 */ void updateSensitiveHistogramPlot(); + void onSensitiveHistogramOptions(); + void onSensitiveHistogramBinsChanged(int bins); + void onSensitiveScatter(); /** @brief 当前分析的建网提交结束后,恢复待启动或待捕获的求解流程。 */ void onPebiGridGenerationFinished(quint64 nGridInputRevision, bool bSucceeded); diff --git a/Include/nmNum/nmSubWxs/nmWxSensitive.h b/Include/nmNum/nmSubWxs/nmWxSensitive.h index ef509947..de9cb30c 100644 --- a/Include/nmNum/nmSubWxs/nmWxSensitive.h +++ b/Include/nmNum/nmSubWxs/nmWxSensitive.h @@ -24,6 +24,48 @@ class QCloseEvent; class SensitivityDistributionPlot; class SensitivityResultsModel; class iGuiPlot; +class QMenu; + +class NM_SUB_WXS_EXPORT nmWxSensitivityHistogramOptions : public iDlgBase +{ + Q_OBJECT +public: + nmWxSensitivityHistogramOptions(const QSharedPointer& results, + int bins, QWidget* parent); +signals: + void binsChanged(int bins); +private slots: + void onApply(); + void onAccept(); +private: + QSpinBox* m_bins; +}; + +class NM_SUB_WXS_EXPORT nmWxSensitivityScatter : public iDlgBase +{ + Q_OBJECT +public: + nmWxSensitivityScatter(const QSharedPointer& results, + double baseError, QWidget* parent = nullptr); +protected: + bool eventFilter(QObject* object, QEvent* event) override; +private slots: + void updateParameter(); + void updateThreshold(); + void resetThreshold(); + void adjustContextMenu(QMenu* menu); +private: + QSharedPointer m_results; + double m_baseError; + double m_defaultThreshold; + bool m_draggingThreshold; + QComboBox* m_parameter; + double m_threshold; + QLabel* m_legend; + iGuiPlot* m_plot; + QVector m_points; + QVector m_runRows; +}; // 复用原结果表格,每个 Show 窗口只控制所属图中的采样曲线。 class NM_SUB_WXS_EXPORT nmWxSensitivityShow : public iDlgBase diff --git a/Src/nmNum/nmCalculation/nmCalculationDllPebiSolverTask.cpp b/Src/nmNum/nmCalculation/nmCalculationDllPebiSolverTask.cpp index 7b63eb35..3df56e71 100644 --- a/Src/nmNum/nmCalculation/nmCalculationDllPebiSolverTask.cpp +++ b/Src/nmNum/nmCalculation/nmCalculationDllPebiSolverTask.cpp @@ -1021,6 +1021,13 @@ bool nmCalculationDllPebiSolverTask::wasSensitivityBatchCompleted() const return m_bSensitivityBatchCompleted; } +double nmCalculationDllPebiSolverTask::calculatePressureRmse( + const QVector >& measured, const QVector >& simulated) +{ + // 散点图的基准点复用批量求解的插值与 RMSE 计算,不另写误差公式。 + return calculateSensitivityPressureRmse(measured, simulated, nullptr); +} + bool nmCalculationDllPebiSolverTask::executeSensitivityBatch() { m_pSensitivityResult->m_runs.clear(); diff --git a/Src/nmNum/nmSubWnd/nmSubWndMain.cpp b/Src/nmNum/nmSubWnd/nmSubWndMain.cpp index da2f160d..67df7c75 100644 --- a/Src/nmNum/nmSubWnd/nmSubWndMain.cpp +++ b/Src/nmNum/nmSubWnd/nmSubWndMain.cpp @@ -75,7 +75,6 @@ #include #include #include -#include #include #include #include @@ -2200,12 +2199,13 @@ void nmSubWndMain::updateSensitiveHistogramPlot() QVBoxLayout* layout = new QVBoxLayout(page); layout->setContentsMargins(0, 0, 0, 0); QHBoxLayout* options = new QHBoxLayout; - options->addWidget(new QLabel(tr("Bins:"), page)); - QSpinBox* bins = new QSpinBox(page); - bins->setObjectName("nmHistogramBins"); - bins->setRange(1, 1000); - bins->setValue(20); - options->addWidget(bins); + page->setProperty("nmHistogramBins", 20); + QPushButton* scatter = new QPushButton(tr("Scatter plot"), page); + scatter->setObjectName("nmScatterButton"); + QPushButton* settings = new QPushButton(tr("Histogram options"), page); + settings->setObjectName("nmHistogramOptionsButton"); + options->addWidget(scatter); + options->addWidget(settings); QLabel* count = new QLabel(page); count->setObjectName("nmHistogramCount"); options->addWidget(count); @@ -2227,10 +2227,11 @@ void nmSubWndMain::updateSensitiveHistogramPlot() window->setObjectName("nmSensitivityHistogram"); window->setWindowTitle(tr("Sensitivity histogram plot")); window->setAttribute(Qt::WA_DeleteOnClose, false); - connect(bins, SIGNAL(valueChanged(int)), this, SLOT(updateSensitiveHistogramPlot())); + connect(scatter, SIGNAL(clicked()), this, SLOT(onSensitiveScatter())); + connect(settings, SIGNAL(clicked()), this, SLOT(onSensitiveHistogramOptions())); } - iGuiPlot* plot = window->findChild(); - const int binCount = window->findChild("nmHistogramBins")->value(); + iGuiPlot* plot = window->widget()->findChild(); + const int binCount = window->widget()->property("nmHistogramBins").toInt(); QVector errors; for(size_t i = 0; i < batch->m_runs.size(); ++i) { const nmDataSensitive::RunResult& run = batch->m_runs[i]; @@ -2324,6 +2325,67 @@ void nmSubWndMain::updateSensitiveHistogramPlot() if(created || restore) area->relayoutSubWnds(); } +void nmSubWndMain::onSensitiveHistogramOptions() +{ + // 设置窗口复用当前批次,分箱数在 Apply 或 OK 后才应用到直方图。 + iSubWndFitting* fitting = m_pResultRefreshFitting.data(); + nmDataAnalyzeManager* manager = m_pResultRefreshDataManager.data(); + if(!fitting || !fitting->m_pMdiArea || !manager || !manager->getSensitiveData()) return; + QMdiSubWindow* window = fitting->m_pMdiArea->findChild("nmSensitivityHistogram"); + const QSharedPointer batch = manager->getSensitiveData()->getResults(); + if(!window || batch.isNull()) return; + nmWxSensitivityHistogramOptions* dialog = window->findChild(); + if(!dialog) { + dialog = new nmWxSensitivityHistogramOptions(batch, window->widget()->property("nmHistogramBins").toInt(), window->widget()); + connect(dialog, SIGNAL(binsChanged(int)), this, SLOT(onSensitiveHistogramBinsChanged(int))); + connect(manager, SIGNAL(sigSensitiveResultsChanged()), dialog, SLOT(reject())); + } + dialog->show(); + dialog->raise(); + dialog->activateWindow(); +} + +void nmSubWndMain::onSensitiveHistogramBinsChanged(int bins) +{ + // 分箱设置仅影响本图,散点图继续使用未分箱的逐组误差。 + iSubWndFitting* fitting = m_pResultRefreshFitting.data(); + if(!fitting || !fitting->m_pMdiArea) return; + QMdiSubWindow* window = fitting->m_pMdiArea->findChild("nmSensitivityHistogram"); + if(!window) return; + window->widget()->setProperty("nmHistogramBins", bins); + updateSensitiveHistogramPlot(); +} + +void nmSubWndMain::onSensitiveScatter() +{ + // 与 Show 一样打开独立弹窗,重复点击时激活已有窗口。 + iSubWndFitting* fitting = m_pResultRefreshFitting.data(); + nmDataAnalyzeManager* manager = m_pResultRefreshDataManager.data(); + if(!fitting || !fitting->m_pMdiArea || !manager || !manager->getSensitiveData()) return; + const QSharedPointer batch = manager->getSensitiveData()->getResults(); + if(batch.isNull() || batch->m_calcType != nmDataSensitive::CALC_MONTE_CARLO) return; + QMdiSubWindow* window = fitting->m_pMdiArea->findChild("nmSensitivityHistogram"); + if(!window) return; + nmWxSensitivityScatter* dialog = window->findChild(); + if(!dialog) { + double baseError = -1.0; + const QSharedPointer snapshot = manager->getPebiResultSnapshot(); + for(int i = 0; !snapshot.isNull() && i < snapshot->getWellCount(); ++i) { + const nmPebiResultWellSnapshot* well = snapshot->getWellAt(i); + if(well->m_sWellCode != batch->m_sWellCode) continue; + baseError = nmCalculationDllPebiSolverTask::calculatePressureRmse( + well->m_oCurves.m_vecHistoryPressure, well->m_oCurves.m_vecResultPressure); + break; + } + dialog = new nmWxSensitivityScatter(batch, baseError, window->widget()); + // 新结果或新模型生成后关闭弹窗,避免保留旧批次的点和阈值。 + connect(manager, SIGNAL(sigSensitiveResultsChanged()), dialog, SLOT(reject())); + } + dialog->show(); + dialog->raise(); + dialog->activateWindow(); +} + void nmSubWndMain::startSolverTask() { if(!m_bSolverStartPending) { diff --git a/Src/nmNum/nmSubWxs/nmWxSensitive.cpp b/Src/nmNum/nmSubWxs/nmWxSensitive.cpp index cba9989b..4fcd3d53 100644 --- a/Src/nmNum/nmSubWxs/nmWxSensitive.cpp +++ b/Src/nmNum/nmSubWxs/nmWxSensitive.cpp @@ -32,6 +32,13 @@ #include "iGuiPlot.h" #include "ZxPlot.h" #include "ZxObjCurve.h" +#include "ZxSubAxisX.h" +#include "ZxSubAxisY.h" +#include "tCurvePlotView.h" +#include "iCurveDesc.h" +#include +#include +#include #include #include #include @@ -175,13 +182,37 @@ bool validSamplingValue(const QString& name, double& value) } } +namespace { +bool hasSensitivityError(const nmDataSensitive::RunResult& run) +{ + // 统计只使用成功且误差有效的运行,与曲线显示勾选无关。 + return run.m_bSucceeded && !run.m_bCancelled && qIsFinite(run.m_dPressureRmse) && run.m_dPressureRmse >= 0.0; +} + +QString sensitivityRunParameters(const nmDataSensitive::BatchResult& results, const nmDataSensitive::RunResult& run) +{ + // 表格和散点提示共用冻结参数的单位换算。 + QStringList descriptions; + for(int i = 0; i < results.m_variables.size() && i < run.m_vecParameters.size(); ++i) { + const nmDataSensitive::VariableSampling& variable = results.m_variables[i]; + if(!variable.m_enabled) continue; + double value = run.m_vecParameters[i]; + const QString unit = variable.m_modelValue.getUnit(); + convertSamplingValue(variable.m_varName, value, samplingBaseUnit(variable.m_varName), unit, value); + descriptions << variable.m_varName + " = " + formatSamplingValue(value, 3) + + (unit.isEmpty() ? QString() : " " + unit); + } + return descriptions.join(" + "); +} +} + // ========= 已完成批次的连续结果列表 ========= class SensitivityResultsModel : public QAbstractTableModel { public: SensitivityResultsModel(const QSharedPointer& results, - iGuiPlot* plot, QObject* parent) - : QAbstractTableModel(parent), m_results(results), m_plot(plot) {} + iGuiPlot* plot, QObject* parent, bool statistics = false) + : QAbstractTableModel(parent), m_results(results), m_plot(plot), m_statistics(statistics) {} QList runCurves(int row) const { @@ -220,6 +251,8 @@ public: { // 表格仅保留显示选择、运行编号与冻结参数。 if(orientation != Qt::Horizontal || role != Qt::DisplayRole) return QVariant(); + if(m_statistics) return (QStringList() << "#" << nmWxSensitive::tr("Realization") + << nmWxSensitive::tr("Goodness of fit [MPa]")).value(section); const QStringList titles = QStringList() << nmWxSensitive::tr("Show") << "#" << nmWxSensitive::tr("Parameters"); return titles.value(section); @@ -230,6 +263,15 @@ public: // 参数显示使用冻结配置中的单位和三位有效数字,不修改原始采样值。 if(!index.isValid() || index.row() >= rowCount()) return QVariant(); const nmDataSensitive::RunResult& run = m_results->m_runs[index.row()]; + if(m_statistics) { + if(role == Qt::ToolTipRole && !run.m_sFailureReason.isEmpty()) return run.m_sFailureReason; + if(role != Qt::DisplayRole && role != Qt::ToolTipRole) return QVariant(); + if(index.column() == 0) return QString::number(run.m_nRunIndex + 1); + if(index.column() == 1) return sensitivityRunParameters(*m_results, run); + return hasSensitivityError(run) ? QString::number(run.m_dPressureRmse, 'g', 6) + : run.m_bCancelled ? nmWxSensitive::tr("Cancelled") + : !run.m_bSucceeded ? nmWxSensitive::tr("Failed") : nmWxSensitive::tr("N/A"); + } if(role == Qt::CheckStateRole && index.column() == 0) return run.m_bSucceeded && !run.m_bCancelled && m_pendingVisibility.value(index.row(), isRunVisible(index.row())) ? Qt::Checked : Qt::Unchecked; @@ -239,17 +281,7 @@ public: if(role != Qt::DisplayRole && role != Qt::ToolTipRole) return QVariant(); if(index.column() == 1) return QString::number(run.m_nRunIndex + 1); if(index.column() != 2) return QVariant(); - QStringList descriptions; - for(int i = 0; i < m_results->m_variables.size() && i < run.m_vecParameters.size(); ++i) { - const nmDataSensitive::VariableSampling& variable = m_results->m_variables[i]; - if(!variable.m_enabled) continue; - double value = run.m_vecParameters[i]; - const QString unit = variable.m_modelValue.getUnit(); - convertSamplingValue(variable.m_varName, value, samplingBaseUnit(variable.m_varName), unit, value); - descriptions << variable.m_varName + " = " + formatSamplingValue(value, 3) - + (unit.isEmpty() ? QString() : " " + unit); - } - return descriptions.join(" + "); + return sensitivityRunParameters(*m_results, run); } Qt::ItemFlags flags(const QModelIndex& index) const override @@ -258,7 +290,7 @@ public: if(!index.isValid()) return Qt::NoItemFlags; Qt::ItemFlags result = Qt::ItemIsEnabled | Qt::ItemIsSelectable; const nmDataSensitive::RunResult& run = m_results->m_runs[index.row()]; - if(index.column() == 0 && run.m_bSucceeded && !run.m_bCancelled && !runCurves(index.row()).isEmpty()) + if(!m_statistics && index.column() == 0 && run.m_bSucceeded && !run.m_bCancelled && !runCurves(index.row()).isEmpty()) result |= Qt::ItemIsUserCheckable; return result; } @@ -266,7 +298,7 @@ public: bool setData(const QModelIndex& index, const QVariant& value, int role) override { // 勾选只记在本窗口,点击 Apply 或 OK 后才改变所属图的显示。 - if(!index.isValid() || index.column() != 0 || role != Qt::CheckStateRole) return false; + if(m_statistics || !index.isValid() || index.column() != 0 || role != Qt::CheckStateRole) return false; const nmDataSensitive::RunResult& run = m_results->m_runs[index.row()]; if(!run.m_bSucceeded || run.m_bCancelled || runCurves(index.row()).isEmpty()) return false; const bool visible = value.toInt() == Qt::Checked; @@ -308,6 +340,7 @@ private: QSharedPointer m_results; QMap m_pendingVisibility; QPointer m_plot; + bool m_statistics; }; nmWxSensitivityShow::nmWxSensitivityShow( @@ -381,6 +414,304 @@ void nmWxSensitivityShow::onHideAll() m_model->setAllVisible(false); } +nmWxSensitivityHistogramOptions::nmWxSensitivityHistogramOptions( + const QSharedPointer& results, int bins, QWidget* parent) + : iDlgBase(parent) +{ + // 复用运行表格的参数展示,普通 Monte-Carlo 的统计变量只有误差。 + setAttribute(Qt::WA_DeleteOnClose); + setObjectName("nmHistogramOptions"); + setWindowTitle(tr("Histogram options")); + resize(720, 400); + QVBoxLayout* layout = new QVBoxLayout(this); + QHBoxLayout* options = new QHBoxLayout; + options->addWidget(new QLabel(tr("Number of bins:"), this)); + m_bins = new QSpinBox(this); + m_bins->setRange(1, 1000); + m_bins->setValue(bins); + options->addWidget(m_bins); + options->addStretch(); + options->addWidget(new QLabel(tr("Variable:"), this)); + QComboBox* variable = new QComboBox(this); + variable->addItem(tr("Goodness of fit")); + options->addWidget(variable); + layout->addLayout(options); + QTableView* table = new QTableView(this); + table->setStyleSheet("QTableView { background-color: white; }"); + table->setModel(new SensitivityResultsModel(results, nullptr, table, true)); + table->setSelectionBehavior(QAbstractItemView::SelectRows); + table->setEditTriggers(QAbstractItemView::NoEditTriggers); + table->setWordWrap(false); + table->verticalHeader()->hide(); + table->horizontalHeader()->setResizeMode(0, QHeaderView::ResizeToContents); + table->horizontalHeader()->setResizeMode(1, QHeaderView::Stretch); + table->horizontalHeader()->setResizeMode(2, QHeaderView::ResizeToContents); + layout->addWidget(table); + QHBoxLayout* buttons = new QHBoxLayout; + buttons->addStretch(); + QPushButton* apply = new QPushButton(tr("Apply"), this); + QPushButton* ok = new QPushButton(tr("OK"), this); + QPushButton* cancel = new QPushButton(tr("Cancel"), this); + buttons->addWidget(apply); + buttons->addWidget(ok); + buttons->addWidget(cancel); + layout->addLayout(buttons); + connect(apply, SIGNAL(clicked()), this, SLOT(onApply())); + connect(ok, SIGNAL(clicked()), this, SLOT(onAccept())); + connect(cancel, SIGNAL(clicked()), this, SLOT(reject())); +} + +void nmWxSensitivityHistogramOptions::onApply() +{ + // 只提交分箱数,取消不会撤销已经应用的设置。 + emit binsChanged(m_bins->value()); +} + +void nmWxSensitivityHistogramOptions::onAccept() +{ + // 与 Show 表格保持相同的确认行为。 + onApply(); + accept(); +} + +nmWxSensitivityScatter::nmWxSensitivityScatter( + const QSharedPointer& results, double baseError, QWidget* parent) + : iDlgBase(parent), m_results(results), m_baseError(baseError), + m_defaultThreshold(0.0), m_draggingThreshold(false) +{ + // 散点与基准均来自同一批次快照,不读取后来编辑的模型参数。 + setObjectName("nmSensitivityScatterPlot"); + setAttribute(Qt::WA_DeleteOnClose); + setWindowTitle(tr("Scatter plot")); + resize(850, 550); + QVBoxLayout* layout = new QVBoxLayout(this); + layout->setContentsMargins(8, 8, 8, 8); + QHBoxLayout* options = new QHBoxLayout; + options->addWidget(new QLabel(tr("X Axis:"), this)); + m_parameter = new QComboBox(this); + for(int i = 0; i < results->m_variables.size(); ++i) + if(results->m_variables[i].m_enabled) m_parameter->addItem(results->m_variables[i].m_varName, i); + options->addWidget(m_parameter, 1); + options->addSpacing(20); + options->addWidget(new QLabel(tr("Y Axis:"), this)); + QComboBox* ordinate = new QComboBox(this); + ordinate->addItem(tr("Goodness of fit")); + options->addWidget(ordinate, 1); + for(size_t i = 0; i < results->m_runs.size(); ++i) + if(hasSensitivityError(results->m_runs[i])) m_defaultThreshold = qMax(m_defaultThreshold, results->m_runs[i].m_dPressureRmse); + if(qIsFinite(baseError) && baseError >= 0.0) m_defaultThreshold = baseError; + m_threshold = m_defaultThreshold; + layout->addLayout(options); + m_plot = new iGuiPlot(true, this); + m_plot->initUI(tr("Sensitivity scatter plot")); + m_plot->setDropEnabled(false); + m_plot->setAxisY(tr("Goodness of fit"), "MPa"); + m_plot->setAxisXYLog(false, 0); + m_plot->setAxisXYLog(false, 1); + m_plot->getAxisOf(2)->setVisible(false); + // 给纵轴标题与刻度留出间距。 + m_plot->getAxisOf(1)->setSpan(20.0); + m_plot->m_pPlot->setBKColor(Qt::white); + m_plot->m_pPlot->setLegendVisible(false); + layout->addWidget(m_plot); + // 两项固定图例不使用框架的分组标题,覆盖在绘图区左上角。 + m_legend = new QLabel(m_plot->m_pPlotView->viewport()); + m_legend->setText("
□" + tr("sensitivity data") + + "
■" + tr("reference") + "
"); + m_legend->setStyleSheet("QLabel { background: white; color: black; border: 1px solid #cccccc; }"); + m_legend->setAttribute(Qt::WA_TransparentForMouseEvents); + m_legend->adjustSize(); + m_plot->m_pPlotView->viewport()->installEventFilter(this); + connect(m_parameter, SIGNAL(currentIndexChanged(int)), this, SLOT(updateParameter())); + connect(m_plot->m_pPlotView, SIGNAL(sigAdjustContextMenu(QMenu*)), this, SLOT(adjustContextMenu(QMenu*))); + updateParameter(); +} + +void nmWxSensitivityScatter::updateParameter() +{ + // 切换横轴时重建参数坐标,阈值在各参数之间共用。 + m_points.clear(); + m_runRows.clear(); + if(m_parameter->currentIndex() < 0) { + m_plot->setToolTip(tr("No sampled parameters")); + return; + } + const int index = m_parameter->itemData(m_parameter->currentIndex()).toInt(); + const nmDataSensitive::VariableSampling& variable = m_results->m_variables[index]; + const QString unit = variable.m_modelValue.getUnit(); + m_plot->setAxisX(variable.m_varName, unit); + double modelValue = variable.m_modelValue.getValue().toDouble(); + const bool hasModel = convertSamplingValue(variable.m_varName, modelValue, + samplingBaseUnit(variable.m_varName), unit, modelValue) && m_baseError >= 0.0 && qIsFinite(m_baseError); + for(size_t i = 0; i < m_results->m_runs.size(); ++i) { + const nmDataSensitive::RunResult& run = m_results->m_runs[i]; + if(!hasSensitivityError(run) || index >= run.m_vecParameters.size()) continue; + double value = run.m_vecParameters[index]; + if(!convertSamplingValue(variable.m_varName, value, samplingBaseUnit(variable.m_varName), unit, value)) continue; + m_points.append(QPointF(value, run.m_dPressureRmse)); + m_runRows.append(int(i)); + } + QVector curves; + for(int i = 0; i < 4; ++i) { + iCurveDesc curve; + curve.m_sCurveName = i == 0 ? tr("sensitivity data") : i == 1 ? tr("Below threshold") + : i == 2 ? tr("reference") : tr("Threshold"); + curve.m_oCurveType = POT_CurveDiscrete; + curve.m_bLineVisible = false; + curve.m_bPointVisible = true; + curve.m_oDot = ZxDot(DTS_Square, i == 2 ? Qt::blue : Qt::black, 1.0, i != 0); + if(i < 2) for(int j = 0; j < m_points.size(); ++j) { + if(i == 1 && m_points[j].y() >= m_threshold) continue; + curve.m_vecX.append(m_points[j].x()); + curve.m_vecY.append(m_points[j].y()); + } + if(i == 2 && hasModel) { + curve.m_vecX.append(modelValue); + curve.m_vecY.append(m_baseError); + } + if(i == 3) { + curve.m_bLineVisible = true; + curve.m_bPointVisible = false; + curve.m_oPen = QPen(Qt::red, 0.35); + curve.m_vecX << 0.0 << 1.0; + curve.m_vecY << m_threshold << m_threshold; + } + curves.append(curve); + } + // 固定图层名称,参数切换不叠加上一参数的点,也不让旧阈值影响自动范围。 + for(int i = m_plot->m_pPlot->getObjCount() - 1; i >= 0; --i) + if(qobject_cast(m_plot->m_pPlot->getObjByIndex(i))) m_plot->m_pPlot->removeObjByIndex(i); + m_plot->clearUndoStack(); + m_plot->setCurveData(curves); + m_plot->runUpdate(); + m_plot->setReadOnly(true); + double left = hasModel ? modelValue : m_points.isEmpty() ? 0.0 : m_points.first().x(); + double right = left, top = hasModel ? m_baseError : 0.0; + for(int i = 0; i < m_points.size(); ++i) { + left = qMin(left, m_points[i].x()); + right = qMax(right, m_points[i].x()); + top = qMax(top, m_points[i].y()); + } + const double padding = qMax(1e-6, (right > left ? right - left : qMax(1.0, qAbs(left))) * 0.05); + left -= padding; + right += padding; + top = qMax(1e-6, qMax(top, m_threshold) * 1.1); + VecDouble ticksX, ticksY; + for(int i = 0; i <= 5; ++i) { + ticksX.append(left + i * (right - left) / 5.0); + ticksY.append(i * top / 5.0); + } + m_plot->setAxisScaleX(left, right, ticksX); + m_plot->setAxisScaleY(0.0, top, ticksY); + updateThreshold(); +} + +void nmWxSensitivityScatter::updateThreshold() +{ + // 阈值以下的点填黑,范围使用这些采样点的参数值,不包含蓝色基准点。 + if(m_parameter->currentIndex() < 0) return; + QVector accepted; + double lower = 0.0, upper = 0.0; + for(int i = 0; i < m_points.size(); ++i) if(m_points[i].y() < m_threshold) { + if(accepted.isEmpty()) lower = upper = m_points[i].x(); + lower = qMin(lower, m_points[i].x()); + upper = qMax(upper, m_points[i].x()); + accepted.append(m_points[i]); + } + const int index = m_parameter->itemData(m_parameter->currentIndex()).toInt(); + const nmDataSensitive::VariableSampling& variable = m_results->m_variables[index]; + m_plot->setToolTip(tr("Threshold: %1 MPa\n").arg(m_threshold, 0, 'g', 6) + + tr("Below threshold: %1 / %2; %3 range: %4").arg(accepted.size()).arg(m_points.size()) + .arg(variable.m_varName).arg(accepted.isEmpty() ? tr("N/A") + : QString::number(lower, 'g', 6) + " - " + QString::number(upper, 'g', 6) + " " + variable.m_modelValue.getUnit())); + if(m_threshold > m_plot->getAxisOf(1)->getRangeMax()) { + VecDouble ticks; + const double top = m_threshold * 1.1; + for(int i = 0; i <= 5; ++i) ticks.append(i * top / 5.0); + m_plot->setAxisScaleY(0.0, top, ticks); + } + QVector line; + line << QPointF(m_plot->getAxisOf(0)->getRangeMin(), m_threshold) + << QPointF(m_plot->getAxisOf(0)->getRangeMax(), m_threshold); + QVector curves = m_plot->getCurveData(); + // 原位更新图元及导出数据,不触发框架重新缩放,拖动时坐标轴保持稳定。 + for(int i = 0; i < curves.size(); ++i) { + const QString name = curves[i].m_sCurveName; + if(name != tr("Below threshold") && name != tr("Threshold")) continue; + const QVector& points = name == tr("Threshold") ? line : accepted; + curves[i].m_vecX.clear(); + curves[i].m_vecY.clear(); + for(int j = 0; j < points.size(); ++j) { + curves[i].m_vecX.append(points[j].x()); + curves[i].m_vecY.append(points[j].y()); + } + ZxObjCurve* curve = m_plot->getCurve(name); + if(curve) curve->setAllValues(points); + else if(!points.isEmpty()) { + curve = m_plot->appendSeriesD(curves[i].m_vecX, curves[i].m_vecY, name); + if(curve) curve->setCurvePty(curves[i].m_oPen, curves[i].m_oDot, + curves[i].m_bLineVisible, curves[i].m_bPointVisible); + } + } + m_plot->setCurveData(curves); + // 基准点始终置顶,包括首次出现阈值以下的点时。 + ZxObjCurve* reference = m_plot->getCurve(tr("reference")); + if(reference) m_plot->m_pPlot->bringToFront(reference); + m_plot->m_pPlot->update(); +} + +void nmWxSensitivityScatter::resetThreshold() +{ + // 有基准误差时恢复至基准值,无实测数据时使用本批最大有效误差。 + m_threshold = m_defaultThreshold; + updateThreshold(); +} + +void nmWxSensitivityScatter::adjustContextMenu(QMenu* menu) +{ + // 复用绘图右键菜单,保留框架的缩放、复制与导出入口。 + menu->addAction(tr("Reset line"), this, SLOT(resetThreshold())); +} + +bool nmWxSensitivityScatter::eventFilter(QObject* object, QEvent* event) +{ + if(object != m_plot->m_pPlotView->viewport()) return iDlgBase::eventFilter(object, event); + tCurvePlotView* view = m_plot->m_pPlotView; + ZxSubAxisBase* axisY = m_plot->getAxisOf(1); + // 位置跟随实际绘图区,窗口缩放后仍贴在坐标轴内侧。 + if(event->type() == QEvent::Paint) + m_legend->move(view->mapFromScene(m_plot->m_pPlot->getInnerRectF().topLeft()).toPoint() + QPoint(8, 8)); + // 只接管阈值线附近的左键拖动,其余缩放、右键及导出仍由框架处理。 + if(event->type() == QEvent::MouseButtonPress || event->type() == QEvent::MouseMove || event->type() == QEvent::MouseButtonRelease) { + QMouseEvent* mouse = static_cast(event); + const QPointF scene = view->mapToScene(QPointF(mouse->pos())); + const double lineY = view->mapFromScene(QPointF(scene.x(), axisY->getPosForValue(m_threshold))).y(); + if(event->type() == QEvent::MouseButtonPress && mouse->button() == Qt::LeftButton && + m_plot->m_pPlot->getInnerRectF().contains(scene) && qAbs(mouse->pos().y() - lineY) <= 6.0) m_draggingThreshold = true; + if(m_draggingThreshold) { + m_threshold = qBound(0.0, axisY->getValueForPos(scene.y()), axisY->getRangeMax()); + updateThreshold(); + if(event->type() == QEvent::MouseButtonRelease) m_draggingThreshold = false; + return true; + } + } + if(event->type() == QEvent::ToolTip) { + // 点提示显示对应运行的完整参数组合;不以排序后的点号代替运行编号。 + QHelpEvent* help = static_cast(event); + for(int i = 0; i < m_points.size(); ++i) { + const QPointF position = view->mapFromScene(QPointF(m_plot->getAxisOf(0)->getPosForValue(m_points[i].x()), axisY->getPosForValue(m_points[i].y()))); + if(qAbs(position.x() - help->pos().x()) > 6.0 || qAbs(position.y() - help->pos().y()) > 6.0) continue; + const nmDataSensitive::RunResult& run = m_results->m_runs[m_runRows[i]]; + QToolTip::showText(help->globalPos(), tr("Run %1\n%2\nGoodness of fit: %3 MPa") + .arg(run.m_nRunIndex + 1).arg(sensitivityRunParameters(*m_results, run)) + .arg(run.m_dPressureRmse, 0, 'g', 6), view->viewport()); + return true; + } + QToolTip::showText(help->globalPos(), m_plot->toolTip(), view->viewport()); + return true; + } + return iDlgBase::eventFilter(object, event); +} class SensitivityDistributionPlot : public QWidget { public: