class PlotWidget(QtWidgets.QWidget): def __init__(self, parent=None): QtWidgets.QWidget.__init__(self, parent) self.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.figure = plt.figure() self.canvas = FigureCanvas(self.figure) self.toolbar = NavigationToolbar(self.canvas, self) self.button = QtWidgets.QPushButton("Plot") self.button.clicked.connect(self.plot) layout = QtWidgets.QVBoxLayout() layout.addWidget(self.toolbar) layout.addWidget(self.canvas) layout.addWidget(self.button) self.setLayout(layout) def plot(self): data = [x for x in range(10)] ax = self.figure.add_subplot(111) ax.hold(False) ax.plot(data, "*-") self.canvas.draw()
class PlotWidget(Widgets.WidgetBase): def __init__(self, plot, width=500, height=500): super(PlotWidget, self).__init__() self.widget = FigureCanvas(plot.get_figure()) self.widget._resizeEvent = self.widget.resizeEvent self.widget.resizeEvent = self.resize_event self.plot = plot self.logger = plot.logger def set_plot(self, plot): self.plot = plot self.logger = plot.logger self.logger.debug("set_plot called") def configure_window(self, wd, ht): fig = self.plot.get_figure() fig.set_size_inches(float(wd) / fig.dpi, float(ht) / fig.dpi) def resize_event(self, event): rect = self.widget.geometry() x1, y1, x2, y2 = rect.getCoords() width = x2 - x1 height = y2 - y1 if width > 0 and height > 0: self.configure_window(width, height) self.widget._resizeEvent(event)
def __init__(self): QWidget.__init__(self) self.win_list=windows() self.setFixedSize(900, 600) self.setWindowIcon(QIcon(os.path.join(get_image_file_path(),"doping.png"))) self.setWindowTitle(_("Doping profile editor (www.gpvdm.com)")) self.win_list.set_window(self,"doping") self.main_vbox=QVBoxLayout() toolbar=QToolBar() toolbar.setIconSize(QSize(48, 48)) self.save = QAction(QIcon(os.path.join(get_image_file_path(),"save.png")), _("Save"), self) self.save.triggered.connect(self.callback_save) toolbar.addAction(self.save) spacer = QWidget() spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) toolbar.addWidget(spacer) self.help = QAction(QIcon(os.path.join(get_image_file_path(),"help.png")), _("Help"), self) self.help.triggered.connect(self.callback_help) toolbar.addAction(self.help) self.main_vbox.addWidget(toolbar) self.fig = Figure(figsize=(5,4), dpi=100) self.ax1=None self.show_key=True canvas = FigureCanvas(self.fig) #canvas.set_background('white') #canvas.set_facecolor('white') canvas.figure.patch.set_facecolor('white') canvas.show() self.main_vbox.addWidget(canvas) self.tab = QTableWidget() self.tab.resizeColumnsToContents() self.tab.verticalHeader().setVisible(False) self.tab.clear() self.tab.setColumnCount(4) self.tab.setSelectionBehavior(QAbstractItemView.SelectRows) self.load() self.build_mesh() self.tab.cellChanged.connect(self.tab_changed) self.main_vbox.addWidget(self.tab) self.draw_graph() self.setLayout(self.main_vbox) return
def plot_data(self): if not self.has_graph: new_x = [mdates.datestr2num(x) for x in self.graph_x] plt.xlabel('Time') plt.ylabel('Count') ax = self.fig.add_subplot(111) ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M')) ax.plot(new_x, self.graph_y, 'r-') ax.get_xaxis().set_ticks([]) #ax.get_yaxis().set_ticks([]) self.canvas = FigureCanvas(self.fig) self.graph_layout.addWidget(self.canvas) self.canvas.draw() self.has_graph = True else: self.graph_layout.removeWidget(self.canvas) self.canvas.close() self.fig.clf() plt.xlabel('Time') plt.ylabel('Count') ax = self.fig.add_subplot(111) ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M')) new_x = [mdates.datestr2num(x) for x in self.graph_x] ax.plot(new_x, self.graph_y, 'r-') ax.get_xaxis().set_ticks([]) #ax.get_yaxis().set_ticks([]) self.canvas = FigureCanvas(self.fig) self.graph_layout.addWidget(self.canvas) self.canvas.draw()
class MPLibWidget(QtWidgets.QWidget): """ base MatPlotLib widget """ def __init__(self, parent=None): super(MPLibWidget, self).__init__(parent) self.figure = Figure() self.canvas = FigureCanvasQTAgg(self.figure) self.canvas.setParent(self) self.mpl_toolbar = NavigationToolbar2QT(self.canvas, self) self.canvas.mpl_connect('key_press_event', self.on_key_press) self.axes = self.figure.add_subplot(111) # self.axes.hold(False) self.compute_initial_figure() self.layoutVertical = QtWidgets.QVBoxLayout(self) self.layoutVertical.addWidget(self.canvas) self.layoutVertical.addWidget(self.mpl_toolbar) def on_key_press(self, event): """not working""" print('you pressed', event.key) # implement the default mpl key press events described at # http://matplotlib.org/users/navigation_toolbar.html#navigation-keyboard-shortcuts key_press_handler(event, self.canvas, self.mpl_toolbar) def compute_initial_figure(self): pass
def __init__(self, parent=None, width=5, height=4, dpi=100): fig = Figure(figsize=(width, height), dpi=dpi) self.axes = fig.add_subplot(111) # We want the axes cleared every time plot() is called self.axes.hold(False) self.compute_initial_figure() # FigureCanvas.__init__(self, fig) self.setParent(parent) self.setStyleSheet("{background-color:transparent;border:none;}") """FigureCanvas.setSizePolicy(self, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)""" FigureCanvas.updateGeometry(self) self.tootlbar = NavigationToolbar(self, parent) self.tootlbar.hide() self.fid = 0 self.data = [] self.index = []
def __init__(self, parent=None): super(DoseCalc, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.fig = Figure() self.axes = self.fig.add_subplot(1, 1, 1) self.axes.hold(False) self.Canvas = FigureCanvas(self.fig) self.Canvas.setParent(self.ui.plot_widget) self.Canvas.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.Canvas.updateGeometry() l = QVBoxLayout(self.ui.plot_widget) l.addWidget(self.Canvas) self.fig_erg = Figure() self.axes_erg = self.fig_erg.add_subplot(1, 1, 1, projection='3d') self.axes_erg.axis('off') self.axes_erg.hold(False) self.Canvas_erg = FigureCanvas(self.fig_erg) self.Canvas_erg.setParent(self.ui.erg_widget) self.Canvas_erg.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.Canvas_erg.updateGeometry() l2 = QVBoxLayout(self.ui.erg_widget) l2.addWidget(self.Canvas_erg)
def __init__(self): self.fig = Figure() FigureCanvas.__init__(self, self.fig) self.main_plot = None self.create_main_plot()
def keyPressEvent(self, event): if self.redetecter: self.detecter() key = event.key() txt = event.text() modifiers = event.modifiers() accept = True debug("key: ", key) if key == Qt.Key_Delete and self.select: if shift_down(event): self.executer("%s.cacher()" %self.select.nom) else: self.executer("%s.supprimer()" %self.select.nom) elif key in (Qt.Key_Return, Qt.Key_Enter) and self.editeur.objet is not self.select: self.editer(shift_down(event)) elif self.editeur and not self.editeur.key(key, txt, modifiers): accept = False if key == Qt.Key_Escape: if self.action_en_cours is not None: self.interrompre_action_en_cours() elif self.interaction: print("ESCAPE !") self.interaction(special="ESC") accept = True if not accept: FigureCanvasQTAgg.keyPressEvent(self, event)
def create_canvas(self): # pragma: no cover self.fig = Figure() canvas = FigureCanvas(self.fig) self.ui.mainLayout.addWidget(canvas) canvas.setFocusPolicy(QtCore.Qt.StrongFocus) # Add subplots gridspec = GridSpec(2, 4) self.map_ax = self.fig.add_subplot( gridspec.new_subplotspec((0, 0), rowspan=2, colspan=2) ) self.spectrum_ax = self.fig.add_subplot( gridspec.new_subplotspec((0, 2), rowspan=1, colspan=2) ) self.hist_ax = self.fig.add_subplot( gridspec.new_subplotspec((1, 2), rowspan=1, colspan=1) ) self.edge_ax = self.fig.add_subplot( gridspec.new_subplotspec((1, 3), rowspan=1, colspan=1) ) # Create the colorbar on the histogram axes self.cbar = plots.draw_histogram_colorbar(ax=self.hist_ax, cmap="viridis", norm=Normalize(0, 1)) self.cbar.ax.set_xlabel("Map Value") # Adjust the margins self.fig.tight_layout(pad=0) self.fig.canvas.draw_idle()
def __init__(self): self._fig = Figure(dpi=170) FigureCanvasQTAgg.__init__(self, self._fig) FigureCanvasQTAgg.setSizePolicy(self, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) self._fig.subplots_adjust(left=0, right=1, top=1, bottom=0) self._mpl_toolbar = NavigationToolbar2QTAgg(self, self) self._mpl_toolbar.hide() self.__taking = False self._scale = 'log' self._scales = OrderedDict() self._scales['Logarithmic'] = 'log' self._scales['Linear'] = 'linear' self._scales['Square Root'] = 'sqrt' self._scales['Power'] = 'power' self._scales['Arc Sinh'] = 'arcsinh' self._gc = None self._upperCut = 99.75 self._lowerCut = 0.25 self._cmap = 'gray' self._refresh_timer = QtCore.QTimer(self) self._refresh_timer.setSingleShot(True) self._refresh_timer.timeout.connect(self._refreshConcrete) self.apertures = []
def __init__(self, parent=None, size = (7,3.5), dpi = 100, logx = False, logy = False, legends = True, bw = False): self.fig = Figure(figsize=size, dpi=dpi) #in inches FigureCanvas.__init__(self, self.fig) FigureCanvas.setSizePolicy(self, qt.QSizePolicy.Expanding, qt.QSizePolicy.Expanding) self.curveTable = None self.dpi=dpi ddict = {'logx':logx, 'logy': logy, 'legends':legends, 'bw':bw} self.ax=None self.curveList = [] self.curveDict = {} self.setParameters(ddict) #self.setBlackAndWhiteEnabled(bw) #self.setLogXEnabled(logx) #self.setLogYEnabled(logy) #self.setLegendsEnabled(legends) self.xmin = None self.xmax = None self.ymin = None self.ymax = None self.limitsSet = False
def __init__(self, parent=None, width=6, height=4, dpi=110): """ Init canvas. """ self.fig = Figure(figsize=(width, height), dpi=dpi) # Here one can adjust the position of the CTX plot area. # self.axes = self.fig.add_subplot(111) self.axes = self.fig.add_axes([0.1, 0.1, 0.85, 0.85]) self.axes.grid(True) self.axes.set_xlabel("(no data)") self.axes.set_ylabel("(no data)") FigureCanvas.__init__(self, self.fig) layout = QVBoxLayout(parent) layout.addWidget(self) parent.setLayout(layout) FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) # next too lines are needed in order to catch keypress events in plot canvas by mpl_connect() FigureCanvas.setFocusPolicy(self, QtCore.Qt.ClickFocus) FigureCanvas.setFocus(self)
class ColorbarWidget(QWidget): def __init__(self, parent=None): super(ColorbarWidget, self).__init__(parent) fig = Figure() rect = 0.25, 0.05, 0.1, 0.90 self.cb_axes = fig.add_axes(rect) self.canvas = FigureCanvas(fig) self.setLayout(QVBoxLayout()) self.layout().addWidget(self.canvas) self.button = QPushButton("Update") self.layout().addWidget(self.button) self.button.pressed.connect(self._update_cb_scale) self._create_colorbar(fig) def _create_colorbar(self, fig): self.mappable = ScalarMappable(norm=SymLogNorm(0.0001, 1,vmin=-10., vmax=10000.), cmap=DEFAULT_CMAP) self.mappable.set_array([]) fig.colorbar(self.mappable, ax=self.cb_axes, cax=self.cb_axes) def _update_cb_scale(self): self.mappable.colorbar.remove() rect = 0.25, 0.05, 0.1, 0.90 self.cb_axes = self.canvas.figure.add_axes(rect) self.mappable = ScalarMappable(Normalize(30, 4300), cmap=DEFAULT_CMAP) self.mappable.set_array([]) self.canvas.figure.colorbar(self.mappable, ax=self.cb_axes, cax=self.cb_axes) self.canvas.draw()
def __init__(self, parent=None, width=4, height=3, dpi=100, use_seaborn=False, style=0, context=0): self.seaborn = use_seaborn if use_seaborn: import seaborn as sns sns.set_style(self.SEABORN_STYLE[style]) sns.set_context(self.SEABORN_CONTEXT[context]) # set matplitlib figure object self.fig = Figure(figsize=(width, height), dpi=int(dpi)) self.axes = self.fig.add_subplot(111) self.axes.hold(True) # call constructor of FigureCanvas super(Figurecanvas, self).__init__(self.fig) self.setParent(parent) # expand plot area as large as possible FigureCanvas.setSizePolicy(self, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) self.x_min = 0 self.x_max = 30 # set color map object self.__cm = matplotlib.cm.gist_rainbow
class GraphTab(QWidget): def __init__(self, options): super(GraphTab, self).__init__() self.options = options self.options.reset.connect(self.reset) self.options.redraw.connect(self.redraw) self.commodities = CommodityBox(options) self.commodities.changed.connect(self.redraw) self.fig = Figure() self.ax = self.fig.add_subplot(111) self.canvas = FigureCanvas(self.fig) self.canvas.setParent(self) self.mpl_toolbar = NavigationToolbar(self.canvas, self) self.cmap = get_cmap('gist_ncar') graphLayout = QVBoxLayout() graphLayout.addWidget(self.canvas) graphLayout.addWidget(self.mpl_toolbar) layout = QHBoxLayout(self) layout.addWidget(self.commodities) layout.addLayout(graphLayout) self.running_total = None def reset(self): options = self.options self.commodity = options.show_currency.currentText() self.merge = bool(self.commodity and options.merge.isChecked()) filter = options.filter.text() self.running_total, self.total = options.journal.time_series(filter, self.commodity, self.merge) self.redraw() def redraw(self): self.ax.clear() if not self.running_total: return lines = len(self.total) colors = map(self.cmap, ((x+0.5)/lines for x in range(lines))) for color, (commodity, amount) in zip(colors, sorted(self.total.items(), key=lambda x: x[1].number(), reverse=True)): if commodity not in self.commodities: continue series = self.running_total[commodity] x = sorted(series.keys()) y = [series[i].number() for i in x] label = ("%s (%." + str(amount.commodity.precision) + "f %s)") % (commodity, amount.number(), amount.commodity.symbol) self.ax.plot_date(x, y, fmt='o-', color=color, label=label) if self.commodity: self.ax.set_ylabel(self.commodity) self.ax.legend(loc='upper left') self.fig.canvas.draw()
class Window(QDialog): # https://stackoverflow.com/questions/12459811/how-to-embed-matplotlib-in-pyqt-for-dummies def __init__(self, parent=None): super(Window, self).__init__(parent) # a figure instance to plot on self.figure = plt.figure() # this is the Canvas Widget that displays the `figure` # it takes the `figure` instance as a parameter to __init__ self.canvas = FigureCanvas(self.figure) # this is the Navigation widget # it takes the Canvas widget and a parent self.toolbar = NavigationToolbar(self.canvas, self) # Just some button connected to `plot` method self.button = QPushButton('Plot') self.button.clicked.connect(self.plot) # set the layout layout = QVBoxLayout() layout.addWidget(self.toolbar) layout.addWidget(self.canvas) layout.addWidget(self.button) self.setLayout(layout) def plot(self): ''' plot some random stuff ''' # random data data = [random.random() for i in range(10)] # instead of ax.hold(False) self.figure.clear() # create an axis ax = self.figure.add_subplot(111) # discards the old graph # ax.hold(False) # deprecated, see above # plot data ax.plot(data, '*-') # refresh canvas self.canvas.draw() def keyPressEvent(self, event): # http://zetcode.com/gui/pyqt5/eventssignals/ if event.key() == QtCore.Qt.Key_Escape: self.close() if event.key() == QtCore.Qt.Key_Space: global gridLayout item = gridLayout.itemAtPosition(1,1) w = item.widget() w.setText("test")
def mouseReleaseEvent(self, event): button = event.button() if button == Qt.LeftButton: self.onLeftUp(event) elif button == Qt.RightButton: self.onRightUp(event) else: FigureCanvasQTAgg.mouseReleaseEvent(self, event)
def mousePressEvent(self, event): button = event.button() if button == Qt.LeftButton: self.onLeftDown(event) elif button == Qt.RightButton: self.onRightDown(event) else: FigureCanvasQTAgg.mousePressEvent(self, event)
def __init__(self, parent, width, height, dpi=100): self.fig = Figure(figsize=(width, height), dpi=dpi) self.ax = self.fig.add_subplot(111) self.ax.hold(False) self.ax.xaxis.set_visible(False) self.ax.yaxis.set_visible(False) FigCanvas.__init__(self, self.fig) self.setParent(parent)
def __init__(self, parent=None): self.fig = Figure(dpi=40) self.axes = self.fig.add_subplot(111) self.axes.hold(False) self.fig.set_facecolor('white') FigureCanvas.__init__(self, self.fig) self.setParent(parent) self.axes.get_yaxis().set_visible(False) self.fig.tight_layout(pad=1, h_pad=1)
class MainWindow(QMainWindow, Ui_MainWindow): def __init__(self): super(MainWindow, self).__init__() self.setupUi(self) self.setWindowTitle('Fit Window') self._create_mplplot() self._peak_picker = self._create_peak_picker(self._canvas) self._onpick = self._canvas.mpl_connect('pick_event', self._on_pick) def _create_mplplot(self): x = np.arange(1,101, 0.01) mu, sigma = 50, 5 y = np.exp( - (x - mu)**2 / (2 * sigma**2)) fig = Figure() axes = fig.add_subplot(111) axes.plot(x, y, color='black') axes.set_title('Text', y=1.02) self._canvas = FigureCanvas(fig) print(dir(FigureCanvas)) self._filter = MouseClickMonitor(self._canvas) self._canvas.installEventFilter(self._filter) self.mpllayout.addWidget(self._canvas) self._canvas.draw() return fig def _create_peak_picker(self, canvas): picker = PeakPickerTool(canvas) self.on_region_update(picker.lines[0].get_xdata()[0], picker.lines[1].get_xdata()[0]) picker.region_updated.connect(self.on_region_update) return picker def _on_pick(self, evt): if not evt.mouseevent.dblclick: return print(dir(evt.artist.get_text())) # print("Title double clicked at matplotlib coords",evt.mouseevent.x, evt.mouseevent.y) # print("Canvas width=",self._canvas.width(), "height=", self._canvas.height()) # editor = QLineEdit(self._canvas) # editor.setAttribute(Qt.WA_DeleteOnClose) # editor.setText(self._canvas.figure.get_axes()[0].get_title()) # self._canvas.figure.get_axes()[0].set_title('') # self._canvas.draw() # editor.move(evt.mouseevent.x - (0.5*editor.width()), self._canvas.height() - evt.mouseevent.y - 0.5*editor.height()) # editor.show() # self._editor = editor def on_region_update(self, leftx, rightx): self.table_widget.setItem(0, 1, QTableWidgetItem(str(leftx))) self.table_widget.setItem(1, 1, QTableWidgetItem(str(rightx)))
def __init__(self, parent=None, width=6, height=4, dpi=100): self.fig = Figure(figsize=(width, height), dpi=dpi) super(MplCanvas, self).__init__(self.fig) self.setParent(parent) self.axes = self.fig.add_subplot(1, 1, 1) FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) self.plot()
def __init__(self, parent=None, width=5.0, height=4.0, dpi=100): fig = Figure((width, height), dpi=dpi) self.axes = fig.add_subplot(1, 1, 1) FigureCanvas.__init__(self, fig) self.setParent(parent) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.updateGeometry() self.plot()
def __init__(self): # Figure self.figure = Figure() # Add subplot for plot and legend self.ax = self.figure.add_axes([0.1, 0.15, 0.8, 0.8]) # Canvas initialization FigCanvas.__init__(self, self.figure) # Set empty ticks self.ax.set_xticks([]) self.ax.set_yticks([])
class PlotFigure(object): signals = [] canvas = None def __init__(self, parent=None): self.fig = Figure(figsize=(600, 600), dpi=72, facecolor=(1, 1, 1), edgecolor=(0, 0, 0)) self.canvas = FigureCanvas(self.fig) def addSeries(self, series): self.rmSeries(series) # Add a new series if self.signals: if((self.signals[0].xunits == series.xunits) and (self.signals[0].yunits == series.yunits)): self.signals.append(series) else: self.signals = [series] else: self.signals = [series] def rmSeries(self, series): if self.signals: try: self.signals.remove(series) except: pass def clearSeries(self): self.signals = [] def draw(self): self.ax = self.fig.add_subplot(1, 1, 1) self.ax.cla() for s in self.signals: self.ax.plot(s.xvalues, s.data, label=s.label) if len(self.signals): self.ax.set_xlabel(self.signals[0].xunits) self.ax.set_ylabel(self.signals[0].yunits) handles, labels = self.ax.get_legend_handles_labels() self.ax.legend(handles[::-1], labels[::-1]) self.ax.legend(handles, labels) try: self.plotExtras() except: pass self.canvas.draw() def getWidget(self): return self.canvas
def test_resize_qt(): # This test just ensures that the code runs, but doesn't check for now # that the behavior is correct. pytest.importorskip('PyQt5') from PyQt5.QtWidgets import QMainWindow from matplotlib.figure import Figure from matplotlib.backends.backend_qt5 import FigureManagerQT from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg fig = Figure() canvas = FigureCanvasQTAgg(fig) canvas.manager = FigureManagerQT(canvas, 0) # noqa ax = fig.add_subplot(1, 1, 1) canvas.draw = Mock(side_effect=canvas.draw) from matplotlib.backends.backend_qt5 import qApp window = QMainWindow() window.setCentralWidget(canvas) window.show() x1 = np.random.normal(0, 1, 10000000) y1 = np.random.normal(0, 1, 10000000) a = ScatterDensityArtist(ax, x1, y1) ax.add_artist(a) canvas.draw() assert not a.stale assert canvas.draw.call_count == 1 window.resize(300, 300) # We can't actually check that stale is set to True since it only remains # so for a short amount of time, but we can check that draw is called twice # (once at the original resolution then once with the updated resolution). start = time.time() while time.time() - start < 1: qApp.processEvents() assert canvas.draw.call_count == 3 assert not a.stale start = time.time() while time.time() - start < 1: qApp.processEvents() a.remove() qApp.processEvents()
class LiveGraphQt4(Backend): """Ultimately, this is a QWidget (as well as a FigureCanvasAgg, etc.).""" def show(self, delay=50): self.canvas = FigureCanvasQTAgg(self.figure) self.canvas.show() self.timer = QtCore.QTimer(self.canvas) self.timer.timeout.connect(self.run) super().show(delay)
def __init__(self, data_frame, parent=None): """data_frame is Pandas DataFrame""" if data_frame is None: self.generate_data() else: self.data = data_frame self.fig = Figure() # TODO change to dynamic ylim self.axes = self.fig.add_subplot(111, ylim=(0.0, 200.0)) self.axes.hold(False) FigureCanvas.__init__(self, self.fig) self.plot(data_frame)
def __init__(self, samplePoints, filteredResistivity, voltageSpacing, apparentResistivity, voltageSpacingExtrapolated, newResistivity, xlabel='Electrode Spacing (m)', ylabel='Apparent Resitivity (ohm-m)', linestyle='--', marker='o', dpi=150, hold=False, colors=colors[0:5:4]): plt.clf() # Save figure input parameters as class properties self.samplePoints = samplePoints self.filteredResistivity = filteredResistivity self.voltageSpacing = voltageSpacing self.apparentResistivity = apparentResistivity self.voltageSpacingExtrapolated = voltageSpacingExtrapolated self.newResistivity = newResistivity self.xlabel = xlabel self.ylabel = ylabel self.linestyle = linestyle self.marker = marker self.dpi = dpi self.hold = hold self.colors = colors self.fig = Figure(dpi=dpi) # Super from the class for Qt super(ReportCanvas, self).__init__(self.fig) # Initialize a FigureCanvas from the figure FigureCanvas.__init__(self, self.fig) # Allow the FigureCanvas to adjust with Main window using mpl Qt5 API FigureCanvas.setSizePolicy( self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) # self.setParent(self.ax.figure.canvas) self.ax = plt.gca() self.ax.set_xlabel(xlabel) self.ax.set_ylabel(ylabel) self.axes = self.fig.add_subplot(111) self.axes.hold(hold) self.initFigure() # Allow the FigureCanvas to adjust with Main window using mpl Qt5 API FigureCanvas.setSizePolicy( self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) # Super from the class for Qt super(ReportCanvas, self).__init__(self.fig)
def setup(self, MainWindow): ''' Creates Qt interactor ''' #if called as a script, then treat as a mainwindow, otherwise treat as a generic widget if hasattr(MainWindow,'setCentralWidget'): MainWindow.setCentralWidget(self.centralWidget) else: self.centralWidget=MainWindow MainWindow.setWindowTitle("OpenRS - model viewer v%s" %__version__) #create new layout to hold both VTK and Qt interactors mainlayout=QtWidgets.QHBoxLayout(self.centralWidget) #create VTK widget self.vtkWidget = QVTKRenderWindowInteractor(self.centralWidget) #create Qt layout to contain interactions load_model_box = QtWidgets.QGridLayout() #create VTK widget self.vtkWidget = QVTKRenderWindowInteractor(self.centralWidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.MinimumExpanding) sizePolicy.setHorizontalStretch(100) sizePolicy.setVerticalStretch(100) self.vtkWidget.setSizePolicy(sizePolicy) self.vtkWidget.setMinimumSize(QtCore.QSize(800, 600)) #set fonts head_font=QtGui.QFont("Helvetica [Cronyx]",weight=QtGui.QFont.Bold) io_font = QtGui.QFont("Helvetica") #make display layout display_box = QtWidgets.QGroupBox('Display') #buttons self.load_button = QtWidgets.QPushButton('Load') self.load_label = QtWidgets.QLabel("Nothing loaded.") self.load_label.setWordWrap(True) self.load_label.setFont(io_font) self.load_label.setToolTip('Load results file') #make combo box for components self.component_cb = QtWidgets.QComboBox() self.component_cb.setToolTip('Change stress component displayed') # self.component_cb.addItems(['\u03C311', '\u03C322', '\u03C333']) self.component_cb.setEnabled(False) self.mesh_display=QtWidgets.QPushButton("Edges off") self.mesh_display.setToolTip('Turn mesh/edges on and off') self.mesh_display.setCheckable(True) self.mesh_display.setChecked(False) self.mesh_display.setEnabled(False) self.extract_boundaries_button = QtWidgets.QPushButton('Extract boundary') self.extract_boundaries_button.setEnabled(False) self.extract_boundaries_button.setToolTip('Extract boundary of model') self.export_STL_button = QtWidgets.QRadioButton("Write STL") self.export_STL_button.setChecked(False) self.export_STL_button.setEnabled(False) #make contour layout contour_layout = QtWidgets.QGridLayout() contour_box = QtWidgets.QGroupBox('Contours') min_contour_label = QtWidgets.QLabel("Min:") self.min_contour = QtWidgets.QDoubleSpinBox() self.min_contour.setMinimum(-100000) self.min_contour.setMaximum(100000) max_contour_label = QtWidgets.QLabel("Max:") self.max_contour = QtWidgets.QDoubleSpinBox() self.max_contour.setMinimum(-100000) self.max_contour.setMaximum(100000) num_contour_label = QtWidgets.QLabel("Interval:") self.num_contour = QtWidgets.QSpinBox() self.num_contour.setToolTip('Number of entries shown on colorbar') self.num_contour.setMinimum(3) self.num_contour.setMaximum(20) self.num_contour.setValue(5) self.update_contours_button = QtWidgets.QPushButton('Update') self.update_contours_button.setToolTip('Update the contour limits and interval') self.update_contours_button.setEnabled(False) contour_layout.addWidget(min_contour_label,1,0,1,1) contour_layout.addWidget(self.min_contour,1,1,1,1) contour_layout.addWidget(max_contour_label,1,2,1,1) contour_layout.addWidget(self.max_contour,1,3,1,1) contour_layout.addWidget(num_contour_label,1,4,1,1) contour_layout.addWidget(self.num_contour,1,5,1,1) contour_layout.addWidget(self.update_contours_button,1,6,1,1) # line extraction from surface extract_layout = QtWidgets.QGridLayout() extract_box = QtWidgets.QGroupBox('Extract') # labels for axes x_label = QtWidgets.QLabel("x") y_label = QtWidgets.QLabel("y") z_label = QtWidgets.QLabel("z") # x, y, z of first point start_label = QtWidgets.QLabel("Start") start_label.setToolTip('Start coordinate of line trace') self.point1_x_coord = QtWidgets.QDoubleSpinBox() self.point1_x_coord.setMinimum(-100000) self.point1_x_coord.setMaximum(100000) self.point1_y_coord = QtWidgets.QDoubleSpinBox() self.point1_y_coord.setMinimum(-100000) self.point1_y_coord.setMaximum(100000) self.point1_z_coord = QtWidgets.QDoubleSpinBox() self.point1_z_coord.setMinimum(-100000) self.point1_z_coord.setMaximum(100000) # x, y, z of second point end_label = QtWidgets.QLabel("End") end_label.setToolTip('End coordinate of line trace') self.point2_x_coord = QtWidgets.QDoubleSpinBox() self.point2_x_coord.setMinimum(-100000) self.point2_x_coord.setMaximum(100000) self.point2_y_coord = QtWidgets.QDoubleSpinBox() self.point2_y_coord.setMinimum(-100000) self.point2_y_coord.setMaximum(100000) self.point2_z_coord = QtWidgets.QDoubleSpinBox() self.point2_z_coord.setMinimum(-100000) self.point2_z_coord.setMaximum(100000) # x, y, z of clip point clip_label = QtWidgets.QLabel("Clip") clip_label.setToolTip('Tertiary coordinate to specify clipping plane') self.clip_x_coord = QtWidgets.QDoubleSpinBox() self.clip_x_coord.setMinimum(-100000) self.clip_x_coord.setMaximum(100000) self.clip_y_coord = QtWidgets.QDoubleSpinBox() self.clip_y_coord.setMinimum(-100000) self.clip_y_coord.setMaximum(100000) self.clip_z_coord = QtWidgets.QDoubleSpinBox() self.clip_z_coord.setMinimum(-100000) self.clip_z_coord.setMaximum(100000) #clip settings self.clip_active_button=QtWidgets.QPushButton("Update clip") self.clip_active_button.setToolTip('Show/update clipped model') self.clip_active_button.setEnabled(False) interval_label=QtWidgets.QLabel("Line interval:") self.extract_interval=QtWidgets.QSpinBox() self.extract_interval.setToolTip('Number of points to extract along line trace') self.extract_interval.setValue(50) self.extract_interval.setMinimum(3) self.extract_interval.setMaximum(1000) self.extract_button = QtWidgets.QPushButton('Update line') self.extract_button.setToolTip('Show/update line trace') self.extract_button.setEnabled(False) self.export_line_button = QtWidgets.QPushButton('Export line') self.export_line_button.setEnabled(False) self.export_line_button.setToolTip('Export line trace to file') #create figure canvas etc #initialize plot self.figure = plt.figure(figsize=(4,4)) plt.text(0.5, 0.5, "'Update line' for plot", ha='center', style='italic', fontweight = 'bold', color='lightgray', size= 18) plt.axis('off') #changes the background of the plot, otherwise white # self.figure.patch.set_facecolor((242/255,242/255,242/255)) self.canvas = FigureCanvas(self.figure) self.canvas.setMinimumSize(QtCore.QSize(400, 500)) #add everything to the extract layout extract_layout.addWidget(x_label,1,1,1,1) extract_layout.addWidget(y_label,1,2,1,1) extract_layout.addWidget(z_label,1,3,1,1) extract_layout.addWidget(start_label,2,0,1,1) extract_layout.addWidget(self.point1_x_coord,2,1,1,1) extract_layout.addWidget(self.point1_y_coord,2,2,1,1) extract_layout.addWidget(self.point1_z_coord,2,3,1,1) extract_layout.addWidget(end_label,3,0,1,1) extract_layout.addWidget(self.point2_x_coord,3,1,1,1) extract_layout.addWidget(self.point2_y_coord,3,2,1,1) extract_layout.addWidget(self.point2_z_coord,3,3,1,1) extract_layout.addWidget(clip_label,4,0,1,1) extract_layout.addWidget(self.clip_x_coord,4,1,1,1) extract_layout.addWidget(self.clip_y_coord,4,2,1,1) extract_layout.addWidget(self.clip_z_coord,4,3,1,1) extract_layout.addWidget(self.extract_button,5,2,1,1) extract_layout.addWidget(self.clip_active_button,5,3,1,1) extract_layout.addWidget(self.canvas,6,0,1,4) load_model_box.addWidget(self.load_button,0,0,1,1) load_model_box.addWidget(self.component_cb,0,1,1,1) load_model_box.addWidget(self.mesh_display,0,2,1,1) load_model_box.addWidget(self.load_label,1,0,1,3) load_model_box.addWidget(self.extract_boundaries_button,2,1,1,1) load_model_box.addWidget(self.export_STL_button,2,2,1,1) #add layouts to boxes display_box.setLayout(load_model_box) contour_box.setLayout(contour_layout) evlayout=QtWidgets.QVBoxLayout() evbutton_layout = QtWidgets.QHBoxLayout() evbutton_layout.addWidget(interval_label) evbutton_layout.addWidget(self.extract_interval) verticalSpacer = QtWidgets.QSpacerItem(200, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) evbutton_layout.addItem(verticalSpacer) evbutton_layout.addWidget(self.export_line_button) evlayout.addLayout(extract_layout) evlayout.addLayout(evbutton_layout) extract_box.setLayout(evlayout) lvlayout=QtWidgets.QVBoxLayout() lvlayout.addWidget(display_box) lvlayout.addWidget(contour_box) lvlayout.addWidget(extract_box) lvlayout.addStretch(1) mainlayout.addWidget(self.vtkWidget) mainlayout.addStretch(1) mainlayout.addLayout(lvlayout) def initialize(self): self.vtkWidget.start()
class QPlot(QtWidgets.QWidget): # Signal that emits the index of the axes that (x,y) originate from as well as (x,y) themselves. newMarker = QtCore.pyqtSignal(int, float, float) # New isocenter. newIsocenter = QtCore.pyqtSignal(float, float, float) # Clear all the markers. clearMarkers = QtCore.pyqtSignal() def __init__(self): """ QPlot is designed to interface with syncmrt.file.image.Image2D objects. Parameters ---------- tableModel : QsWorkspace.QPlotTableModel object A table model must be provided for the storage of marker locations. """ super().__init__() # Create the figure/canvas. self.fig = plt.figure(constrained_layout=True) self.fig.patch.set_facecolor('#000000') # Create the canvas. self.canvas = FigureCanvasQTAgg(self.fig) # Create the figure manager. self.figureManager = FigureManagerQT(self.canvas, 1) # Create the toolbar manager. self.toolbarManager = self.figureManager.toolbar.toolmanager # Create the toolbar self.toolbar = self.figureManager.toolbar # Reference to ax.imshows(). self.images = {} # Set up marker tracking. self.markers = {} self.markersMaximum = 0 self.ctd = [None, None] # Set up histograms dict for axes. self.histograms = {} # Create 2 axes. self.ax = self.fig.subplots(1, 2, gridspec_kw={ 'hspace': 0, 'wspace': 0, 'left': 0, 'right': 1, 'bottom': 0, 'top': 1 }, sharey=False) for idx, ax in enumerate(self.ax): # Set up tracking for markers in the axes. self.markers[ax] = [] # Set up histogram connections. self.histograms[ax] = QHistogramWindow() self.histograms[ax].windowUpdated.connect( partial(self.applyWindow, ax)) # Set up the axes. ax.set_facecolor('#000000') ax.title.set_color('#FFFFFF') ax.xaxis.label.set_color('#FFFFFF') ax.yaxis.label.set_color('#FFFFFF') ax.xaxis.set_label_coords(0.5, 0.12) ax.yaxis.set_label_coords(0.12, 0.5) ax.xaxis.label.set_size(20) ax.yaxis.label.set_size(20) ax.yaxis.label.set_rotation(90) ax.spines['left'].set_visible(False) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['bottom'].set_visible(False) ax.tick_params('both', which='both', length=7, width=1, pad=-35, direction='in', colors='#FFFFFF') # Remove useless tools. items = list(self.toolbar._toolitems.keys()) for item in items: self.toolbar.remove_toolitem(item) # Populate the toolbar manager. self.toolbarManager.add_tool('home', 'ToolHome') self.toolbarManager.add_tool('zoom', 'ToolZoom') self.toolbarManager.add_tool('pan', 'ToolPan') self.toolbarManager.add_tool('pick', ToolPickPoint) self.toolbarManager.add_tool('pickIso', ToolPickIso) self.toolbarManager.add_tool('clear', ToolClearPoints) # Populate the toolbar. self.toolbar.add_tool('home', "default") self.toolbar.add_tool('zoom', "default") self.toolbar.add_tool('pan', "default") self.toolbar.add_tool('pick', "default") self.toolbar.add_tool('clear', "default") # Get the layout. layout = QtWidgets.QVBoxLayout() layout.addWidget(self.toolbar) layout.addWidget(self.canvas) self.setLayout(layout) # Get tools. pick = self.toolbarManager.get_tool('pick') clear = self.toolbarManager.get_tool('clear') pickIso = self.toolbarManager.get_tool('pickIso') # Connect tool signals. pick.newPoint.connect(self.addMarker) clear.clearPoints.connect(self.removeMarkers) pickIso.newIsocenter.connect(self._updateIsocenter) # Refresh the canvas. self.canvas.draw() # self._radiographMode = 'sum' # self._R = np.identity(3) # self._imagingAngle = 0 # self.mask = None self.maskSize = 20.0 self.overlay = {} self.machineIsocenter = [0, 0, 0] self.patientIsocenter = [0, 0, 0] def loadImages(self, images): """ Load up to 2 images into the plot environment. Parameters ---------- images : list A list containing up to two items of syncmrt.file.image.Image2D """ # Clear the axes. self.clear() # Remove all previous images. for key in self.images: # Remove the imshow. self.images[key].remove() # Remove the stored references. self.images.clear() # Remove all previous markers. for ax in self.ax: del self.markers[ax][:] for i, image in enumerate(images): # Load the image. Assumes 2D array, forces 32-bit floats. self.images[self.ax[i]] = self.ax[i].imshow(np.array( image.pixelArray, dtype=np.float32), cmap='bone', extent=image.extent) # Setup the axes. self.ax[i].set_xlim(image.extent[0:2]) self.ax[i].set_ylim(image.extent[2:4]) self.ax[i].set_aspect("equal", "datalim") # Setup the histogram data. self.histograms[self.ax[i]].setData(image.pixelArray) self.histograms[self.ax[i]].setTitle('View: ' + image.view['title']) if i == 0: # Only one image. self.ax[0].set_position([0, 0, 1, 1]) self.ax[1].set_position([0.9999, 0.9999, 0.0001, 0.0001]) self.ax[1].set_visible(False) else: # Show two images. self.ax[0].set_position([0, 0, 0.5, 1]) self.ax[1].set_position([0.5, 0, 0.5, 1]) self.ax[1].set_visible(True) self.canvas.draw() def pickIsocenter(self): """ Trigger the pick isocenter tool. """ self.toolbarManager.trigger_tool('pickIso') def _updateIsocenter(self, ax, x, y): """ Update the patient isocenter with mouse click in plot. """ # Get the axis index that it originated from. index = np.argwhere(self.ax == ax)[0][0] if index == 0: self.patientIsocenter[0:2] = [x, y] elif index == 1: self.patientIsocenter[1:3] = [y, x] # Update the overlays. if 'patIso' in self.overlay: self.toggleOverlay(2, False) self.toggleOverlay(2, True) if 'beamArea' in self.overlay: self.toggleOverlay(3, False) self.toggleOverlay(3, True) # Emit the signal to say we have a new iso. x, y, z = list(map(float, self.patientIsocenter)) self.newIsocenter.emit(x, y, z) def updatePatientIsocenter(self, x, y, z): """ Update the patient isocenter and refresh the overlay. """ self.patientIsocenter = [x, y, z] if 'patIso' in self.overlay: self.toggleOverlay(2, False) self.toggleOverlay(2, True) if 'beamArea' in self.overlay: self.toggleOverlay(3, False) self.toggleOverlay(3, True) def getHistograms(self): """ Return a list of histograms. """ return list(self.histograms.values()) def applyWindow(self, axes, imin, imax): # Set the color scale to match the window. if imin < imax: self.images[axes].set_clim(vmin=imin, vmax=imax) self.canvas.draw() else: return def addMarker(self, ax, x, y): """ Append marker position if it is within the maximum marker limit.""" n = len(self.markers[ax]) if n < self.markersMaximum: # Plot marker list. scatter = ax.scatter(x, y, c='r', marker='+', s=50) text = ax.text(x + 1, y, n + 1, color='r') self.markers[ax].append([scatter, text]) # Refresh views. self.canvas.draw() # Emit signal for new marker. index = np.argwhere(self.ax == ax)[0][0] self.newMarker.emit(index, x, y) def setCentroid(self, axes, ctd): """ Set the centroid of a given axes. """ self.ctd[axes] = ctd # If it's currently an overlay, then toggle it off and on. if 'ctd' in self.overlay: # Refresh it's position on the screen. self.toggleOverlay(0, False) self.toggleOverlay(0, True) def markerUpdate(self, axesIndex, markerLocations): """ Update all the markers. """ # Get the desired axes. ax = self.ax[axesIndex] # Create a new centroid. centroid = np.array([0, 0]).astype(float) # Clear the markers and add the new ones. for pos, marker in enumerate(self.markers[ax]): marker[0].remove() marker[1].remove() x, y = markerLocations[pos] marker[0] = ax.scatter(x, y, c='r', marker='+', s=50) marker[1] = ax.text(x + 1, y, pos + 1, color='r') centroid += np.array([x, y]).astype(float) # Calculate new centroid. centroid = centroid / len(centroid) # Set the centroid. self.setCentroid(axesIndex, centroid) # Refresh the canvas. self.canvas.draw() def removeMarkers(self): """ Clear all markers in all axes. Parameters ---------- plot : int Can take values of -1 (both plots) or plot 1 or 2. """ # Remove stuff from plots. for ax in self.ax: for pos, marker in enumerate(self.markers[ax]): marker[0].remove() marker[1].remove() # Reset the list to empty. self.markers[ax] = [] # Reset centroid. self.ctd = [None, None] # If it's currently an overlay, then toggle it off and on. if 'ctd' in self.overlay: # Refresh it's position on the screen. self.toggleOverlay(0, False) self.toggleOverlay(0, True) # Refresh the canvas. self.canvas.draw() # Emit the signal to tell everything else we're done. self.clearMarkers.emit() def clear(self): """ Clears all images in the plot. """ for ax in self.ax: # Clear the plot. ax.cla() # Clear the histogram. self.histograms[ax].clear() # Remove all references to ax.imshows. self.images.clear() # Refresh the canvas. self.canvas.draw() def updatePatientIsocenter(self, x, y, z): """ Update the patient isocenter in 3D. """ self.patientIsocenter = [x, y, z] if 'patIso' in self.overlay: self.toggleOverlay(2, False) self.toggleOverlay(2, True) if 'beamArea' in self.overlay: self.toggleOverlay(3, False) self.toggleOverlay(3, True) def getIsocenter(self): """ Return the patient isocenter. """ return self.patientIsocenter def toggleOverlay(self, overlayType, state=False): ''' Single overlay function with various types. 0: Centroid overlay 1: Machine Isocenter overlay 2: Patient Isocenter overlay 3: Beam area overlay ''' if overlayType == 0: # Centroid overlay. # Remove overlay lines if they exist. if 'ctd' in self.overlay: if self.overlay['ctd'] is not None: for obj in self.overlay['ctd']: obj.remove() del (self.overlay['ctd']) if state is True: self.overlay['ctd'] = [] # Plot overlay scatter points. if type(self.ctd[0]) != type(None): x, y = self.ctd[0] self.overlay['ctd'].append(self.ax[0].scatter(x, y, c='b', marker='+', s=50)) self.overlay['ctd'].append(self.ax[0].text(x + 1, y - 3, 'ctd', color='b')) if type(self.ctd[1]) != type(None): x, y = self.ctd[1] self.overlay['ctd'].append(self.ax[1].scatter(x, y, c='b', marker='+', s=50)) self.overlay['ctd'].append(self.ax[1].text(x + 1, y - 3, 'ctd', color='b')) else: pass elif overlayType == 1: # Machine isocenter overlay. # Remove overlay lines. if 'machIsoH' in self.overlay: for obj in self.overlay['machIsoH']: obj.remove() del (self.overlay['machIsoH']) if 'machIsoV' in self.overlay: for obj in self.overlay['machIsoV']: obj.remove() del (self.overlay['machIsoV']) if state is True: self.overlay['machIsoV'] = [] self.overlay['machIsoH'] = [] # Plot overlay lines. self.overlay['machIsoV'].append(self.ax[0].axvline( self.machineIsocenter[0], c='r', alpha=0.5)) self.overlay['machIsoV'].append(self.ax[1].axvline( self.machineIsocenter[2], c='r', alpha=0.5)) self.overlay['machIsoH'].append(self.ax[0].axhline( self.machineIsocenter[1], c='r', alpha=0.5)) self.overlay['machIsoH'].append(self.ax[1].axhline( self.machineIsocenter[1], c='r', alpha=0.5)) else: pass elif overlayType == 2: # Overlay of the patient iso. # Remove the overlay lines. if 'patIso' in self.overlay: for obj in reversed(self.overlay['patIso']): obj.remove() del (self.overlay['patIso']) if state is True: self.overlay['patIso'] = [] # Plot patient iso. self.overlay['patIso'].append(self.ax[0].scatter( self.patientIsocenter[0], self.patientIsocenter[1], marker='+', color='y', s=50)) self.overlay['patIso'].append(self.ax[0].text( self.patientIsocenter[0] + 1, self.patientIsocenter[1] + 1, 'ptv', color='y')) self.overlay['patIso'].append(self.ax[1].scatter( self.patientIsocenter[2], self.patientIsocenter[1], marker='+', color='y', s=50)) self.overlay['patIso'].append(self.ax[1].text( self.patientIsocenter[2] + 1, self.patientIsocenter[1] + 1, 'ptv', color='y')) else: pass elif overlayType == 3: # Overlay of the beam field. # Remove it first if it already exists. if 'beamArea' in self.overlay: for obj in reversed(self.overlay['beamArea']): obj.remove() del (self.overlay['beamArea']) if state is True: self.overlay['beamArea'] = [] # Create new patches. _beam = Rectangle((-self.maskSize / 2, -self.maskSize / 2), self.maskSize, self.maskSize, fc='r', ec='none', alpha=0.2) _ptv1 = Rectangle( (self.patientIsocenter[0] - self.maskSize / 2, self.patientIsocenter[1] - self.maskSize / 2), self.maskSize, self.maskSize, fc='none', ec='y', ls='--', alpha=1.0) _ptv2 = Rectangle( (self.patientIsocenter[2] - self.maskSize / 2, self.patientIsocenter[1] - self.maskSize / 2), self.maskSize, self.maskSize, fc='none', ec='y', ls='--', alpha=1.0) # Different patch collection for each plot. pc1 = PatchCollection([_beam, _ptv1], match_original=True) pc2 = PatchCollection([_beam, _ptv2], match_original=True) # Add the collections to the axes. self.overlay['beamArea'].append(self.ax[0].add_collection(pc1)) self.overlay['beamArea'].append(self.ax[1].add_collection(pc2)) else: pass pass # Update the canvas. self.canvas.draw() def setMaskSize(self, size): """ Set the mask size and toggle the overlay if it is enabled. """ self.maskSize = size self.toggleOverlay(3, 'beamArea' in self.overlay) self.toggleOverlay(3, 'beamArea' in self.overlay) def eventFilter(self, event): # If mouse button 1 is clicked (left click). if (event.button == 1): # event.inaxes is the axes the click originated from # event.xdata is the data point w.r.t. the active axes. self.markerAdd(event.inaxes, event.xdata, event.ydata)
class ClusterPointsView(QMainWindow): """ В этом окне можно видеть таблицу со списком точек, входящих в кластер. Точки можно удалять и добавлять. """ def __init__(self, parent, cluster): super().__init__(parent) self.cluster = cluster self.columnCount = self.parent().globalData.columnCount() self.centralWidget = QWidget() self.layout = QHBoxLayout(self.centralWidget) self.setCentralWidget(self.centralWidget) self.tabletabs = QTabWidget() self.tabletabs.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) self.clusterPointsTable = QTableWidget() self.clusterPointsTable.resizeColumnsToContents() self.tabletabs.addTab(self.clusterPointsTable, "Удаление точек") self.unbusyPointsTable = QTableWidget() self.tabletabs.addTab(self.unbusyPointsTable, "Добавление точек") self.layout.addWidget(self.tabletabs) self.figure = Figure() self.barWidget = FigureCanvas(self.figure) self.barWidget.mpl_connect('button_press_event', self.onclickonbar) self.axes = self.figure.add_subplot(111) self.refreshBarChart() self.figure_manh = Figure() self.barWidget_manh = FigureCanvas(self.figure_manh) self.barWidget.mpl_connect('button_press_event', self.onclickonbarmanh) self.axes_manh = self.figure_manh.add_subplot(111) self.refreshManhBarChart() self.bartabs = QTabWidget() self.bartabs.addTab(self.barWidget, "Евклидово расстояние") self.bartabs.addTab(self.barWidget_manh, "Манхэттэнское расстояние") self.bartabs.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) self.layout.addWidget(self.bartabs) self.refreshUnbusyPointsTable() self.refreshClusterPointsTable() self.resize(1000, 500) self.setWindowTitle("Точки кластера: " + cluster.getName()) self.show() def refreshBarChart(self): self.axes.clear() xcoords = np.arange(self.cluster.getSize()) distances = [] indexes = Data.getIndexList(self.cluster) massCenter = self.cluster.evaluateMassCenter() significancefactors = self.parent().globalData.getSignificanceFactors() for row in self.cluster: distances.append(row.distanceTo(massCenter, significancefactors)) sorteddata = self.sortBarData(indexes, distances) self.axes.bar(xcoords, sorteddata[1], align="center", tick_label=sorteddata[0]) if self.cluster.getSize() > 10: for item in self.axes.get_xticklabels(): item.set_fontsize(10 - self.cluster.getSize() // 8) self.axes.set_title("Расстояния до центра \n масс кластера") self.barWidget.draw() def refreshManhBarChart(self): self.axes_manh.clear() xcoords = np.arange(self.cluster.getSize()) distances = [] indexes = Data.getIndexList(self.cluster) massCenter = self.cluster.evaluateMassCenter() significancefactors = self.parent().globalData.getSignificanceFactors() for row in self.cluster: distances.append( row.manhattanDistanceTo(massCenter, significancefactors)) sorteddata = self.sortBarData(indexes, distances) self.axes_manh.bar(xcoords, sorteddata[1], align="center", tick_label=sorteddata[0]) if self.cluster.getSize() > 10: for item in self.axes_manh.get_xticklabels(): item.set_fontsize(10 - self.cluster.getSize() // 8) self.axes_manh.set_title( "Манхэттенские расстояния до центра \n масс кластера") self.barWidget_manh.draw() def refreshClusterPointsTable(self): self.clusterPointsTable.setRowCount(0) Utils.fillTableWithCluster(self.clusterPointsTable, self.cluster) self.clusterPointsTable.setColumnCount(self.columnCount + 1) self.clusterPointsTable.setHorizontalHeaderItem( self.columnCount, QTableWidgetItem(" ")) for i, row in enumerate(self.cluster): removePointButton = QPushButton("Исключить") self.clusterPointsTable.setCellWidget(i, self.columnCount, removePointButton) index = QPersistentModelIndex( self.clusterPointsTable.model().index(i, 0)) removePointButton.clicked.connect( lambda *args, index=index: self.removePointFromCluster(index. row())) def refreshUnbusyPointsTable(self): self.unbusyPointsTable.setColumnCount(self.columnCount + 1) self.unbusyPointsTable.setRowCount(0) busyIndexes = self.cluster.getIndexSet() indexes = [] for rowNum, row in enumerate(self.parent().globalData): if row.getIndex() not in busyIndexes: self.unbusyPointsTable.setRowCount( self.unbusyPointsTable.rowCount() + 1) indexes.append(row.getIndex()) for columnIndex in range(0, self.columnCount): self.unbusyPointsTable.setItem( self.unbusyPointsTable.rowCount() - 1, columnIndex, QTableWidgetItem(str(row[columnIndex]))) addPointButton = QPushButton("Добавить") a = self.unbusyPointsTable.rowCount() b = self.columnCount self.unbusyPointsTable.setCellWidget( self.unbusyPointsTable.rowCount() - 1, self.columnCount, addPointButton) addPointButton.clicked.connect( lambda *args, row=row: self.addPointToCluster(row)) self.unbusyPointsTable.setVerticalHeaderLabels(list(map(str, indexes))) def removePointFromCluster(self, index): del self.cluster[index] self.refreshBarChart() self.refreshManhBarChart() self.refreshClusterPointsTable() self.refreshUnbusyPointsTable() def addPointToCluster(self, row): self.cluster.addRow(row) self.refreshBarChart() self.refreshManhBarChart() self.refreshClusterPointsTable() self.refreshUnbusyPointsTable() def sortBarData(self, indexes, distances): mappeddata = dict(zip(indexes, distances)) sorteddata = sorted(mappeddata.items(), key=operator.itemgetter(1)) sorteddistances = [] sortedindexes = [] for element in sorteddata: sortedindexes.append(element[0]) sorteddistances.append(element[1]) return sortedindexes, sorteddistances def onclickonbar(self, event): mousex, mousey = event.xdata, event.ydata if (mousex != None) and (mousey != None): massCenter = self.cluster.evaluateMassCenter() significancefactors = self.parent( ).globalData.getSignificanceFactors() for element in self.cluster: if element.distanceTo(massCenter, significancefactors) > mousey: self.cluster.remove(element) self.refreshBarChart() def onclickonbarmanh(self, event): pass def closeEvent(self, event): self.parent().refreshCanvas() self.parent().refreshClusterTable() event.accept()
class AppForm(QMainWindow): def __init__(self, parent=None): QMainWindow.__init__(self, parent) self.setWindowTitle('Demo: PyQt with matplotlib') self.create_menu() self.create_main_frame() self.create_status_bar() self.textbox.setText('1 2 3 4') self.on_draw() def save_plot(self): file_choices = "PNG (*.png)|*.png" path = QFileDialog.getSaveFileName(self, 'Save file', '', file_choices) if path: self.canvas.print_figure(path, dpi=self.dpi) self.statusBar().showMessage('Saved to %s' % path, 2000) def on_about(self): msg = """ A demo of using PyQt with matplotlib: * Use the matplotlib navigation bar * Add values to the text box and press Enter (or click "Draw") * Show or hide the grid * Drag the slider to modify the width of the bars * Save the plot to a file using the File menu * Click on a bar to receive an informative message """ QMessageBox.about(self, "About the demo", msg.strip()) def on_pick(self, event): # The event received here is of the type # matplotlib.backend_bases.PickEvent # # It carries lots of information, of which we're using # only a small amount here. # box_points = event.artist.get_bbox().get_points() msg = "You've clicked on a bar with coords:\n %s" % box_points QMessageBox.information(self, "Click!", msg) def on_draw(self): """ Redraws the figure """ # str = unicode(self.textbox.text()) self.data = list(map(int, self.textbox.text().split())) x = range(len(self.data)) # clear the axes and redraw the plot anew # self.axes.clear() self.axes.grid(self.grid_cb.isChecked()) self.axes.bar([0, 1, 2, 3], self.data, self.slider.value() / 100.0, align="center",alpha=0.44,picker=5) self.canvas.draw() def create_main_frame(self): self.main_frame = QWidget() # Create the mpl Figure and FigCanvas objects. # 5x4 inches, 100 dots-per-inch # self.dpi = 100 self.fig = Figure((5.0, 4.0), dpi=self.dpi) self.canvas = FigureCanvas(self.fig) self.canvas.setParent(self.main_frame) # Since we have only one plot, we can use add_axes # instead of add_subplot, but then the subplot # configuration tool in the navigation toolbar wouldn't # work. # self.axes = self.fig.add_subplot(111) # Bind the 'pick' event for clicking on one of the bars # self.canvas.mpl_connect('pick_event', self.on_pick) # Create the navigation toolbar, tied to the canvas # self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame) # Other GUI controls # self.textbox = QLineEdit() self.textbox.setMinimumWidth(200) self.textbox.editingFinished.connect(self.on_draw) self.draw_button = QPushButton("&Draw") self.draw_button.clicked.connect(self.on_draw) self.grid_cb = QCheckBox("Show &Grid") self.grid_cb.setChecked(False) self.grid_cb.stateChanged.connect(self.on_draw) # int slider_label = QLabel('Bar width (%):') self.slider = QSlider(Qt.Horizontal) self.slider.setRange(1, 100) self.slider.setValue(20) self.slider.setTracking(True) self.slider.setTickPosition(QSlider.TicksBothSides) self.slider.valueChanged.connect(self.on_draw) # int # # Layout with box sizers # hbox = QHBoxLayout() for w in [self.textbox, self.draw_button, self.grid_cb, slider_label, self.slider]: hbox.addWidget(w) hbox.setAlignment(w, Qt.AlignVCenter) vbox = QVBoxLayout() vbox.addWidget(self.mpl_toolbar) vbox.addWidget(self.canvas) vbox.addLayout(hbox) self.main_frame.setLayout(vbox) self.setCentralWidget(self.main_frame) def create_status_bar(self): self.status_text = QLabel("This is a demo") self.statusBar().addWidget(self.status_text, 1) def create_menu(self): self.file_menu = self.menuBar().addMenu("&File") load_file_action = self.create_action("&Save plot", shortcut="Ctrl+S", slot=self.save_plot, tip="Save the plot") quit_action = self.create_action("&Quit", slot=self.close, shortcut="Ctrl+Q", tip="Close the application") self.add_actions(self.file_menu, (load_file_action, None, quit_action)) self.help_menu = self.menuBar().addMenu("&Help") about_action = self.create_action("&About", shortcut='F1', slot=self.on_about, tip='About the demo') self.add_actions(self.help_menu, (about_action,)) def add_actions(self, target, actions): for action in actions: if action is None: target.addSeparator() else: target.addAction(action) def create_action(self, text, slot=None, shortcut=None, icon=None, tip=None, checkable=False, signal="triggered()"): action = QAction(text, self) if icon is not None: action.setIcon(QIcon(":/%s.png" % icon)) if shortcut is not None: action.setShortcut(shortcut) if tip is not None: action.setToolTip(tip) action.setStatusTip(tip) if slot is not None: action.triggered.connect(slot) if checkable: action.setCheckable(True) return action
class AppForm(QMainWindow): def __init__(self, parent=None): QMainWindow.__init__(self, parent) self.setWindowTitle('Serial Port Real Time Plotter') self.ser = None self.create_main_frame() self.create_status_bar() self.serialport_connected = False self.textbox.setText('0.0') self.xdata = list(range(-N, 0, 1)) self.ydata_ch1 = [0 for i in range(N)] self.ydata_ch2 = [0 for i in range(N)] self.ydata_ch3 = [0 for i in range(N)] self.ydata_ch4 = [0 for i in range(N)] self.ydata_ch5 = [0 for i in range(N)] self.ydata_ch6 = [0 for i in range(N)] self.ydata_ch1_cont = [] self.ydata_ch2_cont = [] self.ydata_ch3_cont = [] self.ydata_ch4_cont = [] self.ydata_ch5_cont = [] self.ydata_ch6_cont = [] os.chdir("./outputs") self.setFileName() self.ydata_raw = [] self.axes.clear() self.axes.grid(True) self.axes.set_xlim([-N, 0]) self.axes.set_ylim([0, 1.25]) self.plot_refs = self.axes.plot(self.xdata, self.ydata_ch1, 'r', self.xdata, self.ydata_ch2, 'g', self.xdata, self.ydata_ch3, 'b', self.xdata, self.ydata_ch4, 'y', self.xdata, self.ydata_ch5, 'k', self.xdata, self.ydata_ch6, 'r') #self.axes.legend(['Channel 1','Channel 2','Channel 3','Channel 4'],loc='upper center', bbox_to_anchor=(0.5, -0.05), ncol=4) self.canvas.draw() self.background = self.fig.canvas.copy_from_bbox(self.axes.bbox) self.timer = QTimer() self.timer.setInterval(10) self.timer.timeout.connect(self.update_plot) self.timer_send = QTimer() self.timer_send.setInterval(100) self.timer_send.timeout.connect(self.send_data) def setFileName(self): self.files = [] for file in glob.glob("*.mat"): self.files.append(file) i = 0 while True: self.filename = "out_" + time.strftime( "%Y-%m-%d_%H-%M-%S") + "_" + str(i) + ".mat" if self.filename not in self.files: break i += 1 def closeEvent(self, event): reply = QMessageBox.question( self, 'Window Close', 'Are you sure you want to close the window?', QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: if self.ser is not None: self.ser.close() event.accept() else: event.ignore() def create_main_frame(self): self.main_frame = QWidget() self.dpi = 100 self.fig = Figure((10.0, 6.0), dpi=self.dpi, tight_layout=True) self.canvas = FigureCanvas(self.fig) self.canvas.setParent(self.main_frame) self.axes = self.fig.add_subplot(111) #self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame) self.textbox = QLineEdit() self.textbox.setMinimumWidth(100) self.set_button = QPushButton("&Set") self.set_button.clicked.connect(self.set_setpoint) self.show_ch1 = QCheckBox("Show &Channel1") self.show_ch1.setChecked(True) self.show_ch2 = QCheckBox("Show &Channel2") self.show_ch2.setChecked(True) self.show_ch3 = QCheckBox("Show &Channel3") self.show_ch3.setChecked(True) self.show_ch4 = QCheckBox("Show &Channel4") self.show_ch4.setChecked(True) self.show_ch5 = QCheckBox("Show &Channel4") self.show_ch5.setChecked(True) self.show_ch6 = QCheckBox("Show &Channel4") self.show_ch6.setChecked(True) slider_label = QLabel('Setpoint:') self.slider = QSlider(Qt.Horizontal) self.slider.setRange(0, 65535) self.slider.setValue(0) self.slider.setTracking(True) self.slider.setTickPosition(QSlider.TicksBothSides) hbox = QHBoxLayout() for w in [self.textbox, self.set_button, slider_label, self.slider]: hbox.addWidget(w) hbox.setAlignment(w, Qt.AlignVCenter) hbox2 = QHBoxLayout() for w in [self.show_ch1, self.show_ch2, self.show_ch3, self.show_ch4]: hbox2.addWidget(w) hbox2.setAlignment(w, Qt.AlignVCenter) vbox = QVBoxLayout() vbox.addWidget(self.canvas) #vbox.addWidget(self.mpl_toolbar) vbox.addLayout(hbox2) vbox.addLayout(hbox) hbox3 = QHBoxLayout() self.save_mat_button = QPushButton("&Save .mat") self.save_mat_button.clicked.connect(self.save_mat) self.start_button = QPushButton("&Start") self.start_button.clicked.connect(self.connect) hbox3.addWidget(self.start_button) hbox3.addWidget(self.save_mat_button) hbox3.setAlignment(w, Qt.AlignVCenter) vbox.addLayout(hbox3) hbox4 = QHBoxLayout() self.combo_box_ports = QComboBox() self.button_update_ports = QPushButton("&Update Ports") self.button_update_ports.clicked.connect(self.update_ports) hbox4.addWidget(self.combo_box_ports) hbox4.addWidget(self.button_update_ports) vbox.addLayout(hbox4) self.main_frame.setLayout(vbox) self.setCentralWidget(self.main_frame) self.info_message('Press Start to start plotting') def update_ports(self): self.info_message('Updating Ports...') ports = serial.tools.list_ports.comports() self.combo_box_ports.clear() for port, desc, hwid in sorted(ports): self.combo_box_ports.addItem(str(port) + ": " + str(desc)) self.success_message('Updated Ports') def set_setpoint(self): try: self.slider.setValue(int(float(self.textbox.text()) * 65565)) except: self.error_message('Parsing error for set value') def create_status_bar(self): self.status_text = QLabel("") self.statusBar().addWidget(self.status_text, 1) def add_actions(self, target, actions): for action in actions: if action is None: target.addSeparator() else: target.addAction(action) def create_action(self, text, slot=None, shortcut=None, icon=None, tip=None, checkable=False): action = QAction(text, self) if icon is not None: action.setIcon(QIcon(":/%s.png" % icon)) if shortcut is not None: action.setShortcut(shortcut) if tip is not None: action.setToolTip(tip) action.setStatusTip(tip) if slot is not None: action.triggered.connect(slot) if checkable: action.setCheckable(True) return action def connect(self): if 'COM' in str(self.combo_box_ports.currentText()): com_port = str(self.combo_box_ports.currentText()).split(':')[0] else: self.error_message('Select COM Port') return if self.serialport_connected is False: try: self.ser = serial.Serial(com_port, 115200, timeout=0.2) if self.ser.isOpen() == False: self.ser.open() self.success_message('Connected to serial port') self.start_button.setText('&Stop') self.serialport_connected = True self.ydata_ch1 = [-1 for i in range(N)] self.ydata_ch2 = [-1 for i in range(N)] self.ydata_ch3 = [-1 for i in range(N)] self.ydata_ch4 = [-1 for i in range(N)] self.ydata_ch5 = [-1 for i in range(N)] self.ydata_ch6 = [-1 for i in range(N)] self.timer.start() self.timer_send.start() except: self.error_message('Connecting to serial port') self.setFileName() else: try: if self.ser.isOpen(): self.ser.close() self.info_message('Disconnected from serial port') self.start_button.setText('&Start') self.timer.stop() self.timer_send.stop() self.serialport_connected = False except: self.error_message('Disconnecting from serial port') def save_mat(self): try: mat_ch1 = np.array(self.ydata_ch1_cont) mat_ch2 = np.array(self.ydata_ch2_cont) mat_ch3 = np.array(self.ydata_ch3_cont) mat_ch4 = np.array(self.ydata_ch4_cont) mat_ch5 = np.array(self.ydata_ch5_cont) mat_ch6 = np.array(self.ydata_ch6_cont) mat_ch3_raw = np.array(self.ydata_raw) print(os.getcwd() + '\\' + self.filename) scipy.io.savemat( os.getcwd() + '\\' + self.filename, { 'channel1': mat_ch1, 'channel2': mat_ch2, 'channel3': mat_ch3, 'channel4': mat_ch4, 'channel5': mat_ch5, 'channel6': mat_ch6 }) self.success_message('Saved data to out.mat') except Exception as e: self.error_message('Saving Data ' + str(e)) def error_message(self, message): self.statusBar().showMessage('ERROR: ' + str(message)) self.statusBar().setStyleSheet( 'QStatusBar { background-color : red; }') def info_message(self, message): self.statusBar().showMessage('INFO: ' + str(message)) self.statusBar().setStyleSheet( 'QStatusBar { background-color : yellow; }') def success_message(self, message): self.statusBar().showMessage('SUCCESS: ' + str(message)) self.statusBar().setStyleSheet( 'QStatusBar { background-color : green; }') def update_plot(self): #ser.flushInput() #print('new plot') if self.ser.isOpen() == False: return rawData = self.ser.read(15) if len(rawData) != 15: return # print(time.time()) start = rawData[0] channel1 = int.from_bytes([rawData[1], rawData[2]], byteorder='little', signed=False) * 1.25 / 65536 channel2 = int.from_bytes([rawData[3], rawData[4]], byteorder='little', signed=False) * 1.25 / 65536 channel3 = int.from_bytes([rawData[5], rawData[6]], byteorder='little', signed=False) * 1.25 / 65536 channel4 = int.from_bytes([rawData[7], rawData[8]], byteorder='little', signed=False) * 150 / 65536 channel5 = int.from_bytes([rawData[9], rawData[10]], byteorder='little', signed=False) * 150 / 65536 channel6 = int.from_bytes([rawData[11], rawData[12]], byteorder='little', signed=False) * 150 / 65536 channel3_raw = int.from_bytes([rawData[5], rawData[6]], byteorder='little', signed=False) self.ydata_raw.append(channel3_raw) end = rawData[13] if start != 2 and end != 3: print('ERROR: Wrong frame') return print( int.from_bytes( [rawData[1], rawData[2]], byteorder='little', signed=False) * 1.25 / 65536) print( int.from_bytes( [rawData[3], rawData[4]], byteorder='little', signed=False) * 1.25 / 65536) print( int.from_bytes( [rawData[5], rawData[6]], byteorder='little', signed=False) * 1.25 / 65536) print( int.from_bytes( [rawData[7], rawData[8]], byteorder='little', signed=False) * 150 / 65536) print( int.from_bytes( [rawData[9], rawData[10]], byteorder='little', signed=False) * 150 / 65536) print( int.from_bytes( [rawData[11], rawData[12]], byteorder='little', signed=False) * 150 / 65536) # print(time.time()) print('----') # Drop off the first y element, append a new one. self.ydata_ch1 = self.ydata_ch1[1:] + [channel1] self.ydata_ch2 = self.ydata_ch2[1:] + [channel2] self.ydata_ch3 = self.ydata_ch3[1:] + [channel3] self.ydata_ch4 = self.ydata_ch4[1:] + [channel4] self.ydata_ch5 = self.ydata_ch5[1:] + [channel5] self.ydata_ch6 = self.ydata_ch6[1:] + [channel6] self.ydata_ch1_cont = self.ydata_ch1_cont + [channel1] self.ydata_ch2_cont = self.ydata_ch2_cont + [channel2] self.ydata_ch3_cont = self.ydata_ch3_cont + [channel3] self.ydata_ch4_cont = self.ydata_ch4_cont + [channel4] self.ydata_ch5_cont = self.ydata_ch5_cont + [channel5] self.ydata_ch6_cont = self.ydata_ch6_cont + [channel6] #print(time.time()) if (self.show_ch1.isChecked()): self.plot_refs[0].set_visible(True) self.plot_refs[0].set_ydata(self.ydata_ch1) else: self.plot_refs[0].set_visible(False) if (self.show_ch2.isChecked()): self.plot_refs[1].set_visible(True) self.plot_refs[1].set_ydata(self.ydata_ch2) else: self.plot_refs[1].set_visible(False) if (self.show_ch3.isChecked()): self.plot_refs[2].set_visible(True) self.plot_refs[2].set_ydata(self.ydata_ch3) else: self.plot_refs[2].set_visible(False) if (self.show_ch4.isChecked()): self.plot_refs[3].set_visible(True) self.plot_refs[3].set_ydata(self.ydata_ch4) else: self.plot_refs[3].set_visible(False) if (self.show_ch5.isChecked()): self.plot_refs[4].set_visible(True) self.plot_refs[4].set_ydata(self.ydata_ch5) else: self.plot_refs[4].set_visible(False) if (self.show_ch6.isChecked()): self.plot_refs[5].set_visible(True) self.plot_refs[5].set_ydata(self.ydata_ch6) else: self.plot_refs[5].set_visible(False) self.fig.canvas.restore_region(self.background) self.fig.draw_artist(self.plot_refs[0]) self.fig.draw_artist(self.plot_refs[1]) self.fig.draw_artist(self.plot_refs[2]) self.fig.draw_artist(self.plot_refs[3]) self.fig.draw_artist(self.plot_refs[4]) self.fig.draw_artist(self.plot_refs[5]) self.fig.canvas.update() #self.fig.canvas.blit() self.fig.canvas.flush_events() #print(time.time()) #print('-------') #self.ser.reset_input_buffer() def send_data(self): if self.ser.isOpen() == False: return data = bytearray(ctypes.c_uint16(self.slider.value())) send_array = bytearray(ctypes.c_uint8(2)) + data + bytearray( ctypes.c_uint8(3)) cs = ctypes.c_uint8(0) for byte in data: cs = ctypes.c_uint8(cs.value + byte) send_array = send_array + cs self.ser.write(send_array)
class Window(QDialog): """ Main GUI class for the matplotlib visualization and parameter controls. """ def __init__(self, parent=None): """ Initialize the main window. :param parent: Parent window. """ super(Window, self).__init__(parent) # Figure instance to plot on self.figure = plt.figure() # create an axis self.ax = self.figure.add_subplot(111) # The Canvas Widget that displays the `figure` self.canvas = FigureCanvas(self.figure) # The Navigation widget self.toolbar = NavigationToolbar(self.canvas, self) # Refresh plot button self.button = QPushButton("Refresh plot") self.button.clicked.connect(self.plot) # NPP control self.npp_label = QLabel("Number of plot points [int]:") self.npp_box = QLineEdit(self) self.npp_box.setText("300") # Temperature control self.temp_label = QLabel("Temperature [K]: ") self.temp_box = QLineEdit(self) self.temp_box.setText("288.0") # Wavelength range control self.wl_lower_label = QLabel("Wavelength [m] from ") self.wl_box_lower = QLineEdit(self) self.wl_box_lower.setText("5.0e-6") self.wl_upper_label = QLabel(" to ") self.wl_box_upper = QLineEdit(self) self.wl_box_upper.setText("20.0e-6") # Setting up the layout of the Window self.hbox0 = QHBoxLayout() self.hbox0.addWidget(self.button) self.hbox0.addWidget(self.npp_label) self.hbox0.addWidget(self.npp_box) self.hbox0.addStretch(1) self.hbox1 = QHBoxLayout() self.hbox1.addWidget(self.temp_label) self.hbox1.addWidget(self.temp_box) self.hbox1.addStretch(1) self.hbox2 = QHBoxLayout() self.hbox2.addWidget(self.wl_lower_label) self.hbox2.addWidget(self.wl_box_lower) self.hbox2.addWidget(self.wl_upper_label) self.hbox2.addWidget(self.wl_box_upper) self.vbox = QVBoxLayout() self.vbox.addLayout(self.hbox0) self.vbox.addLayout(self.hbox1) self.vbox.addLayout(self.hbox2) # Finalize the layout self.layout = QVBoxLayout() self.layout.addWidget(self.toolbar) self.layout.addWidget(self.canvas) self.layout.addLayout(self.vbox) self.setLayout(self.layout) def check_input(self): """ Small helper function to check if the input in the textfields is valid at a given point. :return: True if valid inputs are given. Error messages and False if the inputs are invalid. """ npp_value = int(self.npp_box.text()) if npp_value < 100: msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText("Invalid number of plot points input") msg.setInformativeText( "Should have more than 100 plot points for good visual results." ) msg.setWindowTitle("Invalid number of plot points input") msg.exec_() return False temp_value = float(self.temp_box.text()) if temp_value < 0.0: msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText("Invalid temperature input") msg.setInformativeText( "Temperature needs to be positive value. [Kelvin]") msg.setWindowTitle("Invalid temperature input") msg.exec_() return False wl_lower = float(self.wl_box_lower.text()) wl_upper = float(self.wl_box_upper.text()) if wl_lower > wl_upper: msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText("Invalid wavelength input") msg.setInformativeText( "Lower wavelength needs to be smaller than larger wavelength.") msg.setWindowTitle("Invalid wavelength input") msg.exec_() return False return True def plot(self): """Function to create plots according to the given valid inputs. This function is called if the 'plot' button is pressed. """ if self.check_input(): # Get values from input fields temp_value = float(self.temp_box.text()) wl_lower = float(self.wl_box_lower.text()) wl_upper = float(self.wl_box_upper.text()) npp = int(self.npp_box.text()) # Create arrays for plot wave_linspace = np.linspace(wl_lower, wl_upper, npp) blackbody_radiation = np.zeros(len(wave_linspace)) # Calculate all values for w in range(len(wave_linspace)): blackbody_radiation[w] = PlancksLaw.plancks_law_function( temp_value, wave_linspace[w]) # Plot the curve self.ax.plot(wave_linspace * PlancksLaw.m_to_micrometer, blackbody_radiation[:]) # Set axis labels self.ax.set_xlabel(r"Wavelength $\mu m$") self.ax.set_ylabel(r"Black body radiation $W sr^{-1} m^{-3}$", rotation="horizontal") self.ax.yaxis.set_label_coords(0.2, 1.05) # Tighten the plot self.figure.tight_layout() # Refresh canvas self.canvas.draw()
class QVisaDynamicPlot(QWidget): def __init__(self, _app): QWidget.__init__(self) # Axes are be stored in a standard dictionary # [111] = subplot(111) # [111t] = subplot(111).twinx() self._axes = {} # Axes handles will be stored in QVisaDataObject # [111] # [<key0>] = handles(list) # [<key1>] = handles(list) self._handles = QVisaDataObject() # QVisaColorMap class and generator function self._cmap = QVisaColorMap() self._cgen = self._cmap.gen_next_color() # Dictionary to hold plot adjust values self._adjust = {'l': 0.15, 'r': 0.90, 't': 0.90, 'b': 0.10} # Generate main layout self._gen_main_layout() # Cache a reference to the calling application self._app = _app self.sync = False def _gen_main_layout(self): self._layout = QVBoxLayout() # Generate widgets self._gen_mpl_widgets() # HBoxLayout for toolbar and clear button self._layout_toolbar = QHBoxLayout() self._layout_toolbar.addWidget(self.mpl_toolbar) self._layout_toolbar.addWidget(self.mpl_handles_label) self._layout_toolbar.addWidget(self.mpl_handles) self._layout_toolbar.addWidget(self.mpl_refresh) # HBoxLayout for plot object self._layout_plot = QHBoxLayout() self._layout_plot.addWidget(self.mpl_canvas) # Add layouts self._layout.addLayout(self._layout_toolbar) self._layout.addLayout(self._layout_plot) # Set widget layout self.setLayout(self._layout) # Generate matplotlib widgets def _gen_mpl_widgets(self): # Generate matplotlib figure and canvas self.mpl_figure = plt.figure(figsize=(8, 5)) self.mpl_canvas = FigureCanvas(self.mpl_figure) self.mpl_toolbar = NavigationToolbar(self.mpl_canvas, self) # Handle selector self.mpl_handles_label = QLabel("<b>Show:</b>") self.mpl_handles = QComboBox() self.mpl_handles.addItem("all-traces") self.mpl_handles.setFixedHeight(30) self.mpl_handles.currentTextChanged.connect( self.update_visible_handles) # Refresh button self.mpl_refresh = QPushButton("Clear Data") self.mpl_refresh.clicked.connect(self.refresh_canvas) self.mpl_refresh.setFixedHeight(32) self.mpl_refresh_callback = None # Method to enable and disable mpl_refresh button def mpl_refresh_setEnabled(self, _bool): self.mpl_refresh.setEnabled(_bool) # Add mechanism to pass app method to run on mpl_refresh.clicked def set_mpl_refresh_callback(self, __func__): self.mpl_refresh_callback = str(__func__) # Run app method attached to mpl_refresh.clicked def _run_mpl_refresh_callback(self): if self.mpl_refresh_callback is not None: __func__ = getattr(self._app, self.mpl_refresh_callback) __func__() # Sync application data. When True, refresh lines will attempt to # del self._app._data.data[_handle_key] when clearing data in axes # self._handles[_axes_key][_handle_key]. This will synchonize plots # with application data. def sync_application_data(self, _bool): self.sync = _bool # Wrapper method to set(change) colormap def gen_cmap_colors(self, _cmap="default"): self._cmap.gen_cmap_colors(_cmap) # Wrapper method to gnertae next color def gen_next_color(self): return next(self._cgen) # Add axes object to widget def add_subplot(self, _axes_key=111, twinx=False): self._handles.add_key(str(_axes_key)) self._axes[str(_axes_key)] = self.mpl_figure.add_subplot(_axes_key) if twinx: self._handles.add_key(str(_axes_key) + 't') self._axes[str(_axes_key) + 't'] = self._axes[str(_axes_key)].twinx() # Add axes xlabels def set_axes_xlabel(self, _axes_key, _xlabel): self._axes[_axes_key].set_xlabel(str(_xlabel)) # Add axes ylabels def set_axes_ylabel(self, _axes_key, _ylabel): self._axes[_axes_key].set_ylabel(str(_ylabel)) # Convenience method to set axes labels def set_axes_labels(self, _axes_key, _xlabel, _ylabel): self.set_axes_xlabel(str(_axes_key), _xlabel) self.set_axes_ylabel(str(_axes_key), _ylabel) # Set axes adjust def set_axes_adjust(self, _left, _right, _top, _bottom): self._adjust = {'l': _left, 'r': _right, 't': _top, 'b': _bottom} # Add origin lines def add_origin_lines(self, _axes_key, key="both"): # x-line only if key == "x": self._axes[_axes_key].axhline(y=0, color='k', linewidth=0.5, linestyle=":") # y-line only if key == "y": self._axes[_axes_key].axvline(x=0, color='k', linewidth=0.5, linestyle=":") # both lines if key == "both": self._axes[_axes_key].axhline(y=0, color='k', linewidth=0.5, linestyle=":") self._axes[_axes_key].axvline(x=0, color='k', linewidth=0.5, linestyle=":") # Add handle to axes def add_axes_handle(self, _axes_key, _handle_key, _color=None): # Get handle keys from comboBox _handle_keys = [ self.mpl_handles.itemText(i) for i in range(self.mpl_handles.count()) ] # Check if handle key is in list if _handle_key not in _handle_keys: self.mpl_handles.addItem(_handle_key) # Add option to set color directly if _color is not None: h, = self._axes[str(_axes_key)].plot([], [], color=_color) # Otherwise generate color on defined map else: h, = self._axes[str(_axes_key)].plot([], [], color=self.gen_next_color()) # Add handle to handle keys self._handles.add_subkey(_axes_key, _handle_key) self._handles.append_subkey_data(_axes_key, _handle_key, h) # Method to get axes handles def get_axes_handles(self): return self._handles # Update axes handle (set) def set_handle_data(self, _axes_key, _handle_key, x_data, y_data, _handle_index=0): # Get the list of handles _h = self._handles.get_subkey_data(_axes_key, _handle_key) # Set data values on _handle_index _h[_handle_index].set_xdata(x_data) _h[_handle_index].set_ydata(y_data) # Update axes handle (append) def append_handle_data(self, _axes_key, _handle_key, x_value, y_value, _handle_index=0): # Get the list of handles _h = self._handles.get_subkey_data(_axes_key, _handle_key) # Append new values to handle data _x = np.append(_h[_handle_index].get_xdata(), x_value) _y = np.append(_h[_handle_index].get_ydata(), y_value) # Set xdata and ydata to handle _h[_handle_index].set_xdata(_x) _h[_handle_index].set_ydata(_y) # Method to redraw canvas lines def update_visible_handles(self): # Get handle _show_handle = self.mpl_handles.currentText() # Set all traces visible if _show_handle == "all-traces": # For each axis (e.g. 111) for _axes_key in self._handles.keys(): # Check if there are handles on the key if self._handles.subitems(_axes_key) is not None: # Loop through handle_key and handle_list for _handle_key, _handle_list in self._handles.subitems( _axes_key): [_h.set_visible(True) for _h in _handle_list] else: # For each axis (e.g. 111) for _axes_key in self._axes.keys(): # Check if there are handles on the key if self._handles.subitems(_axes_key) is not None: # Loop through handle_key and handle_list for _handle_key, _handle_list in self._handles.subitems( _axes_key): if _show_handle == _handle_key: [_h.set_visible(True) for _h in _handle_list] else: [_h.set_visible(False) for _h in _handle_list] self.update_canvas() # Method to update canvas dynamically def update_canvas(self): # Loop through all figure axes and relimit for _key, _axes in self._axes.items(): _axes.relim() _axes.autoscale_view() _axes.ticklabel_format(style='sci', scilimits=(0, 0), axis='y', useOffset=False) # Adjust subplots plt.subplots_adjust(left=self._adjust['l'], right=self._adjust['r'], top=self._adjust['t'], bottom=self._adjust['b']) # Draw and flush_events self.mpl_canvas.draw() self.mpl_canvas.flush_events() # Refresh canvas. Note callback will expose args as False def refresh_canvas(self, supress_warning=False): # Only ask to redraw if there is data present if (self._handles.keys_empty() == False) and (supress_warning == False): msg = QMessageBox() msg.setIcon(QMessageBox.Information) msg.setText("Clear measurement data (%s)?" % self.mpl_handles.currentText()) msg.setWindowTitle("QDynamicPlot") msg.setWindowIcon(self._app._get_icon()) msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No) self.msg_clear = msg.exec_() # Note that mpl_refresh_callback is run after refresh lines. if self.msg_clear == QMessageBox.Yes: self.refresh_lines() self._run_mpl_refresh_callback() return True else: return False else: self.refresh_lines() self._run_mpl_refresh_callback() return True # Method to delete lines from handle def refresh_lines(self): # Create empty handle cache _del_cache = [] # For each axes (e.g. 111) for _axes_key in self._axes.keys(): # Check if there are handles on the key if self._handles.subitems(_axes_key) is not None: # Loop through handle_key, handle_list objects on axes for _handle_key, _handle_list in self._handles.subitems( _axes_key): # Check if first handle in the list is visible if _handle_list[0].get_visible( ) == True and _handle_key not in _del_cache: # Cache the handle key for deletion if it has not beed cached yet _del_cache.append(_handle_key) # Loop through cached keys for _handle_key in _del_cache: # Check for key on each axis (e.g. 111, 111t) for _axes_key in self._axes.keys(): # Remove handles (mpl.Artist obejcts) by calling destructor for _handle in self._handles.get_subkey_data( _axes_key, _handle_key): _handle.remove() # Delete the _handle_key from _handles object self._handles.del_subkey(_axes_key, _handle_key) # Remove _handle_key from dropdown self.mpl_handles.removeItem(self.mpl_handles.findText(_handle_key)) # Remove _handle_key from application data if syncing if self.sync == True: _data = self._app._get_data_object() _data.del_key(_handle_key) # If deleting all traces, reset the colormap if self.mpl_handles.currentText() == "all-traces": self._cmap.gen_reset() # Otherwise set text to "all-traces" else: self.mpl_handles.setCurrentIndex(0) # Redraw canvas self.update_canvas() # Method to reset axes def reset_canvas(self): # Clear the axes for _key, _axes in self._axes.items(): # Pull labels _xlabel = _axes.get_xlabel() _ylabel = _axes.get_ylabel() # clear axes and reset labels _axes.clear() _axes.set_xlabel(_xlabel) _axes.set_ylabel(_ylabel) # Clear registered handles # Calling add_key() will re-initialize data dictionary to {} for axes [ self._handles.add_key(_axes_key) for _axes_key in self._handles.keys() ] # Clear the combobox self.mpl_handles.clear() self.mpl_handles.addItem("all-traces") # Reset the colormap self._cmap.gen_reset() # Update canvas self.update_canvas()
def UI_setup(self): self.figure = Figure() self.canvas = FigureCanvas(self.figure) self.button = QtWidgets.QPushButton("Plot", self) self.button.clicked.connect(self.plot) self.button.resize(self.button.minimumSizeHint()) self.button.move(100, 100) VLabel = QtWidgets.QLabel("y(x) = ax^2 + bx + c", self) LLabel = QtWidgets.QLabel("Line Color", self) RLabel = QtWidgets.QLabel("Root Color", self) LcomboBox = QtWidgets.QComboBox(self) RcomboBox = QtWidgets.QComboBox(self) LcomboBox.addItem("Blue") LcomboBox.addItem("Green") LcomboBox.addItem("Red") LcomboBox.addItem("Cyan") LcomboBox.addItem("Magenta") LcomboBox.addItem("Yellow") LcomboBox.addItem("Black") LcomboBox.addItem("White") RcomboBox.addItem("Blue") RcomboBox.addItem("Green") RcomboBox.addItem("Red") RcomboBox.addItem("Cyan") RcomboBox.addItem("Magenta") RcomboBox.addItem("Yellow") RcomboBox.addItem("Black") RcomboBox.addItem("White") LcomboBox.activated[str].connect(self.set_color) RcomboBox.activated[str].connect(self.set_root_color) hbox1 = QtWidgets.QHBoxLayout() hbox2 = QtWidgets.QHBoxLayout() hbox3 = QtWidgets.QHBoxLayout() hbox1.addStretch(1) hbox2.addStretch(1) hbox3.addStretch(1) hbox1.addWidget(self.button) hbox1.addWidget(self.canvas) hbox3.addWidget(LLabel) hbox3.addWidget(LcomboBox) hbox3.addWidget(RLabel) hbox3.addWidget(RcomboBox) validator = QtGui.QDoubleValidator() ALabel = QtWidgets.QLabel("a", self) ALineEdit = QtWidgets.QLineEdit("0", self) ALineEdit.setValidator(validator) ALineEdit.textChanged[str].connect(self.set_quadratic_a) BLabel = QtWidgets.QLabel("b", self) BLineEdit = QtWidgets.QLineEdit("0", self) BLineEdit.setValidator(validator) BLineEdit.textChanged[str].connect(self.set_quadratic_b) CLabel = QtWidgets.QLabel("c", self) CLineEdit = QtWidgets.QLineEdit("0", self) CLineEdit.setValidator(validator) CLineEdit.textChanged[str].connect(self.set_quadratic_c) hbox2.addWidget(ALabel) hbox2.addWidget(ALineEdit) hbox2.addWidget(BLabel) hbox2.addWidget(BLineEdit) hbox2.addWidget(CLabel) hbox2.addWidget(CLineEdit) vbox = QtWidgets.QVBoxLayout() vbox.addStretch(1) vbox.addLayout(hbox1) vbox.addWidget(VLabel, alignment=QtCore.Qt.AlignCenter) vbox.addLayout(hbox2) vbox.addLayout(hbox3) self.CenWidget.setLayout(vbox) self.setGeometry(50, 50, 600, 600) self.setWindowTitle("Quadratic Function Plotter")
class PlotGui(QtWidgets.QMainWindow): # def plotting_gui(): """ Function: plotting_gui() INPUT: None OUTPUT: A GUI window Definition: Using Qt, outputs a GUI where a user can input a quadratic function y(x) = ax2 + bx + c, and then it plots the parabola, indicating and labeling the roots. The user can choose a color for the parabola and the roots. """ def __init__(self): super(PlotGui, self).__init__() self.CenWidget = QtWidgets.QWidget(self) self.setCentralWidget(self.CenWidget) self.color = "Blue" self.root_color = 'b' self.quad_eq_a = 0 self.quad_eq_b = 0 self.quad_eq_c = 0 self.UI_setup() self.show() def UI_setup(self): self.figure = Figure() self.canvas = FigureCanvas(self.figure) self.button = QtWidgets.QPushButton("Plot", self) self.button.clicked.connect(self.plot) self.button.resize(self.button.minimumSizeHint()) self.button.move(100, 100) VLabel = QtWidgets.QLabel("y(x) = ax^2 + bx + c", self) LLabel = QtWidgets.QLabel("Line Color", self) RLabel = QtWidgets.QLabel("Root Color", self) LcomboBox = QtWidgets.QComboBox(self) RcomboBox = QtWidgets.QComboBox(self) LcomboBox.addItem("Blue") LcomboBox.addItem("Green") LcomboBox.addItem("Red") LcomboBox.addItem("Cyan") LcomboBox.addItem("Magenta") LcomboBox.addItem("Yellow") LcomboBox.addItem("Black") LcomboBox.addItem("White") RcomboBox.addItem("Blue") RcomboBox.addItem("Green") RcomboBox.addItem("Red") RcomboBox.addItem("Cyan") RcomboBox.addItem("Magenta") RcomboBox.addItem("Yellow") RcomboBox.addItem("Black") RcomboBox.addItem("White") LcomboBox.activated[str].connect(self.set_color) RcomboBox.activated[str].connect(self.set_root_color) hbox1 = QtWidgets.QHBoxLayout() hbox2 = QtWidgets.QHBoxLayout() hbox3 = QtWidgets.QHBoxLayout() hbox1.addStretch(1) hbox2.addStretch(1) hbox3.addStretch(1) hbox1.addWidget(self.button) hbox1.addWidget(self.canvas) hbox3.addWidget(LLabel) hbox3.addWidget(LcomboBox) hbox3.addWidget(RLabel) hbox3.addWidget(RcomboBox) validator = QtGui.QDoubleValidator() ALabel = QtWidgets.QLabel("a", self) ALineEdit = QtWidgets.QLineEdit("0", self) ALineEdit.setValidator(validator) ALineEdit.textChanged[str].connect(self.set_quadratic_a) BLabel = QtWidgets.QLabel("b", self) BLineEdit = QtWidgets.QLineEdit("0", self) BLineEdit.setValidator(validator) BLineEdit.textChanged[str].connect(self.set_quadratic_b) CLabel = QtWidgets.QLabel("c", self) CLineEdit = QtWidgets.QLineEdit("0", self) CLineEdit.setValidator(validator) CLineEdit.textChanged[str].connect(self.set_quadratic_c) hbox2.addWidget(ALabel) hbox2.addWidget(ALineEdit) hbox2.addWidget(BLabel) hbox2.addWidget(BLineEdit) hbox2.addWidget(CLabel) hbox2.addWidget(CLineEdit) vbox = QtWidgets.QVBoxLayout() vbox.addStretch(1) vbox.addLayout(hbox1) vbox.addWidget(VLabel, alignment=QtCore.Qt.AlignCenter) vbox.addLayout(hbox2) vbox.addLayout(hbox3) self.CenWidget.setLayout(vbox) self.setGeometry(50, 50, 600, 600) self.setWindowTitle("Quadratic Function Plotter") def plot(self): xvalues = [] yvalues = [] xroots = [] yroots = [] z = sp.symbols('z') f = self.quad_eq_a * z**2 + self.quad_eq_b * z + self.quad_eq_c for i in sp.solve(f, z): complexCheck = np.iscomplex(complex(i)) if not complexCheck: xroots.append(i) yroots.append(0) for x in range(-10, 10, 1): # for x in range(-100,100,1): y = self.quad_eq_a * x**2 + self.quad_eq_b * x + self.quad_eq_c xvalues.append(x) yvalues.append(y) self.figure.clear() plot1 = self.figure.add_subplot(1, 1, 1) plot1.axhline(0, color="black", linestyle='--') plot1.axvline(0, color="black", linestyle='--') if self.color == "Blue": plot1.plot(xvalues, yvalues, 'b-', markersize=1) plot1.plot(xroots, yroots, 'o', markersize=12, markerfacecolor=self.root_color) elif self.color == "Green": plot1.plot(xvalues, yvalues, 'g-', markersize=1, markerfacecolor=self.root_color) plot1.plot(xroots, yroots, 'o', markersize=12, markerfacecolor=self.root_color) elif self.color == "Red": plot1.plot(xvalues, yvalues, 'r-', markersize=1, markerfacecolor=self.root_color) plot1.plot(xroots, yroots, 'o', markersize=12, markerfacecolor=self.root_color) elif self.color == "Cyan": plot1.plot(xvalues, yvalues, 'c-', markersize=1, markerfacecolor=self.root_color) plot1.plot(xroots, yroots, 'o', markersize=12, markerfacecolor=self.root_color) elif self.color == "Magenta": plot1.plot(xvalues, yvalues, 'm-', markersize=1, markerfacecolor=self.root_color) plot1.plot(xroots, yroots, 'o', markersize=12, markerfacecolor=self.root_color) elif self.color == "Yellow": plot1.plot(xvalues, yvalues, 'y-', markersize=1, markerfacecolor=self.root_color) plot1.plot(xroots, yroots, 'o', markersize=12, markerfacecolor=self.root_color) elif self.color == "Black": plot1.plot(xvalues, yvalues, 'k-', markersize=1, markerfacecolor=self.root_color) plot1.plot(xroots, yroots, 'o', markersize=12, markerfacecolor=self.root_color) elif self.color == "White": plot1.plot(xvalues, yvalues, 'w-', markersize=1, markerfacecolor=self.root_color) plot1.plot(xroots, yroots, 'o', markersize=12, markerfacecolor=self.root_color) else: plot1.plot(xvalues, yvalues, 'b-', markersize=1, markerfacecolor=self.root_color) plot1.plot(xroots, yroots, 'o', markersize=12, markerfacecolor=self.root_color) self.canvas.draw() def set_color(self, text): self.color = text def set_root_color(self, text): if text == "Black": self.root_color = 'k' else: firstchar = text[0] self.root_color = firstchar.lower() def set_quadratic_a(self, value): if value: if value[0] == '-': if len(value) > 1: negative_value = -1 * float(value[1:]) self.quad_eq_a = negative_value else: self.quad_eq_a = float(value) def set_quadratic_b(self, value): if value: if value[0] == '-': if len(value) > 1: negative_value = -1 * float(value[1:]) self.quad_eq_b = negative_value else: self.quad_eq_b = float(value) def set_quadratic_c(self, value): if value: if value[0] == '-': if len(value) > 1: negative_value = -1 * float(value[1:]) self.quad_eq_c = negative_value else: self.quad_eq_c = float(value)
def initUI(self): has_type = [] frame_left = {} vbox_left = {} label_left = {} topic_type_dict = bag_reader.read_bag(sys.argv[1]) for msg_type in topic_type_dict.values(): if bag_reader.msg_types.count( msg_type) and not has_type.count(msg_type): has_type.append(msg_type) splitter_left = QtWidgets.QSplitter(QtCore.Qt.Vertical) # Separates the variables to different categories in order to populate the screen for msg_type in has_type: frame_left[msg_type] = QtWidgets.QFrame(self) frame_left[msg_type].setFrameShape(QtWidgets.QFrame.StyledPanel) vbox_left[msg_type] = QtWidgets.QVBoxLayout(self) label_left[msg_type] = QtWidgets.QLabel(self) label_left[msg_type].setText(msg_type) label_left[msg_type].adjustSize() vbox_left[msg_type].addWidget(label_left[msg_type]) for topic in topic_type_dict.keys(): if topic_type_dict[topic] == msg_type: cb = QtWidgets.QCheckBox(topic, self) cb.stateChanged.connect(self.addTopic) vbox_left[msg_type].addWidget(cb) vbox_left[msg_type].addStretch(1) frame_left[msg_type].setLayout(vbox_left[msg_type]) splitter_left.addWidget(frame_left[msg_type]) vbox_left_var = QtWidgets.QVBoxLayout(self) label_left_var = QtWidgets.QLabel(self) label_left_var.setText('Variables') label_left_var.adjustSize() vbox_left_var.addWidget(label_left_var) frame_left_var = QtWidgets.QFrame(self) frame_left_var.setFrameShape(QtWidgets.QFrame.StyledPanel) for var in bag_reader.var_types: cb = QtWidgets.QCheckBox(var, self) cb.stateChanged.connect(self.addVar) vbox_left_var.addWidget(cb) vbox_left_var.addStretch(0) frame_left_var.setLayout(vbox_left_var) splitter_left.addWidget(frame_left_var) frame_left_control = QtWidgets.QFrame(self) frame_left_control.setFrameShape(QtWidgets.QFrame.StyledPanel) vbox_left_control = QtWidgets.QVBoxLayout(self) load_btn = QtWidgets.QPushButton('Load', self) clear_btn = QtWidgets.QPushButton('Clear', self) save_btn = QtWidgets.QPushButton('Save Figure', self) load_btn.clicked.connect(self.buttonClicked) clear_btn.clicked.connect(self.buttonClearClicked) save_btn.clicked.connect(self.buttonSaveClicked) vbox_left_control.addWidget(load_btn) vbox_left_control.addWidget(clear_btn) vbox_left_control.addWidget(save_btn) vbox_left_control.addStretch(1) frame_left_control.setLayout(vbox_left_control) splitter_left.addWidget(frame_left_control) frame_right = QtWidgets.QFrame(self) frame_right.setFrameShape(QtWidgets.QFrame.StyledPanel) splitter_v = QtWidgets.QSplitter(QtCore.Qt.Horizontal) splitter_v.addWidget(splitter_left) splitter_v.addWidget(frame_right) hbox = QtWidgets.QHBoxLayout(self) hbox.addWidget(splitter_v) self.figure = plt.figure() self.canvas = FigureCanvas(self.figure) vbox_right = QtWidgets.QVBoxLayout(self) vbox_right.addWidget(self.canvas) frame_right.setLayout(vbox_right) self.setLayout(hbox) self.resize(1000, 800) self.center() self.show()
class Example(QtWidgets.QWidget): def __init__(self): super(Example, self).__init__() self.initUI() def initUI(self): has_type = [] frame_left = {} vbox_left = {} label_left = {} topic_type_dict = bag_reader.read_bag(sys.argv[1]) for msg_type in topic_type_dict.values(): if bag_reader.msg_types.count( msg_type) and not has_type.count(msg_type): has_type.append(msg_type) splitter_left = QtWidgets.QSplitter(QtCore.Qt.Vertical) # Separates the variables to different categories in order to populate the screen for msg_type in has_type: frame_left[msg_type] = QtWidgets.QFrame(self) frame_left[msg_type].setFrameShape(QtWidgets.QFrame.StyledPanel) vbox_left[msg_type] = QtWidgets.QVBoxLayout(self) label_left[msg_type] = QtWidgets.QLabel(self) label_left[msg_type].setText(msg_type) label_left[msg_type].adjustSize() vbox_left[msg_type].addWidget(label_left[msg_type]) for topic in topic_type_dict.keys(): if topic_type_dict[topic] == msg_type: cb = QtWidgets.QCheckBox(topic, self) cb.stateChanged.connect(self.addTopic) vbox_left[msg_type].addWidget(cb) vbox_left[msg_type].addStretch(1) frame_left[msg_type].setLayout(vbox_left[msg_type]) splitter_left.addWidget(frame_left[msg_type]) vbox_left_var = QtWidgets.QVBoxLayout(self) label_left_var = QtWidgets.QLabel(self) label_left_var.setText('Variables') label_left_var.adjustSize() vbox_left_var.addWidget(label_left_var) frame_left_var = QtWidgets.QFrame(self) frame_left_var.setFrameShape(QtWidgets.QFrame.StyledPanel) for var in bag_reader.var_types: cb = QtWidgets.QCheckBox(var, self) cb.stateChanged.connect(self.addVar) vbox_left_var.addWidget(cb) vbox_left_var.addStretch(0) frame_left_var.setLayout(vbox_left_var) splitter_left.addWidget(frame_left_var) frame_left_control = QtWidgets.QFrame(self) frame_left_control.setFrameShape(QtWidgets.QFrame.StyledPanel) vbox_left_control = QtWidgets.QVBoxLayout(self) load_btn = QtWidgets.QPushButton('Load', self) clear_btn = QtWidgets.QPushButton('Clear', self) save_btn = QtWidgets.QPushButton('Save Figure', self) load_btn.clicked.connect(self.buttonClicked) clear_btn.clicked.connect(self.buttonClearClicked) save_btn.clicked.connect(self.buttonSaveClicked) vbox_left_control.addWidget(load_btn) vbox_left_control.addWidget(clear_btn) vbox_left_control.addWidget(save_btn) vbox_left_control.addStretch(1) frame_left_control.setLayout(vbox_left_control) splitter_left.addWidget(frame_left_control) frame_right = QtWidgets.QFrame(self) frame_right.setFrameShape(QtWidgets.QFrame.StyledPanel) splitter_v = QtWidgets.QSplitter(QtCore.Qt.Horizontal) splitter_v.addWidget(splitter_left) splitter_v.addWidget(frame_right) hbox = QtWidgets.QHBoxLayout(self) hbox.addWidget(splitter_v) self.figure = plt.figure() self.canvas = FigureCanvas(self.figure) vbox_right = QtWidgets.QVBoxLayout(self) vbox_right.addWidget(self.canvas) frame_right.setLayout(vbox_right) self.setLayout(hbox) self.resize(1000, 800) self.center() self.show() # Returns a list of topics that are actually filled with values among all listed topics def topics_to_read(self): topics_to_read = [] for topic in topics_selected: if not topics_has_read.count(topic): topics_has_read.append(topic) if not topics_to_read.count(topic): topics_to_read.append(topic) return topics_to_read def plot(self): new_data = bag_reader.read_msg(self.topics_to_read()) for key in new_data.keys(): if key not in data: data[key] = new_data[key] mouse_interface.plot_data(data, variables_selected, topics_selected) self.canvas.draw() def addTopic(self, state): topic = str(self.sender().text()) if state == QtCore.Qt.Checked: if not topics_selected.count(topic): topics_selected.append(topic) else: if topics_selected.count(topic): topics_selected.remove(topic) def addVar(self, state): var = str(self.sender().text()) if state == QtCore.Qt.Checked: if not variables_selected.count(var): variables_selected.append(var) else: if variables_selected.count(var): variables_selected.remove(var) def buttonClearClicked(self): mouse_interface.clear() def buttonSaveClicked(self): mouse_interface.save() def buttonClicked(self): self.plot() def keyPressEvent(self, e): if e.key() == QtCore.Qt.Key_Escape: self.close() elif e.key() == QtCore.Qt.Key_Shift: mouse_interface.shift_hold = True else: mouse_interface.shift_hold = False def keyReleaseEvent(self, e): if e.key() == QtCore.Qt.Key_Shift: mouse_interface.shift_hold = False def center(self): qr = self.frameGeometry() cp = QtWidgets.QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft())
class PrettyWidget(QtWidgets.QWidget): def __init__(self): super(PrettyWidget, self).__init__() self.initUI() def initUI(self): self.setGeometry(600, 300, 1000, 600) self.center() self.setWindowTitle('MTI GUI') #Grid Layout grid = QtWidgets.QGridLayout() self.setLayout(grid) #Canvas and Toolbar self.figure = plt.figure(figsize=(15, 5)) self.canvas = FigureCanvas(self.figure) #self.toolbar = NavigationToolbar(self.canvas, self) self.lblDistance = QtWidgets.QLabel() self.lblMetadata = QtWidgets.QLabel() self.lblCenter = QtWidgets.QLabel() grid.addWidget(self.canvas, 2, 0, 1, 2) grid.addWidget(self.lblMetadata, 3, 0) grid.addWidget(self.lblDistance, 4, 0) grid.addWidget(self.lblCenter, 5, 0) #grid.addWidget(self.toolbar, 1,0,1,2) #Import CSV Button btn1 = QtWidgets.QPushButton('Import text file', self) btn1.resize(btn1.sizeHint()) btn1.clicked.connect(self.getCSV) grid.addWidget(btn1, 0, 0) self.show() def getCSV(self): filePath = QtWidgets.QFileDialog.getOpenFileName( self, 'Single File', '~/Desktop/PyRevolution/PyQt4', '*.txt') tuple = load_data(filePath[0], True) df = tuple[0] metaData = tuple[1] #get distance and center for intersection print(getCenterAndDistance(filePath[0])) distance, center, intersectLine, lowPoint, highPoint = getCenterAndDistance( filePath[0]) x = list(df.iloc[:, 0].values) y = list(df.iloc[:, 1].values) line = SG.LineString(list(zip(x, y))) yline = SG.LineString([(min(x), intersectLine), (max(x), intersectLine)]) coords = np.array(line.intersection(yline)) ax = self.figure.add_subplot(111) ax.axhline(y=intersectLine, color='k', linestyle='--') ax.plot(x, y, 'b-') if coords.size != 0: ax.scatter(coords[:, 0], coords[:, 1], s=50, c='red') ax.axvline(x=lowPoint, color='k', linestyle='--') ax.plot(x, y, 'y-') ax.axvline(x=highPoint, color='k', linestyle='--') ax.plot(x, y, 'p-') ax.set_xlabel('Wavelength') ax.set_ylabel('Transmission') self.canvas.draw() self.lblMetadata.setText("Metadata: " + metaData) self.lblDistance.setText("Distance: " + str(distance)) self.lblCenter.setText("Center:" + str(center)) def plot(self): y = [] for n in range(9): try: y.append(float(self.table.item(0, n).text())) except: y.append(np.nan) plt.cla() ax = self.figure.add_subplot(111) ax.plot(y, 'r.-') ax.set_title('Table Plot') self.canvas.draw() def center(self): qr = self.frameGeometry() cp = QtWidgets.QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft())
def new_figure_manager_given_figure(num, figure): """Create a new figure manager instance for the given figure.""" canvas = FigureCanvasQTAgg(figure) manager = FigureManagerWorkbench(canvas, num) return manager
class MyMainWindow(QtWidgets.QMainWindow): def __init__(self, *args): super().__init__(*args) fnameUI = os.path.join(os.path.dirname(__file__), 'neuronmodel.ui') uic.loadUi(fnameUI, self) self.setWindowTitle('NEURON Hodgkin–Huxley model') def initModel(self): self.cell = BallAndStick(0, self) def initFigures(self): #Descriptive figures self.dendrite_plot_group.layout = QtWidgets.QVBoxLayout() self.fig_dend = plt.figure() self.ax_dend = self.fig_dend.add_axes([0.2, 0.2, 0.7, 0.7]) self.canvas_dend = FigureCanvas(self.fig_dend) self.dendrite_plot_group.layout.addWidget(self.canvas_dend) self.dendrite_plot_group.setLayout(self.dendrite_plot_group.layout) self.ax_dend.set_xlabel('t (ms)') self.ax_dend.set_ylabel('v (mV)') #Statistics figures self.soma_plot_group.layout = QtWidgets.QVBoxLayout() self.fig_soma = plt.figure() self.ax_soma = self.fig_soma.add_axes([0.2, 0.2, 0.7, 0.7]) self.canvas_soma = FigureCanvas(self.fig_soma) self.soma_plot_group.layout.addWidget(self.canvas_soma) self.soma_plot_group.setLayout(self.soma_plot_group.layout) self.ax_soma.set_xlabel('t (ms)') self.ax_soma.set_ylabel('v (mV)') def plot(self): stim = h.IClamp(self.cell.dend(1)) stim.get_segment() stim.delay = 5 stim.dur = 1 stim.amp = 0.1 soma_v = h.Vector().record(self.cell.soma(0.5)._ref_v) dend_v = h.Vector().record(self.cell.dend(0.5)._ref_v) t = h.Vector().record(h._ref_t) amps = [0.075 * i for i in range(1, 5)] colors = ['green', 'blue', 'red', 'black'] self.ax_soma.clear() self.ax_dend.clear() self.ax_dend.set_xlabel('t (ms)') self.ax_dend.set_ylabel('v (mV)') self.ax_soma.set_xlabel('t (ms)') self.ax_soma.set_ylabel('v (mV)') try: for amp, color in zip(amps, colors): stim.amp = amp h.finitialize(-65 * mV) h.continuerun(25 * ms) self.canvas_dend.draw() self.ax_dend.plot(t, dend_v, color) self.canvas_soma.draw() self.ax_soma.plot(t, soma_v, color) self.ax_dend.legend(["{:.2f}".format(elem) for elem in amps]) except: self.ax_soma.clear() self.ax_dend.clear() def updateModel(self): self.initModel() self.plot()
class WaterfallPlotter(QWidget): generated_rectangles_signal = QtCore.pyqtSignal(list) #send list of rects for data display in tree def __init__(self,parent): super(WaterfallPlotter,self).__init__(parent) self.figure = plt.figure() self.canvas = FigureCanvas(self.figure) self.toolbar = NavigationToolbar(self.canvas,self) self.btn_plot = QPushButton('Default Plot') self.btn_plot.clicked.connect(self.default_plot) self.layout = QVBoxLayout() self.layout.addWidget(self.toolbar) self.layout.addWidget(self.canvas) self.layout.addWidget(self.btn_plot) self.setLayout(self.layout) def on_waterfall_data_signal(self,signal): self.waterfall_data = signal['waterfall_data'] #pandas dataframe self.btn_plot.setEnabled(True) def on_general_settings_signal(self,signal): try: hasattr(self,'ax') self.ax.set_title(signal[0]) self.ax.set_xlabel(signal[1]) self.ax.set_ylabel(signal[2]) self.canvas.draw() except Exception as e: print(e) def default_plot(self): ''' Plot waterfall data ''' self.figure.clear() self.rect_locations = np.arange(len(self.waterfall_data['Best response percent change'])) self.ax = self.figure.add_subplot(111) self.ax.axhline(y=20, linestyle='--', c='k', alpha=0.5, lw=2.0, label='twenty_percent') self.ax.axhline(y=-30, linestyle='--', c='k', alpha=0.5, lw=2.0, label='thirty_percent') self.ax.axhline(y=0, c='k', alpha=1, lw=2.0, label='zero_percent') self.ax.grid(color = 'k', axis = 'y', alpha=0.25) self.rects = self.ax.bar(self.rect_locations,self.waterfall_data['Best response percent change']) self.auto_label_responses(self.ax, self.rects, self.waterfall_data) #self.plot_table() self.canvas.draw() self.ax.hold(False) #rewrite the plot when plot() called self.generated_rectangles_signal.emit([self.rects]) def plot_table(self): rows = ['%s' % x for x in self.waterfall_data.keys()] rows = rows[4:] #skip first three, they are the 4 standard headers, rest are table rows columns = self.waterfall_data['Patient number'] #patient numbers cell_text = [] for row in rows: cell_text_temp = [] for col in range(len(columns)): cell_text_temp.append(self.waterfall_data[row][col]) cell_text.append(cell_text_temp) the_table = plt.table(cellText=cell_text, rowLabels=rows, colLabels=columns, loc='bottom', cellLoc='center') plt.subplots_adjust(bottom=0.15,left=0.5) self.ax.set_xlim(-0.5,len(columns)-0.5) plt.tick_params( axis='x', # changes apply to the x-axis which='both', # both major and minor ticks are affected bottom='off', # ticks along the bottom edge are off top='off', # ticks along the top edge are off labelbottom='off' ) # labels along the bottom edge are off def update_plot(self): ''' TODO ''' pass def auto_label_responses(self, ax, rects, waterfall_data): '''Add labels above/below bars''' i = 0 for rect in rects: height = rect.get_height() if height >= 0: valign = 'bottom' else: valign = 'top' ax.text(rect.get_x() + rect.get_width()/2., height, '%s' % waterfall_data['Overall response'][i], ha='center', va=valign) i+=1
class App(QMainWindow): def __init__(self): super().__init__() self.initUI() self.showUI() self.show() def initUI(self): self.setGeometry(100, 50, 850, 600) self.setWindowTitle('Neural Network Interface Solver') self.setWindowIcon(QIcon('brainGUI.png')) self.toolbar = self.addToolBar('Toolbar') self.functions = [sigmoid, sigmoid, sigmoid] self.erf = error def showUI(self): # Central widget and layout wid = QWidget() self.setCentralWidget(wid) grid = QGridLayout() wid.setLayout(grid) grid.setSpacing(5) # Creamos las cuatro cajas que vamos a usar Caja1 = QGroupBox('Dimensión de los datos del entrenamiento') Caja2 = QGroupBox('Área de la representación del error') Caja3 = QGroupBox('Parámetros de la red neuronal') Caja4 = QGroupBox('Zona de resultados') Caja5 = QGroupBox('Zona de botones') Caja1.setObjectName('PrimeraCaja') # Creamos los cuatro layouts. Son 4 Grids, al fin y al cabo. Caja1Layout = QGridLayout() Caja2Layout = QGridLayout() Caja3Layout = QGridLayout() Caja4Layout = QGridLayout() Caja5Layout = QGridLayout() Caja1.setLayout(Caja1Layout) Caja2.setLayout(Caja2Layout) Caja3.setLayout(Caja3Layout) Caja4.setLayout(Caja4Layout) Caja5.setLayout(Caja5Layout) grid.addWidget(Caja1, 0, 0, 1, 2) # 1 Fila - 2 Columnas grid.addWidget(Caja2, 1, 0, 1, 4) # 1 Fila - 4 Columnas grid.addWidget(Caja3, 2, 0, 1, 4) # 1 Fila - 2 Columnas grid.addWidget(Caja4, 0, 4, 2, 1) # 2 Filas - 1 Columna grid.addWidget(Caja5, 3, 0, 3, 4) # 3 Filas - 4 Columnas grid.setColumnStretch(0, 2) Caja1.setSizePolicy( QSizePolicy.Maximum, QSizePolicy.Maximum ) # Con esto se consigue dejar pequeña la mierda esa Caja3.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum) # Objects # Plot object self.figure = plt.figure(tight_layout=True) self.canvas = FigureCanvas(self.figure) self.canvas.setMinimumSize( 200, 200) # Esto hace que no se pueda hacer el widget to pequeño ax = self.figure.add_subplot(111) plt.xlabel('Iteración') plt.ylabel('Error') plt.title('Error vs Iteración') self.canvas.draw() # Labels for the functions label1 = QLabel('Input - H1') label2 = QLabel('H1 - H(-1)') label3 = QLabel('H(-1) - Output') label4 = QLabel('Error') label5 = QLabel('Layers') label6 = QLabel('Neurons') label7 = QLabel('Learning rate') label8 = QLabel('Regularization') label9 = QLabel('Resultados:') label10 = QLabel('Dimensión de inputs') label11 = QLabel('Dimensión de outputs') # Selectors for the functions self.combo1 = QComboBox(self) self.combo1.addItem('Sigmoid') self.combo1.addItem('ReLu') self.combo1.addItem('Linear') self.combo1.addItem('SoftMax') self.combo2 = QComboBox(self) self.combo2.addItem('Sigmoid') self.combo2.addItem('ReLu') self.combo2.addItem('Linear') self.combo2.addItem('SoftMax') self.combo3 = QComboBox(self) self.combo3.addItem('Sigmoid') self.combo3.addItem('ReLu') self.combo3.addItem('Linear') self.combo3.addItem('SoftMax') self.combo4 = QComboBox(self) self.combo4.addItem('Quadratic Error') self.combo4.addItem('Cross-Entropy function') # Botones btn = QPushButton('Cargar parámetros') btn.clicked.connect(self.checkParameters) btn2 = QPushButton('Crear Redes Neuronales') btn2.clicked.connect(self.initNetwork) btn3 = QPushButton('Resolver red') btn3.clicked.connect(self.solveNetwork) btn3.setStyleSheet( "font: bold; background-color: cyan; font-size: 26px; border-width: 100px; border-color: black" ) btn3.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) btn4 = QPushButton('Cargar Inputs y Outputs') btn4.clicked.connect(self.readInputs) # Edit Texts self.ed1 = QLineEdit(' ') self.ed2 = QLineEdit(' ') self.ed3 = QLineEdit(' ') self.ed4 = QLineEdit(' ') self.ed1.setText('1') self.ed2.setText('1') self.ed3.setText('1') self.ed4.setText('1') self.ed5 = QLineEdit('1') self.ed6 = QLineEdit('1') self.ed5.setMaximumWidth(30) self.ed6.setMaximumWidth(30) # Bloque de texto self.block = QTextEdit('Status:') self.block.moveCursor(QTextCursor.End) self.block.insertPlainText('\n' + 'Run for results') self.block.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) # Colocamos los objetos # Labels Caja1Layout.addWidget(label10, 0, 0) Caja1Layout.addWidget(label11, 1, 0) Caja1Layout.addWidget(self.ed5, 0, 1) Caja1Layout.addWidget(self.ed6, 1, 1) Caja1Layout.setColumnStretch(1, 3) # Plot Caja2Layout.addWidget(self.canvas, 0, 0) # 1 fila, 4 columnas # Parametros a introducir Caja3Layout.addWidget(label1, 0, 0) Caja3Layout.addWidget(self.combo1, 0, 1) Caja3Layout.addWidget(label2, 1, 0) Caja3Layout.addWidget(self.combo2, 1, 1) Caja3Layout.addWidget(label3, 2, 0) Caja3Layout.addWidget(self.combo3, 2, 1) Caja3Layout.addWidget(label4, 3, 0) Caja3Layout.addWidget(self.combo4, 3, 1) Caja3Layout.addWidget(label5, 0, 2) Caja3Layout.addWidget(self.ed1, 0, 3) Caja3Layout.addWidget(label6, 1, 2) Caja3Layout.addWidget(self.ed2, 1, 3) Caja3Layout.addWidget(label7, 2, 2) Caja3Layout.addWidget(self.ed3, 2, 3) Caja3Layout.addWidget(label8, 3, 2) Caja3Layout.addWidget(self.ed4, 3, 3) # Bloque de texto Caja4Layout.addWidget(label9, 0, 0, 1, 1) Caja4Layout.addWidget(self.block, 1, 0, 1, 1) # Botones Caja5Layout.addWidget(btn, 0, 0) Caja5Layout.addWidget(btn2, 2, 0) Caja5Layout.addWidget(btn3, 0, 1, 3, 3) Caja5Layout.addWidget(btn4, 1, 0) def checkParameters(self): f1s = str(self.combo1.currentText()) f2s = str(self.combo2.currentText()) f3s = str(self.combo3.currentText()) f4s = str(self.combo4.currentText()) if f1s[:2] == 'Si': f1 = sigmoid elif f1s[0] == 'R': f1 = relu elif f1s[0] == 'L': f1 = lin elif f1s[:2] == 'So': f1 = soft if f2s[:2] == 'Si': f2 = sigmoid elif f2s[0] == 'R': f2 = relu elif f2s[0] == 'L': f2 = lin elif f2s[:2] == 'So': f2 = soft if f3s[:2] == 'Si': f3 = sigmoid elif f3s[0] == 'R': f3 = relu elif f3s[0] == 'L': f3 = lin elif f3s[:2] == 'So': f3 = soft if f4s[:2] == 'Qu': f4 = error elif f4s[0] == 'C': f4 = crossEntrop self.functions = [f1, f2, f3] self.erf = f4 self.NI = int(self.ed5.text()) self.NO = int(self.ed6.text()) self.NL = int(self.ed1.text()) self.NN = int(self.ed2.text()) self.lr = float(self.ed3.text()) self.reg = float(self.ed4.text()) print('The functions are: ', self.functions) print('The error calculus is: ', self.erf) print('The dimension of the inputs is: ', self.NI) print('The dimension of the outputs is: ', self.NO) print('The number of layers is: ', self.NL) print('The number of neurons per hidden layer is: ', self.NN) print('The learning rate is: ', self.lr) print('The reg parameter is: ', self.reg) def readInputs(self): fname = QFileDialog.getOpenFileName(self, 'Open File') Inputs_df = read_excel(fname[0]) self.Inputs = np.array(Inputs_df.iloc[:, :self.NI]) self.Outputs = np.array(Inputs_df.iloc[:, self.NI:]) print(self.Inputs.shape) print(self.Outputs.shape) if self.NO != self.Outputs.shape[1]: print( 'AVISO: EL NUMERO DE OUTPUTS NO COINCIDE CON LOS DATOS DADOS') def initNetwork(self): self.Layers = HiddenLayers(self.functions[0], self.functions[1], self.functions[2]) self.Layers.setlayers(self.Inputs.shape[1], self.Outputs.shape[1], self.NL, self.NN) print(self.Layers.f) def solveNetwork(self): self.block.clear() self.calculo = CalculoNeural( NeuralNetwork(self.Inputs, self.Layers.W, self.Layers.b, self.Layers.f, self.lr, self.Outputs), self.erf, self.reg) self.calculo.mySignal.connect( self.setText ) # Se conecta el objeto de señal con el slot de setText, definido abajo # Creamos las listas para guardar los errores self.IterPlot = [] self.ErrorPlot = [] self.calculo.PlotSignal.connect( self.setPlot ) # Lo mismo. Se conecta la señal PlotSignal con el slot de setPlot. self.calculo.start() def setText(self, text): # Este text es lo que se envia con la señal self.block.moveCursor(QTextCursor.End) self.block.insertPlainText('\n' + text) def setPlot(self, value, iteration): print('Iteración: ', iteration, ' Valor del error : ', value) if iteration > 1: self.IterPlot.append(iteration / 10000) self.ErrorPlot.append(value) self.figure.clear() ax = self.figure.add_subplot(111) if iteration > 10000: ax.plot(self.IterPlot, self.ErrorPlot, '-*r') plt.xlabel('Iteración') plt.ylabel('Error') plt.title('Error vs Iteración') self.canvas.draw()
def __init__(self, parent=None): """ Initialize the main window. :param parent: Parent window. """ super(Window, self).__init__(parent) # Figure instance to plot on self.figure = plt.figure() # create an axis self.ax = self.figure.add_subplot(111) # The Canvas Widget that displays the `figure` self.canvas = FigureCanvas(self.figure) # The Navigation widget self.toolbar = NavigationToolbar(self.canvas, self) # Refresh plot button self.button = QPushButton("Refresh plot") self.button.clicked.connect(self.plot) # NPP control self.npp_label = QLabel("Number of plot points [int]:") self.npp_box = QLineEdit(self) self.npp_box.setText("300") # Temperature control self.temp_label = QLabel("Temperature [K]: ") self.temp_box = QLineEdit(self) self.temp_box.setText("288.0") # Wavelength range control self.wl_lower_label = QLabel("Wavelength [m] from ") self.wl_box_lower = QLineEdit(self) self.wl_box_lower.setText("5.0e-6") self.wl_upper_label = QLabel(" to ") self.wl_box_upper = QLineEdit(self) self.wl_box_upper.setText("20.0e-6") # Setting up the layout of the Window self.hbox0 = QHBoxLayout() self.hbox0.addWidget(self.button) self.hbox0.addWidget(self.npp_label) self.hbox0.addWidget(self.npp_box) self.hbox0.addStretch(1) self.hbox1 = QHBoxLayout() self.hbox1.addWidget(self.temp_label) self.hbox1.addWidget(self.temp_box) self.hbox1.addStretch(1) self.hbox2 = QHBoxLayout() self.hbox2.addWidget(self.wl_lower_label) self.hbox2.addWidget(self.wl_box_lower) self.hbox2.addWidget(self.wl_upper_label) self.hbox2.addWidget(self.wl_box_upper) self.vbox = QVBoxLayout() self.vbox.addLayout(self.hbox0) self.vbox.addLayout(self.hbox1) self.vbox.addLayout(self.hbox2) # Finalize the layout self.layout = QVBoxLayout() self.layout.addWidget(self.toolbar) self.layout.addWidget(self.canvas) self.layout.addLayout(self.vbox) self.setLayout(self.layout)
def showUI(self): # Central widget and layout wid = QWidget() self.setCentralWidget(wid) grid = QGridLayout() wid.setLayout(grid) grid.setSpacing(5) # Creamos las cuatro cajas que vamos a usar Caja1 = QGroupBox('Dimensión de los datos del entrenamiento') Caja2 = QGroupBox('Área de la representación del error') Caja3 = QGroupBox('Parámetros de la red neuronal') Caja4 = QGroupBox('Zona de resultados') Caja5 = QGroupBox('Zona de botones') Caja1.setObjectName('PrimeraCaja') # Creamos los cuatro layouts. Son 4 Grids, al fin y al cabo. Caja1Layout = QGridLayout() Caja2Layout = QGridLayout() Caja3Layout = QGridLayout() Caja4Layout = QGridLayout() Caja5Layout = QGridLayout() Caja1.setLayout(Caja1Layout) Caja2.setLayout(Caja2Layout) Caja3.setLayout(Caja3Layout) Caja4.setLayout(Caja4Layout) Caja5.setLayout(Caja5Layout) grid.addWidget(Caja1, 0, 0, 1, 2) # 1 Fila - 2 Columnas grid.addWidget(Caja2, 1, 0, 1, 4) # 1 Fila - 4 Columnas grid.addWidget(Caja3, 2, 0, 1, 4) # 1 Fila - 2 Columnas grid.addWidget(Caja4, 0, 4, 2, 1) # 2 Filas - 1 Columna grid.addWidget(Caja5, 3, 0, 3, 4) # 3 Filas - 4 Columnas grid.setColumnStretch(0, 2) Caja1.setSizePolicy( QSizePolicy.Maximum, QSizePolicy.Maximum ) # Con esto se consigue dejar pequeña la mierda esa Caja3.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum) # Objects # Plot object self.figure = plt.figure(tight_layout=True) self.canvas = FigureCanvas(self.figure) self.canvas.setMinimumSize( 200, 200) # Esto hace que no se pueda hacer el widget to pequeño ax = self.figure.add_subplot(111) plt.xlabel('Iteración') plt.ylabel('Error') plt.title('Error vs Iteración') self.canvas.draw() # Labels for the functions label1 = QLabel('Input - H1') label2 = QLabel('H1 - H(-1)') label3 = QLabel('H(-1) - Output') label4 = QLabel('Error') label5 = QLabel('Layers') label6 = QLabel('Neurons') label7 = QLabel('Learning rate') label8 = QLabel('Regularization') label9 = QLabel('Resultados:') label10 = QLabel('Dimensión de inputs') label11 = QLabel('Dimensión de outputs') # Selectors for the functions self.combo1 = QComboBox(self) self.combo1.addItem('Sigmoid') self.combo1.addItem('ReLu') self.combo1.addItem('Linear') self.combo1.addItem('SoftMax') self.combo2 = QComboBox(self) self.combo2.addItem('Sigmoid') self.combo2.addItem('ReLu') self.combo2.addItem('Linear') self.combo2.addItem('SoftMax') self.combo3 = QComboBox(self) self.combo3.addItem('Sigmoid') self.combo3.addItem('ReLu') self.combo3.addItem('Linear') self.combo3.addItem('SoftMax') self.combo4 = QComboBox(self) self.combo4.addItem('Quadratic Error') self.combo4.addItem('Cross-Entropy function') # Botones btn = QPushButton('Cargar parámetros') btn.clicked.connect(self.checkParameters) btn2 = QPushButton('Crear Redes Neuronales') btn2.clicked.connect(self.initNetwork) btn3 = QPushButton('Resolver red') btn3.clicked.connect(self.solveNetwork) btn3.setStyleSheet( "font: bold; background-color: cyan; font-size: 26px; border-width: 100px; border-color: black" ) btn3.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) btn4 = QPushButton('Cargar Inputs y Outputs') btn4.clicked.connect(self.readInputs) # Edit Texts self.ed1 = QLineEdit(' ') self.ed2 = QLineEdit(' ') self.ed3 = QLineEdit(' ') self.ed4 = QLineEdit(' ') self.ed1.setText('1') self.ed2.setText('1') self.ed3.setText('1') self.ed4.setText('1') self.ed5 = QLineEdit('1') self.ed6 = QLineEdit('1') self.ed5.setMaximumWidth(30) self.ed6.setMaximumWidth(30) # Bloque de texto self.block = QTextEdit('Status:') self.block.moveCursor(QTextCursor.End) self.block.insertPlainText('\n' + 'Run for results') self.block.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) # Colocamos los objetos # Labels Caja1Layout.addWidget(label10, 0, 0) Caja1Layout.addWidget(label11, 1, 0) Caja1Layout.addWidget(self.ed5, 0, 1) Caja1Layout.addWidget(self.ed6, 1, 1) Caja1Layout.setColumnStretch(1, 3) # Plot Caja2Layout.addWidget(self.canvas, 0, 0) # 1 fila, 4 columnas # Parametros a introducir Caja3Layout.addWidget(label1, 0, 0) Caja3Layout.addWidget(self.combo1, 0, 1) Caja3Layout.addWidget(label2, 1, 0) Caja3Layout.addWidget(self.combo2, 1, 1) Caja3Layout.addWidget(label3, 2, 0) Caja3Layout.addWidget(self.combo3, 2, 1) Caja3Layout.addWidget(label4, 3, 0) Caja3Layout.addWidget(self.combo4, 3, 1) Caja3Layout.addWidget(label5, 0, 2) Caja3Layout.addWidget(self.ed1, 0, 3) Caja3Layout.addWidget(label6, 1, 2) Caja3Layout.addWidget(self.ed2, 1, 3) Caja3Layout.addWidget(label7, 2, 2) Caja3Layout.addWidget(self.ed3, 2, 3) Caja3Layout.addWidget(label8, 3, 2) Caja3Layout.addWidget(self.ed4, 3, 3) # Bloque de texto Caja4Layout.addWidget(label9, 0, 0, 1, 1) Caja4Layout.addWidget(self.block, 1, 0, 1, 1) # Botones Caja5Layout.addWidget(btn, 0, 0) Caja5Layout.addWidget(btn2, 2, 0) Caja5Layout.addWidget(btn3, 0, 1, 3, 3) Caja5Layout.addWidget(btn4, 1, 0)
def create_main_frame(self): self.main_frame = QWidget() self.dpi = 100 self.fig = Figure((10.0, 6.0), dpi=self.dpi, tight_layout=True) self.canvas = FigureCanvas(self.fig) self.canvas.setParent(self.main_frame) self.axes = self.fig.add_subplot(111) #self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame) self.textbox = QLineEdit() self.textbox.setMinimumWidth(100) self.set_button = QPushButton("&Set") self.set_button.clicked.connect(self.set_setpoint) self.show_ch1 = QCheckBox("Show &Channel1") self.show_ch1.setChecked(True) self.show_ch2 = QCheckBox("Show &Channel2") self.show_ch2.setChecked(True) self.show_ch3 = QCheckBox("Show &Channel3") self.show_ch3.setChecked(True) self.show_ch4 = QCheckBox("Show &Channel4") self.show_ch4.setChecked(True) self.show_ch5 = QCheckBox("Show &Channel4") self.show_ch5.setChecked(True) self.show_ch6 = QCheckBox("Show &Channel4") self.show_ch6.setChecked(True) slider_label = QLabel('Setpoint:') self.slider = QSlider(Qt.Horizontal) self.slider.setRange(0, 65535) self.slider.setValue(0) self.slider.setTracking(True) self.slider.setTickPosition(QSlider.TicksBothSides) hbox = QHBoxLayout() for w in [self.textbox, self.set_button, slider_label, self.slider]: hbox.addWidget(w) hbox.setAlignment(w, Qt.AlignVCenter) hbox2 = QHBoxLayout() for w in [self.show_ch1, self.show_ch2, self.show_ch3, self.show_ch4]: hbox2.addWidget(w) hbox2.setAlignment(w, Qt.AlignVCenter) vbox = QVBoxLayout() vbox.addWidget(self.canvas) #vbox.addWidget(self.mpl_toolbar) vbox.addLayout(hbox2) vbox.addLayout(hbox) hbox3 = QHBoxLayout() self.save_mat_button = QPushButton("&Save .mat") self.save_mat_button.clicked.connect(self.save_mat) self.start_button = QPushButton("&Start") self.start_button.clicked.connect(self.connect) hbox3.addWidget(self.start_button) hbox3.addWidget(self.save_mat_button) hbox3.setAlignment(w, Qt.AlignVCenter) vbox.addLayout(hbox3) hbox4 = QHBoxLayout() self.combo_box_ports = QComboBox() self.button_update_ports = QPushButton("&Update Ports") self.button_update_ports.clicked.connect(self.update_ports) hbox4.addWidget(self.combo_box_ports) hbox4.addWidget(self.button_update_ports) vbox.addLayout(hbox4) self.main_frame.setLayout(vbox) self.setCentralWidget(self.main_frame) self.info_message('Press Start to start plotting')
class window(QMainWindow): def __init__(self, parent=None): super(window, self).__init__(parent) self.setGeometry(550, 250, 850, 550) self.setWindowTitle('eDNA Fish Analyzer') #Menu bar File and Edit and activates the home function goHome = QAction("&Home", self) goHome.setShortcut("Ctrl+H") goHome.setStatusTip("Go to homepage") goHome.triggered.connect(self.home) extractAction = QAction('&Quit', self) extractAction.setShortcut('Ctrl+Q') extractAction.setStatusTip('leave the app') extractAction.triggered.connect(self.close_application) openEditor = QAction('&Editor', self) openEditor.setShortcut('Ctrl+E') openEditor.setStatusTip('Open Editor') openEditor.triggered.connect(self.editor) openFile = QAction('&Open File', self) openFile.setShortcut('Ctrl+O') openFile.setStatusTip('Open File') openFile.triggered.connect(self.file_open) saveFile = QAction('&Save File', self) saveFile.setShortcut('Ctrl+s') saveFile.setStatusTip('Save File') saveFile.triggered.connect(self.file_save) self.statusBar() mainMenu = self.menuBar() fileMenu = mainMenu.addMenu('&File') fileMenu.addAction(goHome) fileMenu.addAction(openFile) fileMenu.addAction(saveFile) fileMenu.addAction(extractAction) editorMenu = mainMenu.addMenu('&Edit') editorMenu.addAction(openEditor) self.figure = plt.figure(figsize=(6, 4), dpi=100) self.canvas = FigureCanvas(self.figure) self.canvas.move(230, 90) self.canvas.setParent(self) self.home() #This function will edit files def editor(self): self.textEdit = QTextEdit() self.setCentralWidget(self.textEdit) #This function will save written files def file_save(self): name, _ = QFileDialog.getSaveFileName( self, 'Save File', options=QFileDialog.DontUseNativeDialog) file = open(name, 'w') text = self.textEdit.toPlainText() file.write(text) file.close() #This function will open selected files def file_open(self): self.fileName, _ = QFileDialog.getOpenFileName( self, 'Open File', options=QFileDialog.DontUseNativeDialog) self.myTextBox.setText(self.fileName) if self.fileName: return self.fileName #This function controles where all the buttons, checkboxes, labels, etc are located and add them to different functions def home(self): btn = QPushButton('Load', self) btn.clicked.connect(self.file_open) btn.resize(btn.sizeHint()) btn.move(10, 50) self.btn1 = QPushButton('Run', self) self.btn1.resize(btn.sizeHint()) self.btn1.move(20, 470) self.btn1.clicked.connect(self.pipeline) self.checkBox2 = QCheckBox("Filtering:", self) self.checkBox2.setChecked(False) self.checkBox2.move(10, 120) self.checkBox1 = QCheckBox("Adapters", self) self.checkBox1.setChecked(False) self.checkBox1.move(110, 80) self.checkBox = QCheckBox("Fastq file", self) self.checkBox.setChecked(False) self.checkBox.move(10, 80) self.checkBox = QCheckBox("Cluster filtering:", self) self.checkBox.setChecked(False) self.checkBox.resize(150, 25) self.checkBox.move(10, 255) box = self.myTextBox = QTextEdit(self) box.resize(732, 25) box.move(100, 50) self.box1 = QLineEdit(self) self.box1.resize(50, 25) self.box1.move(170, 150) self.box2 = QLineEdit(self) self.box2.resize(50, 25) self.box2.move(170, 180) self.box3 = QLineEdit(self) self.box3.resize(50, 25) self.box3.move(170, 220) self.box4 = QLineEdit(self) self.box4.resize(100, 25) self.box4.move(10, 345) self.box5 = QLineEdit(self) self.box5.resize(50, 25) self.box5.move(170, 280) label1 = QLabel(self) label1.setText("Sequence divergence") label1.resize(150, 25) label1.move(10, 220) label2 = QLabel(self) label2.setText("Read length cut-off") label2.resize(150, 25) label2.move(30, 150) label3 = QLabel(self) label3.setText("Q-score cut-off") label3.resize(150, 25) label3.move(30, 180) label4 = QLabel(self) label4.setText("Database:") label4.resize(200, 25) label4.move(10, 320) label6 = QLabel(self) label6.setText("OTU cut-off") label6.resize(150, 22) label6.move(31, 280) self.progress = QProgressBar(self) self.progress.setGeometry(227, 500, 275, 20) #This function will run the functions in the selected order. Dependent on wich inputs you gave in the GUI. It will also display the progressbar. def pipeline(self): self.completed = 0 if self.checkBox1.isChecked() and self.checkBox.isChecked( ) and self.checkBox2.isChecked(): while self.completed < 100: start = time.time() self.Remove_tmp() self.completed += 1.0 self.progress.setValue(self.completed) self.Filtlong() self.completed += 5.0 self.progress.setValue(self.completed) self.Fastq_omzetter() self.completed += 4.0 self.progress.setValue(self.completed) self.Porechop() self.completed += 25.0 self.progress.setValue(self.completed) self.Clustering() self.completed += 25.0 self.progress.setValue(self.completed) self.splitter() self.completed += 5.0 self.progress.setValue(self.completed) self.Singleton() self.completed += 5.0 self.progress.setValue(self.completed) self.local_Blast() self.completed += 20.0 self.progress.setValue(self.completed) self.hitter() self.completed += 5.0 self.progress.setValue(self.completed) self.listmk() self.completed += 5.0 self.progress.setValue(self.completed) end = time.time() end1 = end / 60 start1 = start / 60 print(end1 - start1) self.plot() elif self.checkBox1.isChecked(): while self.completed < 100: self.Remove_tmp() self.completed += 5.0 self.progress.setValue(self.completed) self.Porechop() self.completed += 30.0 self.progress.setValue(self.completed) self.Clustering() self.completed += 30.0 self.progress.setValue(self.completed) self.splitter() self.completed += 5.0 self.progress.setValue(self.completed) self.local_Blast() self.completed += 20.0 self.progress.setValue(self.completed) self.hitter() self.completed += 5.0 self.progress.setValue(self.completed) self.listmk() self.completed += 5.0 self.progress.setValue(self.completed) self.plot() elif self.checkBox.isChecked(): self.Remove_tmp() self.local_Blast() else: self.Clustering() self.splitter() self.local_Blast() self.hitter() self.listmk() self.plot() #This function will create a plot with the frequency results def plot(self): file = open("Names.txt", "r") Taxa = file.readlines() d = defaultdict(int) acession = re.compile("[A-Z]{2}_?[0-9]{6}\.1") for item in Taxa: for word in item.split("\n"): d[word] += 1 del d[''] ax = self.figure.add_subplot(111) ax.set_title("eDNA classification results") ax.set_ylabel("Frequency") ax.set_xlabel("Organisme") ax.bar(range(len(d)), list(d.values()), align="center") #ax.xticks(range(len(d)), list(d.keys()), rotation="50") self.canvas.draw() def style_choice(self, text): self.styleChoice.setText(text) QApplication.setStyle(QStyleFactory.create(text)) #This function will call on filtlong on the command line to set a threshhold for read lenght and for def Filtlong(self): file = open(self.fileName, 'r') file2 = file.readlines() result = open('inputReads.fastq', 'w') for i in file2: result.write(i) result.close() length = self.box1.text() score = self.box2.text() path = "Testfasta.fasta" os.system('filtlong --min_mean_q ' + score + ' --min_length ' + length + ' inputReads.fastq > output.fastq') #This function turns a fastq file to an fasta file def Fastq_omzetter(self): # works from io import StringIO File = open("output.fastq", "r") self.File2 = open("Testfasta.fasta", "w") handle = StringIO("") SeqIO.convert(File, "fastq", handle, "fasta") self.File2.write(handle.getvalue()) #This function will call on Porchop on the commandline to trimm the adapters from the reads def Porechop(self): #works InputPore = "Testfasta.fasta" #str(self.fileName) #OutputPore = "output_reads.fasta" self.command_line = [ "porechop", "-i", InputPore, "-o", "output_reads.fasta" ] subprocess.call(self.command_line) #self.Pop_up2() #This function will call on VSearch on the commandline to cluster the reads into OTU's def Clustering(self): #works ID = str(self.box3.text()) Input = "output_reads.fasta" # str(self.fileName) self.command_line = [ "vsearch", "-cluster_fast", Input, "-id", ID, "-consout", "Test.fasta" ] subprocess.call(self.command_line) #This function splits the consencus clusters in single FASTA files def splitter(self): #works i = 0 with open("Test.fasta", "r") as file: data = file.read() seqs1 = re.split(">", data) for seqs2 in seqs1: filename = "result" + str(i) result = open( "/home/ruben/PycharmProjects/Stage_Wagenigen/Project_eDNA/Fasta/" + filename + ".fasta", "w") result.write(">" + seqs2) i += 1 #This function will filter out the clusters with 3 or less sequences, tis option can be selected at the GUI def Singleton(self): src_dict = "/home/ruben/PycharmProjects/Stage_Wagenigen/Project_eDNA/Fasta/" # Specify base directory result_dict = "/home/ruben/PycharmProjects/Stage_Wagenigen/Project_eDNA/Singletons/" rginput = "(seq=)[1-" + str(self.box5.text()) + "]\n" print(rginput) reseqs = re.compile(rginput) print(reseqs) self.result = seqs = [] for filename in os.listdir(src_dict): path = os.path.join(src_dict, filename) x = open(path, "r") regex = re.findall(reseqs, x.read()) print(seqs) if regex: shutil.move(path, result_dict) print("moved", path) else: seqs.append(filename) x.close() #This function will run a BLAST with the found concensus clusters against the selected local blast database def local_Blast(self): #works l = 1 database = self.box4.text() for seq in self.result: l += 1 command_line = [ "blastn", "-query", "/home/ruben/PycharmProjects/Stage_Wagenigen/Project_eDNA/Fasta/" + seq, "-out", "/home/ruben/PycharmProjects/Stage_Wagenigen/Project_eDNA/Results/" + seq, "-evalue", "0.00001", "-num_alignments", "1", "-task", "megablast", "-num_threads", "4", "-db", "/home/ruben/PycharmProjects/Stage_Wagenigen/Project_eDNA/Databases/" + database ] subprocess.call(command_line) #This function will remove all temporaly files if at the start of a new analisis, so that the resultst will not overlap def Remove_tmp(self): #works Fasta = '/home/ruben/PycharmProjects/Stage_Wagenigen/Project_eDNA/Fasta/' Results = '/home/ruben/PycharmProjects/Stage_Wagenigen/Project_eDNA/Results/' best_hits = '/home/ruben/PycharmProjects/Stage_Wagenigen/Project_eDNA/90%/' Singletons = "/home/ruben/PycharmProjects/Stage_Wagenigen/Project_eDNA/Singletons/" for the_file in os.listdir(Fasta): file_path = os.path.join(Fasta, the_file) try: if os.path.isfile(file_path): os.unlink(file_path) except Exception as e: print(e) for the_file in os.listdir(Results): file_path = os.path.join(Results, the_file) try: if os.path.isfile(file_path): os.unlink(file_path) except Exception as e: print(e) for the_file in os.listdir(best_hits): file_path = os.path.join(best_hits, the_file) try: if os.path.isfile(file_path): os.unlink(file_path) except Exception as e: print(e) for the_file in os.listdir(Singletons): file_path = os.path.join(Singletons, the_file) try: if os.path.isfile(file_path): os.unlink(file_path) except Exception as e: print(e) #This function searches for the results with an identity score of higer then 90. If there are H**o sapiens found that hit for 90% he will filter those out def hitter(self): self.lijst = List = [] src_dict = "/home/ruben/PycharmProjects/Stage_Wagenigen/Project_eDNA/Results/" # Specify base directory result_dict = "/home/ruben/PycharmProjects/Stage_Wagenigen/Project_eDNA/90%/" pattern = re.compile( "\(9\d%\)") # CPatter to search for 90% and higher Name_organism = re.compile( ">\s[A-Z]{1,}_?[0-9]{5,}\.[0-9]\s[A-Z][a-z]{2,}\s[a-z]{2,}" ) # CPatter to search for Name Homo_sapiens = re.compile( ">\s[A-Z]{1,}_?[0-9]{5,}\.[0-9]\sHomo\ssapiens" ) # CPattern to search for acession and H**o sapiens for filename in os.listdir(src_dict): path = os.path.join(src_dict, filename) x = open(path, "r") y = open(path, "r") z = open(path, "r") regex = re.findall(pattern, x.read()) regex1 = re.findall(Name_organism, y.read()) regex2 = re.findall(Homo_sapiens, z.read()) if not regex: print("No hit!") else: print("Hit!") if not regex2: shutil.move(path, result_dict) print("moved", path) List.append(regex1) x.close() y.close() z.close() #This function makes a list with the organismes def listmk(self): #naar cvs file zetten file = open("Names.txt", "w") with open('Names.txt', 'a') as f: for item in self.lijst: print(item) f.write( str(item).replace("]", "").replace("[", "").replace( "'", "").replace(">", "")) f.write("\n") self.Pop_up() #This function will give a pop-up message if the analysis is completed def Pop_up(self): popup = QMessageBox.about(self, "Process", "Analysis is done!") return popup def Pop_up1(self): popup = QMessageBox.about(self, "Process", "Fasta is done") return popup def Pop_up2(self): popup = QMessageBox.about(self, "Process", "Adapter trimming is done") return popup def Pop_up3(self): popup = QMessageBox.about(self, "Process", "Nothing has happend") return popup def close_application(self): choice = QMessageBox.question(self, 'Message', "Are you sure to quit?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if choice == QMessageBox.Yes: print('quit application') sys.exit() else: pass
def create_main_frame(self): self.main_frame = QWidget() # Create the mpl Figure and FigCanvas objects. # 5x4 inches, 100 dots-per-inch # self.dpi = 100 self.fig = Figure((5.0, 4.0), dpi=self.dpi) self.canvas = FigureCanvas(self.fig) self.canvas.setParent(self.main_frame) # Since we have only one plot, we can use add_axes # instead of add_subplot, but then the subplot # configuration tool in the navigation toolbar wouldn't # work. # self.axes = self.fig.add_subplot(111) # Bind the 'pick' event for clicking on one of the bars # self.canvas.mpl_connect('pick_event', self.on_pick) # Create the navigation toolbar, tied to the canvas # self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame) # Other GUI controls # self.textbox = QLineEdit() self.textbox.setMinimumWidth(200) self.textbox.editingFinished.connect(self.on_draw) self.draw_button = QPushButton("&Draw") self.draw_button.clicked.connect(self.on_draw) self.grid_cb = QCheckBox("Show &Grid") self.grid_cb.setChecked(False) self.grid_cb.stateChanged.connect(self.on_draw) # int slider_label = QLabel('Bar width (%):') self.slider = QSlider(Qt.Horizontal) self.slider.setRange(1, 100) self.slider.setValue(20) self.slider.setTracking(True) self.slider.setTickPosition(QSlider.TicksBothSides) self.slider.valueChanged.connect(self.on_draw) # int # # Layout with box sizers # hbox = QHBoxLayout() for w in [self.textbox, self.draw_button, self.grid_cb, slider_label, self.slider]: hbox.addWidget(w) hbox.setAlignment(w, Qt.AlignVCenter) vbox = QVBoxLayout() vbox.addWidget(self.mpl_toolbar) vbox.addWidget(self.canvas) vbox.addLayout(hbox) self.main_frame.setLayout(vbox) self.setCentralWidget(self.main_frame)
def initTabs(self): self.tabs.setEnabled(True) self.tabs.setCurrentIndex(0) outputNames = self.model.getOutputNames() # Optimization Setup self.output_combo.setEnabled(True) self.output_combo.clear() self.output_combo.addItems(outputNames) self.mean_radio.setChecked(True) self.betaDoubleSpin.setValue(0) self.alphaDoubleSpin.setValue(0.5) self.secondarySolver_combo.setCurrentIndex(0) # Outputs self.outputs_table.blockSignals(True) self.outputs_table.setColumnCount(2) self.outputs_table.setRowCount(len(outputNames)) self.useAsConstraint = [False] * len(outputNames) self.useAsDerivative = [False] * len(outputNames) for r in range(len(outputNames)): # radio = QRadioButton() # if r == 0: # radio.setChecked(True) # radio.setProperty('row', r) # radio.toggled.connect(self.setObjectiveFunction) # self.outputs_table.setCellWidget(r, 0, radio) combobox = QComboBox() combobox.addItems([ ouuSetupFrame.NotUsedText, ouuSetupFrame.ObjFuncText, ouuSetupFrame.ConstraintText, ouuSetupFrame.DerivativeText ]) if r == 0: combobox.setCurrentIndex(1) self.outputs_table.setCellWidget(r, 0, combobox) item = QTableWidgetItem(outputNames[r]) self.outputs_table.setItem(r, 1, item) # item = QTableWidgetItem() # item.setCheckState(QtCore.Qt.Unchecked) # self.outputs_table.setItem(r, 2, item) # if r == 0: # flags = item.flags() # flags &= (~QtCore.Qt.ItemIsEnabled) # item.setFlags(flags) self.outputs_table.resizeColumnsToContents() self.outputs_table.blockSignals(False) # UQ Setup self.compressSamples_chk.setChecked(False) self.compressSamples_chk.setEnabled(False) self.scenariosCalculated = False self.scenarioSelect_static.setEnabled(False) self.scenarioSelect_combo.setEnabled(False) self.scenarioSelect_combo.clear() self.x4SampleScheme_combo.setCurrentIndex(0) self.x4SampleSize_label.setText('Sample Size') self.x4SampleSize_spin.setValue(5) self.x4SampleSize_spin.setRange(5, 1000) self.x4RSMethod_check.setChecked(False) # Launch/Progress self.run_button.setEnabled( True) # TO DO: disable until inputs are validated self.bestValue_table.setColumnCount(1) self.bestValue_table.clearContents() # Plots self.plots_group = QGroupBox() self.plotsLayout = QVBoxLayout() self.plots_group.setLayout(self.plotsLayout) self.progressScrollArea.setMinimumHeight(150) self.progressScrollArea.setWidget(self.plots_group) self.plots_group.setMinimumHeight(150) self.objFig = Figure(figsize=(400, 200), dpi=72, facecolor=(1, 1, 1), edgecolor=(0, 0, 0), tight_layout=True) self.objCanvas = FigureCanvas(self.objFig) self.objFigAx = self.objFig.add_subplot(111) self.objFigAx.set_title('OUU Progress') self.objFigAx.set_ylabel('Objective') self.objFigAx.set_xlabel('Iteration') self.objLine = None self.plotsLayout.addWidget(self.objCanvas) self.objCanvas.setParent(self.plots_group) self.inputPlots = [] self.objXPoints = [] self.objYPoints = [] self.objPlotPoints = None
class KCMainWindow(Ui_MainWindow): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.spin_updater_enabled = True self.xcalib_enabled = True def setupUi(self, MainWindow): super().setupUi(MainWindow) self.spinR_G.setValue(1.0) self.spinG_G.setValue(1.0) self.spinB_G.setValue(1.0) self.sliderR_G.valueChanged['int'].connect( self._spin_gammaexp_updater(self.spinR_G)) self.spinR_G.valueChanged['double'].connect( self._slider_gammalog_updater(self.sliderR_G)) self.sliderG_G.valueChanged['int'].connect( self._spin_gammaexp_updater(self.spinG_G)) self.spinG_G.valueChanged['double'].connect( self._slider_gammalog_updater(self.sliderG_G)) self.sliderB_G.valueChanged['int'].connect( self._spin_gammaexp_updater(self.spinB_G)) self.spinB_G.valueChanged['double'].connect( self._slider_gammalog_updater(self.sliderB_G)) self.spinR_B.valueChanged['int'].connect(self.do_xcalib) self.spinR_C.valueChanged['int'].connect(self.do_xcalib) self.spinR_G.valueChanged['double'].connect(self.do_xcalib) self.spinG_B.valueChanged['int'].connect(self.do_xcalib) self.spinG_C.valueChanged['int'].connect(self.do_xcalib) self.spinG_G.valueChanged['double'].connect(self.do_xcalib) self.spinB_B.valueChanged['int'].connect(self.do_xcalib) self.spinB_C.valueChanged['int'].connect(self.do_xcalib) self.spinB_G.valueChanged['double'].connect(self.do_xcalib) # a figure instance to plot on self.figure = Figure() self.ax = None # it takes the `figure` instance as a parameter to __init__ self.canvas = FigureCanvas(self.figure) self.canvas.setMinimumSize(QtCore.QSize(200, 100)) self.plotLayout.addWidget(self.canvas) self.resetButton.clicked.connect(self.on_resetButton_clicked) def _spin_gammaexp_updater(self, spin): def f(gamma): if self.spin_updater_enabled: spin.setValue(gammaexp(gamma)) return f def _slider_gammalog_updater(self, slider): def f(gamma): self.spin_updater_enabled = False slider.setValue(gammalog(gamma)) self.spin_updater_enabled = True return f def update_graph(self, data): if not self.ax: self.ax = self.figure.add_subplot(111) self.ax.clear() self.ax.set_xlim(0, 1) self.ax.set_ylim(0, 1) self.figure.tight_layout() n, _ = data.shape scale = math.floor(65535 * (n - 1) / n) x = np.linspace(0, 1, n) self.ax.plot(x, data[:, 0] / scale, color="red") self.ax.plot(x, data[:, 1] / scale, color="green") self.ax.plot(x, data[:, 2] / scale, color="blue") self.canvas.draw() def do_xcalib(self): if self.xcalib_enabled: textcommands = [] textcommands.append(reset_xcalib(self.spinScreen.value())) try: c, output = set_xcalib( self.spinScreen.value(), self.spinR_B.value(), self.spinR_C.value(), self.spinR_G.value(), self.spinG_B.value(), self.spinG_C.value(), self.spinG_G.value(), self.spinB_B.value(), self.spinB_C.value(), self.spinB_G.value(), ) textcommands.append(c) self.update_graph(output) self.textBrowser.setText("\n".join(textcommands)) except ValueError: pass def on_resetButton_clicked(self): self.xcalib_enabled = False self.spinR_B.setValue(0) self.spinG_B.setValue(0) self.spinB_B.setValue(0) self.spinR_C.setValue(100) self.spinG_C.setValue(100) self.spinB_C.setValue(100) self.spinR_G.setValue(1.0) self.spinG_G.setValue(1.0) self.spinB_G.setValue(1.0) self.xcalib_enabled = True textcommand = reset_xcalib(self.spinScreen.value()) self.ax.clear() self.canvas.draw() self.textBrowser.setText(textcommand)
class ouuSetupFrame(_ouuSetupFrame, _ouuSetupFrameUI): plotSignal = QtCore.pyqtSignal(dict) NotUsedText = "Not used" ObjFuncText = "Objective Function" ConstraintText = "Inequality Constraint" DerivativeText = "Derivative" def __init__(self, dat=None, parent=None): super(ouuSetupFrame, self).__init__(parent=parent) self.setupUi(self) self.dat = dat self.filesDir = '' self.scenariosCalculated = False self.result = None self.useAsConstraint = None self.plotsToUpdate = [0] self.objLine = None # Refresh table self.refresh() self.plotSignal.connect(self.addPlotValues) self.setFixed_button.setEnabled(False) self.setX1_button.setEnabled(False) self.setX1d_button.setEnabled(False) self.setX2_button.setEnabled(False) self.setX3_button.setEnabled(False) self.setX4_button.setEnabled(False) self.input_table.setColumnHidden(3, True) # Hide scale column self.modelFile_edit.clear() self.modelFile_radio.setChecked(True) self.uqTab = self.tabs.widget(2) self.tabs.removeTab(2) self.tabs.setCurrentIndex(0) self.tabs.setEnabled(False) self.output_label.setHidden(True) self.output_combo.setHidden(True) self.output_combo.setEnabled(False) self.mean_radio.setChecked(True) self.betaDoubleSpin.setValue(0) self.alphaDoubleSpin.setValue(0.5) self.primarySolver_combo.setEnabled(False) self.secondarySolver_combo.setCurrentIndex(0) self.z3_table.setRowCount(1) self.compressSamples_chk.setEnabled(False) self.calcScenarios_button.setEnabled(False) self.scenarioSelect_static.setEnabled(False) self.scenarioSelect_combo.setEnabled(False) self.z4NewSample_radio.setChecked(True) self.x4SampleScheme_combo.setCurrentIndex(0) self.x4SampleSize_label.setText('Sample Size') self.x4SampleSize_spin.setValue(5) self.x4SampleSize_spin.setRange(5, 1000) self.x4FileBrowse_button.setEnabled(False) self.x4SampleScheme_combo.clear() self.x4SampleScheme_combo.addItems([ SamplingMethods.getFullName(SamplingMethods.LH), SamplingMethods.getFullName(SamplingMethods.LPTAU), SamplingMethods.getFullName(SamplingMethods.FACT) ]) self.x4RSMethod_check.setChecked(False) self.z4_table.setEnabled(False) self.z4_table.setRowCount(1) self.z4SubsetSize_label.setEnabled(False) self.z4SubsetSize_spin.setEnabled(False) self.run_button.setEnabled(True) self.summary_group.setMaximumHeight(250) self.progress_group.setMaximumHeight(250) self.setWindowTitle('Optimization Under Uncertainty (OUU)') # Connect signals self.node_radio.toggled.connect(self.chooseNode) self.node_combo.currentIndexChanged.connect(self.loadNodeData) self.modelFile_radio.toggled.connect(self.chooseModel) self.modelFileBrowse_button.clicked.connect(self.loadModelFileData) self.input_table.typeChanged.connect(self.setCounts) #self.input_table.typeChanged.connect(self.managePlots) #self.input_table.typeChanged.connect(self.manageBestValueTable) self.setFixed_button.clicked.connect(self.setFixed) self.setX1_button.clicked.connect(self.setX1) self.setX1d_button.clicked.connect(self.setX1d) self.setX2_button.clicked.connect(self.setX2) self.setX3_button.clicked.connect(self.setX3) self.setX4_button.clicked.connect(self.setX4) self.z4NewSample_radio.toggled.connect(self.chooseZ4NewSample) self.z4LoadSample_radio.toggled.connect(self.chooseZ4LoadSample) self.x4SampleSize_spin.valueChanged.connect(self.setZ4RS) self.z4SubsetSize_spin.valueChanged.connect(self.setZ4RS) self.x3FileBrowse_button.clicked.connect(self.loadX3Sample) self.compressSamples_chk.toggled.connect(self.activateCompressSample) self.calcScenarios_button.clicked.connect(self.calcScenarios) self.x4SampleScheme_combo.currentIndexChanged.connect(self.setX4Label) self.x4FileBrowse_button.clicked.connect(self.loadX4Sample) self.x4RSMethod_check.toggled.connect(self.showZ4Subset) self.run_button.clicked.connect(self.analyze) self.z3_table.cellChanged.connect(self.z3TableCellChanged) self.z4_table.cellChanged.connect(self.z4TableCellChanged) self.progressScrollArea.verticalScrollBar().valueChanged.connect( self.scrollProgressPlots) def freeze(self): QApplication.setOverrideCursor(QCursor(QtCore.Qt.WaitCursor)) def semifreeze(self): QApplication.setOverrideCursor(QCursor(QtCore.Qt.BusyCursor)) def unfreeze(self): QApplication.restoreOverrideCursor() def refresh(self): if self.dat is not None: nodes = sorted(self.dat.flowsheet.nodes.keys()) items = ['Select node'] items.extend(nodes) items.append('Full flowsheet') self.node_combo.clear() self.node_combo.addItems(items) self.node_radio.setChecked(True) else: self.node_radio.setEnabled(False) self.node_combo.setEnabled(False) self.modelFile_radio.setChecked(True) self.input_table.clearContents() self.input_table.setRowCount(0) self.modelFile_edit.clear() self.output_combo.clear() self.bestValue_table.clearContents() self.bestValue_table.setRowCount(2) self.clearPlots() def chooseNode(self, value): if value: self.node_combo.setEnabled(True) self.modelFile_edit.setEnabled(False) self.modelFileBrowse_button.setEnabled(False) def chooseModel(self, value): if value: self.node_combo.setEnabled(False) self.modelFile_edit.setEnabled(True) self.modelFileBrowse_button.setEnabled(True) def loadNodeData(self): nodeName = self.node_combo.currentText() if nodeName in ['', 'Select node']: return if nodeName == 'Full flowsheet': self.model = flowsheetToUQModel(self.dat.flowsheet) else: node = self.dat.flowsheet.nodes[nodeName] self.model = nodeToUQModel(nodeName, node) self.input_table.init(self.model, InputPriorTable.OUU) self.setFixed_button.setEnabled(True) self.setX1_button.setEnabled(True) self.setX1d_button.setEnabled(True) self.setX2_button.setEnabled(True) self.setX3_button.setEnabled(True) self.setX4_button.setEnabled(True) self.initTabs() self.setCounts() def loadModelFileData(self): if platform.system() == 'Windows': allFiles = '*.*' else: allFiles = '*' fname, _ = QFileDialog.getOpenFileName( self, 'Open Model File', self.filesDir, 'Model files (*.in *.dat *.psuade *.filtered);;All files (%s)' % allFiles) if fname == '': return self.filesDir, name = os.path.split(fname) self.modelFile_edit.setText(fname) self.model = LocalExecutionModule.readSampleFromPsuadeFile(fname) self.model = self.model.model self.input_table.init(self.model, InputPriorTable.OUU) self.setFixed_button.setEnabled(True) self.setX1_button.setEnabled(True) self.setX1d_button.setEnabled(True) self.setX2_button.setEnabled(True) self.setX3_button.setEnabled(True) self.setX4_button.setEnabled(True) self.initTabs() self.setCounts() ##### Brenda: Start here! ##### def getSampleFileData(self): if platform.system() == 'Windows': allFiles = '*.*' else: allFiles = '*' fname, _ = QFileDialog.getOpenFileName( self, 'Open Sample File', self.filesDir, "Psuade Simple Files (*.smp);;CSV (Comma delimited) (*.csv);;All files (%s)" % allFiles) if fname == '': return (None, None) self.filesDir, name = os.path.split(fname) try: if fname.endswith('.csv'): data = LocalExecutionModule.readDataFromCsvFile( fname, askForNumInputs=False) else: data = LocalExecutionModule.readDataFromSimpleFile( fname, hasColumnNumbers=False) data = data[0] return (fname, data) except: import traceback traceback.print_exc() QMessageBox.critical( self, 'Incorrect format', 'File does not have the correct format! Please consult the users manual about the format.' ) return (None, None) def loadX3Sample(self): fname, data = self.getSampleFileData() if fname is None: return numInputs = data.shape[1] M3 = len(self.input_table.getUQDiscreteVariables()[0]) if numInputs != M3: QMessageBox.warning( self, "Number of variables don't match", 'The number of variables from the file (%d) does not match the number of Z3 discrete variables (%d). You will not be able to perform analysis until this is corrected.' % (numInputs, M3)) else: self.compressSamples_chk.setEnabled(True) self.loadTable(self.z3_table, data) def loadTable(self, table, data): numSamples = data.shape[0] numInputs = data.shape[1] table.setRowCount(numSamples + 1) for r in range(numSamples): for c in range(numInputs): item = QTableWidgetItem('%g' % data[r, c]) table.setItem(r, c, item) table.resizeColumnsToContents() def z3TableCellChanged(self, row, col): self.randomVarTableCellChanged(self.z3_table, row, col) self.compressSamples_chk.setEnabled(True) def z4TableCellChanged(self, row, col): self.randomVarTableCellChanged(self.z4_table, row, col) def randomVarTableCellChanged(self, table, row, col): if row == table.rowCount() - 1: table.setRowCount(table.rowCount() + 1) def writeTableToFile(self, table, fileName, numCols): names = {self.z3_table: 'Z3', self.z4_table: 'Z4'} assert (numCols <= table.columnCount()) values = [] for r in range(table.rowCount()): rowVals = [] rowHasData = False rowFull = True for c in range(numCols): item = table.item(r, c) if not item: rowFull = False else: text = item.text() if not text: rowFull = False else: try: rowVals.append(float(text)) rowHasData = True except ValueError: rowFull = False if not rowFull and rowHasData: break if rowFull: values.append(rowVals) if not values or (rowHasData and not rowFull): QMessageBox.warning( self, "Missing data", 'The %s table is missing required data!' % names[table]) return False # Failed LocalExecutionModule.writeSimpleFile(fileName, values, rowLabels=False) return True def activateCompressSample(self, on): if on: rowCount = 0 for r in range(self.z3_table.rowCount()): for c in range(self.z3_table.columnCount()): rowFull = True item = self.z3_table.item(r, c) if item: text = item.text() if not text: rowFull = False break try: float(text) except ValueError: rowFull = False break else: break if rowFull: rowCount += 1 if rowCount < 100: QMessageBox.warning( self, "Not enough samples in file", 'The file requires at least 100 samples for compression.') self.compressSamples_chk.setChecked(False) return self.calcScenarios_button.setEnabled(on) if self.scenariosCalculated: self.scenarioSelect_static.setEnabled(True) self.scenarioSelect_combo.setEnabled(True) def calcScenarios(self): self.freeze() self.writeTableToFile( self.z3_table, 'z3Samples.smp', len(self.input_table.getUQDiscreteVariables()[0])) self.scenarioFiles = OUU.compress('z3Samples.smp') if self.scenarioFiles is not None: self.scenarioSelect_combo.clear() for i, n in enumerate(sorted(self.scenarioFiles.keys())): self.scenarioSelect_combo.addItem(str(n)) self.scenarioSelect_combo.setItemData( i, '%d bins per dimension' % self.scenarioFiles[n][1], QtCore.Qt.ToolTipRole) self.scenarioSelect_static.setEnabled(True) self.scenarioSelect_combo.setEnabled(True) self.scenariosCalculated = True self.unfreeze() def loadX4Sample(self): fname, inData = self.getSampleFileData() if fname is None: return numInputs = inData.shape[1] numSamples = inData.shape[0] self.z4SubsetSize_spin.setMaximum(numSamples) self.z4SubsetSize_spin.setValue(min(numSamples, 100)) M4 = len(self.input_table.getContinuousVariables()[0]) if numInputs != M4: QMessageBox.warning( self, "Number of variables don't match", 'The number of input variables from the file (%d) does not match the number of Z4 continuous variables (%d). You will not be able to perform analysis until this is corrected.' % (numInputs, M4)) else: self.loadTable(self.z4_table, inData) def setX4Label(self): method = self.x4SampleScheme_combo.currentText() if method in [ SamplingMethods.getFullName(SamplingMethods.LH), SamplingMethods.getFullName(SamplingMethods.LPTAU) ]: self.x4SampleSize_label.setText('Sample Size') numM1 = len(self.input_table.getPrimaryVariables()[0]) self.x4SampleSize_spin.setRange(numM1 + 1, 1000) self.x4SampleSize_spin.setValue(numM1 + 1) self.x4SampleSize_spin.setSingleStep(1) elif method == SamplingMethods.getFullName(SamplingMethods.FACT): self.x4SampleSize_label.setText('Number of Levels') self.x4SampleSize_spin.setRange(3, 100) self.x4SampleSize_spin.setValue(3) self.x4SampleSize_spin.setSingleStep(2) def initTabs(self): self.tabs.setEnabled(True) self.tabs.setCurrentIndex(0) outputNames = self.model.getOutputNames() # Optimization Setup self.output_combo.setEnabled(True) self.output_combo.clear() self.output_combo.addItems(outputNames) self.mean_radio.setChecked(True) self.betaDoubleSpin.setValue(0) self.alphaDoubleSpin.setValue(0.5) self.secondarySolver_combo.setCurrentIndex(0) # Outputs self.outputs_table.blockSignals(True) self.outputs_table.setColumnCount(2) self.outputs_table.setRowCount(len(outputNames)) self.useAsConstraint = [False] * len(outputNames) self.useAsDerivative = [False] * len(outputNames) for r in range(len(outputNames)): # radio = QRadioButton() # if r == 0: # radio.setChecked(True) # radio.setProperty('row', r) # radio.toggled.connect(self.setObjectiveFunction) # self.outputs_table.setCellWidget(r, 0, radio) combobox = QComboBox() combobox.addItems([ ouuSetupFrame.NotUsedText, ouuSetupFrame.ObjFuncText, ouuSetupFrame.ConstraintText, ouuSetupFrame.DerivativeText ]) if r == 0: combobox.setCurrentIndex(1) self.outputs_table.setCellWidget(r, 0, combobox) item = QTableWidgetItem(outputNames[r]) self.outputs_table.setItem(r, 1, item) # item = QTableWidgetItem() # item.setCheckState(QtCore.Qt.Unchecked) # self.outputs_table.setItem(r, 2, item) # if r == 0: # flags = item.flags() # flags &= (~QtCore.Qt.ItemIsEnabled) # item.setFlags(flags) self.outputs_table.resizeColumnsToContents() self.outputs_table.blockSignals(False) # UQ Setup self.compressSamples_chk.setChecked(False) self.compressSamples_chk.setEnabled(False) self.scenariosCalculated = False self.scenarioSelect_static.setEnabled(False) self.scenarioSelect_combo.setEnabled(False) self.scenarioSelect_combo.clear() self.x4SampleScheme_combo.setCurrentIndex(0) self.x4SampleSize_label.setText('Sample Size') self.x4SampleSize_spin.setValue(5) self.x4SampleSize_spin.setRange(5, 1000) self.x4RSMethod_check.setChecked(False) # Launch/Progress self.run_button.setEnabled( True) # TO DO: disable until inputs are validated self.bestValue_table.setColumnCount(1) self.bestValue_table.clearContents() # Plots self.plots_group = QGroupBox() self.plotsLayout = QVBoxLayout() self.plots_group.setLayout(self.plotsLayout) self.progressScrollArea.setMinimumHeight(150) self.progressScrollArea.setWidget(self.plots_group) self.plots_group.setMinimumHeight(150) self.objFig = Figure(figsize=(400, 200), dpi=72, facecolor=(1, 1, 1), edgecolor=(0, 0, 0), tight_layout=True) self.objCanvas = FigureCanvas(self.objFig) self.objFigAx = self.objFig.add_subplot(111) self.objFigAx.set_title('OUU Progress') self.objFigAx.set_ylabel('Objective') self.objFigAx.set_xlabel('Iteration') self.objLine = None self.plotsLayout.addWidget(self.objCanvas) self.objCanvas.setParent(self.plots_group) self.inputPlots = [] self.objXPoints = [] self.objYPoints = [] self.objPlotPoints = None # def setObjectiveFunction(self, on): # self.outputs_table.blockSignals(True) # row = self.sender().property('row') # item = self.outputs_table.item(row, 2) # Checkbox for inequality constraint # flags = item.flags() # if on: # flags &= ~QtCore.Qt.ItemIsEnabled # item.setCheckState(QtCore.Qt.Unchecked) # else: # flags |= QtCore.Qt.ItemIsEnabled # item.setCheckState(QtCore.Qt.Checked if self.useAsConstraint[row] else QtCore.Qt.Unchecked) # item.setFlags(flags) # def toggleConstraintStatus(self, item): # self.useAsConstraint[item.row()] = (item.checkState() == QtCore.Qt.Checked) # def manageBestValueTable(self): self.bestValue = None names, indices = self.input_table.getPrimaryVariables() self.bestValue_table.setRowCount(len(names) + 2) self.bestValue_table.setVerticalHeaderLabels( ['Iteration', 'Objective Value'] + names) self.bestValue_table.clearContents() def setBestValueTable(self, iteration, objValue, inputs): item = self.bestValue_table.item(0, 0) #iteration if item is None: self.bestValue_table.setItem(0, 0, QTableWidgetItem('%d' % iteration)) else: item.setText('%d' % iteration) if self.bestValue == None or objValue < self.bestValue: self.bestValue = objValue item = self.bestValue_table.item(1, 0) #objective value if item is None: self.bestValue_table.setItem(1, 0, QTableWidgetItem('%f' % objValue)) else: item.setText('%f' % objValue) for i, value in enumerate(inputs): item = self.bestValue_table.item(i + 2, 0) #input if item is None: self.bestValue_table.setItem( i + 2, 0, QTableWidgetItem('%f' % value)) else: item.setText('%f' % value) def addPlotValues(self, valuesDict): self.addPointToObjPlot(valuesDict['objective']) self.addToInputPlots(valuesDict['input']) (iteration, objValue) = valuesDict['objective'] self.setBestValueTable(iteration, objValue, valuesDict['input'][1:]) def addPointToObjPlot(self, x): self.objXPoints.append(x[0]) self.objYPoints.append(x[1]) if 0 in self.plotsToUpdate: numPoints = len(self.objXPoints) if numPoints % math.ceil( float(numPoints) / 30 ) == 0: # limit refresh rate as number of points gets large self.updateObjPlot() def updateObjPlot(self): self.objLine, = self.objFigAx.plot(self.objXPoints, self.objYPoints, 'bo') self.objCanvas.draw() def addToInputPlots(self, x): for i in range(len(self.inputPoints)): self.inputPoints[i].append(x[i]) if i > 0 and i in self.plotsToUpdate: numPoints = len(self.inputPoints[i]) if numPoints % math.ceil( float(numPoints) / 30 ) == 0: # limit refresh rate as number of points gets large self.updateInputPlot(i) def updateInputPlot(self, index): # Index starts at 1 for first input plot self.inputPlots[index - 1]['ax'].plot(self.inputPoints[0], self.inputPoints[index], 'bo') self.inputPlots[index - 1]['canvas'].draw() def managePlots(self): names, indices = self.input_table.getPrimaryVariables() if len(self.inputPlots) < len(names): # add plots for i in range(len(self.inputPlots), len(names)): fig = Figure(figsize=(400, 200), dpi=72, facecolor=(1, 1, 1), edgecolor=(0, 0, 0), tight_layout=True) canvas = FigureCanvas(fig) ax = fig.add_subplot(111) ax.set_xlabel('Iteration') self.inputPlots.append({ 'fig': fig, 'canvas': canvas, 'ax': ax }) self.plotsLayout.addWidget(canvas) canvas.setParent(self.plots_group) elif len(self.inputPlots) > len(names): #remove plots for i in range(len(names), len(self.inputPlots)): self.inputPlots[i]['fig'].clf() self.inputPlots[i]['canvas'].deleteLater() del self.inputPlots[i] for i, name in enumerate(names): #self.inputPlots[i]['ax'].set_ylabel('Primary Input %s' % name) self.inputPlots[i]['ax'].set_ylabel(name) self.plots_group.setMinimumHeight(190 * (len(names) + 1)) self.inputPoints = [[] for i in range(len(names) + 1)] self.clearPlots() def clearPlots(self): self.objXPoints = [] self.objYPoints = [] if 'objFigAx' in self.__dict__ and len(self.objFigAx.lines) > 0: self.objFigAx.lines = [] self.objFigAx.relim() #self.objFigAx.set_xlim([0.0, 1.0]) self.objCanvas.draw() if 'inputPoints' in self.__dict__: self.inputPoints = [[] for i in range(len(self.inputPoints))] for i in range(1, len(self.inputPoints)): if len(self.inputPlots[i - 1]['ax'].lines) > 0: self.inputPlots[i - 1]['ax'].lines = [] self.inputPlots[i - 1]['canvas'].draw() def scrollProgressPlots(self, value): QApplication.processEvents() names, indices = self.input_table.getPrimaryVariables() numPlots = len(names) + 1 firstPlotToUpdate = int(value / 190) firstPlotToUpdate = min(firstPlotToUpdate, numPlots - 1) self.plotsToUpdate = [firstPlotToUpdate] if firstPlotToUpdate < numPlots - 1: self.plotsToUpdate.append(firstPlotToUpdate + 1) #print "Scroll", value,self.plotsToUpdate for index in self.plotsToUpdate: if index == 0: self.updateObjPlot() else: self.updateInputPlot(index) QApplication.processEvents() def setFixed(self): self.input_table.setCheckedToType(0) def setX1(self): self.input_table.setCheckedToType(1) def setX1d(self): self.input_table.setCheckedToType(2) def setX2(self): self.input_table.setCheckedToType(3) def setX3(self): self.input_table.setCheckedToType(4) def setX4(self): self.input_table.setCheckedToType(5) def setCounts(self): # update counts M0 = len(self.input_table.getFixedVariables()[0]) M1 = len(self.input_table.getPrimaryVariables()[0]) M2 = len(self.input_table.getRecourseVariables()[0]) M3Vars = self.input_table.getUQDiscreteVariables()[0] M3 = len(M3Vars) M4Vars = self.input_table.getContinuousVariables()[0] M4 = len(M4Vars) self.fixedCount_static.setText('# Fixed: %d' % M0) self.x1Count_static.setText('# Primary Opt Vars: %d' % M1) self.x2Count_static.setText('# Recourse Opt Vars: %d' % M2) self.x3Count_static.setText('# Discrete RVs: %d' % M3) self.x4Count_static.setText('# Continuous RVs: %d' % M4) hideInnerSolver = (M2 == 0) self.secondarySolver_label.setHidden(hideInnerSolver) self.secondarySolver_combo.setHidden(hideInnerSolver) hideZ3Group = (M3 == 0) hideZ4Group = (M4 == 0) if hideZ3Group and hideZ4Group: #Hide tab if self.tabs.widget(2) == self.uqTab: if self.tabs.currentIndex() == 2: self.tabs.setCurrentIndex(0) self.tabs.removeTab(2) else: #Show tab if self.tabs.widget(2) != self.uqTab: self.tabs.insertTab(2, self.uqTab, 'UQ Setup') numCols = max(len(M3Vars), self.z3_table.columnCount()) self.z3_table.setColumnCount(numCols) self.z3_table.setHorizontalHeaderLabels(M3Vars + ['Unused'] * (numCols - len(M3Vars))) numCols = max(len(M4Vars), self.z4_table.columnCount()) self.z4_table.setColumnCount(numCols) self.z4_table.setHorizontalHeaderLabels(M4Vars + ['Unused'] * (numCols - len(M4Vars))) self.z3_group.setHidden(hideZ3Group) self.z4_group.setHidden(hideZ4Group) if self.x4SampleScheme_combo.currentText( ) == SamplingMethods.getFullName(SamplingMethods.FACT): self.x4SampleSize_spin.setMinimum(3) else: self.x4SampleSize_spin.setMinimum(M4 + 1) self.z4SubsetSize_spin.setMinimum(M4 + 1) def chooseZ4NewSample(self, value): if value: self.x4SampleScheme_label.setEnabled(True) self.x4SampleScheme_combo.setEnabled(True) self.x4SampleSize_label.setEnabled(True) self.x4SampleSize_spin.setEnabled(True) self.x4FileBrowse_button.setEnabled(False) self.showZ4Subset(False) self.setZ4RS(self.x4SampleSize_spin.value()) self.z4_table.setEnabled(False) def chooseZ4LoadSample(self, value): if value: self.x4SampleScheme_label.setEnabled(False) self.x4SampleScheme_combo.setEnabled(False) self.x4SampleSize_label.setEnabled(False) self.x4SampleSize_spin.setEnabled(False) self.x4FileBrowse_button.setEnabled(True) self.showZ4Subset(True) self.setZ4RS(self.z4SubsetSize_spin.value()) self.z4_table.setEnabled(True) def setZ4RS(self, value): if value <= 300: rs = ResponseSurfaces.getFullName(ResponseSurfaces.KRIGING) elif value <= 600: rs = ResponseSurfaces.getFullName(ResponseSurfaces.RBF) else: rs = ResponseSurfaces.getFullName(ResponseSurfaces.MARS) self.x4RSMethod_check.setText('Use Response Surface (%s)' % rs) def showZ4Subset(self, show): if show and self.x4RSMethod_check.isChecked( ) and self.z4LoadSample_radio.isChecked(): self.z4SubsetSize_label.setEnabled(True) self.z4SubsetSize_spin.setEnabled(True) else: self.z4SubsetSize_label.setEnabled(False) self.z4SubsetSize_spin.setEnabled(False) def setupPSUADEClient(self, client_exe_name='foqusPSUADEClient'): full_path_to_client_exe = shutil.which(client_exe_name) assert full_path_to_client_exe is not None, 'The "foqusPSUADEClient" executable was not found' return full_path_to_client_exe def analyze(self): dir = os.getcwd() for f in os.listdir(dir): if re.search('psuadeEval.out', f): os.remove(os.path.join(dir, f)) if self.run_button.text() == 'Run OUU': # Run OUU names, indices = self.input_table.getPrimaryVariables() if len(names) == 0: QMessageBox.information( self, 'No Primary Variables', 'At least one input must be a primary variable!') return valid, error = self.input_table.checkValidInputs() if not valid: QMessageBox.information( self, 'Input Table Distributions', 'Input table distributions are either not correct or not filled out completely! %s' % error) return if self.compressSamples_chk.isChecked( ) and not self.scenariosCalculated: QMessageBox.information( self, 'Compress Samples Not Calculated', 'You have elected to compress samples for discrete random variables (Z3), but have not selected the sample size to use!' ) return M1 = len(self.input_table.getPrimaryVariables()[0]) M2 = len(self.input_table.getRecourseVariables()[0]) M3 = len(self.input_table.getUQDiscreteVariables()[0]) M4 = len(self.input_table.getContinuousVariables()[0]) Common.initFolder(OUU.dname) self.managePlots() self.clearPlots() self.manageBestValueTable() self.summary_group.setTitle('Best So Far') xtable = self.input_table.getTableValues() # get arguments for ouu() model = copy.deepcopy(self.model) inputNames = model.getInputNames() inputTypes = list(model.getInputTypes()) defaultValues = model.getInputDefaults() for row in xtable: if row['type'] == 'Fixed': modelIndex = inputNames.index(row['name']) inputTypes[modelIndex] = Model.FIXED defaultValues[modelIndex] = row['value'] #print inputTypes #print defaultValues model.setInputTypes(inputTypes) model.setInputDefaults(defaultValues) data = SampleData(model) fname = 'ouuTemp.dat' data.writeToPsuade(fname) # Outputs numOutputs = self.outputs_table.rowCount() y = [] self.useAsConstraint = [False] * numOutputs self.useAsDerivative = [False] * numOutputs for r in range(numOutputs): type = self.outputs_table.cellWidget(r, 0).currentText() if type == ouuSetupFrame.ObjFuncText: y.append(r + 1) elif type == ouuSetupFrame.ConstraintText: self.useAsConstraint[r] = True elif type == ouuSetupFrame.DerivativeText: self.useAsDerivative[r] = True if self.mean_radio.isChecked(): phi = {'type': 1} elif self.meanWithBeta_radio.isChecked(): beta = self.betaDoubleSpin.value() phi = {'type': 2, 'beta': beta} elif self.alpha_radio.isChecked(): alpha = self.alphaDoubleSpin.value() phi = {'type': 3, 'alpha': alpha} x3sample = None if M3 > 0: if self.compressSamples_chk.isChecked(): selectedSamples = int( self.scenarioSelect_combo.currentText()) sfile = self.scenarioFiles[selectedSamples][0] else: sfile = 'z3Samples.smp' success = self.writeTableToFile(self.z3_table, sfile, M3) if not success: return if sfile.endswith( '.csv'): # Convert .csv file to simple file newFileName = OUU.dname + os.sep + os.path.basename( fname)[:-4] + '.smp' inData = LocalExecutionModule.readDataFromCsvFile( sfile, askForNumInputs=False) LocalExecutionModule.writeSimpleFile( newFileName, inData[0]) sfile = newFileName #print 'x3 file is', sfile x3sample = {'file': sfile} # x3sample file data, _, numInputs, _ = LocalExecutionModule.readDataFromSimpleFile( sfile, hasColumnNumbers=False) if numInputs != M3: QMessageBox.critical( self, "Number of variables don't match", 'The number of variables from the file (%d) does not match the number of Z3 discrete variables (%d). You will not be able to perform analysis until this is corrected.' % (numInputs, M3)) return useRS = self.x4RSMethod_check.isChecked() x4sample = None if self.z4NewSample_radio.isChecked(): method = self.x4SampleScheme_combo.currentText() method = SamplingMethods.getEnumValue(method) N = self.x4SampleSize_spin.value() if method in [SamplingMethods.LH, SamplingMethods.LPTAU]: x4sample = { 'method': method, 'nsamples': N } # number of samples (range: [M1+1,1000]) elif method == SamplingMethods.FACT: x4sample = { 'method': method, 'nlevels': N } # number of levels (range: [3,100]) else: sfile = 'z4Samples.smp' success = self.writeTableToFile(self.z4_table, sfile, M4) if not success: return if len(sfile) == 0: QMessageBox.critical(self, 'Missing file', 'Z4 sample file not specified!') return if sfile.endswith('.csv'): # Convert .csv file to simple file newFileName = OUU.dname + os.sep + os.path.basename( fname)[:-4] + '.smp' inData = LocalExecutionModule.readDataFromCsvFile( sfile, askForNumInputs=False) LocalExecutionModule.writeSimpleFile( newFileName, inData[0]) sfile = newFileName inData, outData, numInputs, numOutputs = LocalExecutionModule.readDataFromSimpleFile( sfile, hasColumnNumbers=False) numSamples = inData.shape[0] if numInputs != M4: QMessageBox.critical( self, "Number of variables don't match", 'The number of input variables from the file (%d) does not match the number of Z4 continuous variables (%d). You will not be able to perform analysis until this is corrected.' % (numInputs, M4)) return if numSamples <= M4: QMessageBox.critical( self, 'Not enough samples', 'Z4 sample file must have at least %d samples!' % (M4 + 1)) return x4sample = { 'file': sfile } # x4sample file, must have at least M4+1 samples if useRS: Nrs = self.z4SubsetSize_spin.value( ) # add spinbox to get number of samples to generate RS x4sample[ 'nsamplesRS'] = Nrs # TO DO: make sure spinbox has M4+1 as min and x4sample's sample size as max # TODO: Get rid of usebobyqa option. Behavior should be as if usebobyqa is always false # TODO: Change GUI to display optimizer and optimizing with bobyqa # TODO: Get rid of primarySolver_combo completely useBobyqa = False method = self.primarySolver_combo.currentText() if method == "BOBYQA": pass elif method == "NEWUOA": pass if 'simulator' in self.secondarySolver_combo.currentText(): useBobyqa = True # use BOBYQA if driver is a simulator, not an optimizer self.run_button.setText('Stop') optDriver = None ensembleOptDriver = None if self.node_radio.isChecked(): ensembleOptDriver = self.setupPSUADEClient() optDriver = ensembleOptDriver listener = listen.foqusListener(self.dat) variableNames = [] fixedNames = [] for row in xtable: #print row if row['type'] == 'Fixed': fixedNames.append(row['name']) else: variableNames.append(row['name']) #print fixedNames, variableNames #print variableNames + fixedNames listener.inputNames = variableNames + fixedNames outputNames = self.model.getOutputNames() listener.outputNames = [outputNames[yItem - 1] for yItem in y] listener.failValue = -111111 self.listenerAddress = listener.address listener.start() # print M1, M2, M3, M4, useBobyqa self.OUUobj = OUU() try: # WHY pylint is right in reporting that self.OUUobj.ouu() always returns None; # this is not a runtime error (in the sense that it will not cause the program to crash) # but the assignment could be removed from this function call for greater clarity results = self.OUUobj.ouu( # TODO pylint: disable=assignment-from-none fname, y, self.useAsConstraint, self.useAsDerivative, xtable, phi, x3sample=x3sample, x4sample=x4sample, useRS=useRS, useBobyqa=useBobyqa, optDriver=optDriver, ensOptDriver=ensembleOptDriver, plotSignal=self.plotSignal, endFunction=self.finishOUU) except: import traceback traceback.print_exc() if self.node_radio.isChecked(): # stop the listener conn = Client(self.listenerAddress) conn.send(['quit']) conn.close() # enable run button self.run_button.setEnabled(True) return else: # Stop OUU self.OUUobj.stopOUU() self.run_button.setEnabled(False) self.freeze() def finishOUU(self): if self.node_radio.isChecked(): # stop the listener conn = Client(self.listenerAddress) conn.send(['quit']) conn.close() # enable run button if not self.run_button.isEnabled(): self.unfreeze() self.run_button.setText('Run OUU') self.run_button.setEnabled(True) if not self.OUUobj.getHadError(): self.summary_group.setTitle('Best Solution') # results.replace('X','Z') # # QMessageBox.information(self, 'OUU Results', results) msgBox = QMessageBox() msgBox.setWindowTitle('FOQUS OUU Finished') msgBox.setText('Optimization under Uncertainty analysis finished') self.result = msgBox.exec_() def getResult(self): return self.result
def __init__(self): """ QPlot is designed to interface with syncmrt.file.image.Image2D objects. Parameters ---------- tableModel : QsWorkspace.QPlotTableModel object A table model must be provided for the storage of marker locations. """ super().__init__() # Create the figure/canvas. self.fig = plt.figure(constrained_layout=True) self.fig.patch.set_facecolor('#000000') # Create the canvas. self.canvas = FigureCanvasQTAgg(self.fig) # Create the figure manager. self.figureManager = FigureManagerQT(self.canvas, 1) # Create the toolbar manager. self.toolbarManager = self.figureManager.toolbar.toolmanager # Create the toolbar self.toolbar = self.figureManager.toolbar # Reference to ax.imshows(). self.images = {} # Set up marker tracking. self.markers = {} self.markersMaximum = 0 self.ctd = [None, None] # Set up histograms dict for axes. self.histograms = {} # Create 2 axes. self.ax = self.fig.subplots(1, 2, gridspec_kw={ 'hspace': 0, 'wspace': 0, 'left': 0, 'right': 1, 'bottom': 0, 'top': 1 }, sharey=False) for idx, ax in enumerate(self.ax): # Set up tracking for markers in the axes. self.markers[ax] = [] # Set up histogram connections. self.histograms[ax] = QHistogramWindow() self.histograms[ax].windowUpdated.connect( partial(self.applyWindow, ax)) # Set up the axes. ax.set_facecolor('#000000') ax.title.set_color('#FFFFFF') ax.xaxis.label.set_color('#FFFFFF') ax.yaxis.label.set_color('#FFFFFF') ax.xaxis.set_label_coords(0.5, 0.12) ax.yaxis.set_label_coords(0.12, 0.5) ax.xaxis.label.set_size(20) ax.yaxis.label.set_size(20) ax.yaxis.label.set_rotation(90) ax.spines['left'].set_visible(False) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['bottom'].set_visible(False) ax.tick_params('both', which='both', length=7, width=1, pad=-35, direction='in', colors='#FFFFFF') # Remove useless tools. items = list(self.toolbar._toolitems.keys()) for item in items: self.toolbar.remove_toolitem(item) # Populate the toolbar manager. self.toolbarManager.add_tool('home', 'ToolHome') self.toolbarManager.add_tool('zoom', 'ToolZoom') self.toolbarManager.add_tool('pan', 'ToolPan') self.toolbarManager.add_tool('pick', ToolPickPoint) self.toolbarManager.add_tool('pickIso', ToolPickIso) self.toolbarManager.add_tool('clear', ToolClearPoints) # Populate the toolbar. self.toolbar.add_tool('home', "default") self.toolbar.add_tool('zoom', "default") self.toolbar.add_tool('pan', "default") self.toolbar.add_tool('pick', "default") self.toolbar.add_tool('clear', "default") # Get the layout. layout = QtWidgets.QVBoxLayout() layout.addWidget(self.toolbar) layout.addWidget(self.canvas) self.setLayout(layout) # Get tools. pick = self.toolbarManager.get_tool('pick') clear = self.toolbarManager.get_tool('clear') pickIso = self.toolbarManager.get_tool('pickIso') # Connect tool signals. pick.newPoint.connect(self.addMarker) clear.clearPoints.connect(self.removeMarkers) pickIso.newIsocenter.connect(self._updateIsocenter) # Refresh the canvas. self.canvas.draw() # self._radiographMode = 'sum' # self._R = np.identity(3) # self._imagingAngle = 0 # self.mask = None self.maskSize = 20.0 self.overlay = {} self.machineIsocenter = [0, 0, 0] self.patientIsocenter = [0, 0, 0]
class WaterfallPlotter(QWidget): generated_rectangles_signal = QtCore.pyqtSignal(list) #send list of rects for data display in tree def __init__(self,parent): super(WaterfallPlotter,self).__init__(parent) self.get_settings() self.settings_update = False self.figure = plt.figure() self.canvas = FigureCanvas(self.figure) self.toolbar = NavigationToolbar(self.canvas,self) self.btn_plot = QPushButton('Default Plot') self.btn_plot.clicked.connect(self.default_plot) self.layout = QVBoxLayout() self.layout.addWidget(self.toolbar) self.layout.addWidget(self.canvas) self.layout.addWidget(self.btn_plot) self.setLayout(self.layout) def on_waterfall_data_signal(self,signal): self.waterfall_data = signal['waterfall_data'] #pandas dataframe self.btn_plot.setEnabled(True) def get_settings(self): try: with shelve.open('WaterfallSettings') as shelfFile: self.keys_and_colors = shelfFile['keys_and_colors'] shelfFile.close() except: #set and use default settings self.keys_and_colors = { 'CR':'#03945D', 'PR':'#B1EE97', 'PD':'#FF6F69', 'SD':'#707070'} with shelve.open('WaterfallSettings') as shelfFile: shelfFile['keys_and_colors'] = self.keys_and_colors shelfFile.close() def on_general_settings_signal(self,signal): self.gen_settings = signal self.settings_update = True self.default_plot() def get_bar_colors(self,responses): return [self.keys_and_colors[x] for x in responses] def default_plot(self): ''' Plot waterfall data ''' self.figure.clear() self.rect_locations = np.arange(len(self.waterfall_data['Best response percent change'])) self.ax = self.figure.add_subplot(111) self.bar_colors = self.get_bar_colors(self.waterfall_data['Overall response']) if self.settings_update == False: self.ax.tick_params( axis='x', # changes apply to the x-axis which='both', # both major and minor ticks are affected bottom='on', # ticks along the bottom edge are off top='on', # ticks along the top edge are off labelbottom='on' ) # labels along the bottom edge are off self.ax.axhline(y=20, linestyle='--', c='k', alpha=0.5, lw=2.0, label='twenty_percent') self.ax.axhline(y=-30, linestyle='--', c='k', alpha=0.5, lw=2.0, label='thirty_percent') self.ax.axhline(y=0, c='k', alpha=1, lw=2.0, label='zero_percent') self.ax.grid(color = 'k', axis = 'y', alpha=0.25) self.rects = self.ax.bar(self.rect_locations, self.waterfall_data['Best response percent change'], color=self.bar_colors) else: #settings were updated, we received them and stored in variable self.gen_settings self.ax.set_title(self.gen_settings[0]) self.ax.set_xlabel(self.gen_settings[1]) self.ax.set_ylabel(self.gen_settings[2]) if self.gen_settings[3][0]: self.ax.axhline(y=20, linestyle='--', c='k', alpha=0.5, lw=2.0, label='twenty_percent') if self.gen_settings[3][1]: self.ax.axhline(y=-30, linestyle='--', c='k', alpha=0.5, lw=2.0, label='thirty_percent') if self.gen_settings[3][2]: self.ax.axhline(y=0, c='k', alpha=1, lw=2.0, label='zero_percent') if self.gen_settings[4][0] and ~self.gen_settings[6]: #show responses as labels, default color bars #legend depends on user specified keys self.rects = self.ax.bar(self.rect_locations, self.waterfall_data['Best response percent change']) self.auto_label_responses(self.ax, self.rects, self.waterfall_data) elif self.gen_settings[4][1]: #color bars with response type self.rects = self.ax.bar(self.rect_locations, self.waterfall_data['Best response percent change'], color=self.bar_colors) self.patches = [] for key in self.keys_and_colors.keys(): self.patches.append(mpatches.Patch(color = self.keys_and_colors[key],label=key)) self.ax.legend(handles=self.patches) else: self.rects = self.ax.bar(self.rect_locations, self.waterfall_data['Best response percent change']) if self.gen_settings[5]: self.plot_table() if self.gen_settings[6] and ~self.gen_settings[4][0]: self.ax.grid(color = 'k', axis = 'y', alpha=0.25) self.canvas.draw() self.generated_rectangles_signal.emit([self.rects]) def plot_table(self): rows = ['%s' % x for x in self.waterfall_data.keys()] rows = rows[4:] #skip first three, they are the 4 standard headers, rest are table rows columns = self.waterfall_data['Patient number'] #patient numbers cell_text = [] for row in rows: cell_text_temp = [] for col in range(len(columns)): cell_text_temp.append(self.waterfall_data[row][col]) cell_text.append(cell_text_temp) the_table = self.ax.table(cellText=cell_text, rowLabels=rows, colLabels=columns, loc='bottom', cellLoc='center', colLoc='bottom') plt.subplots_adjust(bottom=0.15,left=0.5) self.ax.set_xlim(-0.5,len(columns)-0.5) self.ax.tick_params( axis='x', # changes apply to the x-axis which='both', # both major and minor ticks are affected bottom='off', # ticks along the bottom edge are off top='off', # ticks along the top edge are off labelbottom='off' ) # labels along the bottom edge are off def update_plot(self): ''' TODO ''' pass def auto_label_responses(self, ax, rects, waterfall_data, type): '''Add labels above/below bars''' i = 0 for rect in rects: height = rect.get_height() if height >= 0: valign = 'bottom' else: valign = 'top' ax.text(rect.get_x() + rect.get_width()/2., height, '%s' % waterfall_data['Overall response'][i], ha='center', va=valign) i+=1
def initWidgets(self): btnCol = QPushButton('Wybierz kolor', self) #przycisk btn = QPushButton('Rysuj', self) btnsave = QPushButton('Zapisz wynik', self) xaLabel = QLabel('Xa', self) #sluzy nad do podpisywania yaLabel = QLabel('Ya', self) xbLabel = QLabel('Xb', self) ybLabel = QLabel('Yb', self) xcLabel = QLabel('Xc', self) ycLabel = QLabel('Yc', self) xdLabel = QLabel('Xd', self) ydLabel = QLabel('Yd', self) xpLabel = QLabel('Xp', self) ypLabel = QLabel('Yp', self) NAPISLabel = QLabel('Gdzie się znajduję punkt ?', self) self.xpEdit = QLineEdit() #pole w ktorym wpisujemy tekst badz liczbe self.ypEdit = QLineEdit() self.xaEdit = QLineEdit() self.yaEdit = QLineEdit() self.xbEdit = QLineEdit() self.ybEdit = QLineEdit() self.xcEdit = QLineEdit() self.ycEdit = QLineEdit() self.xdEdit = QLineEdit() self.ydEdit = QLineEdit() self.NAPISEdit = QLineEdit() resultLabel = QLabel('', self) #wykres self.figure = plt.figure() self.canvas = FigureCanvas(self.figure) grid = QGridLayout() #tworzenie siatki grid.addWidget(xaLabel, 2, 0) #2wiersz 0 kolumna grid.addWidget(self.xaEdit, 2, 1) grid.addWidget(yaLabel, 3, 0) grid.addWidget(self.yaEdit, 3, 1) grid.addWidget(xbLabel, 4, 0) grid.addWidget(self.xbEdit, 4, 1) grid.addWidget(ybLabel, 5, 0) grid.addWidget(self.ybEdit, 5, 1) grid.addWidget(xcLabel, 6, 0) grid.addWidget(self.xcEdit, 6, 1) grid.addWidget(ycLabel, 7, 0) grid.addWidget(self.ycEdit, 7, 1) grid.addWidget(xdLabel, 8, 0) grid.addWidget(self.xdEdit, 8, 1) grid.addWidget(xpLabel, 10, 0) grid.addWidget(self.xpEdit, 10, 1, 1, 2) grid.addWidget(ypLabel, 11, 0) grid.addWidget(self.ypEdit, 11, 1, 1, 2) grid.addWidget(NAPISLabel, 12, 0) grid.addWidget(self.NAPISEdit, 13, 0, 1, 4) grid.addWidget(ydLabel, 9, 0) grid.addWidget(self.ydEdit, 9, 1) grid.addWidget( btn, 14, 0, 1, 2 ) #czternasty wiersz, zerowa kolumna, rozciaga sie na jeden wiersz i dwie kolumny grid.addWidget(btnCol, 15, 0, 1, 2) grid.addWidget(btnsave, 16, 0, 1, 2) grid.addWidget(resultLabel, 17, 0) grid.addWidget(self.canvas, 1, 7, -1, -1) self.setLayout(grid) btn.clicked.connect( self.oblicz ) #przycisk ktory za pomoca klikniecia wywoluje sygnal ktory w dalszej czesci cos robi btnCol.clicked.connect(self.zmienKolor) btnsave.clicked.connect(self.zapisz)
def __init__(self): self.fig = Figure() self.ax = self.fig.add_subplot(111) Canvas.__init__(self, self.fig) Canvas.setSizePolicy(self, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) Canvas.updateGeometry(self)
class AppWindow(QWidget): #klasa reprezentujaca aplikacje def __init__(self): super().__init__() self.title = 'Przecięcia prostych' #tytuł self.initInterface() #klasa odpowiedzialna za tworzenie interfejsu self.initWidgets() def initInterface(self): self.setWindowTitle(self.title) self.setGeometry(500, 500, 600, 600) #geometria okna self.show() #wyswietlenie okna def initWidgets(self): btnCol = QPushButton('Wybierz kolor', self) #przycisk btn = QPushButton('Rysuj', self) btnsave = QPushButton('Zapisz wynik', self) xaLabel = QLabel('Xa', self) #sluzy nad do podpisywania yaLabel = QLabel('Ya', self) xbLabel = QLabel('Xb', self) ybLabel = QLabel('Yb', self) xcLabel = QLabel('Xc', self) ycLabel = QLabel('Yc', self) xdLabel = QLabel('Xd', self) ydLabel = QLabel('Yd', self) xpLabel = QLabel('Xp', self) ypLabel = QLabel('Yp', self) NAPISLabel = QLabel('Gdzie się znajduję punkt ?', self) self.xpEdit = QLineEdit() #pole w ktorym wpisujemy tekst badz liczbe self.ypEdit = QLineEdit() self.xaEdit = QLineEdit() self.yaEdit = QLineEdit() self.xbEdit = QLineEdit() self.ybEdit = QLineEdit() self.xcEdit = QLineEdit() self.ycEdit = QLineEdit() self.xdEdit = QLineEdit() self.ydEdit = QLineEdit() self.NAPISEdit = QLineEdit() resultLabel = QLabel('', self) #wykres self.figure = plt.figure() self.canvas = FigureCanvas(self.figure) grid = QGridLayout() #tworzenie siatki grid.addWidget(xaLabel, 2, 0) #2wiersz 0 kolumna grid.addWidget(self.xaEdit, 2, 1) grid.addWidget(yaLabel, 3, 0) grid.addWidget(self.yaEdit, 3, 1) grid.addWidget(xbLabel, 4, 0) grid.addWidget(self.xbEdit, 4, 1) grid.addWidget(ybLabel, 5, 0) grid.addWidget(self.ybEdit, 5, 1) grid.addWidget(xcLabel, 6, 0) grid.addWidget(self.xcEdit, 6, 1) grid.addWidget(ycLabel, 7, 0) grid.addWidget(self.ycEdit, 7, 1) grid.addWidget(xdLabel, 8, 0) grid.addWidget(self.xdEdit, 8, 1) grid.addWidget(xpLabel, 10, 0) grid.addWidget(self.xpEdit, 10, 1, 1, 2) grid.addWidget(ypLabel, 11, 0) grid.addWidget(self.ypEdit, 11, 1, 1, 2) grid.addWidget(NAPISLabel, 12, 0) grid.addWidget(self.NAPISEdit, 13, 0, 1, 4) grid.addWidget(ydLabel, 9, 0) grid.addWidget(self.ydEdit, 9, 1) grid.addWidget( btn, 14, 0, 1, 2 ) #czternasty wiersz, zerowa kolumna, rozciaga sie na jeden wiersz i dwie kolumny grid.addWidget(btnCol, 15, 0, 1, 2) grid.addWidget(btnsave, 16, 0, 1, 2) grid.addWidget(resultLabel, 17, 0) grid.addWidget(self.canvas, 1, 7, -1, -1) self.setLayout(grid) btn.clicked.connect( self.oblicz ) #przycisk ktory za pomoca klikniecia wywoluje sygnal ktory w dalszej czesci cos robi btnCol.clicked.connect(self.zmienKolor) btnsave.clicked.connect(self.zapisz) def zmienKolor(self): #definicja ktora otwiera nam palete z kolorami color = QColorDialog.getColor() if color.isValid(): print(color.name()) self.robCos(col=color.name()) def oblicz(self): # self.robCos() def robCos(self, col='red'): # plt.cla #czyszczenie wykresu xa = self.sprawdzenieWartosci( self.xaEdit ) #sprawdzanie czy dane zostały zapisane poprawnie jak opisuje nam definicja sprawdzenieWartosci ya = self.sprawdzenieWartosci(self.yaEdit) xb = self.sprawdzenieWartosci(self.xbEdit) yb = self.sprawdzenieWartosci(self.ybEdit) xc = self.sprawdzenieWartosci(self.xcEdit) yc = self.sprawdzenieWartosci(self.ycEdit) xd = self.sprawdzenieWartosci(self.xdEdit) yd = self.sprawdzenieWartosci(self.ydEdit) if (xa is not None) and (ya is not None) and (xb is not None) and ( yb is not None) and (xc is not None) and (yc is not None) and ( xd is not None) and (yd is not None): if (((xb - xa) * (yd - yc)) - ((yb - ya) * (xd - xc))) == 0: #przypadek równoległosci self.NAPISEdit.setText('proste są równoległe') else: #przypadki inne niż kiedy proste są względem siebie równoległe T1 = (((xc - xa) * (yd - yc)) - ((yc - ya) * (xd - xc))) / (((xb - xa) * (yd - yc)) - ((yb - ya) * (xd - xc))) T2 = (((xc - xa) * (yb - ya)) - ((yc - ya) * (xb - xa))) / (((xb - xa) * (yd - yc)) - ((yb - ya) * (xd - xc))) self.xP = round(xa + T1 * (xb - xa), 3) self.yP = round(ya + T1 * (yb - ya), 3) if T1 > 0 and T1 < 1 and T2 > 0 and T2 < 1: #warunki self.NAPISEdit.setText( "punkt leży na przecięciu odcinków AB i CD") elif T1 > 0 and T1 < 1 and T2 < 0: self.NAPISEdit.setText( "przecięcie odcinka AB oraz przedłuzenie CD") elif T1 > 0 and T1 < 1 and T2 > 1: self.NAPISEdit.setText( "przecięcie odcinka AB oraz przedłuzenie CD") elif T2 > 0 and T2 < 1 and T1 > 1: self.NAPISEdit.setText( "przecięcie odcinka CD oraz przedłuzenie AB") elif T2 > 0 and T2 < 1 and T1 < 0: self.NAPISEdit.setText( "przecięcie odcinka CD oraz przedłuzenie AB") elif T2 < 0 or T2 > 1 and T1 > 1 or T1 < 0: self.NAPISEdit.setText( "na przedłużeniach odcinków AB i CD") self.xpEdit.setText(str(self.xP)) self.ypEdit.setText(str(self.yP)) x_1 = ['A', 'B', 'C', 'D', 'P'] X_2 = [xa, xb, xc, xd, self.xP] Y_2 = [ya, yb, yc, yd, self.yP] self.figure.clear() ax = self.figure.add_subplot(111) ax.scatter(X_2, Y_2) ax.plot( [xa, xb], [ya, yb], color=col, marker='o' ) #rysuje nam linie w dowolnym wybranym przez nas kolorze dzieki definicji zmienKolor ax.plot([xc, xd], [yc, yd], color=col, marker='o') ax.plot( [xa, self.xP], [ya, self.yP], linestyle='--', color='red') #rysuje nam linie przerywaną o kolorze czerwonym ax.plot([xd, self.xP], [yd, self.yP], linestyle='--', color='blue') for (x, y, l) in zip(X_2, Y_2, enumerate(x_1)): #etykietowanie punktów ax.annotate("{}({};{})".format(l[1], x, y), xy=(x, y)) self.canvas.draw() def zapisz(self): plik1 = open( 'wspolrzedne.txt', 'w+') #stworzenie pliku tekstowego, ktory aktualizuje dane plik1.write(80 * '-') plik1.write('\n|{:^10}|\n'.format( 'współrzędne')) #okrelenie formatu zapisu danych plik1.write('\n|{:^10}|{:^10}|\n'.format('xP', 'yP')) plik1.write('\n|{:^10}|{:^10}|\n'.format(self.xP, self.yP)) plik1.close() def sprawdzenieWartosci(self, element): if element.text().lstrip('-').replace('.', '', 1).isdigit( ): #sprawdzenie czy dane zostały zapisane w prawidłowy sposób, jesli nie obraz prostych nie zostane narysowany return float(element.text()) else: element.setFocus() #zeby element byl widoczny return None
class MainWindow(QMainWindow): def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) # Cria a conexão com o banco de dados self.mysql = CidadesMySQL() self.bot = Bot(self.mysql) self.setWindowTitle('Cidades!') self.width = 768 self.heigth = 1024 self.setGeometry(10, 10, self.heigth, self.width) # Cria o mapa e adiciona na janela self.map = Mapa() self.canvas = FigureCanvasQTAgg(self.map.fig) self.canvas.move(100, 100) self.canvas.resize(1000, 700) self.setCentralWidget(self.canvas) # Label da caixa de entrada self.input_label = QLabel('Digite a cidade!', self.canvas) self.input_label.resize(280, 20) self.input_label.move(0.5 * self.width, 10) self.input_label.setAlignment(QtCore.Qt.AlignCenter) # Entrada de texto do usuário self.city_input = QLineEdit('', self.canvas) self.city_input.resize(280, 30) self.city_input.move(self.width / 2, 40) self.city_input.setAlignment(QtCore.Qt.AlignCenter) # Conecta o Enter com o envio do input self.city_input.returnPressed.connect(self.check_input) # Contador de acertos e cidades faltando self.counter = 0 self.remaining = 5570 self.counter_label = QLabel( 'Contador: %d\nCidades Faltando: %d' % (self.counter, self.remaining), self) self.counter_label.resize(280, 50) self.counter_label.move(self.width, 30) # Aviso de cidade não encontrada self.not_found_label = QLabel('', self) self.not_found_label.resize(280, 50) self.not_found_label.move(0.1 * self.width, 30) self.not_found_label.setStyleSheet('color: red') # Usar bot self.bot_btn = QPushButton(text='Usar bot', parent=self) self.bot_btn.resize(100, 100) self.bot_btn.move(0.1 * self.width, 300) self.bot_btn.clicked.connect(self.use_bot) self.show() def check_input(self): # Limpa o possível valor errado self.not_found_label.clear() city = self.city_input.text() coords = self.query_coord(city) matches = len(coords) if matches == 0: self.not_found_label.setText('Cidade %s não encontrada!' % city) else: # altera os contadores self.counter += matches self.remaining -= matches self.counter_label.setText('Contador: %d\nCidades Faltando: %d' % (self.counter, self.remaining)) # mostra a cidade na figura for c in coords: lon = c[0] lat = c[1] self.map.ax.plot(lon, lat, marker='x', transform=ccrs.PlateCarree()) self.map.fig.canvas.draw() self.map.fig.canvas.flush_events() self.city_input.clear() def query_coord(self, city): self.mysql.cursor.execute( 'SELECT longitude, latitude FROM municipios WHERE nome = "%s"' % city) coords = self.mysql.cursor.fetchall() return coords def use_bot(self): for name in self.bot.results: self.city_input.setText(name[0]) self.check_input()