diff --git a/DESCRIPTION b/DESCRIPTION index 2ecef3e8..ec24d2e7 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -44,30 +44,6 @@ Description: Fits hierarchical models of animal abundance and occurrence to data License: GPL (>=3) LazyLoad: yes LazyData: yes -Collate: 'classes.R' 'unmarkedEstimate.R' 'unmarkedFrame.R' - 'unmarkedFit.R' 'utils.R' 'getDesign.R' - 'fitted.R' 'residuals.R' 'update.R' 'simulate.R' 'nonparboot.R' 'getP.R' - 'ranef.R' 'posteriorSamples.R' - 'colext.R' 'distsamp.R' - 'multinomPois.R' 'occu.R' 'occuRN.R' 'occuMulti.R' 'pcount.R' 'gmultmix.R' - 'pcountOpen.R' 'gdistsamp.R' 'unmarkedFitList.R' 'unmarkedLinComb.R' - 'parboot.R' 'occuFP.R' 'gpcount.R' 'occuPEN.R' 'pcount.spHDS.R' - 'occuMS.R' 'occuTTD.R' 'distsampOpen.R' 'multmixOpen.R' - 'unmarkedCrossVal.R' 'piFun.R' 'vif.R' 'makePiFun.R' - 'nmixTTD.R' - 'gdistremoval.R' - 'plotEffects.R' - 'mixedModelTools.R' - 'power.R' - 'predict.R' - 'IDS.R' - 'goccu.R' - 'occuCOP.R' - 'occuComm.R' - 'removed_functions.R' - 'square_brackets.R' - 'RcppExports.R' - 'zzz.R' LinkingTo: Rcpp, RcppArmadillo, diff --git a/R/All_classes.R b/R/All_classes.R new file mode 100644 index 00000000..dae86cde --- /dev/null +++ b/R/All_classes.R @@ -0,0 +1,534 @@ +# This file starts with All_ so it is loaded first by R + +# Class unions----------------------------------------------------------------- +setClassUnion("optionalDataFrame", c("data.frame","NULL")) +setClassUnion("optionalMatrix", c("matrix","NULL")) +setClassUnion("optionalNumeric", c("numeric","NULL")) +setClassUnion("optionalCharacter", c("character","NULL")) +setClassUnion("optionalList", c("list","NULL")) +setClassUnion("numericOrLogical", c("numeric", "logical")) +setClassUnion("matrixOrVector", c("matrix","numeric")) + +# unmarkedFrame classes-------------------------------------------------------- + +# Basic unmarkedFrame +validunmarkedFrame <- function(object) { + errors <- character(0) + M <- nrow(object@y) + J <- ncol(object@y) + if(!is.null(object@siteCovs)) + if(nrow(object@siteCovs) != M) + errors <- c(errors, + "siteCovData does not have same size number of sites as y.") + if(!is.null(obsCovs(object)) & !is.null(obsNum(object))) + if(nrow(object@obsCovs) != M*obsNum(object)) + errors <- c(errors, "obsCovData does not have M*obsNum rows.") + if(length(errors) == 0) + TRUE + else + errors +} + +setClass("unmarkedFrame", + representation(y = "matrix", + obsCovs = "optionalDataFrame", + siteCovs = "optionalDataFrame", + obsToY = "optionalMatrix"), + validity = validunmarkedFrame) + +### Single-season models ### + +# Count-based occupancy +setClass("unmarkedFrameOccuCOP", + representation(L = "matrix"), + contains = "unmarkedFrame", + validity = function(object) { + errors <- character(0) + M <- nrow(object@y) + J <- ncol(object@y) + y_integers = sapply(object@y, check.integer, na.ignore = T) + if (!all(y_integers)) { + errors <- c(errors, + paste( + "Count detection should be integers. Non-integer values:", + paste(object@y[which(!y_integers)], collapse = ', ') + )) + } + if (!all(all(dim(object@L) == dim(object@y)))){ + errors <- c( errors, paste( + "L should be a matrix of the same dimension as y, with M =", M, + "rows (sites) and J =", J, "columns (sampling occasions)." + ))} + if (length(errors) == 0) TRUE + else errors + } +) + +# Distance sampling +setClass("unmarkedFrameDS", + representation( + dist.breaks = "numeric", + tlength = "numeric", + survey = "character", + unitsIn = "character"), + contains = "unmarkedFrame", + validity = function(object) { + errors <- character(0) + J <- numY(object) + db <- object@dist.breaks + if(J != length(db) - 1) + errors <- c(errors, "ncol(y) must equal length(dist.breaks)-1") + if(db[1] != 0) + errors <- c(errors, "dist.breaks[1] must equal 0") + if(!is.null(obsCovs(object))) + "obsCovs cannot be used with distsamp" + if(length(errors) == 0) TRUE + else errors + }) + +# Multinomial mixture model +setClass("unmarkedFrameMPois", + representation(samplingMethod = "character", piFun = "character"), + contains = "unmarkedFrame" +) + +# Single-season occupancy model +setClass("unmarkedFrameOccu", contains = "unmarkedFrame") + +# Community occupancy model +setClass("unmarkedFrameOccuComm", + representation(ylist = "list", speciesCovs="optionalList"), + contains = "unmarkedFrame" +) + +# False-positive occupancy model +setClass("unmarkedFrameOccuFP", + representation(type = "numeric"), + contains = "unmarkedFrame" +) + +# Rota multiple species occupancy model +setClass("unmarkedFrameOccuMulti", + representation(ylist = "list", fDesign = "matrix"), + contains = "unmarkedFrame", + validity = function(object) { + errors <- character(0) + M <- nrow(object@y) + J <- ncol(object@y) + Ms <- sapply(object@ylist,nrow) + Js <- sapply(object@ylist,ncol) + if(length(unique(Ms)) != 1) + errors <- c(errors, "All species must have same number of sites") + if(length(unique(Js)) != 1) + errors <- c(errors, "All species must have same number of observations") + if(!is.null(object@siteCovs)) + if(nrow(object@siteCovs) != M) + errors <- c(errors, + "siteCovData does not have same size number of sites as y.") + if(!is.null(obsCovs(object)) & !is.null(obsNum(object))) + if(nrow(object@obsCovs) != M*obsNum(object)) + errors <- c(errors, "obsCovData does not have M*obsNum rows.") + if(length(errors) == 0) + TRUE + else + errors + } +) + +# N-mixture model +setClass("unmarkedFramePCount", contains = "unmarkedFrame") + + +### Multi-season models ### + +# Basic multi-season class used by dynamic occupancy model +setClass("unmarkedMultFrame", + representation(numPrimary = "numeric", yearlySiteCovs = "optionalDataFrame"), + contains="unmarkedFrame" +) + +# Multi-state occupancy +setClass('unmarkedFrameOccuMS', + representation(numStates = "numeric", phiOrder = "list"), + contains = "unmarkedMultFrame" +) + +# Time-to-detection occupancy +setClass("unmarkedFrameOccuTTD", + representation( + surveyLength = "matrix"), + contains = "unmarkedMultFrame") + + +### Temporary emigration (TE) models + +# Basic class for temporary emigration data +setClass("unmarkedFrameG3", contains = "unmarkedMultFrame") + +# TE multinomial mixture +setClass("unmarkedFrameGMM", + representation(piFun = "character", samplingMethod = "character"), + contains = "unmarkedFrameG3" +) + +# TE distance sampling +setClass("unmarkedFrameGDS", + representation(dist.breaks = "numeric", tlength = "numeric", + survey = "character", unitsIn = "character"), + contains = "unmarkedFrameG3" +) + +# TE N-mixture +setClass("unmarkedFrameGPC", contains = "unmarkedFrameG3") + +# TE occupancy +setClass("unmarkedFrameGOccu", contains = "unmarkedFrameG3") + +# TE distance-removal model +setClass("unmarkedFrameGDR", + representation( + yDistance = "matrix", + yRemoval = "matrix", + survey = "character", + dist.breaks = "numeric", + unitsIn = "character", + period.lengths = "numeric" + ), + contains="unmarkedMultFrame" +) + + +### Open population count models ### + +# Basic class for all open pop models +setClass("unmarkedFrameDailMadsen", + representation(primaryPeriod = "matrix"), + contains = "unmarkedMultFrame" +) + +# Open-pop distance sampling +setClass("unmarkedFrameDSO", + representation(dist.breaks = "numeric", tlength = "numeric", + survey = "character", unitsIn = "character"), + contains = "unmarkedFrameDailMadsen" +) + +# Open-pop multinomial mixture +setClass("unmarkedFrameMMO", + representation(piFun = "character", samplingMethod = "character"), + contains = "unmarkedFrameDailMadsen" +) + +# Open-pop N-mixture +setClass("unmarkedFramePCO", contains = "unmarkedFrameDailMadsen") + + +# unmarkedEstimate class------------------------------------------------------- + +# Stores parameter estimates for a submodel (e.g. state, det) +setClass("unmarkedEstimate", + representation( + name = "character", + short.name = "character", + estimates = "numeric", + covMat = "matrix", + fixed = "numeric", + covMatBS = "optionalMatrix", + invlink = "character", + invlinkGrad = "character", + randomVarInfo= "list"), + validity = function(object){ + errors <- character(0) + if(nrow(object@covMat) != length(object@estimates)) { + errors <- c(errors, + "Size of covMat does not match length of estimates.") + } + if(length(errors) > 0) + errors + else + TRUE + } +) + +# List of unmarkedEstimates +setClass("unmarkedEstimateList", + representation(estimates = "list"), + validity = function(object) { + errors <- character(0) + for(est in object@estimates) { + if(!is(est, "unmarkedEstimate")) { + errors <- c("At least one element of unmarkedEstimateList is not an unmarkedEstimate.") + break + } + } + if(length(errors) == 0) { + return(TRUE) + } else { + return(errors) + } + } +) + +# unmarkedFit classes---------------------------------------------------------- + +# Basic class +setClass("unmarkedFit", + representation(fitType = "character", + call = "call", + formula = "formula", + data = "unmarkedFrame", + sitesRemoved = "numeric", # vector of indices of removed sites + estimates = "unmarkedEstimateList", + AIC = "numeric", + opt = "list", + negLogLike = "numeric", + nllFun = "function", + bootstrapSamples = "optionalList", + covMatBS = "optionalMatrix", # list of bootstrap sample fits + TMB = "optionalList") #TMB output object +) + +### Single-season model types ### + +# Distance sampling +setClass("unmarkedFitDS", + representation(keyfun = "character", unitsOut = "character", output = "character"), + contains = "unmarkedFit" +) + +# Multinomial mixture model +setClass("unmarkedFitMPois", contains = "unmarkedFit") + +# N-mixture TTD model +setClass("unmarkedFitNmixTTD", + representation(stateformula = "formula", detformula = "formula", K = "numeric"), + contains = "unmarkedFit" +) + +# Basic occupancy model +setClass("unmarkedFitOccu", + representation(knownOcc = "logical"), + contains = "unmarkedFit" +) + +# Community occupancy model +setClass("unmarkedFitOccuComm", contains="unmarkedFitOccu") + +# Count-based occupancy model +setClass("unmarkedFitOccuCOP", + representation(removed_obs = "matrix", formlist = "list"), + contains = "unmarkedFit" +) + +# False positive occupancy +setClass("unmarkedFitOccuFP", + representation(knownOcc = "logical", detformula = "formula", FPformula = "formula", + Bformula = "formula", stateformula = "formula", type = "numeric"), + contains = "unmarkedFit" +) + +# Penalized likelihood occupancy model +setClass("unmarkedFitOccuPEN", + representation(knownOcc = "logical", pen.type = "character", lambda = "numeric"), + contains = "unmarkedFit" +) + +setClass("unmarkedFitOccuPEN_CV", + representation(knownOcc = "logical", pen.type = "character", lambdaVec = "numeric", + k = "numeric", foldAssignments = "numeric", lambdaScores = "numeric", + chosenLambda = "numeric"), + contains = "unmarkedFit" +) + +# Rota multispecies occupancy model +setClass("unmarkedFitOccuMulti", + representation(detformulas = "character", stateformulas = "character"), + contains = "unmarkedFit" +) + +# Royle-Nichols occupancy model +setClass("unmarkedFitOccuRN", + representation(K = "numeric"), + contains = "unmarkedFit" +) + +# N-mixture model +setClass("unmarkedFitPCount", + representation(K = "numeric", mixture = "character"), + contains = "unmarkedFit" +) + + +### Temporary emigration (TE) model types + +# TE occupancy +setClass("unmarkedFitGOccu", + representation(formlist = "list"), + contains = "unmarkedFit" +) + +# TE multinomial mixture +setClass("unmarkedFitGMM", + representation(formlist = "list", mixture = "character", K = "numeric"), + contains = "unmarkedFit" +) + +# TE distance sampling +setClass("unmarkedFitGDS", + representation(keyfun = "character", unitsOut = "character", output = "character"), + contains = "unmarkedFitGMM" +) + +# TE distance-removal model +setClass("unmarkedFitGDR", contains = "unmarkedFitGDS") + +# TE point count model +setClass("unmarkedFitGPC", contains = "unmarkedFitGMM") + + +### Open-population models ### + +# Dynamic occupancy model +setClass("unmarkedFitColExt", + representation(phi = "matrix", psiformula = "formula", gamformula = "formula", + epsformula = "formula", detformula = "formula", projected = "array", + projected.mean = "matrix", smoothed = "array", smoothed.mean = "matrix", + projected.mean.bsse = "optionalMatrix", smoothed.mean.bsse = "optionalMatrix"), + contains = "unmarkedFit" +) + +# Multi-state occupancy model +setClass("unmarkedFitOccuMS", + representation(detformulas = "character", psiformulas = "character", + phiformulas = "character", parameterization = "character"), + contains = "unmarkedFit" +) + +# Time-to-detection occupancy model +setClass("unmarkedFitOccuTTD", + representation(psiformula = "formula", gamformula = "formula", + epsformula = "formula", detformula = "formula"), + contains = "unmarkedFit" +) + +# This class is not used directly, just used as a base for for PCO, MMO, DSO +setClass("unmarkedFitDailMadsen", + representation(K = "numeric", mixture = "character", formlist = "list", + dynamics = "character", immigration = "logical", fix = "character"), + contains = "unmarkedFit" +) + +# Open-pop distance sampling +setClass("unmarkedFitDSO", + representation(keyfun = "character", unitsOut = "character", output = "character"), + contains = "unmarkedFitDailMadsen" +) + +# Open-pop multinomial mixture +setClass("unmarkedFitMMO", contains = "unmarkedFitDailMadsen") + +# Open-pop N-mixture +setClass("unmarkedFitPCO", contains = "unmarkedFitDailMadsen") + + +### Integrated models ### + +setClassUnion("unmarkedFrameOrNULL", members=c("unmarkedFrame", "NULL")) +setClass("unmarkedFitIDS", + representation( + formlist = "list", + keyfun = "character", + K = "numeric", + dataPC = "unmarkedFrameOrNULL", + dataOC = "unmarkedFrameOrNULL", + maxDist = "list", + surveyDurations = "list", + unitsOut = "character"), + contains = "unmarkedFit") + + +# Other output objects--------------------------------------------------------- + +# Linear combinations object +setClass("unmarkedLinComb", + representation(parentEstimate = "unmarkedEstimate", estimate = "numeric", + covMat = "matrix", covMatBS = "optionalMatrix", coefficients = "matrix") +) + +# Back-transformed linear comb +setClass("unmarkedBackTrans", + representation(parentLinComb = "unmarkedLinComb", estimate = "numeric", + covMat = "matrix", covMatBS = "optionalMatrix") +) + +# Union of linear comb and back transform object types +setClassUnion("linCombOrBackTrans", c("unmarkedLinComb", "unmarkedBackTrans")) + +# Profile likelihood output +setClass("profile", representation(prof = "matrix")) + +# ranef output (posterior of latent variables) +setClass("unmarkedRanef", representation(post = "array")) + +# Posterior samples of latent variable +setClass("unmarkedPostSamples", + representation(numSites="numeric", numPrimary="numeric", + nsims="numeric", samples="array") +) + +# List of unmarkedFit objects +setClass("unmarkedFitList", + representation(fits = "list"), + validity = function(object) { + fl <- object@fits + umf1 <- getData(fl[[1]]) + y1 <- fl_getY(fl[[1]]) + dataTest <- sapply(fl, function(x) isTRUE(all.equal(umf1, getData(x)))) + yTest <- sapply(fl, function(x) isTRUE(all.equal(y1, fl_getY(x)))) + if(!all(dataTest)) { + stop("Data are not the same among models. Make sure you use the same unmarkedFrame object for all models.") + } else if(!all(yTest)) { + stop("Data are not the same among models due to missing covariate values. Consider removing NAs before analysis.") + } + TRUE + } +) + +# Output of model selection (modSel function) +setClass("unmarkedModSel", + representation(Full = "data.frame", Names = "matrix") +) + +# Parametric bootstrap output +setClass("parboot", + representation(call = "call", t0 = "numeric", t.star = "matrix") +) + +# Cross validation output +setClass("unmarkedCrossVal", + representation(stats = "data.frame", summary = "data.frame", method = "character", + folds = "numeric", holdoutPct = "numeric"), + validity=function(object){ + errors <- character(0) + hp <- object@holdoutPct + if(hp<0|hp>1){ + errors <- c(errors,"holdoutPct must be between 0 and 1") + } + } +) + +# List of cross validation objects +setClass("unmarkedCrossValList", + representation(stats_list="list", method = "character", folds="numeric", + holdoutPct="numeric", sort="character") +) + +# Power analysis output +setClass("unmarkedPower", + representation(call="call", data="unmarkedFrame", M="numeric", + J="numeric", T="numeric", coefs="list", estimates="list", + alpha="numeric", nulls="list") +) + +# List of power analysis outputs +setClass("unmarkedPowerList", representation(powerAnalyses="list")) diff --git a/R/All_generics.R b/R/All_generics.R new file mode 100644 index 00000000..1ae2981f --- /dev/null +++ b/R/All_generics.R @@ -0,0 +1,337 @@ +# This filename starts with All_ so it is loaded by R first + +# Converting existing R functions to generics---------------------------------- +setGeneric("coef") +setGeneric("confint") +setGeneric("fitted") +setGeneric("head") +setGeneric("hist") +setGeneric("logLik") +setGeneric("plot") +setGeneric("predict") +setGeneric("profile") +setGeneric("residuals") +setGeneric("simulate") +setGeneric("summary") +setGeneric("update") +setGeneric("vcov") + + +# Generics for exported unmarked-specific functions---------------------------- + +# Transform an object to its natural scale. +setGeneric("backTransform", function(obj, ...) { + standardGeneric("backTransform") +}) + +# Best unbiased predictors +# Method in ranef.R +setGeneric("bup", function(object, stat=c("mean", "mode"), ...){ + standardGeneric("bup") +}) + +# Cross validation for unmarkedFit +# Methods in unmarkedCrossVal.R +setGeneric("crossVal", function(object, + method=c("Kfold","holdout","leaveOneOut"), folds=10, holdoutPct=0.25, + statistic=RMSE_MAE, ...) standardGeneric("crossVal")) + +# Get availability probability matrix, sites x primary periods +# Only implemented for unmarkedFitIDS, in IDS.R +setGeneric("getAvail", function(object, ...) standardGeneric("getAvail")) + +# Get false positive detection probability from unmarkedFitOccuFP object +# Method in unmarkedFit.R +setGeneric("getB", function(object, ...) standardGeneric("getB")) + +# Get data (unmarkedFrame) from an unmarkedFit object +# Method in unmarkedFit.R +setGeneric("getData", function(object) standardGeneric("getData")) + +# Get false positive detection probability from unmarkedFitOccuFP object +# Method in unmarkedFit.R +setGeneric("getFP", function(object, ...) standardGeneric("getFP")) + +# Get observation duration +# Only used by occuCOP +# Method in occuCOP.R +setGeneric("getL", function(object) standardGeneric("getL")) + +# Get a matrix of detection probabilities for each observation +# Method for unmarkedFit in getP.R +setGeneric("getP", function(object, ...) standardGeneric("getP")) + +# Get observation data from unmarkedFrame +# Method in unmarkedFrame.R +setGeneric("getY", function(object) standardGeneric("getY")) + +# Extract hessian matrix +setGeneric("hessian", function(object) standardGeneric("hessian")) + +# Compute linear combinations of parameters. +setGeneric("linearComb", function(obj, coefficients, ...) { + standardGeneric("linearComb") +}) + +# Likelihood ratio test +setGeneric("LRT", function(m1, m2) standardGeneric("LRT")) + +# Model selection +# Method in unmarkedFitList.R +setGeneric("modSel", function(object, ...) standardGeneric("modSel")) + +# Nonparametric bootstrap +# Method in nonparboot.R +setGeneric("nonparboot", function(object, ...) standardGeneric("nonparboot")) + +# Get number of sites from an unmarkedFrame +# Method in unmarkedFrame.R +setGeneric("numSites", function(object) standardGeneric("numSites")) + +# Get number of observations from an unmarkedFrame +# Method in unmarkedFrame.R +setGeneric("numY", function(object) standardGeneric("numY")) + +# Extract observation covs from an unmarkedFrame +# Method in unmarkedFrame.R +setGeneric("obsCovs", function(object,...) standardGeneric("obsCovs")) + +# Assign value to obsCovs slot +# Method in unmarkedFrame.R +setGeneric("obsCovs<-", function(object, value) standardGeneric("obsCovs<-")) + +# Get number of independent observations from an unmarkedFrame +# Method in unmarkedFrame.R +setGeneric("obsNum", function(object) standardGeneric("obsNum")) + +# Extract obsToY matrix +# Method in unmarkedFrame.R +setGeneric("obsToY", function(object) standardGeneric("obsToY")) + +# Assign value to obsToY slot +# Method in unmarkedFrame.R +setGeneric("obsToY<-", function(object, value) standardGeneric("obsToY<-")) + +# Optimize penalize likelihood penalty +# Only used by occuMulti +# Method in occuMulti.R +setGeneric("optimizePenalty", + function(object, penalties=c(0,2^seq(-4,4)), k = 5, boot = 30, ...){ + standardGeneric("optimizePenalty") +}) + +# Parametric bootstrap +# Methods in parboot.R +setGeneric("parboot", function(object, ...) standardGeneric("parboot")) + +# Plot covariate effects +# Method in plotEffects.R +setGeneric("plotEffects", function(object, ...) standardGeneric("plotEffects")) + +# Get data for plotting effects +# Method in plotEffects.R +setGeneric("plotEffectsData", function(object, ...) standardGeneric("plotEffectsData")) + +# Get posterior samples from ranef +# Method in posteriorSamples.R +setGeneric("posteriorSamples", function(object, nsims, ...){ + standardGeneric("posteriorSamples") +}) + +# Power analysis +# Method in powerAnalysis.R +setGeneric("powerAnalysis", function(object, ...) standardGeneric("powerAnalysis")) + +# Get projected values from an unmarkedFitColExt object +# Method in unmarkedFit.R +setGeneric("projected", function(object, mean=TRUE) standardGeneric("projected")) + +# Get data frame of random effect estimates +# Method in mixedModelTools.R +setGeneric("randomTerms", function(object, ...) standardGeneric("randomTerms")) + +# Get posteriors of latent effects +# Method in ranef.R +setGeneric("ranef", function(object, ...) standardGeneric("ranef")) + +# Get richness +# Only used by occuComm +# Method in occuComm.R +setGeneric("richness", function(object, ...) standardGeneric("richness")) + +# Get sample size (number of sites after dropping sites with missing values) +# Method in unmarkedFit.R +setGeneric("sampleSize", function(object) standardGeneric("sampleSize")) + +# Get standard error values +setGeneric("SE", function(obj, ...) standardGeneric("SE")) + +# Extract site covariates from an unmarkedFrame +# Method in unmarkedFrame.R +setGeneric("siteCovs", function(object,...) standardGeneric("siteCovs")) + +# Assign value to siteCovs slot +# Method in unmarkedFrame.R +setGeneric("siteCovs<-", function(object, value) standardGeneric("siteCovs<-")) + +# Get smoothed values from an unmarkedFitColExt object +# Method in unmarkedFit.R +setGeneric("smoothed", function(object, mean=TRUE) standardGeneric("smoothed")) + +# Sum of squared errors statistic +# Methods in utils.R +setGeneric("SSE", function(fit, ...) standardGeneric("SSE")) + +# Create list of unmarkedPower objects +# Method in power.R +setGeneric("unmarkedPowerList", function(object, ...){ + standardGeneric("unmarkedPowerList") +}) + +# Extract yearly site covs (primary period covs) from an unmarkedFrame +# Method in unmarkedFrame.R +setGeneric("yearlySiteCovs", function(object,...){ + standardGeneric("yearlySiteCovs") +}) + +# Assign value to yearlySiteCovs slot +# Method in unmarkedFrame.R +setGeneric("yearlySiteCovs<-", + function(object, value) standardGeneric("yearlySiteCovs<-")) + +# Generics for internal unmarked-specific functions---------------------------- + +# Methods in predict.R +setGeneric("check_predict_arguments", function(object, ...){ + standardGeneric("check_predict_arguments") +}) + +# Internal method for fitted +# Methods for different unmarkedFit types in fitted.R +setGeneric("fitted_internal", function(object){ + standardGeneric("fitted_internal") +}) + +# Get y matrix from unmarkedFit for fitList +# Methods in unmarkedFitList.R +setGeneric("fl_getY", function(fit, ...) standardGeneric("fl_getY")) + +# Create design matrices and handle missing values +# Methods for various unmarkedFrame types in getDesign.R +setGeneric("getDesign", function(umf, ...) standardGeneric("getDesign")) + +# Get fitting function associated with an unmarkedFrame type +# Methods in simulate.R +setGeneric("get_fitting_function", function(object, model, ...){ + standardGeneric("get_fitting_function") +}) + +# Get correct formula for predict based on type +# Methods in predict.R +setGeneric("get_formula", function(object, type, ...){ + standardGeneric("get_formula") +}) + +# Internal method for getP +# Methods for different unmarkedFit types in getP.R +setGeneric("getP_internal", function(object) standardGeneric("getP_internal")) + +# Internal method for getY +# Extracts observation data from an unmarkedFit object +# Methods for various unmarkedFit types in unmarkedFit.R +setGeneric("getY_internal", function(object) standardGeneric("getY_internal")) + +# Get data frame of covariates for predict +# Methods in predict.R +setGeneric("get_orig_data", function(object, type, ...){ + standardGeneric("get_orig_data") +}) + +# Get estimates from unmarkedEstimateList +# Method in unmarkedEstimate.R +setGeneric("estimates", function(object) standardGeneric("estimates")) + +# Check if object has random effect +# Methods in mixedModelTools.R +setGeneric("has_random", function(object) standardGeneric("has_random")) + +# Get maximum likelihood estimate from an unmarkedFit object +# Method in unmarkedFit.R +setGeneric("mle", function(object) standardGeneric("mle")) + +# Get NLL function from an unmarkedFit object +# Method in unmarkedFit.R +setGeneric("nllFun", function(object) standardGeneric("nllFun")) + +# Internal nonparboot method for specific unmarkedFit types +# Methods in nonparboot.R +setGeneric("nonparboot_internal", function(object, B, keepOldSamples){ + standardGeneric("nonparboot_internal") +}) + +# Internal nonparboot update method for specific unmarkedFit types +# Methods in nonparboot.R +setGeneric("nonparboot_update", function(object, data){ + standardGeneric("nonparboot_update") +}) + +# Run prediction calculations in chunks for speed +# Method in predict.R +setGeneric("predict_by_chunk", function(object, ...){ + standardGeneric("predict_by_chunk") +}) + +# Internal method for predict +# Methods for specific unmarkedFit types in predict.R +setGeneric("predict_internal", function(object, ...) standardGeneric("predict_internal")) + +# Methods in predict.R +setGeneric("predict_inputs_from_umf", function(object, ...){ + standardGeneric("predict_inputs_from_umf") +}) + +# Internal method for ranef +# Methods for specific unmarkedFit types in ranef.R +setGeneric("ranef_internal", function(object, ...) standardGeneric("ranef_internal")) + +# Rebuild code used to call model +# Methods in update.R +setGeneric("rebuild_call", function(object) standardGeneric("rebuild_call")) + +# Internal method for residuals +# Methods for specific unmarkedFit types in residuals.R +setGeneric("residuals_internal", function(object){ + standardGeneric("residuals_internal") +}) + +# Replace y-matrix in unmarkedFrame, used by parboot +# Methods in parboot.R +setGeneric("replaceY", function(object, newY, replNA = TRUE, ...){ + standardGeneric("replaceY") +}) + +# Create residual plot from an unmarkedFit object +# Method in unmarkedFit.R +setGeneric("residual_plot", function(x, ...) standardGeneric("residual_plot")) + +# Internal method for simulate +# Methods for specific unmarkedFit types in simulate.R +setGeneric("simulate_internal", function(object, nsim) standardGeneric("simulate_internal")) + +# Subset unmarkedFrame observations +# Method in square_brackets.R +setGeneric("subset_obs", function(umf, j) standardGeneric("subset_obs")) + +# Subset unmarkedFrame sites +# Method in square_brackets.R +setGeneric("subset_sites", function(umf, i) standardGeneric("subset_sites")) + +# Internal summary method +# Methods for different unmarkedFit types in unmarkedFit.R +setGeneric("summary_internal", function(object) standardGeneric("summary_internal")) + +# Set all observation data values to 0 +# Method in simulate.R +setGeneric("y_to_zeros", function(object, ...){ + standardGeneric("y_to_zeros") +}) diff --git a/R/IDS.R b/R/IDS.R index a0cd101b..094770de 100644 --- a/R/IDS.R +++ b/R/IDS.R @@ -1,17 +1,3 @@ -setClassUnion("unmarkedFrameOrNULL", members=c("unmarkedFrame", "NULL")) - -setClass("unmarkedFitIDS", - representation( - formlist = "list", - keyfun = "character", - K = "numeric", - dataPC = "unmarkedFrameOrNULL", - dataOC = "unmarkedFrameOrNULL", - maxDist = "list", - surveyDurations = "list", - unitsOut = "character"), - contains = "unmarkedFit") - get_ds_info <- function(db){ J <- length(db) - 1 a <- u <- rep(NA, J) @@ -448,9 +434,6 @@ setMethod("predict_internal", "unmarkedFitIDS", function(object, type, newdata, out }) -# Get availability probability -setGeneric("getAvail", function(object, ...) standardGeneric("getAvail")) - # Get availability for each data type and site as a probability setMethod("getAvail", "unmarkedFitIDS", function(object, ...){ stopifnot("phi" %in% names(object)) diff --git a/R/classes.R b/R/classes.R deleted file mode 100644 index cd4caaf9..00000000 --- a/R/classes.R +++ /dev/null @@ -1,61 +0,0 @@ -setClassUnion("optionalDataFrame", c("data.frame","NULL")) - - -setClassUnion("optionalMatrix", c("matrix","NULL")) - - -setClassUnion("optionalNumeric", c("numeric","NULL")) - - -setClassUnion("optionalCharacter", c("character","NULL")) - -setClassUnion("optionalList", c("list","NULL")) - -# Compute standard error of an object. -setGeneric("SE", - def = function(obj, ...) { - standardGeneric("SE") - }) - -setGeneric("plot") -setGeneric("predict") -setGeneric("vcov") -setGeneric("coef") -setGeneric("summary") -setGeneric("update") -setGeneric("confint") -setGeneric("profile") -setGeneric("head") -setGeneric("fitted") -setGeneric("simulate") -setGeneric("residuals") -setGeneric("hist") -setGeneric("logLik") - - -# Compute linear combinations of parameters. -setGeneric("linearComb", - function(obj, coefficients, ...) { - standardGeneric("linearComb") - }) - -# Transform an object to it's natural scale. -setGeneric("backTransform", - function(obj, ...) { - standardGeneric("backTransform") - }) - - -setGeneric("hessian", function(object) standardGeneric("hessian")) - - -setGeneric("LRT", function(m1, m2) standardGeneric("LRT")) - - -# TODO: make parent class unmarkedEstimate -# TODO: make binomial detection child class -# TODO: make binomial occ child class -# TODO: make poisson abundance child class -# TODO: make show method for each of these classes. -# TODO: make unmarkedFit show that calls the respective children. -# TODO: separate unmarkedFit class for each model type?... would contain different estimate types diff --git a/R/fitted.R b/R/fitted.R index c3a994a5..b485c079 100644 --- a/R/fitted.R +++ b/R/fitted.R @@ -1,15 +1,15 @@ +# fitted creates a matrix of fitted values, one per observation +# So if the observed data are MxJ the result will be an MxJ matrix of fitted +# values, which are usually calculated as something like +# state parameter * detection parameter + # Method for all fit types, exported +# This method applies to all unmarkedFit types, then internally +# calls a specific method for each unmarkedFit type (minimizes documentation) setMethod("fitted", "unmarkedFit", function(object, ...){ fitted_internal(object) }) - -# Internal method for specific fit type, not exported -setGeneric("fitted_internal", function(object){ - standardGeneric("fitted_internal") -}) - - setMethod("fitted_internal", "unmarkedFit", function(object){ state <- predict(object, type = "state", level=NULL, na.rm=FALSE)$Predicted p <- getP(object, na.rm = FALSE) # P(detection | presence) diff --git a/R/gdistremoval.R b/R/gdistremoval.R index ba6a6926..e26cca6a 100644 --- a/R/gdistremoval.R +++ b/R/gdistremoval.R @@ -54,8 +54,6 @@ setAs("unmarkedFrameGDR", "data.frame", function(from){ data.frame(yDistance, yRemoval, out) }) -setClass("unmarkedFitGDR", contains = "unmarkedFitGDS") - gdistremoval <- function(lambdaformula=~1, phiformula=~1, removalformula=~1, distanceformula=~1, data, keyfun=c("halfnorm", "exp", "hazard", "uniform"), output=c("abund", "density"), unitsOut=c("ha", "kmsq"), mixture=c('P', 'NB', 'ZIP'), diff --git a/R/getDesign.R b/R/getDesign.R index 811bb09c..2252c485 100644 --- a/R/getDesign.R +++ b/R/getDesign.R @@ -1,7 +1,6 @@ # The getDesign function creates design matrices and handles missing values # Many unmarked fitting functions have bespoke getDesign methods # Some methods do other things like creating indices, etc. -setGeneric("getDesign", function(umf, ...) standardGeneric("getDesign")) # generic method for unmarkedFrame # used by distsamp, multinomPois, occu, occuPEN, occuRN, pcount, pcount.spHDS, IDS diff --git a/R/getP.R b/R/getP.R index 1d132b15..184f3bf4 100644 --- a/R/getP.R +++ b/R/getP.R @@ -1,13 +1,14 @@ -setGeneric("getP", function(object, ...) standardGeneric("getP")) +# getP creates a matrix of estimated detection probabilities corresponding +# to the observed data. For example if the data are MxJ detection/non-detection, +# the result will be an MxJ matrix of detection probabilities. # Exported method +# This method applies to all unmarkedFit types, then internally +# calls a specific method for each unmarkedFit type (minimizes documentation) setMethod("getP", "unmarkedFit", function(object, ...){ getP_internal(object) }) -# Internal method -setGeneric("getP_internal", function(object) standardGeneric("getP_internal")) - setMethod("getP_internal", "unmarkedFit", function(object){ M <- numSites(object@data) J <- obsNum(object@data) diff --git a/R/goccu.R b/R/goccu.R index 399c5d2a..9db8eead 100644 --- a/R/goccu.R +++ b/R/goccu.R @@ -1,10 +1,3 @@ -setClass("unmarkedFitGOccu", - representation( - formlist = "list"), - contains = "unmarkedFit") - -setClass("unmarkedFrameGOccu", contains = "unmarkedFrameG3") - unmarkedFrameGOccu <- function(y, siteCovs=NULL, obsCovs=NULL, numPrimary, yearlySiteCovs=NULL) { y[y > 1] <- 1 diff --git a/R/mixedModelTools.R b/R/mixedModelTools.R index 18b3e463..c6c6f5ed 100644 --- a/R/mixedModelTools.R +++ b/R/mixedModelTools.R @@ -271,9 +271,6 @@ setMethod("sigma", "unmarkedFit", function(object, type, level=0.95, ...){ }) -setGeneric("randomTerms", function(object, ...) standardGeneric("randomTerms")) - - setMethod("randomTerms", "unmarkedEstimate", function(object, level=0.95, addMean = FALSE, ...){ @@ -415,10 +412,6 @@ vcov_TMB <- function(object, type, fixedOnly){ } # Check if various objects have random effects -setGeneric("has_random", function(object){ - standardGeneric("has_random") -}) - setMethod("has_random", "unmarkedEstimate", function(object){ methods::.hasSlot(object, "randomVarInfo") && length(object@randomVarInfo) > 0 diff --git a/R/nonparboot.R b/R/nonparboot.R index 82e2e8a6..d2736f8d 100644 --- a/R/nonparboot.R +++ b/R/nonparboot.R @@ -1,5 +1,3 @@ -setGeneric("nonparboot", function(object, ...) standardGeneric("nonparboot")) - # Overall nonparboot method; this is the one exported setMethod("nonparboot", "unmarkedFit", function(object, B = 1, keepOldSamples = TRUE, ...){ bsType <- list(...)$bsType @@ -12,10 +10,6 @@ setMethod("nonparboot", "unmarkedFit", function(object, B = 1, keepOldSamples = }) # Fit-specific internal methods -setGeneric("nonparboot_internal", function(object, B, keepOldSamples){ - standardGeneric("nonparboot_internal") -}) - setMethod("nonparboot_internal", "unmarkedFit", function(object, B, keepOldSamples){ @@ -57,10 +51,6 @@ setMethod("nonparboot_internal", "unmarkedFit", }) # Fit-specific update methods (to handle occuPEN) -setGeneric("nonparboot_update", function(object, data){ - standardGeneric("nonparboot_update") -}) - setMethod("nonparboot_update", "unmarkedFit", function(object, data){ update(object, data = data, se = FALSE) }) diff --git a/R/occuCOP.R b/R/occuCOP.R index c57d0d42..288ad631 100644 --- a/R/occuCOP.R +++ b/R/occuCOP.R @@ -20,19 +20,9 @@ # lambda_ij = Detection rate of the observation j in site i # L_ij = Length/Duration of the observation j in site i -# CLASSES ---------------------------------------------------------------------- - -## unmarkedFitOccuCOP class ---- -setClass("unmarkedFitOccuCOP", - representation(removed_obs = "matrix", - formlist = "list"), - contains = "unmarkedFit") - - # Methods ---------------------------------------------------------------------- ## getL method ---- -setGeneric("getL", function(object) standardGeneric("getL")) setMethod("getL", "unmarkedFrameOccuCOP", function(object) { return(object@L) }) diff --git a/R/occuComm.R b/R/occuComm.R index f170ed2c..fe7a1d75 100644 --- a/R/occuComm.R +++ b/R/occuComm.R @@ -1,10 +1,3 @@ -setClass("unmarkedFrameOccuComm", - representation(ylist = "list", speciesCovs="optionalList"), - contains = "unmarkedFrame") - -setClass("unmarkedFitOccuComm", contains="unmarkedFitOccu") - - unmarkedFrameOccuComm <- function(y, siteCovs=NULL, obsCovs=NULL, speciesCovs=NULL){ if(is.array(y)){ @@ -323,7 +316,6 @@ setMethod("ranef_internal", "unmarkedFitOccuComm", function(object){ }) }) -setGeneric("richness", function(object, ...) standardGeneric("richness")) setMethod("richness", "unmarkedFitOccuComm", function(object, nsims=100, posterior=FALSE){ S <- length(object@data@ylist) diff --git a/R/occuMulti.R b/R/occuMulti.R index 8add92f3..9ce0ed67 100644 --- a/R/occuMulti.R +++ b/R/occuMulti.R @@ -179,9 +179,6 @@ occuMultiLogLik <- function(fit, data){ } -setGeneric("optimizePenalty", - function(object, penalties=c(0,2^seq(-4,4)), k = 5, boot = 30, ...) - standardGeneric("optimizePenalty")) setMethod("optimizePenalty", "unmarkedFitOccuMulti", function(object, penalties=c(0,2^seq(-4,4)), k = 5, boot = 30, ...){ diff --git a/R/parboot.R b/R/parboot.R index 7eebeaf6..05e58cfb 100644 --- a/R/parboot.R +++ b/R/parboot.R @@ -1,20 +1,6 @@ # ----------------------- PARAMETRIC BOOTSTRAP -------------------------- - -setGeneric("parboot", - def = function(object, ...) { - standardGeneric("parboot") - }) - - -setClass("parboot", - representation(call = "call", - t0 = "numeric", - t.star = "matrix")) - -setGeneric("replaceY", function(object, newY, replNA = TRUE, ...){ - standardGeneric("replaceY")}) setMethod("replaceY", "unmarkedFrame", function(object, newY, replNA=TRUE, ...){ if(replNA) is.na(newY) <- is.na(object@y) object@y <- newY diff --git a/R/plotEffects.R b/R/plotEffects.R index c77f5aa3..6eb7e61b 100644 --- a/R/plotEffects.R +++ b/R/plotEffects.R @@ -35,8 +35,6 @@ get_cov_seq <- function(covariate, object, type){ } } -setGeneric("plotEffectsData", function(object, ...) standardGeneric("plotEffectsData")) - setMethod("plotEffectsData", "unmarkedFit", function(object, type, covariate, level=0.95, ...){ @@ -55,7 +53,6 @@ setMethod("plotEffectsData", "unmarkedFit", pr }) -setGeneric("plotEffects", function(object, ...) standardGeneric("plotEffects")) setMethod("plotEffects", "unmarkedFit", function(object, type, covariate, level=0.95, ...){ diff --git a/R/posteriorSamples.R b/R/posteriorSamples.R index 2d59971e..a38ee11d 100644 --- a/R/posteriorSamples.R +++ b/R/posteriorSamples.R @@ -1,14 +1,3 @@ -setGeneric("posteriorSamples", function(object, nsims, ...){ - standardGeneric("posteriorSamples") - }) - -setClass("unmarkedPostSamples", - representation(numSites="numeric", - numPrimary="numeric", - nsims="numeric", - samples="array") - ) - setMethod("posteriorSamples", "unmarkedRanef", function(object, nsims=100, ...) { diff --git a/R/power.R b/R/power.R index 24d4451c..f3b9bd82 100644 --- a/R/power.R +++ b/R/power.R @@ -1,13 +1,3 @@ -setClass("unmarkedPower", - representation(call="call", data="unmarkedFrame", M="numeric", - J="numeric", T="numeric", coefs="list", estimates="list", - alpha="numeric", nulls="list") -) - -setGeneric("powerAnalysis", function(object, ...){ - standardGeneric("powerAnalysis") -}) - # unmarkedFrame method # TODO: random effects handling # TODO: parallel processing @@ -256,11 +246,6 @@ plot_power <- function(object, ind, alpha, ...){ # unmarkedPowerlist stuff------------------------------------------------------ -setClass("unmarkedPowerList", representation(powerAnalyses="list")) - -setGeneric("unmarkedPowerList", function(object, ...){ - standardGeneric("unmarkedPowerList")}) - setMethod("unmarkedPowerList", "unmarkedPower", function(object, ...){ all_objs <- c(object, list(...)) diff --git a/R/predict.R b/R/predict.R index 7c8548da..86aeac1b 100644 --- a/R/predict.R +++ b/R/predict.R @@ -11,8 +11,6 @@ setMethod("predict", "unmarkedFit", level=level, re.form=re.form, ...) }) -setGeneric("predict_internal", function(object, ...) standardGeneric("predict_internal")) - setMethod("predict_internal", "unmarkedFit", function(object, type, newdata, backTransform = TRUE, na.rm = TRUE, appendData = FALSE, level=0.95, re.form=NULL, ...){ @@ -109,10 +107,6 @@ check_nested_formula_functions <- function(formula){ # 5. predict_by_chunk(): Take inputs and generate predictions # Basic methods are shown below; fit type-specific methods in their own sections -setGeneric("check_predict_arguments", function(object, ...){ - standardGeneric("check_predict_arguments") -}) - setMethod("check_predict_arguments", "unmarkedFit", function(object, type, newdata, ...){ # Check if type is supported (i.e., is it in names(object)?) @@ -133,10 +127,6 @@ check_type <- function(mod, type){ } # Get X and offset when newdata is umf -setGeneric("predict_inputs_from_umf", function(object, ...){ - standardGeneric("predict_inputs_from_umf") -}) - setMethod("predict_inputs_from_umf", "unmarkedFit", function(object, type, newdata, na.rm, re.form){ designMats <- getDesign(newdata, object@formula, na.rm = na.rm) @@ -155,10 +145,6 @@ setMethod("predict_inputs_from_umf", "unmarkedFit", }) # Get correct individual formula based on type -setGeneric("get_formula", function(object, type, ...){ - standardGeneric("get_formula") -}) - setMethod("get_formula", "unmarkedFit", function(object, type, ...){ if(type == "state"){ return(as.formula(paste("~", object@formula[3], sep=""))) @@ -170,10 +156,6 @@ setMethod("get_formula", "unmarkedFit", function(object, type, ...){ # When newdata is data.frame/raster, get original dataset # For use in building correct model frame -setGeneric("get_orig_data", function(object, type, ...){ - standardGeneric("get_orig_data") -}) - # Note that by default, final year of yearlySiteCov data at each site is dropped # Because transition probabilities are not estimated for final year # this is appropriate for dynamic models but not temporary emigration models @@ -186,10 +168,6 @@ setMethod("get_orig_data", "unmarkedFit", function(object, type, ...){ # Take inputs (most importantly model matrix and offsets) and generate prediction # done in chunks for speed, 70 was optimal after tests -setGeneric("predict_by_chunk", function(object, ...){ - standardGeneric("predict_by_chunk") -}) - setMethod("predict_by_chunk", "unmarkedFit", function(object, type, level, xmat, offsets, chunk_size, backTransform=TRUE, re.form=NULL, ...){ diff --git a/R/ranef.R b/R/ranef.R index 1f43496f..c3987d25 100644 --- a/R/ranef.R +++ b/R/ranef.R @@ -1,21 +1,10 @@ # ----------------- Empirical Bayes Methods ------------------------------ -setGeneric("ranef", - function(object, ...) standardGeneric("ranef")) - -setClass("unmarkedRanef", - representation(post = "array")) - # Overall exported function setMethod("ranef", "unmarkedFit", function(object, ...){ ranef_internal(object, ...) }) - -# Internal fit-type-specific function -setGeneric("ranef_internal", function(object, ...) standardGeneric("ranef_internal")) - - setMethod("ranef_internal", "unmarkedFitColExt", function(object){ data <- object@data M <- numSites(data) @@ -932,8 +921,6 @@ setMethod("ranef_internal", "unmarkedFitPCO", function(object, ...){ }) -setGeneric("bup", function(object, stat=c("mean", "mode"), ...) - standardGeneric("bup")) setMethod("bup", "unmarkedRanef", function(object, stat=c("mean", "mode"), ...) { stat <- match.arg(stat) diff --git a/R/residuals.R b/R/residuals.R index 69673208..757fdb0c 100644 --- a/R/residuals.R +++ b/R/residuals.R @@ -4,10 +4,6 @@ setMethod("residuals", "unmarkedFit", function(object, ...){ }) # Internal method for specific fit types, not exported -setGeneric("residuals_internal", function(object){ - standardGeneric("residuals_internal") -}) - setMethod("residuals_internal", "unmarkedFit", function(object) { y <- getY(object) e <- fitted(object) diff --git a/R/simulate.R b/R/simulate.R index fc44c865..6ce15d5d 100644 --- a/R/simulate.R +++ b/R/simulate.R @@ -13,10 +13,6 @@ setMethod("simulate", "unmarkedFrame", }) }) -setGeneric("y_to_zeros", function(object, ...){ - standardGeneric("y_to_zeros") -}) - # Other fit-specific methods at the bottom of the file setMethod("y_to_zeros", "unmarkedFrame", function(object, ...){ object@y[] <- 0 @@ -29,10 +25,7 @@ get_fit <- function(object, model, ...){ control=list(maxit=0), se=FALSE) } -setGeneric("get_fitting_function", function(object, model, ...){ - standardGeneric("get_fitting_function") -}) - +# Get fitting function associated with an unmarkedFrame type # Other fit-specific methods at the bottom of the file setMethod("get_fitting_function", "unmarkedFrameOccu", function(object, model, ...){ @@ -254,9 +247,6 @@ setMethod("simulate", "unmarkedFit", function(object, nsim = 1, seed = NULL, ... }) # Internal methods -setGeneric("simulate_internal", function(object, nsim) standardGeneric("simulate_internal")) - - setMethod("simulate_internal", "unmarkedFitColExt", function(object, nsim){ data <- object@data diff --git a/R/square_brackets.R b/R/square_brackets.R index 98935da8..eb3cdddc 100644 --- a/R/square_brackets.R +++ b/R/square_brackets.R @@ -1,5 +1,3 @@ -setClassUnion("numericOrLogical", c("numeric", "logical")) - # Square bracket selector methods (exported)----------------------------------- setMethod("[", c("unmarkedFrame", "numericOrLogical", "missing", "missing"), function(x, i){ @@ -20,8 +18,6 @@ setMethod("[", c("unmarkedFrame", "numericOrLogical", "numericOrLogical", "missi # Internal site-selector methods----------------------------------------------- -setGeneric("subset_sites", function(umf, i) standardGeneric("subset_sites")) - setMethod("subset_sites", c("unmarkedFrame", "numericOrLogical"), function(umf, i){ @@ -220,8 +216,6 @@ process_site_index <- function(umf, i){ # Internal obs/period-selector methods----------------------------------------- -setGeneric("subset_obs", function(umf, j) standardGeneric("subset_obs")) - setMethod("subset_obs", c("unmarkedFrame", "numericOrLogical"), function(umf, j){ if(obsNum(umf) != numY(umf)){ diff --git a/R/unmarkedCrossVal.R b/R/unmarkedCrossVal.R index f74ba39e..e2b3f0f9 100644 --- a/R/unmarkedCrossVal.R +++ b/R/unmarkedCrossVal.R @@ -1,23 +1,3 @@ - -setGeneric("crossVal", function(object, - method=c("Kfold","holdout","leaveOneOut"), folds=10, holdoutPct=0.25, - statistic=RMSE_MAE, ...) standardGeneric("crossVal")) - -setClass("unmarkedCrossVal", - representation(stats = "data.frame", - summary = "data.frame", - method = "character", - folds = "numeric", - holdoutPct = "numeric"), - validity=function(object){ - errors <- character(0) - hp <- object@holdoutPct - if(hp<0|hp>1){ - errors <- c(errors,"holdoutPct must be between 0 and 1") - } - } -) - #Constructor of crossVal objects setMethod("crossVal", "unmarkedFit", function(object, method=c("Kfold","holdout","leaveOneOut"), @@ -150,14 +130,6 @@ setMethod("show", "unmarkedCrossVal", function(object) } }) -setClass("unmarkedCrossValList", - representation(stats_list="list", - method = "character", - folds="numeric", - holdoutPct="numeric", - sort="character") -) - #CrossVal list constructor setMethod("crossVal", "unmarkedFitList", function(object, method=c("Kfold","holdout","leaveOneOut"), diff --git a/R/unmarkedEstimate.R b/R/unmarkedEstimate.R index 71f87168..ebcfb7dc 100644 --- a/R/unmarkedEstimate.R +++ b/R/unmarkedEstimate.R @@ -1,47 +1,3 @@ - -setClassUnion("matrixOrVector", c("matrix","numeric")) - -# Class to store actual parameter estimates -setClass("unmarkedEstimate", - representation( - name = "character", - short.name = "character", - estimates = "numeric", - covMat = "matrix", - fixed = "numeric", - covMatBS = "optionalMatrix", - invlink = "character", - invlinkGrad = "character", - randomVarInfo= "list"), - validity = function(object) { - errors <- character(0) - if(nrow(object@covMat) != length(object@estimates)) { - errors <- c(errors, - "Size of covMat does not match length of estimates.") - } - if(length(errors) > 0) - errors - else - TRUE - }) - -setClass("unmarkedEstimateList", - representation(estimates = "list"), - validity = function(object) { - errors <- character(0) - for(est in object@estimates) { - if(!is(est, "unmarkedEstimate")) { - errors <- c("At least one element of unmarkedEstimateList is not an unmarkedEstimate.") - break - } - } - if(length(errors) == 0) { - return(TRUE) - } else { - return(errors) - } - }) - setMethod("show", "unmarkedEstimateList", function(object) { for(est in object@estimates) { @@ -62,10 +18,6 @@ setMethod("summary", "unmarkedEstimateList", invisible(sumList) }) -setGeneric("estimates", - function(object) { - standardGeneric("estimates") - }) setMethod("estimates", "unmarkedEstimate", function(object) { diff --git a/R/unmarkedFit.R b/R/unmarkedFit.R index de0443f8..f09594fb 100644 --- a/R/unmarkedFit.R +++ b/R/unmarkedFit.R @@ -1,164 +1,3 @@ -setClass("unmarkedFit", - representation(fitType = "character", - call = "call", - formula = "formula", - data = "unmarkedFrame", - sitesRemoved = "numeric", # vector of indices of removed sites - estimates = "unmarkedEstimateList", - AIC = "numeric", - opt = "list", - negLogLike = "numeric", - nllFun = "function", - bootstrapSamples = "optionalList", - covMatBS = "optionalMatrix", # list of bootstrap sample fits - TMB = "optionalList")) #TMB output object - -# ---------------------------- CHILD CLASSES ---------------------------- - - -setClass("unmarkedFitDS", - representation( - keyfun = "character", - unitsOut = "character", - output = "character"), - contains = "unmarkedFit") - - - -setClass("unmarkedFitPCount", - representation( - K = "numeric", - mixture = "character"), - contains = "unmarkedFit") - -# This class is not used directly, just used as a base for for PCO, MMO, DSO -setClass("unmarkedFitDailMadsen", - representation( - K = "numeric", - mixture = "character", - formlist = "list", - dynamics = "character", - immigration = "logical", - fix = "character"), - contains = "unmarkedFit") - -setClass("unmarkedFitPCO", contains = "unmarkedFitDailMadsen") - -setClass("unmarkedFitMMO", contains = "unmarkedFitDailMadsen") - -setClass("unmarkedFitDSO", - representation( - keyfun = "character", - unitsOut = "character", - output = "character"), - contains = "unmarkedFitDailMadsen") - -setClass("unmarkedFitOccu", - representation(knownOcc = "logical"), - contains = "unmarkedFit") - -setClass("unmarkedFitOccuPEN", - representation( - knownOcc = "logical", - pen.type = "character", - lambda = "numeric"), - contains = "unmarkedFit") - -setClass("unmarkedFitOccuPEN_CV", - representation( - knownOcc = "logical", - pen.type = "character", - lambdaVec = "numeric", - k = "numeric", - foldAssignments = "numeric", - lambdaScores = "numeric", - chosenLambda = "numeric"), - contains = "unmarkedFit") - -setClass("unmarkedFitOccuFP", - representation(knownOcc = "logical", - detformula = "formula", - FPformula = "formula", - Bformula = "formula", - stateformula = "formula", - type = "numeric"), - contains = "unmarkedFit") - -setClass("unmarkedFitOccuMulti", - representation( - detformulas = "character", - stateformulas = "character"), - contains = "unmarkedFit") - -setClass("unmarkedFitOccuMS", - representation( - detformulas = "character", - psiformulas = "character", - phiformulas = "character", - parameterization = "character"), - contains = "unmarkedFit") - -setClass("unmarkedFitOccuTTD", - representation( - psiformula = "formula", - gamformula = "formula", - epsformula = "formula", - detformula = "formula"), - contains = "unmarkedFit") - -setClass("unmarkedFitNmixTTD", - representation( - stateformula = "formula", - detformula = "formula", - K = "numeric"), - contains = "unmarkedFit") - -setClass("unmarkedFitMPois", - contains = "unmarkedFit") - - -setClass("unmarkedFitOccuRN", - representation( - K = "numeric"), - contains = "unmarkedFit") - -setClass("unmarkedFitColExt", - representation( - phi = "matrix", - psiformula = "formula", - gamformula = "formula", - epsformula = "formula", - detformula = "formula", - projected = "array", - projected.mean = "matrix", - smoothed = "array", - smoothed.mean = "matrix", - projected.mean.bsse = "optionalMatrix", - smoothed.mean.bsse = "optionalMatrix"), - contains = "unmarkedFit") - - -setClass("unmarkedFitGMM", - representation( - formlist = "list", - mixture = "character", - K = "numeric"), - contains = "unmarkedFit") - - -setClass("unmarkedFitGDS", - representation( - keyfun = "character", - unitsOut = "character", - output = "character"), - contains = "unmarkedFitGMM") - - -setClass("unmarkedFitGPC", - contains = "unmarkedFitGMM") - - - # -------------------------- Show and Summary ---------------------------- @@ -174,8 +13,6 @@ setMethod("summary", "unmarkedFit", function(object) }) -setGeneric("summary_internal", function(object) standardGeneric("summary_internal")) - setMethod("summary_internal", "unmarkedFit", function(object) { cat("\nCall:\n") @@ -462,7 +299,6 @@ setMethod("hessian", "unmarkedFit", }) -setGeneric("sampleSize", function(object) standardGeneric("sampleSize")) setMethod("sampleSize", "unmarkedFit", function(object) { data <- getData(object) M <- numSites(data) @@ -471,30 +307,23 @@ setMethod("sampleSize", "unmarkedFit", function(object) { }) -setGeneric("getData", function(object) standardGeneric("getData")) setMethod("getData", "unmarkedFit",function(object) { object@data }) -setGeneric("nllFun", function(object) standardGeneric("nllFun")) setMethod("nllFun", "unmarkedFit", function(object) object@nllFun) -setGeneric("mle", function(object) standardGeneric("mle")) -setMethod("mle", "unmarkedFit", function(object) object@opt$par) -setClass("profile", representation(prof = "matrix")) +setMethod("mle", "unmarkedFit", function(object) object@opt$par) -setGeneric("smoothed", - function(object, mean=TRUE) standardGeneric("smoothed")) setMethod("smoothed","unmarkedFitColExt", function(object, mean) { if(mean) object@smoothed.mean else object@smoothed }) -setGeneric("projected", - function(object, mean=TRUE) standardGeneric("projected")) + setMethod("projected","unmarkedFitColExt", function(object, mean) { if(mean) object@projected.mean else object@projected @@ -510,8 +339,6 @@ setMethod("plot", c(x = "unmarkedFit", y = "missing"), function(x, y, ...) residual_plot(x, ...) }) -setGeneric("residual_plot", function(x, ...) standardGeneric("residual_plot")) - setMethod("residual_plot", "unmarkedFit", function(x, ...) { r <- residuals(x) @@ -635,10 +462,6 @@ setMethod("hist", "unmarkedFitDS", function(x, lwd=1, lty=1, ...) { # ----------------------- CHILD CLASS METHODS --------------------------- # Extract detection probs -setGeneric("getFP", function(object, ...) standardGeneric("getFP")) -setGeneric("getB", function(object, ...) standardGeneric("getB")) - - setMethod("getFP", "unmarkedFitOccuFP", function(object, na.rm = TRUE) { formula <- object@formula @@ -696,8 +519,6 @@ setMethod("getB", "unmarkedFitOccuFP", function(object, na.rm = TRUE) #Y extractors for unmarkedFit objects setMethod("getY", "unmarkedFit", function(object) getY_internal(object)) -setGeneric("getY_internal", function(object) standardGeneric("getY_internal")) - setMethod("getY_internal", "unmarkedFit", function(object) object@data@y) setMethod("getY_internal", "unmarkedFitOccu", function(object) { truncateToBinary(object@data@y) diff --git a/R/unmarkedFitList.R b/R/unmarkedFitList.R index e90a0064..75d9d3d6 100644 --- a/R/unmarkedFitList.R +++ b/R/unmarkedFitList.R @@ -1,7 +1,5 @@ #Get y (corrected for missing values) based on data and formulas #Approach for some fit functions is different, so this is now a method -setGeneric("fl_getY", function(fit, ...) standardGeneric("fl_getY")) - setMethod("fl_getY", "unmarkedFit", function(fit, ...){ getDesign(getData(fit), fit@formula)$y }) @@ -22,25 +20,6 @@ setMethod("fl_getY", "unmarkedFitOccuFP", function(fit, ...){ fit@Bformula, fit@stateformula)$y }) -setClass("unmarkedFitList", - representation(fits = "list"), - validity = function(object) { - fl <- object@fits - umf1 <- getData(fl[[1]]) - y1 <- fl_getY(fl[[1]]) - dataTest <- sapply(fl, function(x) isTRUE(all.equal(umf1, getData(x)))) - yTest <- sapply(fl, function(x) isTRUE(all.equal(y1, fl_getY(x)))) - if(!all(dataTest)) { - stop("Data are not the same among models. Make sure you use the same unmarkedFrame object for all models.") - } - else if(!all(yTest)) { - stop("Data are not the same among models due to missing covariate values. Consider removing NAs before analysis.") - } - TRUE - } - ) - - # constructor of unmarkedFitList objects fitList <- function(..., fits, autoNames=c("object","formula")) { autoNames <- match.arg(autoNames) @@ -213,23 +192,6 @@ nagR2 <- function(fit, nullfit) return(r2 / r2max) } - - -setGeneric("modSel", - def = function(object, ...) { - standardGeneric("modSel") - } - ) - -setClass("unmarkedModSel", - representation( - Full = "data.frame", - Names = "matrix" - ) - ) - - - # Model selection results from an unmarkedFitList setMethod("modSel", "unmarkedFitList", function(object, nullmod=NULL) diff --git a/R/unmarkedFrame.R b/R/unmarkedFrame.R index 25034bfc..94c6ae9b 100644 --- a/R/unmarkedFrame.R +++ b/R/unmarkedFrame.R @@ -1,204 +1,3 @@ - -# ------------------------ VALIDATION FUNCTIONS -------------------------- - -validunmarkedFrame <- function(object) { - errors <- character(0) - M <- nrow(object@y) - J <- ncol(object@y) - if(!is.null(object@siteCovs)) - if(nrow(object@siteCovs) != M) - errors <- c(errors, - "siteCovData does not have same size number of sites as y.") - if(!is.null(obsCovs(object)) & !is.null(obsNum(object))) - if(nrow(object@obsCovs) != M*obsNum(object)) - errors <- c(errors, "obsCovData does not have M*obsNum rows.") - if(length(errors) == 0) - TRUE - else - errors -} - -# --------------------------- DATA CLASSES ------------------------------- - -# Class to hold data for analyses in unmarked. -setClass("unmarkedFrame", - representation(y = "matrix", - obsCovs = "optionalDataFrame", - siteCovs = "optionalDataFrame", - obsToY = "optionalMatrix"), - validity = validunmarkedFrame) - -## a class for multi-season data - -setClass("unmarkedMultFrame", - representation(numPrimary = "numeric", - #data frame in site-major, year-minor order describing siteCovs - yearlySiteCovs = "optionalDataFrame"), - contains="unmarkedFrame") - - - -## a class for distance sampling data -setClass("unmarkedFrameDS", - representation( - dist.breaks = "numeric", - tlength = "numeric", - survey = "character", - unitsIn = "character"), - contains = "unmarkedFrame", - validity = function(object) { - errors <- character(0) - J <- numY(object) - db <- object@dist.breaks - if(J != length(db) - 1) - errors <- c(errors, "ncol(y) must equal length(dist.breaks)-1") - if(db[1] != 0) - errors <- c(errors, "dist.breaks[1] must equal 0") - if(!is.null(obsCovs(object))) - "obsCovs cannot be used with distsamp" - if(length(errors) == 0) TRUE - else errors - }) - - -setClass("unmarkedFrameOccu", - contains = "unmarkedFrame") - -setClass("unmarkedFrameOccuFP", - representation( - type = "numeric"), - contains = "unmarkedFrame") - -#Multi-state occupancy -setClass('unmarkedFrameOccuMS', - representation( - numStates = "numeric", - phiOrder = "list"), - contains = "unmarkedMultFrame") - -#Time-to-detection occupancy -setClass("unmarkedFrameOccuTTD", - representation( - surveyLength = "matrix"), - contains = "unmarkedMultFrame") - -setClass("unmarkedFrameOccuMulti", - representation(ylist = "list", fDesign = "matrix"), - contains = "unmarkedFrame", - validity = function(object) { - errors <- character(0) - M <- nrow(object@y) - J <- ncol(object@y) - Ms <- sapply(object@ylist,nrow) - Js <- sapply(object@ylist,ncol) - if(length(unique(Ms)) != 1) - errors <- c(errors, "All species must have same number of sites") - if(length(unique(Js)) != 1) - errors <- c(errors, "All species must have same number of observations") - if(!is.null(object@siteCovs)) - if(nrow(object@siteCovs) != M) - errors <- c(errors, - "siteCovData does not have same size number of sites as y.") - if(!is.null(obsCovs(object)) & !is.null(obsNum(object))) - if(nrow(object@obsCovs) != M*obsNum(object)) - errors <- c(errors, "obsCovData does not have M*obsNum rows.") - if(length(errors) == 0) - TRUE - else - errors - }) - -setClass("unmarkedFramePCount", - contains = "unmarkedFrame") - - -setClass("unmarkedFrameMPois", - representation( - samplingMethod = "character", - piFun = "character"), - contains = "unmarkedFrame") - - -setClass("unmarkedFrameG3", - contains = "unmarkedMultFrame") - -setClass("unmarkedFrameGMM", - representation( - piFun = "character", - samplingMethod = "character"), - contains = "unmarkedFrameG3") - -setClass("unmarkedFrameGDS", - representation( - dist.breaks = "numeric", - tlength = "numeric", - survey = "character", - unitsIn = "character"), - contains = "unmarkedFrameG3") - -setClass("unmarkedFrameGPC", - contains = "unmarkedFrameG3") - -setClass("unmarkedFrameDailMadsen", - representation(primaryPeriod = "matrix"), - contains = "unmarkedMultFrame") - -setClass("unmarkedFramePCO", - contains = "unmarkedFrameDailMadsen") - -setClass("unmarkedFrameMMO", - representation( - piFun = "character", - samplingMethod = "character"), - contains = "unmarkedFrameDailMadsen") - -setClass("unmarkedFrameDSO", - representation( - dist.breaks = "numeric", - tlength = "numeric", - survey = "character", - unitsIn = "character"), - contains = "unmarkedFrameDailMadsen") - -setClass("unmarkedFrameGDR", - representation( - yDistance = "matrix", - yRemoval = "matrix", - survey = "character", - dist.breaks = "numeric", - unitsIn = "character", - period.lengths = "numeric" - ), - contains="unmarkedMultFrame" -) - -setClass( - "unmarkedFrameOccuCOP", - representation(L = "matrix"), - contains = "unmarkedFrame", - validity = function(object) { - errors <- character(0) - M <- nrow(object@y) - J <- ncol(object@y) - y_integers = sapply(object@y, check.integer, na.ignore = T) - if (!all(y_integers)) { - errors <- c(errors, - paste( - "Count detection should be integers. Non-integer values:", - paste(object@y[which(!y_integers)], collapse = ', ') - )) - } - if (!all(all(dim(object@L) == dim(object@y)))){ - errors <- c( errors, paste( - "L should be a matrix of the same dimension as y, with M =", M, - "rows (sites) and J =", J, "columns (sampling occasions)." - ))} - if (length(errors) == 0) TRUE - else errors - } -) - - # ------------------------------- CONSTRUCTORS --------------------------- #Convert covs provided as list of matrices/dfs to data frame @@ -849,20 +648,14 @@ setMethod("show", "unmarkedFrameOccuTTD", function(object) ############################ EXTRACTORS ################################## # Extractor for site level covariates -setGeneric("siteCovs", function(object,...) standardGeneric("siteCovs")) - setMethod("siteCovs", "unmarkedFrame", function(object) { return(object@siteCovs) }) -setGeneric("yearlySiteCovs", function(object,...) - standardGeneric("yearlySiteCovs")) setMethod("yearlySiteCovs", "unmarkedMultFrame", function(object) { return(object@yearlySiteCovs) }) - -setGeneric("obsCovs", function(object,...) standardGeneric("obsCovs")) setMethod("obsCovs", "unmarkedFrame", function(object, matrices = FALSE) { M <- numSites(object) R <- obsNum(object) @@ -879,24 +672,18 @@ setMethod("obsCovs", "unmarkedFrame", function(object, matrices = FALSE) { }) -setGeneric("obsNum", function(object) standardGeneric("obsNum")) setMethod("obsNum", "unmarkedFrame", function(object) nrow(object@obsToY)) -setGeneric("numSites", function(object) standardGeneric("numSites")) setMethod("numSites", "unmarkedFrame", function(object) nrow(object@y)) -setGeneric("numY", function(object) standardGeneric("numY")) setMethod("numY", "unmarkedFrame", function(object) ncol(object@y)) -setGeneric("obsToY", function(object) standardGeneric("obsToY")) setMethod("obsToY", "unmarkedFrame", function(object) object@obsToY) -setGeneric("obsCovs<-", function(object, value) - standardGeneric("obsCovs<-")) setReplaceMethod("obsCovs", "unmarkedFrame", function(object, value) { if(inherits(object, "unmarkedFrameDS")) stop("unmarkedFrameDS objects cannot have obsCovs") @@ -905,31 +692,24 @@ setReplaceMethod("obsCovs", "unmarkedFrame", function(object, value) { }) -setGeneric("siteCovs<-", function(object, value) - standardGeneric("siteCovs<-")) setReplaceMethod("siteCovs", "unmarkedFrame", function(object, value) { object@siteCovs <- as.data.frame(value) object }) -setGeneric("yearlySiteCovs<-", - function(object, value) standardGeneric("yearlySiteCovs<-")) setReplaceMethod("yearlySiteCovs", "unmarkedMultFrame", function(object, value) { object@yearlySiteCovs <- as.data.frame(value) object }) -setGeneric("obsToY<-", function(object, value) standardGeneric("obsToY<-")) setReplaceMethod("obsToY", "unmarkedFrame", function(object, value) { object@obsToY <- value object }) - -setGeneric("getY", function(object) standardGeneric("getY")) setMethod("getY", "unmarkedFrame", function(object) object@y) setMethod("getY", "unmarkedFrameOccuMulti", function(object) object@ylist[[1]]) diff --git a/R/unmarkedLinComb.R b/R/unmarkedLinComb.R index df5fcac9..33f192ab 100644 --- a/R/unmarkedLinComb.R +++ b/R/unmarkedLinComb.R @@ -1,20 +1,3 @@ - -setClass("unmarkedLinComb", - representation(parentEstimate = "unmarkedEstimate", - estimate = "numeric", - covMat = "matrix", - covMatBS = "optionalMatrix", - coefficients = "matrix")) - -setClass("unmarkedBackTrans", - representation(parentLinComb = "unmarkedLinComb", - estimate = "numeric", - covMat = "matrix", - covMatBS = "optionalMatrix")) - -setClassUnion("linCombOrBackTrans", - c("unmarkedLinComb", "unmarkedBackTrans")) - setMethod("show", signature(object = "unmarkedLinComb"), function(object) { diff --git a/R/update.R b/R/update.R index 583bccc9..e5c77378 100644 --- a/R/update.R +++ b/R/update.R @@ -21,14 +21,13 @@ setMethod("update", "unmarkedFit", function(object, ..., evaluate=TRUE){ eval(cl) }) -# This method starts with a fitted model's saved call, and inserts +# The rebuild_call method starts with a fitted model's saved call, and inserts # as much saved information from the object into the call as possible. # This avoids situations where the original call referenced e.g. a # vector of formulas saved in the global environment, which would not be # available if updating the model later in a different environment. # In general we're just inserting everything from fit-specific slots # in the unmarkedFit object that is also an input argument. -setGeneric("rebuild_call", function(object) standardGeneric("rebuild_call")) # This method is not actually used directly by any fitting function, instead # it's a base piece of the call for most of them. diff --git a/R/utils.R b/R/utils.R index a35b0b9f..4c379b9a 100644 --- a/R/utils.R +++ b/R/utils.R @@ -490,8 +490,6 @@ formatDistData <- function (distData, distCol, transectNameCol, dist.breaks, occ #Sum of squared errors method -setGeneric("SSE", function(fit, ...) standardGeneric("SSE")) - setMethod("SSE", "unmarkedFit", function(fit, ...){ sse <- sum(residuals(fit)^2, na.rm=TRUE) return(c(SSE=sse))