Brush C++ API
A flexible interpretable machine learning framework
Loading...
Searching...
No Matches
bind_variation.h
Go to the documentation of this file.
1#include "module.h"
2
3#include "../pop/population.h"
5
6#include "../bandit/bandit.h"
10#include "../bandit/dummy.h"
11#include "../bandit/dummy.cpp"
12#include "../bandit/thompson.h"
16#include "../ind/individual.h"
17#include "../ind/individual.cpp"
18
23
24#include "../vary/variation.h"
25#include "../vary/variation.cpp"
26
27namespace py = pybind11;
28namespace nl = nlohmann;
29namespace br = Brush;
30
31template<br::ProgramType PT>
32void bind_variation(py::module& m, string name)
33{
34 using Class = br::Var::Variation<PT>;
35
36 // TODO: make variation a non-templated class
37 py::class_<Class> vary(m, name.data() );
38
39 vary.def(py::init<>([](br::Parameters& p, br::SearchSpace& ss, br::Data::Dataset& d){
40 Class variation(p, ss, d);
41 return variation; }))
42 .def("mutate", &Class::mutate, py::return_value_policy::automatic)
43 .def("cross", &Class::cross, py::return_value_policy::automatic)
44 .def("vary_pop", [](Class &self,
45 std::vector<br::Pop::Individual<PT>>& individuals,
46 const Parameters& params) {
47 if (individuals.size() != params.pop_size) {
48 string msg = "Individual vector has different number of "
49 "individuals than pop_size. When calling "
50 "variation, they should be the same. popsize is "+
51 to_string(params.pop_size)+", number of "
52 "individuals is "+to_string(individuals.size());
53
54 throw std::runtime_error(msg);
55 }
56
57 auto pop = br::Pop::Population<PT>();
58
59 pop.init(individuals, params);
60
61 vector<br::Pop::Individual<PT>> pool;
62 pool.resize(0);
63
64 for (int island = 0; island < params.num_islands; ++island)
65 {
66 // I am assuming the individual vector passed as argument
67 // will contain the selected parents already
68 vector<size_t> parents = pop.get_island_indexes(island);
69
70 // including offspring indexes (the vary method will store the
71 // offspring in the second half of the index vector)
72 pop.add_offspring_indexes(island);
73
74 self.vary(pop, island, parents);
75
76 // making copies of the second half of the island individuals
77 vector<size_t> indices = pop.get_island_indexes(island);
78 int start = indices.size()/2;
79 for (unsigned i = start; i<indices.size(); ++i)
80 {
81 // this is where the offspring is saved
82 pool.push_back(pop[indices.at(i)]);
83 }
84 }
85 return pool;
86 })
87 ;
88}
void bind_variation(py::module &m, string name)
holds variable type data.
Definition data.h:51
Class representing the variation operators in Brush.
Definition variation.h:44
string to_string(const T &value)
template function to convert objects to string for logging
Definition utils.h:369
< nsga2 selection operator for getting the front
Definition bandit.cpp:4
Holds a search space, consisting of operations and terminals and functions, and methods to sample tha...