Exemple #1
0
    def build(self):
        rox_data = self.record.annotations["abif_raw"]["DATA4"]
        wt_data = self.record.annotations["abif_raw"]["DATA1"]
        mt_data = self.record.annotations["abif_raw"]["DATA2"]
        self.model = PeaksModel()
        self.model.find_peaks(rox_data)

        self.chart = qtc.QChart()
        self.chart.setTitle(self.filename)
        self.rox_series = qtc.QLineSeries()
        self.rox_series.setColor(Qt.red)

        self.wt_series = qtc.QLineSeries()
        self.wt_series.setColor(QColor("#4e9a06"))

        self.mt_series = qtc.QLineSeries()
        self.mt_series.setColor(QColor("#27A4DD"))

        for x, y in enumerate(rox_data):
            self.rox_series.append(self.model.predict(x), y)

        for x, y in enumerate(wt_data):
            self.wt_series.append(self.model.predict(x), y)

        for x, y in enumerate(mt_data):
            self.mt_series.append(self.model.predict(x), y)

        self.chart.addSeries(self.rox_series)
        self.chart.addSeries(self.wt_series)
        self.chart.addSeries(self.mt_series)
        self.chart.createDefaultAxes()
        self.setRubberBand(qtc.QChartView.RectangleRubberBand)
        self.chart.axisX().setRange(120, 200)
        #self.chart.axisY().setRange(0,2000)

        self.setChart(self.chart)
Exemple #2
0
    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)
Exemple #3
0
    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)
Exemple #4
0
    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')
Exemple #5
0
    def plotAllExpenseBars(self, legendPlot=None):
        chart = QtCharts.QChart()

        barSets = []
        barSeries = QtCharts.QBarSeries()
        maxVal = 0
        if legendPlot is None:
            catList = ['Alle']
            for cat in list(self.plotData.keys()):
                if cat == "Einnahmen" or cat == "Zählerstände":
                    continue
                barSet = QtCharts.QBarSet(cat)
                barSet.append(self.plotData[cat])
                barSets.append(barSet)
                barSeries.append(barSet)
                catList.append(cat)
                maxVal = max(maxVal, max(self.plotData[cat]))
            self.barSets = barSets
            self.catList = catList
        else:
            barSet = QtCharts.QBarSet(legendPlot)
            barSet.append(self.plotData[legendPlot])
            barSets.append(barSet)
            barSeries.append(barSet)
            maxVal = max(self.plotData[legendPlot])

        chart.addSeries(barSeries)

        titleFont = QFont("Sans Serif")
        titleFont.setPointSize(16)
        titleFont.setBold(True)
        chart.setTitleFont(titleFont)
        if legendPlot is None:
            chart.setTitle("Ausgaben")
        else:
            chart.setTitle("Ausgaben: " + legendPlot)

        axisX = QtCharts.QBarCategoryAxis()
        axisX.append(self.plotDataTags)
        chart.setAxisX(axisX, barSeries)
        # axisX.setRange(self.plotDataTags[0], self.plotDataTags[-1])

        axisY = QtCharts.QValueAxis()
        axisY.setLabelFormat("%i")
        axisY.setTitleText("€")
        self.setYRange(maxVal, axisY)
        # chart.setAxisY(axisY, lineSeries)
        chart.setAxisY(axisY, barSeries)
        # axisY.setRange(0, 20)

        if legendPlot is None:
            chart.legend().setVisible(True)
            chart.legend().setAlignment(Qt.AlignRight)
        else:
            chart.legend().setVisible(False)

        self.setChart(chart)
        self.setRenderHint(QPainter.Antialiasing)
        if legendPlot is None:
            self.sgn_updateLegendSelection.emit(self.catList)
        # draw the plot from scratch (if that makes a difference)
        print('Expense bar plot drawn')
