-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
699 lines (600 loc) · 20.8 KB
/
script.js
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
// const { calculateAssemblyIndex} = require('./assembley.js');
const lof_policy = {
lof_weights: [1, 1, 1, 1, 0]
};
const sliders = document.querySelectorAll('.slider');
const percents = [
document.getElementById('percent1'),
document.getElementById('percent2'),
document.getElementById('percent3'),
document.getElementById('percent4'),
document.getElementById('percent5'),
];
sliders.forEach((slider, index) => {
slider.addEventListener('input', () => {
lof_policy.lof_weights[index] = parseInt(slider.value);
updatePercentages();
});
});
function updatePercentages() {
const total = lof_policy.lof_weights.reduce((acc, val) => acc + val, 0);
lof_policy.lof_weights.forEach((value, index) => {
const percent = total > 0 ? (value / total * 100).toFixed(1) : 0;
percents[index].textContent = `${percent}%`;
});
}
// Initialize percentages
updatePercentages();
function formCount(structure) {
function countSubarrays(arr) {
if (!Array.isArray(arr)) {
return 0;
}
let count = 1; // count the current array
for (let item of arr) {
count += countSubarrays(item);
}
return count;
}
return countSubarrays(structure);
}
function calculateAssemblyIndex(structure) {
// Helper function to determine the type of structure
function getType(array) {
if (array.length === 0) {
return 'A'; // Empty array
}
if (array.length === 1 && Array.isArray(array[0])) {
return 'C'; // Single nested array
}
if (array.length === 2 && JSON.stringify(array[0]) === JSON.stringify(array[1])) {
return 'D'; // Two identical nested arrays
}
return null; // Unrecognized structure
}
// Recursive function to calculate the assembly index
function assemblySteps(array) {
const type = getType(array);
if (type === 'A') {
return 1; // Rule 1: [A] = [A],[A]
}
if (type === 'C') {
return assemblySteps(array[0]) + 1; // Rule 3: [[C]] = C
}
if (type === 'D') {
return assemblySteps(array[0]) + 1; // Rule 4: [B],[B] = [D]
}
if (Array.isArray(array) && array.length === 2 && array[0].length === 0 && array[1].length === 0) {
return 2; // Special case for two empty arrays
}
// Calculate for more complex or unrecognized structures
let steps = 0;
for (const item of array) {
if (Array.isArray(item)) {
steps += assemblySteps(item);
}
}
return steps;
}
// Start calculation
return assemblySteps(structure);
}
let step = 0;
let counter = [0,0,0,0];
let selectedPoints = [];
// Operation functions
function air(structure) {
counter[0]+=1;
return LoFCancel(structure);
}
function fire(structure) {
counter[1]+=1;
return LoFConfirm(structure);
}
function water(structure) {
counter[2]+=1;
return LoFCondense(structure);
}
function earth(structure) {
counter[3]+=1;
return LofCompensate(structure);
}
// Function to get a random path in the structure
function getRandomPath(structure, path = []) {
if (structure.length === 0 || Math.random() < 0.75) {
return path;
}
const randomIndex = Math.floor(Math.random() * structure.length);
return getRandomPath(structure[randomIndex], [...path, randomIndex]);
}
// Timer for triggering operations
let timer = null;
function calculateOmega(nestedArray) {
function countArrays(structure) {
if (!Array.isArray(structure)) {
return 0;
}
let count = 1; // count the current array
for (let item of structure) {
count += countArrays(item);
}
return count;
}
function findDuplicates(structure) {
if (!Array.isArray(structure) || structure.length === 0) {
return 0;
}
const siblingCounts = new Map();
for (let item of structure) {
const itemStr = JSON.stringify(item);
if (siblingCounts.has(itemStr)) {
siblingCounts.set(itemStr, siblingCounts.get(itemStr) + 1);
} else {
siblingCounts.set(itemStr, 1);
}
}
let duplicates = 0;
for (let count of siblingCounts.values()) {
if (count > 1) {
duplicates += count - 1;
}
}
let subtreeDuplicates = 0;
for (let item of structure) {
subtreeDuplicates += findDuplicates(item);
}
return duplicates + subtreeDuplicates;
}
function omega(structure) {
if (!Array.isArray(structure)) {
return 0;
}
const nArrayCount = countArrays(structure);
const duplicateCount = findDuplicates(structure);
let omegaValue = nArrayCount * 3 + duplicateCount;
for (let item of structure) {
omegaValue += omega(item);
}
return omegaValue;
}
return omega(nestedArray);
}
// // Example usage
// const nestedStructure = [[], [[], []], [[], [[]]]];
// const omegaValue = calculateOmega(nestedStructure);
// console.log("Omega value:", omegaValue);
function calculateEntropy(structure) {
let depthCounts = {};
function countDepths(structure, currentDepth = 0) {
if (!Array.isArray(structure)) return;
depthCounts[currentDepth] = (depthCounts[currentDepth] || 0) + 1;
structure.forEach(subStructure => countDepths(subStructure, currentDepth + 1));
}
countDepths(structure);
let entropy = 0;
let total = Object.values(depthCounts).reduce((sum, count) => sum + count, 0);
Object.values(depthCounts).forEach(count => {
let probability = count / total;
entropy -= probability * Math.log2(probability);
});
return entropy;
}
function calculateMaxDepth(structure, currentDepth = 0) {
if (!Array.isArray(structure) || structure.length === 0) return currentDepth;
return Math.max(...structure.map(sub => calculateMaxDepth(sub, currentDepth + 1)));
}
// Update step counter display
function updateStepCounter() {
document.getElementById('stepCounter').textContent = `Steps: ${step}`;
}
// Update step counter display
function updateRealtimeMetrics() {
document.getElementById('metric-avg-depth').textContent = `Avg Depth: ${metrics_rt[0].avg.toFixed(2)} ± ${metrics_rt[0].std.toFixed(2)}`;
document.getElementById('metric-avg-entropy').textContent = `Avg Entropy: ${metrics_rt[1].avg.toFixed(2)} ± ${metrics_rt[1].std.toFixed(2)}`;
}
// Update frequency display when slider value changes
document.getElementById('frequencySlider').addEventListener('input', function() {
document.getElementById('frequencyDisplay').textContent = this.value + ' Hz';
});
let steps = 0;
// Clear button functionality
document.getElementById('clearButton').addEventListener('click', () => {
// reset all important and relevant variables
structure = [[]];
redrawCanvas();
chart.data.datasets[0].data = []; chart.update();
step=0;
});
// Play button functionality
document.getElementById('playButton').addEventListener('click', () => {
if (timer) {
clearInterval(timer);
timer = null;
} else {
const frequency = document.getElementById('frequencySlider').value;
timer = setInterval(() => {
const lof = [LoFCancel, LofCompensate, LoFCondense, LoFConfirm, LoFMeasure]
const execution_distribution = lof_policy.lof_weights; // [3, 1, 3, 3]
// Create an array to hold the weighted functions
let weightedFunctions = [];
// Populate the weightedFunctions array based on the execution_distribution
for (let i = 0; i < execution_distribution.length; i++) {
for (let j = 0; j < execution_distribution[i]; j++) {
weightedFunctions.push(i);
}
}
// Function to randomly select and execute a function based on the distribution
function executeRandomFunction() {
const randomIndex = Math.floor(Math.random() * weightedFunctions.length);
structure = lof[weightedFunctions[randomIndex]](structure);
updateMetrics(lof[weightedFunctions[randomIndex]]);
}
executeRandomFunction();
redrawCanvas();
}, 1000 / frequency);
}
});
// Operation functions
// function air(structure) {
// const randomPath = getRandomPath(structure);
// addChild(randomPath);
// counter[0]+=1;
// }
// function fire(structure) {
// // console.log("fire")
// duplicateRandomForm(structure);
// counter[1]+=1;
// }
// function water(structure) {
// // console.log("water")
// concatenateRandomForms(structure);
// counter[2]+=1;
// }
// function earth(structure) {
// // console.log("earth")
// deleteRandomPrunableArray(structure);
// counter[3]+=1;
// }
function drawRoundedRect(ctx, x, y, width, height, radius) {
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width, y);
ctx.lineTo(x + width, y + height);
// ctx.arcTo(x + width, y + height, x, y + height, radius);
// ctx.arcTo(x, y + height, x, y, radius);
// ctx.arcTo(x, y, x + width, y, radius);
// ctx.closePath();
ctx.strokeStyle = '#FFFFFF'
ctx.stroke();
}
function drawSquares(ctx, x, y, size, structure, path = [], highlightPath = null) {
if (structure.length === 0) {
return;
}
const padding = size * 0.1; // 10% padding
const netSize = size - 2 * padding; // Adjust size for padding
let rowSize = Math.ceil(Math.sqrt(structure.length));
let gap = netSize * 0.05; // Gap between squares, 5% of net size
let squareSize = (netSize - gap * (rowSize - 1)) / rowSize;
structure.forEach((subStructure, index) => {
let col = index % rowSize;
let row = Math.floor(index / rowSize);
let newX = x + padding + (squareSize + gap) * col;
let newY = y + padding + (squareSize + gap) * row;
let currentPath = [...path, index];
// Store path information for click event
squarePaths.push({ path: currentPath, x: newX, y: newY, size: squareSize, depth: currentPath.length });
// Highlight the clicked square
if (highlightPath && JSON.stringify(highlightPath) === JSON.stringify(currentPath)) {
ctx.fillStyle = 'rgba(255, 165, 0, 0.2)'; // Orange highlight
// ctx.fillRect(newX, newY, squareSize, squareSize);
drawRoundedRect(ctx, newX, newY, squareSize, squareSize, squareSize * 0.1); // 10% for rounded corner
ctx.fill();
}
ctx.beginPath();
drawRoundedRect(ctx, newX, newY, squareSize, squareSize, squareSize * 0.1); // 10% for rounded corner
ctx.stroke();
if (subStructure.length > 0) {
drawSquares(ctx, newX, newY, squareSize, subStructure, currentPath, highlightPath);
}
});
}
function onCanvasClick(e) {
const addMode = document.getElementById('addMode').value;
const rect = canvas.getBoundingClientRect();
const mouseX = e.clientX - rect.left;
const mouseY = e.clientY - rect.top;
let clicked = false;
squarePaths.sort((a, b) => b.depth - a.depth);
for (let squarePath of squarePaths) {
let { path, x, y, size } = squarePath;
if (mouseX >= x && mouseX <= x + size && mouseY >= y && mouseY <= y + size) {
if (addMode === 'child') {
addChild(path);
} else {
addSibling(path);
}
clicked = true;
redrawCanvas(path);
break;
}
}
// If no square is clicked, treat it as a click on the outer container
if (!clicked) {
if (addMode === 'child') {
addChild([]); // Add child to the root
} else {
structure = [[...structure], []]
}
redrawCanvas();
}
}
function addChild(path) {
let target = structure;
// console.log("path", path);
for (let i = 0; i < path.length; i++) {
if (!target[path[i]]) {
// Initialize an empty array if the target is undefined
target[path[i]] = [];
}
target = target[path[i]];
// console.log("target", target)
}
target.push([[]]);
}
function addSibling(path, moment) {
if (moment=='now') {
structure=[[...structure], []]
return;
}
if (path.length === 0) {
structure.push([]);
return;
}
let parentPath = path.slice(0, -1);
let siblingIndex = path[path.length - 1] + 1;
let parent = structure;
parentPath.forEach(p => {
if (!parent[p]) {
parent[p] = [];
}
parent = parent[p];
});
parent.splice(siblingIndex, 0, []);
}
function redrawCanvas(highlightPath = null) {
setCanvasSize(ctx.canvas);
ctx.clearRect(0, 0, canvas.width, canvas.height);
squarePaths = [];
drawSquares(ctx, 10, 10, canvas.width*0.98, structure, [], highlightPath);
}
const calculateAverages = () => {
let sum_1 = 0;
let sum_1_pow2 = 0;
let sum_2 = 0;
let sum_2_pow2 = 0;
// mean = sum (values) / N
// std = sum (values^2) / N - mean^2
for (let i=0;i<metrics.length;i++) {
const { step, entropy, maxDepth } = metrics[i];
sum_1+= entropy;
sum_1_pow2+= Math.pow(maxDepth,2);
sum_2+= maxDepth;
sum_2_pow2+= Math.pow(maxDepth,2);
}
metrics_rt[0].avg = sum_1 / metrics.length;
metrics_rt[0].std = sum_1_pow2 / metrics.length - Math.pow(metrics_rt[0].avg,2);
metrics_rt[1].avg = sum_2 / metrics.length;
metrics_rt[1].std = sum_2_pow2 / metrics.length - Math.pow(metrics_rt[1].avg,2);
}
const update_chart_data = async (chart) => {
chart.data.datasets[0].data.push({x: metrics[metrics.length-1].entropy, y: metrics[metrics.length-1].assembley});
}
function updateMetrics(element) {
const entropy = calculateEntropy(structure);
const maxDepth = calculateMaxDepth(structure);
const assembley = calculateAssemblyIndex(structure);
const omega = calculateOmega(structure);
const order = formCount(structure);
metrics.push({ step, element, entropy, maxDepth, assembley, omega, order});
// if (step % 20 == 0){
// chart.data.labels.push(step);
// chart.data.datasets[0].data.push(entropy);
// chart.data.datasets[1].data.push(maxDepth);
// chart.data.datasets[2].data.push(assembley);
// chart.data.datasets[3].data.push(omega);
// chart.data.datasets[4].data.push(order);
// chart.update();
// }
update_chart_data(chart)
if (step % 100 == 0){
chart.update();
}
step++; // Increment step counter
updateStepCounter();
if (step % 100 == 0){
calculateAverages();
updateRealtimeMetrics();
}
}
let structure = [[]]; // array to store LoF Structure
let metrics = []; // Array to store metrics
let metrics_rt = [
// depth
{
avg: 0,
std: 0,
},
// entropy
{
avg: 0,
std: 0,
}
];
let squarePaths = [];
// INIT CANVAS
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
canvas.addEventListener('click', onCanvasClick);
redrawCanvas();
// INIT CHART
let chart = null;
function initializeChartScatter() {
const ctx = document.getElementById('myChart').getContext('2d');
chart = new Chart(ctx, {
type: 'scatter',
data: {
datasets: [{
label: 'Entropy vs Assembly',
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgba(54, 162, 235, 1)',
data: [], // Initialize with empty data array
fill: false,
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
x: {
type: 'linear',
position: 'bottom',
title: {
display: true,
text: 'Entropy'
}
},
y: {
type: 'linear', // logarithmic
position: 'left',
title: {
display: true,
text: 'Assembly',
}
}
},
},
onClick: function(evt, activeElements) {
if (activeElements.length > 0) {
const datasetIndex = activeElements[0].datasetIndex;
const index = activeElements[0].index;
const selectedData = chart.data.datasets[datasetIndex].data[index];
selectedPoints.push(selectedData);
console.log('Selected Points:', selectedPoints);
}
}
});
}
function initializeChart() {
const ctx = document.getElementById('myChart').getContext('2d');
chart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: 'Entropy',
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255, 99, 132, 1)',
yAxisID: 'yEntropy',
fill: false,
}, {
label: 'Max Depth',
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgba(54, 162, 235, 1)',
yAxisID: 'yDepth',
fill: false,
},
{
label: 'Assembley',
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgba(54, 162, 235, 1)',
yAxisID: 'Assembley Index',
fill: false,
},
{
label: 'Omega',
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgba(54, 162, 235, 1)',
yAxisID: 'Omega',
fill: false,
},
{
label: 'Order',
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgba(54, 162, 235, 1)',
yAxisID: 'Order',
fill: false,
}
],
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
x: {
type: 'linear',
position: 'bottom',
},
yEntropy: {
type: 'linear',
position: 'left',
},
yDepth: {
type: 'linear',
position: 'right',
grid: {
drawOnChartArea: false,
},
},
},
},
});
}
function setCanvasSize(canvas) {
var parent = canvas.parentNode,
styles = getComputedStyle(parent),
w = parseInt(styles.getPropertyValue("width"), 10),
h = parseInt(styles.getPropertyValue("height"), 10);
let s = Math.min(w,h);
canvas.width = s*.9;
canvas.height = s*.9;
}
// Initialize the chart when the page loads
document.addEventListener('DOMContentLoaded', initializeChartScatter); // initializeChart
document.getElementById('exportCsvButton').addEventListener('click', () => {
let csvContent = "data:text/csv;charset=utf-8,";
csvContent += "Step,Element,Entropy,Max Depth, Assembly, Omega, Order\r\n";
metrics.forEach(row => {
const rowContent = `${row.step},${row.element},${row.entropy},${row.maxDepth},${row.assembley},${row.omega},${row.order}\r\n`;
csvContent += rowContent;
});
const encodedUri = encodeURI(csvContent);
const link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "metrics.csv");
document.body.appendChild(link); // Required for FF
link.click();
document.body.removeChild(link);
});
// Handle zoom
canvas.addEventListener('wheel', (event) => {
event.preventDefault();
const mousex = event.clientX - canvas.getBoundingClientRect().left;
const mousey = event.clientY - canvas.getBoundingClientRect().top;
const wheel = event.deltaY < 0 ? 1.1 : 0.9;
const newScale = scale * wheel;
// Translate so the origin will be the mouse coordinates
originx -= mousex / scale - mousex / newScale;
originy -= mousey / scale - mousey / newScale;
// Scale the canvas
scale = newScale;
// Redraw
draw();
});
function toggleScale() {
const currentXScaleType = chart.options.scales.x.type;
const newScaleType = currentXScaleType === 'linear' ? 'logarithmic' : 'linear';
chart.options.scales.x.type = newScaleType;
chart.options.scales.y.type = newScaleType;
chart.update();
}
document.getElementById('toggleScaleButton').addEventListener('click', toggleScale);