@mkbabb/fourier 0.0.0-stage → 0.2.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Michael Babb
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
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,39 @@
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
+ /** How `chainAt` orders the chain's vectors, and where it writes. */
22
+ export interface ChainOptions {
23
+ /**
24
+ * `"amplitude"` (the default): the largest first, as the Python
25
+ * `EpicycleChain` orders them. `"frequency"`: the stored order 0, +1, −1,
26
+ * +2, −2, ..., which never changes while the coefficients move, so a curve
27
+ * morphing between two shapes never reorders its circles.
28
+ */
29
+ order?: "amplitude" | "frequency";
30
+ /** Written into when given (length at least `2 · (terms + 1)`); no allocation. */
31
+ out?: Float64Array;
32
+ }
33
+ /**
34
+ * The chain's cumulative positions at θ = `t`: `[0, 0, x1, y1, ...]`, the
35
+ * origin and then the tip of each of the first `terms` vectors (Python's
36
+ * `positions_at` in the default order). The last pair is `evaluateAt(s, t,
37
+ * terms)` in that order.
38
+ */
39
+ export declare function chainAt(s: Spectrum, t: number, terms?: number, opts?: ChainOptions): Float64Array;
@@ -0,0 +1,113 @@
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 { frequencyAt, slotOf, 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
+ // Read in place: a frame's partial sum walks every term, and `coef` returns a new pair for each.
28
+ for (let k = -top; k <= top; k++) {
29
+ const w = weight(k, level);
30
+ if (!w)
31
+ continue;
32
+ const j = 2 * slotOf(k);
33
+ if (j + 1 >= s.c.length)
34
+ continue;
35
+ const i = (k + m) % m;
36
+ re[i] = re[i] + w * s.c[j];
37
+ im[i] = im[i] + w * s.c[j + 1];
38
+ }
39
+ ifft(re, im);
40
+ for (let j = 0; j < m; j++) {
41
+ out[2 * j] = re[j];
42
+ out[2 * j + 1] = im[j];
43
+ }
44
+ return out;
45
+ }
46
+ /** Each spectrum's pair slots in descending amplitude, computed once per array. */
47
+ const ORDER = new WeakMap();
48
+ function amplitudeOrder(s) {
49
+ let order = ORDER.get(s.c);
50
+ if (!order) {
51
+ const pairs = s.c.length >> 1;
52
+ const amp = new Float64Array(pairs);
53
+ for (let j = 0; j < pairs; j++)
54
+ amp[j] = Math.hypot(s.c[2 * j], s.c[2 * j + 1]);
55
+ // A stable sort over the frequency order: the Python chain's order exactly.
56
+ order = Uint32Array.from(Array.from({ length: pairs }, (_, j) => j).sort((a, b) => amp[b] - amp[a]));
57
+ ORDER.set(s.c, order);
58
+ }
59
+ return order;
60
+ }
61
+ /**
62
+ * The curve at θ = `t`, summing the chain's first `terms` vectors (the
63
+ * largest, as the Python `EpicycleChain` orders them); all of them by default.
64
+ */
65
+ export function evaluateAt(s, t, terms) {
66
+ const order = amplitudeOrder(s);
67
+ const n = Math.min(terms ?? order.length, order.length);
68
+ let x = 0;
69
+ let y = 0;
70
+ for (let i = 0; i < n; i++) {
71
+ const j = order[i];
72
+ const a = 2 * Math.PI * frequencyAt(j) * t;
73
+ const ca = Math.cos(a);
74
+ const sa = Math.sin(a);
75
+ const re = s.c[2 * j];
76
+ const im = s.c[2 * j + 1];
77
+ x += re * ca - im * sa;
78
+ y += re * sa + im * ca;
79
+ }
80
+ return [x, y];
81
+ }
82
+ /**
83
+ * The chain's cumulative positions at θ = `t`: `[0, 0, x1, y1, ...]`, the
84
+ * origin and then the tip of each of the first `terms` vectors (Python's
85
+ * `positions_at` in the default order). The last pair is `evaluateAt(s, t,
86
+ * terms)` in that order.
87
+ */
88
+ export function chainAt(s, t, terms, opts = {}) {
89
+ const frequency = opts.order === "frequency";
90
+ const order = frequency ? null : amplitudeOrder(s);
91
+ const pairs = s.c.length >> 1;
92
+ const n = Math.min(terms ?? pairs, pairs);
93
+ const out = opts.out ?? new Float64Array(2 * (n + 1));
94
+ if (out.length < 2 * (n + 1))
95
+ throw new RangeError(`chainAt: out holds ${out.length >> 1} points, not ${n + 1}`);
96
+ out[0] = 0;
97
+ out[1] = 0;
98
+ let x = 0;
99
+ let y = 0;
100
+ for (let i = 0; i < n; i++) {
101
+ const j = order ? order[i] : i;
102
+ const a = 2 * Math.PI * frequencyAt(j) * t;
103
+ const ca = Math.cos(a);
104
+ const sa = Math.sin(a);
105
+ const re = s.c[2 * j];
106
+ const im = s.c[2 * j + 1];
107
+ x += re * ca - im * sa;
108
+ y += re * sa + im * ca;
109
+ out[2 * i + 2] = x;
110
+ out[2 * i + 3] = y;
111
+ }
112
+ return out;
113
+ }
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,11 @@
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 { ChainOptions, Scratch } from "./evaluate.js";
7
+ export { alignStart, circleBetween, morphSpectra } from "./morph.js";
8
+ export { lensBlend, nearestParam } from "./lens.js";
9
+ export { svgPathOf, tracePath } from "./render.js";
10
+ export { frameLoop } from "./loop.js";
11
+ export type { FrameLoop } from "./loop.js";
package/dist/index.js ADDED
@@ -0,0 +1,8 @@
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 { alignStart, circleBetween, morphSpectra } from "./morph.js";
6
+ export { lensBlend, nearestParam } from "./lens.js";
7
+ export { svgPathOf, tracePath } from "./render.js";
8
+ 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,62 @@
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
+ // A tick may start the loop again (a new shape dealt mid-frame), which has
22
+ // already asked for the next frame: one callback per frame, never two chains.
23
+ if (runnable() && !raf)
24
+ raf = requestAnimationFrame(frame);
25
+ };
26
+ const sync = () => {
27
+ if (runnable()) {
28
+ if (!raf)
29
+ raf = requestAnimationFrame(frame);
30
+ }
31
+ else {
32
+ if (raf)
33
+ cancelAnimationFrame(raf);
34
+ raf = 0;
35
+ last = -1;
36
+ }
37
+ };
38
+ const io = typeof IntersectionObserver === "undefined"
39
+ ? null
40
+ : new IntersectionObserver((entries) => {
41
+ onScreen = entries[entries.length - 1].isIntersecting;
42
+ sync();
43
+ });
44
+ io?.observe(el);
45
+ document.addEventListener("visibilitychange", sync);
46
+ return {
47
+ start() {
48
+ wanted = true;
49
+ sync();
50
+ },
51
+ stop() {
52
+ wanted = false;
53
+ sync();
54
+ },
55
+ dispose() {
56
+ wanted = false;
57
+ sync();
58
+ io?.disconnect();
59
+ document.removeEventListener("visibilitychange", sync);
60
+ },
61
+ };
62
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * One curve becoming another, in the coefficients themselves. Two spectra over
3
+ * the same band morph circle by circle (each grows or shrinks, each arm turns
4
+ * the short way); `alignStart` first lines the new curve's start up with the
5
+ * old one's, so nothing spins on the way; `circleBetween` is the one circle a
6
+ * morph can pass through, the size of both shapes, so the way from a rose to a
7
+ * Lissajous figure is never a dot or a tangle.
8
+ */
9
+ import { type Spectrum } from "./spectrum.js";
10
+ /**
11
+ * `b` with its parameter shifted so it starts where `a` does: the shift τ
12
+ * (a turn in `steps` parts, then refined) that best matches the two curves'
13
+ * first `terms` harmonics, applied as c_k · e^{2πikτ}. The curve is the same;
14
+ * only where θ = 0 falls on it moves.
15
+ */
16
+ export declare function alignStart(a: Spectrum, b: Spectrum, terms?: number, steps?: number): Spectrum;
17
+ /**
18
+ * The spectrum `s` of the way from `a` (s = 0) to `b` (s = 1), polar per
19
+ * coefficient: each |c_k| moves linearly and each arm turns the short way
20
+ * round (an arm that is not there takes the other's angle). The band is the
21
+ * wider of the two; written into `out` when given (no allocation).
22
+ */
23
+ export declare function morphSpectra(a: Spectrum, b: Spectrum, s: number, out?: Float64Array): Spectrum;
24
+ /**
25
+ * The one circle between `a` and `b`: the pair k = +1 alone, its radius
26
+ * `scale` times the mean of the two curves' sizes over their first `terms`
27
+ * harmonics, its arm at `a`'s first harmonic (or `b`'s, when `a` has next to
28
+ * none there), its centre midway between theirs. The band is the wider one.
29
+ */
30
+ export declare function circleBetween(a: Spectrum, b: Spectrum, terms?: number, scale?: number): Spectrum;
package/dist/morph.js ADDED
@@ -0,0 +1,132 @@
1
+ /**
2
+ * One curve becoming another, in the coefficients themselves. Two spectra over
3
+ * the same band morph circle by circle (each grows or shrinks, each arm turns
4
+ * the short way); `alignStart` first lines the new curve's start up with the
5
+ * old one's, so nothing spins on the way; `circleBetween` is the one circle a
6
+ * morph can pass through, the size of both shapes, so the way from a rose to a
7
+ * Lissajous figure is never a dot or a tangle.
8
+ */
9
+ import { slotOf, topOf } from "./spectrum.js";
10
+ const TAU = 2 * Math.PI;
11
+ /** |c_k|² summed over 1 ≤ |k| ≤ `top`, square-rooted: the curve's size about its centre. */
12
+ function sizeOf(s, top) {
13
+ const last = Math.min(top, topOf(s));
14
+ let e = 0;
15
+ for (let k = 1; k <= last; k++) {
16
+ for (const i of [slotOf(k), slotOf(-k)])
17
+ e += s.c[2 * i] ** 2 + s.c[2 * i + 1] ** 2;
18
+ }
19
+ return Math.sqrt(e);
20
+ }
21
+ /**
22
+ * `b` with its parameter shifted so it starts where `a` does: the shift τ
23
+ * (a turn in `steps` parts, then refined) that best matches the two curves'
24
+ * first `terms` harmonics, applied as c_k · e^{2πikτ}. The curve is the same;
25
+ * only where θ = 0 falls on it moves.
26
+ */
27
+ export function alignStart(a, b, terms = 24, steps = 720) {
28
+ const top = Math.min(terms, topOf(a), topOf(b));
29
+ // Re Σ a_k · conj(b_k e^{2πikτ}): the match at a shift τ.
30
+ const match = (tau) => {
31
+ let v = 0;
32
+ for (let k = -top; k <= top; k++) {
33
+ if (!k)
34
+ continue;
35
+ const i = slotOf(k);
36
+ const ang = TAU * k * tau;
37
+ const ca = Math.cos(ang);
38
+ const sa = Math.sin(ang);
39
+ const br = b.c[2 * i] * ca - b.c[2 * i + 1] * sa;
40
+ const bi = b.c[2 * i] * sa + b.c[2 * i + 1] * ca;
41
+ v += a.c[2 * i] * br + a.c[2 * i + 1] * bi;
42
+ }
43
+ return v;
44
+ };
45
+ let best = 0;
46
+ let bestV = -Infinity;
47
+ for (let j = 0; j < steps; j++) {
48
+ const v = match(j / steps);
49
+ if (v > bestV) {
50
+ bestV = v;
51
+ best = j / steps;
52
+ }
53
+ }
54
+ // A golden-section refinement inside the winning step.
55
+ let lo = best - 1 / steps;
56
+ let hi = best + 1 / steps;
57
+ const g = (Math.sqrt(5) - 1) / 2;
58
+ for (let it = 0; it < 24; it++) {
59
+ const m1 = hi - g * (hi - lo);
60
+ const m2 = lo + g * (hi - lo);
61
+ if (match(m1) >= match(m2))
62
+ hi = m2;
63
+ else
64
+ lo = m1;
65
+ }
66
+ const tau = (lo + hi) / 2;
67
+ const c = new Float64Array(b.c.length);
68
+ for (let j = 0; 2 * j + 1 < c.length; j++) {
69
+ const k = j === 0 ? 0 : j % 2 ? (j + 1) / 2 : -j / 2;
70
+ const ang = TAU * k * tau;
71
+ const ca = Math.cos(ang);
72
+ const sa = Math.sin(ang);
73
+ c[2 * j] = b.c[2 * j] * ca - b.c[2 * j + 1] * sa;
74
+ c[2 * j + 1] = b.c[2 * j] * sa + b.c[2 * j + 1] * ca;
75
+ }
76
+ return { c };
77
+ }
78
+ /**
79
+ * The spectrum `s` of the way from `a` (s = 0) to `b` (s = 1), polar per
80
+ * coefficient: each |c_k| moves linearly and each arm turns the short way
81
+ * round (an arm that is not there takes the other's angle). The band is the
82
+ * wider of the two; written into `out` when given (no allocation).
83
+ */
84
+ export function morphSpectra(a, b, s, out) {
85
+ const len = Math.max(a.c.length, b.c.length);
86
+ const c = out ?? new Float64Array(len);
87
+ if (c.length !== len)
88
+ throw new RangeError(`morphSpectra: out has ${c.length} values, the band needs ${len}`);
89
+ for (let i = 0; 2 * i + 1 < len; i++) {
90
+ const ar = 2 * i + 1 < a.c.length ? a.c[2 * i] : 0;
91
+ const ai = 2 * i + 1 < a.c.length ? a.c[2 * i + 1] : 0;
92
+ const br = 2 * i + 1 < b.c.length ? b.c[2 * i] : 0;
93
+ const bi = 2 * i + 1 < b.c.length ? b.c[2 * i + 1] : 0;
94
+ const ra = Math.hypot(ar, ai);
95
+ const rb = Math.hypot(br, bi);
96
+ let fa = Math.atan2(ai, ar);
97
+ let fb = Math.atan2(bi, br);
98
+ if (ra < 1e-12)
99
+ fa = fb;
100
+ if (rb < 1e-12)
101
+ fb = fa;
102
+ let df = fb - fa;
103
+ df -= TAU * Math.round(df / TAU);
104
+ const r = ra + (rb - ra) * s;
105
+ const f = fa + df * s;
106
+ c[2 * i] = r * Math.cos(f);
107
+ c[2 * i + 1] = r * Math.sin(f);
108
+ }
109
+ return { c };
110
+ }
111
+ /**
112
+ * The one circle between `a` and `b`: the pair k = +1 alone, its radius
113
+ * `scale` times the mean of the two curves' sizes over their first `terms`
114
+ * harmonics, its arm at `a`'s first harmonic (or `b`'s, when `a` has next to
115
+ * none there), its centre midway between theirs. The band is the wider one.
116
+ */
117
+ export function circleBetween(a, b, terms = 24, scale = 0.92) {
118
+ const len = Math.max(a.c.length, b.c.length);
119
+ const r = (scale * (sizeOf(a, terms) + sizeOf(b, terms))) / 2;
120
+ const first = (s) => (s.c.length > 3 ? [s.c[2], s.c[3]] : [0, 0]);
121
+ const [a1r, a1i] = first(a);
122
+ const [b1r, b1i] = first(b);
123
+ const phase = Math.hypot(a1r, a1i) > 0.05 * r ? Math.atan2(a1i, a1r) : Math.hypot(b1r, b1i) > 0.05 * r ? Math.atan2(b1i, b1r) : 0;
124
+ const c = new Float64Array(len);
125
+ c[0] = (a.c[0] + b.c[0]) / 2;
126
+ c[1] = (a.c[1] + b.c[1]) / 2;
127
+ if (len > 3) {
128
+ c[2] = r * Math.cos(phase);
129
+ c[3] = r * Math.sin(phase);
130
+ }
131
+ return { c };
132
+ }
@@ -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.2.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
+ }