lattice-graph 0.7.0

Set of Lattice(Grid) based Graph Structures
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
//! Module for Abstract 2D Lattice Graph. It is used inside by other lattice graph in other modules like [`hex`](`crate::hex`).
//! Use it when you want to define your own lattice graph, or to use the concreate visit iterator structs for traits in [`visit`](`petgraph::visit`).

use crate::unreachable_debug_checked;
use fixedbitset::FixedBitSet;
use ndarray::Array2;
use petgraph::{
    data::{DataMap, DataMapMut},
    visit::{Data, GraphBase, GraphProp, IntoNodeIdentifiers, NodeCount, VisitMap, Visitable},
    EdgeType,
};
use std::{marker::PhantomData, mem::MaybeUninit, ptr::drop_in_place};

mod edges;
pub use edges::{EdgeReference, EdgeReferences, Edges, EdgesDirected};
mod neighbors;
pub use neighbors::*;
mod nodes;
pub use nodes::*;
pub mod shapes;
pub(crate) use shapes::*;
pub mod square;

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
/// Abstract Lattice Graph.
/// It holds the node and edge weight data.
/// The actural behaviour is dependent on [`Shape`](`shapes::Shape`).
pub struct LatticeGraph<N, E, S: Shape> {
    nodes: Array2<N>,
    edges: Vec<Array2<E>>,
    s: S,
}

impl<N, E, S: Shape> LatticeGraph<N, E, S> {
    /// Creates a graph from raw data. This api might change.
    #[doc(hidden)]
    pub unsafe fn new_raw(nodes: Array2<N>, edges: Vec<Array2<E>>, s: S) -> Self {
        Self { nodes, edges, s }
    }

    /// Creates a graph with uninitalized node and edge weight data.
    /// It is extremely unsafe so should use with [`MaybeUninit`](`core::mem::MaybeUninit`) and use [`assume_init`](`Self::assume_init`).
    pub unsafe fn new_uninit(s: S) -> LatticeGraph<MaybeUninit<N>, MaybeUninit<E>, S> {
        let nodes = Array2::uninit((s.horizontal(), s.vertical()));
        let ac = S::Axis::COUNT;
        let mut edges = Vec::with_capacity(ac);
        for _i in 0..ac {
            edges.push(Array2::uninit((s.horizontal(), s.vertical())))
        }
        debug_assert_eq!(edges.len(), S::Axis::COUNT);
        LatticeGraph { nodes, edges, s }
    }

    /// Creates a graph with node and edge weight data set to [`default`](`Default::default`).
    pub fn new(s: S) -> Self
    where
        N: Default,
        E: Default,
    {
        Self::new_with(s, |_| N::default(), |_, _| E::default())
    }

    /// Creates a graph with node and edge weight data from the coordinate.
    pub fn new_with<FN, FE>(s: S, mut n: FN, mut e: FE) -> Self
    where
        FN: FnMut(S::Coordinate) -> N,
        FE: FnMut(S::Coordinate, S::Axis) -> E, // change to E ?
    {
        let mut uninit = unsafe { Self::new_uninit(s) };
        let s = &uninit.s;
        let nodes = uninit.nodes.as_slice_mut().unwrap();
        let edges = &mut uninit.edges;
        for i in 0..s.node_count() {
            let offset = s.index_to_offset(i);
            let c = s.offset_to_coordinate(offset);
            unsafe { std::ptr::write(nodes.get_unchecked_mut(i), MaybeUninit::new(n(c))) }
            for (j, edge) in edges.iter_mut().enumerate() {
                let a = unsafe { <S::Axis as Axis>::from_index_unchecked(j) };
                if s.move_coord(c, a.foward()).is_err() {
                    continue;
                }
                let ex = e(c, a);
                let t = edge.get_mut((offset.horizontal, offset.vertical));
                if let Some(x) = t {
                    unsafe { std::ptr::write(x, MaybeUninit::new(ex)) };
                }
            }
        }
        unsafe { uninit.assume_init() }
    }

    /// Get a reference to the lattice graph's s.
    pub fn shape(&self) -> &S {
        &self.s
    }
}

impl<N, E, S: Shape + Default> LatticeGraph<N, E, S> {
    /// Creates a graph with node and edge weight data set to [`default`](`Default::default`) with [`Shape`] from default.
    pub fn new_s() -> Self
    where
        N: Default,
        E: Default,
    {
        Self::new(S::default())
    }

    /// Creates a graph with uninitalized node and edge weight data with [`Shape`] from default.
    /// It is extremely unsafe so should use with [`MaybeUninit`](`core::mem::MaybeUninit`) and use [`assume_init`](`Self::assume_init`).
    pub unsafe fn new_uninit_s() -> LatticeGraph<MaybeUninit<N>, MaybeUninit<E>, S> {
        Self::new_uninit(S::default())
    }

