Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/python-package.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ jobs:
- uses: dtolnay/rust-toolchain@stable
- name: Test temporal properties and CRS-tagged geometry
run: cargo test --locked --manifest-path src/rust/freestiler-core/Cargo.toml --features geoparquet,duckdb --test native_input
- name: Test reproducible coalescing
run: cargo test --locked --manifest-path src/rust/freestiler-core/Cargo.toml --test coalesce_order

build-wheels:
name: Build Wheel (${{ matrix.os }}, py${{ matrix.python-version }})
Expand Down
4 changes: 4 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@
without GeoParquet or DuckDB support, including in the CRAN build. Existing
calls without category options retain their clustering behavior.

* `coalesce = TRUE` now produces the same archive on every run. Coalesced
groups were emitted in hash-map order, which changes from run to run; they
now keep the order in which their first feature appears in the tile.

# freestiler 0.3.0

* MVT output with `simplification = FALSE` now preserves line positions when
Expand Down
35 changes: 21 additions & 14 deletions src/rust/freestiler-core/src/coalesce.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,22 +61,34 @@ fn property_hash(props: &[PropertyValue]) -> u64 {
hasher.finish()
}

/// Group features by property hash, in order of first appearance, so the
/// output (and the encoded tile bytes) does not depend on hash iteration order.
fn group_by_properties(features: Vec<Feature>) -> Vec<Vec<Feature>> {
let mut slots: HashMap<u64, usize> = HashMap::new();
let mut groups: Vec<Vec<Feature>> = Vec::new();
for f in features {
let slot = *slots
.entry(property_hash(&f.properties))
.or_insert_with(|| {
groups.push(Vec::new());
groups.len() - 1
});
groups[slot].push(f);
}
groups
}

/// Merge line features that share properties and endpoints.
/// Uses an endpoint adjacency graph to chain connected line segments.
fn merge_lines(lines: Vec<Feature>) -> Vec<Feature> {
if lines.is_empty() {
return Vec::new();
}

// Group by property hash
let mut groups: HashMap<u64, Vec<Feature>> = HashMap::new();
for f in lines {
let key = property_hash(&f.properties);
groups.entry(key).or_default().push(f);
}
let groups = group_by_properties(lines);

let mut result = Vec::new();
for (_, group) in groups {
for group in groups {
result.extend(merge_line_group(group));
}
result
Expand Down Expand Up @@ -234,15 +246,10 @@ fn group_polygons(polygons: Vec<Feature>) -> Vec<Feature> {
return Vec::new();
}

// Group by property hash
let mut groups: HashMap<u64, Vec<Feature>> = HashMap::new();
for f in polygons {
let key = property_hash(&f.properties);
groups.entry(key).or_default().push(f);
}
let groups = group_by_properties(polygons);

let mut result = Vec::new();
for (_, group) in groups {
for group in groups {
if group.len() == 1 {
result.push(group.into_iter().next().unwrap());
} else {
Expand Down
89 changes: 89 additions & 0 deletions src/rust/freestiler-core/tests/coalesce_order.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
//! `coalesce_features()` must emit its property groups in a stable order.
//! Groups used to come out in `HashMap` iteration order, which is seeded per
//! map, so `coalesce = TRUE` archives differed from run to run.

use freestiler_core::{
coalesce::coalesce_features,
geo_types::{LineString, Polygon},
tiler::{Feature, Geometry, PropertyValue},
};

fn square(x: f64, y: f64) -> Geometry {
let ring = LineString::from(vec![
(x, y),
(x + 1.0, y),
(x + 1.0, y + 1.0),
(x, y + 1.0),
(x, y),
]);
Geometry::Polygon(Polygon::new(ring, vec![]))
}

fn segment(x: f64, y: f64) -> Geometry {
Geometry::LineString(LineString::from(vec![(x, y), (x + 1.0, y)]))
}

/// Interleaved features from eight property groups, first seen in the order
/// class 0, 1, ..., 7 for polygons and lines alike.
fn features() -> Vec<Feature> {
let mut out = Vec::new();
for k in 0..48u64 {
let class = (k % 8) as i64;
let column = (k / 8) as f64;
out.push(Feature {
id: Some(k + 1),
geometry: square(column * 2.0, class as f64 * 2.0),
properties: vec![PropertyValue::Int(class)],
});
out.push(Feature {
id: Some(1000 + k),
// Segments of one class touch end to end, so they merge.
geometry: segment(column, 100.0 + class as f64),
properties: vec![PropertyValue::Int(class)],
});
}
out
}

fn classes(features: &[Feature]) -> Vec<(bool, i64)> {
features
.iter()
.map(|f| {
let is_line = matches!(
f.geometry,
Geometry::LineString(_) | Geometry::MultiLineString(_)
);
match f.properties[0] {
PropertyValue::Int(class) => (is_line, class),
_ => unreachable!(),
}
})
.collect()
}

#[test]
fn coalesce_groups_in_first_appearance_order() {
let names = vec!["class".to_string()];
let first = coalesce_features(features(), &names);

// Lines first (one merged LineString per class), then one MultiPolygon
// per class, each in order of first appearance.
let expected: Vec<(bool, i64)> = (0..8)
.map(|c| (true, c))
.chain((0..8).map(|c| (false, c)))
.collect();
assert_eq!(classes(&first), expected);
assert!(first[..8]
.iter()
.all(|f| matches!(f.geometry, Geometry::LineString(_))));
assert!(first[8..]
.iter()
.all(|f| matches!(f.geometry, Geometry::MultiPolygon(_))));

// Each HashMap gets a fresh random seed, so repeated calls in one process
// were enough to reorder the groups before the fix.
for _ in 0..32 {
let again = coalesce_features(features(), &names);
assert_eq!(format!("{first:?}"), format!("{again:?}"));
}
}
31 changes: 31 additions & 0 deletions tests/testthat/test-coalesce.R
Original file line number Diff line number Diff line change
Expand Up @@ -109,3 +109,34 @@ test_that("all features combined: drop + cluster + coalesce", {
expect_true(file.exists(output))
expect_true(file.info(output)$size > 0)
})

test_that("coalesce output is identical from run to run", {
skip_on_cran()
skip_if_not_installed("sf")

nc <- sf::st_read(
system.file("shape/nc.shp", package = "sf"),
quiet = TRUE
)
# Few distinct values, so most tiles hold several coalesced groups.
nc <- sf::st_sf(class = nc$SID74 %% 3, geometry = sf::st_geometry(nc))

outputs <- replicate(2, tempfile(fileext = ".pmtiles"))
on.exit(unlink(outputs), add = TRUE)

for (output in outputs) {
freestile(
nc,
output,
layer_name = "counties",
tile_format = "mvt",
min_zoom = 0,
max_zoom = 7,
coalesce = TRUE,
quiet = TRUE
)
}

read_all <- function(path) readBin(path, "raw", file.info(path)$size)
expect_identical(read_all(outputs[[1]]), read_all(outputs[[2]]))
})