├── surveyIndex ├── R │ ├── deg2rad.R │ ├── gcd.hf.R │ ├── concTransform.R │ ├── exportSI.R │ ├── internalCons.R │ ├── externalCons.R │ ├── getSurveyIdxStratMean.R │ ├── anova.SI.R │ ├── fixAgeGroup.R │ ├── getEffect.R │ ├── getBathyGrid.R │ ├── getGrid.R │ ├── removeZeroClusters.R │ ├── resid.R │ ├── simulate.R │ ├── retroLO.R │ ├── surveyIdxPlots.R │ └── getSurveyIdx.R ├── man │ ├── concTransform.Rd │ ├── anova.SI.Rd │ ├── plot.surveyIndexGrid.Rd │ ├── qres.tweedie.Rd │ ├── internalCons.Rd │ ├── getGrid.Rd │ ├── AIC.surveyIdx.Rd │ ├── residuals.surveyIdx.Rd │ ├── factorplot.Rd │ ├── exportSI.Rd │ ├── externalCons.Rd │ ├── getSurveyIdxStratMean.Rd │ ├── leaveout.surveyIdx.Rd │ ├── mohn.surveyIdx.Rd │ ├── getEffect.Rd │ ├── surveyIdx.simulate.Rd │ ├── retro.surveyIdx.Rd │ ├── mapLegend.Rd │ ├── removeZeroClusters.Rd │ ├── fixAgeGroup.Rd │ ├── depthDist.Rd │ ├── getBathyGrid.Rd │ ├── redoSurveyIndex.Rd │ ├── plot.SIlist.Rd │ ├── surveyIdxPlots.Rd │ └── getSurveyIdx.Rd ├── DESCRIPTION └── NAMESPACE ├── surveyIndex.pdf ├── .gitignore ├── README.md ├── Makefile └── LICENSE /surveyIndex/R/deg2rad.R: -------------------------------------------------------------------------------- 1 | deg2rad <- 2 | function(deg) return(deg*pi/180) 3 | -------------------------------------------------------------------------------- /surveyIndex.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/casperwberg/surveyIndex/HEAD/surveyIndex.pdf -------------------------------------------------------------------------------- /surveyIndex/R/gcd.hf.R: -------------------------------------------------------------------------------- 1 | gcd.hf <- 2 | function(long1, lat1, long2, lat2) { 3 | R <- 6371 # Earth mean radius [km] 4 | delta.long <- (long2 - long1) 5 | delta.lat <- (lat2 - lat1) 6 | a <- sin(delta.lat/2)^2 + cos(lat1) * cos(lat2) * sin(delta.long/2)^2 7 | c <- 2 * asin(min(1,sqrt(a))) 8 | d = R * c 9 | return(d) # Distance in km 10 | } 11 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # History files 2 | .Rhistory 3 | .Rapp.history 4 | 5 | # Session Data files 6 | .RData 7 | 8 | # Example code in package build process 9 | *-Ex.R 10 | 11 | # RStudio files 12 | .Rproj.user/ 13 | 14 | # produced vignettes 15 | vignettes/*.html 16 | vignettes/*.pdf 17 | 18 | # OAuth2 token, see https://github.com/hadley/httr/releases/tag/v0.3 19 | .httr-oauth 20 | -------------------------------------------------------------------------------- /surveyIndex/R/concTransform.R: -------------------------------------------------------------------------------- 1 | ##' Concentration transform 2 | ##' 3 | ##' @title Helper function for plotting survey indices. 4 | ##' @param x a vector of log-responses 5 | ##' @return vector of transformed responses 6 | concTransform <- 7 | function (x) 8 | { 9 | i <- order(x) 10 | ys <- sort(exp(x)) 11 | p <- ys/sum(ys) 12 | x[i] <- cumsum(p) 13 | x 14 | } 15 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # surveyIndex 2 | R package for calculating survey indices by age from DATRAS exchange data 3 | 4 | Installation 5 | ============ 6 | 7 | To install you need the DATRAS package 8 | 9 | remotes::install_github("DTUAqua/DATRAS/DATRAS") 10 | remotes::install_github("casperwberg/surveyIndex/surveyIndex") 11 | 12 | Usage 13 | ===== 14 | see example for the function **getSurveyIdx** (write ?getSurveyIdx in **R**) 15 | -------------------------------------------------------------------------------- /surveyIndex/man/concTransform.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/concTransform.R 3 | \name{concTransform} 4 | \alias{concTransform} 5 | \title{Helper function for plotting survey indices.} 6 | \usage{ 7 | concTransform(x) 8 | } 9 | \arguments{ 10 | \item{x}{a vector of log-responses} 11 | } 12 | \value{ 13 | vector of transformed responses 14 | } 15 | \description{ 16 | Concentration transform 17 | } 18 | -------------------------------------------------------------------------------- /surveyIndex/man/anova.SI.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/anova.SI.R 3 | \name{anova.SI} 4 | \alias{anova.SI} 5 | \title{Likelihood ratio test for comparing two survey indices.} 6 | \usage{ 7 | \method{anova}{SI}(m1, m2) 8 | } 9 | \arguments{ 10 | \item{m1}{} 11 | 12 | \item{m2}{} 13 | } 14 | \value{ 15 | A p-value. 16 | } 17 | \description{ 18 | Likelihood ratio test for comparing two survey indices. 19 | } 20 | -------------------------------------------------------------------------------- /surveyIndex/man/plot.surveyIndexGrid.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/getGrid.R 3 | \name{plot.surveyIndexGrid} 4 | \alias{plot.surveyIndexGrid} 5 | \title{Plot a surveyIndexGrid} 6 | \usage{ 7 | \method{plot}{surveyIndexGrid}(grid, pch = 1, gridCol = "lightgrey") 8 | } 9 | \arguments{ 10 | \item{grid}{a surveyIndexGrid (as created by the "getGrid" function)} 11 | } 12 | \value{ 13 | nothing 14 | } 15 | \description{ 16 | Plot a surveyIndexGrid 17 | } 18 | -------------------------------------------------------------------------------- /surveyIndex/man/qres.tweedie.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/resid.R 3 | \name{qres.tweedie} 4 | \alias{qres.tweedie} 5 | \title{Randomized quantile residuals for Tweedie models} 6 | \usage{ 7 | qres.tweedie(gam.obj) 8 | } 9 | \arguments{ 10 | \item{gam.obj}{A gam object (mgcv package)} 11 | } 12 | \value{ 13 | A vector of residuals, which should be iid standard normal distributed 14 | } 15 | \description{ 16 | Randomized quantile residuals for Tweedie models 17 | } 18 | -------------------------------------------------------------------------------- /surveyIndex/man/internalCons.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/internalCons.R 3 | \name{internalCons} 4 | \alias{internalCons} 5 | \title{Calculate internal consistency of a survey index.} 6 | \usage{ 7 | internalCons(tt, do.plot = FALSE) 8 | } 9 | \arguments{ 10 | \item{tt}{A matrix with survey indices (rows=years, cols=ages)} 11 | 12 | \item{do.plot}{Plot it?} 13 | } 14 | \value{ 15 | a vector of consistencies 16 | } 17 | \description{ 18 | Calculate internal consistency of a survey index. 19 | } 20 | -------------------------------------------------------------------------------- /surveyIndex/man/getGrid.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/getGrid.R 3 | \name{getGrid} 4 | \alias{getGrid} 5 | \title{Create a grid of haul positions from a DATRASraw object.} 6 | \usage{ 7 | getGrid(dd, nLon = 20) 8 | } 9 | \arguments{ 10 | \item{dd}{DATRASraw object} 11 | 12 | \item{nLon}{number of grid cells in the longitude direction.} 13 | } 14 | \value{ 15 | A surveyIndexGrid (a list of coordinates and haul.ids) 16 | } 17 | \description{ 18 | Create a grid of haul positions from a DATRASraw object. 19 | } 20 | -------------------------------------------------------------------------------- /surveyIndex/man/AIC.surveyIdx.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/anova.SI.R 3 | \name{AIC.surveyIdx} 4 | \alias{AIC.surveyIdx} 5 | \title{Akaike Information Criterion (or BIC) for survey index models} 6 | \usage{ 7 | \method{AIC}{surveyIdx}(x, BIC = FALSE) 8 | } 9 | \arguments{ 10 | \item{x}{survey index as return from getSurveyIdx} 11 | 12 | \item{BIC}{if TRUE compute BIC instead of AIC} 13 | } 14 | \value{ 15 | numeric value 16 | } 17 | \description{ 18 | Akaike Information Criterion (or BIC) for survey index models 19 | } 20 | -------------------------------------------------------------------------------- /surveyIndex/man/residuals.surveyIdx.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/resid.R 3 | \name{residuals.surveyIdx} 4 | \alias{residuals.surveyIdx} 5 | \title{Randomized quantile residuals for class 'surveyIndex'} 6 | \usage{ 7 | \method{residuals}{surveyIdx}(x, a = 1) 8 | } 9 | \arguments{ 10 | \item{x}{An object of type 'surveyIndex' as created by 'getSurveyIdx'} 11 | 12 | \item{a}{age group} 13 | } 14 | \value{ 15 | A vector of residuals, which should be iid standard normal distributed 16 | } 17 | \description{ 18 | Randomized quantile residuals for class 'surveyIndex' 19 | } 20 | -------------------------------------------------------------------------------- /surveyIndex/man/factorplot.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/surveyIdxPlots.R 3 | \name{factorplot} 4 | \alias{factorplot} 5 | \title{Plot estimates of factor levels (or random effects) from a GAM model.} 6 | \usage{ 7 | factorplot(x, name, invlink = exp, levs = NULL, ylim = NULL, ...) 8 | } 9 | \arguments{ 10 | \item{x}{A model of class 'gam' or 'glm'} 11 | 12 | \item{name}{name of the factor} 13 | 14 | \item{invlink}{inverse link function} 15 | 16 | \item{levs}{optional custom factor level names} 17 | 18 | \item{...}{extra arguments to 'plot'} 19 | } 20 | \description{ 21 | Plot estimates of factor levels (or random effects) from a GAM model. 22 | } 23 | -------------------------------------------------------------------------------- /surveyIndex/man/exportSI.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/exportSI.R 3 | \name{exportSI} 4 | \alias{exportSI} 5 | \title{Write survey index to file in standard XSA/SAM format} 6 | \usage{ 7 | exportSI(x, ages, years, toy, file, nam = "") 8 | } 9 | \arguments{ 10 | \item{x}{matrix with survey indices} 11 | 12 | \item{ages}{vector of ages} 13 | 14 | \item{years}{vector of years} 15 | 16 | \item{toy}{fraction of year the survey is conducted (between 0 and 1)} 17 | 18 | \item{file}{filename to write to} 19 | 20 | \item{nam}{file description header} 21 | } 22 | \value{ 23 | nothing 24 | } 25 | \description{ 26 | Write survey index to file in standard XSA/SAM format 27 | } 28 | -------------------------------------------------------------------------------- /surveyIndex/man/externalCons.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/externalCons.R 3 | \name{externalCons} 4 | \alias{externalCons} 5 | \title{Calculate external consistencies between two survey indices.} 6 | \usage{ 7 | externalCons(tt, tt2, do.plot = FALSE) 8 | } 9 | \arguments{ 10 | \item{tt}{A matrix with survey indices (rows=years, cols=ages)} 11 | 12 | \item{tt2}{A matrix with survey indices (rows=years, cols=ages)} 13 | 14 | \item{do.plot}{plot it?} 15 | } 16 | \value{ 17 | A vector of correlations (consistencies) 18 | } 19 | \description{ 20 | Calculate external consistencies between two survey indices. 21 | } 22 | \details{ 23 | Proper alignment of years and ages must be ensured by the user. 24 | } 25 | -------------------------------------------------------------------------------- /surveyIndex/man/getSurveyIdxStratMean.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/getSurveyIdxStratMean.R 3 | \name{getSurveyIdxStratMean} 4 | \alias{getSurveyIdxStratMean} 5 | \title{Survey index using the stratified mean method using ICES statistical rectangles as strata.} 6 | \usage{ 7 | getSurveyIdxStratMean(x, ageCols, doLog = FALSE) 8 | } 9 | \arguments{ 10 | \item{x}{DATRASraw object. Must contain a matrix: x[[2]]$Nage.} 11 | 12 | \item{ageCols}{which columns of the Nage matrix should be included?} 13 | 14 | \item{doLog}{log-transform?} 15 | } 16 | \value{ 17 | a matrix with survey indices 18 | } 19 | \description{ 20 | Survey index using the stratified mean method using ICES statistical rectangles as strata. 21 | } 22 | -------------------------------------------------------------------------------- /surveyIndex/DESCRIPTION: -------------------------------------------------------------------------------- 1 | Package: surveyIndex 2 | Type: Package 3 | Title: Calculate survey indices of abundance from DATRAS exchange data. 4 | Version: 1.11 5 | Date: 2024-24-04 6 | Author: Casper W. Berg 7 | Maintainer: Casper W. Berg 8 | Description: This is an implementation of the methods described in 9 | Berg et al. (2014): "Evaluation of alternative age-based methods for estimating relative abundance from survey data in relation to assessment models", Fisheries Research 151(2014) 91-99. 10 | License: GPL (>=3) 11 | Copyright: Casper W. Berg 12 | Depends: 13 | R (>= 3.0), 14 | DATRAS, 15 | mgcv, 16 | parallel, 17 | maps, 18 | mapdata 19 | Imports: 20 | MASS, 21 | tweedie 22 | RoxygenNote: 7.2.3 23 | -------------------------------------------------------------------------------- /surveyIndex/man/leaveout.surveyIdx.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/retroLO.R 3 | \name{leaveout.surveyIdx} 4 | \alias{leaveout.surveyIdx} 5 | \title{Make leave-one-out analysis} 6 | \usage{ 7 | leaveout.surveyIdx(model, d, grid, fac, predD = NULL, ...) 8 | } 9 | \arguments{ 10 | \item{model}{object of class "surveyIdx" as created by "getSurveyIdx"} 11 | 12 | \item{d}{DATRASraw dataset} 13 | 14 | \item{grid}{surveyIndexGrid object (see getGrid) defining the grid.} 15 | 16 | \item{fac}{a factor in d to leave out one at a time, e.g. d$Survey} 17 | 18 | \item{...}{Optional extra arguments to "gam"} 19 | } 20 | \value{ 21 | SIlist (list of surveyIndex objects) 22 | } 23 | \description{ 24 | Make leave-one-out analysis 25 | } 26 | -------------------------------------------------------------------------------- /surveyIndex/man/mohn.surveyIdx.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/retroLO.R 3 | \name{mohn.surveyIdx} 4 | \alias{mohn.surveyIdx} 5 | \title{Mohn's rho for retrospective analysis} 6 | \usage{ 7 | mohn.surveyIdx(x, base, rescale = FALSE) 8 | } 9 | \arguments{ 10 | \item{x}{SIlist as returned by the 'retro.surveyIdx' function} 11 | 12 | \item{base}{Object of class 'surveyIdx' (full run with all years)} 13 | 14 | \item{rescale}{should the indices for each age group be rescaled to have mean 1 over shortest timespan before calculating mohns rho? Only appropriate for purely relative indices.} 15 | } 16 | \value{ 17 | vector with mohn's rho for each age group 18 | } 19 | \description{ 20 | Mohn's rho for retrospective analysis 21 | } 22 | -------------------------------------------------------------------------------- /surveyIndex/NAMESPACE: -------------------------------------------------------------------------------- 1 | # Generated by roxygen2: do not edit by hand 2 | 3 | S3method(plot,SIlist) 4 | S3method(plot,surveyIndexGrid) 5 | S3method(print,surveyIdx) 6 | S3method(residuals,surveyIdx) 7 | export(AIC.surveyIdx) 8 | export(anova.SI) 9 | export(depthDist) 10 | export(exportSI) 11 | export(externalCons) 12 | export(factorplot) 13 | export(fixAgeGroup) 14 | export(getBathyGrid) 15 | export(getEffect) 16 | export(getGrid) 17 | export(getSurveyIdx) 18 | export(getSurveyIdxStratMean) 19 | export(internalCons) 20 | export(leaveout.surveyIdx) 21 | export(mapLegend) 22 | export(mohn.surveyIdx) 23 | export(qres.tweedie) 24 | export(redoSurveyIndex) 25 | export(removeZeroClusters) 26 | export(retro.surveyIdx) 27 | export(surveyIdx.simulate) 28 | export(surveyIdxPlots) 29 | import(mapdata) 30 | import(maps) 31 | import(tweedie) 32 | importFrom(MASS,mvrnorm) 33 | -------------------------------------------------------------------------------- /surveyIndex/man/getEffect.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/getEffect.R 3 | \name{getEffect} 4 | \alias{getEffect} 5 | \title{Calculate confidence intervals for a named parameter in a survey index model.} 6 | \usage{ 7 | getEffect(x, dat, parName = "Gear", cutOff, nboot = 1000, pOnly = FALSE) 8 | } 9 | \arguments{ 10 | \item{x}{survey index} 11 | 12 | \item{dat}{DATRASraw object} 13 | 14 | \item{parName}{name of the parameter, e.g. "Gear"} 15 | 16 | \item{cutOff}{see getSurveyIndex()} 17 | 18 | \item{nboot}{see getSurveyIndex()} 19 | 20 | \item{pOnly}{only calculate for positive part of model, defaults to FALSE.} 21 | } 22 | \value{ 23 | list of estimates + ci bounds for each age group. 24 | } 25 | \description{ 26 | Calculate confidence intervals for a named parameter in a survey index model. 27 | } 28 | -------------------------------------------------------------------------------- /surveyIndex/R/exportSI.R: -------------------------------------------------------------------------------- 1 | ##' Write survey index to file in standard XSA/SAM format 2 | ##' 3 | ##' @title Write survey index to file in standard XSA/SAM format 4 | ##' @param x matrix with survey indices 5 | ##' @param ages vector of ages 6 | ##' @param years vector of years 7 | ##' @param toy fraction of year the survey is conducted (between 0 and 1) 8 | ##' @param file filename to write to 9 | ##' @param nam file description header 10 | ##' @return nothing 11 | ##' @export 12 | exportSI <- 13 | function(x,ages,years,toy,file,nam=""){ 14 | cat(nam,"\n",file=file) 15 | cat(range(as.numeric(as.character(years))),"\n",file=file,append=TRUE) 16 | cat("1 1 ",rep(toy,2),"\n",file=file,append=TRUE) 17 | cat(min(ages),max(ages),"\n",file=file,append=TRUE) 18 | write.table(round(cbind(1,x[,]),4),file=file,row.names=FALSE,col.names=FALSE,append=TRUE) 19 | } 20 | -------------------------------------------------------------------------------- /surveyIndex/R/internalCons.R: -------------------------------------------------------------------------------- 1 | ##' Calculate internal consistency of a survey index. 2 | ##' 3 | ##' @title Calculate internal consistency of a survey index. 4 | ##' @param tt A matrix with survey indices (rows=years, cols=ages) 5 | ##' @param do.plot Plot it? 6 | ##' @return a vector of consistencies 7 | ##' @export 8 | internalCons <- 9 | function(tt,do.plot=FALSE){ 10 | tt[tt==0]=NA 11 | sel1=1:(nrow(tt)-1); 12 | sel2=2:nrow(tt); 13 | if(do.plot){ X11(); b=ceiling((ncol(tt)-1)/2); par(mfrow=c(b,b));} 14 | for(a in 1:(ncol(tt)-1)){ 15 | cat("Age ",a," vs ",a+1," : ",cor(log(tt[sel1,a]),log(tt[sel2,a+1]),use="pairwise.complete.obs"),"\n") 16 | if(do.plot) {plot(log(tt[sel1,a]),log(tt[sel2,a+1])); abline(0,1);} 17 | } 18 | return( sapply(1:(ncol(tt)-1), function(a) cor(log(tt[sel1,a]),log(tt[sel2,a+1]),use="pairwise.complete.obs"))); 19 | } 20 | -------------------------------------------------------------------------------- /surveyIndex/R/externalCons.R: -------------------------------------------------------------------------------- 1 | ##' Calculate external consistencies between two survey indices. 2 | ##' 3 | ##' Proper alignment of years and ages must be ensured by the user. 4 | ##' @title Calculate external consistencies between two survey indices. 5 | ##' @param tt A matrix with survey indices (rows=years, cols=ages) 6 | ##' @param tt2 A matrix with survey indices (rows=years, cols=ages) 7 | ##' @param do.plot plot it? 8 | ##' @return A vector of correlations (consistencies) 9 | ##' @export 10 | externalCons <- 11 | function(tt,tt2,do.plot=FALSE){ 12 | tt[tt==0]=NA 13 | tt2[tt2==0]=NA 14 | if(do.plot){ X11(); b=ceiling((ncol(tt))/2); par(mfrow=c(b,b));} 15 | for(a in 1:ncol(tt)){ 16 | cat("Survey 1 Age ",a," vs Survey 2 ",a," : ",cor(log(tt[,a]),log(tt2[,a]),use="pairwise.complete.obs"),"\n") 17 | if(do.plot) {plot(log(tt[,a]),log(tt2[,a])); abline(0,1);} 18 | } 19 | return( sapply(1:ncol(tt),function(a) cor(log(tt[,a]),log(tt2[,a]),use="pairwise.complete.obs") )); 20 | } 21 | -------------------------------------------------------------------------------- /surveyIndex/man/surveyIdx.simulate.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/simulate.R 3 | \name{surveyIdx.simulate} 4 | \alias{surveyIdx.simulate} 5 | \title{Simulate data from a surveyIndex model (experimental and subject to change)} 6 | \usage{ 7 | surveyIdx.simulate(model, d, sampleFit = FALSE, condSim = NULL) 8 | } 9 | \arguments{ 10 | \item{model}{object of class 'surveyIdx'} 11 | 12 | \item{d}{A dataset (DATRASraw object)} 13 | 14 | \item{sampleFit}{Use a random sample from the gaussian approximation to distribution of the estimated parameter vector. Default: FALSE.} 15 | 16 | \item{condSim}{optional results of previous call to this function. Use this if you want to generate many datasets (much faster, since mean predictions are re-used).} 17 | } 18 | \value{ 19 | list with 1) simulated observations with noise 2) mean (no noise) 3) zero probability. 20 | } 21 | \description{ 22 | Simulate data from a surveyIdx model (experimental and subject to change) 23 | } 24 | -------------------------------------------------------------------------------- /surveyIndex/R/getSurveyIdxStratMean.R: -------------------------------------------------------------------------------- 1 | 2 | ##' Survey index using the stratified mean method using ICES statistical rectangles as strata. 3 | ##' 4 | ##' @title Survey index using the stratified mean method using ICES statistical rectangles as strata. 5 | ##' @param x DATRASraw object. Must contain a matrix: x[[2]]$Nage. 6 | ##' @param ageCols which columns of the Nage matrix should be included? 7 | ##' @param doLog log-transform? 8 | ##' @return a matrix with survey indices 9 | ##' @export 10 | getSurveyIdxStratMean <- 11 | function(x,ageCols,doLog=FALSE){ 12 | ysplit=split(x,x$Year); 13 | res=matrix(NA,nrow=length(ysplit),ncol=length(ageCols)) 14 | for(y in 1:length(ysplit)){ 15 | 16 | if(!doLog) { 17 | byRec=aggregate(ysplit[[y]][[2]]$Nage[,ageCols],by=list(ysplit[[y]][[2]]$StatRec),FUN="mean") } else { 18 | byRec=aggregate(log(ysplit[[y]][[2]]$Nage[,ageCols]+1),by=list(ysplit[[y]][[2]]$StatRec),FUN="mean") 19 | } 20 | 21 | res[y,]=colMeans(byRec[,-1]) 22 | } 23 | res 24 | } 25 | -------------------------------------------------------------------------------- /surveyIndex/man/retro.surveyIdx.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/retroLO.R 3 | \name{retro.surveyIdx} 4 | \alias{retro.surveyIdx} 5 | \title{Make retrospective analysis for a "surveyIdx" model.} 6 | \usage{ 7 | retro.surveyIdx(model, d, grid, npeels = 5, predD = NULL, nBoot = 1000, ...) 8 | } 9 | \arguments{ 10 | \item{model}{object of class "surveyIdx" as created by "getSurveyIdx"} 11 | 12 | \item{d}{DATRASraw dataset} 13 | 14 | \item{grid}{surveyIndexGrid object (see getGrid) defining the grid.} 15 | 16 | \item{npeels}{number of years to successively peel of the data set} 17 | 18 | \item{predD}{alternative way of specifiyng the grid (see getSurveyIdx function)} 19 | 20 | \item{nBoot}{number of bootstrap samples used for calculating index confidence intervals} 21 | 22 | \item{...}{Optional extra arguments to "gam"} 23 | } 24 | \value{ 25 | SIlist (list of surveyIndex objects) 26 | } 27 | \description{ 28 | Make retrospective analysis for a "surveyIdx" model. 29 | } 30 | -------------------------------------------------------------------------------- /surveyIndex/man/mapLegend.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/surveyIdxPlots.R 3 | \name{mapLegend} 4 | \alias{mapLegend} 5 | \title{Plot values for each color level in a map as created by 'surveyIdxPlots'.} 6 | \usage{ 7 | mapLegend( 8 | x, 9 | year, 10 | colors = rev(heat.colors(6)), 11 | age = 1, 12 | legend.signif = 3, 13 | cutp = NULL, 14 | lwd = 10, 15 | las = 2 16 | ) 17 | } 18 | \arguments{ 19 | \item{x}{object of class 'surveyIdx'} 20 | 21 | \item{year}{vector of years (should be the same as used for 'surveyIdxPlots')} 22 | 23 | \item{colors}{vector of colors to use} 24 | 25 | \item{age}{age group (integer >=1)} 26 | 27 | \item{legend.signif}{number of significant digits shown} 28 | 29 | \item{cutp}{optional custom vector of cut points for color scales.} 30 | 31 | \item{lwd}{line width for bars} 32 | 33 | \item{las}{orientation of x-axis lables} 34 | } 35 | \description{ 36 | Plot values for each color level in a map as created by 'surveyIdxPlots'. 37 | } 38 | -------------------------------------------------------------------------------- /surveyIndex/man/removeZeroClusters.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/removeZeroClusters.R 3 | \name{removeZeroClusters} 4 | \alias{removeZeroClusters} 5 | \title{Remove factor levels with only zero observations, which can cause estimation problems} 6 | \usage{ 7 | removeZeroClusters( 8 | d, 9 | cutat = 0, 10 | response = NULL, 11 | factors = c("Gear", "Ship", "Year", "StatRec"), 12 | verbose = TRUE 13 | ) 14 | } 15 | \arguments{ 16 | \item{d}{DATRASraw object} 17 | 18 | \item{cutat}{numeric in the interval [0,1[. If greater than 0, then factor levels where mu/max(mu) < cutat are removed. Note, that this will remove some positive observations.} 19 | 20 | \item{response}{Character naming the response column. If NULL, then total numbers are used as response.} 21 | 22 | \item{factors}{vector naming the factors to consider.} 23 | 24 | \item{verbose}{print out extra info? Default: TRUE} 25 | } 26 | \value{ 27 | DATRASraw object 28 | } 29 | \description{ 30 | Remove factor levels with only/many zero observations, which can cause estimation problems 31 | } 32 | -------------------------------------------------------------------------------- /surveyIndex/man/fixAgeGroup.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/fixAgeGroup.R 3 | \name{fixAgeGroup} 4 | \alias{fixAgeGroup} 5 | \title{Helper function to "borrow" missing age groups from other years} 6 | \usage{ 7 | fixAgeGroup(x, age = 0, n = 3, fun = "mean") 8 | } 9 | \arguments{ 10 | \item{x}{DATRASraw object} 11 | 12 | \item{age}{age to impute} 13 | 14 | \item{n}{at least this many individuals in each year} 15 | 16 | \item{fun}{A function such as 'mean','median','min', or 'max'.} 17 | } 18 | \value{ 19 | a DATRASraw object 20 | } 21 | \description{ 22 | Helper function to "borrow" missing age groups from other years 23 | } 24 | \details{ 25 | In years where there are less than 'n' individuals of age 'age', 26 | add fake individuals of that age such that there are 'n'. 27 | The length of the individuals are set to the mean (or whatever 'fun' specifies) 28 | of all other individuals of the same age. 29 | For the minimum and maximum age groups fun it is reasonable to replace 'mean' with 'min' and 'max' respectively. 30 | Note, that you might need to call 'addSpectrum' on the object again. 31 | } 32 | -------------------------------------------------------------------------------- /surveyIndex/man/depthDist.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/surveyIdxPlots.R 3 | \name{depthDist} 4 | \alias{depthDist} 5 | \title{Calculate and plot the distribution as a function of depth} 6 | \usage{ 7 | depthDist( 8 | m, 9 | grid, 10 | by = 5, 11 | type = c("dist", "density", "mean"), 12 | colfun = colorRampPalette(c("red", "lightgrey", "blue")), 13 | lwd = 1.5, 14 | rangeFrac = 0.5, 15 | age = 1, 16 | ... 17 | ) 18 | } 19 | \arguments{ 20 | \item{m}{object of class 'surveyIdx'} 21 | 22 | \item{grid}{grid object used when fitting 'm'} 23 | 24 | \item{by}{depth bin size} 25 | 26 | \item{type}{character vector indicating what to plot. 'dist' or 'mean' or both.} 27 | 28 | \item{colfun}{color function to use for plotting.} 29 | 30 | \item{lwd}{plotting line width} 31 | 32 | \item{rangeFrac}{Fraction ]0;1[ indicating the percentile range in the mean plot. Default is 0.5, i.e. interquartile range.} 33 | 34 | \item{age}{which age group to plot} 35 | 36 | \item{...}{extra arguments to 'plot} 37 | } 38 | \value{ 39 | a matrix with depth distribution in each year. 40 | } 41 | \description{ 42 | Calculate and plot the distribution as a function of depth 43 | } 44 | -------------------------------------------------------------------------------- /surveyIndex/man/getBathyGrid.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/getBathyGrid.R 3 | \name{getBathyGrid} 4 | \alias{getBathyGrid} 5 | \title{Get bathymetric prediction grid corresponding to the area for a DATRASraw object using the 'marmap' package} 6 | \usage{ 7 | getBathyGrid( 8 | d, 9 | minDepth = 10, 10 | maxDepth = Inf, 11 | resolution = 2, 12 | maxDist = Inf, 13 | keep = TRUE, 14 | shapefile = NULL, 15 | select = NULL 16 | ) 17 | } 18 | \arguments{ 19 | \item{d}{DATRASraw object} 20 | 21 | \item{minDepth}{Minimum depth to include} 22 | 23 | \item{maxDepth}{Maximum depth to include} 24 | 25 | \item{resolution}{grid resolution (see marmap::getNOAA.bathy)} 26 | 27 | \item{maxDist}{Do not include grid points farther than maxDist from nearest observation.} 28 | 29 | \item{keep}{Save grid on disk for fast loading next time?} 30 | 31 | \item{shapefile}{extra shapefile information to add (optional)} 32 | 33 | \item{select}{columns to extract from shapefile} 34 | } 35 | \value{ 36 | data.frame with depths and geographical coordinates 37 | } 38 | \description{ 39 | Get bathymetric prediction grid corresponding to the area for a DATRASraw object using the 'marmap' package 40 | } 41 | -------------------------------------------------------------------------------- /surveyIndex/R/anova.SI.R: -------------------------------------------------------------------------------- 1 | ##' Likelihood ratio test for comparing two survey indices. 2 | ##' 3 | ##' @title Likelihood ratio test for comparing two survey indices. 4 | ##' @param m1 5 | ##' @param m2 6 | ##' @return A p-value. 7 | ##' @export anova.SI 8 | anova.SI <- 9 | function(m1,m2){ 10 | ll1=m1$logLik 11 | ll2=m2$logLik 12 | edfs1=m1$edfs 13 | edfs2=m2$edfs 14 | 15 | if (edfs2 > edfs1) { 16 | 1 - pchisq(2 * (ll2 - ll1), edfs2 - edfs1) 17 | } 18 | else { 19 | 1 - pchisq(2 * (ll1 - ll2), edfs1 - edfs2) 20 | } 21 | } 22 | 23 | ##' Akaike Information Criterion (or BIC) for survey index models 24 | ##' 25 | ##' @title Akaike Information Criterion (or BIC) for survey index models 26 | ##' @param x survey index as return from getSurveyIdx 27 | ##' @param BIC if TRUE compute BIC instead of AIC 28 | ##' @return numeric value 29 | ##' @export AIC.surveyIdx 30 | AIC.surveyIdx<-function(x, BIC=FALSE){ 31 | if(!BIC) return(2*x$edfs-2*x$logLik) 32 | if(pmatch("Tweedie",x$pModels[[1]]$family$family,nomatch=-1)==1 || 33 | pmatch("negbin",x$pModels[[1]]$family$family,nomatch=-1)==1 ){ 34 | log(length(x$pModels[[1]]$y)*(length(x$pModels)))*x$edfs-2*x$logLik 35 | } else { 36 | log(length(x$zModels[[1]]$y)*(length(x$zModels)))*x$edfs-2*x$logLik 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /surveyIndex/man/redoSurveyIndex.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/getSurveyIdx.R 3 | \name{redoSurveyIndex} 4 | \alias{redoSurveyIndex} 5 | \title{Re-compute standardized survey indices for an alternative grid from a previous fitted "surveyIdx" model.} 6 | \usage{ 7 | redoSurveyIndex( 8 | x, 9 | model, 10 | predD = NULL, 11 | myids, 12 | nBoot = 1000, 13 | predfix = list(), 14 | mc.cores = 1, 15 | addTimeOfYear = FALSE 16 | ) 17 | } 18 | \arguments{ 19 | \item{x}{DATRASraw dataset} 20 | 21 | \item{model}{object of class "surveyIdx" as created by "getSurveyIdx"} 22 | 23 | \item{predD}{optional DATRASraw object, defaults to NULL. If not null this is used as grid.} 24 | 25 | \item{myids}{haul.ids for grid} 26 | 27 | \item{nBoot}{number of bootstrap samples used for calculating index confidence intervals} 28 | 29 | \item{predfix}{optional named list of extra variables (besides Gear, HaulDur, Ship, and TimeShotHour), that should be fixed during prediction step (standardized)} 30 | 31 | \item{mc.cores}{mc.cores number of cores for parallel processing} 32 | 33 | \item{addTimeOfYear}{if TRUE, add predfix$timeOfYear to 'ctime' when standardizing (otherwise it is 1st of January).} 34 | } 35 | \value{ 36 | An object of class "surveyIdx" 37 | } 38 | \description{ 39 | Re-compute standardized survey indices for an alternative grid from a previous fitted "surveyIdx" model. 40 | } 41 | -------------------------------------------------------------------------------- /surveyIndex/man/plot.SIlist.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/retroLO.R 3 | \name{plot.SIlist} 4 | \alias{plot.SIlist} 5 | \title{Plot survey index list (e.g. retrospective analysis)} 6 | \usage{ 7 | \method{plot}{SIlist}( 8 | x, 9 | base = 1, 10 | rescale = FALSE, 11 | lwd = 1.5, 12 | main = NULL, 13 | allCI = FALSE, 14 | includeCI = TRUE, 15 | ylim = NULL, 16 | density = FALSE 17 | ) 18 | } 19 | \arguments{ 20 | \item{x}{(named) list of "surveyIdx" objects for example from "retro.surveyIdx" or "leaveout.surveyIdx"} 21 | 22 | \item{base}{Either index of x that should considered the "base run" (integer), OR object of class "surveyIdx". Confidence bounds will be shown for this model only.} 23 | 24 | \item{rescale}{Should indices be rescaled to have mean 1 (over the set of intersecting years)? Default: FALSE} 25 | 26 | \item{lwd}{line width argument to plot} 27 | 28 | \item{main}{if not NULL override main plotting default title of "Age group a"} 29 | 30 | \item{allCI}{show 95\% confidence lines for all indices? Default FALSE.} 31 | 32 | \item{includeCI}{Show confidence intervals? Default TRUE.} 33 | 34 | \item{ylim}{Y axis range. If NULL (default) then determine automatically.} 35 | 36 | \item{density}{if TRUE, divide each index by the number of grid points to get densities rather than totals.} 37 | } 38 | \value{ 39 | nothing 40 | } 41 | \description{ 42 | Plot survey index list (e.g. retrospective analysis) 43 | } 44 | -------------------------------------------------------------------------------- /surveyIndex/R/fixAgeGroup.R: -------------------------------------------------------------------------------- 1 | ##' Helper function to "borrow" missing age groups from other years 2 | ##' 3 | ##' In years where there are less than 'n' individuals of age 'age', 4 | ##' add fake individuals of that age such that there are 'n'. 5 | ##' The length of the individuals are set to the mean (or whatever 'fun' specifies) 6 | ##' of all other individuals of the same age. 7 | ##' For the minimum and maximum age groups fun it is reasonable to replace 'mean' with 'min' and 'max' respectively. 8 | ##' Note, that you might need to call 'addSpectrum' on the object again. 9 | ##' @title Helper function to "borrow" missing age groups from other years 10 | ##' @param x DATRASraw object 11 | ##' @param age age to impute 12 | ##' @param n at least this many individuals in each year 13 | ##' @param fun A function such as 'mean','median','min', or 'max'. 14 | ##' @return a DATRASraw object 15 | ##' @export 16 | fixAgeGroup <- 17 | function(x,age=0,n=3,fun="mean"){ 18 | cm.breaks<-attr(x,"cm.breaks") 19 | f <- match.fun(fun) 20 | d=split(x,x$Year) 21 | subsLength=f(x[[1]]$LngtCm[x[[1]]$Age==age],na.rm=TRUE) 22 | for(y in 1:length(d)){ 23 | nobs = sum(d[[y]][[1]]$Age==age,na.rm=TRUE) 24 | if(nobscutOff) 24 | zNam=levels(dat$Ship) 25 | pNam=levels(dd$Ship) 26 | dif=setdiff(zNam,pNam); 27 | remo = which(zNam %in% dif) 28 | if(length(remo)>0) shipSelZ = shipSelZ[-remo]; 29 | 30 | if(length(shipSelP)!=length(shipSelZ)) { print("unequal number of ship effects"); } 31 | 32 | 33 | brp.1=mvrnorm(n=nboot,coef(x$pModels[[a]]),x$pModels[[a]]$Vp); 34 | brp.0=mvrnorm(n=nboot,coef(x$zModels[[a]]),x$zModels[[a]]$Vp); 35 | 36 | shipE = exp(brp.1[,shipSelP,drop=FALSE]); 37 | if(!pOnly) shipE = shipE*x$zModels[[a]]$family$linkinv(brp.0[,shipSelZ,drop=FALSE]) 38 | 39 | upres = apply(shipE,2, quantile,probs=0.975); 40 | lores = apply(shipE,2, quantile,probs=0.025); 41 | 42 | tmp=cbind(colMeans(shipE),upres,lores); 43 | 44 | res[[a]]=tmp; 45 | } 46 | return(res); 47 | } 48 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | R=R 2 | # -> you can do R=R-devel make .... 3 | 4 | PACKAGE=surveyIndex 5 | VERSION := $(shell sed -n '/^Version: /s///p' surveyIndex/DESCRIPTION) 6 | DATE := $(shell sed -n '/^Date: /s///p' surveyIndex/DESCRIPTION) 7 | TARBALL=${PACKAGE}_${VERSION}.tar.gz 8 | ZIPFILE=${PACKAGE}_${VERSION}.zip 9 | 10 | SUBDIRS := $(wildcard testmore/*/.) 11 | 12 | .PHONY: all testmoreseq testonemore testmore $(SUBDIRS) 13 | 14 | all: 15 | make doc-update 16 | make build-package 17 | make install 18 | make pdf 19 | 20 | doc-update: 21 | echo "library(roxygen2);roxygenize(\"$(PACKAGE)\")" | R --slave 22 | 23 | build-package: 24 | R CMD build --resave-data=no $(PACKAGE) 25 | 26 | install: 27 | make build-package 28 | R CMD INSTALL --preclean $(TARBALL) 29 | 30 | unexport TEXINPUTS 31 | pdf: 32 | rm -f $(PACKAGE).pdf 33 | R CMD Rd2pdf --no-preview $(PACKAGE) 34 | 35 | check: 36 | R CMD check $(PACKAGE) 37 | 38 | ##unlock: 39 | ## rm -rf `Rscript --vanilla -e 'writeLines(.Library)'`/00LOCK- 40 | 41 | ##.PHONY: dox 42 | ##dox: 43 | ## sed -i s/^PROJECT_NUMBER.*/PROJECT_NUMBER=v$(VERSION)/g dox/Doxyfile 44 | ## cd dox; doxygen 45 | 46 | ##dox-clean: 47 | ## cd dox; rm -rf html latex 48 | 49 | 50 | ## Get a rough changelog since most recent github revision tag 51 | ## (Use as starting point when updating NEWS file) 52 | ## NOTE: Run *after* updating version and date in DESCRIPTION. 53 | changelog: 54 | echo; \ 55 | echo "------------------------------------------------------------------------"; \ 56 | echo TMB $(VERSION) \($(DATE)\); \ 57 | echo "------------------------------------------------------------------------"; \ 58 | echo; \ 59 | git --no-pager log --format="o %B" `git describe --abbrev=0 --tags`..HEAD | sed s/^-/\ \ -/g 60 | 61 | NPROCS:=1 62 | OS:=$(shell uname -s) 63 | 64 | ifeq ($(OS),Linux) 65 | NPROCS:=$(shell grep -c ^processor /proc/cpuinfo) 66 | endif 67 | 68 | testmore: 69 | $(MAKE) -j $(NPROCS) testmoreseq 70 | 71 | testmoreseq: $(SUBDIRS) 72 | 73 | testonemore: 74 | @$(MAKE) testmore/$(ARG)/. 75 | 76 | $(SUBDIRS): 77 | @cp testmore/Makefile $@ 78 | @$(MAKE) -i -s -C $@ 79 | @rm -f $@/Makefile 80 | -------------------------------------------------------------------------------- /surveyIndex/R/getBathyGrid.R: -------------------------------------------------------------------------------- 1 | ##' Get bathymetric prediction grid corresponding to the area for a DATRASraw object using the 'marmap' package 2 | ##' 3 | ##' @title Get bathymetric prediction grid corresponding to the area for a DATRASraw object using the 'marmap' package 4 | ##' @param d DATRASraw object 5 | ##' @param minDepth Minimum depth to include 6 | ##' @param maxDepth Maximum depth to include 7 | ##' @param resolution grid resolution (see marmap::getNOAA.bathy) 8 | ##' @param maxDist Do not include grid points farther than maxDist from nearest observation. 9 | ##' @param keep Save grid on disk for fast loading next time? 10 | ##' @param shapefile extra shapefile information to add (optional) 11 | ##' @param select columns to extract from shapefile 12 | ##' @return data.frame with depths and geographical coordinates 13 | ##' @export 14 | getBathyGrid<-function(d,minDepth=10, maxDepth=Inf, resolution=2,maxDist=Inf, keep=TRUE, shapefile=NULL, select=NULL){ 15 | if (!requireNamespace("marmap", quietly = TRUE)) { 16 | stop("Package \"marmap\" needed for this function to work. Please install it.", 17 | call. = FALSE) 18 | } 19 | bathy <- marmap::getNOAA.bathy(lon1=min(d$lon),lon2=max(d$lon),lat1=min(d$lat),lat2=max(d$lat),resolution=resolution, keep=keep) 20 | xyzbathy <- as.data.frame( marmap::as.xyz(bathy) ) 21 | colnames(xyzbathy) <- c("lon","lat","Depth") 22 | xyzbathy$Depth <- -xyzbathy$Depth 23 | xyzbathy <- subset(xyzbathy, Depth>minDepth & Depth0 & any(mutab/maxmu < cutat)){ 38 | if(verbose) cat("Removing following levels of ", fac,":",names(factab[mutab/maxmu < cutat]),"\n") 39 | badids <- d$haul.id[ d[[2]][,fac] %in% names(factab[mutab/maxmu < cutat]) ] 40 | bad <- subset(d, haul.id %in% badids) 41 | d <- subset(d, !haul.id %in% badids) 42 | nposremoved <- sum(bad[[2]][,response]>0) 43 | } 44 | 45 | ## re-factor (drop empty factor levels) 46 | d[[2]][,fac] = factor(d[[2]][,fac],levels=unique(d[[2]][,fac])) 47 | } 48 | 49 | Nnew = nrow(d[[2]]) 50 | if(verbose) { 51 | cat("Number of hauls before: " , N, " , after: ",Nnew, " (",round((N-Nnew)/N*100,1),"% reduction)\n") 52 | cat("Number of positive hauls removed: ",nposremoved,"\n") 53 | } 54 | 55 | return(d) 56 | 57 | } 58 | -------------------------------------------------------------------------------- /surveyIndex/man/surveyIdxPlots.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/surveyIdxPlots.R 3 | \name{surveyIdxPlots} 4 | \alias{surveyIdxPlots} 5 | \title{Visualize results from a survey index model fitted with getSurveyIdx().} 6 | \usage{ 7 | surveyIdxPlots( 8 | x, 9 | dat, 10 | alt.idx = NULL, 11 | myids, 12 | cols = 1:length(x$pModels), 13 | select = c("index", "map", "residuals", "fitVsRes"), 14 | par = list(mfrow = c(3, 3)), 15 | colors = rev(heat.colors(6)), 16 | map.cex = 1, 17 | plotByAge = TRUE, 18 | legend = TRUE, 19 | predD = NULL, 20 | year = NULL, 21 | main = NULL, 22 | legend.signif = 3, 23 | legend.pos = "topright", 24 | restoreOldPar = FALSE, 25 | mapBubbles = FALSE, 26 | cutp = NULL, 27 | map.pch = 16, 28 | mapArgs = list(fill = TRUE, col = grey(0.5)), 29 | ... 30 | ) 31 | } 32 | \arguments{ 33 | \item{x}{Survey index as produced by getSurveyIndex()} 34 | 35 | \item{dat}{DATRASraw object} 36 | 37 | \item{alt.idx}{optional matrix with alternative index} 38 | 39 | \item{myids}{vector of haul ids that constitute the grid} 40 | 41 | \item{cols}{which age columns to consider?} 42 | 43 | \item{select}{character vector of chosen plots. Either one of "index","map","absolutemap","CVmap","residuals","fitVsRes",""resVsYear","resVsShip","spatialResiduals", or a number. Numbers refer to smooths in the order they appear in the formula.} 44 | 45 | \item{par}{'par' settings for plotting (a named list).} 46 | 47 | \item{colors}{colors for spatial effect.} 48 | 49 | \item{map.cex}{size of grid points on maps} 50 | 51 | \item{plotByAge}{boolean (default=TRUE). If true, par(par) is called for each age group.} 52 | 53 | \item{legend}{boolean (default=TRUE). add legends to plot?} 54 | 55 | \item{predD}{DATRASraw object with grid (optional). Overrides 'myids' if supplied.} 56 | 57 | \item{year}{numeric scalar or vector (default=NULL). If 'select' equals 'map' a specific year can be chosen (only meaningful for time-varying spatial effects). If select equals 'absolutemap' or 'CVmap' then year must be a vector.} 58 | 59 | \item{main}{optional main title (overrides default title)} 60 | 61 | \item{legend.signif}{Number of significant digits in map legends} 62 | 63 | \item{legend.pos}{Position of legend (e.g. "bottomleft") see ?legend} 64 | 65 | \item{restoreOldPar}{restore old par() on exit? Default=FALSE} 66 | 67 | \item{mapBubbles}{boolean (default=FALSE) add observation bubbles?} 68 | 69 | \item{cutp}{optional vector of break points for the color scale on maps} 70 | 71 | \item{map.pch}{pch for map points, default=16 (filled round).} 72 | 73 | \item{mapArgs}{arguments to maps::map for drawing coastlines/land} 74 | 75 | \item{...}{Additional parameters for plot()} 76 | } 77 | \value{ 78 | nothing 79 | } 80 | \description{ 81 | Visualize results from a survey index model fitted with getSurveyIdx(). 82 | } 83 | -------------------------------------------------------------------------------- /surveyIndex/R/resid.R: -------------------------------------------------------------------------------- 1 | ##' Randomized quantile residuals for class 'surveyIndex' 2 | ##' 3 | ##' @title Randomized quantile residuals for class 'surveyIndex' 4 | ##' @param x An object of type 'surveyIndex' as created by 'getSurveyIdx' 5 | ##' @param a age group 6 | ##' @return A vector of residuals, which should be iid standard normal distributed 7 | ##' @export 8 | residuals.surveyIdx <- function(x,a=1){ 9 | if (pmatch("Tweedie", x$pModels[[a]]$family$family, 10 | nomatch = -1) == 1) { 11 | resi = qres.tweedie(x$pModels[[a]]) 12 | } else if(pmatch("gaussian", x$pModels[[a]]$family$family, 13 | nomatch = -1) == 1 ){## Delta-Lognormal 14 | y = x$allobs[[a]] 15 | logy = y 16 | psel = y>x$cutOff 17 | logy[psel] = log( y[psel] ) 18 | 19 | p0 = predict(x$zModels[[a]],type="response") ## P( obs > cutOff ) 20 | vari = x$pModels[[a]]$sig2 21 | cdfpos = rep(0,length(y)) 22 | cdfpos[psel] = pnorm( q=logy[psel],mean=predict(x$pModels[[a]],type="link"), sd=sqrt(vari)) 23 | u = (1-p0) + cdfpos*p0 24 | u[ !psel ] = runif(sum(!psel), min = 0, max = u[!psel]) 25 | resi = qnorm(u) 26 | 27 | } else if(pmatch("Gamma", x$pModels[[a]]$family$family, 28 | nomatch = -1) == 1 ){ 29 | requireNamespace("MASS") 30 | y = x$allobs[[a]] 31 | psel = y>x$cutOff 32 | 33 | p0 = predict(x$zModels[[a]],type="response") 34 | means = predict(x$pModels[[a]],type="response") 35 | shape = MASS::gamma.shape(x$pModels[[a]])$alpha 36 | cdfpos = rep(0,length(y)) 37 | cdfpos[psel] = pgamma( q=y[psel],shape=shape,rate=shape/means) 38 | u = (1-p0) + cdfpos*p0 39 | u[ !psel ] = runif(sum(!psel), min = 0, max = u[!psel]) 40 | resi = qnorm(u) 41 | 42 | } else if(pmatch("Negative Binomial", x$pModels[[a]]$family$family, 43 | nomatch = -1) == 1 ){ 44 | y = x$pModels[[a]]$y 45 | size = x$pModels[[a]]$family$getTheta(TRUE) 46 | mu = fitted(x$pModels[[a]]) 47 | p = size/(mu + size) 48 | a = ifelse(y > 0, pbeta(p, size, pmax(y, 1)), 0) 49 | b = pbeta(p, size, y + 1) 50 | u = runif(n = length(y), min = a, max = b) 51 | resi = qnorm(u) 52 | } 53 | 54 | resi 55 | } 56 | 57 | ##' Randomized quantile residuals for Tweedie models 58 | ##' 59 | ##' @title Randomized quantile residuals for Tweedie models 60 | ##' @param gam.obj A gam object (mgcv package) 61 | ##' @return A vector of residuals, which should be iid standard normal distributed 62 | ##' @export 63 | ##' @import tweedie 64 | qres.tweedie<-function (gam.obj) 65 | { 66 | requireNamespace("tweedie") 67 | mu <- fitted(gam.obj) 68 | y <- gam.obj$y 69 | df <- gam.obj$df.residual 70 | w <- gam.obj$prior.weights 71 | if (is.null(w)) 72 | w <- rep(1,length(y)) 73 | p <- gam.obj$family$getTheta(TRUE) 74 | dispersion <- gam.obj$scale 75 | u <- numeric(length(y)) 76 | fitt <- fitted(gam.obj) 77 | for(i in 1:length(u)){ 78 | u[i] <- tweedie::ptweedie(q = y[i], power = p, mu = fitt[i],phi = dispersion/w[i]) 79 | } 80 | if (p > 1 && p < 2) 81 | u[y == 0] <- runif(sum(y == 0), min = 0, max = u[y == 82 | 0]) 83 | qnorm(u) 84 | } 85 | -------------------------------------------------------------------------------- /surveyIndex/R/simulate.R: -------------------------------------------------------------------------------- 1 | ##' Simulate data from a surveyIdx model (experimental and subject to change) 2 | ##' 3 | ##' @title Simulate data from a surveyIndex model (experimental and subject to change) 4 | ##' @param model object of class 'surveyIdx' 5 | ##' @param d A dataset (DATRASraw object) 6 | ##' @param sampleFit Use a random sample from the gaussian approximation to distribution of the estimated parameter vector. Default: FALSE. 7 | ##' @param condSim optional results of previous call to this function. Use this if you want to generate many datasets (much faster, since mean predictions are re-used). 8 | ##' @return list with 1) simulated observations with noise 2) mean (no noise) 3) zero probability. 9 | ##' @export 10 | surveyIdx.simulate<-function(model,d,sampleFit=FALSE,condSim=NULL){ 11 | ages = as.numeric(colnames(model$idx)) 12 | dataAges <- model$dataAges 13 | famVec = model$family 14 | 15 | out = d$Nage 16 | out.mu = list() 17 | out.mu0 = list() 18 | 19 | for(a in 1:length(ages)){ 20 | 21 | 22 | if(sampleFit && is.null(condSim)){ 23 | m.pos = model$pModels[[a]] 24 | 25 | Xp.1=predict(m.pos,newdata=d[[2]],type="lpmatrix"); 26 | brp.1=MASS::mvrnorm(n=1,coef(m.pos),m.pos$Vp); 27 | OS.pos = matrix(0,nrow(d[[2]]),1); 28 | terms.pos=terms(m.pos) 29 | if(!is.null(m.pos$offset)){ 30 | off.num.pos <- attr(terms.pos, "offset") 31 | for (i in off.num.pos) OS.pos <- OS.pos + eval(attr(terms.pos, 32 | "variables")[[i + 1]], d[[2]]) 33 | } 34 | mu = Xp.1%*%brp.1+OS.pos 35 | out.mu[[a]] = exp(mu) ## obs, assumes log link! 36 | 37 | if(!famVec[a] %in% c("Tweedie","negbin")){ 38 | m0 = model$zModels[[a]] 39 | Xp.0=predict(m0,newdata=d[[2]],type="lpmatrix"); 40 | brp.0=MASS::mvrnorm(n=1,coef(m0),m0$Vp); 41 | OS0 = matrix(0,nrow(d[[2]]),1); 42 | terms.0=terms(m0) 43 | if(!is.null(m0$offset)){ 44 | off.num.0 <- attr(terms.0, "offset") 45 | for (i in off.num.0) OS0 <- OS0 + eval(attr(terms.0, 46 | "variables")[[i + 1]], d[[2]]) 47 | } 48 | mu0=m0$family$linkinv(Xp.0%*%brp.0+OS0); 49 | out.mu0[[a]] = mu0 50 | } 51 | 52 | } 53 | if(!is.null(condSim)) out.mu[[a]] = condSim[[2]][[a]] 54 | if(!is.null(condSim) && !famVec[a] %in% c("Tweedie","negbin")) out.mu0[[a]] = condSim[[3]][[a]] 55 | 56 | if(famVec[a]==c("Tweedie")){ 57 | p = model$pModels[[a]]$family$getTheta(TRUE) 58 | phi = model$pModels[[a]]$scale 59 | if(!sampleFit && is.null(condSim)) { out.mu[[a]] = predict(model$pModels[[a]],newdata=d[[2]],type="response") } 60 | out[,a] = rTweedie(out.mu[[a]],p,phi) 61 | } else if(famVec[a]=="LogNormal"){ 62 | if(!sampleFit && is.null(condSim)) out.mu0[[a]] = predict(model$zModels[[a]],newdata=d[[2]],type="response") 63 | pa = rbinom(nrow(out),1,prob=out.mu0[[a]]) 64 | sig2 = model$pModels[[a]]$sig2 65 | if(!sampleFit && is.null(condSim)) out.mu[[a]] = exp(predict(model$pModels[[a]],newdata=d[[2]])) 66 | pos = exp( rnorm(nrow(out),log(out.mu[[a]]),sqrt(sig2)) ) 67 | out[,a] = pa*pos 68 | } else if(famVec[a]=="Gamma"){ 69 | if(!sampleFit && is.null(condSim)) out.mu0[[a]] = predict(model$zModels[[a]],newdata=d[[2]],type="response") 70 | pa = rbinom(nrow(out),1,prob=out.mu0[[a]]) 71 | 72 | if(!sampleFit && is.null(condSim)){ 73 | out.mu[[a]]= predict(model$pModels[[a]],newdata=d[[2]],type="response") 74 | } 75 | shape = 1/model$pModels[[a]]$scale 76 | pos = rgamma(nrow(out),rate=shape/out.mu[[a]],shape=shape) 77 | out[,a] = pa*pos 78 | } else if(famVec[a]=="negbin"){ 79 | if(!sampleFit && is.null(condSim)) out.mu[[a]] = predict(model$pModels[[a]],newdata=d[[2]],type="response") 80 | size = model$pModels[[a]]$family$getTheta(TRUE) 81 | out[,a] = rnbinom(length(out.mu[[a]]),size=size,mu=out.mu[[a]]) 82 | } 83 | } 84 | list(sim=out,mu=out.mu,prob0=out.mu0) 85 | } 86 | -------------------------------------------------------------------------------- /surveyIndex/man/getSurveyIdx.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/getSurveyIdx.R 3 | \name{getSurveyIdx} 4 | \alias{getSurveyIdx} 5 | \title{Calculate survey indices by age.} 6 | \usage{ 7 | getSurveyIdx( 8 | x, 9 | ages, 10 | myids, 11 | kvecP = rep(12 * 12, length(ages)), 12 | kvecZ = rep(8 * 8, length(ages)), 13 | gamma = 1.4, 14 | cutOff = 1, 15 | fam = "Gamma", 16 | useBIC = FALSE, 17 | nBoot = 1000, 18 | mc.cores = 1, 19 | method = "ML", 20 | predD = NULL, 21 | modelZ = 22 | rep("Year+s(lon,lat,k=kvecZ[a],bs='ts')+s(Ship,bs='re',by=dum)+s(Depth,bs='ts')+s(TimeShotHour,bs='cc')", 23 | length(ages)), 24 | modelP = 25 | rep("Year+s(lon,lat,k=kvecP[a],bs='ts')+s(Ship,bs='re',by=dum)+s(Depth,bs='ts')+s(TimeShotHour,bs='cc')", 26 | length(ages)), 27 | knotsP = NULL, 28 | knotsZ = NULL, 29 | predfix = NULL, 30 | linkZ = "logit", 31 | CIlevel = 0.95, 32 | addTimeOfYear = FALSE, 33 | ... 34 | ) 35 | } 36 | \arguments{ 37 | \item{x}{DATRASraw object} 38 | 39 | \item{ages}{vector of ages} 40 | 41 | \item{myids}{haul.ids for grid} 42 | 43 | \item{kvecP}{vector with spatial smoother max. basis dimension for each age group, strictly positive part of model} 44 | 45 | \item{kvecZ}{vector with spatial smoother max. basis dimension for each age group, presence/absence part of model (ignored for Tweedie models)} 46 | 47 | \item{gamma}{model degress of freedom inflation factor (see 'gamma' argument to gam() )} 48 | 49 | \item{cutOff}{treat observations below this value as zero} 50 | 51 | \item{fam}{distribution, either "Gamma","LogNormal", or "Tweedie".} 52 | 53 | \item{useBIC}{use BIC for smoothness selection (overrides 'gamma' argument)} 54 | 55 | \item{nBoot}{number of bootstrap samples used for calculating index confidence intervals} 56 | 57 | \item{mc.cores}{number of cores for parallel processing} 58 | 59 | \item{method}{smoothness selection method used by 'gam'} 60 | 61 | \item{predD}{optional DATRASraw object or data.frame (or named list with such objects, one for each year with names(predD) being the years) , defaults to NULL. If not null this is used as grid.} 62 | 63 | \item{modelZ}{vector of model formulae for presence/absence part, one pr. age group (ignored for Tweedie models)} 64 | 65 | \item{modelP}{vector of model formulae for strictly positive repsonses, one pr. age group} 66 | 67 | \item{knotsP}{optional list of knots to gam, strictly positive repsonses} 68 | 69 | \item{knotsZ}{optional list of knots to gam, presence/absence} 70 | 71 | \item{predfix}{optional named list of extra variables (besides Gear, HaulDur, Ship, and TimeShotHour), that should be fixed during prediction step (standardized)} 72 | 73 | \item{linkZ}{link function for the binomial part of the model, default: "logit" (not used for Tweedie models).} 74 | 75 | \item{CIlevel}{Confidence interval level, defaults to 0.95.} 76 | 77 | \item{addTimeOfYear}{if TRUE, add predfix$timeOfYear to 'ctime' when standardizing (otherwise it is 1st of January).} 78 | 79 | \item{...}{Optional extra arguments to "gam"} 80 | 81 | \item{length)}{} 82 | } 83 | \value{ 84 | A survey index (list) 85 | } 86 | \description{ 87 | Calculate survey indices by age. 88 | } 89 | \details{ 90 | This is based on the methods described in 91 | Berg et al. (2014): "Evaluation of alternative age-based methods for estimating relative abundance from survey data in relation to assessment models", 92 | Fisheries Research 151(2014) 91-99. 93 | } 94 | \examples{ 95 | \dontrun{ 96 | library(surveyIndex) 97 | ##downloadExchange("NS-IBTS",1994:2014) 98 | dAll<-readExchangeDir(".",strict=FALSE) 99 | mc.cores<-2; library(parallel) 100 | d<-subset(dAll, Species=="Pollachius virens",Quarter==1,HaulVal=="V",StdSpecRecCode==1, Gear=="GOV") 101 | dAll<-NULL; gc(); ## lose dAll because it takes up a lot of memory 102 | d<-addSpectrum(d,by=1) 103 | ## get idea about number of age groups to include 104 | agetab<-xtabs(NoAtALK~Year+Age,data=d[[1]]) 105 | agetab.df<-as.data.frame(agetab) 106 | ages<-1:8 107 | ## require at least 1 aged individual in each year 108 | for(a in ages){ 109 | if(any(agetab.df$Freq[agetab.df$Age==a]<1)) 110 | d<-fixAgeGroup(d,age=a,fun=ifelse(a==min(ages),"min","mean")) 111 | } 112 | d<-subset(d,Age>=min(ages)) 113 | 114 | ############################### 115 | ## Convert to numbers-at-age 116 | ############################### 117 | d.ysplit <- split(d, d$Year) 118 | ALK<-mclapply(d.ysplit,fitALK,minAge=min(ages),maxAge=max(ages),autoChooseK=TRUE,useBIC=TRUE, 119 | varCof=FALSE,maxK=50,mc.cores=mc.cores) 120 | Nage<-mclapply(ALK,predict,mc.cores=mc.cores) 121 | for(i in 1:length(ALK)) d.ysplit[[i]]$Nage=Nage[[i]]; 122 | dd <- do.call("c",d.ysplit) 123 | 124 | ############## 125 | ## Fit model 126 | ############## 127 | grid <- getGrid(dd, nLon=40) 128 | ## set max basis dim for spatial smooths by age, P=positive and Z=zero/absence. 129 | ## These are set relatively low here to speed up the example 130 | kvP <- c(50,50,50,40,30,rep(10,length(ages)-5)) 131 | kvZ <- kvP / 2; 132 | mP <- rep("Year+s(lon,lat,k=kvecP[a],bs='ts')+s(Depth,bs='ts',k=6)+offset(log(HaulDur))",length(ages) ); 133 | mZ <- rep("Year+s(lon,lat,k=kvecZ[a],bs='ts')+s(Depth,bs='ts',k=6)+offset(log(HaulDur))",length(ages) ); 134 | 135 | SIQ1 <- getSurveyIdx(dd,ages=ages,myids=grid[[3]],cutOff=0.1,kvecP=kvP,kvecZ=kvZ, 136 | modelZ=mZ,modelP=mP,mc.cores=mc.cores) ## if errors are encountered, debug with mc.cores=1 137 | 138 | strat.mean<-getSurveyIdxStratMean(dd,ages) 139 | 140 | ## plot indices, distribution map, and estimated depth effects 141 | surveyIdxPlots(SIQ1,dd,cols=ages,alt.idx=strat.mean,grid[[3]],par=list(mfrow=c(3,3)),legend=FALSE, 142 | select="index",plotByAge=FALSE) 143 | 144 | surveyIdxPlots(SIQ1,dd,cols=ages,alt.idx=NULL,grid[[3]],par=list(mfrow=c(3,3)),legend=FALSE, 145 | colors=rev(heat.colors(8)),select="map",plotByAge=FALSE) 146 | 147 | surveyIdxPlots(SIQ1,dd,cols=ages,alt.idx=NULL,grid[[3]],par=list(mfrow=c(3,3)), 148 | legend=FALSE,select="2",plotByAge=FALSE) 149 | 150 | ## Calculate internal concistency and export to file 151 | internalCons(SIQ1$idx) 152 | exportSI(SIQ1$idx,ages=ages,years=levels(dd$Year),toy=mean(dd$timeOfYear),file="out.dat", 153 | nam="Survey index demo example") 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /surveyIndex/R/retroLO.R: -------------------------------------------------------------------------------- 1 | ##' Make retrospective analysis for a "surveyIdx" model. 2 | ##' 3 | ##' @title Make retrospective analysis for a "surveyIdx" model. 4 | ##' @param model object of class "surveyIdx" as created by "getSurveyIdx" 5 | ##' @param d DATRASraw dataset 6 | ##' @param grid surveyIndexGrid object (see getGrid) defining the grid. 7 | ##' @param npeels number of years to successively peel of the data set 8 | ##' @param predD alternative way of specifiyng the grid (see getSurveyIdx function) 9 | ##' @param nBoot number of bootstrap samples used for calculating index confidence intervals 10 | ##' @param ... Optional extra arguments to "gam" 11 | ##' @return SIlist (list of surveyIndex objects) 12 | ##' @export 13 | retro.surveyIdx<-function(model, d, grid,npeels=5,predD=NULL,nBoot=1000,...){ 14 | if(is.null(predD)){ 15 | predD = subset(d, haul.id %in% grid[[3]]) 16 | predD = predD[[2]] 17 | } 18 | ages = as.numeric(colnames(model$idx)) 19 | dataAges = model$dataAges 20 | famVec = model$family 21 | cutOff = model$cutOff 22 | 23 | ## Potential problem with ref gear (most common gear might change after peeling....) 24 | ## so add it to predfix list 25 | predfix = model$predfix 26 | predfix$Gear = model$refGear 27 | 28 | ## How to handle partial data years? 29 | ## A: find last data year,quarter always remove one year from that 30 | lastY = max(model$yearNum) 31 | lastQ = max(as.numeric(as.character(d$Quarter[ d$Year == lastY ] ))) 32 | yearRange = min(model$yearNum):max(model$yearNum) 33 | yearRange = yearRange[ !is.na(model$idx[,1]) ] 34 | ## Recreate formulae needed 35 | mp <- mz <- character(length(ages)) 36 | for(aa in 1:length(ages)){ 37 | mp[aa] = as.character(model$pModels[[aa]]$formula)[3] 38 | if(length(model$zModels)>0){ 39 | mz[aa] = as.character(model$zModels[[aa]]$formula)[3] 40 | } else { mz = NULL } 41 | } 42 | res = list() 43 | for(i in 1:npeels){ 44 | 45 | curd = subset(d, Year %in% as.character(head(yearRange,length(yearRange)-(i+1))) | 46 | ( Year %in% as.character(head(yearRange,length(yearRange)-i)) & 47 | Quarter %in% as.character(1:lastQ) ) 48 | ) 49 | 50 | cat("Peel ",i, ": re-fitting using years ",levels(curd$Year),"\n") 51 | res[[i]] = getSurveyIdx(curd,ages,myids=NULL,predD=predD,cutOff=cutOff,fam=famVec,method=model$pModels[[1]]$method,knotsP=model$knotsP,knotsZ=model$knotsZ,predfix=predfix,nBoot=nBoot,modelP=mp,modelZ=mz,...) 52 | } 53 | 54 | class(res)<-"SIlist" 55 | res 56 | 57 | } 58 | ##' Make leave-one-out analysis 59 | ##' 60 | ##' @title Make leave-one-out analysis 61 | ##' @param model object of class "surveyIdx" as created by "getSurveyIdx" 62 | ##' @param d DATRASraw dataset 63 | ##' @param grid surveyIndexGrid object (see getGrid) defining the grid. 64 | ##' @param fac a factor in d to leave out one at a time, e.g. d$Survey 65 | ##' @param ... Optional extra arguments to "gam" 66 | ##' @return SIlist (list of surveyIndex objects) 67 | ##' @export 68 | leaveout.surveyIdx<-function(model,d,grid,fac,predD=NULL,...){ 69 | stopifnot(is.factor(fac)) 70 | 71 | if(is.null(predD)){ 72 | predD = subset(d, haul.id %in% grid[[3]]) 73 | predD = predD[[2]] 74 | } 75 | ages = as.numeric(colnames(model$idx)) 76 | dataAges = model$dataAges 77 | famVec = model$family 78 | cutOff = model$cutOff 79 | 80 | predfix = model$predfix 81 | predfix$Gear = model$refGear 82 | 83 | ## Recreate formulae needed 84 | mp <- mz <- character(length(ages)) 85 | for(aa in 1:length(ages)){ 86 | mp[aa] = as.character(model$pModels[[aa]]$formula)[3] 87 | if(length(model$zModels)>0){ 88 | mz[aa] = as.character(model$zModels[[aa]]$formula)[3] 89 | } else { mz = NULL } 90 | } 91 | 92 | res = list() 93 | 94 | for(facc in levels(fac)){ 95 | 96 | curd = d[ which(fac!=facc) ] 97 | 98 | cat("Re-fitting without",facc,"\n") 99 | res[[facc]] = getSurveyIdx(curd,ages,myids=NULL,predD=predD,cutOff=cutOff,fam=famVec,method=model$pModels[[1]]$method,knotsP=model$knotsP,knotsZ=model$knotsZ,predfix=predfix,nBoot=0,modelP=mp,modelZ=mz,...) 100 | } 101 | 102 | class(res)<-"SIlist" 103 | res 104 | } 105 | ##' Plot survey index list (e.g. retrospective analysis) 106 | ##' 107 | ##' @title Plot survey index list (e.g. retrospective analysis) 108 | ##' @param x (named) list of "surveyIdx" objects for example from "retro.surveyIdx" or "leaveout.surveyIdx" 109 | ##' @param base Either index of x that should considered the "base run" (integer), OR object of class "surveyIdx". Confidence bounds will be shown for this model only. 110 | ##' @param rescale Should indices be rescaled to have mean 1 (over the set of intersecting years)? Default: FALSE 111 | ##' @param lwd line width argument to plot 112 | ##' @param main if not NULL override main plotting default title of "Age group a" 113 | ##' @param allCI show 95\% confidence lines for all indices? Default FALSE. 114 | ##' @param includeCI Show confidence intervals? Default TRUE. 115 | ##' @param ylim Y axis range. If NULL (default) then determine automatically. 116 | ##' @param density if TRUE, divide each index by the number of grid points to get densities rather than totals. 117 | ##' @return nothing 118 | ##' @export 119 | plot.SIlist <- function (x, base = 1, rescale = FALSE, lwd = 1.5, main = NULL, 120 | allCI = FALSE, includeCI = TRUE, ylim = NULL, density=FALSE){ 121 | if (class(base) == "surveyIdx") { 122 | x = c(list(base), x) 123 | base = 1 124 | } 125 | stopifnot(is.numeric(base)) 126 | nx = length(x) 127 | mainwasnull = is.null(main) 128 | n = ncol(x[[base]]$idx) 129 | if (n > 1) { 130 | op <- par(mfrow = n2mfrow(n)) 131 | on.exit(par(op)) 132 | } 133 | cols = rainbow(nx) 134 | if (nx == 2) 135 | cols = 2:3 136 | cols[base] = "black" 137 | allyears = lapply(x, function(x) rownames(x$idx)) 138 | rsidx = 1:nrow(x[[nx]]$idx) 139 | if (rescale) { 140 | commonyears = allyears[[1]] 141 | if (nx > 1) { 142 | for (i in 2:nx) { 143 | commonyears = intersect(commonyears, allyears[[i]]) 144 | } 145 | if (length(commonyears) == 0) 146 | stop("rescaling not possible because the set of common years is empty") 147 | } 148 | } 149 | ss <- ssbase <- 1 150 | 151 | for (aa in 1:n) { 152 | if(rescale){ 153 | rsidx = which(rownames(x[[1]]$idx) %in% commonyears) 154 | ss <- mean(x[[1]]$idx[rsidx, aa], na.rm = TRUE) 155 | } 156 | if(density){ 157 | ss <- length(x[[1]]$gPreds2[[1]][[1]]) 158 | } 159 | rangevec = x[[1]]$idx[, aa] / ss 160 | if (nx > 1) { 161 | for (xx in 2:nx){ 162 | if(rescale){ 163 | rsidx = which(rownames(x[[xx]]$idx) %in% commonyears) 164 | ss <- mean(x[[xx]]$idx[rsidx, aa], na.rm = TRUE) 165 | } 166 | if(density){ 167 | ss <- length(x[[xx]]$gPreds2[[1]][[1]]) 168 | } 169 | rangevec = c(rangevec, x[[xx]]$idx[,aa]/ss) 170 | } 171 | } 172 | if (includeCI) { 173 | for (xx in 1:nx){ 174 | if(rescale){ 175 | rsidx = which(rownames(x[[xx]]$idx) %in% commonyears) 176 | ss <- mean(x[[xx]]$idx[rsidx, aa], na.rm = TRUE) 177 | } 178 | if(density){ 179 | ss <- length(x[[xx]]$gPreds2[[1]][[1]]) 180 | } 181 | rangevec = c(rangevec, x[[xx]]$lo[,aa]/ss, x[[xx]]$up[, aa]/ss) 182 | } 183 | } 184 | yl = range(rangevec,na.rm=TRUE) 185 | if(rescale){ 186 | rsidx = which(rownames(x[[base]]$idx) %in% commonyears) 187 | ssbase = mean(x[[base]]$idx[rsidx, aa], na.rm = TRUE) 188 | } 189 | if(density){ 190 | ssbase <- length(x[[base]]$gPreds2[[1]][[1]]) 191 | } 192 | if (!is.null(ylim)) 193 | yl = ylim 194 | if (mainwasnull) 195 | main <- paste("Age group", colnames(x[[base]]$idx)[aa]) 196 | y = as.numeric(rownames(x[[base]]$idx)) 197 | plot(y, x[[base]]$idx[, aa]/ssbase, type = "b", ylim = yl, 198 | main = main, xlab = "Year", ylab = "Index") 199 | if (includeCI){ 200 | sel <- which(!is.na(x[[base]]$idx[,aa])) 201 | polygon(c(y[sel], rev(y[sel])), c(x[[base]]$lo[sel, aa], rev(x[[base]]$up[sel,aa]))/ssbase, col = "lightgrey", border = NA) 202 | } 203 | for (i in 1:length(x)) { 204 | y = as.numeric(rownames(x[[i]]$idx)) 205 | if (rescale) { 206 | rsidx = which(rownames(x[[i]]$idx) %in% commonyears) 207 | ss = mean(x[[i]]$idx[rsidx, aa], na.rm = TRUE) 208 | } 209 | if(density){ 210 | ss <- length(x[[i]]$gPreds2[[1]][[1]]) 211 | } 212 | lines(y, x[[i]]$idx[, aa]/ss, col = cols[i], type = "b", 213 | lwd = lwd) 214 | if (includeCI && allCI && i != base) { 215 | lines(y, x[[i]]$lo[, aa]/ss, col = cols[i], lwd = lwd * 216 | 0.6, lty = 2) 217 | lines(y, x[[i]]$up[, aa]/ss, col = cols[i], lwd = lwd * 218 | 0.6, lty = 2) 219 | } 220 | } 221 | y = as.numeric(rownames(x[[base]]$idx)) 222 | lines(y, x[[base]]$idx[, aa]/ssbase, type = "b", lwd = lwd) 223 | } 224 | if (!is.null(names(x))) { 225 | legend("topleft", legend = names(x), col = cols, lty = 1, 226 | lwd = lwd, pch = 1) 227 | } 228 | } 229 | ##' Mohn's rho for retrospective analysis 230 | ##' 231 | ##' @title Mohn's rho for retrospective analysis 232 | ##' @param x SIlist as returned by the 'retro.surveyIdx' function 233 | ##' @param base Object of class 'surveyIdx' (full run with all years) 234 | ##' @param rescale should the indices for each age group be rescaled to have mean 1 over shortest timespan before calculating mohns rho? Only appropriate for purely relative indices. 235 | ##' @return vector with mohn's rho for each age group 236 | ##' @export 237 | mohn.surveyIdx<-function (x, base, rescale=FALSE){ 238 | 239 | commonyears = rownames(x[[length(x)]]$idx) 240 | if(rescale){ 241 | for (aa in 1:ncol(base$idx)) { 242 | base$idx[,aa] = base$idx[,aa] / mean(base$idx[ rownames(base$idx) %in% commonyears,aa],na.rm=TRUE) 243 | } 244 | } 245 | mohns = rep(NA, ncol(base$idx)) 246 | for (aa in 1:ncol(base$idx)) { 247 | bias <- sapply(x, function(xx) { 248 | if(rescale) { xx$idx[,aa] = xx$idx[,aa] / mean(xx$idx[ rownames(xx$idx) %in% commonyears,aa],na.rm=TRUE) 249 | } 250 | y <- rownames(xx$idx)[nrow(xx$idx)] 251 | (xx$idx[rownames(xx$idx) == y, aa] - base$idx[rownames(base$idx) == y, aa])/base$idx[rownames(base$idx) == y, aa] 252 | }) 253 | mohns[aa] = mean(bias, na.rm=TRUE) 254 | } 255 | mohns 256 | } 257 | -------------------------------------------------------------------------------- /surveyIndex/R/surveyIdxPlots.R: -------------------------------------------------------------------------------- 1 | ##' Visualize results from a survey index model fitted with getSurveyIdx(). 2 | ##' 3 | ##' @title Visualize results from a survey index model fitted with getSurveyIdx(). 4 | ##' @param x Survey index as produced by getSurveyIndex() 5 | ##' @param dat DATRASraw object 6 | ##' @param alt.idx optional matrix with alternative index 7 | ##' @param myids vector of haul ids that constitute the grid 8 | ##' @param cols which age columns to consider? 9 | ##' @param select character vector of chosen plots. Either one of "index","map","absolutemap","CVmap","residuals","fitVsRes",""resVsYear","resVsShip","spatialResiduals", or a number. Numbers refer to smooths in the order they appear in the formula. 10 | ##' @param par 'par' settings for plotting (a named list). 11 | ##' @param colors colors for spatial effect. 12 | ##' @param map.cex size of grid points on maps 13 | ##' @param plotByAge boolean (default=TRUE). If true, par(par) is called for each age group. 14 | ##' @param legend boolean (default=TRUE). add legends to plot? 15 | ##' @param predD DATRASraw object with grid (optional). Overrides 'myids' if supplied. 16 | ##' @param year numeric scalar or vector (default=NULL). If 'select' equals 'map' a specific year can be chosen (only meaningful for time-varying spatial effects). If select equals 'absolutemap' or 'CVmap' then year must be a vector. 17 | ##' @param main optional main title (overrides default title) 18 | ##' @param legend.signif Number of significant digits in map legends 19 | ##' @param legend.pos Position of legend (e.g. "bottomleft") see ?legend 20 | ##' @param restoreOldPar restore old par() on exit? Default=FALSE 21 | ##' @param mapBubbles boolean (default=FALSE) add observation bubbles? 22 | ##' @param cutp optional vector of break points for the color scale on maps 23 | ##' @param map.pch pch for map points, default=16 (filled round). 24 | ##' @param mapArgs arguments to maps::map for drawing coastlines/land 25 | ##' @param ... Additional parameters for plot() 26 | ##' @return nothing 27 | ##' @export 28 | ##' @import maps mapdata tweedie 29 | surveyIdxPlots<-function (x, dat, alt.idx = NULL, myids, cols = 1:length(x$pModels), 30 | select = c("index", "map", "residuals", "fitVsRes"), par = list(mfrow = c(3, 31 | 3)), colors = rev(heat.colors(6)), map.cex = 1, plotByAge = TRUE, 32 | legend = TRUE, predD = NULL, year = NULL, main=NULL, legend.signif=3,legend.pos="topright",restoreOldPar=FALSE,mapBubbles=FALSE,cutp = NULL,map.pch=16,mapArgs=list(fill=TRUE,col=grey(0.5)),...) 33 | { 34 | xlims = range(dat$lon, na.rm = TRUE) 35 | ylims = range(dat$lat, na.rm = TRUE) 36 | mapArgs <- c(list(database="worldHires",plot=TRUE,add=TRUE,xlim=xlims,ylim=ylims),mapArgs) 37 | if (!plotByAge & !is.null(par)){ 38 | op<-par(par) 39 | if(restoreOldPar) on.exit(par(op)) 40 | } 41 | mainwasnull <- is.null(main) 42 | for (a in cols) { 43 | if(mainwasnull) main <- paste("Age group", colnames(dat$Nage)[a]) 44 | if (plotByAge & !is.null(par)){ 45 | op<-par(par) 46 | if(restoreOldPar) on.exit(par(op)) 47 | } 48 | if (any(select == "index")) { 49 | ys = range(as.numeric(levels(dat$Year))) 50 | ys = ys[1]:ys[2] 51 | yl = range(c(x$idx[, a],0,x$lo[,a],x$up[,a])/mean(x$idx[, a],na.rm=TRUE),na.rm=TRUE) 52 | if (!is.null(alt.idx) && a <= ncol(alt.idx)) { 53 | yl = range(c(alt.idx[, a]/mean(alt.idx[, a]), 54 | yl)) * 1.1 55 | plot(ys, alt.idx[, a]/mean(alt.idx[, a], na.rm = TRUE), 56 | ylim = yl, col = 2, ylab = "Index", xlab = "Year", 57 | main = main) 58 | } 59 | else { 60 | plot(ys, rep(NA, length(ys)), ylim = yl, col = 2, 61 | ylab = "Index", xlab = "Year", main = main ) 62 | } 63 | idx = x$idx 64 | lo = x$lo 65 | up = x$up 66 | idx[x$idx <= 0] = NA 67 | lo[x$idx <= 0] = NA 68 | up[x$idx <= 0] = NA 69 | lines(ys, idx[, a]/mean(idx[, a], na.rm = TRUE), 70 | lwd = 2) 71 | lines(ys, lo[, a]/mean(idx[, a], na.rm = TRUE), lwd = 2, 72 | lty = 2) 73 | lines(ys, up[, a]/mean(idx[, a], na.rm = TRUE), lwd = 2, 74 | lty = 2) 75 | if (legend && !is.null(alt.idx)) 76 | legend(legend.pos, pch = c(1, NA), lty = c(NA, 77 | 1), col = c(2, 1), legend = c("alt.idx", "GAM")) 78 | } 79 | if (any(select == "map")) { 80 | mapvals = NULL 81 | if (is.null(predD)) { 82 | tmp = subset(dat, haul.id %in% myids) 83 | } 84 | else { 85 | tmp = predD 86 | } 87 | if (is.null(year)) { 88 | concT = surveyIndex:::concTransform(log(x$gPreds[[a]])) 89 | mapvals = x$gPreds[[a]] 90 | } 91 | else { 92 | y = which(as.numeric(as.character(names(x$gPreds2[[a]]))) == 93 | year) 94 | if (length(y) == 0) 95 | stop(paste("Year", year, "age group", a, "not found.")) 96 | concT = surveyIndex:::concTransform(log(x$gPreds2[[a]][[y]])) 97 | mapvals = x$gPreds2[[a]][[y]] 98 | } 99 | if (length(colors) > 1) 100 | zFac = cut(concT, 0:length(colors)/length(colors)) 101 | else zFac = 1 102 | if (length(map.cex) > 1) 103 | sFac = cut(log(x$gPreds[[a]]), length(map.cex)) 104 | else sFac = 1 105 | myCols = colors 106 | plot(tmp$lon, y = tmp$lat, col = 1, pch = 1, cex = map.cex[sFac], 107 | xlim = xlims, ylim = ylims, xlab = "Longitude", 108 | ylab = "Latitude", main = main, ...) 109 | points(tmp$lon, y = tmp$lat, col = myCols[zFac], 110 | pch = 16, cex = map.cex[sFac]) 111 | do.call(maps::map,mapArgs) 112 | if (legend){ 113 | maxcuts = aggregate(mapvals ~ zFac, FUN=max) 114 | mincuts = aggregate(mapvals ~ zFac, FUN=min) 115 | mm = mean(mapvals) 116 | ml = signif(mincuts[,2]/mm,legend.signif) 117 | ml[1] = 0 118 | leg = paste0("[",ml,",",signif(maxcuts[,2]/mm,legend.signif),"]") 119 | legend(legend.pos, legend = leg, pch = 16, col = colors, bg = "white") 120 | } 121 | } 122 | if (any(select == "absolutemap") || any(select == "CVmap")) { 123 | if(is.null(year) || length(year)==0) stop("argument 'year' must be vector of length>=1 for type 'absolutemap'") 124 | if( !all(year %in% levels(dat$Year)) ) stop("invalid years selected") 125 | 126 | if(any(select == "absolutemap")) colsel = "gPreds2" else colsel = "gPreds2.CV" 127 | goodyears = intersect(year,names(x[[colsel]][[a]])) 128 | ## collect all years as data.frame 129 | ally = data.frame(val = numeric(0), year = character(0)) 130 | for(y in goodyears){ 131 | ally = rbind(ally, data.frame(val=x[[colsel]][[a]][[y]], 132 | year=y)) 133 | } 134 | ally$conc = surveyIndex:::concTransform(log(ally$val)) 135 | if(is.null(cutp)){ 136 | ally$zFac=cut( ally$conc,0:length(colors)/length(colors)) 137 | } else { 138 | if(length(cutp) != length(colors) + 1) stop("incompatible number of colors and length of cutp") 139 | ally$zFac=cut( ally$val,cutp) 140 | } 141 | bubbleScale = 0.005*max(dat$Nage[,a]) 142 | for(yy in year){ 143 | sel = which(ally$year == yy) 144 | if (is.null(predD)) { 145 | tmp = subset(dat, haul.id %in% myids) 146 | } 147 | else { 148 | tmp = predD 149 | if(is.list(tmp) && !class(tmp)%in%c("data.frame","DATRASraw")) tmp = predD[[as.character(yy)]] 150 | } 151 | 152 | plot(tmp$lon,y=tmp$lat,col=1,pch=1,cex=map.cex,xlab="Longitude",ylab="Latitude",axes=FALSE,type=ifelse(length(sel)>0,"p","n")) 153 | box() 154 | title(yy,line=1) 155 | if(length(sel)==0) next; 156 | points(tmp$lon,y=tmp$lat,col=colors[as.numeric(ally$zFac[sel])],pch=map.pch,cex=map.cex) 157 | do.call(maps::map,mapArgs) 158 | if(mapBubbles){ 159 | dy = subset(dat,Year==yy) 160 | points(dy$lon,dy$lat,cex=sqrt(dy$Nage[,a]/bubbleScale)) 161 | } 162 | if (legend && yy==year[1]){ 163 | if(is.null(cutp)){ 164 | maxcuts = aggregate(val ~ zFac, data=ally, FUN=max) 165 | mincuts = aggregate(val ~ zFac, data=ally, FUN=min) 166 | mm = mean(ally$val) 167 | ml = signif(mincuts[,2]/mm,legend.signif) 168 | ml[1] = 0 169 | leg = paste0("[",ml,",",signif(maxcuts[,2]/mm,legend.signif),"]") 170 | legend(legend.pos, legend = leg, pch = 16, col = colors, bg = "white") 171 | } else { 172 | legend(legend.pos, legend = levels(ally$zFac), pch = 16, col = colors, bg = "white") } 173 | } 174 | }##rof year 175 | }## absolutemap 176 | 177 | for (k in 1:length(select)) { 178 | ss = suppressWarnings(as.numeric(select[k])) 179 | if (!is.na(ss)) { 180 | plot.gam(x$pModels[[a]], select = ss, main = main, ...) 181 | } 182 | } 183 | if (any(select == "residuals") || any(select == "fitVsRes") || 184 | any(select == "resVsYear") || any(select == "resVsShip") || 185 | any(select == "spatialResiduals")) { 186 | 187 | resi <- x$residuals[[a]] ##residuals(x,a) 188 | } 189 | if (any(select == "residuals")) { 190 | hist(resi, nclass = 30, main = main, xlab = "Residuals",...) 191 | } 192 | if (any(select == "fitVsRes")) { 193 | plot(fitted(x$pModels[[a]]), residuals(x$pModels[[a]]), xlab = "Fitted", 194 | ylab = "Residuals", main = main,...) ## TODO: use quantile residuals here too 195 | } 196 | if (any(select == "resVsYear")) { 197 | plot(dat$Year, resi, main = main, xlab = "Year", ylab = "Residuals", 198 | ...) 199 | } 200 | if (any(select == "resVsShip")) { 201 | plot(dat$Ship, resi, main = main, xlab = "Year", ylab = "Residuals", 202 | ...) 203 | } 204 | if (any(select == "spatialResiduals")) { 205 | scale <- 3 * map.cex 206 | if (is.null(year) || length(year)>1) 207 | stop("a single year must be supplied") 208 | sel <- which(dat[[2]]$Year == as.character(year)) 209 | plot(dat$lon, dat$lat, type = "n", 210 | xlab = "Longitude", ylab = "Latitude", main = main,...) 211 | do.call(maps::map,mapArgs) 212 | positive = resi[sel] > 0 213 | points(dat$lon[sel][positive], dat$lat[sel][positive], 214 | pch = 1, cex = scale * sqrt(resi[sel][positive]), 215 | col = "blue") 216 | points(dat$lon[sel][!positive], dat$lat[sel][!positive], 217 | pch = 1, cex = scale * sqrt(-resi[sel][!positive]), 218 | col = "red") 219 | } 220 | } 221 | } 222 | 223 | ##' Plot values for each color level in a map as created by 'surveyIdxPlots'. 224 | ##' 225 | ##' @title Plot values for each color level in a map as created by 'surveyIdxPlots'. 226 | ##' @param x object of class 'surveyIdx' 227 | ##' @param year vector of years (should be the same as used for 'surveyIdxPlots') 228 | ##' @param colors vector of colors to use 229 | ##' @param age age group (integer >=1) 230 | ##' @param legend.signif number of significant digits shown 231 | ##' @param cutp optional custom vector of cut points for color scales. 232 | ##' @param lwd line width for bars 233 | ##' @param las orientation of x-axis lables 234 | ##' @export 235 | mapLegend<-function(x,year,colors = rev(heat.colors(6)),age = 1,legend.signif=3,cutp = NULL,lwd=10,las=2){ 236 | colsel = "gPreds2" 237 | a = age 238 | goodyears = intersect(year,names(x[[colsel]][[a]])) 239 | 240 | ally = data.frame(val = numeric(0), year = character(0)) 241 | for(y in goodyears){ 242 | ally = rbind(ally, data.frame(val=x[[colsel]][[a]][[y]],year=y)) 243 | } 244 | ally$conc = surveyIndex:::concTransform(log(ally$val)) 245 | if(is.null(cutp)){ 246 | ally$zFac=cut( ally$conc,0:length(colors)/length(colors)) 247 | } else { 248 | if(length(cutp) != length(colors) + 1) stop("incompatible number of colors and length of cutp") 249 | ally$zFac=cut( ally$val,cutp) 250 | } 251 | mvals = aggregate(val ~ zFac, data=ally, FUN=mean) 252 | mm = mean(ally$val) 253 | if(is.null(cutp)){ 254 | maxcuts = aggregate(val ~ zFac, data=ally, FUN=max) 255 | mincuts = aggregate(val ~ zFac, data=ally, FUN=min) 256 | ml = signif(mincuts[,2]/mm,legend.signif) 257 | ml[1] = 0 258 | leg = paste0("[",ml,",",signif(maxcuts[,2]/mm,legend.signif),"]") 259 | plot(mvals[,2],type="h",lwd=lwd+lwd*0.1,col=1,axes=FALSE) 260 | points(mvals[,2],type="h",lwd=lwd,col=colors) 261 | axis(1,at=1:length(colors),labels=leg,las=las) 262 | } else { 263 | leg = levels(ally$zFac) 264 | plot(mvals[,2],type="h",lwd=11,col=1,axes=FALSE) 265 | points(mvals[,2],type="h",lwd=10,col=colors) 266 | axis(1,at=1:length(colors),labels=leg,las=las) 267 | } 268 | 269 | } 270 | 271 | 272 | ##' Plot estimates of factor levels (or random effects) from a GAM model. 273 | ##' 274 | ##' @param x A model of class 'gam' or 'glm' 275 | ##' @param name name of the factor 276 | ##' @param invlink inverse link function 277 | ##' @param levs optional custom factor level names 278 | ##' @param ... extra arguments to 'plot' 279 | ##' @export 280 | factorplot<-function(x, name, invlink=exp, levs=NULL,ylim=NULL,... ){ 281 | sel<- grep( name, names(coef(x))) 282 | est <- coef(x)[ sel ] 283 | sds <- sqrt(diag( vcov(x) ))[ sel ] 284 | lo <- invlink(est - 2*sds) 285 | hi <- invlink(est + 2*sds) 286 | if(is.null(ylim)) ylim <- range(c(lo,hi)) 287 | xs <- 1:length(est) 288 | 289 | nams <- names(est) 290 | if(!is.null(levs)) nams <- levs 291 | op <- par(las=2) 292 | on.exit(par(op)) 293 | plot( xs, invlink(est), ylim=ylim,...,xaxt="n",xlab="", ylab="Estimate") 294 | axis(1,labels=nams,at=xs) 295 | arrows( xs,lo,y1=hi,angle=90,code=3,length=0.1) 296 | } 297 | 298 | ##' Calculate and plot the distribution as a function of depth 299 | ##' 300 | ##' @title Calculate and plot the distribution as a function of depth 301 | ##' @param m object of class 'surveyIdx' 302 | ##' @param grid grid object used when fitting 'm' 303 | ##' @param by depth bin size 304 | ##' @param type character vector indicating what to plot. 'dist' or 'mean' or both. 305 | ##' @param colfun color function to use for plotting. 306 | ##' @param lwd plotting line width 307 | ##' @param rangeFrac Fraction ]0;1[ indicating the percentile range in the mean plot. Default is 0.5, i.e. interquartile range. 308 | ##' @param age which age group to plot 309 | ##' @param ... extra arguments to 'plot 310 | ##' @return a matrix with depth distribution in each year. 311 | ##' @export 312 | depthDist<-function(m,grid,by=5,type=c("dist","density","mean"),colfun=colorRampPalette(c("red","lightgrey","blue")),lwd=1.5,rangeFrac=0.5,age=1,...){ 313 | br = seq(min(grid$Depth)-1,max(grid$Depth)+1,by=by) 314 | gridd = cut(grid$Depth,breaks=br) 315 | dds = lapply(m$gPreds2[[age]],function(x) xtabs(x ~ gridd)/sum(x)) 316 | ddsrs = do.call(cbind,dds) 317 | cols = colfun(ncol(ddsrs)) 318 | if("dist" %in% type){ 319 | matplot(ddsrs,type="l",lty=1,col=cols,axes=FALSE,xlab="Depth",ylab="Proportion",lwd=lwd,...) 320 | axis(1,labels=levels(gridd),at=1:nrow(ddsrs)) 321 | axis(2) 322 | box() 323 | sel = seq(1,nrow(m$idx),length.out=min(nrow(m$idx),5)) 324 | legend("topright",lty=1,legend=rownames(m$idx)[sel],col=cols[sel],lwd=lwd) 325 | } 326 | if("density" %in% type){ 327 | dds.dens = lapply(m$gPreds2[[age]],function(x) xtabs(x ~ gridd)/xtabs(~gridd)) 328 | dds.dens = lapply(dds.dens,function(x) x/sum(x)) 329 | ddsrs = do.call(cbind,dds.dens) 330 | cols = colfun(ncol(ddsrs)) 331 | matplot(ddsrs,type="l",lty=1,col=cols,axes=FALSE,xlab="Depth",ylab="Density",lwd=lwd,...) 332 | axis(1,labels=levels(gridd),at=1:nrow(ddsrs)) 333 | axis(2) 334 | box() 335 | sel = seq(1,nrow(m$idx),length.out=min(nrow(m$idx),5)) 336 | legend("topright",lty=1,legend=rownames(m$idx)[sel],col=cols[sel],lwd=lwd) 337 | } 338 | if("mean" %in% type){ 339 | md = br[-1]+0.5 340 | mdy = colSums(ddsrs*md) 341 | lo = md[apply( ddsrs,2,function(x) match(TRUE,cumsum(x)>rangeFrac/2) )] 342 | hi = md[apply( ddsrs,2,function(x) match(TRUE,cumsum(x)>(1-rangeFrac/2) ))] 343 | plot(names(mdy),mdy,type="p",pch=16,cex=1.5,ylab="Mean depth",xlab="Year",ylim=range(c(lo,hi)),col=cols) 344 | arrows(as.numeric(names(mdy)),y0=lo,y1=hi,code=3,angle=90,length=0.1,col=cols,lwd=lwd) 345 | abline(h=mean(mdy),lty=2) 346 | } 347 | ddsrs 348 | } 349 | -------------------------------------------------------------------------------- /surveyIndex/R/getSurveyIdx.R: -------------------------------------------------------------------------------- 1 | ##' Calculate survey indices by age. 2 | ##' 3 | ##' This is based on the methods described in 4 | ##' Berg et al. (2014): "Evaluation of alternative age-based methods for estimating relative abundance from survey data in relation to assessment models", 5 | ##' Fisheries Research 151(2014) 91-99. 6 | ##' @title Calculate survey indices by age. 7 | ##' @param x DATRASraw object 8 | ##' @param ages vector of ages 9 | ##' @param myids haul.ids for grid 10 | ##' @param kvecP vector with spatial smoother max. basis dimension for each age group, strictly positive part of model 11 | ##' @param kvecZ vector with spatial smoother max. basis dimension for each age group, presence/absence part of model (ignored for Tweedie models) 12 | ##' @param gamma model degress of freedom inflation factor (see 'gamma' argument to gam() ) 13 | ##' @param cutOff treat observations below this value as zero 14 | ##' @param fam distribution, either "Gamma","LogNormal", or "Tweedie". 15 | ##' @param useBIC use BIC for smoothness selection (overrides 'gamma' argument) 16 | ##' @param nBoot number of bootstrap samples used for calculating index confidence intervals 17 | ##' @param mc.cores number of cores for parallel processing 18 | ##' @param method smoothness selection method used by 'gam' 19 | ##' @param predD optional DATRASraw object or data.frame (or named list with such objects, one for each year with names(predD) being the years) , defaults to NULL. If not null this is used as grid. 20 | ##' @param modelZ vector of model formulae for presence/absence part, one pr. age group (ignored for Tweedie models) 21 | ##' @param length) 22 | ##' @param modelP vector of model formulae for strictly positive repsonses, one pr. age group 23 | ##' @param length) 24 | ##' @param knotsP optional list of knots to gam, strictly positive repsonses 25 | ##' @param knotsZ optional list of knots to gam, presence/absence 26 | ##' @param predfix optional named list of extra variables (besides Gear, HaulDur, Ship, and TimeShotHour), that should be fixed during prediction step (standardized) 27 | ##' @param linkZ link function for the binomial part of the model, default: "logit" (not used for Tweedie models). 28 | ##' @param CIlevel Confidence interval level, defaults to 0.95. 29 | ##' @param addTimeOfYear if TRUE, add predfix$timeOfYear to 'ctime' when standardizing (otherwise it is 1st of January). 30 | ##' @param ... Optional extra arguments to "gam" 31 | ##' @return A survey index (list) 32 | ##' @examples 33 | ##' \dontrun{ 34 | ##' library(surveyIndex) 35 | ##' ##downloadExchange("NS-IBTS",1994:2014) 36 | ##' dAll<-readExchangeDir(".",strict=FALSE) 37 | ##' mc.cores<-2; library(parallel) 38 | ##' d<-subset(dAll, Species=="Pollachius virens",Quarter==1,HaulVal=="V",StdSpecRecCode==1, Gear=="GOV") 39 | ##' dAll<-NULL; gc(); ## lose dAll because it takes up a lot of memory 40 | ##' d<-addSpectrum(d,by=1) 41 | ##' ## get idea about number of age groups to include 42 | ##' agetab<-xtabs(NoAtALK~Year+Age,data=d[[1]]) 43 | ##' agetab.df<-as.data.frame(agetab) 44 | ##' ages<-1:8 45 | ##' ## require at least 1 aged individual in each year 46 | ##' for(a in ages){ 47 | ##' if(any(agetab.df$Freq[agetab.df$Age==a]<1)) 48 | ##' d<-fixAgeGroup(d,age=a,fun=ifelse(a==min(ages),"min","mean")) 49 | ##' } 50 | ##' d<-subset(d,Age>=min(ages)) 51 | ##' 52 | ##' ############################### 53 | ##' ## Convert to numbers-at-age 54 | ##' ############################### 55 | ##' d.ysplit <- split(d, d$Year) 56 | ##' ALK<-mclapply(d.ysplit,fitALK,minAge=min(ages),maxAge=max(ages),autoChooseK=TRUE,useBIC=TRUE, 57 | ##' varCof=FALSE,maxK=50,mc.cores=mc.cores) 58 | ##' Nage<-mclapply(ALK,predict,mc.cores=mc.cores) 59 | ##' for(i in 1:length(ALK)) d.ysplit[[i]]$Nage=Nage[[i]]; 60 | ##' dd <- do.call("c",d.ysplit) 61 | ##' 62 | ##' ############## 63 | ##' ## Fit model 64 | ##' ############## 65 | ##' grid <- getGrid(dd, nLon=40) 66 | ##' ## set max basis dim for spatial smooths by age, P=positive and Z=zero/absence. 67 | ##' ## These are set relatively low here to speed up the example 68 | ##' kvP <- c(50,50,50,40,30,rep(10,length(ages)-5)) 69 | ##' kvZ <- kvP / 2; 70 | ##' mP <- rep("Year+s(lon,lat,k=kvecP[a],bs='ts')+s(Depth,bs='ts',k=6)+offset(log(HaulDur))",length(ages) ); 71 | ##' mZ <- rep("Year+s(lon,lat,k=kvecZ[a],bs='ts')+s(Depth,bs='ts',k=6)+offset(log(HaulDur))",length(ages) ); 72 | ##' 73 | ##' SIQ1 <- getSurveyIdx(dd,ages=ages,myids=grid[[3]],cutOff=0.1,kvecP=kvP,kvecZ=kvZ, 74 | ##' modelZ=mZ,modelP=mP,mc.cores=mc.cores) ## if errors are encountered, debug with mc.cores=1 75 | ##' 76 | ##' strat.mean<-getSurveyIdxStratMean(dd,ages) 77 | ##' 78 | ##' ## plot indices, distribution map, and estimated depth effects 79 | ##' surveyIdxPlots(SIQ1,dd,cols=ages,alt.idx=strat.mean,grid[[3]],par=list(mfrow=c(3,3)),legend=FALSE, 80 | ##' select="index",plotByAge=FALSE) 81 | ##' 82 | ##' surveyIdxPlots(SIQ1,dd,cols=ages,alt.idx=NULL,grid[[3]],par=list(mfrow=c(3,3)),legend=FALSE, 83 | ##' colors=rev(heat.colors(8)),select="map",plotByAge=FALSE) 84 | ##' 85 | ##' surveyIdxPlots(SIQ1,dd,cols=ages,alt.idx=NULL,grid[[3]],par=list(mfrow=c(3,3)), 86 | ##' legend=FALSE,select="2",plotByAge=FALSE) 87 | ##' 88 | ##' ## Calculate internal concistency and export to file 89 | ##' internalCons(SIQ1$idx) 90 | ##' exportSI(SIQ1$idx,ages=ages,years=levels(dd$Year),toy=mean(dd$timeOfYear),file="out.dat", 91 | ##' nam="Survey index demo example") 92 | ##' } 93 | ##' @importFrom MASS mvrnorm 94 | ##' @export 95 | getSurveyIdx <- 96 | function(x,ages,myids,kvecP=rep(12*12,length(ages)),kvecZ=rep(8*8,length(ages)),gamma=1.4,cutOff=1,fam="Gamma",useBIC=FALSE,nBoot=1000,mc.cores=1,method="ML",predD=NULL, 97 | modelZ=rep("Year+s(lon,lat,k=kvecZ[a],bs='ts')+s(Ship,bs='re',by=dum)+s(Depth,bs='ts')+s(TimeShotHour,bs='cc')",length(ages) ),modelP=rep("Year+s(lon,lat,k=kvecP[a],bs='ts')+s(Ship,bs='re',by=dum)+s(Depth,bs='ts')+s(TimeShotHour,bs='cc')",length(ages) ),knotsP=NULL,knotsZ=NULL,predfix=NULL,linkZ="logit", CIlevel=0.95,addTimeOfYear=FALSE,... 98 | ){ 99 | 100 | if(is.null(x$Nage)) stop("No age matrix 'Nage' found."); 101 | if(is.null(colnames(x$Nage))) stop("No colnames found on 'Nage' matrix."); 102 | if(length(modelP)cutOff)); 153 | gammaPos=log(nPos)/2; 154 | gammaZ=log(nZ)/2; 155 | cat("gammaPos: ",gammaPos," gammaZ: ",gammaZ,"\n"); 156 | } 157 | pd = subset(ddd,A1>cutOff) 158 | if(famVec[a]=="LogNormal"){ 159 | f.pos = as.formula( paste( "log(A1) ~",modelP[a])); 160 | f.0 = as.formula( paste( "A1>",cutOff," ~",modelZ[a])); 161 | 162 | print(system.time(m.pos<-DATRAS:::tryCatch.W.E(gam(f.pos,data=subset(ddd,A1>cutOff),gamma=gammaPos,method=method,knots=knotsP,na.action=na.fail,...))$value)); 163 | 164 | if(class(m.pos)[2] == "error") { 165 | print(m.pos) 166 | stop("Error occured for age ", a, " in the positive part of the model\n", "Try reducing the number of age groups or decrease the basis dimension of the smooths, k\n") 167 | } 168 | 169 | print(system.time(m0<-DATRAS:::tryCatch.W.E(gam(f.0,gamma=gammaZ,data=ddd,family=binomial(link=linkZ),method=method,knots=knotsZ,na.action=na.fail,...))$value)); 170 | 171 | if(class(m0)[2] == "error") { 172 | print(m0) 173 | stop("Error occured for age ", a, " in the binomial part of the model\n", "Try reducing the number of age groups or decrease the basis dimension of the smooths, k\n") 174 | } 175 | 176 | } else if(famVec[a]=="Gamma"){ 177 | f.pos = as.formula( paste( "A1 ~",modelP[a])); 178 | f.0 = as.formula( paste( "A1>",cutOff," ~",modelZ[a])); 179 | 180 | print(system.time(m.pos<-DATRAS:::tryCatch.W.E(gam(f.pos,data=subset(ddd,A1>cutOff),family=Gamma(link="log"),gamma=gammaPos,method=method,knots=knotsP,na.action=na.fail,...))$value)); 181 | 182 | if(class(m.pos)[2] == "error") { 183 | print(m.pos) 184 | stop("Error occured for age ", a, " in the positive part of the model\n", "Try reducing the number of age groups or decrease the basis dimension of the smooths, k\n") 185 | } 186 | 187 | print(system.time(m0<-DATRAS:::tryCatch.W.E(gam(f.0,gamma=gammaZ,data=ddd,family=binomial(link=linkZ),method=method,knots=knotsZ,na.action=na.fail,...))$value)); 188 | 189 | if(class(m0)[2] == "error") { 190 | print(m0) 191 | stop("Error occured for age ", a, " in the binomial part of the model\n", "Try reducing the number of age groups or decrease the basis dimension of the smooths, k\n") 192 | } 193 | } else if(famVec[a]=="Tweedie"){ 194 | ddd$A1[ ddd$A1cutOff] 219 | p0m1=p0p[ddd$A1<=cutOff] 220 | if(famVec[a]=="Gamma") totll=sum(log(p0m1))+sum(log(1-ppos))+logLik(m.pos)[1]; 221 | ## if logNormal model, we must transform til log-likelihood to be able to use AIC 222 | ## L(y) = prod( dnorm( log y_i, mu_i, sigma^2) * ( 1 / y_i ) ) => logLik(y) = sum( log[dnorm(log y_i, mu_i, sigma^2)] - log( y_i ) ) 223 | if(famVec[a]=="LogNormal") totll=sum(log(p0m1))+ sum(log(1-ppos)) + logLik(m.pos)[1] - sum(m.pos$y); 224 | } 225 | 226 | if(is.null(predD)) predD=subset(ddd,haul.id %in% myids); 227 | res=numeric(length(yearRange)); 228 | res[] <- NA 229 | lores=res; 230 | upres=res; 231 | gp2=list() 232 | gp2.cv=list() 233 | cat("Predicting on grid for age ",age,"\n") 234 | for(y in levels(ddd$Year)){ 235 | cat("Year ",y,"\n") 236 | ## take care of years with all zeroes 237 | if(!any(ddd$A1[ddd$Year==y]>cutOff)){ 238 | res[which(as.character(yearRange)==y)]=NA; 239 | upres[which(as.character(yearRange)==y)] = NA; 240 | lores[which(as.character(yearRange)==y)] = NA; 241 | next; 242 | } 243 | if(is.list(predDc) && !class(predDc)%in%c("data.frame","DATRASraw")) predD = predDc[[as.character(y)]] 244 | if(is.null(predD)) stop(paste("Year",y," not found in predD")) 245 | ## OBS: effects that should be removed should be included here 246 | predD$Year=y; predD$dum=0; 247 | predD$ctime=as.numeric(as.character(y)); 248 | predD$TimeShotHour=mean(ddd$TimeShotHour) 249 | predD$Ship=names(which.max(summary(ddd$Ship))) 250 | predD$timeOfYear=mean(ddd$timeOfYear); 251 | predD$HaulDur=30.0 252 | predD$Gear=myGear; 253 | if(!is.null(predfix)){ ##optional extra variables for standardization 254 | stopifnot(is.list(predfix)) 255 | for(n in names(predfix)){ 256 | predD[,n] = predfix[[n]] 257 | } 258 | } 259 | 260 | if("timeOfYear" %in% names(predfix) && addTimeOfYear){ 261 | predD$ctime = predD$ctime + predfix$timeOfYear 262 | } 263 | 264 | p.1 <- p.0 <- NULL 265 | try({ 266 | Xp.1=predict(m.pos,newdata=predD,type="lpmatrix"); 267 | OS.pos = numeric(nrow(predD)); 268 | terms.pos=terms(m.pos) 269 | if(!is.null(m.pos$offset)){ 270 | off.num.pos <- attr(terms.pos, "offset") 271 | for (i in off.num.pos) OS.pos <- OS.pos + eval(attr(terms.pos, 272 | "variables")[[i + 1]], predD) 273 | } 274 | p.1 =Xp.1%*%coef(m.pos)+OS.pos; 275 | if(!famVec[a] %in% c("Tweedie","negbin")){ 276 | Xp.0=predict(m0,newdata=predD,type="lpmatrix"); 277 | brp.0=coef(m0); 278 | OS0 = numeric(nrow(predD)) 279 | terms.0=terms(m0) 280 | if(!is.null(m0$offset)){ 281 | off.num.0 <- attr(terms.0, "offset") 282 | for (i in off.num.0) OS0 <- OS0 + eval(attr(terms.0, 283 | "variables")[[i + 1]], predD) 284 | } 285 | p.0 = m0$family$linkinv(Xp.0%*%brp.0+OS0); 286 | } 287 | }); 288 | ## take care of failing predictions 289 | if(!is.numeric(p.1) | (!famVec[a] %in% c("Tweedie","negbin") && !is.numeric(p.0))) { 290 | res[which(as.character(yearRange)==y)]=NA; 291 | upres[which(as.character(yearRange)==y)] = NA; 292 | lores[which(as.character(yearRange)==y)] = NA; 293 | next; 294 | } 295 | sig2=m.pos$sig2; 296 | 297 | if(famVec[a]=="Gamma") { res[which(as.character(yearRange)==y)] = sum(p.0*exp(p.1)); gPred=p.0*exp(p.1) } 298 | if(famVec[a]=="LogNormal") { res[which(as.character(yearRange)==y)] = sum(p.0*exp(p.1+sig2/2)); gPred=p.0*exp(p.1+sig2/2) } 299 | if(famVec[a] %in% c("Tweedie","negbin")) { res[which(as.character(yearRange)==y)] = sum(exp(p.1)); gPred=exp(p.1) } 300 | gp2[[y]]=gPred; 301 | if(nBoot>10){ 302 | brp.1=mvrnorm(n=nBoot,coef(m.pos),m.pos$Vp); 303 | if(!famVec[a] %in% c("Tweedie","negbin")){ 304 | brp.0=mvrnorm(n=nBoot,coef(m0),m0$Vp); 305 | OS0 = matrix(0,nrow(predD),nBoot); 306 | terms.0=terms(m0) 307 | if(!is.null(m0$offset)){ 308 | off.num.0 <- attr(terms.0, "offset") 309 | for (i in off.num.0) OS0 <- OS0 + eval(attr(terms.0, 310 | "variables")[[i + 1]], predD) 311 | } 312 | rep0=m0$family$linkinv(Xp.0%*%t(brp.0)+OS0); 313 | } 314 | OS.pos = matrix(0,nrow(predD),nBoot); 315 | terms.pos=terms(m.pos) 316 | if(!is.null(m.pos$offset)){ 317 | off.num.pos <- attr(terms.pos, "offset") 318 | for (i in off.num.pos) OS.pos <- OS.pos + eval(attr(terms.pos, 319 | "variables")[[i + 1]], predD) 320 | } 321 | if(famVec[a]=="LogNormal"){ 322 | rep1=exp(Xp.1%*%t(brp.1)+sig2/2+OS.pos); 323 | } else { 324 | rep1=exp(Xp.1%*%t(brp.1)+OS.pos); 325 | } 326 | 327 | if(!famVec[a] %in% c("Tweedie","negbin")){ 328 | idxSamp = colSums(rep0*rep1); 329 | ##gp.sd = apply(rep0*rep1,1,sd) 330 | ##gp.sd = apply(log(rep0*rep1),1,sd) 331 | ##gp2.cv[[y]] = gp.sd / gPred 332 | ##gp2.cv[[y]] = sqrt( exp(gp.sd)^2 - 1) 333 | gp2.cv[[y]] = apply(log(rep0*rep1),1,sd) 334 | } else { 335 | idxSamp = colSums(rep1); 336 | ##gp.sd = apply(rep1,1,sd) 337 | ##gp.sd = apply(log(rep1),1,sd) 338 | ##gp2.cv[[y]] = gp.sd / gPred 339 | ##gp2.cv[[y]] = sqrt( exp(gp.sd)^2 - 1) 340 | gp2.cv[[y]] = apply(log(rep1),1,sd) 341 | } 342 | halpha = (1-CIlevel)/2 343 | upres[which(as.character(yearRange)==y)] = quantile(idxSamp,1-halpha,na.rm=TRUE); 344 | lores[which(as.character(yearRange)==y)] = quantile(idxSamp,halpha,na.rm=TRUE); 345 | } 346 | } ## rof years 347 | list(res=res,m.pos=m.pos,m0=m0,lo=lores,up=upres,gp=gPred,ll=totll,pd=pd,gp2=gp2,gp2.cv=gp2.cv); 348 | }## end do.one 349 | noAges=length(ages); 350 | rr=parallel::mclapply(1:noAges,do.one.a,mc.cores=mc.cores); 351 | logl=0; 352 | for(a in 1:noAges){ 353 | resMat[,a]=rr[[a]]$res; 354 | zModels[[a]]=rr[[a]]$m0; 355 | pModels[[a]]=rr[[a]]$m.pos; 356 | loMat[,a]=rr[[a]]$lo; 357 | upMat[,a]=rr[[a]]$up; 358 | gPreds[[a]]=rr[[a]]$gp; 359 | logl=logl+rr[[a]]$ll 360 | gPreds2[[a]]=rr[[a]]$gp2 361 | gPreds2.CV[[a]]=rr[[a]]$gp2.cv 362 | allobs[[a]]=x[[2]]$Nage[,a] 363 | } 364 | getEdf<-function(m) sum(m$edf) 365 | totEdf=sum( unlist( lapply(zModels,getEdf))) + sum( unlist( lapply(pModels,getEdf))); 366 | idx.CV=(log(upMat)-log(loMat))/4 367 | rownames(resMat) <- rownames(loMat) <- rownames(upMat) <- rownames(idx.CV) <- yearRange 368 | colnames(resMat) <- colnames(loMat) <- colnames(upMat) <- colnames(idx.CV) <- ages 369 | out <- list(idx=resMat,idx.CV = idx.CV, zModels=zModels,pModels=pModels,lo=loMat,up=upMat,gPreds=gPreds,logLik=logl,edfs=totEdf,gPreds2=gPreds2,gPreds2.CV = gPreds2.CV, family=famVec, cutOff=cutOff, dataAges=dataAges, yearNum=yearNum, refGear=myGear, predfix = predfix, knotsP=knotsP, knotsZ=knotsZ, allobs=allobs,CIlevel=CIlevel); 370 | class(out) <- "surveyIdx" 371 | set.seed(314159265) ## reset seed here (in case multicore option is used) 372 | for(a in 1:noAges) resid[[a]] = residuals(out,a) 373 | out$residuals = resid 374 | out 375 | } 376 | 377 | 378 | ##' Re-compute standardized survey indices for an alternative grid from a previous fitted "surveyIdx" model. 379 | ##' 380 | ##' @title Re-compute standardized survey indices for an alternative grid from a previous fitted "surveyIdx" model. 381 | ##' @param x DATRASraw dataset 382 | ##' @param model object of class "surveyIdx" as created by "getSurveyIdx" 383 | ##' @param predD optional DATRASraw object, defaults to NULL. If not null this is used as grid. 384 | ##' @param myids haul.ids for grid 385 | ##' @param nBoot number of bootstrap samples used for calculating index confidence intervals 386 | ##' @param predfix optional named list of extra variables (besides Gear, HaulDur, Ship, and TimeShotHour), that should be fixed during prediction step (standardized) 387 | ##' @param mc.cores mc.cores number of cores for parallel processing 388 | ##' @param addTimeOfYear if TRUE, add predfix$timeOfYear to 'ctime' when standardizing (otherwise it is 1st of January). 389 | ##' @return An object of class "surveyIdx" 390 | ##' @importFrom MASS mvrnorm 391 | ##' @export 392 | redoSurveyIndex<-function(x,model,predD=NULL,myids,nBoot=1000,predfix=list(),mc.cores=1,addTimeOfYear=FALSE){ 393 | ages = as.numeric(colnames(model$idx)) 394 | dataAges <- model$dataAges 395 | famVec = model$family 396 | cutOff = model$cutOff 397 | 398 | yearNum=as.numeric(as.character(x$Year)) 399 | yearRange=min(yearNum):max(yearNum); 400 | 401 | gPreds=list() ##last data year's predictions 402 | gPreds2=list() ## all years predictions 403 | gPreds2.CV=list() 404 | predDc = predD 405 | 406 | myGear=model$refGear 407 | 408 | resMat=matrix(NA,nrow=length(yearRange),ncol=length(ages)); 409 | upMat=resMat; 410 | loMat=resMat; 411 | do.one.a<-function(a){ 412 | age = which(dataAges==ages[a]) 413 | ddd=x[[2]]; ddd$dum=1.0; 414 | ddd$A1=ddd$Nage[,age] 415 | m.pos = model$pModels[[a]] 416 | m0 = NULL 417 | if(!famVec[a] %in% c("Tweedie","negbin")) m0 = model$zModels[[a]] 418 | if(is.null(predD)) predD=subset(ddd,haul.id %in% myids); 419 | res=numeric(length(yearRange)); 420 | lores=res; 421 | upres=res; 422 | gp2=list() 423 | gp2.cv=list() 424 | do.one.y<-function(y){ 425 | 426 | cat("Doing year ",y,"\n") 427 | 428 | if(is.list(predDc) && !class(predDc)%in%c("data.frame","DATRASraw")) predD = predDc[[as.character(y)]] 429 | if(is.null(predD)) stop(paste("Year",y," not found in predD")) 430 | 431 | ## take care of years with all zeroes 432 | if(!any(ddd$A1[ddd$Year==y]>cutOff)){ 433 | return(list(res=0,upres=0,lores=0,gp2=NULL,gp2.cv=NULL)) 434 | } 435 | 436 | ## OBS: effects that should be removed should be included here 437 | predD$Year=y; predD$dum=0; 438 | predD$ctime=as.numeric(as.character(y)); 439 | predD$TimeShotHour=mean(ddd$TimeShotHour) 440 | predD$Ship=names(which.max(summary(ddd$Ship))) 441 | predD$timeOfYear=mean(ddd$timeOfYear); 442 | predD$HaulDur=30.0 443 | predD$Gear=myGear; 444 | if(!is.null(predfix)){ ##optional extra variables for standardization 445 | stopifnot(is.list(predfix)) 446 | for(n in names(predfix)){ 447 | predD[,n] = predfix[[n]] 448 | } 449 | } 450 | if("timeOfYear" %in% names(predfix) && addTimeOfYear){ 451 | predD$ctime = predD$ctime + predfix$timeOfYear 452 | } 453 | p.1 <- p.0 <- NULL 454 | try({ 455 | Xp.1=predict(m.pos,newdata=predD,type="lpmatrix"); 456 | OS.pos = numeric(nrow(predD)); 457 | terms.pos=terms(m.pos) 458 | if(!is.null(m.pos$offset)){ 459 | off.num.pos <- attr(terms.pos, "offset") 460 | for (i in off.num.pos) OS.pos <- OS.pos + eval(attr(terms.pos, 461 | "variables")[[i + 1]], predD) 462 | } 463 | p.1 =Xp.1%*%coef(m.pos)+OS.pos; 464 | if(!famVec[a] %in% c("Tweedie","negbin")){ 465 | Xp.0=predict(m0,newdata=predD,type="lpmatrix"); 466 | brp.0=coef(m0); 467 | OS0 = numeric(nrow(predD)) 468 | terms.0=terms(m0) 469 | if(!is.null(m0$offset)){ 470 | off.num.0 <- attr(terms.0, "offset") 471 | for (i in off.num.0) OS0 <- OS0 + eval(attr(terms.0, 472 | "variables")[[i + 1]], predD) 473 | } 474 | p.0 = m0$family$linkinv(Xp.0%*%brp.0+OS0); 475 | } 476 | }); 477 | ## take care of failing predictions 478 | if(!is.numeric(p.1) | (!famVec[a] %in% c("Tweedie","negbin") && !is.numeric(p.0))) { 479 | return(list(res=0,upres=0,lores=0,gp2=NULL,gp2.cv=NULL)) 480 | } 481 | sig2=m.pos$sig2; 482 | idx = NA 483 | if(famVec[a]=="Gamma") { idx <- sum(p.0*exp(p.1)); gPred=p.0*exp(p.1) } 484 | if(famVec[a]=="LogNormal") { idx <- sum(p.0*exp(p.1+sig2/2)); gPred=p.0*exp(p.1+sig2/2) } 485 | if(famVec[a] %in% c("Tweedie","negbin")) { idx <- sum(exp(p.1)); gPred=exp(p.1) } 486 | 487 | if(nBoot>10){ 488 | brp.1=mvrnorm(n=nBoot,coef(m.pos),m.pos$Vp); 489 | if(!famVec[a] %in% c("Tweedie","negbin")){ 490 | brp.0=mvrnorm(n=nBoot,coef(m0),m0$Vp); 491 | OS0 = matrix(0,nrow(predD),nBoot); 492 | terms.0=terms(m0) 493 | if(!is.null(m0$offset)){ 494 | off.num.0 <- attr(terms.0, "offset") 495 | 496 | for (i in off.num.0) OS0 <- OS0 + eval(attr(terms.0, 497 | "variables")[[i + 1]], predD) 498 | } 499 | rep0=m0$family$linkinv(Xp.0%*%t(brp.0)+OS0); 500 | } 501 | OS.pos = matrix(0,nrow(predD),nBoot); 502 | terms.pos=terms(m.pos) 503 | if(!is.null(m.pos$offset)){ 504 | off.num.pos <- attr(terms.pos, "offset") 505 | 506 | for (i in off.num.pos) OS.pos <- OS.pos + eval(attr(terms.pos, 507 | "variables")[[i + 1]], predD) 508 | } 509 | 510 | 511 | if(famVec[a]=="LogNormal"){ 512 | rep1=exp(Xp.1%*%t(brp.1)+sig2/2+OS.pos); 513 | } else { 514 | rep1=exp(Xp.1%*%t(brp.1)+OS.pos); 515 | } 516 | 517 | if(!famVec[a] %in% c("Tweedie","negbin")){ 518 | idxSamp = colSums(rep0*rep1); 519 | ##gp.sd = apply(rep0*rep1,1,sd) 520 | ##gp.cv = gp.sd / gPred 521 | gp.cv = apply(log(rep0*rep1),1,sd) 522 | } else { 523 | idxSamp = colSums(rep1); 524 | ##gp.sd = apply(rep1,1,sd) 525 | ##gp.cv = gp.sd / gPred 526 | gp.cv = apply(log(rep1),1,sd) 527 | } 528 | halpha = (1-model$CIlevel)/2 529 | return(list(res=idx,upres=quantile(idxSamp,1-halpha,na.rm=TRUE),lores=quantile(idxSamp,halpha,na.rm=TRUE),gp2=gPred,gp2.cv=gp.cv)) 530 | } 531 | } ## rof years 532 | yres = parallel::mclapply(as.character(yearRange),do.one.y,mc.cores=mc.cores) 533 | for(y in levels(ddd$Year)) { 534 | ii = which(as.character(yearRange)==y) 535 | res[ii] = yres[[ii]]$res 536 | upres[ii] = yres[[ii]]$upres 537 | lores[ii] = yres[[ii]]$lores 538 | gp2[[y]] = yres[[ii]]$gp2 539 | gp2.cv[[y]] = yres[[ii]]$gp2.cv 540 | } 541 | list(res=res,m.pos=m.pos,m0=m0,lo=lores,up=upres,gp=tail(gp2,1),gp2=gp2,gp2.cv=gp2.cv); 542 | }## end do.one 543 | noAges=length(ages); 544 | rr=lapply(1:noAges,do.one.a); 545 | logl=0; 546 | for(a in 1:noAges){ 547 | resMat[,a]=rr[[a]]$res; 548 | loMat[,a]=rr[[a]]$lo; 549 | upMat[,a]=rr[[a]]$up; 550 | gPreds[[a]]=rr[[a]]$gp; 551 | gPreds2[[a]]=rr[[a]]$gp2 552 | gPreds2.CV[[a]]=rr[[a]]$gp2.cv 553 | } 554 | idx.CV=(log(upMat)-log(loMat))/4 555 | rownames(resMat) <- rownames(loMat) <- rownames(upMat) <- rownames(idx.CV) <- yearRange 556 | colnames(resMat) <- colnames(loMat) <- colnames(upMat) <- colnames(idx.CV) <- ages 557 | out <- list(idx=resMat,idx.CV=idx.CV,zModels=model$zModels,pModels=model$pModels,lo=loMat,up=upMat,gPreds=gPreds,logLik=model$logLik,edfs=model$edfs,pData=model$pData,gPreds2=gPreds2,gPreds2.CV=gPreds2.CV, 558 | family=famVec, cutOff=cutOff, dataAges=dataAges, yearNum=yearNum, refGear=myGear, predfix = predfix, knotsP=model$knotsP, knotsZ=model$knotsZ); 559 | class(out) <- "surveyIdx" 560 | out 561 | } 562 | 563 | ##' @export 564 | print.surveyIdx <- function(x){ 565 | cat("Object of class 'surveyIdx'\n") 566 | cat("Family :", x$family,"\n") 567 | cat("Number of age groups: ",length(x$pModels),"\n") 568 | cat("Log-likelihood: ", x$logLik,"\n") 569 | cat("Effective degrees of freedom:",x$edfs,"\n") 570 | cat("CutOff value",x$cutOff,"\n") 571 | cat("===========================\n") 572 | print(x$idx) 573 | 574 | } 575 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------