-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest-integration.ts
More file actions
358 lines (311 loc) · 11.5 KB
/
test-integration.ts
File metadata and controls
358 lines (311 loc) · 11.5 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
/**
* Integration Test - Brain Primitives
*
* Tests all modules working together:
* - Genome definition and loading
* - Sensory encoding
* - Network simulation
* - Neuromodulation
* - Motor decoding
* - Visualization/recording
*
* This creates a simple reflex arc: stimulus → sensory → inter → motor → response
*
* @author Rodrigo Luglio & Claude
* @date December 2025
*/
import { core as mx } from '@frost-beta/mlx'
import type { Genome } from './src/core/genome.svelte.ts'
import { loadGenome, validateGenome, getPopulationForNeuron } from './src/core/genome.svelte.ts'
import { step, getNetworkDerived, networkPopulations } from './src/core/network.svelte.ts'
import { allocateSensor, encodeRate, encodeBinary } from './src/core/sensory.svelte.ts'
import { allocateMotor, updateSpikeWindow, decodeRate } from './src/core/motor.svelte.ts'
import {
allocateModulation,
signalRewardById,
signalPunishmentById,
getModulatorLevels,
} from './src/core/modulation.svelte.ts'
import { recordAll, getNetworkActivitySummary, getRasterData, clearAll } from './src/core/viz.svelte.ts'
import { fired, voltage, populationSize } from './src/core/neuron.svelte.ts'
// ============================================================================
// TEST GENOME: Simple Reflex Arc
// ============================================================================
/**
* A minimal but complete genome for testing.
* Models a simple stimulus-response reflex:
*
* Touch sensor (3 neurons) → Interneurons (5 neurons) → Motor output (2 neurons)
*
* This is analogous to the simplest biological reflex:
* touching a hot surface → sensory neuron → interneuron → motor neuron → withdraw hand
*/
const reflexGenome: Genome = {
name: 'test_reflex',
description: 'Simple reflex arc for integration testing',
neurons: [
// Sensory population - receives external input
{
id: 'sensory',
size: 3,
type: 'RS', // Regular spiking
excitatory: true, // Sensory neurons are excitatory
role: 'sensory',
region: 'other',
noise: 2, // Low background noise
},
// Interneuron population - processes signal
{
id: 'inter',
size: 5,
type: 'RS',
excitatory: true,
role: 'inter',
region: 'other',
noise: 5, // Normal background noise
},
// Inhibitory interneurons - for balance
{
id: 'inhib',
size: 2,
type: 'FS', // Fast spiking inhibitory
excitatory: false,
role: 'inter',
region: 'other',
noise: 3,
},
// Motor population - produces output
{
id: 'motor',
size: 2,
type: 'RS',
excitatory: true,
role: 'motor',
region: 'other',
noise: 2,
},
],
synapses: [
// Sensory → Inter (feedforward)
{
id: 'sens_to_inter',
pre: 'sensory',
post: 'inter',
pattern: 'all-to-all',
plastic: true,
initialWeight: 0.3, // Strong innate connection
},
// Inter → Motor (feedforward)
{
id: 'inter_to_motor',
pre: 'inter',
post: 'motor',
pattern: 'all-to-all',
plastic: true,
initialWeight: 0.25,
},
// Sensory → Inhibitory
{
id: 'sens_to_inhib',
pre: 'sensory',
post: 'inhib',
pattern: 'all-to-all',
plastic: false,
initialWeight: 0.2,
},
// Inhibitory → Inter (lateral inhibition effect)
{
id: 'inhib_to_inter',
pre: 'inhib',
post: 'inter',
pattern: 'all-to-all',
plastic: false,
initialWeight: -0.5, // Negative because inhibitory
},
],
// Simple reflex: strong direct pathway
reflexes: [
{
name: 'withdrawal',
pathway: ['sensory', 'motor'], // Direct shortcut for fast response
strength: 0.4,
plastic: false, // Innate, not learnable
},
],
version: '1.0',
author: 'test',
}
// ============================================================================
// TEST RUNNER
// ============================================================================
async function runTest() {
console.log('='.repeat(60))
console.log('BRAIN PRIMITIVES INTEGRATION TEST')
console.log('='.repeat(60))
console.log()
// -------------------------------------------------------------------------
// 1. Validate and load genome
// -------------------------------------------------------------------------
console.log('1. GENOME VALIDATION AND LOADING')
console.log('-'.repeat(40))
const validation = validateGenome(reflexGenome)
console.log(` Valid: ${validation.valid}`)
if (validation.errors.length > 0) {
console.log(` Errors: ${validation.errors.join(', ')}`)
return
}
if (validation.warnings.length > 0) {
console.log(` Warnings: ${validation.warnings.join(', ')}`)
}
const networkIndex = loadGenome(reflexGenome)
console.log(` Network loaded at index: ${networkIndex}`)
console.log(` Populations: ${networkPopulations[networkIndex].length}`)
console.log()
// -------------------------------------------------------------------------
// 2. Setup sensory and motor interfaces
// -------------------------------------------------------------------------
console.log('2. SENSORY AND MOTOR SETUP')
console.log('-'.repeat(40))
const sensoryPopIndex = getPopulationForNeuron('test_reflex', 'sensory')!
const motorPopIndex = getPopulationForNeuron('test_reflex', 'motor')!
const sensorIndex = allocateSensor('touch', sensoryPopIndex, {
type: 'touch',
encoding: 'rate',
gain: 20, // Amplify input
threshold: 0.1, // Minimum activation
adaptationRate: 0.02,
})
const motorIndex = allocateMotor('withdraw', motorPopIndex, {
type: 'muscle',
decoding: 'rate',
gain: 1.0,
threshold: 0.1,
windowSize: 5,
})
console.log(` Sensor allocated: index ${sensorIndex}`)
console.log(` Motor allocated: index ${motorIndex}`)
console.log()
// -------------------------------------------------------------------------
// 3. Initialize modulation system
// -------------------------------------------------------------------------
console.log('3. NEUROMODULATION SETUP')
console.log('-'.repeat(40))
allocateModulation('test_reflex', {
dopamineDecay: 0.95,
serotoninDecay: 0.98,
norepinephrineDecay: 0.9,
acetylcholineDecay: 0.92,
})
console.log(' Modulation system initialized')
console.log()
// -------------------------------------------------------------------------
// 4. Run simulation: No stimulus phase
// -------------------------------------------------------------------------
console.log('4. SIMULATION: NO STIMULUS (50 steps)')
console.log('-'.repeat(40))
clearAll(networkIndex, 'test_reflex')
for (let t = 0; t < 50; t++) {
// No sensory input
updateSpikeWindow(motorIndex)
step(networkIndex, 1.0)
recordAll(networkIndex, 'test_reflex')
}
let summary = getNetworkActivitySummary(networkIndex)
console.log(` Total neurons: ${summary.totalNeurons}`)
console.log(` Firing neurons: ${summary.firingNeurons}`)
console.log(` Avg voltage: ${summary.avgVoltage.toFixed(2)} mV`)
console.log(` E/I ratio: ${(summary.excRatio * 100).toFixed(1)}%`)
console.log()
// -------------------------------------------------------------------------
// 5. Run simulation: Stimulus phase
// -------------------------------------------------------------------------
console.log('5. SIMULATION: WITH STIMULUS (100 steps)')
console.log('-'.repeat(40))
const motorResponses: number[] = []
for (let t = 0; t < 100; t++) {
// Apply stimulus for first 20 steps
if (t < 20) {
encodeRate(sensorIndex, 0.8) // Strong stimulus
}
// Signal reward when motor responds (simulating successful withdrawal)
mx.eval(fired[motorPopIndex])
const motorFired = mx.sum(fired[motorPopIndex]).item() as number
if (motorFired > 0 && t < 30) {
signalRewardById('test_reflex', 0.5)
}
updateSpikeWindow(motorIndex)
step(networkIndex, 1.0)
recordAll(networkIndex, 'test_reflex')
// Record motor output
mx.eval(decodeRate(motorIndex))
motorResponses.push(decodeRate(motorIndex).item() as number)
}
summary = getNetworkActivitySummary(networkIndex)
console.log(` Final firing neurons: ${summary.firingNeurons}`)
console.log(` Final E/I ratio: ${(summary.excRatio * 100).toFixed(1)}%`)
// Analyze motor response
const maxResponse = Math.max(...motorResponses)
const avgResponse = motorResponses.reduce((a, b) => a + b, 0) / motorResponses.length
const responseLatency = motorResponses.findIndex(r => r > 0.1)
console.log(` Max motor response: ${maxResponse.toFixed(4)}`)
console.log(` Avg motor response: ${avgResponse.toFixed(4)}`)
console.log(` Response latency: ${responseLatency >= 0 ? responseLatency : 'no response'} steps`)
console.log()
// -------------------------------------------------------------------------
// 6. Check modulator levels
// -------------------------------------------------------------------------
console.log('6. MODULATOR LEVELS')
console.log('-'.repeat(40))
const modLevels = getModulatorLevels('test_reflex')
mx.eval(modLevels.dopamine, modLevels.serotonin, modLevels.norepinephrine, modLevels.acetylcholine)
console.log(` Dopamine: ${(modLevels.dopamine.item() as number).toFixed(4)}`)
console.log(` Serotonin: ${(modLevels.serotonin.item() as number).toFixed(4)}`)
console.log(` Norepinephrine: ${(modLevels.norepinephrine.item() as number).toFixed(4)}`)
console.log(` Acetylcholine: ${(modLevels.acetylcholine.item() as number).toFixed(4)}`)
console.log()
// -------------------------------------------------------------------------
// 7. Check raster data
// -------------------------------------------------------------------------
console.log('7. SPIKE RASTER DATA')
console.log('-'.repeat(40))
const raster = getRasterData(networkIndex, 50)
console.log(` Spikes in last 50 steps: ${raster.times.length}`)
// Count spikes per population
const spikesPerPop = new Map<number, number>()
for (const p of raster.populations) {
spikesPerPop.set(p, (spikesPerPop.get(p) ?? 0) + 1)
}
for (const [popIndex, count] of spikesPerPop) {
console.log(` Population ${popIndex}: ${count} spikes`)
}
console.log()
// -------------------------------------------------------------------------
// 8. Test punishment signal
// -------------------------------------------------------------------------
console.log('8. PUNISHMENT SIGNAL TEST')
console.log('-'.repeat(40))
signalPunishmentById('test_reflex', 1.0)
const modLevels2 = getModulatorLevels('test_reflex')
mx.eval(modLevels2.dopamine)
console.log(` Dopamine after punishment: ${(modLevels2.dopamine.item() as number).toFixed(4)}`)
console.log()
// -------------------------------------------------------------------------
// 9. Final summary
// -------------------------------------------------------------------------
console.log('='.repeat(60))
console.log('TEST COMPLETE')
console.log('='.repeat(60))
console.log()
// Report success/failure
const success = maxResponse > 0 && responseLatency >= 0 && responseLatency < 30
if (success) {
console.log('✓ Reflex arc successfully responded to stimulus')
console.log('✓ All modules integrated correctly')
} else {
console.log('✗ Reflex arc did not respond as expected')
console.log(' Check neuron parameters and synaptic weights')
}
console.log()
}
// Run the test
runTest().catch(console.error)