-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpm_solver_trivial.cpp
More file actions
335 lines (271 loc) · 9.18 KB
/
pm_solver_trivial.cpp
File metadata and controls
335 lines (271 loc) · 9.18 KB
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
/*
* Entry point for the whole application
* Depends on fuzzylite and pagmo libraries!
*/
#include "pm_solver.h"
#include <fl/Headers.h>
#include <pagmo/algorithm.hpp>
#include <pagmo/algorithms/sade.hpp>
#include <pagmo/archipelago.hpp>
#include <pagmo/problem.hpp>
#include <pagmo/problems/schwefel.hpp>
using Stats = std::tuple<
double, // strength
double, // constitution
double, // intelligence
double // refinement
>;
using Inclinations = std::tuple<
double, // PhysicalInclination
double // MentalInclination
>;
const std::unordered_map<
std::string, // job name
Stats // stat changes after taking this action
> actions{
/*
* https://princessmaker.fandom.com/wiki/Hunter_(PM2)
* Stats/Skills Affected
Constitution: +1/day
Combat Skill: Random raise, + 0 to 1/day
Refinement: -1/day
Sin: Random raise, +0 to 1/day
Stress: +3/day
Hidden Stat:
Maternal Instinct: -1/day
Stats Required
Constitution, Intelligence.
*/
{ "Hunting", { 0.00, 0.01, 0.00, -0.01 } },
/*
* https://princessmaker.fandom.com/wiki/Lumberjack_(PM2)
* Statistics Affected
Strength: +2/day
Refinement: -2/day
Stress: +4/day
Statistics Required
Constitution, strength.
*/
{ "Lumberjack", { 0.02, 0.00, 0.00, -0.02 } },
/*
* https://princessmaker.fandom.com/wiki/Science_Class_(PM2)
* Charts
Science Novice Adept Expert Master
Tuition/Day 30 G 40 G 50 G 60 G
Intelligence +1 to 4 +2 to 6 +3 to 8 +4 to 12
Faith -0 -0 to 1 -0 to 2 -0 to 3
Magical Defense -0 -0 to 1 -0 to 1 -0 to 1
*/
{ "ScienceClass", { 0.0, 0.0, 0.02, 0.0 } },
/*
https://princessmaker.fandom.com/wiki/Protocol_Class_(PM2)
Charts
Protocol Novice Adept Expert Master
Tuition/Day 40 G 50 G 60 G 70 G
Decorum +1 +1 to 2 +1 to 3 +1 to 4
Refinement +1 +1 to 2 +1 to 3 +1 to 4
*/
{ "MannersClass", { 0.0, 0.0, 0.0, 0.02 } },
};
template <typename... T>
std::tuple<T...> tuple_sum(const std::tuple<T...>& a, const std::tuple<T...>& b) {
return std::apply([&b](const T&... av) {
return std::apply([&](const T&... bv) {
return std::make_tuple((av + bv)...);
}, b);
}, a);
}
Stats sum_stats(const Stats& a, const Stats& b)
{
return tuple_sum(a, b);
}
std::string choose_action(fl::Engine* engine, const Inclinations& inclinations, const Stats& stats)
{
// Load the specimen into the engine
engine->getInputVariable("PhysicalInclination")->setValue(std::get<0>(inclinations));
engine->getInputVariable("MentalInclination")->setValue(std::get<1>(inclinations));
engine->getInputVariable("strength")->setValue(std::get<0>(stats));
engine->getInputVariable("constitution")->setValue(std::get<1>(stats));
engine->getInputVariable("intelligence")->setValue(std::get<2>(stats));
engine->getInputVariable("refinement")->setValue(std::get<3>(stats));
// Get action priorities
engine->process();
const auto& output_vars = engine->outputVariables();
auto it = std::max_element(
output_vars.begin(), output_vars.end(),
[](const auto* a, const auto* b) {
// defaulting to 0 if the value is NaN
const auto left_priority = std::isnan(a->getValue()) ? 0.0 : a->getValue();
const auto right_priority = std::isnan(b->getValue()) ? 0.0 : b->getValue();
std::cout << "Comparing " << a->getName() << " with value " << left_priority
<< " and " << b->getName() << " with value " << right_priority << "\n";
return left_priority < right_priority;
}
);
// Either return the name of the action with the highest priority,
// or the first action if no rules fired (i.e., all priorities are 0).
std::string chosen_action_name = (it != output_vars.end())
? (*it)->getName()
: (*output_vars.begin())->getName();
return chosen_action_name;
}
std::unique_ptr<fl::Engine> init()
{
// Initialize the engine
std::string path{ "C:\\projects\\pm_solver\\Trivial.fll" };
std::unique_ptr<fl::Engine> engine{ fl::FllImporter().fromFile(path) };
// Checking for errors in the engine loading.
std::string status;
if (not engine->isReady(&status))
{
throw fl::Exception("[engine error] engine is not ready: \n" + status);
}
// We want to see the details of the engine processing.
fuzzylite::fuzzylite::setDebugging(false);
return engine;
}
std::string single_step(Stats& stats, const Inclinations& inclinations, fl::Engine* engine)
{
// Choose an action based on the current stats and inclinations
std::string chosen_action_name = choose_action(engine, inclinations, stats);
if (chosen_action_name.empty())
{
std::cout << "No action chosen, exiting.\n";
return "";
}
std::cout << "Chosen action: " << chosen_action_name << "\n";
// Apply the effects of the chosen action
Stats stats_diff = actions.at(chosen_action_name);
stats = sum_stats(stats, stats_diff);
return chosen_action_name;
}
/** the lower the better (conforming to pagmo2 conventions) */
double fitness(const Stats& stats)
{
// demo fitness: desirable refinement is 0.05+
return 0.05 - std::get<1>(stats);
}
constexpr int T = 4; // number of steps to take
std::pair<std::vector<std::string>, double> simulate(const Inclinations& inclinations, fl::Engine* engine)
{
// Initialize a specimen
Stats stats{ 0.0, 0.0, 0.0, 0.0 };
std::vector<std::string> path{};
engine->restart();
for (int i = 0; i < T; ++i)
{
std::cout << "Step " << i + 1 << ":\n";
auto step = single_step(stats, inclinations, engine);
std::cout << "Current stats: "
<< "Strength: " << std::get<0>(stats) << ", "
<< "Constitution: " << std::get<1>(stats) << ", "
<< "Intelligence: " << std::get<2>(stats) << ", "
<< "Refinement: " << std::get<3>(stats) << "\n";
path.push_back(step);
}
return std::make_pair(path, fitness(stats));
}
using SimulationResult = std::pair<
/** Sequence of action names */
std::vector<std::string>,
/** Fitness value */
double>;
void print_simulation_result(const SimulationResult& result)
{
std::cout << "Simulation Result:\n";
std::cout << "Fitness: " << result.second << "\n";
std::cout << "Actions taken:\n";
for (const auto& action : result.first)
{
std::cout << "- " << action << "\n";
}
}
std::string choose_action_fast(fl::Engine* engine, const Stats& stats)
{
// Load the specimen into the engine - assume that inclinations are already set
engine->getInputVariable("strength")->setValue(std::get<0>(stats));
engine->getInputVariable("constitution")->setValue(std::get<1>(stats));
engine->getInputVariable("intelligence")->setValue(std::get<2>(stats));
engine->getInputVariable("refinement")->setValue(std::get<3>(stats));
// Get action priorities
engine->process();
const auto& output_vars = engine->outputVariables();
auto it = std::max_element(
output_vars.begin(), output_vars.end(),
[](const auto* a, const auto* b) {
// defaulting to 0 if the value is NaN
const auto left_priority = std::isnan(a->getValue()) ? 0.0 : a->getValue();
const auto right_priority = std::isnan(b->getValue()) ? 0.0 : b->getValue();
return left_priority < right_priority;
}
);
// Either return the name of the action with the highest priority,
// or the first action if no rules fired (i.e., all priorities are 0).
std::string chosen_action_name = (it != output_vars.end())
? (*it)->getName()
: (*output_vars.begin())->getName();
return chosen_action_name;
}
void single_step_fast(Stats& stats, fl::Engine* engine)
{
// Choose an action based on the current stats and inclinations
std::string chosen_action_name = choose_action_fast(engine, stats);
// Apply the effects of the chosen action
Stats stats_diff = actions.at(chosen_action_name);
stats = sum_stats(stats, stats_diff);
}
double simulate_fast(const Inclinations& inclinations, fl::Engine* engine)
{
// Initialize a specimen
Stats stats{ 0.0, 0.0, 0.0, 0.0 };
engine->restart();
// Set inclinations
engine->getInputVariable("PhysicalInclination")->setValue(std::get<0>(inclinations));
engine->getInputVariable("MentalInclination")->setValue(std::get<1>(inclinations));
for (int i = 0; i < T; ++i)
{
single_step_fast(stats, engine);
}
return fitness(stats);
}
// Pagmo2-compatible problem definition
struct pm_problem {
// Implementation of the objective function.
pagmo::vector_double fitness(const pagmo::vector_double& dv) const
{
const Inclinations specimen{ dv[0], dv[1] };
auto engine = init(); // this is super slow but fuzzylite is not prepared for multithreading so we need to create a new engine for each call
return { simulate_fast(specimen, engine.get())};
}
/**
* Implementation of the box bounds.
* First element is the lower bound, second is the upper bound.
* Bounds are inclination values for Physical and Mental inclinations.
*
* (Range is 0.0 - 1.0, we hope that Pagmo2 will correctly interpolate between them)
*/
std::pair<pagmo::vector_double, pagmo::vector_double> get_bounds() const
{
return { {0., 0.}, {1., 1.} };
}
};
int main()
{
pagmo::problem prob(pm_problem{});
pagmo::algorithm algo(pagmo::sade(100));
pagmo::archipelago archi(16u, algo, prob, 20u);
archi.evolve(10);
archi.wait_check();
for (const auto& isl : archi)
{
const auto& champion = isl.get_population().champion_x();
std::cout << "island champion: {" << champion[0] << ", " << champion[1] << "}\n";
auto engine = init();
const auto& result = simulate(
{ champion[0], champion[1] },
engine.get()
);
print_simulation_result(result);
}
return 0;
}