forked from AdamWilsonLabEDU/SpatialDataScience
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPS_09_weather.Rmd
More file actions
656 lines (498 loc) · 16.5 KB
/
PS_09_weather.Rmd
File metadata and controls
656 lines (498 loc) · 16.5 KB
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
---
title: APIs, time-series, and weather Data
---
```{r, echo=FALSE, message=FALSE, results='hide', purl=FALSE}
source("../functions.R")
library(kableExtra)
options(knitr.table.format = 'markdown')
knitr::opts_chunk$set(cache=T,
fig.width=6,
fig.height=3,
dpi=200,
dev="png")
library(knitr)
```
# API
## Application Programming Interface
<iframe src="https://en.wikipedia.org/wiki/Application_programming_interface" width=100% height=400px></iframe>
> - Imagine I wanted to work with Wikipedia content...
## Manually processing information from the web
* Browse to page, `File->Save As`, repeat.
* Deal with ugly html stuff...
```{}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="generator" content="pandoc">
<title>APIs, time-series, and weather Data</title>
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">
<link rel="stylesheet" href="externals/reveal.js-3.3.0.1/css/reveal.css"/>
```
---
```{r, message=F}
library(WikipediR)
library(tidyverse)
content=page_content(
page_name = "Application_programming_interface",
project="Wikipedia",
language="en",
as_wikitext=T)
```
## APIs allow direct (and often custom) sharing of data
```{r, results='asis'}
c1=content$parse$wikitext%>%
str_split(boundary("sentence"),simplify = T)%>%
str_replace_all("'","")%>%
str_replace_all("\\[|\\]","")
# results:
cat(c1[3:4])
```
## Many data providers now have APIs
* Government Demographic data (census, etc.)
* Government Environmental data
* Google, Twitter, etc.
## Pros & Cons
### Pros
* Get the data you want, when you want it
* Automatic updates - just re-run the request
### Cons
* Dependent on real-time access
* APIs, permissions, etc. can change and break code
## Generic API Access
1. Provide R with a URL to request information
2. The API sends you back a response
* JavaScript Object Notation (JSON)
* Extensible Markup Language (XML).
```{r}
library(tidyverse)
library(httr)
library(jsonlite)
```
## Endpoints
The URL you will request information from.
* Data.gov API: https://www.data.gov/developers/apis
* Github API: https://api.github.com
## Some R Packages for specific APIs
### `FedData` package
* National Elevation Dataset digital elevation models (1 and 1/3 arc-second; USGS)
* National Hydrography Dataset (USGS)
* Soil Survey Geographic (SSURGO) database
* International Tree Ring Data Bank.
* Global Historical Climatology Network (GHCN)
* Others
## NOAA APIv2
<iframe src="https://www.ncdc.noaa.gov/cdo-web/webservices/v2" width=100% height=400px></iframe>
[National Climatic Data Center application programming interface (API)]( http://www.ncdc.noaa.gov/cdo-web/webservices/v2).
## `rNOAA` package
Handles downloading data directly from NOAA APIv2.
* `buoy_*` NOAA Buoy data from the National Buoy Data Center
* `ghcnd_*` GHCND daily data from NOAA
* `isd_*` ISD/ISH data from NOAA
* `homr_*` Historical Observing Metadata Repository
* `ncdc_*` NOAA National Climatic Data Center (NCDC)
* `seaice` Sea ice
* `storm_` Storms (IBTrACS)
* `swdi` Severe Weather Data Inventory (SWDI)
* `tornadoes` From the NOAA Storm Prediction Center
# Global Historical Climatology Network (GHCN)
## GHCN
<iframe src="https://www.ncdc.noaa.gov/ghcn-daily-description" width=100% height=400px></iframe>
## Libraries
```{r,results='hide',message=FALSE, warning=F}
library(sf)
library(broom)
library(tidyverse)
library(ggmap)
library(scales)
# New Packages
library(rnoaa)
library(climdex.pcic)
library(zoo)
```
## Station locations
Download the GHCN station inventory with `ghcnd_stations()` and convert to `sf` object. The download can take a minute or two.
```{r}
st = ghcnd_stations()%>%
na.omit()%>% # remove records with missing values
st_as_sf(coords=c("longitude","latitude"))%>% #convert to sf
st_set_crs("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")
head(st)%>%kable()
```
## GHCND Variables: 5 core values
* **PRCP** Precipitation (tenths of mm)
* **SNOW** Snowfall (mm)
* **SNWD** Snow depth (mm)
* **TMAX** Maximum temperature
* **TMIN** Minimum temperature
---
### And ~50 others! For example:
* **ACMC** Average cloudiness midnight to midnight from 30-second ceilometer
* **AWND** Average daily wind speed
* **FMTM** Time of fastest mile or fastest 1-minute wind
* **MDSF** Multiday snowfall total
## `filter()` to temperature and precipitation
```{r}
st_filtered=dplyr::filter(st,element%in%c("TMAX","TMIN","PRCP"))
```
## Map GHCND stations
First, get a global country polygon
```{r, warning=F, message=F}
library(spData)
data(world)
```
## Station locations
```{r}
map1=ggplot() +
geom_sf(data=world,inherit.aes = F,size=.1,fill="grey",colour="black")+
facet_wrap(~element)+
stat_bin2d(data=st_filtered,
aes(y=st_coordinates(st_filtered)[,2],
x=st_coordinates(st_filtered)[,1]),bins=100)+
scale_fill_distiller(palette="YlOrRd",trans="log",direction=-1,
breaks = c(1,10,100,1000))+
coord_sf()+
labs(x="",y="")
```
---
```{r, echo=F}
map1
```
## Download daily data from GHCN
`ghcnd()` will download a `.dly` text file for a particular station. But how to choose?
## `geocode` in ggmap package useful for geocoding place names
Geocodes a location (find latitude and longitude) using either (1) the Data Science Toolkit (http://www.datasciencetoolkit.org/about) or (2) Google Maps.
```{r, message=F}
geocode("University at Buffalo, NY",source = "dsk")
```
---
However, you have to be careful:
```{r, message=F, warning=F}
geocode("Washington",source = "dsk")
geocode("Washington D.C.",source = "dsk")
```
---
But this is pretty safe for well known and well-defined places.
```{r, message=F, warning=F}
buffalo_c=geocode("Buffalo International Airport, NY",source = "dsk")
buffalo_c
buffalo=buffalo_c%>%
st_as_sf(coords=c(1,2))%>% #convert to sf
st_set_crs("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")
```
---
Now use that location to spatially filter stations.
```{r, message=F, warning=F}
buffalo_b=st_buffer(buffalo, 0.05) #radius of buffer in decimal degrees
st1=st_within(st_filtered,buffalo_b)%>% #find stations in the buffered polygon
apply(1, any)
str(st1)
kable(st_filtered[st1,])
```
---
With the station ID, we can download daily data from NOAA.
```{r}
d=meteo_pull_monitors(monitors=c("USW00014733"),
var = c("TMAX","TMIN","PRCP"),
keep_flags = T)
head(d)%>%kable()
```
---
See [CDO Daily Description](http://www1.ncdc.noaa.gov/pub/data/cdo/documentation/GHCND_documentation.pdf) and raw [GHCND metadata](http://www1.ncdc.noaa.gov/pub/data/ghcn/daily/readme.txt) for more details.
## Quality Control: MFLAG
Measurement Flag/Attribute
* **Blank** no measurement information applicable
* **B** precipitation total formed from two twelve-hour totals
* **H** represents highest or lowest hourly temperature (TMAX or TMIN) or average of hourly values (TAVG)
* **K** converted from knots
* ...
See [CDO Description](http://www1.ncdc.noaa.gov/pub/data/cdo/documentation/GHCND_documentation.pdf)
## Quality Control: QFLAG
* **Blank** did not fail any quality assurance check
* **D** failed duplicate check
* **G** failed gap check
* **I** failed internal consistency check
* **K** failed streak/frequent-value check
* **N** failed naught check
* **O** failed climatological outlier check
* **S** failed spatial consistency check
* **T** failed temporal consistency check
* **W** temperature too warm for snow
* ...
See [CDO Description](http://www1.ncdc.noaa.gov/pub/data/cdo/documentation/GHCND_documentation.pdf)
## Quality Control: SFLAG
Indicates the source of the data...
## Summarize QC flags
Summarize the QC flags. How many of which type are there? Should we be more conservative?
```{r}
table(d$qflag_tmin)
```
* **G** failed gap check
* **I** failed internal consistency check
* **S** failed spatial consistency check
---
### Filter with QC data and change units
```{r}
d_filtered=d%>%
mutate(tmax=ifelse(qflag_tmax!=" "|tmax==-9999,NA,tmax/10))%>% # convert to degrees C
mutate(tmin=ifelse(qflag_tmin!=" "|tmin==-9999,NA,tmin/10))%>% # convert to degrees C
mutate(prcp=ifelse(qflag_prcp!=" "|prcp==-9999,NA,prcp))%>%
arrange(date)
```
---
Plot temperatures
```{r, warning=F}
ggplot(d_filtered,
aes(y=tmax,x=date))+
geom_line(col="red")+
facet_wrap(~id)
```
---
Limit to a few years and plot the daily range and average temperatures.
```{r, fig.height=6}
d_filtered_recent=filter(d_filtered,date>as.Date("2013-01-01"))
ggplot(d_filtered_recent,
aes(ymax=tmax,ymin=tmin,x=date))+
geom_ribbon(col="grey",fill="grey")+
geom_line(aes(y=(tmax+tmin)/2),col="red")
```
## Zoo package for rolling functions
Infrastructure for Regular and Irregular Time Series (Z's Ordered Observations)
* `rollmean()`: Rolling mean
* `rollsum()`: Rolling sum
* `rollapply()`: Custom functions
Use rollmean to calculate a rolling 60-day average.
* `align` whether the index of the result should be left- or right-aligned or centered
---
```{r}
d_rollmean = d_filtered_recent %>%
arrange(date) %>%
mutate(tmax.60 = rollmean(x = tmax, 60, align = "center", fill = NA),
tmax.b60 = rollmean(x = tmax, 60, align = "right", fill = NA))
```
---
```{r, warning=F}
d_rollmean%>%
ggplot(aes(ymax=tmax,ymin=tmin,x=date))+
geom_ribbon(fill="grey")+
geom_line(aes(y=(tmin+tmax)/2),col=grey(0.4),size=.5)+
geom_line(aes(y=tmax.60),col="red")+
geom_line(aes(y=tmax.b60),col="darkred")
```
# Time Series analysis
Most timeseries functions use the time series class (`ts`)
```{r}
tmin.ts=ts(d_filtered_recent$tmin,frequency = 365)
```
## Temporal autocorrelation
Values are highly correlated!
```{r}
ggplot(d_filtered_recent,aes(y=tmin,x=lag(tmin)))+
geom_point()+
geom_abline(intercept=0, slope=1)
```
## Autocorrelation functions
* autocorrelation $x$ vs. $x_{t-1}$ (lag=1)
* partial autocorrelation. $x$ vs. $x_{n}$ _after_ controlling for correlations $\in t-1:n$
## Autocorrelation
```{r}
acf(tmin.ts,lag.max = 365*3,na.action = na.exclude )
```
---
### Partial Autocorrelation
```{r}
pacf(tmin.ts,lag.max = 365,na.action = na.exclude )
```
# Trend analysis
## Group by month, season, year, and decade.
How to convert years into 'decades'?
```{r}
1938
round(1938,-1)
floor(1938/10)
floor(1938/10)*10
```
Now we can make a 'decade' grouping variable.
---
Calculate seasonal and decadal mean temperatures.
```{r}
d_filtered2=d_filtered%>%
mutate(month=as.numeric(format(date,"%m")),
year=as.numeric(format(date,"%Y")),
season=case_when(
month%in%c(12,1,2)~"Winter",
month%in%c(3,4,5)~"Spring",
month%in%c(6,7,8)~"Summer",
month%in%c(9,10,11)~"Fall"),
dec=(floor(as.numeric(format(date,"%Y"))/10)*10))
d_filtered2%>%dplyr::select(date,month,year,season,dec,tmax)%>%head()%>%kable()
```
## Timeseries models
How to assess change? Simple differences?
```{r}
d_filtered2%>%
mutate(period=ifelse(year<=1976-01-01,"early","late"))%>% #create two time periods before and after 1976
group_by(period)%>% # divide the data into the two groups
summarize(n=n(), # calculate the means between the two periods
tmin=mean(tmin,na.rm=T),
tmax=mean(tmax,na.rm=T),
prcp=mean(prcp,na.rm=T))%>%
kable()
```
---
But be careful, there were lots of missing data in the beginning of the record
```{r, warning=F}
d_filtered2%>%
group_by(year)%>%
summarize(n=n())%>%
ggplot(aes(x=year,y=n))+
geom_line()
```
---
```{r}
# which years don't have complete data?
d_filtered2%>%
group_by(year)%>%
summarize(n=n())%>%
filter(n<360)
```
---
Plot 10-year means (excluding years without complete data):
```{r, warning=F}
d_filtered2%>%
filter(year>1938, year<2017)%>%
group_by(dec)%>%
summarize(
n=n(),
tmin=mean(tmin,na.rm=T),
tmax=mean(tmax,na.rm=T),
prcp=mean(prcp,na.rm=T)
)%>%
ggplot(aes(x=dec,y=tmax))+
geom_line(col="grey")
```
## Look for specific events: was 2017 unusually hot in Buffalo, NY?
Let's compare 2017 with all the previous years in the dataset. First add 'day of year' to the data to facilitate showing all years on the same plot.
```{r, warning=F}
df=d_filtered2%>%
mutate(doy=as.numeric(format(date,"%j")),
doydate=as.Date(paste("2017-",doy),format="%Y-%j"))
```
---
Then plot all years (in grey) and add 2017 in red.
```{r, warning=F}
ggplot(df,aes(x=doydate,y=tmax,group=year))+
geom_line(col="grey",alpha=.5)+ # plot each year in grey
stat_smooth(aes(group=1),col="black")+ # Add a smooth GAM to estimate the long-term mean
geom_line(data=filter(df,year>2016),col="red")+ # add 2017 in red
scale_x_date(labels = date_format("%b"),date_breaks = "2 months")
```
---
Then 'zoom' into just the past few months and add 2017 in red.
```{r, warning=F, message=F}
ggplot(df,aes(x=doydate,y=tmax,group=year))+
geom_line(col="grey",alpha=.5)+
stat_smooth(aes(group=1),col="black")+
geom_line(data=filter(df,year>2016),col="red")+
scale_x_date(labels = date_format("%b"),date_breaks = "2 months",
lim=c(as.Date("2017-08-01"),as.Date("2017-10-31")))
```
So there was an unusually warm spell in late September.
## Summarize by season
```{r, warning=F,fig.height=12}
seasonal=d_filtered2%>%
group_by(year,season)%>%
summarize(n=n(),
tmin=mean(tmin),
tmax=mean(tmax),
prcp=mean(prcp))%>%
filter(n>75)
```
## Seasonal Trends
```{r, warning=F}
ggplot(seasonal,aes(y=tmin,x=year))+
facet_wrap(~season,scales = "free_y")+
stat_smooth(method="lm", se=T)+
geom_line()
```
## Fit a linear model to a single season
```{r}
lm1=seasonal%>%
filter(season=="Summer")%>%
lm(tmin~year,data=.)
summary(lm1)$r.squared
tidy(lm1)%>%kable()
```
## Linear regression for _each_ season
```{r, warning=F}
# fit a lm model for each group
models <-
d_filtered2%>%
group_by(season)%>%
nest() %>%
mutate(lm_tmin = purrr::map(data, ~lm(tmin ~ year, data = .)),
tmax_tidy = purrr::map(lm_tmin, broom::tidy))%>%
unnest(tmax_tidy, .drop = T)%>%
filter(term=="year")
models
```
## Autoregressive models
See [Time Series Analysis Task View](https://cran.r-project.org/web/views/TimeSeries.html) for summary of available packages/models.
* Moving average (MA) models
* autoregressive (AR) models
* autoregressive moving average (ARMA) models
* frequency analysis
* Many, many more...
---
# Climate Metrics
## Climate Metrics: ClimdEX
Indices representing extreme aspects of climate derived from daily data:
<img src="../08_assets/climdex.png" alt="alt text" width="50%">
Climate Change Research Centre (CCRC) at University of New South Wales (UNSW) ([climdex.org](http://www.climdex.org)).
## 27 Core indices
For example:
* **FD** Number of frost days: Annual count of days when TN (daily minimum temperature) < 0C.
* **SU** Number of summer days: Annual count of days when TX (daily maximum temperature) > 25C.
* **ID** Number of icing days: Annual count of days when TX (daily maximum temperature) < 0C.
* **TR** Number of tropical nights: Annual count of days when TN (daily minimum temperature) > 20C.
* **GSL** Growing season length: Annual (1st Jan to 31st Dec in Northern Hemisphere (NH), 1st July to 30th June in Southern Hemisphere (SH)) count between first span of at least 6 days with daily mean temperature TG>5C and first span after July 1st (Jan 1st in SH) of 6 days with TG<5C.
* **TXx** Monthly maximum value of daily maximum temperature
* **TN10p** Percentage of days when TN < 10th percentile
* **Rx5day** Monthly maximum consecutive 5-day precipitation
* **SDII** Simple pricipitation intensity index
## Climdex indices
[ClimDex](http://www.climdex.org/indices.html)
## Format data for `climdex`
```{r}
library(PCICt)
## Parse the dates into PCICt.
pc.dates <- as.PCICt(as.POSIXct(d_filtered$date),cal="gregorian")
```
## Generate the climdex object
```{r}
library(climdex.pcic)
ci <- climdexInput.raw(
tmax=d_filtered$tmax,
tmin=d_filtered$tmin,
prec=d_filtered$prcp,
pc.dates,pc.dates,pc.dates,
base.range=c(1971, 2000))
years=as.numeric(as.character(unique(ci@date.factors$annual)))
```
## Cumulative dry days
```{r}
cdd= climdex.cdd(ci, spells.can.span.years = TRUE)
plot(cdd~years,type="l")
```
## Diurnal Temperature Range
```{r}
dtr=climdex.dtr(ci, freq = c("annual"))
plot(dtr~years,type="l")
```
## Frost Days
```{r}
fd=climdex.fd(ci)
plot(fd~years,type="l")
```