cellular_lib 0.1.1

A library for simulation of cellular automata
Documentation
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
#![allow(dead_code)]

//use std::boxed::Box;
//use std::cell::Ref;
//use std::cell::RefCell;
use std::fmt::Debug;
use std::marker::PhantomData;
//use std::rc::Rc;
//use std::rc::Weak;

pub mod cellular_process;
#[macro_use]
pub mod util;

/// Printer is the type of a printer function, which takes a string and prints it (to stdout, a file, whatever)
pub type Printer = Fn(&str) -> ();
/// Reader is the type of a reader function, which returns a string (from stdin, a file, whatever)
pub type Reader = Fn() -> String;

/// Trait `CellularAutomata` is a trait that all cellular automata must satisfy
pub trait CellularAutomata<
    'a,
    CellDataType: Clone + 'static + util::Newable + util::Parseable + util::Encodeable + Debug,
    MetaDataType: Clone + 'static + util::Newable + util::Parseable + cellular_process::GridMeta,
>
{
    /// Function run runs the cellular automata
    fn run(&self, _: &'a str) -> ();
    /// Function input_handler takes the grid and a reader and modifies the grid according to what it reads. The printer argument is there just so the automata can prompt the user (if needed)
    fn input_handler(
        _: &mut cellular_process::Grid<CellDataType, MetaDataType>,
        _: &Reader,
        _: &Printer,
    ) -> ();
    /// Function output_handler takes a grid and a printer and prints out something, according to the data of the grid.
    fn output_handler(_: &cellular_process::Grid<CellDataType, MetaDataType>, _: &Printer) -> ();
}

/// `DummyMetaData` is a dummy metadata struct. Use when you don't actually need your automata to be configuarable at runtime (obviously)
#[derive(Clone)]
pub struct DummyMetaData {}

/*
/// `AdaptiveTransitionFunctionMapNode` is a "node" in the transition function map
#[derive(Clone, Debug, PartialEq)]
pub enum AdaptiveTransitionFunctionMapNode {
    TempLink(Vec<Option<Rc<RefCell<AdaptiveTransitionFunctionMapNode>>>>), // TempLink is like link, but isn't final
    End(util::UsizeWrapper), // End indicates that the chain has ended
    Link(Vec<Option<Box<AdaptiveTransitionFunctionMapNode>>>), // Link stores the next nodes
}
*/

/// `AdaptiveTransitionFunction` is an Object that encapsulates an adaptive (dynamically configurable) transition function
#[derive(Clone, Debug)]
pub struct AdaptiveTransitionFunction {
    /// Matrix is the transition matrix - the transition function is really just a table lookup
    matrix: AdaptiveTransitionFunctionMatrix,
}

/// `AdaptiveNeighborParserNode` is a node in the neighbor function parser map
#[derive(Clone, Debug, PartialEq)]
pub enum AdaptiveNeighborParserNode {
    Relative(Vec<isize>),
    Absolute(Vec<usize>),
}

/// `AdaptiveTransitionFunctionMatrix` is the (new) object that encapsulates an adaptive
/// (dynamically configurable) transition function
#[derive(Clone, Debug)]
pub struct AdaptiveTransitionFunctionMatrix {
    matrix: Vec<Option<util::NanoVec<util::UsizeWrapper>>>,
    dimensions: Vec<usize>,
}

/// `AdaptiveNeighborParser` is an Object that encapsulates an adaptive (dynamically configurable) neighbor parsing function
#[derive(Clone, Debug)]
pub struct AdaptiveNeighborParser {
    addr_matrix: Vec<AdaptiveNeighborParserNode>,
    edge_val: util::NanoVec<util::UsizeWrapper>,
}

/// `AdaptiveMetaData` is your "standard" adaptive `MetaDataType`
#[derive(Clone, Debug)]
pub struct AdaptiveMetaData {
    dimensions: Vec<usize>,
    transition: AdaptiveTransitionFunction,
    neighbor_parser: AdaptiveNeighborParser,
}

/// `AdaptiveCellularAutomata` is a cellular automata that can be configured at runtime
#[derive(Clone)]
pub struct AdaptiveCellularAutomata<'a> {
    meta: AdaptiveMetaData,
    initial: Vec<util::UsizeWrapper>,
    phantom: PhantomData<&'a str>,
}

