From e0577d1649540f2367e035757146711e5b96b3b6 Mon Sep 17 00:00:00 2001 From: lh <2334563547@qq.com> Date: Tue, 1 Sep 2026 14:15:41 +0800 Subject: [PATCH] =?UTF-8?q?feat(numerical):=20=E5=AE=9E=E7=8E=B0=20PEBI=20?= =?UTF-8?q?=E7=BB=93=E6=9E=9C=E5=BF=AB=E7=85=A7=20v3=20=E6=8C=81=E4=B9=85?= =?UTF-8?q?=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 增加快照网格、压力帧和井曲线的流式序列化 - 增加三级 SHA-1 引用链及载荷安全校验 - 增加显式保存会话和 Windows 根清单原子发布 - 数值成果保存与加载切换至 v3,并明确拒绝 v2 - 增加 v3 持久化回归测试 --- Include/nmNum/nmData/nmDataAnalyzeManager.h | 23 +- .../nmData/nmDataNumericalAnalysisCase.h | 7 + .../nmData/nmNumericalResultPersistence.h | 116 ++ Include/nmNum/nmData/nmNumericalSaveSession.h | 102 ++ .../nmData/nmPebiResultSnapshotSerializer.h | 54 + Include/nmNum/nmSubWnd/nmSubWndUtils.h | 50 +- Src/nmNum/nmData/nmDataAnalyzeManager.cpp | 673 +++++++++- .../nmData/nmDataNumericalAnalysisCase.cpp | 20 + .../nmData/nmNumericalResultPersistence.cpp | 520 ++++++++ Src/nmNum/nmData/nmNumericalSaveSession.cpp | 601 +++++++++ .../nmData/nmPebiResultSnapshotSerializer.cpp | 1175 +++++++++++++++++ Src/nmNum/nmSubWnd/nmSubWndUtils.cpp | 175 ++- 12 files changed, 3479 insertions(+), 37 deletions(-) create mode 100644 Include/nmNum/nmData/nmNumericalResultPersistence.h create mode 100644 Include/nmNum/nmData/nmNumericalSaveSession.h create mode 100644 Include/nmNum/nmData/nmPebiResultSnapshotSerializer.h create mode 100644 Src/nmNum/nmData/nmNumericalResultPersistence.cpp create mode 100644 Src/nmNum/nmData/nmNumericalSaveSession.cpp create mode 100644 Src/nmNum/nmData/nmPebiResultSnapshotSerializer.cpp diff --git a/Include/nmNum/nmData/nmDataAnalyzeManager.h b/Include/nmNum/nmData/nmDataAnalyzeManager.h index aa46c4f6..3705fb43 100644 --- a/Include/nmNum/nmData/nmDataAnalyzeManager.h +++ b/Include/nmNum/nmData/nmDataAnalyzeManager.h @@ -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 diff --git a/Include/nmNum/nmData/nmDataNumericalAnalysisCase.h b/Include/nmNum/nmData/nmDataNumericalAnalysisCase.h index 930b85dd..b6595202 100644 --- a/Include/nmNum/nmData/nmDataNumericalAnalysisCase.h +++ b/Include/nmNum/nmData/nmDataNumericalAnalysisCase.h @@ -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(); diff --git a/Include/nmNum/nmData/nmNumericalResultPersistence.h b/Include/nmNum/nmData/nmNumericalResultPersistence.h new file mode 100644 index 00000000..19e5c149 --- /dev/null +++ b/Include/nmNum/nmData/nmNumericalResultPersistence.h @@ -0,0 +1,116 @@ +#ifndef NMNUMERICALRESULTPERSISTENCE_H +#define NMNUMERICALRESULTPERSISTENCE_H + +#include "nmData_global.h" + +#include +#include +#include + +#include + +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 > m_vecPressure; + /** @brief 双对数历史曲线。 */ + QVector > m_vecLogLog; + /** @brief 半对数历史曲线。 */ + QVector > m_vecSemiLog; +}; + +/** @brief 一个窗口主 JSON 引用的全部外部载荷。 */ +struct NM_DATA_EXPORT nmNumericalWindowPayloadReferences +{ + /** @brief 当前输入网格是否存在。 */ + bool m_bHasCurrentGrid; + /** @brief 当前输入网格文件引用。 */ + nmNumericalFileReference m_oCurrentGrid; + /** @brief 按实时井 UUID 保存的历史曲线文件引用。 */ + QMap 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& pGrid, + QString* pError = NULL); + +private: + /** @brief 禁止实例化纯静态工具类。 */ + nmNumericalResultPersistence(); +}; + +#endif // NMNUMERICALRESULTPERSISTENCE_H diff --git a/Include/nmNum/nmData/nmNumericalSaveSession.h b/Include/nmNum/nmData/nmNumericalSaveSession.h new file mode 100644 index 00000000..df7e47c6 --- /dev/null +++ b/Include/nmNum/nmData/nmNumericalSaveSession.h @@ -0,0 +1,102 @@ +#ifndef NMNUMERICALSAVESESSION_H +#define NMNUMERICALSAVESESSION_H + +#include "nmData_global.h" +#include "nmNumericalResultPersistence.h" + +#include +#include +#include + +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 m_mapWindows; + /** @brief 本轮已经写入并完成全引用链校验的窗口标识。 */ + QSet m_setValidatedWindowIds; +}; + +#endif // NMNUMERICALSAVESESSION_H diff --git a/Include/nmNum/nmData/nmPebiResultSnapshotSerializer.h b/Include/nmNum/nmData/nmPebiResultSnapshotSerializer.h new file mode 100644 index 00000000..77f687b8 --- /dev/null +++ b/Include/nmNum/nmData/nmPebiResultSnapshotSerializer.h @@ -0,0 +1,54 @@ +#ifndef NMPEBIRESULTSNAPSHOTSERIALIZER_H +#define NMPEBIRESULTSNAPSHOTSERIALIZER_H + +#include "nmData_global.h" +#include "nmNumericalResultPersistence.h" + +#include +#include + +class nmPebiResultSnapshot; + +/** + * @brief 负责 v3 快照三文件载荷及 Snapshot.json 的流式保存和加载。 + * + * 序列化器是快照的受限友元,只在保存时读取内部 VTK 对象;加载仍通过 + * nmPebiResultSnapshotBuilder 构造和封闭候选。 + */ +class NM_DATA_EXPORT nmPebiResultSnapshotSerializer +{ +public: + /** @brief 将完整快照写入窗口目录下的 Snapshot 子目录。 */ + static bool save( + const QSharedPointer& 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& 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 diff --git a/Include/nmNum/nmSubWnd/nmSubWndUtils.h b/Include/nmNum/nmSubWnd/nmSubWndUtils.h index 2f04a2ee..81b5358b 100644 --- a/Include/nmNum/nmSubWnd/nmSubWndUtils.h +++ b/Include/nmNum/nmSubWnd/nmSubWndUtils.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 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; }; diff --git a/Src/nmNum/nmData/nmDataAnalyzeManager.cpp b/Src/nmNum/nmData/nmDataAnalyzeManager.cpp index a652644b..cb823754 100644 --- a/Src/nmNum/nmData/nmDataAnalyzeManager.cpp +++ b/Src/nmNum/nmData/nmDataAnalyzeManager.cpp @@ -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 #include +#include #include #include "singlePhaseSolver.h" @@ -504,6 +507,185 @@ void createDefaultLayer(double dThickness, QVector& 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(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 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 setWellCodes; QMap 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 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::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 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::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 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 mapLoadedHistories; + QMap::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 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 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 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) diff --git a/Src/nmNum/nmData/nmDataNumericalAnalysisCase.cpp b/Src/nmNum/nmData/nmDataNumericalAnalysisCase.cpp index cf9acf2e..59bffd09 100644 --- a/Src/nmNum/nmData/nmDataNumericalAnalysisCase.cpp +++ b/Src/nmNum/nmData/nmDataNumericalAnalysisCase.cpp @@ -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() { diff --git a/Src/nmNum/nmData/nmNumericalResultPersistence.cpp b/Src/nmNum/nmData/nmNumericalResultPersistence.cpp new file mode 100644 index 00000000..306e6650 --- /dev/null +++ b/Src/nmNum/nmData/nmNumericalResultPersistence.cpp @@ -0,0 +1,520 @@ +#include "nmNumericalResultPersistence.h" + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include + +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(qMin( + static_cast(g_nStreamChunkBytes), + nBytes - nWritten)); + const qint64 nResult = oFile.write(pData + nWritten, nChunk); + if(nResult != nChunk) + { + return false; + } + nWritten += static_cast(nResult); + } + return true; +} + +bool readAll(QFile& oFile, char* pData, quint64 nBytes) +{ + quint64 nRead = 0; + while(nRead < nBytes) + { + const qint64 nChunk = static_cast(qMin( + static_cast(g_nStreamChunkBytes), + nBytes - nRead)); + const qint64 nResult = oFile.read(pData + nRead, nChunk); + if(nResult != nChunk) + { + return false; + } + nRead += static_cast(nResult); + } + return true; +} + +template +bool writePod(QFile& oFile, const T& oValue) +{ + return writeAll(oFile, reinterpret_cast(&oValue), + static_cast(sizeof(T))); +} + +template +bool readPod(QFile& oFile, T& oValue) +{ + return readAll(oFile, reinterpret_cast(&oValue), + static_cast(sizeof(T))); +} + +bool safeMultiply(quint64 nLeft, quint64 nRight, quint64& nProduct) +{ + if(nLeft != 0 && nRight > (~static_cast(0)) / nLeft) + { + return false; + } + nProduct = nLeft * nRight; + return true; +} + +bool writeCurve(QFile& oFile, const QVector >& vecCurve) +{ + const quint32 nSeriesCount = static_cast(vecCurve.size()); + if(!writePod(oFile, nSeriesCount)) + { + return false; + } + for(int nSeries = 0; nSeries < vecCurve.size(); ++nSeries) + { + const QVector& vecValues = vecCurve[nSeries]; + const quint64 nPointCount = static_cast(vecValues.size()); + quint64 nBytes = 0; + if(!safeMultiply(nPointCount, sizeof(double), nBytes) || + !writePod(oFile, nPointCount) || + (nBytes > 0 && !writeAll(oFile, + reinterpret_cast(vecValues.constData()), + nBytes))) + { + return false; + } + } + return true; +} + +bool readCurve(QFile& oFile, + QVector >& vecCurve, + quint64& nTotalPointCount) +{ + quint32 nSeriesCount = 0; + if(!readPod(oFile, nSeriesCount) || nSeriesCount > g_nMaximumCurveSeries) + { + return false; + } + + QVector > vecLoaded; + vecLoaded.resize(static_cast(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(oFile.bytesAvailable()) || + nPointCount > static_cast(INT_MAX)) + { + return false; + } + nTotalPointCount += nPointCount; + vecLoaded[static_cast(nSeries)].resize( + static_cast(nPointCount)); + if(nBytes > 0 && !readAll(oFile, + reinterpret_cast( + vecLoaded[static_cast(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(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(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(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 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& pGrid, + QString* pError) +{ + if(pError != NULL) + { + pError->clear(); + } + pGrid = NULL; + if(!QFileInfo(sFilePath).isFile()) + { + return setError(pError, "Numerical VTU grid is missing."); + } + + try + { + vtkNew 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."); + } +} diff --git a/Src/nmNum/nmData/nmNumericalSaveSession.cpp b/Src/nmNum/nmData/nmNumericalSaveSession.cpp new file mode 100644 index 00000000..ddba41be --- /dev/null +++ b/Src/nmNum/nmData/nmNumericalSaveSession.cpp @@ -0,0 +1,601 @@ +#include "nmNumericalSaveSession.h" + +#include "nmDataAnalyzeManager.h" +#include "nmDataJsonTools.h" + +#include +#include +#include +#include +#include + +#include + +#if defined(Q_OS_WIN) +#include +#include +#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(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& 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(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(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 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(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 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::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 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 mapWindows; + return loadManifest(sResultRootDirectory, mapWindows, NULL, pError); +} diff --git a/Src/nmNum/nmData/nmPebiResultSnapshotSerializer.cpp b/Src/nmNum/nmData/nmPebiResultSnapshotSerializer.cpp new file mode 100644 index 00000000..d84b56e1 --- /dev/null +++ b/Src/nmNum/nmData/nmPebiResultSnapshotSerializer.cpp @@ -0,0 +1,1175 @@ +#include "nmPebiResultSnapshotSerializer.h" + +#include "nmDataJsonTools.h" +#include "nmPebiResultSnapshot.h" +#include "nmPebiResultSnapshotBuilder.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include + +#include + +namespace { + +const char g_aPressureMagic[8] = { 'N', 'M', 'P', 'R', 'E', 'S', '3', 0 }; +const char g_aCurvesMagic[8] = { 'N', 'M', 'C', 'U', 'R', 'V', '3', 0 }; +const quint32 g_nBinaryFormatVersion = 1; +const quint32 g_nEndianMarker = 0x01020304u; +const quint64 g_nMaximumCellCount = 50000000ull; +const quint32 g_nMaximumFrameCount = 10000u; +const quint32 g_nMaximumWellCount = 10000u; +const quint32 g_nMaximumCurveSeries = 64u; +const quint64 g_nMaximumCurvePoints = 50000000ull; +const quint32 g_nMaximumUuidBytes = 128u; +const quint64 g_nMaximumSnapshotJsonBytes = 64ull * 1024ull * 1024ull; +const qint64 g_nStreamChunkBytes = 4 * 1024 * 1024; + +bool setError(QString* pError, const QString& sError) +{ + if(pError != NULL) + { + *pError = sError; + } + return false; +} + +bool isFiniteValue(double dValue) +{ +#if defined(_MSC_VER) + return _finite(dValue) != 0; +#else + return qIsFinite(dValue); +#endif +} + +bool safeMultiply(quint64 nLeft, quint64 nRight, quint64& nProduct) +{ + if(nLeft != 0 && nRight > (~static_cast(0)) / nLeft) + { + return false; + } + nProduct = nLeft * nRight; + return true; +} + +bool safeAdd(quint64 nLeft, quint64 nRight, quint64& nSum) +{ + if(nRight > (~static_cast(0)) - nLeft) + { + return false; + } + nSum = nLeft + nRight; + return true; +} + +bool writeAll(QFile& oFile, const char* pData, quint64 nBytes) +{ + quint64 nWritten = 0; + while(nWritten < nBytes) + { + const qint64 nChunk = static_cast(qMin( + static_cast(g_nStreamChunkBytes), + nBytes - nWritten)); + if(oFile.write(pData + static_cast(nWritten), nChunk) != nChunk) + { + return false; + } + nWritten += static_cast(nChunk); + } + return true; +} + +bool readAll(QFile& oFile, char* pData, quint64 nBytes) +{ + quint64 nRead = 0; + while(nRead < nBytes) + { + const qint64 nChunk = static_cast(qMin( + static_cast(g_nStreamChunkBytes), + nBytes - nRead)); + if(oFile.read(pData + static_cast(nRead), nChunk) != nChunk) + { + return false; + } + nRead += static_cast(nChunk); + } + return true; +} + +template +bool writePod(QFile& oFile, const T& oValue) +{ + return writeAll(oFile, reinterpret_cast(&oValue), + static_cast(sizeof(T))); +} + +template +bool readPod(QFile& oFile, T& oValue) +{ + return readAll(oFile, reinterpret_cast(&oValue), + static_cast(sizeof(T))); +} + +bool hasMagic(const char* pActual, const char* pExpected) +{ + for(int nIndex = 0; nIndex < 8; ++nIndex) + { + if(pActual[nIndex] != pExpected[nIndex]) + { + return false; + } + } + return true; +} + +rapidjson::Value toJsonString(const QString& sValue, + rapidjson::Document::AllocatorType& oAllocator) +{ + const QByteArray baValue = sValue.toUtf8(); + return rapidjson::Value(baValue.constData(), + static_cast(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(); +} + +void addDoubleVector(rapidjson::Value& oParent, + const char* pName, + const QVector& vecValues, + rapidjson::Document::AllocatorType& oAllocator) +{ + rapidjson::Value oArray(rapidjson::kArrayType); + for(int nIndex = 0; nIndex < vecValues.size(); ++nIndex) + { + oArray.PushBack(vecValues[nIndex], oAllocator); + } + oParent.AddMember(rapidjson::Value(pName, oAllocator).Move(), + oArray, oAllocator); +} + +bool readDoubleVector(const rapidjson::Value& oParent, + const char* pName, + QVector& vecValues) +{ + if(!oParent.IsObject() || !oParent.HasMember(pName) || + !oParent[pName].IsArray() || + oParent[pName].Size() > static_cast(10000000)) + { + return false; + } + const rapidjson::Value& oArray = oParent[pName]; + QVector vecLoaded; + vecLoaded.reserve(static_cast(oArray.Size())); + for(rapidjson::SizeType nIndex = 0; nIndex < oArray.Size(); ++nIndex) + { + if(!oArray[nIndex].IsNumber() || + !isFiniteValue(oArray[nIndex].GetDouble())) + { + return false; + } + vecLoaded.append(oArray[nIndex].GetDouble()); + } + vecValues.swap(vecLoaded); + return true; +} + +bool writeCurve(QFile& oFile, const QVector >& vecCurve) +{ + const quint32 nSeriesCount = static_cast(vecCurve.size()); + if(!writePod(oFile, nSeriesCount)) + { + return false; + } + for(int nSeries = 0; nSeries < vecCurve.size(); ++nSeries) + { + const QVector& vecValues = vecCurve[nSeries]; + const quint64 nPointCount = static_cast(vecValues.size()); + quint64 nBytes = 0; + if(!safeMultiply(nPointCount, sizeof(double), nBytes) || + !writePod(oFile, nPointCount) || + (nBytes > 0 && !writeAll(oFile, + reinterpret_cast(vecValues.constData()), nBytes))) + { + return false; + } + } + return true; +} + +bool readCurve(QFile& oFile, + QVector >* pCurve, + quint64& nTotalPoints) +{ + quint32 nSeriesCount = 0; + if(!readPod(oFile, nSeriesCount) || nSeriesCount > g_nMaximumCurveSeries) + { + return false; + } + QVector > vecLoaded; + if(pCurve != NULL) + { + vecLoaded.resize(static_cast(nSeriesCount)); + } + for(quint32 nSeries = 0; nSeries < nSeriesCount; ++nSeries) + { + quint64 nPointCount = 0; + quint64 nBytes = 0; + if(!readPod(oFile, nPointCount) || + nPointCount > g_nMaximumCurvePoints || + nTotalPoints > g_nMaximumCurvePoints - nPointCount || + !safeMultiply(nPointCount, sizeof(double), nBytes) || + nBytes > static_cast(oFile.bytesAvailable()) || + nPointCount > static_cast(INT_MAX)) + { + return false; + } + nTotalPoints += nPointCount; + if(pCurve == NULL) + { + if(!oFile.seek(oFile.pos() + static_cast(nBytes))) + { + return false; + } + } + else + { + QVector& vecValues = vecLoaded[static_cast(nSeries)]; + vecValues.resize(static_cast(nPointCount)); + if(nBytes > 0 && !readAll(oFile, + reinterpret_cast(vecValues.data()), nBytes)) + { + return false; + } + } + } + if(pCurve != NULL) + { + pCurve->swap(vecLoaded); + } + return true; +} + +bool readPressureFrames(const QString& sFilePath, + quint64 nExpectedCellCount, + quint32 nExpectedFrameCount, + nmPebiResultSnapshotBuilder* pBuilder, + QString* pError) +{ + const QFileInfo oInfo(sFilePath); + if(!oInfo.isFile() || oInfo.size() < 0 || + static_cast(oInfo.size()) > + nmNumericalResultPersistence::maximumBinaryPayloadBytes()) + { + return setError(pError, "PEBI pressure payload is missing or too large."); + } + QFile oFile(sFilePath); + if(!oFile.open(QIODevice::ReadOnly)) + { + return setError(pError, "Cannot open PEBI pressure frame file."); + } + char aMagic[8] = { 0 }; + quint32 nVersion = 0; + quint32 nEndian = 0; + quint64 nCellCount = 0; + quint32 nFrameCount = 0; + quint64 nFrameBytes = 0; + quint64 nPerFrameBytes = 0; + quint64 nPayloadBytes = 0; + quint64 nExpectedBytes = 0; + const quint64 nHeaderBytes = 8 + sizeof(quint32) + sizeof(quint32) + + sizeof(quint64) + sizeof(quint32); + bool bOk = readAll(oFile, aMagic, 8) && + hasMagic(aMagic, g_aPressureMagic) && + readPod(oFile, nVersion) && nVersion == g_nBinaryFormatVersion && + readPod(oFile, nEndian) && nEndian == g_nEndianMarker && + readPod(oFile, nCellCount) && nCellCount > 0 && + nCellCount <= g_nMaximumCellCount && + readPod(oFile, nFrameCount) && nFrameCount > 0 && + nFrameCount <= g_nMaximumFrameCount && + nCellCount == nExpectedCellCount && + nFrameCount == nExpectedFrameCount && + safeMultiply(nCellCount, sizeof(double), nFrameBytes) && + safeAdd(sizeof(double), nFrameBytes, nPerFrameBytes) && + safeMultiply(nPerFrameBytes, nFrameCount, nPayloadBytes) && + safeAdd(nHeaderBytes, nPayloadBytes, nExpectedBytes) && + nExpectedBytes == static_cast(oInfo.size()); + double dPreviousTime = 0.0; + for(quint32 nFrame = 0; bOk && nFrame < nFrameCount; ++nFrame) + { + double dTime = 0.0; + bOk = readPod(oFile, dTime) && isFiniteValue(dTime) && + (nFrame == 0 || dTime > dPreviousTime); + if(!bOk) + { + break; + } + if(pBuilder == NULL) + { + bOk = oFile.seek(oFile.pos() + static_cast(nFrameBytes)); + } + else + { + vtkSmartPointer pPressure = + vtkSmartPointer::New(); + pPressure->SetName("p"); + pPressure->SetNumberOfComponents(1); + pPressure->SetNumberOfTuples(static_cast(nCellCount)); + double* pValues = pPressure->GetPointer(0); + bOk = pValues != NULL && + pPressure->GetNumberOfTuples() == + static_cast(nCellCount) && + readAll(oFile, reinterpret_cast(pValues), + nFrameBytes); + for(quint64 nCell = 0; bOk && nCell < nCellCount; ++nCell) + { + bOk = isFiniteValue(pValues[nCell]); + } + bOk = bOk && pBuilder->addPressureFrame(dTime, pPressure) && + pPressure == NULL; + } + dPreviousTime = dTime; + } + bOk = bOk && oFile.atEnd(); + oFile.close(); + return bOk ? true : setError(pError, "PEBI pressure frame file is damaged."); +} + +bool readWellCurves(const QString& sFilePath, + quint32 nExpectedWellCount, + QMap* pCurves, + QString* pError) +{ + const QFileInfo oInfo(sFilePath); + if(!oInfo.isFile() || oInfo.size() < 0 || + static_cast(oInfo.size()) > + nmNumericalResultPersistence::maximumBinaryPayloadBytes()) + { + return setError(pError, "PEBI well curve payload is missing or too large."); + } + QFile oFile(sFilePath); + if(!oFile.open(QIODevice::ReadOnly)) + { + return setError(pError, "Cannot open PEBI well curve file."); + } + char aMagic[8] = { 0 }; + quint32 nVersion = 0; + quint32 nEndian = 0; + quint32 nWellCount = 0; + QMap mapLoaded; + QSet setWellIds; + quint64 nTotalPoints = 0; + bool bOk = readAll(oFile, aMagic, 8) && + hasMagic(aMagic, g_aCurvesMagic) && + readPod(oFile, nVersion) && nVersion == g_nBinaryFormatVersion && + readPod(oFile, nEndian) && nEndian == g_nEndianMarker && + readPod(oFile, nWellCount) && nWellCount <= g_nMaximumWellCount && + nWellCount == nExpectedWellCount; + for(quint32 nWell = 0; bOk && nWell < nWellCount; ++nWell) + { + quint32 nUuidBytes = 0; + bOk = readPod(oFile, nUuidBytes) && nUuidBytes > 0 && + nUuidBytes <= g_nMaximumUuidBytes && + nUuidBytes <= static_cast(oFile.bytesAvailable()); + QByteArray baUuid; + if(bOk) + { + baUuid.resize(static_cast(nUuidBytes)); + bOk = readAll(oFile, baUuid.data(), nUuidBytes); + } + const QString sUuid = QString::fromUtf8(baUuid); + bOk = bOk && !sUuid.isEmpty() && !setWellIds.contains(sUuid); + nmPebiResultWellCurves oCurves; + bOk = bOk && readCurve(oFile, + pCurves == NULL ? NULL : &oCurves.m_vecHistoryPressure, + nTotalPoints) && + readCurve(oFile, + pCurves == NULL ? NULL : &oCurves.m_vecHistoryLogLog, + nTotalPoints) && + readCurve(oFile, + pCurves == NULL ? NULL : &oCurves.m_vecHistorySemiLog, + nTotalPoints) && + readCurve(oFile, + pCurves == NULL ? NULL : &oCurves.m_vecResultPressure, + nTotalPoints) && + readCurve(oFile, + pCurves == NULL ? NULL : &oCurves.m_vecResultLogLog, + nTotalPoints) && + readCurve(oFile, + pCurves == NULL ? NULL : &oCurves.m_vecResultSemiLog, + nTotalPoints); + if(bOk) + { + setWellIds.insert(sUuid); + if(pCurves != NULL) + { + mapLoaded.insert(sUuid, oCurves); + } + } + } + bOk = bOk && oFile.atEnd() && setWellIds.size() == nExpectedWellCount; + oFile.close(); + if(!bOk) + { + return setError(pError, "PEBI well curve file is damaged."); + } + if(pCurves != NULL) + { + pCurves->swap(mapLoaded); + } + return true; +} + +bool readRequiredInt(const rapidjson::Value& oParent, + const char* pName, + int& nValue) +{ + if(!oParent.IsObject() || !oParent.HasMember(pName) || + !oParent[pName].IsInt()) + { + return false; + } + nValue = oParent[pName].GetInt(); + return true; +} + +bool readRequiredDouble(const rapidjson::Value& oParent, + const char* pName, + double& dValue) +{ + if(!oParent.IsObject() || !oParent.HasMember(pName) || + !oParent[pName].IsNumber() || + !isFiniteValue(oParent[pName].GetDouble())) + { + return false; + } + dValue = oParent[pName].GetDouble(); + return true; +} + +bool readRequiredBool(const rapidjson::Value& oParent, + const char* pName, + bool& bValue) +{ + if(!oParent.IsObject() || !oParent.HasMember(pName) || + !oParent[pName].IsBool()) + { + return false; + } + bValue = oParent[pName].GetBool(); + return true; +} + +bool parseSnapshotJson( + const QString& sSnapshotJsonPath, + rapidjson::Document& oDocument, + nmNumericalFileReference& oGridReference, + nmNumericalFileReference& oPressureReference, + nmNumericalFileReference& oCurvesReference, + quint64& nCellCount, + quint32& nFrameCount, + quint32& nWellCount, + QString* pError) +{ + const QFileInfo oInfo(sSnapshotJsonPath); + if(!oInfo.isFile() || oInfo.size() <= 0 || + static_cast(oInfo.size()) > g_nMaximumSnapshotJsonBytes || + !nmDataJsonTools::ReadDomFromFile(sSnapshotJsonPath, oDocument)) + { + return setError(pError, "Snapshot.json is missing, too large or invalid."); + } + if(!oDocument.IsObject() || + !oDocument.HasMember("SnapshotFormatVersion") || + !oDocument["SnapshotFormatVersion"].IsInt() || + oDocument["SnapshotFormatVersion"].GetInt() != 1 || + !oDocument.HasMember("ResultCellCount") || + !oDocument["ResultCellCount"].IsUint64() || + !oDocument.HasMember("PressureFrameCount") || + !oDocument["PressureFrameCount"].IsUint() || + !oDocument.HasMember("WellCount") || + !oDocument["WellCount"].IsUint() || + !readFileReference(oDocument, "ResultGrid", oGridReference) || + !readFileReference(oDocument, "PressureFrames", oPressureReference) || + !readFileReference(oDocument, "WellCurves", oCurvesReference)) + { + return setError(pError, "Snapshot.json header or file references are invalid."); + } + nCellCount = oDocument["ResultCellCount"].GetUint64(); + nFrameCount = oDocument["PressureFrameCount"].GetUint(); + nWellCount = oDocument["WellCount"].GetUint(); + if(nCellCount == 0 || nCellCount > g_nMaximumCellCount || + nFrameCount == 0 || nFrameCount > g_nMaximumFrameCount || + nWellCount > g_nMaximumWellCount || + oGridReference.m_sRelativePath == oPressureReference.m_sRelativePath || + oGridReference.m_sRelativePath == oCurvesReference.m_sRelativePath || + oPressureReference.m_sRelativePath == oCurvesReference.m_sRelativePath) + { + return setError(pError, "Snapshot.json declares invalid or duplicate payloads."); + } + return true; +} + +} + +bool nmPebiResultSnapshotSerializer::writePressureFrames( + const nmPebiResultSnapshot& oSnapshot, + const QString& sFilePath, + QString* pError) +{ + QFile oFile(sFilePath); + if(!oFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) + { + return setError(pError, "Cannot create PEBI pressure frame file."); + } + const quint64 nCellCount = static_cast( + oSnapshot.m_pResultGrid->GetNumberOfCells()); + const quint32 nFrameCount = static_cast( + oSnapshot.m_vecPressureFrames.size()); + bool bOk = writeAll(oFile, g_aPressureMagic, 8) && + writePod(oFile, g_nBinaryFormatVersion) && + writePod(oFile, g_nEndianMarker) && + writePod(oFile, nCellCount) && writePod(oFile, nFrameCount); + quint64 nFrameBytes = 0; + bOk = bOk && safeMultiply(nCellCount, sizeof(double), nFrameBytes); + for(int nIndex = 0; bOk && nIndex < oSnapshot.m_vecPressureFrames.size(); + ++nIndex) + { + const nmPebiResultSnapshot::PressureFrame& oFrame = + oSnapshot.m_vecPressureFrames[nIndex]; + double* pValues = oFrame.m_pPressure == NULL ? NULL : + oFrame.m_pPressure->GetPointer(0); + bOk = pValues != NULL && writePod(oFile, oFrame.m_dTime) && + writeAll(oFile, reinterpret_cast(pValues), + nFrameBytes); + } + bOk = bOk && oFile.flush(); + oFile.close(); + if(!bOk) + { + QFile::remove(sFilePath); + return setError(pError, "Cannot write complete PEBI pressure frame file."); + } + return true; +} + +bool nmPebiResultSnapshotSerializer::writeWellCurves( + const nmPebiResultSnapshot& oSnapshot, + const QString& sFilePath, + QString* pError) +{ + QFile oFile(sFilePath); + if(!oFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) + { + return setError(pError, "Cannot create PEBI well curve file."); + } + const quint32 nWellCount = static_cast(oSnapshot.m_vecWells.size()); + bool bOk = writeAll(oFile, g_aCurvesMagic, 8) && + writePod(oFile, g_nBinaryFormatVersion) && + writePod(oFile, g_nEndianMarker) && writePod(oFile, nWellCount); + for(int nIndex = 0; bOk && nIndex < oSnapshot.m_vecWells.size(); ++nIndex) + { + const nmPebiResultWellSnapshot& oWell = oSnapshot.m_vecWells[nIndex]; + const QByteArray baUuid = oWell.m_sWellInstanceId.toUtf8(); + const quint32 nUuidBytes = static_cast(baUuid.size()); + bOk = nUuidBytes > 0 && nUuidBytes <= g_nMaximumUuidBytes && + writePod(oFile, nUuidBytes) && + writeAll(oFile, baUuid.constData(), nUuidBytes) && + writeCurve(oFile, oWell.m_oCurves.m_vecHistoryPressure) && + writeCurve(oFile, oWell.m_oCurves.m_vecHistoryLogLog) && + writeCurve(oFile, oWell.m_oCurves.m_vecHistorySemiLog) && + writeCurve(oFile, oWell.m_oCurves.m_vecResultPressure) && + writeCurve(oFile, oWell.m_oCurves.m_vecResultLogLog) && + writeCurve(oFile, oWell.m_oCurves.m_vecResultSemiLog); + } + bOk = bOk && oFile.flush(); + oFile.close(); + if(!bOk) + { + QFile::remove(sFilePath); + return setError(pError, "Cannot write complete PEBI well curve file."); + } + return true; +} + +bool nmPebiResultSnapshotSerializer::save( + const QSharedPointer& pSnapshot, + const QString& sWindowDirectory, + nmNumericalFileReference& oSnapshotJsonReference, + QString* pError) +{ + if(pError != NULL) + { + pError->clear(); + } + if(pSnapshot.isNull() || !pSnapshot->m_bComplete || + pSnapshot->m_pResultGrid == NULL) + { + return setError(pError, "Cannot save an incomplete PEBI result snapshot."); + } + + try + { + const QString sSnapshotDirectory = QDir(sWindowDirectory).filePath("Snapshot"); + if(!QDir().mkpath(sSnapshotDirectory)) + { + return setError(pError, "Cannot create PEBI snapshot directory."); + } + const QString sGridPath = QDir(sWindowDirectory).filePath( + "Snapshot/ResultGrid.vtu"); + const QString sPressurePath = QDir(sWindowDirectory).filePath( + "Snapshot/PressureFrames.bin"); + const QString sCurvesPath = QDir(sWindowDirectory).filePath( + "Snapshot/WellCurves.bin"); + const QString sJsonPath = QDir(sWindowDirectory).filePath( + "Snapshot/Snapshot.json"); + + nmNumericalFileReference oGridReference; + nmNumericalFileReference oPressureReference; + nmNumericalFileReference oCurvesReference; + if(!nmNumericalResultPersistence::writeGrid( + pSnapshot->m_pResultGrid, sGridPath, pError) || + !nmNumericalResultPersistence::buildFileReference( + sGridPath, "Snapshot/ResultGrid.vtu", oGridReference) || + !writePressureFrames(*pSnapshot, sPressurePath, pError) || + !nmNumericalResultPersistence::buildFileReference( + sPressurePath, "Snapshot/PressureFrames.bin", + oPressureReference) || + !writeWellCurves(*pSnapshot, sCurvesPath, pError) || + !nmNumericalResultPersistence::buildFileReference( + sCurvesPath, "Snapshot/WellCurves.bin", oCurvesReference)) + { + return false; + } + + rapidjson::Document oDocument; + oDocument.SetObject(); + rapidjson::Document::AllocatorType& oAllocator = + oDocument.GetAllocator(); + oDocument.AddMember("SnapshotFormatVersion", 1, oAllocator); + oDocument.AddMember("SnapshotId", + toJsonString(pSnapshot->m_sSnapshotId, oAllocator), oAllocator); + oDocument.AddMember("GridInputRevision", + pSnapshot->m_nGridInputRevision, oAllocator); + oDocument.AddMember("ResultInputRevision", + pSnapshot->m_nResultInputRevision, oAllocator); + oDocument.AddMember("ResultCellCount", + static_cast(pSnapshot->m_pResultGrid->GetNumberOfCells()), + oAllocator); + oDocument.AddMember("PressureFrameCount", + static_cast(pSnapshot->m_vecPressureFrames.size()), + oAllocator); + oDocument.AddMember("WellCount", + static_cast(pSnapshot->m_vecWells.size()), oAllocator); + oDocument.AddMember("ScalarMinimum", pSnapshot->m_dScalarMin, oAllocator); + oDocument.AddMember("ScalarMaximum", pSnapshot->m_dScalarMax, oAllocator); + addFileReference(oDocument, "ResultGrid", oGridReference, oAllocator); + addFileReference(oDocument, "PressureFrames", oPressureReference, oAllocator); + addFileReference(oDocument, "WellCurves", oCurvesReference, oAllocator); + + rapidjson::Value oSlots(rapidjson::kArrayType); + for(int nIndex = 0; nIndex < pSnapshot->m_vecSolverSlots.size(); ++nIndex) + { + const nmPebiResultSolverSlot& oSlot = + pSnapshot->m_vecSolverSlots[nIndex]; + rapidjson::Value oJson(rapidjson::kObjectType); + oJson.AddMember("SolverIndex", oSlot.m_nSolverIndex, oAllocator); + oJson.AddMember("EntryKind", static_cast(oSlot.m_eEntryKind), oAllocator); + oJson.AddMember("WellInstanceId", + toJsonString(oSlot.m_sWellInstanceId, oAllocator), oAllocator); + oJson.AddMember("WellCode", + toJsonString(oSlot.m_sWellCode, oAllocator), oAllocator); + oJson.AddMember("WellType", static_cast(oSlot.m_eWellType), oAllocator); + oSlots.PushBack(oJson, oAllocator); + } + oDocument.AddMember("SolverSlots", oSlots, oAllocator); + + rapidjson::Value oWells(rapidjson::kArrayType); + for(int nIndex = 0; nIndex < pSnapshot->m_vecWells.size(); ++nIndex) + { + const nmPebiResultWellSnapshot& oWell = pSnapshot->m_vecWells[nIndex]; + rapidjson::Value oJson(rapidjson::kObjectType); + oJson.AddMember("WellInstanceId", toJsonString( + oWell.m_sWellInstanceId, oAllocator), oAllocator); + oJson.AddMember("WellCode", toJsonString( + oWell.m_sWellCode, oAllocator), oAllocator); + oJson.AddMember("WellName", toJsonString( + oWell.m_sWellName, oAllocator), oAllocator); + oJson.AddMember("WellType", static_cast(oWell.m_eWellType), oAllocator); + oJson.AddMember("WellMode", static_cast(oWell.m_eWellMode), oAllocator); + oJson.AddMember("X", oWell.m_oLocation.x(), oAllocator); + oJson.AddMember("Y", oWell.m_oLocation.y(), oAllocator); + oJson.AddMember("HasPerforation", oWell.m_bHasPerforation, oAllocator); + oJson.AddMember("HasSkin", oWell.m_bHasSkin, oAllocator); + oJson.AddMember("HasDfc", oWell.m_bHasDfc, oAllocator); + oJson.AddMember("Radius", oWell.m_dRadius, oAllocator); + oJson.AddMember("WellboreStorage", oWell.m_dWellboreStorage, oAllocator); + oJson.AddMember("Skin", oWell.m_dSkin, oAllocator); + oJson.AddMember("Dfc", oWell.m_dDfc, oAllocator); + oWells.PushBack(oJson, oAllocator); + } + oDocument.AddMember("Wells", oWells, oAllocator); + + rapidjson::Value oDisplayWells(rapidjson::kArrayType); + for(int nIndex = 0; + nIndex < pSnapshot->m_listDisplayWellInstanceIds.size(); ++nIndex) + { + oDisplayWells.PushBack(toJsonString( + pSnapshot->m_listDisplayWellInstanceIds[nIndex], oAllocator), + oAllocator); + } + oDocument.AddMember("DisplayWellInstanceIds", oDisplayWells, oAllocator); + + const nmPebiResultReservoirParameters& oReservoir = + pSnapshot->m_oReservoirParameters; + rapidjson::Value oReservoirJson(rapidjson::kObjectType); + oReservoirJson.AddMember("Pi", oReservoir.m_dInitialPressure, oAllocator); + oReservoirJson.AddMember("K", oReservoir.m_dPermeability, oAllocator); + oReservoirJson.AddMember("h", oReservoir.m_dThickness, oAllocator); + oReservoirJson.AddMember("phi", oReservoir.m_dPorosity, oAllocator); + oReservoirJson.AddMember("Cti", oReservoir.m_dTotalCompressibility, oAllocator); + oReservoirJson.AddMember("Cf", oReservoir.m_dRockCompressibility, oAllocator); + oReservoirJson.AddMember("Soi", oReservoir.m_dOilSaturation, oAllocator); + oReservoirJson.AddMember("Sgi", oReservoir.m_dGasSaturation, oAllocator); + oReservoirJson.AddMember("Swi", oReservoir.m_dWaterSaturation, oAllocator); + oDocument.AddMember("Reservoir", oReservoirJson, oAllocator); + + const nmPebiResultPvtParameters& oPvt = pSnapshot->m_oPvtParameters; + rapidjson::Value oPvtJson(rapidjson::kObjectType); + oPvtJson.AddMember("HasBubblePoint", oPvt.m_bHasBubblePoint, oAllocator); + oPvtJson.AddMember("BubblePoint", oPvt.m_dBubblePoint, oAllocator); + oPvtJson.AddMember("ConstantBo", oPvt.m_dConstantBo, oAllocator); + oPvtJson.AddMember("ConstantMiuo", oPvt.m_dConstantMiuo, oAllocator); + oPvtJson.AddMember("ConstantBg", oPvt.m_dConstantBg, oAllocator); + oPvtJson.AddMember("ConstantMiug", oPvt.m_dConstantMiug, oAllocator); + oPvtJson.AddMember("ConstantBw", oPvt.m_dConstantBw, oAllocator); + oPvtJson.AddMember("ConstantMiuw", oPvt.m_dConstantMiuw, oAllocator); +#define NM_ADD_PVT_VECTOR(Name) addDoubleVector(oPvtJson, #Name, oPvt.m_vec##Name, oAllocator) + NM_ADD_PVT_VECTOR(Pressure); NM_ADD_PVT_VECTOR(Rso); + NM_ADD_PVT_VECTOR(Bo); NM_ADD_PVT_VECTOR(Co); + NM_ADD_PVT_VECTOR(Miuo); NM_ADD_PVT_VECTOR(Rouo); + NM_ADD_PVT_VECTOR(Rv); NM_ADD_PVT_VECTOR(Bg); + NM_ADD_PVT_VECTOR(Cg); NM_ADD_PVT_VECTOR(Miug); + NM_ADD_PVT_VECTOR(Roug); NM_ADD_PVT_VECTOR(Z); + NM_ADD_PVT_VECTOR(Rsw); NM_ADD_PVT_VECTOR(Bw); + NM_ADD_PVT_VECTOR(Cw); NM_ADD_PVT_VECTOR(Miuw); + NM_ADD_PVT_VECTOR(Rouw); NM_ADD_PVT_VECTOR(V); + NM_ADD_PVT_VECTOR(KkInitial); NM_ADD_PVT_VECTOR(CfCfInitial); + NM_ADD_PVT_VECTOR(So); NM_ADD_PVT_VECTOR(Kro); + NM_ADD_PVT_VECTOR(Sg); NM_ADD_PVT_VECTOR(Krg); + NM_ADD_PVT_VECTOR(Sw); NM_ADD_PVT_VECTOR(Krw); +#undef NM_ADD_PVT_VECTOR + oDocument.AddMember("Pvt", oPvtJson, oAllocator); + + const nmPebiResultSolverSettings& oSettings = + pSnapshot->m_oSolverSettings; + rapidjson::Value oSettingsJson(rapidjson::kObjectType); + oSettingsJson.AddMember("SolverModelType", oSettings.m_nSolverModelType, oAllocator); + oSettingsJson.AddMember("PebiSolverType", oSettings.m_nPebiSolverType, oAllocator); + oSettingsJson.AddMember("OmpThreads", oSettings.m_nOmpThreads, oAllocator); + oSettingsJson.AddMember("IluReuseSteps", oSettings.m_nIluReuseSteps, oAllocator); + oSettingsJson.AddMember("GridControl", oSettings.m_dGridControl, oAllocator); + oSettingsJson.AddMember("HasTimeStepSettings", oSettings.m_bHasTimeStepSettings, oAllocator); + oSettingsJson.AddMember("TimeGrowthExponent", oSettings.m_dTimeGrowthExponent, oAllocator); + oSettingsJson.AddMember("MinDeltaT", oSettings.m_dMinDeltaT, oAllocator); + oSettingsJson.AddMember("MaxDeltaT", oSettings.m_dMaxDeltaT, oAllocator); + oDocument.AddMember("SolverSettings", oSettingsJson, oAllocator); + + if(!nmDataJsonTools::WriteDomToFile(oDocument, sJsonPath) || + !nmNumericalResultPersistence::buildFileReference( + sJsonPath, "Snapshot/Snapshot.json", + oSnapshotJsonReference) || + !validate(sWindowDirectory, oSnapshotJsonReference, pError)) + { + return false; + } + return true; + } + catch(const std::bad_alloc&) + { + return setError(pError, "Not enough memory to save PEBI result snapshot."); + } +} + +bool nmPebiResultSnapshotSerializer::validate( + const QString& sWindowDirectory, + const nmNumericalFileReference& oSnapshotJsonReference, + QString* pError) +{ + if(pError != NULL) + { + pError->clear(); + } + QString sJsonPath; + if(!nmNumericalResultPersistence::validateFileReference( + sWindowDirectory, oSnapshotJsonReference, + &sJsonPath, pError)) + { + return false; + } + rapidjson::Document oDocument; + nmNumericalFileReference oGridReference; + nmNumericalFileReference oPressureReference; + nmNumericalFileReference oCurvesReference; + quint64 nCellCount = 0; + quint32 nFrameCount = 0; + quint32 nWellCount = 0; + if(!parseSnapshotJson(sJsonPath, oDocument, oGridReference, + oPressureReference, oCurvesReference, nCellCount, + nFrameCount, nWellCount, pError)) + { + return false; + } + + QString sGridPath; + QString sPressurePath; + QString sCurvesPath; + if(!nmNumericalResultPersistence::validateFileReference( + sWindowDirectory, oGridReference, &sGridPath, pError) || + !nmNumericalResultPersistence::validateFileReference( + sWindowDirectory, oPressureReference, &sPressurePath, pError) || + !nmNumericalResultPersistence::validateFileReference( + sWindowDirectory, oCurvesReference, &sCurvesPath, pError) || + !readPressureFrames(sPressurePath, nCellCount, nFrameCount, + NULL, pError) || + !readWellCurves(sCurvesPath, nWellCount, NULL, pError)) + { + return false; + } + return true; +} + +bool nmPebiResultSnapshotSerializer::load( + const QString& sWindowDirectory, + const nmNumericalFileReference& oSnapshotJsonReference, + QSharedPointer& pCandidate, + QString* pError) +{ + pCandidate.clear(); + if(pError != NULL) + { + pError->clear(); + } + try + { + QString sJsonPath; + if(!nmNumericalResultPersistence::validateFileReference( + sWindowDirectory, oSnapshotJsonReference, + &sJsonPath, pError)) + { + return false; + } + rapidjson::Document oDocument; + nmNumericalFileReference oGridReference; + nmNumericalFileReference oPressureReference; + nmNumericalFileReference oCurvesReference; + quint64 nCellCount = 0; + quint32 nFrameCount = 0; + quint32 nWellCount = 0; + if(!parseSnapshotJson(sJsonPath, oDocument, oGridReference, + oPressureReference, oCurvesReference, nCellCount, + nFrameCount, nWellCount, pError)) + { + return false; + } + QString sGridPath; + QString sPressurePath; + QString sCurvesPath; + if(!nmNumericalResultPersistence::validateFileReference( + sWindowDirectory, oGridReference, &sGridPath, pError) || + !nmNumericalResultPersistence::validateFileReference( + sWindowDirectory, oPressureReference, &sPressurePath, pError) || + !nmNumericalResultPersistence::validateFileReference( + sWindowDirectory, oCurvesReference, &sCurvesPath, pError)) + { + return false; + } + + vtkSmartPointer pGrid; + QMap mapCurves; + if(!nmNumericalResultPersistence::readGrid(sGridPath, pGrid, pError) || + static_cast(pGrid->GetNumberOfCells()) != nCellCount || + !readWellCurves(sCurvesPath, nWellCount, &mapCurves, pError)) + { + return setError(pError, pError != NULL && !pError->isEmpty() + ? *pError : "PEBI snapshot grid or curves are invalid."); + } + + nmPebiResultSnapshotBuilder oBuilder; + if(!oDocument.HasMember("SnapshotId") || + !oDocument["SnapshotId"].IsString() || + !oDocument.HasMember("GridInputRevision") || + !oDocument["GridInputRevision"].IsUint64() || + !oDocument.HasMember("ResultInputRevision") || + !oDocument["ResultInputRevision"].IsUint64() || + !oBuilder.setSnapshotId(QString::fromUtf8( + oDocument["SnapshotId"].GetString())) || + !oBuilder.setInputRevisions( + oDocument["GridInputRevision"].GetUint64(), + oDocument["ResultInputRevision"].GetUint64()) || + !oBuilder.takeResultGrid(pGrid) || pGrid != NULL || + !readPressureFrames(sPressurePath, nCellCount, nFrameCount, + &oBuilder, pError)) + { + return setError(pError, pError != NULL && !pError->isEmpty() + ? *pError : "PEBI snapshot identity or pressure frames are invalid."); + } + + double dScalarMinimum = 0.0; + double dScalarMaximum = 0.0; + if(!readRequiredDouble(oDocument, "ScalarMinimum", dScalarMinimum) || + !readRequiredDouble(oDocument, "ScalarMaximum", dScalarMaximum) || + !oBuilder.setScalarRange(dScalarMinimum, dScalarMaximum) || + !oDocument.HasMember("SolverSlots") || + !oDocument["SolverSlots"].IsArray() || + oDocument["SolverSlots"].Size() > g_nMaximumWellCount + 100000u) + { + return setError(pError, "PEBI snapshot scalar range or solver slots are invalid."); + } + const rapidjson::Value& oSlots = oDocument["SolverSlots"]; + for(rapidjson::SizeType nIndex = 0; nIndex < oSlots.Size(); ++nIndex) + { + const rapidjson::Value& oJson = oSlots[nIndex]; + nmPebiResultSolverSlot oSlot; + int nEntryKind = 0; + int nWellType = 0; + if(!readRequiredInt(oJson, "SolverIndex", oSlot.m_nSolverIndex) || + !readRequiredInt(oJson, "EntryKind", nEntryKind) || + !readRequiredInt(oJson, "WellType", nWellType) || + !oJson.HasMember("WellInstanceId") || + !oJson["WellInstanceId"].IsString() || + !oJson.HasMember("WellCode") || !oJson["WellCode"].IsString()) + { + return setError(pError, "PEBI snapshot solver slot is invalid."); + } + oSlot.m_eEntryKind = static_cast(nEntryKind); + oSlot.m_eWellType = static_cast(nWellType); + oSlot.m_sWellInstanceId = QString::fromUtf8( + oJson["WellInstanceId"].GetString()); + oSlot.m_sWellCode = QString::fromUtf8(oJson["WellCode"].GetString()); + if(!oBuilder.addSolverSlot(oSlot)) + { + return setError(pError, "Cannot restore PEBI snapshot solver slot."); + } + } + + if(!oDocument.HasMember("Wells") || !oDocument["Wells"].IsArray() || + oDocument["Wells"].Size() != nWellCount) + { + return setError(pError, "PEBI snapshot well directory is invalid."); + } + const rapidjson::Value& oWells = oDocument["Wells"]; + QSet setJsonWellIds; + for(rapidjson::SizeType nIndex = 0; nIndex < oWells.Size(); ++nIndex) + { + const rapidjson::Value& oJson = oWells[nIndex]; + nmPebiResultWellSnapshot oWell; + int nWellType = 0; + int nWellMode = 0; + if(!oJson.IsObject() || + !oJson.HasMember("WellInstanceId") || + !oJson["WellInstanceId"].IsString() || + !oJson.HasMember("WellCode") || !oJson["WellCode"].IsString() || + !oJson.HasMember("WellName") || !oJson["WellName"].IsString() || + !readRequiredInt(oJson, "WellType", nWellType) || + !readRequiredInt(oJson, "WellMode", nWellMode) || + !readRequiredDouble(oJson, "X", oWell.m_oLocation.rx()) || + !readRequiredDouble(oJson, "Y", oWell.m_oLocation.ry()) || + !readRequiredBool(oJson, "HasPerforation", oWell.m_bHasPerforation) || + !readRequiredBool(oJson, "HasSkin", oWell.m_bHasSkin) || + !readRequiredBool(oJson, "HasDfc", oWell.m_bHasDfc) || + !readRequiredDouble(oJson, "Radius", oWell.m_dRadius) || + !readRequiredDouble(oJson, "WellboreStorage", oWell.m_dWellboreStorage) || + !readRequiredDouble(oJson, "Skin", oWell.m_dSkin) || + !readRequiredDouble(oJson, "Dfc", oWell.m_dDfc)) + { + return setError(pError, "PEBI snapshot well metadata are invalid."); + } + oWell.m_sWellInstanceId = QString::fromUtf8( + oJson["WellInstanceId"].GetString()); + oWell.m_sWellCode = QString::fromUtf8(oJson["WellCode"].GetString()); + oWell.m_sWellName = QString::fromUtf8(oJson["WellName"].GetString()); + oWell.m_eWellType = static_cast(nWellType); + oWell.m_eWellMode = static_cast(nWellMode); + if(setJsonWellIds.contains(oWell.m_sWellInstanceId) || + !mapCurves.contains(oWell.m_sWellInstanceId)) + { + return setError(pError, "PEBI snapshot well curve mapping is invalid."); + } + setJsonWellIds.insert(oWell.m_sWellInstanceId); + oWell.m_oCurves = mapCurves.take(oWell.m_sWellInstanceId); + if(!oBuilder.takeWell(oWell)) + { + return setError(pError, "Cannot restore PEBI snapshot well."); + } + } + if(!mapCurves.isEmpty()) + { + return setError(pError, "PEBI well curve file contains unreferenced wells."); + } + + if(!oDocument.HasMember("DisplayWellInstanceIds") || + !oDocument["DisplayWellInstanceIds"].IsArray()) + { + return setError(pError, "PEBI display well list is missing."); + } + QStringList listDisplayWellIds; + const rapidjson::Value& oDisplay = oDocument["DisplayWellInstanceIds"]; + for(rapidjson::SizeType nIndex = 0; nIndex < oDisplay.Size(); ++nIndex) + { + if(!oDisplay[nIndex].IsString()) + { + return setError(pError, "PEBI display well list is invalid."); + } + listDisplayWellIds.append(QString::fromUtf8( + oDisplay[nIndex].GetString())); + } + if(!oBuilder.setDisplayWellInstanceIds(listDisplayWellIds)) + { + return setError(pError, "Cannot restore PEBI display well list."); + } + + if(!oDocument.HasMember("Reservoir") || + !oDocument["Reservoir"].IsObject()) + { + return setError(pError, "PEBI reservoir snapshot is missing."); + } + const rapidjson::Value& oReservoirJson = oDocument["Reservoir"]; + nmPebiResultReservoirParameters oReservoir; + if(!readRequiredDouble(oReservoirJson, "Pi", oReservoir.m_dInitialPressure) || + !readRequiredDouble(oReservoirJson, "K", oReservoir.m_dPermeability) || + !readRequiredDouble(oReservoirJson, "h", oReservoir.m_dThickness) || + !readRequiredDouble(oReservoirJson, "phi", oReservoir.m_dPorosity) || + !readRequiredDouble(oReservoirJson, "Cti", oReservoir.m_dTotalCompressibility) || + !readRequiredDouble(oReservoirJson, "Cf", oReservoir.m_dRockCompressibility) || + !readRequiredDouble(oReservoirJson, "Soi", oReservoir.m_dOilSaturation) || + !readRequiredDouble(oReservoirJson, "Sgi", oReservoir.m_dGasSaturation) || + !readRequiredDouble(oReservoirJson, "Swi", oReservoir.m_dWaterSaturation) || + !oBuilder.setReservoirParameters(oReservoir)) + { + return setError(pError, "PEBI reservoir snapshot is invalid."); + } + + if(!oDocument.HasMember("Pvt") || !oDocument["Pvt"].IsObject()) + { + return setError(pError, "PEBI PVT snapshot is missing."); + } + const rapidjson::Value& oPvtJson = oDocument["Pvt"]; + nmPebiResultPvtParameters oPvt; + if(!readRequiredBool(oPvtJson, "HasBubblePoint", oPvt.m_bHasBubblePoint) || + !readRequiredDouble(oPvtJson, "BubblePoint", oPvt.m_dBubblePoint) || + !readRequiredDouble(oPvtJson, "ConstantBo", oPvt.m_dConstantBo) || + !readRequiredDouble(oPvtJson, "ConstantMiuo", oPvt.m_dConstantMiuo) || + !readRequiredDouble(oPvtJson, "ConstantBg", oPvt.m_dConstantBg) || + !readRequiredDouble(oPvtJson, "ConstantMiug", oPvt.m_dConstantMiug) || + !readRequiredDouble(oPvtJson, "ConstantBw", oPvt.m_dConstantBw) || + !readRequiredDouble(oPvtJson, "ConstantMiuw", oPvt.m_dConstantMiuw)) + { + return setError(pError, "PEBI PVT constants are invalid."); + } +#define NM_READ_PVT_VECTOR(Name) readDoubleVector(oPvtJson, #Name, oPvt.m_vec##Name) + if(!NM_READ_PVT_VECTOR(Pressure) || !NM_READ_PVT_VECTOR(Rso) || + !NM_READ_PVT_VECTOR(Bo) || !NM_READ_PVT_VECTOR(Co) || + !NM_READ_PVT_VECTOR(Miuo) || !NM_READ_PVT_VECTOR(Rouo) || + !NM_READ_PVT_VECTOR(Rv) || !NM_READ_PVT_VECTOR(Bg) || + !NM_READ_PVT_VECTOR(Cg) || !NM_READ_PVT_VECTOR(Miug) || + !NM_READ_PVT_VECTOR(Roug) || !NM_READ_PVT_VECTOR(Z) || + !NM_READ_PVT_VECTOR(Rsw) || !NM_READ_PVT_VECTOR(Bw) || + !NM_READ_PVT_VECTOR(Cw) || !NM_READ_PVT_VECTOR(Miuw) || + !NM_READ_PVT_VECTOR(Rouw) || !NM_READ_PVT_VECTOR(V) || + !NM_READ_PVT_VECTOR(KkInitial) || !NM_READ_PVT_VECTOR(CfCfInitial) || + !NM_READ_PVT_VECTOR(So) || !NM_READ_PVT_VECTOR(Kro) || + !NM_READ_PVT_VECTOR(Sg) || !NM_READ_PVT_VECTOR(Krg) || + !NM_READ_PVT_VECTOR(Sw) || !NM_READ_PVT_VECTOR(Krw) || + !oBuilder.setPvtParameters(oPvt)) + { +#undef NM_READ_PVT_VECTOR + return setError(pError, "PEBI PVT arrays are invalid."); + } +#undef NM_READ_PVT_VECTOR + + if(!oDocument.HasMember("SolverSettings") || + !oDocument["SolverSettings"].IsObject()) + { + return setError(pError, "PEBI solver settings are missing."); + } + const rapidjson::Value& oSettingsJson = oDocument["SolverSettings"]; + nmPebiResultSolverSettings oSettings; + if(!readRequiredInt(oSettingsJson, "SolverModelType", oSettings.m_nSolverModelType) || + !readRequiredInt(oSettingsJson, "PebiSolverType", oSettings.m_nPebiSolverType) || + !readRequiredInt(oSettingsJson, "OmpThreads", oSettings.m_nOmpThreads) || + !readRequiredInt(oSettingsJson, "IluReuseSteps", oSettings.m_nIluReuseSteps) || + !readRequiredDouble(oSettingsJson, "GridControl", oSettings.m_dGridControl) || + !readRequiredBool(oSettingsJson, "HasTimeStepSettings", oSettings.m_bHasTimeStepSettings) || + !readRequiredDouble(oSettingsJson, "TimeGrowthExponent", oSettings.m_dTimeGrowthExponent) || + !readRequiredDouble(oSettingsJson, "MinDeltaT", oSettings.m_dMinDeltaT) || + !readRequiredDouble(oSettingsJson, "MaxDeltaT", oSettings.m_dMaxDeltaT) || + !oBuilder.setSolverSettings(oSettings)) + { + return setError(pError, "PEBI solver settings are invalid."); + } + + QString sBuilderError; + if(!oBuilder.finalize(&sBuilderError)) + { + return setError(pError, sBuilderError); + } + pCandidate = oBuilder.takeCandidate(); + if(pCandidate.isNull()) + { + return setError(pError, "Cannot take the loaded PEBI snapshot candidate."); + } + return true; + } + catch(const std::bad_alloc&) + { + pCandidate.clear(); + return setError(pError, "Not enough memory to load PEBI result snapshot."); + } +} diff --git a/Src/nmNum/nmSubWnd/nmSubWndUtils.cpp b/Src/nmNum/nmSubWnd/nmSubWndUtils.cpp index f585005a..1e881119 100644 --- a/Src/nmNum/nmSubWnd/nmSubWndUtils.cpp +++ b/Src/nmNum/nmSubWnd/nmSubWndUtils.cpp @@ -1,6 +1,8 @@ #include "zxLogInstance.h" #include "iRibbonXmlCmd.h" #include +#include +#include #include #include #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(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(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(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);