sgrust 0.8.6

A sparse grid library written in Rust.
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
use std::{hash::{Hash, Hasher}, ops::{Index, IndexMut}};
use rustc_hash::FxHasher;
use serde::{Deserialize, Serialize};
use serde_with::serde_as;
use bitfield_struct::bitfield;
use wide::{CmpGt, CmpLt};
use crate::const_generic::iterators::grid_iterator::{GridIteratorT, HashMapGridIterator};
use nohash_hasher::BuildNoHashHasher;
use crate::adjacency_data::{NodeAdjacency, NodeAdjacencyData};
pub type FastU64Map<V> = std::collections::HashMap<u64, V, BuildNoHashHasher<u64>>;
#[bitfield(u8, new=false)]
#[derive(Serialize, Deserialize, PartialEq, Eq)]
pub struct GridPointFlags
{
    pub is_leaf: bool,
    pub is_inner: bool,
    #[bits(6)]
    pub _empty: u8
}

// rkyv implementations for GridPointFlags (bitfield type)
#[cfg(feature = "rkyv")]
impl rkyv::Archive for GridPointFlags {
    type Archived = u8;
    type Resolver = ();

    fn resolve(&self, _resolver: Self::Resolver, out: rkyv::Place<Self::Archived>) {
        out.write(self.0);
    }
}
#[cfg(feature = "rkyv")]
impl<S: rkyv::rancor::Fallible + ?Sized> rkyv::Serialize<S> for GridPointFlags {
    fn serialize(&self, _serializer: &mut S) -> Result<Self::Resolver, S::Error> {
        Ok(())
    }
}
#[cfg(feature = "rkyv")]
impl<D: rkyv::rancor::Fallible + ?Sized> rkyv::Deserialize<GridPointFlags, D> for u8 {
    fn deserialize(&self, _deserializer: &mut D) -> Result<GridPointFlags, D::Error> {
        Ok(GridPointFlags(*self))
    }
}
impl GridPointFlags
{
    pub fn new<const D: usize>(level: &[u8; D], is_leaf: bool) -> Self
    {
        let mut r = Self::default();        
        r.set_is_leaf(is_leaf);
        r.set_is_inner(!level.contains(&0));
        r
    }
    /// update `is_inner` flag...
    pub fn update_is_inner<const D: usize>(&mut self, level: &[u8; D]) 
    {
        self.set_is_inner(!level.contains(&0));
    }
}
#[serde_as]
#[derive(Copy, Clone, Serialize, Deserialize, Debug)]
#[cfg_attr(feature = "rkyv", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
pub struct GridPoint<const D: usize>
{
    #[serde_as(as = "[_; D]")]
    pub level: [u8; D],
    #[serde_as(as = "[_; D]")]
    pub index: [u32; D],
    pub(crate) flags: GridPointFlags,
}
impl<const D: usize> Hash for GridPoint<D>
{
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.level.hash(state);
        self.index.hash(state);
    }
}
impl<const D: usize> Default for GridPoint<D> 
{
    fn default() -> Self {
        Self { level: [1; D], index: [1; D], flags: GridPointFlags(0) }
    }
}
impl<const D: usize> PartialOrd for GridPoint<D>
{    
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(std::cmp::Ord::cmp(self, other))
    }
}
impl<const D:usize> Ord for GridPoint<D>{
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.index.cmp(&other.index).then(self.level.cmp(&other.level))
    }
}

impl<const D: usize> PartialEq for GridPoint<D>
{
    fn eq(&self, other: &Self) -> bool {
        self.level == other.level && self.index == other.index
    }
}
impl<const D: usize> Eq for GridPoint<D>{}

impl<const D: usize> GridPoint<D>
{
    pub fn new (level: [u8; D], index: [u32; D], is_leaf: bool) -> Self
    {
        let flags= GridPointFlags::new(&level, is_leaf);
        Self { level, index, flags }
    }   
    pub fn is_leaf(&self) -> bool
    {
        self.flags.is_leaf()
    }
    pub fn set_is_leaf(&mut self, is_leaf: bool)
    {
        self.flags.set_is_leaf(is_leaf);
    }

    pub fn set_is_inner(&mut self, is_inner: bool)
    {        
        self.flags.set_is_inner(is_inner);
    }
    /// 
    /// This is an inner point if no indices are zero...
    /// 
    pub fn is_inner_point(&self) -> bool
    {        
        self.flags.is_inner()
    }   
    pub fn level_sum(&self) -> u8
    {
        self.level.iter().sum()
    }
    #[inline]
    pub fn level_max(&self) -> u8
    {
        self.level.iter().copied().max().unwrap_or(0)
    }
    pub fn level_min(&self) -> u8
    {
        self.level.iter().copied().min().unwrap_or(0)
    }
    
    pub fn left_child(&self, dim: usize) -> GridPoint<D>
    {
        let mut r = *self;
        if r.index[dim] == 0
        {
            r.index[dim] = u32::MAX;
            return r;
        }
        r.index[dim] = 2*self.index[dim] - 1;
        r.level[dim] += 1;
        r
    }
    pub fn right_child(&self, dim: usize) -> GridPoint<D>
    {
        let mut r = *self;
        r.index[dim] = 2*self.index[dim] + 1;
        r.level[dim] += 1;
        r
    }
    ///
    /// returns an index with the top level in direction dim
    /// 
    pub fn root(&self, dim: usize) -> GridPoint<D>
    {
        let mut r = *self;
        r.index[dim] = 1;
        r.level[dim] = 1;
        r
    }

    ///
    /// This only works for grids without boundaries.    
    /// 
    pub fn parent(&self, dim: usize) -> GridPoint<D>
    {
        let mut r = *self;
        if self.level[dim] == 0
        {
            r.index[dim] = u32::MAX;
            return r;
        }
        r.index[dim] = (self.index[dim] >> 1) | 1;
        r.level[dim] -= 1;
        r
    }

    pub fn unit_coordinate(&self) -> [f64; D]
    {
        let mut coor = [0.0; D];
        #[allow(clippy::needless_range_loop)]
        for d in 0..D
        {
            coor[d] = self.index[d] as f64 / (1 << self.level[d]) as f64;
        }
        coor
    }

    pub const fn zero_index() -> Self
    {
        Self{ level: [0; D], index: [0; D], flags: GridPointFlags(0) }
    }

}

impl<const D: usize> From<GridPoint<D>> for u64
{
    fn from(val: GridPoint<D>) -> Self {
        let hasher = &mut FxHasher::default();
        val.hash(hasher);
        hasher.finish()
    }
}


#[serde_as]
#[derive(Copy, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "rkyv", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
pub struct BoundingBox<const D: usize>
{
    #[serde_as(as = "[_; D]")]
    pub lower: [f64; D],
    #[serde_as(as = "[_; D]")]
    pub upper: [f64; D],
}

impl<const D: usize> Default for BoundingBox<D>
{
    #[inline]
    fn default() -> Self {
        Self { lower: [0.0; D], upper: [1.0; D] }
    }
}
impl<const D: usize> BoundingBox<D>
{
    #[inline]
    pub fn new(lower: [f64; D], upper: [f64; D]) -> Self
    {
        Self { lower, upper }
    }
    #[inline]
    pub fn width(&self, dim: usize) -> f64
    {
        self.upper[dim] - self.lower[dim]
    }

    ///
    /// Volume of hypercube (width(dim1)*...*width(dim_n))
    /// 
    #[inline]
    pub fn volume(&self) -> f64
    {
        let mut volume = 1.0;
        for d in 0..D
        {
            volume *= self.width(d);
        }
        volume
    }
    #[inline]
    pub fn to_unit_coordinate(&self, point: &[f64; D]) -> [f64; D]
    {
        use wide::f64x4;
        let mut r = [0.0; D];
        let mut i = 0;
        while i + 4 <= D {
            let p = f64x4::from(&point[i..i+4]);            
            let lo = f64x4::from(&self.lower[i..i+4]);
            let hi = f64x4::from(&self.upper[i..i+4]);
            let res = (p - lo) / (hi - lo);
            r[i..i+4].copy_from_slice(res.as_array());
            i += 4;
        }
        while i < D {
            r[i] = (point[i] - self.lower[i]) / (self.upper[i] - self.lower[i]);
            i += 1;
        }        
        r
    }
    #[inline]
    pub fn to_real_coordinate(&self, point: &[f64; D]) -> [f64; D]
    {
        let mut r = [0.0;D];
        for i in 0..D
        {
            r[i] = self.lower[i] + (self.upper[i] - self.lower[i]) * point[i];
        }
        r
    }
    #[inline]
    pub fn contains(&self, point: &[f64; D]) -> bool
    {
        use wide::f64x4;
        let mut i = 0;
        while i + 4 <= D {
            let p  = f64x4::from(&point[i..i+4]);
            let lo = f64x4::from(&self.lower[i..i+4]);
            let hi = f64x4::from(&self.upper[i..i+4]);
            // any lane set means out-of-bounds in that dimension
            if (lo.simd_gt(p) | hi.simd_lt(p)).to_bitmask() != 0 {
                return false;
            }
            i += 4;
        }
        while i < D {
            if self.lower[i] > point[i] || self.upper[i] < point[i] {
                return false;
            }
            i += 1;
        }
        true
    }
}



impl<const D: usize> SparseGridData<D>
{
    #[inline(always)]
    pub fn len(&self) -> usize
    {
        self.nodes.len()
    }
    #[inline(always)]
    pub fn is_empty(&self) -> bool
    {
        self.nodes.is_empty()
    }
    #[inline(always)]
    pub fn has_boundary(&self) -> bool
    {
        self.has_boundary
    }

    #[inline]
    pub fn contains(&self, point: &GridPoint<D>) -> bool
    {
        let hasher = &mut FxHasher::default();
        point.hash(hasher);
        self.map.contains_key(&hasher.finish())
    }
    #[inline]
    pub fn get_mut(&mut self, point: &GridPoint<D>) -> Option<&mut GridPoint<D>>
    {
        let hasher = &mut FxHasher::default();
        point.hash(hasher);
        match self.map.get(&hasher.finish())
        {
            Some(&seq) => Some(&mut self.nodes[seq as usize]),
            None => None
        }
    }

    #[inline]
    pub fn get(&mut self, point: &GridPoint<D>) -> Option<&GridPoint<D>>
    {
        let hasher = &mut FxHasher::default();
        point.hash(hasher);
        match self.map.get(&hasher.finish())
        {
            Some(&seq) => Some(&self.nodes[seq as usize]),
            None => None
        }
    }

    #[inline(always)]
    pub fn nodes(&self) -> &Vec<GridPoint<D>>
    {
        &self.nodes
    }
    
    pub fn nodes_mut(&mut self) -> &mut Vec<GridPoint<D>>
    {
        &mut self.nodes
    }
    
    #[inline]
    pub fn bounding_box(&self) -> &BoundingBox<D>
    {
        &self.bounding_box
    }
    #[inline]
    pub fn bounding_box_mut(&mut self) -> &mut BoundingBox<D>
    {
        &mut self.bounding_box
    }
    #[inline]
    pub fn index_of(&self, point: &GridPoint<D>) -> Option<usize>
    {
        let hasher = &mut FxHasher::default();
        point.hash(hasher);
        self.map.get(&hasher.finish()).map(|v|*v as usize)
    }

    pub fn remove(&mut self, points_to_keep: &[usize])
    {
        let mut new_list = Vec::with_capacity(points_to_keep.len());
        for &i in points_to_keep
        {            
            new_list.push(self.nodes[i]);
        }
        self.nodes = new_list;
        // TODO: This doesn't work for some reason...
        //self.map.retain(|_, v| points_to_keep.contains(v));     
        self.generate_map();
        self.update_leaves();
        self.generate_adjacency_data();
    }

