aggregation.js 7.19 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
    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;
}


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
/**
 * 
 * @param {Array} array containing dates of type Date
 * @param {Date} date date to look for in array 
 * @returns postition of the array where the date was matched
 */

export const whereIsDateInArray = function(array, date) {

    const DAY = date.getDate();
    const MONTH = date.getMonth();
    var pos = -1;

    for (var i = 0; i < array.length; i++) {
        var day = array[i].getDate();
        var month = array[i].getMonth();

        if (day === DAY && MONTH === month) {
            pos = i;
        }
    }
    return pos;

}


/**
 * Converts the date string from DD.MM.YYYY obtained from HTML date picker to -> MM.DD.YYYY
 * @param {String} selctedDate containing a date string in the format DD.MM.YYYY
 * @returns {String} of the provided date in the format MM.DD.YYYY
 */
export const switchDayMonth_inDate = function(selectedDate) {


    var splitedString = selectedDate.split('.');
    var newDate = [];
    newDate.push(splitedString[1]);
    newDate.push(splitedString[0]);
    newDate.push(splitedString[2]);
    return newDate.join('.');;
}


70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
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
/**
 * 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
129
                        aggregatedVals.push(vals.reduce(function(a, b) { return a + b / vals.length; }, -1));
130
131
                        break;
                    case 'sum':
Sven Schneider's avatar
minor    
Sven Schneider committed
132
                        aggregatedVals.push(vals.reduce(function(a, b) { return a + b; }, -1));
133
134
135
136
137
138
139
140
                        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:
141
                        aggregatedVals.push(vals.reduce(function(a, b) { return a + b / vals.length; }, -1));
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
                }
                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
175
                        aggregatedVals.push(vals.reduce(function(a, b) { return a + b / vals.length; }, -1));
176
177
                        break;
                    case 'sum':
Sven Schneider's avatar
minor    
Sven Schneider committed
178
                        aggregatedVals.push(vals.reduce(function(a, b) { return a + b; }, -1));
179
180
                        break;
                    case 'min':
Sven Schneider's avatar
minor    
Sven Schneider committed
181
                        aggregatedVals.push(vals.reduce(function(a, b) { return Math.min(a, b); }, ));
182
183
                        break;
                    case 'max':
Sven Schneider's avatar
minor    
Sven Schneider committed
184
                        aggregatedVals.push(vals.reduce(function(a, b) { return Math.max(a, b); }, ));
185
186
                        break;
                    default:
187
                        aggregatedVals.push(vals.reduce(function(a, b) { return a + b / vals.length; }, -1));
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
                }
                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


203
204
205
206
207
208
209
    // return newOutput;
    return {
        originalFormat: newOutput,
        aggDates: aggDates,
        aggVals: aggregatedVals
    };
}