From dfa4b715e8dd5e106e00a85c681d6faf38373164 Mon Sep 17 00:00:00 2001 From: luen Date: Wed, 4 Nov 2026 09:01:04 +1000 Subject: [PATCH] Charts: statistics behind every trend and difference (#119, #118, #120) - analytics/tests.ts: negative-binomial likelihood-ratio tests of catch rates (raw and adjusted for nursery, season and day of the season, naming what was adjusted), per-group rate ratios, and worded Kruskal-Wallis, chi2, trend, linear-fit/Spearman and Welch tests. stats.ts gains kruskal and pairedT. - ChartCard `stats` line, used on the overview, seasons, nurseries, nursery profiles, morphometrics, neonates, growth, recaptures, physiology, drivers, ocean, tides, moon, time of day, pressure, effort, water quality and adults. - Moon finding (#118): names a best phase only when the phases differ beyond chance; otherwise reports no effect, as Debaere et al. (2024) did. - Overview catch rate per season (#120): adjusted season test and the seasons whose interval excludes the average (2018-19 and 2019-20 lemons). - Nursery, weekend and heat-stress findings report their tests. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 + src/lib/components/ChartCard.svelte | 26 +++ src/lib/server/analytics/findings.ts | 64 ++++-- src/lib/server/analytics/tests.test.ts | 101 +++++++++ src/lib/server/analytics/tests.ts | 220 ++++++++++++++++++++ src/lib/stats.test.ts | 27 +++ src/lib/stats.ts | 41 ++++ src/routes/+page.server.ts | 26 +++ src/routes/+page.svelte | 1 + src/routes/adults/+page.server.ts | 42 +++- src/routes/adults/+page.svelte | 8 +- src/routes/drivers/+page.server.ts | 19 ++ src/routes/drivers/+page.svelte | 15 +- src/routes/effort/+page.server.ts | 15 ++ src/routes/effort/+page.svelte | 2 + src/routes/growth/+page.server.ts | 59 +++++- src/routes/growth/+page.svelte | 8 +- src/routes/moon/+page.server.ts | 13 ++ src/routes/moon/+page.svelte | 4 + src/routes/morphometrics/+page.server.ts | 54 +++++ src/routes/morphometrics/+page.svelte | 11 +- src/routes/neonates/+page.server.ts | 59 ++++++ src/routes/neonates/+page.svelte | 5 + src/routes/nurseries/+page.server.ts | 12 +- src/routes/nurseries/+page.svelte | 1 + src/routes/nurseries/[site]/+page.server.ts | 9 + src/routes/nurseries/[site]/+page.svelte | 1 + src/routes/ocean/+page.server.ts | 9 + src/routes/ocean/+page.svelte | 1 + src/routes/physiology/+page.server.ts | 26 ++- src/routes/physiology/+page.svelte | 11 +- src/routes/pressure/+page.server.ts | 46 +++- src/routes/pressure/+page.svelte | 18 +- src/routes/recaptures/+page.server.ts | 17 ++ src/routes/recaptures/+page.svelte | 3 +- src/routes/seasons/+page.server.ts | 44 +++- src/routes/seasons/+page.svelte | 5 + src/routes/tides/+page.server.ts | 30 ++- src/routes/tides/+page.svelte | 9 +- src/routes/time-of-day/+page.server.ts | 45 ++++ src/routes/time-of-day/+page.svelte | 4 + src/routes/water-quality/+page.server.ts | 17 ++ src/routes/water-quality/+page.svelte | 6 +- 43 files changed, 1091 insertions(+), 45 deletions(-) create mode 100644 src/lib/server/analytics/tests.test.ts create mode 100644 src/lib/server/analytics/tests.ts diff --git a/AGENTS.md b/AGENTS.md index 2e7ad02..f9cb6ae 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -46,6 +46,7 @@ src/lib/server/analytics common.ts (CPUE, Fulton's K, recapture pairs…) · env diet.ts (gastric lavage: fullness, prey groups) events.ts (cyclones and heavy-rain days vs catches) glm.ts (NB/Poisson GLM, splines) · catchModel.ts (joint catch model) + 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, school holidays (schoolDays) and the one-label-per-date dayType @@ -115,6 +116,7 @@ Drop the workbook in `data/` named like `Physioshark_Shark Log 2026-2027.xlsx` ( - Follow the dataviz method: categorical slots in fixed order (`--series-1…8`, validated light and dark), sequential = one hue (`--seq-*`), diverging = blue ↔ red with a neutral midpoint, one y-axis only (never dual axes), legends for ≥ 2 series, text in ink tokens (never the series colour), 4 px rounded bar ends, 2 px lines, hover tooltips, data tables via `ChartCard table`. - Every chart registers its data with the enclosing `ChartCard` (`registerCsv` in `charts/csv.ts`), which shows **Download CSV**. A new chart component must call `registerCsv` too. An explicit `ChartCard table` takes precedence. +- Back every trend, relationship or group difference with a test (#119): compute it in the load function with `analytics/tests.ts` and pass the sentence to `ChartCard stats`. Catch rates: `rateTest`/`rateText` (negative-binomial LRT with log net-hours offset, raw and adjusted for nursery, season and day of the season; pass `skip` for the factor under test). Values across groups: `groupsText` (Kruskal–Wallis). Shares: `tableText` (χ²). One value per season: `trendText`. Scatters: `fitText` (R², p, Spearman) or `rankText`. Copy and findings that name a "best" or "highest" group must check the test first (the moon finding picked the best of eight phases, #118). - Cite the study behind a chart with `` (ids in `src/lib/publications.ts`). Link only papers that analysed the same question with this dataset; check the abstract first. PDFs are served at `rummerlab.com/papers/` (metadata in the rummerlab-website repo, `data/papers.json`). - Species colours come from `src/lib/species.ts` (blacktip = slot 1, sicklefin lemon = slot 2). - Charts measure their width (`bind:clientWidth`) and carry a `viewBox` so pre-hydration renders scale down instead of overflowing. diff --git a/src/lib/components/ChartCard.svelte b/src/lib/components/ChartCard.svelte index bbf875a..ec5df09 100644 --- a/src/lib/components/ChartCard.svelte +++ b/src/lib/components/ChartCard.svelte @@ -8,6 +8,7 @@ title, subtitle, note, + stats, source, id, table, @@ -17,6 +18,8 @@ title: string; subtitle?: string; note?: string; + /** The test behind the chart's pattern (#119); nulls (too little data) are skipped. */ + stats?: string | null | (string | null | undefined)[]; source?: string; id?: string; table?: { columns: Column[]; rows: Record[] }; @@ -25,6 +28,10 @@ children: Snippet; } = $props(); + const statLines = $derived( + (Array.isArray(stats) ? stats : [stats]).filter((x): x is string => !!x) + ); + // Charts inside the card register their data; the button needs JS, so it appears on mount. const sources = collectCsv(); let canDownload = $state(false); @@ -58,6 +65,9 @@
{@render children()}
{#if note}

{note}

{/if} + {#if statLines.length} +

Statistics {statLines.join(' ')}

+ {/if} {#if table && table.rows.length}
Show data ({table.rows.length} rows) @@ -107,6 +117,22 @@ margin: 10px 0 0; line-height: 1.5; } + .stats { + font-size: 0.82rem; + color: var(--ink-2); + margin: 8px 0 0; + line-height: 1.5; + font-variant-numeric: tabular-nums; + } + .stats .k { + display: inline-block; + font-size: 0.7rem; + font-weight: 650; + letter-spacing: 0.06em; + text-transform: uppercase; + color: var(--accent); + margin-right: 4px; + } .papers { font-size: 0.78rem; color: var(--ink-2); diff --git a/src/lib/server/analytics/findings.ts b/src/lib/server/analytics/findings.ts index 8de249f..34cfd05 100644 --- a/src/lib/server/analytics/findings.ts +++ b/src/lib/server/analytics/findings.ts @@ -2,7 +2,7 @@ * Auto-generated findings (#55): records, quirks and patterns computed live from the data, so * they update when a new season's workbook is added. Each links to the page with the chart. */ -import { clock, date, num, pct, season as seasonFmt } from '#lib/format'; +import { clock, date, num, pct, pValue, season as seasonFmt } from '#lib/format'; import { speciesName } from '#lib/species'; import { binomTestHalf, mean, median, pairs, spearman } from '#lib/stats'; import { moonPhaseName } from '../astro'; @@ -22,6 +22,7 @@ import { catchModel } from './catchModel'; import { cloudWater } from './cloud'; import { diet } from './diet'; import { dailyMaxBySite, versusSst } from './insitu'; +import { rateTest } from './tests'; export interface Finding { id: string; @@ -71,23 +72,39 @@ function compute(d: Dataset): Finding[] { }); } - // Moon phase - const phases = Array.from({ length: 8 }, (_, i) => - eff.filter((s) => s.moonPhase != null && Math.round(s.moonPhase * 8) % 8 === i) - ); + // Moon phase (#118): name a best phase only if the phases differ beyond chance. Picking the + // highest of eight raw rates always finds a "best" one. + const phaseOf = (s: (typeof eff)[number]) => + s.moonPhase == null ? null : Math.round(s.moonPhase * 8) % 8; + const phases = Array.from({ length: 8 }, (_, i) => eff.filter((s) => phaseOf(s) === i)); const phaseCpue = phases.map((p) => ({ n: p.length, cpue: cpueOf(p) })); const valid = phaseCpue.map((p, i) => ({ ...p, i })).filter((p) => p.n >= 25 && p.cpue != null); - if (valid.length >= 4) { + const moonTest = rateTest(eff, { groupOf: phaseOf }); + if (valid.length >= 4 && moonTest) { const best = valid.reduce((a, b) => (b.cpue! > a.cpue! ? b : a)); const worst = valid.reduce((a, b) => (b.cpue! < a.cpue! ? b : a)); - out.push({ - id: 'moon', - kind: 'pattern', - title: 'Best moon for finding pups', - value: moonPhaseName(best.i / 8), - text: `Nets set around the ${moonPhaseName(best.i / 8).toLowerCase()} caught ${num(best.cpue!, 2)} sharks per net-hour, against ${num(worst.cpue!, 2)} around the ${moonPhaseName(worst.i / 8).toLowerCase()} (${best.n} and ${worst.n} sets).`, - href: '/moon' - }); + const p = moonTest.adjusted?.p ?? moonTest.raw.p; + const test = `negative-binomial test across all eight phases, adjusted for ${moonTest.adjustedFor}: ${pValue(p)}, ${num(moonTest.n)} sets`; + const phase = (i: number) => moonPhaseName(i / 8).toLowerCase(); + out.push( + p < 0.05 + ? { + id: 'moon', + kind: 'pattern', + title: 'Best moon for finding pups', + value: moonPhaseName(best.i / 8), + text: `Nets set around the ${phase(best.i)} caught ${num(best.cpue!, 2)} sharks per net-hour, against ${num(worst.cpue!, 2)} around the ${phase(worst.i)}; the phases differ beyond chance (${test}).`, + href: '/moon' + } + : { + id: 'moon', + kind: 'pattern', + title: "The moon doesn't change the catch", + value: 'No effect', + text: `The ${phase(best.i)} (${num(best.cpue!, 2)} sharks per net-hour) and the ${phase(worst.i)} (${num(worst.cpue!, 2)}) look different, but across all eight phases the spread is what chance alone produces (${test}). Debaere et al. (2024) reached the same conclusion with this dataset.`, + href: '/moon' + } + ); } // Timing after sunset @@ -207,6 +224,12 @@ function compute(d: Dataset): Finding[] { cm: cpueOf(x.sets, 'cpueCm')! })); if (siteCpue.length) { + const nurseryTest = rateTest( + eff.filter((s) => siteCpue.some((x) => x.id === s.siteId)), + { groupOf: (s) => s.siteId }, + 'cpue', + ['nursery'] + ); const top = siteCpue.reduce((a, b) => (b.cpue > a.cpue ? b : a)); const low = siteCpue.reduce((a, b) => (b.cpue < a.cpue ? b : a)); out.push({ @@ -214,7 +237,7 @@ function compute(d: Dataset): Finding[] { kind: 'pattern', title: 'Most productive nursery', value: siteName(d, top.id), - text: `${num(top.cpue, 2)} sharks per net-hour on average, ${num(top.cpue / low.cpue, 1)}× the rate at ${siteName(d, low.id)} (${num(low.cpue, 2)}).`, + text: `${num(top.cpue, 2)} sharks per net-hour on average, ${num(top.cpue / low.cpue, 1)}× the rate at ${siteName(d, low.id)} (${num(low.cpue, 2)}).${nurseryTest ? ` Nurseries differ ${(nurseryTest.adjusted?.p ?? nurseryTest.raw.p) < 0.05 ? 'well beyond' : 'no more than'} chance (negative-binomial test, adjusted for ${nurseryTest.adjustedFor}: ${pValue(nurseryTest.adjusted?.p ?? nurseryTest.raw.p)}).` : ''}`, href: `/nurseries/${top.id}` }); const lemon = siteCpue.reduce((a, b) => (b.na / (b.cpue || 1) > a.na / (a.cpue || 1) ? b : a)); @@ -350,15 +373,20 @@ function compute(d: Dataset): Finding[] { const wk = eff.filter((s) => s.weekday != null); const weekend = cpueOf(wk.filter((s) => s.weekday === 0 || s.weekday === 6)); const weekday = cpueOf(wk.filter((s) => s.weekday !== 0 && s.weekday !== 6)); - if (weekend != null && weekday != null) + const weekendTest = rateTest(wk, { + groupOf: (s) => (s.weekday === 0 || s.weekday === 6 ? 'weekend' : 'weekday') + }); + if (weekend != null && weekday != null && weekendTest) { + const p = weekendTest.adjusted?.p ?? weekendTest.raw.p; out.push({ id: 'weekend', kind: 'quirk', title: 'Weekend effect?', value: `${num(weekend, 2)} vs ${num(weekday, 2)}`, - text: `Sharks per net-hour on weekend nights against weeknights. Weekends bring more people to the beaches; ${weekend < weekday ? 'catches are a little lower then' : 'catches are no lower then'}.`, + text: `Sharks per net-hour on weekend nights against weeknights. Weekends bring more people to the beaches, but ${p < 0.05 ? `catches really are ${weekend < weekday ? 'lower' : 'higher'} then` : 'the gap is within chance'} (negative-binomial test adjusted for ${weekendTest.adjustedFor}: ${pValue(p)}).`, href: '/drivers' }); + } // Strongest driver const vars: [string, keyof (typeof eff)[number]][] = [ @@ -462,7 +490,7 @@ function compute(d: Dataset): Finding[] { kind: 'pattern', title: 'Heat stress and newborn condition', value: `ρ = ${num(kr.rho, 2)}`, - text: `Correlation between Coral Reef Watch degree heating weeks on the capture date and the body condition (Fulton's K) of newborn blacktips (n = ${num(kr.n)}).`, + text: `Correlation between Coral Reef Watch degree heating weeks on the capture date and the body condition (Fulton's K) of newborn blacktips (n = ${num(kr.n)}, ${pValue(kr.p)}${kr.p < 0.05 ? '' : ': no more than chance'}).`, href: '/ocean' }); diff --git a/src/lib/server/analytics/tests.test.ts b/src/lib/server/analytics/tests.test.ts new file mode 100644 index 0000000..62c17ee --- /dev/null +++ b/src/lib/server/analytics/tests.test.ts @@ -0,0 +1,101 @@ +import { describe, expect, it } from 'vitest'; +import type { SetRow } from '../data'; +import { groupsText, rateEffects, rateTest, rateText, tableText, trendText } from './tests'; + +/** 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; + }; +} + +/** Poisson draw by inversion (small means). */ +function poisson(u: () => number, mu: number) { + let k = 0; + let p = Math.exp(-mu); + let s = p; + const x = u(); + while (x > s && k < 200) { + k++; + p *= mu / k; + s += p; + } + return k; +} + +/** Synthetic timed sets: two nurseries, three seasons, a group factor with given rate ratios. */ +function sets(seed: number, ratio: Record): SetRow[] { + const u = rng(seed); + const groups = Object.keys(ratio); + return Array.from({ length: 600 }, (_, i) => { + // Blocks of seven so groups don't line up with nursery (i % 2) or season (i % 3). + const g = groups[Math.floor(i / 7) % groups.length]; + const hours = 1.5 + u(); + const n = poisson(u, 0.8 * hours * ratio[g]); + const month = ['10', '11', '12', '01'][i % 4]; + const year = month === '01' ? 2020 : 2019; + return { + id: i, + season: ['2019-2020', '2020-2021', '2021-2022'][i % 3], + siteId: i % 2 ? 'a' : 'b', + date: `${year + (i % 3)}-${month}-${String(1 + (i % 27)).padStart(2, '0')}`, + durationMin: hours * 60, + nTotal: n, + cpue: n / hours, + cpueCm: n / hours, + cpueNa: 0, + group: g + } as unknown as SetRow; + }); +} +const groupOf = (s: SetRow) => (s as unknown as { group: string }).group; + +describe('chart statistics (#119)', () => { + it('finds a real catch-rate difference between groups and names the adjustment', () => { + const t = rateTest(sets(3, { x: 1, y: 2 }), { groupOf })!; + expect(t.df).toBe(1); + expect(t.raw.p).toBeLessThan(0.001); + expect(t.adjusted!.p).toBeLessThan(0.001); + expect(t.adjustedFor).toBe('nursery, season and day of the season'); + expect(rateText(t, 'groups')).toMatch(/^Catch rates differ between groups/); + const fx = rateEffects(sets(3, { x: 1, y: 2 }), groupOf)!; + expect(fx[1].rr / fx[0].rr).toBeGreaterThan(1.6); + expect(fx[1].rr / fx[0].rr).toBeLessThan(2.5); + }); + + it('does not invent a difference, and skips the adjustment being tested', () => { + const t = rateTest(sets(5, { x: 1, y: 1, z: 1 }), { groupOf }, 'cpue', ['nursery'])!; + expect(t.adjusted!.p).toBeGreaterThan(0.05); + expect(t.adjustedFor).toBe('season and day of the season'); + expect(rateText(t, 'groups')).toMatch(/^No detectable difference/); + }); + + it('words trends, rank tests and tables', () => { + expect(trendText([1, 2, 3, 4, 5, 6], 'mm')).toMatch( + /^Trend across 6 seasons: \+1\.0 mm per season \(R² = 1\.00/ + ); + expect(trendText([1, null, 2], 'mm')).toBeNull(); + expect( + groupsText( + [ + [1, 2, 3, 4], + [11, 12, 13, 14] + ], + 'groups' + ) + ).toMatch(/^Differs between groups \(Kruskal–Wallis H = 5\.3, df = 1/); + expect( + tableText( + [ + [10, 20], + [20, 10] + ], + 'groups' + ) + ).toBe('Differs between groups (χ²(1) = 6.7, p = 0.010).'); + }); +}); diff --git a/src/lib/server/analytics/tests.ts b/src/lib/server/analytics/tests.ts new file mode 100644 index 0000000..e8ee926 --- /dev/null +++ b/src/lib/server/analytics/tests.ts @@ -0,0 +1,220 @@ +/** + * Statistics behind the charts (#119): the right test for each kind of chart, worded the same way + * everywhere for ChartCard's `stats` line. Catch rates use negative-binomial models of the counts + * with log(net-hours) as the offset, so long and short sets weigh correctly; "adjusted" adds + * nursery, season and a smooth for the day of the season, the calendar that confounds most + * comparisons (#54). Each helper returns null when there is too little data to test. + */ +import { num, pValue } from '#lib/format'; +import { + chiSquare, + chiSquareP, + kruskal, + linearFit, + quantile, + spearman, + welch, + type Num +} from '#lib/stats'; +import type { SetRow } from '../data'; +import { seasonDay } from './common'; +import { contrast, fitGlm, naturalSpline } from './glm'; + +export type RateKey = 'cpue' | 'cpueCm' | 'cpueNa'; + +const count = (s: SetRow, key: RateKey) => Math.round((s[key] ?? 0) * (s.durationMin! / 60)); +const effectCode = (levels: string[], v: string) => + levels.slice(0, -1).map((l) => (v === levels[levels.length - 1] ? -1 : v === l ? 1 : 0)); + +type Confounder = 'nursery' | 'season'; + +/** + * Columns for nursery (≥ 10 sets, the rest pooled), season and a day-of-season spline, and a + * label naming what they actually adjust for (a factor with one level adjusts for nothing). + */ +function calendar(rows: SetRow[], skip: Confounder[] = []) { + const perSite = new Map(); + for (const s of rows) perSite.set(s.siteId ?? '', (perSite.get(s.siteId ?? '') ?? 0) + 1); + const site = (s: SetRow) => ((perSite.get(s.siteId ?? '') ?? 0) >= 10 ? s.siteId! : 'other'); + const sites = [...new Set(rows.map(site))].sort(); + const seasons = [...new Set(rows.map((s) => s.season))].sort(); + const days = rows.map((s) => seasonDay(s.date!)); + const knots = [0, 0.25, 0.5, 0.75, 1].map((q) => quantile(days, q)!); + const spline = new Set(knots).size === knots.length ? naturalSpline(knots) : () => []; + const useSite = !skip.includes('nursery') && sites.length > 1; + const useSeason = !skip.includes('season') && seasons.length > 1; + const parts = [ + ...(useSite ? ['nursery'] : []), + ...(useSeason ? ['season'] : []), + 'day of the season' + ]; + const label = + parts.length > 1 ? `${parts.slice(0, -1).join(', ')} and ${parts.at(-1)}` : parts[0]; + const cols = rows.map((s, i) => [ + ...spline(days[i]), + ...(useSite ? effectCode(sites, site(s)) : []), + ...(useSeason ? effectCode(seasons, s.season) : []) + ]); + return { cols, label }; +} + +export interface RateTest { + n: number; + df: number; + raw: { lr: number; p: number }; + adjusted: { lr: number; p: number } | null; + /** What the adjusted test holds fixed, e.g. "season and day of the season". */ + adjustedFor: string; +} + +/** + * Do catch rates differ between groups (`groupOf`), or change with a number (`valueOf`)? A + * likelihood-ratio test of that term, raw and with the calendar adjustment. `skip` leaves out + * the adjustment the term itself is (testing nurseries, don't also adjust for nursery). + */ +export function rateTest( + sets: SetRow[], + term: + | { groupOf: (s: SetRow) => string | number | null | undefined } + | { valueOf: (s: SetRow) => number | null | undefined }, + key: RateKey = 'cpue', + skip: Confounder[] = [] +): RateTest | null { + const get = 'groupOf' in term ? term.groupOf : term.valueOf; + const rows = sets.filter( + (s) => s.cpue != null && s.durationMin && s.date && get(s) != null && s.season + ); + const levels = + 'groupOf' in term ? [...new Set(rows.map((s) => String(term.groupOf(s))))].sort() : []; + if (rows.length < 20 || ('groupOf' in term && levels.length < 2)) return null; + const cols = (s: SetRow) => + 'groupOf' in term ? effectCode(levels, String(term.groupOf(s))) : [Number(term.valueOf(s))]; + const y = rows.map((s) => count(s, key)); + if (!y.some((v) => v > 0)) return null; + const offset = rows.map((s) => Math.log(s.durationMin! / 60)); + const lrt = (base: number[][]) => { + const f0 = fitGlm(base, y, offset); + const f1 = fitGlm( + base.map((r, i) => [...r, ...cols(rows[i])]), + y, + offset + ); + if (!f0 || !f1) return null; + const lr = Math.max(0, 2 * (f1.loglik - f0.loglik)); + return { lr, p: chiSquareP(lr, df) }; + }; + const df = 'groupOf' in term ? levels.length - 1 : 1; + const raw = lrt(rows.map(() => [1])); + if (!raw) return null; + const cal = calendar(rows, skip); + const adjusted = lrt(rows.map((_, i) => [1, ...cal.cols[i]])); + return { n: rows.length, df, raw, adjusted, adjustedFor: cal.label }; +} + +/** + * Each group's catch rate relative to the average group (rate ratio with 95% interval), from the + * adjusted model: what "this season was unusual" means once nursery and calendar are held fixed. + */ +export function rateEffects( + sets: SetRow[], + groupOf: (s: SetRow) => string | null | undefined, + key: RateKey = 'cpue', + skip: Confounder[] = [] +) { + const rows = sets.filter((s) => s.cpue != null && s.durationMin && s.date && groupOf(s) != null); + const levels = [...new Set(rows.map((s) => groupOf(s)!))].sort(); + if (rows.length < 20 || levels.length < 2) return null; + const cal = calendar(rows, skip); + const X = rows.map((s, i) => [1, ...cal.cols[i], ...effectCode(levels, groupOf(s)!)]); + const fit = fitGlm( + X, + rows.map((s) => count(s, key)), + rows.map((s) => Math.log(s.durationMin! / 60)) + ); + if (!fit) return null; + const p = X[0].length; + const g0 = p - (levels.length - 1); + return levels.map((level, i) => { + const g = Array.from({ length: p }, (_, k) => + k < g0 ? 0 : i === levels.length - 1 ? -1 : k - g0 === i ? 1 : 0 + ); + const c = contrast(fit, g); + return { level, rr: Math.exp(c.est), lo: Math.exp(c.lo), hi: Math.exp(c.hi), p: c.p }; + }); +} + +const chi = (lr: number, df: number) => `χ²(${df}) = ${num(lr, 1)}`; + +/** "Catch rates differ between moon phases (…)" or "No detectable difference … (…)". */ +export function rateText(t: RateTest | null, what: string): string | null { + if (!t) return null; + const p = t.adjusted?.p ?? t.raw.p; + const head = + p < 0.05 + ? `Catch rates differ between ${what}` + : `No detectable difference in catch rate between ${what}`; + const adj = t.adjusted + ? `; adjusted for ${t.adjustedFor}, ${chi(t.adjusted.lr, t.df)}, ${pValue(t.adjusted.p)}` + : ''; + return `${head} (negative-binomial likelihood-ratio test on ${num(t.n)} timed sets: raw ${chi(t.raw.lr, t.df)}, ${pValue(t.raw.p)}${adj}).`; +} + +/** Same for a numeric term: "Catch rate does (not) change with …". */ +export function rateSlopeText(t: RateTest | null, what: string): string | null { + if (!t) return null; + const p = t.adjusted?.p ?? t.raw.p; + const head = + p < 0.05 + ? `Catch rate changes with ${what}` + : `No detectable change in catch rate with ${what}`; + const adj = t.adjusted ? `; adjusted for ${t.adjustedFor}, ${pValue(t.adjusted.p)}` : ''; + return `${head} (negative-binomial likelihood-ratio test on ${num(t.n)} timed sets: raw ${pValue(t.raw.p)}${adj}).`; +} + +/** Kruskal–Wallis across groups of values. */ +export function groupsText(groups: Num[][], what: string): string | null { + const k = kruskal(groups.filter((g) => g.length >= 3)); + if (!k) return null; + return `${k.p < 0.05 ? 'Differs' : 'No detectable difference'} between ${what} (Kruskal–Wallis H = ${num(k.h, 1)}, df = ${k.df}, ${pValue(k.p)}, n = ${num(k.n)}).`; +} + +/** Linear fit and Spearman rank correlation for a scatter. */ +export function fitText(xy: [number, number][], unit = ''): string | null { + const f = linearFit(xy); + const r = spearman(xy); + if (!f || !r) return null; + const slope = `${f.slope >= 0 ? '+' : '−'}${num(Math.abs(f.slope), Math.abs(f.slope) < 1 ? 3 : 1)}${unit ? ` ${unit}` : ''}`; + return `Linear fit: slope ${slope}, R² = ${num(f.r2, 2)}, ${pValue(f.p)}; Spearman ρ = ${num(r.rho, 2)}, ${pValue(r.p)} (n = ${num(f.n)}).`; +} + +/** Spearman only, for monotonic but not necessarily linear relationships and small n. */ +export function rankText(xy: [number, number][]): string | null { + const r = spearman(xy); + if (!r) return null; + return `Spearman ρ = ${num(r.rho, 2)}, ${pValue(r.p)} (n = ${num(r.n)}).`; +} + +/** Linear trend of one value per season (or year: `per`), index 0, 1, 2 …, with R². */ +export function trendText(values: Num[], unit = '', per = 'season'): string | null { + const xy = values + .map((v, i) => [i, v] as [number, Num]) + .filter((p): p is [number, number] => p[1] != null && Number.isFinite(p[1])); + const f = linearFit(xy); + if (!f || xy.length < 5) return null; + const step = `${f.slope >= 0 ? '+' : '−'}${num(Math.abs(f.slope), Math.abs(f.slope) < 1 ? 3 : 1)}${unit ? ` ${unit}` : ''}`; + return `${f.p < 0.05 ? 'Trend' : 'No significant trend'} across ${xy.length} ${per}s: ${step} per ${per} (R² = ${num(f.r2, 2)}, ${pValue(f.p)}).`; +} + +/** χ² test of a table of counts (rows = groups, columns = outcomes). */ +export function tableText(table: number[][], what: string): string | null { + const c = chiSquare(table.filter((r) => r.reduce((a, b) => a + b, 0) >= 5)); + if (!c) return null; + return `${c.p < 0.05 ? 'Differs' : 'No detectable difference'} between ${what} (χ²(${c.df}) = ${num(c.stat, 1)}, ${pValue(c.p)}).`; +} + +/** Welch's t-test between two groups. */ +export function twoGroupText(a: Num[], b: Num[], what: string, unit = ''): string | null { + const w = welch(a, b); + if (!w) return null; + return `${w.p < 0.05 ? 'Differs' : 'No detectable difference'} between ${what}: ${w.diff >= 0 ? '+' : '−'}${num(Math.abs(w.diff), 1)}${unit ? ` ${unit}` : ''} (Welch's t-test ${pValue(w.p)}).`; +} diff --git a/src/lib/stats.test.ts b/src/lib/stats.test.ts index 83877e8..94f0e5b 100644 --- a/src/lib/stats.test.ts +++ b/src/lib/stats.test.ts @@ -5,9 +5,11 @@ import { chiSquare, chiSquareP, histogram, + kruskal, linearFit, median, normalP, + pairedT, powerFit, quantile, spearman, @@ -80,3 +82,28 @@ describe('chi-square', () => { expect(chiSquare([[5, 5]])).toBeNull(); }); }); + +describe('rank and paired tests (#119)', () => { + it('computes Kruskal–Wallis H by hand', () => { + // Ranks 1–3 vs 4–6: H = 12/42 · (6²/3 + 15²/3) − 21 = 3.857. + const r = kruskal([ + [1, 2, 3], + [4, 5, 6] + ])!; + expect(r.h).toBeCloseTo(3.857, 3); + expect(r.df).toBe(1); + expect(r.p).toBeCloseTo(0.0495, 3); + expect(kruskal([[1, 2, 3]])).toBeNull(); + }); + it('runs a paired t-test on the differences', () => { + const r = pairedT([ + [1, 2], + [2, 4], + [3, 5], + [4, 7] + ])!; + expect(r.diff).toBe(2); + expect(r.t).toBeCloseTo(4.899, 3); + expect(r.p).toBeCloseTo(0.0163, 3); + }); +}); diff --git a/src/lib/stats.ts b/src/lib/stats.ts index e492686..53e2f7a 100644 --- a/src/lib/stats.ts +++ b/src/lib/stats.ts @@ -327,6 +327,47 @@ export function welch( return { t, df, p: tTestP(t, df), diff: mx - my }; } +/** Paired t-test of b − a (e.g. second vs first blood draw of the same shark). */ +export function pairedT( + pairs: [number, number][] +): { t: number; df: number; p: number; diff: number } | null { + const d = pairs + .filter(([a, b]) => Number.isFinite(a) && Number.isFinite(b)) + .map(([a, b]) => b - a); + if (d.length < 3) return null; + const m = mean(d)!; + const s = sd(d)!; + if (!s) return null; + const t = m / (s / Math.sqrt(d.length)); + return { t, df: d.length - 1, p: tTestP(t, d.length - 1), diff: m }; +} + +/** Kruskal–Wallis test across groups (rank-based one-way ANOVA), with the tie correction. */ +export function kruskal(groups: Num[][]): { h: number; df: number; p: number; n: number } | null { + const gs = groups.map(finite).filter((g) => g.length > 0); + if (gs.length < 2) return null; + const all = gs.flatMap((g, k) => g.map((v) => [v, k] as const)).sort((a, b) => a[0] - b[0]); + const n = all.length; + const rankSum = new Array(gs.length).fill(0); + let ties = 0; + for (let i = 0; i < n;) { + let j = i; + while (j + 1 < n && all[j + 1][0] === all[i][0]) j++; + const r = (i + j) / 2 + 1; + for (let k = i; k <= j; k++) rankSum[all[k][1]] += r; + const t = j - i + 1; + ties += t ** 3 - t; + i = j + 1; + } + const c = 1 - ties / (n ** 3 - n); + if (n < 3 || c <= 0) return null; + const h = + ((12 / (n * (n + 1))) * gs.reduce((a, g, k) => a + rankSum[k] ** 2 / g.length, 0) - + 3 * (n + 1)) / + c; + return { h, df: gs.length - 1, p: chiSquareP(h, gs.length - 1), n }; +} + // --- grouping ---------------------------------------------------------------------------------- export function groupBy( diff --git a/src/routes/+page.server.ts b/src/routes/+page.server.ts index 6d88ed4..9908a77 100644 --- a/src/routes/+page.server.ts +++ b/src/routes/+page.server.ts @@ -9,6 +9,8 @@ import { siteName } from '#lib/server/analytics/common'; import { topFindings } from '#lib/server/analytics/findings'; +import { rateEffects, rateTest, trendText } from '#lib/server/analytics/tests'; +import { num, pValue, season as seasonFmt } from '#lib/format'; import type { PageServerLoad } from './$types'; export const load: PageServerLoad = () => @@ -34,6 +36,29 @@ export const load: PageServerLoad = () => }; }); + // Do seasons differ beyond chance once nursery and time of season are held fixed (#120)? + const seasonStats = (['cpueCm', 'cpueNa'] as const).map((key) => { + const name = key === 'cpueCm' ? 'Blacktips' : 'Sicklefin lemons'; + const t = rateTest(eff, { groupOf: (s) => s.season }, key, ['season']); + if (!t?.adjusted) return null; + const unusual = (rateEffects(eff, (s) => s.season, key, ['season']) ?? []).filter( + (e) => e.lo > 1 || e.hi < 1 + ); + const differ = t.adjusted.p < 0.05; + return [ + `${name}: seasons ${differ ? 'differ beyond chance' : 'do not differ beyond chance'} once nursery and day of the season are held fixed (negative-binomial test, ${pValue(t.adjusted.p)}).`, + differ && unusual.length + ? `Unusual seasons: ${unusual.map((e) => `${seasonFmt(e.level)} ${num(e.rr, 2)}× the average season (95% interval ${num(e.lo, 2)}–${num(e.hi, 2)})`).join('; ')}.` + : '', + trendText( + perSeason.map((s) => s[key]), + 'sharks per net-hour' + ) ?? '' + ] + .filter(Boolean) + .join(' '); + }); + const months = [8, 9, 10, 11, 12, 1, 2, 3, 4, 5]; const byMonth = months.map((m) => ({ month: m, @@ -70,6 +95,7 @@ export const load: PageServerLoad = () => }); return { + seasonStats, kpi: { captures: caps.length, individuals: new Set(caps.map((c) => c.individualId)).size, diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte index 3414cf1..cb1c2fa 100644 --- a/src/routes/+page.svelte +++ b/src/routes/+page.svelte @@ -106,6 +106,7 @@ title="Catch rate per season" papers={['eustache2024density']} subtitle="Sharks per net-hour of gillnetting (2013–14 logs have no set times)" + stats={data.seasonStats} > @@ -24,7 +26,45 @@ export const load: PageServerLoad = () => return times.length ? times[0] - e.baitInMin! : null; }) .filter((v): v is number => v != null && v >= 0); + // Pregnant females vs other females at the same length: girth residuals from a line fitted + // to the non-pregnant sharks. + const girthFit = linearFit( + a + .filter((x) => x.tlMm && x.pecGirthMm && x.pregnant !== 'Y') + .map((x) => [x.tlMm!, x.pecGirthMm!] as [number, number]) + ); + const resid = (x: (typeof a)[number]) => + girthFit && x.tlMm && x.pecGirthMm + ? x.pecGirthMm - (girthFit.intercept + girthFit.slope * x.tlMm) + : null; + const lactT = pairedT( + a + .filter((x) => x.lact1 != null && x.lact2 != null) + .map((x) => [x.lact1!, x.lact2!] as [number, number]) + ); + const stats = { + size: twoGroupText( + a.filter((x) => x.sex === 'F').map((x) => x.tlMm), + a.filter((x) => x.sex === 'M').map((x) => x.tlMm), + 'females and males', + 'mm for females' + ), + lact: lactT + ? `Second draw ${lactT.diff >= 0 ? '+' : '−'}${num(Math.abs(lactT.diff), 1)} mmol/L on average, ${lactT.p < 0.05 ? 'a real change' : 'no more than chance'} (paired t-test, ${pValue(lactT.p)}, n = ${num(lactT.df + 1)}).` + : null, + girth: girthFit + ? `Girth on length (non-pregnant sharks): R² = ${num(girthFit.r2, 2)}, ${pValue(girthFit.p)}. ${ + twoGroupText( + a.filter((x) => x.pregnant === 'Y').map(resid), + a.filter((x) => x.sex === 'F' && x.pregnant !== 'Y').map(resid), + 'pregnant and other females at the same length', + 'mm of girth when pregnant' + ) ?? '' + }` + : null + }; return { + stats, n: a.length, sex: Object.fromEntries(countBy(a, (x) => x.sex)), maturity: [...countBy(a, (x) => x.maturity ?? 'Unknown').entries()].map(([k, n]) => ({ diff --git a/src/routes/adults/+page.svelte b/src/routes/adults/+page.svelte index dbaef75..6f785ad 100644 --- a/src/routes/adults/+page.svelte +++ b/src/routes/adults/+page.svelte @@ -48,7 +48,11 @@
- + ({ x: p.l1, y: p.l2, label: p.name }))} @@ -117,6 +122,7 @@ title="Girth against length" subtitle="Pectoral girth: pregnant females stand out" papers={['eustache2023philopatry']} + stats={data.stats.girth} > @@ -53,7 +54,25 @@ export const load: PageServerLoad = () => }); const zero = sets.filter((s) => !s.nTotal).length; + const sig = corr.filter((c) => c.p != null && c.p < 0.05); + const bonf = 0.05 / Math.max(1, corr.length); + const both = ( + term: Parameters[1], + what: string, + skip: ('nursery' | 'season')[] = [] + ) => [ + rateText(rateTest(sets, term, 'cpueCm', skip), `${what} for blacktips`), + rateText(rateTest(sets, term, 'cpueNa', skip), `${what} for sicklefin lemons`) + ]; + const stats = { + corr: `${sig.length} of ${corr.length} variables correlate with catch rate at p < 0.05${sig.length ? ` (${sig.map((c) => c.label.toLowerCase()).join(', ')})` : ''}; ${corr.filter((c) => c.p != null && c.p < bonf).length} pass a Bonferroni-corrected p < ${bonf.toPrecision(1)}. With this many variables some links are expected by chance, and the raw correlations mix in the calendar (see the model below).`, + nurseries: both({ groupOf: (s) => s.siteId }, 'nurseries', ['nursery']), + seasons: both({ groupOf: (s) => s.season }, 'seasons', ['season']), + weekday: rateText(rateTest(sets, { groupOf: (s) => s.weekday }), 'days of the week'), + crew: rateSlopeText(rateTest(sets, { valueOf: (s) => s.crewSize }), 'crew size') + }; return { + stats, model: memo('catchModel', catchModel), n: sets.length, zero, diff --git a/src/routes/drivers/+page.svelte b/src/routes/drivers/+page.svelte index 3296c14..ad88e00 100644 --- a/src/routes/drivers/+page.svelte +++ b/src/routes/drivers/+page.svelte @@ -66,6 +66,7 @@ ], rows: data.corr.map((c) => ({ ...c, pL: pValue(c.p) })) }} + stats={data.stats.corr} > md.sites[i].name)} @@ -210,6 +212,7 @@ note={lastSeason ? `${season(lastSeason)} may still be under way; its estimate covers the dates netted so far.` : ''} + stats={data.stats.seasons} > season(x))} @@ -289,7 +292,11 @@
- + w.name)} series={[ @@ -303,7 +310,11 @@ labels /> - + c.k)} series={[ diff --git a/src/routes/effort/+page.server.ts b/src/routes/effort/+page.server.ts index 7c19427..9a33446 100644 --- a/src/routes/effort/+page.server.ts +++ b/src/routes/effort/+page.server.ts @@ -8,6 +8,7 @@ import { siteName } from '#lib/server/analytics/common'; import { histogram } from '#lib/stats'; +import { rateSlopeText, rateTest, tableText } from '#lib/server/analytics/tests'; import type { PageServerLoad } from './$types'; export const load: PageServerLoad = () => @@ -37,7 +38,21 @@ export const load: PageServerLoad = () => const ss = eff.filter((s) => (v === 10 ? (s.visit ?? 0) >= 10 : s.visit === v)); return { v: v === 10 ? '10+' : String(v), cpue: round(cpueOf(ss)), n: ss.length }; }); + const stats = { + zero: tableText( + nurseries.map((id) => { + const ss = eff.filter((s) => s.siteId === id); + return [ss.filter((s) => !s.nTotal).length, ss.filter((s) => s.nTotal).length]; + }), + 'nurseries' + ), + visits: rateSlopeText( + rateTest(eff, { valueOf: (s) => s.visit }), + 'the visit number (later visits also fall later in the season, which the adjusted test allows for)' + ) + }; return { + stats, seasons: d.seasons, nurseryNames: nurseries.map((id) => siteName(d, id)), setGrid, diff --git a/src/routes/effort/+page.svelte b/src/routes/effort/+page.svelte index e964193..5d57ca8 100644 --- a/src/routes/effort/+page.svelte +++ b/src/routes/effort/+page.svelte @@ -65,6 +65,7 @@ title="Zero-catch nights by nursery" papers={['mcinturf2025aggregation']} subtitle="Share of timed sets with no sharks" + stats={data.stats.zero} > v.v)} diff --git a/src/routes/growth/+page.server.ts b/src/routes/growth/+page.server.ts index b1e6a3d..6ca8638 100644 --- a/src/routes/growth/+page.server.ts +++ b/src/routes/growth/+page.server.ts @@ -8,7 +8,9 @@ import { siteName } from '#lib/server/analytics/common'; import { vonBertalanffy } from '#lib/server/analytics/population'; -import { histogram, linearFit, mean, median, pairs } from '#lib/stats'; +import { histogram, linearFit, mean, median, pairedT, pairs } from '#lib/stats'; +import { fitText, groupsText, rankText, twoGroupText } from '#lib/server/analytics/tests'; +import { num, pValue } from '#lib/format'; import type { PageServerLoad } from './$types'; export const load: PageServerLoad = () => @@ -64,7 +66,62 @@ export const load: PageServerLoad = () => .filter((l) => l.rate > -1 && l.rate < 3); const nurseries = activeNurseries(d); + const ofSp = (sp: string) => within.filter((g) => g.species === sp); + const named = (name: string, text: string | null) => (text ? `${name}: ${text}` : null); + const spread = (sp: string) => { + const m = median(ofSp(sp).map((g) => g.rate)) ?? 0; + return ofSp(sp).map((g) => [g.days, Math.abs(g.rate - m)] as [number, number]); + }; + const massVsZero = (sp: string, name: string) => { + const t = pairedT( + ofSp(sp) + .filter((g) => g.massRate != null) + .map((g) => [0, g.massRate!] as [number, number]) + ); + return t + ? `${name}: mean ${t.diff >= 0 ? '+' : '−'}${num(Math.abs(t.diff), 1)} g per day, ${t.p < 0.05 ? 'different from' : 'not different from'} no change (t-test, ${pValue(t.p)}, n = ${num(t.df + 1)}).` + : null; + }; + const stats = { + dist: twoGroupText( + ofSp('Cm').map((g) => g.rate), + ofSp('Na').map((g) => g.rate), + 'blacktips and sicklefin lemons', + 'mm per day' + ), + noise: named( + 'Distance from the median growth rate against days between captures (blacktips)', + rankText(spread('Cm')) + ), + size: ['Cm', 'Na'].map((sp) => + named( + sp === 'Cm' ? 'Blacktips' : 'Sicklefin lemons', + fitText( + ofSp(sp).map((g) => [g.tl0, g.rate]), + 'mm/day per mm' + ) + ) + ), + site: groupsText( + nurseries.map((id) => within.filter((g) => g.site === id).map((g) => g.rate)), + 'nurseries (all species)' + ), + mass: [massVsZero('Cm', 'Blacktips'), massVsZero('Na', 'Sicklefin lemons')], + labTl: twoGroupText( + lab.map((l) => l.rate), + ofSp('Cm').map((g) => g.rate), + 'lab and field blacktips', + 'mm per day in the lab' + ), + labMass: twoGroupText( + lab.map((l) => l.massRate), + ofSp('Cm').map((g) => g.massRate), + 'lab and field blacktips', + 'g per day in the lab' + ) + }; return { + stats, vbgf: vonBertalanffy(d), n: within.length, medianCm: round(median(within.filter((g) => g.species === 'Cm').map((g) => g.rate)), 2), diff --git a/src/routes/growth/+page.svelte b/src/routes/growth/+page.svelte index dcf326d..260fc35 100644 --- a/src/routes/growth/+page.svelte +++ b/src/routes/growth/+page.svelte @@ -32,6 +32,7 @@ num(v, 2)} /> num(v, 2)} /> - + num(v, 1)} />
diff --git a/src/routes/moon/+page.server.ts b/src/routes/moon/+page.server.ts index 4d732aa..a1ae060 100644 --- a/src/routes/moon/+page.server.ts +++ b/src/routes/moon/+page.server.ts @@ -2,6 +2,7 @@ import { memo } from '#lib/server/data'; import { binnedMean, cpueOf, effortSets, fieldCaptures, round } from '#lib/server/analytics/common'; import { MOON_PHASES } from '#lib/server/astro'; import { moonCloud } from '#lib/server/analytics/cloud'; +import { rateSlopeText, rateTest, rateText } from '#lib/server/analytics/tests'; import { histogram, median, welch } from '#lib/stats'; import type { PageServerLoad } from './$types'; @@ -27,7 +28,19 @@ export const load: PageServerLoad = () => const dark = caps.filter((c) => (c.moonIllum ?? 0.5) < 0.25).map((c) => c.minAfterSunset); const bright = caps.filter((c) => (c.moonIllum ?? 0.5) > 0.75).map((c) => c.minAfterSunset); const w = welch(bright, dark); + const phaseOf = { groupOf: (s: (typeof sets)[number]) => phaseIdx(s.moonPhase) }; + const isUp = { + groupOf: (s: (typeof sets)[number]) => + s.moonAltMid == null ? null : s.moonAltMid > 0 ? 'up' : 'down' + }; return { + stats: { + phases: rateText(rateTest(sets, phaseOf), 'the eight moon phases'), + phasesCm: rateText(rateTest(sets, phaseOf, 'cpueCm'), 'moon phases for blacktips'), + phasesNa: rateText(rateTest(sets, phaseOf, 'cpueNa'), 'moon phases for sicklefin lemons'), + illum: rateSlopeText(rateTest(sets, { valueOf: (s) => s.moonIllum }), 'moon illumination'), + up: rateText(rateTest(sets, isUp), 'nights with the moon up and down') + }, moonCloud: moonCloud(d), phases, illum: binnedMean( diff --git a/src/routes/moon/+page.svelte b/src/routes/moon/+page.svelte index ca0b8e3..d7aa11e 100644 --- a/src/routes/moon/+page.svelte +++ b/src/routes/moon/+page.svelte @@ -28,6 +28,7 @@ title="Catch rate around the lunar cycle" papers={['debaere2024lunar']} subtitle="Sharks per net-hour by moon phase (wedge area ∝ catch rate). New moon at the top, full moon at the bottom." + stats={data.stats.phases} > ({ @@ -52,6 +53,7 @@ ], rows: data.phases }} + stats={[data.stats.phasesCm, data.stats.phasesNa]} > p.name)} @@ -75,6 +77,7 @@ title="Catch rate by moon illumination" papers={['debaere2024lunar', 'bouyoucos2024abiotic']} subtitle="Whiskers: 95% confidence intervals" + stats={data.stats.illum} > b.label)} @@ -93,6 +96,7 @@ title="Is the moon up?" papers={['debaere2024lunar']} subtitle="Catch rate when the moon is above or below the horizon at mid-set" + stats={data.stats.up} > `${u.k} (${u.n})`)} diff --git a/src/routes/morphometrics/+page.server.ts b/src/routes/morphometrics/+page.server.ts index 929d7ee..65f1efb 100644 --- a/src/routes/morphometrics/+page.server.ts +++ b/src/routes/morphometrics/+page.server.ts @@ -19,6 +19,8 @@ import { welch, wilson } from '#lib/stats'; +import { fitText, groupsText, trendText, twoGroupText } from '#lib/server/analytics/tests'; +import { num, pValue } from '#lib/format'; import type { PageServerLoad } from './$types'; export const load: PageServerLoad = () => @@ -51,6 +53,7 @@ export const load: PageServerLoad = () => a: fit.a, b: fit.b, r2: round(fit.r2, 3), + p: fit.p, n: fit.n, curve: Array.from({ length: 30 }, (_, i) => { const x = lo + ((hi - lo) * i) / 29; @@ -191,7 +194,58 @@ export const load: PageServerLoad = () => p.x != null && p.y != null && p.y > 5 && p.y < 200 ); + const powerText = (s: 'Cm' | 'Na', name: string) => { + const f = lw(s).fit; + return f + ? `${name}: W = ${f.a.toExponential(2)}·L^${num(f.b, 2)}, R² = ${num(f.r2, 3)}, ${pValue(f.p)} (n = ${num(f.n)}).` + : null; + }; + const neoBySeason = (s: string) => + d.seasons.map((season) => + sp(s) + .filter((c) => c.season === season && isNeonate(c)) + .map(fulton) + ); + const tlSeason = d.seasons.map((season) => + sp('Cm') + .filter((c) => c.season === season) + .map((c) => c.tlMm) + ); + const stats = { + lf: twoGroupText( + sp('Na').map((c) => c.tlMm), + sp('Cm').map((c) => c.tlMm), + 'sicklefin lemons and blacktips at first capture', + 'mm' + ), + lw: [ + 'Power fits on log–log axes (log-mass on log-length regression):', + powerText('Cm', 'Blacktip'), + powerText('Na', 'Sicklefin lemon') + ], + kSite: groupsText( + nurseries.map((id) => neoCm.filter((c) => c.siteId === id).map(fulton)), + 'nurseries' + ), + kSeason: [ + groupsText(neoBySeason('Cm'), 'seasons for blacktips'), + trendText(kBySeason('Cm')), + groupsText(neoBySeason('Na'), 'seasons for sicklefin lemons') + ], + tlSeason: [ + groupsText(tlSeason, 'seasons'), + trendText( + tlBySeason('Cm').map((b) => b.stats?.mean ?? null), + 'mm' + ) + ], + claspers: fitText( + claspers.map((c) => [c.x, c.y]), + 'mm per mm' + ) + }; return { + stats, edges, lfCm: lf('Cm'), lfNa: lf('Na'), diff --git a/src/routes/morphometrics/+page.svelte b/src/routes/morphometrics/+page.svelte index b054f0e..a81b65c 100644 --- a/src/routes/morphometrics/+page.svelte +++ b/src/routes/morphometrics/+page.svelte @@ -33,6 +33,7 @@ ({ ...b, color: SPECIES.Cm.color }))} @@ -102,6 +105,7 @@ title="Newborn condition by season" papers={['weideli2019condition', 'debaere2023umbilicus']} subtitle="Mean Fulton's K of newborns" + stats={data.stats.kSeason} > num(v, 2)} /> - + ({ ...b, color: SPECIES.Cm.color }))} yLabel="TL (mm)" @@ -210,6 +218,7 @@ @@ -122,7 +123,65 @@ export const load: PageServerLoad = () => n: first.filter((c) => c.umbilical === u).length })); + const named = (name: string, text: string | null) => (text ? `${name}: ${text}` : null); + const ofSp = (sp: string) => first.filter((c) => c.species === sp); + const stats = { + open: ['Cm', 'Na'].map((sp) => + named( + sp === 'Cm' + ? 'Blacktips, unhealed scar against day of the season (one point per pup)' + : 'Sicklefin lemons', + rankText( + ofSp(sp) + .filter((c) => c.umbilical) + .map((c) => [seasonDay(c.date!), c.umbilical !== 'closed' ? 1 : 0]) + ) + ) + ), + size: ['Cm', 'Na'].map((sp) => + named( + sp === 'Cm' ? 'Blacktips' : 'Sicklefin lemons', + fitText( + sizeScatter.filter((p) => p.g === sp).map((p) => [p.x, p.y]), + 'mm per day' + ) + ) + ), + window: named( + 'Median capture date of open-scar pups', + trendText( + window.map((w) => (w.n >= 5 ? w.q50 : null)), + 'days' + ) + ), + gSst: fitText( + pairs( + bySeason.filter((r) => r.n >= 10), + (r) => r.gSst, + (r) => r.tl + ), + 'mm per °C' + ), + ageMix: tableText( + ageMix.map((r) => [r.neonate, r.juvenile]), + 'seasons in the newborn share' + ), + scar: ['Cm', 'Na'].map((sp) => + named( + sp === 'Cm' ? 'Blacktips' : 'Sicklefin lemons', + groupsText( + (['open', 'semi', 'closed'] as const).map((u) => + ofSp(sp) + .filter((c) => c.umbilical === u) + .map((c) => c.tlMm) + ), + 'scar stages' + ) + ) + ) + }; return { + stats, weeks, openCm: openShare('Cm'), openNa: openShare('Na'), diff --git a/src/routes/neonates/+page.svelte b/src/routes/neonates/+page.svelte index f439d8f..4ceb06d 100644 --- a/src/routes/neonates/+page.svelte +++ b/src/routes/neonates/+page.svelte @@ -31,6 +31,7 @@ title="Share of pups with an unhealed scar, week by week" papers={['debaere2023umbilicus', 'debaere2025injuries']} subtitle="Open or healing umbilical scars among first captures (weeks with ≥ 5 sharks)" + stats={data.stats.open} > ({ @@ -99,6 +101,7 @@ title="Birth window by season" papers={['debaere2023umbilicus']} subtitle="When open-scar pups were caught: 10th, 50th and 90th percentile dates (seasons with ≥ 5 open-scar pups)" + stats={data.stats.window} > u.u)} diff --git a/src/routes/nurseries/+page.server.ts b/src/routes/nurseries/+page.server.ts index 92998ce..ab9b1c5 100644 --- a/src/routes/nurseries/+page.server.ts +++ b/src/routes/nurseries/+page.server.ts @@ -10,6 +10,7 @@ import { round } from '#lib/server/analytics/common'; import { mean } from '#lib/stats'; +import { rateTest, rateText } from '#lib/server/analytics/tests'; import type { PageServerLoad } from './$types'; export const load: PageServerLoad = () => @@ -69,5 +70,14 @@ export const load: PageServerLoad = () => .join(' · '), href: '/adults' })); - return { rows, seasons: d.seasons, heat, adults }; + const inIds = eff.filter((s) => s.siteId && ids.includes(s.siteId)); + const stats = { + species: (['cpueCm', 'cpueNa'] as const).map((key) => + rateText( + rateTest(inIds, { groupOf: (s) => s.siteId }, key, ['nursery']), + `nurseries for ${key === 'cpueCm' ? 'blacktips' : 'sicklefin lemons'}` + ) + ) + }; + return { rows, seasons: d.seasons, heat, adults, stats }; }); diff --git a/src/routes/nurseries/+page.svelte b/src/routes/nurseries/+page.svelte index e35d3de..fe554fb 100644 --- a/src/routes/nurseries/+page.svelte +++ b/src/routes/nurseries/+page.svelte @@ -60,6 +60,7 @@ title="Sicklefin lemons vs blacktips" papers={['bouyoucos2022nursery']} subtitle="Catch rate per species: lemon sharks are concentrated in a few southern and western nurseries" + stats={data.stats.species} > { @@ -89,7 +90,15 @@ export const load: PageServerLoad = ({ params }) => { href: `/nurseries/${s.id}` })); + const seasonStats = [ + rateText( + rateTest(eff, { groupOf: (s) => s.season }, 'cpue', ['season']), + 'seasons at this nursery' + ), + trendText(perSeason.map((r) => r.cpue)) + ]; return { + seasonStats, site: { ...site, aliases: site.aliases ? (JSON.parse(site.aliases) as string[]) : [] }, kpi: { captures: caps.length, diff --git a/src/routes/nurseries/[site]/+page.svelte b/src/routes/nurseries/[site]/+page.svelte index 3360a4c..6ada432 100644 --- a/src/routes/nurseries/[site]/+page.svelte +++ b/src/routes/nurseries/[site]/+page.svelte @@ -127,6 +127,7 @@ title="Catch rate per season" papers={['eustache2024density']} subtitle="Sharks per net-hour" + stats={data.seasonStats} > Math.round(Date.parse(`${iso}T00:00:00Z`) / 86_400_000); @@ -76,7 +77,15 @@ export const load: PageServerLoad = () => null ); + // Warming: one mean anomaly per complete calendar year, so weekly autocorrelation can't + // inflate the test. + const years = [...new Set(o.map((r) => r.date.slice(0, 4)))].sort(); + const annual = years + .map((y) => o.filter((r) => r.date.startsWith(y) && r.crwAnom != null)) + .map((rs) => (rs.length >= 300 ? mean(rs.map((r) => r.crwAnom)) : null)); + const anomStats = trendText(annual, '°C', 'year'); return { + anomStats, bands, sst: weekly(o, (r) => r.oisst ?? r.crwSst), anom: weekly(o, (r) => r.crwAnom), diff --git a/src/routes/ocean/+page.svelte b/src/routes/ocean/+page.svelte index ae9bc22..2593e7f 100644 --- a/src/routes/ocean/+page.svelte +++ b/src/routes/ocean/+page.svelte @@ -61,6 +61,7 @@ @@ -80,7 +82,29 @@ export const load: PageServerLoad = () => }) .filter((s) => s.points.length > 5); + const bySite = (k: 'hct' | 'cholesterol' | 'triglycerides') => + groupsText( + sites.map((s) => blood.filter((b) => b.siteId === s).map((b) => b[k])), + 'nurseries' + ); + const massT = pairedT(massPairs.map((m) => [m.x, m.y] as [number, number])); + const feedPairs = [...feedDays.entries()].flatMap(([day, v]) => + v.map((pct) => [day, pct] as [number, number]) + ); + const stats = { + hct: bySite('hct'), + tg: bySite('triglycerides'), + chol: bySite('cholesterol'), + mass: massT + ? `Mean change ${massT.diff >= 0 ? '+' : '−'}${num(Math.abs(massT.diff) * 1000)} g between arrival and release, ${massT.p < 0.05 ? 'different from' : 'not different from'} no change (paired t-test, ${pValue(massT.p)}, n = ${num(massT.df + 1)}).` + : null, + feeding: (() => { + const r = rankText(feedPairs); + return r ? `% eaten against days since the first feed, one point per feed: ${r}` : null; + })() + }; return { + stats, diet: diet(d), nBlood: blood.length, hct: metric('hct'), diff --git a/src/routes/physiology/+page.svelte b/src/routes/physiology/+page.svelte index 550a5a1..7f56191 100644 --- a/src/routes/physiology/+page.svelte +++ b/src/routes/physiology/+page.svelte @@ -60,20 +60,25 @@ title="Haematocrit by nursery" papers={['schwieterman2019blood']} subtitle="% packed red cells: oxygen-carrying capacity" + stats={data.stats.hct} > ({ ...b, color: 'var(--series-8)' }))} yLabel="Haematocrit (%)" /> - + ({ ...b, color: 'var(--series-4)' }))} yLabel="Triglycerides" yFormat={(v) => num(v, 2)} /> - + ({ ...b, color: 'var(--series-7)' }))} yLabel="Cholesterol" @@ -116,6 +121,7 @@ @@ -58,19 +59,37 @@ export const load: PageServerLoad = () => ['k', 'Newborn condition (K)'], ['growth', 'Growth (mm/day)'] ] as const; + const rhoOf = (mk: (typeof metrics)[number][0], ok: (typeof outcomes)[number][0]) => + spearman( + pairs( + rows, + (x) => x[mk] as number | null, + (x) => x[ok] as number | null + ) + ); const corr = metrics.map(([mk, ml]) => ({ metric: ml, values: outcomes.map(([ok]) => { - const r = spearman( - pairs( - rows, - (x) => x[mk] as number | null, - (x) => x[ok] as number | null - ) - ); + const r = rhoOf(mk, ok); return r ? round(r.rho, 2) : null; }) })); + // With ten nurseries only strong correlations can reach significance (#119). + const cells = metrics.flatMap(([mk, ml]) => + outcomes.map(([ok, ol]) => ({ + label: `${ml.toLowerCase()} vs ${ol.toLowerCase()}`, + r: rhoOf(mk, ok) + })) + ); + const sig = cells.filter((c) => c.r && c.r.p < 0.05); + const scatter = (mk: (typeof metrics)[number][0], ok: (typeof outcomes)[number][0]) => + rankText( + pairs( + rows, + (x) => x[mk] as number | null, + (x) => x[ok] as number | null + ) + ); // Busy days (#25): do weekends and holidays, when more people are on the water, change the // evening catch? Mean per-set catch rate with a ±1.96·SE interval. const dated = eff.filter((s) => s.date && s.cpue != null); @@ -124,7 +143,20 @@ export const load: PageServerLoad = () => } const counts = (m: Map) => [...m].sort((a, b) => b[1] - a[1]).map(([name, n]) => ({ name, n })); + const stats = { + corr: `Spearman tests across ${rows.length} nurseries (${cells.filter((c) => c.r).length} pairs): ${sig.length ? `significant at p < 0.05: ${sig.map((c) => `${c.label} (ρ = ${c.r!.rho.toFixed(2)}, p = ${c.r!.p.toFixed(3)})`).join('; ')}. With ${cells.filter((c) => c.r).length} tests about one in twenty is expected by chance; ${cells.filter((c) => c.r && c.r.p < 0.05 / cells.filter((x) => x.r).length).length} pass a Bonferroni-corrected threshold.` : 'none is significant at p < 0.05.'}`, + fishing: [ + `Blacktips: ${scatter('fishing', 'cpueCm') ?? '–'}`, + `Sicklefin lemons: ${scatter('fishing', 'cpueNa') ?? '–'}` + ], + artif: scatter('artif', 'k'), + human: scatter('human', 'growth'), + composite: scatter('composite', 'cpueCm'), + dayType: rateText(rateTest(dated, { groupOf: (s) => type(s) }), 'types of day'), + weekday: rateText(rateTest(dated, { groupOf: (s) => s.weekday }), 'days of the week') + }; return { + stats, rows, metrics, outcomes: outcomes.map((o) => o[1]), diff --git a/src/routes/pressure/+page.svelte b/src/routes/pressure/+page.svelte index 7ece842..15fe598 100644 --- a/src/routes/pressure/+page.svelte +++ b/src/routes/pressure/+page.svelte @@ -77,6 +77,7 @@ title="Correlations with shark outcomes" papers={['bouyoucos2024abiotic']} subtitle="Spearman ρ across nurseries (n ≤ 10): blue negative, red positive" + stats={data.stats.corr} > num(v, 2)} /> - + - + r.human, @@ -142,7 +148,11 @@ opacity={0.85} /> - + r.composite, @@ -173,6 +183,7 @@ `${t.label} (${t.n})`)} @@ -192,6 +203,7 @@ `${t.label} (${t.n})`)} diff --git a/src/routes/recaptures/+page.server.ts b/src/routes/recaptures/+page.server.ts index dcc7baf..39975a5 100644 --- a/src/routes/recaptures/+page.server.ts +++ b/src/routes/recaptures/+page.server.ts @@ -8,6 +8,7 @@ import { } from '#lib/server/analytics/common'; import { schnabel } from '#lib/server/analytics/population'; import { histogram, median, pairs as xy, spearman } from '#lib/stats'; +import { tableText, trendText } from '#lib/server/analytics/tests'; import type { PageServerLoad } from './$types'; export const load: PageServerLoad = () => @@ -83,7 +84,23 @@ export const load: PageServerLoad = () => ); return r && r.n >= 8 ? { rho: round(r.rho, 2), p: r.p, n: r.n } : null; }; + const bySeason = rateBy((c) => c.season, d.seasons); + const bySite = rateBy((c) => c.siteId, nurseries); + const stats = { + season: [ + tableText( + bySeason.map((r) => [r.recaptured, r.n - r.recaptured]), + 'seasons' + ), + trendText(bySeason.map((r) => r.rate)) + ], + site: tableText( + bySite.map((r) => [r.recaptured, r.n - r.recaptured]), + 'nurseries' + ) + }; return { + stats, abundance: { rows: est, cm: rho('Cm'), na: rho('Na') }, bySeason: rateBy((c) => c.season, d.seasons), bySite: rateBy((c) => c.siteId, nurseries).map((r) => ({ ...r, name: siteName(d, r.key) })), diff --git a/src/routes/recaptures/+page.svelte b/src/routes/recaptures/+page.svelte index 4c863eb..6868fe4 100644 --- a/src/routes/recaptures/+page.svelte +++ b/src/routes/recaptures/+page.svelte @@ -43,6 +43,7 @@ season(r.key))} @@ -52,7 +53,7 @@ valueFormat={(v) => pct(v)} /> - + r.name)} diff --git a/src/routes/seasons/+page.server.ts b/src/routes/seasons/+page.server.ts index 09e9703..99c4534 100644 --- a/src/routes/seasons/+page.server.ts +++ b/src/routes/seasons/+page.server.ts @@ -9,6 +9,7 @@ import { round } from '#lib/server/analytics/common'; import { mean } from '#lib/stats'; +import { groupsText, tableText, trendText } from '#lib/server/analytics/tests'; import type { PageServerLoad } from './$types'; export const load: PageServerLoad = () => @@ -51,5 +52,46 @@ export const load: PageServerLoad = () => crew: people.size }; }); - return { rows }; + const firstBy = d.seasons.map((season) => + firstPerSeason(caps.filter((c) => c.season === season)) + ); + const effBy = d.seasons.map((season) => eff.filter((s) => s.season === season)); + const stats = { + zero: [ + tableText( + effBy.map((ss) => [ + ss.filter((s) => !s.nTotal).length, + ss.filter((s) => s.nTotal).length + ]), + 'seasons' + ), + trendText(rows.map((r) => r.zero)) + ], + neonates: [ + tableText( + firstBy.map((f) => [f.filter(isNeonate).length, f.filter((c) => !isNeonate(c)).length]), + 'seasons' + ), + trendText(rows.map((r) => r.neonatePct)) + ], + tlCm: [ + groupsText( + firstBy.map((f) => f.filter((c) => c.species === 'Cm').map((c) => c.tlMm)), + 'seasons' + ), + trendText( + rows.map((r) => r.tlCm), + 'mm' + ) + ], + sst: trendText( + rows.map((r) => r.sst), + '°C' + ), + crew: trendText( + rows.map((r) => r.crew), + 'people' + ) + }; + return { rows, stats }; }); diff --git a/src/routes/seasons/+page.svelte b/src/routes/seasons/+page.svelte index 9e41503..d1734b8 100644 --- a/src/routes/seasons/+page.svelte +++ b/src/routes/seasons/+page.svelte @@ -57,6 +57,7 @@ @@ -61,8 +63,34 @@ export const load: PageServerLoad = () => avail[next > h.mm + 2 ? 'rising' : next < h.mm - 2 ? 'falling' : 'slack']++; } const totalAvail = avail.rising + avail.slack + avail.falling || 1; + // Goodness of fit: are captures spread over tide states as the evening offers them? + const share = [avail.rising, avail.slack, avail.falling].map((v) => v / totalAvail); + const gof = (counts: number[], name: string) => { + const n = counts.reduce((a, b) => a + b, 0); + if (n < 30) return null; + const stat = counts.reduce((a, o, i) => a + (o - n * share[i]) ** 2 / (n * share[i]), 0); + const p = chiSquareP(stat, 2); + return `${name}: ${p < 0.05 ? 'not spread as the tide states occur' : 'spread as the tide states occur'} (χ² goodness of fit = ${num(stat, 1)}, df = 2, ${pValue(p)}, ${num(n)} captures; sharks from one set aren't independent, so p is optimistic).`; + }; + const fieldKey = (s: (typeof sets)[number]) => + ['low', 'high', 'incoming', 'outgoing', 'flooding', 'ebbing'].find( + (k) => s.tideRaw && new RegExp(`^${k}`, 'i').test(s.tideRaw.trim()) + ) ?? null; + const stats = { + state: [gof(trendCounts('Cm'), 'Blacktips'), gof(trendCounts('Na'), 'Sicklefin lemons')], + height: rateSlopeText( + rateTest(sets, { valueOf: (s) => (s.tideMidMm == null ? null : s.tideMidMm / 100) }), + 'tide height' + ), + direction: rateText( + rateTest(sets, { groupOf: (s) => s.tideTrend }), + 'rising, slack and falling tides' + ), + field: rateText(rateTest(sets, { groupOf: fieldKey }), "the crew's tide notes") + }; return { + stats, heat, daily, highsEdges: Array.from({ length: 25 }, (_, i) => i), diff --git a/src/routes/tides/+page.svelte b/src/routes/tides/+page.svelte index 5f13580..1ff66ff 100644 --- a/src/routes/tides/+page.svelte +++ b/src/routes/tides/+page.svelte @@ -97,6 +97,7 @@ b.label)} @@ -133,7 +135,11 @@ valueFormat={(v) => num(v, 2)} /> - + `${t.k} (${t.n})`)} series={[ @@ -151,6 +157,7 @@ `${t.k} (${t.n})`)} diff --git a/src/routes/time-of-day/+page.server.ts b/src/routes/time-of-day/+page.server.ts index 006b79a..a820381 100644 --- a/src/routes/time-of-day/+page.server.ts +++ b/src/routes/time-of-day/+page.server.ts @@ -2,6 +2,13 @@ import { memo } from '#lib/server/data'; import { boxOf, effortSets, fieldCaptures, round, seasonDay } from '#lib/server/analytics/common'; import { sunTimes } from '#lib/server/astro'; import { histogram, median } from '#lib/stats'; +import { + fitText, + groupsText, + rankText, + trendText, + twoGroupText +} from '#lib/server/analytics/tests'; import type { PageServerLoad } from './$types'; export const load: PageServerLoad = () => @@ -54,7 +61,45 @@ export const load: PageServerLoad = () => return { x: day, sunset: s.sunset, dusk: s.civilDusk, nautical: s.nauticalDusk }; }); + const workupBy = d.seasons.map((season) => + caps + .filter( + (c) => c.season === season && c.workupMin != null && c.workupMin > 0 && c.workupMin < 90 + ) + .map((c) => c.workupMin) + ); + const starts = sets + .filter((s) => s.date && s.startMin != null && s.startMin > 14 * 60) + .map((s) => [seasonDay(s.date!), s.startMin!] as [number, number]); + const stats = { + sunset: twoGroupText( + after('Na'), + after('Cm'), + 'sicklefin lemons and blacktips', + 'min after sunset' + ), + hazard: (() => { + const r = rankText( + hazard + .filter((h) => h.rate != null && h.sets >= 30) + .map((h) => [h.t0, h.rate!] as [number, number]) + ); + return r ? `Catch rate against minutes since net-in (slices with ≥ 30 sets): ${r}` : null; + })(), + starts: (() => { + const f = fitText(starts, 'min per day'); + return f ? `Net-in time against day of the season: ${f}` : null; + })(), + workup: [ + groupsText(workupBy, 'seasons'), + trendText( + workupBy.map((w) => median(w)), + 'min' + ) + ] + }; return { + stats, edges: Array.from({ length: 25 }, (_, i) => -150 + i * 20), afterCm: histogram(after('Cm'), -150, 330, 20).map((b) => b.count), afterNa: histogram(after('Na'), -150, 330, 20).map((b) => b.count), diff --git a/src/routes/time-of-day/+page.svelte b/src/routes/time-of-day/+page.svelte index ae8b9c7..52dd115 100644 --- a/src/routes/time-of-day/+page.svelte +++ b/src/routes/time-of-day/+page.svelte @@ -30,6 +30,7 @@ `${h.t0}–${h.t0 + 20}`)} @@ -82,6 +84,7 @@ ({ ...b, color: 'var(--series-5)' }))} diff --git a/src/routes/water-quality/+page.server.ts b/src/routes/water-quality/+page.server.ts index 28eba35..dadba2c 100644 --- a/src/routes/water-quality/+page.server.ts +++ b/src/routes/water-quality/+page.server.ts @@ -10,6 +10,7 @@ import { } from '#lib/server/analytics/insitu'; import { cloudWater } from '#lib/server/analytics/cloud'; import { linearFit, mean, pairs } from '#lib/stats'; +import { groupsText } from '#lib/server/analytics/tests'; import type { PageServerLoad } from './$types'; const dayNum = (iso: string) => Math.round(Date.parse(`${iso}T00:00:00Z`) / 86_400_000); @@ -38,6 +39,16 @@ export const load: PageServerLoad = () => sst: null })) ]; + const nurseryTest = (k: 'temp' | 'ph' | 'doMg' | 'sal', lo: number, hi: number) => + groupsText( + nurseries.map((id) => + readings + .filter((r) => r.siteId === id) + .map((r) => r[k]) + .filter((v) => v != null && v >= lo && v <= hi) + ), + 'nurseries' + ); const by = (k: 'temp' | 'ph' | 'doMg' | 'sal', lo: number, hi: number) => nurseries .map((id) => ({ @@ -132,6 +143,12 @@ export const load: PageServerLoad = () => ph: by('ph', 7, 9), doMg: by('doMg', 1, 15), sal: by('sal', 25, 45), + stats: { + temp: nurseryTest('temp', 20, 40), + ph: nurseryTest('ph', 7, 9), + doMg: nurseryTest('doMg', 1, 15), + sal: nurseryTest('sal', 25, 45) + }, tempVsSst: tv.map((s) => ({ x: s.sst!, y: s.waterTemp!, diff --git a/src/routes/water-quality/+page.svelte b/src/routes/water-quality/+page.svelte index 93a7cc8..6943b99 100644 --- a/src/routes/water-quality/+page.svelte +++ b/src/routes/water-quality/+page.svelte @@ -167,7 +167,7 @@ {/if}
- + ({ ...b, color: 'var(--series-2)' }))} yLabel="°C" @@ -200,7 +200,7 @@ r={4} /> - + ({ ...b, color: 'var(--series-7)' }))} yLabel="pH" @@ -211,6 +211,7 @@ title="Salinity" papers={['bouyoucos2024abiotic']} subtitle="ppt; freshwater runoff lowers it near streams" + stats={data.stats.sal} > ({ ...b, color: 'var(--series-1)' }))} @@ -223,6 +224,7 @@ title="Dissolved oxygen" papers={['bouyoucos2021oxygen', 'bouyoucos2024abiotic']} subtitle="mg/L" + stats={data.stats.doMg} > ({ ...b, color: 'var(--series-3)' }))}