appChart.js 14 KB
Newer Older
Pithon Kabiro's avatar
Pithon Kabiro committed
1
"use strict";
Pithon Kabiro's avatar
Pithon Kabiro committed
2
3
4

// Request parameters
const BASE_URL =
Pithon Kabiro's avatar
Pithon Kabiro committed
5
6
7
  "http://193.196.39.91:8080/frost-icity-tp31/v1.1/Datastreams(80)/Observations";
const BASE_URL2 =
  "http://193.196.39.91:8080/frost-icity-tp31-v2/v1.1/Datastreams(41)/Observations";
Pithon Kabiro's avatar
Pithon Kabiro committed
8
9
10
const PARAM_RESULT_FORMAT = "dataArray";
const PARAM_ORDER_BY = "phenomenonTime asc";
const PARAM_FILTER =
Pithon Kabiro's avatar
Pithon Kabiro committed
11
  "resultTime ge 2020-01-01T00:00:00.000Z and resultTime le 2020-07-01T00:00:00.000Z";
Pithon Kabiro's avatar
Pithon Kabiro committed
12
13
14
const PARAM_SELECT = "result,phenomenonTime";

/**
Pithon Kabiro's avatar
Pithon Kabiro committed
15
16
17
18
19
 * Draw an EMPTY chart using Apexcharts library
 * @param {HTMLElement} htmlElement - HTML element where chart will be drawn
 * @param {String} mainTitle - Main chart title
 * @param {String} yAxisTitle - Y-axis title
 * @returns {Object} - An empty chart object
Pithon Kabiro's avatar
Pithon Kabiro committed
20
 */
Pithon Kabiro's avatar
Pithon Kabiro committed
21
22
23
24
25
const drawEmptyLineChartAC = function (
  htmlElement,
  mainTitle = "Main Chart Title",
  yAxisTitle = "y-axis title"
) {
Pithon Kabiro's avatar
Pithon Kabiro committed
26
  // Chart constants
Pithon Kabiro's avatar
Pithon Kabiro committed
27
28
29
  const CHART_HTML_ELEMENT = htmlElement;
  const TITLE_TEXT = mainTitle;
  const Y_AXIS_TITLE = yAxisTitle;
Pithon Kabiro's avatar
Pithon Kabiro committed
30
31

  const options = {
Pithon Kabiro's avatar
Pithon Kabiro committed
32
    series: [],
Pithon Kabiro's avatar
Pithon Kabiro committed
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
    chart: {
      type: "area",
      stacked: false,
      height: 350,
      zoom: {
        type: "x",
        enabled: true,
        autoScaleYaxis: true,
      },
      toolbar: {
        autoSelected: "zoom",
      },
    },
    dataLabels: {
      enabled: false,
    },
    markers: {
      size: 0,
    },
    title: {
      text: TITLE_TEXT,
      align: "left",
    },
Pithon Kabiro's avatar
Pithon Kabiro committed
56
57
58
    noData: {
      text: "Loading...",
    },
Pithon Kabiro's avatar
Pithon Kabiro committed
59
60
61
62
63
64
65
66
67
68
69
70
71
    fill: {
      type: "gradient",
      gradient: {
        shadeIntensity: 1,
        inverseColors: false,
        opacityFrom: 0.5,
        opacityTo: 0,
        stops: [0, 90, 100],
      },
    },
    yaxis: {
      labels: {
        formatter: function (val) {
Pithon Kabiro's avatar
Pithon Kabiro committed
72
          return val.toFixed(0);
Pithon Kabiro's avatar
Pithon Kabiro committed
73
        },
Pithon Kabiro's avatar
Pithon Kabiro committed
74
        forceNiceScale: true,
Pithon Kabiro's avatar
Pithon Kabiro committed
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
      },
      title: {
        text: Y_AXIS_TITLE,
      },
    },
    xaxis: {
      type: "datetime",
    },
    tooltip: {
      shared: false,
      y: {
        formatter: function (val) {
          return val.toFixed(2);
        },
      },
    },
  };

  const chart = new ApexCharts(CHART_HTML_ELEMENT, options);
Pithon Kabiro's avatar
Pithon Kabiro committed
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
  return chart;
};

// Line chart 1 constants
const chart1LineHTML = document.querySelector("#chart-apex-line");
const chart1LineTitle = "Inlet flow (Vorlauf)";
const chart1LineYAxisTitle = "Temperature (°C)";

