-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata_params.py
1921 lines (1675 loc) · 95 KB
/
data_params.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
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 23 13:52:03 2019
@author: Ibrahim Alperen Tunc
"""
"""
Analysis of the models and parameters filtered in the data_analysis.py file.
"""
#Null model
import pickle
import pandas as pd
import json
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as cls
import colclass as col
import sys
sys.path.insert(0,col.pathes.runpath)#!Change the directory accordingly
from supplementary_functions import std2kappa, depth_modulator, plotter, param_dict
from matplotlib.ticker import MultipleLocator, FormatStrFormatter, AutoMinorLocator
from mpl_toolkits.mplot3d import Axes3D
path=col.pathes.figpath
from datetime import date
from scipy.stats import chi2 as chisq
import plotly.express as px
dictTot=pickle.load(open("dicttot.pckl","rb"))#Dictionary of the subject average.
date=date.today()
def file_opener(dataName,rmsThres):
scpath=col.pathes.scanpath
paraml=pickle.load(open(scpath+"\\%s.pckl"%(dataName),"rb"))#Pickle file of the scanned parameters. This name should be changed according to the file wished to be analyzed.
meanrms=[]
#rmsThres=4.5#the RMS threshold for filtering the scan parameters
for i in range(0,len(paraml)):
meanrms.append(np.array(list(paraml[i]["dif"].values())).mean())#The mean root mean square error fo the filtered models
fltrms=[meanrms[np.where(np.array(meanrms)<rmsThres)[0][i]] for i in range(0,len(np.where(np.array(meanrms)<rmsThres)[0]))]#Take out the parameters which have a RMS >4
fltind=[np.where(np.array(meanrms)<rmsThres)[0][i] for i in range(0,len(np.where(np.array(meanrms)<rmsThres)[0]))]#index list of the fltrms
outind=[np.where(np.array(meanrms)>=rmsThres)[0][i] for i in range(0,len(np.where(np.array(meanrms)>=rmsThres)[0]))]#index list of the parameters not included in fltrms
fltrms, fltind=zip(*sorted(zip(fltrms,fltind)))#sort fltind and fltrms values in the same ascending order
return paraml, meanrms, fltrms, fltind, outind
def combine_scans(nuni,cuni,uni,nunirms,cunirms,unirms):
#Combine different model scans together, nuni is non uniform, cuni center only uniform and uni uniform model
#First three variables are scan dictionary lists, last 3 are mean rms values
for i in range(0,len(uni)):
try:
dep=uni[i]["depval"]
k=np.round(uni[i]["kci"],1)
uni[i].update({"depb":dep,"depu":dep,"kb":k,"ku":k})
except KeyError:
pass
try:
del(uni[i]["depval"])
del(uni[i]["kci"])
except KeyError:
pass
rmslist=nunirms+cunirms+unirms#all rms values coaggulated together in the order of nuni,cuni,uni
dictilist=nuni+cuni+uni#all scan dictionaries concatanated in nuni cuni uni order
indexlist=np.arange(0,len(dictilist))#index list of the dictionary list, used to order rms from small to big values
#without losing the track of the scan parameter set in dictionary list
#NOTE that here index list encompasses everything
rmslist1,indexlist=zip(*sorted(zip(rmslist,indexlist)))
return dictilist,rmslist,indexlist
"""
Histogram of the parameter distribution. FIGURE 6
"""
"""
popvec
"""
popVecParams,popVecRms,popvecflt,popvecind,popvecout=file_opener("paraml_fit_10_decoder_vecsum_errType_rms_2020-01-25_nocorr",4.5)
popVecParamsmf,popVecRmsmf,popvecfltmf,popvecindmf,popvecoutmf=file_opener("paraml_fit_10_decoder_vecsum_errType_rms_2020-01-25_nocorr_maxnorm",4.5)
popVecParamsuni,popVecRmsuni,popvecfltuni,popvecinduni,popvecoutuni=file_opener("paraml_fit_10_decoder_vecsum_errType_rms_2020-04-17_nocorr_uni",4.5)
popVecParamscuni,popVecRmscuni,popvecfltcuni,popvecindcuni,popvecoutcuni=file_opener("paraml_fit_10_decoder_vecsum_errType_rms_2020-04-17_nocorr_unicent",4.5)
"""
ml
"""
mlParams,mlRms,mlflt,mlind,mlout=file_opener("paraml_fit_10_decoder_ml_errType_rms_2019-08-23",4)
mlParamsuni,mlRmsuni,mlfltuni,mlinduni,mloutuni=file_opener("paraml_fit_10_decoder_ml_errType_rms_2020-04-17_uni",4.5)
mlParamscuni,mlRmscuni,mlfltcuni,mlindcuni,mloutcuni=file_opener("paraml_fit_10_decoder_ml_errType_rms_2020-04-17_unicent",4.5)
mlParamsmf,mlRmsmf,mlfltmf,mlindmf,mloutmf=file_opener("paraml_fit_10_decoder_ml_errType_rms_phase=22.5_maxfr_2020-05-26",4)
"""
Totally combined lists
"""
popVecParamstot,popVecRmstot,popvecindtot=combine_scans(popVecParams,popVecParamscuni,popVecParamsuni,popVecRms,popVecRmscuni,popVecRmsuni)
mlParamstot,mlRmstot,mlindtot=combine_scans(mlParams,mlParamscuni,mlParamsuni,mlRms,mlRmscuni,mlRmsuni)
"""
Same combination by using the maxact normalized scans (note that normalization is only matter of nonunif model as other models have same center bw!)
"""
popVecParamsmftot,popVecRmsmftot,popvecindmftot=combine_scans(popVecParamsmf,popVecParamscuni,popVecParamsuni,popVecRmsmf,popVecRmscuni,popVecRmsuni)
mlParamsmftot,mlRmsmftot,mlindmftot=combine_scans(mlParamsmf,mlParamscuni,mlParamsuni,mlRmsmf,mlRmscuni,mlRmsuni)
#mlParamsskm,mlRmsskm,mlfltskm,mlindskm,mloutskm=file_opener("paraml_fit_7_decoder_ml_errType_rms_2020-02-22_surkap_modulated_ksurphase_112.5",4)#surround kappa modulated scan
#mlParamsskm2,mlRmsskm2,mlfltskm2,mlindskm2,mloutskm2=file_opener("paraml_fit_7_decoder_ml_errType_rms_2020-02-20_surkap_modulated",4)#surround kappa modulated scan
#mlParamsskm3,mlRmsskm3,mlfltskm3,mlindskm3,mloutskm3=file_opener("paraml_fit_10_decoder_ml_errType_rms_ksurphase=22.5_kcentphase=112.5_2020-03-17",5)#not worked out well
#mlParamsskm4,mlRmsskm4,mlfltskm4,mlindskm4,mloutskm4=file_opener("paraml_fit_10_decoder_ml_errType_rms_ksurphase=112.5_kcentphase=22.5_2020-03-18",5)#not worked out well
#mlParamsskm5,mlRmsskm5,mlfltskm5,mlindskm5,mloutskm5=file_opener("paraml_fit_10_decoder_ml_errType_rms_ksurphase=112.5_kcentphase=22.5_2020-03-18",5)#not worked out well
plt.figure()
plt.hist(mlRms,bins=100,color="black")#min mean val is 3.74, taking mean rms=4 as threshold to look at parameter properties
plt.title("RMS histogram of models with different parameters maximum likelhood decoder",fontsize=20)
plt.xlabel("Root mean square error",fontsize=15)
plt.ylabel("Number of models",fontsize=15)
plt.xticks(np.arange(3.7,7.6,0.2),)
plt.tick_params(axis='both', which='major', labelsize=15)
plt.figure()
plt.hist(popVecRms,bins=100,color="black")#min mean val is 3.74, taking mean rms=4 as threshold to look at parameter properties
plt.title("RMS histogram of models with different parameters population vector decoder",fontsize=20)
plt.xlabel("Root mean square error",fontsize=15)
plt.ylabel("Number of models",fontsize=15)
plt.xticks(np.arange(3.7,7.6,0.2),)
plt.tick_params(axis='both', which='major', labelsize=15)
def param_calculator(paraml,fltind,outind,rmslist,rmsThres,dataPlot=False,deco="ml",paraml2=None,fltind2=None,datDict=None,speplot=False,unimod=False,bwType="gradient/sum",bwType2="gradient/sum",label=None,RMSnorm=False):
#paraml2 for deco=="both", that 2nd colmod model is created for the other decoder (1st ml, 2nd vecsum)
#speplot: use to specify the model you want to plot (based on the index entry)
#unimod: use to specify if plotted model is uniform or non-uniform (for uniform model the dictionary has to be slightly different)
#bwType is for 1st model, bwType2 only when bothdec
#label is for putting labels on the color coded parameter space plot
#for the parameter plot the number of subplots can be reduced to a considerable amount.
#to see which one is distributed to a wider area.
#RMSnorm: bool, optional. If true, the RMS values are normalized per decoder so that the minimum value is 1. This is used to
#compare relative distribution of the parameters for the decoders. You can also use it to only get the parameter distribution
#plots, since this variable has nothing to do with the RMS variable given to the function
"""
Calculate average center BW, min-max center BW difference, average sur mod depth, min-max sur mod depth by using following parameters:
Parameters: surround modulation width, average center BW, min-max center BW difference, average mod depth sur, min-max mod depth sur (phase all equal in this case)
"""
"""
Due to colormapping, some parts will be unnecessary, like filtering data (out ind) etc.
scheme:
fig=plt.figure()
ax=plt.subplot(4,1,1)
ax.scatter(mlflt,mlind,c=np.linspace(0,1,35),cmap="inferno")
plot = ax.pcolor([mlflt,mlind]); fig.colorbar(plot)
ax.set_xlim([3,5,4])
"""
if unimod==True:
kci=[]
ksi=[]
depval=[]
else:
smw=[]#surround modulation width
difc=[]#center min-max BW difference
difsm=[]#surround mod depth min-max difference
cabw=[]#center average BW
smad=[]#surround average mod depth
if deco=="ml":
decName="maximum likelihood"
elif deco=="vecsum":
decName="population vector"
elif deco=="both":
decName=None
else:
raise Exception("False decoder name given")
"""
calculation for fltrms/fltind parameters
"""
for i in range(0,len(paraml)):
if unimod==True:
kci.append(paraml[i]["kci"])
ksi.append(paraml[i]["ksi"])
depval.append(paraml[i]["depval"])
else:
smw.append(paraml[i]["ksi"])#ksi is the surround kappa values in the dictionary.
difc.append(paraml[i]["ku"]-paraml[i]["kb"])#the center min-max difference
difsm.append(paraml[i]["depu"]-paraml[i]["depb"])#surround modulation min-max difference
cabw.append(difc[i]/2+paraml[i]["kb"])#take the min max difference, divide by 2 and add minimal value to get the average bandwidth.
smad.append(difsm[i]/2+paraml[i]["depb"])#take the min max difference, divide by 2 and add below value the average mod depth.
"""
calculation for outind parameters
"""
if unimod==True:
kcif=[]
ksif=[]
depvalf=[]
else:
smwf=[]#surround mod width list for filtered out models
difcf=[]#center min-max BW difference list for filtered out models
difsmf=[]#surround mod depth min-max difference list for filtered out models
cabwf=[]#center average BW list for filtered out models
smadf=[]#surround average mod depth list for filtered out models
for i in range(0,len(outind)):#same loop as above for all model parameters with rms>4
if unimod==True:
kcif.append(paraml[outind[i]]["kci"])
ksif.append(paraml[outind[i]]["ksi"])
depvalf.append(paraml[outind[i]]["depval"])
else:
smwf.append(paraml[outind[i]]["ksi"])
difcf.append(paraml[outind[i]]["ku"]-paraml[outind[i]]["kb"])
difsmf.append(paraml[outind[i]]["depu"]-paraml[outind[i]]["depb"])
cabwf.append(difcf[i]/2+paraml[outind[i]]["kb"])#take the min max difference, divide by 2 and add below value
smadf.append(difsmf[i]/2+paraml[outind[i]]["depb"])#take the min max difference, divide by 2 and add below value
if unimod==True:
rmslist,kci,ksi,depval=zip(*sorted(zip(rmslist,kci,ksi,depval),reverse=True))
else:
rmslist,smw,difc,difsm,cabw,smad=zip(*sorted(zip(rmslist,smw,difc,difsm,cabw,smad),reverse=True))
"""
Plot the parameter triplets in 3D, make also 2D variant of the same (same number of plots) FIGURE 7
Leave it out for the time being
"""
"""
Plot formatting
"""
if unimod==True:
colMap=["gray","red","blue"]#color map
else:
plotdict={"smw":smw,"cBWd":difc,"smd":difsm,"caBW":cabw,"sma":smad}#to assign the parameters to an axes while plotting
plotdictf={"smwf":smwf,"difcf":difcf,"difsmf":difsmf,"cabwf":cabwf,"smadf":smadf}#to assign the parameters to an axes while plotting
params=["smw","cBWd","smd","caBW","sma"]#to name the parameters in the plot title
paramsf=["smwf","difcf","difsmf","cabwf","smadf"]#to name the parameters in the plot title
colMap=["gray","red","blue"]#color map
labmap=["rms>%s"%(rmsThres),"rms<%s"%(rmsThres),"best 10 models"]#label map
fig = plt.figure()
plt.title("Parameter distribution of models %s decoder"%(decName),fontsize=18,y=1.08)
plt.xticks([])#main plot figure ticks are off
plt.yticks([])#main plot figure ticks are off
plt.box(False)#the frame of the main plot is off
"""
Plot all triple combinations of the 5 parameters in a total of 10 subplots. FIGURE SUPPLEMENT 3
"""
i=0
for j in range(0,3):#combinations including smw
x=plotdict[params[j]]#parameters with rms<4
x1=plotdictf[paramsf[j]]#parameters with rms>4
x2=plotdict[params[j]][0:10]#best 10 model parameters
for k in range(1,4):#difc combinations
if j>=k:#stop if j>k to avoid repetition of the same parameter triplets.
continue
y=plotdict[params[k]]
y1=plotdictf[paramsf[k]]
y2=plotdict[params[k]][0:10]
for l in range(2,5):#remaining combinations
if j>=l:#stop if j>l to avoid repetition of the same parameter triplets.
continue
if k>=l:#stop if k>l to avoid repetition of the same parameter triplets.
continue
z=plotdict[params[l]]
z1=plotdictf[paramsf[l]]
z2=plotdict[params[l]][0:10]
i=i+1#in each iteration next subplot figure is chosen
ax=fig.add_subplot(3,4,i,projection='3d')#3D subplots.
ax.plot3D(x1,y1,z1,'o',color=colMap[0],label=labmap[0])
ax.plot3D(x,y,z,'o',color=colMap[1],label=labmap[1])
ax.plot3D(x2,y2,z2,'o',color=colMap[2],label=labmap[2])
ax.set_title('x=%s , y=%s , z=%s'%(params[j],params[k],params[l]),fontdict={'fontsize': 15, 'fontweight': 'medium'})#subplot title serves as the axis naming for each subplot.
ax.tick_params(axis='both', which='major', labelsize=13)#axes ticks are made bigger.
ax.legend(loc="best", bbox_to_anchor=(1.2,1),fontsize=15)
"""
Plot all pair combinations of the 5 parameters in a total of 10 subplots. The loop is structured the same as the triplet version.
FIGURE 7
"""
"""
Due to colormapping, some parts will be unnecessary, like filtering data (out ind) etc.
LAST PLOT HAS A MISTAKE ON COLOR CODE!!! SOMEHOW ONLY THE LAST ONE, something wrong in loop? nope all good now!
scheme:
fig=plt.figure()
ax=plt.subplot(4,1,1)
ax.scatter(mlflt,mlind,c=np.linspace(0,1,35),cmap="inferno")
plot = ax.pcolor([mlflt,mlind]); fig.colorbar(plot)
ax.set_xlim([3,5,4])
"""
i=0
fig2 = plt.figure()
if label!=None:
fig2.text(0.05,0.95,label,fontsize=20)
else:
pass
plt.title("Parameter distribution of models %s decoder"%(decName),y=1.08,fontsize=18)
plt.xticks([])
plt.yticks([])
plt.box(False)
for j in range(0,4):
x=plotdict[params[j]]
for k in range(1,5):
if j>=k:
continue
y=plotdict[params[k]]
i=i+1
ax=fig2.add_subplot(3,4,i)
a=ax.scatter(x,y,c=np.array(rmslist),cmap='coolwarm',edgecolors="none",s=10)
if RMSnorm==False:
a.set_clim(4.5-0.8,4.5+0.8)
else:
a.set_clim(min(rmslist),min(rmslist)+1.6)#color coding to each of the minimum RMS value.
#ax.set_facecolor("whitesmoke")
ax.set_title('x=%s , y=%s'%(params[j],params[k]),fontdict={'fontsize': 15, 'fontweight': 'medium'})
ax.tick_params(axis='both', which='major', labelsize=15)
colbar=plt.colorbar(a,extend="max")
colbar.ax.tick_params(labelsize=15)
plt.subplots_adjust(left=0.05, bottom=0.05, right=0.99, top=0.89, wspace=0.2, hspace=0.39)
if RMSnorm == True:
return
"""
Look at the filtered model fits with waitforbuttonpress
NOTE: this code should be stopped after a while, as it will go through each and every model in the uploaded file.
TO DO: Axis lines (x=0,y=0) and model estimates without psychophysics data DONE
"""
symDict={}
q=0#To track the number of the model fit.
labmap=["data","model"]#label map
surrInt=(135,90,45,180,0,225,270,315)#surround subplot order should be like this (see help(plotter.subplotter))
if speplot==False:
ran=range(0,len(fltind))
else:
ran=[eval(input("Enter the model index you want to plot in terms of fltind"))]#GIVE 0 for first entry of list
q=ran[0]
while q>=len(fltind):
print("The given index exceeds the number of filtered models")
ran=[eval(input("Enter the model index you want to plot"))]
print("Following model is plotted: \n%s"%(paraml[fltind[ran[0]]]))
for i in ran:
q=q+1#in each iteration the model fit number goes up by 1.
fig= plt.figure()
plt.title("Model fit for induced hue shift, model #%s"%(q),fontsize=20)#Figure formatting the usual way from here up until for loop.
plt.xticks([])
plt.yticks([])
plt.box(False)
ax=plt.gca()
ax.xaxis.set_label_coords(0.5, -0.07)
ax.yaxis.set_label_coords(-0.05,0.5)
plt.xlabel("Center-surround hue difference [°]",fontsize=20)
plt.ylabel("Induced hue shift [°]",fontsize=20)
symDict.update({q:{}})
for j in range(0,len(dictTot)):#Create the model and decoder objects for each surround by using the parameter sets. Dicttot has each surround condition as element inside.
#colMod=col.colmod(Kcent,Ksur,maxInh,stdInt,bwType="gradient/sum",phase=phase,avgSur=surrAvg[i],depInt=depInt,depmod=True,stdtransform=False)
if unimod==True:
print("uniform model")
colMod=col.colmod(paraml[fltind[i]]["kci"],paraml[fltind[i]]["ksi"],paraml[fltind[i]]["depval"],bwType="regular",\
avgSur=surrInt[j])
else:
colMod=col.colmod(1,paraml[fltind[i]]["ksi"],1,stdInt=[paraml[fltind[i]]["ku"],paraml[fltind[i]]["kb"]],bwType=bwType,\
phase=paraml[fltind[i]]["phase"],avgSur=surrInt[j],depInt=[paraml[fltind[i]]["depb"],paraml[fltind[i]]["depu"]],depmod=True,stdtransform=False)#The model for ml so gradient/sum
print("model phase is %s"%(paraml[fltind[i]]["phase"]))
if deco=="vecsum":
print("population vector decoder")
dec=col.decoder.vecsum(colMod.x,colMod.resulty,colMod.unitTracker,avgSur=surrInt[j],centery=colMod.centery)#the decoder
elif deco=="ml":
print("maximum likelihood decoder")
dec=col.decoder.ml(colMod.x,colMod.centery,colMod.resulty,colMod.unitTracker,avgSur=surrInt[j],tabStep=1)#the decoder
elif deco=="both":
print("both decoders at once")
if unimod==True:
print("uniform model")
colMod2=col.colmod(paraml2[fltind2[i]]["kci"],paraml2[fltind2[i]]["ksi"],paraml2[fltind2[i]]["depval"],bwType="regular",\
avgSur=surrInt[j])
else:
colMod2=col.colmod(1,paraml2[fltind2[i]]["ksi"],1,stdInt=[paraml2[fltind2[i]]["ku"],paraml2[fltind2[i]]["kb"]],bwType=bwType2,\
phase=paraml2[fltind2[i]]["phase"],avgSur=surrInt[j],depInt=[paraml2[fltind2[i]]["depb"],paraml2[fltind2[i]]["depu"]],depmod=True,stdtransform=False)#The model
print("phases of models are %s (ml) and %s (vecsum)"%(paraml[fltind[i]]["phase"],paraml2[fltind2[i]]["phase"]))
dec1=col.decoder.vecsum(colMod2.x,colMod2.resulty,colMod2.unitTracker,avgSur=surrInt[j],centery=colMod2.centery)#the decoder vecsum
dec2=col.decoder.ml(colMod.x,colMod.centery,colMod.resulty,colMod.unitTracker,avgSur=surrInt[j],tabStep=1)#the decoder ml
else:
pass
ax=plotter.subplotter(fig,j)#subplot the color tilt for each surround
if dataPlot==True:
if datDict==None:
ax.errorbar(dictTot[surrInt[j]]["angshi"].keys(),dictTot[surrInt[j]]["angshi"].values(),dictTot[surrInt[j]]["se"].values(),fmt='.',capsize=3,label=labmap[0],ecolor="gray",color="black")
else:
ax.errorbar(datDict[surrInt[j]]["angshi"].keys(),datDict[surrInt[j]]["angshi"].values(),datDict[surrInt[j]]["se"].values(),fmt='.',capsize=3,label=labmap[0],ecolor="gray",color="black")
#data plot with errorbars (above line)
if deco=="both":
ax.plot(dec1.centSurDif,dec1.angShift,color="green",label="population vector")#model plot
ax.plot(dec2.centSurDif,dec2.angShift,color="magenta",label="maximum likelihood")#model plot
ax.plot([0,0],[-25,25],color="black",linewidth=0.8)
ax.plot([-185,185],[0,0],color="black",linewidth=0.8)
ax.set_ylim(bottom=-25,top=25)#y axis limit +-25
ax.set_xlim([-185,185])
ax.set_xticks(np.linspace(-180,180,9))#x ticks between +-180 and ticks are at cardinal and oblique angles.
ax.set_yticks(np.linspace(-20,20,5))#x ticks between +-180 and ticks are at cardinal and oblique angles.
ax.tick_params(axis='both', which='major', labelsize=15)#major ticks are increazed in label size
ax.xaxis.set_major_locator(MultipleLocator(90))#major ticks at cardinal angles.
ax.xaxis.set_major_formatter(FormatStrFormatter('%d'))
ax.xaxis.set_minor_locator(MultipleLocator(45))#minor ticks at obliques.
print("1 subplot done")
else:
symDict[q].update({surrInt[j]:dec})
ax.plot(dec.centSurDif,dec.angShift,color=colMap[1],label=labmap[1])#model plot
ax.plot([0,0],[-25,25],color="black",linewidth=0.8)
ax.plot([-185,185],[0,0],color="black",linewidth=0.8)
ax.set_ylim(bottom=-25,top=25)#y axis limit +-25
ax.set_xlim([-185,185])
ax.set_xticks(np.linspace(-180,180,9))#x ticks between +-180 and ticks are at cardinal and oblique angles.
ax.set_yticks(np.linspace(-20,20,5))#x ticks between +-180 and ticks are at cardinal and oblique angles.
ax.tick_params(axis='both', which='major', labelsize=15)#major ticks are increazed in label size
ax.xaxis.set_major_locator(MultipleLocator(90))#major ticks at cardinal angles.
ax.xaxis.set_major_formatter(FormatStrFormatter('%d'))
ax.xaxis.set_minor_locator(MultipleLocator(45))#minor ticks at obliques.
print("1 subplot done")
ax.legend(loc="best", bbox_to_anchor=(1,1),fontsize=20)#add the legend to the subplot in the very end, after all surrounds are plotted.
if deco!="both":
plt.subplots_adjust(left=0.07, bottom=0.09, right=0.86, top=0.95, wspace=0.14, hspace=0.1)
else:
plt.subplots_adjust(left=0.07, bottom=0.11, right=0.73, top=0.95, wspace=0.12, hspace=0.13)
while True:#This line ensures the next color tilt curve is plotted when a keyboard button is pressed.
if plt.waitforbuttonpress(0):
break
plt.close()
a=input("continue? ")#if written yes to input, iteration goes on, if not, it stops :)
numa=1
while numa==1:
if a=="yes":
numa=0
pass
elif a=="no":
numa=0
return symDict
else:
numa=1
a=input("continue? ")
if deco!="both":
return symDict
else:
return
"""
THESE ARE KIND OF OBSOLETE NOW; USE THE TOTAL COMBNED LIST
bothdec=param_calculator(mlParams,mlind,mlout,mlRms,4.5,deco="both",dataPlot=True,paraml2=popVecParams,fltind2=popvecind)
bothdec2=param_calculator(mlParams,mlind,mlout,mlRms,4.5,deco="both",dataPlot=True,paraml2=popVecParamsmf,fltind2=popvecindmf,bwType2="gradient/max")
bothdecbest=param_calculator(mlParams,mlind,mlout,mlRms,4.5,deco="both",dataPlot=True,paraml2=popVecParamscuni,fltind2=popvecindcuni)
#Best models
mldec=param_calculator(mlParams,mlind,mlout,mlRms,4,deco="ml",dataPlot=True,label="A")
pvcuni=param_calculator(popVecParamscuni,popvecindcuni,popvecoutcuni,popVecRmscuni,4.5,deco="vecsum",dataPlot=True,bwType="gradient/sum",label="B",nonunif=False)
"""
mltot=param_calculator(mlParamstot,mlindtot,mlout,mlRmstot,4,deco="ml",dataPlot=True,label="A")#mlout now unnecessary parameter which has no effect so leave it be
pvtot=param_calculator(popVecParamstot,popvecindtot,popvecoutcuni,popVecRmstot,4.5,deco="vecsum",dataPlot=True,bwType="gradient/sum",label="B")
#!!!PLOTS LOOK UGLY; REDO THE UNI AND CUNI SCANS WITH EXACTLY THE SAME PARAMETER SCAN SPACE done
#Same with maxfr normalization in nonuniform model
mltotmf=param_calculator(mlParamsmftot,mlindmftot,mlout,mlRmsmftot,4,deco="ml",dataPlot=True,label="A")#mlout now unnecessary parameter which has no effect so leave it be
pvtotmf=param_calculator(popVecParamsmftot,popvecindmftot,popvecoutmf,popVecRmsmftot,4.5,deco="vecsum",dataPlot=True,bwType="gradient/max",label="B")
#best model fits considering also maxfr vs totarea normalizations:
bothdecbest=param_calculator(mlParams,mlind,mlout,mlRms,4.5,deco="both",dataPlot=True,paraml2=popVecParamsmf,fltind2=popvecindmf,bwType2="gradient/max")
bothdecbestttar=param_calculator(mlParams,mlind,mlout,mlRms,4.5,deco="both",dataPlot=True,paraml2=popVecParamstot,fltind2=popvecindtot)
#Other considerations
pvsum=param_calculator(popVecParams,popvecind,popvecout,popVecRms,4.5,deco="vecsum",dataPlot=True)
pvmf=param_calculator(popVecParamsmf,popvecindmf,popvecoutmf,popVecRmsmf,4.5,deco="vecsum",dataPlot=True,bwType="gradient/max")
#Generate the parameter scan with all color coding corresponding to the minimal RMS value of each decoder.
mltotn=param_calculator(mlParamstot,mlindtot,mlout,mlRmstot,4,deco="ml",dataPlot=True,label="A",RMSnorm=True)#mlout now unnecessary parameter which has no effect so leave it be
pvtotmfn=param_calculator(popVecParamsmftot,popvecindmftot,popvecoutmf,popVecRmsmftot,4.5,deco="vecsum",dataPlot=True,bwType="gradient/max",label="B",RMSnorm=True)
#Same trick as before, try to open the pckl file, if not create one
#TODO: redo this with popvec cuni
try:
with open('dictionaries_pvtotarea_2020-06-30.json',"rb") as file:
datDicts=json.load(file)
except FileNotFoundError:
print("forming the dictionaries")
mlSymDict=param_calculator(mlParamstot,mlindtot,mlout,mlRmstot,4,deco="ml",dataPlot=True,label="A")
popvecSymDict=param_calculator(popVecParamsmf,popvecindmf,popvecoutmf,popVecRmsmf,4.5,deco="vecsum",dataPlot=True,bwType="gradient/max",label="B")
jsondict={"ml":{},"vecsum":{}}
for i in list(mlSymDict[1].keys()):
csdml=mlSymDict[1][i].centSurDif
angsml=np.concatenate([*mlSymDict[1][i].angShift]).tolist()#to merge all values to a single array
csdvs=[float(i) for i in popvecSymDict[1][i].centSurDif] #one liner to convert integers to float (json creates problems)
angsvs=popvecSymDict[1][i].angShift
jsondict["ml"].update({i:{}})
jsondict["vecsum"].update({i:{}})
jsondict["ml"][i].update({"csd":csdml})
jsondict["ml"][i].update({"angs":angsml})
jsondict["vecsum"][i].update({"csd":csdvs})
jsondict["vecsum"][i].update({"angs":angsvs})
print("creating the json file")
with open('dictionaries_pvtotarea_%s.json'%(date), 'w') as f:
json.dump(jsondict, f)
print("json file is created")
except EOFError:
mlSymDict=param_calculator(mlParams,mlind,mlout,4)
popvecSymDict=param_calculator(popVecParams,popvecind,popvecout,4.5,deco="vecsum")
jsondict={"ml":{},"vecsum":{}}
for i in list(mlSymDict[1].keys()):
csdml=mlSymDict[1][i].centSurDif
angsml=np.concatenate([*mlSymDict[1][i].angShift]).tolist()#to merge all values to a single array
csdvs=[float(i) for i in popvecSymDict[1][i].centSurDif] #one liner to convert integers to float (json creates problems)
angsvs=popvecSymDict[1][i].angShift
jsondict["ml"].update({i:{}})
jsondict["vecsum"].update({i:{}})
jsondict["ml"][i].update({"csd":csdml})
jsondict["ml"][i].update({"angs":angsml})
jsondict["vecsum"][i].update({"csd":csdvs})
jsondict["vecsum"][i].update({"angs":angsvs})
with open('dictionariess_%s.json'%(date), 'w') as f:
json.dump(jsondict, f)
print("json file is filled")
"""
load json file:
with open('dictionariess_2019-11-17.json',"rb") as file:
data=json.load(file)
"""
"""
Best model different decoders RMS plots relative to different surrounds
"""
mlbestRMS=mlParamstot[mlindtot[0]]["dif"]
pvbestRMS=popVecParamsmftot[popvecindmftot[0]]["dif"]
plt.figure()
ax=plt.subplot(111)
ax.bar(np.array(list(mlbestRMS.keys()))-3,list(mlbestRMS.values()), width=5, edgecolor="magenta",color="None", align="center",label="Maximum likelihood",linewidth=3)
ax.bar(np.array(list(mlbestRMS.keys()))+3,list(pvbestRMS.values()), width=5, edgecolor="green",color="None", align="center",label="Population vector",linewidth=3)
ax.tick_params(axis='both', which='major', labelsize=25)
ax.set_xticks(np.linspace(0,315,8))
ax.set_xlabel("Surround hue angle [°]",fontsize=30)
ax.set_ylabel("RMS between data and model",fontsize=30)
plt.legend(loc="best",fontsize=20)
mng = plt.get_current_fig_manager()
mng.window.state("zoomed")
plt.pause(0.1)
plt.subplots_adjust(left=0.06, bottom=0.12, right=0.99, top=0.99, wspace=0, hspace=0)
plt.savefig(path+"\\decoder_models_comparison.pdf")
#mlSymDict=param_calculator(mlParams,mlind,mlout,4)
#popvecSymDict=param_calculator(popVecParams,popvecind,popvecout,4.5,deco="vecsum")
"""
Kappa and depmod distribution for different surround conditions for best model
Do after looking at the error correction stuff, as this could lead to change in vecsum object etc.
"""
#Kappa
def kappa_vals(kdown,kup,phase):
kapmod=(kdown-kup)/2*np.cos(2*np.deg2rad(np.linspace(0,359,360)-phase))+kup+(kdown-kup)/2#Kappa Modulator, see also depth_modulator() in supplementary_functions.py
return kapmod
#Suppression strength
def dep_vals(depInt,phase):
depval=[]
for i in np.linspace(0,359,360):
depval.append(depth_modulator(depInt,i,phase))
return depval
mlbest=mlParamstot[mlindtot[0]]
pvbest=popVecParamstot[popvecindtot[0]]
pvbestmf=popVecParamsmf[popvecindmf[0]]
mlkap=kappa_vals(mlbest["ku"],mlbest["kb"],mlbest["phase"])
pvkap=kappa_vals(pvbest["ku"],pvbest["kb"],pvbest["phase"])
pvkapmf=kappa_vals(pvbestmf["ku"],pvbestmf["kb"],pvbestmf["phase"])
mldep=dep_vals([mlbest["depb"],mlbest["depu"]],mlbest["phase"])
pvdep=dep_vals([pvbest["depb"],pvbest["depu"]],pvbest["phase"])
pvdepmf=dep_vals([pvbestmf["depb"],pvbestmf["depu"]],pvbestmf["phase"])
mlbestRMS=mlbest["dif"]
pvbestRMS=pvbest["dif"]
pvmfbestRMS=pvbestmf["dif"]
fig=plt.figure()
plt.title("Kappa distribution",fontsize=30,y=1.08)
plt.xticks([])
plt.yticks([])
plt.box(False)
ax1=fig.add_subplot(1,2,1,projection='polar')
ax1.plot(np.deg2rad(np.linspace(0,359,360)),mlkap,".",color="magenta",label="Maximum likelihood")
ax1.set_ylim(0.8,1.3)
ax1.set_yticks(np.arange(0.8,1.3,0.1))
ax1.tick_params(axis='both', which='major', labelsize=20)
ax1.set_title("Maximum likelihood",fontsize=30,y=1.08)
ax1=fig.add_subplot(1,2,2,projection='polar')
ax1.plot(np.deg2rad(np.linspace(0,359,360)),pvkap,".",color="green",label="Population vector decoder")
ax1.set_ylim(1.8,2.1)
ax1.set_yticks(np.arange(1.8,2.1,0.1))
ax1.tick_params(axis='both', which='major', labelsize=20)
ax1.set_title("Population vector decoder",fontsize=30,y=1.08)
fig=plt.figure()
plt.title("Surround modulation strength",fontsize=30,y=1.08)
plt.xticks([])
plt.yticks([])
plt.box(False)
ax1=fig.add_subplot(1,2,1,projection='polar')
ax1.plot(np.deg2rad(np.linspace(0,359,360)),mldep,".",color="magenta",label="Maximum likelihood")
ax1.set_ylim(0.1,0.5)
ax1.set_yticks(np.arange(0.1,0.5,0.1))
ax1.tick_params(axis='both', which='major', labelsize=20)
ax1.set_title("Maximum likelihood",fontsize=30,y=1.08)
ax1=fig.add_subplot(1,2,2,projection='polar')
ax1.plot(np.deg2rad(np.linspace(0,359,360)),pvdep,".",color="green",label="Population vector decoder")
ax1.set_ylim(0.3,0.7)
ax1.set_yticks(np.arange(0.4,0.7,0.1))
ax1.tick_params(axis='both', which='major', labelsize=20)
ax1.set_title("Population vector decoder",fontsize=30,y=1.08)
"""
Same as above but linear coordinate systems:
"""
fig=plt.figure()
plt.xticks([])
plt.yticks([])
plt.box(False)
ax1=fig.add_subplot(1,2,1)
ax1.plot(np.linspace(0,359,360),mlkap,color="magenta",label="Maximum likelihood",linewidth=3)
ax1.plot(np.linspace(0,359,360),pvkapmf,color="green",label="Population vector decoder",linewidth=3)
ax1.set_xticks(np.linspace(0,360,9))
ax1.xaxis.set_major_locator(MultipleLocator(90))
ax1.xaxis.set_major_formatter(FormatStrFormatter('%d'))
ax1.xaxis.set_minor_locator(MultipleLocator(45))
ax1.tick_params(axis='both', which='major', labelsize=20)
ax1.set_ylim([0,2.1])
ax1.set_title("Kappa distribution",fontsize=30)
ax2=fig.add_subplot(1,2,2)
ax2.plot(np.linspace(0,359,360),mldep,color="magenta",label="Maximum likelihood",linewidth=3)
ax2.plot(np.linspace(0,359,360),pvdepmf,color="green",label="Population vector decoder",linewidth=3)
ax2.tick_params(axis='both', which='major', labelsize=20)
ax2.set_xticks(np.linspace(0,360,9))
ax2.xaxis.set_major_locator(MultipleLocator(90))
ax2.xaxis.set_major_formatter(FormatStrFormatter('%d'))
ax2.xaxis.set_minor_locator(MultipleLocator(45))
ax2.set_yticks(np.linspace(0,0.6,7))
ax2.set_title("Surround modulation strength",fontsize=30)
ax1.legend(loc="best",prop={'size':20})
mng = plt.get_current_fig_manager()
mng.window.state("zoomed")
plt.pause(0.1)
plt.subplots_adjust(left=0.05, bottom=0.07, right=0.99, top=0.94, wspace=0.11, hspace=0.28)
plt.savefig(path+"\\dep_kap_plots.pdf")
#USE TOTAL AREA NORMALIZED VECSUM
"""
Depmod distribution plots for center-only uniform models
"""
mlbestcuni=mlParamscuni[mlindcuni[0]]
pvbestcuni=popVecParams[popvecindcuni[0]]
mldepcuni=dep_vals([mlbestcuni["depb"],mlbestcuni["depu"]],mlbestcuni["phase"])
pvdepcuni=dep_vals([pvbestcuni["depb"],pvbestcuni["depu"]],pvbestcuni["phase"])
fig=plt.figure()
plt.xticks([])
plt.yticks([])
ax1=fig.add_subplot(1,1,1)
ax1.plot(np.linspace(0,359,360),mldepcuni,color="magenta",label="Maximum likelihood",linewidth=3)
ax1.plot(np.linspace(0,359,360),pvdepcuni,color="green",label="Population vector decoder",linewidth=3)
ax1.set_xticks(np.linspace(0,360,9))
ax1.xaxis.set_major_locator(MultipleLocator(90))
ax1.xaxis.set_major_formatter(FormatStrFormatter('%d'))
ax1.xaxis.set_minor_locator(MultipleLocator(45))
ax1.tick_params(axis='both', which='major', labelsize=20)
ax1.set_yticks(np.linspace(0,0.8,9))
ax1.set_title("Surround modulation strength",fontsize=30)
ax1.legend(loc="best",prop={'size':20})
mng = plt.get_current_fig_manager()
mng.window.state("zoomed")
plt.pause(0.1)
plt.subplots_adjust(left=0.04, bottom=0.05, right=0.99, top=0.93, wspace=0.11, hspace=0.28)
#TODO: MAKE A SINGLE PLOT OUTTA THOSE 5 PLOTS ABOVE
#Take 2: put the polar plots inside the linear ones (https://stackoverflow.com/questions/17458580/embedding-small-plots-inside-subplots-in-matplotlib)
#Conclusion: Ignore polar plot, linear is enough
fig=plt.figure()
ax1=plt.subplot(2,1,1)#RMS PLOT
ax2=plt.subplot(2,2,3)#lin kappa
ax3=plt.subplot(2,2,4)#lin surr
#Plot fine tunings
plt.subplots_adjust(left=0.05, bottom=0.1, right=0.99, top=0.98, wspace=0.17, hspace=0.38)
fig.text(0.08,0.92,"A",fontsize=20)
fig.text(0.055,0.43,"B",fontsize=20)
fig.text(0.57,0.43,"C",fontsize=20)
#RMS PLOT
ax1.bar(np.array(list(mlbestRMS.keys()))-3,list(mlbestRMS.values()), width=5, edgecolor="magenta",color="None", align="center",label="Maximum likelihood",linewidth=3)
ax1.bar(np.array(list(mlbestRMS.keys()))+3,list(pvmfbestRMS.values()), width=5, edgecolor="green",color="None", align="center",label="Population vector",linewidth=3)
ax1.tick_params(axis='both', which='major', labelsize=15)
ax1.set_xticks(np.linspace(0,315,8))
ax1.set_xlabel("Surround hue angle [°]",fontsize=20)
ax1.set_ylabel("RMS",fontsize=20)
ax1.legend(bbox_to_anchor=(0.07,0.6),fontsize=15)
ax1.set_ylim([0,7.5])
ax1.set_yticks(np.arange(0,8))
#LINEAR PLOTS
#------------
#KAPPA
ax2.plot(np.linspace(0,359,360),mlkap,color="magenta",linewidth=3)
ax2.plot(np.linspace(0,359,360),pvkapmf,color="green",linewidth=3)
ax2.set_xticks(np.linspace(0,360,9))
ax2.xaxis.set_major_locator(MultipleLocator(90))
ax2.xaxis.set_major_formatter(FormatStrFormatter('%d'))
ax2.xaxis.set_minor_locator(MultipleLocator(45))
ax2.set_ylim([0.75,2.1])
ax2.set_yticks(np.linspace(0.8,2,7))
ax2.tick_params(axis='both', which='major', labelsize=15)
ax2.set_title("Tuning Bandwidth $\kappa$",fontsize=20)
ax2.set_xlabel("Preferred hue angle [°]",fontsize=20)
ax2.set_ylabel("$\kappa$",fontsize=20)
#SURR
ax3.plot(np.linspace(0,359,360),mldep,color="magenta",linewidth=3)
ax3.plot(np.linspace(0,359,360),pvdepmf,color="green",linewidth=3)
ax3.tick_params(axis='both', which='major', labelsize=15)
ax3.set_xticks(np.linspace(0,360,9))
ax3.xaxis.set_major_locator(MultipleLocator(90))
ax3.xaxis.set_major_formatter(FormatStrFormatter('%d'))
ax3.xaxis.set_minor_locator(MultipleLocator(45))
ax3.set_yticks(np.linspace(0,0.6,7))
ax3.set_ylim([0.1,0.67])
ax3.set_title("Surround Suppression Strength",fontsize=20)
ax3.set_xlabel("Surround hue angle [°]",fontsize=20)
ax3.set_ylabel("Suppression strength",fontsize=20)
plt.savefig(path+"\\new\\rms_dep_kap_plots_best_models.pdf")
"""
#POLAR KAPPA
#-----------
#ML
#ax2.set_title("Kappa distribution",fontsize=30,y=1.08)#Do with text
ax2.plot(np.deg2rad(np.linspace(0,359,360)),mlkap,".",color="magenta")
ax2.set_ylim(0.8,1.3)
ax2.set_yticks(np.arange(0.8,1.3,0.1))
ax2.tick_params(axis='both', which='major', labelsize=15)
#PV
ax3.plot(np.deg2rad(np.linspace(0,359,360)),pvkap,".",color="green")
ax3.set_ylim(1.7,1.9)
ax3.set_yticks(np.arange(1.7,1.9,0.1))
ax3.tick_params(axis='both', which='major', labelsize=15)
#POLAR SURR
#----------
#ML
#plt.title("Surround modulation strength",fontsize=30,y=1.08)#Text
ax4.plot(np.deg2rad(np.linspace(0,359,360)),mldep,".",color="magenta")
ax4.set_ylim(0.1,0.5)
ax4.set_yticks(np.arange(0.1,0.5,0.1))
ax4.tick_params(axis='both', which='major', labelsize=15)
#PV
ax5.plot(np.deg2rad(np.linspace(0,359,360)),pvdep,".",color="green")
ax5.set_ylim(0.3,0.7)
ax5.set_yticks(np.arange(0.4,0.7,0.1))
ax5.tick_params(axis='both', which='major', labelsize=15)
#Plot fine tuning
plt.subplots_adjust(left=0.04, bottom=0.05, right=0.99, top=0.98, wspace=0.12, hspace=0.41)
"""
"""
Check if the both decoders plot is now correct
fig=plotter.plot_template(auto=True)
angles=(135,90,45,180,0,225,270,315)
for i in range(0,8):
ax=plotter.subplotter(fig,i)
print(i)
while True:#This line ensures the next color tilt curve is plotted when a keyboard button is pressed.
if plt.waitforbuttonpress(0):
break
ax.plot(datDicts["ml"]["%s"%(angles[i])]["csd"],datDicts["ml"]["%s"%(angles[i])]["angs"],color="magenta")
ax.plot(datDicts["vecsum"]["%s"%(angles[i])]["csd"],datDicts["vecsum"]["%s"%(angles[i])]["angs"],color="green")
ax.errorbar(dictTot[angles[i]]["angshi"].keys(),dictTot[angles[i]]["angshi"].values(),dictTot[angles[i]]["se"].values(),fmt=".",capsize=3,ecolor="gray",color="black")
ax.set_xticks(np.linspace(-180,180,9))#x ticks between +-180 and ticks are at cardinal and oblique angles.
ax.set_yticks(np.linspace(-20,20,5))#x ticks between +-180 and ticks are at cardinal and oblique angles.
"""
"""
Look at best fitting parameter margins to make the interval smaller
depb10=[]
depu10=[]
kb10=[]
ku10=[]
ksi10=[]
depb10v=[]
depu10v=[]
kb10v=[]
ku10v=[]
ksi10v=[]
for i in range(0,len(mlind)):
depb10.append(mlParams[mlind[i]]["depb"])
depu10.append(mlParams[mlind[i]]["depu"])
kb10.append(mlParams[mlind[i]]["kb"])
ku10.append(mlParams[mlind[i]]["ku"])
ksi10.append(mlParams[mlind[i]]["ksi"])
for i in range(0,len(popvecind)):
depb10v.append(popVecParams[popvecind[i]]["depb"])
depu10v.append(popVecParams[popvecind[i]]["depu"])
kb10v.append(popVecParams[popvecind[i]]["kb"])
ku10v.append(popVecParams[popvecind[i]]["ku"])
ksi10v.append(popVecParams[popvecind[i]]["ksi"])
print(min(depb10),max(depu10),min(kb10),max(ku10),min(ksi10),max(ksi10),"ml")
print(min(depb10v),max(depu10v),min(kb10v),max(ku10v),min(ksi10v),max(ksi10v),"pv")
"""
def symmetry_analyzer(dicti):
symVal={"ml":{},"vecsum":{}}
angles=(135,90,45,180,0,225,270,315)
if dicti==dictTot:
name="Empirical data"#The data has to be reshaped, that RMS is calculated for
#each individual plot, then the average is taken for the total
symVal={"rms":{},"std":{},"angdif":{}}#angdif is the absolute mean angle difference per surround
fig=plotter.plot_template(auto=True)
plt.title("Symmetry analysis of %s"%(name),y=1.08,fontsize=30)
plt.xlabel("Absolute center surround angle difference [°]",fontsize=30)
plt.ylabel("Absolute hue shift [°]",fontsize=30)
for i in range(0,len(dicti)):
csdneg=np.flip(abs(np.array(list(dicti[angles[i]]["angshi"].keys())))[0:7],0)
angsneg=np.flip(abs(np.array(list(dicti[angles[i]]["angshi"].values())))[0:7],0)
negse=np.flip(abs(np.array(list(dicti[angles[i]]["se"].values())))[0:7],0)#standard error values at negative side
csdpos=np.array(list(dicti[angles[i]]["angshi"].keys()))[8:-1]
angspos=np.array(list(dicti[angles[i]]["angshi"].values()))[8:-1]
posse=np.array(list(dicti[angles[i]]["se"].values()))[8:-1]
angdif = np.mean(abs(angsneg-angspos))
rms=np.sqrt(((angsneg-angspos)**2).mean())
sd=np.std(abs(angsneg-angspos))#the standart deviation of the angle difference between halves (all positive)
symVal["rms"].update({angles[i]:rms})
symVal["std"].update({angles[i]:sd})
symVal["angdif"].update({angles[i]:angdif})
ax=plotter.subplotter(fig,i)
ax.errorbar(csdneg,angsneg,negse,fmt='x',capsize=3,markersize=5,label="negative",ecolor="blue",color="blue")
ax.errorbar(csdpos,angspos,posse,fmt='.',capsize=3,markersize=5,label="positive",ecolor="red",color="red")
#ax.plot(csdneg,angsneg,"x",color="blue",label="negative",markersize=10)
#ax.plot(csdpos,angspos,".",color="red",label="positive",markersize=10)
ax.set_xticks(np.linspace(0,180,9))#x ticks are between 0-180, in obliques and cardinal angles
ax.tick_params(axis='both', which='major', labelsize=20)#major ticks are bigger labeled
ax.xaxis.set_major_locator(MultipleLocator(45))#major ticks are set at 0,90,180,...
ax.xaxis.set_major_formatter(FormatStrFormatter('%d'))
ax.xaxis.set_minor_locator(MultipleLocator(22.5))#minor ticks are set at 45,135,..
ax.set_ylim(bottom=-3,top=25)#y axis is between +-30
if i==7:
ax.legend(loc="best",bbox_to_anchor=(1,1),fontsize=20)
mng = plt.get_current_fig_manager()
mng.window.state("zoomed")
plt.pause(0.1)
return symVal
else:
symVal={"ml":{},"vecsum":{}}
symVal["ml"].update({"angdif":{},"rms":{}})
symVal["vecsum"].update({"angdif":{},"rms":{}})
for i in ("ml","vecsum"):
if i=="ml":
name="maximum likelihood decoder"
else:
name="population vector decoder"
fig=plotter.plot_template(auto=True)
plt.title("Symmetry analysis of %s"%(name),y=1.08,fontsize=30)
plt.xlabel("Absolute center surround angle difference [°]",fontsize=30)
plt.ylabel("Absolute hue shift [°]",fontsize=30)
for j in (135,90,45,180,0,225,270,315):
if j<=180 and i=="vecsum" or j<180:
csdneg=np.flip(abs(np.array(dicti[i]["%s"%(j)]["csd"][0:dicti[i]["%s"%(j)]["csd"].index(0)])),0)#center surround differences are transformed into absolute values.
angsneg=np.flip(abs(np.array(dicti[i]["%s"%(j)]["angs"][0:dicti[i]["%s"%(j)]["csd"].index(0)])),0)#angular shifts are transformed into absolute values.
csdpos=np.array(dicti[i]["%s"%(j)]["csd"][dicti[i]["%s"%(j)]["csd"].index(0)+1:-1])
angspos=np.array(dicti[i]["%s"%(j)]["angs"][dicti[i]["%s"%(j)]["csd"].index(0)+1:-1])
else:
csdneg=np.flip(abs(np.array(dicti[i]["%s"%(j)]["csd"][1:dicti[i]["%s"%(j)]["csd"].index(0)])),0)#center surround differences are transformed into absolute values.
angsneg=np.flip(abs(np.array(dicti[i]["%s"%(j)]["angs"][1:dicti[i]["%s"%(j)]["csd"].index(0)])),0)#angular shifts are transformed into absolute values.
csdpos=np.array(dicti[i]["%s"%(j)]["csd"][dicti[i]["%s"%(j)]["csd"].index(0)+1:])
angspos=np.array(dicti[i]["%s"%(j)]["angs"][dicti[i]["%s"%(j)]["csd"].index(0)+1:])
angdif = np.mean(abs(angsneg-angspos))
rms=np.sqrt(((angsneg-angspos)**2).mean())
symVal[i]["rms"].update({j:rms})
symVal[i]["angdif"].update({j:angdif})
ax=plotter.subplotter(fig,angles.index(j))
ax.plot(csdneg,angsneg,"x",color="blue",label="negative",markersize=5)
ax.plot(csdpos,angspos,".",color="red",label="positive",markersize=5)
ax.set_xticks(np.linspace(0,180,9))#x ticks are between 0-180, in obliques and cardinal angles
ax.tick_params(axis='both', which='major', labelsize=20)#major ticks are bigger labeled
ax.xaxis.set_major_locator(MultipleLocator(45))#major ticks are set at 0,90,180,...
ax.xaxis.set_major_formatter(FormatStrFormatter('%d'))
ax.xaxis.set_minor_locator(MultipleLocator(22.5))#minor ticks are set at 45,135,..
ax.set_ylim(bottom=0,top=20)#y axis is between +-20
if angles.index(j)==7:
ax.legend(loc="best", bbox_to_anchor=(1,1),fontsize=15)
mng = plt.get_current_fig_manager()
mng.window.state("zoomed")
plt.pause(0.1)
return symVal
"""
else:
try:
str(dicti).index("vecsum")
name="population vector decoder"
except ValueError:
name="maximum likelihood decoder"
for i in range(1,len(dicti)+1):
symVal.update({i:{}})
fig=plotter.plot_template(auto=True)
plt.title("Symmetry analysis of %s"%(name),y=1.08,fontsize=30)
plt.xlabel("Absolute center surround angle difference [°]",fontsize=20)
plt.ylabel("Absolute hue shift [°]",fontsize=20)
for j in (135,90,45,180,0,225,270,315):
if j>=180 and name=="maximum likelihood decoder" or j>180:
csdneg=np.flip(abs(np.array(dicti[i][j].centSurDif[1:dicti[i][j].centSurDif.index(0)])),0)#center surround differences are transformed into absolute values.
angsneg=np.flip(abs(np.array(dicti[i][j].angShift[1:dicti[i][j].centSurDif.index(0)])),0)#angular shifts are transformed into absolute values.
csdpos=np.array(dicti[i][j].centSurDif[dicti[i][j].centSurDif.index(0)+1:])
angspos=np.array(dicti[i][j].angShift[dicti[i][j].centSurDif.index(0)+1:])
else:
csdneg=np.flip(abs(np.array(dicti[i][j].centSurDif[0:dicti[i][j].centSurDif.index(0)])),0)#center surround differences are transformed into absolute values.
angsneg=np.flip(abs(np.array(dicti[i][j].angShift[0:dicti[i][j].centSurDif.index(0)])),0)#angular shifts are transformed into absolute values.
csdpos=np.array(dicti[i][j].centSurDif[dicti[i][j].centSurDif.index(0)+1:-1])
angspos=np.array(dicti[i][j].angShift[dicti[i][j].centSurDif.index(0)+1:-1])
rms=np.sqrt(((angsneg-angspos)**2).mean())
symVal[i].update({j:rms})
ax=plotter.subplotter(fig,angles.index(j))
ax.plot(csdneg,angsneg,"x",color="blue",label="negative",markersize=10)
ax.plot(csdpos,angspos,".",color="red",label="positive",markersize=10)
ax.set_xticks(np.linspace(0,180,9))#x ticks are between 0-180, in obliques and cardinal angles
ax.tick_params(axis='both', which='major', labelsize=15)#major ticks are bigger labeled
ax.xaxis.set_major_locator(MultipleLocator(45))#major ticks are set at 0,90,180,...
ax.xaxis.set_major_formatter(FormatStrFormatter('%d'))
ax.xaxis.set_minor_locator(MultipleLocator(22.5))#minor ticks are set at 45,135,..
ax.set_ylim(bottom=0,top=20)#y axis is between +-20
if angles.index(j)==7:
ax.legend(loc="best", bbox_to_anchor=(1,1),fontsize=15)
mng = plt.get_current_fig_manager()
mng.window.state("zoomed")
plt.pause(0.1)
plt.savefig(path+"\\symmetry_analysis_%s.pdf"%(name))
return symVal
"""
datsym=symmetry_analyzer(dictTot)#data symmetry (no change necessary)
decsym=symmetry_analyzer(datDicts)#decoder symmetry (added the absolute mean difference per surround per 30.06)
mlsym = decsym["ml"]
popvecsym = decsym["vecsum"]
mlmeansymdif = np.mean(np.array(list(mlsym["angdif"].values())))
mlsymdifstd = np.std(np.array(list(mlsym["angdif"].values())))
pvmeansymdif = np.mean(np.array(list(popvecsym["angdif"].values())))
pvsymdifstd = np.std(np.array(list(popvecsym["angdif"].values())))
datmeansymdif = np.mean(np.array(list(datsym["angdif"].values())))
datsymdifstd = np.std(np.array(list(datsym["angdif"].values())))
plt.figure()
plt.title("Symmetry comparsion between decoders and data",y=1.08,fontsize=30)
plt.xlabel("Absolute center surround angle difference [°]",fontsize=30)
plt.ylabel("Average symmetry difference",fontsize=30)
#plt.ylim(0.1,2.5)
plt.plot(mlsym.keys(),mlsym.values(),".",color="magenta",label="maximum likelihood",markersize=15)
plt.plot(popvecsym.keys(),popvecsym.values(),".",color="green",label="population vector decoder",markersize=15)
plt.errorbar(datsym["rms"].keys(),datsym["rms"].values(),datsym["std"].values(),fmt='.',capsize=3,markersize=15,label="empirical data",ecolor="black",color="black")
plt.xticks(np.linspace(0,315,8))
plt.tick_params(axis='both', which='major', labelsize=20)#major ticks are bigger labeled
plt.legend(loc="best",fontsize=20)
plt.subplots_adjust(left=0.06, bottom=0.12, right=0.99, top=0.88, wspace=0, hspace=0)
mng = plt.get_current_fig_manager()
mng.window.state("zoomed")
plt.pause(0.1)
plt.savefig(path+"\\symmetry_decoder_comparison.pdf")
"""
Analysis of single individuals
"""
"""
Individual data dictionaries
"""