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
mod aperiodic;
mod periodic;
mod base {
use lattice::Lattice;
use indexmap::IndexMap;
use octree::Octree;
use vecfx::Vector3f;
pub type Point = [f64; 3];
#[derive(Debug, Clone, Copy)]
pub struct Neighbor {
pub node: usize,
pub distance: f64,
pub image: Option<Vector3f>,
}
#[derive(Debug, Clone, Default)]
pub struct Neighborhood {
pub(crate) points: IndexMap<usize, Point>,
pub(crate) tree: Option<Octree>,
pub(crate) lattice: Option<Lattice>,
}
}
mod api {
use crate::base::*;
use lattice::Lattice;
use octree::Octree;
impl Neighborhood {
pub fn new() -> Self {
Self { ..Default::default() }
}
pub fn update<I>(&mut self, iter: I)
where
I: IntoIterator<Item = (usize, Point)>,
{
for (k, v) in iter {
self.points.insert(k, v);
}
let points: Vec<_> = self.points.values().copied().collect();
let mut tree = Octree::new(points);
let bucket_size = 100;
tree.build(bucket_size);
self.tree = Some(tree);
}
#[cfg(feature = "adhoc")]
pub fn clear(&mut self) {
self.points.clear();
self.lattice = None;
self.tree = None;
}
pub fn neighbors(&self, n: usize, radius: f64) -> impl Iterator<Item = Neighbor> + '_ {
let (_, _, &pt) = self.points.get_full(&n).expect("invalid key");
let epsilon = 1e-6;
self.search(pt, radius).filter_map(move |m| {
if m.node == n && m.distance < epsilon {
return None;
}
Some(m)
})
}
pub fn search(&self, pt: Point, radius: f64) -> impl Iterator<Item = Neighbor> + '_ {
let mut iter_periodic = None;
let mut iter_aperiodic = None;
match self.lattice {
Some(lattice) => {
let iter = self.search_neighbors_periodic(pt, radius, lattice);
iter_periodic = Some(iter);
}
None => {
let iter = self.search_neighbors_aperiodic(pt, radius);
iter_aperiodic = Some(iter);
}
}
iter_periodic
.into_iter()
.flatten()
.chain(iter_aperiodic.into_iter().flatten())
}
pub fn npoints(&self) -> usize {
self.points.len()
}
pub fn set_lattice(&mut self, mat: [[f64; 3]; 3]) {
let lat = Lattice::new(mat);
self.lattice = Some(lat);
}
}
}
pub use crate::api::*;
pub use crate::base::*;