-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path.Rhistory
512 lines (512 loc) · 25.2 KB
/
.Rhistory
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
plot(joint_train_weightsG0,ylim =c(0,1 ),ylab='Case Weight',xlab = 'Case Index',cex = 1)
abline(v = 2016,col = "darkgrey",lty = 2, lwd = 3)
dev.off()
wghtFig <-paste0(outDir,SP,'_caseWeights_gam.png')
varNames <- names(transformedCovars_AcOnly.train)
varNamesFormula <- varNames[2:10]
formulaAcOnly_allVars <-paste('s(', varNamesFormula, ", bs = 'ts', k = kVal)", sep = "", collapse = ' + ')
formulaAcOnly_allVars <- as.formula(paste('yAcOnly_TF ~',formulaAcOnly_allVars))
gam_full_AcOnly <- gam(formulaAcOnly_allVars,
data = transformedCovars_AcOnly.train,
na.action = na.omit,family = binomial())
formulaVisOnly_allVars <-paste('s(', varNamesFormula, ", bs = 'ts', k = kVal)", sep = "", collapse = ' + ')
formulaVisOnly_allVars <- as.formula(paste('yVisOnly_TF ~',formulaVisOnly_allVars))
gam_full_VisOnly <- gam(formulaVisOnly_allVars,
data = transformedCovars_VisOnly.train,
na.action = na.omit,family = binomial(),
weights = VisOnly.train_weightsG0)
formulaJoint_allVars <-paste('s(', varNamesFormula, ", bs = 'ts', k = kVal)", sep = "", collapse = ' + ')
formulaJoint_allVars <- as.formula(paste('y_TF ~',formulaJoint_allVars))
gam_full_Joint <- gam(formulaJoint_allVars,
data = transformedCovars.train,
weights = joint_train_weightsG0,
na.action = na.omit,family = binomial())
# Save models if re-calculating everything
save(gam_full_AcOnly_TF,file = paste(outDir,SP,'_AcOnly_binomial_GAMs_ALL.Rdata',sep=''))
save(gam_full_VisOnly_TF,file = paste(outDir,SP,'_VisOnly_binomial_GAMs_ALL.Rdata',sep=''))
save(gam_full_Joint_TF,file = paste(outDir,SP,'_binomial_GAMs_ALL.Rdata',sep=''))
# alternative if models are already calculated
load(paste(outDir,SP,'_AcOnly_binomial_GAMs_ALL.Rdata',sep=''))
load(paste(outDir,SP,'_VisOnly_binomial_GAMs_ALL.Rdata',sep=''))
load(paste(outDir,SP,'_binomial_GAMs_ALL.Rdata',sep=''))
AcOnlySummary <- summary(gam_full_AcOnly)
# AcOnlySummary
significantPvals_AcOnly <- which(AcOnlySummary$s.pv<=.05)
# rerun model with only significant predictors
formulaAcOnly_prunedVars <-paste('s(', varNamesFormula[significantPvals_AcOnly], ", bs = 'ts', k = kVal)", sep = "", collapse = ' + ')
formulaAcOnly_prunedVars <- as.formula(paste('yAcOnly_TF ~',formulaAcOnly_prunedVars))
AcOnly_model <- gam(formulaAcOnly_prunedVars,
data = transformedCovars_AcOnly.train,
na.action = na.omit,family = binomial())
summary(AcOnly_model)
nTerms <- size(AcOnly_model$smooth,2)
png(paste(outDir,SP,'_AcOnly_smooths_pres_abs.png',sep=''), res = 300, units = "in", width = 6.5, height = ceil(nTerms/3)*2)
par(mfrow = c(ceil(nTerms/3),3),mar = c(4,2,1,1))
for (i in 1:nTerms) {
plot(AcOnly_model,select = i,
cex.lab = 1.3,cex.axis = 1.1,scale=0,xlab = varUnits[significantPvals_AcOnly[i]], ylab = "")
}
dev.off()
smoothFig <-paste0(outDir,SP,'_AcOnly_smooths_pres_abs.png')
plot(residuals.gam(AcOnly_model))
# gam.check(AcOnly_gam_pruned_TF_best)
VisOnlySummary <- summary(gam_full_VisOnly)
# VisOnlySummary
significantPvals_VisOnly <- which(VisOnlySummary$s.pv<=.05)
# rerun model with only significant predictors
formulaVisOnly_prunedVars <-paste('s(', varNamesFormula[significantPvals_VisOnly], ", bs = 'ts', k = kVal)", sep = "", collapse = ' + ')
formulaVisOnly_prunedVars <- as.formula(paste('yVisOnly_TF ~',formulaVisOnly_prunedVars))
VisOnly_model <- gam(formulaVisOnly_prunedVars,
data = transformedCovars_VisOnly.train,
family = binomial(),
weights = VisOnly.train_weightsG0)
summary(VisOnly_model)
nTerms <- size(VisOnly_model$smooth,2)
png(paste(outDir,SP,'_VisOnly_smooths_pres_abs.png',sep=''), res = 300, units = "in", width = 6.5, height = ceil(nTerms/3)*2)
par(mfrow = c(ceil(nTerms/3),3),mar = c(4,2,1,1))
for (i in 1:nTerms) {
plot(VisOnly_model,select = i,
cex.lab = 1.3,cex.axis = 1.1,scale=0,xlab = varUnits[significantPvals_VisOnly[i]], ylab = "")
}
dev.off()
smoothFig <-paste0(outDir,SP,'_VisOnly_smooths_pres_abs.png')
plot(residuals.gam(VisOnly_model))
# gam.check(VisOnly_gam_pruned_TF_best)
JointSummary <- summary(gam_full_Joint)
# JointSummary
significantPvals_Joint <- which(JointSummary$s.pv<=.05)
# rerun model with only significant predictors
formulaJoint_prunedVars <-paste('s(', varNamesFormula[significantPvals_Joint], ", bs = 'ts', k = kVal)", sep = "", collapse = ' + ')
formulaJoint_prunedVars <- as.formula(paste('y_TF ~',formulaJoint_prunedVars))
Joint_model <- gam(formulaJoint_prunedVars,
data = transformedCovars.train,
weights = joint_train_weightsG0,
na.action = na.omit,
family = binomial())
summary(Joint_model)
significantPvals_Joint
nTerms <- size(Joint_model$smooth,2)
png(paste(outDir,SP,'_Joint_smooths_pres_abs.png',sep=''), res = 300, units = "in", width = 6, height = ceil(nTerms/5)*2)
n3 <- c("SST","SSH","CHL","MLD","SAL","CUR","Upwell","-Eddy","+Eddy")
windowsFonts(A = windowsFont("Times New Roman"))
par(mfrow = c(ceil(nTerms/4),4),mar = c(4,2,1,1))
for (i in 1:nTerms) {
plot(Joint_model,select = i,
cex.lab = 1.3,cex.axis = 1.1,scale=0,xlab = n3[significantPvals_Joint[i]], ylab = "",family = "A")
}
dev.off()
smoothFig <-paste0(outDir,SP,'_Joint_smooths_pres_abs.png')
knitr::opts_chunk$set(echo = TRUE)
library(mgcv)
library(MASS)
library(rgdal)
library(raster)
library(ggplot2)
library(rgeos)
library(mapview)
library(leaflet)
library(psych)
library(broom)
library(plotrix)
library(magrittr)
library(colorRamps)
library(lubridate)
library(HabitatProject)
library(lmtest)
library(zoo)
library(pracma)
library(grid)
library(zoo)
library(tmap)
source('E:/NASData/AcoustoVisualDE/AcoustoVisualDE/HabitatProject/R/multiplot.R')
source('E:/NASData/AcoustoVisualDE/AcoustoVisualDE/HabitatProject/R/plot_missingdata.R')
source('E:/NASData/AcoustoVisualDE/AcoustoVisualDE/HabitatProject/R/plot_cleveland.R')
source('E:/NASData/AcoustoVisualDE/AcoustoVisualDE/HabitatProject/R/plot_covarDensity.R')
source('E:/NASData/AcoustoVisualDE/AcoustoVisualDE/HabitatProject/R/plot_timeseries.R')
source('E:/NASData/AcoustoVisualDE/AcoustoVisualDE/HabitatProject/R/transform_covars.R')
options(stringsAsFactors = FALSE)
# load some preferences
load('E:/NASData/ModelData/Pm/setup_info_Pm.Rdata')
load('E:/NASData/ModelData/Pm/PmMergedData.Rdata')
outDir <- file.path('E:/NASData/ModelData',SP,'/')
plotCols1 <-c(7:10,14,16,19,22,23)
covarList<-names(mergedSegments[c(plotCols1)])
varUnits <- c("SST (C)","SSH (m)",expression("Chlorophyll A (mg/m"^3*")"),"MLD (m)", "Salinity (ppm)",
"Current Magnitude (m/sec)", "Upwelling (m/sec)",
"Dist. to Anti-Cyclonic Eddy (km)","Dist. to Cyclonic Eddy (km)")
names(varUnits)<-covarList
percFilled <- plot.missingdata(mergedSegments,covarList,
paste0(outDir,'AcousticAndVisual_',SP),varUnits)
percFilled <- plot.missingdata(AcOnlySegments,covarList,
paste0(outDir,'AcousticOnly_',SP),varUnits)
percFilled <- plot.missingdata(VisOnlySegments,covarList,
paste0(outDir,'VisualOnly_',SP),varUnits)
visDataAvailPlot <- paste0(savePath,'/VisualOnly_',SP,'_missingData.png')
# If you decide from the missing data plots that you want to restrict years going forward:
yearListIdx = as.numeric(format(mergedSegments$date,"%Y"))
yearListIdx_AcOnly = as.numeric(format(AcOnlySegments$date,"%Y"))
yearListIdx_VisOnly = as.numeric(format(VisOnlySegments$date,"%Y"))
isVisual <- mergedSegments$Category
keepDates.train <- which(yearListIdx != 2009 &
yearListIdx >= 2003 &
yearListIdx != 2013)
keepDates.test <- which(yearListIdx == 2009 |
yearListIdx == 2013)
keepDates_AcOnly.train <- which(yearListIdx_AcOnly != 2009 &
yearListIdx_AcOnly >= 2003 & yearListIdx_AcOnly <= 2012)
keepDates_AcOnly.test <- which(yearListIdx_AcOnly == 2009 |
yearListIdx_AcOnly == 2013)
keepDatesVisOnly.train <- which(yearListIdx_VisOnly != 2009 &
yearListIdx_VisOnly >= 2003)
keepDatesVisOnly.test <- which(yearListIdx_VisOnly == 2009 |
yearListIdx_VisOnly == 2013)
Train_Joint.set<- mergedSegments[keepDates.train,]
Train_AcOnly.set <- AcOnlySegments[keepDates_AcOnly.train,]
Train_VisOnly.set<- VisOnlySegments[keepDatesVisOnly.train,]
Test_Joint.set<- mergedSegments[keepDates.test,]
Test_AcOnly.set<- AcOnlySegments[keepDates_AcOnly.test,]
Test_VisOnly.set<- VisOnlySegments[keepDatesVisOnly.test,]
# Get test visual sightings
sightingsTrain <- Train_VisOnly.set[Train_VisOnly.set$Density>0,c('lat','long','date')]
sightingsTest <- Test_VisOnly.set[Test_VisOnly.set$Density>0,c('lat','long','date')]
HARPsites <- unique(Train_AcOnly.set[c('lat','long')])
pal <-colorFactor(palette = "RdYlGn",
domain = c(2003,2004,2009,2012,2014))
map1 <- leaflet() %>% setView(lng = -89.4, lat = 27.0, zoom = 6)%>%
addProviderTiles(providers$Esri.OceanBasemap) %>%
addCircleMarkers(data = sightingsTrain, lng = ~ long, lat = ~ lat,color = ~pal(year(date)),
stroke = TRUE, fillOpacity = 0.8, group = 'Training Set',radius = 4)%>%
addCircleMarkers(data = sightingsTest, lng = ~ long, lat = ~ lat,color = ~pal(year(date)),
stroke = TRUE, fillOpacity = 0.8, group = 'Test Set',radius = 4)%>%
addMarkers(data = HARPsites, lng = ~ long, lat = ~ lat) %>%
addLegend(pal = pal,values = c(2003,2004,2009,2012,2014),title = 'Year')
map1
plot.timeseries(siteList,outDir,AcOnlySegments)
MCTS <- paste0(outDir,SP,'_Timeseries_Site_MC.png')
GCTS <- paste0(outDir,SP,'_Timeseries_Site_GC.png')
DTTS <- paste0(outDir,SP,'_Timeseries_Site_DT.png')
### Identify Outliers
# Replace extreme outliers (bad data) with NaNs.
outlierList <-which(Train_Joint.set$CHL< -10)
Train_Joint.set$CHL[outlierList] <- NaN
#outlierList <-which(Train_Joint.set$FrontDist_Cayula>800000)
#Train_Joint.set$FrontDist_Cayula[outlierList] <- NaN
outlierList <-which(Train_Joint.set$Density>100000)
Train_Joint.set$Density[outlierList] <- NaN
outlierList <-which(Test_Joint.set$CHL< -10)
Test_Joint.set$CHL[outlierList] <- NaN
#outlierList <-which(Test_Joint.set$FrontDist_Cayula > 800000)
#Test_Joint.set$FrontDist_Cayula[outlierList] <- NaN
outlierList <-which(Test_Joint.set$Density>100000)
Test_Joint.set$Density[outlierList] <- NaN
outlierList <-which(Train_AcOnly.set$CHL< -10)
Train_AcOnly.set$CHL[outlierList] <- NaN
#outlierList <-which(Train_AcOnly.set$FrontDist_Cayula > 800000)
#Train_AcOnly.set$FrontDist_Cayula[outlierList] <- NaN
outlierList <-which(Train_AcOnly.set$Density > 100000)
Train_AcOnly.set$Density[outlierList] <- NaN
outlierList <-which(Test_AcOnly.set$CHL< -10)
Test_AcOnly.set$CHL[outlierList] <- NaN
#outlierList <-which(Test_AcOnly.set$FrontDist_Cayula>800000)
#Test_AcOnly.set$FrontDist_Cayula[outlierList] <- NaN
outlierList <-which(Test_AcOnly.set$Density>100000)
Test_AcOnly.set$Density[outlierList] <- NaN
outlierList <-which(Train_VisOnly.set$CHL< -10)
Train_VisOnly.set$CHL[outlierList] <- NaN
#outlierList <-which(Train_VisOnly.set$FrontDist_Cayula>800000)
#Train_VisOnly.set$FrontDist_Cayula[outlierList] <- NaN
outlierList <-which(Train_VisOnly.set$Density>100000)
Train_VisOnly.set$Density[outlierList] <- NaN
outlierList <-which(Test_VisOnly.set$CHL< -10)
Test_VisOnly.set$CHL[outlierList] <- NaN
#outlierList <-which(Test_VisOnly.set$FrontDist_Cayula>800000)
#Test_VisOnly.set$FrontDist_Cayula[outlierList] <- NaN
outlierList <-which(Test_VisOnly.set$Density>100000)
Test_VisOnly.set$Density[outlierList] <- NaN
plot.cleveland(Train_AcOnly.set,covarList,FALSE,paste0(outDir,'AcousticOnly_',SP),varUnits)
plot.cleveland(Train_VisOnly.set,covarList,FALSE,paste0(outDir,'VisualOnly_',SP),varUnits)
plot.cleveland(Train_Joint.set,covarList,FALSE,paste0(outDir,'AcousticAndVisual_',SP),varUnits)
ACclevelandPlot<-paste0(outDir,'AcousticOnly_',
SP,'_clevelandDots_noTransform.png')
VisclevelandPlot<-paste0(outDir,'VisualOnly_',
SP,'_clevelandDots_noTransform.png')
covarList2 <- c("Density","SST","SSH","CHL",
"HYCOM_MLD","HYCOM_SALIN_0","HYCOM_MAG_0",
"HYCOM_UPVEL_50",
"Neg_EddyDist","Pos_EddyDist",
"fac1","fac2","EffectiveArea")
# restrict covariates again to limited set
Train_Joint.set2<- Train_Joint.set[,covarList2]
Test_Joint.set2<- Test_Joint.set[,covarList2]
Train_AcOnly.set2<- Train_AcOnly.set[,covarList2]
Test_AcOnly.set2<- Test_AcOnly.set[,covarList2]
Train_VisOnly.set2<- Train_VisOnly.set[,covarList2]
Test_VisOnly.set2<- Test_VisOnly.set[,covarList2]
# without transform
png(paste(outDir,SP,'_correlations_noTransform.png',sep=''), width = 2000, height = 1600)
pairs.panels(Train_Joint.set2[,1:(length(covarList2)-2)], ellipses=FALSE, method = "spearman",cex.cor=.75)
dev.off()
png(paste(outDir,SP,'_correlations_noTransform_AcOnly.png',sep=''), width = 2000, height = 1600)
pairs.panels(Train_AcOnly.set2[,1:(length(covarList2)-2)], ellipses=FALSE, method = "spearman",cex.cor=.75)
dev.off()
png(paste(outDir,SP,'_correlations_noTransform_visOnly.png',sep=''), width = 2000, height = 1600)
pairs.panels(Train_VisOnly.set2[,1:(length(covarList2)-2)], ellipses=FALSE, method = "spearman",cex.cor=.75)
dev.off()
covarPlot <-paste0(outDir,SP,'_correlations_noTransform.png')
# covarList2 <- c("Density","SST","SSH","CHL",
# "HYCOM_MLD","HYCOM_SALIN_0","HYCOM_MAG_0",
# "HYCOM_UPVEL_50",
# "Neg_EddyDist", "PosEddyDist",
# "fac1","fac2")
transformList <- c("none","none","none","log10",
"log10","none","log10",
"none",
"none","none",
"none","none","none")
transformedCovars.train <-
transform.covars(Train_Joint.set2,covarList2,transformList)
transformedCovars.test <-
transform.covars(Test_Joint.set2,covarList2,transformList)
transformedCovars_AcOnly.train <-
transform.covars(Train_AcOnly.set2,covarList2,transformList)
transformedCovars_AcOnly.test <-
transform.covars(Test_AcOnly.set2,covarList2,transformList)
transformedCovars_VisOnly.train <-
transform.covars(Train_VisOnly.set2,covarList2,transformList)
transformedCovars_VisOnly.test <-
transform.covars(Test_VisOnly.set2,covarList2,transformList)
# Generate correlation plots with transform
png(paste(outDir,SP,'_correlations_withTransform.png',sep=''), width = 2000, height = 1600)
pairs.panels(transformedCovars.train[,2:(length(covarList2)-3)], ellipses=FALSE,
method = "spearman",cex.cor=1)
dev.off()
png(paste(outDir,SP,'_correlations_withTransform_AcOnly.png',sep=''),
width = 2000, height = 1600)
pairs.panels(transformedCovars_AcOnly.train[,1:(length(covarList2)-2)],
ellipses=FALSE, method = "spearman",cex.cor=.75)
dev.off()
png(paste(outDir,SP,'_correlations_withTransform_visOnly.png',sep=''),
width = 2000, height = 1600)
pairs.panels(transformedCovars_VisOnly.train[,1:(length(covarList2)-2)],
ellipses=FALSE, method = "spearman",cex.cor=.75)
dev.off()
# Plotting the transformed variables:
plotCols = colnames(transformedCovars.train)[c(2:10)]
names(varUnits)<-plotCols
varUnits["log10_HYCOM_MAG_0"]<-expression("log"[10]*"(Current Magnitude (m/sec))")
varUnits["log10_HYCOM_MLD"]<- expression("log"[10]*"(MLD (m))")
varUnits["log10_CHL"] <-expression("log"[10]*"(Chorophyll A (mg/m"^3*"))")
plot.cleveland(transformedCovars.train,
plotCols,TRUE,paste0(outDir,'AcousticAndVisual_',SP),varUnits)
plot.cleveland(transformedCovars_AcOnly.train,
plotCols,TRUE,paste0(outDir,'AcousticOnly_',SP),varUnits)
plot.cleveland(transformedCovars_VisOnly.train,
plotCols,TRUE,paste0(outDir,'VisualOnly_',SP),varUnits)
clevlandJointTransformed<-paste0(savePath,
'/AcousticAndVisual_',SP,'_clevelandDots_withTransform.png')
plot.covarDensity(transformedCovars.train[,2:10],
colnames(transformedCovars.train[,2:10]),
transformedCovars.train$Density,paste0(outDir,'Both_',SP),varUnits)
plot.covarDensity(transformedCovars_AcOnly.train[,2:10],
colnames(transformedCovars_AcOnly.train[2:10]),
transformedCovars_AcOnly.train$Density,paste0(outDir,'AcousticOnly_',SP),varUnits)
plot.covarDensity(transformedCovars_VisOnly.train[,2:10],
colnames(transformedCovars_VisOnly.train[,2:10]),
transformedCovars_VisOnly.train$Density,paste0(outDir,'VisualOnly_',SP),varUnits)
acKernels <-paste0(savePath,'/AcousticOnly_',SP,'_density_pres_abs.png')
visKernels <- paste0(savePath,'/VisualOnly_',SP,'_density_pres_abs.png')
visDetProbData<-paste0(outDir,SP,'sightwTrunc_GU.Rdata')
load(visDetProbData)
visDetProb <- detFun[[bestModelIdx]]$fitted[1]
visDetProbFigure <- paste0(outDir,SP,'sightwTrunc_GU.png')
pOccur <- read.csv(pOccurenceFile, header = TRUE,na.strings=c('',' ','NA','NaN'))
# set up weighting
visDetProb <- detFun[[bestModelIdx]]$fitted[1]
transformedCovars_AcOnly.train$yAcOnly <- transformedCovars_AcOnly.train$Density
transformedCovars_VisOnly.train$yVisOnly <- transformedCovars_VisOnly.train$Density
transformedCovars.train$y <- transformedCovars.train$Density
transformedCovars_AcOnly.test$yAcOnly <- transformedCovars_AcOnly.test$Density
transformedCovars_VisOnly.test$yVisOnly <- transformedCovars_VisOnly.test$Density
transformedCovars.test$y <- transformedCovars.test$Density
# make some factors and calculate introduce column of g0 weights
joint_train_weightsG0<- array(data = 1, dim = c(length(transformedCovars.train$fac1),1))
joint_test_weightsG0<- array(data = 1, dim = c(length(transformedCovars.test$fac1),1))
for (iFac in 1:length(transformedCovars.train$fac1)) {
if (!is.na(transformedCovars.train$fac1[iFac]) & !is.na(transformedCovars.train$Density[iFac])){
if (transformedCovars.train$fac1[iFac]>5) {
if (transformedCovars.train$Density[iFac]==0){
# if it's visual data and it's a zero, adjust by g0 ie, only a X% chance it was a true zero.
joint_train_weightsG0[iFac,1] <- visG0*visDetProb
}
}
}
}
maxEffectiveAreaJoint <- max(c(transformedCovars.train$EffectiveArea,
transformedCovars.test$EffectiveArea))
# do additional adjustment for effective area
joint_train_weightsG0 <- joint_train_weightsG0*
(transformedCovars.train$EffectiveArea/maxEffectiveAreaJoint)
for (iFac in 1:length(transformedCovars.test$fac1)) {
if (!is.na(transformedCovars.test$fac1[iFac]) & !is.na(transformedCovars.test$Density[iFac])){
if (transformedCovars.test$fac1[iFac]>5) {
if (transformedCovars.test$Density[iFac]==0){
# if it's visual data and it's a zero, adjust by g0 ie, only a X% chance it was a true zero.
joint_test_weightsG0[iFac,1] <- visG0*visDetProb
}
}
}
}
# do additional adjustment for effective area
joint_test_weightsG0 <- joint_test_weightsG0*
(transformedCovars.test$EffectiveArea/maxEffectiveAreaJoint)
VisOnly.train_weightsG0<- array(data = 1, dim = c(length(transformedCovars_VisOnly.train$fac1),1))
VisOnly.test_weightsG0<- array(data = 1, dim = c(length(transformedCovars_VisOnly.test$fac1),1))
for (iFac in 1:length(transformedCovars_VisOnly.train$fac1)) {
if (!is.na(transformedCovars_VisOnly.train$Density[iFac]) &
transformedCovars_VisOnly.train$Density[iFac]==0){
# if it's visual data and it's a zero, adjust by g0 ie, only a X% chance it was a true zero.
VisOnly.train_weightsG0[iFac,1] <- visG0*visDetProb
}
}
maxEffectiveAreaVis <- max(c(transformedCovars_VisOnly.train$EffectiveArea,
transformedCovars_VisOnly.test$EffectiveArea))
# do additional adjustment for effective area
VisOnly.train_weightsG0 <- VisOnly.train_weightsG0*
(transformedCovars_VisOnly.train$EffectiveArea/maxEffectiveAreaVis)
for (iFac in 1:length(transformedCovars_VisOnly.test$fac1)) {
if (!is.na(transformedCovars_VisOnly.test$Density[iFac]) &
transformedCovars_VisOnly.test$Density[iFac]==0){
# if it's visual data and it's a zero, adjust by g0 ie, only a X% chance it was a true zero.
VisOnly.test_weightsG0[iFac,1] <- visG0*visDetProb
}
}
# do additional adjustment for effective area
VisOnly.test_weightsG0 <- VisOnly.test_weightsG0*
(transformedCovars_VisOnly.test$EffectiveArea/maxEffectiveAreaVis)
# Remove NaNs
goodData_Ac <- which(!is.na(rowSums(transformedCovars_AcOnly.train)))
AcOnly.train.NoNa <- transformedCovars_AcOnly.train[goodData_Ac,]
goodData_Vis <- which(!is.na(rowSums(transformedCovars_VisOnly.train)))
VisOnly.train.NoNa <- transformedCovars_VisOnly.train[goodData_Vis,]
goodData_Joint <- which(!is.na(rowSums(transformedCovars.train)))
Joint.train.NoNa <- transformedCovars.train[goodData_Joint,]
goodData_Ac_test <- which(!is.na(rowSums(transformedCovars_AcOnly.test)))
AcOnly.test.NoNa <- transformedCovars_AcOnly.test[goodData_Ac_test,]
goodData_Vis_test <- which(!is.na(rowSums(transformedCovars_VisOnly.test)))
VisOnly.test.NoNa <- transformedCovars_VisOnly.test[goodData_Vis_test,]
goodData_Joint_test <- which(!is.na(rowSums(transformedCovars.test)))
Joint.test.NoNa <- transformedCovars.test[goodData_Joint_test,]
kVal <- 3
gam_full_AcOnly<- NULL
gam_full_VisOnly<- NULL
gam_full_Joint<- NULL
# save ranges of each scaled covariate in training set (max and min)
JointRangesMax <- apply(transformedCovars.train, MARGIN = 2,
function(x) max(x, na.rm=TRUE))
JointRangesMin <- apply(transformedCovars.train, MARGIN = 2,
function(x) min(x, na.rm=TRUE))
AcOnlyRangesMax <- apply(transformedCovars_AcOnly.train, MARGIN = 2,
function(x) max(x, na.rm=TRUE))
AcOnlyRangesMin <- apply(transformedCovars_AcOnly.train, MARGIN = 2,
function(x) min(x, na.rm=TRUE))
VisOnlyRangesMax <- apply(transformedCovars_VisOnly.train, MARGIN = 2,
function(x) max(x, na.rm=TRUE))
VisOnlyRangesMin <- apply(transformedCovars_VisOnly.train, MARGIN = 2,
function(x) min(x, na.rm=TRUE))
varNames <- names(transformedCovars_AcOnly.train)
varNamesFormula <- varNames[2:10]
formulaAcOnly_allVars <-paste('s(', varNamesFormula, ", bs = 'ts', k = kVal)", sep = "", collapse = ' + ')
formulaAcOnly_allVars <- as.formula(paste('yAcOnly ~',formulaAcOnly_allVars))
gam_full_AcOnly <- gam(formulaAcOnly_allVars,
data = transformedCovars_AcOnly.train,
na.action = na.omit,family = tw())
formulaVisOnly_allVars <-paste('s(', varNamesFormula, ", bs = 'ts', k = kVal)", sep = "", collapse = ' + ')
formulaVisOnly_allVars <- as.formula(paste('yVisOnly ~',formulaVisOnly_allVars))
gam_full_VisOnly <- gam(formulaVisOnly_allVars,
data = transformedCovars_VisOnly.train,
na.action = na.omit,
family = Tweedie(p = 1.5, link = log),
weights = VisOnly.train_weightsG0)
formulaJoint_allVars <-paste('s(', varNamesFormula, ", bs = 'ts', k = kVal)", sep = "", collapse = ' + ')
formulaJoint_allVars <- as.formula(paste('y ~',formulaJoint_allVars))
gam_full_Joint <- gam(formulaJoint_allVars,
data = transformedCovars.train,
weights = joint_train_weightsG0,
na.action = na.omit,
family = Tweedie(p = 1.5, link = log))
# Save models if re-calculating everything
save(gam_full_AcOnly,file = paste(outDir,SP,'_AcOnly_tw_GAMs_Density.Rdata',sep=''))
save(gam_full_VisOnly,file = paste(outDir,SP,'_VisOnly_tw_GAMs_Density.Rdata',sep=''))
save(gam_full_Joint,file = paste(outDir,SP,'_Joint_tw_GAMs_Density.Rdata',sep=''))
# alternative if models are already calculated
load(paste(outDir,SP,'_AcOnly_tw_GAMs_Density.Rdata',sep=''))
load(paste(outDir,SP,'_VisOnly_tw_GAMs_Density.Rdata',sep=''))
load(paste(outDir,SP,'_Joint_tw_GAMs_Density.Rdata',sep=''))
AcOnlySummary <- summary(gam_full_AcOnly)
# AcOnlySummary
significantPvals_AcOnly <- which(AcOnlySummary$s.pv<=.05)
# rerun model with only significant predictors
formulaAcOnly_prunedVars <-paste('s(', varNamesFormula[significantPvals_AcOnly], ", bs = 'ts', k = kVal)", sep = "", collapse = ' + ')
formulaAcOnly_prunedVars <- as.formula(paste('yAcOnly ~',formulaAcOnly_prunedVars))
AcOnly_model <- gam(formulaAcOnly_prunedVars,
data = transformedCovars_AcOnly.train,
na.action = na.omit,family = tw())
summary(AcOnly_model)
nTerms <- size(AcOnly_model$smooth,2)
png(paste(outDir,SP,'_AcOnly_smooths_density.png',sep=''), res = 300, units = "in", width = 6.5, height = ceil(nTerms/3)*2)
varUnitsAc <-varNamesFormula[significantPvals_AcOnly]
par(mfrow = c(ceil(nTerms/3),3),mar = c(4,2,1,1))
for (i in 1:nTerms) {
plot(AcOnly_model,select = i,
cex.lab = 1.3,cex.axis = 1.1,scale=0,xlab = varUnitsAc[i], ylab = "")
}
dev.off()
smoothFig <-paste0(outDir,SP,'_AcOnly_smooths_density.png')
plot(residuals.gam(AcOnly_model))
# gam.check(AcOnly_gam_pruned_TF_best)
VisOnlySummary <- summary(gam_full_VisOnly)
# VisOnlySummary
significantPvals_VisOnly <- which(VisOnlySummary$s.pv<=.05)
# rerun model with only significant predictors
formulaVisOnly_prunedVars <-paste('s(', varNamesFormula[significantPvals_VisOnly], ", bs = 'ts', k = kVal)", sep = "", collapse = ' + ')
formulaVisOnly_prunedVars <- as.formula(paste('yVisOnly ~',formulaVisOnly_prunedVars))
VisOnly_model <- gam(formulaVisOnly_prunedVars,
data = transformedCovars_VisOnly.train,
family = Tweedie(p = 1.5, link = log),
weights = VisOnly.train_weightsG0)
summary(VisOnly_model)
nTerms <- size(VisOnly_model$smooth,2)
png(paste(outDir,SP,'_VisOnly_smooths_density.png',sep=''), res = 300, units = "in", width = 6.5, height = ceil(nTerms/3)*2)
par(mfrow = c(ceil(nTerms/3),3),mar = c(4,2,1,1))
for (i in 1:nTerms) {
plot(VisOnly_model,select = i,
cex.lab = 1.3,cex.axis = 1.1,scale=0,xlab = varUnits[i], ylab = "")
}
dev.off()
smoothFig <-paste0(outDir,SP,'_VisOnly_smooths_density.png')
#plot(residuals.gam(VisOnly_model))
plot(residuals.gam(VisOnly_model)*VisOnly_model$prior.weights)
# gam.check(VisOnly_gam_pruned_TF_best)
JointSummary <- summary(gam_full_Joint)
# JointSummary
significantPvals_Joint <- which(JointSummary$s.pv<=.05)
# rerun model with only significant predictors
formulaJoint_prunedVars <-paste('s(', varNamesFormula[significantPvals_Joint], ", bs = 'ts', k = kVal)", sep = "", collapse = ' + ')
formulaJoint_prunedVars <- as.formula(paste('y ~',formulaJoint_prunedVars))
Joint_model <- gam(formulaJoint_prunedVars,
data = transformedCovars.train,
weights = joint_train_weightsG0,
na.action = na.omit,
family = Tweedie(p = 1.5, link = log))
summary(Joint_model)
nTerms <- size(Joint_model$smooth,2)
windowsFonts(A = windowsFont("Times New Roman"))
png(paste(outDir,SP,'_Joint_smooths_density.png',sep=''), res = 300, units = "in", width =5, height = ceil(nTerms/4)*1.5)
n3 = c("SST","SSH","CHL","MLD","SAL","CUR","Upwell","-Eddy","+Eddy")
par(mfrow = c(ceil(nTerms/4),4),mar = c(4,2,1,1))
for (i in 1:nTerms) {
plot(Joint_model,select = i,
cex.lab = 1.5,cex.axis = 1.3,scale=0,xlab = n3[significantPvals_Joint[i]], ylab = "", family = "A")
}
dev.off()
smoothFig <-paste0(outDir,SP,'_Joint_smooths_density.png')