feat: 支持 PSO 多井拟合并完善中文日志

feature/AutoFit-Refactor-20261105
lvjunjie 4 weeks ago
parent b09f5c68f8
commit 19a72eed04

Binary file not shown.

@ -483,7 +483,7 @@ Reason: %1</source>
</message>
<message>
<source> Particle %1: no improvement (Error: %2)</source>
<translation>粒子 %1:无改进</translation>
<translation>粒子 %1:无改进(误差:%2)</translation>
</message>
<message>
<source> Better solution found: %1</source>
@ -661,6 +661,246 @@ Reason: %1</source>
<source>ERROR: %1</source>
<translation>错误:%1</translation>
</message>
<message>
<source>ERROR: Final full-field calculation failed</source>
<translation>错误:最终全场计算失败</translation>
</message>
<message>
<source>Final full-field calculation completed successfully</source>
<translation>最终全场计算成功完成</translation>
</message>
<message>
<source>Optimized parameters applied to data manager</source>
<translation>优化参数已写入数据管理器</translation>
</message>
<message>
<source>Optimized parameters were found, but the final full-field calculation failed</source>
<translation>已获得优化参数,但最终全场计算失败</translation>
</message>
<message>
<source>Parameters and full-field results applied successfully to data manager</source>
<translation>参数及全场计算结果已成功写入数据管理器</translation>
</message>
<message>
<source>Running final full-field calculation with optimized parameters...</source>
<translation>正在使用优化参数进行最终全场计算……</translation>
</message>
<message>
<source>Surrogate model prewarm deferred: %1</source>
<translation>代理模型预热已延后:%1</translation>
</message>
<message>
<source>Surrogate model prewarming started in background</source>
<translation>代理模型已在后台开始预热</translation>
</message>
<message>
<source>Surrogate screening iteration %1: selected %2/%3 particles (keep=%4, audit=%5, min_solver=%6, fallback=%7, domain=%8, guide_pbest=%9)</source>
<translation>代理筛选第 %1 代:选中 %2/%3 个粒子(保留比例=%4,抽查比例=%5,最小真实求解比例=%6,回退=%7,训练域限制=%8,引导个体最优=%9)</translation>
</message>
<message>
<source>The final full-field calculation failed</source>
<translation>最终全场计算失败</translation>
</message>
<message>
<source>SUCCESS</source>
<translation>成功</translation>
</message>
<message>
<source>FAILED</source>
<translation>失败</translation>
</message>
<message>
<source>Disabled by configuration</source>
<translation>已在配置中关闭</translation>
</message>
<message>
<source>Passed</source>
<translation>通过</translation>
</message>
<message>
<source>Unknown</source>
<translation>未知</translation>
</message>
<message>
<source>failed - %1</source>
<translation>未通过:%1</translation>
</message>
<message>
<source>surrogate context file is missing</source>
<translation>缺少代理模型运行上下文文件</translation>
</message>
<message>
<source>surrogate scoring server script not found: %1</source>
<translation>未找到代理评分服务脚本:%1</translation>
</message>
<message>
<source>failed to start scoring server: python=%1, script=%2, error=%3</source>
<translation>评分服务启动失败:Python=%1,脚本=%2,错误=%3</translation>
</message>
<message>
<source>scoring server exited before ready: stdout=%1, stderr=%2</source>
<translation>评分服务在就绪前退出:标准输出=%1,错误输出=%2</translation>
</message>
<message>
<source>scoring server failed during initialization: %1</source>
<translation>评分服务初始化失败:%1</translation>
</message>
<message>
<source>scoring server ready timeout: stderr=%1</source>
<translation>等待评分服务就绪超时:错误输出=%1</translation>
</message>
<message>
<source>failed to send scoring request to server: written=%1 expected=%2 error=%3</source>
<translation>向评分服务发送请求失败:已写入=%1,预期=%2,错误=%3</translation>
</message>
<message>
<source>scoring server exited during request: stdout=%1, stderr=%2</source>
<translation>评分服务在处理请求时退出:标准输出=%1,错误输出=%2</translation>
</message>
<message>
<source>scoring server reported success but score file is missing: %1</source>
<translation>评分服务报告成功,但评分文件不存在:%1</translation>
</message>
<message>
<source>scoring server request failed: %1</source>
<translation>评分服务请求失败:%1</translation>
</message>
<message>
<source>scoring server request timed out</source>
<translation>评分服务请求超时</translation>
</message>
<message>
<source>surrogate scoring script not found: %1</source>
<translation>未找到代理评分脚本:%1</translation>
</message>
<message>
<source>failed to start scoring process (attempt %1/%2): python=%3, script=%4, error=%5</source>
<translation>评分进程启动失败(第 %1/%2 次尝试):Python=%3,脚本=%4,错误=%5</translation>
</message>
<message>
<source>scoring process timed out (attempt %1/%2): python=%3, script=%4, stdout=%5, stderr=%6</source>
<translation>评分进程超时(第 %1/%2 次尝试):Python=%3,脚本=%4,标准输出=%5,错误输出=%6</translation>
</message>
<message>
<source>scoring process failed (attempt %1/%2): exitStatus=%3, exitCode=%4, python=%5, script=%6, stdout=%7, stderr=%8</source>
<translation>评分进程失败(第 %1/%2 次尝试):退出状态=%3,退出码=%4,Python=%5,脚本=%6,标准输出=%7,错误输出=%8</translation>
</message>
<message>
<source>scoring process finished without a usable score file (attempt %1/%2): output=%3, stdout=%4, stderr=%5</source>
<translation>评分进程结束但未生成可用评分文件(第 %1/%2 次尝试):输出文件=%3,标准输出=%4,错误输出=%5</translation>
</message>
<message>
<source>data manager is unavailable</source>
<translation>数据管理器不可用</translation>
</message>
<message>
<source>solverType=%1 is outside the T1-T5 surrogate model</source>
<translation>求解器类型 %1 不在 T1–T5 代理模型的支持范围内</translation>
</message>
<message>
<source>surrogate model is trained only for PEBI grid cases</source>
<translation>代理模型仅使用 PEBI 网格工况训练</translation>
</message>
<message>
<source>target well &apos;%1&apos; is missing</source>
<translation>目标井“%1”不存在</translation>
</message>
<message>
<source>surrogate model is currently limited to vertical-well cases</source>
<translation>代理模型目前仅支持直井工况</translation>
</message>
<message>
<source>surrogate model expects one active calculation well, got %1</source>
<translation>代理模型要求仅有一口有效计算井,当前为 %1 口</translation>
</message>
<message>
<source>surrogate model is not enabled for changed fault/fracture/region geometry</source>
<translation>断层、裂缝或区域几何发生变化时不启用代理模型</translation>
</message>
<message>
<source>parameter &apos;%1&apos; is outside surrogate input set</source>
<translation>参数“%1”不在代理模型输入范围内</translation>
</message>
<message>
<source>Ct=%1 does not match surrogate training value %2</source>
<translation>Ct=%1 与代理模型训练值 %2 不一致</translation>
</message>
<message>
<source>Cf=%1 is outside surrogate domain</source>
<translation>Cf=%1 超出代理模型训练范围</translation>
</message>
<message>
<source>initialPressure=%1 does not match surrogate training context</source>
<translation>初始压力 %1 与代理模型训练工况不一致</translation>
</message>
<message>
<source>flow schedule is too short for surrogate screening</source>
<translation>流量制度段数不足,无法进行代理筛选</translation>
</message>
<message>
<source>production section count %1 is outside surrogate range [%2,%3]</source>
<translation>生产段数 %1 超出代理模型范围 [%2,%3]</translation>
</message>
<message>
<source>production schedule section %1 is outside surrogate dt/q domain</source>
<translation>生产制度第 %1 段的时长或产量超出代理模型训练范围</translation>
</message>
<message>
<source>rate step ratio %1 exceeds surrogate domain</source>
<translation>相邻生产段的产量变化比 %1 超出代理模型训练范围</translation>
</message>
<message>
<source>strongly decreasing production schedule ratio %1 is outside surrogate domain</source>
<translation>强递减生产制度的末段与首段产量比 %1 超出代理模型训练范围</translation>
</message>
<message>
<source>production total time %1 is outside surrogate range</source>
<translation>总生产时长 %1 超出代理模型训练范围</translation>
</message>
<message>
<source>last flow section is not a trained shut-in section</source>
<translation>最后一个流量段不符合训练数据中的关井段条件</translation>
</message>
<message>
<source>target section index %1 is not the last section %2</source>
<translation>目标段索引 %1 不是最后一段 %2</translation>
</message>
<message>
<source>Failed to load configuration from data manager</source>
<translation>从数据管理器加载配置失败</translation>
</message>
<message>
<source>Auto fitting is already running</source>
<translation>自动拟合正在运行</translation>
</message>
<message>
<source>No parameters enabled for optimization</source>
<translation>未选择参与优化的参数</translation>
</message>
<message>
<source>Target LogLog data is empty or insufficient</source>
<translation>目标双对数数据为空或不足</translation>
</message>
<message>
<source>Target LogLog data arrays have inconsistent sizes</source>
<translation>目标双对数数据各列长度不一致</translation>
</message>
<message>
<source>Too many consecutive failed iterations (%1)</source>
<translation>连续失败的迭代次数过多(%1 次)</translation>
</message>
<message>
<source>Failed to apply final parameters: %1</source>
<translation>写入最终参数失败:%1</translation>
</message>
<message>
<source>Failed to apply final parameters due to unknown error</source>
<translation>写入最终参数时发生未知错误</translation>
</message>
<message>
<source>&lt;empty&gt;</source>
<translation>〈空〉</translation>
</message>
</context>
<context>
<name>nmCalculationAutoFitLM</name>

