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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
use alloc::vec::Vec;
use graphlib::{Graph, GraphErr};
use graphlib::VertexId;
use alloc::borrow::ToOwned;
use crate::network::node::Node;
use core::slice;
pub type OperationId = VertexId;
pub struct Network<T>
where T: Copy + 'static
{
// Contains the network
graph: Graph<Node<T>>,
// Stores a flattened representation of the network
topology: Vec<OperationId>,
// Stores references to closed loops
closed_loops: Option<Vec<(OperationId, OperationId)>>,
}
#[derive(Debug)]
pub enum NetworkErr {
OperationNotFound(OperationId),
InternalNetworkError,
GraphError(GraphErr),
}
// Contains the network over which the calculation should be done.
impl<T> Network<T>
where T: Copy + Default
{
/// Creates a new network
///
/// ## Example
/// ```rust
/// use sac_base::network::network::Network;
/// let mut network: Network<f32> = Network::new();
///
/// ```
pub fn new() -> Network<T> {
Network {
graph: Graph::new(),
topology: Vec::new(),
closed_loops: None,
}
}
/// Build the network
/// To build a accurate representation of the network, the topology will be build with
/// Kahn's algorithm. All inputs, filtered out.
/// These are not relevant to propagate through the network once it is built.
/// Without building the network, it will not process the inputs
///
/// ## Example
/// ```rust
/// use sac_base::operations::math::add::Add;
/// use sac_base::network::network::Network;
///
/// let mut network: Network<f32> = Network::new();
/// let add1 = network.add_operation(Add::new());
/// // Add any other desired operations
/// network.build().unwrap();
/// ```
pub fn build(&mut self) -> Result<(), NetworkErr> {
self.topology = self.graph.topo().into_iter().map(|vert| {
return vert.clone();
}).collect();
// The closed loops will be inserted into the graph once the topology is build.
// The network couldn't be build with loops inserted right from the beginning.
// Since all pull their inputs before they execute their functionality,
// we can just enter the connections into the network after the topology is created if there
// are any inserted.
let graph = &mut self.graph;
let _ret: Result<(), NetworkErr> = match &self.closed_loops {
Some(loops) => {
loops.iter().fold(Ok(()),|acc: Result<(), NetworkErr>, req_loop| {
match graph.add_edge(&req_loop.0, &req_loop.1) {
Ok(_) => {acc},
Err(err) => {Err(NetworkErr::GraphError(err))},
}
})
},
None => {Ok(())}
};
// Clear the vector after the edges are inserted to free up some space
self.closed_loops = None;
return _ret;
}
/// Iterates over the network topology and processes all operations.
/// After the iteration, the network will be updated and the outputs pollable
///
/// ## Example
/// ```rust
///
/// use sac_base::network::network::Network;
/// let mut network: Network<f32> = Network::new();
/// // Insert all operations and update the inputs
/// network.process();
/// // Update the inputs
/// network.process();
/// ```
pub fn process(&mut self) {
for vert in &self.topology {
let mut max_len: usize = 0;
let neighbours: Vec<OperationId> = self.graph.in_neighbors(vert).map(|vert| { vert.to_owned() }).collect();
let mut neighbour_nodes: Vec<&Node<T>> = Vec::new();
for vert in neighbours.into_iter() {
match self.graph.fetch(&vert) {
Some(neighbour) => {
neighbour_nodes.push(neighbour);
},
None => {}
};
}
unsafe {
let inputs: Vec<&[T]> = neighbour_nodes.into_iter().map(|node: &Node<T>| {
let slice = &node.data[..];
let slice_len = slice.len();
if slice_len > max_len {
max_len = slice_len;
}
let ptr_to_slice = slice.as_ptr();
// We need the call to the unsafe function because we cannot pass the slice
// reference to the next node. This would cause a immutable and a mutable
// borrow.
// The references are safe but the compiler can't know that.
// The hack to cast it to a pointer and back is to fool borrowck.
// This is not great a all. A better solution for this should be found.
//
// Other options so far:
// Rc: Reference counting is quite heavy on runtime. What we want to avoid.
// Only using T: Only using one sample might prevent us from implementing
// FFT or something similar.
// Lifetime: There might be a way to tell the compiler that this is fine
// by using proper lifetimes.
let referenced_slice = slice::from_raw_parts(ptr_to_slice, slice_len);
return referenced_slice;
}).collect();
match self.graph.fetch_mut(vert) {
Some(node) => {
(node.clk)((inputs, max_len), &mut node.data_container, &mut node.data);
},
None => {}
}
}
}
}
/// Adds an operation and returns the id of it.
///
/// ## Example
/// ```rust
///
/// use sac_base::network::network::Network;
/// use sac_base::operations::math::add::Add;
/// let mut network: Network<f32> = Network::new();
/// let add1 = network.add_operation(Add::new());
/// ```
pub fn add_operation(&mut self, node: Node<T>) -> OperationId {
self.graph.add_vertex(node).clone()
}
/// Adds a connection between two nodes. This will return an error if the nodes couldn't be
/// connected or a cycle is produced.
///
/// ## Example
/// ```rust
///
/// use sac_base::network::network::Network;
/// use sac_base::operations::miscellaneous::buffer::Buffer;
/// use sac_base::operations::math::differentiate::Differentiate;
/// use sac_base::operations::math::add::Add;
/// let mut network: Network<f32> = Network::new();
/// let input = network.add_operation(Buffer::new());
/// let diff = network.add_operation(Differentiate::new());
///
/// // Connects the input to the differentiate operation.
/// // +-----+ +------+
/// // +-----+ | | |
/// // | Add +------+ Diff +---
/// // +-----+ | | |
/// // +-----+ +------+
///
/// network.add_connection(&input, &diff).unwrap();
///
/// let add = network.add_operation(Add::new());
/// // Connects the input and the diff operation to the add operation.
///
/// // +-----+ +------+
/// // +-----+ | | | +-----+
/// // | Add +--+---+ Diff +--------+ |
/// // +-----+ | | | | | Add +----+
/// // +-----+ | +------+ +---+ |
/// // | | +-----+
/// // +---------------+
/// //
/// network.add_connection(&diff, &add).unwrap();
/// network.add_connection(&input, &add).unwrap();
///
/// ```
pub fn add_connection(&mut self, src: &OperationId, dst: &OperationId) -> Result<(), NetworkErr> {
match self.graph.add_edge_check_cycle(src, dst) {
Ok(_) => Ok(()),
Err(err) => Err(NetworkErr::GraphError(err))
}
}
/// Allows to close loops in the network. This is used when as example a feedback loop is
/// needed. The operation with which the loops should be closed (negative/positive)
/// has to be implemented manually.
///
/// ## Example
/// ```rust
///
/// use sac_base::network::network::Network;
/// use sac_base::operations::math::add::Add;
/// let mut network: Network<f32> = Network::new();
/// let add1 = network.add_operation(Add::new());
/// let add2 = network.add_operation(Add::new());
///
/// // +------+ +------+
/// // +-----+ | | |
/// // | Add1 +----------+ Add2 +---+---+
/// // +-----+ | | | |
/// // | +------+ +------+ |
/// // | |
/// // +----------------------------------+
///
/// network.close_loop(&add2, &add1);
///
/// ```
pub fn close_loop(&mut self, src: &OperationId, dst: &OperationId) {
// The network is build with Kahn's algorithm, which is not able to handle loops.
// Therefore they will be manually inserted once the topology is build.
match &mut self.closed_loops {
Some(loops) => {
loops.push((src.clone(), dst.clone()));
},
None => {
let mut loops = Vec::new();
loops.push((src.clone(), dst.clone()));
self.closed_loops = Some(loops);
}
}
}
/// Sets the input of the specified node. Accepts a single sample
///
/// ## Example
/// ```rust
///
/// use sac_base::network::network::Network;
/// use sac_base::operations::miscellaneous::buffer::Buffer;
/// let mut network: Network<f32> = Network::new();
/// let buffer = network.add_operation(Buffer::new());
///
/// network.set_input_sample(&buffer, 1.0);
///
/// ```
pub fn set_input_sample(&mut self, op_id: &OperationId, sample: T) -> Result<(), NetworkErr> {
match self.graph.fetch_mut(op_id) {
Some(input) => {
input.data = Vec::from(&[sample][..]);
},
None => {
return Err(NetworkErr::OperationNotFound(op_id.clone()));
}
}
Ok(())
}
/// Allows to set a whole slice as an input. This can be used if whole chunks of data have to
/// be fed into the network instead of single samples.
///
/// ## Example
/// ```rust
///
/// use sac_base::network::network::Network;
/// use sac_base::operations::miscellaneous::buffer::Buffer;
/// let mut network: Network<f32> = Network::new();
/// let buffer = network.add_operation(Buffer::new());
///
/// network.set_input_slice(&buffer, &[1.0][..]);
///
/// ```
pub fn set_input_slice(&mut self, op_id: &OperationId, slice: &[T]) -> Result<(), NetworkErr> {
match self.graph.fetch_mut(op_id) {
Some(input) => {
input.data = Vec::from(slice);
},
None => {
return Err(NetworkErr::OperationNotFound(op_id.clone()));
}
}
Ok(())
}
/// Fetches the data of a specified node.
///
/// ## Example
/// ```rust
///
/// use sac_base::network::network::Network;
/// use sac_base::operations::miscellaneous::buffer::Buffer;
/// let mut network: Network<f32> = Network::new();
/// let input = network.add_operation(Buffer::new());
///
/// network.build().unwrap();
/// network.set_input_sample(&input, 5.0);
/// network.process();
/// let output = network.get_output(&input).unwrap();
///
/// ```
pub fn get_output(&self, op_id: &OperationId) -> Result<&[T], NetworkErr> {
return match self.graph.fetch(op_id) {
Some(output) => {
Ok(&output.data[..])
},
None => {
Err(NetworkErr::OperationNotFound(op_id.clone()))
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::operations::math::add::Add;
use crate::operations::math::multiply::Multiply;
use crate::operations::miscellaneous::buffer::Buffer;
#[test]
fn test_graph() {
let mut network: Network<f32> = Network::new();
let add1 = network.add_operation(Add::new());
let mul1 = network.add_operation(Multiply::new());
let add2 = network.add_operation(Add::new());
let in1 = network.add_operation(Buffer::new());
let in2 = network.add_operation(Buffer::new());
let in3 = network.add_operation(Buffer::new());
network.add_connection(&in1, &add1).unwrap();
network.add_connection(&in2, &add1).unwrap();
network.add_connection(&add1, &add2).unwrap();
network.add_connection(&in3, &add2).unwrap();
network.add_connection(&add1, &mul1).unwrap();
network.add_connection(&add2, &mul1).unwrap();
network.build().unwrap();
network.set_input_sample(&in1, 1.0).unwrap();
network.set_input_sample(&in2, 1.0).unwrap();
network.set_input_sample(&in3, 1.0).unwrap();
network.process();
let res = network.get_output(&mul1).unwrap();
assert_eq!(res, [6.0]);
}
#[test]
fn test_graph_slices() {
let mut network: Network<f32> = Network::new();
let add1 = network.add_operation(Add::new());
let add2 = network.add_operation(Add::new());
let in1 = network.add_operation(Buffer::new());
let in2 = network.add_operation(Buffer::new());
let in3 = network.add_operation(Buffer::new());
network.add_connection(&in1, &add1).unwrap();
network.add_connection(&in2, &add1).unwrap();
network.add_connection(&add1, &add2).unwrap();
network.add_connection(&in3, &add2).unwrap();
network.build().unwrap();
network.set_input_slice(&in1, &[1.0, 2.0, 3.0][..]).unwrap();
network.set_input_slice(&in2, &[1.0, 2.0, 3.0][..]).unwrap();
network.set_input_slice(&in3, &[1.0, 2.0, 3.0][..]).unwrap();
network.process();
let res1 = network.get_output(&add1).unwrap();
let res2 = network.get_output(&add2).unwrap();
assert_eq!(res1, [2.0, 4.0, 6.0]);
assert_eq!(res2, [3.0, 6.0, 9.0]);
}
#[test]
fn test_graph_closed_loop() {
let mut network = Network::new();
let add1 = network.add_operation(Add::new());
let mul1 = network.add_operation(Multiply::new());
let add2 = network.add_operation(Add::new());
let in1 = network.add_operation(Buffer::new());
let in2 = network.add_operation(Buffer::new());
let in3 = network.add_operation(Buffer::new());
network.add_connection(&in1, &add1).unwrap();
network.add_connection(&in2, &add1).unwrap();
network.add_connection(&add1, &add2).unwrap();
network.add_connection(&in3, &add2).unwrap();
network.add_connection(&add1, &mul1).unwrap();
network.add_connection(&add2, &mul1).unwrap();
// Insert a closed loop
network.close_loop(&mul1, &add2);
network.build().unwrap();
network.set_input_sample(&in1, 1.0).unwrap();
network.set_input_sample(&in2, 1.0).unwrap();
network.set_input_sample(&in3, 1.0).unwrap();
network.process();
let res = network.get_output(&mul1).unwrap();
assert_eq!(res, [6.0]);
// Process twice to let the closed loop propagate
network.process();
let res = network.get_output(&mul1).unwrap();
assert_eq!(res, [18.0]);
}
}