-
Notifications
You must be signed in to change notification settings - Fork 16
/
solve.hpp
96 lines (79 loc) · 2.89 KB
/
solve.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/** @file solve.hpp
*
* Contains a generic function for pre-calculating an initial policy, which can be used to form the
* main method of a problem-specific "solve" executable.
*/
#ifndef SOLVE_HPP_
#define SOLVE_HPP_
#include <fstream> // for operator<<, endl, ostream, ofstream, basic_ostream, basic_ostream<>::__ostream_type
#include <iostream> // for cout
#include <memory> // for unique_ptr
#include <string> // for string
#include <utility> // for move // IWYU pragma: keep
#include "global.hpp" // for RandomGenerator, make_unique
#include "solver/serialization/Serializer.hpp" // for Serializer
#include "solver/Solver.hpp" // for Solver
#include "options/option_parser.hpp"
#ifdef GOOGLE_PROFILER
#include <google/profiler.h>
#endif
using std::cout;
using std::endl;
/** A template method to calculate an initial policy for the given model and options classes, and
* then save the policy to a file.
*/
template<typename ModelType, typename OptionsType>
int solve(int argc, char const *argv[]) {
std::unique_ptr<options::OptionParser> parser = OptionsType::makeParser(false);
OptionsType options;
std::string workingDir = tapir::get_current_directory();
try {
parser->setOptions(&options);
parser->parseCmdLine(argc, argv);
if (!options.baseConfigPath.empty()) {
tapir::change_directory(options.baseConfigPath);
}
if (!options.configPath.empty()) {
parser->parseCfgFile(options.configPath);
}
parser->finalize();
} catch (options::OptionParsingException const &e) {
std::cerr << e.what() << std::endl;
return 2;
}
if (options.seed == 0) {
options.seed = std::time(nullptr);
}
cout << "Seed: " << options.seed << endl;
RandomGenerator randGen;
randGen.seed(options.seed);
randGen.discard(10);
std::unique_ptr<ModelType> newModel = std::make_unique<ModelType>(&randGen,
std::make_unique<OptionsType>(options));
if (!options.baseConfigPath.empty()) {
tapir::change_directory(workingDir);
}
solver::Solver solver(std::move(newModel));
solver.initializeEmpty();
double totT;
double tStart;
tStart = tapir::clock_ms();
#ifdef GOOGLE_PROFILER
ProfilerStart("solve.prof");
#endif
solver.improvePolicy();
#ifdef GOOGLE_PROFILER
ProfilerStop();
#endif
totT = tapir::clock_ms() - tStart;
cout << "Total solving time: " << totT << "ms" << endl;
cout << "Saving to file...";
cout.flush();
std::ofstream outFile(options.policyPath);
outFile << std::setprecision(std::numeric_limits<double>::max_digits10);
solver.getSerializer()->save(outFile);
outFile.close();
cout << " Done." << endl;
return 0;
}
#endif /* SOLVE_HPP_ */