Repository navigation
Expand file tree
/
Copy pathconformalSource.js
More file actions
394 lines (341 loc) · 12.8 KB
/
Copy pathconformalSource.js
File metadata and controls
394 lines (341 loc) · 12.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
import { niceStep } from './grid.js';
import { MAX_LINES, SAMPLES } from './gl/conformalGridPass.js';
const PROBE_RINGS = 48;
const PROBE_ANGLES = 48;
const PROBE_MIN_RADIUS = 1e-4;
const PROBE_MAX_RADIUS = 1e4;
const REFINE_STEPS = 24;
const REFINE_GROWTH = 1.6;
const NEWTON_HIT_THRESHOLD = 24;
const NEWTON_SEEDS = 6;
const NEWTON_GRID = 20;
const VIEW_MARGIN = 0.35;
const TARGET_PX_SPACING = 110;
const REGION_PAD = 0.15;
const MAX_CLUSTERS = 4;
const VIEW_CELLS_X = 32;
const VIEW_CELLS_Y = 20;
const MIN_CLUSTER_COVERAGE = 0.02;
const MIN_CLUSTER_NOVELTY = 0.25;
const TARGET_SEGMENT_PX = 6;
const REGION_TRIM = 0.03;
const STEP_HYSTERESIS = 1.7;
const VIEW_EPSILON = 0.02;
function medianOf(values) {
if (values.length === 0) return 0;
const sorted = Float64Array.from(values).sort();
return sorted[sorted.length >> 1];
}
function quantile(values, q) {
const sorted = Float64Array.from(values).sort();
const idx = Math.min(sorted.length - 1, Math.max(0, Math.round(q * (sorted.length - 1))));
return sorted[idx];
}
function derivativeMagnitude(complexFn, re, im) {
const h = Math.max(1e-7, Math.hypot(re, im) * 1e-5);
const a = complexFn.evaluate(re, im);
const b = complexFn.evaluate(re + h, im);
if (!a || !b) return null;
const d = Math.hypot(b.re - a.re, b.im - a.im) / h;
return Number.isFinite(d) && d > 0 ? d : null;
}
function newtonStep(complexFn, re, im, target) {
const a = complexFn.evaluate(re, im);
if (!a) return null;
const h = Math.max(1e-9, Math.hypot(re, im) * 1e-6);
const b = complexFn.evaluate(re + h, im);
if (!b) return null;
const dRe = (b.re - a.re) / h;
const dIm = (b.im - a.im) / h;
const den = dRe * dRe + dIm * dIm;
if (!(den > 0) || !Number.isFinite(den)) return null;
const nRe = a.re - target.re;
const nIm = a.im - target.im;
const stepRe = (nRe * dRe + nIm * dIm) / den;
const stepIm = (nIm * dRe - nRe * dIm) / den;
const outRe = re - stepRe;
const outIm = im - stepIm;
if (!Number.isFinite(outRe) || !Number.isFinite(outIm)) return null;
return { re: outRe, im: outIm };
}
function solveToward(complexFn, seed, target, iterations = 12) {
let cur = seed;
for (let i = 0; i < iterations; i++) {
const next = newtonStep(complexFn, cur.re, cur.im, target);
if (!next) return cur;
const moved = Math.hypot(next.re - cur.re, next.im - cur.im);
cur = next;
if (moved <= Math.max(1e-12, Math.hypot(cur.re, cur.im) * 1e-12)) break;
}
return cur;
}
function clusterHits(hits, gridR, gridA) {
const occupied = new Int32Array(gridR * gridA).fill(-1);
const buckets = new Map();
for (let i = 0; i < hits.length; i++) {
const c = hits[i].ring * gridA + hits[i].angle;
occupied[c] = 0;
let list = buckets.get(c);
if (!list) buckets.set(c, (list = []));
list.push(i);
}
const label = new Int32Array(gridR * gridA).fill(-1);
let labels = 0;
const stack = [];
for (let c = 0; c < gridR * gridA; c++) {
if (occupied[c] !== 0 || label[c] !== -1) continue;
const id = labels++;
label[c] = id;
stack.push(c);
while (stack.length) {
const cur = stack.pop();
const ring = Math.floor(cur / gridA);
const angle = cur - ring * gridA;
for (let dr = -1; dr <= 1; dr++) {
for (let da = -1; da <= 1; da++) {
const nr = ring + dr;
if (nr < 0 || nr >= gridR) continue;
const na = (angle + da + gridA) % gridA;
const next = nr * gridA + na;
if (occupied[next] === 0 && label[next] === -1) {
label[next] = id;
stack.push(next);
}
}
}
}
}
if (labels === 0) return [];
const clusters = Array.from({ length: labels }, () => []);
for (const [cell, list] of buckets) {
const id = label[cell];
for (const i of list) clusters[id].push(hits[i]);
}
return clusters;
}
function clusterRegion(allMembers) {
const first = new Map();
const last = new Map();
for (const m of allMembers) {
if (!first.has(m.cell)) first.set(m.cell, m);
last.set(m.cell, m);
}
const members = [...first.values(), ...last.values()];
const res = members.map((m) => m.re);
const ims = members.map((m) => m.im);
if (members.length < 24) {
return {
minRe: Math.min(...res), maxRe: Math.max(...res),
minIm: Math.min(...ims), maxIm: Math.max(...ims),
midRe: medianOf(res), midIm: medianOf(ims),
};
}
return {
minRe: quantile(res, REGION_TRIM),
maxRe: quantile(res, 1 - REGION_TRIM),
minIm: quantile(ims, REGION_TRIM),
maxIm: quantile(ims, 1 - REGION_TRIM),
midRe: medianOf(res),
midIm: medianOf(ims),
};
}
function clipRegion(box, step, maxLines) {
const maxSpan = maxLines * step;
const out = { ...box };
if (box.maxRe - box.minRe > maxSpan) {
const c = Number.isFinite(box.midRe) ? box.midRe : (box.minRe + box.maxRe) / 2;
out.minRe = c - maxSpan / 2;
out.maxRe = c + maxSpan / 2;
}
if (box.maxIm - box.minIm > maxSpan) {
const c = Number.isFinite(box.midIm) ? box.midIm : (box.minIm + box.maxIm) / 2;
out.minIm = c - maxSpan / 2;
out.maxIm = c + maxSpan / 2;
}
return out;
}
function padRegion(box, step) {
const padRe = (box.maxRe - box.minRe) * REGION_PAD + step * 0.5;
const padIm = (box.maxIm - box.minIm) * REGION_PAD + step * 0.5;
return {
minRe: box.minRe - padRe,
maxRe: box.maxRe + padRe,
minIm: box.minIm - padIm,
maxIm: box.maxIm + padIm,
};
}
const LOG_MIN_RADIUS = Math.log(PROBE_MIN_RADIUS);
const LOG_RADIUS_SPAN = Math.log(PROBE_MAX_RADIUS) - LOG_MIN_RADIUS;
function latticeOf(re, im) {
const r = Math.max(Math.hypot(re, im), PROBE_MIN_RADIUS);
const ring = Math.min(PROBE_RINGS - 1, Math.max(0, Math.round(
((Math.log(r) - LOG_MIN_RADIUS) / LOG_RADIUS_SPAN) * (PROBE_RINGS - 1))));
let theta = Math.atan2(im, re);
if (theta < 0) theta += 2 * Math.PI;
const angle = Math.min(PROBE_ANGLES - 1, Math.floor((theta / (2 * Math.PI)) * PROBE_ANGLES));
return { ring, angle };
}
export class ConformalSourcePlanner {
constructor() {
this.plan = null;
this._expr = null;
this._scale = 0;
this._centerRe = 0;
this._centerIm = 0;
}
_stale(viewport, expr) {
if (!this.plan || expr !== this._expr) return true;
if (Math.abs(Math.log(viewport.scale / this._scale)) > VIEW_EPSILON) return true;
const spanRe = viewport.width / viewport.scale;
const spanIm = viewport.height / viewport.scale;
if (Math.abs(viewport.centerRe - this._centerRe) > spanRe * VIEW_EPSILON) return true;
if (Math.abs(viewport.centerIm - this._centerIm) > spanIm * VIEW_EPSILON) return true;
return false;
}
update(viewport, complexFn) {
if (!complexFn.compiled) return null;
if (!this._stale(viewport, complexFn.expr)) return this.plan;
const next = this._build(viewport, complexFn);
this._expr = complexFn.expr;
this._scale = viewport.scale;
this._centerRe = viewport.centerRe;
this._centerIm = viewport.centerIm;
this.plan = next;
return next;
}
_build(viewport, complexFn) {
const halfRe = viewport.width / viewport.scale / 2;
const halfIm = viewport.height / viewport.scale / 2;
const loRe = viewport.centerRe - halfRe * (1 + VIEW_MARGIN);
const hiRe = viewport.centerRe + halfRe * (1 + VIEW_MARGIN);
const loIm = viewport.centerIm - halfIm * (1 + VIEW_MARGIN);
const hiIm = viewport.centerIm + halfIm * (1 + VIEW_MARGIN);
const hits = [];
const cellRep = new Map();
const target = { re: viewport.centerRe, im: viewport.centerIm };
const nearMisses = [];
const probe = (re, im, ring, angle) => {
const w = complexFn.evaluate(re, im);
if (!w) return;
if (w.re < loRe || w.re > hiRe || w.im < loIm || w.im > hiIm) {
if (ring >= 0) {
const d = Math.hypot(w.re - target.re, w.im - target.im);
if (Number.isFinite(d)) nearMisses.push({ re, im, d });
}
return;
}
const cx = Math.min(VIEW_CELLS_X - 1, Math.max(0,
Math.floor(((w.re - loRe) / (hiRe - loRe)) * VIEW_CELLS_X)));
const cy = Math.min(VIEW_CELLS_Y - 1, Math.max(0,
Math.floor(((w.im - loIm) / (hiIm - loIm)) * VIEW_CELLS_Y)));
const cell = cy * VIEW_CELLS_X + cx;
let r = ring;
let a = angle;
if (r < 0) ({ ring: r, angle: a } = latticeOf(re, im));
const index = hits.length;
hits.push({ re, im, ring: r, angle: a, cell });
if (!cellRep.has(cell)) cellRep.set(cell, index);
};
const ratio = Math.pow(PROBE_MAX_RADIUS / PROBE_MIN_RADIUS, 1 / (PROBE_RINGS - 1));
let radius = PROBE_MIN_RADIUS;
for (let ring = 0; ring < PROBE_RINGS; ring++, radius *= ratio) {
for (let a = 0; a < PROBE_ANGLES; a++) {
const theta = (2 * Math.PI * a) / PROBE_ANGLES;
probe(radius * Math.cos(theta), radius * Math.sin(theta), ring, a);
}
}
if (cellRep.size < NEWTON_HIT_THRESHOLD && nearMisses.length > 0) {
nearMisses.sort((a, b) => a.d - b.d);
const seeds = [];
for (const candidate of nearMisses) {
if (seeds.length >= NEWTON_SEEDS) break;
const apart = seeds.every(
(sd) => Math.hypot(sd.re - candidate.re, sd.im - candidate.im) >
Math.hypot(candidate.re, candidate.im) * 0.25
);
if (apart) seeds.push(candidate);
}
for (const seed of seeds) {
const root = solveToward(complexFn, seed, target);
const d = derivativeMagnitude(complexFn, root.re, root.im);
if (!d) continue;
const spanRe = (halfRe * (1 + VIEW_MARGIN)) / d;
const spanIm = (halfIm * (1 + VIEW_MARGIN)) / d;
if (!Number.isFinite(spanRe) || !Number.isFinite(spanIm)) continue;
for (let j = 0; j < NEWTON_GRID; j++) {
const im = root.im - spanIm + (2 * spanIm * j) / (NEWTON_GRID - 1);
for (let i = 0; i < NEWTON_GRID; i++) {
const re = root.re - spanRe + (2 * spanRe * i) / (NEWTON_GRID - 1);
probe(re, im, -1, 0);
}
}
}
}
const prior = this.plan && this.plan.bounds;
if (prior) {
const cRe = (prior.minRe + prior.maxRe) / 2;
const cIm = (prior.minIm + prior.maxIm) / 2;
const hRe = ((prior.maxRe - prior.minRe) / 2) * REFINE_GROWTH || 1;
const hIm = ((prior.maxIm - prior.minIm) / 2) * REFINE_GROWTH || 1;
for (let j = 0; j < REFINE_STEPS; j++) {
const im = cIm - hIm + (2 * hIm * j) / (REFINE_STEPS - 1);
for (let i = 0; i < REFINE_STEPS; i++) {
probe(cRe - hRe + (2 * hRe * i) / (REFINE_STEPS - 1), im, -1, 0);
}
}
}
if (cellRep.size === 0) return null;
const derivatives = [];
const reps = [...cellRep.values()];
const stride = Math.max(1, Math.floor(reps.length / 96));
for (let i = 0; i < reps.length; i += stride) {
const h = hits[reps[i]];
const d = derivativeMagnitude(complexFn, h.re, h.im);
if (d !== null) derivatives.push(d);
}
const scaleFactor = medianOf(derivatives) || 1;
let step = niceStep(TARGET_PX_SPACING / (viewport.scale * scaleFactor));
if (!Number.isFinite(step) || step <= 0) return null;
if (this.plan && this.plan.majorStep && this._expr === complexFn.expr) {
const drift = step / this.plan.majorStep;
if (drift < STEP_HYSTERESIS && drift > 1 / STEP_HYSTERESIS) {
step = this.plan.majorStep;
}
}
const ranked = clusterHits(hits, PROBE_RINGS, PROBE_ANGLES)
.map((members) => {
const cells = new Set();
for (const m of members) cells.add(m.cell);
return { members, coverage: cells.size };
})
.filter((c) => c.coverage >= Math.max(2, cellRep.size * MIN_CLUSTER_COVERAGE))
.sort((a, b) => b.coverage - a.coverage);
const claimed = new Set();
const clusters = [];
for (const c of ranked) {
if (clusters.length >= MAX_CLUSTERS) break;
const cells = new Set();
for (const m of c.members) cells.add(m.cell);
let fresh = 0;
for (const cell of cells) if (!claimed.has(cell)) fresh++;
if (clusters.length > 0 && fresh / cells.size < MIN_CLUSTER_NOVELTY) continue;
for (const cell of cells) claimed.add(cell);
clusters.push(c);
}
if (clusters.length === 0) return null;
const boxes = clusters.map((c) => clusterRegion(c.members));
const sampleLimitedSpan = (SAMPLES * TARGET_SEGMENT_PX) / (viewport.scale * scaleFactor);
const spanLimit = Math.min(MAX_LINES - 4, Math.max(4, sampleLimitedSpan / step));
const regions = boxes.map((b) => padRegion(clipRegion(b, step, spanLimit), step));
const bounds = regions.reduce(
(acc, r) => ({
minRe: Math.min(acc.minRe, r.minRe),
maxRe: Math.max(acc.maxRe, r.maxRe),
minIm: Math.min(acc.minIm, r.minIm),
maxIm: Math.max(acc.maxIm, r.maxIm),
}),
{ minRe: Infinity, maxRe: -Infinity, minIm: Infinity, maxIm: -Infinity }
);
return { majorStep: step, regions, bounds };
}
}