forked from NathanKlineInstitute/SMARTAgent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimdat.py
2336 lines (2235 loc) · 96.9 KB
/
simdat.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
from pylab import *
import pickle
import pandas as pd
import conf
from conf import dconf
import os
import sys
import anim
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import animation
import matplotlib.gridspec as gridspec
import matplotlib.patches as mpatches
from collections import OrderedDict
from imgutils import getoptflow, getoptflowframes
from connUtils import gid2pos
from utils import getdatestr
from scipy.stats import pearsonr
rcParams['agg.path.chunksize'] = 100000000000 # for plots of long activity
ion()
rcParams['font.size'] = 12
tl=tight_layout
stepNB = -1
totalDur = int(dconf['sim']['duration']) # total simulation duration
allpossible_pops = list(dconf['net']['allpops'].keys())
def pdf2weightsdict (pdf):
# convert the pandas dataframe with synaptic weights into a dictionary
D = {}
for idx in pdf.index:
t, preid, postid, weight = pdf.loc[idx]
preid=int(preid)
postid=int(postid)
if preid not in D: D[preid] = {}
if postid not in D[preid]: D[preid][postid] = []
D[preid][postid].append([t,weight])
return D
def readweightsfile2pdf (fn):
# read the synaptic plasticity weights saved as a dictionary into a pandas dataframe
D = pickle.load(open(fn,'rb'))
A = []
for preID in D.keys():
for poID in D[preID].keys():
for row in D[preID][poID]:
A.append([row[0], preID, poID, row[1]]) # A.append([row[0], preID, poID, row[1], row[2]])
return pd.DataFrame(A,columns=['time','preid','postid','weight']) # ,(['cumreward'])
#
def readinweights (name,final=False):
# read the synaptic plasticity weights associated with sim name into a pandas dataframe
if final:
fn = 'data/'+name+'synWeights_final.pkl'
else:
fn = 'data/'+name+'synWeights.pkl'
return readweightsfile2pdf(fn)
def savefinalweights (pdf, simstr):
# save final weights to a (small) file
pdfs = pdf[pdf.time==np.amax(pdf.time)]
D = pdf2weightsdict(pdfs)
pickle.dump(D, open('data/'+simstr+'synWeights_final.pkl','wb'))
def shuffleweights (pdf):
# shuffle the weights
npwt = np.array(pdf.weight)
np.random.shuffle(npwt)
Ashuf = np.array([pdf.time,pdf.preid,pdf.postid,npwt]).T
pdfshuf = pd.DataFrame(Ashuf,columns=['time','preid','postid','weight'])
return pdfshuf
#D = pdf2weightsdict(pdfshuf);
#return D
def getsimname (name=None):
if name is None:
if stepNB == -1: name = dconf['sim']['name']
elif stepNB > -1: name = dconf['sim']['name'] + '_step_' + str(stepNB) + '_'
return name
def generateActivityMap(t1, t2, spkT, spkID, numc, startidx):
sN = int(np.sqrt(numc))
Nact = np.zeros(shape=(len(t1),sN,sN)) # Nact is 3D array of number of spikes, indexed by: time, y, x
for i in range(sN):
for j in range(sN):
cNeuronID = j+(i*sN) + startidx
cNeuron_spkT = spkT[spkID==cNeuronID]
for t in range(len(t1)):
cbinSpikes = cNeuron_spkT[(cNeuron_spkT>t1[t]) & (cNeuron_spkT<=t2[t])]
Nact[t][i][j] = len(cbinSpikes)
return Nact
def generateActivityMap1D(t1, t2, spkT, spkID, numc, startidx):
Nact = np.zeros(shape=(len(t1),numc)) # Nact is 2D array of number of spikes, indexed by: time, cellID
for i in range(numc):
cNeuronID = i + startidx
cNeuron_spkT = spkT[spkID==cNeuronID]
for t in range(len(t1)):
cbinSpikes = cNeuron_spkT[(cNeuron_spkT>t1[t]) & (cNeuron_spkT<=t2[t])]
Nact[t][i] = len(cbinSpikes)
return Nact
def getdActMap (totalDur, tstepPerAction, dspkT, dspkID, dnumc, dstartidx,lpop = allpossible_pops):
t1 = range(0,totalDur,tstepPerAction)
t2 = range(tstepPerAction,totalDur+tstepPerAction,tstepPerAction)
dact = {}
for pop in lpop:
if pop in dnumc and dnumc[pop] > 0:
dact[pop] = generateActivityMap(t1, t2, dspkT[pop], dspkID[pop], dnumc[pop], dstartidx[pop])
return dact
def getdActMap1D (totalDur, actreward, dspkT, dspkID, dnumc, dstartidx,lpop = allpossible_pops):
t2 = np.array(actreward.time)
t1 = [0]
for i in range(len(t2)-1):
t1.append(t2[i])
t1 = np.array(t1)
dact = {}
for pop in lpop:
if pop in dnumc and dnumc[pop] > 0:
dact[pop] = generateActivityMap1D(t1, t2, dspkT[pop], dspkID[pop], dnumc[pop], dstartidx[pop])
return dact
def getCumActivityMapForInput(t1,t2,dact1D,lpop):
dCumAct = {}
dStepAct = {}
for pop in lpop:
dCumAct[pop] = []
dStepAct[pop] = []
for i in range(len(t1)):
cPopAct = list(np.sum(dact1D[pop][t1[i]:t2[i]+1,:],0))
cPopStepAct = list(dact1D[pop][t1[i]:t2[i]+1,:])
dCumAct[pop].append(cPopAct)
dStepAct[pop].append(cPopStepAct)
return dCumAct, dStepAct
def getRewardsPerSeq(actreward, seqBegs, seqEnds):
rewards = []
hitsMiss = []
for i in range(len(seqBegs)):
rewards.append(list(actreward.reward)[seqBegs[i]:seqEnds[i]+1])
hitsMiss.append(list(actreward.hit)[seqBegs[i]:seqEnds[i]+1])
return rewards,hitsMiss
def getActionsPerSeq(actreward, seqBegs, seqEnds):
proposedActions = []
executedActions = []
for i in range(len(seqBegs)):
proposedActions.append(list(actreward.proposed)[seqBegs[i]:seqEnds[i]+1])
executedActions.append(list(actreward.action)[seqBegs[i]:seqEnds[i]+1])
return proposedActions,executedActions
def getStepwiseNeuralContribution(executedActions,dStepAct):
stepwisecontribEMUP = []
stepwisecontribEMDOWN = []
for i in range(len(executedActions)):
cTrial_eActions = executedActions[i]
cTrial_actup = dStepAct['EMUP'][i]
cTrial_actdown = dStepAct['EMDOWN'][i]
for steps in range(len(cTrial_eActions)):
popemup = np.zeros((300,))
popemdown = np.zeros((300,))
if cTrial_eActions[steps]==4:
popemup[np.where(cTrial_actup[steps]>0)[0]]=1
elif cTrial_eActions[steps]==3:
popemdown[np.where(cTrial_actdown[steps]>0)[0]]=1
elif cTrial_eActions[steps]==1:
popemup[np.where(cTrial_actup[steps]>0)[0]]=1
popemdown[np.where(cTrial_actdown[steps]>0)[0]]=1
stepwisecontribEMUP.append(list(popemup))
stepwisecontribEMDOWN.append(list(popemdown))
stepwisecontribEMUP = np.array(stepwisecontribEMUP)
stepwisecontribEMDOWN = np.array(stepwisecontribEMDOWN)
return stepwisecontribEMUP, stepwisecontribEMDOWN
def loadsimdat (name=None,getactmap=True,lpop = allpossible_pops): # load simulation data
global totalDur, tstepPerAction
name = getsimname(name)
print('loading data from', name)
conf.dconf = conf.readconf('backupcfg/'+name+'sim.json')
simConfig = pickle.load(open('data/'+name+'simConfig.pkl','rb'))
dstartidx,dendidx={},{} # starting,ending indices for each population
for p in simConfig['net']['pops'].keys():
if simConfig['net']['pops'][p]['tags']['numCells'] > 0:
dstartidx[p] = simConfig['net']['pops'][p]['cellGids'][0]
dendidx[p] = simConfig['net']['pops'][p]['cellGids'][-1]
pdf=None
try:
pdf = readinweights(name) # if RL was off, no weights saved
except:
try:
pdf = readinweights(name,final=True)
except:
pass
actreward=None
try:
actreward = pd.DataFrame(np.loadtxt('data/'+name+'ActionsRewards.txt'),columns=['time','action','reward','proposed','hit','followtargetsign'])
except:
pass
dnumc = {}
for p in simConfig['net']['pops'].keys():
if p in dstartidx:
dnumc[p] = dendidx[p]-dstartidx[p]+1
else:
dnumc[p] = 0
spkID= np.array(simConfig['simData']['spkid'])
spkT = np.array(simConfig['simData']['spkt'])
dspkID,dspkT = {},{}
for pop in simConfig['net']['pops'].keys():
if dnumc[pop] > 0:
dspkID[pop] = spkID[(spkID >= dstartidx[pop]) & (spkID <= dendidx[pop])]
dspkT[pop] = spkT[(spkID >= dstartidx[pop]) & (spkID <= dendidx[pop])]
InputImages=ldflow=None
try:
InputImages = loadInputImages(dconf['sim']['name'])
except:
pass
try:
ldflow = loadMotionFields(dconf['sim']['name'])
except:
pass
totalDur = int(dconf['sim']['duration'])
tstepPerAction = dconf['sim']['tstepPerAction'] # time step per action (in ms)
dact = None
#lpop = ['ER', 'EV1', 'EV4', 'EMT', 'IR', 'IV1', 'IV4', 'IMT',\
# 'EV1DW','EV1DNW', 'EV1DN', 'EV1DNE','EV1DE','EV1DSW', 'EV1DS', 'EV1DSE',\
# 'EMDOWN','EMUP']
if getactmap: dact = getdActMap(totalDur, tstepPerAction, dspkT, dspkID, dnumc, dstartidx, lpop)
return simConfig, pdf, actreward, dstartidx, dendidx, dnumc, dspkID, dspkT, InputImages, ldflow, dact
#
def animActivityMaps (outpath='gif/'+dconf['sim']['name']+'actmap.mp4', framerate=10, figsize=(18,10), dobjpos=None,\
lpop=allpossible_pops, nframe=None):
# plot activity in different layers as a function of input images
ioff()
possible_pops = ['ER','EV1','EV4','EMT','IR','IV1','IV4','IMT','EV1DW','EV1DNW','EV1DN'\
,'EV1DNE','EV1DE','EV1DSW','EV1DS', 'EV1DSE','EMDOWN','EMUP','IM','EA','IA','EA2','IA2']
possible_titles = ['Excit R', 'Excit V1', 'Excit V4', 'Excit MT', 'Inhib R', 'Inhib V1', 'Inhib V4', 'Inhib MT',\
'W','NW','N','NE','E','SW','S','SE','Excit M DOWN', 'Excit M UP', 'Excit M STAY', 'Inhib M',\
'Excit A' , 'Inhib A', 'Excit A2', 'Inhib A2']
dtitle = {p:t for p,t in zip(possible_pops,possible_titles)}
ltitle = ['Input Images']
lact = [InputImages]; lvmax = [255];
dmaxSpk = OrderedDict({pop:np.max(dact[pop]) for pop in dact.keys()})
max_spks = np.max([dmaxSpk[p] for p in dact.keys()])
for pop in lpop:
ltitle.append(dtitle[pop])
lact.append(dact[pop])
lvmax.append(max_spks)
if figsize is not None: fig, axs = plt.subplots(4, 5, figsize=figsize);
else: fig, axs = plt.subplots(4, 5);
lax = axs.ravel()
cbaxes = fig.add_axes([0.95, 0.4, 0.01, 0.2])
ddir = OrderedDict({'EV1DW':'W','EV1DNW':'NW', 'EV1DN':'N','EV1DNE':'NE','EV1DE':'E','EV1DSW':'SW','EV1DS':'S','EV1DSE':'SE'})
lfnimage = []
ddat = {}
fig.suptitle('Time = ' + str(0*tstepPerAction) + ' ms')
idx = 0
objfctr = 1.0
if 'UseFull' in dconf['DirectionDetectionAlgo']:
if dconf['DirectionDetectionAlgo']['UseFull']: objfctr=1/8.
flowdx = 8 # 5
for ldx,ax in enumerate(lax):
if idx > len(dact.keys()):
ax.axis('off')
continue
if ldx==0:
offidx=-1
elif ldx==flowdx:
offidx=1
else:
offidx=0
if ldx==flowdx:
flowrow,flowcol = int(np.sqrt(dnumc['EV1DE'])),int(np.sqrt(dnumc['EV1DE']))
X, Y = np.meshgrid(np.arange(0, flowcol, 1), np.arange(0,flowrow,1))
ddat[ldx] = ax.quiver(X,Y,ldflow[0]['flow'][:,:,0],-ldflow[0]['flow'][:,:,1], pivot='mid', units='inches',width=0.022,scale=1/0.15)
ax.set_xlim((0,flowcol)); ax.set_ylim((0,flowrow))
ax.invert_yaxis()
continue
else:
pcm = ax.imshow(lact[idx][offidx,:,:],origin='upper',cmap='gray',vmin=0,vmax=lvmax[idx])
ddat[ldx] = pcm
if ldx==0 and dobjpos is not None:
lobjx,lobjy = [objfctr*dobjpos[k][0,0] for k in dobjpos.keys()], [objfctr*dobjpos[k][0,1] for k in dobjpos.keys()]
ddat['objpos'], = ax.plot(lobjx,lobjy,'ro')
ax.set_ylabel(ltitle[idx])
if ldx==2: plt.colorbar(pcm, cax = cbaxes)
idx += 1
def updatefig (t):
fig.suptitle('Time = ' + str(t*tstepPerAction) + ' ms')
if t<1: return fig # already rendered t=0 above; skip last for optical flow
print('frame t = ', str(t*tstepPerAction))
idx = 0
for ldx,ax in enumerate(lax):
if idx > len(dact.keys()): continue
if ldx==0 or ldx==flowdx:
offidx=-1
else:
offidx=0
if ldx == flowdx:
ddat[ldx].set_UVC(ldflow[t+offidx]['flow'][:,:,0],-ldflow[t+offidx]['flow'][:,:,1])
else:
ddat[ldx].set_data(lact[idx][t+offidx,:,:])
if ldx==0 and dobjpos is not None:
lobjx,lobjy = [objfctr*dobjpos[k][t,0] for k in dobjpos.keys()], [objfctr*dobjpos[k][t,1] for k in dobjpos.keys()]
ddat['objpos'].set_data(lobjx,lobjy)
idx += 1
return fig
t1 = range(0,totalDur,tstepPerAction)
if nframe is None: nframe = len(t1) - 1
ani = animation.FuncAnimation(fig, updatefig, interval=1, frames=nframe)
writer = anim.getwriter(outpath, framerate=framerate)
ani.save(outpath, writer=writer); print('saved animation to', outpath)
ion()
return fig, axs, plt
def viewInput (t, InputImages, ldflow, dhist, lpop = None, lclr = ['r','b'], twin=100, dobjpos = None):
ax = subplot(2,2,1)
tdx = int(t / tstepPerAction)
imshow( InputImages[tdx][:,:], origin='upper', cmap='gray'); colorbar()
ax.set_title('t = ' + str(t))
objfctr = 1.0/8
if dconf['DirectionDetectionAlgo']['UseFull']: objfctr=1/8.
minobjt = dobjpos['time'][0]
objofftdx = int(minobjt/tstepPerAction)
def drobjpos (ax, tdx):
if dobjpos is not None and tdx - objofftdx >= 0:
lobjx,lobjy = [objfctr*dobjpos[k][tdx-objofftdx][0] for k in ['ball','racket']], [objfctr*dobjpos[k][tdx-objofftdx][1] for k in ['ball','racket']]
#print('lobjx:',lobjx,'lobjy:',lobjy)
for k in ['ball','racket']:
print('t=',tstepPerAction*(tdx),k,'x=',objfctr*dobjpos[k][tdx-objofftdx][0],'y=',objfctr*dobjpos[k][tdx-objofftdx][1])
ax.plot(lobjx,lobjy,'ro')
drobjpos(ax, tdx)
ax = subplot(2,2,2)
tdx += 1
imshow( InputImages[tdx][:,:], origin='upper', cmap='gray'); colorbar();
ax.set_title('t = ' + str(t+tstepPerAction))
drobjpos(ax,tdx)
tdx -= 1
ax = subplot(2,2,3)
ax.set_title('Motion, t = ' + str(t))
X, Y = np.meshgrid(np.arange(0, InputImages[0].shape[1], 1), np.arange(0,InputImages[0].shape[0],1))
ax.quiver(X,Y,ldflow[tdx]['flow'][:,:,0],-ldflow[tdx]['flow'][:,:,1], pivot='mid', units='inches',width=0.01,scale=1/0.9)
ax.set_xlim((0,InputImages[0].shape[1])); ax.set_ylim((0,InputImages[0].shape[0]))
ax.invert_yaxis()
ax = subplot(2,2,4)
for pop,clr in zip(lpop,lclr): ax.plot(dhist[pop][0],dhist[pop][1],clr)
lpatch = [mpatches.Patch(color=c,label=s) for c,s in zip(lclr,lpop)]
ax=gca(); ax.legend(handles=lpatch,handlelength=1)
ax.set_xlim(tdx*tstepPerAction - twin, tdx*tstepPerAction + twin)
xlabel('Time (ms)'); ylabel('Spikes')
#
def animInput (InputImages, outpath, framerate=50, figsize=None, showflow=False, ldflow=None, dobjpos=None,\
actreward=None, nframe=None, skipopp=False):
# animate the input images; showflow specifies whether to calculate/animate optical flow
ioff()
# plot input images and optionally optical flow
ncol = 1
if showflow: ncol+=1
if figsize is not None: fig = figure(figsize=figsize)
else: fig = figure()
lax = [subplot(1,ncol,i+1) for i in range(ncol)]
ltitle = ['Input Images']
lact = [InputImages]; lvmax = [255]; xl = [(-.5,19.5)]; yl = [(19.5,-0.5)]
if dconf['net']['useBinaryImage']: lvmax = [1]
ddat = {}
fig.suptitle('Time = ' + str(0*tstepPerAction) + ' ms')
idx = 0
lflow = []
if showflow and ldflow is None: ldflow = getoptflowframes(InputImages)
objfctr = 1.0
if 'UseFull' in dconf['DirectionDetectionAlgo']:
if dconf['DirectionDetectionAlgo']['UseFull']: objfctr=1/8.
for ldx,ax in enumerate(lax):
if ldx==0:
pcm = ax.imshow( lact[idx][0,:,:], origin='upper', cmap='gray', vmin=0, vmax=lvmax[idx])
ddat[ldx] = pcm
# ax.set_ylabel(ltitle[idx])
if dobjpos is not None:
lobjx,lobjy = [objfctr*dobjpos[k][0,0] for k in dobjpos.keys()], [objfctr*dobjpos[k][0,1] for k in dobjpos.keys()]
ddat['objpos'], = ax.plot(lobjx,lobjy,'ro')
else:
X, Y = np.meshgrid(np.arange(0, InputImages[0].shape[1], 1), np.arange(0,InputImages[0].shape[0],1))
ddat[ldx] = ax.quiver(X,Y,ldflow[0]['flow'][:,:,0],-ldflow[0]['flow'][:,:,1], pivot='mid', units='inches',width=0.01,scale=1/0.3)
ax.set_xlim((0,InputImages[0].shape[1])); ax.set_ylim((0,InputImages[0].shape[0]))
ax.invert_yaxis()
idx += 1
cumHits, cumMissed, cumScore = None,None,None
if actreward is not None:
cumHits, cumMissed, cumScore = getCumPerfCols(actreward)
def updatefig (t):
stitle = 'Time = ' + str(t*tstepPerAction) + ' ms'
if cumHits is not None:
if dconf['rewardcodes']['scorePoint'] > 0.0:
if skipopp:
stitle += '\nModel Points:'+str(cumScore[t]) + ' Model Hits:'+str(cumHits[t])
else:
stitle += '\nOpponent Points:'+str(cumMissed[t])+' Model Points:'+str(cumScore[t]) + ' Model Hits:'+str(cumHits[t])
else:
stitle += '\nModel Hits:'+str(cumHits[t]) + ' Model Misses:'+str(cumMissed[t])
fig.suptitle(stitle)
if t < 1: return fig # already rendered t=0 above
print('frame t = ', str(t*tstepPerAction))
for ldx,ax in enumerate(lax):
if ldx == 0:
ddat[ldx].set_data(lact[0][t,:,:])
if dobjpos is not None:
lobjx,lobjy = [objfctr*dobjpos[k][t,0] for k in dobjpos.keys()], [objfctr*dobjpos[k][t,1] for k in dobjpos.keys()]
ddat['objpos'].set_data(lobjx,lobjy)
else:
ddat[ldx].set_UVC(ldflow[t]['flow'][:,:,0],-ldflow[t]['flow'][:,:,1])
return fig
t1 = range(0,totalDur,tstepPerAction)
if nframe is None: nframe = len(t1)
if showflow: nframe-=1
ani = animation.FuncAnimation(fig, updatefig, interval=1, frames=nframe)
writer = anim.getwriter(outpath, framerate=framerate)
ani.save(outpath, writer=writer); print('saved animation to', outpath)
ion()
return fig
#
def getmaxdir (dact, ddir):
ddir = OrderedDict({'EV1DW':'W','EV1DNW':'NW', 'EV1DN':'N','EV1DNE':'NE','EV1DE':'E','EV1DSW':'SW','EV1DS':'S','EV1DSE':'SE'})
maxdirX = np.zeros(dact['EV1DW'].shape)
maxdirY = np.zeros(dact['EV1DW'].shape)
dAngDir = OrderedDict({'EV1DE': [1,0],'EV1DNE': [np.sqrt(2),np.sqrt(2)], # receptive field peak angles for the direction selective populations
'EV1DN': [0,1],'EV1DNW': [-np.sqrt(2),np.sqrt(2)],
'EV1DW': [-1,0],'EV1DSW': [-np.sqrt(2),-np.sqrt(2)],
'EV1DS': [0,-1],'EV1DSE': [np.sqrt(2),-np.sqrt(2)],
'NOMOVE':[0,0]})
for k in dAngDir.keys():
dAngDir[k][0] *= .4
dAngDir[k][1] *= -.4
for tdx in range(maxdirX.shape[0]):
for y in range(maxdirX.shape[1]):
for x in range(maxdirX.shape[2]):
maxval = 0
maxdir = 'NOMOVE'
for pop in ddir.keys():
if dact[pop][tdx,y,x] > maxval:
maxval = dact[pop][tdx,y,x]
maxdir = pop
maxdirX[tdx,y,x] = dAngDir[maxdir][0]
maxdirY[tdx,y,x] = dAngDir[maxdir][1]
return maxdirX,maxdirY
#
def animDetectedMotionMaps (outpath, framerate=10, figsize=(7,3)):
ioff()
# plot activity in different layers as a function of input images
ddir = OrderedDict({'EV1DW':'W','EV1DNW':'NW', 'EV1DN':'N','EV1DNE':'NE','EV1DE':'E','EV1DSW':'SW','EV1DS':'S','EV1DSE':'SE'})
if figsize is not None: fig, axs = plt.subplots(1, 3, figsize=figsize);
else: fig, axs = plt.subplots(1, 3);
lax = axs.ravel()
ltitle = ['Input Images', 'Motion', 'Detected Motion']
lact = [InputImages]; lvmax = [255];
lfnimage = []
lpop = ['ER', 'EV1', 'EV4', 'EMT', 'IR', 'IV1', 'IV4', 'IMT',\
'EV1DW','EV1DNW', 'EV1DN', 'EV1DNE','EV1DE','EV1DSW', 'EV1DS', 'EV1DSE',\
'EMDOWN','EMUP']
dmaxSpk = OrderedDict({pop:np.max(dact[pop]) for pop in lpop})
max_spks = np.max([dmaxSpk[p] for p in lpop])
for pop in lpop:
lact.append(dact[pop])
lvmax.append(max_spks)
ddat = {}
fig.suptitle('Time = ' + str(0*tstepPerAction) + ' ms')
maxdirX,maxdirY = getmaxdir(dact,ddir)
for ldx,ax in enumerate(lax):
if ldx == 0:
offidx = -1
pcm = ax.imshow(lact[0][offidx,:,:],origin='upper',cmap='gray',vmin=0,vmax=lvmax[0])
ddat[ldx] = pcm
elif ldx == 1:
X, Y = np.meshgrid(np.arange(0, InputImages[0].shape[1], 1), np.arange(0,InputImages[0].shape[0],1))
ddat[ldx] = ax.quiver(X,Y,ldflow[0]['flow'][:,:,0],-ldflow[0]['flow'][:,:,1], pivot='mid', units='inches',width=0.022,scale=1/0.15)
ax.set_xlim((0,InputImages[0].shape[1])); ax.set_ylim((0,InputImages[0].shape[0]))
ax.invert_yaxis()
elif ldx == 2:
X, Y = np.meshgrid(np.arange(0, InputImages[0].shape[1], 1), np.arange(0,InputImages[0].shape[0],1))
ddat[ldx] = ax.quiver(X,Y,maxdirX[0,:,:],maxdirY[0,:,:], pivot='mid', units='inches',width=0.022,scale=1/0.15)
ax.set_xlim((0,InputImages[0].shape[1])); ax.set_ylim((0,InputImages[0].shape[0]))
ax.invert_yaxis()
ax.set_ylabel(ltitle[ldx])
def updatefig (t):
fig.suptitle('Time = ' + str(t*tstepPerAction) + ' ms')
if t<1: return fig # already rendered t=0 above; skip last for optical flow
print('frame t = ', str(t*tstepPerAction))
for ldx,ax in enumerate(lax):
if ldx==0 or ldx==5:
offidx=-1
else:
offidx=0
if ldx == 0:
ddat[ldx].set_data(lact[0][t+offidx,:,:])
elif ldx == 1:
ddat[ldx].set_UVC(ldflow[t+offidx]['flow'][:,:,0],-ldflow[t]['flow'][:,:,1])
else:
ddat[ldx].set_UVC(maxdirX[t+offidx,:,:],maxdirY[t+offidx,:,:])
return fig
ani = animation.FuncAnimation(fig, updatefig, interval=1, frames=len(t1)-1)
writer = anim.getwriter(outpath, framerate=framerate)
ani.save(outpath, writer=writer); print('saved animation to', outpath)
ion()
return fig, axs, plt
def loadInputImages (name=None):
try:
fn = 'data/'+getsimname(name)+'InputImages.npy'
print('loading input images from', fn)
return np.load(fn)
except:
fn = 'data/'+getsimname(name)+'InputImages.txt'
print('loading input images from', fn)
Input_Images = np.loadtxt(fn)
New_InputImages = []
NB_Images = int(Input_Images.shape[0]/Input_Images.shape[1])
for x in range(NB_Images):
fp = x*Input_Images.shape[1]
# 20 is sqrt of 400 (20x20 pixels). what is 400? number of ER neurons? or getting rid of counter @ top of screen?
New_InputImages.append(Input_Images[fp:fp+Input_Images.shape[1],:])
return np.array(New_InputImages)
def loadMotionFields (name=None): return pickle.load(open('data/'+getsimname(name)+'MotionFields.pkl','rb'))
def loadObjPos (name=None): return pickle.load(open('data/'+getsimname(name)+'objpos.pkl','rb'))
def ObjPos2pd (dobjpos):
# convert object pos dictionary to pandas dataframe (for selection)
ballX,ballY = dobjpos['ball'][:,0],dobjpos['ball'][:,1]
racketX,racketY = dobjpos['racket'][:,0],dobjpos['racket'][:,1]
if 'time' in dobjpos:
time = dobjpos['time']
else:
time = np.linspace(0,totalDur,len(dobjpos['ball']))
pdpos = pd.DataFrame(np.array([time, ballX, ballY, racketX, racketY]).T,columns=['time','ballX','ballY','racketX','racketY'])
return pdpos
def getdistvstimecorr (pdpos, ballxmin=137, ballxmax=141, minN=2):
# get distance vs time
pdposs = pdpos[(pdpos.ballY>-1.0) & (pdpos.ballX>ballxmin) & (pdpos.ballX<ballxmax)]
lbally = np.unique(pdposs.ballY)
dout = {}
lr,ly,lN,lpval = [],[],[],[]
for y in lbally:
dout[y] = {}
pdposss = pdposs[(pdposs.ballY==y)]
dist = np.sqrt((pdposss.ballY - pdposss.racketY)**2)
#plot(pdposss.time, dist)
dout[y]['time'] = pdposss.time
dout[y]['dist'] = dist
dout[y]['rackety'] = pdposss.racketY
r,p=0,0
if len(pdposss.time) > 1: r,p = pearsonr(pdposss.time, dist)
if len(dist) >= minN:
lpval.append(p)
lr.append(r)
ly.append(y)
lN.append(len(dist))
dout['lbally'] = ly
dout['lr'] = lr
dout['lpval'] = lpval
dout['lN'] = lN
return dout
def getconcatobjpos (lfn):
# concatenate the object position data frames together so can correlate ball position with learning behavior
# lfn is a list of objpos.pkl filenames from the simulation
pdpos = None
for fn in lfn:
acl = ObjPos2pd(loadObjPos(fn))
if pdpos is None:
pdpos = acl
else:
acl.time += np.amax(pdpos.time)
pdpos = pdpos.append(acl)
return pdpos
def showSpatialBehaviorHitMiss(pdpos,hitsMiss,seqsBegs,seqsEnds):
# find y pos of ball and score at the end of each seq.
yballpos = []
hit_miss_seqs = []
for seq in range(len(seqsBegs)):
y = np.array(pdpos.iloc[seqsBegs[seq]:seqsEnds[seq]].ballY)
yballpos.append(y[np.where(y>1)[0][-1]])
hit_miss_seqs.append(hitsMiss[seq][-1])
hit_inds = np.where(np.array(hit_miss_seqs)==1)[0]
miss_inds = np.where(np.array(hit_miss_seqs)==-1)[0]
hhit = np.histogram(np.array(yballpos)[hit_inds],range(0,161,10))
hmiss = np.histogram(np.array(yballpos)[miss_inds],range(0,161,10))
width = 3
ypos0 = hhit[1][1:]-3
ypos1 = [x + width for x in ypos0]
plt.bar(ypos0, hhit[0], color ='b', width =width, edgecolor ='black', label ='Hits',align='edge')
plt.bar(ypos1, hmiss[0], color ='r', width = width, edgecolor ='black', label ='Miss',align='edge')
xlabel('ball ypos when hit or miss')
ylabel('count')
legend()
def showSpatialBehaviorStepWise(pdpos,actrewards,binsize):
# used binsize of 4
stepwise_correct_spatialmoves = np.zeros((160,160))
stepwise_incorrect_spatialmoves = np.zeros((160,160))
for step in range(len(pdpos)):
reward = actrewards.iloc[step].reward
x = pdpos.iloc[step].ballX
y = pdpos.iloc[step].ballY
r = pdpos.iloc[step].racketY
if reward==dconf['rewardcodes']['followTarget']:
if int(x)>0 and int(y)>0:
stepwise_correct_spatialmoves[int(x),int(y)]+=1
elif reward==dconf['rewardcodes']['avoidTarget']:
if int(x)>0 and int(y)>0:
stepwise_incorrect_spatialmoves[int(x),int(y)]+=1
ds_stepwise_correct_spatialmoves = np.zeros((int(160/binsize),int(160/binsize)))
ds_stepwise_incorrect_spatialmoves = np.zeros((int(160/binsize),int(160/binsize)))
icount = 0
for i in range(0,160,int(binsize)):
jcount = 0
for j in range(0,160,int(binsize)):
ds_stepwise_correct_spatialmoves[icount,jcount]=np.sum(stepwise_correct_spatialmoves[i:i+binsize,j:j+binsize])
ds_stepwise_incorrect_spatialmoves[icount,jcount]=np.sum(stepwise_incorrect_spatialmoves[i:i+binsize,j:j+binsize])
jcount+=1
icount+=1
stepwise_pcorrent_spatialmoves = np.divide(ds_stepwise_correct_spatialmoves,np.add(ds_stepwise_correct_spatialmoves,ds_stepwise_incorrect_spatialmoves))
plt.imshow(stepwise_pcorrent_spatialmoves.T)
plt.colorbar()
title('probability of correct move, when the ball is at a location')
def getspikehist (spkT, numc, binsz, tmax):
tt = np.arange(0,tmax,binsz)
nspk = [len(spkT[(spkT>=tstart) & (spkT<tstart+binsz)]) for tstart in tt]
nspk = [1e3*x/(binsz*numc) for x in nspk]
return tt,nspk
#
def getrate (dspkT,dspkID, pop, dnumc, tlim=None):
# get average firing rate for the population, over entire simulation
nspk = len(dspkT[pop])
ncell = dnumc[pop]
if tlim is not None:
spkT = dspkT[pop]
nspk = len(spkT[(spkT>=tlim[0])&(spkT<=tlim[1])])
return 1e3*nspk/((tlim[1]-tlim[0])*ncell)
else:
return 1e3*nspk/(totalDur*ncell)
def pravgrates (dspkT,dspkID,dnumc,tlim=None):
# print average firing rates over simulation duration
for pop in dspkT.keys(): print(pop,round(getrate(dspkT,dspkID,pop,dnumc,tlim=tlim),2),'Hz')
#
def drawraster (dspkT,dspkID,tlim=None,msz=2,skipstim=True):
# draw raster (x-axis: time, y-axis: neuron ID)
lpop=list(dspkT.keys()); lpop.reverse()
lpop = [x for x in lpop if not skipstim or x.count('stim')==0]
csm=cm.ScalarMappable(cmap=cm.prism); csm.set_clim(0,len(dspkT.keys()))
lclr = []
for pdx,pop in enumerate(lpop):
color = csm.to_rgba(pdx); lclr.append(color)
plot(dspkT[pop],dspkID[pop],'o',color=color,markersize=msz)
if tlim is not None:
xlim(tlim)
else:
xlim((0,totalDur))
xlabel('Time (ms)')
#lclr.reverse();
lpatch = [mpatches.Patch(color=c,label=s+' '+str(round(getrate(dspkT,dspkID,s,dnumc),2))+' Hz') for c,s in zip(lclr,lpop)]
ax=gca()
ax.legend(handles=lpatch,handlelength=1,loc='best')
ylim((0,sum([dnumc[x] for x in lpop])))
#
def drawcellVm (simConfig, ldrawpop=None,tlim=None, lclr=None):
csm=cm.ScalarMappable(cmap=cm.prism); csm.set_clim(0,len(dspkT.keys()))
if tlim is not None:
dt = simConfig['simData']['t'][1]-simConfig['simData']['t'][0]
sidx,eidx = int(0.5+tlim[0]/dt),int(0.5+tlim[1]/dt)
dclr = OrderedDict(); lpop = []
for kdx,k in enumerate(list(simConfig['simData']['V_soma'].keys())):
color = csm.to_rgba(kdx);
if lclr is not None and kdx < len(lclr): color = lclr[kdx]
cty = simConfig['net']['cells'][int(k.split('_')[1])]['tags']['cellType']
if ldrawpop is not None and cty not in ldrawpop: continue
dclr[kdx]=color
lpop.append(simConfig['net']['cells'][int(k.split('_')[1])]['tags']['cellType'])
if ldrawpop is None: ldrawpop = lpop
for kdx,k in enumerate(list(simConfig['simData']['V_soma'].keys())):
cty = simConfig['net']['cells'][int(k.split('_')[1])]['tags']['cellType']
if ldrawpop is not None and cty not in ldrawpop: continue
if tlim is not None:
plot(simConfig['simData']['t'][sidx:eidx],simConfig['simData']['V_soma'][k][sidx:eidx],color=dclr[kdx])
else:
plot(simConfig['simData']['t'],simConfig['simData']['V_soma'][k],color=dclr[kdx])
lpatch = [mpatches.Patch(color=c,label=s) for c,s in zip(dclr.values(),ldrawpop)]
ax=gca()
ax.legend(handles=lpatch,handlelength=1,loc='best')
if tlim is not None: ax.set_xlim(tlim)
#
def plotFollowBall (actreward, ax=None,cumulative=True,msz=3,binsz=1e3,color='r',pun=False):
# plot probability of model racket following target(predicted ball y intercept) vs time
# when cumulative == True, plots cumulative probability; otherwise bins probabilities over binsz interval
# not a good way to plot probabilities over time when uneven sampling - could resample to uniform intervals ...
# for now cumulative == False is not plotted at all ...
global tstepPerAction
if ax is None: ax = gca()
ax.plot([0,np.amax(actreward.time)],[0.5,0.5],'--',color='gray')
allproposed = actreward[(actreward.proposed!=-1)] # only care about cases when can suggest a proposed action
if dconf['useFollowMoveOutput']:
val = 1
if pun: val = -1
rewardingActions = np.where(allproposed.followtargetsign==val,1,0)
else:
rewardingActions = np.where(allproposed.proposed-allproposed.action==0,1,0)
if cumulative:
rewardingActions = np.cumsum(rewardingActions) # cumulative of rewarding action
cumActs = np.array(range(1,len(allproposed)+1))
aout = np.divide(rewardingActions,cumActs)
ax.plot(allproposed.time,aout,'.',color=color,markersize=msz)
else:
nbin = int(binsz / (np.array(actreward.time)[1]-np.array(actreward.time)[0]))
aout = avgfollow = [mean(rewardingActions[sidx:sidx+nbin]) for sidx in arange(0,len(rewardingActions),nbin)]
ax.plot(np.linspace(0,np.amax(actreward.time),len(avgfollow)), avgfollow, color=color,linewidth=msz)
ax.set_xlim((0,np.amax(actreward.time)))
ax.set_ylim((0,1))
ax.set_xlabel('Time (ms)'); ax.set_ylabel('p(Follow Target)')
return aout
def getCumScore (actreward):
# get cumulative score - assumes score has max reward
ScoreLoss = np.array(actreward.reward)
allScore = np.where(ScoreLoss==dconf['rewardcodes']['scorePoint'],1,0)
return np.cumsum(allScore) #cumulative score evolving with time.
#
def plotHitMiss (actreward,ax=None,msz=3,asratio=False,asbin=False,binsz=10e3,lclr=['r','g','b']):
if ax is None: ax = gca()
action_times = np.array(actreward.time)
Hit_Missed = np.array(actreward.hit)
allHit = np.where(Hit_Missed==1,1,0)
allMissed = np.where(Hit_Missed==-1,1,0)
cumHits = np.cumsum(allHit) #cumulative hits evolving with time.
cumMissed = np.cumsum(allMissed) #if a reward is -1, replace it with 1 else replace it with 0.
if asbin:
nbin = int(binsz / (np.array(actreward.time)[1]-np.array(actreward.time)[0]))
avgHit = np.array([sum(allHit[sidx:sidx+nbin]) for sidx in arange(0,len(allHit),nbin)])
avgMiss = np.array([sum(allMissed[sidx:sidx+nbin]) for sidx in arange(0,len(allMissed),nbin)])
score = avgHit / (avgHit + avgMiss)
ax.plot(np.linspace(0,np.amax(actreward.time),len(score)), score, color=lclr[0],linewidth=msz)
ax.set_ylabel('Hit/(Hit+Miss) ('+str(round(score[-1],2))+')')
return score
elif asratio:
ax.plot(action_times,cumHits/cumMissed,'-o',color=lclr[0],markersize=msz)
ax.set_xlim((0,np.max(action_times)))
ax.set_ylabel('Hit/Miss ('+str(round(cumHits[-1]/cumMissed[-1],2))+')')
return cumHits[-1]/cumMissed[-1]
else:
ax.plot(action_times,cumHits,'-o',color=lclr[0],markersize=msz)
ax.plot(action_times,cumMissed,'-o',color=lclr[1],markersize=msz)
ax.set_xlim((0,np.max(action_times)))
ax.set_ylim((0,np.max([cumHits[-1],cumMissed[-1]])))
ax.set_ylabel('Hit Ball ('+str(cumHits[-1])+'), Miss Ball ('+str(cumMissed[-1])+')')
return cumHits[-1],cumMissed[-1]
#
def plotHitMissRatioPerStep (lpda,ax=None):
if ax is None: ax=gca()
lhit,lmiss = [],[]
for pda in lpda:
hit,miss = plotHitMiss(pda,asratio=False,asbin=False,ax=ax)
lhit.append(hit); lmiss.append(miss)
cla()
lrat = np.array(lhit)/lmiss
cla(); plot(lrat,'k',linewidth=4); plot(lrat,'ko',markersize=15)
xlabel('Step',fontsize=35); ylabel('Hit/miss ratio',fontsize=35); xlim((0-.1,len(lhit)-1+.1))
return lrat
#
def plotScoreMiss (actreward,ax=None,msz=3,asratio=False,clr='r'):
if ax is None: ax = gca()
action_times = np.array(actreward.time)
Hit_Missed = np.array(actreward.hit)
allMissed = np.where(Hit_Missed==-1,1,0)
cumMissed = np.cumsum(allMissed) #if a reward is -1, replace it with 1 else replace it with 0.
cumScore = getCumScore(actreward)
if asratio:
ax.plot(action_times,cumScore/cumMissed,'-o',color=clr,markersize=msz)
ax.set_xlim((0,np.max(action_times)))
ax.set_ylabel('Score/Miss ('+str(round(cumScore[-1]/cumMissed[-1],2))+')')
return cumScore[-1]/cumMissed[-1]
else:
ax.plot(action_times,cumScore,'-o',color=clr,markersize=msz)
ax.set_xlim((0,np.max(action_times)))
ax.set_ylim((0,cumMissed[-1]))
ax.set_ylabel('Score ('+str(cumScore[-1])+')')
return cumScore[-1]
#
def plotScoreLoss (actreward,ax=None,msz=3):
# plot cumulative score points and lose points; assumes score/lose point is max/min reward
if ax is None: ax = gca()
action_times = np.array(actreward.time)
ScoreLoss = np.array(actreward.reward)
allScore = np.where(ScoreLoss==np.amax(ScoreLoss),1,0)
allLoss = np.where(ScoreLoss==np.amin(ScoreLoss),1,0)
cumScore = np.cumsum(allScore) #cumulative hits evolving with time.
cumLoss = np.cumsum(allLoss) #if a reward is -1, replace it with 1 else replace it with 0.
ax.plot(action_times,cumScore,'r-o',markersize=msz)
ax.plot(action_times,cumLoss,'b-o',markersize=msz)
ax.set_xlim((0,np.max(action_times)))
ax.set_ylim((0,np.max([cumScore[-1],cumLoss[-1]])))
ax.legend(('Score Point ('+str(cumScore[-1])+')','Lose Point ('+str(cumLoss[-1])+')'),loc='best')
return cumScore[-1],cumLoss[-1]
def getCumPerfCols (actreward):
# get cumulative performance arrays
action_times = np.array(actreward.time)
Hit_Missed = np.array(actreward.hit)
allMissed = np.where(Hit_Missed==-1,1,0)
cumMissed = np.cumsum(allMissed) #if a reward is -1, replace it with 1 else replace it with 0.
cumScore = getCumScore(actreward)
#actreward['cumScoreRatio'] = cumScore/cumMissed # cumulative score/loss ratio
allproposed = actreward[(actreward.proposed!=-1)] # only care about cases when can suggest a proposed action
rewardingActions = np.where(allproposed.proposed-allproposed.action==0,1,0)
rewardingActions = np.cumsum(rewardingActions) # cumulative of rewarding action
cumActs = np.array(range(1,len(allproposed)+1))
#actreward['cumFollow'] = np.divide(rewardingActions,cumActs) # cumulative follow probability
allHit = np.where(Hit_Missed==1,1,0)
allMissed = np.where(Hit_Missed==-1,1,0)
cumHits = np.cumsum(allHit) #cumulative hits evolving with time.
cumMissed = np.cumsum(allMissed) #if a reward is -1, replace it with 1 else replace it with 0.
#actreward['cumHitMissRatio'] = cumHits/cumMissed # cumulative hits/missed ratio
return cumHits, cumMissed, cumScore
def plotPerf (actreward,yl=(0,1),asratio=True,asbin=False,binsz=10e3):
# plot performance
plotFollowBall(actreward,ax=subplot(1,1,1),cumulative=True,color='b');
if dconf['useFollowMoveOutput']: plotFollowBall(actreward,ax=subplot(1,1,1),cumulative=True,color='m',pun=True);
plotHitMiss(actreward,ax=subplot(1,1,1),lclr=['g'],asratio=asratio,asbin=asbin,binsz=binsz);
plotScoreMiss(actreward,ax=subplot(1,1,1),clr='r',asratio=asratio);
ylim(yl)
ylabel('Performance')
if dconf['useFollowMoveOutput']:
lpatch = [mpatches.Patch(color=c,label=s) for c,s in zip(['b','m','g','r'],['Follow','Avoid','Hit/Miss','Score/Miss'])]
else:
lpatch = [mpatches.Patch(color=c,label=s) for c,s in zip(['b','g','r'],['Follow','Hit/Miss','Score/Miss'])]
ax=gca()
ax.legend(handles=lpatch,handlelength=1)
return ax
def plotComparePerf (lpda, lclr, yl=(0,.55), lleg=None, skipfollow=False, skipscore=False, asratio=True,asbin=False,binsz=10e3):
# plot comparison of performance of list of action rewards dataframes in lpda
# lclr is color to plot
# lleg is optional legend
ngraph=3
if skipfollow: ngraph-=1
if skipscore: ngraph-=1
for pda,clr in zip(lpda,lclr):
gdx=1
if not skipfollow: plotFollowBall(pda,ax=subplot(1,ngraph,gdx),cumulative=True,color=clr); ylim(yl); gdx+=1
plotHitMiss(pda,ax=subplot(1,ngraph,gdx),lclr=[clr],asratio=asratio,asbin=asbin,binsz=binsz); ylim(yl); gdx+=1
if not skipscore: plotScoreMiss(pda,ax=subplot(1,ngraph,gdx),clr=clr,asratio=asratio); ylim(yl);
if lleg is not None:
lpatch = [mpatches.Patch(color=c,label=s) for c,s in zip(lclr,lleg)]
ax=gca()
ax.legend(handles=lpatch,handlelength=1)
#
def plotRewards (actreward,ax=None,msz=3,xl=None):
if ax is None: ax = gca()
ax.plot(actreward.time,actreward.reward,'ko-',markersize=msz)
if xl is not None: ax.set_xlim(xl)
ax.set_ylim((np.min(actreward.reward),np.max(actreward.reward)))
ax.set_ylabel('Rewards'); #f_ax1.set_xlabel('Time (ms)')
def getactsel (dhist, actreward):
# get action selected based on firing rates in dhist (no check for consistency with sim.py)
actsel = []
for i in range(len(dhist['EMDOWN'][1])):
dspk, uspk = dhist['EMDOWN'][1][i], dhist['EMUP'][1][i]
if dspk > uspk:
actsel.append(dconf['moves']['DOWN'])
elif uspk > dspk:
actsel.append(dconf['moves']['UP'])
else: # dspk == uspk:
actsel.append(dconf['moves']['NOMOVE'])
return actsel
def getconcatweightpdf (lfn,usefinal=False):
# concatenate the weights together so can look at cumulative rewards,actions,etc.
# lfn is a list of actionrewards filenames from the simulation
pdf = None
for fn in lfn:
try:
wtmp = readinweights(fn,final=usefinal)
except:
try:
wtmp = readinweights(fn,final=True)
except:
print('could not load weights from', fn)
if pdf is None:
pdf = wtmp
else:
wtmp.time += np.amax(pdf.time)
pdf = pdf.append(wtmp)
return pdf
def getconcatactionreward (lfn):
# concatenate the actionreward data frames together so can look at cumulative rewards,actions,etc.
# lfn is a list of actionrewards filenames from the simulation
pda = None
for fn in lfn:
if not fn.endswith('ActionsRewards.txt'): fn = 'data/'+fn+'ActionsRewards.txt'
acl = pd.DataFrame(np.loadtxt(fn),columns=['time','action','reward','proposed','hit','followtargetsign'])
if pda is None:
pda = acl
else:
acl.time += np.amax(pda.time)
pda = pda.append(acl)
return pda
def getconcatactivity(lfn, lpop = allpossible_pops):
# CAUTION: this function assumes that the simConfig['simData']['spkid'] are preserved across the steps
spkIDs = []
spkTs = []
t_lastSim = 0
for fn in lfn:
conf.dconf = conf.readconf('backupcfg/'+fn+'sim.json')
simConfig = pickle.load(open('data/'+fn+'simConfig.pkl','rb'))
spkT = np.add(simConfig['simData']['spkt'],t_lastSim)
spkID = np.array(simConfig['simData']['spkid'])
for i in range(len(spkT)):
spkTs.append(spkT[i])
spkIDs.append(spkID[i])
totalDur = int(dconf['sim']['duration'])
t_lastSim = t_lastSim + totalDur
dstartidx, dendidx = {},{}
for p in lpop:
dstartidx[p] = simConfig['net']['pops'][p]['cellGids'][0]
dendidx[p] = simConfig['net']['pops'][p]['cellGids'][-1]
dspkID,dspkT = {},{}
spkIDs = np.array(spkIDs)
spkTs = np.array(spkTs)
for pop in lpop:
dspkID[pop] = spkIDs[(spkIDs>=dstartidx[pop])&(spkIDs<=dendidx[pop])]
dspkT[pop] = spkTs[(spkIDs>=dstartidx[pop])&(spkIDs<=dendidx[pop])]
return dspkID, dspkT, t_lastSim
def getindivactionreward (lfn):
# get the individual actionreward data frames separately so can compare cumulative rewards,actions,etc.
# lfn is a list of actionrewards filenames from the simulation or list of simulation names
if lfn[0].endswith('ActionsRewards.txt'):
return [pd.DataFrame(np.loadtxt(fn),columns=['time','action','reward','proposed','hit','followtargetsign']) for fn in lfn]
else:
return [pd.DataFrame(np.loadtxt('data/'+fn+'ActionsRewards.txt'),columns=['time','action','reward','proposed','hit','followtargetsign']) for fn in lfn]
def plotMeanNeuronWeight (pdf,postid,clr='k',ax=None,msz=1,xl=None):
if ax is None: ax = gca()
utimes = np.unique(pdf.time)
mnw,mxw=1e9,-1e9
pdfs = pdf[(pdf.postid==postid) & (pdf.postid==postid)]
wts = [np.mean(pdfs[(pdfs.time==t)].weight) for t in utimes] #wts of connections onto pop
ax.plot(utimes,wts,clr+'-o',markersize=msz)
mnw=min(mnw, min(wts))
mxw=max(mxw, max(wts))
if xl is not None: ax.set_xlim(xl)
ax.set_ylim((mnw,mxw))
ax.set_ylabel('Average weight');
return wts
def unnanl (l, val=0):
out = []
for x in l:
if isnan(x):
out.append(0)
else:
out.append(x)
return out
def plotMeanWeights (pdf,ax=None,msz=1,xl=None,lpop=['EMDOWN','EMUP'],lclr=['k','r','b','g'],plotindiv=True,fsz=15,prety=None):
#plot mean weights of all plastic synaptic weights onto lpop
if ax is None: ax = gca()
utimes = np.unique(pdf.time)
popwts = {}
mnw,mxw=1e9,-1e9
for pop,clr in zip(lpop,lclr):
#print(pop,clr)
if pop in dstartidx:
if plotindiv: