You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
nmWTAI-Platform/Src/nmNum/nmCalculation/nmCalculationAutoFitPSO.cpp

2097 lines
87 KiB
C++

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include "nmCalculationAutoFitPSO.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 "nmCalculationPebiGrid.h"
#include <QApplication>
#include <QDebug>
#include <QTime>
#include <QDir>
#include <QTextStream>
#include <QFileInfo>
#include <QProcess>
#include <QProcessEnvironment>
#include <QPair>
#include <QtCore/qmath.h>
#include <cmath>
#include <algorithm>
#include <limits>
#include <QTimer>
#ifdef Q_OS_WIN
#include <windows.h>
#include <float.h>
#define DEBUG_OUT(msg) OutputDebugStringA(QString("[AutoFit] %1\n").arg(msg).toLocal8Bit().data())
#endif
#ifdef QT_NO_DEBUG
static const bool kAutoFitDiagnosticTraceEnabled = false;
#else
static const bool kAutoFitDiagnosticTraceEnabled = true;
#endif
// ===== PSO基础常量 =====
// MIN_FITNESS_IMPROVEMENT:判断适应度是否有有效改善的最小阈值。
// VELOCITY_LIMIT_FACTOR:单次速度最大值占参数搜索区间的比例,防止粒子一步跨太远。
// CONVERGENCE_CHECK_INTERVAL:收敛检查的基础间隔,部分历史逻辑和日志会使用它。
// 判断 double 是否为有限数。PSO、误差函数、trace 写出都依赖它过滤 NaN/Inf。
static inline bool isFiniteNumber(double value)
{
#ifdef Q_OS_WIN
return _finite(value) != 0;
#else
return std::isfinite(value);
#endif
}
// Windows 下的毫秒级睡眠封装。用于重试间隔、UI 事件循环间隔和模拟模式节奏控制。
static inline void msleep(int ms)
{
#ifdef Q_OS_WIN
Sleep(ms);
#endif
}
static QString csvEscape(const QString& text)
{
// CSV 字段转义。trace 中的 run_id、phase、screeningDecision 等字符串都走这里,
// 防止逗号或引号破坏表格结构。
QString escaped = text;
escaped.replace("\"", "\"\"");
return QString("\"%1\"").arg(escaped);
}
static QString traceNumber(double value)
{
// trace CSV 中的数值格式化。不可用数值写空字段,便于后续 pandas/Excel 读取。
if(!isFiniteNumber(value)) {
return QString();
}
return QString::number(value, 'g', 17);
}
static QString traceParamAt(const QVector<double>& params, int index)
{
// 从完整参数向量中安全取值并格式化。越界时写空字段,避免 trace 写出崩溃。
if(index < 0 || index >= params.size()) {
return QString();
}
return traceNumber(params[index]);
}
static QString jsonEscape(const QString& text)
{
// 手写 JSON 字符串转义。trace meta 不依赖第三方 JSON writer,
// 所以所有字符串字段写入前必须统一经过这里。
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)
{
// JSON 数值格式化。NaN/Inf 在 JSON 中没有合法表示,因此写 null。
if(!isFiniteNumber(value)) {
return "null";
}
return QString::number(value, 'g', 17);
}
static QString jsonDoubleArray(const QVector<double>& values)
{
// 将 double 数组写成 JSON 数组,用于 trace meta 的目标曲线、参数上下界等。
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)
{
// 将 int 数组写成 JSON 数组,用于 enabled_param_indices 等字段。
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)
{
// 将 bool 数组写成 JSON 数组,用于参数是否启用等字段。
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)
{
// 将字符串列表写成 JSON 数组,用于参数名、启用参数名等字段。
QStringList items;
for(int i = 0; i < values.size(); ++i) {
items << jsonEscape(values[i]);
}
return QString("[%1]").arg(items.join(","));
}
static QString jsonPointArray(const QVector<QPointF>& points)
{
// 将 QPointF 数组写成 [{"x":...,"y":...}],用于 trace meta 保存流量制度。
QStringList items;
for(int i = 0; i < points.size(); ++i) {
items << QString("{\"x\":%1,\"y\":%2}").arg(jsonNumber(points[i].x())).arg(jsonNumber(points[i].y()));
}
return QString("[%1]").arg(items.join(","));
}
// 构造函数:初始化 PSO 参数、收敛判断阈值、trace/代理统计和模拟模式状态。
// 这里设置的是默认值,真正运行前会由 loadOptimizationConfig() 和
// loadParameterBounds() 从 DataManager 读取界面配置覆盖一部分字段。
nmCalculationAutoFitPSO::nmCalculationAutoFitPSO(QObject* parent)
: QObject(parent), m_engine(new nmFitPSO(this)), m_isRunning(false), m_shouldStop(false), m_isFinalizing(false),
m_currentIteration(0), m_globalBestFitness(1e10), m_maxIterations(100), m_targetError(0.001),
m_totalEvaluations(0), m_successfulEvaluations(0), m_evaluationInProgress(0),
m_swarmSize(20), m_traceEnabled(kAutoFitDiagnosticTraceEnabled), m_surrogateScreeningEnabled(false),
m_proxy(new nmSurrogate(this)), m_simulationMode(false),
m_simulationTimer(nullptr), m_simulationIteration(0), m_simulationMaxIterations(100),
m_simulationTargetError(0.001), m_simulationStartError(0.5), m_simulationCurrentError(0.5),
m_simulationLogInterval(2), m_simulationCurrentParticle(0), m_simulationSuccessCount(0), m_simulationFailCount(0),
m_simulationIterationStarted(false), m_simulationPreviousIterError(0.5)
{
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(traceRowGenerated(int, int, QString, QVector<double>, double, bool, int, double, QString,
QVector<double>, double)),
this,
SLOT(writeTraceRow(int, int, QString, QVector<double>, double, bool, int, double, QString, QVector<double>,
double)),
Qt::DirectConnection);
connect(m_proxy, SIGNAL(logMessageGenerated(QString)), this, SIGNAL(logMessageGenerated(QString)));
m_proxy->setEventPump([this]() {
pollEvents();
if(m_shouldStop)
m_proxy->cancel();
});
DEBUG_OUT(QString("PSO Constructor: this=0x%1").arg((quintptr)this, 0, 16));
DEBUG_OUT("AutoFit calculator initialized (data-driven mode)");
DEBUG_OUT("PSO Constructor completed");
}
// 析构函数:停止仍在进行的拟合、关闭代理评分服务、关闭 trace 文件并清理临时目录。
// 自动拟合可能在 UI 线程中被窗口关闭打断,因此析构时要尽量温和地等待当前评价结束;
// 如果等待超时,再强制清除运行标志,避免对象销毁后还有信号回调或后台进程访问成员变量。
nmCalculationAutoFitPSO::~nmCalculationAutoFitPSO()
{
DEBUG_OUT(QString("PSO Destructor: this=0x%1").arg((quintptr)this, 0, 16));
if(m_simulationTimer) {
m_simulationTimer->stop();
delete m_simulationTimer;
m_simulationTimer = nullptr;
}
// Stop algorithm.
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 PSO - timeout reached");
m_isRunning = false;
}
}
// Clean temp directory.
stopSurrogateScoringServer();
closeTraceFile();
cleanupTemporaryDirectory();
// Disconnect all signals to avoid callbacks after destruction.
disconnect(this, nullptr, nullptr, nullptr);
DEBUG_OUT("PSO Destructor completed");
}
// ===== 临时目录工具 =====
//
// 求解器中间文件和代理评分文件共用一个受控的单次运行目录。创建失败时
// 直接禁用本次拟合,绝不回退到程序目录。
bool nmCalculationAutoFitPSO::initializeTemporaryDirectory()
{
nmCalculationUtils::cleanupStaleAutoFitTemporaryDirectories();
m_tempDirectory = nmCalculationUtils::createAutoFitTemporaryDirectory();
if(m_tempDirectory.isEmpty()) {
DEBUG_OUT("Failed to create PSO 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 nmCalculationAutoFitPSO::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 nmCalculationAutoFitPSO::stopFitting()
{
if(m_isFinalizing) {
emit logMessageGenerated(tr("The final full-field calculation is already running"));
return;
}
// 与 LM 一致,只登记停止请求,由主循环和求解器等待逻辑完成收尾。
if(m_simulationMode && m_simulationTimer) {
m_simulationTimer->stop();
m_shouldStop = true;
m_engine->stopFitting();
m_isRunning = false;
emit logMessageGenerated(tr("PSO simulation stop request processed"));
return;
}
if(m_isRunning) {
DEBUG_OUT("Stop request received, setting stop flag...");
// 添加停止日志
emit logMessageGenerated(tr("=== User Stop Request Received ==="));
emit logMessageGenerated(tr("Gracefully stopping PSO optimization..."));
m_shouldStop = true;
m_engine->stopFitting();
// 当前 DLL 任务可能仍持有临时文件,等待主循环自然收尾后再统一清理。
if(m_evaluationInProgress > 0) {
emit logMessageGenerated(tr("Waiting for current solver evaluation to stop..."));
}
emit logMessageGenerated(tr("PSO optimization stop request processed"));
DEBUG_OUT("Stop request processed");
} else {
DEBUG_OUT("Stop request received but PSO is not running");
emit logMessageGenerated(tr("Stop request received but optimization is not running"));
}
}
void nmCalculationAutoFitPSO::initializeTraceFile()
{
syncAlgorithmProgress();
closeTraceFile();
m_traceFilePath.clear();
m_traceMetaFilePath.clear();
configureSurrogate();
captureSurrogateRunContextSummary();
// 诊断轨迹只在 Debug 构建中启用,并写入系统临时目录而不是仓库。
if(m_traceEnabled) {
QDir traceDirectory(QDir(QDir::tempPath()).absoluteFilePath("WTAI/AutoFitTrace/PSO"));
if(!QDir().mkpath(traceDirectory.absolutePath())) {
DEBUG_OUT(QString("Failed to create PSO trace directory: %1").arg(traceDirectory.absolutePath()));
} else {
m_traceFilePath = traceDirectory.absoluteFilePath(QString("pso_baseline_trace_%1.csv").arg(m_traceRunId));
m_traceFile.setFileName(m_traceFilePath);
if(!m_traceFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
DEBUG_OUT(QString("Failed to open PSO trace file: %1").arg(m_traceFilePath));
m_traceFilePath.clear();
} else {
writeTraceHeader();
const QString metaPath =
traceDirectory.absoluteFilePath(QString("pso_baseline_trace_%1.meta.json").arg(m_traceRunId));
if(writeTraceMetaFile(metaPath)) {
m_traceMetaFilePath = metaPath;
}
emit logMessageGenerated(tr("PSO baseline trace: %1").arg(m_traceFilePath));
if(!m_traceMetaFilePath.isEmpty()) {
emit logMessageGenerated(tr("PSO baseline trace meta: %1").arg(m_traceMetaFilePath));
}
}
}
}
emit logMessageGenerated(tr("PSO surrogate screening: %1, model=%2, keep=%3, audit=%4, warmup=%5, min_solver=%6")
.arg(isSurrogateScreeningEnabled() ? tr("enabled") : tr("disabled"))
.arg(getSurrogateTag())
.arg(getSurrogateKeepFraction(), 0, 'f', 2)
.arg(getSurrogateAuditFraction(), 0, 'f', 2)
.arg(getSurrogateWarmupIterations())
.arg(getSurrogateMinSolverFraction(), 0, 'f', 2));
if(!isSurrogateScreeningEnabled()) {
emit logMessageGenerated(tr("Surrogate screening is turned off in the automatic fitting configuration"));
} else {
if(m_surrogateRunContextSummary == "passed") {
emit logMessageGenerated(tr("Surrogate run context check: passed"));
} else {
emit logMessageGenerated(tr("Surrogate run context check: %1").arg(m_surrogateRunContextSummary));
}
}
}
void nmCalculationAutoFitPSO::resetRunSummary()
{
// 代理实现位于独立模块,软件仅转发调用。
m_proxy->resetRunSummary();
}
void nmCalculationAutoFitPSO::captureSurrogateRunContextSummary()
{
// 在 trace 初始化阶段记录一次“本项目是否支持代理模型”的结论。
// 后续每代仍会再次检查,防止运行中 DataManager 状态发生变化。
if(!isSurrogateScreeningEnabled()) {
m_surrogateRunContextSummary = "disabled_by_config";
return;
}
QString contextReason;
if(isSurrogateRunContextSupported(&contextReason)) {
m_surrogateRunContextSummary = "passed";
} else {
m_surrogateRunContextSummary = tr("failed - %1").arg(contextReason);
}
}
void nmCalculationAutoFitPSO::emitRunSummary(bool success, StopReasonPSO finalReason)
{
// 运行结束时输出一组交接/排障最有用的摘要:
// 真实求解次数、成功失败数、代理模型启用情况、各类筛选决策计数,以及 trace 文件路径。
// 内部状态标识保留原值,仅在界面日志中转换为当前语言。
QString contextSummary = m_surrogateRunContextSummary;
if(contextSummary == "disabled_by_config")
contextSummary = tr("Disabled by configuration");
else if(contextSummary == "passed")
contextSummary = tr("Passed");
else if(contextSummary.isEmpty())
contextSummary = tr("Unknown");
emit logMessageGenerated(tr("=== PSO Run Summary ==="));
emit logMessageGenerated(tr("Stop reason: %1").arg(m_engine->getStopReasonDescription(finalReason)));
emit logMessageGenerated(tr("Result: %1, final error=%2, iterations=%3, evaluations=%4 (successful=%5, failed=%6)")
.arg(success ? tr("SUCCESS") : tr("FAILED"))
.arg(m_globalBestFitness, 0, 'e', 4)
.arg(m_currentIteration + 1)
.arg(m_totalEvaluations)
.arg(m_successfulEvaluations)
.arg(m_totalEvaluations - m_successfulEvaluations));
emit logMessageGenerated(tr("Surrogate config: %1, context=%2")
.arg(isSurrogateScreeningEnabled() ? tr("enabled") : tr("disabled"))
.arg(contextSummary));
emit logMessageGenerated(tr("Surrogate iterations: active=%1, warmup=%2, periodic_audit=%3, context_blocked=%4")
.arg(m_proxy->statistics().m_surrogateActiveIterationCount)
.arg(m_proxy->statistics().m_surrogateWarmupIterationCount)
.arg(m_proxy->statistics().m_surrogatePeriodicAuditIterationCount)
.arg(m_proxy->statistics().m_surrogateContextBlockedIterationCount));
emit logMessageGenerated(tr("Surrogate particles: selected=%1, screened_out=%2, topk=%3, random_audit=%4, "
"fallback=%5, domain_gate=%6, min_solver_floor=%7")
.arg(m_proxy->statistics().m_surrogateSelectedParticleCount)
.arg(m_proxy->statistics().m_surrogateScreenedParticleCount)
.arg(m_proxy->statistics().m_surrogateTopKParticleCount)
.arg(m_proxy->statistics().m_surrogateAuditParticleCount)
.arg(m_proxy->statistics().m_surrogateFallbackParticleCount)
.arg(m_proxy->statistics().m_surrogateDomainParticleCount)
.arg(m_proxy->statistics().m_surrogateMinFloorParticleCount));
if(!m_traceFilePath.isEmpty()) {
emit logMessageGenerated(tr("Artifacts: trace=%1").arg(m_traceFilePath));
}
if(!m_traceMetaFilePath.isEmpty()) {
emit logMessageGenerated(tr("Artifacts: trace_meta=%1").arg(m_traceMetaFilePath));
}
}
void nmCalculationAutoFitPSO::closeTraceFile()
{
// trace 与代理评分 server 生命周期绑定在一次 PSO run 内。
// 关闭 trace 时同时停止 server,避免 Python 进程继续占用模型或 stdout 管道。
stopSurrogateScoringServer();
if(m_traceFile.isOpen()) {
m_traceFile.flush();
m_traceFile.close();
}
}
void nmCalculationAutoFitPSO::writeTraceHeader()
{
// trace CSV 字段说明:
// - 当前粒子参数记录 k/skin/wellboreC/phi/h/Ct/Cf 及压裂井的 Dfc/裂缝半长;
// - solver_objective 是真实求解器误差;
// - surrogate_objective 是 Python 代理评分;
// - screening_decision 说明该粒子为什么跑/不跑真实求解器;
// - pbest/gbest 字段用于离线复盘 PSO 更新是否只依赖真实误差。
if(!m_traceFile.isOpen()) {
return;
}
QStringList cols;
cols << "run_id"
<< "generation"
<< "particle_id"
<< "phase"
<< "k"
<< "skin"
<< "wellboreC"
<< "phi"
<< "h"
<< "Ct"
<< "Cf"
<< "Dfc"
<< "fractureHalfLength"
<< "solver_objective"
<< "solver_success"
<< "elapsed_ms"
<< "surrogate_objective"
<< "screening_decision"
<< "pbest_objective"
<< "pbest_k"
<< "pbest_skin"
<< "pbest_wellboreC"
<< "pbest_phi"
<< "pbest_h"
<< "pbest_Ct"
<< "pbest_Cf"
<< "pbest_Dfc"
<< "pbest_fractureHalfLength"
<< "gbest_objective"
<< "gbest_k"
<< "gbest_skin"
<< "gbest_wellboreC"
<< "gbest_phi"
<< "gbest_h"
<< "gbest_Ct"
<< "gbest_Cf"
<< "gbest_Dfc"
<< "gbest_fractureHalfLength"
<< "enabled_param_indices"
<< "selected_parameters"
<< "pbest_selected_parameters"
<< "gbest_selected_parameters";
QTextStream out(&m_traceFile);
out << cols.join(",") << "\n";
}
bool nmCalculationAutoFitPSO::writeTraceMetaFile(const QString& filePath)
{
// 写 trace 的配套 JSON。它把“如何解释 CSV”的上下文固化下来:
// 目标井、目标 log-log 曲线、流量制度、参数名和上下界、初始参数、PSO 配置、
// 代理模型 tag/stage/筛选比例等。Python 评分脚本会读取这个文件来构造模型输入。
if(filePath.isEmpty()) {
return false;
}
QFile metaFile(filePath);
if(!metaFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
DEBUG_OUT(QString("Failed to open PSO context/meta file: %1").arg(filePath));
return false;
}
nmDataAnalyzeManager* dataManager = nmDataAnalyzeManager::getCurrentInstance();
nmDataWellBase* pTargetWell = dataManager ? dataManager->findWellByName(m_targetWellName) : nullptr;
// 元数据按完整参数列表记录井编码,避免不同井的同名参数混淆。
QStringList parameterNames, wellCodes;
QVector<int> parameterTypes;
QVector<double> initialFullParams;
for(int i = 0; i < m_modelParameters.size(); ++i) {
const nmFitParameterValue& p = m_modelParameters[i];
parameterNames << p.name();
wellCodes << p.wellCode;
parameterTypes << p.type;
initialFullParams << p.initial;
}
QStringList enabledNames;
for(int i = 0; i < m_enabledParamIndices.size(); ++i) {
const int index = m_enabledParamIndices[i];
enabledNames << parameterNames[index];
initialFullParams[index] = m_initialValues[i];
}
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>();
QVector<QPointF> flowPoints = pTargetWell ? pTargetWell->getFlowPoints() : QVector<QPointF>();
QTextStream out(&metaFile);
out << "{\n";
out << " \"schema_version\": 3,\n";
out << " \"trace_type\": \"pso_baseline_replay_meta\",\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 << " \"target\": {\n";
out << " \"well_name\": " << jsonEscape(m_targetWellName) << ",\n";
out << " \"well_type\": "
<< (pTargetWell ? QString::number(static_cast<int>(pTargetWell->getWellType())) : "null") << ",\n";
out << " \"section_policy\": \"current_target_well_indexF\",\n";
out << " \"section_index\": " << (pTargetWell ? QString::number(pTargetWell->getIndexF()) : "null") << ",\n";
out << " \"target_loglog\": {\n";
out << " \"time\": " << jsonDoubleArray(targetTime) << ",\n";
out << " \"pressure\": " << jsonDoubleArray(targetPressure) << ",\n";
out << " \"derivative\": " << jsonDoubleArray(targetDerivative) << "\n";
out << " },\n";
out << " \"flow_points\": " << jsonPointArray(flowPoints) << "\n";
out << " },\n";
out << " \"pso\": {\n";
out << " \"swarm_size\": " << m_swarmSize << ",\n";
out << " \"max_iterations\": " << m_maxIterations << ",\n";
out << " \"target_error\": " << jsonNumber(m_targetError) << ",\n";
out << " \"inertia_weight\": " << jsonNumber(m_engine->getInertiaWeight()) << ",\n";
out << " \"cognitive_param\": " << jsonNumber(m_engine->getCognitiveParam()) << ",\n";
out << " \"social_param\": " << jsonNumber(m_engine->getSocialParam()) << ",\n";
out << " \"random_seed\": " << m_engine->getRandomSeed() << "\n";
out << " },\n";
out << " \"surrogate_screening\": {\n";
out << " \"enabled\": " << (isSurrogateScreeningEnabled() ? "true" : "false") << ",\n";
out << " \"model_tag\": " << jsonEscape(getSurrogateTag()) << ",\n";
out << " \"keep_fraction\": " << jsonNumber(getSurrogateKeepFraction()) << ",\n";
out << " \"audit_fraction\": " << jsonNumber(getSurrogateAuditFraction()) << ",\n";
out << " \"min_solver_fraction\": " << jsonNumber(getSurrogateMinSolverFraction()) << ",\n";
out << " \"warmup_iterations\": " << getSurrogateWarmupIterations() << ",\n";
out << " \"full_solver_interval\": " << getSurrogateFullSolverInterval() << ",\n";
out << " \"audit_random_source\": \"deterministic_hash\"\n";
out << " },\n";
out << " \"parameters\": {\n";
out << " \"names\": " << jsonStringArray(parameterNames) << ",\n";
out << " \"well_codes\": " << jsonStringArray(wellCodes) << ",\n";
out << " \"types\": " << jsonIntArray(parameterTypes) << ",\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 << " \"replay_notes\": [\n";
out << " \"CSV rows contain true solver objectives for evaluated particles.\",\n";
out << " \"This meta file contains the target curve and run context needed for surrogate replay.\",\n";
out << " \"pbest and gbest must be updated only from true solver objectives.\"\n";
out << " ]\n";
out << "}\n";
metaFile.flush();
metaFile.close();
return true;
}
QVector<double> nmCalculationAutoFitPSO::buildTraceParameterVector(const QVector<double>& selectedParameters) const
{
// 前七项保留代理输入的 k/skin/wellboreC/phi/h/Ct/Cf 顺序,末尾追加 Dfc 和裂缝半长。
// h/Ct/Cf 始终读取储层固定值,裂缝参数只用于真实求解和追踪记录。
// trace CSV、候选 CSV、代理训练域检查都需要这个完整向量。
QVector<double> fullParams(9, 0.0);
nmDataAnalyzeManager* dataManager = nmDataAnalyzeManager::getCurrentInstance();
if(dataManager) {
nmDataReservoir reservoirData = dataManager->getReservoirDataCopy();
fullParams[0] = reservoirData.getPermeability().getValue().toDouble();
fullParams[3] = reservoirData.getPorosity().getValue().toDouble();
fullParams[4] = reservoirData.getThickness().getValue().toDouble();
fullParams[5] = reservoirData.getCt().getValue().toDouble();
fullParams[6] = reservoirData.getCf().getValue().toDouble();
nmDataWellBase* pTargetWell = dataManager->findWellByName(m_targetWellName);
if(pTargetWell) {
if(pTargetWell->getPerforationCount() > 0) {
fullParams[1] = pTargetWell->getPerforation(0)->getSkin().getValue().toDouble();
}
fullParams[2] = pTargetWell->getWellboreStorage().getValue().toDouble();
if(nmDataVerticalFracturedWell* fractured = dynamic_cast<nmDataVerticalFracturedWell*>(pTargetWell)) {
fullParams[7] = fractured->getDfc().getValue().toDouble();
fullParams[8] = fractured->getFractureHalfLength().getValue().toDouble();
} else if(nmDataHorizontalFracturedWell* fractured =
dynamic_cast<nmDataHorizontalFracturedWell*>(pTargetWell)) {
fullParams[7] = fractured->getDfc().getValue().toDouble();
fullParams[8] = fractured->getFractureHalfLength().getValue().toDouble();
}
}
}
for(int i = 0; i < selectedParameters.size() && i < m_enabledParamIndices.size(); ++i) {
int paramIndex = m_enabledParamIndices[i];
const nmFitParameterValue& p = m_modelParameters[paramIndex];
// 固定物理列只描述目标井,其他井的参数保存在完整的启用向量中。
nmDataWellBase* targetWell = dataManager ? dataManager->findWellByName(m_targetWellName) : nullptr;
if(p.wellCode.isEmpty() || (targetWell && p.wellCode == targetWell->getWellCode())) {
const int physicalIndex = p.type >= 4 ? p.type + 3 : p.type;
fullParams[physicalIndex] = selectedParameters[i];
}
}
return fullParams;
}
void nmCalculationAutoFitPSO::writeTraceRow(int generation, int particleIndex, const QString& phase,
const QVector<double>& parameters, double solverObjective,
bool solverSuccess, int elapsedMs, double surrogateObjective,
const QString& screeningDecision, const QVector<double>& pbestPosition,
double pbestObjective)
{
syncAlgorithmProgress();
// 写一行 trace。generation=-1/particleIndex=-1 表示用户初始解;
// 普通粒子行的 phase 为 particle_solver、particle_verified_cache 或 particle_not_evaluated。
// 被代理筛掉的粒子 solver_objective 写空值,但仍保留 surrogate_objective 和 decision。
if(!m_traceFile.isOpen()) {
return;
}
QVector<double> currentParams = buildTraceParameterVector(parameters);
QVector<double> pbestParams =
pbestPosition.isEmpty() ? QVector<double>() : buildTraceParameterVector(pbestPosition);
QVector<double> gbestParams =
m_globalBestPosition.isEmpty() ? QVector<double>() : buildTraceParameterVector(m_globalBestPosition);
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(generation) << QString::number(particleIndex) << csvEscape(phase)
<< traceParamAt(currentParams, 0) << traceParamAt(currentParams, 1) << traceParamAt(currentParams, 2)
<< traceParamAt(currentParams, 3) << traceParamAt(currentParams, 4) << traceParamAt(currentParams, 5)
<< traceParamAt(currentParams, 6) << traceParamAt(currentParams, 7) << traceParamAt(currentParams, 8)
<< traceNumber(solverObjective) << QString::number(solverSuccess ? 1 : 0) << QString::number(elapsedMs)
<< traceNumber(surrogateObjective) << csvEscape(screeningDecision) << traceNumber(pbestObjective)
<< traceParamAt(pbestParams, 0) << traceParamAt(pbestParams, 1) << traceParamAt(pbestParams, 2)
<< traceParamAt(pbestParams, 3) << traceParamAt(pbestParams, 4) << traceParamAt(pbestParams, 5)
<< traceParamAt(pbestParams, 6) << traceParamAt(pbestParams, 7) << traceParamAt(pbestParams, 8)
<< traceNumber(m_globalBestFitness) << traceParamAt(gbestParams, 0) << traceParamAt(gbestParams, 1)
<< traceParamAt(gbestParams, 2) << traceParamAt(gbestParams, 3) << traceParamAt(gbestParams, 4)
<< traceParamAt(gbestParams, 5) << traceParamAt(gbestParams, 6) << traceParamAt(gbestParams, 7)
<< traceParamAt(gbestParams, 8) << csvEscape(enabledIndices.join(";"))
<< csvEscape(jsonDoubleArray(parameters)) << csvEscape(jsonDoubleArray(pbestPosition))
<< csvEscape(jsonDoubleArray(m_globalBestPosition));
QTextStream out(&m_traceFile);
out << cols.join(",") << "\n";
m_traceFile.flush();
}
bool nmCalculationAutoFitPSO::isSurrogateScreeningEnabled() const
{
// 对应界面上的 PSO acceleration / surrogate screening 开关。
return m_surrogateScreeningEnabled;
}
QString nmCalculationAutoFitPSO::getMlRootPath() const
{
// 代理实现位于独立模块,软件仅转发调用。
return m_proxy->getMlRootPath();
}
QString nmCalculationAutoFitPSO::getPythonExecutablePath() const
{
// 代理实现位于独立模块,软件仅转发调用。
return m_proxy->getPythonExecutablePath();
}
QString nmCalculationAutoFitPSO::getSurrogateTag() const
{
// 代理实现位于独立模块,软件仅转发调用。
return m_proxy->getSurrogateTag();
}
QString nmCalculationAutoFitPSO::getSurrogateStage() const
{
// 代理实现位于独立模块,软件仅转发调用。
return m_proxy->getSurrogateStage();
}
double nmCalculationAutoFitPSO::getSurrogateKeepFraction() const
{
// 代理实现位于独立模块,软件仅转发调用。
return m_proxy->getSurrogateKeepFraction();
}
double nmCalculationAutoFitPSO::getSurrogateAuditFraction() const
{
// 代理实现位于独立模块,软件仅转发调用。
return m_proxy->getSurrogateAuditFraction();
}
double nmCalculationAutoFitPSO::getSurrogateMinSolverFraction() const
{
// 代理实现位于独立模块,软件仅转发调用。
return m_proxy->getSurrogateMinSolverFraction();
}
int nmCalculationAutoFitPSO::getSurrogateWarmupIterations() const
{
// 代理实现位于独立模块,软件仅转发调用。
return m_proxy->getSurrogateWarmupIterations();
}
int nmCalculationAutoFitPSO::getSurrogateFullSolverInterval() const
{
// 代理实现位于独立模块,软件仅转发调用。
return m_proxy->getSurrogateFullSolverInterval();
}
void nmCalculationAutoFitPSO::stopSurrogateScoringServer()
{
// 代理实现位于独立模块,软件仅转发调用。
m_proxy->stopSurrogateScoringServer();
}
bool nmCalculationAutoFitPSO::isSurrogateRunContextSupported(QString* reason) const
{
// 代理实现位于独立模块,软件仅转发调用。
return m_proxy->isSurrogateRunContextSupported(reason);
}
// ==================== 数据加载方法 ====================
bool nmCalculationAutoFitPSO::loadConfiguration()
{
// 统一从 DataManager 加载本次运行所需配置。
// UI 层只负责把用户选择保存到 nmDataAutomaticFitting,本类从这里开始完全数据驱动。
try {
loadOptimizationConfig();
loadParameterBounds();
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 nmCalculationAutoFitPSO::loadOptimizationConfig()
{
// 读取“优化控制”配置:迭代次数、目标误差、是否启用代理筛选。
// PSO 的 swarm/inertia/cognitive/social 目前是类内固定默认值,
// 不是界面输入项;后续若要开放高级设置,可以从这里扩展。
nmDataAnalyzeManager* dataManager = nmDataAnalyzeManager::getCurrentInstance();
nmDataAutomaticFitting fittingData = dataManager->getAutomaticFittingDataCopy();
// 加载基本配置
m_maxIterations = fittingData.getIterationCount().getValue().toInt();
m_targetError = fittingData.getErrorTolerance().getValue().toDouble();
m_surrogateScreeningEnabled = fittingData.getSurrogateScreeningEnabled();
// 设置 PSO 默认参数:
// swarmSize=20 控制每代粒子数;inertia/cognitive/social 控制搜索惯性、
// 个体经验和群体经验的权重。adaptiveParameterUpdate() 会在运行中微调这些值。
m_swarmSize = 20;
DEBUG_OUT(QString("Loaded optimization config: iterations=%1, error=%2, surrogate=%3")
.arg(m_maxIterations)
.arg(m_targetError)
.arg(m_surrogateScreeningEnabled ? "enabled" : "disabled"));
}
void nmCalculationAutoFitPSO::loadParameterBounds()
{
// 与 LM 共用按井分组的参数列表,位置和类型分离,允许多口井拥有同类参数。
const nmDataAutomaticFitting fittingData =
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);
}
}
// ==================== PSO算法核心方法 ====================
bool nmCalculationAutoFitPSO::startAutoFitting()
{
// 软件只准备输入与求解回调;拟合迭代由模块统一执行。
if(m_isRunning) {
m_lastError = tr("Auto fitting is already running");
return false;
}
resetOptimizer();
if(!loadConfiguration())
return false;
if(m_simulationMode) {
runSimulatedFitting();
return true;
}
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;
nmFitCallbacks callbacks;
callbacks.processEvents = [this]() { pollEvents(); };
const nmFitResult result = m_engine->fit(
request,
[this](const QVector<double>& values, bool retry) -> nmFitCurve { return evaluateCurve(values, retry); },
[this]() -> bool { return m_shouldStop; }, m_surrogateScreeningEnabled ? m_proxy : nullptr, callbacks);
syncAlgorithmProgress();
m_lastError = result.error;
m_globalBestLogLogData = result.curve;
if(!result.completed) {
m_isRunning = false;
closeTraceFile();
cleanupTemporaryDirectory();
emit fittingFinished(false, m_lastError);
return false;
}
bool finalFullSolverSucceeded = false;
// 应用最终参数
if(!m_globalBestPosition.isEmpty()) {
try {
// Stop 只结束优化迭代;从这里开始必须用当前最优参数生成并发布正式快照。
m_isFinalizing = true;
emit finalizingStarted();
emit logMessageGenerated(tr("Applying optimized parameters to model..."));
applyParametersToDataManager(m_globalBestPosition);
// 候选粒子只返回目标井曲线;最优参数确定后必须再生成并提交完整结果快照。
emit logMessageGenerated(tr("Running final full-field calculation with optimized parameters..."));
finalFullSolverSucceeded = runFinalFullSolver();
if(finalFullSolverSucceeded) {
emit logMessageGenerated(tr("Final full-field calculation completed successfully"));
} else {
m_lastError = tr("Optimized parameters were found, but the final full-field calculation failed");
emit logMessageGenerated(tr("ERROR: Final full-field calculation failed"));
}
saveOptimizationResult();
// 输出最终优化结果
emit logMessageGenerated(tr("=== Optimization Results ==="));
emit logMessageGenerated(tr("Final error: %1").arg(m_globalBestFitness, 0, 'e', 4));
emit logMessageGenerated(tr("Total iterations: %1").arg(m_currentIteration + 1)); // 显示实际完成的迭代数
emit logMessageGenerated(
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);
}
emit logMessageGenerated(finalParams);
if(finalFullSolverSucceeded) {
emit logMessageGenerated(tr("Parameters and full-field results applied successfully to data manager"));
} else {
emit logMessageGenerated(tr("Optimized parameters applied to data manager"));
}
}
catch(const std::exception& e) {
emit logMessageGenerated(tr("ERROR: Failed to apply final parameters: %1").arg(e.what()));
m_lastError = tr("Failed to apply final parameters: %1").arg(e.what());
}
catch(...) {
emit logMessageGenerated(tr("ERROR: Unknown error applying final parameters"));
m_lastError = tr("Failed to apply final parameters due to unknown error");
}
}
m_isFinalizing = false;
m_isRunning = false;
// 判断系统确定最终结果
bool success;
QString message;
StopReasonPSO finalReason = static_cast<StopReasonPSO>(result.stopReason);
if(finalReason == PSO_TARGET_ACHIEVED) {
success = true;
message = QString(tr("Target achieved. Best error: %1, Iterations: %2"))
.arg(m_globalBestFitness, 0, 'e', 4)
.arg(m_currentIteration + 1);
emit logMessageGenerated(tr("=== PSO OPTIMIZATION SUCCESSFUL ==="));
} else if(finalReason == PSO_TRUE_CONVERGENCE) {
success = true;
message = QString(tr("PSO optimization converged to stable solution. Best error: %1, Iterations: %2"))
.arg(m_globalBestFitness, 0, 'e', 4)
.arg(m_currentIteration + 1);
emit logMessageGenerated(tr("=== PSO OPTIMIZATION CONVERGED ==="));
} else if(finalReason == PSO_LOCAL_OPTIMUM) {
success = true;
message = QString(tr("PSO optimization trapped in local optimum. Best error: %1, Iterations: %2"))
.arg(m_globalBestFitness, 0, 'e', 4)
.arg(m_currentIteration + 1);
emit logMessageGenerated(tr("=== PSO OPTIMIZATION - LOCAL OPTIMUM ==="));
} else if(finalReason == PSO_MAX_ITERATIONS) {
success = true;
message = QString(tr("Max iterations reached. Best error: %1, Iterations: %2"))
.arg(m_globalBestFitness, 0, 'e', 4)
.arg(m_currentIteration + 1);
emit logMessageGenerated(tr("=== PSO OPTIMIZATION - MAX ITERATIONS ==="));
} else if(finalReason == PSO_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);
emit logMessageGenerated(tr("=== PSO OPTIMIZATION STOPPED BY USER ==="));
} else if(finalReason == PSO_CONSECUTIVE_FAILURES) {
success = false;
message = QString(tr("PSO optimization failed due to consecutive failures. Best error: %1, Iterations: %2"))
.arg(m_globalBestFitness, 0, 'e', 4)
.arg(m_currentIteration + 1);
emit logMessageGenerated(tr("=== PSO OPTIMIZATION FAILED ==="));
} else {
success = false;
message = QString(tr("PSO optimization ended unexpectedly. Best error: %1, Iterations: %2"))
.arg(m_globalBestFitness, 0, 'e', 4)
.arg(m_currentIteration + 1);
emit logMessageGenerated(tr("=== PSO OPTIMIZATION - UNKNOWN END ==="));
}
// 只有正式快照已经提交,界面收到的成功信号才代表本次拟合结果完整可用。
if(success && !finalFullSolverSucceeded) {
success = false;
message = m_lastError.isEmpty() ? tr("The final full-field calculation failed") : m_lastError;
}
emitRunSummary(success, finalReason);
// 先发送最终进度更新,确保进度条达到100%
emit progressUpdated(m_maxIterations, m_globalBestFitness);
// 确保界面更新完成
QApplication::processEvents();
// 短暂延迟,让进度条动画完成
msleep(200);
// 再次确保界面更新
QApplication::processEvents();
// 现在才发送完成信号,这会触发消息框
closeTraceFile();
cleanupTemporaryDirectory();
emit fittingFinished(success, message);
return success;
}
nmFitCurve nmCalculationAutoFitPSO::evaluateCurve(const QVector<double>& parameters, bool retrySolver)
{
// 粒子适应度评价函数,也是自动拟合最核心的闭环:
// 1. 校验粒子参数是否在用户设置的上下界和基本物理范围内;
// 2. 将参数写入 DataManager 的储层/各所属井对象;
// 3. 调用真实数值求解器,生成模拟结果;
// 4. 从目标井读取模拟后的 result log-log 曲线;
// 5. 与目标 history log-log 曲线计算误差,误差越小代表拟合越好。
//
// 返回 1e10 表示该粒子评价失败或结果不可用。PSO 会把它当成很差的解。
syncAlgorithmProgress();
const QString funcName = QString("evaluateError[%1]").arg(m_currentIteration);
static int callCount = 0;
callCount++;
m_lastEvaluatedLogLogData.clear();
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));
// 1. 与 LM 一致,检查参数数量、有限数和界面上下界。
// 参数物理范围由拟合窗口统一校验。
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));
// 2. 数据管理器检查。后续参数写回和求解器组装都依赖当前 DataManager。
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));
// 3. 应用参数。parameters 的顺序与 m_enabledParamIndices 对齐,
// applyParametersToDataManager() 会把它们按列表写入共享储层参数和各井参数。
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();
}
// 4. 运行求解器。真实求解器偶发失败时允许重试,避免一次 DLL 调用异常
// 直接让整个粒子评价失败。
QVector<QVector<double>> solverResult;
const int maxRetries = 2;
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 = runSolver();
// 详细检查求解器结果
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();
}
// 5. 新求解任务不回写每个候选的临时结果,直接使用任务返回的曲线快照。
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));
// 详细输出LogLog数据问题
if(resultLogLogData.size() < 3) {
DEBUG_OUT(QString(" -> LogLog arrays count: %1 (need 3)").arg(resultLogLogData.size()));
} else {
DEBUG_OUT(QString(" -> LogLog array sizes: X=%1, Y1=%2, Y2=%3")
.arg(resultLogLogData[0].size())
.arg(resultLogLogData[1].size())
.arg(resultLogLogData[2].size()));
// 检查数据有效性
for(int i = 0; i < qMin(5, resultLogLogData[0].size()); ++i) {
if(!isFiniteNumber(resultLogLogData[0][i]) || !isFiniteNumber(resultLogLogData[1][i]) ||
!isFiniteNumber(resultLogLogData[2][i])) {
DEBUG_OUT(QString(" -> Invalid data at index %1: X=%2, Y1=%3, Y2=%4")
.arg(i)
.arg(resultLogLogData[0][i])
.arg(resultLogLogData[1][i])
.arg(resultLogLogData[2][i]));
}
}
}
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 nmCalculationAutoFitPSO::applyParametersToDataManager(const QVector<double>& parameters)
{
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);
// 任意一口井的裂缝参数参与搜索时,候选评价和最终求解均须重建网格。
for(int i = 0; i < m_enabledParamIndices.size(); ++i) {
const int type = m_modelParameters[m_enabledParamIndices[i]].type;
if(type == 4 || type == 5) {
manager->invalidatePebiGrid();
break;
}
}
}
// ==================== 求解器相关方法 ====================
QVector<QVector<double>> nmCalculationAutoFitPSO::runSolver()
{
// 调用 DLL 求解器,评价回调将本次曲线返回给 PSO 模块。
return runSolverDll();
}
// ==================== 算法辅助方法 ====================
void nmCalculationAutoFitPSO::saveOptimizationResult()
{
// 当前函数只做日志记录。真正把最优参数写回项目数据的是
// startAutoFitting() 结束阶段的 applyParametersToDataManager(m_globalBestPosition)。
DEBUG_OUT(QString("Optimization result: error=%1, evaluations=%2/%3")
.arg(m_globalBestFitness, 0, 'e', 4)
.arg(m_successfulEvaluations)
.arg(m_totalEvaluations));
}
// ==================== 验证和处理方法 ====================
QVector<QVector<double>> nmCalculationAutoFitPSO::runSolverDll()
{
// DLL 求解器路径。
// 这个函数负责把当前 DataManager 中的项目状态交给底层数值求解器,
// 从任务快照读取目标井的 result log-log 数据,交给评价回调。
//
// 如果这里失败,通常需要优先检查:HX_NWTM.dll、license、网格/井数据是否完整、
// 目标井是否存在,以及 DataManager 中刚写入的参数是否导致求解器异常。
DEBUG_OUT("SOLVER DLL START");
// 新求解任务要求在创建线程绑定所属分析,并把目标井结果保存在任务快照中。
nmDataAnalyzeManager* pDataManager = nmDataAnalyzeManager::getCurrentInstance();
if(pDataManager == nullptr || m_targetWellName.isEmpty()) {
return QVector<QVector<double>>();
}
if(m_evaluationInProgress > 0) {
DEBUG_OUT("DLL Solver already running, skipping");
return QVector<QVector<double>>();
}
++m_evaluationInProgress;
QVector<QVector<double>> result;
nmCalculationDllPebiSolverTask* dllTask = nullptr;
try {
DEBUG_OUT("Creating DLL solver task");
dllTask = new nmCalculationDllPebiSolverTask(m_tempDirectory, pDataManager, 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,保证界面不会完全卡死。
dllTask->start();
// 等待完成。最大等待 1 小时;用户停止使用任务已有的协作取消接口。
const int maxWait = 3600000; // 1h超时
const int checkInterval = 50;
QTime waitTimer;
waitTimer.start();
while(waitTimer.elapsed() < maxWait) {
// wait(timeout) 会在线程一完成时立即返回,避免原来固定 msleep(500)
// 带来的每次 0~500ms 额外等待;50ms 间隔仍可及时处理停止请求和界面事件。
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()));
// 检查结果是否与之前不同。若连续粒子得到完全相同的压力曲线,
// 可能说明参数没有正确写入 DataManager,或求解器缓存/状态没有刷新。
static QVector<double> lastPressureResult;
bool isDifferentFromLast = false;
if(lastPressureResult.isEmpty() || lastPressureResult.size() != pressureResult[1].size()) {
isDifferentFromLast = true;
} else {
for(int i = 0; i < qMin(5, pressureResult[1].size()); ++i) {
if(qAbs(lastPressureResult[i] - pressureResult[1][i]) > 1e-12) {
isDifferentFromLast = true;
break;
}
}
}
if(isDifferentFromLast) {
DEBUG_OUT("RESULT VERIFICATION: Got NEW result data from DLL");
lastPressureResult = pressureResult[1];
} else {
DEBUG_OUT("!!! WARNING: Result data appears to be identical to previous run !!!");
}
} 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");
}
// 清理DLL任务
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 nmCalculationAutoFitPSO::runFinalFullSolver()
{
// 不设置目标井名,任务按普通完整模式构建全部井、网格和压力场结果。
nmDataAnalyzeManager* pDataManager = nmDataAnalyzeManager::getCurrentInstance();
if(pDataManager == nullptr || m_evaluationInProgress > 0) {
DEBUG_OUT("Cannot start final full-field solver");
return false;
}
++m_evaluationInProgress;
nmCalculationDllPebiSolverTask dllTask(m_tempDirectory, pDataManager);
dllTask.start();
const int maxWait = 3600000;
const int checkInterval = 50;
QTime waitTimer;
waitTimer.start();
while(waitTimer.elapsed() < maxWait) {
if(dllTask.wait(checkInterval) || !dllTask.isRunning()) {
break;
}
// 最终求解期间继续处理绘制事件,避免进度窗口看起来失去响应。
QApplication::processEvents(QEventLoop::ExcludeUserInputEvents, checkInterval);
}
if(dllTask.isRunning()) {
DEBUG_OUT("Final full-field solver timeout, terminating task");
dllTask.terminate();
dllTask.wait(2000);
--m_evaluationInProgress;
return false;
}
dllTask.wait();
// 后台只生成候选快照,必须回到 DataManager 所属线程一次性提交。
const bool succeeded = dllTask.wasSuccessful() && dllTask.commitResult(pDataManager);
--m_evaluationInProgress;
return succeeded;
}
void nmCalculationAutoFitPSO::setSimulationMode(bool enabled)
{
// 仿真模式开关。它用于 UI 演示/调试进度和日志,不调用真实 DLL 求解器。
// 正式自动拟合流程通常保持 false。
m_simulationMode = enabled;
DEBUG_OUT(QString("Simulation mode %1").arg(enabled ? "enabled" : "disabled"));
}
void nmCalculationAutoFitPSO::setSimulationTargetParams(const QVector<double>& targetParams, double targetError)
{
// 设置仿真模式的“目标参数”和“目标误差”。
// 仿真过程会把参数和误差平滑地从初始值过渡到这里。
m_simulationTargetParams = targetParams;
m_simulationTargetError = targetError;
DEBUG_OUT(QString("Simulation target params set: %1 parameters, target error: %2")
.arg(targetParams.size())
.arg(targetError, 0, 'e', 4));
}
QVector<QVector<double>> nmCalculationAutoFitPSO::buildSimulatedLogLogData(double progress) const
{
// 为仿真模式生成一条看起来逐渐贴近目标曲线的 log-log 曲线。
// progress=0 表示偏离目标较多,progress=1 基本等于目标曲线。
QVector<QVector<double>> simulated;
if(m_targetLogLogData.size() < 3) {
return simulated;
}
int count = qMin(m_targetLogLogData[0].size(), qMin(m_targetLogLogData[1].size(), m_targetLogLogData[2].size()));
simulated.resize(3);
simulated[0].reserve(count);
simulated[1].reserve(count);
simulated[2].reserve(count);
double clampedProgress = qMax(0.0, qMin(1.0, progress));
double pressureOffset = 0.35 * (1.0 - clampedProgress);
double derivativeOffset = 0.28 * (1.0 - clampedProgress);
for(int i = 0; i < count; ++i) {
double x = m_targetLogLogData[0][i];
double y1 = m_targetLogLogData[1][i];
double y2 = m_targetLogLogData[2][i];
if(!isFiniteNumber(x) || !isFiniteNumber(y1) || !isFiniteNumber(y2) || x <= 0.0 || y1 <= 0.0 || y2 <= 0.0) {
continue;
}
double localWave = 1.0 + 0.04 * (1.0 - clampedProgress) * qSin(i * 0.17);
simulated[0].append(x);
simulated[1].append(qMax(1e-12, y1 * (1.0 + pressureOffset) * localWave));
simulated[2].append(qMax(1e-12, y2 * (1.0 - derivativeOffset) / localWave));
}
return simulated;
}
void nmCalculationAutoFitPSO::runSimulatedFitting()
{
// 仿真模式入口:模拟完整 PSO 日志、进度、bestCurveUpdated 信号和最终写回。
// 它不评价粒子、不调用代理模型、不调用 DLL,只用于界面联调或演示自动拟合流程。
DEBUG_OUT("=== SIMULATED PSO AUTO FITTING START ===");
m_isRunning = true;
m_shouldStop = false;
m_simulationIteration = 0;
m_simulationMaxIterations = m_maxIterations;
m_simulationCurrentParticle = 0;
m_simulationSuccessCount = 0;
m_simulationFailCount = 0;
m_simulationIterationStarted = false;
// 设置起始误差
m_simulationStartError = 0.7324;
m_simulationCurrentError = m_simulationStartError;
m_simulationPreviousIterError = m_simulationStartError;
int enabledParams = getEnabledParameterCount();
// 从界面提取的初始值
m_simulationStartParams = m_initialValues;
m_globalBestPosition = m_simulationStartParams;
m_globalBestFitness = m_simulationStartError;
m_globalBestLogLogData = buildSimulatedLogLogData(0.0);
emit bestCurveUpdated(m_targetLogLogData, m_globalBestLogLogData, 0, m_globalBestFitness);
// 发送初始化日志
emit logMessageGenerated(tr("=== PSO Automatic Fitting Started ==="));
emit logMessageGenerated(tr("Algorithm: Particle Swarm Optimization"));
emit logMessageGenerated(tr("Enabled parameters count: %1").arg(enabledParams));
emit logMessageGenerated(tr("Target data validation passed (%1 data points)")
.arg(m_targetLogLogData.isEmpty() ? 156 : m_targetLogLogData[0].size()));
emit logMessageGenerated(tr("=== Evaluating Initial Solution (Elite Protection) ==="));
QString paramStr = tr("Initial parameters: ");
for(int i = 0; i < m_simulationStartParams.size(); ++i) {
paramStr += QString("[%1]=%2 ").arg(i).arg(m_simulationStartParams[i], 0, 'f', 6);
}
emit logMessageGenerated(paramStr);
emit logMessageGenerated(tr("Starting initial solution evaluation..."));
QApplication::processEvents();
msleep(500);
emit logMessageGenerated(tr("evaluateError returned: %1").arg(m_simulationStartError, 0, 'e', 10));
emit logMessageGenerated(tr("Taking SUCCESS branch (Error < 1e9)"));
emit logMessageGenerated(tr("Initial solution evaluation successful"));
emit logMessageGenerated(tr("Initial Error: %1").arg(m_simulationStartError, 0, 'e', 4));
emit logMessageGenerated(
tr("Elite protection activated - initial solution will be preserved if no significant improvement found"));
emit logMessageGenerated(tr("Swarm initialized: %1 particles, %2 dimensions").arg(m_swarmSize).arg(enabledParams));
emit logMessageGenerated(tr("=== Starting PSO Main Loop ==="));
if(!m_simulationTimer) {
m_simulationTimer = new QTimer(this);
connect(m_simulationTimer, SIGNAL(timeout()), this, SLOT(onSimulationTimerTick()));
}
int intervalMs = m_simulationLogInterval * 1000;
m_simulationTimer->start(intervalMs);
DEBUG_OUT(QString("Simulation timer started with interval: %1 ms").arg(intervalMs));
}
void nmCalculationAutoFitPSO::onSimulationTimerTick()
{
// 仿真模式用 QTimer 分步输出日志,避免一次性刷完,效果更接近真实长任务。
// 检查是否需要停止
if(m_shouldStop) {
m_simulationTimer->stop();
emit logMessageGenerated(tr("=== User Stop Request Received ==="));
emit logMessageGenerated(tr("Gracefully stopping PSO optimization..."));
emit logMessageGenerated(tr("PSO optimization stop request processed"));
m_globalBestPosition = calculateSimulatedParams(m_simulationIteration);
m_globalBestFitness = m_simulationCurrentError;
m_isRunning = false;
QString message = QString(tr("Stopped by user. Best error: %1, Iterations: %2"))
.arg(m_globalBestFitness, 0, 'e', 4)
.arg(m_simulationIteration);
emit logMessageGenerated(tr("=== PSO OPTIMIZATION STOPPED BY USER ==="));
emit progressUpdated(m_simulationMaxIterations, m_globalBestFitness);
QApplication::processEvents();
msleep(200);
emit fittingFinished(true, message);
return;
}
// 检查是否完成所有迭代
if(m_simulationIteration >= m_simulationMaxIterations) {
m_simulationTimer->stop();
finishSimulation();
return;
}
// 检查是否需要开始新的迭代
if(!m_simulationIterationStarted) {
startNewSimulationIteration();
return;
}
// 处理当前粒子
if(m_simulationCurrentParticle < m_swarmSize) {
emitParticleLog(m_simulationCurrentParticle);
m_simulationCurrentParticle++;
// 每处理2个粒子,处理一次事件
if(m_simulationCurrentParticle % 2 == 0) {
QApplication::processEvents();
}
} else {
// 当前迭代的所有粒子都处理完了,输出迭代统计
finishCurrentIteration();
}
}
double nmCalculationAutoFitPSO::calculateSimulatedError(int iteration)
{
// 生成随迭代递减的模拟误差,并叠加少量随机扰动。
// 使用非线性 decay,让前期下降较快、后期逐渐变慢,更像真实优化曲线。
if(iteration <= 0)
return m_simulationStartError;
if(iteration >= m_simulationMaxIterations)
return m_simulationTargetError;
double progress = (double)iteration / m_simulationMaxIterations;
double decayFactor = 1.0 - pow(progress, 0.6);
double error = m_simulationTargetError + (m_simulationStartError - m_simulationTargetError) * decayFactor;
double noise = (qrand() % 1000 - 500) / 500000.0;
error = error * (1.0 + noise);
error = qMax(m_simulationTargetError, error);
return error;
}
QVector<double> nmCalculationAutoFitPSO::calculateSimulatedParams(int iteration)
{
// 生成随迭代从初始参数平滑靠近目标参数的模拟参数。
// 返回向量仍然是“启用参数向量”,可直接传给 applyParametersToDataManager()。
QVector<double> currentParams;
if(iteration <= 0)
return m_simulationStartParams;
if(iteration >= m_simulationMaxIterations)
return m_simulationTargetParams;
double progress = (double)iteration / m_simulationMaxIterations;
double blendFactor = 1.0 - pow(1.0 - progress, 0.6);
for(int i = 0; i < m_simulationStartParams.size() && i < m_simulationTargetParams.size(); ++i) {
double startVal = m_simulationStartParams[i];
double targetVal = m_simulationTargetParams[i];
double currentVal = startVal + (targetVal - startVal) * blendFactor;
double noise = (qrand() % 1000 - 500) / 50000.0;
currentVal = currentVal * (1.0 + noise);
currentParams.append(currentVal);
}
return currentParams;
}
void nmCalculationAutoFitPSO::startNewSimulationIteration()
{
// 开始仿真模式的一代:更新误差/最优曲线,输出该代标题和累计评价数。
m_simulationIteration++;
m_simulationCurrentParticle = 0;
m_simulationSuccessCount = 0;
m_simulationFailCount = 0;
m_simulationIterationStarted = true;
// 保存上一次迭代的误差
m_simulationPreviousIterError = m_simulationCurrentError;
// 计算当前迭代的目标误差
m_simulationCurrentError = calculateSimulatedError(m_simulationIteration);
if(m_simulationCurrentError < m_globalBestFitness) {
QVector<double> currentParams = calculateSimulatedParams(m_simulationIteration);
m_globalBestFitness = m_simulationCurrentError;
m_globalBestPosition = currentParams;
double progress = (double)m_simulationIteration / qMax(1, m_simulationMaxIterations);
m_globalBestLogLogData = buildSimulatedLogLogData(progress);
emit bestCurveUpdated(m_targetLogLogData, m_globalBestLogLogData, m_simulationIteration, m_globalBestFitness);
}
bool shouldOutputDetail = (m_simulationIteration % qMax(1, m_simulationMaxIterations / 10) == 0) ||
(m_simulationIteration <= 5) || (m_simulationIteration >= m_simulationMaxIterations - 2);
// 输出迭代标题
emit logMessageGenerated(tr("--- Iteration %1/%2 ---").arg(m_simulationIteration).arg(m_simulationMaxIterations));
if(shouldOutputDetail) {
emit logMessageGenerated(tr("Current best error: %1").arg(m_globalBestFitness, 0, 'e', 4));
emit logMessageGenerated(tr("Total evaluations: %1 (successful: %2, failures: %3)")
.arg((m_simulationIteration - 1) * m_swarmSize)
.arg((m_simulationIteration - 1) * m_swarmSize)
.arg(0));
}
}
void nmCalculationAutoFitPSO::emitParticleLog(int particleIndex)
{
// 输出单个仿真粒子的日志。这里随机生成失败、显著改进、微小改进、无改进四类情况,
// 目的是让 UI 日志表现接近真实 PSO,而不是用于任何真实优化计算。
int particleId = particleIndex + 1;
// 为每个粒子生成模拟的误差值
double particleNewError = m_simulationCurrentError * (0.97 + 0.06 * (qrand() % 100) / 100.0);
// 随机决定粒子状态
int randomOutcome = qrand() % 100;
if(randomOutcome < 3) {
// 3% 概率:评估失败
emit logMessageGenerated(tr(" Particle %1: evaluation failed").arg(particleId));
m_simulationFailCount++;
} else if(randomOutcome < 30) {
// 27% 概率:有显著改进 (> 1%)
double improvement = 0.01 + 0.12 * (qrand() % 100) / 100.0;
double oldErr = particleNewError / (1.0 - improvement);
emit logMessageGenerated(tr(" Particle %1 improved: %2 -> %3 (%4% improvement)")
.arg(particleId)
.arg(oldErr, 0, 'e', 3)
.arg(particleNewError, 0, 'e', 3)
.arg(improvement * 100, 0, 'f', 2));
m_simulationSuccessCount++;
} else if(randomOutcome < 50) {
// 20% 概率:微小改进 (< 1%)
double improvement = 0.001 + 0.008 * (qrand() % 100) / 100.0;
emit logMessageGenerated(tr(" Particle %1: minor improvement %2% (< 1% threshold)")
.arg(particleId)
.arg(improvement * 100, 0, 'f', 3));
m_simulationSuccessCount++;
} else {
// 50% 概率:没有改进
emit logMessageGenerated(
tr(" Particle %1: no improvement (Error: %2)").arg(particleId).arg(particleNewError, 0, 'e', 3));
m_simulationSuccessCount++;
}
}
void nmCalculationAutoFitPSO::finishCurrentIteration()
{
// 完成仿真模式的一代:输出统计、收敛检查和进度更新,然后等待下一次 timer tick。
m_simulationIterationStarted = false;
bool shouldOutputDetail = (m_simulationIteration % qMax(1, m_simulationMaxIterations / 10) == 0) ||
(m_simulationIteration <= 5) || (m_simulationIteration >= m_simulationMaxIterations - 2);
// 每5次迭代输出"发现更好解"
if(m_simulationIteration % 5 == 0 && m_simulationIteration > 0) {
emit logMessageGenerated(tr("Better solution found: %1").arg(m_globalBestFitness, 0, 'e', 4));
}
// 输出当前迭代统计
double successRate = (double)m_simulationSuccessCount / m_swarmSize * 100;
if(shouldOutputDetail) {
emit logMessageGenerated(
tr("Current iteration stats: %1 successful, %2 failed out of %3 particles (success rate: %4%)")
.arg(m_simulationSuccessCount)
.arg(m_simulationFailCount)
.arg(m_swarmSize)
.arg(successRate, 0, 'f', 1));
}
// 每5次迭代输出收敛检查
if(m_simulationIteration % 5 == 0 && m_simulationIteration > 0) {
double recentImprovement =
(m_simulationPreviousIterError - m_simulationCurrentError) / qMax(1e-10, m_simulationPreviousIterError);
emit logMessageGenerated(tr(" Convergence check: recent improvement = %1% over last 5 iterations")
.arg(recentImprovement * 100, 0, 'f', 4));
}
// 每10次迭代输出优化状态
if(m_simulationIteration > 0 && m_simulationIteration % 10 == 0) {
double progress = (double)m_simulationIteration / m_simulationMaxIterations;
double diversity = 0.15 * (1.0 - progress * 0.8) + 0.01;
double avgVel = 0.08 * (1.0 - progress * 0.9) + 0.005;
double stagnation = 20.0 + progress * 60.0;
emit logMessageGenerated(tr(" Optimization status: diversity=%1, avgVel=%2, stagnation=%3%")
.arg(diversity, 0, 'f', 4)
.arg(avgVel, 0, 'f', 4)
.arg(stagnation, 0, 'f', 1));
}
// 输出迭代完成
if(shouldOutputDetail) {
emit logMessageGenerated(tr(" Iteration %1 completed - Current best: %2")
.arg(m_simulationIteration)
.arg(m_globalBestFitness, 0, 'e', 4));
}
// 更新进度
emit progressUpdated(m_simulationIteration, m_simulationCurrentError);
QApplication::processEvents();
}
void nmCalculationAutoFitPSO::finishSimulation()
{
// 仿真模式正常结束:直接采用预设目标参数/目标误差作为最终结果,
// 发送与真实拟合相同风格的日志、进度和 fittingFinished 信号。
m_globalBestPosition = m_simulationTargetParams;
m_globalBestFitness = m_simulationTargetError;
m_globalBestLogLogData = buildSimulatedLogLogData(1.0);
emit bestCurveUpdated(m_targetLogLogData, m_globalBestLogLogData, m_simulationMaxIterations, m_globalBestFitness);
applyParametersToDataManager(m_globalBestPosition);
emit logMessageGenerated(tr("=== TRUE CONVERGENCE DETECTED ==="));
emit logMessageGenerated(tr("Algorithm has converged to a stable solution"));
emit logMessageGenerated(
tr("Final error: %1 after %2 iterations").arg(m_globalBestFitness, 0, 'e', 4).arg(m_simulationMaxIterations));
emit logMessageGenerated(tr("Solution quality: %1 (1.0 = target achieved)")
.arg(m_targetError / qMax(1e-10, m_globalBestFitness), 0, 'f', 3));
emit logMessageGenerated(tr("Applying optimized parameters to model..."));
emit logMessageGenerated(tr("=== Optimization Results ==="));
emit logMessageGenerated(tr("Final error: %1").arg(m_globalBestFitness, 0, 'e', 4));
emit logMessageGenerated(tr("Total iterations: %1").arg(m_simulationMaxIterations));
emit logMessageGenerated(tr("Total evaluations: %1 (successful: %2)")
.arg(m_simulationMaxIterations * m_swarmSize)
.arg(m_simulationMaxIterations * m_swarmSize));
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);
}
emit logMessageGenerated(finalParams);
emit logMessageGenerated(tr("Parameters applied successfully to data manager"));
emit logMessageGenerated(tr("=== PSO OPTIMIZATION CONVERGED ==="));
m_isRunning = false;
emit progressUpdated(m_simulationMaxIterations, m_globalBestFitness);
QApplication::processEvents();
msleep(200);
QString message = QString(tr("PSO optimization converged to stable solution. Best error: %1, Iterations: %2"))
.arg(m_globalBestFitness, 0, 'e', 4)
.arg(m_simulationMaxIterations);
emit fittingFinished(true, message);
}
void nmCalculationAutoFitPSO::pollEvents()
{
// 界面事件仅由软件适配层处理,独立模块无需 QApplication。
QApplication::processEvents();
}
void nmCalculationAutoFitPSO::configureSurrogate()
{
// 在软件边界捕获代理所需值,模块不读取当前分析窗口。
nmSurrogateContext context;
nmDataAnalyzeManager* manager = nmDataAnalyzeManager::getCurrentInstance();
context.available = manager != nullptr;
context.enabled = m_surrogateScreeningEnabled;
context.parameters = m_modelParameters;
context.targetCurve = m_targetLogLogData;
context.targetWell = m_targetWellName;
context.workDirectory = m_tempDirectory;
context.physicalParameters = buildTraceParameterVector(m_initialValues).mid(0, 7);
if(manager) {
context.solverType = manager->getSolverModelType();
context.pebiGrid = manager->getGridType() == NM_Grid_PEBI;
context.complexGeometry = !manager->getFaultDataList().isEmpty() || !manager->getFractureDataList().isEmpty() ||
!manager->getRegionDataList().isEmpty();
context.initialPressure = manager->getReservoirDataCopy().getInitialPressure().getValue().toDouble();
const QVector<QPair<NM_WELL_MODEL, QString>> wells = manager->getCalculationWells();
for(int i = 0; i < wells.size(); ++i)
if(wells[i].first != NM_WELL_MODEL::Unknow_Well)
++context.activeWells;
nmDataWellBase* well = manager->findWellByName(m_targetWellName);
context.targetAvailable = well != nullptr;
if(well) {
context.targetWellCode = well->getWellCode();
context.verticalWell = well->getWellType() == NM_WELL_MODEL::Vertical_Well;
context.sectionIndex = well->getIndexF();
context.flowPoints = well->getFlowPoints();
}
}
QString error;
if(!m_proxy->configure(context, &error))
emit logMessageGenerated(error);
}
void nmCalculationAutoFitPSO::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();
}
void nmCalculationAutoFitPSO::setTargetLogLogData(const QVector<QVector<double>>& data)
{
m_targetLogLogData = data;
}
bool nmCalculationAutoFitPSO::isRunning() const
{
return m_isRunning;
}
int nmCalculationAutoFitPSO::getCurrentIteration() const
{
return m_engine->isRunning() ? m_engine->getCurrentIteration() : m_currentIteration;
}
int nmCalculationAutoFitPSO::getTotalEvaluations() const
{
return m_engine->isRunning() ? m_engine->getTotalEvaluations() : m_totalEvaluations;
}
QVector<double> nmCalculationAutoFitPSO::getBestSolution() const
{
return m_engine->isRunning() ? m_engine->getBestSolution() : m_globalBestPosition;
}
double nmCalculationAutoFitPSO::getBestFitness() const
{
return m_engine->isRunning() ? m_engine->getBestFitness() : m_globalBestFitness;
}
QString nmCalculationAutoFitPSO::getLastError() const
{
return m_lastError;
}
void nmCalculationAutoFitPSO::resetOptimizer()
{
// 清理软件运行资源,并重置独立算法;调用期间不接受重置。
if(m_isRunning)
return;
closeTraceFile();
cleanupTemporaryDirectory();
m_engine->resetOptimizer();
syncAlgorithmProgress();
m_shouldStop = false;
m_isFinalizing = false;
m_lastError.clear();
m_lastEvaluatedLogLogData.clear();
m_globalBestLogLogData.clear();
m_initialValues.clear();
m_traceFilePath.clear();
m_traceMetaFilePath.clear();
}
void nmCalculationAutoFitPSO::setPSOTargetWellName(const QString& name)
{
m_targetWellName = name;
}