Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python3
- # -*- coding: utf-8 -*-
- import time,sys
- import math as m
- import pyperclip as x_p
- import numpy as np
- import random as rn
- import matplotlib
- from mpl_toolkits.mplot3d import Axes3D
- import matplotlib.pyplot as plt
- from PyQt5.QtWidgets import QTableView
- from PyQt5.QtCore import Qt
- from PyQt5.QtWidgets import (QWidget, QGridLayout,QHBoxLayout,
- QPushButton, QApplication,QLineEdit,QCheckBox, QLabel,QMessageBox,QScrollArea,QVBoxLayout,QMainWindow)
- from PyQt5.QtGui import QIcon,QPainter, QColor, QPen,QPixmap, QPalette,QBrush
- from PyQt5.QtCore import *
- class LAB3(QWidget):
- def __init__(self):
- super().__init__()
- self.qwa = 0
- self.he = 300
- self.wh = 750
- self.initUI()
- def init_analyze(self):
- try:
- self.qwa = 1
- def manhet(x_l,n,x_p,k):
- sum = 0
- sum += abs(x_l[n][0]-x_p[k][0])
- sum += abs(x_l[n][1]-x_p[k][1])
- sum += abs(x_l[n][2]-x_p[k][2])
- return sum
- def evk(x_l,n,x_p,k):
- evk = 0
- evk = m.sqrt( (x_l[n][0]-x_p[k][0])**2 + (x_l[n][1]-x_p[k][1])**2 + (x_l[n][2]-x_p[k][2])**2)
- return evk
- def nor():
- max_x = np.max(self.X[:, 0])
- max_y = np.max(self.X[:, 1])
- max_z = np.max(self.X[:, 2])
- min_x = np.min(self.X[:, 0])
- min_y = np.min(self.X[:, 1])
- min_z = np.min(self.X[:, 2])
- for n in range(len(self.X)):
- self.X[n][0] = (self.X[n][0] - min_x)/(max_x - min_x)
- self.X[n][1] = (self.X[n][1] - min_y) / (max_y - min_y)
- self.X[n][2] = (self.X[n][2] - min_z) / (max_z - min_z)
- self.X = np.around((self.X), 4)
- return
- def cov_man():
- tabl_cov_man = np.zeros((len(self.X),len(self.X)))
- k = 0
- while k != len(self.X):
- for i in range(k,len(self.X)):
- result = 0
- result += manhet(self.X, k, self.X, i)
- tabl_cov_man[k][i] = result
- tabl_cov_man[i][k] = result
- k += 1
- return tabl_cov_man
- def cov_evk():
- tabl_cov_evk = np.zeros((len(self.X),len(self.X)))
- k = 0
- while k != len(self.X):
- for i in range(k,len(self.X)):
- result = 0
- result += evk(self.X, k, self.X, i)
- tabl_cov_evk[k][i] = result
- tabl_cov_evk[i][k] = result
- k += 1
- return tabl_cov_evk
- def draw(spisok):
- cnt = 0
- for cluster in spisok:
- R = np.around((rn.uniform(0, 0.85)), 1)
- G = np.around((rn.uniform(0, 0.85)), 1)
- B = np.around((rn.uniform(0, 0.5)), 1)
- color = (R, G, B)
- cnt +=1
- for point in cluster:
- ax2.scatter(self.X[point, 0], self.X[point, 1], self.X[point, 2], s=75, c=color, marker='o', alpha=0.65)
- ax2.text(self.X[point, 0], self.X[point, 1], self.X[point, 2], str(cnt))
- plt.show()
- return
- def weight(Ox,Oy,Oz):
- self.X[:, 0] = self.X[:, 0] * Ox
- self.X[:, 1] = self.X[:, 1] * Oy
- self.X[:, 2] = self.X[:, 2] * Oz
- return
- def draw_init():
- ax.scatter(self.X[:, 0], self.X[:, 1], self.X[:, 2],s=75,marker='o', alpha=0.85)
- return
- def search_cluster(spisok,point=None,dl=None):
- if point!=None:
- for i in spi_1:
- if TABL[point][i] <= threshold:
- spisok.append(i)
- search_cluster(spisok)
- else:
- for k in spisok:
- for i in spi_1:
- if TABL[k][i] <= threshold:
- if i not in spisok:
- spisok.append(i)
- if dl == 1:
- for i in spisok:
- spi_1.remove(i)
- return spisok
- fig = plt.figure(figsize=(5.5, 8))
- ax = fig.add_subplot(211, projection='3d')
- ax.set_title('Исходные данные')
- ax2 = fig.add_subplot(212, projection='3d')
- ax2.set_title('Результат кластеризации')
- mngr = plt.get_current_fig_manager()
- ax.set_xlabel('X');ax2.set_xlabel('X');
- ax.set_ylabel('Y');ax2.set_ylabel('Y');
- ax.set_zlabel('Z');ax2.set_zlabel('Z');
- x = 800; y = 0;
- backend = matplotlib.get_backend()
- if backend == 'TkAgg':
- fig.canvas.manager.window.wm_geometry("+%d+%d" % (x, y))
- elif backend == 'WXAgg':
- fig.canvas.manager.window.SetPosition((x, y))
- else:
- # This works for QT and GTK
- # You can also use window.setGeometry
- fig.canvas.manager.window.move(x, y)
- self.X = np.array([[ 14.0, 3.0, 16.0], #1
- [ 2.0, 16.0, 1.0], #2
- [ -9.0, -4.0, 3.0], #3
- [ 18.0, 11.0, 11.0], #4
- [ 11.0, 15.0, -12.0], #5
- [ -1.0, 7.0, -32.0], #6
- [ 10.0, 2.0, 18.0], #7
- [ 7.0, 19.0, 2.0], #8
- [ -8.0, -5.0, 6.0], #9
- [ 15.0, 14.0, 18.0], #10
- [ 16.0, 16.0, -20.0], #11
- [ -3.0, 6.0, -33.0], #12
- [ 13.0, 6.0, 13.0], #13
- [ 9.0, 16.0, 4.0]]) #14
- TABL = []
- list_cluster = []
- spi_1 = []
- for i in range(len(self.X)):
- spi_1.append(i)
- draw_init()
- # Проверяем условтя
- if self.tt[0].checkState():
- weight(float(self.nm[21].text()), float(self.nm[35].text()), float(self.nm[49].text()))
- if self.tt[2].checkState():
- nor()
- threshold = float(self.nm[32].text())
- if threshold < 0:
- print('Неправильный ввод. Порог не должен быть меньше 0!')
- reply = QMessageBox.question(self, 'Message',"Ну это не серьезно", QMessageBox.Yes)
- return
- # 27 41
- if self.tt[27].checkState():
- TABL = cov_man()
- elif self.tt[41].checkState():
- TABL = cov_evk()
- while spi_1 != []:
- list_cluster.append(search_cluster([],rn.choice(spi_1),1))
- print('Tabl',TABL)
- print()
- print('Кластеры:\n',list_cluster)
- draw(list_cluster)
- except Exception:
- print('error')
- reply = QMessageBox.question(self, 'Message',"Что то пошло не так...", QMessageBox.Yes)
- def initUI(self):
- self.i = 0;
- palette = QPalette()
- self.palettem = QPalette()
- self.setPalette(palette)
- self.time = 0;
- self.i = 0;
- self.horizontalLayout = QVBoxLayout(self)
- self.scrollArea = QScrollArea(self)
- self.scrollArea.setWidgetResizable(True)
- self.scrollAreaWidgetContents = QWidget()
- self.scrollArea.setFixedHeight(self.he)
- self.scrollArea.setFixedWidth(self.wh)
- self.horizontalLayout_2 = QHBoxLayout(self.scrollAreaWidgetContents)
- self.grid = QGridLayout()
- self.horizontalLayout_2.addLayout(self.grid)
- self.scrollArea.setWidget(self.scrollAreaWidgetContents)
- h = 10; x_l = 7
- names = [ 't00Веса', ' 01', 't02Нормирование',' 03', ' 04Порог', ' 05', ' 06 Метод',
- ' 07', ' 08', ' 09', ' 10', ' 11', ' 12', ' 13Рассчета расстояний',
- ' 14X:', ' 15', ' 16', ' 17', ' 18', ' 19', ' 20',
- '211.0', ' 22', ' 23', ' 24', ' 25', ' 26', 't27Манхетонский метод',
- ' 28Y:', ' 29', ' 30Хз', ' 31', '3210.45', ' 33', ' 34',
- '351.0', ' 36', ' 37', ' 38', ' 39', ' 40', 't41Метод Евклида',
- ' 42Z:', ' 43', ' 44', ' 45', ' 46', ' 47', ' 48',
- '491.0', ' 50', ' 51', ' 52', ' 53', ' 54', ' 55',
- ' 56', ' 57', ' 58', ' 59', ' 60', ' 61', ' 62',
- ' 63', ' 64', ' 65', 'b66Запуск кластеризации',' 67',' 68',' 69', ]
- positions = [(i,j) for i in range(h) for j in range(x_l)]
- ps = 0
- self.nm = names
- self.lb = [self.lb for self.lb in range(0,len(names))]
- self.tt = [self.tt for self.tt in range(0,len(names))]
- for position, name in zip(positions, names):
- if name[0] == ' ':
- self.lb[ps] = QLabel(name[3:])
- self.grid.addWidget(self.lb[ps], *position)
- self.lb[ps].setAlignment(Qt.AlignCenter)
- if self.lb[ps].text() != '':
- self.lb[ps].setFixedWidth(150)
- else:
- self.lb[ps].setFixedWidth(10)
- ps =ps+1
- elif name[0] == 'b':
- self.nm[ps] = QPushButton(name[3:])
- self.grid.addWidget(self.nm[ps] ,8,0,3,7)
- self.nm[ps].setStyleSheet("background-color: red")
- ps =ps+1
- elif name[0] == 't':
- self.tt[ps] = QCheckBox(name[3:])
- self.grid.addWidget(self.tt[ps], *position)
- ps=ps+1
- else:
- self.nm[ps] = QLineEdit(name[2:])
- self.grid.addWidget(self.nm[ps], *position)
- self.nm[ps].setFixedWidth(150)
- self.nm[ps].setAlignment(Qt.AlignCenter)
- ps=ps+1
- self.tt[2].animateClick(200)
- self.tt[27].animateClick(600)
- self.move(10, 150)
- self.rej = 0
- self.tt[0].stateChanged.connect(self.lsnu)
- self.tt[27].stateChanged.connect(self.ls)
- self.tt[41].stateChanged.connect(self.lstw)
- self.tt[2].stateChanged.connect(self.textnorm)
- self.nm[66].clicked.connect(lambda: self.init_analyze())
- self.setWindowTitle('Кластерный анализ')
- self.setWindowIcon(QIcon('bg.png'))
- self.setFixedSize(self.wh,self.he)
- self.show()
- app.exec_()
- def ls(self,state):
- if state == Qt.Checked:
- self.rej = 1
- if self.tt[41].checkState():
- self.tt[41].click()
- def lsnu(self,state):
- if state == Qt.Checked:
- self.nm[32].setText(str(round(float(self.nm[32].text())+float(10.0),2)))
- if (self.tt[2].checkState()):
- self.tt[2].click()
- def textnorm(self,state):
- if state == Qt.Checked:
- self.lb[30].setText('Нормировать')
- if self.tt[0].checkState():
- self.tt[0].click()
- self.nm[32].setText(str(round(float(self.nm[32].text())-float(10.0),2)))
- else:
- self.lb[30].setText('Не нормировать')
- def lstw(self,state):
- if state == Qt.Checked:
- self.rej = 2
- if self.tt[27].checkState():
- self.tt[27].click()
- def closeEvent(self, event):
- reply = QMessageBox.question(self, 'А он такой...',
- "Я не могу работать в таких условиях!", QMessageBox.No |
- QMessageBox.Yes, QMessageBox.Yes)
- if reply == QMessageBox.Yes:
- sys.exit(0)
- event.accept()
- else:
- event.ignore()
- if __name__ == '__main__':
- app = QApplication(sys.argv)
- ex = LAB3()
- sys.exit(app.exec_())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement