def addSeries( self, _x2idx: typing.Dict, _idx2x: list, _chart: QChart, _axis_x: QValueAxis, _axis_y: QValueAxis ): bar_set = QBarSet(self.name) tmp_dict = dict(zip(self.x_list, self.y_list)) for k in _idx2x: if k in tmp_dict.keys(): bar_set.append(tmp_dict[k]) else: bar_set.append(0) if self.color is not None: bar_set.setColor(self.color) bar_series = QBarSeries() bar_series.append(bar_set) _chart.addSeries(bar_series) _chart.setAxisX(_axis_x, bar_series) _chart.setAxisY(_axis_y, bar_series) if self.show_value: self.createShow()
def agg_results(self) -> None: """ Display results in the corresponding chart view. :return: nothing :rtype: None """ # aggregate "other" abundances if self.cbAggResults.isChecked(): agg_abundance = ( self.results.iloc[self.sbAggResults.value():].sum()) agg_abundance["glycoform"] = self.tr("other") self.results_agg = ( self.results.iloc[:self.sbAggResults.value()].append( agg_abundance, ignore_index=True)) else: self.results_agg = self.results # extract x- and y-values from series x_values = list(self.results_agg["glycoform"].str.split(" or").str[0]) y_values_obs = list(self.results_agg["abundance"]) y_values_cor = list(self.results_agg["corr_abundance"]) # assemble the chart bar_set_obs = QBarSet(self.tr("observed")) bar_set_obs.append(y_values_obs) bar_set_obs.setColor(QColor("#225ea8")) bar_set_obs.hovered.connect(self.update_results_label) bar_set_cor = QBarSet(self.tr("corrected")) bar_set_cor.append(y_values_cor) bar_set_cor.setColor(QColor("#41b6c4")) bar_set_cor.hovered.connect(self.update_results_label) bar_series = QBarSeries() bar_series.append([bar_set_obs, bar_set_cor]) x_axis = QBarCategoryAxis() x_axis.append(x_values) x_axis.setTitleVisible(False) x_axis.setLabelsAngle(270) range_min = min( self.results_agg[["abundance", "corr_abundance"]].min().min(), 0) range_min = math.floor(range_min / 20) * 20 range_max = (self.results_agg[["abundance", "corr_abundance"]].max().max()) range_max = math.ceil(range_max / 20) * 20 tick_count = (range_max - range_min) // 20 + 1 y_axis = QValueAxis() y_axis.setRange(range_min, range_max) y_axis.setTickCount(tick_count) y_axis.setTitleText(self.tr("abundance")) y_axis.setLabelFormat("%d") chart = QChart() chart.addSeries(bar_series) chart.setAxisX(x_axis, bar_series) chart.setAxisY(y_axis, bar_series) chart.legend().setVisible(False) chart.setBackgroundRoundness(0) chart.layout().setContentsMargins(0, 0, 0, 0) chart.setMargins(QMargins(5, 5, 5, 5)) self.cvResults.setChart(chart)
class Menu(QMainWindow): default_title = "FaceNet" face_box = None face_reader = None # numpy_image is the desired image we want to display given as a numpy array. def __init__(self, numpy_image=None, opacity=1, start_position=(300, 300, 550, 500)): super().__init__() self.opacity = opacity self.drawing = False self.brushSize = 1 self.brushColor = Qt.red self.lastPoint = QPoint() self.total_snips = 0 self.title = Menu.default_title self.model_running = False self.box_x = None self.box_y = None self.box_w = None self.box_h = None self.box_drawn_can_start = False self.face_anger_digust = 0 self.face_happy = 0 self.face_neutral = 0 self.face_sadness = 0 self.face_surprise_fear = 0 self.face_lock = threading.Lock() self.face_confidence_level = numpy.zeros((1, 5)) self.face_confidence_entry_count = 0 self.emotion_set = None self.create_graph() self._timer = QTimer() self._timer.setInterval(33) self._timer.timeout.connect(self.calculate_emotion) self._timer.start() self._graph_timer = None self.face_model_process = None # self.face_model_process2 = None # self.face_model_process3 = None # self.face_model_process4 = None self.inputs_queue = Queue() self.outputs_queue = Queue() # New snip new_snip_action = QAction("Draw Box", self) new_snip_action.triggered.connect(self.__new_image_window) close_box = QAction('Close Box', self) close_box.triggered.connect(self.__close_box) run_program = QAction('start program', self) run_program.triggered.connect(self.__start_program) stop_program = QAction('stop program', self) stop_program.triggered.connect(self.__stop_program) self.toolbar = self.addToolBar('Exit') self.toolbar.addAction(new_snip_action) self.toolbar.addAction(close_box) self.toolbar.addAction(run_program) self.toolbar.addAction(stop_program) self.snippingTool = faceReader_draw_image.SnippingWidget(self) self.setGeometry(*start_position) # From the second initialization, both arguments will be valid self.image = QPixmap("background.PNG") self.show() def create_graph(self): self.emotion_set = QBarSet('Confidence Level') self.emotion_set.append([ self.face_anger_digust, self.face_happy, self.face_neutral, self.face_sadness, self.face_surprise_fear ]) series = QHorizontalBarSeries() series.append(self.emotion_set) chart = QChart() chart.addSeries(series) chart.setTitle('ReLuu FaceReader') chart.setAnimationOptions(QChart.SeriesAnimations) months = ('Angery and Disgusted', 'Happy', 'Neutral', 'Sadness', 'Fear and Surprise') axisY = QBarCategoryAxis() axisY.append(months) chart.addAxis(axisY, Qt.AlignLeft) series.attachAxis(axisY) axisX = QValueAxis() axisX.setMax(1.0) chart.addAxis(axisX, Qt.AlignBottom) series.attachAxis(axisX) axisX.applyNiceNumbers() chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) chartView = QChartView(chart) chartView.setRenderHint(QPainter.Antialiasing) self.setCentralWidget(chartView) def __new_image_window(self): self.snippingTool.start() def __create_box(self, x, y, w, h): Menu.face_box = faceReader_box.Box(x, y, w, h) self.box_x = x self.box_y = y self.box_w = w self.box_h = h self.box_drawn_can_start = True def __start_program(self): if self.box_drawn_can_start and not self.model_running: self._graph_timer = QTimer() self._graph_timer.setInterval(1000) self._graph_timer.timeout.connect(self.__graph) self._graph_timer.start() self.face_model_process = Process( target=model_worker, args=(self.inputs_queue, self.outputs_queue, self.box_x, self.box_y, self.box_w, self.box_h)) self.face_model_process.start() self.model_running = True self.inputs_queue.put("start") # self.face_model_process2 = Process(target=model_worker2, args=(self.inputs_queue, self.outputs_queue, # self.box_x, self.box_y, self.box_w, self.box_h)) # self.face_model_process2.start() # self.inputs_queue.put("start2") # self.face_model_process3 = Process(target=model_worker3, args=(self.inputs_queue, self.outputs_queue, # self.box_x, self.box_y, self.box_w, self.box_h)) # self.face_model_process3.start() # self.inputs_queue.put("start3") # self.face_model_process4 = Process(target=model_worker4, args=(self.inputs_queue, self.outputs_queue, # self.box_x, self.box_y, self.box_w, self.box_h)) # self.face_model_process4.start() # self.inputs_queue.put("start4") elif not self.box_drawn_can_start: print("---Cannot start program, box not drawn---") else: print("---model running___") def calculate_emotion(self): if not self.outputs_queue.empty(): self.face_lock.acquire() self.face_confidence_entry_count += 1 face_confidence_output = self.outputs_queue.get() self.face_confidence_level += face_confidence_output self.face_lock.release() def __stop_program(self): if self.face_model_process is not None: self.face_model_process.terminate() # self.face_model_process2.terminate() # self.face_model_process3.terminate() # self.face_model_process4.terminate() print("---closing model---") self.model_running = False self._graph_timer.stop() def __close_box(self): if Menu.face_box: self.__stop_program() Menu.face_box.close_window() self.box_drawn_can_start = False print("---closing box---") def __graph(self): self.face_lock.acquire() new_graph_value = self.face_confidence_level / self.face_confidence_entry_count print(str(new_graph_value)) self.face_anger_digust = new_graph_value[0][0] self.face_happy = new_graph_value[0][1] self.face_neutral = new_graph_value[0][2] self.face_sadness = new_graph_value[0][3] self.face_surprise_fear = new_graph_value[0][4] self.emotion_set.append([ self.face_anger_digust, self.face_happy, self.face_neutral, self.face_sadness, self.face_surprise_fear ]) self.face_confidence_level = numpy.zeros((1, 5)) self.face_confidence_entry_count = 0 self.face_lock.release() def paintEvent(self, event): painter = QPainter(self) rect = QRect(0, self.toolbar.height(), self.image.width(), self.image.height()) painter.drawPixmap(rect, self.image) def mousePressEvent(self, event): if event.button() == Qt.LeftButton: self.drawing = True self.lastPoint = event.pos() - QPoint(0, self.toolbar.height()) def mouseMoveEvent(self, event): if event.buttons() and Qt.LeftButton and self.drawing: painter = QPainter(self.image) painter.setPen( QPen(self.brushColor, self.brushSize, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) painter.drawLine(self.lastPoint, event.pos() - QPoint(0, self.toolbar.height())) self.lastPoint = event.pos() - QPoint(0, self.toolbar.height()) self.update() def mouseReleaseEvent2(self, event): if event.button == Qt.LeftButton: self.drawing = False # TODO exit application when we exit all windows def closeEvent(self, event): event.accept() @staticmethod def convert_numpy_img_to_qpixmap(np_img): height, width, channel = np_img.shape bytesPerLine = 3 * width return QPixmap( QImage(np_img.data, width, height, bytesPerLine, QImage.Format_RGB888).rgbSwapped())
import sys import numpy as np from PyQt5.QtWidgets import QApplication from PyQt5.QtChart import QChart, QChartView, QBarSet, QBarSeries, QBarCategoryAxis app = QApplication(sys.argv) chart = QChart() b_set = QBarSet("test") series = QBarSeries() b_set.append(np.arange(5, dtype=np.float64)) series.append(b_set) chart.addSeries(series) chart.createDefaultAxes() chart.setAnimationOptions(QChart.SeriesAnimations) axisX = QBarCategoryAxis() axisX.append((*"12345", )) chart.setAxisX(axisX, series) chartView = QChartView(chart) ##chartView.setRenderHint(QPainter.Antialiasing) chartView.show() app.exec_()
def draw(self): # 通过 UI 单选框的状态判断选项 if self.main_ui.radio_ip.isChecked(): plotCategory = 'IP' else: plotCategory = 'protocol' if self.main_ui.radio_packet.isChecked(): plotUnit = 'packet' else: plotUnit = 'length' # 根据选项调整 sql 查询语法 sql = ''' SELECT {0}, upload_{1} AS upload, download_{1} AS download FROM network_monitor.{0}_upload_download ORDER BY all_{1} DESC LIMIT {2};''' sql = sql.format(plotCategory, plotUnit, PLOT_NUMBER) sql_values = run_sql_with_result(sql) # 查询结果是 list 里面套 dict try: sql_values.reverse() # 如果 except 说明 sql_values 为空 except: self.removeAllSeries() # 删除掉已经绘制的图像 return if plotUnit == 'length': # 如果按包大小绘图,为了美观,需要调整单位和用于绘图的数据 max_value = 0 for i in sql_values: for j in ['download', 'upload']: max_value = max(max_value, i[j]) (unit, base) = speed2str(max_value) for i in sql_values: for j in ['download', 'upload']: i[j] /= base unit_str = ',单位:' + unit + 'B' else: unit_str = ',单位:包' # 每组创建两个柱状条 set0 = QBarSet('下载' + unit_str) set1 = QBarSet('上传' + unit_str) for i in range(len(sql_values)): # PyQt 的传入数据的语法,估计是跟 C++ 的 Qt 学的 set0 << sql_values[i]['download'] set1 << sql_values[i]['upload'] # 创建横向柱状条 series = QHorizontalBarSeries() series.append(set0) series.append(set1) # 添加Series self.removeAllSeries() self.addSeries(series) # 分类 categories = [x[plotCategory] for x in sql_values] # 分类 x 轴,注意 x 轴在横向柱状图中是竖着的轴 axis = QBarCategoryAxis() axis.append(categories) # 创建默认轴线 self.createDefaultAxes() # 替换默认y轴 self.setAxisY(axis, series) # 显示图例 # 显示图例 self.legend().setVisible(True) self.legend().setAlignment(Qt.AlignBottom)
def setupLayout(self): parentLayout = QVBoxLayout() parentLayout.setContentsMargins(20,20,20,20) buttonLayout = QHBoxLayout() # CREATE SERIAL COMMUNICATION CONNECT BUTTON self.connectButton = QPushButton("CONNECT") self.connectButton.setFixedSize(150, 40) self.connectButton.setCheckable(True) self.connectButton.setStyleSheet("QPushButton {background-color: #66BB6A; color: black; border-radius: 20px}" "QPushButton:hover {background-color: #4CAF50; color: black; border-radius: 20px}" "QPushButton:checked {background-color: #EF5350; color: white; border-radius: 20px}" "QPushButton:checked:hover {background-color: #F44336; color: white; border-radius: 20px}") # CREATE SENSORS CALIBRATION BUTTON self.calibrateButton = QPushButton("CALIBRATE") self.calibrateButton.setFixedSize(150, 40) self.calibrateButton.setStyleSheet("QPushButton {background-color: #E0E0E0; color: black; border-radius: 20px}" "QPushButton:hover {background-color: #BDBDBD; color: black; border-radius: 20px}" "QPushButton:pressed {background-color: #D5D5D5; color: black; border-radius: 20px}") # ADD BUTTONS TO HORIZONTAL LAYOUT buttonLayout.addWidget(self.connectButton, alignment = Qt.AlignLeft) buttonLayout.addWidget(self.calibrateButton, alignment = Qt.AlignRight) # CREATE BAR CHART TO DISPLAY SENSOR READINGS self.bars = QBarSet('Sensor Readings') self.bars.append([0 for i in range(5)]) self.chart = QChart() self.chart.setBackgroundRoundness(20) self.chart.layout().setContentsMargins(0, 0, 0, 0) self.series = QBarSeries() self.series.append(self.bars) self.chart.addSeries(self.series) self.chart.setTitle('Sensor Readings') # CREATE X-AXIS AS SENSOR LABELS xAxis = QBarCategoryAxis() labels = ["Sensor {}".format(i+1) for i in range(5)] xAxis.append(labels) # CREATE Y-AXIS AND SENSOR READINGS yAxis = QValueAxis() yAxis.setRange(-100, 100) yAxis.setTickCount(11) yAxis.setTitleText("Pressure (%)") # ADD AXES TO CHART self.chart.addAxis(xAxis, Qt.AlignBottom) self.chart.addAxis(yAxis, Qt.AlignLeft) self.chart.legend().setVisible(False) # ATTACH AXES TO SERIES self.series.attachAxis(xAxis) self.series.attachAxis(yAxis) # ADD CHART TO A VIEW chartView = QChartView(self.chart) labelLayout = QFrame() labelLayout.setStyleSheet("background-color: white; border-radius: 20px") layout1 = QVBoxLayout() labelLayout.setLayout(layout1) layout2 = QHBoxLayout() layout3 = QHBoxLayout() for i in range(5): label = QLabel("Sensor {}".format(i+1)) label.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) label.setStyleSheet("font-weight: bold;") layout2.addWidget(label) value = QLabel("0 mV") value.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) self.labelWidgets.append(value) layout3.addWidget(value) layout1.addLayout(layout2, 1) layout1.addLayout(layout3, 1) parentLayout.addLayout(buttonLayout) parentLayout.addWidget(chartView, 5) parentLayout.addWidget(labelLayout, 1) # LINK WIDGETS self.connectButton.clicked.connect(self.serialToggle) self.calibrateButton.clicked.connect(self.sensorCalibrate) self.setLayout(parentLayout)
def add_series_values(self, data: pd.DataFrame, is_init=False): self._stocks = data bar_red = QBarSet('red') bar_red.setColor(Qt.red) bar_green = QBarSet('green') bar_green.setColor(Qt.green) for _, stock in self._stocks.iterrows(): if stock['open'] < stock['close']: bar_red.append(stock['vol'] / self._vol_multiple) bar_green.append(0) else: bar_red.append(0) bar_green.append(stock['vol'] / self._vol_multiple) self._series.append(bar_red) self._series.append(bar_green) if not is_init: self._stocks = data self._category = self._stocks['trade_date'] axis_x = self._chart.axisX() axis_y = self._chart.axisY() axis_x.setCategories(self._category) max_p = self._stocks[[ 'vol', ]].stack().max() min_p = self._stocks[[ 'vol', ]].stack().min() axis_y.setRange(min_p / self._vol_multiple * 0.9, max_p / self._vol_multiple * 1.1) self._zero_value = (0, self._chart.axisY().min()) self._max_value = (len(self._chart.axisX().categories()), self._chart.axisY().max()) # 计算x轴单个cate的宽度,用来处理横线不能画到边界 self._cate_width = (self._max_point.x() - self._zero_point.x()) / len(self._category)
def analysisUI(self, smwui): btn_refresh = QPushButton('Refresh') btn_refresh.clicked.connect(smwui.update_chart) smwui.cb_targetAxis1 = QCheckBox('X : Horizontal action') smwui.cb_targetAxis1.setChecked(True) smwui.cb_targetAxis1.stateChanged.connect(smwui.update_chart) smwui.cb_targetAxis2 = QCheckBox('Y : Vertical action') smwui.cb_targetAxis2.setChecked(True) smwui.cb_targetAxis2.stateChanged.connect(smwui.update_chart) smwui.cb_targetAxis3 = QCheckBox('Z : Depth action') smwui.cb_targetAxis3.setChecked(True) smwui.cb_targetAxis3.stateChanged.connect(smwui.update_chart) smwui.cb_targetValue1 = QCheckBox('Head') smwui.cb_targetValue1.setChecked(True) smwui.cb_targetValue2 = QCheckBox('ShoulderRight') smwui.cb_targetValue3 = QCheckBox('ElbowRight') smwui.cb_targetValue4 = QCheckBox('HandRight') smwui.cb_targetValue4.setChecked(True) smwui.cb_targetValue5 = QCheckBox('SpineBase') smwui.cb_targetValue6 = QCheckBox('HandLeft') smwui.cb_targetValue6.setChecked(True) smwui.cb_targetValue7 = QCheckBox('ElbowLeft') smwui.cb_targetValue8 = QCheckBox('ShoulderLeft') smwui.cb_targetValue9 = QCheckBox('Neck') smwui.cb_targetValue1.stateChanged.connect(smwui.update_chart) smwui.cb_targetValue2.stateChanged.connect(smwui.update_chart) smwui.cb_targetValue3.stateChanged.connect(smwui.update_chart) smwui.cb_targetValue4.stateChanged.connect(smwui.update_chart) smwui.cb_targetValue5.stateChanged.connect(smwui.update_chart) smwui.cb_targetValue6.stateChanged.connect(smwui.update_chart) smwui.cb_targetValue7.stateChanged.connect(smwui.update_chart) smwui.cb_targetValue8.stateChanged.connect(smwui.update_chart) smwui.cb_targetValue9.stateChanged.connect(smwui.update_chart) ### chart set1 = QBarSet("X") set2 = QBarSet("Y") set3 = QBarSet("Z") set1.setColor(QColor(0, 0, 200, 150)) set2.setColor(QColor(0, 200, 0, 150)) set3.setColor(QColor(200, 50, 0, 150)) series = QHorizontalBarSeries() series.append(set1) series.append(set2) series.append(set3) categories = [] categories.append('Parts') axisX = QValueAxis() axisX.applyNiceNumbers() axisY = QBarCategoryAxis() axisY.append(categories) chart = QChart() chart.addSeries(series) chart.setTitle("Timeseries Distance") chart.setAnimationOptions(QChart.SeriesAnimations) chart.setAxisX(axisX, series) chart.setAxisY(axisY) chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignTop) smwui.chartView = QChartView(chart) smwui.chartView.setRenderHint(QPainter.Antialiasing) ### draw parts smwui.viewParts = QQuickWidget() smwui.viewParts.setSource(QUrl("./qml/qmlptviewer/main.qml")) smwui.viewParts.rootContext().setContextProperty( "HandRight", "0,0,0,0") smwui.viewParts.rootContext().setContextProperty("HandLeft", "0,0,0,0") smwui.viewParts.rootContext().setContextProperty( "ElbowRight", "0,0,0,0") smwui.viewParts.rootContext().setContextProperty( "ElbowLeft", "0,0,0,0") smwui.viewParts.rootContext().setContextProperty("Head", "0,0,0,0") scrollArea_viewParts = QScrollArea() scrollArea_viewParts.setMinimumWidth(420) scrollArea_viewParts.setWidget(smwui.viewParts) scrollArea_viewParts.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) ### |1| vbox1 = QVBoxLayout() vbox1.addWidget(smwui.cb_targetAxis1) vbox1.addWidget(smwui.cb_targetAxis2) vbox1.addWidget(smwui.cb_targetAxis3) gb_targetAxis = QGroupBox() gb_targetAxis.setTitle('Axis') gb_targetAxis.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Maximum) gb_targetAxis.setLayout(vbox1) ### |2| vbox2 = QVBoxLayout() vbox2.addWidget(smwui.cb_targetValue1) vbox2.addWidget(smwui.cb_targetValue2) vbox2.addWidget(smwui.cb_targetValue3) vbox2.addWidget(smwui.cb_targetValue4) vbox2.addWidget(smwui.cb_targetValue5) vbox2.addWidget(smwui.cb_targetValue6) vbox2.addWidget(smwui.cb_targetValue7) vbox2.addWidget(smwui.cb_targetValue8) vbox2.addWidget(smwui.cb_targetValue9) gb_targetValue = QGroupBox() gb_targetValue.setTitle('Parts') gb_targetValue.setLayout(vbox2) vbox3 = QVBoxLayout() vbox3.addWidget(btn_refresh) vbox3.addWidget(gb_targetAxis) vbox3.addWidget(gb_targetValue) ### -1- hbox = QHBoxLayout() hbox.addLayout(vbox3) hbox.addWidget(smwui.chartView) hbox.addWidget(scrollArea_viewParts) self.gb_analysis.setTitle("Analysis") self.gb_analysis.setLayout(hbox)
def createBar(self): print("in create bar") min_num, max_num = 0, 100 max_count = 0 linked_bag_list = [] try: df = self.linked['Beam Diff'].dropna() linked_bag_list = df.values.tolist() min_num = int(min(linked_bag_list)) if min_num > 0: # check if greater than 0, set to 0 min_num = 0 max_num = int(max(linked_bag_list)) except AttributeError: self.statusbar.showMessage('Data not ready') count = linked_bag_list count = [0] * (max_num + 1) # choose the largest num as length of count for num in linked_bag_list: count[int(num)] += 1 # update every number's count max_count = max(count) setBar = QBarSet('Beam Difference Occurrence') setBar.append(count) brush = QBrush(QColor(0x57B1FD)) pen = QPen(QColor(0x57B1FD)) pen.setWidth(2) setBar.setPen(pen) setBar.setBrush(brush) series = QBarSeries() series.append(setBar) chart = QChart() font = QFont() font.setPixelSize(18) chart.setTitleFont(font) chart.setTitle('Linked Bags Histogram') chart.addSeries(series) chart.setAnimationOptions(QChart.SeriesAnimations) axisX = QValueAxis() axisX.setRange(min_num, max_num+20) chart.setAxisX(axisX, series) axisY = QValueAxis() axisY.setRange(0, max_count+20) chart.setAxisY(axisY, series) chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) chartView = QChartView(chart) chartView.setRenderHint(QPainter.Antialiasing) # MainWindow.setCentralWidget(chartView) return chartView
def raceBarChart(self): janKills=[0,0,0,0] #BWHO febKills=[0,0,0,0] marchKills=[0,0,0,0] aprilKills=[0,0,0,0] with open('killings.csv', 'r') as f: reader = csv.reader(f, delimiter=',') for row in reader: if '01/15' in row[2]: if row[7]=='B': janKills[0]+=1 elif row[7]=='W': janKills[1]+=1 elif row[7]=='H': janKills[2]+=1 else: janKills[3]+=1 elif '02/15' in row[2]: if row[7]=='B': febKills[0]+=1 elif row[7]=='W': febKills[1]+=1 elif row[7]=='H': febKills[2]+=1 else: febKills[3]+=1 elif '03/15' in row[2]: if row[7]=='B': marchKills[0]+=1 elif row[7]=='W': marchKills[1]+=1 elif row[7]=='H': marchKills[2]+=1 else: marchKills[3]+=1 elif '04/15' in row[2]: if row[7]=='B': aprilKills[0]+=1 elif row[7]=='W': aprilKills[1]+=1 elif row[7]=='H': aprilKills[2]+=1 else: marchKills[3]+=1 finalAppend=[] finalAppend.append(janKills) finalAppend.append(febKills) finalAppend.append(marchKills) finalAppend.append(aprilKills) self.w = Window2() self.w.show() set0 = QBarSet('Black') set1 = QBarSet('White') set2 = QBarSet('Hispanic') set3 = QBarSet('Other') print(finalAppend) for x in range(4): set0.append(janKills[x]) for x in range(4): set1.append(febKills[x]) for x in range(4): set2.append(marchKills[x]) for x in range(4): set3.append(aprilKills[x]) series = QBarSeries() series.append(set0) series.append(set1) series.append(set2) series.append(set3) chart = QChart() chart.addSeries(series) chart.setTitle('Monthly racial Death comparison') chart.setAnimationOptions(QChart.SeriesAnimations) months = ('Jan', 'Feb', 'Mar', 'Apr') axisX = QBarCategoryAxis() axisX.append(months) axisY = QValueAxis() axisY.setRange(0, 100) chart.addAxis(axisX, Qt.AlignBottom) chart.addAxis(axisY, Qt.AlignLeft) chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) chartView = QChartView(chart) self.w.setCentralWidget(chartView)
def ageWiseBarGraph(self): self.w = Window2() self.w.show() set0 = QBarSet('below 25') set1 = QBarSet('25 to 35') set2 = QBarSet('36 to 45') set3 = QBarSet('46 to 55') set4 = QBarSet('above 55') file="killings.csv" ageSet = [0,0,0,0,0] with open('killings.csv') as File: csvReader = csv.reader(File) next(csvReader) for row in csvReader: if int(row[5]) < 25: ageSet[0]+=1 elif int(row[5]) >=25 and int(row[5])<= 35: ageSet[1]+=1 elif int(row[5]) >35 and int(row[5])<=45: ageSet[2]+=1 elif int(row[5]) >45 and int(row[5])<= 55: ageSet[3]+=1 else: ageSet[4]+=1 print (ageSet) set0.append(ageSet[0]) set1.append(ageSet[1]) set2.append(ageSet[2]) set3.append(ageSet[3]) set4.append(ageSet[4]) series = QBarSeries() series.append(set0) series.append(set1) series.append(set2) series.append(set3) series.append(set4) chart = QChart() chart.addSeries(series) chart.setTitle('Age wise comparison') chart.setAnimationOptions(QChart.SeriesAnimations) msg = ('Death Toll') axisX = QBarCategoryAxis() axisX.append(msg) axisY = QValueAxis() axisY.setRange(0, 200) chart.addAxis(axisX, Qt.AlignBottom) chart.addAxis(axisY, Qt.AlignLeft) chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) chartView = QChartView(chart) self.w.setCentralWidget(chartView)
def create_fleeChart(self): file="killings.csv" flee = [0,0,0,0] with open('killings.csv') as File: csvReader = csv.reader(File) next(csvReader) for row in csvReader: if row[12]== 'Not fleeing': flee[0]+=1 elif row[12]== 'Car': flee[1]+=1 elif row[12]=='Foot': flee[2]+=1 else: flee[3]+=1 self.w = Window2() self.w.show() set0 = QBarSet('Not Fleeing') set1 = QBarSet('Car') set2 = QBarSet('Foot') set3 = QBarSet('Other') file="killings.csv" #appending graph values here set0.append(flee[0]) set1.append(flee[1]) set2.append(flee[2]) set3.append(flee[3]) series = QBarSeries() series.append(set0) series.append(set1) series.append(set2) series.append(set3) chart = QChart() chart.addSeries(series) chart.setTitle('Mode of Fleeing') chart.setAnimationOptions(QChart.SeriesAnimations) msg = ('Flee') axisX = QBarCategoryAxis() axisX.append(msg) axisY = QValueAxis() axisY.setRange(0, 250) chart.addAxis(axisX, Qt.AlignBottom) chart.addAxis(axisY, Qt.AlignLeft) chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) chartView = QChartView(chart) self.w.setCentralWidget(chartView)
class BandPowerGraph(QWidget): def __init__(self, name: str): super().__init__() self.band_power_chart = QChart() self.band_power_chart.setAnimationOptions(QChart.SeriesAnimations) self.channel_band_power_set = QBarSet("Band Power") self.channel_band_power_set.append(1) self.channel_band_power_set.append(1) self.channel_band_power_set.append(1) self.channel_band_power_set.append(1) self.channel_band_power_set.append(1) self.bands_axis = QBarCategoryAxis() self.bands_axis.append("Delta (1 - 3 Hz)") self.bands_axis.append("Theta (4 - 7 Hz)") self.bands_axis.append("Alpha (8 - 13 Hz)") self.bands_axis.append("Beta (13 - 30 Hz)") self.bands_axis.append("Gamma (30 - 100)") self.power_axis = QValueAxis() self.chart_series = QBarSeries() self.chart_series.append(self.channel_band_power_set) self.band_power_chart.addSeries(self.chart_series) self.band_power_chart.setTitle(f"<h1>Band Power For {name}</h1>") self.band_power_chart.addAxis(self.bands_axis, Qt.AlignBottom) self.band_power_chart.addAxis(self.power_axis, Qt.AlignLeft) self.chart_series.attachAxis(self.bands_axis) self.chart_series.attachAxis(self.power_axis) self.chart_view = QChartView(self.band_power_chart) self.chart_view.setRenderHint(QPainter.Antialiasing) self.root_layout = QStackedLayout() self.setLayout(self.root_layout) self.root_layout.addWidget(self.chart_view) def set_name(self, name: str): self.band_power_chart.setTitle(f"<h1>Band Power For {name}</h1>") def update_values(self, data: np.ndarray, fft_window_size: float = 0): eeg_data = utils.EegData(data) feature_extractor = eeg_data.feature_extractor(0, global_config.SAMPLING_RATE) self.channel_band_power_set.replace( 0, feature_extractor.average_band_amplitude(utils.FrequencyBand.delta_freq_band(), fft_window_size) ) self.channel_band_power_set.replace( 1, feature_extractor.average_band_amplitude(utils.FrequencyBand.theta_freq_band(), fft_window_size) ) self.channel_band_power_set.replace( 2, feature_extractor.average_band_amplitude(utils.FrequencyBand.alpha_freq_band(), fft_window_size) ) self.channel_band_power_set.replace( 3, feature_extractor.average_band_amplitude(utils.FrequencyBand.beta_freq_band(), fft_window_size) ) self.channel_band_power_set.replace( 4, feature_extractor.average_band_amplitude(utils.FrequencyBand.gama_freq_band(), fft_window_size) ) def auto_adjust_axis(self): utils.auto_adjust_axis(self.power_axis, [self.channel_band_power_set], 0.1)
def setupChartWithData(self): """ Chart gets updated displaying the new data. Data has to be expressed on a dictionary form: - keys are timestamps - values are total balance for that timestamp """ self.chart = QChart() self.chart.setTheme(QChart.ChartThemeDark) self.chart.setAnimationOptions(QChart.SeriesAnimations) self.chart.setBackgroundBrush(QBrush(QColor("transparent"))) # Series self.barseries = QBarSeries() currentyear, currentmonth = datetime.today().year, datetime.today( ).month dates, amounts = [], [] # Get 5 previous month numbers for _ in range(5): dates.append((currentmonth, currentyear)) currentmonth -= 1 if currentmonth == 0: currentmonth = 12 currentyear -= 1 # Get amounts for each month for d in dates: month, year = d amounts.append( dbhandler.get_total_wealth_on_month(month, year=year)) # Iterate months and amount and insert them into the histogram appropiately barset = QBarSet('Total wealth') labelsfont = QFont() labelsfont.setFamily('Inter') labelsfont.setBold(True) barset.setLabelFont(labelsfont) barset.setColor(QColor("#D3EABD")) x_values = [] for d, a in zip(reversed(dates), reversed(amounts)): if a > 0: barset.append(int(a)) x_values.append(calendar.month_name[d[0]]) self.barseries.append(barset) self.barseries.setName("Last Months") self.barseries.setLabelsVisible(True) self.barseries.setBarWidth(0.2) self.barseries.setLabelsPosition(QAbstractBarSeries.LabelsOutsideEnd) self.chart.addSeries(self.barseries) # Axis X (Dates) self.x_axis = QBarCategoryAxis() self.x_axis.setTitleText(self.tr('Date')) labelsfont = QFont() labelsfont.setFamily('Roboto') labelsfont.setLetterSpacing(QFont.AbsoluteSpacing, 1) labelsfont.setWeight(QFont.Light) labelsfont.setPointSize(9) self.x_axis.setLabelsFont(labelsfont) self.x_axis.setGridLineVisible(False) self.x_axis.setLineVisible(False) self.x_axis.setLinePenColor(QColor("#D3EABD")) self.x_axis.setTitleVisible(False) self.x_axis.append(x_values) self.chart.addAxis(self.x_axis, Qt.AlignBottom) # Axis Y (Balances) self.y_axis = QValueAxis() self.y_axis.setMax(max(amounts) * 1.3) self.y_axis.setMin(min(amounts) * 0.95) self.y_axis.hide() labelsfont = QFont() labelsfont.setPointSize(4) self.y_axis.setLabelsFont(labelsfont) self.chart.addAxis(self.y_axis, Qt.AlignLeft) # Attach axis to series self.barseries.attachAxis(self.x_axis) self.barseries.attachAxis(self.y_axis) # Legend self.chart.legend().hide() # Set up chart on ChartView self.setChart(self.chart) self.setRenderHint(QPainter.Antialiasing) self.setStyleSheet("border: 0px; background-color: rgba(0,0,0,0)")
def __init__(self, board: BoardShim): super().__init__() self.setGeometry(0, 0, 1800, 900) self.setWindowTitle("Resonance-Like Frequency") self.board = board self.recording_progress_dialog = None self.eeg_data_buffer = utils.EegData() self.reading_timer = QTimer() self.recording = False self.recording_reference = False self.reference_eeg_data = utils.EegData() self.index_generator = utils.FrequencyIndexGenerator(global_config.SAMPLING_RATE) self.eeg_sample_count = 0 self.root_widget = QWidget() self.root_layout = QGridLayout() self.root_widget.setLayout(self.root_layout) self.setCentralWidget(self.root_widget) title = QLabel("<h1>Resonance Frequency Finder</h1>") title.setAlignment(Qt.AlignCenter) self.root_layout.addWidget(title, 0, 0, 1, 3) # window_size_label = QLabel("window size: ") # window_size_label.setAlignment(Qt.AlignRight) # self.window_size_combo_box = QComboBox() # self.window_size_combo_box.addItems(self.AVAILABLE_WINDOW_SIZES) self.root_directory_label = QLabel() self.select_root_directory = QPushButton("Select/Change") self.select_root_directory.clicked.connect(self.pick_root_directory) self.record_btn = QPushButton("Record") self.record_btn.setEnabled(False) self.record_btn.clicked.connect(self.record_clicked) self.record_reference_btn = QPushButton("Record Reference") self.record_reference_btn.clicked.connect(self.record_reference_clicked) # self.root_layout.addWidget(utils.construct_horizontal_box([ # window_size_label, self.window_size_combo_box, self.record_btn # ]), 1, 0, 1, 3) self.load_results_btn = QPushButton("Load Existing Data") self.load_results_btn.clicked.connect(self.load_existing_data) self.root_layout.addWidget(utils.construct_horizontal_box([ self.record_btn, self.record_reference_btn, self.root_directory_label, self.select_root_directory, self.load_results_btn ]), 1, 0, 1, 3) self.current_freq_label = QLabel() self.root_layout.addWidget(utils.construct_horizontal_box([self.current_freq_label]), 2, 0, 1, 3) self.frequency_slider = QSlider() self.frequency_slider.setRange(self.DEFAULT_MIN_FREQUENCY, self.DEFAULT_MAX_FREQUENCY) self.frequency_slider.setSingleStep(self.DEFAULT_FREQUENCY_STEP) self.frequency_slider.setTickInterval(self.DEFAULT_FREQUENCY_STEP) self.frequency_slider.valueChanged.connect(self.update_freq_label) self.frequency_slider.setTickPosition(QSlider.TicksBelow) self.frequency_slider.setOrientation(Qt.Horizontal) min_freq_label = QLabel(f"<b>{self.DEFAULT_MIN_FREQUENCY} Hz</b>") max_freq_label = QLabel(f"<b>{self.DEFAULT_MAX_FREQUENCY} Hz</b>") self.root_layout.addWidget(utils.construct_horizontal_box([ min_freq_label, self.frequency_slider, max_freq_label ]), 3, 0, 1, 3) self.c3_amplitude_bar_set = QBarSet("Electrode C3") self.cz_amplitude_bar_set = QBarSet("Electrode Cz") self.c4_amplitude_bar_set = QBarSet("Electrode C4") self.frequencies = [] for freq in range(self.DEFAULT_MIN_FREQUENCY, self.DEFAULT_MAX_FREQUENCY + 1, self.DEFAULT_FREQUENCY_STEP): self.frequencies.append(f"{freq} Hz") self.c3_amplitude_bar_set.append(1) self.cz_amplitude_bar_set.append(1) self.c4_amplitude_bar_set.append(1) self.freq_axis = QBarCategoryAxis() self.freq_axis.append(self.frequencies) self.amplitude_axis = QValueAxis() self.amplitude_axis.setRange(0, 4) self.freq_chart = QChart() self.freq_chart.setAnimationOptions(QChart.SeriesAnimations) self.electrodes_data_series = QBarSeries() self.electrodes_data_series.append(self.c3_amplitude_bar_set) self.electrodes_data_series.append(self.cz_amplitude_bar_set) self.electrodes_data_series.append(self.c4_amplitude_bar_set) self.freq_chart.addSeries(self.electrodes_data_series) self.freq_chart.setTitle("<h1>Frequency Amplitude Increase</h1>") self.freq_chart.addAxis(self.freq_axis, Qt.AlignBottom) self.freq_chart.addAxis(self.amplitude_axis, Qt.AlignLeft) self.electrodes_data_series.attachAxis(self.amplitude_axis) self.electrodes_data_series.attachAxis(self.freq_axis) self.frequency_amplitude_graph = QChartView(self.freq_chart) self.frequency_amplitude_graph.setRenderHint(QPainter.Antialiasing) self.root_layout.addWidget(self.frequency_amplitude_graph, 4, 0, 15, 3) self.auto_adjust_axis()
def update_chart(self): if not self.cb_targetAxis1.checkState( ) and not self.cb_targetAxis2.checkState( ) and not self.cb_targetAxis3.checkState(): return -1 ## draw chart set1 = QBarSet("X") set2 = QBarSet("Y") set3 = QBarSet("Z") set1.setColor(QColor(0, 0, 200, 180)) set2.setColor(QColor(0, 200, 0, 180)) set3.setColor(QColor(200, 100, 0, 180)) self.categories = [] self.set1_val = np.array([]) self.set2_val = np.array([]) self.set3_val = np.array([]) for i in range(len(self.parts_dict)): flag_add = False if self.parts_dict[self.cb_targetValue1.text( )] == i and self.cb_targetValue1.checkState(): flag_add = True self.categories.append(self.cb_targetValue1.text()) elif self.parts_dict[self.cb_targetValue2.text( )] == i and self.cb_targetValue2.checkState(): flag_add = True self.categories.append(self.cb_targetValue2.text()) elif self.parts_dict[self.cb_targetValue3.text( )] == i and self.cb_targetValue3.checkState(): flag_add = True self.categories.append(self.cb_targetValue3.text()) elif self.parts_dict[self.cb_targetValue4.text( )] == i and self.cb_targetValue4.checkState(): flag_add = True self.categories.append(self.cb_targetValue4.text()) elif self.parts_dict[self.cb_targetValue5.text( )] == i and self.cb_targetValue5.checkState(): flag_add = True self.categories.append(self.cb_targetValue5.text()) elif self.parts_dict[self.cb_targetValue6.text( )] == i and self.cb_targetValue6.checkState(): flag_add = True self.categories.append(self.cb_targetValue6.text()) elif self.parts_dict[self.cb_targetValue7.text( )] == i and self.cb_targetValue7.checkState(): flag_add = True self.categories.append(self.cb_targetValue7.text()) elif self.parts_dict[self.cb_targetValue8.text( )] == i and self.cb_targetValue8.checkState(): flag_add = True self.categories.append(self.cb_targetValue8.text()) elif self.parts_dict[self.cb_targetValue9.text( )] == i and self.cb_targetValue9.checkState(): flag_add = True self.categories.append(self.cb_targetValue9.text()) if flag_add: set1 << self.ctd.distanceList[0 + 3 * i] set2 << self.ctd.distanceList[1 + 3 * i] set3 << self.ctd.distanceList[2 + 3 * i] self.set1_val = np.append(self.set1_val, [self.ctd.distanceList[0 + 3 * i]]) self.set2_val = np.append(self.set2_val, [self.ctd.distanceList[1 + 3 * i]]) self.set3_val = np.append(self.set3_val, [self.ctd.distanceList[2 + 3 * i]]) series = QHorizontalBarSeries() if self.cb_targetAxis1.checkState(): series.append(set1) else: self.set1_val = np.zeros(len(self.categories)) if self.cb_targetAxis2.checkState(): series.append(set2) else: self.set2_val = np.zeros(len(self.categories)) if self.cb_targetAxis3.checkState(): series.append(set3) else: self.set3_val = np.zeros(len(self.categories)) axisX = QValueAxis() axisX.applyNiceNumbers() axisY = QBarCategoryAxis() axisY.append(self.categories) chart = QChart() chart.setTitle("Timeseries Distance") chart.setAnimationOptions(QChart.SeriesAnimations) chart.addSeries(series) chart.setAxisX(axisX, series) chart.setAxisY(axisY) self.chartView.setChart(chart) self.chartView.setRenderHint(QPainter.Antialiasing) self.update_parts()
def createUnlinkedBar(self): max_count = 0 unlinked_bag_list = [] try: df = self.unlinked['Beam Diff'].dropna() unlinked_bag_list = df.values.tolist() except AttributeError: self.statusbar.showMessage('Data not ready') count = [0] * 4 for num in unlinked_bag_list: if -1000 <= num and num <= -51: count[0] += 1 elif -50 <= num and num <= -1: count[1] += 1 elif 151 <= num and num <= 200: count[2] += 1 elif 201 <= num: count[3] += 1 # print(count) max_count = max(count) setBar = QBarSet('Beam Difference Occurrence') setBar.append(count) series = QBarSeries() series.append(setBar) brush = QBrush(QColor(0xfdb157)) pen = QPen(QColor(0xfdb157)) pen.setWidth(2) setBar.setPen(pen) setBar.setBrush(brush) chart = QChart() font = QFont() font.setPixelSize(18) chart.setTitleFont(font) chart.setTitle('Unlinked Bags Summary') chart.addSeries(series) chart.setAnimationOptions(QChart.SeriesAnimations) labels = ['Not useful(-50 to -1000)', 'Pushed by operator(-1 to -50)', 'Slipping on belt(151 to 200)', 'Not useful 201+'] axisX = QBarCategoryAxis() axisX.append(labels) # chart.setAxisX(axisX, series) chart.addAxis(axisX, Qt.AlignBottom) # chart.ChartAreas[0].AxisX.LabelAutoFitStyle = LabelAutoFitStyle.WrodWrap series.attachAxis(axisX) axisY = QValueAxis() axisY.setRange(0, max_count+1) # chart.setAxisY(axisY, series) chart.addAxis(axisY, Qt.AlignLeft) series.attachAxis(axisY) chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) chartView = QChartView(chart) chartView.setRenderHint(QPainter.Antialiasing) # MainWindow.setCentralWidget(chartView) return chartView
class initial(QDialog): def __init__(self): super(initial, self).__init__() loadUi("main.ui", self) # definir elementos de la UI y acciones/funciones asociadas # creamos sets para mostrar resultados en el barchart self.setRecall = QBarSet("Recalls") self.setRecall.append([0, 0, 0]) self.setAccurracy = QBarSet("Accurracy") self.setAccurracy.append([0, 0, 0]) self.series = QBarSeries() # Elementos Tab Entrenamiento: # =========================== # Btn Insertar primeros datos entrenamiento self.trainingAddFilesBtn.clicked.connect( self.insertarNoticiasEntrenamientoDespoblacion) # Btn Insertar segundos datos entrenamiento self.trainingAddFilesBtn2.clicked.connect( self.insertarNoticiasEntrenamientoNoDespoblacion) # Btn Preprocesamiento de texto self.procesarTextoBtn.clicked.connect(self.procesarTextoEntrenamiento) # ComboBox selector de Modelo a entrenar # self.chooseModelComboBox.activated.connect(self.elegirModeloEntrenamiento) # añadir elementos al comboBox y sus valores asociados self.chooseModelComboBox.addItem("KNN", 1) self.chooseModelComboBox.addItem("Naive Bayes", 2) self.chooseModelComboBox.addItem("Decision Tree", 3) # Btn para entrenar el modelo seleccionado self.trainModelBtn.clicked.connect(self.entrenarModelo) # Elementos Tab Testeo: # ==================== # Btn Insertar Datos Testeo self.testingFilesBtn.clicked.connect(self.insertarNoticiasTesteo) # Btn Seleccionar Modelo self.selectTestModelBtn.clicked.connect(self.elegirModeloTesteo) # Btn Mostrar Resultados self.testBtn.clicked.connect(self.mostrarResultados) # Tab Testeo #self.tabTest.clicked.connect(self.abrirTabTesteo) # nombre excel self.nombreresultadoexcel = ':)' # funciones # ========= # abrir tab testeo def abrirTabTesteo(self): self.stepTipsField.setPlainText( "En esta pestaña puede realizar el testeo sobre un nuevo set de datos para un modelo ya existente." ) # abrir dialog window para seleccionar los datos de entrenamiento def insertarNoticiasEntrenamientoDespoblacion(self): del desp[:] print(desp) # cambiar texto campo descripcion self.stepTipsField.setPlainText( "Seleccionamos los directorios donde tenemos los archivos de texto que utilizaremos para entrenar nuestro modelo." ) # abrir ventana seleccion archivos desp.append(self.openDialogBox()) print(desp) #cambiar self.procesarTextoBtn a habilitado self.trainingAddFilesBtn2.setEnabled(True) # abrir dialog window para seleccionar los segundos datos de entrenamiento def insertarNoticiasEntrenamientoNoDespoblacion(self): del no_despoblacion[:] # cambiar texto campo descripcion self.stepTipsField.setPlainText( "Seleccionamos los directorios donde tenemos los archivos de texto que utilizaremos para entrenar nuestro modelo." ) # abrir ventana seleccion archivos no_despoblacion.append(self.openDialogBox()) #cambiar self.procesarTextoBtn a habilitado self.procesarTextoBtn.setEnabled(True) # aplicar preprocesamiento de texto def procesarTextoEntrenamiento(self): # cambiar texto campo descripcion self.stepTipsField.setPlainText( "El preprocesamiento a realizar consta de 4 etapas:\n1. Tokenizar: separar las palabras que componen un texto, obteniendo como resultado una secuencia de tokens.\n2. Normalización: se pasa a minúsculas tdoos los tokens.\n3.Filtrado de stopwords: en esta etapa eliminamos aquellas palabras con poco valor semántico, denominadas stopwords.\n4.Stemming: extraemos el lexema de los tokens restantes (un ejemplo sería ‘cas-’ para la palabra ‘casero’)" ) del noticias[:] del clases[:] # bucle inserción de noticias mediante open ingresar_noticias(desp[0], noticias) ingresar_noticias(no_despoblacion[0], noticias) ingresar_noticias(desp[0], despoblacion) # Procesamiento de texto texto_procesado(processed_text_entrenamiento, noticias) # Creación de arreglo de clases crea_clases(clases, processed_text_entrenamiento, despoblacion) # cambiar self.trainModelBtn a habilitado self.trainModelBtn.setEnabled(True) # cambiar texto campo descripcion self.stepTipsField.setPlainText( "El preprocesamiento a realizar consta de 4 etapas:\n1. Tokenizar: separar las palabras que componen un texto, obteniendo como resultado una secuencia de tokens.\n2. Normalización: se pasa a minúsculas tdoos los tokens.\n3.Filtrado de stopwords: en esta etapa eliminamos aquellas palabras con poco valor semántico, denominadas stopwords.\n4.Stemming: extraemos el lexema de los tokens restantes (un ejemplo sería ‘cas-’ para la palabra ‘casero’).\n====================\nEl preprocesamiento ha acabado" ) # cambiar self.procesarTextoBtn a deshabilitado self.procesarTextoBtn.setEnabled(False) # abrir ventana seleccion archivos def openDialogBox(self): filenames = QFileDialog.getOpenFileNames() return filenames[0] # mostrar resultados testeo en nueva tabla def mostrarResultados(self): # cambiar texto campo descripcion self.stepTipsField.setPlainText( "A continuación se muestra una tabla con los resultados de la clasificación realizada por el modelo seleccionado." ) # para ocupar toda la tabla self.tableWidgetshowTest.horizontalHeader().setSectionResizeMode( QtWidgets.QHeaderView.Stretch) # resetear tabla self.tableWidgetshowTest.setRowCount(0) nombre = self.nombreresultadoexcel # mostrar contenido xlsx documento = xlrd.open_workbook(nombre + '.xlsx') df = documento.sheet_by_index(0) self.tableWidgetshowTest.setRowCount((df.nrows) - 1) self.tableWidgetshowTest.setColumnCount(2) for x in range(1, df.nrows): for y in range(2): print('x: ' + df.cell_value(x, y - 1)) item = QTableWidgetItem() nombreArchivo = df.cell_value(x, y - 1).split("/") item.setText(nombreArchivo[len(nombreArchivo) - 1]) self.tableWidgetshowTest.setItem(x - 1, y - 1, item) # insertar archivos fase testeo def insertarNoticiasTesteo(self): # cambiar texto campo descripcion self.stepTipsField.setPlainText( "Seleccione los archivos que utilizará durante la fase de testeo.") # abrir ventana seleccion archivos filepaths = self.openDialogBox() #ingresar noticias ingresar_noticias(filepaths, nuevas) #Procesamiento de texto texto_procesado(processed_text_testeo, nuevas) # cambiar self.selectTestModelBtn a deshabilitado self.selectTestModelBtn.setEnabled(True) # cambiar self.testingFilesBtn a habilitado # self.testingFilesBtn.setEnabled(False) # seleccionar modelo fase testeo def elegirModeloTesteo(self): # cambiar texto campo descripcion self.stepTipsField.setPlainText( "Seleccione el diccionario .pk y modelo correspondiente .pk1.") # abrir ventana seleccion archivos modelopath = self.openDialogBox() if (len(modelopath) == 2): # cargar diccionario cv1 = cargar_modelo(modelopath[0]) # cargar modelo modelo = cargar_modelo(modelopath[1]) # aplicar tfidf X_testcv = tfid_fit(processed_text_testeo, cv1) # insertar predicciones predicciones = [] for i in X_testcv: predicciones.append(prediccion(modelo, i)) # crear dataframe df = pd.DataFrame(data=predicciones, index=nuevas) # nombrar archivo y exportar a excel archivo = modelopath[0] new_archivo = archivo.replace('modelos', 'resultados') nombre = new_archivo[:len(new_archivo) - 3] self.nombreresultadoexcel = nombre df.to_excel(nombre + ".xlsx", "Sheet1") # cambiar self.testBtn a habilitado self.testBtn.setEnabled(True) # cambiar texto campo descripcion self.stepTipsField.setPlainText( "Resultados exportados a la carpeta resultados en formato Excel." ) # aplicar modelo NaiveBayes entrenamiento def entrenamientoNaiveBayes(self): # Proceso TFIDF X_traincv = cv.fit_transform(processed_text_entrenamiento) # Partición de datos X_train, X_test, Y_train, Y_test = train_test_split(X_traincv, clases, test_size=0.15, random_state=324) #Modelos naive = naive_bayes(X_train, Y_train) print(naive) print( "####################### Test Score ##############################\n" ) test_score(naive, X_train, Y_train) # Creamos los datos a testear Y_true_naive, Y_pred_naive = datos_test(Y_test, naive, X_test) # Datos de los modelos print( "###################### Accuracy ###############################\n" ) accuracy(Y_true_naive, Y_pred_naive) self.setAccurracy.replace( 1, accuracy_score(Y_true_naive, Y_pred_naive) * 100) print( "####################### Recall ##############################\n") print(recall_score(Y_true_naive, Y_pred_naive, average='macro')) self.setRecall.replace( 1, recall_score(Y_true_naive, Y_pred_naive, average='macro') * 100) a = "Modelo Naive-Bayes\n==================\nRecall:" + str( recall_score(Y_true_naive, Y_pred_naive, average='macro')) + "\nAccuracy: " + str( accuracy_score(Y_true_naive, Y_pred_naive)) self.stepTipsField.setPlainText(a) #llamar a funcion para actualizar los valores del Barchart self.appendResults() print( "\n###################### Matriz de confusion ###############################\n" ) matrizconf(Y_true_naive, Y_pred_naive) #Guardamos modelo now = datetime.now() # dd/mm/YY H:M:S dt_string = now.strftime("dia_%d-%m-%Y,hora_%H-%M-%S") guardar_modelo('modelos/naive_' + dt_string, naive) with open('modelos/naive_' + dt_string + '.pk', 'wb') as f: pickle.dump(cv, f) # aplicar modelo Decision Tree entrenamiento def entrenamientoArbolDecision(self): # Proceso TFIDF X_traincv = cv.fit_transform(processed_text_entrenamiento) #Partición de datos X_train, X_test, Y_train, Y_test = train_test_split(X_traincv, clases, test_size=0.15, random_state=324) #Modelos tree = decision_tree(X_train, Y_train) print( "####################### Test Score ##############################\n" ) test_score(tree, X_train, Y_train) #Creamos los datos a testear Y_true_tree, Y_pred_tree = datos_test(Y_test, tree, X_test) #Datos de los modelos print( "###################### Accuracy ###############################\n" ) accuracy(Y_true_tree, Y_pred_tree) #incluir nueva accurracy al set de resultados de NaiveBayes #self.setDTrees.append(accuracy_score(Y_true_tree, Y_pred_tree)*100) self.setAccurracy.replace( 2, accuracy_score(Y_true_tree, Y_pred_tree) * 100) #llamar a funcion para actualizar los valores del Barchart print( "####################### Recall ##############################\n") print(recall_score(Y_true_tree, Y_pred_tree, average='macro')) #self.setDTrees.append(recall_score(Y_true_tree, Y_pred_tree, average='macro')*100) self.setRecall.replace( 2, recall_score(Y_true_tree, Y_pred_tree, average='macro') * 100) a = "Modelo Arbol Decision\n=====================\nRecall:" + str( recall_score(Y_true_tree, Y_pred_tree, average='macro')) + "\nAccuracy: " + str( accuracy_score(Y_true_tree, Y_pred_tree)) self.stepTipsField.setPlainText(a) self.appendResults() #Matriz confusion print( "\n###################### Matriz de confusion ###############################\n" ) matrizconf(Y_true_tree, Y_pred_tree) now = datetime.now() # dd/mm/YY H:M:S dt_string = now.strftime("dia_%d-%m-%Y,hora_%H-%M-%S") guardar_modelo('modelos/tree_' + dt_string, tree) with open('modelos/tree_' + dt_string + '.pk', 'wb') as f: pickle.dump(cv, f) # aplicar modelo KNN def entrenamientoKnn(self): # Proceso TFIDF X_traincv = cv.fit_transform(processed_text_entrenamiento) #Partición de datos X_train, X_test, Y_train, Y_test = train_test_split(X_traincv, clases, test_size=0.15, random_state=324) #Modelos modknn = knn(X_train, Y_train) print( "####################### Test Score ##############################\n" ) test_score(modknn, X_train, Y_train) #Creamos los datos a testear Y_true_knn, Y_pred_knn = datos_test(Y_test, modknn, X_test) #Datos de los modelos print( "###################### Accuracy ###############################\n" ) accuracy(Y_true_knn, Y_pred_knn) #llamar a funcion para actualizar los valores del Barchart self.setAccurracy.replace(0, accuracy_score(Y_true_knn, Y_pred_knn) * 100) print( "####################### Recall ##############################\n") print(recall_score(Y_true_knn, Y_pred_knn, average='macro')) #self.setDTrees.append(recall_score(Y_true_knn, Y_pred_knn, average='macro')*100) self.setRecall.replace( 0, recall_score(Y_true_knn, Y_pred_knn, average='macro') * 100) a = "Modelo KNN\n===============\nRecall:" + str( recall_score(Y_true_knn, Y_pred_knn, average='macro')) + "\nAccuracy: " + str( accuracy_score(Y_true_knn, Y_pred_knn)) self.stepTipsField.setPlainText(a) self.appendResults() #Matriz confusion print( "\n###################### Matriz de confusion ###############################\n" ) matrizconf(Y_true_knn, Y_pred_knn) #Guardamos modelo now = datetime.now() # dd/mm/YY H:M:S dt_string = now.strftime("dia_%d-%m-%Y,hora_%H-%M-%S") guardar_modelo('modelos/knn_' + dt_string, modknn) with open('modelos/knn_' + dt_string + '.pk', 'wb') as f: pickle.dump(cv, f) # comprobar modelo seleccionado en comboBox def entrenarModelo(self): #cambiar texto en self.stepTipsField self.stepTipsField.setPlainText("Entrenando el modelo seleccionado...") #tomar valor actual del comboBox modelSelect = self.chooseModelComboBox.currentData() #no existe switch en python (o.o) if modelSelect == 1: self.entrenamientoKnn() if modelSelect == 2: self.entrenamientoNaiveBayes() if modelSelect == 3: self.entrenamientoArbolDecision() # add resultados entrenamiento y actualizar barchart def appendResults(self): #clear de series self.series = QBarSeries() #add sets de Accurracy y Recall de todos los modelos procesados a series self.series.append(self.setAccurracy) self.series.append(self.setRecall) # crear nuevo Chart chart = QChart() # add series al nuevo Chart chart.addSeries(self.series) chart.setTitle("Precisiones de Modelos") chart.setAnimationOptions(QChart.SeriesAnimations) # parametro QChart modelosEjeX = ('KNN', 'Naive Bayes', 'Decision Trees') # parametros ejeX ejeX = QBarCategoryAxis() ejeX.append(modelosEjeX) # parametros ejeY ejeY = QValueAxis() chart.addAxis(ejeX, Qt.AlignBottom) chart.addAxis(ejeY, Qt.AlignLeft) # leyenda Barchart chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) # Mostrar ventana Barchart self.QChartView = QChartView(chart) self.QChartView.resize(600, 600) self.QChartView.show()
def createBar(self): set0 = QBarSet('X0') set1 = QBarSet('X1') set2 = QBarSet('X2') set3 = QBarSet('X3') set4 = QBarSet('X4') set0.append([random.randint(0, 10) for i in range(6)]) set1.append([random.randint(0, 10) for i in range(6)]) set2.append([random.randint(0, 10) for i in range(6)]) set3.append([random.randint(0, 10) for i in range(6)]) set4.append([random.randint(0, 10) for i in range(6)]) series = QBarSeries() series.append(set0) series.append(set1) series.append(set2) series.append(set3) series.append(set4) chart = QChart() chart.addSeries(series) chart.setTitle('Bar Chart Demo') chart.setAnimationOptions(QChart.SeriesAnimations) months = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun') axisX = QBarCategoryAxis() axisX.append(months) axisY = QValueAxis() axisY.setRange(0, 15) chart.addAxis(axisX, Qt.AlignBottom) chart.addAxis(axisY, Qt.AlignLeft) chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) chartView = QChartView(chart) return chartView
class SENSOR_TEST(QWidget): bars = None series = None chart = None labelWidgets = [] comms = None commsStatus = False deviceID = "HARP" def __init__(self): QWidget.__init__(self) # ADD GUI WIDGETS self.setupLayout() # LAUNCH GUI self.show() self.resize(800,600) def setupLayout(self): parentLayout = QVBoxLayout() parentLayout.setContentsMargins(20,20,20,20) buttonLayout = QHBoxLayout() # CREATE SERIAL COMMUNICATION CONNECT BUTTON self.connectButton = QPushButton("CONNECT") self.connectButton.setFixedSize(150, 40) self.connectButton.setCheckable(True) self.connectButton.setStyleSheet("QPushButton {background-color: #66BB6A; color: black; border-radius: 20px}" "QPushButton:hover {background-color: #4CAF50; color: black; border-radius: 20px}" "QPushButton:checked {background-color: #EF5350; color: white; border-radius: 20px}" "QPushButton:checked:hover {background-color: #F44336; color: white; border-radius: 20px}") # CREATE SENSORS CALIBRATION BUTTON self.calibrateButton = QPushButton("CALIBRATE") self.calibrateButton.setFixedSize(150, 40) self.calibrateButton.setStyleSheet("QPushButton {background-color: #E0E0E0; color: black; border-radius: 20px}" "QPushButton:hover {background-color: #BDBDBD; color: black; border-radius: 20px}" "QPushButton:pressed {background-color: #D5D5D5; color: black; border-radius: 20px}") # ADD BUTTONS TO HORIZONTAL LAYOUT buttonLayout.addWidget(self.connectButton, alignment = Qt.AlignLeft) buttonLayout.addWidget(self.calibrateButton, alignment = Qt.AlignRight) # CREATE BAR CHART TO DISPLAY SENSOR READINGS self.bars = QBarSet('Sensor Readings') self.bars.append([0 for i in range(5)]) self.chart = QChart() self.chart.setBackgroundRoundness(20) self.chart.layout().setContentsMargins(0, 0, 0, 0) self.series = QBarSeries() self.series.append(self.bars) self.chart.addSeries(self.series) self.chart.setTitle('Sensor Readings') # CREATE X-AXIS AS SENSOR LABELS xAxis = QBarCategoryAxis() labels = ["Sensor {}".format(i+1) for i in range(5)] xAxis.append(labels) # CREATE Y-AXIS AND SENSOR READINGS yAxis = QValueAxis() yAxis.setRange(-100, 100) yAxis.setTickCount(11) yAxis.setTitleText("Pressure (%)") # ADD AXES TO CHART self.chart.addAxis(xAxis, Qt.AlignBottom) self.chart.addAxis(yAxis, Qt.AlignLeft) self.chart.legend().setVisible(False) # ATTACH AXES TO SERIES self.series.attachAxis(xAxis) self.series.attachAxis(yAxis) # ADD CHART TO A VIEW chartView = QChartView(self.chart) labelLayout = QFrame() labelLayout.setStyleSheet("background-color: white; border-radius: 20px") layout1 = QVBoxLayout() labelLayout.setLayout(layout1) layout2 = QHBoxLayout() layout3 = QHBoxLayout() for i in range(5): label = QLabel("Sensor {}".format(i+1)) label.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) label.setStyleSheet("font-weight: bold;") layout2.addWidget(label) value = QLabel("0 mV") value.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) self.labelWidgets.append(value) layout3.addWidget(value) layout1.addLayout(layout2, 1) layout1.addLayout(layout3, 1) parentLayout.addLayout(buttonLayout) parentLayout.addWidget(chartView, 5) parentLayout.addWidget(labelLayout, 1) # LINK WIDGETS self.connectButton.clicked.connect(self.serialToggle) self.calibrateButton.clicked.connect(self.sensorCalibrate) self.setLayout(parentLayout) def getSensorReadings(self): """ PURPOSE Requests sensor readings from ROV and updates GUI. INPUT NONE RETURNS NONE """ # SENSOR POLLING RATE (HZ) refreshRate = 100 # START QTIMER TO REPEATEDLY UPDATE SENSORS AT THE DESIRED POLLING RATE self.timer = QTimer() self.timer.setTimerType(Qt.PreciseTimer) self.timer.timeout.connect(self.getSensorReadings) self.timer.start(int(1000*1/refreshRate)) # STOP REQUESTING SENSOR VALUES IF ROV IS DISCONNECTED if self.commsStatus == False: self.timer.stop() else: # REQEST SINGLE READING sensorReadings = self.getSensors() # UPDATE VOLTAGE READINGS self.updateVoltageReadings(sensorReadings) # SCALE SENSOR READINGS scaledReadings = self.mapPressureReadings(sensorReadings) try: # UPDATE GUI self.series.remove(self.bars) self.bars = QBarSet("") self.bars.append([float(item) for item in scaledReadings]) self.series.append(self.bars) except: self.teensyDisconnect() def mapPressureReadings(self, values): mappedValues = [] for value in values: try: mappedValues.append((200/1023)*float(value) - 100) except: pass return mappedValues def updateVoltageReadings(self, values): voltageValues = [round((3300/1023)*float(i)) for i in values] for i, label in enumerate(self.labelWidgets): label.setText(str(voltageValues[i]) + " mV") def serialToggle(self, buttonState): """ PURPOSE Determines whether to connect or disconnect from the ROV serial interface. INPUT - buttonState = the state of the button (checked or unchecked). RETURNS NONE """ # CONNECT if buttonState: self.teensyConnect() # DISCONNECT else: self.teensyDisconnect() def sensorCalibrate(self): """ PURPOSE INPUT RETURNS """ self.calibrateSensors() ######################## ### SERIAL FUNCTIONS ### ######################## def teensyConnect(self): """ PURPOSE Attempts to connect to the ROV using the comms library. Changes the appearance of the connect buttons. If connection is successful, the ROV startup procedure is initiated. INPUT NONE RETURNS NONE """ # DISABLE BUTTONS TO AVOID DOUBLE CLICKS self.connectButton.setEnabled(False) # FIND ALL AVAILABLE COM PORTS availableComPorts, comPort, identity = self.findComPorts(115200, self.deviceID) print(availableComPorts, comPort, identity) # ATTEMPT CONNECTION TO ROV COM PORT status, message = self.serialConnect(comPort, 115200) print(status, message) # IF CONNECTION IS SUCCESSFUL if status == True: # MODIFY BUTTON STYLE self.connectButton.setText('DISCONNECT') # START READING SENSOR VALUES self.getSensorReadings() # IF CONNECTION IS UNSUCCESSFUL else: self.teensyDisconnect() # RE-ENABLE CONNECT BUTTONS self.connectButton.setEnabled(True) def teensyDisconnect(self): """ PURPOSE Disconnects from the ROV using the comms library. Changes the appearance of the connect buttons INPUT NONE RETURNS NONE """ # MODIFY BUTTON STYLE self.connectButton.setText('CONNECT') self.connectButton.setChecked(False) # CLOSE COM PORT if self.commsStatus: self.comms.close() self.commsStatus = False def findComPorts(self, baudRate, identity): """ PURPOSE Find all available COM ports and requests the devices identity. INPUT - menuObject = pointer to the drop down menu to display the available COM ports. - baudRate = baud rate of the serial interface. - identity = string containing the required device identity to connect to. RETURNS - availableComPorts = list of all the available COM ports. - rovComPort = the COM port that belongs to the device. - identity = the devices response from an identity request. """ # CREATE LIST OF ALL POSSIBLE COM PORTS ports = ['COM%s' % (i + 1) for i in range(256)] deviceIdentity = "" comPort = None availableComPorts = [] # CHECK WHICH COM PORTS ARE AVAILABLE for port in ports: try: comms = serial.Serial(port, baudRate, timeout = 1) availableComPorts.append(port) # REQUEST IDENTITY FROM COM PORT self.commsStatus = True deviceIdentity = self.getIdentity(comms, identity) comms.close() self.commsStatus = False # FIND WHICH COM PORT IS THE ROV if deviceIdentity == identity: comPort = port break # SKIP COM PORT IF UNAVAILABLE except (OSError, serial.SerialException): pass return availableComPorts, comPort, deviceIdentity def getIdentity(self, serialInterface, identity): """ PURPOSE Request identity from a defined COM port. INPUT - serialInterface = pointer to the serial interface object. - identity = the desired identity response from the device connected to the COM port. RETURNS - identity = the devices response. """ identity = "" startTime = datetime.now() elapsedTime = 0 # REPEATIDELY REQUEST IDENTIFICATION FROM DEVICE FOR UP TO 3 SECONDS while (identity == "") and (elapsedTime < 3): self.serialSend("?I", serialInterface) identity = self.serialReceive(serialInterface) elapsedTime = (datetime.now() - startTime).total_seconds() return identity def serialConnect(self, comPort, baudRate): """ PURPOSE Attempts to initialise a serial communication interface with a desired COM port. INPUT - rovComPort = the COM port of the ROV. - baudRate = the baud rate of the serial interface. RETURNS NONE """ self.commsStatus = False if comPort != None: try: self.comms = serial.Serial(comPort, baudRate, timeout = 1) message = "Connection to ROV successful." self.commsStatus = True except: message = "Failed to connect to {}.".format(comPort) else: message = "Failed to recognise device identity." return self.commsStatus, message def serialSend(self, command, serialInterface): """ PURPOSE Sends a string down the serial interface to the ROV. INPUT - command = the command to send. - serialInterface = pointer to the serial interface object. RETURNS NONE """ if self.commsStatus: try: serialInterface.write((command + '\n').encode('ascii')) except: self.teensyDisconnect() print("Failed to send command.") def serialReceive(self, serialInterface): """ PURPOSE Waits for data until a newline character is received. INPUT - serialInterface = pointer to the serial interface object. RETURNS NONE """ received = "" try: received = serialInterface.readline().decode('ascii').strip() except: self.teensyDisconnect() print("Failed to receive data.") return(received) def getSensors(self): """ PURPOSE Send request to device to return sensor readings. INPUT NONE RETURNS - results = array containing the sensor readings. """ results = [] # REQUEST SENSOR READINGS command = "?S" self.serialSend(command, self.comms) # READ RESPONSE INTO AN ARRAY results = self.serialReceive(self.comms).split(",") print(results) return results def calibrateSensors(self): """ """ # REQUEST SENSOR READINGS command = "?C" self.serialSend(command, self.comms)
def createBar(self, MainWindow): dp = DataProc() # print(dp.linked) linked_list = dp.linked['Beam Diff'].values.tolist() # print(linked_list) count = [0] * 200 # print(count) for item in linked_list: if item <= 160: count[int(item)] += 1 set0 = QBarSet('Beam Difference') # set0.setColor(QColor("blue")) # add pen width to bar pen = QPen(QColor(0xfdb157)) pen.setWidth(5) set0.setPen(pen) # set1 = QBarSet('X1') set0.append(count) # set0.append([random.randint(0, 10) for i in range(6)]) series = QBarSeries() series.append(set0) # series.barWidth() # series.append(set1) # Getting the Chart chart = QChart() # Getting the Chart # add font to title font = QFont() font.setPixelSize(18) chart.setTitleFont(font) chart.addSeries(series) # Add data chart.setTitle('Linked Bags Histogram') # Set title chart.setAnimationOptions(QChart.SeriesAnimations) # Set animation # months = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun') # Set custom axis times = [ '0-20', '20-40', '40-60', '60-80', '80-100', '100-120', '120-140', '140-160' ] # Set x-axis axisX = QBarCategoryAxis() # axisX.append(months) axisX.append(times) # Set y-axis # axisY = QValueAxis() # axisY.setRange(0, 200) # Alignment for x,y axis chart.addAxis(axisX, Qt.AlignBottom) # chart.addAxis(axisY, Qt.AlignLeft) # Enable legend and set custom axis alignment to bottom chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) # Create ChartView chartView = QChartView(chart) # add rendering # chartView.setRenderHint(QPainter.Antialiasing) # Set view at the center of MainWindw (show view) MainWindow.setCentralWidget(chartView)
## a written agreement between you and Digia. ## $QT_END_LICENSE$ ## ############################################################################# import sys from PyQt5.QtChart import (QBarCategoryAxis, QBarSeries, QBarSet, QChart, QChartView) from PyQt5.QtCore import Qt from PyQt5.QtGui import QPainter from PyQt5.QtWidgets import QApplication, QMainWindow app = QApplication(sys.argv) set0 = QBarSet("Jane") set1 = QBarSet("John") set2 = QBarSet("Axel") set3 = QBarSet("Mary") set4 = QBarSet("Samantha") set0 << 1 << 2 << 3 << 4 << 5 << 6 set1 << 5 << 0 << 0 << 4 << 0 << 7 set2 << 3 << 5 << 8 << 13 << 8 << 5 set3 << 5 << 6 << 7 << 3 << 4 << 5 set4 << 9 << 7 << 5 << 3 << 1 << 2 series = QBarSeries() series.append(set0) series.append(set1) series.append(set2)
def _create_reviews_due_chart(self): ## TODO: later replace by date selector start, end, chunk = 0, 31, 1 stats = CollectionStats(self.col) ## TODO: refactor stats._due categories_labels = list(range(0, 31, 1)) data = stats.due(start, end, chunk) data = self._transform_first_column_to_key(data) data = self._add_default_value_for_missing_keys( data, [0, 0, 0, 0], categories_labels) series = QStackedBarSeries(self) setYoung = QBarSet("Young", self) [setYoung.append(row[0]) for row in data] setAdolescent = QBarSet("Adolescent", self) [setAdolescent.append(row[1]) for row in data] setMature = QBarSet("Mature", self) [setMature.append(row[2]) for row in data] setOld = QBarSet("Old", self) [setOld.append(row[3]) for row in data] categories = QBarCategoryAxis() categories.setCategories([str(i) for i in categories_labels]) series.append(setOld) series.append(setMature) series.append(setAdolescent) series.append(setYoung) chart = QChart() chart.addSeries(series) chart.createDefaultAxes() chart.setAxisX(categories, series) chart.setAnimationOptions(QChart.SeriesAnimations) chart.setTitle("Forecast: the number of reviews due in the future") chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) chartview = QChartView(chart) chartview.setRenderHint(QPainter.Antialiasing) self.layout.addWidget(chartview)
def setData(self, timeData, valueData, chartTypes="Bar"): axisX = QDateTimeAxis() axisX.setFormat("yyyy-MM-dd") if self.chartTypes == "Bar": # Clear all series self.clearAll() self.zoomSeries = QLineSeries(self.chart()) barSeries = QBarSeries(self.chart()) barset = QBarSet("data") barSeries.setBarWidth(0.8) barSeries.append(barset) for td, vd in zip(timeData, valueData): self.zoomSeries.append(td.toMSecsSinceEpoch(), vd) barset.append(valueData) self.zoomSeries.hide() self.chart().addSeries(self.zoomSeries) self.chart().addSeries(barSeries) self.chart().setAxisY(QValueAxis(), self.zoomSeries) axisX.setRange(min(timeData), max(timeData)) self.chart().setAxisX(axisX, self.zoomSeries) elif self.chartTypes == "Scatter": # Clear all series self.clearAll() self.zoomSeries = QLineSeries(self.chart()) scattSeries = QScatterSeries(self.chart()) scattSeries.setMarkerSize(8) for td, vd in zip(timeData, valueData): self.zoomSeries.append(td.toMSecsSinceEpoch(), vd) scattSeries.append(td.toMSecsSinceEpoch(), vd) self.zoomSeries.hide() self.chart().addSeries(self.zoomSeries) self.chart().addSeries(scattSeries) self.chart().setAxisY(QValueAxis(), self.zoomSeries) axisX.setRange(min(timeData), max(timeData)) self.chart().setAxisX(axisX, self.zoomSeries) elif self.chartTypes in ["Line", "PLine"]: self.clearAll() if self.chartTypes == "Line": self.zoomSeries = QLineSeries(self.chart()) else: self.zoomSeries = QSplineSeries(self.chart()) for td, vd in zip(timeData, valueData): self.zoomSeries.append(td.toMSecsSinceEpoch(), vd) self.chart().addSeries(self.zoomSeries) self.chart().setAxisY(QValueAxis(), self.zoomSeries) axisX.setRange(min(timeData), max(timeData)) self.chart().setAxisX(axisX, self.zoomSeries) elif self.chartTypes == "Area": self.clearAll() self.zoomSeries = QLineSeries() self.zoomSeries.setColor(QColor("#666666")) for td, vd in zip(timeData, valueData): self.zoomSeries.append(td.toMSecsSinceEpoch(), vd) areaSeries = QAreaSeries(self.zoomSeries, None) self.chart().addSeries(self.zoomSeries) self.chart().addSeries(areaSeries) self.chart().setAxisY(QValueAxis(), areaSeries) axisX.setRange(min(timeData), max(timeData)) self.chart().setAxisX(axisX, areaSeries) self.zoomSeries.hide() self.mintimeData = min(timeData) self.maxtimeData = max(timeData) self.BtnsWidget.dateRangeEdit.setDateRange([ self.mintimeData.toString("yyyy-MM-dd"), self.maxtimeData.toString("yyyy-MM-dd"), ]) self.updateView()
def _create_revision_count_graph(self): stats = CollectionStats(self.col) categories_labels = list(range(-30, 1, 1)) data = stats.revision_count_stats() data = self._transform_first_column_to_key(data) data = self._add_default_value_for_missing_keys( data, [0, 0, 0, 0, 0], categories_labels) series = QStackedBarSeries(self) setLearning = QBarSet("Learning", self) [setLearning.append(row[0]) for row in data] setYoung = QBarSet("Young", self) [setYoung.append(row[1]) for row in data] setMature = QBarSet("Mature", self) [setMature.append(row[2]) for row in data] setLapse = QBarSet("Lapse", self) [setLapse.append(row[3]) for row in data] setEarly = QBarSet("Early", self) [setEarly.append(row[4]) for row in data] categories = QBarCategoryAxis() categories.setCategories([str(-i) for i in categories_labels]) series.append(setLearning) series.append(setYoung) series.append(setMature) series.append(setLapse) series.append(setEarly) chart = QChart() chart.addSeries(series) chart.createDefaultAxes() chart.setAxisX(categories, series) chart.setAnimationOptions(QChart.SeriesAnimations) chart.setTitle("Number of cards reviewed recently") chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) chartview = QChartView(chart) chartview.setRenderHint(QPainter.Antialiasing) self.layout.addWidget(chartview)
def add_set(self, label, values): # print('adding bar set') my_set = QBarSet(label, self) my_set.append(values) self.series.append(my_set)
def initChart(self): self._chart = QChart(title='数量') self._chart.setAnimationOptions(QChart.SeriesAnimations) series = QStackedBarSeries() series.setName('数量') bar_red = QBarSet('red') bar_red.setColor(Qt.red) bar_green = QBarSet('green') bar_green.setColor(Qt.green) for _, stock in self.stocks.iterrows(): if stock['open'] < stock['close']: bar_red.append(stock['vol'] / 100) bar_green.append(0) else: bar_red.append(0) bar_green.append(stock['vol'] / 100) series.append(bar_red) series.append(bar_green) self._chart.addSeries(series) self._chart.createDefaultAxes() self._chart.setLocalizeNumbers(True) axis_x = self._chart.axisX() axis_y = self._chart.axisY() axis_x.setGridLineVisible(False) axis_y.setGridLineVisible(False) axis_y.setLabelFormat("%.2f") axis_x.setCategories(self.category) max_p = self.stocks[[ 'vol', ]].stack().max() / 100 + 10 min_p = self.stocks[[ 'vol', ]].stack().min() / 100 - 10 axis_y.setRange(min_p, max_p) # chart的图例 legend = self._chart.legend() legend.hide() # 设置图例由Series来决定样式 # legend.setMarkerShape(QLegend.MarkerShapeFromSeries) self.setChart(self._chart) self._chart.layout().setContentsMargins(0, 0, 0, 0) # self._chart.setMargins(QMargins(0, 0, 0, 0)) self._chart.setBackgroundRoundness(0)
def show_proportional_chart(self): type_diagram = self.pushButton_3.text() self.student_diagram_window.hide() if type_diagram == "Отобразить диаграмму в пропорциях": student = self.label_4.text() session = self.label_7.text() period = self.label_8.text() control = Control() result: np.ndarray = control.analysis_student_proportional(self.session, student, session, period) r_len = len(result) set0 = QBarSet('0-24') set1 = QBarSet('25-49') set2 = QBarSet('50-74') set3 = QBarSet('75-100') if r_len == 4: set0 << int(result[0][1]) << int(result[1][1]) << int(result[2][1]) << int(result[3][1]) set1 << int(result[0][2]) << int(result[1][2]) << int(result[2][2]) << int(result[3][2]) set2 << int(result[0][3]) << int(result[1][3]) << int(result[2][3]) << int(result[3][3]) set3 << int(result[0][4]) << int(result[1][4]) << int(result[2][4]) << int(result[3][4]) elif r_len == 3: set0 << int(result[0][1]) << int(result[1][1]) << int(result[2][1]) set1 << int(result[0][2]) << int(result[1][2]) << int(result[2][2]) set2 << int(result[0][3]) << int(result[1][3]) << int(result[2][3]) set3 << int(result[0][4]) << int(result[1][4]) << int(result[2][4]) elif r_len == 2: set0 << int(result[0][1]) << int(result[1][1]) set1 << int(result[0][2]) << int(result[1][2]) set2 << int(result[0][3]) << int(result[1][3]) set3 << int(result[0][4]) << int(result[1][4]) else: set0 << int(result[0][1]) set1 << int(result[0][2]) set2 << int(result[0][3]) set3 << int(result[0][4]) cat = [] for i in result: cat.append(i[0]) series = QPercentBarSeries() series.append(set0) series.append(set1) series.append(set2) series.append(set3) chart = QChart() chart.addSeries(series) chart.setAnimationOptions(QChart.SeriesAnimations) axis = QBarCategoryAxis() axis.append(cat) chart.createDefaultAxes() chart.setAxisX(axis, series) chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) centralwidget = self.centralwidget self.chartview = QChartView(chart, centralwidget) self.chartview.setGeometry(QtCore.QRect(10, 110, 880, 371)) else: series = QPieSeries() for i in self.data: value = str(i[0]) + " / " + str(i[1]) series.append(value, float(i[1])) # adding slice slice = QPieSlice() slice = series.slices()[0] slice.setExploded(True) slice.setLabelVisible(True) slice.setPen(QPen(Qt.darkGreen, 2)) slice.setBrush(Qt.green) chart = QChart() chart.legend().hide() chart.addSeries(series) chart.createDefaultAxes() chart.setAnimationOptions(QChart.SeriesAnimations) chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) centralwidget = self.centralwidget self.chartview = QChartView(chart, centralwidget) self.chartview.setGeometry(QtCore.QRect(10, 110, 880, 371)) self.pushButton_3.hide() self.student_diagram_window.show()
def __init__(self, parent): super(QWidget, self).__init__(parent) self.layout = QVBoxLayout(self) # Initialize tab screen self.tabs = QTabWidget() self.tab1 = QWidget() self.tab2 = QWidget() self.tab3 = QWidget() self.tab4 = QWidget() self.tab5 = QWidget() self.tab6 = QWidget() self.tabs.resize(300, 200) self.pushButton_2 = QPushButton() self.pushButton_2.resize(0, 200) # Add tabs self.tabs.addTab(self.tab1, "Reservaciones por ciclo") self.tabs.addTab(self.tab2, "Reservaciones por Laboratorio") self.tabs.addTab(self.tab3, "Horas de uso") self.tabs.addTab(self.tab4, "Horas de uso por laboratorio") self.tabs.addTab(self.tab5, "Estudiantes") self.tabs.addTab(self.tab6, "Horas de uso por mes") # Create first tab # Gráficos de reservaciones por ciclo--------------------------------------------------------------------------- self.tab1.layout = QVBoxLayout(self) self.conn = connector() # Generar el conector df_1 = reservacionesPorCiclo( self.conn ) # Se realiza la consulta y se devuelve en formato DataFrame val_max_g1 = df_1['contador'].max( ) # Se determina el valor maximo de columna para generar el rango maximo del eje Y lista_periodos_g1 = [ ] # Estrucuta que almacenara las etiquetas y valores para cada periodo series = QBarSeries( ) # Estructura donde se almacena los valores de cada serie for index, row in df_1.iterrows( ): # Bucle para almanceanar los datos en la estructura dada por PyChart lista_periodos_g1.append(QBarSet(row['Periodo'])) lista_periodos_g1[index].append(row['contador']) series.append(lista_periodos_g1[index]) chart = QChart() chart.addSeries(series) chart.setTitle('Reservaciones por ciclo') chart.setAnimationOptions(QChart.SeriesAnimations) text = ('Períodos') axisX = QBarCategoryAxis() axisX.append(text) axisY = QValueAxis() axisY.setRange(0, val_max_g1) chart.addAxis(axisX, Qt.AlignBottom) chart.addAxis(axisY, Qt.AlignLeft) chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) self.chartView = QChartView(chart) self.tab1.layout.addWidget(self.chartView) self.tab1.setLayout(self.tab1.layout) #Reservaciones por laboratorio------------------------------------------------------------------------- self.tab2.layout = QVBoxLayout(self) list_QBarSet_g2 = [] # Estructura de datos para graficar df_contarPeriodos = contarPeriodos(self.conn) df_contarLaboratorios = contarLaboratorios(self.conn) df_g2 = reservacionesPorLaboratorio(self.conn) val_max_g2 = df_g2['contador'].max( ) # Se determina el valor maximo de columna para generar el rango maximo del eje Y for index, row in df_contarPeriodos.iterrows(): list_QBarSet_g2.append(QBarSet(row['Periodo'])) series_bar = QBarSeries() lis_laboratorio = ( ) # Estructura para almacenar los nombres de los laboratorio lis_laboratorio = list(lis_laboratorio) for index, row in df_contarLaboratorios.iterrows(): lis_laboratorio.insert(index, row["Image"]) for index_2, row_2 in df_contarPeriodos.iterrows(): find_value = df_g2.loc[ (df_g2['Periodo'] == str(row_2["Periodo"])) & (df_g2['Image'] == str(row["Image"]))] if find_value.empty: list_QBarSet_g2[index_2].append(0) else: value_get = find_value['contador'].iloc[0] list_QBarSet_g2[index_2].append(value_get) for index_3, row in df_contarPeriodos.iterrows(): series_bar.append(list_QBarSet_g2[index_3]) chart = QChart() chart.addSeries(series_bar) chart.setTitle('Reservaciones por laboratorio') chart.setAnimationOptions(QChart.SeriesAnimations) axisX = QBarCategoryAxis() axisX.append(lis_laboratorio) axisY = QValueAxis() axisY.setRange(0, val_max_g2) chart.addAxis(axisX, Qt.AlignBottom) chart.addAxis(axisY, Qt.AlignLeft) chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) self.chartView_2 = QChartView(chart) self.tab2.layout.addWidget(self.chartView_2) self.tab2.setLayout(self.tab2.layout) # Gráficos de horas de uso--------------------------------------------------------------------------- self.tab3.layout = QVBoxLayout(self) df_3 = horasDeUso( self.conn ) # Se realiza la consulta y se devuelve en formato DataFrame val_max_g3 = df_3['contador'].max( ) # Se determina el valor maximo de columna para generar el rango maximo del eje Y lista_periodos_g3 = [ ] # Estrucuta que almacenara las etiquetas y valores para cada periodo series_3 = QBarSeries( ) # Estructura donde se almacena los valores de cada serie for index, row in df_3.iterrows( ): # Bucle para almanceanar los datos en la estructura dada por PyChart lista_periodos_g3.append(QBarSet(row['Periodo'])) lista_periodos_g3[index].append(row['contador']) series_3.append(lista_periodos_g3[index]) chart = QChart() chart.addSeries(series_3) chart.setTitle('Horas de uso') chart.setAnimationOptions(QChart.SeriesAnimations) text = ('Períodos') axisX = QBarCategoryAxis() axisX.append(text) axisY = QValueAxis() axisY.setRange(0, val_max_g1) chart.addAxis(axisX, Qt.AlignBottom) chart.addAxis(axisY, Qt.AlignLeft) chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) self.chartView_3 = QChartView(chart) self.tab3.layout.addWidget(self.chartView_3) self.tab3.setLayout(self.tab3.layout) #Horas de Uso por laboratorio------------------------------------------------------------------------- self.tab4.layout = QVBoxLayout(self) list_QBarSet_g4 = [] # Estructura de datos para graficar df_g4 = horasDeUsoPorLaboratorio(self.conn) val_max_g4 = df_g4['contador'].max( ) # Se determina el valor maximo de columna para generar el rango maximo del eje Y #val_min_g4 = df_g4['contador'].min() # Se determina el valor maximo de columna para generar el rango maximo del eje Y for index, row in df_contarPeriodos.iterrows(): list_QBarSet_g4.append(QBarSet(row['Periodo'])) series_bar_4 = QBarSeries() lis_laboratorio = () lis_laboratorio = list(lis_laboratorio) for index, row in df_contarLaboratorios.iterrows(): lis_laboratorio.insert(index, row["Image"]) for index_2, row_2 in df_contarPeriodos.iterrows(): find_value = df_g4.loc[ (df_g4['Periodo'] == str(row_2["Periodo"])) & (df_g4['Image'] == str(row["Image"]))] if find_value.empty: list_QBarSet_g4[index_2].append(0) else: value_get = find_value['contador'].iloc[0] list_QBarSet_g4[index_2].append(value_get) for index_3, row in df_contarPeriodos.iterrows(): series_bar_4.append(list_QBarSet_g4[index_3]) chart = QChart() chart.addSeries(series_bar_4) chart.setTitle('Horas de Uso por laboratorio') chart.setAnimationOptions(QChart.SeriesAnimations) months = lis_laboratorio axisX = QBarCategoryAxis() axisX.append(months) axisY = QValueAxis() axisY.setRange(0, val_max_g4) chart.addAxis(axisX, Qt.AlignBottom) chart.addAxis(axisY, Qt.AlignLeft) chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) self.chartView_4 = QChartView(chart) self.tab4.layout.addWidget(self.chartView_4) self.tab4.setLayout(self.tab4.layout) # Gráficos de Estudiantes--------------------------------------------------------------------------- self.tab5.layout = QVBoxLayout(self) df_5 = estudiantes( self.conn ) # Se realiza la consulta y se devuelve en formato DataFrame val_max_g5 = df_5['contador'].max( ) # Se determina el valor maximo de columna para generar el rango maximo del eje Y lista_periodos_g5 = [ ] # Estrucuta que almacenara las etiquetas y valores para cada periodo series_5 = QBarSeries( ) # Estructura donde se almacena los valores de cada serie for index, row in df_5.iterrows( ): # Bucle para almanceanar los datos en la estructura dada por PyChart lista_periodos_g5.append(QBarSet(row['Periodo'])) lista_periodos_g5[index].append(row['contador']) series_5.append(lista_periodos_g5[index]) chart = QChart() chart.addSeries(series_5) chart.setTitle('Estudiantes') chart.setAnimationOptions(QChart.SeriesAnimations) text = ('Período') axisX = QBarCategoryAxis() axisX.append(text) axisY = QValueAxis() axisY.setRange(0, val_max_g5) chart.addAxis(axisX, Qt.AlignBottom) chart.addAxis(axisY, Qt.AlignLeft) chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) self.chartView_5 = QChartView(chart) self.tab5.layout.addWidget(self.chartView_5) self.tab5.setLayout(self.tab5.layout) #Horas de uso por mes---------------------------------------------------------------------------------------- self.tab6.layout = QVBoxLayout(self) df_6 = horasUsoPorMes(self.conn) val_max_g6 = df_6['contador'].max( ) # Se determina el valor maximo de columna para generar el rango maximo del eje Y series_6 = QLineSeries( ) # Estructura donde se almacena los valores de cada serie lis_mes_ano = () # Estructura para almacenar mes y el año lis_mes_ano = list(lis_mes_ano) for index, row in df_6.iterrows( ): # Bucle para almanceanar los datos en la estructura dada por PyChart lis_mes_ano.insert( index, str(int(row['Ano'])) + "/" + str(int(row['Mes']))) series_6.append((index + 1), row['contador']) chart = QChart() chart.addSeries(series_6) chart.setTitle('Horas de Uso por Mes') chart.setAnimationOptions(QChart.SeriesAnimations) axisX = QBarCategoryAxis() axisX.append(lis_mes_ano) # monthos axisY = QValueAxis() axisY.setRange(0, val_max_g6) chart.addAxis(axisX, Qt.AlignBottom) chart.addAxis(axisY, Qt.AlignLeft) chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) self.chartView_6 = QChartView(chart) self.tab6.layout.addWidget(self.chartView_6) self.tab6.setLayout(self.tab6.layout) self.layout.addWidget(self.tabs) self.setLayout(self.layout)
class QtHistogram(QChartView): def __init__(self, spec): super().__init__(None) self.spec = spec self.chart = QChart() self.chart.setTitle(self.spec.variable) self.chart.legend().hide() self.mainset = QBarSet("") self.mainset.append([0] * len(spec.bins)) self.mainset.setColor( QColor(spec.color[0], spec.color[1], spec.color[2])) self.series = QBarSeries() self.series.append(self.mainset) self.setMinimumWidth(400) self.setMinimumHeight(230) self.y_ranges = [0, 1, 5, 10, 25, 50, 100, 250, 500, 1000] self.max_y = 1000 self.max_y_range = 1000 self.lookback = 30 self.recent_max_y = deque([self.max_y_range] * self.lookback) font = QtGui.QFont() font.setPixelSize(10) self.axis_x = QBarCategoryAxis() self.axis_x.setLabelsAngle(-90) self.axis_x.setLabelsFont(font) self.axis_y = QValueAxis() self.axis_y.setRange(0, self.max_y) self.axis_x.append(map(str, spec.bins)) self.chart.addSeries(self.series) self.chart.setAxisX(self.axis_x, self.series) self.chart.setAxisY(self.axis_y, self.series) self.setChart(self.chart) self.setRenderHint(QPainter.Antialiasing) self._updates_per_second = 10 self._dataset = [] def clear(self): self._dataset = [] def update_data(self, dataset): data = [] for d in dataset: data.append(d) self._dataset = data def redraw(self): if len(self._dataset) > 0: for i in range(len(self._dataset)): self.mainset.replace(i, self._dataset[i]) # Calculate max of current values max_y_range = max(self._dataset) # Store max value self.recent_max_y.appendleft(max_y_range) if len(self.recent_max_y) > self.lookback: self.recent_max_y.pop() # Set max based on the last 30 max values, # to avoid flickering self.max_y_range = max(self.recent_max_y) y_range = bisect.bisect_left(self.y_ranges, self.max_y_range) if y_range < len(self.y_ranges): self.max_y = self.y_ranges[y_range] elif max_y_range > self.max_y: self.max_y += self.max_y elif max_y_range < self.max_y / 2: self.max_y = self.max_y / 2 self.axis_y.setRange(0, self.max_y)
def __actualizar_grafico_barras(self): self.grafico.legend().setVisible(True) medias = [ math.floor(np.mean(datos)) if len(datos) > 0 else 0 for datos in self.datos.values() ] mejores = [ np.min(datos) if len(datos) > 0 else 0 for datos in self.datos.values() ] peores = [ np.max(datos) if len(datos) > 0 else 0 for datos in self.datos.values() ] self.eje_y.setRange(1, max(max(medias), max(peores))) barset_media = QBarSet('Media') barset_media.append(medias) barset_mejor = QBarSet('Mejor') barset_mejor.append(mejores) barset_peor = QBarSet('Peor') barset_peor.append(peores) series = QBarSeries() series.append(barset_media) series.append(barset_mejor) series.append(barset_peor) series.setLabelsVisible(True) self.grafico.addSeries(series) series.attachAxis(self.eje_y) self.init_grafico()