-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutilis.py
2132 lines (1518 loc) · 68.5 KB
/
utilis.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
import nengo
import numpy as np
from numpy import random
import matplotlib.pyplot as plt
import matplotlib.cm as cm
# import tensorflow as tf
import os
from nengo.dists import Choice
from datetime import datetime
import pickle
from nengo.utils.matplotlib import rasterplot
plt.rcParams.update({'figure.max_open_warning': 0})
import time
from InputData import PresentInputWithPause
# from custom_rule import CustomRule
# from custom_rule import CustomRule_prev
# import nengo_ocl
from nengo.neurons import LIFRate
# from custom_rule import CustomRule
# from custom_rule import CustomRule_prev
from nengo.params import Parameter, NumberParam, FrozenObject
from nengo.dists import Choice, Distribution, get_samples, Uniform
from nengo.utils.numpy import clip, is_array_like
from nengo.connection import LearningRule
from nengo.builder import Builder, Operator, Signal
from nengo.builder.neurons import SimNeurons
from nengo.learning_rules import LearningRuleType
from nengo.builder.learning_rules import get_pre_ens,get_post_ens
from nengo.neurons import AdaptiveLIF
from nengo.synapses import Lowpass, SynapseParam
from nengo.params import (NumberParam,Default)
from nengo.dists import Choice
from nengo.utils.numpy import clip
import numpy as np
import random
import math
def evaluation(classes,n_neurons,presentation_time,spikes_layer1_probe,label_test_filtered,dt):
ConfMatrix = np.zeros((classes,n_neurons))
labels = np.zeros(n_neurons)
accuracy = np.zeros(n_neurons)
total = 0
Good = 0
Bad = 0
# confusion matrix
x = 0
for i in label_test_filtered:
tmp = spikes_layer1_probe[(x*presentation_time):(x+1)*presentation_time].sum(axis=0)
tmp[tmp < np.max(tmp)] = 0
tmp[tmp != 0] = 1
ConfMatrix[i] = ConfMatrix[i] + tmp
x = x + 1
Classes = dict()
for i in range(0,n_neurons):
Classes[i] = np.argmax(ConfMatrix[:,i])
x = 0
for i in label_test_filtered:
correct = False
tmp = spikes_layer1_probe[(x*presentation_time):(x+1)*presentation_time].sum(axis=0)
tmp[tmp < np.max(tmp)] = 0
tmp[tmp != 0] = 1
for index,l in enumerate(tmp):
if(l == 1):
correct = correct or (Classes[index] == i)
if(correct):
Good += 1
else:
Bad += 1
x = x + 1
total += 1
return Classes, round((Good * 100)/(Good+Bad),2)
def evaluation_v2(classes,n_neurons,presentation_time,spikes_layer1_probe_train,label_train_filtered,spikes_layer1_probe_test,label_test_filtered,dt):
ConfMatrix = np.zeros((classes,n_neurons))
labels = np.zeros(n_neurons)
accuracy = np.zeros(n_neurons)
total = 0
Good = 0
Bad = 0
# confusion matrix
x = 0
for i in label_train_filtered:
tmp = spikes_layer1_probe_train[(x*presentation_time):(x+1)*presentation_time].sum(axis=0)
tmp[tmp < np.max(tmp)] = 0
tmp[tmp != 0] = 1
ConfMatrix[i] = ConfMatrix[i] + tmp
x = x + 1
Classes = dict()
for i in range(0,n_neurons):
Classes[i] = np.argmax(ConfMatrix[:,i])
x = 0
for i in label_test_filtered:
correct = False
tmp = spikes_layer1_probe_test[(x*presentation_time):(x+1)*presentation_time].sum(axis=0)
tmp[tmp < np.max(tmp)] = 0
tmp[tmp != 0] = 1
for index,l in enumerate(tmp):
if(l == 1):
correct = correct or (Classes[index] == i)
if(correct):
Good += 1
else:
Bad += 1
x = x + 1
total += 1
return round((Good * 100)/(Good+Bad),2)
class MyLIF_in(LIFRate):
"""Spiking version of the leaky integrate-and-fire (LIF) neuron model.
Parameters
----------
tau_rc : float
Membrane RC time constant, in seconds. Affects how quickly the membrane
voltage decays to zero in the absence of input (larger = slower decay).
tau_ref : float
Absolute refractory period, in seconds. This is how long the
membrane voltage is held at zero after a spike.
min_voltage : float
Minimum value for the membrane voltage. If ``-np.inf``, the voltage
is never clipped.
amplitude : float
Scaling factor on the neuron output. Corresponds to the relative
amplitude of the output spikes of the neuron.
initial_state : {str: Distribution or array_like}
Mapping from state variables names to their desired initial value.
These values will override the defaults set in the class's state attribute.
"""
state = {
"voltage": Uniform(low=0, high=1),
"refractory_time": Choice([0]),
}
spiking = True
min_voltage = NumberParam("min_voltage", high=0)
def __init__(
self, tau_rc=0.02, tau_ref=0.002, min_voltage=0, amplitude=1, initial_state=None
):
super().__init__(
tau_rc=tau_rc,
tau_ref=tau_ref,
amplitude=amplitude,
initial_state=initial_state,
)
self.min_voltage = min_voltage
def step(self, dt, J, output, voltage, refractory_time):
# look these up once to avoid repeated parameter accesses
tau_rc = self.tau_rc
min_voltage = self.min_voltage
# reduce all refractory times by dt
refractory_time -= dt
# compute effective dt for each neuron, based on remaining time.
# note that refractory times that have completed midway into this
# timestep will be given a partial timestep, and moreover these will
# be subtracted to zero at the next timestep (or reset by a spike)
delta_t = clip((dt - refractory_time), 0, dt)
# update voltage using discretized lowpass filter
# since v(t) = v(0) + (J - v(0))*(1 - exp(-t/tau)) assuming
# J is constant over the interval [t, t + dt)
voltage -= (J - voltage) * np.expm1(-delta_t / tau_rc)
# determine which neurons spiked (set them to 1/dt, else 0)
spiked_mask = voltage > 1.8
output[:] = spiked_mask * (self.amplitude / dt)
# set v(0) = 1 and solve for t to compute the spike time
t_spike = dt + tau_rc * np.log1p(
-(voltage[spiked_mask] - 1) / (J[spiked_mask] - 1)
)
# set spiked voltages to zero, refractory times to tau_ref, and
# rectify negative voltages to a floor of min_voltage
voltage[voltage < min_voltage] = min_voltage
voltage[spiked_mask] = -1.8 #reset voltage
refractory_time[spiked_mask] = self.tau_ref + t_spike
def plan_MyLIF_in(
queue,
dt,
J,
V,
W,
outS,
ref,
tau,
amp,
N=None,
tau_n=None,
inc_n=None,
upsample=1,
fastlif=False,
**kwargs
):
adaptive = N is not None
assert J.ctype == "float"
for x in [V, W, outS]:
assert x.ctype == J.ctype
adaptive = False
fastlif = False
inputs = dict(J=J, V=V, W=W)
outputs = dict(outV=V, outW=W, outS=outS)
parameters = dict(tau=tau, ref=ref, amp=amp)
if adaptive:
assert all(x is not None for x in [N, tau_n, inc_n])
assert N.ctype == J.ctype
inputs.update(dict(N=N))
outputs.update(dict(outN=N))
parameters.update(dict(tau_n=tau_n, inc_n=inc_n))
dt = float(dt)
textconf = dict(
type=J.ctype,
dt=dt,
upsample=upsample,
adaptive=adaptive,
dtu=dt / upsample,
dtu_inv=upsample / dt,
dt_inv=1 / dt,
fastlif=fastlif,
)
decs = """
char spiked;
${type} dV;
const ${type} V_threshold = 1;
const ${type} dtu = ${dtu}, dtu_inv = ${dtu_inv}, dt_inv = ${dt_inv};
% if adaptive:
const ${type} dt = ${dt};
% endif
%if fastlif:
const ${type} delta_t = dtu;
%else:
${type} delta_t;
%endif
"""
# TODO: could precompute -expm1(-dtu / tau)
text = """
spiked = 0;
% for ii in range(upsample):
W -= dtu;
% if not fastlif:
delta_t = (W > dtu) ? 0 : (W < 0) ? dtu : dtu - W;
% endif
% if adaptive:
dV = -expm1(-delta_t / tau) * (J - N - V);
% else:
dV = -expm1(-delta_t / tau) * (J - V);
% endif
V += dV;
% if fastlif:
if (V < 0 || W > dtu)
V = 0;
else if (W >= 0)
V *= 1 - W * dtu_inv;
% endif
if (V > V_threshold) {
% if fastlif:
const ${type} overshoot = dtu * (V - V_threshold) / dV;
W = ref - overshoot + dtu;
% else:
const ${type} t_spike = dtu + tau * log1p(
-(V - V_threshold) / (J - V_threshold));
W = ref + t_spike;
% endif
V = 0;
spiked = 1;
}
% if not fastlif:
else if (V < 0) {
V = 0;
}
% endif
% endfor
outV = V;
outW = W;
outS = (spiked) ? amp*dt_inv : 0;
% if adaptive:
outN = N + (dt / tau_n) * (inc_n * outS - N);
% endif
"""
decs = as_ascii(Template(decs, output_encoding="ascii").render(**textconf))
text = as_ascii(Template(text, output_encoding="ascii").render(**textconf))
cl_name = "cl_alif" if adaptive else "cl_lif"
return _plan_template(
queue,
cl_name,
text,
declares=decs,
inputs=inputs,
outputs=outputs,
parameters=parameters,
**kwargs,
)
class MyLIF_in_v2(LIFRate):
"""Spiking version of the leaky integrate-and-fire (LIF) neuron model.
Parameters
----------
tau_rc : float
Membrane RC time constant, in seconds. Affects how quickly the membrane
voltage decays to zero in the absence of input (larger = slower decay).
tau_ref : float
Absolute refractory period, in seconds. This is how long the
membrane voltage is held at zero after a spike.
min_voltage : float
Minimum value for the membrane voltage. If ``-np.inf``, the voltage
is never clipped.
amplitude : float
Scaling factor on the neuron output. Corresponds to the relative
amplitude of the output spikes of the neuron.
initial_state : {str: Distribution or array_like}
Mapping from state variables names to their desired initial value.
These values will override the defaults set in the class's state attribute.
"""
state = {
"voltage": Uniform(low=0, high=1),
"refractory_time": Choice([0]),
}
spiking = True
min_voltage = NumberParam("min_voltage", high=0)
def __init__(
self, tau_rc=0.02, tau_ref=0.002, min_voltage=0, amplitude=1, initial_state=None
):
super().__init__(
tau_rc=tau_rc,
tau_ref=tau_ref,
amplitude=amplitude,
initial_state=initial_state,
)
self.min_voltage = min_voltage
def step(self, dt, J, output, voltage, refractory_time):
# look these up once to avoid repeated parameter accesses
tau_rc = self.tau_rc
min_voltage = self.min_voltage
# reduce all refractory times by dt
refractory_time -= dt
# compute effective dt for each neuron, based on remaining time.
# note that refractory times that have completed midway into this
# timestep will be given a partial timestep, and moreover these will
# be subtracted to zero at the next timestep (or reset by a spike)
delta_t = clip((dt - refractory_time), 0, dt)
# update voltage using discretized lowpass filter
# since v(t) = v(0) + (J - v(0))*(1 - exp(-t/tau)) assuming
# J is constant over the interval [t, t + dt)
voltage -= (J - voltage) * np.expm1(-delta_t / tau_rc)
# determine which neurons spiked (set them to 1/dt, else 0)
spiked_mask = voltage > 1
output[:] = spiked_mask * (self.amplitude / dt)
# set v(0) = 1 and solve for t to compute the spike time
t_spike = dt + tau_rc * np.log1p(
-(voltage[spiked_mask] - 1) / (J[spiked_mask] - 1)
)
# set spiked voltages to zero, refractory times to tau_ref, and
# rectify negative voltages to a floor of min_voltage
voltage[voltage < min_voltage] = min_voltage
voltage[spiked_mask] = -1 #reset voltage
refractory_time[spiked_mask] = self.tau_ref + t_spike
class MyLIF_out(LIFRate):
"""Spiking version of the leaky integrate-and-fire (LIF) neuron model.
Parameters
----------
tau_rc : float
Membrane RC time constant, in seconds. Affects how quickly the membrane
voltage decays to zero in the absence of input (larger = slower decay).
tau_ref : float
Absolute refractory period, in seconds. This is how long the
membrane voltage is held at zero after a spike.
min_voltage : float
Minimum value for the membrane voltage. If ``-np.inf``, the voltage
is never clipped.
amplitude : float
Scaling factor on the neuron output. Corresponds to the relative
amplitude of the output spikes of the neuron.
initial_state : {str: Distribution or array_like}
Mapping from state variables names to their desired initial value.
These values will override the defaults set in the class's state attribute.
"""
state = {
"voltage": Uniform(low=0, high=1),
"refractory_time": Choice([0]),
}
spiking = True
min_voltage = NumberParam("min_voltage", high=0)
def __init__(
self, tau_rc=0.02, tau_ref=0.002, min_voltage=0, amplitude=1, initial_state=None, inhib=[]
):
super().__init__(
tau_rc=tau_rc,
tau_ref=tau_ref,
amplitude=amplitude,
initial_state=initial_state,
)
self.min_voltage = min_voltage
self.inhib = inhib
def step(self, dt, J, output, voltage, refractory_time):
# look these up once to avoid repeated parameter accesses
tau_rc = self.tau_rc
min_voltage = self.min_voltage
# reduce all refractory times by dt
refractory_time -= dt
# compute effective dt for each neuron, based on remaining time.
# note that refractory times that have completed midway into this
# timestep will be given a partial timestep, and moreover these will
# be subtracted to zero at the next timestep (or reset by a spike)
delta_t = clip((dt - refractory_time), 0, dt)
# update voltage using discretized lowpass filter
# since v(t) = v(0) + (J - v(0))*(1 - exp(-t/tau)) assuming
# J is constant over the interval [t, t + dt)
voltage -= (J - voltage) * np.expm1(-delta_t / tau_rc)
# determine which neurons spiked (set them to 1/dt, else 0)
spiked_mask = voltage > 1
output[:] = spiked_mask * (self.amplitude / dt)
if(np.sum(output)!=0):
voltage[voltage != np.max(voltage)] = 0 #WTA
# set v(0) = 1 and solve for t to compute the spike time
t_spike = dt + tau_rc * np.log1p(
-(voltage[spiked_mask] - 1) / (J[spiked_mask] - 1)
)
# set spiked voltages to zero, refractory times to tau_ref, and
# rectify negative voltages to a floor of min_voltage
voltage[voltage < min_voltage] = min_voltage
voltage[spiked_mask] = -1
refractory_time[spiked_mask] = self.tau_ref + t_spike
# def fun_post_baseline(X,
# alpha=1,lr=1,dead_zone=0,multiplicative=1
# ):
# w, vmem = X
# vapp = -vmem
# # multiplicative = 1
# f_pot = (np.exp(-alpha*(w))*(-w+ 1))*multiplicative
# f_dep = (np.exp(alpha*(w-1))*w)*multiplicative
# cond_pot = vapp > dead_zone
# cond_dep = vapp < -dead_zone
# exp_vapp = np.exp(vapp-dead_zone)
# g_pot = exp_vapp-1
# g_dep = (1/exp_vapp)-1
# # g_pot = np.exp(vapp)-1
# # g_dep = np.exp(-vapp)-1
# dW = (cond_pot*f_pot*g_pot - cond_dep*f_dep*g_dep)*lr
# return dW
def fun_post_baseline(X,
alpha=1,lr=1
):
w, vmem = X
f_pot = 1-w
f_dep = w
cond_pot = vmem < 0
cond_dep = vmem > 0
exp_vapp = np.exp(-vmem)
g_pot = exp_vapp-1
g_dep = (1/exp_vapp)-1
dW = (cond_pot*f_pot*g_pot - cond_dep*f_dep*g_dep)*lr
return dW
def fun_post_baseline_lite(X,
lr=1
):
w, vmem = X
vapp = -vmem
cond_pot = vapp > 0
cond_dep = vapp < 0
exp_vapp = np.exp(vapp)
g_pot = exp_vapp-1
g_dep = (1/exp_vapp)-1
dW = (cond_pot*g_pot - cond_dep*g_dep)*lr
return dW
class CustomRule_post_baseline(nengo.Process):
def __init__(self,winit_min=0, winit_max=1, sample_distance = 1, lr=6.0e-05, alpha=2):
self.signal_vmem_pre = None
self.signal_out_post = None
self.winit_min = winit_min
self.winit_max = winit_max
self.alpha = alpha
self.sample_distance = sample_distance
self.lr = lr
# self.multiplicative = multiplicative
# self.dead_zone = dead_zone
self.history = [0]
# self.tstep=0 #Just recording the tstep to sample weights. (To save memory)
super().__init__()
def make_step(self, shape_in, shape_out, dt, rng, state=None):
self.w = np.random.uniform(self.winit_min, self.winit_max, (shape_out[0], shape_in[0]))
def step(t, x):
assert self.signal_vmem_pre is not None
assert self.signal_out_post is not None
post_out = self.signal_out_post
vmem = np.reshape(self.signal_vmem_pre, (1, shape_in[0]))
post_out_matrix = np.reshape(post_out, (shape_out[0], 1))
self.w = np.clip((self.w + dt*(fun_post_baseline((self.w,vmem),self.alpha,self.lr))*post_out_matrix), 0, 1)
self.history[0] = self.w.copy()
return np.dot(self.w, x*dt)
return step
def set_signal_vmem(self, signal):
self.signal_vmem_pre = signal
def set_signal_out(self, signal):
self.signal_out_post = signal
class CustomRule_post_baseline_lite(nengo.Process):
def __init__(self,winit_min=0, winit_max=1, sample_distance = 1, lr=6.0e-05):
self.signal_vmem_pre = None
self.signal_out_post = None
self.winit_min = winit_min
self.winit_max = winit_max
# self.alpha = alpha
self.sample_distance = sample_distance
self.lr = lr
# self.multiplicative = multiplicative
# self.dead_zone = dead_zone
self.history = [0]
# self.tstep=0 #Just recording the tstep to sample weights. (To save memory)
super().__init__()
def make_step(self, shape_in, shape_out, dt, rng, state=None):
self.w = np.random.uniform(self.winit_min, self.winit_max, (shape_out[0], shape_in[0]))
def step(t, x):
assert self.signal_vmem_pre is not None
assert self.signal_out_post is not None
post_out = self.signal_out_post
vmem = np.reshape(self.signal_vmem_pre, (1, shape_in[0]))
post_out_matrix = np.reshape(post_out, (shape_out[0], 1))
self.w = np.clip((self.w + dt*(fun_post_baseline((self.w,vmem),self.lr))*post_out_matrix), 0, 1)
self.history[0] = self.w.copy()
return np.dot(self.w, x*dt)
return step
def set_signal_vmem(self, signal):
self.signal_vmem_pre = signal
def set_signal_out(self, signal):
self.signal_out_post = signal
def fun_post(X,
alphap=1,alphan=5,Ap=4000,An=4000,eta=1
):
w, vmem, vprog, vthp,vthn = X
# vthp=0.16
# vthn=0.15
# vprog=0
xp=0.3
xn=0.5
vapp = vprog-vmem
cond_pot_fast = w<xp
cond_pot_slow = 1-cond_pot_fast
cond_dep_fast = w>(1-xn)
cond_dep_slow = 1-cond_dep_fast
f_pot = (np.exp(-alphap*(w-xp))*((xp-w)/(1-xp) + 1))*cond_pot_slow + cond_pot_fast
f_dep = (np.exp(alphan*(w+xn-1))*w/(1-xn))*cond_dep_slow + cond_dep_fast
cond_pot = vapp > vthp
cond_dep = vapp < -vthn
g_pot = Ap*(np.exp(vapp)-np.exp(vthp))
g_dep = -An*(np.exp(-vapp)-np.exp(vthn))
dW = (cond_pot*f_pot*g_pot + cond_dep*f_dep*g_dep)*eta
return dW
popt = np.array((1.00006690e+00, 5.00098722e+00, 1.27251859e-05, 1.27251790e-05,
6.28659913e+00))
#The above popt is for Tpw = 20n, maximum dw=0.0001. Use lr=1
def fun_post_var(X,
alphap=1,alphan=5,Ap=4000,An=4000,eta=1
):
w, vmem, vprog, vthp,vthn,var_amp_1,var_amp_2 = X
# vthp=0.16
# vthn=0.15
# vprog=0
xp=0.3
xn=0.5
vapp = vprog-vmem
Ap = var_amp_1*Ap
An = var_amp_2*An
cond_pot_fast = w<xp
cond_pot_slow = 1-cond_pot_fast
cond_dep_fast = w>(1-xn)
cond_dep_slow = 1-cond_dep_fast
f_pot = (np.exp(-alphap*(w-xp))*((xp-w)/(1-xp) + 1))*cond_pot_slow + cond_pot_fast
f_dep = (np.exp(alphan*(w+xn-1))*w/(1-xn))*cond_dep_slow + cond_dep_fast
cond_pot = vapp > vthp
cond_dep = vapp < -vthn
g_pot = Ap*(np.exp(vapp)-np.exp(vthp))
g_dep = -An*(np.exp(-vapp)-np.exp(vthn))
dW = (cond_pot*f_pot*g_pot + cond_dep*f_dep*g_dep)*eta
return dW
popt = np.array((1.00220687e+00, 5.01196597e+00, -3.54137489e-03, -3.54157996e-03,
-2.25853150e-01))
def fun_post_tio2(X,
alphap=1,alphan=5,Ap=4000,An=4000,eta=1,
# a1=1,a2=1,a3=1,a4=1
):
w, vmem, vprog, vthp, vthn, voltage_clip_max, voltage_clip_min, Vapp_multiplier = X
# vthp=0.5
# vthn=0.5
# vprog=0
xp=0.01
xn=0.01
# vapp = (vprog-vmem)*(1+w*Vapp_multiplier)
vapp = (vprog-vmem)*Vapp_multiplier
vapp = np.clip(vapp, voltage_clip_min, voltage_clip_max)
cond_pot_fast = w<xp
cond_pot_slow = 1-cond_pot_fast
cond_dep_fast = w>(1-xn)
cond_dep_slow = 1-cond_dep_fast
f_pot = cond_pot_fast + cond_pot_slow*(np.exp(-alphap*(w-xp))*((xp-w)/(1-xp) + 1))
f_dep = (np.exp(alphan*(w+xn-1))*w/(1-xn))*cond_dep_slow + cond_dep_fast
cond_pot = vapp > vthp
cond_dep = vapp < -vthn
g_pot = Ap*(np.exp(vapp)-np.exp(vthp))
g_dep = -An*(np.exp(-vapp)-np.exp(vthn))
dW = (cond_pot*f_pot*g_pot + cond_dep*f_dep*g_dep)*eta
return dW
# parameter for TiO2 with 0.5 threshold and 77.07 accuracy
popt_tio2 = np.array((1.62708935, 2.1204144 , 0.044, 0.07223655, 0.95411709))
# popt_tio2 = np.array((0.86066859, 1.28831255, 0.44703269, 0.21166331, 0.80906049))
def fun_post_tio2_var(X,
alphap=1,alphan=5,Ap=4000,An=4000,eta=1,
# a1=1,a2=1,a3=1,a4=1
):
w, vmem, vprog, vthp, vthn, var_amp_1, var_amp_2, voltage_clip_max, voltage_clip_min = X
# vthp=0.5
# vthn=0.5
# vprog=0
xp=0.01
xn=0.01
Ap = var_amp_1*Ap
An = var_amp_2*An
vapp = vprog-vmem
vapp = np.clip(vapp, voltage_clip_min, voltage_clip_max)
cond_pot_fast = w<xp
cond_pot_slow = 1-cond_pot_fast
cond_dep_fast = w>(1-xn)
cond_dep_slow = 1-cond_dep_fast
f_pot = cond_pot_fast + cond_pot_slow*(np.exp(-alphap*(w-xp))*((xp-w)/(1-xp) + 1))
f_dep = (np.exp(alphan*(w+xn-1))*w/(1-xn))*cond_dep_slow + cond_dep_fast
cond_pot = vapp > vthp
cond_dep = vapp < -vthn
g_pot = Ap*(np.exp(vapp)-np.exp(vthp))
g_dep = -An*(np.exp(-vapp)-np.exp(vthn))
dW = (cond_pot*f_pot*g_pot + cond_dep*f_dep*g_dep)*eta
return dW
def fun_post_tio2_var_th(X,
alphap=1,alphan=5,Ap=4000,An=4000,eta=1,
# a1=1,a2=1,a3=1,a4=1
):
w, vmem, vprog, vthp, vthn, var_th_1, var_th_2, voltage_clip_max, voltage_clip_min = X
# vthp=0.5
# vthn=0.5
# vprog=0
xp=0.01
xn=0.01
vthp = var_th_1*vthp
vthn = var_th_2*vthn
vapp = vprog-vmem
vapp = np.clip(vapp, voltage_clip_min, voltage_clip_max)
cond_pot_fast = w<xp
cond_pot_slow = 1-cond_pot_fast
cond_dep_fast = w>(1-xn)
cond_dep_slow = 1-cond_dep_fast
f_pot = cond_pot_fast + cond_pot_slow*(np.exp(-alphap*(w-xp))*((xp-w)/(1-xp) + 1))
f_dep = (np.exp(alphan*(w+xn-1))*w/(1-xn))*cond_dep_slow + cond_dep_fast
cond_pot = vapp > vthp
cond_dep = vapp < -vthn
g_pot = Ap*(np.exp(vapp)-np.exp(vthp))
g_dep = -An*(np.exp(-vapp)-np.exp(vthn))
dW = (cond_pot*f_pot*g_pot + cond_dep*f_dep*g_dep)*eta
return dW
def fun_post_tio2_var_v2(X,
alphap=1,alphan=5,Ap=4000,An=4000,eta=1,
# a1=1,a2=1,a3=1,a4=1
):
w, vmem, vprog, vthp, vthn, var_amp_1, var_amp_2, var_vthp, var_vthn, voltage_clip_max, voltage_clip_min = X
# vthp=0.5
# vthn=0.5
# vprog=0
xp=0.01
xn=0.01
Ap = var_amp_1*Ap
An = var_amp_2*An
vthp = var_vthp*vthp
vthn = var_vthn*vthn
vapp = vprog-vmem
vapp = np.clip(vapp, voltage_clip_min, voltage_clip_max)
cond_pot_fast = w<xp
cond_pot_slow = 1-cond_pot_fast
cond_dep_fast = w>(1-xn)
cond_dep_slow = 1-cond_dep_fast
f_pot = cond_pot_fast + cond_pot_slow*(np.exp(-alphap*(w-xp))*((xp-w)/(1-xp) + 1))
f_dep = (np.exp(alphan*(w+xn-1))*w/(1-xn))*cond_dep_slow + cond_dep_fast
cond_pot = vapp > vthp
cond_dep = vapp < -vthn
g_pot = Ap*(np.exp(vapp)-np.exp(vthp))
g_dep = -An*(np.exp(-vapp)-np.exp(vthn))
dW = (cond_pot*f_pot*g_pot + cond_dep*f_dep*g_dep)*eta
return dW
class CustomRule_post_v2_tio2(nengo.Process):
def __init__(self, vprog=0,winit_min=0, winit_max=1, sample_distance = 1, lr=1,vthp=0.5,vthn=0.5,gmax=0.0008,gmin=0.00008,vprog_increment=0,voltage_clip_max=None,voltage_clip_min=None,Vapp_multiplier=0):
self.vprog = vprog
self.signal_vmem_pre = None
self.signal_out_post = None
self.winit_min = winit_min
self.winit_max = winit_max
self.sample_distance = sample_distance
self.lr = lr
self.vthp = vthp
self.vthn = vthn
self.gmax=gmax
self.gmin = gmin
self.history = [0]
self.voltage_clip_min=voltage_clip_min
self.voltage_clip_max=voltage_clip_max
self.vprog_increment=vprog_increment
self.Vapp_multiplier = Vapp_multiplier
# self.tstep=0 #Just recording the tstep to sample weights. (To save memory)
super().__init__()
def make_step(self, shape_in, shape_out, dt, rng, state=None):
self.w = np.random.uniform(self.winit_min, self.winit_max, (shape_out[0], shape_in[0]))
def step(t, x):
assert self.signal_vmem_pre is not None
assert self.signal_out_post is not None
# vmem = np.clip(self.signal_vmem_pre, -1, 1)
post_out = self.signal_out_post
vmem = np.reshape(self.signal_vmem_pre, (1, shape_in[0]))
post_out_matrix = np.reshape(post_out, (shape_out[0], 1))
self.w = np.clip((self.w + dt*(fun_post_tio2((self.w,vmem, self.vprog, self.vthp,self.vthn,self.voltage_clip_max,self.voltage_clip_min,self.Vapp_multiplier),*popt_tio2))*post_out_matrix*self.lr), 0, 1)
post_spiked = post_out_matrix*dt
self.vprog += post_spiked*self.vprog_increment
self.vprog = np.clip(self.vprog, None, 0)
# if (self.tstep%self.sample_distance ==0):
# self.history.append(self.w.copy())
# self.tstep +=1
self.history[0] = self.w.copy()
# self.history.append(self.w.copy())
# self.history = self.history[-2:]
# self.history = self.w
return np.dot((self.w*(self.gmax-self.gmin)) + self.gmin, x)
return step
# self.current_weight = self.w
def set_signal_vmem(self, signal):
self.signal_vmem_pre = signal
def set_signal_out(self, signal):
self.signal_out_post = signal
class CustomRule_post_v2_tio2_gaussian(nengo.Process):
def __init__(self, vprog=0,winit_mean=5, winit_dev=0.5, sample_distance = 1, lr=1,vthp=0.5,vthn=0.5,gmax=0.0008,gmin=0.00008,vprog_increment=0,voltage_clip_max=None,voltage_clip_min=None,Vapp_multiplier=0):
self.vprog = vprog
self.signal_vmem_pre = None
self.signal_out_post = None
self.winit_mean = winit_mean
self.winit_dev = winit_dev
self.sample_distance = sample_distance
self.lr = lr
self.vthp = vthp
self.vthn = vthn
self.gmax=gmax
self.gmin = gmin
self.history = [0]
self.voltage_clip_min=voltage_clip_min
self.voltage_clip_max=voltage_clip_max
self.vprog_increment=vprog_increment
self.Vapp_multiplier = Vapp_multiplier
# self.tstep=0 #Just recording the tstep to sample weights. (To save memory)
super().__init__()
def make_step(self, shape_in, shape_out, dt, rng, state=None):
self.w = np.random.normal(self.winit_mean, self.winit_dev, (shape_out[0], shape_in[0]))
self.w = np.clip(self.w,0,1)
def step(t, x):
assert self.signal_vmem_pre is not None
assert self.signal_out_post is not None
# vmem = np.clip(self.signal_vmem_pre, -1, 1)
post_out = self.signal_out_post
vmem = np.reshape(self.signal_vmem_pre, (1, shape_in[0]))
post_out_matrix = np.reshape(post_out, (shape_out[0], 1))
self.w = np.clip((self.w + dt*(fun_post_tio2((self.w,vmem, self.vprog, self.vthp,self.vthn,self.voltage_clip_max,self.voltage_clip_min,self.Vapp_multiplier),*popt_tio2))*post_out_matrix*self.lr), 0, 1)
post_spiked = post_out_matrix*dt
self.vprog += post_spiked*self.vprog_increment
self.vprog = np.clip(self.vprog, None, 0)
# if (self.tstep%self.sample_distance ==0):
# self.history.append(self.w.copy())
# self.tstep +=1
self.history[0] = self.w.copy()
# self.history.append(self.w.copy())
# self.history = self.history[-2:]
# self.history = self.w
return np.dot((self.w*(self.gmax-self.gmin)) + self.gmin, x)
return step
# self.current_weight = self.w
def set_signal_vmem(self, signal):