aggregation.js 6.13 KB
Newer Older
1
2
3
4
5
6
7
8
/**
 * 
 * @param {JSON} obj JSON object on which to replace a specific key. 
 * @param {String} oldKey is the old key in the JSON to be renamed to newKey
 * @param {String} newKey is the key that should replace the oldKey
 * usage: myjson.forEach((obj) => renameKey(obj, "oldkey", "newkey"));
 */

9
function renameKey(obj, oldKey, newKey) {
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
    obj[newKey] = obj[oldKey];
    delete obj[oldKey];
}


/**
 * 
 * @param {Array} arr is the Array to be converted into a JSON
 * @returns {JSON} stringToJsonObject 
 */
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;
}


/**
 * Format the response from SensorThings API to make it suitable for heatmap
 * @param {Array} obsArray Response from SensorThings API as array
 * @param {Int8} hours Number of hours to aggregate over. If hours=0, 
 * it will be aggregated by date (e.g. all values recorded on 1st of May etc...) 
 * if hours to any number (also hours=24) data will be aggregated over every 24hours, 
 * even if the date changes (e.g. data from 1st of May from 10pm up 9pm on 2nd of May etc.)
 * @param {String} method Specify how to aggregate date. Use: 'mean' = default, 'sum', 'min' or 'max'
 * @returns {Array} Aggregated Response
 */

export const aggregateResponse = function(obsArray, hours, method) {
    if (!obsArray) return;
    if (hours < 0) return;

    // check if we have a defined method or the method specified is accepted, rest is handeled in switch/case below
    if (method == undefined) method = 'mean';


    // convert obsArray to json

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

    // rename the keys in the jason
    jsonFromArr.forEach((obj) => renameKey(obj, "0", "datetime"));
    let jsonData = jsonFromArr;
    jsonData.forEach((obj) => renameKey(obj, "1", "temperature"));


    let newOutput = [];
    var aggDates = [];
    var aggregatedVals = [];
    var vals = []; // store values temporarily to use for processing

    if (hours == 0) { // i.e. aggregate over one Date / Day

        var currentDate;
        var oldDate;
        for (var d = 0; d < jsonData.length; d++) {
            let tmpDate = new Date(jsonData[d].datetime);
            currentDate = tmpDate.getDate(); // gets the day of the month 1...31
            if (d === 0) oldDate = currentDate;

            if (currentDate == oldDate) {
                vals.push(jsonData[d].temperature);
            } else {
                aggDates.push(new Date(tmpDate - 1));

                if (vals.length == 0) {
                    aggregatedVals.push(-1);
                    oldDate = currentDate;
                    continue;
                }

                switch (method) {
                    case 'mean':
Sven Schneider's avatar
minor    
Sven Schneider committed
86
                        aggregatedVals.push(vals.reduce(function(a, b) { return a + b / vals.length; }, -1));
87
88
                        break;
                    case 'sum':
Sven Schneider's avatar
minor    
Sven Schneider committed
89
                        aggregatedVals.push(vals.reduce(function(a, b) { return a + b; }, -1));
90
91
92
93
94
95
96
97
                        break;
                    case 'min':
                        aggregatedVals.push(vals.reduce(function(a, b) { return Math.min(a, b); }));
                        break;
                    case 'max':
                        aggregatedVals.push(vals.reduce(function(a, b) { return Math.max(a, b); }));
                        break;
                    default:
98
                        aggregatedVals.push(vals.reduce(function(a, b) { return a + b / vals.length; }, -1));
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
                }
                vals = []; // clear the daily value vector 
                vals.push(jsonData[d].temperature); // now push first entry of new day into my temp value vector.
            }
            oldDate = currentDate;
        } // end of for loop

        // create output to be in the same List format as the original data from obsArray.

        for (let i = 0; i < aggregatedVals.length; i++) {
            newOutput.push([aggDates[i].toISOString(), aggregatedVals[i]]);
        }

    } else { // i.e. aggregate over X hours, irrespective of the day.
        let cnt = 0;
        let cumHours = 0;

        for (var d = 0; d < jsonData.length; d++) {
            if (cnt < hours) {
                vals.push(jsonData[d].temperature);
                cnt++;
            } else {
                cumHours += cnt;
                cnt = 0;
                aggDates.push(cumHours);

                if (vals.length == 0) {
                    aggregatedVals.push(-1);
                    continue;
                }

                switch (method) {
                    case 'mean':
Sven Schneider's avatar
minor    
Sven Schneider committed
132
                        aggregatedVals.push(vals.reduce(function(a, b) { return a + b / vals.length; }, -1));
133
134
                        break;
                    case 'sum':
Sven Schneider's avatar
minor    
Sven Schneider committed
135
                        aggregatedVals.push(vals.reduce(function(a, b) { return a + b; }, -1));
136
137
                        break;
                    case 'min':
Sven Schneider's avatar
minor    
Sven Schneider committed
138
                        aggregatedVals.push(vals.reduce(function(a, b) { return Math.min(a, b); }, ));
139
140
                        break;
                    case 'max':
Sven Schneider's avatar
minor    
Sven Schneider committed
141
                        aggregatedVals.push(vals.reduce(function(a, b) { return Math.max(a, b); }, ));
142
143
                        break;
                    default:
144
                        aggregatedVals.push(vals.reduce(function(a, b) { return a + b / vals.length; }, -1));
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
                }
                vals = []; // clear the daily value vector 
                vals.push(jsonData[d].temperature); // now push first entry of new day into my temp value vector.
                cnt++;
            }
            oldDate = currentDate;
        } // end of for loop
        // create output to be in the same List format as the original data from obsArray.

        for (let i = 0; i < aggregatedVals.length; i++) {
            newOutput.push([aggDates[i], aggregatedVals[i]]);
        }
    } // end else


160
161
162
163
164
165
166
    // return newOutput;
    return {
        originalFormat: newOutput,
        aggDates: aggDates,
        aggVals: aggregatedVals
    };
}