Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BREAKING CHANGE: add non-geospatial option #2

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
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
160 changes: 125 additions & 35 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,41 @@ const OFFSET_NUM: usize = 5;
/// An offset index used to access the properties associated with a cluster in the data arrays.
const OFFSET_PROP: usize = 6;

/// The range of the incoming data if choosing the cartesian coordinate system
#[derive(Clone, Debug)]
pub struct DataRange {
min_x: f64,
min_y: f64,
max_x: f64,
max_y: f64,
}

// TODO: Add comment and rename this
impl DataRange {
fn scale_x(&self, x: f64) -> f64 {
(x - self.min_x) / (self.max_x - self.min_x)
}

fn scale_y(&self, y: f64) -> f64 {
(y - self.min_y) / (self.max_y - self.min_y)
}

fn unscale_x(&self, x_scaled: f64) -> f64 {
x_scaled * (self.max_x - self.min_x) + self.min_x
}

fn unscale_y(&self, y_scaled: f64) -> f64 {
y_scaled * (self.max_y - self.min_y) + self.min_y
}
}

/// Coordinate system for clustering.
#[derive(Clone, Debug)]
pub enum CoordinateSystem {
LatLng, // Choose this for geo-spatial data
Cartesian { data_range: DataRange }, // Chose this for non-geospatial (i.e. microscopy, etc.) data
}