// Draw an empty line chart
const lineChartApex = drawEmptyLineChartAC(
  chart1LineHTML,
  chart1LineTitle,
  chart1LineYAxisTitle
);
lineChartApex.render();

/**
 * Update an empty chart created using Apexcharts library
 * @param {String} chartName
 * @param {Array} dataArr
 * @returns {void}
 */
const updateLineChartAC = function (chartName, dataArr) {
  const CHART_NAME = chartName;
  // Update the chart
  lineChartApex.updateSeries([
    {
      name: CHART_NAME,
      data: dataArr,
    },
  ]);
};

/**
 * Draw a heatmap using the ApexCharts library
 * ATTEMPT 1
 * @param {Array} obsArray - Response from SensorThings API as array
 * @returns {void}
 */
const drawHeatMapAC1 = function (obsArray) {
  // Chart constants
  const CHART_HEATMAP_TITLE = "HeatMap Chart";
  const CHART_HEATMAP_NAME_SERIES_1 = "VL-225";
  // const CHART_HEATMAP_NAME_SERIES_2 = "W2";

  /**
   * Convert SensorThings API response (an array) into an object
   * @returns {Object} - Chart series object
   */
  const generateHeatMapData = function () {
    const series = [];
    obsArray.forEach(([obsTime, obsValue]) => {
      series.push({
        x: obsTime.slice(0, -1), // remove trailing "Z" from timestamp
        y: obsValue,
      });
    });
    return series;
  };

  const data = [
    {
      name: CHART_HEATMAP_NAME_SERIES_1,
      data: generateHeatMapData(obsArray),
    },
    // {
    //   name: CHART_HEATMAP_NAME_SERIES_2,
    //   data: generateHeatMapData(obsArray),
    // },
  ];

  data.reverse();

  const colors = [
    "#F3B415",
    "#F27036",
    "#663F59",
    "#6A6E94",
    "#4E88B4",
    "#00A7C6",
    "#18D8D8",
    "#A9D794",
    "#46AF78",
    "#A93F55",
    "#8C5E58",
    "#2176FF",
    "#33A1FD",
    "#7A918D",
    "#BAFF29",
  ];

  // colors.reverse();

  const options = {
    series: data,
    chart: {
      height: 350,
      type: "heatmap",
    },
    dataLabels: {
      enabled: false,
    },
    colors: colors,

    title: {
      text: CHART_HEATMAP_TITLE,
    },
    grid: {
      padding: {
        right: 20,
      },
    },
    xaxis: {
      type: "datetime",
    },
    tooltip: {
      shared: false,
      x: {
        formatter: function (val) {
          return new Date(val).toLocaleString();
        },
      },
      y: {
        formatter: function (val) {
          return val.toFixed(2);
        },
      },
    },
    plotOptions: {
      heatmap: {
        useFillColorAsStroke: true, // we need this option for the chart to be visible
        // distributed: true,
        // enableShades: false,
      },
    },
  };

  const chart = new ApexCharts(
    document.querySelector("#chart-apex-heatmap"),
    options
  );
  chart.render();
};

/**
 * Draw a heatmap using the ApexCharts library
 * ATTEMPT 2
 * @param {Array} obsArray - Response from SensorThings API as array
 * @returns {void}
 */
