Skip to content

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

[Feature] Abstract Data Container (#1555)

Igor Dykhta070b04b2c02a
diff --git a/docs/RFC/table-class.md b/docs/RFC/table-class.md
index f46a8333b..b603d4197 100644
--- a/docs/RFC/table-class.md
+++ b/docs/RFC/table-class.md
@@ -10,7 +10,7 @@ export type KeplerDataset = {
// fields and data
fields: KeplerField[];
- allData: any[][];
+ dataContainer: DataContainer;
allIndexes: number[];
filteredIndex: number[];
@@ -68,7 +68,7 @@ Missing features
1. `initalize`
-to replace utils/dataset-utils `createNewDataEntry` This table method takes a `ProtoTable` and return a `Table` to be saved in kepler state.
+to replace utils/dataset-utils `createNewDataEntry` This table method takes a `ProtoTable` and returns a `Table` to be saved in kepler state.
```js
table.initalize(protoTable);
diff --git a/src/components/common/data-table/cell-size.js b/src/components/common/data-table/cell-size.js
index aeb5afd11..9a79956b2 100644
--- a/src/components/common/data-table/cell-size.js
+++ b/src/components/common/data-table/cell-size.js
@@ -24,11 +24,11 @@ import {parseFieldValue} from 'utils/data-utils';
const MIN_GHOST_CELL_SIZE = 200;
/**
- * Measure rows and column content to determin min width for each column
+ * Measure rows and column content to determine min width for each column
* @param {*} param0
*/
export function renderedSize({
- text: {rows, column},
+ text: {dataContainer, column},
type = 'string',
colIdx,
numRowsToCalculate = 10,
@@ -50,19 +50,21 @@ export function renderedSize({
document.body.appendChild(textCanvas);
const context = textCanvas.getContext('2d');
context.font = [fontSize, font].join('px ');
+
let rowsToSample = [...Array(numRowsToCalculate)].map(() =>
- Math.floor(Math.random() * (rows.length - 1))
+ Math.floor(Math.random() * (dataContainer.numRows() - 1))
);
- // IF we have less than 10 rows, lets measure all of them
- if (rows.length <= numRowsToCalculate) {
- rowsToSample = Array.from(Array(rows.length).keys());
+ // If we have less than 10 rows, lets measure all of them
+ if (dataContainer.numRows() <= numRowsToCalculate) {
+ rowsToSample = Array.from(Array(dataContainer.numRows()).keys());
}
const rowWidth = Math.max(
...rowsToSample.map(
rowIdx =>
- Math.ceil(context.measureText(parseFieldValue(rows[rowIdx][colIdx], type)).width) +
- cellPadding
+ Math.ceil(
+ context.measureText(parseFieldValue(dataContainer.valueAt(rowIdx, colIdx), type)).width
+ ) + cellPadding
)
);
// header cell only has left padding
diff --git a/src/components/common/data-table/index.js b/src/components/common/data-table/index.js
index a580dae5e..b1cd12a51 100644
--- a/src/components/common/data-table/index.js
+++ b/src/components/common/data-table/index.js
@@ -232,11 +232,13 @@ const columnWidthFunction = (columns, cellSizeCache, ghost) => ({index}) => {
/*
* This is an accessor method used to generalize getting a cell from a data row
*/
-const getRowCell = ({rows, columns, column, colMeta, rowIndex, sortOrder}) => {
+const getRowCell = ({dataContainer, columns, column, colMeta, rowIndex, sortOrder}) => {
const rowIdx = sortOrder && sortOrder.length ? get(sortOrder, rowIndex) : rowIndex;
const {type} = colMeta[column];
- return parseFieldValue(get(rows, [rowIdx, columns.indexOf(column)], 'Err'), type);
+ let value = dataContainer.valueAt(rowIdx, columns.indexOf(column));
+ if (value === undefined) value = 'Err';
+ return parseFieldValue(value, type);
};
export const TableSection = ({
@@ -300,7 +302,7 @@ DataTableFactory.deps = [FieldTokenFactory];
function DataTableFactory(FieldToken) {
class DataTable extends Component {
static defaultProps = {
- rows: [],
+ dataContainer: null,
pinnedColumns: [],
colMeta: {},
cellSizeCache: {},
@@ -460,16 +462,18 @@ function DataTableFactory(FieldToken) {
renderDataCell = (columns, isPinned, props) => {
return cellInfo => {
const {columnIndex, key, style, rowIndex} = cellInfo;
- const {rows, colMeta} = props;
+ const {dataContainer, colMeta} = props;
const column = columns[columnIndex];
const isGhost = column.ghost;
const rowCell = isGhost ? '' : getRowCell({...props, column, rowIndex});
const type = isGhost ? null : colMeta[column].type;
+ const lastRowIndex = dataContainer ? dataContainer.numRows() - 1 : 0;
+
const endCell = columnIndex === columns.length - 1;
const firstCell = columnIndex === 0;
- const bottomCell = rowIndex === rows.length - 1;
+ const bottomCell = rowIndex === lastRowIndex;
const alignRight = fieldToAlignRight[type];
const cell = (
@@ -496,7 +500,7 @@ function DataTableFactory(FieldToken) {
};
render() {
- const {rows, pinnedColumns, theme = {}, fixedWidth, fixedHeight} = this.props;
+ const {dataContainer, pinnedColumns, theme = {}, fixedWidth, fixedHeight} = this.props;
const unpinnedColumns = this.unpinnedColumns(this.props);
const {cellSizeCache, moreOptionsColumn, ghost} = this.state;
@@ -521,7 +525,7 @@ function DataTableFactory(FieldToken) {
cellSizeCache,
overscanColumnCount,
overscanRowCount,
- rowCount: (rows || []).length,
+ rowCount: dataContainer ? dataContainer.numRows() : 0,
rowHeight
};
diff --git a/src/components/modals/data-table-modal.js b/src/components/modals/data-table-modal.js
index 20d1e7789..edfffec04 100644
--- a/src/components/modals/data-table-modal.js
+++ b/src/components/modals/data-table-modal.js
@@ -111,14 +111,14 @@ function DataTableModalFactory(DataTable) {
if (!datasets[dataId]) {
return {};
}
- const {fields, allData} = datasets[dataId];
+ const {fields, dataContainer} = datasets[dataId];
let showCalculate = null;
if (!this.datasetCellSizeCache[dataId]) {
showCalculate = true;
} else if (
this.datasetCellSizeCache[dataId].fields !== fields ||
- this.datasetCellSizeCache[dataId].allData !== allData
+ this.datasetCellSizeCache[dataId].dataContainer !== dataContainer
) {
showCalculate = true;
}
@@ -132,7 +132,7 @@ function DataTableModalFactory(DataTable) {
...acc,
[field.name]: renderedSize({
text: {
- rows: allData,
+ dataContainer,
column: field.name
},
colIdx,
@@ -147,7 +147,7 @@ function DataTableModalFactory(DataTable) {
this.datasetCellSizeCache[dataId] = {
cellSizeCache,
fields,
- allData
+ dataContainer
};
return cellSizeCache;
});
@@ -194,7 +194,7 @@ function DataTableModalFactory(DataTable) {
columns={columns}
colMeta={colMeta}
cellSizeCache={cellSizeCache}
- rows={activeDataset.allData}
+ dataContainer={activeDataset.dataContainer}
pinnedColumns={activeDataset.pinnedColumns}
sortOrder={activeDataset.sortOrder}
sortColumn={activeDataset.sortColumn}
diff --git a/src/components/modals/export-data-modal.js b/src/components/modals/export-data-modal.js
index 6d9b97102..26683a706 100644
--- a/src/components/modals/export-data-modal.js
+++ b/src/components/modals/export-data-modal.js
@@ -54,13 +54,13 @@ const getDataRowCount = (datasets, selectedDataset, filtered, intl) => {
{fileCount: Object.keys(datasets).length}
);
}
- const {allData, filteredIdxCPU} = selectedData;
+ const {dataContainer, filteredIdxCPU} = selectedData;
if (filtered && !filteredIdxCPU) {
return '-';
}
- const rowCount = filtered ? filteredIdxCPU.length : allData.length;
+ const rowCount = filtered ? filteredIdxCPU.length : dataContainer.numRows();
return intl.formatMessage(
{id: 'modal.exportData.rowCount'},
diff --git a/src/components/side-panel/common/dataset-info.js b/src/components/side-panel/common/dataset-info.js
index 36da74294..77dd5bcbd 100644
--- a/src/components/side-panel/common/dataset-info.js
+++ b/src/components/side-panel/common/dataset-info.js
@@ -36,7 +36,7 @@ export default function DatasetInfoFactory() {
<StyledDataRowCount className="source-data-rows">
<FormattedMessage
id={'datasetInfo.rowCount'}
- values={{rowCount: numFormat(dataset.allData.length)}}
+ values={{rowCount: numFormat(dataset.dataContainer.numRows())}}
/>
</StyledDataRowCount>
);
diff --git a/src/layers/aggregation-layer.js b/src/layers/aggregation-layer.js
index aae2b9a04..d385f4054 100644
--- a/src/layers/aggregation-layer.js
+++ b/src/layers/aggregation-layer.js
@@ -26,7 +26,10 @@ import {HIGHLIGH_COLOR_3D} from 'constants/default-settings';
import {CHANNEL_SCALES, FIELD_OPTS, DEFAULT_AGGREGATION} from 'constants/default-settings';
-export const pointPosAccessor = ({lat, lng}) => d => [d.data[lng.fieldIdx], d.data[lat.fieldIdx]];
+export const pointPosAccessor = ({lat, lng}) => dc => d => [
+ dc.valueAt(d.index, lng.fieldIdx),
+ dc.valueAt(d.index, lat.fieldIdx)
+];
export const pointPosResolver = ({lat, lng}) => `${lat.fieldIdx}-${lng.fieldIdx}`;
@@ -34,7 +37,9 @@ export const getValueAggrFunc = (field, aggregation) => {
return points => {
return field
? aggregate(
- points.map(p => field.valueAccessor(p.data)),
+ points.map(p => {
+ return field.valueAccessor(p);
+ }),
aggregation
)
: points.length;
@@ -52,7 +57,8 @@ export default class AggregationLayer extends Layer {
constructor(props) {
super(props);
- this.getPositionAccessor = () => pointPosAccessor(this.config.columns);
+ this.getPositionAccessor = dataContainer =>
+ pointPosAccessor(this.config.columns)(dataContainer);
this.getColorRange = memoize(getLayerColorRange);
}
@@ -138,7 +144,7 @@ export default class AggregationLayer extends Layer {
/**
* Aggregation layer handles visual channel aggregation inside deck.gl layer
*/
- updateLayerVisualChannel({data, allData}, channel) {
+ updateLayerVisualChannel({data, dataContainer}, channel) {
this.validateVisualChannel(channel);
}
@@ -209,26 +215,25 @@ export default class AggregationLayer extends Layer {
return this;
}
- updateLayerMeta(allData, getPosition) {
+ updateLayerMeta(dataContainer, getPosition) {
// get bounds from points
- const bounds = this.getPointsBounds(allData, d => getPosition({data: d}));
+ const bounds = this.getPointsBounds(dataContainer, getPosition);
this.updateMeta({bounds});
}
- calculateDataAttribute({allData, filteredIndex}, getPosition) {
+ calculateDataAttribute({dataContainer, filteredIndex}, getPosition) {
const data = [];
for (let i = 0; i < filteredIndex.length; i++) {
const index = filteredIndex[i];
- const pos = getPosition({data: allData[index]});
+ const pos = getPosition({index});
// if doesn't have point lat or lng, do not add the point
// deck.gl can't handle position = null
if (pos.every(Number.isFinite)) {
data.push({
- index,
- data: allData[index]
+ index
});
}
}
@@ -237,8 +242,8 @@ export default class AggregationLayer extends Layer {
}
formatLayerData(datasets, oldLayerData) {
- const getPosition = this.getPositionAccessor(); // if (
- const {gpuFilter} = datasets[this.config.dataId];
+ const {gpuFilter, dataContainer} = datasets[this.config.dataId];
+ const getPosition = this.getPositionAccessor(dataContainer);
const getColorValue = getValueAggrFunc(
this.config.colorField,
@@ -250,7 +255,8 @@ export default class AggregationLayer extends Layer {
this.config.visConfig.sizeAggregation
);
const hasFilter = Object.values(gpuFilter.filterRange).some(arr => arr.some(v => v !== 0));
- const getFilterValue = gpuFilter.filterValueAccessor();
+
+ const getFilterValue = gpuFilter.filterValueAccessor(dataContainer)();
const filterData = hasFilter
? getFilterDataFunc(gpuFilter.filterRange, getFilterValue)
: undefined;
diff --git a/src/layers/arc-layer/arc-layer.js b/src/layers/arc-layer/arc-layer.js
index c2f81d7fc..7801c4c8a 100644
--- a/src/layers/arc-layer/arc-layer.js
+++ b/src/layers/arc-layer/arc-layer.js
@@ -26,12 +26,12 @@ import {hexToRgb} from 'utils/color-utils';
import ArcLayerIcon from './arc-layer-icon';
import {DEFAULT_LAYER_COLOR} from 'constants/default-settings';
-export const arcPosAccessor = ({lat0, lng0, lat1, lng1}) => d => [
- d.data[lng0.fieldIdx],
- d.data[lat0.fieldIdx],
+export const arcPosAccessor = ({lat0, lng0, lat1, lng1}) => dc => d => [
+ dc.valueAt(d.index, lng0.fieldIdx),
+ dc.valueAt(d.index, lat0.fieldIdx),
0,
- d.data[lng1.fieldIdx],
- d.data[lat1.fieldIdx],
+ dc.valueAt(d.index, lng1.fieldIdx),
+ dc.valueAt(d.index, lat1.fieldIdx),
0
];
@@ -56,7 +56,7 @@ export default class ArcLayer extends Layer {
super(props);
this.registerVisConfig(arcVisConfigs);
- this.getPositionAccessor = () => arcPosAccessor(this.config.columns);
+ this.getPositionAccessor = dataContainer => arcPosAccessor(this.config.columns)(dataContainer);
}
get type() {
@@ -127,11 +127,11 @@ export default class ArcLayer extends Layer {
return {props: [props]};
}
- calculateDataAttribute({allData, filteredIndex}, getPosition) {
+ calculateDataAttribute({dataContainer, filteredIndex}, getPosition) {
const data = [];
for (let i = 0; i < filteredIndex.length; i++) {
const index = filteredIndex[i];
- const pos = getPosition({data: allData[index]});
+ const pos = getPosition({index});
// if doesn't have point lat or lng, do not add the point
// deck.gl can't handle position = null
@@ -139,8 +139,7 @@ export default class ArcLayer extends Layer {
data.push({
index,
sourcePosition: [pos[0], pos[1], pos[2]],
- targetPosition: [pos[3], pos[4], pos[5]],
- data: allData[index]
+ targetPosition: [pos[3], pos[4], pos[5]]
});
}
}
@@ -149,27 +148,27 @@ export default class ArcLayer extends Layer {
}
formatLayerData(datasets, oldLayerData) {
- const {gpuFilter} = datasets[this.config.dataId];
+ const {gpuFilter, dataContainer} = datasets[this.config.dataId];
const {data} = this.updateData(datasets, oldLayerData);
- const accessors = this.getAttributeAccessors();
+ const accessors = this.getAttributeAccessors({dataContainer});
return {
data,
- getFilterValue: gpuFilter.filterValueAccessor(),
+ getFilterValue: gpuFilter.filterValueAccessor(dataContainer)(),
...accessors
};
}
/* eslint-enable complexity */
- updateLayerMeta(allData) {
+ updateLayerMeta(dataContainer) {
// get bounds from arcs
- const getPosition = this.getPositionAccessor();
+ const getPosition = this.getPositionAccessor(dataContainer);
- const sBounds = this.getPointsBounds(allData, d => {
- const pos = getPosition({data: d});
+ const sBounds = this.getPointsBounds(dataContainer, (d, i) => {
+ const pos = getPosition(d);
return [pos[0], pos[1]];
});
- const tBounds = this.getPointsBounds(allData, d => {
- const pos = getPosition({data: d});
+ const tBounds = this.getPointsBounds(dataContainer, (d, i) => {
+ const pos = getPosition(d);
return [pos[3], pos[4]];
});
diff --git a/src/layers/base-layer.js b/src/layers/base-layer.js
index ef76766fb..d2f5a6d99 100644
--- a/src/layers/base-layer.js
+++ b/src/layers/base-layer.js
@@ -50,7 +50,8 @@ import {
import {generateHashId, isPlainObject} from 'utils/utils';
-import {getSampleData, getLatLngBounds, notNullorUndefined} from 'utils/data-utils';
+import {getLatLngBounds, notNullorUndefined} from 'utils/data-utils';
+import {getSampleData} from 'utils/table-utils/data-container-utils';
import {hexToRgb, getColorGroupByName, reverseColorRange} from 'utils/color-utils';
@@ -65,8 +66,9 @@ export const LAYER_ID_LENGTH = 6;
const MAX_SAMPLE_SIZE = 5000;
const defaultDomain = [0, 1];
const dataFilterExtension = new DataFilterExtension({filterSize: MAX_GPU_FILTERS});
-const identity = d => d;
-const defaultDataAccessor = d => d.data;
+
+const defaultDataAccessor = dc => d => d;
+const defaultGetFieldValue = (field, d) => field.valueAccessor(d);
export const OVERLAY_TYPE = keymirror({
deckgl: null,
@@ -85,7 +87,6 @@ function* generateColor() {
}
export const colorMaker = generateColor();
-const defaultGetFieldValue = (field, d) => field.valueAccessor(d);
/** @type {LayerClass} */
class Layer {
@@ -421,14 +422,14 @@ class Layer {
return [];
}
- getHoverData(object) {
+ getHoverData(object, dataContainer) {
if (!object) {
return null;
}
- // by default, each entry of layerData should have a data property points
- // to the original item in the allData array
- // each layer can implement its own getHoverData method
- return object.data;
+
+ // By default, each entry of layerData should have an index of a row in the original data container.
+ // Each layer can implement its own getHoverData method
+ return dataContainer.row(object.index);
}
/**
@@ -734,10 +735,12 @@ class Layer {
/**
* Mapping from visual channels to deck.gl accesors
- * @param {Function} dataAccessor - access kepler.gl layer data from deck.gl layer
+ * @param {Object} param Parameters
+ * @param {Function} param.dataAccessor Access kepler.gl layer data from deck.gl layer
+ * @param {import('utils/table-utils/data-container-interface').DataContainerInterface} param.dataContainer DataContainer to use use with dataAccessor
* @return {Object} attributeAccessors - deck.gl layer attribute accessors
*/
- getAttributeAccessors(dataAccessor = defaultDataAccessor) {
+ getAttributeAccessors({dataAccessor = defaultDataAccessor, dataContainer}) {
const attributeAccessors = {};
Object.keys(this.visualChannels).forEach(channel => {
@@ -768,7 +771,7 @@ class Layer {
attributeAccessors[accessor] = d =>
this.getEncodedChannelValue(
scaleFunction,
- dataAccessor(d),
+ dataAccessor(dataContainer)(d),
this.config[field],
nullValue
);
@@ -780,7 +783,7 @@ class Layer {
}
if (!attributeAccessors[accessor]) {
- Console.warn(`Failed to provide accesso function for ${accessor || channel}`);
+ Console.warn(`Failed to provide accessor function for ${accessor || channel}`);
}
});
@@ -793,12 +796,21 @@ class Layer {
.range(fixed ? domain : range);
}
- getPointsBounds(allData, getPosition = identity) {
+ /**
+ * Get longitude and latitude bounds of the data.
+ * @param {import('utils/table-utils/data-container-interface').DataContainerInterface} dataContainer DataContainer to calculate bounds for.
+ * @param {(d: {index: number}, dc: import('utils/table-utils/data-container-interface').DataContainerInterface) => number[]} getPosition Access kepler.gl layer data from deck.gl layer
+ * @return {number[]|null} bounds of the data.
+ */
+ getPointsBounds(dataContainer, getPosition) {
// no need to loop through the entire dataset
// get a sample of data to calculate bounds
const sampleData =
- allData.length > MAX_SAMPLE_SIZE ? getSampleData(allData, MAX_SAMPLE_SIZE) : allData;
- const points = sampleData.map(getPosition);
+ dataContainer.numRows() > MAX_SAMPLE_SIZE
+ ? getSampleData(dataContainer, MAX_SAMPLE_SIZE)
+ : dataContainer;
+
+ const points = sampleData.mapIndex(getPosition);
const latBounds = getLatLngBounds(points, 1, [-90, 90]);
const lngBounds = getLatLngBounds(points, 0, [-180, 180]);
@@ -872,14 +884,14 @@ class Layer {
return {};
}
const layerDataset = datasets[this.config.dataId];
- const {allData} = datasets[this.config.dataId];
+ const {dataContainer} = layerDataset;
- const getPosition = this.getPositionAccessor();
+ const getPosition = this.getPositionAccessor(dataContainer);
const dataUpdateTriggers = this.getDataUpdateTriggers(layerDataset);
const triggerChanged = this.getChangedTriggers(dataUpdateTriggers);
if (triggerChanged.getMeta) {
- this.updateLayerMeta(allData, getPosition);
+ this.updateLayerMeta(dataContainer, getPosition);
}
let data = [];
@@ -893,6 +905,7 @@ class Layer {
return {data, triggerChanged};
}
+
/**
* helper function to update one layer domain when state.data changed
* if state.data change is due ot update filter, newFiler will be passed
@@ -909,7 +922,7 @@ class Layer {
Object.values(this.visualChannels).forEach(channel => {
const {scale} = channel;
const scaleType = this.config[scale];
- // ordinal domain is based on allData, if only filter changed
+ // ordinal domain is based on dataContainer, if only filter changed
// no need to update ordinal domain
if (!newFilter || scaleType !== SCALE_TYPES.ordinal) {
const {domain} = channel;
@@ -1137,16 +1150,16 @@ class Layer {
}, []);
}
- calculateDataAttribute(dataset, getPosition) {
+ calculateDataAttribute(keplerTable, getPosition) {
// implemented in subclasses
return [];
}
- updateLayerMeta(allData, getPosition) {
+ updateLayerMeta(dataContainer, getPosition) {
// implemented in subclasses
}
- getPositionAccessor() {
+ getPositionAccessor(dataContainer) {
// implemented in subclasses
return () => null;
}
diff --git a/src/layers/geojson-layer/geojson-layer.js b/src/layers/geojson-layer/geojson-layer.js
index 8f324248d..3c607711f 100644
--- a/src/layers/geojson-layer/geojson-layer.js
+++ b/src/layers/geojson-layer/geojson-layer.js
@@ -61,7 +61,8 @@ export const geojsonVisConfigs = {
};
export const geoJsonRequiredColumns = ['geojson'];
-export const featureAccessor = ({geojson}) => d => d[geojson.fieldIdx];
+export const featureAccessor = ({geojson}) => dc => d => dc.valueAt(d.index, geojson.fieldIdx);
+
// access feature properties from geojson sub layer
export const defaultElevation = 500;
export const defaultLineWidth = 1;
@@ -73,7 +74,7 @@ export default class GeoJsonLayer extends Layer {
this.dataToFeature = [];
this.registerVisConfig(geojsonVisConfigs);
- this.getPositionAccessor = () => featureAccessor(this.config.columns);
+ this.getPositionAccessor = dataContainer => featureAccessor(this.config.columns)(dataContainer);
}
get type() {
@@ -156,10 +157,6 @@ export default class GeoJsonLayer extends Layer {
};
}
- getPositionAccessor() {
- return this.getFeature(this.config.columns);
- }
-
static findDefaultLayerProps({label, fields = []}) {
const geojsonColumns = fields
.filter(f => f.type === 'geojson' && SUPPORTED_ANALYZER_TYPES[f.analyzerType])
@@ -204,32 +201,40 @@ export default class GeoJsonLayer extends Layer {
};
}
- getHoverData(object, allData) {
- // index of allData is saved to feature.properties
- return allData[object.properties.index];
+ getHoverData(object, dataContainer) {
+ // index of dataContainer is saved to feature.properties
+ return dataContainer.row(object.properties.index);
}
- calculateDataAttribute({allData, filteredIndex}, getPosition) {
+ calculateDataAttribute({dataContainer, filteredIndex}, getPosition) {
return filteredIndex.map(i => this.dataToFeature[i]).filter(d => d);
}
formatLayerData(datasets, oldLayerData) {
- const {allData, gpuFilter} = datasets[this.config.dataId];
+ const {gpuFilter, dataContainer} = datasets[this.config.dataId];
const {data} = this.updateData(datasets, oldLayerData);
- const valueAccessor = f => allData[f.properties.index];
+
+ const customFilterValueAccessor = (dc, d, fieldIndex) => {
+ return dc.valueAt(d.properties.index, fieldIndex);
+ };
const indexAccessor = f => f.properties.index;
- const accessors = this.getAttributeAccessors(valueAccessor);
+
+ const dataAccessor = dc => d => ({index: d.properties.index});
+ const accessors = this.getAttributeAccessors({dataAccessor, dataContainer});
return {
data,
- getFilterValue: gpuFilter.filterValueAccessor(indexAccessor, valueAccessor),
+ getFilterValue: gpuFilter.filterValueAccessor(dataContainer)(
+ indexAccessor,
+ customFilterValueAccessor
+ ),
...accessors
};
}
- updateLayerMeta(allData) {
- const getFeature = this.getPositionAccessor();
- this.dataToFeature = getGeojsonDataMaps(allData, getFeature);
+ updateLayerMeta(dataContainer) {
+ const getFeature = this.getPositionAccessor(dataContainer);
+ this.dataToFeature = getGeojsonDataMaps(dataContainer, getFeature);
// get bounds from features
const bounds = getGeojsonBounds(this.dataToFeature);
@@ -244,8 +249,8 @@ export default class GeoJsonLayer extends Layer {
this.updateMeta({bounds, fixedRadius, featureTypes});
}
- setInitialLayerConfig({allData}) {
- this.updateLayerMeta(allData);
+ setInitialLayerConfig({dataContainer}) {
+ this.updateLayerMeta(dataContainer);
const {featureTypes} = this.meta;
// default settings is stroke: true, filled: false
diff --git a/src/layers/geojson-layer/geojson-utils.js b/src/layers/geojson-layer/geojson-utils.js
index e5327ec0f..4910cdc2b 100644
--- a/src/layers/geojson-layer/geojson-utils.js
+++ b/src/layers/geojson-layer/geojson-utils.js
@@ -53,11 +53,11 @@ export function parseGeoJsonRawFeature(rawFeature) {
}
/**
* Parse raw data to GeoJson feature
- * @param allData
+ * @param dataContainer
* @param getFeature
* @returns {{}}
*/
-export function getGeojsonDataMaps(allData, getFeature) {
+export function getGeojsonDataMaps(dataContainer, getFeature) {
const acceptableTypes = [
'Point',
'MultiPoint',
@@ -70,8 +70,8 @@ export function getGeojsonDataMaps(allData, getFeature) {
const dataToFeature = [];
- for (let index = 0; index < allData.length; index++) {
- const feature = parseGeoJsonRawFeature(getFeature(allData[index]));
+ for (let index = 0; index < dataContainer.numRows(); index++) {
+ const feature = parseGeoJsonRawFeature(getFeature({index}));
if (feature && feature.geometry && acceptableTypes.includes(feature.geometry.type)) {
const cleaned = {
diff --git a/src/layers/h3-hexagon-layer/h3-hexagon-layer.js b/src/layers/h3-hexagon-layer/h3-hexagon-layer.js
index 8356a4b83..aa5ff88bd 100644
--- a/src/layers/h3-hexagon-layer/h3-hexagon-layer.js
+++ b/src/layers/h3-hexagon-layer/h3-hexagon-layer.js
@@ -27,10 +27,13 @@ import {getCentroid, idToPolygonGeo, h3IsValid, getHexFields} from './h3-utils';
import H3HexagonLayerIcon from './h3-hexagon-layer-icon';
import {CHANNEL_SCALES, HIGHLIGH_COLOR_3D} from 'constants/default-settings';
+import {createDataContainer} from 'utils/table-utils';
+
const DEFAULT_LINE_SCALE_VALUE = 8;
export const hexIdRequiredColumns = ['hex_id'];
-export const hexIdAccessor = ({hex_id}) => d => d.data[hex_id.fieldIdx];
+export const hexIdAccessor = ({hex_id}) => dc => d => dc.valueAt(d.index, hex_id.fieldIdx);
+
export const defaultElevation = 500;
export const defaultCoverage = 1;
@@ -49,7 +52,7 @@ export default class HexagonIdLayer extends Layer {
constructor(props) {
super(props);
this.registerVisConfig(HexagonIdVisConfigs);
- this.getPositionAccessor = () => hexIdAccessor(this.config.columns);
+ this.getPositionAccessor = dataContainer => hexIdAccessor(this.config.columns)(dataContainer);
}
get type() {
@@ -112,8 +115,8 @@ export default class HexagonIdLayer extends Layer {
return this;
}
- static findDefaultLayerProps({fields = [], allData = []}) {
- const hexFields = getHexFields(fields, allData);
+ static findDefaultLayerProps({fields = [], dataContainer}) {
+ const hexFields = getHexFields(fields, dataContainer);
if (!hexFields.length) {
return {props: []};
}
@@ -143,19 +146,17 @@ export default class HexagonIdLayer extends Layer {
};
}
- calculateDataAttribute({allData, filteredIndex}, getHexId) {
+ calculateDataAttribute({dataContainer, filteredIndex}, getHexId) {
const data = [];
for (let i = 0; i < filteredIndex.length; i++) {
const index = filteredIndex[i];
- const id = getHexId({data: allData[index]});
+ const id = getHexId({index});
const centroid = this.dataToFeature.centroids[index];
if (centroid) {
data.push({
- // keep a reference to the original data index
index,
- data: allData[index],
id,
centroid
});
@@ -167,32 +168,36 @@ export default class HexagonIdLayer extends Layer {
// TODO: fix complexity
/* eslint-disable complexity */
formatLayerData(datasets, oldLayerData, opt = {}) {
- const {gpuFilter} = datasets[this.config.dataId];
- const getHexId = this.getPositionAccessor();
+ const {gpuFilter, dataContainer} = datasets[this.config.dataId];
+ const getHexId = this.getPositionAccessor(dataContainer);
const {data} = this.updateData(datasets, oldLayerData);
- const accessors = this.getAttributeAccessors();
+ const accessors = this.getAttributeAccessors({dataContainer});
return {
data,
getHexId,
- getFilterValue: gpuFilter.filterValueAccessor(),
+ getFilterValue: gpuFilter.filterValueAccessor(dataContainer)(),
...accessors
};
}
/* eslint-enable complexity */
- updateLayerMeta(allData, getHexId) {
- const centroids = allData.map((d, index) => {
- const id = getHexId({data: d});
+ updateLayerMeta(dataContainer, getHexId) {
+ const centroids = dataContainer.map((d, index) => {
+ const id = getHexId({index});
if (!h3IsValid(id)) {
return null;
}
// save a reference of centroids to dataToFeature
// so we don't have to re calculate it again
return getCentroid({id});
- });
+ }, true);
- const bounds = this.getPointsBounds(centroids);
+ const centroidsDataContainer = createDataContainer(centroids);
+
+ const bounds = this.getPointsBounds(centroidsDataContainer, (d, dc) => {
+ return [dc.valueAt(d.index, 0), dc.valueAt(d.index, 1)];
+ });
this.dataToFeature = {centroids};
this.updateMeta({bounds});
}
diff --git a/src/layers/h3-hexagon-layer/h3-utils.js b/src/layers/h3-hexagon-layer/h3-utils.js
index df8b97ce0..a27eb8b02 100644
--- a/src/layers/h3-hexagon-layer/h3-utils.js
+++ b/src/layers/h3-hexagon-layer/h3-utils.js
@@ -52,12 +52,14 @@ export function idToPolygonGeo(object, properties) {
};
}
-export const isHexField = (field, fieldIdx, allData) => {
+export const isHexField = (field, fieldIdx, dataContainer) => {
if (field.type !== ALL_FIELD_TYPES.string) {
return false;
}
- const firstDP = allData.find(d => notNullorUndefined(d[fieldIdx]));
- return firstDP && h3IsValid(firstDP[fieldIdx]);
+
+ const firstDP = dataContainer.find(d => notNullorUndefined(d.valueAt(fieldIdx)), true);
+ return firstDP && h3IsValid(firstDP.valueAt(fieldIdx));
};
-export const getHexFields = (fields, allData) => fields.filter((f, i) => isHexField(f, i, allData));
+export const getHexFields = (fields, dataContainer) =>
+ fields.filter((f, i) => isHexField(f, i, dataContainer));
diff --git a/src/layers/heatmap-layer/heatmap-layer.js b/src/layers/heatmap-layer/heatmap-layer.js
index e36218a66..bd0c30063 100644
--- a/src/layers/heatmap-layer/heatmap-layer.js
+++ b/src/layers/heatmap-layer/heatmap-layer.js
@@ -27,11 +27,9 @@ import HeatmapLayerIcon from './heatmap-layer-icon';
export const MAX_ZOOM_LEVEL = 18;
-export const pointPosAccessor = ({lat, lng}) => d => [
- // lng
- d[lng.fieldIdx],
- // lat
- d[lat.fieldIdx]
+export const pointPosAccessor = ({lat, lng}) => dc => d => [
+ dc.valueAt(d.index, lng.fieldIdx),
+ dc.valueAt(d.index, lat.fieldIdx)
];
export const pointColResolver = ({lat, lng}) => `${lat.fieldIdx}-${lng.fieldIdx}`;
@@ -135,13 +133,13 @@ class HeatmapLayer extends MapboxGLLayer {
return layerConfig;
}
- getPositionAccessor() {
- return this.getPosition(this.config.columns);
+ getPositionAccessor(dataContainer) {
+ return this.getPosition(this.config.columns)(dataContainer);
}
- updateLayerMeta(allData) {
- const getPosition = this.getPositionAccessor();
- const bounds = this.getPointsBounds(allData, d => getPosition(d));
+ updateLayerMeta(dataContainer) {
+ const getPosition = this.getPositionAccessor(dataContainer);
+ const bounds = this.getPointsBounds(dataContainer, getPosition);
this.updateMeta({bounds});
}
@@ -208,7 +206,8 @@ class HeatmapLayer extends MapboxGLLayer {
formatLayerData(datasets, oldLayerData) {
const {weightField} = this.config;
- const getPosition = this.getPositionAccessor();
+ const {dataContainer} = datasets[this.config.dataId];
+ const getPosition = this.getPositionAccessor(dataContainer);
const {data} = this.updateData(datasets, oldLayerData);
const newConfig = this.computeHeatmapConfiguration(this.config, datasets);
diff --git a/src/layers/icon-layer/icon-layer.js b/src/layers/icon-layer/icon-layer.js
index 8af9c44ae..610108934 100644
--- a/src/layers/icon-layer/icon-layer.js
+++ b/src/layers/icon-layer/icon-layer.js
@@ -32,12 +32,13 @@ const brushingExtension = new BrushingExtension();
export const SVG_ICON_URL = `${CLOUDFRONT}/icons/svg-icons.json`;
-export const iconPosAccessor = ({lat, lng, altitude}) => d => [
- d.data[lng.fieldIdx],
- d.data[lat.fieldIdx],
- altitude?.fieldIdx > -1 ? d.data[altitude.fieldIdx] : 0
+export const iconPosAccessor = ({lat, lng, altitude}) => dc => d => [
+ dc.valueAt(d.index, lng.fieldIdx),
+ dc.valueAt(d.index, lat.fieldIdx),
+ altitude?.fieldIdx > -1 ? dc.valueAt(d.index, altitude.fieldIdx) : 0
];
-export const iconAccessor = ({icon}) => d => d.data[icon.fieldIdx];
+
+export const iconAccessor = ({icon}) => dc => d => dc.valueAt(d.index, icon.fieldIdx);
export const iconRequiredColumns = ['lat', 'lng', 'icon'];
export const iconOptionalColumns = ['altitude'];
@@ -67,8 +68,8 @@ export default class IconLayer extends Layer {
super(props);
this.registerVisConfig(pointVisConfigs);
- this.getPositionAccessor = () => iconPosAccessor(this.config.columns);
- this.getIconAccessor = () => iconAccessor(this.config.columns);
+ this.getPositionAccessor = dataContainer => iconPosAccessor(this.config.columns)(dataContainer);
+ this.getIconAccessor = dataContainer => iconAccessor(this.config.columns)(dataContainer);
// prepare layer info modal
this._layerInfoModal = IconInfoModalFactory();
@@ -187,22 +188,22 @@ export default class IconLayer extends Layer {
return {props};
}
- calculateDataAttribute({allData, filteredIndex}, getPosition) {
- const getIcon = this.getIconAccessor();
+ calculateDataAttribute({dataContainer, filteredIndex}, getPosition) {
+ const getIcon = this.getIconAccessor(dataContainer);
const data = [];
for (let i = 0; i < filteredIndex.length; i++) {
const index = filteredIndex[i];
- const pos = getPosition({data: allData[index]});
- const icon = getIcon({data: allData[index]});
+ const rowIndex = {index};
+ const pos = getPosition(rowIndex);
+ const icon = getIcon(rowIndex);
// if doesn't have point lat or lng, do not add the point
// deck.gl can't handle position = null
if (pos.every(Number.isFinite) && typeof icon === 'string') {
data.push({
index,
- icon,
- data: allData[index]
+ icon
});
}
}
@@ -212,9 +213,10 @@ export default class IconLayer extends Layer {
formatLayerData(datasets, oldLayerData) {
const {textLabel} = this.config;
- const getPosition = this.getPositionAccessor();
+ const {gpuFilter, dataContainer} = datasets[this.config.dataId];
+
+ const getPosition = this.getPositionAccessor(dataContainer);
- const {gpuFilter} = datasets[this.config.dataId];
const {data, triggerChanged} = this.updateData(datasets, oldLayerData);
// get all distinct characters in the text labels
@@ -222,22 +224,23 @@ export default class IconLayer extends Layer {
textLabel,
triggerChanged,
oldLayerData,
- data
+ data,
+ dataContainer
});
- const accessors = this.getAttributeAccessors();
+ const accessors = this.getAttributeAccessors({dataContainer});
return {
data,
getPosition,
- getFilterValue: gpuFilter.filterValueAccessor(),
+ getFilterValue: gpuFilter.filterValueAccessor(dataContainer)(),
textLabels,
...accessors
};
}
- updateLayerMeta(allData, getPosition) {
- const bounds = this.getPointsBounds(allData, d => getPosition({data: d}));
+ updateLayerMeta(dataContainer, getPosition) {
+ const bounds = this.getPointsBounds(dataContainer, getPosition);
this.updateMeta({bounds});
}
diff --git a/src/layers/layer-text-label.js b/src/layers/layer-text-label.js
index d25b8eb06..a41d32659 100644
--- a/src/layers/layer-text-label.js
+++ b/src/layers/layer-text-label.js
@@ -52,12 +52,18 @@ export function getTextOffsetByRadius(radiusScale, getRadius, mapState) {
};
}
-export const textLabelAccessor = textLabel => d => {
- const val = textLabel.field.valueAccessor(d.data);
+export const textLabelAccessor = textLabel => dc => d => {
+ const val = textLabel.field.valueAccessor(d);
return notNullorUndefined(val) ? String(val) : '';
};
-export const formatTextLabelData = ({textLabel, triggerChanged, oldLayerData, data}) => {
+export const formatTextLabelData = ({
+ textLabel,
+ triggerChanged,
+ oldLayerData,
+ data,
+ dataContainer
+}) => {
return textLabel.map((tl, i) => {
if (!tl.field) {
// if no field selected,
@@ -67,7 +73,7 @@ export const formatTextLabelData = ({textLabel, triggerChanged, oldLayerData, da
};
}
- const getText = textLabelAccessor(tl);
+ const getText = textLabelAccessor(tl)(dataContainer);
let characterSet;
if (
diff --git a/src/layers/line-layer/line-layer.js b/src/layers/line-layer/line-layer.js
index 561f4002b..0b7d0e211 100644
--- a/src/layers/line-layer/line-layer.js
+++ b/src/layers/line-layer/line-layer.js
@@ -25,13 +25,13 @@ import LineLayerIcon from './line-layer-icon';
import ArcLayer from '../arc-layer/arc-layer';
import EnhancedLineLayer from 'deckgl-layers/line-layer/line-layer';
-export const linePosAccessor = ({lat0, lng0, lat1, lng1, alt0, alt1}) => d => [
- d.data[lng0.fieldIdx],
- d.data[lat0.fieldIdx],
- alt0?.fieldIdx > -1 ? d.data[alt0.fieldIdx] : 0,
- d.data[lng1.fieldIdx],
- d.data[lat1.fieldIdx],
- alt1?.fieldIdx > -1 ? d.data[alt1.fieldIdx] : 0
+export const linePosAccessor = ({lat0, lng0, lat1, lng1, alt0, alt1}) => dc => d => [
+ dc.valueAt(d.index, lng0.fieldIdx),
+ dc.valueAt(d.index, lat0.fieldIdx),
+ alt0?.fieldIdx > -1 ? dc.valueAt(d.index, alt0.fieldIdx) : 0,
+ dc.valueAt(d.index, lng1.fieldIdx),
+ dc.valueAt(d.index, lat1.fieldIdx),
+ alt1?.fieldIdx > -1 ? dc.valueAt(d.index, alt1.fieldIdx) : 0
];
export const lineRequiredColumns = ['lat0', 'lng0', 'lat1', 'lng1'];
@@ -63,7 +63,7 @@ export default class LineLayer extends ArcLayer {
super(props);
this.registerVisConfig(lineVisConfigs);
- this.getPositionAccessor = () => linePosAccessor(this.config.columns);
+ this.getPositionAccessor = dataContainer => linePosAccessor(this.config.columns)(dataContainer);
}
get type() {
diff --git a/src/layers/mapbox-utils.js b/src/layers/mapbox-utils.js
index 81a7ab048..2d44fe5f4 100644
--- a/src/layers/mapbox-utils.js
+++ b/src/layers/mapbox-utils.js
@@ -129,20 +129,15 @@ function updateSourceData(map, sourceId, data) {
source.setData(data);
}
}
+
/**
*
- * @param allData
* @param filteredIndex
- * @param getGeometry {(point: any) => any}
- * @param getProperties {(point: any, index: number) => any}
+ * @param getGeometry {({index: number}) => any}
+ * @param getProperties {({index: number}) => any}
* @returns FeatureCollection
*/
-export function geoJsonFromData(
- allData = [],
- filteredIndex = [],
- getGeometry,
- getProperties = (d, i) => {}
-) {
+export function geoJsonFromData(filteredIndex = [], getGeometry, getProperties = d => {}) {
const geojson = {
type: 'FeatureCollection',
/** @type {Feature[]} */
@@ -151,15 +146,15 @@ export function geoJsonFromData(
for (let i = 0; i < filteredIndex.length; i++) {
const index = filteredIndex[i];
- const point = allData[index];
- const geometry = getGeometry(point);
+ const rowIndex = {index};
+ const geometry = getGeometry(rowIndex);
if (geometry) {
geojson.features.push({
type: 'Feature',
properties: {
index,
- ...getProperties(point, index)
+ ...getProperties(rowIndex)
},
geometry
});
diff --git a/src/layers/mapboxgl-layer.js b/src/layers/mapboxgl-layer.js
index 6934123f3..9009dc5b7 100644
--- a/src/layers/mapboxgl-layer.js
+++ b/src/layers/mapboxgl-layer.js
@@ -99,7 +99,7 @@ class MapboxLayerGL extends Layer {
return updateTriggers;
}
- calculateDataAttribute({allData, filteredIndex, gpuFilter}, getPosition) {
+ calculateDataAttribute({dataContainer, filteredIndex, gpuFilter}, getPosition) {
const getGeometry = d => this.getGeometry(getPosition(d));
const vcFields = Object.values(this.visualChannels)
@@ -121,11 +121,11 @@ class MapboxLayerGL extends Layer {
// gpuField To property
const hasFilter = Object.values(filterValueUpdateTriggers).filter(d => d).length;
- const valueAccessor = filterValueAccessor();
+ const valueAccessor = filterValueAccessor(dataContainer)();
const getPropertyFromFilter = hasFilter
- ? (d, index) => {
- const filterValue = valueAccessor({data: d, index});
+ ? d => {
+ const filterValue = valueAccessor(d);
return Object.values(filterValueUpdateTriggers).reduce(
(accu, name, i) => ({
...accu,
@@ -136,12 +136,12 @@ class MapboxLayerGL extends Layer {
}
: d => ({});
- const getProperties = (d, i) => ({
+ const getProperties = d => ({
...getPropertyFromVisualChanel(d),
- ...getPropertyFromFilter(d, i)
+ ...getPropertyFromFilter(d)
});
- return geoJsonFromData(allData, filteredIndex, getGeometry, getProperties);
+ return geoJsonFromData(filteredIndex, getGeometry, getProperties);
}
// this layer is rendered at mapbox level
diff --git a/src/layers/point-layer/point-layer.js b/src/layers/point-layer/point-layer.js
index 01f5cf773..76a2e4c99 100644
--- a/src/layers/point-layer/point-layer.js
+++ b/src/layers/point-layer/point-layer.js
@@ -29,12 +29,10 @@ import {DEFAULT_LAYER_COLOR, CHANNEL_SCALES} from 'constants/default-settings';
import {getTextOffsetByRadius, formatTextLabelData} from '../layer-text-label';
-export const pointPosAccessor = ({lat, lng, altitude}) => d => [
- // lng
- d.data[lng.fieldIdx],
- // lat
- d.data[lat.fieldIdx],
- altitude && altitude.fieldIdx > -1 ? d.data[altitude.fieldIdx] : 0
+export const pointPosAccessor = ({lat, lng, altitude}) => dc => d => [
+ dc.valueAt(d.index, lng.fieldIdx),
+ dc.valueAt(d.index, lat.fieldIdx),
+ altitude && altitude.fieldIdx > -1 ? dc.valueAt(d.index, altitude.fieldIdx) : 0
];
export const pointRequiredColumns = ['lat', 'lng'];
@@ -65,7 +63,8 @@ export default class PointLayer extends Layer {
super(props);
this.registerVisConfig(pointVisConfigs);
- this.getPositionAccessor = () => pointPosAccessor(this.config.columns);
+ this.getPositionAccessor = dataContainer =>
+ pointPosAccessor(this.config.columns)(dataContainer);
}
get type() {
@@ -186,20 +185,18 @@ export default class PointLayer extends Layer {
};
}
- calculateDataAttribute({allData, filteredIndex}, getPosition) {
+ calculateDataAttribute({filteredIndex}, getPosition) {
const data = [];
for (let i = 0; i < filteredIndex.length; i++) {
const index = filteredIndex[i];
- const pos = getPosition({data: allData[index]});
+ const pos = getPosition({index});
// if doesn't have point lat or lng, do not add the point
// deck.gl can't handle position = null
if (pos.every(Number.isFinite)) {
data.push({
- data: allData[index],
position: pos,
- // index is important for filter
index
});
}
@@ -209,33 +206,34 @@ export default class PointLayer extends Layer {
formatLayerData(datasets, oldLayerData) {
const {textLabel} = this.config;
- const {gpuFilter} = datasets[this.config.dataId];
+ const {gpuFilter, dataContainer} = datasets[this.config.dataId];
const {data, triggerChanged} = this.updateData(datasets, oldLayerData);
- const getPosition = this.getPositionAccessor();
+ const getPosition = this.getPositionAccessor(dataContainer);
// get all distinct characters in the text labels
const textLabels = formatTextLabelData({
textLabel,
triggerChanged,
oldLayerData,
- data
+ data,
+ dataContainer
});
- const accessors = this.getAttributeAccessors();
+ const accessors = this.getAttributeAccessors({dataContainer});
return {
data,
getPosition,
- getFilterValue: gpuFilter.filterValueAccessor(),
+ getFilterValue: gpuFilter.filterValueAccessor(dataContainer)(),
textLabels,
...accessors
};
}
/* eslint-enable complexity */
- updateLayerMeta(allData) {
- const getPosition = this.getPositionAccessor();
- const bounds = this.getPointsBounds(allData, d => getPosition({data: d}));
+ updateLayerMeta(dataContainer) {
+ const getPosition = this.getPositionAccessor(dataContainer);
+ const bounds = this.getPointsBounds(dataContainer, getPosition);
this.updateMeta({bounds});
}
diff --git a/src/layers/s2-geometry-layer/s2-geometry-layer.js b/src/layers/s2-geometry-layer/s2-geometry-layer.js
index f113f0255..4e328d8ce 100644
--- a/src/layers/s2-geometry-layer/s2-geometry-layer.js
+++ b/src/layers/s2-geometry-layer/s2-geometry-layer.js
@@ -21,6 +21,7 @@
import {S2Layer} from '@deck.gl/geo-layers';
import {HIGHLIGH_COLOR_3D, CHANNEL_SCALES} from 'constants/default-settings';
import {LAYER_VIS_CONFIGS} from 'layers/layer-factory';
+import {createDataContainer} from 'utils/table-utils';
import Layer from '../base-layer';
import S2LayerIcon from './s2-layer-icon';
import {getS2Center} from './s2-utils';
@@ -32,7 +33,8 @@ export const S2_TOKEN_FIELDS = {
};
export const s2RequiredColumns = ['token'];
-export const S2TokenAccessor = ({token}) => d => d.data[token.fieldIdx];
+export const S2TokenAccessor = ({token}) => dc => d => dc.valueAt(d.index, token.fieldIdx);
+
export const defaultElevation = 500;
export const defaultLineWidth = 1;
@@ -71,7 +73,7 @@ export default class S2GeometryLayer extends Layer {
constructor(props) {
super(props);
this.registerVisConfig(S2VisConfigs);
- this.getPositionAccessor = () => S2TokenAccessor(this.config.columns);
+ this.getPositionAccessor = dataContainer => S2TokenAccessor(this.config.columns)(dataContainer);
}
get type() {
@@ -164,17 +166,15 @@ export default class S2GeometryLayer extends Layer {
};
}
- calculateDataAttribute({allData, filteredIndex}, getS2Token) {
+ calculateDataAttribute({dataContainer, filteredIndex}, getS2Token) {
const data = [];
for (let i = 0; i < filteredIndex.length; i++) {
const index = filteredIndex[i];
- const token = getS2Token({data: allData[index]});
+ const token = getS2Token({index});
if (token) {
data.push({
- // keep a reference to the original data index
index,
- data: allData[index],
token
});
}
@@ -182,28 +182,37 @@ export default class S2GeometryLayer extends Layer {
return data;
}
- updateLayerMeta(allData, getS2Token) {
- const centroids = allData.reduce((acc, entry) => {
- const s2Token = getS2Token({data: entry});
- return s2Token ? [...acc, getS2Center(s2Token)] : acc;
- }, []);
-
- const bounds = this.getPointsBounds(centroids);
+ updateLayerMeta(dataContainer, getS2Token) {
+ // add safe row flag
+ const centroids = dataContainer.reduce(
+ (acc, entry, index) => {
+ const s2Token = getS2Token({index});
+ return s2Token ? [...acc, getS2Center(s2Token)] : acc;
+ },
+ [],
+ true
+ );
+
+ const centroidsDataContainer = createDataContainer(centroids);
+ const bounds = this.getPointsBounds(centroidsDataContainer, (d, dc) => [
+ dc.valueAt(d.index, 0),
+ dc.valueAt(d.index, 1)
+ ]);
this.dataToFeature = {centroids};
this.updateMeta({bounds});
}
formatLayerData(datasets, oldLayerData, opt = {}) {
- const {gpuFilter} = datasets[this.config.dataId];
- const getS2Token = this.getPositionAccessor();
+ const {gpuFilter, dataContainer} = datasets[this.config.dataId];
+ const getS2Token = this.getPositionAccessor(dataContainer);
const {data} = this.updateData(datasets, oldLayerData);
- const accessors = this.getAttributeAccessors();
+ const accessors = this.getAttributeAccessors({dataContainer});
return {
data,
getS2Token,
- getFilterValue: gpuFilter.filterValueAccessor(),
+ getFilterValue: gpuFilter.filterValueAccessor(dataContainer)(),
...accessors
};
}
diff --git a/src/layers/scenegraph-layer/scenegraph-layer.js b/src/layers/scenegraph-layer/scenegraph-layer.js
index 99452cba0..6f52b67c9 100644
--- a/src/layers/scenegraph-layer/scenegraph-layer.js
+++ b/src/layers/scenegraph-layer/scenegraph-layer.js
@@ -38,13 +38,10 @@ function fetch(url, {propName, layer}) {
return fetch(url).then(response => response.json());
}
-export const scenegraphPosAccessor = ({lat, lng, altitude}) => d => [
- // lng
- d.data[lng.fieldIdx],
- // lat
- d.data[lat.fieldIdx],
- // altitude
- altitude && altitude.fieldIdx > -1 ? d.data[altitude.fieldIdx] : 0
+export const scenegraphPosAccessor = ({lat, lng, altitude}) => dc => d => [
+ dc.valueAt(d.index, lng.fieldIdx),
+ dc.valueAt(d.index, lat.fieldIdx),
+ altitude && altitude.fieldIdx > -1 ? dc.valueAt(d.index, altitude.fieldIdx) : 0
];
export const scenegraphVisConfigs = {
@@ -81,7 +78,8 @@ export default class ScenegraphLayer extends Layer {
super(props);
this.registerVisConfig(scenegraphVisConfigs);
- this.getPositionAccessor = () => scenegraphPosAccessor(this.config.columns);
+ this.getPositionAccessor = dataContainer =>
+ scenegraphPosAccessor(this.config.columns)(dataContainer);
// prepare layer info modal
this._layerInfoModal = ScenegraphInfoModalFactory();
@@ -117,20 +115,18 @@ export default class ScenegraphLayer extends Layer {
};
}
- calculateDataAttribute({allData, filteredIndex}, getPosition) {
+ calculateDataAttribute({dataContainer, filteredIndex}, getPosition) {
const data = [];
for (let i = 0; i < filteredIndex.length; i++) {
const index = filteredIndex[i];
- const pos = getPosition({data: allData[index]});
+ const pos = getPosition({index});
// if doesn't have point lat or lng, do not add the point
// deck.gl can't handle position = null
if (pos.every(Number.isFinite)) {
data.push({
- data: allData[index],
position: pos,
- // index is important for filter
index
});
}
@@ -139,18 +135,18 @@ export default class ScenegraphLayer extends Layer {
}
formatLayerData(datasets, oldLayerData) {
- const {gpuFilter} = datasets[this.config.dataId];
+ const {gpuFilter, dataContainer} = datasets[this.config.dataId];
const {data} = this.updateData(datasets, oldLayerData);
- const getPosition = this.getPositionAccessor();
+ const getPosition = this.getPositionAccessor(dataContainer);
return {
data,
getPosition,
- getFilterValue: gpuFilter.filterValueAccessor()
+ getFilterValue: gpuFilter.filterValueAccessor(dataContainer)()
};
}
- updateLayerMeta(allData, getPosition) {
- const bounds = this.getPointsBounds(allData, d => getPosition({data: d}));
+ updateLayerMeta(dataContainer, getPosition) {
+ const bounds = this.getPointsBounds(dataContainer, getPosition);
this.updateMeta({bounds});
}
diff --git a/src/layers/trip-layer/trip-layer.js b/src/layers/trip-layer/trip-layer.js
index cb8fd904c..f05488389 100644
--- a/src/layers/trip-layer/trip-layer.js
+++ b/src/layers/trip-layer/trip-layer.js
@@ -58,7 +58,7 @@ export const tripVisConfigs = {
};
export const geoJsonRequiredColumns = ['geojson'];
-export const featureAccessor = ({geojson}) => d => d[geojson.fieldIdx];
+export const featureAccessor = ({geojson}) => dc => d => dc.valueAt(d.index, geojson.fieldIdx);
export const featureResolver = ({geojson}) => geojson.fieldIdx;
export default class TripLayer extends Layer {
@@ -126,11 +126,11 @@ export default class TripLayer extends Layer {
};
}
- getPositionAccessor() {
- return this.getFeature(this.config.columns);
+ getPositionAccessor(dataContainer) {
+ return this.getFeature(this.config.columns)(dataContainer);
}
- static findDefaultLayerProps({label, fields = [], allData = [], id}, foundLayers) {
+ static findDefaultLayerProps({label, fields = [], dataContainer, id}, foundLayers) {
const geojsonColumns = fields.filter(f => f.type === 'geojson').map(f => f.name);
const defaultColumns = {
@@ -140,7 +140,7 @@ export default class TripLayer extends Layer {
const geoJsonColumns = this.findDefaultColumnField(defaultColumns, fields);
const tripColumns = (geoJsonColumns || []).filter(col =>
- isTripGeoJsonField(allData, fields[col.geojson.fieldIdx])
+ isTripGeoJsonField(dataContainer, fields[col.geojson.fieldIdx])
);
if (!tripColumns.length) {
@@ -174,29 +174,36 @@ export default class TripLayer extends Layer {
};
}
- getHoverData(object, allData) {
- // index of allData is saved to feature.properties
- return allData[object.properties.index];
+ getHoverData(object, dataContainer) {
+ // index for dataContainer is saved to feature.properties
+ return dataContainer.row(object.properties.index);
}
- calculateDataAttribute({allData, filteredIndex}, getPosition) {
+ calculateDataAttribute({dataContainer, filteredIndex}, getPosition) {
return filteredIndex
.map(i => this.dataToFeature[i])
.filter(d => d && d.geometry.type === 'LineString');
}
formatLayerData(datasets, oldLayerData) {
- // to-do: parse segment from allData
- const {allData, gpuFilter} = datasets[this.config.dataId];
+ // to-do: parse segment from dataContainer
+ const {dataContainer, gpuFilter} = datasets[this.config.dataId];
const {data} = this.updateData(datasets, oldLayerData);
- const valueAccessor = f => allData[f.properties.index];
+ const customFilterValueAccessor = (dc, f, fieldIndex) => {
+ return dc.valueAt(f.properties.index, fieldIndex);
+ };
const indexAccessor = f => f.properties.index;
- const accessors = this.getAttributeAccessors(valueAccessor);
+
+ const dataAccessor = dc => d => ({index: d.properties.index});
+ const accessors = this.getAttributeAccessors({dataAccessor, dataContainer});
return {
data,
- getFilterValue: gpuFilter.filterValueAccessor(indexAccessor, valueAccessor),
+ getFilterValue: gpuFilter.filterValueAccessor(dataContainer)(
+ indexAccessor,
+ customFilterValueAccessor
+ ),
getPath: d => d.geometry.coordinates,
getTimestamps: d => this.dataToTimeStamp[d.properties.index],
...accessors
@@ -212,14 +219,14 @@ export default class TripLayer extends Layer {
});
}
- updateLayerMeta(allData) {
- const getFeature = this.getPositionAccessor();
+ updateLayerMeta(dataContainer) {
+ const getFeature = this.getPositionAccessor(dataContainer);
if (getFeature === this.meta.getFeature) {
// TODO: revisit this after gpu filtering
return;
}
- this.dataToFeature = getGeojsonDataMaps(allData, getFeature);
+ this.dataToFeature = getGeojsonDataMaps(dataContainer, getFeature);
const {dataToTimeStamp, animationDomain} = parseTripGeoJsonTimestamp(this.dataToFeature);
@@ -235,8 +242,8 @@ export default class TripLayer extends Layer {
this.updateMeta({bounds, featureTypes, getFeature});
}
- setInitialLayerConfig({allData}) {
- this.updateLayerMeta(allData);
+ setInitialLayerConfig({dataContainer}) {
+ this.updateLayerMeta(dataContainer);
return this;
}
diff --git a/src/layers/trip-layer/trip-utils.js b/src/layers/trip-layer/trip-utils.js
index 3902dc2c2..4fde96f6d 100644
--- a/src/layers/trip-layer/trip-utils.js
+++ b/src/layers/trip-layer/trip-utils.js
@@ -20,7 +20,8 @@
import {Analyzer, DATA_TYPES} from 'type-analyzer';
-import {getSampleData, timeToUnixMilli, notNullorUndefined} from 'utils/data-utils';
+import {timeToUnixMilli, notNullorUndefined} from 'utils/data-utils';
+import {getSampleData} from 'utils/table-utils/data-container-utils';
import {parseGeoJsonRawFeature, getGeojsonFeatureTypes} from 'layers/geojson-layer/geojson-utils';
@@ -63,20 +64,23 @@ export function containValidTime(timestamps) {
/**
* Check if geojson features are trip layer animatable by meeting 3 conditions
- * @param {array} allData array of geojson feature objects
+ * @param {import('utils/table-utils/data-container-interface').DataContainerInterface} dataContainer geojson feature objects container
* @param {object} field array of geojson feature objects
* @returns {boolean} whether it is trip layer animatable
*/
-export function isTripGeoJsonField(allData = [], field) {
- if (!allData.length) {
+export function isTripGeoJsonField(dataContainer, field) {
+ if (dataContainer.numRows() < 1) {
return false;
}
- const getValue = d => field.valueAccessor(d);
+
const maxCount = 10000;
const sampleRawFeatures =
- allData.length > maxCount ? getSampleData(allData, maxCount, getValue) : allData.map(getValue);
+ dataContainer.numRows() > maxCount ? getSampleData(dataContainer, maxCount) : dataContainer;
- const features = sampleRawFeatures.map(parseGeoJsonRawFeature).filter(f => f);
+ const features = sampleRawFeatures
+ .mapIndex(field.valueAccessor)
+ .map(parseGeoJsonRawFeature)
+ .filter(f => f);
const featureTypes = getGeojsonFeatureTypes(features);
// condition 1: contain line string
diff --git a/src/processors/data-processor.d.ts b/src/processors/data-processor.d.ts
index 13f40b7f3..46fd3a824 100644
--- a/src/processors/data-processor.d.ts
+++ b/src/processors/data-processor.d.ts
@@ -1,6 +1,7 @@
import {ProtoDataset} from '../actions';
import {Field} from 'reducers/vis-state-updaters';
import {SavedMap, ParsedDataset} from 'schemas';
+import {DataContainerInterface} from 'utils/table-utils/data-container-interface';
type RowData = {
[key: string]: any;
@@ -18,7 +19,7 @@ export function validateInputData(data: any): ProcessorResult;
export function getSampleForTypeAnalyze(p: {
fields: string[];
- allData: any[][];
+ rows: any[][];
sampleCount?: number;
}): object[];
@@ -31,7 +32,7 @@ export function parseCsvRowsByFieldType(
i: number
): void;
-export function formatCsv(data: any[][], fields: Field[]): string;
+export function formatCsv(data: DataContainerInterface, fields: Field[]): string;
export function analyzerTypeToFieldType(aType: string): string;
diff --git a/src/processors/data-processor.js b/src/processors/data-processor.js
index bd4288d49..83cff96de 100644
--- a/src/processors/data-processor.js
+++ b/src/processors/data-processor.js
@@ -138,7 +138,7 @@ export function processCsvData(rawData, header) {
cleanUpFalsyCsvValue(rows);
// No need to run type detection on every data point
// here we get a list of none null values to run analyze on
- const sample = getSampleForTypeAnalyze({fields: headerRow, allData: rows});
+ const sample = getSampleForTypeAnalyze({fields: headerRow, rows});
const fields = getFieldsFromData(sample, headerRow);
const parsedRows = parseRowsByFields(rows, fields);
@@ -162,8 +162,8 @@ export function parseRowsByFields(rows, fields) {
*
* @type {typeof import('./data-processor').getSampleForTypeAnalyze}
*/
-export function getSampleForTypeAnalyze({fields, allData, sampleCount = 50}) {
- const total = Math.min(sampleCount, allData.length);
+export function getSampleForTypeAnalyze({fields, rows, sampleCount = 50}) {
+ const total = Math.min(sampleCount, rows.length);
// const fieldOrder = fields.map(f => f.name);
const sample = range(0, total, 1).map(d => ({}));
@@ -175,15 +175,13 @@ export function getSampleForTypeAnalyze({fields, allData, sampleCount = 50}) {
let j = 0;
while (j < total) {
- if (i >= allData.length) {
+ if (i >= rows.length) {
// if depleted data pool
sample[j][field] = null;
j++;
- } else if (notNullorUndefined(allData[i][fieldIdx])) {
- sample[j][field] =
- typeof allData[i][fieldIdx] === 'string'
- ? allData[i][fieldIdx].trim()
- : allData[i][fieldIdx];
+ } else if (notNullorUndefined(rows[i][fieldIdx])) {
+ const value = rows[i][fieldIdx];
+ sample[j][field] = typeof value === 'string' ? value.trim() : value;
j++;
i++;
} else {
@@ -314,7 +312,9 @@ export function getFieldsFromData(data, fieldOrder) {
fieldIdx: index,
type: analyzerTypeToFieldType(type),
analyzerType: type,
- valueAccessor: values => values[index]
+ valueAccessor: dc => d => {
+ return dc.valueAt(d.index, index);
+ }
};
});
@@ -535,18 +535,18 @@ export function processGeojson(rawData) {
/**
* On export data to csv
- * @param {Array<Array>} data `dataset.allData` or filtered data `dataset.data`
+ * @param {import('utils/table-utils/data-container-interface').DataContainerInterface} dataContainer
* @param {Array<Object>} fields `dataset.fields`
* @returns {string} csv string
*/
-export function formatCsv(data, fields) {
+export function formatCsv(dataContainer, fields) {
const columns = fields.map(f => f.displayName || f.name);
const formattedData = [columns];
// parse geojson object as string
- data.forEach(row => {
+ for (const row of dataContainer.rows(true)) {
formattedData.push(row.map((d, i) => parseFieldValue(d, fields[i].type)));
- });
+ }
return csvFormatRows(formattedData);
}
@@ -610,7 +610,7 @@ export function validateInputData(data) {
// because we simply lost faith in humanity
const sampleData = getSampleForTypeAnalyze({
fields: fields.map(f => f.name),
- allData: rows
+ rows
});
const fieldOrder = fields.map(f => f.name);
const meta = getFieldsFromData(sampleData, fieldOrder);
@@ -635,6 +635,7 @@ function findNonEmptyRowsAtField(rows, fieldIdx, total) {
}
return sample;
}
+
/**
* Process saved kepler.gl json to be pass to [`addDataToMap`](../actions/actions.md#adddatatomap).
* The json object should contain `datasets` and `config`.
diff --git a/src/reducers/vis-state-updaters.js b/src/reducers/vis-state-updaters.js
index 9082efbf3..d4f8243e8 100644
--- a/src/reducers/vis-state-updaters.js
+++ b/src/reducers/vis-state-updaters.js
@@ -2063,7 +2063,9 @@ export function copyTableColumnUpdater(state, {dataId, column}) {
return state;
}
const {type} = dataset.fields[fieldIdx];
- const text = dataset.allData.map(d => parseFieldValue(d[fieldIdx], type)).join('\n');
+ const text = dataset.dataContainer
+ .map(row => parseFieldValue(row.valueAt(fieldIdx), type), true)
+ .join('\n');
copy(text);
diff --git a/src/schemas/dataset-schema.js b/src/schemas/dataset-schema.js
index ba7d24d4a..f96da5091 100644
--- a/src/schemas/dataset-schema.js
+++ b/src/schemas/dataset-schema.js
@@ -74,7 +74,14 @@ class DatasetSchema extends Schema {
key = 'dataset';
save(dataset) {
- return this.savePropertiesOrApplySchema(dataset)[this.key];
+ const datasetFlattened = dataset.dataContainer
+ ? {
+ ...dataset,
+ allData: dataset.dataContainer.flattenData()
+ }
+ : dataset;
+
+ return this.savePropertiesOrApplySchema(datasetFlattened)[this.key];
}
load(dataset) {
const {fields, allData} = dataset;
@@ -90,7 +97,10 @@ class DatasetSchema extends Schema {
if (needCalculateMeta) {
const fieldOrder = fields.map(f => f.name);
- const sampleData = getSampleForTypeAnalyze({fields: fieldOrder, allData});
+ const sampleData = getSampleForTypeAnalyze({
+ fields: fieldOrder,
+ rows: allData
+ });
const meta = getFieldsFromData(sampleData, fieldOrder);
updatedFields = meta.map((f, i) => ({
diff --git a/src/utils/data-scale-utils.d.ts b/src/utils/data-scale-utils.d.ts
index 1ac3d5e63..15a2b20e3 100644
--- a/src/utils/data-scale-utils.d.ts
+++ b/src/utils/data-scale-utils.d.ts
@@ -1,11 +1,26 @@
+import {DataContainerInterface} from './table-utils/data-container-interface';
+
function dataValueAccessor(any): any;
function sort(a: any, b: any): any;
+function dataContainerValueAccessor(d: {index: number}, dc: DataContainerInterface): any;
export function getQuantileDomain(
data: any[],
valueAccessor?: typeof dataValueAccessor,
sortFunc?: typeof sort
): number[];
-export function getOrdinalDomain(data: any[], valueAccessor?: typeof dataValueAccessor): string[];
-export function getLinearDomain(data: any[], valueAccessor?: typeof dataValueAccessor): [number, number];
-export function getLogDomain(data: any[], valueAccessor?: typeof dataValueAccessor): [number, number];
+
+export function getOrdinalDomain(
+ dataContainer: DataContainerInterface,
+ valueAccessor: typeof dataContainerValueAccessor
+): string[];
+
+export function getLinearDomain(
+ data: any[],
+ valueAccessor?: typeof dataValueAccessor
+): [number, number];
+
+export function getLogDomain(
+ data: any[],
+ valueAccessor?: typeof dataValueAccessor
+): [number, number];
diff --git a/src/utils/data-scale-utils.js b/src/utils/data-scale-utils.js
index a28717ee7..cdb68304a 100644
--- a/src/utils/data-scale-utils.js
+++ b/src/utils/data-scale-utils.js
@@ -32,11 +32,11 @@ export function getQuantileDomain(data, valueAccessor, sortFunc) {
}
/**
- * return ordinal domain for an array of data
+ * return ordinal domain for a data container
* @type {typeof import('./data-scale-utils').getOrdinalDomain}
*/
-export function getOrdinalDomain(data, valueAccessor) {
- const values = typeof valueAccessor === 'function' ? data.map(valueAccessor) : data;
+export function getOrdinalDomain(dataContainer, valueAccessor) {
+ const values = dataContainer.mapIndex(valueAccessor);
return unique(values)
.filter(notNullorUndefined)
@@ -59,6 +59,5 @@ export function getLinearDomain(data, valueAccessor) {
*/
export function getLogDomain(data, valueAccessor) {
const [d0, d1] = getLinearDomain(data, valueAccessor);
-
return [d0 === 0 ? 1e-5 : d0, d1];
}
diff --git a/src/utils/data-utils.d.ts b/src/utils/data-utils.d.ts
index 020d4fc47..3a84dd5c5 100644
--- a/src/utils/data-utils.d.ts
+++ b/src/utils/data-utils.d.ts
@@ -1,8 +1,10 @@
import {Millisecond} from 'reducers/types';
import {Layer, Field} from 'reducers/vis-state-updaters';
import {Bounds} from 'reducers/map-state-updaters';
+import {DataRow} from './table-utils/data-row';
+import {DataContainerInterface} from './table-utils/data-container-interface';
-export function maybeToDate(isTime: boolean, fieldIdx: number, format: string, d: any[]): any;
+export function maybeToDate(isTime: boolean, fieldIdx: number, format: string, dc: DataContainerInterface, d: {index: number}): any;
export function timeToUnixMilli(value: any, format: string): Millisecond | null;
export function notNullorUndefined<T extends NonNullable<any>>(d: T | null | undefined): d is T;
@@ -14,7 +16,11 @@ export function arrayMove(array: any[], from: number, to: number);
export function getSortingFunction(fieldType: string): numberSort | undefined;
export function preciseRound(num: number, decimals: number): string;
export function parseFieldValue(value: any, type: string): string;
-export function getLatLngBounds(points: [number, number], idx: number, limit: [number, number]): [number, number];
+export function getLatLngBounds(
+ points: number[][],
+ idx: number,
+ limit: [number, number]
+): [number, number] | null;
export function getSampleData(data: any[], sampleSize?: number, getValue?: any): any[];
export function findMapBounds(layers: Layer[]): Bounds | null;
function formatter(v: any): any;
diff --git a/src/utils/data-utils.js b/src/utils/data-utils.js
index a551c4382..bb15df8bc 100644
--- a/src/utils/data-utils.js
+++ b/src/utils/data-utils.js
@@ -129,12 +129,12 @@ export function timeToUnixMilli(value, format) {
*
* @type {typeof import('./data-utils').maybeToDate}
*/
-export function maybeToDate(isTime, fieldIdx, format, d) {
+export function maybeToDate(isTime, fieldIdx, format, dc, d) {
if (isTime) {
- return timeToUnixMilli(d[fieldIdx], format);
+ return timeToUnixMilli(dc.valueAt(d.index, fieldIdx), format);
}
- return d[fieldIdx];
+ return dc.valueAt(d.index, fieldIdx);
}
/**
diff --git a/src/utils/export-utils.js b/src/utils/export-utils.js
index f962f4712..d9983ef56 100644
--- a/src/utils/export-utils.js
+++ b/src/utils/export-utils.js
@@ -33,6 +33,8 @@ import {formatCsv} from 'processors/data-processor';
import get from 'lodash.get';
import {set, generateHashId} from 'utils/utils';
+import {createIndexedDataContainer} from './table-utils/data-container-utils';
+
/**
* Default file names
*/
@@ -203,8 +205,11 @@ export function exportData(state, option) {
}
selectedDatasets.forEach(selectedData => {
- const {allData, fields, label, filteredIdxCPU = []} = selectedData;
- const toExport = filtered ? filteredIdxCPU.map(i => allData[i]) : allData;
+ const {dataContainer, fields, label, filteredIdxCPU = []} = selectedData;
+ const toExport = filtered
+ ? createIndexedDataContainer(dataContainer, filteredIdxCPU)
+ : dataContainer;
+
// start to export data according to selected data type
switch (dataType) {
case EXPORT_DATA_TYPE.CSV: {
diff --git a/src/utils/filter-utils.d.ts b/src/utils/filter-utils.d.ts
index fc570c708..2b6419d25 100644
--- a/src/utils/filter-utils.d.ts
+++ b/src/utils/filter-utils.d.ts
@@ -18,6 +18,8 @@ import {Layer} from 'layers';
import {Field} from 'reducers/types';
import {ParsedConfig} from 'schemas';
import {FilterDatasetOpt} from './table-utils/kepler-table';
+import {DataContainerInterface} from './table-utils/data-container-interface';
+import {DataRow} from './table-utils/data-row';
export function applyFilterFieldName(
filter: Filter,
@@ -28,7 +30,7 @@ export function applyFilterFieldName(
): {
filter: Filter | null;
dataset: KeplerTable;
-}
+};
export function getDefaultFilter(dataId: string | null | string[]): FilterBase;
export function shouldApplyFilter(filter: Filter, datasetId: string): boolean;
@@ -64,14 +66,22 @@ export function getFilterRecord(
option?: FilterDatasetOpt
): FilterRecord;
-function filterFunction(data: any[], index?: number): boolean;
+/**
+ * @param param An object that represents a row record.
+ * @param param.index Index of the row in data container.
+ * @returns Returns true to keep the element, or false otherwise.
+ */
+function filterFunction(
+ data: {index: number}
+): boolean;
export function isValidFilterValue(type: string | null, value: any): boolean;
export function getFilterFunction(
field: Field | null,
dataId: string,
filter: Filter,
- layers: Layer[]
+ layers: Layer[],
+ dataContainer: DataContainerInterface
): typeof filterFunction;
export type FilterResult = {
@@ -86,7 +96,7 @@ export function filterDataByFilterTypes(
[key: string]: typeof filterFunction;
};
},
- allData: KeplerTable['allData']
+ dataContainer: DataContainerInterface
): FilterResult;
export type FilterChanged = {
@@ -99,18 +109,14 @@ export function diffFilters(
oldFilterRecord?: FilterRecord | {}
): FilterChanged;
-export type FilterDomain = any;
-
-export function getFieldDomain(allData: KeplerTable['allData'], filed: Field): FieldDomain;
-
-export function dataValueAccessor(data: any[]): number | null;
+export function dataValueAccessor(data: {index: number}): number | null;
export function getTimestampFieldDomain(
- data: KeplerTable['allData'],
+ dataContainer: DataContainerInterface,
valueAccessor: typeof dataValueAccessor
): TimeRangeFieldDomain;
export function getNumericFieldDomain(
- data: KeplerTable['allData'],
+ dataContainer: DataContainerInterface,
valueAccessor: typeof dataValueAccessor
): RangeFieldDomain;
@@ -157,11 +163,14 @@ export function getFilterPlot(
export function getFilterIdInFeature(f: FeatureValue): string;
export function isInRange(v: any, domain: number[]): boolean;
export function updateFilterDataId(dataId: string): FilterBase;
-export function validateFiltersUpdateDatasets(state: VisState, filtersToValidate: ParsedConfig['visState']['filters']): {
- validated: Filter[],
- failed: Filter[],
- updatedDatasets: Datasets
-}
+export function validateFiltersUpdateDatasets(
+ state: VisState,
+ filtersToValidate: ParsedConfig['visState']['filters']
+): {
+ validated: Filter[];
+ failed: Filter[];
+ updatedDatasets: Datasets;
+};
export function isInPolygon(point: number[], polygon: object): boolean;
export function getIntervalBins(filter: TimeRangeFilter);
export function getTimeWidgetHintFormatter(domain: [number, number]): string;
diff --git a/src/utils/filter-utils.js b/src/utils/filter-utils.js
index 2a9714815..f2940dd8d 100644
--- a/src/utils/filter-utils.js
+++ b/src/utils/filter-utils.js
@@ -353,20 +353,20 @@ export function getFilterProps(field, fieldDomain) {
}
}
-export const getPolygonFilterFunctor = (layer, filter) => {
- const getPosition = layer.getPositionAccessor();
+export const getPolygonFilterFunctor = (layer, filter, dataContainer) => {
+ const getPosition = layer.getPositionAccessor(dataContainer);
switch (layer.type) {
case LAYER_TYPES.point:
case LAYER_TYPES.icon:
return data => {
- const pos = getPosition({data});
+ const pos = getPosition(data);
return pos.every(Number.isFinite) && isInPolygon(pos, filter.value);
};
case LAYER_TYPES.arc:
case LAYER_TYPES.line:
return data => {
- const pos = getPosition({data});
+ const pos = getPosition(data);
return (
pos.every(Number.isFinite) &&
[
@@ -377,14 +377,14 @@ export const getPolygonFilterFunctor = (layer, filter) => {
};
case LAYER_TYPES.hexagonId:
if (layer.dataToFeature && layer.dataToFeature.centroids) {
- return (data, index) => {
+ return data => {
// null or getCentroid({id})
- const centroid = layer.dataToFeature.centroids[index];
+ const centroid = layer.dataToFeature.centroids[data.index];
return centroid && isInPolygon(centroid, filter.value);
};
}
return data => {
- const id = getPosition({data});
+ const id = getPosition(data);
if (!h3IsValid(id)) {
return false;
}
@@ -401,10 +401,11 @@ export const getPolygonFilterFunctor = (layer, filter) => {
* @param dataId Dataset id
* @param filter Filter object
* @param layers list of layers to filter upon
+ * @param dataContainer Data container
* @return filterFunction
* @type {typeof import('./filter-utils').getFilterFunction}
*/
-export function getFilterFunction(field, dataId, filter, layers) {
+export function getFilterFunction(field, dataId, filter, layers, dataContainer) {
// field could be null in polygon filter
const valueAccessor = field ? field.valueAccessor : data => null;
const defaultFunc = d => true;
@@ -422,9 +423,9 @@ export function getFilterFunction(field, dataId, filter, layers) {
}
const mappedValue = get(field, ['filterProps', 'mappedValue']);
const accessor = Array.isArray(mappedValue)
- ? (data, index) => mappedValue[index]
+ ? data => mappedValue[data.index]
: data => timeToUnixMilli(valueAccessor(data), field.format);
- return (data, index) => isInRange(accessor(data, index), filter.value);
+ return data => isInRange(accessor(data), filter.value);
case FILTER_TYPES.polygon:
if (!layers || !layers.length) {
return defaultFunc;
@@ -433,9 +434,9 @@ export function getFilterFunction(field, dataId, filter, layers) {
const layerFilterFunctions = filter.layerId
.map(id => layers.find(l => l.id === id))
.filter(l => l && l.config.dataId === dataId)
- .map(layer => getPolygonFilterFunctor(layer, filter));
+ .map(layer => getPolygonFilterFunctor(layer, filter, dataContainer));
- return (data, index) => layerFilterFunctions.every(filterFunc => filterFunc(data, index));
+ return data => layerFilterFunctions.every(filterFunc => filterFunc(data));
default:
return defaultFunc;
}
@@ -448,28 +449,32 @@ export function updateFilterDataId(dataId) {
/**
* @type {typeof import('./filter-utils').filterDataByFilterTypes}
*/
-export function filterDataByFilterTypes({dynamicDomainFilters, cpuFilters, filterFuncs}, allData) {
+export function filterDataByFilterTypes(
+ {dynamicDomainFilters, cpuFilters, filterFuncs},
+ dataContainer
+) {
const result = {
...(dynamicDomainFilters ? {filteredIndexForDomain: []} : {}),
...(cpuFilters ? {filteredIndex: []} : {})
};
- for (let i = 0; i < allData.length; i++) {
- const d = allData[i];
+ const filterContext = {index: -1, dataContainer};
+ const filterFuncCaller = filter => filterFuncs[filter.id](filterContext);
- const matchForDomain =
- dynamicDomainFilters && dynamicDomainFilters.every(filter => filterFuncs[filter.id](d, i));
+ const numRows = dataContainer.numRows();
+ for (let i = 0; i < numRows; ++i) {
+ filterContext.index = i;
+ const matchForDomain = dynamicDomainFilters && dynamicDomainFilters.every(filterFuncCaller);
if (matchForDomain) {
// @ts-ignore
- result.filteredIndexForDomain.push(i);
+ result.filteredIndexForDomain.push(filterContext.index);
}
- const matchForRender = cpuFilters && cpuFilters.every(filter => filterFuncs[filter.id](d, i));
-
+ const matchForRender = cpuFilters && cpuFilters.every(filterFuncCaller);
if (matchForRender) {
// @ts-ignore
- result.filteredIndex.push(i);
+ result.filteredIndex.push(filterContext.index);
}
}
@@ -588,13 +593,13 @@ export function adjustValueToFilterDomain(value, {domain, type}) {
*
* @type {typeof import('./filter-utils').getNumericFieldDomain}
*/
-export function getNumericFieldDomain(data, valueAccessor) {
+export function getNumericFieldDomain(dataContainer, valueAccessor) {
let domain = [0, 1];
let step = 0.1;
- const mappedValue = Array.isArray(data) ? data.map(valueAccessor) : [];
+ const mappedValue = dataContainer.mapIndex(valueAccessor);
- if (Array.isArray(data) && data.length > 1) {
+ if (dataContainer.numRows() > 1) {
domain = ScaleUtils.getLinearDomain(mappedValue);
const diff = domain[1] - domain[0];
@@ -647,14 +652,13 @@ export function getNumericStepSize(diff) {
/**
* Calculate timestamp domain and suitable step
- *
* @type {typeof import('./filter-utils').getTimestampFieldDomain}
*/
-export function getTimestampFieldDomain(data, valueAccessor) {
+export function getTimestampFieldDomain(dataContainer, valueAccessor) {
// to avoid converting string format time to epoch
// every time we compare we store a value mapped to int in filter domain
- const mappedValue = Array.isArray(data) ? data.map(valueAccessor) : [];
+ const mappedValue = dataContainer.mapIndex(valueAccessor);
const domain = ScaleUtils.getLinearDomain(mappedValue);
const defaultTimeFormat = getTimeWidgetTitleFormatter(domain);
@@ -823,11 +827,14 @@ export function getFilterPlot(filter, dataset) {
}
// return lineChart
- const series = dataset.allData
- .map((d, i) => ({
- x: mappedValue[i],
- y: d[fieldIdx]
- }))
+ const series = dataset.dataContainer
+ .map(
+ (row, rowIndex) => ({
+ x: mappedValue[rowIndex],
+ y: row.valueAt(fieldIdx)
+ }),
+ true
+ )
.filter(({x, y}) => Number.isFinite(x) && Number.isFinite(y))
.sort((a, b) => ascending(a.x, b.x));
diff --git a/src/utils/gpu-filter-utils.js b/src/utils/gpu-filter-utils.js
index 5ec06eb5f..70fdc8c21 100644
--- a/src/utils/gpu-filter-utils.js
+++ b/src/utils/gpu-filter-utils.js
@@ -28,7 +28,7 @@ import moment from 'moment';
* @type {typeof import('./gpu-filter-utils').setFilterGpuMode}
*/
export function setFilterGpuMode(filter, filters) {
- // filter can be apply to multiple dataset, hence gpu filter mode should also be
+ // filter can be applied to multiple datasets, hence gpu filter mode should also be
// an array, however, to keep us sane, for now, we only check if there is available channel for every dataId,
// if all of them has, we set gpu mode to true
// TODO: refactor filter so we don't keep an array of everything
@@ -152,17 +152,31 @@ function getEmptyFilterRange() {
return new Array(MAX_GPU_FILTERS).fill(0).map(d => [0, 0]);
}
-// By default filterValueAccessor expect each datum to be formated as {index, data}
-// data is the row in allData, and index is its index in allData
+/**
+ * Returns index of the data element.
+ * @param {any} d Data element with row index info.
+ * @returns number
+ */
const defaultGetIndex = d => d.index;
-const defaultGetData = d => d.data;
/**
- *
+ * Returns value at the specified row from the data container.
+ * @param {import('./table-utils/data-container-interface').DataContainerInterface} dc Data container.
+ * @param {any} d Data element with row index info.
+ * @param {number} fieldIndex Column index in the data container.
+ * @returns
+ */
+const defaultGetData = (dc, d, fieldIndex) => {
+ return dc.valueAt(d.index, fieldIndex);
+};
+
+/**
* @param {Array<Object>} channels
+ * @param {string} dataId
+ * @param {Array<Object>} fields
* @return {Function} getFilterValue
*/
-const getFilterValueAccessor = (channels, dataId, fields) => (
+const getFilterValueAccessor = (channels, dataId, fields) => dc => (
getIndex = defaultGetIndex,
getData = defaultGetData
) => d =>
@@ -178,8 +192,8 @@ const getFilterValueAccessor = (channels, dataId, fields) => (
filter.type === FILTER_TYPES.timeRange
? field.filterProps && Array.isArray(field.filterProps.mappedValue)
? field.filterProps.mappedValue[getIndex(d)]
- : moment.utc(getData(d)[fieldIndex]).valueOf()
- : getData(d)[fieldIndex];
+ : moment.utc(getData(dc, d, fieldIndex)).valueOf()
+ : getData(dc, d, fieldIndex);
return notNullorUndefined(value) ? value - filter.domain[0] : Number.MIN_SAFE_INTEGER;
});
diff --git a/src/utils/index.js b/src/utils/index.js
index dab96ac75..97598feb5 100644
--- a/src/utils/index.js
+++ b/src/utils/index.js
@@ -45,3 +45,4 @@ export {updateAllLayerDomainData} from '../reducers/vis-state-updaters';
export {getHexFields} from '../layers/h3-hexagon-layer/h3-utils';
export {containValidTime} from '../layers/trip-layer/trip-utils';
export {KeplerTable, findPointFieldPairs} from './table-utils/kepler-table';
+export {createDataContainer, createIndexedDataContainer} from './table-utils/data-container-utils';
diff --git a/src/utils/interaction-utils.d.ts b/src/utils/interaction-utils.d.ts
index 9b5399b67..0a25eed89 100644
--- a/src/utils/interaction-utils.d.ts
+++ b/src/utils/interaction-utils.d.ts
@@ -1,4 +1,5 @@
import {InteractionConfig, Field, TooltipField, CompareType} from '../reducers/vis-state-updaters';
+import {DataRow} from './table-utils/data-row';
/**
* Minus sign used in tooltip formatting.
@@ -6,10 +7,11 @@ import {InteractionConfig, Field, TooltipField, CompareType} from '../reducers/v
export const TOOLTIP_MINUS_SIGN: string;
export const BRUSH_CONFIG: {
- range: [number, number]
+ range: [number, number];
};
export function getDefaultInteraction(): InteractionConfig;
+
export function findFieldsToShow(p: {
fields: Field[];
id: string;
@@ -20,14 +22,15 @@ export function findFieldsToShow(p: {
export function getTooltipDisplayDeltaValue(args: {
item: TooltipField;
field: Field;
- data: any[];
+ data: DataRow;
fieldIdx: number;
- primaryData: any[];
+ primaryData: DataRow;
compareType: CompareType;
}): string | null;
+
export function getTooltipDisplayValue(args: {
item: TooltipField;
field: Field;
- data: any[];
- fieldIdx: string;
+ data: DataRow;
+ fieldIdx: number;
}): string;
diff --git a/src/utils/interaction-utils.js b/src/utils/interaction-utils.js
index 891283de9..3732d95ee 100644
--- a/src/utils/interaction-utils.js
+++ b/src/utils/interaction-utils.js
@@ -145,8 +145,8 @@ export function getTooltipDisplayDeltaValue({
// comparison mode only works for numeric field
(field.type === ALL_FIELD_TYPES.integer || field.type === ALL_FIELD_TYPES.real)
) {
- const baseDp = primaryData[fieldIdx];
- const dp = data[fieldIdx];
+ const baseDp = primaryData.valueAt(fieldIdx);
+ const dp = data.valueAt(fieldIdx);
if (isNumber(baseDp) && isNumber(dp)) {
const deltaValue = compareType === COMPARE_TYPES.RELATIVE ? dp / baseDp - 1 : dp - baseDp;
const deltaFormat =
@@ -174,11 +174,12 @@ export function getTooltipDisplayDeltaValue({
* @type {typeof import('./interaction-utils').getTooltipDisplayValue}
*/
export function getTooltipDisplayValue({item, field, data, fieldIdx}) {
- if (!notNullorUndefined(data[fieldIdx])) {
+ const dataValue = data.valueAt(fieldIdx);
+ if (!notNullorUndefined(dataValue)) {
return '';
}
return item.format
- ? getFormatter(item.format, field)(data[fieldIdx])
- : parseFieldValue(data[fieldIdx], field.type);
+ ? getFormatter(item.format, field)(dataValue)
+ : parseFieldValue(dataValue, field.type);
}
diff --git a/src/utils/layer-utils.js b/src/utils/layer-utils.js
index 32a117514..6b9172c3d 100644
--- a/src/utils/layer-utils.js
+++ b/src/utils/layer-utils.js
@@ -47,7 +47,7 @@ export function findDefaultLayer(dataset, layerClasses) {
// go through all layerProps to create layer
return layerProps.map(props => {
const layer = new layerClasses[props.type](props);
- return typeof layer.setInitialLayerConfig === 'function' && Array.isArray(dataset.allData)
+ return typeof layer.setInitialLayerConfig === 'function' && dataset.dataContainer
? layer.setInitialLayerConfig(dataset)
: layer;
});
@@ -95,8 +95,8 @@ export function getLayerHoverProp({
if (!dataId) {
return null;
}
- const {allData, fields} = datasets[dataId];
- const data = layer.getHoverData(object, allData, fields);
+ const {dataContainer, fields} = datasets[dataId];
+ const data = layer.getHoverData(object, dataContainer, fields);
const fieldsToShow = interactionConfig.tooltip.config.fieldsToShow[dataId];
return {
diff --git a/src/utils/table-utils/data-container-interface.d.ts b/src/utils/table-utils/data-container-interface.d.ts
new file mode 100644
index 000000000..76afd09ca
--- /dev/null
+++ b/src/utils/table-utils/data-container-interface.d.ts
@@ -0,0 +1,140 @@
+import {DataRow, SharedRowOptions} from './data-row';
+
+/**
+ * Specifies a range of rows of a data container that should be processed.
+ */
+export type RangeOptions = {
+ start?: number;
+ end?: number;
+};
+export interface DataContainerInterface {
+ /**
+ * Returns the number of rows in the data container.
+ * @returns Number of rows in the data container.
+ */
+ numRows(): number;
+
+ /**
+ * Returns the number of columns in the data container.
+ * @returns Number of columns in the data container.
+ */
+ numColumns(): number;
+
+ /**
+ * Returns the value stored at the specified cell in the data container.
+ * @param rowIndex Row index.
+ * @param columnIndex Column index.
+ * @returns Value at the specified cell.
+ */
+ valueAt(rowIndex: number, columnIndex: number): any;
+
+ /**
+ * Returns the row at the specified index.
+ * @param rowIndex Row index.
+ * @param sharedRow Passed row is filled with contents from the specified index and returned without extra row allocations.
+ * @returns A row object.
+ */
+ row(rowIndex: number, sharedRow?: SharedRowOptions): DataRow;
+
+ /**
+ * Returns the specified row of the data container represented as an array.
+ * @param rowIndex Row index.
+ * @returns The specified row represented as an array.
+ */
+ rowAsArray(rowIndex: number): any[];
+
+ /**
+ * Returns an iterator to sequentially access all rows in the data container.
+ * @param sharedRow Indicates that a temporary row object should be used.
+ * If enabled, the returned row object is shared between calls
+ * and mustn't be stored without cloning.
+ * Passed row is filled with contents of the specified row and returned on each iteration.
+ * @returns An iterator to sequentially access all rows in the data container.
+ */
+ rows(sharedRow?: SharedRowOptions): Generator<DataRow, void, any>;
+
+ /**
+ * Returns an iterator to sequentially access all values in the specified column of the data container.
+ * @param columnIndex Column index.
+ * @returns An iterator to all values in the specified column of the data container.
+ */
+ column(columnIndex: number): Generator<any, void, any>;
+
+ /**
+ * Returns contents of the data container as a two-dimensional array.
+ * @returns Data.
+ */
+ flattenData(): any[][];
+
+ /**
+ * Generates an array of indices where each index represents a row in the data container.
+ * @returns An array of indices.
+ */
+ getPlainIndex(): number[];
+
+ /**
+ * Creates a new array populated with the results of calling the provided callback
+ * on every row in the data container.
+ * @param func Callback that is called for every row of the data container.
+ * The callback is called with the following arguments:
+ * - row: The current row being processed in the data container.
+ * - index: The index of the current row being processed in the data container.
+ * @param sharedRow Truthy value indicates that a shared row object should be used.
+ * Make sure the func callback doesn't store the row object in such case,
+ * and clone the row in case you need to store it.
+ * @param options Specify start and end row indices that should be mapped.
+ * @returns A new array with each element being the result of the func callback.
+ */
+ map(
+ func: (row: DataRow, index: number) => any,
+ sharedRow?: SharedRowOptions,
+ options?: RangeOptions
+ ): any[];
+
+ /**
+ * Creates a new array populated with the results of calling the provided callback.
+ * The callback is called for every row in the dataset, but only {index} object is passed.
+ * @param func Callback that is called for every row of the data container.
+ * @param options Specify start and end row indices that should be mapped.
+ * @returns A new array with each element being the result of the func callback.
+ */
+ mapIndex(
+ func: ({index: number}, dataContainer: DataContainerInterface) => any,
+ options?: RangeOptions
+ ): any[];
+
+ /**
+ * Returns the value of the first row in the provided data container that satisfies the provided testing function.
+ * @param func Function to execute on each value in the array.
+ * The function is called with the following arguments:
+ * - row: The current row being processed in the data container.
+ * - index: The index of the current row being processed in the data container.
+ * @param sharedRow Truthy value indicates that a shared row object should be used.
+ * Make sure the func callback doesn't store the row object in such case,
+ * and clone the row in case you need to store it.
+ * @returns First matching row or undefined if no rows satisfy the testing function.
+ */
+ find(
+ func: (row: DataRow, index: number) => any,
+ sharedRow?: SharedRowOptions
+ ): DataRow | undefined;
+
+ /**
+ * Executes a reducer function on each element of the data container, resulting in single output value.
+ * @param func A function to execute on each row in the data container.
+ * The function is called with the following arguments:
+ * - acc: The accumulator accumulates func's return values.
+ * - row: The current row being processed in the data container.
+ * - index: The index of the current row being processed in the data container.
+ * @param initialValue A value to use as the first argument to the first call of the func.
+ * @param sharedRow Truthy value indicates that a shared row object should be used.
+ * Make sure the func callback doesn't store the row object in such case,
+ * and clone the row in case you need to store it.
+ * @returns The single value that results from the reduction.
+ */
+ reduce(
+ func: (acc: any, row: DataRow, index: number) => any,
+ initialValue: any,
+ sharedRow?: SharedRowOptions
+ ): any;
+}
diff --git a/src/utils/table-utils/data-container-utils.d.ts b/src/utils/table-utils/data-container-utils.d.ts
new file mode 100644
index 000000000..275646956
--- /dev/null
+++ b/src/utils/table-utils/data-container-utils.d.ts
@@ -0,0 +1,43 @@
+import {Field} from './kepler-table';
+import {DataContainerInterface} from './data-container-interface';
+
+type DataForm = {
+ ROWS_ARRAY: string;
+};
+
+export type DataContainerOptions = {
+ inputDataFormat?: string; // one of DataForm
+ fields?: Field[];
+};
+
+/**
+ * Creates a data container wrapper for the data.
+ * @param data Data.
+ * @param options Options.
+ * @returns A data container object which is based on data and options.
+ */
+export function createDataContainer(
+ data: any[],
+ options?: DataContainerOptions
+): DataContainerInterface;
+
+/**
+ * Creates a data container wrapper around another data container.
+ * @param dataContainer Parent data container.
+ * @param indices An array of row indices in the parent data container.
+ */
+export function createIndexedDataContainer(
+ dataContainer: DataContainerInterface,
+ indices: number[]
+): DataContainerInterface;
+
+/**
+ * Get a sample of rows from a data container.
+ * @param dataContainer Data container to get samples from.
+ * @param sampleSize Max number of samples.
+ * @returns A data container which contains samples from the original data container.
+ */
+export function getSampleData(
+ dataContainer: DataContainerInterface,
+ sampleSize?: number
+): DataContainerInterface;
\ No newline at end of file
diff --git a/src/utils/table-utils/data-container-utils.js b/src/utils/table-utils/data-container-utils.js
new file mode 100644
index 000000000..ff3d8d0ec
--- /dev/null
+++ b/src/utils/table-utils/data-container-utils.js
@@ -0,0 +1,61 @@
+// Copyright (c) 2021 Uber Technologies, Inc.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+import {RowDataContainer} from './row-data-container';
+import {IndexedDataContainer} from './indexed-data-container';
+
+/** @type {import('./data-container-utils').DataForm} */
+export const DataForm = {
+ ROWS_ARRAY: 'ROWS_ARRAY'
+};
+
+/** @type {import('./data-container-utils').DataContainerOptions} */
+const defaultOptions = {
+ inputDataFormat: DataForm.ROWS_ARRAY
+};
+
+/** @type {typeof import('./data-container-utils').createDataContainer} */
+export function createDataContainer(data, options = defaultOptions) {
+ options = {...defaultOptions, ...options};
+
+ if (options.inputDataFormat === DataForm.ROWS_ARRAY) {
+ return new RowDataContainer({rows: data, fields: options.fields});
+ }
+
+ throw Error('Failed to create a data container: not implemented format');
+}
+
+/** @type {typeof import('./data-container-utils').createIndexedDataContainer} */
+export function createIndexedDataContainer(dataContainer, indices) {
+ return new IndexedDataContainer(dataContainer, indices);
+}
+
+/** @type {typeof import('./data-container-utils').getSampleData} */
+export function getSampleData(dataContainer, sampleSize = 500) {
+ const numberOfRows = dataContainer.numRows();
+ const sampleStep = Math.max(Math.floor(numberOfRows / sampleSize), 1);
+
+ const indices = [];
+ for (let i = 0; i < numberOfRows; i += sampleStep) {
+ indices.push(i);
+ }
+
+ return createIndexedDataContainer(dataContainer, indices);
+}
diff --git a/src/utils/table-utils/data-row.d.ts b/src/utils/table-utils/data-row.d.ts
new file mode 100644
index 000000000..878336e62
--- /dev/null
+++ b/src/utils/table-utils/data-row.d.ts
@@ -0,0 +1,65 @@
+import {DataContainerInterface} from './data-container-interface';
+
+/**
+ * Setting for shared row optimization.
+ * - False/undefined indicates that unique row objects should be used (default).
+ * - True indicates that a single temporary row object should be created and used without extra allocations.
+ * - A DataRow object indicates that the row should be used as a temporary shared row.
+ * When used, the content of the shared row isn't preserved between calls.
+ */
+export type SharedRowOptions = DataRow | boolean | undefined;
+
+/**
+ * Return type for createSharedRow:
+ * - DataRow object that should be used as shared row.
+ * - Falsy values indicate that shared row object shouldn't be used.
+ */
+export type SharedRowOptionsResult = DataRow | false | undefined;
+
+export class DataRow {
+ /**
+ * Creates new DataRow.
+ * @param dataContainer Data container where data is stored. Can be initialized with null for shared rows.
+ * @param rowIndex Index of a row in the data container.
+ */
+ constructor(dataContainer: DataContainerInterface | null, rowIndex: number);
+
+ /**
+ * Conditionally creates a DataRow object.
+ * @param sharedRowDesc Accepts forllowing options:
+ * - true indicates that new DataRow should be created.
+ * - falsy value or a DataRow object is passed through without any change.
+ * @returns A new DataRow object or unchanged input argument.
+ */
+ static createSharedRow(sharedRowDesc: SharedRowOptions): SharedRowOptionsResult;
+
+ /**
+ * Returns the value stored at the specified index in the row.
+ * @param index Index of the requested field in the row.
+ * @returns Value at the index.
+ */
+ valueAt(index: number): any;
+
+ /**
+ * Returns the row represented as an array.
+ * @returns The row represented as an array.
+ */
+ values(): any[];
+
+ /**
+ * Setup a row object. The method is used by shared rows to prevent excessive allocations.
+ * @param dataContainer Data container.
+ * @param rowIndex Index of a row in the data container.
+ */
+ setSource(dataContainer: DataContainerInterface, rowIndex: number): void;
+
+ /**
+ * Creates a new array populated with the results of calling the provided function
+ * on every element of the row.
+ * @param func The callback is called with the following arguments:
+ * - elem: The current element being processed in the row.
+ * - index: The index of the current element being processed in the row.
+ * @returns A new array with each element being the result of the func callback.
+ */
+ map(func: (elem: any, index: number) => any): any[];
+}
diff --git a/src/utils/table-utils/data-row.js b/src/utils/table-utils/data-row.js
new file mode 100644
index 000000000..b419dbbdf
--- /dev/null
+++ b/src/utils/table-utils/data-row.js
@@ -0,0 +1,54 @@
+// Copyright (c) 2021 Uber Technologies, Inc.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+export class DataRow {
+ constructor(dataContainer, rowIndex) {
+ this.setSource(dataContainer, rowIndex);
+ }
+
+ static createSharedRow(sharedRowDesc) {
+ if (sharedRowDesc === true) {
+ return new DataRow(null, 0);
+ }
+ return sharedRowDesc;
+ }
+
+ valueAt(columnIndex) {
+ return this._dataContainer.valueAt(this._rowIndex, columnIndex);
+ }
+
+ values() {
+ return this._dataContainer.rowAsArray(this._rowIndex);
+ }
+
+ setSource(dataContainer, rowIndex) {
+ this._dataContainer = dataContainer;
+ this._rowIndex = rowIndex;
+ }
+
+ map(handler) {
+ const numColumns = this._dataContainer.numColumns();
+ const out = [];
+ for (let column = 0; column < numColumns; ++column) {
+ out[column] = handler(this.valueAt(column), column);
+ }
+ return out;
+ }
+}
diff --git a/src/utils/table-utils/index.d.ts b/src/utils/table-utils/index.d.ts
new file mode 100644
index 000000000..004bb10e7
--- /dev/null
+++ b/src/utils/table-utils/index.d.ts
@@ -0,0 +1 @@
+export {createDataContainer, createIndexedDataContainer} from './data-container-utils';
diff --git a/src/utils/table-utils/index.js b/src/utils/table-utils/index.js
new file mode 100644
index 000000000..ad80f870c
--- /dev/null
+++ b/src/utils/table-utils/index.js
@@ -0,0 +1,21 @@
+// Copyright (c) 2021 Uber Technologies, Inc.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+export {createDataContainer, createIndexedDataContainer} from './data-container-utils';
diff --git a/src/utils/table-utils/indexed-data-container.d.ts b/src/utils/table-utils/indexed-data-container.d.ts
new file mode 100644
index 000000000..3536fe6c9
--- /dev/null
+++ b/src/utils/table-utils/indexed-data-container.d.ts
@@ -0,0 +1,26 @@
+import {DataContainerInterface} from './data-container-interface';
+import {DataRow, SharedRowOptions} from './data-row';
+
+/**
+ * A data container wrapper around another data container.
+ * You have to pass an array of indices to reference rows in the parent data container.
+ * For example indices [3, 4, 6, 8] means that IndexedDataContainer is going to have
+ * 4 rows and row(2) points to 6th row in the referenced data container.
+ */
+export class IndexedDataContainer implements DataContainerInterface {
+ constructor(parentDataContainer: DataContainerInterface, indices: number[]);
+
+ numRows(): number;
+ numColumns(): number;
+ valueAt(rowIndex: number, columnIndex: number): any;
+ row(rowIndex: number, sharedRow?: SharedRowOptions): DataRow;
+ rowAsArray(rowIndex: number): any[];
+ rows(sharedRow?: SharedRowOptions): Generator<DataRow, void, any>;
+ column(columnIndex: number): Generator<any, void, any>;
+ flattenData(): any[][];
+ getPlainIndex(): number[];
+ map(func: (row: DataRow, index: number) => any, sharedRow?: SharedRowOptions, options?: RangeOptions): any[];
+ mapIndex(func: ({index: number}, dc: DataContainerInterface) => any, options?: RangeOptions): any[];
+ find(func: (row: DataRow, index: number) => any, sharedRow?: SharedRowOptions): DataRow | undefined;
+ reduce(func: (acc: any, row: DataRow, index: number) => any, initialValue: any, sharedRow?: SharedRowOptions): any;
+}
diff --git a/src/utils/table-utils/indexed-data-container.js b/src/utils/table-utils/indexed-data-container.js
new file mode 100644
index 000000000..14fef5c6c
--- /dev/null
+++ b/src/utils/table-utils/indexed-data-container.js
@@ -0,0 +1,152 @@
+// Copyright (c) 2021 Uber Technologies, Inc.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+import {DataRow} from './data-row';
+
+/**
+ * @param {import('./data-container-interface').DataContainerInterface} dataContainer
+ * @param {number[]} indices
+ * @param {import('./data-row').SharedRowOptions} sharedRow
+ * @returns {Generator<DataRow, void, unknown>}
+ */
+function* rowsIterator(dataContainer, indices, sharedRow) {
+ const numRows = indices.length;
+ for (let rowIndex = 0; rowIndex < numRows; ++rowIndex) {
+ const mappedRowIndex = indices[rowIndex];
+ yield dataContainer.row(mappedRowIndex, sharedRow);
+ }
+}
+
+/**
+ * @param {import('./data-container-interface').DataContainerInterface} dataContainer
+ * @param {number[]} indices
+ * @param {number} columnIndex
+ * @returns {Generator<any, void, unknown>}
+ */
+function* columnIterator(dataContainer, indices, columnIndex) {
+ const numRows = indices.length;
+ for (let rowIndex = 0; rowIndex < numRows; ++rowIndex) {
+ const mappedRowIndex = indices[rowIndex];
+ yield dataContainer.valueAt(mappedRowIndex, columnIndex);
+ }
+}
+
+export class IndexedDataContainer {
+ constructor(parentDataContainer, indices) {
+ this._parentDataContainer = parentDataContainer;
+ this._indices = indices;
+ }
+
+ numRows() {
+ return this._indices.length;
+ }
+
+ numColumns() {
+ return this._parentDataContainer.numColumns();
+ }
+
+ /**
+ * Remaps a local index to an index in the parent dataset
+ * @param {number} rowIndex
+ * @returns number
+ */
+ _mappedRowIndex(rowIndex) {
+ return this._indices[rowIndex];
+ }
+
+ valueAt(rowIndex, columnIndex) {
+ return this._parentDataContainer.valueAt(this._mappedRowIndex(rowIndex), columnIndex);
+ }
+
+ row(rowIndex, sharedRow) {
+ return this._parentDataContainer.row(this._mappedRowIndex(rowIndex), sharedRow);
+ }
+
+ rowAsArray(rowIndex) {
+ return this._parentDataContainer.rowAsArray(this._mappedRowIndex(rowIndex));
+ }
+
+ rows(sharedRow) {
+ return rowsIterator(this._parentDataContainer, this._indices, sharedRow);
+ }
+
+ column(columnIndex) {
+ return columnIterator(this._parentDataContainer, this._indices, columnIndex);
+ }
+
+ getPlainIndex() {
+ return this._indices.map((_, i) => i);
+ }
+
+ flattenData() {
+ const tSharedRow = DataRow.createSharedRow(true);
+
+ return this._indices.map((_, i) => {
+ return this.row(i, tSharedRow).values();
+ }, this);
+ }
+
+ map(func, sharedRow, options = {}) {
+ const {start = 0, end = this.numRows()} = options;
+ const endRow = Math.min(this.numRows(), end);
+
+ const tSharedRow = DataRow.createSharedRow(sharedRow);
+
+ const out = [];
+ for (let rowIndex = start; rowIndex < endRow; ++rowIndex) {
+ const row = this.row(rowIndex, tSharedRow);
+ out.push(func(row, rowIndex));
+ }
+ return out;
+ }
+
+ mapIndex(func, options = {}) {
+ const {start = 0, end = this.numRows()} = options;
+ const endRow = Math.min(this.numRows(), end);
+
+ const out = [];
+ for (let rowIndex = start; rowIndex < endRow; ++rowIndex) {
+ out.push(func({index: this._mappedRowIndex(rowIndex)}, this._parentDataContainer));
+ }
+ return out;
+ }
+
+ find(func, sharedRow) {
+ const tSharedRow = DataRow.createSharedRow(sharedRow);
+
+ for (let rowIndex = 0; rowIndex < this.numRows(); ++rowIndex) {
+ const row = this.row(rowIndex, tSharedRow);
+ if (func(row, rowIndex)) {
+ return row;
+ }
+ }
+ return undefined;
+ }
+
+ reduce(func, initialValue, sharedRow) {
+ const tSharedRow = DataRow.createSharedRow(sharedRow);
+
+ for (let rowIndex = 0; rowIndex < this._indices.length; ++rowIndex) {
+ const row = this.row(rowIndex, tSharedRow);
+ initialValue = func(initialValue, row, rowIndex);
+ }
+ return initialValue;
+ }
+}
diff --git a/src/utils/table-utils/kepler-table.d.ts b/src/utils/table-utils/kepler-table.d.ts
index 32561a978..60806df07 100644
--- a/src/utils/table-utils/kepler-table.d.ts
+++ b/src/utils/table-utils/kepler-table.d.ts
@@ -1,7 +1,8 @@
import {RGBColor} from '../../reducers/types';
import {Layer} from 'layers';
import {Filter} from '../reducers/vis-state-updaters';
-import {Dataset, Feild} from '../../reducers/vis-state-updaters';
+import {Dataset} from '../../reducers/vis-state-updaters';
+import {DataContainerInterface} from './data-container-interface';
export type Field = {
analyzerType: string;
@@ -11,7 +12,7 @@ export type Field = {
format: string;
type: string;
fieldIdx: number;
- valueAccessor(v: any[]): any;
+ valueAccessor(v: {index: number}): any;
filterProps?: any;
metadata?: any;
displayName: string;
@@ -20,7 +21,18 @@ export type Field = {
export type GpuFilter = {
filterRange: number[][];
filterValueUpdateTriggers: any;
- filterValueAccessor: any;
+ filterValueAccessor: (
+ dc: DataContainerInterface
+ ) => (
+ getIndex?: (any) => number,
+ getData?: (
+ dc: DataContainerInterface,
+ d: any,
+ fieldIndex: number
+ ) => any
+ ) => (
+ d: any
+ ) => number;
};
export type FieldPair = {
@@ -50,7 +62,7 @@ export type FilterDatasetOpt = {
export function sortDatasetByColumn(dataset: Dataset, column: string, mode?: string): Dataset;
-export function findPointFieldPairs(fields: Feild[]): FieldPair[];
+export function findPointFieldPairs(fields: Field[]): FieldPair[];
export class KeplerTable {
constructor(schema: {info?: object; data: any; color: RGBColor; metadata: any});
@@ -60,7 +72,8 @@ export class KeplerTable {
// fields and data
fields: Field[];
- allData: any[][];
+
+ dataContainer: DataContainerInterface;
allIndexes: number[];
filteredIndex: number[];
diff --git a/src/utils/table-utils/kepler-table.js b/src/utils/table-utils/kepler-table.js
index 7172b8211..1c1869e5a 100644
--- a/src/utils/table-utils/kepler-table.js
+++ b/src/utils/table-utils/kepler-table.js
@@ -44,6 +44,8 @@ import {
import {ALL_FIELD_TYPES, SCALE_TYPES} from 'constants/default-settings';
+import {createDataContainer} from './data-container-utils';
+
// Unique identifier of each field
const FID_KEY = 'name';
@@ -60,7 +62,8 @@ class KeplerTable {
// return this;
// }
- const allData = data.rows;
+ const dataContainer = createDataContainer(data.rows, {fields: data.fields});
+
const datasetInfo = {
id: generateHashId(4),
label: 'new dataset',
@@ -78,11 +81,12 @@ class KeplerTable {
// is time
f.type === ALL_FIELD_TYPES.timestamp,
i,
- f.format
+ f.format,
+ dataContainer
)
}));
- const allIndexes = allData.map((_, i) => i);
+ const allIndexes = dataContainer.getPlainIndex();
this.id = datasetInfo.id;
this.label = datasetInfo.label;
@@ -92,7 +96,8 @@ class KeplerTable {
id: datasetInfo.id,
label: datasetInfo.label
};
- this.allData = allData;
+
+ this.dataContainer = dataContainer;
this.allIndexes = allIndexes;
this.filteredIndex = allIndexes;
this.filteredIndexForDomain = allIndexes;
@@ -126,7 +131,7 @@ class KeplerTable {
*/
getValue(columnName, rowIdx) {
const field = this.getColumnField(columnName);
- return field ? field.valueAccessor(this.allData[rowIdx]) : null;
+ return field ? field.valueAccessor({index: rowIdx}) : null;
}
/**
@@ -169,14 +174,13 @@ class KeplerTable {
}
/**
- *
* Apply filters to dataset, return the filtered dataset with updated `gpuFilter`, `filterRecord`, `filteredIndex`, `filteredIndexForDomain`
* @param filters
* @param layers
* @param opt
*/
filterTable(filters, layers, opt) {
- const {allData, id: dataId, filterRecord: oldFilterRecord, fields} = this;
+ const {dataContainer, id: dataId, filterRecord: oldFilterRecord, fields} = this;
// if there is no filters
const filterRecord = getFilterRecord(dataId, filters, opt || {});
@@ -211,13 +215,13 @@ class KeplerTable {
return {
...acc,
- [filter.id]: getFilterFunction(field, this.id, filter, layers)
+ [filter.id]: getFilterFunction(field, this.id, filter, layers, dataContainer)
};
}, {});
filterResult = filterDataByFilterTypes(
{dynamicDomainFilters, cpuFilters, filterFuncs},
- allData
+ dataContainer
);
}
@@ -272,7 +276,7 @@ class KeplerTable {
* for Filter
*/
getColumnFilterDomain(field) {
- const {allData} = this;
+ const {dataContainer} = this;
const {valueAccessor} = field;
let domain;
@@ -281,21 +285,21 @@ class KeplerTable {
case ALL_FIELD_TYPES.real:
case ALL_FIELD_TYPES.integer:
// calculate domain and step
- return getNumericFieldDomain(allData, valueAccessor);
+ return getNumericFieldDomain(dataContainer, valueAccessor);
case ALL_FIELD_TYPES.boolean:
return {domain: [true, false]};
case ALL_FIELD_TYPES.string:
case ALL_FIELD_TYPES.date:
- domain = getOrdinalDomain(allData, valueAccessor);
+ domain = getOrdinalDomain(dataContainer, valueAccessor);
return {domain};
case ALL_FIELD_TYPES.timestamp:
- return getTimestampFieldDomain(allData, valueAccessor);
+ return getTimestampFieldDomain(dataContainer, valueAccessor);
default:
- return {domain: getOrdinalDomain(allData, valueAccessor)};
+ return {domain: getOrdinalDomain(dataContainer, valueAccessor)};
}
}
@@ -303,7 +307,7 @@ class KeplerTable {
* Get the domain of this column based on scale type
*/
getColumnLayerDomain(field, scaleType) {
- const {allData, filteredIndexForDomain} = this;
+ const {dataContainer, filteredIndexForDomain} = this;
if (!SCALE_TYPES[scaleType]) {
Console.error(`scale type ${scaleType} not supported`);
@@ -311,7 +315,7 @@ class KeplerTable {
}
const {valueAccessor} = field;
- const indexValueAccessor = i => valueAccessor(allData[i]);
+ const indexValueAccessor = i => valueAccessor({index: i});
const sortFunction = getSortingFunction(field.type);
switch (scaleType) {
@@ -319,7 +323,7 @@ class KeplerTable {
case SCALE_TYPES.point:
// do not recalculate ordinal domain based on filtered data
// don't need to update ordinal domain every time
- return getOrdinalDomain(allData, valueAccessor);
+ return getOrdinalDomain(dataContainer, valueAccessor);
case SCALE_TYPES.quantile:
return getQuantileDomain(filteredIndexForDomain, indexValueAccessor, sortFunction);
@@ -380,6 +384,7 @@ export function findPointFieldPairs(fields) {
const allNames = fields.map(f => f.name.toLowerCase());
// get list of all fields with matching suffixes
+ const acc = [];
return allNames.reduce((carry, fieldName, idx) => {
// This search for pairs will early exit if found.
for (const suffixPair of TRIP_POINT_FIELDS) {
@@ -412,7 +417,7 @@ export function findPointFieldPairs(fields) {
}
}
return carry;
- }, []);
+ }, acc);
}
/**
@@ -423,7 +428,7 @@ export function findPointFieldPairs(fields) {
* @type {typeof import('./kepler-table').sortDatasetByColumn}
*/
export function sortDatasetByColumn(dataset, column, mode) {
- const {allIndexes, fields, allData} = dataset;
+ const {allIndexes, fields, dataContainer} = dataset;
const fieldIndex = fields.findIndex(f => f.name === column);
if (fieldIndex < 0) {
return dataset;
@@ -442,7 +447,9 @@ export function sortDatasetByColumn(dataset, column, mode) {
const sortFunction = sortBy === SORT_ORDER.ASCENDING ? ascending : descending;
const sortOrder = allIndexes
.slice()
- .sort((a, b) => sortFunction(allData[a][fieldIndex], allData[b][fieldIndex]));
+ .sort((a, b) =>
+ sortFunction(dataContainer.valueAt(a, fieldIndex), dataContainer.valueAt(b, fieldIndex))
+ );
return {
...dataset,
diff --git a/src/utils/table-utils/row-data-container.d.ts b/src/utils/table-utils/row-data-container.d.ts
new file mode 100644
index 000000000..d5eacf44c
--- /dev/null
+++ b/src/utils/table-utils/row-data-container.d.ts
@@ -0,0 +1,30 @@
+import {ProcessorResult} from 'processors/data-processor';
+import {Field} from './kepler-table';
+import {DataContainerInterface, RangeOptions} from './data-container-interface';
+import {DataRow, SharedRowOptions} from './data-row';
+
+type RowDataContainerInput = {
+ rows: any[][],
+ fields?: Field[]
+}
+
+/**
+ * A data container where all data is stored internally as a 2D array.
+ */
+export class RowDataContainer implements DataContainerInterface {
+ constructor(data: RowDataContainerInput);
+
+ numRows(): number;
+ numColumns(): number;
+ valueAt(rowIndex: number, columnIndex: number): any;
+ row(rowIndex: number, sharedRow?: SharedRowOptions): DataRow;
+ rowAsArray(rowIndex: number): any[];
+ rows(sharedRow?: SharedRowOptions): Generator<DataRow, void, any>;
+ column(columnIndex: number): Generator<any, void, any>;
+ flattenData(): any[][];
+ getPlainIndex(): number[];
+ map(func: (row: DataRow, index: number) => any, sharedRow?: SharedRowOptions, options?: RangeOptions): any[];
+ mapIndex(func: ({index: number}, dc: DataContainerInterface) => any, options?: RangeOptions): any[];
+ find(func: (row: DataRow, index: number) => any, sharedRow?: SharedRowOptions): DataRow | undefined;
+ reduce(func: (acc: any, row: DataRow, index: number) => any, initialValue: any, sharedRow?: SharedRowOptions): any;
+}
diff --git a/src/utils/table-utils/row-data-container.js b/src/utils/table-utils/row-data-container.js
new file mode 100644
index 000000000..e9013c224
--- /dev/null
+++ b/src/utils/table-utils/row-data-container.js
@@ -0,0 +1,151 @@
+// Copyright (c) 2021 Uber Technologies, Inc.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+import {DataRow} from './data-row';
+
+/**
+ * @param {import('./data-container-interface').DataContainerInterface} dataContainer
+ * @param {import('./data-row').SharedRowOptions} sharedRow
+ */
+function* rowsIterator(dataContainer, sharedRow) {
+ const numRows = dataContainer.numRows();
+ for (let rowIndex = 0; rowIndex < numRows; ++rowIndex) {
+ yield dataContainer.row(rowIndex, sharedRow);
+ }
+}
+
+/**
+ * @param {import('./data-container-interface').DataContainerInterface} dataContainer
+ * @param {number} columnIndex
+ */
+function* columnIterator(dataContainer, columnIndex) {
+ const numRows = dataContainer.numRows();
+ for (let rowIndex = 0; rowIndex < numRows; ++rowIndex) {
+ yield dataContainer.valueAt(rowIndex, columnIndex);
+ }
+}
+
+export class RowDataContainer {
+ constructor(data) {
+ if (!data.rows) {
+ throw Error('RowDataContainer: no rows provided');
+ }
+
+ if (!Array.isArray(data.rows)) {
+ throw Error("RowDataContainer: rows object isn't an array");
+ }
+
+ this._rows = data.rows;
+ this._numColumns = data.rows[0]?.length || 0;
+ }
+
+ numRows() {
+ return this._rows.length;
+ }
+
+ numColumns() {
+ return this._numColumns;
+ }
+
+ valueAt(rowIndex, columnIndex) {
+ if (this._rows[rowIndex] === null) {
+ return null;
+ }
+ return this._rows[rowIndex][columnIndex];
+ }
+
+ row(rowIndex, sharedRow) {
+ const tSharedRow = DataRow.createSharedRow(sharedRow);
+ if (tSharedRow) {
+ tSharedRow.setSource(this, rowIndex);
+ return tSharedRow;
+ }
+
+ return new DataRow(this, rowIndex);
+ }
+
+ rowAsArray(rowIndex) {
+ return this._rows[rowIndex];
+ }
+
+ rows(sharedRow) {
+ const tSharedRow = DataRow.createSharedRow(sharedRow);
+ return rowsIterator(this, tSharedRow);
+ }
+
+ column(columnIndex) {
+ return columnIterator(this, columnIndex);
+ }
+
+ flattenData() {
+ return this._rows;
+ }
+
+ getPlainIndex(valid) {
+ return this._rows.map((_, i) => i);
+ }
+
+ map(func, sharedRow, options = {}) {
+ const tSharedRow = DataRow.createSharedRow(sharedRow);
+
+ const {start = 0, end = this.numRows()} = options;
+ const endRow = Math.min(this.numRows(), end);
+
+ const out = [];
+ for (let rowIndex = start; rowIndex < endRow; ++rowIndex) {
+ const row = this.row(rowIndex, tSharedRow);
+ out.push(func(row, rowIndex));
+ }
+ return out;
+ }
+
+ mapIndex(func, options = {}) {
+ const {start = 0, end = this.numRows()} = options;
+ const endRow = Math.min(this.numRows(), end);
+
+ const out = [];
+ for (let rowIndex = start; rowIndex < endRow; ++rowIndex) {
+ out.push(func({index: rowIndex}, this));
+ }
+ return out;
+ }
+
+ find(func, sharedRow) {
+ const tSharedRow = DataRow.createSharedRow(sharedRow);
+
+ for (let rowIndex = 0; rowIndex < this._rows.length; ++rowIndex) {
+ const row = this.row(rowIndex, tSharedRow);
+ if (func(row, rowIndex)) {
+ return row;
+ }
+ }
+ return undefined;
+ }
+
+ reduce(func, initialValue, sharedRow) {
+ const tSharedRow = DataRow.createSharedRow(sharedRow);
+
+ for (let rowIndex = 0; rowIndex < this._rows.length; ++rowIndex) {
+ const row = this.row(rowIndex, tSharedRow);
+ initialValue = func(initialValue, row, rowIndex);
+ }
+ return initialValue;
+ }
+}
diff --git a/test/browser/components/modals/data-table-modal-test.js b/test/browser/components/modals/data-table-modal-test.js
index bda06a4cf..7238d4980 100644
--- a/test/browser/components/modals/data-table-modal-test.js
+++ b/test/browser/components/modals/data-table-modal-test.js
@@ -41,6 +41,8 @@ import {geoStyleFields, geoStyleRows} from 'test/fixtures/geojson';
import {StateWFiles, testCsvDataId, testGeoJsonDataId} from 'test/helpers/mock-state';
import {appInjector} from '../../../../src/components/container';
+import {createDataContainer} from 'utils/table-utils';
+
const DataTableModal = appInjector.get(DataTableModalFactory);
const DataTable = appInjector.get(DataTableFactory);
const FieldToken = appInjector.get(FieldTokenFactory);
@@ -174,7 +176,14 @@ test('Components -> DataTableModal.render: csv 1', t => {
t.deepEqual(props.columns, expectedColumns, 'DataTable should have the correct props.columns');
t.deepEqual(props.colMeta, expectedColMeta, 'DataTable should have the correct props.colMeta');
- t.equal(props.rows, testAllData, 'DataTable should have the correct props.rows');
+
+ const datasetId = Object.keys(StateWFiles.visState.datasets)[0];
+
+ t.equal(
+ props.dataContainer,
+ StateWFiles.visState.datasets[datasetId].dataContainer,
+ 'DataTable should have the correct props.dataContainer'
+ );
// we can't test it without mocking the canvas response
t.deepEqual(
Object.keys(props.cellSizeCache),
@@ -505,17 +514,20 @@ test('Components -> DatableModal -> sort/pin and copy should be called with the
test('Components -> cellSize -> renderedSize', t => {
prepareMockCanvas();
+ const fields = [
+ {name: testColumns[0], type: 'geojson'},
+ {name: testColumns[1], type: 'real'},
+ {name: testColumns[2], type: 'string'}
+ ];
+ const dataContainer = createDataContainer(texts, {fields});
+
const wrapper = mountWithTheme(
<DataTableModal
datasets={{
smoothie: {
id: 'smoothie',
- allData: texts,
- fields: [
- {name: testColumns[0], type: 'geojson'},
- {name: testColumns[1], type: 'real'},
- {name: testColumns[2], type: 'string'}
- ],
+ dataContainer,
+ fields,
color: [113, 113, 113]
}
}}
@@ -545,12 +557,14 @@ test('Components -> cellSize -> renderedSize', t => {
});
test('Components -> DataTableModal.render: csv 2', t => {
+ const dataContainer = createDataContainer(geoStyleRows, {fields: geoStyleFields});
+
const wrapper = mountWithTheme(
<DataTableModal
datasets={{
smoothie: {
id: 'smoothie',
- allData: geoStyleRows,
+ dataContainer,
fields: geoStyleFields,
color: [113, 113, 113],
data: geoStyleRows
diff --git a/test/browser/layer-tests/arc-layer-specs.js b/test/browser/layer-tests/arc-layer-specs.js
index 5229cfe64..4be9e56ce 100644
--- a/test/browser/layer-tests/arc-layer-specs.js
+++ b/test/browser/layer-tests/arc-layer-specs.js
@@ -95,13 +95,11 @@ test('#ArcLayer -> formatLayerData', t => {
const expectedLayerData = {
data: [
{
- data: testRows[0],
index: 0,
sourcePosition: [testRows[0][2], testRows[0][1], 0],
targetPosition: [testRows[0][4], testRows[0][3], 0]
},
{
- data: testRows[4],
index: 4,
sourcePosition: [testRows[4][2], testRows[4][1], 0],
targetPosition: [testRows[4][4], testRows[4][3], 0]
@@ -235,13 +233,11 @@ test('#ArcLayer -> formatLayerData', t => {
const expectedLayerData = {
data: [
{
- data: testRows[0],
index: 0,
sourcePosition: [testRows[0][2], testRows[0][1], 0],
targetPosition: [testRows[0][4], testRows[0][3], 0]
},
{
- data: testRows[4],
index: 4,
sourcePosition: [testRows[4][2], testRows[4][1], 0],
targetPosition: [testRows[4][4], testRows[4][3], 0]
diff --git a/test/browser/layer-tests/cluster-layer-specs.js b/test/browser/layer-tests/cluster-layer-specs.js
index 4b975364a..38004b1b5 100644
--- a/test/browser/layer-tests/cluster-layer-specs.js
+++ b/test/browser/layer-tests/cluster-layer-specs.js
@@ -91,7 +91,6 @@ test('#ClusterLayer -> formatLayerData', t => {
const {layerData, layer} = result;
const expectedLayerData = {
data: [0, 1, 4, 5, 7].map(index => ({
- data: testRows[index],
index
})),
_filterData: () => {},
@@ -171,7 +170,6 @@ test('#ClusterLayer -> formatLayerData', t => {
const {layerData} = result;
const expectedLayerData = {
data: [0, 1, 4, 5, 7].map(index => ({
- data: testRows[index],
index
})),
_filterData: () => {},
@@ -285,8 +283,7 @@ test('#ClusterLayer -> renderLayer', t => {
{
points: [
{
- index: 4,
- data: preparedDataset.allData[4]
+ index: 4
}
],
position: [-122.136795, 37.456535],
@@ -296,8 +293,7 @@ test('#ClusterLayer -> renderLayer', t => {
{
points: [
{
- index: 5,
- data: preparedDataset.allData[5]
+ index: 5
}
],
position: [-122.10239, 37.40066],
@@ -307,8 +303,7 @@ test('#ClusterLayer -> renderLayer', t => {
{
points: [
{
- index: 7,
- data: preparedDataset.allData[7]
+ index: 7
}
],
position: [-122.26108, 37.879066],
diff --git a/test/browser/layer-tests/grid-layer-specs.js b/test/browser/layer-tests/grid-layer-specs.js
index cde030b0d..caa2b9b45 100644
--- a/test/browser/layer-tests/grid-layer-specs.js
+++ b/test/browser/layer-tests/grid-layer-specs.js
@@ -90,7 +90,6 @@ test('#GridLayer -> formatLayerData', t => {
const {layerData, layer} = result;
const expectedLayerData = {
data: [0, 1, 4, 5, 7].map(index => ({
- data: testRows[index],
index
})),
_filterData: () => {},
@@ -170,7 +169,6 @@ test('#GridLayer -> formatLayerData', t => {
const {layerData} = result;
const expectedLayerData = {
data: [0, 1, 4, 5, 7].map(index => ({
- data: testRows[index],
index
})),
_filterData: () => {},
@@ -291,12 +289,10 @@ test('#GridLayer -> renderLayer', t => {
count: 2,
points: [
{
- index: 0,
- data: preparedDataset.allData[0]
+ index: 0
},
{
- index: 1,
- data: preparedDataset.allData[1]
+ index: 1
}
],
lonIdx: 253,
@@ -309,24 +305,20 @@ test('#GridLayer -> renderLayer', t => {
count: 2,
points: [
{
- index: 4,
- data: preparedDataset.allData[4]
+ index: 4
},
{
- index: 5,
- data: preparedDataset.allData[5]
+ index: 5
}
],
lonIdx: 255,
latIdx: 709,
filteredPoints: [
{
- index: 4,
- data: preparedDataset.allData[4]
+ index: 4
},
{
- index: 5,
- data: preparedDataset.allData[5]
+ index: 5
}
]
},
@@ -336,16 +328,14 @@ test('#GridLayer -> renderLayer', t => {
count: 1,
points: [
{
- index: 7,
- data: preparedDataset.allData[7]
+ index: 7
}
],
lonIdx: 254,
latIdx: 711,
filteredPoints: [
{
- index: 7,
- data: preparedDataset.allData[7]
+ index: 7
}
]
}
diff --git a/test/browser/layer-tests/h3-hexagon-layer-specs.js b/test/browser/layer-tests/h3-hexagon-layer-specs.js
index 99f7d5a1f..83773af21 100644
--- a/test/browser/layer-tests/h3-hexagon-layer-specs.js
+++ b/test/browser/layer-tests/h3-hexagon-layer-specs.js
@@ -90,13 +90,11 @@ test('#H3Layer -> formatLayerData', t => {
const expectedLayerData = {
data: [
{
- data: testRows[0],
index: 0,
id: '89283082c2fffff',
centroid: getCentroid({id: '89283082c2fffff'})
},
{
- data: testRows[4],
index: 4,
id: '89283082c3bffff',
centroid: getCentroid({id: '89283082c3bffff'})
diff --git a/test/browser/layer-tests/heatmap-layer-specs.js b/test/browser/layer-tests/heatmap-layer-specs.js
index efed6eda7..37fee6043 100644
--- a/test/browser/layer-tests/heatmap-layer-specs.js
+++ b/test/browser/layer-tests/heatmap-layer-specs.js
@@ -272,7 +272,7 @@ test('#Heatmaplayer -> formatLayerData -> w/o GpuFilter', t => {
// test data
t.equal(
layerData.data.features.length,
- testData.allData.length,
+ testData.dataContainer.numRows(),
'should have same number of features'
);
diff --git a/test/browser/layer-tests/hexagon-layer-specs.js b/test/browser/layer-tests/hexagon-layer-specs.js
index 0f4dd1264..aead66dc7 100644
--- a/test/browser/layer-tests/hexagon-layer-specs.js
+++ b/test/browser/layer-tests/hexagon-layer-specs.js
@@ -88,7 +88,6 @@ test('#HexagonLayer -> formatLayerData', t => {
const {layerData, layer} = result;
const expectedLayerData = {
data: [0, 1, 4, 5, 7].map(index => ({
- data: testRows[index],
index
})),
_filterData: () => {},
@@ -172,7 +171,6 @@ test('#HexagonLayer -> formatLayerData', t => {
const {layerData} = result;
const expectedLayerData = {
data: [0, 1, 4, 5, 7].map(index => ({
- data: testRows[index],
index
})),
_filterData: () => {},
@@ -226,7 +224,6 @@ test('#HexagonLayer -> formatLayerData', t => {
test('#HexagonLayer -> renderLayer', t => {
const filteredIndex = [0, 1, 2, 4, 5, 7];
const spyLayerCallbacks = sinon.spy();
- const {allData} = preparedDataset;
const TEST_CASES = [
{
@@ -271,28 +268,23 @@ test('#HexagonLayer -> renderLayer', t => {
// deckGl default pointToHexbin reads viewport set to width: 1 and height: 1 on initial render
const pt0 = {
screenCoord: [81.93285590277779, 314.10787407420145],
- index: 0,
- data: allData[0]
+ index: 0
};
const pt1 = {
screenCoord: [81.90728081597221, 314.125282797666],
- index: 1,
- data: allData[1]
+ index: 1
};
const pt4 = {
screenCoord: [82.29433593749998, 313.5296684059477],
- index: 4,
- data: allData[4]
+ index: 4
};
const pt5 = {
screenCoord: [82.34327256944445, 313.4296004913215],
- index: 5,
- data: allData[5]
+ index: 5
};
const pt7 = {
screenCoord: [82.11757812499998, 314.2888411459387],
- index: 7,
- data: allData[7]
+ index: 7
};
const expectedHexCellData = [
@@ -412,10 +404,10 @@ function creatLayerObjectHovered({layerId, data, object}) {
test('#HexagonLayer -> renderHover', t => {
const filteredIndex = [0, 1, 2, 4, 5, 7];
- const {allData} = preparedDataset;
+ const {dataContainer} = preparedDataset;
const testObjectHovered = creatLayerObjectHovered({
layerId: 'test_layer_1',
- data: allData[0],
+ data: dataContainer.row(0),
object: {
colorValue: 1,
elevationValue: 1,
diff --git a/test/browser/layer-tests/icon-layer-specs.js b/test/browser/layer-tests/icon-layer-specs.js
index 565baa1be..3a77b8a1d 100644
--- a/test/browser/layer-tests/icon-layer-specs.js
+++ b/test/browser/layer-tests/icon-layer-specs.js
@@ -133,7 +133,6 @@ test('#IconLayer -> formatLayerData', t => {
const expectedLayerData = {
data: [
{
- data: testRows[0],
index: 0,
icon: 'accel'
}
diff --git a/test/browser/layer-tests/line-layer-specs.js b/test/browser/layer-tests/line-layer-specs.js
index 94d785985..e02a75c76 100644
--- a/test/browser/layer-tests/line-layer-specs.js
+++ b/test/browser/layer-tests/line-layer-specs.js
@@ -92,13 +92,11 @@ test('#LineLayer -> formatLayerData', t => {
const expectedLayerData = {
data: [
{
- data: testRows[0],
index: 0,
sourcePosition: [testRows[0][2], testRows[0][1], 0],
targetPosition: [testRows[0][4], testRows[0][3], 0]
},
{
- data: testRows[4],
index: 4,
sourcePosition: [testRows[4][2], testRows[4][1], 0],
targetPosition: [testRows[4][4], testRows[4][3], 0]
@@ -219,13 +217,11 @@ test('#LineLayer -> formatLayerData', t => {
const expectedLayerData = {
data: [
{
- data: testRows[0],
index: 0,
sourcePosition: [testRows[0][2], testRows[0][1], 0],
targetPosition: [testRows[0][4], testRows[0][3], 0]
},
{
- data: testRows[4],
index: 4,
sourcePosition: [testRows[4][2], testRows[4][1], 0],
targetPosition: [testRows[4][4], testRows[4][3], 0]
diff --git a/test/browser/layer-tests/point-layer-specs.js b/test/browser/layer-tests/point-layer-specs.js
index 12b56e488..b58875e66 100644
--- a/test/browser/layer-tests/point-layer-specs.js
+++ b/test/browser/layer-tests/point-layer-specs.js
@@ -127,12 +127,10 @@ test('#PointLayer -> formatLayerData', t => {
],
data: [
{
- data: testRows[0],
index: 0,
position: [testRows[0][2], testRows[0][1], testRows[0][7]]
},
{
- data: testRows[4],
index: 4,
position: [testRows[4][2], testRows[4][1], testRows[4][7]]
}
@@ -239,12 +237,10 @@ test('#PointLayer -> formatLayerData', t => {
const expectedLayerData = {
data: [
{
- data: testRows[0],
index: 0,
position: [testRows[0][2], testRows[0][1], 0]
},
{
- data: testRows[4],
index: 4,
position: [testRows[4][2], testRows[4][1], 0]
}
@@ -333,12 +329,10 @@ test('#PointLayer -> formatLayerData', t => {
const expectedLayerData = {
data: [
{
- data: testRows[0],
index: 0,
position: [testRows[0][2], testRows[0][1], 0]
},
{
- data: testRows[4],
index: 4,
position: [testRows[4][2], testRows[4][1], 0]
}
@@ -418,12 +412,10 @@ test('#PointLayer -> formatLayerData', t => {
const expectedLayerData = {
data: [
{
- data: testRows[0],
index: 0,
position: [testRows[0][2], testRows[0][1], 0]
},
{
- data: testRows[4],
index: 4,
position: [testRows[4][2], testRows[4][1], 0]
}
diff --git a/test/browser/layer-tests/s2-geometry-layer-specs.js b/test/browser/layer-tests/s2-geometry-layer-specs.js
index 5e78807d1..f07515592 100644
--- a/test/browser/layer-tests/s2-geometry-layer-specs.js
+++ b/test/browser/layer-tests/s2-geometry-layer-specs.js
@@ -97,8 +97,8 @@ test('#S2Geometry -> formatLayerData', t => {
const {layerData, layer} = result;
const expectedLayerData = {
data: [
- {index: 0, token: '80858004', data: testRows[0]},
- {index: 4, token: '8085801c', data: testRows[4]}
+ {index: 0, token: '80858004'},
+ {index: 4, token: '8085801c'}
],
getElevation: () => {},
getFillColor: () => {},
diff --git a/test/browser/layer-tests/scenegraph-layer-specs.js b/test/browser/layer-tests/scenegraph-layer-specs.js
index 84a931198..b69f8a68d 100644
--- a/test/browser/layer-tests/scenegraph-layer-specs.js
+++ b/test/browser/layer-tests/scenegraph-layer-specs.js
@@ -89,12 +89,10 @@ test('#ScenegraphLayer -> formatLayerData', t => {
const expectedLayerData = {
data: [
{
- data: testRows[0],
index: 0,
position: [testRows[0][2], testRows[0][1], 0]
},
{
- data: testRows[4],
index: 4,
position: [testRows[4][2], testRows[4][1], 0]
}
diff --git a/test/fixtures/test-csv-data.js b/test/fixtures/test-csv-data.js
index c2f51d334..945c815f0 100644
--- a/test/fixtures/test-csv-data.js
+++ b/test/fixtures/test-csv-data.js
@@ -462,7 +462,9 @@ export const testFields = [
displayName: 'gps_data.utc_timestamp',
format: 'YYYY-M-D H:m:s',
analyzerType: 'DATETIME',
- valueAccessor: values => values[0]
+ valueAccessor: dc => d => {
+ return dc.valueAt(d.index, 0);
+ }
},
{
type: 'real',
@@ -472,7 +474,9 @@ export const testFields = [
displayName: 'gps_data.lat',
format: '',
analyzerType: 'FLOAT',
- valueAccessor: values => values[1]
+ valueAccessor: dc => d => {
+ return dc.valueAt(d.index, 1);
+ }
},
{
type: 'real',
@@ -482,7 +486,9 @@ export const testFields = [
displayName: 'gps_data.lng',
format: '',
analyzerType: 'FLOAT',
- valueAccessor: values => values[2]
+ valueAccessor: dc => d => {
+ return dc.valueAt(d.index, 2);
+ }
},
{
type: 'string',
@@ -492,7 +498,9 @@ export const testFields = [
displayName: 'gps_data.types',
format: '',
analyzerType: 'STRING',
- valueAccessor: values => values[3]
+ valueAccessor: dc => d => {
+ return dc.valueAt(d.index, 3);
+ }
},
{
type: 'timestamp',
@@ -502,7 +510,9 @@ export const testFields = [
displayName: 'epoch',
format: 'X',
analyzerType: 'TIME',
- valueAccessor: values => values[4]
+ valueAccessor: dc => d => {
+ return dc.valueAt(d.index, 4);
+ }
},
{
type: 'boolean',
@@ -512,7 +522,9 @@ export const testFields = [
displayName: 'has_result',
format: '',
analyzerType: 'BOOLEAN',
- valueAccessor: values => values[5]
+ valueAccessor: dc => d => {
+ return dc.valueAt(d.index, 5);
+ }
},
{
type: 'integer',
@@ -522,7 +534,9 @@ export const testFields = [
displayName: 'id',
format: '',
analyzerType: 'INT',
- valueAccessor: values => values[6]
+ valueAccessor: dc => d => {
+ return dc.valueAt(d.index, 6);
+ }
},
{
type: 'timestamp',
@@ -532,7 +546,9 @@ export const testFields = [
displayName: 'time',
format: 'YYYY-M-DTHH:mm:ss.SSSS',
analyzerType: 'DATETIME',
- valueAccessor: values => values[7]
+ valueAccessor: dc => d => {
+ return dc.valueAt(d.index, 7);
+ }
},
{
type: 'timestamp',
@@ -542,7 +558,9 @@ export const testFields = [
displayName: 'begintrip_ts_utc',
format: 'YYYY-M-D HH:mm:ssZZ',
analyzerType: 'DATETIME',
- valueAccessor: values => values[8]
+ valueAccessor: dc => d => {
+ return dc.valueAt(d.index, 8);
+ }
},
{
type: 'timestamp',
@@ -552,7 +570,9 @@ export const testFields = [
displayName: 'begintrip_ts_local',
format: 'YYYY-M-D HH:mm:ssZZ',
analyzerType: 'DATETIME',
- valueAccessor: values => values[9]
+ valueAccessor: dc => d => {
+ return dc.valueAt(d.index, 9);
+ }
},
{
type: 'date',
@@ -562,7 +582,9 @@ export const testFields = [
displayName: 'date',
format: 'YYYY-M-D',
analyzerType: 'DATE',
- valueAccessor: values => values[10]
+ valueAccessor: dc => d => {
+ return dc.valueAt(d.index, 10);
+ }
}
];
@@ -909,7 +931,9 @@ export const wktCsvFields = [
format: '',
fieldIdx: 0,
analyzerType: 'INT',
- valueAccessor: values => values[0]
+ valueAccessor: dc => d => {
+ return dc.valueAt(d.index, 0);
+ }
},
{
type: 'geojson',
@@ -919,7 +943,9 @@ export const wktCsvFields = [
format: '',
fieldIdx: 1,
analyzerType: 'PAIR_GEOMETRY_FROM_STRING',
- valueAccessor: values => values[1]
+ valueAccessor: dc => d => {
+ return dc.valueAt(d.index, 1);
+ }
},
{
type: 'geojson',
@@ -929,7 +955,9 @@ export const wktCsvFields = [
format: '',
fieldIdx: 2,
analyzerType: 'GEOMETRY_FROM_STRING',
- valueAccessor: values => values[2]
+ valueAccessor: dc => d => {
+ return dc.valueAt(d.index, 2);
+ }
},
{
type: 'real',
@@ -939,7 +967,9 @@ export const wktCsvFields = [
format: '',
fieldIdx: 3,
analyzerType: 'FLOAT',
- valueAccessor: values => values[3]
+ valueAccessor: dc => d => {
+ return dc.valueAt(d.index, 3);
+ }
},
{
type: 'string',
@@ -949,7 +979,9 @@ export const wktCsvFields = [
format: '',
fieldIdx: 4,
analyzerType: 'STRING',
- valueAccessor: values => values[4]
+ valueAccessor: dc => d => {
+ return dc.valueAt(d.index, 4);
+ }
},
{
type: 'real',
@@ -959,7 +991,9 @@ export const wktCsvFields = [
format: '',
fieldIdx: 5,
analyzerType: 'FLOAT',
- valueAccessor: values => values[5]
+ valueAccessor: dc => d => {
+ return dc.valueAt(d.index, 5);
+ }
}
];
diff --git a/test/fixtures/test-hex-id-data.js b/test/fixtures/test-hex-id-data.js
index d8d3ccede..31a7da0fe 100644
--- a/test/fixtures/test-hex-id-data.js
+++ b/test/fixtures/test-hex-id-data.js
@@ -22,6 +22,8 @@ import {KeplerGlLayers} from 'layers';
const {H3Layer} = KeplerGlLayers;
import {DEFAULT_COLOR_UI} from 'layers/layer-factory';
+import {createDataContainer} from 'utils/table-utils';
+
export default `hex_id,value
89283082c2fffff,64
8928308288fffff,73
@@ -402,6 +404,34 @@ mergedH3Layer.config = {
}
};
+const expectedMergedDatasetData = [
+ ['89283082c2fffff', 64],
+ ['8928308288fffff', 73],
+ ['89283082c07ffff', 65],
+ ['89283082817ffff', 74],
+ ['89283082c3bffff', 66],
+ ['89283082883ffff', 76],
+ ['89283082c33ffff', 43],
+ ['89283082c23ffff', 40],
+ ['89283082887ffff', 36],
+ ['89283082ca7ffff', 27],
+ ['89283082cb3ffff', 32],
+ ['89283082c0bffff', 26],
+ ['89283082ca3ffff', 19],
+ ['89283082dcfffff', 18],
+ ['89283082d8fffff', 1],
+ ['89283095347ffff', 3],
+ ['89283095363ffff', 2],
+ ['8928309537bffff', 4],
+ ['89283082d93ffff', 6],
+ ['89283082d73ffff', 1],
+ ['8928309530bffff', 1],
+ ['8928309532bffff', 1]
+];
+
+const dataContainer = createDataContainer(expectedMergedDatasetData, {fields: mergedFields});
+const indices = dataContainer.getPlainIndex();
+
export const expectedMergedDataset = {
id: 'h3-hex-id',
label: 'new dataset',
@@ -410,32 +440,9 @@ export const expectedMergedDataset = {
id: 'h3-hex-id',
label: 'new dataset'
},
- allData: [
- ['89283082c2fffff', 64],
- ['8928308288fffff', 73],
- ['89283082c07ffff', 65],
- ['89283082817ffff', 74],
- ['89283082c3bffff', 66],
- ['89283082883ffff', 76],
- ['89283082c33ffff', 43],
- ['89283082c23ffff', 40],
- ['89283082887ffff', 36],
- ['89283082ca7ffff', 27],
- ['89283082cb3ffff', 32],
- ['89283082c0bffff', 26],
- ['89283082ca3ffff', 19],
- ['89283082dcfffff', 18],
- ['89283082d8fffff', 1],
- ['89283095347ffff', 3],
- ['89283095363ffff', 2],
- ['8928309537bffff', 4],
- ['89283082d93ffff', 6],
- ['89283082d73ffff', 1],
- ['8928309530bffff', 1],
- ['8928309532bffff', 1]
- ],
- allIndexes: new Array(22).fill(0).map((d, i) => i),
- filteredIndex: new Array(22).fill(0).map((d, i) => i),
+ dataContainer,
+ allIndexes: indices,
+ filteredIndex: indices,
filteredIndexForDomain: [9, 11, 12, 13],
fieldPairs: [],
fields: mergedFields,
@@ -453,7 +460,7 @@ export const expectedMergedDataset = {
gpuFilter_3: null
},
filterValueAccessor: {
- inputs: [{data: ['89283082c33ffff', 43], index: 6}],
+ inputs: [{index: 6}],
result: [42, 0, 0, 0]
}
},
diff --git a/test/helpers/comparison-utils.js b/test/helpers/comparison-utils.js
index 6d75df3bb..77403d4db 100644
--- a/test/helpers/comparison-utils.js
+++ b/test/helpers/comparison-utils.js
@@ -234,7 +234,12 @@ export function cmpDataset(t, expectedDataset, actualDataset, opt = {}) {
break;
case 'gpuFilter':
// test gpuFilter props
- cmpGpuFilterProp(t, expectedDataset.gpuFilter, actualDataset.gpuFilter);
+ cmpGpuFilterProp(
+ t,
+ expectedDataset.gpuFilter,
+ actualDataset.gpuFilter,
+ actualDataset.dataContainer
+ );
break;
case 'filterRecord':
case 'filterRecordCPU':
@@ -269,14 +274,14 @@ export function cmpDataset(t, expectedDataset, actualDataset, opt = {}) {
});
}
-export function cmpGpuFilterProp(t, expectedGpuFilter, actualGpuFilter) {
+export function cmpGpuFilterProp(t, expectedGpuFilter, actualGpuFilter, dataContainer) {
cmpObjectKeys(t, expectedGpuFilter, actualGpuFilter, 'gpu filter');
Object.keys(expectedGpuFilter).forEach(key => {
if (key === 'filterValueAccessor' && expectedGpuFilter.filterValueAccessor.inputs) {
const {inputs, result} = expectedGpuFilter.filterValueAccessor;
t.deepEqual(
- actualGpuFilter.filterValueAccessor()(...inputs),
+ actualGpuFilter.filterValueAccessor(dataContainer)()(...inputs),
result,
'getFilterValue should be correct'
);
diff --git a/test/node/reducers/vis-state-merger-test.js b/test/node/reducers/vis-state-merger-test.js
index 982a67c8c..49af350ad 100644
--- a/test/node/reducers/vis-state-merger-test.js
+++ b/test/node/reducers/vis-state-merger-test.js
@@ -38,6 +38,8 @@ import {receiveMapConfig, addDataToMap} from 'actions/actions';
import {getDefaultInteraction} from 'utils/interaction-utils';
import {processKeplerglJSON} from 'processors/data-processor';
+import {createDataContainer} from 'utils/table-utils';
+
// fixtures
import {
savedStateV0,
@@ -1503,23 +1505,37 @@ test('VisStateMerger.v1 -> mergeFilters -> multiFilters', t => {
);
// check datasets is filtered
// and field has filterProps
+
+ const tFields0 = testFields.map(f => ({
+ ...f,
+ ...(f.name === 'time'
+ ? {filterProps: timeFilterProps}
+ : f.name === 'date'
+ ? {filterProps: dateFilterProps}
+ : f.name === 'epoch'
+ ? {filterProps: epochFilterProps}
+ : {})
+ }));
+ const dc0 = createDataContainer(testAllData, {fields: tFields0});
+
+ const tFields1 = fields.map(f => ({
+ ...f,
+ ...(f.name === 'TRIPS'
+ ? {filterProps: geoJsonTripFilterProps}
+ : f.name === 'RATE'
+ ? {filterProps: geoJsonRateFilterProps}
+ : {})
+ }));
+ const dc1 = createDataContainer(testGeoJsonAllData, {fields: tFields1});
+
const expectedDatasets = {
[testCsvDataId]: {
metadata: {
id: testCsvDataId,
label: 'hello.csv'
},
- fields: testFields.map(f => ({
- ...f,
- ...(f.name === 'time'
- ? {filterProps: timeFilterProps}
- : f.name === 'date'
- ? {filterProps: dateFilterProps}
- : f.name === 'epoch'
- ? {filterProps: epochFilterProps}
- : {})
- })),
- allData: testAllData,
+ fields: tFields0,
+ dataContainer: dc0,
allIndexes: [
0,
1,
@@ -1574,7 +1590,6 @@ test('VisStateMerger.v1 -> mergeFilters -> multiFilters', t => {
filterValueAccessor: {
inputs: [
{
- data: testAllData[1],
index: 1
}
],
@@ -1593,14 +1608,7 @@ test('VisStateMerger.v1 -> mergeFilters -> multiFilters', t => {
id: testGeoJsonDataId,
label: 'zip.geojson'
},
- fields: fields.map(f => ({
- ...f,
- ...(f.name === 'TRIPS'
- ? {filterProps: geoJsonTripFilterProps}
- : f.name === 'RATE'
- ? {filterProps: geoJsonRateFilterProps}
- : {})
- })),
+ fields: tFields1,
filterRecord: {
dynamicDomain: [mergedRateFilter, mergedTripFilter],
fixedDomain: [],
@@ -1623,14 +1631,13 @@ test('VisStateMerger.v1 -> mergeFilters -> multiFilters', t => {
filterValueAccessor: {
inputs: [
{
- data: testGeoJsonAllData[1],
index: 1
}
],
result: [0, 0, 0, 0]
}
},
- allData: testGeoJsonAllData,
+ dataContainer: dc1,
allIndexes: [0, 1, 2, 3, 4],
id: testGeoJsonDataId,
label: 'zip.geojson',
diff --git a/test/node/reducers/vis-state-test.js b/test/node/reducers/vis-state-test.js
index fae1be868..396e157ef 100644
--- a/test/node/reducers/vis-state-test.js
+++ b/test/node/reducers/vis-state-test.js
@@ -42,6 +42,8 @@ import {ALL_FIELD_TYPES, EDITOR_MODES} from 'constants/default-settings';
const {ArcLayer, PointLayer, GeojsonLayer, LineLayer, TripLayer} = KeplerGlLayers;
+import {createDataContainer} from 'utils/table-utils';
+
// fixtures
import testData, {mergedTimeFilter, testFields, testAllData} from 'test/fixtures/test-csv-data';
import {
@@ -365,7 +367,7 @@ test('#visStateReducer -> LAYER_TYPE_CHANGE.2', t => {
isReversed: true,
colors: ['a', 'b', 'c']
};
- const smoothie = createNewDataEntry({
+ const datasets = createNewDataEntry({
info: {id: 'smoothie'},
data: {
rows: testAllData,
@@ -374,13 +376,17 @@ test('#visStateReducer -> LAYER_TYPE_CHANGE.2', t => {
});
const oldState = {
...INITIAL_VIS_STATE,
- datasets: smoothie,
+ datasets,
layers: [pointLayer],
layerData: []
};
// set point layer colorField to a string field
- const stringField = testFields.find(f => f.type === 'string');
+ let stringField = testFields.find(f => f.type === 'string');
+ stringField = {
+ ...stringField,
+ valueAccessor: stringField.valueAccessor(datasets.smoothie.dataContainer)
+ };
let nextState = reducer(
oldState,
VisStateActions.layerVisualChannelConfigChange(pointLayer, {colorField: stringField}, 'color')
@@ -402,7 +408,8 @@ test('#visStateReducer -> LAYER_TYPE_CHANGE.2', t => {
t.equal(newLayer.config.visConfig.colorRange, mockColorRange, 'should update color range');
// set point layer sizeField to a int field
- const intField = testFields.find(f => f.type === 'integer');
+ let intField = testFields.find(f => f.type === 'integer');
+ intField = {...intField, valueAccessor: intField.valueAccessor(datasets.smoothie.dataContainer)};
let nextState2 = reducer(
nextState,
VisStateActions.layerVisualChannelConfigChange(newLayer, {sizeField: intField}, 'size')
@@ -927,7 +934,6 @@ test('#visStateReducer -> REMOVE_FILTER', t => {
filterValueAccessor: {
inputs: [
{
- data: dataset0.allData[0],
index: 0
}
],
@@ -959,7 +965,7 @@ test('#visStateReducer -> REMOVE_FILTER', t => {
// remove smoothie filter - gpu: true, fixedDomain: false
const newReducer = reducer(initialState, VisStateActions.removeFilter(1));
- const expectedLayerData1 = {data: dataset1.allData.map(d => d)};
+ const expectedLayerData1 = {data: dataset1.dataContainer.mapIndex(d => d)};
const expectedState = {
...initialState,
filters: expectedFilters,
@@ -1194,7 +1200,7 @@ test('#visStateReducer -> UPDATE_VIS_DATA.2 -> to empty state', t => {
filteredIndex: mockRawData.rows.map((_, i) => i),
filteredIndexForDomain: mockRawData.rows.map((_, i) => i),
allIndexes: mockRawData.rows.map((_, i) => i),
- allData: mockRawData.rows,
+ dataContainer: createDataContainer(mockRawData.rows, {fields: mockRawData.fields}),
gpuFilter: {
filterRange: [
[0, 0],
@@ -1347,6 +1353,7 @@ test('#visStateReducer -> UPDATE_VIS_DATA.3 -> merge w/ existing state', t => {
}
});
+ const testFields3 = [{id: 'a'}, {id: 'b'}];
const oldState = {
...INITIAL_VIS_STATE,
layers: [mockLayer],
@@ -1358,8 +1365,10 @@ test('#visStateReducer -> UPDATE_VIS_DATA.3 -> merge w/ existing state', t => {
],
datasets: {
snowflake: {
- fields: [{id: 'a'}, {id: 'b'}],
- allData: [['something'], ['something_else']]
+ fields: testFields3,
+ dataContainer: createDataContainer([['something'], ['something_else']], {
+ fields: testFields3
+ })
}
},
filters: [{name: 'hello'}, {name: 'world'}],
@@ -1378,10 +1387,13 @@ test('#visStateReducer -> UPDATE_VIS_DATA.3 -> merge w/ existing state', t => {
splitMaps: []
};
+ const testFields2 = [{id: 'a'}, {id: 'b'}];
const expectedDatasets = {
snowflake: {
- fields: [{id: 'a'}, {id: 'b'}],
- allData: [['something'], ['something_else']]
+ fields: testFields2,
+ dataContainer: createDataContainer([['something'], ['something_else']], {
+ fields: testFields2
+ })
},
smoothie: {
metadata: {
@@ -1389,7 +1401,7 @@ test('#visStateReducer -> UPDATE_VIS_DATA.3 -> merge w/ existing state', t => {
label: 'smoothie and milkshake'
},
fields: expectedFields,
- allData: mockRawData.rows,
+ dataContainer: createDataContainer(mockRawData.rows, {fields: mockRawData.fields}),
color: 'donnot test me',
filteredIndex: mockRawData.rows.map((_, i) => i),
filteredIndexForDomain: mockRawData.rows.map((_, i) => i),
@@ -1513,11 +1525,11 @@ test('#visStateReducer -> UPDATE_VIS_DATA.4.Geojson -> geojson data', t => {
id: 'milkshake',
label: 'king milkshake',
color: 'donnot test me',
- allData: rows,
+ dataContainer: createDataContainer(rows, {fields}),
filteredIndex: rows.map((_, i) => i),
filteredIndexForDomain: rows.map((_, i) => i),
allIndexes: rows.map((_, i) => i),
- fields: fields.map((f, i) => ({...f, valueAccessor: values => values[i]})),
+ fields,
fieldPairs: [],
gpuFilter: {
filterRange: [
@@ -1709,7 +1721,8 @@ test('#visStateReducer -> UPDATE_VIS_DATA -> mergeFilters', t => {
])
);
- const allIndexes = mockRawData.rows.map((_, i) => i);
+ const dc = createDataContainer(mockRawData.rows, {fields: mockRawData.fields});
+ const allIndexes = dc.getPlainIndex();
const expectedDatasets = {
smoothie: {
@@ -1751,12 +1764,12 @@ test('#visStateReducer -> UPDATE_VIS_DATA -> mergeFilters', t => {
gpuFilter_3: null
},
filterValueAccessor: {
- inputs: [{data: mockRawData.rows[0], index: 1}],
+ inputs: [{index: 0}],
result: [12.25 - expectedFilter.domain[0], 0, 0, 0]
}
},
allIndexes,
- allData: mockRawData.rows,
+ dataContainer: dc,
color: 'donot test me',
id: 'smoothie',
label: 'smoothie and milkshake',
@@ -2013,7 +2026,8 @@ test('#visStateReducer -> setFilter.dynamicDomain & cpu', t => {
}
};
- const {allData} = initialState.datasets.smoothie;
+ const fieldsEx = [...initialState.datasets.smoothie.fields.slice(0, 10), updatedField];
+ const {dataContainer} = initialState.datasets.smoothie;
// test dataset
const expectedDataset = {
@@ -2024,11 +2038,11 @@ test('#visStateReducer -> setFilter.dynamicDomain & cpu', t => {
id: 'smoothie',
label: 'queen smoothie',
color: 'donnot test me',
- allData,
- fields: [...initialState.datasets.smoothie.fields.slice(0, 10), updatedField],
- filteredIndex: allData.map((d, i) => i),
- filteredIndexForDomain: allData.map((d, i) => i),
- allIndexes: allData.map((d, i) => i),
+ dataContainer,
+ fields: fieldsEx,
+ filteredIndex: dataContainer.getPlainIndex(),
+ filteredIndexForDomain: dataContainer.getPlainIndex(),
+ allIndexes: dataContainer.getPlainIndex(),
filterRecord: {
dynamicDomain: [],
fixedDomain: [],
@@ -2049,7 +2063,7 @@ test('#visStateReducer -> setFilter.dynamicDomain & cpu', t => {
gpuFilter_3: null
},
filterValueAccessor: {
- inputs: [{data: allData[0], index: 0}],
+ inputs: [{index: 0}],
result: [0, 0, 0, 0]
}
},
@@ -2097,7 +2111,7 @@ test('#visStateReducer -> setFilter.dynamicDomain & cpu', t => {
cpu: [updatedFilterWValue],
gpu: []
},
- allData,
+ dataContainer,
filteredIndex: [17, 18, 19, 20, 21, 22],
filteredIndexForDomain: [17, 18, 19, 20, 21, 22],
changedFilters: {
@@ -2112,12 +2126,12 @@ test('#visStateReducer -> setFilter.dynamicDomain & cpu', t => {
const expectedLayerData1 = {
data: [
- {data: allData[17], index: 17, position: [31.2165983, 30.0538936, 0]},
- {data: allData[18], index: 18, position: [31.2148748, 30.060911, 0]},
- {data: allData[19], index: 19, position: [31.2212278, 30.060334, 0]},
- {data: allData[20], index: 20, position: [31.2288985, 30.0554663, 0]},
- {data: allData[21], index: 21, position: [31.2187021, 30.0614122, 0]},
- {data: allData[22], index: 22, position: [31.2191059, 30.0612697, 0]}
+ {index: 17, position: [31.2165983, 30.0538936, 0]},
+ {index: 18, position: [31.2148748, 30.060911, 0]},
+ {index: 19, position: [31.2212278, 30.060334, 0]},
+ {index: 20, position: [31.2288985, 30.0554663, 0]},
+ {index: 21, position: [31.2187021, 30.0614122, 0]},
+ {index: 22, position: [31.2191059, 30.0612697, 0]}
],
getPosition: () => {},
getColor: () => {},
@@ -2292,7 +2306,8 @@ function testSetFilterDynamicDomainGPU(t, setFilter) {
// is time
f.type === ALL_FIELD_TYPES.timestamp,
i,
- f.format
+ f.format,
+ initialState.datasets.milkshake.dataContainer
),
...(f.name === 'TRIPS' ? {filterProps: geoJsonTripFilterProps} : {})
})),
@@ -2310,7 +2325,7 @@ function testSetFilterDynamicDomainGPU(t, setFilter) {
gpuFilter_3: null
},
filterValueAccessor: {
- inputs: [{data: initialState.datasets.milkshake.allData[0], index: 0}],
+ inputs: [{index: 0}],
result: [7, 0, 0, 0]
}
},
@@ -2514,13 +2529,13 @@ test('#visStateReducer -> setFilter.fixedDomain & DynamicDomain & gpu & cpu', t
gpuFilter_3: null
},
filterValueAccessor: {
- inputs: [{data: datasetSmoothie.allData[1], index: 1}],
+ inputs: [{index: 1}],
result: [61000, 0, 0, 0]
}
},
// copy everything
- filteredIndex: datasetSmoothie.allData.map((d, i) => i),
- filteredIndexForDomain: datasetSmoothie.allData.map((d, i) => i),
+ filteredIndex: datasetSmoothie.dataContainer.getPlainIndex(),
+ filteredIndexForDomain: datasetSmoothie.dataContainer.getPlainIndex(),
changedFilters: {
dynamicDomain: null,
fixedDomain: {[filterId]: 'value_changed'},
@@ -2579,7 +2594,7 @@ test('#visStateReducer -> setFilter.fixedDomain & DynamicDomain & gpu & cpu', t
gpuFilter_3: null
},
filterValueAccessor: {
- inputs: [{data: datasetSmoothie.allData[1], index: 1}],
+ inputs: [{index: 1}],
result: [61000, 0, 0, 0]
}
},
diff --git a/test/node/utils/data-container-test.js b/test/node/utils/data-container-test.js
new file mode 100644
index 000000000..832ef5e3e
--- /dev/null
+++ b/test/node/utils/data-container-test.js
@@ -0,0 +1,139 @@
+// Copyright (c) 2021 Uber Technologies, Inc.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a copy
+// of this software and associated documentation files (the "Software"), to deal
+// in the Software without restriction, including without limitation the rights
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+// copies of the Software, and to permit persons to whom the Software is
+// furnished to do so, subject to the following conditions:
+//
+// The above copyright notice and this permission notice shall be included in
+// all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+// THE SOFTWARE.
+
+import test from 'tape';
+
+import {createDataContainer, createIndexedDataContainer} from 'utils/table-utils/';
+
+const data = [
+ [10, 20], // 0
+ [30, 40], // 1
+ [50, 60], // 2
+ [80, 90], // 3
+ [100, 110], // 4
+ [120, 130] // 5
+];
+
+const indices = [1, 3, 5];
+
+test('RowDataContainer', t => {
+ const dc = createDataContainer(data);
+
+ t.deepEqual(dc.numRows(), 6, `RowDataContainer should have expected number of rows`);
+ t.deepEqual(dc.numColumns(), 2, `RowDataContainer should have expected number of columns`);
+ t.deepEqual(dc.valueAt(2, 1), 60, `RowDataContainer.valueAt should return expected value`);
+ t.deepEqual(dc.row(2).valueAt(1), 60, `RowDataContainer.row should return expected value`);
+ t.deepEqual(
+ dc.rowAsArray(2),
+ [50, 60],
+ `RowDataContainer.rowAsArray should return expected value`
+ );
+ t.deepEqual(dc.flattenData(), data, `RowDataContainer.flattenData should return expected data`);
+ t.deepEqual(
+ dc.getPlainIndex(),
+ [0, 1, 2, 3, 4, 5],
+ `RowDataContainer.getPlainIndex should return expected indices`
+ );
+
+ t.deepEqual(
+ dc.map((row, rowIndex) => row.valueAt(1)),
+ [20, 40, 60, 90, 110, 130],
+ `RowDataContainer.map should return expected array`
+ );
+
+ t.deepEqual(
+ dc.mapIndex(d => d),
+ [{index: 0}, {index: 1}, {index: 2}, {index: 3}, {index: 4}, {index: 5}],
+ `RowDataContainer.mapIndex should return expected array`
+ );
+
+ t.deepEqual(
+ dc.find((row, rowIndex) => {
+ return row.valueAt(1) === 60;
+ }),
+ dc.row(2),
+ `RowDataContainer.find should return expected row`
+ );
+
+ t.deepEqual(
+ dc.reduce((acc, row, index) => {
+ return acc + row.valueAt(1);
+ }, 10),
+ 460,
+ `RowDataContainer.reduce should return expected value`
+ );
+
+ t.end();
+});
+
+test('IndexedDataContainer', t => {
+ const dc = createIndexedDataContainer(createDataContainer(data), indices);
+
+ t.deepEqual(dc.numRows(), 3, `IndexedDataContainer should have expected number of rows`);
+ t.deepEqual(dc.numColumns(), 2, `IndexedDataContainer should have expected number of columns`);
+ t.deepEqual(dc.valueAt(2, 1), 130, `IndexedDataContainer.valueAt should return expected value`);
+ t.deepEqual(dc.row(2).valueAt(1), 130, `IndexedDataContainer.row should return expected value`);
+ t.deepEqual(
+ dc.rowAsArray(2),
+ [120, 130],
+ `IndexedDataContainer.rowAsArray should return expected value`
+ );
+
+ t.deepEqual(
+ dc.flattenData(),
+ [data[indices[0]], data[indices[1]], data[indices[2]]],
+ `IndexedDataContainer.flattenData should return expected data`
+ );
+ t.deepEqual(
+ dc.getPlainIndex(),
+ [0, 1, 2],
+ `IndexedDataContainer.getPlainIndex should return expected indices`
+ );
+
+ t.deepEqual(
+ dc.map((row, rowIndex) => row.valueAt(1)),
+ [40, 90, 130],
+ `IndexedDataContainer.map should return expected array`
+ );
+
+ t.deepEqual(
+ dc.mapIndex(d => d),
+ [{index: 1}, {index: 3}, {index: 5}],
+ `IndexedDataContainer.mapIndex should return expected array`
+ );
+
+ t.deepEqual(
+ dc.find((row, rowIndex) => {
+ return row.valueAt(1) === 90;
+ }),
+ dc.row(1),
+ `IndexedDataContainer.find should return expected row`
+ );
+
+ t.deepEqual(
+ dc.reduce((acc, row, index) => {
+ return acc + row.valueAt(1);
+ }, 10),
+ 270,
+ `RowDataContainer.reduce should return expected value`
+ );
+
+ t.end();
+});
diff --git a/test/node/utils/data-processor-test.js b/test/node/utils/data-processor-test.js
index b6f5d00b0..9cf32036d 100644
--- a/test/node/utils/data-processor-test.js
+++ b/test/node/utils/data-processor-test.js
@@ -55,6 +55,8 @@ import {
validateInputData
} from 'processors/data-processor';
+import {createDataContainer} from 'utils/table-utils';
+
import {ALL_FIELD_TYPES} from 'constants/default-settings';
import {cmpFields} from '../../helpers/comparison-utils';
@@ -424,7 +426,7 @@ test('Processor -> parseCsvRowsByFieldType -> boolean', t => {
test('Processor -> getSampleForTypeAnalyze', t => {
const fields = ['string', 'int', 'bool', 'time'];
- const allData = [
+ const rows = [
['a', 0, true, null],
['b', 2, false, null],
['c', 3, true, '2017-01-01'],
@@ -436,7 +438,7 @@ test('Processor -> getSampleForTypeAnalyze', t => {
['h', undefined, true, '2017-01-04']
];
- const sample = getSampleForTypeAnalyze({fields, allData, sampleCount: 5});
+ const sample = getSampleForTypeAnalyze({fields, rows, sampleCount: 5});
const expected = [
{
string: 'a',
@@ -670,8 +672,9 @@ test('Processor -> formatCsv', t => {
cases.forEach(({input, expected, msg, processor}) => {
const {fields, rows} = processor(input);
+ const dataContainer = createDataContainer(rows, {fields});
- t.deepEqual(formatCsv(rows, fields), expected, msg);
+ t.deepEqual(formatCsv(dataContainer, fields), expected, msg);
});
t.end();
});
diff --git a/test/node/utils/data-scale-utils-test.js b/test/node/utils/data-scale-utils-test.js
index 7af8521a6..157d8ab9a 100644
--- a/test/node/utils/data-scale-utils-test.js
+++ b/test/node/utils/data-scale-utils-test.js
@@ -25,24 +25,22 @@ import {
getLinearDomain,
getLogDomain
} from 'utils/data-scale-utils';
+import {createDataContainer} from 'utils/table-utils';
function numberSort(a, b) {
return a - b;
}
test('DataScaleUtils -> getOrdinalDomain', t => {
- const data = ['a', 'a', 'b', undefined, null, 0];
- function valueAccessor(d) {
- return d.value;
- }
+ const data = [['a'], ['a'], ['b'], [undefined], [null], [0], null];
- const values = [{value: 'a'}, {value: 'b'}, {value: 'b'}];
-
- t.deepEqual(getOrdinalDomain(data), [0, 'a', 'b'], 'should get correct ordinal domain');
+ function valueAccessor(d, dc) {
+ return dc.valueAt(d.index, 0);
+ }
t.deepEqual(
- getOrdinalDomain(values, valueAccessor),
- ['a', 'b'],
+ getOrdinalDomain(createDataContainer(data), valueAccessor),
+ [0, 'a', 'b'],
'should get correct ordinal domain'
);
diff --git a/test/node/utils/filter-utils-test.js b/test/node/utils/filter-utils-test.js
index dbff7a79f..f375402df 100644
--- a/test/node/utils/filter-utils-test.js
+++ b/test/node/utils/filter-utils-test.js
@@ -39,6 +39,8 @@ import {getDatasetFieldIndexForFilter} from 'utils/gpu-filter-utils';
import {FILTER_TYPES} from 'constants/default-settings';
import {mockPolygonFeature, mockPolygonData} from '../../fixtures/polygon';
+import {createDataContainer} from 'utils/table-utils';
+
/* eslint-disable max-statements */
test('filterUtils -> adjustValueToFilterDomain', t => {
// TODO: needs id
@@ -370,19 +372,20 @@ test('filterUtils -> Polygon getFilterFunction ', t => {
const dataset = {
id: 'puppy',
data: mockPolygonData.data,
- allData: mockPolygonData.data,
fields: mockPolygonData.fields
};
+ const dataContainer = createDataContainer(dataset.data);
+
const {layers, data} = mockPolygonData;
const polygonFilter = generatePolygonFilter(layers, mockPolygonFeature);
- let filterFunction = getFilterFunction(null, dataset.id, polygonFilter, []);
+ let filterFunction = getFilterFunction(null, dataset.id, polygonFilter, [], dataContainer);
t.equal(filterFunction(data[0], 0), true, `Should return true because layer list is empty`);
- filterFunction = getFilterFunction(null, 'puppy-2', polygonFilter, layers);
+ filterFunction = getFilterFunction(null, 'puppy-2', polygonFilter, layers, dataContainer);
t.equal(
filterFunction(data[0], 0),
@@ -472,21 +475,7 @@ test('filterUtils -> diffFilters', t => {
});
test('filterUtils -> getTimestampFieldDomain', t => {
- /* eslint-disable func-style */
- const valueAccessor = d => moment.utc(d).valueOf();
- /* eslint-enable func-style */
-
const timeData = {
- no: {
- input: 0.5,
- expect: {
- domain: [0, 1],
- step: 0.05,
- ...getHistogram([0, 1], []),
- mappedValue: [],
- defaultTimeFormat: 'L LTS'
- }
- },
zero: {
input: ['2016-10-01 09:45:39', '2016-10-01 09:45:39'],
expect: {
@@ -547,11 +536,14 @@ test('filterUtils -> getTimestampFieldDomain', t => {
};
Object.keys(timeData).forEach(key => {
- const tsFieldDomain = getTimestampFieldDomain(timeData[key].input, valueAccessor);
+ const dataContainer = createDataContainer(timeData[key].input.map(d => [d]));
+ const valueAccessor = dc => d => moment.utc(dc.valueAt(d.index, 0)).valueOf();
+ const tsFieldDomain = getTimestampFieldDomain(dataContainer, valueAccessor(dataContainer));
+
t.deepEqual(
Object.keys(tsFieldDomain).sort(),
Object.keys(timeData[key].expect).sort(),
- 'Should domain should have same keys'
+ 'domain should have same keys'
);
Object.keys(timeData[key].expect).forEach(k => {
diff --git a/test/node/utils/index.js b/test/node/utils/index.js
index 7455d2928..9704756b9 100644
--- a/test/node/utils/index.js
+++ b/test/node/utils/index.js
@@ -21,6 +21,7 @@
import './data-utils-test';
import './data-processor-test';
import './kepler-table-test';
+import './data-container-test';
import './filter-utils-test';
import './gpu-filter-utils-test';
import './layer-utils-test';
diff --git a/test/node/utils/interaction-utils-test.js b/test/node/utils/interaction-utils-test.js
index 57b9ee0e1..b4cdc8ee2 100644
--- a/test/node/utils/interaction-utils-test.js
+++ b/test/node/utils/interaction-utils-test.js
@@ -148,10 +148,10 @@ test('interactionUtil -> getTooltipDisplayDeltaValue', t => {
const TEST_CASES = [
{
input: {
- primaryData: dataset.allData[0],
+ primaryData: dataset.dataContainer.row(0),
field: dataset.fields[testFieldIdx],
compareType: COMPARE_TYPES.ABSOLUTE,
- data: dataset.allData[1],
+ data: dataset.dataContainer.row(1),
fieldIdx: testFieldIdx,
item
},
@@ -160,10 +160,10 @@ test('interactionUtil -> getTooltipDisplayDeltaValue', t => {
},
{
input: {
- primaryData: dataset.allData[0],
+ primaryData: dataset.dataContainer.row(0),
field: dataset.fields[testFieldIdx],
compareType: COMPARE_TYPES.RELATIVE,
- data: dataset.allData[1],
+ data: dataset.dataContainer.row(1),
fieldIdx: testFieldIdx,
item
},
@@ -172,10 +172,10 @@ test('interactionUtil -> getTooltipDisplayDeltaValue', t => {
},
{
input: {
- primaryData: dataset.allData[3],
+ primaryData: dataset.dataContainer.row(3),
field: dataset.fields[testFieldIdx],
compareType: COMPARE_TYPES.ABSOLUTE,
- data: dataset.allData[1],
+ data: dataset.dataContainer.row(1),
fieldIdx: testFieldIdx,
item
},
@@ -184,10 +184,10 @@ test('interactionUtil -> getTooltipDisplayDeltaValue', t => {
},
{
input: {
- primaryData: dataset.allData[0],
+ primaryData: dataset.dataContainer.row(0),
field: dataset.fields[testFieldIdx],
compareType: COMPARE_TYPES.ABSOLUTE,
- data: dataset.allData[3],
+ data: dataset.dataContainer.row(3),
fieldIdx: testFieldIdx,
item
},
@@ -196,10 +196,10 @@ test('interactionUtil -> getTooltipDisplayDeltaValue', t => {
},
{
input: {
- primaryData: dataset.allData[4],
+ primaryData: dataset.dataContainer.row(4),
field: dataset.fields[testFieldIdx],
compareType: COMPARE_TYPES.ABSOLUTE,
- data: dataset.allData[3],
+ data: dataset.dataContainer.row(3),
fieldIdx: testFieldIdx,
item
},
@@ -243,7 +243,7 @@ test('interactionUtil -> getTooltipDisplayValue', t => {
const fieldIdx = dataset.fields.findIndex(f => f.name === tc.input.name);
t.deepEqual(
- dataset.allData.map(data =>
+ dataset.dataContainer.map(data =>
getTooltipDisplayValue({
field,
data,
diff --git a/test/node/utils/kepler-table-test.js b/test/node/utils/kepler-table-test.js
index cd0693058..ab173008a 100644
--- a/test/node/utils/kepler-table-test.js
+++ b/test/node/utils/kepler-table-test.js
@@ -119,7 +119,7 @@ function testGetNumericFieldStep(table, t) {
);
}
-function testGetFilterFunction({fields, allData}, t) {
+function testGetFilterFunction({fields, dataContainer}, t) {
const dataId = 'dataset-1';
const timeStringFilter = {
fieldIdx: [0],
@@ -134,11 +134,19 @@ function testGetFilterFunction({fields, allData}, t) {
let field = fields[timeStringFilter.fieldIdx[0]];
- let filterFunction = getFilterFunction(field, dataId, timeStringFilter, []);
+ let filterFunction = getFilterFunction(field, dataId, timeStringFilter, [], dataContainer);
- t.equal(filterFunction(allData[10], 10), true, `${allData[10][0]} should be inside the range`);
+ t.equal(
+ filterFunction({index: 10}),
+ true,
+ `${dataContainer.valueAt(10, 0)} should be inside the range`
+ );
- t.equal(filterFunction(allData[15], 15), false, `${allData[15][0]} should be outside the range`);
+ t.equal(
+ filterFunction({index: 15}),
+ false,
+ `${dataContainer.valueAt(15, 0)} should be outside the range`
+ );
const epochFilter = {
fieldIdx: [4],
@@ -150,11 +158,19 @@ function testGetFilterFunction({fields, allData}, t) {
field = fields[epochFilter.fieldIdx[0]];
- filterFunction = getFilterFunction(field, dataId, epochFilter, []);
+ filterFunction = getFilterFunction(field, dataId, epochFilter, [], dataContainer);
- t.equal(filterFunction(allData[10], 10), true, `${allData[10][1]} should be inside the range`);
+ t.equal(
+ filterFunction({index: 10}),
+ true,
+ `${dataContainer.valueAt(10, 1)} should be inside the range`
+ );
- t.equal(filterFunction(allData[15], 15), false, `${allData[15][1]} should be outside the range`);
+ t.equal(
+ filterFunction({index: 15}),
+ false,
+ `${dataContainer.valueAt(15, 1)} should be outside the range`
+ );
const tzFilter = {
fieldIdx: [7],
@@ -169,11 +185,19 @@ function testGetFilterFunction({fields, allData}, t) {
field = fields[tzFilter.fieldIdx[0]];
- filterFunction = getFilterFunction(field, dataId, tzFilter, []);
+ filterFunction = getFilterFunction(field, dataId, tzFilter, [], dataContainer);
- t.equal(filterFunction(allData[10], 10), true, `${allData[10][7]} should be inside the range`);
+ t.equal(
+ filterFunction({index: 10}),
+ true,
+ `${dataContainer.valueAt(10, 7)} should be inside the range`
+ );
- t.equal(filterFunction(allData[23], 10), false, `${allData[23][7]} should be outside the range`);
+ t.equal(
+ filterFunction({index: 23}),
+ false,
+ `${dataContainer.valueAt(23, 7)} should be outside the range`
+ );
const utcFilter = {
fieldIdx: [8],
@@ -188,13 +212,25 @@ function testGetFilterFunction({fields, allData}, t) {
field = fields[utcFilter.fieldIdx[0]];
- filterFunction = getFilterFunction(field, dataId, utcFilter, []);
+ filterFunction = getFilterFunction(field, dataId, utcFilter, [], dataContainer);
- t.equal(filterFunction(allData[6], 6), false, `${allData[0][8]} should be outside the range`);
+ t.equal(
+ filterFunction({index: 6}),
+ false,
+ `${dataContainer.valueAt(0, 8)} should be outside the range`
+ );
- t.equal(filterFunction(allData[4], 4), true, `${allData[4][8]} should be inside the range`);
+ t.equal(
+ filterFunction({index: 4}),
+ true,
+ `${dataContainer.valueAt(4, 8)} should be inside the range`
+ );
- t.equal(filterFunction(allData[23], 23), false, `${allData[23][8]} should be outside the range`);
+ t.equal(
+ filterFunction({index: 23}),
+ false,
+ `${dataContainer.valueAt(23, 8)} should be outside the range`
+ );
}
test('KeplerTable -> getColumnFilterDomain -> time', t => {
diff --git a/test/node/utils/layer-utils-test.js b/test/node/utils/layer-utils-test.js
index d12faf6ce..ed2253f92 100644
--- a/test/node/utils/layer-utils-test.js
+++ b/test/node/utils/layer-utils-test.js
@@ -36,6 +36,8 @@ import {getNextColorMakerValue} from 'test/helpers/layer-utils';
import tripGeojson, {timeStampDomain, tripBounds} from 'test/fixtures/trip-geojson';
import {geoJsonWithStyle} from 'test/fixtures/geojson';
+import {createDataContainer} from 'utils/table-utils';
+
test('layerUtils -> findDefaultLayer.1', t => {
const inputFields = [
// layer 1
@@ -593,30 +595,33 @@ test('layerUtils -> findDefaultLayer:GeojsonLayer', t => {
const {fields} = dataset;
+ const dataContainer = createDataContainer([
+ [
+ 0,
+ 1,
+ 2,
+ 3,
+ {
+ type: 'Feature',
+ properties: {index: 0},
+ geometry: {type: 'Point', coordinates: []}
+ },
+ {
+ type: 'Feature',
+ properties: {index: 0},
+ geometry: {type: 'Polygon', coordinates: []}
+ }
+ ],
+ {fields}
+ ]);
+
const geojsonLayers = findDefaultLayer(
{
fields,
label: 'what',
id: 'smoothie',
fieldPairs: [],
- allData: [
- [
- 0,
- 1,
- 2,
- 3,
- {
- type: 'Feature',
- properties: {index: 0},
- geometry: {type: 'Point', coordinates: []}
- },
- {
- type: 'Feature',
- properties: {index: 0},
- geometry: {type: 'Polygon', coordinates: []}
- }
- ]
- ]
+ dataContainer
},
KeplerGlLayers
);
@@ -661,8 +666,10 @@ test('layerUtils -> findDefaultLayer:GeojsonLayer.wkt', t => {
strokeColor: strokeColor2
});
+ const dataContainer = createDataContainer(rows, {fields});
+
const geojsonLayers = findDefaultLayer(
- {fields, id: dataId, label, fieldPairs: [], allData: rows},
+ {fields, id: dataId, label, fieldPairs: [], dataContainer},
KeplerGlLayers
);
@@ -673,6 +680,8 @@ test('layerUtils -> findDefaultLayer:GeojsonLayer.wkt', t => {
test('layerUtils -> findDefaultLayer:GeojsonWithStyle', t => {
const {fields, rows} = processGeojson(geoJsonWithStyle);
+ const dataContainer = createDataContainer(rows, {fields});
+
const geojsonLayers = findDefaultLayer(
{
fields,
@@ -680,7 +689,7 @@ test('layerUtils -> findDefaultLayer:GeojsonWithStyle', t => {
dataId: 'taro',
label: 'chubby prince',
fieldPairs: [],
- allData: rows
+ dataContainer
},
KeplerGlLayers
);
@@ -853,10 +862,10 @@ test('layerUtils -> getLayerHoverProp', t => {
[layer.id]: layer
};
+ const obj = layerData.data[0];
+
const mockHoverInfo = {
- object: {
- data: layerData[0]
- },
+ object: obj,
picked: true,
layer: {
props: {
@@ -876,9 +885,10 @@ test('layerUtils -> getLayerHoverProp', t => {
datasets: visState.datasets
};
+ const expectedDataset = visState.datasets[layer.config.dataId];
const expected = {
- data: layerData[0],
- fields: visState.datasets[layer.config.dataId].fields,
+ data: expectedDataset.dataContainer.row(obj.index),
+ fields: expectedDataset.fields,
fieldsToShow: visState.interactionConfig.tooltip.config.fieldsToShow[layer.config.dataId],
layer
};