/*
impl util::Parseable for AdaptiveTransitionFunctionMapNode {
    fn parse(input: &str) -> Self {
        let to_return = Self::temp_link();

        let input_as_string = input.to_string();
        let split_input: Vec<&str> = input_as_string.split(',').collect();
        let tokens: Vec<Vec<util::UsizeWrapper>> = {
            let mut to_return: Vec<Vec<util::UsizeWrapper>> = Vec::new();
            let dimension_count = split_input[0].split(' ').count() - 1;
            to_return.resize(dimension_count + 1, Vec::new());
            for (indx1, j) in split_input.iter().enumerate() {
                let tmp: Vec<&str> = j.split(' ').collect();
                for item in tmp {
                    to_return[indx1].push(util::Parseable::parse(item));
                }
            }
            to_return
        };
        if split_input.is_empty() {
            panic!("ERROR - error reading transition function symbol table - table is empty");
        }
        let num_dimensions = split_input[0].split(' ').count() - 1; //num_dimensions is the number of dimensions, -1 because the last token is not a dimension, but the final value

        // Perform dimension sanity checks (make sure that all inputs have the same number of dimensions)
        for j in split_input {
            let tokens: Vec<&str> = j.split(' ').collect();
            if (tokens.len() - 1) != num_dimensions {
                // Malformed input (extra dimensions inserted, dimensions missing, etc)
                panic!("ERROR - missing or extra dimension");
            }
        }

        let to_return_rc = Rc::new(RefCell::new(to_return));
        let mut old_cell_weak_ptr: Weak<RefCell<Self>> = Rc::downgrade(&to_return_rc);
        for val_1 in tokens {
            for (addr, val_2) in val_1.iter().enumerate() {
                let current_ref_cell = {
                    if addr == num_dimensions {
                        RefCell::new(AdaptiveTransitionFunctionMapNode::End(val_2.clone()))
                    } else {
                        RefCell::new(Self::temp_link())
                    }
                };
                let node: Rc<RefCell<Self>> = Rc::new(current_ref_cell);
                let tmp = {
                    if addr == 0 {
                        Rc::new(RefCell::new(Self::temp_link())) // If addr == 0, make tmp hold some garbage, it won't be used anyways
                    } else if let Some(a) = old_cell_weak_ptr.upgrade() {
                        a
                    } else {
                        panic!("Cannot borrow last processed node as mutable");
                    }
                };
                let mut data = {
                    if addr == 0 {
                        if let Ok(d) = to_return_rc.try_borrow_mut() {
                            d
                        } else {
                            panic!("Cannot borrow last processed node as mutable");
                        }
                    } else if let Ok(a) = tmp.try_borrow_mut() {
                        a
                    } else {
                        panic!("Cannot borrow last processed node as mutable");
                    }
                };
                old_cell_weak_ptr = data.add_link(&Some(val_2.clone()), Some(node));
            }
        }
        Self::solidify(
            {
                if let Ok(a) = Rc::try_unwrap(to_return_rc) {
                    a
                } else {
                    panic!("Cannot unwrap to_return_Rc");
                }
            }
            .into_inner(),
        )
    }
}
*/

impl AdaptiveTransitionFunction {
    #[inline]
    pub fn apply(
        data: &mut util::NanoVec<util::UsizeWrapper>,
        neighbor: &cellular_process::NeighborType<util::UsizeWrapper>,
        meta: &AdaptiveMetaData,
    ) {
        *data = meta
            .get_transition_function()
            .get_matrix()
            .follow_path(neighbor.get_data().as_slice());
    }
    #[inline]
    pub fn get_matrix(&self) -> &AdaptiveTransitionFunctionMatrix {
        &self.matrix
    }
}

impl util::Parseable for AdaptiveTransitionFunction {
    fn parse(input: &str) -> Self {
        Self {
            matrix: util::Parseable::parse(input),
        }
    }
}

impl util::Newable for AdaptiveTransitionFunction {
    fn new() -> Self {
        Self {
            matrix: util::Newable::new(),
        }
    }
}

