def __init__(self, scrollAreaWidgetContents, dataname, currentFolder): QtGui.QWidget.__init__(self) self.setParent(scrollAreaWidgetContents) fig = Figure((3.0, 2.0), dpi=100) canvas = FigureCanvas(fig) canvas.setParent(self) toolbar = myNavigationToolbar(canvas, self) temporal_toolbar = temporalNavigationToolbar(canvas, self) axes = fig.add_subplot(111) axes.autoscale(True) axes.set_yscale('log') axes.set_title(dataname) # place plot components in a layout plotLayout = QtGui.QVBoxLayout() plotLayout.addWidget(temporal_toolbar) plotLayout.addWidget(canvas,1) plotLayout.addWidget(toolbar,0,QtCore.Qt.AlignCenter) self.setLayout(plotLayout) canvas.setMinimumSize(canvas.size()) self.name = dataname self.dirList = [] self.dirType = 'Sampled Line' self.lastPos = -1 self.colors = ['r', 'b', 'k', 'g', 'y', 'c'] self.labels = ['x','y','z'] self.currentFolder = currentFolder filename = '%s/system/controlDict'%(self.currentFolder) parsedData = ParsedParameterFile(filename,createZipped=False) self.ifield=parsedData['functions'][dataname]['fields'][0] self.archifield = 'data_%s.xy'%self.ifield
def __init__(self, scrollAreaWidgetContents, dataname): QtGui.QWidget.__init__(self) self.setParent(scrollAreaWidgetContents) fig = Figure((3.0, 2.0), dpi=100) canvas = FigureCanvas(fig) canvas.setParent(self) toolbar = myNavigationToolbar(canvas, self) temporal_toolbar = temporalNavigationToolbar(canvas, self) axes = fig.add_subplot(111) axes.autoscale(True) axes.set_yscale('log') axes.set_title(dataname) # place plot components in a layout plotLayout = QtGui.QVBoxLayout() plotLayout.addWidget(temporal_toolbar) plotLayout.addWidget(canvas) plotLayout.addWidget(toolbar) self.setLayout(plotLayout) canvas.setMinimumSize(canvas.size()) self.name = dataname self.dirList = [] self.dirType = 'Sampled Line' self.lastPos = -1 self.colors = ['r', 'b', 'k', 'g', 'y', 'c'] self.labels = ['_x', '_y', '_z']
def __init__(self, scrollAreaWidgetContents): QtGui.QWidget.__init__(self) self.setParent(scrollAreaWidgetContents) canvas = FigureCanvas(Figure((3.0, 2.0), dpi=100)) canvas.setParent(self) toolbar = myNavigationToolbar(canvas, self) toolbar.disableButtons() temporal_toolbar = temporalNavigationToolbar(canvas, self) mainImage = QtGui.QLabel(self) mainImage.setText(_fromUtf8("")) mainImage.setPixmap( QtGui.QPixmap( _fromUtf8(":/newPrefix/images/fromHelyx/emptyFigure.png"))) mainImage.setObjectName(_fromUtf8("mainImage")) plotLayout = QtGui.QVBoxLayout() plotLayout.addWidget(temporal_toolbar) plotLayout.addWidget(mainImage) plotLayout.addWidget(toolbar) self.setLayout(plotLayout) canvas.setMinimumSize(canvas.size())
def __init__(self, scrollAreaWidgetContents, currentFolder): QtGui.QWidget.__init__(self) self.setParent(scrollAreaWidgetContents) canvas = FigureCanvas(Figure((3.0, 2.0), dpi=100)) canvas.setParent(self) toolbar = myNavigationToolbar(canvas, self) toolbar.disableButtons() temporal_toolbar = temporalNavigationToolbar(canvas, self) mainImage = QtGui.QLabel(self) mainImage.setText(_fromUtf8("")) mainImage.setPixmap( QtGui.QPixmap( _fromUtf8(":/newPrefix/images/fromHelyx/emptyFigure.png"))) mainImage.setObjectName(_fromUtf8("mainImage")) mainImage.setScaledContents(True) mainImage.setSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Ignored) plotLayout = QtGui.QVBoxLayout() plotLayout.addWidget(temporal_toolbar) plotLayout.addWidget(mainImage, 1) plotLayout.addWidget(toolbar, 0, QtCore.Qt.AlignCenter) self.setLayout(plotLayout) self.lastPos = -1 self.dirList = [] self.currentFolder = currentFolder canvas.setMinimumSize(canvas.size())
def __init__(self, scrollAreaWidgetContents, dataname): QtGui.QWidget.__init__(self) self.setParent(scrollAreaWidgetContents) fig = Figure((3.0, 2.0), dpi=100) canvas = FigureCanvas(fig) canvas.setParent(self) toolbar = myNavigationToolbar(canvas, self) temporal_toolbar = temporalNavigationToolbar(canvas, self) axes = fig.add_subplot(111) axes.autoscale(True) axes.set_yscale('log') axes.set_title(dataname) # place plot components in a layout plotLayout = QtGui.QVBoxLayout() plotLayout.addWidget(temporal_toolbar) plotLayout.addWidget(canvas) plotLayout.addWidget(toolbar) self.setLayout(plotLayout) canvas.setMinimumSize(canvas.size()) self.name = dataname self.dirList = [] self.dirType = 'Sampled Line' self.lastPos = -1 self.colors = ['r', 'b', 'k', 'g', 'y', 'c'] self.labels = ['_x','_y','_z']
def __init__(self, fig, parent=None): FigureCanvas.__init__(self, fig) FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) FigureCanvas.setMinimumSize(self, 400, 150) FigureCanvas.updateGeometry(self)
def __init__(self, scrollAreaWidgetContents, name): QtGui.QWidget.__init__(self) self.setParent(scrollAreaWidgetContents) fig = Figure((3.0, 2.0), dpi=100) canvas = FigureCanvas(fig) canvas.setParent(self) toolbar = myNavigationToolbar(canvas, self) axes = fig.add_subplot(111) axes.autoscale(True) axes.set_title(name) axes.set_xlabel('Time [s]') axes.set_ylabel('T') # place plot components in a layout plotLayout = QtGui.QVBoxLayout() plotLayout.addWidget(canvas) plotLayout.addWidget(toolbar) self.setLayout(plotLayout) self.dataPlot = [] self.dirList = [] self.dirType = 'Tracers' self.lastPos = -1 self.name = name self.colors = ['r', 'b', 'k', 'g', 'y', 'c'] # prevent the canvas to shrink beyond a point #original size looks like a good minimum size canvas.setMinimumSize(canvas.size())
def __init__(self, scrollAreaWidgetContents, currentFolder): QtGui.QWidget.__init__(self) self.setParent(scrollAreaWidgetContents) canvas = FigureCanvas(Figure((3.0, 2.0), dpi=100)) canvas.setParent(self) toolbar = myNavigationToolbar(canvas, self) toolbar.disableButtons() temporal_toolbar = temporalNavigationToolbar(canvas, self) mainImage = QtGui.QLabel(self) mainImage.setText(_fromUtf8("")) mainImage.setPixmap(QtGui.QPixmap(_fromUtf8(":/newPrefix/images/fromHelyx/emptyFigure.png"))) mainImage.setObjectName(_fromUtf8("mainImage")) mainImage.setScaledContents(True) mainImage.setSizePolicy(QtGui.QSizePolicy.Ignored,QtGui.QSizePolicy.Ignored) plotLayout = QtGui.QVBoxLayout() plotLayout.addWidget(temporal_toolbar) plotLayout.addWidget(mainImage,1) plotLayout.addWidget(toolbar,0,QtCore.Qt.AlignCenter) self.setLayout(plotLayout) self.lastPos = -1 self.dirList = [] self.currentFolder = currentFolder canvas.setMinimumSize(canvas.size())
def __init__(self, scrollAreaWidgetContents, name): QtGui.QWidget.__init__(self) self.setParent(scrollAreaWidgetContents) fig = Figure((3.0, 2.0), dpi=100) canvas = FigureCanvas(fig) canvas.setParent(self) toolbar = myNavigationToolbar(canvas, self) axes = fig.add_subplot(111) axes.autoscale(True) axes.set_yscale('log') axes.set_title(name) axes.set_xlabel('Time [s]') axes.set_ylabel('|R|') # place plot components in a layout plotLayout = QtGui.QVBoxLayout() plotLayout.addWidget(canvas) plotLayout.addWidget(toolbar) self.setLayout(plotLayout) self.dataPlot = [] self.dirList = [] self.dirType = 'Residuals' self.lastPos = -1 self.name = name self.colors = ['r', 'b', 'k', 'g', 'y', 'c'] # prevent the canvas to shrink beyond a point #original size looks like a good minimum size canvas.setMinimumSize(canvas.size())
def plot_file(fps, base_dir, string_graph_map): app = QtGui.QApplication('Bodysim') graph_map = ast.literal_eval(string_graph_map) # Find the length of the simulation by looking at trajectory results. start_frame = 1 count = 0 with open(base_dir + os.sep + 'Trajectory' + os.sep + graph_map.keys()[0] + '.csv') as f: iterF = iter(f) # Skip header next(iterF) line = next(iterF) start_frame = float(line.split(',')[0]) count = sum(1 for line in iterF) frame = MainWindow(start_frame, count) for sensor in graph_map: layout_contents = frame.add_tab(sensor) for plugin in graph_map[sensor]: data = get_data(base_dir + os.sep + plugin + os.sep + sensor + '.csv') for variable_group in graph_map[sensor][plugin]: qfigWidget = QtGui.QWidget(layout_contents[1]) fig = Figure((5.0, 4.0), dpi=100) canvas = FigureCanvas(fig) canvas.setParent(qfigWidget) toolbar = NavigationToolbar(canvas, qfigWidget) axes = fig.add_subplot(111) axes.set_title(plugin + ' ' + variable_group[2]) yDatum = [data[variable[1]] for variable in graph_map[sensor][plugin][variable_group]] yLabels = [variable[0] for variable in graph_map[sensor][plugin][variable_group]] for i in range(len(yDatum)): axes.plot(data[0], yDatum[i], label=yLabels[i]) axes.grid(True) axes.legend() axes.autoscale(enable=False, axis='both') axes.set_xlabel(variable_group[0]) axes.set_ylabel(variable_group[1]) # Place plot components in a layout plotLayout = QtGui.QVBoxLayout() plotLayout.addWidget(canvas) plotLayout.addWidget(toolbar) qfigWidget.setLayout(plotLayout) frame.toolbars[fig] = toolbar frame.plots.append(axes) canvas.setMinimumSize(canvas.size()) frame.bind_to_onclick_event(fig) layout_contents[0].addWidget(qfigWidget) frame.show() sys.exit(app.exec_())
class HistogramDialog(QDialog, FORM_CLASS): signalAskCloseWindow = pyqtSignal(int, name='signalAskCloseWindow') def __init__(self, parent=None): """Constructor.""" QDialog.__init__(self, parent) self.setupUi(self) # Connect slot. self.button_box.button(QDialogButtonBox.Ok).clicked.connect( self.draw_plot) self.button_box.button(QDialogButtonBox.Cancel).clicked.connect( self.hide) self.button_box.button(QDialogButtonBox.Cancel).clicked.connect( self.signalAskCloseWindow.emit) # Setup the graph. self.figure = Figure() self.ax = self.figure.add_subplot(1, 1, 1) self.canvas = FigureCanvas(self.figure) self.canvas.setMinimumSize(QSize(300, 0)) self.toolbar = CustomNavigationToolbar(self.canvas, self) self.layout_plot.addWidget(self.toolbar) self.layout_plot.addWidget(self.canvas) def draw_plot(self): """Function to draw the plot and display it in the canvas.""" index = self.cbx_layer.currentIndex() layer = self.cbx_layer.itemData(index) render = layer.rendererV2() for ran in render.ranges(): print "%f - %f: %s %s" % ( ran.lowerValue(), ran.upperValue(), ran.label(), str(ran.symbol()) ) bar_list = self.ax.bar([1, 2, 3, 4], [1, 2, 3, 4]) bar_list[0].set_color('r') bar_list[1].set_color('g') bar_list[2].set_color('b') self.canvas.draw()
class HistogramDialog(QDialog, FORM_CLASS): signalAskCloseWindow = pyqtSignal(int, name='signalAskCloseWindow') def __init__(self, parent=None): """Constructor.""" QDialog.__init__(self, parent) self.setupUi(self) # Connect slot. self.button_box.button(QDialogButtonBox.Ok).clicked.connect( self.draw_plot) self.button_box.button(QDialogButtonBox.Cancel).clicked.connect( self.hide) self.button_box.button(QDialogButtonBox.Cancel).clicked.connect( self.signalAskCloseWindow.emit) # Setup the graph. self.figure = Figure() self.ax = self.figure.add_subplot(1, 1, 1) self.canvas = FigureCanvas(self.figure) self.canvas.setMinimumSize(QSize(300, 0)) self.toolbar = CustomNavigationToolbar(self.canvas, self) self.layout_plot.addWidget(self.toolbar) self.layout_plot.addWidget(self.canvas) def draw_plot(self): """Function to draw the plot and display it in the canvas.""" index = self.cbx_layer.currentIndex() layer = self.cbx_layer.itemData(index) render = layer.rendererV2() for ran in render.ranges(): print "%f - %f: %s %s" % (ran.lowerValue(), ran.upperValue(), ran.label(), str(ran.symbol())) bar_list = self.ax.bar([1, 2, 3, 4], [1, 2, 3, 4]) bar_list[0].set_color('r') bar_list[1].set_color('g') bar_list[2].set_color('b') self.canvas.draw()
def __init__(self, parent=None): super(ExperimentResultWidget, self).__init__() self.tab = QtGui.QTabWidget() # Figure 1 figure = plt.figure() canvas = FigureCanvas(figure) canvas.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding) canvas.setMinimumSize(50, 50) toolbar = NavigationToolbar(canvas, self) toolbar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) widget = QtGui.QWidget() layout = QtGui.QVBoxLayout() layout.addWidget(canvas) layout.addWidget(toolbar) widget.setLayout(layout) self.tab.addTab(widget, 'Results') self.plot = figure # Tab 1 self.trackCountsTable = QtGui.QTableWidget() self.tab.addTab(self.trackCountsTable, 'Track Counts') # Tab 2 self.networkOverviewTable = QtGui.QTableWidget() self.tab.addTab(self.networkOverviewTable, 'Network Overview') # Tab 3 self.trackTerminationTable = QtGui.QTableWidget() self.trackInitiationTable = QtGui.QTableWidget() widget = QtGui.QWidget() layout = QtGui.QVBoxLayout() layout.addWidget(self.trackTerminationTable) layout.addWidget(self.trackInitiationTable) widget.setLayout(layout) self.tab.addTab(widget, 'Track Fragmentation') layout = QtGui.QVBoxLayout() layout.addWidget(self.tab) self.setLayout(layout)
def __init__(self, scrollAreaWidgetContents): QtGui.QWidget.__init__(self) self.setParent(scrollAreaWidgetContents) canvas = FigureCanvas(Figure((3.0, 2.0), dpi=100)) canvas.setParent(self) toolbar = myNavigationToolbar(canvas, self) toolbar.disableButtons() temporal_toolbar = temporalNavigationToolbar(canvas, self) mainImage = QtGui.QLabel(self) mainImage.setText(_fromUtf8("")) mainImage.setPixmap(QtGui.QPixmap(_fromUtf8(":/newPrefix/images/fromHelyx/emptyFigure.png"))) mainImage.setObjectName(_fromUtf8("mainImage")) plotLayout = QtGui.QVBoxLayout() plotLayout.addWidget(temporal_toolbar) plotLayout.addWidget(mainImage) plotLayout.addWidget(toolbar) self.setLayout(plotLayout) canvas.setMinimumSize(canvas.size())
class GUI(QtGui.QDialog): def __init__(self): super(GUI, self).__init__() # Pola pomocnicze do obsługi pętli self._generator = None self._timerId = None # Właściwe pola klasy self.serial = serial.Serial() self.data = np.array([[], [], []]) self.frames = 0; self.last_frame = 0; self.frames_lost = 0; self.window = 100 # Szerokość okna rysowanego sygnału # Ustawienia ramki self.frame_length = 30; # Długość ramki z danymi self.frame_markers = np.array([int('A5', 16), int('5a', 16)]) self.buffer = bytearray(self.frame_length - len(self.frame_markers)) # Elementy okna self.figure = plt.figure() self.canvas = FigureCanvas(self.figure) self.canvas.setMinimumSize(self.canvas.size()) self.serial_line = QtGui.QLineEdit(self) self.serial_line.setText('COM9') self.serial_line.setAlignment(QtCore.Qt.AlignCenter) self.serial_line.setMaxLength(30) self.serial_line_label = QtGui.QLabel("Port") self.serial_line_label.setAlignment(QtCore.Qt.AlignCenter) self.lost_frames_count = QtGui.QLineEdit(self) self.lost_frames_count.setText('0%') self.lost_frames_count.setAlignment(QtCore.Qt.AlignCenter) self.lost_frames_count.setMaxLength(30) self.lost_frames_label = QtGui.QLabel("Frames lost") self.lost_frames_label.setAlignment(QtCore.Qt.AlignCenter) self.start_button = self.createButton("Start", self.start) self.stop_button = self.createButton("Stop", self.stop) self.stop_button.setEnabled(False) self.info_line = QtGui.QLineEdit(self) self.info_line.setReadOnly(True) self.info_line.setAlignment(QtCore.Qt.AlignCenter) self.info_line.setMaxLength(30) self.info_line.setText('INFO') self.setWindowTitle('Signal Reader v.1.0') # Układanie layout'u layout = QtGui.QGridLayout() layout.setSizeConstraint(QtGui.QLayout.SetFixedSize) layout layout.addWidget(self.canvas, 0, 0, 1, 2) layout.addWidget(self.serial_line_label, 1, 0, 1, 2) layout.addWidget(self.serial_line, 2, 0, 1, 2) layout.addWidget(self.start_button, 3, 0, 1, 1) layout.addWidget(self.stop_button, 3, 1, 1, 1) layout.addWidget(self.lost_frames_label, 4, 0, 1, 2) layout.addWidget(self.lost_frames_count, 5, 0, 1, 2) layout.addWidget(self.info_line, 6, 0, 1, 2) self.setLayout(layout) self.setFigures() def setFigures(self): self.channel1 = self.figure.add_subplot(3, 1, 1) self.channel1.hold(True) self.channel1_data, = self.channel1.plot(np.zeros(self.window)) plt.ylim([0, 4096]) plt.title('Channel 1') plt.grid() plt.tight_layout(pad = 0.4, w_pad = 0.5, h_pad = 1.0) self.channel2 = self.figure.add_subplot(3, 1, 2) self.channel2.hold(True) self.channel2_data, = self.channel2.plot(np.zeros(self.window)) plt.ylim([0, 4096]) plt.title('Channel 2') plt.grid() plt.tight_layout(pad = 0.4, w_pad = 0.5, h_pad = 1.0) self.channel3 = self.figure.add_subplot(3, 1, 3) self.channel3.hold(True) self.channel3_data, = self.channel3.plot(np.zeros(self.window)) plt.ylim([0, 4096]) plt.title('Channel 3') plt.grid() plt.tight_layout(pad = 0.4, w_pad = 0.5, h_pad = 1.0) plt.ion() def start(self): # Aktywancja/deazktywacja przycisków self.start_button.setEnabled(False) self.stop_button.setEnabled(True) self.port = str(self.serial_line.text()) # Zapisuje nazwę portu if self._timerId is not None: self.killTimer(self._timerId) self.serial_line.setReadOnly(True) # Ustawia pole z portem na niezmienialne self._generator = self.readData() # Wchodzi do pętli wczytywania danych self._timerId = self.startTimer(0) def stop(self): # Aktywancja/deazktywacja przycisków self.start_button.setEnabled(True) self.stop_button.setEnabled(False) if self._timerId is not None: self.killTimer(self._timerId) self._generator = None self._timerId = None self.serial_line.setReadOnly(False) if(self.serial.isOpen()): self.serial.close() self.info_line.setText('STOP') def readData(self): ''' Metoda do czytania dancyh z podanego portu. ''' try: self.serial = serial.Serial(self.port) # Otwiera port self.info_line.setText('Reading data...') # Zmienia napis while (True): input = self.serial.read() # Czyta 1 bajt # Sprawdzenie czy jest starszym bajtem znacznika if(int.from_bytes(input, byteorder = 'big') == self.frame_markers[0]): # Czytanie kolejnego 1 bajtu input = self.serial.read() # Sprawdzenie czy następny jest młodszym bajtem znacznika if(int.from_bytes(input, byteorder = 'big') == self.frame_markers[1]): # Jeśli tak to znaczy, że mamy ramkę self.frames += 1 # Wczytujemy do struktury buffer (która jest tablicą # bajtów) 28 bajtów (bo taki został ustalony jej rozmiar) self.serial.readinto(self.buffer) # Zamiana tablicy bajtów na macierz liczb całkowitych self.buffer = np.array(self.buffer, dtype = np.int32); self.parseData() self.plot() self.buffer = bytearray(self.frame_length - 2) yield except serial.SerialException as ex: self.info_line.setText('Can\'t open the serial port!') def parseData(self): ''' Metoda analizująca pobraną ramkę z danymi. ''' if(self.last_frame == 0): self.last_frame = self.buffer[0] * 256 + self.buffer[1] else: frame = self.buffer[0] * 256 + self.buffer[1] if(frame - 1 != self.last_frame): self.frames_lost += 1 self.last_frame = frame self.lost_frames_count.setText(str(round(self.frames_lost / self.frames * 100, 2)) + '%') # Sprawdzanie sumy kontrolnej checksum = self.buffer[-2] * 256 + self.buffer[-1] sum = np.sum(self.buffer[:-2]) #----------------------------------------------------------------------- # Tutaj w warunku ustawić sum == checksum #----------------------------------------------------------------------- if(True): self.buffer = self.buffer[2:-2].reshape((-1, 2)) self.buffer[:, 0] *= 256 self.buffer = np.sum(self.buffer, 1) self.buffer = self.buffer.reshape((-1, 3)).T self.data = np.hstack((self.data, self.buffer)) def plot(self): if(self.data.shape[1] >= self.window): self.data = self.data[:, -self.window:] self.channel1_data.set_ydata(self.data[0]) self.channel2_data.set_ydata(self.data[1]) self.channel3_data.set_ydata(self.data[2]) self.canvas.draw() def timerEvent(self, event): if self._generator is None: return try: next(self._generator) except StopIteration: self.stop() def closeEvent(self, event): self.stop() event.accept() def createButton(self, text, member): button = Button(text) button.clicked.connect(member) return button
class Amoeba_Line_Graph(): def __init__(self): """ This class is for the plot on each of the parameter UIs. """ #Generate plot x = [] y = [] self.fig = Figure(figsize=(8,4),dpi=72, facecolor=(1,1,1), edgecolor=(0,0,0)) self.sub_plot = self.fig.add_subplot(111) self.sub_plot.xaxis_date() if AMOEBA_LINE_GRAPH_DEBUG: print "X = " print x print "Y = " print y print "Create " print self.sub_plot.plot self.sub_plot.plot(y,x,'b') self.sub_plot.set_xlabel('Time') self.fig.autofmt_xdate() #Create canvas for the plot self.canvas = FigureCanvas(self.fig) self.canvas.setMinimumSize(self.canvas.size()) def update(self,datay,datax): """ This method updates the plot with the input data. :param datay: Y axis of the points to plot. :param datax: X axis of the points to plot. """ if AMOEBA_LINE_GRAPH_DEBUG: print "Update sub plot" print "X = " print datax print "Y = " print datay print "Update " print self.sub_plot.plot # Clear the graph. self.clear_graph() self.sub_plot.plot(datax,datay,'b') self.sub_plot.set_visible(True) self.sub_plot.autoscale(True,"both") self.canvas.draw() def retrieve_graph(self): """ This method returns the plot's widget. :return: """ return self.canvas def clear_graph(self): """ This method clears the graph. """ y = [] x = [] self.sub_plot.clear() self.sub_plot.set_visible(True) self.sub_plot.autoscale(True,"both",False) self.sub_plot.plot(y,x,'b') self.canvas.draw()
class HistogramQWidget(QtGui.QWidget): """ QT wrapper for matplotlib """ def __init__(self, parent=None): """ setup GUI """ self.data = None self.value = 0 QtGui.QWidget.__init__(self, parent) self.my_layout = QtGui.QGridLayout(self) #self.my_layout.setMargin(0) self.my_layout.setSpacing(10) # set up matplotlib self.dpi = 100 self.fig = Figure((6.0, 6.0), dpi=self.dpi) self.canvas = FigureCanvas(self.fig) self.canvas.setMinimumSize(300, 100) self.canvas.mpl_connect('button_press_event', self.on_click) #self.canvas.setParent(self) self.my_layout.addWidget(self.canvas, 0, 0, 1, 2) self.axes = self.fig.add_subplot(111) self.cax = None # add spin box self.spin_label = QtGui.QLabel(self) self.spin_label.setText('Value:') self.my_layout.addWidget(self.spin_label, 1, 0) self.spin = QtGui.QDoubleSpinBox(self) self.spin.setMinimum(0.0) self.spin.setMaximum(1000.0) #self.spin.setFocusPolicy(QtCore.Qt.NoFocus) self.spin.setSingleStep(10) self.spin.setKeyboardTracking(False) self.spin.setReadOnly(False) self.my_layout.addWidget(self.spin, 1, 1) # connect signals self.connect(self.spin, QtCore.SIGNAL('valueChanged(double)'), self.update_value) def on_click(self, event): """ process click from matplotlib """ print 'button=%d, x=%d, y=%d, xdata=%f, ydata=%f'%(event.button, event.x, event.y, event.xdata, event.ydata) self.update_value(float(event.xdata)) def update_value(self, v): """ update plot """ self.value = v self.spin.setValue(self.value) self.update_plot() self.emit(QtCore.SIGNAL('thresholdChanged(double)'), self.value) def update_dataset(self, dataset): """ wrapper for update value """ #TODO this can go in subclass self.value = dataset.threshold self.data = dataset.red_channel.flatten() self.update_plot() self.spin.blockSignals(True) self.spin.setValue(self.value) self.spin.blockSignals(False) def update_plot(self): """ plotting routine """ print "updating histogram plot" self.axes.clear() self.axes.hist(self.data, bins=100, range=(min(self.data), max(self.data))) self.axes.axvline(x=self.value, linewidth=1, color='r') self.canvas.draw()
class SimpleSlicerQWidget(QtGui.QWidget): """ QT wrapper for matplotlib """ def __init__(self, parent=None): """ setup GUI """ self.dataset = None self.ellipse_stack = None self.active_layer = 0 QtGui.QWidget.__init__(self, parent) self.my_layout = QtGui.QVBoxLayout(self) #self.my_layout.setContentsMargin(0) self.my_layout.setSpacing(0) # set up matplotlib self.dpi = 100 self.fig = Figure((6.0, 6.0), dpi=self.dpi) self.canvas = FigureCanvas(self.fig) self.canvas.setMinimumSize(800, 400) #self.canvas.setParent(self) self.my_layout.addWidget(self.canvas) self.axes = self.fig.add_subplot(121) self.axes_green = self.fig.add_subplot(122) self.cax = None #slider self.sld = QtGui.QSlider(QtCore.Qt.Horizontal, self) self.sld.setFocusPolicy(QtCore.Qt.NoFocus) self.sld.setMinimum(0) #self.sld.setGeometry(30, 40, 100, 30) #sld.valueChanged[int].connect(self.changeValue) self.my_layout.addWidget(self.sld) self.connect(self.sld, QtCore.SIGNAL('valueChanged(int)'), self.update_active_layer) def update_dataset(self, dataset): """ update plot """ self.dataset = dataset new_max = self.dataset.volume.shape[2] - 1 self.sld.setMaximum(new_max) self.update_plot() def update_active_layer(self, idx_z): """ update active layer """ self.active_layer = idx_z self.update_plot() def update_plot(self): """ plotting routine """ channel1 = self.dataset.volume[:,:,self.active_layer].T channel2 = self.dataset.green_channel[:,:,self.active_layer].T self.axes.clear() self.axes_green.clear() self.axes.imshow(channel1, interpolation="nearest") self.axes_green.imshow(channel2, interpolation="nearest", cmap=cm.Greys_r) if self.dataset.stack: n = 50 z = int(self.active_layer) # check if ellipse is available for layer if self.dataset.stack.has_key(z): e = self.dataset.stack[z] dat = e.sample_equidistant(n) self.axes.plot(dat[0], dat[1], "b-", scalex=False, scaley=False) self.axes_green.plot(dat[0], dat[1], "b-", scalex=False, scaley=False) offset = self.dataset.radius_offset # plot manual offset in red if offset != 0: e_off = copy.copy(e) e_off.rx += offset e_off.ry += offset dat_off = e_off.sample_equidistant(n) self.axes.plot(dat_off[0], dat_off[1], "r-", scalex=False, scaley=False) self.axes_green.plot(dat_off[0], dat_off[1], "r-", scalex=False, scaley=False) self.canvas.draw()
class IncidenceDensityDialog(QDialog): signalAskCloseWindow = pyqtSignal(int, name='signalAskCloseWindow') signalStatus = pyqtSignal(int, str, name='signalStatus') def __init__(self, parent=None): """Constructor. Base class for Incidence and Density dialogs. use_area : If you use the area of the polygon or the population field. use_point_layer : If you a point a layer, or a field in the polygon layer. """ self.parent = parent QDialog.__init__(self, parent) self.name_field = None self.admin_layer = None self.figure = None self.canvas = None self.toolbar = None self.output_file_path = None self.output_layer = None # Settings self.use_area = None self.use_point_layer = None def setup_ui(self): # Connect slot. # noinspection PyUnresolvedReferences self.button_browse.clicked.connect(self.open_file_browser) self.button_box_ok.button(QDialogButtonBox.Ok).clicked.connect( self.run_stats) self.button_box_ok.button(QDialogButtonBox.Cancel).clicked.connect( self.hide) self.button_box_ok.button(QDialogButtonBox.Cancel).clicked.connect( self.signalAskCloseWindow.emit) # Add items in symbology self.cbx_mode.addItem('Equal interval', QgsGraduatedSymbolRendererV2.EqualInterval) self.cbx_mode.addItem('Quantile (equal count)', QgsGraduatedSymbolRendererV2.Quantile) self.cbx_mode.addItem('Natural breaks', QgsGraduatedSymbolRendererV2.Jenks) self.cbx_mode.addItem('Standard deviation', QgsGraduatedSymbolRendererV2.StdDev) self.cbx_mode.addItem('Pretty breaks', QgsGraduatedSymbolRendererV2.Pretty) # Setup the graph. self.figure = Figure() self.canvas = FigureCanvas(self.figure) self.canvas.setMinimumSize(QSize(300, 0)) self.toolbar = CustomNavigationToolbar(self.canvas, self) self.layout_plot.addWidget(self.toolbar) self.layout_plot.addWidget(self.canvas) self.cbx_aggregation_layer.setFilters( QgsMapLayerProxyModel.PolygonLayer) if self.use_point_layer: self.cbx_case_layer.setFilters(QgsMapLayerProxyModel.PointLayer) if not self.use_area: self.cbx_population_field.setLayer( self.cbx_aggregation_layer.currentLayer()) self.cbx_aggregation_layer.layerChanged.connect( self.cbx_population_field.setLayer) self.cbx_aggregation_layer.layerChanged.connect( self.reset_field_population) self.reset_field_population() if not self.use_point_layer: self.cbx_case_field.setLayer( self.cbx_aggregation_layer.currentLayer()) self.cbx_aggregation_layer.layerChanged.connect( self.cbx_case_field.setLayer) self.cbx_aggregation_layer.layerChanged.connect( self.reset_field_case) self.reset_field_case() def reset_field_population(self): self.cbx_population_field.setCurrentIndex(0) def reset_field_case(self): self.cbx_case_field.setCurrentIndex(0) def open_file_browser(self): output_file = QFileDialog.getSaveFileNameAndFilter( self.parent, tr('Save shapefile'), filter='SHP (*.shp)') self.le_output_filepath.setText(output_file[0]) def run_stats(self): """Main function which do the process.""" # Get the common fields. self.admin_layer = self.cbx_aggregation_layer.currentLayer() if self.use_point_layer: # If we use a point layer. point_layer = self.cbx_case_layer.currentLayer() else: # If we use a column with number of case. case_column = self.cbx_case_field.currentField() index_case = self.admin_layer.fieldNameIndex(case_column) if not self.use_area: # If we don't use density. population = self.cbx_population_field.currentField() index_population = self.admin_layer.fieldNameIndex(population) if not self.name_field: self.name_field = self.le_new_column.placeholderText() # Add new column. add_nb_intersections = self.checkBox_addNbIntersections.isChecked() # Ratio ratio = self.cbx_ratio.currentText() ratio = ratio.replace(' ', '') # Output. self.output_file_path = self.le_output_filepath.text() try: self.button_box_ok.setDisabled(True) # noinspection PyArgumentList QApplication.setOverrideCursor(Qt.WaitCursor) # noinspection PyArgumentList QApplication.processEvents() if not self.admin_layer: raise NoLayerProvidedException if not self.admin_layer and self.use_point_layer: raise NoLayerProvidedException crs_admin_layer = self.admin_layer.crs() if self.use_point_layer: crs_point_layer = point_layer.crs() if crs_admin_layer != crs_point_layer: raise DifferentCrsException(epsg1=crs_point_layer.authid(), epsg2=crs_admin_layer.authid()) if not self.use_point_layer and not self.use_area: if index_population == index_case: raise FieldException(field_1='Population', field_2='Case') try: ratio = float(ratio) except ValueError: raise NotANumberException(suffix=ratio) # Output if not self.output_file_path: temp_file = NamedTemporaryFile(delete=False, suffix='-geohealth.shp') self.output_file_path = temp_file.name temp_file.flush() temp_file.close() admin_layer_provider = self.admin_layer.dataProvider() fields = admin_layer_provider.fields() if admin_layer_provider.fieldNameIndex(self.name_field) != -1: raise FieldExistingException(field=self.name_field) fields.append(QgsField(self.name_field, QVariant.Double)) if add_nb_intersections: fields.append(QgsField('nb_of_intersections', QVariant.Int)) data = [] file_writer = QgsVectorFileWriter(self.output_file_path, 'utf-8', fields, QGis.WKBPolygon, self.admin_layer.crs(), 'ESRI Shapefile') if self.use_point_layer: total_case = point_layer.featureCount() else: total_case = 0 for i, feature in enumerate(self.admin_layer.getFeatures()): attributes = feature.attributes() if self.use_point_layer: count = 0 for f in point_layer.getFeatures(): if f.geometry().intersects(feature.geometry()): count += 1 else: count = int(attributes[index_case]) total_case += count try: if self.use_area: area = feature.geometry().area() value = float(count) / area * ratio else: try: population = float(attributes[index_population]) except ValueError: raise NotANumberException( suffix=attributes[index_population]) value = float(count) / population * ratio except ZeroDivisionError: value = None except TypeError: value = None data.append(value) attributes.append(value) if add_nb_intersections: attributes.append(count) new_feature = QgsFeature() new_geom = QgsGeometry(feature.geometry()) new_feature.setAttributes(attributes) new_feature.setGeometry(new_geom) file_writer.addFeature(new_feature) del file_writer self.output_layer = QgsVectorLayer(self.output_file_path, self.name_field, 'ogr') QgsMapLayerRegistry.instance().addMapLayer(self.output_layer) if self.checkBox_incidence_runStats.isChecked(): stats = Stats(data) items_stats = [ 'Incidence null,%d' % stats.null_values(), 'Count(point),%d' % total_case, 'Count(polygon),%d' % self.admin_layer.featureCount(), 'Min,%d' % stats.min(), 'Average,%f' % stats.average(), 'Max,%d' % stats.max(), 'Median,%f' % stats.median(), 'Range,%d' % stats.range(), 'Variance,%f' % stats.variance(), 'Standard deviation,%f' % stats.standard_deviation() ] self.tableWidget.clear() self.tableWidget.setColumnCount(2) labels = ['Parameters', 'Values'] self.tableWidget.setHorizontalHeaderLabels(labels) self.tableWidget.setRowCount(len(items_stats)) for i, item in enumerate(items_stats): s = item.split(',') self.tableWidget.setItem(i, 0, QTableWidgetItem(s[0])) self.tableWidget.setItem(i, 1, QTableWidgetItem(s[1])) self.tableWidget.resizeRowsToContents() self.draw_plot(data) else: self.hide() if self.symbology.isChecked(): self.add_symbology() self.signalStatus.emit(3, tr('Successful process')) except GeoHealthException, e: display_message_bar(msg=e.msg, level=e.level, duration=e.duration) finally:
class FilterDesignDialog(QtGui.QDialog): """A dialog to apply Takanami's AR picking method to a selected piece of a seismic signal. Attributes: document: Current opened document containing a seismic record. seismic_event: A seismic event to be refined by using Takanami method. If no event is provided, then a new seismic event will be created by using the estimated arrival time after clicking on 'Accept' """ def __init__(self, stream, trace_list=None, parent=None): super(FilterDesignDialog, self).__init__(parent) # Calc max. frequency traces = stream.traces if not trace_list else trace_list self.max_freq = max([trace.fs for trace in traces]) self._init_ui() self.load_settings() # Initial draw w, h_db, angles = self._retrieve_filter_plot_data() self._module_data = self.module_axes.plot(w, h_db, 'b')[0] self._phase_data = self.phase_axes.plot(w, angles, 'g')[0] self.module_axes.set_ylim([-60,10]) self.phase_axes.set_ylim([min(angles), max(angles)]) self.canvas.draw_idle() self.start_point_spinbox.valueChanged.connect(self.on_freq_min_changed) self.end_point_spinbox.valueChanged.connect(self.on_freq_max_changed) self.start_point_spinbox.valueChanged.connect(self._draw_filter_response) self.end_point_spinbox.valueChanged.connect(self._draw_filter_response) self.number_coefficient_spinbox.valueChanged.connect(self._draw_filter_response) self.zeroPhaseCheckBox.toggled.connect(self._draw_filter_response) self.button_box.accepted.connect(self.accept) self.button_box.rejected.connect(self.reject) self.button_box.clicked.connect(self.on_click) def _init_ui(self): self.setWindowTitle("Filter Design (Butterworth-Bandpass Filter)") self.fig, _ = plt.subplots(1, 1, sharex=True) # Set up filter axes self.module_axes = self.fig.axes[0] self.phase_axes = self.module_axes.twinx() self.module_axes.set_title('Digital filter frequency response (Butterworth-Bandpass filter)') self.module_axes.set_xlabel('Frequency [Hz]') self.module_axes.set_ylabel('Amplitude [dB]', color='b') self.module_axes.axis('tight') self.module_axes.grid(which='both', axis='both') self.phase_axes.set_ylabel('Angle (radians)', color='g') self.canvas = FigureCanvas(self.fig) self.canvas.setMinimumSize(self.canvas.size()) self.canvas.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Policy.Expanding, QtGui.QSizePolicy.Policy.Expanding)) self.toolBarNavigation = navigationtoolbar.NavigationToolBar(self.canvas, self) self.group_box = QtGui.QGroupBox(self) self.group_box2 = QtGui.QGroupBox(self) self.group_box3 = QtGui.QGroupBox(self) self.group_box4 = QtGui.QGroupBox(self) self.group_box.setTitle("") self.group_box2.setTitle("") self.group_box3.setTitle("Parameters") self.start_point_label = QtGui.QLabel("Lower cutoff frequency (Hz): ") self.start_point_label.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Policy.Maximum, QtGui.QSizePolicy.Policy.Preferred)) self.start_point_spinbox = QtGui.QDoubleSpinBox(self.group_box) self.start_point_spinbox.setMinimum(1.0) self.start_point_spinbox.setSingleStep(1.00) self.start_point_spinbox.setAccelerated(True) self.start_point_spinbox.setMaximum(self.max_freq * 0.5) self.end_point_label = QtGui.QLabel("Higher cutoff frequency (Hz):") self.end_point_label.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Policy.Maximum, QtGui.QSizePolicy.Policy.Preferred)) self.end_point_spinbox = QtGui.QDoubleSpinBox(self.group_box4) self.end_point_spinbox.setMinimum(1.0) self.end_point_spinbox.setSingleStep(1.00) self.end_point_spinbox.setAccelerated(True) self.end_point_spinbox.setMaximum(self.max_freq * 0.5) self.end_point_spinbox.setValue(5.0) ####################################################################### self.number_coefficient_label = QtGui.QLabel("Order: ") self.number_coefficient_label2 = QtGui.QLabel("") self.number_coefficient_label.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Policy.Maximum, QtGui.QSizePolicy.Policy.Preferred)) self.number_coefficient_label2.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Policy.Maximum, QtGui.QSizePolicy.Policy.Preferred)) self.number_coefficient_spinbox = QtGui.QSpinBox(self.group_box3) self.number_coefficient_spinbox.adjustSize() self.number_coefficient_spinbox.setMinimum(1) self.number_coefficient_spinbox.setSingleStep(1) self.number_coefficient_spinbox.setAccelerated(True) self.zeroPhaseCheckBox = QtGui.QCheckBox("Zero phase filtering", self.group_box2) self.zeroPhaseCheckBox.setChecked(True) ####################################################################### self.group_box_layout = QtGui.QHBoxLayout(self.group_box) self.group_box_layout.setContentsMargins(9, 9, 9, 9) self.group_box_layout.setSpacing(12) self.group_box_layout.addWidget(self.start_point_label) self.group_box_layout.addWidget(self.start_point_spinbox) self.group_box4_layout = QtGui.QHBoxLayout(self.group_box4) self.group_box4_layout.setContentsMargins(9, 9, 9, 9) self.group_box4_layout.setSpacing(12) self.group_box4_layout.addWidget(self.end_point_label) self.group_box4_layout.addWidget(self.end_point_spinbox) ##################################################################### self.group_box2_layout = QtGui.QHBoxLayout(self.group_box2) self.group_box2_layout.setContentsMargins(9, 9, 9, 9) self.group_box2_layout.setSpacing(12) self.group_box2_layout.addWidget(self.zeroPhaseCheckBox) ################################################################### self.group_box3_layout = QtGui.QHBoxLayout(self.group_box3) self.group_box3_layout.setContentsMargins(9, 9, 9, 9) self.group_box3_layout.setSpacing(12) self.group_box3_layout.addWidget(self.number_coefficient_label) self.group_box3_layout.addWidget(self.number_coefficient_spinbox) self.group_box3_layout.addWidget(self.number_coefficient_label2) ##################################################################### self.button_box = QtGui.QDialogButtonBox(self) self.button_box.setOrientation(QtCore.Qt.Horizontal) self.button_box.setStandardButtons(QtGui.QDialogButtonBox.Apply | QtGui.QDialogButtonBox.Cancel | QtGui.QDialogButtonBox.Ok) self.layout = QtGui.QVBoxLayout(self) self.layout.setContentsMargins(9, 9, 9, 9) self.layout.setSpacing(6) self.layout.addWidget(self.toolBarNavigation) self.layout.addWidget(self.canvas) self.layout.addWidget(self.group_box3) self.layout.addWidget(self.group_box) self.layout.addWidget(self.group_box4) #self.layout.addWidget(self.group_box2) self.layout.addWidget(self.zeroPhaseCheckBox) self.layout.addWidget(self.button_box) def on_freq_min_changed(self, value): self.end_point_spinbox.setMinimum(value + 1.0) def on_freq_max_changed(self, value): self.start_point_spinbox.setMaximum(value - 1.0) def on_click(self, button): if self.button_box.standardButton(button) == QtGui.QDialogButtonBox.Ok: self.save_settings() if self.button_box.standardButton(button) == QtGui.QDialogButtonBox.Apply: self._draw_filter_response() def save_settings(self): """Save settings to persistent storage.""" settings = QtCore.QSettings(_organization, _application_name) settings.beginGroup("filterdesign_settings") #self.default_margin = int(float(settings.value('filterdesign_margin', 5.0)) * #self.record.fs) settings.setValue('freq_min', self.start_point_spinbox.value()) settings.setValue('freq_max', self.end_point_spinbox.value()) settings.setValue('coef_number', self.number_coefficient_spinbox.value()) settings.setValue('zero_phase', self.zeroPhaseCheckBox.isChecked()) settings.endGroup() def load_settings(self): """Loads settings from persistent storage.""" settings = QtCore.QSettings(_organization, _application_name) settings.beginGroup("filterdesign_settings") self.start_point_spinbox.setValue(float(settings.value('freq_min', 0.0))) self.end_point_spinbox.setValue(float(settings.value('freq_max', self.max_freq * 0.5))) self.number_coefficient_spinbox.setValue(int(settings.value('coef_number', 1))) self.zeroPhaseCheckBox.setChecked(bool(settings.value('zero_phase', True))) settings.endGroup() def _butter_bandpass(self, lowcut, highcut, fs, order=5): nyq = 0.5 * fs low = lowcut / nyq high = highcut / nyq b, a = butter(order, [low, high], btype='band') return b, a def _retrieve_filter_plot_data(self): b, a = self._butter_bandpass(self.start_point_spinbox.value(), self.end_point_spinbox.value(), self.max_freq, order=self.number_coefficient_spinbox.value()) #w, h = freqz(b, a) w, h = freqz(b, a,1024) angles = np.unwrap(np.angle(h)) #return (self.max_freq * 0.5 / np.pi) * w, 20 * np.log10(abs(h)), angles f= (self.max_freq/2)*(w/np.pi) return f, 20 * np.log10(abs(h)), angles def _draw_filter_response(self, *args, **kwargs): w, h_db, angles = self._retrieve_filter_plot_data() self._module_data.set_xdata(w) self._module_data.set_ydata(h_db) self._phase_data.set_xdata(w) self._phase_data.set_ydata(angles) self.phase_axes.set_ylim([min(angles), max(angles)]) self.canvas.draw_idle()
class ProbeGraphDisplay(object): """The ProbeGraphDisplay controls one tab of the Area Probe Graphs. The ProbeGraphDisplay handles generating a displaying a single graph. """ # the most data we are willing to plot in a scatter plot # this limit was determined experimentally on Eva's laptop for glance, may need to revisit this MAX_SCATTER_PLOT_DATA = 1e7 # the default number of bins for the histogram and density scatter plot DEFAULT_NUM_BINS = 100 # the display name of the probe, should be unique across all probes myName = None # plotting related controls figure = None canvas = None toolbar = None yCheckBox = None xDropDown = None yDropDown = None # internal objects to reference for info and data polygon = None point = None manager = None workspace = None queue = None document = None # internal values that control the behavior of plotting and controls xSelectedUUID = None ySelectedUUID = None uuidMap = None # this is needed because the drop downs can't properly handle objects as ids _stale = True # whether or not the plot needs to be redrawn def __init__(self, manager, qt_parent, workspace, queue, document, name_str): """build the graph tab controls :return: """ # hang on to our name self.myName = name_str # save the workspace and queue for use later self.manager = manager self.workspace = workspace self.queue = queue self.document = document # a figure instance to plot on self.figure = Figure(figsize=(3, 3), dpi=72) # this is the Canvas Widget that displays the `figure` # it takes the `figure` instance as a parameter to __init__ self.canvas = FigureCanvas(self.figure) self.canvas.setMinimumSize(100, 100) # make sure our figure is clear self.clearPlot() # make a matplotlib toolbar to attach to the graph self.toolbar = NavigationToolbar(self.canvas, qt_parent) # create our selection controls # the label for the x selection xLabel = QtWidgets.QLabel("X layer:") # the check box that turns on and off comparing to a y layer self.yCheckBox = QtWidgets.QCheckBox("vs Y layer:") self.yCheckBox.setToolTip( "Plot X layer data vs Y layer when this is checked.") self.yCheckBox.stateChanged.connect(self.vsChecked) # the drop down for selecting the x layer self.xDropDown = QtWidgets.QComboBox(qt_parent) self.xDropDown.setToolTip("The X layer data to use for plotting.") self.xDropDown.activated.connect(self.xSelected) # the drop down for selecting the y layer self.yDropDown = QtWidgets.QComboBox(qt_parent) self.yDropDown.setDisabled(True) self.yDropDown.setToolTip("The Y layer data to use for plotting.") self.yDropDown.activated.connect(self.ySelected) # set the layout # Note: add in a grid is (widget, row#, col#) or (widget, row#, col#, row_span, col_span) layout = QtWidgets.QGridLayout() layout.addWidget(self.toolbar, 1, 1, 1, 3) layout.addWidget(self.canvas, 2, 1, 1, 3) layout.addWidget(xLabel, 3, 1) layout.addWidget(self.xDropDown, 3, 2, 1, 2) layout.addWidget(self.yCheckBox, 4, 1) layout.addWidget(self.yDropDown, 4, 2, 1, 2) qt_parent.setLayout(layout) def set_possible_layers(self, uuid_list, do_rebuild_plot=False): """Given a list of layer UUIDs, set the names and UUIDs in the drop downs """ # make a uuid map because the mapping in a combo box doesn't work with objects self.uuidMap = {} # clear out the current lists self.xDropDown.clear() self.yDropDown.clear() # fill up our lists of layers for uuid in uuid_list: layer = self.document[uuid] layer_name = layer.get(Info.DISPLAY_NAME, "??unknown layer??") if layer.get(Info.KIND, None) == Kind.RGB: # skip RGB layers continue uuid_string = str(uuid) self.xDropDown.addItem(layer_name, uuid_string) self.yDropDown.addItem(layer_name, uuid_string) self.uuidMap[uuid_string] = uuid # if possible, set the selections back to the way they were need_rebuild = False xIndex = self.xDropDown.findData(str(self.xSelectedUUID)) if xIndex >= 0: # Selection didn't change self.xDropDown.setCurrentIndex(xIndex) elif self.xDropDown.count() > 0: # Setting to a new layer need_rebuild = True self.xSelectedUUID = self.uuidMap[self.xDropDown.itemData(0)] self.xDropDown.setCurrentIndex(0) else: # we had something selected but now there is nothing new to select need_rebuild = need_rebuild or self.xSelectedUUID is not None self.xSelectedUUID = None yIndex = self.yDropDown.findData(str(self.ySelectedUUID)) if yIndex >= 0: # Selection didn't change self.yDropDown.setCurrentIndex(yIndex) elif self.yDropDown.count() > 0: # Setting to a new layer need_rebuild = need_rebuild or self.yCheckBox.isChecked() self.ySelectedUUID = self.uuidMap[self.yDropDown.itemData(0)] self.yDropDown.setCurrentIndex(0) else: # we had something selected but now there is nothing new to select need_rebuild = need_rebuild or self.ySelectedUUID is not None self.ySelectedUUID = None # refresh the plot self._stale = need_rebuild if do_rebuild_plot: # Rebuild the plot (stale is used to determine if actual rebuild is needed) self.rebuildPlot() def set_default_layer_selections(self, *layer_uuids): # only set the defaults if we don't have a polygon yet if self.polygon is not None: return if len(layer_uuids) >= 1: xIndex = self.xDropDown.findData(str(layer_uuids[0])) if xIndex >= 0: self.xDropDown.setCurrentIndex(xIndex) self.xSelectedUUID = layer_uuids[0] else: LOG.error("Tried to set probe graph to non-existent layer: %s", layer_uuids[0]) if len(layer_uuids) >= 2: yIndex = self.xDropDown.findData(str(layer_uuids[1])) if yIndex >= 0: self.yDropDown.setCurrentIndex(yIndex) self.ySelectedUUID = layer_uuids[1] else: LOG.error("Tried to set probe graph to non-existent layer: %s", layer_uuids[1]) @property def checked(self): return self.yCheckBox.isChecked() @checked.setter def checked(self, is_checked): return self.yCheckBox.setChecked(is_checked) def xSelected(self): """The user selected something in the X layer list. """ oldXStr = str(self.xSelectedUUID) newXStr = self.xDropDown.itemData(self.xDropDown.currentIndex()) self.xSelectedUUID = self.uuidMap[newXStr] # regenerate the plot if oldXStr != newXStr: self._stale = True self.rebuildPlot() def ySelected(self): """The user selected something in the Y layer list.""" oldYStr = str(self.ySelectedUUID) newYStr = self.yDropDown.itemData(self.yDropDown.currentIndex()) self.ySelectedUUID = self.uuidMap[newYStr] # regenerate the plot if (oldYStr != newYStr) and self.yCheckBox.isChecked(): self._stale = True self.rebuildPlot() def vsChecked(self): """The vs check box was checked!""" # look at the state of the vs box and enable/disable the y drop down accordingly doPlotVS = self.yCheckBox.isChecked() self.yDropDown.setDisabled(not doPlotVS) # regenerate the plot self._stale = True self.rebuildPlot() def setPolygon(self, polygonPoints): """Set the polygon selection for this graph.""" self.polygon = polygonPoints # regenerate the plot self._stale = True self.rebuildPlot() # return our name to be used for the polygon name return self.myName def setPoint(self, coordinates, rebuild=True): self.point = coordinates self._stale = True # sometimes we set the point to be redrawn later if rebuild: self.rebuildPlot() def getName(self): """Accessor method for the graph's name.""" return self.myName def rebuildPlot(self): """Given what we currently know about the selection area and selected bands, rebuild our plot Note: This should be called only when the selections change in some way. """ if not self._stale: LOG.debug("Plot doesn't need to be rebuilt") return # should be be plotting vs Y? doPlotVS = self.yCheckBox.isChecked() task_name = "%s_%s_region_plotting" % (self.xSelectedUUID, self.ySelectedUUID) self.queue.add(task_name, self._rebuild_plot_task(self.xSelectedUUID, self.ySelectedUUID, self.polygon, self.point, plot_versus=doPlotVS), "Creating plot for region probe data", interactive=True) # Assume that the task gets resolved otherwise we might try to draw multiple times self._stale = False def _rebuild_plot_task(self, x_uuid, y_uuid, polygon, point_xy, plot_versus=False): # if we are plotting only x and we have a selected x and a polygon if not plot_versus and x_uuid is not None and polygon is not None: yield { TASK_DOING: 'Probe Plot: Collecting polygon data...', TASK_PROGRESS: 0.0 } # get the data and info we need for this plot data_polygon = self.workspace.get_content_polygon(x_uuid, polygon) unit_info = self.document[x_uuid][Info.UNIT_CONVERSION] data_polygon = unit_info[1](data_polygon) title = self.document[x_uuid][Info.DISPLAY_NAME] # get point probe value if point_xy: x_point = self.workspace.get_content_point(x_uuid, point_xy) x_point = unit_info[1](x_point) else: x_point = None # plot a histogram yield { TASK_DOING: 'Probe Plot: Creating histogram plot', TASK_PROGRESS: 0.25 } self.plotHistogram(data_polygon, title, x_point) # if we are plotting x vs y and have x, y, and a polygon elif plot_versus and x_uuid is not None and y_uuid is not None and polygon is not None: yield { TASK_DOING: 'Probe Plot: Collecting polygon data (layer 1)...', TASK_PROGRESS: 0.0 } # get the data and info we need for this plot x_info = self.document[x_uuid] y_info = self.document[y_uuid] name1 = x_info[Info.DISPLAY_NAME] name2 = y_info[Info.DISPLAY_NAME] hires_uuid = self.workspace.lowest_resolution_uuid(x_uuid, y_uuid) # hires_coord_mask are the lat/lon coordinates of each of the # pixels in hires_data. The coordinates are (lat, lon) to resemble # the (Y, X) indexing of numpy arrays hires_coord_mask, hires_data = self.workspace.get_coordinate_mask_polygon( hires_uuid, polygon) hires_conv_func = self.document[hires_uuid][ Info.UNIT_CONVERSION][1] x_conv_func = x_info[Info.UNIT_CONVERSION][1] y_conv_func = y_info[Info.UNIT_CONVERSION][1] hires_data = hires_conv_func(hires_data) yield { TASK_DOING: 'Probe Plot: Collecting polygon data (layer 2)...', TASK_PROGRESS: 0.15 } if hires_uuid == x_uuid: # the hires data was from the X UUID data1 = hires_data data2 = self.workspace.get_content_coordinate_mask( y_uuid, hires_coord_mask) data2 = y_conv_func(data2) else: # the hires data was from the Y UUID data2 = hires_data data1 = self.workspace.get_content_coordinate_mask( x_uuid, hires_coord_mask) data1 = x_conv_func(data1) yield { TASK_DOING: 'Probe Plot: Creating scatter plot...', TASK_PROGRESS: 0.25 } if point_xy: x_point = self.workspace.get_content_point(x_uuid, point_xy) x_point = x_conv_func(x_point) y_point = self.workspace.get_content_point(y_uuid, point_xy) y_point = y_conv_func(y_point) else: x_point = None y_point = None # plot a scatter plot good_mask = ~(np.isnan(data1) | np.isnan(data2)) data1 = data1[good_mask] data2 = data2[good_mask] self.plotDensityScatterplot(data1, name1, data2, name2, x_point, y_point) # if we have some combination of selections we don't understand, clear the figure else: yield { TASK_DOING: 'Probe Plot: Clearing plot figure...', TASK_PROGRESS: 0.0 } self.clearPlot() yield {TASK_DOING: 'Probe Plot: Drawing plot...', TASK_PROGRESS: 0.95} self.manager.drawChildGraph.emit(self.myName) yield {TASK_DOING: 'Probe Plot: Done', TASK_PROGRESS: 1.0} def draw(self): self.canvas.draw() def plotHistogram(self, data, title, x_point, numBins=100): """Make a histogram using the given data and label it with the given title """ self.figure.clf() axes = self.figure.add_subplot(111) bars = axes.hist(data[~np.isnan(data)], bins=self.DEFAULT_NUM_BINS) if x_point is not None: # go through each rectangle object and make the one that contains x_point 'red' # default color is blue so red should stand out for bar in bars[2][::-1]: if bar.xy[0] <= x_point: bar.set_color('red') break axes.set_title(title) def plotScatterplot(self, dataX, nameX, dataY, nameY): """Make a scatter plot of the x and y data """ # we should have the same size data here assert (dataX.size == dataY.size) if dataX.size > self.MAX_SCATTER_PLOT_DATA: LOG.info( "Too much data in selected region to generate scatter plot.") self.clearPlot() # self.plotDensityScatterplot(dataX, nameX, dataY, nameY) else: self.figure.clf() axes = self.figure.add_subplot(111) axes.scatter(dataX, dataY, color='b', s=1, alpha=0.5) axes.set_xlabel(nameX) axes.set_ylabel(nameY) axes.set_title(nameX + " vs " + nameY) self._draw_xy_line(axes) def plotDensityScatterplot(self, dataX, nameX, dataY, nameY, pointX, pointY): """Make a density scatter plot for the given data """ # clear the figure and make a new subplot self.figure.clf() axes = self.figure.add_subplot(111) # figure out the range of the data # you might not be comparing the same units xmin_value = np.min(dataX) xmax_value = np.max(dataX) ymin_value = np.min(dataY) ymax_value = np.max(dataY) # bounds should be defined in the form [[xmin, xmax], [ymin, ymax]] bounds = [[xmin_value, xmax_value], [ymin_value, ymax_value]] # make the binned density map for this data set density_map, _, _ = np.histogram2d(dataX, dataY, bins=self.DEFAULT_NUM_BINS, range=bounds) # mask out zero counts; flip because y goes the opposite direction in an imshow graph density_map = np.flipud( np.transpose(np.ma.masked_array(density_map, mask=density_map == 0))) # display the density map data img = axes.imshow( density_map, extent=[xmin_value, xmax_value, ymin_value, ymax_value], aspect='auto', interpolation='nearest', norm=LogNorm()) if pointX is not None: axes.set_autoscale_on(False) axes.plot(pointX, pointY, marker='o', markerfacecolor='white', markeredgecolor='black', markersize=10, markeredgewidth=1.) axes.set_autoscale_on(True) colorbar = self.figure.colorbar(img) colorbar.set_label('log(count of data points)') # set the various text labels axes.set_xlabel(nameX) axes.set_ylabel(nameY) axes.set_title(nameX + " vs " + nameY) # draw the x vs y line self._draw_xy_line(axes) def clearPlot(self): """Clear our plot """ self.figure.clf() def _draw_xy_line(self, axes): # get the bounds for our calculations and so we can reset the viewing window later x_bounds = axes.get_xbound() y_bounds = axes.get_ybound() # draw the x=y line perfect = [ max(x_bounds[0], y_bounds[0]), min(x_bounds[1], y_bounds[1]) ] axes.plot(perfect, perfect, '--', color='k', label='X = Y') # reset the bounds axes.set_xbound(x_bounds) axes.set_ybound(y_bounds)
def plot_file(fps, base_dir, string_graph_map): app = QtGui.QApplication('Bodysim') graph_map = ast.literal_eval(string_graph_map) # Find the length of the simulation by looking at trajectory results. start_frame = 1 count = 0 with open(base_dir + os.sep + 'Trajectory' + os.sep + graph_map.keys()[0] + '.csv') as f: iterF = iter(f) # Skip header next(iterF) line = next(iterF) start_frame = float(line.split(',')[0]) count = sum(1 for line in iterF) frame = MainWindow(start_frame, count) for sensor in graph_map: layout_contents = frame.add_tab(sensor) for plugin in graph_map[sensor]: data = get_data(base_dir + os.sep + plugin + os.sep + sensor + '.csv') for variable_group in graph_map[sensor][plugin]: qfigWidget = QtGui.QWidget(layout_contents[1]) fig = Figure((5.0, 4.0), dpi=100) canvas = FigureCanvas(fig) canvas.setParent(qfigWidget) toolbar = NavigationToolbar(canvas, qfigWidget) axes = fig.add_subplot(111) axes.set_title(plugin + ' ' + variable_group[2]) yDatum = [ data[variable[1]] for variable in graph_map[sensor][plugin][variable_group] ] yLabels = [ variable[0] for variable in graph_map[sensor][plugin][variable_group] ] for i in range(len(yDatum)): axes.plot(data[0], yDatum[i], label=yLabels[i]) axes.grid(True) axes.legend() axes.autoscale(enable=False, axis='both') axes.set_xlabel(variable_group[0]) axes.set_ylabel(variable_group[1]) # Place plot components in a layout plotLayout = QtGui.QVBoxLayout() plotLayout.addWidget(canvas) plotLayout.addWidget(toolbar) qfigWidget.setLayout(plotLayout) frame.toolbars[fig] = toolbar frame.plots.append(axes) canvas.setMinimumSize(canvas.size()) frame.bind_to_onclick_event(fig) layout_contents[0].addWidget(qfigWidget) frame.show() sys.exit(app.exec_())
class TakanamiDialog(QtGui.QDialog): """A dialog to apply Takanami's AR picking method to a selected piece of a seismic signal. Attributes: document: Current opened document containing a seismic record. seismic_event: A seismic event to be refined by using Takanami method. If no event is provided, then a new seismic event will be created by using the estimated arrival time after clicking on 'Accept' """ def __init__(self, document, t_start=None, t_end=None, seismic_event=None, parent=None): super(TakanamiDialog, self).__init__(parent) self.document = document self.record = self.document.record self.load_settings() self.seismic_event = seismic_event self._start = t_start self._end = t_end if self.seismic_event is not None: self.event_time = self.seismic_event.time if self._start is None: self._start = max(0, self.event_time - self.default_margin) if self._end is None: self._end = min( len(self.record.signal) - 1, self.event_time + self.default_margin) else: if self._start is None or self._end is None: raise ValueError("t_start and t_end values not specified") else: self._start = max(0, int(t_start * self.record.fs)) self._end = min( len(self.record.signal) - 1, int(t_end * self.record.fs)) self.event_time = self._start + int( (self._end - self._start) / 2) if not 0 <= self._start < self._end: raise ValueError("Invalid t_start value") if not self._start < self._end < len(self.record.signal): raise ValueError("Invalid t_end value") if (self._end - self._start) < (MINIMUM_MARGIN_IN_SECS * self.record.fs): raise ValueError("Distance between t_start and t_end must be" " at least of %g seconds" % MINIMUM_MARGIN_IN_SECS) if not self._start < self.event_time < self._end: raise ValueError( "Event time must be a value between t-start and t_end") self._init_ui() self.button_box.accepted.connect(self.accept) self.button_box.rejected.connect(self.reject) self.button_box.clicked.connect(self.on_click) self.start_point_spinbox.timeChanged.connect( self.on_start_point_changed) self.end_point_spinbox.timeChanged.connect(self.on_end_point_changed) def _init_ui(self): self.setWindowTitle("Takanami's Autoregressive Method") self.fig, _ = plt.subplots(2, 1, sharex=True) self.canvas = FigureCanvas(self.fig) self.canvas.setMinimumSize(self.canvas.size()) self.canvas.setSizePolicy( QtGui.QSizePolicy(QtGui.QSizePolicy.Policy.Expanding, QtGui.QSizePolicy.Policy.Expanding)) self.toolBarNavigation = navigationtoolbar.NavigationToolBar( self.canvas, self) self.position_label = QtGui.QLabel( "Estimated Arrival Time: 00 h 00 m 00.000 s") self.group_box = QtGui.QGroupBox(self) self.group_box.setTitle("Limits") self.start_point_label = QtGui.QLabel("Start point:") self.start_point_label.setSizePolicy( QtGui.QSizePolicy(QtGui.QSizePolicy.Policy.Maximum, QtGui.QSizePolicy.Policy.Preferred)) self.start_point_spinbox = QtGui.QTimeEdit(self.group_box) self.start_point_spinbox.setDisplayFormat("hh 'h' mm 'm' ss.zzz 's'") self.end_point_label = QtGui.QLabel("End point:") self.end_point_label.setSizePolicy( QtGui.QSizePolicy(QtGui.QSizePolicy.Policy.Maximum, QtGui.QSizePolicy.Policy.Preferred)) self.end_point_spinbox = QtGui.QTimeEdit(self.group_box) self.end_point_spinbox.setDisplayFormat("hh 'h' mm 'm' ss.zzz 's'") self.group_box_layout = QtGui.QHBoxLayout(self.group_box) self.group_box_layout.setContentsMargins(9, 9, 9, 9) self.group_box_layout.setSpacing(12) self.group_box_layout.addWidget(self.start_point_label) self.group_box_layout.addWidget(self.start_point_spinbox) self.group_box_layout.addWidget(self.end_point_label) self.group_box_layout.addWidget(self.end_point_spinbox) self.button_box = QtGui.QDialogButtonBox(self) self.button_box.setOrientation(QtCore.Qt.Horizontal) self.button_box.setStandardButtons(QtGui.QDialogButtonBox.Apply | QtGui.QDialogButtonBox.Cancel | QtGui.QDialogButtonBox.Ok) self.layout = QtGui.QVBoxLayout(self) self.layout.setContentsMargins(9, 9, 9, 9) self.layout.setSpacing(6) self.layout.addWidget(self.toolBarNavigation) self.layout.addWidget(self.canvas) self.layout.addWidget(self.position_label) self.layout.addWidget(self.group_box) self.layout.addWidget(self.button_box) # set spinboxes's initial values and limits max_time_in_msecs = int( ((len(self.record.signal) - 1) * 1000) / self.record.fs) start_time_in_msecs = int((self._start * 1000.0) / self.record.fs) end_time_in_msecs = int((self._end * 1000.0) / self.record.fs) self.start_point_spinbox.setTime( QtCore.QTime().addMSecs(start_time_in_msecs)) self.end_point_spinbox.setTime( QtCore.QTime().addMSecs(end_time_in_msecs)) self.start_point_spinbox.setMinimumTime(QtCore.QTime().addMSecs(0)) self.end_point_spinbox.setMinimumTime( QtCore.QTime().addMSecs(start_time_in_msecs + MINIMUM_MARGIN_IN_SECS * 1000)) self.start_point_spinbox.setMaximumTime( QtCore.QTime().addMSecs(end_time_in_msecs - MINIMUM_MARGIN_IN_SECS * 1000)) self.end_point_spinbox.setMaximumTime( QtCore.QTime().addMSecs(max_time_in_msecs)) def on_click(self, button): if self.button_box.standardButton(button) == QtGui.QDialogButtonBox.Ok: self.save_event() if self.button_box.standardButton( button) == QtGui.QDialogButtonBox.Apply: self.do_takanami() def on_start_point_changed(self, value): time_in_msecs = QtCore.QTime().msecsTo(value) t_start = int(max(0, (time_in_msecs / 1000.0) * self.record.fs)) if self._start != t_start: self._start = t_start self.end_point_spinbox.setMinimumTime( QtCore.QTime().addMSecs(time_in_msecs + MINIMUM_MARGIN_IN_SECS * 1000)) def on_end_point_changed(self, value): time_in_msecs = QtCore.QTime().msecsTo(value) t_end = int( min(len(self.record.signal), ((time_in_msecs / 1000.0) * self.record.fs))) if self._end != t_end: self._end = t_end self.start_point_spinbox.setMaximumTime( QtCore.QTime().addMSecs(time_in_msecs - MINIMUM_MARGIN_IN_SECS * 1000)) def on_position_estimated(self, time, aic, n0_aic): self.event_time = time time_in_msecs = QtCore.QTime().addMSecs( (self.event_time * 1000.0) / self.record.fs) self.position_label.setText( "Estimated Arrival Time: %s" % time_in_msecs.toString("hh 'h' mm 'm' ss.zzz 's'")) # Plot estimated arrival time m_event = rc.Event(self.record, time, aic=aic, n0_aic=n0_aic) m_event.plot_aic(show_envelope=True, num=self.fig.number) self.fig.canvas.draw_idle() def load_settings(self): """Loads settings from persistent storage.""" settings = QtCore.QSettings(_organization, _application_name) settings.beginGroup("takanami_settings") self.default_margin = int( float(settings.value('takanami_margin', 5.0)) * self.record.fs) settings.endGroup() def save_event(self): """""" if self.seismic_event is not None: if self.seismic_event.time != self.event_time: self.document.editEvent(self.seismic_event, time=self.event_time, method=rc.method_takanami, mode=rc.mode_automatic, status=rc.status_reported) else: self.document.createEvent(self.event_time, method=rc.method_takanami, mode=rc.mode_automatic, status=rc.status_reported) def do_takanami(self): self._task = TakanamiTask(self.record, self._start, self._end) self._task.position_estimated.connect(self.on_position_estimated) self.wait_dialog = processingdialog.ProcessingDialog( label_text="Applying Takanami's AR method...") self.wait_dialog.setWindowTitle("Event detection") return self.wait_dialog.run(self._task) def exec_(self, *args, **kwargs): return_code = self.do_takanami() if return_code == QtGui.QDialog.Accepted: return QtGui.QDialog.exec_(self, *args, **kwargs)
class ThresholdCacheWidget(QtGui.QWidget): def __init__(self, on_changed_ev, parent=None): super(ThresholdCacheWidget, self).__init__() self.on_changed_ev = on_changed_ev self.parent = parent self.histogram_figure = plt.figure() self.histogram_canvas = FigureCanvas(self.histogram_figure) self.histogram_canvas.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding) self.histogram_canvas.setMinimumSize(50, 50) self.histogram_toolbar = NavigationToolbar(self.histogram_canvas, parent) self.histogram_toolbar.coordinates = False self.histogram_toolbar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) self.image_figure = plt.figure() self.image_canvas = FigureCanvas(self.image_figure) self.image_canvas.setMinimumSize(50, 50) self.image_canvas.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding) self.image_toolbar = NavigationToolbar(self.image_canvas, parent) self.image_toolbar.coordinates = False self.image_toolbar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) gs = grd.GridSpec(3, 1) self.ax_objects = self.histogram_figure.add_subplot(gs[0, 0]) self.ax_area = self.histogram_figure.add_subplot(gs[1, 0], sharex=self.ax_objects) self.ax_image = self.image_figure.add_subplot(111) layout = QtGui.QGridLayout() q1 = QtGui.QLabel("<b>Choose Threshold</b>") layout.addWidget(q1, 0, 0, 1, 1) layout.addWidget(QtGui.QLabel("Click on either graph to pick a threshold value"), 1, 0, 1, 1) layout.addWidget(self.histogram_canvas, 3, 0, 1, 1) layout.addWidget(self.histogram_toolbar, 4, 0, 1, 1) self.roiSelectorBar = ROISelectorBar(self.image_figure, self.ax_image) self.roiSelectorBar.roi_changed.connect(self.roiSelectorBar_roi_changed) self.calibrationBar = CalibrationBar(10, self.image_figure, self.ax_image) self.calibrationBar.calibration_changed.connect(self.calibrationBar_calibration_changed) q2 = QtGui.QLabel("<b>Define Region of Interest</b>") layout.addWidget(q2, 0, 1, 1, 1) layout.addWidget(self.roiSelectorBar, 1, 1, 1, 1) layout.addWidget(self.calibrationBar, 2, 1, 1, 1) layout.addWidget(self.image_canvas, 3, 1, 1, 1) layout.addWidget(self.image_toolbar, 4, 1, 1, 1) self.setLayout(layout) self.histogram_figure.canvas.mpl_connect('button_press_event', self.on_histogram_button_pressed) # self.image_figure.canvas.mpl_connect('button_press_event', self.on_image_button_pressed) self.thresholds = [] @staticmethod def create_background(impaths): """ create a background image for background subtraction. The background image is the maximum pixel values from three grayscale images. params --------- impaths: (list) this is a sorted list containing paths to all the image files from one recording. """ if len(impaths) == 0: return None first = mpimg.imread(impaths[0]) mid = mpimg.imread(impaths[int(len(impaths)/2)]) last = mpimg.imread(impaths[-1]) return np.maximum(np.maximum(first, mid), last) def clear_experiment_data(self): self.roiSelectorBar.clear_roi() self.threshold = 0.0005 def load_experiment(self, experiment): self.experiment = experiment self.annotation_filename = str(paths.threshold_data(experiment.id)) try: with open(self.annotation_filename, "rt") as f: data = json.loads(f.read()) # self.circle = None self.roiSelectorBar.json_to_data(data) self.threshold = data.get('threshold', 0.0005) except IOError as ex: self.clear_experiment_data() self.calibration_filename = str(paths.calibration_data(experiment.id)) try: with open(self.calibration_filename, "rt") as f: data = json.loads(f.read()) self.calibrationBar.json_to_data(data) except IOError as ex: self.calibrationBar.clear_calibration() times, impaths = zip(*sorted(experiment.image_files.items())) impaths = [str(s) for s in impaths] if times is not None and len(times) > 0: times = [float(t) for t in times] times, impaths = zip(*sorted(zip(times, impaths))) if impaths is None or len(impaths) == 0: self.background = None self.mid_image = None self.plate_distance = None self.roiSelectorBar.set_guess_polygon([]) else: self.background = ThresholdCacheWidget.create_background(impaths) self.im_shape = self.background.shape # shape is (y,x) self.mid_image = mpimg.imread(impaths[int(len(impaths)/2)]) self.plate_distance = PlateDistance(self.background) self.plate_distance.calculate() p = self.plate_distance.polygon(border=settings.ROI_BORDER_OFFSET, corner=settings.ROI_CORNER_OFFSET) p = [(y, x) for x, y in p] self.roiSelectorBar.set_guess_polygon(p) self.calibrationBar.update_plate_distance(self.plate_distance) self.mouse_points = [] QTimer.singleShot(0, self.show_dialog) def show_dialog(self): dlg = CacheThresholdLoadingDialog(self.experiment.id, self.calculate_threshold, self.finished, self.parent) dlg.setModal(True) dlg.exec_() def calculate_threshold(self, callback): self.thresholds = [] for i, t in enumerate(np.linspace(start=0.00001, stop=0.001, num=30)): valid, N, m, s = self.data_from_threshold(t) if valid: self.thresholds.append((t, N, m, s)) callback(0, i / 30.) callback(0, 1) def finished(self): self.update_data(self.thresholds, self.threshold) self.histogram_figure.canvas.draw() def isComplete(self): return self.roiSelectorBar.isComplete() def create_binary_mask(self, img, background, threshold, minsize=100): """ creates a binary array the same size as the image with 1s denoting objects and 0s denoting background. params -------- img: (image ie. numpy array) each pixel denotes greyscale pixel intensities. background: (image ie. numpy array) the background image with maximum pixel intensities (made with create_background) threshold: (float) the threshold value used to create the binary mask after pixel intensities for (background - image) have been calculated. minsize: (int) the fewest allowable pixels for an object. objects with an area containing fewer pixels are removed. """ if img is None or background is None: return None mask = (background - img) > threshold result = morphology.remove_small_objects(mask, minsize) return result def data_from_threshold(self, threshold): if self.mid_image is None: return False, None, None, None mask = self.create_binary_mask(self.mid_image, self.background, threshold=threshold) labels, N = ndimage.label(mask) sizes = [r.area for r in regionprops(labels)] if len(sizes) == 0: return False, None, None, None else: m, s = np.mean(sizes), np.std(sizes) return True, N, m, s @staticmethod def mkdir_p(path): try: os.makedirs(path) except OSError as exc: # Python >2.5 if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise def save_roi_data(self): if self.annotation_filename is None: return # note: the image is usually transposed. we didn't here, # so x and y are flipped during saving process. data = self.roiSelectorBar.data_to_json() data['threshold'] = self.threshold data['shape'] = self.im_shape ThresholdCacheWidget.mkdir_p(os.path.dirname(self.annotation_filename)) with open(self.annotation_filename, "wt") as f: f.write(json.dumps(data, indent=4)) def save_calibration_data(self): if self.calibration_filename is None: return data = self.calibrationBar.data_to_json() ThresholdCacheWidget.mkdir_p(os.path.dirname(self.calibration_filename)) with open(self.calibration_filename, "wt") as f: f.write(json.dumps(data, indent=4)) def update_data(self, thresholds, current_threshold): if len(thresholds) == 0: self.ax_objects.clear() self.ax_area.clear() self.ax_image.clear() self.line_objects = None self.line_area = None return x, ns, means, stds = zip(*thresholds) final_t = x[-1] # make the plot self.ax_objects.clear() self.ax_objects.plot(x, ns, '.-', color='black') self.ax_objects.set_ylabel('N Objects') self.ax_objects.set_ylim([0, 150]) top = np.array(means) + np.array(stds) bottom = np.array(means) - np.array(stds) self.ax_area.clear() self.ax_area.plot(x, means, '.-', color='blue', label='mean') self.ax_area.fill_between(x, top, bottom, color='green', alpha=0.5) # self.ax_area.plot(x, top, '--', color='green', label='mean') # self.ax_area.plot(x, bottom, '--', color='green', label='mean - std') self.ax_area.axvline(x=.5, ymin=0, ymax=1) self.ax_area.legend(loc='upper right') self.ax_area.set_ylim([0, 600]) self.ax_area.set_ylabel('Blob Area (pxls)') self.ax_area.set_xlabel('Contrast Threshold') self.ax_objects.set_xlim([0, final_t]) self.line_objects = self.ax_objects.plot((current_threshold, current_threshold), (-10000, 10000), '--', color='red') self.line_area = self.ax_area.plot((current_threshold, current_threshold), (-1000000, 1000000), '--', color='red') self.show_threshold() def show_threshold(self): """ plots an image with the outlines of all objects overlaid on top. params -------- img: (image ie. numpy array) each pixel denotes greyscale pixel intensities. background: (image ie. numpy array) the background image with maximum pixel intensities (made with create_background) threshold: (float) the threshold value used to create the binary mask after pixel intensities for (background - image) have been calculated. """ mask = self.create_binary_mask(self.mid_image, self.background, self.threshold) self.ax_image.clear() self.ax_image.imshow(self.mid_image, cmap=plt.cm.gray, interpolation='nearest') self.ax_image.contour(mask, [0.5], linewidths=1.2, colors='b') self.ax_image.axis('off') self.roiSelectorBar.update_image() self.calibrationBar.update_image() def on_histogram_button_pressed(self, ev): if self.threshold != ev.xdata: self.threshold = ev.xdata if self.line_objects is not None and len(self.line_objects) > 0: self.line_objects[0].remove() if self.line_area is not None and len(self.line_area) > 0: self.line_area[0].remove() self.line_objects = self.ax_objects.plot((self.threshold, self.threshold), (-10000, 10000), '--', color='red') self.line_area = self.ax_area.plot((self.threshold, self.threshold), (-1000000, 1000000), '--', color='red') self.show_threshold() self.histogram_figure.canvas.draw() self.save_roi_data() def roiSelectorBar_roi_changed(self): self.save_roi_data() self.on_changed_ev() def calibrationBar_calibration_changed(self): self.save_calibration_data()
class PlotGenerator(QFrame): def __init__(self, plot_path, plot_config_path): QFrame.__init__(self) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.plot_figure = PlotFigure() self.canvas = FigureCanvas(self.plot_figure.getFigure()) self.canvas.setParent(self) self.canvas.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) size = QSize(297*2, 210*2) # A4 aspectratio self.canvas.setMaximumSize(size) self.canvas.setMinimumSize(size) self.setMaximumSize(size) self.setMinimumSize(size) self.popup = Popup(self) self.plot_config_loader = PlotSettingsLoader() self.plot_settings = PlotSettings() self.plot_settings.setPlotPath(plot_path) self.plot_settings.setPlotConfigPath(plot_config_path) self.connect(self.popup, SIGNAL('updateProgress(int)'), self.updateProgress) self.plot_context_data_fetcher = PlotContextDataFetcher() self.plot_context_data_fetcher.initialize(self.plot_context_data_fetcher.getModel()) self.plot_data_fetcher = PlotDataFetcher() self.plot_data_fetcher.initialize(self.plot_data_fetcher.getModel()) def updateProgress(self, progress = 1): value = self.popup.progress_bar.value() self.popup.progress_bar.setValue(value + progress) def saveAll(self): self.popup.show() context_data = self.plot_context_data_fetcher.getFromModel() save_list = [] count = 0 for parameter in context_data.parameters: pt = parameter.type if pt == SummaryModel.TYPE or pt == KeywordModel.TYPE or pt == enums.obs_impl_type.FIELD_OBS: save_list.append(parameter) parameter.setUserData({'state' : enums.ert_state_enum.FORECAST}) if pt == KeywordModel.TYPE: choices = context_data.key_index_list[parameter.name] parameter.getUserData()['key_index_choices'] = choices count += len(choices) else: count += 1 self.popup.progress_bar.setMaximum(count) for parameter in save_list: if parameter.type == KeywordModel.TYPE: for choice in parameter.getUserData()['key_index_choices']: self.plot_data_fetcher.setParameter(parameter, context_data) parameter.getUserData()['key_index'] = choice # because setParameter overwrites this value self.plot_data_fetcher.fetchContent() self.savePlot(self.plot_data_fetcher.data) else: self.plot_data_fetcher.setParameter(parameter, context_data) self.plot_data_fetcher.fetchContent() self.savePlot(self.plot_data_fetcher.data) self.popup.ok_button.setEnabled(True) def save(self, plot_data): self.popup.show() self.popup.progress_bar.setMaximum(1) self.savePlot(plot_data) self.popup.ok_button.setEnabled(True) def savePlot(self, plot_data): generated_plot = self.generatePlot(plot_data) if generated_plot: self.savePlotToFile(plot_data.getSaveName()) self.popup.emit(SIGNAL('updateProgress(int)'), 1) def generatePlot(self, plot_data): name = plot_data.getSaveName() load_success = self.plot_config_loader.load(name, self.plot_settings) if load_success: self.plot_figure.drawPlot(plot_data, self.plot_settings) self.canvas.draw() return load_success def savePlotToFile(self, filename): """Save the plot visible in the figure.""" plot_path = self.plot_settings.getPlotPath() if not os.path.exists(plot_path): os.makedirs(plot_path) path = plot_path + "/" + filename self.plot_figure.getFigure().savefig(path + ".png", dpi=400, format="png") self.plot_figure.getFigure().savefig(path + ".pdf", dpi=400, format="pdf")
class resultsTab(QtGui.QWidget): def __init__(self, thr, cls, anom, num): QtGui.QWidget.__init__(self) self.CurrentDir = os.getcwd() self.plotList = [] self.tabLayout = QtGui.QVBoxLayout(self) self.Picture = QtGui.QPixmap(self.CurrentDir + '/cc_Cluster_%.2f_%s_%s/Dendrogram.png' % (float(thr), cls, anom)) self.ImageBox = QtGui.QLabel(self) self.ImageBox.setPixmap(self.Picture) self.ImageBox.setMaximumSize(400, 150) self.ImageBox.setScaledContents(True) self.Title = QtGui.QLabel(self) self.Title.setText('Threshold %.2f, Cluster %s, %s, %s datasets' % (float(thr), cls, anom, num)) self.Text = QtGui.QTextEdit() #self.LogFile=open(self.CurrentDir+'/cc_Cluster_%.2f_%s/XSCALE.LP'%(float(thr), cls)).read() self.statsPlot = Figure() self.Ax = self.statsPlot.add_subplot(111) self.statsCanvas = FigureCanvas(self.statsPlot) self.statsBar = NavigationToolbar(self.statsCanvas, self) self.statsCanvas.setMinimumSize(700, 500) with open( self.CurrentDir + '/cc_Cluster_%.2f_%s_%s/XSCALE.LP' % (float(thr), cls, anom), 'r') as LogFile: for line in LogFile: if line.strip().startswith('LIMIT'): break for line in LogFile: break for line in LogFile: if line.strip().startswith('total'): break self.plotList.append(line.split()) self.Text.append(line.strip()) # self.Text.setText(self.LogFile) #Buttons to plot stats self.buttonBar = QtGui.QWidget() self.barLayout = QtGui.QHBoxLayout(self.buttonBar) self.ccVsR = QtGui.QPushButton() self.ccVsR.setText(_fromUtf8("Compl. vs Res")) self.ccVsR.clicked.connect( lambda: self.plotStats(0, 4, "Compl. vs Res")) self.compVsR = QtGui.QPushButton() self.compVsR.setText(_fromUtf8("cc vs Res")) self.compVsR.clicked.connect( lambda: self.plotStats(0, 10, "cc vs Res")) self.RobsVsR = QtGui.QPushButton() self.RobsVsR.setText(_fromUtf8("Robs vs Res")) self.RobsVsR.clicked.connect( lambda: self.plotStats(0, 5, "Robs vs Res")) self.IsigmaVsR = QtGui.QPushButton() self.IsigmaVsR.setText(_fromUtf8("I/sigmaI vs Res")) self.IsigmaVsR.clicked.connect( lambda: self.plotStats(0, 8, "I/sigmaI vs Res")) self.SanoVsR = QtGui.QPushButton() self.SanoVsR.setText(_fromUtf8("Sig. Ano. vs Res")) self.SanoVsR.clicked.connect( lambda: self.plotStats(0, 12, "Sig. Ano. vs Res")) self.barLayout.addWidget(self.ccVsR) self.barLayout.addWidget(self.compVsR) self.barLayout.addWidget(self.RobsVsR) self.barLayout.addWidget(self.SanoVsR) self.barLayout.addWidget(self.IsigmaVsR) self.tabLayout.addWidget(self.Title) self.tabLayout.addWidget(self.ImageBox) self.tabLayout.addWidget(self.Text) self.tabLayout.addWidget(self.buttonBar) self.tabLayout.addWidget(self.statsBar) self.tabLayout.addWidget(self.statsCanvas) def plotStats(self, res, value, title): # plt.xkcd() self.Ax.clear() plotDataX = [] plotDataY = [] for el in self.plotList: plotDataX.append(float(el[res])) plotDataY.append(float(el[value].strip('*').strip('%'))) self.Ax.plot(plotDataX, plotDataY, 'r-^') self.Ax.set_xlim(10, 0) self.Ax.set_title(title) self.statsCanvas.draw()
class Window(QtGui.QWidget): def __init__(self, parent=None): super(Window, self).__init__(parent) self.setWindowTitle('OpenWave-2KE V%s'%__version__) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap("openwave.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.setWindowIcon(icon) #Waveform area. self.figure = plt.figure() self.figure.set_facecolor('white') self.canvas = FigureCanvas(self.figure) self.canvas.setMinimumSize(800, 400) self.toolbar = NavigationToolbar(self.canvas, self) self.toolbar.hide() #Zoom In/out and Capture Buttons self.zoomBtn = QtGui.QPushButton('Zoom') self.zoomBtn.setFixedSize(100, 30) self.zoomBtn.clicked.connect(self.toolbar.zoom) self.panBtn = QtGui.QPushButton('Pan') self.panBtn.setFixedSize(100, 30) self.panBtn.clicked.connect(self.toolbar.pan) self.homeBtn = QtGui.QPushButton('Home') self.homeBtn.setFixedSize(100, 30) self.homeBtn.clicked.connect(self.toolbar.home) self.captureBtn = QtGui.QPushButton('Capture') self.captureBtn.setFixedSize(100, 50) self.captureBtn.clicked.connect(self.captureAction) if(dso.connection_status==0): self.captureBtn.setEnabled(False) #Type: Raw Data/Image self.typeBtn = QtGui.QPushButton('Raw Data') self.typeBtn.setToolTip("Switch to get raw data or image from DSO.") self.typeBtn.setFixedSize(120, 50) self.typeFlag=True #Initial state -> Get raw data self.typeBtn.setCheckable(True) self.typeBtn.setChecked(True) self.typeBtn.clicked.connect(self.typeAction) #Channel Selection. self.ch1checkBox = QtGui.QCheckBox('CH1') self.ch1checkBox.setFixedSize(60, 30) self.ch2checkBox = QtGui.QCheckBox('CH2') self.ch2checkBox.setFixedSize(60, 30) if(dso.chnum==4): self.ch3checkBox = QtGui.QCheckBox('CH3') self.ch3checkBox.setFixedSize(60, 30) self.ch4checkBox = QtGui.QCheckBox('CH4') self.ch4checkBox.setFixedSize(60, 30) #Set channel selection layout. self.selectLayout = QtGui.QHBoxLayout() self.selectLayout.addWidget(self.ch1checkBox) self.selectLayout.addWidget(self.ch2checkBox) if(dso.chnum==4): self.selectLayout2 = QtGui.QHBoxLayout() self.selectLayout2.addWidget(self.ch3checkBox) self.selectLayout2.addWidget(self.ch4checkBox) self.typeLayout = QtGui.QHBoxLayout() self.typeLayout.addWidget(self.typeBtn) self.typeLayout.addLayout(self.selectLayout) if(dso.chnum==4): self.typeLayout.addLayout(self.selectLayout2) #Save/Load/Quit button self.saveBtn = QtGui.QPushButton('Save') self.saveBtn.setFixedSize(100, 50) self.saveMenu = QtGui.QMenu(self) self.csvAction = self.saveMenu.addAction("&As CSV File") self.pictAction = self.saveMenu.addAction("&As PNG File") self.saveBtn.setMenu(self.saveMenu) self.saveBtn.setToolTip("Save waveform to CSV file or PNG file.") self.connect(self.csvAction, QtCore.SIGNAL("triggered()"), self.saveCsvAction) self.connect(self.pictAction, QtCore.SIGNAL("triggered()"), self.savePngAction) self.loadBtn = QtGui.QPushButton('Load') self.loadBtn.setToolTip("Load CHx's raw data from file(*.csv, *.lsf).") self.loadBtn.setFixedSize(100, 50) self.loadBtn.clicked.connect(self.loadAction) self.quitBtn = QtGui.QPushButton('Quit') self.quitBtn.setFixedSize(100, 50) self.quitBtn.clicked.connect(self.quitAction) # set the layout self.waveLayout = QtGui.QHBoxLayout() self.waveLayout.addWidget(self.canvas) self.wave_box=QtGui.QVBoxLayout() self.wave_box.addLayout(self.waveLayout) self.wavectrlLayout = QtGui.QHBoxLayout() self.wavectrlLayout.addWidget(self.zoomBtn) self.wavectrlLayout.addWidget(self.panBtn) self.wavectrlLayout.addWidget(self.homeBtn) self.wavectrlLayout.addWidget(self.captureBtn) self.saveloadLayout = QtGui.QHBoxLayout() self.saveloadLayout.addWidget(self.saveBtn) self.saveloadLayout.addWidget(self.loadBtn) self.saveloadLayout.addWidget(self.quitBtn) self.ctrl_box=QtGui.QHBoxLayout() self.ctrl_box.addLayout(self.typeLayout) self.ctrl_box.addLayout(self.saveloadLayout) main_box=QtGui.QVBoxLayout() main_box.addLayout(self.wave_box) #Waveform area. main_box.addLayout(self.wavectrlLayout) #Zoom In/Out... main_box.addLayout(self.ctrl_box) #Save/Load/Quit self.setLayout(main_box) def typeAction(self): if(self.typeFlag==True): self.typeFlag=False self.typeBtn.setText("Image") self.csvAction.setEnabled(False) else: self.typeFlag=True self.typeBtn.setText("Raw Data") self.csvAction.setEnabled(True) self.typeBtn.setChecked(self.typeFlag) self.ch1checkBox.setEnabled(self.typeFlag) self.ch2checkBox.setEnabled(self.typeFlag) if(dso.chnum==4): self.ch3checkBox.setEnabled(self.typeFlag) self.ch4checkBox.setEnabled(self.typeFlag) def saveCsvAction(self): if(self.typeFlag==True): #Save raw data to csv file. file_name=QtGui.QFileDialog.getSaveFileName(self, "Save as", '', "Fast CSV File(*.CSV)")[0] num=len(dso.ch_list) #print num for ch in xrange(num): if(dso.info[ch]==[]): print('Failed to save data, raw data information is required!') return f = open(file_name, 'wb') item=len(dso.info[0]) #Write file header. f.write('%s,\r\n' % dso.info[0][0]) for x in xrange(1, 24): str='' for ch in xrange(num): str+=('%s,' % dso.info[ch][x]) str+='\r\n' f.write(str) #Write Fast CSV mode only. str='' for ch in xrange(num): str+='Mode,Fast,' str+='\r\n' f.write(str) str='' if(num==1): str+=('%s,' % dso.info[0][25]) else: for ch in xrange(num): str+=('%s,,' % dso.info[ch][25]) str+='\r\n' f.write(str) #Write raw data. item=len(dso.iWave[0]) #print item tenth=int(item/10) n_tenth=tenth-1 percent=10 for x in xrange(item): str='' if(num==1): str+=('%s,' % dso.iWave[0][x]) else: for ch in xrange(num): str+=('%s, ,' % dso.iWave[ch][x]) str+='\r\n' f.write(str) if(x==n_tenth): n_tenth+=tenth print('%3d %% Saved\r'%percent), percent+=10 f.close() def savePngAction(self): #Save figure to png file. file_name=QtGui.QFileDialog.getSaveFileName(self, "Save as", '', "PNG File(*.png)")[0] if(file_name==''): return if(self.typeFlag==True): #Save raw data waveform as png file. main.figure.savefig(file_name) else: #Save figure to png file. if(dso.osname=='pi'): #For raspberry pi only. img=dso.im.transpose(Image.FLIP_TOP_BOTTOM) img.save(file_name) else: dso.im.save(file_name) print('Saved image to %s.'%file_name) def loadAction(self): dso.ch_list=[] full_path_name=QtGui.QFileDialog.getOpenFileName(self,self.tr("Open File"),".","CSV/LSF files (*.csv *.lsf);;All files (*.*)") sFileName=unicode(full_path_name).split(',')[0][3:-1] #For PySide print sFileName if(len(sFileName)<=0): return if os.path.exists(sFileName): print 'Reading file...' count=dso.readRawDataFile(sFileName) #Draw waveform. if(count>0): total_chnum=len(dso.ch_list) if(total_chnum==0): return self.drawWaveform(0) else: print('File not found!') def quitAction(self): if(dso.connection_status==1): dso.closeIO() self.close() def captureAction(self): dso.iWave=[[], [], [], []] dso.ch_list=[] if(self.typeFlag==True): #Get raw data. draw_flag=False #Turn on the selected channels. if((self.ch1checkBox.isChecked()==True) and (dso.isChannelOn(1)==False)): dso.write(":CHAN1:DISP ON\n") #Set CH1 on. if((self.ch2checkBox.isChecked()==True) and (dso.isChannelOn(2)==False)): dso.write(":CHAN2:DISP ON\n") #Set CH2 on. if(dso.chnum==4): if((self.ch3checkBox.isChecked()==True) and (dso.isChannelOn(3)==False)): dso.write(":CHAN3:DISP ON\n") #Set CH3 on. if((self.ch4checkBox.isChecked()==True) and (dso.isChannelOn(4)==False)): dso.write(":CHAN4:DISP ON\n") #Set CH4 on. #Get all the selected channel's raw datas. if(self.ch1checkBox.isChecked()==True): dso.getRawData(True, 1) #Read CH1's raw data from DSO (including header). if(self.ch2checkBox.isChecked()==True): dso.getRawData(True, 2) #Read CH2's raw data from DSO (including header). if(dso.chnum==4): if(self.ch3checkBox.isChecked()==True): dso.getRawData(True, 3) #Read CH3's raw data from DSO (including header). if(self.ch4checkBox.isChecked()==True): dso.getRawData(True, 4) #Read CH4's raw data from DSO (including header). #Draw waveform. total_chnum=len(dso.ch_list) if(total_chnum==0): return if(self.drawWaveform(1)==-1): time.sleep(5) self.drawWaveform(0) else: #Get image. img_type=1 #1 for RLE format, 0 for PNG format. if(img_type): dso.write(':DISP:OUTP?\n') #Send command to get image from DSO. else: dso.write(':DISP:PNGOutput?\n') #Send command to get image from DSO. dso.getBlockData() dso.ImageDecode(img_type) self.showImage() plt.tight_layout(True) self.canvas.draw() print('Image is ready!') def showImage(self): #Turn the ticks off and show image. plt.clf() ax = plt.gca() ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) plt.imshow(dso.im) def drawWaveform(self, mode): total_chnum=len(dso.ch_list) num=dso.points_num ch_colortable=['#C0B020', '#0060FF', '#FF0080', '#00FF60'] ch=int(dso.ch_list[0][2])-1 #Get the channel of first waveform. plt.cla() plt.clf() #Due to the memory limitation of matplotlib, we must reduce the sample points. if(num==10000000): if(total_chnum>2): down_sample_factor=4 elif(total_chnum==2): down_sample_factor=4 else: down_sample_factor=1 num=num/down_sample_factor else: down_sample_factor=1 dt=dso.dt[0] #Get dt from the first opened channel. t_start=dso.hpos[0]-num*dt/2 t_end =dso.hpos[0]+num*dt/2 t = np.arange(t_start, t_end, dt) #print t_start, t_end, dt, len(t) if((len(t)-num)==1): #Avoid floating point rounding error. t=t[:-1] wave_type='-' #Set waveform type to vector. #Draw waveforms. ax=[[], [], [], []] p=[] for ch in xrange(total_chnum): if(ch==0): ax[ch]=host_subplot(111, axes_class=AA.Axes) ax[ch].set_xlabel("Time (sec)") else: ax[ch]=ax[0].twinx() ax[ch].set_ylabel("%s Units: %s" %(dso.ch_list[ch], dso.vunit[ch])) ch_color=ch_colortable[int(dso.ch_list[ch][2])-1] if(ch>1): new_fixed_axis = ax[ch].get_grid_helper().new_fixed_axis ax[ch].axis["right"] = new_fixed_axis(loc="right", axes=ax[ch], offset=(60*(ch-1), 0)) ax[ch].set_xlim(t_start, t_end) ax[ch].set_ylim(-4*dso.vdiv[ch]-dso.vpos[ch], 4*dso.vdiv[ch]-dso.vpos[ch]) #Setup vertical display range. fwave=dso.convertWaveform(ch, down_sample_factor) #print('Length=%d'%(len(fwave))) if(ch==0): try: p=ax[ch].plot(t, fwave, color=ch_color, ls=wave_type, label = dso.ch_list[ch]) except: if(mode==1): #print sys.exc_info()[0] time.sleep(5) print 'Trying to plot again!', return -1 else: try: p+=ax[ch].plot(t, fwave, color=ch_color, ls=wave_type, label = dso.ch_list[ch]) except: if(mode==1): #print sys.exc_info()[0] time.sleep(5) print 'Trying to plot again!', return -1 if(total_chnum>1): labs = [l.get_label() for l in p] plt.legend(p, labs, loc='upper right') plt.tight_layout() self.canvas.draw() del ax, t, p return 0
class PlotGenerator(QFrame): def __init__(self, plot_path, plot_config_path): QFrame.__init__(self) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.plot_figure = PlotFigure() self.canvas = FigureCanvas(self.plot_figure.getFigure()) self.canvas.setParent(self) self.canvas.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) size = QSize(297*2, 210*2) # A4 aspectratio self.canvas.setMaximumSize(size) self.canvas.setMinimumSize(size) self.setMaximumSize(size) self.setMinimumSize(size) self.popup = Popup(self) self.plot_config_loader = PlotSettingsLoader() self.plot_settings = PlotSettings() self.plot_settings.setPlotPath(plot_path) self.plot_settings.setPlotConfigPath(plot_config_path) self.connect(self.popup, SIGNAL('updateProgress(int)'), self.updateProgress) self.plot_context_data_fetcher = PlotContextDataFetcher() self.plot_context_data_fetcher.initialize(self.plot_context_data_fetcher.getModel()) self.plot_data_fetcher = PlotDataFetcher() self.plot_data_fetcher.initialize(self.plot_data_fetcher.getModel()) def updateProgress(self, progress = 1): value = self.popup.progress_bar.value() self.popup.progress_bar.setValue(value + progress) def saveAll(self): self.popup.show() context_data = self.plot_context_data_fetcher.getFromModel() save_list = [] count = 0 for parameter in context_data.parameters: pt = parameter.type if pt == SummaryModel.TYPE or pt == KeywordModel.TYPE or pt == enums.obs_impl_type.FIELD_OBS: save_list.append(parameter) parameter.setUserData({'state' : enums.ert_state_enum.FORECAST}) if pt == KeywordModel.TYPE: choices = context_data.key_index_list[parameter.name] parameter.getUserData()['key_index_choices'] = choices count += len(choices) else: count += 1 self.popup.progress_bar.setMaximum(count) for parameter in save_list: if parameter.type == KeywordModel.TYPE: for choice in parameter.getUserData()['key_index_choices']: self.plot_data_fetcher.setParameter(parameter, context_data) parameter.getUserData()['key_index'] = choice # because setParameter overwrites this value self.plot_data_fetcher.fetchContent() self.savePlot(self.plot_data_fetcher.data) else: self.plot_data_fetcher.setParameter(parameter, context_data) self.plot_data_fetcher.fetchContent() self.savePlot(self.plot_data_fetcher.data) self.popup.ok_button.setEnabled(True) def save(self, plot_data): self.popup.show() self.popup.progress_bar.setMaximum(1) self.savePlot(plot_data) self.popup.ok_button.setEnabled(True) def savePlot(self, plot_data): generated_plot = self.generatePlot(plot_data) if generated_plot: self.savePlotToFile(plot_data.getSaveName()) self.popup.emit(SIGNAL('updateProgress(int)'), 1) def generatePlot(self, plot_data): name = plot_data.getSaveName() load_success = self.plot_config_loader.load(name, self.plot_settings) if load_success: self.plot_figure.drawPlot(plot_data, self.plot_settings) self.canvas.draw() return load_success def savePlotToFile(self, filename): """Save the plot visible in the figure.""" plot_path = self.plot_settings.getPlotPath() if not os.path.exists(plot_path): os.makedirs(plot_path) path = plot_path + "/" + filename self.plot_figure.getFigure().savefig(path + ".png", dpi=400, format="png") self.plot_figure.getFigure().savefig(path + ".pdf", dpi=400, format="pdf")
qscrollLayout.setGeometry(QtCore.QRect(0, 0, 1000, 1000)) qscroll.setWidget(qscrollContents) qscroll.setWidgetResizable(True) for i in xrange(5): qfigWidget = QtGui.QWidget(qscrollContents) fig = Figure((5.0, 4.0), dpi=100) canvas = FigureCanvas(fig) canvas.setParent(qfigWidget) toolbar = NavigationToolbar(canvas, qfigWidget) axes = fig.add_subplot(111) axes.plot([1, 2, 3, 4]) # place plot components in a layout plotLayout = QtGui.QVBoxLayout() plotLayout.addWidget(canvas) plotLayout.addWidget(toolbar) qfigWidget.setLayout(plotLayout) # prevent the canvas to shrink beyond a point # original size looks like a good minimum size canvas.setMinimumSize(canvas.size()) qscrollLayout.addWidget(qfigWidget) qscrollContents.setLayout(qscrollLayout) qwidget.show() exit(qapp.exec_())
class MainWindow(QtGui.QMainWindow): def __init__(self, repo, options, parent=None): QtGui.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.repo = repo self.options = options self.createConfigurationWidget() self.createLayout() # initialize stuff self.splitChanged(split_list.index(self.options.split)) # fetch + redraw def createConfigurationWidget(self): self.configurationwidget = QtGui.QGroupBox() self.cwui = Ui_ConfigurationWidget() self.cwui.setupUi(self.configurationwidget) # set initial values self.cwui.splitComboBox.setCurrentIndex(split_list.index(self.options.split)) if self.options.filename: self.cwui.filenameLineEdit.setText(self.options.filename) if self.options.imagetitle: self.cwui.imageTitleLineEdit.setText(self.options.imagetitle) if self.options.skipmerges: self.cwui.skipMergesCheckBox.setCheckState(QtCore.Qt.Checked) if self.options.showtags: self.cwui.showTagsCheckBox.setCheckState(QtCore.Qt.Checked) if self.options.uselines: self.cwui.uselinesCheckBox.setCheckState(QtCore.Qt.Checked) self.cwui.maxcaptionSpinBox.setValue(self.options.maxcaptions) # overall min/max self.cwui.startDateEdit.setMinimumDate(self.options.repo_datemin) self.cwui.endDateEdit.setMaximumDate(self.options.repo_datemax) # initial value if self.options.datemin == None: self.cwui.startDateEdit.setDate(self.options.repo_datemin) else: self.cwui.startDateEdit.setDate(self.options.datemin) if self.options.datemax == None: self.cwui.endDateEdit.setDate(self.options.repo_datemax) else: self.cwui.endDateEdit.setDate(self.options.datemax) if self.options.datemin != None or self.options.datemax != None: self.timerangeUpdate(4) # 4 = custom self.cwui.timerangeComboBox.setCurrentIndex(4) else: self.timerangeUpdate(0) # 0 = whole range self.cwui.timerangeComboBox.setCurrentIndex(0) # # connect them all # self.connect(self.cwui.splitComboBox, QtCore.SIGNAL("currentIndexChanged(int)"), self.splitChanged) self.connect(self.cwui.timerangeComboBox, QtCore.SIGNAL("currentIndexChanged(int)"), self.timerangeChanged) self.connect(self.cwui.filenameLineEdit, QtCore.SIGNAL("textChanged(const QString)"), self.filenameChanged) self.connect(self.cwui.imageTitleLineEdit, QtCore.SIGNAL("textChanged(const QString)"), self.imageTitleChanged) self.connect(self.cwui.skipMergesCheckBox, QtCore.SIGNAL("stateChanged(int)"), self.skipMergesChanged) self.connect(self.cwui.showTagsCheckBox, QtCore.SIGNAL("stateChanged(int)"), self.showTagsChanged) self.connect(self.cwui.uselinesCheckBox, QtCore.SIGNAL("stateChanged(int)"), self.uselinesChanged) self.connect(self.cwui.maxcaptionSpinBox, QtCore.SIGNAL("valueChanged(int)"), self.maxcaptionChanged) self.connect(self.cwui.startDateEdit, QtCore.SIGNAL("dateChanged(const QDate&)"), self.timerangeChanged) self.connect(self.cwui.endDateEdit, QtCore.SIGNAL("dateChanged(const QDate&)"), self.timerangeChanged) # # remaining mainwindow stuff # self.connect(self.ui.action_About, QtCore.SIGNAL("triggered()"), self.about) self.connect(self.ui.action_Quit, QtCore.SIGNAL("triggered()"), QtGui.qApp.quit) def createLayout(self): # layout vbox = QtGui.QVBoxLayout() hbox = QtGui.QHBoxLayout() self.fig = Figure() self.fig.add_subplot(111) self.canvas = FigureCanvas(self.fig) self.canvas.setParent(self.ui.centralWidget) self.canvas.setMinimumSize(50, 50) hbox.addWidget(self.canvas, 1.0) hbox.addWidget(self.configurationwidget) vbox.addLayout(hbox, 1) label = QtGui.QLabel( "You can copy paste this command line to get the same result with no graphical interface:", self.ui.centralWidget, ) vbox.addWidget(label) self.commandline = QtGui.QLineEdit(self.ui.centralWidget) self.commandline.setReadOnly(True) vbox.addWidget(self.commandline) self.ui.centralWidget.setLayout(vbox) self.setCentralWidget(self.ui.centralWidget) def skipMergesChanged(self, value): "This is heavy : we need to refetch everything" self.options.skipmerges = not not value self.dates = collect_data(self.repo.changelog, self.options) self.redraw() def showTagsChanged(self, value): self.options.showtags = not not value self.redraw() def uselinesChanged(self, value): "This is heavy : we need to refetch everything" self.options.uselines = not not value self.dates = collect_data(self.repo.changelog, self.options) self.redraw() def splitChanged(self, index): "This is heavy : we need to refetch everything" self.options.split = split_list[index] if index == 0: # disable maxcaptions self.cwui.maxcaptionSpinBox.setEnabled(False) self.cwui.maxcaptionsLabel.setEnabled(False) else: # enable maxcaptions self.cwui.maxcaptionSpinBox.setEnabled(True) self.cwui.maxcaptionsLabel.setEnabled(True) self.dates = collect_data(self.repo.changelog, self.options) self.redraw() def timerangeUpdate(self, index): now = datetime.now() self.options.datemax = None if index == 0: self.options.datemin = None elif index == 1: self.options.datemin = now - timedelta(365) elif index == 2: self.options.datemin = now - timedelta(30) elif index == 3: self.options.datemin = now - timedelta(7) if index == 4: # custom self.cwui.startDateEdit.setEnabled(True) self.cwui.endDateEdit.setEnabled(True) self.options.datemin = datetime.combine(self.cwui.startDateEdit.date().toPyDate(), time()) self.options.datemax = datetime.combine(self.cwui.endDateEdit.date().toPyDate(), time()) else: self.cwui.startDateEdit.setEnabled(False) self.cwui.endDateEdit.setEnabled(False) if self.options.datemin == None: self.cwui.startDateEdit.setDate(self.options.repo_datemin) else: self.cwui.startDateEdit.setDate(self.options.datemin) if self.options.datemax == None: self.cwui.endDateEdit.setDate(self.options.repo_datemax) else: self.cwui.endDateEdit.setDate(self.options.datemax) def timerangeChanged(self): "This is heavy : we need to refetch everything" index = self.cwui.timerangeComboBox.currentIndex() self.timerangeUpdate(index) self.dates = collect_data(self.repo.changelog, self.options) self.redraw() def maxcaptionChanged(self, newvalue): self.options.maxcaptions = newvalue self.redraw() def imageTitleChanged(self, newtext): self.options.imagetitle = newtext self.recomputeLineCommand() def filenameChanged(self, newtext): self.options.filename = newtext self.recomputeLineCommand() def redraw(self): draw_graph(self.fig, self.options, self.dates) self.canvas.draw() self.recomputeLineCommand() def recomputeLineCommand(self): line = "hg activity" if self.options.imagetitle != self.repo.root: line += " -t='%s'" % self.options.imagetitle if self.options.filename != "activity.png": line += " -o='%s'" % self.options.filename if self.options.skipmerges: line += " --skipmerges" if self.options.showtags: line += " --showtags" if self.options.uselines: line += " --uselines" if self.options.split != "none": line += " --split=%s" % self.options.split if self.options.maxcaptions != 4: line += " --maxcaptions=%d" % self.options.maxcaptions if self.options.datemin != None: line += " --datemin=%s" % self.options.datemin.strftime("%Y-%m-%d") if self.options.datemax != None: line += " --datemax=%s" % self.options.datemax.strftime("%Y-%m-%d") self.commandline.setText(line) def about(self): msg = """ <h2>About</h2> hgactivity is an extension for <a href="http://mercurial.selenic.com/">mercurial</a> that creates an image displaying the activity for a repository. <br/> <br/> The official homepage is <a href="http://labs.freehackers.org/projects/hgactivity">http://labs.freehackers.org/projects/hgactivity</a>. <br/> <br/> More information can be found on the <a href="http://labs.freehackers.org/projects/hgactivity/wiki">wiki</a> and on <a href="http://labs.freehackers.org/projects/hgactivity/wiki/documentation">the documentation page</a>. <h2>Design & Coding</h2> Thomas Capricelli <*****@*****.**> <br/> <a href="http://www.freehackers.org/thomas/free-software/">http://www.freehackers.org/thomas/free-software/</a> """ box = QtGui.QDialog(self) label = QtGui.QLabel(box) label.setOpenExternalLinks(True) label.setWordWrap(True) label.setWindowTitle("About hg activity (qt interface)") label.setText(msg) vbox = QtGui.QVBoxLayout() vbox.addWidget(label) box.setLayout(vbox) button = QtGui.QPushButton("Ok", box) box.connect(button, QtCore.SIGNAL("clicked()"), box.accept) vbox.addWidget(button) box.exec_()
class Amoeba_Line_Graph(): def __init__(self): """ This class is for the plot on each of the parameter UIs. """ #Generate plot x = [] y = [] self.fig = Figure(figsize=(8, 4), dpi=72, facecolor=(1, 1, 1), edgecolor=(0, 0, 0)) self.sub_plot = self.fig.add_subplot(111) self.sub_plot.xaxis_date() if AMOEBA_LINE_GRAPH_DEBUG: print "X = " print x print "Y = " print y print "Create " print self.sub_plot.plot self.sub_plot.plot(y, x, 'b') self.sub_plot.set_xlabel('Time') self.fig.autofmt_xdate() #Create canvas for the plot self.canvas = FigureCanvas(self.fig) self.canvas.setMinimumSize(self.canvas.size()) def update(self, datay, datax): """ This method updates the plot with the input data. :param datay: Y axis of the points to plot. :param datax: X axis of the points to plot. """ if AMOEBA_LINE_GRAPH_DEBUG: print "Update sub plot" print "X = " print datax print "Y = " print datay print "Update " print self.sub_plot.plot # Clear the graph. self.clear_graph() self.sub_plot.plot(datax, datay, 'b') self.sub_plot.set_visible(True) self.sub_plot.autoscale(True, "both") self.canvas.draw() def retrieve_graph(self): """ This method returns the plot's widget. :return: """ return self.canvas def clear_graph(self): """ This method clears the graph. """ y = [] x = [] self.sub_plot.clear() self.sub_plot.set_visible(True) self.sub_plot.autoscale(True, "both", False) self.sub_plot.plot(y, x, 'b') self.canvas.draw()
class WaldoProcessPage(QtGui.QWizardPage): SHOWING_NOTHING = 0 SHOWING_IMAGE = 1 SHOWING_REPORT = 2 def __init__(self, data, parent=None): super(WaldoProcessPage, self).__init__(parent) self.data = data self.waldoProcessCompleted = False self.setTitle("Running WALDO") self.image_figure = plt.figure() self.image_canvas = FigureCanvas(self.image_figure) self.image_canvas.setMinimumSize(50, 50) self.image_canvas.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding) self.ax_image = self.image_figure.add_subplot(111) self.ax_image.axis('off') self.report_figure = plt.figure() self.report_canvas = FigureCanvas(self.report_figure) self.report_canvas.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding) self.report_canvas.setMinimumSize(50, 50) self.ax_report = self.report_figure.add_subplot(111) self.main_layout = QtGui.QHBoxLayout() self.showing_status = WaldoProcessPage.SHOWING_NOTHING layout = QtGui.QVBoxLayout() layout.addLayout(self.main_layout) self.setLayout(layout) def initializePage(self): self.data.single_result_message = (WaldoBatchRunResult.CACHED, None) self.waldoProcessCompleted = False QTimer.singleShot(0, self.show_dialog) def show_dialog(self): dlg = WaldoProcessDialog(self.data.experiment, self.waldoProcess, self.show_image, self.show_report, self.finished, self) dlg.setModal(True) dlg.exec_() def _set_image(self, image): if self.showing_status == WaldoProcessPage.SHOWING_REPORT: self.report_canvas.setParent(None) self.showing_status = WaldoProcessPage.SHOWING_NOTHING if self.showing_status == WaldoProcessPage.SHOWING_NOTHING: self.main_layout.addWidget(self.image_canvas) self.showing_status = WaldoProcessPage.SHOWING_IMAGE self.ax_image.clear() self.ax_image.imshow(image, cmap=plt.cm.gray, interpolation='nearest') self.ax_image.axis('off') def _set_report(self, report): # print("HELIO", report.head()) if self.showing_status == WaldoProcessPage.SHOWING_IMAGE: self.image_canvas.setParent(None) self.showing_status = WaldoProcessPage.SHOWING_NOTHING if self.showing_status == WaldoProcessPage.SHOWING_NOTHING: self.main_layout.addWidget(self.report_canvas) self.showing_status = WaldoProcessPage.SHOWING_REPORT d = report[['phase', 'connected-nodes', 'total-nodes']][::-1] d = d.drop_duplicates('phase', take_last=False) d = d.set_index('phase') self.ax_report.clear() d.plot(ax=self.ax_report, kind='barh') self.ax_report.set_xlabel('Number of Track Fragments', size=15) self.ax_report.legend(frameon=False, loc=(1.01, 0.7), fontsize=15) self.ax_report.set_ylabel('phase', size=15) self.report_figure.tight_layout() self.report_figure.subplots_adjust(right=0.6) self.report_figure.canvas.draw() # plt.yticks(fontsize=12) # plt.xticks(fontsize=12) def waldoProcess(self, callback): try: times, impaths = zip(*sorted(self.data.experiment.image_files.items())) impaths = [str(s) for s in impaths] self.last_image_index = 0 def callback_with_image(x): if len(impaths) == 0: return index = int(x * len(impaths)) if index > len(impaths) - 1: index = len(impaths) - 1 if index - self.last_image_index < 1: return self.last_image_index = index im = mpimg.imread(impaths[index]) callback(10, im) def PROCESS_BLOBS_CALLBACK(x): callback(1, x) callback_with_image(x) LOAD_EXPERIMENT_CALLBACK = lambda x: callback(2, x) CORRECT_ERROR_CALLBACK = lambda x: callback(3, x) WRITE_OUTPUT_CALLBACK = lambda x: callback(4, x) GENERATE_REPORT_CALLBACK = lambda x: callback(5, x) NEW_IMAGE_CALLBACK = lambda im: callback(11, im) REDRAW_SOLVE_FIGURE_CALLBACK = lambda df: callback(21, df) STEPS = 4.0 ex_id = self.data.experiment.id callback(0, 0.0 / STEPS) prepare_summarize(ex_id, experiment=self.data.experiment, callback=PROCESS_BLOBS_CALLBACK) PROCESS_BLOBS_CALLBACK(1) callback(0, 1.0 / STEPS) experiment = self.data.experiment LOAD_EXPERIMENT_CALLBACK(1) callback(0, 2.0 / STEPS) graph = experiment.graph.copy() solver = WaldoSolver(experiment, graph) callback(22, solver.report()) solver.run(callback=CORRECT_ERROR_CALLBACK, redraw_callback=REDRAW_SOLVE_FIGURE_CALLBACK) graph = solver.graph CORRECT_ERROR_CALLBACK(1) callback(0, 3.0 / STEPS) info.create_and_copy(experiment.id, created_by="guiwaldo.py") out_writer = OutputWriter(experiment.id, graph=graph) out_writer.export(callback1=WRITE_OUTPUT_CALLBACK, callback2=GENERATE_REPORT_CALLBACK) WRITE_OUTPUT_CALLBACK(1) GENERATE_REPORT_CALLBACK(1) callback(0, 4.0 / STEPS) self.export_tables() self.data.single_result_message = (WaldoBatchRunResult.SUCCEEDED, None) except Exception as ex: tb = traceback.format_exc() self.data.single_result_message = (WaldoBatchRunResult.FAILED, (ex, tb)) def show_image(self, id, image): self._set_image(image) def show_report(self, id, report): self._set_report(report) def export_tables(self): ex_id = self.data.experiment.id path = os.path.join(settings.PROJECT_DATA_ROOT, ex_id) report_card_df = self.data.experiment.prepdata.load('report-card') if report_card_df is not None: headers = ['phase', 'step', 'total-nodes', '>10min', '>20min', '>30min', '>40min', '>50min', 'duration-mean', 'duration-std'] b = report_card_df[headers] name = os.path.join(path, ex_id + '-track_counts.csv') b.to_csv(path_or_buf=name) headers = ['phase', 'step', 'total-nodes', 'connected-nodes', 'isolated-nodes', 'giant-component-size', '# components'] b = report_card_df[headers] name = os.path.join(path, ex_id + '-network_overview.csv') b.to_csv(path_or_buf=name) df = self.data.experiment.prepdata.load('end_report') if df is not None: df['lifespan'] = ['0-1 min', '1-5 min', '6-10 min', '11-20 min', '21-60 min', 'total'] df = df.rename(columns={'lifespan': 'track-duration', 'unknown': 'disappear', 'timing': 'recording-finishes', 'on_edge': 'image-edge'}) df.set_index('track-duration', inplace=True) name = os.path.join(path, ex_id + '-tract_termination.csv') df.to_csv(path_or_buf=name) df = self.data.experiment.prepdata.load('start_report') if df is not None: df['lifespan'] = ['0-1 min', '1-5 min', '6-10 min', '11-20 min', '21-60 min', 'total'] df = df.rename(columns={'lifespan': 'track-duration', 'unknown': 'appear', 'timing': 'recording-begins', 'on_edge': 'image-edge'}) df.set_index('track-duration', inplace=True) name = os.path.join(path, ex_id + '-tract_initiation.csv') df.to_csv(path_or_buf=name) def finished(self): self.waldoProcessCompleted = True self.completeChanged.emit() self.wizard().next() def isComplete(self): return self.waldoProcessCompleted
class Window(QtGui.QWidget): def __init__(self, parent=None): super(Window, self).__init__(parent) self.setWindowTitle('OpenWave-1KB') icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap("openwave.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.setWindowIcon(icon) #Waveform area. self.figure = plt.figure() self.figure.set_facecolor('white') self.canvas = FigureCanvas(self.figure) self.canvas.setMinimumSize(800, 400) self.toolbar = NavigationToolbar(self.canvas, self) self.toolbar.hide() #Zoom In/out and Capture Buttons self.zoomBtn = QtGui.QPushButton('Zoom') self.zoomBtn.setFixedSize(100, 30) self.zoomBtn.clicked.connect(self.toolbar.zoom) self.panBtn = QtGui.QPushButton('Pan') self.panBtn.setFixedSize(100, 30) self.panBtn.clicked.connect(self.toolbar.pan) self.homeBtn = QtGui.QPushButton('Home') self.homeBtn.setFixedSize(100, 30) self.homeBtn.clicked.connect(self.toolbar.home) self.captureBtn = QtGui.QPushButton('Capture') self.captureBtn.setFixedSize(100, 50) self.captureBtn.clicked.connect(self.captureAction) if (portNum == -1): self.captureBtn.setEnabled(False) #Type: Raw Data/Image self.typeBtn = QtGui.QPushButton('Raw Data') self.typeBtn.setToolTip("Switch to get raw data or image from DSO.") self.typeBtn.setFixedSize(120, 50) self.typeFlag = True #Initial state -> Get raw data self.typeBtn.setCheckable(True) self.typeBtn.setChecked(True) self.typeBtn.clicked.connect(self.typeAction) #Channel Selection. self.ch1checkBox = QtGui.QCheckBox('CH1') self.ch1checkBox.setFixedSize(60, 30) self.ch2checkBox = QtGui.QCheckBox('CH2') self.ch2checkBox.setFixedSize(60, 30) if (dso.chnum == 4): self.ch3checkBox = QtGui.QCheckBox('CH3') self.ch3checkBox.setFixedSize(60, 30) self.ch4checkBox = QtGui.QCheckBox('CH4') self.ch4checkBox.setFixedSize(60, 30) #Set channel selection layout. self.selectLayout = QtGui.QHBoxLayout() self.selectLayout.addWidget(self.ch1checkBox) self.selectLayout.addWidget(self.ch2checkBox) if (dso.chnum == 4): self.selectLayout2 = QtGui.QHBoxLayout() self.selectLayout2.addWidget(self.ch3checkBox) self.selectLayout2.addWidget(self.ch4checkBox) self.typeLayout = QtGui.QHBoxLayout() self.typeLayout.addWidget(self.typeBtn) self.typeLayout.addLayout(self.selectLayout) if (dso.chnum == 4): self.typeLayout.addLayout(self.selectLayout2) #Save/Load/Quit button self.saveBtn = QtGui.QPushButton('Save') self.saveBtn.setFixedSize(100, 50) self.saveMenu = QtGui.QMenu(self) self.csvAction = self.saveMenu.addAction("&As CSV File") self.pictAction = self.saveMenu.addAction("&As PNG File") self.saveBtn.setMenu(self.saveMenu) self.saveBtn.setToolTip("Save waveform to CSV file or PNG file.") self.connect(self.csvAction, QtCore.SIGNAL("triggered()"), self.saveCsvAction) self.connect(self.pictAction, QtCore.SIGNAL("triggered()"), self.savePngAction) self.loadBtn = QtGui.QPushButton('Load') self.loadBtn.setToolTip("Load CHx's raw data from file(*.csv, *.lsf).") self.loadBtn.setFixedSize(100, 50) self.loadBtn.clicked.connect(self.loadAction) self.quitBtn = QtGui.QPushButton('Quit') self.quitBtn.setFixedSize(100, 50) self.quitBtn.clicked.connect(self.quitAction) # set the layout self.waveLayout = QtGui.QHBoxLayout() self.waveLayout.addWidget(self.canvas) self.wave_box = QtGui.QVBoxLayout() self.wave_box.addLayout(self.waveLayout) self.wavectrlLayout = QtGui.QHBoxLayout() self.wavectrlLayout.addWidget(self.zoomBtn) self.wavectrlLayout.addWidget(self.panBtn) self.wavectrlLayout.addWidget(self.homeBtn) self.wavectrlLayout.addWidget(self.captureBtn) self.saveloadLayout = QtGui.QHBoxLayout() self.saveloadLayout.addWidget(self.saveBtn) self.saveloadLayout.addWidget(self.loadBtn) self.saveloadLayout.addWidget(self.quitBtn) self.ctrl_box = QtGui.QHBoxLayout() self.ctrl_box.addLayout(self.typeLayout) self.ctrl_box.addLayout(self.saveloadLayout) main_box = QtGui.QVBoxLayout() main_box.addLayout(self.wave_box) #Waveform area. main_box.addLayout(self.wavectrlLayout) #Zoom In/Out... main_box.addLayout(self.ctrl_box) #Save/Load/Quit self.setLayout(main_box) def typeAction(self): if (self.typeFlag == True): self.typeFlag = False self.typeBtn.setText("Image") self.csvAction.setEnabled(False) else: self.typeFlag = True self.typeBtn.setText("Raw Data") self.csvAction.setEnabled(True) self.typeBtn.setChecked(self.typeFlag) self.ch1checkBox.setEnabled(self.typeFlag) self.ch2checkBox.setEnabled(self.typeFlag) if (dso.chnum == 4): self.ch3checkBox.setEnabled(self.typeFlag) self.ch4checkBox.setEnabled(self.typeFlag) def saveCsvAction(self): if (self.typeFlag == True): #Save raw data to csv file. file_name = QtGui.QFileDialog.getSaveFileName( self, "Save as", '', "Fast CSV File(*.csv)")[0] num = len(dso.ch_list) #print num for ch in xrange(num): if (dso.info[ch] == []): print( 'Failed to save data, raw data information is required!' ) return f = open(file_name, 'wb') item = len(dso.info[0]) #Write file header. f.write('%s, \n' % dso.info[0][0]) for x in xrange(1, 23): str = '' for ch in xrange(num): str += ('%s,' % dso.info[ch][x]) str += '\n' f.write(str) if (num == 1): str = 'Mode,Fast,\n' f.write(str) str = 'Waveform Data,\n' f.write(str) else: str = '' for ch in xrange(num): str += ('Mode,Fast,') str += '\n' f.write(str) str = '' for ch in xrange(num): str += ('Waveform Data,,') str += '\n' f.write(str) #Write raw data. item = len(dso.iWave[0]) #print item tenth = int(item / 10) n_tenth = tenth - 1 percent = 10 for x in xrange(item): str = '' if (num == 1): str += ('%s,' % dso.iWave[0][x]) else: for ch in xrange(num): str += ('%s, ,' % dso.iWave[ch][x]) str += '\n' f.write(str) if (x == n_tenth): n_tenth += tenth print('%3d %% Saved\r' % percent), percent += 10 f.close() def savePngAction(self): #Save figure to png file. file_name = QtGui.QFileDialog.getSaveFileName(self, "Save as", '', "PNG File(*.png)")[0] if (file_name == ''): return if (self.typeFlag == True): #Save raw data waveform as png file. main.figure.savefig(file_name) print('Saved image to %s.' % file_name) else: #Save figure to png file. if (dso.nodename == 'pi'): #For raspberry pi only. img = dso.im.transpose(Image.FLIP_TOP_BOTTOM) img.save(file_name) else: dso.im.save(file_name) print('Saved image to %s.' % file_name) def loadAction(self): dso.ch_list = [] full_path_name = QtGui.QFileDialog.getOpenFileName( self, self.tr("Open File"), ".", "CSV/LSF files (*.csv *.lsf);;All files (*.*)") sFileName = unicode(full_path_name).split(',')[0][3:-1] #For PySide print sFileName if (len(sFileName) <= 0): return if os.path.exists(sFileName): print 'Reading file...' count = dso.readRawDataFile(sFileName) #Draw waveform. if (count > 0): total_chnum = len(dso.ch_list) if (total_chnum == 0): return if (dso.dataMode == 'Fast'): self.drawWaveform(0) else: self.drawWaveform(0) else: print('File not found!') def quitAction(self): if (portNum != -1): dso.IO.close() self.close() def captureAction(self): dso.iWave = [[], [], [], []] dso.ch_list = [] if (self.typeFlag == True): #Get raw data. draw_flag = False #Turn on the selected channels. if ((self.ch1checkBox.isChecked() == True) and (dso.isChannelOn(1) == False)): dso.write(":CHAN1:DISP ON\n") #Set CH1 on. if ((self.ch2checkBox.isChecked() == True) and (dso.isChannelOn(2) == False)): dso.write(":CHAN2:DISP ON\n") #Set CH2 on. if (dso.chnum == 4): if ((self.ch3checkBox.isChecked() == True) and (dso.isChannelOn(3) == False)): dso.write(":CHAN3:DISP ON\n") #Set CH3 on. if ((self.ch4checkBox.isChecked() == True) and (dso.isChannelOn(4) == False)): dso.write(":CHAN4:DISP ON\n") #Set CH4 on. #Get all the selected channel's raw datas. if (self.ch1checkBox.isChecked() == True): dso.getRawData( True, 1) #Read CH1's raw data from DSO (including header). if (self.ch2checkBox.isChecked() == True): dso.getRawData( True, 2) #Read CH2's raw data from DSO (including header). if (dso.chnum == 4): if (self.ch3checkBox.isChecked() == True): dso.getRawData( True, 3) #Read CH3's raw data from DSO (including header). if (self.ch4checkBox.isChecked() == True): dso.getRawData( True, 4) #Read CH4's raw data from DSO (including header). #Draw waveform. total_chnum = len(dso.ch_list) if (total_chnum == 0): return if (self.drawWaveform(1) == -1): time.sleep(5) self.drawWaveform(0) else: #Get image. dso.write(':DISP:OUTP?\n') #Send command to get image from DSO. dso.getBlockData() dso.RleDecode() self.showImage() plt.tight_layout(True) self.canvas.draw() print('Image is ready!') def showImage(self): #Turn the ticks off and show image. plt.clf() ax = plt.gca() ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) plt.imshow(dso.im) def drawWaveform(self, mode): total_chnum = len(dso.ch_list) num = dso.points_num ch_colortable = ['#C0B020', '#0060FF', '#FF0080', '#00FF60'] ch = int(dso.ch_list[0][2]) - 1 #Get the channel of first waveform. plt.cla() plt.clf() #Due to the memory limitation of matplotlib, we must reduce the sample points. if (num == 10000000): if (total_chnum > 2): down_sample_factor = 4 elif (total_chnum == 2): down_sample_factor = 4 else: down_sample_factor = 1 num = num / down_sample_factor else: down_sample_factor = 1 dt = dso.dt[0] #Get dt from the first opened channel. t_start = dso.hpos[0] - num * dt / 2 t_end = dso.hpos[0] + num * dt / 2 t = np.arange(t_start, t_end, dt) #print t_start, t_end, dt, len(t) if ((len(t) - num) == 1): #Avoid floating point rounding error. t = t[:-1] wave_type = '-' #Set waveform type to vector. #Draw waveforms. ax = [[], [], [], []] p = [] for ch in xrange(total_chnum): if (ch == 0): ax[ch] = host_subplot(111, axes_class=AA.Axes) ax[ch].set_xlabel("Time (sec)") else: ax[ch] = ax[0].twinx() ax[ch].set_ylabel("%s Units: %s" % (dso.ch_list[ch], dso.vunit[ch])) ch_color = ch_colortable[int(dso.ch_list[ch][2]) - 1] if (ch > 1): new_fixed_axis = ax[ch].get_grid_helper().new_fixed_axis ax[ch].axis["right"] = new_fixed_axis(loc="right", axes=ax[ch], offset=(60 * (ch - 1), 0)) ax[ch].set_xlim(t_start, t_end) ax[ch].set_ylim(-4 * dso.vdiv[ch] - dso.vpos[ch], 4 * dso.vdiv[ch] - dso.vpos[ch]) #Setup vertical display range. fwave = dso.convertWaveform(ch, down_sample_factor) #print('Length=%d'%(len(fwave))) if (ch == 0): try: p = ax[ch].plot(t, fwave, color=ch_color, ls=wave_type, label=dso.ch_list[ch]) except: if (mode == 1): #print sys.exc_info()[0] time.sleep(5) print 'Trying to plot again!', return -1 else: try: p += ax[ch].plot(t, fwave, color=ch_color, ls=wave_type, label=dso.ch_list[ch]) except: if (mode == 1): #print sys.exc_info()[0] time.sleep(5) print 'Trying to plot again!', return -1 if (total_chnum > 1): labs = [l.get_label() for l in p] plt.legend(p, labs, loc='upper right') plt.tight_layout() self.canvas.draw() del ax, t, p return 0
class StatsWidget(QWidget, FORM_CLASS): signalAskCloseWindow = pyqtSignal(name='signalAskCloseWindow') def __init__(self, parent=None): self.parent = parent super(StatsWidget, self).__init__() self.setupUi(self) self.label_progressStats.setText('') # Connect # noinspection PyUnresolvedReferences self.pushButton_saveTable.clicked.connect(self.save_table) # noinspection PyUnresolvedReferences self.pushButton_saveYValues.clicked.connect(self.save_y_values) self.buttonBox_stats.button(QDialogButtonBox.Ok).clicked.connect( self.run_stats) self.buttonBox_stats.button(QDialogButtonBox.Cancel).clicked.connect( self.signalAskCloseWindow.emit) # a figure instance to plot on self.figure = Figure() self.canvas = FigureCanvas(self.figure) self.canvas.setMinimumSize(QSize(300, 0)) self.toolbar = CustomNavigationToolbar(self.canvas, self) self.layout_plot.addWidget(self.toolbar) self.layout_plot.addWidget(self.canvas) self.tab = [] self.comboBox_blurredLayer.setFilters( QgsMapLayerProxyModel.PolygonLayer) self.comboBox_statsLayer.setFilters( QgsMapLayerProxyModel.PolygonLayer) def run_stats(self): self.progressBar_stats.setValue(0) self.label_progressStats.setText('') # noinspection PyArgumentList QApplication.processEvents() blurred_layer = self.comboBox_blurredLayer.currentLayer() stats_layer = self.comboBox_statsLayer.currentLayer() try: if not blurred_layer or not stats_layer: raise NoLayerProvidedException crs_blurred_layer = blurred_layer.crs() crs_stats_layer = stats_layer.crs() if crs_blurred_layer != crs_stats_layer: raise DifferentCrsException( epsg1=crs_blurred_layer.authid(), epsg2=crs_stats_layer.authid()) if blurred_layer == stats_layer: raise NoLayerProvidedException if not blurred_layer or not stats_layer: raise NoLayerProvidedException nb_feature_stats = stats_layer.featureCount() nb_feature_blurred = blurred_layer.featureCount() features_stats = {} label_preparing = tr('Preparing index on the stats layer') label_creating = tr('Creating index on the stats layer') label_calculating = tr('Calculating') if QGis.QGIS_VERSION_INT < 20700: self.label_progressStats.setText('%s 1/3' % label_preparing) for i, feature in enumerate(stats_layer.getFeatures()): features_stats[feature.id()] = feature percent = int((i + 1) * 100 / nb_feature_stats) self.progressBar_stats.setValue(percent) # noinspection PyArgumentList QApplication.processEvents() self.label_progressStats.setText('%s 2/3' % label_creating) # noinspection PyArgumentList QApplication.processEvents() index = QgsSpatialIndex() for i, f in enumerate(stats_layer.getFeatures()): index.insertFeature(f) percent = int((i + 1) * 100 / nb_feature_stats) self.progressBar_stats.setValue(percent) # noinspection PyArgumentList QApplication.processEvents() self.label_progressStats.setText('%s 3/3' % label_calculating) else: # If QGIS >= 2.7, we can speed up the spatial index. # From 1 min 15 to 7 seconds on my PC. self.label_progressStats.setText('%s 1/2' % label_creating) # noinspection PyArgumentList QApplication.processEvents() index = QgsSpatialIndex(stats_layer.getFeatures()) self.label_progressStats.setText('%s 2/2' % label_calculating) # noinspection PyArgumentList QApplication.processEvents() self.tab = [] for i, feature in enumerate(blurred_layer.getFeatures()): count = 0 ids = index.intersects(feature.geometry().boundingBox()) for unique_id in ids: request = QgsFeatureRequest().setFilterFid(unique_id) f = stats_layer.getFeatures(request).next() if f.geometry().intersects(feature.geometry()): count += 1 self.tab.append(count) percent = int((i + 1) * 100 / nb_feature_blurred) self.progressBar_stats.setValue(percent) # noinspection PyArgumentList QApplication.processEvents() stats = Stats(self.tab) items_stats = [ 'Count(blurred),%d' % nb_feature_blurred, 'Count(stats),%d' % nb_feature_stats, 'Min,%d' % stats.min(), 'Average,%f' % stats.average(), 'Max,%d' % stats.max(), 'Median,%f' % stats.median(), 'Range,%d' % stats.range(), 'Variance,%f' % stats.variance(), 'Standard deviation,%f' % stats.standard_deviation() ] self.tableWidget.clear() self.tableWidget.setColumnCount(2) labels = ['Parameters', 'Values'] self.tableWidget.setHorizontalHeaderLabels(labels) self.tableWidget.setRowCount(len(items_stats)) for i, item in enumerate(items_stats): s = item.split(',') self.tableWidget.setItem(i, 0, QTableWidgetItem(s[0])) self.tableWidget.setItem(i, 1, QTableWidgetItem(s[1])) self.tableWidget.resizeRowsToContents() self.draw_plot(self.tab) except GeoHealthException, e: self.label_progressStats.setText('') display_message_bar(msg=e.msg, level=e.level, duration=e.duration)
class MainWindow(QtGui.QMainWindow): def __init__(self, repo, options, parent=None): QtGui.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.repo = repo self.options = options self.createConfigurationWidget() self.createLayout() # initialize stuff self.splitChanged(split_list.index( self.options.split)) # fetch + redraw def createConfigurationWidget(self): self.configurationwidget = QtGui.QGroupBox() self.cwui = Ui_ConfigurationWidget() self.cwui.setupUi(self.configurationwidget) # set initial values self.cwui.splitComboBox.setCurrentIndex( split_list.index(self.options.split)) if self.options.filename: self.cwui.filenameLineEdit.setText(self.options.filename) if self.options.imagetitle: self.cwui.imageTitleLineEdit.setText(self.options.imagetitle) if self.options.skipmerges: self.cwui.skipMergesCheckBox.setCheckState(QtCore.Qt.Checked) if self.options.showtags: self.cwui.showTagsCheckBox.setCheckState(QtCore.Qt.Checked) if self.options.uselines: self.cwui.uselinesCheckBox.setCheckState(QtCore.Qt.Checked) self.cwui.maxcaptionSpinBox.setValue(self.options.maxcaptions) # overall min/max self.cwui.startDateEdit.setMinimumDate(self.options.repo_datemin) self.cwui.endDateEdit.setMaximumDate(self.options.repo_datemax) # initial value if self.options.datemin == None: self.cwui.startDateEdit.setDate(self.options.repo_datemin) else: self.cwui.startDateEdit.setDate(self.options.datemin) if self.options.datemax == None: self.cwui.endDateEdit.setDate(self.options.repo_datemax) else: self.cwui.endDateEdit.setDate(self.options.datemax) if self.options.datemin != None or self.options.datemax != None: self.timerangeUpdate(4) # 4 = custom self.cwui.timerangeComboBox.setCurrentIndex(4) else: self.timerangeUpdate(0) # 0 = whole range self.cwui.timerangeComboBox.setCurrentIndex(0) # # connect them all # self.connect(self.cwui.splitComboBox, QtCore.SIGNAL('currentIndexChanged(int)'), self.splitChanged) self.connect(self.cwui.timerangeComboBox, QtCore.SIGNAL('currentIndexChanged(int)'), self.timerangeChanged) self.connect(self.cwui.filenameLineEdit, QtCore.SIGNAL('textChanged(const QString)'), self.filenameChanged) self.connect(self.cwui.imageTitleLineEdit, QtCore.SIGNAL('textChanged(const QString)'), self.imageTitleChanged) self.connect(self.cwui.skipMergesCheckBox, QtCore.SIGNAL('stateChanged(int)'), self.skipMergesChanged) self.connect(self.cwui.showTagsCheckBox, QtCore.SIGNAL('stateChanged(int)'), self.showTagsChanged) self.connect(self.cwui.uselinesCheckBox, QtCore.SIGNAL('stateChanged(int)'), self.uselinesChanged) self.connect(self.cwui.maxcaptionSpinBox, QtCore.SIGNAL('valueChanged(int)'), self.maxcaptionChanged) self.connect(self.cwui.startDateEdit, QtCore.SIGNAL('dateChanged(const QDate&)'), self.timerangeChanged) self.connect(self.cwui.endDateEdit, QtCore.SIGNAL('dateChanged(const QDate&)'), self.timerangeChanged) # # remaining mainwindow stuff # self.connect(self.ui.action_About, QtCore.SIGNAL('triggered()'), self.about) self.connect(self.ui.action_Quit, QtCore.SIGNAL('triggered()'), QtGui.qApp.quit) def createLayout(self): # layout vbox = QtGui.QVBoxLayout() hbox = QtGui.QHBoxLayout() self.fig = Figure() self.fig.add_subplot(111) self.canvas = FigureCanvas(self.fig) self.canvas.setParent(self.ui.centralWidget) self.canvas.setMinimumSize(50, 50) hbox.addWidget(self.canvas, 1.) hbox.addWidget(self.configurationwidget) vbox.addLayout(hbox, 1) label = QtGui.QLabel( "You can copy paste this command line to get the same result with no graphical interface:", self.ui.centralWidget) vbox.addWidget(label) self.commandline = QtGui.QLineEdit(self.ui.centralWidget) self.commandline.setReadOnly(True) vbox.addWidget(self.commandline) self.ui.centralWidget.setLayout(vbox) self.setCentralWidget(self.ui.centralWidget) def skipMergesChanged(self, value): "This is heavy : we need to refetch everything" self.options.skipmerges = not not value self.dates = collect_data(self.repo.changelog, self.options) self.redraw() def showTagsChanged(self, value): self.options.showtags = not not value self.redraw() def uselinesChanged(self, value): "This is heavy : we need to refetch everything" self.options.uselines = not not value self.dates = collect_data(self.repo.changelog, self.options) self.redraw() def splitChanged(self, index): "This is heavy : we need to refetch everything" self.options.split = split_list[index] if index == 0: # disable maxcaptions self.cwui.maxcaptionSpinBox.setEnabled(False) self.cwui.maxcaptionsLabel.setEnabled(False) else: # enable maxcaptions self.cwui.maxcaptionSpinBox.setEnabled(True) self.cwui.maxcaptionsLabel.setEnabled(True) self.dates = collect_data(self.repo.changelog, self.options) self.redraw() def timerangeUpdate(self, index): now = datetime.now() self.options.datemax = None if index == 0: self.options.datemin = None elif index == 1: self.options.datemin = now - timedelta(365) elif index == 2: self.options.datemin = now - timedelta(30) elif index == 3: self.options.datemin = now - timedelta(7) if index == 4: # custom self.cwui.startDateEdit.setEnabled(True) self.cwui.endDateEdit.setEnabled(True) self.options.datemin = datetime.combine( self.cwui.startDateEdit.date().toPyDate(), time()) self.options.datemax = datetime.combine( self.cwui.endDateEdit.date().toPyDate(), time()) else: self.cwui.startDateEdit.setEnabled(False) self.cwui.endDateEdit.setEnabled(False) if self.options.datemin == None: self.cwui.startDateEdit.setDate(self.options.repo_datemin) else: self.cwui.startDateEdit.setDate(self.options.datemin) if self.options.datemax == None: self.cwui.endDateEdit.setDate(self.options.repo_datemax) else: self.cwui.endDateEdit.setDate(self.options.datemax) def timerangeChanged(self): "This is heavy : we need to refetch everything" index = self.cwui.timerangeComboBox.currentIndex() self.timerangeUpdate(index) self.dates = collect_data(self.repo.changelog, self.options) self.redraw() def maxcaptionChanged(self, newvalue): self.options.maxcaptions = newvalue self.redraw() def imageTitleChanged(self, newtext): self.options.imagetitle = newtext self.recomputeLineCommand() def filenameChanged(self, newtext): self.options.filename = newtext self.recomputeLineCommand() def redraw(self): draw_graph(self.fig, self.options, self.dates) self.canvas.draw() self.recomputeLineCommand() def recomputeLineCommand(self): line = "hg activity" if self.options.imagetitle != self.repo.root: line += " -t='%s'" % self.options.imagetitle if self.options.filename != 'activity.png': line += " -o='%s'" % self.options.filename if self.options.skipmerges: line += " --skipmerges" if self.options.showtags: line += " --showtags" if self.options.uselines: line += " --uselines" if self.options.split != "none": line += " --split=%s" % self.options.split if self.options.maxcaptions != 4: line += " --maxcaptions=%d" % self.options.maxcaptions if self.options.datemin != None: line += " --datemin=%s" % self.options.datemin.strftime("%Y-%m-%d") if self.options.datemax != None: line += " --datemax=%s" % self.options.datemax.strftime("%Y-%m-%d") self.commandline.setText(line) def about(self): msg = """ <h2>About</h2> hgactivity is an extension for <a href="http://mercurial.selenic.com/">mercurial</a> that creates an image displaying the activity for a repository. <br/> <br/> The official homepage is <a href="http://labs.freehackers.org/projects/hgactivity">http://labs.freehackers.org/projects/hgactivity</a>. <br/> <br/> More information can be found on the <a href="http://labs.freehackers.org/projects/hgactivity/wiki">wiki</a> and on <a href="http://labs.freehackers.org/projects/hgactivity/wiki/documentation">the documentation page</a>. <h2>Design & Coding</h2> Thomas Capricelli <*****@*****.**> <br/> <a href="http://www.freehackers.org/thomas/free-software/">http://www.freehackers.org/thomas/free-software/</a> """ box = QtGui.QDialog(self) label = QtGui.QLabel(box) label.setOpenExternalLinks(True) label.setWordWrap(True) label.setWindowTitle("About hg activity (qt interface)") label.setText(msg) vbox = QtGui.QVBoxLayout() vbox.addWidget(label) box.setLayout(vbox) button = QtGui.QPushButton("Ok", box) box.connect(button, QtCore.SIGNAL('clicked()'), box.accept) vbox.addWidget(button) box.exec_()
class IncidenceDensityDialog(QDialog): signalAskCloseWindow = pyqtSignal(int, name='signalAskCloseWindow') signalStatus = pyqtSignal(int, str, name='signalStatus') def __init__(self, parent=None): """Constructor. Base class for Incidence and Density dialogs. use_area : If you use the area of the polygon or the population field. use_point_layer : If you a point a layer, or a field in the polygon layer. """ self.parent = parent QDialog.__init__(self, parent) self.name_field = None self.admin_layer = None self.figure = None self.canvas = None self.toolbar = None self.output_file_path = None self.output_layer = None # Settings self.use_area = None self.use_point_layer = None def setup_ui(self): # Connect slot. # noinspection PyUnresolvedReferences self.button_browse.clicked.connect(self.open_file_browser) self.button_box_ok.button(QDialogButtonBox.Ok).clicked.connect( self.run_stats) self.button_box_ok.button(QDialogButtonBox.Cancel).clicked.connect( self.hide) self.button_box_ok.button(QDialogButtonBox.Cancel).clicked.connect( self.signalAskCloseWindow.emit) # Add items in symbology self.cbx_mode.addItem( 'Equal interval', QgsGraduatedSymbolRendererV2.EqualInterval) self.cbx_mode.addItem( 'Quantile (equal count)', QgsGraduatedSymbolRendererV2.Quantile) self.cbx_mode.addItem( 'Natural breaks', QgsGraduatedSymbolRendererV2.Jenks) self.cbx_mode.addItem( 'Standard deviation', QgsGraduatedSymbolRendererV2.StdDev) self.cbx_mode.addItem( 'Pretty breaks', QgsGraduatedSymbolRendererV2.Pretty) # Setup the graph. self.figure = Figure() self.canvas = FigureCanvas(self.figure) self.canvas.setMinimumSize(QSize(300, 0)) self.toolbar = CustomNavigationToolbar(self.canvas, self) self.layout_plot.addWidget(self.toolbar) self.layout_plot.addWidget(self.canvas) self.cbx_aggregation_layer.setFilters( QgsMapLayerProxyModel.PolygonLayer) if self.use_point_layer: self.cbx_case_layer.setFilters(QgsMapLayerProxyModel.PointLayer) if not self.use_area: self.cbx_population_field.setLayer( self.cbx_aggregation_layer.currentLayer()) self.cbx_aggregation_layer.layerChanged.connect( self.cbx_population_field.setLayer) self.cbx_aggregation_layer.layerChanged.connect( self.reset_field_population) self.reset_field_population() if not self.use_point_layer: self.cbx_case_field.setLayer( self.cbx_aggregation_layer.currentLayer()) self.cbx_aggregation_layer.layerChanged.connect( self.cbx_case_field.setLayer) self.cbx_aggregation_layer.layerChanged.connect( self.reset_field_case) self.reset_field_case() def reset_field_population(self): self.cbx_population_field.setCurrentIndex(0) def reset_field_case(self): self.cbx_case_field.setCurrentIndex(0) def open_file_browser(self): output_file = QFileDialog.getSaveFileNameAndFilter( self.parent, tr('Save shapefile'), filter='SHP (*.shp)') self.le_output_filepath.setText(output_file[0]) def run_stats(self): """Main function which do the process.""" # Get the common fields. self.admin_layer = self.cbx_aggregation_layer.currentLayer() if self.use_point_layer: # If we use a point layer. point_layer = self.cbx_case_layer.currentLayer() else: # If we use a column with number of case. case_column = self.cbx_case_field.currentField() index_case = self.admin_layer.fieldNameIndex(case_column) if not self.use_area: # If we don't use density. population = self.cbx_population_field.currentField() index_population = self.admin_layer.fieldNameIndex(population) if not self.name_field: self.name_field = self.le_new_column.placeholderText() # Add new column. add_nb_intersections = self.checkBox_addNbIntersections.isChecked() # Ratio ratio = self.cbx_ratio.currentText() ratio = ratio.replace(' ', '') # Output. self.output_file_path = self.le_output_filepath.text() try: self.button_box_ok.setDisabled(True) # noinspection PyArgumentList QApplication.setOverrideCursor(Qt.WaitCursor) # noinspection PyArgumentList QApplication.processEvents() if not self.admin_layer: raise NoLayerProvidedException if not self.admin_layer and self.use_point_layer: raise NoLayerProvidedException crs_admin_layer = self.admin_layer.crs() if self.use_point_layer: crs_point_layer = point_layer.crs() if crs_admin_layer != crs_point_layer: raise DifferentCrsException( epsg1=crs_point_layer.authid(), epsg2=crs_admin_layer.authid()) if not self.use_point_layer and not self.use_area: if index_population == index_case: raise FieldException(field_1='Population', field_2='Case') try: ratio = float(ratio) except ValueError: raise NotANumberException(suffix=ratio) # Output if not self.output_file_path: temp_file = NamedTemporaryFile( delete=False, suffix='-geohealth.shp') self.output_file_path = temp_file.name temp_file.flush() temp_file.close() admin_layer_provider = self.admin_layer.dataProvider() fields = self.admin_layer.pendingFields() if admin_layer_provider.fieldNameIndex(self.name_field) != -1: raise FieldExistingException(field=self.name_field) fields.append(QgsField(self.name_field, QVariant.Double)) if add_nb_intersections: fields.append(QgsField('nb_of_intersections', QVariant.Int)) data = [] file_writer = QgsVectorFileWriter( self.output_file_path, 'utf-8', fields, QGis.WKBPolygon, self.admin_layer.crs(), 'ESRI Shapefile') if self.use_point_layer: total_case = point_layer.featureCount() else: total_case = 0 for i, feature in enumerate(self.admin_layer.getFeatures()): attributes = feature.attributes() if self.use_point_layer: count = 0 for f in point_layer.getFeatures(): if f.geometry().intersects(feature.geometry()): count += 1 else: count = int(attributes[index_case]) total_case += count try: if self.use_area: area = feature.geometry().area() value = float(count) / area * ratio else: try: population = float(attributes[index_population]) except ValueError: raise NotANumberException( suffix=attributes[index_population]) value = float(count) / population * ratio except ZeroDivisionError: value = None except TypeError: value = None data.append(value) attributes.append(value) if add_nb_intersections: attributes.append(count) new_feature = QgsFeature() new_geom = QgsGeometry(feature.geometry()) new_feature.setAttributes(attributes) new_feature.setGeometry(new_geom) file_writer.addFeature(new_feature) del file_writer self.output_layer = QgsVectorLayer( self.output_file_path, self.name_field, 'ogr') QgsMapLayerRegistry.instance().addMapLayer(self.output_layer) if self.checkBox_incidence_runStats.isChecked(): stats = Stats(data) items_stats = [ 'Incidence null,%d' % stats.null_values(), 'Count(point),%d' % total_case, 'Count(polygon),%d' % self.admin_layer.featureCount(), 'Min,%d' % stats.min(), 'Average,%f' % stats.average(), 'Max,%d' % stats.max(), 'Median,%f' % stats.median(), 'Range,%d' % stats.range(), 'Variance,%f' % stats.variance(), 'Standard deviation,%f' % stats.standard_deviation() ] self.tableWidget.clear() self.tableWidget.setColumnCount(2) labels = ['Parameters', 'Values'] self.tableWidget.setHorizontalHeaderLabels(labels) self.tableWidget.setRowCount(len(items_stats)) for i, item in enumerate(items_stats): s = item.split(',') self.tableWidget.setItem(i, 0, QTableWidgetItem(s[0])) self.tableWidget.setItem(i, 1, QTableWidgetItem(s[1])) self.tableWidget.resizeRowsToContents() self.draw_plot(data) else: self.hide() if self.symbology.isChecked(): self.add_symbology() self.signalStatus.emit(3, tr('Successful process')) except GeoPublicHealthException, e: display_message_bar(msg=e.msg, level=e.level, duration=e.duration) finally:
qscrollLayout.setGeometry(QtCore.QRect(0, 0, 1000, 1000)) qscroll.setWidget(qscrollContents) qscroll.setWidgetResizable(True) for i in xrange(5): qfigWidget = QtGui.QWidget(qscrollContents) fig = Figure((5.0, 4.0), dpi=100) canvas = FigureCanvas(fig) canvas.setParent(qfigWidget) toolbar = NavigationToolbar(canvas, qfigWidget) axes = fig.add_subplot(111) axes.plot([1,2,3,4]) # place plot components in a layout plotLayout = QtGui.QVBoxLayout() plotLayout.addWidget(canvas) plotLayout.addWidget(toolbar) qfigWidget.setLayout(plotLayout) # prevent the canvas to shrink beyond a point # original size looks like a good minimum size canvas.setMinimumSize(canvas.size()) qscrollLayout.addWidget(qfigWidget) qscrollContents.setLayout(qscrollLayout) qwidget.show() exit(qapp.exec_())
class MatplotWidget(QWidget): """ Class to plot data inside a QWidget """ def __init__(self, parent=None, toolbar=False): """ """ super(MatplotWidget, self).__init__(parent) self.figure, self.axes = plt.subplots(nrows=1, ncols=1) self.canvas = FigureCanvasQTAgg(self.figure) self.figure.subplots_adjust(right=0.85) self.figure.subplots_adjust(left=0.1) self.figure.subplots_adjust(bottom=0.3) self.axes1 = self.axes.twinx() self.axes1.set_ylabel('quality') self.axes.locator_params(nbins=5) self.axes1.locator_params(nbins=5) self.vbox = QVBoxLayout(self) if toolbar: self.toolbar = NavigationToolbar(self.canvas, self) self.vbox.addWidget(self.toolbar) self.vbox.addWidget(self.canvas) def set_data(self, data, qi=False, min_size=False): """ draw data to canvas Args: data (sensor) : sensor containing data qi (bool): if true plot quality min_size (bool): force to set min size to chart """ self.figure.suptitle(data.name, fontsize=12) self.axes.set_ylabel(data.unit, fontsize=12) self.axes.set_xlabel('') ax = data.plot(quality=qi, axis=self.axes, qaxis=self.axes1) n = 5 ticks = ax.xaxis.get_ticklocs() ticklabels = [l.get_text() for l in ax.xaxis.get_ticklabels()] ax.xaxis.set_ticks(ticks[::n]) ax.xaxis.set_ticklabels(ticklabels[::n]) if min_size: size = self.canvas.size() size.setHeight(size.height() / 2) self.canvas.setMinimumSize(size) def set_multiple_data(self, data, qi=False): """ Plot multiple data source to chart Args: data (list): list of sensor to plot qi (bool): if true plot quality """ colors = ['b', 'g', 'm', 'lime', 'orange', 'gray', 'salmon', 'tomato'] ax = None labels = [] for idx, evt in enumerate(data): if len(evt.ts) == 0: continue color = colors[idx % len(colors)] ax = evt.plot(quality=qi, data_color=color, axis=self.axes, qaxis=self.axes1) labels.append(evt.name) lines, _ = ax.get_legend_handles_labels() ax.legend(lines, labels, loc='best') plt.legend(loc="upper left", bbox_to_anchor=[0, 1], ncol=2, shadow=True, title="Legend", fancybox=True) if not ax: n = 5 ticks = ax.xaxis.get_ticklocs() ticklabels = [l.get_text() for l in ax.xaxis.get_ticklabels()] ax.xaxis.set_ticks(ticks[::n]) ax.xaxis.set_ticklabels(ticklabels[::n])
class TakanamiDialog(QtGui.QDialog): """A dialog to apply Takanami's AR picking method to a selected piece of a seismic signal. Attributes: document: Current opened document containing a seismic record. seismic_event: A seismic event to be refined by using Takanami method. If no event is provided, then a new seismic event will be created by using the estimated arrival time after clicking on 'Accept' """ def __init__(self, document, t_start=None, t_end=None, seismic_event=None, parent=None): super(TakanamiDialog, self).__init__(parent) self.document = document self.record = self.document.record self.load_settings() self.seismic_event = seismic_event self._start = t_start self._end = t_end if self.seismic_event is not None: self.event_time = self.seismic_event.stime if self._start is None: self._start = max(0, self.event_time - self.default_margin) if self._end is None: self._end = min(len(self.record.signal) - 1, self.event_time + self.default_margin) else: if self._start is None or self._end is None: raise ValueError("t_start and t_end values not specified") else: self._start = max(0, int(t_start * self.record.fs)) self._end = min(len(self.record.signal) - 1, int(t_end * self.record.fs)) self.event_time = self._start + int((self._end - self._start) / 2) if not 0 <= self._start < self._end: raise ValueError("Invalid t_start value") if not self._start < self._end < len(self.record.signal): raise ValueError("Invalid t_end value") if (self._end - self._start) < (MINIMUM_MARGIN_IN_SECS * self.record.fs): raise ValueError("Distance between t_start and t_end must be" " at least of %g seconds" % MINIMUM_MARGIN_IN_SECS) if not self._start < self.event_time < self._end: raise ValueError("Event time must be a value between t-start and t_end") self._init_ui() self.button_box.accepted.connect(self.accept) self.button_box.rejected.connect(self.reject) self.button_box.clicked.connect(self.on_click) self.start_point_spinbox.timeChanged.connect(self.on_start_point_changed) self.end_point_spinbox.timeChanged.connect(self.on_end_point_changed) def _init_ui(self): self.setWindowTitle("Takanami's Autoregressive Method") self.fig, _ = plt.subplots(2, 1, sharex=True) self.canvas = FigureCanvas(self.fig) self.canvas.setMinimumSize(self.canvas.size()) self.canvas.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Policy.Expanding, QtGui.QSizePolicy.Policy.Expanding)) self.toolBarNavigation = navigationtoolbar.NavigationToolBar(self.canvas, self) self.position_label = QtGui.QLabel("Estimated Arrival Time: 00 h 00 m 00.000 s") self.group_box = QtGui.QGroupBox(self) self.group_box.setTitle("Limits") self.start_point_label = QtGui.QLabel("Start point:") self.start_point_label.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Policy.Maximum, QtGui.QSizePolicy.Policy.Preferred)) self.start_point_spinbox = QtGui.QTimeEdit(self.group_box) self.start_point_spinbox.setDisplayFormat("hh 'h' mm 'm' ss.zzz 's'") self.end_point_label = QtGui.QLabel("End point:") self.end_point_label.setSizePolicy(QtGui.QSizePolicy(QtGui.QSizePolicy.Policy.Maximum, QtGui.QSizePolicy.Policy.Preferred)) self.end_point_spinbox = QtGui.QTimeEdit(self.group_box) self.end_point_spinbox.setDisplayFormat("hh 'h' mm 'm' ss.zzz 's'") self.group_box_layout = QtGui.QHBoxLayout(self.group_box) self.group_box_layout.setContentsMargins(9, 9, 9, 9) self.group_box_layout.setSpacing(12) self.group_box_layout.addWidget(self.start_point_label) self.group_box_layout.addWidget(self.start_point_spinbox) self.group_box_layout.addWidget(self.end_point_label) self.group_box_layout.addWidget(self.end_point_spinbox) self.button_box = QtGui.QDialogButtonBox(self) self.button_box.setOrientation(QtCore.Qt.Horizontal) self.button_box.setStandardButtons(QtGui.QDialogButtonBox.Apply | QtGui.QDialogButtonBox.Cancel | QtGui.QDialogButtonBox.Ok) self.layout = QtGui.QVBoxLayout(self) self.layout.setContentsMargins(9, 9, 9, 9) self.layout.setSpacing(6) self.layout.addWidget(self.toolBarNavigation) self.layout.addWidget(self.canvas) self.layout.addWidget(self.position_label) self.layout.addWidget(self.group_box) self.layout.addWidget(self.button_box) # set spinboxes's initial values and limits max_time_in_msecs = int(((len(self.record.signal) - 1) * 1000) / self.record.fs) start_time_in_msecs = int((self._start * 1000.0) / self.record.fs) end_time_in_msecs = int((self._end * 1000.0) / self.record.fs) self.start_point_spinbox.setTime(QtCore.QTime().addMSecs(start_time_in_msecs)) self.end_point_spinbox.setTime(QtCore.QTime().addMSecs(end_time_in_msecs)) self.start_point_spinbox.setMinimumTime(QtCore.QTime().addMSecs(0)) self.end_point_spinbox.setMinimumTime(QtCore.QTime().addMSecs(start_time_in_msecs + MINIMUM_MARGIN_IN_SECS * 1000)) self.start_point_spinbox.setMaximumTime(QtCore.QTime().addMSecs(end_time_in_msecs - MINIMUM_MARGIN_IN_SECS * 1000)) self.end_point_spinbox.setMaximumTime(QtCore.QTime().addMSecs(max_time_in_msecs)) def on_click(self, button): if self.button_box.standardButton(button) == QtGui.QDialogButtonBox.Ok: self.save_event() if self.button_box.standardButton(button) == QtGui.QDialogButtonBox.Apply: self.do_takanami() def on_start_point_changed(self, value): time_in_msecs = QtCore.QTime().msecsTo(value) t_start = int(max(0, (time_in_msecs / 1000.0) * self.record.fs)) if self._start != t_start: self._start = t_start self.end_point_spinbox.setMinimumTime(QtCore.QTime(). addMSecs(time_in_msecs + MINIMUM_MARGIN_IN_SECS * 1000)) def on_end_point_changed(self, value): time_in_msecs = QtCore.QTime().msecsTo(value) t_end = int(min(len(self.record.signal), ((time_in_msecs / 1000.0) * self.record.fs))) if self._end != t_end: self._end = t_end self.start_point_spinbox.setMaximumTime(QtCore.QTime(). addMSecs(time_in_msecs - MINIMUM_MARGIN_IN_SECS * 1000)) def on_position_estimated(self, time, aic, n0_aic): self.event_time = time time_in_secs = self.event_time / self.record.fs self.position_label.setText("Estimated Arrival Time: {}".format( clt.float_secs_2_string_date(time_in_secs, starttime=self.record.starttime))) # Plot estimated arrival time m_event = rc.ApasvoEvent(self.record, time, aic=aic, n0_aic=n0_aic) m_event.plot_aic(show_envelope=True, num=self.fig.number) self.fig.canvas.draw_idle() def load_settings(self): """Loads settings from persistent storage.""" settings = QtCore.QSettings(_organization, _application_name) settings.beginGroup("takanami_settings") self.default_margin = int(float(settings.value('takanami_margin', 5.0)) * self.record.fs) settings.endGroup() def save_event(self): """""" if self.seismic_event is not None: if self.seismic_event.stime != self.event_time: self.document.editEvent(self.seismic_event, stime=self.event_time, method=rc.method_takanami, evaluation_mode=rc.mode_automatic, evaluation_status=rc.status_preliminary) else: self.document.createEvent(self.event_time, method=rc.method_takanami, evaluation_mode=rc.mode_automatic, evaluation_status=rc.status_preliminary) def do_takanami(self): self._task = TakanamiTask(self.record, self._start, self._end) self._task.position_estimated.connect(self.on_position_estimated) self.wait_dialog = processingdialog.ProcessingDialog(label_text="Applying Takanami's AR method...") self.wait_dialog.setWindowTitle("Event detection") return self.wait_dialog.run(self._task) def exec_(self, *args, **kwargs): return_code = self.do_takanami() if return_code == QtGui.QDialog.Accepted: return QtGui.QDialog.exec_(self, *args, **kwargs)
class Window(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.shot = None #opened shot self.folder_name = '' #folder to search for shots self.current_num = 0 #current diagram self.currently_selected = None #selected point plot self.selected_points = OrderedSet() #point to be added self.current_point = None #plot of current point self.overall_selected = None #points added to selected list #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) self.canvas.setParent(parent) self.canvas.setFocusPolicy(QtCore.Qt.StrongFocus) self.canvas.setFocus() self.canvas.setMinimumSize(500, 0) self.canvas.mpl_connect('pick_event', self.on_pick) self.canvas.mpl_connect('motion_notify_event', self.on_move) self.canvas.hide() # this is the Navigation widget # it takes the Canvas widget and a pa rent self.toolbar = NavigationToolbar(self.canvas, self) self.toolbar.hide() # Show files widget self.files = QtGui.QListWidget() self.files.itemDoubleClicked.connect(self.select_file) self.files.setMaximumSize(200, 100000) self.files.setMinimumSize(100, 0) self.files.hide() # Show selected points self.points = ThumbListWidget(self) #self.points.itemDoubleClicked.connect(self.unselect_point) self.points.itemClicked.connect(self.points_clicked) self.points.itemDoubleClicked.connect(self.points_doubleclicked) self.points.setMaximumSize(200, 100000) self.points.setMinimumSize(100, 0) self.points.hide() #Show diagram widget self.diagrams = QtGui.QListWidget() self.diagrams.itemClicked.connect(self.select_item) self.diagrams.setMaximumSize(250, 100000) self.diagrams.setMinimumSize(190, 0) self.diagrams.hide() #save result button self.save_button = QtGui.QPushButton('Add time point', self) self.save_button.clicked.connect(self.add_time) self.save_button.hide() #filter menu self.filters_button = QtGui.QPushButton('Manage filters', self) self.filters_button.clicked.connect(self.show_filters) self.filters_button.hide() self.filters = OrderedDict self.read_filters() #diagramms self.bottom_layout = QtGui.QGridLayout() self.diagrams_figure = plt.figure() self.diagrams_canvas = FigureCanvas(self.diagrams_figure) self.diagrams_canvas.setParent(parent) self.diagrams_canvas.setMinimumSize(250, 250) self.diagrams_canvas.setMaximumSize(500, 500) self.diagrams_toolbar = NavigationToolbar(self.diagrams_canvas, self) self.diagrams_toolbar.setMaximumWidth(250) self.diagrams_ax = self.diagrams_figure.add_subplot(111) self.diagrams_ax.set_ylim(ymin=0) self.diagrams_ax.set_xlim(xmin=0) self.diagrams_canvas.draw() self.enlargre_button = QtGui.QPushButton('Enlarge diagram', self) self.enlargre_button.clicked.connect(self.enlarge_diagram) self.bottom_layout.addWidget(self.diagrams_toolbar, 0, 2) self.bottom_layout.addWidget(self.diagrams_canvas, 1, 2, QtCore.Qt.AlignRight) self.bottom_layout.addWidget(self.enlargre_button, 0, 1) # set the layout self.layout = QtGui.QGridLayout() self.layout.addWidget(self.filters_button, 0, 1) self.layout.addWidget(self.toolbar, 0, 2) self.layout.addWidget(self.canvas, 1, 2) self.layout.addWidget(self.diagrams, 1, 1) self.layout.addWidget(self.files, 1, 0) self.layout.addWidget(self.points, 1, 3) self.layout.addWidget(self.save_button, 0, 3) self.layout.addLayout(self.bottom_layout, 2, 2) self.setLayout(self.layout) def enlarge_diagram(self): #меняет местами диаграммы pass def points_doubleclicked(self): if self.points._mouse_button == 1: num = self.points.currentRow() point = list(self.selected_points)[num] diag = self.shot.get_diagram(self.current_num) xs = np.array(diag.x) ys = np.array(diag.y) idx = np.absolute(xs - point[0]).argmin() npoint = (xs[idx], ys[idx], self.current_num, self.shot.file[0]) for point in list(self.selected_points): if point[2] == self.current_point[2] and point[3] == self.current_point[3]: self.selected_points.remove(point) self.selected_points.add(npoint) self.refresh_points() def greenvald(self): #диаграмма хьюгилла #TODO - move to another file temp = {} names = self.shot.get_diagram_names() for x in self.selected_points: if x[3] not in temp: temp[x[3]] = {} tag = "" for name, value in self.filters.items(): if re.compile(value).match(names[x[2]]): tag = name break if tag: temp[x[3]][tag] = x[0], x[1], x[3] #X, Y, Shot points = [] for x in temp: if "Ip" in temp[x] and "neL" in temp[x] and "ITF" in temp[x]: a = 24 R = 36 k = 1.65 #print("wololo") Ip = temp[x]["Ip"][1]/1000 Itf = temp[x]["ITF"][1]/1000 neL = temp[x]["neL"][1] Bt = Itf*0.001*100*16*0.2/R print(Ip) print(Itf) print(neL) print(Bt) qcyl = 5*a*a*0.01*0.01*Bt*100*1000/(R*Ip) print(qcyl) #print(temp[x]) #print(Itf) #print(neL) rqcyl = 1/qcyl print(rqcyl) print("wololo") ne = neL*0.03/k BtrR = Bt*100/R print(ne) print(BtrR) neRrBt = ne/BtrR print(neRrBt) points.append(((neRrBt, rqcyl), temp[x]["Ip"][2])) return points def update_diagramms(self): points = self.greenvald() x = [tmp[0][0] for tmp in points] y = [tmp[0][1] for tmp in points] #self.diagrams_figure.clf() self.diagrams_ax.set_xlabel('neR/BT, 10^20/(T*m^2)') self.diagrams_ax.set_ylabel('1/qcyl') self.diagrams_ax.set_title("Greenwald") self.diagrams_ax.plot(x, y, 'bo', ms=5, alpha=0.8, markersize=5) self.diagrams_canvas.draw() print(points) def points_clicked(self):#один клик, правая кнопка - удалить точку, левая - подсветить if self.points._mouse_button == 1: num = self.points.currentRow() point = list(self.selected_points)[num] diag = self.shot.get_diagram(self.current_num) xs = np.array(diag.x) ys = np.array(diag.y) idx = np.absolute(xs - point[0]).argmin() self.highlight.set_xdata([xs[idx]]) self.highlight.set_ydata([ys[idx]]) else: self.unselect_point(None) def read_filters(self): with open("filters.conf") as inp: lines = inp.readlines() n = int(lines[0]) mass = [] for i in range(n): mass.append((lines[2*i+1].strip(), lines[2*(i+1)].strip())) self.filters = OrderedDict(mass) def show_filters(self): self.f = FiltersPopup(self.filters) self.f.setGeometry(100, 100, 400, 200) self.f.exec_() self.filters = self.f.getValues() self.show_diagrams() def add_time(self): time, ok = QtGui.QInputDialog.getText(self, 'Time point', 'enter time point in seconds(e.g. 0.123):') if ok: if time.isdigit: diag = self.shot.get_diagram(self.current_num) xs = np.array(diag.x) ys = np.array(diag.y) idx = np.absolute(xs - float(time)/1000).argmin() npoint = (xs[idx], ys[idx], self.current_num, self.shot.file[0]) for point in list(self.selected_points): if point[2] == self.current_point[2] and point[3] == self.current_point[3]: print("wololololololo") self.selected_points.remove(point) self.selected_points.add(npoint) self.refresh_points() def select_item(self, current): self.figure.clf() name = self.diagrams.currentItem().text() names = self.shot.get_diagram_names() if name in names: self.current_num = names.index(name) else: self.current_num = names.index("".join(name.split(':')[1:])[1:]) self.plot(self.shot.get_diagram(self.current_num)) def unselect_point(self, current): num = self.points.currentRow() self.selected_points.remove(list(self.selected_points)[num]) self.refresh_points() def select_file(self, current): self.figure.clf() self.show_shot(Shot(join(self.folder_name, self.files.currentItem().text()))) self.canvas.setFocus() def on_pick(self, event): print(self.selected_points) if self.current_point in self.selected_points: self.selected_points.remove(self.current_point) else: for point in list(self.selected_points): if point[2] == self.current_point[2] and point[3] == self.current_point[3]: print("wololo") self.selected_points.remove(point) self.selected_points.add(self.current_point) self.refresh_points() def refresh_points(self): self.update_diagramms() self.points.clear() self.points.addItems([str(x[0]) for x in self.selected_points]) self.overall_selected.set_xdata(self.active_points[0]) self.overall_selected.set_ydata(self.active_points[1]) def on_move(self, event): # get the x and y pixel coords x, y = event.x, event.y if event.inaxes: ax = event.inaxes # the axes instance diag = self.shot.get_diagram(self.current_num) xs = np.array(diag.x) ys = np.array(diag.y) idx = np.absolute(xs - event.xdata).argmin() self.currently_selected.set_xdata([diag.x[idx]]) self.currently_selected.set_ydata([diag.y[idx]]) self.current_point = (diag.x[idx], diag.y[idx], self.current_num, self.shot.file[0]) self.canvas.draw() @property def active_points(self): x = [x[0] for x in self.selected_points if x[2] == self.current_num and x[3] == self.shot.file[0]] y = [x[1] for x in self.selected_points if x[2] == self.current_num and x[3] == self.shot.file[0]] return x, y def plot(self, diagram=None): # create an axis ax = self.figure.add_subplot(111) # discards the old graph #pridicted max value ind = np.argmax(np.array(diagram.y)) # plot data if diagram: self.highlight, = ax.plot([diagram.x[ind]], [diagram.y[ind]], 'bo', ms=12, alpha=0.8, markersize=8) ax.plot(diagram.x, diagram.y, 'b-') self.currently_selected, = ax.plot([diagram.x[ind]], [diagram.y[ind]], 'yo', ms=12, alpha=0.6, markersize=6, picker=15) self.overall_selected, = ax.plot(self.active_points[0], self.active_points[1], 'ro', ms=12, alpha=0.9, markersize=4) ax.set_xlabel('t, sec') ax.set_ylabel(diagram.unit) ax.set_title(diagram.comment) self.figure.tight_layout() # refresh canvas self.canvas.draw() def show_diagrams(self): names = self.shot.get_diagram_names() self.diagrams.clear() res = set() for x in names: for name, reg in self.filters.items(): try: if re.compile(reg).match(x): res.add(str(name) + ': ' + str(x)) break except: pass #self.diagrams.addItems(list(names)) self.diagrams.addItems(list(res)) self.diagrams.show() def show_shot(self, shot): self.shot = shot self.show_diagrams() self.toolbar.show() self.canvas.show() self.files.show() self.points.show() self.save_button.show() self.filters_button.show() self.current_num = 0 self.plot(self.shot.get_diagram(0)) self.canvas.setFocus()