|
|
#include "nmCalculationAutoFitLM.h"
|
|
|
#include "nmCalculationDllPebiSolverTask.h"
|
|
|
#include "nmCalculationUtils.h"
|
|
|
#include "nmDataAnalyzeManager.h"
|
|
|
#include "nmDataWellBase.h"
|
|
|
#include "nmDataVerticalFracturedWell.h"
|
|
|
#include "nmDataHorizontalFracturedWell.h"
|
|
|
#include "nmDataReservoir.h"
|
|
|
#include "nmDataAutomaticFitting.h"
|
|
|
|
|
|
#include <QApplication>
|
|
|
#include <QTime>
|
|
|
#include <QDir>
|
|
|
#include <QTextStream>
|
|
|
#include <QFileInfo>
|
|
|
#include <QDateTime>
|
|
|
#include <QtCore/qmath.h>
|
|
|
#include <cmath>
|
|
|
#include <algorithm>
|
|
|
#include <limits>
|
|
|
|
|
|
#ifdef Q_OS_WIN
|
|
|
#include <windows.h>
|
|
|
#include <float.h>
|
|
|
#define DEBUG_OUT(msg) OutputDebugStringA(QString("[AutoFitLM] %1\n").arg(msg).toLocal8Bit().data())
|
|
|
#endif
|
|
|
|
|
|
// 诊断元数据记录每个对数时间十倍区间的采样数,与 LM 模块的误差采样一致。
|
|
|
static const int kAutoFitIntervalsPerDecade = 20;
|
|
|
|
|
|
static inline bool isFiniteNumber(double value)
|
|
|
{
|
|
|
#ifdef Q_OS_WIN
|
|
|
return _finite(value) != 0;
|
|
|
#else
|
|
|
return std::isfinite(value);
|
|
|
#endif
|
|
|
}
|
|
|
|
|
|
static inline void msleep(int ms)
|
|
|
{
|
|
|
#ifdef Q_OS_WIN
|
|
|
Sleep(ms);
|
|
|
#else
|
|
|
Q_UNUSED(ms);
|
|
|
#endif
|
|
|
}
|
|
|
|
|
|
static QString csvEscape(const QString& text)
|
|
|
{
|
|
|
QString escaped = text;
|
|
|
escaped.replace("\"", "\"\"");
|
|
|
return QString("\"%1\"").arg(escaped);
|
|
|
}
|
|
|
|
|
|
static QString traceNumber(double value)
|
|
|
{
|
|
|
return isFiniteNumber(value) ? QString::number(value, 'g', 17) : QString();
|
|
|
}
|
|
|
|
|
|
static QString traceParamAt(const QVector<double>& params, int index)
|
|
|
{
|
|
|
return (index >= 0 && index < params.size()) ? traceNumber(params[index]) : QString();
|
|
|
}
|
|
|
|
|
|
static QString jsonEscape(const QString& text)
|
|
|
{
|
|
|
QString escaped = text;
|
|
|
escaped.replace("\\", "\\\\");
|
|
|
escaped.replace("\"", "\\\"");
|
|
|
escaped.replace("\b", "\\b");
|
|
|
escaped.replace("\f", "\\f");
|
|
|
escaped.replace("\n", "\\n");
|
|
|
escaped.replace("\r", "\\r");
|
|
|
escaped.replace("\t", "\\t");
|
|
|
return QString("\"%1\"").arg(escaped);
|
|
|
}
|
|
|
|
|
|
static QString jsonNumber(double value)
|
|
|
{
|
|
|
return isFiniteNumber(value) ? QString::number(value, 'g', 17) : QString("null");
|
|
|
}
|
|
|
|
|
|
static QString jsonDoubleArray(const QVector<double>& values)
|
|
|
{
|
|
|
QStringList items;
|
|
|
for(int i = 0; i < values.size(); ++i) {
|
|
|
items << jsonNumber(values[i]);
|
|
|
}
|
|
|
return QString("[%1]").arg(items.join(","));
|
|
|
}
|
|
|
|
|
|
static QString jsonIntArray(const QVector<int>& values)
|
|
|
{
|
|
|
QStringList items;
|
|
|
for(int i = 0; i < values.size(); ++i) {
|
|
|
items << QString::number(values[i]);
|
|
|
}
|
|
|
return QString("[%1]").arg(items.join(","));
|
|
|
}
|
|
|
|
|
|
static QString jsonBoolArray(const QVector<bool>& values)
|
|
|
{
|
|
|
QStringList items;
|
|
|
for(int i = 0; i < values.size(); ++i) {
|
|
|
items << (values[i] ? "true" : "false");
|
|
|
}
|
|
|
return QString("[%1]").arg(items.join(","));
|
|
|
}
|
|
|
|
|
|
static QString jsonStringArray(const QStringList& values)
|
|
|
{
|
|
|
QStringList items;
|
|
|
for(int i = 0; i < values.size(); ++i) {
|
|
|
items << jsonEscape(values[i]);
|
|
|
}
|
|
|
return QString("[%1]").arg(items.join(","));
|
|
|
}
|
|
|
|
|
|
// 诊断文件按固定顺序记录各类物理参数。
|
|
|
static QStringList traceParameterNames()
|
|
|
{
|
|
|
QStringList names;
|
|
|
names << "k"
|
|
|
<< "skin"
|
|
|
<< "wellboreC"
|
|
|
<< "phi"
|
|
|
<< "Dfc"
|
|
|
<< "fractureHalfLength";
|
|
|
return names;
|
|
|
}
|
|
|
|
|
|
nmCalculationAutoFitLM::nmCalculationAutoFitLM(QObject* parent)
|
|
|
: QObject(parent), m_engine(new nmFitLM(this)), m_isRunning(false), m_shouldStop(false), m_isFinalizing(false),
|
|
|
m_currentIteration(-1), m_globalBestFitness(1e10), m_maxIterations(100), m_targetError(0.001),
|
|
|
m_totalEvaluations(0), m_successfulEvaluations(0), m_evaluationInProgress(0), m_userInitialFitness(1e10),
|
|
|
m_solverCallCount(0), m_skipShapeStage(false), m_sensitivitySettings(nullptr), m_sensitivityVerticalWell(false)
|
|
|
{
|
|
|
connect(m_engine, SIGNAL(logMessageGenerated(QString)), this, SIGNAL(logMessageGenerated(QString)));
|
|
|
connect(m_engine, SIGNAL(progressUpdated(int, double)), this, SIGNAL(progressUpdated(int, double)));
|
|
|
connect(m_engine, SIGNAL(bestCurveUpdated(QVector<QVector<double>>, QVector<QVector<double>>, int, double)), this,
|
|
|
SIGNAL(bestCurveUpdated(QVector<QVector<double>>, QVector<QVector<double>>, int, double)));
|
|
|
connect(m_engine, SIGNAL(runInitialized()), this, SLOT(initializeTraceFile()), Qt::DirectConnection);
|
|
|
connect(m_engine, SIGNAL(fittingStageChanged(int)), this, SIGNAL(fittingStageChanged(int)));
|
|
|
connect(m_engine, SIGNAL(comparisonRangeChanged()), this, SLOT(writeTraceMetaFile()), Qt::DirectConnection);
|
|
|
connect(m_engine,
|
|
|
SIGNAL(traceRowGenerated(int, int, QString, QVector<double>, double, bool, int, QString,
|
|
|
const AutoFitObjectiveBreakdownLM*)),
|
|
|
this,
|
|
|
SLOT(writeTraceRow(int, int, QString, QVector<double>, double, bool, int, QString,
|
|
|
const AutoFitObjectiveBreakdownLM*)),
|
|
|
Qt::DirectConnection);
|
|
|
|
|
|
// 单次运行目录在输入校验通过后创建,避免只打开界面也产生临时文件。
|
|
|
DEBUG_OUT("LM automatic fitting calculator initialized");
|
|
|
}
|
|
|
|
|
|
// 请求停止并限时等待,然后关闭轨迹文件、清理临时目录和信号连接。
|
|
|
// 等待超时后仅清除运行标志,不代表外层同步调用已经退出。
|
|
|
nmCalculationAutoFitLM::~nmCalculationAutoFitLM()
|
|
|
{
|
|
|
if(m_isRunning) {
|
|
|
m_shouldStop = true;
|
|
|
int waitCount = 0;
|
|
|
while(m_isRunning && waitCount < 100) {
|
|
|
QApplication::processEvents(QEventLoop::ExcludeUserInputEvents, 50);
|
|
|
msleep(50);
|
|
|
waitCount++;
|
|
|
}
|
|
|
if(m_isRunning) {
|
|
|
DEBUG_OUT("Force stopping LM fitting after timeout");
|
|
|
m_isRunning = false;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
closeTraceFile();
|
|
|
cleanupTemporaryDirectory();
|
|
|
disconnect(this, nullptr, nullptr, nullptr);
|
|
|
}
|
|
|
|
|
|
// ==================== 临时目录工具 ====================
|
|
|
// 真实求解器和井曲线 CSV 共用一个受控的单次运行目录。创建失败时不允许
|
|
|
// 回退到程序目录,否则后续递归清理可能删除安装文件。
|
|
|
bool nmCalculationAutoFitLM::initializeTemporaryDirectory()
|
|
|
{
|
|
|
// 敏感性任务由自身的冻结输入评价,不能写回当前项目。
|
|
|
if(m_sensitivitySettings)
|
|
|
return true;
|
|
|
nmCalculationUtils::cleanupStaleAutoFitTemporaryDirectories();
|
|
|
m_tempDirectory = nmCalculationUtils::createAutoFitTemporaryDirectory();
|
|
|
if(m_tempDirectory.isEmpty()) {
|
|
|
DEBUG_OUT("Failed to create LM auto-fit temporary directory");
|
|
|
return false;
|
|
|
}
|
|
|
|
|
|
m_traceRunId = QFileInfo(m_tempDirectory).fileName();
|
|
|
DEBUG_OUT(QString("Initialized temp directory: %1").arg(m_tempDirectory));
|
|
|
return true;
|
|
|
}
|
|
|
|
|
|
void nmCalculationAutoFitLM::cleanupTemporaryDirectory()
|
|
|
{
|
|
|
if(m_tempDirectory.isEmpty()) {
|
|
|
return;
|
|
|
}
|
|
|
const QString directoryPath = m_tempDirectory;
|
|
|
m_tempDirectory.clear();
|
|
|
if(nmCalculationUtils::removeAutoFitTemporaryDirectory(directoryPath)) {
|
|
|
DEBUG_OUT("Temp directory cleaned up successfully");
|
|
|
} else {
|
|
|
DEBUG_OUT(QString("Failed to clean auto-fit temporary directory: %1").arg(directoryPath));
|
|
|
}
|
|
|
}
|
|
|
|
|
|
// ==================== 公共接口方法 ====================
|
|
|
|
|
|
void nmCalculationAutoFitLM::initializeTraceFile()
|
|
|
{
|
|
|
syncAlgorithmProgress();
|
|
|
// 敏感性任务由自身的冻结输入评价,不能写回当前项目。
|
|
|
if(m_sensitivitySettings)
|
|
|
return;
|
|
|
closeTraceFile();
|
|
|
m_traceFilePath.clear();
|
|
|
m_traceMetaFilePath.clear();
|
|
|
|
|
|
// 诊断轨迹在所有构建中启用,并与源码、安装目录完全分离。
|
|
|
if(m_traceRunId.isEmpty()) {
|
|
|
m_traceRunId = QString("%1-%2")
|
|
|
.arg(QString::number(QCoreApplication::applicationPid()))
|
|
|
.arg(QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss_zzz"));
|
|
|
}
|
|
|
QDir traceDir(QDir(QDir::tempPath()).absoluteFilePath("WTAI/AutoFitTrace/LM"));
|
|
|
|
|
|
if(!traceDir.exists() && !QDir().mkpath(traceDir.absolutePath())) {
|
|
|
DEBUG_OUT(QString("Failed to create LM trace directory: %1").arg(traceDir.absolutePath()));
|
|
|
m_traceFilePath.clear();
|
|
|
m_traceMetaFilePath.clear();
|
|
|
return;
|
|
|
}
|
|
|
|
|
|
m_traceFilePath = traceDir.absoluteFilePath(QString("lm_trust_region_trace_%1.csv").arg(m_traceRunId));
|
|
|
m_traceMetaFilePath = traceDir.absoluteFilePath(QString("lm_trust_region_trace_%1.meta.json").arg(m_traceRunId));
|
|
|
m_traceFile.setFileName(m_traceFilePath);
|
|
|
|
|
|
if(!m_traceFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
|
|
|
DEBUG_OUT(QString("Failed to open LM trace file: %1").arg(m_traceFilePath));
|
|
|
m_traceFilePath.clear();
|
|
|
m_traceMetaFilePath.clear();
|
|
|
return;
|
|
|
}
|
|
|
|
|
|
writeTraceHeader();
|
|
|
writeTraceMetaFile();
|
|
|
DEBUG_OUT(tr("LM fitting trace: %1").arg(m_traceFilePath));
|
|
|
if(!m_traceMetaFilePath.isEmpty()) {
|
|
|
DEBUG_OUT(tr("LM fitting trace metadata: %1").arg(m_traceMetaFilePath));
|
|
|
}
|
|
|
}
|
|
|
|
|
|
void nmCalculationAutoFitLM::closeTraceFile()
|
|
|
{
|
|
|
if(m_traceFile.isOpen()) {
|
|
|
m_traceFile.flush();
|
|
|
m_traceFile.close();
|
|
|
}
|
|
|
}
|
|
|
|
|
|
void nmCalculationAutoFitLM::writeTraceHeader()
|
|
|
{
|
|
|
if(!m_traceFile.isOpen()) {
|
|
|
return;
|
|
|
}
|
|
|
|
|
|
QStringList cols;
|
|
|
cols << "run_id"
|
|
|
<< "iteration"
|
|
|
<< "parameter_index"
|
|
|
<< "phase"
|
|
|
<< "k"
|
|
|
<< "skin"
|
|
|
<< "wellboreC"
|
|
|
<< "phi"
|
|
|
<< "Dfc"
|
|
|
<< "fractureHalfLength"
|
|
|
<< "solver_objective"
|
|
|
<< "solver_success"
|
|
|
<< "elapsed_ms"
|
|
|
<< "decision"
|
|
|
<< "enabled_param_indices"
|
|
|
<< "pressure_loss"
|
|
|
<< "derivative_loss"
|
|
|
<< "vertical_common_bias"
|
|
|
<< "vertical_loss"
|
|
|
<< "vertical_reliable"
|
|
|
<< "horizontal_physical_shift"
|
|
|
<< "horizontal_loss"
|
|
|
<< "horizontal_reliable"
|
|
|
<< "shape_loss"
|
|
|
<< "registration_ambiguous";
|
|
|
|
|
|
cols << "sampling_mode" << "sampling_points"
|
|
|
<< "pressure_vertical_bias" << "derivative_vertical_bias";
|
|
|
QTextStream out(&m_traceFile);
|
|
|
out << cols.join(",") << "\n";
|
|
|
}
|
|
|
|
|
|
void nmCalculationAutoFitLM::writeTraceMetaFile()
|
|
|
{
|
|
|
if(m_traceMetaFilePath.isEmpty()) {
|
|
|
return;
|
|
|
}
|
|
|
|
|
|
QFile metaFile(m_traceMetaFilePath);
|
|
|
if(!metaFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
|
|
|
DEBUG_OUT(QString("Failed to open LM trace meta file: %1").arg(m_traceMetaFilePath));
|
|
|
m_traceMetaFilePath.clear();
|
|
|
return;
|
|
|
}
|
|
|
|
|
|
QStringList parameterNames = traceParameterNames();
|
|
|
QStringList enabledNames;
|
|
|
for(int i = 0; i < m_enabledParamIndices.size(); ++i) {
|
|
|
int paramIndex = m_enabledParamIndices[i];
|
|
|
enabledNames << m_modelParameters[paramIndex].name();
|
|
|
}
|
|
|
|
|
|
QVector<double> initialFullParams = buildTraceParameterVector(m_initialValues);
|
|
|
QVector<double> targetTime = m_targetLogLogData.size() > 0 ? m_targetLogLogData[0] : QVector<double>();
|
|
|
QVector<double> targetPressure = m_targetLogLogData.size() > 1 ? m_targetLogLogData[1] : QVector<double>();
|
|
|
QVector<double> targetDerivative = m_targetLogLogData.size() > 2 ? m_targetLogLogData[2] : QVector<double>();
|
|
|
|
|
|
QTextStream out(&metaFile);
|
|
|
out << "{\n";
|
|
|
out << " \"schema_version\": 56,\n";
|
|
|
out << " \"strategy\": \"permeability_height_then_joint_lm_total_for_vertical_well_else_shape_then_total\",\n";
|
|
|
out << " \"height_acceptance\": \"reliable_vertical_loss_decrease; no_shape_or_total_loss_constraint\",\n";
|
|
|
out << " \"shape_metric\": "
|
|
|
"\"pressure_and_derivative_log_slopes_shared_sampling_grid_lag_round_10_percent_min_1\",\n";
|
|
|
out << " \"shape_parameter_selection\": \"all_valid_free_columns_joint_LM; "
|
|
|
"no_single_parameter_sweep_or_wellbore_recheck\",\n";
|
|
|
out << " \"shape_acceptance\": \"strict_full_shape_loss_decrease; no_total_loss_constraint\",\n";
|
|
|
out << " \"lm_step_policy\": "
|
|
|
"\"same_joint_LM_damping_trust_radius_secant_updates_and_sensitivity_rebuilds_in_both_phases\",\n";
|
|
|
out << " \"lm_phase_switch\": "
|
|
|
"\"shape_target_reached_or_confirmed_stagnation_or_phase_evaluation_budget_exhausted_then_total_if_"
|
|
|
"iterations_remain; shared_iteration_limit_or_user_stop_or_consecutive_solver_failure_abort\",\n";
|
|
|
out << " \"lm_phase_budget\": \"shared_max_iterations_including_height; "
|
|
|
"each_LM_phase_retains_max(dimensions+2,20,3*max_iterations)_evaluations\",\n";
|
|
|
out << " \"lm_effective_improvement\": \"max(0.01,0.10*baseline_stage_error); "
|
|
|
"after_sensitivity_rebuild_reset_baseline_to_accepted_probe_error_if_improved_else_rebuild_start_error; "
|
|
|
"reset_ineffective_count_preserving_stagnation_confirmation; "
|
|
|
"3_ineffective_steps_trigger_stagnation_confirmation\",\n";
|
|
|
out << " \"iteration_count_scope\": \"height_shape_and_total_share_max_iterations; "
|
|
|
"rejected_and_failed_candidates_count; sensitivity_evaluations_are_not_iterations; "
|
|
|
"trace_iteration_is_zero_based_cumulative\",\n";
|
|
|
out << " \"total_stage_shape_constraint\": false,\n";
|
|
|
out << " \"total_parameter_selection\": \"all_valid_free_columns\",\n";
|
|
|
out << " \"skin_difference_policy\": \"local_scale_fraction_0.02_in_both_LM_phases\",\n";
|
|
|
out << " \"difference_policy\": \"coordinate_step_cap_0.04_with_half_trust_radius_in_both_LM_phases\",\n";
|
|
|
out << " \"difference_failure_policy\": \"halve_before_opposite_direction\",\n";
|
|
|
out << " \"trace_type\": \"finite_difference_lm_trust_region\",\n";
|
|
|
out << " \"run_id\": " << jsonEscape(m_traceRunId) << ",\n";
|
|
|
out << " \"created_at\": " << jsonEscape(QDateTime::currentDateTime().toString(Qt::ISODate)) << ",\n";
|
|
|
out << " \"trace_csv\": " << jsonEscape(QFileInfo(m_traceFilePath).fileName()) << ",\n";
|
|
|
out << " \"sampling_mode\": " << 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";
|
|
|
out << " \"pressure\": " << jsonDoubleArray(targetPressure) << ",\n";
|
|
|
out << " \"derivative\": " << jsonDoubleArray(targetDerivative) << "\n";
|
|
|
out << " },\n";
|
|
|
out << " \"lm\": {\n";
|
|
|
out << " \"max_iterations\": " << m_maxIterations << ",\n";
|
|
|
out << " \"target_error\": " << jsonNumber(m_targetError) << "\n";
|
|
|
out << " },\n";
|
|
|
// 区间尚未冻结时写 null;首次有效评价后记录固定的误差比较范围。
|
|
|
out << " \"comparison_time_range\": {\n";
|
|
|
out << " \"comparison_time_min\": "
|
|
|
<< (m_engine->getComparisonTimeMin() > 0.0 ? jsonNumber(m_engine->getComparisonTimeMin()) : QString("null"))
|
|
|
<< ",\n";
|
|
|
out << " \"comparison_time_max\": "
|
|
|
<< (m_engine->getComparisonTimeMax() > 0.0 ? jsonNumber(m_engine->getComparisonTimeMax()) : QString("null"))
|
|
|
<< "\n";
|
|
|
out << " },\n";
|
|
|
out << " \"parameters\": {\n";
|
|
|
out << " \"names\": " << jsonStringArray(parameterNames) << ",\n";
|
|
|
out << " \"enabled_indices\": " << jsonIntArray(m_enabledParamIndices) << ",\n";
|
|
|
out << " \"enabled_names\": " << jsonStringArray(enabledNames) << ",\n";
|
|
|
out << " \"selected_flags\": " << jsonBoolArray(m_parameterSelected) << ",\n";
|
|
|
out << " \"lower\": " << jsonDoubleArray(m_parameterLower) << ",\n";
|
|
|
out << " \"upper\": " << jsonDoubleArray(m_parameterUpper) << ",\n";
|
|
|
out << " \"initial_selected\": " << jsonDoubleArray(m_initialValues) << ",\n";
|
|
|
out << " \"initial_full\": " << jsonDoubleArray(initialFullParams) << "\n";
|
|
|
out << " }\n";
|
|
|
out << "}\n";
|
|
|
metaFile.flush();
|
|
|
metaFile.close();
|
|
|
}
|
|
|
|
|
|
void nmCalculationAutoFitLM::writeTraceRow(int iteration, int parameterIndex, const QString& phase,
|
|
|
const QVector<double>& parameters, double solverObjective,
|
|
|
bool solverSuccess, int elapsedMs, const QString& decision,
|
|
|
const AutoFitObjectiveBreakdownLM* objectiveBreakdown)
|
|
|
{
|
|
|
syncAlgorithmProgress();
|
|
|
if(!m_traceFile.isOpen()) {
|
|
|
return;
|
|
|
}
|
|
|
|
|
|
QVector<double> fullParams = buildTraceParameterVector(parameters);
|
|
|
QStringList enabledIndices;
|
|
|
for(int i = 0; i < m_enabledParamIndices.size(); ++i) {
|
|
|
enabledIndices << QString::number(m_enabledParamIndices[i]);
|
|
|
}
|
|
|
|
|
|
QStringList cols;
|
|
|
cols << csvEscape(m_traceRunId) << QString::number(iteration) << QString::number(parameterIndex)
|
|
|
<< csvEscape(phase);
|
|
|
for(int i = 0; i < 6; ++i) {
|
|
|
cols << traceParamAt(fullParams, i);
|
|
|
}
|
|
|
cols << traceNumber(solverObjective) << QString::number(solverSuccess ? 1 : 0) << QString::number(elapsedMs)
|
|
|
<< csvEscape(decision) << csvEscape(enabledIndices.join(";"));
|
|
|
|
|
|
if(objectiveBreakdown && objectiveBreakdown->valid) {
|
|
|
cols << traceNumber(objectiveBreakdown->pressureLoss) << traceNumber(objectiveBreakdown->derivativeLoss)
|
|
|
<< traceNumber(objectiveBreakdown->verticalCommonBias) << traceNumber(objectiveBreakdown->verticalLoss)
|
|
|
<< QString::number(objectiveBreakdown->verticalReliable ? 1 : 0)
|
|
|
<< traceNumber(objectiveBreakdown->horizontalPhysicalShift)
|
|
|
<< traceNumber(objectiveBreakdown->horizontalLoss)
|
|
|
<< QString::number(objectiveBreakdown->horizontalReliable ? 1 : 0)
|
|
|
<< traceNumber(objectiveBreakdown->shapeLoss)
|
|
|
<< QString::number(objectiveBreakdown->registrationAmbiguous ? 1 : 0);
|
|
|
} else {
|
|
|
for(int i = 0; i < 10; ++i) {
|
|
|
cols << QString();
|
|
|
}
|
|
|
}
|
|
|
|
|
|
cols << "log_uniform_per_decade"
|
|
|
<< (objectiveBreakdown ? QString::number(objectiveBreakdown->residualVector.size() / 2) : QString())
|
|
|
<< (objectiveBreakdown ? traceNumber(objectiveBreakdown->pressureVerticalBias) : QString())
|
|
|
<< (objectiveBreakdown ? traceNumber(objectiveBreakdown->derivativeVerticalBias) : QString());
|
|
|
QTextStream out(&m_traceFile);
|
|
|
out << cols.join(",") << "\n";
|
|
|
m_traceFile.flush();
|
|
|
}
|
|
|
|
|
|
// 拟合界面统一显示普通小数;失败评价不展示惩罚值或非有限数。
|
|
|
static QString lmLogError(double value)
|
|
|
{
|
|
|
return isFiniteNumber(value) && value < 1.0e9 ? QString::number(value, 'f', 6) : QString("--");
|
|
|
}
|
|
|
|
|
|
void nmCalculationAutoFitLM::emitRunSummary(bool success, StopReasonLM finalReason)
|
|
|
{
|
|
|
// 最终只汇总总误差,耗时由进度窗口在收到结束信号后追加。
|
|
|
emit logMessageGenerated(success ? tr("[Fitting completed]") : tr("[Fitting ended]"));
|
|
|
emit logMessageGenerated(
|
|
|
tr("Stop reason: %1")
|
|
|
.arg(success ? m_engine->getStopReasonDescription(finalReason)
|
|
|
: (m_lastError.isEmpty() ? m_engine->getStopReasonDescription(finalReason) : m_lastError)));
|
|
|
emit logMessageGenerated(
|
|
|
tr("Total error: %1 -> %2").arg(lmLogError(m_userInitialFitness)).arg(lmLogError(m_globalBestFitness)));
|
|
|
emit logMessageGenerated(tr("Solver calls: %1").arg(getSolverCallCount()));
|
|
|
}
|
|
|
|
|
|
QVector<double> nmCalculationAutoFitLM::buildTraceParameterVector(const QVector<double>& selectedParameters) const
|
|
|
{
|
|
|
// 保留原 trace 的六列目标井摘要;多井参数名称和取值另由运行日志及进度界面显示。
|
|
|
// 未启用的参数从当前 DataManager 读取,启用的参数用 selectedParameters 覆盖。
|
|
|
QVector<double> fullParams(6, 0.0);
|
|
|
|
|
|
nmDataAnalyzeManager* dataManager = nmDataAnalyzeManager::getCurrentInstance();
|
|
|
|
|
|
if(dataManager) {
|
|
|
nmDataReservoir reservoirData = dataManager->getReservoirDataCopy();
|
|
|
fullParams[0] = reservoirData.getPermeability().getValue().toDouble();
|
|
|
fullParams[3] = reservoirData.getPorosity().getValue().toDouble();
|
|
|
|
|
|
nmDataWellBase* pTargetWell = dataManager->findWellByName(m_targetWellName);
|
|
|
|
|
|
if(pTargetWell) {
|
|
|
nmDataPerforation* perforation = pTargetWell->getPerforation(0);
|
|
|
if(perforation) {
|
|
|
fullParams[1] = perforation->getSkin().getValue().toDouble();
|
|
|
}
|
|
|
fullParams[2] = pTargetWell->getWellboreStorage().getValue().toDouble();
|
|
|
|
|
|
// Dfc 只存在于两类压裂井,普通井在完整向量中保持为 0。
|
|
|
if(pTargetWell->getWellType() == NM_WELL_MODEL::Vertical_Fractured_Well) {
|
|
|
nmDataVerticalFracturedWell* fracturedWell = dynamic_cast<nmDataVerticalFracturedWell*>(pTargetWell);
|
|
|
if(fracturedWell) {
|
|
|
fullParams[4] = fracturedWell->getDfc().getValue().toDouble();
|
|
|
fullParams[5] = fracturedWell->getFractureHalfLength().getValue().toDouble();
|
|
|
}
|
|
|
} else if(pTargetWell->getWellType() == NM_WELL_MODEL::Horizontal_Fractured_Well) {
|
|
|
nmDataHorizontalFracturedWell* fracturedWell =
|
|
|
dynamic_cast<nmDataHorizontalFracturedWell*>(pTargetWell);
|
|
|
if(fracturedWell) {
|
|
|
fullParams[4] = fracturedWell->getDfc().getValue().toDouble();
|
|
|
fullParams[5] = fracturedWell->getFractureHalfLength().getValue().toDouble();
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
|
|
|
for(int i = 0; i < selectedParameters.size() && i < m_enabledParamIndices.size(); ++i) {
|
|
|
const int index = m_enabledParamIndices[i];
|
|
|
if(!m_modelParameters[index].wellCode.isEmpty() && m_modelParameters[index].wellName != m_targetWellName)
|
|
|
continue;
|
|
|
int paramIndex = m_modelParameters[index].type;
|
|
|
|
|
|
if(paramIndex >= 0 && paramIndex < fullParams.size()) {
|
|
|
fullParams[paramIndex] = selectedParameters[i];
|
|
|
}
|
|
|
}
|
|
|
|
|
|
return fullParams;
|
|
|
}
|
|
|
|
|
|
// ==================== 数据加载方法 ====================
|
|
|
|
|
|
bool nmCalculationAutoFitLM::loadConfiguration()
|
|
|
{
|
|
|
// 统一从 DataManager 加载本次运行所需配置。
|
|
|
// UI 层只负责把用户选择保存到 nmDataAutomaticFitting,本类从这里开始完全数据驱动。
|
|
|
try {
|
|
|
loadOptimizationConfig();
|
|
|
loadParameterBounds();
|
|
|
// 不再回退到旧单井字段,旧配置需要通过设置窗口重新生成参数列表。
|
|
|
if(m_modelParameters.isEmpty()) {
|
|
|
m_lastError = tr("Fitting parameter list is empty. Please configure fitting parameters again.");
|
|
|
return false;
|
|
|
}
|
|
|
m_initialValues.clear();
|
|
|
for(int i = 0; i < m_enabledParamIndices.size(); ++i) {
|
|
|
const nmFitParameterValue& p = m_modelParameters[m_enabledParamIndices[i]];
|
|
|
m_initialValues.append(qBound(p.lower, p.initial, p.upper));
|
|
|
}
|
|
|
return true;
|
|
|
}
|
|
|
catch(...) {
|
|
|
m_lastError = tr("Failed to load configuration from data manager");
|
|
|
return false;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
void nmCalculationAutoFitLM::loadOptimizationConfig()
|
|
|
{
|
|
|
nmDataWellBase* target =
|
|
|
m_sensitivitySettings ? nullptr : nmDataAnalyzeManager::getCurrentInstance()->findWellByName(m_targetWellName);
|
|
|
m_skipShapeStage = m_sensitivitySettings ? m_sensitivityVerticalWell
|
|
|
: target && target->getWellType() == NM_WELL_MODEL::Vertical_Well;
|
|
|
// LM 只读取迭代次数和目标误差,其他数值控制保留在现有算法实现中。
|
|
|
// 敏感性运行只读取确认过的设置,普通拟合保留原来的配置来源。
|
|
|
nmDataAutomaticFitting fittingData =
|
|
|
m_sensitivitySettings ? m_sensitivitySettings->parameters
|
|
|
: nmDataAnalyzeManager::getCurrentInstance()->getAutomaticFittingDataCopy();
|
|
|
|
|
|
m_maxIterations = fittingData.getIterationCount().getValue().toInt();
|
|
|
m_targetError = fittingData.getErrorTolerance().getValue().toDouble();
|
|
|
DEBUG_OUT(QString("Loaded LM config: iterations=%1, error=%2").arg(m_maxIterations).arg(m_targetError));
|
|
|
}
|
|
|
|
|
|
void nmCalculationAutoFitLM::loadParameterBounds()
|
|
|
{
|
|
|
// 参数位置与类型分开,单井和多井统一按列表读取勾选状态及上下界。
|
|
|
const nmDataAutomaticFitting fittingData =
|
|
|
m_sensitivitySettings ? m_sensitivitySettings->parameters
|
|
|
: nmDataAnalyzeManager::getCurrentInstance()->getAutomaticFittingDataCopy();
|
|
|
m_modelParameters = nmConvertFitParameters(fittingData.getModelParameters());
|
|
|
m_parameterSelected.clear();
|
|
|
m_parameterLower.clear();
|
|
|
m_parameterUpper.clear();
|
|
|
m_enabledParamIndices.clear();
|
|
|
for(int i = 0; i < m_modelParameters.size(); ++i) {
|
|
|
const nmFitParameterValue& p = m_modelParameters[i];
|
|
|
m_parameterSelected.append(p.selected);
|
|
|
m_parameterLower.append(p.lower);
|
|
|
m_parameterUpper.append(p.upper);
|
|
|
if(p.selected)
|
|
|
m_enabledParamIndices.append(i);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
// ==================== 自动拟合核心方法 ====================
|
|
|
bool nmCalculationAutoFitLM::startSensitivityFitting(
|
|
|
const nmSensitivityFitSettings& settings,
|
|
|
const std::function<QVector<QVector<double>>(const QVector<double>&)>& evaluate,
|
|
|
const std::function<bool()>& cancelled, bool verticalWell)
|
|
|
{
|
|
|
// 同步复用原算法;返回前释放回调,避免持有任务局部对象。
|
|
|
m_sensitivitySettings = &settings;
|
|
|
m_sensitivityEvaluate = evaluate;
|
|
|
m_sensitivityCancelled = cancelled;
|
|
|
m_sensitivityVerticalWell = verticalWell;
|
|
|
m_targetWellName = settings.targetWell;
|
|
|
const bool succeeded = startAutoFitting();
|
|
|
m_sensitivitySettings = nullptr;
|
|
|
m_sensitivityEvaluate = std::function<QVector<QVector<double>>(const QVector<double>&)>();
|
|
|
m_sensitivityCancelled = std::function<bool()>();
|
|
|
return succeeded;
|
|
|
}
|
|
|
|
|
|
bool nmCalculationAutoFitLM::startAutoFitting()
|
|
|
{
|
|
|
// 软件只准备输入与求解回调;拟合迭代由模块统一执行。
|
|
|
if(m_isRunning) {
|
|
|
m_lastError = tr("Auto fitting is already running");
|
|
|
return false;
|
|
|
}
|
|
|
resetOptimizer();
|
|
|
if(!loadConfiguration())
|
|
|
return false;
|
|
|
if(!initializeTemporaryDirectory()) {
|
|
|
m_lastError = tr("Cannot create the automatic fitting temporary directory");
|
|
|
return false;
|
|
|
}
|
|
|
m_isRunning = true;
|
|
|
nmFitRequest request;
|
|
|
request.parameters = m_modelParameters;
|
|
|
request.targetCurve = m_targetLogLogData;
|
|
|
request.targetWell = m_targetWellName;
|
|
|
request.maxIterations = m_maxIterations;
|
|
|
request.targetError = m_targetError;
|
|
|
request.verticalWell = m_skipShapeStage;
|
|
|
nmFitCallbacks callbacks;
|
|
|
callbacks.processEvents = [this]() { pollEvents(); };
|
|
|
callbacks.restoreParameters = [this](const QVector<double>& values) { applyParametersToDataManager(values); };
|
|
|
const nmFitResult result = m_engine->fit(
|
|
|
request,
|
|
|
[this](const QVector<double>& values, bool retry) -> nmFitCurve { return evaluateCurve(values, retry); },
|
|
|
[this]() -> bool {
|
|
|
if(m_sensitivityCancelled && m_sensitivityCancelled())
|
|
|
m_shouldStop = true;
|
|
|
return m_shouldStop;
|
|
|
},
|
|
|
callbacks);
|
|
|
syncAlgorithmProgress();
|
|
|
m_lastError = result.error;
|
|
|
if(!result.completed) {
|
|
|
m_isRunning = false;
|
|
|
closeTraceFile();
|
|
|
cleanupTemporaryDirectory();
|
|
|
emit fittingFinished(false, m_lastError);
|
|
|
return false;
|
|
|
}
|
|
|
StopReasonLM finalReason = static_cast<StopReasonLM>(result.stopReason);
|
|
|
// 敏感性任务自己用最优参数收尾,不能进入普通拟合的模型回写流程。
|
|
|
if(m_sensitivitySettings) {
|
|
|
m_isRunning = false;
|
|
|
return !m_shouldStop && !m_sensitivityCancelled() && !m_globalBestPosition.isEmpty() &&
|
|
|
m_globalBestFitness < 1.0e9;
|
|
|
}
|
|
|
|
|
|
// 普通拟合只有完整求解并提交快照后才算成功。
|
|
|
bool finalFullSolverSucceeded = false;
|
|
|
bool finalFullSolverExecuted = false;
|
|
|
|
|
|
if(!m_globalBestPosition.isEmpty()) {
|
|
|
try {
|
|
|
// Stop 只结束优化迭代;从这里开始必须用当前最优参数生成并发布正式快照。
|
|
|
m_isFinalizing = true;
|
|
|
emit finalizingStarted();
|
|
|
DEBUG_OUT(tr("Applying optimized parameters to model..."));
|
|
|
applyParametersToDataManager(m_globalBestPosition);
|
|
|
|
|
|
// 裂缝参数会改变网格输入;标记失效后,最终求解任务会基于新快照重建网格。
|
|
|
const bool fractureGridParameterSelected = m_engine->fitsFractureGeometry();
|
|
|
if(fractureGridParameterSelected) {
|
|
|
nmDataAnalyzeManager* dataManager = nmDataAnalyzeManager::getCurrentInstance();
|
|
|
if(!dataManager) {
|
|
|
throw std::runtime_error("Data manager is unavailable");
|
|
|
}
|
|
|
dataManager->invalidatePebiGrid();
|
|
|
}
|
|
|
|
|
|
DEBUG_OUT(tr("Running final full-field calculation with optimized parameters..."));
|
|
|
finalFullSolverExecuted = true;
|
|
|
finalFullSolverSucceeded = runFinalFullSolver();
|
|
|
|
|
|
if(finalFullSolverSucceeded) {
|
|
|
DEBUG_OUT(tr("Final full-field calculation completed successfully"));
|
|
|
} else {
|
|
|
m_lastError = tr("Optimized parameters were found, but the final full-field calculation failed");
|
|
|
DEBUG_OUT(tr("ERROR: Final full-field calculation failed"));
|
|
|
}
|
|
|
|
|
|
DEBUG_OUT(tr("=== Optimization Results ==="));
|
|
|
DEBUG_OUT(tr("Final error: %1").arg(m_globalBestFitness, 0, 'e', 4));
|
|
|
DEBUG_OUT(tr("Total iterations: %1").arg(m_currentIteration + 1));
|
|
|
DEBUG_OUT(
|
|
|
tr("Total evaluations: %1 (successful: %2)").arg(m_totalEvaluations).arg(m_successfulEvaluations));
|
|
|
|
|
|
QString finalParams = tr("Optimized parameters: ");
|
|
|
for(int i = 0; i < m_globalBestPosition.size(); ++i) {
|
|
|
finalParams += QString("[%1]=%2 ").arg(i).arg(m_globalBestPosition[i], 0, 'f', 6);
|
|
|
}
|
|
|
DEBUG_OUT(finalParams);
|
|
|
|
|
|
if(finalFullSolverExecuted && finalFullSolverSucceeded) {
|
|
|
DEBUG_OUT(tr("Parameters and full-field results applied successfully to data manager"));
|
|
|
} else if(!finalFullSolverExecuted) {
|
|
|
DEBUG_OUT(tr("Optimized parameters applied to data manager"));
|
|
|
}
|
|
|
}
|
|
|
catch(const std::exception& e) {
|
|
|
finalFullSolverSucceeded = false;
|
|
|
m_lastError = tr("Failed to apply final parameters: %1").arg(e.what());
|
|
|
DEBUG_OUT(tr("ERROR: Failed to apply final parameters: %1").arg(e.what()));
|
|
|
}
|
|
|
catch(...) {
|
|
|
finalFullSolverSucceeded = false;
|
|
|
m_lastError = tr("Failed to apply final parameters due to unknown error");
|
|
|
DEBUG_OUT(tr("ERROR: Unknown error applying final parameters"));
|
|
|
}
|
|
|
}
|
|
|
|
|
|
m_isFinalizing = false;
|
|
|
m_isRunning = false;
|
|
|
bool success = false;
|
|
|
QString message;
|
|
|
|
|
|
if(finalReason == LM_TARGET_ACHIEVED) {
|
|
|
success = true;
|
|
|
message = QString(tr("Target achieved. Best error: %1, Iterations: %2"))
|
|
|
.arg(m_globalBestFitness, 0, 'e', 4)
|
|
|
.arg(m_currentIteration + 1);
|
|
|
DEBUG_OUT(tr("=== LM AUTOMATIC FITTING SUCCESSFUL ==="));
|
|
|
} else if(finalReason == LM_LOCAL_OPTIMUM) {
|
|
|
success = true;
|
|
|
message = QString(tr("Automatic fitting reached a local optimum. Best error: %1, Iterations: %2"))
|
|
|
.arg(m_globalBestFitness, 0, 'e', 4)
|
|
|
.arg(m_currentIteration + 1);
|
|
|
DEBUG_OUT(tr("=== LM AUTOMATIC FITTING - LOCAL OPTIMUM ==="));
|
|
|
} else if(finalReason == LM_MAX_ITERATIONS) {
|
|
|
success = true;
|
|
|
message = QString(tr("Iteration or evaluation budget reached. Best error: %1, Cumulative iterations: %2"))
|
|
|
.arg(m_globalBestFitness, 0, 'e', 4)
|
|
|
.arg(m_currentIteration + 1);
|
|
|
DEBUG_OUT(tr("=== LM AUTOMATIC FITTING - MAX ITERATIONS ==="));
|
|
|
} else if(finalReason == LM_USER_STOPPED) {
|
|
|
success = true;
|
|
|
message = QString(tr("Stopped by user. Best error: %1, Iterations: %2"))
|
|
|
.arg(m_globalBestFitness, 0, 'e', 4)
|
|
|
.arg(m_currentIteration + 1);
|
|
|
DEBUG_OUT(tr("=== LM AUTOMATIC FITTING STOPPED BY USER ==="));
|
|
|
} else if(finalReason == LM_CONSECUTIVE_FAILURES) {
|
|
|
message = QString(tr("Automatic fitting failed due to consecutive failures. Best error: %1, Iterations: %2"))
|
|
|
.arg(m_globalBestFitness, 0, 'e', 4)
|
|
|
.arg(m_currentIteration + 1);
|
|
|
DEBUG_OUT(tr("=== LM AUTOMATIC FITTING FAILED ==="));
|
|
|
} else {
|
|
|
message = QString(tr("Automatic fitting ended unexpectedly. Best error: %1, Iterations: %2"))
|
|
|
.arg(m_globalBestFitness, 0, 'e', 4)
|
|
|
.arg(m_currentIteration + 1);
|
|
|
DEBUG_OUT(tr("=== LM AUTOMATIC FITTING - UNKNOWN END ==="));
|
|
|
}
|
|
|
|
|
|
if(!finalFullSolverSucceeded) {
|
|
|
success = false;
|
|
|
message = m_lastError;
|
|
|
}
|
|
|
|
|
|
emitRunSummary(success, finalReason);
|
|
|
QApplication::processEvents();
|
|
|
msleep(200);
|
|
|
QApplication::processEvents();
|
|
|
closeTraceFile();
|
|
|
cleanupTemporaryDirectory();
|
|
|
emit fittingFinished(success, message);
|
|
|
return success;
|
|
|
}
|
|
|
|
|
|
nmFitCurve nmCalculationAutoFitLM::evaluateCurve(const QVector<double>& parameters, bool retrySolver)
|
|
|
{
|
|
|
// 应用候选参数并调用求解器,返回本次曲线;误差计算由模块完成。
|
|
|
syncAlgorithmProgress();
|
|
|
const QString funcName = QString("evaluateError[%1]").arg(m_currentIteration);
|
|
|
static int callCount = 0;
|
|
|
callCount++;
|
|
|
m_lastEvaluatedLogLogData.clear();
|
|
|
|
|
|
// 敏感性任务自行提供完整冻结输入,不访问当前项目。
|
|
|
if(m_sensitivitySettings)
|
|
|
return m_sensitivityEvaluate(parameters);
|
|
|
|
|
|
try {
|
|
|
DEBUG_OUT(QString("%1: Call #%2 - Starting evaluation with %3 parameters")
|
|
|
.arg(funcName)
|
|
|
.arg(callCount)
|
|
|
.arg(parameters.size()));
|
|
|
|
|
|
QString paramStr = "Parameters: ";
|
|
|
|
|
|
for(int i = 0; i < parameters.size(); ++i) {
|
|
|
paramStr += QString("[%1]=%2 ").arg(i).arg(parameters[i], 0, 'f', 6);
|
|
|
}
|
|
|
|
|
|
DEBUG_OUT(QString("%1: %2").arg(funcName).arg(paramStr));
|
|
|
|
|
|
// 拦截维度不匹配、非有限数或超出用户范围的参数。
|
|
|
if(!m_engine->validateParameters(parameters)) {
|
|
|
DEBUG_OUT(QString("%1: Call #%2 - VALIDATION FAILED").arg(funcName).arg(callCount));
|
|
|
|
|
|
for(int i = 0; i < parameters.size(); ++i) {
|
|
|
if(!isFiniteNumber(parameters[i])) {
|
|
|
DEBUG_OUT(QString(" -> Param[%1] is NOT finite: %2").arg(i).arg(parameters[i]));
|
|
|
}
|
|
|
|
|
|
if(i < m_enabledParamIndices.size()) {
|
|
|
int paramIndex = m_enabledParamIndices[i];
|
|
|
|
|
|
if(paramIndex >= 0 && paramIndex < m_parameterLower.size()) {
|
|
|
double lower = m_parameterLower[paramIndex];
|
|
|
double upper = m_parameterUpper[paramIndex];
|
|
|
|
|
|
if(parameters[i] < lower) {
|
|
|
DEBUG_OUT(
|
|
|
QString(" -> Param[%1]=%2 < lower bound %3").arg(i).arg(parameters[i]).arg(lower));
|
|
|
}
|
|
|
|
|
|
if(parameters[i] > upper) {
|
|
|
DEBUG_OUT(
|
|
|
QString(" -> Param[%1]=%2 > upper bound %3").arg(i).arg(parameters[i]).arg(upper));
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
|
|
|
return nmFitCurve();
|
|
|
}
|
|
|
|
|
|
DEBUG_OUT(QString("%1: Call #%2 - Parameters validated OK").arg(funcName).arg(callCount));
|
|
|
|
|
|
// 参数写回和求解任务依赖当前数据管理器。
|
|
|
nmDataAnalyzeManager* dataManager = nmDataAnalyzeManager::getCurrentInstance();
|
|
|
|
|
|
if(!dataManager) {
|
|
|
DEBUG_OUT(QString("%1: Call #%2 - DataManager is NULL").arg(funcName).arg(callCount));
|
|
|
return nmFitCurve();
|
|
|
}
|
|
|
|
|
|
DEBUG_OUT(QString("%1: Call #%2 - DataManager OK").arg(funcName).arg(callCount));
|
|
|
|
|
|
// 按勾选顺序将候选值写入储层和目标井。
|
|
|
try {
|
|
|
DEBUG_OUT(QString("%1: Call #%2 - Applying parameters...").arg(funcName).arg(callCount));
|
|
|
applyParametersToDataManager(parameters);
|
|
|
DEBUG_OUT(QString("%1: Call #%2 - Parameters applied successfully").arg(funcName).arg(callCount));
|
|
|
}
|
|
|
catch(const std::exception& e) {
|
|
|
DEBUG_OUT(
|
|
|
QString("%1: Call #%2 - FAILED to apply parameters: %3").arg(funcName).arg(callCount).arg(e.what()));
|
|
|
return nmFitCurve();
|
|
|
}
|
|
|
|
|
|
// Dfc 和裂缝半长属于网格输入。标记网格失效,使下一次任务基于当前参数快照重建。
|
|
|
const bool fractureGridParameterSelected = m_engine->fitsFractureGeometry();
|
|
|
if(fractureGridParameterSelected) {
|
|
|
dataManager->invalidatePebiGrid();
|
|
|
}
|
|
|
|
|
|
// 初始评价失败可重试;LM 候选失败则交给信赖域缩步,不重复相同参数。
|
|
|
QVector<QVector<double>> solverResult;
|
|
|
const int maxRetries = retrySolver ? 2 : 0;
|
|
|
bool solverSuccess = false;
|
|
|
|
|
|
for(int retry = 0; retry <= maxRetries; ++retry) {
|
|
|
if(m_shouldStop) {
|
|
|
DEBUG_OUT(QString("%1: Call #%2 - User stop requested").arg(funcName).arg(callCount));
|
|
|
return nmFitCurve();
|
|
|
}
|
|
|
|
|
|
try {
|
|
|
DEBUG_OUT(QString("%1: Call #%2 - Solver attempt %3/%4")
|
|
|
.arg(funcName)
|
|
|
.arg(callCount)
|
|
|
.arg(retry + 1)
|
|
|
.arg(maxRetries + 1));
|
|
|
|
|
|
if(retry > 0) {
|
|
|
DEBUG_OUT(QString("%1: Call #%2 - Retry delay...").arg(funcName).arg(callCount));
|
|
|
msleep(1000);
|
|
|
}
|
|
|
|
|
|
solverResult = runSolverDll();
|
|
|
|
|
|
if(solverResult.isEmpty()) {
|
|
|
DEBUG_OUT(QString("%1: Call #%2 - Solver returned EMPTY result").arg(funcName).arg(callCount));
|
|
|
} else {
|
|
|
DEBUG_OUT(QString("%1: Call #%2 - Solver returned %3 arrays")
|
|
|
.arg(funcName)
|
|
|
.arg(callCount)
|
|
|
.arg(solverResult.size()));
|
|
|
|
|
|
for(int i = 0; i < solverResult.size(); ++i) {
|
|
|
DEBUG_OUT(QString(" -> Array[%1] size: %2").arg(i).arg(solverResult[i].size()));
|
|
|
}
|
|
|
|
|
|
if(m_engine->validateSolverResult(solverResult)) {
|
|
|
DEBUG_OUT(QString("%1: Call #%2 - Solver result VALIDATED on attempt %3")
|
|
|
.arg(funcName)
|
|
|
.arg(callCount)
|
|
|
.arg(retry + 1));
|
|
|
solverSuccess = true;
|
|
|
break;
|
|
|
} else {
|
|
|
DEBUG_OUT(QString("%1: Call #%2 - Solver result VALIDATION FAILED on attempt %3")
|
|
|
.arg(funcName)
|
|
|
.arg(callCount)
|
|
|
.arg(retry + 1));
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
catch(const std::exception& e) {
|
|
|
DEBUG_OUT(QString("%1: Call #%2 - Solver EXCEPTION on attempt %3: %4")
|
|
|
.arg(funcName)
|
|
|
.arg(callCount)
|
|
|
.arg(retry + 1)
|
|
|
.arg(e.what()));
|
|
|
}
|
|
|
}
|
|
|
|
|
|
if(!solverSuccess) {
|
|
|
DEBUG_OUT(QString("%1: Call #%2 - ALL SOLVER ATTEMPTS FAILED").arg(funcName).arg(callCount));
|
|
|
return nmFitCurve();
|
|
|
}
|
|
|
|
|
|
// 使用求解任务复制的目标井曲线,避免读取其他井或上一候选的共享结果。
|
|
|
QVector<QVector<double>> resultLogLogData = m_lastEvaluatedLogLogData;
|
|
|
|
|
|
try {
|
|
|
if(!m_engine->validateLogLogData(resultLogLogData)) {
|
|
|
DEBUG_OUT(QString("%1: Call #%2 - LogLog data VALIDATION FAILED").arg(funcName).arg(callCount));
|
|
|
|
|
|
return nmFitCurve();
|
|
|
}
|
|
|
|
|
|
DEBUG_OUT(QString("%1: Call #%2 - LogLog data validated, size: %3")
|
|
|
.arg(funcName)
|
|
|
.arg(callCount)
|
|
|
.arg(resultLogLogData[0].size()));
|
|
|
}
|
|
|
catch(const std::exception& e) {
|
|
|
DEBUG_OUT(
|
|
|
QString("%1: Call #%2 - Error getting LogLog data: %3").arg(funcName).arg(callCount).arg(e.what()));
|
|
|
return nmFitCurve();
|
|
|
}
|
|
|
|
|
|
// 目标函数和最优解更新统一由独立算法处理。
|
|
|
return resultLogLogData;
|
|
|
}
|
|
|
catch(const std::exception& e) {
|
|
|
DEBUG_OUT(QString("%1: Call #%2 - TOP-LEVEL EXCEPTION: %3").arg(funcName).arg(callCount).arg(e.what()));
|
|
|
return nmFitCurve();
|
|
|
}
|
|
|
catch(...) {
|
|
|
DEBUG_OUT(QString("%1: Call #%2 - UNKNOWN TOP-LEVEL EXCEPTION").arg(funcName).arg(callCount));
|
|
|
return nmFitCurve();
|
|
|
}
|
|
|
}
|
|
|
|
|
|
// ==================== 参数应用方法 ====================
|
|
|
|
|
|
void nmCalculationAutoFitLM::applyParametersToDataManager(const QVector<double>& parameters)
|
|
|
{
|
|
|
// 敏感性任务由自身的冻结输入评价,不能写回当前项目。
|
|
|
if(m_sensitivitySettings)
|
|
|
return;
|
|
|
if(parameters.size() != getEnabledParameterCount()) {
|
|
|
return;
|
|
|
}
|
|
|
|
|
|
// 写回每项所属井的现有属性,不更换井对象;共用储层参数只更新一次。
|
|
|
nmDataAnalyzeManager* manager = nmDataAnalyzeManager::getCurrentInstance();
|
|
|
nmDataReservoir reservoir = manager->getReservoirDataCopy();
|
|
|
for(int i = 0; i < m_enabledParamIndices.size(); ++i) {
|
|
|
const nmFitParameterValue& p = m_modelParameters[m_enabledParamIndices[i]];
|
|
|
const double value = parameters[i];
|
|
|
if(p.type == 0)
|
|
|
reservoir.getPermeability().setValue(value);
|
|
|
else if(p.type == 3)
|
|
|
reservoir.getPorosity().setValue(value);
|
|
|
else {
|
|
|
nmDataWellBase* well = manager->findWellByCode(p.wellCode);
|
|
|
if(!well)
|
|
|
continue;
|
|
|
if(p.type == 1 && well->getPerforationCount() > 0)
|
|
|
well->getPerforation(0)->getSkin().setValue(value);
|
|
|
else if(p.type == 2)
|
|
|
well->getWellboreStorage().setValue(value);
|
|
|
else if(nmDataVerticalFracturedWell* fractured = dynamic_cast<nmDataVerticalFracturedWell*>(well)) {
|
|
|
if(p.type == 4)
|
|
|
fractured->getDfc().setValue(value);
|
|
|
else if(p.type == 5)
|
|
|
fractured->getFractureHalfLength().setValue(value);
|
|
|
} else if(nmDataHorizontalFracturedWell* fractured = dynamic_cast<nmDataHorizontalFracturedWell*>(well)) {
|
|
|
if(p.type == 4)
|
|
|
fractured->getDfc().setValue(value);
|
|
|
else if(p.type == 5)
|
|
|
fractured->getFractureHalfLength().setValue(value);
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
manager->updateReservoirData(reservoir);
|
|
|
}
|
|
|
|
|
|
// ==================== 验证和处理方法 ====================
|
|
|
|
|
|
QVector<QVector<double>> nmCalculationAutoFitLM::runSolverDll()
|
|
|
{
|
|
|
// DLL 求解器路径。
|
|
|
// 这个函数负责把当前 DataManager 中的项目状态交给底层数值求解器,
|
|
|
// 数值求解仍包含全部计算井,以保留井间干扰;后处理只提取目标井曲线。
|
|
|
//
|
|
|
// 如果这里失败,通常需要优先检查:HX_NWTM.dll、license、网格/井数据是否完整、
|
|
|
// 目标井是否存在,以及 DataManager 中刚写入的参数是否导致求解器异常。
|
|
|
DEBUG_OUT("SOLVER DLL START");
|
|
|
|
|
|
// 创建任务时绑定当前分析,并在当前线程冻结本次求解所需的全部输入。
|
|
|
nmDataAnalyzeManager* dataManager = nmDataAnalyzeManager::getCurrentInstance();
|
|
|
if(!dataManager || m_targetWellName.isEmpty()) {
|
|
|
DEBUG_OUT("Data manager or target well is unavailable");
|
|
|
return QVector<QVector<double>>();
|
|
|
}
|
|
|
|
|
|
if(m_evaluationInProgress > 0) {
|
|
|
DEBUG_OUT("DLL Solver already running, skipping");
|
|
|
return QVector<QVector<double>>();
|
|
|
}
|
|
|
|
|
|
++m_evaluationInProgress;
|
|
|
m_lastEvaluatedLogLogData.clear();
|
|
|
QVector<QVector<double>> result;
|
|
|
nmCalculationDllPebiSolverTask* dllTask = nullptr;
|
|
|
|
|
|
try {
|
|
|
DEBUG_OUT("Creating DLL solver task");
|
|
|
dllTask = new nmCalculationDllPebiSolverTask(m_tempDirectory, dataManager, m_targetWellName);
|
|
|
|
|
|
if(m_shouldStop) {
|
|
|
DEBUG_OUT("Should stop - cleaning up and returning empty result");
|
|
|
delete dllTask;
|
|
|
--m_evaluationInProgress;
|
|
|
return result;
|
|
|
}
|
|
|
|
|
|
DEBUG_OUT("Starting DLL solver execution...");
|
|
|
|
|
|
// 异步执行 DLL 任务。循环等待期间持续 processEvents,保证界面不会完全卡死。
|
|
|
connect(dllTask, SIGNAL(solverInvoked()), this, SLOT(recordSolverCall()), Qt::DirectConnection);
|
|
|
dllTask->start();
|
|
|
|
|
|
// 等待完成。最大等待 1 小时;用户停止使用任务已有的协作取消接口。
|
|
|
const int maxWait = 3600000;
|
|
|
const int checkInterval = 50;
|
|
|
QTime waitTimer;
|
|
|
waitTimer.start();
|
|
|
|
|
|
while(waitTimer.elapsed() < maxWait) {
|
|
|
// 求解完成时立即返回;等待期间每 50 ms 处理停止请求和界面事件。
|
|
|
if(dllTask->wait(checkInterval)) {
|
|
|
DEBUG_OUT("DLL solver task completed");
|
|
|
break;
|
|
|
}
|
|
|
|
|
|
// 等待期间也派发鼠标、键盘事件,让停止按钮能及时登记请求。
|
|
|
QApplication::processEvents(QEventLoop::AllEvents, checkInterval);
|
|
|
|
|
|
if(m_shouldStop) {
|
|
|
// DLL 没有中断接口,返回后丢弃结果,避免强制终止破坏其内部锁。
|
|
|
dllTask->requestCancel();
|
|
|
}
|
|
|
}
|
|
|
|
|
|
if(dllTask->isRunning()) {
|
|
|
DEBUG_OUT("DLL solver task timeout, terminating...");
|
|
|
dllTask->terminate();
|
|
|
dllTask->wait(2000);
|
|
|
|
|
|
delete dllTask;
|
|
|
dllTask = nullptr;
|
|
|
--m_evaluationInProgress;
|
|
|
return result;
|
|
|
}
|
|
|
|
|
|
// 线程结束后检查真实执行结果,防止失败时复用上一候选的旧曲线。
|
|
|
dllTask->wait();
|
|
|
if(m_shouldStop) {
|
|
|
DEBUG_OUT("DLL solver evaluation cancelled by user");
|
|
|
delete dllTask;
|
|
|
dllTask = nullptr;
|
|
|
--m_evaluationInProgress;
|
|
|
return result;
|
|
|
}
|
|
|
if(!dllTask->wasSuccessful()) {
|
|
|
DEBUG_OUT("DLL solver task reported failure");
|
|
|
delete dllTask;
|
|
|
dllTask = nullptr;
|
|
|
--m_evaluationInProgress;
|
|
|
return result;
|
|
|
}
|
|
|
|
|
|
// 任务结束后复制其局部结果,删除任务前不再持有任务内部引用。
|
|
|
QVector<QVector<double>> pressureResult = dllTask->getAutoFitResultPressure();
|
|
|
QVector<QVector<double>> logLogResult = dllTask->getAutoFitResultLogLog();
|
|
|
|
|
|
DEBUG_OUT(QString("DLL result verification - Pressure arrays: %1, LogLog arrays: %2")
|
|
|
.arg(pressureResult.size())
|
|
|
.arg(logLogResult.size()));
|
|
|
|
|
|
if(pressureResult.size() >= 2) {
|
|
|
DEBUG_OUT(QString("Pressure result - Time points: %1, Pressure points: %2")
|
|
|
.arg(pressureResult[0].size())
|
|
|
.arg(pressureResult[1].size()));
|
|
|
|
|
|
if(pressureResult[0].size() > 0) {
|
|
|
DEBUG_OUT(QString("Sample pressure data - Time[0]: %1, Time[last]: %2, P[0]: %3, P[last]: %4")
|
|
|
.arg(pressureResult[0][0])
|
|
|
.arg(pressureResult[0][pressureResult[0].size() - 1])
|
|
|
.arg(pressureResult[1][0])
|
|
|
.arg(pressureResult[1][pressureResult[1].size() - 1]));
|
|
|
}
|
|
|
}
|
|
|
|
|
|
if(pressureResult.size() >= 2 && pressureResult[0].size() > 0 && pressureResult[1].size() > 0 &&
|
|
|
m_engine->validateLogLogData(logLogResult)) {
|
|
|
result = pressureResult;
|
|
|
m_lastEvaluatedLogLogData = logLogResult;
|
|
|
DEBUG_OUT(QString("Got DLL solver result: %1 points").arg(result[0].size()));
|
|
|
|
|
|
} else {
|
|
|
DEBUG_OUT("DLL solver result is empty or invalid");
|
|
|
DEBUG_OUT(QString("Pressure result size: %1, Array sizes: %2, %3")
|
|
|
.arg(pressureResult.size())
|
|
|
.arg(pressureResult.size() > 0 ? pressureResult[0].size() : 0)
|
|
|
.arg(pressureResult.size() > 1 ? pressureResult[1].size() : 0));
|
|
|
}
|
|
|
}
|
|
|
catch(const std::bad_alloc& e) {
|
|
|
DEBUG_OUT(QString("Memory allocation failed in DLL solver: %1").arg(e.what()));
|
|
|
}
|
|
|
catch(const std::exception& e) {
|
|
|
DEBUG_OUT(QString("Exception in DLL solver: %1").arg(e.what()));
|
|
|
}
|
|
|
catch(...) {
|
|
|
DEBUG_OUT("Unknown exception in DLL solver");
|
|
|
}
|
|
|
|
|
|
// 释放求解任务,退出评价前处理待派发的界面事件。
|
|
|
if(dllTask) {
|
|
|
if(dllTask->isRunning()) {
|
|
|
dllTask->terminate();
|
|
|
dllTask->wait(3000);
|
|
|
}
|
|
|
|
|
|
DEBUG_OUT("Cleaning up DLL solver task...");
|
|
|
delete dllTask;
|
|
|
dllTask = nullptr;
|
|
|
}
|
|
|
|
|
|
QApplication::processEvents(QEventLoop::AllEvents, 100);
|
|
|
--m_evaluationInProgress;
|
|
|
|
|
|
DEBUG_OUT(QString("SOLVER DLL END - ResultPoints: %1").arg(result.isEmpty() ? 0 : result[0].size()));
|
|
|
|
|
|
return result;
|
|
|
}
|
|
|
|
|
|
bool nmCalculationAutoFitLM::runFinalFullSolver()
|
|
|
{
|
|
|
// 不设置目标井名,任务按原完整模式保存全部井和网格结果。
|
|
|
nmDataAnalyzeManager* dataManager = nmDataAnalyzeManager::getCurrentInstance();
|
|
|
if(!dataManager) {
|
|
|
DEBUG_OUT("Cannot start final full-field solver without a data manager");
|
|
|
return false;
|
|
|
}
|
|
|
|
|
|
if(m_evaluationInProgress > 0) {
|
|
|
DEBUG_OUT("Cannot start final full-field solver while another evaluation is running");
|
|
|
return false;
|
|
|
}
|
|
|
|
|
|
++m_evaluationInProgress;
|
|
|
nmCalculationDllPebiSolverTask dllTask(m_tempDirectory, dataManager);
|
|
|
connect(&dllTask, SIGNAL(solverInvoked()), this, SLOT(recordSolverCall()), Qt::DirectConnection);
|
|
|
dllTask.start();
|
|
|
|
|
|
const int maxWait = 3600000;
|
|
|
const int checkInterval = 50;
|
|
|
QTime waitTimer;
|
|
|
waitTimer.start();
|
|
|
|
|
|
while(waitTimer.elapsed() < maxWait) {
|
|
|
if(dllTask.wait(checkInterval)) {
|
|
|
break;
|
|
|
}
|
|
|
|
|
|
// 最终完整计算期间处理界面事件,保持窗口响应。
|
|
|
QApplication::processEvents(QEventLoop::AllEvents, checkInterval);
|
|
|
|
|
|
if(!dllTask.isRunning()) {
|
|
|
break;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
if(dllTask.isRunning()) {
|
|
|
DEBUG_OUT("Final full-field solver timeout, terminating task");
|
|
|
dllTask.terminate();
|
|
|
dllTask.wait(2000);
|
|
|
--m_evaluationInProgress;
|
|
|
return false;
|
|
|
}
|
|
|
|
|
|
dllTask.wait();
|
|
|
// 后台只生成局部结果快照;确认求解和输入版本均有效后再一次性写回当前分析。
|
|
|
const bool succeeded = dllTask.wasSuccessful() && dllTask.commitResult(dataManager);
|
|
|
--m_evaluationInProgress;
|
|
|
return succeeded;
|
|
|
}
|
|
|
|
|
|
void nmCalculationAutoFitLM::pollEvents()
|
|
|
{
|
|
|
// 界面事件仅由软件适配层处理,独立模块无需 QApplication。
|
|
|
if(m_sensitivitySettings)
|
|
|
m_shouldStop = m_shouldStop || m_sensitivityCancelled();
|
|
|
QApplication::processEvents();
|
|
|
}
|
|
|
|
|
|
void nmCalculationAutoFitLM::syncAlgorithmProgress()
|
|
|
{
|
|
|
// 只复制界面与诊断所需的结果快照,迭代状态由算法对象独占。
|
|
|
m_currentIteration = m_engine->getCurrentIteration();
|
|
|
m_totalEvaluations = m_engine->getTotalEvaluations();
|
|
|
m_successfulEvaluations = m_engine->getSuccessfulEvaluations();
|
|
|
m_globalBestPosition = m_engine->getBestSolution();
|
|
|
m_globalBestFitness = m_engine->getBestFitness();
|
|
|
m_userInitialFitness = m_engine->getInitialFitness();
|
|
|
}
|
|
|
|
|
|
void nmCalculationAutoFitLM::setTargetLogLogData(const QVector<QVector<double>>& data)
|
|
|
{
|
|
|
m_targetLogLogData = data;
|
|
|
}
|
|
|
|
|
|
bool nmCalculationAutoFitLM::isRunning() const
|
|
|
{
|
|
|
return m_isRunning;
|
|
|
}
|
|
|
int nmCalculationAutoFitLM::getCurrentIteration() const
|
|
|
{
|
|
|
return m_engine->isRunning() ? m_engine->getCurrentIteration() : m_currentIteration;
|
|
|
}
|
|
|
int nmCalculationAutoFitLM::getTotalEvaluations() const
|
|
|
{
|
|
|
return m_engine->isRunning() ? m_engine->getTotalEvaluations() : m_totalEvaluations;
|
|
|
}
|
|
|
QVector<double> nmCalculationAutoFitLM::getBestSolution() const
|
|
|
{
|
|
|
return m_engine->isRunning() ? m_engine->getBestSolution() : m_globalBestPosition;
|
|
|
}
|
|
|
double nmCalculationAutoFitLM::getBestFitness() const
|
|
|
{
|
|
|
return m_engine->isRunning() ? m_engine->getBestFitness() : m_globalBestFitness;
|
|
|
}
|
|
|
QString nmCalculationAutoFitLM::getLastError() const
|
|
|
{
|
|
|
return m_lastError;
|
|
|
}
|
|
|
|
|
|
void nmCalculationAutoFitLM::resetOptimizer()
|
|
|
{
|
|
|
// 清理软件运行资源,并重置独立算法;调用期间不接受重置。
|
|
|
if(m_isRunning)
|
|
|
return;
|
|
|
closeTraceFile();
|
|
|
cleanupTemporaryDirectory();
|
|
|
m_engine->resetOptimizer();
|
|
|
syncAlgorithmProgress();
|
|
|
m_shouldStop = false;
|
|
|
m_solverCallCount = 0;
|
|
|
m_isFinalizing = false;
|
|
|
m_lastError.clear();
|
|
|
m_lastEvaluatedLogLogData.clear();
|
|
|
m_initialValues.clear();
|
|
|
m_traceFilePath.clear();
|
|
|
m_traceMetaFilePath.clear();
|
|
|
}
|
|
|
|
|
|
void nmCalculationAutoFitLM::setTargetWellName(const QString& name)
|
|
|
{
|
|
|
m_targetWellName = name;
|
|
|
}
|
|
|
|
|
|
void nmCalculationAutoFitLM::stopFitting()
|
|
|
{
|
|
|
// 最终成果提交阶段不可中断;迭代阶段同时通知模块和当前求解任务。
|
|
|
if(m_isFinalizing || !m_isRunning)
|
|
|
return;
|
|
|
m_shouldStop = true;
|
|
|
m_engine->stopFitting();
|
|
|
}
|
|
|
|
|
|
int nmCalculationAutoFitLM::getSolverCallCount() const
|
|
|
{
|
|
|
return m_solverCallCount;
|
|
|
}
|
|
|
void nmCalculationAutoFitLM::recordSolverCall()
|
|
|
{
|
|
|
m_solverCallCount.fetchAndAddOrdered(1);
|
|
|
}
|
|
|
AutoFitObjectiveBreakdownLM nmCalculationAutoFitLM::getLastObjectiveBreakdown() const
|
|
|
{
|
|
|
return m_engine->getLastObjectiveBreakdown();
|
|
|
}
|