-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadd_random_synapse.rs
More file actions
82 lines (73 loc) · 2.63 KB
/
add_random_synapse.rs
File metadata and controls
82 lines (73 loc) · 2.63 KB
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
//! Command and handler for randomly adding a synapse between two neurons.
use rand::{seq::SliceRandom, Rng};
use uuid::Uuid;
use super::NetworkHandlerBase;
use crate::domain::{Event, RandomSynapseAdded};
use crate::infrastructure::EventStore;
/// Command requesting the creation of a random synapse.
#[derive(Debug, Clone, Copy)]
pub struct AddRandomSynapseCommand;
/// Possible errors when adding a random synapse.
#[derive(Debug, Clone, PartialEq)]
pub enum AddRandomSynapseError {
/// The network does not contain at least two neurons.
NotEnoughNeurons,
/// All neuron pairs are already connected.
NoAvailableConnection,
/// Persisting the event failed.
StorageError,
}
/// Handles [`AddRandomSynapseCommand`], emitting a [`RandomSynapseAdded`] event.
pub struct AddRandomSynapseHandler<S: EventStore, R: Rng> {
/// Shared handler state including store, network and RNG.
pub base: NetworkHandlerBase<S, R>,
}
impl<S: EventStore, R: Rng> AddRandomSynapseHandler<S, R> {
/// Loads events from the store to initialize the handler.
pub fn new(store: S, rng: R) -> Result<Self, S::Error> {
Ok(Self {
base: NetworkHandlerBase::new(store, rng)?,
})
}
/// Handles the command and returns the identifier of the created synapse.
pub fn handle(&mut self, _cmd: AddRandomSynapseCommand) -> Result<Uuid, AddRandomSynapseError> {
let base = &mut self.base;
let neuron_ids: Vec<Uuid> = base.network.neurons.keys().copied().collect();
if neuron_ids.len() < 2 {
return Err(AddRandomSynapseError::NotEnoughNeurons);
}
let mut pairs = Vec::new();
for &from in &neuron_ids {
for &to in &neuron_ids {
if from == to {
continue;
}
if base
.network
.synapses
.values()
.any(|s| s.from == from && s.to == to)
{
continue;
}
pairs.push((from, to));
}
}
let (from, to) = *pairs
.choose(&mut base.rng)
.ok_or(AddRandomSynapseError::NoAvailableConnection)?;
let weight = base.rng.gen_range(-1.0..=1.0);
let synapse_id = Uuid::new_v4();
let event = Event::RandomSynapseAdded(RandomSynapseAdded {
synapse_id,
from,
to,
weight,
});
base.store
.append(&event)
.map_err(|_| AddRandomSynapseError::StorageError)?;
base.network.apply(&event);
Ok(synapse_id)
}
}