/*
impl util::Newable for AdaptiveTransitionFunctionMapNode {
    fn new() -> Self {
        Self::temp_link()
    }
}
*/

/*
impl AdaptiveTransitionFunctionMapNode {
    fn solidify(self) -> Self {
        match self {
            AdaptiveTransitionFunctionMapNode::TempLink(mut the_vec) => {
                let mut tmp: Vec<Option<Box<Self>>> = Vec::new();
                for dat in &mut the_vec {
                    tmp.push(if let Some(a) = dat.take() {
                        let to_solidify: Self = {
                            if let Ok(d) = Rc::try_unwrap(a) {
                                d.into_inner()
                            } else {
                                panic!("Cannot unwrap Rc");
                            }
                        };
                        Some(Box::new(Self::solidify(to_solidify)))
                    } else {
                        None
                    });
                }
                AdaptiveTransitionFunctionMapNode::Link(tmp)
            }
            AdaptiveTransitionFunctionMapNode::End(val) => {
                AdaptiveTransitionFunctionMapNode::End(val)
            }
            AdaptiveTransitionFunctionMapNode::Link(val) => {
                AdaptiveTransitionFunctionMapNode::Link(val)
            }
        }
    }
    #[inline]
    /// Function follow_path follows the path from a Start node all the way to the end
    pub fn follow_path(&self, input: Vec<&util::UsizeWrapper>) -> util::UsizeWrapper {
        let mut old = self;
        for data in input {
            old = old.next_node(data);
        }
        if let AdaptiveTransitionFunctionMapNode::End(dat) = old {
            dat.clone()
        } else {
            panic!("Incorrect number of dimensions");
        }
    }
    /// Function next_node returns the node pointed to by self and value
    #[inline]
    pub fn next_node(&self, value: &util::UsizeWrapper) -> &Self {
        if let AdaptiveTransitionFunctionMapNode::Link(a) = self {
            if let Some(d) = &a[value.get_data()].as_ref() {
                d
            } else {
                panic!("No value associated with given key");
            }
        } else {
            panic!("The type of node is incorrect");
        }
    }
    pub fn get_end_data(&self) -> Result<util::UsizeWrapper, usize> {
        if let AdaptiveTransitionFunctionMapNode::End(to_ret) = self {
            Ok(to_ret.clone())
        } else {
            Err(0)
        }
    }
    pub fn temp_link() -> Self {
        AdaptiveTransitionFunctionMapNode::TempLink(Vec::new())
    }
    pub fn end(value: &util::UsizeWrapper) -> Self {
        AdaptiveTransitionFunctionMapNode::End(value.clone())
    }
    pub fn link_links_to(&mut self, pointers: Vec<Option<Rc<RefCell<Self>>>>) {
        *self = AdaptiveTransitionFunctionMapNode::TempLink(pointers);
    }
    pub fn link_link_to(
        &mut self,
        value: &Option<util::UsizeWrapper>,
        pointer: Option<Rc<RefCell<Self>>>,
    ) -> Weak<RefCell<Self>> {
        let mut to_return = Weak::new();
        if let AdaptiveTransitionFunctionMapNode::TempLink(input_vector) = self {
            let usize_value = {
                if let Some(temp) = value.clone() {
                    temp.get_data()
                } else {
                    panic!("Attempted to make a link with a \"none\" value as the key");
                }
            };
            let mut is_end: bool = false;
            let remade_pointer = if let Some(a) = pointer {
                if let Ok(b) = Rc::try_unwrap(a) {
                    let inner = b.into_inner();
                    if let AdaptiveTransitionFunctionMapNode::End(c) = inner {
                        is_end = true;
                        Some(Rc::new(RefCell::new(
                            AdaptiveTransitionFunctionMapNode::End(c),
                        )))
                    } else if let AdaptiveTransitionFunctionMapNode::TempLink(c) = inner {
                        is_end = false;
                        Some(Rc::new(RefCell::new(
                            AdaptiveTransitionFunctionMapNode::TempLink(c),
                        )))
                    } else {
                        panic!("This shouldn't happen");
                    }
                } else {
                    panic!("Cannot unwrap Rc");
                }
            } else {
                None
            };
            if is_end {
                *self = {
                    if let Some(a) = remade_pointer {
                        if let Ok(b) = Rc::try_unwrap(a) {
                            b.into_inner()
                        } else {
                            panic!("This shouldn't happen");
                        }
                    } else {
                        panic!("This shouldn't happen");
                    }
                };
            } else {
                // If the current key is "too big", make room for it
                if input_vector.len() < usize_value {
                    let diff = usize_value - input_vector.len() + 1;
                    for _ in 0..diff {
                        input_vector.push(None);
                    }
                }
                if input_vector[usize_value] == None {
                    input_vector[usize_value] = remade_pointer;
                }
                if let Some(unwrapped) = &input_vector[usize_value] {
                    to_return = Rc::downgrade(&unwrapped);
                }
                *self = AdaptiveTransitionFunctionMapNode::TempLink(input_vector.to_vec());
            }
        } else {
            panic!("Improper use of link_link_to function");
        }
        to_return
    }
    pub fn add_link(
        &mut self,
        value: &Option<util::UsizeWrapper>,
        pointer: Option<Rc<RefCell<Self>>>,
    ) -> Weak<RefCell<Self>> {
        let mut to_return;
        if let AdaptiveTransitionFunctionMapNode::TempLink(_) = self {
            to_return = self.link_link_to(&value, pointer);
        } else {
            panic!("A link can only be added to a link node");
        }
        to_return
    }
}
*/

