feat(numerical): 实现 PEBI 结果快照 v3 持久化

- 增加快照网格、压力帧和井曲线的流式序列化
- 增加三级 SHA-1 引用链及载荷安全校验
- 增加显式保存会话和 Windows 根清单原子发布
- 数值成果保存与加载切换至 v3,并明确拒绝 v2
- 增加 v3 持久化回归测试
feature/pebi-result-snapshot-20260831
lh 3 months ago
parent 3bf169cd54
commit e0577d1649

@ -11,6 +11,7 @@
#include "nmDataVerticalFracturedWell.h"
#include "nmDataHorizontalFracturedWell.h"
#include "nmDataNumericalAnalysisCase.h"
#include "nmNumericalResultPersistence.h"
#include "nmGridDefine.h"
@ -663,7 +664,27 @@ public:
// 统一的写整个项目数据的方法
// @param filePath JSON文件的路径
// @return 写入成功返回 true,否则返回 false
bool WriteProjectData(const QString& filePath);
bool WriteProjectData(
const QString& filePath,
const nmNumericalWindowPayloadReferences* pPayloadReferences = NULL);
/**
* @brief 将本窗口完整写入保存会话指定的 v3 代次目录。
* @note 主 JSON 最后写入,并在返回前校验全部引用文件。
*/
bool saveNmResultV3(
const QString& sWindowDirectory,
nmNumericalFileReference& oMainJsonReference,
QString* pError = NULL);
/**
* @brief 校验一个 v3 窗口主 JSON 明确引用的全部载荷。
* @note 保存会话用它复核从旧根清单保留、但本轮未重写的窗口。
*/
static bool validateNmResultV3Window(
const QString& sWindowDirectory,
const QString& sMainJsonPath,
QString* pError = NULL);
// 保存数值成果到本地
// @param sRstCode 当前成果ID

@ -172,6 +172,13 @@ public:
quint64 getBuiltGridRevision() const;
/** @brief 返回最新产量/PVT等求解输入版本,供后台任务启动时捕获。 */
quint64 getResultInputRevision() const;
/**
* @brief 从 v3 成果恢复三个输入版本号。
* @note 当前网格版本只能为 0 或等于网格输入版本。
*/
bool restoreInputRevisions(quint64 nGridInputRevision,
quint64 nBuiltGridRevision,
quint64 nResultInputRevision);
/** @brief 清空方案状态,用于重新加载项目。 */
void clear();

@ -0,0 +1,116 @@
#ifndef NMNUMERICALRESULTPERSISTENCE_H
#define NMNUMERICALRESULTPERSISTENCE_H
#include "nmData_global.h"
#include <QMap>
#include <QString>
#include <QVector>
#include <vtkSmartPointer.h>
class QFile;
class vtkUnstructuredGrid;
/** @brief v3 清单中对一个不可变文件的长度和 SHA-1 引用。 */
struct NM_DATA_EXPORT nmNumericalFileReference
{
/** @brief 初始化空文件引用。 */
nmNumericalFileReference();
/** @brief 相对于所属窗口目录或成果根目录的正斜杠路径。 */
QString m_sRelativePath;
/** @brief 文件的精确字节长度。 */
quint64 m_nLength;
/** @brief 小写十六进制 SHA-1,固定为 40 个字符。 */
QString m_sSha1;
/** @brief 返回三个引用字段是否满足基本格式。 */
bool isValid() const;
};
/** @brief 一口实时井在 v3 成果中的冻结历史曲线。 */
struct NM_DATA_EXPORT nmNumericalWellHistoryData
{
/** @brief 压力历史曲线。 */
QVector<QVector<double> > m_vecPressure;
/** @brief 双对数历史曲线。 */
QVector<QVector<double> > m_vecLogLog;
/** @brief 半对数历史曲线。 */
QVector<QVector<double> > m_vecSemiLog;
};
/** @brief 一个窗口主 JSON 引用的全部外部载荷。 */
struct NM_DATA_EXPORT nmNumericalWindowPayloadReferences
{
/** @brief 当前输入网格是否存在。 */
bool m_bHasCurrentGrid;
/** @brief 当前输入网格文件引用。 */
nmNumericalFileReference m_oCurrentGrid;
/** @brief 按实时井 UUID 保存的历史曲线文件引用。 */
QMap<QString, nmNumericalFileReference> m_mapWellHistories;
/** @brief 最后成功结果快照是否存在。 */
bool m_bHasSnapshot;
/** @brief 快照元数据 JSON 文件引用。 */
nmNumericalFileReference m_oSnapshot;
/** @brief 初始化为不含网格和快照的窗口引用。 */
nmNumericalWindowPayloadReferences();
};
/**
* @brief v3 持久化共用的路径、哈希、网格和小型二进制工具。
*
* 大文件始终分块处理;JSON 可以由调用方在受限文件大小校验后读取。
*/
class NM_DATA_EXPORT nmNumericalResultPersistence
{
public:
/** @brief 返回当前数值成果格式版本。 */
static int projectVersion();
/** @brief 返回单个二进制载荷的初始损坏拒绝阈值。 */
static quint64 maximumBinaryPayloadBytes();
/** @brief 校验相对路径,并返回规范化后的正斜杠路径。 */
static bool normalizeRelativePath(const QString& sPath,
QString& sNormalizedPath);
/** @brief 将相对路径安全解析到指定根目录内。 */
static bool resolveReferencedPath(const QString& sRootDirectory,
const QString& sRelativePath,
QString& sAbsolutePath);
/** @brief 流式计算文件长度和 SHA-1。 */
static bool buildFileReference(const QString& sAbsolutePath,
const QString& sRelativePath,
nmNumericalFileReference& oReference);
/** @brief 校验引用格式、路径边界、文件长度和流式 SHA-1。 */
static bool validateFileReference(const QString& sRootDirectory,
const nmNumericalFileReference& oReference,
QString* pAbsolutePath = NULL,
QString* pError = NULL);
/** @brief 写入一口实时井的三组历史曲线,不构造整文件缓冲。 */
static bool writeWellHistory(
const QString& sFilePath,
const nmNumericalWellHistoryData& oHistory,
QString* pError = NULL);
/** @brief 在数量和剩余字节校验后读取一口井的历史曲线。 */
static bool readWellHistory(
const QString& sFilePath,
nmNumericalWellHistoryData& oHistory,
QString* pError = NULL);
/** @brief 以二进制 VTU 写出网格并检查 VTK 返回值和文件存在性。 */
static bool writeGrid(vtkUnstructuredGrid* pGrid,
const QString& sFilePath,
QString* pError = NULL);
/** @brief 从 VTU 读取网格;调用方接管返回的 VTK 引用。 */
static bool readGrid(const QString& sFilePath,
vtkSmartPointer<vtkUnstructuredGrid>& pGrid,
QString* pError = NULL);
private:
/** @brief 禁止实例化纯静态工具类。 */
nmNumericalResultPersistence();
};
#endif // NMNUMERICALRESULTPERSISTENCE_H

@ -0,0 +1,102 @@
#ifndef NMNUMERICALSAVESESSION_H
#define NMNUMERICALSAVESESSION_H
#include "nmData_global.h"
#include "nmNumericalResultPersistence.h"
#include <QMap>
#include <QSet>
#include <QString>
class nmDataAnalyzeManager;
/** @brief 根清单中的一个数值分析窗口条目。 */
struct NM_DATA_EXPORT nmNumericalSavedWindow
{
/** @brief 成果业务标识。 */
QString m_sResultId;
/** @brief 数值分析窗口的稳定标识。 */
QString m_sWindowId;
/** @brief 相对于成果根目录的窗口主 JSON 引用。 */
nmNumericalFileReference m_oMainJson;
};
/**
* @brief 跨窗口 v3 保存会话,负责新代次、根清单发布和失败中止。
*
* 一个实例一次只能处理一个代次。析构时若尚未成功提交,会自动中止,
* 防止下一轮保存复用未完成状态。
*/
class NM_DATA_EXPORT nmNumericalSaveSession
{
public:
/** @brief 创建尚未开始的保存会话。 */
nmNumericalSaveSession();
/** @brief 未提交的会话在析构时自动删除本代次临时目录。 */
~nmNumericalSaveSession();
/**
* @brief 开始一个全窗口保存代次。
* @param bPreserveExistingWindows 单窗口兼容保存时保留旧清单其他窗口。
*/
bool begin(const QString& sResultRootDirectory,
const QString& sResultId,
bool bPreserveExistingWindows = false,
QString* pError = NULL);
/** @brief 将一个 Manager 的完整 v3 载荷写入当前代次。 */
bool saveWindowGeneration(const QString& sWindowId,
nmDataAnalyzeManager* pDataManager,
QString* pError = NULL);
/** @brief 校验全部窗口后原子发布根清单并清理未引用旧代次。 */
bool commit(QString* pError = NULL);
/** @brief 中止当前会话并删除尚未发布的本代次目录。 */
void abort();
/** @brief 返回会话是否已经开始且尚未结束。 */
bool isActive() const;
/** @brief 返回本次保存生成的唯一代次标识。 */
QString generationId() const;
/** @brief 返回成果根目录。 */
QString resultRootDirectory() const;
/** @brief 从已发布根清单解析并校验指定窗口的主 JSON。 */
static bool resolveWindowMainJson(
const QString& sResultRootDirectory,
const QString& sWindowId,
QString& sWindowDirectory,
QString& sMainJsonPath,
nmNumericalFileReference* pMainReference = NULL,
QString* pError = NULL);
/** @brief 只校验根清单结构、窗口唯一性和全部主 JSON 哈希。 */
static bool validatePublishedManifest(
const QString& sResultRootDirectory,
QString* pError = NULL);
private:
/** @brief 禁止复制保存会话。 */
nmNumericalSaveSession(const nmNumericalSaveSession&);
/** @brief 禁止赋值保存会话。 */
nmNumericalSaveSession& operator=(const nmNumericalSaveSession&);
private:
/** @brief 会话是否已开始。 */
bool m_bActive;
/** @brief 根清单是否已经成功发布。 */
bool m_bCommitted;
/** @brief 回滚清单失败时保留新代次,避免根清单形成悬空引用。 */
bool m_bKeepGenerationOnAbort;
/** @brief 成果业务标识。 */
QString m_sResultId;
/** @brief 成果根目录。 */
QString m_sResultRootDirectory;
/** @brief 当前保存代次 UUID。 */
QString m_sGenerationId;
/** @brief 当前代次的绝对目录。 */
QString m_sGenerationDirectory;
/** @brief 按窗口标识保存的新旧主 JSON 引用。 */
QMap<QString, nmNumericalSavedWindow> m_mapWindows;
/** @brief 本轮已经写入并完成全引用链校验的窗口标识。 */
QSet<QString> m_setValidatedWindowIds;
};
#endif // NMNUMERICALSAVESESSION_H

@ -0,0 +1,54 @@
#ifndef NMPEBIRESULTSNAPSHOTSERIALIZER_H
#define NMPEBIRESULTSNAPSHOTSERIALIZER_H
#include "nmData_global.h"
#include "nmNumericalResultPersistence.h"
#include <QSharedPointer>
#include <QString>
class nmPebiResultSnapshot;
/**
* @brief 负责 v3 快照三文件载荷及 Snapshot.json 的流式保存和加载。
*
* 序列化器是快照的受限友元,只在保存时读取内部 VTK 对象;加载仍通过
* nmPebiResultSnapshotBuilder 构造和封闭候选。
*/
class NM_DATA_EXPORT nmPebiResultSnapshotSerializer
{
public:
/** @brief 将完整快照写入窗口目录下的 Snapshot 子目录。 */
static bool save(
const QSharedPointer<const nmPebiResultSnapshot>& pSnapshot,
const QString& sWindowDirectory,
nmNumericalFileReference& oSnapshotJsonReference,
QString* pError = NULL);
/** @brief 校验 Snapshot.json 及其三条引用,不创建快照对象。 */
static bool validate(
const QString& sWindowDirectory,
const nmNumericalFileReference& oSnapshotJsonReference,
QString* pError = NULL);
/** @brief 完整读取并通过 Builder 返回尚未发布的可写候选。 */
static bool load(
const QString& sWindowDirectory,
const nmNumericalFileReference& oSnapshotJsonReference,
QSharedPointer<nmPebiResultSnapshot>& pCandidate,
QString* pError = NULL);
private:
/** @brief 从快照内部数组流式写出全部压力帧。 */
static bool writePressureFrames(const nmPebiResultSnapshot& oSnapshot,
const QString& sFilePath,
QString* pError);
/** @brief 从快照内部井目录流式写出六组冻结曲线。 */
static bool writeWellCurves(const nmPebiResultSnapshot& oSnapshot,
const QString& sFilePath,
QString* pError);
/** @brief 禁止实例化纯静态序列化器。 */
nmPebiResultSnapshotSerializer();
};
#endif // NMPEBIRESULTSNAPSHOTSERIALIZER_H

