-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRetinotopicMapping.py
3033 lines (2355 loc) · 112 KB
/
RetinotopicMapping.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
__author__ = 'junz'
import numpy as np
import os
import scipy.ndimage as ni
import scipy.sparse as sparse
import math
import matplotlib.pyplot as plt
from itertools import combinations
from operator import itemgetter
import skimage.morphology as sm
import skimage.transform as tsfm
import matplotlib.colors as col
from matplotlib import cm
from core import FileTools as ft
from core import ImageAnalysis as ia
from core import PlottingTools as pt
def loadTrial(trialPath):
"""
load single retinotopic mapping trial from database
"""
trialDict = ft.loadFile(trialPath)
trial = RetinotopicMappingTrial(mouseID=trialDict['mouseID'], # str, mouseID
dateRecorded=trialDict['dateRecorded'], # int, date recorded, yearmonthday
comments=trialDict['comments'], # str, number of the trail on that day
altPosMap=trialDict['altPosMap'], # altitude position map
aziPosMap=trialDict['aziPosMap'], # azimuth position map
altPowerMap=trialDict['altPowerMap'], # altitude power map
aziPowerMap=trialDict['aziPowerMap'], # azimuth power map
vasculatureMap=trialDict['vasculatureMap'], # vasculature map
params=trialDict['params'])
try:
trial.altPosMapf = trialDict['altPosMapf']
except KeyError:
pass
try:
trial.aziPosMapf = trialDict['aziPosMapf']
except KeyError:
pass
try:
trial.altPowerMapf = trialDict['altPowerMapf']
except KeyError:
pass
try:
trial.aziPowerMapf = trialDict['aziPowerMapf']
except KeyError:
pass
try:
if isinstance(trialDict['finalPatches'].values()[0], dict):
trial.finalPatches = {}
for area, patchDict in trialDict['finalPatches'].items():
try:
trial.finalPatches.update({area: Patch(patchDict['array'], patchDict['sign'])})
except KeyError:
trial.finalPatches.update({area: Patch(patchDict['sparseArray'], patchDict['sign'])})
else:
pass
except KeyError:
pass
try:
if isinstance(trialDict['finalPatchesMarked'].values()[0], dict):
trial.finalPatchesMarked = {}
for area, patchDict in trialDict['finalPatchesMarked'].items():
try:
trial.finalPatchesMarked.update({area: Patch(patchDict['array'], patchDict['sign'])})
except KeyError:
trial.finalPatchesMarked.update({area: Patch(patchDict['sparseArray'], patchDict['sign'])})
else:
pass
except KeyError:
pass
try:
trial.signMap = trialDict['signMap']
except KeyError:
pass
try:
trial.signMapf = trialDict['signMapf']
except KeyError:
pass
try:
trial.rawPatchMap = trialDict['rawPatchMap']
except KeyError:
pass
try:
trial.rawPatches = trialDict['rawPatches']
except KeyError:
pass
try:
trial.eccentricityMapf = trialDict['eccentricityMapf']
except KeyError:
pass
return trial
def visualSignMap(phasemap1, phasemap2):
"""
calculate visual sign map from two orthogonally oriented phase maps
"""
if phasemap1.shape != phasemap2.shape:
raise LookupError("'phasemap1' and 'phasemap2' should have same size.")
gradmap1 = np.gradient(phasemap1)
gradmap2 = np.gradient(phasemap2)
# gradmap1 = ni.filters.median_filter(gradmap1,100.)
# gradmap2 = ni.filters.median_filter(gradmap2,100.)
graddir1 = np.zeros(np.shape(gradmap1[0]))
# gradmag1 = np.zeros(np.shape(gradmap1[0]))
graddir2 = np.zeros(np.shape(gradmap2[0]))
# gradmag2 = np.zeros(np.shape(gradmap2[0]))
for i in range(phasemap1.shape[0]):
for j in range(phasemap2.shape[1]):
graddir1[i, j] = math.atan2(gradmap1[1][i, j], gradmap1[0][i, j])
graddir2[i, j] = math.atan2(gradmap2[1][i, j], gradmap2[0][i, j])
# gradmag1[i,j] = np.sqrt((gradmap1[1][i,j]**2)+(gradmap1[0][i,j]**2))
# gradmag2[i,j] = np.sqrt((gradmap2[1][i,j]**2)+(gradmap2[0][i,j]**2))
vdiff = np.multiply(np.exp(1j * graddir1), np.exp(-1j * graddir2))
areamap = np.sin(np.angle(vdiff))
return areamap
def dilationPatches(rawPatches, smallPatchThr=5, borderWidth=1): # pixel width of the border after dilation
"""
dilation patched in a given area untill the border between them are as
narrow as defined by 'borderWidth'.
"""
# get patch borders
total_area = sm.convex_hull_image(rawPatches)
patchBorder = np.multiply(-1 * (rawPatches - 1), total_area)
# thinning patch borders
patchBorder = sm.skeletonize(patchBorder)
# thicking patch borders
if borderWidth > 1:
patchBorder = ni.binary_dilation(patchBorder, iterations=borderWidth - 1).astype(np.int)
# genertating new patches
newPatches = np.multiply(-1 * (patchBorder - 1), total_area)
# removing small edges
labeledPatches, patchNum = ni.label(newPatches)
for i in range(1, patchNum + 1):
currPatch = np.array(labeledPatches)
currPatch[currPatch != i] = 0
currPatch = currPatch / i
if (np.sum(np.multiply(currPatch, rawPatches)[:]) == 0) or (np.sum(currPatch[:]) < smallPatchThr):
# revCurrPatch = -1 * (currPatch - 1)
# newPatches = np.multiply(newPatches, revCurrPatch)
newPatches[currPatch == 1] = 0
else:
currPatch = ni.binary_closing(currPatch,
structure=np.ones((borderWidth + 2, borderWidth + 2))).astype(np.int)
newPatches[currPatch == 1] = 1
return newPatches
def dilationPatches2(rawPatches, dilationIter=20, borderWidth=1): # pixel width of the border after dilation
"""
dilation patched in a given area untill the border between them are as
narrow as defined by 'borderWidth'.
"""
total_area = ni.binary_dilation(rawPatches, iterations=dilationIter).astype(np.int)
patchBorder = total_area - rawPatches
# thinning patch borders
patchBorder = sm.skeletonize(patchBorder)
# thickening patch borders
if borderWidth > 1:
patchBorder = ni.binary_dilation(patchBorder, iterations=borderWidth - 1).astype(np.int)
# genertating new patches
newPatches = np.multiply(-1 * (patchBorder - 1), total_area)
# removing small edges
labeledPatches, patchNum = ni.label(newPatches)
newPatches2 = np.zeros(newPatches.shape, dtype=np.int)
for i in range(1, patchNum + 1):
currPatch = np.zeros(labeledPatches.shape, dtype=np.int)
currPatch[labeledPatches == i] = 1
currPatch[labeledPatches != i] = 0
if (np.sum(np.multiply(currPatch, rawPatches)[:]) > 0):
# currPatch = ni.binary_closing(currPatch,
# structure = np.ones((borderWidth+2,borderWidth+2))).astype(np.int)
newPatches2[currPatch == 1] = 1
return newPatches2
def labelPatches(patchmap, signMap):
"""
from a segregated patchmap generate a dictionary with each entry represents
a single patch, sorted by area
"""
labeledPatches, patchNum = ni.label(patchmap)
# list of area of every patch, first column: patch label, second column: area
patchArea = np.zeros((patchNum, 2), dtype=np.int)
for i in range(1, patchNum + 1):
currPatch = np.zeros(labeledPatches.shape, dtype=np.int)
currPatch[labeledPatches == i] = 1
currPatch[labeledPatches != i] = 0
patchArea[i - 1] = [i, np.sum(currPatch[:])]
# sort patches by the area, from largest to the smallest
sortArea = patchArea[patchArea[:, 1].argsort(axis=0)][::-1, :]
patches = {}
for i, ind in enumerate(sortArea[:, 0]):
currPatch = np.zeros(labeledPatches.shape, dtype=np.int)
currPatch[labeledPatches == ind] = 1
currPatch[labeledPatches != ind] = 0
currSignPatch = np.multiply(currPatch, signMap)
if np.sum(currSignPatch[:]) > 0:
currSign = 1
elif np.sum(currSignPatch[:]) < 0:
currSign = -1
else:
raise LookupError('This patch has no visual Sign!!')
patchname = 'patch' + ft.int2str(i, 2)
patches.update({patchname: Patch(currPatch, currSign)})
return patches
def phaseFilter(phaseMap, filterType='gaussian', filterSize=3, isPositive=True):
"""
smooth phaseMap in a circular fashion. filterType should be "gaussian" or "uniform"
isPositive: bool, if Ture return phase [0 2pi], if False return phase [-pi, pi]
"""
phaseMapSin = np.sin(phaseMap)
phaseMapCos = np.cos(phaseMap)
if filterType == 'Gaussian':
phaseMapSinf = ni.filters.gaussian_filter(phaseMapSin, filterSize)
phaseMapCosf = ni.filters.gaussian_filter(phaseMapCos, filterSize)
elif filterType == 'uniform':
phaseMapSinf = ni.filters.uniform_filter(phaseMapSin, filterSize)
phaseMapCosf = ni.filters.uniform_filter(phaseMapCos, filterSize)
else:
raise ValueError('filterType should be either "gaussian" or "uniform".')
phaseMapf = np.arctan2(phaseMapSinf, phaseMapCosf)
if isPositive:
phaseMapf = phaseMapf % (2 * np.pi)
return phaseMapf
def visualCoverage(patch, altMap, aziMap, pixelSize=2., closeIter=None, isPlot=False):
"""
get the visual response coverage of a cortical patch
:param patch:
:param altMap:
:param aziMap:
:param pixelSize: pixel size in visual space, deg
:param closeIter: closer iteration for generating visual coverage
:param isPlot:
:return:
"""
pixelSize = np.float(pixelSize)
altRange = np.array([-40., 60.])
aziRange = np.array([-20., 120.])
gridAzi, gridAlt = np.meshgrid(np.arange(aziRange[0], aziRange[1], pixelSize),
np.arange(altRange[0], altRange[1], pixelSize))
visualSpace = np.zeros((np.ceil((altRange[1] - altRange[0]) / pixelSize),
np.ceil((aziRange[1] - aziRange[0]) / pixelSize)))
patchArray = patch.array
for i in range(patchArray.shape[0]):
for j in range(patchArray.shape[1]):
if patchArray[i, j]:
corAlt = altMap[i, j]
corAzi = aziMap[i, j]
if (corAlt >= altRange[0]) & (corAlt < altRange[1]) & (corAzi >= aziRange[0]) & (corAzi < aziRange[1]):
indAlt = (corAlt - altRange[0]) // pixelSize
indAzi = (corAzi - aziRange[0]) // pixelSize
visualSpace[np.int(indAlt), np.int(indAzi)] = 1
if closeIter >= 1:
visualSpace = ni.binary_closing(visualSpace, iterations=closeIter).astype(np.int)
uniqueArea = np.sum(visualSpace[:]) * (pixelSize ** 2)
visualAltCenter = np.mean(gridAlt[visualSpace != 0])
visualAziCenter = np.mean(gridAzi[visualSpace != 0])
if isPlot:
plotVisualCoverage(visualSpace, pixelSize=pixelSize)
return visualSpace, uniqueArea, visualAltCenter, visualAziCenter
def plotVisualCoverage(visualSpace, pixelSize, altStart=-40, aziStart=-20, tickSpace=10, plotAxis=None):
"""
plot visual space in given plotAxis
"""
pixelSize = np.float(pixelSize)
altRange = np.arange(altStart, altStart + pixelSize * visualSpace.shape[0], pixelSize)
aziRange = np.arange(aziStart, aziStart + pixelSize * visualSpace.shape[1], pixelSize)
tickPixelSpace = int(tickSpace / pixelSize)
xtickInd = np.arange(int((aziStart % tickSpace) / pixelSize),
visualSpace.shape[1],
tickPixelSpace)
ytickInd = np.arange(int((altStart % tickSpace) / pixelSize),
visualSpace.shape[0],
tickPixelSpace)
xtickLabel = [str(int(round(aziRange[x]))) for x in xtickInd]
ytickLabel = [str(int(round(altRange[x]))) for x in ytickInd]
if not plotAxis:
f = plt.figure()
ax = f.add_subplot(111)
else:
ax = plotAxis
ax.imshow(visualSpace, cmap='hot_r', interpolation='nearest')
ax.invert_yaxis()
ax.set_aspect(1)
ax.set_xticks(xtickInd)
ax.set_xticklabels(xtickLabel)
ax.set_yticks(ytickInd)
ax.set_yticklabels(ytickLabel)
def localMin(eccMap, binSize):
"""
find local minimum of eccenticity map (in degree), with binning by binSize
in degree
"""
eccMap2 = np.array(eccMap)
cutStep = np.arange(np.nanmin(eccMap2[:]) - binSize,
np.nanmax(eccMap2[:]) + binSize * 2,
binSize)
NumOfMin = 0
i = 0
while (NumOfMin <= 1) and (i < len(cutStep)):
currThr = cutStep[i]
marker = np.zeros(eccMap.shape, dtype=np.int)
marker[eccMap2 <= (currThr)] = 1
marker, NumOfMin = ni.measurements.label(marker)
i = i + 1
# if NumOfMin == 1:
# print 'Only one local minumum was found!!!'
# elif NumOfMin == 0:
# print 'No local minumum was found!!!'
# else:
# print str(NumOfMin) + ' local minuma were found!!!'
#
# if NumOfMin > 1:
# plt.figure()
# plt.imshow(marker,vmin=np.amin(marker), vmax=np.amax(marker),cmap='jet',interpolation='nearest')
# plt.colorbar()
# plt.title('marker from local min')
return marker
def adjacentPairs(patches, borderWidth=2):
"""
return all the patch pairs with same visual sign and sharing border
"""
keyList = patches.keys()
pairKeyList = []
for pair in combinations(keyList, 2):
patch1 = patches[pair[0]]
patch2 = patches[pair[1]]
if (ia.is_adjacent(patch1.array, patch2.array, borderWidth=borderWidth)) and (patch1.sign == patch2.sign):
pairKeyList.append(pair)
return pairKeyList
def mergePatches(array1, array2, borderWidth=2):
"""
merge two binary patches with borderWidth no greater than borderWidth
"""
sp = array1 + array2
spc = ni.binary_closing(sp, iterations=(borderWidth)).astype(np.int8)
_, patchNum = ni.measurements.label(spc)
if patchNum > 1:
raise LookupError('this two patches are too far apart!!!')
else:
return spc
def eccentricityMap(altMap, aziMap, altCenter, aziCenter):
"""
calculate eccentricity map of with defined center
altMap, aziMap, altCenter, aziCenter: in degree
eccentricity map is returned in degree
"""
altMap2 = altMap * np.pi / 180
aziMap2 = aziMap * np.pi / 180
altCenter2 = altCenter * np.pi / 180
aziCenter2 = aziCenter * np.pi / 180
eccMap = np.zeros(altMap.shape)
eccMap[:] = np.nan
# for i in xrange(altMap.shape[0]):
# for j in xrange(altMap.shape[1]):
# alt = altMap2[i,j]
# azi = aziMap2[i,j]
# eccMap[i,j] = np.arctan(np.sqrt(np.tan(alt-altCenter2)**2 + ((np.tan(azi-aziCenter2)**2)/(np.cos(alt-altCenter2)**2))))
eccMap = np.arctan(
np.sqrt(
np.square(np.tan(altMap2 - altCenter2))
+
np.square(np.tan(aziMap2 - aziCenter2)) / np.square(np.cos(altMap2 - altCenter2))
)
)
eccMap = eccMap * 180 / np.pi
return eccMap
def sortPatches(patchDict):
"""
from a patch dictionary generate an new dictionary with patches sorted by there area
"""
patches = []
newPatchDict = {}
for key, value in patchDict.items():
patches.append((value, value.getArea()))
patches = sorted(patches, key=lambda a: a[1], reverse=True)
for i, item in enumerate(patches):
patchName = 'patch' + ft.int2str(i + 1, 2)
newPatchDict.update({patchName: item[0]})
return newPatchDict
def plotPatches(patches, plotaxis=None, zoom=1, alpha=0.5, markersize=5):
"""
plot a patches in a patch dictionary
"""
if plotaxis == None:
f = plt.figure()
plotaxis = f.add_axes([1, 1, 1, 1])
imageHandle = {}
for key, value in patches.items():
if zoom > 1:
currPatch = Patch(ni.zoom(value.array, zoom, order=0), value.sign)
else:
currPatch = value
h = plotaxis.imshow(currPatch.getSignedMask(), vmax=1, vmin=-1, interpolation='nearest', alpha=alpha, cmap='jet')
plotaxis.plot(currPatch.getCenter()[1], currPatch.getCenter()[0], '.k', markersize=markersize * zoom)
imageHandle.update({'handle_' + key: h})
plotaxis.set_xlim([0, currPatch.array.shape[1] - 1])
plotaxis.set_ylim([currPatch.array.shape[0] - 1, 0])
# plotaxis.set_axis_off()
return imageHandle
def plotPatchBorders(patches, plotaxis=None, borderWidth=2, color='#ff0000', zoom=1, isPlotCenter=True, isCenter=True,
rotationAngle=0): # rotation of map in degrees, counter-clockwise
# generating plot axis
if plotaxis == None:
f = plt.figure()
plotaxis = f.add_subplot(111)
cmap1 = col.ListedColormap(color, 'temp')
cm.register_cmap(cmap=cmap1)
borderArray = []
# initiating center and area
center = None
area = 0
for key, value in patches.items():
if zoom > 1:
currPatch = Patch(ni.zoom(value.array, zoom, order=0), value.sign)
currBorderWidth = borderWidth * zoom
else:
currPatch = value
currBorderWidth = borderWidth
# updating center
currArea = currPatch.getArea()
currCenter = currPatch.getCenter()
if currArea > area:
center = currCenter
area = np.int(currArea)
# print 'currArea:', currArea, ' currCenter:', currCenter, ' center:', center
# generating border array for the current patch
currBorder = currPatch.getBorder(borderWidth=currBorderWidth)
# adding center of current patches to the border array
if isPlotCenter:
currBorder[currCenter[0] - currBorderWidth - 1:currCenter[0] + currBorderWidth + 1,
currCenter[1] - currBorderWidth - 1:currCenter[1] + currBorderWidth + 1] = 1
currBorder[np.isnan(currBorder)] = 0
borderArray.append(currBorder)
# binarize border array
borderArray = np.sum(np.array(borderArray), axis=0)
borderArray[borderArray >= 1] = 1
# centering and expanding border array
if isCenter:
NW = np.array([0, 0])
NE = np.array([0, borderArray.shape[1]])
SW = np.array([borderArray.shape[0], 0])
SE = np.array([borderArray.shape[0], borderArray.shape[1]])
# calculate maximum distance to four corners
maxDis = np.int(np.ceil(np.max([ia.distance(center, NW),
ia.distance(center, NE),
ia.distance(center, SW),
ia.distance(center, SE)
])))
# calculate expansion distance to all four directions
expandN = maxDis - center[0]
expandS = maxDis - (borderArray.shape[0] - center[0])
expandE = maxDis - center[1]
expandW = maxDis - (borderArray.shape[1] - center[1])
borderArray = np.concatenate((np.zeros((expandN, borderArray.shape[1])), borderArray), axis=0)
borderArray = np.concatenate((borderArray, np.zeros((expandS, borderArray.shape[1]))), axis=0)
borderArray = np.concatenate((np.zeros((borderArray.shape[0], expandE)), borderArray), axis=1)
borderArray = np.concatenate((borderArray, np.zeros((borderArray.shape[0], expandW))), axis=1)
# rotating border array
borderArrayR = tsfm.rotate(borderArray, rotationAngle)
# binarize rotated border array
borderArrayR[borderArrayR > 0] = 1
# thinning rotated border array
# borderArrayR = sm.binary_opening(borderArrayR,np.array([[0,1,0],[1,1,1],[0,1,0]]))
borderArrayR = sm.skeletonize(borderArrayR)
# dilating rotated border array
borderArrayR = sm.binary_dilation(borderArrayR, sm.square(currBorderWidth))
# clear unwanted pixels
borderR = np.array(borderArrayR).astype(np.float32)
borderR[borderArrayR == 0] = np.nan
# plotting
imageHandle = plotaxis.imshow(borderR, vmin=0, vmax=1, cmap='temp', interpolation='nearest')
return imageHandle
def plotPatchBorders2(patches, plotAxis=None, plotSize=None, borderWidth=2, zoom=1, centerPatch=1, rotationAngle=0,
markerSize=2, closeIteration=None):
"""
plot rotated and centered patch borders
centerPatch defines center at which patch
1: center at the biggest patch
2: center at the second biggest patch
...
rotationAngle: rotation of map in degrees, counter-clockwise
markerSize: size of center dot
closeIteration: close iteration for patch borders
"""
# generating plot axis
if plotAxis == None:
f = plt.figure()
plotAxis = f.add_subplot(111)
# generating list for plotting
# for each patch: first item: center, second item: area, third item: patch array, forth item: sign
forPlotting = []
for key, value in patches.items():
currPatch = Patch(ni.zoom(value.array, zoom, order=0), value.sign)
forPlotting.append([currPatch.getCenter(),
currPatch.getArea(),
currPatch.getMask(),
value.sign])
# sort borders with area: biggest to smalles
forPlotting = sorted(forPlotting, key=lambda a: a[1], reverse=True)
# get the plotting center
center = forPlotting[centerPatch - 1][0]
# width and height of original plot
width = forPlotting[0][2].shape[1]
height = forPlotting[0][2].shape[0]
# coordinate of four corners
NW = np.array([0, 0])
NE = np.array([0, width])
SW = np.array([height, 0])
SE = np.array([height, width])
# calculate maximum distance to four corners
maxDis = np.int(np.ceil(np.max([ia.distance(center, NW),
ia.distance(center, NE),
ia.distance(center, SW),
ia.distance(center, SE)
])))
# calculate expansion distance to all four directions
expandN = maxDis - center[0]
expandS = maxDis - (height - center[0])
expandE = maxDis - center[1]
expandW = maxDis - (width - center[1])
for ind, value in enumerate(forPlotting):
# expanding border map for each patch
value[2] = np.concatenate((np.zeros((expandN, value[2].shape[1])), value[2]), axis=0)
value[2] = np.concatenate((value[2], np.zeros((expandS, value[2].shape[1]))), axis=0)
value[2] = np.concatenate((np.zeros((value[2].shape[0], expandE)), value[2]), axis=1)
value[2] = np.concatenate((value[2], np.zeros((value[2].shape[0], expandW))), axis=1)
value[2][value[2] == 0] = np.nan
# rotate border map for each patch
value[2] = tsfm.rotate(value[2], rotationAngle)
# #binarize current border map
# value[2][value[2]<0.9]=np.nan
# value[2][value[2]>=0.9]=1
# ploting current border
if value[3] == -1:
pt.plot_mask(value[2], plotAxis=plotAxis, color='#0000ff', borderWidth=borderWidth,
closingIteration=closeIteration)
elif value[3] == 1:
pt.plot_mask(value[2], plotAxis=plotAxis, color='#ff0000', borderWidth=borderWidth,
closingIteration=closeIteration)
# expanding center coordinate for each patch
value[0][0] = value[0][0] + expandN
value[0][1] = value[0][1] + expandE
# rotate center coordinate for each patch
x = value[0][1] - maxDis
y = maxDis - value[0][0]
xx = x * np.cos(rotationAngle * np.pi / 180) - y * np.sin(rotationAngle * np.pi / 180)
yy = y * np.cos(rotationAngle * np.pi / 180) + x * np.sin(rotationAngle * np.pi / 180)
value[0][0] = int(np.round(maxDis - yy))
value[0][1] = int(np.round(maxDis + xx))
# ploting current center
if value[3] == -1:
plotAxis.plot(value[0][1], value[0][0], '.b', markersize=markerSize)
elif value[3] == 1:
plotAxis.plot(value[0][1], value[0][0], '.r', markersize=markerSize)
if plotSize:
plotAxis.set_xlim([maxDis - plotSize / 2, maxDis + plotSize / 2])
plotAxis.set_ylim([maxDis + plotSize / 2, maxDis - plotSize / 2])
else:
plotAxis.set_xlim([0, 2 * maxDis])
plotAxis.set_ylim([2 * maxDis, 0])
plotAxis.get_xaxis().set_visible(False)
plotAxis.get_yaxis().set_visible(False)
return forPlotting
def plotPatchBorders3(patches, altPosMap, aziPosMap, plotAxis=None, plotSize=None, borderWidth=2, zoom=1,
centerPatchKey='patch01', markerSize=2, closeIteration=None, arrowLength=10):
"""
plot patch border centered and rotated by a certain patch defined by 'centerPatch'
also plot vetors of altitude gradiant and azimuth gradiant
plotSize: size of plotting area
centerPatchKey: size of center dot
closeIteration: open iteration for patch borders
arrowLength: length of arrow of gradiant
"""
# generating plot axis
if plotAxis == None:
f = plt.figure()
plotAxis = f.add_subplot(111)
# calculat rotation angle and center
try:
centerPatchObj = patches[centerPatchKey]
except KeyError:
area = []
for key, value in patches.items():
area.append([key, value.getArea()])
area = sorted(area, key=lambda a: a[1], reverse=True)
centerPatchKey = area[0][0]
centerPatchObj = patches[centerPatchKey]
altGradMap = np.gradient(altPosMap)
aziGradMap = np.gradient(aziPosMap)
# altGradMapX = np.sum(altGradMap[0] * centerPatchObj.array)
# altGradMapY = np.sum(altGradMap[1] * centerPatchObj.array)
aziGradMapX = np.sum(aziGradMap[0] * centerPatchObj.array)
aziGradMapY = np.sum(aziGradMap[1] * centerPatchObj.array)
rotationAngle = -(np.arctan2(-aziGradMapX, aziGradMapY) % (2 * np.pi)) * 180 / np.pi
# rotationAngle = 0
# print (np.arctan2(-altGradMapX,altGradMapY)%(2*np.pi))*180/np.pi
zoomedCenterPatch = Patch(ni.zoom(centerPatchObj.array, zoom, order=0), centerPatchObj.sign)
center = zoomedCenterPatch.getCenter()
# width and height of original plot
width = zoomedCenterPatch.array.shape[1]
height = zoomedCenterPatch.array.shape[0]
# coordinate of four corners
NW = np.array([0, 0])
NE = np.array([0, width])
SW = np.array([height, 0])
SE = np.array([height, width])
# calculate maximum distance to four corners
maxDis = np.int(np.ceil(np.max([ia.distance(center, NW),
ia.distance(center, NE),
ia.distance(center, SW),
ia.distance(center, SE)
])))
# calculate expansion distance to all four directions
expandN = maxDis - center[0]
expandS = maxDis - (height - center[0])
expandE = maxDis - center[1]
expandW = maxDis - (width - center[1])
for key, currPatch in patches.items():
zoomedArray = ni.zoom(currPatch.array, zoom, order=0)
# expanding border map for each patch
zoomedArray = np.concatenate((np.zeros((expandN, zoomedArray.shape[1])), zoomedArray), axis=0)
zoomedArray = np.concatenate((zoomedArray, np.zeros((expandS, zoomedArray.shape[1]))), axis=0)
zoomedArray = np.concatenate((np.zeros((zoomedArray.shape[0], expandE)), zoomedArray), axis=1)
zoomedArray = np.concatenate((zoomedArray, np.zeros((zoomedArray.shape[0], expandW))), axis=1)
# rotate border map for each patch
zoomedArray = tsfm.rotate(zoomedArray, rotationAngle)
# get center
zoomedCenter = np.round(np.mean(np.argwhere(zoomedArray).astype(np.float32), axis=0)).astype(np.int)
# binarize current border map
zoomedArray[zoomedArray < 0.9] = np.nan
zoomedArray[zoomedArray >= 0.9] = 1
# ploting current border
if currPatch.sign == -1:
pt.plot_mask(zoomedArray, plotAxis=plotAxis, color='#0000ff', borderWidth=borderWidth,
closingIteration=closeIteration)
plotAxis.plot(zoomedCenter[1], zoomedCenter[0], '.b', markersize=markerSize)
elif currPatch.sign == 1:
pt.plot_mask(zoomedArray, plotAxis=plotAxis, color='#ff0000', borderWidth=borderWidth,
closingIteration=closeIteration)
plotAxis.plot(zoomedCenter[1], zoomedCenter[0], '.r', markersize=markerSize)
# get gradiant vectors for current patch
currAltGradMapX = np.sum(altGradMap[0] * currPatch.array)
currAltGradMapY = np.sum(altGradMap[1] * currPatch.array)
currAltAngle = np.arctan2(-currAltGradMapX, currAltGradMapY) % (2 * np.pi) + (rotationAngle * np.pi / 180)
currAziGradMapX = np.sum(aziGradMap[0] * currPatch.array)
currAziGradMapY = np.sum(aziGradMap[1] * currPatch.array)
currAziAngle = np.arctan2(-currAziGradMapX, currAziGradMapY) % (2 * np.pi) + (rotationAngle * np.pi / 180)
# if key == centerPatchKey:
# print currAltAngle*180/np.pi
# print np.sin(currAltAngle)
# print np.cos(currAltAngle)
# plotting arrow for the current patch
plotAxis.arrow(zoomedCenter[1], zoomedCenter[0], arrowLength * zoom * np.cos(currAltAngle),
-arrowLength * zoom * np.sin(currAltAngle), color='#ff00ff', linewidth=2, width=0.5)
plotAxis.arrow(zoomedCenter[1], zoomedCenter[0], arrowLength * zoom * np.cos(currAziAngle),
-arrowLength * zoom * np.sin(currAziAngle), color='#00ffff', linewidth=2, width=0.5)
if plotSize:
plotAxis.set_xlim([maxDis - plotSize * zoom / 2, maxDis + plotSize * zoom / 2])
plotAxis.set_ylim([maxDis + plotSize * zoom / 2, maxDis - plotSize * zoom / 2])
else:
plotAxis.set_xlim([0, 2 * maxDis])
plotAxis.set_ylim([2 * maxDis, 0])
plotAxis.get_xaxis().set_visible(False)
plotAxis.get_yaxis().set_visible(False)
def plotPairedPatches(patch1, patch2, altMap, aziMap, title, pixelSize=1, closeIter=None):
visualSpace1, area1, _, _ = patch1.getVisualSpace(altMap=altMap,
aziMap=aziMap,
pixelSize=pixelSize,
closeIter=closeIter)
visualSpace2, area2, _, _ = patch2.getVisualSpace(altMap=altMap,
aziMap=aziMap,
pixelSize=pixelSize,
closeIter=closeIter)
visualSpace1 = np.array(visualSpace1, dtype=np.float32)
visualSpace2 = np.array(visualSpace2, dtype=np.float32)
visualSpace1[visualSpace1 == 0] = np.nan
visualSpace2[visualSpace2 == 0] = np.nan
f = plt.figure()
f.suptitle(title)
f_121 = f.add_subplot(121)
patchPlot1 = f_121.imshow(patch1.getMask(), interpolation='nearest', alpha=0.5, vmax=2, vmin=1)
patchPlot2 = f_121.imshow(patch2.getMask() * 2, interpolation='nearest', alpha=0.5, vmax=2, vmin=1)
f_121.set_title('patch1: blue, patch2: red')
f_122 = f.add_subplot(122)
areaPlot1 = f_122.imshow(visualSpace1, interpolation='nearest', alpha=0.5, vmax=2, vmin=1)
areaPlot2 = f_122.imshow(visualSpace2 * 2, interpolation='nearest', alpha=0.5, vmax=2, vmin=1)
f_122.set_title('area1: %.1f, area2: %.1f (deg^2)' % (area1, area2))
f_122.invert_yaxis()
# ---------------------------------------------------------------------------------------------
# reorganize visual space axis label
altRange = np.array([np.amin(altMap), np.amax(altMap)])
aziRange = np.array([np.amin(aziMap), np.amax(aziMap)])
xlist = np.arange(aziRange[0], aziRange[1], pixelSize)
ylist = np.arange(altRange[0], altRange[1], pixelSize)
xtick = []
xticklabel = []
i = 0
while i < len(xlist):
if int(np.floor(xlist[i])) % 10 == 0:
xtick.append(i)
xticklabel.append(str(int(np.floor(xlist[i]))))
i = int(i + 9 / pixelSize)
else:
i = i + 1
ytick = []
yticklabel = []
i = 0
while i < len(ylist):
if int(np.floor(ylist[i])) % 10 == 0:
ytick.append(i)
yticklabel.append(str(int(np.floor(ylist[i]))))
i = int(i + 9 / pixelSize)
else:
i = i + 1
f_122.set_xticks(xtick)
f_122.set_xticklabels(xticklabel)
f_122.set_yticks(ytick)
f_122.set_yticklabels(yticklabel)
def getPatchDict(patch):
return {'sparseArray': patch.sparseArray, 'sign': patch.sign}
class RetinotopicMappingTrial(object):
def __init__(self,
altPosMap, # altitude position map
aziPosMap, # azimuth position map
altPowerMap, # altitude power map
aziPowerMap, # azimuth power map
vasculatureMap, # vasculature map
mouseID, # str, mouseID
dateRecorded, # int, date recorded, yearmonthday
comments='', # str, comments of this particular trial
params={
'phaseMapFilterSigma': 1.,
'signMapFilterSigma': 9.,
'signMapThr': 0.35,
'eccMapFilterSigma': 10.,
'splitLocalMinCutStep': 5.,
'mergeOverlapThr': 0.1,
'closeIter': 3,
'openIter': 3,
'dilationIter': 15,
'borderWidth': 1,
'smallPatchThr': 100,
'visualSpacePixelSize': 0.5,
'visualSpaceCloseIter': 15,
'splitOverlapThr': 1.1
},
):
self.mouseID = mouseID
self.dateRecorded = dateRecorded
self.altPosMap = altPosMap
self.aziPosMap = aziPosMap
self.altPowerMap = altPowerMap
self.aziPowerMap = aziPowerMap
self.vasculatureMap = vasculatureMap
self.comments = comments
self.params = params
def getName(self):
trialName = str(self.dateRecorded) + \
'_M' + str(self.mouseID)
return trialName
def __str__(self):
return 'A retinotopic mapping trial: ' + self.getName()
def _getSignMap(self, isReverse=False, isPlot=False, isFixedRange=True):
altPosMapf = ni.filters.gaussian_filter(self.altPosMap,
self.params['phaseMapFilterSigma'])
aziPosMapf = ni.filters.gaussian_filter(self.aziPosMap,
self.params['phaseMapFilterSigma'])
if self.altPowerMap is not None: