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
use crate::{traits::*, GraphErrors, GenericGraph};
use rand::seq::SliceRandom;
#[cfg(feature = "serde_support")]
use serde::{Serialize, Deserialize};
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct SpacialNodeContainer<T>
{
pub(crate) adj: Vec<usize>,
id: usize,
pub(crate) x: f64,
pub(crate) y: f64,
node: T,
}
impl<T: Node + SerdeStateConform> AdjContainer<T> for SpacialNodeContainer<T> {
fn new(id: usize, node: T) -> Self {
SpacialNodeContainer{
id,
adj: Vec::new(),
node,
x: f64::NAN,
y: f64::NAN,
}
}
fn contained(&self) -> &T {
&self.node
}
fn contained_mut(&mut self) -> &mut T {
&mut self.node
}
fn neighbors(&self) -> IterWrapper {
IterWrapper::new_generic(self.adj.iter())
}
fn degree(&self) -> usize {
self.adj.len()
}
fn id(&self) -> usize {
self.id
}
fn is_adjacent(&self, other_id: usize) -> bool {
self.adj.contains(&other_id)
}
fn sort_adj(&mut self) {
self.adj.sort_unstable();
}
fn shuffle_adj<R: rand::Rng>(&mut self, rng: &mut R) {
self.adj.shuffle(rng)
}
#[doc(hidden)]
unsafe fn clear_edges(&mut self) {
self.adj.clear();
}
#[doc(hidden)]
unsafe fn push(&mut self, other: &mut Self)
-> Result<(), GraphErrors>
{
if self.is_adjacent(other.id()) {
return Err(GraphErrors::EdgeExists);
}
self.adj.push(other.id());
other.adj.push(self.id);
Ok(())
}
#[doc(hidden)]
unsafe fn remove(&mut self, other: &mut Self)
-> Result<(), GraphErrors>
{
if !self.is_adjacent(other.id()){
return Err(GraphErrors::EdgeDoesNotExist);
}
self.swap_remove_element(other.id());
other.swap_remove_element(self.id());
Ok(())
}
fn get_adj_first(&self) -> Option<&usize> {
self.adj.first()
}
}
impl<T> SpacialNodeContainer<T> {
fn swap_remove_element(&mut self, elem: usize) {
let index = self.adj
.iter()
.position(|&x| x == elem)
.expect("swap_remove_element ERROR 0");
self.adj
.swap_remove(index);
}
pub fn distance(&self, other: &Self) -> f64 {
let x = self.x - other.x;
let y = self.y - other.y;
y.hypot(x)
}
pub fn get_x(&self) -> f64
{
self.x
}
pub fn get_y(&self) -> f64
{
self.y
}
}
pub type SpacialGraph<T> = GenericGraph<T, SpacialNodeContainer<T>>;
impl<T> SpacialGraph<T>
{
pub fn distance(&self, i: usize, j: usize) -> Option<f64>
where SpacialNodeContainer<T>: AdjContainer<T>
{
let container_i = self.container_checked(i)?;
self.container_checked(j)
.map(
|container_j|
{
container_i.distance(container_j)
}
)
}
}