-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathinput_rec_transform_nengo_plot_figs.py
2471 lines (2292 loc) · 158 KB
/
input_rec_transform_nengo_plot_figs.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 numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.patheffects as mpl_pe
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.patches as patches
from plot_utils import *
import os.path
#from nengo.utils.matplotlib import rasterplot
#import pickle
import shelve, contextlib
datapath = '../lcncluster/paper_data_final/'
#datapath = '../data/'
#datapath = '../data_draft4/'
# set seed for selecting random weight indices
np.random.seed([1])
def plot_learnt_data(axlist,dataFileName,N,errFactor,plotvars=[],addTime=0.,phaseplane=False):
# with ensures that the file is closed at the end / if error
with contextlib.closing(
shelve.open(datapath+dataFileName, 'r')
) as data_dict:
trange = data_dict['trange']
Tmax = data_dict['Tmax']
rampT = data_dict['rampT']
Tperiod = data_dict['Tperiod']
if Tperiod>20.: Tperiod = 20. # for Lorenz testing, Tperiod = 200., but we plot less
dt = data_dict['dt']
tau = data_dict['tau']
errorLearning = data_dict['errorLearning']
spikingNeurons = data_dict['spikingNeurons']
trange = data_dict['trange']+addTime
if 'start' in dataFileName:
tstart = 0
tend = int(2*Tperiod/dt) # Tnolearning = 4*Tperiod
#if 'robot2' in dataFileName: tend *= 2
trange = trange[:tend] # data only for saved period
else:
tstart = -int(5*Tperiod/dt) # (Tnolearning + Tperiod) if Tmax allows at least one noFlush Tperiod
# (2*Tnolearning) if Tmax doesn't allow at least one noFlush Tperiod
tend = int(2*Tperiod/dt)
#if 'robot2' in dataFileName: tend *= 2
trange = trange[tstart:tstart+tend] # data only for saved period
if 'robot2' in dataFileName:
u = data_dict['ratorOut']
else:
u = data_dict['nodeIn']
y = data_dict['ratorOut']
y2 = data_dict['ratorOut2']
if errorLearning:
recurrentLearning = data_dict['recurrentLearning']
copycatLayer = data_dict['copycatLayer']
if recurrentLearning and copycatLayer:
yExpect = data_dict['yExpectRatorOut']
else:
## rateEvolve is stored for the full time,
## so take only end part similar to yExpectRatorOut
#yExpect = data_dict['rateEvolve'][tstart:]
yExpect = -data_dict['rateEvolveFiltered'] # filtered rateEvolve given wih -ve sign to error Node
errWt = data_dict['error_p']
err = -data_dict['error'] # Definition of error in paper is now ref-pred, hence -ve here
# error is not flushed, so it contains the full time. Take only the relevant part.
if 'start' in dataFileName: err = err[:tend,:]
else: err = err[tstart:tstart+tend,:]
# am plotting the actual first in red and then reference in width/1.5 after in blue, so that both are visible
if len(plotvars)==0: plotvars = [0]#range(N)
for axi,i in enumerate(plotvars):
# CAUTION -- replace this ratorOut (has extra filtering and spiking noise) soon by nodeIn
if 'robot2' in dataFileName:
# for y2: 0,1 are angles, 2,3 are velocities and 4,5 are torques
#axlist[axi].plot(trange, y2[:tend,5], color='r', linewidth=plot_linewidth, label='\hat{tau}')
axlist[axi].plot(trange, u[:tend,1], color='b', linewidth=plot_linewidth/1.5, label='\tau')
axlist[axi+1].plot(trange, y2[:tend,3], color='r', linewidth=plot_linewidth, linestyle='dotted', label='$\hat{\omega}$')
axlist[axi+1].plot(trange, yExpect[:tend,3], color='b', linewidth=plot_linewidth/1.5, linestyle='dotted', label='$\omega$')
axlist[axi+1].plot(trange, y2[:tend,1], color='r', linewidth=plot_linewidth, label='$\hat{\theta}$')
axlist[axi+1].plot(trange, yExpect[:tend,1], color='b', linewidth=plot_linewidth/1.5, label='$\theta$')
if not phaseplane:
axlist[axi+2].plot(trange, err[:,1]*errFactor, color='k', linewidth=plot_linewidth/2., label='err')
phaseboxesTime = None
else:
axlist[axi].plot(trange, u[:tend,i],color='b', linewidth=plot_linewidth, label=' in')
if '_nonlin' in dataFileName:
reprRadius = 1.0
# /20 is just for plotting, scales the non-linear transform to fit within reprRadiusIn
u_nonlin = 5.*2.*((u/0.1/reprRadius)**3 - u/0.4/reprRadius)[:tend,i]
axlist[axi].plot(trange, u_nonlin/20., color='c', linewidth=plot_linewidth, label=' in-nonlin')
phaseboxesTime = None
elif 'Lorenz' in dataFileName:
phaseboxesTime = ((20.,30.),)
phaseboxesHeightTop = 20.
phaseboxesHeightBottom = -25.
elif 'vanderPol' in dataFileName:
phaseboxesTime = ((1.,2.),(5.,7.))
phaseboxesHeightTop = 5.
phaseboxesHeightBottom = -5.
else:
phaseboxesTime = None
axlist[axi+1].plot(trange, y2[:tend,i], color='r', linewidth=plot_linewidth, label=' out')
axlist[axi+1].plot(trange, yExpect[:tend,i], color='b', linewidth=plot_linewidth/1.5, label='ref')
## error is forced zero after learning, so instead of using probed error above; compute the error
## errorWt is 200ms filtered (error for weights update);
## trying to filter the error as it would be in the simulation, but not very effective!
## also requires an *2 after normalization by tau_s. why?
#tau_s = 0.02
#tau_wt = 0.2
#expi = np.convolve(yExpect[:tend,i],np.array([np.exp(-t/tau_s) for t in trange-trange[0]])*tau_s*2,mode='full')[:tend]
#erri = np.convolve(y2[:tend,i]-expi,np.array([np.exp(-t/tau_wt) for t in trange-trange[0]])*tau_wt*2,mode='full')[:tend]
if not phaseplane:
axlist[axi+2].plot(trange, err[:,i]*errFactor, color='k', linewidth=plot_linewidth/2., label='err')
# phase plane plot
if phaseplane:
colors = ['b','c']
if phaseboxesTime is not None:
for i,(t1,t2) in enumerate(phaseboxesTime):
# put a box on axes above that shows which time is shown in phase plot below
axlist[axi+1].add_patch(
patches.Rectangle(
(t1, phaseboxesHeightBottom), # (x,y)
t2-t1, # width
phaseboxesHeightTop-phaseboxesHeightBottom,
# height
fill=False,color=colors[i]) )
axlist[axi+1].text(t2+0.1,phaseboxesHeightTop*0.8,['$\star$','$\diamond$'][i],color=colors[i])
for i,(t1,t2) in enumerate(phaseboxesTime):
# plot 2D phase plane curve
tstartidx = int(t1/dt)
tendidx = int(t2/dt)
if i%2==0: colorslist = ['b','r']
else: colorslist = ['c','m']
axlist[axi+2].plot(yExpect[tstartidx:tendidx,1],yExpect[tstartidx:tendidx,0],\
linewidth=plot_linewidth, color=colorslist[0]) # reference
axlist[axi+2].plot(y2[tstartidx:tendidx,1],y2[tstartidx:tendidx,0],\
linewidth=plot_linewidth, color=colorslist[1]) # predicted
else: # plot for full time (see tstart, tend above) that is plotted in subplots A,B above
axlist[axi+2].plot(yExpect[tstart:tend,1],yExpect[tstart:tend,0],\
linewidth=plot_linewidth, color='b') # reference
axlist[axi+2].plot(y2[tstart:tend,1],y2[tstart:tend,0],\
linewidth=plot_linewidth, color='r') # predicted
points_per_bin = int(0.1/dt) # choose the bin size for the mean in mean squared error
## mean squared error per dimension per second (last .mean(axis=1) is for 1 dt, hence /dt to get per second)
#axlist[i+3].plot(trange[::points_per_bin], np.sum(err**2,axis=1).reshape(-1,points_per_bin).mean(axis=1)/N/dt,\
# color='k', linewidth=plot_linewidth/2.)
def plot_error_fulltime(ax,dataFileName,startT=0.,color='k'):
if isinstance(dataFileName, list):
dataFileNames = [(dataFileName[0],0.)]
if 'continueFrom' in dataFileName[-1]:
breakFile = dataFileName[-1].split("continueFrom",1)
breakFile_ = breakFile[1].split("_",1)
breakFileSeed = breakFile_[1].split("seed",1)
breakFileby = breakFileSeed[1].split("by",1)
addTime = np.float(breakFile_[0])
seedIn = 3
if '_g2' in dataFileName[-1]: fileTstep = 1000.0
else: fileTstep = 10000.0
for addT in np.arange(fileTstep,addTime-1,fileTstep):
intermediateFileName = breakFile[0]+'continueFrom'+str(addT)+\
'_'+breakFileSeed[0]+'seed'+str(seedIn)+'by'+breakFileby[1]
print(intermediateFileName)
if os.path.exists(datapath+intermediateFileName+'_end.shelve'):
dataFileNames.append((intermediateFileName,addT))
seedIn += 1
dataFileNames.append((dataFileName[-1],addTime))
else: addTime = 0.
else: dataFileNames = [(dataFileName,startT)]
for dataFileName,startT in dataFileNames:
print(dataFileName)
# with ensures that the file is closed at the end / if error
with contextlib.closing(
shelve.open(datapath+dataFileName+'_end.shelve', 'r')
) as data_dict:
trange = data_dict['trange']
Tmax = data_dict['Tmax']
Tperiod = data_dict['Tperiod']
dt = data_dict['dt']
errWt = data_dict['error_p'] # filtered error for weight update
N = errWt.shape[1] # number of error dimensions
# remove the end Tnolearning period where error is forced to zero
# remove the start Tperiod where error is forced to zero
Tnolearning = 4*Tperiod
Tmax = Tmax - Tnolearning - Tperiod
trange = trange[int(Tperiod/dt):-int(Tnolearning/dt)]
errWt = errWt[int(Tperiod/dt):-int(Tnolearning/dt)]
# bin squared error into every Tperiod
points_per_bin = int(Tperiod/dt)
# in the _end.shelve, error is available for the full time (not flushed)
# mean squared error, with mean over dimensions and over time
# note: dt doesn't appear, as dt in denominator is cancelled by dt in integral in numerator
mse = np.mean(errWt**2,axis=1).reshape(-1,points_per_bin).mean(axis=1)
ax.plot(trange[::points_per_bin]+startT, mse, color=color, linewidth=plot_linewidth)
ax.set_yscale('log')
#ax.set_ylim([ax.get_ylim()[0],0.1])
print('Error in first few Tperiods with feedback is',mse[:5])
def plot_phaseplane2D(axlist,dataFileName):
# with ensures that the file is closed at the end / if error
with contextlib.closing(
shelve.open(dataFileName, 'r')
) as data_dict:
trange = data_dict['trange']
Tmax = data_dict['Tmax']
rampT = data_dict['rampT']
Tperiod = data_dict['Tperiod']
dt = data_dict['dt']
tau = data_dict['tau']
errorLearning = data_dict['errorLearning']
spikingNeurons = data_dict['spikingNeurons']
y2 = data_dict['ratorOut2']
if errorLearning:
recurrentLearning = data_dict['recurrentLearning']
copycatLayer = data_dict['copycatLayer']
if recurrentLearning and copycatLayer:
yExpect = data_dict['yExpectRatorOut']
else:
# rateEvolve is stored for the full time,
# so take only end part similar to yExpectRatorOut
yExpect = data_dict['rateEvolve'][-int(5*Tperiod/dt):]
err = data_dict['error_p']
tstartidx = int(Tperiod/dt) # learning stops after a Tperiod in the _end data
if 'robot' in dataFileName: tduration = int(3*Tperiod/dt)
else: tduration = int(Tperiod/dt)
if axlist[0]==axlist[1]: colorslist = ['b','r']
else: colorslist = ['k','k']
axlist[0].plot(yExpect[tstartidx:tstartidx+tduration,0],yExpect[tstartidx:tstartidx+tduration,1],\
linewidth=plot_linewidth, color=colorslist[0])
axlist[1].plot(y2[tstartidx:tstartidx+tduration,0],y2[tstartidx:tstartidx+tduration,1],\
linewidth=plot_linewidth, color=colorslist[1])
def plot_Lorenz(axlist,dataFileName):
# with ensures that the file is closed at the end / if error
with contextlib.closing(
shelve.open(dataFileName, 'r')
) as data_dict:
trange = data_dict['trange']
Tmax = data_dict['Tmax']
rampT = data_dict['rampT']
Tperiod = 20.#data_dict['Tperiod']
dt = data_dict['dt']
tau = data_dict['tau']
errorLearning = data_dict['errorLearning']
spikingNeurons = data_dict['spikingNeurons']
y2 = data_dict['ratorOut2']
if errorLearning:
recurrentLearning = data_dict['recurrentLearning']
copycatLayer = data_dict['copycatLayer']
if recurrentLearning and copycatLayer:
yExpect = data_dict['yExpectRatorOut']
else:
# rateEvolve is stored for the full time,
# so take only end part similar to yExpectRatorOut
yExpect = data_dict['rateEvolve'][-int(5*Tperiod/dt):]
err = data_dict['error_p']
tstartidx = -int(3*Tperiod/dt) # no learning in last 4 Tperiods in the _end data
tendidx = -int(1*Tperiod/dt) # 2*Tperiods of plotting
axlist[0].plot(yExpect[tstartidx:tendidx,0],yExpect[tstartidx:tendidx,1],yExpect[tstartidx:tendidx,2],\
linewidth=plot_linewidth, color='b')
axlist[1].plot(y2[tstartidx:tendidx,0],y2[tstartidx:tendidx,1],y2[tstartidx:tendidx,2],\
linewidth=plot_linewidth, color='r')
def plot_current_weights(axlist,dataFileName,wtFactor,wtHistFact):
print('reading _weights')
if axlist[0] is None:
if 'continueFrom' in dataFileName:
breakFile = dataFileName.split("continueFrom",1)
breakFile_ = breakFile[1].split("_")
ttotal = np.float(breakFile_[0])+np.float(breakFile_[-1].split('s')[0])
fileName = datapath+breakFile[0]+str(ttotal)+'s_endweights'
else:
fileName = datapath+dataFileName+'_endweights'
# with ensures that the file is closed at the end / if error
with contextlib.closing(
( pd.HDFStore(fileName+'.h5') \
if 'robot' in dataFileName \
else shelve.open(fileName+'.shelve', 'r') )
) as data_dict:
endweights = np.array(data_dict['learnedWeights'])
else:
# with ensures that the file is closed at the end / if error
with contextlib.closing(
( pd.HDFStore(datapath+dataFileName+'_currentweights.h5') \
if 'robot' in dataFileName \
else shelve.open(datapath+dataFileName+'_currentweights.shelve', 'r') )
) as data_dict:
if '_nonlin' in dataFileName: weights = np.array(data_dict['weightsIn'])
else: weights = np.array(data_dict['weights'])
if 'encoders' in data_dict.keys():
encoders = data_dict['encoders']
reprRadius = data_dict['reprRadius']
weights = np.dot(encoders,weights)/reprRadius
weights = np.swapaxes(weights,0,1)
weightdt = data_dict['weightdt']
Tmax = data_dict['Tmax']
weighttimes = np.arange(0.0,Tmax+weightdt,weightdt)[:len(weights)]
#print(weights.shape)
endweights = np.array(weights[-1])
# Weights analysis
exc_wts_nonzero = endweights[np.where(endweights!=0)] # only non-zero weights
#exc_wts_nonzero = endweights
mean_exc_wts = np.mean(np.abs(exc_wts_nonzero))
axlist[1].hist(exc_wts_nonzero.flatten()/mean_exc_wts,bins=101,normed=True,linewidth=plot_linewidth,\
range=(-wtHistFact,wtHistFact),histtype='step')
#axlist[1].set_title('Histogram of learnt weights != 0',fontsize=label_fontsize)
## plot only |weights| > 90% max
#absendweights = np.abs(endweights.flatten()) # absolute values of final learnt weights
#cutendweights = 0.90*np.max(absendweights)
#largewt_idxs = np.where(absendweights>cutendweights)[0]
# # Take only |weights| > 90% of the maximum
#if len(largewt_idxs)>0:
# # reshape weights to flatten axes 1,2, not the time axis 0
# # -1 below in reshape will mean total size / weights.shape[0]
# weightsflat = weights.reshape(weights.shape[0],-1)
# axlist[0].plot( weighttimes, weightsflat[:,largewt_idxs]*1e3 )
# #axlist[0].set_title('Evolution of a few largest weights',fontsize=label_fontsize)
if axlist[0] is not None:
# plot a random selection of weights
# reshape weights to flatten axes 1,2, not the time axis 0
# -1 below in reshape will mean total size / weights.shape[0]
weightsflat = weights.reshape(weights.shape[0],-1)
# permute indices and take 50 of them
np.random.seed([1]) # repeatable plots!
weight_idxs = np.random.permutation(np.arange(endweights.size))[:50]
axlist[0].plot( weighttimes, weightsflat[:,weight_idxs]*wtFactor, linewidth=plot_linewidth )
#axlist[0].set_title('Evolution of a few weights',fontsize=label_fontsize)
def rates_CVs(spikesOut,trange,tCutoff,tMax,dt,ratetimeranges):
''' Takes nengo style spikesOut
and returns rates and CVs of each neuron
for spiketimes>tCutoff and spiketimes<tMax.
If fullavg, then rates and None are returned,
over time-periods specified in fulldetails = [(tstart,tend),...]
'''
n_times, n_neurons = spikesOut.shape
CV = 100.*np.ones(n_neurons)
rate = np.zeros(n_neurons)
totalspikes, totalspikes_select = 0.,0.
for i in range(n_neurons):
spikesti = trange[spikesOut[:, i] > 0].ravel()
totalspikes += len(spikesti)
spikesti_select = np.zeros(0) # zero-length array of floats
ttotal = 0.
for tstart,tend in ratetimeranges:
spikesti_select = np.append(spikesti_select,
spikesti[np.where((spikesti>=tstart) & (spikesti<tend))])
ttotal += tend-tstart
totalspikes_select += len(spikesti_select)
rate[i]=len(spikesti_select)/float(ttotal)
ISI = np.diff(spikesti_select)*dt
if(len(spikesti_select)>5):
CV[i] = np.std(ISI)/np.mean(ISI)
CV = CV[CV!=100.]
print ("Mean firing rate over ",n_neurons,"neurons for full time",trange[-1]-trange[0],\
'is',totalspikes/(trange[-1]-trange[0])/n_neurons)
print ("Mean firing rate over ",n_neurons,"neurons for the selected time",\
ttotal,'is',\
totalspikes_select/ttotal/n_neurons)
return rate,CV
def rasterplot(ax,trange,tstart,tend,spikesOut,n_neurons,colors=['r','b'],\
size=2.5,marker='.',sort=False):
spikesPlot = []
for i in n_neurons:
spikesti = trange[spikesOut[:, i] > 0].ravel()
spikesti = spikesti[np.where((spikesti>tstart) & (spikesti<tend))]
if len(spikesti)==0: spikesPlot.append([np.NAN])
else: spikesPlot.append(spikesti)
if sort:
idxs = np.argsort(
[spikesPlot[i][0] for i in range(len(spikesPlot))] )
idxs = idxs[::-1] # reverse sorted in time to first spike
else: idxs = range(len(n_neurons))
for i,idx in enumerate(idxs):
ax.scatter(spikesPlot[idx],[i+1]*len(spikesPlot[idx]),\
marker=marker,s=size,\
facecolor=colors[i%2],lw=0,clip_on=False)
ax.set_ylim((1,len(n_neurons)))
ax.set_xlim((tstart,tend))
ax.get_xaxis().get_major_formatter().set_useOffset(False)
def plot_spikes_rates(axlist,testFileName,tstart,tend,fullavg=False,sort=False):
# with ensures that the file is closed at the end / if error
with contextlib.closing(
shelve.open(datapath+testFileName+'_start.shelve', 'r')
) as data_dict:
trange = data_dict['trange']
Tmax = data_dict['Tmax']
rampT = data_dict['rampT']
Tperiod = data_dict['Tperiod']
dt = data_dict['dt']
tau = data_dict['tau']
errorLearning = data_dict['errorLearning']
spikingNeurons = data_dict['spikingNeurons']
y2 = data_dict['ratorOut2']
if 'EspikesOut2' in data_dict.keys():
EspikesOut = data_dict['EspikesOut2']
if fullavg:
fullavgdetails1 = np.arange(0.,4*Tperiod,Tperiod) # _start.shelve datafile, hence 4*Tperiod max time
## remove 0.5s at end of trial when output was clamped
#fullavgdetails = zip(fullavgdetails1,fullavgdetails1+Tperiod-0.5)
fullavgdetails = zip(fullavgdetails1,fullavgdetails1+Tperiod) # testing without clamp at end of trial, no need of -0.5
else: fullavgdetails = [(0.7,0.95)] # only average a short period where o/p is ~constant
rate,CV = rates_CVs(EspikesOut,trange,tstart,tend,dt,fullavgdetails)
if ('by4rates' in testFileName) or ('_g2o' in testFileName):
maxrate = 100.
num_bins = 25
elif 'by2rates' in testFileName:
maxrate = 200.
num_bins = 50
else:
maxrate = 400.
num_bins = 50
vals,_,_ = axlist[0].hist(rate,bins=num_bins,range=(0.,maxrate),color='k',histtype='step')
print ('number of neurons in bin at 0 Hz =',vals[0],"out of total",np.sum(vals),"neurons")
rasterplot(axlist[1],trange,tstart,tstart+0.75,EspikesOut,range(1,51),sort=sort)
if sort: # draw gray plot to compare output with spike times
# plot the predicted x_hat in the background
axlist[1].plot(trange[int(tstart/dt):int((tstart+0.75)/dt)],\
(y2[int(tstart/dt):int((tstart+0.75)/dt),1]+5)*5,\
linewidth=plot_linewidth, color='grey') # predicted
def plot_fig1_2_3(dataFileName,testFileNames,wtHistFact,altSpikes=False):
print('plotting figure 1/2/3',dataFileName)
fig = plt.figure(facecolor='w',figsize=(2*columnwidth, 1.5*columnwidth),dpi=fig_dpi)
if isinstance(dataFileName, list):
dataFileNameStart = dataFileName[0]
dataFileNameEnd = dataFileName[1]
if 'continueFrom' in dataFileNameEnd:
addTime = np.float(dataFileNameEnd.split("continueFrom",1)[1].split("_",1)[0])
else: addTime = 0.
else:
dataFileNameStart = dataFileName
dataFileNameEnd = dataFileName
addTime = 0.
N = 2
plotvar = 1
if 'robot2' in dataFileNameStart:
figlen = 12
testFileName = testFileNames[1] # plot RLSwing as test
N = 4
jutOut = 0.15
else:
figlen = 9
testFileName = testFileNames
if 'vanderPol' in dataFileNameStart:
figlen = 12
jutOut = 0.17
elif 'Lorenz' in dataFileNameStart:
N = 3
plotvar = 2
jutOut = 0.12
elif 'LinOsc' in dataFileNameStart:
if 'nonlin' in dataFileNameStart: plotvar = 1
else: plotvar = 0
jutOut = 0.17
# start, end and test low-dim vars and error
axlist_start = [plt.subplot2grid((figlen,9),(i*2,0),rowspan=2,colspan=3,zorder=10) for i in range(3)]
plot_learnt_data(axlist_start,dataFileNameStart+'_start.shelve',N=N,errFactor=1,plotvars=[plotvar])
axlist_end = [plt.subplot2grid((figlen,9),(i*2,3),rowspan=2,colspan=3,zorder=10) for i in range(3)]
if '_g2oR4.5' in dataFileNameEnd:
plot_learnt_data(axlist_end,"ff_ocl_g2oR4.5_wt80ms_Nexc3000_seeds2344_weightErrorCutoff0.0_nodeerr_learn_rec_nocopycat_func_vanderPol_trials_seed2by50.0amplVaryHeightsScaled_continueFrom5000.0_trials_seed11by50.0amplVaryHeightsScaled_40.0s_end.shelve",
N=N,errFactor=1,plotvars=[plotvar],addTime=addTime)
else:
plot_learnt_data(axlist_end,dataFileNameEnd+'_end.shelve',N=N,errFactor=1,plotvars=[plotvar],addTime=addTime)
axlist_test = [plt.subplot2grid((figlen,9),(i*2,6),rowspan=2,colspan=3,zorder=10) for i in range(3)]
print (testFileName)
plot_learnt_data(axlist_test,testFileName+'_start.shelve',N=N,errFactor=1,plotvars=[plotvar],phaseplane=True)
formatter = mpl.ticker.ScalarFormatter(useOffset=False) # used below to remove offset value shown added to axes ticks
for i in range(3):
# set y limits of start and end plots to the outermost values of the two
ylim1 = axlist_start[i].get_ylim()
ylim2 = axlist_end[i].get_ylim()
ylim3 = axlist_test[i].get_ylim()
if i<2:
ylim_min = np.min((ylim1[0],ylim2[0],ylim3[0]))
ylim_max = np.max((ylim1[1],ylim2[1],ylim3[1]))
else:
ylim_min = np.min((ylim1[0],ylim2[0]))
ylim_max = np.max((ylim1[1],ylim2[1]))
axlist_start[i].set_ylim(ylim_min,ylim_max)
axlist_end[i].set_ylim(ylim_min,ylim_max)
if i!=2: axlist_test[i].set_ylim(ylim_min,ylim_max) # 3rd row, 3rd col is 2D phase plot
beautify_plot(axlist_end[i],x0min=False,y0min=False)
beautify_plot(axlist_test[i],x0min=False,y0min=False)
beautify_plot(axlist_start[i],x0min=False,y0min=False)
axlist_end[i].xaxis.set_major_formatter(formatter)
axlist_test[i].xaxis.set_major_formatter(formatter)
axes_off(axlist_end[i],i!=2,True) # no x labels for first two rows
axes_off(axlist_test[i],i==0,i!=2) # no x labels for first row
axes_off(axlist_start[i],i!=2,False) # no y labels except for start axes
# vertical line to mark end of learning
xlim = axlist_end[i].get_xlim()
#if 'robot' in dataFileName: xmid = xlim[0]+(xlim[1]-xlim[0])*0.25
#else:
xmid = xlim[0]+(xlim[1]-xlim[0])*0.5
axlist_end[i].plot([xmid,xmid],[ylim_min,ylim_max],color='r',linewidth=plot_linewidth)
# vertical line to mark start of error feedback
xlim = axlist_start[i].get_xlim()
#if 'robot' in dataFileName: xmid = xlim[0]+(xlim[1]-xlim[0])*0.25
#else:
xmid = xlim[0]+(xlim[1]-xlim[0])*0.5
axlist_start[i].plot([xmid,xmid],[ylim_min,ylim_max],color='r',linewidth=plot_linewidth)
add_x_break_lines(axlist_start[i],axlist_end[i],jutOut=jutOut) # jutOut is half-length between x-axis in axes coordinates i.e. (0,1)
axes_labels(axlist_start[0],'','$u_'+str(plotvar+1)+'$',ypad=-3)
axes_labels(axlist_start[1],'','$x_'+str(plotvar+1)+'$,$\hat{x}_'+str(plotvar+1)+'$',ypad=-2)
axes_labels(axlist_start[2],'time (s)','error $\epsilon_'+str(plotvar+1)+'$',xpad=-6,ypad=-3)
#axes_labels(axlist_start[3],'time (s)','$MSE (s^{-1})$',xpad=-6)
#axlist_start[-1].yaxis.set_label_coords(0.05,0.5,transform=fig.transFigure)
axes_labels(axlist_end[-1],'time (s)','',xpad=-6)
axes_labels(axlist_test[-2],'time (s)','',xpad=-2) # xlabel on the axes above this one
# 2D phase plane
axes_labels(axlist_test[-1],'$x_1$, $\hat{x}_1$','$x_2$, $\hat{x}_2$',xpad=-6,ypad=-3)
if 'robot2' in dataFileNameStart:
axlist_start[1].set_ylabel('$\\theta_2,\hat{\\theta}_2$\n$\omega_2,\hat{\omega}_2$')
axlist_test[2].set_ylim((-0.2,0.2))
beautify_plot(axlist_test[2],x0min=False,y0min=False)
axes_labels(axlist_test[2],'$\\theta_2$, $\hat{\\theta}_2$','$\\theta_1$, $\hat{\\theta}_1$',xpad=-6,ypad=-3)
axlist_test[2].arrow(0, -0.05, 0.1, -0.04, head_width=0.025, head_length=0.05, fc='g', ec='g')
averageDts = 1
figcols = [0,4]
for filei,testFileName in enumerate(testFileNames):
N, Ncoords, get_robot_position, xextent, yextent = get_robot_func(testFileName)
dt, trange, u, uref, y2, yExpect, varFactors, Tperiod, task, target = get_robot_data(testFileName,'_start')
keysteps = [[0.,0.3,0.6-averageDts*dt],[0.,0.7,1.1,1.6,2.3-averageDts*dt]]
def plot_robot_keysteps(axlist,robvars,tlist,dt,color,timelabel=True):
for i,ax in enumerate(axlist):
ax.add_patch(mpl.patches.Rectangle(target,0.1,0.1,transform=ax.transData,\
ec='k',fc='c',clip_on=False,lw=linewidth/2.))
# Rectangle has (x,y),width,height
posns = np.mean([ get_robot_position(robvars[int(tlist[i]/dt)+j,:Ncoords]/varFactors[:Ncoords])
for j in range(averageDts) ], axis=0)
ax.plot(posns[0],posns[1],color=color,lw=3,clip_on=False,solid_capstyle='round',\
path_effects=[mpl_pe.Stroke(linewidth=4, foreground='k'), mpl_pe.Normal()])
# circular arrow showing mean direction of torque for next 200ms at each joint
for ang in [0,1]:
if i == len(axlist)-1: break
meantorque = np.mean( u[int(tlist[i]/dt):int((tlist[i]+0.2)/dt),ang] )
if meantorque > 1e-6: marker = r'$\circlearrowleft$'
elif meantorque < -1e-6: marker = r'$\circlearrowright$'
else: marker = None
ax.plot(posns[0][ang],posns[1][ang],marker=marker,ms=15,color='k',clip_on=False)
beautify_plot(ax,x0min=False,y0min=False,xticks=[],yticks=[],drawxaxis=False,drawyaxis=False)
if timelabel: ax.text(0.2, 1., '%2.1f s'%(tlist[i],), transform=ax.transAxes,\
color='k', fontsize=label_fontsize, clip_on=False)
# divide xextent=(-lim,lim) or yextent by a factor, to have ~1:1 aspect ratio if you can change say wspace
# as rowspan of 3*colspan, figsize aspect-ratio of 2:1.5, and wspace between plots change aspect ratio
axEx = [plt.subplot2grid((figlen,9),(6,figcols[filei]+i),rowspan=3,colspan=1,\
autoscale_on=False, xlim=xextent/6., ylim=yextent,
clip_on=False, zorder=len(keysteps[filei])-i) \
for i in range(len(keysteps[filei]))] # decreasing zorder to not occlude target patch
axY2 = [plt.subplot2grid((figlen,9),(9,figcols[filei]+i),rowspan=3,colspan=1,\
autoscale_on=False, xlim=xextent/6., ylim=yextent,\
clip_on=False, zorder=len(keysteps[filei])-i) \
for i in range(len(keysteps[filei]))] # decreasing zorder to not occlude target patch
plot_robot_keysteps(axEx,yExpect,keysteps[filei],dt,'b',timelabel=False)
plot_robot_keysteps(axY2,y2,keysteps[filei],dt,'r')
axlist_start[1].text(0.1, 0.77, 'feedback off', transform=fig.transFigure,\
fontsize=label_fontsize, color='r')
axlist_start[1].text(0.213, 0.77, '|', transform=fig.transFigure,\
fontsize=label_fontsize, color='r')
axlist_start[1].text(0.22, 0.77, 'feedback on', transform=fig.transFigure,\
fontsize=label_fontsize, color='r')
# the Axes to which each text is attached is irrelevant, as I'm using figure coords
axlist_start[0].text(0.31, 0.96, 'Learning', transform=fig.transFigure)
axlist_start[0].text(0.206, 0.93, '|', color='r', transform=fig.transFigure, fontsize=25)
axlist_start[0].text(0.23, 0.92, 'start', transform=fig.transFigure)
axlist_start[0].text(0.43, 0.92, 'end', transform=fig.transFigure)
axlist_start[0].text(0.515, 0.93, '|', color='r', transform=fig.transFigure, fontsize=25)
axlist_start[0].text(0.64, 0.96, 'Testing', transform=fig.transFigure)
axlist_start[0].text(0.54, 0.92, 'noise', transform=fig.transFigure)
axlist_start[0].text(0.72, 0.92, 'acrobot-like task', transform=fig.transFigure)
axlist_start[1].text(0.41, 0.77, 'feedback on', transform=fig.transFigure,\
fontsize=label_fontsize, color='r')
axlist_start[1].text(0.522, 0.77, '|', transform=fig.transFigure,\
fontsize=label_fontsize, color='r')
axlist_start[1].text(0.53, 0.77, 'feedback off', transform=fig.transFigure,\
fontsize=label_fontsize, color='r')
axlist_start[1].text(0.78, 0.77, 'feedback off', transform=fig.transFigure,\
fontsize=label_fontsize, color='r')
axlist_start[0].text(0.015, 0.9, 'Ai', transform=fig.transFigure)
axlist_start[0].text(0.015, 0.75, 'Bi', transform=fig.transFigure)
axlist_start[0].text(0.015, 0.61, 'Ci', transform=fig.transFigure)
axlist_start[0].text(0.65, 0.9, 'Aii', transform=fig.transFigure)
axlist_start[0].text(0.65, 0.75, 'Bii', transform=fig.transFigure)
axlist_start[0].text(0.65, 0.61, 'Cii', transform=fig.transFigure)
axlist_start[0].text(0.015, 0.4, 'D', transform=fig.transFigure)
axEx[3].text(0.47, 0.4, 'E', transform=fig.transFigure)
axlist_start[0].text(0.015, 0.33, 'reference', transform=fig.transFigure, fontsize=label_fontsize)
axlist_start[0].text(0.015, 0.1, 'network', transform=fig.transFigure, fontsize=label_fontsize)
axEx[0].text(0.2, 0.425, 'reaching task', transform=fig.transFigure, fontsize=label_fontsize, zorder=5)
axEx[0].text(0.65, 0.425, 'acrobot-like task', transform=fig.transFigure, fontsize=label_fontsize, zorder=5)
axEx[3].text(0.43, 0.25,'$\longleftarrow$ gravity', rotation='vertical',\
transform=fig.transFigure, fontsize=label_fontsize)
fig.subplots_adjust(top=0.9,left=0.1,right=0.95,bottom=0.05,hspace=2.5,wspace=4.)
elif 'Lorenz' in dataFileNameStart:
# adjust subplots early, so that ax.set_position is not overridden.
fig.subplots_adjust(top=0.9,left=0.1,right=0.95,bottom=0.05,hspace=2.5,wspace=2.)
# mark the symbol in Lorenz 2D phase plane
axlist_test[-1].text(17.,18.,'$\star$',color='b')
# Lorenz configuration space - strange attractor in 3D
axexpect = plt.subplot2grid((figlen,9),(6,0),rowspan=3,colspan=3,projection='3d')
axlearnt = plt.subplot2grid((figlen,9),(6,3),rowspan=3,colspan=3,projection='3d')
plot_Lorenz([axexpect,axlearnt],datapath+testFileName+'_end.shelve')
beautify_plot3d(axexpect,x0min=False,y0min=False,xticks=[],yticks=[],zticks=[])
beautify_plot3d(axlearnt,x0min=False,y0min=False,xticks=[],yticks=[],zticks=[])
for axnum,ax in enumerate([axexpect,axlearnt]):
ax.set_xlabel(('$x_1$','$\hat{x}_1$')[axnum],fontsize=label_fontsize,labelpad=-10)
ax.set_ylabel(('$x_2$','$\hat{x}_2$')[axnum],fontsize=label_fontsize,labelpad=-10)
ax.set_zlabel(('$x_3$','$\hat{x}_3$')[axnum],fontsize=label_fontsize,labelpad=-15)
## labelpad doesn't work above -- no it does
## see: http://stackoverflow.com/questions/5525782/adjust-label-positioning-in-axes3d-of-matplotlib
#ax.xaxis._axinfo['label']['space_factor'] = 1.0
#ax.yaxis._axinfo['label']['space_factor'] = 1.0
#ax.zaxis._axinfo['label']['space_factor'] = 1.0
bbox=ax.get_position()
ax.set_position([bbox.x0-0.04,bbox.y0-0.025,bbox.x1-bbox.x0+0.05,bbox.y1-bbox.y0+0.05])
# tent map
axtent = plt.subplot2grid((figlen,9),(6,6),rowspan=3,colspan=3)
plot_tentmap(axtent, testFileName)
beautify_plot(axtent,x0min=False,y0min=False)
axes_labels(axtent,'$\max{}_n(x_'+str(plotvar+1)+')$',\
'$\max{}_{n+1}(x_'+str(plotvar+1)+')$',xpad=-6,ypad=-3)
axlist_start[0].text(0.015, 0.89, 'Ai', transform=fig.transFigure)
axlist_start[0].text(0.015, 0.69, 'Bi', transform=fig.transFigure)
axlist_start[0].text(0.015, 0.5, 'Ci', transform=fig.transFigure)
axlist_start[0].text(0.65, 0.89, 'Aii', transform=fig.transFigure)
axlist_start[0].text(0.65, 0.69, 'Bii', transform=fig.transFigure)
axlist_start[0].text(0.65, 0.5, 'Cii', transform=fig.transFigure)
axtent.text(0.015, 0.28, 'D', transform=fig.transFigure) # text in x,y,z attached to 3D axes, combined with transFigure doesn't work!
#axtent.text(0.36, 0.28, 'E', transform=fig.transFigure) # text in x,y,z attached to 3D axes, combined with transFigure doesn't work!
axtent.text(0.66, 0.28, 'E', transform=fig.transFigure)
axlist_start[1].text(0.1, 0.72, 'feedback off', transform=fig.transFigure,\
fontsize=label_fontsize, color='r')
axlist_start[1].text(0.215, 0.72, '|', transform=fig.transFigure,\
fontsize=label_fontsize, color='r')
axlist_start[1].text(0.225, 0.72, 'feedback on', transform=fig.transFigure,\
fontsize=label_fontsize, color='r')
# the Axes to which each text is attached is irrelevant, as I'm using figure coords
axlist_start[0].text(0.31, 0.96, 'Learning', transform=fig.transFigure)
axlist_start[0].text(0.21, 0.93, '|', color='r', transform=fig.transFigure, fontsize=25)
axlist_start[0].text(0.25, 0.92, 'start', transform=fig.transFigure)
axlist_start[0].text(0.43, 0.92, 'end', transform=fig.transFigure)
axlist_start[0].text(0.515, 0.93, '|', color='r', transform=fig.transFigure, fontsize=25)
axlist_start[0].text(0.64, 0.96, 'Testing', transform=fig.transFigure)
axlist_start[0].text(0.54, 0.92, 'zero', transform=fig.transFigure)
axlist_start[0].text(0.8, 0.92, 'zero', transform=fig.transFigure)
axlist_start[1].text(0.41, 0.72, 'feedback on', transform=fig.transFigure,\
fontsize=label_fontsize, color='r')
axlist_start[1].text(0.522, 0.72, '|', transform=fig.transFigure,\
fontsize=label_fontsize, color='r')
axlist_start[1].text(0.53, 0.72, 'feedback off', transform=fig.transFigure,\
fontsize=label_fontsize, color='r')
axlist_start[1].text(0.78, 0.72, 'feedback off', transform=fig.transFigure,\
fontsize=label_fontsize, color='r')
elif 'vanderPol' in dataFileNameStart and altSpikes:
# phase plane plot
axlist_test[-1].text(-4,-2.7,'$\star$',color='b')
axlist_test[-1].text(3.5,1.5,'$\diamond$',color='c')
if '_g2' in dataFileNameStart:
max_bin = 2200
errxlim = -100
else:
max_bin=1500
errxlim = -1000
# error evolution - full time
ax_err = plt.subplot2grid((figlen,9),(6,0),rowspan=3,colspan=3)
plot_error_fulltime(ax_err,dataFileName)
beautify_plot(ax_err,x0min=False,y0min=False)
axes_labels(ax_err,'time (s)','$\langle err^2 \\rangle_{N_d,t}$',xpad=-6,ypad=-1)
ax_err.set_xlim([errxlim,ax_err.get_xlim()[1]])
## check that get_MSE() returns same error as plotted by plot_error_fulltime()
#print get_MSE(dataFileNameEnd+'_end.shelve')
# weights
ax_wts_hist = plt.subplot2grid((figlen,9),(9,0),rowspan=3,colspan=3)
plot_current_weights([None,ax_wts_hist],dataFileNameEnd,\
wtFactor=1000,wtHistFact=wtHistFact)
beautify_plot(ax_wts_hist,x0min=False,y0min=False)
axes_labels(ax_wts_hist,'weight (arb)','density',xpad=-6,ypad=-5)
# spike trains and rates
ax_rates = plt.subplot2grid((figlen,9),(6,3),rowspan=3,colspan=3,clip_on=False)
ax_spikes = plt.subplot2grid((figlen,9),(9,3),rowspan=3,colspan=3,clip_on=False)
ax_rates2 = plt.subplot2grid((figlen,9),(6,6),rowspan=3,colspan=3,clip_on=False)
ax_spikes2 = plt.subplot2grid((figlen,9),(9,6),rowspan=3,colspan=3,clip_on=False)
# plot the rates in the time period 0.65s to 0.9s (hard-coded in fn)
# during which output is constant,
# and spikes from 0.5 to 0.5+0.75
plot_spikes_rates([ax_rates,ax_spikes],testFileName,tstart=0.5,tend=3.5)
# plot the rates in the time period 0s to 16s,
# and spikes from 0.5 to 0.5+0.75
plot_spikes_rates([ax_rates2,ax_spikes2],testFileName,tstart=0.5,tend=None,\
fullavg=True,sort=True)
#plot_spikes_rates([ax_rates2,ax_spikes2],testFileName,tstart=0.5,tend=20.)
ax_rates.set_ylim((0,max_bin))
# plot a green rectangle on time axis for which rates are plotted
ax_spikes.plot([0.7,0.7,0.95,0.95,0.7],[0,2,2,0,0],\
'g',clip_on=False,lw=plot_linewidth)
beautify_plot(ax_rates,x0min=False,y0min=False)
beautify_plot(ax_spikes,x0min=False,y0min=False)
axes_labels(ax_rates,'rate (Hz)','count',xpad=-6,ypad=-6)
axes_labels(ax_spikes,'time (s)','neuron #',xpad=-6,ypad=-3)
ax_rates2.set_ylim((0,max_bin))
beautify_plot(ax_rates2,x0min=False,y0min=False)
beautify_plot(ax_spikes2,x0min=False,y0min=False)
axes_labels(ax_rates2,'rate (Hz)','count',xpad=-6,ypad=-6)
axes_labels(ax_spikes2,'time (s)','neuron #',xpad=-6,ypad=-3)
axlist_start[0].text(0.015, 0.92, 'Ai', transform=fig.transFigure)
axlist_start[0].text(0.015, 0.75, 'Bi', transform=fig.transFigure)
axlist_start[0].text(0.015, 0.6, 'Ci', transform=fig.transFigure)
axlist_start[0].text(0.665, 0.92, 'Aii', transform=fig.transFigure)
axlist_start[0].text(0.665, 0.75, 'Bii', transform=fig.transFigure)
axlist_start[0].text(0.665, 0.6, 'Cii', transform=fig.transFigure)
axlist_start[0].text(0.015, 0.45, 'D', transform=fig.transFigure)
ax_rates.text(0.34, 0.45, 'E', transform=fig.transFigure)
ax_spikes.text(0.665, 0.45, 'F', transform=fig.transFigure)
axlist_start[0].text(0.015, 0.21, 'G', transform=fig.transFigure)
ax_rates.text(0.34, 0.21, 'H', transform=fig.transFigure)
ax_spikes.text(0.665, 0.21, 'I', transform=fig.transFigure)
axlist_start[1].text(0.09, 0.77, 'feedback off', transform=fig.transFigure,\
fontsize=label_fontsize, color='r')
axlist_start[1].text(0.209, 0.77, '|', transform=fig.transFigure,\
fontsize=label_fontsize, color='r')
axlist_start[1].text(0.22, 0.77, 'feedback on', transform=fig.transFigure,\
fontsize=label_fontsize, color='r')
# the Axes to which each text is attached is irrelevant, as I'm using figure coords
axlist_start[0].text(0.31, 0.96, 'Learning', transform=fig.transFigure)
axlist_start[0].text(0.205, 0.93, '|', color='r', transform=fig.transFigure, fontsize=25)
axlist_start[0].text(0.25, 0.92, 'start', transform=fig.transFigure)
axlist_start[0].text(0.43, 0.92, 'end', transform=fig.transFigure)
axlist_start[0].text(0.515, 0.93, '|', color='r', transform=fig.transFigure, fontsize=25)
axlist_start[0].text(0.64, 0.96, 'Testing', transform=fig.transFigure)
axlist_start[0].text(0.54, 0.92, 'noise', transform=fig.transFigure)
axlist_start[0].text(0.72, 0.92, 'pulse on pedestal', transform=fig.transFigure)
axlist_start[1].text(0.41, 0.77, 'feedback on', transform=fig.transFigure,\
fontsize=label_fontsize, color='r')
axlist_start[1].text(0.522, 0.77, '|', transform=fig.transFigure,\
fontsize=label_fontsize, color='r')
axlist_start[1].text(0.53, 0.77, 'feedback off', transform=fig.transFigure,\
fontsize=label_fontsize, color='r')
axlist_start[1].text(0.78, 0.77, 'feedback off', transform=fig.transFigure,\
fontsize=label_fontsize, color='r')
fig.subplots_adjust(top=0.9,left=0.1,right=0.95,bottom=0.05,hspace=6,wspace=6.)
else:
# error evolution - full time
ax_err = plt.subplot2grid((figlen,9),(6,0),rowspan=3,colspan=3)
plot_error_fulltime(ax_err,dataFileNameEnd)
beautify_plot(ax_err,x0min=False,y0min=False)
axes_labels(ax_err,'time (s)','$\langle err^2 \\rangle_{N_d,t}$',xpad=-6,ypad=-1)
ax_err.set_xlim([-500,ax_err.get_xlim()[1]])
## check that get_MSE() returns same error as plotted by plot_error_fulltime()
#print get_MSE(dataFileNameEnd+'_end.shelve')
if 'nonlin2' not in dataFileName:
axlist_test[2].arrow(0, -0.05, 0.1, -0.04, head_width=0.025, head_length=0.05, fc='g', ec='g')
# weights
ax_wts_evolve = plt.subplot2grid((figlen,9),(6,3),rowspan=3,colspan=3)
ax_wts_hist = plt.subplot2grid((figlen,9),(6,6),rowspan=3,colspan=3)
plot_current_weights([ax_wts_evolve,ax_wts_hist],dataFileNameEnd,\
wtFactor=1000,wtHistFact=wtHistFact)
beautify_plot(ax_wts_evolve,x0min=False,y0min=False)
beautify_plot(ax_wts_hist,x0min=False,y0min=False)
axes_labels(ax_wts_evolve,'time (s)','weight (arb)',xpad=-6,ypad=-3)
axes_labels(ax_wts_hist,'weight (arb)','density',xpad=-6,ypad=-5)
axlist_start[0].text(0.015, 0.89, 'Ai', transform=fig.transFigure)
axlist_start[0].text(0.015, 0.69, 'Bi', transform=fig.transFigure)
axlist_start[0].text(0.015, 0.5, 'Ci', transform=fig.transFigure)
axlist_start[0].text(0.66, 0.89, 'Aii', transform=fig.transFigure)
axlist_start[0].text(0.66, 0.69, 'Bii', transform=fig.transFigure)
axlist_start[0].text(0.66, 0.5, 'Cii', transform=fig.transFigure)
axlist_start[0].text(0.015, 0.28, 'D', transform=fig.transFigure)
ax_wts_hist.text(0.35, 0.28, 'E', transform=fig.transFigure)
ax_wts_hist.text(0.675, 0.28, 'F', transform=fig.transFigure)
axlist_start[1].text(0.09, 0.72, 'feedback off', transform=fig.transFigure,\
fontsize=label_fontsize, color='r')
axlist_start[1].text(0.21, 0.72, '|', transform=fig.transFigure,\
fontsize=label_fontsize, color='r')
axlist_start[1].text(0.22, 0.72, 'feedback on', transform=fig.transFigure,\
fontsize=label_fontsize, color='r')
# the Axes to which each text is attached is irrelevant, as I'm using figure coords
axlist_start[0].text(0.31, 0.96, 'Learning', transform=fig.transFigure)
axlist_start[0].text(0.205, 0.93, '|', color='r', transform=fig.transFigure, fontsize=25)
axlist_start[0].text(0.25, 0.92, 'start', transform=fig.transFigure)
axlist_start[0].text(0.43, 0.92, 'end', transform=fig.transFigure)
axlist_start[0].text(0.515, 0.93, '|', color='r', transform=fig.transFigure, fontsize=25)
axlist_start[0].text(0.64, 0.96, 'Testing', transform=fig.transFigure)
axlist_start[0].text(0.54, 0.92, 'noise', transform=fig.transFigure)
if 'LinOsc' in dataFileNameStart:
axlist_start[0].text(0.74, 0.92, 'ramp and step', transform=fig.transFigure)
else:
axlist_start[0].text(0.72, 0.92, 'pulse on pedestal', transform=fig.transFigure)
axlist_start[1].text(0.41, 0.72, 'feedback on', transform=fig.transFigure,\
fontsize=label_fontsize, color='r')
axlist_start[1].text(0.522, 0.72, '|', transform=fig.transFigure,\
fontsize=label_fontsize, color='r')
axlist_start[1].text(0.53, 0.72, 'feedback off', transform=fig.transFigure,\
fontsize=label_fontsize, color='r')
axlist_start[1].text(0.78, 0.72, 'feedback off', transform=fig.transFigure,\
fontsize=label_fontsize, color='r')
fig.subplots_adjust(top=0.9,left=0.1,right=0.95,bottom=0.05,hspace=6,wspace=6.)
fig.savefig('figures/fig_'+dataFileNameStart+('_altSpikes' if altSpikes else '')+'.pdf',dpi=fig_dpi)
def plot_figcosyne(dataFileName,wtHistFact):
print('plotting figure for cosyne',dataFileName)
fig = plt.figure(facecolor='w',figsize=(2*columnwidth, columnwidth),dpi=fig_dpi)
# start and end low-dim vars and error
axlist_start = [plt.subplot2grid((2,3),(i,0)) for i in range(2)]
# reversed axes, N=-1,plotvars=[1], hack to plot_learnt_data for small cosyne figure!
plot_learnt_data(axlist_start[::-1],dataFileName+'_start.shelve',-1,1000,[1])
axlist_end = [plt.subplot2grid((2,3),(i,1)) for i in range(2)]
# reversed axes, N=-1,plotvars=[1], hack to plot_learnt_data for small cosyne figure!
plot_learnt_data(axlist_end[::-1],dataFileName+'_end.shelve',-1,1000,[1])
for i in range(2):
beautify_plot(axlist_start[i],x0min=False,y0min=False,xticks=[])
beautify_plot(axlist_end[i],x0min=False,y0min=False,xticks=[],yticks=[])
# set y limits of start and end plots to the outermost values of the two
ylim1 = axlist_start[i].get_ylim()
ylim2 = axlist_end[i].get_ylim()
ylim_min = np.min((ylim1[0],ylim2[0]))
ylim_max = np.max((ylim1[1],ylim2[1]))
axlist_start[i].set_ylim(ylim_min,ylim_max)
axlist_end[i].set_ylim(ylim_min,ylim_max)
# vertical line to mark end of learning
xlim = axlist_end[i].get_xlim()
if 'robot' in dataFileName: xmid = xlim[0]+(xlim[1]-xlim[0])*0.25
else: xmid = xlim[0]+(xlim[1]-xlim[0])*0.5
axlist_end[i].plot([xmid,xmid],[ylim_min,ylim_max],color='r',linewidth=plot_linewidth)
beautify_plot(axlist_start[-1],x0min=False,y0min=False)
beautify_plot(axlist_end[-1],x0min=False,y0min=False,yticks=[])
axes_labels(axlist_start[0],'','$x_2$, $\hat{x}_2$',ypad=-2)
axes_labels(axlist_start[-1],'time (s)','error ($\cdot 10^{-3}$)',xpad=-6,ypad=-6)
axes_labels(axlist_end[-1],'time (s)','',xpad=-6)
formatter = mpl.ticker.ScalarFormatter(useOffset=False) # remove the offset on axes ticks
axlist_end[-1].xaxis.set_major_formatter(formatter)
# error evolution - full time
ax_err = plt.subplot2grid((2,3),(0,2),rowspan=1,colspan=1)
plot_error_fulltime(ax_err,dataFileName)
beautify_plot(ax_err,x0min=False,y0min=False)
axes_labels(ax_err,'time (s)','error$^2$',xpad=-6,ypad=-8)
# Phase plane portrait
ax_phase = plt.subplot2grid((2,3),(1,2),rowspan=1,colspan=1)
plot_phaseplane2D([ax_phase,ax_phase],datapath+dataFileName+'_end.shelve')
beautify_plot(ax_phase,x0min=False,y0min=False)
axes_labels(ax_phase,'$x_1$','$x_2$',xpad=-6,ypad=-4)
#fig.tight_layout()
fig.subplots_adjust(top=0.9,left=0.08,right=0.95,bottom=0.1,hspace=0.3,wspace=0.3)
#for ax in [ax_wts_hist,ax_wts_evolve]:
# bbox=ax.get_position()
# ax.set_position([bbox.x0,bbox.y0+0.01,bbox.width,bbox.height])
# the Axes to which each text is attached is irrelevant, as I'm using figure coords
axlist_start[0].text(0.12, 0.95, 'learning starts', transform=fig.transFigure)
axlist_start[1].text(0.44, 0.95, 'learning ends', transform=fig.transFigure)
if 'robot' in dataFileName:
axlist_start[1].text(0.5125, 0.485, '|feedback off', transform=fig.transFigure,\
fontsize=label_fontsize, color='r')
else:
axlist_start[1].text(0.5125, 0.485, '|feedback off', transform=fig.transFigure,\
fontsize=label_fontsize, color='r')
axlist_start[0].text(0.015, 0.9, 'A', transform=fig.transFigure)
axlist_end[0].text(0.01, 0.46, 'B', transform=fig.transFigure)
#axlist_start[1].text(0.36, 0.9, 'C', transform=fig.transFigure)
#axlist_end[1].text(0.36, 0.46, 'D', transform=fig.transFigure)
ax_err.text(0.645, 0.9, 'C', transform=fig.transFigure)
ax_phase.text(0.645, 0.46, 'D', transform=fig.transFigure)
fig.savefig('figures/figcosyne_'+dataFileName+'.pdf',dpi=fig_dpi)
def plot_fig3(dataFileName,wtHistFact):
print('plotting figure 3')
fig = plt.figure(facecolor='w',figsize=(columnwidth, 3*columnwidth),dpi=fig_dpi)
axlist_start = [plt.subplot2grid((10,2),(i,0)) for i in range(6)]
plot_learnt_data(axlist_start,\
dataFileName+'_start.shelve',3,1)
axlist_end = [plt.subplot2grid((10,2),(i,1)) for i in range(6)]
plot_learnt_data(axlist_end,\
dataFileName+'_end.shelve',3,1)
for i in range(6):
beautify_plot(axlist_start[i],x0min=False,y0min=False,xticks=[])
beautify_plot(axlist_end[i],x0min=False,y0min=False,xticks=[],yticks=[])
ylim = axlist_start[i].get_ylim()
axlist_end[i].set_ylim(ylim[0],ylim[1])
# vertical line to mark end of learning
xlim = axlist_end[i].get_xlim()
xmid = (xlim[0]+xlim[1])/2.
axlist_end[i].plot([xmid,xmid],[ylim[0],ylim[1]],color='r',linewidth=plot_linewidth)
beautify_plot(axlist_start[-1],x0min=False,y0min=False)
beautify_plot(axlist_end[-1],x0min=False,y0min=False,yticks=[])
axes_labels(axlist_start[1],'','$x$, $\hat{x}$',ypad=4)
axes_labels(axlist_start[-1],'time (s)','',xpad=-6)
axes_labels(axlist_start[4],'','error ($\cdot 10^{-3}$)',ypad=2)
axes_labels(axlist_end[-1],'time (s)','',xpad=-6)
formatter = mpl.ticker.ScalarFormatter(useOffset=False) # remove the offset on axes ticks
axlist_end[-1].xaxis.set_major_formatter(formatter)
# Lorenz attractor
axLexpect = plt.subplot2grid((10,2),(6,0),rowspan=2,colspan=1,projection='3d')
axLlearnt = plt.subplot2grid((10,2),(6,1),rowspan=2,colspan=1,projection='3d')
plot_Lorenz([axLexpect,axLlearnt],datapath+dataFileName+'_end.shelve')
beautify_plot3d(axLexpect,x0min=False,y0min=False,xticks=[],yticks=[],zticks=[])
beautify_plot3d(axLlearnt,x0min=False,y0min=False,xticks=[],yticks=[],zticks=[])
# weights
ax_wts_evolve = plt.subplot2grid((10,2),(8,0),rowspan=2,colspan=1)
ax_wts_hist = plt.subplot2grid((10,2),(8,1),rowspan=2,colspan=1)
plot_current_weights([ax_wts_evolve,ax_wts_hist],dataFileName,\
wtFactor=1e6,wtHistFact=wtHistFact)
beautify_plot(ax_wts_evolve,x0min=False,y0min=False)
beautify_plot(ax_wts_hist,x0min=False,y0min=False)
axes_labels(ax_wts_hist,'weight ($\cdot 10^{-6}$)','density',xpad=-6,ypad=-5)
axes_labels(ax_wts_evolve,'time (s)','weight ($\cdot 10^{-6}$)',xpad=-6)
# the Axes to which each text is attached is irrelevant, as I'm using figure coords
axlist_start[0].text(0.15, 0.95, 'learning starts', transform=fig.transFigure)
axlist_start[1].text(0.62, 0.95, 'learning ends', transform=fig.transFigure)
axlist_start[1].text(0.78, 0.68, '|feedback off', transform=fig.transFigure,\
fontsize=label_fontsize, color='r')
axlist_start[0].text(0.015, 0.91, 'A', transform=fig.transFigure)
axlist_start[3].text(0.015, 0.66, 'B', transform=fig.transFigure)
axlist_start[3].text(0.015, 0.37, 'C', transform=fig.transFigure)
axlist_start[3].text(0.015, 0.19, 'D', transform=fig.transFigure)
#fig.tight_layout()
fig.subplots_adjust(top=0.92,left=0.15,right=0.95,bottom=0.1,hspace=0.6,wspace=0.4)
for ax in [ax_wts_hist,ax_wts_evolve]:
bbox=ax.get_position()
ax.set_position([bbox.x0,bbox.y0-0.05,bbox.x1-bbox.x0,bbox.y1-bbox.y0])
for ax in [axLexpect,axLlearnt]:
ax.set_xlabel('$x_1$',fontsize=label_fontsize,labelpad=10)
ax.set_ylabel('$x_2$',fontsize=label_fontsize,labelpad=0)
ax.set_zlabel('$x_3$',fontsize=label_fontsize,labelpad=-20)
# labelpad doesn't work above,
# see: http://stackoverflow.com/questions/5525782/adjust-label-positioning-in-axes3d-of-matplotlib
ax.xaxis._axinfo['label']['space_factor'] = 1.0
ax.yaxis._axinfo['label']['space_factor'] = 1.0
ax.zaxis._axinfo['label']['space_factor'] = 1.0
bbox=ax.get_position()
ax.set_position([bbox.x0-0.05,bbox.y0-0.05,bbox.x1-bbox.x0+0.1,bbox.y1-bbox.y0+0.05])
fig.savefig('figures/fig_'+dataFileName+'.pdf',dpi=fig_dpi)
def plot_tentmap(ax,dataFileName):
print('plotting Lorenz tent map using: ',dataFileName)
# with ensures that the file is closed at the end / if error
with contextlib.closing(
shelve.open(datapath+dataFileName+'_end.shelve', 'r')
) as data_dict:
trange = data_dict['trange']
Tmax = data_dict['Tmax']
rampT = data_dict['rampT']
Tperiod = data_dict['Tperiod']
dt = data_dict['dt']
tau = data_dict['tau']
errorLearning = data_dict['errorLearning']
spikingNeurons = data_dict['spikingNeurons']
trange = data_dict['trange']
tstart = -int(4*Tperiod/dt) # end Tnolearning without error feedback
trange = trange[tstart:]
y = data_dict['ratorOut']
y2 = data_dict['ratorOut2']