Skip to content

Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.

fix: avoid quadratic membership copies in dense clusters (#3890)

Igor Dykhtad41c7bc30273
diff --git a/src/deckgl-layers/src/layer-utils/cluster-utils.spec.ts b/src/deckgl-layers/src/layer-utils/cluster-utils.spec.ts
index 771be01b0..f2d9055e3 100644
--- a/src/deckgl-layers/src/layer-utils/cluster-utils.spec.ts
+++ b/src/deckgl-layers/src/layer-utils/cluster-utils.spec.ts
@@ -2,6 +2,7 @@
// Copyright contributors to the kepler.gl project
import ClusterBuilder, {getGeoJSON} from './cluster-utils';
+import Supercluster from 'supercluster';
const WORLD_BBOX: [number, number, number, number] = [-180, -85, 180, 85];
@@ -40,4 +41,139 @@ describe('ClusterBuilder.clustersAtZoom', () => {
test('a cutoff above every cluster leaves nothing to draw', () => {
expect(clusterSizes(4)).toEqual({sizes: [], indices: []});
});
+
+ test('membership reads grow linearly for coincident points', () => {
+ for (const size of [128, 256, 512]) {
+ let reads = 0;
+ const proxies = new WeakMap<object[], object[]>();
+ const countReads = (points: object[]) => {
+ const existing = proxies.get(points);
+ if (existing) return existing;
+ const proxy = new Proxy(points, {
+ get(target, key, receiver) {
+ if (typeof key === 'string' && /^\d+$/.test(key)) reads++;
+ return Reflect.get(target, key, receiver);
+ }
+ });
+ proxies.set(points, proxy);
+ proxies.set(proxy, proxy);
+ return proxy;
+ };
+ const load = Supercluster.prototype.load;
+ const spy = jest
+ .spyOn(Supercluster.prototype, 'load')
+ .mockImplementation(function (this: Supercluster, points) {
+ const {options} = this as unknown as {
+ options: {
+ reduce: (accumulated: {points: object[]}, props: {points: object[]}) => void;
+ };
+ };
+ const reduce = options.reduce;
+ options.reduce = (accumulated, props) => {
+ // Observe reference reads by the real reducer, including slice/concat/spread.
+ // Preserve accumulator identity and never modify the incoming properties.
+ accumulated.points = countReads(accumulated.points);
+ reduce(accumulated, {...props, points: countReads(props.points)});
+ };
+ return load.call(this, points);
+ });
+ try {
+ const input = Array.from({length: size}, (_, index) => ({index, position: [0, 0]}));
+ const clusters = query(
+ new ClusterBuilder(),
+ getGeoJSON(input, d => d.position, null)
+ );
+ expect(clusters).toHaveLength(1);
+ expect(clusters[0].points).toHaveLength(size);
+ // Allow constant-factor implementation differences, but reject repeated prefixes.
+ expect(reads).toBeLessThanOrEqual(size * 4);
+ } finally {
+ spy.mockRestore();
+ }
+ }
+ });
+
+ test('preserves child membership, identity, multiplicity and order across zooms', () => {
+ const hierarchy = [0, 0.0002, 0.002, 0.02, 0.2, 2, 20].flatMap((lng, group) =>
+ Array.from({length: group + 2}, (_, index) =>
+ Object.freeze({index: group * 100 + index, position: Object.freeze([lng, 0])})
+ )
+ );
+ const scattered = Array.from({length: 128}, (_, index) =>
+ Object.freeze({
+ index,
+ position: Object.freeze([-170 + ((index * 37) % 340), -65 + ((index * 19) % 130)])
+ })
+ );
+ for (const input of [Object.freeze([...hierarchy, hierarchy[0]]), Object.freeze(scattered)]) {
+ const geoJSON = getGeoJSON(input, d => d.position, null);
+ for (const point of geoJSON) {
+ Object.freeze(point.properties.points);
+ Object.freeze(point.properties);
+ Object.freeze(point.geometry);
+ Object.freeze(point);
+ }
+ Object.freeze(geoJSON);
+
+ // The immutable reducer defines the existing ordering independently of ownership.
+ const reference = new Supercluster({
+ maxZoom: 20,
+ radius: 40,
+ map: props => ({points: [props.data]}),
+ reduce: (accumulated, props) => {
+ accumulated.points = accumulated.points.concat(props.points);
+ }
+ }).load(geoJSON);
+ const builder = new ClusterBuilder();
+ for (const zoom of [21, 20, 18, 15, 12, 9, 6, 3, 0, 20, 4, 21]) {
+ const expected = reference.getClusters(WORLD_BBOX, zoom);
+ const actual = query(builder, geoJSON, zoom);
+ expect(actual).toHaveLength(expected.length);
+ actual.forEach((cluster, index) => {
+ const members = expected[index].properties.points;
+ expect(cluster.index).toBe(index);
+ expect(cluster.position).toEqual(expected[index].geometry.coordinates);
+ expect(cluster.points).toHaveLength(members.length);
+ cluster.points.forEach((point, i) => expect(point).toBe(members[i]));
+ });
+ expect(actual.reduce((sum, cluster) => sum + cluster.points.length, 0)).toBe(input.length);
+ }
+ geoJSON.forEach(point => {
+ expect(point.properties.points).toHaveLength(1);
+ expect(point.properties.points[0]).toBe(point.properties.data);
+ });
+ }
+ });
+
+ test('keeps cached membership stable through radius changes and filtered rebuilds', () => {
+ const input = [...data, {index: 4, position: [NaN, 0]}, {index: 5, position: [0, Infinity]}];
+ const geoJSON = getGeoJSON(input, d => d.position, null);
+ const builder = new ClusterBuilder();
+ const initial = query(builder, geoJSON);
+ const snapshot = initial.map(cluster => cluster.points.slice());
+ const firstIndex = builder.clusterer({clusterRadius: 40, geoJSON});
+ query(builder, geoJSON, 12, 60);
+ expect(builder.clusterer({clusterRadius: 40, geoJSON})).toBe(firstIndex);
+ expect(query(builder, geoJSON).map(cluster => cluster.points)).toEqual(snapshot);
+
+ builder.clearClustererCache();
+ const filtered = getGeoJSON(
+ input,
+ d => d.position,
+ d => d.index % 2 === 0
+ );
+ expect(query(builder, filtered).flatMap(cluster => cluster.points)).toEqual([data[0], data[2]]);
+ expect(builder.clusterer({clusterRadius: 40, geoJSON: filtered})).not.toBe(firstIndex);
+ expect(initial.map(cluster => cluster.points)).toEqual(snapshot);
+
+ for (const remaining of [[], [data[3]]]) {
+ builder.clearClustererCache();
+ const next = getGeoJSON(remaining, d => d.position, null);
+ expect(query(builder, next).flatMap(cluster => cluster.points)).toEqual(remaining);
+ }
+ });
});
+
+function query(builder: ClusterBuilder, geoJSON, zoom = 4, clusterRadius = 40) {
+ return builder.clustersAtZoom({bbox: WORLD_BBOX, clusterRadius, geoJSON, zoom});
+}
diff --git a/src/deckgl-layers/src/layer-utils/cluster-utils.ts b/src/deckgl-layers/src/layer-utils/cluster-utils.ts
index b47d79ab3..e1331ed16 100644
--- a/src/deckgl-layers/src/layer-utils/cluster-utils.ts
+++ b/src/deckgl-layers/src/layer-utils/cluster-utils.ts
@@ -33,15 +33,26 @@ export function getGeoJSON(data, getPosition, filterData) {
const clusterResolver = ({clusterRadius}: {clusterRadius: number}) => `${clusterRadius}`;
-const getClusterer = ({clusterRadius, geoJSON}: {clusterRadius: number; geoJSON}) =>
- new Supercluster({
+const getClusterer = ({clusterRadius, geoJSON}: {clusterRadius: number; geoJSON}) => {
+ const ownedAccumulators = new WeakSet();
+ return new Supercluster({
maxZoom: 20,
radius: clusterRadius,
reduce: (accumulated, props) => {
- accumulated.points = [...accumulated.points, ...props.points];
+ // Supercluster shallow-copies a child's properties when starting a parent.
+ // Clone its shared points once per accumulator, then append without copying
+ // the growing prefix. Track object identity so a parent acquires its own array.
+ if (!ownedAccumulators.has(accumulated)) {
+ accumulated.points = accumulated.points.slice();
+ ownedAccumulators.add(accumulated);
+ }
+ for (const point of props.points) {
+ accumulated.points.push(point);
+ }
},
map: props => ({points: [props.data]})
}).load(geoJSON);
+};
export default class ClusterBuilder {
clusterer: (({clusterRadius, geoJSON}: {clusterRadius: number; geoJSON}) => Supercluster) &
diff --git a/test/browser/layer-tests/cluster-layer-specs.js b/test/browser/layer-tests/cluster-layer-specs.js
index 8007c585c..919c43792 100644
--- a/test/browser/layer-tests/cluster-layer-specs.js
+++ b/test/browser/layer-tests/cluster-layer-specs.js
@@ -3,6 +3,10 @@
import test from 'tape';
import sinon from 'sinon';
+import Supercluster from 'supercluster';
+import {LayerManager, WebMercatorViewport} from '@deck.gl/core';
+import {device} from '@deck.gl/test-utils';
+import {DeckGLClusterLayer} from '@kepler.gl/deckgl-layers';
import {
testCreateCases,
@@ -497,3 +501,85 @@ test('#ClusterLayer -> count labels follow the text label field', t => {
]);
t.end();
});
+
+test('#ClusterLayer -> membership survives cached zooms and filtered rebuilds', t => {
+ const points = Object.freeze(
+ Array.from({length: 24}, (_, index) =>
+ Object.freeze({index, value: index + 1, position: [index < 12 ? 0 : 0.0002, 0]})
+ )
+ );
+ const viewport = new WebMercatorViewport({
+ longitude: 0,
+ latitude: 0,
+ zoom: 0,
+ width: 2048,
+ height: 2048
+ });
+ const manager = new LayerManager(device, {viewport});
+ const load = sinon.spy(Supercluster.prototype, 'load');
+ let labels = [];
+ let layer = new DeckGLClusterLayer({
+ id: 'cluster-membership-updates',
+ data: points,
+ getPosition: point => point.position,
+ getColorValue: members => members.reduce((sum, point) => sum + point.value, 0),
+ colorRange: [
+ [0, 0, 0],
+ [255, 255, 255]
+ ],
+ clusterRadius: 40,
+ zoom: 20,
+ width: 2048,
+ height: 2048,
+ renderCountLabels: data => {
+ labels = data;
+ return [];
+ }
+ });
+ const update = (patch, expected, rebuilds) => {
+ const before = load.callCount;
+ layer = layer.clone(patch);
+ manager.setLayers([layer]);
+ const cells = layer.state.aggregatorState.layerData.data;
+ t.equal(load.callCount - before, rebuilds, 'only changed inputs build a cluster index');
+ t.deepEqual(
+ cells.flatMap(cell => cell.points).sort((a, b) => a.index - b.index),
+ expected,
+ 'membership contains exactly the retained source rows'
+ );
+ t.equal(
+ labels.reduce((sum, label) => sum + label.count, 0),
+ expected.length,
+ 'labels count members'
+ );
+ cells.forEach(cell => {
+ const picked = layer.getPickingInfo({info: {picked: true, index: cell.index}}).object;
+ t.deepEqual(picked.points, cell.points, 'picking returns the ordered cluster members');
+ t.equal(picked.radiusValue, cell.points.length, 'radius uses the member count');
+ t.equal(
+ picked.colorValue,
+ cell.points.reduce((sum, point) => sum + point.value, 0),
+ 'color aggregates the same members'
+ );
+ });
+ };
+ try {
+ update({}, points, 1);
+ update({zoom: 4}, points, 0);
+ update(
+ {filterData: point => point.index % 2 === 0, updateTriggers: {filterData: 1}},
+ points.filter(point => point.index % 2 === 0),
+ 1
+ );
+ update({filterData: () => false, updateTriggers: {filterData: 2}}, [], 1);
+ update({filterData: null, updateTriggers: {filterData: 3}}, points, 1);
+ update({clusterRadius: 60}, points, 1);
+ update({clusterRadius: 40}, points, 0);
+ update({zoom: 20}, points, 0);
+ update({data: points.slice(0, 8)}, points.slice(0, 8), 1);
+ } finally {
+ load.restore();
+ manager.finalize();
+ }
+ t.end();
+});