chartHeatmap.mjs 5.59 KB
Newer Older
1
2
"use strict";

3
4
5
6
7
import {
  chartExportOptions,
  createTitleForHeatmap,
  createSubtitleForHeatmap,
} from "./chartHelpers.mjs";
8

9
10
11
12
13
14
15
16
/**
 * Format the response from SensorThings API to make it suitable for use in a heatmap
 * @param {Array} obsArray Array of observations (timestamp + value) that is response from SensorThings API
 * @returns {Array} Array of formatted observations suitable for use in a heatmap
 */
const formatSensorThingsApiResponseForHeatMap = function (obsArray) {
  if (!obsArray) return;

Pithon Kabiro's avatar
Pithon Kabiro committed
17
  return obsArray.map((obs) => {
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
    // Get the date/time string; first element in input array; remove trailing "Z"
    const obsDateTimeInput = obs[0].slice(0, -1);
    // Get the "date" part of an observation
    const obsDateInput = obs[0].slice(0, 10);
    // Create Date objects
    const obsDateTime = new Date(obsDateTimeInput);
    const obsDate = new Date(obsDateInput);
    // x-axis -> timestamp; will be the same for observations from the same date
    const timestamp = Date.parse(obsDate);
    // y-axis -> hourOfDay
    const hourOfDay = obsDateTime.getHours();
    // value -> the observation's value; second element in input array
    const value = obs[1];
    return [timestamp, hourOfDay, value];
  });
};

/**
 * Calculate the minimum and maximum values for a heatmap's color axis
 * @param {Array} formattedObsArrHeatmap Response from SensorThings API formatted for use in a heatmap
 * @returns {Object} An object containing the minimum and maximum values
 */
const calculateMinMaxValuesForHeatmapColorAxis = function (
  formattedObsArrHeatmap
) {
  // The observation value is the third element in array
  const obsValueArr = formattedObsArrHeatmap.map((obs) => obs[2]);

  // Extract integer part
  const minValue = Math.trunc(Math.min(...obsValueArr));
  const maxValue = Math.trunc(Math.max(...obsValueArr));

  // Calculate the closest multiple of 5
51
52
  const minObsValue =
    minValue > 0 ? minValue - (minValue % 5) : minValue + (minValue % 5);
53
54
55
56
57
58
59
  const maxObsValue = maxValue + (5 - (maxValue % 5));

  return { minObsValue, maxObsValue };
};

/**
 * Draw a heatmap using Highcharts library
60
 * @param {Array} formattedObsArrayForHeatmap Response from SensorThings API formatted for use in a heatmap. Currently, only raw observations are supported, i.e. no aggregation
Pithon Kabiro's avatar
Pithon Kabiro committed
61
 * @param {Object} extractedFormattedDatastreamProperties An object that contains arrays of formatted Datastream properties
62
63
64
65
 * @returns {undefined} undefined
 */
const drawHeatMapHighcharts = function (
  formattedObsArrayForHeatmap,
Pithon Kabiro's avatar
Pithon Kabiro committed
66
  extractedFormattedDatastreamProperties
67
) {
Pithon Kabiro's avatar
Pithon Kabiro committed
68
  // Arrays of datastream properties
69
  const {
Pithon Kabiro's avatar
Pithon Kabiro committed
70
71
72
73
74
75
76
77
78
79
    datastreamDescriptionsArr,
    datastreamNamesArr,
    phenomenonNamesArr,
    unitOfMeasurementSymbolsArr,
  } = extractedFormattedDatastreamProperties;

  const [DATASTREAM_DESCRIPTION] = datastreamDescriptionsArr;
  const [DATASTREAM_NAME] = datastreamNamesArr;
  const [PHENOMENON_NAME] = phenomenonNamesArr;
  const [PHENOMENON_SYMBOL] = unitOfMeasurementSymbolsArr;
80

81
82
83
84
  const TEXT_CHART_TITLE = createTitleForHeatmap(phenomenonNamesArr);

  const TEXT_CHART_SUBTITLE = createSubtitleForHeatmap(datastreamNamesArr);

85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
  const {
    minObsValue: MINIMUM_VALUE_COLOR_AXIS,
    maxObsValue: MAXIMUM_VALUE_COLOR_AXIS,
  } = calculateMinMaxValuesForHeatmapColorAxis(formattedObsArrayForHeatmap);

  Highcharts.chart("chart-heatmap", {
    chart: {
      type: "heatmap",
      zoomType: "x",
    },

    boost: {
      useGPUTranslations: true,
    },

    title: {
101
      text: TEXT_CHART_TITLE,
102
      align: "center",
103
104
105
106
      x: 40,
    },

    subtitle: {
107
      text: TEXT_CHART_SUBTITLE,
108
      align: "center",
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
      x: 40,
    },

    xAxis: {
      type: "datetime",
      // min: Date.UTC(2017, 0, 1),
      // max: Date.UTC(2017, 11, 31, 23, 59, 59),
      labels: {
        align: "left",
        x: 5,
        y: 14,
        format: "{value:%B}", // long month
      },
      showLastLabel: false,
      tickLength: 16,
    },

    yAxis: {
      title: {
        text: null,
      },
      labels: {
        format: "{value}:00",
      },
      minPadding: 0,
      maxPadding: 0,
      startOnTick: false,
      endOnTick: false,
      tickPositions: [0, 3, 6, 9, 12, 15, 18, 21, 24],
      tickWidth: 1,
      min: 0,
      max: 23,
      reversed: true,
    },

    colorAxis: {
      stops: [
        [0, "#3060cf"],
        [0.5, "#fffbbc"],
        [0.9, "#c4463a"],
        [1, "#c4463a"],
      ],
      min: MINIMUM_VALUE_COLOR_AXIS,
      max: MAXIMUM_VALUE_COLOR_AXIS,
      startOnTick: false,
      endOnTick: false,
      labels: {
        format: `{value}${PHENOMENON_SYMBOL}`,
      },
    },

160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
    exporting: chartExportOptions,

    tooltip: {
      formatter() {
        const headerString = `${PHENOMENON_NAME}<br/>`;

        // Check whether the point value is null or not; this will determine the string that we'll render
        const pointString =
          this.point.value === null
            ? `${Highcharts.dateFormat("%e %b, %Y", this.point.x)} ${
                this.point.y
              }:00:00 <b>null</b>`
            : `${Highcharts.dateFormat("%e %b, %Y", this.point.x)} ${
                this.point.y
              }:00:00 <b>${this.point.value.toFixed(
                2
              )} ${PHENOMENON_SYMBOL}</b>`;

        return headerString + pointString;
      },
    },

182
183
184
185
186
187
188
189
190
191
192
193
194
195
    series: [
      {
        data: formattedObsArrayForHeatmap,
        boostThreshold: 100,
        borderWidth: 0,
        nullColor: "#525252",
        colsize: 24 * 36e5, // one day
        turboThreshold: Number.MAX_VALUE, // #3404, remove after 4.0.5 release
      },
    ],
  });
};

export { formatSensorThingsApiResponseForHeatMap, drawHeatMapHighcharts };