krabmaga 0.6.1

A modern developing art for reliable and efficient Agent-based Model (ABM) simulation with the Rust language.
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
use crate::engine::{
    fields::{field::Field, grid_option::GridOption},
    location::Int2D,
};

use cfg_if::cfg_if;

cfg_if! {
    if #[cfg(any(feature = "parallel", feature = "visualization", feature = "visualization_wasm"))]{
        use crate::utils::dbdashmap::DBDashMap;
    } else {
        use crate::rand::Rng;
        use std::cell::RefCell;
    }
}

cfg_if! {
    if #[cfg(any(feature = "parallel", feature = "visualization", feature = "visualization_wasm"))]{
        pub struct DenseNumberGrid2D<T: Copy + Clone> {
            pub locs: DBDashMap<Int2D, T>,
            pub width: i32,
            pub height: i32,
        }

        impl<T: Copy + Clone > DenseNumberGrid2D<T> {
            pub fn new(width: i32, height: i32) -> DenseNumberGrid2D<T> {
                DenseNumberGrid2D {
                    locs: DBDashMap::new(),
                    width: width.abs(),
                    height: height.abs(),
                }
            }

            pub fn apply_to_all_values<F>(&self, closure: F, option: GridOption)
            where
                F: Fn(&T) -> T,
            {
                match option {
                    GridOption::READ => {
                        self.locs.apply_to_all_values(closure);
                    },
                    GridOption::WRITE => {
                        self.locs.apply_to_all_values_write(closure);
                    },
                    GridOption::READWRITE => {
                        self.locs.apply_to_all_values_read_write(closure);
                    }
                }
            }

            pub fn get_value(&self, loc: &Int2D) -> Option<T> {
                match self.locs.get_read(loc){
                    Some(value) => Some(*value),
                    None => None
                }
            }

            pub fn get_value_unbuffered(&self, loc: &Int2D) -> Option<T> {
                match self.locs.get_write(loc){
                    Some(value) => Some(*value),
                    None => None
                }
            }

            pub fn set_value_location(&self, value: T, loc: &Int2D) {
                self.locs.insert(*loc, value);
            }

        }

        impl<T: Copy + Clone> Field for DenseNumberGrid2D<T> {
            fn lazy_update(&mut self) {
                self.locs.lazy_update();
            }

            fn update(&mut self) {
                self.locs.update();
            }
        }

    } else {

        /// Field with double buffering for dense matrix.
        /// You can insert/update values preserving a common state to read from in a step.
        /// As a values matrix, can contain one value per cell.
        ///
        ///
        /// A simpler version of the DenseGrid2D to use with simple values.
        /// This is useful to represent simulation spaces covered by a simple entity that can be represented with a non-agent structure.
        pub struct DenseNumberGrid2D<T: Copy + Clone + PartialEq> {

            // /// Matrix to write data. It is managed as a single Vector to improve performance.
            // pub locs: RefCell<Vec<Option<T>>>,
            // /// Matrix to read data.
            // pub rlocs: RefCell<Vec<Option<T>>>,

            pub locs: Vec<RefCell<Vec<Option<T>>>>,
            read: usize,
            write: usize,
            /// First dimension of the field
            pub width: i32,
            /// Second dimension of the field
            pub height: i32
        }

        impl<T: Copy + Clone + PartialEq> DenseNumberGrid2D<T> {
            /// Create new instance of DenseNumberGrid2D
            ///
            /// # Arguments
            /// * `width` - First dimension of the field
            /// * `height` - Second dimension of the field
            pub fn new(width: i32, height: i32) -> DenseNumberGrid2D<T> {
                DenseNumberGrid2D {
                    // locs: RefCell::new(std::iter::repeat_with(Vec::new).take((width * height) as usize).collect()),
                    // rlocs: RefCell::new(std::iter::repeat_with(Vec::new).take((width * height)as usize).collect()),
                    locs: vec![
                        RefCell::new(vec![None; (width * height) as usize]),
                        RefCell::new(vec![None; (width * height) as usize])
                    ],
                    // rlocs: RefCell::new(vec![None; (width * height) as usize]),
                    read: 0,
                    write: 1,
                    width: width.abs(),
                    height: height.abs(),
                }
            }

            /// Apply a closure to all values.
            ///
            /// # Arguments
            /// * `closure` - closure to apply to all values
            /// * `option` - option to read or write
            /// ## `option` possible values
            /// * `READ` - update the values from rlocs
            /// * `WRITE` - update the values from locs
            /// * `READWRITE` - check locs and rlocs simultaneously to apply the closure
            ///
            /// # Example
            /// ```
            /// let mut grid = DenseNumberGrid2D::<u16>::new(10, 10);
            /// for i in 0..10 {
            ///    for j in 0..10 {
            ///       grid.set_value_location(i as u16, &Int2D::new(i, j));
            ///   }
            /// }
            ///
            /// // Need WRITE or READWRITE option to update the values
            /// // because Read state isn't updated
            /// grid.apply_to_all_values(|x| x + 1, GridOption::WRITE);
            ///
            /// grid.lazy_update();
            /// grid.apply_to_all_values(|x| x - 1, GridOption::READ);
            ///
            /// ```
            pub fn apply_to_all_values<F>(&self, closure: F, option: GridOption)
            where
                F: Fn(&T) -> T,
            {
                match option {
                    GridOption::READ => {
                        let mut rlocs = self.locs[self.read].borrow_mut();
                        for value in rlocs.iter_mut() {
                            if value.is_none() {continue};
                            let result = closure(&value.unwrap());
                            *value = Some(result);
                        }

                    },
                    GridOption::WRITE => {
                        let mut locs = self.locs[self.write].borrow_mut();
                        let rlocs = self.locs[self.read].borrow();
                        for (i, value) in rlocs.iter().enumerate() {
                            if value.is_none() {continue};
                            let result = closure(&value.unwrap());
                            locs[i] = Some(result);
                        }
                    },
                    //works only with 1 element for bag
                    GridOption::READWRITE =>{

                        let mut locs = self.locs[self.write].borrow_mut();
                        let rlocs = self.locs[self.read].borrow_mut();
                        for (i, elem) in rlocs.iter().enumerate() {
                            if let Some(value) = locs[i] {
                                let result = closure(&value);
                                locs[i] = Some(result);
                            }
                            else if let Some(value) = elem {
                                let result = closure(value);
                                locs[i] = Some(result);
                            }
                        }
                    }
                }
            }

            /// Return the position of the first element that matches the given value.
            /// Return None if no element matches.
            ///
            /// # Arguments
            /// * `value` - value to search for
            ///
            /// # Example
            /// ```
            /// let mut grid = DenseNumberGrid2D::<u16>::new(10, 10);
            /// grid.set_value_location(1, &Int2D::new(5, 5));
            /// grid.set_value_location(1, &Int2D::new(6, 6));
            ///
            /// grid.lazy_update();
            /// let pos = grid.get_location(1);
            /// assert_eq!(pos, Some(Int2D::new(5, 5)));
            ///
            /// let none = grid.get_location(2);
            /// assert_eq!(none, None);
            /// ```
            ///
            pub fn get_location(&self, value: T) -> Option<Int2D> {
                let locs = self.locs[self.read].borrow();
                for i in  0..self.width{
                    for j in 0..self.height{
                        let elem = locs[(i *  self.height + j) as usize];
                        if elem.is_some() && elem.unwrap() == value {
                            return Some(Int2D {x: i, y: j});
                        }
                    }
                }
                None

            }

            /// Return the position of the first element that matches the given value from write state.
            /// Return None if no element matches.
            ///
            /// # Arguments
            /// * `value` - value to search for
            ///
            /// # Example
            /// ```
            /// let mut grid = DenseNumberGrid2D::<u16>::new(10, 10);
            /// grid.set_value_location(1, &Int2D::new(5, 5));
            /// grid.set_value_location(1, &Int2D::new(6, 6));
            ///
            /// // Work on write state, so on unupdated state
            /// let pos = grid.get_location_unbuffered(1);
            /// assert_eq!(pos, Some(Int2D::new(5, 5)));
            ///
            /// let none = grid.get_location_unbuffered(2);
            /// assert_eq!(none, None);
            ///
            /// grid.lazy_update();
            /// let pos = grid.get_location_unbuffered(1);
            /// assert_eq!(pos, None);
            /// ```
            ///
            pub fn get_location_unbuffered(&self, value: T) -> Option<Int2D> {
                let locs = self.locs[self.write].borrow();
                for i in  0..self.width{
                    for j in 0..self.height{
                        let elem = locs[(i *  self.height + j) as usize];
                        if elem.is_some() && elem.unwrap() == value {
                            return Some(Int2D {x: i, y: j});
                        }
                    }
                }
                None
            }

            /// Return all the empty bags of the read state.
            ///
            /// # Example
            /// ```
            /// let mut grid = DenseNumberGrid2D::<u16>::new(10, 10);
            /// let empty = grid.get_empty_bags();
            /// assert_eq!(empty.len(), 100);
            ///
            /// for i in 0..10 {
            ///   for j in 0..10 {
            ///      grid.set_value_location(1, &Int2D::new(i, j));
            ///   }
            /// }
            ///
            /// // Before an update, the grid is not updated, so the empty bags are still available
            /// let empty = grid.get_empty_bags();
            /// assert_eq!(empty.len(), 100);
            ///
            /// grid.lazy_update();
            /// let empty = grid.get_empty_bags();
            /// assert_eq!(empty.len(), 0);
            ///
            pub fn get_empty_bags(&self) -> Vec<Int2D>{
                let mut empty_bags = Vec::new();
                for i in 0 ..  self.width{
                    for j in 0 .. self.height{
                        let index = ((i * self.height) +j) as usize;
                        if self.locs[self.read].borrow()[index].is_none() {
                            empty_bags.push(Int2D{x: i, y: j});
                        }
                    }
                }
                empty_bags
            }

            /// Return a random empty bag in rlocs. `None` if no bags are available.
            ///
            /// # Example
            /// ```
            /// let mut grid = DenseNumberGrid2D::<u16>::new(10, 10);
            /// let empty = grid.get_random_empty_bag();
            /// assert(empty.is_some());
            ///
            /// grid.set_value_location(1, &empty.unwrap());
            /// grid.lazy_update();
            ///
            /// let empty2 = grid.get_random_empty_bag();
            /// assert(empty2.is_some());
            /// assert_ne!(empty.unwrap(), empty2.unwrap());
            ///
            /// ```
            pub fn get_random_empty_bag(&self) -> Option<Int2D>{

                let empty_bags = self.get_empty_bags();
                if empty_bags.is_empty() {
                    return None;
                }

                let mut rng = rand::rng();
                let index = rng.random_range(0..empty_bags.len());
                Some(empty_bags[index])
            }

            /// Return the value in a specific position. `None` if position is empty.
            ///
            /// # Arguments
            /// * `loc` - location to get the value from
            ///
            /// # Example
            /// ```
            /// let mut grid = DenseNumberGrid2D::<u16>::new(10, 10);
            /// grid.set_value_location(1, &Int2D::new(5, 5));
            ///
            /// let value = grid.get_value(&Int2D::new(5, 5));
            /// assert_eq!(value, None);
            ///
            /// grid.lazy_update();
            ///
            /// let value = grid.get_value(&Int2D::new(5, 5));
            /// assert_eq!(value, Some(1));
            /// ```
            ///
            pub fn get_value(&self, loc: &Int2D) -> Option<T> {
                let index = ((loc.x * self.height) + loc.y) as usize;
                let rlocs = self.locs[self.read].borrow();
                rlocs[index]
            }

            /// Return value of a specific position from write state. `None` if position is empty.
            ///
            /// Useful when you want to get some value written in the current step.
            /// For example, you want to get the value of a cell that is being written with a `set_value_location()`.
            ///
            /// # Arguments
            /// * `loc` - location to get the value from
            ///
            /// # Example
            /// ```
            /// let mut grid = DenseNumberGrid2D::<u16>::new(10, 10);
            /// grid.set_value_location(1, &Int2D::new(5, 5));
            /// let value = grid.get_value_unbuffered(&Int2D::new(5, 5));
            /// assert_eq!(value, Some(1));
            ///
            /// grid.lazy_update();
            /// let value = grid.get_value_unbuffered(&Int2D::new(5, 5));
            /// assert_eq!(value, None);
            ///
            /// ```
            pub fn get_value_unbuffered(&self, loc: &Int2D) -> Option<T> {
                let index = ((loc.x * self.height) + loc.y) as usize;
                let locs = self.locs[self.write].borrow();
                locs[index]
            }


            /// Read and call a closure to all values inside Read state
            ///
            /// # Arguments
            /// * `closure` - closure to apply to all values
            ///
            /// # Example
            /// ```
            /// let mut grid = DenseNumberGrid2D::<u16>::new(10, 10);
            /// for i in 0..10 {
            ///     for j in 0..10 {
            ///         grid.set_value_location(1, &Int2D::new(i, j));
            ///     }
            /// }
            ///
            /// grid.lazy_update();
            /// grid.iter_values(|&loc, &value| {
            ///     // do something with loc and value
            ///     // can't modify the grid here
            /// };
            ///
            /// ```
            pub fn iter_values<F>(&self, closure: F)
                where
                    F: Fn(
                        &Int2D, //location
                        &T, //value
                    )
            {
                for i in 0 .. self.width{
                    for j in 0 .. self.height{
                        let index = ((i * self.height) + j) as usize;
                        let locs = self.locs[self.read].borrow()[index];
                        if let Some(value) = locs {
                            closure(&Int2D{x: i, y: j}, &value);
                        }
                        // if !locs.is_empty() {
                        //     for obj in locs{
                        //         closure(&Int2D{x: i, y: j}, obj);
                        //     }
                        // }
                    }
                }
            }

            /// Read and apply a closure to all values inside Write state.
            /// Useful when you want to iterate over all values written in the current step.
            ///
            /// # Arguments
            /// * `closure` - closure to apply to all values
            ///
            /// # Example
            ///
            /// ```rust
            /// let mut grid = DenseNumberGrid2D::<u16>::new(10, 10);
            /// for i in 0..10 {
            ///     for j in 0..10 {
            ///       grid.set_value_location(1, &Int2D::new(i, j));
            ///     }
            /// }
            ///
            /// // can't modify the grid here
            /// grid.iter_values_unbuffered(|&loc, &value| {
            ///    some_function(loc, value);
            /// };
            ///
            /// ```
            pub fn iter_values_unbuffered<F>(&self, closure: F)
            where
                F: Fn(
                    &Int2D, //location
                    &T //value
                )
            {
                for i in 0 ..  self.width{
                    for j in 0 .. self.height{
                        let index = ((i * self.height) + j) as usize;
                        let locs = self.locs[self.write].borrow()[index];
                        if let Some(value) = locs {
                            closure(&Int2D{x: i, y: j}, &value);
                        }
                        // if !locs.is_empty() {
                        //     for obj in locs{
                        //         closure(&loc, obj);
                        //     }
                        // }
                    }
                }
            }


            /// Write a value in a specific position.
            /// Thanks to the double buffering, you havent to worry about remove value of previous step.
            ///
            /// # Arguments
            /// * `value` - value to set at the location
            /// * `loc` - location to set the value at
            ///
            /// # Example
            /// ```
            /// let mut grid = DenseNumberGrid2D::<u16>::new(10, 10);
            /// grid.set_value_location(1, &Int2D::new(5, 5));
            /// grid.set_value_location(2, &Int2D::new(5, 5));
            ///
            /// grid.lazy_update();
            ///
            /// let value = grid.get_value(&Int2D::new(5, 5));
            /// assert_ne!(value, Some(1));
            /// assert_eq!(value, Some(2));
            /// ```
            pub fn set_value_location(&self, value: T, loc: &Int2D) {
                let index = ((loc.x * self.height) + loc.y) as usize;
                let mut locs = self.locs[self.write].borrow_mut();
                locs[index] = Some(value);

                // if !locs[index].is_empty() {
                //     locs[index].retain(|&obj| obj != value);
                // }
                // locs[index].push(value);
            }

            /// Remove a value from write state.
            /// You have to use it to remove a value written/updated in this step.
            /// Double buffering swap the write and read state at the end of the step, so you have to call
            /// this function only if the value was written/set in this step.
            ///
            /// # Arguments
            /// * `loc` - location to remove the value from
            ///
            /// # Example
            /// ```
            /// let mut grid = DenseNumberGrid2D::<u16>::new(10, 10);
            /// grid.set_value_location(1, &Int2D::new(5, 5));
            /// grid.remove_value_location(&Int2D::new(5, 5));
            ///
            /// let value = grid.get_value_unbuffered(&Int2D::new(5, 5));
            /// assert_eq!(value, None);
            ///
            /// grid.lazy_update();
            /// let value = grid.get_value(&Int2D::new(5, 5));
            /// assert_eq!(value, None);
            ///
            /// ```
            ///
            pub fn remove_value_location(&self, loc: &Int2D) {
                let mut locs = self.locs[self.write].borrow_mut();
                let index = ((loc.x * self.height) + loc.y) as usize;
                locs[index] = None;
            }


        }

        impl<T: Copy + Clone + PartialEq> Field for DenseNumberGrid2D<T> {
            /// Swap read and write states of the field and clear write State
            fn lazy_update(&mut self){

                std::mem::swap(&mut self.read, &mut self.write);

                let mut locs = self.locs[self.write].borrow_mut();
                //set None all elements
                for i in 0..locs.len(){
                    locs[i] = None;
                }

                // for i in 0..locs.len(){
                //     locs[i].clear();
                // }
            }

            /// Copy values from write state into read one
            fn update(&mut self) {
                // copy locs to rlocs
                let mut locs = self.locs[self.write].borrow_mut();
                let mut rlocs = self.locs[self.read].borrow_mut();
                for i in 0..locs.len(){
                    rlocs[i] = locs[i];
                    locs[i] = None;
                }
            }
        }

    }
}