@ -11,6 +11,7 @@
#include <QFile>
#include "nmCalculation_global.h"
#include "nmDataAutomaticFitting.h"
// 前向声明
class nmCalculationDllPebiSolverTask;
@ -20,7 +21,7 @@ class QProcess;
// PSO粒子结构
// 这里的 position / velocity / bestPosition 只保存“用户勾选参与拟合的参数”,
// 拟合参数为 k/skin/wellboreC/phi。包含固定储层输入的物理参数向量在写 trace 或调用代理模型时
// 拟合参数为 k/skin/wellboreC/phi/Dfc/裂缝半长。包含固定储层输入的物理参数向量在写 trace 或调用代理模型时
// 通过 buildTraceParameterVector() 重新组装。
//
// surrogate* 和 screeningDecision 是 PSO 加速筛选的辅助字段。真实 pbest / gbest
@ -156,11 +157,9 @@ private:
//
// 每次评价粒子前,都会把该粒子的参数临时写入 DataManager:
// - 储层参数写入 nmDataReservoir;
// - 井参数(skin / wellbore storage)写入目标井。
// - 井参数(skin / wellbore storage / Dfc / 裂缝半长)按井编码写入各自所属井。
// 求解器随后基于 DataManager 的当前状态计算模拟曲线。
void applyParametersToDataManager(const QVector<double>& parameters);
void updateReservoirParameters(const QVector<double>& parameters);
void updateWellParameters(const QVector<double>& parameters);
// ===== 求解器相关 =====
QVector<QVector<double> > runSolver();
@ -293,16 +292,17 @@ private:
// ===== 优化配置 =====
//
// 参数索引约定:
// 参数类型约定(与列表位置无关):
// 0 k 渗透率;1 skin 表皮系数;2 wellboreC 井筒储集;
// 3 phi 孔隙度。
// 3 phi 孔隙度;4 Dfc 裂缝导流能力;5 裂缝半长。
// m_enabledParamIndices 保存被用户勾选的参数索引,粒子的 position 维度与它一致。
QVector<bool> m_parameterSelected; // 0 k,1 skin,2 wellboreC,3 phi。
QVector<double> m_parameterLower; // 5 个拟合参数的搜索下界。
QVector<double> m_parameterUpper; // 5 个拟合参数的搜索上界。
QVector<int> m_enabledParamIndices; // 被勾选参数在 5 维拟合参数中的索引。
QVector<nmFitParameter> m_modelParameters; // 按井分组的完整参数列表,储层参数共享。
QVector<bool> m_parameterSelected; // 每项参数的勾选状态。
QVector<double> m_parameterLower; // 完整参数列表的搜索下界。
QVector<double> m_parameterUpper; // 完整参数列表的搜索上界。
QVector<int> m_enabledParamIndices; // 被勾选参数在完整列表中的索引。
QVector<QVector<double> > m_targetLogLogData; // 目标井 history log-log 曲线:time/pressure/derivative。
QString m_targetWellName; // 目标井名称;读写井参数和读取模拟曲线都依赖它。
QString m_targetWellName; // 目标井名称;用于读取模拟曲线并计算误差。
// ===== 算法配置 =====
int m_swarmSize; // 粒子数量,当前默认 20。

