diff --git a/AGENTS.md b/AGENTS.md index ace5450..e5d6501 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -47,6 +47,7 @@ src/lib/server/analytics common.ts (CPUE, Fulton's K, recapture pairs…) · env events.ts (cyclones and heavy-rain days vs catches) glm.ts (NB/Poisson GLM, splines) · catchModel.ts (joint catch model) glmm.ts (binomial mixed model, crossed random intercepts) · sex.ts + survival.ts (Cormack–Jolly–Seber apparent survival, BFGS) tests.ts (the statistic behind each chart, worded for ChartCard stats) src/lib/server/astro.ts sunset/twilight/moon (local formulas) · tides.ts (extrema, interpolation) src/lib/server/holidays.ts French Polynesia public holidays (Easter-based too), festive window, @@ -108,6 +109,12 @@ samples/fixture/ synthetic workbooks for tests/CI (committed) - `analytics/sex.ts`: female (1) vs male (0) per individual, counted once at its first capture, with the nursery and season of that capture as crossed random intercepts (`glmm.ts`: Laplace approximation, PIRLS as lme4's nAGQ = 0, SDs by Nelder–Mead). Tests fix one SD at 0 and halve the χ²₁ p (boundary). - Reuse `fitBinomialGlmm` for any yes/no outcome with grouping (fed or empty, recaptured or not) instead of pooling groups; there is no R in CI, so validate new uses against simulated data as `glmm.test.ts` does. +### Apparent survival (#42) + +- `analytics/survival.ts`: Cormack–Jolly–Seber per species on 14-day blocks of the season. One history per pup, nursery and season, starting at its first capture there, so pups born later don't bias it. φ is shared, or one per nursery for the nursery test. Capture probability is cloglog(aₙ + β·log net-hours) for that fortnight, with an intercept per nursery and p = 0 in fortnights with no set. Untimed sets count as a typical set, and a catch in a fortnight with no set on record counts as one. +- φ is apparent: death and leaving look the same, and moving to another nursery counts as leaving. Nurseries need ≥ 10 pups seen again in a later fortnight of the same season. The transience model gives the first fortnight after tagging its own φ. +- `fitCjs` is generic and validated on simulated histories in `survival.test.ts`. Reuse it rather than writing another fitter. Wald intervals are on the logit scale and are null at the boundary (φ ≈ 1). + ### School holidays (#25) - `fetch-external.mjs --only=school` writes `external/school-holidays.csv` (first and last day off, local dates). 2013-14 to 2016-17 are transcribed in the script from the Polynesian government's calendar orders for collèges and lycées (arrêtés 0270/CM 2013, 0399, 0401 and 0403/CM 2014), archived from education.pf by the Wayback Machine; the national dataset only starts in 2017-18. From 2017-18 it is the Ministry's `fr-en-calendrier-scolaire` open data (Polynésie, Licence Ouverte 2.0, credit it): pupils only, a day counts when either level is off, `end_date` is the day classes resume. diff --git a/src/lib/server/analytics/survival.test.ts b/src/lib/server/analytics/survival.test.ts new file mode 100644 index 0000000..bcf31dd --- /dev/null +++ b/src/lib/server/analytics/survival.test.ts @@ -0,0 +1,96 @@ +import { describe, expect, it } from 'vitest'; +import { dataset } from '../data'; +import { fitCjs, survival, type CjsGroup, type CjsHistory } from './survival'; + +/** Seeded uniform draws (mulberry32). */ +function rng(seed: number) { + let a = seed; + return () => { + a = (a + 0x6d2b79f5) | 0; + let t = Math.imul(a ^ (a >>> 15), 1 | a); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +const expit = (v: number) => 1 / (1 + Math.exp(-v)); + +/** + * Pups arrive through the season and stay each fortnight with chance φ[nursery]; a fortnight + * with h net-hours catches a pup that is there with p = 1 − exp(−q·h). `transient` pups leave + * after their first fortnight whatever φ is. Pups never caught don't enter a CJS data set. + */ +function simulate(seed: number, phi: number[], q: number[], transient = 0) { + const u = rng(seed); + const groups: CjsGroup[] = []; + const histories: CjsHistory[] = []; + for (let n = 0; n < phi.length; n++) + for (let season = 0; season < 8; season++) { + const hours = Array.from({ length: 12 }, () => (u() < 0.2 ? 0 : 1.5 + 2.5 * u())); + const g = groups.length; + groups.push({ nursery: n, hours }); + for (let pup = 0; pup < 70; pup++) { + const leavesEarly = u() < transient; + const seen: number[] = []; + let firstSeen = -1; + for (let t = Math.floor(u() * 8); t < 12; t++) { + if (hours[t] > 0 && u() < 1 - Math.exp(-q[n] * hours[t])) { + seen.push(t); + if (firstSeen < 0) firstSeen = t; + } + if (leavesEarly && firstSeen >= 0) break; + if (u() > phi[n]) break; + } + if (seen.length) histories.push({ group: g, seen }); + } + } + return { groups, histories }; +} + +describe('Cormack–Jolly–Seber apparent survival (#42)', () => { + it('recovers a shared φ and the effort slope', () => { + const { groups, histories } = simulate(1, [0.8, 0.8, 0.8], [0.25, 0.15, 0.35]); + const fit = fitCjs(groups, histories, 3)!; + expect(expit(fit.theta[0])).toBeGreaterThan(0.74); + expect(expit(fit.theta[0])).toBeLessThan(0.86); + // p = 1 − exp(−q·h) is the cloglog model with β = 1 and aₙ = log qₙ. + expect(fit.theta[4]).toBeGreaterThan(0.6); + expect(fit.theta[4]).toBeLessThan(1.4); + expect(fit.theta[3]).toBeCloseTo(Math.log(0.35), 0); + expect(fit.se[0]).not.toBeNull(); + }); + + it('tells nurseries apart when φ differs, and not when it does not', () => { + const diff = simulate(2, [0.9, 0.6], [0.25, 0.25]); + const shared = fitCjs(diff.groups, diff.histories, 2)!; + const each = fitCjs(diff.groups, diff.histories, 2, { nurseryPhi: true })!; + expect(expit(each.theta[0])).toBeCloseTo(0.9, 1); + expect(expit(each.theta[1])).toBeCloseTo(0.6, 1); + expect(2 * (each.loglik - shared.loglik)).toBeGreaterThan(10); + + const same = simulate(3, [0.8, 0.8], [0.25, 0.25]); + const s0 = fitCjs(same.groups, same.histories, 2)!; + const s1 = fitCjs(same.groups, same.histories, 2, { nurseryPhi: true })!; + expect(2 * (s1.loglik - s0.loglik)).toBeLessThan(6.6); // χ²₁ at p = 0.01 + }); + + it('flags transients as a lower φ in the first fortnight', () => { + const { groups, histories } = simulate(4, [0.85, 0.85], [0.3, 0.3], 0.4); + const shared = fitCjs(groups, histories, 2)!; + const trans = fitCjs(groups, histories, 2, { transience: true })!; + expect(trans.theta[1]).toBeLessThan(0); + expect(expit(trans.theta[0])).toBeCloseTo(0.85, 1); + expect(2 * (trans.loglik - shared.loglik)).toBeGreaterThan(6.6); + }); + + it('runs on the synthetic fixture without NaN', () => { + for (const sp of ['Cm', 'Na'] as const) { + const r = survival(dataset(), sp); + if (!r) continue; + for (const e of [r.phi, r.month, ...r.nurseries.map((n) => n.phi)]) { + expect(e.est).toBeGreaterThanOrEqual(0); + expect(e.est).toBeLessThanOrEqual(1); + } + } + }); +}); diff --git a/src/lib/server/analytics/survival.ts b/src/lib/server/analytics/survival.ts new file mode 100644 index 0000000..1910464 --- /dev/null +++ b/src/lib/server/analytics/survival.ts @@ -0,0 +1,386 @@ +/** + * Apparent survival within a season from mark–recapture (#42): a Cormack–Jolly–Seber model. + * + * Occasions are 14-day blocks of the season at each nursery. A pup is "seen" in a block if it was + * caught at that nursery in any set that fortnight; its history starts at its first capture there + * that season. Conditioning on first capture means pups born later in the season don't bias the + * estimate, unlike the Schnabel abundance, which assumes a closed population. + * + * φ is the chance that a pup at the nursery is still alive and still there a fortnight later: + * deaths and departures look the same, hence "apparent". Capture probability grows with that + * fortnight's net-hours, p = 1 − exp(−exp(aₙ + β·log hours)), with an intercept per nursery + * (nets catch differently at each site); a fortnight without a set has p = 0. Sets without + * recorded times count as a typical set. Maximum likelihood by BFGS, Wald intervals on the logit + * scale from a numerical Hessian. + */ +import { chiSquareP, median } from '#lib/stats'; +import type { Dataset } from '../data'; +import { fieldCaptures, seasonDay, siteName } from './common'; +import { invertSpd } from './glm'; + +export const OCCASION_DAYS = 14; + +/** One nursery-season: net-hours per occasion (0 = no set that fortnight). */ +export interface CjsGroup { + nursery: number; + hours: number[]; +} + +/** Occasions (indices into its group's `hours`) in which a pup was caught, sorted, unique. */ +export interface CjsHistory { + group: number; + seen: number[]; +} + +export interface CjsOptions { + /** One φ per nursery instead of one shared φ. */ + nurseryPhi?: boolean; + /** A separate φ for the first fortnight after first capture (transients, #42). */ + transience?: boolean; +} + +export interface CjsFit { + /** logit φ (one, or one per nursery), then τ (transience), then aₙ, then β. */ + theta: number[]; + se: (number | null)[]; + cov: number[][] | null; + loglik: number; + k: number; +} + +const LIMIT = 15; +const clampL = (v: number) => Math.max(-LIMIT, Math.min(LIMIT, v)); +const expit = (v: number) => 1 / (1 + Math.exp(-v)); +const P_MIN = 1e-9; + +function layout(nNursery: number, o: CjsOptions) { + const nPhi = o.nurseryPhi ? nNursery : 1; + const tau = o.transience ? nPhi : -1; + const a0 = nPhi + (o.transience ? 1 : 0); + return { nPhi, tau, a0, beta: a0 + nNursery, k: a0 + nNursery + 1 }; +} + +/** Log-likelihood of the histories, conditional on each pup's first capture. */ +export function cjsLogLik( + theta: number[], + groups: CjsGroup[], + histories: CjsHistory[], + nNursery: number, + o: CjsOptions = {} +): number { + const L = layout(nNursery, o); + const beta = theta[L.beta]; + const tau = L.tau >= 0 ? theta[L.tau] : 0; + const per = groups.map((g) => { + const lp = theta[o.nurseryPhi ? g.nursery : 0]; + const phi = expit(clampL(lp)); + const phi1 = expit(clampL(lp + tau)); + const a = theta[L.a0 + g.nursery]; + const p = g.hours.map((h) => + h > 0 + ? Math.min( + 1 - P_MIN, + Math.max(P_MIN, 1 - Math.exp(-Math.exp(clampL(a + beta * Math.log(h))))) + ) + : 0 + ); + // χ[t]: chance of never being caught again after occasion t (χ1 for a pup marked at t). + const T = p.length; + const chi = new Array(T).fill(1); + const chi1 = new Array(T).fill(1); + for (let t = T - 2; t >= 0; t--) { + chi[t] = 1 - phi + phi * (1 - p[t + 1]) * chi[t + 1]; + chi1[t] = 1 - phi1 + phi1 * (1 - p[t + 1]) * chi[t + 1]; + } + return { + lphi: Math.log(phi), + lphi1: Math.log(phi1), + lp: p.map((v) => (v > 0 ? Math.log(v) : -Infinity)), + lq: p.map((v) => Math.log(1 - v)), + chi, + chi1 + }; + }); + let ll = 0; + for (const h of histories) { + const g = per[h.group]; + const f = h.seen[0]; + const l = h.seen[h.seen.length - 1]; + let k = 1; + for (let t = f; t < l; t++) { + const caught = h.seen[k] === t + 1; + if (caught) k++; + ll += (t === f ? g.lphi1 : g.lphi) + (caught ? g.lp[t + 1] : g.lq[t + 1]); + } + ll += Math.log(l === f ? g.chi1[l] : g.chi[l]); + } + return ll; +} + +const dot = (a: number[], b: number[]) => a.reduce((s, v, i) => s + v * b[i], 0); + +function gradient(f: (x: number[]) => number, x: number[], h = 1e-5): number[] { + return x.map((_, i) => { + const up = x.slice(); + const dn = x.slice(); + up[i] += h; + dn[i] -= h; + return (f(up) - f(dn)) / (2 * h); + }); +} + +/** BFGS minimisation with a backtracking line search and numerical gradients. */ +function minimise(f: (x: number[]) => number, x0: number[]): { x: number[]; fx: number } { + const n = x0.length; + const eye = (): number[][] => + Array.from({ length: n }, (_, i) => x0.map((__, j) => (i === j ? 1 : 0))); + let x = x0.slice(); + let fx = f(x); + let g = gradient(f, x); + let H = eye(); + for (let it = 0; it < 500; it++) { + let d = H.map((row) => -dot(row, g)); + let slope = dot(g, d); + if (!(slope < 0)) { + H = eye(); + d = g.map((v) => -v); + slope = dot(g, d); + } + let step = 1; + let xn = x; + let fn = fx; + for (let ls = 0; ls < 50; ls++) { + xn = x.map((v, i) => v + step * d[i]); + fn = f(xn); + if (Number.isFinite(fn) && fn <= fx + 1e-4 * step * slope) break; + step /= 2; + } + if (!(fn < fx)) break; + const gn = gradient(f, xn); + const s = xn.map((v, i) => v - x[i]); + const y = gn.map((v, i) => v - g[i]); + const sy = dot(s, y); + if (sy > 1e-12) { + const rho = 1 / sy; + const Hy = H.map((row) => dot(row, y)); + const yHy = dot(y, Hy); + H = H.map((row, i) => + row.map( + (v, j) => v - rho * (s[i] * Hy[j] + Hy[i] * s[j]) + (rho * rho * yHy + rho) * s[i] * s[j] + ) + ); + } + const small = fx - fn < 1e-10 * (1 + Math.abs(fx)); + x = xn; + fx = fn; + g = gn; + if (small && Math.max(...g.map(Math.abs)) < 1e-3) break; + } + return { x, fx }; +} + +/** Numerical Hessian of f at x (central differences). */ +function hessian(f: (x: number[]) => number, x: number[], h = 1e-4): number[][] { + const n = x.length; + const at = (i: number, di: number, j: number, dj: number) => { + const y = x.slice(); + y[i] += di; + y[j] += dj; + return f(y); + }; + const out = Array.from({ length: n }, () => new Array(n).fill(0)); + for (let i = 0; i < n; i++) + for (let j = 0; j <= i; j++) { + const v = + (at(i, h, j, h) - at(i, h, j, -h) - at(i, -h, j, h) + at(i, -h, j, -h)) / (4 * h * h); + out[i][j] = v; + out[j][i] = v; + } + return out; +} + +/** Fit a CJS model; `withSe` adds Wald standard errors (skipped for the comparison models). */ +export function fitCjs( + groups: CjsGroup[], + histories: CjsHistory[], + nNursery: number, + o: CjsOptions = {}, + withSe = true +): CjsFit | null { + const L = layout(nNursery, o); + const x0 = new Array(L.k).fill(0); + for (let i = 0; i < L.nPhi; i++) x0[i] = 1.5; + for (let i = 0; i < nNursery; i++) x0[L.a0 + i] = -3; + x0[L.beta] = 1; + const f = (t: number[]) => -cjsLogLik(t, groups, histories, nNursery, o); + if (!Number.isFinite(f(x0))) return null; + const { x, fx } = minimise(f, x0); + const cov = withSe ? invertSpd(hessian(f, x)) : null; + // A logit at the edge (φ ≈ 0 or 1) has no usable Wald interval. + const se = x.map((v, i) => + cov && Math.abs(v) < LIMIT - 3 && cov[i][i] > 0 ? Math.sqrt(cov[i][i]) : null + ); + return { theta: x, se, cov, loglik: -fx, k: L.k }; +} + +export interface Est { + est: number; + lo: number | null; + hi: number | null; +} + +const phiEst = (lp: number, se: number | null, power = 1): Est => ({ + est: expit(lp) ** power, + lo: se == null ? null : expit(lp - 1.96 * se) ** power, + hi: se == null ? null : expit(lp + 1.96 * se) ** power +}); + +/** Days a pup stays on average (alive and at the nursery) when it stays a fortnight with chance φ. */ +const residence = (phi: number) => + phi >= 1 ? null : phi <= 0 ? 0 : -OCCASION_DAYS / Math.log(phi); + +export interface LrTest { + lr: number; + df: number; + p: number; +} + +export interface SurvivalResult { + species: 'Cm' | 'Na'; + histories: number; + recaptured: number; + nurseries: { + siteId: string; + name: string; + histories: number; + recaptured: number; + phi: Est; + month: Est; + }[]; + /** Shared φ per fortnight, and the share still there 30 days later. */ + phi: Est; + month: Est; + residenceDays: number | null; + /** Likelihood-ratio test: does φ differ between nurseries? */ + nurseryTest: LrTest | null; + /** φ in the first fortnight after first capture vs later fortnights, and its LR test. */ + transience: (LrTest & { first: Est; later: Est }) | null; + /** Chance of catching a pup that is there, in a fortnight with one typical set. */ + pTypicalSet: number | null; +} + +/** Nurseries need this many pups seen again (a later fortnight, same season) to get a φ. */ +const MIN_RECAPTURED = 10; + +export function survival(d: Dataset, species: 'Cm' | 'Na'): SurvivalResult | null { + const block = (date: string) => Math.floor(seasonDay(date) / OCCASION_DAYS); + const nets = d.sets.filter((s) => s.gear === 'Gillnet' && s.date && s.siteId); + const typical = + median(nets.map((s) => (s.durationMin != null && s.durationMin > 0 ? s.durationMin : null))) ?? + 150; + const hoursOf = (s: (typeof nets)[number]) => + (s.durationMin != null && s.durationMin > 0 ? s.durationMin : typical) / 60; + + // Blocks caught per pup, per nursery-season. + const caught = new Map>>(); + for (const c of fieldCaptures(d)) { + if (c.species !== species || !c.date || !c.individualId || !c.siteId) continue; + if (d.siteById.get(c.siteId)?.kind !== 'nursery') continue; + const k = `${c.season}|${c.siteId}`; + const m = caught.get(k) ?? new Map>(); + const s = m.get(c.individualId) ?? new Set(); + s.add(block(c.date)); + m.set(c.individualId, s); + caught.set(k, m); + } + const recapturedAt = new Map(); + const historiesAt = new Map(); + for (const [k, m] of caught) { + const site = k.split('|')[1]; + historiesAt.set(site, (historiesAt.get(site) ?? 0) + m.size); + const re = [...m.values()].filter((s) => s.size > 1).length; + recapturedAt.set(site, (recapturedAt.get(site) ?? 0) + re); + } + const sites = [...recapturedAt.entries()] + .filter(([, n]) => n >= MIN_RECAPTURED) + .sort((a, b) => b[1] - a[1]) + .map(([s]) => s); + if (!sites.length) return null; + const siteIdx = new Map(sites.map((s, i) => [s, i])); + + const groups: CjsGroup[] = []; + const histories: CjsHistory[] = []; + for (const [k, m] of caught) { + const [season, site] = k.split('|'); + const n = siteIdx.get(site); + if (n == null) continue; + const effort = new Map(); + for (const s of nets) + if (s.season === season && s.siteId === site) + effort.set(block(s.date!), (effort.get(block(s.date!)) ?? 0) + hoursOf(s)); + // A catch in a fortnight with no set on record still means the net was out. + for (const bs of m.values()) + for (const b of bs) if (!effort.get(b)) effort.set(b, typical / 60); + const first = Math.min(...effort.keys()); + const last = Math.max(...effort.keys()); + const hours = Array.from({ length: last - first + 1 }, (_, i) => effort.get(first + i) ?? 0); + const g = groups.length; + groups.push({ nursery: n, hours }); + for (const bs of m.values()) + histories.push({ group: g, seen: [...bs].map((b) => b - first).sort((a, b) => a - b) }); + } + const recaptured = histories.filter((h) => h.seen.length > 1).length; + if (recaptured < 20) return null; + + const K = sites.length; + const shared = fitCjs(groups, histories, K); + if (!shared) return null; + const byNursery = K > 1 ? fitCjs(groups, histories, K, { nurseryPhi: true }) : null; + const trans = fitCjs(groups, histories, K, { transience: true }); + const lrTest = (full: CjsFit | null, df: number): LrTest | null => { + if (!full) return null; + const lr = Math.max(0, 2 * (full.loglik - shared.loglik)); + return { lr, df, p: chiSquareP(lr, df) }; + }; + const transTest = lrTest(trans, 1); + + const beta = shared.theta[shared.k - 1]; + const pSet = (a: number) => 1 - Math.exp(-Math.exp(a + beta * Math.log(typical / 60))); + const pTypicalSet = median(sites.map((_, i) => pSet(shared.theta[1 + i]))); + const perMonth = 30 / OCCASION_DAYS; + return { + species, + histories: histories.length, + recaptured, + nurseries: sites.map((s, i) => { + const lp = byNursery ? byNursery.theta[i] : shared.theta[0]; + const se = byNursery ? byNursery.se[i] : shared.se[0]; + return { + siteId: s, + name: siteName(d, s), + histories: historiesAt.get(s) ?? 0, + recaptured: recapturedAt.get(s) ?? 0, + phi: phiEst(lp, se), + month: phiEst(lp, se, perMonth) + }; + }), + phi: phiEst(shared.theta[0], shared.se[0]), + month: phiEst(shared.theta[0], shared.se[0], perMonth), + residenceDays: residence(expit(shared.theta[0])), + nurseryTest: lrTest(byNursery, K - 1), + transience: + trans && transTest + ? { + ...transTest, + first: phiEst( + trans.theta[0] + trans.theta[1], + trans.cov && trans.se[0] != null && trans.se[1] != null + ? Math.sqrt(trans.cov[0][0] + trans.cov[1][1] + 2 * trans.cov[0][1]) + : null + ), + later: phiEst(trans.theta[0], trans.se[0]) + } + : null, + pTypicalSet + }; +} diff --git a/src/routes/recaptures/+page.server.ts b/src/routes/recaptures/+page.server.ts index 39975a5..b2eb722 100644 --- a/src/routes/recaptures/+page.server.ts +++ b/src/routes/recaptures/+page.server.ts @@ -7,6 +7,7 @@ import { siteName } from '#lib/server/analytics/common'; import { schnabel } from '#lib/server/analytics/population'; +import { OCCASION_DAYS, survival } from '#lib/server/analytics/survival'; import { histogram, median, pairs as xy, spearman } from '#lib/stats'; import { tableText, trendText } from '#lib/server/analytics/tests'; import type { PageServerLoad } from './$types'; @@ -99,7 +100,11 @@ export const load: PageServerLoad = () => 'nurseries' ) }; + // Apparent survival within a season (#42). + const stay = (['Cm', 'Na'] as const).map((sp) => survival(d, sp)).filter((r) => r != null); return { + stay, + occasionDays: OCCASION_DAYS, stats, abundance: { rows: est, cm: rho('Cm'), na: rho('Na') }, bySeason: rateBy((c) => c.season, d.seasons), diff --git a/src/routes/recaptures/+page.svelte b/src/routes/recaptures/+page.svelte index 6868fe4..1620976 100644 --- a/src/routes/recaptures/+page.svelte +++ b/src/routes/recaptures/+page.svelte @@ -11,6 +11,11 @@ import type { PageProps } from './$types'; let { data }: PageProps = $props(); + type Est = { est: number; lo: number | null; hi: number | null }; + const ci = (e: Est) => + e.lo != null && e.hi != null ? ` (95% interval ${pct(e.lo)}–${pct(e.hi)})` : ''; + const chi = (t: { lr: number; df: number; p: number }) => + `likelihood-ratio χ²(${t.df}) = ${num(t.lr, 1)}, ${pValue(t.p)}`;
@@ -106,6 +111,71 @@ + {#if data.stay.length} +
+

How long do pups stay?

+

+ A Cormack–Jolly–Seber model follows each tagged pup from its first capture at a nursery + through the rest of that season, in {data.occasionDays}-day steps, and separates two things + a simple recapture rate mixes up: how likely a pup is to still be there, and how likely the + net is to catch it when it is. The second rises with that fortnight's net-hours; a single + typical set catches {data.stay + .map((r) => `${pct(r.pTypicalSet)} of the ${speciesName(r.species).toLowerCase()} pups`) + .join(' and ')} present. Because each pup enters at its own first capture, pups born later in + the season don't bias the answer. +

+

+ {#each data.stay as r (r.species)} + {speciesName(r.species)}: {pct(r.month.est)} of pups are still at their nursery 30 days later{ci( + r.month + )}, an average stay of about {num(r.residenceDays)} days ({num(r.histories)} + pups, {`${num(r.recaptured)} seen again later in the season). `} + {/each} +

+

+ "Still there" means alive and not moved away: the model can't tell a pup that died from one + that left, and a pup that moved to another nursery counts as gone (the movement chart above + shows how often recaptures cross nurseries). Nurseries need at least ten pups seen again + within a season to get their own estimate. +

+
+ {#each data.stay as r (r.species)} + + `${n.name} (${n.histories})`)} + series={[ + { + name: 'Still there after 30 days', + color: SPECIES[r.species].color, + values: r.nurseries.map((n) => n.month.est) + } + ]} + errors={r.nurseries.map((n) => + n.month.lo != null && n.month.hi != null ? [n.month.lo, n.month.hi] : null + )} + valueFormat={(v) => pct(v)} + /> + + {/each} +
+
+ {/if} +

Longest moves between nurseries