From f43eb568d8f7114346a225d8b95bfcd1d7103995 Mon Sep 17 00:00:00 2001 From: lvjunjie Date: Tue, 29 Sep 2026 16:39:34 +0800 Subject: [PATCH] =?UTF-8?q?refactor(nmNum):=20=E7=A7=BB=E9=99=A4=E5=88=86?= =?UTF-8?q?=E5=B1=82=E9=87=87=E6=A0=B7=E5=B9=B6=E6=8C=89=E5=AF=B9=E6=95=B0?= =?UTF-8?q?=E6=97=B6=E9=97=B4=E8=B7=A8=E5=BA=A6=E7=A1=AE=E5=AE=9A=E9=87=87?= =?UTF-8?q?=E6=A0=B7=E7=82=B9=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 删除 LM 分层采样选项、逐层加密逻辑及专用诊断字段 - 每个对数时间数量级取 20 个间隔,采样点包含区间两端 - 整体误差、形状误差及前期指标共用采样网格 - 形状斜率跨度保持约为对数时间范围的 10%,同步适配残差维度和窗口权重 - 更新拟合记录中的采样策略描述,翻译资源留待统一调整 --- .../nmCalculation/nmCalculationAutoFitLM.h | 18 +- Include/nmNum/nmSubWxs/nmWxAutomaticFitting.h | 2 - .../nmCalculation/nmCalculationAutoFitLM.cpp | 357 ++++-------------- Src/nmNum/nmSubWxs/nmWxAutomaticFitting.cpp | 14 - 4 files changed, 67 insertions(+), 324 deletions(-) diff --git a/Include/nmNum/nmCalculation/nmCalculationAutoFitLM.h b/Include/nmNum/nmCalculation/nmCalculationAutoFitLM.h index 5e6d028d..e88920fd 100644 --- a/Include/nmNum/nmCalculation/nmCalculationAutoFitLM.h +++ b/Include/nmNum/nmCalculation/nmCalculationAutoFitLM.h @@ -12,7 +12,7 @@ #include "nmCalculation_global.h" // 固定对数时间窗口的误差诊断。时间边界为不含重叠区的基础边界; -// rmsError 是局部加权均方根,energy 是对当前层残差能量的贡献。 +// rmsError 是局部加权均方根,energy 是对整体残差能量的贡献。 struct AutoFitTimeWindowLM { double timeMin; double timeMax; @@ -33,11 +33,6 @@ struct AutoFitObjectiveBreakdownLM { double pressureLoss; double derivativeLoss; QVector residualVector; - // 分层模式的残差属于当前层,total 属于全部目标点;固定模式坐标数组为空。 - QVector sampleCoordinates; - int samplingStride; - int fullPointCount; - double layerError; QVector timeWindows; double verticalCommonBias; double verticalLoss; @@ -46,9 +41,9 @@ struct AutoFitObjectiveBreakdownLM { double horizontalLoss; bool horizontalReliable; bool registrationAmbiguous; - // 固定 log-time 网格上的双曲线斜率残差,独立于数值残差的采样层级。 + // 与整体误差共用 log-time 采样网格,斜率跨度约为完整对数时域的 10%。 QVector shapeResiduals; - // 前期数值残差为 81 点,形状残差为 73 个斜率区间,均含第一窗口权重。 + // 前期数值和形状残差沿用同一网格与斜率跨度,均含第一窗口权重。 // earlyParallelResiduals/Loss 沿用历史字段名,现为压力、导数分别匹配目标的形状误差。 // earlyParallelBias 仍记录相对斜率偏差,仅供诊断。 QVector earlyValueResiduals; @@ -68,9 +63,6 @@ struct AutoFitObjectiveBreakdownLM { , total(1.0e10) , pressureLoss(std::numeric_limits::quiet_NaN()) , derivativeLoss(std::numeric_limits::quiet_NaN()) - , samplingStride(1) - , fullPointCount(80) - , layerError(1.0e10) , verticalCommonBias(std::numeric_limits::quiet_NaN()) , verticalLoss(std::numeric_limits::quiet_NaN()) , verticalReliable(false) @@ -122,7 +114,6 @@ public: int getTotalEvaluations() const; void resetOptimizer(); void setTargetWellName(const QString& wellName); - void setLayeredSamplingEnabled(bool enabled); signals: void progressUpdated(int iteration, double bestFitness); @@ -217,9 +208,6 @@ private: double m_comparisonTimeMin; double m_comparisonTimeMax; QString m_targetWellName; - // 此开关由拟合界面传入;每轮重置层级,固定模式仍使用原来的 80 点目标。 - bool m_layeredSampling; - int m_samplingStride; int m_maxIterations; double m_targetError; diff --git a/Include/nmNum/nmSubWxs/nmWxAutomaticFitting.h b/Include/nmNum/nmSubWxs/nmWxAutomaticFitting.h index 4c6c6947..3f526c4d 100644 --- a/Include/nmNum/nmSubWxs/nmWxAutomaticFitting.h +++ b/Include/nmNum/nmSubWxs/nmWxAutomaticFitting.h @@ -82,8 +82,6 @@ private: QLineEdit* m_errorLimitEdit; QComboBox* m_targetWellCombo; QComboBox* m_algorithmCombo; - QLabel* m_samplingLabel; - QComboBox* m_samplingCombo; QLabel* m_surrogateLabel; QComboBox* m_surrogateCombo; diff --git a/Src/nmNum/nmCalculation/nmCalculationAutoFitLM.cpp b/Src/nmNum/nmCalculation/nmCalculationAutoFitLM.cpp index 4b0257c8..3c396d3f 100644 --- a/Src/nmNum/nmCalculation/nmCalculationAutoFitLM.cpp +++ b/Src/nmNum/nmCalculation/nmCalculationAutoFitLM.cpp @@ -29,6 +29,13 @@ static const bool kAutoFitDiagnosticTraceEnabled = true; static const int kAutoFitTimeWindowCount = 4; static const double kAutoFitTimeWindowOverlapRatio = 0.20; +static const int kAutoFitIntervalsPerDecade = 20; + +static int autoFitShapeLag(int pointCount) +{ + // 保持斜率跨度约为完整对数时间范围的 10%,四舍五入到间隔数且至少跨一个间隔。 + return qMax(1, qRound((pointCount - 1) * 0.10)); +} static double autoFitTimeWindowWeight(double coordinate, int windowIndex) { @@ -53,50 +60,8 @@ static double autoFitTimeWindowWeight(double coordinate, int windowIndex) return weight; } -// 目标时间点构成嵌套子集。窗口中心、重叠区两端及边界使用原始点两侧作锚点。 -static QVector autoFitSamplingIndices(const QVector& coordinates, int stride) -{ - QVector selected(coordinates.size(), false); - for(int i = 0; i < selected.size(); i += stride) { - selected[i] = true; - } - selected[0] = true; - selected[selected.size() - 1] = true; - for(int k = 0; k < kAutoFitTimeWindowCount; ++k) { - const double width = 1.0 / kAutoFitTimeWindowCount; - const double anchors[] = {(k + 0.5) * width, - k * width - width * kAutoFitTimeWindowOverlapRatio * 0.5, - k * width, k * width + width * kAutoFitTimeWindowOverlapRatio * 0.5}; - for(int a = 0; a < 4; ++a) { - const int right = static_cast(std::lower_bound( - coordinates.begin(), coordinates.end(), anchors[a]) - coordinates.begin()); - if(right < selected.size()) selected[right] = true; - if(right > 0) selected[right - 1] = true; - } - } - QVector indices; - for(int i = 0; i < selected.size(); ++i) { - if(selected[i]) indices.append(i); - } - return indices; -} - -// 在归一化 log(time) 上使用梯形积分权重,避免原始数据密集段被重复放大。 -static QVector autoFitLogTimeWeights(const QVector& coordinates) -{ - QVector weights(coordinates.size(), 0.0); - for(int i = 1; i < coordinates.size(); ++i) { - const double halfWidth = 0.5 * (coordinates[i] - coordinates[i - 1]); - weights[i - 1] += halfWidth; - weights[i] += halfWidth; - } - return weights; -} - static QVector calculateAutoFitTimeWindows( - const QVector& residualVector, double timeMin, double timeMax, - const QVector& coordinates = QVector(), - const QVector& timeWeights = QVector()) + const QVector& residualVector, double timeMin, double timeMax) { // 残差前后两半分别为压力和导数,已包含各占一半及时间采样权重的归一化。 const int pointCount = residualVector.size() / 2; @@ -111,16 +76,14 @@ static QVector calculateAutoFitTimeWindows( : qExp(logMin + logSpan * (k + 1) / kAutoFitTimeWindowCount); for(int i = 0; i < pointCount; ++i) { const double weight = autoFitTimeWindowWeight( - coordinates.isEmpty() ? static_cast(i) / (pointCount - 1) - : coordinates[i], k); - window.weightSum += weight * (timeWeights.isEmpty() ? 1.0 : timeWeights[i]); + static_cast(i) / (pointCount - 1), k); + window.weightSum += weight; window.energy += weight * (residualVector[i] * residualVector[i] + residualVector[pointCount + i] * residualVector[pointCount + i]); } window.rmsError = window.weightSum > 0.0 - ? qSqrt(window.energy * (timeWeights.isEmpty() ? pointCount : 1.0) - / window.weightSum) : 0.0; + ? qSqrt(window.energy * pointCount / window.weightSum) : 0.0; } return windows; } @@ -295,15 +258,13 @@ struct TrustRegionEvaluation {} }; -// LM 只使用固定长度、全部有限的普通残差。 +// LM 残差长度由本轮固定比较区间决定,所有残差必须有限。 static bool trustRegionResidualsValid( const AutoFitObjectiveBreakdownLM& breakdown) { - // 固定模式仍要求 160 维;分层模式按当前时间点数校验,切层后重建 J。 - const int pointCount = breakdown.sampleCoordinates.isEmpty() - ? 80 : breakdown.sampleCoordinates.size(); - if(!breakdown.valid || pointCount < 3 || - breakdown.residualVector.size() != 2 * pointCount) { + // 压力和导数共用采样时间,两个通道点数相同且各至少三个点。 + if(!breakdown.valid || breakdown.residualVector.size() < 6 || + breakdown.residualVector.size() % 2 != 0) { return false; } @@ -312,11 +273,14 @@ static bool trustRegionResidualsValid( return false; } } - if(breakdown.shapeResiduals.size() != 146 || !isFiniteNumber(breakdown.shapeLoss)) return false; + const int pointCount = breakdown.residualVector.size() / 2; + const int slopeCount = pointCount - autoFitShapeLag(pointCount); + if(breakdown.shapeResiduals.size() != 2 * slopeCount || !isFiniteNumber(breakdown.shapeLoss)) return false; for(int i = 0; i < breakdown.shapeResiduals.size(); ++i) { if(!isFiniteNumber(breakdown.shapeResiduals[i])) return false; } - if(breakdown.earlyValueResiduals.size() != 162 || breakdown.earlyParallelResiduals.size() != 146 || + if(breakdown.earlyValueResiduals.size() != 2 * pointCount || + breakdown.earlyParallelResiduals.size() != 2 * slopeCount || !isFiniteNumber(breakdown.earlyValueLoss) || !isFiniteNumber(breakdown.earlyParallelLoss) || !isFiniteNumber(breakdown.earlyParallelBias)) return false; for(int i = 0; i < breakdown.earlyValueResiduals.size(); ++i) { @@ -383,12 +347,15 @@ static double trustRegionEarlyGapBias(const AutoFitObjectiveBreakdownLM& objecti // 第一窗口的形状能量与局部 Fisher 使用相同的中心时间和重叠权重, // 压力、导数同时参与;不重新插值或调用求解器。 -static double trustRegionEarlyShapeEnergy(const QVector& residual) +static double trustRegionEarlyShapeEnergy(const AutoFitObjectiveBreakdownLM& objective) { - const int pointCount = residual.size() / 2; + const QVector& residual = objective.shapeResiduals; + const int pointCount = objective.residualVector.size() / 2; + const int lag = autoFitShapeLag(pointCount); + const int slopeCount = pointCount - lag; double energy = 0.0; for(int row = 0; row < residual.size(); ++row) { - const double coordinate = (row % pointCount + 4.0) / 80.0; + const double coordinate = (row % slopeCount + lag * 0.5) / (pointCount - 1); energy += autoFitTimeWindowWeight(coordinate, 0) * residual[row] * residual[row]; } return energy; @@ -399,11 +366,12 @@ static double trustRegionEarlyShapeEnergy(const QVector& residual) static void populateEarlyWellboreMetrics(AutoFitObjectiveBreakdownLM* objective, const QVector targetLogs[2], const QVector resultLogs[2], double logTimeSpan) { - const int count = 81; + const int count = targetLogs[0].size(); QVector weights(count, 0.0); double weightSum = 0.0; for(int i = 0; i < count; ++i) { - weights[i] = autoFitTimeWindowWeight(i / 80.0, 0) * ((i == 0 || i == count - 1) ? 0.5 : 1.0); + weights[i] = autoFitTimeWindowWeight(static_cast(i) / (count - 1), 0) * + ((i == 0 || i == count - 1) ? 0.5 : 1.0); weightSum += weights[i]; } objective->earlyValueResiduals.fill(0.0, 2 * count); @@ -417,8 +385,8 @@ static void populateEarlyWellboreMetrics(AutoFitObjectiveBreakdownLM* objective, } objective->earlyValueLoss = qSqrt(trustRegionSquaredNorm(objective->earlyValueResiduals)); - // 复用形状指标的 8 点跨度,窗口权重取斜率区间中心,减少相邻点噪声。 - const int lag = 8; + // 复用整体形状的斜率跨度,窗口权重取区间中心,随采样数量同步变化。 + const int lag = autoFitShapeLag(count); const int slopeCount = count - lag; const double logTimeStep = logTimeSpan * lag / (count - 1); QVector parallelWeights(slopeCount, 0.0); @@ -748,8 +716,6 @@ nmCalculationAutoFitLM::nmCalculationAutoFitLM(QObject* parent) , m_globalBestFitness(1e10) , m_comparisonTimeMin(0.0) , m_comparisonTimeMax(0.0) - , m_layeredSampling(false) - , m_samplingStride(1) , m_maxIterations(100) , m_targetError(0.001) , m_totalEvaluations(0) @@ -929,7 +895,6 @@ void nmCalculationAutoFitLM::resetOptimizer() m_userInitialObjectiveBreakdown = AutoFitObjectiveBreakdownLM(); m_comparisonTimeMin = 0.0; m_comparisonTimeMax = 0.0; - m_samplingStride = m_layeredSampling ? 4 : 1; m_currentIteration = 0; m_totalEvaluations = 0; m_successfulEvaluations = 0; @@ -944,14 +909,6 @@ void nmCalculationAutoFitLM::resetOptimizer() DEBUG_OUT("LM optimizer reset"); } -void nmCalculationAutoFitLM::setLayeredSamplingEnabled(bool enabled) -{ - // 拟合运行期间不允许改变残差定义;新一轮由 resetOptimizer 初始化层级。 - if(!m_isRunning) { - m_layeredSampling = enabled; - } -} - void nmCalculationAutoFitLM::setTargetWellName(const QString& wellName) { // 目标井名是贯穿拟合流程的关键索引: @@ -1056,8 +1013,7 @@ void nmCalculationAutoFitLM::writeTraceHeader() << prefix + "weight_sum" << prefix + "rms_error" << prefix + "energy"; } - cols << "sampling_mode" << "sampling_stride" << "sampling_points" - << "full_target_points" << "layer_objective" + cols << "sampling_mode" << "sampling_points" << "pressure_vertical_bias" << "derivative_vertical_bias" << "first_window_shape_loss" << "early_value_loss" << "early_parallel_loss" << "early_parallel_bias" << "early_gap_loss" << "early_gap_bias"; QTextStream out(&m_traceFile); @@ -1096,13 +1052,13 @@ void nmCalculationAutoFitLM::writeTraceMetaFile() QTextStream out(&metaFile); out << "{\n"; - out << " \"schema_version\": 47,\n"; + out << " \"schema_version\": 50,\n"; out << " \"strategy\": \"permeability_height_then_shape_then_joint_lm\",\n"; out << " \"height_acceptance\": \"reliable_vertical_loss_decrease; no_shape_or_total_loss_constraint\",\n"; out << " \"shape_priority\": \"wellbore_parameter_sweep_then_non_wellbore_sweep_then_optional_wellbore_recheck\",\n"; - out << " \"shape_metric\": \"pressure_and_derivative_log_slopes_81_points_lag_8\",\n"; - out << " \"early_parallel_metric\": \"pressure_and_derivative_log_slopes_first_window_81_points_lag_8\",\n"; - out << " \"early_gap_metric\": \"weighted_rms_log10_pressure_derivative_ratio_error_first_window_81_points\",\n"; + out << " \"shape_metric\": \"pressure_and_derivative_log_slopes_shared_sampling_grid_lag_round_10_percent_min_1\",\n"; + out << " \"early_parallel_metric\": \"pressure_and_derivative_log_slopes_first_window_shared_sampling_grid_lag_round_10_percent_min_1\",\n"; + out << " \"early_gap_metric\": \"weighted_rms_log10_pressure_derivative_ratio_error_first_window_shared_sampling_grid\",\n"; out << " \"early_gap_bias_metric\": \"weighted_mean_signed_log10_gap_simulation_minus_target_first_window\",\n"; out << " \"early_direction_policy\": \"first_window_shape_LM_selects_unvisited_wellbore_parameter_and_initial_direction; direction_locked_until_parameter_finished; gap_diagnostics_only\",\n"; out << " \"early_initial_step_policy\": \"same_as_later_shape_sweep; initial_LM_coordinate_radius_0.24; no_cached_probe_acceptance\",\n"; @@ -1132,7 +1088,8 @@ void nmCalculationAutoFitLM::writeTraceMetaFile() << jsonEscape(QDateTime::currentDateTime().toString(Qt::ISODate)) << ",\n"; out << " \"trace_csv\": " << jsonEscape(QFileInfo(m_traceFilePath).fileName()) << ",\n"; out << " \"sampling_mode\": " - << jsonEscape(m_layeredSampling ? "layered_target" : "fixed_80") << ",\n"; + << jsonEscape("log_uniform_per_decade") << ",\n"; + out << " \"sampling_intervals_per_decade\": " << kAutoFitIntervalsPerDecade << ",\n"; out << " \"target\": {\n"; out << " \"well_name\": " << jsonEscape(m_targetWellName) << ",\n"; out << " \"time\": " << jsonDoubleArray(targetTime) << ",\n"; @@ -1237,15 +1194,12 @@ void nmCalculationAutoFitLM::writeTraceRow( } } - cols << (m_layeredSampling ? "layered_target" : "fixed_80") - << QString::number(objectiveBreakdown ? objectiveBreakdown->samplingStride : m_samplingStride) + cols << "log_uniform_per_decade" << (objectiveBreakdown ? QString::number(objectiveBreakdown->residualVector.size() / 2) : QString()) - << (objectiveBreakdown ? QString::number(objectiveBreakdown->fullPointCount) : QString()) - << (objectiveBreakdown ? traceNumber(objectiveBreakdown->layerError) : QString()) << (objectiveBreakdown ? traceNumber(objectiveBreakdown->pressureVerticalBias) : QString()) << (objectiveBreakdown ? traceNumber(objectiveBreakdown->derivativeVerticalBias) : QString()) << (objectiveBreakdown && objectiveBreakdown->valid - ? traceNumber(qSqrt(trustRegionEarlyShapeEnergy(objectiveBreakdown->shapeResiduals))) : QString()) + ? traceNumber(qSqrt(trustRegionEarlyShapeEnergy(*objectiveBreakdown))) : QString()) << (objectiveBreakdown && objectiveBreakdown->valid ? traceNumber(objectiveBreakdown->earlyValueLoss) : QString()) << (objectiveBreakdown && objectiveBreakdown->valid ? traceNumber(objectiveBreakdown->earlyParallelLoss) : QString()) << (objectiveBreakdown && objectiveBreakdown->valid ? traceNumber(objectiveBreakdown->earlyParallelBias) : QString()) @@ -1551,29 +1505,6 @@ bool nmCalculationAutoFitLM::startAutoFitting() finalReason = runTrustRegionFitting(); validateAndProtectFinalResult(); - // 两种模式共用全目标点比较指标,仅重算已有曲线,不增加真实求解次数。 - if(m_comparisonTimeMin > 0.0 && !m_globalBestLogLogData.isEmpty()) { - const bool savedMode = m_layeredSampling; - const int savedStride = m_samplingStride; - const AutoFitObjectiveBreakdownLM savedBreakdown = m_lastObjectiveBreakdown; - m_layeredSampling = true; - m_samplingStride = 1; - const double comparisonFinal = calculateLogLogCurveError(m_targetLogLogData, m_globalBestLogLogData); - const double comparisonInitial = m_userInitialLogLogData.isEmpty() ? 1.0e10 - : calculateLogLogCurveError(m_targetLogLogData, m_userInitialLogLogData); - m_layeredSampling = savedMode; - m_samplingStride = savedStride; - m_lastObjectiveBreakdown = savedBreakdown; - if(comparisonFinal < 1.0e9) { - emit logMessageGenerated(tr("Full-target comparison error: initial=%1; final=%2") - .arg(comparisonInitial < 1.0e9 ? QString::number(comparisonInitial, 'e', 6) : tr("Unavailable")) - .arg(comparisonFinal, 0, 'e', 6)); - } - if(savedMode && savedStride > 1 && finalReason == LM_MAX_ITERATIONS) { - emit logMessageGenerated(tr("Budget exhausted before the full sampling layer; convergence is not confirmed.")); - } - } - if(!m_globalBestPosition.isEmpty() && m_globalBestObjectiveBreakdown.valid) { // 精英保护之后记录最终行,保证轨迹与实际写回参数一致。 writeTraceRow(m_currentIteration, @@ -1588,7 +1519,7 @@ bool nmCalculationAutoFitLM::startAutoFitting() } if(finalReason != LM_USER_STOPPED && finalReason != LM_OPTIMIZATION_FAILED && - (!m_layeredSampling || m_samplingStride == 1) && m_globalBestFitness < m_targetError) { + m_globalBestFitness < m_targetError) { finalReason = LM_TARGET_ACHIEVED; } } catch(const std::exception& e) { @@ -1859,7 +1790,7 @@ bool nmCalculationAutoFitLM::evaluateTrustRegionPoint( } // evaluateFitness() 会写入 DataManager 并调用真实求解器。这里统一统计 - // 真实评价次数和耗时,同时要求当前层残差、误差结构和结果曲线均有效。 + // 真实评价次数和耗时,同时要求固定采样残差、误差结构和结果曲线均有效。 QTime timer; timer.start(); *fitness = evaluateFitness(parameters, false); @@ -1924,7 +1855,7 @@ StopReasonLM nmCalculationAutoFitLM::runTrustRegionFitting() bool globalFallbackAttempted = false; StopReasonLM stopReason = LM_MAX_ITERATIONS; - // jacobian 的行对应当前采样层的残差,列对应用户勾选的参数。 + // jacobian 的行对应固定采样的残差,列对应用户勾选的参数。 // Fisher 按当前阶段取数值或形状残差行;冻结列不参与形状差分,整体阶段重建全部列。 QVector > jacobian; QVector jacobianColumnValid(dimensions, false); @@ -2159,54 +2090,8 @@ StopReasonLM nmCalculationAutoFitLM::runTrustRegionFitting() // 第三阶段有效改善相对上一次有效基准累计判断;第二阶段按逐参数拒绝次数结束。 double effectiveImprovementBaseline = stageError(current); - int fullDataRejections = 0; - bool samplingRefreshFailed = false; - auto promoteSampling = [&](bool complete) -> bool { - if(!m_layeredSampling || m_samplingStride == 1 || m_shouldStop) { - return false; - } - const int previousStride = m_samplingStride; - const AutoFitObjectiveBreakdownLM previousBreakdown = current.breakdown; - m_samplingStride = complete ? 1 : m_samplingStride / 2; - const double refreshedFitness = calculateLogLogCurveError(m_targetLogLogData, current.curve); - if(refreshedFitness >= 1.0e9 || !trustRegionResidualsValid(m_lastObjectiveBreakdown)) { - m_samplingStride = previousStride; - m_lastObjectiveBreakdown = previousBreakdown; - m_lastError = tr("Failed to refresh the sampling layer from the current curve."); - samplingRefreshFailed = true; - return false; - } - current.fitness = refreshedFitness; - current.breakdown = m_lastObjectiveBreakdown; - publishAcceptedPoint(current); - restoreEvaluationState(current); - jacobian.clear(); - jacobianColumnValid.fill(false); - rebuildRequested = true; - rebuildReason = QT_TR_NOOP("sampling layer changed"); - trustRadius = 0.12; - damping = 1.0e-2; - consecutiveRejectedSteps = 0; - consecutiveIneffectiveSteps = 0; - acceptedSinceRebuild = 0; - consecutivePoorPredictions = 0; - modelRebuiltAtMinimumRadius = false; - stagnationConfirmationRequested = false; - globalFallbackAttempted = false; - fullDataRejections = 0; - effectiveImprovementBaseline = stageError(current); - emit logMessageGenerated(tr("LM sampling refined: %1 / %2 target points; full-target error: %3") - .arg(current.breakdown.residualVector.size() / 2) - .arg(current.breakdown.fullPointCount).arg(current.fitness, 0, 'e', 4)); - writeTraceRow(m_currentIteration, -1, "sampling_refinement", current.parameters, - current.fitness, true, 0, "rebuild_required", ¤t.breakdown); - return true; - }; - - emit logMessageGenerated(m_layeredSampling - ? tr("LM sampling: layered target points (%1 / %2); total-stage acceptance uses all valid target points.") - .arg(current.breakdown.residualVector.size() / 2).arg(current.breakdown.fullPointCount) - : tr("LM sampling: fixed 80 points (original mode).")); + emit logMessageGenerated(tr("LM sampling: %1 points (%2 intervals per log-time decade).") + .arg(current.breakdown.residualVector.size() / 2).arg(kAutoFitIntervalsPerDecade)); auto reuseSensitivityForNextStage = [&]() { // 更换目标时复用完整 J,清除旧目标下的拒绝和预测失准计数。 @@ -2401,8 +2286,7 @@ StopReasonLM nmCalculationAutoFitLM::runTrustRegionFitting() .arg(maximumIneffectiveSteps)); if(!shapeStage && current.fitness < m_targetError) { - promoteSampling(true); - return samplingRefreshFailed ? LM_OPTIMIZATION_FAILED : LM_TARGET_ACHIEVED; + return LM_TARGET_ACHIEVED; } // 在同一个真实工作点逐参数做单边差分。失败先在原方向缩步,再反向尝试; @@ -2621,22 +2505,6 @@ StopReasonLM nmCalculationAutoFitLM::runTrustRegionFitting() } if(m_shouldStop) break; if(!shapeStage && (totalIterations >= m_maxIterations || m_totalEvaluations >= maximumEvaluations)) break; - if(!shapeStage && m_layeredSampling && m_samplingStride > 1) { - const int remainingEvaluations = maximumEvaluations - m_totalEvaluations; - // 已准备重建时,提前计入本轮差分及候选的开销,避免紧接着因预算再加密。 - const bool reserveFinalBudget = remainingEvaluations <= 2 * (dimensions + 1) || - (rebuildRequested && remainingEvaluations <= 3 * (dimensions + 1)); - const int layerDeadline = qMax(1, m_maxIterations * (m_samplingStride == 4 ? 1 : 2) / 3); - const bool mergeRefinement = rebuildRequested && totalIterations < layerDeadline && - (totalIterations + 1 >= layerDeadline || reserveFinalBudget); - if(reserveFinalBudget || totalIterations >= layerDeadline || mergeRefinement) { - const bool promoted = promoteSampling(reserveFinalBudget); - if(samplingRefreshFailed) break; - if(promoted && mergeRefinement) { - rebuildReason = QT_TR_NOOP("sampling refinement merged with pending rebuild"); - } - } - } if(rebuildRequested) { emit logMessageGenerated(tr("Rebuilding sensitivity model: %1").arg(tr(rebuildReason))); writeTraceRow(m_currentIteration, -1, "sensitivity_rebuild", current.parameters, @@ -2654,14 +2522,12 @@ StopReasonLM nmCalculationAutoFitLM::runTrustRegionFitting() stopReason = LM_OPTIMIZATION_FAILED; break; } - if(promoteSampling(false)) continue; stopReason = m_shouldStop ? LM_USER_STOPPED : LM_LOCAL_OPTIMUM; break; } if(!shapeStage && current.fitness < m_targetError) { - promoteSampling(true); stopReason = LM_TARGET_ACHIEVED; break; } @@ -2684,10 +2550,13 @@ StopReasonLM nmCalculationAutoFitLM::runTrustRegionFitting() current.breakdown.earlyValueResiduals.size() : (shapeStage ? current.breakdown.residualVector.size() : 0); const QVector > objectiveJacobian = jacobian.mid(rowOffset, objectiveResidual.size()); - QVector objectiveCoordinates = current.breakdown.sampleCoordinates; + QVector objectiveCoordinates; if(shapeStage) { - objectiveCoordinates.clear(); - for(int i = 0; i < 73; ++i) objectiveCoordinates.append((i + 4.0) / 80.0); + // Fisher 窗口与形状残差使用同一组斜率区间中心。 + const int pointCount = current.breakdown.residualVector.size() / 2; + const int lag = autoFitShapeLag(pointCount); + for(int i = 0; i < pointCount - lag; ++i) + objectiveCoordinates.append((i + lag * 0.5) / (pointCount - 1)); } const QVector information = buildTrustRegionFisher( objectiveJacobian, objectiveResidual, jacobianColumnValid, objectiveCoordinates); @@ -2769,7 +2638,6 @@ StopReasonLM nmCalculationAutoFitLM::runTrustRegionFitting() if(selectedColumns.isEmpty()) { if(trustRadius <= minimumTrustRadius * 1.01 && modelRebuiltAtMinimumRadius) { - if(promoteSampling(false)) continue; stopReason = LM_LOCAL_OPTIMUM; break; } @@ -2778,7 +2646,6 @@ StopReasonLM nmCalculationAutoFitLM::runTrustRegionFitting() rebuildRequested = true; rebuildReason = QT_TR_NOOP("no feasible descent step"); if(recordIneffectiveStep()) { - if(promoteSampling(false)) continue; stopReason = LM_LOCAL_OPTIMUM; break; } @@ -2849,7 +2716,6 @@ StopReasonLM nmCalculationAutoFitLM::runTrustRegionFitting() break; } if(recordIneffectiveStep()) { - if(promoteSampling(false)) continue; stopReason = LM_LOCAL_OPTIMUM; break; } @@ -2879,7 +2745,7 @@ StopReasonLM nmCalculationAutoFitLM::runTrustRegionFitting() const double candidateEnergy = 0.5 * trustRegionSquaredNorm(candidateResidual); double actualReduction = objectiveEnergy - candidateEnergy; double reductionRatio = predictedReduction > 1.0e-14 ? actualReduction / predictedReduction : 0.0; - // 使用同一采样层、同一阶段目标比较预测和实际改善。接近收敛时的微小 + // 使用固定采样和同一阶段目标比较预测与实际改善。接近收敛时的微小 // 预测量交给停滞逻辑处理,避免比例数值波动反复触发昂贵的全参数重建。 const double predictionFloor = qMax(1.0e-14, objectiveEnergy * 1.0e-8); const bool poorPrediction = predictedReduction > predictionFloor && @@ -2890,12 +2756,6 @@ StopReasonLM nmCalculationAutoFitLM::runTrustRegionFitting() rebuildReason = QT_TR_NOOP("2 consecutive steps with actual improvement below 25% of prediction"); } bool accepted = acceptable(candidate, current); - // 粗层认为下降而完整数据不认可时累计,连续两次就提前加密。 - if(!shapeStage && m_layeredSampling && m_samplingStride > 1 && !accepted && actualReduction > 0.0) { - ++fullDataRejections; - } else { - fullDataRejections = 0; - } QString componentName = earlyShapeStage ? (m_enabledParamIndices[selectedColumns[0]] == 2 ? "storage_parallel" : "skin_parallel") : (shapeStage ? "shape" : "total"); @@ -2982,23 +2842,15 @@ StopReasonLM nmCalculationAutoFitLM::runTrustRegionFitting() const bool effectiveImprovement = registerEffectiveImprovement(stageError(current)); if(!effectiveImprovement && recordIneffectiveStep()) stopReason = LM_LOCAL_OPTIMUM; - if(stopReason == LM_LOCAL_OPTIMUM || fullDataRejections >= 2) { - if(promoteSampling(false)) { - stopReason = LM_MAX_ITERATIONS; - continue; - } - if(stopReason == LM_LOCAL_OPTIMUM || samplingRefreshFailed) break; - } + if(stopReason == LM_LOCAL_OPTIMUM) break; if(!shapeStage && current.fitness < m_targetError) { - promoteSampling(true); stopReason = LM_TARGET_ACHIEVED; break; } if(!shapeStage && selectedWindow < 0 && trustRadius <= minimumTrustRadius * 1.01 && consecutiveRejectedSteps >= 2 && consecutivePoorPredictions >= 2) { if(modelRebuiltAtMinimumRadius) { - if(promoteSampling(false)) continue; stopReason = LM_LOCAL_OPTIMUM; break; } @@ -3017,10 +2869,8 @@ StopReasonLM nmCalculationAutoFitLM::runTrustRegionFitting() if(m_shouldStop) { return LM_USER_STOPPED; } - if(samplingRefreshFailed) return LM_OPTIMIZATION_FAILED; if(!shapeStage && current.fitness < m_targetError) { - promoteSampling(true); - return samplingRefreshFailed ? LM_OPTIMIZATION_FAILED : LM_TARGET_ACHIEVED; + return LM_TARGET_ACHIEVED; } if(stopReason == LM_CONSECUTIVE_FAILURES || stopReason == LM_LOCAL_OPTIMUM || @@ -3711,7 +3561,6 @@ double nmCalculationAutoFitLM::calculateLogLogCurveError( // 整个计算过程均位于 log(time)-log(value) 坐标。 const double invalidLoss = 1.0e10; const double valueFloor = 1.0e-12; - const int numPoints = 80; m_lastObjectiveBreakdown = AutoFitObjectiveBreakdownLM(); if(!validateLogLogData(target) || !validateLogLogData(result)) { @@ -3849,11 +3698,15 @@ double nmCalculationAutoFitLM::calculateLogLogCurveError( return invalidLoss; } + // 所有指标共用每个对数时间数量级 20 个间隔,向上取整并包含两端,至少三个点。 + // 比较区间在本轮固定,因此点数也固定;微小容差避免整数量级因舍入多取一点。 + const double timeDecades = (qLn(overlapMaxX) - qLn(overlapMinX)) / qLn(10.0); + const int numPoints = qMax(3, qCeil(timeDecades * kAutoFitIntervalsPerDecade - 1.0e-10) + 1); auto populateStageMetrics = [&](AutoFitObjectiveBreakdownLM* objective) -> bool { - // 81 个固定对数时间点只用于插值评价,不增加求解点数或 DLL 调用。 - // 斜率用跨度为全时域 10% 的差分,避免相邻点噪声;两条曲线等权。 - const int count = 81; - const int lag = 8; + // 阶段指标沿用相同网格,仅做插值评价,不增加求解点数或 DLL 调用。 + // 斜率跨度保持约为全对数时域的 10%,压力和导数仍等权。 + const int count = numPoints; + const int lag = autoFitShapeLag(count); const double span = qLn(overlapMaxX) - qLn(overlapMinX); QVector residuals[2]; QVector targetLogs[2], resultLogs[2]; @@ -3896,87 +3749,6 @@ double nmCalculationAutoFitLM::calculateLogLogCurveError( return isFiniteNumber(objective->shapeLoss); }; - if(m_layeredSampling) { - // 完整基准只取公共范围内的目标原始时间点;模拟点数不改变评价标准。 - QVector times; - QVector pressureResidual; - QVector derivativeResidual; - for(int i = 0; i < targetPressure.size(); ++i) { - const double time = targetPressure[i].x(); - if(time < overlapMinX || time > overlapMaxX) { - continue; - } - double pressure = 0.0; - double derivative = 0.0; - if(!interpolateLogValue(resultPressure, time, &pressure) || - !interpolateLogValue(resultDerivative, time, &derivative)) { - return invalidLoss; - } - times.append(time); - pressureResidual.append(pressure - qLn(qMax(targetPressure[i].y(), valueFloor))); - derivativeResidual.append(derivative - qLn(targetDerivative[i].y())); - } - if(times.size() < 3) { - return invalidLoss; - } - overlapMinX = times.first(); - overlapMaxX = times.last(); - QVector coordinates; - const double logMin = qLn(overlapMinX); - const double logSpan = qLn(overlapMaxX) - logMin; - for(int i = 0; i < times.size(); ++i) { - coordinates.append((qLn(times[i]) - logMin) / logSpan); - } - - // 数据较少时直接全量。补点只引用原始目标点,且各层共享同一组锚点。 - const int stride = times.size() <= 41 ? 1 : m_samplingStride; - const QVector indices = autoFitSamplingIndices(coordinates, stride); - const QVector fullWeights = autoFitLogTimeWeights(coordinates); - QVector layerCoordinates; - for(int i = 0; i < indices.size(); ++i) { - layerCoordinates.append(coordinates[indices[i]]); - } - const QVector layerWeights = autoFitLogTimeWeights(layerCoordinates); - AutoFitObjectiveBreakdownLM breakdown; - breakdown.sampleCoordinates = layerCoordinates; - breakdown.samplingStride = stride; - breakdown.fullPointCount = times.size(); - double pressureEnergy = 0.0; - double derivativeEnergy = 0.0; - for(int i = 0; i < times.size(); ++i) { - pressureEnergy += fullWeights[i] * pressureResidual[i] * pressureResidual[i]; - derivativeEnergy += fullWeights[i] * derivativeResidual[i] * derivativeResidual[i]; - } - breakdown.pressureLoss = qSqrt(pressureEnergy); - breakdown.derivativeLoss = qSqrt(derivativeEnergy); - breakdown.total = qSqrt(0.5 * (pressureEnergy + derivativeEnergy)); - for(int component = 0; component < 2; ++component) { - for(int i = 0; i < indices.size(); ++i) { - const double residual = component == 0 - ? pressureResidual[indices[i]] : derivativeResidual[indices[i]]; - breakdown.residualVector.append(qSqrt(0.5 * layerWeights[i]) * residual); - } - } - breakdown.layerError = qSqrt(trustRegionSquaredNorm(breakdown.residualVector)); - breakdown.valid = isFiniteNumber(breakdown.total) && breakdown.total < 1.0e9; - if(!populateStageMetrics(&breakdown)) return invalidLoss; - if(!trustRegionResidualsValid(breakdown)) { - return invalidLoss; - } - breakdown.timeWindows = calculateAutoFitTimeWindows( - breakdown.residualVector, overlapMinX, overlapMaxX, - layerCoordinates, layerWeights); - m_lastObjectiveBreakdown = breakdown; - // 首次完整评价有效后再冻结区间和实际层级,失败候选不能改变基准。 - m_samplingStride = stride; - if(!comparisonRangeFixed) { - m_comparisonTimeMin = overlapMinX; - m_comparisonTimeMax = overlapMaxX; - writeTraceMetaFile(); - } - return breakdown.total; - } - QVector commonX(numPoints); QVector commonLogX(numPoints); QVector targetLogPressure(numPoints); @@ -3984,7 +3756,7 @@ double nmCalculationAutoFitLM::calculateLogLogCurveError( const double comparisonLogMinX = qLn(overlapMinX); const double comparisonLogMaxX = qLn(overlapMaxX); - // 在公共时间范围内生成固定维度的 log-time 网格,保持 LM 残差向量为 160 维。 + // 在公共时间范围内生成等距 log-time 网格,压力和导数各使用 numPoints 个残差。 for(int i = 0; i < numPoints; ++i) { double logX = comparisonLogMinX + static_cast(i) * @@ -4599,7 +4371,6 @@ double nmCalculationAutoFitLM::calculateLogLogCurveError( breakdown.total = qSqrt( 0.5 * breakdown.pressureLoss * breakdown.pressureLoss + 0.5 * breakdown.derivativeLoss * breakdown.derivativeLoss); - breakdown.layerError = breakdown.total; breakdown.valid = isFiniteNumber(breakdown.total) && breakdown.total >= 0.0; diff --git a/Src/nmNum/nmSubWxs/nmWxAutomaticFitting.cpp b/Src/nmNum/nmSubWxs/nmWxAutomaticFitting.cpp index 9204f0e5..9ba34c6d 100644 --- a/Src/nmNum/nmSubWxs/nmWxAutomaticFitting.cpp +++ b/Src/nmNum/nmSubWxs/nmWxAutomaticFitting.cpp @@ -729,13 +729,6 @@ void nmWxAutomaticFitting::setupControlPanel() m_surrogateCombo->setCurrentIndex(automaticFittingData.getSurrogateScreeningEnabled() ? 1 : 0); m_surrogateCombo->setMaximumWidth(160); m_surrogateCombo->setMinimumWidth(160); - // 分层采样用于 LM 对比试验,每次打开默认使用原来的固定 80 点模式。 - m_samplingLabel = new QLabel(tr("LM sampling:")); - m_samplingCombo = new QComboBox(); - m_samplingCombo->addItem(tr("Fixed sampling (80 points)")); - m_samplingCombo->addItem(tr("Layered target sampling")); - m_samplingCombo->setMinimumWidth(180); - m_samplingCombo->setToolTip(tr("Layered sampling uses target-point subsets for directions and all valid target points for acceptance.")); connect(m_algorithmCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(onAlgorithmChanged(int))); onAlgorithmChanged(m_algorithmCombo->currentIndex()); @@ -793,10 +786,6 @@ void nmWxAutomaticFitting::setupControlPanel() m_controlLayout->addWidget(m_surrogateCombo); m_controlLayout->addSpacing(15); - m_controlLayout->addWidget(m_samplingLabel); - m_controlLayout->addWidget(m_samplingCombo); - m_controlLayout->addSpacing(15); - m_controlLayout->addWidget(iterationLabel); m_controlLayout->addWidget(m_iterationEdit); m_controlLayout->addSpacing(15); @@ -818,8 +807,6 @@ void nmWxAutomaticFitting::onAlgorithmChanged(int index) const bool usePSO = (index == 0); m_surrogateLabel->setEnabled(usePSO); m_surrogateCombo->setEnabled(usePSO); - m_samplingLabel->setEnabled(!usePSO); - m_samplingCombo->setEnabled(!usePSO); } void nmWxAutomaticFitting::setupButtons() @@ -1207,7 +1194,6 @@ void nmWxAutomaticFitting::startAutoFitting(const QVector>& targ m_autoFitterLM = new nmCalculationAutoFitLM(this); m_autoFitterLM->setTargetLogLogData(targetData); m_autoFitterLM->setTargetWellName(targetWellName); - m_autoFitterLM->setLayeredSamplingEnabled(m_samplingCombo->currentIndex() == 1); } else { DEBUG_UI("Creating PSO auto fitter"); m_autoFitterPSO = new nmCalculationAutoFitPSO(this);