-
Notifications
You must be signed in to change notification settings - Fork 10
/
popsom.py
1493 lines (1157 loc) · 43.5 KB
/
popsom.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import seaborn as sns
from random import randint
from sklearn.metrics.pairwise import euclidean_distances
import statsmodels.stats.api as sms # t-test
import statistics as stat # F-test
from scipy import stats # KS Test
from scipy.stats import f # F-test
from itertools import combinations
class map:
def __init__(self, xdim=10, ydim=5, alpha=.3, train=1000, norm=False):
""" __init__ -- Initialize the Model
parameters:
- xdim,ydim - the dimensions of the map
- alpha - the learning rate, should be a positive non-zero real number
- train - number of training iterations
- algorithm - selection switch (som and som_f)
- norm - normalize the input data space
"""
self.xdim = xdim
self.ydim = ydim
self.alpha = alpha
self.train = train
self.norm = norm
def fit(self, data, labels):
""" fit -- Train the Model with Python or Fortran
parameters:
- data - a dataframe where each row contains an unlabeled training instance
- labels - a vector or dataframe with one label for each observation in data
"""
if self.norm:
data = data.div(data.sum(axis=1), axis=0)
self.data = data
self.labels = labels
# check if the dims are reasonable
if (self.xdim < 3 or self.ydim < 3):
sys.exit("build: map is too small.")
self.vsom_p()
visual = []
for i in range(self.data.shape[0]):
b = self.best_match(self.data.iloc[[i]])
visual.extend([b])
self.visual = visual
def marginal(self, marginal):
""" marginal -- plot that shows the marginal probability distribution of the neurons and data
parameters:
- marginal is the name of a training data frame dimension or index
"""
# check if the second argument is of type character
if type(marginal) == str and marginal in list(self.data):
f_ind = list(self.data).index(marginal)
f_name = marginal
train = np.matrix(self.data)[:, f_ind]
neurons = self.neurons[:, f_ind]
plt.ylabel('Density')
plt.xlabel(f_name)
sns.kdeplot(np.ravel(train),
label="training data",
shade=True,
color="b")
sns.kdeplot(neurons, label="neurons", shade=True, color="r")
plt.legend(fontsize=15)
plt.show()
elif (type(marginal) == int and marginal < len(list(self.data)) and marginal >= 0):
f_ind = marginal
f_name = list(self.data)[marginal]
train = np.matrix(self.data)[:, f_ind]
neurons = self.neurons[:, f_ind]
plt.ylabel('Density')
plt.xlabel(f_name)
sns.kdeplot(np.ravel(train),
label="training data",
shade=True,
color="b")
sns.kdeplot(neurons, label="neurons", shade=True, color="r")
plt.legend(fontsize=15)
plt.show()
else:
sys.exit("marginal: second argument is not the name of a training \
data frame dimension or index")
def vsom_p(self):
""" vsom_p -- vectorized, unoptimized version of the stochastic SOM
training algorithm written entirely in python
"""
# some constants
dr = self.data.shape[0]
dc = self.data.shape[1]
nr = self.xdim*self.ydim
nc = dc # dim of data and neurons is the same
# build and initialize the matrix holding the neurons
cells = nr * nc # No. of neurons times number of data dimensions
# vector with small init values for all neurons
v = np.random.uniform(-1, 1, cells)
# NOTE: each row represents a neuron, each column represents a dimension.
neurons = np.transpose(np.reshape(v, (nc, nr))) # rearrange the vector as matrix
# neurons = np.reshape(v, (nr, nc)) # Another option to reshape
# compute the initial neighborhood size and step
nsize = max(self.xdim, self.ydim) + 1
nsize_step = np.ceil(self.train/nsize)
step_counter = 0 # counts the number of epochs per nsize_step
# convert a 1D rowindex into a 2D map coordinate
def coord2D(rowix):
x = np.array(rowix) % self.xdim
y = np.array(rowix) // self.xdim
return np.concatenate((x, y))
# constants for the Gamma function
m = [i for i in range(nr)] # a vector with all neuron 1D addresses
# x-y coordinate of ith neuron: m2Ds[i,] = c(xi, yi)
m2Ds = np.matrix.transpose(coord2D(m).reshape(2, nr))
# neighborhood function
def Gamma(c):
# lookup the 2D map coordinate for c
c2D = m2Ds[c, ]
# a matrix with each row equal to c2D
c2Ds = np.outer(np.linspace(1, 1, nr), c2D)
# distance vector of each neuron from c in terms of map coords!
d = np.sqrt(np.dot((c2Ds - m2Ds)**2, [1, 1]))
# if m on the grid is in neigh then alpha else 0.0
hood = np.where(d < nsize*1.5, self.alpha, 0.0)
return hood
# training #
# the epochs loop
self.animation = []
for epoch in range(self.train):
# hood size decreases in disrete nsize.steps
step_counter = step_counter + 1
if step_counter == nsize_step:
step_counter = 0
nsize = nsize - 1
# create a sample training vector
ix = randint(0, dr-1)
# ix = (epoch+1) % dr # For Debugging
xk = self.data.iloc[[ix]]
# competitive step
xk_m = np.outer(np.linspace(1, 1, nr), xk)
diff = neurons - xk_m
squ = diff * diff
s = np.dot(squ, np.linspace(1, 1, nc))
o = np.argsort(s)
c = o[0]
# update step
gamma_m = np.outer(Gamma(c), np.linspace(1, 1, nc))
neurons = neurons - diff * gamma_m
self.animation.append(neurons.tolist())
self.neurons = neurons
def convergence(self, conf_int=.95, k=50, verb=False, ks=False):
""" convergence -- the convergence index of a map
Parameters:
- conf_int - the confidence interval of the quality assessment (default 95%)
- k - the number of samples used for the estimated topographic accuracy computation
- verb - if true reports the two convergence components separately, otherwise it will
report the linear combination of the two
- ks - a switch, true for ks-test, false for standard var and means test
Return
- return value is the convergence index
"""
if ks:
embed = self.embed_ks(conf_int, verb=False)
else:
embed = self.embed_vm(conf_int, verb=False)
topo_ = self.topo(k, conf_int, verb=False, interval=False)
if verb:
return {"embed": embed, "topo": topo_}
else:
return (0.5*embed + 0.5*topo_)
def starburst(self, explicit=False, smoothing=2, merge_clusters=True, merge_range=.25):
""" starburst -- compute and display the starburst representation of clusters
parameters:
- explicit - controls the shape of the connected components
- smoothing - controls the smoothing level of the umat (NULL,0,>0)
- merge_clusters - a switch that controls if the starburst clusters are merged together
- merge_range - a range that is used as a percentage of a certain distance in the code
to determine whether components are closer to their centroids or
centroids closer to each other.
"""
umat = self.compute_umat(smoothing=smoothing)
self.plot_heat(umat,
explicit=explicit,
comp=True,
merge=merge_clusters,
merge_range=merge_range)
def compute_umat(self, smoothing=None):
""" compute_umat -- compute the unified distance matrix
parameters:
- smoothing - is either NULL, 0, or a positive floating point value controlling the
smoothing of the umat representation
return:
- a matrix with the same x-y dims as the original map containing the umat values
"""
d = euclidean_distances(self.neurons, self.neurons)
umat = self.compute_heat(d, smoothing)
return umat
def compute_heat(self, d, smoothing=None):
""" compute_heat -- compute a heat value map representation of the given distance matrix
parameters:
- d - a distance matrix computed via the 'dist' function
- smoothing - is either NULL, 0, or a positive floating point value controlling the
smoothing of the umat representation
return:
- a matrix with the same x-y dims as the original map containing the heat
"""
x = self.xdim
y = self.ydim
heat = np.matrix([[0.0] * y for _ in range(x)])
if x == 1 or y == 1:
sys.exit("compute_heat: heat map can not be computed for a map \
with a dimension of 1")
# this function translates our 2-dim map coordinates
# into the 1-dim coordinates of the neurons
def xl(ix, iy):
return ix + iy * x
# check if the map is larger than 2 x 2 (otherwise it is only corners)
if x > 2 and y > 2:
# iterate over the inner nodes and compute their umat values
for ix in range(1, x-1):
for iy in range(1, y-1):
sum = (d[xl(ix, iy), xl(ix-1, iy-1)] +
d[xl(ix, iy), xl(ix, iy-1)] +
d[xl(ix, iy), xl(ix+1, iy-1)] +
d[xl(ix, iy), xl(ix+1, iy)] +
d[xl(ix, iy), xl(ix+1, iy+1)] +
d[xl(ix, iy), xl(ix, iy+1)] +
d[xl(ix, iy), xl(ix-1, iy+1)] +
d[xl(ix, iy), xl(ix-1, iy)])
heat[ix, iy] = sum/8
# iterate over bottom x axis
for ix in range(1, x-1):
iy = 0
sum = (d[xl(ix, iy), xl(ix+1, iy)] +
d[xl(ix, iy), xl(ix+1, iy+1)] +
d[xl(ix, iy), xl(ix, iy+1)] +
d[xl(ix, iy), xl(ix-1, iy+1)] +
d[xl(ix, iy), xl(ix-1, iy)])
heat[ix, iy] = sum/5
# iterate over top x axis
for ix in range(1, x-1):
iy = y-1
sum = (d[xl(ix, iy), xl(ix-1, iy-1)] +
d[xl(ix, iy), xl(ix, iy-1)] +
d[xl(ix, iy), xl(ix+1, iy-1)] +
d[xl(ix, iy), xl(ix+1, iy)] +
d[xl(ix, iy), xl(ix-1, iy)])
heat[ix, iy] = sum/5
# iterate over the left y-axis
for iy in range(1, y-1):
ix = 0
sum = (d[xl(ix, iy), xl(ix, iy-1)] +
d[xl(ix, iy), xl(ix+1, iy-1)] +
d[xl(ix, iy), xl(ix+1, iy)] +
d[xl(ix, iy), xl(ix+1, iy+1)] +
d[xl(ix, iy), xl(ix, iy+1)])
heat[ix, iy] = sum/5
# iterate over the right y-axis
for iy in range(1, y-1):
ix = x-1
sum = (d[xl(ix, iy), xl(ix-1, iy-1)] +
d[xl(ix, iy), xl(ix, iy-1)] +
d[xl(ix, iy), xl(ix, iy+1)] +
d[xl(ix, iy), xl(ix-1, iy+1)] +
d[xl(ix, iy), xl(ix-1, iy)])
heat[ix, iy] = sum/5
# compute umat values for corners
if x >= 2 and y >= 2:
# bottom left corner
ix = 0
iy = 0
sum = (d[xl(ix, iy), xl(ix+1, iy)] +
d[xl(ix, iy), xl(ix+1, iy+1)] +
d[xl(ix, iy), xl(ix, iy+1)])
heat[ix, iy] = sum/3
# bottom right corner
ix = x-1
iy = 0
sum = (d[xl(ix, iy), xl(ix, iy+1)] +
d[xl(ix, iy), xl(ix-1, iy+1)] +
d[xl(ix, iy), xl(ix-1, iy)])
heat[ix, iy] = sum/3
# top left corner
ix = 0
iy = y-1
sum = (d[xl(ix, iy), xl(ix, iy-1)] +
d[xl(ix, iy), xl(ix+1, iy-1)] +
d[xl(ix, iy), xl(ix+1, iy)])
heat[ix, iy] = sum/3
# top right corner
ix = x-1
iy = y-1
sum = (d[xl(ix, iy), xl(ix-1, iy-1)] +
d[xl(ix, iy), xl(ix, iy-1)] +
d[xl(ix, iy), xl(ix-1, iy)])
heat[ix, iy] = sum/3
# smooth the heat map
pts = []
for i in range(y):
for j in range(x):
pts.extend([[j, i]])
if smoothing is not None:
if smoothing == 0:
heat = self.smooth_2d(heat,
nrow=x,
ncol=y,
surface=False)
elif smoothing > 0:
heat = self.smooth_2d(heat,
nrow=x,
ncol=y,
surface=False,
theta=smoothing)
else:
sys.exit("compute_heat: bad value for smoothing parameter")
return heat
def plot_heat(self, heat, explicit=False, comp=True, merge=False, merge_range=0.25):
""" plot_heat -- plot a heat map based on a 'map', this plot also contains the connected
components of the map based on the landscape of the heat map
parameters:
- heat - is a 2D heat map of the map returned by 'map'
- explicit - controls the shape of the connected components
- comp - controls whether we plot the connected components on the heat map
- merge - controls whether we merge the starbursts together.
- merge_range - a range that is used as a percentage of a certain distance in the code
to determine whether components are closer to their centroids or
centroids closer to each other.
"""
umat = heat
x = self.xdim
y = self.ydim
nobs = self.data.shape[0]
count = np.matrix([[0]*y]*x)
# need to make sure the map doesn't have a dimension of 1
if (x <= 1 or y <= 1):
sys.exit("plot_heat: map dimensions too small")
tmp = pd.cut(heat, bins=100, labels=False)
tmp_1 = np.array(np.matrix.transpose(tmp))
fig, ax = plt.subplots()
ax.pcolor(tmp_1, cmap=plt.cm.YlOrRd)
ax.set_xticks(np.arange(x)+0.5, minor=False)
ax.set_yticks(np.arange(y)+0.5, minor=False)
plt.xlabel("x")
plt.ylabel("y")
ax.set_xticklabels(np.arange(x), minor=False)
ax.set_yticklabels(np.arange(y), minor=False)
ax.xaxis.set_tick_params(labeltop='on')
ax.yaxis.set_tick_params(labelright='on')
# put the connected component lines on the map
if comp:
if not merge:
# find the centroid for each neuron on the map
centroids = self.compute_centroids(heat, explicit)
else:
# find the unique centroids for the neurons on the map
centroids = self.compute_combined_clusters(umat, explicit, merge_range)
# connect each neuron to its centroid
for ix in range(x):
for iy in range(y):
cx = centroids['centroid_x'][ix, iy]
cy = centroids['centroid_y'][ix, iy]
plt.plot([ix+0.5, cx+0.5],
[iy+0.5, cy+0.5],
color='grey',
linestyle='-',
linewidth=1.0)
# put the labels on the map if available
if not (self.labels is None) and (len(self.labels) != 0):
# count the labels in each map cell
for i in range(nobs):
nix = self.visual[i]
c = self.coordinate(nix)
ix = c[0]
iy = c[1]
count[ix-1, iy-1] = count[ix-1, iy-1]+1
for i in range(nobs):
c = self.coordinate(self.visual[i])
ix = c[0]
iy = c[1]
# we only print one label per cell
if count[ix-1, iy-1] > 0:
count[ix-1, iy-1] = 0
ix = ix - .5
iy = iy - .5
l = self.labels[i]
plt.text(ix+1, iy+1, l)
plt.show()
def compute_centroids(self, heat, explicit=False):
""" compute_centroids -- compute the centroid for each point on the map
parameters:
- heat - is a matrix representing the heat map representation
- explicit - controls the shape of the connected component
return value:
- a list containing the matrices with the same x-y dims as the original map containing the centroid x-y coordinates
"""
xdim = self.xdim
ydim = self.ydim
centroid_x = np.matrix([[-1] * ydim for _ in range(xdim)])
centroid_y = np.matrix([[-1] * ydim for _ in range(xdim)])
heat = np.matrix(heat)
def compute_centroid(ix, iy):
# recursive function to find the centroid of a point on the map
if (centroid_x[ix, iy] > -1) and (centroid_y[ix, iy] > -1):
return {"bestx": centroid_x[ix, iy], "besty": centroid_y[ix, iy]}
min_val = heat[ix, iy]
min_x = ix
min_y = iy
# (ix, iy) is an inner map element
if ix > 0 and ix < xdim-1 and iy > 0 and iy < ydim-1:
if heat[ix-1, iy-1] < min_val:
min_val = heat[ix-1, iy-1]
min_x = ix-1
min_y = iy-1
if heat[ix, iy-1] < min_val:
min_val = heat[ix, iy-1]
min_x = ix
min_y = iy-1
if heat[ix+1, iy-1] < min_val:
min_val = heat[ix+1, iy-1]
min_x = ix+1
min_y = iy-1
if heat[ix+1, iy] < min_val:
min_val = heat[ix+1, iy]
min_x = ix+1
min_y = iy
if heat[ix+1, iy+1] < min_val:
min_val = heat[ix+1, iy+1]
min_x = ix+1
min_y = iy+1
if heat[ix, iy+1] < min_val:
min_val = heat[ix, iy+1]
min_x = ix
min_y = iy+1
if heat[ix-1, iy+1] < min_val:
min_val = heat[ix-1, iy+1]
min_x = ix-1
min_y = iy+1
if heat[ix-1, iy] < min_val:
min_val = heat[ix-1, iy]
min_x = ix-1
min_y = iy
# (ix, iy) is bottom left corner
elif ix == 0 and iy == 0:
if heat[ix+1, iy] < min_val:
min_val = heat[ix+1, iy]
min_x = ix+1
min_y = iy
if heat[ix+1, iy+1] < min_val:
min_val = heat[ix+1, iy+1]
min_x = ix+1
min_y = iy+1
if heat[ix, iy+1] < min_val:
min_val = heat[ix, iy+1]
min_x = ix
min_y = iy+1
# (ix, iy) is bottom right corner
elif ix == xdim-1 and iy == 0:
if heat[ix, iy+1] < min_val:
min_val = heat[ix, iy+1]
min_x = ix
min_y = iy+1
if heat[ix-1, iy+1] < min_val:
min_val = heat[ix-1, iy+1]
min_x = ix-1
min_y = iy+1
if heat[ix-1, iy] < min_val:
min_val = heat[ix-1, iy]
min_x = ix-1
min_y = iy
# (ix, iy) is top right corner
elif ix == xdim-1 and iy == ydim-1:
if heat[ix-1, iy-1] < min_val:
min_val = heat[ix-1, iy-1]
min_x = ix-1
min_y = iy-1
if heat[ix, iy-1] < min_val:
min_val = heat[ix, iy-1]
min_x = ix
min_y = iy-1
if heat[ix-1, iy] < min_val:
min_val = heat[ix-1, iy]
min_x = ix-1
min_y = iy
# (ix, iy) is top left corner
elif ix == 0 and iy == ydim-1:
if heat[ix, iy-1] < min_val:
min_val = heat[ix, iy-1]
min_x = ix
min_y = iy-1
if heat[ix+1, iy-1] < min_val:
min_val = heat[ix+1, iy-1]
min_x = ix+1
min_y = iy-1
if heat[ix+1, iy] < min_val:
min_val = heat[ix+1, iy]
min_x = ix+1
min_y = iy
# (ix, iy) is a left side element
elif ix == 0 and iy > 0 and iy < ydim-1:
if heat[ix, iy-1] < min_val:
min_val = heat[ix, iy-1]
min_x = ix
min_y = iy-1
if heat[ix+1, iy-1] < min_val:
min_val = heat[ix+1, iy-1]
min_x = ix+1
min_y = iy-1
if heat[ix+1, iy] < min_val:
min_val = heat[ix+1, iy]
min_x = ix+1
min_y = iy
if heat[ix+1, iy+1] < min_val:
min_val = heat[ix+1, iy+1]
min_x = ix+1
min_y = iy+1
if heat[ix, iy+1] < min_val:
min_val = heat[ix, iy+1]
min_x = ix
min_y = iy+1
# (ix, iy) is a bottom side element
elif ix > 0 and ix < xdim-1 and iy == 0:
if heat[ix+1, iy] < min_val:
min_val = heat[ix+1, iy]
min_x = ix+1
min_y = iy
if heat[ix+1, iy+1] < min_val:
min_val = heat[ix+1, iy+1]
min_x = ix+1
min_y = iy+1
if heat[ix, iy+1] < min_val:
min_val = heat[ix, iy+1]
min_x = ix
min_y = iy+1
if heat[ix-1, iy+1] < min_val:
min_val = heat[ix-1, iy+1]
min_x = ix-1
min_y = iy+1
if heat[ix-1, iy] < min_val:
min_val = heat[ix-1, iy]
min_x = ix-1
min_y = iy
# (ix, iy) is a right side element
elif ix == xdim-1 and iy > 0 and iy < ydim-1:
if heat[ix-1, iy-1] < min_val:
min_val = heat[ix-1, iy-1]
min_x = ix-1
min_y = iy-1
if heat[ix, iy-1] < min_val:
min_val = heat[ix, iy-1]
min_x = ix
min_y = iy-1
if heat[ix, iy+1] < min_val:
min_val = heat[ix, iy+1]
min_x = ix
min_y = iy+1
if heat[ix-1, iy+1] < min_val:
min_val = heat[ix-1, iy+1]
min_x = ix-1
min_y = iy+1
if heat[ix-1, iy] < min_val:
min_val = heat[ix-1, iy]
min_x = ix-1
min_y = iy
# (ix, iy) is a top side element
elif ix > 0 and ix < xdim-1 and iy == ydim-1:
if heat[ix-1, iy-1] < min_val:
min_val = heat[ix-1, iy-1]
min_x = ix-1
min_y = iy-1
if heat[ix, iy-1] < min_val:
min_val = heat[ix, iy-1]
min_x = ix
min_y = iy-1
if heat[ix+1, iy-1] < min_val:
min_val = heat[ix+1, iy-1]
min_x = ix+1
min_y = iy-1
if heat[ix+1, iy] < min_val:
min_val = heat[ix+1, iy]
min_x = ix+1
min_y = iy
if heat[ix-1, iy] < min_val:
min_val = heat[ix-1, iy]
min_x = ix-1
min_y = iy
# if successful
# move to the square with the smaller value, i_e_, call
# compute_centroid on this new square
# note the RETURNED x-y coords in the centroid_x and
# centroid_y matrix at the current location
# return the RETURNED x-y coordinates
if min_x != ix or min_y != iy:
r_val = compute_centroid(min_x, min_y)
# if explicit is set show the exact connected component
# otherwise construct a connected componenent where all
# nodes are connected to a centrol node
if explicit:
centroid_x[ix, iy] = min_x
centroid_y[ix, iy] = min_y
return {"bestx": min_x, "besty": min_y}
else:
centroid_x[ix, iy] = r_val['bestx']
centroid_y[ix, iy] = r_val['besty']
return r_val
else:
centroid_x[ix, iy] = ix
centroid_y[ix, iy] = iy
return {"bestx": ix, "besty": iy}
for i in range(xdim):
for j in range(ydim):
compute_centroid(i, j)
return {"centroid_x": centroid_x, "centroid_y": centroid_y}
def compute_combined_clusters(self, heat, explicit, rang):
# compute the connected components
centroids = self.compute_centroids(heat, explicit)
# Get unique centroids
unique_centroids = self.get_unique_centroids(centroids)
# Get distance from centroid to cluster elements for all centroids
within_cluster_dist = self.distance_from_centroids(centroids,
unique_centroids,
heat)
# Get average pairwise distance between clusters
between_cluster_dist = self.distance_between_clusters(centroids,
unique_centroids,
heat)
# Get a boolean matrix of whether two components should be combined
combine_cluster_bools = self.combine_decision(within_cluster_dist,
between_cluster_dist,
rang)
# Create the modified connected components grid
ne_centroid = self.new_centroid(combine_cluster_bools,
centroids,
unique_centroids)
return ne_centroid
def get_unique_centroids(self, centroids):
""" get_unique_centroids -- a function that computes a list of unique centroids from
a matrix of centroid locations.
parameters:
- centroids - a matrix of the centroid locations in the map
"""
# get the dimensions of the map
xdim = self.xdim
ydim = self.ydim
xlist = []
ylist = []
x_centroid = centroids['centroid_x']
y_centroid = centroids['centroid_y']
for ix in range(xdim):
for iy in range(ydim):
cx = x_centroid[ix, iy]
cy = y_centroid[ix, iy]
# Check if the x or y of the current centroid is not in the list
# and if not
# append both the x and y coordinates to the respective lists
if not(cx in xlist) or not(cy in ylist):
xlist.append(cx)
ylist.append(cy)
# return a list of unique centroid positions
return {"position_x": xlist, "position_y": ylist}
def distance_from_centroids(self, centroids, unique_centroids, heat):
""" distance_from_centroids -- A function to get the average distance from
centroid by cluster.
parameters:
- centroids - a matrix of the centroid locations in the map
- unique_centroids - a list of unique centroid locations
- heat - a unified distance matrix
"""
centroids_x_positions = unique_centroids['position_x']
centroids_y_positions = unique_centroids['position_y']
within = []
for i in range(len(centroids_x_positions)):
cx = centroids_x_positions[i]
cy = centroids_y_positions[i]
# compute the average distance
distance = self.cluster_spread(cx, cy, np.matrix(heat), centroids)
# append the computed distance to the list of distances
within.append(distance)
return within
def cluster_spread(self, x, y, umat, centroids):
""" cluster_spread -- Function to calculate the average distance in
one cluster given one centroid.
parameters:
- x - x position of a unique centroid
- y - y position of a unique centroid
- umat - a unified distance matrix
- centroids - a matrix of the centroid locations in the map
"""
centroid_x = x
centroid_y = y
sum = 0
elements = 0
xdim = self.xdim
ydim = self.ydim
centroid_weight = umat[centroid_x, centroid_y]
for xi in range(xdim):
for yi in range(ydim):
cx = centroids['centroid_x'][xi, yi]
cy = centroids['centroid_y'][xi, yi]
if(cx == centroid_x and cy == centroid_y):
cweight = umat[xi, yi]
sum = sum + abs(cweight - centroid_weight)
elements = elements + 1
average = sum / elements
return average
def distance_between_clusters(self, centroids, unique_centroids, umat):
""" distance_between_clusters -- A function to compute the average pairwise
distance between clusters.
parameters:
- centroids - a matrix of the centroid locations in the map
- unique_centroids - a list of unique centroid locations
- umat - a unified distance matrix
"""
cluster_elements = self.list_clusters(centroids, unique_centroids, umat)
tmp_1 = np.zeros(shape=(max([len(cluster_elements[i]) for i in range(
len(cluster_elements))]), len(cluster_elements)))
for i in range(len(cluster_elements)):
for j in range(len(cluster_elements[i])):
tmp_1[j, i] = cluster_elements[i][j]
columns = tmp_1.shape[1]
tmp = np.matrix.transpose(np.array(list(combinations([i for i in range(columns)], 2))))
tmp_3 = np.zeros(shape=(tmp_1.shape[0], tmp.shape[1]))
for i in range(tmp.shape[1]):
tmp_3[:, i] = np.where(tmp_1[:, tmp[1, i]]*tmp_1[:, tmp[0, i]] != 0,
abs(tmp_1[:, tmp[0, i]]-tmp_1[:, tmp[1, i]]), 0)
# both are not equals 0
mean = np.true_divide(tmp_3.sum(0), (tmp_3 != 0).sum(0))
index = 0
mat = np.zeros((columns, columns))
for xi in range(columns-1):
for yi in range(xi, columns-1):
mat[xi, yi + 1] = mean[index]
mat[yi + 1, xi] = mean[index]
index = index + 1
return mat
def list_clusters(self, centroids, unique_centroids, umat):
""" list_clusters -- A function to get the clusters as a list of lists.
parameters:
- centroids - a matrix of the centroid locations in the map
- unique_centroids - a list of unique centroid locations
- umat - a unified distance matrix
"""
centroids_x_positions = unique_centroids['position_x']
centroids_y_positions = unique_centroids['position_y']
cluster_list = []
for i in range(len(centroids_x_positions)):
cx = centroids_x_positions[i]
cy = centroids_y_positions[i]
# get the clusters associated with a unique centroid and store it in a list
cluster_list.append(self.list_from_centroid(cx, cy, centroids, umat))
return cluster_list
def list_from_centroid(self, x, y, centroids, umat):
""" list_from_centroid -- A funtion to get all cluster elements
associated to one centroid.
parameters:
- x - the x position of a centroid
- y - the y position of a centroid
- centroids - a matrix of the centroid locations in the map
- umat - a unified distance matrix
"""
centroid_x = x
centroid_y = y
xdim = self.xdim
ydim = self.ydim
cluster_list = []
for xi in range(xdim):
for yi in range(ydim):
cx = centroids['centroid_x'][xi, yi]
cy = centroids['centroid_y'][xi, yi]
if(cx == centroid_x and cy == centroid_y):
cweight = np.matrix(umat)[xi, yi]
cluster_list.append(cweight)
return cluster_list
def combine_decision(self, within_cluster_dist, distance_between_clusters, rang):
""" combine_decision -- A function that produces a boolean matrix
representing which clusters should be combined.
parameters:
- within_cluster_dist - A list of the distances from centroid to cluster elements for all centroids
- distance_between_clusters - A list of the average pairwise distance between clusters
- range - The distance where the clusters are merged together.
"""
inter_cluster = distance_between_clusters
centroid_dist = within_cluster_dist
dim = inter_cluster.shape[1]
to_combine = np.matrix([[False]*dim]*dim)