-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
kepler-table.js
467 lines (395 loc) · 12.9 KB
/
kepler-table.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
// 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 {console as Console} from 'global/console';
import {TRIP_POINT_FIELDS, SORT_ORDER} from 'constants/default-settings';
import {ascending, descending} from 'd3-array';
// import {validateInputData} from 'processors/data-processor';
import {generateHashId} from 'utils/utils';
import {getGpuFilterProps, getDatasetFieldIndexForFilter} from 'utils/gpu-filter-utils';
import {
getFilterProps,
getFilterRecord,
diffFilters,
getFilterFunction,
filterDataByFilterTypes,
getNumericFieldDomain,
getTimestampFieldDomain
} from 'utils/filter-utils';
import {maybeToDate, getSortingFunction} from 'utils/data-utils';
import {
getQuantileDomain,
getOrdinalDomain,
getLogDomain,
getLinearDomain
} from 'utils/data-scale-utils';
import {ALL_FIELD_TYPES, SCALE_TYPES} from 'constants/default-settings';
// Unique identifier of each field
const FID_KEY = 'name';
/** @typedef {import('./kepler-table').KeplerTable} KeplerTableClass} */
/**
* @type {KeplerTableClass}
*/
class KeplerTable {
constructor({info = {}, data, color, metadata}) {
// TODO - what to do if validation fails? Can kepler handle exceptions?
// const validatedData = validateInputData(data);
// if (!validatedData) {
// return this;
// }
const allData = data.rows;
const datasetInfo = {
id: generateHashId(4),
label: 'new dataset',
...(info || {})
};
const dataId = datasetInfo.id;
const fields = data.fields.map((f, i) => ({
...f,
fieldIdx: i,
id: f.name,
displayName: f.displayName || f.name,
valueAccessor: maybeToDate.bind(
null,
// is time
f.type === ALL_FIELD_TYPES.timestamp,
i,
f.format
)
}));
const allIndexes = allData.map((_, i) => i);
this.id = datasetInfo.id;
this.label = datasetInfo.label;
this.color = color;
this.metadata = {
...metadata,
id: datasetInfo.id,
label: datasetInfo.label
};
this.allData = allData;
this.allIndexes = allIndexes;
this.filteredIndex = allIndexes;
this.filteredIndexForDomain = allIndexes;
this.fieldPairs = findPointFieldPairs(fields);
this.fields = fields;
this.gpuFilter = getGpuFilterProps([], dataId, fields);
}
/**
* Get field
* @param columnName
*/
getColumnField(columnName) {
const field = this.fields.find(fd => fd[FID_KEY] === columnName);
this._assetField(columnName, field);
return field;
}
/**
* Get fieldIdx
* @param columnName
*/
getColumnFieldIdx(columnName) {
const fieldIdx = this.fields.findIndex(fd => fd[FID_KEY] === columnName);
this._assetField(columnName, Boolean(fieldIdx > -1));
return fieldIdx;
}
/**
* Get the value of a cell
*/
getValue(columnName, rowIdx) {
const field = this.getColumnField(columnName);
return field ? field.valueAccessor(this.allData[rowIdx]) : null;
}
/**
* Updates existing field with a new object
* @param fieldIdx
* @param newField
*/
updateColumnField(fieldIdx, newField) {
this.fields = Object.assign([...this.fields], {[fieldIdx]: newField});
}
/**
* Save filterProps to field and retrieve it
* @param {string} columnName
*/
getColumnFilterProps(columnName) {
const fieldIdx = this.getColumnFieldIdx(columnName);
if (fieldIdx < 0) {
return null;
}
const field = this.fields[fieldIdx];
if (field.hasOwnProperty('filterProps')) {
return field.filterProps;
}
const fieldDomain = this.getColumnFilterDomain(field);
if (!fieldDomain) {
return null;
}
const filterProps = getFilterProps(field, fieldDomain);
const newField = {
...field,
filterProps
};
this.updateColumnField(fieldIdx, newField);
return filterProps;
}
/**
*
* 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;
// if there is no filters
const filterRecord = getFilterRecord(dataId, filters, opt || {});
this.filterRecord = filterRecord;
this.gpuFilter = getGpuFilterProps(filters, dataId, fields);
// const newDataset = set(['filterRecord'], filterRecord, dataset);
if (!filters.length) {
this.filteredIndex = this.allIndexes;
this.filteredIndexForDomain = this.allIndexes;
return this;
}
this.changedFilters = diffFilters(filterRecord, oldFilterRecord);
// generate 2 sets of filter result
// filteredIndex used to calculate layer data
// filteredIndexForDomain used to calculate layer Domain
const shouldCalDomain = Boolean(this.changedFilters.dynamicDomain);
const shouldCalIndex = Boolean(this.changedFilters.cpu);
let filterResult = {};
if (shouldCalDomain || shouldCalIndex) {
const dynamicDomainFilters = shouldCalDomain ? filterRecord.dynamicDomain : null;
const cpuFilters = shouldCalIndex ? filterRecord.cpu : null;
const filterFuncs = filters.reduce((acc, filter) => {
const fieldIndex = getDatasetFieldIndexForFilter(this.id, filter);
const field = fieldIndex !== -1 ? fields[fieldIndex] : null;
return {
...acc,
[filter.id]: getFilterFunction(field, this.id, filter, layers)
};
}, {});
filterResult = filterDataByFilterTypes(
{dynamicDomainFilters, cpuFilters, filterFuncs},
allData
);
}
this.filteredIndex = filterResult.filteredIndex || this.filteredIndex;
this.filteredIndexForDomain =
filterResult.filteredIndexForDomain || this.filteredIndexForDomain;
return this;
}
/**
* Apply filters to a dataset all on CPU, assign to `filteredIdxCPU`, `filterRecordCPU`
* @param filters
* @param layers
*/
filterTableCPU(filters, layers) {
const opt = {
cpuOnly: true,
ignoreDomain: true
};
// no filter
if (!filters.length) {
this.filteredIdxCPU = this.allIndexes;
this.filterRecordCPU = getFilterRecord(this.id, filters, opt);
return this;
}
// no gpu filter
if (!filters.find(f => f.gpu)) {
this.filteredIdxCPU = this.filteredIndex;
this.filterRecordCPU = getFilterRecord(this.id, filters, opt);
return this;
}
// make a copy for cpu filtering
const copied = copyTable(this);
copied.filterRecord = this.filterRecordCPU;
copied.filteredIndex = this.filteredIdxCPU || [];
const filtered = copied.filterTable(filters, layers, opt);
this.filteredIdxCPU = filtered.filteredIndex;
this.filterRecordCPU = filtered.filterRecord;
return this;
}
/**
* Calculate field domain based on field type and data
* for Filter
*/
getColumnFilterDomain(field) {
const {allData} = this;
const {valueAccessor} = field;
let domain;
switch (field.type) {
case ALL_FIELD_TYPES.real:
case ALL_FIELD_TYPES.integer:
// calculate domain and step
return getNumericFieldDomain(allData, valueAccessor);
case ALL_FIELD_TYPES.boolean:
return {domain: [true, false]};
case ALL_FIELD_TYPES.string:
case ALL_FIELD_TYPES.date:
domain = getOrdinalDomain(allData, valueAccessor);
return {domain};
case ALL_FIELD_TYPES.timestamp:
return getTimestampFieldDomain(allData, valueAccessor);
default:
return {domain: getOrdinalDomain(allData, valueAccessor)};
}
}
/**
* Get the domain of this column based on scale type
*/
getColumnLayerDomain(field, scaleType) {
const {allData, filteredIndexForDomain} = this;
if (!SCALE_TYPES[scaleType]) {
Console.error(`scale type ${scaleType} not supported`);
return null;
}
const {valueAccessor} = field;
const indexValueAccessor = i => valueAccessor(allData[i]);
const sortFunction = getSortingFunction(field.type);
switch (scaleType) {
case SCALE_TYPES.ordinal:
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);
case SCALE_TYPES.quantile:
return getQuantileDomain(filteredIndexForDomain, indexValueAccessor, sortFunction);
case SCALE_TYPES.log:
return getLogDomain(filteredIndexForDomain, indexValueAccessor);
case SCALE_TYPES.quantize:
case SCALE_TYPES.linear:
case SCALE_TYPES.sqrt:
default:
return getLinearDomain(filteredIndexForDomain, indexValueAccessor);
}
}
/**
* Get a sample of rows to calculate layer boundaries
*/
// getSampleData(rows)
/**
* Parse cell value based on column type and return a string representation
* Value the field value, type the field type
*/
// parseFieldValue(value, type)
// sortDatasetByColumn()
/**
* Assert whether field exist
* @param fieldName
* @param condition
*/
_assetField(fieldName, condition) {
if (!condition) {
Console.error(`${fieldName} doesnt exist in dataset ${this.id}`);
}
}
}
// HELPER FUNCTIONS (MAINLY EXPORTED FOR TEST...)
export function removeSuffixAndDelimiters(layerName, suffix) {
return layerName
.replace(new RegExp(suffix, 'ig'), '')
.replace(/[_,.]+/g, ' ')
.trim();
}
/**
* Find point fields pairs from fields
*
* @param fields
* @returns found point fields
* @type {typeof import('./kepler-table').findPointFieldPairs}
*/
export function findPointFieldPairs(fields) {
const allNames = fields.map(f => f.name.toLowerCase());
// get list of all fields with matching suffixes
return allNames.reduce((carry, fieldName, idx) => {
// This search for pairs will early exit if found.
for (const suffixPair of TRIP_POINT_FIELDS) {
// match first suffix```
if (fieldName.endsWith(suffixPair[0])) {
// match second suffix
const otherPattern = new RegExp(`${suffixPair[0]}\$`);
const partner = fieldName.replace(otherPattern, suffixPair[1]);
const partnerIdx = allNames.findIndex(d => d === partner);
if (partnerIdx > -1) {
const defaultName = removeSuffixAndDelimiters(fieldName, suffixPair[0]);
carry.push({
defaultName,
pair: {
lat: {
fieldIdx: idx,
value: fields[idx].name
},
lng: {
fieldIdx: partnerIdx,
value: fields[partnerIdx].name
}
},
suffix: suffixPair
});
return carry;
}
}
}
return carry;
}, []);
}
/**
*
* @param dataset
* @param column
* @param mode
* @type {typeof import('./kepler-table').sortDatasetByColumn}
*/
export function sortDatasetByColumn(dataset, column, mode) {
const {allIndexes, fields, allData} = dataset;
const fieldIndex = fields.findIndex(f => f.name === column);
if (fieldIndex < 0) {
return dataset;
}
const sortBy = SORT_ORDER[mode] || SORT_ORDER.ASCENDING;
if (sortBy === SORT_ORDER.UNSORT) {
return {
...dataset,
sortColumn: {},
sortOrder: null
};
}
const sortFunction = sortBy === SORT_ORDER.ASCENDING ? ascending : descending;
const sortOrder = allIndexes
.slice()
.sort((a, b) => sortFunction(allData[a][fieldIndex], allData[b][fieldIndex]));
return {
...dataset,
sortColumn: {
[column]: sortBy
},
sortOrder
};
}
export function copyTable(original) {
return Object.assign(Object.create(Object.getPrototypeOf(original)), original);
}
export function copyTableAndUpdate(original, options = {}) {
return Object.entries(options).reduce((acc, entry) => {
acc[entry[0]] = entry[1];
return acc;
}, copyTable(original));
}
export default KeplerTable;