Vita
evolution_summary.tcc
1/**
2 * \file
3 * \remark This file is part of VITA.
4 *
5 * \copyright Copyright (C) 2013-2019 EOS di Manlio Morini.
6 *
7 * \license
8 * This Source Code Form is subject to the terms of the Mozilla Public
9 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
10 * You can obtain one at http://mozilla.org/MPL/2.0/
11 */
12
13#if !defined(VITA_EVOLUTION_SUMMARY_H)
14# error "Don't include this file directly, include the specific .h instead"
15#endif
16
17#if !defined(VITA_EVOLUTION_SUMMARY_TCC)
18#define VITA_EVOLUTION_SUMMARY_TCC
19
20///
21/// Default constructor just call the summary::clear method.
22///
23template<class T>
24summary<T>::summary() : az(), best{T(), model_measurements()}, elapsed(0),
25 crossovers(0), mutations(0), gen(0), last_imp(0)
26{
27}
28
29///
30/// Resets summary informations.
31///
32template<class T>
33void summary<T>::clear()
34{
35 *this = summary<T>();
36}
37
38///
39/// Loads the object from a stream.
40///
41/// \param[in] in input stream
42/// \param[in] p active problem
43/// \return `true` if the object loaded correctly
44///
45/// \note
46/// If the load operation isn't successful the current object isn't changed.
47///
48template<class T>
49bool summary<T>::load(std::istream &in, const problem &p)
50{
51 unsigned known_best(false);
52 if (!(in >> known_best))
53 return false;
54
55 summary tmp_summary;
56 if (known_best)
57 {
58 T tmp_ind;
59 if (!tmp_ind.load(in, p.sset))
60 return false;
61
62 decltype(best.score.fitness) tmp_fitness;
63 if (!tmp_fitness.load(in))
64 return false;
65
66 decltype(best.score.accuracy) tmp_accuracy;
67 if (!load_float_from_stream(in, &tmp_accuracy))
68 return false;
69
70 tmp_summary.best.solution = tmp_ind;
71 tmp_summary.best.score.fitness = tmp_fitness;
72 tmp_summary.best.score.accuracy = tmp_accuracy;
73 }
74
75 int ms;
76 if (!(in >> ms))
77 return false;
78 tmp_summary.elapsed = std::chrono::milliseconds(ms);
79
80 if (!(in >> tmp_summary.mutations >> tmp_summary.crossovers
81 >> tmp_summary.gen >> tmp_summary.last_imp))
82 return false;
83
84 *this = tmp_summary;
85 return true;
86}
87
88///
89/// Saves the object into a stream.
90///
91/// \param[out] out output stream
92/// \return `true` if summary was saved correctly
93///
94template<class T>
95bool summary<T>::save(std::ostream &out) const
96{
97 // analyzer az doesn't need to be saved: it'll be recalculated at the
98 // beginning of evolution.
99
100 if (best.solution.empty())
101 out << "0\n";
102 else
103 {
104 out << "1\n";
105 best.solution.save(out);
106 best.score.fitness.save(out);
107 save_float_to_stream(out, best.score.accuracy);
108 out << '\n';
109 }
110
111 out << elapsed.count() << ' ' << mutations << ' ' << crossovers << ' '
112 << gen << ' ' << last_imp << '\n';
113
114 return out.good();
115}
116
117#endif // include guard