forked from anitas-giraldo/GB_Habitat_Classification
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0.Prepare_data_coarse_dominant_TV.R
286 lines (208 loc) · 7.41 KB
/
0.Prepare_data_coarse_dominant_TV.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
#################################################
############ Prepare data for RF ################
### Load libraries --
library(ggplot2)
library(cowplot)
library(sp)
library(rgdal)
library(raster)
library(sf)
library(dplyr)
# Clear memory ----
rm(list=ls())
### Set directories ----
w.dir <- "Y:/GB_Habitat_Classification"
d.dir <- "Y:/GB_Habitat_Classification/data"
s.dir <- "Y:/GB_Habitat_Classification/spatial_data"
p.dir <- "Y:/GB_Habitat_Classification/plots"
o.dir <- "Y:/GB_Habitat_Classification/outputs"
#### DOMINANT DATA ----
### Load data ----
# Habitat data --
df <- read.csv(paste(d.dir, "raw", "dominant-towed_broad.percent.cover.csv", sep='/'))
str(df) # 7 categories
# Bathy 250m all Geo Bay --
b <- raster(paste(s.dir, "GB_Bathy_250m.tif", sep='/'))
b
plot(b)
#e <- drawExtent()
ext <- extent(115.029,115.6675,-33.65969,-33.29265)
b2 <- crop(b, ext)
plot(b2)
#bx <- raster(paste(s.dir, "GBmultib_lidarUTM_CMR.tif", sep='/'))
#bx # in UTM
#plot(bx)
# Reproject lidat and multibeam data
#b2 <- projectRaster(b, crs="+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0")
#b2
#plot(b2)
# save
#writeRaster(b2, paste(s.dir, "GBmultib_lidar_CMR.tif", sep='/'))
# Check data points --
dfs <- df
coordinates(dfs) <- ~longitude+latitude
points(dfs)
# Filter data to use just where there is lidar and multib --
dnew <- raster::extract(b2, dfs, sp=T)
str(dnew)
dfnew <- as.data.frame(dnew)
dfnew <- na.omit(dfnew)
str(dfnew)
dfsnew <- dfnew
coordinates(dfsnew) <- ~longitude+latitude
points(dfsnew, pch = 20, col="red")
h <- dfsnew
# save points --
#write.csv(dfnew, paste(d.dir, "GB_Bruvs_fine_bathy_habitat_presence_absence_broad.csv"))
#writeOGR(dfsnew, dsn= s.dir, layer= "GB_Bruvs_fine_bathy_habitat_presence_absence_broad", driver="ESRI Shapefile", overwrite_layer=TRUE)
## load shape file with habitat data ----
#h <- readOGR(paste(s.dir, "GB_Bruvs_fine_bathy_habitat_presence_absence_broad.shp", sep='/'))
######################################
#### Calculate Bathy Derivatives ####
slope4 <- raster::terrain(b, "slope", unit="degrees", neighboors=4)
slope4@data@names
slope4@data@names <- "slope4"
slope8 <- raster::terrain(b, "slope", unit="degrees", neighboors=8)
slope8@data@names
slope8@data@names <- "slope8"
aspect4 <- raster::terrain(b, "aspect", unit="degrees", neighboors=4)
aspect4@data@names
aspect4@data@names <- "aspect4"
aspect8 <- raster::terrain(b, "aspect", unit="degrees", neighboors=8)
aspect8@data@names
aspect8@data@names <- "aspect8"
tpi <- raster::terrain(b, "TPI")
tri <- raster::terrain(b, "TRI")
roughness <- raster::terrain(b, "roughness")
flowdir <- raster::terrain(b, "flowdir")
b@data@names <- "depth"
predictors <- stack(b, slope4, slope8, aspect4, aspect8, tpi, tri, roughness, flowdir)
plot(predictors)
names(predictors)
namesp <- names(predictors)
# save
#writeRaster(predictors, paste(s.dir,"predictors_coarse.tif", sep='/'), overwrite=T)
#write.csv(namesp, paste(s.dir, "namespredictors.csv", sep='/'))
# load predictors
predictors <- stack(paste(s.dir,"predictors_coarse.tif", sep='/'))
namesp <- read.csv(paste(s.dir,"namespredictors.csv", sep='/'))
names(predictors) <- namesp[,2]
### Extract predictor values for each observation ----
hp <- raster::extract(predictors, h, sp=T)
hp
hab_pred <- as.data.frame(hp)
head(hab_pred)
str(hab_pred) # 837 observations
names(hab_pred)
## remove unwanted columns ----
#tv_dom <- hab_pred[,c(2:4,14, 16:24)] # not sure what to remove for AUV
tv_dom <- hab_pred
names(tv_dom)
sp1 <- tv_dom
coordinates(sp1) <- ~longitude+latitude
plot(b)
#plot(sp1, border="white", col="lightgrey", add=TRUE)
plot(sp1, pch=20, col=sp1$Max_if_2_habitats_have_same, add=TRUE)
## Filter per cell ----
# AUV data has many images / pixel
# More frequent dominant class/pixel
# to get coordinates of each cell and the value --
d <- data.frame(coordinates(b2), count=b2[])
head(d)
str(d)
# https://gis.stackexchange.com/questions/279079/extracting-value-of-raster-with-coordinates-using-r
# extract cell ids with points on them --
result <- raster::extract(b2, sp1, cellnumbers=T, df=T)
head(result)
str(result)
result$cells <- as.factor(result$cells)
cellid <- as.data.frame(result %>%
group_by(cells, GB_Bathy_250m) %>%
# group_by(Class) %>%
summarize(n()))
str(cellid) # 321 obs
head(cellid)
cellid1 <- aggregate(GB_Bathy_250m~cells, data=result, mean)
str(cellid1) # 321 obs -> 321 cells with TV data
# extract as spatial points cell ids --
resultsp <- raster::extract(b2, sp1, cellnumbers=T, coordinates = T ,sp =T)
resultsp
head(resultsp)
# get the coordinates --
rdf <- as.data.frame(resultsp)
str(rdf)
rdf$cells <- as.factor(rdf$cells)
rdflat <- aggregate(latitude ~ cells, data=rdf, FUN=mean)
rdflat
str(rdflat) # 321 obs
rdflon <- aggregate(longitude ~ cells, data=rdf, FUN=mean)
str(rdflon)
rdflon
rdfcoords <- merge(rdflon, rdflat)
str(rdfcoords) # 321 obs
# make auv points a df
sp1df <- as.data.frame(sp1)
head(sp1df)
# join auv poins and cell ids
sp1cells <- cbind(sp1df, result)
head(sp1cells)
## aggregate by Class --
# rename Class column
colnames(sp1cells)[colnames(sp1cells)=="Max_if_2_habitats_have_same"] <- "Class"
names(sp1cells)
str(sp1cells)
sp1cells$cells <- as.factor(sp1cells$cells)
names(sp1cells)
sp1cells <- sp1cells[,-25]
# to get the dominant class and the cell id --
letsee <- as.data.frame(sp1cells %>%
group_by(cells, Class) %>%
# group_by(Class) %>%
summarize(n()))
head(letsee) # has cellnumbers but not coordinates
str(letsee) # 532 obs
names(letsee) <- c("cells", "Class", "n")
str(letsee) # 532 obs
## aggregate data frame by cell and max n()
### Up to here ####
# https://stackoverflow.com/questions/6289538/aggregate-a-dataframe-on-a-given-column-and-display-another-column
domhcell <- aggregate(n ~ cells, data=letsee, max)
head(domhcell)
str(domhcell) # 321 obs ## I need class info..
# split the data using split: to get class with max n in each cell id
#https://stackoverflow.com/questions/6289538/aggregate-a-dataframe-on-a-given-column-and-display-another-column
splitdf <- do.call(rbind,lapply(split(letsee,letsee$cells), function(chunk) chunk[which.max(chunk$n),]))
splitdf
str(splitdf) # 321 obs
# match cell ids to lats and longs ---
coarseauv <- merge(splitdf, rdfcoords)
str(coarseauv) # 321 obs
head(coarseauv)
# check!
csp <- coarseauv
coordinates(csp) <- ~longitude+latitude
plot(b2)
plot(b3)
points(csp, pch = 20, cex=0.5, col=csp$Class)
# save
#writeOGR(csp, dsn= s.dir, layer= "GB_tv_coarse_bathy_filtered_habitat_dominant_broad", driver="ESRI Shapefile", overwrite_layer=TRUE)
#write.csv(coarseauv, paste(d.dir, "tidy", "GB_tv_coarse_bathy_filtered_habitat_dominant_broad.csv", sep='/'))
## Get predictor data for each point --
data <- readOGR(paste(s.dir, "GB_tv_coarse_bathy_filtered_habitat_dominant_broad.shp", sep='/'))
pts <- raster::extract(predictors, data, df=T)
head(pts)
str(pts)
datadf <- as.data.frame(data)
head(datadf)
str(datadf)
# join predictor info to classes --
dnew <- cbind(datadf, pts)
head(dnew)
# make sp points
dnews <- dnew
coordinates(dnews) <- ~coords.x1+coords.x2
plot(b2)
points(dnews,pch = 20, cex=1, col=dnews$Class)
# save
writeOGR(dnews, dsn= s.dir, layer= "GB_tv_coarse_bathy_filtered_habitat_dominant_broad", driver="ESRI Shapefile", overwrite_layer=TRUE)
write.csv(dnew, paste(d.dir, "tidy", "GB_tv_coarse_bathy_filtered_habitat_dominant_broad.csv", sep='/'))