-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathicecup.html
More file actions
683 lines (597 loc) · 23.6 KB
/
icecup.html
File metadata and controls
683 lines (597 loc) · 23.6 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
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Icecup</title>
<link rel="stylesheet" href="styles.css">
<link rel="shortcut icon" type="image/png" href="favicon.png">
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.8.0/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/ace-builds@1.4.12/src-min-noconflict/ace.js"></script>
<script src="https://cdn.jsdelivr.net/npm/lz-string@1.4.4/libs/lz-string.min.js"></script>
<style type="text/css" media="screen">
.ace_editor {
font-size: 100%;
height: 100%;
min-width: 600px;
}
</style>
</head>
<body>
<div class="row" id="main" style="border: 1px solid lightgray; resize: vertical; overflow-x: auto; overflow-y: hidden; height: 30vh; min-height: 150px;">
<div class="col" id="editor"></div>
<div class="col" style="overflow: auto; height: 100%;">
<h3 id="error_header" style="text-align:left; display:none;">Error log</h3>
<div id="error" style="color: red; white-space: pre; font-family: monospace; display:none;"></div>
<h3 style="text-align:left;margin-top:0;">Output log</h3>
<div id="output" style="white-space: pre; font-family: monospace; margin-bottom: 15px"></div>
</div>
</div>
<div>
<form>
<button type="button" id="run" style="font-size: 100%; border: 2px solid green;">Run</button>
<button type="button" id="stop" style="font-size: 100%; border: 2px solid red;">Stop</button>
Probability:
<input type="radio" name="p" id="eq" value="eq" checked="checked" />
<label for="eq">Equal to</label>
<input type="radio" name="p" id="ge" value="ge" />
<label for="ge">At least</label>
<input type="radio" name="p" id="le" value="le" />
<label for="le">At most</label>
<input type="checkbox" name="ls" id="ls" />
<label for="ls">Log scale</label>
<input type="checkbox" name="t" id="t" />
<label for="t">Transpose</label>
<button type="button" id="copy_url" style="font-size: 100%; width: 150px;">Copy URL</button>
</form>
</div>
<div style="border: 1px solid lightgray; resize: vertical; overflow-x: auto; overflow-y: hidden; height: 60vh; min-height: 300px;">
<canvas id="chart"></canvas>
</div>
<span style="float: left;" id="computation_time">Computation time:</span>
<div style="float:right;">
<span id="icepool_version">Icepool version:</span>
<button type="button" id="switch_to_latest" style="font-size: 100%; border: 2px dark grey;">Switch to latest</button>
</div>
<div style="clear: both;"></div>
<div class="text_content">
<h1>Icecup</h1>
<p>A simple frontend for the Icepool Python package.</p>
<h2>Tips</h2>
<ul>
<li>Use the <tt>output(die, [label])</tt> function to add a die to the plot and print its probabilities. You can use the optional second <tt>label</tt> argument to give the die a name.</li>
<li>Experimental: Use the <tt>area(die, [label])</tt> function to fill the area between the curve and the previous area plot. You should plot from the lowest/most specific condition to highest/least specific condition.</li>
<li>Use the <tt>limit(left, right)</tt> function to limit the extent of the x-axis (inclusive). <tt>None</tt> will not limit values on that side.</li>
<li>In addition to the "Run" button, you can use Ctrl-Enter or Cmd-Enter to run the script.</li>
<li>The URL updates automatically when you run the script.</li>
<li>If you use the <tt>random</tt> module (including <tt>.sample()</tt> methods), the script will be re-run each time.</li>
</ul>
<h2>Useful links</h2>
<ul>
<li><a href="https://github.com/HighDiceRoller/icepool">Icepool Github.</a></li>
<li><a href="https://highdiceroller.github.io/icepool/apidoc/latest/icepool.html">API documentation.</a></li>
<li><a href="https://highdiceroller.github.io/icepool/notebooks/lab/index.html">JupyterLite distribution.</a> Contains a collection of example notebooks.</li>
</ul>
Built using the <a href="https://ace.c9.io/">Ace code editor</a>, <a href="https://www.chartjs.org/">Chart.js</a>, and <a href="https://pyodide.org/">Pyodide</a>.
</div>
<script id="icecupWorker" type="javascript/worker">
importScripts("https://cdn.jsdelivr.net/pyodide/v0.26.0/full/pyodide.js");
async function initPyodide(){
self.postMessage({ cmd: 'setLoadingText', text: 'Loading pyodide' });
let pyodide = await loadPyodide({
indexURL : "https://cdn.jsdelivr.net/pyodide/v0.26.0/full/",
stdout: (s) => {self.postMessage({ cmd: 'appendOutput', text: s + '\n'});},
stderr: (s) => {self.postMessage({ cmd: 'appendError', text: s + '\n'});}
});
await pyodide.loadPackage(["micropip"],
{messageCallback : (s) => {self.postMessage({ cmd: 'setLoadingText', text: s });}}
);
self.postMessage({ cmd: 'setLoadingText', text: 'Loading icepool' });
let icepool_version_request = icepool_version != "" ? "==" + icepool_version : "";
icepool_version = await pyodide.runPythonAsync(`
import micropip
await micropip.install('icepool${icepool_version_request}', pre=True)
import icepool
icepool.__version__
`)
self.postMessage({ cmd: 'setIcepoolVersion', text: icepool_version });
self.postMessage({ cmd: 'setLoadingText', text: '' });;
return pyodide;
}
let pyodideReadyPromise = initPyodide();
async function resetIcepool() {
let pyodide = await pyodideReadyPromise;
pyodide.runPython(`
import icepool
import fractions
import pyodide
import builtins
import js
import itertools
import numbers
def type_sort_string(outcome):
if isinstance(outcome, numbers.Real):
return ''
else:
return type(outcome).__qualname__
class OutputManager():
DEFAULT_COLORS = [
(49, 189, 245),
(189, 35, 42),
(42, 217, 49),
(140, 35, 196),
(217, 147, 49),
(35, 210, 210),
(210, 98, 189),
(35, 154, 98),
(49, 21, 245),
(217, 210, 105),
]
DEFAULT_POINTS = [
('circle', 3),
('triangle', 4),
('rect', 3),
('rectRot', 3),
]
def __init__(self):
self.reset()
def reset(self):
import random
self.prints = []
self.outputs = []
self.starting_random_state = random.getstate()
self.limit_left = None
self.limit_right = None
def limit(self, left, right):
if left is not None and right is not None:
self.limit_left = min(left, right)
self.limit_right = max(left, right)
self.limit_left = left
self.limit_right = right
@staticmethod
def probability(die, outcome, probability_type):
if probability_type == 'ge':
try:
return die.probability('>=', outcome)
except TypeError:
return None
elif probability_type == 'le':
try:
return die.probability('<=', outcome)
except TypeError:
return None
else:
return die.probability(outcome)
@staticmethod
def probabilities(die, outcomes, probability_type):
return [OutputManager.probability(die, outcome, probability_type) for outcome in outcomes]
@staticmethod
def format_string(probability_type):
if probability_type == 'ge':
return 'md:*o|q>=|%>='
elif probability_type == 'le':
return 'md:*o|q<=|%<='
else:
return 'md:*o|q==|%=='
@staticmethod
def outcome_to_js(outcome, a, b):
if isinstance(outcome, icepool.Vector):
return js.Array.from_(outcome)
elif isinstance(outcome, fractions.Fraction):
return float(outcome)
return str(outcome)
def append_output(self, die, label, fill=False):
if label is None:
label = f'Output #{len(self.outputs)}'
else:
label = str(label)
label_with_stats = label
try:
label_with_stats += f' (Mean: {float(die.mean()):.2f} SD: {die.standard_deviation():.2f})'
except:
pass
self.outputs.append((die, label, label_with_stats, fill))
self.append_print(label_with_stats)
self.append_print(die)
def chart_data(self, probability_type, transpose):
"""
Returns:
labels, datasets in js format
"""
outcomes = set()
for i, (die, label, label_with_stats, fill) in enumerate(self.outputs):
outcomes = outcomes.union(die.outcomes())
if not outcomes:
return pyodide.ffi.to_js({'labels': [], 'datasets': []}, dict_converter=js.Object.fromEntries, default_converter=self.outcome_to_js)
if self.limit_left is not None:
outcomes = {x for x in outcomes if x >= self.limit_left}
if self.limit_right is not None:
outcomes = {x for x in outcomes if x <= self.limit_right}
if all(isinstance(x, int) for x in outcomes) and max(outcomes) - min(outcomes) <= 1000:
outcomes = list(range(min(outcomes), max(outcomes) + 1))
else:
try:
outcomes = sorted(outcomes)
except TypeError:
_, outcomes = zip(*sorted((type_sort_string(outcome), outcome) for outcome in outcomes))
if transpose:
x_labels = []
datasets = []
for i, (die, label, label_with_stats, fill) in enumerate(self.outputs):
x_labels.append(label)
for i, outcome in enumerate(outcomes):
probabilities = []
for die, label, label_with_stats, fill in self.outputs:
probabilities.append(self.probability(die, outcome, probability_type))
color = OutputManager.DEFAULT_COLORS[i % len(OutputManager.DEFAULT_COLORS)]
point, radius = OutputManager.DEFAULT_POINTS[i // len(OutputManager.DEFAULT_COLORS) % len(OutputManager.DEFAULT_POINTS)]
dataset = {
'data': probabilities,
'label': outcome,
'borderColor': 'rgba(%d, %d, %d, 1.0)' % color,
'backgroundColor': 'rgba(%d, %d, %d, 1.0)' % color,
'pointStyle': point,
'radius': radius,
}
if probability_type == 'ge':
if i == len(outcomes) - 1:
dataset['fill'] = 'start'
else:
dataset['fill'] = '+1'
dataset['backgroundColor'] = 'rgba(%d, %d, %d, 0.25)' % color
elif probability_type == 'le':
if i == 0:
dataset['fill'] = 'start'
else:
dataset['fill'] = '-1'
dataset['backgroundColor'] = 'rgba(%d, %d, %d, 0.25)' % color
datasets.append(dataset)
else:
x_labels = outcomes
datasets = []
any_fill = False
for i, (die, label, label_with_stats, fill) in enumerate(self.outputs):
dataset = {}
color = OutputManager.DEFAULT_COLORS[i % len(OutputManager.DEFAULT_COLORS)]
point, radius = OutputManager.DEFAULT_POINTS[i // len(OutputManager.DEFAULT_COLORS) % len(OutputManager.DEFAULT_POINTS)]
probabilities = self.probabilities(die, outcomes, probability_type)
dataset = {
'data': probabilities,
'label': label_with_stats,
'borderColor': 'rgba(%d, %d, %d, 1.0)' % color,
'backgroundColor': 'rgba(%d, %d, %d, 1.0)' % color,
'pointStyle': point,
'radius': radius,
}
if fill:
if any_fill:
fill = '-1'
else:
fill = 'origin'
any_fill = True
dataset['fill'] = fill
dataset['backgroundColor'] = 'rgba(%d, %d, %d, 0.25)' % color
datasets.append(dataset)
return pyodide.ffi.to_js({'labels': x_labels, 'datasets': datasets}, dict_converter=js.Object.fromEntries, default_converter=self.outcome_to_js)
def append_print(self, *args, **kwargs):
self.prints.append((args, kwargs))
def execute_prints(self, probability_type):
for args, kwargs in self.prints:
args = (arg.format(self.format_string(probability_type))
if isinstance(arg, icepool.Population)
else arg
for arg in args)
builtins.print(*args, **kwargs)
def used_random(self):
import random
return random.getstate() != self.starting_random_state
_manager = OutputManager()
def output(die, /, label=None):
"""Plots a die and also prints it."""
_manager.append_output(die, label)
def print(*args, **kwargs):
_manager.append_print(*args, **kwargs)
def area(die, /, label=None):
_manager.append_output(die, label, fill=True)
def limit(left=None, right=None):
_manager.limit(left, right)
`)
}
var usedRandom = false;
var prevCode = '';
async function runCode(code, probabilityType, transpose) {
let pyodide = await pyodideReadyPromise;
self.postMessage({ cmd: 'clearOutput' });
if (usedRandom || code != prevCode) {
await resetIcepool();
self.postMessage({ cmd: 'clearError' });
pyodide.runPython(`_manager.reset()`);
let code_in_main = 'def main():\n' + code.replace(/^/gm, ' ') + '\nmain()';
self.postMessage({ cmd: 'setStartTime', time: performance.now() + performance.timeOrigin });
try {
pyodide.runPython(code_in_main);
usedRandom = pyodide.runPython(`_manager.used_random()`);
} catch (err) {
self.postMessage({ cmd: 'appendError', text: err + '\n'});
}
self.postMessage({ cmd: 'setEndTime', time: performance.now() + performance.timeOrigin });
prevCode = code;
}
try {
pyodide.runPython("_manager.execute_prints('" + probabilityType + "')");
let chart_data = pyodide.runPython("_manager.chart_data('" + probabilityType + "', " + transpose + ")");
self.postMessage({ cmd: 'updateChart', labels: chart_data.labels, datasets: chart_data.datasets });
} catch (err) {
self.postMessage({ cmd: 'appendError', text: err + '\n'});
}
}
self.onmessage = async (msg) => {
if (msg.data.cmd === "setInterruptBuffer") {
pyodide.setInterruptBuffer(msg.data.interruptBuffer);
} else if (msg.data.cmd === "runCode") {
runCode(msg.data.code, msg.data.probabilityType, msg.data.transpose);
}
}
</script>
<script type="text/javascript">
var searchParams = new URLSearchParams(window.location.search);
var icepool_version = searchParams.get('v');
if (!icepool_version || !icepool_version.match(/^\d+\.\d+\.\d+((a|b|pre)\d+)?$/)) {
icepool_version = '';
}
var startTime = 0.0;
var endTime = 0.0;
function createPyodideWorker() {
let worker_blob = new Blob([`var icepool_version="${icepool_version}";`,
document.getElementById('icecupWorker').textContent],
{type: "text/javascript"});
let worker = new Worker(window.URL.createObjectURL(worker_blob));
worker.onmessage = (msg) => {
if (msg.data.cmd === "clearOutput") {
clearOutput();
} else if (msg.data.cmd === "clearError") {
clearError();
} else if (msg.data.cmd === "appendOutput") {
appendOutput(msg.data.text);
} else if (msg.data.cmd === "appendError") {
appendError(msg.data.text);
} else if (msg.data.cmd === "updateChart") {
updateChart(msg.data.labels, msg.data.datasets);
} else if (msg.data.cmd === "setStartTime") {
startTime = msg.data.time;
} else if (msg.data.cmd === "setEndTime") {
endTime = msg.data.time;
} else if (msg.data.cmd === "setLoadingText") {
setLoadingText(msg.data.text);
} else if (msg.data.cmd === "setIcepoolVersion") {
setIcepoolVersion(msg.data.text);
}
}
return worker;
}
var pyodideWorker = createPyodideWorker();
function interruptExecution() {
// The signal method seems difficult to implement for now.
// We use a crude termination instead.
pyodideWorker.terminate();
startTime = 0.0;
endTime = 0.0;
pyodideWorker = createPyodideWorker();
}
async function runCode() {
let code = editor.getValue();
lastRunCode = code;
updateSearchQuery();
let probabilityType;
if (document.getElementById('ge').checked) {
probabilityType = 'ge';
} else if (document.getElementById('le').checked) {
probabilityType = 'le';
} else {
probabilityType = 'eq';
}
let transpose;
if (document.getElementById('t').checked) {
transpose = 'True';
} else {
transpose = 'False';
}
pyodideWorker.postMessage({ cmd: "runCode", code, probabilityType, transpose });
}
function switchToLatest() {
icepool_version = "";
interruptExecution();
runCode();
}
// Setup editor.
var editor = ace.edit("editor");
editor.setTheme("ace/theme/github");
editor.session.setMode("ace/mode/python");
editor.setOptions({
"useSoftTabs" : true,
"scrollPastEnd" : 1.0
});
var resizer = new ResizeObserver(entries => {editor.resize();});
resizer.observe(document.getElementById("main"));
var initialCode = 'from icepool import d\n\noutput(3 @ d(6))\n';
var url_code = searchParams.get('c');
if (url_code) {
try {
initialCode = LZString.decompressFromEncodedURIComponent(url_code);
} catch (err) {
document.getElementById("error").textContent = "Failed to decompress code from URL.";
}
}
editor.setValue(initialCode, 1);
var lastRunCode = initialCode;
var probabilityDisplay = searchParams.get('p');
if (probabilityDisplay) {
document.getElementById(probabilityDisplay).checked = true;
}
if (searchParams.get('ls')) {
document.getElementById('ls').checked = true;
}
if (searchParams.get('t')) {
document.getElementById('t').checked = true;
}
// Setup chart.
var chartContext = document.getElementById('chart').getContext('2d');
var chart = new Chart(chartContext, {
type: 'line',
data: {
labels: [],
datasets: [],
},
options: {
animation: {
duration: 0,
},
responsive: true,
maintainAspectRatio: false,
interaction: {
intersect: false,
},
scales: {
x: {
title: {
display: true,
text: 'Outcome',
},
},
y: {
beginAtZero: true,
title: {
display: true,
text: 'Probability',
},
},
},
plugins: {
title: {
fullSize: true,
display : true,
font: {
size: 36,
},
},
legend: {
labels: {
usePointStyle: true,
},
},
tooltip : {
usePointStyle: true,
callbacks: {},
},
filler: {
propagate: true,
},
},
elements: {
point: {
radius: 3,
},
},
},
});
if (document.getElementById('ls').checked) {
chart.options.scales.y.type = 'logarithmic';
chart.options.scales.y.ticks.callback = (val) => (val.toExponential());
}
function setLoadingText(text) {
console.log(text);
let loadingText = text.match(/Loading \w+/);
if (loadingText) {
chart.options.plugins.title = {
text: loadingText[0],
fullSize: true,
display: true,
font: {
size: 36,
},
};
} else {
chart.options.plugins.title = {
text: "",
fullSize: false,
display : false,
};
}
chart.update();
}
function setIcepoolVersion(text) {
icepool_version = text;
updateSearchQuery();
document.getElementById("icepool_version").textContent = 'Icepool version: ' + text;
}
function clearOutput() {
document.getElementById("output").textContent = '';
}
function clearError() {
document.getElementById("error_header").style.display = 'none';
document.getElementById("error").style.display = 'none';
document.getElementById("error").textContent = '';
}
function appendOutput(text) {
document.getElementById("output").textContent += text;
}
function appendError(text) {
document.getElementById("error_header").style.display = 'block';
document.getElementById("error").style.display = 'inline';
document.getElementById("error").textContent += text;
}
function updateChart(labels, datasets) {
chart.data.labels = labels;
chart.data.datasets = datasets;
chart.update();
}
function updateLogScale() {
updateSearchQuery();
if (document.getElementById('ls').checked) {
chart.options.scales.y.type = 'logarithmic';
chart.options.scales.y.ticks.callback = (val) => val.toExponential(0);
chart.options.plugins.tooltip.callbacks.label = (ctx) => ctx.dataset.label + ': ' + ctx.raw.toExponential(2);
} else {
chart.options.scales.y.type = 'linear';
chart.options.scales.y.ticks.callback = (val) => ((val * 100.0).toPrecision(3) * 1.0 + '%');
chart.options.plugins.tooltip.callbacks.label = (ctx) => ctx.dataset.label + ': ' + (ctx.raw * 100.0).toPrecision(3) + '%';
}
chart.update();
}
function updateSearchQuery() {
let searchParams = $("form").serialize();
history.replaceState(null, "", "?" + searchParams + "&v=" + icepool_version + "&c=" + LZString.compressToEncodedURIComponent(lastRunCode));
}
document.getElementById("run").addEventListener("click", runCode);
document.getElementById("stop").addEventListener("click", interruptExecution);
document.getElementById("switch_to_latest").addEventListener("click", switchToLatest);
document.body.addEventListener('keydown', function (e) {
if (e.key == 'Enter' && (e.ctrlKey || e.metaKey)) {
e.preventDefault();
run();
}
});
document.getElementById("eq").addEventListener("change", runCode);
document.getElementById("ge").addEventListener("change", runCode);
document.getElementById("le").addEventListener("change", runCode);
document.getElementById("ls").addEventListener("change", updateLogScale);
document.getElementById("t").addEventListener("change", runCode);
document.getElementById("copy_url").addEventListener("click", function (e) {
navigator.clipboard.writeText(window.location.href);
document.getElementById("copy_url").textContent = 'Copied!';
setTimeout( () => {document.getElementById("copy_url").textContent = 'Copy URL';}, 1000);
});
// Initial run.
updateLogScale();
setInterval(() => {
let computationTime = 0.0;
if (endTime >= startTime) {
computationTime = endTime - startTime;
} else {
computationTime = performance.now() + performance.timeOrigin - startTime;
}
document.getElementById("computation_time").textContent = 'Computation time: ' + (computationTime * 0.001).toFixed(3) + ' s';
}, 100)
runCode();
</script>
</body>