-
Notifications
You must be signed in to change notification settings - Fork 96
/
Copy pathwidget-glad-alerts-selectors.js
283 lines (268 loc) · 7.84 KB
/
widget-glad-alerts-selectors.js
1
2
3
4
5
6
7
8
9
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
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
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
import { createSelector } from 'reselect';
import isEmpty from 'lodash/isEmpty';
import { format } from 'd3-format';
import meanBy from 'lodash/meanBy';
import mean from 'lodash/mean';
import groupBy from 'lodash/groupBy';
import upperCase from 'lodash/upperCase';
import maxBy from 'lodash/maxBy';
import minBy from 'lodash/minBy';
import concat from 'lodash/concat';
import moment from 'moment';
import { getColorPalette } from 'utils/data';
const MIN_YEAR = 2015;
// get list data
const getAlerts = state => state.alerts || null;
const getLatestDates = state => state.latest || null;
const getSettings = state => state.settings || null;
const getColors = state => state.colors || null;
const getActiveData = state => state.activeData || null;
const getYearsObj = (data, startSlice, endSlice) => {
const grouped = groupBy(data, 'year');
return Object.keys(grouped).map(key => ({
year: key,
weeks: grouped[key].slice(
startSlice < 0 ? grouped[key].length + startSlice : startSlice,
endSlice < 0 ? grouped[key].length : endSlice
)
}));
};
const meanData = data => {
const means = [];
data.forEach(w => {
w.weeks.forEach((y, i) => {
means[i] = means[i] ? [...means[i], y.count] : [y.count];
});
});
return means.map(w => mean(w));
};
const runningMean = (data, windowSize) => {
const smoothedMean = [];
data.forEach((d, i) => {
const slice = data.slice(i, i + windowSize);
if (i < data.length - windowSize + 1) {
smoothedMean.push(mean(slice));
}
});
return smoothedMean;
};
export const getData = createSelector(
[getAlerts, getLatestDates],
(data, latest) => {
if (!data || isEmpty(data)) return null;
const groupedByYear = groupBy(data, 'year');
const years = [];
const latestFullWeek = moment(latest).subtract(1, 'weeks');
const lastWeek = {
isoWeek: latestFullWeek.isoWeek(),
year: latestFullWeek.year()
};
for (let i = MIN_YEAR; i <= lastWeek.year; i += 1) {
years.push(i);
}
const yearLengths = {};
years.forEach(y => {
const lastIsoWeek =
lastWeek.year !== parseInt(y, 10)
? moment(`${y}-12-31`).isoWeek()
: lastWeek.isoWeek;
yearLengths[y] = lastIsoWeek;
});
const zeroFilledData = [];
years.forEach(d => {
const yearDataByWeek = groupBy(groupedByYear[d], 'week');
for (let i = 1; i <= yearLengths[d]; i += 1) {
zeroFilledData.push(
yearDataByWeek[i]
? yearDataByWeek[i][0]
: { count: 0, week: i, year: parseInt(d, 10) }
);
}
});
return zeroFilledData;
}
);
export const getMeans = createSelector([getData], data => {
if (!data) return null;
const minYear = minBy(data, 'year').year;
const maxYear = maxBy(data, 'year').year;
const grouped = groupBy(data, 'week');
const centralMeans = Object.keys(grouped).map(d => {
const weekData = grouped[d];
return meanBy(weekData, 'count');
});
const leftYears = data.filter(d => d.year !== maxYear);
const rightYears = data.filter(d => d.year !== minYear);
const leftMeans = meanData(getYearsObj(leftYears, -6));
const rightMeans = meanData(getYearsObj(rightYears, 0, 6));
const allMeans = concat(leftMeans, centralMeans, rightMeans);
const smoothedMeans = runningMean(allMeans, 12);
const pastYear = data.slice(-52);
const parsedData = pastYear.map((d, i) => ({
...d,
mean: smoothedMeans[i]
}));
return parsedData;
});
export const getStdDev = createSelector(
[getMeans, getData],
(data, rawData) => {
if (!data) return null;
const stdDevs = [];
const centralMeans = data.map(d => d.mean);
const groupedByYear = groupBy(rawData, 'year');
const meansFromGroup = Object.keys(groupedByYear).map(key =>
groupedByYear[key].map(d => d.count)
);
for (let i = 0; i < centralMeans.length; i += 1) {
meansFromGroup.forEach(m => {
const value = m[i] || 0;
const some =
value && centralMeans[i] ? (centralMeans[i] - value) ** 2 : null;
stdDevs[i] = stdDevs[i] ? [...stdDevs[i], some] : [some];
});
}
const stdDev = mean(stdDevs.map(s => mean(s) ** 0.5));
return data.map(d => ({
...d,
plusStdDev: [d.mean, d.mean + stdDev],
minusStdDev: [d.mean - stdDev, d.mean],
twoPlusStdDev: [d.mean + stdDev, d.mean + stdDev * 2],
twoMinusStdDev: [d.mean - stdDev * 2, d.mean - stdDev]
}));
}
);
export const getDates = createSelector([getStdDev], data => {
if (!data) return null;
return data.map(d => ({
...d,
date: moment()
.year(d.year)
.week(d.week)
.format('YYYY-MM-DD'),
month: upperCase(
moment()
.year(d.year)
.week(d.week)
.format('MMM')
)
}));
});
export const chartData = createSelector(
[getDates, getSettings],
(data, settings) => {
if (!data) return null;
return data.slice(-settings.weeks);
}
);
export const chartConfig = createSelector(
[getColors, chartData],
(colors, data) => {
if (!data) return null;
const lastDate = data[data.length - 1].date;
const ticks = [];
while (ticks.length < 12) {
ticks.push(
parseInt(
moment(lastDate)
.subtract(ticks.length, 'months')
.format('Mo'),
10
)
);
}
return {
xKey: 'date',
yKeys: {
lines: {
count: {
stroke: colors.main
}
},
areas: {
plusStdDev: {
fill: '#555555',
stroke: '#555555',
opacity: 0.1,
strokeWidth: 0,
background: false,
activeDot: false
},
minusStdDev: {
fill: '#555555',
stroke: '#555555',
opacity: 0.1,
strokeWidth: 0,
background: false,
activeDot: false
},
twoPlusStdDev: {
fill: '#555555',
stroke: '#555555',
opacity: 0.2,
strokeWidth: 0,
background: false,
activeDot: false
},
twoMinusStdDev: {
fill: '#555555',
stroke: '#555555',
opacity: 0.2,
strokeWidth: 0,
background: false,
activeDot: false
}
}
},
xAxis: {
tickCount: 12,
interval: 4,
tickFormatter: t => moment(t).format('MMM')
},
yAxis: {
domain: [0, 'auto'],
allowDataOverflow: true
}
};
}
);
export const getSentence = createSelector(
[chartData, getColors, getActiveData],
(data, colors, activeData) => {
if (!data) return null;
let lastDate = data[data.length - 1];
if (!isEmpty(activeData)) {
lastDate = activeData;
}
const colorRange = getColorPalette(colors.ramp, 5);
let statusColor = colorRange[4];
let status = 'unusually low';
if (lastDate.count > lastDate.twoPlusStdDev[1]) {
status = 'unusually high';
statusColor = colorRange[0];
} else if (
lastDate.count <= lastDate.twoPlusStdDev[1] &&
lastDate.count > lastDate.twoPlusStdDev[0]
) {
status = 'high';
statusColor = colorRange[1];
} else if (
lastDate.count <= lastDate.plusStdDev[1] &&
lastDate.count > lastDate.minusStdDev[0]
) {
status = 'normal';
statusColor = colorRange[2];
} else if (
lastDate.count >= lastDate.twoMinusStdDev[0] &&
lastDate.count < lastDate.twoMinusStdDev[1]
) {
status = 'low';
statusColor = colorRange[3];
}
const date = moment(lastDate.date).format('Do of MMMM YYYY');
return `There were <b style="color: ${colors.main}">${format(',')(
lastDate.count
)}</b> GLAD alerts reported in the week of the <b>${date}</b>. This was
<b style="color: ${statusColor}">${status}</b> compared to the same week in previous years.`;
}
);