impl AdaptiveNeighborParser {
    #[inline]
    pub fn neighbor_func_parser<'b>(
        grid: &'b cellular_process::GridDataType<util::UsizeWrapper>,
        meta: &'b AdaptiveMetaData,
        address: usize,
    ) -> cellular_process::NeighborType<'b, util::UsizeWrapper> {
        let tmp = meta.get_neighbor_parser();
        tmp.apply_neighbors(grid, meta, address)
        //unimplemented!();
    }
    #[inline]
    pub fn apply_neighbors<'b>(
        &'b self,
        grid: &'b cellular_process::GridDataType<util::UsizeWrapper>,
        meta: &'b AdaptiveMetaData,
        address: usize,
    ) -> cellular_process::NeighborType<'b, util::UsizeWrapper> {
        let dimensions = cellular_process::GridMeta::get_dimensions(meta);
        let table = &self.addr_matrix;
        let mut to_ret: Vec<&'b util::NanoVec<util::UsizeWrapper>> = Vec::new();
        for item in table {
            if let AdaptiveNeighborParserNode::Absolute(the_vec) = item {
                to_ret.push(util::access_flattened_vec(
                    grid.get_data_ref(),
                    &(the_vec.iter().map(|&x| x as isize).collect::<Vec<isize>>()),
                    &dimensions.to_vec(),
                    0,
                    &self.edge_val,
                ))
            } else if let AdaptiveNeighborParserNode::Relative(the_vec) = item {
                to_ret.push(util::access_flattened_vec(
                    grid.get_data_ref(),
                    &the_vec,
                    &dimensions.to_vec(),
                    address,
                    &self.edge_val,
                ))
            } else {
                panic!("This shouldn't happen");
            }
        }
        cellular_process::NeighborType::new(to_ret, dimensions)
    }
}

impl util::Newable for AdaptiveNeighborParser {
    fn new() -> Self {
        Self {
            addr_matrix: Vec::new(),
            edge_val: util::NanoVec::new(1, util::UsizeWrapper::from(0)),
        }
    }
}

impl util::Parseable for AdaptiveNeighborParser {
    fn parse(input: &str) -> Self {
        let mut split = input.split(',');
        let mut temp_vec: Vec<AdaptiveNeighborParserNode> = Vec::new();
        let edge_case: util::NanoVec<util::UsizeWrapper> = {
            let cached = split.next().unwrap();
            let mut to_ret: util::NanoVec<util::UsizeWrapper> =
                util::NanoVec::new(0, util::UsizeWrapper::from(0));
            if cached.starts_with('e') {
                to_ret.push(util::Parseable::parse(&cached[1..cached.len()]))
            } else {
                panic!("Symbol table is invalid");
            }
            to_ret
        };
        for item in split {
            temp_vec.push(util::Parseable::parse(item));
        }
        Self {
            addr_matrix: temp_vec,
            edge_val: edge_case,
        }
    }
}

