-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
412 lines (345 loc) · 12.8 KB
/
script.js
File metadata and controls
412 lines (345 loc) · 12.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
function draw(N, perc) {
var canvas = document.getElementById('animation');
var ctx = canvas.getContext('2d');
var canvasSize = canvas.width;
var siteSize = canvasSize / N;
// DEBUG: Check for CSS filters affecting canvas
console.log('Canvas computed styles:', {
backdropFilter: window.getComputedStyle(canvas).backdropFilter,
filter: window.getComputedStyle(canvas).filter,
opacity: window.getComputedStyle(canvas).opacity
});
// DEBUG: Check parent container effects
var canvasWrapper = canvas.parentElement;
console.log('Canvas wrapper styles:', {
backdropFilter: window.getComputedStyle(canvasWrapper).backdropFilter,
filter: window.getComputedStyle(canvasWrapper).filter
});
function loc(coordinate) {
return (coordinate - 1) * siteSize;
}
// --- FINAL CORRECTED DRAWING LOGIC ---
this.drawGrid = function () {
// DEBUG: Log canvas rendering context
console.log('Canvas context settings:', {
fillStyle: ctx.fillStyle,
globalAlpha: ctx.globalAlpha,
globalCompositeOperation: ctx.globalCompositeOperation,
filter: ctx.filter
});
// 1. Clear the canvas for a fresh start.
ctx.clearRect(0, 0, canvasSize, canvasSize);
// 2. FIX: Use a solid, OPAQUE black background to block the backdrop-filter effect.
ctx.fillStyle = "black";
ctx.fillRect(0, 0, canvasSize, canvasSize);
// 3. Draw all the cells.
for (var row = 1; row < N + 1; row++) {
for (var col = 1; col < N + 1; col++) {
var x = loc(col);
var y = loc(row);
if (perc.isFull(row, col)) {
// User's requested color for full sites
ctx.fillStyle = "rgba(0, 69, 99, 0.8)";
} else if (perc.isOpen(row, col)) {
// More visible white for open sites
ctx.fillStyle = "rgba(255, 255, 255, 1)";
} else {
// FIX: Use the same solid black color for blocked sites
ctx.fillStyle = "black";
}
ctx.fillRect(x, y, siteSize, siteSize);
}
}
// 4. Draw the grid lines ON TOP of the cells.
ctx.strokeStyle = "rgba(255, 255, 255, 0.1)";
ctx.lineWidth = 0.5;
for (var i = 0; i <= N; i++) {
var pos = i * siteSize;
ctx.beginPath();
ctx.moveTo(pos, 0);
ctx.lineTo(pos, canvasSize);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(0, pos);
ctx.lineTo(canvasSize, pos);
ctx.stroke();
}
}
// --- END OF FINAL CORRECTED LOGIC ---
}
var currentPerc, currentDrawPerc, currentN, currentCount = 0, isPaused = false, isRunning = false;
var lastThresholds = [];
function simulatePercolation() {
if (isRunning) return;
clearInterval(interval);
resetSimulationState();
var N = +document.getElementById("gridSize").value;
var radios = document.getElementsByName('speed');
var delay = 50;
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
if (radios[i].value == "instant") { delay = 0; }
else if (radios[i].value == "fast") { delay = 5; }
else if (radios[i].value == "slow") { delay = 100; }
break;
}
}
currentN = N;
currentPerc = new Percolation(N);
currentDrawPerc = new draw(N, currentPerc);
// Draw the initial empty grid state
currentDrawPerc.drawGrid();
currentCount = 0;
isRunning = true;
isPaused = false;
document.getElementById("runBtn").disabled = true;
document.getElementById("pauseBtn").disabled = false;
document.getElementById("pauseBtn").textContent = "Pause";
document.getElementById("resetBtn").disabled = false;
function openRandom() {
var i = Math.floor(Math.random() * N + 1);
var j = Math.floor(Math.random() * N + 1);
if (currentPerc.isOpen(i, j)) {
openRandom();
} else {
currentPerc.open(i, j);
return;
}
}
function checkPerc() {
if (isPaused) return;
if (!currentPerc.percolates()) {
openRandom();
currentCount++;
// Redraw the entire grid with the new state
currentDrawPerc.drawGrid();
updateStats();
} else {
clearInterval(interval);
finishSimulation();
}
}
function outputInstantly() {
while (!currentPerc.percolates()) {
openRandom();
currentCount++;
}
// The final draw will now be perfectly clean
currentDrawPerc.drawGrid();
updateStats();
finishSimulation();
}
if (delay === 0) {
outputInstantly();
} else {
interval = setInterval(checkPerc, delay);
}
}
function togglePause() {
if (!isRunning) return;
isPaused = !isPaused;
document.getElementById("pauseBtn").textContent = isPaused ? "Resume" : "Pause";
}
function resetSimulation() {
clearInterval(interval);
resetSimulationState();
// --- MODIFIED: Reset the canvas to a clean empty grid ---
var N = +document.getElementById("gridSize").value;
// We need a Percolation object for the draw function to check states (even if empty)
var tempPerc = new Percolation(N);
var tempDraw = new draw(N, tempPerc);
tempDraw.drawGrid();
document.getElementById("simulation-result").innerHTML = "";
document.getElementById("simulation-result").style.display = "none";
document.getElementById("currentPercent").textContent = "Sites opened: 0% (0/0)";
document.getElementById("runBtn").disabled = false;
document.getElementById("pauseBtn").disabled = true;
document.getElementById("resetBtn").disabled = true;
}
function resetSimulationState() {
currentPerc = null;
currentDrawPerc = null;
currentN = 0;
currentCount = 0;
isRunning = false;
isPaused = false;
}
function updateStats() {
var percentage = parseFloat((currentCount * 100) / (currentN * currentN)).toFixed(1);
document.getElementById("currentPercent").textContent = `Sites opened: ${percentage}% (${currentCount}/${currentN * currentN})`;
}
function finishSimulation() {
var percentage = parseFloat((currentCount * 100) / (currentN * currentN)).toFixed(1);
var outstring = `With ${currentCount} sites opened, a spanning cluster has formed. ${percentage}% of sites are open`;
document.getElementById("simulation-result").innerHTML = outstring;
document.getElementById("simulation-result").style.display = "block";
document.getElementById("pauseBtn").disabled = true;
document.getElementById("runBtn").disabled = false;
isRunning = false;
}
function runStatistics() {
var N = +document.getElementById("gridSize").value;
var numSims = +document.getElementById("numSimulations").value;
lastThresholds = [];
document.getElementById("statsBtn").disabled = true;
document.getElementById("statsBtn").textContent = "Running...";
for (var sim = 0; sim < numSims; sim++) {
var perc = new Percolation(N);
var count = 0;
function openRandom() {
var i = Math.floor(Math.random() * N + 1);
var j = Math.floor(Math.random() * N + 1);
if (perc.isOpen(i, j)) {
openRandom();
} else {
perc.open(i, j);
return;
}
}
while (!perc.percolates()) {
openRandom();
count++;
}
var threshold = (count * 100) / (N * N);
lastThresholds.push(threshold);
}
var sum = lastThresholds.reduce((a, b) => a + b, 0);
var avg = (sum / numSims).toFixed(2);
var min = Math.min(...lastThresholds).toFixed(2);
var max = Math.max(...lastThresholds).toFixed(2);
var statsResult = `
<div class="stats-meta" style="text-align: center; margin-bottom: 20px; font-size: 16px; color: var(--text-color); opacity: 0.8;">
${numSims} simulations • Grid: ${N}×${N}
</div>
<div class="stats-grid">
<div class="stat-card">
<div class="stat-value">${avg}%</div>
<div class="stat-label">Average Threshold</div>
</div>
<div class="stat-card">
<div class="stat-value">${min}% - ${max}%</div>
<div class="stat-label">Range</div>
</div>
<div class="stat-card">
<div class="stat-value">${lastThresholds.length}</div>
<div class="stat-label">Total Samples</div>
</div>
</div>
<div class="thresholds-list">
<div class="thresholds-label">Individual Thresholds:</div>
<div class="thresholds-values">${lastThresholds.map(t => t.toFixed(2)).join('%, ')}%</div>
</div>
<div style="text-align: center; margin-top: 20px;">
<button type="button" class="btn btn-secondary" onclick="exportResults()" style="margin-right: 10px;">📊 Export Results</button>
<button type="button" class="btn btn-secondary" onclick="closeStatsModal()">Close</button>
</div>
`;
document.getElementById("stats-content").innerHTML = statsResult;
document.getElementById("stats-modal").style.display = "flex";
document.getElementById("statsBtn").disabled = false;
document.getElementById("statsBtn").textContent = "Run Statistics";
}
function closeStatsModal() {
document.getElementById("stats-modal").style.display = "none";
}
function exportResults() {
if (lastThresholds.length === 0) {
alert("No statistics data to export. Run statistics first.");
return;
}
var N = +document.getElementById("gridSize").value;
var numSims = lastThresholds.length;
var sum = lastThresholds.reduce((a, b) => a + b, 0);
var avg = (sum / numSims).toFixed(2);
var csvContent = "Simulation,Grid Size,Threshold (%)\n";
for (var i = 0; i < lastThresholds.length; i++) {
csvContent += `${i + 1},${N},${lastThresholds[i]}\n`;
}
csvContent += `Average,,${avg}\n`;
var blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
var link = document.createElement("a");
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", `percolation_stats_${N}x${N}_${numSims}_simulations.csv`);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
function Percolation(N) {
var size = N;
var uf = new WeightedQuickUnionUF(N * N + 2);
var topUF = new WeightedQuickUnionUF(N * N + 2);
var opened = [];
for (var i = 0; i < N * N; i++) {
opened[i] = false;
}
function xyTo1D(i, j) {
return size * (i - 1) + j;
}
this.open = function (i, j) {
opened[xyTo1D(i, j)] = true;
if (i != 1 && this.isOpen(i - 1, j)) {
uf.union(xyTo1D(i, j), xyTo1D(i - 1, j));
topUF.union(xyTo1D(i, j), xyTo1D(i - 1, j));
}
if (i != size && this.isOpen(i + 1, j)) {
uf.union(xyTo1D(i, j), xyTo1D(i + 1, j));
topUF.union(xyTo1D(i, j), xyTo1D(i + 1, j));
}
if (j != 1 && this.isOpen(i, j - 1)) {
uf.union(xyTo1D(i, j), xyTo1D(i, j - 1));
topUF.union(xyTo1D(i, j), xyTo1D(i, j - 1));
}
if (j != size && this.isOpen(i, j + 1)) {
uf.union(xyTo1D(i, j), xyTo1D(i, j + 1));
topUF.union(xyTo1D(i, j), xyTo1D(i, j + 1));
}
if (i == 1) {
uf.union(0, xyTo1D(i, j));
topUF.union(0, xyTo1D(i, j));
}
if (i == size) {
uf.union(size * size + 1, xyTo1D(i, j));
}
}
this.isOpen = function (i, j) {
return opened[xyTo1D(i, j)];
}
this.isFull = function (i, j) {
return topUF.connected(0, xyTo1D(i, j));
}
this.percolates = function () {
return uf.connected(0, size * size + 1);
}
}
function WeightedQuickUnionUF(N) {
var parent = [];
var size = [];
for (var i = 0; i < N; i++) {
parent[i] = i;
size[i] = 1;
}
function root(i) {
while (i != parent[i]) {
parent[i] = parent[parent[i]];
i = parent[i];
}
return i;
}
this.union = function (p, q) {
var i = root(p);
var j = root(q);
if (i == j) return;
if (size[i] < size[j]) {
parent[i] = j;
size[j] += size[i];
} else {
parent[j] = i;
size[i] += size[j];
}
}
this.connected = function (p, q) {
return root(p) == root(q);
}
}