-
Notifications
You must be signed in to change notification settings - Fork 62
/
integers.html
425 lines (397 loc) · 12.1 KB
/
integers.html
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
<body>
<div class="buttons">
<button id="prime">Highlight Primes</button>
<button id="even">Highlight Even</button>
<button id="even2">Stable highlight Even</button>
<button id="b">Clear</button>
<button id="select-ids">Select ids</button>
<input id="input-ids" title="selection" label="selection" type="text" value="1066 1968 2431 10012" />
<button id="select-lots-of-ids">Select lots of ids</button>
<div id="filter">FILTER:</div>
<div id="filter2">FILTER2:</div>
<div id="foreground">FOREGROUND:</div>
<div id="categorical">CATEGORICAL:</div>
</div>
<textarea style="display:none" data-testid="API">
</textarea>
<div id="deepscatter"></div>
</body>
<script type="module" lang="ts">
import { Scatterplot, Deeptable, Bitmask, dictionaryFromArrays } from './src/deepscatter';
import {
tableFromArrays,
Table,
RecordBatch,
vectorFromArray,
Utf8,
Int8,
Int16,
Int32,
Dictionary,
makeVector
} from 'apache-arrow';
const num_batches = 4;
window.RecordBatch = RecordBatch;
window.vectorFromArray = vectorFromArray;
function num_to_string(d) {
return Number(d).toString();
}
let batch_no = 0;
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const filterMethod = urlParams.get('filter-method') || 'bitmask';
// A function to create a single batch
function createTable(n_batches) {
function make_batch(start = 0, length = 65536) {
const batch_number_here = batch_no++;
let x = new Float32Array(length);
let y = new Float32Array(length);
let integers = new Int32Array(length);
let ix = new Uint32Array(length);
let batch_id = new Float32Array(length).fill(batch_number_here);
for (let i = start; i < start + length; i++) {
ix[i - start] = i;
let x_ = 0;
let y_ = 0;
const binary = i.toString(2).split('').reverse();
for (let j = 0; j < binary.length; j++) {
const bit = binary[j];
if (bit == 1) {
if (j % 2 == 0) {
x_ += 2 ** (j / 2);
} else {
y_ += 2 ** ((j - 1) / 2);
}
}
}
x[i - start] = x_;
y[i - start] = y_;
integers[i - start] = i;
}
const vs = [...ix].map(num_to_string);
// const _id = vectorFromArray(vs, new Utf8());
// console.log({ _id });
return new Table({
x: vectorFromArray(x),
y: vectorFromArray(y),
_id: vectorFromArray(vs, new Utf8()),
integers: vectorFromArray(integers),
batch_id: vectorFromArray(batch_id),
});
}
const batches = [];
const SIZE = 65536 / 4 / 4;
for (let i = 0; i < n_batches; i++) {
const batch = make_batch(i * SIZE, SIZE);
batches.push(batch);
window.b = batch;
console.log(i);
}
const table = new Table([batches]);
return table;
}
const table = createTable(num_batches);
const plot = new Scatterplot('#deepscatter');
function eratosthenes(n) {
// improved from https://stackoverflow.com/questions/15471291/sieve-of-eratosthenes-algorithm-in-javascript-running-endless-for-large-number
// Eratosthenes algorithm to find all primes under n
var upperLimit = Math.sqrt(n),
output = [2];
// Make an array from 2 to (n - 1)
const array = new Uint32Array(n);
// Remove multiples of primes starting from 2, 3, 5,...
for (var i = 3; i <= upperLimit; i += 2) {
if (array[i] == 0) {
for (var j = i * i; j < n; j += i * 2) array[j] = 1;
}
}
// All array[i] set to 1 (true) are primes
for (var i = 3; i < n; i += 2) {
if (array[i] == 0) {
output.push(i);
}
}
return output;
}
const draw1 = plot.plotAPI({
arrow_table: table,
point_size: 2.5,
max_points: num_batches * 65536,
alpha: 25,
background_color: '#EEEDDE',
zoom_balance: 0.75,
duration: 500,
encoding: {
x: {
field: 'x',
transform: 'literal',
},
y: {
field: 'y',
transform: 'literal',
},
color: {
field: 'integers',
range: 'viridis',
domain: [1, 65000 / 4],
transform: 'log',
},
},
});
draw1.then(() => {
for (let dim of ['filter', 'filter2', 'foreground']) {
const id = document.getElementById(dim);
const button = document.createElement('button');
button.textContent = `clear`;
const encoding = {};
encoding[dim] = null;
button.addEventListener('click', function () {
plot.plotAPI({ encoding });
});
id.appendChild(button);
for (const i of [2, 3, 5, 7, 11, 13, 17]) {
const button = document.createElement('button');
button.textContent = `products of ${i}`;
button.addEventListener('click', function () {
bindproductsOf(i);
const encoding = {};
encoding[dim] = {
field: `products of ${i}`,
op: 'gt',
a: 0,
};
console.log(JSON.stringify(encoding, null, 2));
plot.plotAPI({
encoding,
});
});
id.appendChild(button);
}
}
const id = document.getElementById("categorical");
const button = document.createElement('button');
button.textContent = `Color by lowest prime factor`;
plot.ready.then(() => {
plot._root.promise.then(dataset => {
[2, 3, 5, 7, 11, 13, 17, 19].map(prime => {
if (plot.dataset.transformations[`products of ${prime}`] === undefined) {
bindproductsOf(prime)
}
})
})
})
button.addEventListener('click', function () {
plot.dataset.transformations['lowest_prime'] = async function (tile) {
const factors = {}
const primes = [2, 3, 5, 7, 11, 13, 17];
const labels = ["NA", "2", "3", "5", "7", "11", "13", "seventeen"]
const indices = new Int8Array(tile.record_batch.numRows);
const lookups = []
for (const prime of primes) {
lookups.push(await tile.get_column(`products of ${prime}`))
}
outer: for (let i = 0; i < tile.record_batch.numRows; i++) {
for (let j = 0; j < lookups.length; j++) {
if (i < 10) {
// console.log(i, j, lookups[j].get(i))
}
if (lookups[j].get(i) > 0) {
indices[i] = j + 1
continue outer
}
}
}
console.log("YOOHOO")
console.log({ indices, labels })
const dicto = dictionaryFromArrays(indices, labels)
console.log({ dicto })
console.log(dicto.length, dicto.toArray())
return dicto
}
plot.plotAPI({
encoding: {
color: {
field: "lowest_prime",
range: 'dark2'
}
}
})
})
id.appendChild(button);
{
const id = document.getElementById("categorical");
// colorize by factors
const numbers = []
for (let i = 0; i < 1_000_000; i++) {
numbers.push("" + i)
}
let dictionaryBuilder = undefined
const button = document.createElement('button');
button.textContent = `Color by individual numbers as factors`;
plot.ready.then(() => {
if (dictionaryBuilder === undefined) {
// Curry up the numbers first to ensure we're always in the same dictionary.
dictionaryBuilder = dictionaryFromArrays(numbers);
}
button.addEventListener('click', function () {
plot.dataset.transformations['dictionary number coloring'] = async function (tile) {
const num = await tile.get_column("integers");
console.log({ num })
return dictionaryBuilder(num.toArray())
}
plot.plotAPI({
encoding: {
color: {
field: "dictionary number coloring",
range: 'category10'
}
}
})
})
})
id.appendChild(button);
}
});
window.plot = plot;
const functions = {
prime: (n) => eratosthenes(n),
even: (n) => [...Array(n).keys()].filter((x) => x % 2 === 0),
stable_even: (n) => [...Array(n).keys()].filter((x) => x % 2 === 0),
};
function bindproductsOf(n) {
if (filterMethod === 'float32') {
plot.dataset.transformations[`products of ${n}`] = function (tile) {
const integers = tile.record_batch.getChild('integers');
const output = new Float32Array(integers.length);
for (let i = 0; i < integers.length; i += 1) {
let int = integers.get(i);
if (int % n === 0) {
output[i] += 1;
int = int / n;
}
}
return output;
};
} else if (filterMethod === 'bitmask') {
plot.dataset.transformations[`products of ${n}`] = async function (tile) {
const integers = tile.record_batch.getChild('integers');
const mask = new Bitmask(integers.length);
for (let i = 0; i < integers.length; i += 1) {
let int = integers.get(i);
if (int % n === 0) {
mask.set(i, true);
}
}
return mask.to_arrow();
}
}
}
const done = new Set();
function highlight(key) {
const vals = functions[key](num_batches * 2 ** 16);
const prime_ids = vals.map((d) => d.toString());
if (!done.has(key)) {
plot.select_data(
{
name: key,
ids: prime_ids,
field: '_id',
}
)
}
if (key.slice(0, 7) == 'stable_') {
done.add(key);
}
plot.plotAPI({
duration: 1000,
encoding: {
foreground: {
field: key,
op: 'eq',
a: 1,
},
size: {
field: key,
domain: [0, 1],
range: [0.5, 5],
},
},
});
}
document.getElementById('select-ids').addEventListener('click', () => {
const ids = document
.getElementById('input-ids')
.value.split(' ')
.filter((d) => d);
console.log({ ids });
const name = Math.random().toString(36);
plot.select_and_plot({ name, ids, idField: '_id' }).then(selection => {
window.selection = selection;
})
});
document
.getElementById('select-lots-of-ids')
.addEventListener('click', () => {
const ids = [];
for (let i = 0; i < 1000; i += 1) {
ids.push(Math.floor(Math.random() * 2 ** 16).toString());
}
console.log({ ids });
const name = Math.random().toString(36);
plot.select_and_plot({
name,
ids,
idField: '_id',
});
});
document
.getElementById('prime')
.addEventListener('click', () => highlight('prime'));
document
.getElementById('even')
.addEventListener('click', () => highlight('even'));
document
.getElementById('even2')
.addEventListener('click', () => highlight('stable_even'));
document
.getElementById('b')
.addEventListener('click', () =>
plot.plotAPI({ encoding: { foreground: null, size: {} } })
);
// function dictionaryFromArrays(indices, labels) {
// const labelsArrow = vectorFromArray(labels, new Utf8());
// let t;
// if (indices[Symbol.toStringTag] === `Int8Array`) {
// t = new Int8()
// } else if (indices[Symbol.toStringTag] === `Int16Array`) {
// t = new Int16()
// } else if (indices[Symbol.toStringTag] === `Int32Array`) {
// t = new Int32()
// } else {
// console.log(indices[Symbol.toStringTag])
// throw new Error("values must be an array of signed integers, 32 bit or smaller.")
// }
// console.log({ indices }, indices.length)
// const type = new Dictionary(labelsArrow.type, t, 0, false);
// const returnval = makeVector({
// type,
// length: indices.length,
// nullCount: 0,
// data: indices,
// dictionary: labelsArrow,
// });
// return returnval
// }
</script>
<style>
.buttons {
position: fixed;
top: 0;
left: 0;
padding: 20px;
z-index: 199;
}
.tooltip {
transform: translate(-50%, -100%);
}
</style>