impl util::Parseable for AdaptiveNeighborParserNode {
    fn parse(input: &str) -> Self {
        let collected: Vec<char> = input.chars().collect::<Vec<char>>();
        if collected.len() <= 1 {
            panic!("Node is invalid");
        }
        let discrim: char = {
            if let Some(d) = collected[0].to_lowercase().nth(0) {
                d
            } else {
                panic!("Character has no lowercase version");
            }
        };
        let the_string = input[1..input.len()].to_string();
        let tokenized = {
            let tmp = the_string.split(' ');
            let mut to_return: Vec<isize> = Vec::new();
            for item in tmp {
                to_return.push(if let Ok(a) = item.parse::<isize>() {
                    a
                } else {
                    panic!("Position index is not an integer");
                });
            }
            to_return
        };
        if discrim == 'a' {
            // Absolute address
            AdaptiveNeighborParserNode::Absolute(
                tokenized
                    .iter()
                    .map(|x| *x as usize)
                    .collect::<Vec<usize>>(),
            )
        } else if discrim == 'r' {
            // Relative address
            AdaptiveNeighborParserNode::Relative(
                tokenized
                    .iter()
                    .map(|&x| x as isize)
                    .collect::<Vec<isize>>(),
            )
        } else {
            panic!("Discriminator is invalid");
        }
    }
}

impl util::Newable for DummyMetaData {
    fn new() -> Self {
        Self {}
    }
}
impl util::Parseable for DummyMetaData {
    fn parse(_data: &str) -> Self {
        util::Newable::new()
    }
}
impl util::Encodeable for DummyMetaData {
    fn encode(&self) -> String {
        String::new()
    }
}

impl AdaptiveMetaData {
    #[inline(always)]
    pub fn get_neighbor_parser(&self) -> &AdaptiveNeighborParser {
        &self.neighbor_parser
    }
    #[inline(always)]
    pub fn get_transition_function(&self) -> &AdaptiveTransitionFunction {
        &self.transition
    }
}

impl cellular_process::GridMeta for AdaptiveMetaData {
    fn get_dimensions(&self) -> &[usize] {
        self.dimensions.as_slice()
    }
}

impl util::Parseable for AdaptiveMetaData {
    fn parse(input: &str) -> Self {
        let split = util::parse_table_sections(input);
        if split.len() != 3 {
            panic!("Malformed metadata table");
        }
        Self {
            dimensions: util::parse_csv_list_native(&split[0], ','),
            neighbor_parser: util::Parseable::parse(&split[1]),
            transition: util::Parseable::parse(&split[2]),
        }
    }
}

impl util::Newable for AdaptiveMetaData {
    fn new() -> Self {
        Self {
            dimensions: Vec::new(),
            neighbor_parser: util::Newable::new(),
            transition: util::Newable::new(),
        }
    }
}

impl<'a> util::Parseable for AdaptiveCellularAutomata<'a> {
    fn parse(input: &str) -> Self {
        let split = util::parse_table_sections(input);
        if split.len() != 2 {
            panic!("Malformed metadata table")
        }
        let parsed = util::parse_csv_list(&split[1], ',');
        AdaptiveCellularAutomata {
            phantom: PhantomData,
            meta: util::Parseable::parse(&split[0]),
            initial: parsed,
        }
    }
}

