Skip to content
Draft
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
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,23 @@ findStation("noaa/8443970"); // Boston
findStation("9440083"); // Vancouver
```

### Predicting many stations efficiently

When predicting tides for many stations at the same time, astronomical computations are identical across all stations for a given time period. Pass a shared `CorrectionsCache` to eliminate redundant work:

```typescript
import { stationsNear, createCorrectionsCache } from "neaps";

const cache = createCorrectionsCache();
const time = new Date();

const predictions = stationsNear({ latitude: 45.6, longitude: -122.7 }, 10).map((station) =>
station.getWaterLevelAt({ time, cache }),
);
```

See the [`@neaps/tide-predictor` README](packages/tide-predictor/README.md#predicting-many-stations) for full details and options.

## Accuracy & Validation

Neaps is continuously validated against NOAA tidal predictions, comparing the **time** and **height** of predicted high and low tides for all NOAA tide stations.
Expand Down
5 changes: 4 additions & 1 deletion benchmarks/noaa.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { expect } from "vitest";
import { mkdir, readFile, writeFile } from "fs/promises";
import { createWriteStream } from "fs";
import { join } from "path";
import { findStation } from "neaps";
import { createCorrectionsCache, findStation } from "neaps";
import { stations as db } from "@neaps/tide-database";
import createFetch from "make-fetch-happen";

Expand Down Expand Up @@ -47,6 +47,8 @@ const scheme = (process.env.SCHEME ?? "iho") as "iho" | "schureman";
const FAST = !!process.env.FAST;
const RANGE_DAYS = FAST ? 3 : 365;

const cache = createCorrectionsCache({ interval: 24 * 7 });

console.log(
`Testing tide predictions against ${stations.length} NOAA stations (scheme=${scheme}, days=${RANGE_DAYS})`,
);
Expand Down Expand Up @@ -81,6 +83,7 @@ for (const id of stations) {
start,
end,
nodeCorrections: scheme,
cache,
})
.extremes.map((e) => ({
time: e.time.getTime(),
Expand Down
26 changes: 20 additions & 6 deletions packages/neaps/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,14 @@ import {
type NearOptions,
type NearestOptions,
} from "@neaps/tide-database";
import { createTidePredictor, type ExtremesInput, type TimelineInput } from "@neaps/tide-predictor";
import {
createTidePredictor,
type ExtremesInput,
type TimelineInput,
type CorrectionsCache,
} from "@neaps/tide-predictor";

export { createCorrectionsCache, type CorrectionsCache } from "@neaps/tide-predictor";

type Units = "meters" | "feet";
type PredictionOptions = {
Expand All @@ -18,6 +25,10 @@ type PredictionOptions = {

/** Nodal correction fundamentals. Defaults to 'iho'. */
nodeCorrections?: "iho" | "schureman";

/** Shared corrections cache. Pass the same cache to multiple station predictors
* to avoid recomputing node corrections for each station at the same time. */
cache?: CorrectionsCache;
};

export type ExtremesOptions = ExtremesInput & PredictionOptions;
Expand Down Expand Up @@ -106,7 +117,7 @@ export function useStation(station: Station, distance?: number) {
// Use station chart datum as the default datum if available
const defaultDatum = station.chart_datum in datums ? station.chart_datum : undefined;

function getPredictor({ datum = defaultDatum, nodeCorrections }: PredictionOptions = {}) {
function getPredictor({ datum = defaultDatum, nodeCorrections, cache }: PredictionOptions = {}) {
let offset = 0;

if (datum) {
Expand All @@ -128,7 +139,7 @@ export function useStation(station: Station, distance?: number) {
offset = mslOffset - datumOffset;
}

return createTidePredictor(harmonic_constituents, { offset, nodeCorrections });
return createTidePredictor(harmonic_constituents, { offset, nodeCorrections, cache });
}

return {
Expand All @@ -141,9 +152,10 @@ export function useStation(station: Station, distance?: number) {
datum = defaultDatum,
units = defaultUnits,
nodeCorrections,
cache,
...options
}: ExtremesOptions) {
const extremes = getPredictor({ datum, nodeCorrections })
const extremes = getPredictor({ datum, nodeCorrections, cache })
.getExtremesPrediction({ ...options, offsets: station.offsets })
.map((e) => toPreferredUnits(e, units));

Expand All @@ -154,9 +166,10 @@ export function useStation(station: Station, distance?: number) {
datum = defaultDatum,
units = defaultUnits,
nodeCorrections,
cache,
...options
}: TimelineOptions) {
const timeline = getPredictor({ datum, nodeCorrections })
const timeline = getPredictor({ datum, nodeCorrections, cache })
.getTimelinePrediction({ ...options, offsets: station.offsets })
.map((e) => toPreferredUnits(e, units));

Expand All @@ -168,9 +181,10 @@ export function useStation(station: Station, distance?: number) {
datum = defaultDatum,
units = defaultUnits,
nodeCorrections,
cache,
}: WaterLevelOptions) {
const prediction = toPreferredUnits(
getPredictor({ datum, nodeCorrections }).getWaterLevelAtTime({
getPredictor({ datum, nodeCorrections, cache }).getWaterLevelAtTime({
time,
offsets: station.offsets,
}),
Expand Down
31 changes: 30 additions & 1 deletion packages/tide-predictor/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,9 @@ Note that all times internally are evaluated as UTC, so be sure to specify a tim
Calling `createTidePredictor` will generate a new tide prediction object. It accepts the following arguments:

- `constituents` - An array of [constituent objects](#constituent-object)
- `options` - An object with one of:
- `options` - An optional object with:
- `offset` - A value to add to **all** values predicted. This is useful if you want to, for example, offset tides by mean high water, etc.
- `cache` - A [`CorrectionsCache`](#predicting-many-stations) to share astronomical computations across multiple predictors. Recommended when predicting tides for many stations at the same time.

### Tide prediction methods

Expand Down Expand Up @@ -161,6 +162,34 @@ A single object is returned with:
- `time` - A Javascript date object
- `level` - The predicted water level

## <a name="predicting-many-stations"></a>Predicting many stations

When predicting tides for many stations at the same time, astronomical computations (node corrections, equilibrium arguments) are identical across all stations for a given time. By default each predictor computes these independently. Passing a shared `CorrectionsCache` eliminates this redundancy.

```typescript
import { createCorrectionsCache, createTidePredictor } from "@neaps/tide-predictor";

