-
Notifications
You must be signed in to change notification settings - Fork 0
/
openMeteoInterface.tsx
318 lines (285 loc) · 16 KB
/
openMeteoInterface.tsx
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
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
import { formState, getWeekNumber, inputState, median, medianY, months, myColors, visualizationModes } from "./utils";
import styles from '../styles/form.module.css'
/**
*
* @returns Historical data for the current state of the form
*/
async function getHistoricalData(latitude: number, longitude: number, startDate: string, endDate: string) {
const res = await fetch(`https://archive-api.open-meteo.com/v1/archive?latitude=${latitude}&longitude=${longitude}&start_date=${startDate}&end_date=${endDate}&daily=temperature_2m_max,temperature_2m_min,temperature_2m_mean,precipitation_sum&timezone=Europe%2FBerlin`);
const msg = await res.json();
return msg;
}
/**
*
* @returns Recent data (past 5 days) for the current state of the form
*/
async function getRecentData(latitude: number, longitude: number) {
const res = await fetch(`https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}&daily=temperature_2m_max,temperature_2m_min,precipitation_sum&past_days=7&forecast_days=1&timezone=Europe%2FBerlin`);
const msg = await res.json();
return msg;
}
/**
* This fails to visualize for big timespans. Also we dont really need it as it is implemented in many other apps
*/
export async function getOpenMeteoData(inputState: inputState, state: formState, setState: React.Dispatch<React.SetStateAction<formState>>) {
const now = Date.now()
const todaysDate = now - (now % 86400000)
// First get the historical data
const msg = await getHistoricalData(inputState.latitude!, inputState.longitude!, inputState.startDate, inputState.endDate);
let min: any = [], max: any = [], mean: any = [], prec: any = []
msg.daily.time.forEach((k: string, i: number) => {
min.push({ x: new Date(k), y: parseFloat(msg.daily.temperature_2m_min[i]) })
max.push({ x: new Date(k), y: parseFloat(msg.daily.temperature_2m_max[i]) })
mean.push({ x: new Date(k), y: parseFloat(msg.daily.temperature_2m_mean[i]) })
prec.push({ x: new Date(k), y: parseFloat(msg.daily.precipitation_sum[i]) })
});
// Now if the end date is more recent than 7 days ago, also fetch the forecast data for the more recent dates
if (todaysDate - new Date(inputState.endDate).valueOf() <= 604800000) {
// calculate the date offset
const offset = (new Date(inputState.endDate).valueOf() - (todaysDate - 604800000)) / (1000 * 60 * 60 * 24)
const recentData = await getRecentData(inputState.latitude!, inputState.longitude!);
recentData.daily.time.forEach((k: string, i: number) => {
if (new Date(k).valueOf() < new Date(inputState.startDate).valueOf() || new Date(k).valueOf() > new Date(inputState.endDate).valueOf()) { // ignore the fetched data before the start date
return
}
const index = (-(offset + 1)) + i
min.at(index).y = parseFloat(recentData.daily.temperature_2m_min[i])
max.at(index).y = parseFloat(recentData.daily.temperature_2m_max[i])
// for forecast data we approximate the mean, which yields okay errors at daily measures (~1C)
mean.at(index).y = (max.at(index).y + min.at(index).y) / 2
prec.at(index).y = parseFloat(recentData.daily.precipitation_sum[i])
});
}
setState({
...state,
tempData: [max, mean, min, prec],
tempDataMedian: mean.map((e: any) => { return { x: e.x, y: medianY(mean).y } }),
crosshairValues: [],
keepCrosshair: false,
currentVisMode: visualizationModes.Interval,
formGeoString: `for ${msg.latitude.toFixed(2)}˚N ${msg.longitude.toFixed(2)}˚E at ${msg.elevation}m above sea level`,
//formTitle: `Daily Data between ${inputState.startDate} and ${inputState.endDate}.`
formTitle: <div className={styles.formTitle}><h1>Daily Data between
<p className={styles.highlightText} style={{ color: myColors.IconBlue }}>
{inputState.startDate}
</p>and
<p className={styles.highlightText} style={{ color: myColors.IconBlue }}>
{inputState.endDate}
</p>.
</h1>
</div>
})
}
export async function getDateHistory(inputState: inputState, state: formState, setState: React.Dispatch<React.SetStateAction<formState>>) {
const now = Date.now()
const todaysDate = now - (now % 86400000)
// First get the historical data
const msg = await getHistoricalData(inputState.latitude!, inputState.longitude!, inputState.startDate, inputState.endDate);
let min: any = [], max: any = [], mean: any = [], prec: any = []
msg.daily.time.forEach((k: string, i: number) => {
if (k.slice(5) === inputState.targetDate.slice(5)) {
min.push({ x: new Date(k), y: parseFloat(msg.daily.temperature_2m_min[i]) })
max.push({ x: new Date(k), y: parseFloat(msg.daily.temperature_2m_max[i]) })
mean.push({ x: new Date(k), y: parseFloat(msg.daily.temperature_2m_mean[i]) })
prec.push({ x: new Date(k), y: parseFloat(msg.daily.precipitation_sum[i]) })
}
});
// Now if the end date is more recent than 7 days ago, also fetch the forecast data for the more recent dates
if (todaysDate - new Date(inputState.endDate).valueOf() <= 604800000) {
const recentData = await getRecentData(inputState.latitude!, inputState.longitude!);
// add the recent data which will be the last entry of the arrays filled before
recentData.daily.time.forEach((k: string, i: number) => {
if (k.slice(5) === inputState.targetDate.slice(5)) {
min.at(-1).y = parseFloat(recentData.daily.temperature_2m_min[i])
max.at(-1).y = parseFloat(recentData.daily.temperature_2m_max[i])
// for forecast data we approximate the mean, which yields okay errors at daily measures (~1C)
mean.at(-1).y = (max.at(-1).y + min.at(-1).y) / 2
prec.at(-1).y = parseFloat(recentData.daily.precipitation_sum[i])
}
});
}
let avg = (mean.reduce((a: number, b: any) => a + (b.y || 0), 0) / mean.length)
setState({
...state,
tempData: [max, mean, min, prec],
tempDataMedian: mean.map((e: any) => { return { x: e.x, y: medianY(mean).y } }),
tempDataMean: mean.map((e: any) => { return { x: e.x, y: (avg || 0) } }),
crosshairValues: [],
keepCrosshair: false,
currentVisMode: visualizationModes.DateHistory,
formGeoString: `for ${msg.latitude.toFixed(2)}˚N ${msg.longitude.toFixed(2)}˚E at ${msg.elevation}m above sea level`,
//formTitle: `History of ${inputState.targetDate.slice(5)} between ${inputState.startDate} and ${inputState.endDate}.`
formTitle: <div className={styles.formTitle}><h1>History of
<p className={styles.highlightText} style={{ color: myColors.IconBlue }}>
{inputState.targetDate.slice(5)}
</p>
between
<p className={styles.highlightText} style={{ color: myColors.IconBlue }}>
{inputState.startDate}
</p>and
<p className={styles.highlightText} style={{ color: myColors.IconBlue }}>
{inputState.endDate}
</p>.
</h1>
</div>
})
}
export async function getWeekHistory(inputState: inputState, state: formState, setState: React.Dispatch<React.SetStateAction<formState>>) {
const now = Date.now()
const todaysDate = now - (now % 86400000)
// First get the historical data
const msg = await getHistoricalData(inputState.latitude!, inputState.longitude!, inputState.startDate, inputState.endDate);
let min: any = [], max: any = [], mean: any = [], prec: any = []
// get target week
const targetWeek = getWeekNumber(new Date(inputState.targetDate))[1]
for (let i = 0; i < msg.daily.time.length; i++) {
const k = msg.daily.time[i]
const weekInfo = getWeekNumber(new Date(k));
if (weekInfo[1] === targetWeek) {
let weekMinData = [], weekMaxData = [], weekMeanData = [], weekPrecData = []
for (let j = i; j < i + 7; j++) {
if (msg.daily.temperature_2m_min[j]) { // check if there is data. if not we just take the available data
weekMinData.push(parseFloat(msg.daily.temperature_2m_min[j]))
weekMaxData.push(parseFloat(msg.daily.temperature_2m_max[j]))
weekMeanData.push(parseFloat(msg.daily.temperature_2m_mean[j]))
weekPrecData.push(parseFloat(msg.daily.precipitation_sum[j]))
}
}
const xVal = new Date(k)
//const xVal = weekInfo[0]
min.push({ x: xVal, y: Math.min(...weekMinData) })
max.push({ x: xVal, y: Math.max(...weekMaxData) })
//mean.push({ x: xVal, y: (avg || undefined) })
mean.push({ x: xVal, y: weekMeanData })
prec.push({ x: xVal, y: weekPrecData })
i = i + 363
}
}
// Now if the end date is more recent than 7 days ago, also fetch the forecast data for the more recent dates
if (todaysDate - new Date(inputState.endDate).valueOf() <= 604800000) {
const recentData = await getRecentData(inputState.latitude!, inputState.longitude!);
// add the recent data which will be the last entry of the arrays filled before
recentData.daily.time.forEach((k: string, i: number) => {
if (new Date(k).valueOf() < new Date(inputState.startDate).valueOf()) {
return;
}
const weekInfo = getWeekNumber(new Date(k));
if (weekInfo[1] === targetWeek) {
// We only take the values of they are bigger/smaller than the ones we found so far
min.at(-1).y = Math.min(min.at(-1).y, parseFloat(recentData.daily.temperature_2m_min[i]))
max.at(-1).y = Math.max(max.at(-1).y, parseFloat(recentData.daily.temperature_2m_max[i]))
// approximate forecast mean data
mean.at(-1).y.push((max.at(-1).y + min.at(-1).y) / 2)
prec.at(-1).y.push(parseFloat(recentData.daily.precipitation_sum[i]))
}
});
}
// first filter out the nan values
mean.forEach((d: any) => {
d.y = d.y.filter((x: number) => !Number.isNaN((x)))
d.y = (d.y.reduce((a: number, b: any) => a + (b || 0), 0) / d.y.length).toFixed(2)
});
prec.forEach((d: any) => {
d.y = (d.y.reduce((a: number, b: any) => a + (b || 0), 0) /*/ d.y.length*/).toFixed(2)
});
setState({
...state,
tempData: [max, mean, min, prec],
tempDataMedian: mean.map((e: any) => { return { x: e.x, y: medianY(mean).y } }),
crosshairValues: [],
keepCrosshair: false,
currentVisMode: visualizationModes.WeekHistory,
formGeoString: `for ${msg.latitude.toFixed(2)}˚N ${msg.longitude.toFixed(2)}˚E at ${msg.elevation}m above sea level`,
//formTitle: `History of Calender Week ${targetWeek} between ${inputState.startDate} and ${inputState.endDate}.`
formTitle: <div className={styles.formTitle}><h1>History of Calender Week
<p className={styles.highlightText} style={{ color: myColors.IconBlue }}>
{targetWeek}
</p>
between
<p className={styles.highlightText} style={{ color: myColors.IconBlue }}>
{inputState.startDate}
</p>and
<p className={styles.highlightText} style={{ color: myColors.IconBlue }}>
{inputState.endDate}
</p>.
</h1>
</div>
})
}
export async function getMonthHistory(inputState: inputState, state: formState, setState: React.Dispatch<React.SetStateAction<formState>>) {
const now = Date.now()
const todaysDate = now - (now % 86400000)
// First get the historical data
const msg = await getHistoricalData(inputState.latitude!, inputState.longitude!, inputState.startDate, inputState.endDate);
let min: any = [], max: any = [], mean: any = [], prec: any = []
for (let i = 0; i < msg.daily.time.length; i++) {
const k = msg.daily.time[i]
const date = new Date(k)
const month = k.slice(5).slice(0, -3);
const year = date.getFullYear()
if (month === (inputState.targetDate.slice(5).slice(0, -3))) {
//check if we already have an entry for this month else create a new one
if (min.length === 0 || min.at(-1)?.x.getFullYear() !== year) {
const xVal = date
//const xVal = year
min.push({ x: xVal, y: parseFloat(msg.daily.temperature_2m_min[i]) || Infinity })
max.push({ x: xVal, y: parseFloat(msg.daily.temperature_2m_max[i] || -Infinity) })
mean.push({ x: xVal, y: [parseFloat(msg.daily.temperature_2m_mean[i])] })
prec.push({ x: xVal, y: [parseFloat(msg.daily.precipitation_sum[i])] })
}
else {
min.at(-1).y = Math.min(min.at(-1).y, parseFloat(msg.daily.temperature_2m_min[i]) || Infinity)
max.at(-1).y = Math.max(max.at(-1).y, parseFloat(msg.daily.temperature_2m_max[i]) || -Infinity)
mean.at(-1).y.push(parseFloat(msg.daily.temperature_2m_mean[i]))
prec.at(-1).y.push(parseFloat(msg.daily.precipitation_sum[i]))
}
}
}
// Now if the end date is more recent than 7 days ago, also fetch the forecast data for the more recent dates
if (todaysDate - new Date(inputState.endDate).valueOf() <= 604800000) {
const recentData = await getRecentData(inputState.latitude!, inputState.longitude!);
// add the recent data which will be the last entry of the arrays filled before
recentData.daily.time.forEach((k: string, i: number) => {
const month = k.slice(5).slice(0, -3);
if (month == (inputState.targetDate.slice(5).slice(0, -3))) {
// We only take the values of they are bigger/smaller than the ones we found so far
min.at(-1).y = Math.min(min.at(-1).y, parseFloat(recentData.daily.temperature_2m_min[i]))
max.at(-1).y = Math.max(max.at(-1).y, parseFloat(recentData.daily.temperature_2m_max[i]))
// for forecast data we approximate the mean, which yields okay errors at daily measures (~1C)
mean.at(-1).y.push((max.at(-1).y + min.at(-1).y) / 2)
prec.at(-1).y.push(parseFloat(recentData.daily.precipitation_sum[i]))
}
});
}
// first filter out the nan values
mean.forEach((d: any) => {
d.y = d.y.filter((x: number) => !Number.isNaN((x)))
d.y = Number((d.y.reduce((a: number, b: any) => a + (b || 0), 0) / d.y.length).toFixed(2))
});
prec.forEach((d: any) => {
d.y = Number((d.y.reduce((a: number, b: any) => a + (b || 0), 0) /*/ d.y.length*/).toFixed(2))
});
setState({
...state,
tempData: [max, mean, min, prec],
tempDataMedian: mean.map((e: any) => { return { x: e.x, y: medianY(mean).y } }),
crosshairValues: [],
keepCrosshair: false,
currentVisMode: visualizationModes.MonthHistory,
formGeoString: `for ${msg.latitude.toFixed(2)}˚N ${msg.longitude.toFixed(2)}˚E at ${msg.elevation}m above sea level`,
//formTitle: `History of Month ${months[Number(inputState.targetDate.slice(5).slice(0, -3))]} between ${inputState.startDate} and ${inputState.endDate}.`,
formTitle: <div className={styles.formTitle}><h1>History of Month
<p className={styles.highlightText} style={{ color: myColors.IconBlue }}>
{months[Number(inputState.targetDate.slice(5).slice(0, -3))]}
</p>
between
<p className={styles.highlightText} style={{ color: myColors.IconBlue }}>
{inputState.startDate}
</p>and
<p className={styles.highlightText} style={{ color: myColors.IconBlue }}>
{inputState.endDate}
</p>.
</h1>
</div>
})
}