impl<'a> AdaptiveCellularAutomata<'a> {
    pub fn test_1() {
        let neighbor_str = "e2,a1 1";
        let parser_str = "1 2";
        let data_str = "1,1,1";
        let dim_str = "3,1";
        let meta_str = util::encode_table_sections(&[
            String::from(dim_str),
            String::from(neighbor_str),
            String::from(parser_str),
        ]);
        let final_str = util::encode_table_sections(&[meta_str, String::from(data_str)]);
        dbg!(&final_str);
        let transition: &cellular_process::TransitionFunc<util::UsizeWrapper, AdaptiveMetaData> =
            &AdaptiveTransitionFunction::apply;
        let neighbor: &cellular_process::NeighborFuncParser<util::UsizeWrapper, AdaptiveMetaData> =
            &AdaptiveNeighborParser::neighbor_func_parser;
        let mut grid = cellular_process::Grid::<util::UsizeWrapper, AdaptiveMetaData>::decode(
            final_str.as_str(),
        );
        let meta = grid.get_meta().clone();
        grid.apply(transition, neighbor, &meta);
        dbg!(grid.get_data_read()); // it's `get_data_read`, not `get_data_mut` because the direction field is
                                    //flipped after apply, so the "old" data is actually the most recent.
    }
    fn get_meta_data(&self) -> &AdaptiveMetaData {
        &self.meta
    }
    fn get_initial_state(&self) -> &Vec<util::UsizeWrapper> {
        &self.initial
    }
}

impl<'a> CellularAutomata<'a, util::UsizeWrapper, AdaptiveMetaData>
    for AdaptiveCellularAutomata<'a>
{
    fn input_handler(
        _: &mut cellular_process::Grid<util::UsizeWrapper, AdaptiveMetaData>,
        _: &Reader,
        _: &Printer,
    ) {
    }
    fn output_handler(
        _: &cellular_process::Grid<util::UsizeWrapper, AdaptiveMetaData>,
        _: &Printer,
    ) {
    }
    fn run(&self, input: &str) {
        let transition: &cellular_process::TransitionFunc<util::UsizeWrapper, AdaptiveMetaData> =
            &AdaptiveTransitionFunction::apply;
        let neighbor: &cellular_process::NeighborFuncParser<util::UsizeWrapper, AdaptiveMetaData> =
            &AdaptiveNeighborParser::neighbor_func_parser;
        let mut grid =
            cellular_process::Grid::<util::UsizeWrapper, AdaptiveMetaData>::decode(input);
        let meta = grid.get_meta().clone();
        grid.apply(transition, neighbor, &meta);
        dbg!(grid);
        //TODO: finish
    }
}

impl util::Newable for AdaptiveTransitionFunctionMatrix {
    fn new() -> Self {
        Self {
            matrix: Vec::new(),
            dimensions: Vec::new(),
        }
    }
}

