-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinteractiveNeurons.html
More file actions
1063 lines (927 loc) · 34.3 KB
/
Copy pathinteractiveNeurons.html
File metadata and controls
1063 lines (927 loc) · 34.3 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
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">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Interactive Neurons</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.7.0/p5.js"></script>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background: #808080;
}
</style>
</head>
<body>
<script>
// Interactive Neurons
//
// Creates a spiking network of neurons, each connected to a number of nearest neighbors.
// The simulation uses a leaky integrate and fire model, with synaptic weights updated
// using STDP (Spike Timing Dependent Plasticity), meaning that if a spike is received at
// a neuron just before that neuron fires, the synaptic weight is strengthened. If a spike
//. is received just after a neuron has fired, the synaptic weight is weakened.
//. Neurons can be set to be I/O channels by left-clicking the neuron while pressing
//. a key.
//.
// To-Do tasks:
//
// If "a" then "b" and b pressed just after a pulse arrived, strengthen a->b
//. key to quiet all neuron charge to non-firing state (sleep), then wake up, same patterns?
// add measure of learning rate (changes/sec) and firing rate (firing/sec)
// correct dt to be accurate rather than a constant
let startingNeurons = 100;
let numNeighbors = 8;
let neuronRadius = 9;
let firingThreshold = 0.9; // Neuron fires at this charge
let axonVelocity = 200.0; // Axon conduction rate in pixels/sec
const REFRACTORY_PERIOD_CONSTANT = 0.75 * 200.0; // Constant for inverse proportionality (refractoryPeriod * axonVelocity)
let refractoryPeriod = REFRACTORY_PERIOD_CONSTANT / axonVelocity; // Refractory period in seconds (inversely proportional to axon velocity)
let bluesScale = [440, 6/5*440, 4/3*440, 45/32*440, 3/2*440, 9/5*440, 2*440];
const NOTE_FREQUENCIES = {
A: 440.00,
B: 493.88,
C: 523.25,
D: 587.33,
E: 659.25,
F: 698.46,
G: 783.99
};
const NOTE_NAMES = Object.keys(NOTE_FREQUENCIES);
const NOTE_SAMPLES = {
A: "A4.mp3",
B: "B4.mp3",
C: "C5.mp3",
D: "D5.mp3",
E: "E5.mp3",
F: "F5.mp3",
G: "G5.mp3"
};
const PIANO_SAMPLE_BASE_URL = "https://gleitz.github.io/midi-js-soundfonts/FluidR3_GM/acoustic_grand_piano-mp3/";
const HARPSICHORD_SAMPLE_BASE_URL = "https://gleitz.github.io/midi-js-soundfonts/FluidR3_GM/harpsichord-mp3/";
const TRAINING_TUNE = "EEFGGFEDCCDEEDD EEFGGFEDCCDEDCC";
const BASE_TRAINING_NOTE_INTERVAL_MS = 420;
const DEFAULT_PLAYOUT_RATE = 0.5;
let justUpdatedNeurons = false;
let learning = true;
let averageFPS = 0;
let leakageRate = 0.1; // charge leakage rate/second
// STDP (Spike Timing Dependent Plasticity) parameters
const STDP_TIME_WINDOW = 0.050; // 50ms time window for STDP (in seconds)
const STDP_TAU_PLUS = 0.020; // Time constant for LTP (pre-before-post) decay (20ms)
const STDP_TAU_MINUS = 0.020; // Time constant for LTD (post-before-pre) decay (20ms)
const STDP_A_PLUS = 0.15; // Maximum LTP weight change
const STDP_A_MINUS = 0.10; // Maximum LTD weight change (slightly smaller for asymmetry)
let weightStrengthenCount = 0; // Counter for weight strengthening (positive changes)
let weightWeakenCount = 0; // Counter for weight weakening (negative changes)
let lastLearningRateMeasureTime = 0;
let measuredStrengthenRate = 0;
let measuredWeakenRate = 0;
let firingCount = 0; // Counter for neuron firings
let measuredFiringRate = 0; // Measured firing rate (firings per second)
let outputString = []; // Array of {char, source} objects where source is 'key' or 'spontaneous'
let neighborSlider;
let neuronSlider;
let conductionSpeedSlider;
let playoutRateSlider;
let playTuneButton;
let soundButton;
let audioCtx;
let soundEnabled = false;
let keyboardSamples = {
piano: {},
harpsichord: {}
};
let keyboardSamplesLoading = false;
let keyboardSamplesReady = false;
let tunePlaying = false;
let tuneIndex = 0;
let lastTuneNoteTime = 0;
class Neuron {
constructor(x, y, radius, charge) {
this.x = x;
this.y = y;
this.radius = radius;
this.charge = charge;
this.connections = [];
this.dragging = false;
this.clicked = false;
this.recovering = 0.0;
this.frequency = bluesScale[floor(random(bluesScale.length))];
this.key = "";
this.lastFired = null;
this.outputAddedForKeyPress = false; // Flag to track if output was already added for a key press
this.pendingInstrument = null;
}
connect(neuron, weight) {
let connection = new Connection(this, neuron, weight);
this.connections.push(connection);
}
removeConnection(target) {
this.connections = this.connections.filter(conn => conn.to !== target);
}
disconnect(neuron) {
// Remove connections to the given neuron
this.removeConnection(neuron);
// Remove connection from the given neuron back to this neuron
neuron.removeConnection(this);
}
getRadius() {
return this.radius;
}
update(dt) {
// Update this neuron
this.recovering = constrain(this.recovering - dt, 0, refractoryPeriod);
this.maybeFire();
this.charge = constrain(this.charge - (leakageRate * dt), 0, 1);
}
// Fire this neuron on next update
fire(instrument = 'piano') {
this.charge += firingThreshold;
this.pendingInstrument = instrument;
}
maybeFire() {
if (this.charge < 0) this.charge = 0;
if(!this.recovering && (this.charge >= firingThreshold)){
// Fire this neuron
//print("fire!");
let currentTime = new Date();
this.lastFired = currentTime;
firingCount++; // Increment firing counter
// Only add output if it wasn't already added for a key press and neuron has a key set
if (!this.outputAddedForKeyPress && this.key !== "") {
this.addToOutput(this.key, 'spontaneous');
}
this.outputAddedForKeyPress = false; // Reset flag after firing
if (this.key) {
let instrument = this.pendingInstrument || 'piano';
playTone(this.frequency, 0.7, instrument);
}
this.pendingInstrument = null;
// STDP: Check all incoming connections for recent pre-synaptic spikes (pre-before-post = LTP)
if (learning) {
// Find all connections that target this neuron (incoming connections)
for (let neuron of neurons) {
for (let connection of neuron.connections) {
if (connection.to === this && connection.lastSpikeArrivalTime !== null) {
// Calculate time difference: (when post fired) - (when spike arrived at post)
// Positive timeDiff means spike arrived before post fired (LTP condition)
let timeDiff = (currentTime - connection.lastSpikeArrivalTime) / 1000.0; // Convert to seconds
// If spike arrived before post fired (positive timeDiff), and within time window
if (timeDiff > 0 && timeDiff < STDP_TIME_WINDOW) {
// Apply LTP (Long Term Potentiation): strengthen connection
let oldWeight = connection.weight;
let weightChange = STDP_A_PLUS * Math.exp(-timeDiff / STDP_TAU_PLUS);
connection.weight = constrain(connection.weight + weightChange, -1, 1);
// Update learning indicators
if (connection.weight !== oldWeight) {
if (connection.weight > oldWeight) {
weightStrengthenCount++;
}
connection.learned = 60; // LEARNING_COLOR_DELAY
}
}
}
}
}
}
for (let connection of this.connections) {
connection.charge = this.charge; // send impulse to connections
}
this.recovering = refractoryPeriod;
this.charge = 0; // reset neuron charge to zero
}
}
addToOutput(key, source = 'spontaneous') {
// Don't add empty keys to output
if (key === "" || key === null || key === undefined) {
return;
}
let MAX_OUTPUT = 100;
outputString.push({char: key, source: source});
// Truncate to last 50 characters
if(outputString.length > MAX_OUTPUT) {
outputString = outputString.slice(outputString.length - MAX_OUTPUT);
}
}
display() {
// Draw boundary of neuron, then inside to indicate charge level
fill("grey");
strokeWeight(1);
stroke('black');
ellipse(this.x, this.y, this.getRadius() * 2);
noStroke();
if (this.recovering) {
fill((this.recovering / refractoryPeriod)*255);
ellipse(this.x, this.y, this.getRadius() * 2);
} else {
fill('green');
ellipse(this.x, this.y, map(this.charge, 0, 1.0, 0, this.getRadius() * 2));
}
if (this.key != "") {
fill('white');
textSize(neuronRadius);
textAlign(CENTER, CENTER);
text(this.key === ' ' ? '_' : this.key, this.x, this.y);
}
}
mousePressed() {
let d = dist(mouseX, mouseY, this.x, this.y);
if (d < this.getRadius()) {
this.offsetX = this.x - mouseX;
this.offsetY = this.y - mouseY;
this.startingX = this.x;
this.startingY = this.y;
if (mouseButton === RIGHT) {
// If right-clicking a neuron, prompt for a key to be associated with it
let k = prompt('Enter a key to associate with this neuron:')
if (k) {
console.log(`Setting neuron key to ${k}`);
this.key = k;
}
} else if (mouseButton === LEFT) {
this.clicked = true;
}
}
}
mouseDragged() {
if (this.clicked) {
this.dragging = true;
}
}
mouseReleased() {
if (this.clicked) {
this.clicked = false;
if (this.dragging) {
// Calculate how far the neuron was dragged
let dragDistance = dist(this.x, this.y, this.startingX, this.startingY);
// Only re-wire if dragged more than 1/4 of the neuron's diameter
let dragThreshold = this.getRadius() / 2; // 1/4 of diameter = radius / 2
if (dragDistance > dragThreshold) {
// When a neuron is dragged and released, recompute connections for all neurons
// since positions have changed and nearest neighbors may have changed
// First, build a map of existing connection weights to preserve them
let existingWeights = buildConnectionWeightMap();
for (let neuron of neurons) {
updateNeuronConnections(neuron, existingWeights);
}
// Reset all connection charges and chargePositions to zero after resetting connections
for (let neuron of neurons) {
for (let connection of neuron.connections) {
connection.charge = 0;
connection.chargePosition = 0;
}
}
fixOffsets();
} else {
// If dragged less than threshold, just reset position and fire
this.x = this.startingX;
this.y = this.startingY;
this.charge = firingThreshold;
}
this.dragging = false;
} else {
// Fire the neuron on release if it wasn't dragged
this.charge = firingThreshold;
}
}
}
drag() {
if (this.dragging) {
this.x = mouseX + this.offsetX;
this.y = mouseY + this.offsetY;
}
}
}
class Connection {
constructor(from, to, weight) {
this.from = from;
this.to = to;
this.weight = weight;
this.dragging = false;
this.startWeight = 0;
this.startMouseX = 0;
this.offsetX = 0;
this.offsetY = 0;
this.charge = random(1.0);
this.chargePosition = random(1.0); // How far along the axon is the charge right now?
this.setOffsets();
this.learned = 0;
this.lastSpikeArrivalTime = null; // Track when the last spike arrived at post-synaptic neuron
}
setOffsets() {
const hasOppositeConnection = this.to.connections.filter(conn => conn.to === this.from).length > 0;
this.offsetX = 0;
this.offsetY = 0;
if(hasOppositeConnection) {
let angle = atan2(this.to.y - this.from.y, this.to.x - this.from.x); // calculate angle of line
const offsetDistance = 3; // pixel gap between adjacent connection lines
this.offsetX = offsetDistance * cos(angle + PI / 2); // calculate x offset
this.offsetY = offsetDistance * sin(angle + PI / 2); // calculate y offset
}
}
update(dt) {
// If there's a charge moving along the connection
if (this.charge > 0) {
let d = dist(this.from.x, this.from.y, this.to.x, this.to.y);
this.chargePosition += (axonVelocity * dt)/d; // Calculate how much charge will move
// If the charge reaches the target neuron, convey to target
if (this.chargePosition >= 1.0) {
// Calculate new charge: current charge + (weight * incoming charge)
// Then constrain to valid range [0, firingThreshold]
this.to.charge = constrain(this.to.charge + this.weight * this.charge, 0, firingThreshold);
this.lastSpikeArrivalTime = new Date(); // Record when spike arrived
// STDP: Check if post-synaptic neuron recently fired (post-before-pre = LTD)
if (learning && this.to.lastFired !== null) {
let timeDiff = (this.lastSpikeArrivalTime - this.to.lastFired) / 1000.0; // Convert to seconds
// If post fired before pre arrived (positive timeDiff), and within time window
if (timeDiff > 0 && timeDiff < STDP_TIME_WINDOW) {
// Apply LTD (Long Term Depression): weaken connection
let oldWeight = this.weight;
let weightChange = -STDP_A_MINUS * Math.exp(-timeDiff / STDP_TAU_MINUS);
this.weight = constrain(this.weight + weightChange, -1, 1);
// Update learning indicators
if (this.weight !== oldWeight) {
if (this.weight < oldWeight) {
weightWeakenCount++;
}
this.learned = 60; // LEARNING_COLOR_DELAY
}
}
}
this.charge = 0; // reset charge on connection to zero
this.chargePosition = 0;
}
}
}
displayCharge() {
if (this.charge > 0) {
let x = lerp(this.from.x + this.offsetX, this.to.x + this.offsetX, this.chargePosition);
let y = lerp(this.from.y + this.offsetY, this.to.y + this.offsetY, this.chargePosition);
// Use paler version of connection color (green for positive, red for negative)
if (this.weight > 0) {
fill(150, 220, 150); // Paler green
} else {
fill(220, 150, 150); // Paler red
}
noStroke();
ellipse(x, y, 5 + map(abs(this.weight), 0, 1, 1, 5));
}
}
display() {
// Find if there's a connection in opposite direction
const hasOppositeConnection = this.to.connections.filter(conn => conn.to === this.from).length > 0;
// Calculate start and end point considering the neuron radii and the offset
let startX = lerp(this.from.x, this.to.x, this.from.getRadius() / dist(this.from.x, this.from.y, this.to.x, this.to.y));
let startY = lerp(this.from.y, this.to.y, this.from.getRadius() / dist(this.from.x, this.from.y, this.to.x, this.to.y));
let endX = lerp(this.from.x, this.to.x, 1 - (this.to.getRadius() + 6) / dist(this.from.x, this.from.y, this.to.x, this.to.y));
let endY = lerp(this.from.y, this.to.y, 1 - (this.to.getRadius() + 6) / dist(this.from.x, this.from.y, this.to.x, this.to.y));
// Draw the line
noFill();
strokeWeight(map(abs(this.weight), 0, 1, 1, 5));
stroke(this.learned ? 'white' : (this.weight > 0 ? 'green' : 'red'));
line(startX + this.offsetX, startY + this.offsetY, endX + this.offsetX, endY + this.offsetY);
this.learned = false;
}
contains(x, y) {
// Same as original code, except for using stored offsets
// use this.offsetX and this.offsetY instead of recalculating them
let v = {x: this.from.x + this.offsetX, y: this.from.y + this.offsetY};
let w = {x: this.to.x + this.offsetX, y: this.to.y + this.offsetY};
let d = distToSegmentSquared({x:x, y:y}, v, w);
return d < 8;
}
mousePressed() {
if(this.contains(mouseX, mouseY)){
this.dragging = true;
this.startWeight = this.weight;
this.startMouseX = mouseX;
} else {
this.dragging = false;
}
}
mouseDragged() {
if(this.dragging) {
// Scale mouse move distance to [-1, 1] range and add to startWeight
let scaleFactor = 20; // Change this for more or less sensitivity
let moveAmount = (mouseX - this.startMouseX) / scaleFactor;
this.weight = constrain(this.startWeight + moveAmount, -1, 1);
}
}
mouseReleased() {
this.dragging = false;
}
}
let neurons = [];
let simulationRunning = true;
function findNearestNeighbors(neuron, count) {
// Get all neurons and their distances to the given neuron
let distances = neurons.map(other => {
return {
neuron: other,
distance: dist(neuron.x, neuron.y, other.x, other.y)
};
});
// Sort by distance and exclude the given neuron itself
distances = distances.filter(d => d.neuron !== neuron);
distances.sort((a, b) => a.distance - b.distance);
// Return the 'count' nearest neurons
return distances.slice(0, count).map(d => d.neuron);
}
function buildConnectionWeightMap() {
// Build a map of all existing connections and their weights
// Key format: "fromIndex-toIndex" where indices are positions in neurons array
let weightMap = new Map();
for (let i = 0; i < neurons.length; i++) {
for (let connection of neurons[i].connections) {
let toIndex = neurons.indexOf(connection.to);
let key = `${i}-${toIndex}`;
weightMap.set(key, connection.weight);
}
}
return weightMap;
}
function updateNeuronConnections(neuron, existingWeights = null) {
// Build weight map if not provided
let weightMap = existingWeights;
if (weightMap === null) {
weightMap = buildConnectionWeightMap();
}
// Get this neuron's index
let fromIndex = neurons.indexOf(neuron);
// Clear existing connections first
neuron.connections = [];
// Connect to the nearest neighbors based on the global numNeighbors variable
let nearestNeighbors = findNearestNeighbors(neuron, numNeighbors);
for (let neighbor of nearestNeighbors) {
// Check if this connection already existed
let toIndex = neurons.indexOf(neighbor);
let key = `${fromIndex}-${toIndex}`;
let weight;
if (weightMap.has(key)) {
// Use existing weight if connection already existed
weight = weightMap.get(key);
} else {
// Create new weight for new connections
// 80% chance excitatory (positive), 20% chance inhibitory (negative)
if (random() < 0.8) {
// Excitatory: positive weight between 0 and 1
weight = random(0, 1);
} else {
// Inhibitory: negative weight between -1 and 0
weight = random(-1, 0);
}
}
neuron.connect(neighbor, weight);
}
}
function setup() {
createCanvas(windowWidth, windowHeight);
if (!audioCtx) {
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
}
loadKeyboardSamples();
let startStopButton = createButton('Stop');
startStopButton.position(10, 10);
startStopButton.mousePressed(() => {
if(simulationRunning){
simulationRunning = false;
startStopButton.html('Start');
} else {
simulationRunning = true;
SimulationLoop(); // restart the simulation loop
startStopButton.html('Stop');
}
});
let inhibitButton = createButton('Inhibit');
inhibitButton.position(60, 10);
inhibitButton.mousePressed(() => incrementWeightsBy(-0.1));
let exciteButton = createButton('Excite');
exciteButton.position(120, 10);
exciteButton.mousePressed(() => incrementWeightsBy(0.1));
soundButton = createButton('Sound: Off');
soundButton.position(180, 10);
soundButton.mousePressed(() => {
soundEnabled = !soundEnabled;
soundButton.html(soundEnabled ? 'Sound: On' : 'Sound: Off');
if (soundEnabled && audioCtx && audioCtx.state === 'suspended') {
audioCtx.resume();
}
});
let sleepButton = createButton('Sleep');
sleepButton.position(265, 10);
sleepButton.mousePressed(() => {
sleepNetwork();
});
let learningToggleButton = createButton(learning ? 'Learning: On' : 'Learning: Off');
learningToggleButton.position(315, 10);
learningToggleButton.mousePressed(() => {
learning = !learning;
learningToggleButton.html(learning ? 'Learning: On' : 'Learning: Off');
});
playTuneButton = createButton('Play');
playTuneButton.position(430, 10);
playTuneButton.mousePressed(toggleTunePlayback);
neuronSlider = createSlider(2, 200, startingNeurons, 1);
neuronSlider.position(10, 80);
neuronSlider.style('width', '150px');
neighborSlider = createSlider(1, 20, numNeighbors, 1);
neighborSlider.position(10, 125);
neighborSlider.style('width', '150px');
neighborSlider.changed(() => {
// Preserve existing connection weights when changing neighbor count
let existingWeights = buildConnectionWeightMap();
for (let neuron of neurons) {
updateNeuronConnections(neuron, existingWeights);
}
});
conductionSpeedSlider = createSlider(50, 500, axonVelocity, 10);
conductionSpeedSlider.position(10, 170);
conductionSpeedSlider.style('width', '150px');
playoutRateSlider = createSlider(0.25, 2, DEFAULT_PLAYOUT_RATE, 0.05);
playoutRateSlider.position(10, 215);
playoutRateSlider.style('width', '150px');
// Initial creation of neurons
initializeNeurons(neuronSlider.value());
SimulationLoop();
}
function SimulationLoop() {
const dt = 0.016; // Time step for the simulation (s)
// Update axonVelocity based on the slider's value
axonVelocity = conductionSpeedSlider.value();
// Update refractoryPeriod inversely proportionally to axonVelocity (faster velocity = shorter refractory period)
refractoryPeriod = REFRACTORY_PERIOD_CONSTANT / axonVelocity;
updateTunePlayback();
// For each neuron in the network, check if the neuron needs to fire
for (let neuron of neurons) {
neuron.update(dt);
// For each connection of the neuron, update the position of the charge
for(let connection of neuron.connections) {
connection.update(dt);
}
}
// Call the simulation loop again after a delay (corresponding to the time step)
if(simulationRunning) setTimeout(SimulationLoop, dt * 1000); // Convert from s to ms
}
function initializeNeurons(numNeurons) {
neurons = [];
// Place first neuron in the center
neurons.push(new Neuron(width / 2, height / 2, neuronRadius, random(0.99)));
// Minimum distance between neurons (2x diameter = 4x radius)
const minDistance = 5 * neuronRadius;
// Distance range to place new from existing neuron
const minDistanceFromExisting = minDistance;
const maxDistanceFromExisting = minDistance * 3;
// Try to place remaining neurons
let attempts = 0;
const maxAttempts = numNeurons * 1000; // Limit attempts to avoid infinite loops
while (neurons.length < numNeurons && attempts < maxAttempts) {
attempts++;
// Pick a random existing neuron to place near
let referenceNeuron = neurons[floor(random(neurons.length))];
// Try to find a valid position
let validPosition = false;
let newX, newY;
let placementAttempts = 0;
const maxPlacementAttempts = 100;
while (!validPosition && placementAttempts < maxPlacementAttempts) {
placementAttempts++;
// Generate random angle and distance from reference neuron
let angle = random(TWO_PI);
let distance = random(minDistanceFromExisting, maxDistanceFromExisting);
newX = referenceNeuron.x + cos(angle) * distance;
newY = referenceNeuron.y + sin(angle) * distance;
// Check if position is within canvas bounds
if (newX < neuronRadius || newX > width - neuronRadius ||
newY < neuronRadius || newY > height - neuronRadius) {
continue; // Try again
}
// Check if this position is far enough from all existing neurons
validPosition = true;
for (let existingNeuron of neurons) {
let d = dist(newX, newY, existingNeuron.x, existingNeuron.y);
if (d < minDistance) {
validPosition = false;
break;
}
}
}
// If we found a valid position, add the neuron
if (validPosition) {
neurons.push(new Neuron(newX, newY, neuronRadius, random(0.99)));
}
}
// Connect neurons to their nearest neighbors
for (let neuron of neurons) {
updateNeuronConnections(neuron);
}
assignNoteNeurons();
// Finally, correct offsets for all
fixOffsets();
}
function assignNoteNeurons() {
let shuffledNeurons = shuffle(neurons.slice());
let noteCount = min(NOTE_NAMES.length, shuffledNeurons.length);
for (let i = 0; i < noteCount; i++) {
let note = NOTE_NAMES[i];
shuffledNeurons[i].key = note;
shuffledNeurons[i].frequency = NOTE_FREQUENCIES[note];
}
}
function fixOffsets() {
// Correct rendered position of weight line at initialization and if neuron is dragged
console.log("fixing offsets");
for (let neuron of neurons) {
for (let connection of neuron.connections) {
connection.setOffsets();
}
}
}
function sleepNetwork() {
// Clear all charges and chargePositions to put the network to sleep
for (let neuron of neurons) {
// Reset neuron charge to zero (clear all active charges)
neuron.charge = 0;
// Also reset recovering state to allow immediate firing if needed
neuron.recovering = 0;
// Clear all connection charges and chargePositions
for (let connection of neuron.connections) {
connection.charge = 0;
connection.chargePosition = 0;
}
}
// Clear the output string
outputString = [];
}
function toggleTunePlayback() {
tunePlaying = !tunePlaying;
playTuneButton.html(tunePlaying ? 'Stop Tune' : 'Play');
if (tunePlaying) {
enableSound();
tuneIndex = 0;
lastTuneNoteTime = 0;
advanceTune();
}
}
function enableSound() {
soundEnabled = true;
if (soundButton) {
soundButton.html('Sound: On');
}
if (audioCtx && audioCtx.state === 'suspended') {
audioCtx.resume();
}
}
function advanceTune() {
if (!tunePlaying) {
return;
}
let note = TRAINING_TUNE[tuneIndex];
tuneIndex = (tuneIndex + 1) % TRAINING_TUNE.length;
lastTuneNoteTime = millis();
if (note && note !== " ") {
triggerNote(note, 'key', 'harpsichord');
}
}
function updateTunePlayback() {
let noteInterval = BASE_TRAINING_NOTE_INTERVAL_MS / playoutRateSlider.value();
if (tunePlaying && millis() - lastTuneNoteTime >= noteInterval) {
advanceTune();
}
}
function triggerNote(note, source = 'key', instrument = 'harpsichord') {
for (let n of neurons) {
if (n.key == note) {
n.addToOutput(note, source);
n.outputAddedForKeyPress = true;
n.fire(instrument);
}
}
}
function draw() {
background(128);
if (justUpdatedNeurons) {
justUpdatedNeurons = false;
return;
}
if (neuronSlider.value() != neurons.length) {
initializeNeurons(neuronSlider.value());
justUpdatedNeurons = true;
return;
}
// Add charge to neuron if mouse is hovering over it (and not dragging)
if (!mouseIsPressed) {
for (let neuron of neurons) {
let d = dist(mouseX, mouseY, neuron.x, neuron.y);
if (d < neuron.getRadius()) {
// Add a small charge increment each frame when hovering
neuron.charge = constrain(neuron.charge + 0.01, 0, 1);
}
}
}
for(let neuron of neurons) {
for(let connection of neuron.connections) {
connection.display();
connection.displayCharge();
}
}
for (let neuron of neurons) {
neuron.display();
}
textSize(12);
textAlign(LEFT, TOP);
fill(0, 0, 0);
noStroke();
numNeighbors = neighborSlider.value();
text(`Neurons: ${neurons.length}`, 20, 102);
text(`Neighbors: ${numNeighbors}`, 20, 147);
text(`Speed: ${axonVelocity}`, 20, 192);
text(`Playout: ${playoutRateSlider.value().toFixed(2)}x`, 20, 237);
if (simulationRunning) {
// Update and display neurons
for (let neuron of neurons) {
neuron.drag();
neuron.display();
}
}
// Display the training song, highlighting the note currently being played.
textAlign(LEFT, TOP);
textSize(18);
let tuneX = 10;
let activeTuneIndex = (tuneIndex - 1 + TRAINING_TUNE.length) % TRAINING_TUNE.length;
for (let i = 0; i < TRAINING_TUNE.length; i++) {
let note = TRAINING_TUNE[i];
fill(tunePlaying && i === activeTuneIndex ? 255 : 0);
text(note === " " ? " " : note, tuneX, 35);
tuneX += textWidth(note);
}
// Measure learning rate and firing rate once per second
let currentTime = millis();
if (currentTime - lastLearningRateMeasureTime >= 1000) {
measuredStrengthenRate = weightStrengthenCount;
measuredWeakenRate = weightWeakenCount;
measuredFiringRate = firingCount;
weightStrengthenCount = 0; // Reset counters
weightWeakenCount = 0;
firingCount = 0;
lastLearningRateMeasureTime = currentTime;
}
// Display output string with color coding: red for key-pressed, white for spontaneous
// Display the last 50 characters (or all if less than 50)
textAlign(LEFT, BOTTOM);
textSize(20);
noStroke();
// Get the last 50 characters to display (most recent)
let charsToDisplay = outputString.slice(-50);
let xPos = 10;
// Display all characters
for (let item of charsToDisplay) {
if (item.source === 'key') {
fill(255, 0, 0); // Red for key-pressed
} else {
fill(255, 255, 255); // White for spontaneous firing
}
text(item.char, xPos, windowHeight - 24);
xPos += textWidth(item.char);
}
// Display frame rate, learning rate, and firing rate near bottom of canvas
fill(0);
noStroke();
textAlign(LEFT, BOTTOM);
textSize(12);
averageFPS = 0.9 * averageFPS + 0.1 * frameRate();
let normalizedFiringRate = neurons.length > 0 ? (measuredFiringRate / neurons.length).toFixed(2) : '0.00';
text(`Fps: ${averageFPS.toFixed(0)} Learning Rate: ${measuredStrengthenRate}/${measuredWeakenRate} Firing Rate: ${normalizedFiringRate}`, 10, windowHeight - 5);
}
function mousePressed() {
for (let neuron of neurons) {
neuron.mousePressed();
if (!neuron.dragging) {
for(let connection of neuron.connections) {
connection.mousePressed();
}
}
}
}
function mouseDragged() {
for (let neuron of neurons) {
neuron.mouseDragged();
if (!neuron.dragging) {
for(let connection of neuron.connections) {
connection.mouseDragged();
}
}
}
}
function mouseReleased() {
for (let neuron of neurons) {
neuron.mouseReleased();
for(let connection of neuron.connections) {
connection.mouseReleased();
}
}
}
// New function to handle the keyTyped event
function keyTyped() {
//console.log(`key = ${key}`);
for (let n of neurons) {
if (n.key == key) {
// Add output immediately with 'key' source when key is pressed
n.addToOutput(key, 'key');
n.outputAddedForKeyPress = true; // Set flag to prevent duplicate output in maybeFire()
n.fire('harpsichord')
}
if (n.clicked) {
n.key = key;
console.log("mapped to " + key);
}
}
}
async function loadKeyboardSamples() {
if (keyboardSamplesLoading || keyboardSamplesReady || !audioCtx) {
return;
}
keyboardSamplesLoading = true;
try {
let loadedSamples = {
piano: {},
harpsichord: {}
};
let instruments = [
{name: 'piano', baseUrl: PIANO_SAMPLE_BASE_URL},
{name: 'harpsichord', baseUrl: HARPSICHORD_SAMPLE_BASE_URL}
];
await Promise.all(instruments.flatMap((instrument) => {
return NOTE_NAMES.map(async (note) => {
let response = await fetch(instrument.baseUrl + NOTE_SAMPLES[note]);
let arrayBuffer = await response.arrayBuffer();
loadedSamples[instrument.name][note] = await audioCtx.decodeAudioData(arrayBuffer);
});
}));
keyboardSamples = loadedSamples;
keyboardSamplesReady = true;
} catch (error) {
console.warn("Could not load keyboard samples", error);
} finally {
keyboardSamplesLoading = false;
}
}
function noteForFrequency(frequency) {
let bestNote = null;
let bestDifference = Infinity;
for (let note of NOTE_NAMES) {
let difference = abs(NOTE_FREQUENCIES[note] - frequency);