Advertisement
Guest User

Untitled

a guest
Nov 23rd, 2017
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 13.02 KB | None | 0 0
  1. #!/usr/bin/python3
  2. # -*- coding: utf-8 -*-
  3.  
  4. import time,sys
  5. import math as m
  6. import pyperclip as x_p
  7. import numpy as np
  8. import random as rn
  9. import matplotlib
  10. from mpl_toolkits.mplot3d import Axes3D
  11. import matplotlib.pyplot as plt
  12. from PyQt5.QtWidgets import QTableView
  13. from PyQt5.QtCore import Qt
  14. from PyQt5.QtWidgets import (QWidget, QGridLayout,QHBoxLayout,
  15.     QPushButton, QApplication,QLineEdit,QCheckBox, QLabel,QMessageBox,QScrollArea,QVBoxLayout,QMainWindow)
  16. from PyQt5.QtGui import QIcon,QPainter, QColor, QPen,QPixmap, QPalette,QBrush
  17. from PyQt5.QtCore import *
  18.  
  19. class LAB3(QWidget):
  20.  
  21.     def __init__(self):
  22.         super().__init__()
  23.         self.qwa = 0
  24.         self.he = 300
  25.         self.wh = 750
  26.         self.initUI()
  27.     def init_analyze(self):
  28.         try:
  29.             self.qwa = 1
  30.             def manhet(x_l,n,x_p,k):
  31.                 sum = 0
  32.                 sum += abs(x_l[n][0]-x_p[k][0])
  33.                 sum += abs(x_l[n][1]-x_p[k][1])
  34.                 sum += abs(x_l[n][2]-x_p[k][2])
  35.                 return sum
  36.  
  37.             def evk(x_l,n,x_p,k):
  38.                 evk = 0
  39.                 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)    
  40.                 return evk
  41.  
  42.             def nor():
  43.                 max_x = np.max(self.X[:, 0])
  44.                 max_y = np.max(self.X[:, 1])
  45.                 max_z = np.max(self.X[:, 2])
  46.                 min_x = np.min(self.X[:, 0])
  47.                 min_y = np.min(self.X[:, 1])
  48.                 min_z = np.min(self.X[:, 2])
  49.                 for n in range(len(self.X)):
  50.                     self.X[n][0] = (self.X[n][0] - min_x)/(max_x - min_x)
  51.                     self.X[n][1] = (self.X[n][1] - min_y) / (max_y - min_y)
  52.                     self.X[n][2] = (self.X[n][2] - min_z) / (max_z - min_z)
  53.                 self.X = np.around((self.X), 4)
  54.                 return
  55.  
  56.             def cov_man():
  57.                 tabl_cov_man = np.zeros((len(self.X),len(self.X)))
  58.                 k = 0
  59.                 while k != len(self.X):
  60.                     for i in range(k,len(self.X)):
  61.                         result = 0
  62.                         result += manhet(self.X, k, self.X, i)
  63.                         tabl_cov_man[k][i] = result
  64.                         tabl_cov_man[i][k] = result
  65.                     k += 1
  66.                 return tabl_cov_man
  67.  
  68.             def cov_evk():
  69.                 tabl_cov_evk = np.zeros((len(self.X),len(self.X)))
  70.                 k = 0
  71.                 while k != len(self.X):
  72.                     for i in range(k,len(self.X)):
  73.                         result = 0
  74.                         result += evk(self.X, k, self.X, i)
  75.                         tabl_cov_evk[k][i] = result
  76.                         tabl_cov_evk[i][k] = result
  77.                     k += 1
  78.                 return tabl_cov_evk
  79.  
  80.             def draw(spisok):
  81.                 cnt = 0
  82.                 for cluster in spisok:
  83.                     R = np.around((rn.uniform(0, 0.85)), 1)
  84.                     G = np.around((rn.uniform(0, 0.85)), 1)
  85.                     B = np.around((rn.uniform(0, 0.5)), 1)
  86.                     color = (R, G, B)
  87.                     cnt +=1
  88.                     for point in cluster:
  89.                         ax2.scatter(self.X[point, 0], self.X[point, 1], self.X[point, 2], s=75, c=color, marker='o', alpha=0.65)
  90.                         ax2.text(self.X[point, 0], self.X[point, 1], self.X[point, 2], str(cnt))
  91.  
  92.                 plt.show()
  93.                 return
  94.            
  95.             def weight(Ox,Oy,Oz):
  96.                 self.X[:, 0] = self.X[:, 0] * Ox
  97.                 self.X[:, 1] = self.X[:, 1] * Oy
  98.                 self.X[:, 2] = self.X[:, 2] * Oz
  99.                 return
  100.  
  101.             def draw_init():
  102.                 ax.scatter(self.X[:, 0], self.X[:, 1], self.X[:, 2],s=75,marker='o', alpha=0.85)
  103.                 return
  104.  
  105.             def search_cluster(spisok,point=None,dl=None):
  106.                 if point!=None:
  107.                     for i in spi_1:
  108.                         if TABL[point][i] <= threshold:
  109.                             spisok.append(i)
  110.                     search_cluster(spisok)
  111.                 else:
  112.                     for k in spisok:
  113.                         for i in spi_1:
  114.                             if TABL[k][i] <= threshold:
  115.                                 if i not in spisok:
  116.                                     spisok.append(i)
  117.                 if dl == 1:
  118.                     for i in spisok:
  119.                         spi_1.remove(i)
  120.                 return spisok
  121.             fig = plt.figure(figsize=(5.5, 8))
  122.             ax = fig.add_subplot(211, projection='3d')
  123.             ax.set_title('Исходные данные')
  124.             ax2 = fig.add_subplot(212, projection='3d')
  125.             ax2.set_title('Результат кластеризации')
  126.             mngr = plt.get_current_fig_manager()
  127.            
  128.             ax.set_xlabel('X');ax2.set_xlabel('X');
  129.             ax.set_ylabel('Y');ax2.set_ylabel('Y');
  130.             ax.set_zlabel('Z');ax2.set_zlabel('Z');
  131.  
  132.             x = 800; y = 0;
  133.             backend = matplotlib.get_backend()
  134.             if backend == 'TkAgg':
  135.                 fig.canvas.manager.window.wm_geometry("+%d+%d" % (x, y))
  136.             elif backend == 'WXAgg':
  137.                 fig.canvas.manager.window.SetPosition((x, y))
  138.             else:
  139.                 # This works for QT and GTK
  140.                 # You can also use window.setGeometry
  141.                 fig.canvas.manager.window.move(x, y)
  142.  
  143.             self.X = np.array([[ 14.0,   3.0,   16.0], #1
  144.                               [   2.0,  16.0,    1.0],  #2
  145.                               [  -9.0,  -4.0,    3.0],  #3
  146.                               [  18.0,  11.0,   11.0],  #4
  147.                               [  11.0,  15.0,  -12.0],  #5
  148.                               [  -1.0,   7.0,  -32.0],  #6
  149.                               [  10.0,   2.0,   18.0],  #7
  150.                               [   7.0,  19.0,    2.0],  #8
  151.                               [  -8.0,  -5.0,    6.0],  #9
  152.                               [  15.0,  14.0,   18.0],  #10
  153.                               [  16.0,  16.0,  -20.0],  #11
  154.                               [  -3.0,   6.0,  -33.0],  #12
  155.                               [  13.0,   6.0,   13.0],  #13
  156.                               [   9.0,  16.0,   4.0]]) #14
  157.             TABL = []
  158.             list_cluster = []
  159.             spi_1 = []
  160.             for i in range(len(self.X)):
  161.                 spi_1.append(i)
  162.             draw_init()
  163.             # Проверяем условтя
  164.             if self.tt[0].checkState():
  165.                 weight(float(self.nm[21].text()), float(self.nm[35].text()), float(self.nm[49].text()))
  166.             if self.tt[2].checkState():
  167.                 nor()
  168.             threshold = float(self.nm[32].text())
  169.             if threshold < 0:
  170.                 print('Неправильный ввод. Порог не должен быть меньше 0!')
  171.                 reply = QMessageBox.question(self, 'Message',"Ну это не серьезно", QMessageBox.Yes)
  172.                 return
  173.             # 27 41
  174.             if  self.tt[27].checkState():
  175.                 TABL = cov_man()
  176.             elif self.tt[41].checkState():
  177.                 TABL = cov_evk()
  178.  
  179.             while spi_1 != []:
  180.                 list_cluster.append(search_cluster([],rn.choice(spi_1),1))
  181.                    
  182.             print('Tabl',TABL)
  183.             print()
  184.             print('Кластеры:\n',list_cluster)
  185.             draw(list_cluster)
  186.         except Exception:
  187.             print('error')
  188.             reply = QMessageBox.question(self, 'Message',"Что то пошло не так...", QMessageBox.Yes)
  189.  
  190.     def initUI(self):
  191.         self.i = 0;
  192.         palette    = QPalette()
  193.         self.palettem    = QPalette()
  194.         self.setPalette(palette)
  195.         self.time = 0;
  196.         self.i = 0;
  197.         self.horizontalLayout   = QVBoxLayout(self)
  198.         self.scrollArea         = QScrollArea(self)
  199.         self.scrollArea.setWidgetResizable(True)
  200.         self.scrollAreaWidgetContents = QWidget()
  201.         self.scrollArea.setFixedHeight(self.he)
  202.         self.scrollArea.setFixedWidth(self.wh)
  203.         self.horizontalLayout_2 = QHBoxLayout(self.scrollAreaWidgetContents)
  204.         self.grid = QGridLayout()
  205.         self.horizontalLayout_2.addLayout(self.grid)
  206.         self.scrollArea.setWidget(self.scrollAreaWidgetContents)
  207.  
  208.         h = 10; x_l = 7
  209.         names = [   't00Веса', ' 01',   't02Нормирование',' 03', ' 04Порог',    ' 05',    ' 06 Метод',                  
  210.                     ' 07',     ' 08',   ' 09',            ' 10', ' 11',         ' 12',    ' 13Рассчета расстояний',                  
  211.                     ' 14X:',   ' 15',   ' 16',            ' 17', ' 18',         ' 19',    ' 20',                  
  212.                     '211.0',   ' 22',   ' 23',            ' 24', ' 25',         ' 26',    't27Манхетонский метод',                  
  213.                     ' 28Y:',   ' 29',   ' 30Хз',          ' 31', '3210.45',     ' 33',    ' 34',                  
  214.                     '351.0',   ' 36',   ' 37',            ' 38', ' 39',         ' 40',    't41Метод Евклида',                  
  215.                     ' 42Z:',   ' 43',   ' 44',            ' 45', ' 46',         ' 47',    ' 48',                  
  216.                     '491.0',   ' 50',   ' 51',            ' 52', ' 53',         ' 54',    ' 55',                  
  217.                     ' 56',     ' 57',   ' 58',            ' 59', ' 60',         ' 61',    ' 62',                  
  218.                     ' 63',     ' 64',   ' 65',            'b66Запуск кластеризации',' 67',' 68',' 69',  ]
  219.         positions = [(i,j) for i in range(h) for j in range(x_l)]
  220.         ps = 0
  221.         self.nm = names
  222.         self.lb = [self.lb for self.lb in range(0,len(names))]
  223.         self.tt = [self.tt for self.tt in range(0,len(names))]
  224.         for position, name in zip(positions, names):
  225.             if name[0] == ' ':
  226.                 self.lb[ps] = QLabel(name[3:])
  227.                 self.grid.addWidget(self.lb[ps], *position)
  228.                 self.lb[ps].setAlignment(Qt.AlignCenter)
  229.                 if self.lb[ps].text() != '':
  230.                     self.lb[ps].setFixedWidth(150)
  231.                 else:
  232.                     self.lb[ps].setFixedWidth(10)
  233.                 ps =ps+1    
  234.             elif name[0] == 'b':
  235.                 self.nm[ps] = QPushButton(name[3:])
  236.  
  237.                 self.grid.addWidget(self.nm[ps] ,8,0,3,7)
  238.                 self.nm[ps].setStyleSheet("background-color: red")
  239.                 ps =ps+1
  240.             elif name[0] == 't':
  241.                 self.tt[ps] = QCheckBox(name[3:])
  242.                 self.grid.addWidget(self.tt[ps], *position)
  243.                 ps=ps+1
  244.  
  245.             else:
  246.                 self.nm[ps] = QLineEdit(name[2:])
  247.                 self.grid.addWidget(self.nm[ps], *position)
  248.                 self.nm[ps].setFixedWidth(150)
  249.                 self.nm[ps].setAlignment(Qt.AlignCenter)
  250.                 ps=ps+1
  251.  
  252.         self.tt[2].animateClick(200)
  253.         self.tt[27].animateClick(600)
  254.         self.move(10, 150)
  255.         self.rej = 0
  256.         self.tt[0].stateChanged.connect(self.lsnu)
  257.         self.tt[27].stateChanged.connect(self.ls)
  258.         self.tt[41].stateChanged.connect(self.lstw)
  259.         self.tt[2].stateChanged.connect(self.textnorm)
  260.         self.nm[66].clicked.connect(lambda: self.init_analyze())
  261.         self.setWindowTitle('Кластерный анализ')
  262.         self.setWindowIcon(QIcon('bg.png'))
  263.         self.setFixedSize(self.wh,self.he)
  264.         self.show()
  265.        
  266.         app.exec_()
  267.  
  268.     def ls(self,state):
  269.         if state == Qt.Checked:
  270.             self.rej = 1
  271.             if self.tt[41].checkState():
  272.                 self.tt[41].click()  
  273.  
  274.     def lsnu(self,state):
  275.         if state == Qt.Checked:
  276.             self.nm[32].setText(str(round(float(self.nm[32].text())+float(10.0),2)))
  277.             if (self.tt[2].checkState()):
  278.                 self.tt[2].click()  
  279.     def textnorm(self,state):
  280.          
  281.         if state == Qt.Checked:
  282.             self.lb[30].setText('Нормировать')
  283.             if self.tt[0].checkState():
  284.                 self.tt[0].click()  
  285.             self.nm[32].setText(str(round(float(self.nm[32].text())-float(10.0),2)))
  286.         else:
  287.             self.lb[30].setText('Не нормировать')
  288.  
  289.     def lstw(self,state):
  290.         if state == Qt.Checked:
  291.             self.rej = 2
  292.             if self.tt[27].checkState():
  293.                 self.tt[27].click()      
  294.  
  295.     def closeEvent(self, event):
  296.         reply = QMessageBox.question(self, 'А он такой...',
  297.             "Я не могу работать в таких условиях!", QMessageBox.No |
  298.             QMessageBox.Yes, QMessageBox.Yes)
  299.  
  300.         if reply == QMessageBox.Yes:
  301.             sys.exit(0)
  302.             event.accept()
  303.         else:
  304.             event.ignore()
  305. if __name__ == '__main__':
  306.     app = QApplication(sys.argv)
  307.     ex = LAB3()
  308.     sys.exit(app.exec_())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement