-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
data-processor.ts
456 lines (420 loc) · 14.1 KB
/
data-processor.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
// SPDX-License-Identifier: MIT
// Copyright contributors to the kepler.gl project
import * as arrow from 'apache-arrow';
import {csvParseRows} from 'd3-dsv';
import {DATA_TYPES as AnalyzerDATA_TYPES} from 'type-analyzer';
import normalize from '@mapbox/geojson-normalize';
import {ALL_FIELD_TYPES, DATASET_FORMATS, GUIDES_FILE_FORMAT_DOC} from '@kepler.gl/constants';
import {ProcessorResult, Field} from '@kepler.gl/types';
import {
arrowDataTypeToAnalyzerDataType,
arrowDataTypeToFieldType,
notNullorUndefined,
hasOwnProperty,
isPlainObject,
analyzerTypeToFieldType,
getSampleForTypeAnalyze,
getFieldsFromData,
toArray
} from '@kepler.gl/utils';
import {KeplerGlSchema, ParsedDataset, SavedMap, LoadedMap} from '@kepler.gl/schemas';
import {Feature} from '@nebula.gl/edit-modes';
// if any of these value occurs in csv, parse it to null;
// const CSV_NULLS = ['', 'null', 'NULL', 'Null', 'NaN', '/N'];
// matches empty string
export const CSV_NULLS = /^(null|NULL|Null|NaN|\/N||)$/;
function tryParseJsonString(str) {
try {
return JSON.parse(str);
} catch (e) {
return null;
}
}
export const PARSE_FIELD_VALUE_FROM_STRING = {
[ALL_FIELD_TYPES.boolean]: {
valid: (d: unknown): boolean => typeof d === 'boolean',
parse: (d: unknown): boolean => d === 'true' || d === 'True' || d === 'TRUE' || d === '1'
},
[ALL_FIELD_TYPES.integer]: {
// @ts-ignore
valid: (d: unknown): boolean => parseInt(d, 10) === d,
// @ts-ignore
parse: (d: unknown): number => parseInt(d, 10)
},
[ALL_FIELD_TYPES.timestamp]: {
valid: (d: unknown, field: Field): boolean =>
['x', 'X'].includes(field.format) ? typeof d === 'number' : typeof d === 'string',
parse: (d: any, field: Field) => (['x', 'X'].includes(field.format) ? Number(d) : d)
},
[ALL_FIELD_TYPES.real]: {
// @ts-ignore
valid: (d: unknown): boolean => parseFloat(d) === d,
// Note this will result in NaN for some string
parse: parseFloat
},
[ALL_FIELD_TYPES.object]: {
valid: isPlainObject,
parse: tryParseJsonString
},
[ALL_FIELD_TYPES.array]: {
valid: Array.isArray,
parse: tryParseJsonString
}
};
/**
* Process csv data, output a data object with `{fields: [], rows: []}`.
* The data object can be wrapped in a `dataset` and pass to [`addDataToMap`](../actions/actions.md#adddatatomap)
* @param rawData raw csv string
* @returns data object `{fields: [], rows: []}` can be passed to addDataToMaps
* @public
* @example
* import {processCsvData} from 'kepler.gl/processors';
*
* const testData = `gps_data.utc_timestamp,gps_data.lat,gps_data.lng,gps_data.types,epoch,has_result,id,time,begintrip_ts_utc,begintrip_ts_local,date
* 2016-09-17 00:09:55,29.9900937,31.2590542,driver_analytics,1472688000000,False,1,2016-09-23T00:00:00.000Z,2016-10-01 09:41:39+00:00,2016-10-01 09:41:39+00:00,2016-09-23
* 2016-09-17 00:10:56,29.9927699,31.2461142,driver_analytics,1472688000000,False,2,2016-09-23T00:00:00.000Z,2016-10-01 09:46:37+00:00,2016-10-01 16:46:37+00:00,2016-09-23
* 2016-09-17 00:11:56,29.9907261,31.2312742,driver_analytics,1472688000000,False,3,2016-09-23T00:00:00.000Z,,,2016-09-23
* 2016-09-17 00:12:58,29.9870074,31.2175827,driver_analytics,1472688000000,False,4,2016-09-23T00:00:00.000Z,,,2016-09-23`
*
* const dataset = {
* info: {id: 'test_data', label: 'My Csv'},
* data: processCsvData(testData)
* };
*
* dispatch(addDataToMap({
* datasets: [dataset],
* options: {centerMap: true, readOnly: true}
* }));
*/
export function processCsvData(rawData: unknown[][] | string, header?: string[]): ProcessorResult {
let rows: unknown[][] | undefined;
let headerRow: string[] | undefined;
if (typeof rawData === 'string') {
const parsedRows: string[][] = csvParseRows(rawData);
if (!Array.isArray(parsedRows) || parsedRows.length < 2) {
// looks like an empty file, throw error to be catch
throw new Error('process Csv Data Failed: CSV is empty');
}
headerRow = parsedRows[0];
rows = parsedRows.slice(1);
} else if (Array.isArray(rawData) && rawData.length) {
rows = rawData;
headerRow = header;
if (!Array.isArray(headerRow)) {
// if data is passed in as array of rows and missing header
// assume first row is header
// @ts-ignore
headerRow = rawData[0];
rows = rawData.slice(1);
}
}
if (!rows || !headerRow) {
throw new Error('invalid input passed to processCsvData');
}
// here we assume the csv file that people uploaded will have first row
// as name of the column
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, rows});
const fields = getFieldsFromData(sample, headerRow);
const parsedRows = parseRowsByFields(rows, fields);
return {fields, rows: parsedRows};
}
/**
* Parse rows of csv by analyzed field types. So that `'1'` -> `1`, `'True'` -> `true`
* @param rows
* @param fields
*/
export function parseRowsByFields(rows: any[][], fields: Field[]) {
// Edit rows in place
const geojsonFieldIdx = fields.findIndex(f => f.name === '_geojson');
fields.forEach(parseCsvRowsByFieldType.bind(null, rows, geojsonFieldIdx));
return rows;
}
/**
* Convert falsy value in csv including `'', 'null', 'NULL', 'Null', 'NaN'` to `null`,
* so that type-analyzer won't detect it as string
*
* @param rows
*/
function cleanUpFalsyCsvValue(rows: unknown[][]): void {
const re = new RegExp(CSV_NULLS, 'g');
for (let i = 0; i < rows.length; i++) {
for (let j = 0; j < rows[i].length; j++) {
// analyzer will set any fields to 'string' if there are empty values
// which will be parsed as '' by d3.csv
// here we parse empty data as null
// TODO: create warning when deltect `CSV_NULLS` in the data
if (typeof rows[i][j] === 'string' && (rows[i][j] as string).match(re)) {
rows[i][j] = null;
}
}
}
}
/**
* Process uploaded csv file to parse value by field type
*
* @param rows
* @param geoFieldIdx field index
* @param field
* @param i
*/
export function parseCsvRowsByFieldType(
rows: unknown[][],
geoFieldIdx: number,
field: Field,
i: number
): void {
const parser = PARSE_FIELD_VALUE_FROM_STRING[field.type];
if (parser) {
// check first not null value of it's already parsed
const first = rows.find(r => notNullorUndefined(r[i]));
if (!first || parser.valid(first[i], field)) {
return;
}
rows.forEach(row => {
// parse string value based on field type
if (row[i] !== null) {
row[i] = parser.parse(row[i], field);
if (
geoFieldIdx > -1 &&
isPlainObject(row[geoFieldIdx]) &&
// @ts-ignore
hasOwnProperty(row[geoFieldIdx], 'properties')
) {
// @ts-ignore
row[geoFieldIdx].properties[field.name] = row[i];
}
}
});
}
}
/* eslint-enable complexity */
/**
* Process data where each row is an object, output can be passed to [`addDataToMap`](../actions/actions.md#adddatatomap)
* NOTE: This function may mutate input.
* @param rawData an array of row object, each object should have the same number of keys
* @returns dataset containing `fields` and `rows`
* @public
* @example
* import {addDataToMap} from 'kepler.gl/actions';
* import {processRowObject} from 'kepler.gl/processors';
*
* const data = [
* {lat: 31.27, lng: 127.56, value: 3},
* {lat: 31.22, lng: 126.26, value: 1}
* ];
*
* dispatch(addDataToMap({
* datasets: {
* info: {label: 'My Data', id: 'my_data'},
* data: processRowObject(data)
* }
* }));
*/
export function processRowObject(rawData: unknown[]): ProcessorResult {
if (!Array.isArray(rawData)) {
return null;
} else if (!rawData.length) {
// data is empty
return {
fields: [],
rows: []
};
}
const keys = Object.keys(rawData[0]); // [lat, lng, value]
const rows = rawData.map(d => keys.map(key => d[key])); // [[31.27, 127.56, 3]]
// row object an still contain values like `Null` or `N/A`
cleanUpFalsyCsvValue(rows);
return processCsvData(rows, keys);
}
/**
* Process GeoJSON [`FeatureCollection`](http://wiki.geojson.org/GeoJSON_draft_version_6#FeatureCollection),
* output a data object with `{fields: [], rows: []}`.
* The data object can be wrapped in a `dataset` and passed to [`addDataToMap`](../actions/actions.md#adddatatomap)
* NOTE: This function may mutate input.
*
* @param rawData raw geojson feature collection
* @returns dataset containing `fields` and `rows`
* @public
* @example
* import {addDataToMap} from 'kepler.gl/actions';
* import {processGeojson} from 'kepler.gl/processors';
*
* const geojson = {
* "type" : "FeatureCollection",
* "features" : [{
* "type" : "Feature",
* "properties" : {
* "capacity" : "10",
* "type" : "U-Rack"
* },
* "geometry" : {
* "type" : "Point",
* "coordinates" : [ -71.073283, 42.417500 ]
* }
* }]
* };
*
* dispatch(addDataToMap({
* datasets: {
* info: {
* label: 'Sample Taxi Trips in New York City',
* id: 'test_trip_data'
* },
* data: processGeojson(geojson)
* }
* }));
*/
export function processGeojson(rawData: unknown): ProcessorResult {
const normalizedGeojson = normalize(rawData);
if (!normalizedGeojson || !Array.isArray(normalizedGeojson.features)) {
const error = new Error(
`Read File Failed: File is not a valid GeoJSON. Read more about [supported file format](${GUIDES_FILE_FORMAT_DOC})`
);
throw error;
// fail to normalize geojson
}
// getting all feature fields
const allDataRows: Array<{_geojson: Feature} & keyof Feature> = [];
for (let i = 0; i < normalizedGeojson.features.length; i++) {
const f = normalizedGeojson.features[i];
if (f.geometry) {
allDataRows.push({
// add feature to _geojson field
_geojson: f,
...(f.properties || {})
});
}
}
// get all the field
const fields = allDataRows.reduce<string[]>((accu, curr) => {
Object.keys(curr).forEach(key => {
if (!accu.includes(key)) {
accu.push(key);
}
});
return accu;
}, []);
// make sure each feature has exact same fields
allDataRows.forEach(d => {
fields.forEach(f => {
if (!(f in d)) {
d[f] = null;
if (d._geojson.properties) {
d._geojson.properties[f] = null;
}
}
});
});
return processRowObject(allDataRows);
}
/**
* Process saved kepler.gl json to be pass to [`addDataToMap`](../actions/actions.md#adddatatomap).
* The json object should contain `datasets` and `config`.
* @param rawData
* @param schema
* @returns datasets and config `{datasets: {}, config: {}}`
* @public
* @example
* import {addDataToMap} from 'kepler.gl/actions';
* import {processKeplerglJSON} from 'kepler.gl/processors';
*
* dispatch(addDataToMap(processKeplerglJSON(keplerGlJson)));
*/
export function processKeplerglJSON(rawData: SavedMap, schema = KeplerGlSchema): LoadedMap | null {
return rawData ? schema.load(rawData.datasets, rawData.config) : null;
}
/**
* Parse a single or an array of datasets saved using kepler.gl schema
* @param rawData
* @param schema
*/
export function processKeplerglDataset(
rawData: object | object[],
schema = KeplerGlSchema
): ParsedDataset | ParsedDataset[] | null {
if (!rawData) {
return null;
}
const results = schema.parseSavedData(toArray(rawData));
if (!results) {
return null;
}
return Array.isArray(rawData) ? results : results[0];
}
/**
* Parse arrow table and return a dataset
*
* @param arrowTable ArrowTable to parse, see loaders.gl/schema
* @returns dataset containing `fields` and `rows` or null
*/
export function processArrowTable(arrowTable: arrow.Table): ProcessorResult | null {
return processArrowBatches(arrowTable.batches);
}
/**
* Parse arrow batches returned from parseInBatches()
*
* @param arrowTable the arrow table to parse
* @returns dataset containing `fields` and `rows` or null
*/
export function processArrowBatches(arrowBatches: arrow.RecordBatch[]): ProcessorResult | null {
if (arrowBatches.length === 0) {
return null;
}
const arrowTable = new arrow.Table(arrowBatches);
const fields: Field[] = [];
// parse fields
arrowTable.schema.fields.forEach((field: arrow.Field, index: number) => {
const isGeometryColumn = field.metadata.get('ARROW:extension:name')?.startsWith('geoarrow');
fields.push({
name: field.name,
id: field.name,
displayName: field.name,
format: '',
fieldIdx: index,
type: isGeometryColumn ? ALL_FIELD_TYPES.geoarrow : arrowDataTypeToFieldType(field.type),
analyzerType: isGeometryColumn
? AnalyzerDATA_TYPES.GEOMETRY
: arrowDataTypeToAnalyzerDataType(field.type),
valueAccessor: (dc: any) => d => {
return dc.valueAt(d.index, index);
},
metadata: field.metadata
});
});
const cols = [...Array(arrowTable.numCols).keys()].map(i => arrowTable.getChildAt(i));
// return empty rows and use raw arrow table to construct column-wise data container
return {fields, rows: [], cols, metadata: arrowTable.schema.metadata};
}
export const DATASET_HANDLERS = {
[DATASET_FORMATS.row]: processRowObject,
[DATASET_FORMATS.geojson]: processGeojson,
[DATASET_FORMATS.csv]: processCsvData,
[DATASET_FORMATS.arrow]: processArrowTable,
[DATASET_FORMATS.keplergl]: processKeplerglDataset
};
export const Processors: {
processGeojson: typeof processGeojson;
processCsvData: typeof processCsvData;
processArrowTable: typeof processArrowTable;
processArrowBatches: typeof processArrowBatches;
processRowObject: typeof processRowObject;
processKeplerglJSON: typeof processKeplerglJSON;
processKeplerglDataset: typeof processKeplerglDataset;
analyzerTypeToFieldType: typeof analyzerTypeToFieldType;
getFieldsFromData: typeof getFieldsFromData;
parseCsvRowsByFieldType: typeof parseCsvRowsByFieldType;
} = {
processGeojson,
processCsvData,
processArrowTable,
processArrowBatches,
processRowObject,
processKeplerglJSON,
processKeplerglDataset,
analyzerTypeToFieldType,
getFieldsFromData,
parseCsvRowsByFieldType
};