-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
kepler-table.ts
627 lines (535 loc) · 16.9 KB
/
kepler-table.ts
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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
// Copyright (c) 2022 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, ALL_FIELD_TYPES, SCALE_TYPES} from '@kepler.gl/constants';
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,
FilterResult
} from 'utils/filter-utils';
import {maybeToDate, getSortingFunction} from 'utils/data-utils';
import {
getQuantileDomain,
getOrdinalDomain,
getLogDomain,
getLinearDomain
} from 'utils/data-scale-utils';
import {createDataContainer} from './data-container-utils';
import {RGBColor} from '@kepler.gl/types';
import {Layer} from '@kepler.gl/layers';
import {FieldDomain, Filter} from 'reducers/vis-state-updaters';
import {DataContainerInterface} from './data-container-interface';
import {ProtoDataset} from 'actions';
export type Field = {
analyzerType: string;
id?: string;
name: string;
displayName: string;
format: string;
type: string;
fieldIdx: number;
valueAccessor(v: {index: number}): any;
filterProps?: any;
metadata?: any;
};
export type GpuFilter = {
filterRange: number[][];
filterValueUpdateTriggers: any;
filterValueAccessor: (
dc: DataContainerInterface
) => (
getIndex?: (any) => number,
getData?: (dc_: DataContainerInterface, d: any, fieldIndex: number) => any
) => (d: any) => number;
};
export type FieldPair = {
defaultName: string;
pair: {
[key: string]: {
fieldIdx: number;
value: string;
};
};
suffix: string[];
};
export type FilterRecord = {
dynamicDomain: Filter[];
fixedDomain: Filter[];
cpu: Filter[];
gpu: Filter[];
};
export type FilterDatasetOpt = {
// only allow cpu filtering
cpuOnly?: boolean;
// ignore filter for domain calculation
ignoreDomain?: boolean;
};
// Unique identifier of each field
const FID_KEY = 'name';
class KeplerTable {
readonly id: string;
type?: string;
label: string;
color: RGBColor;
// fields and data
fields: Field[];
dataContainer: DataContainerInterface;
allIndexes: number[];
filteredIndex: number[];
filteredIdxCPU?: number[];
filteredIndexForDomain: number[];
fieldPairs: FieldPair[];
gpuFilter: GpuFilter;
filterRecord?: FilterRecord;
filterRecordCPU?: FilterRecord;
changedFilters?: any;
// table-injected metadata
sortColumn?: {
// column name: sorted idx
[key: string]: string; // ASCENDING | DESCENDING | UNSORT
};
sortOrder?: number[] | null;
pinnedColumns?: string[];
supportedFilterTypes?: string[] | null;
disableDataOperation?: boolean;
// table-injected metadata
metadata: object;
constructor({
info = {},
data,
color,
metadata,
supportedFilterTypes = null,
disableDataOperation = false
}: {
info?: ProtoDataset['info'];
data: ProtoDataset['data'];
color: RGBColor;
metadata?: ProtoDataset['metadata'];
supportedFilterTypes?: ProtoDataset['supportedFilterTypes'];
disableDataOperation?: ProtoDataset['disableDataOperation'];
}) {
// TODO - what to do if validation fails? Can kepler handle exceptions?
// const validatedData = validateInputData(data);
// if (!validatedData) {
// return this;
// }
// @ts-expect-error
const dataContainer = createDataContainer(data.rows, {fields: data.fields});
const datasetInfo = {
id: generateHashId(4),
label: 'new dataset',
type: '',
...info
};
const dataId = datasetInfo.id;
// @ts-expect-error
const fields: Field[] = data.fields.map((f, i) => ({
...f,
fieldIdx: i,
id: f.name,
displayName: f.displayName || f.name,
valueAccessor: getFieldValueAccessor(f, i, dataContainer)
}));
const allIndexes = dataContainer.getPlainIndex();
const defaultMetadata = {
id: datasetInfo.id,
// @ts-ignore
format: datasetInfo.format || '',
label: datasetInfo.label || ''
};
this.id = datasetInfo.id;
this.type = datasetInfo.type;
this.label = datasetInfo.label;
this.color = color;
this.metadata = {
...defaultMetadata,
...metadata
};
this.dataContainer = dataContainer;
this.allIndexes = allIndexes;
this.filteredIndex = allIndexes;
this.filteredIndexForDomain = allIndexes;
this.fieldPairs = findPointFieldPairs(fields);
this.fields = fields;
this.gpuFilter = getGpuFilterProps([], dataId, fields);
this.supportedFilterTypes = supportedFilterTypes;
this.disableDataOperation = disableDataOperation;
}
/**
* Get field
* @param columnName
*/
getColumnField(columnName: string): Field | undefined {
const field = this.fields.find(fd => fd[FID_KEY] === columnName);
this._assetField(columnName, field);
return field;
}
/**
* Get fieldIdx
* @param columnName
*/
getColumnFieldIdx(columnName: string): number {
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: string, rowIdx: number): any {
const field = this.getColumnField(columnName);
return field ? field.valueAccessor({index: rowIdx}) : null;
}
/**
* Updates existing field with a new object
* @param fieldIdx
* @param newField
*/
updateColumnField(fieldIdx: number, newField: Field): void {
this.fields = Object.assign([...this.fields], {[fieldIdx]: newField});
}
/**
* Update dataset color by custom color
* @param newColor
*/
updateTableColor(newColor: RGBColor): void {
this.color = newColor;
}
/**
* Save filterProps to field and retrieve it
* @param columnName
*/
getColumnFilterProps(columnName: string): Field['filterProps'] | null | undefined {
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: Filter[], layers: Layer[], opt?: FilterDatasetOpt): KeplerTable {
const {dataContainer, 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: 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, dataContainer)
};
}, {});
filterResult = filterDataByFilterTypes(
{dynamicDomainFilters, cpuFilters, filterFuncs},
dataContainer
);
}
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: Filter[], layers: Layer[]): KeplerTable {
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: Field): FieldDomain {
const {dataContainer} = 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(dataContainer, valueAccessor);
case ALL_FIELD_TYPES.boolean:
return {domain: [true, false]};
case ALL_FIELD_TYPES.string:
case ALL_FIELD_TYPES.date:
domain = getOrdinalDomain(dataContainer, valueAccessor);
return {domain};
case ALL_FIELD_TYPES.timestamp:
return getTimestampFieldDomain(dataContainer, valueAccessor);
default:
return {domain: getOrdinalDomain(dataContainer, valueAccessor)};
}
}
/**
* Get the domain of this column based on scale type
*/
getColumnLayerDomain(
field: Field,
scaleType: string
): number[] | string[] | [number, number] | null {
const {dataContainer, filteredIndexForDomain} = this;
if (!SCALE_TYPES[scaleType]) {
Console.error(`scale type ${scaleType} not supported`);
return null;
}
const {valueAccessor} = field;
const indexValueAccessor = i => valueAccessor({index: 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(dataContainer, 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: string, condition: any): void {
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
*/
export function findPointFieldPairs(fields: Field[]): FieldPair[] {
const allNames = fields.map(f => f.name.toLowerCase());
// get list of all fields with matching suffixes
const acc: FieldPair[] = [];
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;
}, acc);
}
/**
*
* @param dataset
* @param column
* @param mode
* @type
*/
export function sortDatasetByColumn(
dataset: KeplerTable,
column: string,
mode?: string
): KeplerTable {
const {allIndexes, fields, dataContainer} = 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) {
dataset.sortColumn = {};
dataset.sortOrder = null;
return dataset;
}
const sortFunction = sortBy === SORT_ORDER.ASCENDING ? ascending : descending;
const sortOrder = allIndexes
.slice()
.sort((a, b) =>
sortFunction(dataContainer.valueAt(a, fieldIndex), dataContainer.valueAt(b, fieldIndex))
);
dataset.sortColumn = {
[column]: sortBy
};
dataset.sortOrder = sortOrder;
return dataset;
}
export function pinTableColumns(dataset: KeplerTable, column: string): KeplerTable {
const field = dataset.getColumnField(column);
if (!field) {
return dataset;
}
let pinnedColumns;
if (Array.isArray(dataset.pinnedColumns) && dataset.pinnedColumns.includes(field.name)) {
// unpin it
pinnedColumns = dataset.pinnedColumns.filter(co => co !== field.name);
} else {
pinnedColumns = (dataset.pinnedColumns || []).concat(field.name);
}
// @ts-ignore
return copyTableAndUpdate(dataset, {pinnedColumns});
}
export function copyTable<T extends KeplerTable>(original: T): T {
return Object.assign(Object.create(Object.getPrototypeOf(original)), original);
}
/**
* @type
* @returns
*/
export function copyTableAndUpdate<T extends KeplerTable>(
original: T,
options: Partial<T> = {}
): T {
return Object.entries(options).reduce((acc, entry) => {
acc[entry[0]] = entry[1];
return acc;
}, copyTable(original));
}
export function getFieldValueAccessor<
F extends {
type?: Field['type'];
format?: Field['format'];
}
>(f: F, i: number, dc: DataContainerInterface) {
return maybeToDate.bind(
null,
// is time
f.type === ALL_FIELD_TYPES.timestamp,
i,
f.format || '',
dc
);
}
export default KeplerTable;