    fn update_leaves(&mut self)
    {
    
        #[allow(clippy::needless_range_loop)]
        for i in 0..self.len()
        {
            let point = &mut self.nodes[i];
            let mut is_leaf = true;
            
            for dim in 0..D
            {                
                if point.level[dim] > 0
                {   
                    // Check if this point has any children. If not it is a leaf.
                    if self.map.contains_key(&point.left_child(dim).into()) ||
                        self.map.contains_key(&point.right_child(dim).into()) 
                    {
                        is_leaf = false;
                        break; 
                    }                
                }
                else
                {
                    // Boundary node in this dimension - check for level-1 child
                    let mut child = *point;
                    child.level[dim] = 1;
                    child.index[dim] = 1;
                    if self.map.contains_key(&child.into())
                    {
                        is_leaf = false;
                        break;
                    }
                }
            }                
            point.flags.set_is_leaf(is_leaf);            
        }       
        // for i in 0..self.len()
        // {
        //     let point = self.nodes[i];
        //     if point.is_leaf() && point.is_inner_point()
        //     {
        //         continue;
        //     }
        //     for dim in 0..D
        //     {                
        //         let llz = point.left_level_zero(dim);
        //         let rlz = point.right_level_zero(dim);
        //         if let Some(&index) = self.map.get(&llz.into())
        //         {
        //             self.nodes[index].set_is_leaf(false);
        //         }
        //         if let Some(&index) = self.map.get(&rlz.into())
        //         {
        //             self.nodes[index].set_is_leaf(false);
        //         }      
        //     }          
        // }
    }

    ///
    /// Inserts a point
    /// 
    #[inline]
    pub fn insert_point(&mut self, mut point: GridPoint<D>) -> usize
    {
        // make sure our is_inner flag is up-to-date...
        point.flags.update_is_inner(&point.level);
        self.nodes.push(point);        
        self.map.insert(point.into(), self.len() as u32 - 1);
        self.len() - 1
    }

    #[inline]
    pub fn update(&mut self, mut point: GridPoint<D>, index: usize)
    {
        // make sure our is_inner flag is up-to-date...
        point.flags.update_is_inner(&point.level);
        let key: u64 = point.into();
        self.map.insert(key, index as u32);
        self.nodes[index] = point;
    }
    ///
    /// Return the real coordinates for each node...
    /// 
    pub fn points(&self) -> PointIterator<'_, D> {
        PointIterator::new(&self.nodes, self.bounding_box)
    }
}
#[cfg(feature = "rkyv")]
use rkyv::{with::Skip};
#[derive(Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "rkyv", derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize))]
pub struct SparseGridData<const D: usize>
{
    pub(crate) bounding_box: BoundingBox<D>,
    pub(crate) nodes: Vec<GridPoint<D>>,
    #[serde(skip_serializing, skip_deserializing)]
    #[cfg_attr(feature = "rkyv", rkyv(with = Skip))]
    pub(crate) adjacency_data: NodeAdjacencyData,    
    pub(crate) has_boundary: bool,    
    pub(crate) map: FastU64Map<u32>
}

impl<const D: usize> Index<usize> for SparseGridData<D>
{
    type Output = GridPoint<D>;

    fn index(&self, index: usize) -> &Self::Output {
        &self.nodes[index]
    }
}
impl<const D: usize> IndexMut<usize> for SparseGridData<D>
{
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        &mut self.nodes[index]
    }
}

impl<const D: usize> Default for SparseGridData<D>
{
    fn default() -> Self {
        Self { nodes: Default::default(), bounding_box: Default::default(), adjacency_data: NodeAdjacencyData::default(), has_boundary: false, map: FastU64Map::default() }
    }
}

impl<const D: usize> SparseGridData<D>
{
    pub fn generate_map(&mut self)
    {
        
        let mut map = FastU64Map::default();
        for (i, node) in self.nodes.iter().enumerate()
        {
            let mut hasher = FxHasher::default();
            node.hash(&mut hasher);            
            map.insert(hasher.finish(), i as u32);
        }
        self.map = map;
    }