@ -426,13 +426,15 @@ static QString findExecutableInPath(const QString& executableName)
static QStringList traceParameterNames()
{
// 拟合参数顺序与 m_parameterSelected 的 0-3 索引一致。
// 参数类型名称供代理模型的输入限制提示使用,不代表多井列表位置。
// 代理输入仍使用 buildTraceParameterVector() 的物理参数顺序。
QStringList names;
names << "k"
<< "skin"
<< "wellboreC"
<< "phi";
<< "phi"
<< "Dfc"
<< "fractureHalfLength";
return names;
}
@ -842,7 +844,7 @@ void nmCalculationAutoFitPSO::captureSurrogateRunContextSummary()
if(isSurrogateRunContextSupported(&contextReason)) {
m_surrogateRunContextSummary = "passed";
} else {
m_surrogateRunContextSummary = QString("failed - %1").arg(contextReason);
m_surrogateRunContextSummary = tr("failed - %1").arg(contextReason);
}
}
@ -850,18 +852,23 @@ void nmCalculationAutoFitPSO::emitRunSummary(bool success, StopReasonPSO finalRe
{
// 运行结束时输出一组交接/排障最有用的摘要:
// 真实求解次数、成功失败数、代理模型启用情况、各类筛选决策计数,以及 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(getStopReasonDescription(finalReason)));
emit logMessageGenerated(tr("Result: %1, final error=%2, iterations=%3, evaluations=%4 (successful=%5, failed=%6)")
.arg(success ? "SUCCESS" : "FAILED")
.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() ? "enabled" : "disabled")
.arg(m_surrogateRunContextSummary.isEmpty() ? QString("unknown") : m_surrogateRunContextSummary));
.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_surrogateActiveIterationCount)
.arg(m_surrogateWarmupIterationCount)
@ -900,7 +907,7 @@ void nmCalculationAutoFitPSO::closeTraceFile()
void nmCalculationAutoFitPSO::writeTraceHeader()
{
// trace CSV 字段说明:
// - 当前粒子参数只记录代理模型关心的 k/skin/wellboreC/phi/h/Ct/Cf;
// - 当前粒子参数记录 k/skin/wellboreC/phi/h/Ct/Cf 及压裂井的 Dfc/裂缝半长;
// - solver_objective 是真实求解器误差;
// - surrogate_objective 是 Python 代理评分;
// - screening_decision 说明该粒子为什么跑/不跑真实求解器;
@ -921,6 +928,8 @@ void nmCalculationAutoFitPSO::writeTraceHeader()
<< "h"
<< "Ct"
<< "Cf"
<< "Dfc"
<< "fractureHalfLength"
<< "solver_objective"
<< "solver_success"
<< "elapsed_ms"
@ -934,6 +943,8 @@ void nmCalculationAutoFitPSO::writeTraceHeader()
<< "pbest_h"
<< "pbest_Ct"
<< "pbest_Cf"
<< "pbest_Dfc"
<< "pbest_fractureHalfLength"
<< "gbest_objective"
<< "gbest_k"
<< "gbest_skin"
@ -942,7 +953,12 @@ void nmCalculationAutoFitPSO::writeTraceHeader()
<< "gbest_h"
<< "gbest_Ct"
<< "gbest_Cf"
<< "enabled_param_indices";
<< "gbest_Dfc"
<< "gbest_fractureHalfLength"
<< "enabled_param_indices"
<< "selected_parameters"
<< "pbest_selected_parameters"
<< "gbest_selected_parameters";
QTextStream out(&m_traceFile);
out << cols.join(",") << "\n";
@ -967,16 +983,23 @@ bool nmCalculationAutoFitPSO::writeTraceMetaFile(const QString& filePath)
nmDataAnalyzeManager* dataManager = nmDataAnalyzeManager::getCurrentInstance();
nmDataWellBase* pTargetWell = dataManager ? dataManager->findWellByName(m_targetWellName) : nullptr;
QStringList parameterNames = traceParameterNames();
// 元数据按完整参数列表记录井编码,避免不同井的同名参数混淆。
QStringList parameterNames, wellCodes;
QVector<int> parameterTypes;
QVector<double> initialFullParams;
for(int i = 0; i < m_modelParameters.size(); ++i) {
const nmFitParameter& 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) {
int paramIndex = m_enabledParamIndices[i];
enabledNames << ((paramIndex >= 0 && paramIndex < parameterNames.size()) ? parameterNames[paramIndex] : QString::number(paramIndex));
const int index = m_enabledParamIndices[i];
enabledNames << parameterNames[index];
initialFullParams[index] = m_initialValues[i];
}
QVector<double> initialPhysicalParams = buildTraceParameterVector(m_initialValues);
QVector<double> initialFullParams = initialPhysicalParams.mid(0, 4);
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>();
@ -984,7 +1007,7 @@ bool nmCalculationAutoFitPSO::writeTraceMetaFile(const QString& filePath)
QTextStream out(&metaFile);
out << "{\n";
out << " \"schema_version\": 2,\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";
@ -1022,6 +1045,8 @@ bool nmCalculationAutoFitPSO::writeTraceMetaFile(const QString& filePath)
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";
@ -1043,10 +1068,10 @@ bool nmCalculationAutoFitPSO::writeTraceMetaFile(const QString& filePath)
QVector<double> nmCalculationAutoFitPSO::buildTraceParameterVector(const QVector<double>& selectedParameters) const
{
// 代理输入保留 k/skin/wellboreC/phi/h/Ct/Cf 的 7 维物理参数顺序。
// h/Ct/Cf 始终读取储层固定值,仅用候选值覆盖剩余拟合参数。
// 前七项保留代理输入的 k/skin/wellboreC/phi/h/Ct/Cf 顺序,末尾追加 Dfc 和裂缝半长。
// h/Ct/Cf 始终读取储层固定值,裂缝参数只用于真实求解和追踪记录。
// trace CSV、候选 CSV、代理训练域检查都需要这个完整向量。
QVector<double> fullParams(7, 0.0);
QVector<double> fullParams(9, 0.0);
nmDataAnalyzeManager* dataManager = nmDataAnalyzeManager::getCurrentInstance();
@ -1061,16 +1086,29 @@ QVector<double> nmCalculationAutoFitPSO::buildTraceParameterVector(const QVector
nmDataWellBase* pTargetWell = dataManager->findWellByName(m_targetWellName);
if(pTargetWell) {
fullParams[1] = pTargetWell->getPerforation(0)->getSkin().getValue().toDouble();
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];
if(paramIndex >= 0 && paramIndex < m_parameterSelected.size()) {
fullParams[paramIndex] = selectedParameters[i];
const nmFitParameter& 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];
}
}
@ -1118,6 +1156,8 @@ void nmCalculationAutoFitPSO::writeTraceRow(int generation,
<< 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)
@ -1131,6 +1171,8 @@ void nmCalculationAutoFitPSO::writeTraceRow(int generation,
<< traceParamAt(pbestParams, 4)
<< traceParamAt(pbestParams, 5)
<< traceParamAt(pbestParams, 6)
<< traceParamAt(pbestParams, 7)
<< traceParamAt(pbestParams, 8)
<< traceNumber(m_globalBestFitness)
<< traceParamAt(gbestParams, 0)
<< traceParamAt(gbestParams, 1)
@ -1139,7 +1181,12 @@ void nmCalculationAutoFitPSO::writeTraceRow(int generation,
<< traceParamAt(gbestParams, 4)
<< traceParamAt(gbestParams, 5)
<< traceParamAt(gbestParams, 6)
<< csvEscape(enabledIndices.join(";"));
<< 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";
@ -1399,7 +1446,7 @@ bool nmCalculationAutoFitPSO::ensureSurrogateScoringServer(QString* failureReaso
// 只要其中任何一个变化,就停止旧进程并启动新进程,避免拿旧模型或旧目标曲线评分。
if(m_surrogateContextFilePath.isEmpty() ||
!QFileInfo(m_surrogateContextFilePath).exists()) {
QString reason = "surrogate context file is missing";
QString reason = tr("surrogate context file is missing");
DEBUG_OUT(QString("Surrogate scoring server skipped: %1").arg(reason));
if(failureReason) {
@ -1413,7 +1460,7 @@ bool nmCalculationAutoFitPSO::ensureSurrogateScoringServer(QString* failureReaso
QString scriptPath = QDir(mlRoot).absoluteFilePath("scripts/score_pso_candidates_server.py");
if(!QFileInfo(scriptPath).exists()) {
QString reason = QString("surrogate scoring server script not found: %1").arg(scriptPath);
QString reason = tr("surrogate scoring server script not found: %1").arg(scriptPath);
DEBUG_OUT(reason);
if(failureReason) {
@ -1456,7 +1503,7 @@ bool nmCalculationAutoFitPSO::ensureSurrogateScoringServer(QString* failureReaso
m_surrogateScoringProcess->start(pythonPath, args);
if(!m_surrogateScoringProcess->waitForStarted(15000)) {
QString reason = QString("failed to start scoring server: python=%1, script=%2, error=%3")
QString reason = tr("failed to start scoring server: python=%1, script=%2, error=%3")
.arg(pythonPath)
.arg(scriptPath)
.arg(m_surrogateScoringProcess->errorString());
@ -1494,9 +1541,9 @@ bool nmCalculationAutoFitPSO::ensureSurrogateScoringServer(QString* failureReaso
if(m_surrogateScoringProcess->state() != QProcess::Running) {
QString stdOut = QString::fromLocal8Bit(m_surrogateScoringProcess->readAllStandardOutput()).trimmed();
QString stdErr = QString::fromLocal8Bit(m_surrogateScoringProcess->readAllStandardError()).trimmed();
QString reason = QString("scoring server exited before ready: stdout=%1, stderr=%2")
.arg(stdOut.isEmpty() ? QString("<empty>") : stdOut)
.arg(stdErr.isEmpty() ? QString("<empty>") : stdErr);
QString reason = tr("scoring server exited before ready: stdout=%1, stderr=%2")
.arg(stdOut.isEmpty() ? tr("<empty>") : stdOut)
.arg(stdErr.isEmpty() ? tr("<empty>") : stdErr);
DEBUG_OUT(reason);
stopSurrogateScoringServer();
@ -1527,7 +1574,7 @@ bool nmCalculationAutoFitPSO::ensureSurrogateScoringServer(QString* failureReaso
}
if(readyLine.contains("\"ok\"") && readyLine.contains("false")) {
QString reason = QString("scoring server failed during initialization: %1").arg(QString::fromLocal8Bit(readyLine));
QString reason = tr("scoring server failed during initialization: %1").arg(QString::fromLocal8Bit(readyLine));
DEBUG_OUT(reason);
stopSurrogateScoringServer();
@ -1540,8 +1587,8 @@ bool nmCalculationAutoFitPSO::ensureSurrogateScoringServer(QString* failureReaso
}
QString stdErr = QString::fromLocal8Bit(m_surrogateScoringProcess->readAllStandardError()).trimmed();
QString reason = QString("scoring server ready timeout: stderr=%1")
.arg(stdErr.isEmpty() ? QString("<empty>") : stdErr);
QString reason = tr("scoring server ready timeout: stderr=%1")
.arg(stdErr.isEmpty() ? tr("<empty>") : stdErr);
DEBUG_OUT(reason);
stopSurrogateScoringServer();
@ -1571,7 +1618,7 @@ bool nmCalculationAutoFitPSO::requestSurrogateScoresFromServer(const QString& ca
qint64 written = m_surrogateScoringProcess->write(bytes);
if(written != bytes.size() || !m_surrogateScoringProcess->waitForBytesWritten(10000)) {
QString reason = QString("failed to send scoring request to server: written=%1 expected=%2 error=%3")
QString reason = tr("failed to send scoring request to server: written=%1 expected=%2 error=%3")
.arg(written)
.arg(bytes.size())
.arg(m_surrogateScoringProcess->errorString());
@ -1592,9 +1639,9 @@ bool nmCalculationAutoFitPSO::requestSurrogateScoresFromServer(const QString& ca
if(m_surrogateScoringProcess->state() != QProcess::Running) {
QString stdOut = QString::fromLocal8Bit(m_surrogateScoringProcess->readAllStandardOutput()).trimmed();
QString stdErr = QString::fromLocal8Bit(m_surrogateScoringProcess->readAllStandardError()).trimmed();
QString reason = QString("scoring server exited during request: stdout=%1, stderr=%2")
.arg(stdOut.isEmpty() ? QString("<empty>") : stdOut)
.arg(stdErr.isEmpty() ? QString("<empty>") : stdErr);
QString reason = tr("scoring server exited during request: stdout=%1, stderr=%2")
.arg(stdOut.isEmpty() ? tr("<empty>") : stdOut)
.arg(stdErr.isEmpty() ? tr("<empty>") : stdErr);
DEBUG_OUT(reason);
if(failureReason) {
@ -1626,7 +1673,7 @@ bool nmCalculationAutoFitPSO::requestSurrogateScoresFromServer(const QString& ca
return true;
}
QString reason = QString("scoring server reported success but score file is missing: %1").arg(scorePath);
QString reason = tr("scoring server reported success but score file is missing: %1").arg(scorePath);
DEBUG_OUT(reason);
if(failureReason) {
@ -1637,7 +1684,7 @@ bool nmCalculationAutoFitPSO::requestSurrogateScoresFromServer(const QString& ca
}
if(line.contains("\"ok\"") && line.contains("false")) {
QString reason = QString("scoring server request failed: %1").arg(line);
QString reason = tr("scoring server request failed: %1").arg(line);
DEBUG_OUT(reason);
if(failureReason) {
@ -1648,7 +1695,7 @@ bool nmCalculationAutoFitPSO::requestSurrogateScoresFromServer(const QString& ca
}
}
QString reason = "scoring server request timed out";
QString reason = tr("scoring server request timed out");
DEBUG_OUT(reason);
if(failureReason) {
@ -1698,7 +1745,7 @@ bool nmCalculationAutoFitPSO::runSurrogateScoringScriptOnce(const QString& candi
// - scorePath:Python 写出的评分 CSV,随后由 readSurrogateScores() 读取。
if(m_surrogateContextFilePath.isEmpty() ||
!QFileInfo(m_surrogateContextFilePath).exists()) {
QString reason = "surrogate context file is missing";
QString reason = tr("surrogate context file is missing");
DEBUG_OUT(QString("Surrogate scoring skipped: %1").arg(reason));
if(failureReason) {
@ -1712,7 +1759,7 @@ bool nmCalculationAutoFitPSO::runSurrogateScoringScriptOnce(const QString& candi
QString scriptPath = QDir(mlRoot).absoluteFilePath("scripts/score_pso_candidates.py");
if(!QFileInfo(scriptPath).exists()) {
QString reason = QString("surrogate scoring script not found: %1").arg(scriptPath);
QString reason = tr("surrogate scoring script not found: %1").arg(scriptPath);
DEBUG_OUT(reason);
if(failureReason) {
@ -1748,7 +1795,7 @@ bool nmCalculationAutoFitPSO::runSurrogateScoringScriptOnce(const QString& candi
process.start(pythonPath, args);
if(!process.waitForStarted(10000)) {
lastFailure = QString("failed to start scoring process (attempt %1/%2): python=%3, script=%4, error=%5")
lastFailure = tr("failed to start scoring process (attempt %1/%2): python=%3, script=%4, error=%5")
.arg(attempt)
.arg(kSurrogateScoringMaxAttempts)
.arg(pythonPath)
@ -1774,13 +1821,13 @@ bool nmCalculationAutoFitPSO::runSurrogateScoringScriptOnce(const QString& candi
process.waitForFinished(3000);
QString stdOut = QString::fromLocal8Bit(process.readAllStandardOutput()).trimmed();
QString stdErr = QString::fromLocal8Bit(process.readAllStandardError()).trimmed();
lastFailure = QString("scoring process timed out (attempt %1/%2): python=%3, script=%4, stdout=%5, stderr=%6")
lastFailure = tr("scoring process timed out (attempt %1/%2): python=%3, script=%4, stdout=%5, stderr=%6")
.arg(attempt)
.arg(kSurrogateScoringMaxAttempts)
.arg(pythonPath)
.arg(scriptPath)
.arg(stdOut.isEmpty() ? QString("<empty>") : stdOut)
.arg(stdErr.isEmpty() ? QString("<empty>") : stdErr);
.arg(stdOut.isEmpty() ? tr("<empty>") : stdOut)
.arg(stdErr.isEmpty() ? tr("<empty>") : stdErr);
DEBUG_OUT(lastFailure);
if(attempt < kSurrogateScoringMaxAttempts) {
@ -1800,15 +1847,15 @@ bool nmCalculationAutoFitPSO::runSurrogateScoringScriptOnce(const QString& candi
QString stdErr = QString::fromLocal8Bit(process.readAllStandardError()).trimmed();
if(process.exitStatus() != QProcess::NormalExit || process.exitCode() != 0) {
lastFailure = QString("scoring process failed (attempt %1/%2): exitStatus=%3, exitCode=%4, python=%5, script=%6, stdout=%7, stderr=%8")
lastFailure = tr("scoring process failed (attempt %1/%2): exitStatus=%3, exitCode=%4, python=%5, script=%6, stdout=%7, stderr=%8")
.arg(attempt)
.arg(kSurrogateScoringMaxAttempts)
.arg(process.exitStatus() == QProcess::NormalExit ? "NormalExit" : "CrashExit")
.arg(process.exitCode())
.arg(pythonPath)
.arg(scriptPath)
.arg(stdOut.isEmpty() ? QString("<empty>") : stdOut)
.arg(stdErr.isEmpty() ? QString("<empty>") : stdErr);
.arg(stdOut.isEmpty() ? tr("<empty>") : stdOut)
.arg(stdErr.isEmpty() ? tr("<empty>") : stdErr);
DEBUG_OUT(lastFailure);
if(attempt < kSurrogateScoringMaxAttempts) {
@ -1827,12 +1874,12 @@ bool nmCalculationAutoFitPSO::runSurrogateScoringScriptOnce(const QString& candi
QFileInfo scoreInfo(scorePath);
if(!scoreInfo.exists() || scoreInfo.size() <= 0) {
lastFailure = QString("scoring process finished without a usable score file (attempt %1/%2): output=%3, stdout=%4, stderr=%5")
lastFailure = tr("scoring process finished without a usable score file (attempt %1/%2): output=%3, stdout=%4, stderr=%5")
.arg(attempt)
.arg(kSurrogateScoringMaxAttempts)
.arg(scorePath)
.arg(stdOut.isEmpty() ? QString("<empty>") : stdOut)
.arg(stdErr.isEmpty() ? QString("<empty>") : stdErr);
.arg(stdOut.isEmpty() ? tr("<empty>") : stdOut)
.arg(stdErr.isEmpty() ? tr("<empty>") : stdErr);
DEBUG_OUT(lastFailure);
if(attempt < kSurrogateScoringMaxAttempts) {
@ -1925,7 +1972,7 @@ bool nmCalculationAutoFitPSO::isSurrogateRunContextSupported(QString* reason) co
nmDataAnalyzeManager* dataManager = nmDataAnalyzeManager::getCurrentInstance();
if(!dataManager) {
if(reason) *reason = "data manager is unavailable";
if(reason) *reason = tr("data manager is unavailable");
return false;
}
@ -1936,7 +1983,7 @@ bool nmCalculationAutoFitPSO::isSurrogateRunContextSupported(QString* reason) co
if(!isSupportedSolverType) {
if(reason) {
*reason = QString("solverType=%1 is outside the T1-T5 surrogate model")
*reason = tr("solverType=%1 is outside the T1-T5 surrogate model")
.arg(static_cast<int>(solverModelType));
}
return false;
@ -1944,7 +1991,7 @@ bool nmCalculationAutoFitPSO::isSurrogateRunContextSupported(QString* reason) co
// 网格类型 gate:当前代理模型只按 PEBI 网格样本训练。
if(dataManager->getGridType() != NM_Grid_PEBI) {
if(reason) *reason = "surrogate model is trained only for PEBI grid cases";
if(reason) *reason = tr("surrogate model is trained only for PEBI grid cases");
return false;
}
@ -1952,14 +1999,14 @@ bool nmCalculationAutoFitPSO::isSurrogateRunContextSupported(QString* reason) co
nmDataWellBase* pTargetWell = dataManager->findWellByName(m_targetWellName);
if(!pTargetWell) {
if(reason) *reason = QString("target well '%1' is missing").arg(m_targetWellName);
if(reason) *reason = tr("target well '%1' is missing").arg(m_targetWellName);
return false;
}
// 井型 gate:当前只支持垂直井。水平井/压裂井等几何特征不在训练集中。
if(pTargetWell->getWellType() != NM_WELL_MODEL::Vertical_Well) {
if(reason) *reason = "surrogate model is currently limited to vertical-well cases";
if(reason) *reason = tr("surrogate model is currently limited to vertical-well cases");
return false;
}
@ -1975,7 +2022,7 @@ bool nmCalculationAutoFitPSO::isSurrogateRunContextSupported(QString* reason) co
// 单井 gate:训练数据假设只有一口有效计算井,多井干扰会改变压力响应形态。
if(validCalculationWells != 1) {
if(reason) *reason = QString("surrogate model expects one active calculation well, got %1").arg(validCalculationWells);
if(reason) *reason = tr("surrogate model expects one active calculation well, got %1").arg(validCalculationWells);
return false;
}
@ -1984,7 +2031,7 @@ bool nmCalculationAutoFitPSO::isSurrogateRunContextSupported(QString* reason) co
if(!dataManager->getFaultDataList().isEmpty() ||
!dataManager->getFractureDataList().isEmpty() ||
!dataManager->getRegionDataList().isEmpty()) {
if(reason) *reason = "surrogate model is not enabled for changed fault/fracture/region geometry";
if(reason) *reason = tr("surrogate model is not enabled for changed fault/fracture/region geometry");
return false;
}
@ -1994,12 +2041,12 @@ bool nmCalculationAutoFitPSO::isSurrogateRunContextSupported(QString* reason) co
allowedParamIndices << 0 << 1 << 2 << 3;
for(int i = 0; i < m_enabledParamIndices.size(); ++i) {
if(!allowedParamIndices.contains(m_enabledParamIndices[i])) {
if(!allowedParamIndices.contains(m_modelParameters[m_enabledParamIndices[i]].type)) {
if(reason) {
QStringList names = traceParameterNames();
int idx = m_enabledParamIndices[i];
int idx = m_modelParameters[m_enabledParamIndices[i]].type;
QString name = (idx >= 0 && idx < names.size()) ? names[idx] : QString::number(idx);
*reason = QString("parameter '%1' is outside surrogate input set").arg(name);
*reason = tr("parameter '%1' is outside surrogate input set").arg(name);
}
return false;
@ -2012,7 +2059,7 @@ bool nmCalculationAutoFitPSO::isSurrogateRunContextSupported(QString* reason) co
if(!isNearRelative(ct, parameterDomain.ctFixed, parameterDomain.ctRelTol)) {
if(reason) {
*reason = QString("Ct=%1 does not match surrogate training value %2")
*reason = tr("Ct=%1 does not match surrogate training value %2")
.arg(ct, 0, 'g', 10)
.arg(parameterDomain.ctFixed, 0, 'g', 10);
}
@ -2027,7 +2074,7 @@ bool nmCalculationAutoFitPSO::isSurrogateRunContextSupported(QString* reason) co
bool cfSupported = isNearRelative(cf, parameterDomain.cfFixed, parameterDomain.cfRelTol);
if(!cfSupported) {
if(reason) {
*reason = QString("Cf=%1 is outside surrogate domain").arg(cf, 0, 'g', 10);
*reason = tr("Cf=%1 is outside surrogate domain").arg(cf, 0, 'g', 10);
}
return false;
@ -2038,7 +2085,7 @@ bool nmCalculationAutoFitPSO::isSurrogateRunContextSupported(QString* reason) co
if(!isNearRelative(initialPressure, kSurrogateTrainingInitialPressure, 1.0e-4)) {
if(reason) {
*reason = QString("initialPressure=%1 does not match surrogate training context")
*reason = tr("initialPressure=%1 does not match surrogate training context")
.arg(initialPressure, 0, 'g', 10);
}
@ -2053,7 +2100,7 @@ bool nmCalculationAutoFitPSO::isSurrogateRunContextSupported(QString* reason) co
}
if(flowPoints.size() < 2) {
if(reason) *reason = "flow schedule is too short for surrogate screening";
if(reason) *reason = tr("flow schedule is too short for surrogate screening");
return false;
}
@ -2063,7 +2110,7 @@ bool nmCalculationAutoFitPSO::isSurrogateRunContextSupported(QString* reason) co
if(productionSections < kSurrogateMinProdSections || productionSections > kSurrogateMaxProdSections) {
if(reason) {
*reason = QString("production section count %1 is outside surrogate range [%2,%3]")
*reason = tr("production section count %1 is outside surrogate range [%2,%3]")
.arg(productionSections)
.arg(kSurrogateMinProdSections)
.arg(kSurrogateMaxProdSections);
@ -2080,7 +2127,7 @@ bool nmCalculationAutoFitPSO::isSurrogateRunContextSupported(QString* reason) co
if(!isFiniteNumber(dt) || dt <= 0.0 || !isInClosedRange(q, kSurrogateQMin, kSurrogateQMax)) {
if(reason) {
*reason = QString("production schedule section %1 is outside surrogate dt/q domain").arg(i + 1);
*reason = tr("production schedule section %1 is outside surrogate dt/q domain").arg(i + 1);
}
return false;
@ -2093,7 +2140,7 @@ bool nmCalculationAutoFitPSO::isSurrogateRunContextSupported(QString* reason) co
if(stepRatio > kSurrogateMaxRateStepRatio) {
if(reason) {
*reason = QString("rate step ratio %1 exceeds surrogate domain").arg(stepRatio, 0, 'g', 10);
*reason = tr("rate step ratio %1 exceeds surrogate domain").arg(stepRatio, 0, 'g', 10);
}
return false;
@ -2109,7 +2156,7 @@ bool nmCalculationAutoFitPSO::isSurrogateRunContextSupported(QString* reason) co
if(isStrongDecliningProductionSchedule(&endStartRatio)) {
if(reason) {
*reason = QString("strongly decreasing production schedule ratio %1 is outside surrogate domain")
*reason = tr("strongly decreasing production schedule ratio %1 is outside surrogate domain")
.arg(endStartRatio, 0, 'g', 10);
}
@ -2119,7 +2166,7 @@ bool nmCalculationAutoFitPSO::isSurrogateRunContextSupported(QString* reason) co
if(!isInClosedRange(productionTime, kSurrogateProdTimeMin, kSurrogateProdTimeMax)) {
if(reason) {
*reason = QString("production total time %1 is outside surrogate range").arg(productionTime, 0, 'g', 10);
*reason = tr("production total time %1 is outside surrogate range").arg(productionTime, 0, 'g', 10);
}
return false;
@ -2130,7 +2177,7 @@ bool nmCalculationAutoFitPSO::isSurrogateRunContextSupported(QString* reason) co
if(!isInClosedRange(shutinTime, kSurrogateShutinTimeMin, kSurrogateShutinTimeMax) ||
qAbs(shutinRate) > kSurrogateQZeroThreshold) {
if(reason) *reason = "last flow section is not a trained shut-in section";
if(reason) *reason = tr("last flow section is not a trained shut-in section");
return false;
}
@ -2138,7 +2185,7 @@ bool nmCalculationAutoFitPSO::isSurrogateRunContextSupported(QString* reason) co
// 当前目标段必须是最后的关井段,对应试井解释的双对数分析段。
if(pTargetWell->getIndexF() != flowPoints.size()) {
if(reason) {
*reason = QString("target section index %1 is not the last section %2")
*reason = tr("target section index %1 is not the last section %2")
.arg(pTargetWell->getIndexF())
.arg(flowPoints.size());
}
@ -2670,7 +2717,7 @@ bool nmCalculationAutoFitPSO::loadAllConfigFromDataManager()
extractUserInitialValues(); // 直接提取初始值,无需条件判断
return true;
} catch(...) {
m_lastError = "Failed to load configuration from data manager";
m_lastError = tr("Failed to load configuration from data manager");
return false;
}
}
@ -2702,49 +2749,21 @@ void nmCalculationAutoFitPSO::loadOptimizationConfig()
void nmCalculationAutoFitPSO::loadParameterBounds()
{
// 读取用户勾选的拟合参数及上下界。
//
// 这里构建三个核心数组:
// - m_parameterSelected[4]:完整参数体系中每个参数是否参与拟合;
// - m_parameterLower/Upper[4]:完整参数体系的搜索上下界;
// - m_enabledParamIndices:把粒子内部紧凑向量映射回完整参数索引。
nmDataAnalyzeManager* dataManager = nmDataAnalyzeManager::getCurrentInstance();
nmDataAutomaticFitting fittingData = dataManager->getAutomaticFittingDataCopy();
// 获取参数选择状态
m_parameterSelected.resize(4);
m_parameterSelected[0] = fittingData.getPermeabilitySelected();
m_parameterSelected[1] = fittingData.getSkinSelected();
m_parameterSelected[2] = fittingData.getWellboreStorageSelected();
m_parameterSelected[3] = fittingData.getPorositySelected();
// 获取参数边界
m_parameterLower.resize(4);
m_parameterUpper.resize(4);
m_parameterLower[0] = fittingData.getPermeabilityMin().getValue().toDouble();
m_parameterUpper[0] = fittingData.getPermeabilityMax().getValue().toDouble();
m_parameterLower[1] = fittingData.getSkinMin().getValue().toDouble();
m_parameterUpper[1] = fittingData.getSkinMax().getValue().toDouble();
m_parameterLower[2] = fittingData.getWellboreStorageMin().getValue().toDouble();
m_parameterUpper[2] = fittingData.getWellboreStorageMax().getValue().toDouble();
m_parameterLower[3] = fittingData.getPorosityMin().getValue().toDouble();
m_parameterUpper[3] = fittingData.getPorosityMax().getValue().toDouble();
// 更新启用参数索引
// 与 LM 共用按井分组的参数列表,位置和类型分离,允许多口井拥有同类参数。
const nmDataAutomaticFitting fittingData =
nmDataAnalyzeManager::getCurrentInstance()->getAutomaticFittingDataCopy();
m_modelParameters = fittingData.getModelParameters();
m_parameterSelected.clear();
m_parameterLower.clear();
m_parameterUpper.clear();
m_enabledParamIndices.clear();
for(int i = 0; i < m_parameterSelected.size(); ++i) {
if(m_parameterSelected[i]) {
m_enabledParamIndices.append(i);
}
for(int i = 0; i < m_modelParameters.size(); ++i) {
const nmFitParameter& 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);
}
DEBUG_OUT(QString("Loaded parameter bounds: %1 enabled parameters")
.arg(m_enabledParamIndices.size()));
}
// ==================== PSO算法核心方法 ====================
@ -2754,7 +2773,7 @@ bool nmCalculationAutoFitPSO::startAutoFitting()
// 读取配置 -> 校验输入 -> 评价用户初始解 -> 初始化粒子群 ->
// 按代循环评价粒子 -> 更新全局最优 -> 判断停止 -> 保存结果。
if(m_isRunning) {
m_lastError = "Auto fitting is already running";
m_lastError = tr("Auto fitting is already running");
return false;
}
@ -2781,13 +2800,13 @@ bool nmCalculationAutoFitPSO::startAutoFitting()
emit logMessageGenerated(tr("Enabled parameters count: %1").arg(enabledParams));
if(enabledParams == 0) {
m_lastError = "No parameters enabled for optimization";
m_lastError = tr("No parameters enabled for optimization");
emit logMessageGenerated(tr("ERROR: No parameters enabled for optimization"));
return false;
}
if(m_targetLogLogData.isEmpty() || m_targetLogLogData.size() < 3) {
m_lastError = "Target LogLog data is empty or insufficient";
m_lastError = tr("Target LogLog data is empty or insufficient");
emit logMessageGenerated(tr("ERROR: Target LogLog data is empty or insufficient"));
return false;
}
@ -2796,7 +2815,7 @@ bool nmCalculationAutoFitPSO::startAutoFitting()
// 且三列长度一致。后续误差函数会按 time 做插值对齐。
if(m_targetLogLogData[0].size() != m_targetLogLogData[1].size() ||
m_targetLogLogData[0].size() != m_targetLogLogData[2].size()) {
m_lastError = "Target LogLog data arrays have inconsistent sizes";
m_lastError = tr("Target LogLog data arrays have inconsistent sizes");
emit logMessageGenerated(tr("ERROR: Target LogLog data arrays have inconsistent sizes"));
return false;
}
@ -2868,7 +2887,7 @@ bool nmCalculationAutoFitPSO::startAutoFitting()
QString paramStr = tr("Initial parameters: ");
for(int i = 0; i < m_userInitialSolution.size(); ++i) {
paramStr += QString("[%1]=%2 ").arg(i).arg(m_userInitialSolution[i], 0, 'f', 6);
paramStr += QString("%1=%2 ").arg(m_modelParameters[m_enabledParamIndices[i]].name()).arg(m_userInitialSolution[i], 0, 'g', 10);
}
emit logMessageGenerated(paramStr);
@ -3072,7 +3091,7 @@ bool nmCalculationAutoFitPSO::startAutoFitting()
// 检查是否需要停止优化
if(m_consecutiveFailedIterations >= m_maxConsecutiveFailures) {
m_lastError = QString("Too many consecutive failed iterations (%1)").arg(m_consecutiveFailedIterations);
m_lastError = tr("Too many consecutive failed iterations (%1)").arg(m_consecutiveFailedIterations);
emit logMessageGenerated(tr("ERROR: Too many consecutive failed iterations (%1/%2) - stopping optimization")
.arg(m_consecutiveFailedIterations).arg(m_maxConsecutiveFailures));
break;
@ -3248,10 +3267,10 @@ bool nmCalculationAutoFitPSO::startAutoFitting()
}
} catch(const std::exception& e) {
emit logMessageGenerated(tr("ERROR: Failed to apply final parameters: %1").arg(e.what()));
m_lastError = QString("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 = "Failed to apply final parameters due to unknown error";
m_lastError = tr("Failed to apply final parameters due to unknown error");
}
}
@ -3333,62 +3352,11 @@ bool nmCalculationAutoFitPSO::startAutoFitting()
void nmCalculationAutoFitPSO::extractUserInitialValues()
{
// 从当前项目模型读取用户已有初始参数。
// 只提取用户勾选的参数,并按 m_enabledParamIndices 的顺序写入 m_initialValues。
// 这些值用于:
// 1. 初始解真实评价;
// 2. 粒子群引导初始化;
// 3. 最终精英保护。
nmDataAnalyzeManager* dataManager = nmDataAnalyzeManager::getCurrentInstance();
nmDataReservoir reservoirData = dataManager->getReservoirDataCopy();
//QVector<nmDataWellBase*> wells = dataManager->getWellDataList();
nmDataWellBase* pTargetWell = dataManager->findWellByName(m_targetWellName);
// 初值由设置窗口读取并校验,按本次启用的参数列表顺序提取。
m_initialValues.clear();
// 按照启用参数的顺序提取初始值。井参数来自目标井,储层参数来自 reservoirData。
for(int i = 0; i < m_enabledParamIndices.size(); ++i) {
int paramIndex = m_enabledParamIndices[i];
double initialValue = 0.0;
switch(paramIndex) {
case 0: // 渗透率
initialValue = reservoirData.getPermeability().getValue().toDouble();
break;
case 1: // 表皮系数
if(pTargetWell) {
initialValue = pTargetWell->getPerforation(0)->getSkin().getValue().toDouble();
}
break;
case 2: // 井筒储集系数
if(pTargetWell) {
initialValue = pTargetWell->getWellboreStorage().getValue().toDouble();
}
break;
case 3: // 孔隙度
initialValue = reservoirData.getPorosity().getValue().toDouble();
break;
}
m_initialValues.append(initialValue);
}
DEBUG_OUT(QString("Extracted %1 user initial values").arg(m_initialValues.size()));
for(int i = 0; i < m_initialValues.size(); ++i) {
DEBUG_OUT(QString(" Initial[%1] = %2").arg(i).arg(m_initialValues[i], 0, 'e', 3));
}
// 验证初始值
if(!validateInitialValues()) {
DEBUG_OUT("Warning: Some initial values are outside parameter bounds");
const nmFitParameter& p = m_modelParameters[m_enabledParamIndices[i]];
m_initialValues.append(qBound(p.lower, p.initial, p.upper));
}
}
@ -3887,7 +3855,7 @@ double nmCalculationAutoFitPSO::evaluateFitness(const QVector<double>& parameter
{
// 粒子适应度评价函数,也是自动拟合最核心的闭环:
// 1. 校验粒子参数是否在用户设置的上下界和基本物理范围内;
// 2. 将参数写入 DataManager 的储层/目标井对象;
// 2. 将参数写入 DataManager 的储层/各所属井对象;
// 3. 调用真实数值求解器,生成模拟结果;
// 4. 从目标井读取模拟后的 result log-log 曲线;
// 5. 与目标 history log-log 曲线计算误差,误差越小代表拟合越好。
@ -3911,8 +3879,8 @@ double nmCalculationAutoFitPSO::evaluateFitness(const QVector<double>& parameter
DEBUG_OUT(QString("%1: %2").arg(funcName).arg(paramStr));
// 1. 参数有效性检查。这里先在 PSO 层拦截明显非法的候选,
// 避免把非有限数、越界值或极端危险值传给求解器。
// 1. 与 LM 一致,检查参数数量、有限数和界面上下界。
// 参数物理范围由拟合窗口统一校验。
if(!validateParameters(parameters)) {
DEBUG_OUT(QString("%1: Call #%2 - VALIDATION FAILED").arg(funcName).arg(callCount));
@ -3939,30 +3907,7 @@ double nmCalculationAutoFitPSO::evaluateFitness(const QVector<double>& parameter
.arg(i).arg(parameters[i]).arg(upper));
}
// 检查危险值。这些条件不是严格物理模型定义,
// 而是工程保护:避免求解器在明显异常输入下崩溃或返回无意义曲线。
switch(paramIndex) {
case 0: // 渗透率
if(parameters[i] <= 1e-6) {
DEBUG_OUT(QString(" -> REJECTED: Permeability too small: %1").arg(parameters[i]));
}
break;
case 2: // 井筒储集系数
if(parameters[i] <= 1e-8) {
DEBUG_OUT(QString(" -> REJECTED: Wellbore storage too small: %1").arg(parameters[i]));
}
break;
case 3: // 孔隙度
if(parameters[i] <= 1e-4 || parameters[i] >= 0.95) {
DEBUG_OUT(QString(" -> REJECTED: Unrealistic porosity: %1").arg(parameters[i]));
}
break;
}
}
}
}
@ -3983,7 +3928,7 @@ double nmCalculationAutoFitPSO::evaluateFitness(const QVector<double>& parameter
DEBUG_OUT(QString("%1: Call #%2 - DataManager OK").arg(funcName).arg(callCount));
// 3. 应用参数。parameters 的顺序与 m_enabledParamIndices 对齐,
// applyParametersToDataManager() 会把它们拆分写入储层参数和目标井参数。
// applyParametersToDataManager() 会把它们按列表写入共享储层参数和各井参数。
try {
DEBUG_OUT(QString("%1: Call #%2 - Applying parameters...").arg(funcName).arg(callCount));
applyParametersToDataManager(parameters);
@ -4138,111 +4083,45 @@ double nmCalculationAutoFitPSO::evaluateFitness(const QVector<double>& parameter
void nmCalculationAutoFitPSO::applyParametersToDataManager(const QVector<double>& parameters)
{
// 将粒子的“启用参数向量”写回项目数据。
// parameters 的维度必须等于用户勾选的参数数量,顺序由 m_enabledParamIndices 决定。
// 这里不直接跑求解器,只负责把 DataManager 调整到该粒子对应的模型状态。
if(parameters.size() != getEnabledParameterCount()) {
return;
}
updateReservoirParameters(parameters);
updateWellParameters(parameters);
}
void nmCalculationAutoFitPSO::updateReservoirParameters(const QVector<double>& parameters)
{
// 更新储层级参数。井级参数 skin/wellboreC 不在这里改,由 updateWellParameters() 负责。
// 这里先取 DataManager 中 reservoir 的副本,修改后再整体写回 DataManager。
nmDataAnalyzeManager* dataManager = nmDataAnalyzeManager::getCurrentInstance();
nmDataReservoir reservoirData = dataManager->getReservoirDataCopy();
// paramIndex 是粒子 position 中的索引;i 是完整 4 个拟合参数体系中的索引。
// 只有 m_parameterSelected[i] 为 true 时,才从 parameters 中消费一个值。
int paramIndex = 0;
for(int i = 0; i < m_parameterSelected.size(); ++i) {
if(m_parameterSelected[i] && paramIndex < parameters.size()) {
double value = parameters[paramIndex];
switch(i) {
case 0: // 渗透率
reservoirData.getPermeability().setValue(value);
break;
case 3: // 孔隙度
reservoirData.getPorosity().setValue(value);
break;
// 写回每项所属井的现有属性,不更换井对象;共用储层参数只更新一次。
nmDataAnalyzeManager* manager = nmDataAnalyzeManager::getCurrentInstance();
nmDataReservoir reservoir = manager->getReservoirDataCopy();
for(int i = 0; i < m_enabledParamIndices.size(); ++i) {
const nmFitParameter& 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);
}
paramIndex++;
}
}
// 更新数据管理器
dataManager->updateReservoirData(reservoirData);
}
void nmCalculationAutoFitPSO::updateWellParameters(const QVector<double>& parameters)
{
// 更新目标井上的拟合参数。目前井级可拟合参数主要是:
// - skin:写入第一个 perforation;
// - wellboreC:写入井筒储集系数。
// 如果目标井不存在或没有射孔数据,这里只记录 debug,不抛异常。
nmDataAnalyzeManager* dataManager = nmDataAnalyzeManager::getCurrentInstance();
// 只更新当前目标井的井参数,避免多井项目中误改其他井。
//QVector<nmDataWellBase*> wells = dataManager->getWellDataList();
nmDataWellBase* pWell = dataManager->findWellByName(m_targetWellName);
if(!pWell) return;
// 先修改独立的参数副本,解析完成后再写回原井对象中的现有属性。
// 不再整井赋值,避免拟合过程中删除并重建射孔对象。
nmDataPerforation* pPerforation = pWell->getPerforation(0);
nmDataAttribute skinAttr;
bool updateSkin = false;
if(pPerforation) {
skinAttr = pPerforation->getSkin();
}
nmDataAttribute wellboreAttr = pWell->getWellboreStorage();
bool updateWellboreStorage = false;
int paramIndex = 0;
for(int i = 0; i < m_parameterSelected.size(); ++i) {
if(m_parameterSelected[i] && paramIndex < parameters.size()) {
double value = parameters[paramIndex];
switch(i) {
case 1: { // 表皮系数
if(pPerforation) {
skinAttr.setValue(value);
updateSkin = true;
}
}
break;
case 2: { // 井筒储集系数
wellboreAttr.setValue(value);
updateWellboreStorage = true;
}
break;
}
paramIndex++;
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;
}
}
if(updateSkin) {
pPerforation->getSkin().setValue(skinAttr.getValue());
}
if(updateWellboreStorage) {
pWell->getWellboreStorage().setValue(wellboreAttr.getValue());
}
}
// ==================== 求解器相关方法 ====================
QVector<QVector<double>> nmCalculationAutoFitPSO::runSolver()
@ -4549,9 +4428,8 @@ int nmCalculationAutoFitPSO::getEnabledParameterCount() const
bool nmCalculationAutoFitPSO::validateParameters(const QVector<double>& parameters) const
{
// 参数合法性检查分两层:
// 1. 与用户界面设置一致:维度、有限数、上下界;
// 2. 求解器保护:拦截会导致数值崩溃或明显无物理意义的极端值。
// 参数物理范围已由拟合窗口统一校验;候选评价只检查维度、有限数和
// 用户设置的上下界,避免另一套硬编码阈值与实际搜索范围冲突。
if(parameters.size() != getEnabledParameterCount()) {
return false;
}
@ -4561,7 +4439,6 @@ bool nmCalculationAutoFitPSO::validateParameters(const QVector<double>& paramete
return false;
}
// 检查参数范围
if(i < m_enabledParamIndices.size()) {
int paramIndex = m_enabledParamIndices[i];
@ -4574,38 +4451,6 @@ bool nmCalculationAutoFitPSO::validateParameters(const QVector<double>& paramete
}
}
// 直接拦截会导致求解器数值崩溃的参数值
for(int i = 0; i < parameters.size() && i < m_enabledParamIndices.size(); ++i) {
int paramIndex = m_enabledParamIndices[i];
double value = parameters[i];
switch(paramIndex) {
case 0: // 渗透率:必须大于零
if(value <= 1e-8) {
DEBUG_OUT(QString("Rejecting near-zero permeability: %1").arg(value));
return false;
}
break;
case 2: // 井筒储集系数:必须大于零
if(value <= 1e-10) {
DEBUG_OUT(QString("Rejecting near-zero wellbore storage: %1").arg(value));
return false;
}
break;
case 3: // 孔隙度:必须在合理范围
if(value <= 1e-6 || value >= 0.99) {
DEBUG_OUT(QString("Rejecting unrealistic porosity: %1").arg(value));
return false;
}
break;
}
}
return true;
}

@ -440,9 +440,8 @@ void nmWxAutomaticFitting::setupControlPanel()
m_algorithmCombo = new QComboBox();
m_algorithmCombo->addItem(tr("PSO (Particle Swarm)"));
m_algorithmCombo->addItem(tr("LM"));
// 多井和敏感性拟合固定使用 LM,单井普通拟合才允许切换算法。
const bool lmOnly = m_sensitivitySettings
|| nmDataAnalyzeManager::getCurrentInstance()->getEffectiveCalculationWells().size() > 1;
// 普通单井、多井拟合均可切换算法;敏感性入口仍使用 LM。
const bool lmOnly = m_sensitivitySettings != nullptr;
m_algorithmCombo->setCurrentIndex(lmOnly ? 1 : 0);
m_algorithmCombo->setEnabled(!lmOnly);
m_algorithmCombo->setFixedWidth(160);
@ -481,13 +480,8 @@ void nmWxAutomaticFitting::onAlgorithmChanged(int index)
const nmFitParameter& p = parameters[i];
nmDataWellBase* well = p.wellCode.isEmpty() ? nullptr
: nmDataAnalyzeManager::getCurrentInstance()->findWellByCode(p.wellCode);
// PSO 不支持裂缝参数,隐藏并禁用,避免全选或保存时带入。
const bool hidden = usePSO && (p.type == 4 || p.type == 5);
const bool unavailable = (m_sensitivitySettings && m_sampledParameters.contains(p.samplingKey()))
|| hidden
|| (usePSO && !p.wellCode.isEmpty() && p.wellCode != m_targetWellCode)
|| (p.type == 1 && (!well || well->getPerforationCount() == 0));
m_parameterItems[i]->setHidden(hidden);
m_parameterItems[i]->setDisabled(unavailable);
if(unavailable) m_parameterItems[i]->setCheckState(0, Qt::Unchecked);
}
@ -674,7 +668,7 @@ void nmWxAutomaticFitting::onReject()
void nmWxAutomaticFitting::setAutomaticFittingValue()
{
// 单井旧字段继续供 PSO 和旧配置读取,LM 直接使用完整分组参数列表。
// 旧字段用于配置兼容,两种算法均直接读取完整分组参数列表。
automaticFittingData.setPermeabilitySelected(false);
automaticFittingData.setSkinSelected(false);
automaticFittingData.setWellboreStorageSelected(false);
@ -723,55 +717,9 @@ void nmWxAutomaticFitting::setAutomaticFittingValue()
automaticFittingData.getIterationCount().setValue(m_iterationEdit->text().toInt());
automaticFittingData.getErrorTolerance().setValue(m_errorLimitEdit->text().toDouble());
automaticFittingData.setAlgorithmName(m_algorithmCombo->currentIndex() == 1 ? "LM" : "PSO");
// 敏感性入口只保存设置;普通 LM 在启动时按井应用初值。
// 敏感性入口只保存设置;普通拟合由算法按完整列表应用各井选中参数的初值。
if(m_sensitivitySettings) return;
if(m_algorithmCombo->currentIndex() == 1) {
nmDataAnalyzeManager::getCurrentInstance()->updateAutomaticFittingData(automaticFittingData);
return;
}
const QVector<double> initial = targetInitialValues();
// PSO 只写回可拟合的储层初值,井参数仅写入 Skin 和 C。
reservoirData.getPermeability().setValue(initial[0]); // 渗透率
reservoirData.getPorosity().setValue(initial[3]); // 孔隙度
// 更新储层数据(全局)
nmDataAnalyzeManager::getCurrentInstance()->updateReservoirData(reservoirData);
// 保存自动拟合数据
nmDataAutomaticFitting psoSettings = automaticFittingData;
psoSettings.getModelParameters().clear();
nmDataAnalyzeManager::getCurrentInstance()->updateAutomaticFittingData(psoSettings);
// 只更新目标井的参数
QString selectedWellName = m_targetWellName;
if(!selectedWellName.isEmpty()) {
double newSkinValue = initial[1];
double newWellboreStorageValue = initial[2];
// 直接从数据管理器获取目标井
nmDataAnalyzeManager* manager = nmDataAnalyzeManager::getCurrentInstance();
nmDataWellBase* pTargetWell = manager->findWellByName(selectedWellName);
if(pTargetWell) {
// 先修改井参数副本,最后写回原对象中的现有属性,保持射孔对象地址不变。
nmDataPerforation* perf = pTargetWell->getPerforation(0);
if(perf) {
nmDataAttribute skinAttr = perf->getSkin();
skinAttr.setValue(newSkinValue);
perf->getSkin().setValue(skinAttr.getValue());
}
// 更新井筒储集系数
nmDataAttribute wellboreAttr = pTargetWell->getWellboreStorage();
wellboreAttr.setValue(newWellboreStorageValue);
pTargetWell->getWellboreStorage().setValue(wellboreAttr.getValue());
// 全部井参数落地后统一刷新一次右侧参数面板。
if(manager->getAttrRegistry()) {
manager->getAttrRegistry()->refreshAll();
}
}
}
nmDataAnalyzeManager::getCurrentInstance()->updateAutomaticFittingData(automaticFittingData);
}
void nmWxAutomaticFitting::startAutoFitting(const QVector<QVector<double>>& targetData, const QStringList& selectedParams, const QString& targetWellName)
@ -1097,17 +1045,10 @@ QVector<double> nmWxAutomaticFitting::targetInitialValues() const
QStringList nmWxAutomaticFitting::selectedParameterLabels(bool units) const
{
// 单位与设置表格共用 XML 定义;LM 按完整向量顺序,PSO 只取四类可拟合参数。
// 两种算法均按分组列表顺序输出,井名和单位与每个启用维度一一对应。
QStringList labels;
const QVector<nmFitParameter>& parameters = automaticFittingData.getModelParameters();
if(m_algorithmCombo->currentIndex() == 1) {
for(int i = 0; i < parameters.size(); ++i)
if(parameters[i].selected) labels << (units ? nmAutoFitDisplayUnit(parameters[i]) : parameters[i].name());
} else {
for(int type = 0; type < 4; ++type)
for(int i = 0; i < parameters.size(); ++i)
if(parameters[i].selected && parameters[i].type == type)
labels << (units ? nmAutoFitDisplayUnit(parameters[i]) : parameters[i].name());
}
for(int i = 0; i < parameters.size(); ++i)
if(parameters[i].selected) labels << (units ? nmAutoFitDisplayUnit(parameters[i]) : parameters[i].name());
return labels;
}

Loading…
Cancel
Save