Skip to content

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

feat(dataset-ops): suitability analysis (#3799)

Igor Dykhtaf999fa696c20
diff --git a/docs/user-guides/dataset-operations.md b/docs/user-guides/dataset-operations.md
index 9da6c7029..f23498e85 100644
--- a/docs/user-guides/dataset-operations.md
+++ b/docs/user-guides/dataset-operations.md
@@ -7,6 +7,7 @@ Open the **⋯** menu on a local dataset in the Layers catalog to:
- **Group by** one column and aggregate the rest
- **Join** two tables on a shared key (left, inner, or full)
- **Spatial join** a **target dataset** to a **join dataset** with a spatial join operation (intersects, equals, crosses, overlaps, within, touches)
+- **Suitability analysis** rank rows by a weighted combination of numeric columns
Operations run entirely in the browser. They are available for local (and remote file) tables, and are hidden for vector tiles, raster tiles, WMS, and 3D tiles.
@@ -58,6 +59,35 @@ Choose a **Join Operation**:
Distance joins and geometry merge are not included. For SQL predicates, use the [SQL/DuckDB Data Explorer](./sql-data-explorer.md).
+## Suitability analysis
+
+Rank every row by a weighted combination of numeric columns. The result is a new table with a `score` column (source columns are kept unless you uncheck them). When the result has geometry, a layer is created the same way as for other dataset operations, and the default color field prefers `score`.
+
+The panel is arranged like this:
+
+1. **Fields & Weights** — numeric columns that contribute to the score, each with a 0–1 weight
+2. **Scoring Options** — how weights and values are standardized, the score column name, and which source columns to keep
+3. **Result name**
+
+A row scores blank when any selected column is missing a value, so partial rows do not look like low scores.
+
+**Weight standardization**
+
+| Option | Effect |
+| --- | --- |
+| Normalize | Divide each weight by the sum of selected weights so they add to 1 |
+| Raw | Use the slider values as-is |
+
+**Data standardization** (applied to each selected column before weighting)
+
+| Option | Effect |
+| --- | --- |
+| Range | Map values onto 0–1: `(value − min) / (max − min)` |
+| Z-score | `(value − mean) / standard deviation` |
+| Raw | Leave the column unchanged |
+
+If a column has no range or no deviation, it is left unchanged. The score is then the weighted sum of those standardized values.
+
## Saving maps
Result tables are snapshots. Deleting a source dataset does not remove the result. Re-running an operation with the same result name replaces that table so existing layers keep their bindings.
diff --git a/src/actions/src/action-types.ts b/src/actions/src/action-types.ts
index 9ce1a9bde..39545ceff 100644
--- a/src/actions/src/action-types.ts
+++ b/src/actions/src/action-types.ts
@@ -134,6 +134,9 @@ export const ActionTypes = {
ADD_SPATIAL_JOIN: `${ACTION_PREFIX}ADD_SPATIAL_JOIN`,
SET_SPATIAL_JOIN_CONFIG: `${ACTION_PREFIX}SET_SPATIAL_JOIN_CONFIG`,
RUN_SPATIAL_JOIN: `${ACTION_PREFIX}RUN_SPATIAL_JOIN`,
+ ADD_SUITABILITY: `${ACTION_PREFIX}ADD_SUITABILITY`,
+ SET_SUITABILITY_CONFIG: `${ACTION_PREFIX}SET_SUITABILITY_CONFIG`,
+ RUN_SUITABILITY: `${ACTION_PREFIX}RUN_SUITABILITY`,
REMOVE_DATASET_OP: `${ACTION_PREFIX}REMOVE_DATASET_OP`,
ADD_TO_DATASET: `${ACTION_PREFIX}ADD_TO_DATASET`,
REMOVE_FROM_DATASET: `${ACTION_PREFIX}REMOVE_FROM_DATASET`,
diff --git a/src/actions/src/vis-state-actions.ts b/src/actions/src/vis-state-actions.ts
index 946a07465..8182e5bfa 100644
--- a/src/actions/src/vis-state-actions.ts
+++ b/src/actions/src/vis-state-actions.ts
@@ -5,7 +5,7 @@
import {default as ActionTypes} from './action-types';
import {FileCacheItem, ZipArchiveExpansion} from '@kepler.gl/processors';
import {Layer, LayerBaseConfig} from '@kepler.gl/layers';
-import {GroupByOp, JoinOp, KeplerTable} from '@kepler.gl/table';
+import {GroupByOp, JoinOp, KeplerTable, SuitabilityOp} from '@kepler.gl/table';
import {
AddDataToMapOptions,
AddDataToMapPayload,
@@ -2644,6 +2644,48 @@ export function runSpatialJoin(
};
}
+export type AddSuitabilityUpdaterAction = {
+ dataId: string;
+};
+
+export function addSuitability(
+ dataId: string
+): Merge<AddSuitabilityUpdaterAction, {type: typeof ActionTypes.ADD_SUITABILITY}> {
+ return {
+ type: ActionTypes.ADD_SUITABILITY,
+ dataId
+ };
+}
+
+export type SetSuitabilityConfigUpdaterAction = {
+ id: string;
+ config: Partial<SuitabilityOp>;
+};
+
+export function setSuitabilityConfig(
+ id: string,
+ config: Partial<SuitabilityOp>
+): Merge<SetSuitabilityConfigUpdaterAction, {type: typeof ActionTypes.SET_SUITABILITY_CONFIG}> {
+ return {
+ type: ActionTypes.SET_SUITABILITY_CONFIG,
+ id,
+ config
+ };
+}
+
+export type RunSuitabilityUpdaterAction = {
+ id: string;
+};
+
+export function runSuitability(
+ id: string
+): Merge<RunSuitabilityUpdaterAction, {type: typeof ActionTypes.RUN_SUITABILITY}> {
+ return {
+ type: ActionTypes.RUN_SUITABILITY,
+ id
+ };
+}
+
export type RemoveDatasetOpUpdaterAction = {
id: string;
};
diff --git a/src/components/src/common/icons/index.tsx b/src/components/src/common/icons/index.tsx
index 4a037b734..9ec3a67e5 100644
--- a/src/components/src/common/icons/index.tsx
+++ b/src/components/src/common/icons/index.tsx
@@ -81,6 +81,7 @@ export {default as Settings} from './settings';
export {default as Search} from './search';
export {default as SpatialJoin} from './spatial-join';
export {default as Split} from './split';
+export {default as Suitability} from './suitability';
export {default as Trash} from './trash';
export {default as Overflow} from './overflow';
export {default as VertDots} from './vert-dots';
diff --git a/src/components/src/common/icons/suitability.tsx b/src/components/src/common/icons/suitability.tsx
new file mode 100644
index 000000000..c11a7d83e
--- /dev/null
+++ b/src/components/src/common/icons/suitability.tsx
@@ -0,0 +1,26 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React, {Component} from 'react';
+import Base, {BaseProps} from './base';
+
+export default class Suitability extends Component<Partial<BaseProps>> {
+ static defaultProps = {
+ height: '16px',
+ viewBox: '0 0 16 16',
+ predefinedClassName: 'data-ex-icons-suitability'
+ };
+
+ render() {
+ return (
+ <Base {...this.props}>
+ <path d="M1 12.5h4v2.5H1zM6 8.5h4V15H6zM11 3.5h4V15h-4z" />
+ <path
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M15 1.2 8.9 6.1 5.7 4 0.6 7.6l0.8 1.1 4.4-3.1 3.2 2.1 6.7-5.4z"
+ />
+ </Base>
+ );
+ }
+}
diff --git a/src/components/src/index.ts b/src/components/src/index.ts
index c26e92ee9..b36f20bce 100644
--- a/src/components/src/index.ts
+++ b/src/components/src/index.ts
@@ -141,6 +141,7 @@ export {default as DatasetOpsPanelsFactory} from './side-panel/dataset-ops/datas
export {default as GroupByPanelFactory} from './side-panel/dataset-ops/group-by-panel';
export {default as JoinPanelFactory} from './side-panel/dataset-ops/join-panel';
export {default as SpatialJoinPanelFactory} from './side-panel/dataset-ops/spatial-join-panel';
+export {default as SuitabilityPanelFactory} from './side-panel/dataset-ops/suitability-panel';
export {default as SourceDataSelectorFactory} from './side-panel/common/source-data-selector';
export {default as FilterManagerFactory} from './side-panel/filter-manager';
diff --git a/src/components/src/kepler-gl.tsx b/src/components/src/kepler-gl.tsx
index 65c71cddb..a5429bd2c 100644
--- a/src/components/src/kepler-gl.tsx
+++ b/src/components/src/kepler-gl.tsx
@@ -240,6 +240,7 @@ export const sidePanelSelector = (props: KeplerGLProps, availableProviders, filt
overlayBlending: props.visState.overlayBlending,
groupBys: props.visState.groupBys,
joins: props.visState.joins,
+ suitabilities: props.visState.suitabilities,
width: props.sidePanelWidth ?? DEFAULT_KEPLER_GL_PROPS.sidePanelWidth,
availableProviders,
diff --git a/src/components/src/side-panel.tsx b/src/components/src/side-panel.tsx
index 40414a413..ffe880387 100644
--- a/src/components/src/side-panel.tsx
+++ b/src/components/src/side-panel.tsx
@@ -137,7 +137,8 @@ export default function SidePanelFactory(
version,
width,
groupBys,
- joins
+ joins,
+ suitabilities
} = props;
const {openDeleteModal, toggleModal, toggleSidePanel} = uiStateActions;
const {activeSidePanel} = uiState;
@@ -188,7 +189,7 @@ export default function SidePanelFactory(
any
>;
const PanelComponent = currentPanel?.component;
- const datasetOpOpen = hasActiveDatasetOp(groupBys, joins);
+ const datasetOpOpen = hasActiveDatasetOp(groupBys, joins, suitabilities);
return (
<Sidebar
@@ -230,6 +231,7 @@ export default function SidePanelFactory(
datasets={datasets}
groupBys={groupBys}
joins={joins}
+ suitabilities={suitabilities}
visStateActions={visStateActions}
/>
) : (
diff --git a/src/components/src/side-panel/common/dataset-title.tsx b/src/components/src/side-panel/common/dataset-title.tsx
index 32d066a81..0bab0c8d5 100644
--- a/src/components/src/side-panel/common/dataset-title.tsx
+++ b/src/components/src/side-panel/common/dataset-title.tsx
@@ -134,6 +134,7 @@ export type DatasetTitleProps = {
addGroupBy?: ActionHandler<typeof VisStateActions.addGroupBy>;
addJoin?: ActionHandler<typeof VisStateActions.addJoin>;
addSpatialJoin?: ActionHandler<typeof VisStateActions.addSpatialJoin>;
+ addSuitability?: ActionHandler<typeof VisStateActions.addSuitability>;
replaceDataset?: ActionHandler<typeof openReplaceDatasetModal>;
};
@@ -224,6 +225,7 @@ export default function DatasetTitleFactory(
addGroupBy,
addJoin,
addSpatialJoin,
+ addSuitability,
replaceDataset
}) => {
const [displayColorPicker, setDisplayColorPicker] = useState(false);
@@ -298,6 +300,7 @@ export default function DatasetTitleFactory(
addGroupBy={addGroupBy}
addJoin={addJoin}
addSpatialJoin={addSpatialJoin}
+ addSuitability={addSuitability}
replaceDataset={replaceDataset}
showDeleteDataset={showDeleteDataset}
removeDataset={removeDataset}
diff --git a/src/components/src/side-panel/common/source-data-catalog.tsx b/src/components/src/side-panel/common/source-data-catalog.tsx
index e81c8aa94..7ef492de4 100644
--- a/src/components/src/side-panel/common/source-data-catalog.tsx
+++ b/src/components/src/side-panel/common/source-data-catalog.tsx
@@ -49,6 +49,7 @@ export type SourceDataCatalogProps = {
addGroupBy?: ActionHandler<typeof VisStateActions.addGroupBy>;
addJoin?: ActionHandler<typeof VisStateActions.addJoin>;
addSpatialJoin?: ActionHandler<typeof VisStateActions.addSpatialJoin>;
+ addSuitability?: ActionHandler<typeof VisStateActions.addSuitability>;
replaceDataset?: ReplaceDatasetHandler;
};
@@ -70,6 +71,7 @@ function SourceDataCatalogFactory(
addGroupBy,
addJoin,
addSpatialJoin,
+ addSuitability,
replaceDataset
}: SourceDataCatalogProps) => {
const [openRefreshSettingsId, setOpenRefreshSettingsId] = useState<string | null>(null);
@@ -97,6 +99,7 @@ function SourceDataCatalogFactory(
addGroupBy={addGroupBy}
addJoin={addJoin}
addSpatialJoin={addSpatialJoin}
+ addSuitability={addSuitability}
replaceDataset={replaceDataset}
onToggleRefreshSettings={
(refreshDataset || updateDatasetProps) &&
diff --git a/src/components/src/side-panel/dataset-ops/dataset-op-panel.tsx b/src/components/src/side-panel/dataset-ops/dataset-op-panel.tsx
index 8c2477670..402bee509 100644
--- a/src/components/src/side-panel/dataset-ops/dataset-op-panel.tsx
+++ b/src/components/src/side-panel/dataset-ops/dataset-op-panel.tsx
@@ -336,7 +336,13 @@ export function DatasetOpPanel({
<Button secondary small type="button" onClick={onClose}>
<FormattedMessage id="datasetOps.cancel" />
</Button>
- <Button small type="button" disabled={!canRun} onClick={onRun}>
+ <Button
+ className="dataset-ops-panel__run"
+ small
+ type="button"
+ disabled={!canRun}
+ onClick={onRun}
+ >
<FormattedMessage id="datasetOps.run" />
</Button>
</Actions>
diff --git a/src/components/src/side-panel/dataset-ops/dataset-ops-menu.spec.tsx b/src/components/src/side-panel/dataset-ops/dataset-ops-menu.spec.tsx
index 17ad8ebc1..6ca521aeb 100644
--- a/src/components/src/side-panel/dataset-ops/dataset-ops-menu.spec.tsx
+++ b/src/components/src/side-panel/dataset-ops/dataset-ops-menu.spec.tsx
@@ -10,6 +10,7 @@ import {renderWithTheme} from 'test/helpers/component-jest-utils';
import {DatasetOpsMenu} from './dataset-ops-menu';
import GroupByPanelFactory from './group-by-panel';
import DatasetOpPanel, {CollapsibleSection, fieldNameFromSelector} from './dataset-op-panel';
+import SuitabilityPanelFactory from './suitability-panel';
function MockFieldSelector({
fields,
@@ -36,6 +37,23 @@ function MockFieldSelector({
);
}
+function MockRangeSlider({
+ value1,
+ onChange
+}: {
+ value1: number;
+ onChange: (value: [number, number]) => void;
+}) {
+ return (
+ <input
+ type="number"
+ className="mock-range-slider"
+ value={value1}
+ onChange={event => onChange([0, Number(event.target.value)])}
+ />
+ );
+}
+
describe('DatasetOpsMenu', () => {
beforeEach(() => {
initApplicationConfig({enableDatasetOps: true});
@@ -110,6 +128,21 @@ describe('DatasetOpsMenu', () => {
expect(addGroupBy).toHaveBeenCalledWith('cities');
});
+ test('offers suitability analysis for local datasets', () => {
+ const addSuitability = jest.fn();
+ const {container} = renderWithTheme(
+ <DatasetOpsMenu
+ datasetId="cities"
+ dataset={{type: 'local'}}
+ addSuitability={addSuitability}
+ />
+ );
+
+ fireEvent.click(container.querySelector('.dataset-ops-menu__toggle') as HTMLElement);
+ fireEvent.click(document.querySelector('.dataset-ops-menu__suitability') as HTMLButtonElement);
+ expect(addSuitability).toHaveBeenCalledWith('cities');
+ });
+
test('moves remove dataset into the more settings menu', () => {
const removeDataset = jest.fn();
const {container} = renderWithTheme(
@@ -383,3 +416,128 @@ describe('DatasetOpPanel layout', () => {
expect(onClose).toHaveBeenCalled();
});
});
+
+describe('SuitabilityPanel', () => {
+ const SuitabilityPanel = SuitabilityPanelFactory(MockRangeSlider as any);
+
+ const datasets = {
+ sites: {
+ id: 'sites',
+ label: 'sites',
+ fields: [
+ {name: 'name', displayName: 'name', type: 'string'},
+ {name: 'access', displayName: 'access', type: 'integer'},
+ {name: 'cost', displayName: 'cost', type: 'real'}
+ ] as Field[]
+ }
+ } as unknown as Datasets;
+
+ const op = (overrides = {}) => ({
+ id: 'op-1',
+ dataId: 'sites',
+ weights: {access: 1, cost: 1},
+ weightStandardization: 'normalize' as const,
+ dataStandardization: 'range' as const,
+ outputFieldName: 'score',
+ resultId: 'out',
+ resultLabel: 'sites suitability',
+ isConfigActive: true,
+ ...overrides
+ });
+
+ test('lists only numeric fields as weights and toggles them off', () => {
+ const setSuitabilityConfig = jest.fn();
+ const {container} = renderWithTheme(
+ <SuitabilityPanel
+ op={op()}
+ datasets={datasets}
+ setSuitabilityConfig={setSuitabilityConfig}
+ runSuitability={jest.fn()}
+ removeDatasetOp={jest.fn()}
+ />
+ );
+
+ const list = container.querySelector('.dataset-ops-column-list') as HTMLElement;
+ expect(list.textContent).toContain('access');
+ expect(list.textContent).toContain('cost');
+ expect(list.textContent).not.toContain('name');
+
+ fireEvent.click(list.querySelectorAll('input[type="checkbox"]')[0]);
+ expect(setSuitabilityConfig).toHaveBeenCalledWith('op-1', {weights: {cost: 1}});
+ });
+
+ test('cannot run without a weighted field', () => {
+ const runButtonFor = (weights: Record<string, number>) => {
+ const {container} = renderWithTheme(
+ <SuitabilityPanel
+ op={op({weights})}
+ datasets={datasets}
+ setSuitabilityConfig={jest.fn()}
+ runSuitability={jest.fn()}
+ removeDatasetOp={jest.fn()}
+ />
+ );
+ return container.querySelector('.dataset-ops-panel__run') as HTMLButtonElement;
+ };
+
+ expect(runButtonFor({}).disabled).toBe(true);
+ expect(runButtonFor({access: 1}).disabled).toBe(false);
+ });
+
+ test('select all restores a default weight for every numeric field', () => {
+ const setSuitabilityConfig = jest.fn();
+ const {container} = renderWithTheme(
+ <SuitabilityPanel
+ op={op({weights: {access: 0.5}})}
+ datasets={datasets}
+ setSuitabilityConfig={setSuitabilityConfig}
+ runSuitability={jest.fn()}
+ removeDatasetOp={jest.fn()}
+ />
+ );
+
+ fireEvent.click(container.querySelector('.dataset-ops-suitability__select-all') as HTMLElement);
+ expect(setSuitabilityConfig).toHaveBeenCalledWith('op-1', {weights: {access: 1, cost: 1}});
+ });
+
+ test('moving a slider updates only that field weight', () => {
+ const setSuitabilityConfig = jest.fn();
+ const {container} = renderWithTheme(
+ <SuitabilityPanel
+ op={op()}
+ datasets={datasets}
+ setSuitabilityConfig={setSuitabilityConfig}
+ runSuitability={jest.fn()}
+ removeDatasetOp={jest.fn()}
+ />
+ );
+
+ fireEvent.change(container.querySelectorAll('.mock-range-slider')[1], {
+ target: {value: '0.25'}
+ });
+ expect(setSuitabilityConfig).toHaveBeenCalledWith('op-1', {
+ weights: {access: 1, cost: 0.25}
+ });
+ });
+
+ test('the column picker includes every source column, not just numeric ones', () => {
+ const setSuitabilityConfig = jest.fn();
+ const {container} = renderWithTheme(
+ <SuitabilityPanel
+ op={op()}
+ datasets={datasets}
+ setSuitabilityConfig={setSuitabilityConfig}
+ runSuitability={jest.fn()}
+ removeDatasetOp={jest.fn()}
+ />
+ );
+
+ fireEvent.click(container.querySelector('.dataset-ops-collapsible__header') as HTMLElement);
+ const lists = container.querySelectorAll('.dataset-ops-column-list');
+ const picker = lists[lists.length - 1] as HTMLElement;
+ expect(picker.children.length).toBe(3);
+
+ fireEvent.click(picker.querySelectorAll('input[type="checkbox"]')[0]);
+ expect(setSuitabilityConfig).toHaveBeenCalledWith('op-1', {columns: ['access', 'cost']});
+ });
+});
diff --git a/src/components/src/side-panel/dataset-ops/dataset-ops-menu.tsx b/src/components/src/side-panel/dataset-ops/dataset-ops-menu.tsx
index e733d1986..bf97f3b52 100644
--- a/src/components/src/side-panel/dataset-ops/dataset-ops-menu.tsx
+++ b/src/components/src/side-panel/dataset-ops/dataset-ops-menu.tsx
@@ -13,7 +13,15 @@ import {
openReplaceDatasetModal
} from '@kepler.gl/actions';
-import {Grouping, Join, Overflow, Replace, SpatialJoin, Trash} from '../../common/icons';
+import {
+ Grouping,
+ Join,
+ Overflow,
+ Replace,
+ SpatialJoin,
+ Suitability,
+ Trash
+} from '../../common/icons';
import {Tooltip} from '../../common/styled-components';
import Portaled from '../../common/portaled';
import {
@@ -33,6 +41,7 @@ export type DatasetOpsMenuProps = {
addGroupBy?: ActionHandler<typeof VisStateActions.addGroupBy>;
addJoin?: ActionHandler<typeof VisStateActions.addJoin>;
addSpatialJoin?: ActionHandler<typeof VisStateActions.addSpatialJoin>;
+ addSuitability?: ActionHandler<typeof VisStateActions.addSuitability>;
replaceDataset?: ActionHandler<typeof openReplaceDatasetModal>;
showDeleteDataset?: boolean;
removeDataset?: ActionHandler<typeof openDeleteModal>;
@@ -44,6 +53,7 @@ export function DatasetOpsMenu({
addGroupBy,
addJoin,
addSpatialJoin,
+ addSuitability,
replaceDataset,
showDeleteDataset,
removeDataset
@@ -54,7 +64,8 @@ export function DatasetOpsMenu({
const tabular = isTabularDatasetForOps(dataset);
const showReplace =
opsEnabled && Boolean(replaceDataset) && tabular && !dataset.metadata?.derivedDataset;
- const showOps = opsEnabled && tabular && Boolean(addGroupBy || addJoin || addSpatialJoin);
+ const showOps =
+ opsEnabled && tabular && Boolean(addGroupBy || addJoin || addSpatialJoin || addSuitability);
const showRemove = Boolean(showDeleteDataset && removeDataset);
const tooltipId = `dataset-ops-${datasetId}`;
const tooltipLabel = intl.formatMessage({id: 'datasetTitle.moreSettings'});
@@ -133,6 +144,15 @@ export function DatasetOpsMenu({
onClick: () => onSelect(addSpatialJoin)
});
}
+ if (showOps && addSuitability) {
+ opItems.push({
+ className: 'dataset-ops-menu__suitability',
+ labelId: 'datasetOps.suitability',
+ Icon: Suitability,
+ iconHeight: '14px',
+ onClick: () => onSelect(addSuitability)
+ });
+ }
return (
<>
diff --git a/src/components/src/side-panel/dataset-ops/dataset-ops-panels.tsx b/src/components/src/side-panel/dataset-ops/dataset-ops-panels.tsx
index 8844a69d2..8cbf69bb0 100644
--- a/src/components/src/side-panel/dataset-ops/dataset-ops-panels.tsx
+++ b/src/components/src/side-panel/dataset-ops/dataset-ops-panels.tsx
@@ -3,7 +3,7 @@
import React from 'react';
import styled from 'styled-components';
-import {GroupByOp, JoinOp} from '@kepler.gl/table';
+import {GroupByOp, JoinOp, SuitabilityOp} from '@kepler.gl/table';
import {Datasets} from '@kepler.gl/table';
import {VisStateActions} from '@kepler.gl/actions';
import {getApplicationConfig} from '@kepler.gl/utils';
@@ -11,6 +11,7 @@ import {getApplicationConfig} from '@kepler.gl/utils';
import GroupByPanelFactory from './group-by-panel';
import JoinPanelFactory from './join-panel';
import SpatialJoinPanelFactory from './spatial-join-panel';
+import SuitabilityPanelFactory from './suitability-panel';
const Panels = styled.div.attrs({
className: 'dataset-ops-panels'
@@ -22,28 +23,44 @@ const Panels = styled.div.attrs({
height: 100%;
`;
-DatasetOpsPanelsFactory.deps = [GroupByPanelFactory, JoinPanelFactory, SpatialJoinPanelFactory];
+DatasetOpsPanelsFactory.deps = [
+ GroupByPanelFactory,
+ JoinPanelFactory,
+ SpatialJoinPanelFactory,
+ SuitabilityPanelFactory
+];
export type DatasetOpsPanelsProps = {
datasets: Datasets;
groupBys?: GroupByOp[];
joins?: JoinOp[];
+ suitabilities?: SuitabilityOp[];
visStateActions: typeof VisStateActions;
};
-export function hasActiveDatasetOp(groupBys: GroupByOp[] = [], joins: JoinOp[] = []): boolean {
- return Boolean(groupBys.some(op => op.isConfigActive) || joins.some(op => op.isConfigActive));
+export function hasActiveDatasetOp(
+ groupBys: GroupByOp[] = [],
+ joins: JoinOp[] = [],
+ suitabilities: SuitabilityOp[] = []
+): boolean {
+ return Boolean(
+ groupBys.some(op => op.isConfigActive) ||
+ joins.some(op => op.isConfigActive) ||
+ suitabilities.some(op => op.isConfigActive)
+ );
}
function DatasetOpsPanelsFactory(
GroupByPanel: ReturnType<typeof GroupByPanelFactory>,
JoinPanel: ReturnType<typeof JoinPanelFactory>,
- SpatialJoinPanel: ReturnType<typeof SpatialJoinPanelFactory>
+ SpatialJoinPanel: ReturnType<typeof SpatialJoinPanelFactory>,
+ SuitabilityPanel: ReturnType<typeof SuitabilityPanelFactory>
) {
const DatasetOpsPanels: React.FC<DatasetOpsPanelsProps> = ({
datasets,
groupBys = [],
joins = [],
+ suitabilities = [],
visStateActions
}) => {
if (getApplicationConfig().enableDatasetOps === false) {
@@ -53,7 +70,8 @@ function DatasetOpsPanelsFactory(
const activeGroupBy = groupBys.find(op => op.isConfigActive);
const activeJoin = joins.find(op => op.isConfigActive && op.implementation !== 'spatial');
const activeSpatial = joins.find(op => op.isConfigActive && op.implementation === 'spatial');
- if (!activeGroupBy && !activeJoin && !activeSpatial) {
+ const activeSuitability = suitabilities.find(op => op.isConfigActive);
+ if (!activeGroupBy && !activeJoin && !activeSpatial && !activeSuitability) {
return null;
}
@@ -86,6 +104,15 @@ function DatasetOpsPanelsFactory(
removeDatasetOp={visStateActions.removeDatasetOp}
/>
) : null}
+ {activeSuitability ? (
+ <SuitabilityPanel
+ op={activeSuitability}
+ datasets={datasets}
+ setSuitabilityConfig={visStateActions.setSuitabilityConfig}
+ runSuitability={visStateActions.runSuitability}
+ removeDatasetOp={visStateActions.removeDatasetOp}
+ />
+ ) : null}
</Panels>
);
};
diff --git a/src/components/src/side-panel/dataset-ops/suitability-panel.tsx b/src/components/src/side-panel/dataset-ops/suitability-panel.tsx
new file mode 100644
index 000000000..4c5f3b14e
--- /dev/null
+++ b/src/components/src/side-panel/dataset-ops/suitability-panel.tsx
@@ -0,0 +1,289 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React, {useMemo} from 'react';
+import styled from 'styled-components';
+import {useIntl} from 'react-intl';
+import {FormattedMessage} from '@kepler.gl/localization';
+import {
+ DATA_STANDARDIZATION_OPTIONS,
+ DataStandardization,
+ DEFAULT_SUITABILITY_WEIGHT,
+ SUITABILITY_WEIGHT_RANGE,
+ SuitabilityOp,
+ WEIGHT_STANDARDIZATION_OPTIONS,
+ WeightStandardization,
+ defaultSuitabilityWeights,
+ isSuitabilityWeightField
+} from '@kepler.gl/table';
+import {Datasets} from '@kepler.gl/table';
+import {VisStateActions, ActionHandler} from '@kepler.gl/actions';
+
+import RangeSliderFactory from '../../common/range-slider';
+import ItemSelector from '../../common/item-selector/item-selector';
+import {Input, PanelLabel, SidePanelSection} from '../../common/styled-components';
+import {Suitability} from '../../common/icons';
+import DatasetOpPanel, {
+ CollapsibleSection,
+ DatasetOpHelp,
+ DatasetOpsAggRow,
+ DatasetOpsFieldName,
+ DatasetOpsSection,
+ DatasetOpsSectionTitle,
+ ResultNameInput,
+ ScrollableColumnList
+} from './dataset-op-panel';
+
+const WEIGHT_STEP = 0.05;
+
+const WeightRow = styled.div`
+ margin-bottom: 6px;
+
+ ${DatasetOpsAggRow} {
+ margin-bottom: 0;
+ }
+`;
+
+const WeightValue = styled.div`
+ flex: 0 0 auto;
+ font-size: 11px;
+ color: ${props => props.theme.subtextColor};
+ font-variant-numeric: tabular-nums;
+`;
+
+/**
+ * The slider bar is 4px tall and its handle overflows by 4px either side, so the row only
+ * needs enough height to keep the handle from clipping.
+ */
+const WeightSlider = styled.div<{$disabled?: boolean}>`
+ padding: 4px 0 4px 22px;
+ opacity: ${props => (props.$disabled ? 0.4 : 1)};
+ pointer-events: ${props => (props.$disabled ? 'none' : 'auto')};
+`;
+
+const SelectAllWeights = styled.span.attrs({
+ className: 'dataset-ops-suitability__select-all'
+})`
+ margin-left: auto;
+ color: ${props => props.theme.activeColor};
+ font-size: 11px;
+ cursor: pointer;
+`;
+
+SuitabilityPanelFactory.deps = [RangeSliderFactory];
+
+function SuitabilityPanelFactory(RangeSlider: ReturnType<typeof RangeSliderFactory>) {
+ const SuitabilityPanel: React.FC<{
+ op: SuitabilityOp;
+ datasets: Datasets;
+ setSuitabilityConfig: ActionHandler<typeof VisStateActions.setSuitabilityConfig>;
+ runSuitability: ActionHandler<typeof VisStateActions.runSuitability>;
+ removeDatasetOp: ActionHandler<typeof VisStateActions.removeDatasetOp>;
+ }> = ({op, datasets, setSuitabilityConfig, runSuitability, removeDatasetOp}) => {
+ const intl = useIntl();
+ const dataset = datasets[op.dataId];
+
+ const weightOptions = useMemo(
+ () =>
+ WEIGHT_STANDARDIZATION_OPTIONS.map(option => ({
+ id: option.id,
+ label: intl.formatMessage({id: option.labelId})
+ })),
+ [intl]
+ );
+ const dataOptions = useMemo(
+ () =>
+ DATA_STANDARDIZATION_OPTIONS.map(option => ({
+ id: option.id,
+ label: intl.formatMessage({id: option.labelId})
+ })),
+ [intl]
+ );
+
+ if (!dataset) {
+ return null;
+ }
+
+ const weightFields = dataset.fields.filter(isSuitabilityWeightField);
+ const allWeightsSelected = Boolean(
+ weightFields.length && weightFields.every(field => field.name in op.weights)
+ );
+ const selectedColumns = new Set(op.columns ?? dataset.fields.map(field => field.name));
+ const allColumnsSelected = dataset.fields.every(field => selectedColumns.has(field.name));
+
+ const onToggleWeight = (fieldName: string, enabled: boolean) => {
+ const weights = {...op.weights};
+ if (enabled) {
+ weights[fieldName] = weights[fieldName] ?? DEFAULT_SUITABILITY_WEIGHT;
+ } else {
+ delete weights[fieldName];
+ }
+ setSuitabilityConfig(op.id, {weights});
+ };
+
+ return (
+ <DatasetOpPanel
+ titleId="datasetOps.suitability"
+ titleIcon={<Suitability height="20px" />}
+ descriptionId="datasetOps.suitabilityHelp"
+ error={op.error}
+ onClose={() => removeDatasetOp(op.id)}
+ onRun={() => runSuitability(op.id)}
+ canRun={Object.keys(op.weights).length > 0}
+ >
+ <DatasetOpsSection sectionColor={dataset.color}>
+ <DatasetOpsSectionTitle>
+ <FormattedMessage id="datasetOps.suitabilityWeights" />
+ <DatasetOpHelp helpId="datasetOps.suitabilityWeightsHelp" />
+ {weightFields.length ? (
+ <SelectAllWeights
+ onClick={() =>
+ setSuitabilityConfig(op.id, {
+ weights: allWeightsSelected ? {} : defaultSuitabilityWeights(dataset.fields)
+ })
+ }
+ >
+ <FormattedMessage
+ id={allWeightsSelected ? 'datasetOps.unselectAll' : 'datasetOps.selectAll'}
+ />
+ </SelectAllWeights>
+ ) : null}
+ </DatasetOpsSectionTitle>
+ <ScrollableColumnList>
+ {weightFields.map(field => {
+ const weight = op.weights[field.name];
+ const enabled = field.name in op.weights;
+ return (
+ <WeightRow key={field.name}>
+ <DatasetOpsAggRow>
+ <input
+ type="checkbox"
+ checked={enabled}
+ onChange={e => onToggleWeight(field.name, e.target.checked)}
+ />
+ <DatasetOpsFieldName>{field.displayName || field.name}</DatasetOpsFieldName>
+ {enabled ? <WeightValue>{weight.toFixed(2)}</WeightValue> : null}
+ </DatasetOpsAggRow>
+ <WeightSlider $disabled={!enabled}>
+ <RangeSlider
+ range={SUITABILITY_WEIGHT_RANGE}
+ value0={SUITABILITY_WEIGHT_RANGE[0]}
+ value1={enabled ? weight : DEFAULT_SUITABILITY_WEIGHT}
+ step={WEIGHT_STEP}
+ isRanged={false}
+ showInput={false}
+ onChange={value =>
+ setSuitabilityConfig(op.id, {
+ weights: {...op.weights, [field.name]: value[1]}
+ })
+ }
+ />
+ </WeightSlider>
+ </WeightRow>
+ );
+ })}
+ </ScrollableColumnList>
+ </DatasetOpsSection>
+
+ <DatasetOpsSection>
+ <DatasetOpsSectionTitle>
+ <FormattedMessage id="datasetOps.suitabilityStandardization" />
+ <DatasetOpHelp helpId="datasetOps.suitabilityStandardizationHelp" />
+ </DatasetOpsSectionTitle>
+ <SidePanelSection>
+ <PanelLabel>
+ <FormattedMessage id="datasetOps.weightStandardization" />
+ </PanelLabel>
+ <ItemSelector
+ options={weightOptions}
+ selectedItems={
+ weightOptions.find(option => option.id === op.weightStandardization) || null
+ }
+ displayOption={option => option.label}
+ getOptionValue={option => option.id}
+ onChange={value =>
+ setSuitabilityConfig(op.id, {
+ weightStandardization: String(value) as WeightStandardization
+ })
+ }
+ searchable={false}
+ multiSelect={false}
+ />
+ </SidePanelSection>
+ <SidePanelSection>
+ <PanelLabel>
+ <FormattedMessage id="datasetOps.dataStandardization" />
+ </PanelLabel>
+ <ItemSelector
+ options={dataOptions}
+ selectedItems={
+ dataOptions.find(option => option.id === op.dataStandardization) || null
+ }
+ displayOption={option => option.label}
+ getOptionValue={option => option.id}
+ onChange={value =>
+ setSuitabilityConfig(op.id, {
+ dataStandardization: String(value) as DataStandardization
+ })
+ }
+ searchable={false}
+ multiSelect={false}
+ />
+ </SidePanelSection>
+ <SidePanelSection>
+ <PanelLabel>
+ <FormattedMessage id="datasetOps.scoreColumn" />
+ </PanelLabel>
+ <Input
+ type="text"
+ value={op.outputFieldName}
+ onChange={e => setSuitabilityConfig(op.id, {outputFieldName: e.target.value})}
+ />
+ </SidePanelSection>
+ <CollapsibleSection
+ titleId="datasetOps.columnsToInclude"
+ helpId="datasetOps.columnsToIncludeHelp"
+ selectAll={allColumnsSelected}
+ onToggleSelectAll={() =>
+ setSuitabilityConfig(op.id, {
+ columns: allColumnsSelected ? [] : dataset.fields.map(field => field.name)
+ })
+ }
+ >
+ <ScrollableColumnList>
+ {dataset.fields.map(field => {
+ const checked = selectedColumns.has(field.name);
+ return (
+ <DatasetOpsAggRow key={field.name}>
+ <input
+ type="checkbox"
+ checked={checked}
+ onChange={() => {
+ const next = dataset.fields
+ .map(item => item.name)
+ .filter(name =>
+ name === field.name ? !checked : selectedColumns.has(name)
+ );
+ setSuitabilityConfig(op.id, {columns: next});
+ }}
+ />
+ <DatasetOpsFieldName>{field.displayName || field.name}</DatasetOpsFieldName>
+ </DatasetOpsAggRow>
+ );
+ })}
+ </ScrollableColumnList>
+ </CollapsibleSection>
+ </DatasetOpsSection>
+
+ <ResultNameInput
+ value={op.resultLabel}
+ onChange={resultLabel => setSuitabilityConfig(op.id, {resultLabel})}
+ />
+ </DatasetOpPanel>
+ );
+ };
+
+ return SuitabilityPanel;
+}
+
+export default SuitabilityPanelFactory;
diff --git a/src/components/src/side-panel/filter-manager.tsx b/src/components/src/side-panel/filter-manager.tsx
index f4890d505..713744e06 100644
--- a/src/components/src/side-panel/filter-manager.tsx
+++ b/src/components/src/side-panel/filter-manager.tsx
@@ -159,6 +159,7 @@ function FilterManagerFactory(
addGroupBy={visStateActions.addGroupBy}
addJoin={visStateActions.addJoin}
addSpatialJoin={visStateActions.addSpatialJoin}
+ addSuitability={visStateActions.addSuitability}
/>
<FilterList
filtersByIndex={filtersByIndex}
diff --git a/src/components/src/side-panel/layer-panel/dataset-layer-section.tsx b/src/components/src/side-panel/layer-panel/dataset-layer-section.tsx
index 63181e069..4ca46829b 100644
--- a/src/components/src/side-panel/layer-panel/dataset-layer-section.tsx
+++ b/src/components/src/side-panel/layer-panel/dataset-layer-section.tsx
@@ -126,6 +126,7 @@ function DatasetLayerSectionFactory(
addGroupBy={visStateActions.addGroupBy}
addJoin={visStateActions.addJoin}
addSpatialJoin={visStateActions.addSpatialJoin}
+ addSuitability={visStateActions.addSuitability}
/>
<LayerList
datasets={datasets}
diff --git a/src/components/src/side-panel/layer-panel/dataset-section.tsx b/src/components/src/side-panel/layer-panel/dataset-section.tsx
index 165bffee0..9d81ca02c 100644
--- a/src/components/src/side-panel/layer-panel/dataset-section.tsx
+++ b/src/components/src/side-panel/layer-panel/dataset-section.tsx
@@ -110,6 +110,7 @@ function DatasetSectionFactory(
addGroupBy={visStateActions?.addGroupBy}
addJoin={visStateActions?.addJoin}
addSpatialJoin={visStateActions?.addSpatialJoin}
+ addSuitability={visStateActions?.addSuitability}
/>
)}
</StyledDatasetSection>
diff --git a/src/components/src/types.ts b/src/components/src/types.ts
index 5cac5d0a2..c7356cee4 100644
--- a/src/components/src/types.ts
+++ b/src/components/src/types.ts
@@ -12,7 +12,7 @@ import {
MapStateActions,
UIStateActions
} from '@kepler.gl/actions';
-import {Datasets, GroupByOp, JoinOp} from '@kepler.gl/table';
+import {Datasets, GroupByOp, JoinOp, SuitabilityOp} from '@kepler.gl/table';
export type BaseComponentProps = PropsWithChildren<HTMLAttributes<unknown>>;
@@ -39,6 +39,7 @@ export type SidePanelProps = {
width: number;
datasets: Datasets;
groupBys?: GroupByOp[];
+ suitabilities?: SuitabilityOp[];
joins?: JoinOp[];
uiStateActions: typeof UIStateActions;
visStateActions: typeof VisStateActions;
diff --git a/src/localization/src/translations/en.ts b/src/localization/src/translations/en.ts
index 523f2a947..3c60f038b 100644
--- a/src/localization/src/translations/en.ts
+++ b/src/localization/src/translations/en.ts
@@ -507,6 +507,27 @@ export default {
median: 'Median',
countUnique: 'Unique',
merge: 'Merge'
+ },
+ suitability: 'Suitability Analysis',
+ suitabilityHelp:
+ 'Rank rows by a weighted combination of numeric columns. The result is added as a new dataset with a score column. The new layer is colored by that column when possible.',
+ suitabilityWeights: 'Fields & Weights',
+ suitabilityWeightsHelp:
+ 'Pick the numeric columns that contribute to the score and how much each one matters. A row scores blank when any selected column is missing a value.',
+ suitabilityStandardization: 'Scoring Options',
+ suitabilityStandardizationHelp:
+ 'Standardization puts columns measured on different scales onto a comparable footing before they are combined.',
+ weightStandardization: 'Weight standardization',
+ dataStandardization: 'Data standardization',
+ scoreColumn: 'Score column',
+ weightStandardizationOption: {
+ raw: 'Raw',
+ normalize: 'Normalize'
+ },
+ dataStandardizationOption: {
+ raw: 'Raw',
+ range: 'Range',
+ zScore: 'Z-score'
}
},
datasetInfo: {
diff --git a/src/reducers/src/dataset-ops-updaters.spec.ts b/src/reducers/src/dataset-ops-updaters.spec.ts
index 592594e7d..43ec86da6 100644
--- a/src/reducers/src/dataset-ops-updaters.spec.ts
+++ b/src/reducers/src/dataset-ops-updaters.spec.ts
@@ -258,3 +258,124 @@ describe('dataset ops vis-state', () => {
expect(saved.config.config.visState.groupBys?.[0].fieldName).toBe('region');
});
});
+
+describe('suitability vis-state', () => {
+ beforeEach(() => {
+ drainTasksForTesting();
+ });
+
+ function siteState(): VisState {
+ const sites = makeTable(
+ 'sites',
+ [
+ {name: 'name', type: ALL_FIELD_TYPES.string},
+ {name: 'lat', type: ALL_FIELD_TYPES.real},
+ {name: 'lng', type: ALL_FIELD_TYPES.real},
+ {name: 'access', type: ALL_FIELD_TYPES.integer},
+ {name: 'cost', type: ALL_FIELD_TYPES.integer}
+ ],
+ [
+ ['a', 0, 0, 0, 100],
+ ['b', 1, 1, 5, 200],
+ ['c', 2, 2, 10, 300]
+ ]
+ );
+ return {...INITIAL_VIS_STATE, datasets: {sites}};
+ }
+
+ test('addSuitability seeds numeric weights and a short random result name', () => {
+ const state = reduceVisState(siteState(), VisStateActions.addSuitability('sites'));
+
+ expect(state.suitabilities).toHaveLength(1);
+ const op = state.suitabilities[0];
+ expect(op.weights).toEqual({lat: 1, lng: 1, access: 1, cost: 1});
+ expect(op.weightStandardization).toBe('normalize');
+ expect(op.dataStandardization).toBe('range');
+ expect(op.outputFieldName).toBe('score');
+ expect(op.resultLabel).toMatch(/^suitability-\d{2}$/);
+ });
+
+ test('opening a suitability op closes an open group by', () => {
+ let state = reduceVisState(siteState(), VisStateActions.addGroupBy('sites'));
+ expect(state.groupBys[0].isConfigActive).toBe(true);
+
+ state = reduceVisState(state, VisStateActions.addSuitability('sites'));
+ expect(state.groupBys[0].isConfigActive).toBe(false);
+ expect(state.suitabilities[0].isConfigActive).toBe(true);
+
+ state = reduceVisState(state, VisStateActions.addGroupBy('sites'));
+ expect(state.suitabilities[0].isConfigActive).toBe(false);
+ });
+
+ test('runSuitability adds a scored dataset and a default layer', () => {
+ let state = reduceVisState(siteState(), VisStateActions.addSuitability('sites'));
+ const op = state.suitabilities[0];
+
+ state = reduceVisState(
+ state,
+ VisStateActions.setSuitabilityConfig(op.id, {weights: {access: 1, cost: 1}})
+ );
+ state = reduceVisState(state, VisStateActions.runSuitability(op.id));
+ state = flushCreateTableTasks(state);
+
+ const result = state.datasets[op.resultId];
+ expect(result).toBeTruthy();
+ expect(result.metadata.derivedDataset).toEqual({
+ type: 'suitability',
+ sourceDataIds: ['sites'],
+ operationId: op.id
+ });
+ expect(result.fields.map(field => field.name)).toContain('score');
+ expect(state.suitabilities[0].isConfigActive).toBe(false);
+
+ const layer = state.layers.find(item => item.config.dataId === op.resultId);
+ expect(layer).toBeTruthy();
+ expect(layer?.config.colorField?.name).toBe('score');
+ });
+
+ test('running without a weighted field surfaces an error instead of a dataset', () => {
+ let state = reduceVisState(siteState(), VisStateActions.addSuitability('sites'));
+ const op = state.suitabilities[0];
+
+ state = reduceVisState(state, VisStateActions.setSuitabilityConfig(op.id, {weights: {}}));
+ state = reduceVisState(state, VisStateActions.runSuitability(op.id));
+
+ expect(state.suitabilities[0].error).toBe('Select at least one field to score');
+ expect(state.suitabilities[0].isConfigActive).toBe(true);
+ expect(state.datasets[op.resultId]).toBeUndefined();
+ });
+
+ test('deleting the source dataset drops the op but keeps the scored snapshot', () => {
+ let state = reduceVisState(siteState(), VisStateActions.addSuitability('sites'));
+ const op = state.suitabilities[0];
+ state = reduceVisState(state, VisStateActions.runSuitability(op.id));
+ state = flushCreateTableTasks(state);
+
+ expect(state.datasets[op.resultId]).toBeTruthy();
+ state = reduceVisState(state, VisStateActions.removeDataset('sites'));
+ expect(state.datasets.sites).toBeUndefined();
+ expect(state.datasets[op.resultId]).toBeTruthy();
+ expect(state.suitabilities).toHaveLength(0);
+ });
+
+ test('the op config stays out of saved maps while the derived dataset persists', () => {
+ let state = reduceVisState(siteState(), VisStateActions.addSuitability('sites'));
+ const op = state.suitabilities[0];
+ state = reduceVisState(state, VisStateActions.runSuitability(op.id));
+ state = flushCreateTableTasks(state);
+
+ const saved = SchemaManager.save({
+ visState: state,
+ mapState: {},
+ mapStyle: {},
+ uiState: {}
+ });
+
+ expect(saved.config.config.visState).not.toHaveProperty('suitabilities');
+ const derived = saved.datasets.find(dataset => dataset.data.id === op.resultId);
+ const derivedMeta = derived?.data.metadata as
+ | {derivedDataset?: {type?: string} | null}
+ | undefined;
+ expect(derivedMeta?.derivedDataset?.type).toBe('suitability');
+ });
+});
diff --git a/src/reducers/src/dataset-ops-updaters.ts b/src/reducers/src/dataset-ops-updaters.ts
index a27784fbd..830e24d95 100644
--- a/src/reducers/src/dataset-ops-updaters.ts
+++ b/src/reducers/src/dataset-ops-updaters.ts
@@ -4,13 +4,17 @@
import {generateHashId} from '@kepler.gl/common-utils';
import {
defaultAggregationsForFields,
+ defaultSuitabilityWeights,
groupByDataset,
isTabularDatasetForOps,
joinDatasets,
spatialJoinDatasets,
suggestSpatialGeo,
+ suitabilityDataset,
+ DEFAULT_SUITABILITY_SCORE_FIELD,
GroupByOp,
- JoinOp
+ JoinOp,
+ SuitabilityOp
} from '@kepler.gl/table';
import {ProtoDataset} from '@kepler.gl/types';
import {VisStateActions} from '@kepler.gl/actions';
@@ -41,6 +45,10 @@ function defaultSpatialJoinLabel(resultId: string): string {
return `spatial-join-${resultId}`;
}
+function defaultSuitabilityLabel(): string {
+ return `suitability-${randomTwoDigitSuffix()}`;
+}
+
export function addGroupByUpdater(
state: VisState,
action: VisStateActions.AddGroupByUpdaterAction
@@ -64,7 +72,8 @@ export function addGroupByUpdater(
return {
...state,
groupBys: [...deactivateOps(state.groupBys), op],
- joins: deactivateOps(state.joins)
+ joins: deactivateOps(state.joins),
+ suitabilities: deactivateOps(state.suitabilities)
};
}
@@ -154,7 +163,8 @@ export function addJoinUpdater(
return {
...state,
joins: [...deactivateOps(state.joins), op],
- groupBys: deactivateOps(state.groupBys)
+ groupBys: deactivateOps(state.groupBys),
+ suitabilities: deactivateOps(state.suitabilities)
};
}
@@ -276,6 +286,91 @@ export function executeSpatialJoin(
}
}
+export function addSuitabilityUpdater(
+ state: VisState,
+ action: VisStateActions.AddSuitabilityUpdaterAction
+): VisState {
+ const dataset = state.datasets[action.dataId];
+ if (!isTabularDatasetForOps(dataset)) {
+ return state;
+ }
+ const op: SuitabilityOp = {
+ id: generateHashId(6),
+ dataId: action.dataId,
+ weights: defaultSuitabilityWeights(dataset.fields),
+ weightStandardization: 'normalize',
+ dataStandardization: 'range',
+ outputFieldName: DEFAULT_SUITABILITY_SCORE_FIELD,
+ resultId: generateHashId(6),
+ resultLabel: defaultSuitabilityLabel(),
+ isConfigActive: true,
+ error: null
+ };
+ return {
+ ...state,
+ suitabilities: [...deactivateOps(state.suitabilities), op],
+ groupBys: deactivateOps(state.groupBys),
+ joins: deactivateOps(state.joins)
+ };
+}
+
+export function setSuitabilityConfigUpdater(
+ state: VisState,
+ action: VisStateActions.SetSuitabilityConfigUpdaterAction
+): VisState {
+ return {
+ ...state,
+ suitabilities: state.suitabilities.map(op =>
+ op.id === action.id ? {...op, ...action.config, error: action.config.error ?? null} : op
+ )
+ };
+}
+
+export function executeSuitability(
+ state: VisState,
+ action: VisStateActions.RunSuitabilityUpdaterAction
+): DerivedDatasetOpResult {
+ const op = state.suitabilities.find(item => item.id === action.id);
+ const dataset = op ? state.datasets[op.dataId] : undefined;
+ if (!op || !dataset || !Object.keys(op.weights).length) {
+ return {
+ state: setSuitabilityConfigUpdater(state, {
+ id: action.id,
+ config: {error: 'Select at least one field to score'}
+ })
+ };
+ }
+
+ try {
+ const proto = suitabilityDataset(dataset, {
+ weights: op.weights,
+ weightStandardization: op.weightStandardization,
+ dataStandardization: op.dataStandardization,
+ outputFieldName: op.outputFieldName,
+ columns: op.columns,
+ label: op.resultLabel,
+ resultId: op.resultId,
+ operationId: op.id
+ });
+ return {
+ state: {
+ ...state,
+ suitabilities: state.suitabilities.map(item =>
+ item.id === op.id ? {...item, isConfigActive: false, error: null} : item
+ )
+ },
+ proto
+ };
+ } catch (error) {
+ return {
+ state: setSuitabilityConfigUpdater(state, {
+ id: action.id,
+ config: {error: error instanceof Error ? error.message : String(error)}
+ })
+ };
+ }
+}
+
export function removeDatasetOpUpdater(
state: VisState,
action: VisStateActions.RemoveDatasetOpUpdaterAction
@@ -283,7 +378,8 @@ export function removeDatasetOpUpdater(
return {
...state,
groupBys: state.groupBys.filter(op => op.id !== action.id),
- joins: state.joins.filter(op => op.id !== action.id)
+ joins: state.joins.filter(op => op.id !== action.id),
+ suitabilities: state.suitabilities.filter(op => op.id !== action.id)
};
}
@@ -297,6 +393,7 @@ export function removeOpsForDatasets(state: VisState, dataIds: string[]): VisSta
!ids.has(op.leftDataId) &&
!(op.rightDataId && ids.has(op.rightDataId)) &&
!ids.has(op.resultId)
- )
+ ),
+ suitabilities: state.suitabilities.filter(op => !ids.has(op.dataId) && !ids.has(op.resultId))
};
}
diff --git a/src/reducers/src/vis-state-updaters.ts b/src/reducers/src/vis-state-updaters.ts
index 53056d553..fb0c91574 100644
--- a/src/reducers/src/vis-state-updaters.ts
+++ b/src/reducers/src/vis-state-updaters.ts
@@ -218,14 +218,17 @@ import {
addGroupByUpdater,
addJoinUpdater,
addSpatialJoinUpdater,
+ addSuitabilityUpdater,
executeGroupBy,
executeJoin,
executeSpatialJoin,
+ executeSuitability,
removeDatasetOpUpdater,
removeOpsForDatasets,
setGroupByConfigUpdater,
setJoinConfigUpdater,
- setSpatialJoinConfigUpdater
+ setSpatialJoinConfigUpdater,
+ setSuitabilityConfigUpdater
} from './dataset-ops-updaters';
import {
fixEffectOrder,
@@ -399,6 +402,7 @@ export const INITIAL_VIS_STATE: VisState = {
editingDataset: undefined,
groupBys: [],
joins: [],
+ suitabilities: [],
// effects
effects: [],
@@ -6696,12 +6700,22 @@ export function runSpatialJoinUpdater(
return proto ? applyDerivedProtoDataset(nextState, proto) : nextState;
}
+export function runSuitabilityUpdater(
+ state: VisState,
+ action: VisStateActions.RunSuitabilityUpdaterAction
+): VisState {
+ const {state: nextState, proto} = executeSuitability(state, action);
+ return proto ? applyDerivedProtoDataset(nextState, proto) : nextState;
+}
+
export {
addGroupByUpdater,
addJoinUpdater,
addSpatialJoinUpdater,
+ addSuitabilityUpdater,
removeDatasetOpUpdater,
setGroupByConfigUpdater,
setJoinConfigUpdater,
- setSpatialJoinConfigUpdater
+ setSpatialJoinConfigUpdater,
+ setSuitabilityConfigUpdater
};
diff --git a/src/reducers/src/vis-state.ts b/src/reducers/src/vis-state.ts
index e1b3eac93..b0768c676 100644
--- a/src/reducers/src/vis-state.ts
+++ b/src/reducers/src/vis-state.ts
@@ -239,6 +239,9 @@ const actionHandler = {
[ActionTypes.ADD_SPATIAL_JOIN]: visStateUpdaters.addSpatialJoinUpdater,
[ActionTypes.SET_SPATIAL_JOIN_CONFIG]: visStateUpdaters.setSpatialJoinConfigUpdater,
[ActionTypes.RUN_SPATIAL_JOIN]: visStateUpdaters.runSpatialJoinUpdater,
+ [ActionTypes.ADD_SUITABILITY]: visStateUpdaters.addSuitabilityUpdater,
+ [ActionTypes.SET_SUITABILITY_CONFIG]: visStateUpdaters.setSuitabilityConfigUpdater,
+ [ActionTypes.RUN_SUITABILITY]: visStateUpdaters.runSuitabilityUpdater,
[ActionTypes.REMOVE_DATASET_OP]: visStateUpdaters.removeDatasetOpUpdater
};
diff --git a/src/schemas/src/vis-state-schema.ts b/src/schemas/src/vis-state-schema.ts
index 786cc0529..a99d7267b 100644
--- a/src/schemas/src/vis-state-schema.ts
+++ b/src/schemas/src/vis-state-schema.ts
@@ -39,7 +39,7 @@ import {
Annotation,
ChartConfig
} from '@kepler.gl/types';
-import {Datasets, GroupByOp, JoinOp} from '@kepler.gl/table';
+import {Datasets, GroupByOp, JoinOp, SuitabilityOp} from '@kepler.gl/table';
import {Layer, LayerClassesType} from '@kepler.gl/layers';
import {Loader} from '@loaders.gl/loader-utils';
import KeplerGLSchema from './schema-manager';
@@ -79,6 +79,7 @@ export interface VisState {
editingDataset: string | undefined;
groupBys: GroupByOp[];
joins: JoinOp[];
+ suitabilities: SuitabilityOp[];
interactionConfig: InteractionConfig;
interactionToBeMerged: any;
layerBlending: string;
@@ -1098,6 +1099,8 @@ export const propertiesV1 = {
layerOrder: null,
groupBys: null,
joins: null
+ // suitabilities is intentionally absent: the op config is ephemeral and only the
+ // derived dataset is persisted. A `null` entry here would write it to saved maps.
};
export class VisStateSchemaV1 extends Schema {
diff --git a/src/table/src/dataset-ops.spec.ts b/src/table/src/dataset-ops.spec.ts
index 463be7227..05436bc49 100644
--- a/src/table/src/dataset-ops.spec.ts
+++ b/src/table/src/dataset-ops.spec.ts
@@ -13,7 +13,10 @@ import {
isDatasetOpsAggregationField,
isTabularDatasetForOps,
joinDatasets,
- spatialJoinDatasets
+ spatialJoinDatasets,
+ defaultSuitabilityWeights,
+ isSuitabilityWeightField,
+ suitabilityDataset
} from './dataset-ops';
function makeTable({
@@ -458,3 +461,151 @@ describe('dataset-ops engine', () => {
).toEqual({geom: 'merge'});
});
});
+
+describe('suitability engine', () => {
+ const sites = () =>
+ makeTable({
+ id: 'sites',
+ fields: [
+ {name: 'name', type: ALL_FIELD_TYPES.string},
+ {name: 'access', type: ALL_FIELD_TYPES.integer},
+ {name: 'cost', type: ALL_FIELD_TYPES.integer}
+ ],
+ rows: [
+ ['a', 0, 100],
+ ['b', 5, 200],
+ ['c', 10, 300]
+ ]
+ });
+
+ test('scores rows as a normalized weighted sum of range-standardized columns', () => {
+ const result = suitabilityDataset(sites(), {
+ weights: {access: 1, cost: 1},
+ resultId: 'sites-score',
+ operationId: 'su-1'
+ });
+
+ expect(result.info.id).toBe('sites-score');
+ expect(result.metadata.derivedDataset).toEqual({
+ type: 'suitability',
+ sourceDataIds: ['sites'],
+ operationId: 'su-1'
+ });
+ // source columns are kept, score is appended last as a real column
+ expect(result.data.fields.map(field => field.name)).toEqual([
+ 'name',
+ 'access',
+ 'cost',
+ 'score'
+ ]);
+ expect(result.data.fields[3].type).toBe(ALL_FIELD_TYPES.real);
+ // both columns span their full range, so normalized weights put scores on 0..1
+ expect(result.data.rows.map(row => row[3])).toEqual([0, 0.5, 1]);
+ });
+
+ test('raw weights skip normalization', () => {
+ const result = suitabilityDataset(sites(), {
+ weights: {access: 1, cost: 1},
+ weightStandardization: 'raw'
+ });
+
+ expect(result.data.rows.map(row => row[3])).toEqual([0, 1, 2]);
+ });
+
+ test('z-score standardization divides by the standard deviation', () => {
+ const result = suitabilityDataset(sites(), {
+ weights: {access: 1},
+ weightStandardization: 'raw',
+ dataStandardization: 'zScore'
+ });
+
+ const deviation = Math.sqrt(((0 - 5) ** 2 + (5 - 5) ** 2 + (10 - 5) ** 2) / 3);
+ expect(result.data.rows.map(row => row[3])).toEqual([-5 / deviation, 0, 5 / deviation]);
+ });
+
+ test('raw data standardization leaves values untouched', () => {
+ const result = suitabilityDataset(sites(), {
+ weights: {access: 2},
+ weightStandardization: 'raw',
+ dataStandardization: 'raw'
+ });
+
+ expect(result.data.rows.map(row => row[3])).toEqual([0, 10, 20]);
+ });
+
+ test('a constant column falls back to its raw values', () => {
+ const dataset = makeTable({
+ id: 'flat',
+ fields: [{name: 'value', type: ALL_FIELD_TYPES.integer}],
+ rows: [[3], [3]]
+ });
+
+ const result = suitabilityDataset(dataset, {
+ weights: {value: 1},
+ weightStandardization: 'raw'
+ });
+
+ expect(result.data.rows.map(row => row[1])).toEqual([3, 3]);
+ });
+
+ test('rows missing a weighted value score null', () => {
+ const dataset = makeTable({
+ id: 'gaps',
+ fields: [
+ {name: 'a', type: ALL_FIELD_TYPES.integer},
+ {name: 'b', type: ALL_FIELD_TYPES.integer}
+ ],
+ rows: [
+ [0, 1],
+ [null, 2],
+ [10, 3]
+ ]
+ });
+
+ const result = suitabilityDataset(dataset, {weights: {a: 1, b: 1}});
+ expect(result.data.rows[1][2]).toBeNull();
+ expect(result.data.rows[0][2]).not.toBeNull();
+ });
+
+ test('columns restricts the copied source columns and renames a clashing score column', () => {
+ const dataset = makeTable({
+ id: 'clash',
+ fields: [
+ {name: 'name', type: ALL_FIELD_TYPES.string},
+ {name: 'score', type: ALL_FIELD_TYPES.integer}
+ ],
+ rows: [
+ ['a', 1],
+ ['b', 2]
+ ]
+ });
+
+ const result = suitabilityDataset(dataset, {
+ weights: {score: 1},
+ columns: ['score']
+ });
+
+ expect(result.data.fields.map(field => field.name)).toEqual(['score', 'score_1']);
+ expect(result.data.rows[0]).toEqual([1, 0]);
+ });
+
+ test('rejects empty, unknown, and non-numeric weight fields', () => {
+ expect(() => suitabilityDataset(sites(), {weights: {}})).toThrow(
+ 'Select at least one field to score'
+ );
+ expect(() => suitabilityDataset(sites(), {weights: {nope: 1}})).toThrow(
+ 'Suitability field "nope" was not found'
+ );
+ expect(() => suitabilityDataset(sites(), {weights: {name: 1}})).toThrow(
+ 'Suitability field "name" is not numeric'
+ );
+ });
+
+ test('only numeric fields can be weighted', () => {
+ expect(isSuitabilityWeightField({type: ALL_FIELD_TYPES.real})).toBe(true);
+ expect(isSuitabilityWeightField({type: ALL_FIELD_TYPES.integer})).toBe(true);
+ expect(isSuitabilityWeightField({type: ALL_FIELD_TYPES.boolean})).toBe(false);
+ expect(isSuitabilityWeightField({type: ALL_FIELD_TYPES.string})).toBe(false);
+ expect(defaultSuitabilityWeights(sites().fields)).toEqual({access: 1, cost: 1});
+ });
+});
diff --git a/src/table/src/dataset-ops/index.ts b/src/table/src/dataset-ops/index.ts
index 8a4f54661..c2ba9c426 100644
--- a/src/table/src/dataset-ops/index.ts
+++ b/src/table/src/dataset-ops/index.ts
@@ -8,15 +8,18 @@ export * from './table-helpers';
export * from './group-by';
export * from './join';
export * from './spatial-join';
+export * from './suitability';
export {makeResultProtoDataset} from './proto-dataset';
import {groupByDataset} from './group-by';
import {joinDatasets} from './join';
import {spatialJoinDatasets} from './spatial-join';
+import {suitabilityDataset} from './suitability';
import {DatasetOpsEngine} from './types';
export const inMemoryDatasetOpsEngine: DatasetOpsEngine = {
groupByDataset,
joinDatasets,
- spatialJoinDatasets
+ spatialJoinDatasets,
+ suitabilityDataset
};
diff --git a/src/table/src/dataset-ops/suitability.ts b/src/table/src/dataset-ops/suitability.ts
new file mode 100644
index 000000000..b5033f87c
--- /dev/null
+++ b/src/table/src/dataset-ops/suitability.ts
@@ -0,0 +1,177 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import {generateHashId} from '@kepler.gl/common-utils';
+import {ALL_FIELD_TYPES} from '@kepler.gl/constants';
+import {Field, ProtoDataset} from '@kepler.gl/types';
+
+import {copyFieldAs, makeResultProtoDataset, uniqueColumnName} from './proto-dataset';
+import {findFieldByName, rowCount, rowValue} from './table-helpers';
+import {
+ DataStandardization,
+ DatasetOpsTable,
+ DEFAULT_SUITABILITY_SCORE_FIELD,
+ DEFAULT_SUITABILITY_WEIGHT,
+ SuitabilityDatasetConfig,
+ WeightStandardization
+} from './types';
+
+const SCORABLE_FIELD_TYPES = new Set<string>([ALL_FIELD_TYPES.integer, ALL_FIELD_TYPES.real]);
+
+/** Only plain numeric columns can carry a suitability weight. */
+export function isSuitabilityWeightField(field: {type?: string}): boolean {
+ return Boolean(field.type && SCORABLE_FIELD_TYPES.has(field.type));
+}
+
+export function defaultSuitabilityWeights(fields: Field[]): Record<string, number> {
+ const weights: Record<string, number> = {};
+ fields.forEach(field => {
+ if (isSuitabilityWeightField(field)) {
+ weights[field.name] = DEFAULT_SUITABILITY_WEIGHT;
+ }
+ });
+ return weights;
+}
+
+function toNumber(value: unknown): number | null {
+ if (typeof value === 'number') {
+ return Number.isFinite(value) ? value : null;
+ }
+ if (typeof value === 'bigint') {
+ return Number(value);
+ }
+ return null;
+}
+
+function rangeStandardize(values: (number | null)[]): (number | null)[] {
+ let min = Infinity;
+ let max = -Infinity;
+ for (const value of values) {
+ if (value === null) continue;
+ if (value < min) min = value;
+ if (value > max) max = value;
+ }
+ const span = max - min;
+ if (!Number.isFinite(span) || span === 0) {
+ return values;
+ }
+ return values.map(value => (value === null ? null : (value - min) / span));
+}
+
+function zStandardize(values: (number | null)[]): (number | null)[] {
+ const defined = values.filter((value): value is number => value !== null);
+ if (!defined.length) {
+ return values;
+ }
+ const mean = defined.reduce((sum, value) => sum + value, 0) / defined.length;
+ const variance = defined.reduce((sum, value) => sum + (value - mean) ** 2, 0) / defined.length;
+ // Studio divides by the variance here, which does not produce a z-score.
+ const deviation = Math.sqrt(variance);
+ if (deviation === 0) {
+ return values;
+ }
+ return values.map(value => (value === null ? null : (value - mean) / deviation));
+}
+
+export function standardizeColumn(
+ values: (number | null)[],
+ method: DataStandardization
+): (number | null)[] {
+ switch (method) {
+ case 'range':
+ return rangeStandardize(values);
+ case 'zScore':
+ return zStandardize(values);
+ default:
+ return values;
+ }
+}
+
+export function standardizeWeights(weights: number[], method: WeightStandardization): number[] {
+ if (method !== 'normalize') {
+ return weights;
+ }
+ const total = weights.reduce((sum, weight) => sum + weight, 0);
+ return total === 0 ? weights : weights.map(weight => weight / total);
+}
+
+/**
+ * Scores every row as the weighted sum of its standardized values, and returns the source
+ * columns plus the score as a new dataset. A row scores null when any weighted value is
+ * missing, so partial rows do not masquerade as low scores.
+ */
+export function suitabilityDataset(
+ dataset: DatasetOpsTable,
+ config: SuitabilityDatasetConfig
+): ProtoDataset {
+ const weightEntries = Object.entries(config.weights || {});
+ if (!weightEntries.length) {
+ throw new Error('Select at least one field to score');
+ }
+
+ const weightedFields = weightEntries.map(([fieldName, weight]) => {
+ const field = findFieldByName(dataset.fields, fieldName);
+ if (!field) {
+ throw new Error(`Suitability field "${fieldName}" was not found`);
+ }
+ if (!isSuitabilityWeightField(field)) {
+ throw new Error(`Suitability field "${fieldName}" is not numeric`);
+ }
+ return {field, weight};
+ });
+
+ const n = rowCount(dataset);
+ const dataStandardization = config.dataStandardization || 'range';
+ const standardized = weightedFields.map(({field}) =>
+ standardizeColumn(
+ Array.from({length: n}, (_, i) => toNumber(rowValue(dataset, i, field))),
+ dataStandardization
+ )
+ );
+ const weights = standardizeWeights(
+ weightedFields.map(({weight}) => weight),
+ config.weightStandardization || 'normalize'
+ );
+
+ const scores: (number | null)[] = Array.from({length: n}, (_, row) => {
+ let score = 0;
+ for (let col = 0; col < standardized.length; col++) {
+ const value = standardized[col][row];
+ if (value === null) {
+ return null;
+ }
+ score += value * weights[col];
+ }
+ return score;
+ });
+
+ const includedFields =
+ config.columns === undefined
+ ? dataset.fields
+ : dataset.fields.filter(field => config.columns?.includes(field.name));
+
+ const usedNames = new Set<string>();
+ const fields = includedFields.map(field =>
+ copyFieldAs(field, uniqueColumnName(field.name, usedNames))
+ );
+ fields.push({
+ name: uniqueColumnName(config.outputFieldName || DEFAULT_SUITABILITY_SCORE_FIELD, usedNames),
+ type: ALL_FIELD_TYPES.real,
+ analyzerType: ALL_FIELD_TYPES.real
+ });
+
+ const rows = Array.from({length: n}, (_, row) => [
+ ...includedFields.map(field => rowValue(dataset, row, field)),
+ scores[row]
+ ]);
+
+ return makeResultProtoDataset({
+ source: dataset,
+ type: 'suitability',
+ operationId: config.operationId || generateHashId(6),
+ label: config.label || `suitability-${config.resultId || generateHashId(6)}`,
+ resultId: config.resultId,
+ fields,
+ rows
+ });
+}
diff --git a/src/table/src/dataset-ops/types.ts b/src/table/src/dataset-ops/types.ts
index d0abd9684..1ba53c37f 100644
--- a/src/table/src/dataset-ops/types.ts
+++ b/src/table/src/dataset-ops/types.ts
@@ -19,7 +19,7 @@ export const DATASET_OPS_AGGREGATIONS = {
export type DatasetOpAggregation =
(typeof DATASET_OPS_AGGREGATIONS)[keyof typeof DATASET_OPS_AGGREGATIONS];
-export type DerivedDatasetType = 'groupBy' | 'join' | 'spatialJoin';
+export type DerivedDatasetType = 'groupBy' | 'join' | 'spatialJoin' | 'suitability';
export type DerivedDatasetMetadata = {
type: DerivedDatasetType;
@@ -133,6 +133,64 @@ export type JoinOp = {
error?: string | null;
};
+export const WEIGHT_STANDARDIZATIONS = {
+ raw: 'raw',
+ normalize: 'normalize'
+} as const;
+
+export type WeightStandardization =
+ (typeof WEIGHT_STANDARDIZATIONS)[keyof typeof WEIGHT_STANDARDIZATIONS];
+
+export const WEIGHT_STANDARDIZATION_OPTIONS: {id: WeightStandardization; labelId: string}[] = [
+ {id: 'normalize', labelId: 'datasetOps.weightStandardizationOption.normalize'},
+ {id: 'raw', labelId: 'datasetOps.weightStandardizationOption.raw'}
+];
+
+export const DATA_STANDARDIZATIONS = {
+ raw: 'raw',
+ range: 'range',
+ zScore: 'zScore'
+} as const;
+
+export type DataStandardization =
+ (typeof DATA_STANDARDIZATIONS)[keyof typeof DATA_STANDARDIZATIONS];
+
+export const DATA_STANDARDIZATION_OPTIONS: {id: DataStandardization; labelId: string}[] = [
+ {id: 'range', labelId: 'datasetOps.dataStandardizationOption.range'},
+ {id: 'zScore', labelId: 'datasetOps.dataStandardizationOption.zScore'},
+ {id: 'raw', labelId: 'datasetOps.dataStandardizationOption.raw'}
+];
+
+export const DEFAULT_SUITABILITY_SCORE_FIELD = 'score';
+export const DEFAULT_SUITABILITY_WEIGHT = 1;
+export const SUITABILITY_WEIGHT_RANGE: [number, number] = [0, 1];
+
+export type SuitabilityDatasetConfig = {
+ /** Weight per source field name. Fields absent from this map are not scored. */
+ weights: Record<string, number>;
+ weightStandardization?: WeightStandardization;
+ dataStandardization?: DataStandardization;
+ outputFieldName?: string;
+ columns?: string[];
+ label?: string;
+ resultId?: string;
+ operationId?: string;
+};
+
+export type SuitabilityOp = {
+ id: string;
+ dataId: string;
+ weights: Record<string, number>;
+ weightStandardization: WeightStandardization;
+ dataStandardization: DataStandardization;
+ outputFieldName: string;
+ columns?: string[];
+ resultId: string;
+ resultLabel: string;
+ isConfigActive: boolean;
+ error?: string | null;
+};
+
export type DatasetOpsEngine = {
groupByDataset: (dataset: DatasetOpsTable, config: GroupByDatasetConfig) => ProtoDataset;
joinDatasets: (
@@ -145,4 +203,5 @@ export type DatasetOpsEngine = {
right: DatasetOpsTable,
config: SpatialJoinDatasetConfig
) => ProtoDataset;
+ suitabilityDataset: (dataset: DatasetOpsTable, config: SuitabilityDatasetConfig) => ProtoDataset;
};
diff --git a/src/utils/src/dataset-utils.ts b/src/utils/src/dataset-utils.ts
index fc7d2d8d6..a0ebf6804 100644
--- a/src/utils/src/dataset-utils.ts
+++ b/src/utils/src/dataset-utils.ts
@@ -104,6 +104,7 @@ const EXCLUDED_DEFAULT_FIELDS = [
* most preferred.
*/
const METRIC_DEFAULT_FIELDS = [
+ 'score',
'metric',
'value',
'sum',
diff --git a/test/node/utils/dataset-utils-test.js b/test/node/utils/dataset-utils-test.js
index fe44bb82a..fa2899bf4 100644
--- a/test/node/utils/dataset-utils-test.js
+++ b/test/node/utils/dataset-utils-test.js
@@ -43,6 +43,11 @@ const DEFAULT_FIELD_TEST_CASES = [
name: 'included real, with inclusion ordering',
csv: 'zipcode mean,a metric,b,c\n0.5,0.1,0,0.5\n0.5,0.1,1,0.5',
expected: 'a metric'
+ },
+ {
+ name: 'prefers score over other reals',
+ csv: 'depth,magnitude,score\n1.0,2.0,0.5\n3.0,4.0,0.8',
+ expected: 'score'
}
];