Exemple #6
0
    def __init__(self):
        QObject.__init__(self)

        self.module_path = os.path.dirname(__file__)

        self.mouse_pressed = False
        self.draw_ellipse = False
        self.write_text = False
        self.mouse_pressed_x = 0
        self.mouse_pressed_y = 0
        self.tables = []
        self.ellipses = []
        self.texts = []

        self.text_event_filter = TextEventFilter(self)

        # loading widgets from designer file

        loader = QUiLoader()

        loader.registerCustomWidget(QtCharts.QChartView)

        self.window = loader.load(self.module_path +
                                  "/ui/application_window.ui")

        self.tab_widget = self.window.findChild(QTabWidget, "tab_widget")
        chart_frame = self.window.findChild(QFrame, "chart_frame")
        chart_cfg_frame = self.window.findChild(QFrame, "chart_cfg_frame")
        self.chart_view = self.window.findChild(QtCharts.QChartView,
                                                "chart_view")
        button_add_tab = self.window.findChild(QPushButton, "button_add_tab")
        button_reset_zoom = self.window.findChild(QPushButton,
                                                  "button_reset_zoom")
        button_save_image = self.window.findChild(QPushButton,
                                                  "button_save_image")
        self.label_mouse_coords = self.window.findChild(
            QLabel, "label_mouse_coords")
        self.radio_zoom = self.window.findChild(QRadioButton, "radio_zoom")
        self.radio_ellipse = self.window.findChild(QRadioButton,
                                                   "radio_ellipse")
        self.radio_text = self.window.findChild(QRadioButton, "radio_text")

        # Creating QChart
        self.chart = QtCharts.QChart()
        self.chart.setAnimationOptions(QtCharts.QChart.AllAnimations)
        self.chart.setTheme(QtCharts.QChart.ChartThemeLight)
        self.chart.setAcceptHoverEvents(True)

        self.axis_x = QtCharts.QValueAxis()
        self.axis_x.setTitleText("PC1")
        self.axis_x.setRange(-10, 10)
        self.axis_x.setLabelFormat("%.1f")

        self.axis_y = QtCharts.QValueAxis()
        self.axis_y.setTitleText("PC2")
        self.axis_y.setRange(-10, 10)
        self.axis_y.setLabelFormat("%.1f")

        self.chart.addAxis(self.axis_x, Qt.AlignBottom)
        self.chart.addAxis(self.axis_y, Qt.AlignLeft)

        self.chart_view.setChart(self.chart)
        self.chart_view.setRenderHint(QPainter.Antialiasing)
        self.chart_view.setRubberBand(QtCharts.QChartView.RectangleRubberBand)

        # 1 tab by default

        self.add_tab()

        # custom stylesheet

        style_file = QFile(self.module_path + "/ui/custom.css")
        style_file.open(QFile.ReadOnly)

        self.window.setStyleSheet(style_file.readAll().data().decode("utf-8"))

        style_file.close()

        # effects

        self.tab_widget.setGraphicsEffect(self.card_shadow())
        chart_frame.setGraphicsEffect(self.card_shadow())
        chart_cfg_frame.setGraphicsEffect(self.card_shadow())
        button_add_tab.setGraphicsEffect(self.button_shadow())
        button_reset_zoom.setGraphicsEffect(self.button_shadow())
        button_save_image.setGraphicsEffect(self.button_shadow())

        # signal connection

        self.tab_widget.tabCloseRequested.connect(self.remove_tab)
        button_add_tab.clicked.connect(self.add_tab)
        button_reset_zoom.clicked.connect(self.reset_zoom)
        button_save_image.clicked.connect(self.save_image)
        self.radio_zoom.toggled.connect(self.on_mouse_function_changed)
        self.radio_ellipse.toggled.connect(self.on_mouse_function_changed)
        self.radio_text.toggled.connect(self.on_mouse_function_changed)

        # event filter

        self.chart.installEventFilter(self)

        # show window

        self.window.show()