@ -18,6 +18,7 @@ class iSubWndFitting;
class nmDataAnalyzeManager;
class nmWxParaPropertyPebi;
class nmSubWndMain;
class nmNumericalSaveSession;
// 本来主要是为数值部分提供SubWnd初始化构造的方法
class NM_SUB_WND_EXPORT nmSubWndUtils : public QObject
@ -108,6 +109,22 @@ public:
QString sRstName, \
const ZxMainWindow* pMainWnd);
/**
* @brief 显式开始一次跨窗口数值成果保存会话。
* @note 外层遍历无论成功、失败或提前退出,都必须 commit 或 abort。
*/
static bool beginNumericalSaveSession(iSubWnd* pFirstSubWnd,
const QString& sRstName,
QString* pError = NULL);
/** @brief 将一个数值分析窗口写入当前保存代次。 */
static bool saveWindowGeneration(iSubWnd* pSubWnd,
const QString& sRstName,
QString* pError = NULL);
/** @brief 校验全部窗口并发布根清单,成功后结束会话。 */
static bool commitNumericalSaveSession(QString* pError = NULL);
/** @brief 中止当前保存会话,清理未发布代次。 */
static void abortNumericalSaveSession();
/// @brief 在成果加载时,辅助信息(如数值解相关)加载
/// @param pSubWnd(in) 基本上指的是 SubWndFitting 窗体
/// @param sRstName(in) 指的是成果的名称
@ -172,6 +189,35 @@ public:
// 外层成果窗口关闭时,其画布已在MDI Close阶段清理,后续子窗口Close不再重复处理
QSet<QObject*> m_closingMdiChildren;
// 保存周期内是否已清空成果目录,确保多窗口保存时只清空一次
bool m_bClearRootDone;
/** @brief 当前显式跨窗口保存会话;析构时自动中止未提交代次。 */
nmNumericalSaveSession* m_pNumericalSaveSession;
};
/**
* @brief 外层跨窗口保存使用的 VS2010 兼容 RAII 中止守卫。
*
* begin 成功后立即创建守卫;commit 成功后调用 release()。其他返回路径
* 会在析构时自动 abort,确保未完成代次不会留给下一轮保存。
*/
class NM_SUB_WND_EXPORT nmNumericalSaveSessionAbortGuard
{
public:
/** @brief 创建仍处于生效状态的中止守卫。 */
nmNumericalSaveSessionAbortGuard();
/** @brief 未解除时中止当前数值保存会话。 */
~nmNumericalSaveSessionAbortGuard();
/** @brief commit 成功后解除自动中止。 */
void release();
private:
/** @brief 禁止复制中止守卫。 */
nmNumericalSaveSessionAbortGuard(
const nmNumericalSaveSessionAbortGuard&);
/** @brief 禁止赋值中止守卫。 */
nmNumericalSaveSessionAbortGuard& operator=(
const nmNumericalSaveSessionAbortGuard&);
private:
/** @brief 析构时是否仍需自动中止。 */
bool m_bAbortRequired;
};

