@mdgs/pivotjet 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/dataset.js ADDED
@@ -0,0 +1,404 @@
1
+ // Columnar, chunked, dictionary-encoded in-memory store.
2
+ //
3
+ // * dimensions -> dictionary code per row (Uint8/16/32 chosen per chunk, auto-upgraded)
4
+ // * measures -> Float64 per row (NaN = null)
5
+ // * rows are never kept as objects, so 10M rows cost ~ (bytes per code + 8 per measure) each.
6
+
7
+ import { formatDateLabel } from './format.js';
8
+ import { Slicer } from './util.js';
9
+ import { compileFormula, FormulaError } from './expr.js';
10
+
11
+ export const CHUNK_SHIFT = 17;
12
+ export const CHUNK_SIZE = 1 << CHUNK_SHIFT; // 131,072 rows
13
+ const CHUNK_MASK = CHUNK_SIZE - 1;
14
+ const CAP = [255, 65535, 4294967295];
15
+
16
+ const newCodes = (w) => (w === 0 ? new Uint8Array(CHUNK_SIZE) : w === 1 ? new Uint16Array(CHUNK_SIZE) : new Uint32Array(CHUNK_SIZE));
17
+
18
+ const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });
19
+
20
+ /** Natural ordering: blanks last, numbers before strings, strings by locale+numeric. */
21
+ export function compareValues(a, b) {
22
+ if (a === b) return 0;
23
+ if (a == null) return 1;
24
+ if (b == null) return -1;
25
+ const ta = typeof a, tb = typeof b;
26
+ if (ta === 'number' && tb === 'number') return a - b;
27
+ if (ta === 'string' && tb === 'string') return collator.compare(a, b);
28
+ if (ta === 'number') return -1;
29
+ if (tb === 'number') return 1;
30
+ if (ta === 'boolean' && tb === 'boolean') return a === b ? 0 : a ? 1 : -1;
31
+ return collator.compare(String(a), String(b));
32
+ }
33
+
34
+ export const ISO_DATE = /^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;
35
+ export const NUM = /^\s*[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?\s*$/;
36
+
37
+ export function coercerFor(type) {
38
+ switch (type) {
39
+ case 'number': return (v) => { const n = typeof v === 'number' ? v : Number(v); return n - n === 0 ? n : null; };
40
+ case 'date': return (v) => {
41
+ let t;
42
+ if (v instanceof Date) t = v.getTime();
43
+ else if (typeof v === 'number') t = v;
44
+ else {
45
+ let s = String(v);
46
+ // date-times without a zone are read as UTC so results don't depend on the machine's timezone
47
+ if (/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/.test(s) && !/(Z|[+-]\d{2}:?\d{2})$/.test(s)) s = s.replace(' ', 'T') + 'Z';
48
+ t = Date.parse(s);
49
+ }
50
+ return t - t === 0 ? t : null;
51
+ };
52
+ case 'boolean': return (v) => (typeof v === 'string' ? !(v === '' || v === '0' || v.toLowerCase() === 'false') : !!v);
53
+ default: return (v) => (typeof v === 'string' ? v : String(v));
54
+ }
55
+ }
56
+
57
+ function inferType(v) {
58
+ if (typeof v === 'number') return 'number';
59
+ if (typeof v === 'boolean') return 'boolean';
60
+ if (v instanceof Date) return 'date';
61
+ return 'string';
62
+ }
63
+
64
+ function resolveRole(type, role) {
65
+ if (role && role !== 'auto') return role;
66
+ return type === 'number' ? 'measure' : 'dimension';
67
+ }
68
+
69
+ export class Dataset {
70
+ /**
71
+ * @param {Array<string|{name:string,type?:string,role?:string,label?:string}>} [fields]
72
+ * @param {{maxCardinality?:number}} [opts]
73
+ */
74
+ constructor(fields = null, opts = {}) {
75
+ this.maxCardinality = opts.maxCardinality ?? 2_000_000;
76
+ this.rowCount = 0;
77
+ this.fields = [];
78
+ this.byName = new Map();
79
+ this.warnings = [];
80
+ this._chunks = 0;
81
+ this._active = [];
82
+ this._calc = [];
83
+ this._pendingInfer = [];
84
+ if (fields) this._defineFields(fields);
85
+ }
86
+
87
+ // ---- construction helpers -------------------------------------------------
88
+ static fromRows(rows, fields = null, opts = {}) {
89
+ const ds = new Dataset(fields, opts);
90
+ ds.addRows(rows);
91
+ return ds;
92
+ }
93
+ static fromColumns(columns, fields = null, opts = {}) {
94
+ const ds = new Dataset(fields, opts);
95
+ ds.addColumns(columns);
96
+ return ds;
97
+ }
98
+
99
+ _defineFields(defs) {
100
+ defs.forEach((d, idx) => {
101
+ const def = typeof d === 'string' ? { name: d } : d;
102
+ const f = {
103
+ name: def.name,
104
+ label: def.label || def.name,
105
+ index: idx,
106
+ type: def.type || 'auto',
107
+ role: def.role || 'auto',
108
+ single: def.precision === 'single',
109
+ dim: null,
110
+ meas: null,
111
+ coerce: null,
112
+ };
113
+ if (this.byName.has(f.name)) throw new Error(`Duplicate field "${f.name}"`);
114
+ this.fields.push(f);
115
+ this.byName.set(f.name, f);
116
+ if (f.type !== 'auto') this._materialize(f);
117
+ });
118
+ this._active = this.fields.filter((f) => f.role !== 'skip' && !f.calc);
119
+ }
120
+
121
+ _materialize(f) {
122
+ if (f.type === 'auto') f.type = 'string';
123
+ f.role = resolveRole(f.type, f.role);
124
+ f.coerce = coercerFor(f.type);
125
+ if (f.role === 'skip') return;
126
+ if (f.role === 'dimension' || f.role === 'both') {
127
+ f.dim = { map: new Map(), values: [null], chunks: [], widths: [], overflow: false };
128
+ }
129
+ if (f.role === 'measure' || f.role === 'both') f.meas = { chunks: [] };
130
+ // back-fill chunks for already allocated ones
131
+ for (let i = 0; i < this._chunks; i++) this._addChunkFor(f);
132
+ }
133
+
134
+ _inferFrom(sampleGetter, sampleSize) {
135
+ for (const f of this.fields) {
136
+ if (f.type !== 'auto') continue;
137
+ let t = null;
138
+ for (let i = 0; i < sampleSize && t === null; i++) {
139
+ const v = sampleGetter(f, i);
140
+ if (v != null && v !== '') t = inferType(v);
141
+ }
142
+ f.type = t || 'string';
143
+ this._materialize(f);
144
+ }
145
+ this._active = this.fields.filter((f) => f.role !== 'skip' && !f.calc);
146
+ }
147
+
148
+ _addChunkFor(f) {
149
+ if (f.dim && !f.dim.overflow) { f.dim.chunks.push(newCodes(0)); f.dim.widths.push(0); }
150
+ if (f.meas) f.meas.chunks.push(f.single ? new Float32Array(CHUNK_SIZE) : new Float64Array(CHUNK_SIZE));
151
+ }
152
+ _reserve(upTo) {
153
+ while (this._chunks * CHUNK_SIZE < upTo) {
154
+ for (const f of this._active) this._addChunkFor(f);
155
+ for (const f of this._calc) this._addChunkFor(f);
156
+ this._chunks++;
157
+ }
158
+ }
159
+
160
+ // ---- writers ---------------------------------------------------------------
161
+ _putDim(f, v, row) {
162
+ const d = f.dim;
163
+ if (d.overflow) return;
164
+ let code = 0;
165
+ if (v !== null && v !== undefined && v !== '') {
166
+ const cv = f.coerce(v);
167
+ if (cv !== null) {
168
+ code = d.map.get(cv);
169
+ if (code === undefined) {
170
+ code = d.values.length;
171
+ if (code > this.maxCardinality) {
172
+ d.overflow = true; d.map = null; d.chunks = []; d.widths = []; d.values = [null];
173
+ this.warnings.push(`Field "${f.name}" exceeded ${this.maxCardinality.toLocaleString()} distinct values and was disabled as a dimension. Mark it role:'skip' or role:'measure' to silence this.`);
174
+ return;
175
+ }
176
+ d.values.push(cv);
177
+ d.map.set(cv, code);
178
+ }
179
+ }
180
+ }
181
+ const ci = row >> CHUNK_SHIFT;
182
+ let arr = d.chunks[ci];
183
+ let w = d.widths[ci];
184
+ if (code > CAP[w]) {
185
+ while (code > CAP[w]) w++;
186
+ const na = newCodes(w);
187
+ na.set(arr);
188
+ d.chunks[ci] = arr = na;
189
+ d.widths[ci] = w;
190
+ }
191
+ arr[row & CHUNK_MASK] = code;
192
+ }
193
+
194
+ _putMeas(f, v, row) {
195
+ let x;
196
+ if (typeof v === 'number') x = v;
197
+ else if (v == null || v === '') x = NaN;
198
+ else if (v instanceof Date) x = v.getTime();
199
+ else if (typeof v === 'boolean') x = v ? 1 : 0;
200
+ else x = Number(v);
201
+ if (x - x !== 0) x = NaN; // NaN / +-Infinity -> null
202
+ f.meas.chunks[row >> CHUNK_SHIFT][row & CHUNK_MASK] = x;
203
+ }
204
+
205
+ // ---- ingestion ---------------------------------------------------------------
206
+ /** Append an array of row objects. */
207
+ addRows(rows) {
208
+ if (!rows.length) return this;
209
+ if (!this.fields.length) {
210
+ this._defineFields(Object.keys(rows[0]));
211
+ }
212
+ this._inferFrom((f, i) => (i < rows.length ? rows[i][f.name] : null), Math.min(rows.length, 1000));
213
+ this._reserve(this.rowCount + rows.length);
214
+ const start = this.rowCount;
215
+ const fs = this._active;
216
+ for (let r = 0; r < rows.length; r++) {
217
+ const row = rows[r];
218
+ const at = this.rowCount;
219
+ for (let i = 0; i < fs.length; i++) {
220
+ const f = fs[i];
221
+ const v = row[f.name];
222
+ if (f.dim) this._putDim(f, v, at);
223
+ if (f.meas) this._putMeas(f, v, at);
224
+ }
225
+ this.rowCount++;
226
+ }
227
+ this._applyCalcs(start);
228
+ return this;
229
+ }
230
+
231
+ /** Append positional rows (arrays in field order). Fastest path for generated / parsed data. */
232
+ addRowArrays(rows) {
233
+ if (!rows.length) return this;
234
+ if (!this.fields.length) throw new Error('addRowArrays requires fields to be defined');
235
+ this._inferFrom((f, i) => (i < rows.length ? rows[i][f.index] : null), Math.min(rows.length, 1000));
236
+ this._reserve(this.rowCount + rows.length);
237
+ const start = this.rowCount;
238
+ const fs = this._active;
239
+ for (let r = 0; r < rows.length; r++) {
240
+ const row = rows[r];
241
+ const at = this.rowCount;
242
+ for (let i = 0; i < fs.length; i++) {
243
+ const f = fs[i];
244
+ const v = row[f.index];
245
+ if (f.dim) this._putDim(f, v, at);
246
+ if (f.meas) this._putMeas(f, v, at);
247
+ }
248
+ this.rowCount++;
249
+ }
250
+ this._applyCalcs(start);
251
+ return this;
252
+ }
253
+ addRow(arr) { return this.addRowArrays([arr]); }
254
+
255
+ /** Append column arrays: { fieldName: Array | TypedArray }. */
256
+ addColumns(columns) {
257
+ const names = Object.keys(columns);
258
+ if (!names.length) return this;
259
+ if (!this.fields.length) this._defineFields(names);
260
+ const n = Math.max(...names.map((k) => columns[k].length));
261
+ this._inferFrom((f, i) => (columns[f.name] ? columns[f.name][i] : null), Math.min(n, 1000));
262
+ this._reserve(this.rowCount + n);
263
+ const base = this.rowCount;
264
+ for (const f of this._active) {
265
+ const col = columns[f.name];
266
+ if (!col) continue;
267
+ for (let i = 0; i < col.length; i++) {
268
+ if (f.dim) this._putDim(f, col[i], base + i);
269
+ if (f.meas) this._putMeas(f, col[i], base + i);
270
+ }
271
+ }
272
+ this.rowCount += n;
273
+ this._applyCalcs(base);
274
+ return this;
275
+ }
276
+
277
+ /**
278
+ * Stream batches from an (async) iterable. Each batch is an array of row
279
+ * objects (or arrays when `positional`). Yields to the event loop.
280
+ */
281
+ async loadAsync(source, { positional = false, onProgress, signal, sliceMs } = {}) {
282
+ const slicer = new Slicer({ signal, sliceMs, onProgress: onProgress && (() => onProgress({ rows: this.rowCount })) });
283
+ for await (const batch of source) {
284
+ if (positional) this.addRowArrays(batch); else this.addRows(batch);
285
+ await slicer.tick();
286
+ }
287
+ if (onProgress) onProgress({ rows: this.rowCount, done: true });
288
+ return this;
289
+ }
290
+
291
+ // ---- calculated fields ---------------------------------------------------------
292
+ /**
293
+ * Add a row-level calculated measure, e.g. { name:'Profit', formula:'Revenue - Cost' }.
294
+ * It is computed for existing rows now and for every row appended later, and can then be
295
+ * summed / averaged / min / max'd like any measure.
296
+ * Formulas can use other measures (bare names or [Names With Spaces]), + - * / % ^, comparisons,
297
+ * if(), round(), abs(), min(), max(), iferror() ... Missing values propagate as null.
298
+ */
299
+ addCalculatedField({ name, label, formula }) {
300
+ if (!name) throw new Error('Calculated field needs a name');
301
+ if (this.byName.has(name)) throw new Error(`Duplicate field "${name}"`);
302
+ const c = compileFormula(formula);
303
+ const refs = c.refs.map((r) => {
304
+ const f = this.byName.get(r.name);
305
+ if (!f) throw new FormulaError(`Unknown field "${r.name}" in formula`);
306
+ if (!f.meas) throw new FormulaError(`Field "${r.name}" is not numeric (role: ${f.role}); use role:'measure' or 'both'`);
307
+ return f;
308
+ });
309
+ const f = {
310
+ name, label: label || name, index: this.fields.length, type: 'number', role: 'measure',
311
+ dim: null, meas: { chunks: [] }, coerce: null, calc: { formula, refs, fn: c.evaluate },
312
+ };
313
+ this.fields.push(f);
314
+ this.byName.set(name, f);
315
+ this._calc.push(f);
316
+ for (let i = 0; i < this._chunks; i++) this._addChunkFor(f);
317
+ this._computeCalc(f, 0, this.rowCount);
318
+ return this;
319
+ }
320
+ _applyCalcs(from) { for (const f of this._calc) this._computeCalc(f, from, this.rowCount); }
321
+ _computeCalc(f, from, to) {
322
+ const refs = f.calc.refs, fn = f.calc.fn, vals = new Array(refs.length);
323
+ for (let row = from; row < to;) {
324
+ const ci = row >> CHUNK_SHIFT;
325
+ const end = Math.min(to, (ci + 1) << CHUNK_SHIFT);
326
+ const src = refs.map((r) => r.meas.chunks[ci]);
327
+ const dst = f.meas.chunks[ci];
328
+ for (; row < end; row++) {
329
+ const o = row & CHUNK_MASK;
330
+ for (let k = 0; k < src.length; k++) { const x = src[k][o]; vals[k] = x === x ? x : null; }
331
+ const r = fn(vals);
332
+ dst[o] = r === null ? NaN : r;
333
+ }
334
+ }
335
+ }
336
+
337
+ // ---- introspection -----------------------------------------------------------
338
+ getField(name) {
339
+ const f = this.byName.get(name);
340
+ if (!f) throw new Error(`Unknown field "${name}"`);
341
+ return f;
342
+ }
343
+ hasField(name) { return this.byName.has(name); }
344
+
345
+ fieldInfo() {
346
+ return this.fields.map((f) => ({
347
+ name: f.name,
348
+ label: f.label,
349
+ type: f.type,
350
+ role: f.role,
351
+ isDimension: !!(f.dim && !f.dim.overflow),
352
+ isMeasure: !!f.meas,
353
+ overflow: !!(f.dim && f.dim.overflow),
354
+ cardinality: f.dim && !f.dim.overflow ? f.dim.values.length - 1 : null,
355
+ formula: f.calc ? f.calc.formula : null,
356
+ precision: f.single ? 'single' : 'double',
357
+ }));
358
+ }
359
+
360
+ /** Display label for a raw dictionary value. */
361
+ labelOf(f, v) {
362
+ if (v == null) return '(blank)';
363
+ if (f.type === 'date') return formatDateLabel(v);
364
+ return String(v);
365
+ }
366
+
367
+ /** Distinct values of a dimension for filter UIs: sorted by natural order. */
368
+ distinct(name, { search = '', limit = 500 } = {}) {
369
+ const f = this.getField(name);
370
+ if (!f.dim || f.dim.overflow) throw new Error(`"${name}" is not available as a dimension`);
371
+ const q = search.toLowerCase();
372
+ const vals = f.dim.values;
373
+ const items = [];
374
+ let total = 0;
375
+ for (let c = 0; c < vals.length; c++) {
376
+ if (c === 0 && !this._hasBlank(f)) continue;
377
+ const label = this.labelOf(f, vals[c]);
378
+ if (q && !label.toLowerCase().includes(q)) continue;
379
+ total++;
380
+ items.push({ code: c, value: vals[c], label });
381
+ }
382
+ items.sort((a, b) => compareValues(a.value, b.value));
383
+ return { total, items: items.slice(0, limit) };
384
+ }
385
+ _hasBlank(f) {
386
+ const ch = f.dim.chunks;
387
+ for (let ci = 0; ci < ch.length; ci++) {
388
+ const len = Math.min(CHUNK_SIZE, this.rowCount - ci * CHUNK_SIZE);
389
+ const a = ch[ci];
390
+ for (let i = 0; i < len; i++) if (a[i] === 0) return true;
391
+ }
392
+ return false;
393
+ }
394
+
395
+ /** Rough in-memory footprint in bytes. */
396
+ memoryUsage() {
397
+ let b = 0;
398
+ for (const f of this.fields) {
399
+ if (f.dim) { for (const c of f.dim.chunks) b += c.byteLength; b += f.dim.values.length * 48; }
400
+ if (f.meas) for (const c of f.meas.chunks) b += c.byteLength;
401
+ }
402
+ return b;
403
+ }
404
+ }