Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ samples/fixture/ synthetic workbooks for tests/CI (committed)
- Site: EnvLogger by download GPS (≤ 400 m from a nursery), then custom name, file-name prefix (`PIAENA_2_…`), then the register workbook (detected by its `Serial number` + `Custom name` header, checked before the `/gps|location/` file-name rule). HOBO by the file-name suffix (`…_Intercontinental`), then the season workbooks' HOBO log (logger number + date overlap). A name/GPS disagreement is a warning on the Data quality page.
- Cleaning: trim 2 h at the start of each file and 2 h (EnvLogger) or 24 h (HOBO, read out back at the station) at the end; drop readings outside 15–40 °C; merge repeated downloads of one logger by timestamp. Days need ≥ 18 site-hours. Tables: `logger_files`, `logger_daily`, `logger_diel`, plus `sets.insitu_temp`.
- Comparisons between nurseries only use those logged ≥ 1 year with both seasons covered (a summer-only logger looks hottest).
- Month × hour calendars (#127, `analytics/thermalCalendar.ts`) read `logger_diel`, whose `n` is contributing days (one nursery-wide hourly mean per day), not sensor samples. Cells need ≥ 10 days. Every nursery shares one colour domain taken from the supported cells, in whole degrees (24–33 °C with the current loggers): the 15–40 °C cleaning window squeezed the lagoon into two colour steps. Pooled means can't show peaks or hours above a threshold.

### Cloud cover (#104)

Expand Down
27 changes: 27 additions & 0 deletions e2e/thermal-calendar.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { expect, test } from '@playwright/test';
import AxeBuilder from '@axe-core/playwright';

test('temperature calendar supports keyboard, CSV and mobile in both themes', async ({ page }) => {
await page.setViewportSize({ width: 375, height: 800 });
for (const theme of ['light', 'dark'] as const) {
await page.emulateMedia({ colorScheme: theme });
await page.goto('/water-quality');
const card = page
.locator('figure')
.filter({ has: page.getByRole('heading', { name: /^Month and hour:/ }) });
await expect(card).toBeVisible();
const chart = card.locator('svg');
await chart.focus();
await page.keyboard.press('ArrowRight');
await expect(card.locator('.tip')).toBeVisible();
await page.keyboard.press('Escape');
await expect(card.getByRole('button', { name: /Download CSV/ })).toBeVisible();
const result = await new AxeBuilder({ page }).include('main').analyze();
expect(
result.violations.filter((v) => ['serious', 'critical'].includes(v.impact ?? ''))
).toEqual([]);
expect(
await page.evaluate(() => document.documentElement.scrollWidth - innerWidth)
).toBeLessThanOrEqual(1);
}
});
87 changes: 87 additions & 0 deletions src/lib/components/ThermalCalendar.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
<script lang="ts">
import ChartCard from './ChartCard.svelte';
import Heatmap from './charts/Heatmap.svelte';
import { MONTH_NAMES, monthYear, num } from '#lib/format';
import type { thermalCalendar } from '#lib/server/analytics/thermalCalendar';
let { calendar }: { calendar: ReturnType<typeof thermalCalendar> } = $props();
let selected = $state('');
const site = $derived(calendar.sites.find((s) => s.id === selected) ?? calendar.sites[0]);
const [lo, hi] = $derived(calendar.domain);
</script>

<section class="section">
<h2>Nursery temperature through the year</h2>
<p class="muted small">
Mean logger temperature for each month and hour of the day, pooled over every year a nursery was
logged. A cell needs at least ten logged days. Nurseries were logged in different years and for
different lengths of time (under each chart), so years and months don't count equally. These are
long-run averages, not a forecast, and not a ranking of nurseries. Downloads left out above stay
out here, and a very shallow logger may be out of the water at low tide.
</p>
{#if site}
<label
>Nursery <select value={site.id} onchange={(e) => (selected = e.currentTarget.value)}
>{#each calendar.sites as s (s.id)}<option value={s.id}>{s.name}</option>{/each}</select
></label
>
<ChartCard
title={`Month and hour: ${site.name}`}
subtitle={`Mean °C, Moorea local time (UTC−10). Every nursery uses the same ${lo}–${hi} °C colour scale.${site.first && site.last ? ` Logged on ${num(site.days)} days, ${monthYear(site.first)} to ${monthYear(site.last)}.` : ''}`}
note="Dashed cells have fewer than ten logged days. Each day adds one nursery-wide hourly mean however many loggers were in the water. Long-run means can't show peak temperatures or hours above a stress threshold."
table={{
columns: [
{ key: 'month', label: 'Month', num: true },
{ key: 'hour', label: 'Local hour', num: true },
{ key: 'temperature', label: 'Mean °C', num: true },
{ key: 'days', label: 'Contributing days', num: true }
],
rows: site.rows
}}
>
<!-- svelte-ignore a11y_no_noninteractive_tabindex (The horizontally scrollable region must be keyboard reachable.) -->
<div class="scroll" role="region" aria-label="Scrollable temperature calendar" tabindex="0">
<div class="calendar">
<Heatmap
xLabels={Array.from({ length: 24 }, (_, h) => String(h))}
yLabels={MONTH_NAMES}
values={site.values}
domain={calendar.domain}
format={(v) => `${v.toFixed(1)} °C`}
xTitle="Local hour"
yTitle="Month"
/>
</div>
</div>
<div class="ramp">
<span>{lo} °C</span>{#each [1, 2, 3, 4, 5, 6, 7] as k (k)}<i
aria-hidden="true"
style:background={`var(--seq-${k})`}
></i>{/each}<span>{hi} °C</span>
</div>
</ChartCard>
{:else}<p>No nursery logger observations available.</p>{/if}
</section>

<style>
.ramp {
display: flex;
align-items: center;
gap: 4px;
font-size: 0.8rem;
color: var(--ink-2);
}
.ramp i {
width: 24px;
height: 12px;
}
label {
display: block;
margin-bottom: 1rem;
}
.scroll {
overflow-x: auto;
}
.calendar {
min-width: 620px;
}
</style>
8 changes: 6 additions & 2 deletions src/lib/components/charts/Heatmap.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,9 @@
const absMax = $derived(Math.max(Math.abs(lo), Math.abs(hi)) || 1);

function fill(v: number | null): { color: string; opacity: number; dark: boolean } {
if (v == null || !Number.isFinite(v))
return { color: 'var(--surface-2)', opacity: 0.6, dark: false };
// No data: an empty dashed cell, never a colour from the scale (the lightest steps are
// close to --surface-2, in dark mode especially).
if (v == null || !Number.isFinite(v)) return { color: 'none', opacity: 1, dark: false };
if (mode === 'div') {
const t = Math.max(-1, Math.min(1, v / absMax));
if (Math.abs(t) < 0.06) return { color: 'var(--div-mid)', opacity: 1, dark: false };
Expand Down Expand Up @@ -118,6 +119,9 @@
rx="3"
fill={f.color}
fill-opacity={f.opacity}
stroke={f.color === 'none' ? 'var(--axis)' : undefined}
stroke-dasharray={f.color === 'none' ? '3 2' : undefined}
pointer-events={f.color === 'none' ? 'all' : undefined}
role="presentation"
data-mark={r * xLabels.length + c}
onpointermove={(e) => show(pointerIn(e), r, c)}
Expand Down
53 changes: 53 additions & 0 deletions src/lib/server/analytics/thermalCalendar.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { expect, it } from 'vitest';
import type { Dataset } from '../data';
import { thermalCalendar } from './thermalCalendar';

type Input = Pick<Dataset, 'sites' | 'loggerDiel' | 'loggerDaily'>;

it('keeps the full calendar, masks sparse cells and preserves site-hour support', () => {
const d = {
sites: [{ id: 'a', name: 'A' }],
loggerDiel: [
{ siteId: 'a', month: 12, hour: 23, temp: 29, n: 10 },
{ siteId: 'a', month: 1, hour: 0, temp: 31, n: 9 }
],
loggerDaily: [
{ siteId: 'a', date: '2020-12-02' },
{ siteId: 'a', date: '2019-12-01' }
]
} as unknown as Input;
const { sites, domain } = thermalCalendar(d);
const [s] = sites;
expect(s.values).toHaveLength(12);
expect(s.values[0]).toHaveLength(24);
expect(s.values[0][0]).toBeNull();
expect(s.values[11][23]).toBe(29);
expect(s.rows[0].days).toBe(9);
expect(s.rows[1]).toMatchObject({ days: 0, temperature: null });
expect(s).toMatchObject({ days: 2, first: '2019-12-01', last: '2020-12-02' });
// The masked 31 °C cell doesn't stretch the scale; a single value still gets a span.
expect(domain).toEqual([29, 30]);
expect(thermalCalendar({ sites: [], loggerDiel: [], loggerDaily: [] })).toEqual({
domain: [15, 40],
sites: []
});
});

it('shares one domain across nurseries, rounded out to whole degrees', () => {
const cell = (siteId: string, month: number, temp: number) => ({
siteId,
month,
hour: 12,
temp,
n: 20
});
const d = {
sites: [
{ id: 'a', name: 'A' },
{ id: 'b', name: 'B' }
],
loggerDiel: [cell('a', 1, 26.4), cell('a', 2, 28), cell('b', 1, 31.2)],
loggerDaily: []
} as unknown as Input;
expect(thermalCalendar(d).domain).toEqual([26, 32]);
});
50 changes: 50 additions & 0 deletions src/lib/server/analytics/thermalCalendar.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import type { Dataset } from '../data';

/** A month-hour needs ten observed days. n counts site-hours, not sensor samples. */
export const MIN_THERMAL_DAYS = 10;

/**
* Month × hour mean temperature per nursery (#127), from `logger_diel`. One colour domain for
* every nursery so they compare, taken from the supported cells (whole degrees): the 15–40 °C
* plausibility window would squeeze the lagoon's few degrees into two colour steps.
*/
export function thermalCalendar(d: Pick<Dataset, 'loggerDiel' | 'loggerDaily' | 'sites'>) {
const sites = d.sites
.filter((s) => d.loggerDiel.some((r) => r.siteId === s.id))
.map((s) => {
const records = new Map(
d.loggerDiel.filter((r) => r.siteId === s.id).map((r) => [`${r.month}|${r.hour}`, r])
);
const rows = Array.from({ length: 12 }, (_, m) =>
Array.from({ length: 24 }, (_, hour) => {
const r = records.get(`${m + 1}|${hour}`);
return {
month: m + 1,
hour,
days: r?.n ?? 0,
temperature: r && r.n >= MIN_THERMAL_DAYS && Number.isFinite(r.temp) ? r.temp : null
};
})
);
const days = d.loggerDaily.filter((r) => r.siteId === s.id).map((r) => r.date);
days.sort();
return {
id: s.id,
name: s.name,
days: days.length,
first: days[0] ?? null,
last: days.at(-1) ?? null,
rows: rows.flat(),
values: rows.map((rs) => rs.map((r) => r.temperature))
};
})
.sort((a, b) => a.name.localeCompare(b.name));
const cells = sites
.flatMap((s) => s.rows.map((r) => r.temperature))
.filter((v): v is number => v != null);
const domain: [number, number] = cells.length
? [Math.floor(Math.min(...cells)), Math.ceil(Math.max(...cells))]
: [15, 40];
if (domain[0] === domain[1]) domain[1] += 1;
return { domain, sites };
}
2 changes: 2 additions & 0 deletions src/routes/water-quality/+page.server.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { memo } from '#lib/server/data';
import { thermalCalendar } from '#lib/server/analytics/thermalCalendar';
import { activeNurseries, boxOf, round, siteName } from '#lib/server/analytics/common';
import {
coverage,
Expand Down Expand Up @@ -138,6 +139,7 @@ export const load: PageServerLoad = () =>
: null;

return {
thermalCalendar: thermalCalendar(d),
insitu,
temp: by('temp', 20, 40),
ph: by('ph', 7, 9),
Expand Down
3 changes: 3 additions & 0 deletions src/routes/water-quality/+page.svelte
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<script lang="ts">
import ThermalCalendar from '#lib/components/ThermalCalendar.svelte';
import ChartCard from '#lib/components/ChartCard.svelte';
import StatTile from '#lib/components/StatTile.svelte';
import BoxPlot from '#lib/components/charts/BoxPlot.svelte';
Expand Down Expand Up @@ -166,6 +167,8 @@
</section>
{/if}

<ThermalCalendar calendar={data.thermalCalendar} />

<section class="section grid-2">
<ChartCard title="Water temperature at the net" stats={data.stats.temp}>
<BoxPlot
Expand Down
Loading