MTCT
Design Automation and Optimization for ETCS Railway Networks
Loading...
Searching...
No Matches
GeneralSolver.hpp
Go to the documentation of this file.
1#ifndef CDA_RAIL_SOLVER_GENERALSOLVER_HPP
2#define CDA_RAIL_SOLVER_GENERALSOLVER_HPP
3
5#include "GeneralHelper.hpp"
6#include "nlohmann/json.hpp"
7#include "nlohmann/json_fwd.hpp"
9
10// NOLINTNEXTLINE(misc-include-cleaner)
11#include "gtest/gtest_prod.h"
12#include <chrono>
13#include <concepts>
14#include <cstdint>
15#include <exception>
16#include <filesystem>
17#include <fstream>
18#include <optional>
19#include <plog/Log.h>
20#include <string>
21#include <type_traits>
22#include <unordered_map>
23#include <utility>
24
25// If TEST_FRIENDS has value true, the corresponding test is friended to test
26// complex private functions.
27// This is not good practice. However, after consideration, it was decided that
28// - it is not reasonable to make the functions public
29// - they have a complexity that should be tested
30// - by only testing the overall solution, there is too much code tested at once
31#ifndef TEST_FRIENDS
32#define TEST_FRIENDS false
33#endif
34#if TEST_FRIENDS
35class GenPOMovingBlockAStarSolver_SolverDataExport_Test;
36#endif
37
38namespace cda_rail::solver {
51
63 std::string working_directory{};
64 std::string solution_subdirectory{"unnamed-experiment"};
65 std::optional<std::string> parameter_identifier{};
66 std::optional<double> evaluation_time_step{};
67};
68
76inline void write_solver_data(std::filesystem::path const& export_directory,
77 nlohmann::json const& solver_data) {
78 if (!is_directory_and_create(export_directory)) {
79 throw exceptions::ExportException("Could not create directory " +
80 export_directory.string());
81 }
82 std::ofstream data_file(export_directory / "solver_data.json");
83 if (!data_file.is_open()) {
85 "Could not open solver_data.json for writing");
86 }
87 data_file << solver_data << '\n';
88 if (!data_file) {
89 throw exceptions::ExportException("Failed to write solver_data.json");
90 }
91}
92
106template <typename T, typename S> class GeneralSolver {
107#if TEST_FRIENDS
108 FRIEND_TEST(::GenPOMovingBlockAStarSolver, SolverDataExport);
109#endif
110
111 static_assert(
112 std::is_base_of_v<cda_rail::instances::GeneralProblemInstance, T>,
113 "T must be a child of GeneralProblemInstance");
114 static_assert(
115 std::is_base_of_v<cda_rail::instances::SolGeneralProblemInstance, S>,
116 "S must be a child of SolGeneralProblemInstance<T>");
117
118protected:
120 decltype(std::chrono::high_resolution_clock::now()) m_start;
121 decltype(std::chrono::high_resolution_clock::now()) m_model_created;
122 decltype(std::chrono::high_resolution_clock::now()) m_model_solved;
123 int64_t m_create_time = 0;
124 int64_t m_solve_time = 0;
125 nlohmann::json m_solver_data;
126
127 template <typename... Args>
128 struct IsSingleInstanceArgument : std::false_type {};
129 template <typename Arg>
130 struct IsSingleInstanceArgument<Arg> : std::is_same<T, std::decay_t<Arg>> {};
131
142 void solve_init_general(bool debug_input, bool overwrite_severity) {
143 cda_rail::initialize_plog(debug_input, overwrite_severity);
144
145 m_start = std::chrono::high_resolution_clock::now();
146 }
147
151 GeneralSolver() = default;
157 explicit GeneralSolver(T instance) : m_instance(std::move(instance)) {}
164 template <typename... Args>
165 explicit GeneralSolver(Args&&... args)
166 requires(sizeof...(Args) > 0 && !IsSingleInstanceArgument<Args...>::value &&
167 std::constructible_from<T, Args...>)
168 : m_instance(std::forward<Args>(args)...) {}
169
177 struct FurtherData {
178 std::unordered_map<std::string, bool> bool_data;
179 std::unordered_map<std::string, int> integer_data;
180 std::unordered_map<std::string, double> double_data;
181 std::unordered_map<std::string, std::string> string_data;
182 };
183
189 [[nodiscard]] nlohmann::json
190 solver_data(FurtherData const& further_data) const {
191 nlohmann::json data;
192 data["model_creation_time"] =
194 data["model_solving_time"] =
196 data["total_time"] =
198 for (auto const& [key, value] : further_data.bool_data) {
199 data[concatenate_string_views({key, "_bool"})] = value;
200 }
201 for (auto const& [key, value] : further_data.integer_data) {
202 data[concatenate_string_views({key, "_int"})] = value;
203 }
204 for (auto const& [key, value] : further_data.double_data) {
205 data[concatenate_string_views({key, "_double"})] = value;
206 }
207 for (auto const& [key, value] : further_data.string_data) {
208 data[concatenate_string_views({key, "_string"})] = value;
209 }
210 return data;
211 }
212
220 void export_solver_data(std::filesystem::path const& export_directory,
221 FurtherData const& further_data = {}) {
222 write_solver_data(export_directory, solver_data(further_data));
223 }
224
242 std::optional<std::filesystem::path>
244 const GeneralSolutionSettings& solution_settings,
245 FurtherData const& further_data = {}) {
246 m_solver_data = solver_data(further_data);
247 if (solution_settings.export_option == GeneralExportOption::NoExport) {
248 return std::nullopt;
249 }
250
251 if constexpr (requires(S& sol, double dt) { sol.evaluate(dt); }) {
252 if (solution_settings.evaluation_time_step.has_value() &&
253 solution.has_solution()) {
254 // A failing evaluation must not cost the solution itself
255 // NOLINTBEGIN(cppcoreguidelines-pro-type-reinterpret-cast,readability-inconsistent-ifelse-braces)
256 try {
257 solution.evaluate(solution_settings.evaluation_time_step.value());
258 } catch (const std::exception& e) {
259 PLOGW << "Exporting the solution without evaluation, since it "
260 "failed: "
261 << e.what();
262 }
263 // NOLINTEND(cppcoreguidelines-pro-type-reinterpret-cast,readability-inconsistent-ifelse-braces)
264 }
265 }
266
267 const bool export_instance =
268 (solution_settings.export_option ==
270
271 auto export_path =
272 solution.get_export_path(solution_settings.working_directory,
273 solution_settings.solution_subdirectory,
274 solution_settings.parameter_identifier);
275 // The reinterpret_cast is a false positive stemming from the plog macro
276 // NOLINTBEGIN(cppcoreguidelines-pro-type-reinterpret-cast,readability-inconsistent-ifelse-braces)
277 PLOGI << "Saving solution to " << export_path.string();
278 // NOLINTEND(cppcoreguidelines-pro-type-reinterpret-cast,readability-inconsistent-ifelse-braces)
279 solution.export_solution(solution_settings.working_directory,
280 solution_settings.solution_subdirectory,
281 export_instance,
282 solution_settings.parameter_identifier);
283 write_solver_data(export_path, m_solver_data);
284
285 return export_path;
286 }
287
288public:
294 [[nodiscard]] const nlohmann::json& get_solver_data() const {
295 return m_solver_data;
296 }
297
302 [[nodiscard]] const T& get_instance() const { return m_instance; }
307 [[nodiscard]] T& editable_instance() { return m_instance; }
308
314 [[nodiscard]] S solve() { return solve(-1, false); };
323 [[nodiscard]] S solve(int time_limit, bool debug_input) {
324 return solve(time_limit, debug_input, true);
325 }
326
336 [[nodiscard]] virtual S solve(int time_limit, bool debug_input,
337 bool overwrite_severity) = 0;
338
340 virtual ~GeneralSolver() = default;
341};
342} // namespace cda_rail::solver
343
344#endif // CDA_RAIL_SOLVER_GENERALSOLVER_HPP
Thrown when export fails.
Definition CustomExceptions.hpp:63
nlohmann::json m_solver_data
Definition GeneralSolver.hpp:125
nlohmann::json solver_data(FurtherData const &further_data) const
Solver data, i.e., timing and further information (e.g. iterations, nodes, etc.), as written to solve...
Definition GeneralSolver.hpp:190
void solve_init_general(bool debug_input, bool overwrite_severity)
Initializes logging and records solver start time.
Definition GeneralSolver.hpp:142
virtual ~GeneralSolver()=default
Virtual destructor.
S solve()
Solves the problem instance using default configuration.
Definition GeneralSolver.hpp:314
decltype(std::chrono::high_resolution_clock::now()) m_model_created
Definition GeneralSolver.hpp:121
GeneralSolver(Args &&... args)
Constructs a GeneralSolver with arguments for the problem instance constructor.
Definition GeneralSolver.hpp:165
int64_t m_create_time
Definition GeneralSolver.hpp:123
decltype(std::chrono::high_resolution_clock::now()) m_model_solved
Definition GeneralSolver.hpp:122
int64_t m_solve_time
Definition GeneralSolver.hpp:124
virtual S solve(int time_limit, bool debug_input, bool overwrite_severity)=0
Solves the problem instance, which every solver implements.
std::optional< std::filesystem::path > export_general_solution(S &solution, const GeneralSolutionSettings &solution_settings, FurtherData const &further_data={})
Exports the solution together with the solver data if requested.
Definition GeneralSolver.hpp:243
GeneralSolver(T instance)
Constructs a solver from a problem instance.
Definition GeneralSolver.hpp:157
const nlohmann::json & get_solver_data() const
The solver data of the last solve, as written to solver_data.json if the solution is exported,...
Definition GeneralSolver.hpp:294
T m_instance
Definition GeneralSolver.hpp:119
const T & get_instance() const
Accesses the problem instance stored in this solver.
Definition GeneralSolver.hpp:302
decltype(std::chrono::high_resolution_clock::now()) m_start
Definition GeneralSolver.hpp:120
S solve(int time_limit, bool debug_input)
Solves the problem instance.
Definition GeneralSolver.hpp:323
void export_solver_data(std::filesystem::path const &export_directory, FurtherData const &further_data={})
Exports solver data, see solver_data, into solver_data.json.
Definition GeneralSolver.hpp:220
GeneralSolver()=default
Constructs a solver with a default-initialized problem instance.
T & editable_instance()
Provides mutable access to the problem instance.
Definition GeneralSolver.hpp:307
Definition CompletionHeuristic.hpp:10
void write_solver_data(std::filesystem::path const &export_directory, nlohmann::json const &solver_data)
Writes solver data, see GeneralSolver::get_solver_data, to solver_data.json in export_directory.
Definition GeneralSolver.hpp:76
GeneralExportOption
What a solver writes to disk once it is done.
Definition GeneralSolver.hpp:46
@ NoExport
Definition GeneralSolver.hpp:47
@ ExportSolution
Definition GeneralSolver.hpp:48
@ ExportSolutionWithInstance
Definition GeneralSolver.hpp:49
bool is_directory_and_create(const std::filesystem::path &p)
Ensures that a filesystem path exists as a directory.
Definition GeneralHelper.cpp:99
double get_time_difference_in_seconds(std::chrono::time_point< Clock, Duration1 > const &start, std::chrono::time_point< Clock, Duration2 > const &end)
Definition GeneralHelper.hpp:136
void initialize_plog(bool debug_input, bool overwrite_severity=false)
Initializes the global plog console logger and adjusts its severity.
Definition GeneralHelper.cpp:89
std::string concatenate_string_views(std::initializer_list< std::string_view > parts)
Concatenates multiple string views into a single string.
Definition StringHelper.cpp:11
Where a solver writes its solution to, see GeneralSolver::export_general_solution.
Definition GeneralSolver.hpp:61
GeneralExportOption export_option
Definition GeneralSolver.hpp:62
std::string working_directory
Definition GeneralSolver.hpp:63
std::optional< double > evaluation_time_step
Definition GeneralSolver.hpp:66
std::optional< std::string > parameter_identifier
Definition GeneralSolver.hpp:65
std::string solution_subdirectory
Definition GeneralSolver.hpp:64
Solver-specific values to be written to solver_data.json.
Definition GeneralSolver.hpp:177
std::unordered_map< std::string, int > integer_data
Definition GeneralSolver.hpp:179
std::unordered_map< std::string, std::string > string_data
Definition GeneralSolver.hpp:181
std::unordered_map< std::string, bool > bool_data
Definition GeneralSolver.hpp:178
std::unordered_map< std::string, double > double_data
Definition GeneralSolver.hpp:180