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
//! signals that passes between neurons

use std::fmt;

use crate::{
    blob::block::{BlockDepth, ParentAnchor},
    consts::*,
};
use bevy::prelude::Entity;
use itertools::Itertools;
use ndarray::{concatenate, prelude::*};
use serde::{Deserialize, Serialize};

const CL: usize = INWARD_NN_CHILDREN_INPUT_LEN;
const DL: usize = OUTWARD_NN_PARENT_INPUT_LEN;

// TODO: test correctness of signal
/// `SignalHandler` handles input signal from bevy
pub struct SignalHandler {
    pub inward_signal_vec: Vec<InwardNNInputSignalUnit>,
    pub brain_signal_vec: Vec<BrainSignalUnit>,
}

impl Default for SignalHandler {
    fn default() -> Self {
        Self {
            inward_signal_vec: Vec::<InwardNNInputSignalUnit>::new(),
            brain_signal_vec: Vec::<BrainSignalUnit>::new(),
        }
    }
}

impl SignalHandler {
    pub fn inward_len(&self) -> usize {
        self.inward_signal_vec.len()
    }

    pub fn brain_len(&self) -> usize {
        self.brain_signal_vec.len()
    }

    // /// stratify signals base on depth.
    // ///
    // /// Output order is positive-going,
    // /// which means groups with small depth have small index
    // ///
    // /// Side effect: `inward_signal_vec` will be sorted
    // pub fn stratify(&mut self) -> Vec<Vec<&mut InwardNNInputSignalUnit>> {
    //     // Sort by depth first
    //     self.inward_signal_vec.sort_by(|a, b| a.depth.cmp(&b.depth));

    //     // Group by depth
    //     self.inward_signal_vec
    //         .iter_mut()
    //         .group_by(|item| item.depth)
    //         .into_iter()
    //         .map(|(_, group)| group.collect())
    //         .collect()
    // }

    /// stratify signals base on depth.
    ///
    /// Output order is positive-going,
    /// which means groups with small depth have small index
    ///
    /// Side effect: `inward_signal_vec` will be sorted
    pub fn get_sig_mut(
        &mut self,
    ) -> (
        Vec<Vec<&mut InwardNNInputSignalUnit>>,
        Vec<&mut BrainSignalUnit>,
    ) {
        self.inward_signal_vec.sort_by(|a, b| a.depth.cmp(&b.depth));

        (
            self.inward_signal_vec
                .iter_mut()
                .group_by(|item| item.depth)
                .into_iter()
                .map(|(_, group)| group.collect())
                .collect(),
            self.brain_signal_vec.iter_mut().collect(),
        )
    }

    /// push inward signals and ids to handler
    pub fn push_inward(
        &mut self,
        signal: InwardNNInputSignal,
        nn_id: usize,
        parent_nn_id: usize,
        depth: &BlockDepth,
        anchor: &ParentAnchor,
        entity_id: Entity,
    ) {
        self.inward_signal_vec.push(InwardNNInputSignalUnit {
            signal: signal,
            nn_id: nn_id,
            parent_nn_id: parent_nn_id,
            depth: depth.0 as usize,
            // inward nn must have parent anchor so unwarp
            anchor_pos: anchor.0.unwrap(),
            entity_id: entity_id,
        })
    }

    pub fn push_brain(&mut self, signal: BrainSignal, nn_id: usize) {
        self.brain_signal_vec.push(BrainSignalUnit {
            signal: signal,
            nn_id: nn_id,
        })
    }
}

pub struct InwardNNInputSignalUnit {
    pub signal: InwardNNInputSignal,
    pub nn_id: usize,
    pub parent_nn_id: usize,
    pub depth: usize,
    /// anchor point to parent
    pub anchor_pos: usize,
    /// bond the entity
    pub entity_id: Entity,
}

impl fmt::Debug for InwardNNInputSignalUnit {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

impl fmt::Display for InwardNNInputSignalUnit {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "ID: {}, Parent: {}, Depth: {}",
            self.nn_id, self.parent_nn_id, self.depth
        )
    }
}

impl InwardNNInputSignalUnit {
    pub fn get_signal_mut(&mut self) -> &mut InwardNNInputSignal {
        &mut self.signal
    }
}

/// Input singal for single inward `BlockNeuron`
pub struct InwardNNInputSignal {
    // collision signal
    collision_with_wall: bool,
    collision_with_other_blob: bool,
    collision_vect: [f32; 2],
    collision_mag: f32,

    // joint signal
    cur_motor_pos: f32,
    cur_motor_v: f32,
    joint_ang_pos: f32,
    joint_ang_v: f32,

    /// Input singal from children neurons.
    ///
    /// Order of children inputs depends on children's parent_anchor.
    children_input: Array2<f32>,
}

impl Default for InwardNNInputSignal {
    fn default() -> Self {
        Self {
            collision_with_wall: false,
            collision_with_other_blob: false,
            collision_vect: [0.0, 0.0],
            collision_mag: 0.0,
            cur_motor_pos: 0.0,
            cur_motor_v: 0.0,
            joint_ang_pos: 0.0,
            joint_ang_v: 0.0,
            children_input: Array2::<f32>::zeros((4, CL)),
        }
    }
}

impl InwardNNInputSignal {
    pub fn with_cf_signal(mut self, signal: Option<(bool, bool, [f32; 2], f32)>) -> Self {
        if let Some((wall, blob, vect, mag)) = signal {
            self.collision_with_wall = wall;
            self.collision_with_other_blob = blob;
            self.collision_vect = vect;
            self.collision_mag = mag;
        }
        self
    }