    /// Creates a graph with node and edge weight data from the coordinate with [`Shape`] from default.
    pub fn new_with_s<FN, FE>(n: FN, e: FE) -> Self
    where
        FN: FnMut(S::Coordinate) -> N,
        FE: FnMut(S::Coordinate, S::Axis) -> E,
    {
        Self::new_with(S::default(), n, e)
    }
}

impl<N, E, S: Shape> LatticeGraph<MaybeUninit<N>, MaybeUninit<E>, S> {
    /**
    Assume the underlying nodes and edges to be initialized.
    ```
    # use lattice_graph::hex::axial_based::*;
    # use core::mem::MaybeUninit;
    # use petgraph::data::*;
    let mut hex = unsafe { HexGraphConst::<f32, (), OddR, 5, 5>::new_uninit_s() };
    for i in 0..5{
        for j in 0..5{
            let offset = Offset::new(i, j);
            let coord = hex.shape().offset_to_coordinate(offset);
            if let Some(ref mut n) = hex.node_weight_mut(coord){
                **n = MaybeUninit::new((i + j) as f32);
            }
        }
    }
    let hex_init = unsafe{ hex.assume_init() };
    ```
    */
    pub unsafe fn assume_init(self) -> LatticeGraph<N, E, S> {
        let md = std::mem::ManuallyDrop::new(self);
        LatticeGraph {
            nodes: core::ptr::read(&md.nodes).assume_init(),
            edges: core::ptr::read(&md.edges)
                .into_iter()
                .map(|e| e.assume_init())
                .collect(),
            s: core::ptr::read(&md.s),
        }
    }
}

impl<N, E, S: Shape> Drop for LatticeGraph<N, E, S> {
    fn drop(&mut self) {
        // if e is drop type, drop manually to prevent dropping for invalid (uninitialized) edges.
        if std::mem::needs_drop::<E>() {
            let ni = self.node_identifiers();
            let s = &self.s;
            let e = &mut self.edges;
            unsafe {
                for (di, edges) in e.drain(..).enumerate() {
                    let dir = S::Axis::from_index_unchecked(di).foward();
                    for (coord, mut e) in ni.clone().zip(edges.into_iter()) {
                        if s.move_coord(coord, dir.clone()).is_ok() {
                            drop_in_place(&mut e);
                        }
                    }
                }
            }
        }
    }
}

impl<N, E, S> Default for LatticeGraph<N, E, S>
where
    N: Default,
    E: Default,
    S: Shape + Default + Clone,
{
    fn default() -> Self {
        Self::new(S::default())
    }
}

impl<N, E, S: Shape> GraphBase for LatticeGraph<N, E, S> {
    type NodeId = S::Coordinate;
    type EdgeId = (S::Coordinate, S::Axis);
}

impl<N, E, S: Shape> Data for LatticeGraph<N, E, S> {
    type NodeWeight = N;
    type EdgeWeight = E;
}

impl<N, E, S: Shape> DataMap for LatticeGraph<N, E, S> {
    fn node_weight(&self, id: Self::NodeId) -> Option<&Self::NodeWeight> {
        let offset = self.s.to_offset(id);
        // SAFETY : offset must be checked in `to_offset`
        offset
            .map(move |offset| unsafe {
                if cfg!(debug_assertions) {
                    self.nodes
                        .get((offset.horizontal, offset.vertical))
                        .unwrap()
                } else {
                    self.nodes
                        .get((offset.horizontal, offset.vertical))
                        .unwrap_unchecked()
                }
            })
            .ok()
    }

    fn edge_weight(&self, id: Self::EdgeId) -> Option<&Self::EdgeWeight> {
        let offset = self.s.to_offset(id.0);
        let ax = id.1.to_index();
        if let Ok(offset) = offset {
            if self.s.move_coord(id.0, id.1.foward()).is_err() {
                return None;
            }
            unsafe {
                self.edges
                    .get_unchecked(ax)
                    .get((offset.horizontal, offset.vertical))
            }
        } else {
            None
        }
    }
}

impl<N, E, S: Shape> DataMapMut for LatticeGraph<N, E, S> {
    fn node_weight_mut(&mut self, id: Self::NodeId) -> Option<&mut Self::NodeWeight> {
        let offset = self.s.to_offset(id);

        // SAFETY : offset must be checked in `to_offset`
        offset
            .map(move |offset| unsafe {
                if cfg!(debug_assertions) {
                    self.nodes
                        .get_mut((offset.horizontal, offset.vertical))
                        .unwrap()
                } else {
                    self.nodes
                        .get_mut((offset.horizontal, offset.vertical))
                        .unwrap_unchecked()
                }
            })
            .ok()
    }

    fn edge_weight_mut(&mut self, id: Self::EdgeId) -> Option<&mut Self::EdgeWeight> {
        let offset = self.s.to_offset(id.0);
        let ax = id.1.to_index();
        if let Ok(offset) = offset {
            if self.s.move_coord(id.0, id.1.foward()).is_err() {
                return None;
            }
            unsafe {
                self.edges
                    .get_unchecked_mut(ax)
                    .get_mut((offset.horizontal, offset.vertical))
            }
        } else {
            None
        }
    }
}

