-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
387 lines (346 loc) · 17.1 KB
/
main.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
from PyQt5.QtWidgets import QApplication, QWidget, QTableWidget, QTableWidgetItem, QHeaderView, QFileDialog, QMessageBox
from PyQt5.QtGui import *
from PyQt5.QtCore import*
from GUI import *
import sys
import dataProcessing
import algorithms
import basicFun
import visualization
import os
import numpy
# this class is for the user interface of the software
class clusteringApplication(QWidget):
def __init__(self):
'''
Initializing the ui
'''
super(clusteringApplication, self).__init__()
self.ui = Ui_Widget()
self.ui.setupUi(self)
self.algorithmList = ['','K-means','DBSCAN','Hierachical','Hierachical_2','Spectral', 'Affinity','Rote']
self.database = dataProcessing.readJson()
self.database = dataProcessing.transformCoordinate(self.database)
self.starsWithName = dataProcessing.chooseStarWithName(self.database)
self.assignments = []
def addItemToAlgorithmbox(self):
'''
add algorithms to the combobox
'''
self.ui.algorithmBox.addItems(self.algorithmList)
self.ui.algorithmBox.activated.connect(self._setParameterTable)
return
def addContentsToParameterTable(self):
'''
add contents to the parameters table
'''
self.ui.parameterWidget.setHorizontalHeaderItem(0, QTableWidgetItem('Parameter'))
self.ui.parameterWidget.setHorizontalHeaderItem(1, QTableWidgetItem('Value'))
self.ui.parameterWidget.verticalHeader().setVisible(False)
self.ui.parameterWidget.horizontalHeader().setStretchLastSection(True)
self.ui.parameterWidget.resizeColumnsToContents()
self.ui.parameterWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Fixed)
return
def addReadOnlyToClusteringResults(self):
'''
add constraints to the plain text edit
'''
#self.ui.scrollArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
self.ui.clusteringResults.setReadOnly(True)
def addActionToRunButton(self):
'''
add action to the run button
'''
self.ui.runButton.clicked.connect(self._run_algorithms)
return
def addActionToVisualButtom(self):
'''
add action to the visualizing button
'''
self.ui.visualButton.clicked.connect(self._visualization)
return
def addActionToSaveButton(self):
'''
add action to the save button
'''
self.ui.saveButton.clicked.connect(self._savedata)
return
def addActionToClearButton(self):
'''
add action to the clear button'
'''
self.ui.clearButton.clicked.connect(self._clearAll)
return
def _setParameterTable(self):
'''
the action of changing parameter table contents according to the combobox
'''
if self.ui.algorithmBox.currentText() == 'K-means':
'''
Set up kmeans
'''
self.ui.parameterWidget.clearContents()
self.ui.clusteringResults.clear()
self.ui.parameterWidget.setItem(0,0, QTableWidgetItem('Bright_th'))
self.ui.parameterWidget.setItem(1,0, QTableWidgetItem('K'))
elif self.ui.algorithmBox.currentText() == 'DBSCAN':
'''
set up DBSCAN
'''
self.ui.parameterWidget.clearContents()
self.ui.clusteringResults.clear()
self.ui.parameterWidget.setItem(0,0, QTableWidgetItem('Bright_th'))
self.ui.parameterWidget.setItem(1,0, QTableWidgetItem('Eps'))
self.ui.parameterWidget.setItem(2,0, QTableWidgetItem('minDist'))
elif self.ui.algorithmBox.currentText() == 'Hierachical':
'''
set up hierachical clustering
'''
self.ui.parameterWidget.clearContents()
self.ui.clusteringResults.clear()
self.ui.parameterWidget.setItem(0,0, QTableWidgetItem('Bright_th'))
self.ui.parameterWidget.setItem(1,0, QTableWidgetItem('n_cluster'))
elif self.ui.algorithmBox.currentText() == 'Hierachical_2':
'''
set up hierachical cluster_2
'''
self.ui.parameterWidget.clearContents()
self.ui.clusteringResults.clear()
self.ui.parameterWidget.setItem(0,0, QTableWidgetItem('Bright_th'))
elif self.ui.algorithmBox.currentText() == 'Spectral':
'''
set up spectral clustering
'''
self.ui.parameterWidget.clearContents()
self.ui.clusteringResults.clear()
self.ui.parameterWidget.setItem(0,0, QTableWidgetItem('Bright_th'))
self.ui.parameterWidget.setItem(1,0, QTableWidgetItem('n_cluster'))
elif self.ui.algorithmBox.currentText() == 'Affinity':
'''
set up affinity propagation
'''
self.ui.parameterWidget.clearContents()
self.ui.clusteringResults.clear()
self.ui.parameterWidget.setItem(0,0, QTableWidgetItem('Bright_th'))
self.ui.parameterWidget.setItem(1,0, QTableWidgetItem('damping'))
self.ui.parameterWidget.setItem(2,0, QTableWidgetItem('max_iter'))
elif self.ui.algorithmBox.currentText() == 'Rote':
'''
set up rote classification
'''
self.ui.parameterWidget.clearContents()
self.ui.clusteringResults.clear()
self.ui.parameterWidget.setItem(0,0, QTableWidgetItem('Bright_th'))
def _clearAll(self):
'''
the action of clear button
'''
self.ui.algorithmBox.setCurrentIndex(0)
self.ui.parameterWidget.clearContents()
self.ui.clusteringResults.clear()
return
def _visualization(self):
'''
the action of visualizing button
'''
if self.ui.algorithmBox.currentText() != 'Hierachical_2':
visualization.visualize(self.assignments, self.ui.algorithmBox.currentText())
else:
visualization.drawDendrogram(self.linkMatrix)
return
def _savedata(self):
'''
the action of saving data
'''
filename = QFileDialog.getSaveFileName(self, 'Save File',os.path.expanduser('~'), 'plain text file (*.txt *.dat)')
try:
fname = open(filename[0], 'w')
filedata = str(self.ui.clusteringResults.toPlainText())
fname.write(filedata)
fname.close()
except:
QMessageBox.information(self, 'Warning!', 'Data not saved!', QMessageBox.Ok)
return
def _run_algorithms(self):
'''
The action of run button
'''
#----------------------------------------------------------------------------------#
if self.ui.algorithmBox.currentText() == 'K-means':
# if running K-means algorithm
bright_th = float(self.ui.parameterWidget.item(0,1).text())
K = int(self.ui.parameterWidget.item(1,1).text())
starsNeedClustering = dataProcessing.selectBrightness(self.starsWithName, bright_th)
logScore = 0
standardKmeans = algorithms.KMeansPlusPlus(starsNeedClustering, K)
#standardKmeans.randInitCentroid()
#standardKmeans.runStandardKmeansWithoutIter()
standardKmeans.runKmeansPlusPlus()
self.ui.clusteringResults.setPlainText('# Algorithm finished. '+ str(K)+ ' Clusters found!\n\n# Press "visualizing" to see the 3D results.\n\n# Clusters are shown below.\n')
self.ui.clusteringResults.appendPlainText('# The Silhouette Coefficient is ' + str(standardKmeans.silhouetteScore) + '\n')
self.ui.clusteringResults.appendPlainText('# The Adjusted Rand index is ' + str(standardKmeans.adjustedScore) + '\n')
#self.ui.clusteringResults.appendPlainText('# The overall cosine dissimilarity is ' + str(standardKmeans.getDissimilarity()))
for i in range(K):
self.ui.clusteringResults.appendPlainText('\n**************************************')
self.ui.clusteringResults.appendPlainText('Stars belong to cluster '+str(i+1)+':\n')
cluster = standardKmeans.getCluster(i)
names = []
for idx in range(len(cluster)):
self.ui.clusteringResults.appendPlainText('[name] '+cluster[idx]['name']+', [Brightness] ' + str(cluster[idx]['brightness']))
names.append(cluster[idx]['name'][-3:])
if names != []:
logScore += numpy.log(len(list(set(names))))
#self.ui.clusteringResults.appendPlainText('\nThe total log Score is '+str(logScore))
self.assignments = standardKmeans.assignments
#----------------------------------------------------------------------------------#
elif self.ui.algorithmBox.currentText() == 'DBSCAN':
# if running DBSCAN algorithm
bright_th = float(self.ui.parameterWidget.item(0,1).text())
Eps = float(self.ui.parameterWidget.item(1,1).text())
minDist = int(self.ui.parameterWidget.item(2,1).text())
starsNeedClustering = dataProcessing.selectBrightness(self.starsWithName, bright_th)
logScore = 0
standardDBS = algorithms.densityBasedClustering(starsNeedClustering, Eps, minDist)
standardDBS.runDBA()
self.ui.clusteringResults.setPlainText('# Algorithm finished. '+ str(standardDBS.getNumOfClusters())+ ' Clusters found!\n\n# Press "visualizing" to see the 3D results.\n\n# Clusters are shown below.\n')
noise = standardDBS.getNoise()
self.ui.clusteringResults.appendPlainText('# The Silhouette Coefficient is ' + str(standardDBS.silhouetteScore) + '\n')
self.ui.clusteringResults.appendPlainText('# The Adjusted Rand index is ' + str(standardDBS.adjustedScore) + '\n')
self.ui.clusteringResults.appendPlainText('\n**************************************')
self.ui.clusteringResults.appendPlainText('Stars that are detected as noises:\n')
# output noise
for idx in range(len(noise)):
self.ui.clusteringResults.appendPlainText('[name] '+noise[idx]['name']+', [Brightness] ' + str(noise[idx]['brightness']))
# output clusters
for i in range(standardDBS.numOfClusters):
self.ui.clusteringResults.appendPlainText('\n**************************************')
self.ui.clusteringResults.appendPlainText('Stars belong to cluster '+str(i+1)+':\n')
cluster = standardDBS.getCluster(i)
names = []
for idx in range(len(cluster)):
self.ui.clusteringResults.appendPlainText('[name] '+cluster[idx]['name']+', [Brightness] ' + str(cluster[idx]['brightness']))
names.append(cluster[idx]['name'][-3:])
if names != []:
logScore += numpy.log(len(list(set(names))))
# self.ui.clusteringResults.appendPlainText('\nThe total log Score is '+str(logScore))
self.assignments = standardDBS.assignments
#----------------------------------------------------------------------------------#
elif self.ui.algorithmBox.currentText() == 'Hierachical':
# if running Hierarchical clustering
bright_th = float(self.ui.parameterWidget.item(0,1).text())
n_cluster = int(self.ui.parameterWidget.item(1,1).text())
starsNeedClustering = dataProcessing.selectBrightness(self.starsWithName, bright_th)
logScore = 0
standardHC = algorithms.aggolomerativeClustering(starsNeedClustering, n_cluster)
standardHC.runHierachicalClustering()
self.ui.clusteringResults.setPlainText('# Algorithm finished. '+ str(n_cluster)+ ' Clusters found!\n\n# Press "visualizing" to see the 3D results.\n\n# Clusters are shown below.\n')
self.ui.clusteringResults.appendPlainText('# The Silhouette Coefficient is ' + str(standardHC.silhouetteScore) + '\n')
self.ui.clusteringResults.appendPlainText('# The Adjusted Rand index is ' + str(standardHC.adjustedScore) + '\n')
for i in range(n_cluster):
self.ui.clusteringResults.appendPlainText('\n**************************************')
self.ui.clusteringResults.appendPlainText('Stars belong to cluster '+str(i+1)+':\n')
cluster = standardHC.getCluster(i)
names = []
for idx in range(len(cluster)):
self.ui.clusteringResults.appendPlainText('[name] '+cluster[idx]['name']+', [Brightness] ' + str(cluster[idx]['brightness']))
names.append(cluster[idx]['name'][-3:])
if names != []:
logScore += numpy.log(len(list(set(names))))
#self.ui.clusteringResults.appendPlainText('\nThe total log Score is '+str(logScore))
self.assignments = standardHC.assignments
#----------------------------------------------------------------------------------#
elif self.ui.algorithmBox.currentText() == 'Hierachical_2':
# if running Hierarchical clustering_2
bright_th = float(self.ui.parameterWidget.item(0,1).text())
starsNeedClustering = dataProcessing.selectBrightness(self.starsWithName, bright_th)
HC_2 = algorithms.hierarchicalClustering(starsNeedClustering)
HC_2.runHC_Version_2()
self.ui.clusteringResults.setPlainText('# Algorithm finished. \n\n# Press "visualizing" to see the hierarchical trees.\n')
self.linkMatrix = HC_2.linkMatrix;
#----------------------------------------------------------------------------------#
elif self.ui.algorithmBox.currentText() == 'Spectral':
# if running spectral clustering
bright_th = float(self.ui.parameterWidget.item(0,1).text())
n_cluster = int(self.ui.parameterWidget.item(1,1).text())
starsNeedClustering = dataProcessing.selectBrightness(self.starsWithName, bright_th)
logScore = 0
standardSpectralClustering = algorithms.spectralClustering(starsNeedClustering, n_cluster)
standardSpectralClustering.runSpectralClustering()
self.ui.clusteringResults.setPlainText('# Algorithm finished. '+ str(n_cluster)+ ' Clusters found!\n\n# Press "visualizing" to see the 3D results.\n\n# Clusters are shown below.\n')
self.ui.clusteringResults.appendPlainText('# The Silhouette Coefficient is ' + str(standardSpectralClustering.silhouetteScore) + '\n')
self.ui.clusteringResults.appendPlainText('# The Adjusted Rand index is ' + str(standardSpectralClustering.adjustedScore) + '\n')
for i in range(n_cluster):
self.ui.clusteringResults.appendPlainText('\n**************************************')
self.ui.clusteringResults.appendPlainText('Stars belong to cluster '+str(i+1)+':\n')
cluster = standardSpectralClustering.getCluster(i)
names = []
for idx in range(len(cluster)):
self.ui.clusteringResults.appendPlainText('[name] '+cluster[idx]['name']+', [Brightness] ' + str(cluster[idx]['brightness']))
names.append(cluster[idx]['name'][-3:])
if names != []:
logScore += numpy.log(len(list(set(names))))
#self.ui.clusteringResults.appendPlainText('\nThe total log Score is '+str(logScore))
self.assignments = standardSpectralClustering.assignments
#----------------------------------------------------------------------------------#
elif self.ui.algorithmBox.currentText() == 'Affinity':
# if running affinity propagation
bright_th = float(self.ui.parameterWidget.item(0,1).text())
damping = float(self.ui.parameterWidget.item(1,1).text())
max_iter = int(self.ui.parameterWidget.item(2,1).text())
starsNeedClustering = dataProcessing.selectBrightness(self.starsWithName, bright_th)
logScore = 0
standardAP = algorithms.affinityPropagation(starsNeedClustering, damping, max_iter)
standardAP.runAffinityPropagation()
self.ui.clusteringResults.setPlainText('# Algorithm finished. '+ str(standardAP.getNumOfClusters())+ ' Clusters found!\n\n# Press "visualizing" to see the 3D results.\n\n# Clusters are shown below.\n')
self.ui.clusteringResults.appendPlainText('# The Silhouette Coefficient is ' + str(standardAP.silhouetteScore) + '\n')
self.ui.clusteringResults.appendPlainText('# The Adjusted Rand index is ' + str(standardAP.adjustedScore) + '\n')
#self.ui.clusteringResults.appendPlainText('# The overall cosine dissimilarity is ' + str(standardAP.getDissimilarity()))
centers = standardAP.getCenters()
for i in range(standardAP.getNumOfClusters()):
self.ui.clusteringResults.appendPlainText('\n**************************************')
self.ui.clusteringResults.appendPlainText('Stars belong to cluster '+str(i+1)+':\n')
self.ui.clusteringResults.appendPlainText('The center of this cluster: ' + str(centers[i]['name'])+'\n')
cluster = standardAP.getCluster(i)
names = []
for idx in range(len(cluster)):
self.ui.clusteringResults.appendPlainText('[name] '+cluster[idx]['name']+', [Brightness] ' + str(cluster[idx]['brightness']))
names.append(cluster[idx]['name'][-3:])
if names != []:
logScore += numpy.log(len(list(set(names))))
# self.ui.clusteringResults.appendPlainText('\nThe total log Score is '+str(logScore))
self.assignments = standardAP.assignments
#----------------------------------------------------------------------------------#
elif self.ui.algorithmBox.currentText() == 'Rote':
# if running rote classification
bright_th = float(self.ui.parameterWidget.item(0,1).text())
starsNeedClustering = dataProcessing.selectBrightness(self.starsWithName, bright_th)
constellationNames = dataProcessing.getConstellationNames(starsNeedClustering)
logScore = 0
rote = algorithms.roteClassification(starsNeedClustering, constellationNames)
rote.runRoteClassification()
self.ui.clusteringResults.setPlainText('# Algorithm finished. '+ str(rote.getNumOfClusters())+ ' Clusters found!\n\n# Press "visualizing" to see the 3D results.\n\n# Clusters are shown below.\n')
for i in range(rote.getNumOfClusters()):
self.ui.clusteringResults.appendPlainText('\n**************************************')
self.ui.clusteringResults.appendPlainText('Stars belong to cluster '+str(i+1)+':\n')
cluster = rote.getCluster(i)
names = []
for idx in range(len(cluster)):
self.ui.clusteringResults.appendPlainText('[name] '+cluster[idx]['name']+', [Brightness] ' + str(cluster[idx]['brightness']))
names.append(cluster[idx]['name'][-3:])
if names != []:
logScore += numpy.log(len(list(set(names))))
#self.ui.clusteringResults.appendPlainText('\nThe total log Score is '+str(logScore))
self.assignments = rote.assignments
return
# create instances
app = QApplication(sys.argv)
interface = clusteringApplication()
interface.addItemToAlgorithmbox()
interface.addActionToRunButton()
interface.addContentsToParameterTable()
interface.addReadOnlyToClusteringResults()
interface.addActionToClearButton()
interface.addActionToSaveButton()
interface.addActionToVisualButtom()
interface.show()
sys.exit(app.exec_())