    pub fn with_joint_singal(mut self, signal: (f32, f32, f32, f32)) -> Self {
        let (motor_pos, motor_v, ang_pos, ang_v) = signal;
        self.cur_motor_pos = motor_pos;
        self.cur_motor_v = motor_v;
        self.joint_ang_pos = ang_pos;
        self.joint_ang_v = ang_v;
        self
    }

    pub fn push_child_signal(&mut self, signal: Array1<f32>, anchor: usize) {
        // anchor must in 0..=3
        match anchor {
            0..=3 => self
                .children_input
                .slice_mut(s![anchor, ..])
                .assign(&signal),
            _ => {
                panic!()
            }
        }
    }

    pub fn to_array(&self) -> Array1<f32> {
        let bool_data = vec![
            self.collision_with_wall as u8 as f32,
            self.collision_with_other_blob as u8 as f32,
        ];

        let vect_data = self.collision_vect.iter().cloned();
        // flatten children_data
        let children_data = self.children_input.rows().into_iter().flatten().map(|&x| x);

        let all_data = bool_data
            .into_iter()
            .chain(vect_data)
            .chain(std::iter::once(self.collision_mag))
            .chain(std::iter::once(self.cur_motor_pos))
            .chain(std::iter::once(self.cur_motor_v))
            .chain(std::iter::once(self.joint_ang_pos))
            .chain(std::iter::once(self.joint_ang_v))
            .chain(children_data);

        Array1::from_iter(all_data)
    }
}

/// Input singal for single outward `BlockNeuron`
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OutwardNNInputSignal {
    // // collision signal
    // collision_with_wall: bool,
    // collision_with_other_blob: bool,
    // collision_vect: [f32; 2],
    // collision_mag: f32,

    // // joint signal
    // cur_motor_pos: f32,
    // cur_motor_v: f32,
    // joint_ang_pos: f32,
    // joint_ang_v: f32,
    inherited: Array1<f32>,

    /// Input singal from parent neurons.
    /// Array length in constant
    pub parent_input: Array1<f32>,
}

impl Default for OutwardNNInputSignal {
    fn default() -> Self {
        Self {
            // collision_with_wall: false,
            // collision_with_other_blob: false,
            // collision_vect: [0.0, 0.0],
            // collision_mag: 0.0,
            // cur_motor_pos: 0.0,
            // cur_motor_v: 0.0,
            // joint_ang_pos: 0.0,
            // joint_ang_v: 0.0,
            inherited: Array1::<f32>::zeros(9),
            parent_input: Array1::<f32>::zeros(DL),
        }
    }
}

impl OutwardNNInputSignal {
    /// inherit processed signal from inward signal
    pub fn inherit(&mut self, inward_signal_array: &Array1<f32>) {
        self.inherited = inward_signal_array.slice(s![0..9]).to_owned()
    }

    pub fn to_array(&mut self) -> Array1<f32> {
        concatenate(Axis(0), &[self.inherited.view(), self.parent_input.view()]).unwrap()
    }
}

/// Input signal of center block,
/// which do not have parent and joint
#[derive(Debug)]
pub struct BrainSignal {
    // collision signal
    collision_with_wall: bool,
    collision_with_other_blob: bool,
    collision_vect: [f32; 2],
    collision_mag: f32,

    /// input singal from children neurons.
    /// Shape is (4,CL)
    children_input: Array2<f32>,

    blob_mass_center: [f32; 2],
    blob_speed: [f32; 2],
}

impl Default for BrainSignal {
    fn default() -> Self {
        Self {
            collision_with_wall: false,
            collision_with_other_blob: false,
            collision_vect: [0.0, 0.0],
            collision_mag: 0.0,
            children_input: Array2::<f32>::zeros((4, CL)),
            blob_mass_center: [0.0, 0.0],
            blob_speed: [0.0, 0.0],
        }
    }
}

impl BrainSignal {
    pub fn with_cf_signal(mut self, signal: Option<(bool, bool, [f32; 2], f32)>) -> Self {
        if let Some((wall, blob, vect, mag)) = signal {
            self.collision_with_wall = wall;
            self.collision_with_other_blob = blob;
            self.collision_vect = vect;
            self.collision_mag = mag;
        }
        self
    }

    pub fn with_blob_info(mut self, center: [f32; 2], speed: [f32; 2]) -> Self {
        self.blob_mass_center = center;
        self.blob_speed = speed;
        self
    }

    pub fn push_child_signal(&mut self, signal: Array1<f32>, anchor: usize) {
        // anchor must in 0..=3
        match anchor {
            0..=3 => self
                .children_input
                .slice_mut(s![anchor, ..])
                .assign(&signal),
            _ => {
                panic!()
            }
        }
    }

    pub fn to_array(&self) -> Array1<f32> {
        let bool_data = vec![
            self.collision_with_wall as u8 as f32,
            self.collision_with_other_blob as u8 as f32,
        ];

        let vect_data = self.collision_vect.iter().cloned();
        // flatten children_data
        let children_data = self.children_input.rows().into_iter().flatten().map(|&x| x);
        let mass_center_data = self.blob_mass_center.iter().cloned();
        let speed_data = self.blob_speed.iter().cloned();

        let all_data = bool_data
            .into_iter()
            .chain(vect_data)
            .chain(std::iter::once(self.collision_mag))
            .chain(children_data)
            .chain(mass_center_data)
            .chain(speed_data);

        Array1::from_iter(all_data)
    }
}

pub struct BrainSignalUnit {
    pub signal: BrainSignal,
    pub nn_id: usize,
}

impl BrainSignalUnit {
    pub fn get_signal_mut(&mut self) -> &mut BrainSignal {
        &mut self.signal
    }
}

impl fmt::Debug for BrainSignalUnit {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

impl fmt::Display for BrainSignalUnit {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Brain:  ID: {}", self.nn_id)
    }
}