-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathloopui.py
More file actions
1985 lines (1882 loc) · 93.1 KB
/
Copy pathloopui.py
File metadata and controls
1985 lines (1882 loc) · 93.1 KB
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 Tue Jun 1 15:13:56 2021
@author: Guillaume Pirot
"""
# import modules
from matplotlib import pyplot as plt
import numpy as np
from scipy.ndimage import label
from numpy.random import default_rng
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
from sklearn.cluster import KMeans
import pywt
from urllib.request import urlopen
import gzip
import pandas as pd
import glob,sys
base = np.e
#%% from noddyverse
# define colormap
def rand_cmap(nlabels, type='bright', first_color_black=True, last_color_black=False, verbose=True):
"""
Creates a random colormap to be used together with matplotlib. Useful for segmentation tasks
:param nlabels: Number of labels (size of colormap)
:param type: 'bright' for strong colors, 'soft' for pastel colors
:param first_color_black: Option to use first color as black, True or False
:param last_color_black: Option to use last color as black, True or False
:param verbose: Prints the number of labels and shows the colormap. True or False
:return: colormap for matplotlib
Thanks to https://gist.github.com/delestro/54d5a34676a8cef7477e
"""
from matplotlib.colors import LinearSegmentedColormap
import colorsys
import numpy as np
np.random.seed(seed=0)
if type not in ('bright', 'soft'):
print ('Please choose "bright" or "soft" for type')
return
if verbose:
print('Number of labels: ' + str(nlabels))
# Generate color map for bright colors, based on hsv
if type == 'bright':
randHSVcolors = [(np.random.uniform(low=0.0, high=1),
np.random.uniform(low=0.2, high=1),
np.random.uniform(low=0.9, high=1)) for i in range(nlabels)]
# Convert HSV list to RGB
randRGBcolors = []
for HSVcolor in randHSVcolors:
randRGBcolors.append(colorsys.hsv_to_rgb(HSVcolor[0], HSVcolor[1], HSVcolor[2]))
if first_color_black:
randRGBcolors[0] = [0, 0, 0]
if last_color_black:
randRGBcolors[-1] = [0, 0, 0]
random_colormap = LinearSegmentedColormap.from_list('new_map', randRGBcolors, N=nlabels)
# Generate soft pastel colors, by limiting the RGB spectrum
if type == 'soft':
low = 0.6
high = 0.95
randRGBcolors = [(np.random.uniform(low=low, high=high),
np.random.uniform(low=low, high=high),
np.random.uniform(low=low, high=high)) for i in range(nlabels)]
if first_color_black:
randRGBcolors[0] = [0, 0, 0]
if last_color_black:
randRGBcolors[-1] = [0, 0, 0]
random_colormap = LinearSegmentedColormap.from_list('new_map', randRGBcolors, N=nlabels)
# Display colorbar
if verbose:
from matplotlib import colors, colorbar
from matplotlib import pyplot as plt
fig, ax = plt.subplots(1, 1, figsize=(15, 0.5))
bounds = np.linspace(0, nlabels, nlabels + 1)
norm = colors.BoundaryNorm(bounds, nlabels)
cb = colorbar.ColorbarBase(ax, cmap=random_colormap, norm=norm, spacing='proportional', ticks=None,
boundaries=bounds, format='%1i', orientation=u'horizontal')
return random_colormap
#download file, ungzip and stuff into numpy array
def get_gz_array(url,skiprows):
my_gzip_stream = urlopen(url)
my_stream = gzip.open(my_gzip_stream, 'r')
return(np.loadtxt(my_stream,skiprows=skiprows))
#%% ENTROPY and CARDINALITY
def cardinality(array):
nbsamples = array.shape[-1]
voxetdim = array.shape[0:-1]
tmp = np.reshape(array,(np.prod(voxetdim),nbsamples))
crd = np.zeros(len(tmp))
classes = np.unique(tmp)
for c in range(len(classes)):
ixc = 1.0*(tmp==classes[c])
p = np.sum(ixc,axis=1)/nbsamples
crd += 1.0*(p>0)
crd=crd.reshape(voxetdim)
return crd
def cardinality_continuous_eq(array):
crdeq_min = np.amin(array,-1)
crdeq_max = np.amax(array,-1)
crdeq_rng = crdeq_max-crdeq_min
crdeq_std = np.std(array,-1)
crdeq_rngstd = (crdeq_std/np.amax(crdeq_std[np.isnan(crdeq_std)==False]) + crdeq_rng/np.amax(crdeq_rng[np.isnan(crdeq_rng)==False]))/2
return crdeq_rng,crdeq_std,crdeq_rngstd
def plot_cardinality(mag_crd,grv_crd,lit_crd,rho_crd,sus_crd,lgdlong,lgdsmall,litholgd):
fig, ax = plt.subplots(2,6) #,figsize=(13,13)
ax[0,0].axis('off')
ax[0,1].axis('off')
ax[0,2].axis('off')
ax[0,3].axis('off')
ax[0,4].axis('off')
ax[0,5].axis('off')
ax[1,0].axis('off')
ax[1,1].axis('off')
ax[1,2].axis('off')
ax[1,3].axis('off')
ax[1,4].axis('off')
ax[1,5].axis('off')
ax[0,0].set_title(lgdlong+' & '+litholgd )
ax[0,1].set_title(lgdsmall+' mag') #title.set_text
ax[0,2].set_title(lgdsmall+' grav')
ax[0,3].set_title(litholgd+' Map')
ax[0,4].set_title(litholgd+' W (N) E')
ax[0,5].set_title(litholgd+' N (W) S')
ax[1,0].set_title(lgdsmall+' density Map')
ax[1,1].set_title(lgdsmall+' density W (N) E')
ax[1,2].set_title(lgdsmall+' density N (W) S')
ax[1,3].set_title(lgdsmall+' mag. susc. Map')
ax[1,4].set_title(lgdsmall+' susc. W (N) E')
ax[1,5].set_title(lgdsmall+' susc. N (W) S')
ax[0,1].imshow(mag_crd,cmap='rainbow')
ax[0,2].imshow(grv_crd,cmap='rainbow')
ax[0,3].imshow(lit_crd[0,:,:],cmap='rainbow')
ax[0,4].imshow(lit_crd[:,0,:],cmap='rainbow')
ax[0,5].imshow(lit_crd[:,:,0],cmap='rainbow')
ax[1,0].imshow(rho_crd[0,:,:],cmap='rainbow')
ax[1,1].imshow(rho_crd[:,0,:],cmap='rainbow')
ax[1,2].imshow(rho_crd[:,:,0],cmap='rainbow')
ax[1,3].imshow(sus_crd[0,:,:],cmap='rainbow')
ax[1,4].imshow(sus_crd[:,0,:],cmap='rainbow')
ax[1,5].imshow(sus_crd[:,:,0],cmap='rainbow')
fig.subplots_adjust(left=0.0, bottom=0.0, right=2.0, top=1.05, wspace=0.1, hspace=0.1)
plt.show()
return
def entropy(array):
nbsamples = array.shape[-1]
voxetdim = array.shape[0:-1]
tmp = np.reshape(array,(np.prod(voxetdim),nbsamples))
ent = np.zeros(len(tmp))
classes = np.unique(tmp)
for c in range(len(classes)):
ixc = 1.0*(tmp==classes[c])
p = np.sum(ixc,axis=1)/nbsamples
ixp = np.where(p>0)
logpbase = np.zeros(len(tmp))
logpbase[ixp] = np.log(p[ixp])/np.log(base)
ent -= p * logpbase
ent=ent.reshape(voxetdim)
return ent
def entropyNcardinality(array):
nbsamples = array.shape[-1]
voxetdim = array.shape[0:-1]
tmp = np.reshape(array,(np.prod(voxetdim),nbsamples))
ent = np.zeros(len(tmp))
crd = np.zeros(len(tmp))
classes = np.unique(tmp)
for c in range(len(classes)):
ixc = 1.0*(tmp==classes[c])
p = np.sum(ixc,axis=1)/nbsamples
ixp = np.where(p>0)
logpbase = np.zeros(len(tmp))
logpbase[ixp] = np.log(p[ixp])/np.log(base)
ent -= p * logpbase
crd += 1.0*(p>0)
ent=ent.reshape(voxetdim)
crd=crd.reshape(voxetdim)
return ent,crd
def vec_hist(a, bins):
i = np.repeat(np.arange(np.product(a.shape[:-1])), a.shape[-1])
return np.histogram2d(i, a.flatten(), (a.shape[0], bins))[0] #.reshape(a.shape[:-1], -1)
def continuous_entropy(array,nbins):
nbsamples = array.shape[-1]
voxetdim = array.shape[0:-1]
array_min = np.nanmin(array.flatten())
array_max = np.nanmax(array.flatten())
ent=np.zeros(np.prod(voxetdim))
tmp = np.copy(np.reshape(array,(np.prod(voxetdim),nbsamples)))
tmp.sort(axis=1)
binlim = np.linspace(array_min,array_max,nbins+1)
histcount = vec_hist(tmp, binlim)
logpbase = np.zeros(histcount.shape)
p = histcount/nbsamples
ixp = np.where(p>0)
logpbase[ixp] = np.log(p[ixp])/np.log(base)
ent = -1*np.sum(p*logpbase,axis=1)
ent = np.reshape(ent,voxetdim)
return ent
#%% Multiple-Point Histogram Based distances
def stochastic_upscale(mx,seed):
rng = default_rng(seed)
ndim = len(mx.shape)
ux_shape = tuple(np.floor(np.asarray(mx.shape)/2).astype(int))
reductionfactor = 2**ndim
tmp_shape = list(np.floor( np.asarray(list(mx.shape))/2 ).astype(int))
tmp_shape.append(reductionfactor)
tmp_shape=tuple(tmp_shape)
tmp = np.ones(tmp_shape)*np.nan
v = np.array([0,1])
if ndim == 2:
ny,nx = mx.shape
[dx,dy]=np.meshgrid(v,v)
dx=dx.flatten().astype(int)
dy=dy.flatten().astype(int)
elif ndim ==3:
nz,ny,nx = mx.shape
[dx,dy,dz]=np.meshgrid(v,v,v)
dx=dx.flatten().astype(int)
dy=dy.flatten().astype(int)
dz=dz.flatten().astype(int)
else:
return -1
for i in range(reductionfactor):
if ndim == 2:
tmp2 = mx[dy[i]:ny+dy[i]:2,dx[i]:nx+dx[i]:2]
tmp[:,:,i] = tmp2[0:ux_shape[0],0:ux_shape[1]]
del tmp2
elif ndim==3:
tmp2 = mx[dz[i]:nz+dz[i]:2,dy[i]:ny+dy[i]:2,dx[i]:nx+dx[i]:2]
tmp[:,:,:,i] = tmp2[0:ux_shape[0],0:ux_shape[1],0:ux_shape[2]]
del tmp2
ix2 = np.reshape(np.floor(rng.uniform(0,reductionfactor-1e-12,np.prod(ux_shape))).astype(int),ux_shape).flatten()
ix1 = np.arange(np.prod(ux_shape)).flatten()
tmp = np.reshape(tmp,(np.prod(ux_shape),reductionfactor))
upscaled_mx = np.reshape(tmp[ix1,ix2],ux_shape)
return upscaled_mx
def dist_kmeans_mph(img1,img2,n_levels,patternsize,n_clusters,nmax_patterns,seed,plot=False,verb=False):
# initialize distance value for incrementation
d=0.0
# get ndim
ndim = len(img1.shape)
for l in range(n_levels+1):
rng = np.random.default_rng(2*seed+l)
if verb:
print('Level '+str(l))
# get pattern matrix shape
tmp_shape = list(np.asarray(list(img1.shape)) - patternsize +1)
tmp_shape.append(np.prod(patternsize))
tmp_shape=tuple(tmp_shape)
# get nb patterns
npat = np.prod(tmp_shape[:-1])
# get patterns and sample from img1 and img2
img1_all_patterns = np.ones(tmp_shape)*np.nan
img2_all_patterns = np.ones(tmp_shape)*np.nan
if verb:
print('Number of possible patterns: '+str(npat))
if ndim==2:
[ppdim1,ppdim0] = np.meshgrid(np.arange(patternsize[1]),np.arange(patternsize[0]))
ppdim0 = ppdim0.flatten()
ppdim1 = ppdim1.flatten()
for pp in range(np.prod(patternsize)):
img1_all_patterns[:,:,pp] = img1[ppdim0[pp]:tmp_shape[0]+ppdim0[pp],
ppdim1[pp]:tmp_shape[1]+ppdim1[pp]]
img2_all_patterns[:,:,pp] = img2[ppdim0[pp]:tmp_shape[0]+ppdim0[pp],
ppdim1[pp]:tmp_shape[1]+ppdim1[pp]]
elif ndim==3:
[ppdim2,ppdim1,ppdim0] = np.meshgrid(np.arange(patternsize[2]),np.arange(patternsize[1]),np.arange(patternsize[0]))
ppdim0 = ppdim0.flatten()
ppdim1 = ppdim1.flatten()
ppdim2 = ppdim2.flatten()
for pp in range(np.prod(patternsize)):
img1_all_patterns[:,:,:,pp] = img1[ppdim0[pp]:tmp_shape[0]+ppdim0[pp],
ppdim1[pp]:tmp_shape[1]+ppdim1[pp],
ppdim2[pp]:tmp_shape[2]+ppdim2[pp]]
img2_all_patterns[:,:,:,pp] = img2[ppdim0[pp]:tmp_shape[0]+ppdim0[pp],
ppdim1[pp]:tmp_shape[1]+ppdim1[pp],
ppdim2[pp]:tmp_shape[2]+ppdim2[pp]]
img1_all_patterns = np.reshape(img1_all_patterns,(npat,np.prod(patternsize)))
img2_all_patterns = np.reshape(img2_all_patterns,(npat,np.prod(patternsize)))
# subsamling the patterns
if npat>nmax_patterns:
ix_sub1 = (np.floor(rng.uniform(0,1,nmax_patterns)*(npat-1))).astype(int)
ix_sub2 = (np.floor(rng.uniform(0,1,nmax_patterns)*(npat-1))).astype(int)
else:
ix_sub1 = np.arange(npat)
ix_sub2 = np.arange(npat)
img1_patterns = img1_all_patterns[ix_sub1,:]
img2_patterns = img2_all_patterns[ix_sub2,:]
if verb:
print('Number of sub-sampled patterns: '+str(len(ix_sub1)))
del img1_all_patterns,img2_all_patterns,ix_sub1,ix_sub2
# kmeans clustering of patterns
kmeans_img1 = KMeans(n_clusters=n_clusters, random_state=0).fit(img1_patterns)
img1_cluster_id,img1_cluster_size = np.unique(kmeans_img1.labels_,return_counts=True)
kmeans_img2 = KMeans(n_clusters=n_clusters, random_state=0).fit(img2_patterns)
img2_cluster_id,img2_cluster_size = np.unique(kmeans_img2.labels_,return_counts=True)
# find best cluster pairing for mph dist computation
img_cluster_id_pairs_dist = np.ones((n_clusters,3))*np.nan # cluster_id1, cluster_id2, distance
cpy_img2_cluster_id = img2_cluster_id + 0
for c in range(n_clusters):
tmp_cluster = kmeans_img1.cluster_centers_[img1_cluster_id[c],:]
tmp_dist = (np.sum((kmeans_img2.cluster_centers_[cpy_img2_cluster_id,:] - tmp_cluster)**2,axis=1))**0.5
img_cluster_id_pairs_dist[c,0] = img1_cluster_id[c]
img_cluster_id_pairs_dist[c,1] = cpy_img2_cluster_id[np.argmin(tmp_dist)]
img_cluster_id_pairs_dist[c,2] = tmp_dist[np.argmin(tmp_dist)]
cpy_img2_cluster_id = np.delete(cpy_img2_cluster_id,np.argmin(tmp_dist))
# compute distance contribution as density weighted distance between closest best paired clusters
p1 = img1_cluster_size/np.sum(img1_cluster_size)
p2 = img2_cluster_size/np.sum(img2_cluster_size)
weights = (np.abs(p1-p2)/(p1+p2))
# weights_sum = np.sum(img1_cluster_size+img2_cluster_size)
# weights = img1_cluster_size[(img_cluster_id_pairs_dist[:,0]).astype(int)] + img2_cluster_size[(img_cluster_id_pairs_dist[:,1]).astype(int)]
# dist_mphc = np.sum( img_cluster_id_pairs_dist[:,2] * weights ) / weights_sum
dist_mphc = np.sum( ( (1+img_cluster_id_pairs_dist[:,2]) * (1+weights) - 1 ) )
d += dist_mphc/n_levels
if verb:
print('Distance component: '+str(dist_mphc/n_levels))
if plot:
plot_kmeans_mph(img1,img2,l,kmeans_img1,kmeans_img2,img_cluster_id_pairs_dist,patternsize,uniqueColorScale=False)
plot_kmeans_mph(img1,img2,l,kmeans_img1,kmeans_img2,img_cluster_id_pairs_dist,patternsize,uniqueColorScale=True)
if l<=n_levels:
img1 = stochastic_upscale(img1,seed+l)
img2 = stochastic_upscale(img2,seed+l)
del img_cluster_id_pairs_dist,tmp_cluster,tmp_dist,cpy_img2_cluster_id,kmeans_img1,kmeans_img2
del img1_cluster_id,img1_cluster_size,img2_cluster_id,img2_cluster_size
del tmp_shape,npat,img1_patterns,img2_patterns
return d
def plot_kmeans_mph(img1,img2,l,kmeans_img1,kmeans_img2,img_cluster_id_pairs_dist,patternsize,uniqueColorScale=False):
c10 = np.reshape(kmeans_img1.cluster_centers_[(img_cluster_id_pairs_dist[0,0]).astype(int),:],tuple(patternsize))
c11 = np.reshape(kmeans_img1.cluster_centers_[(img_cluster_id_pairs_dist[1,0]).astype(int),:],tuple(patternsize))
c12 = np.reshape(kmeans_img1.cluster_centers_[(img_cluster_id_pairs_dist[2,0]).astype(int),:],tuple(patternsize))
c13 = np.reshape(kmeans_img1.cluster_centers_[(img_cluster_id_pairs_dist[3,0]).astype(int),:],tuple(patternsize))
c14 = np.reshape(kmeans_img1.cluster_centers_[(img_cluster_id_pairs_dist[4,0]).astype(int),:],tuple(patternsize))
c15 = np.reshape(kmeans_img1.cluster_centers_[(img_cluster_id_pairs_dist[5,0]).astype(int),:],tuple(patternsize))
c16 = np.reshape(kmeans_img1.cluster_centers_[(img_cluster_id_pairs_dist[6,0]).astype(int),:],tuple(patternsize))
c17 = np.reshape(kmeans_img1.cluster_centers_[(img_cluster_id_pairs_dist[7,0]).astype(int),:],tuple(patternsize))
c18 = np.reshape(kmeans_img1.cluster_centers_[(img_cluster_id_pairs_dist[8,0]).astype(int),:],tuple(patternsize))
c19 = np.reshape(kmeans_img1.cluster_centers_[(img_cluster_id_pairs_dist[9,0]).astype(int),:],tuple(patternsize))
c20 = np.reshape(kmeans_img2.cluster_centers_[(img_cluster_id_pairs_dist[0,1]).astype(int),:],tuple(patternsize))
c21 = np.reshape(kmeans_img2.cluster_centers_[(img_cluster_id_pairs_dist[1,1]).astype(int),:],tuple(patternsize))
c22 = np.reshape(kmeans_img2.cluster_centers_[(img_cluster_id_pairs_dist[2,1]).astype(int),:],tuple(patternsize))
c23 = np.reshape(kmeans_img2.cluster_centers_[(img_cluster_id_pairs_dist[3,1]).astype(int),:],tuple(patternsize))
c24 = np.reshape(kmeans_img2.cluster_centers_[(img_cluster_id_pairs_dist[4,1]).astype(int),:],tuple(patternsize))
c25 = np.reshape(kmeans_img2.cluster_centers_[(img_cluster_id_pairs_dist[5,1]).astype(int),:],tuple(patternsize))
c26 = np.reshape(kmeans_img2.cluster_centers_[(img_cluster_id_pairs_dist[6,1]).astype(int),:],tuple(patternsize))
c27 = np.reshape(kmeans_img2.cluster_centers_[(img_cluster_id_pairs_dist[7,1]).astype(int),:],tuple(patternsize))
c28 = np.reshape(kmeans_img2.cluster_centers_[(img_cluster_id_pairs_dist[8,1]).astype(int),:],tuple(patternsize))
c29 = np.reshape(kmeans_img2.cluster_centers_[(img_cluster_id_pairs_dist[9,1]).astype(int),:],tuple(patternsize))
bc1 = np.bincount(kmeans_img1.labels_)
bc2 = np.bincount(kmeans_img2.labels_)
bc2 = bc2[(img_cluster_id_pairs_dist[:,1]).astype(int)]
tfs = 8
fig_m = plt.figure(constrained_layout=True)
gs = fig_m.add_gridspec(4, 7)
fm_ax1 = fig_m.add_subplot(gs[:2,:2])
fm_ax1.set_title('img1 level '+str(l)),fm_ax1.axis('off')
fm_ax2 = fig_m.add_subplot(gs[2:,:2])
fm_ax2.set_title('img2 level '+str(l)),fm_ax2.axis('off')
fm_ax10 = fig_m.add_subplot(gs[0,2])
fm_ax10.axis('off'),fm_ax10.set_title(str(bc1[1]),fontsize=tfs) #'CP '+str((img_cluster_id_pairs_dist[0,0]).astype(int))+' - '+
fm_ax11 = fig_m.add_subplot(gs[0,3])
fm_ax11.axis('off'),fm_ax11.set_title(str(bc1[1]),fontsize=tfs) #'CP '+str((img_cluster_id_pairs_dist[1,0]).astype(int))+' - '+
fm_ax12 = fig_m.add_subplot(gs[0,4])
fm_ax12.axis('off'),fm_ax12.set_title(str(bc1[2]),fontsize=tfs) #'CP '+str((img_cluster_id_pairs_dist[2,0]).astype(int))+' - '+
fm_ax13 = fig_m.add_subplot(gs[0,5])
fm_ax13.axis('off'),fm_ax13.set_title(str(bc1[3]),fontsize=tfs) #'CP '+str((img_cluster_id_pairs_dist[3,0]).astype(int))+' - '+
fm_ax14 = fig_m.add_subplot(gs[0,6])
fm_ax14.axis('off'),fm_ax14.set_title(str(bc1[4]),fontsize=tfs) #'CP '+str((img_cluster_id_pairs_dist[4,0]).astype(int))+' - '+
fm_ax15 = fig_m.add_subplot(gs[1,2])
fm_ax15.axis('off'),fm_ax15.set_title(str(bc1[5]),fontsize=tfs) #'CP '+str((img_cluster_id_pairs_dist[5,0]).astype(int))+' - '+
fm_ax16 = fig_m.add_subplot(gs[1,3])
fm_ax16.axis('off'),fm_ax16.set_title(str(bc1[6]),fontsize=tfs) #'CP '+str((img_cluster_id_pairs_dist[6,0]).astype(int))+' - '+
fm_ax17 = fig_m.add_subplot(gs[1,4])
fm_ax17.axis('off'),fm_ax17.set_title(str(bc1[7]),fontsize=tfs) #'CP '+str((img_cluster_id_pairs_dist[7,0]).astype(int))+' - '+
fm_ax18 = fig_m.add_subplot(gs[1,5])
fm_ax18.axis('off'),fm_ax18.set_title(str(bc1[8]),fontsize=tfs) #'CP '+str((img_cluster_id_pairs_dist[8,0]).astype(int))+' - '+
fm_ax19 = fig_m.add_subplot(gs[1,6])
fm_ax19.axis('off'),fm_ax19.set_title(str(bc1[9]),fontsize=tfs) #'CP '+str((img_cluster_id_pairs_dist[9,0]).astype(int))+' - '+
fm_ax20 = fig_m.add_subplot(gs[2,2])
fm_ax20.axis('off'),fm_ax20.set_title(str(bc2[0]),fontsize=tfs) #'CP '+str((img_cluster_id_pairs_dist[0,1]).astype(int))+' - '+
fm_ax21 = fig_m.add_subplot(gs[2,3])
fm_ax21.axis('off'),fm_ax21.set_title(str(bc2[1]),fontsize=tfs) #'CP '+str((img_cluster_id_pairs_dist[1,1]).astype(int))+' - '+
fm_ax22 = fig_m.add_subplot(gs[2,4])
fm_ax22.axis('off'),fm_ax22.set_title(str(bc2[2]),fontsize=tfs) #'CP '+str((img_cluster_id_pairs_dist[2,1]).astype(int))+' - '+
fm_ax23 = fig_m.add_subplot(gs[2,5])
fm_ax23.axis('off'),fm_ax23.set_title(str(bc2[3]),fontsize=tfs) #'CP '+str((img_cluster_id_pairs_dist[3,1]).astype(int))+' - '+
fm_ax24 = fig_m.add_subplot(gs[2,6])
fm_ax24.axis('off'),fm_ax24.set_title(str(bc2[4]),fontsize=tfs) #'CP '+str((img_cluster_id_pairs_dist[4,1]).astype(int))+' - '+
fm_ax25 = fig_m.add_subplot(gs[3,2])
fm_ax25.axis('off'),fm_ax25.set_title(str(bc2[5]),fontsize=tfs) #'CP '+str((img_cluster_id_pairs_dist[5,1]).astype(int))+' - '+
fm_ax26 = fig_m.add_subplot(gs[3,3])
fm_ax26.axis('off'),fm_ax26.set_title(str(bc2[6]),fontsize=tfs) #'CP '+str((img_cluster_id_pairs_dist[6,1]).astype(int))+' - '+
fm_ax27 = fig_m.add_subplot(gs[3,4])
fm_ax27.axis('off'),fm_ax27.set_title(str(bc2[7]),fontsize=tfs) #'CP '+str((img_cluster_id_pairs_dist[7,1]).astype(int))+' - '+
fm_ax28 = fig_m.add_subplot(gs[3,5])
fm_ax28.axis('off'),fm_ax28.set_title(str(bc2[8]),fontsize=tfs) #'CP '+str((img_cluster_id_pairs_dist[8,1]).astype(int))+' - '+
fm_ax29 = fig_m.add_subplot(gs[3,6])
fm_ax29.axis('off'),fm_ax29.set_title(str(bc2[9]),fontsize=tfs) #'CP '+str((img_cluster_id_pairs_dist[9,1]).astype(int))+' - '+
if uniqueColorScale==True:
vmin1 = np.amin(img1)
vmin2 = np.amin(img2)
vmax1 = np.amax(img1)
vmax2 = np.amax(img2)
vmin = np.min([vmin1,vmin2])
vmax = np.min([vmax1,vmax2])
fm_ax1.imshow(img1,vmin=vmin,vmax=vmax)
fm_ax2.imshow(img2,vmin=vmin,vmax=vmax)
fm_ax10.imshow(c10,vmin=vmin,vmax=vmax)
fm_ax11.imshow(c11,vmin=vmin,vmax=vmax)
fm_ax12.imshow(c12,vmin=vmin,vmax=vmax)
fm_ax13.imshow(c13,vmin=vmin,vmax=vmax)
fm_ax14.imshow(c14,vmin=vmin,vmax=vmax)
fm_ax15.imshow(c15,vmin=vmin,vmax=vmax)
fm_ax16.imshow(c16,vmin=vmin,vmax=vmax)
fm_ax17.imshow(c17,vmin=vmin,vmax=vmax)
fm_ax18.imshow(c18,vmin=vmin,vmax=vmax)
fm_ax19.imshow(c19,vmin=vmin,vmax=vmax)
fm_ax20.imshow(c20,vmin=vmin,vmax=vmax)
fm_ax21.imshow(c21,vmin=vmin,vmax=vmax)
fm_ax22.imshow(c22,vmin=vmin,vmax=vmax)
fm_ax23.imshow(c23,vmin=vmin,vmax=vmax)
fm_ax24.imshow(c24,vmin=vmin,vmax=vmax)
fm_ax25.imshow(c25,vmin=vmin,vmax=vmax)
fm_ax26.imshow(c26,vmin=vmin,vmax=vmax)
fm_ax27.imshow(c27,vmin=vmin,vmax=vmax)
fm_ax28.imshow(c28,vmin=vmin,vmax=vmax)
fm_ax29.imshow(c29,vmin=vmin,vmax=vmax)
else:
fm_ax1.imshow(img1) #,vmin=vmin,vmax=vmax
fm_ax2.imshow(img2) #,vmin=vmin,vmax=vmax
fm_ax10.imshow(c10)
fm_ax11.imshow(c11)
fm_ax12.imshow(c12)
fm_ax13.imshow(c13)
fm_ax14.imshow(c14)
fm_ax15.imshow(c15)
fm_ax16.imshow(c16)
fm_ax17.imshow(c17)
fm_ax18.imshow(c18)
fm_ax19.imshow(c19)
fm_ax20.imshow(c20)
fm_ax21.imshow(c21)
fm_ax22.imshow(c22)
fm_ax23.imshow(c23)
fm_ax24.imshow(c24)
fm_ax25.imshow(c25)
fm_ax26.imshow(c26)
fm_ax27.imshow(c27)
fm_ax28.imshow(c28)
fm_ax29.imshow(c29)
plt.show()
return
#%% Kullback-Leibler and Jensen-Shanon divergences
def kldiv(pVec1,pVec2,base,divtype):
eps2 = np.finfo('float').eps**2
pVec1 = pVec1 + eps2
pVec2 = pVec2 + eps2
if divtype=='kl':
KL = np.sum(pVec1 * np.log(pVec1 / pVec2) / np.log(base))
elif divtype=='js':
pM = (pVec1 + pVec2)/2
KL = 0.5 * np.sum(pVec1 * np.log(pVec1 / pM) / np.log(base)) + 0.5 * np.sum(pVec2 * np.log(pVec2 / pM) / np.log(base))
elif divtype=='sym':
KL = ( np.sum(pVec1 * np.log(pVec1 / pVec2) / np.log(base)) + np.sum(pVec2 * np.log(pVec2 / pVec1) / np.log(base)) ) /2
return KL
def jsdist_hist(img1,img2,nbins,base,plot=False,title="",lab1="img1",lab2="img2",iz_section=0):
# nbins >1 : for continuous variables
# otherwise for discrete variables
tmp_min = np.min([np.nanmin(img1.flatten()),np.nanmin(img2.flatten())])
tmp_max = np.max([np.nanmax(img1.flatten()),np.nanmax(img2.flatten())])
if nbins>1:
binedges = np.linspace(tmp_min,tmp_max,num=int(nbins+1))
else:
tmp_unique = np.unique( np.vstack( (img1.flatten(),img2.flatten()) ) )
binedges = np.zeros(len(tmp_unique)+1)
binedges[0:-1] = tmp_unique-1/2
binedges[-1] = tmp_unique[-1]+1/2
p1,_ = np.histogram(img1,bins=binedges)
p1 = p1/np.prod(img1.shape)
p2,_ = np.histogram(img2,bins=binedges)
p2 = p2/np.prod(img2.shape)
if plot:
ix = np.where((p1>0) | (p2>0))
if nbins>1:
X = np.round((binedges[1:]+binedges[:-1])/2,2)
else:
X = tmp_unique
X_axis = np.arange(len(X[ix]))
if len(img1.shape)==3:
map1 = img1[iz_section,:,:]
else:
map1 = img1
if len(img2.shape)==3:
map2 = img2[iz_section,:,:]
else:
map2 = img2
fig = plt.figure()
gs = fig.add_gridspec(1,9)
ax0 = fig.add_subplot(gs[0, 0:2])
ax1 = fig.add_subplot(gs[0, 2:4])
ax2 = fig.add_subplot(gs[0, 4])
ax3 = fig.add_subplot(gs[0, 5:])
ax0.axis('off')
ax1.axis('off')
ax2.axis('off')
axins02 = inset_axes(ax2,
width="10%", # width = 5% of parent_bbox width
height="90%", # height : 50%
loc='center left'
)
ax0.set_title('Map '+lab1+" - iz="+str(iz_section))
ax1.set_title('Map '+lab2+" - iz="+str(iz_section)) # 'entropy W (N) E'
ax2.set_title(title) # 'entropy N (W) S'
vmin = np.min([np.min(img1),np.min(img2)])
vmax = np.max([np.max(img1),np.max(img2)])
pos00 = ax0.imshow(map1,origin='lower',cmap='viridis',vmin=vmin,vmax=vmax)
ax1.imshow(map2,origin='lower',cmap='viridis',vmin=vmin,vmax=vmax) # .imshow(ent[:,0,:],cmap='viridis',vmin=vmin,vmax=vmax)
fig.colorbar(pos00,cax=axins02) #,label=clblab
ax3.bar(X_axis - 0.2, p1[ix], 0.4, label = lab1)
ax3.bar(X_axis + 0.2, p2[ix], 0.4, label = lab2)
ax3.set_xticks(X_axis)
ax3.set_xticklabels(X[ix])
ax3.set_xlabel("Property Values")
ax3.set_ylabel("Proportion")
ax3.set_title("histogram of "+title)
ax3.legend()
fig.subplots_adjust(left=0.0, bottom=0.0, right=2.0, top=.65, wspace=0.1, hspace=0.2)
plt.show()
return kldiv(p1,p2,base,'js')
#%% CONNECTIVITY
def indicator_lag_connectivity(array,xxx,yyy,zzz,nblags,maxh,maxnbsamples,clblab='',verb=False):
lag_count = np.zeros(nblags)+np.nan # lag center
lag_proba = np.zeros(nblags)+np.nan # connectivity probability
lag_center = (np.arange(nblags)+1)*maxh/nblags # count per lag
if np.sum(array)==0:
return lag_center,lag_count,lag_proba
array_size = np.prod(array.shape)
laglim = np.linspace(0,maxh,nblags+1)
clblabed_array, num_features = label(array) # clblab array
clblabed_array = np.reshape(clblabed_array,(array_size,1)).flatten()
ix_c = (np.asarray(np.where(clblabed_array>0))).flatten()
ix_rn = (np.round(np.random.uniform(0,1,int(min(maxnbsamples,np.sum(array),len(ix_c)))) * (np.sum(array)-1))).astype(int)
samples_ix = ix_c[ix_rn]
samples_val = clblabed_array[samples_ix]
samples_xxx = np.reshape(xxx,(array_size,1)).flatten()[samples_ix]
samples_yyy = np.reshape(yyy,(array_size,1)).flatten()[samples_ix]
samples_zzz = np.reshape(zzz,(array_size,1)).flatten()[samples_ix]
# compute distance and square diff between sampled pair of points
dist = np.zeros(np.round(len(samples_ix)*(len(samples_ix)-1)/2).astype(int))+np.nan
conn = np.zeros(np.round(len(samples_ix)*(len(samples_ix)-1)/2).astype(int))+np.nan
k=0
if verb:
print('computing distance and connexion for each sampled pair of point')
for i in range(len(samples_ix)):
for j in np.arange(i):
dist[k] = ( (samples_xxx[i]-samples_xxx[j])**2 + (samples_yyy[i]-samples_yyy[j])**2 + (samples_zzz[i]-samples_zzz[j])**2 )**0.5
conn[k] = 1 - ( samples_val[i] != samples_val[j] )**2
k += 1
# for each lag
if verb:
print('computing connexion probability per lag')
for l in range(nblags):
# identify sampled pairs belonging to the lag
lag_lb = laglim[l]
lag_ub = laglim[l+1]
ix = np.where((dist>=lag_lb) & (dist<lag_ub))
# count, experimental semi vario value and center of lag cloud
lag_count[l]=len(ix[0])
if len(ix[0])>0:
lag_center[l]=np.mean(dist[ix])
lag_proba[l]=np.mean(conn[ix])
return lag_center,lag_count,lag_proba
def weighted_lpnorm(array1,array2,p,weights=np.array([]),verb=False):
if weights.shape!=array1.shape:
weights=np.ones(array1.shape)
if verb:
print('weights: '+np.array2string(weights, precision=2, separator=','))
ix2keep=np.where((np.isnan(array1) | np.isnan(array2))==False)
w=weights[ix2keep]/np.sum(weights[ix2keep])
L=(np.sum(w*(np.abs(array1[ix2keep]-array2[ix2keep]))**p))**(1/p)
return L
def plot_ind_cty(img1,img2,lag_xc1,lag_cp1,lag_xc2,lag_cp2,classcode,clblab="",slice_ix=0,slice_iy=0,slice_iz=0):
ndim = len(img1.shape)
vmin = np.min([np.min(img1),np.min(img2)])
vmax = np.max([np.max(img1),np.max(img2)])
if ndim==3:
fig = plt.figure()
gs = fig.add_gridspec(2,7)
ax00 = fig.add_subplot(gs[0:, 3])
ax01 = fig.add_subplot(gs[0, 0])
ax02 = fig.add_subplot(gs[0, 1])
ax03 = fig.add_subplot(gs[0, 2])
ax11 = fig.add_subplot(gs[1, 0])
ax12 = fig.add_subplot(gs[1, 1])
ax13 = fig.add_subplot(gs[1, 2])
ax4 = fig.add_subplot(gs[0:, 4:])
axins = inset_axes(ax00,
width="10%", # width = 5% of parent_bbox width
height="90%", # height : 50%
loc='center left'
)
ax00.axis('off')
ax01.axis('off')
ax02.axis('off')
ax03.axis('off')
ax01.set_title('img1 Map')
ax02.set_title('img1 W (N) E')
ax03.set_title('img1 N (W) S')
ax11.axis('off')
ax12.axis('off')
ax13.axis('off')
ax11.set_title('img2 Map')
ax12.set_title('img2 W (N) E')
ax13.set_title('img2 N (W) S')
ax4.set_title("img code "+str(classcode)+" connectivity")
pos01=ax01.imshow(img1[slice_iz,:,:],cmap='rainbow',vmin=vmin,vmax=vmax)
ax02.imshow(img1[:,slice_iy,:],cmap='rainbow',vmin=vmin,vmax=vmax)
ax03.imshow(img1[:,:,slice_ix],cmap='rainbow',vmin=vmin,vmax=vmax)
fig.colorbar(pos01,cax=axins,label=clblab)
ax11.imshow(img2[slice_iz,:,:],cmap='rainbow',vmin=vmin,vmax=vmax)
ax12.imshow(img2[:,slice_iy,:],cmap='rainbow',vmin=vmin,vmax=vmax)
ax13.imshow(img2[:,:,slice_ix],cmap='rainbow',vmin=vmin,vmax=vmax)
ax4.plot(lag_xc1, lag_cp1, 'ro-')
ax4.plot(lag_xc2, lag_cp2, 'b+--')
ax4.legend(('img1', 'img2'),loc='best')
ax4.set_xlabel("lag distance [px]",fontsize=14)
ax4.set_ylabel("Connectivity probability") #,fontsize=14
if ndim==2:
fig = plt.figure()
gs = fig.add_gridspec(1,5)
ax00 = fig.add_subplot(gs[0, 2])
ax01 = fig.add_subplot(gs[0, 0])
ax11 = fig.add_subplot(gs[0,1])
ax4 = fig.add_subplot(gs[0, 3:])
axins = inset_axes(ax00,
width="10%", # width = 5% of parent_bbox width
height="90%", # height : 50%
loc='center left'
)
ax00.axis('off')
ax01.axis('off')
ax01.set_title('img1')
ax11.axis('off')
ax11.set_title('img2')
ax4.set_title("img code "+str(classcode)+" connectivity")
pos01=ax01.imshow(img1,cmap='rainbow',vmin=vmin,vmax=vmax)
fig.colorbar(pos01,cax=axins,label=clblab)
ax11.imshow(img2,cmap='rainbow',vmin=vmin,vmax=vmax)
ax4.plot(lag_xc1, lag_cp1, 'ro-')
ax4.plot(lag_xc2, lag_cp2, 'b+--')
ax4.legend(('img1', 'img2'),loc='best')
ax4.set_xlabel("lag distance [px]",fontsize=14)
ax4.set_ylabel("Connectivity probability") #,fontsize=14
fig.subplots_adjust(left=0.0, bottom=0.0, right=2.0, top=0.55, wspace=0.1, hspace=0.5)
plt.show()
return
def plot_pct_lag_cty(img1,img2,extent,low_cp_pct1,low_cp_pct2,hig_cp_pct1,hig_cp_pct2,clblab='',verb=False,slice_ix=0,slice_iy=0,slice_iz=0):
ndim = len(img1.shape)
if ndim==3:
fig = plt.figure()
gs = fig.add_gridspec(2,7)
ax3 = fig.add_subplot(gs[0:, 3])
ax00 = fig.add_subplot(gs[0, 0])
ax01 = fig.add_subplot(gs[0, 1])
ax02 = fig.add_subplot(gs[0, 2])
ax04 = fig.add_subplot(gs[0, 4])
ax05 = fig.add_subplot(gs[0, 5])
ax10 = fig.add_subplot(gs[1, 0])
ax11 = fig.add_subplot(gs[1, 1])
ax12 = fig.add_subplot(gs[1, 2])
ax14 = fig.add_subplot(gs[1, 4])
ax15 = fig.add_subplot(gs[1, 5])
ax6 = fig.add_subplot(gs[0:, 6])
axins3 = inset_axes(ax3,
width="10%", # width = 5% of parent_bbox width
height="90%", # height : 50%
loc='center left'
)
axins6 = inset_axes(ax6,
width="10%", # width = 5% of parent_bbox width
height="90%", # height : 50%
loc='center left'
)
ax00.axis('off')
ax01.axis('off')
ax02.axis('off')
ax3.axis('off')
# ax04.axis('off')
# ax05.axis('off')
ax6.axis('off')
ax00.set_title('img1 Map')
ax01.set_title('img1 W (N) E')
ax02.set_title('img1 N (W) S')
ax04.set_title('img1 l-conn.')
ax05.set_title('img1 h-conn.')
ax10.axis('off')
ax11.axis('off')
ax12.axis('off')
# ax14.axis('off')
# ax15.axis('off')
ax10.set_title('img2 Map')
ax11.set_title('img2 W (N) E')
ax12.set_title('img2 N (W) S')
ax14.set_title('img2 l-conn.')
ax15.set_title('img2h-conn.')
pos00=ax00.imshow(img1[slice_iz,:,:],cmap='rainbow')
ax01.imshow(img1[:,slice_ix,:],cmap='rainbow')
ax02.imshow(img1[:,:,slice_ix],cmap='rainbow')
fig.colorbar(pos00,cax=axins3,label=clblab)
ax10.imshow(img2[slice_iz,:,:],cmap='rainbow')
ax11.imshow(img2[:,slice_ix,:],cmap='rainbow')
ax12.imshow(img2[:,:,slice_ix],cmap='rainbow')
pos04=ax04.imshow(low_cp_pct1,origin='lower',extent=extent,cmap='rainbow',vmin=0,vmax=1)
ax05.imshow(hig_cp_pct1,origin='lower',extent=extent,cmap='rainbow',vmin=0,vmax=1)
fig.colorbar(pos04,cax=axins6,label=clblab)
ax04.set_ylabel("percentile") #,fontsize=14
ax04.set_xticks([])
ax04.set_xticklabels([])
ax05.set_xticks([])
ax05.set_xticklabels([])
ax05.set_yticks([])
ax05.set_yticklabels([])
ax14.imshow(low_cp_pct2,origin='lower',extent=extent,cmap='rainbow',vmin=0,vmax=1)
ax15.imshow(hig_cp_pct2,origin='lower',extent=extent,cmap='rainbow',vmin=0,vmax=1)
ax14.set_xlabel("lag distance [px]")
ax14.set_ylabel("percentile") #,fontsize=14
ax15.set_xlabel("lag distance [px]")
ax15.set_yticks([])
ax15.set_yticklabels([])
if ndim==2:
fig = plt.figure()
gs = fig.add_gridspec(2,5)
ax1 = fig.add_subplot(gs[0:, 1])
ax00 = fig.add_subplot(gs[0, 0])
ax02 = fig.add_subplot(gs[0, 2])
ax03 = fig.add_subplot(gs[0, 3])
ax10 = fig.add_subplot(gs[1, 0])
ax12 = fig.add_subplot(gs[1, 2])
ax13 = fig.add_subplot(gs[1, 3])
ax2 = fig.add_subplot(gs[0:, 4])
ax02.set_xticks([])
ax02.set_xticklabels([])
ax03.set_xticks([])
ax03.set_xticklabels([])
ax03.set_yticks([])
ax03.set_yticklabels([])
ax13.set_yticks([])
ax13.set_yticklabels([])
axins1 = inset_axes(ax1,
width="10%", # width = 5% of parent_bbox width
height="90%", # height : 50%
loc='center left'
)
axins2 = inset_axes(ax2,
width="10%", # width = 5% of parent_bbox width
height="90%", # height : 50%
loc='center left'
)
ax1.axis('off')
ax2.axis('off')
ax00.axis('off')
# ax02.axis('off')
# ax03.axis('off')
ax10.axis('off')
# ax12.axis('off')
# ax13.axis('off')
ax00.set_title('img1 Map')
ax02.set_title('img1 l-conn.')
ax03.set_title('img1 h-conn.')
ax10.set_title('img2 Map')
ax12.set_title('img2 l-conn.')
ax13.set_title('img2h-conn.')
pos00=ax00.imshow(img1,cmap='rainbow')
fig.colorbar(pos00,cax=axins1,label=clblab)
ax10.imshow(img2,cmap='rainbow')
pos02=ax02.imshow(low_cp_pct1,origin='lower',extent=extent,cmap='rainbow',vmin=0,vmax=1)
ax03.imshow(hig_cp_pct1,origin='lower',extent=extent,cmap='rainbow',vmin=0,vmax=1)
fig.colorbar(pos02,cax=axins2,label=clblab)
# ax02.set_xlabel("lag distance [px]")
ax02.set_ylabel("percentile") #,fontsize=14
# ax03.set_xlabel("lag distance [px]")
ax03.set_ylabel("percentile") #,fontsize=14
ax12.imshow(low_cp_pct2,origin='lower',extent=extent,cmap='rainbow',vmin=0,vmax=1)
ax13.imshow(hig_cp_pct2,origin='lower',extent=extent,cmap='rainbow',vmin=0,vmax=1)
ax12.set_xlabel("lag distance [px]")
ax12.set_ylabel("percentile") #,fontsize=14
ax13.set_xlabel("lag distance [px]")
ax13.set_ylabel("percentile") #,fontsize=14
fig.subplots_adjust(left=0.0, bottom=0.0, right=2.0, top=0.55, wspace=0.01, hspace=0.5)
plt.show()
return
def dist_lpnorm_categorical_lag_connectivity(img1,img2,xxx,yyy,zzz,nblags,maxh,maxnbsamples,pnorm,clblab='',plot=False,verb=False,slice_ix=0,slice_iy=0,slice_iz=0):
d=0
# identify all indicators
indicators = np.unique(np.hstack((img1.flatten(),img2.flatten())))
nbind = len(indicators)
d_ind = np.zeros(nbind)
# for all indicators
for i in range(nbind):
classcode = indicators[i]
if verb:
print('indicator '+str(i))
img1bin = ((img1==classcode)*1).astype(int)
img2bin = ((img2==classcode)*1).astype(int)
img1cnt=np.sum(img1bin)
img2cnt=np.sum(img2bin)
if img1cnt+img2cnt==0:
d_ind[i] = 0
elif img1cnt*img2cnt==0:
d_ind[i] = 1/nbind
else:
if verb:
print('img1 compute indicator_lag_connectivity')
[lag_xc1,lag_ct1,lag_cp1] = indicator_lag_connectivity(img1bin,xxx,yyy,zzz,nblags,maxh,maxnbsamples,verb=verb)
if verb:
print('img2 compute indicator_lag_connectivity')
[lag_xc2,lag_ct2,lag_cp2] = indicator_lag_connectivity(img2bin,xxx,yyy,zzz,nblags,maxh,maxnbsamples,verb=verb)
d_ind[i] = weighted_lpnorm(lag_cp1,lag_cp2,pnorm,verb=verb)
d += 1/nbind * d_ind[i]**pnorm
if verb:
print('distance contribution: '+str(d_ind[i]))
if plot:
plot_ind_cty(img1,img2,lag_xc1,lag_cp1,lag_xc2,lag_cp2,classcode,clblab=clblab,slice_ix=slice_ix,slice_iy=slice_iy,slice_iz=slice_iz)
d = d**(1/pnorm)
return d #, d_ind, id_ind
def dist_lpnorm_percentile_lag_connectivity(img1,img2,xxx,yyy,zzz,npctiles,nblags,maxh,maxnbsamples,pnorm,clblab='',plot=False,verb=False,slice_ix=0,slice_iy=0,slice_iz=0):
d=0
d_pct=np.zeros(npctiles)
pctiles = (np.arange(npctiles)+1)*100/npctiles
lag_center = (np.arange(nblags)+1)*maxh/nblags
th_pct1 = np.nanpercentile(img1,pctiles)
th_pct2 = np.nanpercentile(img2,pctiles)
low_xc_pct1 = np.ones((npctiles,nblags))*np.nan
low_ct_pct1 = np.ones((npctiles,nblags))*np.nan
low_cp_pct1 = np.ones((npctiles,nblags))*np.nan
hig_xc_pct1 = np.ones((npctiles,nblags))*np.nan
hig_ct_pct1 = np.ones((npctiles,nblags))*np.nan
hig_cp_pct1 = np.ones((npctiles,nblags))*np.nan
low_xc_pct2 = np.ones((npctiles,nblags))*np.nan
low_ct_pct2 = np.ones((npctiles,nblags))*np.nan
low_cp_pct2 = np.ones((npctiles,nblags))*np.nan
hig_xc_pct2 = np.ones((npctiles,nblags))*np.nan
hig_ct_pct2 = np.ones((npctiles,nblags))*np.nan
hig_cp_pct2 = np.ones((npctiles,nblags))*np.nan
for i in range(npctiles):
# lower parts
img1_low = ((img1<=th_pct1[i])*1.0).astype(int)
img2_low = ((img2<=th_pct2[i])*1.0).astype(int)
img1cntl=np.sum(img1_low)
img2cntl=np.sum(img2_low)
if verb:
print(str(pctiles[i])+"th percentile connectivity - lower img1")
if img1cntl==0:
low_xc1 = lag_center
low_ct1 = np.ones(nblags)*np.nan
low_cp1 = np.ones(nblags)*np.nan
else:
[low_xc1,low_ct1,low_cp1] = indicator_lag_connectivity(img1_low,xxx,yyy,zzz,nblags,maxh,maxnbsamples,verb=verb)
if verb:
print(str(pctiles[i])+"th percentile connectivity - lower img2")
if img2cntl==0:
low_xc2 = lag_center
low_ct2 = np.ones(nblags)*np.nan
low_cp2 = np.ones(nblags)*np.nan
else:
[low_xc2,low_ct2,low_cp2] = indicator_lag_connectivity(img2_low,xxx,yyy,zzz,nblags,maxh,maxnbsamples,verb=verb)
low_xc_pct1[i,:]=low_xc1
low_ct_pct1[i,:]=low_ct1
low_cp_pct1[i,:]=low_cp1
low_xc_pct2[i,:]=low_xc2
low_ct_pct2[i,:]=low_ct2
low_cp_pct2[i,:]=low_cp2
# upper parts
img1_hig = ((img1>th_pct1[i])*1.0).astype(int)
img2_hig = ((img2>th_pct2[i])*1.0).astype(int)
img1cnth=np.sum(img1_hig)
img2cnth=np.sum(img2_hig)
if verb:
print(str(pctiles[i])+"th percentile connectivity - upper img1")
if img1cnth==0:
hig_xc1 = lag_center
hig_ct1 = np.ones(nblags)*np.nan
hig_cp1 = np.ones(nblags)*np.nan
else:
[hig_xc1,hig_ct1,hig_cp1] = indicator_lag_connectivity(img1_hig,xxx,yyy,zzz,nblags,maxh,maxnbsamples,verb=verb)
if verb:
print(str(pctiles[i])+"th percentile connectivity - upper img2")
if img2cnth==0:
hig_xc2 = lag_center
hig_ct2 = np.ones(nblags)*np.nan
hig_cp2 = np.ones(nblags)*np.nan
else:
[hig_xc2,hig_ct2,hig_cp2] = indicator_lag_connectivity(img2_hig,xxx,yyy,zzz,nblags,maxh,maxnbsamples,verb=verb)
hig_xc_pct1[i,:]=hig_xc1
hig_ct_pct1[i,:]=hig_ct1
hig_cp_pct1[i,:]=hig_cp1
hig_xc_pct2[i,:]=hig_xc2
hig_ct_pct2[i,:]=hig_ct2
hig_cp_pct2[i,:]=hig_cp2
# compute distance
if img1cntl+img2cntl==0:
d_low = 0
elif img1cntl*img2cntl==0:
d_low = 1
else:
d_low = weighted_lpnorm(low_cp1,low_cp2,pnorm,verb=verb)
if img1cnth+img2cnth==0:
d_hig = 0
elif img1cnth*img2cnth==0:
d_hig = 1
else:
d_hig = weighted_lpnorm(hig_cp1,hig_cp2,pnorm,verb=verb)
d_pct[i] = (d_low**pnorm + d_hig**pnorm )*0.5/npctiles
d += d_pct[i]
if verb:
print('distance contribution: '+str(d_pct[i]))
d = d**(1/pnorm)
if verb:
print('total distance: '+str(d))
# plot option
if plot:
extent = 0,maxh,0,100
plot_pct_lag_cty(img1,img2,extent,low_cp_pct1,low_cp_pct2,hig_cp_pct1,hig_cp_pct2,clblab=clblab,verb=verb,slice_ix=slice_ix,slice_iy=slice_iy,slice_iz=slice_iz)
return d #, d_ind, id_ind
def continuous_pct_connectivity(array,npctiles,verb=False):
if verb:
print('Computing global percentile connectivity')
pctiles = np.linspace(100/npctiles,100,npctiles)
low_connect = np.zeros(npctiles)+np.nan
hig_connect = np.zeros(npctiles)+np.nan
th_pct = np.nanpercentile(array,pctiles)
for i in range(npctiles):
if verb:
print(str(pctiles[i])+'th percentile - global connectivity')
array_low = array<=th_pct[i]
lab_low, num_features_low = label(array_low)
cnt_low = np.zeros(num_features_low)
for j in range(num_features_low):
cnt_low[j]=np.sum((lab_low==j+1)*1.0)
array_hig = array>th_pct[i]
lab_hig, num_features_hig = label(array_hig)
cnt_hig = np.zeros(num_features_hig)
for j in range(num_features_hig):
cnt_hig[j]=np.sum((lab_hig==j+1)*1.0)
nb_low = np.sum(array_low)
nb_hig = np.sum(array_hig)
low_connect[i] = np.sum((cnt_low/nb_low)**2)
hig_connect[i] = np.sum((cnt_hig/nb_hig)**2)
return low_connect,hig_connect,pctiles
def plot_pct_cty(img1,img2,pctiles,low_connect1,low_connect2,hig_connect1,hig_connect2,clblab='',slice_ix=0,slice_iy=0,slice_iz=0):
ndim = len(img1.shape)
if ndim==3:
fig = plt.figure()
gs = fig.add_gridspec(2,11)
ax00 = fig.add_subplot(gs[0, 0:2])
ax01 = fig.add_subplot(gs[0, 2:4])