pulsatrix
Loading...
Searching...
No Matches
neat_phenotype.hpp
Go to the documentation of this file.
1
16#pragma once
17
18#include <algorithm>
19#include <cmath>
20#include <functional>
21#include <map>
22#include <stdexcept>
23#include <vector>
24
26
27namespace pulsatrix {
28
42inline std::vector<double> EvaluateNEATPhenotype(const NEATGenome& genome, const std::vector<double>& inputs) {
43 std::vector<int> input_ids;
44 std::vector<int> output_ids;
45 int bias_id = -1;
46 for (const auto& n : genome.nodes()) {
47 switch (n.type) {
49 input_ids.push_back(n.id);
50 break;
52 bias_id = n.id;
53 break;
55 output_ids.push_back(n.id);
56 break;
58 break;
59 }
60 }
61 std::sort(input_ids.begin(), input_ids.end());
62 std::sort(output_ids.begin(), output_ids.end());
63
64 if (inputs.size() != input_ids.size()) {
65 throw std::invalid_argument("EvaluateNEATPhenotype: inputs.size() must match the genome's Input node count");
66 }
67
68 std::map<int, double> fixed_values;
69 for (size_t i = 0; i < input_ids.size(); ++i) {
70 fixed_values[input_ids[i]] = inputs[i];
71 }
72 if (bias_id != -1) {
73 fixed_values[bias_id] = 1.0;
74 }
75
76 std::map<int, double> cache;
77 std::function<double(int)> evaluate = [&](int node_id) -> double {
78 auto fixed_it = fixed_values.find(node_id);
79 if (fixed_it != fixed_values.end()) {
80 return fixed_it->second;
81 }
82 auto cached_it = cache.find(node_id);
83 if (cached_it != cache.end()) {
84 return cached_it->second;
85 }
86 double sum = 0.0;
87 for (const auto& c : genome.connections()) {
88 if (c.enabled && c.out_node == node_id) {
89 sum += c.weight * evaluate(c.in_node);
90 }
91 }
92 double activated = 1.0 / (1.0 + std::exp(-4.9 * sum));
93 cache[node_id] = activated;
94 return activated;
95 };
96
97 std::vector<double> outputs;
98 outputs.reserve(output_ids.size());
99 for (int id : output_ids) {
100 outputs.push_back(evaluate(id));
101 }
102 return outputs;
103}
104
105} // namespace pulsatrix
A NEAT genome: its node and connection genes, growable via structural mutation.
Definition neat_genome.hpp:94
const std::vector< ConnectionGene > & connections() const
Definition neat_genome.hpp:134
const std::vector< NodeGene > & nodes() const
Definition neat_genome.hpp:133
Definition acquisition_functions.hpp:16
std::vector< double > EvaluateNEATPhenotype(const NEATGenome &genome, const std::vector< double > &inputs)
Evaluates genome's phenotype forward pass on inputs (one value per Input node, ordered by ascending n...
Definition neat_phenotype.hpp:42
NEAT genome (Stanley & Miikkulainen, "Evolving Neural Networks through Augmenting Topologies,...