Rceattle C++ template
The CEATTLE likelihood: src/TMB/ceattle.cpp and its headers
Loading...
Searching...
No Matches
comp_osa.hpp
Go to the documentation of this file.
1// Adapted in part from distr.hpp (github.com/vtrijoulet/OSA_multivariate_dists),
2// whose notice is kept here:
3// --------------------------------------------------------------------------
4// Copyright (c) 2022, Vanessa Trijoulet <vtri@aqua.dtu.dk>,
5// Christoffer Moesgaard Albertsen <cmoe@aqua.dtu.dk>,
6// Kasper Kristensen <kkr@aqua.dtu.dk>,
7// Chris M. Legault <chris.legault@noaa.gov>,
8// Timothy J. Miller <Timothy.J.Miller@noaa.gov>,
9// and Anders Nielsen <an@aqua.dtu.dk>.
10// All rights reserved.
11// --------------------------------------------------------------------------
12
13/**
14 * @file comp_osa.hpp
15 * @brief One-step-ahead (OSA) residual helpers for composition data.
16 *
17 * TMB's oneStepPredict() needs every observation in a flat `obsvec`, its likelihood
18 * term multiplied by its own `keep` element, which multivariate discrete
19 * composition data cannot supply directly. Following Trijoulet et al. (2023), their
20 * reference code (distr.hpp in github.com/vtrijoulet/OSA_multivariate_dists, from
21 * which dmultinom_osa() and ddirmultinom_osa() take their names and CDF terms) and
22 * WHAM (src/age_comp_osa.hpp), a composition of A bins is decomposed into A-1
23 * univariate conditionals -- binomials for the multinomial, beta-binomials for the
24 * Dirichlet-multinomial -- each gated by its keep element. The last bin is fixed by
25 * the sum-to-N constraint, contributes nothing, and is reported as NA on the R side.
26 * With every keep at 1 the conditional log-densities sum to the joint log-density,
27 * so OSA changes how the likelihood is *decomposed*, not its value. The `_osa`
28 * suffix and the data_indicator argument keep these clear of TMB's dmultinom() and
29 * of the ddirmultinom() in helper_functions.hpp that ordinary fitting uses.
30 *
31 * The file also holds the conditional CDFs oneStepPredict(method = "cdf") reads --
32 * continuous binomial for a composition bin, normal / left-truncated normal for an
33 * aggregate series. That residual is Phi^-1(F(x)), formed without a conditional
34 * mean, so it cannot leave the support of a bounded observation.
35 *
36 * Shared contract of the CDF terms below -- the two `_cdf_terms` helpers and
37 * dmultinom_osa()'s `do_cdf` path. Each contributes to the log-likelihood
38 * `keep.cdf_lower` times log F plus `keep.cdf_upper` times log of its complement,
39 * which is 0 whenever the cdf gates are 0: every evaluation except the two
40 * oneStepPredict(method = "cdf") makes per observation. The terms are added only when
41 * the caller asks (`do_cdf`, from osa_mode == 2), so ordinary fitting and the Gaussian
42 * OSA methods are unchanged and pay nothing for them. Every F is mapped onto the open
43 * interval by osa_squeeze_cdf() first, because an exactly 0 or 1 CDF puts a -Inf on
44 * the tape and a -Inf times a zero gate is a NaN.
45 */
46
47// Place kept categories (keep > 0.5) before dropped ones, preserving order within
48// each group (Anders Nielsen's order(), via WHAM src/age_comp_osa.hpp).
49template<class Type>
50vector<int> osa_order(vector<Type> k){
51 int n = k.size();
52 vector<int> ord(n);
53 ord.setZero();
54 int at = -1;
55 for(int i = 0; i < n; ++i){
56 if(k(i) > 0.5){ ord(++at) = i; }
57 }
58 at = n;
59 for(int i = n - 1; i >= 0; --i){
60 if(k(i) < 0.5){ ord(--at) = i; }
61 }
62 return ord;
63}
64
65// Map the closed [0, 1] interval onto the open interval. Identical to TMB's
66// convenience.hpp squeeze() (eps = machine epsilon), which WHAM's OSA composition
67// likelihood uses, so the two agree to the last digit.
68template<class Type>
69Type osa_squeeze(Type u){
70 Type eps = std::numeric_limits<double>::epsilon();
71 return (Type(1.0) - eps) * (u - Type(0.5)) + Type(0.5);
72}
73
74/**
75 * @brief Map a CDF onto the open interval before its logarithm is taken.
76 *
77 * Four machine epsilons wide where osa_squeeze() uses one: oneStepPredict recovers F
78 * from 1/(1 + exp(nlcdf.lower - nlcdf.upper)) in double precision, and at one epsilon
79 * that denominator sits on the round-half-to-even tie above 1 -- where it rounds to 1
80 * so does F, and the residual is infinite. Measured on BS2017SS: 6 of 4538
81 * composition residuals infinite at one epsilon, none at four; the cost is where
82 * |residual| saturates -- 8.04 against 8.13 -- a tail no Q-Q plot resolves.
83 *
84 * It maps rather than clamps, so a caller that forms F by subtracting two CDFs relies
85 * on it to absorb the cancellation: osa_trunc_norm_cdf_terms()'s numerator can round
86 * to about -2e-16 at an observation near zero, which this shift carries back above 0
87 * before the log. Narrowing it would return NaN there.
88 */
89template<class Type>
90Type osa_squeeze_cdf(Type u){
91 Type eps = Type(4.0) * std::numeric_limits<double>::epsilon();
92 return (Type(1.0) - eps) * (u - Type(0.5)) + Type(0.5);
93}
94
95/**
96 * @brief Conditional binomial CDF P(X <= x), X ~ Binomial(n, p), at fractional x.
97 *
98 * Written through the regularized incomplete beta, 1 - I_p(x + 1, n - x), which equals
99 * the binomial CDF at whole counts and stays smooth at the fractional ones composition
100 * data carry: a bin count is proportion * effective sample size, an integer only by
101 * coincidence. Same expression as the Trijoulet et al. (2023) reference implementation
102 * (distr.hpp, `dists::pbinom`, which TMB:::install.contrib() installs).
103 *
104 * @param x Count in this bin.
105 * @param n Count still unplaced across this bin and every later one.
106 * @param p Probability of landing in this bin rather than a later one.
107 */
108template<class Type>
109Type osa_pbinom(Type x, Type n, Type p){
110 // n - x is the count left for the later bins. comp_offset (default 1e-5) is added to
111 // every bin, so it is positive unless comp_offset is 0, where pbeta at a zero shape
112 // returns NaN rather than the limit -- and a NaN times a zero gate is still a NaN.
113 Type nx = CppAD::CondExpLt(n - x, Type(1e-12), Type(1e-12), n - x);
114 return Type(1.0) - pbeta(p, x + Type(1.0), nx);
115}
116
117/**
118 * @brief One-step-ahead CDF terms for a normal observation.
119 *
120 * Every aggregate series in CEATTLE is normal on the scale `obsvec` stores it in --
121 * log for lognormal catch and index, natural scale for a "Normal" index, the whitened
122 * L^-1 scale for "MVN" -- so its conditional CDF is `pnorm` of the standardized
123 * residual.
124 *
125 * @param x Observation, on the scale it is stored in.
126 * @param mu Predicted value on that same scale.
127 * @param sd Standard deviation on that same scale.
128 * @param cdf_lower,cdf_upper The observation's `keep.cdf_lower`/`keep.cdf_upper`.
129 */
130template<class Type>
131Type osa_norm_cdf_terms(Type x, Type mu, Type sd, Type cdf_lower, Type cdf_upper){
132 Type F = osa_squeeze_cdf(pnorm((x - mu) / sd));
133 return cdf_lower * log(F) + cdf_upper * log(Type(1.0) - F);
134}
135
136/**
137 * @brief One-step-ahead CDF terms for a normal left-truncated at zero.
138 *
139 * With z = (x - mu)/sd and m = mu/sd, the truncated CDF is
140 * F(x) = [Phi(z) - Phi(-m)] / Phi(m) and its complement is 1 - F(x) = Phi(-z) / Phi(m),
141 * because Phi(m) + Phi(-m) = 1. Both are written in that form rather than as 1 - F, so
142 * the upper tail keeps its precision. This is exact wherever the truncation carries
143 * mass, which is what the Gaussian OSA methods cannot see: the truncation enters the
144 * density only through log Phi(m), a function of the prediction and not of the
145 * observation.
146 *
147 * @param x Observation (natural scale, > 0).
148 * @param mu Predicted index (natural scale).
149 * @param sd Observation standard deviation (absolute, natural scale).
150 * @param cdf_lower,cdf_upper The observation's `keep.cdf_lower`/`keep.cdf_upper`.
151 */
152template<class Type>
153Type osa_trunc_norm_cdf_terms(Type x, Type mu, Type sd,
154 Type cdf_lower, Type cdf_upper){
155 Type m = mu / sd;
156 Type Zm = pnorm(m);
157 Type F = osa_squeeze_cdf((pnorm((x - mu) / sd) - pnorm(-m)) / Zm);
158 Type G = osa_squeeze_cdf(pnorm(-(x - mu) / sd) / Zm);
159 return cdf_lower * log(F) + cdf_upper * log(G);
160}
161
162/**
163 * @brief Keep-aware multinomial log-density via conditional binomials.
164 *
165 * @param x Observed counts (length A; may be non-integer, e.g. Neff * prop).
166 * @param p Predicted proportions (length A; normalized internally).
167 * @param keep Data indicator for these A bins (from keep.segment(...)).
168 * @param do_osa 1 = conditional-binomial decomposition; 0 = plain multinomial.
169 * @param give_log 1 = return the log-density.
170 * @param do_cdf 1 = also add the CDF terms (osa_mode == 2); 0 skips the `pbeta`.
171 */
172template <class Type>
173Type dmultinom_osa(vector<Type> x, vector<Type> p,
174 data_indicator<vector<Type>, Type> keep,
175 int do_osa, int give_log, int do_cdf = 0)
176{
177 Type logres = 0;
178 // Normalize predicted proportions, guarding the denominator so a bin vector with no
179 // predicted mass (sum(p) == 0, e.g. a growth-transition row exactly zero in the
180 // tails) gives p_x == 0 rather than 0/0 = NaN, matching WHAM for vanishing p.
181 vector<Type> p_x = p / (sum(p) + Type(1e-300));
182
183 if(do_osa){
184 vector<Type> k = keep;
185 // The cdf gates are separate data_indicator members, so they are reordered by
186 // hand alongside keep; keep.segment() at the call site already carries them
187 // (tmb_core.hpp), and gating the wrong bin is silent.
188 //
189 // osa_order() branches on keep, a PARAMETER under oneStepPredict, so the sort is
190 // taped once at the initial values -- 1 for every bin that will ever be
191 // residualized or conditioned on -- and later per-observation keep changes do not
192 // re-sort. Within a composition that pattern is 1 on every bin but the last, so
193 // the order is the identity and this reorder is a no-op on every sequence the
194 // package generates. Kept because it is what makes the decomposition right for an
195 // arbitrary keep (test-likelihood-osa-cdf.R supplies one directly).
196 vector<Type> cl = keep.cdf_lower;
197 vector<Type> cu = keep.cdf_upper;
198 vector<int> o = osa_order(k);
199 x = x(o); p_x = p_x(o); k = k(o); // kept bins first
200 if(do_cdf){ cl = cl(o); cu = cu(o); }
201 Type nUnused = asDouble(sum(x));
202 Type pUsed = 0;
203 Type cdf = 1;
204 for(int i = 0; i < x.size(); ++i){
205 if(i != (x.size() - 1)){
206 // Bin i versus all remaining bins: a binomial written as a 2-category
207 // multinomial. Conditional success probability p_i / (1 - pUsed).
208 vector<Type> x2(2), p2(2);
209 x2(0) = x(i);
210 x2(1) = nUnused - x(i);
211 p2(0) = osa_squeeze(p_x(i)) / osa_squeeze(Type(1) - pUsed);
212 p2(0) = osa_squeeze(p2(0));
213 // When one bin holds ~all remaining mass the separately-squeezed numerator and
214 // denominator can push the ratio marginally above 1; clamp so p2(1) = 1 - p2(0)
215 // stays non-negative: dmultinom of a negative probability is log(negative) = NaN.
216 Type eps_clamp = std::numeric_limits<double>::epsilon();
217 p2(0) = CppAD::CondExpGt(p2(0), Type(1) - eps_clamp, Type(1) - eps_clamp, p2(0));
218 p2(1) = Type(1) - p2(0);
219 logres += k(i) * dmultinom(x2, p2, true);
220 // Same conditional binomial the density above scores, read as a CDF.
221 // Taken before nUnused is decremented, so the size matches the density.
222 if(do_cdf) cdf = osa_pbinom(x(i), nUnused, p2(0));
223 nUnused -= x(i);
224 pUsed += p_x(i);
225 // Keep pUsed inside (0, 1) so 1 - pUsed never reaches 0 or goes negative. WHAM
226 // squeezes only 1 - pUsed, so this extra squeeze is redundant protection that
227 // contracts pUsed toward 0.5 by one machine epsilon per bin: a composition of A
228 // bins sits O(A * eps), ~1e-15 relative, from WHAM's value. Removing it would
229 // match WHAM exactly at the cost of re-pinning the OSA references.
230 pUsed = osa_squeeze(pUsed);
231 } else {
232 logres += k(i) * Type(0); // last bin: fixed by sum-to-N
233 cdf = Type(1); // ... so it sits at the top of its own CDF
234 }
235 if(do_cdf){
236 // Onto the open interval before the logs; the width matters (osa_squeeze_cdf()).
237 cdf = osa_squeeze_cdf(cdf);
238 logres += cl(i) * log(cdf);
239 logres += cu(i) * log(Type(1) - cdf);
240 }
241 }
242 } else {
243 logres = dmultinom(x, p_x, true);
244 }
245 return give_log ? logres : exp(logres);
246}
247
248/**
249 * @brief Keep-aware Dirichlet-multinomial log-density via conditional beta-binomials.
250 *
251 * No `do_cdf` counterpart: a beta-binomial has no elementary CDF, and the reference
252 * route -- summing the pmf over 0..floor(x)
253 * (contrib/OSA_multivariate_dists-main/distr.hpp, `pbetabinom`) -- is a step function
254 * of a fractional count costing O(x) beta functions per bin, thousands of times the
255 * multinomial path at CEATTLE sample sizes. So a Dirichlet-multinomial fleet cannot be
256 * residualized with oneStepPredict(method = "cdf"); osa_residuals() sends it to a
257 * Gaussian method instead.
258 *
259 * @param obs Observed counts (length A).
260 * @param alpha Dirichlet-multinomial concentration parameters (length A).
261 * @param keep Data indicator for these A bins.
262 * @param do_osa 1 = conditional beta-binomial decomposition; 0 = plain D-M.
263 * @param give_log 1 = return the log-density.
264 */
265template<class Type>
266Type ddirmultinom_osa(vector<Type> obs, vector<Type> alpha,
267 data_indicator<vector<Type>, Type> keep,
268 int do_osa, int give_log)
269{
270 Type ll = 0.0;
271 if(do_osa){
272 vector<Type> k = keep;
273 vector<int> o = osa_order(k);
274 obs = obs(o); alpha = alpha(o); k = k(o); // kept bins first
275 int dim = obs.size();
276 Type alp_sum = alpha.sum();
277 Type obs_sum = asDouble(obs.sum());
278 for(int a = 0; a < dim - 1; ++a){
279 // Bin a versus all remaining bins: a beta-binomial written as a
280 // 2-category Dirichlet-multinomial (alpha_a vs sum of remaining alphas).
281 obs_sum -= obs(a);
282 alp_sum -= alpha(a);
283 vector<Type> obs_a(2), alphas_a(2);
284 obs_a(0) = obs(a); obs_a(1) = obs_sum;
285 alphas_a(0) = alpha(a); alphas_a(1) = alp_sum;
286 ll += k(a) * ddirmultinom(obs_a, alphas_a, 1);
287 }
288 } else {
289 ll = ddirmultinom(obs, alpha, 1);
290 }
291 return give_log ? ll : exp(ll);
292}
Type osa_pbinom(Type x, Type n, Type p)
Conditional binomial CDF P(X <= x), X ~ Binomial(n, p), at fractional x.
Definition comp_osa.hpp:109
Type ddirmultinom_osa(vector< Type > obs, vector< Type > alpha, data_indicator< vector< Type >, Type > keep, int do_osa, int give_log)
Keep-aware Dirichlet-multinomial log-density via conditional beta-binomials.
Definition comp_osa.hpp:266
Type dmultinom_osa(vector< Type > x, vector< Type > p, data_indicator< vector< Type >, Type > keep, int do_osa, int give_log, int do_cdf=0)
Keep-aware multinomial log-density via conditional binomials.
Definition comp_osa.hpp:173
Type osa_norm_cdf_terms(Type x, Type mu, Type sd, Type cdf_lower, Type cdf_upper)
One-step-ahead CDF terms for a normal observation.
Definition comp_osa.hpp:131
Type osa_trunc_norm_cdf_terms(Type x, Type mu, Type sd, Type cdf_lower, Type cdf_upper)
One-step-ahead CDF terms for a normal left-truncated at zero.
Definition comp_osa.hpp:153
Type osa_squeeze(Type u)
Definition comp_osa.hpp:69
Type osa_squeeze_cdf(Type u)
Map a CDF onto the open interval before its logarithm is taken.
Definition comp_osa.hpp:90
vector< int > osa_order(vector< Type > k)
Definition comp_osa.hpp:50
Type ddirmultinom(vector< Type > obs, vector< Type > alpha, int do_log)