-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexpression.html
More file actions
705 lines (646 loc) · 22 KB
/
expression.html
File metadata and controls
705 lines (646 loc) · 22 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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Les incertitudes et leur propagation dans un calcul</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: 'Menlo', 'Consolas', 'Monaco', monospace;
background: #1e1e2e;
color: #cdd6f4;
min-height: 100vh;
display: flex;
flex-direction: column;
padding: 20px;
}
.top-bar {
width: 100%;
margin-bottom: 15px;
}
.columns {
flex: 1;
display: flex;
gap: 20px;
min-height: 0;
}
@media (max-width: 800px) {
.columns {
flex-direction: column;
}
.right-panel {
width: 100% !important;
}
#output {
min-height: 200px !important;
}
.chart-box canvas {
height: auto !important;
}
}
h1 {
font-size: 1.2em;
color: #89b4fa;
margin-bottom: 10px;
}
.help {
font-size: 0.75em;
color: #6c7086;
margin-bottom: 15px;
line-height: 1.6;
}
.left-panel {
flex: 1;
display: flex;
flex-direction: column;
min-width: 0;
}
.right-panel {
width: 400px;
display: flex;
flex-direction: column;
gap: 10px;
}
#output {
flex: 1;
overflow-y: auto;
padding: 10px;
background: #181825;
border: 1px solid #313244;
border-radius: 8px 8px 0 0;
min-height: 300px;
}
#output .line { margin: 2px 0; }
#output .input-line { color: #a6adc8; }
#output .input-line .prompt { color: #89b4fa; }
#output .result-line { color: #a6e3a1; }
#output .error-line { color: #f38ba8; }
#output .info-line { color: #6c7086; font-style: italic; }
.input-row {
display: flex;
background: #181825;
border: 1px solid #313244;
border-top: none;
border-radius: 0 0 8px 8px;
padding: 8px 10px;
align-items: center;
gap: 6px;
}
.input-row .prompt { color: #89b4fa; font-size: 1em; }
#userInput {
flex: 1;
background: transparent;
border: none;
outline: none;
color: #cdd6f4;
font-family: inherit;
font-size: 1em;
}
.pm-btn {
background: #313244;
color: #cdd6f4;
border: 1px solid #45475a;
border-radius: 4px;
padding: 2px 8px;
font-family: inherit;
font-size: 1em;
cursor: pointer;
}
.pm-btn:hover { background: #45475a; }
.vars-box {
flex: 1;
overflow-y: auto;
}
.variables {
font-size: 0.8em;
color: #a6adc8;
line-height: 1.8;
}
.variables .var-entry { margin: 2px 0; }
.variables .var-name { color: #f9e2af; }
.variables .var-val { color: #a6e3a1; }
.no-vars { color: #6c7086; font-style: italic; }
.chart-box {
background: #181825;
border: 1px solid #313244;
border-radius: 8px;
padding: 12px;
flex: 1;
}
.chart-box h2 {
font-size: 0.85em;
color: #89b4fa;
margin-bottom: 8px;
}
.chart-box canvas {
width: 100%;
border-radius: 4px;
}
.legend {
margin-top: 8px;
font-size: 0.75em;
line-height: 1.8;
}
.legend-item {
display: inline-block;
margin-right: 12px;
}
.legend-dot {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 50%;
margin-right: 4px;
vertical-align: middle;
}
.no-chart {
color: #6c7086;
font-style: italic;
font-size: 0.8em;
padding: 20px 0;
text-align: center;
}
</style>
</head>
<body>
<div class="top-bar">
<h1 id="pageTitle"></h1>
<div class="help">
<span id="helpIntro"></span><br>
<span id="helpSyntax"></span>
<span id="helpKeyboard"></span> | <a href="https://github.com/DCC-Lab/Expression" style="color:#89b4fa" id="githubLink"></a>
| <button class="pm-btn" id="langBtn" style="margin-left:4px"></button>
</div>
</div>
<div class="columns">
<div class="left-panel">
<div id="output">
<div class="line info-line" id="startMsg"></div>
</div>
<div class="input-row">
<span class="prompt">:></span>
<input type="text" id="userInput" autocomplete="off" autofocus>
<button class="pm-btn" id="pmBtn">±</button>
</div>
</div>
<div class="right-panel">
<div class="chart-box vars-box" id="varsBox">
<h2 id="varsTitle"></h2>
<div class="variables" id="varsDisplay">
<div class="no-vars" id="noVarsMsg"></div>
</div>
</div>
<div class="chart-box">
<h2 id="distTitle"></h2>
<canvas id="chartCanvas" width="376" height="280"></canvas>
<div class="legend" id="chartLegend"></div>
<div class="no-chart" id="noChart"></div>
</div>
</div>
</div>
<script src="i18n.js"></script>
<script src="expression.js?v=4"></script>
<script>
let N_EVAL = 500_000;
const COLORS = [
'#89b4fa', '#f9e2af', '#a6e3a1', '#f38ba8',
'#cba6f7', '#fab387', '#94e2d5', '#f2cdcd',
];
const RESULT_COLOR = '#ffffff';
const outputDiv = document.getElementById('output');
const input = document.getElementById('userInput');
const varsDisplay = document.getElementById('varsDisplay');
const pmBtn = document.getElementById('pmBtn');
const chartCanvas = document.getElementById('chartCanvas');
const chartLegend = document.getElementById('chartLegend');
const noChart = document.getElementById('noChart');
const ctx = chartCanvas.getContext('2d');
const langBtn = document.getElementById('langBtn');
const history = [];
let historyIndex = -1;
function updateLang() {
document.getElementById('pageTitle').textContent = t('title');
document.getElementById('helpIntro').innerHTML = t('helpIntro');
document.getElementById('helpSyntax').innerHTML = t('helpSyntax');
document.getElementById('helpKeyboard').innerHTML = t('helpKeyboard');
document.getElementById('githubLink').textContent = t('githubLink');
document.getElementById('startMsg').textContent = t('startMsg');
document.getElementById('varsTitle').textContent = t('variables');
document.getElementById('distTitle').textContent = t('distributions');
const noVarsEl = document.getElementById('noVarsMsg');
if (noVarsEl) noVarsEl.textContent = t('noVars');
noChart.textContent = t('noChart');
pmBtn.title = t('insertPm');
langBtn.textContent = t('langBtn');
document.title = t('title');
updateVarsDisplay();
}
langBtn.addEventListener('click', function() {
currentLang = currentLang === 'fr' ? 'en' : 'fr';
updateLang();
});
// Insert ± at cursor position
pmBtn.addEventListener('click', function() {
const pos = input.selectionStart;
const val = input.value;
input.value = val.slice(0, pos) + '±' + val.slice(pos);
input.focus();
input.selectionStart = input.selectionEnd = pos + 1;
});
function addLine(text, cls) {
const div = document.createElement('div');
div.className = 'line ' + cls;
div.textContent = text;
outputDiv.appendChild(div);
outputDiv.scrollTop = outputDiv.scrollHeight;
}
function addInputLine(text) {
const div = document.createElement('div');
div.className = 'line input-line';
div.innerHTML = '<span class="prompt">:></span> ' + escapeHtml(text);
outputDiv.appendChild(div);
}
function escapeHtml(s) {
return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
}
function updateVarsDisplay() {
const fmt = Expression.globalVariables.format || 3;
const lines = [];
for (const [k, v] of Object.entries(Expression.globalVariables)) {
if (['pi', '\u03C0', 'e', 'format'].includes(k)) continue;
let valStr;
if (v instanceof Expression) {
// := definition
const mean = v.evaluateScalar();
const mc = v.evaluate(10000);
const std = isArray(mc) ? arrayStd(mc) : 0;
valStr = std > 0
? `<span class="var-val">${mean.toFixed(fmt)} \u00B1 ${std.toFixed(fmt)}</span> <span style="color:#6c7086">(:= ${v.expression})</span>`
: `<span class="var-val">${mean.toFixed(fmt)}</span>`;
} else if (isArray(v)) {
const mean = arrayMean(v);
const std = arrayStd(v);
valStr = std > 0
? `<span class="var-val">${mean.toFixed(fmt)} \u00B1 ${std.toFixed(fmt)}</span>`
: `<span class="var-val">${mean.toFixed(fmt)}</span>`;
} else {
valStr = `<span class="var-val">${formatNumber(v)}</span>`;
}
lines.push(`<div class="var-entry"><span class="var-name">${k}</span> = ${valStr}</div>`);
}
for (const [k, v] of Object.entries(Expression.functions)) {
if (['cos','sin','tan','acos','asin','atan','sqrt','exp','ln','log','log10','log2','abs','round'].includes(k)) continue;
if (v instanceof Expression) {
lines.push(`<div class="var-entry"><span class="var-name">${k}()</span> <span style="color:#6c7086">:= ${v.expression}</span></div>`);
}
}
varsDisplay.innerHTML = lines.length > 0
? lines.join('')
: '<div class="no-vars">' + t('noVars') + '</div>';
}
function formatNumber(v) {
if (typeof v !== 'number') return String(v);
const fmt = Expression.globalVariables.format || 3;
return v.toFixed(fmt);
}
function processInput(text) {
text = text.trim();
text = text.replace(/\+\-/g, '±').replace(/pm/g, '±');
return text;
}
// --- Chart drawing ---
function gaussian(x, mean, std) {
const z = (x - mean) / std;
return Math.exp(-0.5 * z * z);
}
function getVarDistribution(name) {
const v = Expression.globalVariables[name];
if (v === undefined) return null;
if (v instanceof Expression) {
const result = v.evaluate(N_EVAL);
if (isArray(result)) {
return { mean: arrayMean(result), std: arrayStd(result), rawData: null };
}
return null;
}
if (isArray(v)) {
const std = arrayStd(v);
if (std > 0) {
// Small arrays (user-entered data): include raw data for histogram
const rawData = v.length <= 10000 ? Array.from(v) : null;
return { mean: arrayMean(v), std: std, rawData: rawData };
}
return null;
}
return null;
}
function extractVariableNames(expr) {
const names = [];
const builtins = new Set(['pi', '\u03C0', 'e', 'format']);
for (const token of expr.expressionTokens) {
if (token.type === TokenType.VAR && !builtins.has(token.text)) {
if (!names.includes(token.text)) names.push(token.text);
}
}
return names;
}
function drawDistributions(distributions) {
const W = chartCanvas.width;
const H = chartCanvas.height;
const pad = { top: 10, bottom: 30, left: 10, right: 10 };
const plotW = W - pad.left - pad.right;
const plotH = H - pad.top - pad.bottom;
ctx.clearRect(0, 0, W, H);
if (distributions.length === 0) {
noChart.style.display = '';
chartLegend.innerHTML = '';
return;
}
noChart.style.display = 'none';
// Compute global x range: cover all distributions to +-3.5 sigma
let xMin = Infinity, xMax = -Infinity;
for (const d of distributions) {
xMin = Math.min(xMin, d.mean - 3.5 * d.std);
xMax = Math.max(xMax, d.mean + 3.5 * d.std);
}
// Small padding
const xPad = (xMax - xMin) * 0.05;
xMin -= xPad;
xMax += xPad;
// Compute max Y across all distributions for normalization
let yMax = 0;
for (const d of distributions) {
yMax = Math.max(yMax, gaussian(d.mean, d.mean, d.std));
}
function toCanvasX(x) { return pad.left + (x - xMin) / (xMax - xMin) * plotW; }
function toCanvasY(y) { return pad.top + plotH - (y / yMax) * plotH; }
// Draw axis line
ctx.strokeStyle = '#45475a';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(pad.left, pad.top + plotH);
ctx.lineTo(pad.left + plotW, pad.top + plotH);
ctx.stroke();
// Draw tick marks
ctx.fillStyle = '#6c7086';
ctx.font = '10px Menlo, monospace';
ctx.textAlign = 'center';
const nTicks = 5;
for (let i = 0; i <= nTicks; i++) {
const xVal = xMin + (xMax - xMin) * i / nTicks;
const cx = toCanvasX(xVal);
ctx.beginPath();
ctx.moveTo(cx, pad.top + plotH);
ctx.lineTo(cx, pad.top + plotH + 4);
ctx.stroke();
ctx.fillText(xVal.toPrecision(3), cx, pad.top + plotH + 16);
}
// Draw each distribution
const nPoints = 200;
for (let di = 0; di < distributions.length; di++) {
const d = distributions[di];
// Draw histogram if hist() was called
if (d.histData && isArray(d.histData)) {
const data = d.histData;
const nBins = 50;
const binWidth = (xMax - xMin) / nBins;
const bins = new Array(nBins).fill(0);
for (let i = 0; i < data.length; i++) {
const idx = Math.min(nBins - 1, Math.max(0, Math.floor((data[i] - xMin) / binWidth)));
bins[idx]++;
}
// Normalize: bin density = count / (total * binWidth)
const gaussPeak = gaussian(d.mean, d.mean, d.std);
const maxDensity = Math.max(...bins) / (data.length * binWidth);
const scale = maxDensity > 0 ? gaussPeak / maxDensity : 1;
ctx.fillStyle = d.color + '35';
ctx.strokeStyle = d.color + '60';
ctx.lineWidth = 1;
for (let i = 0; i < nBins; i++) {
if (bins[i] === 0) continue;
const bx = xMin + i * binWidth;
const density = bins[i] / (data.length * binWidth) * scale;
const cx1 = toCanvasX(bx);
const cx2 = toCanvasX(bx + binWidth);
const cy1 = toCanvasY(density);
const cy2 = toCanvasY(0);
ctx.fillRect(cx1, cy1, cx2 - cx1, cy2 - cy1);
ctx.strokeRect(cx1, cy1, cx2 - cx1, cy2 - cy1);
}
}
// Draw gaussian curve
ctx.strokeStyle = d.color;
ctx.lineWidth = 2;
ctx.beginPath();
for (let i = 0; i <= nPoints; i++) {
const x = xMin + (xMax - xMin) * i / nPoints;
const y = gaussian(x, d.mean, d.std);
const cx = toCanvasX(x);
const cy = toCanvasY(y);
if (i === 0) ctx.moveTo(cx, cy);
else ctx.lineTo(cx, cy);
}
ctx.stroke();
// Fill under curve with transparency
ctx.fillStyle = d.color + '15';
ctx.lineTo(toCanvasX(xMax), toCanvasY(0));
ctx.lineTo(toCanvasX(xMin), toCanvasY(0));
ctx.closePath();
ctx.fill();
// Vertical line at mean
const meanX = toCanvasX(d.mean);
const peakY = toCanvasY(gaussian(d.mean, d.mean, d.std));
ctx.strokeStyle = d.color;
ctx.lineWidth = 1;
ctx.setLineDash([4, 3]);
ctx.beginPath();
ctx.moveTo(meanX, peakY);
ctx.lineTo(meanX, toCanvasY(0));
ctx.stroke();
ctx.setLineDash([]);
// Mean label
ctx.fillStyle = d.color;
ctx.font = '9px Menlo, monospace';
ctx.textAlign = 'center';
ctx.fillText(d.mean.toFixed(2), meanX, peakY - 4);
// Horizontal line for std (at half height)
const halfY = toCanvasY(gaussian(d.mean, d.mean, d.std) * 0.5);
const stdLeft = toCanvasX(d.mean - d.std);
const stdRight = toCanvasX(d.mean + d.std);
ctx.strokeStyle = d.color;
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(stdLeft, halfY);
ctx.lineTo(stdRight, halfY);
// Arrow heads
ctx.moveTo(stdLeft, halfY - 3);
ctx.lineTo(stdLeft, halfY + 3);
ctx.moveTo(stdRight, halfY - 3);
ctx.lineTo(stdRight, halfY + 3);
ctx.stroke();
// Std label
ctx.fillText('\u00B1' + d.std.toFixed(2), toCanvasX(d.mean), halfY - 4);
}
// Legend
chartLegend.innerHTML = distributions.map(d =>
`<span class="legend-item"><span class="legend-dot" style="background:${d.color}"></span>${d.label} (${d.mean.toFixed(2)} \u00B1 ${d.std.toFixed(2)})</span>`
).join('');
}
function updateChart(expr, resultMean, resultStd, histData) {
const distributions = [];
let colorIdx = 0;
// Collect input variable distributions
const varNames = extractVariableNames(expr);
for (const name of varNames) {
const d = getVarDistribution(name);
if (d && d.std > 0) {
distributions.push({
label: name,
mean: d.mean,
std: d.std,
color: COLORS[colorIdx % COLORS.length],
rawData: d.rawData || null,
});
colorIdx++;
}
}
// Add result distribution
if (resultStd > 0) {
distributions.push({
label: t('result'),
mean: resultMean,
std: resultStd,
color: RESULT_COLOR,
histData: histData,
});
}
drawDistributions(distributions);
}
// --- REPL ---
function evaluate(text) {
text = processInput(text);
if (text === '') return;
if (text === 'clear') {
Expression.resetGlobalVariables();
outputDiv.innerHTML = '';
updateVarsDisplay();
drawDistributions([]);
return;
}
if (text === 'reset') {
Expression.resetGlobalVariables();
addLine(t('varsReset'), 'info-line');
updateVarsDisplay();
drawDistributions([]);
return;
}
// lang command
if (text === 'en' || text === 'fr') {
currentLang = text;
updateLang();
addInputLine(text);
return;
}
// help command
if (text === 'help' || text === '?') {
addInputLine(text);
const builtins = Object.keys(Expression.functions).filter(k =>
!((Expression.functions[k]) instanceof Expression));
addLine(t('helpFunctions') + ': ' + builtins.join(', ') + ', random(m,s), hist(x)', 'info-line');
addLine(t('helpConstants'), 'info-line');
addLine(t('helpAssign'), 'info-line');
addLine(t('helpDefine'), 'info-line');
addLine(t('helpFunc'), 'info-line');
addLine(t('helpData'), 'info-line');
addLine(t('helpShortcuts'), 'info-line');
addLine(t('helpCommands'), 'info-line');
return;
}
// samples=xxx command
const nMatch = text.match(/^samples\s*=\s*(\d+)$/);
if (nMatch) {
N_EVAL = parseInt(nMatch[1]);
Expression.defaultN = N_EVAL;
addInputLine(text);
addLine(t('mcSamples') + ': ' + N_EVAL, 'info-line');
updateVarsDisplay();
return;
}
// decimal=N command
const decMatch = text.match(/^decimal\s*=\s*(\d+)$/);
if (decMatch) {
Expression.globalVariables.format = parseInt(decMatch[1]);
addInputLine(text);
addLine(t('decimals') + ': ' + decMatch[1], 'info-line');
updateVarsDisplay();
return;
}
addInputLine(text);
try {
const m = new Expression(text);
const fmt = Expression.globalVariables.format || 3;
// Function/variable definitions: don't evaluate
const lv = m.lvalue;
if (lv !== null && lv.type === TokenType.LFUNCTION) {
addLine(lv.text + '() ' + t('defined') + '.', 'info-line');
updateVarsDisplay();
return;
}
// Compute exact mean (no Monte Carlo)
const mean = m.evaluateScalar();
// Compute uncertainty via Monte Carlo
const mcResult = m.evaluate(N_EVAL);
const std = (mcResult instanceof Float64Array || Array.isArray(mcResult))
? arrayStd(mcResult) : 0;
if (std > 0) {
addLine(mean.toFixed(fmt) + ' \u00B1 ' + std.toFixed(fmt), 'result-line');
} else {
addLine(formatNumber(mean), 'result-line');
}
updateChart(m, mean, std, m._showHist ? mcResult : null);
} catch (err) {
Expression.evalStack.length = 0;
addLine(err.message, 'error-line');
}
updateVarsDisplay();
}
input.addEventListener('keydown', function(event) {
if (event.key === 'Enter') {
const text = input.value;
if (text.trim() !== '') {
history.push(text);
historyIndex = history.length;
}
evaluate(text);
input.value = '';
} else if (event.key === 'ArrowUp') {
event.preventDefault();
if (historyIndex > 0) {
historyIndex--;
input.value = history[historyIndex];
}
} else if (event.key === 'ArrowDown') {
event.preventDefault();
if (historyIndex < history.length - 1) {
historyIndex++;
input.value = history[historyIndex];
} else {
historyIndex = history.length;
input.value = '';
}
}
});
// Init language and run example on load
updateLang();
window.addEventListener('load', function() {
evaluate('a := 10+-2');
evaluate('b := 20+-1');
evaluate('a + b');
evaluate('c = [14.2, 15.1, 14.8, 15.5, 14.9, 15.3, 14.7, 15.0, 15.4, 14.6]');
evaluate('hist(a + c)');
evaluate('sin(a*b)/sqrt(c)');
});
</script>
</body>
</html>