Exemple #7
0
    def __init__(self, data, splineChartData, areaChartData, scatterChartData,
                 pieChartData, bwChartData, candlestickChartData):
        QWidget.__init__(self)
        """ получение модели """
        self.model = CustomTableModel(data)
        """переходим в класс CustomTableModel и создаем объект-таблицу, model-часть класса с помощью которого работаем с данными,имя поля-model  """
        self.table_view = QTableView()
        """полностью устраивает класс  QTableView поэтому доп конструкторов и ф-ций не пишем, а просто создаем и он поле нашего класса, имя поля-table_view  """
        self.table_view.setModel(self.model)
        """может рисовать таблицу в соотвествие с полученными данными(3 столбца, нужные числа и тд) """
        resize = QHeaderView.ResizeToContents
        """ Класс QHeaderView предоставляет строку заголовка или столбец заголовка для представлений элементов, заголовок маштабируется """
        self.horizontal_header = self.table_view.horizontalHeader()

        self.vertical_header = self.table_view.verticalHeader()

        self.horizontal_header.setSectionResizeMode(resize)

        self.vertical_header.setSectionResizeMode(resize)

        self.horizontal_header.setStretchLastSection(True)
        """ Формируется данные для рисования заголовка  """
        """создание графика 
        модуль QtChart предоставляет множество типов графиков и опций для графического представления данных. 
        """

        chart1 = QtCharts.QChart()
        """нас устраивает класс QChart полностью, доп методы и консрукторы не нужны """
        chart1.setAnimationOptions(QtCharts.QChart.AllAnimations)
        """ установить параметры анимации, запускается рисование """
        self.add_series("Значение", [0, 1], chart1)
        """подготовка вкладки на кот размещена диаграмма """
        size = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        size.setHorizontalStretch(4)
        #-----------------------------------------
        chart_view1 = QtCharts.QChartView(chart1)
        """подготовка визуализации продолжается """
        chart_view1.setRenderHint(QPainter.Antialiasing)

        #self.chart_view1.setSizePolicy(size)
        minWidth = 400
        chart_view1.setMinimumWidth(minWidth)

        #-----------------------------------------------------
        chart2 = QtCharts.QChart()
        chart2.setAnimationOptions(QtCharts.QChart.AllAnimations)
        self.add_series("Глубина", [0, 2], chart2)  #данные для каждого графика
        chart_view2 = QtCharts.QChartView(chart2)
        """подготовка визуализации продолжается """
        chart_view2.setRenderHint(QPainter.Antialiasing)
        """ QWidget расположение """
        """ правое расположение """
        #self.chart_view2.setSizePolicy(size)
        chart_view2.setMinimumWidth(minWidth)

        main_layout = QHBoxLayout()
        splitter = QSplitter()

        dateColumn = 0
        magColumn = 1
        depthsColumn = 2

        xDates = self.getDateAsCategoricalColumn(dateColumn)
        yMagnitudes = self.getFloatColumn(magColumn)
        yDepths = self.getFloatColumn(depthsColumn)

        # print("ymags")
        # print(yMagnitudes)
        # print("ydepths")
        # print(yDepths)

        bc1 = self.createBarCharts(xDates, yMagnitudes, yDepths)
        bar1ChartView = QtCharts.QChartView(bc1)
        bar1ChartView.setRenderHint(QPainter.Antialiasing)

        chartViewsHbox = QHBoxLayout()
        chartViewsHbox.addWidget(chart_view1)
        chartViewsHbox.addWidget(chart_view2)

        vbox = QVBoxLayout()
        vbox.addLayout(chartViewsHbox)
        vbox.addWidget(bar1ChartView)

        vboxWidget = QWidget()
        vboxWidget.setLayout(vbox)
        splitter.addWidget(vboxWidget)

        splitter.addWidget(self.table_view)

        main_layout.addWidget(splitter)

        # self.setLayout(main_layout) # установить макет на QWidget """

        mainWidget = QWidget()
        mainWidget.setLayout(main_layout)

        tabWidget = QTabWidget()

        tabWidget.addTab(mainWidget, "travis scott")

        splineTab = ddv.charts.createSplineChart(splineChartData)
        tabWidget.addTab(splineTab, "spline chart")

        #areaTab = ddv.charts.createAreaChart(areaChartData)
        #tabWidget.addTab(areaTab, "area chart")

        scatterTab = ddv.charts.createScatterChart(scatterChartData)
        tabWidget.addTab(scatterTab, "scatter chart")

        pieTab = ddv.charts.createPieChart(pieChartData)
        tabWidget.addTab(pieTab, "pie chart")

        bwTab = ddv.charts.createBwChart(bwChartData)
        tabWidget.addTab(bwTab, "b w chart")

        candlestickTab = ddv.charts.createCandlestickChart(
            candlestickChartData)
        tabWidget.addTab(candlestickTab, "candlestick chart")

        grid = QGridLayout()
        grid.addWidget(tabWidget)

        #grid.addWidget(areaTab)

        self.setLayout(grid)
        """ левое расположение """
        size.setHorizontalStretch(1)
        self.table_view.setSizePolicy(size)
Exemple #8
0
    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)
Exemple #10
0
    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)
Exemple #11
0
    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)
Exemple #12
0
 def clearChart(self) -> None:
     if self.chart:
         self.chartView.setChart(QtCharts.QChart())
         self.chart.deleteLater()
         self.chart = None
