#include "nmSurrogate.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include /** @brief 沿用原软件 PSO 的翻译上下文。 */ static QString fitTr(const char* text) { return QCoreApplication::translate("nmCalculationAutoFitPSO", text); } #ifdef Q_OS_WIN #include #define DEBUG_OUT(msg) OutputDebugStringA(QString("[Surrogate] %1\n").arg(msg).toLocal8Bit().data()) #else #define DEBUG_OUT(msg) qDebug() << msg #endif namespace { enum { SMT_Oil_ConstPvt = 1, SMT_Oil_VariablePvt = 2, SMT_Water_ConstPvt = 3, SMT_Water_VariablePvt = 4, SMT_Gas_VariablePvt = 5 }; // ===== 代理模型筛选参数 ===== // // PSO acceleration 的原则是“少跑一部分真实求解器,但不能完全信任代理模型”: // - keep_fraction:代理评分排名靠前的粒子进入真实求解器; // - audit_fraction:从被筛掉的粒子中随机抽查一部分,避免代理模型系统性漏掉好解; // - min_solver_fraction:每代至少有一定比例粒子跑真实求解器,保证 pbest/gbest 仍由真实误差支撑; // - warmup_iterations:前几代全量真实评价,让每个粒子先拿到可靠的个体最优; // - full_solver_interval:周期性全量审计,用于纠偏代理模型排序误差。 static const double kSurrogateKeepFraction = 0.40; // 常规工况:代理排序前 40% 粒子进入真实求解器。 static const double kSurrogateHighRiskKeepFraction = 0.70; // 高风险流量制度:保留更多 top 粒子。 static const double kSurrogateAuditFraction = 0.05; // 从被筛掉候选中随机审计 5%。 static const double kSurrogateMinSolverFraction = 0.45; // 常规工况:每代至少 45% 粒子跑真实求解器。 static const double kSurrogateHighRiskMinSolverFraction = 0.80; // 高风险流量制度:每代至少 80% 粒子跑真实求解器。 static const int kSurrogateWarmupIterations = 2; // 前 2 代全量真实评价,给每个粒子建立 pbest。 static const int kSurrogateFullSolverInterval = 10; // 每 10 代做一次全量真实求解审计。 static const double kSurrogateGuidePbestMinRelativeImprovement = 1.0e-4; // 引导 pbest 至少改善 0.01%,过滤数值噪声。 static const int kSurrogateScoringMaxAttempts = 2; // Python 评分失败时最多重试 2 次。 static const bool kUseFixedPsoSeed = true; // 固定随机种子便于复现 trace 和交接演示。 static const unsigned int kFixedPsoSeed = 1792008679u; // 当前固定种子值。 // ===== 代理模型训练域约束 ===== // // 这些范围必须与 ML/nmWTAI-ML/configs/data_gen_family_random_v2_q.yaml 中的 // 数据生成范围保持一致。PSO 中渗透率使用 mD,因此将训练配置中的 Darcy 范围 // 乘以 1000 后再门控;超出范围时强制退回真实求解器。 static const double kSurrogateKMin = 1.0; // 代理模型训练域:渗透率下界,单位 mD。 static const double kSurrogateKMax = 10000.0; // 代理模型训练域:渗透率上界,单位 mD。 static const double kSurrogateSkinMin = -10.0; // 代理模型训练域:skin 下界。 static const double kSurrogateSkinMax = 10.0; // 代理模型训练域:skin 上界。 static const double kSurrogateWellboreCMin = 1.0e-4; // 代理模型训练域:井筒储集下界。 static const double kSurrogateWellboreCMax = 2.0; // 代理模型训练域:井筒储集上界。 static const double kSurrogatePhiMin = 1.0e-2; // 代理模型训练域:孔隙度下界。 static const double kSurrogatePhiMax = 0.50; // 代理模型训练域:孔隙度上界。 static const double kSurrogateHMin = 2.0; // 代理模型训练域:储层厚度下界。 static const double kSurrogateHMax = 50.0; // 代理模型训练域:储层厚度上界。 static const double kSurrogateConstPvtCfFixed = 4.3e-4; // T1/T3 模型输入使用训练数据中的固定 Cf。 static const double kSurrogateT5CfFixed = 3.0e-4; // T5 专用训练数据中的固定 Cf。 static const double kSurrogateConstPvtCtFixed = 1.0e-2; // T1/T3 训练数据中的固定 Ct。 static const double kSurrogateFixedParamRelTol = 1.0e-4; // 固定参数仅允许 0.01% 相对偏差。 static const double kSurrogateCfMin = 1.0e-5; // T2/T4 训练数据中的 Cf 下界。 static const double kSurrogateCfMax = 1.0e-2; // T2/T4 训练数据中的 Cf 上界。 static const double kSurrogateTrainingInitialPressure = 34.47; static const int kSurrogateMinProdSections = 3; // 代理训练流量制度:生产段数量下界。 static const int kSurrogateMaxProdSections = 5; // 代理训练流量制度:生产段数量上界。 static const double kSurrogateProdTimeMin = 24.0; // 代理训练流量制度:生产总时长下界。 static const double kSurrogateProdTimeMax = 220.0; // 代理训练流量制度:生产总时长上界。 static const double kSurrogateShutinTimeMin = 12.0; // 代理训练流量制度:关井段时长下界。 static const double kSurrogateShutinTimeMax = 140.0; // 代理训练流量制度:关井段时长上界。 static const double kSurrogateQMin = 50.0; // 代理训练流量制度:产量下界。 static const double kSurrogateQMax = 500.0; // 代理训练流量制度:产量上界。 static const double kSurrogateQZeroThreshold = 1.0e-6; // 判断最后一段是否关井的零产量阈值。 static const double kSurrogateMaxRateStepRatio = 2.0; // 相邻生产段产量最大跳变比。 static const double kSurrogateStrongDeclineEndStartRatio = 0.70; // 末段/首段产量小于该值视为强递减。 static const double kSurrogateRateTrendRelTol = 1.0e-9; // 判断产量趋势时的相对容差。 // 判断 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 } static inline bool isInClosedRange(double value, double lower, double upper) { return isFiniteNumber(value) && value >= lower && value <= upper; } // 判断 value 是否接近 reference。用于 Ct/Cf 等固定训练参数的运行域检查。 static inline bool isNearRelative(double value, double reference, double relTol) { if(!isFiniteNumber(value) || !isFiniteNumber(reference)) { return false; } return qAbs(value - reference) <= qMax(1e-12, qAbs(reference) * relTol); } struct SurrogateParameterDomain { double kMin; double kMax; double skinMin; double skinMax; double wellboreCMin; double wellboreCMax; double phiMin; double phiMax; double hMin; double hMax; double cfMin; double cfMax; double cfFixed; double cfRelTol; double ctFixed; double ctRelTol; bool checkCf; bool checkCt; bool variableCf; }; // 每种相态只能在生成该相态训练数据时使用的参数范围内调用代理模型。 static bool getSurrogateParameterDomain(int solverModelType, SurrogateParameterDomain* domain) { if(!domain) { return false; } domain->kMin = kSurrogateKMin; domain->kMax = kSurrogateKMax; domain->skinMin = kSurrogateSkinMin; domain->skinMax = kSurrogateSkinMax; domain->wellboreCMin = kSurrogateWellboreCMin; domain->wellboreCMax = kSurrogateWellboreCMax; domain->phiMin = kSurrogatePhiMin; domain->phiMax = kSurrogatePhiMax; domain->hMin = kSurrogateHMin; domain->hMax = kSurrogateHMax; domain->cfMin = kSurrogateCfMin; domain->cfMax = kSurrogateCfMax; domain->cfFixed = kSurrogateT5CfFixed; domain->cfRelTol = kSurrogateFixedParamRelTol; domain->ctFixed = kSurrogateConstPvtCtFixed; domain->ctRelTol = kSurrogateFixedParamRelTol; domain->checkCf = false; domain->checkCt = false; domain->variableCf = false; switch(solverModelType) { case SMT_Oil_ConstPvt: case SMT_Water_ConstPvt: domain->checkCt = true; return true; case SMT_Oil_VariablePvt: domain->checkCf = true; domain->variableCf = true; return true; case SMT_Water_VariablePvt: domain->checkCf = true; domain->variableCf = true; return true; case SMT_Gas_VariablePvt: domain->kMin = 4.5e-3; domain->kMax = 6.2e-3; domain->skinMin = 0.0; domain->skinMax = 4.5; domain->wellboreCMin = 5.0e-5; domain->wellboreCMax = 1.6e-4; domain->phiMin = 8.0e-3; domain->phiMax = 4.0e-2; domain->hMin = 7.0; domain->hMax = 11.0; domain->cfFixed = kSurrogateT5CfFixed; domain->checkCf = true; domain->variableCf = false; return true; default: return false; } } // Windows 下的毫秒级睡眠封装。用于重试间隔、UI 事件循环间隔和模拟模式节奏控制。 static inline void msleep(int ms) { #ifdef Q_OS_WIN Sleep(ms); #endif } 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& 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& 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 double deterministicAuditRandom01(unsigned int seed, int generation, int particleIndex) { // 代理筛选的随机审计需要“随机但可复现”: // 同一个 PSO 种子、代号、粒子号会得到同一个 0-1 值,方便复盘 trace。 unsigned int x = seed; x ^= 0x9e3779b9u + static_cast(generation + 1) + (x << 6) + (x >> 2); x ^= 0x85ebca6bu + static_cast(particleIndex + 1) + (x << 6) + (x >> 2); x ^= x >> 16; x *= 0x7feb352du; x ^= x >> 15; x *= 0x846ca68bu; x ^= x >> 16; return static_cast(x) / 4294967295.0; } static QString jsonPointArray(const QVector& 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(",")); } static bool isValidMlRootDirectory(const QString& mlRootPath) { // 判断一个目录是不是可用的 ML/nmWTAI-ML 根目录。 // 目前以评分脚本是否存在作为最小可用条件。 if(mlRootPath.isEmpty()) { return false; } QFileInfo scriptInfo(QDir(mlRootPath).absoluteFilePath("scripts/score_pso_candidates.py")); return scriptInfo.exists() && scriptInfo.isFile(); } static QString findExecutableInPath(const QString& executableName) { // 在系统 PATH 中查找可执行文件。找不到 .venv 里的 python.exe 时会用它兜底。 if(executableName.isEmpty()) { return QString(); } QString pathValue = QProcessEnvironment::systemEnvironment().value("PATH"); if(pathValue.isEmpty()) { pathValue = QString::fromLocal8Bit(qgetenv("PATH")); } if(pathValue.isEmpty()) { return QString(); } QStringList executableCandidates; executableCandidates << executableName; #ifdef Q_OS_WIN if(!executableName.contains('.')) { executableCandidates << (executableName + ".exe") << (executableName + ".bat") << (executableName + ".cmd"); } #endif #ifdef Q_OS_WIN QChar pathSeparator(';'); #else QChar pathSeparator(':'); #endif QStringList pathEntries = pathValue.split(pathSeparator, QString::SkipEmptyParts); for(int i = 0; i < pathEntries.size(); ++i) { QDir dir(pathEntries[i].trimmed()); if(!dir.exists()) { continue; } for(int j = 0; j < executableCandidates.size(); ++j) { QFileInfo executableInfo(dir.absoluteFilePath(executableCandidates[j])); if(executableInfo.exists() && executableInfo.isFile()) { return QDir::cleanPath(executableInfo.absoluteFilePath()); } } } return QString(); } static QStringList traceParameterNames() { // 参数类型名称供代理模型的输入限制提示使用,不代表多井列表位置。 // 代理输入仍使用 buildTraceParameterVector() 的物理参数顺序。 QStringList names; names << "k" << "skin" << "wellboreC" << "phi" << "Dfc" << "fractureHalfLength"; return names; } } // namespace QString nmSurrogate::getMlRootPath() const { if(!m_context.mlRoot.isEmpty()) return m_context.mlRoot; // 查找 ML/nmWTAI-ML 根目录。程序可能从 build/bin/release 等不同目录启动, // 因此按多个相对路径尝试。isValidMlRootDirectory() 用评分脚本是否存在来确认。 QString appDir = QCoreApplication::applicationDirPath(); QString cwd = QDir::currentPath(); QStringList candidateRoots; candidateRoots << QDir::cleanPath(appDir + "/../../ML/nmWTAI-ML") << QDir::cleanPath(appDir + "/../ML/nmWTAI-ML") << QDir::cleanPath(cwd + "/ML/nmWTAI-ML") << QDir::cleanPath(cwd + "/../ML/nmWTAI-ML") << QDir::cleanPath(cwd + "/../../ML/nmWTAI-ML"); for(int i = 0; i < candidateRoots.size(); ++i) { if(isValidMlRootDirectory(candidateRoots[i])) { return candidateRoots[i]; } } return candidateRoots.isEmpty() ? QString() : candidateRoots.first(); } QString nmSurrogate::getPythonExecutablePath() const { if(!m_context.pythonExecutable.isEmpty()) return m_context.pythonExecutable; // 优先使用 ML 项目内的虚拟环境 python,其次使用 PATH 中的 python。 // 这样开发机上只要 ML/nmWTAI-ML/.venv 已配置,就不依赖全局 Python 环境。 QString mlRoot = getMlRootPath(); QStringList candidateExecutables; if(!mlRoot.isEmpty()) { candidateExecutables << QDir(mlRoot).absoluteFilePath(".venv/Scripts/python.exe"); candidateExecutables << QDir(mlRoot).absoluteFilePath(".venv/bin/python"); } for(int i = 0; i < candidateExecutables.size(); ++i) { QFileInfo pythonInfo(candidateExecutables[i]); if(pythonInfo.exists() && pythonInfo.isFile()) { return QDir::cleanPath(pythonInfo.absoluteFilePath()); } } QString resolvedPython = findExecutableInPath("python"); if(!resolvedPython.isEmpty()) { return QDir::cleanPath(resolvedPython); } return "python"; } QString nmSurrogate::getSurrogateTag() const { if(!m_context.modelTag.isEmpty()) return m_context.modelTag; // 当前 C++ 绑定的代理模型实验标识,对应 ML 侧训练输出目录/checkpoint 命名。 // 如果以后换模型,需要同步更新这里和 ML 脚本可识别的 tag。 if(m_context.solverType == SMT_Gas_VariablePvt) { return "T5_family_random_18448_local_delta"; } return "T1_T4_family_random_40k_merged_autofit"; } QString nmSurrogate::getSurrogateStage() const { if(!m_context.modelStage.isEmpty()) return m_context.modelStage; // 当前代理模型的数据生成阶段。v2_q 表示训练时包含流量制度 q 的变化。 return "family_random_v2_q"; } double nmSurrogate::getSurrogateKeepFraction() const { // 强递减生产制度下代理排序风险更高,因此保留更多 top 粒子进入真实求解器。 if(getSurrogateStage().contains("v2_q") && isStrongDecliningProductionSchedule()) { return kSurrogateHighRiskKeepFraction; } return kSurrogateKeepFraction; } double nmSurrogate::getSurrogateAuditFraction() const { // 随机审计比例,审计的是代理模型筛掉的候选。 return kSurrogateAuditFraction; } double nmSurrogate::getSurrogateMinSolverFraction() const { // 每代真实求解器最低覆盖比例。强递减生产制度下提高到高风险配置。 if(getSurrogateStage().contains("v2_q") && isStrongDecliningProductionSchedule()) { return kSurrogateHighRiskMinSolverFraction; } return kSurrogateMinSolverFraction; } int nmSurrogate::getSurrogateWarmupIterations() const { // 前若干代不筛选,确保粒子先建立真实 pbest。 return kSurrogateWarmupIterations; } int nmSurrogate::getSurrogateFullSolverInterval() const { // 周期性全量真实评价间隔,用于审计代理模型排序。 return kSurrogateFullSolverInterval; } bool nmSurrogate::writeSurrogateCandidateCsv(const QString& candidatePath, bool includeGuideCandidates) const { // 写给 Python 代理模型的候选粒子 CSV。 // // 文件位于本次运行目录的 surrogate/candidates.csv,并在每代读取后删除。 // 字段顺序必须与 ML 脚本 score_pso_candidates*.py 保持一致: // particle_id,k,skin,wellboreC,phi,h,Cf,solverType // // 这里写的是“完整参数体系”中的关键字段,不是粒子内部紧凑向量。 // T1/T3 的 Cf 不影响真实求解,模型输入固定为训练值,避免界面 Cf 把模型带出训练分布。 QFile file(candidatePath); if(!file.open(QIODevice::WriteOnly | QIODevice::Text)) { DEBUG_OUT(QString("Failed to open surrogate candidate file: %1").arg(candidatePath)); return false; } QTextStream out(&file); if(!m_context.available) { DEBUG_OUT("Failed to write surrogate candidates: data manager is unavailable"); return false; } int solverType = static_cast(m_context.solverType); bool useConstPvtTrainingCf = solverType == static_cast(SMT_Oil_ConstPvt) || solverType == static_cast(SMT_Water_ConstPvt); // 代理模型只需要这些输入字段;其它参数当前不在训练输入集中。 out << "particle_id,k,skin,wellboreC,phi,h,Cf,solverType\n"; for(int i = 0; i < m_swarm.size(); ++i) { QVector params = buildTraceParameterVector(m_swarm[i].position); QString cfForModel = useConstPvtTrainingCf ? QString::number(kSurrogateConstPvtCfFixed, 'g', 17) : traceParamAt(params, 6); QStringList cols; cols << QString::number(i) << traceParamAt(params, 0) << traceParamAt(params, 1) << traceParamAt(params, 2) << traceParamAt(params, 3) << traceParamAt(params, 4) << cfForModel << QString::number(solverType); out << cols.join(",") << "\n"; } if(includeGuideCandidates) { // T1-T5 都需要判断当前位置是否优于自己的 guide pbest。当前位置和 guide 必须在 // 同一次代理推理中评分,避免把模型预测误差与真实求解器误差直接比较。 for(int i = 0; i < m_swarm.size(); ++i) { const QVector& guidePosition = m_swarm[i].guideBestPosition.size() == m_swarm[i].position.size() ? m_swarm[i].guideBestPosition : m_swarm[i].bestPosition; QVector params = buildTraceParameterVector(guidePosition); QString cfForModel = useConstPvtTrainingCf ? QString::number(kSurrogateConstPvtCfFixed, 'g', 17) : traceParamAt(params, 6); QStringList cols; cols << QString::number(m_swarm.size() + i) << traceParamAt(params, 0) << traceParamAt(params, 1) << traceParamAt(params, 2) << traceParamAt(params, 3) << traceParamAt(params, 4) << cfForModel << QString::number(solverType); out << cols.join(",") << "\n"; } } file.flush(); file.close(); return true; } bool nmSurrogate::runSurrogateScoringProcess(const QString& candidatePath, const QString& scorePath, QString* failureReason) { if(m_cancelRequested) { if(failureReason) *failureReason = fitTr("Cancelled"); return false; } // 代理评分统一入口。优先走常驻 Python server,失败后降级为一次性脚本。 // 常驻 server 可以避免每一代重复加载模型,速度更快;一次性脚本更稳,适合作为兜底。 QString serverFailure; if(requestSurrogateScoresFromServer(candidatePath, scorePath, &serverFailure)) { return true; } emit logMessageGenerated(fitTr("Surrogate scoring server unavailable; falling back to one-shot Python scoring")); if(!serverFailure.isEmpty()) { emit logMessageGenerated(fitTr("Surrogate scoring server detail: %1").arg(serverFailure)); } stopSurrogateScoringServer(); return runSurrogateScoringScriptOnce(candidatePath, scorePath, failureReason); } bool nmSurrogate::ensureSurrogateScoringServer(QString* failureReason, bool waitForReady) { if(m_cancelRequested) { if(failureReason) *failureReason = fitTr("Cancelled"); return false; } // 确保常驻代理评分 server 已启动且与当前 run 配置匹配。 // // serverKey 由 Python 路径、脚本路径、跟踪元数据、模型标识和阶段组成。 // 只要其中任何一个变化,就停止旧进程并启动新进程,避免拿旧模型或旧目标曲线评分。 if(m_surrogateContextFilePath.isEmpty() || !QFileInfo(m_surrogateContextFilePath).exists()) { QString reason = fitTr("surrogate context file is missing"); DEBUG_OUT(QString("Surrogate scoring server skipped: %1").arg(reason)); if(failureReason) { *failureReason = reason; } return false; } QString mlRoot = getMlRootPath(); QString scriptPath = QDir(mlRoot).absoluteFilePath("scripts/score_pso_candidates_server.py"); if(!QFileInfo(scriptPath).exists()) { QString reason = fitTr("surrogate scoring server script not found: %1").arg(scriptPath); DEBUG_OUT(reason); if(failureReason) { *failureReason = reason; } return false; } QString pythonPath = getPythonExecutablePath(); QString serverKey = QString("%1|%2|%3|%4|%5") .arg(pythonPath) .arg(scriptPath) .arg(m_surrogateContextFilePath) .arg(getSurrogateTag()) .arg(getSurrogateStage()); bool matchingProcessRunning = m_surrogateScoringProcess && m_surrogateScoringProcess->state() == QProcess::Running && m_surrogateScoringServerKey == serverKey; if(!matchingProcessRunning) { stopSurrogateScoringServer(); QStringList args; // -u 关闭 Python 标准输出和错误输出的缓冲,C++ 可以及时读到就绪或完成消息。 args << "-u" << scriptPath << "--trace-meta" << m_surrogateContextFilePath << "--tag" << getSurrogateTag() << "--stage" << getSurrogateStage(); m_surrogateScoringProcess = new QProcess(this); m_surrogateScoringProcess->setWorkingDirectory(mlRoot); emit logMessageGenerated( fitTr("Starting surrogate scoring server: python=%1, mlRoot=%2").arg(pythonPath).arg(mlRoot)); m_surrogateScoringProcess->start(pythonPath, args); if(!m_surrogateScoringProcess->waitForStarted(15000)) { QString reason = fitTr("failed to start scoring server: python=%1, script=%2, error=%3") .arg(pythonPath) .arg(scriptPath) .arg(m_surrogateScoringProcess->errorString()); DEBUG_OUT(reason); stopSurrogateScoringServer(); if(failureReason) { *failureReason = reason; } return false; } m_surrogateScoringServerKey = serverKey; m_surrogateScoringServerReady = false; } // 预热调用只负责尽早启动 Python,让模型加载与初始解、预热代真实求解重叠。 // 第一次真正评分时会再次进入本函数并等待 ready=true。 if(!waitForReady) { return true; } if(m_surrogateScoringServerReady) { return true; } QTime timer; timer.start(); QByteArray readyLine; while(timer.elapsed() < 120000) { // server 启动协议:Python 首先输出一行 JSON,包含 ready=true 或 ok=false。 // C++ 不做完整 JSON 解析,只检查关键字段,降低 Qt 版本依赖。 if(m_surrogateScoringProcess->state() != QProcess::Running) { QString stdOut = QString::fromLocal8Bit(m_surrogateScoringProcess->readAllStandardOutput()).trimmed(); QString stdErr = QString::fromLocal8Bit(m_surrogateScoringProcess->readAllStandardError()).trimmed(); QString reason = fitTr("scoring server exited before ready: stdout=%1, stderr=%2") .arg(stdOut.isEmpty() ? fitTr("") : stdOut) .arg(stdErr.isEmpty() ? fitTr("") : stdErr); DEBUG_OUT(reason); stopSurrogateScoringServer(); if(failureReason) { *failureReason = reason; } return false; } if(!m_surrogateScoringProcess->canReadLine()) { m_surrogateScoringProcess->waitForReadyRead(500); pollEvents(); if(m_cancelRequested) { if(failureReason) *failureReason = fitTr("Cancelled"); return false; } continue; } readyLine = m_surrogateScoringProcess->readLine().trimmed(); if(readyLine.contains("\"ready\"") && readyLine.contains("true")) { m_surrogateScoringServerReady = true; QString stdErr = QString::fromLocal8Bit(m_surrogateScoringProcess->readAllStandardError()).trimmed(); if(!stdErr.isEmpty()) { emit logMessageGenerated(fitTr("Surrogate scoring server stderr: %1").arg(stdErr)); } return true; } if(readyLine.contains("\"ok\"") && readyLine.contains("false")) { QString reason = fitTr("scoring server failed during initialization: %1").arg(QString::fromLocal8Bit(readyLine)); DEBUG_OUT(reason); stopSurrogateScoringServer(); if(failureReason) { *failureReason = reason; } return false; } } QString stdErr = QString::fromLocal8Bit(m_surrogateScoringProcess->readAllStandardError()).trimmed(); QString reason = fitTr("scoring server ready timeout: stderr=%1").arg(stdErr.isEmpty() ? fitTr("") : stdErr); DEBUG_OUT(reason); stopSurrogateScoringServer(); if(failureReason) { *failureReason = reason; } return false; } bool nmSurrogate::requestSurrogateScoresFromServer(const QString& candidatePath, const QString& scorePath, QString* failureReason) { if(m_cancelRequested) { if(failureReason) *failureReason = fitTr("Cancelled"); return false; } // 向常驻 Python server 发送一次评分请求。 // 请求通过 stdin 传 JSON 行,server 读取候选 CSV 后把评分写入 scorePath, // 再通过 stdout 返回 ok=true/false。 if(!ensureSurrogateScoringServer(failureReason)) { return false; } QFile::remove(scorePath); QString command = QString("{\"cmd\":\"score\",\"candidates\":%1,\"output\":%2}\n") .arg(jsonEscape(candidatePath)) .arg(jsonEscape(scorePath)); QByteArray bytes = command.toUtf8(); qint64 written = m_surrogateScoringProcess->write(bytes); if(written != bytes.size() || !m_surrogateScoringProcess->waitForBytesWritten(10000)) { QString reason = fitTr("failed to send scoring request to server: written=%1 expected=%2 error=%3") .arg(written) .arg(bytes.size()) .arg(m_surrogateScoringProcess->errorString()); DEBUG_OUT(reason); if(failureReason) { *failureReason = reason; } return false; } QTime timer; timer.start(); while(timer.elapsed() < 120000) { // 每次请求最多等待 120 秒。超时或 server 退出都会让本代代理筛选降级为全量真实求解器。 if(m_surrogateScoringProcess->state() != QProcess::Running) { QString stdOut = QString::fromLocal8Bit(m_surrogateScoringProcess->readAllStandardOutput()).trimmed(); QString stdErr = QString::fromLocal8Bit(m_surrogateScoringProcess->readAllStandardError()).trimmed(); QString reason = fitTr("scoring server exited during request: stdout=%1, stderr=%2") .arg(stdOut.isEmpty() ? fitTr("") : stdOut) .arg(stdErr.isEmpty() ? fitTr("") : stdErr); DEBUG_OUT(reason); if(failureReason) { *failureReason = reason; } return false; } if(!m_surrogateScoringProcess->canReadLine()) { m_surrogateScoringProcess->waitForReadyRead(500); pollEvents(); if(m_cancelRequested) { if(failureReason) *failureReason = fitTr("Cancelled"); return false; } continue; } QByteArray lineBytes = m_surrogateScoringProcess->readLine().trimmed(); QString line = QString::fromLocal8Bit(lineBytes); if(line.contains("\"ok\"") && line.contains("true")) { QFileInfo scoreInfo(scorePath); if(scoreInfo.exists() && scoreInfo.size() > 0) { QString stdErr = QString::fromLocal8Bit(m_surrogateScoringProcess->readAllStandardError()).trimmed(); if(!stdErr.isEmpty()) { emit logMessageGenerated(fitTr("Surrogate scoring server stderr: %1").arg(stdErr)); } return true; } QString reason = fitTr("scoring server reported success but score file is missing: %1").arg(scorePath); DEBUG_OUT(reason); if(failureReason) { *failureReason = reason; } return false; } if(line.contains("\"ok\"") && line.contains("false")) { QString reason = fitTr("scoring server request failed: %1").arg(line); DEBUG_OUT(reason); if(failureReason) { *failureReason = reason; } return false; } } QString reason = fitTr("scoring server request timed out"); DEBUG_OUT(reason); if(failureReason) { *failureReason = reason; } return false; } void nmSurrogate::stopSurrogateScoringServer() { // 停止常驻 Python 评分进程。 // 先发送 quit 指令,短时间内不退出再 kill,避免应用关闭时遗留 python.exe。 if(!m_surrogateScoringProcess) { m_surrogateScoringServerKey.clear(); m_surrogateScoringServerReady = false; return; } if(m_surrogateScoringProcess->state() == QProcess::Running) { m_surrogateScoringProcess->write("{\"cmd\":\"quit\"}\n"); m_surrogateScoringProcess->waitForBytesWritten(1000); m_surrogateScoringProcess->waitForFinished(3000); if(m_surrogateScoringProcess->state() == QProcess::Running) { m_surrogateScoringProcess->kill(); m_surrogateScoringProcess->waitForFinished(3000); } } delete m_surrogateScoringProcess; m_surrogateScoringProcess = nullptr; m_surrogateScoringServerKey.clear(); m_surrogateScoringServerReady = false; } bool nmSurrogate::runSurrogateScoringScriptOnce(const QString& candidatePath, const QString& scorePath, QString* failureReason) { if(m_cancelRequested) { if(failureReason) *failureReason = fitTr("Cancelled"); return false; } // 一次性代理评分脚本兜底路径。 // // 输入: // - candidates:writeSurrogateCandidateCsv() 写出的粒子参数; // - trace-meta:目标曲线、流量制度、参数上下界等上下文; // - tag/stage:选择 ML 侧模型。 // // 输出: // - scorePath:Python 写出的评分 CSV,随后由 readSurrogateScores() 读取。 if(m_surrogateContextFilePath.isEmpty() || !QFileInfo(m_surrogateContextFilePath).exists()) { QString reason = fitTr("surrogate context file is missing"); DEBUG_OUT(QString("Surrogate scoring skipped: %1").arg(reason)); if(failureReason) { *failureReason = reason; } return false; } QString mlRoot = getMlRootPath(); QString scriptPath = QDir(mlRoot).absoluteFilePath("scripts/score_pso_candidates.py"); if(!QFileInfo(scriptPath).exists()) { QString reason = fitTr("surrogate scoring script not found: %1").arg(scriptPath); DEBUG_OUT(reason); if(failureReason) { *failureReason = reason; } return false; } QString pythonPath = getPythonExecutablePath(); QStringList args; args << scriptPath << "--candidates" << candidatePath << "--trace-meta" << m_surrogateContextFilePath << "--output" << scorePath << "--tag" << getSurrogateTag() << "--stage" << getSurrogateStage(); QFile::remove(scorePath); QString lastFailure; for(int attempt = 1; attempt <= kSurrogateScoringMaxAttempts; ++attempt) { // 评分脚本可能因首次加载模型、文件占用或环境抖动失败,因此允许有限重试。 emit logMessageGenerated(fitTr("Surrogate scoring attempt %1/%2: python=%3, mlRoot=%4") .arg(attempt) .arg(kSurrogateScoringMaxAttempts) .arg(pythonPath) .arg(mlRoot)); QProcess process; process.setWorkingDirectory(mlRoot); process.start(pythonPath, args); if(!process.waitForStarted(10000)) { lastFailure = fitTr("failed to start scoring process (attempt %1/%2): python=%3, script=%4, error=%5") .arg(attempt) .arg(kSurrogateScoringMaxAttempts) .arg(pythonPath) .arg(scriptPath) .arg(process.errorString()); DEBUG_OUT(lastFailure); if(attempt < kSurrogateScoringMaxAttempts) { emit logMessageGenerated( fitTr("Surrogate scoring start failed, retrying once: %1").arg(process.errorString())); msleep(500); continue; } if(failureReason) { *failureReason = lastFailure; } return false; } if(!process.waitForFinished(120000)) { process.kill(); process.waitForFinished(3000); QString stdOut = QString::fromLocal8Bit(process.readAllStandardOutput()).trimmed(); QString stdErr = QString::fromLocal8Bit(process.readAllStandardError()).trimmed(); lastFailure = fitTr("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() ? fitTr("") : stdOut) .arg(stdErr.isEmpty() ? fitTr("") : stdErr); DEBUG_OUT(lastFailure); if(attempt < kSurrogateScoringMaxAttempts) { emit logMessageGenerated(fitTr("Surrogate scoring timed out, retrying once")); msleep(500); continue; } if(failureReason) { *failureReason = lastFailure; } return false; } QString stdOut = QString::fromLocal8Bit(process.readAllStandardOutput()).trimmed(); QString stdErr = QString::fromLocal8Bit(process.readAllStandardError()).trimmed(); if(process.exitStatus() != QProcess::NormalExit || process.exitCode() != 0) { lastFailure = fitTr("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() ? fitTr("") : stdOut) .arg(stdErr.isEmpty() ? fitTr("") : stdErr); DEBUG_OUT(lastFailure); if(attempt < kSurrogateScoringMaxAttempts) { emit logMessageGenerated( fitTr("Surrogate scoring process failed, retrying once: exitCode=%1").arg(process.exitCode())); msleep(500); continue; } if(failureReason) { *failureReason = lastFailure; } return false; } QFileInfo scoreInfo(scorePath); if(!scoreInfo.exists() || scoreInfo.size() <= 0) { lastFailure = fitTr("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() ? fitTr("") : stdOut) .arg(stdErr.isEmpty() ? fitTr("") : stdErr); DEBUG_OUT(lastFailure); if(attempt < kSurrogateScoringMaxAttempts) { emit logMessageGenerated(fitTr("Surrogate scoring produced no score file, retrying once")); msleep(500); continue; } if(failureReason) { *failureReason = lastFailure; } return false; } if(!stdErr.isEmpty()) { emit logMessageGenerated(fitTr("Surrogate scoring stderr: %1").arg(stdErr)); } if(!stdOut.isEmpty()) { emit logMessageGenerated(fitTr("Surrogate scoring stdout: %1").arg(stdOut)); } return true; } if(failureReason) { *failureReason = lastFailure; } return false; } QVector nmSurrogate::readSurrogateScores(const QString& scorePath, int expectedCount) const { // 读取 Python 输出的评分 CSV。 // // 当前脚本约定至少包含: // particle_id,surrogate_objective,...,success // 本函数只读取 particle_id、score 和 success 标志。失败或缺失的粒子保持 NaN, // 后续 buildSurrogateEvaluationMask() 会通过 fallback_gate 强制跑真实求解器。 QVector scores(expectedCount, std::numeric_limits::quiet_NaN()); QFile file(scorePath); if(!file.open(QIODevice::ReadOnly | QIODevice::Text)) { DEBUG_OUT(QString("Failed to open surrogate score file: %1").arg(scorePath)); return scores; } QTextStream in(&file); bool firstLine = true; while(!in.atEnd()) { QString line = in.readLine().trimmed(); if(line.isEmpty()) { continue; } if(firstLine) { firstLine = false; continue; } QStringList parts = line.split(","); if(parts.size() < 5) { continue; } bool idOk = false; bool scoreOk = false; int particleId = parts[0].toInt(&idOk); double score = parts[1].toDouble(&scoreOk); bool success = parts[4].trimmed() == "1"; if(idOk && scoreOk && success && particleId >= 0 && particleId < scores.size()) { scores[particleId] = score; } } return scores; } bool nmSurrogate::isSurrogateRunContextSupported(QString* reason) const { // 判断“当前项目工况”是否适合使用代理模型。 // 这是运行级别的 gate:只要项目整体不满足训练域条件,本次 PSO 全程退回真实求解器。 // 这样做比盲目调用代理模型更稳,因为代理模型只在特定 PEBI/单井/垂直井/无复杂几何场景训练过。 if(!m_context.available) { if(reason) *reason = fitTr("data manager is unavailable"); return false; } int solverModelType = m_context.solverType; SurrogateParameterDomain parameterDomain; bool isSupportedSolverType = getSurrogateParameterDomain(solverModelType, ¶meterDomain); if(!isSupportedSolverType) { if(reason) { *reason = fitTr("solverType=%1 is outside the T1-T5 surrogate model").arg(static_cast(solverModelType)); } return false; } // 网格类型 gate:当前代理模型只按 PEBI 网格样本训练。 if(!m_context.pebiGrid) { if(reason) *reason = fitTr("surrogate model is trained only for PEBI grid cases"); return false; } if(!m_context.targetAvailable) { if(reason) *reason = fitTr("target well '%1' is missing").arg(m_context.targetWell); return false; } // 井型 gate:当前只支持垂直井。水平井/压裂井等几何特征不在训练集中。 if(!m_context.verticalWell) { if(reason) *reason = fitTr("surrogate model is currently limited to vertical-well cases"); return false; } int validCalculationWells = m_context.activeWells; // 单井 gate:训练数据假设只有一口有效计算井,多井干扰会改变压力响应形态。 if(validCalculationWells != 1) { if(reason) *reason = fitTr("surrogate model expects one active calculation well, got %1").arg(validCalculationWells); return false; } // 几何 gate:断层、裂缝、区域变化会引入训练集中没有的边界/非均质影响。 if(m_context.complexGeometry) { if(reason) *reason = fitTr("surrogate model is not enabled for changed fault/fracture/region geometry"); return false; } // 代理支持拟合 k/skin/wellboreC/phi。 QVector allowedParamIndices; allowedParamIndices << 0 << 1 << 2 << 3; for(int i = 0; i < m_enabledParamIndices.size(); ++i) { if(!allowedParamIndices.contains(m_modelParameters[m_enabledParamIndices[i]].type)) { if(reason) { QStringList names = traceParameterNames(); int idx = m_modelParameters[m_enabledParamIndices[i]].type; QString name = (idx >= 0 && idx < names.size()) ? names[idx] : QString::number(idx); *reason = fitTr("parameter '%1' is outside surrogate input set").arg(name); } return false; } } if(parameterDomain.checkCt) { double ct = m_context.physicalParameters.value(5); if(!isNearRelative(ct, parameterDomain.ctFixed, parameterDomain.ctRelTol)) { if(reason) { *reason = fitTr("Ct=%1 does not match surrogate training value %2") .arg(ct, 0, 'g', 10) .arg(parameterDomain.ctFixed, 0, 'g', 10); } return false; } } // 固定 Cf 的 T5 在整次拟合入口检查;T2/T4 的可变 Cf 留到逐粒子阶段检查。 if(parameterDomain.checkCf && !parameterDomain.variableCf) { double cf = m_context.physicalParameters.value(6); bool cfSupported = isNearRelative(cf, parameterDomain.cfFixed, parameterDomain.cfRelTol); if(!cfSupported) { if(reason) { *reason = fitTr("Cf=%1 is outside surrogate domain").arg(cf, 0, 'g', 10); } return false; } } double initialPressure = m_context.initialPressure; if(!isNearRelative(initialPressure, kSurrogateTrainingInitialPressure, 1.0e-4)) { if(reason) { *reason = fitTr("initialPressure=%1 does not match surrogate training context").arg(initialPressure, 0, 'g', 10); } return false; } QVector flowPoints = m_context.flowPoints; // flowPoints 有时第一段是 (0,0) 占位点,不代表真实生产段,先移除。 if(!flowPoints.isEmpty() && qAbs(flowPoints[0].x()) <= 1e-12 && qAbs(flowPoints[0].y()) <= 1e-12) { flowPoints.remove(0); } if(flowPoints.size() < 2) { if(reason) *reason = fitTr("flow schedule is too short for surrogate screening"); return false; } // 约定最后一段是关井段,因此生产段数量 = 总段数 - 1。 int productionSections = flowPoints.size() - 1; if(productionSections < kSurrogateMinProdSections || productionSections > kSurrogateMaxProdSections) { if(reason) { *reason = fitTr("production section count %1 is outside surrogate range [%2,%3]") .arg(productionSections) .arg(kSurrogateMinProdSections) .arg(kSurrogateMaxProdSections); } return false; } double productionTime = 0.0; for(int i = 0; i < productionSections; ++i) { double dt = flowPoints[i].x(); double q = flowPoints[i].y(); if(!isFiniteNumber(dt) || dt <= 0.0 || !isInClosedRange(q, kSurrogateQMin, kSurrogateQMax)) { if(reason) { *reason = fitTr("production schedule section %1 is outside surrogate dt/q domain").arg(i + 1); } return false; } if(i > 0) { // 相邻生产段产量跳变不能太大,否则代理模型可能没见过这种制度。 double previousQ = flowPoints[i - 1].y(); double stepRatio = qMax(q, previousQ) / qMax(1e-12, qMin(q, previousQ)); if(stepRatio > kSurrogateMaxRateStepRatio) { if(reason) { *reason = fitTr("rate step ratio %1 exceeds surrogate domain").arg(stepRatio, 0, 'g', 10); } return false; } } productionTime += dt; } // 旧阶段模型对强递减制度不稳;v2_q 阶段允许但会提高真实求解比例。 if(!getSurrogateStage().contains("v2_q")) { double endStartRatio = std::numeric_limits::quiet_NaN(); if(isStrongDecliningProductionSchedule(&endStartRatio)) { if(reason) { *reason = fitTr("strongly decreasing production schedule ratio %1 is outside surrogate domain") .arg(endStartRatio, 0, 'g', 10); } return false; } } if(!isInClosedRange(productionTime, kSurrogateProdTimeMin, kSurrogateProdTimeMax)) { if(reason) { *reason = fitTr("production total time %1 is outside surrogate range").arg(productionTime, 0, 'g', 10); } return false; } double shutinTime = flowPoints.last().x(); double shutinRate = flowPoints.last().y(); if(!isInClosedRange(shutinTime, kSurrogateShutinTimeMin, kSurrogateShutinTimeMax) || qAbs(shutinRate) > kSurrogateQZeroThreshold) { if(reason) *reason = fitTr("last flow section is not a trained shut-in section"); return false; } // 当前目标段必须是最后的关井段,对应试井解释的双对数分析段。 if(m_context.sectionIndex != flowPoints.size()) { if(reason) { *reason = fitTr("target section index %1 is not the last section %2") .arg(m_context.sectionIndex) .arg(flowPoints.size()); } return false; } return true; } bool nmSurrogate::isSurrogateCandidateInDomain(const QVector& selectedParameters, QString* reason) const { // 判断“单个粒子候选参数”是否在代理模型训练域内。 // 与 isSurrogateRunContextSupported() 不同,这里检查的是粒子参数值本身。 // 超出范围的粒子会被 domain_gate 强制跑真实求解器。 QVector params = buildTraceParameterVector(selectedParameters); double k = params.size() > 0 ? params[0] : std::numeric_limits::quiet_NaN(); double skin = params.size() > 1 ? params[1] : std::numeric_limits::quiet_NaN(); double wellboreC = params.size() > 2 ? params[2] : std::numeric_limits::quiet_NaN(); double phi = params.size() > 3 ? params[3] : std::numeric_limits::quiet_NaN(); double h = params.size() > 4 ? params[4] : std::numeric_limits::quiet_NaN(); double cf = params.size() > 6 ? params[6] : std::numeric_limits::quiet_NaN(); int solverModelType = m_context.solverType; SurrogateParameterDomain parameterDomain; if(!getSurrogateParameterDomain(solverModelType, ¶meterDomain)) { if(reason) *reason = QString("solverType=%1").arg(static_cast(solverModelType)); return false; } if(!isInClosedRange(k, parameterDomain.kMin, parameterDomain.kMax)) { if(reason) *reason = QString("k=%1").arg(k, 0, 'g', 10); return false; } if(!isInClosedRange(skin, parameterDomain.skinMin, parameterDomain.skinMax)) { if(reason) *reason = QString("skin=%1").arg(skin, 0, 'g', 10); return false; } if(!isInClosedRange(wellboreC, parameterDomain.wellboreCMin, parameterDomain.wellboreCMax)) { if(reason) *reason = QString("wellboreC=%1").arg(wellboreC, 0, 'g', 10); return false; } if(!isInClosedRange(phi, parameterDomain.phiMin, parameterDomain.phiMax)) { if(reason) *reason = QString("phi=%1").arg(phi, 0, 'g', 10); return false; } if(!isInClosedRange(h, parameterDomain.hMin, parameterDomain.hMax)) { if(reason) *reason = QString("h=%1").arg(h, 0, 'g', 10); return false; } // 只有参与搜索的 T2/T4 Cf 需要逐粒子检查;T5 固定 Cf 已在运行入口确认。 if(parameterDomain.checkCf && parameterDomain.variableCf) { bool cfSupported = isInClosedRange(cf, parameterDomain.cfMin, parameterDomain.cfMax); if(!cfSupported) { if(reason) *reason = QString("Cf=%1").arg(cf, 0, 'g', 10); return false; } } return true; } bool nmSurrogate::forceSolverByFallbackGate(const QVector& selectedParameters) const { // 经验 fallback gate。 // 有些点虽然还在训练域边界内,但组合起来属于代理模型容易排序失真的区域, // 例如极低渗透率配大井筒储集、极端 skin 等。遇到这些候选时直接跑真实求解器。 QVector params = buildTraceParameterVector(selectedParameters); double k = params.size() > 0 ? params[0] : std::numeric_limits::quiet_NaN(); double skin = params.size() > 1 ? params[1] : std::numeric_limits::quiet_NaN(); double wellboreC = params.size() > 2 ? params[2] : std::numeric_limits::quiet_NaN(); double phi = params.size() > 3 ? params[3] : std::numeric_limits::quiet_NaN(); double h = params.size() > 4 ? params[4] : std::numeric_limits::quiet_NaN(); if(!isFiniteNumber(k) || !isFiniteNumber(skin) || !isFiniteNumber(wellboreC) || !isFiniteNumber(phi) || !isFiniteNumber(h)) { return true; } if(k <= 1e-3 && wellboreC > 0.5) { return true; } if(phi < 0.03 && h < 4.0) { return true; } if(k < 0.1 && h >= 50.0) { return true; } if(qAbs(skin) > 6.0) { return true; } return false; } bool nmSurrogate::isStrongDecliningProductionSchedule(double* endStartRatio) const { // 判断生产段产量是否整体非增且首末下降明显。 // 这类流量制度代理模型风险更高,所以 keep/min_solver 会自动提高。 if(endStartRatio) { *endStartRatio = std::numeric_limits::quiet_NaN(); } if(!m_context.available) { return false; } if(!m_context.targetAvailable) { return false; } QVector flowPoints = m_context.flowPoints; if(!flowPoints.isEmpty() && qAbs(flowPoints[0].x()) <= 1e-12 && qAbs(flowPoints[0].y()) <= 1e-12) { flowPoints.remove(0); } if(flowPoints.size() < 2) { return false; } int productionSections = flowPoints.size() - 1; bool productionRatesNonIncreasing = true; bool productionRatesHaveMeaningfulDrop = false; for(int i = 0; i < productionSections; ++i) { double q = flowPoints[i].y(); if(!isFiniteNumber(q)) { return false; } if(i > 0) { double previousQ = flowPoints[i - 1].y(); if(q > previousQ * (1.0 + kSurrogateRateTrendRelTol)) { productionRatesNonIncreasing = false; } if(q < previousQ * (1.0 - kSurrogateRateTrendRelTol)) { productionRatesHaveMeaningfulDrop = true; } } } if(!productionRatesNonIncreasing || !productionRatesHaveMeaningfulDrop) { return false; } double firstRate = flowPoints.first().y(); double lastProductionRate = flowPoints[productionSections - 1].y(); double ratio = lastProductionRate / qMax(1e-12, firstRate); if(endStartRatio) { *endStartRatio = ratio; } return ratio < kSurrogateStrongDeclineEndStartRatio; } void nmSurrogate::resetGuideBestToVerified() { // 全量真实评价或代理降级时,丢弃尚未验证的引导位置。 // 真实 bestPosition/bestFitness 始终是唯一可信的 pbest/gbest 数据源。 for(int i = 0; i < m_swarm.size(); ++i) { AutoFitParticle& particle = m_swarm[i]; if(particle.bestPosition.size() == particle.position.size()) { particle.guideBestPosition = particle.bestPosition; particle.guideBestObjective = particle.bestFitness; particle.guideBestFromSurrogate = false; } } } QVector nmSurrogate::buildSurrogateEvaluationMask() { // 返回值 evaluateMask 与 m_swarm 一一对应: // true 表示该粒子本代需要继续跑真实数值求解器; // false 表示该粒子本代被代理模型筛掉,只记录 screened_out,不更新 pbest/gbest。 // // 这个函数是 PSO acceleration 的唯一入口。为了保证结果可信,它包含多层保护: // 1. 工况不支持代理模型时,全量真实求解器; // 2. 前几代 warmup,全量真实求解器; // 3. 周期性审计,全量真实求解器; // 4. 代理评分失败时,全量真实求解器; // 5. top-k + random audit + fallback + min solver floor 共同决定最终 mask。 QVector evaluateMask(m_swarm.size(), true); for(int i = 0; i < m_swarm.size(); ++i) { m_swarm[i].surrogateObjective = std::numeric_limits::quiet_NaN(); m_swarm[i].selectedForSolver = true; m_swarm[i].selectedByAudit = false; m_swarm[i].screeningDecision = "full_solver"; } if(!isSurrogateScreeningEnabled()) { // 用户关闭 PSO acceleration:保持原始 PSO 行为,所有粒子都跑真实求解器。 resetGuideBestToVerified(); return evaluateMask; } QString contextReason; if(!isSurrogateRunContextSupported(&contextReason)) { // 当前项目工况不在代理模型训练域内。这里不报错,只降级为全量真实求解器, // 这样用户仍能完成自动拟合,只是没有代理加速收益。 m_statistics.m_surrogateContextBlockedIterationCount++; for(int i = 0; i < m_swarm.size(); ++i) { m_swarm[i].screeningDecision = "context_gate_full_solver"; } resetGuideBestToVerified(); emit logMessageGenerated(fitTr("Surrogate screening disabled for this run context: %1").arg(contextReason)); return evaluateMask; } // 前几代全量真实评价,让每个粒子都先获得可信的个体最优 pbest。 // 否则代理模型一开始就筛掉粒子,可能导致某些粒子从未有真实误差基准。 if(m_currentIteration < getSurrogateWarmupIterations()) { m_statistics.m_surrogateWarmupIterationCount++; for(int i = 0; i < m_swarm.size(); ++i) { m_swarm[i].screeningDecision = "warmup_full_solver"; } resetGuideBestToVerified(); return evaluateMask; } if(getSurrogateFullSolverInterval() > 0 && m_currentIteration > 0 && ((m_currentIteration + 1) % getSurrogateFullSolverInterval()) == 0) { // 周期性全量审计。它牺牲少量速度,换取对代理排序偏差的长期纠偏能力。 m_statistics.m_surrogatePeriodicAuditIterationCount++; for(int i = 0; i < m_swarm.size(); ++i) { m_swarm[i].screeningDecision = "periodic_full_solver"; } resetGuideBestToVerified(); emit logMessageGenerated( fitTr("Surrogate audit iteration %1: running full solver for all particles").arg(m_currentIteration + 1)); return evaluateMask; } QDir tempDir(QDir(m_tempDirectory).absoluteFilePath("surrogate")); if(!tempDir.exists() && !QDir().mkpath(tempDir.absolutePath())) { emit logMessageGenerated(fitTr("Surrogate temporary directory is unavailable; using the full solver")); resetGuideBestToVerified(); return evaluateMask; } // 同一代评分是串行请求,固定文件名可安全覆盖,避免每代累积两个 CSV。 const QString candidatePath = tempDir.absoluteFilePath("candidates.csv"); const QString scorePath = tempDir.absoluteFilePath("scores.csv"); QString scoringFailureReason; // 运行上下文已经通过 T1-T5 代理模型门控,所有支持相态都使用引导 pbest。 const bool includeGuideCandidates = true; if(!writeSurrogateCandidateCsv(candidatePath, includeGuideCandidates) || !runSurrogateScoringProcess(candidatePath, scorePath, &scoringFailureReason)) { // 评分失败时删除本代生成的临时 CSV。 QFile::remove(candidatePath); QFile::remove(scorePath); // Python 环境、checkpoint、processed 数据或脚本异常时都走这里。 // 降级策略是全量真实求解器,保证代理模块故障不会中断 PSO 拟合。 emit logMessageGenerated(fitTr("Surrogate screening unavailable; falling back to full solver for iteration %1") .arg(m_currentIteration + 1)); if(!scoringFailureReason.isEmpty()) { emit logMessageGenerated(fitTr("Surrogate scoring failure detail: %1").arg(scoringFailureReason)); } resetGuideBestToVerified(); return evaluateMask; } int expectedScoreCount = m_swarm.size() * (includeGuideCandidates ? 2 : 1); QVector allScores = readSurrogateScores(scorePath, expectedScoreCount); // 分数读入内存后删除本代候选和评分 CSV。 QFile::remove(candidatePath); QFile::remove(scorePath); QVector scores(m_swarm.size(), std::numeric_limits::quiet_NaN()); QVector guideScores(m_swarm.size(), std::numeric_limits::quiet_NaN()); QVector finiteScoreIndices; // 只接受成功写出的有限代理目标函数。失败候选后面会通过 fallback 强制真实评价。 for(int i = 0; i < m_swarm.size(); ++i) { if(i < allScores.size()) { scores[i] = allScores[i]; } if(includeGuideCandidates && m_swarm.size() + i < allScores.size()) { guideScores[i] = allScores[m_swarm.size() + i]; if(isFiniteNumber(guideScores[i])) { m_swarm[i].guideBestObjective = guideScores[i]; } } m_swarm[i].surrogateObjective = scores[i]; if(isFiniteNumber(scores[i])) { finiteScoreIndices.append(i); } } if(finiteScoreIndices.isEmpty()) { emit logMessageGenerated(fitTr("Surrogate scoring returned no valid scores; falling back to full solver")); resetGuideBestToVerified(); return evaluateMask; } std::sort(finiteScoreIndices.begin(), finiteScoreIndices.end(), [&](int a, int b) { return scores[a] < scores[b]; }); // 代理目标函数越小越好。先将所有粒子设为 screened_out,再逐步放回需要真实评价的粒子。 evaluateMask.fill(false); for(int i = 0; i < m_swarm.size(); ++i) { m_swarm[i].selectedForSolver = false; m_swarm[i].screeningDecision = "screened_out"; } int keepN = qMax(1, qCeil(m_swarm.size() * getSurrogateKeepFraction())); keepN = qMin(keepN, finiteScoreIndices.size()); // 代理评分 top-k:这些粒子最可能给出好解,优先跑真实求解器。 for(int rank = 0; rank < keepN; ++rank) { int idx = finiteScoreIndices[rank]; evaluateMask[idx] = true; m_swarm[idx].selectedForSolver = true; m_swarm[idx].screeningDecision = "surrogate_topk"; } QVector> auditCandidates; // 随机审计:从代理模型认为“不好”的候选中抽查一部分。 // 使用 deterministicAuditRandom01 保证同一随机种子下 trace 可复现。 for(int i = 0; i < finiteScoreIndices.size(); ++i) { int idx = finiteScoreIndices[i]; if(!evaluateMask[idx]) { auditCandidates.append( qMakePair(deterministicAuditRandom01(m_psoRandomSeed, m_currentIteration, idx), idx)); } } std::sort(auditCandidates.begin(), auditCandidates.end(), [](const QPair& a, const QPair& b) { return a.first < b.first; }); int auditN = qMin(auditCandidates.size(), qCeil(m_swarm.size() * getSurrogateAuditFraction())); for(int i = 0; i < auditN; ++i) { int idx = auditCandidates[i].second; evaluateMask[idx] = true; m_swarm[idx].selectedForSolver = true; m_swarm[idx].selectedByAudit = true; m_swarm[idx].screeningDecision = "random_audit"; } int fallbackCount = 0; int domainFallbackCount = 0; // fallback gate:只要候选点超出代理训练域、代理评分无效、粒子还没有可靠 pbest, // 或落入经验高风险区域,就强制真实求解。这样做是为了保护 PSO 收敛质量。 for(int i = 0; i < m_swarm.size(); ++i) { QString domainReason; bool domainFallback = !isSurrogateCandidateInDomain(m_swarm[i].position, &domainReason); bool fallback = !isFiniteNumber(scores[i]) || m_swarm[i].bestFitness >= 1e9 || forceSolverByFallbackGate(m_swarm[i].position) || domainFallback; if(fallback) { if(!evaluateMask[i]) { fallbackCount++; } if(domainFallback) { domainFallbackCount++; } evaluateMask[i] = true; m_swarm[i].selectedForSolver = true; m_swarm[i].screeningDecision = domainFallback ? "domain_gate" : "fallback_gate"; } } int selectedCount = 0; for(int i = 0; i < evaluateMask.size(); ++i) { if(evaluateMask[i]) { selectedCount++; } } int minSolverN = qMax(1, qCeil(m_swarm.size() * getSurrogateMinSolverFraction())); if(selectedCount < minSolverN) { // 最小真实求解比例:防止代理模型过度筛选,导致一代中真实误差信息太少。 QVector> extraCandidates; for(int i = 0; i < m_swarm.size(); ++i) { if(!evaluateMask[i] && isFiniteNumber(scores[i])) { extraCandidates.append(qMakePair(scores[i], i)); } } std::sort(extraCandidates.begin(), extraCandidates.end(), [](const QPair& a, const QPair& b) { return a.first < b.first; }); for(int i = 0; i < extraCandidates.size() && selectedCount < minSolverN; ++i) { int idx = extraCandidates[i].second; evaluateMask[idx] = true; m_swarm[idx].selectedForSolver = true; m_swarm[idx].screeningDecision = "min_solver_floor"; selectedCount++; } } int guidePbestUpdateCount = 0; // 单纯按本代绝对误差 top-k 可能漏掉“当前还不够好、但正在显著改善自己 // pbest”的探索粒子。对真正被筛掉的粒子,仅更新一套 // 用于个体认知速度项的引导位置;真实 bestPosition、bestFitness 和 gbest 完全不变。 if(includeGuideCandidates) { for(int i = 0; i < m_swarm.size(); ++i) { AutoFitParticle& particle = m_swarm[i]; if(evaluateMask[i] || !isFiniteNumber(scores[i]) || !isFiniteNumber(guideScores[i])) { continue; } double requiredImprovement = qMax(1.0e-10, qAbs(guideScores[i]) * kSurrogateGuidePbestMinRelativeImprovement); if(guideScores[i] - scores[i] > requiredImprovement) { particle.guideBestPosition = particle.position; particle.guideBestObjective = scores[i]; particle.guideBestFromSurrogate = true; particle.screeningDecision = "screened_out_guide_pbest"; guidePbestUpdateCount++; } } } emit logMessageGenerated(fitTr("Surrogate screening iteration %1: selected %2/%3 particles (keep=%4, audit=%5, " "min_solver=%6, fallback=%7, domain=%8, guide_pbest=%9)") .arg(m_currentIteration + 1) .arg(selectedCount) .arg(m_swarm.size()) .arg(getSurrogateKeepFraction(), 0, 'f', 2) .arg(getSurrogateAuditFraction(), 0, 'f', 2) .arg(getSurrogateMinSolverFraction(), 0, 'f', 2) .arg(fallbackCount) .arg(domainFallbackCount) .arg(guidePbestUpdateCount)); m_statistics.m_surrogateActiveIterationCount++; for(int i = 0; i < m_swarm.size(); ++i) { const QString& decision = m_swarm[i].screeningDecision; if(m_swarm[i].selectedForSolver) { m_statistics.m_surrogateSelectedParticleCount++; } if(decision.startsWith("screened_out")) { m_statistics.m_surrogateScreenedParticleCount++; } else if(decision == "surrogate_topk") { m_statistics.m_surrogateTopKParticleCount++; } else if(decision == "random_audit") { m_statistics.m_surrogateAuditParticleCount++; } else if(decision == "fallback_gate") { m_statistics.m_surrogateFallbackParticleCount++; } else if(decision == "domain_gate") { m_statistics.m_surrogateDomainParticleCount++; } else if(decision == "min_solver_floor") { m_statistics.m_surrogateMinFloorParticleCount++; } } return evaluateMask; } void nmSurrogate::resetRunSummary() { // 重置本次运行的代理筛选统计。这里只记录统计口径,不参与 PSO 更新。 m_statistics.m_surrogateWarmupIterationCount = 0; m_statistics.m_surrogatePeriodicAuditIterationCount = 0; m_statistics.m_surrogateContextBlockedIterationCount = 0; m_statistics.m_surrogateActiveIterationCount = 0; m_statistics.m_surrogateSelectedParticleCount = 0; m_statistics.m_surrogateScreenedParticleCount = 0; m_statistics.m_surrogateTopKParticleCount = 0; m_statistics.m_surrogateAuditParticleCount = 0; m_statistics.m_surrogateFallbackParticleCount = 0; m_statistics.m_surrogateDomainParticleCount = 0; m_statistics.m_surrogateMinFloorParticleCount = 0; } nmSurrogate::nmSurrogate(QObject* parent) : QObject(parent), m_currentIteration(0), m_psoRandomSeed(1792008679u), m_surrogateScoringProcess(nullptr), m_surrogateScoringServerReady(false), m_cancelRequested(0) { resetRunSummary(); } nmSurrogate::~nmSurrogate() { releaseSession(); } void nmSurrogate::cancel() { m_cancelRequested = 1; } void nmSurrogate::pollEvents() { // 仅由软件提供兼容事件泵,独立评分不依赖 QApplication。 if(m_eventPump) m_eventPump(); } void nmSurrogate::releaseSession() { // 只清理本对象创建的工作目录及已知通信文件,不递归删除调用方目录。 stopSurrogateScoringServer(); if(m_tempDirectory.isEmpty()) return; QDir dir(QDir(m_tempDirectory).filePath("surrogate")); const QStringList files = dir.entryList(QDir::Files); for(int i = 0; i < files.size(); ++i) dir.remove(files[i]); QDir().rmdir(dir.absolutePath()); QDir().rmdir(m_tempDirectory); m_tempDirectory.clear(); } bool nmSurrogate::configure(const nmSurrogateContext& context, QString* error) { // 每次 configure 建立独占目录,候选文件不会跨运行串用。 releaseSession(); m_context = context; m_cancelRequested = 0; resetRunSummary(); if(error) error->clear(); m_surrogateContextFilePath.clear(); if(!context.enabled) return true; m_modelParameters = context.parameters; m_enabledParamIndices.clear(); for(int i = 0; i < m_modelParameters.size(); ++i) if(m_modelParameters[i].selected) m_enabledParamIndices.append(i); const QString root = context.workDirectory.isEmpty() ? QDir::tempPath() : context.workDirectory; m_tempDirectory = QDir(root).filePath("nmSurrogate-" + QUuid::createUuid().toString().remove('{').remove('}')); if(!QDir().mkpath(QDir(m_tempDirectory).filePath("surrogate")) || !writeContext()) { if(error) *error = fitTr("Cannot prepare surrogate context"); return false; } return true; } bool nmSurrogate::writeContext() { // 评分上下文是计算输入,与诊断 trace 是否启用无关。 m_surrogateContextFilePath = QDir(m_tempDirectory).filePath("surrogate/context.meta.json"); QFile file(m_surrogateContextFilePath); if(!file.open(QIODevice::WriteOnly | QIODevice::Text)) return false; QTextStream out(&file); out << "{\"target\":{\"well_name\":" << jsonEscape(m_context.targetWell) << ",\"section_index\":" << m_context.sectionIndex << ",\"flow_points\":" << jsonPointArray(m_context.flowPoints) << ",\"target_loglog\":{\"time\":" << jsonDoubleArray(m_context.targetCurve.value(0)) << ",\"pressure\":" << jsonDoubleArray(m_context.targetCurve.value(1)) << ",\"derivative\":" << jsonDoubleArray(m_context.targetCurve.value(2)) << "}}}"; return file.flush(); } QVector nmSurrogate::buildTraceParameterVector(const QVector& parameters) const { // 固定物理特征只在启动时捕获,候选值按参数类型覆盖。 QVector full = m_context.physicalParameters; full.resize(7); for(int i = 0; i < parameters.size() && i < m_enabledParamIndices.size(); ++i) { const nmFitParameterValue& p = m_modelParameters[m_enabledParamIndices[i]]; if(p.type >= 0 && p.type <= 3 && (p.wellCode.isEmpty() || p.wellCode == m_context.targetWellCode)) full[p.type] = parameters[i]; } return full; } QVector nmSurrogate::scoreCandidates(const QVector>& candidates, QString* error) { // 独立评分无需创建 PSO;内部 CSV 继续使用原脚本协议。 QVector invalid(candidates.size(), std::numeric_limits::quiet_NaN()); if(error) error->clear(); if(!m_context.enabled || m_tempDirectory.isEmpty()) { if(error) *error = fitTr("Surrogate is not configured or is disabled"); return invalid; } if(!isSurrogateRunContextSupported(error) || m_cancelRequested) return invalid; m_swarm.clear(); QVector candidateIndices; for(int i = 0; i < candidates.size(); ++i) { if(candidates[i].size() != m_enabledParamIndices.size()) { if(error) *error = fitTr("Candidate parameter count mismatch"); return invalid; } // 独立评分沿用 PSO 的训练域检查;无效项保留 NaN,不交给评分进程。 if(!isSurrogateCandidateInDomain(candidates[i], nullptr)) continue; AutoFitParticle p; p.position = candidates[i]; m_swarm.append(p); candidateIndices.append(i); } if(m_swarm.isEmpty()) return invalid; const QDir dir(QDir(m_tempDirectory).filePath("surrogate")); const QString input = dir.filePath("candidates.csv"), output = dir.filePath("scores.csv"); bool ok = writeSurrogateCandidateCsv(input, false) && runSurrogateScoringProcess(input, output, error); QVector result = invalid; if(ok) { const QVector scores = readSurrogateScores(output, candidateIndices.size()); for(int i = 0; i < candidateIndices.size(); ++i) result[candidateIndices[i]] = scores[i]; } QFile::remove(input); QFile::remove(output); return result; } QVector nmSurrogate::select(const QVector& particles, int iteration, unsigned int seed) { // 策略操作本地值快照,PSO 只接收筛选和引导字段。 m_swarm = particles; m_currentIteration = iteration; m_psoRandomSeed = seed; buildSurrogateEvaluationMask(); return m_swarm; } bool nmSurrogate::preserveGuide(const AutoFitParticle& particle, bool beatsGlobalBest) const { // 原 updateParticle 中的引导保留判断原样迁移,真实最优仍由 PSO 维护。 if(!beatsGlobalBest && m_context.enabled && particle.guideBestFromSurrogate && isFiniteNumber(particle.guideBestObjective) && isFiniteNumber(particle.surrogateObjective)) { double requiredImprovement = qMax(1.0e-10, qAbs(particle.guideBestObjective) * kSurrogateGuidePbestMinRelativeImprovement); return particle.surrogateObjective - particle.guideBestObjective > requiredImprovement; } return false; } void nmSurrogate::begin() { // 与原 PSO 一样提前异步预热,首次评分时再等待模型就绪。 QString reason; if(isSurrogateScreeningEnabled() && isSurrogateRunContextSupported(&reason)) { if(ensureSurrogateScoringServer(&reason, false)) emit logMessageGenerated(fitTr("Surrogate model prewarming started in background")); else if(!reason.isEmpty()) emit logMessageGenerated(fitTr("Surrogate model prewarm deferred: %1").arg(reason)); } }