/// Supercluster configuration options.
#[derive(Clone, Debug)]
pub struct Options {
Expand All @@ -42,6 +77,9 @@ pub struct Options {

/// Size of the KD-tree leaf node, affects performance.
pub node_size: usize,

/// The type of coordinate system for clustering: lat/lng or cartesian.
pub coordinate_system: CoordinateSystem,
}

#[derive(Clone, Debug)]
Expand Down Expand Up @@ -116,11 +154,22 @@ impl Supercluster {
None => continue,
};

// Longitude
data.push(lng_x(coordinates[0]));
match &self.options.coordinate_system {
CoordinateSystem::Cartesian { data_range } => {
// X Coordinate
data.push(data_range.scale_x(coordinates[0]));

// Latitude
data.push(lat_y(coordinates[1]));
// Y Coordinate
data.push(data_range.scale_y(coordinates[1]));
}
CoordinateSystem::LatLng => {
// Longitude
data.push(lng_x(coordinates[0]));

// Latitude
data.push(lat_y(coordinates[1]));
}
};

// The last zoom the point was processed at
data.push(f64::INFINITY);
Expand Down Expand Up @@ -161,39 +210,55 @@ impl Supercluster {
///
/// A vector of GeoJSON features representing the clusters within the specified bounding box and zoom level.
pub fn get_clusters(&self, bbox: [f64; 4], zoom: u8) -> Vec<Feature> {
let mut min_lng = ((((bbox[0] + 180.0) % 360.0) + 360.0) % 360.0) - 180.0;
let min_lat = bbox[1].clamp(-90.0, 90.0);
let mut max_lng = if bbox[2] == 180.0 {
180.0
} else {
((((bbox[2] + 180.0) % 360.0) + 360.0) % 360.0) - 180.0
};
let max_lat = bbox[3].clamp(-90.0, 90.0);
let tree = &self.trees[self.limit_zoom(zoom)];
let ids = match &self.options.coordinate_system {
CoordinateSystem::Cartesian { data_range } => tree.range(
data_range.scale_x(bbox[0]),
data_range.scale_y(bbox[1]),
data_range.scale_x(bbox[2]),
data_range.scale_y(bbox[3]),
),
CoordinateSystem::LatLng => {
let mut min_lng = ((((bbox[0] + 180.0) % 360.0) + 360.0) % 360.0) - 180.0;
let min_lat = bbox[1].clamp(-90.0, 90.0);
let mut max_lng = if bbox[2] == 180.0 {
180.0
} else {
((((bbox[2] + 180.0) % 360.0) + 360.0) % 360.0) - 180.0
};
let max_lat = bbox[3].clamp(-90.0, 90.0);

if bbox[2] - bbox[0] >= 360.0 {
min_lng = -180.0;
max_lng = 180.0;
} else if min_lng > max_lng {
let eastern_hem = self.get_clusters([min_lng, min_lat, 180.0, max_lat], zoom);
let western_hem = self.get_clusters([-180.0, min_lat, max_lng, max_lat], zoom);
if bbox[2] - bbox[0] >= 360.0 {
min_lng = -180.0;
max_lng = 180.0;
} else if min_lng > max_lng {
let eastern_hem = self.get_clusters([min_lng, min_lat, 180.0, max_lat], zoom);
let western_hem = self.get_clusters([-180.0, min_lat, max_lng, max_lat], zoom);

return eastern_hem.into_iter().chain(western_hem).collect();
}
return eastern_hem.into_iter().chain(western_hem).collect();
}

tree.range(
lng_x(min_lng),
lat_y(max_lat),
lng_x(max_lng),
lat_y(min_lat),
)
}
};

let tree = &self.trees[self.limit_zoom(zoom)];
let ids = tree.range(
lng_x(min_lng),
lat_y(max_lat),
lng_x(max_lng),
lat_y(min_lat),
);
let mut clusters = Vec::new();

for id in ids {
let k = self.stride * id;

clusters.push(if tree.data[k + OFFSET_NUM] > 1.0 {
get_cluster_json(&tree.data, k, &self.cluster_props)
get_cluster_json(
&tree.data,
k,
&self.cluster_props,
&self.options.coordinate_system,
)
} else {
self.points[tree.data[k + OFFSET_ID] as usize].clone()
});
Expand Down Expand Up @@ -244,7 +309,12 @@ impl Supercluster {

if data[k + OFFSET_PARENT] == (cluster_id as f64) {
if data[k + OFFSET_NUM] > 1.0 {
children.push(get_cluster_json(data, k, &self.cluster_props));
children.push(get_cluster_json(
data,
k,
&self.cluster_props,
&self.options.coordinate_system,
));
} else {
let point_id = data[k + OFFSET_ID] as usize;

Expand Down Expand Up @@ -490,8 +560,16 @@ impl Supercluster {
match p.geometry.as_ref() {
Some(geometry) => {
if let Point(coordinates) = &geometry.value {
px = lng_x(coordinates[0]);
py = lat_y(coordinates[1]);
match &self.options.coordinate_system {
CoordinateSystem::Cartesian { data_range } => {
px = data_range.scale_x(coordinates[0]);
py = data_range.scale_y(coordinates[1]);
}
CoordinateSystem::LatLng => {
px = lng_x(coordinates[0]);
py = lat_y(coordinates[1]);
}
}
} else {
continue;
}
Expand Down Expand Up @@ -679,8 +757,19 @@ impl Supercluster {
/// # Returns
///
/// A GeoJSON feature representing a cluster.
fn get_cluster_json(data: &[f64], i: usize, cluster_props: &[JsonObject]) -> Feature {
let geometry = Geometry::new(Point(vec![x_lng(data[i]), y_lat(data[i + 1])]));
fn get_cluster_json(
data: &[f64],
i: usize,
cluster_props: &[JsonObject],
coordinate_system: &CoordinateSystem,
) -> Feature {
let geometry = match coordinate_system {
CoordinateSystem::Cartesian { data_range } => Geometry::new(Point(vec![
data_range.unscale_x(data[i]),
data_range.unscale_y(data[i + 1]),
])),
CoordinateSystem::LatLng => Geometry::new(Point(vec![x_lng(data[i]), y_lat(data[i + 1])])),
};

Feature {
id: Some(Id::String(data[i + OFFSET_ID].to_string())),
Expand Down Expand Up @@ -797,6 +886,7 @@ mod tests {
min_zoom: 0,
min_points: 2,
node_size: 64,
coordinate_system: CoordinateSystem::LatLng,
})
}

Expand Down Expand Up @@ -836,7 +926,7 @@ mod tests {
json!("0".to_string()),
);

let result = get_cluster_json(&data, i, &[cluster_props]);
let result = get_cluster_json(&data, i, &[cluster_props], &CoordinateSystem::LatLng);

assert_eq!(result.id, Some(Id::String("0".to_string())));

Expand Down Expand Up @@ -873,7 +963,7 @@ mod tests {
let i = 0;
let cluster_props = vec![];

let result = get_cluster_json(&data, i, &cluster_props);
let result = get_cluster_json(&data, i, &cluster_props, &CoordinateSystem::LatLng);

assert_eq!(result.id, Some(Id::String("0".to_string())));

Expand Down
7 changes: 7 additions & 0 deletions tests/common/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,10 @@ pub fn load_tile_places_with_min_5() -> FeatureCollection {

serde_json::from_str(&json_string).expect("places-z0-0-0-min5.json was not parsed")
}

pub fn load_non_geospatial() -> Vec<Feature> {
let file_path = Path::new("./tests/common/non-geospatial.json");
let json_string = fs::read_to_string(file_path).expect("non-geospatial.json was not found");

serde_json::from_str(&json_string).expect("non-geospatial.json was not parsed")
}
83 changes: 83 additions & 0 deletions tests/common/non-geospatial.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
[
{
"type": "Feature",
"properties": {
"name": "Feature A"
},
"geometry": {
"type": "Point",
"coordinates": [10.0, 10.0]
}
},
{
"type": "Feature",
"properties": {
"name": "Feature B"
},
"geometry": {
"type": "Point",
"coordinates": [15.0, 15.0]
}
},
{
"type": "Feature",
"properties": {
"name": "Feature C"
},
"geometry": {
"type": "Point",
"coordinates": [20.0, 20.0]
}
},
{
"type": "Feature",
"properties": {
"name": "Feature D"
},
"geometry": {
"type": "Point",
"coordinates": [50.0, 50.0]
}
},
{
"type": "Feature",
"properties": {
"name": "Feature E"
},
"geometry": {
"type": "Point",
"coordinates": [181.0, 541.0]
}
},
{
"type": "Feature",
"properties": {
"name": "Feature F"
},
"geometry": {
"type": "Point",
"coordinates": [997.0, 800.0]
}
},
{
"type": "Feature",
"properties": {
"name": "Feature G"
},
"geometry": {
"type": "Point",
"coordinates": [998.0, 800.0]
}
},
{
"type": "Feature",
"properties": {
"name": "Feature H"
},
"geometry": {
"type": "Point",
"coordinates": [999.0, 800.0]
}
}
]

18 changes: 17 additions & 1 deletion tests/supercluster_integration_test.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
mod common;

use common::{get_options, load_places, load_tile_places, load_tile_places_with_min_5};
use common::{
get_options, load_non_geospatial, load_places, load_tile_places, load_tile_places_with_min_5,
};
use geojson::{Feature, Geometry, JsonObject, Value::Point};
use serde_json::json;
use supercluster::Supercluster;
Expand Down Expand Up @@ -192,3 +194,17 @@ fn test_does_not_crash_on_weird_bbox_values() {
61
);
}

#[test]
fn test_non_geospatial() {
let mut cluster = Supercluster::new_non_geospatial(get_options(500.0, 32.0, 2, 16));
let index = cluster.load(load_non_geospatial());

let clusters = index.get_clusters([0.0, 0.0, 1000.0, 1000.0], 0);

assert_eq!(clusters.len(), 4);
assert_eq!(clusters[0].property("point_count").unwrap(), 3);
assert_eq!(clusters[1].property("point_count"), None);
assert_eq!(clusters[2].property("point_count"), None);
assert_eq!(clusters[3].property("point_count").unwrap(), 3);
}