File indexing completed on 2025-11-29 09:18:20
0001
0002
0003
0004
0005
0006
0007
0008
0009 #include "ActsExamples/Io/HepMC3/HepMC3Metadata.hpp"
0010
0011 #include "Acts/Utilities/Logger.hpp"
0012
0013 #include <fstream>
0014
0015 #include <nlohmann/json.hpp>
0016
0017 namespace ActsExamples::HepMC3Metadata {
0018
0019 static const std::string kEventCountKey = "num_events";
0020
0021 std::filesystem::path getSidecarPath(const std::filesystem::path& hepmc3File) {
0022 return hepmc3File.string() + ".json";
0023 }
0024
0025 std::optional<HepMC3Metadata> readSidecar(
0026 const std::filesystem::path& hepmc3File) {
0027 auto sidecarPath = getSidecarPath(hepmc3File);
0028
0029 if (!std::filesystem::exists(sidecarPath)) {
0030 return std::nullopt;
0031 }
0032
0033 try {
0034 std::ifstream file(sidecarPath);
0035 if (!file.is_open()) {
0036 return std::nullopt;
0037 }
0038
0039 nlohmann::json j;
0040 file >> j;
0041
0042 if (!j.contains(kEventCountKey) ||
0043 !j[kEventCountKey].is_number_unsigned()) {
0044 return std::nullopt;
0045 }
0046
0047 return HepMC3Metadata{.numEvents = j[kEventCountKey].get<std::size_t>()};
0048 } catch (...) {
0049
0050 return std::nullopt;
0051 }
0052 }
0053
0054 bool writeSidecar(const std::filesystem::path& hepmc3File,
0055 const HepMC3Metadata& metadata, const Acts::Logger& logger) {
0056 auto sidecarPath = getSidecarPath(hepmc3File);
0057 ACTS_DEBUG("Writing HepMC3 sidecar metadata to " << sidecarPath);
0058
0059 try {
0060 nlohmann::json j;
0061 j[kEventCountKey] = metadata.numEvents;
0062
0063 std::ofstream file(sidecarPath);
0064 if (!file.is_open()) {
0065 ACTS_DEBUG("Failed to open sidecar file for writing: " << sidecarPath);
0066 return false;
0067 }
0068
0069 file << j.dump(2);
0070 return file.good();
0071 } catch (...) {
0072 ACTS_DEBUG("Failed to write sidecar metadata file: " << sidecarPath);
0073
0074 return false;
0075 }
0076 }
0077
0078 }