# Advanced density surface models ### \textit{Practical 5, Intermediate Distance Sampling workshop, CREEM, 2018} ## Aims By the end of this practical, you should feel comfortable: - Fitting DSMs with multiple smooth terms in them - Selecting smooth terms by $p$-values - Using shrinkage smoothers - Selecting between models using deviance, AIC, REML score - Investigating concurvity in DSMs with multiple smooths - Investigating sensitivity sensitivity and path dependence ## Load data and packages ```{r pdfmakerdsmadv, echo=FALSE} pdf <- FALSE ``` ```{r load-packages-03} library(Distance) library(dsm) library(ggplot2) library(knitr) library(plyr) library(reshape2) ``` Loading the data processed from GIS and the fitted detection function objects from the previous exercises: ```{r load-data-03} load("sperm-data.RData") load("df-models.RData") ``` ## Exploratory analysis We can do some exploratory analysis by aggregating the counts to each cell and plotting what's going on. *Don't worry about understanding what this code is doing at the moment.* ```{r make-data} # join the observations onto the segments join_dat <- join(segs, obs, by="Sample.Label", type="full") # sum up the observations per segment n <- ddply(join_dat, .(Sample.Label), summarise, n=sum(size), .drop = FALSE) # sort the segments by their labsl segs_eda <- segs[sort(segs$Sample.Label),] # make a new column for the counts segs_eda$n <- n$n # remove the columns we don't need, segs_eda$CentreTime <- NULL segs_eda$POINT_X <- NULL segs_eda$POINT_Y <- NULL segs_eda$segment.area <- NULL segs_eda$off.set <- NULL segs_eda$CenterTime <- NULL segs_eda$Effort <- NULL segs_eda$Length <- NULL segs_eda$SegmentID <- NULL segs_eda$coords.x1 <- NULL segs_eda$coords.x2 <- NULL # "melt" the data so we have four columns: # Sample.Label, n (number of observations), # variable (which variable), value (its value) segs_eda <- melt(segs_eda, id.vars=c("Sample.Label", "n")) # try head(segs_eda) ``` Finally, we can plot histograms of counts for different values of the covariates: ```{r, histcovar, fig.cap="Histograms of segment counts at various covariate levels."} p <- ggplot(segs_eda) + geom_histogram(aes(value, weight=n)) + facet_wrap(~variable, scale="free") + xlab("Covariate value") + ylab("Aggregated counts") print(p) ``` We can also just plot the counts against the covariates, note the high number of zeros (but still some interesting patterns): ```{r, countcovar, fig.cap="Relationship of segment counts to covariate values."} p <- ggplot(segs_eda) + geom_point(aes(value, n)) + facet_wrap(~variable, scale="free") + xlab("Covariate value") + ylab("Aggregated counts") print(p) ``` These plots give a very rough idea of the relationships we can expect in the model. Notably these plots don't take into account interactions between the variables and potential correlations between the terms, as well as detectability. ## Pre-model fitting As we did in the previous exercise we must remove the observations from the spatial data that we excluded when we fitted the detection function -- those observations at distances greater than the truncation. ```{r truncate-obs-03} obs <- obs[obs$distance <= df_hn$ddf$meta.data$width,] ``` Here we've used the value of the truncation stored in the detection function object, but we could also use the numeric value (which we can also find by checking the model's `summary()`). Again note that if you want to fit DSMs using detection functions with different truncation distances, then you'll need to reload the `sperm-data.RData` and do the truncation again for that detection function. ## Our new friend `+` We can build a really big model using `+` to include all the terms that we want in the model. We can check what's available to us by using `head()` to look at the segment table: ```{r seg-table} head(segs) ``` We can then fit a model with the available covariates in it, each as an `s()` term. ```{r nb-xy-03} dsm_nb_xy_ms <- dsm(count~s(x,y, bs="ts") + s(Depth, bs="ts") + s(DistToCAS, bs="ts") + s(SST, bs="ts") + s(EKE, bs="ts") + s(NPP, bs="ts"), df_hn, segs, obs, family=nb()) summary(dsm_nb_xy_ms) ``` Notes: 1. We're using `bs="ts"` to use the shrinkage thin plate regression spline. More technical detail on these smooths can be found on their manual page `?smooth.construct.ts.smooth.spec`. 2. We've not specified basis complexity (`k`) at the moment. Note that if you want to specify the same complexity for multiple terms, it's often easier to make a variable that can then be given as `k` (for example, setting `k1<-15` and then setting `k=k1` in the required `s()` terms). ### Plot Let's plot the smooths from this model: ```{r plot-nb-xy, fig.cap="Smooths for all covariates with neg-binomial response distribution."} plot(dsm_nb_xy_ms, pages=1, scale=0) ``` Notes: 1. Setting `shade=TRUE` gives prettier confidence bands. 2. As with `vis.gam()` the response is on the link scale. 3. `scale=0` puts each plot on a different $y$-axis scale, making it easier to see the effects. Setting `scale=-1` will put the plots on a common $y$-axis scale We can also plot the bivariate smooth of `x` and `y` as we did before, using `vis.gam()`: ```{r nb-xy-visgam-03, fig.width=4, fig.height=4, fig.cap="Fitted surface with all environmental covariates, and neg-binomial response distribution."} vis.gam(dsm_nb_xy_ms, view=c("x","y"), plot.type="contour", too.far=0.1, main="s(x,y) (link scale)", asp=1) ``` Compare this plot to Figure \@ref(fig:nb-xy-visgam), generated in the previous practical when only `x` and `y` were included in the model. ### Check We can use `gam.check()` and `rqgam.check()` to look at the residual check plots for this model. Do this in the below gaps and comment on the resulting plots and diagnostics. ```{r check-xy} ``` ```{r rqcheck-xy} ``` Looking back through the lecture notes, do you see any problems in these plots or in the text output from `gam.check()`. You might decide from the diagnostics that you need to increase `k` for some of the terms in the model. Do this and re-run the above code to ensure that the smooths are flexible enough. The `?choose.k` manual page can offer some guidance. Generally if the EDF is close to the value of `k` you supplied, it's worth doubling `k` and refitting to see what happens. You can always switch back to the smaller `k` if there is little difference. ### Select terms As was covered in the lectures, we can select terms by (approximate) $p$-values and by looking for terms that have EDFs significantly less than 1 (those which have been shrunk). Decide on a significance level that you'll use to discard terms in the model. Remove the terms that are non-significant at this level and re-run the above checks, summaries and plots to see what happens. It's helpful to make notes to yourself as you go It's easiest to either comment out the terms that are to be removed (using `#`) or by copying the code chunk above and pasting it below. Having removed a smooth and reviewed your model, you may decide you wish to remove another. Follow the process again, removing a term, looking at plots and diagnostics. ### Compare response distributions Use the `gam.check()` to compare quantile-quantile plots between negative binomial and Tweedie distributions for the response. ## Estimated abundance as a response Again, we've only looked at models with `count` as the response. Try using a detection function with covariates and the `abundance.est` response in the chunk below: ```{r abund-est} ``` ## Concurvity Checking concurvity of terms in the model can be accomplished using the `concurvity()` function. ```{r concurvity-checks, fig.cap="Concurvity for model with many environmental covariates."} concurvity(dsm_nb_xy_ms) ``` By default the function returns a matrix of a measure of concurvity between one of the terms and the rest of the model. Compare the output of the models before and after removing terms. Reading these matrices can be laborious and not very fun. The function `vis.concurvity()` in the `dsm` package is used to visualise the concurvity *between terms* in a model by colour coding the matrix (and blanking out the redundant information). Again compare the results of plotting for models with different terms. ## Sensitivity ### Compare bivariate and additive spatial effects If we replace the bivariate smooth of location (`s(x, y)`) with an additive terms (`s(x)+s(y)`), we may see a difference in the final model (different covariates selected). ```{r nb-x-y} dsm_nb_x_y_ms <- dsm(count~s(x, bs="ts") + s(y, bs="ts") + s(Depth, bs="ts") + s(DistToCAS, bs="ts") + s(SST, bs="ts") + s(EKE, bs="ts") + s(NPP, bs="ts"), df_hn, segs, obs, family=nb()) summary(dsm_nb_x_y_ms) ``` Try performing model selection as before from this base model and compare the resulting models. Compare the resulting smooths from like terms in the model. For example, if depth were selected in both models, compare EDFs and plots, e.g.: ```{r compare-depth, fig.cap="Shape of depth covariate response with bivariate s(x,y) and univariate s(x)+s(y)."} par(mfrow=c(1,2)) plot(dsm_nb_xy_ms, select=2) plot(dsm_nb_x_y_ms, select=3) ``` Note that there `select=` picks just one term to plot. These are in the order in which the terms occur in the `summary()` output (so you may well need to adjust the above code). ## Comparing models As with the detection functions in the earlier exercises, here is a quick function to generate model results tables with appropriate summary statistics: ```{r summarize-models} summarize_dsm <- function(model){ summ <- summary(model) data.frame(response = model$family$family, terms = paste(rownames(summ$s.table), collapse=", "), AIC = AIC(model), REML = model$gcv.ubre, "Deviance_explained" = paste0(round(summ$dev.expl*100,2),"%") ) } ``` We can make a list of the models and pass the list to the above function. ```{r apply-summary} # add your models to this list! model_list <- list(dsm_nb_x_y_ms, dsm_nb_xy_ms) library(plyr) summary_table <- ldply(model_list, summarize_dsm) row.names(summary_table) <- c("dsm_nb_x_y_ms", "dsm_nb_xy_ms") ``` ```{r print-table-03, results="asis"} summary_table <- summary_table[order(summary_table$REML, decreasing=TRUE),] kable(summary_table, caption = "Model performance of s(x,y) and s(x)+s(y) in presence of other covariates.") ``` ## Saving models Now save the models that you'd like to use to predict with later. I recommend saving as many models as you can so you can compare their results in the next practical. ```{r save-models-03} # add your models here save(dsm_nb_xy_ms, dsm_nb_x_y_ms, file="dsms.RData") ```