-
Notifications
You must be signed in to change notification settings - Fork 0
/
variable_binding.py
1785 lines (1258 loc) · 59.2 KB
/
variable_binding.py
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
#!/usr/bin/env python3
import matplotlib.pyplot as plt
import nest
import numpy as np
from os.path import join
import pickle as pkl
from analysis import *
from neural_space import *
from inpop import *
from utils import *
# parameters for trace extraction
_t_burn_in = 50. # discarded at beginning so activity can settle
_tau_filter = 20. # time constant of filter
_len_filter = 100. # filter length
_C_readout_args = dict(t_burn_in=_t_burn_in, tau_filter=_tau_filter,
len_filter=_len_filter, use_data='all', noise_var=0, drop_silent=False)
# plot settings
plt.rcParams.update({'figure.max_open_warning': 0})
def setup_variable_binding(outdir, swtafile, variant, config_c, config_v, num_variable_spaces=1):
if not isinstance(variant, dict):
assert variant == 'big_V'
setup_nest(modname='vb_module')
# load content space parameters
with open(swtafile, 'rb') as f:
p = pkl.load(f)
if len(p) == 4: # legacy
wiring, t_per_pattern, t_silence, N_show_pattern = p
num_assemblies = 5
else:
num_assemblies, wiring, t_per_pattern, t_silence, N_show_pattern = p
rate_on = 100
#rate_on = 75.
#rate_on = 60.
rate_off = .1
#rate_off = 1.
#rate_off = 5.
# setup inputs
inpop = InPop(rate_on=rate_on, rate_off=rate_off, num_pattern=num_assemblies, num_neurons=num_assemblies*25+75)
N_pattern = inpop.num_pattern
print('using swta file', swtafile)
print(' t_per_pattern', t_per_pattern)
print(' t_silence', t_silence)
print(' N_show_pattern', N_show_pattern)
print('using inpop')
print(' num_neurons', inpop.num_neurons)
print(' num_pattern', inpop.num_pattern)
print(' rate_off', inpop.rate_off)
print(' rate_on', inpop.rate_on)
print(' rate_clear', inpop.rate_clear)
c_activity_mu = 1
n_activity_mu = 1
# setup circuit
print('restoring content space...')
if isinstance(variant, dict):
config_c.update({'N_E': int(variant['size_C']), 'N_I': int(variant['size_C']*.25)})
C_min_ind = min([w[0] for w in wiring['EE']] + [w[1] for w in wiring['EE']])
C_max_ind = max([w[0] for w in wiring['EE']] + [w[1] for w in wiring['EE']])
assert C_max_ind - C_min_ind == variant['size_C'] - 1
c_space = NeuralSpace('C', config=config_c, wiring_EE=wiring['EE'], activity_mu=c_activity_mu)
c_space.connect_input(inpop.pop_X, wiring_XE=wiring['XE'])
c_space.set_synaptic_plasticity(XE=False, EE=False) # freeze input weights
print('creating variable space...')
# modifications
if variant == 'big_V':
print(' using big neural spaces')
symmetric = False
config_v.update({'N_E': 2000, 'N_I': 500})
elif isinstance(variant, dict):
symmetric = False
config_v.update({'N_E': int(variant['size_N']), 'N_I': int(variant['size_N']*.25)})
assert c_space.config['N_E'] == int(variant['size_C'])
assert c_space.config['N_I'] == int(variant['size_C']*.25)
assert len(c_space.pop_E) == int(variant['size_C'])
assert len(c_space.pop_I) == int(variant['size_C']*.25)
else:
raise ValueError()
n_spaces = []
for k in range(num_variable_spaces):
name = chr(ord('V') - k)
n_space = NeuralSpace(name, config=config_v, activity_mu=n_activity_mu)
n_space.connect_input_space(c_space)
c_space.connect_input_space(n_space, symmetric=symmetric)
n_space.inhibit()
n_spaces += [n_space]
# ----------------------------------------------------------------------
# test
# connect new spike detectors for convenient plotting
c_space.clear_spikes()
t_test_start = []
t_test_end = []
labels = []
# simulate one period of silence
inpop.clear()
nest.Simulate(t_silence)
for k in range(N_pattern):
print("TEST {}/{}".format(k+1, N_pattern))
labels += [k]
t_test_start += [nest.GetKernelStatus()['time']]
inpop.set(k)
nest.Simulate(t_per_pattern)
t_test_end += [nest.GetKernelStatus()['time']]
inpop.clear()
nest.Simulate(t_silence)
# train readouts for decoding from C
print("train readout on C")
t_lim = (t_test_start[0], t_test_end[-1])
spikes_C = c_space.get_spikes(t_lim=t_lim)[0]
_, x, y = spikes_to_traces(spikes_C, c_space.pop_E, [*zip(t_test_start, t_test_end, labels)], **_C_readout_args)
C_readout_test = train_readout(x, y)
# ----------------------------------------------------------------------
# CREATE assemblies in variable space(s)
# return a list of lists, i.e. a list containing 2 lists containing 5 items
# each for num_spaces=2 and num_pattern=5
t_create_start = []
t_create_end = []
k_pattern = list(range(num_assemblies))
for n, n_space in enumerate(n_spaces):
t_create_start_cur = []
t_create_end_cur = []
for k, pat in enumerate(k_pattern):
print("CREATE {}/{}".format(len(k_pattern)*n+k+1, len(n_spaces)*len(k_pattern)))
inpop.clear()
nest.Simulate(1000.)
n_space.disinhibit()
t_create_start_cur += [nest.GetKernelStatus()['time']]
inpop.set(pat)
nest.Simulate(1000.)
t_create_end_cur += [nest.GetKernelStatus()['time']]
n_space.inhibit(reset_sfa=True)
c_space.reset_sfa()
t_create_start += [t_create_start_cur]
t_create_end += [t_create_end_cur]
return inpop, c_space, n_spaces, t_test_start, t_test_end, t_create_start, t_create_end, C_readout_test
def store_recall(outdir, swtafile, variant, config_c, config_v, recall_cfg, k_pattern=None, print_results=True, print_assemblies=True, gather_statistics=False, plot=True, show=True):
# unpack input
inhibit_V = recall_cfg['inhibit_V']
t_store = recall_cfg['t_store']
t_recall_1 = recall_cfg['t_recall_1']
t_recall_2 = recall_cfg['t_recall_2']
# setup
r = setup_variable_binding(
outdir,
swtafile,
variant,
config_c=config_c,
config_v=config_v,
num_variable_spaces=1
)
inpop, c_space, n_spaces, t_test_start, t_test_end, t_create_start, t_create_end, C_readout_test = r
N_pattern = inpop.num_pattern
# only one variable space is used
assert len(n_spaces) == 1
assert len(t_create_start) == 1
assert len(t_create_end) == 1
n_space = n_spaces[0]
t_create_start = t_create_start[0]
t_create_end = t_create_end[0]
# assert E_sfa clipping is used
assert nest.GetStatus(n_space.pop_E)[0]['E_sfa_clip'] == True
assert nest.GetStatus(n_space.pop_E)[0]['E_sfa_max'] < 0.
# gather statistics
if gather_statistics:
arg = [
('a_test_C', c_space, t_test_start, t_test_end, False),
#('a_create_C', c_space, t_create_start, t_create_end, False),
('a_create_V', n_space, t_create_start, t_create_end, False)]
r = multi_assembly_analysis(arg)
a_test_C = r['a_test_C']
#a_create_C = r['a_create_C']
a_create_V = r['a_create_V']
# weights in content space
c_wiring = c_space.get_wiring(normalize_indices=False)
r = analyze_assembly_weights(c_wiring['EE'], a_test_C)
w_c_within_a, w_c_between_a, w_c_between_a_and_noa, w_c_within_noa = r
if plot:
plot_assembly_correlations(r, 'in_c', save=join(outdir, 'weights_in_c.pdf'), close=(not show))
# weights in variable space
n_wiring = n_space.get_wiring(normalize_indices=False)
r = analyze_assembly_weights(n_wiring['EE'], a_create_V)
w_n_within_a, w_n_between_a, w_n_between_a_and_noa, w_n_within_noa = r
if plot:
plot_assembly_correlations(r, 'in_n', save=join(outdir, 'weights_in_n.pdf'), close=(not show))
# weights between neural spaces
r_cn = analyze_assembly_weights(n_wiring['SE_C_to_V'], a_test_C, a_create_V)
w_cn_within_a, w_cn_between_a, w_cn_between_a_and_noa, w_cn_within_noa = r_cn
r_nc = analyze_assembly_weights(c_wiring['SE_V_to_C'], a_create_V, a_test_C)
w_nc_within_a, w_nc_between_a, w_nc_between_a_and_noa, w_nc_within_noa = r_nc
if plot:
plot_assembly_correlations(r_cn, 'c_to_n', save=join(outdir, 'weights_c_to_n.pdf'), close=(not show))
plot_assembly_correlations(r_nc, 'n_to_c', save=join(outdir, 'weights_n_to_c.pdf'), close=(not show))
# stats
def elementary_stats(w):
return { 'num_synapses': len(w), 'weight_mean': w.mean(), 'weight_std': w.std()}
stats = {
'content_space': {
'within_assemblies': elementary_stats(w_c_within_a),
'between_assemblies': elementary_stats(w_c_between_a),
'between_assemblies_and_free': elementary_stats(w_c_between_a_and_noa),
'between_free': elementary_stats(w_c_within_noa)},
'variable_space': {
'within_assemblies': elementary_stats(w_n_within_a),
'between_assemblies': elementary_stats(w_n_between_a),
'between_assemblies_and_free': elementary_stats(w_n_between_a_and_noa),
'between_free': elementary_stats(w_n_within_noa)},
'feedforward_projection': {
'between_linked_assemblies': elementary_stats(w_cn_within_a),
'between_nonlinked_assemblies': elementary_stats(w_cn_between_a)},
'feedback_projection': {
'between_linked_assemblies': elementary_stats(w_nc_within_a),
'between_nonlinked_assemblies': elementary_stats(w_nc_between_a)}}
dump_dict(stats, dumpfile=join(outdir, 'statistics.json'))
# spontaneous activity of content space
t_spontaneous = 200.
plot_num = 100
inpop.clear()
c_space.disinhibit()
n_space.inhibit(reset_sfa=True)
t_c_spontaneous_start = nest.GetKernelStatus()['time']
nest.Simulate(t_spontaneous)
t_c_spontaneous_end = nest.GetKernelStatus()['time']
spikes_exc, spikes_inh = c_space.get_spikes(t_lim=(t_c_spontaneous_start, t_c_spontaneous_end))
spontaneous_rate_c_exc = len(spikes_exc[0]) / len(c_space.pop_E) / t_spontaneous * 1000
spontaneous_rate_c_inh = len(spikes_inh[0]) / len(c_space.pop_I) / t_spontaneous * 1000
spontaneous_rate_c = (len(spikes_exc[0])+len(spikes_inh[0])) / len(c_space.pop) / t_spontaneous * 1000
plot_spikes_fancy(
c_space.spike_rec_E,
targets=np.arange(plot_num)+min(c_space.pop_E),
xlim=(t_c_spontaneous_start, t_c_spontaneous_end),
save=join(outdir, 'spontaneous_activity_c_exc.pdf'))
plot_spikes_fancy(
c_space.spike_rec_I,
targets=np.arange(plot_num)+min(c_space.pop_I),
xlim=(t_c_spontaneous_start, t_c_spontaneous_end),
save=join(outdir, 'spontaneous_activity_c_inh.pdf'))
# spontaneous activity of variable space
c_space.inhibit()
n_space.disinhibit()
t_n_spontaneous_start = nest.GetKernelStatus()['time']
nest.Simulate(t_spontaneous)
t_n_spontaneous_end = nest.GetKernelStatus()['time']
spikes_exc, spikes_inh = n_space.get_spikes(t_lim=(t_n_spontaneous_start, t_n_spontaneous_end))
spontaneous_rate_n_exc = len(spikes_exc[0]) / len(n_space.pop_E) / t_spontaneous * 1000
spontaneous_rate_n_inh = len(spikes_inh[0]) / len(n_space.pop_I) / t_spontaneous * 1000
spontaneous_rate_n = (len(spikes_exc[0])+len(spikes_inh[0])) / len(n_space.pop) / t_spontaneous * 1000
plot_spikes_fancy(
n_space.spike_rec_E,
targets=np.arange(plot_num)+min(n_space.pop_E),
xlim=(t_n_spontaneous_start, t_n_spontaneous_end),
save=join(outdir, 'spontaneous_activity_n_exc.pdf'))
plot_spikes_fancy(
n_space.spike_rec_I,
targets=np.arange(plot_num)+min(n_space.pop_I),
xlim=(t_n_spontaneous_start, t_n_spontaneous_end),
save=join(outdir, 'spontaneous_activity_n_inh.pdf'))
# stats
spontaneous_stats = {
'time': t_spontaneous,
'content_space': {
'mean_excitatory_rate': spontaneous_rate_c_exc,
'mean_inhibitory_rate': spontaneous_rate_c_inh,
'mean_rate': spontaneous_rate_c},
'variable_space': {
'mean_excitatory_rate': spontaneous_rate_n_exc,
'mean_inhibitory_rate': spontaneous_rate_n_inh,
'mean_rate': spontaneous_rate_n}}
dump_dict(spontaneous_stats, dumpfile=join(outdir, 'spontaneous_activtiy_statistics.json'))
if not show:
plt.close('all')
return
# check parameters
if k_pattern is None:
k_pattern = list(range(N_pattern))
for p in k_pattern:
assert p < N_pattern
# perform STORE/RECALL
t_store_start = []
t_store_end = []
t_recall_start = []
t_recall_end = []
labels = []
for k, pat in enumerate(k_pattern):
print("STORE/RECALL {}/{}".format(k+1, len(k_pattern)))
labels += [pat]
# STORE
n_space.inhibit(reset_sfa=True)
inpop.clear()
nest.Simulate(1000.)
t_store_start += [nest.GetKernelStatus()['time']]
n_space.disinhibit()
inpop.set(pat)
nest.Simulate(t_store)
t_store_end += [nest.GetKernelStatus()['time']]
# RECALL
c_space.inhibit()
if inhibit_V:
n_space.inhibit()
inpop.clear()
nest.Simulate(5000.)
t_recall_start += [nest.GetKernelStatus()['time']]
if inhibit_V:
n_space.disinhibit()
if t_recall_1 > 0:
nest.Simulate(t_recall_1)
c_space.disinhibit()
nest.Simulate(t_recall_2)
t_recall_end += [nest.GetKernelStatus()['time']]
# ----------------------------------------------------------------------
# analysis
print('analysis')
if plot:
c_weights = c_space.get_weights()
n_weights = n_space.get_weights()
if inhibit_V:
for t0, t1 in zip(t_store_end, t_recall_start):
# make sure neural spaces are silent when they should be
spikes_n = nest.GetStatus(n_space.spike_rec_E)[0]['events']['times']
delta = 50. # allow spikes in first 50 ms of each inhibited period
spikes_v_delay = (spikes_n > t0+delta) & (spikes_n < t1)
nspikes_v_d = sum(spikes_v_delay)
if nspikes_v_d > 0:
print('WARNING: spikes in V during delay period (count: {0:d})'.format(nspikes_v_d))
# assembly analysis
print_test_C = True if print_assemblies else False
arg = [
('a_test_C', c_space, t_test_start, t_test_end, print_test_C),
('a_create_C', c_space, t_create_start, t_create_end, False),
('a_create_V', n_space, t_create_start, t_create_end, False),
('a_recall_C', c_space, t_recall_start, t_recall_end, False),
('a_recall_V', n_space, t_recall_start, t_recall_end, False)]
r = multi_assembly_analysis(arg)
cost_v = 0
cost_c = 0
results_k = []
for j in range(len(k_pattern)):
a_test_C = r['a_test_C'][k_pattern[j]]
a_create_C = r['a_create_C'][j]
a_create_V = r['a_create_V'][j]
a_recall_C = r['a_recall_C'][j]
a_recall_V = r['a_recall_V'][j]
# assembly match V: create vs. recall
am_V_CR = assembly_match(a_create_V, a_recall_V)
# assembly match C: test vs. recall
am_C_TR = assembly_match(a_test_C, a_recall_C)
if print_results:
print('STORE/RECALL {0:d}/{1:d}'.format(j+1, len(k_pattern)))
if print_assemblies:
print('assembly in C during test:')
print(a_test_C, 'size:', len(a_test_C))
print('assembly in C during create:')
print(a_create_C, 'size:', len(a_create_C))
print('assembly in V during create:')
print(a_create_V, 'size:', len(a_create_V))
print('assembly in V during recall:')
print(a_recall_V, 'size:', len(a_recall_V))
print('assembly in C during recall:')
print(a_recall_C, 'size:', len(a_recall_C))
print(' assembly match in V (create vs. recall): {} shared, {} only in create, {} only in recall'.format(*am_V_CR))
print(' assembly match in C (test vs. recall): {} shared, {} only in test, {} only in recall'.format(*am_C_TR))
cost_v += am_V_CR[1] + am_V_CR[2]
cost_c += am_C_TR[1] + am_C_TR[2]
# calculate success criterion
# if > threshold % of the test assembly are active, and if
# <= (100 - threshold) % are wrongly active, count as success
threshold = .8
if len(a_test_C) > 0 and \
(am_C_TR[0] / len(a_test_C) > threshold) and \
(am_C_TR[2] / len(a_test_C) <= (1-threshold)):
success = True
else:
success = False
results_k += [{
'a_test_C_size': len(a_test_C),
'a_create_C_size': len(a_create_C),
'a_create_V_size': len(a_create_V),
'a_recall_C_size': len(a_recall_C),
'a_recall_V_size': len(a_recall_V),
'match_V_shared': am_V_CR[0],
'match_V_only_in_create': am_V_CR[1],
'match_V_only_in_recall': am_V_CR[2],
'match_C_shared': am_C_TR[0],
'match_C_only_in_test': am_C_TR[1],
'match_C_only_in_recall': am_C_TR[2],
'success': success,
}]
# check success with readout
t_lim = (t_recall_start[0], t_recall_end[-1])
spikes_C = c_space.get_spikes(t_lim=t_lim)[0]
args = _C_readout_args.copy()
args['t_burn_in'] += t_recall_1
_, xt, yt = spikes_to_traces(spikes_C, c_space.pop_E, [*zip(t_recall_start, t_recall_end, labels)], **args)
readout_error = C_readout_test(xt, yt)
print('readout error', readout_error)
# ----------------------------------------------------------------------
# plots
if plot:
plot_multi_weight_hist(c_weights, save=join(outdir, 'weights_C'))
plot_multi_weight_hist(n_weights, save=join(outdir, 'weights_V'))
time_test = [min(t_test_start), max(t_test_end)]
plot_spikes(c_space.spike_rec_E, '$C$ during test', xlim=time_test, save=join(outdir, 'test_C.pdf'))
# fancy plots
for j in range(len(k_pattern)):
num = 200
targets_x = np.arange(num) + min(inpop.pop_X)
np.random.shuffle(targets_x)
targets_c = np.arange(num) + min(c_space.pop_E)
targets_v = np.arange(num) + min(n_space.pop_E)
xlim1 = [t_store_start[j]-50., t_store_end[j]+200.]
xlim2 = [t_recall_start[j]-200., t_recall_end[j]]
markers = [t_store_start[j], t_store_end[j], t_recall_start[j]]
labels = ['LOAD', 'DELAY', 'RECALL']
xticks_labeled = [x for x in zip(markers, labels)]
xticks_unlabeled = []
plot_spikes_fancy(inpop.spike_rec, targets=targets_x, xlabel='time', ylabel='$\mathcal{X}$', xlim=xlim1, markers=markers, xticks=xticks_labeled, hide_spines_right=True, save=join(outdir, 'overview_X_{}a.pdf'.format(j)))
plot_spikes_fancy(inpop.spike_rec, targets=targets_x, xlabel='time', ylabel='', xlim=xlim2, markers=markers, xticks=xticks_labeled, hide_spines_left=True, save=join(outdir, 'overview_X_{}b.pdf'.format(j)))
plot_spikes_fancy(c_space.spike_rec_E, targets=targets_c, xlabel='', ylabel='$\mathcal{C}$', xlim=xlim1, markers=markers, xticks=xticks_unlabeled, hide_spines_right=True, save=join(outdir, 'overview_C_{}a.pdf'.format(j)))
plot_spikes_fancy(c_space.spike_rec_E, targets=targets_c, xlabel='', ylabel='', xlim=xlim2, markers=markers, xticks=xticks_unlabeled, hide_spines_left=True, save=join(outdir, 'overview_C_{}b.pdf'.format(j)))
plot_spikes_fancy(n_space.spike_rec_E, targets=targets_v, xlabel='', ylabel='$\mathcal{N}_V$', xlim=xlim1, markers=markers, xticks=xticks_unlabeled, hide_spines_right=True, save=join(outdir, 'overview_V_{}a.pdf'.format(j)))
plot_spikes_fancy(n_space.spike_rec_E, targets=targets_v, xlabel='', ylabel='', xlim=xlim2, markers=markers, xticks=xticks_unlabeled, hide_spines_left=True, save=join(outdir, 'overview_V_{}b.pdf'.format(j)))
# also save all spike data
spikes_X = inpop.get_spikes()
spikes_C = c_space.get_spikes()[0]
spikes_V = n_space.get_spikes()[0]
with open(join(outdir, 'all-spikes.pkl'), 'wb') as f:
I_pop_X = inpop.pop_X
C_pop_E = c_space.pop_E
V_pop_E = n_space.pop_E
pkl.dump([
t_create_start,
t_create_end,
t_store_start,
t_store_end,
t_recall_start,
t_recall_end,
spikes_X,
spikes_C,
spikes_V,
I_pop_X,
C_pop_E,
V_pop_E], f)
if not show:
plt.close('all')
results = {
'k_pattern': k_pattern,
'results_k': results_k,
'readout_error': readout_error,
}
return cost_c, cost_v, results
def store_copy_recall(outdir, swtafile, variant, config_c, config_v, recall_cfg, k_pattern=None, print_results=True, plot=True, show=False):
# unpack input
inhibit_V = recall_cfg['inhibit_V']
t_store = recall_cfg['t_store']
t_recall_1 = recall_cfg['t_recall_1']
t_recall_2 = recall_cfg['t_recall_2']
dump_dict(config_v, ordered=True, key='config_v')
dump_dict(config_c, ordered=True, key='config_c')
# procedure: copy pointer in V to U
#
# 1. clear network activity
# 2. perform create op for t_store, U inhibited
# 3. delay for t_copy_delay_1, C and U inhibited (and possibly V)
# 4. recall from V for t_recall_1, C and U inhibited
# 5. recall from V for t_recall_2, U inhibited
# 6. recall from V for t_copy_create
# 7. delay for t_copy_delay_2, C and V inhibited (and possibly U)
# 8. recall from U for t_recall_1, C and V inhibited
# 9. recall from U for t_recall_2, V inhibited
t_copy_delay_1 = 400. # time to wait after first create in V
t_copy_create = 100. # time of disinhibited U space after recall from V
t_copy_delay_2 = 400. # delay before recall from U
# setup
r = setup_variable_binding(
outdir,
swtafile,
variant,
config_c=config_c,
config_v=config_v,
num_variable_spaces=2
)
inpop, c_space, n_spaces, t_test_start, t_test_end, t_create_start, t_create_end, C_readout_test = r
N_pattern = inpop.num_pattern
assert len(n_spaces) == 2
assert len(t_create_start) == 2
assert len(t_create_end) == 2
n_space_v = n_spaces[0]
n_space_u = n_spaces[1]
t_create_start_V = t_create_start[0]
t_create_start_U = t_create_start[1]
t_create_end_V = t_create_end[0]
t_create_end_U = t_create_end[1]
# assert E_sfa clipping is used
assert nest.GetStatus(n_space_v.pop_E)[0]['E_sfa_clip'] == True
assert nest.GetStatus(n_space_v.pop_E)[0]['E_sfa_max'] < 0.
assert nest.GetStatus(n_space_u.pop_E)[0]['E_sfa_clip'] == True
assert nest.GetStatus(n_space_u.pop_E)[0]['E_sfa_max'] < 0.
# check parameters
if k_pattern is None:
# test with random pattern
k_pattern = np.random.randint(0, N_pattern)
assert type(k_pattern) is int
assert k_pattern < N_pattern
# perform STORE on V
print("STORE")
# clear network activity: inhibit V und U spaces, give random input for C
n_space_v.inhibit()
n_space_u.inhibit()
inpop.clear()
nest.Simulate(1000.)
# perform short create op from C to V
n_space_v.disinhibit()
t_store_start = nest.GetKernelStatus()['time']
inpop.set(k_pattern)
nest.Simulate(t_store)
t_store_end = nest.GetKernelStatus()['time']
# first delay while pointer is saved in V
c_space.inhibit()
if inhibit_V:
n_space_v.inhibit()
inpop.clear()
nest.Simulate(t_copy_delay_1)
print("COPY")
# recall from V to C in two stages
if inhibit_V:
n_space_v.disinhibit()
t_copy_start = nest.GetKernelStatus()['time']
if t_recall_1 > 0:
nest.Simulate(t_recall_1)
c_space.disinhibit()
nest.Simulate(t_recall_2)
# now, copy pointer by additionally activating U
n_space_u.disinhibit()
nest.Simulate(t_copy_create)
t_copy_end = nest.GetKernelStatus()['time']
# delay again before recall from U begins
c_space.inhibit()
n_space_v.inhibit()
#n_space_v.inhibit(reset_sfa=True) # reset to mute space completely
if inhibit_V:
n_space_u.inhibit()
nest.Simulate(t_copy_delay_2)
print("RECALL")
# recall from U in two stages
t_recall_start = nest.GetKernelStatus()['time']
if inhibit_V:
n_space_u.disinhibit()
if t_recall_1 > 0:
nest.Simulate(t_recall_1)
c_space.disinhibit()
nest.Simulate(t_recall_2)
t_recall_end = nest.GetKernelStatus()['time']
# ----------------------------------------------------------------------
# analysis
print('analysis')
if inhibit_V:
# make sure neural spaces are silent when they should be
spikes_nv = nest.GetStatus(n_space_v.spike_rec_E)[0]['events']['times']
spikes_nu = nest.GetStatus(n_space_u.spike_rec_E)[0]['events']['times']
delta = 50. # allow spikes in first 50 ms of each inhibited period
spikes_v_delay_1 = (spikes_nv > t_store_end+delta) & (spikes_nv < t_copy_start)
spikes_u_delay_1 = (spikes_nu > t_store_end+delta) & (spikes_nu < t_copy_start)
spikes_v_delay_2 = (spikes_nv > t_copy_end+delta) & (spikes_nv < t_recall_start)
spikes_u_delay_2 = (spikes_nu > t_copy_end+delta) & (spikes_nu < t_recall_start)
nspikes_v_d1 = sum(spikes_v_delay_1)
nspikes_u_d1 = sum(spikes_u_delay_1)
nspikes_v_d2 = sum(spikes_v_delay_2)
nspikes_u_d2 = sum(spikes_u_delay_2)
if nspikes_v_d1 > 0:
print('WARNING: spikes in V during delay period 1 (count: {0:d})'.format(nspikes_v_d1))
if nspikes_u_d1 > 0:
print('WARNING: spikes in U during delay period 1 (count: {0:d})'.format(nspikes_u_d1))
if nspikes_v_d2 > 0:
print('WARNING: spikes in V during delay period 2 (count: {0:d})'.format(nspikes_v_d2))
if nspikes_u_d2 > 0:
print('WARNING: spikes in U during delay period 2 (count: {0:d})'.format(nspikes_u_d2))
if nspikes_v_d1 == 0 and nspikes_u_d1 == 0 and \
nspikes_v_d2 == 0 and nspikes_u_d2 == 0:
print('neural inhibition ok.')
if plot:
c_weights = c_space.get_weights()
nv_weights = n_space_v.get_weights()
nu_weights = n_space_u.get_weights()
# assembly analysis
t_copy_start_U = t_copy_start + t_recall_1 + t_recall_2
arg = [
('a_test_C', c_space, t_test_start, t_test_end, False),
('a_store_C', c_space, [t_store_start], [t_store_end], False),
('a_store_V', n_space_v, [t_store_start], [t_store_end], False),
('a_copy_C', n_space_v, [t_copy_start], [t_copy_end], False),
('a_copy_V', n_space_v, [t_copy_start], [t_copy_end], False),
('a_copy_U', n_space_u, [t_copy_start_U], [t_copy_end], False),
('a_recall_C', c_space, [t_recall_start], [t_recall_end], False),
('a_recall_U', n_space_u, [t_recall_start], [t_recall_end], False)]
r = multi_assembly_analysis(arg)
a_test_C = r['a_test_C'][k_pattern]
a_store_C = r['a_store_C'][0]
a_store_V = r['a_store_V'][0]
a_copy_C = r['a_copy_C'][0]
a_copy_V = r['a_copy_V'][0]
a_copy_U = r['a_copy_U'][0]
a_recall_C = r['a_recall_C'][0]
a_recall_U = r['a_recall_U'][0]
# assembly match C: test vs. store
am_C_TS = assembly_match(a_test_C, a_store_C)
# assembly match C: test vs. copy
am_C_TC = assembly_match(a_test_C, a_copy_C)
# assembly match C: test vs. recall
am_C_TR = assembly_match(a_test_C, a_recall_C)
# assembly match V: store vs. copy
am_V_SC = assembly_match(a_store_V, a_copy_V)
# assembly match U: copy vs. recall
am_U_CR = assembly_match(a_copy_U, a_recall_U)
if print_results:
print('assembly match in C (test vs. recall): {} shared, {} only in test, {} only in recall'.format(*am_C_TR))
cost_c = am_C_TR[1] + am_C_TR[2]
# calculate success criterion
# if > threshold % of the test assembly are active, and if
# <= (100 - threshold) % are wrongly active, count as success
threshold = .8
if (am_C_TR[0] / len(a_test_C) > threshold) and \
(am_C_TR[2] / len(a_test_C) <= (1-threshold)):
success = True
else:
success = False
# check success with readout
t_lim = (t_recall_start, t_recall_end)
spikes_C = c_space.get_spikes(t_lim=t_lim)[0]
args = _C_readout_args.copy()
args['t_burn_in'] += t_recall_1
label = k_pattern
_, xt, yt = spikes_to_traces(spikes_C, c_space.pop_E, [(t_recall_start, t_recall_end, label)], **args)
readout_error = C_readout_test(xt, yt)
print('readout error', readout_error)
# save results
results = {
'a_test_C_size': len(a_test_C),
'a_store_C_size': len(a_store_C),
'a_store_V_size': len(a_store_V),
'a_copy_C_size': len(a_copy_C),
'a_copy_V_size': len(a_copy_V),
'a_copy_U_size': len(a_copy_U),
'a_recall_C_size': len(a_recall_C),
'a_recall_U_size': len(a_recall_U),
'match_C_TS_shared': am_C_TS[0],
'match_C_TS_missing': am_C_TS[1],
'match_C_TS_excess': am_C_TS[2],
'match_C_TC_shared': am_C_TC[0],
'match_C_TC_missing': am_C_TC[1],
'match_C_TC_excess': am_C_TC[2],
'match_C_TR_shared': am_C_TR[0],
'match_C_TR_missing': am_C_TR[1],
'match_C_TR_excess': am_C_TR[2],
'match_V_SC_shared': am_V_SC[0],
'match_V_SC_missing': am_V_SC[1],
'match_V_SC_excess': am_V_SC[2],
'match_U_CR_shared': am_U_CR[0],
'match_U_CR_missing': am_U_CR[1],
'match_U_CR_excess': am_U_CR[2],
'success': success,
'readout_error': readout_error,
}
# ----------------------------------------------------------------------
# plots
if plot:
plot_multi_weight_hist(c_weights, save=join(outdir, 'weights_C'))
plot_multi_weight_hist(nv_weights, save=join(outdir, 'weights_V'))
plot_multi_weight_hist(nu_weights, save=join(outdir, 'weights_U'))
t_store = [t_store_start, t_store_end]
t_copy = [t_copy_start, t_copy_end]
t_recall = [t_recall_start, t_recall_end]
# fancy plots
num = 200
targets_x = np.arange(num) + min(inpop.pop_X)
np.random.shuffle(targets_x)
targets_c = np.arange(num) + min(c_space.pop_E)
targets_v = np.arange(num) + min(n_space_v.pop_E)
targets_u = np.arange(num) + min(n_space_u.pop_E)
xlim = [t_store_start-50., t_recall_end]
markers = [t_store_start, t_store_end, t_copy_start, t_copy_end, t_recall_start]
labels = ['LOAD', 'DELAY', 'COPY', 'DELAY', 'RECALL']
xticks_labeled = [x for x in zip(markers, labels)]
xticks_unlabeled = []
plot_spikes_fancy(inpop.spike_rec, targets=targets_x, xlabel='time', ylabel='$\mathcal{X}$', xlim=xlim, markers=markers, xticks=xticks_labeled, wide=True, save=join(outdir, 'overview_X.pdf'))
plot_spikes_fancy(c_space.spike_rec_E, targets=targets_c, xlabel='', ylabel='$\mathcal{C}$', xlim=xlim, markers=markers, xticks=xticks_unlabeled, wide=True, save=join(outdir, 'overview_C.pdf'))
plot_spikes_fancy(n_space_v.spike_rec_E, targets=targets_v, xlabel='', ylabel='$\mathcal{N}_V$', xlim=xlim, markers=markers, xticks=xticks_unlabeled, wide=True, save=join(outdir, 'overview_V.pdf'))
plot_spikes_fancy(n_space_u.spike_rec_E, targets=targets_u, xlabel='', ylabel='$\mathcal{N}_U$', xlim=xlim, markers=markers, xticks=xticks_unlabeled, wide=True, save=join(outdir, 'overview_U.pdf'))
# debug: check all neurons for activity during DELAYs
plot_spikes_fancy(n_space_v.spike_rec_E, targets=None, xlabel='', ylabel='$\mathcal{N}_V$', xlim=xlim, markers=markers, xticks=xticks_unlabeled, wide=True)
plot_spikes_fancy(n_space_u.spike_rec_E, targets=None, xlabel='', ylabel='$\mathcal{N}_U$', xlim=xlim, markers=markers, xticks=xticks_unlabeled, wide=True)
# also save all spike data
spikes_X = inpop.get_spikes()
spikes_C = c_space.get_spikes()[0]
spikes_V = n_space_v.get_spikes()[0]
spikes_U = n_space_u.get_spikes()[0]
with open(join(outdir, 'all-spikes.pkl'), 'wb') as f:
I_pop_X = inpop.pop_X
C_pop_E = c_space.pop_E
V_pop_E = n_space_v.pop_E
U_pop_E = n_space_u.pop_E
pkl.dump([t_create_start, t_create_end, t_store_start, t_store_end,
t_copy_start, t_copy_end, t_recall_start, t_recall_end,
spikes_X, spikes_C, spikes_V, spikes_U, I_pop_X, C_pop_E,
V_pop_E, U_pop_E], f)
if not show:
plt.close('all')
return cost_c, results
def compare(outdir, swtafile, variant, config_c, config_v, recall_cfg, k_pattern_1=None, k_pattern_2=None, n_readout=1, print_results=True, plot=True, show=True):
# unpack input
inhibit_V = recall_cfg['inhibit_V']
t_store = recall_cfg['t_store']
t_recall_1 = recall_cfg['t_recall_1']
t_recall_2 = recall_cfg['t_recall_2']
dump_dict(config_v, ordered=True, key='config_v')
dump_dict(config_c, ordered=True, key='config_c')
# procedure:
#