Exemple #13
0
    def _generateChartImage(self):
        chart = QtCharts.QChart()

        chart.legend().setVisible(False)
        chart.setBackgroundBrush(QBrush(QColor("transparent")))
        chart.setMargins(QMargins(0, 0, 0, 0))
        chart.setTitleBrush(QBrush(Loader.QSSColor("@dark")))

        axis_pen = QPen(Loader.QSSColor("@dark"))
        axis_pen.setWidth(4)

        grid_line_pen = QPen(Loader.QSSColor("@light-gray"))

        labels_font = QFont(Loader.QSSVariable("@font"))
        labels_font.setPointSize(18)

        axis_x = QtCharts.QValueAxis()
        axis_y = QtCharts.QValueAxis()

        for axis in (axis_x, axis_y):
            axis.setLinePen(axis_pen)
            axis.setLabelFormat("%d")
            axis.setGridLinePen(grid_line_pen)
            axis.setLabelsFont(labels_font)

        chart.addAxis(axis_x, Qt.AlignBottom)
        chart.addAxis(axis_y, Qt.AlignLeft)
        

        current_series = {}
        max_s = 0
        for i, m in self._analysis.parameters().selectedMorphotypes().items():
            current_series[i] = QtCharts.QSplineSeries()
            current_series[i].setName(m.name())
            current_series[i].setColor(m.color())

            s = 0
            current_series[i].append(0, 0)
            for k, img in enumerate(self._analysis.processedImages()):
                s += img.detectionsCount().get(i, 0)
                current_series[i].append(k + 1, s)
            max_s = max(s, max_s)
            
            chart.addSeries(current_series[i])

            current_series[i].attachAxis(axis_x)
            current_series[i].attachAxis(axis_y)

            pen = current_series[i].pen()
            pen.setWidth(5)
            current_series[i].setPen(pen)

        chart.axisX().setRange(0, max(len(self._analysis.processedImages()), 4))
        chart.axisY().setRange(0, max(round(max_s), 4)*1.05)

        chart_view = QtCharts.QChartView(chart)
        chart_view.setRenderHint(QPainter.Antialiasing)
        chart_view.resize(QSize(1080, 500))

        chart_pixmap = chart_view.grab()
        self._analysis.setBase64ChartImage(ImageConverter.QPixmapToBase64(chart_pixmap, "png"))
    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)
Exemple #15
0
    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()
Exemple #16
0
    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)
def createSplineChart(data):

    chart = QtCharts.QChart()
    # chart.legend().hide()
    chart.setTitle("Spline chart (market shares)")

    axisX = QtCharts.QDateTimeAxis()
    # axisX.setTickCount(10);

    axisX.setFormat("MM-yyyy")
    #axisX.setFormat("yyyy/MM/dd hh:mm:ss:zzz");
    #axisX.setFormat("hh:mm:ss:zzz");

    axisX.setTitleText("Time")
    chart.addAxis(axisX, Qt.AlignBottom)

    axisY = QtCharts.QValueAxis()
    # axisY.setLabelFormat("%.2f");
    axisY.setTitleText("%")
    chart.addAxis(axisY, Qt.AlignLeft)

    # chart.axes(Qt.Vertical)[0].setRange(0, 100)
    chart.axes(Qt.Vertical)[0].setRange(0, 3)

    # seriesFilter = [0, 3, 4, 6]
    # seriesFilter = [0]
    # seriesFilter = [3, 4, 6, 7, 9, 10]
    seriesFilter = [3, 4]

    valuesToDraw = [data[1][i] for i in seriesFilter]
    namesToDraw = [data[2][i] for i in seriesFilter]

    for i in range(len(seriesFilter)):

        values = valuesToDraw[i]
        name = namesToDraw[i]

        series = QtCharts.QSplineSeries()
        series.setName(name)

        c1 = PySide2.QtWidgets.QColorDialog.getColor(
            options=PySide2.QtWidgets.QColorDialog.DontUseNativeDialog)
        series.setColor(c1)

        n = len(values)

        # print(values)

        # конвертируем столбец time в float, чтобы можно было использовать его как значения оси x
        for j in range(n):
            # print(x)
            time = data[0][j]
            series.append(float(time.toMSecsSinceEpoch()), values[j])

        chart.addSeries(series)

        series.attachAxis(axisX)
        series.attachAxis(axisY)

    # chart.createDefaultAxes()

    chartView = QtCharts.QChartView(chart)
    chartView.setRenderHint(QPainter.Antialiasing)

    return chartView
Exemple #18
0
    def __init__(self, data):

        QWidget.__init__(self)


        # Getting the Model

        self.model = CustomTableModel(data)


        # Creating a QTableView

        self.table_view = QTableView()

        self.table_view.setModel(self.model)


        # QTableView Headers

        resize = QHeaderView.ResizeToContents

        self.horizontal_header = self.table_view.horizontalHeader()

        self.vertical_header = self.table_view.verticalHeader()

        self.horizontal_header.setSectionResizeMode(resize)

        self.vertical_header.setSectionResizeMode(resize)

        self.horizontal_header.setStretchLastSection(True)


        # Creating QChart

        self.chart = QtCharts.QChart()

        self.chart.setAnimationOptions(QtCharts.QChart.AllAnimations)

        self.add_series("Magnitude (Column 1)", [0, 1])


        # Creating QChartView

        self.chart_view = QtCharts.QChartView(self.chart)

        self.chart_view.setRenderHint(QPainter.Antialiasing)


        # QWidget Layout

        self.main_layout = QHBoxLayout()

        size = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)


        # Left layout

        size.setHorizontalStretch(1)

        self.table_view.setSizePolicy(size)

        self.main_layout.addWidget(self.table_view)


        # Right Layout

        size.setHorizontalStretch(4)

        self.chart_view.setSizePolicy(size)

        self.main_layout.addWidget(self.chart_view)


        # Set the layout to the QWidget

        self.setLayout(self.main_layout)
