-
Notifications
You must be signed in to change notification settings - Fork 0
/
myceliumsim.html
1347 lines (1185 loc) · 43.2 KB
/
myceliumsim.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
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
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Virtual Mycelium Simulator with Console and Recording</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
/* Styles for the simulator */
/* test */
body {
margin: 0;
background-color: #000;
color: #fff;
font-family: Arial, sans-serif;
}
.container {
display: flex;
flex-direction: row;
justify-content: center;
align-items: flex-start;
padding: 20px;
flex-wrap: wrap;
}
.sim-container {
display: flex;
flex-direction: column;
align-items: center; /* Centers the canvas and console */
}
#petriDish {
border: 2px solid rgba(255, 255, 255, 0.5);
background-color: rgba(255, 255, 255, 0.1);
max-width: 100%;
height: auto;
}
.side-panel {
margin-left: 20px;
width: 220px;
flex-shrink: 0;
}
.side-panel h2 {
border-bottom: 1px solid rgba(255, 255, 255, 0.5);
padding-bottom: 5px;
}
.side-panel select,
.side-panel button,
.side-panel input[type="range"] {
width: 100%;
margin-bottom: 10px;
padding: 5px;
background-color: #444;
border: none;
color: #fff;
border-radius: 4px;
}
.side-panel button {
cursor: pointer;
}
.side-panel button:hover,
.side-panel select:hover {
background-color: #555;
}
#resetButton {
background-color: rgba(255, 0, 0, 0.5);
}
#resetButton:hover {
background-color: rgba(255, 0, 0, 0.7);
}
/* Cursor styles based on the selected tool */
#petriDish.cursor-swab {
cursor: crosshair;
}
#petriDish.cursor-scalpel {
cursor: alias;
}
#petriDish.cursor-contamination {
cursor: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAQAAAC1+jfqAAAAO0lEQVR4AWMYBUwAYoAUsABiB4QG+YDQgVkJwTD0/98yEgsHnABASIzJrBEYYkYIbNAiYGABZ1gE0qp3haAAAAAElFTkSuQmCC'), auto;
}
/* Virtual hour display style */
#hourDisplay {
margin-top: 20px;
font-size: 18px;
text-align: center;
}
/* Slider labels */
.slider-label {
display: flex;
justify-content: space-between;
margin-bottom: 15px;
font-size: 14px;
}
/* Console for live data display */
#console {
width: 100%;
max-height: 200px;
background-color: #111;
color: #0f0;
font-family: monospace;
overflow-y: auto;
border-top: 2px solid #333;
padding: 10px;
}
/* Responsive design */
@media (max-width: 768px) {
.container {
flex-direction: column;
align-items: center;
}
.side-panel {
margin-left: 0;
width: 90%;
max-width: 400px;
}
#petriDish {
width: 90%;
height: auto;
}
}
</style>
</head>
<body>
<div class="container">
<div class="sim-container" style="display: flex; flex-direction: column; align-items: center;">
<canvas id="petriDish" width="750" height="750"></canvas>
<div id="console" style="width: 750px; height: 500px; overflow-y: auto; background-color: #333; color: #fff; padding: 10px; margin-top: 10px;">
<!-- Console output will appear here -->
</div>
</div>
<div class="side-panel">
<h2>Mushrooms</h2>
<select id="speciesSelect">
<option value="shiitake">Shiitake</option>
<option value="oyster">Oyster</option>
<option value="pinkOyster">Pink Oyster Mushroom</option>
<option value="enoki">Enoki</option>
<option value="cordyceps">Cordyceps</option>
<option value="lionsMane">Lion's Mane</option>
<option value="buttonMushroom">Button Mushroom</option>
<option value="cremini">Cremini Mushroom</option>
<option value="portobello">Portobello Mushroom</option>
<option value="maitake">Maitake Mushroom</option>
<option value="blackTrumpet">Black Trumpet Mushroom</option>
<option value="morel">Morel Mushroom</option>
</select>
<h2>Tools</h2>
<button id="sporeSwab">Spore Swab</button>
<button id="scalpel">Scalpel</button>
<button id="contaminationTool">Contamination</button>
<h2>Contaminant Type</h2>
<select id="contaminantSelect">
<option value="mold">Mold</option>
<option value="mildew">Mildew</option>
<option value="bacteria">Bacteria</option>
<option value="virus">Virus</option>
</select>
<h2>Agar Type</h2>
<select id="agarSelect">
<option value="charcoal">Charcoal Agar</option>
<option value="blood">Blood Agar</option>
<option value="dextrose">Dextrose Pine Wood Agar</option>
<option value="feces">Feces Agar</option>
<option value="maltExtract">Malt Extract Agar (MEA)</option>
<option value="fungalAgar">Fungal Agar (Mycological Agar)</option>
<option value="sabouraud">Sabouraud Dextrose Agar</option>
</select>
<h2>Time-lapse Speed</h2>
<input type="range" id="speedRange" min="1" max="10" value="5">
<label for="speedRange" class="slider-label">Speed: <span id="speedValue">5</span>x</label>
<h2>pH Level</h2>
<input type="range" id="pHRange" min="4" max="10" step="0.1" value="6.0">
<label for="pHRange" class="slider-label">pH: <span id="pHValue">6.0</span></label>
<h2>Temperature (°F)</h2>
<input type="range" id="tempRange" min="50" max="120" value="70">
<label for="tempRange" class="slider-label">Temperature: <span id="tempValue">70</span>°F</label>
<h2>Humidity (%)</h2>
<input type="range" id="humidityRange" min="40" max="100" value="70">
<label for="humidityRange" class="slider-label">Humidity: <span id="humidityValue">70</span>%</label>
<button id="resetButton">Reset Simulation</button>
<button id="saveButton">Save Simulation</button> <!-- New Save Button -->
<button id="toggleRecordButton" style="background-color: grey;">Start Recording</button>
<div id="hourDisplay">Virtual Hours: 0</div>
</div>
</div>
<div id="console"></div>
<script>
// Console log functionality
function logToConsole(message) {
const consoleDiv = document.getElementById('console');
const logEntry = document.createElement('div');
logEntry.textContent = message;
consoleDiv.appendChild(logEntry);
consoleDiv.scrollTop = consoleDiv.scrollHeight; // Auto scroll to the bottom
}
// Initialize canvas and context
const canvas = document.getElementById('petriDish');
const ctx = canvas.getContext('2d');
const width = canvas.width;
const height = canvas.height;
const dishRadius = 375;
// Function to set the canvas background color and draw the petri dish perimeter
function setCanvasBackgroundAndDrawDish() {
// Set the background color to match the desired style
ctx.fillStyle = '#1a1a1a'; // Dark grey to match the simulator dark mode
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Draw the petri dish perimeter
ctx.beginPath();
ctx.arc(canvas.width / 2, canvas.height / 2, dishRadius, 0, 2 * Math.PI);
ctx.fillStyle = 'rgba(255, 255, 255, 0.05)'; // Slightly transparent fill for dish
ctx.fill();
ctx.strokeStyle = 'rgba(255, 255, 255, 0.5)'; // White perimeter for dish boundary
ctx.lineWidth = 2;
ctx.stroke();
}
function drawPetriDishBackground() {
// Draw the petri dish background and border
ctx.fillStyle = 'rgba(255, 255, 255, 0.05)'; // Adjust as necessary for a subtle background fill
ctx.beginPath();
ctx.arc(canvas.width / 2, canvas.height / 2, dishRadius, 0, 2 * Math.PI);
ctx.fill();
ctx.strokeStyle = 'rgba(255, 255, 255, 0.5)'; // Adjust the border style as needed
ctx.lineWidth = 2;
ctx.stroke();
}
// Call once at the start
setCanvasBackgroundAndDrawDish();
// Variables for user selections
let selectedTool = 'sporeSwab';
let selectedSpecies = document.getElementById('speciesSelect').value;
let selectedContaminant = document.getElementById('contaminantSelect').value;
let agarType = document.getElementById('agarSelect').value;
// Simulation running flag
let simulationRunning = false;
// Initialize environmental variables
let speed = Number(document.getElementById('speedRange').value);
let pH = Number(document.getElementById('pHRange').value);
let temperature = Number(document.getElementById('tempRange').value);
let humidity = Number(document.getElementById('humidityRange').value);
// Display initial values
document.getElementById('speedValue').textContent = speed;
document.getElementById('pHValue').textContent = pH.toFixed(1);
document.getElementById('tempValue').textContent = temperature;
document.getElementById('humidityValue').textContent = humidity;
// Function to update the cursor based on the selected tool
function updateCursor() {
canvas.classList.remove('cursor-swab', 'cursor-scalpel', 'cursor-contamination');
if (selectedTool === 'sporeSwab') {
canvas.classList.add('cursor-swab');
} else if (selectedTool === 'scalpel') {
canvas.classList.add('cursor-scalpel');
} else if (selectedTool === 'contamination') {
canvas.classList.add('cursor-contamination');
} else {
canvas.style.cursor = 'default';
}
}
// Initialize cursor
updateCursor();
// Event listeners for tool buttons
document.getElementById('sporeSwab').addEventListener('click', () => {
selectedTool = 'sporeSwab';
updateCursor();
});
document.getElementById('scalpel').addEventListener('click', () => {
selectedTool = 'scalpel';
updateCursor();
});
document.getElementById('contaminationTool').addEventListener('click', () => {
selectedTool = 'contamination';
updateCursor();
});
// Event listeners for selections and sliders
document.getElementById('speciesSelect').addEventListener('change', (e) => {
selectedSpecies = e.target.value;
});
document.getElementById('contaminantSelect').addEventListener('change', (e) => {
selectedContaminant = e.target.value;
});
document.getElementById('agarSelect').addEventListener('change', (e) => {
agarType = e.target.value;
initializeNutrientGrid();
});
document.getElementById('speedRange').addEventListener('input', (e) => {
speed = Number(e.target.value);
document.getElementById('speedValue').textContent = speed;
// Update the simulation speed without restarting
if (simulationRunning) {
clearInterval(simulationInterval);
simulationInterval = setInterval(simulate, 1000 / (speed * 2)); // Adjust the interval for new speed
}
});
document.getElementById('pHRange').addEventListener('input', (e) => {
pH = Number(e.target.value);
document.getElementById('pHValue').textContent = pH.toFixed(1);
});
document.getElementById('tempRange').addEventListener('input', (e) => {
temperature = Number(e.target.value);
document.getElementById('tempValue').textContent = temperature;
});
document.getElementById('humidityRange').addEventListener('input', (e) => {
humidity = Number(e.target.value);
document.getElementById('humidityValue').textContent = humidity;
});
// User interaction with the canvas
let isDrawing = false;
canvas.addEventListener('mousedown', (e) => {
const rect = canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
if (isInsidePetriDish(x, y)) {
isDrawing = true;
if (selectedTool === 'sporeSwab') {
placeSample(x, y);
} else if (selectedTool === 'scalpel') {
placeRandomTissue(x, y);
} else if (selectedTool === 'contamination') {
placeContaminant(x, y);
}
}
});
canvas.addEventListener('mousemove', (e) => {
if (isDrawing && (selectedTool === 'sporeSwab' || selectedTool === 'contamination')) {
const rect = canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
if (isInsidePetriDish(x, y)) {
if (selectedTool === 'sporeSwab') {
placeSample(x, y);
} else if (selectedTool === 'contamination') {
placeContaminant(x, y);
}
}
}
});
canvas.addEventListener('mouseup', () => {
isDrawing = false;
});
canvas.addEventListener('mouseleave', () => {
isDrawing = false;
});
// Function to check if a point is inside the petri dish
function isInsidePetriDish(x, y) {
const dx = x - width / 2;
const dy = y - height / 2;
return Math.sqrt(dx * dx + dy * dy) <= dishRadius;
}
// Initialize grids
let nutrientGrid = [];
let occupancyGrid = [];
let antifungalGrid = []; // For antifungal responses
function initializeNutrientGrid() {
nutrientGrid = [];
occupancyGrid = [];
antifungalGrid = [];
const nutrientLevel = getAgarNutrientLevel(agarType);
for (let x = 0; x < width; x++) {
nutrientGrid[x] = [];
occupancyGrid[x] = [];
antifungalGrid[x] = [];
for (let y = 0; y < height; y++) {
nutrientGrid[x][y] = nutrientLevel;
occupancyGrid[x][y] = null;
antifungalGrid[x][y] = 0;
}
}
}
initializeNutrientGrid();
// Get initial nutrient level based on agar type
function getAgarNutrientLevel(agar) {
const nutrientLevels = {
charcoal: 80,
blood: 120,
dextrose: 100,
feces: 60,
maltExtract: 110,
fungalAgar: 100,
sabouraud: 90,
};
return nutrientLevels[agar] || 80;
}
// Arrays to hold samples and contaminants
let samples = [];
let contaminants = [];
// Species properties
const speciesProperties = {
shiitake: {
growthRate: 1.0,
filamentThickness: 0.5,
branchingProbability: 0.05,
color: '#A0522D', // Sienna
edgeColor: '#FF6347', // Tomato
preferredAgar: 'charcoal',
mergeProbability: 0.2,
isContaminant: false,
antifungalStrength: 2,
},
oyster: {
growthRate: 1.2,
filamentThickness: 0.7,
branchingProbability: 0.07,
color: '#87CEFA', // LightSkyBlue
edgeColor: '#1E90FF', // DodgerBlue
preferredAgar: 'dextrose',
mergeProbability: 0.4,
isContaminant: false,
antifungalStrength: 1,
},
pinkOyster: {
growthRate: 1.3,
filamentThickness: 0.6,
branchingProbability: 0.08,
color: '#FFC0CB', // Pink
edgeColor: '#FF69B4', // HotPink
preferredAgar: 'dextrose',
mergeProbability: 0.4,
isContaminant: false,
antifungalStrength: 1,
},
enoki: {
growthRate: 0.9,
filamentThickness: 0.4,
branchingProbability: 0.04,
color: '#FFFACD', // LemonChiffon
edgeColor: '#FFD700', // Gold
preferredAgar: 'blood',
mergeProbability: 0.3,
isContaminant: false,
antifungalStrength: 1,
},
cordyceps: {
growthRate: 0.8,
filamentThickness: 0.3,
branchingProbability: 0.03,
color: '#FF8C00', // DarkOrange
edgeColor: '#FF4500', // OrangeRed
preferredAgar: 'feces',
mergeProbability: 0.1,
isContaminant: false,
antifungalStrength: 2,
},
lionsMane: {
growthRate: 1.1,
filamentThickness: 0.6,
branchingProbability: 0.06,
color: '#FFFFFF', // White
edgeColor: '#F0E68C', // Khaki
preferredAgar: 'blood',
mergeProbability: 0.35,
isContaminant: false,
antifungalStrength: 1,
},
buttonMushroom: {
growthRate: 1.0,
filamentThickness: 0.5,
branchingProbability: 0.05,
color: '#F5F5DC', // Beige
edgeColor: '#DEB887', // BurlyWood
preferredAgar: 'maltExtract',
mergeProbability: 0.3,
isContaminant: false,
antifungalStrength: 1,
},
cremini: {
growthRate: 1.0,
filamentThickness: 0.5,
branchingProbability: 0.05,
color: '#CD853F', // Peru
edgeColor: '#D2691E', // Chocolate
preferredAgar: 'maltExtract',
mergeProbability: 0.3,
isContaminant: false,
antifungalStrength: 1,
},
portobello: {
growthRate: 0.9,
filamentThickness: 0.6,
branchingProbability: 0.04,
color: '#8B4513', // SaddleBrown
edgeColor: '#A0522D', // Sienna
preferredAgar: 'maltExtract',
mergeProbability: 0.25,
isContaminant: false,
antifungalStrength: 1,
},
maitake: {
growthRate: 1.1,
filamentThickness: 0.6,
branchingProbability: 0.06,
color: '#708090', // SlateGray
edgeColor: '#2F4F4F', // DarkSlateGray
preferredAgar: 'fungalAgar',
mergeProbability: 0.35,
isContaminant: false,
antifungalStrength: 2,
},
blackTrumpet: {
growthRate: 0.8,
filamentThickness: 0.4,
branchingProbability: 0.03,
color: '#000000', // Black
edgeColor: '#696969', // DimGray
preferredAgar: 'fungalAgar',
mergeProbability: 0.2,
isContaminant: false,
antifungalStrength: 2,
},
morel: {
growthRate: 1.2,
filamentThickness: 0.5,
branchingProbability: 0.07,
color: '#D2B48C', // Tan
edgeColor: '#BC8F8F', // RosyBrown
preferredAgar: 'sabouraud',
mergeProbability: 0.4,
isContaminant: false,
antifungalStrength: 2,
},
// Contaminant properties
mold: {
growthRate: 1.5,
filamentThickness: 0.4,
branchingProbability: 0.1,
color: '#00FF00', // Bright Green
edgeColor: '#008000', // Dark Green
preferredAgar: 'any',
mergeProbability: 0.5,
isContaminant: true,
},
mildew: {
growthRate: 1.2,
filamentThickness: 0.3,
branchingProbability: 0.08,
color: '#CCCCCC', // Light Gray
edgeColor: '#888888', // Gray
preferredAgar: 'any',
mergeProbability: 0.5,
isContaminant: true,
},
bacteria: {
growthRate: 2.0,
filamentThickness: 0.2,
branchingProbability: 0.2,
color: '#FFFF00', // Yellow
edgeColor: '#FFD700', // Gold
preferredAgar: 'blood',
mergeProbability: 0.6,
isContaminant: true,
},
virus: {
growthRate: 0.5,
filamentThickness: 0.1,
branchingProbability: 0.05,
color: '#FF00FF', // Magenta
edgeColor: '#8B008B', // Dark Magenta
preferredAgar: 'any',
mergeProbability: 0.8,
isContaminant: true,
},
};
// Function to place a sample on the dish
function placeSample(x, y) {
if (!simulationRunning) {
startSimulation();
}
ctx.beginPath();
ctx.fillStyle = speciesProperties[selectedSpecies].color;
ctx.arc(x, y, 2, 0, 2 * Math.PI);
ctx.fill();
// Add the sample with initial branches
const initialBranches = [];
const numBranches = 8;
for (let i = 0; i < numBranches; i++) {
initialBranches.push({
x: x,
y: y,
angle: (i / numBranches) * 2 * Math.PI + (Math.random() - 0.5) * 0.1,
age: 0,
});
}
samples.push({
species: selectedSpecies,
branches: initialBranches,
id: generateSampleId(),
color: speciesProperties[selectedSpecies].color,
nutrients: 0,
isContaminant: false,
});
}
// Function to place a tissue sample
function placeRandomTissue(x, y) {
if (!simulationRunning) {
startSimulation();
}
// Generate random polygon shape
const numPoints = Math.floor(Math.random() * 5) + 5;
const radius = Math.random() * 10 + 5;
const angles = [];
for (let i = 0; i < numPoints; i++) {
angles.push((i / numPoints) * 2 * Math.PI + (Math.random() - 0.5) * 0.2);
}
angles.sort((a, b) => a - b);
ctx.beginPath();
for (let i = 0; i < numPoints; i++) {
const px = x + Math.cos(angles[i]) * radius * (Math.random() * 0.4 + 0.8);
const py = y + Math.sin(angles[i]) * radius * (Math.random() * 0.4 + 0.8);
if (i === 0) {
ctx.moveTo(px, py);
} else {
ctx.lineTo(px, py);
}
}
ctx.closePath();
ctx.fillStyle = speciesProperties[selectedSpecies].color;
ctx.fill();
// Add multiple samples within the tissue area
const numSamples = numPoints * 3;
const sampleId = generateSampleId();
for (let i = 0; i < numSamples; i++) {
const angle = Math.random() * 2 * Math.PI;
const dist = Math.random() * radius;
const sampleX = x + Math.cos(angle) * dist;
const sampleY = y + Math.sin(angle) * dist;
if (isInsidePetriDish(sampleX, sampleY)) {
const initialBranches = [];
const numBranches = 8;
for (let j = 0; j < numBranches; j++) {
initialBranches.push({
x: sampleX,
y: sampleY,
angle: (j / numBranches) * 2 * Math.PI + (Math.random() - 0.5) * 0.1,
age: 0,
});
}
samples.push({
species: selectedSpecies,
branches: initialBranches,
id: sampleId,
color: speciesProperties[selectedSpecies].color,
nutrients: 0,
isContaminant: false,
});
}
}
}
// Function to place a contaminant
function placeContaminant(x, y) {
if (!simulationRunning) {
startSimulation();
}
ctx.beginPath();
ctx.fillStyle = speciesProperties[selectedContaminant].color;
ctx.arc(x, y, 2, 0, 2 * Math.PI);
ctx.fill();
const initialBranches = [];
const numBranches = 6;
for (let i = 0; i < numBranches; i++) {
initialBranches.push({
x: x,
y: y,
angle: (i / numBranches) * 2 * Math.PI + (Math.random() - 0.5) * 0.2,
age: 0,
});
}
contaminants.push({
species: selectedContaminant,
branches: initialBranches,
id: generateSampleId(),
color: speciesProperties[selectedContaminant].color,
nutrients: 0,
isContaminant: true,
});
}
// Function to generate a unique ID
function generateSampleId() {
return Math.random().toString(36).substr(2, 9);
}
// Simulation interval variable
let simulationInterval;
// Virtual hour counter
let virtualHours = 0;
const hourDisplay = document.getElementById('hourDisplay');
// Function to calculate pH growth factor
function getpHGrowthFactor(pH, species) {
const speciespH = {
shiitake: 5.5,
oyster: 6.0,
pinkOyster: 6.0,
enoki: 6.5,
cordyceps: 6.8,
lionsMane: 6.0,
buttonMushroom: 6.2,
cremini: 6.2,
portobello: 6.2,
maitake: 5.8,
blackTrumpet: 6.0,
morel: 7.0,
mold: 5.0,
mildew: 6.5,
bacteria: 7.0,
virus: 6.5,
};
const optimalpH = speciespH[species] || 6.5; // Default optimal pH
const pHTolerance = 2.0; // pH units where growth is acceptable
const pHDifference = Math.abs(pH - optimalpH);
const pHFactor = Math.max(0, 1 - (pHDifference / pHTolerance));
return pHFactor;
}
// Function to calculate temperature growth factor
function getTemperatureGrowthFactor(temperature, species) {
const speciesTemps = {
shiitake: { optimal: 60, range: 20 },
oyster: { optimal: 65, range: 25 },
pinkOyster: { optimal: 80, range: 20 },
enoki: { optimal: 55, range: 15 },
cordyceps: { optimal: 68, range: 15 },
lionsMane: { optimal: 60, range: 20 },
psilocybe: { optimal: 75, range: 15 },
buttonMushroom: { optimal: 65, range: 15 },
cremini: { optimal: 65, range: 15 },
portobello: { optimal: 65, range: 15 },
maitake: { optimal: 60, range: 20 },
blackTrumpet: { optimal: 55, range: 20 },
morel: { optimal: 55, range: 20 },
mold: { optimal: 70, range: 30 },
mildew: { optimal: 75, range: 25 },
bacteria: { optimal: 98.6, range: 20 },
virus: { optimal: 90, range: 30 },
};
const speciesTemp = speciesTemps[species] || { optimal: 70, range: 20 };
const tempDifference = Math.abs(temperature - speciesTemp.optimal);
const tempFactor = Math.max(0, 1 - (tempDifference / speciesTemp.range));
return tempFactor;
}
// Function to calculate humidity growth factor
function getHumidityGrowthFactor(humidity, species) {
const speciesHumidity = {
shiitake: { optimal: 80, range: 20 },
oyster: { optimal: 85, range: 15 },
pinkOyster: { optimal: 90, range: 10 },
enoki: { optimal: 90, range: 10 },
cordyceps: { optimal: 75, range: 20 },
lionsMane: { optimal: 85, range: 15 },
buttonMushroom: { optimal: 90, range: 15 },
cremini: { optimal: 90, range: 15 },
portobello: { optimal: 85, range: 10 },
maitake: { optimal: 80, range: 20 },
blackTrumpet: { optimal: 75, range: 20 },
morel: { optimal: 70, range: 20 },
mold: { optimal: 90, range: 20 },
mildew: { optimal: 95, range: 15 },
bacteria: { optimal: 85, range: 20 },
virus: { optimal: 80, range: 30 },
};
const speciesHumidityRange = speciesHumidity[species] || { optimal: 80, range: 20 };
const humidityDifference = Math.abs(humidity - speciesHumidityRange.optimal);
const humidityFactor = Math.max(0, 1 - (humidityDifference / speciesHumidityRange.range));
return humidityFactor;
}
// Function to clear the console log
function clearConsole() {
const consoleDiv = document.getElementById('console');
consoleDiv.innerHTML = ''; // Clear all log entries
}
// Simulation loop
function simulate() {
// Update virtual hours
virtualHours += 1;
hourDisplay.textContent = `Virtual Hours: ${virtualHours}`;
// No canvas clearing; we draw filaments only once
// Example log for demonstration purposes
setInterval(() => {
if (simulationRunning) {
logToConsole(`Virtual Hours: ${virtualHours}, Samples: ${samples.length}, Contaminants: ${contaminants.length}`);
logToConsole(`Organism ${organism.id} merged with ${occupyingOrganism.id}. Nutrients increased to ${organism.nutrients}.`);
logToConsole(`Organism ${organism.id} growth stopped due to interaction with ${occupyingOrganism.id}.`);
logToConsole(`Organism ${organism.id} experienced starvation at (${newX.toFixed(2)}, ${newY.toFixed(2)}).`);
logToConsole(`Organism ${organism.id} started forming pins at edge (${branch.x.toFixed(2)}, ${branch.y.toFixed(2)}).`);
}
}, 2000);
// Simulate mycelium samples
samples.forEach((sample) => {
simulateOrganism(sample, 'mycelium');
});
// Simulate contaminants
contaminants.forEach((contaminant) => {
simulateOrganism(contaminant, 'contaminant');
});
// Remove samples with no more branches
samples = samples.filter(sample => sample.branches.length > 0);
contaminants = contaminants.filter(contaminant => contaminant.branches.length > 0);
// Stop the simulation if no organisms are left
if (samples.length === 0 && contaminants.length === 0) {
stopSimulation();
}
}
// Function to simulate organism growth (both mycelium and contaminants)
function simulateOrganism(organism, type) {
const speciesProp = speciesProperties[organism.species];
const agarGrowthRate = getAgarGrowthRate(agarType, organism.species);
// Calculate environmental growth factors
const pHGrowthFactor = getpHGrowthFactor(pH, organism.species);
const tempGrowthFactor = getTemperatureGrowthFactor(temperature, organism.species);
const humidityGrowthFactor = getHumidityGrowthFactor(humidity, organism.species);
// Adjust the base growth rate
let baseGrowthRate =
speciesProp.growthRate *
agarGrowthRate *
pHGrowthFactor *
tempGrowthFactor *
humidityGrowthFactor;
// If baseGrowthRate is zero or negative, skip this organism
if (baseGrowthRate <= 0) {
return; // Skip to the next organism
}
const newBranches = [];
organism.branches.forEach((branch) => {
branch.age += 1;
// Calculate growth direction and position
const dx = Math.cos(branch.angle) * baseGrowthRate;
const dy = Math.sin(branch.angle) * baseGrowthRate;
const newX = branch.x + dx;
const newY = branch.y + dy;
const gridX = Math.floor(newX);
const gridY = Math.floor(newY);
// Check if new position is within the dish
if (isInsidePetriDish(newX, newY)) {
// Check for occupancy
const occupyingOrganism = occupancyGrid[gridX][gridY];
if (occupyingOrganism && occupyingOrganism.id !== organism.id) {
// Interaction occurs
const interactionOutcome = determineInteractionOutcome(organism, occupyingOrganism);
if (interactionOutcome === 'merge') {
// Merge the organisms
occupancyGrid[gridX][gridY] = organism;
drawFilament(branch.x, branch.y, newX, newY, speciesProp, branch.age, true);
newBranches.push({
x: newX,
y: newY,
angle: branch.angle + (Math.random() - 0.5) * 0.3,
age: branch.age,
});
// Nutrient sharing upon merging
organism.nutrients += 10;
} else if (interactionOutcome === 'stop') {
// Branch stops growing
// Do nothing
} else if (interactionOutcome === 'overgrow') {
// Continue growing over existing organism
occupancyGrid[gridX][gridY] = organism;
drawFilament(branch.x, branch.y, newX, newY, speciesProp, branch.age, true);
newBranches.push({
x: newX,
y: newY,
angle: branch.angle + (Math.random() - 0.5) * 0.3,
age: branch.age,
});
} else if (interactionOutcome === 'avoid') {
// Change direction to avoid the contaminant
branch.angle += (Math.random() - 0.5) * Math.PI;
// If organism is mycelium and encountering a contaminant, produce antifungal response
if (!organism.isContaminant && occupyingOrganism.isContaminant) {
// Increase antifungal compound concentration at this location
antifungalGrid[gridX][gridY] += speciesProp.antifungalStrength || 1;
// Draw antifungal response visually
drawAntifungalResponse(newX, newY, speciesProp);
}
}
} else {
// Consume nutrients
const nutrient = nutrientGrid[gridX][gridY];
if (nutrient > 0) {
// Reduce nutrient level at the new position
nutrientGrid[gridX][gridY] = Math.max(0, nutrient - 0.5);
// Adjust growth rate based on nutrient level
const nutrientFactor = nutrient / 100; // Normalize nutrient level
const adjustedGrowthRate = baseGrowthRate * nutrientFactor;
// Occupy the grid
occupancyGrid[gridX][gridY] = organism;
// Draw the filament
drawFilament(branch.x, branch.y, newX, newY, speciesProp, branch.age, false);
// Add the new branch point
newBranches.push({
x: newX,
y: newY,
angle: branch.angle + (Math.random() - 0.5) * 0.3,
age: branch.age,
});
// Branching
if (Math.random() < speciesProp.branchingProbability * nutrientFactor) {
newBranches.push({