    pub fn generate_adjacency_data(&mut self)
    {
        let total_size = D * self.len();
        let mut array = vec![NodeAdjacency::default(); total_size];
        let mut left_zero = vec![0_u32; total_size];
        let mut right_zero = vec![0_u32; total_size];
        if self.map.len() != self.len()
        {
            self.generate_map();
        }
        for dim in 0..D
        {
            for i in 0..self.len()
            {
                self.generate_adjacency_data_for_index(&mut array, &mut left_zero, &mut right_zero, i, dim);     
            }
        }
        self.adjacency_data.zero_index = self.index_of(&GridPoint::zero_index()).unwrap_or(usize::MAX);
        self.adjacency_data.data = array;
        self.adjacency_data.left_zero = left_zero;
        self.adjacency_data.right_zero = right_zero;
    }

    fn generate_adjacency_data_for_index(&mut self, array:&mut [NodeAdjacency], left_zero: &mut [u32], right_zero: &mut [u32], seq: usize, dim: usize)
    {

        let mut iterator = HashMapGridIterator::new(self);
        let offset =  dim * self.len();
        let active_index = offset + seq;
        let node_index= iterator.storage[seq]; 
        
        // Only process adjacency links if not already complete
        if !array[active_index].is_complete()
        {            
            iterator.set_index(node_index);
            iterator.up(dim);       
            if let Some(parent_index) = iterator.index()  // parent exists
            {
                // assign parent
                array[active_index].set_up(parent_index as i64 - seq as i64);      
                array[active_index].set_has_parent(true);
            }
            iterator.set_index(node_index);
            // get left child
            iterator.left_child(dim);
            if let Some(lc_index) = iterator.index()
            {
                // assign left child - down_left offset
                array[active_index].set_down_left(lc_index as i64 - seq as i64);
            }
            
            iterator.set_index(node_index);
            // get right child
            iterator.right_child(dim);
            if let Some(rc_index) = iterator.index()
            {
                // assign right child - down_right offset
                array[active_index].set_down_right(rc_index as i64 - seq as i64);
            }
        }
        array[active_index].set_is_leaf(!array[active_index].has_left_child() && !array[active_index].has_right_child());

        // Always populate boundary and level indices (even for complete nodes)
        iterator.set_index(node_index);
        iterator.reset_to_left_level_zero(dim);
        if let Some(lzero) = iterator.index() {
            left_zero[active_index] = lzero as u32;
        }
        else
        {
            left_zero[active_index] = u32::MAX;
        }
        iterator.reset_to_right_level_zero(dim);
        if let Some(rzero) = iterator.index() {
            right_zero[active_index] = rzero as u32;
        }
        else
        {
            right_zero[active_index] = u32::MAX;
        }
        iterator.set_index(node_index);
        iterator.reset_to_level_one(dim);
        if let Some(level_one_idx) = iterator.index() {
            array[active_index].set_level_one(level_one_idx as u32);
        }
        else
        {
            array[active_index].set_level_one(u32::MAX); 
        }
    }
}

pub struct PointIterator<'a, const D: usize>
{
    pub data: &'a Vec<GridPoint<D>>,
    bounding_box: BoundingBox<D>,
    index: usize
}

impl<'a, const D: usize>  PointIterator<'a, D>
{
    pub fn new( data: &'a Vec<GridPoint<D>>, bounding_box: BoundingBox<D>) -> Self
    {
        Self { data, bounding_box, index: 0 }
    }
}

impl<const D: usize> Iterator for PointIterator<'_, D>
{
    type Item=[f64; D];

    fn next(&mut self) -> Option<Self::Item> {

        if self.index < self.data.len()
        {
            let mut point = self.data[self.index].unit_coordinate();
            point = self.bounding_box.to_real_coordinate(&point);
            self.index += 1;
            Some(point)
        }
        else
        {
            None
        }
    }
}