-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
filter-utils.ts
1300 lines (1139 loc) · 35 KB
/
filter-utils.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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2023 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 {ascending, extent, histogram as d3Histogram, ticks} from 'd3-array';
import keyMirror from 'keymirror';
import Console from 'global/console';
import get from 'lodash.get';
import isEqual from 'lodash.isequal';
import booleanWithin from '@turf/boolean-within';
import {point as turfPoint} from '@turf/helpers';
import {Decimal} from 'decimal.js';
import {
ALL_FIELD_TYPES,
FILTER_TYPES,
ANIMATION_WINDOW,
PLOT_TYPES,
LAYER_TYPES,
FILTER_VIEW_TYPES
} from '@kepler.gl/constants';
import {VisState} from '@kepler.gl/schemas';
import * as ScaleUtils from './data-scale-utils';
import {h3IsValid} from 'h3-js';
import {
Millisecond,
Entries,
Field,
ParsedFilter,
Filter,
FilterBase,
PolygonFilter,
FieldDomain,
TimeRangeFieldDomain,
HistogramBin,
Feature,
FeatureValue,
LineChart,
TimeRangeFilter,
RangeFieldDomain,
FilterDatasetOpt,
FilterRecord
} from '@kepler.gl/types';
import {DataContainerInterface} from './data-container-interface';
import {generateHashId, set, toArray} from './utils';
import {notNullorUndefined, timeToUnixMilli, unique} from './data-utils';
import {getCentroid} from './h3-utils';
export const durationSecond = 1000;
export const durationMinute = durationSecond * 60;
export const durationHour = durationMinute * 60;
export const durationDay = durationHour * 24;
export const durationWeek = durationDay * 7;
export const durationYear = durationDay * 365;
export type FilterResult = {
filteredIndexForDomain?: number[];
filteredIndex?: number[];
};
export type FilterChanged = {
// eslint-disable-next-line no-unused-vars
[key in keyof FilterRecord]: {
[key: string]: 'added' | 'deleted' | 'name_changed' | 'value_changed' | 'dataId_changed';
} | null;
};
export type dataValueAccessor = (data: {index: number}) => number | null;
export const TimestampStepMap = [
{max: 1, step: 0.05},
{max: 10, step: 0.1},
{max: 100, step: 1},
{max: 500, step: 5},
{max: 1000, step: 10},
{max: 5000, step: 50},
{max: Number.POSITIVE_INFINITY, step: 1000}
];
export const histogramBins = 30;
export const enlargedHistogramBins = 100;
export const FILTER_UPDATER_PROPS = keyMirror({
dataId: null,
name: null,
layerId: null
});
export const LIMITED_FILTER_EFFECT_PROPS = keyMirror({
[FILTER_UPDATER_PROPS.name]: null
});
/**
* Max number of filter value buffers that deck.gl provides
*/
const SupportedPlotType = {
[FILTER_TYPES.timeRange]: {
default: 'histogram',
[ALL_FIELD_TYPES.integer]: 'lineChart',
[ALL_FIELD_TYPES.real]: 'lineChart'
},
[FILTER_TYPES.range]: {
default: 'histogram',
[ALL_FIELD_TYPES.integer]: 'lineChart',
[ALL_FIELD_TYPES.real]: 'lineChart'
}
};
export const FILTER_COMPONENTS = {
[FILTER_TYPES.select]: 'SingleSelectFilter',
[FILTER_TYPES.multiSelect]: 'MultiSelectFilter',
[FILTER_TYPES.timeRange]: 'TimeRangeFilter',
[FILTER_TYPES.range]: 'RangeFilter',
[FILTER_TYPES.polygon]: 'PolygonFilter'
};
export const DEFAULT_FILTER_STRUCTURE = {
dataId: [], // [string]
freeze: false,
id: null,
enabled: true,
// time range filter specific
fixedDomain: false,
view: FILTER_VIEW_TYPES.side,
isAnimating: false,
animationWindow: ANIMATION_WINDOW.free,
speed: 1,
// field specific
name: [], // string
type: null,
fieldIdx: [], // [integer]
domain: null,
value: null,
// plot
plotType: PLOT_TYPES.histogram,
yAxis: null,
interval: null,
// mode
gpu: false
};
export const FILTER_ID_LENGTH = 4;
export const LAYER_FILTERS = [FILTER_TYPES.polygon];
/**
* Generates a filter with a dataset id as dataId
*/
export function getDefaultFilter({
dataId,
id
}: {
dataId?: string | null | string[];
id?: string;
} = {}): FilterBase<LineChart> {
return {
...DEFAULT_FILTER_STRUCTURE,
// store it as dataId and it could be one or many
dataId: dataId ? toArray(dataId) : [],
id: id || generateHashId(FILTER_ID_LENGTH)
};
}
/**
* Check if a filter is valid based on the given dataId
* @param filter to validate
* @param datasetId id to validate filter against
* @return true if a filter is valid, false otherwise
*/
export function shouldApplyFilter(filter: Filter, datasetId: string): boolean {
const dataIds = toArray(filter.dataId);
return dataIds.includes(datasetId) && filter.value !== null;
}
interface KeplerTableModel<K, L> {
id: string;
getColumnFieldIdx(columnName: string): number;
filterTable(filters: Filter[], layers: L[], opt?: FilterDatasetOpt): K;
getColumnFilterProps(columnName: string): Field['filterProps'] | null | undefined;
dataContainer: DataContainerInterface;
filterTableCPU(filters: Filter[], layers: L[]): K;
}
/**
* Validates and modifies polygon filter structure
* @param dataset
* @param filter
* @param layers
* @return - {filter, dataset}
*/
export function validatePolygonFilter<K extends KeplerTableModel<K, L>, L extends {id: string}>(
dataset: K,
filter: PolygonFilter,
layers: L[]
): {filter: PolygonFilter | null; dataset: K} {
const failed = {dataset, filter: null};
const {value, layerId, type, dataId} = filter;
if (!layerId || !isValidFilterValue(type, value)) {
return failed;
}
const isValidDataset = dataId.includes(dataset.id);
if (!isValidDataset) {
return failed;
}
const layer = layers.find(l => layerId.includes(l.id));
if (!layer) {
return failed;
}
return {
filter: {
...filter,
freeze: true,
fieldIdx: []
},
dataset
};
}
/**
* Custom filter validators
*/
const filterValidators = {
[FILTER_TYPES.polygon]: validatePolygonFilter
};
/**
* Default validate filter function
* @param dataset
* @param filter
* @return - {filter, dataset}
*/
export function validateFilter<K extends KeplerTableModel<K, L>, L>(
dataset: K,
filter: ParsedFilter
): {filter: Filter | null; dataset: K} {
// match filter.dataId
const failed = {dataset, filter: null};
const filterDataId = toArray(filter.dataId);
const filterDatasetIndex = filterDataId.indexOf(dataset.id);
if (filterDatasetIndex < 0 || !toArray(filter.name)[filterDatasetIndex]) {
// the current filter is not mapped against the current dataset
return failed;
}
const initializeFilter: Filter = {
...getDefaultFilter({dataId: filter.dataId}),
...filter,
dataId: filterDataId,
name: toArray(filter.name)
};
const fieldName = initializeFilter.name[filterDatasetIndex];
const {filter: updatedFilter, dataset: updatedDataset} = applyFilterFieldName(
initializeFilter,
dataset,
fieldName,
filterDatasetIndex,
{mergeDomain: true}
);
if (!updatedFilter) {
return failed;
}
updatedFilter.value = adjustValueToFilterDomain(filter.value, updatedFilter);
updatedFilter.view = filter.view ?? updatedFilter.view;
if (updatedFilter.value === null) {
// cannot adjust saved value to filter
return failed;
}
return {
filter: validateFilterYAxis(updatedFilter, updatedDataset),
dataset: updatedDataset
};
}
/**
* Validate saved filter config with new data,
* calculate domain and fieldIdx based new fields and data
*
* @param dataset
* @param filter - filter to be validate
* @param layers - layers
* @return validated filter
*/
export function validateFilterWithData<K extends KeplerTableModel<K, L>, L>(
dataset: K,
filter: ParsedFilter,
layers: L[]
): {filter: Filter; dataset: K} {
return filter.type && filterValidators.hasOwnProperty(filter.type)
? filterValidators[filter.type](dataset, filter, layers)
: validateFilter(dataset, filter);
}
/**
* Validate YAxis
* @param filter
* @param dataset
* @return {*}
*/
function validateFilterYAxis(filter, dataset) {
// TODO: validate yAxis against other datasets
const {fields} = dataset;
const {yAxis} = filter;
// TODO: validate yAxis against other datasets
if (yAxis) {
const matchedAxis = fields.find(({name, type}) => name === yAxis.name && type === yAxis.type);
filter = matchedAxis
? {
...filter,
yAxis: matchedAxis,
...getFilterPlot({...filter, yAxis: matchedAxis}, dataset)
}
: filter;
}
return filter;
}
/**
* Get default filter prop based on field type
*
* @param field
* @param fieldDomain
* @returns default filter
*/
export function getFilterProps(
field: Field,
fieldDomain: FieldDomain
): Partial<Filter> & {fieldType: string} {
const filterProps = {
...fieldDomain,
fieldType: field.type,
view: FILTER_VIEW_TYPES.side
};
switch (field.type) {
case ALL_FIELD_TYPES.real:
case ALL_FIELD_TYPES.integer:
return {
...filterProps,
value: fieldDomain.domain,
type: FILTER_TYPES.range,
// @ts-expect-error
typeOptions: [FILTER_TYPES.range],
gpu: true
};
case ALL_FIELD_TYPES.boolean:
// @ts-expect-error
return {
...filterProps,
type: FILTER_TYPES.select,
value: true,
gpu: false
};
case ALL_FIELD_TYPES.string:
case ALL_FIELD_TYPES.date:
// @ts-expect-error
return {
...filterProps,
type: FILTER_TYPES.multiSelect,
value: [],
gpu: false
};
case ALL_FIELD_TYPES.timestamp:
// @ts-expect-error
return {
...filterProps,
type: FILTER_TYPES.timeRange,
view: FILTER_VIEW_TYPES.enlarged,
fixedDomain: true,
value: filterProps.domain,
gpu: true
};
default:
// @ts-expect-error
return {};
}
}
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);
return pos.every(Number.isFinite) && isInPolygon(pos, filter.value);
};
case LAYER_TYPES.arc:
case LAYER_TYPES.line:
return data => {
const pos = getPosition(data);
return (
pos.every(Number.isFinite) &&
[
[pos[0], pos[1]],
[pos[3], pos[4]]
].every(point => isInPolygon(point, filter.value))
);
};
case LAYER_TYPES.hexagonId:
if (layer.dataToFeature && layer.dataToFeature.centroids) {
return data => {
// null or getCentroid({id})
const centroid = layer.dataToFeature.centroids[data.index];
return centroid && isInPolygon(centroid, filter.value);
};
}
return data => {
const id = getPosition(data);
if (!h3IsValid(id)) {
return false;
}
const pos = getCentroid({id});
return pos.every(Number.isFinite) && isInPolygon(pos, filter.value);
};
default:
return () => true;
}
};
/**
* @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.
*/
type filterFunction = (data: {index: number}) => boolean;
/**
* @param field dataset Field
* @param dataId Dataset id
* @param filter Filter object
* @param layers list of layers to filter upon
* @param dataContainer Data container
* @return filterFunction
*/
/* eslint-disable complexity */
export function getFilterFunction<L extends {config: {dataId: string | null}; id: string}>(
field: Field | null,
dataId: string,
filter: Filter,
layers: L[],
dataContainer: DataContainerInterface
): filterFunction {
// field could be null in polygon filter
const valueAccessor = field ? field.valueAccessor : data => null;
const defaultFunc = d => true;
if (filter.enabled === false) {
return defaultFunc;
}
switch (filter.type) {
case FILTER_TYPES.range:
return data => isInRange(valueAccessor(data), filter.value);
case FILTER_TYPES.multiSelect:
return data => filter.value.includes(valueAccessor(data));
case FILTER_TYPES.select:
return data => valueAccessor(data) === filter.value;
case FILTER_TYPES.timeRange:
if (!field) {
return defaultFunc;
}
const mappedValue = get(field, ['filterProps', 'mappedValue']);
const accessor = Array.isArray(mappedValue)
? data => mappedValue[data.index]
: data => timeToUnixMilli(valueAccessor(data), field.format);
return data => isInRange(accessor(data), filter.value);
case FILTER_TYPES.polygon:
if (!layers || !layers.length || !filter.layerId) {
return defaultFunc;
}
const layerFilterFunctions = filter.layerId
.map(id => layers.find(l => l.id === id))
.filter(l => l && l.config.dataId === dataId)
.map(layer => getPolygonFilterFunctor(layer, filter, dataContainer));
return data => layerFilterFunctions.every(filterFunc => filterFunc(data));
default:
return defaultFunc;
}
}
export function updateFilterDataId(dataId: string | string[]): FilterBase<LineChart> {
return getDefaultFilter({dataId});
}
export function filterDataByFilterTypes(
{
dynamicDomainFilters,
cpuFilters,
filterFuncs
}: {
dynamicDomainFilters: Filter[] | null;
cpuFilters: Filter[] | null;
filterFuncs: {
[key: string]: filterFunction;
};
},
dataContainer: DataContainerInterface
): FilterResult {
const filteredIndexForDomain: number[] = [];
const filteredIndex: number[] = [];
const filterContext = {index: -1, dataContainer};
const filterFuncCaller = (filter: Filter) => filterFuncs[filter.id](filterContext);
const numRows = dataContainer.numRows();
for (let i = 0; i < numRows; ++i) {
filterContext.index = i;
const matchForDomain = dynamicDomainFilters && dynamicDomainFilters.every(filterFuncCaller);
if (matchForDomain) {
filteredIndexForDomain.push(filterContext.index);
}
const matchForRender = cpuFilters && cpuFilters.every(filterFuncCaller);
if (matchForRender) {
filteredIndex.push(filterContext.index);
}
}
return {
...(dynamicDomainFilters ? {filteredIndexForDomain} : {}),
...(cpuFilters ? {filteredIndex} : {})
};
}
/**
* Get a record of filters based on domain type and gpu / cpu
*/
export function getFilterRecord(
dataId: string,
filters: Filter[],
opt: FilterDatasetOpt = {}
): FilterRecord {
const filterRecord: FilterRecord = {
dynamicDomain: [],
fixedDomain: [],
cpu: [],
gpu: []
};
filters.forEach(f => {
if (isValidFilterValue(f.type, f.value) && toArray(f.dataId).includes(dataId)) {
(f.fixedDomain || opt.ignoreDomain
? filterRecord.fixedDomain
: filterRecord.dynamicDomain
).push(f);
(f.gpu && !opt.cpuOnly ? filterRecord.gpu : filterRecord.cpu).push(f);
}
});
return filterRecord;
}
/**
* Compare filter records to get what has changed
*/
export function diffFilters(
filterRecord: FilterRecord,
oldFilterRecord: FilterRecord | {} = {}
): FilterChanged {
let filterChanged: Partial<FilterChanged> = {};
(Object.entries(filterRecord) as Entries<FilterRecord>).forEach(([record, items]) => {
items.forEach(filter => {
const oldFilter: Filter = (oldFilterRecord[record] || []).find(
(f: Filter) => f.id === filter.id
);
if (!oldFilter) {
// added
filterChanged = set([record, filter.id], 'added', filterChanged);
} else {
// check what has changed
['name', 'value', 'dataId'].forEach(prop => {
if (filter[prop] !== oldFilter[prop]) {
filterChanged = set([record, filter.id], `${prop}_changed`, filterChanged);
}
});
}
});
(oldFilterRecord[record] || []).forEach((oldFilter: Filter) => {
// deleted
if (!items.find(f => f.id === oldFilter.id)) {
filterChanged = set([record, oldFilter.id], 'deleted', filterChanged);
}
});
});
return {...{dynamicDomain: null, fixedDomain: null, cpu: null, gpu: null}, ...filterChanged};
}
/**
* Call by parsing filters from URL
* Check if value of filter within filter domain, if not adjust it to match
* filter domain
*
* @returns value - adjusted value to match filter or null to remove filter
*/
// eslint-disable-next-line complexity
export function adjustValueToFilterDomain(value: Filter['value'], {domain, type}) {
if (!type) {
return false;
}
// if the current filter is a polygon it will not have any domain
// all other filter types require domain
if (type !== FILTER_TYPES.polygon && !domain) {
return false;
}
switch (type) {
case FILTER_TYPES.range:
case FILTER_TYPES.timeRange:
if (!Array.isArray(value) || value.length !== 2) {
return domain.map(d => d);
}
return value.map((d, i) => (notNullorUndefined(d) && isInRange(d, domain) ? d : domain[i]));
case FILTER_TYPES.multiSelect:
if (!Array.isArray(value)) {
return [];
}
const filteredValue = value.filter(d => domain.includes(d));
return filteredValue.length ? filteredValue : [];
case FILTER_TYPES.select:
return domain.includes(value) ? value : true;
case FILTER_TYPES.polygon:
return value;
default:
return null;
}
}
/* eslint-enable complexity */
/**
* Calculate numeric domain and suitable step
*/
export function getNumericFieldDomain(
dataContainer: DataContainerInterface,
valueAccessor: dataValueAccessor
): RangeFieldDomain {
let domain: [number, number] = [0, 1];
let step = 0.1;
const mappedValue = dataContainer.mapIndex(valueAccessor);
if (dataContainer.numRows() > 1) {
domain = ScaleUtils.getLinearDomain(mappedValue);
const diff = domain[1] - domain[0];
// in case equal domain, [96, 96], which will break quantize scale
if (!diff) {
domain[1] = domain[0] + 1;
}
step = getNumericStepSize(diff) || step;
domain[0] = formatNumberByStep(domain[0], step, 'floor');
domain[1] = formatNumberByStep(domain[1], step, 'ceil');
}
const {histogram, enlargedHistogram} = getHistogram(domain, mappedValue);
return {domain, step, histogram, enlargedHistogram};
}
/**
* Calculate step size for range and timerange filter
*/
export function getNumericStepSize(diff: number): number {
diff = Math.abs(diff);
if (diff > 100) {
return 1;
} else if (diff > 3) {
return 0.01;
} else if (diff > 1) {
return 0.001;
}
// Try to get at least 1000 steps - and keep the step size below that of
// the (diff > 1) case.
const x = diff / 1000;
// Find the exponent and truncate to 10 to the power of that exponent
const exponentialForm = x.toExponential();
const exponent = parseFloat(exponentialForm.split('e')[1]);
// Getting ready for node 12
// this is why we need decimal.js
// Math.pow(10, -5) = 0.000009999999999999999
// the above result shows in browser and node 10
// node 12 behaves correctly
return new Decimal(10).pow(exponent).toNumber();
}
/**
* Calculate timestamp domain and suitable step
*/
export function getTimestampFieldDomain(
dataContainer: DataContainerInterface,
valueAccessor: dataValueAccessor
): TimeRangeFieldDomain {
// to avoid converting string format time to epoch
// every time we compare we store a value mapped to int in filter domain
const mappedValue = dataContainer.mapIndex(valueAccessor);
const domain = ScaleUtils.getLinearDomain(mappedValue);
const defaultTimeFormat = getTimeWidgetTitleFormatter(domain);
let step = 0.01;
const diff = domain[1] - domain[0];
// in case equal timestamp add 1 second padding to prevent break
if (!diff) {
domain[1] = domain[0] + 1000;
}
const entry = TimestampStepMap.find(f => f.max >= diff);
if (entry) {
step = entry.step;
}
const {histogram, enlargedHistogram} = getHistogram(domain, mappedValue);
return {
domain,
step,
mappedValue,
histogram,
enlargedHistogram,
defaultTimeFormat
};
}
export function histogramConstruct(
domain: [number, number],
mappedValue: (Millisecond | number)[],
bins: number
): HistogramBin[] {
return d3Histogram()
.thresholds(ticks(domain[0], domain[1], bins))
.domain(domain)(mappedValue)
.map(bin => ({
count: bin.length,
bin,
x0: bin.x0,
x1: bin.x1
}));
}
/**
* Calculate histogram from domain and array of values
*/
export function getHistogram(
domain: [number, number],
mappedValue: (Millisecond | number)[]
): {histogram: HistogramBin[]; enlargedHistogram: HistogramBin[]} {
const histogram = histogramConstruct(domain, mappedValue, histogramBins);
const enlargedHistogram = histogramConstruct(domain, mappedValue, enlargedHistogramBins);
return {histogram, enlargedHistogram};
}
/**
* round number based on step
*
* @param {Number} val
* @param {Number} step
* @param {string} bound
* @returns {Number} rounded number
*/
export function formatNumberByStep(val: number, step: number, bound: 'floor' | 'ceil'): number {
if (bound === 'floor') {
return Math.floor(val * (1 / step)) / (1 / step);
}
return Math.ceil(val * (1 / step)) / (1 / step);
}
export function isInRange(val: any, domain: number[]): boolean {
if (!Array.isArray(domain)) {
return false;
}
return val >= domain[0] && val <= domain[1];
}
/**
* Determines whether a point is within the provided polygon
*
* @param point as input search [lat, lng]
* @param polygon Points must be within these (Multi)Polygon(s)
* @return {boolean}
*/
export function isInPolygon(point: number[], polygon: any): boolean {
return booleanWithin(turfPoint(point), polygon);
}
export function getTimeWidgetTitleFormatter(domain: [number, number]): string | null {
if (!isValidTimeDomain(domain)) {
return null;
}
const diff = domain[1] - domain[0];
// Local aware formats
// https://momentjs.com/docs/#/parsing/string-format
return diff > durationYear ? 'L' : diff > durationDay ? 'L LT' : 'L LTS';
}
/**
* Sanity check on filters to prepare for save
* @type {typeof import('./filter-utils').isFilterValidToSave}
*/
export function isFilterValidToSave(filter: any): boolean {
return (
filter?.type && Array.isArray(filter?.name) && (filter?.name.length || filter?.layerId.length)
);
}
/**
* Sanity check on filters to prepare for save
* @type {typeof import('./filter-utils').isValidFilterValue}
*/
/* eslint-disable complexity */
export function isValidFilterValue(type: string | null, value: any): boolean {
if (!type) {
return false;
}
switch (type) {
case FILTER_TYPES.select:
return value === true || value === false;
case FILTER_TYPES.range:
case FILTER_TYPES.timeRange:
return Array.isArray(value) && value.every(v => v !== null && !isNaN(v));
case FILTER_TYPES.multiSelect:
return Array.isArray(value) && Boolean(value.length);
case FILTER_TYPES.input:
return Boolean(value.length);
case FILTER_TYPES.polygon:
const coordinates = get(value, ['geometry', 'coordinates']);
return Boolean(value && value.id && coordinates);
default:
return true;
}
}
export function getColumnFilterProps<K extends KeplerTableModel<K, L>, L>(
filter: Filter,
dataset: K
): {lineChart: LineChart; yAxs: Field} | {} {
if (filter.plotType === PLOT_TYPES.histogram || !filter.yAxis) {
// histogram should be calculated when create filter
return {};
}
const {mappedValue = []} = filter;
const {yAxis} = filter;
const fieldIdx = dataset.getColumnFieldIdx(yAxis.name);
if (fieldIdx < 0) {
Console.warn(`yAxis ${yAxis.name} does not exist in dataset`);
return {lineChart: {}, yAxis};
}
// return lineChart
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));
const yDomain = extent(series, d => d.y);
const xDomain = [series[0].x, series[series.length - 1].x];
return {lineChart: {series, yDomain, xDomain}, yAxis};
}
export function getDefaultFilterPlotType(filter: Filter): string | null {
const filterPlotTypes: typeof SupportedPlotType[keyof typeof SupportedPlotType] | null =
filter.type && SupportedPlotType[filter.type];
if (!filterPlotTypes) {
return null;
}
if (!filter.yAxis) {
return filterPlotTypes.default;
}
return filterPlotTypes[filter.yAxis.type] || null;
}
/**
*
* @param datasetIds list of dataset ids to be filtered
* @param datasets all datasets
* @param filters all filters to be applied to datasets
* @return datasets - new updated datasets
*/
export function applyFiltersToDatasets<
K extends KeplerTableModel<K, L>,
L extends {config: {dataId: string | null}}
>(
datasetIds: string[],
datasets: {[id: string]: K},
filters: Filter[],
layers?: L[]
): {[id: string]: K} {
const dataIds = toArray(datasetIds);
return dataIds.reduce((acc, dataId) => {
const layersToFilter = (layers || []).filter(l => l.config.dataId === dataId);
const appliedFilters = filters.filter(d => shouldApplyFilter(d, dataId));
const table = datasets[dataId];
return {
...acc,
[dataId]: table.filterTable(appliedFilters, layersToFilter, {})
};
}, datasets);
}
/**
* Applies a new field name value to fielter and update both filter and dataset
* @param filter - to be applied the new field name on
* @param dataset - dataset the field belongs to
* @param fieldName - field.name
* @param filterDatasetIndex - field.name
* @param option
* @return - {filter, datasets}
*/
export function applyFilterFieldName<K extends KeplerTableModel<K, L>, L>(
filter: Filter,
dataset: K,
fieldName: string,
filterDatasetIndex = 0,
option?: {mergeDomain: boolean}
): {
filter: Filter | null;
dataset: K;
} {
// using filterDatasetIndex we can filter only the specified dataset
const mergeDomain = option && option.hasOwnProperty('mergeDomain') ? option.mergeDomain : false;
const fieldIndex = dataset.getColumnFieldIdx(fieldName);
// if no field with same name is found, move to the next datasets
if (fieldIndex === -1) {
// throw new Error(`fieldIndex not found. Dataset must contain a property with name: ${fieldName}`);
return {filter: null, dataset};
}