Exemple #19
0
    def __init__(self) -> None:
        super().__init__()

        layout = self._main_layout = QVBoxLayout()
        size = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        size.setVerticalStretch(1)

        grid = QGridLayout()
        grid.setColumnStretch(3, 1)
        grid.addWidget(self._label("Bands:"), 0, 0)
        self.lat_bands_field = self._int_field(
            0, 360, tooltip="Number of latitude bands")
        grid.addWidget(self.lat_bands_field, 0, 1)

        # Control for setting initial global average temperature
        grid.addWidget(self._label("Init. Temp:"), 1, 0)
        self.gat0_field = self._int_field(
            -100,
            100,
            placeholder="°C",
            tooltip="Initial global average temperature, Celsius",
        )

        grid.addWidget(self.gat0_field, 1, 1)

        # Control for setting range of solar multiplier values
        grid.addWidget(self._label("Solar Multiplier:"), 2, 0)
        ff = self._float_field
        field = self.min_sol_mult_field = ff(
            0,
            100,
            placeholder="Min",
            tooltip="Minimum Solar Constant multiplier",
        )
        grid.addWidget(field, 2, 1)
        field = self.max_sol_mult_field = ff(
            0,
            100,
            placeholder="Max",
            tooltip="Maximum Solar Constant multiplier",
        )
        grid.addWidget(field, 2, 2)

        # Control rate of lateral heat transfer:
        grid.addWidget(self._label("Transfer Coefficient:"), 3, 0)
        field = self.lhtc_field = ff(
            0,
            10,
            placeholder="W/m^2",
            tooltip="Latitudinal heat transport coefficient, W/m^2",
        )
        grid.addWidget(field, 3, 1)

        layout.addLayout(grid)

        # Display of global average temperature vs. solar multiplier,
        #   rising vs. falling
        chart = self.gatsm_chart = QtCharts.QChart()
        chart.setAnimationOptions(QtCharts.QChart.AllAnimations)
        chart_view = self.gatsm_view = QtCharts.QChartView(chart)
        chart_view.setRenderHint(QPainter.Antialiasing)

        size.setVerticalStretch(1)
        chart_view.setSizePolicy(size)
        chart_view.setMinimumSize(480, 320)

        self._main_layout.addWidget(chart_view)

        # Display of albedo by latitude band, for a given
        # point on the rising plot
        hbox = QHBoxLayout()
        hbox.addStretch(1)

        vbox1 = QVBoxLayout()
        vbox1.addWidget(self._label("Rising", Qt.AlignCenter))
        vm = self.rising_vc = LatBandsVC()
        min_size = (192, 192)
        widget = vm.widget
        widget.setMinimumSize(*min_size)
        vbox1.addWidget(widget)
        hbox.addLayout(vbox1)

        hbox.addStretch(1)

        # Display of albedo by latitude band, for a given
        # point on the falling plot
        vbox2 = QVBoxLayout()
        vbox2.addWidget(self._label("Falling", Qt.AlignCenter))
        vm = self.falling_vc = LatBandsVC()
        widget = vm.widget
        widget.setMinimumSize(*min_size)
        vbox2.addWidget(widget)
        hbox.addLayout(vbox2)

        hbox.addStretch(1)

        self._main_layout.addLayout(hbox)
        self.setLayout(self._main_layout)
Exemple #20
0
    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"