@ -2,6 +2,8 @@
#include "nmAttrRegistry.h"
#include "nmPebiResultSnapshot.h"
#include "nmPebiResultSnapshotSerializer.h"
#include "nmNumericalSaveSession.h"
#include "nmDataAnalyzeContext.h"
#include "nmDataAnalyzeContextProvider.h"
@ -56,6 +58,7 @@
#include <Windows.h>
#include <iostream>
#include <new>
#include <vector>
#include "singlePhaseSolver.h"
@ -504,6 +507,185 @@ void createDefaultLayer(double dThickness, QVector<nmDataLayer*>& vecLayers)
vecLayers.append(pDefaultLayer);
}
rapidjson::Value numericalJsonString(
const QString& sValue,
rapidjson::Document::AllocatorType& oAllocator)
{
const QByteArray baValue = sValue.toUtf8();
return rapidjson::Value(baValue.constData(),
static_cast<rapidjson::SizeType>(baValue.size()), oAllocator);
}
void addNumericalFileReference(
rapidjson::Value& oParent,
const char* pName,
const nmNumericalFileReference& oReference,
rapidjson::Document::AllocatorType& oAllocator)
{
rapidjson::Value oJson(rapidjson::kObjectType);
oJson.AddMember("Path", numericalJsonString(
oReference.m_sRelativePath, oAllocator), oAllocator);
oJson.AddMember("Length", oReference.m_nLength, oAllocator);
oJson.AddMember("Sha1", numericalJsonString(
oReference.m_sSha1, oAllocator), oAllocator);
oParent.AddMember(rapidjson::Value(pName, oAllocator).Move(),
oJson, oAllocator);
}
bool readNumericalFileReference(
const rapidjson::Value& oParent,
const char* pName,
nmNumericalFileReference& oReference)
{
if(!oParent.IsObject() || !oParent.HasMember(pName) ||
!oParent[pName].IsObject())
{
return false;
}
const rapidjson::Value& oJson = oParent[pName];
if(!oJson.HasMember("Path") || !oJson["Path"].IsString() ||
!oJson.HasMember("Length") || !oJson["Length"].IsUint64() ||
!oJson.HasMember("Sha1") || !oJson["Sha1"].IsString())
{
return false;
}
oReference.m_sRelativePath = QString::fromUtf8(oJson["Path"].GetString());
oReference.m_nLength = oJson["Length"].GetUint64();
oReference.m_sSha1 = QString::fromLatin1(oJson["Sha1"].GetString());
return oReference.isValid();
}
bool readV3WindowHeader(
const QString& sMainJsonPath,
nmNumericalWindowPayloadReferences& oReferences,
QString& sCurrentResultWellInstanceId,
quint64& nGridInputRevision,
quint64& nBuiltGridRevision,
quint64& nResultInputRevision,
QString* pError)
{
const QFileInfo oInfo(sMainJsonPath);
if(!oInfo.isFile() || oInfo.size() <= 0 ||
oInfo.size() > 64ll * 1024ll * 1024ll)
{
if(pError != NULL) *pError = "Numerical v3 main JSON is missing or too large.";
return false;
}
rapidjson::Document oDocument;
if(!nmDataJsonTools::ReadDomFromFile(sMainJsonPath, oDocument) ||
!oDocument.IsObject() ||
!oDocument.HasMember("NumericalProjectVersion") ||
!oDocument["NumericalProjectVersion"].IsInt())
{
if(pError != NULL) *pError = "Numerical project version is missing.";
return false;
}
const int nVersion = oDocument["NumericalProjectVersion"].GetInt();
if(nVersion != nmNumericalResultPersistence::projectVersion())
{
if(pError != NULL)
{
*pError = nVersion == 2
? "Numerical project version 2 is not supported."
: "Numerical project version is not supported.";
}
return false;
}
if(!oDocument.HasMember("InputRevisions") ||
!oDocument["InputRevisions"].IsObject() ||
!oDocument.HasMember("CurrentResultWellInstanceId") ||
!oDocument["CurrentResultWellInstanceId"].IsString() ||
!oDocument.HasMember("PayloadFiles") ||
!oDocument["PayloadFiles"].IsObject())
{
if(pError != NULL) *pError = "Numerical v3 main JSON header is incomplete.";
return false;
}
const rapidjson::Value& oRevisions = oDocument["InputRevisions"];
if(!oRevisions.HasMember("GridInputRevision") ||
!oRevisions["GridInputRevision"].IsUint64() ||
!oRevisions.HasMember("BuiltGridRevision") ||
!oRevisions["BuiltGridRevision"].IsUint64() ||
!oRevisions.HasMember("ResultInputRevision") ||
!oRevisions["ResultInputRevision"].IsUint64())
{
if(pError != NULL) *pError = "Numerical input revisions are invalid.";
return false;
}
nGridInputRevision = oRevisions["GridInputRevision"].GetUint64();
nBuiltGridRevision = oRevisions["BuiltGridRevision"].GetUint64();
nResultInputRevision = oRevisions["ResultInputRevision"].GetUint64();
if(nGridInputRevision == 0 || nResultInputRevision == 0 ||
(nBuiltGridRevision != 0 && nBuiltGridRevision != nGridInputRevision))
{
if(pError != NULL) *pError = "Numerical input revision values are invalid.";
return false;
}
sCurrentResultWellInstanceId = QString::fromUtf8(
oDocument["CurrentResultWellInstanceId"].GetString());
const rapidjson::Value& oPayload = oDocument["PayloadFiles"];
if(!oPayload.HasMember("CurrentGrid") ||
!oPayload.HasMember("WellHistories") ||
!oPayload["WellHistories"].IsArray() ||
oPayload["WellHistories"].Size() > 10000u ||
!oPayload.HasMember("Snapshot"))
{
if(pError != NULL) *pError = "Numerical payload reference list is invalid.";
return false;
}
QSet<QString> setPaths;
oReferences = nmNumericalWindowPayloadReferences();
if(!oPayload["CurrentGrid"].IsNull())
{
if(!readNumericalFileReference(oPayload, "CurrentGrid",
oReferences.m_oCurrentGrid))
{
if(pError != NULL) *pError = "Current grid reference is invalid.";
return false;
}
oReferences.m_bHasCurrentGrid = true;
setPaths.insert(oReferences.m_oCurrentGrid.m_sRelativePath);
}
const rapidjson::Value& oHistories = oPayload["WellHistories"];
for(rapidjson::SizeType nIndex = 0; nIndex < oHistories.Size(); ++nIndex)
{
const rapidjson::Value& oJson = oHistories[nIndex];
nmNumericalFileReference oReference;
if(!oJson.IsObject() ||
!oJson.HasMember("WellInstanceId") ||
!oJson["WellInstanceId"].IsString() ||
!readNumericalFileReference(oJson, "File", oReference))
{
if(pError != NULL) *pError = "Well history reference is invalid.";
return false;
}
const QString sWellInstanceId = QString::fromUtf8(
oJson["WellInstanceId"].GetString());
if(sWellInstanceId.isEmpty() ||
oReferences.m_mapWellHistories.contains(sWellInstanceId) ||
setPaths.contains(oReference.m_sRelativePath))
{
if(pError != NULL) *pError = "Well history references are duplicated.";
return false;
}
oReferences.m_mapWellHistories.insert(sWellInstanceId, oReference);
setPaths.insert(oReference.m_sRelativePath);
}
if(!oPayload["Snapshot"].IsNull())
{
if(!readNumericalFileReference(oPayload, "Snapshot",
oReferences.m_oSnapshot) ||
setPaths.contains(oReferences.m_oSnapshot.m_sRelativePath))
{
if(pError != NULL) *pError = "Snapshot reference is invalid or duplicated.";
return false;
}
oReferences.m_bHasSnapshot = true;
}
return true;
}
}
ZX_DEFINE_DYNAMIC(DataAnalyzeManager, nmDataAnalyzeManager)
@ -4456,7 +4638,7 @@ bool nmDataAnalyzeManager::ReadProjectData(const QString & filePath)
// 新数据模型不兼容旧项目。明确校验版本,避免按井名或对象顺序猜测关联关系。
const int nSupportedProjectVersion = 2;
const int nSupportedProjectVersion = 3;
if(!doc.HasMember("NumericalProjectVersion") ||
!doc["NumericalProjectVersion"].IsInt() ||
doc["NumericalProjectVersion"].GetInt() != nSupportedProjectVersion) {
@ -4464,6 +4646,39 @@ bool nmDataAnalyzeManager::ReadProjectData(const QString & filePath)
return false;
}
quint64 nSavedGridInputRevision = 0;
quint64 nSavedBuiltGridRevision = 0;
quint64 nSavedResultInputRevision = 0;
if(!doc.HasMember("InputRevisions") ||
!doc["InputRevisions"].IsObject()) {
qWarning() << "Numerical v3 project has no input revisions:" << filePath;
return false;
}
const rapidjson::Value& oRevisionJson = doc["InputRevisions"];
if(!oRevisionJson.HasMember("GridInputRevision") ||
!oRevisionJson["GridInputRevision"].IsUint64() ||
!oRevisionJson.HasMember("BuiltGridRevision") ||
!oRevisionJson["BuiltGridRevision"].IsUint64() ||
!oRevisionJson.HasMember("ResultInputRevision") ||
!oRevisionJson["ResultInputRevision"].IsUint64()) {
qWarning() << "Numerical v3 project contains invalid input revisions:"
<< filePath;
return false;
}
nSavedGridInputRevision =
oRevisionJson["GridInputRevision"].GetUint64();
nSavedBuiltGridRevision =
oRevisionJson["BuiltGridRevision"].GetUint64();
nSavedResultInputRevision =
oRevisionJson["ResultInputRevision"].GetUint64();
if(nSavedGridInputRevision == 0 || nSavedResultInputRevision == 0 ||
(nSavedBuiltGridRevision != 0 &&
nSavedBuiltGridRevision != nSavedGridInputRevision)) {
qWarning() << "Numerical v3 project input revision values are invalid:"
<< filePath;
return false;
}
QString sSavedPrimaryWellCode;
QString sSavedCurrentResultWellCode;
NM_CASE_WELL_MODE eSavedPrimaryWellMode = NM_CaseWell_Observation;
@ -4819,9 +5034,8 @@ bool nmDataAnalyzeManager::ReadProjectData(const QString & filePath)
return false;
}
// 前置校验已完成,从这里开始替换当前项目;旧项目快照不能跨项目残留。
clearPebiResultSnapshot();
// 前置校验已完成,从这里开始替换当前输入。旧快照要到全部 v3 载荷
// 成功后才替换,加载失败或内存不足时仍保留上一套已发布快照。
// 清空现有数据,确保从头加载新数据
foreach(nmDataFracture* pFractureData, m_vFractureData) {
delete pFractureData; // 释放堆上分配的 nmDataFracture 对象
@ -5238,13 +5452,27 @@ bool nmDataAnalyzeManager::ReadProjectData(const QString & filePath)
if(doc.HasMember("PebiIluReuseSteps") && doc["PebiIluReuseSteps"].IsInt()) {
setPebiIluReuseSteps(doc["PebiIluReuseSteps"].GetInt());
}
if(!m_oNumericalAnalysisCase.restoreInputRevisions(
nSavedGridInputRevision,
nSavedBuiltGridRevision,
nSavedResultInputRevision)) {
qWarning() << "Failed to restore numerical v3 input revisions:"
<< filePath;
return false;
}
return true;
}
// 将 C++ 对象数据写入 JSON 文件
bool nmDataAnalyzeManager::WriteProjectData(const QString & filePath)
bool nmDataAnalyzeManager::WriteProjectData(
const QString & filePath,
const nmNumericalWindowPayloadReferences* pPayloadReferences)
{
if(pPayloadReferences == NULL) {
qWarning() << "Numerical v3 project requires explicit payload references.";
return false;
}
// 第一步:保存前校验 Map 井目录,持久化身份只允许非空且唯一的 WellCode。
QSet<QString> setWellCodes;
QMap<QString, NM_WELL_MODEL> mapWellTypes;
@ -5260,7 +5488,9 @@ bool nmDataAnalyzeManager::WriteProjectData(const QString & filePath)
}
const QString sPrimaryWellCode = getPrimaryWellCode();
const QString sCurrentResultWellCode = getCurrentResultWellCode();
const QString sCurrentResultWellCode =
setWellCodes.contains(getCurrentResultWellCode())
? getCurrentResultWellCode() : sPrimaryWellCode;
if(!setWellCodes.contains(sPrimaryWellCode) ||
!setWellCodes.contains(sCurrentResultWellCode) ||
!qIsFinite(getPebiGridControl()) ||
@ -5321,7 +5551,8 @@ bool nmDataAnalyzeManager::WriteProjectData(const QString & filePath)
// 最后结果使用独立井顺序,不要求继续属于当前有效计算井,也不要求井型
// 仍与当前模型一致;但对应 WellCode 必须仍存在,才能保存单井曲线数据。
const bool bHasResults = m_oNumericalAnalysisCase.hasResults();
// v3 的最后结果只由独立快照表达,旧 AnalysisCase 结果字段写成空适配值。
const bool bHasResults = false;
QVector<nmSolverWellRef> vecValidatedResultOrder;
if(bHasResults) {
vecValidatedResultOrder =
@ -5395,8 +5626,17 @@ bool nmDataAnalyzeManager::WriteProjectData(const QString & filePath)
doc.SetObject(); // 根节点是对象
rapidjson::Document::AllocatorType& allocator = doc.GetAllocator(); // 获取内存分配器
// 新的数据模型从版本2开始只使用 WellCode 建立跨模块关联。
doc.AddMember("NumericalProjectVersion", 2, allocator);
doc.AddMember("NumericalProjectVersion", 3, allocator);
rapidjson::Value oRevisionJson(rapidjson::kObjectType);
oRevisionJson.AddMember("GridInputRevision",
m_oNumericalAnalysisCase.getGridInputRevision(), allocator);
oRevisionJson.AddMember("BuiltGridRevision",
m_oNumericalAnalysisCase.getBuiltGridRevision(), allocator);
oRevisionJson.AddMember("ResultInputRevision",
m_oNumericalAnalysisCase.getResultInputRevision(), allocator);
doc.AddMember("InputRevisions", oRevisionJson, allocator);
doc.AddMember("CurrentResultWellInstanceId", numericalJsonString(
m_sCurrentResultWellInstanceId, allocator), allocator);
// 构建 "Fractures" 数组的 JSON Value
rapidjson::Value fracturesJsonArray(rapidjson::kArrayType);
@ -5648,9 +5888,9 @@ bool nmDataAnalyzeManager::WriteProjectData(const QString & filePath)
vecSolverOrderJson.PushBack(oOrderJson, allocator);
}
oCaseJson.AddMember("SolverWellOrder", vecSolverOrderJson, allocator);
oCaseJson.AddMember("ResultsAvailable", bHasResults, allocator);
oCaseJson.AddMember("ResultsCurrent",
m_oNumericalAnalysisCase.areResultsCurrent(), allocator);
// v3 的结果状态只由独立快照及输入版本判断,旧字段必须保持一致的空状态。
oCaseJson.AddMember("ResultsAvailable", false, allocator);
oCaseJson.AddMember("ResultsCurrent", false, allocator);
rapidjson::Value vecResultOrderJson(rapidjson::kArrayType);
for(int nIndex = 0;
@ -5699,6 +5939,37 @@ bool nmDataAnalyzeManager::WriteProjectData(const QString & filePath)
doc.AddMember("PebiOmpThreads", m_nPebiOmpThreads, allocator);
doc.AddMember("PebiIluReuseSteps", m_nPebiIluReuseSteps, allocator);
// 主 JSON 只保存引用,不通过目录扫描推断网格、历史或快照载荷。
rapidjson::Value oPayloadJson(rapidjson::kObjectType);
if(pPayloadReferences->m_bHasCurrentGrid) {
addNumericalFileReference(oPayloadJson, "CurrentGrid",
pPayloadReferences->m_oCurrentGrid, allocator);
} else {
oPayloadJson.AddMember("CurrentGrid",
rapidjson::Value(rapidjson::kNullType).Move(), allocator);
}
rapidjson::Value oHistoryJson(rapidjson::kArrayType);
QMap<QString, nmNumericalFileReference>::const_iterator oHistoryIt =
pPayloadReferences->m_mapWellHistories.constBegin();
for(; oHistoryIt != pPayloadReferences->m_mapWellHistories.constEnd();
++oHistoryIt) {
rapidjson::Value oWellJson(rapidjson::kObjectType);
oWellJson.AddMember("WellInstanceId", numericalJsonString(
oHistoryIt.key(), allocator), allocator);
addNumericalFileReference(oWellJson, "File",
oHistoryIt.value(), allocator);
oHistoryJson.PushBack(oWellJson, allocator);
}
oPayloadJson.AddMember("WellHistories", oHistoryJson, allocator);
if(pPayloadReferences->m_bHasSnapshot) {
addNumericalFileReference(oPayloadJson, "Snapshot",
pPayloadReferences->m_oSnapshot, allocator);
} else {
oPayloadJson.AddMember("Snapshot",
rapidjson::Value(rapidjson::kNullType).Move(), allocator);
}
doc.AddMember("PayloadFiles", oPayloadJson, allocator);
// 将最终构建好的 Document 写入文件
if(!nmDataJsonTools::WriteDomToFile(doc, filePath)) {
qDebug() << "Error: Failed to write DOM to file:" << filePath;
@ -5708,6 +5979,181 @@ bool nmDataAnalyzeManager::WriteProjectData(const QString & filePath)
return true;
}
bool nmDataAnalyzeManager::saveNmResultV3(
const QString& sWindowDirectory,
nmNumericalFileReference& oMainJsonReference,
QString* pError)
{
if(pError != NULL) {
pError->clear();
}
oMainJsonReference = nmNumericalFileReference();
try {
if(sWindowDirectory.isEmpty() ||
!ensureDirectoryExists(sWindowDirectory)) {
if(pError != NULL) *pError = "Cannot create numerical v3 window directory.";
return false;
}
nmNumericalWindowPayloadReferences oReferences;
if(isPebiGridValid()) {
if(m_pVtkUnstructuredGrid == NULL ||
!ensureDirectoryExists(QDir(sWindowDirectory).filePath("Grid"))) {
if(pError != NULL) *pError = "Current PEBI grid is unavailable.";
return false;
}
const QString sCurrentGridPath = QDir(sWindowDirectory).filePath(
"Grid/CurrentGrid.vtu");
if(!nmNumericalResultPersistence::writeGrid(
m_pVtkUnstructuredGrid, sCurrentGridPath, pError) ||
!nmNumericalResultPersistence::buildFileReference(
sCurrentGridPath, "Grid/CurrentGrid.vtu",
oReferences.m_oCurrentGrid)) {
return false;
}
oReferences.m_bHasCurrentGrid = true;
}
const QString sHistoryDirectory = QDir(sWindowDirectory).filePath(
"WellHistory");
if(!ensureDirectoryExists(sHistoryDirectory)) {
if(pError != NULL) *pError = "Cannot create v3 well history directory.";
return false;
}
QSet<QString> setWellInstanceIds;
for(int nIndex = 0; nIndex < m_vWellData.size(); ++nIndex) {
nmDataWellBase* pWell = m_vWellData[nIndex];
if(pWell == NULL || pWell->getWellInstanceId().isEmpty() ||
setWellInstanceIds.contains(pWell->getWellInstanceId())) {
if(pError != NULL) *pError = "Live well UUID directory is invalid.";
return false;
}
setWellInstanceIds.insert(pWell->getWellInstanceId());
nmNumericalWellHistoryData oHistory;
oHistory.m_vecPressure = pWell->getHistoryPressure();
oHistory.m_vecLogLog = pWell->getHistoryLogLog();
oHistory.m_vecSemiLog = pWell->getHistorySemiLog();
const QString sRelativePath = QString("WellHistory/%1.bin")
.arg(pWell->getWellInstanceId());
const QString sHistoryPath = QDir(sWindowDirectory).filePath(
sRelativePath);
nmNumericalFileReference oReference;
if(!nmNumericalResultPersistence::writeWellHistory(
sHistoryPath, oHistory, pError) ||
!nmNumericalResultPersistence::buildFileReference(
sHistoryPath, sRelativePath, oReference)) {
return false;
}
oReferences.m_mapWellHistories.insert(
pWell->getWellInstanceId(), oReference);
}
if(!m_pPebiResultSnapshot.isNull()) {
if(!nmPebiResultSnapshotSerializer::save(
m_pPebiResultSnapshot, sWindowDirectory,
oReferences.m_oSnapshot, pError)) {
return false;
}
oReferences.m_bHasSnapshot = true;
}
// 所有外部载荷成功后才写主 JSON,使引用链不会指向半成品文件。
const QString sMainJsonPath = QDir(sWindowDirectory).filePath(
"Numerical_Parameters.json");
if(!WriteProjectData(sMainJsonPath, &oReferences) ||
!nmNumericalResultPersistence::buildFileReference(
sMainJsonPath, "Numerical_Parameters.json",
oMainJsonReference)) {
if(pError != NULL && pError->isEmpty())
*pError = "Cannot write numerical v3 main JSON.";
return false;
}
// 返回保存会话前沿主 JSON 的明确引用完整复核本窗口载荷。
return validateNmResultV3Window(
sWindowDirectory, sMainJsonPath, pError);
}
catch(const std::bad_alloc&) {
if(pError != NULL) *pError = "Not enough memory to save numerical v3 result.";
return false;
}
}
bool nmDataAnalyzeManager::validateNmResultV3Window(
const QString& sWindowDirectory,
const QString& sMainJsonPath,
QString* pError)
{
if(pError != NULL) {
pError->clear();
}
try {
const QString sExpectedDirectory = QDir::cleanPath(
QFileInfo(sWindowDirectory).absoluteFilePath());
const QFileInfo oMainInfo(sMainJsonPath);
if(!oMainInfo.isFile() ||
QDir::cleanPath(oMainInfo.absolutePath()).compare(
sExpectedDirectory, Qt::CaseInsensitive) != 0) {
if(pError != NULL)
*pError = "Numerical v3 main JSON leaves its window directory.";
return false;
}
nmNumericalWindowPayloadReferences oReferences;
QString sCurrentResultWellInstanceId;
quint64 nGridInputRevision = 0;
quint64 nBuiltGridRevision = 0;
quint64 nResultInputRevision = 0;
if(!readV3WindowHeader(sMainJsonPath, oReferences,
sCurrentResultWellInstanceId, nGridInputRevision,
nBuiltGridRevision, nResultInputRevision, pError)) {
return false;
}
Q_UNUSED(nGridInputRevision);
Q_UNUSED(nBuiltGridRevision);
Q_UNUSED(nResultInputRevision);
if(!oReferences.m_bHasSnapshot &&
!sCurrentResultWellInstanceId.isEmpty()) {
if(pError != NULL)
*pError = "Numerical v3 result well is selected without a snapshot.";
return false;
}
if(oReferences.m_bHasCurrentGrid &&
!nmNumericalResultPersistence::validateFileReference(
sWindowDirectory, oReferences.m_oCurrentGrid,
NULL, pError)) {
return false;
}
QMap<QString, nmNumericalFileReference>::const_iterator oIt =
oReferences.m_mapWellHistories.constBegin();
for(; oIt != oReferences.m_mapWellHistories.constEnd(); ++oIt) {
QString sHistoryPath;
nmNumericalWellHistoryData oValidatedHistory;
if(!nmNumericalResultPersistence::validateFileReference(
sWindowDirectory, oIt.value(), &sHistoryPath, pError) ||
!nmNumericalResultPersistence::readWellHistory(
sHistoryPath, oValidatedHistory, pError)) {
return false;
}
}
if(oReferences.m_bHasSnapshot &&
!nmPebiResultSnapshotSerializer::validate(
sWindowDirectory, oReferences.m_oSnapshot, pError)) {
return false;
}
return true;
}
catch(const std::bad_alloc&) {
if(pError != NULL)
*pError = "Not enough memory to validate numerical v3 result.";
return false;
}
}
bool nmDataAnalyzeManager::saveNmResult(QString sRstCode, iSubWndFitting* pSubWndF, bool bClearRoot)
{
Q_ASSERT(nullptr != pSubWndF);
@ -5719,6 +6165,23 @@ bool nmDataAnalyzeManager::saveNmResult(QString sRstCode, iSubWndFitting* pSubWn
return false;
}
Q_UNUSED(bClearRoot);
// 旧入口按单窗口兼容会话执行;显式跨窗口会话由 nmSubWndUtils 统一持有。
nmNumericalSaveSession oCompatibilitySession;
const QFileInfo oLogicalWindowInfo(QDir::cleanPath(sDir));
QString sError;
if(!oCompatibilitySession.begin(
oLogicalWindowInfo.dir().absolutePath(), sRstCode,
true, &sError) ||
!oCompatibilitySession.saveWindowGeneration(
oLogicalWindowInfo.fileName(), this, &sError) ||
!oCompatibilitySession.commit(&sError)) {
qWarning() << sError;
return false;
}
return true;
#if 0
// bClearRoot为true时清空整个成果目录,清理已删除窗口的残留数据。
// 仅在遍历保存的第一个窗口传入true,后续窗口传false避免误删其他窗口数据。
if(bClearRoot) {
@ -5852,10 +6315,195 @@ bool nmDataAnalyzeManager::saveNmResult(QString sRstCode, iSubWndFitting* pSubWn
}
return true;
#endif
}
bool nmDataAnalyzeManager::loadNmResult(QString sLoadAnalDir)
{
try {
// 外部框架仍传入旧的“成果根/窗口标识”逻辑路径;v3 只从根清单解析真实代次。
const QFileInfo oLogicalWindowInfo(QDir::cleanPath(sLoadAnalDir));
const QString sWindowId = oLogicalWindowInfo.fileName();
const QString sResultRootDirectory = oLogicalWindowInfo.dir().absolutePath();
const QString sManifestPath = QDir(sResultRootDirectory).filePath(
"NumericalSaveManifest.json");
if(!QFileInfo(sManifestPath).isFile()) {
const QString sLegacyJsonPath = QDir(sLoadAnalDir).filePath(
"Results/Numerical_Parameters.json");
if(QFileInfo(sLegacyJsonPath).isFile()) {
qWarning() << "Numerical project version 2 is not supported:"
<< sLegacyJsonPath;
} else {
qWarning() << "Numerical v3 root manifest is missing:"
<< sManifestPath;
}
return false;
}
QString sWindowDirectory;
QString sMainJsonPath;
QString sError;
if(!nmNumericalSaveSession::resolveWindowMainJson(
sResultRootDirectory, sWindowId, sWindowDirectory,
sMainJsonPath, NULL, &sError)) {
qWarning() << sError;
return false;
}
nmNumericalWindowPayloadReferences oReferences;
QString sSavedResultWellInstanceId;
quint64 nGridInputRevision = 0;
quint64 nBuiltGridRevision = 0;
quint64 nResultInputRevision = 0;
if(!readV3WindowHeader(sMainJsonPath, oReferences,
sSavedResultWellInstanceId, nGridInputRevision,
nBuiltGridRevision, nResultInputRevision, &sError)) {
qWarning() << sError << sMainJsonPath;
return false;
}
// 所有引用文件先完成哈希和结构读取,任何失败都不能替换已发布快照。
vtkSmartPointer<vtkUnstructuredGrid> pLoadedCurrentGrid;
if(oReferences.m_bHasCurrentGrid) {
QString sCurrentGridPath;
if(!nmNumericalResultPersistence::validateFileReference(
sWindowDirectory, oReferences.m_oCurrentGrid,
&sCurrentGridPath, &sError) ||
!nmNumericalResultPersistence::readGrid(
sCurrentGridPath, pLoadedCurrentGrid, &sError)) {
qWarning() << sError;
return false;
}
}
QMap<QString, nmNumericalWellHistoryData> mapLoadedHistories;
QMap<QString, nmNumericalFileReference>::const_iterator oHistoryIt =
oReferences.m_mapWellHistories.constBegin();
for(; oHistoryIt != oReferences.m_mapWellHistories.constEnd();
++oHistoryIt) {
QString sHistoryPath;
nmNumericalWellHistoryData oHistory;
if(!nmNumericalResultPersistence::validateFileReference(
sWindowDirectory, oHistoryIt.value(),
&sHistoryPath, &sError) ||
!nmNumericalResultPersistence::readWellHistory(
sHistoryPath, oHistory, &sError)) {
qWarning() << sError;
return false;
}
mapLoadedHistories.insert(oHistoryIt.key(), oHistory);
}
QSharedPointer<nmPebiResultSnapshot> pLoadedCandidate;
if(oReferences.m_bHasSnapshot &&
!nmPebiResultSnapshotSerializer::load(
sWindowDirectory, oReferences.m_oSnapshot,
pLoadedCandidate, &sError)) {
qWarning() << sError;
return false;
}
// 主 JSON 在外部载荷全部可用后才恢复当前输入;v2 会在版本检查处直接拒绝。
if(!ReadProjectData(sMainJsonPath)) {
return false;
}
if(m_oNumericalAnalysisCase.getGridInputRevision() !=
nGridInputRevision ||
m_oNumericalAnalysisCase.getBuiltGridRevision() !=
nBuiltGridRevision ||
m_oNumericalAnalysisCase.getResultInputRevision() !=
nResultInputRevision ||
oReferences.m_bHasCurrentGrid !=
m_oNumericalAnalysisCase.isGridValid()) {
qWarning() << "Loaded numerical input revisions and current grid are inconsistent.";
return false;
}
// 实时井历史按 UUID 一一匹配;井名、井编码和数组顺序都不能替代身份。
if(mapLoadedHistories.size() != m_vWellData.size()) {
qWarning() << "Loaded numerical well history directory is incomplete.";
return false;
}
for(int nIndex = 0; nIndex < m_vWellData.size(); ++nIndex) {
nmDataWellBase* pWell = m_vWellData[nIndex];
if(pWell == NULL ||
!mapLoadedHistories.contains(pWell->getWellInstanceId())) {
qWarning() << "Loaded numerical well UUID has no history payload.";
return false;
}
const nmNumericalWellHistoryData oHistory =
mapLoadedHistories.take(pWell->getWellInstanceId());
pWell->setHistoryPressure(oHistory.m_vecPressure);
pWell->setHistoryLogLog(oHistory.m_vecLogLog);
pWell->setHistorySemiLog(oHistory.m_vecSemiLog);
}
if(!mapLoadedHistories.isEmpty()) {
qWarning() << "Numerical v3 project contains unreferenced well histories.";
return false;
}
loadWellPreAndFlow();
const QVector<nmCalculationWellRef> vecIncludedWells =
getIncludedCalculationWells();
for(int nIndex = 0; nIndex < vecIncludedWells.size(); ++nIndex) {
nmDataWellBase* pWell = findWellByCode(
vecIncludedWells[nIndex].m_sWellCode);
if(!isSupportedNumericalWell(pWell) ||
pWell->getFlowPoints().size() < 2) {
qWarning() << "Failed to restore included numerical well:"
<< vecIncludedWells[nIndex].m_sWellCode;
return false;
}
}
if(!pLoadedCandidate.isNull() &&
!sSavedResultWellInstanceId.isEmpty() &&
!pLoadedCandidate->isDisplayWell(sSavedResultWellInstanceId)) {
qWarning() << "Saved result well UUID is absent from the PEBI snapshot.";
return false;
}
if(pLoadedCandidate.isNull() &&
!sSavedResultWellInstanceId.isEmpty()) {
qWarning() << "Numerical project selects a result well without a snapshot.";
return false;
}
// 所有可能失败的读取和映射已完成,再一次替换当前网格与规范快照。
m_pVtkUnstructuredGrid = pLoadedCurrentGrid;
m_mapTimeStepDataP.clear();
m_mapWellLocations.clear();
m_pResultBaseGrid = NULL;
m_dScalarRangeP[0] = DBL_MAX;
m_dScalarRangeP[1] = -DBL_MAX;
if(pLoadedCandidate.isNull()) {
clearPebiResultSnapshot();
} else {
QSharedPointer<const nmPebiResultSnapshot> pPublished(
pLoadedCandidate);
QString sNextWellInstanceId = sSavedResultWellInstanceId;
if(sNextWellInstanceId.isEmpty()) {
const QStringList& listDisplayIds =
pPublished->getDisplayWellInstanceIds();
sNextWellInstanceId = listDisplayIds.isEmpty()
? QString() : listDisplayIds.first();
}
m_pPebiResultSnapshot = pPublished;
m_sCurrentResultWellInstanceId = sNextWellInstanceId;
pLoadedCandidate.clear();
rebindPebiResultSnapshotToWells();
emit sigPebiResultSnapshotChanged();
}
m_bIsLoadData = m_pVtkUnstructuredGrid != NULL ||
!m_pPebiResultSnapshot.isNull();
return true;
}
catch(const std::bad_alloc&) {
qWarning() << "Not enough memory to load numerical v3 result.";
return false;
}
#if 0
// 将Json文件内容读取出来
QString sResultPath = sLoadAnalDir + "/Results/Numerical_Parameters.json";
if(!this->ReadProjectData(sResultPath)) {
@ -6063,6 +6711,7 @@ bool nmDataAnalyzeManager::loadNmResult(QString sLoadAnalDir)
m_bIsLoadData = true;
return true;
#endif
}
bool nmDataAnalyzeManager::ensureDirectoryExists(const QString & dirPath)

@ -474,6 +474,26 @@ quint64 nmDataNumericalAnalysisCase::getResultInputRevision() const
return m_nResultInputRevision;
}
bool nmDataNumericalAnalysisCase::restoreInputRevisions(
quint64 nGridInputRevision,
quint64 nBuiltGridRevision,
quint64 nResultInputRevision)
{
if(nGridInputRevision == 0 || nResultInputRevision == 0 ||
(nBuiltGridRevision != 0 &&
nBuiltGridRevision != nGridInputRevision))
{
return false;
}
// v3 保存的是输入代次本身,加载期间 setter 产生的临时递增不能带入结果判断。
m_nGridInputRevision = nGridInputRevision;
m_nBuiltGridRevision = nBuiltGridRevision;
m_nResultInputRevision = nResultInputRevision;
m_bResultsValid = false;
return true;
}
// 项目重新初始化时恢复完整默认状态,不保留上一成果的井关联或有效标记。
void nmDataNumericalAnalysisCase::clear()
{

@ -0,0 +1,520 @@
#include "nmNumericalResultPersistence.h"
#include <QCryptographicHash>
#include <QDataStream>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QtGlobal>
#include <float.h>
#include <new>
#include <vtkNew.h>
#include <vtkUnstructuredGrid.h>
#include <vtkXMLUnstructuredGridReader.h>
#include <vtkXMLUnstructuredGridWriter.h>
namespace {
const char g_aWellHistoryMagic[8] = { 'N', 'M', 'W', 'H', 'I', 'S', '3', 0 };
const quint32 g_nWellHistoryFormatVersion = 1;
const quint32 g_nEndianMarker = 0x01020304u;
const quint32 g_nMaximumCurveSeries = 64u;
const quint64 g_nMaximumCurvePoints = 50000000ull;
const qint64 g_nStreamChunkBytes = 4 * 1024 * 1024;
bool setError(QString* pError, const QString& sError)
{
if(pError != NULL)
{
*pError = sError;
}
return false;
}
bool writeAll(QFile& oFile, const char* pData, quint64 nBytes)
{
quint64 nWritten = 0;
while(nWritten < nBytes)
{
const qint64 nChunk = static_cast<qint64>(qMin(
static_cast<quint64>(g_nStreamChunkBytes),
nBytes - nWritten));
const qint64 nResult = oFile.write(pData + nWritten, nChunk);
if(nResult != nChunk)
{
return false;
}
nWritten += static_cast<quint64>(nResult);
}
return true;
}
bool readAll(QFile& oFile, char* pData, quint64 nBytes)
{
quint64 nRead = 0;
while(nRead < nBytes)
{
const qint64 nChunk = static_cast<qint64>(qMin(
static_cast<quint64>(g_nStreamChunkBytes),
nBytes - nRead));
const qint64 nResult = oFile.read(pData + nRead, nChunk);
if(nResult != nChunk)
{
return false;
}
nRead += static_cast<quint64>(nResult);
}
return true;
}
template<typename T>
bool writePod(QFile& oFile, const T& oValue)
{
return writeAll(oFile, reinterpret_cast<const char*>(&oValue),
static_cast<quint64>(sizeof(T)));
}
template<typename T>
bool readPod(QFile& oFile, T& oValue)
{
return readAll(oFile, reinterpret_cast<char*>(&oValue),
static_cast<quint64>(sizeof(T)));
}
bool safeMultiply(quint64 nLeft, quint64 nRight, quint64& nProduct)
{
if(nLeft != 0 && nRight > (~static_cast<quint64>(0)) / nLeft)
{
return false;
}
nProduct = nLeft * nRight;
return true;
}
bool writeCurve(QFile& oFile, const QVector<QVector<double> >& vecCurve)
{
const quint32 nSeriesCount = static_cast<quint32>(vecCurve.size());
if(!writePod(oFile, nSeriesCount))
{
return false;
}
for(int nSeries = 0; nSeries < vecCurve.size(); ++nSeries)
{
const QVector<double>& vecValues = vecCurve[nSeries];
const quint64 nPointCount = static_cast<quint64>(vecValues.size());
quint64 nBytes = 0;
if(!safeMultiply(nPointCount, sizeof(double), nBytes) ||
!writePod(oFile, nPointCount) ||
(nBytes > 0 && !writeAll(oFile,
reinterpret_cast<const char*>(vecValues.constData()),
nBytes)))
{
return false;
}
}
return true;
}
bool readCurve(QFile& oFile,
QVector<QVector<double> >& vecCurve,
quint64& nTotalPointCount)
{
quint32 nSeriesCount = 0;
if(!readPod(oFile, nSeriesCount) || nSeriesCount > g_nMaximumCurveSeries)
{
return false;
}
QVector<QVector<double> > vecLoaded;
vecLoaded.resize(static_cast<int>(nSeriesCount));
for(quint32 nSeries = 0; nSeries < nSeriesCount; ++nSeries)
{
quint64 nPointCount = 0;
quint64 nBytes = 0;
if(!readPod(oFile, nPointCount) ||
nPointCount > g_nMaximumCurvePoints ||
nTotalPointCount > g_nMaximumCurvePoints - nPointCount ||
!safeMultiply(nPointCount, sizeof(double), nBytes) ||
nBytes > static_cast<quint64>(oFile.bytesAvailable()) ||
nPointCount > static_cast<quint64>(INT_MAX))
{
return false;
}
nTotalPointCount += nPointCount;
vecLoaded[static_cast<int>(nSeries)].resize(
static_cast<int>(nPointCount));
if(nBytes > 0 && !readAll(oFile,
reinterpret_cast<char*>(
vecLoaded[static_cast<int>(nSeries)].data()), nBytes))
{
return false;
}
}
vecCurve.swap(vecLoaded);
return true;
}
bool hasExactMagic(const char* pActual, const char* pExpected, int nSize)
{
for(int nIndex = 0; nIndex < nSize; ++nIndex)
{
if(pActual[nIndex] != pExpected[nIndex])
{
return false;
}
}
return true;
}
}
nmNumericalFileReference::nmNumericalFileReference()
: m_nLength(0)
{
}
bool nmNumericalFileReference::isValid() const
{
QString sNormalizedPath;
if(!nmNumericalResultPersistence::normalizeRelativePath(
m_sRelativePath, sNormalizedPath) ||
sNormalizedPath != m_sRelativePath || m_sSha1.size() != 40)
{
return false;
}
for(int nIndex = 0; nIndex < m_sSha1.size(); ++nIndex)
{
const QChar oChar = m_sSha1[nIndex];
if(!((oChar >= '0' && oChar <= '9') ||
(oChar >= 'a' && oChar <= 'f')))
{
return false;
}
}
return true;
}
nmNumericalWindowPayloadReferences::nmNumericalWindowPayloadReferences()
: m_bHasCurrentGrid(false),
m_bHasSnapshot(false)
{
}
int nmNumericalResultPersistence::projectVersion()
{
return 3;
}
quint64 nmNumericalResultPersistence::maximumBinaryPayloadBytes()
{
return 512ull * 1024ull * 1024ull;
}
bool nmNumericalResultPersistence::normalizeRelativePath(
const QString& sPath,
QString& sNormalizedPath)
{
sNormalizedPath.clear();
if(sPath.isEmpty() || QDir::isAbsolutePath(sPath) ||
sPath.contains(':'))
{
return false;
}
QString sForwardPath = sPath;
sForwardPath.replace('\\', '/');
const QStringList listParts = sForwardPath.split(
'/', QString::KeepEmptyParts);
if(listParts.isEmpty())
{
return false;
}
for(int nIndex = 0; nIndex < listParts.size(); ++nIndex)
{
if(listParts[nIndex].isEmpty() || listParts[nIndex] == "." ||
listParts[nIndex] == "..")
{
return false;
}
}
sNormalizedPath = listParts.join("/");
return !sNormalizedPath.isEmpty();
}
bool nmNumericalResultPersistence::resolveReferencedPath(
const QString& sRootDirectory,
const QString& sRelativePath,
QString& sAbsolutePath)
{
QString sBaseCanonical;
QString sFileCanonical;
sAbsolutePath.clear();
QString sNormalizedPath;
if(!normalizeRelativePath(sRelativePath, sNormalizedPath))
{
return false;
}
QString sRoot = QDir::cleanPath(QFileInfo(sRootDirectory).absoluteFilePath());
QString sTarget = QDir::cleanPath(
QDir(sRoot).absoluteFilePath(sNormalizedPath));
sRoot.replace('\\', '/');
sTarget.replace('\\', '/');
const QString sRootPrefix = sRoot.endsWith('/') ? sRoot : sRoot + "/";
if(!sTarget.startsWith(sRootPrefix, Qt::CaseInsensitive))
{
return false;
}
// 已存在文件再核对规范路径,防止目录联接或符号链接逃逸成果根目录。
sBaseCanonical = QFileInfo(sRoot).canonicalFilePath();
sFileCanonical = QFileInfo(sTarget).canonicalFilePath();
if(!sBaseCanonical.isEmpty() && !sFileCanonical.isEmpty())
{
QString sCanonicalPrefix = QDir::fromNativeSeparators(sBaseCanonical);
if(!sCanonicalPrefix.endsWith('/'))
{
sCanonicalPrefix += "/";
}
if(!QDir::fromNativeSeparators(sFileCanonical).startsWith(
sCanonicalPrefix, Qt::CaseInsensitive))
{
return false;
}
}
sAbsolutePath = QDir::toNativeSeparators(sTarget);
return true;
}
bool nmNumericalResultPersistence::buildFileReference(
const QString& sAbsolutePath,
const QString& sRelativePath,
nmNumericalFileReference& oReference)
{
QString sNormalizedPath;
if(!normalizeRelativePath(sRelativePath, sNormalizedPath))
{
return false;
}
QFile oFile(sAbsolutePath);
if(!oFile.open(QIODevice::ReadOnly))
{
return false;
}
QCryptographicHash oHash(QCryptographicHash::Sha1);
while(!oFile.atEnd())
{
const QByteArray baChunk = oFile.read(g_nStreamChunkBytes);
if(baChunk.isEmpty() && oFile.error() != QFile::NoError)
{
oFile.close();
return false;
}
oHash.addData(baChunk);
}
const qint64 nSize = oFile.size();
oFile.close();
if(nSize < 0)
{
return false;
}
oReference.m_sRelativePath = sNormalizedPath;
oReference.m_nLength = static_cast<quint64>(nSize);
oReference.m_sSha1 = QString::fromLatin1(oHash.result().toHex());
return oReference.isValid();
}
bool nmNumericalResultPersistence::validateFileReference(
const QString& sRootDirectory,
const nmNumericalFileReference& oReference,
QString* pAbsolutePath,
QString* pError)
{
if(pError != NULL)
{
pError->clear();
}
if(!oReference.isValid())
{
return setError(pError, "Numerical file reference is invalid.");
}
QString sFilePath;
if(!resolveReferencedPath(sRootDirectory,
oReference.m_sRelativePath, sFilePath))
{
return setError(pError, "Numerical file reference leaves its root directory.");
}
const QFileInfo oInfo(sFilePath);
if(!oInfo.exists() || !oInfo.isFile() || oInfo.size() < 0 ||
static_cast<quint64>(oInfo.size()) != oReference.m_nLength)
{
return setError(pError, "Numerical file length does not match its manifest.");
}
nmNumericalFileReference oActual;
if(!buildFileReference(sFilePath, oReference.m_sRelativePath, oActual) ||
oActual.m_nLength != oReference.m_nLength ||
oActual.m_sSha1 != oReference.m_sSha1)
{
return setError(pError, "Numerical file SHA-1 does not match its manifest.");
}
if(pAbsolutePath != NULL)
{
*pAbsolutePath = sFilePath;
}
return true;
}
bool nmNumericalResultPersistence::writeWellHistory(
const QString& sFilePath,
const nmNumericalWellHistoryData& oHistory,
QString* pError)
{
if(pError != NULL)
{
pError->clear();
}
QFile oFile(sFilePath);
if(!oFile.open(QIODevice::WriteOnly | QIODevice::Truncate))
{
return setError(pError, "Cannot create numerical well history file.");
}
const bool bWritten = writeAll(oFile, g_aWellHistoryMagic, 8) &&
writePod(oFile, g_nWellHistoryFormatVersion) &&
writePod(oFile, g_nEndianMarker) &&
writeCurve(oFile, oHistory.m_vecPressure) &&
writeCurve(oFile, oHistory.m_vecLogLog) &&
writeCurve(oFile, oHistory.m_vecSemiLog) &&
oFile.flush();
oFile.close();
if(!bWritten)
{
QFile::remove(sFilePath);
return setError(pError, "Cannot write complete numerical well history file.");
}
return true;
}
bool nmNumericalResultPersistence::readWellHistory(
const QString& sFilePath,
nmNumericalWellHistoryData& oHistory,
QString* pError)
{
if(pError != NULL)
{
pError->clear();
}
const QFileInfo oInfo(sFilePath);
if(!oInfo.exists() || oInfo.size() < 0 ||
static_cast<quint64>(oInfo.size()) > maximumBinaryPayloadBytes())
{
return setError(pError, "Numerical well history payload is missing or too large.");
}
try
{
QFile oFile(sFilePath);
if(!oFile.open(QIODevice::ReadOnly))
{
return setError(pError, "Cannot open numerical well history file.");
}
char aMagic[8] = { 0 };
quint32 nFormatVersion = 0;
quint32 nEndianMarker = 0;
quint64 nTotalPointCount = 0;
nmNumericalWellHistoryData oLoaded;
const bool bRead = readAll(oFile, aMagic, 8) &&
hasExactMagic(aMagic, g_aWellHistoryMagic, 8) &&
readPod(oFile, nFormatVersion) &&
nFormatVersion == g_nWellHistoryFormatVersion &&
readPod(oFile, nEndianMarker) &&
nEndianMarker == g_nEndianMarker &&
readCurve(oFile, oLoaded.m_vecPressure, nTotalPointCount) &&
readCurve(oFile, oLoaded.m_vecLogLog, nTotalPointCount) &&
readCurve(oFile, oLoaded.m_vecSemiLog, nTotalPointCount) &&
oFile.atEnd();
oFile.close();
if(!bRead)
{
return setError(pError, "Numerical well history file is damaged.");
}
oHistory = oLoaded;
return true;
}
catch(const std::bad_alloc&)
{
return setError(pError, "Not enough memory to load numerical well history.");
}
}
bool nmNumericalResultPersistence::writeGrid(
vtkUnstructuredGrid* pGrid,
const QString& sFilePath,
QString* pError)
{
if(pError != NULL)
{
pError->clear();
}
if(pGrid == NULL || pGrid->GetNumberOfPoints() <= 0 ||
pGrid->GetNumberOfCells() <= 0)
{
return setError(pError, "Numerical grid is empty.");
}
vtkNew<vtkXMLUnstructuredGridWriter> pWriter;
pWriter->SetInputData(pGrid);
pWriter->SetFileName(sFilePath.toLocal8Bit().constData());
pWriter->SetDataModeToBinary();
if(pWriter->Write() == 0 || !QFileInfo(sFilePath).isFile() ||
QFileInfo(sFilePath).size() <= 0)
{
QFile::remove(sFilePath);
return setError(pError, "Cannot write numerical VTU grid.");
}
return true;
}
bool nmNumericalResultPersistence::readGrid(
const QString& sFilePath,
vtkSmartPointer<vtkUnstructuredGrid>& pGrid,
QString* pError)
{
if(pError != NULL)
{
pError->clear();
}
pGrid = NULL;
if(!QFileInfo(sFilePath).isFile())
{
return setError(pError, "Numerical VTU grid is missing.");
}
try
{
vtkNew<vtkXMLUnstructuredGridReader> pReader;
pReader->SetFileName(sFilePath.toLocal8Bit().constData());
pReader->Update();
vtkUnstructuredGrid* pOutput = pReader->GetOutput();
if(pOutput == NULL || pOutput->GetNumberOfPoints() <= 0 ||
pOutput->GetNumberOfCells() <= 0)
{
return setError(pError, "Numerical VTU grid is invalid.");
}
pGrid = pOutput;
return pGrid != NULL;
}
catch(const std::bad_alloc&)
{
pGrid = NULL;
return setError(pError, "Not enough memory to load numerical VTU grid.");
}
}

@ -0,0 +1,601 @@
#include "nmNumericalSaveSession.h"
#include "nmDataAnalyzeManager.h"
#include "nmDataJsonTools.h"
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QSet>
#include <QUuid>
#include <rapidjson/document.h>
#if defined(Q_OS_WIN)
#include <windows.h>
#include <io.h>
#endif
namespace {
const char* g_pManifestFileName = "NumericalSaveManifest.json";
const quint64 g_nMaximumManifestBytes = 16ull * 1024ull * 1024ull;
const int g_nMaximumWindowCount = 10000;
bool setError(QString* pError, const QString& sError)
{
if(pError != NULL)
{
*pError = sError;
}
return false;
}
rapidjson::Value toJsonString(const QString& sValue,
rapidjson::Document::AllocatorType& oAllocator)
{
const QByteArray baValue = sValue.toUtf8();
return rapidjson::Value(baValue.constData(),
static_cast<rapidjson::SizeType>(baValue.size()),
oAllocator);
}
void addFileReference(rapidjson::Value& oParent,
const char* pName,
const nmNumericalFileReference& oReference,
rapidjson::Document::AllocatorType& oAllocator)
{
rapidjson::Value oJson(rapidjson::kObjectType);
oJson.AddMember("Path", toJsonString(oReference.m_sRelativePath,
oAllocator), oAllocator);
oJson.AddMember("Length", oReference.m_nLength, oAllocator);
oJson.AddMember("Sha1", toJsonString(oReference.m_sSha1,
oAllocator), oAllocator);
oParent.AddMember(rapidjson::Value(pName, oAllocator).Move(),
oJson, oAllocator);
}
bool readFileReference(const rapidjson::Value& oParent,
const char* pName,
nmNumericalFileReference& oReference)
{
if(!oParent.IsObject() || !oParent.HasMember(pName) ||
!oParent[pName].IsObject())
{
return false;
}
const rapidjson::Value& oJson = oParent[pName];
if(!oJson.HasMember("Path") || !oJson["Path"].IsString() ||
!oJson.HasMember("Length") || !oJson["Length"].IsUint64() ||
!oJson.HasMember("Sha1") || !oJson["Sha1"].IsString())
{
return false;
}
oReference.m_sRelativePath = QString::fromUtf8(oJson["Path"].GetString());
oReference.m_nLength = oJson["Length"].GetUint64();
oReference.m_sSha1 = QString::fromLatin1(oJson["Sha1"].GetString());
return oReference.isValid();
}
bool removeDirectoryTree(const QString& sDirectory)
{
const QFileInfo oInfo(sDirectory);
if(!oInfo.exists())
{
return true;
}
if(!oInfo.isDir())
{
return false;
}
QDir oDirectory(sDirectory);
const QFileInfoList listEntries = oDirectory.entryInfoList(
QDir::NoDotAndDotDot | QDir::AllEntries | QDir::Hidden |
QDir::System, QDir::DirsFirst);
for(int nIndex = 0; nIndex < listEntries.size(); ++nIndex)
{
const QFileInfo& oEntry = listEntries[nIndex];
if(oEntry.isDir())
{
if(!removeDirectoryTree(oEntry.absoluteFilePath()))
{
return false;
}
}
else if(!QFile::remove(oEntry.absoluteFilePath()))
{
return false;
}
}
return QDir().rmdir(sDirectory);
}
bool loadManifest(const QString& sResultRootDirectory,
QMap<QString, nmNumericalSavedWindow>& mapWindows,
QString* pGenerationId,
QString* pError)
{
mapWindows.clear();
const QString sManifestPath = QDir(sResultRootDirectory).filePath(
g_pManifestFileName);
const QFileInfo oInfo(sManifestPath);
if(!oInfo.isFile() || oInfo.size() <= 0 ||
static_cast<quint64>(oInfo.size()) > g_nMaximumManifestBytes)
{
return setError(pError, "Numerical v3 root manifest is missing or too large.");
}
rapidjson::Document oDocument;
if(!nmDataJsonTools::ReadDomFromFile(sManifestPath, oDocument) ||
!oDocument.IsObject() ||
!oDocument.HasMember("NumericalProjectVersion") ||
!oDocument["NumericalProjectVersion"].IsInt() ||
oDocument["NumericalProjectVersion"].GetInt() !=
nmNumericalResultPersistence::projectVersion() ||
!oDocument.HasMember("ManifestFormatVersion") ||
!oDocument["ManifestFormatVersion"].IsInt() ||
oDocument["ManifestFormatVersion"].GetInt() != 1 ||
!oDocument.HasMember("GenerationId") ||
!oDocument["GenerationId"].IsString() ||
!oDocument.HasMember("Windows") ||
!oDocument["Windows"].IsArray() ||
oDocument["Windows"].Size() >
static_cast<rapidjson::SizeType>(g_nMaximumWindowCount))
{
return setError(pError, "Numerical v3 root manifest is invalid.");
}
const QString sGenerationId = QString::fromUtf8(
oDocument["GenerationId"].GetString());
QString sNormalizedGenerationId;
if(!nmNumericalResultPersistence::normalizeRelativePath(
sGenerationId, sNormalizedGenerationId) ||
sNormalizedGenerationId != sGenerationId ||
sNormalizedGenerationId.contains('/'))
{
return setError(pError, "Numerical v3 root manifest generation is invalid.");
}
if(pGenerationId != NULL)
{
*pGenerationId = sGenerationId;
}
const rapidjson::Value& oWindows = oDocument["Windows"];
QSet<QString> setReferencedPaths;
bool bReferencesCurrentGeneration = false;
for(rapidjson::SizeType nIndex = 0; nIndex < oWindows.Size(); ++nIndex)
{
const rapidjson::Value& oJson = oWindows[nIndex];
if(!oJson.IsObject() ||
!oJson.HasMember("ResultId") || !oJson["ResultId"].IsString() ||
!oJson.HasMember("WindowId") || !oJson["WindowId"].IsString())
{
return setError(pError, "Numerical root manifest window is invalid.");
}
nmNumericalSavedWindow oWindow;
oWindow.m_sResultId = QString::fromUtf8(oJson["ResultId"].GetString());
oWindow.m_sWindowId = QString::fromUtf8(oJson["WindowId"].GetString());
QString sNormalizedWindowId;
if(oWindow.m_sResultId.isEmpty() ||
!nmNumericalResultPersistence::normalizeRelativePath(
oWindow.m_sWindowId, sNormalizedWindowId) ||
sNormalizedWindowId != oWindow.m_sWindowId ||
sNormalizedWindowId.contains('/') ||
mapWindows.contains(oWindow.m_sWindowId) ||
!readFileReference(oJson, "MainJson", oWindow.m_oMainJson) ||
setReferencedPaths.contains(oWindow.m_oMainJson.m_sRelativePath))
{
return setError(pError, "Numerical root manifest contains duplicate or invalid windows.");
}
// 根清单只接受固定代次目录,窗口身份不能与物理目录脱节。
const QStringList listPathParts =
oWindow.m_oMainJson.m_sRelativePath.split('/');
if(listPathParts.size() != 5 ||
listPathParts[0] != "NumericalGenerations" ||
listPathParts[2] != "Windows" ||
listPathParts[3] != oWindow.m_sWindowId ||
listPathParts[4] != "Numerical_Parameters.json")
{
return setError(pError, "Numerical root manifest window path is invalid.");
}
if(listPathParts[1] == sGenerationId)
{
bReferencesCurrentGeneration = true;
}
QString sMainPath;
if(!nmNumericalResultPersistence::validateFileReference(
sResultRootDirectory, oWindow.m_oMainJson,
&sMainPath, pError))
{
return false;
}
setReferencedPaths.insert(oWindow.m_oMainJson.m_sRelativePath);
mapWindows.insert(oWindow.m_sWindowId, oWindow);
}
return !mapWindows.isEmpty() && bReferencesCurrentGeneration
? true
: setError(pError, "Numerical root manifest does not reference its current generation.");
}
bool flushFileToDisk(const QString& sFilePath)
{
QFile oFile(sFilePath);
if(!oFile.open(QIODevice::ReadWrite) || !oFile.flush())
{
oFile.close();
return false;
}
#if defined(Q_OS_WIN)
const intptr_t nNativeHandle = _get_osfhandle(oFile.handle());
const bool bFlushed = nNativeHandle != -1 &&
FlushFileBuffers(reinterpret_cast<HANDLE>(nNativeHandle)) != FALSE;
#else
const bool bFlushed = true;
#endif
oFile.close();
return bFlushed;
}
bool publishManifestFile(const QString& sTargetPath,
const QString& sTemporaryPath,
const QString& sBackupPath)
{
#if defined(Q_OS_WIN)
const std::wstring wsTarget = QDir::toNativeSeparators(
sTargetPath).toStdWString();
const std::wstring wsTemporary = QDir::toNativeSeparators(
sTemporaryPath).toStdWString();
const std::wstring wsBackup = QDir::toNativeSeparators(
sBackupPath).toStdWString();
if(QFileInfo(sTargetPath).exists())
{
QFile::remove(sBackupPath);
return ReplaceFileW(wsTarget.c_str(), wsTemporary.c_str(),
wsBackup.c_str(), 0, NULL, NULL) != FALSE;
}
return MoveFileExW(wsTemporary.c_str(), wsTarget.c_str(),
MOVEFILE_WRITE_THROUGH) != FALSE;
#else
Q_UNUSED(sBackupPath);
if(QFileInfo(sTargetPath).exists() && !QFile::remove(sTargetPath))
{
return false;
}
return QFile::rename(sTemporaryPath, sTargetPath);
#endif
}
bool restoreManifestBackup(const QString& sTargetPath,
const QString& sBackupPath)
{
if(!QFileInfo(sBackupPath).isFile())
{
return false;
}
#if defined(Q_OS_WIN)
const std::wstring wsTarget = QDir::toNativeSeparators(
sTargetPath).toStdWString();
const std::wstring wsBackup = QDir::toNativeSeparators(
sBackupPath).toStdWString();
return ReplaceFileW(wsTarget.c_str(), wsBackup.c_str(),
NULL, 0, NULL, NULL) != FALSE;
#else
QFile::remove(sTargetPath);
return QFile::rename(sBackupPath, sTargetPath);
#endif
}
}
nmNumericalSaveSession::nmNumericalSaveSession()
: m_bActive(false),
m_bCommitted(false),
m_bKeepGenerationOnAbort(false)
{
}
nmNumericalSaveSession::~nmNumericalSaveSession()
{
if(m_bActive && !m_bCommitted)
{
abort();
}
}
bool nmNumericalSaveSession::begin(
const QString& sResultRootDirectory,
const QString& sResultId,
bool bPreserveExistingWindows,
QString* pError)
{
if(pError != NULL)
{
pError->clear();
}
if(m_bActive)
{
abort();
}
if(sResultRootDirectory.isEmpty() || sResultId.isEmpty() ||
!QDir().mkpath(sResultRootDirectory))
{
return setError(pError, "Cannot start numerical save session.");
}
m_sResultRootDirectory = QFileInfo(
sResultRootDirectory).absoluteFilePath();
m_sResultId = sResultId;
m_sGenerationId = QUuid::createUuid().toString().remove('{').remove('}');
m_sGenerationDirectory = QDir(m_sResultRootDirectory).filePath(
"NumericalGenerations/" + m_sGenerationId);
m_mapWindows.clear();
m_setValidatedWindowIds.clear();
m_bKeepGenerationOnAbort = false;
if(bPreserveExistingWindows && QFileInfo(QDir(
m_sResultRootDirectory).filePath(g_pManifestFileName)).isFile())
{
if(!loadManifest(m_sResultRootDirectory, m_mapWindows, NULL, pError))
{
m_mapWindows.clear();
return false;
}
}
if(!QDir().mkpath(QDir(m_sGenerationDirectory).filePath("Windows")))
{
m_mapWindows.clear();
return setError(pError, "Cannot create numerical generation directory.");
}
m_bActive = true;
m_bCommitted = false;
return true;
}
bool nmNumericalSaveSession::saveWindowGeneration(
const QString& sWindowId,
nmDataAnalyzeManager* pDataManager,
QString* pError)
{
if(pError != NULL)
{
pError->clear();
}
QString sNormalizedWindowId;
if(!m_bActive || pDataManager == NULL ||
!nmNumericalResultPersistence::normalizeRelativePath(
sWindowId, sNormalizedWindowId) ||
sNormalizedWindowId.contains('/'))
{
return setError(pError, "Numerical save window identifier is invalid.");
}
const QString sRelativeWindowDirectory = QString(
"NumericalGenerations/%1/Windows/%2")
.arg(m_sGenerationId, sNormalizedWindowId);
const QString sWindowDirectory = QDir(m_sResultRootDirectory).filePath(
sRelativeWindowDirectory);
if(!QDir().mkpath(sWindowDirectory))
{
return setError(pError, "Cannot create numerical window generation.");
}
nmNumericalFileReference oWindowMainReference;
if(!pDataManager->saveNmResultV3(sWindowDirectory,
oWindowMainReference, pError))
{
return false;
}
oWindowMainReference.m_sRelativePath = sRelativeWindowDirectory +
"/Numerical_Parameters.json";
if(!oWindowMainReference.isValid() ||
!nmNumericalResultPersistence::validateFileReference(
m_sResultRootDirectory, oWindowMainReference, NULL, pError))
{
return false;
}
nmNumericalSavedWindow oWindow;
oWindow.m_sResultId = m_sResultId;
oWindow.m_sWindowId = sNormalizedWindowId;
oWindow.m_oMainJson = oWindowMainReference;
m_mapWindows.insert(sNormalizedWindowId, oWindow);
// Manager 已在返回前完整校验本窗口,提交时无需重复扫描大压力文件。
m_setValidatedWindowIds.insert(sNormalizedWindowId);
return true;
}
bool nmNumericalSaveSession::commit(QString* pError)
{
QSet<QString> setReferencedGenerations;
if(pError != NULL)
{
pError->clear();
}
if(!m_bActive || m_mapWindows.isEmpty())
{
return setError(pError, "Numerical save session has no window generation.");
}
rapidjson::Document oDocument;
oDocument.SetObject();
rapidjson::Document::AllocatorType& oAllocator = oDocument.GetAllocator();
oDocument.AddMember("NumericalProjectVersion",
nmNumericalResultPersistence::projectVersion(), oAllocator);
oDocument.AddMember("ManifestFormatVersion", 1, oAllocator);
oDocument.AddMember("GenerationId",
toJsonString(m_sGenerationId, oAllocator), oAllocator);
rapidjson::Value oWindows(rapidjson::kArrayType);
QMap<QString, nmNumericalSavedWindow>::const_iterator oIt =
m_mapWindows.constBegin();
for(; oIt != m_mapWindows.constEnd(); ++oIt)
{
const nmNumericalSavedWindow& oWindow = oIt.value();
QString sMainJsonPath;
if(!nmNumericalResultPersistence::validateFileReference(
m_sResultRootDirectory, oWindow.m_oMainJson,
&sMainJsonPath, pError))
{
return false;
}
// 单窗口兼容会话会保留旧窗口;发布新清单前也必须复核其完整引用链。
if(!m_setValidatedWindowIds.contains(oIt.key()))
{
const bool bWindowValid =
nmDataAnalyzeManager::validateNmResultV3Window(
QFileInfo(sMainJsonPath).absolutePath(),
sMainJsonPath, pError);
if(!bWindowValid)
{
return false;
}
}
rapidjson::Value oJson(rapidjson::kObjectType);
oJson.AddMember("ResultId", toJsonString(
oWindow.m_sResultId, oAllocator), oAllocator);
oJson.AddMember("WindowId", toJsonString(
oWindow.m_sWindowId, oAllocator), oAllocator);
addFileReference(oJson, "MainJson", oWindow.m_oMainJson, oAllocator);
oWindows.PushBack(oJson, oAllocator);
}
oDocument.AddMember("Windows", oWindows, oAllocator);
const QString sManifestPath = QDir(m_sResultRootDirectory).filePath(
g_pManifestFileName);
const bool bHadPreviousManifest = QFileInfo(sManifestPath).isFile();
const QString sTemporaryPath = sManifestPath + ".tmp." + m_sGenerationId;
const QString sBackupPath = sManifestPath + ".bak." + m_sGenerationId;
QFile::remove(sTemporaryPath);
QFile::remove(sBackupPath);
if(!nmDataJsonTools::WriteDomToFile(oDocument, sTemporaryPath) ||
!flushFileToDisk(sTemporaryPath) ||
!publishManifestFile(sManifestPath, sTemporaryPath, sBackupPath))
{
QFile::remove(sTemporaryPath);
return setError(pError, "Cannot atomically publish numerical root manifest.");
}
// 发布后必须重新从磁盘解析和校验;失败时恢复原清单或删除无效的新清单。
if(!validatePublishedManifest(m_sResultRootDirectory, pError))
{
const QString sValidationError = pError == NULL
? QString("Published numerical root manifest validation failed.")
: *pError;
bool bRolledBack = false;
if(bHadPreviousManifest)
{
bRolledBack = restoreManifestBackup(
sManifestPath, sBackupPath) &&
validatePublishedManifest(m_sResultRootDirectory, NULL);
}
else
{
bRolledBack = QFile::remove(sManifestPath) ||
!QFileInfo(sManifestPath).exists();
}
if(!bRolledBack)
{
// 回滚失败时不能再由 abort 删除新代次,否则磁盘上的新清单会悬空。
m_bKeepGenerationOnAbort = true;
m_bActive = false;
return setError(pError, sValidationError +
" Root manifest rollback failed; the new generation and backup were retained.");
}
return setError(pError, sValidationError);
}
QFile::remove(sBackupPath);
m_bCommitted = true;
m_bActive = false;
// 只清理新清单未引用的代次;文件占用导致失败不影响已发布清单。
oIt = m_mapWindows.constBegin();
for(; oIt != m_mapWindows.constEnd(); ++oIt)
{
const QStringList listParts = oIt.value().m_oMainJson.m_sRelativePath
.split('/');
if(listParts.size() >= 2 && listParts[0] == "NumericalGenerations")
{
setReferencedGenerations.insert(listParts[1]);
}
}
QDir oGenerations(QDir(m_sResultRootDirectory).filePath(
"NumericalGenerations"));
const QFileInfoList listGenerations = oGenerations.entryInfoList(
QDir::Dirs | QDir::NoDotAndDotDot);
for(int nIndex = 0; nIndex < listGenerations.size(); ++nIndex)
{
if(!setReferencedGenerations.contains(listGenerations[nIndex].fileName()))
{
removeDirectoryTree(listGenerations[nIndex].absoluteFilePath());
}
}
return true;
}
void nmNumericalSaveSession::abort()
{
if(!m_bCommitted && !m_bKeepGenerationOnAbort &&
!m_sGenerationDirectory.isEmpty())
{
removeDirectoryTree(m_sGenerationDirectory);
}
m_bActive = false;
m_bCommitted = false;
m_bKeepGenerationOnAbort = false;
m_sResultId.clear();
m_sResultRootDirectory.clear();
m_sGenerationId.clear();
m_sGenerationDirectory.clear();
m_mapWindows.clear();
m_setValidatedWindowIds.clear();
}
bool nmNumericalSaveSession::isActive() const
{
return m_bActive;
}
QString nmNumericalSaveSession::generationId() const
{
return m_sGenerationId;
}
QString nmNumericalSaveSession::resultRootDirectory() const
{
return m_sResultRootDirectory;
}
bool nmNumericalSaveSession::resolveWindowMainJson(
const QString& sResultRootDirectory,
const QString& sWindowId,
QString& sWindowDirectory,
QString& sMainJsonPath,
nmNumericalFileReference* pMainReference,
QString* pError)
{
sWindowDirectory.clear();
sMainJsonPath.clear();
QMap<QString, nmNumericalSavedWindow> mapWindows;
if(!loadManifest(sResultRootDirectory, mapWindows, NULL, pError) ||
!mapWindows.contains(sWindowId))
{
return setError(pError, "Numerical v3 manifest does not reference this window.");
}
const nmNumericalFileReference oReference =
mapWindows.value(sWindowId).m_oMainJson;
if(!nmNumericalResultPersistence::validateFileReference(
sResultRootDirectory, oReference, &sMainJsonPath, pError))
{
return false;
}
sWindowDirectory = QFileInfo(sMainJsonPath).absolutePath();
if(pMainReference != NULL)
{
*pMainReference = oReference;
}
return true;
}
bool nmNumericalSaveSession::validatePublishedManifest(
const QString& sResultRootDirectory,
QString* pError)
{
QMap<QString, nmNumericalSavedWindow> mapWindows;
return loadManifest(sResultRootDirectory, mapWindows, NULL, pError);
}

File diff suppressed because it is too large Load Diff

@ -1,6 +1,8 @@
#include "zxLogInstance.h"
#include "iRibbonXmlCmd.h"
#include <QEvent>
#include <QDir>
#include <QFileInfo>
#include <QMdiArea>
#include <QMdiSubWindow>
#include "zxSysUtils.h"
@ -40,6 +42,9 @@
#include "nmDataAnalyzeManager.h"
#include "nmDataWellBase.h"
#include "nmDataAnalyzeContext.h"
#include "nmDataAnalyzeContextProvider.h"
#include "nmNumericalSaveSession.h"
#include "nmAttrRegistry.h"
#include "iRibbonXmlTab.h"
#include "nmWxParameterProperty.h"
@ -98,7 +103,7 @@ nmSubWndUtils::nmSubWndUtils()
{
m_pMainWnd = nullptr;
m_pTabWx = nullptr;
m_bClearRootDone = false;
m_pNumericalSaveSession = new nmNumericalSaveSession;
// 加载NM模块专用参数定义XML(Bin/XmlFiles/ModelParaDefinesNM_cn.xml)
{
@ -111,7 +116,11 @@ nmSubWndUtils::nmSubWndUtils()
}
}
nmSubWndUtils::~nmSubWndUtils() {}
nmSubWndUtils::~nmSubWndUtils()
{
delete m_pNumericalSaveSession;
m_pNumericalSaveSession = nullptr;
}
iSubWnd* nmSubWndUtils::createSubWnd(const iRibbonXmlCmd* pCmdInfo, \
const ZxMainWindow* pMainWnd, \
@ -775,6 +784,103 @@ bool nmSubWndUtils::nmCalAndFresh(iSubWnd* pSubWnd, \
return false;
}
bool nmSubWndUtils::beginNumericalSaveSession(
iSubWnd* pFirstSubWnd,
const QString& sRstName,
QString* pError)
{
if(pError != NULL) {
pError->clear();
}
iSubWndFitting* pSubWndF = dynamic_cast<iSubWndFitting*>(pFirstSubWnd);
nmDataAnalyzeManager* pDataManager = pSubWndF == nullptr ? nullptr :
nmDataAnalyzeManager::findManagerByFitting(pSubWndF);
nmDataAnalyzeContextProvider* pProvider = nmDataAnalyzeContext::provider();
QString sLogicalWindowDirectory;
nmSubWndUtils* pUtils = getInstance();
if(pDataManager == nullptr || pProvider == nullptr || pUtils == nullptr ||
pUtils->m_pNumericalSaveSession == nullptr ||
!pProvider->getSaveResultDir(pSubWndF, sRstName,
sLogicalWindowDirectory)) {
if(pError != NULL) *pError = "Cannot resolve numerical save session root.";
return false;
}
const QFileInfo oWindowInfo(QDir::cleanPath(sLogicalWindowDirectory));
// 显式会话从空窗口清单开始,只有本轮实际遍历到的窗口会被发布。
return pUtils->m_pNumericalSaveSession->begin(
oWindowInfo.dir().absolutePath(), sRstName, false, pError);
}
bool nmSubWndUtils::saveWindowGeneration(
iSubWnd* pSubWnd,
const QString& sRstName,
QString* pError)
{
if(pError != NULL) {
pError->clear();
}
iSubWndFitting* pSubWndF = dynamic_cast<iSubWndFitting*>(pSubWnd);
nmDataAnalyzeManager* pDataManager = pSubWndF == nullptr ? nullptr :
nmDataAnalyzeManager::findManagerByFitting(pSubWndF);
nmDataAnalyzeContextProvider* pProvider = nmDataAnalyzeContext::provider();
nmSubWndUtils* pUtils = getInstance();
QString sLogicalWindowDirectory;
if(pDataManager == nullptr || pProvider == nullptr || pUtils == nullptr ||
pUtils->m_pNumericalSaveSession == nullptr ||
!pUtils->m_pNumericalSaveSession->isActive() ||
!pProvider->getSaveResultDir(pSubWndF, sRstName,
sLogicalWindowDirectory)) {
if(pError != NULL) *pError = "Numerical save session is not active.";
return false;
}
const QFileInfo oWindowInfo(QDir::cleanPath(sLogicalWindowDirectory));
if(QDir::cleanPath(oWindowInfo.dir().absolutePath()) !=
QDir::cleanPath(
pUtils->m_pNumericalSaveSession->resultRootDirectory())) {
if(pError != NULL) *pError = "Numerical window belongs to another result root.";
return false;
}
return pUtils->m_pNumericalSaveSession->saveWindowGeneration(
oWindowInfo.fileName(), pDataManager, pError);
}
bool nmSubWndUtils::commitNumericalSaveSession(QString* pError)
{
nmSubWndUtils* pUtils = getInstance();
if(pUtils == nullptr || pUtils->m_pNumericalSaveSession == nullptr ||
!pUtils->m_pNumericalSaveSession->isActive()) {
if(pError != NULL) *pError = "Numerical save session is not active.";
return false;
}
return pUtils->m_pNumericalSaveSession->commit(pError);
}
void nmSubWndUtils::abortNumericalSaveSession()
{
nmSubWndUtils* pUtils = getInstance();
if(pUtils != nullptr && pUtils->m_pNumericalSaveSession != nullptr) {
pUtils->m_pNumericalSaveSession->abort();
}
}
nmNumericalSaveSessionAbortGuard::nmNumericalSaveSessionAbortGuard()
: m_bAbortRequired(true)
{
}
nmNumericalSaveSessionAbortGuard::~nmNumericalSaveSessionAbortGuard()
{
if(m_bAbortRequired) {
nmSubWndUtils::abortNumericalSaveSession();
}
}
void nmNumericalSaveSessionAbortGuard::release()
{
m_bAbortRequired = false;
}
bool nmSubWndUtils::saveRsts(iSubWnd* pSubWnd, \
QString sRstName, \
const ZxMainWindow* pMainWnd)
@ -799,15 +905,37 @@ bool nmSubWndUtils::saveRsts(iSubWnd* pSubWnd, \
return false;
}
// 对当前分析数据进行保存
// 保存周期内只在第一个窗口保存时清空成果目录,后续窗口不再清空
// 外层已经显式 begin 时只写当前窗口,由外层在遍历结束后 commit。
// 尚未接入外层钩子的旧调用走单窗口会话,并保留清单中的其他窗口。
nmSubWndUtils* pUtils = nmSubWndUtils::getInstance();
bool bClearRoot = (pUtils != nullptr) ? !pUtils->m_bClearRootDone : true;
if(!pDataManager->saveNmResult(sRstName, pSubWndF, bClearRoot)) {
return false;
}
if(pUtils != nullptr) {
pUtils->m_bClearRootDone = true;
QString sError;
if(pUtils != nullptr && pUtils->m_pNumericalSaveSession != nullptr &&
pUtils->m_pNumericalSaveSession->isActive()) {
if(!saveWindowGeneration(pSubWnd, sRstName, &sError)) {
qWarning() << sError;
return false;
}
} else {
nmDataAnalyzeContextProvider* pProvider = nmDataAnalyzeContext::provider();
QString sLogicalWindowDirectory;
if(pUtils == nullptr || pUtils->m_pNumericalSaveSession == nullptr ||
pProvider == nullptr ||
!pProvider->getSaveResultDir(pSubWndF, sRstName,
sLogicalWindowDirectory)) {
return false;
}
const QFileInfo oWindowInfo(QDir::cleanPath(
sLogicalWindowDirectory));
if(!pUtils->m_pNumericalSaveSession->begin(
oWindowInfo.dir().absolutePath(), sRstName,
true, &sError) ||
!pUtils->m_pNumericalSaveSession->saveWindowGeneration(
oWindowInfo.fileName(), pDataManager, &sError) ||
!pUtils->m_pNumericalSaveSession->commit(&sError)) {
pUtils->m_pNumericalSaveSession->abort();
qWarning() << sError;
return false;
}
}
} else if(pSubWnd->getWndID() == "5118") {
return true;
@ -831,11 +959,6 @@ bool nmSubWndUtils::loadRsts(iSubWnd* pSubWnd, \
ZxMainWindow* pMainWnd1 = const_cast<ZxMainWindow*>(pMainWnd);
nmSubWndUtils* pUtilsInstance = nmSubWndUtils::getInstance();
// 加载成果时重置清空标志,确保下次保存时第一个窗口会清空成果目录
if(pUtilsInstance != nullptr) {
pUtilsInstance->m_bClearRootDone = false;
}
if(nullptr != pMainWnd1) {
ZxTabWidget* pTabWx = pMainWnd1->getCurTabWx();
@ -870,11 +993,19 @@ bool nmSubWndUtils::loadRsts(iSubWnd* pSubWnd, \
// 获取该分析所在的目录
QString sDir = ZxBaseUtil::getWellDirOf(pCurrentWell->getName(), "Nm");
sDir += sRstName + "/" + sRstUtilWndCode;
// 判断分析目录是否存在
bool bDirExists = nmDataAnalyzeManager::isDirExist(sDir);
// 如果不存在,则说明没有保存数值解的参数
if(!bDirExists) {
// v3 的逻辑窗口目录不再直接落盘,只以成果根清单作为加载入口。
const QFileInfo oLogicalWindowInfo(QDir::cleanPath(sDir));
const QString sManifestPath = QDir(
oLogicalWindowInfo.dir().absolutePath()).filePath(
"NumericalSaveManifest.json");
if(!QFileInfo(sManifestPath).isFile()) {
const QString sLegacyJsonPath = QDir(sDir).filePath(
"Results/Numerical_Parameters.json");
if(QFileInfo(sLegacyJsonPath).isFile()) {
QMessageBox::warning(nullptr,
QObject::tr("Unsupported Numerical Result"),
QObject::tr("Numerical project version 2 is not supported. Only version 3 results can be loaded."));
}
return false;
}
@ -922,8 +1053,8 @@ bool nmSubWndUtils::loadRsts(iSubWnd* pSubWnd, \
setupNumericalDockWidgets(pDataManager, pSubWndMain,
pWxDockNm1, pWxDockNm2);
// 判断是否保存了时间步数据
if(!pDataManager->isTimeStepDataEmpty()) {
// v3 场图只以独立快照是否存在为准,不再依赖旧时间步 Map。
if(pDataManager->hasPebiResultSnapshot()) {
QString sErrorMessage;
// 刷新场图
QWidget* p3DWidget = pSubWndF->getFitSubRstWxOf(FSRT_Nm3D, true, &sErrorMessage);

Loading…
Cancel
Save