const drawHeatMapAC2 = function (obsArray) {
  // Chart constants
  const CHART_HEATMAP_TITLE = "HeatMap Chart";
  const CHART_HEATMAP_NAME_SERIES_1 = "VL-225";

  /**
   * Convert SensorThings API response (an array) into an object
   * @returns {Object} - Chart series object
   */
  const generateHeatMapData = function () {
    const series = [];
    obsArray.forEach(([obsTime, obsValue]) => {
      series.push({
        x: obsTime.slice(0, -1), // remove trailing "Z" from timestamp
        y: obsValue,
      });
    });
    return series;
  };

  const data = [
    {
      name: CHART_HEATMAP_NAME_SERIES_1,
      data: generateHeatMapData(obsArray),
    },
    // {
    //   name: CHART_HEATMAP_NAME_SERIES_2,
    //   data: generateHeatMapData(obsArray),
    // },
  ];

  // Constants for our data range
  const LOW_FROM = 65;
  const LOW_TO = 70;
  const MEDIUM_FROM = 70;
  const MEDIUM_TO = 75;
  const HIGH_FROM = 75;
  const HIGH_TO = 80;
  const EXTREME_FROM = 80;
  const EXTREME_TO = 85;
  const options = {
    series: data,
    chart: {
      height: 450,
      type: "heatmap",
    },
    plotOptions: {
      heatmap: {
        shadeIntensity: 0.5,
        radius: 0,
        useFillColorAsStroke: true,
        colorScale: {
          ranges: [
            {
              from: null,
              to: null,
              name: "null",
              color: "#525252",
            },
            {
              from: LOW_FROM,
              to: LOW_TO,
              name: `${LOW_FROM}°C`,
              color: "#1a9641",
            },
            {
              from: MEDIUM_FROM,
              to: MEDIUM_TO,
              name: `${MEDIUM_FROM}°C`,
              color: "#a6d96a",
            },
            {
              from: HIGH_FROM,
              to: HIGH_TO,
              name: `${HIGH_FROM}°C`,
              color: "#fdae61",
            },
            {
              from: EXTREME_FROM,
              to: EXTREME_TO,
              name: `${EXTREME_FROM}°C`,
              color: "#d7191c",
            },
          ],
        },
      },
    },
    dataLabels: {
      enabled: false,
    },
    stroke: {
      width: 1,
    },
    title: {
      text: CHART_HEATMAP_TITLE,
    },
    grid: {
      padding: {
        right: 20,
      },
    },
    xaxis: {
      type: "datetime",
      // labels: {
      //   format: "MMM",
      // },
    },
    tooltip: {
      shared: false,
      x: {
        formatter: function (val) {
          return new Date(val).toLocaleString();
        },
      },
      y: {
        formatter: function (val) {
          if (val) {
            return val.toFixed(2);
          } else {
            return "null";
          }
        },
      },
    },
    // distributed: true,
  };
Pithon Kabiro's avatar
Pithon Kabiro committed
370

Pithon Kabiro's avatar
Pithon Kabiro committed
371
372
373
374
  const chart = new ApexCharts(
    document.querySelector("#chart-apex-heatmap"),
    options
  );
Pithon Kabiro's avatar
Pithon Kabiro committed
375
376
377
378
  chart.render();
};

/**
Pithon Kabiro's avatar
Pithon Kabiro committed
379
 * Follows "@iot.nextLink" links in SensorThingsAPI's response
Pithon Kabiro's avatar
Pithon Kabiro committed
380
 * Appends new results to existing results
Pithon Kabiro's avatar
Pithon Kabiro committed
381
382
383
 * @async
 * @param {Object} responsePromise - Promise object
 * @returns {Object} - Object containing results from all the "@iot.nextLink" links
Pithon Kabiro's avatar
Pithon Kabiro committed
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
 */
const followNextLink = function (responsePromise) {
  return responsePromise
    .then(function (lastSuccess) {
      if (lastSuccess.data["@iot.nextLink"]) {
        return followNextLink(
          axios.get(lastSuccess.data["@iot.nextLink"])
        ).then(function (nextLinkSuccess) {
          nextLinkSuccess.data.value = lastSuccess.data.value.concat(
            nextLinkSuccess.data.value
          );
          return nextLinkSuccess;
        });
      } else {
        return lastSuccess;
      }
    })
    .catch(function (err) {
      console.log(err);
    });
};