Exemple #21
0
    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 createAreaChart(data):
    """
    axisX = QtCharts.QDateTimeAxis();
    # axisX.setTickCount(10);
    
    axisX.setFormat("yyyy");
    #axisX.setFormat("yyyy/MM/dd hh:mm:ss:zzz");
    #axisX.setFormat("hh:mm:ss:zzz");
    
    axisX.setTitleText("Time");
    chart.addAxis(axisX, Qt.AlignBottom);

    axisY = QtCharts.QValueAxis();
    # axisY.setLabelFormat("%.2f");
    axisY.setTitleText("%");
    chart.addAxis(axisY, Qt.AlignLeft);

    # chart.axes(Qt.Vertical)[0].setRange(0, 100)
    # chart.axes(Qt.Vertical)[0].setRange(0, 3)
    """

    series0 = QtCharts.QSplineSeries()

    series0.append(QPointF(1, 5))
    series0.append(QPointF(3, 7))
    series0.append(QPointF(7, 6))
    series0.append(QPointF(9, 7))
    series0.append(QPointF(12, 6))
    series0.append(QPointF(16, 7))
    series0.append(QPointF(18, 5))

    series1 = QtCharts.QSplineSeries()

    series1.append(QPointF(1, 3))
    series1.append(QPointF(3, 4))
    series1.append(QPointF(7, 3))
    series1.append(QPointF(8, 2))
    series1.append(QPointF(12, 3))
    series1.append(QPointF(16, 4))
    series1.append(QPointF(18, 3))
    """    

    # seriesFilter = [0, 3, 4, 6]
    # seriesFilter = [0]
    seriesFilter = [0]

    valuesToDraw = [data[1][i] for i in seriesFilter]
    namesToDraw = [data[2][i] for i in seriesFilter]
  

    i = 0

    values = valuesToDraw[i]
    name = namesToDraw[i]

    topLineSeries = QtCharts.QLineSeries()    

    n = len(values)

    print(values)

     # конвертируем столбец time в float, чтобы можно было использовать его как значения оси x
    for j in range(n):
        # print(x)
        time = data[0][j]                
        topLineSeries.append(float(time.toMSecsSinceEpoch()), values[j])

    """

    #areaSeries = QtCharts.QAreaSeries(topLineSeries);
    areaSeries = QtCharts.QAreaSeries(series0, series1)
    #areaSeries.setName(name);
    areaSeries.setName("name4535343534")

    pen = QPen(0x059605)
    pen.setWidth(3)
    areaSeries.setPen(pen)

    gradient = QLinearGradient(QPointF(0, 0), QPointF(0, 1))
    gradient.setColorAt(0.0, 0x3cc63c)
    gradient.setColorAt(1.0, 0x26f626)
    gradient.setCoordinateMode(QGradient.ObjectBoundingMode)
    areaSeries.setBrush(gradient)

    chart = QtCharts.QChart()
    chart.addSeries(areaSeries)
    # chart.legend().hide()
    chart.setTitle("Area chart (population by continents)")
    chart.createDefaultAxes()
    chart.axes(Qt.Horizontal)[0].setRange(0, 20)
    chart.axes(Qt.Vertical)[0].setRange(0, 10)

    chartView = QtCharts.QChartView(chart)
    chartView.setRenderHint(QPainter.Antialiasing)

    # areaSeries.attachAxis(axisX);
    # areaSeries.attachAxis(axisY);
    """
    for i in range(len(seriesFilter)):

        values = valuesToDraw[i]
        name = namesToDraw[i]
    
        series = QtCharts.QSplineSeries()
        series.setName(name)

        n = len(values)

        # print(values)

         # конвертируем столбец time в float, чтобы можно было использовать его как значения оси x
        for j in range(n):
            # print(x)
            time = data[0][j]                
            series.append(float(time.toMSecsSinceEpoch()), values[j])

        chart.addSeries(series)

        series.attachAxis(axisX);        
        series.attachAxis(axisY);
    
    
    
    """

    return chartView
Exemple #23
0
    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)
Exemple #24
0
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))
gradient.setCoordinateMode(QGradient.ObjectBoundingMode)
series.setBrush(gradient)

chart = QtCharts.QChart()
chart.addSeries(series)
chart.setTitle('Simple Area Chart')
chart.legend().hide()
chart.createDefaultAxes()
chart.axes(Qt.Horizontal)[0].setRange(0, 3)
chart.axes(Qt.Vertical)[0].setRange(0, 10)

chartView = QtCharts.QChartView(chart)
chartView.setWindowTitle('Area Chart')
chartView.resize(800, 600)
chartView.show()

