DPsim
Loading...
Searching...
No Matches
RealTimeDataLogger.cpp
Go to the documentation of this file.
1/* A data logger for real-time simulation data logging.
2 *
3 * Author: Niklas Eiling <niklas.eiling@eonerc.rwth-aachen.de>
4 * SPDX-FileCopyrightText: 2024 Niklas Eiling <niklas.eiling@eonerc.rwth-aachen.de>
5 * SPDX-License-Identifier: Apache-2.0
6 */
7
8#include <algorithm>
9#include <charconv>
10#include <iomanip>
11#include <memory>
12#include <string>
13
15
17#include <dpsim-models/Logger.h>
18
19using namespace DPsim;
20
21RealTimeDataLogger::RealTimeDataLogger(std::filesystem::path &filename,
22 size_t rowNumber)
23 : DataLoggerInterface(), mFilename(filename), mRowNumber(rowNumber),
25
26RealTimeDataLogger::RealTimeDataLogger(std::filesystem::path &filename,
27 Real finalTime, Real timeStep)
28 : DataLoggerInterface(), mFilename(filename),
29 // Include the initial t=0 row and reserve one more row for an endpoint
30 // that can be reached exactly by the simulation's floating-point loop.
31 mRowNumber(static_cast<size_t>(finalTime / timeStep + 0.5) + 1),
33
35 double mb_size =
36 static_cast<double>(mRowNumber) * (mAttributes.size() + 1) * sizeof(Real);
37 auto log = CPS::Logger::get("RealTimeDataLogger", CPS::Logger::Level::off,
38 CPS::Logger::Level::info);
39 SPDLOG_LOGGER_INFO(
40 log,
41 "Preallocating memory for real-time data logger: {} rows for {} "
42 "attributes ({} MB)",
43 mRowNumber, mAttributes.size(), mb_size / (1024 * 1024));
44 // We are doing real time so preallocate everything
46 for (auto &it : mAttributeData) {
47 // We have to add one to the size because we also log the time
48 it.resize(mAttributes.size() + 1);
49 }
50}
51
53 auto log = CPS::Logger::get("RealTimeDataLogger", CPS::Logger::Level::off,
54 CPS::Logger::Level::info);
55 SPDLOG_LOGGER_INFO(
56 log, "Stopping real-time data logger. Writing memory to file {}",
57 mFilename.string());
58
59 const auto parent = mFilename.parent_path();
60 if (!parent.empty()) {
61 std::error_code ec;
62 std::filesystem::create_directories(parent, ec);
63 if (ec) {
64 throw std::runtime_error("Cannot create log directory '" +
65 parent.string() + "': " + ec.message());
66 }
67 }
68
69 auto mLogFile =
70 std::ofstream(mFilename, std::ios_base::out | std::ios_base::trunc);
71 if (!mLogFile.is_open()) {
72 throw std::runtime_error("Cannot open log file " + mFilename.string());
73 }
74
75 mLogFile << std::right << std::setw(14) << "time";
76 for (auto it : mAttributes)
77 mLogFile << ", " << std::right << std::setw(13) << it.first;
78 mLogFile << '\n';
79
80 constexpr size_t rowsPerWrite = 256;
81 std::string buffer;
82 buffer.reserve(rowsPerWrite * (mAttributes.size() + 1) * 16);
83 auto appendValue = [&buffer](Real value, std::chars_format format,
84 int precision, size_t width) {
85 char formatted[128];
86 const auto result = std::to_chars(formatted, formatted + sizeof(formatted),
87 value, format, precision);
88 if (result.ec != std::errc())
89 throw std::runtime_error("Failed to format real-time logger value.");
90 const size_t length = static_cast<size_t>(result.ptr - formatted);
91 if (length < width)
92 buffer.append(width - length, ' ');
93 buffer.append(formatted, result.ptr);
94 };
95
96 for (size_t rowIdx = 0; rowIdx < mRowsWritten; ++rowIdx) {
97 const auto &row = mAttributeData[rowIdx];
98 appendValue(row[0], std::chars_format::scientific, 6, 14);
99 for (size_t i = 1; i < row.size(); ++i) {
100 buffer.append(", ");
101 appendValue(row[i], std::chars_format::fixed, 6, 13);
102 }
103 buffer.push_back('\n');
104 if ((rowIdx + 1) % rowsPerWrite == 0) {
105 mLogFile.write(buffer.data(),
106 static_cast<std::streamsize>(buffer.size()));
107 buffer.clear();
108 }
109 }
110 if (!buffer.empty())
111 mLogFile.write(buffer.data(), static_cast<std::streamsize>(buffer.size()));
112 mLogFile.close();
113 SPDLOG_LOGGER_INFO(log, "Finished writing real-time data log to file {}",
114 mFilename.string());
115}
116
117void RealTimeDataLogger::log(Real time, Int timeStepCount) {
118 // Simulation::start logs the t=0 state with count 0; the first solved step
119 // also has count 0, but occurs at t=dt. Keep both rows by offsetting all
120 // positive-time samples by one.
121 if (timeStepCount < 0) {
122 throw std::runtime_error(
123 "RealTimeDataLogger: timeStepCount out of bounds. Please verify the "
124 "logger was initialized correctly.");
125 }
126 const size_t row = static_cast<size_t>(timeStepCount) + (time > 0 ? 1 : 0);
127 mCurrentRow = row;
128 if (row >= mRowNumber) {
129 throw std::runtime_error(
130 "RealTimeDataLogger: timeStepCount out of bounds. Please verify the "
131 "logger was initialized correctly.");
132 }
133 if (mAttributeData.size() != mRowNumber ||
134 mAttributeData[row].size() != mAttributes.size() + 1) {
135 throw std::runtime_error(
136 "RealTimeDataLogger: Attribute data size mismatch");
137 }
138 mAttributeData[row][0] = time;
139 mRowsWritten = std::max(mRowsWritten, row + 1);
141
142 for (auto &it : mAttributes) {
143 auto base = it.second.getPtr(); // std::shared_ptr<CPS::AttributeBase>
144
145 if (it.second->getType() == typeid(Real)) {
146 auto attr = std::dynamic_pointer_cast<CPS::Attribute<Real>>(base);
147 if (!attr) { /* skip */
148 continue;
149 }
150 mAttributeData[row][mCurrentAttribute++] = attr->get();
151 } else if (it.second->getType() == typeid(Int)) {
152 auto attr = std::dynamic_pointer_cast<CPS::Attribute<Int>>(base);
153 if (!attr) { /* skip */
154 continue;
155 }
156 mAttributeData[row][mCurrentAttribute++] = attr->get();
157 }
158 }
159}
160
161void RealTimeDataLogger::Step::execute(Real time, Int timeStepCount) {
162 mLogger.log(time, timeStepCount);
163}
164
166 return std::make_shared<RealTimeDataLogger::Step>(*this);
167}
static Log get(const std::string &name, Level filelevel=Level::info, Level clilevel=Level::off)
Definition Logger.cpp:139
std::shared_ptr< Task > Ptr
Definition Task.h:27
std::map< String, CPS::AttributeBase::Ptr > mAttributes
void execute(Real time, Int timeStepCount)
virtual void stop() override
RealTimeDataLogger(std::filesystem::path &filename, Real finalTime, Real timeStep)
virtual CPS::Task::Ptr getTask() override
virtual void start() override
virtual void log(Real time, Int timeStepCount) override
std::filesystem::path mFilename
std::vector< std::vector< Real > > mAttributeData
CPS::Real Real
Definition Definitions.h:18
CPS::Int Int
Definition Definitions.h:22