def __init__(self, image, parent=None): super(ToolWidget, self).__init__(parent) max_q = 101 progress = QProgressDialog(self.tr('Computing residuals...'), None, 0, max_q, self) progress.setWindowModality(Qt.WindowModal) loss_series = QtCharts.QLineSeries() gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY) for q in range(max_q): loss = cv.mean(cv.absdiff(compress_img(gray, q, color=False), gray)) loss_series.append(q, loss[0]) progress.setValue(q) progress.setValue(max_q) loss_chart = QtCharts.QChart() loss_chart.legend().hide() loss_chart.setTitle(self.tr('Loss vs Compression')) loss_chart.addSeries(loss_series) loss_chart.createDefaultAxes() loss_chart.axisX().setRange(0, 100) loss_chart.axisX().setTitleText(self.tr('quality (%)')) loss_chart.axisX().setTickCount(11) loss_chart.axisX().setLabelFormat('%d') loss_chart.axisY().setTitleText(self.tr('loss (%)')) loss_chart.setMinimumSize(600, 400) font = loss_chart.titleFont() font.setBold(True) loss_chart.setTitleFont(font) loss_view = QtCharts.QChartView(loss_chart) loss_view.setRenderHint(QPainter.Antialiasing) main_layout = QVBoxLayout() main_layout.addWidget(loss_view) self.setLayout(main_layout)
def add_series(self, name, columns): # Create QLineSeries self.series = QtCharts.QLineSeries() self.series.setName(name) # Filling QLineSeries for i in range(self.model.rowCount()): # Getting the data t = self.model.index(i, 0).data() data_fmt = "yyyy-MM-dd HH:mm:ss.zzz" x = QDateTime().fromString(t, data_fmt).toMSecsSinceEpoch() y = float(self.model.index(i, 1).data()) if x > 0 and y > 0: self.series.append(x, y) self.chart.addSeries(self.series) # Setting X-axis self.axis_x = QtCharts.QDateTimeAxis() self.axis_x.setTickCount(10) self.axis_x.setFormat("dd.MM (h:mm)") self.axis_x.setTitleText("Date") self.chart.addAxis(self.axis_x, Qt.AlignBottom) self.series.attachAxis(self.axis_x) # Setting Y-axis self.axis_y = QtCharts.QValueAxis() self.axis_y.setTickCount(10) self.axis_y.setLabelFormat("%.2f") self.axis_y.setTitleText("Magnitude") self.chart.addAxis(self.axis_y, Qt.AlignLeft) self.series.attachAxis(self.axis_y) # Gettign the color from the QChart to use it on the QTableView self.model.color = "{}".format(self.series.pen().color().name())
def __init__(self, device): super(MainWindow, self).__init__() self.series = QtCharts.QLineSeries() self.chart = QtCharts.QChart() self.chart.addSeries(self.series) self.axisX = QtCharts.QValueAxis() self.axisX.setRange(0, sampleCount) self.axisX.setLabelFormat("%g") self.axisX.setTitleText("Samples") self.axisY = QtCharts.QValueAxis() self.axisY.setRange(-1, 1) self.axisY.setTitleText("Audio level") self.chart.setAxisX(self.axisX, self.series) self.chart.setAxisY(self.axisY, self.series) self.chart.legend().hide() self.chart.setTitle("Data from the microphone ({})".format( device.deviceName())) formatAudio = QAudioFormat() formatAudio.setSampleRate(8000) formatAudio.setChannelCount(1) formatAudio.setSampleSize(8) formatAudio.setCodec("audio/pcm") formatAudio.setByteOrder(QAudioFormat.LittleEndian) formatAudio.setSampleType(QAudioFormat.UnSignedInt) self.audioInput = QAudioInput(device, formatAudio, self) self.ioDevice = self.audioInput.start() self.ioDevice.readyRead.connect(self._readyRead) self.chartView = QtCharts.QChartView(self.chart) self.setCentralWidget(self.chartView) self.buffer = [QPointF(x, 0) for x in range(sampleCount)] self.series.append(self.buffer)
def add_series(self, chart, title, x, y): series = QtCharts.QLineSeries() series.setName(title) for idx, elem in enumerate(x): series.append(x[idx], y[idx]) chart.addSeries(series)
def plotMeterAvg(self, legendSelection): origEndIdx = legendSelection.find(':') category = legendSelection[0:origEndIdx] yearly = legendSelection[origEndIdx + 2:origEndIdx + 3] == "J" if len(self.plotData['Zählerstände'][category]) < 2: return avgLevelData = [] # compute average data lastDate = None lastLevel = None for entry in self.plotData['Zählerstände'][category]: date = entry['date'] level = entry['level'] if lastDate is None: lastDate = date lastLevel = level else: dayDiff = lastDate.daysTo(date) if yearly: averageFactor = dayDiff / 365.25 else: averageFactor = dayDiff / 30.44 averageLevel = (level - lastLevel) / averageFactor avgLevelData.append({'date': lastDate, 'level': averageLevel}) lastDate = date lastLevel = level chart = QtCharts.QChart() lineSeries = QtCharts.QLineSeries() for entry in avgLevelData: lineSeries.append(entry['date'].toMSecsSinceEpoch(), entry['level']) chart.addSeries(lineSeries) titleFont = QFont("Sans Serif") titleFont.setPointSize(16) titleFont.setBold(True) chart.setTitleFont(titleFont) if yearly: chart.setTitle("Jährlicher Verbrauch: " + category) else: chart.setTitle("Monatlicher Verbrauch: " + category) axisX = QtCharts.QDateTimeAxis() tickCount = min([12, len(avgLevelData)]) axisX.setTickCount(tickCount) axisX.setFormat("MM/yy") # axisX.setFormat("MMM yyyy") axisX.setTitleText("Ablesedatum") chart.setAxisX(axisX, lineSeries) # chart.addAxis(axisX, Qt.AlignBottom) # lineSeries.attachAxis(axisX) # axisX.setRange(self.plotDataTags[0], self.plotDataTags[-1]) axisY = QtCharts.QValueAxis() axisY.setLabelFormat("%i") if category == 'Strom': axisY.setTitleText("Stromverbrauch [kWh]") elif category == 'Gas': axisY.setTitleText("Gasverbrauch [m<sup>3</sup>]") elif category == 'Wasser': axisY.setTitleText("Wasserverbrauch [m<sup>3</sup>]") # if minVal < 0: # self.setYRange(maxVal, axisY, minVal) # else: # self.setYRange(maxVal, axisY) chart.setAxisY(axisY, lineSeries) # chart.addAxis(axisY, Qt.AlignLeft) # lineSeries.attachAxis(axisY) # axisY.setRange(0, 20) chart.legend().setVisible(False) # chart.legend().setAlignment(Qt.AlignRight) self.setChart(chart) self.setRenderHint(QPainter.Antialiasing) # draw the plot from scratch (if that makes a difference) print('Meter bar plot drawn')
def __init__(self, parent=None): super(NetworkGraph, self).__init__(parent) self.setScene(QGraphicsScene(self)) self.setDragMode(QGraphicsView.NoDrag) self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) #self.setFrameShape(QFrame.NoFrame) # Chart self._chart = QtCharts.QChart() self._chart.setBackgroundRoundness(0) self._chart.setMargins(QMargins( -28, -9, -11, -23)) # make sure the graphing area fills the whole chart view # self._chart.zoom(0.1) self._chart.setAnimationOptions(QtCharts.QChart.SeriesAnimations) self._chart.setTheme(QtCharts.QChart.ChartThemeDark) #self._chart.setMinimumSize(340, 280) #self._chart.setTitle("Hover the line to show callout. Click the line to make it stay") self._chart.legend().hide() # Series 1 self.series = QtCharts.QLineSeries() self.series.append(1, 3) self.series.append(4, 5) self.series.append(6, 2) self._chart.addSeries(self.series) # Series 2 self.series2 = QtCharts.QLineSeries() self.series2.append(4, 5) self.series2.append(5, 6) self._chart.addSeries(self.series2) # Scatter self.seriesS = QtCharts.QScatterSeries() self.seriesS.setMarkerShape(QtCharts.QScatterSeries.MarkerShapeCircle) self.seriesS.append(1, 3) self.seriesS.append(4, 5) self.seriesS.append(5, 6) self.seriesS.append(6, 2) self._chart.addSeries(self.seriesS) # Create axes and config grid invisible self._chart.createDefaultAxes() self.axes = self._chart.axes() for axis in self.axes: axis.setLabelsVisible(False) axis.setGridLineVisible(False) axis.setLineVisible(False) self._chart.setAcceptHoverEvents(True) # Add to scene self.setRenderHint(QPainter.Antialiasing) self.scene().addItem(self._chart) # Callout setup self._callouts = [] self._tooltip = Callout(self._chart) self.series.clicked.connect(self.keepCallout) self.series.hovered.connect(self.tooltip) self.series2.clicked.connect(self.keepCallout) self.series2.hovered.connect(self.tooltip) self.setMouseTracking(True)
def Create_MPP_Plot(self, data, name): parent = self.frame_3 self.graph_3 = QtCharts.QLineSeries(parent)
def __init__(self): global pixmapDict, specialDescriptionDict super(MainWindow, self).__init__() self.ui = Ui_pipboy() self.ui.setupUi(self) self.ui.chartContainer.setContentsMargins(0, 0, 0, 0) self.anim = QTimeLine(20000, self) self.anim.setFrameRange(0, 500) self.anim.setLoopCount(0) self.anim.setUpdateInterval(16) self.anim.frameChanged[int].connect( self.ui.perks_description.verticalScrollBar().setValue) self.anim.frameChanged[int].connect( self.ui.aid_effect_label.verticalScrollBar().setValue) self.anim.frameChanged[int].connect( self.ui.data_description.verticalScrollBar().setValue) #self.anim2 = QPropertyAnimation(self.ui.main_tab, b"pos") #self.anim2.setEasingCurve(QEasingCurve.OutBounce) #self.anim2.setDuration(2000) #self.anim2.setStartValue(QPoint(10, -400)) #self.anim2.setEndValue(QPoint(10, 0)) #self.anim2.start() self.random = QRandomGenerator.global_() self.ui.stat_tab.setFocus() self.ui.stat_tab.currentChanged.connect(self.shift) self.ui.stat_tab.installEventFilter(self) self.ui.inv_tab.installEventFilter(self) self.ui.special_list.installEventFilter(self) self.ui.perks_list.installEventFilter(self) self.ui.test_list.installEventFilter(self) self.ui.apparel_list.installEventFilter(self) self.ui.aid_list.installEventFilter(self) self.ui.ammo_list.installEventFilter(self) self.ui.data_list.installEventFilter(self) self.ui.radio_list.installEventFilter(self) self.ui.main_img.setPixmap(description.main_img_pixmap) self.ui.special_image.setPixmap(description.pixmapDict.get(0)) self.ui.perks_image.setPixmap(description.pixmatPerksDict.get(0)) self.ui.weapon_image.setPixmap(description.pixmapWeaponDict.get(0)) self.ui.apparel_image.setPixmap(description.pixmapWeaponDict.get(0)) self.ui.aid_image.setPixmap(description.pixmapAidDict.get(0)) self.ui.ammo_image.setPixmap(description.pixmapAmmoDict.get(0)) lay = QVBoxLayout(self.ui.chartContainer) lay.setContentsMargins(0, 0, 0, 0) self.chartview = QtCharts.QChartView() self.chartview.setContentsMargins(0, 0, 0, 0) lay.addWidget(self.chartview) self.chart = QtCharts.QChart() self.chart.legend().hide() self.chart.setAnimationOptions(QtCharts.QChart.SeriesAnimations) self.series = QtCharts.QLineSeries() self.pen = QPen(QColor(119, 251, 81, 255)) self.pen.setWidth(3) self.pen.setJoinStyle(Qt.RoundJoin) self.series.setPen(self.pen) backgroundGradient = QLinearGradient(QPointF(100, 100), QPointF(200, 200)) backgroundGradient.setColorAt(0, QColor(0, 0, 0, 255)) backgroundGradient.setColorAt(1, QColor(0, 0, 0, 255)) self.chart.setBackgroundBrush(backgroundGradient) self.chart.setPlotAreaBackgroundBrush(backgroundGradient) self.chart.addSeries(self.series) self.chart.createDefaultAxes() self.chart.axisX(self.series).setVisible(False) self.chart.axisY(self.series).setVisible(False) self.chart.axisY(self.series).setRange(0, 100) self.chartview.setChart(self.chart) self.play = False self.player = QMediaPlayer() self.playlistFalloutNewVegas = QMediaPlaylist(self.player) self.playlistFalloutNewVegas.addMedia( QMediaContent(description.falooutNewVegas)) self.playlistFalloutNewVegas.setCurrentIndex(1) self.playListMohaveMusic = QMediaPlaylist(self.player) for url in description.mohaveMusic: self.playListMohaveMusic.addMedia(QMediaContent(url)) self.playListMohaveMusic.setCurrentIndex(1) self.playlisNewVegas = QMediaPlaylist(self.player) for url in description.newVegas: self.playlisNewVegas.addMedia(QMediaContent(url)) self.playlisNewVegas.setCurrentIndex(1) self.playlistDict = { 0: self.playlistFalloutNewVegas, 1: self.playListMohaveMusic, 2: self.playlisNewVegas }
def init_gui(self): self.min = 0 self.max = 10 self.dat = [0] self.median_m = int() self.mean_m = int() self.mode_m = int() self.mode_list = [2, -34, 14, 14, 19, 15, -14, -13, 5] vbox = QVBoxLayout() print(self.median_m) layout = QHBoxLayout() text_layout = QHBoxLayout() self.median_ = QLabel(("Median: {0}".format(self.median_m))) self.mean_ = QLabel("Mean: {0}".format(self.mean_m)) self.mode_ = QLabel("Mode: {0}".format(mode(self.mode_list))) text_layout.addWidget(self.median_) text_layout.addWidget(self.mean_) text_layout.addWidget(self.mode_) vbox.addLayout(text_layout) central_widget = QWidget() self.chart = QtCharts.QChart() self.chart_view = QtCharts.QChartView() self.chart_view.setChart(self.chart) self.series = QtCharts.QLineSeries() self.chart_view.setRenderHint(QPainter.Antialiasing) self.chart.addSeries(self.series) axis_y = QtCharts.QValueAxis() axis_y.setTickCount(21) axis_y.setTickInterval(5) axis_y.setRange(-50, 50) self.chart.addAxis(axis_y, Qt.AlignLeft) axis_x = QtCharts.QValueAxis() axis_x.setTickCount(5) axis_x.setTickInterval(1) axis_x.setRange(self.min, self.max) self.chart.addAxis(axis_x, Qt.AlignBottom) self.series.attachAxis(axis_x) self.series.attachAxis(axis_y) self.series.setName("Temp") list_ = QListWidget() list_.addItem("Light theme") list_.addItem("Dark theme") list_.addItem("Sand theme") # list_.setSizePolicy(QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Preferred) list_.currentRowChanged.connect(self.clicked_theme) '''statistic_list = QListWidget() statistic_list.addItem("Median") statistic_list.addItem("Mode") statistic_list.addItem("Mean") # statistic_list.setSizePolicy(QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Preferred) statistic_list.currentRowChanged.connect(self.clicked_statistic)''' tab_widget = QTabWidget() tab_widget.addTab(list_, "Themes") # tab_widget.addTab(statistic_list, "Statistic data") tab_widget.setSizePolicy(QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Preferred) layout.addWidget(tab_widget) # layout.addWidget(list_) vbox.addWidget(self.chart_view) layout.addLayout(vbox) central_widget.setLayout(layout) self.setCentralWidget(central_widget)
def __init__(self): QWidget.__init__(self) self.ip = default_psu_ip self.channel = 1 layout_final = QVBoxLayout() #left top: ip text = QLabel("IPv4 Address:", self) text.setAlignment(Qt.AlignCenter) self.ip_input = QLineEdit(self.ip, self) top = QHBoxLayout() top.addWidget(text) top.addWidget(self.ip_input) #left bottom: channel text = QLabel("Channel:", self) self.channel_input = QLineEdit("{0}".format(self.channel), self) bottom = QHBoxLayout() bottom.addWidget(text) bottom.addWidget(self.channel_input) left = QVBoxLayout() left.addLayout(top) left.addLayout(bottom) #right: connect checkbox self.checkbox = QCheckBox("connect", self) layout = QHBoxLayout() layout.addLayout(left) layout.addWidget(self.checkbox) layout_final.addLayout(layout) #layout: Name text = QLabel("Name:", self) text.setAlignment(Qt.AlignRight) self.name = QLabel("", self) layout = QHBoxLayout() layout.addWidget(text) layout.addWidget(self.name) layout_final.addLayout(layout) #layout: Time text = QLabel("Time:", self) text.setAlignment(Qt.AlignRight) self.time = QLabel("", self) layout = QHBoxLayout() layout.addWidget(text) layout.addWidget(self.time) layout_final.addLayout(layout) #layout: target voltage text = QLabel("Target Voltage (V):", self) self.target_voltage_input = QLineEdit("", self) self.target_voltage_output = QLabel("", self) layout = QHBoxLayout() layout.addWidget(text) layout.addWidget(self.target_voltage_input) layout.addWidget(self.target_voltage_output) layout_final.addLayout(layout) #layout: output voltage text = QLabel("Output Voltage (V):", self) self.output_voltage = QLabel("", self) layout = QHBoxLayout() layout.addWidget(text) layout.addWidget(self.output_voltage) layout_final.addLayout(layout) #layout: current limit text = QLabel("Current Limit (mA):", self) self.current_limit_input = QLineEdit("", self) self.current_limit_output = QLabel("", self) layout = QHBoxLayout() layout.addWidget(text) layout.addWidget(self.current_limit_input) layout.addWidget(self.current_limit_output) layout_final.addLayout(layout) #layout: output current text = QLabel("Output Current (mA):", self) self.output_current = QLabel("", self) layout = QHBoxLayout() layout.addWidget(text) layout.addWidget(self.output_current) layout_final.addLayout(layout) #layout: switch output self.switch_input = QPushButton("Switch Output", self) self.switch_output = QLabel("", self) layout = QHBoxLayout() layout.addWidget(self.switch_input) layout.addWidget(self.switch_output) layout_final.addLayout(layout) #layout: ChartView chartView = QtCharts.QChartView() layout_final.addWidget(chartView) self.setLayout(layout_final) #signal and slot self.ip_input.returnPressed.connect(self.update_ip) self.channel_input.returnPressed.connect(self.update_channel) self.checkbox.stateChanged.connect(self.connect) self.target_voltage_input.returnPressed.connect( self.set_target_voltage) self.current_limit_input.returnPressed.connect(self.set_current_limit) self.switch_input.clicked.connect(self.toggle_switch) #Timer self.timer = QTimer(self) self.timer.timeout.connect(self.update_data) #Line Chart self.series_voltage = QtCharts.QLineSeries() self.series_current = QtCharts.QLineSeries() chart = QtCharts.QChart() chart.addSeries(self.series_voltage) chart.addSeries(self.series_current) chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignTop) markers = chart.legend().markers() markers[0].setLabel("Output Voltage") markers[1].setLabel("Output Current") #chart.setTitle("") self.axisX = QtCharts.QDateTimeAxis() self.axisX.setTickCount(5) self.axisX.setFormat("hh:mm:ss") self.axisX.setTitleText("Time") self.axisX.setMin(QDateTime().currentDateTime().addSecs(-60)) self.axisX.setMax(QDateTime().currentDateTime()) chart.addAxis(self.axisX, Qt.AlignBottom) self.series_voltage.attachAxis(self.axisX) self.series_current.attachAxis(self.axisX) axisY_voltage = QtCharts.QValueAxis() axisY_voltage.setTickCount(8) axisY_voltage.setLabelFormat("%.3f") axisY_voltage.setTitleText("Output Voltage (V)") axisY_voltage.setRange(0, 14) chart.addAxis(axisY_voltage, Qt.AlignLeft) self.series_voltage.attachAxis(axisY_voltage) axisY_current = QtCharts.QValueAxis() axisY_current.setTickCount(8) axisY_current.setLabelFormat("%i") axisY_current.setTitleText("Output Current (mA)") axisY_current.setRange(0, 700) chart.addAxis(axisY_current, Qt.AlignRight) self.series_current.attachAxis(axisY_current) chartView.setChart(chart) chartView.setRenderHint(QPainter.Antialiasing)
def __init__(self): QWidget.__init__(self) self.model = CustomTableModel() self.table_view = QTableView() self.table_view.setModel(self.model) self.table_view.horizontalHeader().setSectionResizeMode( QHeaderView.Stretch) self.table_view.verticalHeader().setSectionResizeMode( QHeaderView.Stretch) self.chart = QtCharts.QChart() self.chart.setAnimationOptions(QtCharts.QChart.AllAnimations) self.series = QtCharts.QLineSeries() self.series.setName("Line 1") self.mapper = QtCharts.QVXYModelMapper(self) self.mapper.setXColumn(0) self.mapper.setYColumn(1) self.mapper.setSeries(self.series) self.mapper.setModel(self.model) self.chart.addSeries(self.series) # for storing color hex from the series seriesColorHex = "#000000" # get the color of the series and use it for showing the mapped area seriesColorHex = "{}".format(self.series.pen().color().name()) self.model.add_mapping(seriesColorHex, QRect(0, 0, 2, self.model.rowCount())) # series 2 self.series = QtCharts.QLineSeries() self.series.setName("Line 2") self.mapper = QtCharts.QVXYModelMapper(self) self.mapper.setXColumn(2) self.mapper.setYColumn(3) self.mapper.setSeries(self.series) self.mapper.setModel(self.model) self.chart.addSeries(self.series) # get the color of the series and use it for showing the mapped area seriesColorHex = "{}".format(self.series.pen().color().name()) self.model.add_mapping(seriesColorHex, QRect(2, 0, 2, self.model.rowCount())) self.chart.createDefaultAxes() self.chart_view = QtCharts.QChartView(self.chart) self.chart_view.setRenderHint(QPainter.Antialiasing) self.chart_view.setMinimumSize(640, 480) # create main layout self.main_layout = QGridLayout() self.main_layout.addWidget(self.table_view, 1, 0) self.main_layout.addWidget(self.chart_view, 1, 1) self.main_layout.setColumnStretch(1, 1) self.main_layout.setColumnStretch(0, 0) self.setLayout(self.main_layout) self.thread_quote = ThreadQuote() self.thread_quote.test.connect(self.random_update) self.thread_quote.start()
def initUI(self): dataY = [ 9.030, 8.810, 9.402, 8.664, 8.773, 8.774, 8.416, 9.101, 8.687, 8.767 ] seriesList = [] series1 = QtCharts.QLineSeries() seriesList.append(series1) series2 = QtCharts.QScatterSeries() seriesList.append(series2) for i in range(len(dataY)): for series in seriesList: series.append(i + 1, dataY[i]) series1.setColor(QtGui.QColor('blue')) series2.setColor(QtGui.QColor('gray')) chart = QtCharts.QChart() for series in seriesList: chart.addSeries(series) chart.setTitle('SPC Chart Example') chart.setBackgroundBrush(QtGui.QColor("ivory")) chart.legend().hide() axisX = QtCharts.QValueAxis() axisX.setLinePenColor('gray') axisX.setTickCount(len(dataY) + 2) axisX.setRange(0, len(dataY) + 1) axisX.setLabelFormat('%d') axisX2 = QtCharts.QValueAxis() axisX2.setLinePenColor('gray') axisX2.setRange(0, len(dataY) + 1) axisX2.setLabelFormat(' ') ymax = max(dataY) ymin = min(dataY) yrange = ymax - ymin ydelta = yrange * 0.05 axisY = QtCharts.QValueAxis() axisY.setLinePenColor('gray') axisY.setRange(ymin - ydelta, ymax + ydelta) axisY2 = QtCharts.QValueAxis() axisY2.setLinePenColor('gray') axisY2.setRange(ymin - ydelta, ymax + ydelta) chart.addAxis(axisX, QtCore.Qt.AlignBottom) chart.addAxis(axisX2, QtCore.Qt.AlignTop) chart.addAxis(axisY, QtCore.Qt.AlignLeft) chart.addAxis(axisY2, QtCore.Qt.AlignRight) for series in seriesList: # chart.setAxisX(axisX, series) # chart.setAxisY(axisY, series) series.attachAxis(axisX) series.attachAxis(axisY) chartView = QtCharts.QChartView(chart) chartView.setRenderHint(QPainter.Antialiasing) layout = QVBoxLayout() layout.addWidget(chartView) self.setLayout(layout) self.resize(600, 400)
def __init__(self, ui_fil, parent=None): super(MainWindow, self).__init__(parent) self.ui_file = QFile(ui_fil) self.ui_file.open(QFile.ReadOnly) self.loader = QUiLoader() self.loader.setLanguageChangeEnabled(True) self.window = self.loader.load(self.ui_file) self.window.setGeometry(50, 50, 860, 640) self.window.setWindowIcon(QIcon('icons/icons8-wi-fi-64.png')) self.ui_file.close() self.trans = QTranslator() self.trans.load('lang/pl_PL.qm') self.conn_baudrates = [ "9600", "115200", "300", "1200", "2400", "4800", "14400", "19200", "31250", "38400", "57600" ] self.conn_boards = ["ESP32", "ESP8266"] self.widget_tab = self.window.findChild(QTabWidget, 'tabWidget') self.widget_tab.setIconSize(QSize(36, 36)) self.widget_tab.setTabIcon(0, QIcon('icons/icons8-automatic-64.png')) self.widget_tab.setTabIcon(1, QIcon('icons/icons8-bar-chart-50.png')) self.widget_tab.setTabIcon(2, QIcon('icons/icons8-menu-64.png')) self.widget_tab.setTabIcon(3, QIcon('icons/icons8-timeline-64.png')) self.widget_tab.setTabIcon(4, QIcon('icons/icons8-bluetooth-50.png')) self.widget_tab.setTabIcon(5, QIcon('icons/icons8-console-64.png')) self.lang_combo_box = self.window.findChild(QComboBox, 'lang_combo_box') self.lang_combo_box.addItem("English") self.lang_combo_box.addItem("Polski") self.lang_combo_box.currentTextChanged.connect(self.change_language) self.serial_port_box = self.window.findChild(QComboBox, 'serial_port_box') self.baud_rate_box = self.window.findChild(QComboBox, 'baud_rate_box') self.select_board_box = self.window.findChild(QComboBox, 'select_board_box') self.scan_time_edit = self.window.findChild(QTimeEdit, 'scan_time_edit') self.wifi_scan_box = self.window.findChild(QCheckBox, 'wifi_scan_box') self.blue_scan_box = self.window.findChild(QCheckBox, 'blue_scan_box') self.save_data_check = self.window.findChild(QCheckBox, 'save_data_check') self.connection_status_edit = self.window.findChild( QLineEdit, 'connection_status_edit') self.start_button = self.window.findChild(QPushButton, 'start_button') self.stop_button = self.window.findChild(QPushButton, 'stop_button') self.stop_button.setEnabled(False) self.vertical_wifi_layout = self.window.findChild( QVBoxLayout, 'verticalLayout_5') self.wifi_list_view = self.window.findChild(QListWidget, 'wifi_list_view') self.wifi_list_view.setIconSize(QSize(64, 64)) self.vertical_timeline_layout = self.window.findChild( QVBoxLayout, 'verticalLayout_7') self.blue_list_view = self.window.findChild(QListWidget, 'blue_list_view') self.blue_list_view.setIconSize(QSize(64, 64)) self.console_logging_check = self.window.findChild( QCheckBox, 'console_logging_check') self.console_autoscroll_check = self.window.findChild( QCheckBox, 'console_autoscroll_check') self.console_text_edit = self.window.findChild(QTextEdit, 'console_text_edit') self.select_board_box.activated[str].connect(self.change_board) #Settings tab for i in self.conn_baudrates: self.baud_rate_box.addItem(i) for i in self.conn_boards: self.select_board_box.addItem(i) self.connection_status_edit.setText('Not connected') self.connection_status_edit.setStyleSheet( "background: red; color: white; font-size: 14px; border-width: 1px; \ border-style: solid; border-radius: 2px; border-color: red;") thread1 = ReadSerialPortsThread.ReadSerialPortsThread(self) thread1.add_serial_port.connect( lambda p: self.serial_port_box.addItem(p)) thread1.remove_serial_port.connect( lambda p: self.serial_port_box.removeItem( self.serial_port_box.findText(p))) thread1.start() thread2 = MakeSerialConnection.MakeSerialConnection(self) thread4 = WriteToDatabase.WriteToDatabase(self) self.serial_port_box.currentTextChanged.connect(thread2.get_curr_port) self.baud_rate_box.activated[str].connect(thread2.get_curr_baud) self.select_board_box.activated[str].connect(thread2.get_curr_board) self.scan_time_edit.timeChanged.connect(thread2.get_curr_time) self.start_button.clicked.connect(thread2.start) self.stop_button.clicked.connect(thread2.stop_serial_communication) self.wifi_scan_box.clicked.connect(thread2.get_wifi_check) self.blue_scan_box.clicked.connect(thread2.get_blue_check) self.save_data_check.clicked.connect(thread2.enable_saving_to_db) self.save_data_check.clicked.connect(thread4.enable_saving_data_func) self.lang_combo_box.currentTextChanged.connect( lambda s: thread2.get_current_lang(s)) thread2.baud_box_state.connect( lambda b: self.baud_rate_box.setEnabled(b)) thread2.port_box_state.connect( lambda b: self.serial_port_box.setEnabled(b)) thread2.board_box_state.connect( lambda b: self.select_board_box.setEnabled(b)) thread2.time_edit_state.connect( lambda b: self.scan_time_edit.setEnabled(b)) thread2.wifi_check_state.connect( lambda b: self.wifi_scan_box.setEnabled(b)) thread2.blue_check_state.connect( lambda b: self.blue_scan_box.setEnabled(b)) thread2.serial_port_placeholder.connect( lambda t: self.serial_port_box.addItem(t)) thread2.serial_port_clear.connect(self.serial_port_box.clear) thread2.send_text_signal.connect( lambda t: self.console_text_edit.append(t)) thread2.start_btn_state.connect( lambda b: self.start_button.setEnabled(b)) thread2.stop_btn_state.connect( lambda b: self.stop_button.setEnabled(b)) thread2.conn_stat_text.connect( lambda t: self.connection_status_edit.setText(t)) thread2.conn_stat_style.connect( lambda s: self.connection_status_edit.setStyleSheet(s)) #Wi-Fi Chart tab self.chart = QtCharts.QChart() self.axis_x = QtCharts.QValueAxis() self.axis_y = QtCharts.QValueAxis() self.line_series = QtCharts.QLineSeries() self.line_series.append(QPoint(0, 0)) self.chart.setAxisX(self.axis_x, self.line_series) self.axis_x.setRange(2400, 2483) self.axis_x.setTickCount(10) self.axis_x.setMinorTickCount(4) self.axis_x.applyNiceNumbers() self.axis_x.setTitleText("Frequency [MHz]") self.chart.setAxisY(self.axis_y, self.line_series) self.axis_y.setRange(-100, -30) self.axis_y.applyNiceNumbers() self.axis_y.setTickCount(9) self.axis_y.setMinorTickCount(4) self.axis_y.setTitleText("RSSI [dBm]") self.chart.legend().setVisible(True) self.chart.legend().setAlignment(Qt.AlignRight) self.chart.setBackgroundRoundness(0) self.chart_view = QtCharts.QChartView(self.chart) self.chart_view.setRenderHint(QPainter.Antialiasing) self.vertical_wifi_layout.addWidget(self.chart_view) #WiFi List tab thread2.clear_wifi_list.connect(self.wifi_list_view.clear) thread2.append_wifi_list_item.connect( lambda i: self.wifi_list_view.addItem(i)) thread2.append_wifi_timeline_data.connect( lambda d: self.append_data(d)) thread2.save_wifi_timeline_data.connect( lambda t: thread4.update_db_file(t)) thread2.clear_wifi_series.connect(self.chart.removeAllSeries) thread2.add_wifi_series.connect(lambda s: self.chart.addSeries(s)) thread2.set_axis_x_series.connect( lambda s: self.chart.setAxisX(self.axis_x, s)) thread2.set_axis_y_series.connect( lambda s: self.chart.setAxisY(self.axis_y, s)) thread2.wifi_data_to_func.connect( lambda d: thread2.append_wifi_data(d)) thread2.wifi_data_to_func.connect( lambda d: thread2.append_data_to_wifi_graph(d)) thread2.wifi_data_to_func.connect( lambda d: thread2.append_data_to_wifi_timeline(d)) thread2.blue_data_to_func.connect( lambda d: thread2.append_blue_data(d)) #Wi-Fi Timeline tab self.wifi_channels_occupancy_array = [] self.wifi_channels_timestamps = [] self.deleted_empty_vals = False self.freeze_graph_bool_val = False self.last_item = 0 self.graph_item_color = QColor(255, 195, 0) self.bars = QtDataVisualization.Q3DBars() self.column_axis = QtDataVisualization.QCategory3DAxis() self.column_axis.setTitle('Channels') self.column_axis.setTitleVisible(True) self.column_axis.setLabels([ 'Channel 1', 'Channel 2', 'Channel 3', 'Channel 4', 'Channel 5', 'Channel 6', 'Channel 7', 'Channel 8', 'Channel 9', 'Channel 10', 'Channel 11', 'Channel 12', 'Channel 13' ]) self.column_axis.setLabelAutoRotation(45) self.column_axis.setAutoAdjustRange(True) self.row_axis = QtDataVisualization.QCategory3DAxis() self.row_axis.setTitle('Timeline') self.row_axis.setTitleVisible(True) self.value_axis = QtDataVisualization.QValue3DAxis() self.value_axis.setTitle('RSSI [dBm]') self.value_axis.setTitleVisible(True) self.value_axis.setRange(-100, -10) self.bars.setRowAxis(self.row_axis) self.bars.setColumnAxis(self.column_axis) self.bars.setValueAxis(self.value_axis) self.bars.setBarSpacingRelative(False) self.bars.setFloorLevel(-100) self.series = QtDataVisualization.QBar3DSeries() self.array_data = [[]] self.series.dataProxy().addRows( self.data_to_bar_data_array(self.array_data)) self.series.setBaseColor(self.graph_item_color) self.bars.setPrimarySeries(self.series) self.container = QWidget.createWindowContainer(self.bars) if not self.bars.hasContext(): print("Couldn't initialize the OpenGL context") sys.exit(-1) camera = self.bars.scene().activeCamera() camera.setXRotation(-45.0) camera.setYRotation(22.5) geometry = QGuiApplication.primaryScreen().geometry() size = geometry.height() * 3 / 4 self.container.setMinimumSize(size, size) self.container.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) self.container.setFocusPolicy(Qt.StrongFocus) self.append_data([ -100, -80, -100, -80, -100, -80, -100, -80, -100, -80, -100, -80, -100 ]) self.nav_layout_h = QHBoxLayout() self.freeze_check = QCheckBox() self.freeze_check.setText("Freeze") self.freeze_check.clicked.connect(self.enable_scrolling_data) self.freeze_check.stateChanged.connect(self.freeze_graph) self.prev_button = QPushButton() self.prev_button.setText("Previous") self.prev_button.setEnabled(False) self.prev_button.clicked.connect(self.previous_data) self.next_button = QPushButton() self.next_button.setText("Next") self.next_button.setEnabled(False) self.next_button.clicked.connect(self.next_data) self.nav_layout_h.addWidget(self.freeze_check) self.nav_layout_h.addWidget(self.prev_button) self.nav_layout_h.addWidget(self.next_button) self.load_data_check = QCheckBox() self.load_data_check.setText("Load archival data") self.load_data_check.clicked.connect(self.enable_load_data) self.load_data_combo = QComboBox() self.load_data_combo.addItem("No data found") self.load_data_combo.setEnabled(False) self.load_data_btn = QPushButton() self.load_data_btn.setText("Load") self.load_data_btn.setEnabled(False) self.nav_layout_h2 = QHBoxLayout() self.nav_layout_h2.addWidget(self.load_data_check) self.nav_layout_h2.addWidget(self.load_data_combo) self.nav_layout_h2.addWidget(self.load_data_btn) thread4.start() thread4.remove_defualt_item.connect( lambda: self.load_data_combo.clear()) thread4.append_available_day.connect( lambda s: self.load_data_combo.addItem(s)) thread4.send_data_from_database.connect( lambda t: self.append_data_from_database(t)) self.load_data_combo.currentTextChanged.connect( lambda t: thread4.get_curr_table(t)) self.load_data_btn.clicked.connect(thread4.load_data_button) self.vertical_timeline_layout.addWidget(self.container) self.vertical_timeline_layout.addLayout(self.nav_layout_h) self.vertical_timeline_layout.addLayout(self.nav_layout_h2) #Bluetooth tab thread2.clear_blue_list.connect(self.blue_list_view.clear) thread2.append_blue_list_item.connect( lambda i: self.blue_list_view.addItem(i)) #Console tab self.console_autoscroll_check.stateChanged.connect( self.enable_auto_scroll) thread3 = WriteToFile.WriteToFile(self) self.console_logging_check.stateChanged.connect(thread3.enable_logging) thread2.send_text_signal.connect(lambda t: thread3.write_to_file(t)) self.window.show()
from PySide2 import QtGui from PySide2.QtWidgets import * from PySide2.QtCharts import QtCharts from PySide2.QtGui import QPainter from random import randint app = QApplication([]) window = QWidget() layout = QVBoxLayout() # Initialize chart chart = QtCharts.QChart() lineSeries = QtCharts.QLineSeries() # Make some random data points dataSeries = [(i+1, randint(0, 99999)) for i in range(200)] # load data into chart: for point in dataSeries: lineSeries.append(point[0],point[1]) # Add Some Chart Options chart.addSeries(lineSeries) chart.setTitle("Random Numbers from 0-9000") chart.createDefaultAxes() # Create a container (similar to a widget) chartView = QtCharts.QChartView(chart) chartView.setRenderHint(QPainter.Antialiasing) # Some Chart Styling
def __init__(self, parent): super(GraphView, self).__init__(parent) self._model = None self._series = QtCharts.QLineSeries()
def __init__(self, parent, capacity, color, gradient_start=None, gradient_end=None, speeds=(), is_upload=False, dp=1, max_speed=0): self._parent = parent self._capacity = capacity self._color = color self._gradient_start = gradient_start if gradient_start \ else self._color self._gradient_end = gradient_end if gradient_end \ else self._color.lighter() self._last_max_speed = max_speed self._chart = QtCharts.QChart() self._line_series = QtCharts.QLineSeries() self._lower_series = QtCharts.QLineSeries() if len(speeds) > self._capacity: speeds = speeds[len(speeds) - self._capacity:] for i, speed in enumerate(speeds): self._line_series.append(i, speed) self._lower_series.append(i, 0) self._last_index = len(speeds) self._series = QtCharts.QAreaSeries(self._line_series, self._lower_series) pen = QPen(self._color) pen.setWidth(1) self._series.setPen(pen) self._series.lowerSeries().setColor(self._gradient_end) gradient = QLinearGradient(QPointF(0, 0), QPointF(0, 1)) gradient.setColorAt(0.0, self._gradient_start) gradient.setColorAt(1.0, self._gradient_end) gradient.setCoordinateMode(QGradient.ObjectBoundingMode) self._series.setBrush(gradient) self._chart.addSeries(self._series) self._chart.layout().setContentsMargins(0, 0, 0, 0) # make chart look bigger margins = [-35, -25, -35, -37] self._chart.setContentsMargins(*margins) self._chart.setBackgroundRoundness(0) grid_pen = QPen(QColor("#EFEFF4")) grid_pen.setWidth(1) self._chart.createDefaultAxes() self._chart.axisX().setLabelsVisible(False) # self._chart.axisY().setLabelsVisible(False) self._chart.axisX().setTitleVisible(False) # self._chart.axisY().setTitleVisible(False) self._chart.axisX().setGridLineVisible(True) self._chart.axisX().setGridLinePen(grid_pen) # self._chart.axisY().setGridLineVisible(False) # self._chart.axisY().setGridLinePen(grid_pen) self._chart.axisX().setLineVisible(False) self._chart.axisY().setLineVisible(False) self._chart.axisX().setRange(self._last_index - self._capacity, self._last_index - 1) self._set_y_range() self._chart.axisY().hide() # self._chart.setBackgroundBrush(QBrush(QColor("#EFEFF4"))) self._view = QtCharts.QChartView(self._chart, self._parent) self._view.setRenderHint(QPainter.Antialiasing) self._view.setFixedSize(self._parent.size()) self._view.chart().legend().hide() self._chart.resize(self._view.width(), self._view.height()) text_start = "" self._scale_line = ScaleLine(self._chart, QColor("#777777"), QColor("black"), text_start=text_start, margins=margins, dp=dp, is_upload=is_upload) self._scale_line.set_line(self._last_max_speed, resize=True)
reader = VCFReader("data/17-36166.vcf.gz") reader.compute() print(reader.sample_id) import sys app = QApplication(sys.argv) reader = FSAReader("data/17-36166.fsa") reader.compute() print(reader.sample_id) view = qtc.QChartView() chart = qtc.QChart() serie = qtc.QLineSeries() for x, y in enumerate(reader.wt_data[4211:4248]): serie.append(reader.scale(x), y) for i in serie.points(): print(i) break chart.addSeries(serie) chart.createDefaultAxes() view.setRubberBand(qtc.QChartView.RectangleRubberBand) #chart.axisX().setRange(0,500) chart.axisY().setRange(0, 1000) view.setChart(chart)
def createChart(self, title, days, type, db): with open('config.json', 'r') as f: config = json.load(f) names = config['SEARCH'] if (type == "lines"): datesLookUp = self.DateSeriesMongoDB( self.calcultateFirstDate(days)) datesAvailable = self.datesWithData(datesLookUp, db, title) series = [] for name in names: newSeries = QtCharts.QLineSeries() newSeries.setName(name) #series.append(self.fillLineSeries(newSeries, datesLookUp, db, title)) series.append( self.fillLineSeries(newSeries, datesAvailable, db, title, name)) chart = QtCharts.QChart() for serie in series: chart.addSeries(serie) chart.setTitle(title) #datesAxis = self.calculateDateSeries(self.calcultateFirstDate(days)) print(datesAvailable) datesAxis = [dt.strftime("%m-%d") for dt in datesAvailable] print(datesAxis) chart.createDefaultAxes() axisX = QtCharts.QBarCategoryAxis() axisY = QtCharts.QValueAxis() axisX.append(datesAxis) axisX.setRange(datesAxis[0], datesAxis[len(datesAxis) - 1]) for serie in series: chart.setAxisX(axisX, serie) chart.setAxisY(axisY, serie) chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) chartView = QtCharts.QChartView(chart) chartView.setMinimumSize(700, 500) chartView.setRenderHint(QPainter.Antialiasing) return chartView elif (type == "bars"): datesLookUp = self.DateSeriesMongoDB( self.calcultateFirstDate(days)) datesAvailable = self.datesWithData(datesLookUp, db, title) series = [] for name in names: newSeries = QtCharts.QBarSet(name) #series.append(self.fillBarSeries(newSeries, datesLookUp, db, title)) series.append( self.fillBarSeries(newSeries, datesAvailable, db, title, name)) chart = QtCharts.QChart() barSeries = QtCharts.QBarSeries() for serie in series: barSeries.append(serie) chart.setTitle(title) chart.addSeries(barSeries) #datesAxis = self.calculateDateSeries(self.calcultateFirstDate(days)) datesAxis = [dt.strftime("%m-%d") for dt in datesAvailable] chart.createDefaultAxes() axisX = QtCharts.QBarCategoryAxis() axisX.append(datesAxis) chart.setAxisX(axisX, barSeries) axisX.setRange(datesAxis[0], datesAxis[len(datesAxis) - 1]) axisY = QtCharts.QValueAxis() chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) chartView = QtCharts.QChartView(chart) chartView.setMinimumSize(700, 500) chartView.setRenderHint(QPainter.Antialiasing) return chartView elif (type == "percentage"): datesLookUp = self.DateSeriesMongoDB( self.calcultateFirstDate(days)) datesAvailable = self.datesWithData(datesLookUp, db, title) #datesAxis = self.calculateDateSeries(self.calcultateFirstDate(days)) datesAxis = [dt.strftime("%m-%d") for dt in datesAvailable] series = [] for name in names: newSeries = QtCharts.QBarSet(name) #series.append(self.fillBarSeries(newSeries, datesLookUp, db, title)) series.append( self.fillBarSeries(newSeries, datesAvailable, db, title, name)) if (len(names) == 1): filler = QtCharts.QBarSet("") filler.append([100 for item in range(0, len(datesAxis))]) series.append(filler) chart = QtCharts.QChart() percentBarSeries = QtCharts.QPercentBarSeries() for serie in series: percentBarSeries.append(serie) chart.setTitle(title) chart.addSeries(percentBarSeries) chart.createDefaultAxes() axisX = QtCharts.QBarCategoryAxis() axisX.append(datesAxis) chart.setAxisX(axisX, percentBarSeries) axisX.setRange(datesAxis[0], datesAxis[len(datesAxis) - 1]) axisY = QtCharts.QValueAxis() chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) chartView = QtCharts.QChartView(chart) chartView.setMinimumSize(700, 500) chartView.setRenderHint(QPainter.Antialiasing) return chartView elif (type == "schedule"): datesLookUp = self.DateSeriesMongoDB( self.calcultateFirstDate(days)) datesAvailable = self.datesWithData(datesLookUp, db, title) series = [] for name in names: newSeries = QtCharts.QBarSet(name) #series.append(self.fillScheduleSeries(newSeries, datesLookUp, db, title)) series.append( self.fillScheduleSeries(newSeries, datesAvailable, db, title, name)) chart = QtCharts.QChart() barSeries = QtCharts.QBarSeries() for serie in series: barSeries.append(serie) chart.setTitle(title) #datesAxis = self.scheduleAxis(newSeries, datesLookUp, db, title) datesAxis = self.scheduleAxis(newSeries, datesAvailable, db, title) chart.addSeries(barSeries) chart.createDefaultAxes() axisX = QtCharts.QBarCategoryAxis() axisX.append(datesAxis) chart.setAxisX(axisX, barSeries) axisX.setRange(datesAxis[0], datesAxis[len(datesAxis) - 1]) axisY = QtCharts.QValueAxis() chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) chartView = QtCharts.QChartView(chart) chartView.setMinimumSize(700, 500) #chartView.setMaximumSize(1000,500) chartView.setRenderHint(QPainter.Antialiasing) return chartView else: raise "Wrong chart type"
data = ((1, 7380, 7520, 7380, 7510, 7324), (2, 7520, 7580, 7410, 7440, 7372), (3, 7440, 7650, 7310, 7520, 7434), (4, 7450, 7640, 7450, 7550, 7480), (5, 7510, 7590, 7460, 7490, 7502), (6, 7500, 7590, 7480, 7560, 7512), (7, 7560, 7830, 7540, 7800, 7584)) app = QApplication([]) # set dark stylesheet # import pdb; pdb.set_trace() app.setStyleSheet(qdarkstyle.load_stylesheet_pyside()) series = QtCharts.QCandlestickSeries() series.setDecreasingColor(Qt.darkRed) series.setIncreasingColor(Qt.darkGreen) ma5 = QtCharts.QLineSeries() # 5-days average data line tm = [] # stores str type data # in a loop, series and ma5 append corresponding data for num, o, h, l, c, m in data: candle = QtCharts.QCandlestickSet(o, h, l, c) series.append(candle) ma5.append(QPointF(num, m)) tm.append(str(num)) pen = candle.pen() # import pdb; pdb.set_trace() chart = QtCharts.QChart() # import pdb; pdb.set_trace()
import sys from PySide2.QtWidgets import QApplication from PySide2.QtCharts import QtCharts from PySide2.QtGui import QPen, QLinearGradient, QColor, QGradient from PySide2.QtCore import QPointF, Qt app = QApplication([]) upperSeries = QtCharts.QLineSeries() lowerSeries = QtCharts.QLineSeries() #x = [x for x in range(1, 20, 2)] #y1 = [5, 7, 6, 7, 5, 7, 5, 4, 7, 5] #y2 = [3, 4, 2, 5, 3, 5, 2, 1, 4, 2] x = [x for x in range(1, 3, 1)] y1 = [5, 7] y2 = [3, 4] for i in range(len(x)): upperSeries.append(x[i], y1[i]) lowerSeries.append(x[i], y2[i]) series = QtCharts.QAreaSeries(upperSeries, lowerSeries) pen = QPen(Qt.red) pen.setWidth(3) series.setPen(pen) gradient = QLinearGradient(QPointF(0, 0), QPointF(0, 1)) gradient.setColorAt(0.0, QColor(255, 255, 255)) gradient.setColorAt(1.0, QColor(0, 255, 0))
def __init__(self, ds, classes, model, created, *args, **kwargs): super(TrainingWindow, self).__init__(*args, **kwargs) if created: # Initialising network self.network = Network() self.network.use(mean_squared_error, mean_squared_error_prime) else: self.network = model[0] # Getting inputs and outputs self.__dataset = ds self.__classes = classes #fill_missing_values(self.__dataset) #min_max_normalize_dataset(self.__dataset) ((x_train, y_train), (x_test, y_test)) = self.network.regular_split(self.__dataset, 0.5) # Getting inputs if len(x_train.shape) == 2: inputs = x_train.shape[1] else: inputs = x_train.shape[1:] first = inputs[0] second = inputs[1] third = inputs[2] # Getting expected outputs expected_output = y_train.shape[1] # Getting network name self.networkName = model[1] if created: # Getting model list self.__modelList = model[0] self.__modelList[0].setOutput(inputs) for i in range(1, len(self.__modelList)): # Getting the layer name name = self.__modelList[i].text( )[:len(self.__modelList[i].text()) - 6] activation = None activ_prime = None # Getting the activation function if self.__modelList[i].activation() == 0: activation = sigmoid activ_prime = sigmoid_prime elif self.__modelList[i].activation() == 1: activation = tanh activ_prime = tanh_prime elif self.__modelList[i].activation() == 2: activation = rectified_linear_unit activ_prime = rectified_linear_unit_prime elif self.__modelList[i].activation() == 3: activation = softmax activ_prime = softmax_prime # Adding layer to the network if name == "Dense": if self.__modelList[i - 1].text()[:2] == "Fl": self.network.add( FullyConnectedLayer(first * second * third, self.__modelList[i].output())) self.network.add( ActivationLayer(activation, activ_prime)) else: self.network.add( FullyConnectedLayer( self.__modelList[i - 1].output(), self.__modelList[i].output())) self.network.add( ActivationLayer(activation, activ_prime)) elif name == "Flatten": self.network.add(FlattenLayer()) elif name == "Convolutional": self.network.add( ConvLayer((first, second, third), (self.__modelList[i].kernelRows, self.__modelList[i].kernelColumns), 1)) self.network.add(ActivationLayer(activation, activ_prime)) first = first - self.__modelList[i].kernelRows + 1 second = second - self.__modelList[i].kernelColumns + 1 self.network.add( FullyConnectedLayer( self.__modelList[len(self.__modelList) - 1].output(), expected_output)) self.network.add(ActivationLayer(sigmoid, sigmoid_prime)) # Loading Fonts QFontDatabase.addApplicationFont("fonts/BebasNeue-Light.ttf") # Window Settings self.setFixedSize(1280, 720) self.setWindowTitle("Training window") #background = QPixmap("images/menu") #palette = QPalette() #palette.setBrush(QPalette.Background, background) #self.setAttribute(Qt.WA_StyledBackground, True) #self.setPalette(palette) self.setAutoFillBackground(True) # Stylesheet Settings styleFile = QFile("stylesheets/training.qss") styleFile.open(QFile.ReadOnly) style = str(styleFile.readAll()) self.setStyleSheet(style) # Title Settings self.title = QLabel("Training", self) self.title.setFont(QFont("BebasNeue", 30, QFont.Bold)) self.title.setAlignment(Qt.AlignCenter) self.title.setGeometry(600, 10, 300, 120) # Epochs line edit settings self.__epochsLineEdit = QLineEdit(self) self.__epochsLineEdit.setValidator(QIntValidator(0, 100000, self)) # Epochs label settings self.__epochsLabel = QLabel("Epoch number", self) self.__epochsLabel.setFont(QFont("BebasNeue", 20, QFont.Bold)) # Learning rate line edit settings self.__learningRateLineEdit = QLineEdit(self) self.__learningRateLineEdit.setValidator( QDoubleValidator(0.0, 1.0, 3, self)) # Learning rate label settings self.__learningRateLabel = QLabel("Learning rate", self) self.__learningRateLabel.setFont(QFont("BebasNeue", 20, QFont.Bold)) # Learning rate checkboxsettings (auto or not) self.__learningRateCheckBox = QCheckBox("Auto adjustment", self) self.__learningRateCheckBox.setFont(QFont("BebasNeue", 15, QFont.Bold)) # Dataset split settings label self.__datasetSplitLabel = QLabel("Dataset split percentage", self) self.__datasetSplitLabel.setFont((QFont("BebasNeue", 20, QFont.Bold))) # Dataset split mode buttons self.__datasetSplitRegular = QRadioButton("Regular split") self.__datasetSplitRandom = QRadioButton("Random split") # Dataset split mode buttons groupbox self.__datasetSplitModeButtonsLayout = QHBoxLayout(self) self.__datasetSplitModeButtonsGroupBox = QGroupBox(self) self.__datasetSplitModeButtonsGroupBox.setObjectName("setting") self.__datasetSplitModeButtonsLayout.addWidget( self.__datasetSplitRegular) self.__datasetSplitModeButtonsLayout.addWidget( self.__datasetSplitRandom) self.__datasetSplitModeButtonsGroupBox.setLayout( self.__datasetSplitModeButtonsLayout) self.__datasetSplitRegular.setChecked(True) # Dataset split combo box settings self.__datasetSplitComboBox = QComboBox(self) self.__datasetSplitComboBox.addItems( ['90% - 10%', '80% - 20%', '70% - 30%', '60% - 40%']) # Dataset split form layout settings self.__datasetSplitLayout = QFormLayout(self) self.__datasetSplitGroupBox = QGroupBox(self) self.__datasetSplitGroupBox.setObjectName("setting") self.__datasetSplitLayout.addWidget(self.__datasetSplitLabel) self.__datasetSplitLayout.addWidget(self.__datasetSplitComboBox) self.__datasetSplitGroupBox.setLayout(self.__datasetSplitLayout) # Epochs form layout settings self.__epochsFormLayout = QFormLayout(self) self.__epochsGroupBox = QGroupBox(self) self.__epochsGroupBox.setObjectName("setting") self.__epochsFormLayout.addWidget(self.__epochsLabel) self.__epochsFormLayout.addWidget(self.__epochsLineEdit) self.__epochsGroupBox.setLayout(self.__epochsFormLayout) # Learning rate form layout settings self.__learningRateFormLayout = QFormLayout(self) self.__learningRateGroupBox = QGroupBox(self) self.__learningRateGroupBox.setObjectName("setting") self.__learningRateFormLayout.addWidget(self.__learningRateLabel) self.__learningRateFormLayout.addWidget(self.__learningRateCheckBox) self.__learningRateFormLayout.addWidget(self.__learningRateLineEdit) self.__learningRateGroupBox.setLayout(self.__learningRateFormLayout) # Epochs number label self.__epochNumberLabel = QLabel("Epoch : ", self) self.__epochNumberLabel.setFont((QFont("BebasNeue", 15, QFont.Bold))) # Training accuracy label self.__trainingAccuracyLabel = QLabel("Accuracy : ", self) self.__trainingAccuracyLabel.setFont((QFont("BebasNeue", 15, QFont.Bold))) # Training stats layout self.__trainingStatsLayout = QVBoxLayout(self) self.__trainingStatsGroupBox = QGroupBox(self) self.__trainingStatsLayout.addWidget(self.__epochNumberLabel) self.__trainingStatsLayout.addWidget(self.__trainingAccuracyLabel) self.__trainingStatsGroupBox.setLayout(self.__trainingStatsLayout) self.__trainingStatsGroupBox.setGeometry(1000, -30, 300, 150) # Training button settings self.__trainingButton = QPushButton("Start", self) self.__trainingButton.setCursor(Qt.PointingHandCursor) self.__trainingButton.setFont((QFont("BebasNeue", 30, QFont.Bold))) self.__trainingButton.clicked.connect(self.startTraining) # Go back button self.goBackButton = QPushButton("Back", self) self.goBackButton.setObjectName("retour") # Customising go back button self.goBackButton.setCursor(Qt.PointingHandCursor) self.goBackButton.setIcon(QIcon("images/goback_icon")) self.goBackButton.setIconSize(QSize(30, 30)) self.goBackButton.setFont(QFont("BebasNeue", 20, QFont.Bold)) # Confusion matrix button self.__confusionMatrixButton = QPushButton("Show confusion matrix", self) self.__confusionMatrixButton.setCursor(Qt.PointingHandCursor) self.__confusionMatrixButton.setFont((QFont("BebasNeue", 17, QFont.Bold))) self.__confusionMatrixButton.clicked.connect(self.showStats) self.__confusionMatrixButton.setGeometry(420, 20, 250, 80) self.__confusionMatrixButton.hide() # Parameters group box settings self.__parametersGroupBox = QGroupBox("Training parameters", self) self.__parametersGroupBox.setObjectName("parameters") self.__parametersLayout = QVBoxLayout(self) self.__parametersLayout.addWidget(self.__epochsGroupBox) self.__parametersLayout.addWidget(self.__datasetSplitGroupBox) self.__parametersLayout.addWidget( self.__datasetSplitModeButtonsGroupBox) self.__parametersLayout.addWidget(self.__learningRateGroupBox) self.__parametersLayout.addWidget(self.__trainingButton) self.__parametersLayout.addWidget(self.goBackButton) self.__parametersGroupBox.setLayout(self.__parametersLayout) self.__parametersGroupBox.setGeometry(0, 0, 400, 720) # Chart axis settings self.__xAxis = QtCharts.QValueAxis() self.__xAxis.setRange(0, 5) self.__yAxis = QtCharts.QValueAxis() self.__yAxis.setRange(0, 100) # Chart settings self.__series = QtCharts.QLineSeries() self.__chart = QtCharts.QChart() self.__chart.addAxis(self.__xAxis, Qt.AlignBottom) self.__chart.addAxis(self.__yAxis, Qt.AlignLeft) self.__chart.addSeries(self.__series) self.__series.attachAxis(self.__xAxis) self.__series.attachAxis(self.__yAxis) self.__chart.setTitle("Accuracy") self.__chartView = QtCharts.QChartView(self.__chart) self.__chartView.setRenderHint(QPainter.Antialiasing) # Chart layout settings self.__chartLayout = QVBoxLayout(self) self.__chartGroupBox = QGroupBox(self) self.__chartGroupBox.setObjectName("chart") self.__chartLayout.addWidget(self.__chartView) self.__chartGroupBox.setLayout(self.__chartLayout) self.__chartGroupBox.setGeometry(390, 100, 900, 600) # Update timer settings #self.__timer = QTimer(self) #self.__timer.timeout.connect(self.autoSave) #self.__timer.start(1000) #app = QApplication(sys.argv) #window = TrainingWindow() #window.show() #app.exec_()
def get_lineSeries_psnr(self): lineSeries = QtCharts.QLineSeries() for i in range(0, len(self.psnr)): lineSeries.append(QPoint(i, self.psnr[i])) lineSeries.setName(self.filename) return lineSeries
def __init__(self): QWidget.__init__(self) self.ip = default_ip self.nPoint = 1000 self.nChannel = 4 self.nRow = 4 layout_final = QVBoxLayout() #layout: ip and connect checkbox text = QLabel("IPv4 Address:", self) text.setAlignment(Qt.AlignCenter) self.ip_input = QLineEdit(self.ip, self) self.connect_input = QCheckBox("connect", self) layout = QHBoxLayout() layout.addWidget(text) layout.addWidget(self.ip_input) layout.addWidget(self.connect_input) layout_final.addLayout(layout) #layout: Name text = QLabel("Name:", self) text.setAlignment(Qt.AlignRight) self.name = QLabel("", self) layout = QHBoxLayout() layout.addWidget(text) layout.addWidget(self.name) layout_final.addLayout(layout) #layout: Time text = QLabel("Time:", self) text.setAlignment(Qt.AlignRight) self.time = QLabel("", self) layout = QHBoxLayout() layout.addWidget(text) layout.addWidget(self.time) layout_final.addLayout(layout) #layout: Horizontal text = QLabel("Horizontal: Scale (second per division):", self) self.x_scale_output = QLineEdit("", self) self.x_scale_input_zoom_in = QPushButton("+", self) self.x_scale_input_zoom_out = QPushButton("-", self) layout = QHBoxLayout() layout.addWidget(text) layout.addWidget(self.x_scale_output) layout.addWidget(self.x_scale_input_zoom_in) layout.addWidget(self.x_scale_input_zoom_out) layout_final.addLayout(layout) #layout: Vertical text1 = QLabel("Vertical: Channel:", self) self.y_channel_input = QComboBox(self) for i in range(self.nChannel): self.y_channel_input.insertItem(i, "Ch{0}".format(i + 1)) self.y_enabled = QCheckBox("Enabled", self) text2 = QLabel("Coupling:", self) self.y_coupling = QComboBox(self) self.y_coupling.insertItem(0, "DC") self.y_coupling.insertItem(1, "AC") text3 = QLabel("Scale (V per division):", self) self.y_scale_output = QLineEdit("", self) self.y_scale_input_zoom_in = QPushButton("+", self) self.y_scale_input_zoom_out = QPushButton("-", self) layout = QHBoxLayout() layout.addWidget(text1) layout.addWidget(self.y_channel_input) layout.addWidget(self.y_enabled) layout.addWidget(text2) layout.addWidget(self.y_coupling) layout.addWidget(text3) layout.addWidget(self.y_scale_output) layout.addWidget(self.y_scale_input_zoom_in) layout.addWidget(self.y_scale_input_zoom_out) layout_final.addLayout(layout) #layout: Measurement config text1 = QLabel("Measurement:", self) text2 = QLabel("Row:", self) text2.setAlignment(Qt.AlignRight) self.measurement_row_input = QComboBox(self) for i in range(self.nRow): self.measurement_row_input.insertItem(i, str(i + 1)) self.measurement_row_input.setCurrentText("1") self.measurement_enabled = QCheckBox("Enabled", self) text3 = QLabel("Channel:", self) text3.setAlignment(Qt.AlignRight) self.measurement_channel_input = QComboBox(self) for i in range(self.nChannel): self.measurement_channel_input.insertItem(i, "CH{0}".format(i + 1)) text4 = QLabel("Type:", self) text4.setAlignment(Qt.AlignRight) self.measurement_type_input = QComboBox(self) self.measurement_type_input.insertItem(0, "MEAN") self.measurement_type_input.insertItem(1, "RMS") layout = QHBoxLayout() layout.addWidget(text1) layout.addWidget(text2) layout.addWidget(self.measurement_row_input) layout.addWidget(self.measurement_enabled) layout.addWidget(text3) layout.addWidget(self.measurement_channel_input) layout.addWidget(text4) layout.addWidget(self.measurement_type_input) layout_final.addLayout(layout) #layout: ChartView chartView = QtCharts.QChartView() layout_final.addWidget(chartView) #layout: Measurement table self.measurement_table = QTableWidget(self) self.measurement_table.setRowCount(self.nRow) self.measurement_statistics_list = [ "Value", "Mean", "Minimum", "Maximum", "StdDev" ] self.measurement_table.setColumnCount( 2 + len(self.measurement_statistics_list)) self.measurement_table.setHorizontalHeaderItem( 0, QTableWidgetItem("Channel")) self.measurement_table.setHorizontalHeaderItem( 1, QTableWidgetItem("Type")) for i in range(len(self.measurement_statistics_list)): self.measurement_table.setHorizontalHeaderItem( 2 + i, QTableWidgetItem(self.measurement_statistics_list[i])) layout_final.addWidget(self.measurement_table) self.setLayout(layout_final) #signal and slot self.ip_input.returnPressed.connect(self.update_ip) self.connect_input.stateChanged.connect(self.connect) self.x_scale_input_zoom_in.clicked.connect(self.x_scale_zoom_in) self.x_scale_input_zoom_out.clicked.connect(self.x_scale_zoom_out) self.x_scale_output.returnPressed.connect(self.set_x_scale) self.y_channel_input.activated.connect(self.update_channel) self.y_enabled.clicked.connect(self.channel_enabled) self.y_coupling.activated.connect(self.set_coupling) self.y_scale_input_zoom_in.clicked.connect(self.y_scale_zoom_in) self.y_scale_input_zoom_out.clicked.connect(self.y_scale_zoom_out) self.y_scale_output.returnPressed.connect(self.set_y_scale) self.measurement_row_input.activated.connect( self.update_measurement_config) self.measurement_enabled.clicked.connect(self.enable_measurement) self.measurement_channel_input.activated.connect( self.update_measurement_channel) self.measurement_type_input.activated.connect( self.update_measurement_type) #Timer self.timer = QTimer(self) self.timer.timeout.connect(self.update_data) #Line Chart chart = QtCharts.QChart() self.series = [] for i in range(self.nChannel): self.series.append(QtCharts.QLineSeries()) chart.addSeries(self.series[i]) for j in range(self.nPoint): self.series[i].append(0, 0) chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignTop) markers = chart.legend().markers() for i in range(self.nChannel): markers[i].setLabel("Ch{0}".format(i + 1)) self.axisX = QtCharts.QValueAxis() self.axisX.setTickCount(11) self.axisX.setLabelFormat("%.1e") self.axisX.setTitleText("Time (s)") self.axisX.setRange(-2e-3, 2e-3) chart.addAxis(self.axisX, Qt.AlignBottom) for i in range(self.nChannel): self.series[i].attachAxis(self.axisX) self.axisY = QtCharts.QValueAxis() self.axisY.setTickCount(11) self.axisY.setLabelFormat("%.1e") self.axisY.setTitleText("Voltage Division") self.axisY.setRange(-5, 5) self.axisY.setLabelsVisible(False) chart.addAxis(self.axisY, Qt.AlignLeft) for i in range(self.nChannel): self.series[i].attachAxis(self.axisY) chartView.setChart(chart) chartView.setRenderHint(QPainter.Antialiasing)