Compute an objective value (error, negative log-likelihood, and/or penalty)
given observed data (obs) and model outputs (sim). This function is a thin
dispatcher: it resolves FUN via match.fun() and returns FUN(obs = obs, sim = sim, ...).
Arguments
- obs
Observed data as expected by
FUN. Typically a numeric vector, matrix, or array. Missing values (NA) are permitted; see Missing values below.- sim
Simulated data matching
obs, in the sense expected byFUN. For most pointwise criteria (e.g.norm2,lnorm2,pois),simshould have the same shape asobs. For composition criteria (e.g.multinom),obsandsimare expected to be matrices with rows representing samples and columns representing classes.- FUN
Objective function to apply. Can be:
a function, e.g.
FUN = norm2;or a character string naming a function, e.g.
FUN = "norm2".
The function must accept arguments named
obsandsim(additional arguments may be supplied via...) and must return a single numeric scalar.- ...
Additional arguments forwarded to
FUN.
Value
A numeric scalar: the value of FUN(obs = obs, sim = sim, ...).
By convention this is an objective to be minimised.
Details
The returned value is intended to be minimised by an optimiser: lower
values indicate a better match between sim and obs (or a lower penalty).
Conventions and expectations
Minimisation: all provided objectives are formulated so that lower values indicate a better fit (or weaker penalty).
Shapes:
objFn()does not reshape or recycle data. It is the caller's responsibility to supplyobsandsimin a compatible form for the chosenFUN.Scalar output:
FUNshould return a length-one numeric value. Returning vectors is not supported byobjFn()itself (although higher level workflows may aggregate vector-valued objectives elsewhere).
Missing values
Most built-in objectives stop if all(is.na(obs)). Otherwise, they ignore
missing values using na.rm = TRUE inside sum()/mean(). This means:
partial
NAs inobsare ignored;NAs insimwill also be dropped from sums whenna.rm = TRUE(possibly masking simulation failures if not checked upstream).
Numerical constraints and stability
Some objectives impose additional constraints:
Poisson (
pois): useslog(sim);simmust be strictly positive whereverobs > 0(otherwise-Infmay occur). Consider flooring the simulated intensity, e.g.sim <- pmax(sim, 1e-12).Log-scale (
lnorm2,lnorm3,lnorm4,lnorm4b): applylog(x + tiny); bothobs + tinyandsim + tinymust be positive. If your data may contain zeros,tinyshould be chosen accordingly.Compositions (
multinom): expects matrix inputs and uses row sums to convert counts/weights into proportions. See details below.
Supported built-in objective functions
The following functions are available with their current behaviour. All are formulated as objectives to be minimised.
norm2Sum of squared errors on the original scale: $$\sum (obs - sim)^2$$ Typical use: continuous observations with approximately additive errors.
lnorm2Sum of squared errors on the log scale: $$\sum (\log(obs + tiny) - \log(sim + tiny))^2$$ Arguments:
tiny(default1e-2), added before the log to avoidlog(0). Typical use: positive-valued data with multiplicative (lognormal) error structure.lnorm3Log-scale squared error with an estimated multiplicative scaling factor \(q\). Internally:
compute element-wise ratios
ratio <- obs/sim;set
NaNratios toNA;estimate
q <- mean(ratio, na.rm = TRUE);return \(\sum (\log(obs+tiny) - \log(sim+tiny) - \log(q))^2\).
Typical use: positive data where an overall multiplicative bias (scale mismatch) is expected and should not be fully penalised.
lnorm4/lnorm4bExtensions of
lnorm3that add a penalty term to discourage extreme values of the scaling factor \(q\) (or extreme per-observation ratios). They rely on the helperrangeq():compute
ratio <- obs/sim, estimateq <- mean(ratio, na.rm=TRUE);compute a penalty using parameters
bandc: $$pen = n \cdot (\max(|\log_2(q)|, b)^c - b^c)$$ whendump = TRUE(used bylnorm4), or $$pen = \sum (\max(|\log_2(ratio)|, b)^c - b^c)$$ whendump = FALSE(used bylnorm4b), wherenis the number of non-missing ratios.add the penalty to the
lnorm3-style objective.
Arguments:
tiny,b(default1),c(default2). Typical use: log-scale fitting where scale drift must be controlled.poisPoisson negative log-likelihood (up to constants): $$-\sum (obs \log(sim) - sim)$$ Typical use: counts (or count-like rates) with Poisson observation error. Note:
simmust be positive whereobs > 0.multinomA composition (multinomial-like) objective operating on matrices. Inputs are expected as
obsandsimmatrices with:rows = samples (e.g. time steps, hauls, sites),
columns = classes (e.g. age/size bins, categories).
Internal steps (high-level):
Let \(A\) be the number of classes (
A <- ncol(sim)).Rows of
simthat are all zeros (excluding rows that are allNA) are replaced by1on that row (interpreted as a uniform prior).Row sums are used to compute proportions: \(Psim = sim/sum(sim)\), \(Pobs = obs/sum(obs)\) (row-wise).
Rows with
sum(sim) == 0are set toNAfor numerical convenience.Rows with
sum(obs) == 0are set toNA(interpreted as “no proportion data available”).A variance term
sigma2and a small stabilisertinyare used to define an objective that penalises discrepancies betweenPobsandPsim.
Arguments:
size(default20) andtiny(default1e-3). Interpretation:sizeplays the role of an effective sample size (larger values typically increase the weight of the composition fit).normp/rePure penalty on simulated values: $$\sum sim^2$$ This ignores
obsand can be used as a regulariser, or whensimrepresents a residual vector or deviates already computed upstream.reis an alias ofnormp.penaltyScaled quadratic penalty: $$n \cdot mean(sim^2)$$ Arguments:
n(default100). This assumes a fixed sample size and can be used to put the penalty on a comparable scale across datasets.
