@mkbabb/fourier 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,94 @@
1
- # Temporary Holding Version
1
+ # @mkbabb/fourier
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The Fourier series of a closed curve, in a few small functions: take a curve's
4
+ spectrum, draw any partial sum of it, walk its epicycle chain, and (on a
5
+ server) ask [fourier.babb.dev](https://fourier.babb.dev)'s API to turn an image
6
+ into one. It's the engine the fourier web app runs on. No dependencies.
7
+
8
+ ```sh
9
+ npm install @mkbabb/fourier
10
+ ```
11
+
12
+ ## The spectrum
13
+
14
+ A `Spectrum` is one closed curve z(θ) = Σ c_k e^{2πikθ}, θ in [0, 1), with
15
+ x = Re z and y = Im z. The coefficients are stored flat, in frequency order:
16
+
17
+ ```
18
+ c = [re0, im0, re+1, im+1, re-1, im-1, re+2, im+2, re-2, im-2, ...] // up to ±top
19
+ ```
20
+
21
+ `n`, when present, is N_c: the fewest harmonics whose partial sum sits within a
22
+ small tolerance of the whole band. This is the one shape everywhere, from the
23
+ API's JSON to the arrays you draw with.
24
+
25
+ ## Drawing a curve
26
+
27
+ ```ts
28
+ import { partialSum, resampleArcLength, spectrumOf, svgPathOf } from "@mkbabb/fourier";
29
+
30
+ // Points are flat too: [x0, y0, x1, y1, ...].
31
+ const outline = resampleArcLength(points, 1024);
32
+ const s = spectrumOf(outline, 200);
33
+
34
+ // The curve with its first 12 harmonics, at 512 points, as an SVG path.
35
+ const d = svgPathOf(partialSum(s, 12, 512));
36
+ ```
37
+
38
+ `partialSum` takes a fractional level. The pair ±k fades in as the level moves
39
+ from k − 1 to k, so animating the level from 0 to N writes the curve in one term
40
+ at a time, and nothing pops.
41
+
42
+ ## The epicycle chain
43
+
44
+ ```ts
45
+ import { chainAt, evaluateAt } from "@mkbabb/fourier";
46
+
47
+ const tip = evaluateAt(s, t); // [x, y] at θ = t
48
+ const chain = chainAt(s, t, 40); // [0, 0, x1, y1, ...]: the 40 largest circles, largest first
49
+ ```
50
+
51
+ ## The lens
52
+
53
+ `nearestParam` finds where a point sits along a sampled curve, and `lensBlend`
54
+ lets the curve give way to a lower partial sum of itself in a small window
55
+ around that spot. Near the pointer the drawing loses detail; at depth 0 it is
56
+ exactly the rest form.
57
+
58
+ ## Frame loop
59
+
60
+ `frameLoop(el, tick)` runs `tick(dtMs, nowMs)` once per frame, only while the
61
+ page is visible and `el` is on screen, with the step capped (50 ms by default)
62
+ so a tab that comes back doesn't jump. Return `false` from `tick` to stop.
63
+
64
+ ## The API client
65
+
66
+ The client calls the API's two token routes. A token is a secret: use the
67
+ client from a server, a build step or a script, and never put a token in code a
68
+ browser loads.
69
+
70
+ ```ts
71
+ import { createFourierClient } from "@mkbabb/fourier/client";
72
+
73
+ const fourier = createFourierClient({ baseUrl: "https://api.fourier.babb.dev", token: process.env.FOURIER_TOKEN! });
74
+
75
+ const { contour, spectrum } = await fourier.spectrumOfImage(imageBlob, { n_harmonics: 300 });
76
+ const s = await fourier.spectrumOfContour({ x, y }, { nHarmonics: 100 });
77
+ ```
78
+
79
+ A non-2xx answer throws `FourierApiError` with its `status`, the
80
+ problem+json body as `problem`, and for a 429 the wait the server asked for as
81
+ `retryAfterS`. Nothing is retried for you. Each token has its own rate (10 calls
82
+ a minute unless it was minted with another), and the routes store nothing: no
83
+ image, no contour, no session.
84
+
85
+ Tokens are minted by the site's admin, under Gallery, Tokens.
86
+
87
+ ## Versions
88
+
89
+ 0.x minors may break; pin an exact version. The API's major version is in its
90
+ path (`/api/v1/`).
91
+
92
+ The Python library in [fourier-analysis](https://github.com/mkbabb/fourier-analysis)
93
+ is the reference: `spectrumOf`, `partialSum`, `evaluateAt` and `chainAt` are
94
+ held equal to it within 1e-9 by golden fixtures.
@@ -0,0 +1,53 @@
1
+ /**
2
+ * A small client for the fourier API's token routes (`/api/v1/spectrum/*`).
3
+ *
4
+ * The token is a server-side secret: use this from a server, a build step or
5
+ * a script, never from code shipped to a browser (a token in a public bundle
6
+ * is a published token). The API answers browsers only from its own origins.
7
+ */
8
+ import type { Spectrum } from "./spectrum.js";
9
+ /** Extraction settings for `spectrumOfImage` (the API's `ContourSettings` subset). */
10
+ export interface ImageSettings {
11
+ strategy: string;
12
+ resize: number;
13
+ blur_sigma: number;
14
+ n_points: number;
15
+ n_harmonics: number;
16
+ n_classes: number;
17
+ min_contour_length: number;
18
+ min_contour_area: number;
19
+ max_contours: number | null;
20
+ smooth_contours: number;
21
+ ml_threshold: number;
22
+ ml_detail_threshold: number;
23
+ }
24
+ export interface Contour {
25
+ x: number[];
26
+ y: number[];
27
+ }
28
+ export interface ImageSpectrum {
29
+ /** The single closed tour through the image's contours, resampled. */
30
+ contour: Contour;
31
+ spectrum: Spectrum;
32
+ /** `[minX, minY, maxX, maxY]` of the resized image in the contour's units. */
33
+ imageBounds?: [number, number, number, number];
34
+ }
35
+ export interface FourierClient {
36
+ spectrumOfImage(image: Blob, settings?: Partial<ImageSettings>, signal?: AbortSignal): Promise<ImageSpectrum>;
37
+ spectrumOfContour(points: Contour, opts?: {
38
+ nHarmonics?: number;
39
+ nPoints?: number;
40
+ }, signal?: AbortSignal): Promise<Spectrum>;
41
+ }
42
+ /** A non-2xx answer: its status, its problem+json body, and for a 429 the wait the server asked for. */
43
+ export declare class FourierApiError extends Error {
44
+ readonly status: number;
45
+ readonly problem: unknown;
46
+ readonly retryAfterS?: number;
47
+ constructor(status: number, problem: unknown, retryAfterS?: number);
48
+ }
49
+ export declare function createFourierClient(opts: {
50
+ baseUrl: string;
51
+ token: string;
52
+ fetch?: typeof fetch;
53
+ }): FourierClient;
package/dist/client.js ADDED
@@ -0,0 +1,68 @@
1
+ /** A non-2xx answer: its status, its problem+json body, and for a 429 the wait the server asked for. */
2
+ export class FourierApiError extends Error {
3
+ status;
4
+ problem;
5
+ retryAfterS;
6
+ constructor(status, problem, retryAfterS) {
7
+ const p = problem;
8
+ const what = typeof p?.detail === "string" ? p.detail : typeof p?.title === "string" ? p.title : "";
9
+ super(`fourier API ${status}${what ? `: ${what}` : ""}`);
10
+ this.name = "FourierApiError";
11
+ this.status = status;
12
+ this.problem = problem;
13
+ if (retryAfterS !== undefined)
14
+ this.retryAfterS = retryAfterS;
15
+ }
16
+ }
17
+ const spectrumOfWire = (w) => w.n == null ? { c: Float64Array.from(w.c) } : { c: Float64Array.from(w.c), n: w.n };
18
+ export function createFourierClient(opts) {
19
+ if (!opts.baseUrl)
20
+ throw new TypeError("createFourierClient: baseUrl is required");
21
+ if (!opts.token)
22
+ throw new TypeError("createFourierClient: token is required");
23
+ const base = opts.baseUrl.replace(/\/+$/, "");
24
+ const doFetch = opts.fetch ?? fetch;
25
+ async function call(path, body, json, signal) {
26
+ const headers = { Authorization: `Bearer ${opts.token}`, Accept: "application/json" };
27
+ if (json)
28
+ headers["Content-Type"] = "application/json";
29
+ const init = { method: "POST", headers, body };
30
+ if (signal)
31
+ init.signal = signal;
32
+ const res = await doFetch(`${base}${path}`, init);
33
+ if (!res.ok) {
34
+ let problem = null;
35
+ try {
36
+ problem = await res.json();
37
+ }
38
+ catch {
39
+ problem = null;
40
+ }
41
+ const ra = Number(res.headers.get("Retry-After"));
42
+ throw new FourierApiError(res.status, problem, res.status === 429 && Number.isFinite(ra) ? ra : undefined);
43
+ }
44
+ return (await res.json());
45
+ }
46
+ return {
47
+ async spectrumOfImage(image, settings = {}, signal) {
48
+ const form = new FormData();
49
+ form.append("image", image, "image");
50
+ form.append("settings", JSON.stringify(settings));
51
+ const r = await call("/api/v1/spectrum/image", form, false, signal);
52
+ const out = { contour: r.contour, spectrum: spectrumOfWire(r.spectrum) };
53
+ const b = r.image_bounds;
54
+ if (b)
55
+ out.imageBounds = [b.minX, b.minY, b.maxX, b.maxY];
56
+ return out;
57
+ },
58
+ async spectrumOfContour(points, o = {}, signal) {
59
+ const body = { points };
60
+ if (o.nHarmonics !== undefined)
61
+ body.n_harmonics = o.nHarmonics;
62
+ if (o.nPoints !== undefined)
63
+ body.n_points = o.nPoints;
64
+ const r = await call("/api/v1/spectrum/contour", JSON.stringify(body), true, signal);
65
+ return spectrumOfWire(r.spectrum);
66
+ },
67
+ };
68
+ }
@@ -0,0 +1,26 @@
1
+ import { type Spectrum } from "./spectrum.js";
2
+ /** Reusable buffers for `partialSum` (each of length `m`). */
3
+ export interface Scratch {
4
+ re: Float64Array;
5
+ im: Float64Array;
6
+ }
7
+ /** The default sample count: a power of two, at least 256 and above four times the band. */
8
+ export declare function samplesFor(s: Spectrum): number;
9
+ /**
10
+ * The weighted partial sum S_level(θ) = Σ_k weight(k, level)·c_k·e^{2πikθ} at
11
+ * `m` points θ = j/m, by one inverse FFT. `level` may be fractional (see
12
+ * `weight`); `m` must be a power of two above twice the band in use.
13
+ * Returns `[x0, y0, x1, y1, ...]`, written into `out` when given.
14
+ */
15
+ export declare function partialSum(s: Spectrum, level: number, m?: number, scratch?: Scratch, out?: Float64Array): Float64Array;
16
+ /**
17
+ * The curve at θ = `t`, summing the chain's first `terms` vectors (the
18
+ * largest, as the Python `EpicycleChain` orders them); all of them by default.
19
+ */
20
+ export declare function evaluateAt(s: Spectrum, t: number, terms?: number): [number, number];
21
+ /**
22
+ * The chain's cumulative positions at θ = `t`: `[0, 0, x1, y1, ...]`, the
23
+ * origin and then the tip of each of the first `terms` vectors in descending
24
+ * amplitude (Python's `positions_at`). The last pair is `evaluateAt(s, t, terms)`.
25
+ */
26
+ export declare function chainAt(s: Spectrum, t: number, terms?: number): Float64Array;
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Evaluating a spectrum: partial sums along the whole curve (one inverse FFT)
3
+ * and the epicycle chain at one moment.
4
+ */
5
+ import { ifft } from "./fft.js";
6
+ import { coef, frequencyAt, topOf, weight } from "./spectrum.js";
7
+ /** The default sample count: a power of two, at least 256 and above four times the band. */
8
+ export function samplesFor(s) {
9
+ let m = 256;
10
+ while (m <= 4 * topOf(s))
11
+ m <<= 1;
12
+ return m;
13
+ }
14
+ /**
15
+ * The weighted partial sum S_level(θ) = Σ_k weight(k, level)·c_k·e^{2πikθ} at
16
+ * `m` points θ = j/m, by one inverse FFT. `level` may be fractional (see
17
+ * `weight`); `m` must be a power of two above twice the band in use.
18
+ * Returns `[x0, y0, x1, y1, ...]`, written into `out` when given.
19
+ */
20
+ export function partialSum(s, level, m = samplesFor(s), scratch = { re: new Float64Array(m), im: new Float64Array(m) }, out = new Float64Array(2 * m)) {
21
+ const { re, im } = scratch;
22
+ re.fill(0);
23
+ im.fill(0);
24
+ const top = Math.min(topOf(s), Math.ceil(level));
25
+ if (2 * top >= m)
26
+ throw new RangeError(`partialSum: m = ${m} cannot carry the band ±${top}`);
27
+ for (let k = -top; k <= top; k++) {
28
+ const w = weight(k, level);
29
+ if (!w)
30
+ continue;
31
+ const [a, b] = coef(s, k);
32
+ const i = (k + m) % m;
33
+ re[i] = re[i] + w * a;
34
+ im[i] = im[i] + w * b;
35
+ }
36
+ ifft(re, im);
37
+ for (let j = 0; j < m; j++) {
38
+ out[2 * j] = re[j];
39
+ out[2 * j + 1] = im[j];
40
+ }
41
+ return out;
42
+ }
43
+ /** Each spectrum's pair slots in descending amplitude, computed once per array. */
44
+ const ORDER = new WeakMap();
45
+ function amplitudeOrder(s) {
46
+ let order = ORDER.get(s.c);
47
+ if (!order) {
48
+ const pairs = s.c.length >> 1;
49
+ const amp = new Float64Array(pairs);
50
+ for (let j = 0; j < pairs; j++)
51
+ amp[j] = Math.hypot(s.c[2 * j], s.c[2 * j + 1]);
52
+ // A stable sort over the frequency order: the Python chain's order exactly.
53
+ order = Uint32Array.from(Array.from({ length: pairs }, (_, j) => j).sort((a, b) => amp[b] - amp[a]));
54
+ ORDER.set(s.c, order);
55
+ }
56
+ return order;
57
+ }
58
+ /**
59
+ * The curve at θ = `t`, summing the chain's first `terms` vectors (the
60
+ * largest, as the Python `EpicycleChain` orders them); all of them by default.
61
+ */
62
+ export function evaluateAt(s, t, terms) {
63
+ const order = amplitudeOrder(s);
64
+ const n = Math.min(terms ?? order.length, order.length);
65
+ let x = 0;
66
+ let y = 0;
67
+ for (let i = 0; i < n; i++) {
68
+ const j = order[i];
69
+ const a = 2 * Math.PI * frequencyAt(j) * t;
70
+ const ca = Math.cos(a);
71
+ const sa = Math.sin(a);
72
+ const re = s.c[2 * j];
73
+ const im = s.c[2 * j + 1];
74
+ x += re * ca - im * sa;
75
+ y += re * sa + im * ca;
76
+ }
77
+ return [x, y];
78
+ }
79
+ /**
80
+ * The chain's cumulative positions at θ = `t`: `[0, 0, x1, y1, ...]`, the
81
+ * origin and then the tip of each of the first `terms` vectors in descending
82
+ * amplitude (Python's `positions_at`). The last pair is `evaluateAt(s, t, terms)`.
83
+ */
84
+ export function chainAt(s, t, terms) {
85
+ const order = amplitudeOrder(s);
86
+ const n = Math.min(terms ?? order.length, order.length);
87
+ const out = new Float64Array(2 * (n + 1));
88
+ let x = 0;
89
+ let y = 0;
90
+ for (let i = 0; i < n; i++) {
91
+ const j = order[i];
92
+ const a = 2 * Math.PI * frequencyAt(j) * t;
93
+ const ca = Math.cos(a);
94
+ const sa = Math.sin(a);
95
+ const re = s.c[2 * j];
96
+ const im = s.c[2 * j + 1];
97
+ x += re * ca - im * sa;
98
+ y += re * sa + im * ca;
99
+ out[2 * i + 2] = x;
100
+ out[2 * i + 3] = y;
101
+ }
102
+ return out;
103
+ }
package/dist/fft.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ /** Forward DFT in place, unscaled: X_k = Σ_j x_j e^{−2πijk/n}. `n` must be a power of two. */
2
+ export declare function fft(re: Float64Array, im: Float64Array): void;
3
+ /** Inverse DFT in place, unscaled: x_j = Σ_k X_k e^{+2πijk/n}. `n` must be a power of two. */
4
+ export declare function ifft(re: Float64Array, im: Float64Array): void;
package/dist/fft.js ADDED
@@ -0,0 +1,51 @@
1
+ /** In-place radix-2 FFT; `sign` −1 is the forward transform, +1 the inverse. Unscaled. */
2
+ function transform(re, im, sign) {
3
+ const n = re.length;
4
+ if (n & (n - 1) || im.length !== n)
5
+ throw new RangeError(`fft: length ${n} is not a power of two matched by im (${im.length})`);
6
+ for (let i = 1, j = 0; i < n; i++) {
7
+ let bit = n >> 1;
8
+ for (; j & bit; bit >>= 1)
9
+ j ^= bit;
10
+ j ^= bit;
11
+ if (i < j) {
12
+ const r = re[i];
13
+ re[i] = re[j];
14
+ re[j] = r;
15
+ const m = im[i];
16
+ im[i] = im[j];
17
+ im[j] = m;
18
+ }
19
+ }
20
+ for (let len = 2; len <= n; len <<= 1) {
21
+ const a = (sign * 2 * Math.PI) / len;
22
+ const wr = Math.cos(a);
23
+ const wi = Math.sin(a);
24
+ const half = len >> 1;
25
+ for (let i = 0; i < n; i += len) {
26
+ let cr = 1;
27
+ let ci = 0;
28
+ for (let j = 0; j < half; j++) {
29
+ const p = i + j;
30
+ const q = p + half;
31
+ const tr = re[q] * cr - im[q] * ci;
32
+ const ti = re[q] * ci + im[q] * cr;
33
+ re[q] = re[p] - tr;
34
+ im[q] = im[p] - ti;
35
+ re[p] = re[p] + tr;
36
+ im[p] = im[p] + ti;
37
+ const nr = cr * wr - ci * wi;
38
+ ci = cr * wi + ci * wr;
39
+ cr = nr;
40
+ }
41
+ }
42
+ }
43
+ }
44
+ /** Forward DFT in place, unscaled: X_k = Σ_j x_j e^{−2πijk/n}. `n` must be a power of two. */
45
+ export function fft(re, im) {
46
+ transform(re, im, -1);
47
+ }
48
+ /** Inverse DFT in place, unscaled: x_j = Σ_k X_k e^{+2πijk/n}. `n` must be a power of two. */
49
+ export function ifft(re, im) {
50
+ transform(re, im, 1);
51
+ }
@@ -0,0 +1,10 @@
1
+ export { coef, fromComponents, toComponents, topOf, weight } from "./spectrum.js";
2
+ export type { BasisComponent, Spectrum } from "./spectrum.js";
3
+ export { fft, ifft } from "./fft.js";
4
+ export { convergingLevel, resampleArcLength, spectrumOf } from "./transform.js";
5
+ export { chainAt, evaluateAt, partialSum, samplesFor } from "./evaluate.js";
6
+ export type { Scratch } from "./evaluate.js";
7
+ export { lensBlend, nearestParam } from "./lens.js";
8
+ export { svgPathOf, tracePath } from "./render.js";
9
+ export { frameLoop } from "./loop.js";
10
+ export type { FrameLoop } from "./loop.js";
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ export { coef, fromComponents, toComponents, topOf, weight } from "./spectrum.js";
2
+ export { fft, ifft } from "./fft.js";
3
+ export { convergingLevel, resampleArcLength, spectrumOf } from "./transform.js";
4
+ export { chainAt, evaluateAt, partialSum, samplesFor } from "./evaluate.js";
5
+ export { lensBlend, nearestParam } from "./lens.js";
6
+ export { svgPathOf, tracePath } from "./render.js";
7
+ export { frameLoop } from "./loop.js";
package/dist/lens.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The local spectral lens: near a point on the curve, the curve gives way to
3
+ * a lower partial sum of itself, in a small window along its parameter.
4
+ *
5
+ * P(θ) = F(θ) + depth · g(θ) · (L(θ) − F(θ)), g = exp(−(Δθ/σ)²), Δθ wrapped
6
+ * on the circle. F and L are two partial sums sampled at the same θ_j (the
7
+ * rest form and the lower level). Windowing the removed band in θ is a local
8
+ * low-pass: no point is pushed in the plane, the curve only loses detail
9
+ * there, and at depth 0 it is exactly F.
10
+ */
11
+ /**
12
+ * The parameter θ0 in [0, 1) of the point on a sampled closed curve
13
+ * `[x0, y0, ...]` nearest (x, y), projected onto the nearest segment so it
14
+ * moves continuously between samples.
15
+ */
16
+ export declare function nearestParam(points: Float64Array, x: number, y: number): number;
17
+ /**
18
+ * Blend the rest form `full` toward `low` in a window of width `sigma` (in θ)
19
+ * around `theta0`, by `depth` in [0, 1]. Both inputs are `[x0, y0, ...]` at
20
+ * the same m samples; the result is written into `out` and returned.
21
+ */
22
+ export declare function lensBlend(full: Float64Array, low: Float64Array, theta0: number, sigma: number, depth: number, out: Float64Array): Float64Array;
package/dist/lens.js ADDED
@@ -0,0 +1,57 @@
1
+ /**
2
+ * The local spectral lens: near a point on the curve, the curve gives way to
3
+ * a lower partial sum of itself, in a small window along its parameter.
4
+ *
5
+ * P(θ) = F(θ) + depth · g(θ) · (L(θ) − F(θ)), g = exp(−(Δθ/σ)²), Δθ wrapped
6
+ * on the circle. F and L are two partial sums sampled at the same θ_j (the
7
+ * rest form and the lower level). Windowing the removed band in θ is a local
8
+ * low-pass: no point is pushed in the plane, the curve only loses detail
9
+ * there, and at depth 0 it is exactly F.
10
+ */
11
+ /**
12
+ * The parameter θ0 in [0, 1) of the point on a sampled closed curve
13
+ * `[x0, y0, ...]` nearest (x, y), projected onto the nearest segment so it
14
+ * moves continuously between samples.
15
+ */
16
+ export function nearestParam(points, x, y) {
17
+ const m = points.length >> 1;
18
+ if (!m)
19
+ return 0;
20
+ let best = 0;
21
+ let bestU = 0;
22
+ let bestD = Infinity;
23
+ for (let j = 0; j < m; j++) {
24
+ const ax = points[2 * j];
25
+ const ay = points[2 * j + 1];
26
+ const k = (j + 1) % m;
27
+ const dx = points[2 * k] - ax;
28
+ const dy = points[2 * k + 1] - ay;
29
+ const len2 = dx * dx + dy * dy;
30
+ const u = len2 > 0 ? Math.min(1, Math.max(0, ((x - ax) * dx + (y - ay) * dy) / len2)) : 0;
31
+ const ex = ax + u * dx - x;
32
+ const ey = ay + u * dy - y;
33
+ const d = ex * ex + ey * ey;
34
+ if (d < bestD) {
35
+ bestD = d;
36
+ best = j;
37
+ bestU = u;
38
+ }
39
+ }
40
+ return ((best + bestU) / m) % 1;
41
+ }
42
+ /**
43
+ * Blend the rest form `full` toward `low` in a window of width `sigma` (in θ)
44
+ * around `theta0`, by `depth` in [0, 1]. Both inputs are `[x0, y0, ...]` at
45
+ * the same m samples; the result is written into `out` and returned.
46
+ */
47
+ export function lensBlend(full, low, theta0, sigma, depth, out) {
48
+ const m = full.length >> 1;
49
+ for (let j = 0; j < m; j++) {
50
+ let d = j / m - theta0;
51
+ d -= Math.round(d);
52
+ const w = sigma > 0 ? depth * Math.exp(-(d * d) / (sigma * sigma)) : 0;
53
+ out[2 * j] = full[2 * j] + w * (low[2 * j] - full[2 * j]);
54
+ out[2 * j + 1] = full[2 * j + 1] + w * (low[2 * j + 1] - full[2 * j + 1]);
55
+ }
56
+ return out;
57
+ }
package/dist/loop.d.ts ADDED
@@ -0,0 +1,20 @@
1
+ /**
2
+ * One animation frame loop for an element: it runs only while the page is
3
+ * visible and the element is on screen, and a step never exceeds `maxStepMs`,
4
+ * so a tab that comes back resumes where it was instead of jumping.
5
+ */
6
+ export interface FrameLoop {
7
+ /** Run (or resume) the loop. */
8
+ start(): void;
9
+ /** Stop until the next `start`. */
10
+ stop(): void;
11
+ /** Stop and release the observers. */
12
+ dispose(): void;
13
+ }
14
+ /**
15
+ * `tick(dtMs, nowMs)` runs once per frame with the capped step; it returns
16
+ * whether to keep going, and a `false` stops the loop (zero callbacks after).
17
+ */
18
+ export declare function frameLoop(el: Element, tick: (dtMs: number, nowMs: number) => boolean, opts?: {
19
+ maxStepMs?: number;
20
+ }): FrameLoop;
package/dist/loop.js ADDED
@@ -0,0 +1,60 @@
1
+ /**
2
+ * `tick(dtMs, nowMs)` runs once per frame with the capped step; it returns
3
+ * whether to keep going, and a `false` stops the loop (zero callbacks after).
4
+ */
5
+ export function frameLoop(el, tick, opts = {}) {
6
+ const maxStep = opts.maxStepMs ?? 50;
7
+ let wanted = false;
8
+ let onScreen = true;
9
+ let raf = 0;
10
+ let last = -1;
11
+ const runnable = () => wanted && onScreen && document.visibilityState === "visible";
12
+ const frame = (now) => {
13
+ raf = 0;
14
+ const dt = last < 0 ? 0 : Math.min(maxStep, Math.max(0, now - last));
15
+ last = now;
16
+ if (!tick(dt, now)) {
17
+ wanted = false;
18
+ last = -1;
19
+ return;
20
+ }
21
+ if (runnable())
22
+ raf = requestAnimationFrame(frame);
23
+ };
24
+ const sync = () => {
25
+ if (runnable()) {
26
+ if (!raf)
27
+ raf = requestAnimationFrame(frame);
28
+ }
29
+ else {
30
+ if (raf)
31
+ cancelAnimationFrame(raf);
32
+ raf = 0;
33
+ last = -1;
34
+ }
35
+ };
36
+ const io = typeof IntersectionObserver === "undefined"
37
+ ? null
38
+ : new IntersectionObserver((entries) => {
39
+ onScreen = entries[entries.length - 1].isIntersecting;
40
+ sync();
41
+ });
42
+ io?.observe(el);
43
+ document.addEventListener("visibilitychange", sync);
44
+ return {
45
+ start() {
46
+ wanted = true;
47
+ sync();
48
+ },
49
+ stop() {
50
+ wanted = false;
51
+ sync();
52
+ },
53
+ dispose() {
54
+ wanted = false;
55
+ sync();
56
+ io?.disconnect();
57
+ document.removeEventListener("visibilitychange", sync);
58
+ },
59
+ };
60
+ }
@@ -0,0 +1,10 @@
1
+ /** Drawing a sampled closed curve `[x0, y0, ...]` to a canvas path or an SVG path. */
2
+ /** Trace the points into a Path2D or a 2D context as one polyline, closed by default. */
3
+ export declare function tracePath(path: Path2D | CanvasRenderingContext2D, points: ArrayLike<number>, closed?: boolean): void;
4
+ /**
5
+ * The points as a closed SVG path `d`: a Catmull-Rom spline through every
6
+ * point (tangents wrap at the seam), emitted at `decimals` places without
7
+ * trailing zeros. Rounding happens at emission, since the control points are
8
+ * computed from the points here.
9
+ */
10
+ export declare function svgPathOf(points: ArrayLike<number>, decimals?: number): string;
package/dist/render.js ADDED
@@ -0,0 +1,34 @@
1
+ /** Drawing a sampled closed curve `[x0, y0, ...]` to a canvas path or an SVG path. */
2
+ /** Trace the points into a Path2D or a 2D context as one polyline, closed by default. */
3
+ export function tracePath(path, points, closed = true) {
4
+ if (points.length < 2)
5
+ return;
6
+ path.moveTo(points[0], points[1]);
7
+ for (let j = 2; j + 1 < points.length; j += 2)
8
+ path.lineTo(points[j], points[j + 1]);
9
+ if (closed)
10
+ path.closePath();
11
+ }
12
+ /**
13
+ * The points as a closed SVG path `d`: a Catmull-Rom spline through every
14
+ * point (tangents wrap at the seam), emitted at `decimals` places without
15
+ * trailing zeros. Rounding happens at emission, since the control points are
16
+ * computed from the points here.
17
+ */
18
+ export function svgPathOf(points, decimals = 2) {
19
+ const count = points.length >> 1;
20
+ if (count < 2)
21
+ return "";
22
+ const f = (v) => String(Number(v.toFixed(decimals)));
23
+ const x = (i) => points[2 * (((i % count) + count) % count)];
24
+ const y = (i) => points[2 * (((i % count) + count) % count) + 1];
25
+ let d = `M${f(x(0))},${f(y(0))}`;
26
+ for (let i = 0; i < count; i++) {
27
+ const c1x = x(i) + (x(i + 1) - x(i - 1)) / 6;
28
+ const c1y = y(i) + (y(i + 1) - y(i - 1)) / 6;
29
+ const c2x = x(i + 1) - (x(i + 2) - x(i)) / 6;
30
+ const c2y = y(i + 1) - (y(i + 2) - y(i)) / 6;
31
+ d += ` C${f(c1x)},${f(c1y)} ${f(c2x)},${f(c2y)} ${f(x(i + 1))},${f(y(i + 1))}`;
32
+ }
33
+ return `${d} Z`;
34
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * A closed curve's Fourier series, stored flat in frequency order.
3
+ *
4
+ * The harmonics are 0, +1, -1, +2, -2, ... up to ±top, each as an [re, im]
5
+ * pair: `c = [re0, im0, re+1, im+1, re-1, im-1, ...]`. The curve is
6
+ * `z(θ) = Σ_k c_k e^{2πikθ}` for θ in [0, 1), with x = Re z and y = Im z.
7
+ * This is the one wire shape between the fourier API, the fourier web app and
8
+ * any other consumer.
9
+ */
10
+ export interface Spectrum {
11
+ /** [re0, im0, re+1, im+1, re-1, im-1, ...] up to ±top. */
12
+ c: Float64Array;
13
+ /** N_c, the converging level, when the producer measured one. */
14
+ n?: number;
15
+ }
16
+ /** One rotating vector of an epicycle chain, as the fourier API sends it. */
17
+ export interface BasisComponent {
18
+ /** The frequency k. */
19
+ index: number;
20
+ /** c_k as [re, im]. */
21
+ coefficient: [number, number];
22
+ amplitude: number;
23
+ phase: number;
24
+ }
25
+ /** The highest harmonic a spectrum stores. */
26
+ export declare const topOf: (s: Spectrum) => number;
27
+ /** The pair slot of frequency `k` in the flat order. */
28
+ export declare const slotOf: (k: number) => number;
29
+ /** The frequency stored at pair slot `j` (the inverse of `slotOf`). */
30
+ export declare const frequencyAt: (j: number) => number;
31
+ /** The coefficient of harmonic `k`, or zero past the stored band. */
32
+ export declare function coef(s: Spectrum, k: number): [number, number];
33
+ /**
34
+ * The weight of the pair ±k at a fractional `level`: 0 at or below k − 1,
35
+ * 1 from k up, smoothstep between. A level that moves continuously moves the
36
+ * curve continuously, so no harmonic pops in.
37
+ */
38
+ export declare const weight: (k: number, level: number) => number;
39
+ /**
40
+ * The spectrum as epicycle components in descending amplitude (ties keep the
41
+ * frequency order), the order the Python `EpicycleChain` and the API use.
42
+ */
43
+ export declare function toComponents(s: Spectrum): BasisComponent[];
44
+ /** Components in any order back to a spectrum. */
45
+ export declare function fromComponents(cs: readonly BasisComponent[]): Spectrum;
@@ -0,0 +1,47 @@
1
+ /** The highest harmonic a spectrum stores. */
2
+ export const topOf = (s) => (s.c.length / 2 - 1) / 2;
3
+ /** The pair slot of frequency `k` in the flat order. */
4
+ export const slotOf = (k) => (k === 0 ? 0 : k > 0 ? 2 * k - 1 : -2 * k);
5
+ /** The frequency stored at pair slot `j` (the inverse of `slotOf`). */
6
+ export const frequencyAt = (j) => (j === 0 ? 0 : j % 2 ? (j + 1) / 2 : -j / 2);
7
+ /** The coefficient of harmonic `k`, or zero past the stored band. */
8
+ export function coef(s, k) {
9
+ const i = slotOf(k);
10
+ return 2 * i + 1 < s.c.length ? [s.c[2 * i], s.c[2 * i + 1]] : [0, 0];
11
+ }
12
+ const smoothstep = (x) => {
13
+ const t = Math.min(1, Math.max(0, x));
14
+ return t * t * (3 - 2 * t);
15
+ };
16
+ /**
17
+ * The weight of the pair ±k at a fractional `level`: 0 at or below k − 1,
18
+ * 1 from k up, smoothstep between. A level that moves continuously moves the
19
+ * curve continuously, so no harmonic pops in.
20
+ */
21
+ export const weight = (k, level) => (k === 0 ? 1 : smoothstep(level - Math.abs(k) + 1));
22
+ /**
23
+ * The spectrum as epicycle components in descending amplitude (ties keep the
24
+ * frequency order), the order the Python `EpicycleChain` and the API use.
25
+ */
26
+ export function toComponents(s) {
27
+ const out = [];
28
+ for (let j = 0; 2 * j + 1 < s.c.length; j++) {
29
+ const re = s.c[2 * j];
30
+ const im = s.c[2 * j + 1];
31
+ out.push({ index: frequencyAt(j), coefficient: [re, im], amplitude: Math.hypot(re, im), phase: Math.atan2(im, re) });
32
+ }
33
+ return out.sort((a, b) => b.amplitude - a.amplitude);
34
+ }
35
+ /** Components in any order back to a spectrum. */
36
+ export function fromComponents(cs) {
37
+ let top = 0;
38
+ for (const c of cs)
39
+ top = Math.max(top, Math.abs(c.index));
40
+ const c = new Float64Array(2 * (2 * top + 1));
41
+ for (const { index, coefficient } of cs) {
42
+ const i = slotOf(index);
43
+ c[2 * i] = coefficient[0];
44
+ c[2 * i + 1] = coefficient[1];
45
+ }
46
+ return { c };
47
+ }
@@ -0,0 +1,24 @@
1
+ import { type Spectrum } from "./spectrum.js";
2
+ /**
3
+ * Resample a closed polyline `[x0, y0, x1, y1, ...]` to `n` points evenly
4
+ * spaced in arc length, the first on the first vertex. A repeated closing
5
+ * vertex and zero-length steps are ignored. (The Python
6
+ * `resample_arc_length` also weights samples toward turns; this is its
7
+ * `detail=0` case, which is what an even parametrisation needs.)
8
+ */
9
+ export declare function resampleArcLength(points: Float64Array, n: number): Float64Array;
10
+ /**
11
+ * The spectrum of a sampled closed curve `[x0, y0, ...]` (N samples, taken as
12
+ * z_j = x_j + i·y_j at θ = j/N), to ±`harmonics`:
13
+ * c_k = (1/N) Σ_j z_j e^{−2πijk/N}. This is `EpicycleChain.from_signal`
14
+ * (`fourier_coefficients` = FFT/N) in frequency order. `harmonics` is
15
+ * clamped to N/2; at exactly N/2 the −N/2 slot is the +N/2 one and stays zero,
16
+ * as Python leaves it out.
17
+ */
18
+ export declare function spectrumOf(points: Float64Array, harmonics: number): Spectrum;
19
+ /**
20
+ * N_c: the least level whose partial sum lies within `epsilon` (Hausdorff, in
21
+ * the curve's units) of the full stored band, capped at `cap`. Both curves are
22
+ * sampled at `m` points (a power of two above twice the band).
23
+ */
24
+ export declare function convergingLevel(s: Spectrum, epsilon: number, cap?: number, m?: number): number;
@@ -0,0 +1,169 @@
1
+ /**
2
+ * Contour → spectrum. The Python engine (`fourier_analysis`) stays canonical
3
+ * for image → contour; this is its forward transform written once in
4
+ * TypeScript and held equal to it by golden fixtures (test/golden.test.ts).
5
+ */
6
+ import { fft } from "./fft.js";
7
+ import { partialSum } from "./evaluate.js";
8
+ import { slotOf, topOf } from "./spectrum.js";
9
+ /**
10
+ * Resample a closed polyline `[x0, y0, x1, y1, ...]` to `n` points evenly
11
+ * spaced in arc length, the first on the first vertex. A repeated closing
12
+ * vertex and zero-length steps are ignored. (The Python
13
+ * `resample_arc_length` also weights samples toward turns; this is its
14
+ * `detail=0` case, which is what an even parametrisation needs.)
15
+ */
16
+ export function resampleArcLength(points, n) {
17
+ const xs = [];
18
+ const ys = [];
19
+ for (let j = 0; j + 1 < points.length; j += 2) {
20
+ const x = points[j];
21
+ const y = points[j + 1];
22
+ const k = xs.length;
23
+ if (k && Math.hypot(x - xs[k - 1], y - ys[k - 1]) <= 1e-12)
24
+ continue;
25
+ xs.push(x);
26
+ ys.push(y);
27
+ }
28
+ while (xs.length > 1 && Math.hypot(xs[0] - xs[xs.length - 1], ys[0] - ys[ys.length - 1]) <= 1e-12) {
29
+ xs.pop();
30
+ ys.pop();
31
+ }
32
+ const m = xs.length;
33
+ const out = new Float64Array(2 * n);
34
+ if (m < 2) {
35
+ for (let i = 0; i < n; i++) {
36
+ out[2 * i] = xs[0] ?? 0;
37
+ out[2 * i + 1] = ys[0] ?? 0;
38
+ }
39
+ return out;
40
+ }
41
+ const cum = new Float64Array(m + 1);
42
+ for (let i = 0; i < m; i++) {
43
+ const j = (i + 1) % m;
44
+ cum[i + 1] = cum[i] + Math.hypot(xs[j] - xs[i], ys[j] - ys[i]);
45
+ }
46
+ const total = cum[m];
47
+ let seg = 0;
48
+ for (let i = 0; i < n; i++) {
49
+ const s = (i / n) * total;
50
+ while (seg < m - 1 && cum[seg + 1] <= s)
51
+ seg++;
52
+ const len = cum[seg + 1] - cum[seg];
53
+ const u = len > 0 ? (s - cum[seg]) / len : 0;
54
+ const j = (seg + 1) % m;
55
+ out[2 * i] = xs[seg] + u * (xs[j] - xs[seg]);
56
+ out[2 * i + 1] = ys[seg] + u * (ys[j] - ys[seg]);
57
+ }
58
+ return out;
59
+ }
60
+ /**
61
+ * The spectrum of a sampled closed curve `[x0, y0, ...]` (N samples, taken as
62
+ * z_j = x_j + i·y_j at θ = j/N), to ±`harmonics`:
63
+ * c_k = (1/N) Σ_j z_j e^{−2πijk/N}. This is `EpicycleChain.from_signal`
64
+ * (`fourier_coefficients` = FFT/N) in frequency order. `harmonics` is
65
+ * clamped to N/2; at exactly N/2 the −N/2 slot is the +N/2 one and stays zero,
66
+ * as Python leaves it out.
67
+ */
68
+ export function spectrumOf(points, harmonics) {
69
+ const n = points.length >> 1;
70
+ const top = Math.max(0, Math.min(Math.floor(harmonics), n >> 1));
71
+ const c = new Float64Array(2 * (2 * top + 1));
72
+ const put = (k, re, im) => {
73
+ const i = slotOf(k);
74
+ c[2 * i] = re / n;
75
+ c[2 * i + 1] = im / n;
76
+ };
77
+ if (n && !(n & (n - 1))) {
78
+ const re = new Float64Array(n);
79
+ const im = new Float64Array(n);
80
+ for (let j = 0; j < n; j++) {
81
+ re[j] = points[2 * j];
82
+ im[j] = points[2 * j + 1];
83
+ }
84
+ fft(re, im);
85
+ put(0, re[0], im[0]);
86
+ for (let k = 1; k <= top; k++) {
87
+ put(k, re[k], im[k]);
88
+ if (2 * k !== n)
89
+ put(-k, re[n - k], im[n - k]);
90
+ }
91
+ return { c };
92
+ }
93
+ // Not a power of two: the direct sum, only for the 2·top + 1 harmonics kept.
94
+ for (let k = -top; k <= top; k++) {
95
+ if (k < 0 && -2 * k === n)
96
+ continue;
97
+ let re = 0;
98
+ let im = 0;
99
+ for (let j = 0; j < n; j++) {
100
+ const a = (-2 * Math.PI * ((k * j) % n)) / n;
101
+ const ca = Math.cos(a);
102
+ const sa = Math.sin(a);
103
+ const x = points[2 * j];
104
+ const y = points[2 * j + 1];
105
+ re += x * ca - y * sa;
106
+ im += x * sa + y * ca;
107
+ }
108
+ put(k, re, im);
109
+ }
110
+ return { c };
111
+ }
112
+ /**
113
+ * Whether two point sets `[x0, y0, ...]` lie within `eps` of each other
114
+ * (symmetric Hausdorff ≤ eps), on a grid of `eps` cells so each point checks
115
+ * only its neighbourhood.
116
+ */
117
+ function withinHausdorff(a, b, eps) {
118
+ const covers = (from, to) => {
119
+ const grid = new Map();
120
+ for (let j = 0; j < to.length; j += 2) {
121
+ const key = `${Math.floor(to[j] / eps)},${Math.floor(to[j + 1] / eps)}`;
122
+ const cell = grid.get(key);
123
+ if (cell)
124
+ cell.push(j);
125
+ else
126
+ grid.set(key, [j]);
127
+ }
128
+ const e2 = eps * eps;
129
+ for (let j = 0; j < from.length; j += 2) {
130
+ const x = from[j];
131
+ const y = from[j + 1];
132
+ const gx = Math.floor(x / eps);
133
+ const gy = Math.floor(y / eps);
134
+ let hit = false;
135
+ for (let dx = -1; dx <= 1 && !hit; dx++)
136
+ for (let dy = -1; dy <= 1 && !hit; dy++) {
137
+ const cell = grid.get(`${gx + dx},${gy + dy}`);
138
+ if (!cell)
139
+ continue;
140
+ for (const i of cell) {
141
+ const ex = to[i] - x;
142
+ const ey = to[i + 1] - y;
143
+ if (ex * ex + ey * ey <= e2) {
144
+ hit = true;
145
+ break;
146
+ }
147
+ }
148
+ }
149
+ if (!hit)
150
+ return false;
151
+ }
152
+ return true;
153
+ };
154
+ return covers(a, b) && covers(b, a);
155
+ }
156
+ /**
157
+ * N_c: the least level whose partial sum lies within `epsilon` (Hausdorff, in
158
+ * the curve's units) of the full stored band, capped at `cap`. Both curves are
159
+ * sampled at `m` points (a power of two above twice the band).
160
+ */
161
+ export function convergingLevel(s, epsilon, cap = Infinity, m) {
162
+ const top = Math.min(topOf(s), Math.floor(cap));
163
+ const ref = partialSum(s, topOf(s), m);
164
+ for (let level = 0; level < top; level++) {
165
+ if (withinHausdorff(partialSum(s, level, m), ref, epsilon))
166
+ return level;
167
+ }
168
+ return top;
169
+ }
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
- "name": "@mkbabb/fourier",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@mkbabb/fourier",
3
+ "version": "0.1.0",
4
+ "description": "Fourier series of closed curves: spectra, partial sums, epicycle chains, and a small client for the fourier.babb.dev API.",
5
+ "license": "MIT",
6
+ "author": "Mike Babb",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/mkbabb/fourier-analysis.git",
10
+ "directory": "packages/fourier"
11
+ },
12
+ "homepage": "https://fourier.babb.dev",
13
+ "type": "module",
14
+ "sideEffects": false,
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/index.d.ts",
18
+ "import": "./dist/index.js"
19
+ },
20
+ "./client": {
21
+ "types": "./dist/client.d.ts",
22
+ "import": "./dist/client.js"
23
+ }
24
+ },
25
+ "files": [
26
+ "dist"
27
+ ],
28
+ "scripts": {
29
+ "build": "tsc -p tsconfig.build.json",
30
+ "build:watch": "tsc -p tsconfig.build.json --watch",
31
+ "typecheck": "tsc -p tsconfig.json",
32
+ "test": "vitest run --maxWorkers=2",
33
+ "prepublishOnly": "npm run build",
34
+ "test:live": "vitest run --config vitest.live.config.ts --maxWorkers=1"
35
+ },
36
+ "devDependencies": {
37
+ "@types/node": "25.9.3",
38
+ "typescript": "6.0.3",
39
+ "vitest": "5.0.1"
40
+ }
41
+ }