const cache = createCorrectionsCache();
const time = new Date();

for (const station of stations) {
const predictor = createTidePredictor(station.constituents, { cache });
results.push(predictor.getWaterLevelAtTime({ time }));
}
```

### `createCorrectionsCache(options?)`

Returns a `CorrectionsCache` that can be passed to multiple `createTidePredictor` calls.

**Options:**

- `interval` - Quantization interval in hours for node corrections (default: `24`). Node corrections change by less than 0.01% per day, so the default introduces less than 0.1 mm of error.

> [!NOTE]
>
> The cache grows by roughly 36 KB per 24-hour bucket (corrections are stored for all ~400 constituent models to enable sharing across any station), so a year of predictions uses around 13 MB. For century-scale prediction tables, consider creating a new cache per time range.

## Data definitions

### <a name="constituent-object"></a>Constituent definition
Expand Down
147 changes: 147 additions & 0 deletions packages/tide-predictor/src/corrections-cache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
import astro from "./astronomy/index.js";
import type { AstroData } from "./astronomy/index.js";
import { d2r } from "./astronomy/constants.js";
import type { Constituent } from "./constituents/types.js";
import type { Fundamentals, NodalCorrection } from "./node-corrections/types.js";

/** Cached node corrections for a single time bucket. The same object reference
* is returned for all times that fall within the same bucket, enabling callers
* to detect bucket transitions via `!==` reference comparison. */
export interface CachedCorrections {
readonly astro: AstroData;
readonly corrections: Map<string, NodalCorrection>;
}

/** A reusable node corrections cache. Pass to `createTidePredictor` to share
* astronomical computations across multiple station predictors. */
export interface CorrectionsCache {
readonly interval: number; // quantization interval in hours
/** Quantized astro — evaluated at bucket midpoint. Used for f/u corrections. */
getAstro(time: Date): AstroData;
/** V0 equilibrium arguments (d2r * model.value(baseAstro)) for all models,
* keyed by constituent name. Computed once per (models, start time) pair and
* shared across all predictors with the same start time. */
getV0(time: Date, models: Record<string, Constituent>): Map<string, number>;
getCorrections(
time: Date,
models: Record<string, Constituent>,
fundamentals: Fundamentals,
): CachedCorrections;
}

export interface CorrectionsCacheOptions {
/** Quantization interval in hours. Default: 24.
* Node corrections change by <0.01% per day, so 24h introduces <0.1mm error. */
interval?: number;
}

/**
* Create a reusable node corrections cache.
*
* When predicting tides for many stations at the same time, pass the same cache
* to each `createTidePredictor` call. Astronomical computations and constituent
* node corrections are computed once per time bucket and shared across all
* station predictors.
*
* @example
* ```ts
* import { createCorrectionsCache, createTidePredictor } from "@neaps/tide-predictor";
*
* const cache = createCorrectionsCache();
*
* for (const station of stations) {
* const predictor = createTidePredictor(station.constituents, { cache });
* results.push(predictor.getWaterLevelAtTime({ time }));
* }
* ```
*/
export function createCorrectionsCache({
interval = 24,
}: CorrectionsCacheOptions = {}): CorrectionsCache {
const intervalMs = interval * 3_600_000;

// exact ms → AstroData evaluated at that precise time (for V0 arguments)
const astroCache = new Map<number, AstroData>();

// fundamentals ref → bucket start (ms) → CachedCorrections
// The corrections Map is populated incrementally across calls so different
// models dicts can share the same CachedCorrections per (fundamentals, bucket).
const correctionsCache = new WeakMap<Fundamentals, Map<number, CachedCorrections>>();

// models ref → exact ms → constituent name → d2r * model.value(baseAstro)
const v0Cache = new WeakMap<Record<string, Constituent>, Map<number, Map<string, number>>>();

function bucketStart(time: Date): number {
return Math.floor(time.getTime() / intervalMs) * intervalMs;
}

function getCachedAstro(time: Date): AstroData {
const key = time.getTime();
let cached = astroCache.get(key);
if (!cached) {
cached = astro(time);
astroCache.set(key, cached);
}
return cached;
}

const cache: CorrectionsCache = {
interval,

// Quantize time to bucket and return astro evaluated at bucket midpoint.
getAstro(time: Date): AstroData {
return getCachedAstro(new Date(bucketStart(time) + intervalMs / 2));
},

getV0(time: Date, models: Record<string, Constituent>): Map<string, number> {
const key = time.getTime();

let byTime = v0Cache.get(models);
if (!byTime) {
byTime = new Map();
v0Cache.set(models, byTime);
}

let v0 = byTime.get(key);
if (!v0) {
const baseAstro = getCachedAstro(time);
v0 = new Map<string, number>();
for (const name of Object.keys(models)) {
v0.set(name, d2r * models[name].value(baseAstro));
}
byTime.set(key, v0);
}

return v0;
},

getCorrections(
time: Date,
models: Record<string, Constituent>,
fundamentals: Fundamentals,
): CachedCorrections {
const key = bucketStart(time);

let byBucket = correctionsCache.get(fundamentals);
if (!byBucket) {
byBucket = new Map();
correctionsCache.set(fundamentals, byBucket);
}

const cached = byBucket.get(key);
if (cached) return cached;

const astro = cache.getAstro(time);
const corrections = new Map<string, NodalCorrection>();
for (const name of Object.keys(models)) {
corrections.set(name, models[name].correction(astro, fundamentals));
}

const entry: CachedCorrections = { astro, corrections };
byBucket.set(key, entry);
return entry;
},
};

return cache;
}
4 changes: 4 additions & 0 deletions packages/tide-predictor/src/harmonics/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { Constituent } from "../constituents/types.js";
import { iho, Fundamentals } from "../node-corrections/index.js";
import { d2r } from "../astronomy/constants.js";
import type { HarmonicConstituent, Prediction } from "./prediction.js";
import type { CorrectionsCache } from "../corrections-cache.js";

export type * from "./prediction.js";

Expand All @@ -12,6 +13,7 @@ export interface HarmonicsOptions {
constituentModels?: Record<string, Constituent>;
offset: number | false;
fundamentals?: Fundamentals;
cache?: CorrectionsCache;
}

export interface PredictionOptions {
Expand Down Expand Up @@ -56,6 +58,7 @@ const harmonicsFactory = ({
constituentModels = defaultConstituentModels,
offset,
fundamentals = iho,
cache,
}: HarmonicsOptions): Harmonics => {
if (!Array.isArray(harmonicConstituents)) {
throw new Error("Harmonic constituents are not an array");
Expand Down Expand Up @@ -104,6 +107,7 @@ const harmonicsFactory = ({
constituentModels,
start: timeline.items[0] ?? start,
fundamentals,
cache,
});
};

Expand Down
Loading