加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
MainWindow.py 12.49 KB
一键复制 编辑 原始数据 按行查看 历史
Rroscha 提交于 2022-01-02 21:16 . Rroscha
from Software_Problem7 import Ui_MainWindow
from PyQt5 import QtCore, QtGui, QtWidgets
import PyQt5.QtCore as PQC
import sys
import re
import os
import threading
import time
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import numpy as np
import seaborn as sns
import matplotlib
matplotlib.use("Qt5Agg") # 声明使用QT5
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
from PyQt5 import sip
from ToolHelper.DataProcess import CDataProcess
__dataProcess = 0
class CThreadStop:
isThreadStop = False
def terminateThread(thread):
thread.isThreadStop = True
time.sleep(0.5)
thread.isThreadStop = False
class CFigureDataProcess(FigureCanvas):
def __init__(self,
dataProcess_,
width=3, height=5, dpi=100):
self.m_DataProcess = dataProcess_
self.fSize = (width, height)
self.dpi = 100
# 第一步:创建一个创建Figure
self.fig = Figure(figsize=(width, height), dpi=dpi)
# 第二步:在父类中激活Figure窗口
super(CFigureDataProcess, self).__init__(self.fig) # 此句必不可少,否则不能显示图形
# 第三步:创建一个子图,用于绘制图形用,111表示子图编号,如matlab的subplot(1,1,1)
self.axes = self.fig.add_subplot(111)
# self.axes = 0
# 第四步:就是画图,【可以在此类中画,也可以在其它类中画】
'''
1.
'''
def getVehicleDensity_Paint(self, beginningTime):
# self.axes.clear()
# plt.cla()
# self.axes = self.fig.add_subplot(111)
gapNumbers = 10
self.m_DataProcess.getVehicleDensity_Internal(beginningTime)
# paint
Map41Array = np.array(self.m_DataProcess.m_Map41)
# fig, axes = plt.subplots(figsize=(6, 8))
# plt.xticks([]) # 去掉横坐标值
# plt.yticks([]) # 去掉纵坐标值
# axes.set_xlabel('Freeway X', fontsize=24) # 设置x轴名称
# axes.set_ylabel('Freeway Y', fontsize=24) # 设置y轴名称
# cmap = sns.cubehelix_palette(start = 0, rot = np.max(Map41Array), gamma=0.8, as_cmap = True)
sns.heatmap(Map41Array,
linewidths=np.max(Map41Array) / gapNumbers,
ax=self.axes, vmax=np.max(Map41Array), vmin=0, cmap='rainbow').invert_yaxis() # Map41Array reverse to set bottom at bottom
'''
2
'''
def getVehicleTrack_Paint(self, vehicleID):
# self.axes.clear()
maxV = 150 * 1000 / 3600 # 150km/h ==> m/s
xMax = 3.75 * 8
yMax = 503
vehicle = self.m_DataProcess.getVehicleTrack_Internal(vehicleID)
# Paint
# array
x = np.array(vehicle['Local_X']) # x coordinate
y = np.array(vehicle['Local_Y']) # y coordinate
v = np.array(vehicle['v_Vel']) # velocity
# Now I utilize v to calculate corresponding colors and sizes of scatter
length = len(x)
colors = v / maxV # Normalize
sizes = v / maxV * 50
# fig = plt.figure(figsize=(6, 8))
# ax1 = fig.add_subplot(1, 1, 1)
self.axes.axis([-1, xMax, 0, yMax])
self.axes.scatter(x, y, s=sizes, c=colors, alpha=0.8)
self.axes.set_xlabel('Local_X')
self.axes.set_ylabel('Local_Y')
self.axes.set_title('Track and Velocity thermal map')
# Paint road
self.axes.plot([0, 0], [0, 503], color='k', linewidth=3, linestyle='-')
for i in range(5):
self.axes.plot([3.75 * (i + 1), 3.75 * (i + 1)], [0, 503], color='k', linewidth=3, linestyle='--')
# The rightest road
self.axes.plot([3.75 * 6, 3.75 * 6], [0, 170], color='teal', linewidth=3, linestyle='--')
self.axes.plot([3.75 * 6, 3.75 * 6], [270, 503], color='teal', linewidth=3, linestyle='--')
# The turnoff
self.axes.plot([3.75 * 6, 3.75 * 7.5], [140, 12], color='darkorange', linewidth=3, linestyle='-')
self.axes.plot([3.75 * 6, 3.75 * 7.5], [270, 152], color='darkorange', linewidth=3, linestyle='-')
# plt.show()
'''
3.
'''
def getAverageVelocity_Paint(self, time):
# self.axes.clear()
maxV = 150 * 1000 / 3600 # 150km/h ==> m/s
gapNumbers = 15
self.m_DataProcess.getAverageVelocity_Internal(time)
# paint
Map43Array = np.array(self.m_DataProcess.m_Map43)
# fig, axes = plt.subplots(figsize=(6, 8))
sns.heatmap(Map43Array,
linewidths=maxV / gapNumbers,
ax=self.axes, vmax=maxV, vmin=0,
cmap='rainbow').invert_yaxis() # Map43Array reverse to set bottom at bottom
class WorkThread(QtCore.QThread):
m_signal43 = PQC.pyqtSignal(int)
def __init__(self, threadID, name, MainWin, beginningTime, isThreadStop):
super(WorkThread, self).__init__()
self.threadID = threadID
self.name = name
self.MainWin = MainWin
self.beginningTime = beginningTime
self.isThreadStop = isThreadStop
def run(self):
print("线程开始:" + self.name)
# global __isThreadStop
# __isThreadStop = False
i = 0
# isLoop = True
while self.isThreadStop.isThreadStop == False:
# global __isThreadStop
# k = 0
# isLoop = not __isThreadStop
if i >= 300 or self.isThreadStop.isThreadStop == True:
break
self.m_signal43.emit(self.beginningTime + i)
time.sleep(0.2)
i += 2
print("线程结束:" + self.name)
class CMainWindow(QtWidgets.QMainWindow):
# Initialize
def __init__(self):
QtWidgets.QMainWindow.__init__(self)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.m_dataProcess = 0
# self.m_DataProcess = 0
# Fixed Size
self.setFixedSize(self.width(), self.height())
# Regression Expression
regExp4Time = QtCore.QRegExp("(^[0-9]:[0-5][0-9])(.[0-9])?$|(^1[0-4]:[0-5][0-9])(.[0-9])?$|(^15:00)(.0)?$")
regExp4VehicleID = QtCore.QRegExp("^[0-9]{0,4}") # {0,3} can't contain space
self.ui.m_lineEdit_1.setValidator(QtGui.QRegExpValidator(regExp4Time, self))
self.ui.m_lineEdit_2.setValidator(QtGui.QRegExpValidator(regExp4VehicleID, self))
self.ui.m_lineEdit_3.setValidator(QtGui.QRegExpValidator(regExp4Time, self))
# self.m_signal43 = PQC.pyqtSignal(int)
# self.m_signal43.connect(self.paintAveVelocity)
self.cwd = os.getcwd() # Get cwd
self.isThreadStop = CThreadStop()
self.thread = None
'''Figure'''
# 第五步:定义MyFigure类的一个实例
self.fig = 0 # CFigureDataProcess()
# self.gridlayout = 0
# self.scene = QGraphicsScene() # 创建一个场景
# self.ui.m_GraphicView.setScene(self.scene) # 将创建添加到图形视图显示窗口
# self.ui.m_GraphicView.show() # 显示
self.gridlayout = QGridLayout(self.ui.m_GroupBox) # 继承容器groupBox
'''
The following section is signal and slot.
'''
self.ui.m_actionExit.triggered.connect(lambda: self.applicationExit()) # must add lambda
self.ui.m_Quit.clicked.connect(self.applicationExit) # The function here can not append '()'
self.ui.m_LoadData.clicked.connect(self.loadData)
self.ui.m_Activate_1.clicked.connect(self.activate1)
self.ui.m_Activate_2.clicked.connect(self.activate2)
self.ui.m_Activate_3.clicked.connect(self.activate3)
# Slot functions
# Exit
def applicationExit(self):
sys.exit(0)
def loadData(self):
print("Hello World!\r\n")
fileName, filetype = QtWidgets.QFileDialog. \
getOpenFileName(self,
'I-80 CSV文件选取',
self.cwd, # Beginning Path
"CSV Files (*.csv)") # 设置文件扩展名过滤,用双分号间隔
if len(fileName) == 0:
# print("\n取消选择")
return
print(fileName)
terminateThread(self.isThreadStop)
if self.gridlayout.count() > 0:
self.gridlayout.removeWidget(self.fig)
sip.delete(self.fig)
# 将fileName load至Canvas中
__dataProcess = CDataProcess(fileName)
self.m_dataProcess = __dataProcess
self.fig = CFigureDataProcess(__dataProcess)
# self.scene.addWidget(self.fig) # 将图形元素添加到场景中
def activate1(self):
# print("Hello World!\r\n")
stringValue = self.ui.m_lineEdit_1.text()
if stringValue is "" or self.fig == 0:
QtWidgets.QMessageBox.information(self, 'Error', 'Input Error or No Data')
return
terminateThread(self.isThreadStop) # Terminate work thread
intValueList = self.stringTransfertoTime(stringValue)
intValue = intValueList[0] * 60 * 10 + intValueList[1] * 10 + intValueList[2]
print('1 intValue: %d' % intValue)
# Invoke corresponding function
if self.gridlayout.count() > 0:
self.gridlayout.removeWidget(self.fig)
sip.delete(self.fig)
self.fig = CFigureDataProcess(self.m_dataProcess)
self.fig.getVehicleDensity_Paint(intValue)
self.gridlayout.addWidget(self.fig, 0, 1)
# self.gridlayout.removeWidget(self.fig)
# self.scene.addWidget(self.fig) # 将图形元素添加到场景中
#
def activate2(self):
# print("Hello World!\r\n")
stringValue = self.ui.m_lineEdit_2.text()
if stringValue is "" or self.fig == 0:
QtWidgets.QMessageBox.information(self, 'Error', 'Input Error or No Data')
return
terminateThread(self.isThreadStop)
intValue = int(stringValue)
print('2 intValue: %d' % intValue)
# Invoke corresponding function
if self.gridlayout.count() > 0:
self.gridlayout.removeWidget(self.fig)
sip.delete(self.fig)
self.fig = CFigureDataProcess(self.m_dataProcess)
self.fig.getVehicleTrack_Paint(intValue)
self.gridlayout.addWidget(self.fig, 0, 1)
# self.scene.addWidget(self.fig) # 将图形元素添加到场景中
# self.ui.m_GraphicView.show() # 显示
def activate3(self):
# print("Hello World!\r\n")
stringValue = self.ui.m_lineEdit_3.text()
if stringValue is "" or self.fig == 0:
QtWidgets.QMessageBox.information(self, 'Error', 'Input Error or No Data')
return
terminateThread(self.isThreadStop)
if self.gridlayout.count() > 0:
self.gridlayout.removeWidget(self.fig)
sip.delete(self.fig)
self.fig = CFigureDataProcess(self.m_dataProcess)
intValueList = self.stringTransfertoTime(stringValue)
intValue = intValueList[0] * 60 * 10 + intValueList[1] * 10 + intValueList[2]
print('3 intValue: %d' % intValue)
# Invoke corresponding function
self.thread = WorkThread(3, 'WorkThread', self, intValue, self.isThreadStop)
self.thread.m_signal43.connect(self.paintAveVelocity)
self.thread.start()
def paintAveVelocity(self, time_):
# Invoke corresponding function
print(time_)
if self.gridlayout.count() > 0:
self.gridlayout.removeWidget(self.fig)
sip.delete(self.fig)
self.fig = CFigureDataProcess(self.m_dataProcess)
self.fig.getAverageVelocity_Paint(time_)
self.gridlayout.addWidget(self.fig, 0, 1)
# time.sleep(0.3)
def stringTransfertoTime(self, stringValue):
valueList = re.findall(r'\d+', stringValue)
intValueMin = int(valueList[0])
intValueSec = 0
intValueLast = 0 # I don't know how to say 0.1s
if len(valueList) is 2:
intValueSec = int(valueList[1])
elif len(valueList) is 3:
intValueSec = int(valueList[1])
intValueLast = int(valueList[2])
return [intValueMin, intValueSec, intValueLast]
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化