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
use std::ops::Add;
use geo::bounding_rect::BoundingRect;
use geo::concave_hull::ConcaveHull;
use geo_types::{Coordinate, MultiPoint, MultiPolygon, Point, Polygon, Rect};
use num_traits::Zero;
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use h3ron::collections::compressed::Decompressor;
use h3ron::collections::partitioned::TPMIter;
use h3ron::collections::{H3Treemap, ThreadPartitionedMap};
use h3ron::iter::H3EdgesBuilder;
use h3ron::{H3Cell, H3Edge, HasH3Resolution, ToCoordinate};
use crate::algorithm::covered_area::{cells_covered_area, CoveredArea};
use crate::error::Error;
use crate::graph::longedge::LongEdge;
use crate::graph::node::NodeType;
use crate::graph::{
EdgeWeight, GetCellNode, GetEdge, GetStats, GraphStats, H3EdgeGraph, IterateCellNodes,
};
#[derive(Serialize, Deserialize, Clone)]
struct OwnedEdgeValue<W: Send + Sync> {
pub weight: W,
pub longedge: Option<(LongEdge, W)>,
}
impl<'a, W: Send + Sync> From<&'a OwnedEdgeValue<W>> for EdgeWeight<'a, W>
where
W: Copy,
{
fn from(owned_edge_value: &'a OwnedEdgeValue<W>) -> Self {
EdgeWeight {
weight: owned_edge_value.weight,
longedge: owned_edge_value
.longedge
.as_ref()
.map(|(longedge, le_weight)| (longedge, *le_weight)),
}
}
}
const MIN_LONGEDGE_LENGTH: usize = 2;
#[derive(Serialize, Deserialize, Clone)]
pub struct PreparedH3EdgeGraph<W: Send + Sync> {
edges: ThreadPartitionedMap<H3Edge, OwnedEdgeValue<W>, 4>,
h3_resolution: u8,
graph_nodes: ThreadPartitionedMap<H3Cell, NodeType, 4>,
}
unsafe impl<W: Sync + Send> Sync for PreparedH3EdgeGraph<W> {}
impl<W: Sync + Send> PreparedH3EdgeGraph<W>
where
W: Copy,
{
pub fn num_long_edges(&self) -> usize {
self.edges
.iter()
.filter(|(_, oev)| oev.longedge.is_some())
.count()
}
pub fn iter_edges(&self) -> impl Iterator<Item = (H3Edge, EdgeWeight<W>)> {
self.edges
.iter()
.map(|(edge, weight)| (*edge, weight.into()))
}
pub fn iter_edges_non_overlapping(
&self,
) -> Result<impl Iterator<Item = (H3Edge, EdgeWeight<W>)>, Error> {
let mut covered_edges = H3Treemap::<H3Edge>::default();
let mut decompressor = Decompressor::default();
for (_, owned_edge_value) in self.edges.iter() {
if let Some((longedge, _)) = owned_edge_value.longedge.as_ref() {
for edge in decompressor.decompress_block(&longedge.edge_path)?.skip(1) {
covered_edges.insert(edge);
}
}
}
Ok(self.edges.iter().filter_map(move |(edge, weight)| {
if covered_edges.contains(edge) {
None
} else {
Some((*edge, weight.into()))
}
}))
}
}
impl<W> HasH3Resolution for PreparedH3EdgeGraph<W>
where
W: Send + Sync,
{
fn h3_resolution(&self) -> u8 {
self.h3_resolution
}
}
impl<W> GetStats for PreparedH3EdgeGraph<W>
where
W: Send + Sync,
{
fn get_stats(&self) -> GraphStats {
GraphStats {
h3_resolution: self.h3_resolution,
num_nodes: self.graph_nodes.len(),
num_edges: self.edges.len(),
}
}
}
impl<W: Send + Sync> GetCellNode for PreparedH3EdgeGraph<W> {
fn get_cell_node(&self, cell: &H3Cell) -> Option<&NodeType> {
self.graph_nodes.get(cell)
}
}
impl<W: Send + Sync + Copy> GetEdge for PreparedH3EdgeGraph<W> {
type EdgeWeightType = W;
fn get_edge(&self, edge: &H3Edge) -> Option<EdgeWeight<Self::EdgeWeightType>> {
self.edges.get(edge).map(|owv| owv.into())
}
}
fn to_longedge_edges<W>(
input_graph: H3EdgeGraph<W>,
min_longedge_length: usize,
) -> Result<ThreadPartitionedMap<H3Edge, OwnedEdgeValue<W>, 4>, Error>
where
W: PartialOrd + PartialEq + Add<Output = W> + Copy + Send + Sync,
{
if min_longedge_length < MIN_LONGEDGE_LENGTH {
return Err(Error::Other(format!(
"minimum longedge length must be >= {}",
MIN_LONGEDGE_LENGTH
)));
}
let mut edges: ThreadPartitionedMap<_, _, 4> = Default::default();
let mut parts: Vec<_> = input_graph
.edges
.partitions()
.par_iter()
.map::<_, Result<_, Error>>(|partition| {
let mut new_edges = Vec::with_capacity(partition.len());
let mut edge_builder = H3EdgesBuilder::new();
for (edge, weight) in partition.iter() {
let mut graph_entry = OwnedEdgeValue {
weight: *weight,
longedge: None,
};
let num_edges_leading_to_this_one = edge_builder
.from_origin_cell(&edge.origin_index_unchecked())
.filter(|new_edge| new_edge != edge)
.map(|new_edge| new_edge.reversed_unchecked())
.filter(|new_edge| input_graph.edges.contains(new_edge))
.count();
if num_edges_leading_to_this_one != 1 {
let mut edge_path = vec![*edge];
let mut longedge_weight = *weight;
let mut last_edge = *edge;
loop {
let last_edge_reverse = last_edge.reversed_unchecked();
let following_edges: Vec<_> = edge_builder
.from_origin_cell(&last_edge.destination_index_unchecked())
.filter_map(|this_edge| {
if this_edge != last_edge_reverse {
input_graph.edges.get_key_value(&this_edge)
} else {
None
}
})
.collect();
if following_edges.len() != 1 {
break;
}
let following_edge = *(following_edges[0].0);
if edge_path.contains(&following_edge) {
break;
}
edge_path.push(following_edge);
longedge_weight = *(following_edges[0].1) + longedge_weight;
last_edge = following_edge;
}
if edge_path.len() >= min_longedge_length {
graph_entry.longedge =
Some((LongEdge::try_from(edge_path)?, longedge_weight));
}
}
new_edges.push((*edge, graph_entry));
}
Ok(new_edges)
})
.collect::<Result<Vec<_>, _>>()?;
for mut part in parts.drain(..) {
edges.insert_many(part.drain(..))
}
Ok(edges)
}
impl<W> PreparedH3EdgeGraph<W>
where
W: PartialOrd + PartialEq + Add + Copy + Send + Ord + Zero + Sync,
{
fn from_h3edge_graph(graph: H3EdgeGraph<W>, min_longedge_length: usize) -> Result<Self, Error> {
let h3_resolution = graph.h3_resolution();
let graph_nodes = graph.nodes();
let edges = to_longedge_edges(graph, min_longedge_length)?;
Ok(Self {
edges,
graph_nodes,
h3_resolution,
})
}
}
impl<W> TryFrom<H3EdgeGraph<W>> for PreparedH3EdgeGraph<W>
where
W: PartialOrd + PartialEq + Add + Copy + Send + Ord + Zero + Sync,
{
type Error = Error;
fn try_from(graph: H3EdgeGraph<W>) -> Result<Self, Self::Error> {
Self::from_h3edge_graph(graph, 3)
}
}
impl<W> From<PreparedH3EdgeGraph<W>> for H3EdgeGraph<W>
where
W: PartialOrd + PartialEq + Add + Copy + Send + Ord + Zero + Sync,
{
fn from(mut prepared_graph: PreparedH3EdgeGraph<W>) -> Self {
Self {
edges: prepared_graph
.edges
.drain()
.map(|(edge, edge_value)| (edge, edge_value.weight))
.collect(),
h3_resolution: prepared_graph.h3_resolution,
}
}
}
impl<W> CoveredArea for PreparedH3EdgeGraph<W>
where
W: Send + Sync,
{
fn covered_area(&self, reduce_resolution_by: u8) -> Result<MultiPolygon<f64>, Error> {
cells_covered_area(
self.graph_nodes.iter().map(|(cell, _)| cell),
self.h3_resolution(),
reduce_resolution_by,
)
}
}
impl<'a, W> IterateCellNodes<'a> for PreparedH3EdgeGraph<W>
where
W: Send + Sync,
{
type CellNodeIterator = TPMIter<'a, H3Cell, NodeType, 4>;
fn iter_cell_nodes(&'a self) -> Self::CellNodeIterator {
self.graph_nodes.iter()
}
}
impl<W> ConcaveHull for PreparedH3EdgeGraph<W>
where
W: Send + Sync,
{
type Scalar = f64;
fn concave_hull(&self, concavity: Self::Scalar) -> Polygon<Self::Scalar> {
let mpoint = MultiPoint::from(
self.iter_cell_nodes()
.map(|(cell, _)| Point::from(cell.to_coordinate()))
.collect::<Vec<_>>(),
);
mpoint.concave_hull(concavity)
}
}
impl<W> BoundingRect<f64> for PreparedH3EdgeGraph<W>
where
W: Send + Sync,
{
type Output = Option<Rect<f64>>;
fn bounding_rect(&self) -> Self::Output {
self.iter_cell_nodes()
.fold(None, |acc, (cell, _): (&H3Cell, &NodeType)| match acc {
Some(rect) => {
let coord = cell.to_coordinate();
Some(Rect::new(
Coordinate {
x: if coord.x < rect.min().x {
coord.x
} else {
rect.min().x
},
y: if coord.y < rect.min().y {
coord.y
} else {
rect.min().y
},
},
Coordinate {
x: if coord.x > rect.max().x {
coord.x
} else {
rect.max().x
},
y: if coord.y > rect.max().y {
coord.y
} else {
rect.max().y
},
},
))
}
None => Some(Point::from(cell.to_coordinate()).bounding_rect()),
})
}
}
#[cfg(test)]
mod tests {
use std::convert::TryInto;
use geo_types::{Coordinate, LineString};
use crate::graph::{H3EdgeGraph, PreparedH3EdgeGraph};
fn build_line_prepared_graph() -> PreparedH3EdgeGraph<u32> {
let full_h3_res = 8;
let cells: Vec<_> = h3ron::line(
&LineString::from(vec![
Coordinate::from((23.3, 12.3)),
Coordinate::from((24.2, 12.2)),
]),
full_h3_res,
)
.unwrap()
.into();
assert!(cells.len() > 100);
let mut graph = H3EdgeGraph::new(full_h3_res);
for w in cells.windows(2) {
graph.add_edge_using_cells(w[0], w[1], 20u32).unwrap();
}
assert!(graph.num_edges() > 50);
let prep_graph: PreparedH3EdgeGraph<_> = graph.try_into().unwrap();
assert_eq!(prep_graph.num_long_edges(), 1);
prep_graph
}
#[test]
fn test_iter_edges() {
let graph = build_line_prepared_graph();
assert!(graph.iter_edges().count() > 50);
}
#[test]
fn test_iter_non_overlapping_edges() {
let graph = build_line_prepared_graph();
assert_eq!(graph.iter_edges_non_overlapping().unwrap().count(), 1);
}
}