-
Notifications
You must be signed in to change notification settings - Fork 1
/
spatial_interpolation_pegiou.R
345 lines (272 loc) · 13.9 KB
/
spatial_interpolation_pegiou.R
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
# Import datasets ( .csv)
observatory1<-read.csv("C:/Users/vicky/Documents/Documents/Metaptuxiako/Analutikes_Methodoi/ergasia_teliki/data/IDCJAC0001_066062_Data12.csv", na.strings="null")
botanic_gardens2<- read.csv("C:/Users/vicky/Documents/Documents/Metaptuxiako/Analutikes_Methodoi/ergasia_teliki/data/IDCJAC0001_066006_Data12.csv", na.strings = "null")
centennial3<- read.csv("C:/Users/vicky/Documents/Documents/Metaptuxiako/Analutikes_Methodoi/ergasia_teliki/data/IDCJAC0001_066160_Data12.csv", na.strings = "null")
randwick4<-read.csv("C:/Users/vicky/Documents/Documents/Metaptuxiako/Analutikes_Methodoi/ergasia_teliki/data/IDCJAC0001_066073_Data12.csv", na.strings = "null")
randwickst5<-read.csv("C:/Users/vicky/Documents/Documents/Metaptuxiako/Analutikes_Methodoi/ergasia_teliki/data/IDCJAC0001_066052_Data12.csv", na.strings = "null")
rosebay6<-read.csv("C:/Users/vicky/Documents/Documents/Metaptuxiako/Analutikes_Methodoi/ergasia_teliki/data/IDCJAC0001_066098_Data12.csv", na.strings = "null")
mosman7<-read.csv("C:/Users/vicky/Documents/Documents/Metaptuxiako/Analutikes_Methodoi/ergasia_teliki/data/IDCJAC0001_066184_Data12.csv", na.strings = "null")
dover8<-read.csv("C:/Users/vicky/Documents/Documents/Metaptuxiako/Analutikes_Methodoi/ergasia_teliki/data/IDCJAC0001_066209_Data12.csv", na.strings = "null")
riverview9<-read.csv("C:/Users/vicky/Documents/Documents/Metaptuxiako/Analutikes_Methodoi/ergasia_teliki/data/IDCJAC0001_066131_Data12.csv", na.strings = "null")
ashfield10<-read.csv("C:/Users/vicky/Documents/Documents/Metaptuxiako/Analutikes_Methodoi/ergasia_teliki/data/IDCJAC0001_066000_Data12.csv", na.strings = "null")
abbotsford11<-read.csv("C:/Users/vicky/Documents/Documents/Metaptuxiako/Analutikes_Methodoi/ergasia_teliki/data/IDCJAC0001_066034_Data12.csv", na.strings = "null")
chatswood12<-read.csv("C:/Users/vicky/Documents/Documents/Metaptuxiako/Analutikes_Methodoi/ergasia_teliki/data/IDCJAC0001_066011_Data12.csv", na.strings = "null")
marrickville13<-read.csv("C:/Users/vicky/Documents/Documents/Metaptuxiako/Analutikes_Methodoi/ergasia_teliki/data/IDCJAC0001_066036_Data12.csv", na.strings = "null")
airport14<-read.csv("C:/Users/vicky/Documents/Documents/Metaptuxiako/Analutikes_Methodoi/ergasia_teliki/data/IDCJAC0001_066037_Data12.csv", na.strings = "null")
dataset_rain<-c(botanic_gardens2,observatory1,centennial3,randwick4,randwickst5,rosebay6,mosman7,dover8,riverview9,ashfield10,abbotsford11,chatswood12,marrickville13,airport14)
help("data.frame")
trial<-rbind(botanic_gardens2,observatory1,centennial3,randwick4,randwickst5,rosebay6,mosman7,dover8,riverview9,ashfield10,abbotsford11,chatswood12,marrickville13,airport14)
head(trial)
tail(trial)
write.csv(trial,"C:/Users/vicky/Documents/Documents/Metaptuxiako/Analutikes_Methodoi/ergasia_teliki/data/full_dataset_rainfall.csv")
help("write.csv")
#` Import new column with the lat lon info of each station
#' **Get the station codes**
stations<-unique(unlist(trial$Station.Number))
stations
# Loop for creating and filling the new columns lon and lat
# Vectors with lat and lon values
lat<-c(-33.87,-33.86,-33.90,-33.91,-33.91,-33.88,-33.83,-33.87,-33.83,-33.89,-33.85,-33.80,-33.92,-33.95)
lon<-c(151.22,151.21,151.23,151.23,151.24,151.27,151.25,151.28,151.16,151.13,151.13,151.18,151.14,151.17)
# Creating backup file of the dataset
full_data<-trial
attach(trial)
for (i in 1:14){
for (j in 1:nrow(trial)) {
if (Station.Number[j]==stations[i]){
trial$lon[j]<-lon[i]
trial$lat[j]<-lat[i]
}
else {
j<-j+1
}
}
}
head(trial)
tail(trial)
lonlat<-data.frame(trial$lon,trial$lat)
simple_rain_data<-trial # in the next steps it will be converted into spatial df
hist(trial$Annual, xlab='Annual precipitation (mm)',las=1 ,ylab='Frequency', main="Histogram of Annual Rainfall",col=rev(terrain.colors(10)), breaks=seq(0,3500,200))
## Subsetting
# Creating the objects i need
stationdata<-c(1,2)
len<-1
i<-0
plot_list = list()
for (i in stations){
# Subsetting each station
assign(paste("station",i,sep = ""),subset(simple_rain_data,simple_rain_data$Station.Number==i))
stationdata[len]<-paste("station",i,sep = "")
len<-len+1
# Metadata of the plot
d<-subset(simple_rain_data,simple_rain_data$Station.Number==i)
file_name = paste("annual_rainfall_lm", i, ".png", sep=".")
#png(filename = file_name)
# Creating the plot
p<-plot(d$Year,d$Annual,xlab="Year",ylab="Annual Rainfall (mm)",main=paste("Annual Rainfall, Station",i),col="magenta")
lines(d$Year,d$Annual,col="red")
abline(lm(formula=d$Annual~d$Year,data=d),col='blue', lty=3)
plot_list[[i]] = p
# Saving the plot in the working dir
#dev.copy(png,file_name)
#dev.off()
}
## Conversion to SpatialPointsDataFrame
# install.packages("sp")
library("sp")
help("coordinates")
coordinates(trial)<-c("lon","lat")
plot(trial)
crs.geo <- CRS("+proj=longlat +ellps=WGS84 +datum=WGS84") # geographical, datum WGS84
proj4string(trial) <- crs.geo # define projection system of our data
summary(trial)
# install.packages("dismo")
# install.packages("rgdal")
# install.packages("XML")
library("XML")
library("rgdal")
library("raster")
library("dismo")
#' Plot the stations on satellite image of Australia (Sydney)
aumap <- gmap(trial, type = "satellite")
aumap.merc <- Mercator(trial) # Google Maps are in Mercator projection.
#' This function projects the points to that projection to enable mapping
plot(aumap)
points(aumap.merc, pch = 20, col = "red")
#' Export in .shp format
# writeOGR(trial, dsn = "C:/Users/vicky/Documents/Documents/Metaptuxiako/Analutikes_Methodoi/ergasia_teliki/data/shp",layer = "stations_data_output", driver = "ESRI Shapefile")
# Plotting shapefile format
shpsyd_base <- readOGR(dsn = "C:/Users/vicky/Documents/Documents/Metaptuxiako/Analutikes_Methodoi/ergasia_teliki/data/shp/Sydney",layer = "basemap3")
plot(shpsyd_base)
# More Subsetting (by year)
# Trial is not a data frame anymore .. so let's do it again
spatial_data<-trial
#trial<-as.data.frame(trial) ## i will convert the trial file itself into df
class(spatial_data)
# Subsetting for the first year of interest (1990)
# Spatial
rain1990sp<-subset.data.frame(trial,trial$Year==1990)
rain_all_sp<-subset.data.frame(trial,trial$Year==1990 | trial$Year==2000 | trial$Year==2010)
rain1990sp
trialbckup<-trial
###############################################
## Also for 2000 and 2010
for(i in z<-seq(2000,2010,10)) {
assign(paste("rain", i, sep = ""), subset.data.frame(trial,trial$Year==i))
# rainidw[i]<-gstat::idw((paste("rain",i,"$Annual",sep = "")) ~ 1, (paste("rain",i,sep = "")), newdata=grd, idp=2.0)
}
# Original Df (Not Spatial)
rain1990<-subset.data.frame(simple_rain_data,simple_rain_data$Year==1990)
head(rain1990)
dim(rain1990)
rain1990
# Spatial Interpolation
#install.packages("gstat")
library("gstat") #idw
library("sp") #spsample
# Create an empty grid where n is the total number of cells
grd <- as.data.frame(spsample(rain1990sp, "regular", n=100000))
names(grd) <- c("X", "Y")
coordinates(grd) <- c("X", "Y")
gridded(grd) <- TRUE # Create SpatialPixel object
fullgrid(grd) <- TRUE # Create SpatialGrid object
proj4string(grd) <- proj4string(rain1990sp)
######## 1990 ###############
# Interpolate the grid cells using a power value of 2 (idp=2.0)
rain1990_idw <- gstat::idw(rain1990sp$Annual ~ 1, rain1990sp, newdata=grd, idp=2.0)
# Convert to raster object then clip
rain1990_idw_raster<- raster(rain1990_idw)
rain1990_idw_masked<- mask(rain1990_idw_raster, shpsyd_base )
idw_full<-plot(rain1990_idw_masked, main="Rainfall measurements' interpolation in the area of Sydney")
points(rain1990sp, pch = 20, col = "red")
# Backup
basemap_syd <-shpsyd_base
########### 2000 ##############
# Interpolate the grid cells using a power value of 2 (idp=2.0)
# rain2000_idw <- gstat::idw(rain2000$Annual ~ 1, rain2000, newdata=grd, idp=2.0, na.action=na.omit)
# rain2000df<-as.data.frame(rain2000)
# rain2000dfnaom<-na.omit(rain2000df)
# rain2000_idw <- gstat::idw(rain2000dfnaom$Annual ~ 1, rain2000dfnaom, newdata=grd, idp=2.0, na.action=na.omit)
# There is an error because of the missing values ... SO....
# Removing obs. with na
# FUNCTION TO REMOVE NA's IN sp DataFrame OBJECT
# x sp spatial DataFrame object
# margin Remove rows (1) or columns (2)
sp.na.omit <- function(x, margin=1) {
if (!inherits(x, "SpatialPointsDataFrame") & !inherits(x, "SpatialPolygonsDataFrame"))
stop("MUST BE sp SpatialPointsDataFrame OR SpatialPolygonsDataFrame CLASS OBJECT")
na.index <- unique(as.data.frame(which(is.na(x@data),arr.ind=TRUE))[,margin])
if(margin == 1) {
cat("DELETING ROWS: ", na.index, "\n")
return( x[-na.index,] )
}
if(margin == 2) {
cat("DELETING COLUMNS: ", na.index, "\n")
return( x[,-na.index] )
}
}
# DELETE NA's IN RAIN2000 AND SHOW CHANGE IN dim
rain2000naom <- sp.na.omit(rain2000)
dim(rain2000naom)
dim(rain2000)
# PLOT DELETED POINTS IN RED
plot(rain2000, col="red", pch=20)
plot(rain2000naom, col="black", pch=20, add=TRUE)
# Now we can use the idw
rain2000_idw <- gstat::idw(rain2000naom$Annual ~ 1, rain2000naom, newdata=grd, idp=2.0)
# Convert to raster object then clip to shp
rain2000_idw_raster<- raster(rain2000_idw)
rain2000_idw_masked<- mask(rain2000_idw_raster, shpsyd_base)
idw_00<-plot(rain2000_idw_masked, main="Rainfall measurements' interpolation in Sydney during 2000", xlab="Longitute",ylab="Latitude")
points(rain2000naom, pch = 20, col = "red", main)
############## 2010 ################
# Interpolate the grid cells using a power value of 2 (idp=2.0)
# rain2010_idw <- gstat::idw(rain2010$Annual ~ 1, rain2010, newdata=grd, idp=2.0)
# There is also an error because of the missing values ... again ....
# Removing obs. with na
# DELETE NA's IN RAIN2010 AND SHOW CHANGE IN dim
rain2010naom <- sp.na.omit(rain2010)
dim(rain2010naom)
dim(rain2010)
# PLOT DELETED POINTS IN RED
plot(rain2010, col="red", pch=20)
plot(rain2010naom, col="black", pch=20, add=TRUE)
# Now we can use the idw
rain2010_idw <- gstat::idw(rain2010naom$Annual ~ 1, rain2010naom, newdata=grd, idp=2.0)
# Convert to raster object then clip to shp
rain2010_idw_raster<- raster(rain2010_idw)
rain2010_idw_masked<- mask(rain2010_idw_raster, shpsyd_base)
idw_00<-plot(rain2010_idw_masked, main="Rainfall measurements' interpolation in Sydney during 2010", xlab="Longitute",ylab="Latitude")
points(rain2010naom, pch = 20, col = "red", main)
## Interpolation of common data
# Convert into data frame
r1990df<-as.data.frame(rain1990sp)
r2000df<-as.data.frame(rain2000)
r2010df<-as.data.frame(rain2010)
# Remove na's
r1990dfna<-na.omit(r1990df)
r2000dfna<-na.omit(r2000df)
r2010dfna<-na.omit(r2010df)
# Get common data
rain_common1<-merge(r1990dfna,r2000dfna,by="Station.Number")
rain_common2<-merge(rain_common1,r2010dfna, by="Station.Number")
rain_common<-rain_common2
# Convert into SpatialPointsDataFrame
coordinates(rain_common)<-c("lon","lat")
plot(rain_common)
crs.geo <- CRS("+proj=longlat +ellps=WGS84 +datum=WGS84") # geographical, datum WGS84
proj4string(rain_common) <- crs.geo # define projection system of our data
summary(rain_common)
rain_common_sp<-rain_common
####################################################
####### INTERPOLATION OF MERGED DATA #############
###################################################
########### 1990 ################
# Interpolate the grid cells using a power value of 2 (idp=2.0)
rc1990_idw <- gstat::idw(rain_common_sp$Annual.x ~ 1, rain_common_sp, newdata=grd, idp=2.0)
rc90idw_df<-as.data.frame(rc1990_idw)
head(rc90idw_df)
# The output variable is called var1.pred, and thevar1.var values
# are NA because inverse distance does not provide prediction error variance
# Convert to raster object then clip to shp
rc1990_idw_raster<- raster(rc1990_idw)
rc1990_idw_masked<- mask(rc1990_idw_raster, shpsyd_base)
idwc_90<-plot(rc1990_idw_masked, main="Rainfall measurements' interpolation in Sydney during 1990", xlab="Longitute",ylab="Latitude")
points(rain_common_sp, pch = 20, col = "red", main)
########### 2000 ###############
# Interpolate the grid cells using a power value of 2 (idp=2.0)
rc2000_idw <- gstat::idw(rain_common_sp$Annual.y ~ 1, rain_common_sp, newdata=grd, idp=2.0)
rc00idw_df<-as.data.frame(rc2000_idw)
head(rc00idw_df)
# Convert to raster object then clip to shp
rc2000_idw_raster<- raster(rc2000_idw)
rc2000_idw_masked<- mask(rc2000_idw_raster, shpsyd_base)
idwc_00<-plot(rc2000_idw_masked, main="Rainfall measurements' interpolation in Sydney during 2000", xlab="Longitute",ylab="Latitude")
points(rain_common_sp, pch = 20, col = "red", main)
########### 2010 ###############
# Interpolate the grid cells using a power value of 2 (idp=2.0)
rc2010_idw <- gstat::idw(rain_common_sp$Annual ~ 1, rain_common_sp, newdata=grd, idp=2.0)
rc10idw_df<-as.data.frame(rc2010_idw)
head(rc10idw_df)
# Convert to raster object then clip to shp
rc2010_idw_raster<- raster(rc2010_idw)
rc2010_idw_masked<- mask(rc2010_idw_raster, shpsyd_base)
idwc_10<-plot(rc2010_idw_masked, main="Rainfall measurements' interpolation in Sydney during 2010", xlab="Longitute",ylab="Latitude")
points(rain_common_sp, pch = 20, col = "red", main)
allplot<-stack(rc1990_idw_masked,rc2000_idw_masked,rc2010_idw_masked)
sp <- as(allplot, 'SpatialGridDataFrame')
spplot(sp, names.attr=c(1990,2000,2010),contour=TRUE, main="Rainfall in Sydney")
### Visualization and Comparison of the results
# install.packages("rasterVis")
library("rasterVis")
levelplot(allplot, col.regions = (rainbow(99, start=0, end=1)), colorkey = list(space = "right",title="Annual Rainfall(mm)"), main="Rainfall in Sydney")
#### Comparison of the interpolated rainfall ####
r0090<-rc2000_idw_masked-rc1990_idw_masked
plot(r0090)
r1000<-rc2010_idw_masked-rc2000_idw_masked
plot(r1000)
r1090<-rc2010_idw_masked-rc1990_idw_masked
plot(r1090)
allplot2<-stack(r0090,r1000,r1090)
sp2 <- as(allplot2, 'SpatialGridDataFrame')
spplot(sp2, names.attr=c("1990-2000","2000-2010","1990-2010"),col.regions=terrain.colors,contour=TRUE, main="Rainfall Change in Sydney")