@eox/chart 2.0.0-alpha12 → 2.0.0-alpha14

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.
@@ -1,601 +0,0 @@
1
- import Chart, {
2
- ChartDataset,
3
- LinearScale,
4
- CategoryScale,
5
- ChartOptions,
6
- } from "chart.js/auto";
7
- import pRetry, { AbortError } from "p-retry";
8
- import { DateTime } from "luxon";
9
-
10
- import {
11
- LineWithErrorBarsController,
12
- LineWithErrorBarsChart,
13
- ScatterWithErrorBarsChart,
14
- ScatterWithErrorBarsController,
15
- PointWithErrorBar,
16
- } from "chartjs-chart-error-bars";
17
-
18
- Chart.register(
19
- LineWithErrorBarsController,
20
- LineWithErrorBarsChart,
21
- PointWithErrorBar,
22
- ScatterWithErrorBarsChart,
23
- ScatterWithErrorBarsController,
24
- LinearScale,
25
- CategoryScale
26
- );
27
-
28
- type status = "ready" | "loading" | "error";
29
- interface DSDict {
30
- [key: number]: {
31
- [key: string]: {
32
- status: string;
33
- data?: {
34
- [key: string]: {
35
- date: string;
36
- basicStats: { mean: number; min: number; max: number };
37
- }[];
38
- };
39
- request: Promise<void>;
40
- };
41
- };
42
- }
43
-
44
- interface yAxisObject {
45
- id: "string";
46
- containedSignals: string[];
47
- }
48
-
49
- export interface SDMOptions {
50
- source: string;
51
- endpoint: string;
52
- features: string[][];
53
- geometry: object;
54
- timeInterval: object;
55
- startTime?: string;
56
- endTime?: string;
57
- timeAggregation?: object;
58
- retries?: number;
59
- normalize?: boolean;
60
- showMinMax?: boolean;
61
- colors?: string[];
62
- additionalYAxis?: yAxisObject[];
63
- }
64
-
65
- class SignalsDataManager {
66
- chart: Chart;
67
- startTime: DateTime;
68
- endTime: DateTime;
69
- timeAggregation: object;
70
- options: SDMOptions;
71
- chartOptions: ChartOptions;
72
- dataStorage: DSDict;
73
- status: status;
74
- activeFields: string[];
75
- additionalYAxis: yAxisObject[] | null;
76
-
77
- constructor(chart: Chart, options: SDMOptions) {
78
- this.chart = chart;
79
- this.options = options;
80
- this.startTime = DateTime.now().minus(options.timeInterval);
81
- this.endTime = DateTime.now();
82
- if (options.startTime && options.endTime) {
83
- // Overwrite values if provided
84
- this.startTime = DateTime.fromISO(options.startTime).setZone("UTC");
85
- this.endTime = DateTime.fromISO(options.endTime).setZone("UTC");
86
- }
87
- if (this.options.timeAggregation) {
88
- this.timeAggregation = this.options.timeAggregation;
89
- }
90
- this.options.retries = this.options.retries ? this.options.retries : 5;
91
- this.options.normalize = this.options.normalize
92
- ? this.options.normalize
93
- : false;
94
- this.options.showMinMax = this.options.showMinMax
95
- ? this.options.showMinMax
96
- : false;
97
- this.additionalYAxis = this.options.additionalYAxis
98
- ? this.options.additionalYAxis
99
- : null;
100
- this.dataStorage = {};
101
- // Initialize data storage
102
- this.options.features.forEach((_, idx) => (this.dataStorage[idx] = {}));
103
- this.status = "ready";
104
- this.chartOptions = {
105
- scales: {
106
- x: {
107
- type: "time",
108
- min: this.startTime.toISODate(),
109
- max: this.endTime.toISODate(),
110
- ticks: {
111
- minRotation: 0,
112
- maxRotation: 0,
113
- },
114
- },
115
- },
116
- interaction: {
117
- axis: "x",
118
- mode: "nearest",
119
- intersect: false,
120
- },
121
- plugins: {
122
- legend: {
123
- labels: {
124
- usePointStyle: true,
125
- pointStyle: "rect",
126
- padding: 5,
127
- sort: (a, b) => a.text.localeCompare(b.text),
128
- },
129
- position: "right",
130
- onClick: (_, legendItem) => {
131
- if (!legendItem.hidden) {
132
- const idx = this.activeFields.indexOf(legendItem.text);
133
- const keys = this.activeFields;
134
- keys.splice(idx, 1);
135
- this.setActiveFields(keys);
136
- } else {
137
- this.setActiveFields([...this.activeFields, legendItem.text]);
138
- }
139
- },
140
- },
141
- tooltip: {
142
- callbacks: {
143
- title: (tooltipItem) => {
144
- const raw: any = tooltipItem[0]?.raw;
145
- return raw.x.toISODate();
146
- },
147
- label: (tooltipItem) => {
148
- const raw: any = tooltipItem.raw;
149
- return `${tooltipItem.dataset.label}: ↔ ${raw.y.toPrecision(
150
- 3
151
- )}; ↓ ${raw.yMin.toPrecision(3)}, ↑ ${raw.yMax.toPrecision(3)}`;
152
- },
153
- },
154
- },
155
- },
156
- };
157
- // Adding possible additional y axis scales
158
- for (let index = 0; index < this.additionalYAxis.length; index++) {
159
- const scale = this.additionalYAxis[index];
160
- this.chartOptions.scales[scale.id] = {
161
- type: "linear",
162
- position: "right",
163
- };
164
- }
165
- }
166
-
167
- private checkLoadingStatus() {
168
- const spinner = document.getElementById("loadingIndicator");
169
- let loading = false;
170
- // TODO: Showing when error state happened
171
- Object.keys(this.dataStorage).forEach((_, groupIdx) => {
172
- Object.keys(this.dataStorage[groupIdx]).forEach((timeKey) => {
173
- if (this.dataStorage[groupIdx][timeKey].status === "fetching") {
174
- loading = true;
175
- }
176
- });
177
- });
178
- spinner.className = loading ? "loader" : "loader hidden";
179
- }
180
-
181
- private fetchSignals(groupIndex: number, start?: DateTime, end?: DateTime) {
182
- const features = this.options.features[groupIndex]
183
- .map((f) => `feature=${f}`)
184
- .join("&");
185
- const times = `${start ? "&start_date=" + start.toISODate() : ""}${
186
- end ? "&end_date=" + end.toISODate() : ""
187
- }`;
188
- const request = `${this.options.endpoint}?source=${this.options.source}&${features}${times}`;
189
- const geom = this.options.geometry;
190
-
191
- async function fetchSignals() {
192
- const response = await fetch(request, {
193
- headers: { "Content-Type": "application/json; charset=utf-8" },
194
- method: "POST",
195
- mode: "cors",
196
- body: JSON.stringify({
197
- geometry: geom,
198
- }),
199
- });
200
- // Abort retrying if the resource doesn't exist
201
- if (response.status === 404) {
202
- throw new AbortError(response.statusText);
203
- }
204
- if (response.status !== 200) {
205
- throw Error(response.statusText);
206
- }
207
- return response;
208
- }
209
- return pRetry(fetchSignals, {
210
- onFailedAttempt: (error) => {
211
- console.log(
212
- `Attempt ${error.attemptNumber} failed. There are ${error.retriesLeft} retries left.`
213
- );
214
- },
215
- retries: this.options.retries,
216
- }).then(function (res) {
217
- return res.json();
218
- });
219
- this.checkLoadingStatus();
220
- }
221
-
222
- private updateChart() {
223
- this.checkLoadingStatus();
224
- this.chart.options = this.chartOptions;
225
- const datasets: ChartDataset[] = [];
226
- this.options.features.flat().forEach((key, dsIndex) => {
227
- // Find group
228
- let groupIndex: number = -1;
229
- this.options.features.forEach((group, idx) => {
230
- if (group.includes(key)) {
231
- groupIndex = idx;
232
- }
233
- });
234
- if (groupIndex !== -1) {
235
- let data: {
236
- date: string;
237
- basicStats?: { mean: number; min: number; max: number };
238
- }[] = [];
239
- Object.keys(this.dataStorage[groupIndex]).forEach((timekey) => {
240
- const dsEntry = this.dataStorage[groupIndex][timekey];
241
- if (dsEntry.status === "finished") {
242
- if (
243
- Object.keys(dsEntry.data).length !== 0 &&
244
- Object.keys(dsEntry.data).includes(key)
245
- ) {
246
- data.push(...dsEntry.data[key]);
247
- }
248
- } else {
249
- data.push({ date: "missing" });
250
- }
251
- });
252
-
253
- let actualDataAdded = false;
254
- let max = Number.MIN_VALUE;
255
- let min = Number.MAX_VALUE;
256
- let signalData = <any>data.map((datapoint) => {
257
- let ds = {};
258
- if (datapoint && datapoint.date !== "missing") {
259
- const stats = datapoint.basicStats;
260
- if (this.options.showMinMax) {
261
- min = stats.min < min ? stats.min : min;
262
- max = stats.max > max ? stats.max : max;
263
- } else {
264
- min = stats.mean < min ? stats.mean : min;
265
- max = stats.mean > max ? stats.mean : max;
266
- }
267
- ds = {
268
- x: DateTime.fromISO(datapoint.date).setZone("UTC"),
269
- y: datapoint.basicStats.mean,
270
- yMin: datapoint.basicStats.min,
271
- yMax: datapoint.basicStats.max,
272
- };
273
- actualDataAdded = true;
274
- }
275
- return ds;
276
- });
277
- if (actualDataAdded && this.timeAggregation) {
278
- // If we aggregate data we recalculate min max so we reset it
279
- max = Number.MIN_VALUE;
280
- min = Number.MAX_VALUE;
281
- const aggrData = [];
282
- let currDataIdx = 0;
283
- let currDate = DateTime.fromObject({
284
- year: this.startTime.year,
285
- month: this.startTime.month,
286
- day: this.startTime.day,
287
- });
288
- while (currDate < this.endTime) {
289
- let dataSum = 0;
290
- let minSum = 0;
291
- let maxSum = 0;
292
- while (
293
- currDataIdx < signalData.length &&
294
- (Object.keys(signalData[currDataIdx]).length === 0 ||
295
- signalData[currDataIdx].x < currDate)
296
- ) {
297
- currDataIdx++;
298
- }
299
- const x1 = currDataIdx;
300
- while (
301
- currDataIdx < signalData.length &&
302
- (Object.keys(signalData[currDataIdx]).length === 0 ||
303
- signalData[currDataIdx].x < currDate.plus(this.timeAggregation))
304
- ) {
305
- const sd = signalData[currDataIdx];
306
- dataSum += sd.y;
307
- minSum += sd.yMin;
308
- maxSum += sd.yMax;
309
- currDataIdx++;
310
- }
311
- const x2 = currDataIdx;
312
- const count = x2 - x1;
313
- // If datapoints are within the interval we push the aggregation to the aggregated data
314
- if (count > 0) {
315
- const yMean = dataSum / count;
316
- const yMinMean = minSum / count;
317
- const yMaxMean = maxSum / count;
318
- if (this.options.showMinMax) {
319
- min = yMinMean < min ? yMinMean : min;
320
- max = yMaxMean > max ? yMaxMean : max;
321
- } else {
322
- min = yMean < min ? yMean : min;
323
- max = yMean > max ? yMean : max;
324
- }
325
- // TODO: can we save a time interval here?
326
- aggrData.push({
327
- x: currDate,
328
- y: yMean,
329
- yMin: yMinMean,
330
- yMax: yMaxMean,
331
- });
332
- }
333
- currDate = currDate.plus(this.timeAggregation);
334
- }
335
- signalData = aggrData;
336
- }
337
-
338
- if (actualDataAdded && this.options.normalize) {
339
- signalData = signalData.map(
340
- (dp: { x: DateTime; y: number; yMin: number; yMax: number }) => {
341
- dp.y = (dp.y - min) / (max - min);
342
- dp.yMin = (dp.yMin - min) / (max - min);
343
- dp.yMax = (dp.yMax - min) / (max - min);
344
- return dp;
345
- }
346
- );
347
- }
348
-
349
- let ds: ChartDataset = {
350
- type: "line",
351
- label: key,
352
- data: signalData,
353
- hidden: !this.activeFields.includes(key),
354
- };
355
- if (this.options.showMinMax) {
356
- ds = {
357
- type: "lineWithErrorBars",
358
- label: key,
359
- data: signalData,
360
- hidden: !this.activeFields.includes(key),
361
- errorBarWhiskerLineWidth: 2,
362
- errorBarColor: "#00000000",
363
- };
364
- }
365
- if (this.options.colors && this.options.colors.length >= dsIndex) {
366
- const color = this.options.colors[dsIndex];
367
- ds.backgroundColor = color;
368
- ds.borderColor = color;
369
-
370
- if (this.options.showMinMax) {
371
- ds = {
372
- type: "lineWithErrorBars",
373
- label: key,
374
- data: signalData,
375
- hidden: !this.activeFields.includes(key),
376
- errorBarWhiskerLineWidth: 2,
377
- errorBarColor: "#00000000",
378
- errorBarWhiskerColor: color,
379
- errorBarWhiskerSize: 10,
380
- backgroundColor: color,
381
- borderColor: color,
382
- };
383
- }
384
- }
385
- // Check if additional y axis should be used
386
- if (this.additionalYAxis !== null) {
387
- for (let index = 0; index < this.additionalYAxis.length; index++) {
388
- const axis = this.additionalYAxis[index];
389
- if (axis.containedSignals.includes(key)) {
390
- ds.yAxisID = axis.id;
391
- }
392
- }
393
- }
394
- datasets.push(ds);
395
- }
396
- });
397
-
398
- this.chart.data = {
399
- datasets,
400
- };
401
- this.chart.update("none");
402
- }
403
-
404
- private retrieveMissingData() {
405
- // Review current time span and see if data needs to be fetched
406
-
407
- // First identify signal groups
408
- const signalGroupIndices: number[] = [];
409
- this.activeFields.forEach((af) => {
410
- this.options.features.forEach((group, index) => {
411
- if (group.includes(af) && !signalGroupIndices.includes(index)) {
412
- signalGroupIndices.push(index);
413
- }
414
- });
415
- });
416
-
417
- // Check if dataStorage has relevant data
418
- // We use monthly steps for data retrieval
419
- let currDate = DateTime.fromObject({
420
- year: this.endTime.year,
421
- month: this.endTime.month,
422
- })
423
- .plus({ month: 1 })
424
- .minus({ second: 1 });
425
- const start = DateTime.fromObject({
426
- year: this.startTime.year,
427
- month: this.startTime.month,
428
- })
429
- .plus({ month: 1 })
430
- .minus({ second: 1 });
431
- while (currDate > start) {
432
- const timeslot = currDate.toFormat("yyyyMM");
433
- signalGroupIndices.forEach((index) => {
434
- if (!(timeslot in this.dataStorage[index])) {
435
- // request data
436
- const request = this.fetchSignals(
437
- index,
438
- DateTime.fromObject({ year: currDate.year, month: currDate.month }),
439
- DateTime.fromObject({
440
- year: currDate.year,
441
- month: currDate.month,
442
- })
443
- .plus({ month: 1 })
444
- .minus({ second: 1 })
445
- )
446
- .then((data) => {
447
- this.dataStorage[index][timeslot].data = data;
448
- this.dataStorage[index][timeslot].status = "finished";
449
- this.updateChart();
450
- })
451
- .catch(() => {
452
- this.dataStorage[index][timeslot].status = "failed";
453
- this.updateChart();
454
- });
455
- this.dataStorage[index][timeslot] = {
456
- request,
457
- status: "fetching",
458
- };
459
- }
460
- });
461
- currDate = currDate.minus({ months: 1 });
462
- }
463
- }
464
-
465
- triggerCSVDownload() {
466
- const completeData: {
467
- date: string;
468
- basicStats?: { mean: number; min: number; max: number };
469
- }[][] = [];
470
- const headers: string[] = [];
471
- const allSignals = this.activeFields;
472
- allSignals.forEach((key, signalIdx) => {
473
- // Find group
474
- let groupIndex: number = -1;
475
- this.options.features.forEach((group, idx) => {
476
- if (group.includes(key)) {
477
- groupIndex = idx;
478
- }
479
- });
480
- if (groupIndex !== -1) {
481
- let data: {
482
- date: string;
483
- basicStats?: { mean: number; min: number; max: number };
484
- }[] = [];
485
- Object.keys(this.dataStorage[groupIndex]).forEach((timekey) => {
486
- const dsEntry = this.dataStorage[groupIndex][timekey];
487
- if (dsEntry.status === "finished") {
488
- if (
489
- Object.keys(dsEntry.data).length !== 0 &&
490
- Object.keys(dsEntry.data).includes(key)
491
- ) {
492
- data.push(...dsEntry.data[key]);
493
- }
494
- }
495
- });
496
- if (data.length > 0) {
497
- headers.push(allSignals[signalIdx]);
498
- completeData.push(data);
499
- }
500
- }
501
- });
502
- // We need to try and bring the different timed datasets into "same timegrid" lets do some binning
503
- const binnedData: {
504
- [key: string]: {
505
- [key: string]: {
506
- mean: number;
507
- max: number;
508
- min: number;
509
- };
510
- };
511
- } = {};
512
- headers.forEach((datakey, idx) => {
513
- completeData[idx].forEach((dp) => {
514
- if (binnedData[dp.date]) {
515
- binnedData[dp.date][datakey] = dp.basicStats;
516
- } else {
517
- binnedData[dp.date] = {};
518
- binnedData[dp.date][datakey] = dp.basicStats;
519
- }
520
- });
521
- });
522
-
523
- // Now we try to construct the csv adding empty values when timestamp not available for a dataset
524
- let csv = "time,";
525
- const allHeaders = headers.map((val) => [val, `${val}_max`, `${val}_min`]);
526
- csv += allHeaders.flat().join(",");
527
- csv += "\n";
528
- Object.keys(binnedData).forEach((dateKey) => {
529
- const row: (string | number)[] = [dateKey];
530
- headers.forEach((signalKey) => {
531
- const stats = binnedData[dateKey][signalKey]
532
- ? binnedData[dateKey][signalKey]
533
- : null;
534
- if (stats != null) {
535
- row.push(...[stats.mean, stats.max, stats.min]);
536
- } else {
537
- row.push(...["", "", ""]);
538
- }
539
- });
540
- csv += row.join(",");
541
- csv += "\n";
542
- });
543
- var hiddenElement = document.createElement("a");
544
- hiddenElement.href = "data:text/csv;charset=utf-8," + encodeURI(csv);
545
- hiddenElement.target = "_blank";
546
- hiddenElement.download = "chart_data.csv";
547
- hiddenElement.click();
548
- }
549
-
550
- setGeometry(geometry: object) {
551
- // Clear all currently saved data
552
- this.dataStorage = {};
553
- // Initialize data storage
554
- this.options.features.forEach((_, idx) => (this.dataStorage[idx] = {}));
555
- this.options.geometry = geometry;
556
- this.retrieveMissingData();
557
- this.updateChart();
558
- }
559
-
560
- setActiveFields(activeFields: string[]) {
561
- this.activeFields = activeFields;
562
- this.retrieveMissingData();
563
- this.updateChart();
564
- }
565
-
566
- setTimeInterval(start: DateTime, end: DateTime) {
567
- this.startTime = start;
568
- this.endTime = end;
569
- this.chartOptions.scales.x.min = start.toISODate();
570
- this.chartOptions.scales.x.max = end.toISODate();
571
- this.retrieveMissingData();
572
- this.updateChart();
573
- }
574
-
575
- setNormalize(normalize: boolean) {
576
- this.options.normalize = normalize;
577
- this.updateChart();
578
- }
579
-
580
- setShowMinMax(showMinMax: boolean) {
581
- this.options.showMinMax = showMinMax;
582
- this.updateChart();
583
- }
584
-
585
- setTimeAggregation(
586
- aggregation: {
587
- day?: number;
588
- week?: number;
589
- month?: number;
590
- year?: number;
591
- } | null
592
- ) {
593
- this.timeAggregation = aggregation;
594
- this.updateChart();
595
- }
596
- /*
597
- setAggregation(aggregation: string) {}
598
- */
599
- }
600
-
601
- export default SignalsDataManager;
package/src/vite-env.d.ts DELETED
@@ -1 +0,0 @@
1
- /// <reference types="vite/client" />
@@ -1,9 +0,0 @@
1
- import Chart from "chart.js/auto";
2
-
3
- declare global {
4
- interface Window {
5
- chart: Chart;
6
- }
7
- }
8
-
9
- export {};