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
|
//! Python bindings for hittekaart.
//!
//! This module provides simple-to-use bindings for hittekaart generation from Python scripts.
use hittekaart::gpx::{self, Compression, Coordinates};
use hittekaart::renderer::{self, Renderer};
use pyo3::create_exception;
use pyo3::exceptions::PyTypeError;
use pyo3::prelude::*;
use std::error::Error;
use std::ffi::OsStr;
use std::fmt::Write as _;
use std::os::unix::ffi::OsStrExt as _;
use std::path::PathBuf;
create_exception!(hittekaart_py, HitteError, pyo3::exceptions::PyException);
/// Converts an error to a Python error.
///
/// This basically maps everything to [`HitteError`] and provides a stringified error explanation.
///
/// This recursively uses `::source()` to walk the chain.
fn err_to_py(mut error: &dyn Error) -> PyErr {
let mut text = error.to_string();
loop {
match error.source() {
None => break,
Some(e) => error = e,
}
write!(&mut text, "\ncaused by: {error}").unwrap();
}
HitteError::new_err(text)
}
/// Python representation of a track.
#[pyclass]
#[derive(Debug, Clone)]
struct Track {
inner: Vec<Coordinates>,
}
#[pymethods]
impl Track {
/// Load a track from a file.
///
/// Compression - if given - should be one of the strings "gzip" or "brotli".
#[staticmethod]
fn from_file(path: &[u8], compression: Option<&str>) -> PyResult<Track> {
let compression = match compression {
None | Some("") => Compression::None,
Some("gzip") => Compression::Gzip,
Some("brotli") => Compression::Brotli,
Some(x) => return Err(HitteError::new_err(format!("invalid compression: {x}"))),
};
let track = gpx::extract_from_file(OsStr::from_bytes(path), compression)
.map_err(|e| err_to_py(&e))?;
Ok(Track { inner: track })
}
/// Load a track from the given coordinates.
#[staticmethod]
fn from_coordinates(coordinates: Vec<(f64, f64)>) -> Track {
Track {
inner: coordinates
.iter()
.map(|(lon, lat)| Coordinates::new(*lon, *lat))
.collect(),
}
}
}
impl Track {
fn coordinates(&self) -> Vec<(f64, f64)> {
self.inner
.iter()
.map(|c| (c.longitude, c.latitude))
.collect()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum StorageType {
Folder(PathBuf),
Sqlite(PathBuf),
}
/// Python representation of a storage target.
#[pyclass]
#[derive(Debug, Clone, PartialEq, Eq)]
struct Storage(StorageType);
#[pymethods]
impl Storage {
/// Output to the given folder.
#[staticmethod]
#[pyo3(name = "Folder")]
fn folder(path: &[u8]) -> Self {
let path = OsStr::from_bytes(path);
Storage(StorageType::Folder(path.into()))
}
/// Output to the given sqlite file.
#[staticmethod]
#[pyo3(name = "Sqlite")]
fn sqlite(path: &[u8]) -> Self {
let path = OsStr::from_bytes(path);
Storage(StorageType::Sqlite(path.into()))
}
}
impl Storage {
fn open(&self) -> PyResult<Box<dyn hittekaart::storage::Storage>> {
match self.0 {
StorageType::Folder(ref path) => {
let storage = hittekaart::storage::Folder::new(path.clone());
Ok(Box::new(storage))
}
StorageType::Sqlite(ref path) => {
let storage = hittekaart::storage::Sqlite::connect(path.clone())
.map_err(|e| err_to_py(&e))?;
Ok(Box::new(storage))
}
}
}
}
/// Python representation of a heatmap renderer.
#[pyclass]
struct HeatmapRenderer {
inner: renderer::heatmap::Renderer,
}
#[pymethods]
impl HeatmapRenderer {
#[new]
fn new() -> HeatmapRenderer {
HeatmapRenderer {
inner: renderer::heatmap::Renderer,
}
}
}
/// Generate the heatmap.
///
/// * `items` is an iterable of [`Track`]s
/// * `renderer` should be a renderer (like [`HeatmapRenderer`])
/// * `storage` is the [`Storage`] output
#[pyfunction]
fn generate(
items: &Bound<'_, PyAny>,
renderer: &Bound<'_, PyAny>,
storage: &Bound<'_, Storage>,
) -> PyResult<()> {
let mut tracks = vec![];
for item in items.try_iter()? {
let item = item?;
tracks.push(item.extract::<Track>()?.inner);
}
if let Ok(r) = renderer.downcast::<HeatmapRenderer>() {
do_generate(tracks, &r.borrow().inner, &mut *storage.borrow().open()?)
} else {
Err(PyTypeError::new_err("Expected a HeatmapRenderer"))
}
}
fn do_generate<R: Renderer>(
tracks: Vec<Vec<Coordinates>>,
renderer: &R,
storage: &mut dyn hittekaart::storage::Storage,
) -> PyResult<()> {
storage.prepare().map_err(|e| err_to_py(&e))?;
for zoom in 0..=19 {
let counter =
renderer::prepare(renderer, zoom, &tracks, || Ok(())).map_err(|e| err_to_py(&e))?;
storage.prepare_zoom(zoom).map_err(|e| err_to_py(&e))?;
renderer::colorize(renderer, counter, |rendered_tile| {
storage.store(zoom, rendered_tile.x, rendered_tile.y, &rendered_tile.data)?;
Ok(())
})
.map_err(|e| err_to_py(&e))?;
}
storage.finish().map_err(|e| err_to_py(&e))?;
Ok(())
}
#[pyfunction]
fn set_threads(threads: usize) -> PyResult<()> {
rayon::ThreadPoolBuilder::new()
.num_threads(threads)
.build_global()
.map_err(|e| err_to_py(&e))
}
/// A Python module implemented in Rust.
#[pymodule]
fn hittekaart_py(py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<Track>()?;
m.add_class::<HeatmapRenderer>()?;
m.add_class::<Storage>()?;
m.add_function(wrap_pyfunction!(generate, m)?)?;
m.add_function(wrap_pyfunction!(set_threads, m)?)?;
m.add("HitteError", py.get_type::<HitteError>())?;
Ok(())
}
|