impl util::Parseable for AdaptiveTransitionFunctionMatrix {
    /// Function `parse` parses an AdaptiveTransitionFunctionMatrix from
    /// a string. The string must be formatted with rules seperated
    /// by semicolons, 'neighbor keys' seperated by spaces,
    /// and 'dimension keys' seperated by commas
    #[inline]
    fn parse(input: &str) -> Self {
        let mut to_return_vec: Vec<Option<util::NanoVec<util::UsizeWrapper>>> = Vec::new();

        let input_as_string = input.to_string();
        let split_input: Vec<&str> = input_as_string.split(';').collect();
        let tokens: Vec<Vec<util::NanoVec<util::UsizeWrapper>>> = {
            let mut to_return: Vec<Vec<util::NanoVec<util::UsizeWrapper>>> = Vec::new();
            let neighbor_count = split_input[0].split(' ').count() - 1;
            to_return.resize(neighbor_count + 1, Vec::new());
            for (indx1, j) in split_input.iter().enumerate() {
                let tmp: Vec<&str> = j.split(' ').collect();
                for item in tmp {
                    to_return[indx1].push({
                        let parsed = util::split_str(item, ',');
                        let mut temp_vec: util::NanoVec<util::UsizeWrapper> =
                            util::NanoVec::new(0, util::UsizeWrapper::from(0));
                        for itm in parsed {
                            temp_vec.push(util::Parseable::parse(itm));
                        }
                        temp_vec
                        /*
                        if let Ok(a) = item.parse::<usize>() {
                            a
                        } else {
                            panic!("Not an integer");
                        }
                        */
                    });
                }
            }
            to_return
        };
        if split_input.is_empty() {
            panic!("ERROR - error reading transition function symbol table - table is empty");
        }
        let num_neighbors = split_input[0].split(' ').count() - 1; // num_dimensions is the number of neighbors, -1 because the last token is not a neighbor, but the final value
        let num_dimensions = tokens[0][0].len();

        // Perform dimension sanity checks (make sure that all inputs have the same number of neighbors)
        for rule in &tokens {
            if rule.len() - 1 != num_neighbors {
                // `rule.len()-1` because the last 'neighbor' token isn't actually a neighbor, it's the final value
                panic!("Inconsistent number of neighbors in rule");
            }
            for cell in rule {
                if cell.len() != num_dimensions {
                    panic!("Inconsistent number of dimensions in cell");
                }
            }
        }

        let dimension_maxima: Vec<util::NanoVec<util::UsizeWrapper>> = {
            let mut to_return: Vec<util::NanoVec<util::UsizeWrapper>> = Vec::new();
            for _ in 0..num_neighbors {
                to_return.push(util::NanoVec::new(
                    num_dimensions,
                    util::UsizeWrapper::from(0),
                ));
            }
            for rule in &tokens {
                for (j, cell) in rule.iter().enumerate() {
                    debug_emit!("Iteration begin");
                    debug_val!(&cell);
                    if j != rule.len() - 1 {
                        // the last neighbor isn't actually a neighbor, so it doesn't need to be stored in the maxima
                        debug_emit!("Here");
                        for (k, data) in cell.into_iter().enumerate() {
                            debug_val!(&data);
                            if data.get_data() > to_return[j].at(k).get_data() {
                                to_return[j].set_at(k, *data);
                            }
                        }
                    } else {
                        debug_emit!("Rule discarded");
                    }
                    debug_emit!("Iteration end");
                }
            }
            to_return
        };
        debug_val!(&dimension_maxima);
        let to_pass_dim: Vec<&util::NanoVec<util::UsizeWrapper>> = {
            let mut to_ret: Vec<&util::NanoVec<util::UsizeWrapper>> = Vec::new();
            for item in dimension_maxima.iter() {
                to_ret.push(&item);
            }
            to_ret
        };

        let flattened_dimension_maxima: Vec<usize> = Self::stitch(to_pass_dim.as_slice())
            .iter()
            .map(|x| x.get_data())
            .collect::<Vec<usize>>();
        for _ in 0..(util::addr_normal_to_flattened_usize(
            &flattened_dimension_maxima,
            &(flattened_dimension_maxima
                .iter()
                .map(|x| x + 1)
                .collect::<Vec<usize>>()),
        )) {
            to_return_vec.push(None);
        }
        for rule in &tokens {
            let to_pass: Vec<&util::NanoVec<util::UsizeWrapper>> = {
                let mut to_ret: Vec<&util::NanoVec<util::UsizeWrapper>> = Vec::new();
                for item in (&rule).into_iter() {
                    to_ret.push(&item);
                }
                to_ret
            };
            to_return_vec
                [Self::compute_index(&to_pass[0..rule.len() - 1], &flattened_dimension_maxima)] =
                Some(rule[rule.len() - 1].clone());
        }
        Self {
            matrix: to_return_vec,
            dimensions: flattened_dimension_maxima,
        }
    }
}

impl AdaptiveTransitionFunctionMatrix {
    fn compute_index(input: &[&util::NanoVec<util::UsizeWrapper>], sizes: &[usize]) -> usize {
        util::addr_normal_to_flattened_usize_wrapper_ref(&Self::stitch(input), sizes)
    }
    fn stitch<'a, T: Clone + util::Encodeable + util::Newable + Debug>(
        input: &[&'a util::NanoVec<T>],
    ) -> Vec<&'a T> {
        let mut to_return: Vec<&T> = Vec::new();
        for item_1 in input {
            for item_2 in item_1.into_iter() {
                to_return.push(item_2);
            }
        }
        to_return
    }
    #[inline]
    pub fn follow_path(
        &self,
        path: &[&util::NanoVec<util::UsizeWrapper>],
    ) -> util::NanoVec<util::UsizeWrapper> {
        if let Some(a) = &self.matrix[Self::compute_index(path, &self.dimensions)] {
            a.clone()
        } else {
            panic!("No value associated with given key");
        }
    }
}