Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
feat(layers): contour layer adjustments (#3976)
Igor Dykhta05676090cff9
diff --git a/docs/user-guides/c-types-of-layers/contour.md b/docs/user-guides/c-types-of-layers/contour.mdindex 45c5a2888..403a045da 100644--- a/docs/user-guides/c-types-of-layers/contour.md+++ b/docs/user-guides/c-types-of-layers/contour.md@@ -1,7 +1,9 @@# Contour layer (prototype)-The Contour layer draws smooth, nested regions and outlines from a numeric scalar field.-Values can represent any quantity; the layer does not calculate travel time or point density.+The Contour layer draws smooth, nested regions and outlines from point observations.+Select a numeric weight column to contour the mean weight in each geographic cell.+Leave the weight column empty to contour point density (the number of points per cell,+not points per square kilometer). The layer does not calculate travel time.## Layer availability@@ -21,7 +23,7 @@ Contour layers in saved maps still load and render, as with other optional layer## Try the sampleStart the demo app with `yarn start` and append `?sample=contour` to its URL. The sample-loads an abstract scalar field around Frankfurt with turquoise fills and outlines.+loads an abstract scalar field around Frankfurt with nested fills and outlines.Use `?sample=contour-scattered` for scattered measurements of the same field.It is synthetic data, not a travel-time map. The generator is in`examples/demo-app/src/data/sample-contour-data.ts`.@@ -30,58 +32,62 @@ It is synthetic data, not a travel-time map. The generator is inSelect **Contour** in the layer selector, then choose a column mode:-- **Scalar samples**: assign numeric longitude, latitude, and value columns.-- **GeoJSON**: assign a geometry column and a numeric value column. Each row produces+- **Points**: assign numeric longitude and latitude columns, and optionally a numeric weight column.+- **GeoJSON**: assign a geometry column and an optional numeric weight column. Each row producesone sample at the geometry's representative point, using the same centroid helperas Grid, Hexbin, and Heatmap. Points use their coordinates; lines, polygons, multi-geometries, and geometry collections use the average of their vertices (includingclosing ring vertices). This is not an area-weighted polygon centroid and can lieoutside a concave feature. GeoJSON geometry/Feature objects and JSON strings are- accepted. Missing, empty, or malformed geometries are skipped. The selected value- column supplies the scalar; polygon boundaries do not clip the resulting contours.--Duplicate measurements at the same position are averaged; values remain in their-original units. Both column modes use the following surface settings:--- **Auto** (default): preserves supported regular grids, including missing cells. If- the coordinates cannot form a supported grid, it interpolates scattered points.- Quantized scattered coordinates can resemble an incomplete grid; choose- **Scattered points** explicitly when those gaps should be interpolated.-- **Regular grid**: requires regularly spaced coordinates with at least two distinct- coordinates per axis. Positions describe sample centers. Blank/nonfinite values,- filtered-out samples, and missing cells remain holes, even after smoothing. A- completely absent row or column can be inferred when other samples establish spacing.-- **Scattered points**: requires at least three distinct, non-collinear samples with- finite values. Linear interpolation over Delaunay triangles creates a regular- surface before smoothing and contour generation. It uses a regional projection- with longitude scaled at the samples' central latitude. Cells outside the convex- hull of valid samples stay empty. Null/nonfinite values and filtered-out samples- are omitted; interpolation can bridge gaps between remaining points inside the hull.- Filtering boundary points can therefore shrink the surface. No distance cutoff,- barrier, or uncertainty model is applied across large unsampled gaps.--Polygon filters select source samples before smoothing and contour generation. Scalar-samples use their longitude/latitude; GeoJSON rows use the representative points described-above. Filters affect only their selected layers, including when layers share a dataset.-Regular grids retain rejected samples as holes; scattered inputs interpolate only retained-samples. Polygon filters do not clip the generated contours, so interpolation may bridge-excluded areas within the remaining samples' convex hull. Inverting, disabling, or clearing-the filter follows the same behavior as other layers.+ accepted. Missing, empty, or malformed geometries are skipped. Polygon boundaries do+ not clip the resulting contours.++All points use the same aggregation; there is no regular-grid/scattered-points choice.+Points are assigned to the nearest cell center on a grid anchored at the westernmost+longitude and northernmost latitude. Cell size is derived from the valid retained samples'+bounds and the selected maximum axis resolution, correcting longitude spacing at the region's central latitude. The longer+axis uses the selected number of cells; the shorter axis scales proportionally. Coincident+points use a 2×2 grid with one-meter spacing because they have no geographic extent.++- **With weights**: each occupied cell contains the arithmetic mean of its finite numeric+ weights. Null/nonfinite weights are skipped, including in the mean's denominator.+ Zero and negative weights are valid. If all weights are missing, no contours are drawn.+- **Without weights**: every valid point contributes one count, including repeated+ coordinates. Clearing the weight selection switches to this density calculation.+- **Empty cells**: contain zero and participate in smoothing. This can pull weighted values+ toward zero in sparse areas. Smoothing zero displays the unsmoothed cell means or counts.++Numeric and polygon filters select observations before aggregation. GeoJSON rows use+representative points as described above. Filters affect only their selected layers,+including when layers share a dataset. Removing points changes cell means/counts and may+change the grid's extent and alignment. Polygon filters do not clip the generated contours;+smoothing can extend into cells with no retained observations. Inverting, disabling, or+clearing a filter follows the same behavior as other layers.++Existing contour maps retain their selected value column as the weight and retain their+style settings. They use the new cell aggregation, so contour geometry and automatic levels+can change. Saved Input type, Interpolation resolution, and kilometer Cell size settings+no longer affect the surface; maps without Grid resolution use the default of 64 cells.## Controls-- **Color by level**: off uses the plain color (the default). Turn on to choose a- standard or custom palette, including reversed palettes. Colors run from the- lowest to highest generated contour value, independent of Invert. Palette stops+- **Weight**: select a numeric column for cell averages, or leave empty for point counts.+ The tooltip beside the label explains both choices.+- **Color by level**: enabled by default with the first blue/teal-to-red palette,+ **Uber Viz Diverging**. Choose a standard or custom palette, including reversed palettes,+ or turn it off to use a plain color. Colors run from the+ lowest to highest generated contour value, independent of the saved fill direction. Palette stopsare interpolated to the number of levels, so each level has its own sampled color.Both fills and outlines use these colors; translucent nested fills blend wherethey overlap. Switching modes preserves both the plain color and selected palette.-- **Input type**: Auto, Regular grid, or Scattered points, as described above.-- **Interpolation resolution**: 32–256 samples along the longer projected axis- (default 192). Higher resolution gives finer contour geometry, not more measured- detail. Applies only when interpolating; regular grids keep their native resolution.-- **Smoothing**: Gaussian standard deviation in grid cells; zero preserves the input.- Smoothing changes the scalar field, so use it deliberately for measured quantities.+- **Grid resolution**: 32–256 cells along the longer geographic axis+ (default 64). Cell size adapts to the data bounds, so small datasets also use the+ selected resolution. Higher resolution gives smaller cells; lower resolution combines+ more observations. Each axis is capped at 256 cells. Changing the dataset extent or+ filtering boundary points changes physical cell size and can change means/counts.+- **Smoothing**: Gaussian standard deviation in grid cells; zero preserves the cell means+ or counts. Smoothing changes values, not just the visual outline. Empty cells contribute+ zero. The default is 3 cells.- **Number of levels**: 2–20 equally spaced thresholds. Automatic levels exclude thefield's extrema to avoid outlining the entire rectangular extent. Numericallyconstant surfaces are omitted; roundoff from smoothing or interpolation does not@@ -89,17 +95,20 @@ the filter follows the same behavior as other layers.- **Custom level range**: minimum and maximum thresholds, inclusive, in the originalvalue units, selected with a two-handle range slider and read-only endpoint labels.Slider bounds use the exact finite minimum and maximum of the selected value- column across the dataset and refresh when the dataset or column changes. Nulls- and nonfinite values are ignored; empty or constant columns cannot supply a slider range.+ column across the dataset and refresh when the dataset or column changes. In density+ mode the bounds come from the current unsmoothed cell counts. Nulls and nonfinite+ weights are ignored; empty or constant ranges cannot supply a slider range.Enabling custom levels initializes both handles to the column bounds. When datachanges, thresholds are kept within the new bounds; a disjoint selection resetsto the full range. There is no manual-input fallback. These controls choose levels;they do not normalize or clamp the data.-- **Invert**: off fills regions where value ≤ threshold (the default). Turn on to- fill regions where value ≥ threshold. Existing maps keep their saved direction.- **Fill / outline**: enable independently. Each translucent filled region overlapsthe larger regions below it, so opacity builds toward nested interiors. Outlines- are rendered afterward, with brighter lines for inner regions.+ are rendered afterward, with brighter lines for inner regions. Fill opacity ranges+ from 0 to 1, with a default of 0.3.++New contours fill regions where value ≥ threshold, enclosing peaks in weights or point+counts. There is no Invert control. Existing maps retain their explicitly saved fill direction.Contours keep the same geographic shape and thresholds while panning or zooming.Hover shows the value threshold. Settings are saved with the map.@@ -120,10 +129,8 @@ filtering, smoothing, or level changes and clears when no contours are generated## Prototype limits-This version supports regional 2D data, native grids up to 512 samples per axis, and-scattered-point interpolation onto grids up to 256 samples per axis. It does not support-globe mode, antimeridian-crossing data, routing, or dedicated contour export.-Geometry is calculated on the CPU when data or contour-settings change. Color, opacity, camera movement, and outline width do not regenerate it.-Smoothing is specified in cells, so its physical footprint depends on grid spacing or-interpolation resolution. The convex-hull boundary is approximated at grid resolution.+This version supports regional 2D data and aggregation grids of up to 65,536 cells.+It does not support globe mode, antimeridian-crossing data, routing, or dedicated contour+export. Geometry is calculated on the CPU when data or contour settings change.+Color, opacity, camera movement, and outline width do not regenerate it.+Smoothing is specified in cells, so its physical footprint depends on cell size.diff --git a/examples/demo-app/src/data/sample-contour-data.ts b/examples/demo-app/src/data/sample-contour-data.tsindex b035d1f52..babb1ec80 100644--- a/examples/demo-app/src/data/sample-contour-data.ts+++ b/examples/demo-app/src/data/sample-contour-data.ts@@ -17,11 +17,12 @@ export function createContourSamples(scattered = false) {strength: 7 + random() * 21}));const samples: {longitude: number; latitude: number; value: number}[] = [];- const size = scattered ? 65 : 201;+ // Both layouts need enough observations to populate the aggregation cells.+ const size = 201;for (let row = 0; row < size; row++) {for (let col = 0; col < size; col++) {- const x = scattered ? (col + (random() - 0.5) * 0.8) / 32 - 1 : col / 100 - 1;- const y = scattered ? (row + (random() - 0.5) * 0.8) / 32 - 1 : row / 100 - 1;+ const x = (col + (scattered ? (random() - 0.5) * 0.8 : 0)) / 100 - 1;+ const y = (row + (scattered ? (random() - 0.5) * 0.8 : 0)) / 100 - 1;const warpedX = x + 0.07 * Math.sin(y * 13) + 0.03 * Math.sin(y * 27);const warpedY = y + 0.05 * Math.cos(x * 17);let surface = 65 * Math.exp(-(warpedX ** 2 / 0.22 + warpedY ** 2 / 0.13));@@ -64,6 +65,7 @@ export const contourConfig = {visConfig: {opacity: 0.85,smoothing: 1.5,+ gridResolution: 192,levels: 8,below: true,customRange: true,diff --git a/src/components/src/map/map-legend.tsx b/src/components/src/map/map-legend.tsxindex 0f961484c..b98805a86 100644--- a/src/components/src/map/map-legend.tsx+++ b/src/components/src/map/map-legend.tsx@@ -512,7 +512,8 @@ function ContourLegendFactory(LegendRow: ReturnType<typeof LegendRowFactory>) {const listId = useId();const [isExpanded, setIsExpanded] = useState(false);const levels = layer.getContourLegend();- const field = String(layer.config.columns.value.value);+ const fieldKey = layer.config.columns.value.value ?? null;+ const field = fieldKey || intl.formatMessage({id: 'columns.contour.density'});const colorRange = layer.config.visConfig.colorRange;const customLabels = colorRange?.colorLegends || {};const canEdit = !disableEdit && !isExport && Boolean(onLayerVisConfigChange);@@ -555,7 +556,7 @@ function ContourLegendFactory(LegendRow: ReturnType<typeof LegendRowFactory>) {maximumSignificantDigits: 12})}`;// Labels follow the scalar threshold, not a color that can change or repeat.- const key = JSON.stringify([field, below, threshold]);+ const key = JSON.stringify([fieldKey, below, threshold]);const label = customLabels[key] ?? defaultLabel;return (<divdiff --git a/src/components/src/side-panel/layer-panel/layer-configurator.tsx b/src/components/src/side-panel/layer-panel/layer-configurator.tsxindex aefdabc9b..30b9372de 100644--- a/src/components/src/side-panel/layer-panel/layer-configurator.tsx+++ b/src/components/src/side-panel/layer-panel/layer-configurator.tsx@@ -9,6 +9,7 @@ import styled from 'styled-components';import {createSelector} from 'reselect';import ItemSelector from '../../common/item-selector/item-selector';+import FieldSelectorFactory from '../../common/field-selector';import InfoHelperFactory from '../../common/info-helper';import {Input,@@ -17,7 +18,6 @@ import {PanelLabelWrapper,SidePanelSection} from '../../common/styled-components';-import Switch from '../../common/switch';import SourceDataSelectorFactory from '../common/source-data-selector';import AggrScaleSelectorFactory from './aggr-scale-selector';@@ -183,11 +183,6 @@ const StyledLayerVisualConfigurator = styled.div.attrs({color: ${props => props.theme.textColor};font-size: ${props => props.theme.sliderInputFontSize};}-- .contour-invert-switch {- display: flex;- justify-content: space-between;- }`;// Keep keyboard behavior scoped to the optional point effects.@@ -518,7 +513,8 @@ LayerConfiguratorFactory.deps = [RasterTileLayerConfiguratorFactory,ScenegraphModelSelectorFactory,RangeSliderFactory,- InfoHelperFactory+ InfoHelperFactory,+ FieldSelectorFactory];export default function LayerConfiguratorFactory(@@ -538,7 +534,8 @@ export default function LayerConfiguratorFactory(RasterTileLayerConfigurator: ReturnType<typeof RasterTileLayerConfiguratorFactory>,ScenegraphModelSelector: ReturnType<typeof ScenegraphModelSelectorFactory>,RangeSlider: ReturnType<typeof RangeSliderFactory>,- InfoHelper: ReturnType<typeof InfoHelperFactory>+ InfoHelper: ReturnType<typeof InfoHelperFactory>,+ FieldSelector: ReturnType<typeof FieldSelectorFactory>): React.ComponentType<LayerConfiguratorProps> {const AggregationTextLabelPanel: React.FC<Omit<React.ComponentProps<typeof TextLabelPanel>, 'fields'>@@ -2254,19 +2251,37 @@ export default function LayerConfiguratorFactory(_renderContourLayerConfig({layer, dataset, visConfiguratorProps, layerConfiguratorProps}) {const {visConfigSettings: settings, config} = layer;const valueColumn = config.columns.value.value;- const valueRange = this._contourValueRange(- dataset?.dataContainer,- dataset?.getColumnField(valueColumn)?.valueAccessor,- dataset?.dataRevision- );+ let valueRange = layer.meta.contourDomain;+ if (valueColumn) {+ const columnRange = this._contourValueRange(+ dataset?.dataContainer,+ dataset?.getColumnField(valueColumn)?.valueAccessor,+ dataset?.dataRevision+ );+ // Empty cells contribute zero, so the surface can extend beyond the raw weights.+ valueRange =+ columnRange && valueRange+ ? [Math.min(columnRange[0], valueRange[0]), Math.max(columnRange[1], valueRange[1])]+ : columnRange;+ }const hasValueRange = valueRange && valueRange[0] < valueRange[1];- const inputModes = [- {id: 'auto', label: 'Auto'},- {id: 'grid', label: 'Regular grid'},- {id: 'points', label: 'Scattered points'}- ];return (<StyledLayerVisualConfigurator>+ <LayerConfigGroup+ label="columns.contour.weight"+ description="layerVisConfigs.contour.weightDescription"+ >+ <FieldSelector+ fields={layerConfiguratorProps.fields}+ filterFieldTypes={['integer', 'real']}+ value={valueColumn}+ placeholder="columns.contour.density"+ erasable+ onSelect={field =>+ layerConfiguratorProps.onChange({columns: layer.assignColumn('value', field)})+ }+ />+ </LayerConfigGroup><LayerConfigGroup label="layer.color" collapsible><VisConfigSwitch {...settings.colorByLevel} {...visConfiguratorProps} />{config.visConfig.colorByLevel ? (@@ -2295,18 +2310,6 @@ export default function LayerConfiguratorFactory(><VisConfigSlider {...settings.levels} {...visConfiguratorProps} /><ConfigGroupCollapsibleContent>- <SidePanelSection>- <div className="contour-invert-switch">- <PanelLabel htmlFor={`${layer.id}-invert-switch`}>- <FormattedMessage id="layerVisConfigs.contour.invert" />- </PanelLabel>- <Switch- id={`${layer.id}-invert-switch`}- checked={!config.visConfig.below}- onChange={() => visConfiguratorProps.onChange({below: !config.visConfig.below})}- />- </div>- </SidePanelSection><VisConfigSwitch{...settings.customRange}{...visConfiguratorProps}@@ -2336,23 +2339,7 @@ export default function LayerConfiguratorFactory(<LayerConfigGroup label="layerVisConfigs.contour.surface" collapsible><VisConfigSlider {...settings.smoothing} {...visConfiguratorProps} /><ConfigGroupCollapsibleContent>- <SidePanelSection>- <PanelLabel>- <FormattedMessage id={settings.inputMode.label} />- </PanelLabel>- <ItemSelector- options={inputModes}- selectedItems={inputModes.find(mode => mode.id === config.visConfig.inputMode)}- displayOption="label"- getOptionValue="id"- multiSelect={false}- searchable={false}- onChange={inputMode => visConfiguratorProps.onChange({inputMode})}- />- </SidePanelSection>- {config.visConfig.inputMode !== 'grid' ? (- <VisConfigSlider {...settings.interpolationResolution} {...visConfiguratorProps} />- ) : null}+ <VisConfigSlider {...settings.gridResolution} {...visConfiguratorProps} /></ConfigGroupCollapsibleContent></LayerConfigGroup><LayerConfigGroup@@ -2528,6 +2515,13 @@ export default function LayerConfiguratorFactory(? datasets[layer.config.dataId]: {};const {config} = layer;+ const sourceColumnModes =+ layer.type === 'contour'+ ? layer.supportedColumnModes?.map(mode => ({+ ...mode,+ optionalColumns: mode.optionalColumns?.filter(key => key !== 'value')+ })) ?? null+ : layer.supportedColumnModes;const visConfiguratorProps = getVisConfiguratorProps(this.props);const layerConfiguratorProps = getLayerConfiguratorProps(this.props);@@ -2570,7 +2564,7 @@ export default function LayerConfiguratorFactory(/><LayerColumnModeConfiglayer={layer}- supportedColumnModes={layer.supportedColumnModes}+ supportedColumnModes={sourceColumnModes}id={layer.id}layerConfig={layer.config}// TODO figure out handler type. String or return type of layer.layerInfoModal ?diff --git a/src/layers/src/contour-layer/contour-layer.spec.ts b/src/layers/src/contour-layer/contour-layer.spec.tsindex 121677ae2..9a6750577 100644--- a/src/layers/src/contour-layer/contour-layer.spec.ts+++ b/src/layers/src/contour-layer/contour-layer.spec.ts@@ -2,11 +2,12 @@// Copyright contributors to the kepler.gl projectimport {KeplerTable, getGpuFilterProps, assignGpuChannels} from '@kepler.gl/table';-import {EDITOR_AVAILABLE_LAYERS, FILTER_TYPES} from '@kepler.gl/constants';-import {generatePolygonFilter, getDefaultFilter} from '@kepler.gl/utils';+import {EDITOR_AVAILABLE_LAYERS, FILTER_TYPES, KEPLER_COLOR_PALETTES} from '@kepler.gl/constants';+import {colorMaybeToRGB, generatePolygonFilter, getDefaultFilter} from '@kepler.gl/utils';import {PickingInfo} from '@deck.gl/core';import {Int64, Uint64, Table, vectorFromArray} from 'apache-arrow';import {processCsvData} from '@kepler.gl/processors';+import booleanWithin from '@turf/boolean-within';import ContourLayer from './contour-layer';import Layer from '../base-layer';import {LayerClasses} from '../index';@@ -20,7 +21,8 @@ import {calculateLayerData,INITIAL_VIS_STATE,layerTypeChangeUpdater,- removeLayerUpdater+ removeLayerUpdater,+ validateLayerWithData} from '@kepler.gl/reducers';import {StateWFiles} from 'test/helpers/mock-state';import {messages} from '@kepler.gl/localization';@@ -61,10 +63,15 @@ async function setup(scatteredRows?: number[][]) {columns: {lat: column('latitude'), lng: column('longitude'), value: column('value')}});layer.updateLayerVisConfig({+ // Existing renderer fixtures exercise saved lower-value, plain-color contours explicitly.+ below: true,+ colorByLevel: false,+ fillOpacity: 0.075,customRange: true,minimum: 2,maximum: 6,smoothing: 0,+ gridResolution: scatteredRows ? 3 : 9,levels: 3,filled: true,stroked: true@@ -88,10 +95,10 @@ function calculateContourLayerData(layer: ContourLayer, datasets) {test.each([{- name: 'irregular grid',+ name: 'invalid grid resolution',scattered: true,- invalid: {inputMode: 'grid'},- message: /regularly spaced/+ invalid: {gridResolution: 0},+ message: /grid resolution/},{name: 'reversed range', scattered: false, invalid: {minimum: 9, maximum: 3}, message: /minimum/},{name: 'constant range', scattered: false, invalid: {minimum: 4, maximum: 4}, message: /minimum/},@@ -105,7 +112,7 @@ test.each(['retains $name validation errors through layer calculation and recovers',async ({scattered, invalid, message}) => {const {layer, datasets} = await setup(scattered ? scatteredSamples : undefined);- layer.updateLayerVisConfig({minimum: 4, maximum: 8, interpolationResolution: 32});+ layer.updateLayerVisConfig({minimum: 4, maximum: 8, gridResolution: 3});expect(calculateContourLayerData(layer, datasets).layerData.data).toHaveLength(3);expect(layer.getContourLegend()).toHaveLength(3);layer.updateLayerVisConfig(invalid);@@ -117,7 +124,7 @@ test.each([expect(result.layerData).toEqual({});expect(layer.getContourLegend()).toEqual([]);}- layer.updateLayerVisConfig({inputMode: 'auto', minimum: 4, maximum: 8});+ layer.updateLayerVisConfig({gridResolution: 3, minimum: 4, maximum: 8});const recovered = calculateContourLayerData(layer, datasets);expect(recovered.layer.isValid).toBe(true);expect(recovered.layer.errorMessage).toBeNull();@@ -159,16 +166,68 @@ function setupGeojson(}});layer.updateLayerVisConfig({+ below: true,+ colorByLevel: false,+ fillOpacity: 0.075,customRange: true,minimum: 4,maximum: 8,levels: 3,smoothing: 0,- interpolationResolution: 64+ gridResolution: 3});return {layer, dataset, datasets: {[dataset.id]: dataset}};}+test.each([false, true])('new contours enclose peaks by default (weighted: %s)', async weighted => {+ const {+ layer: reference,+ dataset,+ datasets+ } = await setup([+ [0, 0, 1],+ [0.18, 0, 1],+ [0, 0.18, 1],+ [0.18, 0.18, 1],+ // Keep the peak away from a cell boundary; this checks fill direction, not bin placement.+ ...Array.from({length: 100}, () => [0.08, 0.08, 100])+ ]);+ const {lat, lng, value} = reference.config.columns;+ const layer = new ContourLayer({+ dataId: dataset.id,+ columns: {lat, lng, ...(weighted ? {value} : {})}+ });+ const {data} = layer.formatLayerData(datasets);+ expect(data).toHaveLength(layer.config.visConfig.levels);+ const contains = (feature, coordinates) =>+ feature.geometry.coordinates.some(polygon =>+ booleanWithin({type: 'Point', coordinates}, {type: 'Polygon', coordinates: polygon})+ );+ for (const feature of data) {+ expect(feature.properties.below).toBe(false);+ expect(contains(feature, [0.08, 0.08])).toBe(true);+ }+ expect(contains(data[data.length - 1], [0.17, 0.01])).toBe(false);+ expect(layer.config.visConfig.colorByLevel).toBe(true);+ expect(layer.config.visConfig.gridResolution).toBe(64);+ expect(layer.config.visConfig.smoothing).toBe(3);+ expect(layer.config.visConfig.fillOpacity).toBe(0.3);+ expect(layer.config.visConfig.colorRange.name).toBe(KEPLER_COLOR_PALETTES[0].name);+ const {colors} = layer.config.visConfig.colorRange;+ const passes = renderContourPasses(layer, dataset, {data});+ const getFillColor = passes[0].props.getFillColor;+ if (typeof getFillColor !== 'function') throw new Error('Expected colors for each contour level');+ for (const [index, color] of [+ [0, colors[0]],+ [data.length - 1, colors[colors.length - 1]]+ ] as const) {+ expect(getFillColor(data[index], {index, data, target: []})).toEqual([+ ...colorMaybeToRGB(color)!,+ Math.round(255 * layer.config.visConfig.fillOpacity)+ ]);+ }+});+test('registers the layer and renders both passes without recomputing on camera movement', async () => {const {layer, dataset, datasets} = await setup();expect(LayerClasses.contour).toBe(ContourLayer);@@ -760,6 +819,30 @@ test('edits and resets contour labels by threshold even when levels have the sam});});+test.each(['point', 'grid'])(+ 'changing a default %s layer to Contour selects the first palette',+ async type => {+ const {dataset, datasets, layer: reference} = await setup();+ const {lat, lng} = reference.config.columns;+ const layer = new LayerClasses[type]({dataId: dataset.id, columns: {lat, lng}});+ const state = {+ ...INITIAL_VIS_STATE,+ datasets,+ layers: [layer],+ layerData: [{}],+ layerOrder: [layer.id]+ };+ const result = layerTypeChangeUpdater(state, {oldLayer: layer, newType: 'contour'});+ const converted = result.layers[0];+ const {colorRange} = converted.config.visConfig;+ expect(colorRange.name).toBe(KEPLER_COLOR_PALETTES[0].name);+ expect(colorRange.colors).toEqual(KEPLER_COLOR_PALETTES[0].colors(colorRange.colors.length));+ expect(converted.config.visConfig.colorByLevel).toBe(true);+ expect(converted.config.visConfig.gridResolution).toBe(64);+ expect(converted.config.visConfig.smoothing).toBe(3);+ }+);+test.each(['point', 'grid'])('changing from Contour to %s removes threshold labels while preserving the palette and color labels',async newType => {@@ -874,15 +957,36 @@ test('keeps legend levels in sync with auto ranges, filters, and invalid or emptexpect(layer.getContourLegend()).toEqual([]);});-test('filtered samples become holes and clearing the filter restores them', async () => {- const {layer, dataset, datasets} = await setup();+test('applies the selected maximum axis resolution when averaging nearby observations', async () => {+ const {layer, datasets} = await setup([+ [0, 0, 10],+ [0.0004, 0.0004, 30],+ [0.03, 0.03, 8]+ ]);+ layer.updateLayerVisConfig({gridResolution: 32});+ layer.formatLayerData(datasets);+ expect(layer.meta.contourDomain).toEqual([0, 20]);+ layer.updateLayerVisConfig({gridResolution: 256});+ layer.formatLayerData(datasets);+ expect(layer.meta.contourDomain).toEqual([0, 30]);+});++test('filters observations before averaging and restores them when the filter clears', async () => {+ const {layer, dataset, datasets} = await setup([+ [0, 0, 10],+ [0.0001, 0.0001, 30],+ [0.03, 0.03, 8]+ ]);+ layer.updateLayerVisConfig({gridResolution: 32, minimum: 5, maximum: 15, below: false});const all = dataset.filteredIndex;- dataset.filteredIndex = all.filter(index => index !== 40);+ const original = layer.formatLayerData(datasets);+ expect(layer.meta.contourDomain).toEqual([0, 20]);+ dataset.filteredIndex = [0, 2];const filtered = layer.formatLayerData(datasets);- expect(filtered.data.every(f => f.geometry.coordinates[0].length === 2)).toBe(true);+ expect(layer.meta.contourDomain).toEqual([0, 10]);+ expect(filtered.data.map(feature => feature.properties.threshold)).toEqual([5, 10]);dataset.filteredIndex = all;- const restored = layer.formatLayerData(datasets);- expect(restored.data.every(f => f.geometry.coordinates[0].length === 1)).toBe(true);+ expect(layer.formatLayerData(datasets)).toEqual(original);});function contourPolygonFilter(layer: ContourLayer, bounds: number[], inverted = false) {@@ -909,9 +1013,15 @@ function contourPolygonFilter(layer: ContourLayer, bounds: number[], inverted =};}-test('polygon filters preserve grid holes, isolate layers, and restore on disable or clear', async () => {- const {layer, dataset, datasets} = await setup();- layer.updateLayerVisConfig({inputMode: 'grid'});+test('polygon filters exclude observations, isolate layers, and restore on disable or clear', async () => {+ const {layer, dataset, datasets} = await setup(+ Array.from({length: 81}, (_, i) => {+ const x = i % 9;+ const y = Math.floor(i / 9);+ return [x, y, i === 40 ? 100 : (x - 4) ** 2 + (y - 4) ** 2];+ })+ );+ layer.updateLayerVisConfig({gridResolution: 9});const other = new ContourLayer({dataId: dataset.id, columns: layer.config.columns});other.updateLayerVisConfig(layer.config.visConfig);const point = new LayerClasses.point({dataId: dataset.id, columns: layer.config.columns});@@ -929,7 +1039,8 @@ test('polygon filters preserve grid holes, isolate layers, and restore on disablexpect(dataset.filteredIndexByLayer[layer.id]).toEqual(all.filter(index => index !== 40));const filtered = calculateContourLayerData(layer, datasets).layerData.data;expect(filtered).toHaveLength(3);- expect(filtered.every(feature => feature.geometry.coordinates[0].length === 2)).toBe(true);+ expect(original.every(feature => feature.geometry.coordinates[0].length === 2)).toBe(true);+ expect(filtered.every(feature => feature.geometry.coordinates[0].length === 1)).toBe(true);expect(other.formatLayerData(datasets).data).toEqual(original);expect(calculateLayerData(point, pointState).layerData.data).toEqual(originalPoint);@@ -967,7 +1078,8 @@ test.each([false, true])('combines polygon filtering with numeric filters (GPU %dataset.dataContainer.mapIndex(({index}) => {const [longitude, latitude, value] = dataset.dataContainer.rowAsArray(index);return {longitude, latitude, value: index !== 40 && value <= 4 ? value : null};- })+ }),+ layer.config.visConfig.gridResolution);const expected = generateContours(grid, {smoothing: 0, levels: 3, below: true, domain: [2, 6]});expect(expected.length).toBeGreaterThan(0);@@ -975,7 +1087,7 @@ test.each([false, true])('combines polygon filtering with numeric filters (GPU %});test.each(['grid', 'geojson'])(- 'polygon filters %s source samples before scattered interpolation and smoothing',+ 'polygon filters %s source samples before aggregation and smoothing',async columnMode => {const rows = scatteredSamples.map((row, index) => [row[0],@@ -995,32 +1107,25 @@ test.each(['grid', 'geojson'])(// Apply before the first render, so filtering cannot depend on cached geometry.dataset.filterTable([filter], [layer]);expect(dataset.filteredIndexByLayer[layer.id]).toEqual([0, 2, 3]);- for (const inputMode of ['auto', 'points'] as const) {- layer.updateLayerVisConfig({- inputMode,- minimum: 4,- maximum: 8,- interpolationResolution: 32,- smoothing: 1.5- });- const expectedGrid = buildContourGrid(- rows.map(([longitude, latitude, value], index) => ({+ layer.updateLayerVisConfig({minimum: 4, maximum: 8, gridResolution: 3, smoothing: 1.5});+ const expectedGrid = buildContourGrid(+ rows+ .filter((_, index) => index !== 1)+ .map(([longitude, latitude, value]) => ({longitude,latitude,- value: index === 1 ? null : value+ value})),- inputMode,- 32- );- const expected = generateContours(expectedGrid, {- smoothing: 1.5,- levels: 3,- below: true,- domain: [4, 8]- });- expect(expected.length).toBeGreaterThan(0);- expect(calculateContourLayerData(layer, datasets).layerData.data).toEqual(expected);- }+ 3+ );+ const expected = generateContours(expectedGrid, {+ smoothing: 1.5,+ levels: 3,+ below: true,+ domain: [4, 8]+ });+ expect(expected.length).toBeGreaterThan(0);+ expect(calculateContourLayerData(layer, datasets).layerData.data).toEqual(expected);dataset.filterTable([contourPolygonFilter(layer, [20, 20, 21, 21])], [layer]);expect(calculateContourLayerData(layer, datasets).layerData.data).toEqual([]);expect(layer.isValid).toBe(true);@@ -1037,10 +1142,9 @@ test.each([Int64, Uint64])(]);const {layer} = reference;layer.updateLayerVisConfig({- inputMode: 'points',minimum: 4,maximum: 8,- interpolationResolution: 32+ gridResolution: 3});const expected = layer.formatLayerData(reference.datasets).data;const arrowVector = (values: (number | null)[]) =>@@ -1082,26 +1186,47 @@ test('reports invalid settings and recovers after correcting them', async () =>]);});-test('applies numeric GPU filters before contouring even at a zero-valued range', async () => {- const {layer, dataset, datasets} = await setup();+test('applies numeric GPU filters to density even at a zero-valued range', async () => {+ const {layer, dataset, datasets} = await setup([+ [0, 0, 3],+ [0, 0, 7],+ [0, 0, 9]+ ]);+ layer.updateLayerConfig({columns: {...layer.config.columns, value: {value: null, fieldIdx: -1}}});+ layer.updateLayerVisConfig({minimum: 1, maximum: 3, below: false});+ layer.formatLayerData(datasets);+ expect(layer.meta.contourDomain).toEqual([0, 3]);dataset.gpuFilter = {...dataset.gpuFilter,filterValueUpdateTriggers: {test: true},filterRange: [[0, 0]],- filterValueAccessor: () => () => d => [d.index === 40 ? 1 : 0]+ filterValueAccessor: () => () => d => [d.index === 1 ? 1 : 0]} as any;- expect(- layer.formatLayerData(datasets).data.every(f => f.geometry.coordinates[0].length === 2)- ).toBe(true);+ expect(layer.formatLayerData(datasets).data.map(feature => feature.properties.threshold)).toEqual(+ [1, 2]+ );+ expect(layer.meta.contourDomain).toEqual([0, 2]);});-test.each(['grid', 'geojson'])(- 'saves and reloads %s contour settings and columns through the map schema',- async columnMode => {- const {layer} = columnMode === 'geojson' ? setupGeojson() : await setup();+test.each(+ [+ {columnMode: 'grid', weighted: true},+ {columnMode: 'grid', weighted: false},+ {columnMode: 'geojson', weighted: true},+ {columnMode: 'geojson', weighted: false}+ ].flatMap(config => [true, false].map(below => ({...config, below})))+)(+ 'saves and reloads $columnMode contours (weighted: $weighted, below: $below) through the map schema',+ async ({columnMode, weighted, below}) => {+ const {layer, dataset, datasets} = columnMode === 'geojson' ? setupGeojson() : await setup();+ if (!weighted) {+ layer.updateLayerConfig({+ columns: {...layer.config.columns, value: {value: null, fieldIdx: -1, optional: true}}+ });+ }layer.updateLayerVisConfig({- inputMode: 'points',- interpolationResolution: 128,+ below,+ gridResolution: 128,colorByLevel: true,colorRange: {...layer.config.visConfig.colorRange,@@ -1120,8 +1245,10 @@ test.each(['grid', 'geojson'])(expect(restored.config.columnMode).toBe(columnMode);expect(restored.config.visConfig).toEqual(layer.config.visConfig);// Saved configs retain column names; field indices are resolved against the loaded table.- expect(restored.config.columns.value).toBe('value');+ expect(restored.config.columns.value).toBe(weighted ? 'value' : undefined);if (columnMode === 'geojson') expect(restored.config.columns.geojson).toBe('geometry');+ const loaded = validateLayerWithData(dataset, restored, LayerClasses)!;+ expect(loaded.formatLayerData(datasets)).toEqual(layer.formatLayerData(datasets));});@@ -1195,13 +1322,13 @@ describe('GeoJSON scalar inputs', () => {});- test('requires geometry and value columns only in GeoJSON mode', () => {+ test('requires only geometry in GeoJSON mode', () => {const {layer, datasets} = setupGeojson();expect(layer.hasAllColumns()).toBe(true);layer.updateLayerConfig({columnMode: 'grid'});expect(layer.hasAllColumns()).toBe(false);layer.updateLayerConfig({columnMode: 'geojson'});- for (const name of ['geojson', 'value']) {+ for (const name of ['geojson']) {const original = layer.config.columns[name];layer.config.columns[name] = {value: null, fieldIdx: -1};expect(layer.hasAllColumns()).toBe(false);@@ -1235,71 +1362,156 @@ describe('GeoJSON scalar inputs', () => {}});- test.each(['cpu', 'gpu'])(- 'applies %s filters before interpolating GeoJSON samples',- filterType => {- const {layer, dataset, datasets} = setupGeojson();- expect(layer.formatLayerData(datasets).data).toHaveLength(3);- if (filterType === 'cpu') {- dataset.filteredIndex = [0, 1, 3];- } else {- dataset.gpuFilter = {- ...getGpuFilterProps([], dataset.id, dataset.fields),- filterValueUpdateTriggers: {test: true},- filterRange: [[0, 0]],- filterValueAccessor: () => () => d => [d.index === 2 ? 1 : 0]- } as any;- }- expect(layer.formatLayerData(datasets).data.length).toBeGreaterThan(0);- expect(layer.meta.bounds[3]).toBeCloseTo(0.625);+ test.each(['cpu', 'gpu'])('applies %s filters before aggregating GeoJSON samples', filterType => {+ const {layer, dataset, datasets} = setupGeojson();+ expect(layer.formatLayerData(datasets).data).toHaveLength(3);+ if (filterType === 'cpu') {+ dataset.filteredIndex = [0, 1, 3];+ } else {+ dataset.gpuFilter = {+ ...getGpuFilterProps([], dataset.id, dataset.fields),+ filterValueUpdateTriggers: {test: true},+ filterRange: [[0, 0]],+ filterValueAccessor: () => () => d => [d.index === 2 ? 1 : 0]+ } as any;}- );+ expect(layer.formatLayerData(datasets).data.length).toBeGreaterThan(0);+ expect(layer.meta.bounds[3]).toBeCloseTo(0.625);+ });- test('retains grid holes when GeoJSON points form a regular lattice', () => {- const rows = Array.from({length: 81}, (_, i) => {- const x = i % 9;- const y = Math.floor(i / 9);- return [pointGeometry(x, y), i === 40 ? null : 1];+ test('uses point counts when the GeoJSON weight column is cleared', () => {+ const {layer, datasets} = setupGeojson([+ [pointGeometry(0, 0), 10],+ [pointGeometry(0, 0), 20]+ ]);+ layer.updateLayerConfig({+ columns: {...layer.config.columns, value: {value: null, fieldIdx: -1}}});- const {layer, datasets} = setupGeojson(rows);- layer.updateLayerVisConfig({smoothing: 2});- const result = layer.formatLayerData(datasets);- expect(result.data).toHaveLength(3);- expect(result.data.every(f => f.geometry.coordinates[0].length === 2)).toBe(true);+ layer.updateLayerVisConfig({minimum: 1, maximum: 2, levels: 2, below: false});+ expect(layer.hasAllColumns()).toBe(true);+ expect(+ layer.formatLayerData(datasets).data.map(feature => feature.properties.threshold)+ ).toEqual([1, 2]);+ expect(layer.meta.contourDomain).toEqual([0, 2]);});});-test('interpolates scattered data and recomputes its support when samples are filtered', async () => {+test('uses one aggregation path for regular and irregular points regardless of legacy input modes', async () => {+ const {layer, datasets} = await setup(scatteredSamples);+ layer.updateLayerVisConfig({minimum: 4, maximum: 8});+ const expected = layer.formatLayerData(datasets);+ expect(expected.data).toHaveLength(3);+ for (const inputMode of ['auto', 'grid', 'points']) {+ layer.updateLayerVisConfig({inputMode});+ expect(layer.formatLayerData(datasets)).toEqual(expected);+ }+});++test('switches between optional weights and density, including legend and hover values', async () => {const {layer, dataset, datasets} = await setup([- [0, 0, 3],- [2, 0, 7],- [0.7, 2, 10.4],- [1.1, 0.6, 7]+ [0, 0, 10],+ [0.0001, 0.0001, 30],+ [0.03, 0.03, 8]]);- layer.updateLayerVisConfig({minimum: 4, maximum: 8, interpolationResolution: 64});- expect(layer.formatLayerData(datasets).data).toHaveLength(3);- expect(layer.errorMessage).toBeNull();- expect(layer.meta.bounds[3]).toBeCloseTo(2);- const all = dataset.filteredIndex;- dataset.filteredIndex = [0, 1, 3];- expect(layer.formatLayerData(datasets).data.length).toBeGreaterThan(0);- expect(layer.meta.bounds[3]).toBeCloseTo(0.6);- dataset.filteredIndex = all;- layer.updateLayerVisConfig({inputMode: 'grid'});+ layer.updateLayerVisConfig({gridResolution: 32, minimum: 1, maximum: 2, levels: 2, below: false});+ layer.formatLayerData(datasets);+ expect(layer.meta.contourDomain).toEqual([0, 20]);+ const columns = layer.config.columns;+ layer.updateLayerConfig({+ columns: {...columns, value: {value: null, fieldIdx: -1, optional: true}}+ });+ expect(layer.hasAllColumns()).toBe(true);+ const data = layer.formatLayerData(datasets);+ expect(layer.meta.contourDomain).toEqual([0, 2]);+ expect(data.data.map(feature => feature.properties.threshold)).toEqual([1, 2]);+ expect(layer.getHoverData(data.data[0])?.fieldValues[0]).toEqual({+ labelMessage: 'columns.contour.density',+ value: 'Point count ≥ 1'+ });+ const view = renderLegend(layer);+ expect(view.getByRole('button', {name: 'Point count'})).toBeTruthy();+ expect(view.getAllByRole('listitem').map(item => item.textContent)).toEqual(['≥ 1', '≥ 2']);+ view.unmount();+ layer.updateLayerConfig({columns});+ layer.formatLayerData(datasets);+ expect(layer.meta.contourDomain).toEqual([0, 20]);+ dataset.filteredIndex = [];+ expect(layer.formatLayerData(datasets).data).toEqual([]);+ expect(layer.meta.contourDomain).toBeNull();+});++test('missing or invalid selected weights do not silently become density', async () => {+ const {layer, datasets} = await setup([+ [0, 0, NaN],+ [0.03, 0.03, Infinity]+ ]);+ expect(layer.formatLayerData(datasets).data).toEqual([]);+ layer.updateLayerConfig({+ columns: {...layer.config.columns, value: {value: 'missing', fieldIdx: -1}}+ });expect(calculateContourLayerData(layer, datasets).layerData).toEqual({});- expect(layer.errorMessage).toMatch(/regularly spaced/);- layer.updateLayerVisConfig({inputMode: 'points'});- expect(calculateContourLayerData(layer, datasets).layerData.data).toHaveLength(3);- expect(layer.errorMessage).toBeNull();- expect(layer.meta.bounds[3]).toBeCloseTo(2);+ expect(layer.errorMessage).toMatch(/numeric contour weight/);});+test.each(['grid', 'geojson'])(+ 'loading %s contours preserves a missing saved weight until explicitly cleared',+ async columnMode => {+ const {layer, dataset} =+ columnMode === 'geojson' ? setupGeojson() : await setup(scatteredSamples);+ layer.updateLayerVisConfig({customRange: false, below: false});+ const saved = SchemaManager.getConfigToSave({+ ...StateWFiles,+ visState: {...StateWFiles.visState, layers: [layer], layerOrder: [layer.id]}+ });+ const restored = SchemaManager.parseSavedConfig(saved)!.visState!.layers![0];+ const fields = dataset.fields.slice(0, -1);+ const missingWeightDataset = new KeplerTable({+ info: {id: dataset.id},+ color: [0, 0, 0]+ }).updateSchema({+ fields,+ rows: Array.from({length: dataset.dataContainer.numRows()}, (_, index) =>+ fields.map((_, fieldIdx) => dataset.dataContainer.valueAt(index, fieldIdx))+ )+ });+ const datasets = {[dataset.id]: missingWeightDataset};++ for (const options of [{}, {allowEmptyColumn: true}]) {+ const loaded = validateLayerWithData(+ missingWeightDataset,+ restored,+ LayerClasses,+ options+ ) as ContourLayer;+ expect(loaded.config.columns.value.value).toBe('value');+ expect(calculateContourLayerData(loaded, datasets).layerData).toEqual({});+ expect(loaded.isValid).toBe(false);+ expect(loaded.errorMessage).toMatch(/numeric contour weight/);++ loaded.updateLayerConfig({+ columns: {+ ...loaded.config.columns,+ value: {...loaded.config.columns.value, value: null, fieldIdx: -1}+ }+ });+ const density = calculateContourLayerData(loaded, datasets);+ expect(density.layer.isValid).toBe(true);+ expect(density.layer.errorMessage).toBeNull();+ expect(density.layerData.data.length).toBeGreaterThan(0);+ expect(loaded.config.columns.value.value).toBeNull();+ }+ expect(() =>+ validateLayerWithData(missingWeightDataset, restored, LayerClasses, {throwOnError: true})+ ).toThrow(/invalid columns: value/);+ }+);+test.each([false, true])('sample (scattered = %s) generates all levels with islands and finite closed geometry',scattered => {const sample = createContourSamples(scattered);const {visConfig} = contourConfig.config.visState.layers[0].config;- const result = generateContours(buildContourGrid(sample), {+ const result = generateContours(buildContourGrid(sample, visConfig.gridResolution), {...visConfig,domain: [visConfig.minimum, visConfig.maximum]});diff --git a/src/layers/src/contour-layer/contour-layer.ts b/src/layers/src/contour-layer/contour-layer.tsindex d1cc8d163..09b750137 100644--- a/src/layers/src/contour-layer/contour-layer.ts+++ b/src/layers/src/contour-layer/contour-layer.ts@@ -5,7 +5,12 @@ import {GeoJsonLayer} from '@deck.gl/layers';import {PickingInfo} from '@deck.gl/core';import {Datasets, KeplerTable} from '@kepler.gl/table';import {RGBColor, VisConfigNumber} from '@kepler.gl/types';-import {LAYER_VIS_CONFIGS} from '@kepler.gl/constants';+import {+ colorPaletteToColorRange,+ DEFAULT_LAYER_COLOR_PALETTE_STEPS,+ KEPLER_COLOR_PALETTES,+ LAYER_VIS_CONFIGS+} from '@kepler.gl/constants';import {colorMaybeToRGB, DataContainerInterface} from '@kepler.gl/utils';import Layer, {LayerBaseConfigPartial} from '../base-layer';import {getFilterDataFunc} from '../aggregation-layer';@@ -31,37 +36,37 @@ const numberConfig = (export const contourVisConfigs = {opacity: 'opacity',- colorRange: 'colorRange',+ colorRange: {+ ...LAYER_VIS_CONFIGS.colorRange,+ defaultValue: colorPaletteToColorRange(KEPLER_COLOR_PALETTES[0], {+ steps: DEFAULT_LAYER_COLOR_PALETTE_STEPS,+ reversed: false+ })+ },colorByLevel: {type: 'boolean',property: 'colorByLevel',- defaultValue: false,+ defaultValue: true,label: 'layerVisConfigs.contour.colorByLevel'},- inputMode: {- type: 'select',- property: 'inputMode',- defaultValue: 'auto',- label: 'layerVisConfigs.contour.inputMode',- options: ['auto', 'grid', 'points']- },- interpolationResolution: {- ...numberConfig('interpolationResolution', 192, [32, 256], 16),- description: 'layerVisConfigs.contour.interpolationResolutionDescription'+ gridResolution: {+ ...numberConfig('gridResolution', 64, [32, 256], 16),+ description: 'layerVisConfigs.contour.gridResolutionDescription'},levels: numberConfig('levels', 7, [2, 20], 1),smoothing: {- ...numberConfig('smoothing', 1.5, [0, 6], 0.25),+ ...numberConfig('smoothing', 3, [0, 6], 0.25),description: 'layerVisConfigs.contour.smoothingDescription'},- fillOpacity: numberConfig('fillOpacity', 0.075, [0, 0.3], 0.005),+ fillOpacity: numberConfig('fillOpacity', 0.3, [0, 1], 0.005),thickness: numberConfig('thickness', 1.5, [0.5, 5], 0.1),filled: {...LAYER_VIS_CONFIGS.filled, defaultValue: true},stroked: 'stroked',below: {type: 'boolean',property: 'below',- defaultValue: true,+ // Keep the saved setting for older maps; new contours enclose peaks.+ defaultValue: false,label: 'layerVisConfigs.contour.below'},customRange: {@@ -181,12 +186,12 @@ export default class ContourLayer extends Layer {return this.defaultPointColumnPairs;}get columnLabels() {- return {lat: 'contour.lat', lng: 'contour.lng', value: 'contour.value'};+ return {lat: 'contour.lat', lng: 'contour.lng', value: 'contour.weight'};}get supportedColumnModes() {return [- {key: 'grid', label: 'Scalar samples', requiredColumns: ['lat', 'lng', 'value']},- {key: 'geojson', label: 'GeoJSON', requiredColumns: ['geojson', 'value']}+ {key: 'grid', label: 'Points', requiredColumns: ['lat', 'lng'], optionalColumns: ['value']},+ {key: 'geojson', label: 'GeoJSON', requiredColumns: ['geojson'], optionalColumns: ['value']}];}get noneLayerDataAffectingProps() {@@ -236,11 +241,16 @@ export default class ContourLayer extends Layer {formatLayerData(datasets: Datasets): {data: ContourFeature[]} {this.errorMessage = null;- this.updateMeta({contourLevels: []});+ this.updateMeta({contourLevels: [], contourDomain: null, bounds: undefined});const dataset = this.config.dataId ? datasets[this.config.dataId] : null;if (!dataset || !this.hasAllColumns()) return {data: []};const {dataContainer, gpuFilter, filteredIndex, filteredIndexByLayer} = dataset;const {value} = this.config.columns;+ const weighted = Boolean(value.value);+ const weightField = value.value ? dataset.getColumnField(value.value) : null;+ if (weighted && (!weightField || !['integer', 'real'].includes(weightField.type))) {+ throw new Error('Select a numeric contour weight column, or clear it to use point density.');+ }const getPosition = this.getPositionAccessor(dataContainer, dataset);const selected = new Set(filteredIndexByLayer?.[this.id] ?? filteredIndex);const activeFilter =@@ -250,27 +260,31 @@ export default class ContourLayer extends Layer {? getFilterDataFunc(gpuFilter.filterRange, gpuFilter.filterValueAccessor(dataContainer)()): null;const samples: ScalarSample[] = [];- for (let index = 0; index < dataContainer.numRows(); index++) {+ for (const index of selected) {+ if (matches && !matches({index})) continue;const position = getPosition({index});if (!position) continue;- // Keep the source lattice even when filters remove an entire row/column.samples.push({longitude: position[0],latitude: position[1],- value:- selected.has(index) && (!matches || matches({index}))- ? dataset.fields[value.fieldIdx].valueAccessor({index})- : null+ value: weightField ? weightField.valueAccessor({index}) : 1});}// Let calculateLayerData retain validation errors and manage invalid/recovered state.const grid = buildContourGrid(samples,- this.config.visConfig.inputMode,- this.config.visConfig.interpolationResolution+ this.config.visConfig.gridResolution,+ weighted ? 'MEAN' : 'COUNT');- if (grid)+ if (grid) {+ let minimum = Infinity;+ let maximum = -Infinity;+ for (const value of grid.values) {+ minimum = Math.min(minimum, value);+ maximum = Math.max(maximum, value);+ }this.updateMeta({+ contourDomain: [minimum, maximum],bounds: [grid.longitude,grid.latitude,@@ -278,6 +292,7 @@ export default class ContourLayer extends Layer {grid.latitude + (grid.height - 1) * grid.stepLat]});+ }const {smoothing, levels, below, customRange, minimum, maximum} = this.config.visConfig;const data = generateContours(grid, {smoothing,@@ -292,10 +307,15 @@ export default class ContourLayer extends Layer {getHoverData(object: ContourFeature | null) {if (!object) return null;const {threshold, below} = object.properties;- const field = String(this.config.columns.value.value || 'value');+ const field = String(this.config.columns.value.value || 'Point count');return {fieldValues: [- {labelMessage: 'columns.contour.value', value: `${field} ${below ? '≤' : '≥'} ${threshold}`}+ {+ labelMessage: this.config.columns.value.value+ ? 'columns.contour.value'+ : 'columns.contour.density',+ value: `${field} ${below ? '≤' : '≥'} ${threshold}`+ }]};}diff --git a/src/layers/src/contour-layer/contour-utils.spec.ts b/src/layers/src/contour-layer/contour-utils.spec.tsindex a8704c7c5..7b91a2bd7 100644--- a/src/layers/src/contour-layer/contour-utils.spec.ts+++ b/src/layers/src/contour-layer/contour-utils.spec.ts@@ -3,10 +3,9 @@import {buildContourGrid,- buildScalarGrid,generateContours,- interpolateScalarSamples,ScalarSample,+ ScalarGrid,smoothScalarGrid} from './contour-utils';@@ -18,11 +17,25 @@ function samples(size: number, value: (x: number, y: number) => number | null):}));}+// Contour geometry and smoothing tests use a fixed surface independently of aggregation.+function testGrid(input: ScalarSample[]): ScalarGrid {+ const size = Math.sqrt(input.length);+ return {+ width: size,+ height: size,+ longitude: 0,+ latitude: 0,+ stepLng: 1,+ stepLat: 1,+ values: Float64Array.from(input, sample => sample.value ?? NaN)+ };+}+const options = {smoothing: 0, levels: 3, below: true, domain: [2, 6] as [number, number]};describe('scalar contours', () => {test('traces nested lower-value regions with thresholds in the original units', () => {- const grid = buildScalarGrid(samples(9, (x, y) => (x - 4) ** 2 + (y - 4) ** 2));+ const grid = testGrid(samples(9, (x, y) => (x - 4) ** 2 + (y - 4) ** 2));const features = generateContours(grid, options);expect(features.map(f => f.properties.threshold)).toEqual([6, 4, 2]);const widths = features.map(f => {@@ -37,20 +50,20 @@ describe('scalar contours', () => {});test('also supports upper-value regions and negative scalar values', () => {- const grid = buildScalarGrid(samples(9, (x, y) => -((x - 4) ** 2 + (y - 4) ** 2)));+ const grid = testGrid(samples(9, (x, y) => -((x - 4) ** 2 + (y - 4) ** 2)));const result = generateContours(grid, {...options, below: false, domain: [-6, -2]});expect(result.map(f => f.properties.threshold)).toEqual([-6, -4, -2]);expect(result.every(f => f.geometry.coordinates.length === 1)).toBe(true);});test('smooths an isolated spike and preserves constant values at boundaries', () => {- const spike = buildScalarGrid(samples(9, (x, y) => (x === 4 && y === 4 ? 100 : 0)))!;+ const spike = testGrid(samples(9, (x, y) => (x === 4 && y === 4 ? 100 : 0)))!;expect(smoothScalarGrid(spike, 0)).toBe(spike.values);const smooth = smoothScalarGrid(spike, 1.5);expect(smooth[40]).toBeLessThan(100);expect(smooth[40]).toBeGreaterThan(smooth[41]);expect(smooth[41]).toBeGreaterThan(0);- const constant = buildScalarGrid(samples(9, () => -12))!;+ const constant = testGrid(samples(9, () => -12))!;expect([...smoothScalarGrid(constant, 2)].every(value => Math.abs(value + 12) < 1e-10)).toBe(true);@@ -60,9 +73,7 @@ describe('scalar contours', () => {'does not invent automatic contours in a constant field of %s',value => {for (const holes of [false, true]) {- const grid = buildScalarGrid(- samples(9, (x, y) => (holes && x === 4 && y === 4 ? null : value))- );+ const grid = testGrid(samples(9, (x, y) => (holes && x === 4 && y === 4 ? null : value)));for (const smoothing of [0, 1.5, 6]) {for (const below of [false, true]) {expect(generateContours(grid, {smoothing, levels: 7, below})).toEqual([]);@@ -76,7 +87,7 @@ describe('scalar contours', () => {[0, 1e-20],[10, 1e-10]])('preserves real small variations around %s at scale %s', (baseline, scale) => {- const grid = buildScalarGrid(samples(9, (x, y) => baseline + scale * (x + y)));+ const grid = testGrid(samples(9, (x, y) => baseline + scale * (x + y)));const result = generateContours(grid, {smoothing: 1.5, levels: 7, below: true});expect(result).toHaveLength(7);expect(new Set(result.map(feature => feature.properties.threshold)).size).toBe(7);@@ -90,9 +101,7 @@ describe('scalar contours', () => {value => {const span = Math.abs(value) || 1;for (const holes of [false, true]) {- const grid = buildScalarGrid(- samples(9, (x, y) => (holes && x === 4 && y === 4 ? null : value))- )!;+ const grid = testGrid(samples(9, (x, y) => (holes && x === 4 && y === 4 ? null : value)))!;for (const below of [false, true]) {const settings = {levels: 3,@@ -113,7 +122,7 @@ describe('scalar contours', () => {);test('keeps missing values as holes after smoothing', () => {- const grid = buildScalarGrid(samples(9, (x, y) => (x === 4 && y === 4 ? null : 1)))!;+ const grid = testGrid(samples(9, (x, y) => (x === 4 && y === 4 ? null : 1)))!;expect(Number.isNaN(smoothScalarGrid(grid, 2)[40])).toBe(true);const result = generateContours(grid, {...options, smoothing: 2});expect(result).toHaveLength(3);@@ -126,177 +135,137 @@ describe('scalar contours', () => {).toBe(true);});- test('retains a missing full column at the original spacing', () => {- const input = samples(5, () => 1).filter(d => d.longitude !== 2);- const grid = buildScalarGrid(input)!;- expect(grid.width).toBe(5);- expect(Number.isNaN(grid.values[2])).toBe(true);- expect(grid.values[3]).toBe(1);- });-- test('averages duplicate measurements without treating them as weights', () => {- const grid = buildScalarGrid([- ...samples(3, () => 10),- {longitude: 1, latitude: 1, value: 30}- ])!;- expect(grid.values[4]).toBe(20);- });-- test('handles empty, nonfinite, constant, and invalid inputs', () => {- expect(buildScalarGrid([])).toBeNull();+ test('handles empty surfaces and invalid custom thresholds', () => {expect(generateContours(null, options)).toEqual([]);- expect(generateContours(buildScalarGrid(samples(3, () => NaN)), options)).toEqual([]);- expect(- generateContours(buildScalarGrid(samples(3, () => 4)), {...options, domain: undefined})- ).toEqual([]);- expect(() => buildScalarGrid([{longitude: 1, latitude: 1, value: 2}])).toThrow('at least two');- expect(() =>- buildScalarGrid(- samples(3, () => 1).map(d => ({...d, longitude: d.longitude === 2 ? 2.5 : d.longitude}))- )- ).toThrow('regularly spaced');+ expect(generateContours(testGrid(samples(3, () => NaN)), options)).toEqual([]);expect(() =>- generateContours(buildScalarGrid(samples(3, () => 1)), {...options, domain: [5, 2]})+ generateContours(testGrid(samples(3, () => 1)), {...options, domain: [5, 2]})).toThrow('minimum');});});-describe('scattered scalar interpolation', () => {- const plane = (x: number, y: number) => 3 + 2 * x + 3 * y;- const scattered = [- [0, 0],- [2, 0],- [0.7, 2],- [1.1, 0.6]- ].map(([longitude, latitude]) => ({+describe('point aggregation for contours', () => {+ const point = (longitude: number, latitude: number, value: number | null): ScalarSample => ({longitude,latitude,- value: plane(longitude, latitude)- }));-- test('reproduces a linear field and keeps cells outside the sample hull empty', () => {- const grid = interpolateScalarSamples(scattered, 64)!;- let valid = 0;- for (let i = 0; i < grid.values.length; i++) {- if (!Number.isFinite(grid.values[i])) continue;- valid++;- expect(grid.values[i]).toBeCloseTo(- plane(- grid.longitude + (i % grid.width) * grid.stepLng,- grid.latitude + Math.floor(i / grid.width) * grid.stepLat- ),- 10- );- }- expect(valid).toBeGreaterThan(1000);- expect(grid.values[0]).toBe(3);- expect(grid.values[grid.width - 1]).toBeCloseTo(7);- expect(Number.isNaN(grid.values[grid.values.length - 1])).toBe(true);- expect(Number.isNaN(smoothScalarGrid(grid, 2)[grid.values.length - 1])).toBe(true);+ value});+ const at = (grid: ScalarGrid, longitude: number, latitude: number) =>+ grid.values[+ Math.round((latitude - grid.latitude) / grid.stepLat) * grid.width ++ Math.round((longitude - grid.longitude) / grid.stepLng)+ ];- test('auto interpolates irregular positions and generates contours in the input units', () => {- const grid = buildContourGrid(scattered, 'auto', 64)!;- expect(Math.max(grid.width, grid.height)).toBe(64);- expect(- generateContours(grid, {...options, domain: [4, 8], smoothing: 1}).map(- f => f.properties.threshold- )- ).toEqual([8, 6, 4]);- expect(() => buildContourGrid(scattered, 'grid')).toThrow('regularly spaced');+ test('averages distinct points in the same cell and leaves empty cells at zero', () => {+ const grid = buildContourGrid(+ [point(0, 0, 10), point(0.0001, 0.0001, 30), point(0.03, 0.03, -8)],+ 32+ )!;+ expect(at(grid, 0, 0)).toBe(20);+ expect(at(grid, 0.03, 0.03)).toBe(-8);+ expect(at(grid, 0.015, 0.015)).toBe(0);+ expect([...grid.values].filter(value => value !== 0).sort((a, b) => a - b)).toEqual([-8, 20]);+ expect(generateContours(grid, {...options, below: false, domain: [5, 15]})).toHaveLength(3);});- test('does not invent automatic contours when interpolating constant scattered values', () => {+ test('counts every point when weights are absent, including duplicate positions', () => {const grid = buildContourGrid(- scattered.map(sample => ({...sample, value: 10})),- 'auto',- 32- );- expect(generateContours(grid, {smoothing: 1.5, levels: 7, below: true})).toEqual([]);+ [point(0, 0, null), point(0, 0, NaN), point(0.0001, 0.0001, -100), point(0.03, 0.03, 99)],+ 32,+ 'COUNT'+ )!;+ expect(at(grid, 0, 0)).toBe(3);+ expect(at(grid, 0.03, 0.03)).toBe(1);+ expect([...grid.values].reduce((a, b) => a + b, 0)).toBe(4);+ });++ test('skips invalid weights without counting them or extending the weighted surface', () => {+ const valid = [point(0, 0, 0), point(0.0001, 0.0001, -10), point(0.03, 0.03, 4)];+ const invalid = [point(0, 0, null), point(10, 10, NaN), point(10, 10, Infinity)];+ const grid = buildContourGrid([...valid, ...invalid], 32)!;+ expect(grid).toEqual(buildContourGrid(valid, 32));+ expect(at(grid, 0, 0)).toBe(-5);+ expect(buildContourGrid(invalid)).toBeNull();});- test.each([0, 1.5])(- 'preserves constant scattered regions at custom thresholds with smoothing %s',- smoothing => {- for (const value of [0, 10, -12, 1e-20, 1e20]) {- const grid = buildContourGrid(- scattered.map(sample => ({...sample, value})),- 'auto',- 32+ test.each(['MEAN', 'COUNT'] as const)('ignores invalid coordinates in %s mode', aggregation => {+ const valid = [point(0, 0, 4), point(0.03, 0.03, 8)];+ expect(+ buildContourGrid(+ [+ ...valid,+ point(NaN, 0, 2),+ point(0, Infinity, 3),+ point(181, 0, 4),+ point(0, 90, 5),+ {longitude: null, latitude: 0, value: 6} as unknown as ScalarSample+ ],+ 32,+ aggregation+ )+ ).toEqual(buildContourGrid(valid, 32, aggregation));+ });++ test.each([undefined, 32, 192, 256])(+ 'fits small and large datasets to a maximum axis of %s',+ resolution => {+ const makeGrid = (scale: number) =>+ buildContourGrid(+ [point(-0.5 * scale, -0.25 * scale, 10), point(0.5 * scale, 0.25 * scale, 30)],+ resolution)!;- const constantGrid = {- ...grid,- values: Float64Array.from(grid.values, cell => (Number.isFinite(cell) ? value : NaN))- };- const span = Math.abs(value) || 1;- for (const below of [false, true]) {- const settings = {- levels: 3,- below,- domain: [value - span, value + span] as [number, number]- };- const expected = generateContours(constantGrid, {...settings, smoothing: 0});- const result = generateContours(grid, {...settings, smoothing});- expect(result).toEqual(expected);- const atValue = result.find(feature => feature.properties.threshold === value)!;- expect(atValue.geometry.coordinates).toHaveLength(1);- expect(atValue.geometry.coordinates[0]).toHaveLength(1);- }- expect(new Set([...grid.values].filter(Number.isFinite))).toEqual(new Set([value]));- expect(Number.isNaN(smoothScalarGrid(grid, smoothing)[grid.values.length - 1])).toBe(true);+ const small = makeGrid(0.00001);+ const large = makeGrid(1);+ for (const grid of [small, large]) {+ expect(Math.max(grid.width, grid.height)).toBe(resolution ?? 64);+ expect(grid.height).toBeLessThan(grid.width);+ expect(grid.stepLng).toBeCloseTo(grid.stepLat, 12);}+ expect(small.width).toBe(large.width);+ expect(small.height).toBe(large.height);+ expect(small.values).toEqual(large.values);+ expect(small.stepLng / large.stepLng).toBeCloseTo(0.00001, 12);});- test('auto preserves the original grid and its holes; explicit points mode fills gaps', () => {- const input = samples(5, (x, y) => (x === 2 && y === 2 ? null : plane(x, y)));- expect(buildContourGrid(input, 'auto', 256)).toEqual(buildScalarGrid(input));- const interpolated = buildContourGrid(input, 'points', 33)!;- expect(interpolated.width).toBeGreaterThan(5);- expect([...interpolated.values].every(Number.isFinite)).toBe(true);+ test('keeps cells geographically square at higher latitudes', () => {+ const grid = buildContourGrid([point(0, 59.99, 10), point(0.03, 60.01, 30)], 192)!;+ expect(grid.height).toBe(192);+ expect(grid.width).toBeGreaterThan(2);+ expect(grid.width).toBeLessThan(grid.height);+ expect(grid.stepLng * Math.cos(Math.PI / 3)).toBeCloseTo(grid.stepLat, 12);+ expect(grid.longitude + (grid.width - 1) * grid.stepLng).toBeGreaterThanOrEqual(0.03);+ expect(grid.latitude).toBeLessThanOrEqual(59.99);+ expect(grid.latitude + (grid.height - 1) * grid.stepLat).toBeCloseTo(60.01);});- test('averages duplicate measurements and ignores missing or invalid samples', () => {- const grid = interpolateScalarSamples(- [- {longitude: 0, latitude: 0, value: 2},- {longitude: 0, latitude: 0, value: 6},- {longitude: 2, latitude: 0, value: 8},- {longitude: 0.7, latitude: 2, value: 10},- {longitude: 20, latitude: 20, value: null},- {longitude: 20, latitude: 20, value: Infinity},- {longitude: NaN, latitude: 0, value: 100}- ],- 32- )!;- expect(grid.values[0]).toBe(4);- expect(grid.longitude + (grid.width - 1) * grid.stepLng).toBeCloseTo(2);- expect([...grid.values].filter(Number.isFinite).every(value => value >= 4 && value <= 10)).toBe(- true- );+ test('resolution determines which observations are averaged', () => {+ const input = [point(0, 0, 10), point(0.0004, 0.0004, 30), point(0.03, 0.03, 8)];+ const fine = buildContourGrid(input, 256)!;+ const coarse = buildContourGrid(input, 32)!;+ expect(at(fine, 0, 0)).toBe(10);+ expect(at(fine, 0.0004, 0.0004)).toBe(30);+ expect(at(coarse, 0, 0)).toBe(20);});- test('bounds resolution and handles empty, insufficient, collinear and global samples', () => {- const grid = interpolateScalarSamples(scattered, 10000)!;+ test('accepts single points and collinear inputs without triangulation', () => {+ for (const input of [[point(0, 0, 8)], [point(0, 0, 8), point(0, 0.03, 12)]]) {+ const grid = buildContourGrid(input, 32)!;+ expect(grid.width).toBeGreaterThanOrEqual(2);+ expect(grid.height).toBeGreaterThanOrEqual(2);+ expect(generateContours(grid, {...options, below: false})).toHaveLength(3);+ }+ });++ test('bounds grid allocation and handles empty, invalid settings and global inputs', () => {+ const grid = buildContourGrid([point(0, 0, 4), point(10, 10, 8)], 100000)!;expect(Math.max(grid.width, grid.height)).toBe(256);- expect(interpolateScalarSamples([])).toBeNull();- expect(interpolateScalarSamples(scattered.map(d => ({...d, value: null})))).toBeNull();- expect(() => interpolateScalarSamples(scattered.slice(0, 2))).toThrow('non-collinear');- expect(() =>- interpolateScalarSamples(- [0, 1, 2].map(x => ({- longitude: x,- latitude: 2 * x,- value: x- }))- )- ).toThrow('non-collinear');- expect(() =>- buildContourGrid([- {longitude: -179, latitude: 0, value: 1},- {longitude: 179, latitude: 0, value: 2},- {longitude: 179, latitude: 1, value: 3}- ])- ).toThrow('antimeridian');+ expect(grid.values.length).toBeLessThanOrEqual(256 * 256);+ expect([...grid.values].every(Number.isFinite)).toBe(true);+ expect(buildContourGrid([])).toBeNull();+ for (const resolution of [0, 1, -1, NaN, Infinity]) {+ expect(() => buildContourGrid([point(0, 0, 1)], resolution)).toThrow('grid resolution');+ }+ expect(() => buildContourGrid([point(-179, 0, 1), point(179, 1, 2)])).toThrow('antimeridian');});});diff --git a/src/layers/src/contour-layer/contour-utils.ts b/src/layers/src/contour-layer/contour-utils.tsindex 905edd37f..a34ce71cd 100644--- a/src/layers/src/contour-layer/contour-utils.ts+++ b/src/layers/src/contour-layer/contour-utils.ts@@ -2,10 +2,9 @@// Copyright contributors to the kepler.gl projectimport {contours} from 'd3-contour';-import Delaunator from 'delaunator';import {Feature, MultiPolygon} from 'geojson';-/** Scalar measurements. In grid mode, positions are cell centers and nulls remain no-data. */+/** Point observations; missing weights are skipped when calculating cell means. */export type ScalarSample = {longitude: number; latitude: number; value: number | null};export type ScalarGrid = {width: number;@@ -27,12 +26,8 @@ export type ContourOptions = {domain?: [number, number];};-const MAX_AXIS = 512;--export type ContourInputMode = 'auto' | 'grid' | 'points';--// Only grid-layout failures may fall back to interpolation. Geographic errors must surface.-class ScalarGridLayoutError extends Error {}+const MAX_GRID_AXIS = 256;+const METERS_PER_DEGREE_LAT = 111320;function hasValidPosition(d: ScalarSample): boolean {return (@@ -62,177 +57,66 @@ function regionalBounds(samples: ScalarSample[]) {return {west, east, south, north};}-function gridAxis(values: number[]): {origin: number; step: number; length: number} {- const sorted = [...new Set(values)].sort((a, b) => a - b);- if (sorted.length < 2) {- throw new ScalarGridLayoutError(- 'Contours need at least two distinct latitudes and longitudes.'- );- }- // The smallest separation also preserves entirely missing rows/columns.- let step = Infinity;- for (let i = 1; i < sorted.length; i++) step = Math.min(step, sorted[i] - sorted[i - 1]);- const origin = sorted[0];- const length = Math.round((sorted[sorted.length - 1] - origin) / step) + 1;- if (length > MAX_AXIS) {- throw new ScalarGridLayoutError(- 'Contour grids support up to 512 samples per axis. Use a coarser regular grid.'- );- }- if (- sorted.some(- value => Math.abs((value - origin) / step - Math.round((value - origin) / step)) > 0.001- )- ) {- throw new ScalarGridLayoutError(- 'Contours require regularly spaced longitude/latitude samples.'- );- }- return {origin, step, length};-}--export function buildScalarGrid(samples: ScalarSample[]): ScalarGrid | null {- const located = samples.filter(hasValidPosition);- if (!located.length) return null;- regionalBounds(located);- const x = gridAxis(located.map(d => d.longitude));- const y = gridAxis(located.map(d => d.latitude));- const values = new Float64Array(x.length * y.length).fill(NaN);- const counts = new Uint32Array(values.length);- for (const d of located) {- if (typeof d.value !== 'number' || !Number.isFinite(d.value)) continue;- const col = Math.round((d.longitude - x.origin) / x.step);- const row = Math.round((d.latitude - y.origin) / y.step);- const i = row * x.length + col;- // Repeated measurements at a cell represent an average, never density.- const count = ++counts[i];- values[i] = count === 1 ? d.value : values[i] + (d.value - values[i]) / count;- }- return {- width: x.length,- height: y.length,- longitude: x.origin,- latitude: y.origin,- stepLng: x.step,- stepLat: y.step,- values- };-}--/** Keep supported lattices (including holes) intact; interpolate only when requested/needed. */+/**+ * Bin points into the nearest geographic cells, fitting the grid resolution to+ * the sample bounds.+ * Empty cells are zero; a weight selects MEAN, otherwise+ * each point contributes one count. Rows run south to north for contour rendering.+ */export function buildContourGrid(samples: ScalarSample[],- mode: ContourInputMode = 'auto',- resolution = 192-): ScalarGrid | null {- if (mode === 'grid') return buildScalarGrid(samples);- if (mode === 'auto') {- try {- return buildScalarGrid(samples);- } catch (error) {- if (!(error instanceof ScalarGridLayoutError)) throw error;- }- }- return interpolateScalarSamples(samples, resolution);-}--/** Linear interpolation over Delaunay triangles; never extrapolate beyond the sample hull. */-export function interpolateScalarSamples(- samples: ScalarSample[],- resolution = 192+ resolution = 64,+ aggregation: 'MEAN' | 'COUNT' = 'MEAN'): ScalarGrid | null {- const unique = new Map<string, ScalarSample & {value: number; count: number}>();- for (const sample of samples) {- if (- !hasValidPosition(sample) ||- typeof sample.value !== 'number' ||- !Number.isFinite(sample.value)- )- continue;- const key = `${sample.longitude},${sample.latitude}`;- const point = unique.get(key);- if (point) {- point.count++;- point.value += (sample.value - point.value) / point.count;- } else {- unique.set(key, {...sample, value: sample.value, count: 1});- }+ if (!Number.isFinite(resolution) || resolution < 2) {+ throw new Error('Contour grid resolution must be a finite number of at least 2 cells.');}- const points = [...unique.values()];- if (!points.length) return null;- const {west, east, south, north} = regionalBounds(points);- const insufficient =- 'Interpolation needs at least three distinct, non-collinear samples with valid values.';- if (points.length < 3 || west === east || south === north) throw new Error(insufficient);-- // Regional equirectangular coordinates correct the longitude/latitude aspect ratio.- const scaleX = Math.cos((((south + north) / 2) * Math.PI) / 180);- const spanX = (east - west) * scaleX;- const spanY = north - south;+ const located = samples.filter(+ sample =>+ hasValidPosition(sample) &&+ (aggregation === 'COUNT' ||+ (typeof sample.value === 'number' && Number.isFinite(sample.value)))+ );+ if (!located.length) return null;+ const {west, east, south, north} = regionalBounds(located);+ const metersPerDegreeLng =+ METERS_PER_DEGREE_LAT * Math.max(0.01, Math.cos((((south + north) / 2) * Math.PI) / 180));+ const axis = Math.min(MAX_GRID_AXIS, Math.round(resolution));+ const spanX = (east - west) * metersPerDegreeLng;+ const spanY = (north - south) * METERS_PER_DEGREE_LAT;const span = Math.max(spanX, spanY);- const size = Number.isFinite(resolution)- ? Math.max(32, Math.min(256, Math.round(resolution)))- : 192;- const width = Math.max(2, Math.round(((size - 1) * spanX) / span) + 1);- const height = Math.max(2, Math.round(((size - 1) * spanY) / span) + 1);- const coords = new Float64Array(points.length * 2);- for (let i = 0; i < points.length; i++) {- coords[2 * i] = ((points[i].longitude - west) * scaleX) / span;- coords[2 * i + 1] = (points[i].latitude - south) / span;- }- const {triangles} = new Delaunator(coords);- if (!triangles.length) throw new Error(insufficient);- const values = new Float64Array(width * height).fill(NaN);- const stepX = spanX / span / (width - 1);- const stepY = spanY / span / (height - 1);- const tolerance = 1e-10;- // Rasterize each triangle's bounding box, rather than searching every point for every cell.- for (let t = 0; t < triangles.length; t += 3) {- const ia = triangles[t];- const ib = triangles[t + 1];- const ic = triangles[t + 2];- // Preserve flat triangles exactly so roundoff cannot split an explicit threshold region.- const constantValue =- points[ia].value === points[ib].value && points[ia].value === points[ic].value- ? points[ia].value- : null;- const ax = coords[2 * ia];- const ay = coords[2 * ia + 1];- const bx = coords[2 * ib];- const by = coords[2 * ib + 1];- const cx = coords[2 * ic];- const cy = coords[2 * ic + 1];- const denominator = (by - cy) * (ax - cx) + (cx - bx) * (ay - cy);- if (denominator === 0) continue;- const col0 = Math.max(0, Math.ceil(Math.min(ax, bx, cx) / stepX - tolerance));- const col1 = Math.min(width - 1, Math.floor(Math.max(ax, bx, cx) / stepX + tolerance));- const row0 = Math.max(0, Math.ceil(Math.min(ay, by, cy) / stepY - tolerance));- const row1 = Math.min(height - 1, Math.floor(Math.max(ay, by, cy) / stepY + tolerance));- for (let row = row0; row <= row1; row++) {- for (let col = col0; col <= col1; col++) {- const x = col * stepX;- const y = row * stepY;- const a = ((by - cy) * (x - cx) + (cx - bx) * (y - cy)) / denominator;- const b = ((cy - ay) * (x - cx) + (ax - cx) * (y - cy)) / denominator;- const c = 1 - a - b;- if (a < -tolerance || b < -tolerance || c < -tolerance) continue;- // Clamp round-off at triangle edges to keep values within their samples' range.- const wa = Math.max(0, a);- const wb = Math.max(0, b);- const wc = Math.max(0, c);- values[row * width + col] =- constantValue ??- (wa * points[ia].value + wb * points[ib].value + wc * points[ic].value) / (wa + wb + wc);- }- }+ // Fit the longer axis to the selected resolution, with square geographic cells.+ // Coincident points have no extent; use a minimal 2x2 grid with one-meter spacing.+ const size = span > 0 ? span / (axis - 1) : 1;+ const stepLng = size / metersPerDegreeLng;+ const stepLat = size / METERS_PER_DEGREE_LAT;+ // Clamp roundoff on the longer axis; pad a degenerate shorter axis to two cells.+ const width = Math.max(2, Math.min(axis, Math.ceil(spanX / size) + 1));+ const height = Math.max(2, Math.min(axis, Math.ceil(spanY / size) + 1));+ const values = new Float64Array(width * height);+ const counts = new Uint32Array(values.length);+ for (const sample of located) {+ // Resolve half-cell ties consistently despite roundoff when rescaling an extent.+ const col = Math.min(width - 1, Math.round((sample.longitude - west) / stepLng + 1e-10));+ const row =+ height - 1 - Math.min(height - 1, Math.round((north - sample.latitude) / stepLat + 1e-10));+ const index = row * width + col;+ const count = ++counts[index];+ // Incremental means avoid accumulating a large sum of weights.+ values[index] =+ aggregation === 'COUNT'+ ? count+ : count === 1+ ? sample.value!+ : values[index] * ((count - 1) / count) + sample.value! / count;}return {width,height,longitude: west,- latitude: south,- stepLng: (east - west) / (width - 1),- stepLat: (north - south) / (height - 1),+ latitude: north - (height - 1) * stepLat,+ stepLng,+ stepLat,values};}diff --git a/src/localization/src/translations/en.ts b/src/localization/src/translations/en.tsindex c5b2c0726..4103f22fa 100644--- a/src/localization/src/translations/en.ts+++ b/src/localization/src/translations/en.ts@@ -331,18 +331,18 @@ export default {levelsGroup: 'Contour levels',fillGroup: 'Fill',colorByLevel: 'Color by level',- inputMode: 'Input type',- interpolationResolution: 'Interpolation resolution',- interpolationResolutionDescription:- 'Samples along the longer axis of the interpolated surface. Regular grids retain their original resolution.',+ weightDescription:+ 'Average a numeric column within each cell. Leave empty to show point density (point count per cell).',+ gridResolution: 'Grid resolution',+ gridResolutionDescription:+ 'Maximum cells along the longer geographic axis. Cell size adapts to the data bounds; the shorter axis scales proportionally.',smoothing: 'Smoothing',- smoothingDescription: 'Gaussian smoothing in grid cells. Missing values remain empty.',+ smoothingDescription: 'Gaussian smoothing in grid cells. Empty cells contribute zero.',levels: 'Number of levels',below: 'Fill below each level',- invert: 'Invert',customRange: 'Custom level range',noValueRange:- 'Select a value column with at least two distinct finite values to use the range slider.',+ 'The selected weight or point counts must have a nonzero finite range to use the range slider.',minimum: 'Minimum level',maximum: 'Maximum level',fillOpacity: 'Opacity',@@ -1204,7 +1204,9 @@ ${'```'}contour: {lat: 'Latitude',lng: 'Longitude',- value: 'Value'+ value: 'Value',+ weight: 'Weight',+ density: 'Point count'},hex_id: 'hex id',flowField: {diff --git a/src/reducers/src/vis-state-merger.ts b/src/reducers/src/vis-state-merger.tsindex 39d9dcd63..d89a6e3ee 100644--- a/src/reducers/src/vis-state-merger.ts+++ b/src/reducers/src/vis-state-merger.ts@@ -1351,6 +1351,14 @@ export function validateLayerWithData(options);if (columns) {+ if (+ type === LAYER_TYPES.contour &&+ savedLayer.config.columns?.value &&+ !columns.value?.value+ ) {+ // Retain unresolved weights so contour validation reports them instead of using density.+ columns.value = {...columns.value, value: savedLayer.config.columns.value, fieldIdx: -1};+ }newLayer.updateLayerConfig({columns: {...newLayer.config.columns,diff --git a/src/reducers/src/vis-state-updaters.ts b/src/reducers/src/vis-state-updaters.tsindex fe76d08ee..c6fa1301f 100644--- a/src/reducers/src/vis-state-updaters.ts+++ b/src/reducers/src/vis-state-updaters.ts@@ -1184,6 +1184,20 @@ export function layerTypeChangeUpdater(defaultLayerProps);+ // Use Contour's palette when the source still has its default; retain customized palettes.+ if (+ newType === LAYER_TYPES.contour &&+ oldLayer.type !== LAYER_TYPES.contour &&+ isEqual(+ oldLayer.config.visConfig.colorRange,+ oldLayer.visConfigSettings.colorRange?.defaultValue+ )+ ) {+ newLayer.updateLayerVisConfig({+ colorRange: newLayer.visConfigSettings.colorRange.defaultValue+ });+ }+// Contour uses scalar thresholds as legend-label keys. When leaving Contour,// retain only color-keyed labels while preserving the palette.const colorRange = newLayer.config.visConfig.colorRange;diff --git a/test/browser/components/side-panel/layer-configurator-test.js b/test/browser/components/side-panel/layer-configurator-test.jsindex 8b86693f4..0e551064f 100644--- a/test/browser/components/side-panel/layer-configurator-test.js+++ b/test/browser/components/side-panel/layer-configurator-test.js@@ -236,6 +236,68 @@ function toggleConfigGroup(group) {fireEvent.click(group.querySelector('.layer-config-group__header'));}+test('Components -> LayerConfigurator -> contour weight lives before Color and can switch to density', t => {+ for (const columnMode of ['grid', 'geojson']) {+ const dataset = contourRangeDataset();+ const layer = contourRangeLayer(dataset);+ layer.updateLayerConfig({columnMode});+ const originalColumns = layer.config.columns;+ const onChange = sinon.spy(config => layer.updateLayerConfig(config));+ const view = renderContourRange(layer, {[dataset.id]: dataset}, sinon.spy(), {+ updateLayerConfig: onChange+ });+ try {+ const weight = contourConfigGroup(view, 'Weight');+ const visual = view.container.querySelector('.layer-panel__config__visualC-config');+ t.equal(weight.parentElement, visual, 'weight is in the main settings');+ t.equal(+ weight.nextElementSibling,+ contourConfigGroup(view, 'Color'),+ 'weight precedes Color'+ );+ t.equal(+ view.queryAllByText('Weight', {selector: '.layer-config-group__label span'}).length,+ 1,+ 'Data Source has no duplicate weight selector'+ );+ t.ok(within(weight).getByText('value'), 'retains the saved weight selection');+ t.ok(+ weight.querySelector('[data-for="columns.contour.weight"] [data-id="tooltip"]'),+ 'weight includes help for averages and the density fallback'+ );++ fireEvent.click(weight.querySelector('.item-selector__dropdown'));+ fireEvent.click(within(document.body).getByText('other', {selector: '.list__item__anchor'}));+ t.deepEqual(+ layer.config.columns.value,+ {...originalColumns.value, value: 'other', fieldIdx: 1},+ 'selecting a weight updates the existing value column'+ );+ t.equal(+ layer.config.columnMode,+ columnMode,+ 'selecting a weight preserves the position mode'+ );+ t.deepEqual(layer.config.columns.lat, originalColumns.lat, 'preserves latitude');+ t.deepEqual(layer.config.columns.lng, originalColumns.lng, 'preserves longitude');+ t.deepEqual(layer.config.columns.geojson, originalColumns.geojson, 'preserves geometry');+ view.update();++ fireEvent.click(weight.querySelector('.data-ex-icons-delete'));+ t.deepEqual(+ layer.config.columns.value,+ {...originalColumns.value, value: null, fieldIdx: -1},+ 'clearing the weight selects point density'+ );+ view.update();+ t.ok(within(weight).getByText('Point count'), 'shows the density fallback');+ } finally {+ view.unmount();+ }+ }+ t.end();+});+test('Components -> LayerConfigurator -> contour switches between plain color and the palette picker', t => {const dataset = contourRangeDataset();const layer = contourRangeLayer(dataset);@@ -249,7 +311,12 @@ test('Components -> LayerConfigurator -> contour switches between plain color antry {const group = contourConfigGroup(view, 'Color');const toggle = group.querySelector('#contour-range-colorByLevel-switch');- t.notOk(toggle.checked, 'existing maps start in plain-color mode');+ t.ok(toggle.checked, 'new contours enable color by level');+ t.ok(group.querySelector('.color-range-palette'), 'shows the default palette preview');+ fireEvent.click(toggle);+ t.deepEqual(onChange.lastCall.args[0], {colorByLevel: false}, 'allows selecting plain color');+ layer.updateLayerVisConfig(onChange.lastCall.args[0]);+ view.update();t.ok(group.querySelector('.color-selector__selector__block'), 'shows the plain color picker');t.notOk(toggle.closest('.layer-config-group__content__collapsible'),@@ -268,8 +335,15 @@ test('Components -> LayerConfigurator -> contour switches between plain color anfireEvent.click(group.querySelector('.color-selector__selector'));view.update();t.ok(group.querySelector('.color-range-selector'), 'opens the standard palette picker');+ const initialPalette = layer.config.visConfig.colorRange;fireEvent.click(group.querySelector('.color-palette-outer'));const {colorRange} = onChange.lastCall.args[0];+ t.equal(colorRange.name, initialPalette.name, 'the default palette is first in the picker');+ t.deepEqual(+ colorRange.colors,+ initialPalette.colors,+ 'the default uses the first palette colors'+ );t.ok(colorRange.colors.length > 1, 'selecting a palette emits multiple colors');t.deepEqual(colorRange.colorLegends,@@ -349,15 +423,60 @@ test('Components -> LayerConfigurator -> contour groups expand independently witt.ok(groups[0].classList.contains('collapsed'), 'closes the color controls');t.ok(onChange.notCalled, 'expanding and collapsing groups does not change layer settings');- layer.updateLayerVisConfig({inputMode: 'grid'});+ t.notOk(groups[2].querySelector('.item-selector'), 'surface has no input-type selector');+ const input = groups[2].querySelector('.kg-range-slider__input');+ t.equal(input.value, '3', 'smoothing starts at three cells');+ fireEvent.change(input, {target: {value: '2'}});+ fireEvent.blur(input);+ t.deepEqual(onChange.lastCall.args[0], {smoothing: 2}, 'smoothing remains editable');+ const resolutionInput = Array.from(groups[2].querySelectorAll('.kg-range-slider__input')).find(+ element => element.value === '64'+ );+ t.ok(resolutionInput, 'grid resolution starts at 64 cells');+ fireEvent.change(resolutionInput, {target: {value: '128'}});+ fireEvent.blur(resolutionInput);+ t.deepEqual(+ onChange.lastCall.args[0],+ {gridResolution: 128},+ 'maximum axis resolution controls aggregation detail'+ );+ t.notOk(groups[2].classList.contains('collapsed'), 'editing settings keeps the group open');+ } finally {+ view.unmount();+ t.end();+ }+});++test('Components -> LayerConfigurator -> density custom levels use the cell count range', t => {+ const dataset = contourRangeDataset();+ const layer = contourRangeLayer(dataset);+ layer.updateLayerConfig({columns: layer.assignColumn('value', null)});+ layer.updateMeta({contourDomain: [0, 12]});+ const onChange = sinon.spy();+ const view = renderContourRange(layer, {[dataset.id]: dataset}, onChange);+ try {+ toggleConfigGroup(contourConfigGroup(view, 'Contour levels'));+ fireEvent.click(view.container.querySelector('#contour-range-customRange-switch'));+ t.deepEqual(+ onChange.lastCall.args[0],+ {customRange: true, minimum: 0, maximum: 12},+ 'initializes thresholds from point counts without a selected column'+ );+ layer.updateLayerVisConfig(onChange.lastCall.args[0]);view.update();- t.notOk(view.queryByText('Interpolation resolution'), 'grid mode hides interpolation settings');- t.notOk(groups[2].classList.contains('collapsed'), 'updating settings keeps the group open');- layer.updateLayerVisConfig({inputMode: 'points'});+ t.deepEqual(contourRangeLabels(view.container), [0, 12], 'shows the count range');+ dragContourHandle(view.container, 1, 50);+ t.deepEqual(+ onChange.lastCall.args[0],+ {minimum: 0, maximum: 6},+ 'density thresholds are editable'+ );+ layer.updateMeta({contourDomain: null});view.update();- t.ok(- view.queryByText('Interpolation resolution'),- 'scattered mode exposes interpolation settings'+ t.equal(+ view.container.querySelectorAll('.contour-level-range .kg-range-slider__handle').length,+ 0,+ 'clears the range when density has no observations');} finally {view.unmount();@@ -365,7 +484,7 @@ test('Components -> LayerConfigurator -> contour groups expand independently wit}});-test('Components -> LayerConfigurator -> contour invert reverses the saved fill direction', t => {+test('Components -> LayerConfigurator -> contour settings preserve saved directions without an Invert control', t => {for (const below of [true, false]) {const dataset = contourRangeDataset();const layer = contourRangeLayer(dataset);@@ -374,21 +493,21 @@ test('Components -> LayerConfigurator -> contour invert reverses the saved fillconst view = renderContourRange(layer, {[dataset.id]: dataset}, onChange);try {toggleConfigGroup(contourConfigGroup(view, 'Contour levels'));- const toggle = view.getByRole('checkbox', {name: 'Invert'});- t.equal(toggle.checked, !below, 'Invert reflects the saved direction without changing it');- t.ok(onChange.notCalled, 'loading the control preserves the saved map');- fireEvent.click(toggle);- t.deepEqual(onChange.lastCall.args[0], {below: !below}, 'updates the existing below setting');- layer.updateLayerVisConfig(onChange.lastCall.args[0]);- view.update();- t.equal(toggle.checked, below, 'reflects the inverted direction');- fireEvent.click(toggle);+ t.notOk(view.queryByRole('checkbox', {name: 'Invert'}), 'does not offer an Invert toggle');+ t.ok(onChange.notCalled, 'loading the controls preserves the saved map');+ fireEvent.click(view.container.querySelector('#contour-range-customRange-switch'));t.deepEqual(onChange.lastCall.args[0],- {below},- 'toggling again restores the original direction'+ {customRange: true, minimum: -2, maximum: 8},+ 'level edits update thresholds without changing direction'+ );+ layer.updateLayerVisConfig(onChange.lastCall.args[0]);+ view.update();+ t.equal(+ layer.config.visConfig.below,+ below,+ 'keeps the saved direction after editing levels');- t.notOk('invert' in layer.config.visConfig, 'does not introduce a new saved setting');} finally {view.unmount();}@@ -422,9 +541,23 @@ test('Components -> LayerConfigurator -> contour fill and outline groups retainfireEvent.mouseUp(document);t.deepEqual(onChange.lastCall.args[0],- {[savedProperty]: property === 'filled' ? 0.18 : 3.2},+ {[savedProperty]: property === 'filled' ? 0.6 : 3.2},`${controlLabel} slider edits only its own setting`);+ if (property === 'filled') {+ for (const percent of [0, 100]) {+ fireEvent.mouseDown(group.querySelectorAll('.kg-range-slider__handle')[1], {+ clientX: percent+ });+ fireEvent.mouseMove(document, {clientX: percent});+ fireEvent.mouseUp(document);+ t.deepEqual(+ onChange.lastCall.args[0],+ {fillOpacity: percent / 100},+ `fill opacity can reach ${percent}%`+ );+ }+ }t.ok(controls.queryByText(controlLabel), `${label} exposes its control`);fireEvent.click(toggle);t.deepEqual(onChange.lastCall.args[0], {[property]: false}, `disables only ${label}`);@@ -552,6 +685,83 @@ test('Components -> LayerConfigurator -> contour custom range starts with the co}});+test('Components -> LayerConfigurator -> sparse weighted contours retain usable custom thresholds', t => {+ for (const weights of [+ [10, 20],+ [10, 10],+ [-20, -10]+ ]) {+ const dataset = contourRangeDataset(+ 'sparse-contour-range',+ weights.map((value, index) => [index, index, value]),+ ['longitude', 'latitude', 'value']+ );+ const layer = new LayerClasses.contour({+ id: 'contour-range',+ dataId: dataset.id,+ columns: {+ lng: {value: 'longitude', fieldIdx: 0},+ lat: {value: 'latitude', fieldIdx: 1},+ value: {value: 'value', fieldIdx: 2}+ }+ });+ layer.updateLayerVisConfig({gridResolution: 32});+ const datasets = {[dataset.id]: dataset};+ const automatic = layer.formatLayerData(datasets).data;+ t.ok(automatic.length > 0, 'sparse weighted samples generate automatic contours');+ const minimum = Math.min(...weights);+ const maximum = Math.max(...weights);+ if (minimum > 0) {+ t.ok(+ automatic.every(feature => feature.properties.threshold < minimum),+ 'smoothing puts the surface below the raw column minimum'+ );+ }++ const onChange = sinon.spy();+ const view = renderContourRange(layer, datasets, onChange);+ try {+ toggleConfigGroup(contourConfigGroup(view, 'Contour levels'));+ fireEvent.click(view.container.querySelector('#contour-range-customRange-switch'));+ const range = [Math.min(0, minimum), Math.max(0, maximum)];+ t.deepEqual(+ onChange.lastCall.args[0],+ {customRange: true, minimum: range[0], maximum: range[1]},+ 'custom levels include the empty-cell baseline and raw weights'+ );+ layer.updateLayerVisConfig(onChange.lastCall.args[0]);+ view.update();+ t.ok(layer.formatLayerData(datasets).data.length > 0, 'enabling custom range keeps contours');+ t.deepEqual(+ contourRangeLabels(view.container),+ range,+ 'the slider exposes the surface range'+ );++ // Narrow the thresholds entirely into the smoothed surface, below the positive raw weights.+ if (minimum > 0) {+ dragContourHandle(view.container, 1, 10);+ layer.updateLayerVisConfig(onChange.lastCall.args[0]);+ view.update();+ dragContourHandle(view.container, 0, 5);+ layer.updateLayerVisConfig(onChange.lastCall.args[0]);+ view.update();+ const contours = layer.formatLayerData(datasets).data;+ t.ok(contours.length > 0, 'both handles can select thresholds that restore peak contours');+ t.ok(+ contours.every(+ feature => feature.properties.threshold > 0 && feature.properties.threshold < minimum+ ),+ 'restored contours enclose positive peaks below the raw minimum'+ );+ }+ } finally {+ view.unmount();+ }+ }+ t.end();+});+test('Components -> LayerConfigurator -> contour slider bounds follow the full selected column and dataset', t => {const dataset = contourRangeDataset('contour-range-data', [[-2.25, 1000.125],