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