forked from jupyterlab/jupyterlab
/
model.ts
683 lines (602 loc) · 22.2 KB
/
model.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
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import { DataModel } from '@lumino/datagrid';
import { IDisposable } from '@lumino/disposable';
import { PromiseDelegate } from '@lumino/coreutils';
import { parseDSV, parseDSVNoQuotes, IParser } from './parse';
/*
Possible ideas for further implementation:
- Show a spinner or something visible when we are doing delayed parsing.
- The cache right now handles scrolling down great - it gets the next several hundred rows. However, scrolling up causes lots of cache misses - each new row causes a flush of the cache. When invalidating an entire cache, we should put the requested row in middle of the cache (adjusting for rows at the beginning or end). When populating a cache, we should retrieve rows both above and below the requested row.
- When we have a header, and we are guessing the parser to use, try checking just the part of the file *after* the header row for quotes. I think often a first header row is quoted, but the rest of the file is not and can be parsed much faster.
- autdetect the delimiter (look for comma, tab, semicolon in first line. If more than one found, parse first row with comma, tab, semicolon delimiters. One with most fields wins).
- Toolbar buttons to control the row delimiter, the parsing engine (quoted/not quoted), the quote character, etc.
- Investigate incremental loading strategies in the parseAsync function. In initial investigations, setting the chunk size to 100k in parseAsync seems cause instability with large files in Chrome (such as 8-million row files). Perhaps this is because we are recycling the row offset and column offset arrays quickly? It doesn't seem that there is a memory leak. On this theory, perhaps we just need to keep the offsets list an actual list, and pass it into the parsing function to extend without copying, and finalize it into an array buffer only when we are done parsing. Or perhaps we double the size of the array buffer each time, which may be wasteful, but at the end we trim it down if it's too wasteful (perhaps we have our own object that is backed by an array buffer, but has a push method that will automatically double the array buffer size as needed, and a trim function to finalize the array to exactly the size needed)? Or perhaps we don't use array buffers at all - compare the memory cost and speed of keeping the offsets as lists instead of memory buffers.
- Investigate a time-based incremental parsing strategy, rather than a row-based one. The parser could take a maximum time to parse (say 300ms), and will parse up to that duration, in which case the parser probably also needs a way to notify when it has reached the end of a file.
- For very large files, where we are only storing a small cache, scrolling is very laggy in Safari. It would be good to profile it.
*/
/**
* Possible delimiter-separated data parsers.
*/
const PARSERS: { [key: string]: IParser } = {
quotes: parseDSV,
noquotes: parseDSVNoQuotes
};
/**
* A data model implementation for in-memory delimiter-separated data.
*
* #### Notes
* This model handles data with up to 2**32 characters.
*/
export class DSVModel extends DataModel implements IDisposable {
/**
* Create a data model with static CSV data.
*
* @param options - The options for initializing the data model.
*/
constructor(options: DSVModel.IOptions) {
super();
let {
data,
delimiter = ',',
rowDelimiter = undefined,
quote = '"',
quoteParser = undefined,
header = true,
initialRows = 500
} = options;
this._data = data;
this._delimiter = delimiter;
this._quote = quote;
this._quoteEscaped = new RegExp(quote + quote, 'g');
this._initialRows = initialRows;
// Guess the row delimiter if it was not supplied. This will be fooled if a
// different line delimiter possibility appears in the first row.
if (rowDelimiter === undefined) {
let i = data.slice(0, 5000).indexOf('\r');
if (i === -1) {
rowDelimiter = '\n';
} else if (data[i + 1] === '\n') {
rowDelimiter = '\r\n';
} else {
rowDelimiter = '\r';
}
}
this._rowDelimiter = rowDelimiter;
if (quoteParser === undefined) {
// Check for the existence of quotes if the quoteParser is not set.
quoteParser = data.indexOf(quote) >= 0;
}
this._parser = quoteParser ? 'quotes' : 'noquotes';
// Parse the data.
this._parseAsync();
// Cache the header row.
if (header === true && this._columnCount! > 0) {
let h = [];
for (let c = 0; c < this._columnCount!; c++) {
h.push(this._getField(0, c));
}
this._header = h;
}
}
/**
* Whether this model has been disposed.
*/
get isDisposed(): boolean {
return this._isDisposed;
}
/**
* A promise that resolves when the model has parsed all of its data.
*/
get ready(): Promise<void> {
return this._ready.promise;
}
/**
* Get the row count for a region in the data model.
*
* @param region - The row region of interest.
*
* @returns - The row count for the region.
*/
rowCount(region: DataModel.RowRegion): number {
if (region === 'body') {
if (this._header.length === 0) {
return this._rowCount!;
} else {
return this._rowCount! - 1;
}
}
return 1;
}
/**
* Get the column count for a region in the data model.
*
* @param region - The column region of interest.
*
* @returns - The column count for the region.
*/
columnCount(region: DataModel.ColumnRegion): number {
if (region === 'body') {
return this._columnCount!;
}
return 1;
}
/**
* Get the data value for a cell in the data model.
*
* @param region - The cell region of interest.
*
* @param row - The row index of the cell of interest.
*
* @param column - The column index of the cell of interest.
*
* @param returns - The data value for the specified cell.
*/
data(region: DataModel.CellRegion, row: number, column: number): string {
let value: string;
// Look up the field and value for the region.
switch (region) {
case 'body':
if (this._header.length === 0) {
value = this._getField(row, column);
} else {
value = this._getField(row + 1, column);
}
break;
case 'column-header':
if (this._header.length === 0) {
value = (column + 1).toString();
} else {
value = this._header[column];
}
break;
case 'row-header':
value = (row + 1).toString();
break;
case 'corner-header':
value = '';
break;
default:
throw 'unreachable';
}
// Return the final value.
return value;
}
/**
* Dispose the resources held by this model.
*/
dispose(): void {
if (this._isDisposed) {
return;
}
this._isDisposed = true;
this._columnCount = undefined;
this._rowCount = undefined;
this._rowOffsets = null;
this._columnOffsets = null;
this._data = null;
// Clear out state associated with the asynchronous parsing.
if (this._doneParsing === false) {
// Explicitly catch this rejection at least once so an error is not thrown
// to the console.
this.ready.catch(() => {
return;
});
this._ready.reject(undefined);
}
if (this._delayedParse !== null) {
window.clearTimeout(this._delayedParse);
}
}
/**
* Compute the row offsets and initialize the column offset cache.
*
* @param endRow - The last row to parse, from the start of the data (first
* row is row 1).
*
* #### Notes
* This method supports parsing the data incrementally by calling it with
* incrementally higher endRow. Rows that have already been parsed will not be
* parsed again.
*/
private _computeRowOffsets(endRow = 4294967295): void {
// If we've already parsed up to endRow, or if we've already parsed the
// entire data set, return early.
if (this._rowCount! >= endRow || this._doneParsing === true) {
return;
}
// Compute the column count if we don't already have it.
if (this._columnCount === undefined) {
// Get number of columns in first row
this._columnCount = PARSERS[this._parser]({
data: this._data,
delimiter: this._delimiter,
rowDelimiter: this._rowDelimiter,
quote: this._quote,
columnOffsets: true,
maxRows: 1
}).ncols;
}
// Parse the data up to and including the requested row, starting from the
// last row offset we have.
let { nrows, offsets } = PARSERS[this._parser]({
data: this._data,
startIndex: this._rowOffsets[this._rowCount! - 1],
delimiter: this._delimiter,
rowDelimiter: this._rowDelimiter,
quote: this._quote,
columnOffsets: false,
maxRows: endRow - this._rowCount! + 1
});
// Return if we didn't actually get any new rows beyond the one we've
// already parsed.
if (this._startedParsing && nrows <= 1) {
this._doneParsing = true;
this._ready.resolve(undefined);
return;
}
this._startedParsing = true;
// Update the row count.
let oldRowCount = this._rowCount!;
this._rowCount = oldRowCount + nrows - 1;
// If we didn't reach the requested row, we must be done.
if (this._rowCount < endRow) {
this._doneParsing = true;
this._ready.resolve(undefined);
}
// Copy the new offsets into a new row offset array.
let oldRowOffsets = this._rowOffsets;
this._rowOffsets = new Uint32Array(this._rowCount);
this._rowOffsets.set(oldRowOffsets);
this._rowOffsets.set(offsets, oldRowCount - 1);
// Expand the column offsets array if needed
// If the full column offsets array is small enough, build a cache big
// enough for all column offsets. We allocate up to 128 megabytes:
// 128*(2**20 bytes/M)/(4 bytes/entry) = 33554432 entries.
let maxColumnOffsetsRows = Math.floor(33554432 / this._columnCount);
// We need to expand the column offset array if we were storing all column
// offsets before. Check to see if the previous size was small enough that
// we stored all column offsets.
if (oldRowCount <= maxColumnOffsetsRows) {
// Check to see if the new column offsets array is small enough to still
// store, or if we should cut over to a small cache.
if (this._rowCount <= maxColumnOffsetsRows) {
// Expand the existing column offset array for new column offsets.
let oldColumnOffsets = this._columnOffsets;
this._columnOffsets = new Uint32Array(
this._rowCount * this._columnCount
);
this._columnOffsets.set(oldColumnOffsets);
this._columnOffsets.fill(0xffffffff, oldColumnOffsets.length);
} else {
// If not, then our cache size is at most the maximum number of rows we
// fill in the cache at a time.
let oldColumnOffsets = this._columnOffsets;
this._columnOffsets = new Uint32Array(
Math.min(this._maxCacheGet, maxColumnOffsetsRows) * this._columnCount
);
// Fill in the entries we already have.
this._columnOffsets.set(
oldColumnOffsets.subarray(0, this._columnOffsets.length)
);
// Invalidate the rest of the entries.
this._columnOffsets.fill(0xffffffff, oldColumnOffsets.length);
this._columnOffsetsStartingRow = 0;
}
}
// We have more rows than before, so emit the rows-inserted change signal.
let firstIndex = oldRowCount;
if (this._header.length > 0) {
firstIndex -= 1;
}
this.emitChanged({
type: 'rows-inserted',
region: 'body',
index: firstIndex,
span: this._rowCount - oldRowCount
});
}
/**
* Get the parsed string field for a row and column.
*
* @param row - The row number of the data item.
* @param column - The column number of the data item.
* @returns The parsed string for the data item.
*/
private _getField(row: number, column: number): string {
// Declare local variables.
let value: string;
let nextIndex;
// Find the index for the first character in the field.
let index = this._getOffsetIndex(row, column);
// Initialize the trim adjustments.
let trimRight = 0;
let trimLeft = 0;
// Find the end of the slice (the start of the next field), and how much we
// should adjust to trim off a trailing field or row delimiter. First check
// if we are getting the last column.
if (column === this._columnCount! - 1) {
// Check if we are getting any row but the last.
if (row < this._rowCount! - 1) {
// Set the next offset to the next row, column 0.
nextIndex = this._getOffsetIndex(row + 1, 0);
// Since we are not at the last row, we need to trim off the row
// delimiter.
trimRight += this._rowDelimiter.length;
} else {
// We are getting the last data item, so the slice end is the end of the
// data string.
nextIndex = this._data.length;
// The string may or may not end in a row delimiter (RFC 4180 2.2), so
// we explicitly check if we should trim off a row delimiter.
if (
this._data[nextIndex - 1] ===
this._rowDelimiter[this._rowDelimiter.length - 1]
) {
trimRight += this._rowDelimiter.length;
}
}
} else {
// The next field starts at the next column offset.
nextIndex = this._getOffsetIndex(row, column + 1);
// Trim off the delimiter if it exists at the end of the field
if (index < nextIndex && this._data[nextIndex - 1] === this._delimiter) {
trimRight += 1;
}
}
// Check to see if the field begins with a quote. If it does, trim a quote on either side.
if (this._data[index] === this._quote) {
trimLeft += 1;
trimRight += 1;
}
// Slice the actual value out of the data string.
value = this._data.slice(index + trimLeft, nextIndex - trimRight);
// If we have a quoted field and we have an escaped quote inside it, unescape it.
if (trimLeft === 1 && value.indexOf(this._quote) !== -1) {
value = value.replace(this._quoteEscaped, this._quote);
}
// Return the value.
return value;
}
/**
* Get the index in the data string for the first character of a row and
* column.
*
* @param row - The row of the data item.
* @param column - The column of the data item.
* @returns - The index into the data string where the data item starts.
*/
private _getOffsetIndex(row: number, column: number): number {
// Declare local variables.
const ncols = this._columnCount!;
// Check to see if row *should* be in the cache, based on the cache size.
let rowIndex = (row - this._columnOffsetsStartingRow) * ncols;
if (rowIndex < 0 || rowIndex > this._columnOffsets.length) {
// Row isn't in the cache, so we invalidate the entire cache and set up
// the cache to hold the requested row.
this._columnOffsets.fill(0xffffffff);
this._columnOffsetsStartingRow = row;
rowIndex = 0;
}
// Check to see if we need to fetch the row data into the cache.
if (this._columnOffsets[rowIndex] === 0xffffffff) {
// Figure out how many rows below us also need to be fetched.
let maxRows = 1;
while (
maxRows <= this._maxCacheGet &&
this._columnOffsets[rowIndex + maxRows * ncols] === 0xffffff
) {
maxRows++;
}
// Parse the data to get the column offsets.
let { offsets } = PARSERS[this._parser]({
data: this._data,
delimiter: this._delimiter,
rowDelimiter: this._rowDelimiter,
quote: this._quote,
columnOffsets: true,
maxRows: maxRows,
ncols: ncols,
startIndex: this._rowOffsets[row]
});
// Copy results to the cache.
for (let i = 0; i < offsets.length; i++) {
this._columnOffsets[rowIndex + i] = offsets[i];
}
}
// Return the offset index from cache.
return this._columnOffsets[rowIndex + column];
}
/**
* Parse the data string asynchronously.
*
* #### Notes
* It can take several seconds to parse a several hundred megabyte string, so
* we parse the first 500 rows to get something up on the screen, then we
* parse the full data string asynchronously.
*/
private _parseAsync(): void {
// Number of rows to get initially.
let currentRows = this._initialRows;
// Number of rows to get in each chunk thereafter. We set this high to just
// get the rest of the rows for now.
let chunkRows = Math.pow(2, 32) - 1;
// We give the UI a chance to draw by delaying the chunk parsing.
let delay = 30; // milliseconds
// Define a function to parse a chunk up to and including endRow.
let parseChunk = (endRow: number) => {
try {
this._computeRowOffsets(endRow);
} catch (e) {
// Sometimes the data string cannot be parsed with the full parser (for
// example, we may have the wrong delimiter). In these cases, fall back to
// the simpler parser so we can show something.
if (this._parser === 'quotes') {
console.warn(e);
this._parser = 'noquotes';
this._resetParser();
this._computeRowOffsets(endRow);
} else {
throw e;
}
}
return this._doneParsing;
};
// Reset the parser to its initial state.
this._resetParser();
// Parse the first rows to give us the start of the data right away.
let done = parseChunk(currentRows);
// If we are done, return early.
if (done) {
return;
}
// Define a function to recursively parse the next chunk after a delay.
let delayedParse = () => {
// Parse up to the new end row.
let done = parseChunk(currentRows + chunkRows);
currentRows += chunkRows;
// Gradually double the chunk size until we reach a million rows, if we
// start below a million-row chunk size.
if (chunkRows < 1000000) {
chunkRows *= 2;
}
// If we aren't done, the schedule another parse.
if (done) {
this._delayedParse = null;
} else {
this._delayedParse = window.setTimeout(delayedParse, delay);
}
};
// Parse full data string in chunks, delayed by a few milliseconds to give the UI a chance to draw.
this._delayedParse = window.setTimeout(delayedParse, delay);
}
/**
* Reset the parser state.
*/
private _resetParser(): void {
this._columnCount = undefined;
// First row offset is *always* 0, so we always have the first row offset.
this._rowOffsets = new Uint32Array(1);
this._rowCount = 1;
this._startedParsing = false;
this._columnOffsets = new Uint32Array(0);
// Clear out state associated with the asynchronous parsing.
if (this._doneParsing === false) {
// Explicitly catch this rejection at least once so an error is not thrown
// to the console.
this.ready.catch(() => {
return;
});
this._ready.reject(undefined);
}
this._doneParsing = false;
this._ready = new PromiseDelegate<void>();
if (this._delayedParse !== null) {
window.clearTimeout(this._delayedParse);
this._delayedParse = null;
}
this.emitChanged({ type: 'model-reset' });
}
// Parser settings
private _delimiter: string;
private _quote: string;
private _quoteEscaped: RegExp;
private _parser: 'quotes' | 'noquotes';
private _rowDelimiter: string;
// Data values
private _data: string;
private _rowCount: number | undefined = 1;
private _columnCount: number | undefined;
// Cache information
/**
* The header strings.
*/
private _header: string[] = [];
/**
* The column offset cache, starting with row _columnOffsetsStartingRow
*
* #### Notes
* The index of the first character in the data string for row r, column c is
* _columnOffsets[(r-this._columnOffsetsStartingRow)*numColumns+c]
*/
private _columnOffsets: Uint32Array = new Uint32Array(0);
/**
* The row that _columnOffsets[0] represents.
*/
private _columnOffsetsStartingRow: number = 0;
/**
* The maximum number of rows to parse when there is a cache miss.
*/
private _maxCacheGet: number = 1000;
/**
* The index for the start of each row.
*/
private _rowOffsets: Uint32Array = new Uint32Array(1);
/**
* The number of rows to parse initially before doing a delayed parse of the
* entire data.
*/
private _initialRows: number;
// Bookkeeping variables.
private _delayedParse: number | null = null;
private _startedParsing: boolean = false;
private _doneParsing: boolean = false;
private _isDisposed: boolean = false;
private _ready = new PromiseDelegate<void>();
}
/**
* The namespace for the `DSVModel` class statics.
*/
export namespace DSVModel {
/**
* An options object for initializing a delimiter-separated data model.
*/
export interface IOptions {
/**
* The field delimiter, such as ',' or '\t'.
*
* #### Notes
* The field delimiter must be a single character.
*/
delimiter: string;
/**
* The data source for the data model.
*/
data: string;
/**
* Whether the data has a one-row header.
*/
header?: boolean;
/**
* Row delimiter.
*
* #### Notes
* Any carriage return or newline character that is not a delimiter should
* be in a quoted field, regardless of the row delimiter setting.
*/
rowDelimiter?: '\r\n' | '\r' | '\n';
/**
* Quote character.
*
* #### Notes
* Quotes are escaped by repeating them, as in RFC 4180. The quote must be a
* single character.
*/
quote?: string;
/**
* Whether to use the parser that can handle quoted delimiters.
*
* #### Notes
* Setting this to false uses a much faster parser, but assumes there are
* not any field or row delimiters that are quoted in fields. If this is not
* set, it defaults to true if any quotes are found in the data, and false
* otherwise.
*/
quoteParser?: boolean;
/**
* The maximum number of initial rows to parse before doing a asynchronous
* full parse of the data. This should be greater than 0.
*/
initialRows?: number;
}
}