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
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
use crate::engine::{
fields::field::Field,
location::{Int2D, Real2D},
};
use core::fmt::Display;
use std::cmp;
use std::hash::Hash;
/// A trait to request implementation of the two basic function that must be implemented
pub trait Location2D<Real2D> {
fn get_location(self) -> Real2D;
fn set_location(&mut self, loc: Real2D);
}
use cfg_if::cfg_if;
cfg_if! {
if #[cfg(any(feature = "visualization", feature = "visualization_wasm", feature = "parallel"))] {
use crate::utils::dbdashmap::DBDashMap;
} else {
use std::cell::RefCell;
use crate::*;
}
}
cfg_if! {
if #[cfg(any(feature = "parallel", feature = "visualization", feature = "visualization_wasm"))]{
pub struct Field2D<O: Location2D<Real2D> + Clone + Hash + Eq + Copy + Display> {
pub findex: DBDashMap<O, Int2D>,
pub fbag: DBDashMap<Int2D, Vec<O>>,
pub floc: DBDashMap<O, Real2D>,
pub width: f32,
pub height: f32,
pub discretization: f32,
pub toroidal: bool,
}
//field 2d
impl<O: Location2D<Real2D> + Clone + Hash + Eq + Copy + Display> Field2D<O> {
pub fn new(w: f32, h: f32, d: f32, t: bool) -> Field2D<O> {
Field2D {
findex: DBDashMap::new(),
fbag: DBDashMap::new(),
floc: DBDashMap::new(),
width: w,
height: h,
discretization: d,
toroidal: t,
}
}
fn discretize(&self, loc: &Real2D) -> Int2D {
let x_floor = (loc.x/self.discretization).floor();
let x_floor = x_floor as i32;
let y_floor = (loc.y/self.discretization).floor();
let y_floor = y_floor as i32;
Int2D {
x: x_floor,
y: y_floor,
}
}
pub fn get_neighbors_within_distance(&self, loc: Real2D, dist: f32) -> Vec<O> {
let density = ((self.width * self.height) as usize)/(self.findex.r_len());
let sdist = (dist * dist) as usize;
let mut neighbors: Vec<O> = Vec::with_capacity(density as usize * sdist);
if dist <= 0.0 {
return neighbors;
}
let disc_dist = (dist/self.discretization).floor() as i32;
let disc_loc = self.discretize(&loc);
let max_x = (self.width/self.discretization).ceil() as i32;
let max_y = (self.height/self.discretization).ceil() as i32;
let mut min_i = disc_loc.x - disc_dist;
let mut max_i = disc_loc.x + disc_dist;
let mut min_j = disc_loc.y - disc_dist;
let mut max_j = disc_loc.y + disc_dist;
if self.toroidal {
min_i = cmp::max(0, min_i);
max_i = cmp::min(max_i, max_x-1);
min_j = cmp::max(0, min_j);
max_j = cmp::min(max_j, max_y-1);
}
for i in min_i..max_i+1 {
for j in min_j..max_j+1 {
let bag_id = Int2D {
x: t_transform(i, max_x),
y: t_transform(j, max_y),
};
let check = check_circle(&bag_id, self.discretization, self.width, self.height, &loc, dist, self.toroidal);
let vector = match self.fbag.get_read(&bag_id) {
Some(i) => i,
None => continue,
};
for elem in vector{
if (check == 0 &&
distance(&loc, &(elem.get_location()), self.width, self.height, self.toroidal) <= dist) ||
check == 1
{
neighbors.push(*elem);
}
}
}
}
neighbors
}
pub fn get_neighbors_within_relax_distance(&self, loc: Real2D, dist: f32) -> Vec<O> {
let density = ((self.width * self.height) as usize)/(self.findex.r_len());
let sdist = (dist * dist) as usize;
let mut neighbors: Vec<O> = Vec::with_capacity(density as usize * sdist);
if dist <= 0.0 {
return neighbors;
}
let disc_dist = (dist/self.discretization).floor() as i32;
let disc_loc = self.discretize(&loc);
let max_x = (self.width/self.discretization).ceil() as i32;
let max_y = (self.height/self.discretization).ceil() as i32;
let mut min_i = disc_loc.x - disc_dist;
let mut max_i = disc_loc.x + disc_dist;
let mut min_j = disc_loc.y - disc_dist;
let mut max_j = disc_loc.y + disc_dist;
if self.toroidal {
min_i = cmp::max(0, min_i);
max_i = cmp::min(max_i, max_x-1);
min_j = cmp::max(0, min_j);
max_j = cmp::min(max_j, max_y-1);
}
for i in min_i..max_i+1 {
for j in min_j..max_j+1 {
let bag_id = Int2D {
x: t_transform(i, max_x),
y: t_transform(j, max_y),
};
let vector = match self.fbag.get_read(&bag_id) {
Some(i) => i,
None => continue,
};
for elem in vector {
neighbors.push(*elem);
}
}
}
neighbors
}
// take an object and check if it is in the field
// if so return the object
// mainly used for visualization
pub fn get(&self, object: &O) -> Option<&O> {
match self.floc.get_key_value(object) {
Some((updated_object, _loc)) => Some(updated_object),
None => None,
}
}
// take a location and return the corresponding objects on that location
pub fn get_objects(&self, loc: Real2D) -> Vec<&O> {
let bag = self.discretize(&loc);
let mut result = Vec::new();
match self.fbag.get_read(&bag){
Some(v) => {
for el in v{
result.push(el);
}
}
None => ()
}
result
}
// take an object and return the corresponding location
pub fn get_location(&self, object: O) -> Option<&Real2D> {
self.floc.get_read(&object)
}
// take an object and return the corresponding location from the write state
pub fn get_location_unbuffered(&self, object: O) -> Option<Real2D> {
let mut loc = self.floc.get_write(&object).expect("error on get_write");
Some(*loc.value_mut())
}
// take an object and check if it is in the field
// if so return the object from the write bags
// mainly used for visualization
pub fn get_unbuffered(&self, object: &O) -> Option<O> {
match self.floc.get_write(object){
Some(loc) =>{
let real_loc = self.discretize(&loc);
for obj in self.fbag.get_write(&real_loc).expect("error on get_write").value_mut(){
if obj == object {
return Some(*obj);
}
}
}, None =>{
return None;
}
}
None
}
// return the number of objects in the field
pub fn num_objects(&self) -> usize {
self.findex.r_len()
}
// return the number of objects in the field on that location
pub fn num_objects_at_location(&self, loc: Real2D) -> usize {
let bag = self.discretize(&loc);
match self.fbag.get_read(&bag){
Some(v) => {
v.len()
}
None => 0
}
}
// put the object in that location
pub fn set_object_location(&self, object: O, loc: Real2D) {
let bag = self.discretize(&loc);
self.floc.insert(object, loc);
self.findex.insert(object, bag);
match self.fbag.get_write(&bag){
Some(v) => {
let mut v = v;
v.push(object);
}
None => {
let mut v = Vec::new();
v.push(object);
self.fbag.insert(bag,v);
}
};
}
}
impl<O: Location2D<Real2D> + Clone + Hash + Eq + Copy + Display> Field for Field2D<O>{
fn update(&mut self){
self.floc.update();
self.fbag.update();
self.findex.update();
}
fn lazy_update(&mut self){
self.floc.lazy_update();
self.fbag.lazy_update();
self.findex.lazy_update();
}
}
} else {
/// Sparse matrix structure modelling agent interactions on a 2D real space with coordinates represented by 2D f32 tuples
pub struct Field2D<O: Location2D<Real2D> + Clone + Hash + Eq + Copy + Display> {
/// Matrix to write data. Vector of vectors that have a generic Object O inside
pub bags: Vec<RefCell<Vec<Vec<O>>>>,
read: usize,
write: usize,
/// Matrix to read data. Vector of vectors that have a generic Object O inside
// pub rbags: RefCell<Vec<Vec<O>>>,
/// Number of agents inside the field
pub nagents: RefCell<usize>,
/// First dimension of the field
pub width: f32,
/// Second dimension of the field
pub height: f32,
/// Value to discretize `Real2D` positions to our Matrix
pub discretization: f32,
/// `true` if you want a Toroidal field, `false` otherwise
pub toroidal: bool,
/// Discretized height of the field
pub dh: i32,
/// Discretized width of the field
pub dw: i32,
/// Field density
pub density_estimation:usize,
/// `true` if you want calculate field density, `false` otherwise
pub density_estimation_check:bool,
}
impl<O: Location2D<Real2D> + Clone + Hash + Eq + Copy + Display> Field2D<O> {
/// Create a new `Field2D`
///
/// # Arguments
/// * `w` - Width, first dimension of the field
/// * `h` - Height, second dimension of the field
/// * `d` - Value to discretize `Real2D` positions to our Matrix
/// * `t` - `true` if you want a Toroidal field, `false` otherwise
pub fn new(w: f32, h: f32, d: f32, t: bool) -> Field2D<O> {
Field2D {
// bags: RefCell::new(std::iter::repeat_with(Vec::new).take((((w/d).ceil()+1.0) * ((h/d).ceil() +1.0))as usize).collect()),
bags: vec![RefCell::new(std::iter::repeat_with(Vec::new).take((((w/d).ceil()+1.0) * ((h/d).ceil() +1.0))as usize).collect()),
RefCell::new(std::iter::repeat_with(Vec::new).take((((w/d).ceil()+1.0) * ((h/d).ceil() +1.0))as usize).collect())],
read: 0,
write: 1,
// rbags: RefCell::new(std::iter::repeat_with(Vec::new).take((((w/d).ceil()+1.0) * ((h/d).ceil() +1.0))as usize).collect()),
nagents: RefCell::new(0),
width: w,
height: h,
discretization: d,
toroidal: t,
dh: ((h/d).ceil() as i32 +1),
dw: ((w/d).ceil() as i32 +1),
density_estimation:0,
density_estimation_check:false
}
}
/// Map coordinates of an object into matrix indexes
///
/// # Arguments
/// * `loc` - `Real2D` coordinates of the object
fn discretize(&self, loc: &Real2D) -> Int2D {
let x_floor = (loc.x/self.discretization).floor();
let x_floor = x_floor as i32;
let y_floor = (loc.y/self.discretization).floor();
let y_floor = y_floor as i32;
Int2D {
x: x_floor,
y: y_floor,
}
}
/// Map matrix indexes into coordinates of an object
///
/// # Arguments
/// * `loc` - `Int2D` indexes of the object
fn not_discretize(&self, loc: &Int2D) -> Real2D {
let x_real = loc.x as f32 * self.discretization;
let y_real = loc.y as f32 * self.discretization;
Real2D {
x: x_real,
y: y_real,
}
}
/// Return the set of objects within a certain distance.
///
/// # Arguments
/// * `loc` - `Real2D` coordinates of the object
/// * `dist` - Distance to look for objects
///
/// # Example
/// ```
/// struct Object {
/// id: u32
/// }
///
/// let DISCRETIZATION = 0.5;
/// let TOROIDAL = true;
/// let mut field = Field2D::new(10.0, 10.0, DISCRETIZATION, TOROIDAL);
/// field.set_object_location(&Object{id: 0}, Real2D {x: 0.0, y: 0.0} );
/// field.set_object_location(&Object{id: 1}, Real2D {x: 3.0, y: 3.0} );
///
/// field.lazy_update();
///
/// let objects = field.get_objects_within_distance(&Real2D {x: 0.0, y: 0.0}, 2.0);
/// assert_eq!(objects.len(), 1);
///
/// let objects = field.get_objects_within_distance(&Real2D {x: 0.0, y: 0.0}, 5.0);
/// assert_eq!(objects.len(), 2);
///
/// let objects = field.get_objects_within_distance(&Real2D {x: 6.0, y: 6.0}, 1.0);
/// assert_eq!(objects.len(), 0);
///
/// ```
pub fn get_neighbors_within_distance(&self, loc: Real2D, dist: f32) -> Vec<O> {
let mut neighbors: Vec<O>;
if self.density_estimation_check {
neighbors = Vec::with_capacity(self.density_estimation*2);
}else {neighbors = Vec::new();}
if dist <= 0.0 {
return neighbors;
}
if dist <= 0.0 {
return neighbors;
}
let disc_dist = (dist/self.discretization).floor() as i32;
let disc_loc = self.discretize(&loc);
let max_x = (self.width/self.discretization).ceil() as i32;
let max_y = (self.height/self.discretization).ceil() as i32;
let mut min_i = disc_loc.x - disc_dist;
let mut max_i = disc_loc.x + disc_dist;
let mut min_j = disc_loc.y - disc_dist;
let mut max_j = disc_loc.y + disc_dist;
if self.toroidal {
min_i = cmp::max(0, min_i);
max_i = cmp::min(max_i, max_x-1);
min_j = cmp::max(0, min_j);
max_j = cmp::min(max_j, max_y-1);
}
for i in min_i..max_i+1 {
for j in min_j..max_j+1 {
let bag_id = Int2D {
x: t_transform(i, max_x),
y: t_transform(j, max_y),
};
let check = check_circle(&bag_id, self.discretization, self.width, self.height, &loc, dist, self.toroidal);
let index = ((bag_id.x * self.dh) + bag_id.y) as usize;
// let bags = self.rbags.borrow();
let bags = self.bags[self.read].borrow();
for elem in &bags[index]{
if (check == 0 && distance(&loc, &(elem.get_location()), self.width, self.height, self.toroidal) <= dist) || check == 1 {
neighbors.push(*elem);
}
}
}
}
neighbors
}
/// Return the set of objects within a certain distance. No circle check.
///
/// # Arguments
/// * `loc` - `Real2D` coordinates of the object
/// * `dist` - Distance to look for objects
///
/// # Example
/// ```
/// struct Object {
/// id: u32
/// }
///
/// let DISCRETIZATION = 0.5;
/// let TOROIDAL = true;
/// let mut field = Field2D::new(10.0, 10.0, DISCRETIZATION, TOROIDAL);
/// field.set_object_location(&Object{id: 0}, Real2D {x: 0.0, y: 0.0} );
/// field.set_object_location(&Object{id: 1}, Real2D {x: 3.0, y: 3.0} );
///
/// field.lazy_update();
///
/// let objects = field.get_objects_within_relax_distance(&Real2D {x: 0.0, y: 0.0}, 2.0);
/// assert_eq!(objects.len(), 1);
///
/// let objects = field.get_objects_within_relax_distance(&Real2D {x: 0.0, y: 0.0}, 5.0);
/// assert_eq!(objects.len(), 2);
///
/// let objects = field.get_objects_within_relax_distance(&Real2D {x: 6.0, y: 6.0}, 1.0);
/// assert_eq!(objects.len(), 0);
///
/// ```
pub fn get_neighbors_within_relax_distance(&self, loc: Real2D, dist: f32) -> Vec<O> {
let mut neighbors;
if self.density_estimation_check {
neighbors = Vec::with_capacity(self.density_estimation*2);
}else {
neighbors = Vec::new();
}
if dist <= 0.0 {
return neighbors;
}
let disc_dist = (dist/self.discretization).floor() as i32;
let disc_loc = self.discretize(&loc);
let max_x = (self.width/self.discretization).ceil() as i32;
let max_y = (self.height/self.discretization).ceil() as i32;
let mut min_i = disc_loc.x - disc_dist;
let mut max_i = disc_loc.x + disc_dist;
let mut min_j = disc_loc.y - disc_dist;
let mut max_j = disc_loc.y + disc_dist;
if self.toroidal {
min_i = cmp::max(0, min_i);
max_i = cmp::min(max_i, max_x-1);
min_j = cmp::max(0, min_j);
max_j = cmp::min(max_j, max_y-1);
}
for i in min_i..max_i+1 {
for j in min_j..max_j+1 {
let bag_id = Int2D {
x: t_transform(i, max_x),
y: t_transform(j, max_y),
};
let index = ((bag_id.x * self.dh) + bag_id.y) as usize;
let bags = self.bags[self.read].borrow_mut();
for elem in &bags[index] {
neighbors.push(*elem);
}
}
}
neighbors
}
/// Return objects at a specific location
///
/// # Arguments
/// * `loc` - `Real2D` coordinates of the object
///
/// # Example
/// ```
/// struct Object {
/// id: u32
/// }
///
/// let DISCRETIZATION = 0.5;
/// let TOROIDAL = true;
/// let mut field = Field2D::new(10.0, 10.0, DISCRETIZATION, TOROIDAL);
///
/// field.set_object_location(&Object{id: 0}, Real2D {x: 5.0, y: 5.0} );
/// field.set_object_location(&Object{id: 1}, Real2D {x: 5.0, y: 5.0} );
///
/// let none = field.get_objects(&Real2D {x: 5.0, y: 5.0});
/// assert_eq!(none.len(), 0);
///
/// field.lazy_update();
/// let objects = field.get_objects(&Real2D {x: 5.0, y: 5.0});
/// assert_eq!(objects.len(), 2);
///
/// ```
pub fn get_objects(&self, loc: Real2D) -> Vec<O>{
let bag = self.discretize(&loc);
let index = ((bag.x * self.dh) + bag.y) as usize;
let rbags = self.bags[self.read].borrow();
rbags[index].clone()
}
/// Return objects at a specific location
///
/// # Arguments
/// * `loc` - `Real2D` coordinates of the object
///
/// # Example
/// ```
/// struct Object {
/// id: u32
/// }
///
/// let DISCRETIZATION = 0.5;
/// let TOROIDAL = true;
/// let mut field = Field2D::new(10.0, 10.0, DISCRETIZATION, TOROIDAL);
///
/// field.set_object_location(&Object{id: 0}, Real2D {x: 5.0, y: 5.0} );
/// field.set_object_location(&Object{id: 1}, Real2D {x: 5.0, y: 5.0} );
///
/// let objects = field.get_objects_unbuffered(&Real2D {x: 5.0, y: 5.0});
/// assert_eq!(objects.len(), 2);
///
/// field.lazy_update();
/// let objects = field.get_objects_unbuffered(&Real2D {x: 5.0, y: 5.0});
/// assert_eq!(objects.len(), 0);
///
/// ```
pub fn get_objects_unbuffered(&self, loc: Real2D) -> Vec<O>{
let bag = self.discretize(&loc);
let index = ((bag.x * self.dh) + bag.y) as usize;
let bags = self.bags[self.write].borrow();
bags[index].clone()
}
/// Iterate over the read state and apply the closure.
///
/// # Arguments
/// * `closure` - closure to apply to each element of the matrix
///
/// # Example
/// ```
/// struct Object {
/// id: u32
/// }
///
/// let DISCRETIZATION = 0.5;
/// let TOROIDAL = true;
/// let mut field = Field2D::new(10.0, 10.0, DISCRETIZATION, TOROIDAL);
///
/// field.set_object_location(&Object{id: 0}, Real2D {x: 5.0, y: 5.0} );
/// field.set_object_location(&Object{id: 1}, Real2D {x: 4.0, y: 4.0} );
/// field.set_object_location(&Object{id: 2}, Real2D {x: 1.5, y: 1.5} );
///
/// field.lazy_update();
///
/// field.iter_objects(|&loc, obj| {
/// if loc.x == 5.0 && loc.y == 5.0 {
/// assert_eq!(obj.id, 0);
/// } else if loc.x == 4.0 && loc.y == 4.0 {
/// assert_eq!(obj.id, 1);
/// } else if loc.x == 1.5 && loc.y == 1.5 {
/// assert_eq!(obj.id, 2);
/// } else {
/// panic!("Unexpected object");
/// }
/// });
///
/// ```
///
pub fn iter_objects<F>(&self, closure: F)
where
F: Fn(
&Real2D, //location
&O, //value
)
{
for i in 0 .. self.dw{
for j in 0 .. self.dh{
let index = ((i * self.dh) + j) as usize;
let locs = &self.bags[self.read].borrow()[index];
if !locs.is_empty() {
let real_pos = self.not_discretize(&Int2D {x: i, y: j});
for obj in locs{
closure(&real_pos, obj);
}
}
}
}
}
/// Iterate over all objects inside the field and apply the closure.
/// Useful when you want to access to all the objects changed/executed into the current step.
///
/// # Arguments
/// * `closure` - closure to apply to each element of the matrix
///
/// # Example
/// ```
/// struct Object {
/// id: u32
/// }
///
/// let DISCRETIZATION = 0.5;
/// let TOROIDAL = true;
/// let mut field = Field2D::new(10.0, 10.0, DISCRETIZATION, TOROIDAL);
///
/// field.set_object_location(&Object{id: 0}, Real2D {x: 5.0, y: 5.0} );
/// field.set_object_location(&Object{id: 1}, Real2D {x: 4.0, y: 4.0} );
/// field.set_object_location(&Object{id: 2}, Real2D {x: 1.5, y: 1.5} );
///
/// // no update required, working on the write state
///
/// field.iter_objects_unbuffered(|&loc, obj| {
/// if loc.x == 5.0 && loc.y == 5.0 {
/// assert_eq!(obj.id, 0);
/// } else if loc.x == 4.0 && loc.y == 4.0 {
/// assert_eq!(obj.id, 1);
/// } else if loc.x == 1.5 && loc.y == 1.5 {
/// assert_eq!(obj.id, 2);
/// } else {
/// panic!("Unexpected object");
/// }
/// });
///
/// field.lazy_update();
///
/// ```
pub fn iter_objects_unbuffered<F>(&self, closure: F)
where
F: Fn(
&Real2D, //location
&O, //value
)
{
for i in 0 .. self.dw{
for j in 0 .. self.dh{
let index = ((i * self.dh) + j) as usize;
let locs = &self.bags[self.write].borrow()[index];
if !locs.is_empty() {
let real_pos = self.not_discretize(&Int2D {x: i, y: j});
for obj in locs{
closure(&real_pos, obj);
}
}
}
}
}
/// Return all the empty bags from read state.
///
/// # Example
/// ```
/// struct Object {
/// id: u32
/// }
///
/// let DISCRETIZATION = 0.5;
/// let TOROIDAL = true;
/// let mut field = Field2D::new(10.0, 10.0, DISCRETIZATION, TOROIDAL);
///
/// let empty_bags = field.get_empty_bags();
/// assert_eq!(empty_bags.len(), 400); // 400 = (10.0 / 0.5) * (10.0 / 0.5)
///
/// field.set_object_location(&Object{id: 0}, Real2D {x: 5.0, y: 5.0} );
/// field.set_object_location(&Object{id: 1}, Real2D {x: 4.0, y: 4.0} );
/// field.set_object_location(&Object{id: 2}, Real2D {x: 1.5, y: 1.5} );
///
/// let empty_bags = field.get_empty_bags();
/// assert_eq!(empty_bags.len(), 400); // 400 = (10.0 / 0.5) * (10.0 / 0.5)
///
/// field.lazy_update();
///
/// let empty_bags = field.get_empty_bags();
/// assert_eq!(empty_bags.len(), 397);
/// ```
///
pub fn get_empty_bags(&self) -> Vec<Real2D>{
let mut empty_bags = Vec::new();
for i in 0 .. self.dw{
for j in 0 .. self.dh{
let index = ((i * self.dh) + j) as usize;
if self.bags[self.read].borrow()[index].is_empty() {
empty_bags.push(self.not_discretize(&Int2D{x: i, y: j}));
}
}
}
empty_bags
}
/// Return a random empty bag from read state. `None` if no bags are available.
///
/// # Example
/// ```
/// struct Object {
/// id: u32
/// }
///
/// let DISCRETIZATION = 0.5;
/// let TOROIDAL = true;
/// let mut field = Field2D::new(10.0, 10.0, DISCRETIZATION, TOROIDAL);
///
/// let empty_bag = field.get_random_empty_bag();
/// assert!(empty_bag.is_some());
///
/// field.set_object_location(&Object{id: 0}, Real2D {x: 5.0, y: 5.0} );
/// field.lazy_update();
///
/// let empty_bag2 = field.get_random_empty_bag();
/// assert!(empty_bag.is_some());
/// assert_ne!(empty_bag.unwrap(), empty_bag2.unwrap());
///
/// ```
pub fn get_random_empty_bag(&self) -> Option<Real2D>{
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 number of object at a specific location
///
/// # Arguments
/// * `loc` - `Real2D` coordinates of the location to check
///
/// # Example
/// ```
/// struct Object {
/// id: u32
/// }
///
/// let DISCRETIZATION = 0.5;
/// let TOROIDAL = true;
/// let mut field = Field2D::new(10.0, 10.0, DISCRETIZATION, TOROIDAL);
///
/// field.set_object_location(&Object{id: 0}, Real2D {x: 5.0, y: 5.0} );
/// field.set_object_location(&Object{id: 1}, Real2D {x: 1.5, y: 1.5} );
/// field.set_object_location(&Object{id: 2}, Real2D {x: 4.0, y: 4.0} );
///
/// field.lazy_update();
///
/// let one = field.get_number_of_objects_at_location(&Real2D {x: 5.0, y: 5.0});
/// assert_eq!(one, 1);
/// let two = field.get_number_of_objects_at_location(&Real2D {x: 1.5, y: 1.5});
/// assert_eq!(two, 2);
/// let zero = field.get_number_of_objects_at_location(&Real2D {x: 8.0, y: 8.0});
/// assert_eq!(zero, 0);
/// ```
///
pub fn num_objects_at_location(&self, loc: Real2D) -> usize {
let bag = self.discretize(&loc);
let index = ((bag.x * self.dh) + bag.y) as usize;
let rbags = self.bags[self.read].borrow();
rbags[index].len()
}
/// Insert an object into a specific position
///
/// # Arguments
/// * `obj` - Object to insert
/// * `loc` - `Real2D` coordinates where to insert the object
///
/// # Example
/// ```
/// struct Object {
/// id: u32
/// }
///
/// let DISCRETIZATION = 0.5;
/// let TOROIDAL = true;
/// let mut field = Field2D::new(10.0, 10.0, DISCRETIZATION, TOROIDAL);
///
/// field.set_object_location(&Object{id: 0}, Real2D {x: 5.0, y: 5.0} );
///
/// let obj = field.get_objects_unbuffered(&Real2D {x: 5.0, y: 5.0});
/// assert_eq!(obj.len(), 1);
/// assert_eq!(obj[0].id, 0);
///
/// field.lazy_update();
/// let obj = field.get_objects(&Real2D {x: 5.0, y: 5.0});
/// assert_eq!(obj.len(), 1);
/// assert_eq!(obj[0].id, 0);
///
/// ```
pub fn set_object_location(&self, object: O, loc: Real2D) {
let bag = self.discretize(&loc);
let index = ((bag.x * self.dh) + bag.y) as usize;
let mut bags = self.bags[self.write].borrow_mut();
bags[index].push(object);
if !self.density_estimation_check{
*self.nagents.borrow_mut() += 1;
}
}
/// Remove an object from a specific position.
/// You have to use it to remove an object 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 object was written/set in this step.
///
/// # Arguments
/// * `object` - Object to remove
/// * `loc` - `Real2D` coordinates of the object
///
/// # Example
/// ```
/// struct Object {
/// id: u32
/// }
///
/// let DISCRETIZATION = 0.5;
/// let TOROIDAL = true;
/// let mut field = Field2D::new(10.0, 10.0, DISCRETIZATION, TOROIDAL);
///
/// field.set_object_location(&Object{id: 0}, Real2D {x: 5.0, y: 5.0} );
/// field.set_object_location(&Object{id: 1}, Real2D {x: 1.5, y: 1.5} );
/// field.set_object_location(&Object{id: 2}, Real2D {x: 5.0, y: 5.0} );
///
/// field.remove_object_location(&Object{id: 0}, Real2D {x: 5.0, y: 5.0} );
/// field.remove_object_location(&Object{id: 1}, Real2D {x: 1.5, y: 1.5} );
///
/// field.lazy_update();
///
/// let obj = field.get_objects(&Real2D {x: 5.0, y: 5.0});
/// assert_eq!(obj.len(), 1);
/// assert_eq!(obj[0].id, 2);
///
/// let no_obj = field.get_objects(&Real2D {x: 1.5, y: 1.5});
/// assert_eq!(no_obj.len(), 0);
///
/// ```
///
pub fn remove_object_location(&self, object: O, loc: Real2D) {
let bag = self.discretize(&loc);
let index = ((bag.x * self.dh) + bag.y) as usize;
let mut bags = self.bags[self.write].borrow_mut();
if !bags[index].is_empty() {
let before = bags[index].len();
bags[index].retain(|&x| x != object);
let after = bags[index].len();
if !self.density_estimation_check{
*self.nagents.borrow_mut() -= before - after;
}
}
}
}
impl<O: Location2D<Real2D> + Clone + Hash + Eq + Copy + Display> Field for Field2D<O>{
fn update(&mut self){}
/// Swap read and write buffer
fn lazy_update(&mut self){
std::mem::swap(&mut self.read, &mut self.write);
if !self.density_estimation_check{
self.density_estimation =
(*self.nagents.borrow_mut())/((self.dw * self.dh) as usize);
self.density_estimation_check = true;
self.bags[self.write] = RefCell::new(std::iter::repeat_with(|| Vec::with_capacity(self.density_estimation)).take((self.dw * self.dh) as usize).collect());
}
else {
let mut bags =self.bags[self.write].borrow_mut();
for b in 0..bags.len(){
bags[b].clear();
}
}
}
}
}
}
fn t_transform(n: i32, size: i32) -> i32 {
if n >= 0 {
n % size
} else {
(n % size) + size
}
}
fn check_circle(
bag: &Int2D,
discretization: f32,
width: f32,
height: f32,
loc: &Real2D,
dis: f32,
tor: bool,
) -> i8 {
let nw = Real2D {
x: (bag.x as f32) * discretization,
y: (bag.y as f32) * discretization,
};
let ne = Real2D {
x: nw.x,
y: (nw.y + discretization).min(height),
};
let sw = Real2D {
x: (nw.x + discretization).min(width),
y: nw.y,
};
let se = Real2D { x: sw.x, y: ne.y };
if distance(&nw, loc, width, height, tor) <= dis
&& distance(&ne, loc, width, height, tor) <= dis
&& distance(&sw, loc, width, height, tor) <= dis
&& distance(&se, loc, width, height, tor) <= dis
{
1
} else if distance(&nw, loc, width, height, tor) > dis
&& distance(&ne, loc, width, height, tor) > dis
&& distance(&sw, loc, width, height, tor) > dis
&& distance(&se, loc, width, height, tor) > dis
{
-1
} else {
0
}
}
fn distance(loc1: &Real2D, loc2: &Real2D, dim1: f32, dim2: f32, tor: bool) -> f32 {
let dx;
let dy;
if tor {
dx = toroidal_distance(loc1.x, loc2.x, dim1);
dy = toroidal_distance(loc1.y, loc2.y, dim2);
} else {
dx = loc1.x - loc2.x;
dy = loc1.y - loc2.y;
}
(dx * dx + dy * dy).sqrt()
}
pub fn toroidal_distance(val1: f32, val2: f32, dim: f32) -> f32 {
if (val1 - val2).abs() <= dim / 2.0 {
return val1 - val2;
}
let d = toroidal_transform(val1, dim) - toroidal_transform(val2, dim);
if d * 2.0 > dim {
d - dim
} else if d * 2.0 < -dim {
d + dim
} else {
d
}
}
pub fn toroidal_transform(val: f32, dim: f32) -> f32 {
if val >= 0.0 && val < dim {
val
} else {
let mut val = val % dim;
if val < 0.0 {
val += dim;
}
val
}
}