agglomerative-clustering 3.7.2 → 4.0.0-beta.1
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 +9 -8
- package/dist/choose.cjs +166 -0
- package/dist/choose.mjs +160 -0
- package/dist/clustering.cjs +1 -1
- package/dist/clustering.js +1 -1
- package/dist/clustering.wasm +0 -0
- package/dist/index.cjs +103 -64
- package/dist/index.d.cts +80 -19
- package/dist/index.d.ts +80 -19
- package/dist/index.mjs +102 -63
- package/dist/shared.cjs +129 -5
- package/dist/shared.mjs +123 -3
- package/dist/worker-thread.mjs +13 -2
- package/dist/worker.cjs +183 -64
- package/dist/worker.d.cts +51 -8
- package/dist/worker.d.ts +51 -8
- package/dist/worker.mjs +184 -65
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -82,7 +82,7 @@ slider.oninput = async () => {
|
|
|
82
82
|
};
|
|
83
83
|
```
|
|
84
84
|
|
|
85
|
-
Input is decoded pixels: a bare `Uint8Array` of RGBA bytes, an `ImageData`, or `{ data, format: 'rgb' | 'rgba' | 'bgra' | 'rgbx' | 'bgrx', width?, height? }`: BGRA for Electron's `nativeImage` and Windows bitmaps, and the `x` formats for buffers whose fourth byte isn't alpha (GDI screenshots, WebCodecs `'BGRX'`, ffmpeg `bgr0`). Alpha is straight
|
|
85
|
+
Input is decoded pixels: a bare `Uint8Array` of RGBA bytes, an `ImageData`, or `{ data, format: 'rgb' | 'rgba' | 'bgra' | 'rgbx' | 'bgrx', width?, height? }`: BGRA for Electron's `nativeImage` and Windows bitmaps, and the `x` formats for buffers whose fourth byte isn't alpha (GDI screenshots, WebCodecs `'BGRX'`, ffmpeg `bgr0`). Alpha is straight, or premultiplied (canvas, Electron): pass `premultiplied: true` with `'rgba'` or `'bgra'`; [where pixels come from](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/api.md#input) lists common sources and what to pass for each. Mapped output of a premultiplied image comes back premultiplied (palettes and indices are straight), so for an `ImageData` or a PNG encoder use the [straight-output recipe](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/guides.md#straight-pixels-from-a-premultiplied-source). RGB bytes passed bare are read as RGBA; the library warns when it sees this (an error from 4.0), so pass them as `{ data, format: 'rgb' }`. To start from a PNG, JPEG, WebP or GIF file, decode it first: [Decoding image files](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/guides.md#decoding-image-files) has a recipe for Node, browsers and edge runtimes. For a page that stays responsive while it clusters, use `agglomerative-clustering/worker`: its functions are the same, and for a slider `createWorker().cluster(image)` keeps the image and its clustering in the worker, behind a handle whose `handle.getPalette(k)` and `handle.quantize(k)` re-cut and re-map without sending the pixels again (see [Workers](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/guides.md#workers)). The `clustering.…` methods above run on the calling thread, so they don't move work off it.
|
|
86
86
|
|
|
87
87
|
## How it works
|
|
88
88
|
|
|
@@ -96,19 +96,20 @@ The one-shot functions (`buildPalette`, `quantize`, …) do every step for you.
|
|
|
96
96
|
|
|
97
97
|
| You want | from the image | from a clustering you hold¹ | with a palette you supply |
|
|
98
98
|
|---|---|---|---|
|
|
99
|
-
| a palette (flat RGB) | `buildPalette` | `clustering.getPalette(k)`
|
|
100
|
-
| a palette with each colour's share | `buildSwatches` | `clustering.getSwatches(k)`
|
|
101
|
-
| the image reduced to those colours | `quantize` | `clustering.quantize(image, k)`
|
|
102
|
-
| palette indices (GIF, PNG-8) | `quantizeToIndices` | `clustering.quantizeToIndices(image, k)`
|
|
103
|
-
| its error curve, for choosing a palette size | | `clustering.getClusteringInfo()`
|
|
99
|
+
| a palette (flat RGB) | `buildPalette` | `clustering.getPalette(k)` | |
|
|
100
|
+
| a palette with each colour's share | `buildSwatches` | `clustering.getSwatches(k)` | |
|
|
101
|
+
| the image reduced to those colours | `quantize` | `clustering.quantize(image, k)` | `quantizeWithPalette` |
|
|
102
|
+
| palette indices (GIF, PNG-8) | `quantizeToIndices` | `clustering.quantizeToIndices(image, k)` | `quantizeToIndicesWithPalette` |
|
|
103
|
+
| its error curve, for choosing a palette size | | `clustering.getClusteringInfo()` | |
|
|
104
|
+
| the `k` entries of a fixed palette (threads, bricks) that best fit | | `clustering.chooseFrom(palette, k)` | |
|
|
104
105
|
|
|
105
106
|
A clustering you hold has **methods** that take the colours from it, and **`…WithPalette`** takes colours you supply; with neither, the image is clustered for you. `buildClustering` builds a clustering, and `init` loads the WebAssembly module (optional). Most code only needs the first column.
|
|
106
107
|
|
|
107
108
|
The verb says how much work a call does. `build…` clusters an image (tens of milliseconds for a photo). `get…` reads or cuts what a clustering or a worker handle already holds (well under a millisecond). `quantize…` maps pixels. So `buildPalette(image, k)` and `clustering.getPalette(k)` give the same kind of result from different starting points. The `build…` names arrived in 3.4.0; [Migrating](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/migrating.md) has the old ones.
|
|
108
109
|
|
|
109
|
-
**
|
|
110
|
+
**Where to call them.** On the main thread, or in a Node script, use the methods: they are the shortest way to cut one clustering many times. **Off the thread, use a handle**: `worker.cluster(image)` keeps an image and its clustering in the worker, and `worker.load(clustering)` keeps a stored clustering (`await using loaded = await worker.load(stored)`, then `loaded.getPalette(k)` and `loaded.quantize(image, k)`). The methods always run on the thread that calls them, with the main entry, and reject with `wasm-load-failed` where only the worker entry is imported.
|
|
110
111
|
|
|
111
|
-
¹
|
|
112
|
+
¹ The `…FromClustering` functions (`getPaletteFromClustering(clustering, k)`, `quantizeFromClustering(image, clustering, k)` and the rest) do the same as the methods. They are deprecated from 3.8 and removed in 4.0: see [Migrating](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/migrating.md#deprecated-in-38-removed-in-40) for the replacement of each, and [Clustering methods](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/api.md#clustering-methods).
|
|
112
113
|
|
|
113
114
|
Palettes come in **split order**: the palette for `k + 1` is the one for `k` with one colour split in two, so entries keep their place as `k` grows (they are not sorted by share). The options are `precision` (6 is about 3× faster at practically the same quality), `colorSpace` (`'rgb'` or `'oklab'`), `alpha`, `transparent`, `dither` (Floyd–Steinberg, Atkinson, or ordered for animation, which keeps still areas still), `width`, `signal` and `onProgress`: see the [API reference](https://github.com/RohanFredriksson/agglomerative-clustering/blob/master/docs/api.md).
|
|
114
115
|
|
package/dist/choose.cjs
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
exports.choose = choose;
|
|
7
|
+
// The search behind clustering.chooseFrom: k entries of a fixed palette that represent a clustered image well. It is the
|
|
8
|
+
// guides' chooseThreads + improveThreads (docs/guides.md), plus a fill step so the result always has k entries. It runs
|
|
9
|
+
// on whatever thread calls it and reaches the WebAssembly only through the functions it is given.
|
|
10
|
+
|
|
11
|
+
// Colours (3 bytes each) as coordinates to measure distance in: OKLab, or the sRGB values themselves.
|
|
12
|
+
function coordinates(rgb, space) {
|
|
13
|
+
if (space === 'rgb') {
|
|
14
|
+
return Float64Array.from(rgb);
|
|
15
|
+
}
|
|
16
|
+
const linear = v => (v /= 255) <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
|
|
17
|
+
const out = new Float64Array(rgb.length);
|
|
18
|
+
for (let i = 0; i < rgb.length; i += 3) {
|
|
19
|
+
const r = linear(rgb[i]),
|
|
20
|
+
g = linear(rgb[i + 1]),
|
|
21
|
+
b = linear(rgb[i + 2]);
|
|
22
|
+
const l = Math.cbrt(0.4122214708 * r + 0.5363329343 * g + 0.0514459929 * b);
|
|
23
|
+
const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
|
|
24
|
+
const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
|
|
25
|
+
out[i] = 0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s;
|
|
26
|
+
out[i + 1] = 1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s;
|
|
27
|
+
out[i + 2] = 0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s;
|
|
28
|
+
}
|
|
29
|
+
return out;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Positions in `entries`, in search order (unsorted), exactly k of them.
|
|
33
|
+
// cut(k) → the k-colour palette; swatches() → {palette, weights} of the 1024 cut; snap(colours) → the nearest entry of
|
|
34
|
+
// each colour (RGB); pause() → checks the signal, and yields when one was given.
|
|
35
|
+
async function choose({
|
|
36
|
+
cut,
|
|
37
|
+
swatches,
|
|
38
|
+
snap,
|
|
39
|
+
pause
|
|
40
|
+
}, entries, k, space) {
|
|
41
|
+
const t = entries.length / 3;
|
|
42
|
+
const {
|
|
43
|
+
palette: colors,
|
|
44
|
+
weights
|
|
45
|
+
} = await swatches();
|
|
46
|
+
const m = weights.length;
|
|
47
|
+
// Nothing to fit (an empty image): the first k entries, the only choice there is.
|
|
48
|
+
if (m === 0) {
|
|
49
|
+
return Array.from({
|
|
50
|
+
length: k
|
|
51
|
+
}, (_, j) => j);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Snap: the cuts from k up, each colour to its nearest entry; the first k distinct, in split order.
|
|
55
|
+
let chosen = [];
|
|
56
|
+
for (let c = k; c <= 4 * k && chosen.length < k; c++) {
|
|
57
|
+
await pause();
|
|
58
|
+
chosen = [...new Set(await snap(await cut(c)))].slice(0, k);
|
|
59
|
+
}
|
|
60
|
+
const a = coordinates(entries, space),
|
|
61
|
+
b = coordinates(colors, space);
|
|
62
|
+
const distance = new Float64Array(t * m); // distance[j * m + i]: squared, from entry j to swatch i
|
|
63
|
+
for (let j = 0; j < t; j++) {
|
|
64
|
+
for (let i = 0; i < m; i++) {
|
|
65
|
+
const dx = a[3 * j] - b[3 * i],
|
|
66
|
+
dy = a[3 * j + 1] - b[3 * i + 1],
|
|
67
|
+
dz = a[3 * j + 2] - b[3 * i + 2];
|
|
68
|
+
distance[j * m + i] = dx * dx + dy * dy + dz * dz;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Fill: with fewer than k distinct entries, add the entry that lowers the error most, one at a time (ties: lower j).
|
|
73
|
+
chosen = [...chosen];
|
|
74
|
+
if (chosen.length < k) {
|
|
75
|
+
const nearestDistance = new Float64Array(m).fill(Infinity);
|
|
76
|
+
for (const j of chosen) {
|
|
77
|
+
for (let i = 0; i < m; i++) {
|
|
78
|
+
nearestDistance[i] = Math.min(nearestDistance[i], distance[j * m + i]);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
while (chosen.length < k) {
|
|
82
|
+
await pause();
|
|
83
|
+
let best = -1,
|
|
84
|
+
lowest = Infinity;
|
|
85
|
+
for (let j = 0; j < t; j++) {
|
|
86
|
+
if (chosen.includes(j)) {
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
let sum = 0;
|
|
90
|
+
for (let i = 0; i < m; i++) {
|
|
91
|
+
sum += weights[i] * Math.min(nearestDistance[i], distance[j * m + i]);
|
|
92
|
+
}
|
|
93
|
+
if (best < 0 || sum < lowest) {
|
|
94
|
+
lowest = sum;
|
|
95
|
+
best = j;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
chosen.push(best);
|
|
99
|
+
for (let i = 0; i < m; i++) {
|
|
100
|
+
nearestDistance[i] = Math.min(nearestDistance[i], distance[best * m + i]);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Swap: entries in and out of `chosen` while that brings the image closer, measured on the swatches.
|
|
106
|
+
const n = chosen.length;
|
|
107
|
+
const nearest = new Int32Array(m),
|
|
108
|
+
first = new Float64Array(m),
|
|
109
|
+
second = new Float64Array(m),
|
|
110
|
+
change = new Float64Array(n);
|
|
111
|
+
for (;;) {
|
|
112
|
+
await pause();
|
|
113
|
+
// Each swatch's nearest chosen entry (its position in `chosen`) and the distances to the nearest two.
|
|
114
|
+
let current = 0;
|
|
115
|
+
for (let i = 0; i < m; i++) {
|
|
116
|
+
let f = Infinity,
|
|
117
|
+
g = Infinity,
|
|
118
|
+
near = 0;
|
|
119
|
+
for (let s = 0; s < n; s++) {
|
|
120
|
+
const d = distance[chosen[s] * m + i];
|
|
121
|
+
if (d < f) {
|
|
122
|
+
g = f;
|
|
123
|
+
f = d;
|
|
124
|
+
near = s;
|
|
125
|
+
} else if (d < g) {
|
|
126
|
+
g = d;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
nearest[i] = near;
|
|
130
|
+
first[i] = f;
|
|
131
|
+
second[i] = g;
|
|
132
|
+
current += weights[i] * f;
|
|
133
|
+
}
|
|
134
|
+
// For each unchosen entry j, one pass over the swatches gives the error after swapping j in at every position s:
|
|
135
|
+
// current + shared + change[s]. Keep the best swap, if any is better.
|
|
136
|
+
let best = null,
|
|
137
|
+
lowest = current * (1 - 1e-9);
|
|
138
|
+
for (let j = 0; j < t; j++) {
|
|
139
|
+
if (j % 64 === 63) {
|
|
140
|
+
await pause();
|
|
141
|
+
}
|
|
142
|
+
if (chosen.includes(j)) {
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
let shared = 0;
|
|
146
|
+
change.fill(0);
|
|
147
|
+
for (let i = 0; i < m; i++) {
|
|
148
|
+
const d = distance[j * m + i],
|
|
149
|
+
gain = d < first[i] ? weights[i] * (d - first[i]) : 0;
|
|
150
|
+
shared += gain;
|
|
151
|
+
change[nearest[i]] += weights[i] * (Math.min(d, second[i]) - first[i]) - gain;
|
|
152
|
+
}
|
|
153
|
+
for (let s = 0; s < n; s++) {
|
|
154
|
+
const error = current + shared + change[s];
|
|
155
|
+
if (error < lowest) {
|
|
156
|
+
lowest = error;
|
|
157
|
+
best = [s, j];
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
if (!best) {
|
|
162
|
+
return chosen;
|
|
163
|
+
}
|
|
164
|
+
chosen[best[0]] = best[1];
|
|
165
|
+
}
|
|
166
|
+
}
|
package/dist/choose.mjs
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
// The search behind clustering.chooseFrom: k entries of a fixed palette that represent a clustered image well. It is the
|
|
2
|
+
// guides' chooseThreads + improveThreads (docs/guides.md), plus a fill step so the result always has k entries. It runs
|
|
3
|
+
// on whatever thread calls it and reaches the WebAssembly only through the functions it is given.
|
|
4
|
+
|
|
5
|
+
// Colours (3 bytes each) as coordinates to measure distance in: OKLab, or the sRGB values themselves.
|
|
6
|
+
function coordinates(rgb, space) {
|
|
7
|
+
if (space === 'rgb') {
|
|
8
|
+
return Float64Array.from(rgb);
|
|
9
|
+
}
|
|
10
|
+
const linear = v => (v /= 255) <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
|
|
11
|
+
const out = new Float64Array(rgb.length);
|
|
12
|
+
for (let i = 0; i < rgb.length; i += 3) {
|
|
13
|
+
const r = linear(rgb[i]),
|
|
14
|
+
g = linear(rgb[i + 1]),
|
|
15
|
+
b = linear(rgb[i + 2]);
|
|
16
|
+
const l = Math.cbrt(0.4122214708 * r + 0.5363329343 * g + 0.0514459929 * b);
|
|
17
|
+
const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);
|
|
18
|
+
const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);
|
|
19
|
+
out[i] = 0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s;
|
|
20
|
+
out[i + 1] = 1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s;
|
|
21
|
+
out[i + 2] = 0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s;
|
|
22
|
+
}
|
|
23
|
+
return out;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Positions in `entries`, in search order (unsorted), exactly k of them.
|
|
27
|
+
// cut(k) → the k-colour palette; swatches() → {palette, weights} of the 1024 cut; snap(colours) → the nearest entry of
|
|
28
|
+
// each colour (RGB); pause() → checks the signal, and yields when one was given.
|
|
29
|
+
export async function choose({
|
|
30
|
+
cut,
|
|
31
|
+
swatches,
|
|
32
|
+
snap,
|
|
33
|
+
pause
|
|
34
|
+
}, entries, k, space) {
|
|
35
|
+
const t = entries.length / 3;
|
|
36
|
+
const {
|
|
37
|
+
palette: colors,
|
|
38
|
+
weights
|
|
39
|
+
} = await swatches();
|
|
40
|
+
const m = weights.length;
|
|
41
|
+
// Nothing to fit (an empty image): the first k entries, the only choice there is.
|
|
42
|
+
if (m === 0) {
|
|
43
|
+
return Array.from({
|
|
44
|
+
length: k
|
|
45
|
+
}, (_, j) => j);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Snap: the cuts from k up, each colour to its nearest entry; the first k distinct, in split order.
|
|
49
|
+
let chosen = [];
|
|
50
|
+
for (let c = k; c <= 4 * k && chosen.length < k; c++) {
|
|
51
|
+
await pause();
|
|
52
|
+
chosen = [...new Set(await snap(await cut(c)))].slice(0, k);
|
|
53
|
+
}
|
|
54
|
+
const a = coordinates(entries, space),
|
|
55
|
+
b = coordinates(colors, space);
|
|
56
|
+
const distance = new Float64Array(t * m); // distance[j * m + i]: squared, from entry j to swatch i
|
|
57
|
+
for (let j = 0; j < t; j++) {
|
|
58
|
+
for (let i = 0; i < m; i++) {
|
|
59
|
+
const dx = a[3 * j] - b[3 * i],
|
|
60
|
+
dy = a[3 * j + 1] - b[3 * i + 1],
|
|
61
|
+
dz = a[3 * j + 2] - b[3 * i + 2];
|
|
62
|
+
distance[j * m + i] = dx * dx + dy * dy + dz * dz;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Fill: with fewer than k distinct entries, add the entry that lowers the error most, one at a time (ties: lower j).
|
|
67
|
+
chosen = [...chosen];
|
|
68
|
+
if (chosen.length < k) {
|
|
69
|
+
const nearestDistance = new Float64Array(m).fill(Infinity);
|
|
70
|
+
for (const j of chosen) {
|
|
71
|
+
for (let i = 0; i < m; i++) {
|
|
72
|
+
nearestDistance[i] = Math.min(nearestDistance[i], distance[j * m + i]);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
while (chosen.length < k) {
|
|
76
|
+
await pause();
|
|
77
|
+
let best = -1,
|
|
78
|
+
lowest = Infinity;
|
|
79
|
+
for (let j = 0; j < t; j++) {
|
|
80
|
+
if (chosen.includes(j)) {
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
let sum = 0;
|
|
84
|
+
for (let i = 0; i < m; i++) {
|
|
85
|
+
sum += weights[i] * Math.min(nearestDistance[i], distance[j * m + i]);
|
|
86
|
+
}
|
|
87
|
+
if (best < 0 || sum < lowest) {
|
|
88
|
+
lowest = sum;
|
|
89
|
+
best = j;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
chosen.push(best);
|
|
93
|
+
for (let i = 0; i < m; i++) {
|
|
94
|
+
nearestDistance[i] = Math.min(nearestDistance[i], distance[best * m + i]);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Swap: entries in and out of `chosen` while that brings the image closer, measured on the swatches.
|
|
100
|
+
const n = chosen.length;
|
|
101
|
+
const nearest = new Int32Array(m),
|
|
102
|
+
first = new Float64Array(m),
|
|
103
|
+
second = new Float64Array(m),
|
|
104
|
+
change = new Float64Array(n);
|
|
105
|
+
for (;;) {
|
|
106
|
+
await pause();
|
|
107
|
+
// Each swatch's nearest chosen entry (its position in `chosen`) and the distances to the nearest two.
|
|
108
|
+
let current = 0;
|
|
109
|
+
for (let i = 0; i < m; i++) {
|
|
110
|
+
let f = Infinity,
|
|
111
|
+
g = Infinity,
|
|
112
|
+
near = 0;
|
|
113
|
+
for (let s = 0; s < n; s++) {
|
|
114
|
+
const d = distance[chosen[s] * m + i];
|
|
115
|
+
if (d < f) {
|
|
116
|
+
g = f;
|
|
117
|
+
f = d;
|
|
118
|
+
near = s;
|
|
119
|
+
} else if (d < g) {
|
|
120
|
+
g = d;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
nearest[i] = near;
|
|
124
|
+
first[i] = f;
|
|
125
|
+
second[i] = g;
|
|
126
|
+
current += weights[i] * f;
|
|
127
|
+
}
|
|
128
|
+
// For each unchosen entry j, one pass over the swatches gives the error after swapping j in at every position s:
|
|
129
|
+
// current + shared + change[s]. Keep the best swap, if any is better.
|
|
130
|
+
let best = null,
|
|
131
|
+
lowest = current * (1 - 1e-9);
|
|
132
|
+
for (let j = 0; j < t; j++) {
|
|
133
|
+
if (j % 64 === 63) {
|
|
134
|
+
await pause();
|
|
135
|
+
}
|
|
136
|
+
if (chosen.includes(j)) {
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
let shared = 0;
|
|
140
|
+
change.fill(0);
|
|
141
|
+
for (let i = 0; i < m; i++) {
|
|
142
|
+
const d = distance[j * m + i],
|
|
143
|
+
gain = d < first[i] ? weights[i] * (d - first[i]) : 0;
|
|
144
|
+
shared += gain;
|
|
145
|
+
change[nearest[i]] += weights[i] * (Math.min(d, second[i]) - first[i]) - gain;
|
|
146
|
+
}
|
|
147
|
+
for (let s = 0; s < n; s++) {
|
|
148
|
+
const error = current + shared + change[s];
|
|
149
|
+
if (error < lowest) {
|
|
150
|
+
lowest = error;
|
|
151
|
+
best = [s, j];
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
if (!best) {
|
|
156
|
+
return chosen;
|
|
157
|
+
}
|
|
158
|
+
chosen[best[0]] = best[1];
|
|
159
|
+
}
|
|
160
|
+
}
|
package/dist/clustering.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
"use strict";var __agglomerativeGlueUrl=typeof __filename=="string"&&typeof process!="undefined"&&typeof process.getBuiltinModule=="function"?process.getBuiltinModule("node:url").pathToFileURL(__filename).href:"";
|
|
2
|
-
async function createWasmModule(moduleArg={}){var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer"&&globalThis.process?.type!="worker"&&globalThis.process?.type!="service-worker"&&typeof __filename=="string"&&typeof process.getBuiltinModule=="function";if(ENVIRONMENT_IS_NODE){var require=(name)=>process.getBuiltinModule(name)}var programArgs=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=__agglomerativeGlueUrl;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");if(_scriptName.startsWith("file:")){scriptDirectory=require("node:path").dirname(require("node:url").fileURLToPath(_scriptName))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(globalThis.process.argv.length>1){thisProgram=globalThis.process.argv[1].replace(/\\/g,"/")}programArgs=globalThis.process.argv.slice(2);quit_=(status,toThrow)=>{globalThis.process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var isFileURI=filename=>filename.startsWith("file://");class EmscriptenEH{}class EmscriptenSjLj extends EmscriptenEH{}var runtimeInitialized=false;function getMemoryBuffer(){return wasmMemory.buffer}function updateMemoryViews(){if(HEAP8?.buffer?.resizable)return;var b=getMemoryBuffer();HEAP8=new Int8Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU32=new Uint32Array(b)}function preRun(){var preRun=Module["preRun"];if(preRun){if(typeof preRun=="function")preRun=[preRun];onPreRuns.push(...preRun)}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;wasmExports["f"]()}function postRun(){var postRun=Module["postRun"];if(postRun){if(typeof postRun=="function")postRun=[postRun];onPostRuns.push(...postRun)}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what=`Aborted(${what})`;err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("clustering.wasm")}return new URL("clustering.wasm",__agglomerativeGlueUrl).href}function getBinarySync(file){if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();var instantiateWasm=Module["instantiateWasm"];if(instantiateWasm){return new Promise(resolve=>{instantiateWasm(info,inst=>resolve(receiveInstance(inst)))})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var HEAP8;var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var onPreRuns=[];var noExitRuntime=true;var HEAPU32;class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var uncaughtExceptionCount=0;var __Unwind_RaiseException=ex=>{abort()};var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);uncaughtExceptionCount++;__Unwind_RaiseException(ptr)};var __abort_js=()=>abort("");var _emscripten_get_now=()=>performance.now();var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var HEAPU8;var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["arguments"])programArgs=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];var preInit=Module["preInit"];if(preInit){if(typeof preInit=="function")Module["preInit"]=preInit=[preInit];while(preInit.length>0){preInit.shift()()}}}var _malloc,_library_version,_clustering_job_start,_clustering_job_step,_clustering_job_result,_clustering_job_free,_mapping_job_start,_mapping_job_step,_mapping_job_result,_mapping_job_free,_free,_get_clustering,_get_palette,_get_palette_from_clustering,_get_palette_weights,_quantize,_quantize_with_clustering,_quantize_with_palette,_quantize_indices,_quantize_indices_with_clustering,_quantize_indices_with_palette,memory,__indirect_function_table,wasmMemory;function assignWasmExports(wasmExports){_malloc=Module["_malloc"]=wasmExports["g"];_library_version=Module["_library_version"]=wasmExports["h"];_clustering_job_start=Module["_clustering_job_start"]=wasmExports["i"];_clustering_job_step=Module["_clustering_job_step"]=wasmExports["j"];_clustering_job_result=Module["_clustering_job_result"]=wasmExports["k"];_clustering_job_free=Module["_clustering_job_free"]=wasmExports["l"];_mapping_job_start=Module["_mapping_job_start"]=wasmExports["m"];_mapping_job_step=Module["_mapping_job_step"]=wasmExports["n"];_mapping_job_result=Module["_mapping_job_result"]=wasmExports["o"];_mapping_job_free=Module["_mapping_job_free"]=wasmExports["p"];_free=Module["_free"]=wasmExports["q"];_get_clustering=Module["_get_clustering"]=wasmExports["r"];_get_palette=Module["_get_palette"]=wasmExports["s"];_get_palette_from_clustering=Module["_get_palette_from_clustering"]=wasmExports["t"];_get_palette_weights=Module["_get_palette_weights"]=wasmExports["u"];_quantize=Module["_quantize"]=wasmExports["v"];_quantize_with_clustering=Module["_quantize_with_clustering"]=wasmExports["w"];_quantize_with_palette=Module["_quantize_with_palette"]=wasmExports["x"];_quantize_indices=Module["_quantize_indices"]=wasmExports["y"];_quantize_indices_with_clustering=Module["_quantize_indices_with_clustering"]=wasmExports["z"];_quantize_indices_with_palette=Module["_quantize_indices_with_palette"]=wasmExports["A"];memory=wasmMemory=wasmExports["e"];__indirect_function_table=wasmExports["__indirect_function_table"]}var wasmImports={b:___cxa_throw,c:__abort_js,a:_emscripten_get_now,d:_emscripten_resize_heap};async function run(){preRun();var setStatus=Module["setStatus"];if(setStatus){setStatus("Running...");await new Promise(resolve=>setTimeout(resolve,1));setTimeout(setStatus,1,"")}if(ABORT)return;initRuntime();Module["onRuntimeInitialized"]?.();postRun()}var wasmExports;wasmExports=await createWasm();await run();
|
|
2
|
+
async function createWasmModule(moduleArg={}){var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer"&&globalThis.process?.type!="worker"&&globalThis.process?.type!="service-worker"&&typeof __filename=="string"&&typeof process.getBuiltinModule=="function";if(ENVIRONMENT_IS_NODE){var require=(name)=>process.getBuiltinModule(name)}var programArgs=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=__agglomerativeGlueUrl;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");if(_scriptName.startsWith("file:")){scriptDirectory=require("node:path").dirname(require("node:url").fileURLToPath(_scriptName))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(globalThis.process.argv.length>1){thisProgram=globalThis.process.argv[1].replace(/\\/g,"/")}programArgs=globalThis.process.argv.slice(2);quit_=(status,toThrow)=>{globalThis.process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var isFileURI=filename=>filename.startsWith("file://");class EmscriptenEH{}class EmscriptenSjLj extends EmscriptenEH{}var runtimeInitialized=false;function getMemoryBuffer(){return wasmMemory.buffer}function updateMemoryViews(){if(HEAP8?.buffer?.resizable)return;var b=getMemoryBuffer();HEAP8=new Int8Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU32=new Uint32Array(b)}function preRun(){var preRun=Module["preRun"];if(preRun){if(typeof preRun=="function")preRun=[preRun];onPreRuns.push(...preRun)}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;wasmExports["f"]()}function postRun(){var postRun=Module["postRun"];if(postRun){if(typeof postRun=="function")postRun=[postRun];onPostRuns.push(...postRun)}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what=`Aborted(${what})`;err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("clustering.wasm")}return new URL("clustering.wasm",__agglomerativeGlueUrl).href}function getBinarySync(file){if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();var instantiateWasm=Module["instantiateWasm"];if(instantiateWasm){return new Promise(resolve=>{instantiateWasm(info,inst=>resolve(receiveInstance(inst)))})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var HEAP8;var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var onPreRuns=[];var noExitRuntime=true;var HEAPU32;class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var uncaughtExceptionCount=0;var __Unwind_RaiseException=ex=>{abort()};var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);uncaughtExceptionCount++;__Unwind_RaiseException(ptr)};var __abort_js=()=>abort("");var _emscripten_get_now=()=>performance.now();var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var HEAPU8;var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["arguments"])programArgs=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];var preInit=Module["preInit"];if(preInit){if(typeof preInit=="function")Module["preInit"]=preInit=[preInit];while(preInit.length>0){preInit.shift()()}}}var _malloc,_library_version,_unpremultiply,_premultiply,_clustering_job_start,_clustering_job_step,_clustering_job_result,_clustering_job_free,_mapping_job_start,_mapping_job_step,_mapping_job_result,_mapping_job_free,_free,_get_clustering,_get_palette,_get_palette_from_clustering,_get_palette_weights,_quantize,_quantize_with_clustering,_quantize_with_palette,_quantize_indices,_quantize_indices_with_clustering,_quantize_indices_with_palette,memory,__indirect_function_table,wasmMemory;function assignWasmExports(wasmExports){_malloc=Module["_malloc"]=wasmExports["g"];_library_version=Module["_library_version"]=wasmExports["h"];_unpremultiply=Module["_unpremultiply"]=wasmExports["i"];_premultiply=Module["_premultiply"]=wasmExports["j"];_clustering_job_start=Module["_clustering_job_start"]=wasmExports["k"];_clustering_job_step=Module["_clustering_job_step"]=wasmExports["l"];_clustering_job_result=Module["_clustering_job_result"]=wasmExports["m"];_clustering_job_free=Module["_clustering_job_free"]=wasmExports["n"];_mapping_job_start=Module["_mapping_job_start"]=wasmExports["o"];_mapping_job_step=Module["_mapping_job_step"]=wasmExports["p"];_mapping_job_result=Module["_mapping_job_result"]=wasmExports["q"];_mapping_job_free=Module["_mapping_job_free"]=wasmExports["r"];_free=Module["_free"]=wasmExports["s"];_get_clustering=Module["_get_clustering"]=wasmExports["t"];_get_palette=Module["_get_palette"]=wasmExports["u"];_get_palette_from_clustering=Module["_get_palette_from_clustering"]=wasmExports["v"];_get_palette_weights=Module["_get_palette_weights"]=wasmExports["w"];_quantize=Module["_quantize"]=wasmExports["x"];_quantize_with_clustering=Module["_quantize_with_clustering"]=wasmExports["y"];_quantize_with_palette=Module["_quantize_with_palette"]=wasmExports["z"];_quantize_indices=Module["_quantize_indices"]=wasmExports["A"];_quantize_indices_with_clustering=Module["_quantize_indices_with_clustering"]=wasmExports["B"];_quantize_indices_with_palette=Module["_quantize_indices_with_palette"]=wasmExports["C"];memory=wasmMemory=wasmExports["e"];__indirect_function_table=wasmExports["__indirect_function_table"]}var wasmImports={b:___cxa_throw,c:__abort_js,a:_emscripten_get_now,d:_emscripten_resize_heap};async function run(){preRun();var setStatus=Module["setStatus"];if(setStatus){setStatus("Running...");await new Promise(resolve=>setTimeout(resolve,1));setTimeout(setStatus,1,"")}if(ABORT)return;initRuntime();Module["onRuntimeInitialized"]?.();postRun()}var wasmExports;wasmExports=await createWasm();await run();
|
|
3
3
|
;return Module}module.exports=createWasmModule;
|
package/dist/clustering.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
async function createWasmModule(moduleArg={}){var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer"&&globalThis.process?.type!="worker"&&globalThis.process?.type!="service-worker"&&typeof import.meta.url=="string"&&import.meta.url.startsWith("file:");if(ENVIRONMENT_IS_NODE){const{createRequire}=await(import(/* webpackIgnore: true */ /* @vite-ignore */ ["node", "module"].join(":")));var require=createRequire(import.meta.url)}var programArgs=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=import.meta.url;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");if(_scriptName.startsWith("file:")){scriptDirectory=require("node:path").dirname(require("node:url").fileURLToPath(_scriptName))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(globalThis.process.argv.length>1){thisProgram=globalThis.process.argv[1].replace(/\\/g,"/")}programArgs=globalThis.process.argv.slice(2);quit_=(status,toThrow)=>{globalThis.process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var isFileURI=filename=>filename.startsWith("file://");class EmscriptenEH{}class EmscriptenSjLj extends EmscriptenEH{}var runtimeInitialized=false;function getMemoryBuffer(){return wasmMemory.buffer}function updateMemoryViews(){if(HEAP8?.buffer?.resizable)return;var b=getMemoryBuffer();HEAP8=new Int8Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU32=new Uint32Array(b)}function preRun(){var preRun=Module["preRun"];if(preRun){if(typeof preRun=="function")preRun=[preRun];onPreRuns.push(...preRun)}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;wasmExports["f"]()}function postRun(){var postRun=Module["postRun"];if(postRun){if(typeof postRun=="function")postRun=[postRun];onPostRuns.push(...postRun)}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what=`Aborted(${what})`;err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("clustering.wasm")}return new URL("clustering.wasm",import.meta.url).href}function getBinarySync(file){if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();var instantiateWasm=Module["instantiateWasm"];if(instantiateWasm){return new Promise(resolve=>{instantiateWasm(info,inst=>resolve(receiveInstance(inst)))})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var HEAP8;var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var onPreRuns=[];var noExitRuntime=true;var HEAPU32;class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var uncaughtExceptionCount=0;var __Unwind_RaiseException=ex=>{abort()};var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);uncaughtExceptionCount++;__Unwind_RaiseException(ptr)};var __abort_js=()=>abort("");var _emscripten_get_now=()=>performance.now();var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var HEAPU8;var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["arguments"])programArgs=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];var preInit=Module["preInit"];if(preInit){if(typeof preInit=="function")Module["preInit"]=preInit=[preInit];while(preInit.length>0){preInit.shift()()}}}var _malloc,_library_version,_clustering_job_start,_clustering_job_step,_clustering_job_result,_clustering_job_free,_mapping_job_start,_mapping_job_step,_mapping_job_result,_mapping_job_free,_free,_get_clustering,_get_palette,_get_palette_from_clustering,_get_palette_weights,_quantize,_quantize_with_clustering,_quantize_with_palette,_quantize_indices,_quantize_indices_with_clustering,_quantize_indices_with_palette,memory,__indirect_function_table,wasmMemory;function assignWasmExports(wasmExports){_malloc=Module["_malloc"]=wasmExports["g"];_library_version=Module["_library_version"]=wasmExports["h"];_clustering_job_start=Module["_clustering_job_start"]=wasmExports["i"];_clustering_job_step=Module["_clustering_job_step"]=wasmExports["j"];_clustering_job_result=Module["_clustering_job_result"]=wasmExports["k"];_clustering_job_free=Module["_clustering_job_free"]=wasmExports["l"];_mapping_job_start=Module["_mapping_job_start"]=wasmExports["m"];_mapping_job_step=Module["_mapping_job_step"]=wasmExports["n"];_mapping_job_result=Module["_mapping_job_result"]=wasmExports["o"];_mapping_job_free=Module["_mapping_job_free"]=wasmExports["p"];_free=Module["_free"]=wasmExports["q"];_get_clustering=Module["_get_clustering"]=wasmExports["r"];_get_palette=Module["_get_palette"]=wasmExports["s"];_get_palette_from_clustering=Module["_get_palette_from_clustering"]=wasmExports["t"];_get_palette_weights=Module["_get_palette_weights"]=wasmExports["u"];_quantize=Module["_quantize"]=wasmExports["v"];_quantize_with_clustering=Module["_quantize_with_clustering"]=wasmExports["w"];_quantize_with_palette=Module["_quantize_with_palette"]=wasmExports["x"];_quantize_indices=Module["_quantize_indices"]=wasmExports["y"];_quantize_indices_with_clustering=Module["_quantize_indices_with_clustering"]=wasmExports["z"];_quantize_indices_with_palette=Module["_quantize_indices_with_palette"]=wasmExports["A"];memory=wasmMemory=wasmExports["e"];__indirect_function_table=wasmExports["__indirect_function_table"]}var wasmImports={b:___cxa_throw,c:__abort_js,a:_emscripten_get_now,d:_emscripten_resize_heap};async function run(){preRun();var setStatus=Module["setStatus"];if(setStatus){setStatus("Running...");await new Promise(resolve=>setTimeout(resolve,1));setTimeout(setStatus,1,"")}if(ABORT)return;initRuntime();Module["onRuntimeInitialized"]?.();postRun()}var wasmExports;wasmExports=await createWasm();await run();
|
|
1
|
+
async function createWasmModule(moduleArg={}){var Module=moduleArg;var ENVIRONMENT_IS_WEB=!!globalThis.window;var ENVIRONMENT_IS_WORKER=!!globalThis.WorkerGlobalScope;var ENVIRONMENT_IS_NODE=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer"&&globalThis.process?.type!="worker"&&globalThis.process?.type!="service-worker"&&typeof import.meta.url=="string"&&import.meta.url.startsWith("file:");if(ENVIRONMENT_IS_NODE){const{createRequire}=await(import(/* webpackIgnore: true */ /* @vite-ignore */ ["node", "module"].join(":")));var require=createRequire(import.meta.url)}var programArgs=[];var thisProgram="./this.program";var quit_=(status,toThrow)=>{throw toThrow};var _scriptName=import.meta.url;var scriptDirectory="";function locateFile(path){if(Module["locateFile"]){return Module["locateFile"](path,scriptDirectory)}return scriptDirectory+path}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=require("node:fs");if(_scriptName.startsWith("file:")){scriptDirectory=require("node:path").dirname(require("node:url").fileURLToPath(_scriptName))+"/"}readBinary=filename=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename);return ret};readAsync=async(filename,binary=true)=>{filename=isFileURI(filename)?new URL(filename):filename;var ret=fs.readFileSync(filename,binary?undefined:"utf8");return ret};if(globalThis.process.argv.length>1){thisProgram=globalThis.process.argv[1].replace(/\\/g,"/")}programArgs=globalThis.process.argv.slice(2);quit_=(status,toThrow)=>{globalThis.process.exitCode=status;throw toThrow}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){try{scriptDirectory=new URL(".",_scriptName).href}catch{}{if(ENVIRONMENT_IS_WORKER){readBinary=url=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.responseType="arraybuffer";xhr.send(null);return new Uint8Array(xhr.response)}}readAsync=async url=>{if(isFileURI(url)){return new Promise((resolve,reject)=>{var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=()=>{if(xhr.status==200||xhr.status==0&&xhr.response){resolve(xhr.response);return}reject(xhr.status)};xhr.onerror=reject;xhr.send(null)})}var response=await fetch(url,{credentials:"same-origin"});if(response.ok){return response.arrayBuffer()}throw new Error(response.status+" : "+response.url)}}}else{}var out=console.log.bind(console);var err=console.error.bind(console);var wasmBinary;var ABORT=false;var isFileURI=filename=>filename.startsWith("file://");class EmscriptenEH{}class EmscriptenSjLj extends EmscriptenEH{}var runtimeInitialized=false;function getMemoryBuffer(){return wasmMemory.buffer}function updateMemoryViews(){if(HEAP8?.buffer?.resizable)return;var b=getMemoryBuffer();HEAP8=new Int8Array(b);Module["HEAPU8"]=HEAPU8=new Uint8Array(b);HEAPU32=new Uint32Array(b)}function preRun(){var preRun=Module["preRun"];if(preRun){if(typeof preRun=="function")preRun=[preRun];onPreRuns.push(...preRun)}callRuntimeCallbacks(onPreRuns)}function initRuntime(){runtimeInitialized=true;wasmExports["f"]()}function postRun(){var postRun=Module["postRun"];if(postRun){if(typeof postRun=="function")postRun=[postRun];onPostRuns.push(...postRun)}callRuntimeCallbacks(onPostRuns)}function abort(what){Module["onAbort"]?.(what);what=`Aborted(${what})`;err(what);ABORT=true;what+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(what);throw e}var wasmBinaryFile;function findWasmBinary(){if(Module["locateFile"]){return locateFile("clustering.wasm")}return new URL("clustering.wasm",import.meta.url).href}function getBinarySync(file){if(readBinary){return readBinary(file)}throw"both async and sync fetching of the wasm failed"}async function getWasmBinary(binaryFile){if(!wasmBinary){try{var response=await readAsync(binaryFile);return new Uint8Array(response)}catch{}}return getBinarySync(binaryFile)}async function instantiateArrayBuffer(binaryFile,imports){try{var binary=await getWasmBinary(binaryFile);var instance=await WebAssembly.instantiate(binary,imports);return instance}catch(reason){err(`failed to asynchronously prepare wasm: ${reason}`);abort(reason)}}async function instantiateAsync(binary,binaryFile,imports){if(!binary&&!isFileURI(binaryFile)&&!ENVIRONMENT_IS_NODE){try{var response=fetch(binaryFile,{credentials:"same-origin"});var instantiationResult=await WebAssembly.instantiateStreaming(response,imports);return instantiationResult}catch(reason){err(`wasm streaming compile failed: ${reason}`);err("falling back to ArrayBuffer instantiation")}}return instantiateArrayBuffer(binaryFile,imports)}function getWasmImports(){var imports={a:wasmImports};return imports}async function createWasm(){function receiveInstance(instance){wasmExports=instance.exports;assignWasmExports(wasmExports);updateMemoryViews();return wasmExports}function receiveInstantiationResult(result){return receiveInstance(result["instance"])}var info=getWasmImports();var instantiateWasm=Module["instantiateWasm"];if(instantiateWasm){return new Promise(resolve=>{instantiateWasm(info,inst=>resolve(receiveInstance(inst)))})}wasmBinaryFile??=findWasmBinary();var result=await instantiateAsync(wasmBinary,wasmBinaryFile,info);var exports=receiveInstantiationResult(result);return exports}class ExitStatus{name="ExitStatus";constructor(status){this.message=`Program terminated with exit(${status})`;this.status=status}}var HEAP8;var callRuntimeCallbacks=callbacks=>{while(callbacks.length>0){callbacks.shift()(Module)}};var onPostRuns=[];var onPreRuns=[];var noExitRuntime=true;var HEAPU32;class ExceptionInfo{constructor(excPtr){this.excPtr=excPtr;this.ptr=excPtr-24}set_type(type){HEAPU32[this.ptr+4>>2]=type}get_type(){return HEAPU32[this.ptr+4>>2]}set_destructor(destructor){HEAPU32[this.ptr+8>>2]=destructor}get_destructor(){return HEAPU32[this.ptr+8>>2]}set_caught(caught){caught=caught?1:0;HEAP8[this.ptr+12]=caught}get_caught(){return HEAP8[this.ptr+12]!=0}set_rethrown(rethrown){rethrown=rethrown?1:0;HEAP8[this.ptr+13]=rethrown}get_rethrown(){return HEAP8[this.ptr+13]!=0}init(type,destructor){this.set_adjusted_ptr(0);this.set_type(type);this.set_destructor(destructor)}set_adjusted_ptr(adjustedPtr){HEAPU32[this.ptr+16>>2]=adjustedPtr}get_adjusted_ptr(){return HEAPU32[this.ptr+16>>2]}}var uncaughtExceptionCount=0;var __Unwind_RaiseException=ex=>{abort()};var ___cxa_throw=(ptr,type,destructor)=>{var info=new ExceptionInfo(ptr);info.init(type,destructor);uncaughtExceptionCount++;__Unwind_RaiseException(ptr)};var __abort_js=()=>abort("");var _emscripten_get_now=()=>performance.now();var getHeapMax=()=>2147483648;var alignMemory=(size,alignment)=>Math.ceil(size/alignment)*alignment;var growMemory=size=>{var oldHeapSize=wasmMemory.buffer.byteLength;var pages=(size-oldHeapSize+65535)/65536|0;try{wasmMemory.grow(pages);updateMemoryViews();return 1}catch(e){}};var HEAPU8;var _emscripten_resize_heap=requestedSize=>{var oldSize=HEAPU8.length;requestedSize>>>=0;var maxHeapSize=getHeapMax();if(requestedSize>maxHeapSize){return false}for(var cutDown=1;cutDown<=4;cutDown*=2){var overGrownHeapSize=oldSize*(1+.2/cutDown);overGrownHeapSize=Math.min(overGrownHeapSize,requestedSize+100663296);var newSize=Math.min(maxHeapSize,alignMemory(Math.max(requestedSize,overGrownHeapSize),65536));var replacement=growMemory(newSize);if(replacement){return true}}return false};{if(Module["noExitRuntime"])noExitRuntime=Module["noExitRuntime"];if(Module["print"])out=Module["print"];if(Module["printErr"])err=Module["printErr"];if(Module["arguments"])programArgs=Module["arguments"];if(Module["thisProgram"])thisProgram=Module["thisProgram"];var preInit=Module["preInit"];if(preInit){if(typeof preInit=="function")Module["preInit"]=preInit=[preInit];while(preInit.length>0){preInit.shift()()}}}var _malloc,_library_version,_unpremultiply,_premultiply,_clustering_job_start,_clustering_job_step,_clustering_job_result,_clustering_job_free,_mapping_job_start,_mapping_job_step,_mapping_job_result,_mapping_job_free,_free,_get_clustering,_get_palette,_get_palette_from_clustering,_get_palette_weights,_quantize,_quantize_with_clustering,_quantize_with_palette,_quantize_indices,_quantize_indices_with_clustering,_quantize_indices_with_palette,memory,__indirect_function_table,wasmMemory;function assignWasmExports(wasmExports){_malloc=Module["_malloc"]=wasmExports["g"];_library_version=Module["_library_version"]=wasmExports["h"];_unpremultiply=Module["_unpremultiply"]=wasmExports["i"];_premultiply=Module["_premultiply"]=wasmExports["j"];_clustering_job_start=Module["_clustering_job_start"]=wasmExports["k"];_clustering_job_step=Module["_clustering_job_step"]=wasmExports["l"];_clustering_job_result=Module["_clustering_job_result"]=wasmExports["m"];_clustering_job_free=Module["_clustering_job_free"]=wasmExports["n"];_mapping_job_start=Module["_mapping_job_start"]=wasmExports["o"];_mapping_job_step=Module["_mapping_job_step"]=wasmExports["p"];_mapping_job_result=Module["_mapping_job_result"]=wasmExports["q"];_mapping_job_free=Module["_mapping_job_free"]=wasmExports["r"];_free=Module["_free"]=wasmExports["s"];_get_clustering=Module["_get_clustering"]=wasmExports["t"];_get_palette=Module["_get_palette"]=wasmExports["u"];_get_palette_from_clustering=Module["_get_palette_from_clustering"]=wasmExports["v"];_get_palette_weights=Module["_get_palette_weights"]=wasmExports["w"];_quantize=Module["_quantize"]=wasmExports["x"];_quantize_with_clustering=Module["_quantize_with_clustering"]=wasmExports["y"];_quantize_with_palette=Module["_quantize_with_palette"]=wasmExports["z"];_quantize_indices=Module["_quantize_indices"]=wasmExports["A"];_quantize_indices_with_clustering=Module["_quantize_indices_with_clustering"]=wasmExports["B"];_quantize_indices_with_palette=Module["_quantize_indices_with_palette"]=wasmExports["C"];memory=wasmMemory=wasmExports["e"];__indirect_function_table=wasmExports["__indirect_function_table"]}var wasmImports={b:___cxa_throw,c:__abort_js,a:_emscripten_get_now,d:_emscripten_resize_heap};async function run(){preRun();var setStatus=Module["setStatus"];if(setStatus){setStatus("Running...");await new Promise(resolve=>setTimeout(resolve,1));setTimeout(setStatus,1,"")}if(ABORT)return;initRuntime();Module["onRuntimeInitialized"]?.();postRun()}var wasmExports;wasmExports=await createWasm();await run();
|
|
2
2
|
;return Module}export default createWasmModule;
|
package/dist/clustering.wasm
CHANGED
|
Binary file
|