-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharchitecturespaceanalyzer.py
More file actions
2331 lines (1932 loc) · 88 KB
/
architecturespaceanalyzer.py
File metadata and controls
2331 lines (1932 loc) · 88 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
import re
from glob import glob
from os.path import basename
import pandas as pd
import requests
from bs4 import BeautifulSoup
#import gdown
import os
import matplotlib.pyplot as plt
from os import listdir
from os.path import isfile, join
from natsort import natsorted, ns
import math
from scipy.spatial.distance import pdist, squareform
from distinctipy import distinctipy
#from fastDamerauLevenshtein import damerauLevenshtein
from collections import Counter, OrderedDict
import numpy as np
import seaborn as sns
from sklearn.decomposition import PCA
from sklearn.cluster import DBSCAN
from sklearn import metrics
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import MinMaxScaler
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_samples, silhouette_score
from sklearn.cluster import AgglomerativeClustering
from sklearn.cluster import SpectralClustering
from sklearn.preprocessing import LabelEncoder
import string
from yellowbrick.cluster import SilhouetteVisualizer
from yellowbrick.features import ParallelCoordinates
from yellowbrick.features import RadViz
import plotly.graph_objects as go
import plotly.offline as pyo
import scipy.cluster.hierarchy as sch
from scipy.spatial import distance
from scipy.stats import entropy
from scipy import spatial
from functools import reduce
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.ticker as ticker
import matplotlib
from pandas.plotting import parallel_coordinates
from collections import defaultdict
from pca import pca
import altair as alt
import networkx as nx
from networkx.drawing.nx_pydot import graphviz_layout
from difflib import SequenceMatcher
import zss
from pymoo.visualization.petal import Petal
from pymoo.mcdm.high_tradeoff import HighTradeoffPoints
from pymoo.decomposition.asf import ASF
from pymoo.mcdm.pseudo_weights import PseudoWeights
from pymoo.indicators.gd import GD
from pymoo.indicators.hv import HV
from pymoo.indicators.igd import IGD
from pymoo.indicators.igd_plus import IGDPlus
#from sklearn.manifold import TSNE
from openTSNE import TSNE
#import hdbscan
###########################################
class ArchitectureSpaceAnalyzer:
def __init__(self, project=None, objectives=None):
# All global (class-level) variables for a given project
self.ALL_OBJECTIVES = ['perfQ', 'reliability', '#changes', 'pas']
self.ALL_ARGUMENTS = ['operation', 'target', 'to', 'where']
self.INITIAL_SOLUTION = None #{'solID': 0, 'perfQ': 0.0, 'reliability': 0.7630625563279512, '#changes': 0, 'pas': 12}
self.ALL_REFACTORINGS = []
self.OBJECTIVES_PATH = ''
self.OBJECTIVES_FILES = ''
self.REFACTIONS_PATH = ''
self.REFACTIONS_FILES = ''
self.PROJECT_NAME = ''
self.FILE_INDEX = -1
self.FILE_DESCRIPTION = ''
# These are the labels to discretize each of the features in a 5-point scale
self.PERFORMANCE_LABELS = ['very-slow','slow', 'average', 'fast', 'very-fast'] # Is this absolute 0..1?
self.RELIABILITY_LABELS = ['unreliable','minimally-reliable', 'average', 'reliable','very-reliable'] # This is absolute 0..1
self.PAS_LABELS = ['very-few','few', 'average', 'some','many']
self.CHANGES_LABELS = ['very-few','few', 'average', 'some','many']
self.PERFORMANCE_LIMITS = (0,1.0)
self.RELIABILITY_LIMITS = (0,1.0)
self.CHANGES_LIMITS = (None,None)
self.PAS_LIMITS = (None,None)
self.CLUSTERS_COLORS = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf','#d3d3d3']
self.CLUSTERS = None
self.CLUSTER_LABELS = None
self.CLUSTERS_PALETTE = None
self.LABELS_COLORS = None
# Show interactive 2D charts with the solutions and the clusters
self.TOOLTIP = ['solID','perfQ', 'reliability', '#changes', 'pas', 'label', 'cluster']
self.ALPHABET = list(string.ascii_letters) + list(string.digits)
self.use_alphabet = True
self.action_parameters = 0 # These are default values for parsing refactoring actions
self.sequence_length = 4
self.objectives_df = None
self.refactions_df = None
if objectives is None:
self.objectives = self.ALL_OBJECTIVES
else:
self.objectives = objectives
self.cluster_labels = None
self.centroids_df = None
self.tagged_objectives_df = None
self.pareto_front_df = None
self._kmeans_kwargs = {
"init": "random",
"n_init": 10,
"max_iter": 300,
"random_state": 42
}
if project is not None:
self.initialize_dataset(project)
def set_colors(self, n=None, show_palette=False):
if n is not None:
# generate N visually distinct colours
colors = distinctipy.get_colors(n, rng=3)
self.CLUSTERS_COLORS = [matplotlib.colors.to_hex(c) for c in colors]
# display the colours
if show_palette:
print("New palette:", n, self.CLUSTERS_COLORS)
distinctipy.color_swatch(colors)
return colors
return None
def set_labels(self, cluster_labels):
n = len(cluster_labels)
colors = self.set_colors(n)
self.LABELS_COLORS = dict()
for idx, lb in enumerate(cluster_labels):
self.LABELS_COLORS[lb] = matplotlib.colors.to_hex(colors[idx])
return self.LABELS_COLORS
# Load both the objectives and refactoring actions for a given case
def initialize_dataset(self, project):
self.PROJECT_NAME = project
print('project:', self.PROJECT_NAME)
self.OBJECTIVES_PATH = './datasets/'+self.PROJECT_NAME+'/objectives'
self.OBJECTIVES_FILES = natsorted([f for f in listdir(self.OBJECTIVES_PATH) if isfile(join(self.OBJECTIVES_PATH, f))], key=lambda y: y.lower())
print('objective files=', len(self.OBJECTIVES_FILES))
self.REFACTIONS_PATH = './datasets/'+self.PROJECT_NAME+'/refactoring_actions'
self.REFACTIONS_FILES = natsorted([f for f in listdir(self.REFACTIONS_PATH) if isfile(join(self.REFACTIONS_PATH, f))], key=lambda y: y.lower())
print('refactoring actions files=', len(self.REFACTIONS_FILES))
###########################################
# static and private method
@staticmethod
def _flatten_block(df, include_parameters=0):
row_list =[]
solID = None
for index, row in df.iterrows():
#print(index,row)
# Create list for the current row
if type(include_parameters) == int:
p = include_parameters
else: # It should be a dictionary
p = include_parameters[row.operation]
if p == 1:
row_list.append(row.operation+'('+row.target+')')
elif p == 2:
row_list.append(row.operation+'('+row.target+','+str(row.to)+')')
elif p == 3:
row_list.append(row.operation+'('+row.target+','+str(row.to)+','+str(row['where'])+')')
else:
row_list.append(row.operation)
solID = row.solID
return [solID] + row_list
#return flat_df
# static and private method
@staticmethod
def _parse_operations(df, k=4, parameters=0): # Parameters control how much information is used for each operation
#print(k)
x = 0 # k is the sequence length
dfs = []
for y in range(0,df.shape[0]//k):
z = k*(y+1)
#print(x, z)
flat_df = ArchitectureSpaceAnalyzer._flatten_block(df[x:z], include_parameters=parameters)
dfs.append(flat_df)
x = z
#print(flat_df)
#print('===')
if k == 4: # TODO: Fix this hack later!
return pd.DataFrame(dfs, columns=['solID', 'op1', 'op2', 'op3', 'op4'])
else: # k should be 2
return pd.DataFrame(dfs, columns=['solID', 'op1', 'op2'])
# Get only the refactoring actions for a given index
def read_refactoring_actions(self, idx, length=4, arguments=3, verbose=True):
self.sequence_length = length
self.action_parameters = arguments
if verbose:
print('loading index:',idx)
self.FILE_INDEX = idx
ref_path = self.REFACTIONS_PATH+'/'+self.REFACTIONS_FILES[idx] # These are global variables
if verbose:
print(ref_path)
self.FILE_DESCRIPTION = self.REFACTIONS_FILES[idx][len('VAR'+str(idx+1)+'__'):]
refacts_df = pd.read_csv(ref_path)
self.ALL_REFACTORINGS = set(refacts_df['operation'])
#print(self.ALL_REFACTORINGS)
refacts_df = ArchitectureSpaceAnalyzer._parse_operations(refacts_df, k=length, parameters=arguments)
if length == 4: # TODO: Fix this hack later!
duplicate_refacts = refacts_df[refacts_df.duplicated(['op1', 'op2', 'op3', 'op4'], keep=False)]
else: # length should be 2
duplicate_refacts = refacts_df[refacts_df.duplicated(['op1', 'op2'], keep=False)]
if len(duplicate_refacts.index):
print("Warning: duplicate rows in refactoring actions!", list(duplicate_refacts['solID']))
self.refactions_df = refacts_df.copy()
return refacts_df
# Get only the objectives for a given index
def read_objectives(self, idx, invert=True, initial_solution=False, verbose=True):
if verbose:
print('loading index:',idx)
self.FILE_INDEX = idx
obj_path = self.OBJECTIVES_PATH+'/'+self.OBJECTIVES_FILES[idx] # These are global variables
if verbose:
print(obj_path)
self.FILE_DESCRIPTION = self.OBJECTIVES_FILES[idx][len('FUN'+str(idx+1)+'__'):]
objs_df = pd.read_csv(obj_path)
if invert:
objs_df['perfQ'] = (-1)*objs_df['perfQ']
objs_df['reliability'] = (-1)*objs_df['reliability']
if initial_solution:
objs_df = objs_df.append(self.INITIAL_SOLUTION, ignore_index=True)
objs_df = objs_df.astype({'solID': int})
if 'pas' not in objs_df.columns: # TODO: Fix this hack later!
objs_df['pas'] = 0.0
objs_df = objs_df[['solID']+self.ALL_OBJECTIVES]
duplicate_objs = objs_df[objs_df.duplicated(self.ALL_OBJECTIVES, keep=False)]
if len(duplicate_objs.index):
print("Warning: duplicate rows in objectives!", list(duplicate_objs['solID']))
self.objectives_df = objs_df.copy()
return objs_df
def read_objectives_refactoring_actions(self, idx, invert=True, length=4, arguments=3, initial_solution=False, verbose=True):
objs_df = self.read_objectives(idx, invert, initial_solution, verbose)
refacts_df = self.read_refactoring_actions(idx, arguments=arguments, verbose=verbose, length=length)
return objs_df, refacts_df
# Get all the feasible files (objectives, refactoring actions, or both) for a given project name
# Note: in case of files with formatting problems, they are ignored
def read_file_batch(self, min, max, invert=True, length=4, arguments=3, initial_solution=False, option='all', add_source=False):
print("Reading files ...", min, max, option)
objs_dflist = []
refactions_dflist = []
for n in range(min-1,max):
print(' file',n)
objs_df = None
refacts_df = None
try:
if option == 'all':
objs_df, refacts_df = self.read_objectives_refactoring_actions(n, length=length, arguments=arguments, initial_solution=False, verbose=False)
if add_source:
objs_df['source'] = str(n+1)+'_'+self.FILE_DESCRIPTION
refacts_df['source'] = str(n+1)+'_'+self.FILE_DESCRIPTION
if option == 'objectives':
objs_df = self.read_objectives(n, initial_solution=False, verbose=False)
if add_source:
objs_df['source'] = str(n+1)+'_'+self.FILE_DESCRIPTION
if option == 'refactions':
refacts_df = self.read_refactoring_actions(n, length=length, arguments=arguments, verbose=False)
if add_source:
refacts_df['source'] = str(n+1)+'_'+self.FILE_DESCRIPTION
except:
print("\tProblems loading objectives and/or refactoring actions:",(n+1))
if option == 'all':
objs_df = None
refacts_df = None
if option == 'objectives':
objs_df = None
if option == 'refactions':
refacts_df = None
#else:
# print("\t"+str(n)+": OK", FILE_DESCRIPTION)
if objs_df is not None:
objs_dflist.append(objs_df)
if refacts_df is not None:
refactions_dflist.append(refacts_df)
print("done.")
merged_objectives_df = None
if len(objs_dflist) > 0:
merged_objectives_df = pd.concat(objs_dflist, axis=0)
merged_objectives_df.reset_index(drop=True, inplace=True)
merged_refactions_df = None
if len(refactions_dflist) > 0:
merged_refactions_df = pd.concat(refactions_dflist, axis=0)
merged_refactions_df.reset_index(drop=True, inplace=True)
if merged_objectives_df is not None:
self.objectives_df = merged_objectives_df.copy()
else:
self.objectives_df = None
if merged_refactions_df is not None:
self.refactions_df = merged_refactions_df.copy()
else:
self.refactions_df = None
return merged_objectives_df, merged_refactions_df
###########################################
# static and private method
@staticmethod
def _get_silhouette_scores_for_clusters(df, labels, num_clusters):
sample_silhouette_values = metrics.silhouette_samples(df, labels)
means_lst = []
for lb in range(num_clusters):
#print(lb)
c_df = sample_silhouette_values[labels == lb]
means_lst.append(c_df.mean())
return means_lst
# Apply K-Means to cluster a dataframe (Pareto front) of numeric values
def run_kmeans(self, k, kwargs=None, n_pca=None, normalize=True, show_silhouette=False):
if kwargs is None:
kwargs = self._kmeans_kwargs
if normalize:
sample = StandardScaler().fit_transform(self.objectives_df[self.objectives])
else:
sample = self.objectives_df[self.objectives]
if n_pca is not None:
pca = PCA(n_components=n_pca)
sample_pca = pca.fit_transform(sample)
#print("Explained PCA variance:", np.sum(pca.explained_variance_ratio_))
print("PCA components:",len(pca.explained_variance_ratio_), pca.explained_variance_ratio_)
#plt.scatter(sample_pca[:,0], sample_pca[:,1])
#plt.show()
kmeans = KMeans(n_clusters=k, **kwargs).fit(sample_pca)
else:
kmeans = KMeans(n_clusters=k, **kwargs).fit(sample)
labels = kmeans.labels_
# Number of clusters in labels, ignoring noise if present.
n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)
n_noise_ = list(labels).count(-1)
print('Labels for instances:', kmeans.labels_)
fixed_labels = np.where(kmeans.labels_ < 0, 0, kmeans.labels_)
print("Estimated number of clusters: %d" % n_clusters_)
print("Estimated number of noise points: %d" % n_noise_)
classes = set(fixed_labels)
if len(classes) > 1:
if n_pca is not None:
silhouette = metrics.silhouette_score(sample_pca, fixed_labels)
silhouette_scores = ArchitectureSpaceAnalyzer._get_silhouette_scores_for_clusters(sample_pca, fixed_labels, k)
print("Individual Silhouette scores:", silhouette_scores)
else:
silhouette = metrics.silhouette_score(sample, fixed_labels)
silhouette_scores = ArchitectureSpaceAnalyzer._get_silhouette_scores_for_clusters(sample, fixed_labels, k)
print("Individual Silhouette scores:", silhouette_scores)
else:
silhouette = 0.0
print("Average Silhouette coefficient: %0.3f" % silhouette)
#print("Individual Silhouette scores:", sample_silhouette_values)
if show_silhouette:
# Instantiate the visualizer
visualizer = SilhouetteVisualizer(kmeans, colors='yellowbrick')
if n_pca is not None:
visualizer.fit(sample_pca)
else:
visualizer.fit(sample)
visualizer.show()
return fixed_labels, kmeans, silhouette
# Apply Aglomerative clustering to a dataframe (Pareto front) of numeric values
def run_agglomerative(self, k, threshold=200, n_pca=None, normalize=True, show_dendogram=False, archstructure=None):
if normalize:
sample = StandardScaler().fit_transform(self.objectives_df[self.objectives])
else:
sample = self.objectives_df[self.objectives]
if n_pca is not None:
pca = PCA(n_components=n_pca)
sample_pca = pca.fit_transform(sample)
#print("Explained PCA variance:", np.sum(pca.explained_variance_ratio_))
print("PCA components:",len(pca.explained_variance_ratio_), pca.explained_variance_ratio_)
#plt.scatter(sample_pca[:,0], sample_pca[:,1])
#plt.show()
model = AgglomerativeClustering(n_clusters=k, metric='euclidean', linkage='ward', connectivity=archstructure, distance_threshold=threshold)
model.fit(sample_pca)
# X = sample_pca
else:
model = AgglomerativeClustering(n_clusters=k, metric='euclidean', linkage='ward', connectivity=archstructure, distance_threshold=threshold)
model.fit(sample)
# X = sample
labels = model.labels_
print(f"Number of clusters = {1+np.amax(model.labels_)}")
# Number of clusters in labels, ignoring noise if present.
n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)
n_noise_ = list(labels).count(-1)
print('Labels for instances:', model.labels_)
fixed_labels = np.where(model.labels_ < 0, 0, model.labels_)
print("Estimated number of clusters: %d" % n_clusters_)
print("Estimated number of noise points: %d" % n_noise_)
classes = set(fixed_labels)
if len(classes) > 1:
if n_pca is not None:
silhouette = metrics.silhouette_score(sample_pca, fixed_labels)
silhouette_scores = ArchitectureSpaceAnalyzer._get_silhouette_scores_for_clusters(sample_pca, fixed_labels, k)
print("Individual Silhouette scores:", silhouette_scores)
else:
silhouette = metrics.silhouette_score(sample, fixed_labels)
silhouette_scores = ArchitectureSpaceAnalyzer._get_silhouette_scores_for_clusters(sample, fixed_labels, k)
print("Individual Silhouette scores:", silhouette_scores)
else:
silhouette = 0.0
print("Average Silhouette coefficient: %0.3f" % silhouette)
#print("Individual Silhouette scores:", sample_silhouette_values)
if show_dendogram:
fig = plt.figure(figsize=(20,10))
ax = fig.add_subplot(1, 1, 1)
dendrogram = sch.dendrogram(sch.linkage(sample, method='ward'), ax=ax)
plt.show()
return fixed_labels, model, silhouette
# def run_hdbscan(self, epsilon=0.0, min_cluster_size=5, n_pca=None, normalize=True,
# show_scatter=False, show_condensed_tree=False, show_linkage=False):
# if normalize:
# sample = StandardScaler().fit_transform(self.objectives_df[self.objectives])
# else:
# sample = self.objectives_df[self.objectives]
#
# if n_pca is not None:
# pca = PCA(n_components=n_pca)
# sample_pca = pca.fit_transform(sample)
# #print("Explained PCA variance:", np.sum(pca.explained_variance_ratio_))
# print("PCA components:",len(pca.explained_variance_ratio_), pca.explained_variance_ratio_)
# #plt.scatter(sample_pca[:,0], sample_pca[:,1])
# #plt.show()
# model = hdbscan.HDBSCAN(cluster_selection_epsilon=epsilon, min_cluster_size=min_cluster_size)
# model.fit(sample_pca)
## X = sample_pca
# else:
# model = hdbscan.HDBSCAN(cluster_selection_epsilon=epsilon, min_cluster_size=min_cluster_size)
# model.fit(sample)
## X = sample
#
# labels = model.labels_
# print(f"Number of clusters = {1+np.amax(model.labels_)}")
#
# # Number of clusters in labels, ignoring noise if present.
# n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)
# n_noise_ = list(labels).count(-1)
#
# print('Labels for instances:', model.labels_)
# fixed_labels = np.where(model.labels_ < 0, 0, model.labels_)
#
# print("Estimated number of clusters: %d" % n_clusters_)
# print("Estimated number of noise points: %d" % n_noise_)
# classes = set(fixed_labels)
# k = model.labels_.max()
# if len(classes) > 1:
# if n_pca is not None:
# silhouette = metrics.silhouette_score(sample_pca, fixed_labels)
# silhouette_scores = ArchitectureSpaceAnalyzer._get_silhouette_scores_for_clusters(sample_pca, fixed_labels, k)
# print("Individual Silhouette scores:", silhouette_scores)
# else:
# silhouette = metrics.silhouette_score(sample, fixed_labels)
# silhouette_scores = ArchitectureSpaceAnalyzer._get_silhouette_scores_for_clusters(sample, fixed_labels, k)
# print("Individual Silhouette scores:", silhouette_scores)
# else:
# silhouette = 0.0
# print("Average Silhouette coefficient: %0.3f" % silhouette)
# #print("Individual Silhouette scores:", sample_silhouette_values)
#
# if show_scatter:
# fig = plt.figure(figsize=(10,10))
# color_palette = sns.color_palette('deep', k+1)
# cluster_colors = [color_palette[x] if x >= 0
# else (0.5, 0.5, 0.5)
# for x in model.labels_]
# cluster_member_colors = [sns.desaturate(x, p) for x, p in
# zip(cluster_colors, model.probabilities_)]
# pca2 = PCA(n_components=2)
# sample_pca2 = pca2.fit_transform(sample)
# plt.scatter(sample_pca2[:, 0], sample_pca2[:, 1], s=50, linewidth=0, c=cluster_member_colors, alpha=0.25)
# plt.xlabel('PCA1 '+str(round(100*pca2.explained_variance_ratio_[0],2))+"%")
# plt.ylabel('PCA2 '+str(round(100*pca2.explained_variance_ratio_[1],2))+"%")
# plt.show()
#
# if show_condensed_tree:
# color_palette = sns.color_palette('deep', k+1)
# model.condensed_tree_.plot(select_clusters=True, selection_palette=color_palette)
#
# if show_linkage:
# model.single_linkage_tree_.plot()
#
# return fixed_labels, model, silhouette
###########################################
def show_parallel_plot(self, cluster_labels=None, title=None, size=(600,400), normalize=False):
sample = self.objectives_df[self.objectives]
if title is None:
title = self.PROJECT_NAME
features = sample.columns
if cluster_labels is None:
classes = None
palette_clusters = sns.color_palette(None, 1)
else:
classes = set(cluster_labels)
palette_clusters = sns.color_palette("husl",len(classes))
# Trying to visualize the different clusters
n = None
if normalize:
n = 'standard'
visualizer = ParallelCoordinates(classes=classes, features=features, fast=False,
title=title, size=size, colors=palette_clusters, normalize=n)
if cluster_labels is None:
cluster_labels = [-1]*(sample.shape[0])
#print(cluster_labels)
visualizer.fit_transform(sample, cluster_labels)
visualizer.show(legend=None)
#visualizer.ax.legend().set_visible(False)
plt.show()
return palette_clusters
# Apply PCA on the dataframe
def _apply_pca(self, df, n_pca=2, normalize=True):
if normalize:
sample = StandardScaler().fit_transform(df)
else:
sample = df
pca_ = PCA(n_components=n_pca)
sample_pca = pca_.fit_transform(sample)
print("PCA components:",len(pca_.explained_variance_ratio_), pca_.explained_variance_ratio_)
return sample_pca, pca_
# Apply t-SNE on the dataframe
def _apply_tsne(self, df, n_tsne=2, normalize=True):
if normalize:
sample = StandardScaler().fit_transform(df)
else:
sample = df
tsne_embedding = TSNE(n_components=n_tsne, random_state=1).fit(sample)
#sample_tsne = tsne_.fit_transform(sample)
return tsne_embedding
# Show the clusters after a 2D t-SNE reduction
def show_clusters_tsne(self, cluster_labels=None, palette=None, title=None, size=(600,400), tsne=None):
df = self.objectives_df[self.ALL_OBJECTIVES]
tsne_ = tsne
if tsne_ is None:
tsne_sample = self._apply_tsne(df)
tsne_ = tsne_sample
else:
print("Reusing t-SNE")
tsne_sample = tsne_.transform(StandardScaler().fit_transform(df.values))
print(len(df.columns), "features", list(df.columns))
if title is None:
title = space.PROJECT_NAME
# Show the 2D representation
plt.figure(figsize=(size[0]/60,size[1]/60))
if cluster_labels is not None:
print(len(set(cluster_labels)), "clusters")
else:
print("no clusters")
if palette is None:
plt.scatter(tsne_sample[:, 0], tsne_sample[:, 1], c='blue', s=50, alpha=0.7, cmap='viridis')
else:
cluster_colors = [palette[c] for c in cluster_labels]
plt.scatter(tsne_sample[:, 0], tsne_sample[:, 1], c=cluster_colors, s=50, alpha=0.7, cmap='viridis')
# title and labels
plt.title(title, fontsize=16)
plt.show()
#return palette
return tsne_
# Show the clusters after a 2D PCA reduction
def show_clusters_pca_2d(self, cluster_labels=None, palette=None, title=None, size=(600,400), pca=None):
df = self.objectives_df[self.ALL_OBJECTIVES]
pca_ = pca
if pca_ is None:
sample_pca, pca_ = self._apply_pca(df)
else:
print("Reusing PCA")
sample_pca = pca_.transform(StandardScaler().fit_transform(df.values))
print(len(df.columns), "features", list(df.columns))
if title is None:
title = self.PROJECT_NAME
# Show the 2D representation
plt.figure(figsize=(size[0]/60,size[1]/60))
if cluster_labels is not None:
print(len(set(cluster_labels)), "clusters")
else:
print("no clusters")
if palette is None:
plt.scatter(sample_pca[:, 0], sample_pca[:, 1], c='blue', s=50, alpha=0.7, cmap='viridis')
else:
cluster_colors = [palette[c] for c in cluster_labels]
plt.scatter(sample_pca[:, 0], sample_pca[:, 1], c=cluster_colors, s=50, alpha=0.7, cmap='viridis')
# title and labels
plt.title(title, fontsize=16)
plt.xlabel('PCA1 '+str(round(100*pca_.explained_variance_ratio_[0],2))+"%")
plt.ylabel('PCA2 '+str(round(100*pca_.explained_variance_ratio_[1],2))+"%")
plt.show()
#return palette
return pca_
# Alternative PCA implementation (supporting both 2D and 3D projections)
def show_clusters_pca(self, cluster_labels=None, n_components=3, kind='2D', size=(18,10), title=None):
if title is None:
title = self.PROJECT_NAME
X = self.objectives_df[self.ALL_OBJECTIVES]
if cluster_labels is not None:
y = cluster_labels
else:
y = np.array([-1]*X.shape[0])
#model = pca(n_components=0.95)
model = pca(n_components=n_components)
results = model.fit_transform(X)
print("Top features:", results['topfeat'])
# Cumulative explained variance
print("Cumulative explained variance:", model.results['explained_var'])
# Explained variance per PC
print("Explained variance:", model.results['variance_ratio'])
# Make 3D Plot
if kind == '3D':
fig, ax = model.biplot3d(n_feat=6, PC=[0,1,2], y=y, label=False, figsize=size, title=title)
else:
# Make 2D plot
fig, ax = model.biplot(n_feat=6, PC=[0,1], y=y, label=False, figsize=size, title=title)
ax.title.set_fontsize(15)
ax.title.set_fontweight('bold')
fig.show()
#plt.show()
def show_radviz(self, cluster_labels, palette=None, title=None, size=(800, 600)):
if title is None:
title = self.PROJECT_NAME
X = self.objectives_df[self.objectives]
if cluster_labels is not None:
y = cluster_labels
else:
y = np.array([-1]*X.shape[0])
clusters = set(y)
# Instantiate the visualizer
visualizer = RadViz(classes=clusters, colors=palette, title=title, size=size)
visualizer.fit_transform(X, y) # Fit the data to the visualizer
#visualizer.transform(X) # Transform the data
visualizer.show()
plt.show()
def show_density_plot(self, objectives=None, pca=False, kind='kde', bins=5,
normalize=False, rug=True, levels=10,
size=(12,10), vminmax=(None,None), title=None, xlim=None, ylim=None):
if title is None:
title = self.PROJECT_NAME
pca_ = None
df = self.objectives_df[self.ALL_OBJECTIVES].copy()
if (pca is True) and (objectives is None):
objectives = ['pca1', 'pca2']
pca_data, pca_ = self._apply_pca(df, normalize=True)
df = pd.DataFrame(pca_data, columns=objectives)
elif (pca is not None) and (objectives is None):
objectives = ['pca1', 'pca2']
print("Reusing PCA transformation ...")
print("PCA components:",len(pca.explained_variance_ratio_), pca.explained_variance_ratio_)
pca_data = pca.transform(StandardScaler().fit_transform(df))
df = pd.DataFrame(pca_data, columns=objectives)
elif objectives is None: # PCA is false
objectives = self.objectives #self.ALL_OBJECTIVES[0:2]
de = None
if not pca:
de = round(self.compute_density_entropy(objectives=objectives, bins=bins),2)
title = title + ' [de=' + str(de) +']'#str(objectives)
if normalize or (kind == 'bins'):
if (xlim is not None) and (ylim is not None):
print("Scaling with:", xlim, ylim)
df[objectives[0]] = (df[objectives[0]] - xlim[0]) / (xlim[1] - xlim[0])
df[objectives[1]] = (df[objectives[1]] - ylim[0]) / (xlim[1] - ylim[0])
data = df
else:
data = MinMaxScaler().fit_transform(df[objectives])
data = pd.DataFrame(data, columns=objectives)
else:
data = df
if kind == 'kde':
# kde_plot = sns.kdeplot(data=data, x=objectives[0], y=objectives[1],
# cmap=sns.color_palette("rocket_r", as_cmap=True),
# vmin=vminmax[0], vmax=vminmax[1], cbar=True,
# levels=levels, shade_lowest=False, shade=True)
kde_plot = sns.displot(data=data, x=objectives[0], y=objectives[1],
cmap=sns.color_palette("rocket_r", as_cmap=True),
vmin=vminmax[0], vmax=vminmax[1], cbar=True,
rug=rug, fill=True, kind="kde",height=6, aspect=11.7/8.27)
if kind == 'bins':
fig,ax = plt.subplots(figsize=size)
bins_plot = sns.histplot(data=data, x=objectives[0], y=objectives[1], # TODO: This needs to be replaces by a heatmap
cmap=sns.color_palette("rocket_r", as_cmap=True),
vmin=vminmax[0], vmax=vminmax[1], cbar=True,
stat='probability', bins=bins, binrange=(xlim,ylim))
#ax.xaxis.set_major_locator(ticker.MultipleLocator(1/5))
#ax.yaxis.set_major_locator(ticker.MultipleLocator(1/5))
if normalize or (kind == 'bins'):
plt.xlim([0,1])
plt.ylim([0,1])
elif (not normalize) and (xlim is not None) and (ylim is not None):
plt.xlim(xlim)
plt.ylim(ylim)
plt.title(title, fontsize=16)
plt.show()
return pca_
def _get_minmax(self, obj):
if obj == '#changes':
return self.CHANGES_LIMITS
if obj == 'pas':
return self.PAS_LIMITS
if obj == 'perfQ':
return self.PERFORMANCE_LIMITS
if obj == 'reliability':
return self.RELIABILITY_LIMITS
return None, None
def _normalize_objectives(self, objectives=None):
if objectives is None:
objectives = self.objectives
df = self.objectives_df[objectives].copy()
for obj in objectives:
minobj, maxobj = self._get_minmax(obj)
if (minobj is None) and (maxobj is None):
minobj = df[obj].min()
maxobj = df[obj].max()
df[obj] = (df[obj] - minobj) / (maxobj - minobj)
return df
# This is a measure of the homogeneity of space, in terms of the density of solutions.
# If closer to 1, the space is "bumpy" (valleys and peaks). If closer to 0, the space is flat.
def compute_density_entropy(self, objectives=None, normalize=True, bins=10):
if objectives is None:
objectives = self.objectives
if normalize:
data = self._normalize_objectives(objectives).values #MinMaxScaler().fit_transform(self.objectives_df[objectives])
spacing = np.linspace(0,1,bins+1)
bin_edges = [tuple(x) for x in [spacing]*len(objectives)]
#print(n_tuples)
else:
data = self.objectives_df[objectives].values
bin_edges = bins
histogram_nd, _ = np.histogramdd(data, bins=bin_edges, density=False)
array_1d = histogram_nd.ravel()
#print("Total:", np.sum(array_1d))
#print("Array size:", array_1d.size)
array_1d = array_1d / np.sum(array_1d)
#print(np.sum(array_1d))
return entropy(array_1d, base=array_1d.size)
###########################################
@staticmethod
def _get_near_centroid(df, cluster): # Select the point with the smallest distance to a given theoretical centroid (point)
objectives = list(df.columns)
objectives.remove('cluster')
if 'label' in objectives:
objectives.remove('label')
if 'prototype' in objectives:
objectives.remove('prototype')
#print(objectives)
points_of_cluster = df[df['cluster']==cluster]
centroid_of_cluster = np.mean(points_of_cluster[objectives], axis=0)
#print("centroid=", centroid_of_cluster)
#print([centroid_of_cluster])
#print(points_of_cluster[objectives])
pos = np.argmax(-distance.cdist([centroid_of_cluster], points_of_cluster[objectives], metric='euclidean'))
idx = points_of_cluster.index[pos]
#print(pos,idx)
#print("Returning a real centroid ...")
return idx, points_of_cluster.loc[idx]
@staticmethod
def _get_centroids(df, cluster_choice=[]): # Get the real centroids for each cluster
centroids = []
#clusters = set(df['cluster'])
if len(cluster_choice) == 0:
clusters = set(df['cluster'])
else:
clusters = cluster_choice
for c in clusters:
pos, _ = ArchitectureSpaceAnalyzer._get_near_centroid(df, c) # Get the real centroids for each cluster
centroids.append(pos)
return centroids
# Generate the (real) cluster centroids as prototypes for each cluster
@staticmethod
def _add_cluster_prototypes(df, protos=None, cluster_choice=[]):
df['prototype'] = False
if protos is None:
protos = ArchitectureSpaceAnalyzer._get_centroids(df, cluster_choice)
print("Configuring (real) cluster centroids as prototypes ...", protos)
else:
print("Using alternatives as prototypes ...", protos)
for p in protos:
df.at[p, 'prototype'] = True
return df
@staticmethod
def _get_dist_bins(col, n): # Split the values of the column into n buckets, according to the distribution of values
unique_values = sorted((set(col.values)))
#print(unique_values)
#sorted(set(pd.qcut(unique_values, 5)))
return sorted(set(pd.qcut(unique_values, n).map(lambda x: x.left))) + [max(unique_values)]
def _get_bins(col, n, min_max=(None,None)):
unique_values = sorted((set(col.values)))
if min_max == (None,None):
min_x = np.min(unique_values)
max_x = np.max(unique_values)
else:
print("Using predefined limits",min_max)
min_x = min_max[0]
max_x = min_max[1]
min_x = min_x - 0.1
max_x = max_x + 0.1
delta = (max_x - min_x)/n
#print(min_x, max_x, delta)
return ([min_x+i*delta for i in range(0,n)] + [max_x])
@staticmethod
def _get_fixed_bins(col, n): # Split the values of the column into n fixed buckets (i.e., same size)
min = col.min()
#if min < 0:
# min = 0
max = col.max()
#if max > 1:
# max = 1
_, fixed_bins = pd.cut([min,max], bins=5, retbins=True)
print(min,max)
return fixed_bins
@staticmethod
def _extract_cluster_labels(df, clusters):
dict_cluster_label = {}
for c in clusters:
lb = df[df['cluster'] == c]['label'].values[0]
dict_cluster_label[c] = lb
n_labels = len(set(dict_cluster_label.values()))
if n_labels < len(clusters):
print("Warning: some clusters have the same labels, so they might not be distinguishable!")
return dict_cluster_label
def _update_cluster_information(self):
print("Updating clustering information ...")
self.CLUSTERS = set(self.centroids_df['cluster'])
#print(self.CLUSTERS)
self.CLUSTER_LABELS = ArchitectureSpaceAnalyzer._extract_cluster_labels(self.centroids_df, self.CLUSTERS)
#print(self.CLUSTER_LABELS)
if self.LABELS_COLORS is None:
self.CLUSTERS_PALETTE = sns.color_palette(self.CLUSTERS_COLORS[0:len(self.CLUSTERS)])
else:
color_list = [self.LABELS_COLORS[lb] for lb in self.CLUSTER_LABELS.values()]
self.CLUSTERS_PALETTE = sns.color_palette(color_list)
# TODO: Try to get always the same palette, based on the labels assigned to each cluster
return self.CLUSTERS_PALETTE
def assign_cluster_labels(self, labels):
self.cluster_labels, n, self.centroids_df, self.tagged_objectives_df = self.get_cluster_labels(labels)
# Warning: Labels are relative to the range of values of each objective
# print(n, cluster_labels)
self.tagged_objectives_df['solID'] = self.objectives_df['solID']
self.centroids_df['cluster'] = self.cluster_labels.keys()
self.centroids_df['label'] = self.cluster_labels.values()
self._update_cluster_information()