impl<N, E, S: Shape> LatticeGraph<N, E, S> {
    #[doc(hidden)]
    #[inline]
    pub unsafe fn node_weight_unchecked(
        &self,
        id: <LatticeGraph<N, E, S> as GraphBase>::NodeId,
    ) -> &<LatticeGraph<N, E, S> as Data>::NodeWeight {
        let offset = self.s.to_offset_unchecked(id);
        // SAFETY : offset must be checked in `to_offset`
        self.node_weight_unchecked_raw(offset)
    }

    #[doc(hidden)]
    pub unsafe fn node_weight_unchecked_raw(
        &self,
        offset: Offset,
    ) -> &<LatticeGraph<N, E, S> as Data>::NodeWeight {
        self.nodes
            .get((offset.horizontal, offset.vertical))
            .unwrap_unchecked()
    }

    #[doc(hidden)]
    #[inline]
    pub unsafe fn edge_weight_unchecked(
        &self,
        id: <LatticeGraph<N, E, S> as GraphBase>::EdgeId,
    ) -> &<LatticeGraph<N, E, S> as Data>::EdgeWeight {
        let offset = self.s.to_offset_unchecked(id.0);
        let ax = id.1.to_index();
        self.edge_weight_unchecked_raw((offset, ax))
    }

    #[doc(hidden)]
    pub unsafe fn edge_weight_unchecked_raw(
        &self,
        (offset, ax): (Offset, usize),
    ) -> &<LatticeGraph<N, E, S> as Data>::EdgeWeight {
        self.edges
            .get_unchecked(ax)
            .get((offset.horizontal, offset.vertical))
            .unwrap_unchecked()
    }

    #[doc(hidden)]
    pub unsafe fn node_weight_mut_unchecked(
        &mut self,
        id: <LatticeGraph<N, E, S> as GraphBase>::NodeId,
    ) -> &mut <LatticeGraph<N, E, S> as Data>::NodeWeight {
        let offset = self.s.to_offset_unchecked(id);
        // SAFETY : offset must be checked in `to_offset`
        self.nodes
            .get_mut((offset.horizontal, offset.vertical))
            .unwrap_unchecked()
    }

    #[doc(hidden)]
    pub unsafe fn edge_weight_mut_unchecked(
        &mut self,
        id: <LatticeGraph<N, E, S> as GraphBase>::EdgeId,
    ) -> &mut <LatticeGraph<N, E, S> as Data>::EdgeWeight {
        let offset = self.s.to_offset_unchecked(id.0);
        let ax = id.1.to_index();
        self.edges
            .get_unchecked_mut(ax)
            .get_mut((offset.horizontal, offset.vertical))
            .unwrap_unchecked()
    }
}

///Wrapper for [`Axis`] to be [`EdgeType`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct EdgeTypeWrap<A>(PhantomData<A>);
impl<A: Axis> EdgeType for EdgeTypeWrap<A> {
    fn is_directed() -> bool {
        A::DIRECTED
    }
}

impl<N, E, S: Shape> GraphProp for LatticeGraph<N, E, S> {
    type EdgeType = EdgeTypeWrap<S::Axis>;
}

/// [`VisitMap`] of [`LatticeGraph`].
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct VisMap<S> {
    v: Vec<FixedBitSet>,
    s: S,
}

impl<S: Shape> VisMap<S> {
    pub(crate) fn new(s: S) -> Self {
        let h = s.horizontal();
        let v = s.vertical();
        let mut vec = Vec::with_capacity(h);
        for _ in 0..h {
            vec.push(FixedBitSet::with_capacity(v));
        }
        Self { v: vec, s }
    }
}

impl<S: Shape> VisitMap<S::Coordinate> for VisMap<S> {
    fn visit(&mut self, a: S::Coordinate) -> bool {
        let offset = self.s.to_offset(a);
        if let Ok(a) = offset {
            !self.v[a.horizontal].put(a.vertical)
        } else {
            false
        }
    }

    fn is_visited(&self, a: &S::Coordinate) -> bool {
        let offset = self.s.to_offset(*a);
        if let Ok(a) = offset {
            self.v[a.horizontal].contains(a.vertical)
        } else {
            false
        }
    }

    fn unvisit(&mut self, a: S::Coordinate) -> bool {
        let offset = self.s.to_offset(a);
        if let Ok(offset) = offset {
            self.v[offset.horizontal].set(offset.vertical, false);
            true
        } else {
            false
        }
    }
}

impl<N, E, S: Shape + Clone> Visitable for LatticeGraph<N, E, S> {
    type Map = VisMap<S>;

    fn visit_map(&self) -> Self::Map {
        VisMap::new(self.s.clone())
    }

    fn reset_map(&self, map: &mut Self::Map) {
        map.v.iter_mut().for_each(|x| x.clear())
    }
}