1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
use crate::brain::Brain;
use crate::config::Config;
use crate::neuron::{NeuronID, Position};
use crate::Scalar;
use rand::{thread_rng, Rng};
use serde::{Deserialize, Serialize};
use std::f64::consts::PI;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BrainBuilder {
    config: Config,
    neurons: usize,
    connections: usize,
    radius: Scalar,
    min_neurogenesis_range: Scalar,
    max_neurogenesis_range: Scalar,
    sensors: usize,
    effectors: usize,
    no_loop_connections: bool,
    max_connecting_tries: usize,
}

impl Default for BrainBuilder {
    fn default() -> Self {
        Self {
            config: Default::default(),
            neurons: 100,
            connections: 0,
            radius: 10.0,
            min_neurogenesis_range: 0.1,
            max_neurogenesis_range: 1.0,
            sensors: 1,
            effectors: 1,
            no_loop_connections: true,
            max_connecting_tries: 10,
        }
    }
}

impl BrainBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn config(mut self, config: Config) -> Self {
        self.config = config;
        self
    }

    pub fn neurons(mut self, value: usize) -> Self {
        self.neurons = value;
        self
    }

    pub fn connections(mut self, value: usize) -> Self {
        self.connections = value;
        self
    }

    pub fn radius(mut self, value: Scalar) -> Self {
        self.radius = value;
        self
    }

    pub fn min_neurogenesis_range(mut self, value: Scalar) -> Self {
        self.min_neurogenesis_range = value;
        self
    }

    pub fn max_neurogenesis_range(mut self, value: Scalar) -> Self {
        self.max_neurogenesis_range = value;
        self
    }

    pub fn sensors(mut self, value: usize) -> Self {
        self.sensors = value;
        self
    }

    pub fn effectors(mut self, value: usize) -> Self {
        self.effectors = value;
        self
    }

    pub fn no_loop_connections(mut self, value: bool) -> Self {
        self.no_loop_connections = value;
        self
    }

    pub fn max_connecting_tries(mut self, value: usize) -> Self {
        self.max_connecting_tries = value;
        self
    }

    pub fn build(mut self) -> Brain {
        let mut brain = Brain::new();
        brain.set_config(self.config.clone());
        let mut rng = thread_rng();

        let mut neurons = vec![];
        neurons.push(brain.create_neuron(Position {
            x: 0.0,
            y: 0.0,
            z: 0.0,
        }));
        for _ in 0..self.neurons {
            neurons.push(self.make_neighbor_neuron(&neurons, &mut brain, &mut rng));
        }

        let neuron_positions = neurons
            .iter()
            .map(|id| (*id, brain.neuron(*id).unwrap().position()))
            .collect::<Vec<_>>();
        for _ in 0..self.sensors {
            let mut tries = self.max_connecting_tries + 1;
            while tries > 0 && !self.make_peripheral_sensor(&neuron_positions, &mut brain, &mut rng)
            {
                tries -= 1;
            }
        }
        for _ in 0..self.effectors {
            let mut tries = self.max_connecting_tries + 1;
            while tries > 0
                && !self.make_peripheral_effector(&neuron_positions, &mut brain, &mut rng)
            {
                tries -= 1;
            }
        }
        for _ in 0..self.connections {
            let mut tries = self.max_connecting_tries + 1;
            while tries > 0
                && self.connect_neighbor_neurons(&neuron_positions, &mut brain, &mut rng)
            {
                tries -= 1;
            }
        }
        for id in brain.get_neurons() {
            if !brain.does_neuron_has_connections(id) {
                drop(brain.kill_neuron(id));
            }
        }

        brain
    }

    fn make_peripheral_sensor<R>(
        &self,
        neuron_positions: &[(NeuronID, Position)],
        brain: &mut Brain,
        rng: &mut R,
    ) -> bool
    where
        R: Rng,
    {
        let pos = self.make_new_peripheral_position(rng);
        let index = neuron_positions
            .iter()
            .map(|(_, p)| p.distance_sqr(pos))
            .enumerate()
            .min_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap())
            .unwrap()
            .0;
        brain.create_sensor(neuron_positions[index].0).is_ok()
    }

    fn make_peripheral_effector<R>(
        &self,
        neuron_positions: &[(NeuronID, Position)],
        brain: &mut Brain,
        rng: &mut R,
    ) -> bool
    where
        R: Rng,
    {
        let pos = self.make_new_peripheral_position(rng);
        let index = neuron_positions
            .iter()
            .map(|(_, p)| p.distance_sqr(pos))
            .enumerate()
            .min_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap())
            .unwrap()
            .0;
        brain.create_effector(neuron_positions[index].0).is_ok()
    }

    fn make_neighbor_neuron<R>(
        &mut self,
        neurons: &[NeuronID],
        brain: &mut Brain,
        rng: &mut R,
    ) -> NeuronID
    where
        R: Rng,
    {
        let distance = rng.gen_range(self.min_neurogenesis_range, self.max_neurogenesis_range);
        let origin = neurons[rng.gen_range(0, neurons.len()) % neurons.len()];
        let origin_pos = brain.neuron(origin).unwrap().position();
        let new_position = self.make_new_position(origin_pos, distance, rng);
        brain.create_neuron(new_position)
    }

    fn connect_neighbor_neurons<R>(
        &mut self,
        neuron_positions: &[(NeuronID, Position)],
        brain: &mut Brain,
        rng: &mut R,
    ) -> bool
    where
        R: Rng,
    {
        let origin =
            neuron_positions[rng.gen_range(0, neuron_positions.len()) % neuron_positions.len()];
        let filtered = neuron_positions
            .iter()
            .filter_map(|(id, p)| {
                if p.distance(origin.1) <= self.max_neurogenesis_range {
                    Some(id)
                } else {
                    None
                }
            })
            .collect::<Vec<_>>();
        let target = *filtered[rng.gen_range(0, filtered.len()) % filtered.len()];
        origin.0 != target
            && (!self.no_loop_connections
                || (!brain.are_neurons_connected(origin.0, target)
                    && !brain.are_neurons_connected(target, origin.0)))
            && brain.bind_neurons(origin.0, target).is_ok()
    }

    fn make_new_position<R>(&self, pos: Position, scale: Scalar, rng: &mut R) -> Position
    where
        R: Rng,
    {
        let phi = rng.gen_range(0.0, PI * 2.0);
        let theta = rng.gen_range(-PI, PI);
        let pos = Position {
            x: pos.x + theta.cos() * phi.cos() * scale,
            y: pos.y + theta.cos() * phi.sin() * scale,
            z: pos.z + theta.sin() * scale,
        };
        let magnitude = pos.magnitude();
        if magnitude > self.radius {
            Position {
                x: self.radius * pos.x / magnitude,
                y: self.radius * pos.y / magnitude,
                z: self.radius * pos.z / magnitude,
            }
        } else {
            pos
        }
    }

    fn make_new_peripheral_position<R>(&self, rng: &mut R) -> Position
    where
        R: Rng,
    {
        let phi = rng.gen_range(0.0, PI * 2.0);
        let theta = rng.gen_range(-PI, PI);
        Position {
            x: theta.cos() * phi.cos() * self.radius,
            y: theta.cos() * phi.sin() * self.radius,
            z: theta.sin() * self.radius,
        }
    }
}