// Get "ALL" the Observations that satisfy our query
followNextLink(
  axios.get(BASE_URL, {
    params: {
      "$resultFormat": PARAM_RESULT_FORMAT,
      "$orderBy": PARAM_ORDER_BY,
      "$filter": PARAM_FILTER,
      "$select": PARAM_SELECT,
    },
  })
)
  .then((success) => {
    const successValue = success.data.value;

    // Array that will hold the combined observations
    const combinedObservations = [];

    successValue.forEach((dataObj) => {
      // Each page of results will have a dataArray that holds the observations
      const dataArrays = dataObj.dataArray;

      combinedObservations.push(...dataArrays);
    });
    // DEBUG: Check total number of observations
    console.log(combinedObservations.length);
Pithon Kabiro's avatar
Pithon Kabiro committed
431
432
    // DEBUG: Print the array of observations
    console.log(combinedObservations);
Pithon Kabiro's avatar
Pithon Kabiro committed
433
434
435
436
437
438
439

    return combinedObservations;
  })
  .catch((err) => {
    console.log(err);
  })
  .then((observationArr) => {
440
    // updateLineChartAC(chart1LineTitle, observationArr);
Sven Schneider's avatar
minor    
Sven Schneider committed
441
    // drawHeatMapAC2(observationArr);
442
443

    ///////////// use chart.js for line chart
444
445
///// check this out : https://stackoverflow.com/questions/57343566/zoom-function-for-chart-js 
    ////////////////////////////////
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467

    function renameKey(obj, oldKey, newKey) {
      obj[newKey] = obj[oldKey];
      delete obj[oldKey];
    }

    function convertArray2JSON(arr) {
      var arrayToString = JSON.stringify(Object.assign({}, arr)); // convert array to string
      var stringToJsonObject = JSON.parse(arrayToString); // convert string to json object
      return stringToJsonObject;
    }

    let jsonFromArr = [];
    for (var i = 0; i < observationArr.length; i++) {
      jsonFromArr.push(convertArray2JSON(observationArr[i]));
    }

    jsonFromArr.forEach((obj) => renameKey(obj, "0", "x"));
    let jsonFromArr2 = jsonFromArr;
    jsonFromArr2.forEach((obj) => renameKey(obj, "1", "y"));
        

468
469
470
    let datx=[];
    let daty=[];
    const MONTH = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
471

472
473
474
475
476
477
478
479
480
    for (var u = 0; u<jsonFromArr.length ; u++){
       daty.push(jsonFromArr2[u].y);
       let date = new Date(jsonFromArr2[u].x);
       let datum = date.getDate();
       let month = MONTH[date.getMonth()];
       let hour = date.getHours() + ":00";
       let newDateStr = datum + "/" + month + "-" + hour;
       datx.push(newDateStr);
       }
481
482
483



484
485
486
487
    // $('#reset_zoom').click(function(){
    //   scatterChart.resetZoom();
    //   console.log(scatterChart);
    // });
488

489
490
491
    // $('#disable_zoom').click(function(){
    //   scatterChart.ctx.canvas.removeEventListener('wheel', scatterChart._wheelHandler);
    // });
492

493
494
495
    // $('#enable_zoom').click(function(){
    //   scatterChart.ctx.canvas.addEventListener('wheel', scatterChart._wheelHandler);
    // });
496

497
    //////////////////////////////////////////
498

499
500
//     const chart1LineTitle = "Inlet flow (Vorlauf)";
// const chart1LineYAxisTitle = "Temperature (°C)";
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
    
    const inflowChart = new Chart('inflowChartCanvas', {
      type: 'line',
      data: {
        labels: datx,
        datasets: [{
          label: 'Inflow Temperature in °C',
          data: daty,
          fill: false,
          borderColor: 'rgb(75, 192, 192,0.3)',
          backgroundColor: 'rgba(153, 102, 255, 0.2)',             
          // tension: 0.1
        }]
      },
     
      options: {
        // responsive: true,
        scales: {
					xAxes: [{
						display: true,
						scaleLabel: {
							display: true,
							labelString: 'Month'
						}
					}],
					yAxes: [{
						display: true,
						scaleLabel: {
							display: true,
							labelString: 'Value'
						}
					}]
				},
      
        plugins: {
        //   title: {
        //     display: true,
        //     text: 'Inlet Flow Temperature'
        // },
        
        
          zoom: {
            pan: {
              // Boolean to enable panning
              enabled: true,
    
              // Panning directions. Remove the appropriate direction to disable
              // Eg. 'y' would only allow panning in the y direction
              mode: "xy",
    
              speed: 1,
            },
            zoom: {
              wheel: {
                enabled: true,
              },
              pinch: {
                enabled: false
              },
              mode: 'x',
            }
          }          
          
        }  // end of plugins
      }   // end of options
    });
568

569
570
571
    $('#reset_zoom').click(function(){
      inflowChart.resetZoom();      
    });
572

573
    // drawHeatMapAC2(observationArr);
574

575
576
577
578
579
580
581
582
583
584
585
586
587
588
    var loadJS = function(url, implementationCode, location){
      //url is URL of external file, implementationCode is the code
      //to be called from the file, location is the location to 
      //insert the <script> element
  
      var scriptTag = document.createElement('script');
      scriptTag.src = url;
  
      scriptTag.onload = implementationCode;
      scriptTag.onreadystatechange = implementationCode;
  
      location.appendChild(scriptTag);
  };
 
589
590
591
   
  loadJS('js/createPlotlyPlots.js', makeRibbonPlot(jsonFromArr2), document.body);  
  makeHeatmap(jsonFromArr2);
592
593
  makeBoxplot(jsonFromArr2);
  makeLinePlot(jsonFromArr2);
594
595
596
  

    ///////////////////////////////////////
597
  }); // this closes the followLink.then ({ .... })