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