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"
4
5#include "../bandit/bandit.h"
7#include "../bandit/dummy.h"
9#include "../ind/individual.h"
10
13
14#include "../vary/variation.h"
15
16namespace py = pybind11;
17namespace nl = nlohmann;
18namespace br = Brush;
19
20template<br::ProgramType PT>
21void bind_variation(py::module& m, string name)
22{
23 using Class = br::Var::Variation<PT>;
24
25 // TODO: make variation a non-templated class
26 py::class_<Class> vary(m, name.data() );
27
28 vary.def(py::init<>([](br::Parameters& p, br::SearchSpace& ss, br::Data::Dataset& d){
29 Class variation(p, ss, d);
30 return variation; }))
31 .def("mutate", &Class::mutate, py::return_value_policy::automatic)
32 .def("cross", &Class::cross, py::return_value_policy::automatic)
33 .def("vary_pop", [](Class &self,
34 std::vector<br::Pop::Individual<PT>>& individuals,
35 const Parameters& params) {
36 if (individuals.size() != params.pop_size) {
37 string msg = "Individual vector has different number of "
38 "individuals than pop_size. When calling "
39 "variation, they should be the same. popsize is "+
40 to_string(params.pop_size)+", number of "
41 "individuals is "+to_string(individuals.size());
42
43 throw std::runtime_error(msg);
44 }
45
46 auto pop = br::Pop::Population<PT>();
47
48 pop.init(individuals, params);
49
50 vector<br::Pop::Individual<PT>> pool;
51 pool.resize(0);
52
53 for (int island = 0; island < params.num_islands; ++island)
54 {
55 // I am assuming the individual vector passed as argument
56 // will contain the selected parents already
57 vector<size_t> parents = pop.get_island_indexes(island);
58
59 // including offspring indexes (the vary method will store the
60 // offspring in the second half of the index vector)
61 pop.add_offspring_indexes(island);
62
63 self.vary(pop, island, parents);
64
65 // making copies of the second half of the island individuals
66 vector<size_t> indices = pop.get_island_indexes(island);
67 int start = indices.size()/2;
68 for (unsigned i = start; i<indices.size(); ++i)
69 {
70 // this is where the offspring is saved
71 pool.push_back(pop[indices.at(i)]);
72 }
73 }
74 return pool;
75 })
76 ;
77}
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:3
Holds a search space, consisting of operations and terminals and functions, and methods to sample tha...