|
|
#include "nmFitPSO.h"
|
|
|
|
|
|
#include <QCoreApplication>
|
|
|
#include <QDebug>
|
|
|
#include <QDateTime>
|
|
|
#include <QTime>
|
|
|
#include <QtCore/qmath.h>
|
|
|
#include <cmath>
|
|
|
#include <float.h>
|
|
|
#include <exception>
|
|
|
#include <limits>
|
|
|
|
|
|
/** @brief 获取提示文本;未加载对应翻译时返回原文。 */
|
|
|
static QString fitTr(const char* text)
|
|
|
{
|
|
|
return QCoreApplication::translate("nmCalculationAutoFitPSO", text);
|
|
|
}
|
|
|
|
|
|
#ifdef Q_OS_WIN
|
|
|
#include <windows.h>
|
|
|
#define DEBUG_OUT(msg) OutputDebugStringA(QString("[nmFitPSO] %1\n").arg(msg).toLocal8Bit().data())
|
|
|
#else
|
|
|
#define DEBUG_OUT(msg) qDebug() << msg
|
|
|
#endif
|
|
|
|
|
|
// ===== PSO基础常量 =====
|
|
|
// VELOCITY_LIMIT_FACTOR:单次速度最大值占参数搜索区间的比例,防止粒子一步跨太远。
|
|
|
const double nmFitPSO::VELOCITY_LIMIT_FACTOR = 0.2;
|
|
|
|
|
|
static const bool kUseFixedPsoSeed = true;
|
|
|
static bool isFiniteNumber(double value)
|
|
|
{
|
|
|
return value == value && value >= -DBL_MAX && value <= DBL_MAX;
|
|
|
}
|
|
|
static void msleep(int ms)
|
|
|
{
|
|
|
#ifdef Q_OS_WIN
|
|
|
Sleep(ms);
|
|
|
#else
|
|
|
Q_UNUSED(ms);
|
|
|
#endif
|
|
|
}
|
|
|
nmFitPSO::nmFitPSO(QObject* parent)
|
|
|
: QObject(parent), m_isRunning(false), m_shouldStop(false), m_currentIteration(0),
|
|
|
m_globalBestFitness(1e10), m_previousBestFitness(1e10), m_swarmSize(20), m_maxIterations(100),
|
|
|
m_targetError(0.001), m_inertiaWeight(0.4), m_cognitiveParam(2.0), m_socialParam(1.2), m_totalEvaluations(0),
|
|
|
m_successfulEvaluations(0), m_userInitialFitness(1e10), m_improvementThreshold(0.05),
|
|
|
m_hasValidUserSolution(false), m_consecutiveFailedIterations(0), m_maxConsecutiveFailures(3),
|
|
|
m_diversityThreshold(0.05), m_convergenceVarianceThreshold(1e-8), m_velocityConvergenceThreshold(0.01),
|
|
|
m_trueConvergenceWindow(15), m_localOptimumWindow(8), m_farTargetFactor(10.0),
|
|
|
m_psoRandomSeed(0), m_stopReason(7), m_acceleration(nullptr)
|
|
|
{
|
|
|
// 算法状态逐实例保存,外部通过 fit 显式提供输入。
|
|
|
}
|
|
|
|
|
|
nmFitPSO::~nmFitPSO() {}
|
|
|
|
|
|
void nmFitPSO::setTargetLogLogData(const QVector<QVector<double>>& targetData)
|
|
|
{
|
|
|
// 目标曲线由调用方提供,所有数据均为未取对数的原始数值。
|
|
|
// 依次为时间、压差(或拟压差)、导数三列。
|
|
|
m_targetLogLogData = targetData;
|
|
|
DEBUG_OUT(QString("Target LogLog data set: %1 arrays").arg(targetData.size()));
|
|
|
|
|
|
if(targetData.size() >= 3) {
|
|
|
DEBUG_OUT(QString("LogLog data points: X=%1, Y1=%2, Y2=%3")
|
|
|
.arg(targetData[0].size())
|
|
|
.arg(targetData[1].size())
|
|
|
.arg(targetData[2].size()));
|
|
|
}
|
|
|
}
|
|
|
|
|
|
bool nmFitPSO::isRunning() const
|
|
|
{
|
|
|
// 供调用方查询当前拟合运行状态。
|
|
|
return m_isRunning;
|
|
|
}
|
|
|
|
|
|
int nmFitPSO::getCurrentIteration() const
|
|
|
{
|
|
|
// 返回从 0 开始的当前迭代序号。
|
|
|
return m_currentIteration;
|
|
|
}
|
|
|
|
|
|
int nmFitPSO::getTotalEvaluations() const
|
|
|
{
|
|
|
// 返回本轮评价尝试次数,可能包含失败或取消的评价。
|
|
|
return m_totalEvaluations;
|
|
|
}
|
|
|
|
|
|
QVector<double> nmFitPSO::getBestSolution() const
|
|
|
{
|
|
|
// 返回紧凑的“启用参数向量”,顺序与 m_enabledParamIndices 一致。
|
|
|
return m_globalBestPosition;
|
|
|
}
|
|
|
|
|
|
double nmFitPSO::getBestFitness() const
|
|
|
{
|
|
|
// 当前全局最优真实误差。越小越好,1e10 附近通常表示尚无有效解。
|
|
|
return m_globalBestFitness;
|
|
|
}
|
|
|
|
|
|
QString nmFitPSO::getLastError() const
|
|
|
{
|
|
|
// 返回最近一次输入或计算错误说明。
|
|
|
return m_lastError;
|
|
|
}
|
|
|
|
|
|
void nmFitPSO::resetOptimizer()
|
|
|
{
|
|
|
// 清空一次运行产生的状态,但不销毁对象。
|
|
|
// 配置字段在 runOptimization() 中由本轮请求重新加载。
|
|
|
|
|
|
m_swarm.clear();
|
|
|
m_globalBestPosition.clear();
|
|
|
m_globalBestFitness = 1e10;
|
|
|
m_previousBestFitness = 1e10;
|
|
|
m_lastEvaluatedLogLogData.clear();
|
|
|
m_globalBestLogLogData.clear();
|
|
|
m_userInitialLogLogData.clear();
|
|
|
m_currentIteration = 0;
|
|
|
m_totalEvaluations = 0;
|
|
|
m_successfulEvaluations = 0;
|
|
|
m_convergenceHistory.clear();
|
|
|
m_lastError.clear();
|
|
|
m_initialValues.clear();
|
|
|
m_userInitialSolution.clear();
|
|
|
m_userInitialFitness = 1e10;
|
|
|
m_hasValidUserSolution = false;
|
|
|
|
|
|
DEBUG_OUT("Optimizer reset");
|
|
|
}
|
|
|
|
|
|
void nmFitPSO::extractUserInitialValues()
|
|
|
{
|
|
|
// 按本轮启用参数的顺序提取初值,并将其限制在给定范围内。
|
|
|
m_initialValues.clear();
|
|
|
for(int i = 0; i < m_enabledParamIndices.size(); ++i) {
|
|
|
const nmFitParameterValue& p = m_modelParameters[m_enabledParamIndices[i]];
|
|
|
m_initialValues.append(qBound(p.lower, p.initial, p.upper));
|
|
|
}
|
|
|
}
|
|
|
|
|
|
void nmFitPSO::initializeSwarm()
|
|
|
{
|
|
|
// 初始化粒子群。
|
|
|
// 若用户已有初始模型有效,则一部分粒子围绕初始值做局部搜索;
|
|
|
// 另一部分粒子在全局上下界内随机分布,保留跳出局部区域的能力。
|
|
|
int dimensions = getEnabledParameterCount();
|
|
|
|
|
|
if(dimensions == 0)
|
|
|
return;
|
|
|
|
|
|
m_swarm.resize(m_swarmSize);
|
|
|
m_globalBestPosition.resize(dimensions);
|
|
|
|
|
|
bool hasValidInitials = !m_initialValues.isEmpty() && m_initialValues.size() >= dimensions;
|
|
|
|
|
|
// 引导搜索比例。guided 粒子围绕用户初始值,非 guided 粒子做全局随机搜索。
|
|
|
int guidedCount = hasValidInitials ? qMax(2, m_swarmSize / 2) : qMax(1, m_swarmSize / 3);
|
|
|
|
|
|
DEBUG_OUT(QString("Enhanced swarm initialization: %1 particles, %2 guided, %3 random")
|
|
|
.arg(m_swarmSize)
|
|
|
.arg(guidedCount)
|
|
|
.arg(m_swarmSize - guidedCount));
|
|
|
|
|
|
for(int i = 0; i < m_swarmSize; ++i) {
|
|
|
AutoFitParticle& particle = m_swarm[i];
|
|
|
particle.position.resize(dimensions);
|
|
|
particle.velocity.resize(dimensions);
|
|
|
particle.bestPosition.resize(dimensions);
|
|
|
particle.guideBestPosition.resize(dimensions);
|
|
|
particle.bestFitness = 1e10;
|
|
|
particle.guideBestObjective = 1e10;
|
|
|
particle.guideBestFromSurrogate = false;
|
|
|
particle.pbestRelativeImprovementThisIteration = 0.0;
|
|
|
particle.fitness = 1e10;
|
|
|
particle.evaluatedThisIteration = false;
|
|
|
particle.lastEvaluationSuccess = false;
|
|
|
particle.lastEvaluationElapsedMs = -1;
|
|
|
particle.surrogateObjective = 1e10;
|
|
|
particle.selectedForSolver = true;
|
|
|
particle.selectedByAudit = false;
|
|
|
particle.screeningDecision = "full_solver";
|
|
|
|
|
|
for(int j = 0; j < dimensions; ++j) {
|
|
|
int paramIndex = m_enabledParamIndices[j];
|
|
|
double range = m_parameterUpper[paramIndex] - m_parameterLower[paramIndex];
|
|
|
|
|
|
if(i == 0 && hasValidInitials) {
|
|
|
// 第一个粒子:完全使用用户初始值,确保初始模型本身参与粒子群。
|
|
|
particle.position[j] = m_initialValues[j];
|
|
|
|
|
|
} else if(i < guidedCount && hasValidInitials) {
|
|
|
// 引导粒子采用分层搜索半径:
|
|
|
// 近邻精细搜索 + 中等扰动 + 较大扰动,覆盖初始模型周围不同尺度。
|
|
|
double searchRadius;
|
|
|
|
|
|
if(i <= guidedCount / 3) {
|
|
|
searchRadius = range * 0.03; // 3%范围内精细搜索
|
|
|
} else if(i <= guidedCount * 2 / 3) {
|
|
|
searchRadius = range * 0.08; // 8%范围内搜索
|
|
|
} else {
|
|
|
searchRadius = range * 0.15; // 15%范围内搜索
|
|
|
}
|
|
|
|
|
|
double offset = (random01() - 0.5) * searchRadius;
|
|
|
particle.position[j] = m_initialValues[j] + offset;
|
|
|
|
|
|
} else {
|
|
|
// 少数粒子进行全局搜索,防止所有粒子都被初始模型附近的局部最优限制。
|
|
|
particle.position[j] = m_parameterLower[paramIndex] + random01() * range;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
// 边界检查
|
|
|
clampToLimits(particle.position);
|
|
|
|
|
|
// 速度初始化。引导粒子速度更小,避免刚开始就离开初始模型邻域;
|
|
|
// 全局粒子速度稍大,便于探索更宽的搜索空间。
|
|
|
for(int j = 0; j < dimensions; ++j) {
|
|
|
int paramIndex = m_enabledParamIndices[j];
|
|
|
double range = m_parameterUpper[paramIndex] - m_parameterLower[paramIndex];
|
|
|
|
|
|
double velocityFactor;
|
|
|
|
|
|
if(i < guidedCount) {
|
|
|
velocityFactor = VELOCITY_LIMIT_FACTOR * 0.15; // 更小的速度
|
|
|
} else {
|
|
|
velocityFactor = VELOCITY_LIMIT_FACTOR * 0.8; // 适中速度
|
|
|
}
|
|
|
|
|
|
particle.velocity[j] = (random01() - 0.5) * range * velocityFactor;
|
|
|
}
|
|
|
|
|
|
particle.bestPosition = particle.position;
|
|
|
particle.guideBestPosition = particle.position;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
void nmFitPSO::updateParticle(int particleIndex)
|
|
|
{
|
|
|
if(particleIndex < 0 || particleIndex >= m_swarm.size())
|
|
|
return;
|
|
|
|
|
|
AutoFitParticle& particle = m_swarm[particleIndex];
|
|
|
|
|
|
// 单粒子真实评价入口。
|
|
|
// 这里调用 evaluateFitness(),通过回调获取真实曲线并计算误差。
|
|
|
// 被代理模型筛掉的粒子不会进入这个函数。
|
|
|
particle.evaluatedThisIteration = false;
|
|
|
particle.lastEvaluationSuccess = false;
|
|
|
particle.lastEvaluationElapsedMs = -1;
|
|
|
particle.pbestRelativeImprovementThisIteration = 0.0;
|
|
|
particle.selectedForSolver = true;
|
|
|
|
|
|
if(particle.screeningDecision.isEmpty()) {
|
|
|
particle.screeningDecision = "full_solver";
|
|
|
}
|
|
|
|
|
|
bool reuseInitialSolution = m_currentIteration == 0 && particleIndex == 0 && m_hasValidUserSolution &&
|
|
|
m_userInitialFitness < 1e9 && particle.position.size() == m_userInitialSolution.size();
|
|
|
|
|
|
for(int i = 0; reuseInitialSolution && i < particle.position.size(); ++i) {
|
|
|
double tolerance = qMax(1.0e-12, qAbs(m_userInitialSolution[i]) * 1.0e-12);
|
|
|
reuseInitialSolution = qAbs(particle.position[i] - m_userInitialSolution[i]) <= tolerance;
|
|
|
}
|
|
|
|
|
|
if(reuseInitialSolution) {
|
|
|
// 初始解在进入粒子群前已经真实求解过。第一代第0号粒子位置完全相同,
|
|
|
// 直接复用真实误差和曲线,避免一次重复 DLL 调用且不改变 PSO 数学状态。
|
|
|
particle.fitness = m_userInitialFitness;
|
|
|
particle.currentLogLogData = m_userInitialLogLogData;
|
|
|
particle.lastEvaluationElapsedMs = 0;
|
|
|
particle.evaluatedThisIteration = true;
|
|
|
particle.lastEvaluationSuccess = true;
|
|
|
particle.screeningDecision = "initial_solution_cache";
|
|
|
} else {
|
|
|
QTime evalTimer;
|
|
|
evalTimer.start();
|
|
|
particle.fitness = evaluateFitness(particle.position);
|
|
|
particle.currentLogLogData = m_lastEvaluatedLogLogData;
|
|
|
particle.lastEvaluationElapsedMs = evalTimer.elapsed();
|
|
|
particle.evaluatedThisIteration = true;
|
|
|
particle.lastEvaluationSuccess = (particle.fitness < 1e9);
|
|
|
m_totalEvaluations++;
|
|
|
|
|
|
if(particle.fitness < 1e9) {
|
|
|
m_successfulEvaluations++;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
// 更新个体最优 pbest。这里使用的是真实求解器误差 particle.fitness,
|
|
|
// 不是代理模型给出的 surrogateObjective。
|
|
|
double previousBestFitness = particle.bestFitness;
|
|
|
|
|
|
if(particle.fitness < previousBestFitness) {
|
|
|
particle.pbestRelativeImprovementThisIteration =
|
|
|
previousBestFitness >= 1e9
|
|
|
? 1.0
|
|
|
: (previousBestFitness - particle.fitness) / qMax(1e-10, qAbs(previousBestFitness));
|
|
|
|
|
|
// 如果当前位置尚未成为新的真实全局最优,而上一代存在尚未真实验证、且代理
|
|
|
// 仍判断更优的 guide,就保留它继续引导速度;真实 pbest 仍照常更新。
|
|
|
bool preserveSurrogateGuide = false;
|
|
|
|
|
|
bool currentBeatsGlobalBest = particle.fitness < m_globalBestFitness;
|
|
|
|
|
|
if(m_acceleration) {
|
|
|
preserveSurrogateGuide = m_acceleration->preserveGuide(particle, currentBeatsGlobalBest);
|
|
|
}
|
|
|
|
|
|
particle.bestFitness = particle.fitness;
|
|
|
particle.bestPosition = particle.position;
|
|
|
particle.bestLogLogData = particle.currentLogLogData;
|
|
|
|
|
|
if(!preserveSurrogateGuide) {
|
|
|
particle.guideBestPosition = particle.position;
|
|
|
particle.guideBestObjective =
|
|
|
isFiniteNumber(particle.surrogateObjective) ? particle.surrogateObjective : particle.fitness;
|
|
|
particle.guideBestFromSurrogate = false;
|
|
|
}
|
|
|
|
|
|
DEBUG_OUT(QString("Particle %1 improved: error = %2").arg(particleIndex).arg(particle.fitness, 0, 'e', 4));
|
|
|
}
|
|
|
}
|
|
|
|
|
|
void nmFitPSO::updateGlobalBest()
|
|
|
{
|
|
|
// 保存上一轮的全局最优,用于后续自适应参数调整等
|
|
|
m_previousBestFitness = m_globalBestFitness;
|
|
|
bool globalBestUpdated = false;
|
|
|
|
|
|
// 遍历所有粒子,寻找比当前 global best 更好的个体最优。
|
|
|
// 注意:particle.bestFitness 只有在真实求解器评价成功后才会更新。
|
|
|
for(int i = 0; i < m_swarm.size(); ++i) {
|
|
|
const AutoFitParticle& particle = m_swarm[i];
|
|
|
|
|
|
// 只要个体最优比当前全局最优小,就认为是更好的解
|
|
|
if(particle.bestFitness < m_globalBestFitness) {
|
|
|
|
|
|
double improvement = m_globalBestFitness - particle.bestFitness;
|
|
|
double relativeImprovement = improvement / qMax(1e-10, qAbs(m_globalBestFitness));
|
|
|
|
|
|
// 区分显著改进和微小改进,但无论如何都会更新全局最优
|
|
|
if(relativeImprovement > m_improvementThreshold) {
|
|
|
DEBUG_OUT(QString(fitTr("Global best updated with %1% improvement: %2"))
|
|
|
.arg(relativeImprovement * 100.0, 0, 'f', 3)
|
|
|
.arg(particle.bestFitness, 0, 'e', 4));
|
|
|
} else {
|
|
|
DEBUG_OUT(QString(fitTr("Global best updated (minor improvement %1% < %2%) to %3"))
|
|
|
.arg(relativeImprovement * 100.0, 0, 'f', 3)
|
|
|
.arg(m_improvementThreshold * 100.0, 0, 'f', 2)
|
|
|
.arg(particle.bestFitness, 0, 'e', 4));
|
|
|
}
|
|
|
|
|
|
// 无论相对改进是否超过阈值,都要更新全局最优
|
|
|
m_globalBestFitness = particle.bestFitness;
|
|
|
m_globalBestPosition = particle.bestPosition;
|
|
|
m_globalBestLogLogData = particle.bestLogLogData;
|
|
|
globalBestUpdated = true;
|
|
|
emit bestCurveUpdated(m_targetLogLogData, m_globalBestLogLogData, m_currentIteration + 1,
|
|
|
m_globalBestFitness);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
// 只有在本轮没有找到任何更好的解时才考虑恢复用户初始解
|
|
|
if(!globalBestUpdated && m_hasValidUserSolution && m_userInitialFitness < m_globalBestFitness) {
|
|
|
|
|
|
double improvement = m_globalBestFitness - m_userInitialFitness;
|
|
|
double relativeImprovement = improvement / qMax(1e-10, qAbs(m_globalBestFitness));
|
|
|
|
|
|
DEBUG_OUT("Elite protection: Restoring user initial solution as global best");
|
|
|
DEBUG_OUT(
|
|
|
QString("Elite solution is better than current best by %1%").arg(relativeImprovement * 100.0, 0, 'f', 3));
|
|
|
|
|
|
m_globalBestFitness = m_userInitialFitness;
|
|
|
m_globalBestPosition = m_userInitialSolution;
|
|
|
m_globalBestLogLogData = m_userInitialLogLogData;
|
|
|
emit bestCurveUpdated(m_targetLogLogData, m_globalBestLogLogData, m_currentIteration + 1, m_globalBestFitness);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
void nmFitPSO::updateVelocityAndPosition()
|
|
|
{
|
|
|
bool useSurrogateGuidePbest = isSurrogateScreeningEnabled();
|
|
|
|
|
|
for(int i = 0; i < m_swarm.size(); ++i) {
|
|
|
AutoFitParticle& particle = m_swarm[i];
|
|
|
const QVector<double>& cognitiveBest =
|
|
|
useSurrogateGuidePbest && particle.guideBestPosition.size() == particle.position.size()
|
|
|
? particle.guideBestPosition
|
|
|
: particle.bestPosition;
|
|
|
|
|
|
for(int j = 0; j < particle.position.size(); ++j) {
|
|
|
// PSO速度更新公式:
|
|
|
// inertia 保留上一轮搜索方向;
|
|
|
// cognitive 项让粒子靠近自己的历史最优;
|
|
|
// social 项让粒子靠近群体全局最优。
|
|
|
double r1 = random01();
|
|
|
double r2 = random01();
|
|
|
|
|
|
particle.velocity[j] = m_inertiaWeight * particle.velocity[j] +
|
|
|
m_cognitiveParam * r1 * (cognitiveBest[j] - particle.position[j]) +
|
|
|
m_socialParam * r2 * (m_globalBestPosition[j] - particle.position[j]);
|
|
|
|
|
|
// 速度限制。不同参数量纲差异很大,所以按该参数搜索区间的一定比例限速。
|
|
|
int paramIndex = m_enabledParamIndices[j];
|
|
|
double range = m_parameterUpper[paramIndex] - m_parameterLower[paramIndex];
|
|
|
double maxVel = range * VELOCITY_LIMIT_FACTOR;
|
|
|
particle.velocity[j] = qMax(-maxVel, qMin(maxVel, particle.velocity[j]));
|
|
|
|
|
|
// 更新位置
|
|
|
particle.position[j] += particle.velocity[j];
|
|
|
}
|
|
|
|
|
|
// 边界约束。PSO 位置更新后如果越界,直接夹回用户设置的上下界。
|
|
|
clampToLimits(particle.position);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
QVector<QPointF> nmFitPSO::interpolateData(const QVector<QPointF>& source, const QVector<double>& targetX) const
|
|
|
{
|
|
|
// 将一条曲线插值到指定 targetX 网格。
|
|
|
// 双对数误差计算前会分别把目标曲线和模拟曲线插到同一个 commonX 上,
|
|
|
// 这样每个时间点才能逐点比较。
|
|
|
QVector<QPointF> result;
|
|
|
|
|
|
if(source.isEmpty() || targetX.isEmpty()) {
|
|
|
DEBUG_OUT("Warning: Empty data in interpolation");
|
|
|
return result;
|
|
|
}
|
|
|
|
|
|
// 数据清理和验证合并:跳过 NaN/Inf 和极端大值,尽量保留可用点继续计算。
|
|
|
// 这里不立即把整个粒子判失败,是为了提高求解器偶发异常输出下的鲁棒性。
|
|
|
QVector<QPointF> validSource;
|
|
|
const double MAX_REASONABLE_VALUE = 1e12;
|
|
|
|
|
|
for(int i = 0; i < source.size(); ++i) {
|
|
|
const QPointF& point = source[i];
|
|
|
|
|
|
// 检查数值有效性
|
|
|
if(!isFiniteNumber(point.x()) || !isFiniteNumber(point.y())) {
|
|
|
DEBUG_OUT(
|
|
|
QString("Skipping invalid data point at index %1: X=%2, Y=%3").arg(i).arg(point.x()).arg(point.y()));
|
|
|
continue;
|
|
|
}
|
|
|
|
|
|
// 检查极大值 - 跳过而不是失败
|
|
|
if(qAbs(point.y()) > MAX_REASONABLE_VALUE) {
|
|
|
DEBUG_OUT(QString("Skipping extremely large Y value at index %1: %2").arg(i).arg(point.y()));
|
|
|
continue;
|
|
|
}
|
|
|
|
|
|
// 只保留有效的数据点
|
|
|
validSource.append(point);
|
|
|
}
|
|
|
|
|
|
// 检查清理后的数据是否足够
|
|
|
if(validSource.size() < 3) {
|
|
|
DEBUG_OUT(QString("Insufficient valid data points after cleaning: %1").arg(validSource.size()));
|
|
|
return result; // 返回空结果,但不算失败
|
|
|
}
|
|
|
|
|
|
DEBUG_OUT(QString("Data cleaning: %1 -> %2 valid points").arg(source.size()).arg(validSource.size()));
|
|
|
|
|
|
// 对清理后的数据按 X 排序。后续线性插值要求横坐标单调。
|
|
|
QVector<QPointF> sortedSource = validSource;
|
|
|
|
|
|
for(int i = 0; i < sortedSource.size() - 1; ++i) {
|
|
|
for(int j = 0; j < sortedSource.size() - 1 - i; ++j) {
|
|
|
if(sortedSource[j].x() > sortedSource[j + 1].x()) {
|
|
|
QPointF temp = sortedSource[j];
|
|
|
sortedSource[j] = sortedSource[j + 1];
|
|
|
sortedSource[j + 1] = temp;
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
|
|
|
double sourceMinX = sortedSource.first().x();
|
|
|
double sourceMaxX = sortedSource.last().x();
|
|
|
|
|
|
double targetMinX = targetX[0];
|
|
|
double targetMaxX = targetX[0];
|
|
|
|
|
|
for(int i = 1; i < targetX.size(); ++i) {
|
|
|
if(targetX[i] < targetMinX)
|
|
|
targetMinX = targetX[i];
|
|
|
|
|
|
if(targetX[i] > targetMaxX)
|
|
|
targetMaxX = targetX[i];
|
|
|
}
|
|
|
|
|
|
DEBUG_OUT(QString("Source X range: [%1, %2], Target X range: [%3, %4]")
|
|
|
.arg(sourceMinX)
|
|
|
.arg(sourceMaxX)
|
|
|
.arg(targetMinX)
|
|
|
.arg(targetMaxX));
|
|
|
|
|
|
// 插值算法:
|
|
|
// - 在源数据范围内用线性内插;
|
|
|
// - 目标 X 落在源范围外时做有限斜率外推;
|
|
|
// - 找不到区间时使用最近点兜底。
|
|
|
for(int i = 0; i < targetX.size(); ++i) {
|
|
|
double x = targetX[i];
|
|
|
|
|
|
if(!isFiniteNumber(x))
|
|
|
continue;
|
|
|
|
|
|
double y = 0.0;
|
|
|
|
|
|
// 插值逻辑
|
|
|
if(x <= sourceMinX) {
|
|
|
if(sortedSource.size() >= 2) {
|
|
|
double dx = sortedSource[1].x() - sortedSource[0].x();
|
|
|
|
|
|
if(qAbs(dx) > 1e-10) {
|
|
|
double slope = (sortedSource[1].y() - sortedSource[0].y()) / dx;
|
|
|
slope = qMax(-1e6, qMin(1e6, slope));
|
|
|
y = sortedSource[0].y() + slope * (x - sortedSource[0].x());
|
|
|
} else {
|
|
|
y = sortedSource[0].y();
|
|
|
}
|
|
|
} else {
|
|
|
y = sortedSource[0].y();
|
|
|
}
|
|
|
} else if(x >= sourceMaxX) {
|
|
|
if(sortedSource.size() >= 2) {
|
|
|
int lastIdx = sortedSource.size() - 1;
|
|
|
double dx = sortedSource[lastIdx].x() - sortedSource[lastIdx - 1].x();
|
|
|
|
|
|
if(qAbs(dx) > 1e-10) {
|
|
|
double slope = (sortedSource[lastIdx].y() - sortedSource[lastIdx - 1].y()) / dx;
|
|
|
slope = qMax(-1e6, qMin(1e6, slope));
|
|
|
y = sortedSource[lastIdx].y() + slope * (x - sortedSource[lastIdx].x());
|
|
|
} else {
|
|
|
y = sortedSource[lastIdx].y();
|
|
|
}
|
|
|
} else {
|
|
|
y = sortedSource.last().y();
|
|
|
}
|
|
|
} else {
|
|
|
// 内插
|
|
|
bool found = false;
|
|
|
|
|
|
for(int j = 0; j < sortedSource.size() - 1; ++j) {
|
|
|
if(x >= sortedSource[j].x() && x <= sortedSource[j + 1].x()) {
|
|
|
double dx = sortedSource[j + 1].x() - sortedSource[j].x();
|
|
|
|
|
|
if(qAbs(dx) > 1e-10) {
|
|
|
double ratio = (x - sortedSource[j].x()) / dx;
|
|
|
y = sortedSource[j].y() + ratio * (sortedSource[j + 1].y() - sortedSource[j].y());
|
|
|
} else {
|
|
|
y = sortedSource[j].y();
|
|
|
}
|
|
|
|
|
|
found = true;
|
|
|
break;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
if(!found) {
|
|
|
// 使用最近点
|
|
|
double minDist = 1e10;
|
|
|
|
|
|
for(int k = 0; k < sortedSource.size(); ++k) {
|
|
|
double dist = qAbs(sortedSource[k].x() - x);
|
|
|
|
|
|
if(dist < minDist) {
|
|
|
minDist = dist;
|
|
|
y = sortedSource[k].y();
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
|
|
|
// 最终数值检查
|
|
|
if(!isFiniteNumber(y)) {
|
|
|
y = sortedSource.size() > 0 ? sortedSource[0].y() : 1.0;
|
|
|
}
|
|
|
|
|
|
y = qMax(-1e12, qMin(1e12, y));
|
|
|
|
|
|
result.append(QPointF(x, y));
|
|
|
}
|
|
|
|
|
|
if(result.isEmpty()) {
|
|
|
DEBUG_OUT("LogLog interpolation failed");
|
|
|
return result;
|
|
|
}
|
|
|
|
|
|
DEBUG_OUT(QString("Interpolation completed: %1 -> %2 points").arg(validSource.size()).arg(result.size()));
|
|
|
|
|
|
return result;
|
|
|
}
|
|
|
|
|
|
void nmFitPSO::adaptiveParameterUpdate(int iteration)
|
|
|
{
|
|
|
// 自适应调整 PSO 系数。
|
|
|
// 随迭代推进降低惯性权重,让搜索从全局探索逐步转向局部收敛;
|
|
|
// 当近期改进很小时,提高 cognitive、降低 social,让粒子更多参考自身历史最优。
|
|
|
double progress = static_cast<double>(iteration) / m_maxIterations;
|
|
|
// 更快降低惯性权重,增强局部搜索
|
|
|
m_inertiaWeight = 0.4 - 0.25 * progress;
|
|
|
|
|
|
if(iteration > 0) {
|
|
|
double improvement = m_previousBestFitness - m_globalBestFitness;
|
|
|
double relativeImprovement = improvement / qMax(1e-10, qAbs(m_previousBestFitness));
|
|
|
|
|
|
if(relativeImprovement < 1e-5) {
|
|
|
// 改进很小时,增强局部搜索
|
|
|
m_cognitiveParam = qMin(2.5, m_cognitiveParam * 1.05);
|
|
|
m_socialParam = qMax(0.8, m_socialParam * 0.95);
|
|
|
} else {
|
|
|
// 有明显改进时,保持平衡
|
|
|
m_cognitiveParam = qMax(1.5, qMin(2.2, m_cognitiveParam));
|
|
|
m_socialParam = qMax(1.0, qMin(1.5, m_socialParam));
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
|
|
|
void nmFitPSO::validateAndProtectFinalResult()
|
|
|
{
|
|
|
// 最终精英保护。
|
|
|
// PSO 是随机启发式算法,某些工况下可能没有找到比用户初始模型更好的结果。
|
|
|
// 这里用初始解误差与最终全局最优误差做比较,如果改进不足,就恢复初始解,
|
|
|
// 避免“自动拟合”把已有模型调坏。
|
|
|
if(!m_hasValidUserSolution) {
|
|
|
emit logMessageGenerated(fitTr("No initial solution for elite protection"));
|
|
|
return;
|
|
|
}
|
|
|
|
|
|
emit logMessageGenerated(fitTr("=== Final Result Validation (Elite Protection) ==="));
|
|
|
|
|
|
// 使用已有的评估结果
|
|
|
double finalFitness = m_globalBestFitness;
|
|
|
double initialFitness = m_userInitialFitness;
|
|
|
|
|
|
emit logMessageGenerated(
|
|
|
fitTr("Comparing results: Initial=%1, Final=%2").arg(initialFitness, 0, 'e', 4).arg(finalFitness, 0, 'e', 4));
|
|
|
|
|
|
// 计算改进程度
|
|
|
double improvement = initialFitness - finalFitness;
|
|
|
double relativeImprovement = improvement / qMax(1e-10, qAbs(initialFitness));
|
|
|
|
|
|
emit logMessageGenerated(
|
|
|
fitTr("Improvement: %1 (%2%)").arg(improvement, 0, 'e', 4).arg(relativeImprovement * 100, 0, 'f', 2));
|
|
|
|
|
|
if(relativeImprovement < m_improvementThreshold) {
|
|
|
emit logMessageGenerated(fitTr("Elite protection triggered: insufficient improvement"));
|
|
|
emit logMessageGenerated(fitTr("Threshold: %1%, Actual: %2%")
|
|
|
.arg(m_improvementThreshold * 100, 0, 'f', 2)
|
|
|
.arg(relativeImprovement * 100, 0, 'f', 4));
|
|
|
emit logMessageGenerated(fitTr("Restoring initial solution as final result"));
|
|
|
|
|
|
m_globalBestFitness = initialFitness;
|
|
|
m_globalBestPosition = m_userInitialSolution;
|
|
|
m_globalBestLogLogData = m_userInitialLogLogData;
|
|
|
emit bestCurveUpdated(m_targetLogLogData, m_globalBestLogLogData, m_currentIteration + 1, m_globalBestFitness);
|
|
|
|
|
|
emit logMessageGenerated(fitTr("Initial solution restored successfully"));
|
|
|
} else {
|
|
|
emit logMessageGenerated(fitTr("Final result validated - significant improvement achieved"));
|
|
|
}
|
|
|
}
|
|
|
|
|
|
double nmFitPSO::random01() const
|
|
|
{
|
|
|
// 使用 Qt 的 qrand/qsrand;runOptimization 根据请求中的种子初始化随机序列。
|
|
|
return static_cast<double>(qrand()) / RAND_MAX;
|
|
|
}
|
|
|
|
|
|
void nmFitPSO::clampToLimits(QVector<double>& parameters) const
|
|
|
{
|
|
|
// 将粒子位置夹回用户给定上下界。parameters 是紧凑的启用参数向量,
|
|
|
// 需要通过 m_enabledParamIndices 找到它在完整参数体系中的上下界。
|
|
|
for(int i = 0; i < parameters.size() && i < m_enabledParamIndices.size(); ++i) {
|
|
|
int paramIndex = m_enabledParamIndices[i];
|
|
|
|
|
|
if(paramIndex >= 0 && paramIndex < m_parameterLower.size()) {
|
|
|
parameters[i] = qMax(m_parameterLower[paramIndex], qMin(m_parameterUpper[paramIndex], parameters[i]));
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
|
|
|
int nmFitPSO::getEnabledParameterCount() const
|
|
|
{
|
|
|
// 返回粒子维度,即用户勾选参与拟合的参数数量。
|
|
|
int count = 0;
|
|
|
|
|
|
for(int i = 0; i < m_parameterSelected.size(); ++i) {
|
|
|
if(m_parameterSelected[i])
|
|
|
count++;
|
|
|
}
|
|
|
|
|
|
return count;
|
|
|
}
|
|
|
|
|
|
bool nmFitPSO::validateParameters(const QVector<double>& parameters) const
|
|
|
{
|
|
|
// 检查候选参数的维度、有限性及请求中的上下界。
|
|
|
if(parameters.size() != getEnabledParameterCount()) {
|
|
|
return false;
|
|
|
}
|
|
|
|
|
|
for(int i = 0; i < parameters.size(); ++i) {
|
|
|
if(!isFiniteNumber(parameters[i])) {
|
|
|
return false;
|
|
|
}
|
|
|
|
|
|
if(i < m_enabledParamIndices.size()) {
|
|
|
int paramIndex = m_enabledParamIndices[i];
|
|
|
|
|
|
if(paramIndex >= 0 && paramIndex < m_parameterLower.size()) {
|
|
|
if(parameters[i] < m_parameterLower[paramIndex] || parameters[i] > m_parameterUpper[paramIndex]) {
|
|
|
return false;
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
|
|
|
return true;
|
|
|
}
|
|
|
|
|
|
bool nmFitPSO::validateLogLogData(const QVector<QVector<double>>& logLogData) const
|
|
|
{
|
|
|
// 校验双对数曲线结构。约定:
|
|
|
// logLogData[0]=time,logLogData[1]=pressure,logLogData[2]=pressure derivative。
|
|
|
// 三列必须长度一致,且至少有足够点数用于插值和误差计算。
|
|
|
if(logLogData.size() < 3) {
|
|
|
DEBUG_OUT("LogLog data has less than 3 arrays");
|
|
|
return false;
|
|
|
}
|
|
|
|
|
|
// 检查数组大小一致性
|
|
|
int size = logLogData[0].size();
|
|
|
|
|
|
if(size == 0) {
|
|
|
DEBUG_OUT("Empty LogLog data");
|
|
|
return false;
|
|
|
}
|
|
|
|
|
|
if(logLogData[1].size() != size || logLogData[2].size() != size) {
|
|
|
DEBUG_OUT(QString("LogLog data size mismatch: X=%1, Y1=%2, Y2=%3")
|
|
|
.arg(logLogData[0].size())
|
|
|
.arg(logLogData[1].size())
|
|
|
.arg(logLogData[2].size()));
|
|
|
return false;
|
|
|
}
|
|
|
|
|
|
// 检查最小数据点数
|
|
|
if(size < 5) {
|
|
|
DEBUG_OUT(QString("Too few LogLog data points: %1").arg(size));
|
|
|
return false;
|
|
|
}
|
|
|
|
|
|
// 数据有效性检查
|
|
|
for(int i = 0; i < size; ++i) {
|
|
|
if(!isFiniteNumber(logLogData[0][i]) || !isFiniteNumber(logLogData[1][i]) ||
|
|
|
!isFiniteNumber(logLogData[2][i])) {
|
|
|
DEBUG_OUT(QString("Invalid LogLog data at index %1").arg(i));
|
|
|
return false;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
return true;
|
|
|
}
|
|
|
|
|
|
bool nmFitPSO::validateSolverResult(const QVector<QVector<double>>& result) const
|
|
|
{
|
|
|
// 校验求解器压力结果。这里检查的是 pressure result,至少需要 time 和 pressure 两列。
|
|
|
// 计算曲线的三列结构由 validateLogLogData() 单独检查。
|
|
|
if(result.size() < 2) {
|
|
|
DEBUG_OUT("Solver result has less than 2 arrays");
|
|
|
return false;
|
|
|
}
|
|
|
|
|
|
if(result[0].size() != result[1].size()) {
|
|
|
DEBUG_OUT(QString("Size mismatch: X=%1, Y=%2").arg(result[0].size()).arg(result[1].size()));
|
|
|
return false;
|
|
|
}
|
|
|
|
|
|
if(result[0].size() == 0) {
|
|
|
DEBUG_OUT("Empty solver result");
|
|
|
return false;
|
|
|
}
|
|
|
|
|
|
// 检查最小数据点数
|
|
|
if(result[0].size() < 10) {
|
|
|
DEBUG_OUT(QString("Too few data points: %1").arg(result[0].size()));
|
|
|
return false;
|
|
|
}
|
|
|
|
|
|
// 数据有效性检查
|
|
|
for(int i = 0; i < result[0].size(); ++i) {
|
|
|
if(!isFiniteNumber(result[0][i]) || !isFiniteNumber(result[1][i])) {
|
|
|
DEBUG_OUT(QString("Invalid data at index %1: X=%2, Y=%3").arg(i).arg(result[0][i]).arg(result[1][i]));
|
|
|
return false;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
// 检查X值单调性
|
|
|
bool isMonotonic = true;
|
|
|
|
|
|
for(int i = 1; i < result[0].size(); ++i) {
|
|
|
if(result[0][i] <= result[0][i - 1]) {
|
|
|
isMonotonic = false;
|
|
|
break;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
if(!isMonotonic) {
|
|
|
DEBUG_OUT("X values are not monotonically increasing");
|
|
|
}
|
|
|
|
|
|
return true;
|
|
|
}
|
|
|
|
|
|
double nmFitPSO::calculateCurveError(const QVector<QPointF>& curve1, const QVector<QPointF>& curve2) const
|
|
|
{
|
|
|
// 两条已经对齐到同一 X 网格的曲线误差。
|
|
|
// 点误差保持无量纲,避免油水压力和气井拟压力因数值尺度不同而不可比。
|
|
|
if(curve1.size() != curve2.size() || curve1.isEmpty()) {
|
|
|
return 1e10;
|
|
|
}
|
|
|
|
|
|
// 预检查:确保没有无穷大值
|
|
|
for(int i = 0; i < curve1.size(); ++i) {
|
|
|
if(!isFiniteNumber(curve1[i].y()) || !isFiniteNumber(curve2[i].y())) {
|
|
|
DEBUG_OUT(QString("Infinite value detected at index %1: Y1=%2, Y2=%3")
|
|
|
.arg(i)
|
|
|
.arg(curve1[i].y())
|
|
|
.arg(curve2[i].y()));
|
|
|
return 1e10;
|
|
|
}
|
|
|
|
|
|
if(qAbs(curve1[i].y()) > 1e12 || qAbs(curve2[i].y()) > 1e12) {
|
|
|
DEBUG_OUT(QString("Extremely large value detected at index %1").arg(i));
|
|
|
return 1e10;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
double totalError = 0.0;
|
|
|
int validPoints = 0;
|
|
|
|
|
|
for(int i = 0; i < curve1.size(); ++i) {
|
|
|
double y1 = curve1[i].y();
|
|
|
double y2 = curve2[i].y();
|
|
|
|
|
|
// 跳过异常值
|
|
|
if(!isFiniteNumber(y1) || !isFiniteNumber(y2)) {
|
|
|
continue;
|
|
|
}
|
|
|
|
|
|
double pointError = calculatePointError(y1, y2);
|
|
|
|
|
|
if(isFiniteNumber(pointError) && pointError < 1e10) {
|
|
|
totalError += pointError * pointError;
|
|
|
validPoints++;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
if(validPoints > 0) {
|
|
|
double result = sqrt(totalError / validPoints);
|
|
|
|
|
|
// 最终检查
|
|
|
if(!isFiniteNumber(result)) {
|
|
|
DEBUG_OUT("Final error calculation produced infinite result");
|
|
|
return 1e10;
|
|
|
}
|
|
|
|
|
|
return qMin(1e9, result); // 限制最大误差值
|
|
|
} else {
|
|
|
DEBUG_OUT(QString("No valid points for error calculation: validPoints=%1").arg(validPoints));
|
|
|
return 1e10;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
double nmFitPSO::calculateLogLogCurveError(const QVector<QVector<double>>& target,
|
|
|
const QVector<QVector<double>>& result) const
|
|
|
{
|
|
|
// 双对数曲线误差计算。
|
|
|
//
|
|
|
// target 通常来自目标井历史曲线,result 来自当前粒子参数下的模拟曲线。
|
|
|
// 两条曲线的时间点往往不完全一致,所以这里先取两者时间范围的重叠区间,
|
|
|
// 再在公共时间网格上插值对齐,最后分别计算压力曲线和压力导数曲线误差。
|
|
|
//
|
|
|
// 返回值越小表示拟合越好;返回 1e10 表示曲线无效或无法比较。
|
|
|
// 验证数据
|
|
|
if(!validateLogLogData(target) || !validateLogLogData(result)) {
|
|
|
return 1e10;
|
|
|
}
|
|
|
|
|
|
try {
|
|
|
// 数据对齐:找到目标曲线与模拟曲线 time 轴的重叠区域。
|
|
|
// 不在重叠区域内的点不参与误差,避免外推导致误差失真。
|
|
|
double targetMinX = target[0][0];
|
|
|
double targetMaxX = target[0][0];
|
|
|
|
|
|
for(int i = 1; i < target[0].size(); ++i) {
|
|
|
if(target[0][i] < targetMinX)
|
|
|
targetMinX = target[0][i];
|
|
|
|
|
|
if(target[0][i] > targetMaxX)
|
|
|
targetMaxX = target[0][i];
|
|
|
}
|
|
|
|
|
|
double resultMinX = result[0][0];
|
|
|
double resultMaxX = result[0][0];
|
|
|
|
|
|
for(int i = 1; i < result[0].size(); ++i) {
|
|
|
if(result[0][i] < resultMinX)
|
|
|
resultMinX = result[0][i];
|
|
|
|
|
|
if(result[0][i] > resultMaxX)
|
|
|
resultMaxX = result[0][i];
|
|
|
}
|
|
|
|
|
|
double overlapMinX = qMax(targetMinX, resultMinX);
|
|
|
double overlapMaxX = qMin(targetMaxX, resultMaxX);
|
|
|
|
|
|
if(overlapMinX >= overlapMaxX) {
|
|
|
DEBUG_OUT("No overlap between target and result LogLog curves");
|
|
|
return 1e10;
|
|
|
}
|
|
|
|
|
|
// 生成公共 X 网格进行插值。使用对数均匀网格,是为了给早期时间段
|
|
|
// 更多分辨率;试井双对数曲线的早期形态通常对参数识别很敏感。
|
|
|
QVector<double> commonX;
|
|
|
int numPoints = 50;
|
|
|
|
|
|
if(overlapMinX > 0 && overlapMaxX > 0) {
|
|
|
// 对数空间均匀分布
|
|
|
double logMin = qLn(overlapMinX);
|
|
|
double logMax = qLn(overlapMaxX);
|
|
|
|
|
|
for(int i = 0; i < numPoints; ++i) {
|
|
|
double logX = logMin + i * (logMax - logMin) / (numPoints - 1);
|
|
|
double x = qExp(logX);
|
|
|
|
|
|
// 数值保护
|
|
|
if(!isFiniteNumber(x) || x <= 0) {
|
|
|
continue;
|
|
|
}
|
|
|
|
|
|
commonX.append(x);
|
|
|
}
|
|
|
|
|
|
DEBUG_OUT("Using log-uniform grid for better early-time coverage");
|
|
|
}
|
|
|
|
|
|
if(commonX.isEmpty()) {
|
|
|
DEBUG_OUT("Failed to generate common X grid");
|
|
|
return 1e10;
|
|
|
}
|
|
|
|
|
|
// 插值目标曲线。target[1] 是压力,target[2] 是压力导数。
|
|
|
QVector<QPointF> targetCurve1, targetCurve2;
|
|
|
|
|
|
for(int i = 0; i < target[0].size(); ++i) {
|
|
|
// 检查数据有效性
|
|
|
if(isFiniteNumber(target[0][i]) && isFiniteNumber(target[1][i]) && isFiniteNumber(target[2][i])) {
|
|
|
targetCurve1.append(QPointF(target[0][i], target[1][i]));
|
|
|
targetCurve2.append(QPointF(target[0][i], target[2][i]));
|
|
|
}
|
|
|
}
|
|
|
|
|
|
if(targetCurve1.isEmpty() || targetCurve2.isEmpty()) {
|
|
|
DEBUG_OUT("Target curves are empty after filtering");
|
|
|
return 1e10;
|
|
|
}
|
|
|
|
|
|
QVector<QPointF> alignedTarget1 = interpolateData(targetCurve1, commonX);
|
|
|
QVector<QPointF> alignedTarget2 = interpolateData(targetCurve2, commonX);
|
|
|
|
|
|
// 插值结果曲线。result 与 target 使用同一 commonX,保证逐点可比。
|
|
|
QVector<QPointF> resultCurve1, resultCurve2;
|
|
|
|
|
|
for(int i = 0; i < result[0].size(); ++i) {
|
|
|
// 检查数据有效性
|
|
|
if(isFiniteNumber(result[0][i]) && isFiniteNumber(result[1][i]) && isFiniteNumber(result[2][i])) {
|
|
|
resultCurve1.append(QPointF(result[0][i], result[1][i]));
|
|
|
resultCurve2.append(QPointF(result[0][i], result[2][i]));
|
|
|
}
|
|
|
}
|
|
|
|
|
|
if(resultCurve1.isEmpty() || resultCurve2.isEmpty()) {
|
|
|
DEBUG_OUT("Result curves are empty after filtering");
|
|
|
return 1e10;
|
|
|
}
|
|
|
|
|
|
QVector<QPointF> alignedResult1 = interpolateData(resultCurve1, commonX);
|
|
|
QVector<QPointF> alignedResult2 = interpolateData(resultCurve2, commonX);
|
|
|
|
|
|
// 检查插值结果
|
|
|
if(alignedTarget1.isEmpty() || alignedTarget2.isEmpty() || alignedResult1.isEmpty() ||
|
|
|
alignedResult2.isEmpty()) {
|
|
|
DEBUG_OUT("LogLog interpolation failed");
|
|
|
return 1e10;
|
|
|
}
|
|
|
|
|
|
if(alignedTarget1.size() != alignedResult1.size() || alignedTarget2.size() != alignedResult2.size()) {
|
|
|
DEBUG_OUT("LogLog interpolation size mismatch");
|
|
|
return 1e10;
|
|
|
}
|
|
|
|
|
|
// 分别计算压差和导数曲线的误差,两者各占 50%。
|
|
|
double error1 = calculateCurveError(alignedTarget1, alignedResult1);
|
|
|
double error2 = calculateCurveError(alignedTarget2, alignedResult2);
|
|
|
|
|
|
// 检查个别误差是否有效
|
|
|
if(!isFiniteNumber(error1) || error1 > 1e9) {
|
|
|
DEBUG_OUT(QString("Curve1 error is invalid: %1").arg(error1));
|
|
|
error1 = 1e10;
|
|
|
}
|
|
|
|
|
|
if(!isFiniteNumber(error2) || error2 > 1e9) {
|
|
|
DEBUG_OUT(QString("Curve2 error is invalid: %1").arg(error2));
|
|
|
error2 = 1e10;
|
|
|
}
|
|
|
|
|
|
// 组合误差 - 添加保护
|
|
|
double combinedError;
|
|
|
|
|
|
if(error1 > 1e9 && error2 > 1e9) {
|
|
|
combinedError = 1e10;
|
|
|
} else if(error1 > 1e9) {
|
|
|
combinedError = error2;
|
|
|
} else if(error2 > 1e9) {
|
|
|
combinedError = error1;
|
|
|
} else {
|
|
|
combinedError = 0.5 * error1 + 0.5 * error2;
|
|
|
}
|
|
|
|
|
|
DEBUG_OUT(QString("LogLog errors: Curve1=%1, Curve2=%2, Combined=%3")
|
|
|
.arg(error1, 0, 'e', 4)
|
|
|
.arg(error2, 0, 'e', 4)
|
|
|
.arg(combinedError, 0, 'e', 4));
|
|
|
|
|
|
return qMin(1e9, combinedError);
|
|
|
}
|
|
|
catch(const std::exception& e) {
|
|
|
DEBUG_OUT(QString("Exception in LogLog error calculation: %1").arg(e.what()));
|
|
|
return 1e10;
|
|
|
}
|
|
|
catch(...) {
|
|
|
DEBUG_OUT("Unknown exception in LogLog error calculation");
|
|
|
return 1e10;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
double nmFitPSO::calculatePointError(double target, double result) const
|
|
|
{
|
|
|
if(!isFiniteNumber(target) || !isFiniteNumber(result)) {
|
|
|
return 1e10;
|
|
|
}
|
|
|
|
|
|
// 对数空间误差:关注数量级差异,适合双对数曲线。
|
|
|
double logTarget = qLn(qMax(1e-10, qAbs(target)));
|
|
|
double logResult = qLn(qMax(1e-10, qAbs(result)));
|
|
|
double logError = qAbs(logTarget - logResult);
|
|
|
|
|
|
// 线性空间相对误差:补充约束实际幅值差异。
|
|
|
double yMax = qMax(qAbs(target), qAbs(result));
|
|
|
double relativeError = qAbs(target - result) / qMax(1e-10, yMax);
|
|
|
|
|
|
// 组合误差:对数误差占 70%,线性误差占 30%。
|
|
|
return 0.7 * logError + 0.3 * relativeError;
|
|
|
}
|
|
|
|
|
|
StopReasonPSO nmFitPSO::analyzeOptimizationStatus()
|
|
|
{
|
|
|
// 按优先级判断本轮是否停止。
|
|
|
// 目标达成和最大迭代是硬条件;真收敛/局部最优需要足够历史数据支撑。
|
|
|
// 返回停止原因,由 runOptimization 完成结果整理及结束通知。
|
|
|
|
|
|
// 1. 检查用户停止
|
|
|
if(m_shouldStop) {
|
|
|
return PSO_USER_STOPPED;
|
|
|
}
|
|
|
|
|
|
// 2. 检查连续失败
|
|
|
if(m_consecutiveFailedIterations >= m_maxConsecutiveFailures) {
|
|
|
return PSO_CONSECUTIVE_FAILURES;
|
|
|
}
|
|
|
|
|
|
// 3. 检查是否达到目标精度
|
|
|
if(m_globalBestFitness < m_targetError) {
|
|
|
return PSO_TARGET_ACHIEVED;
|
|
|
}
|
|
|
|
|
|
// 4. 检查是否达到最大迭代数
|
|
|
if(m_currentIteration >= m_maxIterations - 1) {
|
|
|
return PSO_MAX_ITERATIONS;
|
|
|
}
|
|
|
|
|
|
// 5. 需要足够的历史数据才能判断收敛
|
|
|
if(m_convergenceHistory.size() < m_localOptimumWindow) {
|
|
|
return PSO_CONTINUE_OPTIMIZATION;
|
|
|
}
|
|
|
|
|
|
// 6. 检查真正的收敛
|
|
|
if(m_convergenceHistory.size() >= m_trueConvergenceWindow && checkTrueConvergence()) {
|
|
|
return PSO_TRUE_CONVERGENCE;
|
|
|
}
|
|
|
|
|
|
// 7. 检查局部最优陷阱
|
|
|
if(checkLocalOptimumTrap()) {
|
|
|
return PSO_LOCAL_OPTIMUM;
|
|
|
}
|
|
|
|
|
|
return PSO_CONTINUE_OPTIMIZATION;
|
|
|
}
|
|
|
|
|
|
bool nmFitPSO::checkTrueConvergence() const
|
|
|
{
|
|
|
// 真收敛判断:不是只看“最近没有改进”,而是同时看误差稳定性、粒子群多样性、
|
|
|
// 平均速度、长期改进和粒子停滞率。
|
|
|
// 这样可以减少把局部卡住误判成正常收敛的概率。
|
|
|
if(m_convergenceHistory.size() < m_trueConvergenceWindow) {
|
|
|
return false;
|
|
|
}
|
|
|
|
|
|
// 1. 检查适应度稳定性 - 长期小幅波动
|
|
|
double recentVariance = calculateFitnessVariance(10);
|
|
|
double recentMean = 0.0;
|
|
|
int windowSize = qMin(10, m_convergenceHistory.size());
|
|
|
|
|
|
// 计算最近窗口的均值
|
|
|
for(int i = m_convergenceHistory.size() - windowSize; i < m_convergenceHistory.size(); ++i) {
|
|
|
recentMean += m_convergenceHistory[i];
|
|
|
}
|
|
|
|
|
|
recentMean /= windowSize;
|
|
|
|
|
|
double relativeVariance = recentVariance / qMax(1e-10, recentMean * recentMean);
|
|
|
bool stableError = (relativeVariance < m_convergenceVarianceThreshold);
|
|
|
|
|
|
// 2. 检查粒子群多样性 - 应该收敛到同一区域
|
|
|
double currentDiversity = calculateSwarmDiversity();
|
|
|
bool lowDiversity = (currentDiversity < m_diversityThreshold);
|
|
|
|
|
|
// 3. 检查速度收敛 - 粒子应该几乎停止移动
|
|
|
double avgVelocity = calculateAverageVelocity();
|
|
|
bool velocityConverged = (avgVelocity < m_velocityConvergenceThreshold);
|
|
|
|
|
|
// 4. 检查长期改进趋势
|
|
|
double longTermImprovement = calculateLongTermImprovement(m_trueConvergenceWindow);
|
|
|
bool minimalLongTermImprovement = (longTermImprovement < 1e-4); // 0.01%
|
|
|
|
|
|
// 5. 检查粒子停滞情况
|
|
|
double stagnationRate = calculateParticleStagnationRate();
|
|
|
bool mostParticlesConverged = (stagnationRate > 0.8); // 80%以上粒子收敛
|
|
|
|
|
|
// 真收敛的判断条件
|
|
|
bool isConverged =
|
|
|
stableError && lowDiversity && velocityConverged && minimalLongTermImprovement && mostParticlesConverged;
|
|
|
|
|
|
if(isConverged) {
|
|
|
DEBUG_OUT("=== TRUE CONVERGENCE ANALYSIS ===");
|
|
|
DEBUG_OUT(QString("stableError=%1 (relativeVariance=%2)").arg(stableError).arg(relativeVariance, 0, 'e', 6));
|
|
|
DEBUG_OUT(QString("lowDiversity=%1 (diversity=%2, threshold=%3)")
|
|
|
.arg(lowDiversity)
|
|
|
.arg(currentDiversity, 0, 'f', 6)
|
|
|
.arg(m_diversityThreshold));
|
|
|
DEBUG_OUT(QString("velocityConverged=%1 (avgVel=%2)").arg(velocityConverged).arg(avgVelocity, 0, 'f', 6));
|
|
|
DEBUG_OUT(QString("longTermImprovement=%1%, stagnationRate=%2%")
|
|
|
.arg(longTermImprovement * 100, 0, 'f', 4)
|
|
|
.arg(stagnationRate * 100, 0, 'f', 1));
|
|
|
}
|
|
|
|
|
|
return isConverged;
|
|
|
}
|
|
|
|
|
|
bool nmFitPSO::checkLocalOptimumTrap() const
|
|
|
{
|
|
|
// 局部最优判断:当误差离目标还远,但短期几乎不改进,
|
|
|
// 且粒子群过度聚集/异常分散或大部分粒子停滞时,认为可能卡住。
|
|
|
if(m_convergenceHistory.size() < m_localOptimumWindow) {
|
|
|
return false;
|
|
|
}
|
|
|
|
|
|
// 1. 检查解质量 - 如果距离目标还很远,停滞就可能是局部最优
|
|
|
bool farFromTarget = (m_globalBestFitness > m_targetError * m_farTargetFactor);
|
|
|
|
|
|
// 2. 检查短期改进 - 近期改进非常小
|
|
|
double shortTermImprovement = calculateLongTermImprovement(m_localOptimumWindow);
|
|
|
bool poorShortTermImprovement = (shortTermImprovement < 1e-5); // 0.001%
|
|
|
|
|
|
// 3. 检查粒子多样性 - 可能过早聚集或无效分散
|
|
|
double currentDiversity = calculateSwarmDiversity();
|
|
|
bool problematicDiversity =
|
|
|
(currentDiversity < m_diversityThreshold * 0.1) || (currentDiversity > m_diversityThreshold * 5.0);
|
|
|
|
|
|
// 4. 检查粒子停滞率
|
|
|
double stagnationRate = calculateParticleStagnationRate();
|
|
|
bool mostParticlesStagnant = (stagnationRate > 0.9); // 90%以上停滞但解质量差
|
|
|
|
|
|
// 5. 检查适应度方差 - 可能卡在平坦区域
|
|
|
double fitnessVariance = calculateFitnessVariance(m_localOptimumWindow);
|
|
|
bool flatFitnessLandscape = (fitnessVariance < m_convergenceVarianceThreshold * 0.1);
|
|
|
|
|
|
// 局部最优的判断条件
|
|
|
bool isLocalOptimum = farFromTarget && poorShortTermImprovement &&
|
|
|
(problematicDiversity || (mostParticlesStagnant && flatFitnessLandscape));
|
|
|
|
|
|
if(isLocalOptimum) {
|
|
|
DEBUG_OUT("=== LOCAL OPTIMUM ANALYSIS ===");
|
|
|
DEBUG_OUT(QString("farFromTarget=%1 (error=%2, target*factor=%3)")
|
|
|
.arg(farFromTarget)
|
|
|
.arg(m_globalBestFitness, 0, 'e', 4)
|
|
|
.arg(m_targetError * m_farTargetFactor, 0, 'e', 4));
|
|
|
DEBUG_OUT(QString("poorShortTermImprovement=%1 (improvement=%2%)")
|
|
|
.arg(poorShortTermImprovement)
|
|
|
.arg(shortTermImprovement * 100, 0, 'f', 4));
|
|
|
DEBUG_OUT(QString("problematicDiversity=%1 (diversity=%2)")
|
|
|
.arg(problematicDiversity)
|
|
|
.arg(currentDiversity, 0, 'f', 6));
|
|
|
DEBUG_OUT(QString("stagnationRate=%1%, errorVariance=%2")
|
|
|
.arg(stagnationRate * 100, 0, 'f', 1)
|
|
|
.arg(fitnessVariance, 0, 'e', 6));
|
|
|
}
|
|
|
|
|
|
return isLocalOptimum;
|
|
|
}
|
|
|
|
|
|
double nmFitPSO::calculateSwarmDiversity() const
|
|
|
{
|
|
|
// 粒子群多样性:逐维计算粒子位置标准差,再按该参数搜索范围归一化。
|
|
|
// 返回值越小,说明粒子越集中;越大,说明搜索仍然分散。
|
|
|
if(m_swarm.size() < 2)
|
|
|
return 0.0;
|
|
|
|
|
|
int dimensions = getEnabledParameterCount();
|
|
|
|
|
|
if(dimensions == 0)
|
|
|
return 0.0;
|
|
|
|
|
|
double totalDiversity = 0.0;
|
|
|
|
|
|
for(int dim = 0; dim < dimensions; ++dim) {
|
|
|
// 计算该维度上所有粒子的均值
|
|
|
double mean = 0.0;
|
|
|
|
|
|
for(int i = 0; i < m_swarm.size(); ++i) {
|
|
|
mean += m_swarm[i].position[dim];
|
|
|
}
|
|
|
|
|
|
mean /= m_swarm.size();
|
|
|
|
|
|
// 计算该维度上的方差
|
|
|
double variance = 0.0;
|
|
|
|
|
|
for(int i = 0; i < m_swarm.size(); ++i) {
|
|
|
double diff = m_swarm[i].position[dim] - mean;
|
|
|
variance += diff * diff;
|
|
|
}
|
|
|
|
|
|
variance /= m_swarm.size();
|
|
|
|
|
|
// 归一化到参数范围
|
|
|
int paramIndex = m_enabledParamIndices[dim];
|
|
|
double range = m_parameterUpper[paramIndex] - m_parameterLower[paramIndex];
|
|
|
double normalizedStd = sqrt(variance) / qMax(1e-10, range);
|
|
|
|
|
|
totalDiversity += normalizedStd;
|
|
|
}
|
|
|
|
|
|
return totalDiversity / dimensions;
|
|
|
}
|
|
|
|
|
|
double nmFitPSO::calculateAverageVelocity() const
|
|
|
{
|
|
|
// 平均速度:逐维速度绝对值按参数范围归一化。
|
|
|
// 收敛阶段速度应逐渐变小。
|
|
|
if(m_swarm.isEmpty())
|
|
|
return 0.0;
|
|
|
|
|
|
int dimensions = getEnabledParameterCount();
|
|
|
|
|
|
if(dimensions == 0)
|
|
|
return 0.0;
|
|
|
|
|
|
double totalVelocity = 0.0;
|
|
|
|
|
|
for(int i = 0; i < m_swarm.size(); ++i) {
|
|
|
for(int dim = 0; dim < dimensions; ++dim) {
|
|
|
int paramIndex = m_enabledParamIndices[dim];
|
|
|
double range = m_parameterUpper[paramIndex] - m_parameterLower[paramIndex];
|
|
|
double normalizedVel = qAbs(m_swarm[i].velocity[dim]) / qMax(1e-10, range);
|
|
|
totalVelocity += normalizedVel;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
return totalVelocity / (static_cast<double>(m_swarm.size()) * dimensions);
|
|
|
}
|
|
|
|
|
|
double nmFitPSO::calculateParticleStagnationRate() const
|
|
|
{
|
|
|
// 粒子停滞率:只统计本代经过真实求解器评价的粒子。
|
|
|
// 被代理筛掉的粒子保留的是旧适应度,不能据此判断本代是否停滞。
|
|
|
if(m_swarm.isEmpty())
|
|
|
return 0.0;
|
|
|
|
|
|
int stagnantParticles = 0;
|
|
|
int evaluatedParticles = 0;
|
|
|
|
|
|
for(int i = 0; i < m_swarm.size(); ++i) {
|
|
|
if(!m_swarm[i].evaluatedThisIteration || !m_swarm[i].lastEvaluationSuccess) {
|
|
|
continue;
|
|
|
}
|
|
|
|
|
|
evaluatedParticles++;
|
|
|
|
|
|
// updateParticle() 会在计算该字段后才覆盖 pbest,因此“刚改善的粒子”
|
|
|
// 不会再被错误地当作停滞。
|
|
|
if(m_swarm[i].pbestRelativeImprovementThisIteration <= 1e-6) { // 改进不超过0.0001%
|
|
|
stagnantParticles++;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
return evaluatedParticles > 0 ? static_cast<double>(stagnantParticles) / evaluatedParticles : 0.0;
|
|
|
}
|
|
|
|
|
|
double nmFitPSO::calculateFitnessVariance(int windowSize) const
|
|
|
{
|
|
|
// 最近 windowSize 代全局最优误差的方差。
|
|
|
// 方差越小,说明全局最优曲线越稳定。
|
|
|
if(m_convergenceHistory.size() < windowSize) {
|
|
|
return 1e10; // 数据不足,返回大值
|
|
|
}
|
|
|
|
|
|
// 计算最近windowSize次迭代的方差
|
|
|
double mean = 0.0;
|
|
|
int startIdx = m_convergenceHistory.size() - windowSize;
|
|
|
|
|
|
for(int i = startIdx; i < m_convergenceHistory.size(); ++i) {
|
|
|
mean += m_convergenceHistory[i];
|
|
|
}
|
|
|
|
|
|
mean /= windowSize;
|
|
|
|
|
|
double variance = 0.0;
|
|
|
|
|
|
for(int i = startIdx; i < m_convergenceHistory.size(); ++i) {
|
|
|
double diff = m_convergenceHistory[i] - mean;
|
|
|
variance += diff * diff;
|
|
|
}
|
|
|
|
|
|
variance /= windowSize;
|
|
|
|
|
|
return variance;
|
|
|
}
|
|
|
|
|
|
double nmFitPSO::calculateLongTermImprovement(int windowSize) const
|
|
|
{
|
|
|
// 最近 windowSize 代相对改进幅度。
|
|
|
// 数据不足时返回 1.0,表示“还不能认为没有改进”。
|
|
|
if(m_convergenceHistory.size() < windowSize) {
|
|
|
return 1.0; // 数据不足,假设有改进
|
|
|
}
|
|
|
|
|
|
double oldFitness = m_convergenceHistory[m_convergenceHistory.size() - windowSize];
|
|
|
double improvement = (oldFitness - m_globalBestFitness) / qMax(1e-10, qAbs(oldFitness));
|
|
|
|
|
|
return improvement;
|
|
|
}
|
|
|
|
|
|
QString nmFitPSO::getStopReasonDescription(StopReasonPSO reason) const
|
|
|
{
|
|
|
// 将停止枚举转成人类可读文本,用于日志和运行摘要。
|
|
|
switch(reason) {
|
|
|
case PSO_TARGET_ACHIEVED:
|
|
|
return fitTr("Target error achieved");
|
|
|
|
|
|
case PSO_TRUE_CONVERGENCE:
|
|
|
return fitTr("Algorithm converged to stable solution");
|
|
|
|
|
|
case PSO_LOCAL_OPTIMUM:
|
|
|
return fitTr("Local optimum detected");
|
|
|
|
|
|
case PSO_MAX_ITERATIONS:
|
|
|
return fitTr("Maximum iterations reached");
|
|
|
|
|
|
case PSO_USER_STOPPED:
|
|
|
return fitTr("Stopped by user request");
|
|
|
|
|
|
case PSO_CONSECUTIVE_FAILURES:
|
|
|
return fitTr("Too many consecutive failures");
|
|
|
|
|
|
case PSO_OPTIMIZATION_FAILED:
|
|
|
return fitTr("Optimization failed");
|
|
|
|
|
|
default:
|
|
|
return fitTr("Unknown reason");
|
|
|
}
|
|
|
}
|
|
|
|
|
|
void nmFitPSO::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;
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
|
|
|
bool nmFitPSO::runOptimization()
|
|
|
{
|
|
|
// 自动拟合的总入口。可以把这个函数当成 PSO 的“运行剧本”:
|
|
|
// 读取配置 -> 校验输入 -> 评价用户初始解 -> 初始化粒子群 ->
|
|
|
// 按代循环评价粒子 -> 更新全局最优 -> 判断停止 -> 保存结果。
|
|
|
if(m_isRunning) {
|
|
|
m_lastError = fitTr("Auto fitting is already running");
|
|
|
return false;
|
|
|
}
|
|
|
|
|
|
// 发送初始化日志
|
|
|
emit logMessageGenerated(fitTr("Algorithm: Particle Swarm Optimization"));
|
|
|
|
|
|
try {
|
|
|
// 从本轮请求读取自动拟合配置。
|
|
|
// 配置和曲线均由调用方提供。
|
|
|
if(!loadConfiguration()) {
|
|
|
emit logMessageGenerated(fitTr("ERROR: Failed to load configuration from data manager"));
|
|
|
return false;
|
|
|
}
|
|
|
|
|
|
int enabledParams = getEnabledParameterCount();
|
|
|
emit logMessageGenerated(fitTr("Enabled parameters count: %1").arg(enabledParams));
|
|
|
|
|
|
if(enabledParams == 0) {
|
|
|
m_lastError = fitTr("No parameters enabled for optimization");
|
|
|
emit logMessageGenerated(fitTr("ERROR: No parameters enabled for optimization"));
|
|
|
return false;
|
|
|
}
|
|
|
|
|
|
if(m_targetLogLogData.isEmpty() || m_targetLogLogData.size() < 3) {
|
|
|
m_lastError = fitTr("Target LogLog data is empty or insufficient");
|
|
|
emit logMessageGenerated(fitTr("ERROR: Target LogLog data is empty or insufficient"));
|
|
|
return false;
|
|
|
}
|
|
|
|
|
|
// 目标曲线必须至少包含三列:time、pressure、pressure derivative,
|
|
|
// 且三列长度一致。后续误差函数会按 time 做插值对齐。
|
|
|
if(m_targetLogLogData[0].size() != m_targetLogLogData[1].size() ||
|
|
|
m_targetLogLogData[0].size() != m_targetLogLogData[2].size()) {
|
|
|
m_lastError = fitTr("Target LogLog data arrays have inconsistent sizes");
|
|
|
emit logMessageGenerated(fitTr("ERROR: Target LogLog data arrays have inconsistent sizes"));
|
|
|
return false;
|
|
|
}
|
|
|
|
|
|
emit logMessageGenerated(
|
|
|
fitTr("Target data validation passed (%1 data points)").arg(m_targetLogLogData[0].size()));
|
|
|
|
|
|
// 使用保存的初始值进行精英保护。resetOptimizer() 会清空部分运行状态,
|
|
|
// 所以先把用户当前模型参数缓存下来,后面再恢复用于初始解评价和粒子初始化。
|
|
|
QVector<double> savedInitialValues = m_initialValues;
|
|
|
|
|
|
// 重置状态
|
|
|
resetOptimizer();
|
|
|
|
|
|
m_isRunning = true;
|
|
|
m_shouldStop = false;
|
|
|
m_currentIteration = 0;
|
|
|
|
|
|
if(kUseFixedPsoSeed) {
|
|
|
// 使用请求中的随机种子,便于复现粒子搜索过程和筛选结果。
|
|
|
m_psoRandomSeed = m_request.randomSeed;
|
|
|
} else {
|
|
|
QTime seedTime = QTime::currentTime();
|
|
|
m_psoRandomSeed = static_cast<unsigned int>(QDateTime::currentDateTime().toTime_t());
|
|
|
m_psoRandomSeed ^= static_cast<unsigned int>((seedTime.hour() << 22) ^ (seedTime.minute() << 16) ^
|
|
|
(seedTime.second() << 10) ^ seedTime.msec());
|
|
|
}
|
|
|
|
|
|
if(m_psoRandomSeed == 0u) {
|
|
|
m_psoRandomSeed = 1u;
|
|
|
}
|
|
|
|
|
|
qsrand(m_psoRandomSeed);
|
|
|
m_consecutiveFailedIterations = 0; // 重置连续失败迭代计数
|
|
|
|
|
|
// 精英保护:先评价用户当前模型。
|
|
|
// 如果后续 PSO 没找到更好解,最终结果不会比用户已有模型更差。
|
|
|
m_initialValues = savedInitialValues;
|
|
|
// 通知调用方本轮运行已初始化。
|
|
|
emit runInitialized();
|
|
|
|
|
|
// 加速策略自行准备资源,算法不关心模型进程。
|
|
|
if(m_acceleration)
|
|
|
m_acceleration->begin();
|
|
|
|
|
|
if(!savedInitialValues.isEmpty()) {
|
|
|
m_userInitialSolution = savedInitialValues;
|
|
|
emit logMessageGenerated(fitTr("=== Evaluating Initial Solution (Elite Protection) ==="));
|
|
|
|
|
|
// 输出初始参数值,便于在诊断记录中核对参数顺序。
|
|
|
QString paramStr = fitTr("Initial parameters: ");
|
|
|
|
|
|
for(int i = 0; i < m_userInitialSolution.size(); ++i) {
|
|
|
paramStr += QString("%1=%2 ")
|
|
|
.arg(m_modelParameters[m_enabledParamIndices[i]].name())
|
|
|
.arg(m_userInitialSolution[i], 0, 'g', 10);
|
|
|
}
|
|
|
|
|
|
emit logMessageGenerated(paramStr);
|
|
|
|
|
|
try {
|
|
|
emit logMessageGenerated(fitTr("Starting initial solution evaluation..."));
|
|
|
DEBUG_OUT(
|
|
|
QString("Before evaluateError: m_userInitialSolution size = %1").arg(m_userInitialSolution.size()));
|
|
|
|
|
|
if(m_userInitialSolution.isEmpty()) {
|
|
|
emit logMessageGenerated(fitTr("ERROR: m_userInitialSolution is empty!"));
|
|
|
|
|
|
m_isRunning = false;
|
|
|
return false;
|
|
|
}
|
|
|
|
|
|
QTime initialEvalTimer;
|
|
|
initialEvalTimer.start();
|
|
|
// 初始精英解也是一次真实 DLL 调用。第一代第0号粒子会复用它,
|
|
|
// 因此在这里计数,保证汇总中的评价次数等于实际求解调用数。
|
|
|
m_totalEvaluations++;
|
|
|
m_userInitialFitness = evaluateFitness(m_userInitialSolution);
|
|
|
int initialEvalElapsedMs = initialEvalTimer.elapsed();
|
|
|
|
|
|
if(m_userInitialFitness < 1e9) {
|
|
|
m_successfulEvaluations++;
|
|
|
m_hasValidUserSolution = true;
|
|
|
m_globalBestFitness = m_userInitialFitness;
|
|
|
m_globalBestPosition = m_userInitialSolution;
|
|
|
m_userInitialLogLogData = m_lastEvaluatedLogLogData;
|
|
|
m_globalBestLogLogData = m_userInitialLogLogData;
|
|
|
|
|
|
emit logMessageGenerated(fitTr("Initial solution evaluation successful"));
|
|
|
emit logMessageGenerated(fitTr("Initial Error: %1").arg(m_userInitialFitness, 0, 'e', 4));
|
|
|
emit logMessageGenerated(fitTr("Elite protection activated - initial solution will be preserved if "
|
|
|
"no significant improvement found"));
|
|
|
emit bestCurveUpdated(m_targetLogLogData, m_globalBestLogLogData, 0, m_globalBestFitness);
|
|
|
} else {
|
|
|
m_hasValidUserSolution = false;
|
|
|
emit logMessageGenerated(
|
|
|
fitTr("Initial solution evaluation failed - starting with random initialization"));
|
|
|
}
|
|
|
|
|
|
emitTraceRow(-1, -1, "initial_solution", m_userInitialSolution, m_userInitialFitness,
|
|
|
m_userInitialFitness < 1e9, initialEvalElapsedMs,
|
|
|
std::numeric_limits<double>::quiet_NaN(), "initial_solution",
|
|
|
m_hasValidUserSolution ? m_userInitialSolution : QVector<double>(), m_userInitialFitness);
|
|
|
}
|
|
|
catch(...) {
|
|
|
m_hasValidUserSolution = false;
|
|
|
emit logMessageGenerated(fitTr("Exception during initial solution evaluation"));
|
|
|
}
|
|
|
|
|
|
// 恢复初始值供粒子群初始化使用
|
|
|
m_initialValues = savedInitialValues;
|
|
|
}
|
|
|
|
|
|
// 初始化粒子群,粒子维度等于选中参数的数量。
|
|
|
emit logMessageGenerated(fitTr("PSO random seed: %1 ").arg(m_psoRandomSeed));
|
|
|
|
|
|
initializeSwarm();
|
|
|
emit logMessageGenerated(
|
|
|
fitTr("Swarm initialized: %1 particles, %2 dimensions").arg(m_swarmSize).arg(getEnabledParameterCount()));
|
|
|
|
|
|
// PSO主循环:每一代先决定哪些粒子需要真实评价,再更新全局最优和粒子位置。
|
|
|
emit logMessageGenerated(fitTr("=== Starting PSO Main Loop ==="));
|
|
|
|
|
|
for(m_currentIteration = 0; m_currentIteration < m_maxIterations && !m_shouldStop; ++m_currentIteration) {
|
|
|
// 每次迭代都输出标题,或者只在重要迭代输出详细信息
|
|
|
bool shouldOutputDetail = (m_currentIteration % qMax(1, m_maxIterations / 10) == 0) ||
|
|
|
(m_currentIteration < 5) ||
|
|
|
(m_currentIteration >= m_maxIterations - 2); // 总是输出前5次和最后2次的详细信息
|
|
|
|
|
|
// 每次迭代都输出标题
|
|
|
emit logMessageGenerated(fitTr("--- Iteration %1/%2 ---").arg(m_currentIteration + 1).arg(m_maxIterations));
|
|
|
|
|
|
// 只在特定迭代输出详细统计信息
|
|
|
if(shouldOutputDetail) {
|
|
|
emit logMessageGenerated(fitTr("Current best error: %1").arg(m_globalBestFitness, 0, 'e', 4));
|
|
|
emit logMessageGenerated(fitTr("Total evaluations: %1 (successful: %2, failures: %3)")
|
|
|
.arg(m_totalEvaluations)
|
|
|
.arg(m_successfulEvaluations)
|
|
|
.arg(m_totalEvaluations - m_successfulEvaluations));
|
|
|
}
|
|
|
|
|
|
if(m_shouldStop) {
|
|
|
emit logMessageGenerated(fitTr("Optimization stopped by user request"));
|
|
|
break;
|
|
|
}
|
|
|
|
|
|
int currentIterationSuccessful = 0;
|
|
|
int currentIterationTotal = 0;
|
|
|
int currentIterationFailed = 0;
|
|
|
int currentIterationSkipped = 0;
|
|
|
QVector<bool> evaluateMask = buildSurrogateEvaluationMask();
|
|
|
|
|
|
for(int i = 0; i < m_swarmSize && !m_shouldStop; ++i) {
|
|
|
try {
|
|
|
if(i < evaluateMask.size() && !evaluateMask[i]) {
|
|
|
// 被代理模型筛掉的粒子本代不跑真实求解器。
|
|
|
// 这里不会用 surrogateObjective 更新 pbest,避免代理误差污染真实最优。
|
|
|
AutoFitParticle& particle = m_swarm[i];
|
|
|
particle.evaluatedThisIteration = false;
|
|
|
particle.lastEvaluationSuccess = false;
|
|
|
particle.lastEvaluationElapsedMs = -1;
|
|
|
particle.pbestRelativeImprovementThisIteration = 0.0;
|
|
|
particle.selectedForSolver = false;
|
|
|
|
|
|
if(particle.screeningDecision.isEmpty()) {
|
|
|
particle.screeningDecision = "screened_out";
|
|
|
}
|
|
|
|
|
|
currentIterationSkipped++;
|
|
|
continue;
|
|
|
}
|
|
|
|
|
|
double previousFitness = m_swarm[i].fitness;
|
|
|
// 对单个粒子执行真实评价:写参数 -> 跑求解器 -> 算曲线误差 -> 更新 pbest。
|
|
|
updateParticle(i);
|
|
|
currentIterationTotal++;
|
|
|
|
|
|
if(m_swarm[i].fitness < 1e9) {
|
|
|
currentIterationSuccessful++;
|
|
|
|
|
|
if(shouldOutputDetail && m_swarm[i].fitness < previousFitness) {
|
|
|
// 计算改进幅度
|
|
|
double improvement = (previousFitness - m_swarm[i].fitness) / qMax(1e-10, previousFitness);
|
|
|
|
|
|
if(improvement > 0.01) { // 1%以上改进才输出
|
|
|
emit logMessageGenerated(fitTr(" Particle %1 improved: %2 -> %3 (%4% improvement)")
|
|
|
.arg(i + 1)
|
|
|
.arg(previousFitness, 0, 'e', 3)
|
|
|
.arg(m_swarm[i].fitness, 0, 'e', 3)
|
|
|
.arg(improvement * 100, 0, 'f', 2));
|
|
|
}
|
|
|
}
|
|
|
} else {
|
|
|
currentIterationFailed++;
|
|
|
|
|
|
if(shouldOutputDetail) {
|
|
|
emit logMessageGenerated(fitTr(" Particle %1: evaluation failed").arg(i + 1));
|
|
|
}
|
|
|
}
|
|
|
|
|
|
// 每评估2个粒子处理一次事件
|
|
|
if(i % 2 == 0) {
|
|
|
pollEvents();
|
|
|
}
|
|
|
}
|
|
|
catch(const std::exception& e) {
|
|
|
if(shouldOutputDetail) {
|
|
|
emit logMessageGenerated(fitTr(" Particle %1: Exception: %2").arg(i + 1).arg(e.what()));
|
|
|
}
|
|
|
|
|
|
m_swarm[i].fitness = 1e10;
|
|
|
currentIterationTotal++;
|
|
|
currentIterationFailed++;
|
|
|
m_totalEvaluations++;
|
|
|
}
|
|
|
catch(...) {
|
|
|
if(shouldOutputDetail) {
|
|
|
emit logMessageGenerated(fitTr(" Particle %1: Unknown exception").arg(i + 1));
|
|
|
}
|
|
|
|
|
|
m_swarm[i].fitness = 1e10;
|
|
|
currentIterationTotal++;
|
|
|
currentIterationFailed++;
|
|
|
m_totalEvaluations++;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
if(m_shouldStop)
|
|
|
break;
|
|
|
|
|
|
double currentSuccessRate =
|
|
|
currentIterationTotal > 0 ? (double)currentIterationSuccessful / currentIterationTotal : 0.0;
|
|
|
|
|
|
// 更新连续失败迭代计数
|
|
|
if(currentIterationSuccessful == 0) {
|
|
|
m_consecutiveFailedIterations++;
|
|
|
emit logMessageGenerated(
|
|
|
fitTr("WARNING: No successful evaluations in iteration %1 (consecutive failures: %2)")
|
|
|
.arg(m_currentIteration + 1)
|
|
|
.arg(m_consecutiveFailedIterations));
|
|
|
} else {
|
|
|
m_consecutiveFailedIterations = 0; // 重置连续失败计数
|
|
|
}
|
|
|
|
|
|
// 输出当前迭代统计
|
|
|
if(shouldOutputDetail) {
|
|
|
emit logMessageGenerated(fitTr("Current iteration stats: %1 successful, %2 failed, %3 skipped out of "
|
|
|
"%4 particles (solver success rate: %5%)")
|
|
|
.arg(currentIterationSuccessful)
|
|
|
.arg(currentIterationFailed)
|
|
|
.arg(currentIterationSkipped)
|
|
|
.arg(m_swarmSize)
|
|
|
.arg(currentSuccessRate * 100, 0, 'f', 1));
|
|
|
}
|
|
|
|
|
|
// 检查是否需要停止优化
|
|
|
if(m_consecutiveFailedIterations >= m_maxConsecutiveFailures) {
|
|
|
m_lastError = fitTr("Too many consecutive failed iterations (%1)").arg(m_consecutiveFailedIterations);
|
|
|
emit logMessageGenerated(
|
|
|
fitTr("ERROR: Too many consecutive failed iterations (%1/%2) - stopping optimization")
|
|
|
.arg(m_consecutiveFailedIterations)
|
|
|
.arg(m_maxConsecutiveFailures));
|
|
|
break;
|
|
|
}
|
|
|
|
|
|
// 警告低成功率但不立即停止
|
|
|
if(currentSuccessRate < 0.5 && m_currentIteration > 3) {
|
|
|
emit logMessageGenerated(
|
|
|
fitTr("WARNING: Low success rate (%1%) in iteration %2, but continuing optimization")
|
|
|
.arg(currentSuccessRate * 100, 0, 'f', 1)
|
|
|
.arg(m_currentIteration + 1));
|
|
|
}
|
|
|
|
|
|
// 更新全局最优。updateGlobalBest() 只读取粒子的真实 bestFitness,
|
|
|
// 不使用代理模型的 surrogateObjective。
|
|
|
updateGlobalBest();
|
|
|
// 记录本代所有粒子的真实/代理误差和筛选决策,用于复盘和排障。
|
|
|
emitIterationTraceRows();
|
|
|
|
|
|
// 自适应参数更新
|
|
|
adaptiveParameterUpdate(m_currentIteration);
|
|
|
|
|
|
emit progressUpdated(m_currentIteration + 1, m_globalBestFitness);
|
|
|
|
|
|
// 记录收敛历史
|
|
|
m_convergenceHistory.append(m_globalBestFitness);
|
|
|
|
|
|
// 每5次迭代输出收敛状态
|
|
|
if((m_currentIteration + 1) % 5 == 0) {
|
|
|
double recentImprovement = 0.0;
|
|
|
|
|
|
if(m_convergenceHistory.size() >= 5) {
|
|
|
double oldBest = m_convergenceHistory[m_convergenceHistory.size() - 5];
|
|
|
recentImprovement = (oldBest - m_globalBestFitness) / qMax(1e-10, oldBest);
|
|
|
}
|
|
|
|
|
|
emit logMessageGenerated(fitTr(" Convergence check: recent improvement = %1% over last 5 iterations")
|
|
|
.arg(recentImprovement * 100, 0, 'f', 4));
|
|
|
}
|
|
|
|
|
|
// 智能收敛判断:目标达成、稳定收敛、局部最优、连续失败等都会在这里决策。
|
|
|
StopReasonPSO stopReason = analyzeOptimizationStatus();
|
|
|
|
|
|
if(stopReason == PSO_TARGET_ACHIEVED) {
|
|
|
emit logMessageGenerated(fitTr("=== TARGET ACHIEVED ==="));
|
|
|
emit logMessageGenerated(fitTr("Target error achieved! Current error: %1 < Target: %2")
|
|
|
.arg(m_globalBestFitness, 0, 'e', 4)
|
|
|
.arg(m_targetError, 0, 'e', 4));
|
|
|
emit logMessageGenerated(
|
|
|
fitTr("Optimization completed successfully after %1 iterations").arg(m_currentIteration + 1));
|
|
|
break;
|
|
|
} else if(stopReason == PSO_TRUE_CONVERGENCE) {
|
|
|
emit logMessageGenerated(fitTr("=== TRUE CONVERGENCE DETECTED ==="));
|
|
|
emit logMessageGenerated(fitTr("Algorithm has converged to a stable solution"));
|
|
|
emit logMessageGenerated(fitTr("Final error: %1 after %2 iterations")
|
|
|
.arg(m_globalBestFitness, 0, 'e', 4)
|
|
|
.arg(m_currentIteration + 1));
|
|
|
emit logMessageGenerated(fitTr("Solution quality: %1 (1.0 = target achieved)")
|
|
|
.arg(m_targetError / qMax(1e-10, m_globalBestFitness), 0, 'f', 3));
|
|
|
break;
|
|
|
} else if(stopReason == PSO_LOCAL_OPTIMUM) {
|
|
|
emit logMessageGenerated(fitTr("=== LOCAL OPTIMUM DETECTED ==="));
|
|
|
emit logMessageGenerated(fitTr("Algorithm appears to be trapped in local optimum"));
|
|
|
emit logMessageGenerated(fitTr("Current error: %1 after %2 iterations")
|
|
|
.arg(m_globalBestFitness, 0, 'e', 4)
|
|
|
.arg(m_currentIteration + 1));
|
|
|
emit logMessageGenerated(
|
|
|
fitTr("Suggestion: Try restarting with different parameters or larger search space"));
|
|
|
break;
|
|
|
} else if(stopReason == PSO_CONSECUTIVE_FAILURES) {
|
|
|
emit logMessageGenerated(fitTr("=== CONSECUTIVE FAILURES ==="));
|
|
|
emit logMessageGenerated(fitTr("Too many consecutive failed iterations (%1/%2)")
|
|
|
.arg(m_consecutiveFailedIterations)
|
|
|
.arg(m_maxConsecutiveFailures));
|
|
|
break;
|
|
|
} else if(stopReason == PSO_CONTINUE_OPTIMIZATION) {
|
|
|
// 继续优化,每10次迭代输出一次状态
|
|
|
if(m_currentIteration > 0 && m_currentIteration % 10 == 0) {
|
|
|
double diversity = calculateSwarmDiversity();
|
|
|
double avgVel = calculateAverageVelocity();
|
|
|
double stagnation = calculateParticleStagnationRate();
|
|
|
|
|
|
emit logMessageGenerated(fitTr(" Optimization status: diversity=%1, avgVel=%2, stagnation=%3%")
|
|
|
.arg(diversity, 0, 'f', 4)
|
|
|
.arg(avgVel, 0, 'f', 4)
|
|
|
.arg(stagnation * 100, 0, 'f', 1));
|
|
|
}
|
|
|
}
|
|
|
|
|
|
// 更新粒子位置和速度
|
|
|
updateVelocityAndPosition();
|
|
|
|
|
|
// 输出迭代结束标记
|
|
|
if(shouldOutputDetail) {
|
|
|
emit logMessageGenerated(fitTr(" Iteration %1 completed - Current best: %2")
|
|
|
.arg(m_currentIteration + 1)
|
|
|
.arg(m_globalBestFitness, 0, 'e', 4));
|
|
|
}
|
|
|
|
|
|
// 调用可选事件回调并检查取消状态。
|
|
|
pollEvents();
|
|
|
|
|
|
// 在迭代间稍作停顿,减少系统负载
|
|
|
if(m_currentIteration % 3 == 2) {
|
|
|
msleep(200);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
// 最终结果验证和保护
|
|
|
validateAndProtectFinalResult();
|
|
|
}
|
|
|
catch(const std::exception& e) {
|
|
|
m_lastError = QString(fitTr("Critical exception in PSO main loop: %1")).arg(e.what());
|
|
|
emit logMessageGenerated(fitTr("CRITICAL ERROR: %1").arg(e.what()));
|
|
|
m_isRunning = false;
|
|
|
return false;
|
|
|
}
|
|
|
catch(...) {
|
|
|
m_lastError = QString(fitTr("Unknown critical exception in PSO main loop"));
|
|
|
emit logMessageGenerated(fitTr("CRITICAL ERROR: Unknown exception in PSO main loop"));
|
|
|
m_isRunning = false;
|
|
|
return false;
|
|
|
}
|
|
|
|
|
|
m_stopReason = analyzeOptimizationStatus();
|
|
|
return true;
|
|
|
}
|
|
|
|
|
|
bool nmFitPSO::loadConfiguration()
|
|
|
{
|
|
|
// 每轮拟合开始时恢复自适应更新前的默认系数。
|
|
|
m_swarmSize = 20;
|
|
|
m_inertiaWeight = 0.4;
|
|
|
m_cognitiveParam = 2.0;
|
|
|
m_socialParam = 1.2;
|
|
|
m_modelParameters = m_request.parameters;
|
|
|
m_maxIterations = m_request.maxIterations;
|
|
|
m_targetError = m_request.targetError;
|
|
|
m_parameterSelected.clear();
|
|
|
m_parameterLower.clear();
|
|
|
m_parameterUpper.clear();
|
|
|
m_enabledParamIndices.clear();
|
|
|
for(int i = 0; i < m_modelParameters.size(); ++i) {
|
|
|
const nmFitParameterValue& p = m_modelParameters[i];
|
|
|
if(p.type < 0 || p.type > 5 || !isFiniteNumber(p.initial) || !isFiniteNumber(p.lower) ||
|
|
|
!isFiniteNumber(p.upper) || p.lower > p.upper) {
|
|
|
m_lastError = fitTr("Invalid fitting parameter.");
|
|
|
return false;
|
|
|
}
|
|
|
m_parameterSelected.append(p.selected);
|
|
|
m_parameterLower.append(p.lower);
|
|
|
m_parameterUpper.append(p.upper);
|
|
|
if(p.selected)
|
|
|
m_enabledParamIndices.append(i);
|
|
|
}
|
|
|
if(m_maxIterations < 1 || !isFiniteNumber(m_targetError) || m_targetError <= 0) {
|
|
|
m_lastError = fitTr("Invalid fitting options.");
|
|
|
return false;
|
|
|
}
|
|
|
extractUserInitialValues();
|
|
|
return true;
|
|
|
}
|
|
|
|
|
|
void nmFitPSO::emitTraceRow(int generation, int particleIndex, const QString& phase, const QVector<double>& parameters,
|
|
|
double solverObjective, bool solverSuccess, int elapsedMs, double surrogateObjective,
|
|
|
const QString& screeningDecision, const QVector<double>& pbestPosition,
|
|
|
double pbestObjective)
|
|
|
{
|
|
|
// 只发布数据,不在计算模块写日志文件。
|
|
|
emit traceRowGenerated(generation, particleIndex, phase, parameters, solverObjective, solverSuccess, elapsedMs,
|
|
|
surrogateObjective, screeningDecision, pbestPosition, pbestObjective);
|
|
|
}
|
|
|
|
|
|
double nmFitPSO::evaluateFitness(const QVector<double>& parameters)
|
|
|
{
|
|
|
if(m_cancelled && m_cancelled())
|
|
|
m_shouldStop = true;
|
|
|
m_lastEvaluatedLogLogData.clear();
|
|
|
if(m_shouldStop || !validateParameters(parameters) || !m_evaluate)
|
|
|
return 1e10;
|
|
|
nmFitCurve curve = m_evaluate(parameters, true);
|
|
|
if(m_cancelled && m_cancelled())
|
|
|
m_shouldStop = true;
|
|
|
if(m_shouldStop || !validateLogLogData(curve))
|
|
|
return 1e10;
|
|
|
double error = calculateLogLogCurveError(m_targetLogLogData, curve);
|
|
|
if(error < 1e9)
|
|
|
m_lastEvaluatedLogLogData = curve;
|
|
|
return error;
|
|
|
}
|
|
|
|
|
|
void nmFitPSO::emitIterationTraceRows()
|
|
|
{
|
|
|
// 每代真实评价和全局最优更新后,发布全部粒子的诊断通知。
|
|
|
// 通知包含筛选决策、评价结果及当前个体最优值。
|
|
|
|
|
|
for(int i = 0; i < m_swarm.size(); ++i) {
|
|
|
const AutoFitParticle& particle = m_swarm[i];
|
|
|
double solverObjective =
|
|
|
particle.evaluatedThisIteration ? particle.fitness : std::numeric_limits<double>::quiet_NaN();
|
|
|
QString phase = !particle.evaluatedThisIteration
|
|
|
? "particle_not_evaluated"
|
|
|
: (particle.screeningDecision == "initial_solution_cache" ? "particle_verified_cache"
|
|
|
: "particle_solver");
|
|
|
emitTraceRow(m_currentIteration, i, phase, particle.position, solverObjective, particle.lastEvaluationSuccess,
|
|
|
particle.lastEvaluationElapsedMs, particle.surrogateObjective, particle.screeningDecision,
|
|
|
particle.bestPosition, particle.bestFitness);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
QVector<bool> nmFitPSO::buildSurrogateEvaluationMask()
|
|
|
{
|
|
|
QVector<bool> mask(m_swarm.size(), true);
|
|
|
for(int i = 0; i < m_swarm.size(); ++i) {
|
|
|
m_swarm[i].surrogateObjective = std::numeric_limits<double>::quiet_NaN();
|
|
|
m_swarm[i].selectedForSolver = true;
|
|
|
m_swarm[i].selectedByAudit = false;
|
|
|
m_swarm[i].screeningDecision = "full_solver";
|
|
|
}
|
|
|
if(!m_acceleration) {
|
|
|
resetGuideBestToVerified();
|
|
|
return mask;
|
|
|
}
|
|
|
const QVector<AutoFitParticle> advised = m_acceleration->select(m_swarm, m_currentIteration, m_psoRandomSeed);
|
|
|
if(advised.size() != m_swarm.size()) {
|
|
|
resetGuideBestToVerified();
|
|
|
return mask;
|
|
|
}
|
|
|
// 仅接收筛选和引导字段,真实 pbest/gbest 不允许被策略覆盖。
|
|
|
for(int i = 0; i < m_swarm.size(); ++i) {
|
|
|
AutoFitParticle& p = m_swarm[i];
|
|
|
const AutoFitParticle& a = advised[i];
|
|
|
p.guideBestPosition = a.guideBestPosition;
|
|
|
p.guideBestObjective = a.guideBestObjective;
|
|
|
p.guideBestFromSurrogate = a.guideBestFromSurrogate;
|
|
|
p.surrogateObjective = a.surrogateObjective;
|
|
|
p.selectedForSolver = a.selectedForSolver;
|
|
|
p.selectedByAudit = a.selectedByAudit;
|
|
|
p.screeningDecision = a.screeningDecision;
|
|
|
mask[i] = a.selectedForSolver;
|
|
|
}
|
|
|
return mask;
|
|
|
}
|
|
|
|
|
|
bool nmFitPSO::isSurrogateScreeningEnabled() const
|
|
|
{
|
|
|
return m_acceleration != nullptr;
|
|
|
}
|
|
|
|
|
|
void nmFitPSO::pollEvents()
|
|
|
{
|
|
|
// 可选调度由调用方提供,独立计算不依赖界面。
|
|
|
if(m_callbacks.processEvents)
|
|
|
m_callbacks.processEvents();
|
|
|
if(m_cancelled && m_cancelled())
|
|
|
m_shouldStop = true;
|
|
|
}
|
|
|
|
|
|
void nmFitPSO::stopFitting()
|
|
|
{
|
|
|
// 同步评价返回后由主循环协作退出。
|
|
|
m_shouldStop = true;
|
|
|
}
|
|
|
|
|
|
nmFitResult nmFitPSO::fit(const nmFitRequest& request, const nmFitEvaluator& evaluate,
|
|
|
const std::function<bool()>& cancelled, nmPsoAcceleration* acceleration,
|
|
|
const nmFitCallbacks& callbacks)
|
|
|
{
|
|
|
// 运行输入按值冻结;返回前释放调用方回调,避免持有局部对象。
|
|
|
nmFitResult result;
|
|
|
if(m_isRunning) {
|
|
|
result.error = fitTr("Auto fitting is already running");
|
|
|
return result;
|
|
|
}
|
|
|
resetOptimizer();
|
|
|
m_stopReason = 7;
|
|
|
m_callbacks = callbacks;
|
|
|
m_request = request;
|
|
|
m_evaluate = evaluate;
|
|
|
m_cancelled = cancelled;
|
|
|
setTargetLogLogData(request.targetCurve);
|
|
|
m_acceleration = acceleration;
|
|
|
if(!evaluate)
|
|
|
m_lastError = fitTr("Missing solver evaluator.");
|
|
|
const bool completed = evaluate && runOptimization();
|
|
|
m_isRunning = false;
|
|
|
result.completed = completed;
|
|
|
result.hasSolution = !m_globalBestPosition.isEmpty() && m_globalBestFitness < 1e9;
|
|
|
result.success = completed && result.hasSolution && m_stopReason != 6 && m_stopReason != 7;
|
|
|
result.values = m_globalBestPosition;
|
|
|
result.curve = m_globalBestLogLogData;
|
|
|
result.fitness = m_globalBestFitness;
|
|
|
result.stopReason = m_stopReason;
|
|
|
result.iterations = qMax(0, m_currentIteration + 1);
|
|
|
result.evaluations = m_totalEvaluations;
|
|
|
result.error = m_lastError;
|
|
|
for(int i = 0; i < request.parameters.size(); ++i)
|
|
|
if(request.parameters[i].selected)
|
|
|
result.parameters.append(request.parameters[i]);
|
|
|
m_callbacks = nmFitCallbacks();
|
|
|
m_evaluate = nmFitEvaluator();
|
|
|
m_cancelled = std::function<bool()>();
|
|
|
m_acceleration = nullptr;
|
|
|
return result;
|
|
|
}
|