app.exec_()
Exemple #25
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_()
Exemple #26
0
    def __init__(self, parent=None):
        super(MainWidget, self).__init__(parent)
        self.chart = QtCharts.QChart()
        self.series = QtCharts.QBarSeries()

        self.main_layout = QGridLayout()
        self.button_layout = QGridLayout()
        self.font_layout = QFormLayout()

        self.font_size = QDoubleSpinBox()

        self.legend_posx = QDoubleSpinBox()
        self.legend_posy = QDoubleSpinBox()
        self.legend_width = QDoubleSpinBox()
        self.legend_height = QDoubleSpinBox()

        self.detach_legend_button = QPushButton("Toggle attached")
        self.detach_legend_button.clicked.connect(self.toggle_attached)
        self.button_layout.addWidget(self.detach_legend_button, 0, 0)

        self.add_set_button = QPushButton("add barset")
        self.add_set_button.clicked.connect(self.add_barset)
        self.button_layout.addWidget(self.add_set_button, 2, 0)

        self.remove_barset_button = QPushButton("remove barset")
        self.remove_barset_button.clicked.connect(self.remove_barset)
        self.button_layout.addWidget(self.remove_barset_button, 3, 0)

        self.align_button = QPushButton("Align (Bottom)")
        self.align_button.clicked.connect(self.set_legend_alignment)
        self.button_layout.addWidget(self.align_button, 4, 0)

        self.bold_button = QPushButton("Toggle bold")
        self.bold_button.clicked.connect(self.toggle_bold)
        self.button_layout.addWidget(self.bold_button, 8, 0)

        self.italic_button = QPushButton("Toggle italic")
        self.italic_button.clicked.connect(self.toggle_italic)
        self.button_layout.addWidget(self.italic_button, 9, 0)

        self.legend_posx.valueChanged.connect(self.update_legend_layout)
        self.legend_posy.valueChanged.connect(self.update_legend_layout)
        self.legend_width.valueChanged.connect(self.update_legend_layout)
        self.legend_height.valueChanged.connect(self.update_legend_layout)

        legend_layout = QFormLayout()
        legend_layout.addRow("HPos", self.legend_posx)
        legend_layout.addRow("VPos", self.legend_posy)
        legend_layout.addRow("Width", self.legend_width)
        legend_layout.addRow("Height", self.legend_height)

        self.legend_settings = QGroupBox("Detached legend")
        self.legend_settings.setLayout(legend_layout)
        self.button_layout.addWidget(self.legend_settings)
        self.legend_settings.setVisible(False)

        # Create chart view with the chart
        self.chart_view = QtCharts.QChartView(self.chart, self)

        # Create spinbox to modify font size
        self.font_size.setValue(self.chart.legend().font().pointSizeF())
        self.font_size.valueChanged.connect(self.font_size_changed)

        self.font_layout.addRow("Legend font size", self.font_size)

        # Create layout for grid and detached legend
        self.main_layout.addLayout(self.button_layout, 0, 0)
        self.main_layout.addLayout(self.font_layout, 1, 0)
        self.main_layout.addWidget(self.chart_view, 0, 1, 3, 1)
        self.setLayout(self.main_layout)

        self.create_series()
Exemple #27
0
    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)
Exemple #28
0
    def make_ui(self):
        self.q_chart = QtCharts.QChart()
        self.q_chart.legend().hide()

        self.q_chart.createDefaultAxes()

        # Setting X-axis
        self.axis_x = QtCharts.QValueAxis()
        # self.axis_x.setTickCount(10)
        # self.axis_x.setTitleText("sample")
        self.q_chart.addAxis(self.axis_x, Qt.AlignBottom)

        # Setting Y-axis
        self.axis_y = QtCharts.QValueAxis()
        # self.axis_y.setTickCount(10)
        # self.axis_y.setLabelFormat("%.2f")
        # self.axis_y.setTitleText("V")
        self.q_chart.addAxis(self.axis_y, Qt.AlignLeft)

        self.plot_series("Magnitude (Column 1)", [(0, 1), (2, 2)], True)

        chart_view = QtCharts.QChartView(self.q_chart)
        # chart_view.setRenderHint(QPainter.Antialiasing)

        self.widgets['chart'] = chart_view

        # matplotlib plot
        # https://matplotlib.org/gallery/user_interfaces/embedding_in_qt_sgskip.html
        static_canvas = FigureCanvas(Figure(tight_layout=True))
        static_toolbar = NavigationToolbar(static_canvas, self._parent)
        static_toolbar.setObjectName('StaticToolBar')
        # self._parent.addToolBar(Qt.TopToolBarArea, static_toolbar)

        self.dynamic_canvas = FigureCanvas(Figure(tight_layout=True))

        self._parent.addToolBar(
            Qt.BottomToolBarArea,
            NavigationToolbar(self.dynamic_canvas, self._parent))

        self._static_ax = static_canvas.figure.subplots()
        t = np.linspace(0, 10, 501)
        self._static_ax.plot(t, np.tan(t), ".")
        self._static_ax.grid()

        self._dynamic_ax = self.dynamic_canvas.figure.subplots()
        self._dynamic_ax.tick_params(labelsize=20)
        self._dynamic_ax.set_xlabel('hello')

        # self._dynamic_ax.set_autoscale_on(True)
        # self._dynamic_ax.autoscale_view(True, True, True)

        # t = np.linspace(0, 10, 1)
        # y = np.sin(t + time.time())
        # Shift the sinusoid as a function of time.
        self.dynamic_line, = self._dynamic_ax.plot([], [], 'r.')
        # self._dynamic_ax.xaxis.set_label_size(2)

        vbox = QVBoxLayout()
        vbox.addWidget(chart_view)
        vbox.addWidget(static_canvas)
        vbox.addWidget(static_toolbar)
        vbox.addWidget(self.dynamic_canvas)

        main_widget = QFrame()
        main_widget.setLayout(vbox)

        return main_widget
