forked from a-b-street/ltn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.rs
80 lines (68 loc) · 2.22 KB
/
lib.rs
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
use anyhow::Result;
use geo::{MultiPolygon, PreparedGeometry};
use serde::{Deserialize, Deserializer};
#[derive(Deserialize)]
pub struct StudyArea {
#[serde(deserialize_with = "geojson::de::deserialize_geometry")]
pub geometry: MultiPolygon,
pub name: String,
pub kind: String,
}
impl StudyArea {
pub fn read_all_from_file() -> Result<Vec<Self>> {
let study_areas = geojson::de::deserialize_feature_collection_str_to_vec(
&std::fs::read_to_string("boundaries.geojson")?,
)?;
println!("Read {} study area boundaries", study_areas.len());
Ok(study_areas)
}
pub fn read_all_prepared_from_file(
) -> Result<Vec<(PreparedGeometry<'static, MultiPolygon>, Self)>> {
let iter = Self::read_all_from_file()?.into_iter().map(|study_area| {
(
PreparedGeometry::from(study_area.geometry.clone()),
study_area,
)
});
Ok(iter.collect())
}
}
#[derive(Deserialize)]
pub struct PopulationZoneInput {
#[serde(deserialize_with = "deserialize_prepared_multipolygon")]
pub geometry: PreparedGeometry<'static, MultiPolygon>,
// "id": "S01006506",
// (unused)
// "imd_rank": 4691,
// (unused)
// "imd_percentile": 68,
pub imd_percentile: u8,
// "population": 894,
pub population: u32,
// "area": 4388802.1221970674
pub area: f64,
}
pub fn deserialize_prepared_multipolygon<'de, D>(
deserializer: D,
) -> std::result::Result<PreparedGeometry<'static, MultiPolygon>, D::Error>
where
D: Deserializer<'de>,
{
let multi_polygon: MultiPolygon = geojson::de::deserialize_geometry(deserializer)?;
Ok(PreparedGeometry::from(multi_polygon))
}
impl PopulationZoneInput {
pub fn read_all_from_file() -> Result<Vec<Self>> {
let population_zones = geojson::de::deserialize_feature_collection_str_to_vec(
&fs_err::read_to_string("tmp/population.geojson")?,
)?;
println!("Read {} population zones", population_zones.len());
Ok(population_zones)
}
pub fn area_km2(&self) -> f64 {
self.area / 1000.0 / 1000.0
}
pub fn density_per_km2(&self) -> f64 {
self.population as f64 / self.area_km2()
}
}