Exemple #29
0
    def __init__(self):
        QObject.__init__(self)

        self.module_path = os.path.dirname(__file__)

        self.tables = []
        self.series_dict = dict()

        n_cpu_cores = cpu_count()

        print("number of cpu cores: ", n_cpu_cores)

        self.pool = Pool(processes=n_cpu_cores)
        self.coins = Coins(self.pool)
        self.model = Model()
        self.chart = QtCharts.QChart()
        self.callout = Callout(self.chart)

        self.callout.hide()

        # loading widgets from designer file

        loader = QUiLoader()

        loader.registerCustomWidget(QtCharts.QChartView)

        self.window = loader.load(self.module_path +
                                  "/ui/application_window.ui")

        main_frame = self.window.findChild(QFrame, "main_frame")
        chart_frame = self.window.findChild(QFrame, "chart_frame")
        chart_cfg_frame = self.window.findChild(QFrame, "chart_cfg_frame")
        button_read_tags = self.window.findChild(QPushButton,
                                                 "button_read_tags")
        button_save_matrix = self.window.findChild(QPushButton,
                                                   "button_save_matrix")
        button_save_image = self.window.findChild(QPushButton,
                                                  "button_save_image")
        button_reset_zoom = self.window.findChild(QPushButton,
                                                  "button_reset_zoom")
        self.table_view = self.window.findChild(QTableView, "table_view")
        self.chart_view = self.window.findChild(QtCharts.QChartView,
                                                "chart_view")
        self.label_mouse_coords = self.window.findChild(
            QLabel, "label_mouse_coords")

        self.table_view.horizontalHeader().setSectionResizeMode(
            QHeaderView.ResizeToContents)
        self.table_view.verticalHeader().setSectionResizeMode(
            QHeaderView.ResizeToContents)
        self.table_view.setModel(self.model)

        # signal connection

        button_read_tags.clicked.connect(self.read_tags)
        button_save_matrix.clicked.connect(self.save_matrix)
        button_save_image.clicked.connect(self.save_image)
        button_reset_zoom.clicked.connect(self.reset_zoom)
        self.table_view.selectionModel().selectionChanged.connect(
            self.selection_changed)
        self.coins.new_spectrum.connect(self.on_new_spectrum)
        self.model.dataChanged.connect(self.data_changed)

        # Creating QChart
        self.chart.setAnimationOptions(QtCharts.QChart.AllAnimations)
        self.chart.setTheme(QtCharts.QChart.ChartThemeLight)
        self.chart.setAcceptHoverEvents(True)

        self.axis_x = QtCharts.QValueAxis()
        self.axis_x.setTitleText("Energy [keV]")
        self.axis_x.setRange(0, 100)
        self.axis_x.setLabelFormat("%.0f")

        self.axis_y = QtCharts.QValueAxis()
        self.axis_y.setTitleText("Intensity [a.u.]")
        self.axis_y.setRange(0, 100)
        self.axis_y.setLabelFormat("%d")

        self.chart.addAxis(self.axis_x, Qt.AlignBottom)
        self.chart.addAxis(self.axis_y, Qt.AlignLeft)

        self.chart_view.setChart(self.chart)
        self.chart_view.setRenderHint(QPainter.Antialiasing)
        self.chart_view.setRubberBand(QtCharts.QChartView.RectangleRubberBand)

        # custom stylesheet

        style_file = QFile(self.module_path + "/ui/custom.css")
        style_file.open(QFile.ReadOnly)

        self.window.setStyleSheet(style_file.readAll().data().decode("utf-8"))

        style_file.close()

        # effects

        main_frame.setGraphicsEffect(self.card_shadow())
        chart_frame.setGraphicsEffect(self.card_shadow())
        chart_cfg_frame.setGraphicsEffect(self.card_shadow())
        button_read_tags.setGraphicsEffect(self.button_shadow())
        button_save_matrix.setGraphicsEffect(self.button_shadow())
        button_save_image.setGraphicsEffect(self.button_shadow())
        button_reset_zoom.setGraphicsEffect(self.button_shadow())

        self.window.show()