class MatplotlibWidget(QtGui.QWidget):
    """
    Implements a Matplotlib figure inside a QWidget.
    Use getFigure() and redraw() to interact with matplotlib.
    
    Example::
    
        mw = MatplotlibWidget()
        subplot = mw.getFigure().add_subplot(111)
        subplot.plot(x,y)
        mw.draw()
    """
    
    def __init__(self, size=(5.0, 4.0), dpi=100):
        QtGui.QWidget.__init__(self)
        self.fig = Figure(size, dpi=dpi)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)
        self.toolbar = NavigationToolbar(self.canvas, self)
        
        self.vbox = QtGui.QVBoxLayout()
        self.vbox.addWidget(self.toolbar)
        self.vbox.addWidget(self.canvas)
        
        self.setLayout(self.vbox)

    def getFigure(self):
        return self.fig
        
    def draw(self):
        self.canvas.draw()
예제 #2
0
class ApplicationWindow(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)        
        self.initUI()
    def initUI(self):
        self.main_frame = QtGui.QWidget()        
        self.setWindowTitle("Matplotlib Figure in a Qt4 Window with Navigation Toolbar")
        self.fig=Figure() 
        self.axes = self.fig.add_subplot(111)
        self.x = np.arange(0.0, 1.0, 0.01)
        self.y = np.cos(2*np.pi*self.x + 5) + 2
        self.axes.plot(self.x, self.y)
        self.canvas=FigureCanvas(self.fig)
        self.canvas.setParent(self.main_frame)
        self.canvas.setFocusPolicy(QtCore.Qt.StrongFocus)
        self.canvas.setFocus()
        self.ntb = NavigationToolbar(self.canvas, self.main_frame)
        self.canvas.mpl_connect('key_press_event', self.on_key_press)
       
        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(self.canvas)  # the matplotlib canvas
        vbox.addWidget(self.ntb)
        self.main_frame.setLayout(vbox)
        self.setCentralWidget(self.main_frame)

    def on_key_press(self, event):
        print('you pressed', event.key)
        key_press_handler(event, self.canvas, self.ntb)
예제 #3
0
파일: general.py 프로젝트: cwfinn/igmtools
    def display(self):
        """
        Show the plot in an interactive window.

        """

        # Host widget for show():
        app = QApplication(sys.argv)
        app.aboutToQuit.connect(app.deleteLater)
        main_frame = QWidget()

        # Attach canvas to host widget:
        canvas = FigureCanvasQTAgg(self)
        canvas.setParent(main_frame)

        # Make navigation toolbar:
        mpl_toolbar = NavigationToolbar2QT(self.canvas, main_frame)

        # Set up layout:
        vbox = QVBoxLayout()
        vbox.addWidget(mpl_toolbar)
        vbox.addWidget(self.canvas)

        # Set the layout to the host widget:
        main_frame.setLayout(vbox)

        # Set figure manager:
        FigureManagerQT(self.canvas, 1)

        # Show plot:
        self.show()
        app.exec_()
class dibujante2(QMainWindow):

    def __init__(self, parent, cont):#Hay que pasarle la ventana que lo invoca

        QMainWindow.__init__(self, parent)
        self.fm = cont.dominio.metodo
        self.fm.calcular()

        #self.fm.calcularpozo(1,1,500)
        #self.fm.calcularpozo(10,0.2,10)


        self.main_frame = QWidget()
        self.setWindowTitle(u'Gráficas')

        self.canvas = FigureCanvas(self.fm.fig)
        self.canvas.setParent(self.main_frame)

        vbox = QVBoxLayout()
        vbox.addWidget(self.canvas)
        self.setCentralWidget(self.main_frame)
        self.fm.axt.mouse_init()

    def draw(self):

        self.canvas.draw()
예제 #5
0
class MatplotlibPlot:
    """ Class encapsulating a matplotlib plot"""

    def __init__(self, parent = None, dpi = 100, size = (5,5)):
        """ Class initialiser """

        self.dpi = dpi
        self.figure = Figure(size, dpi = self.dpi)
        self.canvas = FigureCanvas(self.figure)
        self.canvas.setParent(parent)

        # Create the navigation toolbar, tied to the canvas
        self.toolbar = NavigationToolbar(self.canvas, parent)
        self.canvas.show()
        self.toolbar.show()

        # Reset the plot landscape
        self.figure.clear()

    def plotMultiPixel(self, info, data):
        """ Generate multi-pixel plot """

        # Tabula Rasa
        self.figure.clear()
        rows = math.ceil(math.sqrt(info['nbeams']))

	    # Display a subplot per beam (randomly for now)
        for i in range(info['nbeams']):
            ax = self.figure.add_subplot(rows, rows, i)
            ax.plot(data[:,512,i])
            
        

    def updatePlot(self):
        self.canvas.draw()
예제 #6
0
def CreateAnovaResult(x_plot, y_plot, x_fcrit, y_fcrit, F_critical):

    main_frame = QtGui.QWidget()

    dpi = 100
    fig = Figure((5.0, 4.0), dpi=dpi)
    canvas = FigureCanvas(fig)
    canvas.setParent(main_frame)
    axes = fig.add_subplot(111)

    mpl_toolbar = NavigationToolbar(canvas, main_frame)
    hbox = QtGui.QHBoxLayout()
    vbox = QtGui.QVBoxLayout()
    vbox.addWidget(canvas)
    vbox.addWidget(mpl_toolbar)
    vbox.addLayout(hbox)

    main_frame.setLayout(vbox)

    axes.clear()

    # Plot the F-Distribution for dfB and dfW

    axes.fill_between(x_plot, y_plot, alpha=.2)
    axes.plot(x_plot, y_plot)
    # Plot the F-critical value at alpha .05
    axes.fill_between(x_fcrit, y_fcrit, alpha=.5)
    axes.text(F_critical, .07, '$F_{critical}=$'+str(F_critical))
    axes.set_xlabel(u'F-degerleri')
    axes.set_ylabel(u'Olasilik')

    canvas.draw()
    return main_frame
예제 #7
0
def CreateRegression(x, y):

    main_frame = QtGui.QWidget()

    dpi = 100
    fig = Figure((5.0, 4.0), dpi=dpi)
    canvas = FigureCanvas(fig)
    canvas.setParent(main_frame)
    axes = fig.add_subplot(111)

    mpl_toolbar = NavigationToolbar(canvas, main_frame)
    hbox = QtGui.QHBoxLayout()
    vbox = QtGui.QVBoxLayout()
    vbox.addWidget(canvas)
    vbox.addWidget(mpl_toolbar)
    vbox.addLayout(hbox)

    main_frame.setLayout(vbox)

    axes.clear()

    m, b = np.polyfit(x, y, 1)

    yp = polyval([m, b], x)

    axes.plot(x, yp)
    axes.scatter(x,y)
    axes.grid(True)
    axes.set_xlabel('x')
    axes.set_ylabel('y')

    canvas.draw()

    return main_frame
예제 #8
0
def CreateLinePlot(x,y):

        main_frame = QtGui.QWidget()
        
        dpi = 100
        fig = Figure((5.0, 4.0), dpi=dpi)
        canvas = FigureCanvas(fig)
        canvas.setParent(main_frame)

        axes = fig.add_subplot(111)
        
        mpl_toolbar = NavigationToolbar(canvas, main_frame)

        hbox = QtGui.QHBoxLayout()

        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(canvas)
        vbox.addWidget(mpl_toolbar)
        vbox.addLayout(hbox)
        
        main_frame.setLayout(vbox)
               
        # clear the axes and redraw the plot anew
        #
        axes.clear()                       
        
        axes.plot(x, y)
               
        canvas.draw()

        return main_frame
예제 #9
0
def CreateScatter(valueList1, valueList2):

        main_frame = QtGui.QWidget()
        
        dpi = 100
        fig = Figure((5.0, 4.0), dpi=dpi)
        canvas = FigureCanvas(fig)
        canvas.setParent(main_frame)

        axes = fig.add_subplot(111)
        
        mpl_toolbar = NavigationToolbar(canvas, main_frame)

        hbox = QtGui.QHBoxLayout()

        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(canvas)
        vbox.addWidget(mpl_toolbar)
        vbox.addLayout(hbox)
        
        main_frame.setLayout(vbox)
               
        # clear the axes and redraw the plot anew
        #
        axes.clear()                       
        
        axes.scatter(valueList1, valueList2, color="blue", edgecolor="none")
               
        canvas.draw()

        return main_frame
예제 #10
0
def CreatePieChart(labels,sizes):    

        main_frame = QtGui.QWidget()
        
        dpi = 100
        fig = Figure((5.0, 4.0), dpi=dpi)
        canvas = FigureCanvas(fig)
        canvas.setParent(main_frame)

        axes = fig.add_subplot(111)
        
        mpl_toolbar = NavigationToolbar(canvas, main_frame)

        hbox = QtGui.QHBoxLayout()

        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(canvas)
        vbox.addWidget(mpl_toolbar)
        vbox.addLayout(hbox)
        
        main_frame.setLayout(vbox)

        # clear the axes and redraw the plot anew
        #
        axes.clear() 
          
        explode=(0, 0, 0, 0)             
        
        axes.pie(sizes, labels=labels, autopct='%1.1f%%', shadow=True)
               
        canvas.draw()

        return main_frame
예제 #11
0
def CreateHistogram(serie, binCount): 

        main_frame = QtGui.QWidget()
        
        dpi = 100
        fig = Figure((5.0, 4.0), dpi=dpi)
        canvas = FigureCanvas(fig)
        canvas.setParent(main_frame)

        axes = fig.add_subplot(111)
        
        mpl_toolbar = NavigationToolbar(canvas, main_frame)

        hbox = QtGui.QHBoxLayout()

        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(canvas)
        vbox.addWidget(mpl_toolbar)
        vbox.addLayout(hbox)
        
        main_frame.setLayout(vbox)
               
        # clear the axes and redraw the plot anew
        #
        axes.clear()                
        
        axes.hist(serie, binCount, facecolor='green')

        axes.yaxis.grid(True, linestyle='-', which='major', color='lightgrey')
        axes.set_axisbelow(True)
               
        canvas.draw()

        return main_frame
예제 #12
0
    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']
예제 #13
0
class PlotWidget(QWidget):
    def __init__(self):
        super(PlotWidget, self).__init__()
        self.initUI()
        self.data = np.arange(20).reshape([4, 5]).copy()
        self.on_draw()

    def initUI(self):
        self.fig = Figure((5.0, 4.0), dpi=50)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)
        self.canvas.setFocusPolicy(Qt.StrongFocus)
        self.canvas.setFocus()
        # self.mpl_toolbar = NavigationToolbar(self.canvas, self)
        #
        # self.canvas.mpl_connect('key_press_event', self.on_key_press)

        vbox = QVBoxLayout()
        vbox.addWidget(self.canvas)  # the matplotlib canvas
        # vbox.addWidget(self.mpl_toolbar)
        self.setLayout(vbox)

    def on_draw(self):
        self.fig.clear()
        self.axes = self.fig.add_subplot(111)
        # self.axes.plot(self.x, self.y, 'ro')
        self.axes.imshow(self.data, interpolation='nearest')
        # self.axes.plot([1,2,3])
        self.canvas.draw()

    def on_key_press(self, event):
        print('you pressed', event.key)
        # implement the default mpl key press events described at
        # http://matplotlib.org/users/navigation_toolbar.html#navigation-keyboard-shortcuts
        key_press_handler(event, self.canvas, self.mpl_toolbar)
예제 #14
0
파일: plotpanel.py 프로젝트: kjuraic/SAXS
 def plot(self,datastr):
     data=json.loads(unicode(datastr))
     if  "data" in data and "graphs" in data["data"]:
         graphdata= data["data"]["graphs"]
         if len(graphdata)<len(self.canvases):
             for i in reversed(range(self.layout.count())): 
                 self.layout.itemAt(i).widget().deleteLater()
             
             self.canvases=[]
             self.figures=[]
         for maskindex,set in enumerate(graphdata):
             if len(self.canvases)<=maskindex:
                 self.figures.append(plt.figure( ))
                 canvas=FigureCanvas(self.figures[maskindex])
                 canvas.setParent(self)
                 self.canvases.append(canvas)
                 self.layout.addWidget(self.canvases[maskindex])
             figure=self.figures[maskindex]
             figure.clf()
             figure.set_frameon(False)
            
             ax=figure.add_subplot(111)
             ax.set_yscale('symlog')
             ax.set_xlabel(set["columnLabels"][0],fontsize=16)
             ax.set_ylabel(set["columnLabels"][1],fontsize=16)
             ax.set_title( set["kind"]+" "+data["data"]['filename'])
             ax.patch.set_alpha(0)
            
             x=np.array(set["array"][0])[:]
             y=np.array(set["array"][1])[:]
             e=np.array(set["array"][2])[:]
             ppl.plot(ax,x,y,lw=1.0)
             ppl.fill_between(ax,x,y-e,y+e)
             plt.subplots_adjust(bottom=0.2)
             self.canvases[maskindex].draw()
예제 #15
0
def PlotFDistributionDistributionFunction(dfn, dfd):
    if dfn>0 and dfd>0:
        main_frame = QtGui.QWidget()
        dpi = 100
        fig = Figure((5.0, 4.0), dpi=dpi)
        canvas = FigureCanvas(fig)
        canvas.setParent(main_frame)

        axes = fig.add_subplot(111)
        mpl_toolbar = NavigationToolbar(canvas, main_frame)

        hbox = QtGui.QHBoxLayout()
        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(canvas)
        vbox.addWidget(mpl_toolbar)
        vbox.addLayout(hbox)
        main_frame.setLayout(vbox)

        alpha = 0.0005
        sequence = stats.f.isf(alpha, dfn, dfd)

        x = np.linspace(-sequence, sequence, 1000)
        rv = stats.f(dfn, dfd)
        y = rv.cdf(x)

        axes.plot(x,y)
        canvas.draw()

        return main_frame
    else: 
        return False, "Serbestlik derecesi 0'dan kucuk olamaz."
#---/F DISTRIBUTION
예제 #16
0
파일: plotWindow.py 프로젝트: lesire/metal
class PlotWindow(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.setWindowTitle('Online plot')
        self.create_main_frame()
        self.on_draw()

    def save_plot(self):
        pass

    def on_about(self):
        pass

    def on_pick(self, event):
        pass

    def on_draw(self):
        self.axes.clear()        
        self.axes.grid(True)
        self.canvas.draw()

    def create_main_frame(self):
        self.main_frame = QWidget()
        self.dpi = 100
        self.fig = Figure((20.0, 6.0), dpi=self.dpi)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.main_frame)
        self.axes = self.fig.add_subplot(111)
        self.canvas.mpl_connect('pick_event', self.on_pick)
        self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)     
        vbox = QVBoxLayout()
        vbox.addWidget(self.canvas)
        vbox.addWidget(self.mpl_toolbar)
        self.main_frame.setLayout(vbox)
        self.setCentralWidget(self.main_frame)
예제 #17
0
def PlotNormalDistributionDistributionFunction(mean, std):
    if std>0:
        main_frame = QtGui.QWidget()
        dpi = 100
        fig = Figure((5.0, 4.0), dpi=dpi)
        canvas = FigureCanvas(fig)
        canvas.setParent(main_frame)

        axes = fig.add_subplot(111)
        mpl_toolbar = NavigationToolbar(canvas, main_frame)

        hbox = QtGui.QHBoxLayout()
        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(canvas)
        vbox.addWidget(mpl_toolbar)
        vbox.addLayout(hbox)
        main_frame.setLayout(vbox)

        axes.clear()

        q = 0.0005 #lower or upper tail olasiligi
        sequance = stats.norm.isf(q)

        x = np.linspace(-sequance*3, sequance*3, 100)        #100 rasgele degisken
        gaussian = stats.norm(loc = mean, scale = std)  #mean ve std'ye gore normal da??l?m
        y = gaussian.cdf(x)

        axes.plot(x,y)
        canvas.draw()

        return main_frame

    else: 
        return False, "Standart sapma 0'dan kucuk olamaz."
예제 #18
0
class PlotDialog(QDialog,Ui_Widget):
    def __init__(self, qApp, parent=None):
        super(PlotDialog, self).__init__(parent)
        
        self.server=Pyro4.Proxy("PYRONAME:simple_server")
        
        self.__app = qApp
        self.setupUi(self)
        self.setupTimer()
        
        self.dpi = 72
        self.fig = Figure((9.1, 5.2), dpi=self.dpi)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)
        self.verticalLayout.insertWidget(0,self.canvas)
        self.canvas.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Expanding)
        self.axes = self.fig.add_subplot(111)
        
    def update(self):
        list=self.server.fetch_data()
        self.axes.cla()
        if len(list)<51:
            self.axes.plot(list)
        else:
            self.axes.plot(list[-50:])
        self.canvas.draw()
        #print list
        #for debugging
        
    def setupTimer(self):
        #Create a QT Timer that will timeout every half-a-second
        #The timeout is connected to the update function
        self.timer = QTimer()
        self.timer.timeout.connect(self.update)
        self.timer.start(500)
예제 #19
0
class Widget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        QVBoxLayout(self)

        self.figure = Figure()
        self.canvas = FigureCanvas(self.figure)
        self.canvas.setParent(self)

        codes, verts = zip(*pathdata)
        path = mpath.Path(verts, codes)
        patch = mpatches.PathPatch(path, facecolor="red", edgecolor="yellow", alpha=0.5)
        self.axes = self.figure.add_subplot(111)
        self.axes.add_patch(patch)

        x, y = zip(*path.vertices)
        self.axes.plot(x, y, "go-")

        self.axes.grid()
        self.axes.set_xlim(-3, 4)
        self.axes.set_ylim(-3, 4)

        self.axes.set_title("spline paths")

        self.layout().addWidget(self.canvas)

        self.canvas.draw()
예제 #20
0
class LsstCatalogPlot(QDialog):
    def __init__(self, main, ind, dep, color):
        QDialog.__init__(self, main)
        self.main = main
        self.setPalette(main.palette())
        self.ind = ind
        self.dep = dep
        self.color = color
        self.info = QLabel('Click on a point to highlight the corresponding'
                           ' record')
        self.figure = mpl.figure.Figure()
        self.canvas = FigureCanvasQTAgg(self.figure)
        self.canvas.setParent(self)
        self.canvas.setFocus()

        self.toolbar = NavigationToolbar2QT(self.canvas, self)

        self.ax = self.figure.add_subplot(111)
        self.scatterPlot = self.ax.scatter(self.ind, self.dep, c=self.color,
                                           picker=5, cmap=mpl.cm.YlGnBu_r)
        if self.color is not None:
            self.colorbar = self.figure.colorbar(self.scatterPlot)

        self.canvas.mpl_connect('pick_event', self.main.handleClick)

        vbox = QVBoxLayout()
        vbox.addWidget(self.info)
        vbox.addWidget(self.canvas)
        vbox.addWidget(self.toolbar)
        self.setLayout(vbox)

        self.show()
예제 #21
0
    def _refresh_mpl_widget(self):
        """ Create the mpl widget and update the underlying control.

        """
        # Delete the old widgets in the layout, it's just shenanigans
        # to try to reuse the old widgets when the figure changes.
        widget = self.widget
        layout = widget.layout()
        while layout.count():
            layout_item = layout.takeAt(0)
            layout_item.widget().deleteLater()

        # Create the new figure and toolbar widgets. It seems that key
        # events will not be processed without an mpl figure manager.
        # However, a figure manager will create a new toplevel window,
        # which is certainly not desired in this case. This appears to
        # be a limitation of matplotlib. The canvas is manually set to
        # visible, or QVBoxLayout will ignore it for size hinting.
        figure = self.declaration.figure
        if figure:
            canvas = FigureCanvasQTAgg(figure)
            canvas.setParent(widget)
            canvas.setFocusPolicy(Qt.ClickFocus)
            canvas.setVisible(True)
            toolbar = NavigationToolbar2QT(canvas, widget)
            toolbar.setVisible(self.declaration.toolbar_visible)
            layout.addWidget(toolbar)
            layout.addWidget(canvas)
예제 #22
0
파일: XRS_MainView.py 프로젝트: kif/Py2DeX
class MplAxes(object):
    def __init__(self, parent):
        self._parent = parent
        self._parent.resizeEvent = self.resize_graph
        self.create_axes()
        self.redraw_figure()

    def create_axes(self):
        self.figure = Figure(None, dpi=100)
        self.canvas = FigureCanvas(self.figure)
        self.canvas.setParent(self._parent)

        axes_layout = QtGui.QVBoxLayout(self._parent)
        axes_layout.setContentsMargins(0, 0, 0, 0)
        axes_layout.setSpacing(0)
        axes_layout.setMargin(0)
        axes_layout.addWidget(self.canvas)
        self.canvas.setSizePolicy(QtGui.QSizePolicy.Expanding,
                                  QtGui.QSizePolicy.Expanding)
        self.canvas.updateGeometry()
        self.axes = self.figure.add_subplot(111)

    def resize_graph(self, event):
        new_size = event.size()
        self.figure.set_size_inches([new_size.width() / 100.0, new_size.height() / 100.0])
        self.redraw_figure()

    def redraw_figure(self):
        self.figure.tight_layout(None, 0.8, None, None)
        self.canvas.draw()
예제 #23
0
    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 __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())
예제 #25
0
class GraphView(qg.QWidget):
    def __init__(self, name='Name', title='Title', graph_title='Graph Title', parent = None):
        super(GraphView, self).__init__(parent)

        self.name = name
        self.graph_title = graph_title

        self.dpi = 100
        self.fig = Figure((5.0, 3.0), dpi = self.dpi, facecolor = (1,1,1), edgecolor = (0,0,0))
        self.axes = self.fig.add_subplot(111)
        
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)
        self.toolbar = NavigationToolbar(self.canvas,self)
        self.layout = qg.QVBoxLayout()
        self.layout.addWidget(self.toolbar)
        self.layout.addWidget(self.canvas)
        self.layout.setStretchFactor(self.canvas, 1)
        self.setLayout(self.layout)
        self.canvas.show()

    def clear(self):
        self.axes.clear()
    def plot(self,*args,**kwargs):
        self.axes.plot(*args,**kwargs)
    def draw(self):
        self.canvas.draw()
    def add_patch(self,patch):
        self.axes.add_patch(patch)
    def scatter(self,*args,**kwargs):
        self.axes.scatter(*args,**kwargs)
    def text(self,*args,**kwargs):
        self.axes.text(*args,**kwargs)
예제 #26
0
class BarPlot():
    def __init__(self, parent=None):

        # Create the mpl Figure and FigCanvas objects.
        # 5x4 inches, 100 dots-per-inch
        self.dpi = 100
        self.fig = Figure((5,4), dpi=self.dpi)
        self.canvas = FigureCanvas(self.fig)    #pass a figure to the canvas
        self.canvas.setParent(parent)

        self.axes = self.fig.add_subplot(111)

        self.data = [1,2,3,1,2,3]


    def on_draw(self):
        """
        redraw the figure
        """
        self.axes.clear()
        self.axes.grid()

        x = range(len(self.data))
        self.axes.bar(left=x, height=self.data, width=0.3, align='center',
                      alpha=0.44, picker=5)
        self.axes.lefend(loc="best")
        self.axes.xticks(x+w/2, ["image", "judge", "match"])
        self.canvas.draw()
예제 #27
0
def PlotTDistributionDistributionFunction(df): 
    if df>0: 
        main_frame = QtGui.QWidget()
        dpi = 100
        fig = Figure((5.0, 4.0), dpi=dpi)
        canvas = FigureCanvas(fig)
        canvas.setParent(main_frame)

        axes = fig.add_subplot(111)
        mpl_toolbar = NavigationToolbar(canvas, main_frame)

        hbox = QtGui.QHBoxLayout()
        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(canvas)
        vbox.addWidget(mpl_toolbar)
        vbox.addLayout(hbox)
        main_frame.setLayout(vbox)

        axes.clear()

        alpha = 0.0005  #R'da o sekilde alinmis, burada da ayni olmas? icin bu deger verildi
        sequance = stats.t.isf(alpha, df)

        x = np.linspace(-sequance, sequance, 100)    #100 adet veri default verildi
        rv = stats.t(df)
        y = rv.cdf(x)

        axes.plot(x,y)
        canvas.draw()

        return main_frame

    else: 
        return False, "Serbestlik derecesi 0'dan kucuk olamaz."
예제 #28
0
    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
예제 #29
0
class DataFramePlotWidget(QtGui.QWidget):
    """QWidget to hold a matplotlib plot of the pd.DataFrame

    """
    def __init__(self, df=None):
        """Initiates the figure, canvas, toolbar and subplot necessary for
        plotting the dataframe

        Parameters
        ----------
        df: pd.DataFrame, optional
            The dataframe used to initialise the plot, defaults to None

        Returns
        -------
        DataFramePlotWidget
        """
        QtGui.QWidget.__init__(self)
        self.fig = Figure()
        self.canvas = FigureCanvas(self.fig)
        self.chart_type = 'line'
        self.canvas.setParent(self)
        self.toolbar = NavigationToolbar(self.canvas, self)

        self.vbox = QtGui.QVBoxLayout()
        self.vbox.addWidget(self.toolbar)
        self.vbox.addWidget(self.canvas)

        self.setLayout(self.vbox)
        self.subplot = self.fig.add_subplot(111)
        self.legend = self.subplot.legend([])
        self.set_dataframe(df)

    def set_dataframe(self, dataframe):
        """Set the pd.DataFrame for the widget and plot it on the subplot

        Parameters
        ----------
        dataframe: pd.DataFrame
            The dataframe to plot
        """
        self.dataframe = dataframe
        values = dataframe.cumsum(
            axis=1).values if self.chart_type == 'stack' else dataframe.values
        if not dataframe.empty:
            self.subplot.clear()
            if self.chart_type == 'line':
                self.subplot.plot_date(dataframe.index, values, '-')
            elif self.chart_type == 'stack':
                self.subplot.stackplot(dataframe.index, dataframe.values.transpose())
            else:
                raise ValueError('Chart type %s not recognised', self.chart_type)
            legend = self.subplot.legend(self.dataframe.columns)
            legend.set_visible(self.legend.get_visible())
            self.legend = legend

    def draw(self):
        """Draw the Canvas for the plot Figure"""
        self.canvas.draw()
예제 #30
0
    class __MatplotlibWidget(QtGui.QWidget):
        def __init__(self):
            QtGui.QWidget.__init__(self)

            self.figure = Figure((10.0, 6.0), dpi=100)
            self.canvas = FigureCanvas(self.figure)
            self.canvas.setParent(self)
            self.__toolbar = NavigationToolbar(self.canvas, self)
예제 #31
0
class readout_histogram(QtGui.QWidget):
    def __init__(self, reactor, cxn = None, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.reactor = reactor
        self.cxn = cxn
        self.thresholdVal = 10
        self.last_data = None
        self.last_hist = None
        self.last_fid = None
        self.current_data_set = 0
        self.subscribed = [False,False]
        self.create_layout()
        self.connect_labrad()

    def create_layout(self):
        layout = QtGui.QVBoxLayout()
        plot_layout = self.create_plot_layout()
        layout.addLayout(plot_layout)
        self.setLayout(layout)

    def create_plot_layout(self):
        layout = QtGui.QVBoxLayout()
        self.fig = Figure()
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)
        self.axes = self.fig.add_subplot(211)
        self.axes.set_xlim(left = 0, right = 100)
        self.axes.set_ylim(bottom = 0, top = 50)
        self.thresholdLine = self.axes.axvline(self.thresholdVal, linewidth=3.0, color = 'r', label = 'Threshold')
        self.axes.legend(loc = 'best')
        self.mpl_toolbar = NavigationToolbar(self.canvas, self)
        self.axes.set_title('State Readout', fontsize = 22)
        self.axes1 = self.fig.add_subplot(212)
        self.axes1.set_xlim(left = 0, right = 10)
        self.axes1.set_ylim(bottom = 0, top = 1.1)
        self.fig.tight_layout()
        layout.addWidget(self.mpl_toolbar)
        layout.addWidget(self.canvas)
        return layout

    def connect_layout(self):
        self.canvas.mpl_connect('button_press_event', self.on_key_press)

    @inlineCallbacks
    def on_key_press(self, event):
        if event.button == 2:
            xval = int(round(event.xdata))
            yield self.thresholdChange(xval)

    def on_new_data(self, readout):
        self.last_data = readout
        self.current_data_set  = self.current_data_set + 1
        self.update_histogram(readout)
        self.plot_fidelity()

    def update_histogram(self, data):
        #remove old histogram
        if self.last_hist is not None:
            self.last_hist.remove()
            #explicitly delete the reference although not necessary
            #el self.last_hist
        print numpy.max([data[:,1].max()-data[:,1].min(),1])
        y = numpy.histogram(data[:,1],int(numpy.max([data[:,1].max()-data[:,1].min(),1])))
        print y
        counts = y[0]
        bins = y[1][:-1]
        if bins[0] < 0:
        	bins = bins + .5
        print bins, counts
        self.last_hist = self.axes.bar(bins, counts, width = 1)
        print 'plot'
        x_maximum = bins.max()
        x_min = bins.min()
        self.axes.set_xlim(left = int(x_min - 2))
        self.axes.set_xlim(right = int(x_maximum+2))
        self.axes.set_ylim(bottom = 0)
        y_maximum = counts.max()
        self.axes.set_ylim(top = y_maximum+1)
        self.canvas.draw()


    def plot_fidelity(self):
    	# check xaxis
        x_max = self.axes1.get_xlim()[1]
        if self.current_data_set == x_max-2:
            self.axes1.set_xlim(right = x_max+1)
        bright = numpy.where(self.last_data[:,1] >= self.thresholdVal)
        fid = float(len(bright[0]))/len(self.last_data[:,1])
        self.last_fid  = self.axes1.plot(self.current_data_set,fid,'o')
        self.canvas.draw()

    def update_fidelity(self):
    	if self.last_fid is not None:
    		self.axes1.lines[self.current_data_set - 1].remove()

        if self.last_data is not None:
            bright = numpy.where(self.last_data[:,1] >= self.thresholdVal)
            fid = float(len(bright[0]))/len(self.last_data[:,1])
            self.last_fid  = self.axes1.plot(self.current_data_set,fid,'o')
            self.canvas.draw()


    @inlineCallbacks
    def thresholdChange(self, threshold):
        #update canvas
        self.update_canvas_line(threshold)
        self.thresholdVal = threshold
        self.update_fidelity()
        try:
            server = yield self.cxn.get_server('ParameterVault')
            yield server.set_parameter(config_hist.readout_threshold_dir[0], config_hist.readout_threshold_dir[1], threshold, context = self.context)
        except Exception, e:
            print e
            yield None
예제 #32
0
class AppForm(QMainWindow):
    def __init__(self, fileIn, parent=None):
        QMainWindow.__init__(self, parent)

        self.setWindowTitle('PyProf')
        self.currentFile = fileIn

        self.whichShowing = 0
        self.posMouse = [0, 0]

        self.createMainFrame()

    def readParameters(self, rootFile):

        # Read inverted parameters
        ff = nf(rootFile + '.parameters', 'r')
        pars = ff.variables['map'][:]
        ff.close()

        # Read errors
        ff = nf(rootFile + '.errors', 'r')
        errors = ff.variables['map'][:]
        ff.close()

        return pars, errors

    def readProfiles(self, rootFile):

        # Read inverted profiles
        ff = nf(rootFile + '.inversion', 'r')
        synthProf = ff.variables['map'][:]
        ff.close()

        return synthProf

    def readObservations(self, rootFile):

        # Read inverted profiles
        ff = nf(rootFile + '.nc', 'r')
        sizeMask = ff.variables['mask'].shape
        sizeMap = ff.variables['map'].shape
        obsProf = ff.variables['map'][:].reshape(
            (sizeMask[0], sizeMask[1], sizeMap[-2], sizeMap[-1]))
        ff.close()

        return obsProf

    def readData(self):

        # Parameters
        self.obs = self.readObservations(self.currentFile)
        obsShape = self.obs.shape

        self.pars, self.errors = self.readParameters(self.currentFile)
        parsShape = self.pars.shape
        self.pars = self.pars.reshape(
            (obsShape[0], obsShape[1], parsShape[-1]))
        self.errors = self.errors.reshape(
            (obsShape[0], obsShape[1], parsShape[-1]))

        self.syn = self.readProfiles(self.currentFile)
        synShape = self.syn.shape
        self.syn = self.syn.reshape(
            (obsShape[0], obsShape[1], synShape[-2], synShape[-1]))

        self.nx, self.ny, self.nLambda, _ = self.syn.shape

        self.maps = [None] * 4
        self.maps = [None] * 4
        for i in range(4):
            self.maps[i] = np.sum(self.obs[:, :, :, 0], axis=(2))

    def updateProfiles(self):
        # Blit animation. We only redraw the lines
        loop = 0
        for j in range(6):
            for i in range(4):
                self.rightCanvas.restore_region(self.background[loop])
                self.obs[loop].set_ydata(
                    self.profiles[self.rangeFrom[j]:self.rangeTo[j], i])
                self.axes[loop].draw_artist(self.obs[loop])
                self.rightCanvas.blit(self.axes[loop].bbox)
                loop += 1

    def onMouseMove(self, event):
        print(event.xdata, event.ydata)
        if (event.xdata != None and event.ydata != None):
            newPos = np.asarray([event.xdata, event.ydata])
            newPos = newPos.astype(int)

            if (newPos[0] != self.posMouse[0]
                    or newPos[1] != self.posMouse[1]):
                self.posMouse = newPos
                self.profiles = self.getProfiles(newPos[0], newPos[1])
                self.updateProfiles()

    def onScrollMove(self, event):
        pass
        #if (event.button == 'up'):
        #self.newTime += 1
        #if (event.button == 'down'):
        #self.newTime -= 1

        #self.newTime = self.newTime % 35

        #self.profiles = self.getProfiles(self.posMouse[0], self.posMouse[1])
        #self.updateProfiles()

    def getProfiles(self, x, y):
        return self.obs[x, y, :, 0:5], self.syn[x, y, :, :]

    def getMaps(self, x):
        return self.obs[:, :, 0, 0]


#--------------------------------------

    def create_main_frame(self):

        self.mainFrame = QWidget()

        gridLayout = QGridLayout()

        self.dpi = 80
        self.xpos = 0
        self.ypos = 0

        self.titles = [r'I', r'Q', r'U', r'V']

        self.readData()

        self.resize(1500, 900)

        # Left window
        self.leftPlot = QWidget()
        self.leftFig = Figure((2 * self.ny / self.dpi, 4 * self.nx / self.dpi),
                              dpi=self.dpi)
        self.leftCanvas = FigureCanvas(self.leftFig)
        self.leftCanvas.setParent(self.leftPlot)

        self.leftAxes = [None] * 4
        self.drawnMap = [None] * 4
        for i in range(4):
            self.leftAxes[i] = self.leftFig.add_subplot(2, 2, i + 1)
            self.drawnMap[i] = self.leftAxes[i].imshow(self.maps[i],
                                                       aspect='equal')
            # self.leftAxes[i].set_axis_off()
        self.leftCanvas.mpl_connect('motion_notify_event', self.onMouseMove)
        self.leftCanvas.mpl_connect('scroll_event', self.onScrollMove)
        gridLayout.addWidget(self.leftPlot, 0, 0)
        gridLayout.setSpacing(10)

        # Central window
        # self.centralPlot = QWidget()
        # self.centralFig = Figure((10,8), dpi=self.dpi)
        # self.centralCanvas = FigureCanvas(self.centralFig)
        # self.centralCanvas.setParent(self.centralPlot)

        # self.slitMaps = self.getMaps(0)

        # self.centralAxes = [None]*4
        # self.drawnSlitMap = [None]*4
        # # for i in range(4):
        # # 	self.centralAxes[i] = self.centralFig.add_subplot(4,1,i+1)
        # # 	self.drawnSlitMap[i] = self.centralAxes[i].imshow(self.slitMaps[i,:,:])
        # #self.centralCanvas.draw()

        # gridLayout.addWidget(self.centralPlot, 0, 1)

        # Right window
        self.rightPlot = QWidget()
        self.rightFig = Figure((8, 18), dpi=self.dpi)
        self.rightCanvas = FigureCanvas(self.rightFig)
        self.rightCanvas.setParent(self.rightPlot)

        self.stokesObs, self.stokesSyn = self.getProfiles(0, 0)

        # Draw the axes and the first profiles
        nCols = 2
        nRows = 2
        self.axes = [None] * 4
        self.obsLine = [None] * 4
        self.synLine = [None] * 4
        loop = 0
        for j in range(2):
            for i in range(2):
                self.axes[loop] = self.rightFig.add_subplot(
                    nCols, nRows, loop + 1)
                self.obsLine[loop], = self.axes[loop].plot(
                    self.stokesObs[:, loop])
                self.synLine[loop], = self.axes[loop].plot(
                    self.stokesSyn[:, loop])
                loop += 1
        gridLayout.addWidget(self.rightPlot, 0, 2)

        ## Tight layout and redraw
        # self.rightFig.tight_layout()

        self.rightCanvas.draw()

        ## We are using blit animation to do it fast, so we need to recover the axes modified by tight_layout
        self.newAxes = self.rightFig.get_axes()

        ## Save the backgrounds
        # loop = 0
        # for j in range(6):
        # 	for i in range(4):
        # 		self.axes[loop] = self.newAxes[loop]
        # 		self.background[loop] = self.canvasRight.copy_from_bbox(self.axes[loop].bbox)
        # 		loop += 1

        gridLayout.addWidget(self.rightPlot)

        # fullLayout.addLayout(gridLayout)

        self.mainFrame.setLayout(gridLayout)
        self.setCentralWidget(self.mainFrame)
예제 #33
0
class AppForm(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.setWindowTitle('Mandelbrot Set')

        self.create_menu()
        self.create_main_frame()
        self.create_status_bar()

        #
        # Initialize textbox values
        #
        self.textbox_re_min.setText(str(re_min))
        self.textbox_re_max.setText(str(re_max))
        self.textbox_im_min.setText(str(im_min))
        self.textbox_im_max.setText(str(im_max))
        self.textbox_max_iter.setText(str(max_iter))

        #
        # Render mandelbrot set
        #
        self.setMinimumWidth(620)
        self.resize(620, 460)
        self.draw()

    def save_plot(self):
        file_choices = "PNG (*.png)|*.png"

        path = unicode(QFileDialog.getSaveFileName(self,
                        'Save file', '',
                        file_choices))
        if path:
            self.canvas.print_figure(path)
            self.statusBar().showMessage('Saved to %s' % path, 2000)

    #
    # Display infos about application
    #
    def on_about(self):
        msg = """Mandelbrot Set Generator:

    ### Features ###
     * Click left mouse button and drag to zoom
     * Enter custom values for ReMin, ReMin, ImMin and ImMax
     * Show or hide the grid
     * Save the plot to a file using the File menu
     * De-/activate continuous color spectrum
     * De-/activate normalized values

     ### Used Libraries ###
     * PyQt4
     * Matplotlib

     ### Author ###
     Made by Philip Wiese
     [email protected]
     16. Oktober 2016
        """
        QMessageBox.about(self, "About the demo", msg.strip())
    #
    # Show mouse position in statusbar
    #
    def statusbar_coord(self, event):
        # Show coordinates time in statusbar
        if event.inaxes is not None:
            text = "Re(c): % .5f, Im(c) % .5f" % (event.xdata, event.ydata)
            self.coord_text.setText(text)

    #
    # Calculates mandelbrot set and updates mpl plot
    #
    def draw(self):
        """ Redraws the figure
        """
        # Grap values from textboxes
        re_min = float(unicode(self.textbox_re_min.text()))
        re_max = float(unicode(self.textbox_re_max.text()))
        im_min = float(unicode(self.textbox_im_min.text()))
        im_max = float(unicode(self.textbox_im_max.text()))
        max_iter = int(unicode(self.textbox_max_iter.text()))

        # Grap values from checkboxes
        self.axes.grid(self.grid_cb.isChecked())
        cont = self.cont_cb.isChecked()
        norm = self.norm_cb.isChecked()

        # Calculate mandelbrot set
        self.fractal = mandelbrot(re_min, re_max, im_min, im_max, max_betr, max_iter, res, cont)

        # Normalize Values
        if norm:
            self.fractal.data[self.fractal.data > 0] -= self.fractal.min

        # Show calculation time in statusbar
        self.status_text.setText("Calculation Time: %0.3fs" % self.fractal.calc_time)

        # Load data to mpl plot
        self.axes.imshow(self.fractal.data.T, origin="lower left", cmap='jet', extent=[re_min, re_max, im_min, im_max])
        self.axes.set_xlabel("Re(c)", labelpad=20)
        self.axes.set_ylabel("Im(c)")

        # Show/hide grid
        if self.grid_cb.isChecked():
            self.axes.grid(linewidth=1, linestyle='-')
        # Align layout and redraw plot
        self.canvas.draw_idle()
        #self.fig.tight_layout()

    def line_select_callback(self, eclick, erelease):
        # eclick and erelease are the press and release events
        x1, y1 = eclick.xdata, eclick.ydata
        x2, y2 = erelease.xdata, erelease.ydata

        # Zoom with left mouse click
        if eclick.button == 1:
            # Check for valid coordinates
            if (x1 != None and y2 != None and x1 != None and y1 != None):
                self.xmin = min(x1, x2)
                self.xmax = max(x1, x2)
                self.ymin = min(y1, y2)
                self.ymax = max(y1, y2)
                # Save array with relative values
                self.xy = [self.xmax - self.xmin, self.ymax - self.ymin]

                # Calculate precision in decimal digits
                for v in self.xy:
                    if v <= 1:
                        self.decimals = round(log10(1 / v)) + 2

                # Round values with calculated precision
                re_min = round(self.xmin, int(self.decimals))
                re_max = round(self.xmax, int(self.decimals))
                im_min = round(self.ymin, int(self.decimals))
                im_max = round(self.ymax, int(self.decimals))

                # Update textbos values
                self.textbox_re_min.setText(str(re_min))
                self.textbox_re_max.setText(str(re_max))
                self.textbox_im_min.setText(str(im_min))
                self.textbox_im_max.setText(str(im_max))

                # Calculate and draw new mandelbrot set
                self.draw()

        # Zoom with right mouse click
        if eclick.button == 3:
            # Grap values from textboxes
            re_min = float(unicode(self.textbox_re_min.text()))
            re_max = float(unicode(self.textbox_re_max.text()))
            im_min = float(unicode(self.textbox_im_min.text()))
            im_max = float(unicode(self.textbox_im_max.text()))

            self.xy = [ re_max - re_min, im_max - im_min]

            # Calculate new values
            re_min = re_min - self.xy[0] / 2
            re_max = re_max + self.xy[0] / 2
            im_min = im_min - self.xy[1] / 2
            im_max = im_max + self.xy[1] / 2

            # Calculate precision in decimal digits
            for v in self.xy:
                if v <= 1:
                    self.decimals = round(log10(1 / v)) + 2

            # Round values with calculated precision
            re_min = round(re_min, int(self.decimals))
            re_max = round(re_max, int(self.decimals))
            im_min = round(im_min, int(self.decimals))
            im_max = round(im_max, int(self.decimals))

            # Update textbos values
            self.textbox_re_min.setText(str(re_min))
            self.textbox_re_max.setText(str(re_max))
            self.textbox_im_min.setText(str(im_min))
            self.textbox_im_max.setText(str(im_max))

            # Calculate and draw new mandelbrot set
            self.draw()

    def create_main_frame(self):
        self.main_frame = QWidget()
        self.main_frame.setMinimumHeight(280)


        # Create the Figure and FigCanvas objects
        self.fig = Figure((5,10), tight_layout=True)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.main_frame)


        # Add sublot to figure do formatting
        self.axes = self.fig.add_subplot(111)
        self.axes.ticklabel_format(style='sci', scilimits=(0,0), axis='both')

        # Create zoom event handler
        self.RS = RectangleSelector(self.axes, self.line_select_callback,
                           drawtype='box', useblit=True,
                           button=[1, 3],  # don't use middle button
                           spancoords='data')

        # Other GUI controls
        self.textbox_re_min = QLineEdit()
        self.textbox_re_min_text = QLabel("ReMin: ")
        self.textbox_re_min.setMinimumWidth(55)

        self.textbox_re_max = QLineEdit()
        self.textbox_re_max_text = QLabel("ReMax: ")
        self.textbox_re_max.setMinimumWidth(55)

        self.textbox_im_min = QLineEdit()
        self.textbox_im_min_text = QLabel("ImMin: ")
        self.textbox_im_min.setMinimumWidth(55)

        self.textbox_im_max = QLineEdit()
        self.textbox_im_max_text = QLabel("ImMax: ")
        self.textbox_im_max.setMinimumWidth(55)

        self.textbox_max_iter = QLineEdit()
        self.textbox_max_iter_text = QLabel("Max Iterration: ")
        self.textbox_max_iter.setMinimumWidth(55)

        self.grid_cb = QCheckBox("Show Grid")
        self.grid_cb.setChecked(False)

        self.cont_cb = QCheckBox("Continuous Coloring")
        self.cont_cb.setChecked(True)

        self.norm_cb = QCheckBox("Normalize Values")
        self.norm_cb.setChecked(True)

        self.draw_button = QPushButton("Calculate && Draw")
        self.connect(self.draw_button, SIGNAL('clicked()'), self.draw)

        #
        # Layout with box sizers
        #
        hbox = QHBoxLayout()
        grid = QGridLayout()

        hbox.addWidget(self.canvas, 3)
        self.canvas.setCursor(Qt.CrossCursor)
        hbox.addLayout(grid,1)
        grid.setRowStretch(1,1)


        grid.addWidget(self.textbox_re_min , 0,1)
        grid.addWidget(self.textbox_re_min_text , 0,0)
        grid.addWidget(self.textbox_re_max  , 1,1)
        grid.addWidget(self.textbox_re_max_text  , 1,0)
        grid.addWidget(self.textbox_im_min , 2,1)
        grid.addWidget(self.textbox_im_min_text , 2,0)
        grid.addWidget(self.textbox_im_max  , 3,1)
        grid.addWidget(self.textbox_im_max_text , 3,0)
        grid.addWidget(self.textbox_max_iter , 5,1)
        grid.addWidget(self.textbox_max_iter_text , 5,0)
        grid.addWidget(self.grid_cb , 6,0,1,2)
        grid.addWidget(self.cont_cb , 7,0,1,2)
        grid.addWidget(self.norm_cb , 8,0,1,2)

        grid.addWidget(self.draw_button , 9,0,1,2)
        grid.addWidget(QLabel(""), 10,0,2,2)


        self.main_frame.setLayout(hbox)
        self.setCentralWidget(self.main_frame)

    def create_status_bar(self):
        self.status_text = QLabel("Ready")
        self.coord_text = QLabel("Re(c): % 7f, Im(c) % 7f" % (0, 0))

        self.canvas.mpl_connect("motion_notify_event", self.statusbar_coord)

        self.statusBar().addWidget(self.status_text, 1)
        self.statusBar().addWidget(self.coord_text, -1)

    def create_menu(self):
        # -- Menu Structure --
        # File
        #     Save plot (Ctrl+S)
        #     Quit (Ctrl+Q)
        # Help
        #    About (F1)
        #
        self.file_menu = self.menuBar().addMenu("&File")

        load_file_action = self.create_action("&Save plot",
            shortcut="Ctrl+S", slot=self.save_plot,
            tip="Save the plot")
        quit_action = self.create_action("&Quit", slot=self.close,
            shortcut="Ctrl+Q", tip="Close the application")

        self.add_actions(self.file_menu,
            (load_file_action, None, quit_action))

        self.help_menu = self.menuBar().addMenu("&Help")
        about_action = self.create_action("&About",
            shortcut='F1', slot=self.on_about,
            tip='About the application')

        self.add_actions(self.help_menu, (about_action,))

    def add_actions(self, target, actions):
        for action in actions:
            if action is None:
                target.addSeparator()
            else:
                target.addAction(action)

    def create_action(self, text, slot=None, shortcut=None,
                        icon=None, tip=None, checkable=False,
                        signal="triggered()"):
        action = QAction(text, self)
        if icon is not None:
            action.setIcon(QIcon(":/%s.png" % icon))
        if shortcut is not None:
            action.setShortcut(shortcut)
        if tip is not None:
            action.setToolTip(tip)
            action.setStatusTip(tip)
        if slot is not None:
            self.connect(action, SIGNAL(signal), slot)
        if checkable:
            action.setCheckable(True)
        return action
예제 #34
0
class AppForm(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)

        # Read data from source or leakage fraction file
        self.get_file_data()
        self.main_frame = QWidget()
        self.setCentralWidget(self.main_frame)

        # Create the Figure, Canvas, and Axes
        self.dpi = 100
        self.fig = Figure((5.0, 15.0), dpi=self.dpi)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.main_frame)
        self.axes = self.fig.add_subplot(111)

        # Create the navigation toolbar, tied to the canvas
        self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)

        # Grid layout at bottom
        self.grid = QGridLayout()

        # Overall layout
        self.vbox = QVBoxLayout()
        self.vbox.addWidget(self.canvas)
        self.vbox.addWidget(self.mpl_toolbar)
        self.vbox.addLayout(self.grid)
        self.main_frame.setLayout(self.vbox)

        # Tally selections
        label_tally = QLabel("Tally:")
        self.tally = QComboBox()
        self.tally.addItems([(str(i + 1)) for i in range(self.n_tallies)])
        self.connect(self.tally, SIGNAL('activated(int)'), self._update)
        self.connect(self.tally, SIGNAL('activated(int)'), self.populate_boxes)
        self.connect(self.tally, SIGNAL('activated(int)'), self.on_draw)

        # Planar basis
        label_basis = QLabel("Basis:")
        self.basis = QComboBox()
        self.basis.addItems(['xy', 'yz', 'xz'])

        # Update window when 'Basis' selection is changed
        self.connect(self.basis, SIGNAL('activated(int)'), self._update)
        self.connect(self.basis, SIGNAL('activated(int)'), self.populate_boxes)
        self.connect(self.basis, SIGNAL('activated(int)'), self.on_draw)

        # Axial level within selected basis
        label_axial_level = QLabel("Axial Level:")
        self.axial_level = QComboBox()
        self.connect(self.axial_level, SIGNAL('activated(int)'), self.on_draw)

        # Add Option to plot mean or uncertainty
        label_mean = QLabel("Mean or Uncertainty:")
        self.mean = QComboBox()
        self.mean.addItems(
            ['Mean', 'Absolute Uncertainty', 'Relative Uncertainty'])

        # Update window when mean selection is changed
        self.connect(self.mean, SIGNAL('activated(int)'), self.on_draw)

        self.label_filters = QLabel("Filter options:")

        # Labels for all possible filters
        self.labels = {
            'cell': 'Cell: ',
            'cellborn': 'Cell born: ',
            'surface': 'Surface: ',
            'material': 'Material',
            'universe': 'Universe: ',
            'energyin': 'Energy in: ',
            'energyout': 'Energy out: '
        }

        # Empty reusable labels
        self.qlabels = {}
        for j in range(8):
            self.nextLabel = QLabel
            self.qlabels[j] = self.nextLabel

        # Reusable comboboxes labelled with filter names
        self.boxes = {}
        for key in self.labels.keys():
            self.nextBox = QComboBox()
            self.connect(self.nextBox, SIGNAL('activated(int)'), self.on_draw)
            self.boxes[key] = self.nextBox

        # Combobox to select among scores
        self.score_label = QLabel("Score:")
        self.scoreBox = QComboBox()
        for item in self.tally_scores[0]:
            self.scoreBox.addItems(str(item))
        self.connect(self.scoreBox, SIGNAL('activated(int)'), self.on_draw)

        # Fill layout
        self.grid.addWidget(label_tally, 0, 0)
        self.grid.addWidget(self.tally, 0, 1)
        self.grid.addWidget(label_basis, 1, 0)
        self.grid.addWidget(self.basis, 1, 1)
        self.grid.addWidget(label_axial_level, 2, 0)
        self.grid.addWidget(self.axial_level, 2, 1)
        self.grid.addWidget(label_mean, 3, 0)
        self.grid.addWidget(self.mean, 3, 1)
        self.grid.addWidget(self.label_filters, 4, 0)

        self._update()
        self.populate_boxes()
        self.on_draw()

    def get_file_data(self):
        # Get data file name from "open file" browser
        filename = QFileDialog.getOpenFileName(self, 'Select statepoint file',
                                               '.')

        # Create StatePoint object and read in data
        self.datafile = StatePoint(str(filename))
        self.datafile.read_results()
        self.datafile.generate_stdev()

        self.setWindowTitle('Core Map Tool : ' + str(self.datafile.path))

        # Set maximum colorbar value by maximum tally data value
        self.maxvalue = self.datafile.tallies[0].results.max()

        self.labelList = []

        # Read mesh dimensions
        #        for mesh in self.datafile.meshes:
        #            self.nx, self.ny, self.nz = mesh.dimension

        # Read filter types from statepoint file
        self.n_tallies = len(self.datafile.tallies)
        self.tally_list = []
        for tally in self.datafile.tallies:
            self.filter_types = []
            for f in tally.filters:
                self.filter_types.append(f)
            self.tally_list.append(self.filter_types)

        # Read score types from statepoint file
        self.tally_scores = []
        for tally in self.datafile.tallies:
            self.score_types = []
            for s in tally.scores:
                self.score_types.append(s)
            self.tally_scores.append(self.score_types)
#        print 'self.tally_scores = ', self.tally_scores

    def on_draw(self):
        """ Redraws the figure
        """

        #        print 'Calling on_draw...'
        # Get selected basis, axial_level and stage
        basis = self.basis.currentIndex() + 1
        axial_level = self.axial_level.currentIndex() + 1
        is_mean = self.mean.currentIndex()

        # Create spec_list
        spec_list = []
        for tally in self.datafile.tallies[
                self.tally.currentIndex()].filters.values():
            if tally.type == 'mesh':
                continue
            index = self.boxes[tally.type].currentIndex()
            spec_list.append((tally.type, index))

        # Take is_mean and convert it to an index of the score
        score_loc = is_mean
        if score_loc > 1:
            score_loc = 1

        if self.basis.currentText() == 'xy':
            matrix = np.zeros((self.nx, self.ny))
            for i in range(self.nx):
                for j in range(self.ny):
                    matrix[i, j] = self.datafile.get_value(
                        self.tally.currentIndex(),
                        spec_list + [('mesh', (i, j, axial_level))],
                        self.scoreBox.currentIndex())[score_loc]
                    # Calculate relative uncertainty from absolute, if
                    # requested
                    if is_mean == 2:
                        # Take care to handle zero means when normalizing
                        mean_val = self.datafile.get_value(
                            self.tally.currentIndex(),
                            spec_list + [('mesh', (i, j, axial_level))],
                            self.scoreBox.currentIndex())[0]
                        if mean_val > 0.0:
                            matrix[i, j] = matrix[i, j] / mean_val
                        else:
                            matrix[i, j] = 0.0

        elif self.basis.currentText() == 'yz':
            matrix = np.zeros((self.ny, self.nz))
            for i in range(self.ny):
                for j in range(self.nz):
                    matrix[i, j] = self.datafile.get_value(
                        self.tally.currentIndex(),
                        spec_list + [('mesh', (axial_level, i, j))],
                        self.scoreBox.currentIndex())[score_loc]
                    # Calculate relative uncertainty from absolute, if
                    # requested
                    if is_mean == 2:
                        # Take care to handle zero means when normalizing
                        mean_val = self.datafile.get_value(
                            self.tally.currentIndex(),
                            spec_list + [('mesh', (axial_level, i, j))],
                            self.scoreBox.currentIndex())[0]
                        if mean_val > 0.0:
                            matrix[i, j] = matrix[i, j] / mean_val
                        else:
                            matrix[i, j] = 0.0

        else:
            matrix = np.zeros((self.nx, self.nz))
            for i in range(self.nx):
                for j in range(self.nz):
                    matrix[i, j] = self.datafile.get_value(
                        self.tally.currentIndex(),
                        spec_list + [('mesh', (i, axial_level, j))],
                        self.scoreBox.currentIndex())[score_loc]
                    # Calculate relative uncertainty from absolute, if
                    # requested
                    if is_mean == 2:
                        # Take care to handle zero means when normalizing
                        mean_val = self.datafile.get_value(
                            self.tally.currentIndex(),
                            spec_list + [('mesh', (i, axial_level, j))],
                            self.scoreBox.currentIndex())[0]
                        if mean_val > 0.0:
                            matrix[i, j] = matrix[i, j] / mean_val
                        else:
                            matrix[i, j] = 0.0

#        print spec_list

# Clear the figure
        self.fig.clear()

        # Make figure, set up color bar
        self.axes = self.fig.add_subplot(111)
        cax = self.axes.imshow(matrix,
                               vmin=0.0,
                               vmax=matrix.max(),
                               interpolation="nearest")
        self.fig.colorbar(cax)

        self.axes.set_xticks([])
        self.axes.set_yticks([])
        self.axes.set_aspect('equal')

        # Draw canvas
        self.canvas.draw()

    def _update(self):
        '''Updates widget to display new relevant comboboxes and figure data
        '''
        #        print 'Calling _update...'

        self.mesh = self.datafile.meshes[self.datafile.tallies[
            self.tally.currentIndex()].filters['mesh'].bins[0] - 1]

        self.nx, self.ny, self.nz = self.mesh.dimension

        # Clear axial level combobox
        self.axial_level.clear()

        # Repopulate axial level combobox based on current basis selection
        if (self.basis.currentText() == 'xy'):
            self.axial_level.addItems([str(i + 1) for i in range(self.nz)])
        elif (self.basis.currentText() == 'yz'):
            self.axial_level.addItems([str(i + 1) for i in range(self.nx)])
        else:
            self.axial_level.addItems([str(i + 1) for i in range(self.ny)])

        # Determine maximum value from current tally data set
        self.maxvalue = self.datafile.tallies[
            self.tally.currentIndex()].results.max()
        #        print self.maxvalue

        # Clear and hide old filter labels
        for item in self.labelList:
            item.clear()

        # Clear and hide old filter boxes
        for j in self.labels:
            self.boxes[j].clear()
            self.boxes[j].setParent(None)

        self.update()

    def populate_boxes(self):
        #        print 'Calling populate_boxes...'

        n = 5
        labels = {
            'cell': 'Cell : ',
            'cellborn': 'Cell born: ',
            'surface': 'Surface: ',
            'material': 'Material: ',
            'universe': 'Universe: '
        }

        # For each filter in newly-selected tally, name a label and fill the
        # relevant combobox with options
        for element in self.tally_list[self.tally.currentIndex()]:
            nextFilter = self.datafile.tallies[
                self.tally.currentIndex()].filters[element]
            if element == 'mesh':
                continue

            label = QLabel(self.labels[element])
            self.labelList.append(label)
            combobox = self.boxes[element]
            self.grid.addWidget(label, n, 0)
            self.grid.addWidget(combobox, n, 1)
            n += 1

            #            print element
            if element in [
                    'cell', 'cellborn', 'surface', 'material', 'universe'
            ]:
                combobox.addItems([str(i) for i in nextFilter.bins])


#                for i in nextFilter.bins:
#                    print i

            elif element == 'energyin' or element == 'energyout':
                for i in range(nextFilter.length):
                    text = (str(nextFilter.bins[i]) + ' to ' +
                            str(nextFilter.bins[i + 1]))
                    combobox.addItem(text)

        self.scoreBox.clear()
        for item in self.tally_scores[self.tally.currentIndex()]:
            self.scoreBox.addItem(str(item))
        self.grid.addWidget(self.score_label, n, 0)
        self.grid.addWidget(self.scoreBox, n, 1)
예제 #35
0
class AppForm(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.setWindowTitle('UChSonicAnemometer Live View')

        self.autoscale = True

        self.reader = adc_reader.ADCReader()

        self.create_menu()
        self.create_main_frame()
        self.create_status_bar()

        self.on_draw()

    def save_plot(self):
        file_choices = "PNG (*.png)|*.png"

        path = unicode(
            QFileDialog.getSaveFileName(self, 'Save file', '', file_choices))
        if path:
            self.canvas.print_figure(path, dpi=self.dpi)
            self.statusBar().showMessage('Saved to %s' % path, 2000)

    def on_draw(self):
        """ Redraws the figure
        """
        # clear the axes and redraw the plot anew
        #

        x_limits = self.axes.get_xlim()
        y_limits = self.axes.get_ylim()
        self.axes.clear()
        signal = self.reader.get_frame()
        responses = utilities.split_signal(signal)
        self.axes.plot(responses["NORTH"].get_timestamp_array(),
                       responses["NORTH"].values, '-')
        if not self.autoscale:
            self.axes.set_xlim(x_limits)
            self.axes.set_ylim(y_limits)
        self.canvas.draw()
        self.autoscale = False

    def self_on_capture(self):
        """ Callback for capture button. """
        if self.recording_check.isChecked():
            try:
                os.mkdir("records")
            except OSError:
                pass
            for i in range(self.recording_repetitions.value()):
                filename = "records/%s_%04d.bin" % (self.recording_name.text(),
                                                    i)
                self.reader.dump_frame_to_file(filename)
        self.on_draw()

    def create_main_frame(self):
        self.main_frame = QWidget()

        # Create the mpl Figure and FigCanvas objects.
        # 5x4 inches, 100 dots-per-inch
        #
        self.dpi = 100
        self.fig = Figure(dpi=self.dpi)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.main_frame)

        # Since we have only one plot, we can use add_axes
        # instead of add_subplot, but then the subplot
        # configuration tool in the navigation toolbar wouldn't
        # work.
        #
        self.axes = self.fig.add_subplot(111)

        # Create the navigation toolbar, tied to the canvas
        #
        self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)

        self.draw_button = QPushButton("&Capture")
        self.connect(self.draw_button, SIGNAL('clicked()'),
                     self.self_on_capture)

        self.recording_check = QCheckBox("Recording")
        self.recording_name = QLineEdit()
        self.recording_repetitions = QSpinBox()
        self.recording_repetitions.setRange(1, 99)

        #
        # Layout with box sizers
        #
        hbox = QHBoxLayout()

        for w in [
                self.draw_button, self.recording_check,
                QLabel("Recording Name: "), self.recording_name,
                QLabel("Repetitions: "), self.recording_repetitions
        ]:
            hbox.addWidget(w)
            hbox.setAlignment(w, Qt.AlignVCenter)

        vbox = QVBoxLayout()
        vbox.addWidget(self.canvas)
        vbox.addWidget(self.mpl_toolbar)
        vbox.addLayout(hbox)

        self.main_frame.setLayout(vbox)
        self.setCentralWidget(self.main_frame)

    def create_status_bar(self):
        self.status_text = QLabel("This is a demo")
        self.statusBar().addWidget(self.status_text, 1)

    def create_menu(self):
        self.file_menu = self.menuBar().addMenu("&File")

        load_file_action = self.create_action("&Save plot",
                                              shortcut="Ctrl+S",
                                              slot=self.save_plot,
                                              tip="Save the plot")
        quit_action = self.create_action("&Quit",
                                         slot=self.close,
                                         shortcut="Ctrl+Q",
                                         tip="Close the application")

        self.add_actions(self.file_menu, (load_file_action, None, quit_action))

    def add_actions(self, target, actions):
        for action in actions:
            if action is None:
                target.addSeparator()
            else:
                target.addAction(action)

    def create_action(self,
                      text,
                      slot=None,
                      shortcut=None,
                      icon=None,
                      tip=None,
                      checkable=False,
                      signal="triggered()"):
        action = QAction(text, self)
        if icon is not None:
            action.setIcon(QIcon(":/%s.png" % icon))
        if shortcut is not None:
            action.setShortcut(shortcut)
        if tip is not None:
            action.setToolTip(tip)
            action.setStatusTip(tip)
        if slot is not None:
            self.connect(action, SIGNAL(signal), slot)
        if checkable:
            action.setCheckable(True)
        return action
예제 #36
0
class AppForm(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.setWindowTitle('Demo: PyQt with matplotlib')

        self.create_main_frame()

        self.on_draw()

    def on_pick(self, event):
        # The event received here is of the type
        # matplotlib.backend_bases.PickEvent
        #
        # It carries lots of information, of which we're using
        # only a small amount here.
        #
        box_points = event.artist.get_bbox().get_points()
        msg = "You've clicked on a bar with coords:\n %s" % box_points

        QMessageBox.information(self, "Click!", msg)

    def on_draw(self):
        """ Redraws the figure
        """

        self.data = [random.randint(1, 10) for i in range(10)]

        x = range(len(self.data))

        # clear the axes and redraw the plot anew
        #
        self.axes.clear()
        self.axes.grid(self.grid_cb.isChecked())

        self.axes.bar(left=x,
                      height=self.data,
                      width=self.slider.value() / 100.0,
                      align='center',
                      alpha=0.44,
                      picker=5)

        self.canvas.draw()

    def create_main_frame(self):
        self.main_frame = QWidget()

        # Create the mpl Figure and FigCanvas objects.
        # 5x4 inches, 100 dots-per-inch
        #
        self.dpi = 100
        self.fig = Figure((5.0, 4.0), dpi=self.dpi)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.main_frame)

        # Since we have only one plot, we can use add_axes
        # instead of add_subplot, but then the subplot
        # configuration tool in the navigation toolbar wouldn't
        # work.
        #
        self.axes = self.fig.add_subplot(111)

        # Bind the 'pick' event for clicking on one of the bars
        #
        self.canvas.mpl_connect('pick_event', self.on_pick)

        # Create the navigation toolbar, tied to the canvas
        #
        self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)

        # Other GUI controls
        #

        self.draw_button = QPushButton("&Draw")
        self.connect(self.draw_button, SIGNAL('clicked()'), self.on_draw)

        self.grid_cb = QCheckBox("Show &Grid")
        self.grid_cb.setChecked(False)
        self.connect(self.grid_cb, SIGNAL('stateChanged(int)'), self.on_draw)

        slider_label = QLabel('Slider value (%):')
        self.slider = QSlider(Qt.Horizontal)
        self.slider.setRange(1, 100)
        self.slider.setValue(20)
        self.slider.setTracking(True)
        self.slider.setTickPosition(QSlider.TicksBothSides)
        self.connect(self.slider, SIGNAL('valueChanged(int)'), self.on_draw)

        #
        # Layout with box sizers
        #
        hbox = QHBoxLayout()

        for w in [self.draw_button, self.grid_cb, slider_label, self.slider]:
            hbox.addWidget(w)
            hbox.setAlignment(w, Qt.AlignVCenter)

        vbox = QVBoxLayout()
        vbox.addWidget(self.canvas)
        vbox.addWidget(self.mpl_toolbar)
        vbox.addLayout(hbox)

        self.main_frame.setLayout(vbox)
        self.setCentralWidget(self.main_frame)
예제 #37
0
class Ui_Monitor(object):
    def setupUi(self, Monitor):
        Monitor.setObjectName(_fromUtf8("Monitor"))
        Monitor.resize(1060, 680)
        self.setrunning(Monitor)
        self.setbutton(Monitor)
        self.setramprate(Monitor)

        # matplotlib canvas
        self._figVI = Figure(facecolor="whitesmoke")
        self.plotVI = FigureCanvas(self._figVI)
        self.plotVI.setGeometry(QtCore.QRect(380, 20, 640, 400))
        self.plotVI.setObjectName(_fromUtf8("VIshow"))
        self.plotVI.setParent(Monitor)

        self._fig_tI = Figure(facecolor="whitesmoke")
        self.plot_tI = FigureCanvas(self._fig_tI)
        self.plot_tI.setGeometry(QtCore.QRect(40, 450, 300, 200))
        self.plot_tI.setObjectName(_fromUtf8("tIshow"))
        self.plot_tI.setParent(Monitor)

        self._fig_tVp = Figure(facecolor="whitesmoke")
        self.plot_tVp = FigureCanvas(self._fig_tVp)
        self.plot_tVp.setGeometry(QtCore.QRect(380, 450, 300, 200))
        self.plot_tVp.setObjectName(_fromUtf8("tVpshow"))
        self.plot_tVp.setParent(Monitor)

        self._fig_tVh = Figure(facecolor="whitesmoke")
        self.plot_tVh = FigureCanvas(self._fig_tVh)
        self.plot_tVh.setGeometry(QtCore.QRect(720, 450, 300, 200))
        self.plot_tVh.setObjectName(_fromUtf8("tVhshow"))
        self.plot_tVh.setParent(Monitor)

        self.retranslateUi(Monitor)
        #QtCore.QObject.connect(self.exit_but, QtCore.SIGNAL(_fromUtf8("clicked()")), Monitor.close)
        QtCore.QMetaObject.connectSlotsByName(Monitor)

    def retranslateUi(self, Monitor):
        Monitor.setWindowTitle(_translate("Monitor", "Form", None))
        self.supply_dis.setText(
            _translate("Dialog", "Current Supply: OFF", None))
        self.I_on_but.setText(_translate("Dialog", "ON", None))
        self.I_up_but.setText(_translate("Dialog", "SET RAMP", None))
        self.I_off_but.setText(_translate("Dialog", "OFF", None))
        self.exit_but.setText(_translate("Dialog", "EXIT", None))
        self.meas_but.setText(_translate("Dialog", "MEASURE", None))
        self.ramp_lab.setText(_translate("Dialog", "Ramp Rate [A/sec]:", None))

    def setrunning(self, mainwin):
        self.supply_dis = QtGui.QLabel(mainwin)
        self.supply_dis.setGeometry(QtCore.QRect(30, 30, 310, 80))
        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Helvetica"))
        font.setPointSize(28)
        font.setBold(True)
        font.setWeight(75)
        self.supply_dis.setFont(font)
        self.supply_dis.setAlignment(QtCore.Qt.AlignCenter)
        self.supply_dis.setObjectName(_fromUtf8("supply_dis"))

    def setbutton(self, mainwin):
        self.I_on_but = QtGui.QPushButton(mainwin)
        self.I_on_but.setGeometry(QtCore.QRect(90, 200, 200, 40))
        font = QtGui.QFont()
        font.setPointSize(17)
        font.setUnderline(True)
        self.I_on_but.setFont(font)
        self.I_on_but.setAutoFillBackground(False)
        self.I_on_but.setObjectName(_fromUtf8("I_on_but"))
        self.I_up_but = QtGui.QPushButton(mainwin)
        self.I_up_but.setGeometry(QtCore.QRect(90, 250, 200, 40))
        self.I_up_but.setFont(font)
        self.I_up_but.setObjectName(_fromUtf8("I_up_but"))
        self.I_off_but = QtGui.QPushButton(mainwin)
        self.I_off_but.setGeometry(QtCore.QRect(90, 300, 200, 40))
        self.I_off_but.setFont(font)
        self.I_off_but.setObjectName(_fromUtf8("I_off_but"))
        self.meas_but = QtGui.QPushButton(mainwin)
        self.meas_but.setGeometry(QtCore.QRect(90, 360, 200, 40))
        self.meas_but.setFont(font)
        self.meas_but.setObjectName(_fromUtf8("I_off_but"))
        self.exit_but = QtGui.QPushButton(mainwin)
        self.exit_but.setGeometry(QtCore.QRect(90, 410, 200, 40))
        font = QtGui.QFont()
        font.setPointSize(15)
        font.setBold(False)
        font.setItalic(False)
        font.setUnderline(True)
        font.setWeight(50)
        font.setStrikeOut(False)
        font.setKerning(False)
        self.exit_but.setFont(font)
        self.exit_but.setToolTip(_fromUtf8(""))
        self.exit_but.setObjectName(_fromUtf8("exit_but"))

    def setramprate(self, win):
        self.ramp_box = QtGui.QDoubleSpinBox(win)
        self.ramp_box.setEnabled(True)
        self.ramp_box.setGeometry(QtCore.QRect(180, 130, 120, 30))
        self.ramp_box.setProperty("value", 0.1)
        font = QtGui.QFont()
        font.setPointSize(18)
        self.ramp_box.setFont(font)
        self.ramp_box.setAlignment(QtCore.Qt.AlignCenter)
        self.ramp_box.setDecimals(2)
        self.ramp_box.setMaximum(40.0)
        self.ramp_box.setObjectName(_fromUtf8("ramp_box"))
        self.ramp_lab = QtGui.QLabel(win)
        self.ramp_lab.setGeometry(QtCore.QRect(30, 130, 151, 31))
        font = QtGui.QFont()
        font.setPointSize(16)
        self.ramp_lab.setFont(font)
        self.ramp_lab.setObjectName(_fromUtf8("ramp_lab"))
예제 #38
0
class LpdFemGuiLiveViewWindow(QtGui.QDialog):
    
    liveViewUpdateSignal = QtCore.pyqtSignal(object)
    
    matplotlib.rcParams.update({'font.size': 8})
    
    def __init__(self, parent=None, asicModuleType=0):
 
        QtGui.QDialog.__init__(self, parent)

        self.asicModuleType = asicModuleType

        # Set nrows, ncols and moduleType according asicModuleType
        if self.asicModuleType == LpdFemClient.ASIC_MODULE_TYPE_SUPER_MODULE:
            moduleType = "Super Module"
            self.nrows = 256 
            self.ncols = 256
        elif self.asicModuleType == LpdFemClient.ASIC_MODULE_TYPE_TWO_TILE:
            moduleType = "2-Tile System"
            self.nrows = 32
            self.ncols = 256
        elif self.asicModuleType == LpdFemClient.ASIC_MODULE_TYPE_RAW_DATA:
            moduleType = "Super Module [Raw Data]"
            self.nrows = 256 
            self.ncols = 256
        else:
            print("Error: Unsupported asicModuleType selected: %r" % self.asicModuleType, file=sys.stderr)
        
        self.setWindowTitle('Plotting data from %s' % moduleType)

        self.plotFrame =QtGui.QWidget()
        
        # Create the mpl Figure and FigCanvas objects. 
        # 5x4 inches, 100 dots-per-inch
        #
        self.dpi = 100
        self.fig = Figure((8.0, 6.0), dpi=self.dpi)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.plotFrame)
        
        # Since we have only one plot, we can use add_axes 
        # instead of add_subplot, but then the subplot
        # configuration tool in the navigation toolbar wouldn't
        # work.
        #
        self.axes = self.fig.add_subplot(111)
 
        # Disable up the X and Y ticks
        self.axes.set_xticks([])
        self.axes.set_yticks([])
       
        self.imageSize = self.nrows * self.ncols

        # Create an empty plot
        self.data = np.zeros((self.nrows, self.ncols), dtype=np.uint16)                   
        self.imgObject = self.axes.imshow(self.data, interpolation='nearest', vmin=0, vmax=4095, cmap='jet')

        # Position colorbar according to selected asicModuleType
        if self.asicModuleType == 2:
            cBarPosn = 'horizontal'
            # Place 2-Tile plot closer to center of figure
            self.axes.set_position([0.125, 0.4, 0.8, 0.5])
        else: 
            cBarPosn = 'vertical'

        # Create nd show a colourbar
        axc, kw = matplotlib.colorbar.make_axes(self.axes, orientation=cBarPosn)
        cb = matplotlib.colorbar.Colorbar(axc, self.imgObject, orientation=cBarPosn)
        # Fix: Re-adjust tick marks along colour bar:
        cTicks = [0, 511, 1023, 1535, 2047, 2559, 3071, 3583, 4095]
        cb.set_ticks(ticks=cTicks, update_ticks=True)
        self.imgObject.colorbar = cb

        # Add lines according to module type
        if self.asicModuleType == LpdFemClient.ASIC_MODULE_TYPE_TWO_TILE:
             
            # Add vertical lines to differentiate between the ASICs
            for i in range(16, self.ncols, 16):
                self.axes.vlines(i-0.5, 0, self.nrows-1, color='b', linestyles='solid')
            
            # Add vertical lines to differentiate between the two tiles
            self.axes.vlines(128-0.5, 0, self.nrows-1, color='y', linestyle='solid')
            
        elif self.asicModuleType == LpdFemClient.ASIC_MODULE_TYPE_SUPER_MODULE:
                
                # Add vertical lines to differentiate between the ASICs
                for i in range(16, self.ncols, 16):
                    self.axes.vlines(i-0.5, 0, self.nrows-1, color='b', linestyles='solid')
                
                # Add vertical lines to differentiate between tiles
                self.axes.vlines(128-0.5, 0, self.nrows-1, color='y', linestyle='solid')
                
                for i in range(32, self.nrows, 32):
                    self.axes.hlines(i-0.5, 0, self.nrows-1, color='y', linestyles='solid')


        self.canvas.draw()

        # Bind the 'pick' event for clicking on one of the bars
        #
        #self.canvas.mpl_connect('pick_event', self.on_pick)
        
        # Create the navigation toolbar, tied to the canvas
        #
        self.mplToolbar = NavigationToolbar(self.canvas, self.plotFrame)
        
        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(self.mplToolbar)
        vbox.addWidget(self.canvas)
        
        self.setLayout(vbox)
        
        self.setWindowTitle("Live View")
        self.setModal(False)
        
        # Connect the live view update signal
        self.liveViewUpdateSignal.connect(self.liveViewUpdate)
        
    def closeEvent(self, event):
        event.accept()
        
    def liveViewUpdate(self, lpdImage):
        
        # Mask off gain bits
        lpdImage.image_array = lpdImage.image_array & 0xfff
        self.imgObject.set_data(lpdImage.image_array)
        self.axes.draw_artist(self.imgObject)
        self.axes.set_title("Run %d Train %d Image %d" % (lpdImage.run_number, lpdImage.frame_number, lpdImage.image_number))
        self.canvas.draw()
class MyForm(QMainWindow):

    # The __init__ function is what everything the user wants to be initialized when the class is called.
    # Here we shall define the tring functions to corresponding variables.
    # The 'self' variable means that the function is part of the class and can be called inside and outside the class.
    def __init__(self, parent=None):

        # Standard GUI code
        QWidget.__init__(self, parent)

        # All the GUI data and widgets in the Ui_MainWindow() class is defined to "self.ui"
        # Thus to do anything on the GUI, the commands must go through this variable
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # For the canvas.
        self.canvas = FigureCanvas(self.ui.mplwidget.figure)
        self.canvas.setParent(self.ui.widget)
        # We need the toolbar widget for the canvas
        self.mpl_toolbar = NavigationToolbar(self.canvas, self.ui.widget)

        # For the canvas.
        self.canvas_first_step = FigureCanvas(
            self.ui.mplwidget_first_step.figure)
        self.canvas_first_step.setParent(self.ui.widget_first_step)
        # We need the toolbar widget for the canvas
        self.mpl_toolbar_first_step = NavigationToolbar(
            self.canvas_first_step, self.ui.widget_first_step)

        # For the canvas.
        self.canvas_second_step = FigureCanvas(
            self.ui.mplwidget_second_step.figure)
        self.canvas_second_step.setParent(self.ui.widget_second_step)
        # We need the toolbar widget for the canvas
        self.mpl_toolbar_second_step = NavigationToolbar(
            self.canvas_second_step, self.ui.widget_second_step)

        # Create the QVBoxLayout object and add the widget into the layout
        vbox = QVBoxLayout()
        # The matplotlib canvas
        vbox.addWidget(self.canvas)
        # The matplotlib toolbar
        vbox.addWidget(self.mpl_toolbar)
        self.ui.widget.setLayout(vbox)

        # Create the QVBoxLayout object and add the widget into the layout
        vbox_first_step = QVBoxLayout()
        # The matplotlib canvas
        vbox_first_step.addWidget(self.canvas_first_step)
        # The matplotlib toolbar
        vbox_first_step.addWidget(self.mpl_toolbar_first_step)
        self.ui.widget_first_step.setLayout(vbox_first_step)

        # Create the QVBoxLayout object and add the widget into the layout
        vbox_second_step = QVBoxLayout()
        # The matplotlib canvas
        vbox_second_step.addWidget(self.canvas_second_step)
        # The matplotlib toolbar
        vbox_second_step.addWidget(self.mpl_toolbar_second_step)
        self.ui.widget_second_step.setLayout(vbox_second_step)

        # Connect the mplwidget with canvas
        self.ui.mplwidget = self.canvas

        # Connect the mplwidget with canvas
        self.ui.mplwidget_first_step = self.canvas_first_step

        # Connect the mplwidget with canvas
        self.ui.mplwidget_second_step = self.canvas_second_step

        self.connect(self.ui.pushButton_browse, SIGNAL('clicked()'),
                     self.Browse)
        self.connect(self.ui.pushButton_change_name, SIGNAL('clicked()'),
                     self.Plot)
        self.connect(self.ui.pushButton_openfile, SIGNAL('clicked()'),
                     self.OpenFile)
        self.connect(self.ui.radioButton_qmd, SIGNAL('clicked()'),
                     self.Choose_type)
        self.connect(self.ui.radioButton_ppms, SIGNAL('clicked()'),
                     self.Choose_type)
        self.connect(self.ui.radioButton_frontpanel, SIGNAL('clicked()'),
                     self.Choose_type)
        self.connect(self.ui.radioButton_zbridge, SIGNAL('clicked()'),
                     self.Choose_type)
        self.connect(self.ui.radioButton_compressor, SIGNAL('clicked()'),
                     self.Choose_type)
        self.connect(self.ui.pushButton_Plot, SIGNAL('clicked()'),
                     self.Plot_ready)
        self.connect(self.ui.pushButton_recent, SIGNAL('clicked()'),
                     self.Open_Recent)
        self.connect(self.ui.pushButton_plot_first_step, SIGNAL('clicked()'),
                     self.plot1)
        self.connect(self.ui.pushButton_plot_second_step, SIGNAL('clicked()'),
                     self.plot2)
        self.connect(self.ui.pushButton_find, SIGNAL('clicked()'), self.Find)

        self.first_round = True
        self.open_dir = ''
        self.open_files_number = 0
        self.all_info = []

    def Choose_type(self):
        if self.ui.radioButton_qmd.isChecked():
            self.divider = 'Collected Data'
            self.ui.lineEdit_divider.setText(self.divider)
            self.ui.pushButton_browse.setEnabled(True)
            self.ui.lineEdit_condition1.setText('Please choose your file.')
        elif self.ui.radioButton_ppms.isChecked():
            self.divider = '[Data]'
            self.ui.lineEdit_divider.setText(self.divider)
            self.ui.pushButton_browse.setEnabled(True)
            self.ui.lineEdit_condition1.setText('Please choose your file.')
        elif self.ui.radioButton_frontpanel.isChecked():
            self.divider = 'frontpanel'
            self.ui.lineEdit_divider.setText('None')
            self.ui.pushButton_browse.setEnabled(True)
            self.ui.lineEdit_condition1.setText('Please choose your file.')
        elif self.ui.radioButton_zbridge.isChecked():
            self.divider = '#'
            self.ui.lineEdit_divider.setText(self.divider)
            self.ui.pushButton_browse.setEnabled(True)
            self.ui.lineEdit_condition1.setText('Please choose your file.')
        elif self.ui.radioButton_compressor.isChecked():
            self.divider = 'compressor'
            self.ui.lineEdit_divider.setText('None')
            self.ui.pushButton_browse.setEnabled(True)
            self.ui.lineEdit_condition1.setText('Please choose your file.')

    def Browse(self):
        self.open_recent = False

        prev_dir = os.getcwd()
        fileDir = QFileDialog.getOpenFileName(self, 'Select Folder to Save',
                                              prev_dir)
        if fileDir != '':
            open_dir = ''
            file_list = str(fileDir).split('/')
            for i in range(0, len(file_list) - 1):
                if i < len(file_list) - 1:
                    open_dir += file_list[i] + '\\'
                elif i == len(file_list) - 1:
                    open_dir += file_list[i]
            fileDir.replace('/', '\\')
            self.ui.lineEdit_address.setText(fileDir)

            self.ui.pushButton_openfile.setEnabled(True)
            self.ui.groupBox_labels.setEnabled(True)
            self.first_round = False
            filedir = str(fileDir).split('\\')
            self.file_name = filedir[len(filedir) - 1]
            print filedir
        else:
            self.ui.lineEdit_address.setText('None')
            self.ui.lineEdit_condition1.setText('Failed to Read File')

    def OpenFile(self):

        # Every you click the "Open File" button, the content in the plot combox is refreshed
        self.reset_plot()
        self.ui.mplwidget.draw()
        self.reset_first_step_plot()
        self.reset_second_step_plot()
        self.ui.comboBox_x.clear()
        self.ui.comboBox_y.clear()
        self.ui.comboBox_x_2.clear()
        self.ui.comboBox_y_2.clear()
        self.ui.comboBox_y_first_step.clear()
        self.ui.comboBox_y_second_step.clear()
        self.ui.comboBox_first.clear()
        self.ui.comboBox_second.clear()
        self.ui.lineEdit_x.setText('')
        self.ui.lineEdit_y.setText('')
        self.ui.lineEdit_name.setText('')
        self.ui.lineEdit_condition2.setText('')
        self.ui.lineEdit_minute.setText('')
        self.ui.lineEdit_date.setText('')

        labels = ''

        raw_parameters = []
        units = []
        parameters = []
        new_parameters = []
        self.data = []
        new_data = []
        first_data = []

        item = 0
        length = 0
        # This count is the number of the reading loops for labels. If count is over 1000, that means there's something wrong with the divider line and it helps to stop the program
        count = 0

        # It is false when program cannot find the line divider and runs the while loop 1000 times
        self.divider_found = True

        self.fileDir = self.ui.lineEdit_address.text()
        self.divider = str(self.ui.lineEdit_divider.text())
        fp = open(self.fileDir)
        if self.ui.radioButton_frontpanel.isChecked():
            labels = 'None'
        elif self.ui.radioButton_compressor.isChecked():
            labels = fp.readline()
        else:
            while True:
                if count > 1000:
                    self.ui.lineEdit_condition1.setText(
                        'Line divider is not found.')
                    self.divider_found = False
                    break
                line = fp.readline()
                #print 1, line
                linelist = line.split(',')
                if linelist[0].upper() == self.divider.upper() + '\n':
                    break
                for i in range(0, len(linelist)):
                    labels += linelist[i]
                count += 1

        if self.divider_found == True:
            self.ui.textEdit_labels.setText(labels)
            parameters = fp.readline().replace("\n", '')
            if self.ui.radioButton_frontpanel.isChecked():
                parameters = parameters.split('\t')
                for i in range(0, len(parameters)):
                    if parameters[i] == 'P1':
                        parameters[i] = 'Probe Line (P1)'
                    elif parameters[i] == 'P2':
                        parameters[i] = ' OVC Line (P2)'
                    elif parameters[i] == 'P3':
                        parameters[i] = 'IVC/Aux Port Line (P3)'
                    elif parameters[i] == 'P4':
                        parameters[i] = 'Turbo-to-S3 (P4)'
                    elif parameters[i] == 'P5':
                        parameters[i] = 'S3-to-traps (P5)'
                    elif parameters[i] == 'P6':
                        parameters[i] = '4He Dump (P6)'
                    elif parameters[i] == 'P7':
                        parameters[i] = '3He Dump (P7)'
                    elif parameters[i] == 'MG2':
                        parameters[i] = 'OVC Maxigauge (MG2)'
                    elif parameters[i] == 'MG3':
                        parameters[i] = 'Still Maxiguage (MG3)'
                    elif parameters[i] == 'MG4':
                        parameters[i] = 'IVC Maxiguage (MG4)'
                    elif parameters[i] == 'MG5':
                        parameters[i] = 'Probe Maxiguage (MG5)'
            elif self.ui.radioButton_compressor.isChecked():
                parameters = parameters.split('\t')
            else:
                parameters = parameters.split(',')

            if self.ui.radioButton_ppms.isChecked():
                lines = fp.readline().replace("\n", "")
                first_data = lines.split(",")
                for i in range(0, len(first_data)):
                    par = []
                    if first_data[i] != '':
                        par = parameters[i].split(' (')
                        if len(par) == 2:
                            units.append(par[1].replace(')', ''))
                        elif len(par) == 1:
                            units.append('1')
                        new_parameters.append(par[0])
                parameters = new_parameters
            elif self.ui.radioButton_qmd.isChecked():
                units = fp.readline().replace("\n", '')
                units = units.split(",")
            elif self.ui.radioButton_frontpanel.isChecked():
                for i in range(0, len(parameters)):
                    units.append('')
            elif self.ui.radioButton_compressor.isChecked():
                units.append('')
                new_parameters.append(parameters[0])
                for i in range(1, len(parameters)):
                    par = []
                    par = parameters[i].split('(')
                    if par[1].replace(')', '') == 's':
                        units.append('h')
                    else:
                        units.append(par[1].replace(')', ''))
                    new_parameters.append(par[0])
                parameters = new_parameters

            self.ui.comboBox_x_2.addItem('None')
            self.ui.comboBox_y_2.addItem('None')
            self.ui.comboBox_first.addItem('None')
            self.ui.comboBox_second.addItem('None')
            if self.ui.radioButton_compressor.isChecked():
                for i in range(1, len(parameters)):
                    self.ui.comboBox_x.addItem(parameters[i])
                    self.ui.comboBox_y.addItem(parameters[i])
                    self.ui.comboBox_y_first_step.addItem(parameters[i])
                    self.ui.comboBox_y_second_step.addItem(parameters[i])
                    self.ui.comboBox_x_2.addItem(parameters[i])
                    self.ui.comboBox_y_2.addItem(parameters[i])
                    self.ui.comboBox_first.addItem(parameters[i])
                    self.ui.comboBox_second.addItem(parameters[i])
            else:
                for i in range(0, len(parameters)):
                    self.ui.comboBox_x.addItem(parameters[i])
                    self.ui.comboBox_y.addItem(parameters[i])
                    self.ui.comboBox_y_first_step.addItem(parameters[i])
                    self.ui.comboBox_y_second_step.addItem(parameters[i])
                    self.ui.comboBox_x_2.addItem(parameters[i])
                    self.ui.comboBox_y_2.addItem(parameters[i])
                    self.ui.comboBox_first.addItem(parameters[i])
                    self.ui.comboBox_second.addItem(parameters[i])

            for i in range(0, len(parameters)):
                new_data = [parameters[i], units[i], [], []]
                self.data.append(new_data)

            if self.ui.radioButton_ppms.isChecked():
                for i in range(0, len(first_data)):
                    if first_data[i] != '':
                        self.data[item][2].append(first_data[i])
                        item += 1

                length = item

            while True:
                val = []
                lines = fp.readline().replace("\n", "")
                if lines == '':
                    break
                if self.ui.radioButton_frontpanel.isChecked(
                ) or self.ui.radioButton_compressor.isChecked():
                    values = lines.split('\t')
                else:
                    values = lines.split(',')
                for i in range(0, len(values)):
                    if values[0] != 'Measurement was Aborted':
                        if values[i] != '':
                            val.append(values[i])
                if self.ui.radioButton_ppms.isChecked():
                    if len(val) < length:
                        break
                if self.ui.radioButton_frontpanel.isChecked():
                    date_info = val[0].split(' ')
                    weekday = datetime.datetime.strptime(
                        date_info[0], '%Y-%m-%d').strftime('%a')
                    date = date_info[0] + ' ' + weekday + ' ' + date_info[1]
                    self.data[0][3].append(date)
                    self.data[0][3].append(self.convert_time(val[0]))
                for i in range(0, len(val)):
                    self.data[i][2].append(val[i])

            if self.ui.radioButton_frontpanel.isChecked():
                set_zero = self.data[0][3][1]
                for i in range(0, len(self.data[0][2])):
                    self.data[0][2][i] = (
                        (float(self.data[0][3][2 * i + 1]) - set_zero) / 3600)
                self.data[0][1] = 'hour'

            if self.open_recent == False:
                self.item_info = []
                if self.ui.radioButton_frontpanel.isChecked():
                    self.item_info.append('frontpanel')
                elif self.ui.radioButton_compressor.isChecked():
                    self.item_info.append('compressor')
                else:
                    self.item_info.append(self.divider)
                self.item_info.append(self.file_name)
                self.item_info.append(str(self.ui.lineEdit_address.text()))
                self.all_info.append(self.item_info)
                self.ui.comboBox_recent.addItem(
                    self.all_info[len(self.all_info) - 1][1])

            if self.ui.radioButton_compressor.isChecked():
                self.date_transfer = []
                date_tran = []
                date_tran = self.data[0][2]
                for i in range(0, len(date_tran)):
                    date_info = []
                    date_info = date_tran[i].split(' ')
                    weekday = date_info[0]
                    day = date_info[2]
                    year = date_info[4]
                    mon = date_info[1]
                    if mon == 'Jan':
                        mon = '01'
                    elif mon == 'Feb':
                        mon = '02'
                    elif mon == 'Mar':
                        mon = '03'
                    elif mon == 'Apr':
                        mon = '04'
                    elif mon == 'May':
                        mon = '05'
                    elif mon == 'Jun':
                        mon = '06'
                    elif mon == 'Jul':
                        mon = '07'
                    elif mon == 'Aug':
                        mon = '08'
                    elif mon == 'Sep':
                        mon = '09'
                    elif mon == 'Oct':
                        mon = '10'
                    elif mon == 'Nov':
                        mon = '11'
                    elif mon == 'Dec':
                        mon = '12'
                    date = year + '-' + mon + '-' + day + ' ' + weekday + ' ' + date_info[
                        3]
                    self.date_transfer.append(date)
                #self.date_transfer.append(self.data[1][2])
                self.data = self.data[1:]
                for i in range(0, len(self.data[0][2])):
                    self.data[0][2][i] = float(self.data[0][2][i]) / 3600

            self.ui.groupBox_plot.setEnabled(True)
            self.ui.groupBox_first.setEnabled(True)
            self.ui.groupBox_second.setEnabled(True)
            self.ui.lineEdit_condition2.setText('Ready to Plot.')
            self.ui.label_11.setEnabled(True)
            self.ui.comboBox_recent.setEnabled(True)
            self.ui.pushButton_recent.setEnabled(True)
            self.ui.comboBox_y_first_step.setEnabled(True)
            self.ui.pushButton_plot_first_step.setEnabled(True)
            self.ui.pushButton_plot_second_step.setEnabled(True)
            self.ui.comboBox_y_second_step.setEnabled(True)
            self.ui.label_14.setEnabled(True)
            self.ui.label_15.setEnabled(True)
            if self.ui.radioButton_frontpanel.isChecked(
            ) or self.ui.radioButton_compressor.isChecked():
                self.ui.groupBox_date.setEnabled(True)

    def Open_Recent(self):
        file_number = self.ui.comboBox_recent.currentIndex()
        if self.all_info[file_number][0].upper() == '[Data]'.upper():
            self.ui.radioButton_ppms.setChecked(True)
            self.ui.lineEdit_divider.setText('[Data]')
            self.divider = '[Data]' + '\n'
            self.ui.lineEdit_address.setText(self.all_info[file_number][2])
        elif self.all_info[file_number][0].upper() == 'Collected Data'.upper():
            self.ui.radioButton_qmd.setChecked(True)
            self.ui.lineEdit_divider.setText('Collected Data')
            self.divider = 'Collected Data' + '\n'
            self.ui.lineEdit_address.setText(self.all_info[file_number][2])
        elif self.all_info[file_number][0].upper() == 'frontpanel'.upper():
            self.ui.radioButton_frontpanel.setChecked(True)
            self.ui.lineEdit_divider.setText('')
            self.divider = self.all_info[file_number][1] + '\n'
            self.ui.lineEdit_address.setText(self.all_info[file_number][2])
            self.ui.lineEdit_divider.setText('None')
            self.ui.lineEdit_condition1.setText(
                self.ui.comboBox_recent.currentText() + ' has been opened.')
        elif self.all_info[file_number][0].upper() == 'compressor'.upper():
            self.ui.radioButton_compressor.setChecked(True)
            self.ui.lineEdit_divider.setText('')
            self.divider = self.all_info[file_number][1] + '\n'
            self.ui.lineEdit_address.setText(self.all_info[file_number][2])
            self.ui.lineEdit_divider.setText('None')
            self.ui.lineEdit_condition1.setText(
                self.ui.comboBox_recent.currentText() + ' has been opened.')

        self.reset_plot()
        self.ui.mplwidget.draw()
        self.open_recent = True
        self.OpenFile()

    def Find(self):
        try:
            time = float(self.ui.lineEdit_minute.text())
            if time <= self.data[0][2][0]:
                if self.ui.radioButton_frontpanel.isChecked():
                    self.ui.lineEdit_date.setText(self.data[0][3][0])
                elif self.ui.radioButton_compressor.isChecked():
                    self.ui.lineEdit_date.setText(self.date_transfer[0])
            elif time >= self.data[0][2][len(self.data[0][2]) - 1]:
                if self.ui.radioButton_frontpanel.isChecked():
                    self.ui.lineEdit_date.setText(
                        self.data[0][3][2 * (len(self.data[0][2]) - 1)])
                elif self.ui.radioButton_compressor.isChecked():
                    self.ui.lineEdit_date.setText(
                        self.date_transfer[len(self.date_transfer) - 1])
            else:
                item = 0
                while self.data[0][2][item] - time < 0:
                    item += 1
                if abs(self.data[0][2][item - 1] -
                       time) <= abs(self.data[0][2][item] - time):
                    if self.ui.radioButton_frontpanel.isChecked():
                        self.ui.lineEdit_date.setText(
                            self.data[0][3][2 * (item - 1)])
                    elif self.ui.radioButton_compressor.isChecked():
                        self.ui.lineEdit_date.setText(self.date_transfer[item -
                                                                         1])
                else:
                    if self.ui.radioButton_frontpanel.isChecked():
                        self.ui.lineEdit_date.setText(self.data[0][3][2 *
                                                                      item])
                    elif self.ui.radioButton_compressor.isChecked():
                        self.ui.lineEdit_date.setText(self.date_transfer[item])

        except ValueError:
            self.ui.lineEdit_date.setText('')
            self.ui.lineEdit_condition2.setText('Please enter valid time.')

    def Plot_ready(self):
        self.x_value = 0
        self.y_value = 0
        self.x_value = self.ui.comboBox_x.currentIndex()
        self.y_value = self.ui.comboBox_y.currentIndex()
        xaxis = self.data[self.x_value][0]
        xunit = self.data[self.x_value][1]
        yaxis = self.data[self.y_value][0]
        yunit = self.data[self.y_value][1]

        self.x2_value = 0
        self.y2_value = 0
        self.x2_value = self.ui.comboBox_x_2.currentIndex() - 1
        self.y2_value = self.ui.comboBox_y_2.currentIndex() - 1
        x2axis = self.data[self.x2_value][0]
        x2unit = self.data[self.x2_value][1]
        y2axis = self.data[self.y2_value][0]
        y2unit = self.data[self.y2_value][1]

        if self.x2_value == -1:
            self.ui.lineEdit_x.setText(xaxis + ' (' + xunit + ')')
            self.x_value = self.data[self.x_value][2]
        elif self.x2_value >= 0:
            self.ui.lineEdit_x.setText(xaxis + '/' + x2axis + ' (' + xunit +
                                       '/' + x2unit + ')')
            if self.ui.radioButton_x_divide.isChecked():
                self.x_value = numpy.array(
                    self.data[self.x_value][2], dtype='float') / numpy.array(
                        self.data[self.x2_value][2], dtype='float')
            elif self.ui.radioButton_x_multiply.isChecked():
                self.x_value = numpy.array(
                    self.data[self.x_value][2], dtype='float') * numpy.array(
                        self.data[self.x2_value][2], dtype='float')
            elif self.ui.radioButton_x_plus.isChecked():
                self.x_value = numpy.array(
                    self.data[self.x_value][2], dtype='float') + numpy.array(
                        self.data[self.x2_value][2], dtype='float')
            elif self.ui.radioButton_x_minus.isChecked():
                self.x_value = numpy.array(
                    self.data[self.x_value][2], dtype='float') - numpy.array(
                        self.data[self.x2_value][2], dtype='float')
        if self.ui.checkBox_x_value.isChecked():
            self.x_value = numpy.absolute(self.x_value)

        if self.y2_value == -1:
            self.ui.lineEdit_y.setText(yaxis + ' (' + yunit + ')')
            self.y_value = self.data[self.y_value][2]
        elif self.y2_value >= 0:
            self.ui.lineEdit_y.setText(yaxis + '/' + y2axis + ' (' + yunit +
                                       '/' + y2unit + ')')
            if self.ui.radioButton_y_divide.isChecked():
                self.y_value = numpy.array(
                    self.data[self.y_value][2], dtype='float') / numpy.array(
                        self.data[self.y2_value][2], dtype='float')
            elif self.ui.radioButton_x_multiply.isChecked():
                self.y_value = numpy.array(
                    self.data[self.y_value][2], dtype='float') * numpy.array(
                        self.data[self.y2_value][2], dtype='float')
            elif self.ui.radioButton_x_plus.isChecked():
                self.y_value = numpy.array(
                    self.data[self.y_value][2], dtype='float') + numpy.array(
                        self.data[self.y2_value][2], dtype='float')
            elif self.ui.radioButton_x_minus.isChecked():
                self.y_value = numpy.array(
                    self.data[self.y_value][2], dtype='float') - numpy.array(
                        self.data[self.y2_value][2], dtype='float')
        if self.ui.checkBox_y_value.isChecked():
            self.y_value = numpy.absolute(self.y_value)

        if self.x2_value == -1 and self.y2_value == -1:
            self.ui.lineEdit_name.setText(yaxis + ' vs. ' + xaxis)
        elif self.x2_value >= 0 and self.y2_value == -1:
            self.ui.lineEdit_name.setText(yaxis + ' vs. ' + xaxis + '/' +
                                          x2axis)
        elif self.x2_value == -1 and self.y2_value >= 0:
            self.ui.lineEdit_name.setText(yaxis + '/' + y2axis + ' vs. ' +
                                          xaxis)
        else:
            self.ui.lineEdit_name.setText(yaxis + '/' + y2axis + ' vs. ' +
                                          xaxis + '/' + x2axis)

        self.ui.pushButton_change_name.setEnabled(True)
        self.Plot()

    def Plot(self):
        self.reset_plot()
        self.axes.plot(self.x_value, self.y_value, marker='.', linestyle=':')
        self.axes.grid()
        self.axes.set_title(self.ui.lineEdit_name.text())
        self.axes.set_xlabel(self.ui.lineEdit_x.text())
        self.axes.set_ylabel(self.ui.lineEdit_y.text())
        self.ui.mplwidget.draw()

        self.ui.lineEdit_condition2.setText('Plot successfully.')

    def plot1(self):
        y_value1 = self.ui.comboBox_y_first_step.currentIndex()
        y_value2 = self.ui.comboBox_first.currentIndex() - 1
        y_axis1 = self.data[y_value1][0]
        y_axis2 = self.data[y_value2][0]
        y_unit1 = self.data[y_value1][1]
        y_unit2 = self.data[y_value2][1]
        yv1 = self.data[y_value1][2]
        yv2 = self.data[y_value2][2]
        xv = []

        item = 0
        for i in range(0, len(yv1)):
            xv.append(item)
            item += 1

        if y_value2 == -1:
            y_value = yv1
            y_name = y_axis1 + ' (' + y_unit1 + ')'
            name = y_axis1 + ' Steps'
        elif y_value2 >= 0:
            if self.ui.radioButton_first_divide.isChecked():
                y_value = numpy.array(
                    self.data[y_value1][2], dtype='float') / numpy.array(
                        self.data[y_value2][2], dtype='float')
                y_name = y_axis1 + ' / ' + y_axis2 + ' (' + y_unit1 + ' / ' + y_unit2 + ')'
                name = y_axis1 + ' / ' + y_axis2 + ' Steps'
            elif self.ui.radioButton_first_multiply.isChecked():
                y_value = numpy.array(
                    self.data[y_value1][2], dtype='float') * numpy.array(
                        self.data[y_value2][2], dtype='float')
                y_name = y_axis1 + ' * ' + y_axis2 + ' (' + y_unit1 + ' * ' + y_unit2 + ')'
                name = y_axis1 + ' * ' + y_axis2 + ' Steps'
            elif self.ui.radioButton_first_plus.isChecked():
                y_value = numpy.array(
                    self.data[y_value1][2], dtype='float') + numpy.array(
                        self.data[y_value2][2], dtype='float')
                y_name = y_axis1 + ' + ' + y_axis2 + ' (' + y_unit1 + ' + ' + y_unit2 + ')'
                name = y_axis1 + ' + ' + y_axis2 + ' Steps'
            elif self.ui.radioButton_first_minus.isChecked():
                y_value = numpy.array(
                    self.data[y_value1][2], dtype='float') - numpy.array(
                        self.data[y_value2][2], dtype='float')
                y_name = y_axis1 + ' - ' + y_axis2 + ' (' + y_unit1 + ' - ' + y_unit2 + ')'
                name = y_axis1 + ' - ' + y_axis2 + ' Steps'
        if self.ui.checkBox_first.isChecked():
            y_value = numpy.absolute(y_value)

        self.reset_first_step_plot()
        self.axes_first_step.plot(xv, y_value, marker='.', linestyle=':')
        self.axes_first_step.grid()
        self.axes_first_step.set_title(name)
        self.axes_first_step.set_xlabel('Unit Step (1)')
        self.axes_first_step.set_ylabel(y_name)
        self.ui.mplwidget_first_step.draw()

    def plot2(self):
        y_value1 = self.ui.comboBox_y_second_step.currentIndex()
        y_value2 = self.ui.comboBox_second.currentIndex() - 1
        y_axis1 = self.data[y_value1][0]
        y_axis2 = self.data[y_value2][0]
        y_unit1 = self.data[y_value1][1]
        y_unit2 = self.data[y_value2][1]
        yv1 = self.data[y_value1][2]
        yv2 = self.data[y_value2][2]
        xv = []
        item = 0
        for i in range(0, len(yv1)):
            xv.append(item)
            item += 1

        if y_value2 == -1:
            y_value = yv1
            y_name = y_axis1 + ' (' + y_unit1 + ')'
            name = y_axis1 + ' Steps'
        elif y_value2 >= 0:
            if self.ui.radioButton_second_divide.isChecked():
                y_value = numpy.array(
                    self.data[y_value1][2], dtype='float') / numpy.array(
                        self.data[y_value2][2], dtype='float')
                y_name = y_axis1 + ' / ' + y_axis2 + ' (' + y_unit1 + ' / ' + y_unit2 + ')'
                name = y_axis1 + ' / ' + y_axis2 + ' Steps'
            elif self.ui.radioButton_second_multiply.isChecked():
                y_value = numpy.array(
                    self.data[y_value1][2], dtype='float') * numpy.array(
                        self.data[y_value2][2], dtype='float')
                y_name = y_axis1 + ' * ' + y_axis2 + ' (' + y_unit1 + ' * ' + y_unit2 + ')'
                name = y_axis1 + ' * ' + y_axis2 + ' Steps'
            elif self.ui.radioButton_second_plus.isChecked():
                y_value = numpy.array(
                    self.data[y_value1][2], dtype='float') + numpy.array(
                        self.data[y_value2][2], dtype='float')
                y_name = y_axis1 + ' + ' + y_axis2 + ' (' + y_unit1 + ' + ' + y_unit2 + ')'
                name = y_axis1 + ' + ' + y_axis2 + ' Steps'
            elif self.ui.radioButton_second_minus.isChecked():
                y_value = numpy.array(
                    self.data[y_value1][2], dtype='float') - numpy.array(
                        self.data[y_value2][2], dtype='float')
                y_name = y_axis1 + ' - ' + y_axis2 + ' (' + y_unit1 + ' - ' + y_unit2 + ')'
                name = y_axis1 + ' - ' + y_axis2 + ' Steps'
        if self.ui.checkBox_second.isChecked():
            y_value = numpy.absolute(y_value)

        self.reset_second_step_plot()
        self.axes_second_step.plot(xv, y_value, marker='.', linestyle=':')
        self.axes_second_step.grid()
        self.axes_second_step.set_title(name)
        self.axes_second_step.set_xlabel('Unit Step (1)')
        self.axes_second_step.set_ylabel(y_name)
        self.ui.mplwidget_second_step.draw()

    def reset_plot(self):
        self.ui.mplwidget.figure.clear()
        self.axes = self.ui.mplwidget.figure.add_subplot(111)

    def reset_first_step_plot(self):
        self.ui.mplwidget_first_step.figure.clear()
        self.axes_first_step = self.ui.mplwidget_first_step.figure.add_subplot(
            111)

    def reset_second_step_plot(self):
        self.ui.mplwidget_second_step.figure.clear()
        self.axes_second_step = self.ui.mplwidget_second_step.figure.add_subplot(
            111)

    def convert_time(self, d):
        date, times = d.split(" ")
        year, month, day = date.split("-")
        hour, minute, second = times.split(":")

        t = datetime.datetime(int(year), int(month), int(day), int(hour),
                              int(minute), int(second))
        t_sec = time.mktime(t.timetuple())

        return t_sec

    def closeEvent(self, question):
        quit_msg = "Do you want to quit the program?"
        reply = QMessageBox.question(self, 'Message', quit_msg,
                                     QMessageBox.Yes, QMessageBox.No)
        # If your answer is "yes", then quit
        if reply == QMessageBox.Yes:
            question.accept()
        # If your answer is "no", then get back
        else:
            question.ignore()
예제 #40
0
class PerceptronDemo(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        self.setWindowTitle('Perceptron Demo')
        self.frame = QtGui.QWidget()
        self.create_plot()
        self.layout_window()
        self.create_status_bar()
        self.setGeometry(50, 50, 680, 600)
        self.data = []
        self.data = []
        self.total_epochs = 0
        self.net = SingleNeuronPerceptron()

    def create_plot(self):

        self.plot_figure = Figure((6.0, 6.0), dpi=100)
        self.plot_canvas = FigureCanvas(self.plot_figure)
        self.plot_canvas.setParent(self.frame)

        # Add a plot
        self.axes = self.plot_figure.add_subplot(111)
        self.plot_figure.subplots_adjust(bottom=0.2, left=0.1)
        self.axes.set_xlim(0, 10)
        self.axes.set_ylim(0, 10)
        self.axes.tick_params(labelsize=8)
        self.axes.set_xlabel("$p^1$", fontsize=10)
        self.axes.set_ylabel("$p^2$", fontsize=10)
        self.pos_line, = self.axes.plot([], 'mo', label="Positive Class")
        self.neg_line, = self.axes.plot([], 'cs', label="Negative Class")
        self.decision, = self.axes.plot([], 'r-', label="Decision Boundary")
        self.axes.legend(loc='lower center',
                         fontsize=8,
                         framealpha=0.9,
                         numpoints=1,
                         ncol=3,
                         bbox_to_anchor=(0, -.24, 1, -.280),
                         mode='expand')
        self.axes.set_title("Single Neuron Perceptron")
        self.plot_canvas.draw()

        # Add event handler for a mouseclick in the plot
        self.plot_canvas.mpl_connect('button_press_event', self.on_mouseclick)

    def create_status_bar(self):
        self.current_status = QtGui.QLabel("Starting")
        self.statusBar().addWidget(self.current_status, 1)

    def layout_window(self):
        explain = QtGui.QLabel(
            "On the plot, click the: <ul><li><b>Primary mouse button</b> to add a positive class observation</li>"
            +
            "<li><b>Secondary mouse button</b> to add a negative class observation</li></ul>\n"
            +
            "Then click <b>Run</b> to start a training run. The training run will stop when the error goes to 0 or when the epoch limit is reached."
        )

        epoch_font = QtGui.QFont("Courier", 14, QtGui.QFont.Bold)
        epoch_label = QtGui.QLabel("Epochs so far:")
        epoch_label.setFixedHeight(20)
        self.epoch_display = QtGui.QLabel("---")
        self.epoch_display.setFixedHeight(25)
        self.epoch_display.setFont(epoch_font)
        error_label = QtGui.QLabel("Error:")
        error_label.setFixedHeight(20)
        self.error_display = QtGui.QLabel("---")
        self.error_display.setFixedHeight(25)
        self.error_display.setFont(epoch_font)
        epr_label = QtGui.QLabel("Max Epochs per run:")
        self.epochs_per_run = QtGui.QComboBox()
        self.epochs_per_run.addItems(["1", "10", "100", "1000"])
        self.epochs_per_run.setCurrentIndex(2)

        self.run_button = QtGui.QPushButton("Run")
        self.connect(self.run_button, QtCore.SIGNAL('clicked()'), self.on_run)
        self.rerun_button = QtGui.QPushButton("Reset to Start")
        self.connect(self.rerun_button, QtCore.SIGNAL('clicked()'),
                     self.on_reset)
        self.undo_click_button = QtGui.QPushButton("Undo Last Mouse Click")
        self.connect(self.undo_click_button, QtCore.SIGNAL('clicked()'),
                     self.on_undo_mouseclick)
        self.clear_button = QtGui.QPushButton("Clear Data")
        self.connect(self.clear_button, QtCore.SIGNAL('clicked()'),
                     self.on_clear)

        # Control
        control_panel = QtGui.QVBoxLayout()
        for w in (epoch_label, self.epoch_display, error_label, self.error_display, epr_label, \
                  self.epochs_per_run, self.run_button, self.rerun_button, self.undo_click_button, \
                  self.clear_button):
            control_panel.addWidget(w)
            #control_panel.setAlignment(w, QtCore.Qt.AlignHCenter)
        control_panel.addStretch(10)
        # Plot
        plot_panel = QtGui.QVBoxLayout()
        #plot_panel.addWidget(explain)
        plot_panel.addWidget(self.plot_canvas)

        # Main window
        hbox = QtGui.QHBoxLayout()
        hbox.addLayout(plot_panel)
        hbox.addLayout(control_panel)
        vbox = QtGui.QVBoxLayout()
        vbox.addLayout(hbox)
        vbox.addWidget(explain)
        self.frame.setLayout(vbox)
        self.setCentralWidget(self.frame)

    def draw_data(self):
        self.pos_line.set_data([x[0] for x in self.data if x[2] == POS],
                               [y[1] for y in self.data if y[2] == POS])
        self.neg_line.set_data([x[0] for x in self.data if x[2] == NEG],
                               [y[1] for y in self.data if y[2] == NEG])
        self.plot_canvas.draw()

    def draw_decision_boundary(self):
        lim = self.axes.get_xlim()
        X = np.linspace(lim[0], lim[1], 101)
        Y = self.net.find_decision_boundary(X)
        self.decision.set_data(X, Y)
        self.plot_canvas.draw()

    def clear_decision_boundary(self):
        self.decision.set_data([], [])
        self.plot_canvas.draw()

    def on_mouseclick(self, event):
        """Add an item to the plot"""
        if event.xdata != None and event.xdata != None:
            self.data.append(
                (event.xdata, event.ydata, POS if event.button == 1 else NEG))
            self.draw_data()
            self.current_status.setText("x={0:0.2f} y={1:0.2f}".format(
                event.xdata, event.ydata))

    def on_clear(self):
        self.data = []
        self.clear_decision_boundary()
        self.net.initialize_weights()
        self.total_epochs = 0
        self.update_run_status()
        self.draw_data()

    def update_run_status(self):
        if self.total_epochs == 0:
            self.epoch_display.setText("---")
            self.error_display.setText("---")
        else:
            self.epoch_display.setText(str(self.total_epochs))
            self.error_display.setText(str(self.total_error))

    def on_run(self):

        # Do 10 epochs
        for epoch in range(int(self.epochs_per_run.currentText())):

            self.total_epochs += 1

            training = self.data.copy()
            np.random.shuffle(training)
            for d in training:
                self.net.train_one_iteration(np.array(d[0:2]), d[2])

            # Calculate the error for the epoch
            self.all_t_hat = np.array(
                [self.net.run_forward(np.array(xy[0:2])) for xy in self.data])
            self.total_error = abs(
                np.array([t[2] for t in self.data]) - self.all_t_hat).sum()

            if self.total_error == 0:
                break

        # print("Epoch:", self.total_epochs, "Error is:", total_error)
        self.current_status.setText("Epoch: {0} Error: {1}".format(
            self.total_epochs, self.total_error))
        self.update_run_status()
        self.draw_decision_boundary()

    def on_reset(self):
        self.net.initialize_weights()
        self.total_epochs = 0
        self.update_run_status()
        self.clear_decision_boundary()

    def on_undo_mouseclick(self):
        if len(self.data) > 1:
            self.data.pop()
            self.draw_data()
예제 #41
0
class camera_histogram(QtGui.QWidget):
    def __init__(self, reactor, cxn=None, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.reactor = reactor
        self.cxn = cxn
        self.last_data = None
        self.last_hist = None
        self.subscribed = [False, False]
        self.create_layout()
        self.connect_labrad()

    def create_layout(self):
        layout = QtGui.QVBoxLayout()
        plot_layout = self.create_plot_layout()
        layout.addLayout(plot_layout)
        self.setLayout(layout)

    def create_plot_layout(self):
        layout = QtGui.QVBoxLayout()
        self.fig = Figure()
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)
        self.axes = self.fig.add_subplot(111)
        self.axes.set_xlim(left=0, right=1)
        self.axes.set_ylim(bottom=0, top=50)
        self.mpl_toolbar = NavigationToolbar(self.canvas, self)
        self.axes.set_title('Camera Readout', fontsize=22)
        self.fig.tight_layout()
        layout.addWidget(self.mpl_toolbar)
        layout.addWidget(self.canvas)
        return layout

    def on_new_data(self, readout):
        self.last_data = readout
        self.updade_histogram(readout)

    def updade_histogram(self, data):
        #remove old histogram
        if self.last_hist is not None:
            self.last_hist.remove()
            #explicitly delete the refrence although not necessary
            del self.last_hist
        self.last_hist = self.axes.bar(data[:, 0],
                                       data[:, 1],
                                       width=numpy.max(data[:, 0]) /
                                       len(data[:, 0]))
        #redo the limits
        x_maximum = data[:, 0].max()
        self.axes.set_xlim(left=0)
        if x_maximum > self.axes.get_xlim()[1]:
            self.axes.set_xlim(right=x_maximum)
        self.axes.set_ylim(bottom=0)
        y_maximum = data[:, 1].max()
        if y_maximum > self.axes.get_ylim()[1]:
            self.axes.set_ylim(top=y_maximum)
        self.canvas.draw()

    @inlineCallbacks
    def connect_labrad(self):
        if self.cxn is None:
            from common.clients import connection
            self.cxn = connection.connection()
            yield self.cxn.connect()
        self.context = yield self.cxn.context()
        try:
            yield self.subscribe_data_vault()
        except Exception, e:
            print e
            self.setDisabled(True)
        yield self.cxn.add_on_connect('Data Vault',
                                      self.reinitialize_data_vault)
        yield self.cxn.add_on_disconnect('Data Vault', self.disable)
예제 #42
0
class PlotView(QtWidgets.QWidget):
    '''class for plotting plots'''
    def __init__(self, parent=None):
        super(PlotView, self).__init__(parent)

        self.fig = plt.figure()
        self.axisconstant = plt.subplot(221)
        self.axispsd = plt.subplot(122)
        self.axistext = plt.subplot(223)
        plt.sca(self.axistext)
        plt.axis('off')
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)

        self.layout = QtWidgets.QVBoxLayout()
        self.layout.addWidget(self.canvas)
        self.layout.setStretchFactor(self.canvas, 1)
        self.setLayout(self.layout)

        self.configfile = ''
        self.stats_filename = ''
        self.av_window = pd.Timedelta(seconds=30)
        self.datadir = os.getcwd()
        self.canvas.draw()

    def load_data(self):
        '''handles loading of data, depending on what is available'''
        self.datadir = os.path.split(self.configfile)[0]

        self.stats_filename = ''
        self.stats_filename = QFileDialog.getOpenFileName(
            self,
            caption='Load a *-STATS.csv file',
            directory=self.datadir,
            filter=(('*-STATS.csv')))[0]
        if self.stats_filename == '':
            return

        timeseriesgas_file = self.stats_filename.replace(
            '-STATS.csv', '-TIMESERIESgas.xlsx')

        if os.path.isfile(timeseriesgas_file):
            self.load_from_timeseries()
        else:

            msgBox = QMessageBox()
            msgBox.setText(
                'The STATS data appear not to have been exported to TIMSERIES.xlsx'
                +
                '\n We can use the STATS file anyway (which might take a while)'
                + '\n or we can convert the data to TIMSERIES.xls now,'
                '\n which can be used quickly if you want to load these data another time.'
            )
            msgBox.setIcon(QMessageBox.Question)
            msgBox.setWindowTitle('What to do?')
            load_stats_button = msgBox.addButton('Load stats anyway',
                                                 QMessageBox.ActionRole)
            convert_stats_button = msgBox.addButton(
                'Convert and save timeseries', QMessageBox.ActionRole)
            msgBox.addButton(QMessageBox.Cancel)
            msgBox.exec_()
            if self.configfile == '':
                self.configfile = QFileDialog.getOpenFileName(
                    self,
                    caption='Load config ini file',
                    directory=self.datadir,
                    filter=(('*.ini')))[0]
                if self.configfile == '':
                    return
            if (msgBox.clickedButton() == load_stats_button):
                self.settings = PySilcamSettings(self.configfile)
                self.av_window = pd.Timedelta(
                    seconds=self.settings.PostProcess.window_size)
                self.load_from_stats()
            elif (msgBox.clickedButton() == convert_stats_button):
                export_timeseries(self.configfile, self.stats_filename)
                self.load_from_timeseries()
            else:
                return

        self.setup_figure()

    def load_from_timeseries(self):
        '''uses timeseries xls sheets assuming they are available'''
        timeseriesgas_file = self.stats_filename.replace(
            '-STATS.csv', '-TIMESERIESgas.xlsx')
        timeseriesoil_file = self.stats_filename.replace(
            '-STATS.csv', '-TIMESERIESoil.xlsx')

        gas = pd.read_excel(timeseriesgas_file, parse_dates=['Time'])
        oil = pd.read_excel(timeseriesoil_file, parse_dates=['Time'])

        self.dias = np.array(oil.columns[0:52], dtype=float)
        self.vd_oil = oil.as_matrix(columns=oil.columns[0:52])
        self.vd_gas = gas.as_matrix(columns=gas.columns[0:52])
        self.vd_total = self.vd_oil + self.vd_gas
        self.u = pd.to_datetime(oil['Time'].values)
        self.d50_gas = gas['D50']
        self.d50_oil = oil['D50']

        self.d50_total = np.zeros_like(self.d50_oil)
        for i, vd in enumerate(self.vd_total):
            self.d50_total[i] = scpp.d50_from_vd(vd, self.dias)

    def load_from_stats(self):
        '''loads stats data and converts to timeseries without saving'''
        stats = pd.read_csv(self.stats_filename, parse_dates=['timestamp'])

        u = stats['timestamp'].unique()
        u = pd.to_datetime(u)
        sample_volume = scpp.get_sample_volume(
            self.settings.PostProcess.pix_size,
            path_length=self.settings.PostProcess.path_length)

        dias, bin_lims = scpp.get_size_bins()
        vd_oil = np.zeros((len(u), len(dias)))
        vd_gas = np.zeros_like(vd_oil)
        vd_total = np.zeros_like(vd_oil)
        d50_gas = np.zeros(len(u))
        d50_oil = np.zeros_like(d50_gas)
        d50_total = np.zeros_like(d50_gas)
        # @todo make this number of particles per image, and sum according to index later
        nparticles_all = 0
        nparticles_total = 0
        nparticles_oil = 0
        nparticles_gas = 0

        for i, s in enumerate(tqdm(u)):
            substats = stats[stats['timestamp'] == s]
            nparticles_all += len(substats)

            nims = scpp.count_images_in_stats(substats)
            sv = sample_volume * nims

            oil = scog.extract_oil(substats)
            nparticles_oil += len(oil)
            dias, vd_oil_ = scpp.vd_from_stats(oil, self.settings.PostProcess)
            vd_oil_ /= sv
            vd_oil[i, :] = vd_oil_

            gas = scog.extract_gas(substats)
            nparticles_gas += len(gas)
            dias, vd_gas_ = scpp.vd_from_stats(gas, self.settings.PostProcess)
            vd_gas_ /= sv
            vd_gas[i, :] = vd_gas_
            d50_gas[i] = scpp.d50_from_vd(vd_gas_, dias)

            nparticles_total += len(oil) + len(gas)
            vd_total_ = vd_oil_ + vd_gas_
            d50_total[i] = scpp.d50_from_vd(vd_total_, dias)
            vd_total[i, :] = vd_total_

        self.vd_total = vd_total
        self.vd_gas = vd_gas
        self.vd_oil = vd_oil
        self.d50_total = d50_total
        self.d50_oil = d50_oil
        self.d50_gas = d50_gas
        self.u = u
        self.dias = dias

    def setup_figure(self):
        '''sets up the plotting figure'''
        plt.sca(self.axisconstant)
        plt.cla()
        plt.pcolormesh(self.u,
                       self.dias,
                       np.log(self.vd_total.T),
                       cmap=cmocean.cm.matter)
        plt.plot(self.u, self.d50_total, 'kx', markersize=5, alpha=0.25)
        plt.plot(self.u, self.d50_gas, 'bx', markersize=5, alpha=0.25)
        plt.yscale('log')
        plt.ylabel('ECD [um]')
        plt.ylim(10, 12000)

        self.start_time = min(self.u)
        self.end_time = max(self.u)
        self.mid_time = min(self.u) + (max(self.u) - min(self.u)) / 2
        self.line1 = plt.vlines(self.start_time, 1, 12000, 'r')
        self.line2 = plt.vlines(self.end_time, 1, 12000, 'r')

        self.fig.canvas.callbacks.connect('button_press_event', self.on_click)

        self.update_plot()

    def on_click(self, event):
        '''if you click the correct place, update the plot based on where you click'''
        if event.inaxes is not None:
            try:
                self.mid_time = pd.to_datetime(
                    matplotlib.dates.num2date(event.xdata)).tz_convert(None)
                self.update_plot()
            except:
                pass
        else:
            pass

    def update_plot(self, save=False):
        '''update the plots and save to excel is save=True'''
        start_time = self.mid_time - self.av_window / 2
        end_time = self.mid_time + self.av_window / 2
        u = pd.to_datetime(self.u)
        timeind = np.argwhere((u >= start_time) & (u < end_time))

        psd_nims = len(timeind)
        if psd_nims < 1:
            plt.sca(self.axispsd)
            plt.cla()

            plt.sca(self.axistext)

            string = ''
            string += '\n Num images: {:0.0f}'.format(psd_nims)
            string += '\n Start: ' + str(start_time)
            string += '\n End: ' + str(end_time)
            string += '\n Window [sec.] {:0.3f}:'.format(
                (end_time - start_time).total_seconds())

            plt.title(string,
                      verticalalignment='top',
                      horizontalalignment='right',
                      loc='right')

            plt.sca(self.axisconstant)
            self.line1.remove()
            self.line2.remove()
            self.line1 = plt.vlines(start_time, 1, 12000, 'r', linestyle='--')
            self.line2 = plt.vlines(end_time, 1, 12000, 'r', linestyle='--')
            self.canvas.draw()
            return

        psd_start = min(u[timeind])
        psd_end = max(u[timeind])

        psd_total = np.mean(self.vd_total[timeind, :], axis=0)[0]
        psd_oil = np.mean(self.vd_oil[timeind, :], axis=0)[0]
        psd_gas = np.mean(self.vd_gas[timeind, :], axis=0)[0]

        psd_vc_total = np.sum(psd_total)
        psd_vc_oil = np.sum(psd_oil)
        psd_vc_gas = np.sum(psd_gas)

        psd_d50_total = scpp.d50_from_vd(psd_total, self.dias)
        psd_d50_oil = scpp.d50_from_vd(psd_oil, self.dias)
        psd_d50_gas = scpp.d50_from_vd(psd_gas, self.dias)

        psd_gor = sum(psd_gas) / (sum(psd_oil) + sum(psd_gas)) * 100

        plt.sca(self.axispsd)
        plt.cla()
        plt.plot(self.dias, psd_total, 'k', linewidth=5, label='Total')
        plt.plot(self.dias, psd_oil, color=[0.7, 0.4, 0], label='Oil')
        plt.plot(self.dias, psd_gas, 'b', label='Gas')
        plt.xlabel('ECD [um]')
        plt.ylabel('VD [uL/L]')
        plt.xscale('log')
        plt.xlim(10, 12000)

        plt.sca(self.axistext)

        string = ''
        string += 'GOR: {:0.01f}'.format(psd_gor)
        string += '\n d50 total [um]: {:0.0f}'.format(psd_d50_total)
        string += '\n d50 oil [um]: {:0.0f}'.format(psd_d50_oil)
        string += '\n d50 gas [um]: {:0.0f}'.format(psd_d50_gas)
        string += '\n VC total [uL/L]: {:0.0f}'.format(psd_vc_total)
        string += '\n VC oil [uL/L]: {:0.0f}'.format(psd_vc_oil)
        string += '\n VC gas [uL/L]: {:0.0f}'.format(psd_vc_gas)
        string += '\n Num images: {:0.0f}'.format(psd_nims)
        string += '\n Start: ' + str(pd.to_datetime(psd_start[0]))
        string += '\n End: ' + str(pd.to_datetime(psd_end[0]))
        string += '\n Window [sec.] {:0.3f}:'.format(
            pd.to_timedelta(psd_end[0] - psd_start[0]).total_seconds())

        plt.title(string,
                  verticalalignment='top',
                  horizontalalignment='right',
                  loc='right')

        plt.sca(self.axisconstant)
        self.line1.remove()
        self.line2.remove()
        self.line1 = plt.vlines(pd.to_datetime(psd_start[0]), 1, 12000, 'r')
        self.line2 = plt.vlines(pd.to_datetime(psd_end[0]), 1, 12000, 'r')
        self.canvas.draw()

        if save:
            timestring = pd.to_datetime(
                psd_start[0]).strftime('D%Y%m%dT%H%M%S')
            outputname = self.stats_filename.replace('-STATS.csv',
                                                     '-PSD-' + timestring)
            outputname = QFileDialog.getSaveFileName(self,
                                                     "Select file to Save",
                                                     outputname, ".xlsx")
            if outputname[1] == '':
                return
            outputname = outputname[0] + outputname[1]

            wb = Workbook()
            ws = wb.active
            ws['A1'] = 'Start:'
            ws['B1'] = min(u)
            ws['A2'] = 'Weighted average:'
            ws['B2'] = 'NOT IMPLEMENTED'
            ws['A3'] = 'End:'
            ws['B3'] = max(u)

            ws['A5'] = 'Number of images:'
            ws['B5'] = psd_nims

            ws['D5'] = 'd50(microns):'
            ws['E5'] = psd_d50_total
            ws['A6'] = 'Number of particles:'
            ws['B6'] = 'NOT IMPLEMENTED'
            ws['D6'] = 'peak || modal size class (microns):'
            ws['E6'] = 'NOT IMPLEMENTED'

            ws['D13'] = 'd50(microns):'
            ws['E13'] = psd_d50_oil
            ws['D14'] = 'peak || modal size class (microns):'
            ws['E14'] = 'NOT IMPLEMENTED'

            ws['D21'] = 'd50(microns):'
            ws['E21'] = psd_d50_gas
            ws['D22'] = 'peak || modal size class (microns):'
            ws['E22'] = 'NOT IMPLEMENTED'

            ws['A8'] = 'Bin mid-sizes (microns):'
            ws['A9'] = 'Vol. Conc. / bin (uL/L):'
            ws['A16'] = 'Vol. Conc. / bin (uL/L):'
            ws['A24'] = 'Vol. Conc. / bin (uL/L):'
            ws['A12'] = 'OIL Info'
            ws['A20'] = 'GAS Info'
            # d = ws.cells(row='8')
            for c in range(len(self.dias)):
                ws.cell(row=8, column=c + 2, value=self.dias[c])
                ws.cell(row=9, column=c + 2, value=psd_total[c])
                ws.cell(row=16, column=c + 2, value=psd_oil[c])
                ws.cell(row=24, column=c + 2, value=psd_gas[c])

            wb.save(outputname)
            print('Saved:', outputname)

    def save_data(self):
        '''call the update_plot function with option to save'''
        self.update_plot(save=True)
예제 #43
0
class PlotSignals(QMdiSubWindow):
    '''
    A widget for displaying results
    '''

    ########################
    # Initializing Methods #
    ########################
    def __init__(self, ROIs, control, parent=None):
        '''
        Initializes internal variables
        '''
        QMdiSubWindow.__init__(self, parent)
        self.setWindowTitle('Results')
        self.ROIs = ROIs
        self.sequence = control.sequence
        self.onset = control.onset
        self.control = control
        self.title = 'Results'
        self.STD = True
        self.TTEST = True

        self.createMainFrame()
        if np.any(self.ROIs[0].ROI):
            self.onDraw()

    def createMainFrame(self):
        '''
        Creates the main window
        '''
        # Widgets
        self.main_frame = QWidget()
        self.fig = Figure()
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.main_frame)
        self.axes = self.fig.add_subplot(111)
        self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)
        self.stdCB = QCheckBox("Show standard deviation")
        self.stdCB.setChecked(True)
        self.ttestCB = QCheckBox("Show significant difference")
        self.ttestCB.setChecked(True)
        titleLabel = QLabel('Set Title:')
        self.titleText = QLineEdit()
        self.titleText.setText(self.title)

        # Connections
        for roi in self.ROIs:
            roi.plotSignal.connect(self.onDraw)
        self.control.sequenceChanged.connect(self.onSequenceChanged)
        self.control.closeSignal.connect(self.close)
        self.control.exportData.connect(self.onExport)
        self.connect(self.stdCB, SIGNAL('stateChanged(int)'),
                     self.onStdChecked)
        self.connect(self.ttestCB, SIGNAL('stateChanged(int)'),
                     self.onTtestChecked)
        self.connect(self.titleText, SIGNAL('editingFinished()'),
                     self.onChangeTitle)

        # Layouts
        hbox = QHBoxLayout()
        hbox.addWidget(titleLabel)
        hbox.addWidget(self.titleText)
        vbox = QVBoxLayout()
        vbox.addWidget(self.canvas)
        vbox.addWidget(self.mpl_toolbar)
        vbox.addWidget(self.stdCB)
        vbox.addWidget(self.ttestCB)
        vbox.addLayout(hbox)

        self.main_frame.setLayout(vbox)
        self.setWidget(self.main_frame)

    #####################
    #  Internal Methods #
    #####################
    def getResults(self):
        '''
        Helper function that extracts the pixel counts from the images.
        Currently set up to calculate results from 2 ColorConfig objects.
        returns 4 nRepetitions x nFrames numpy arrays, 2 for each ROI 
        (pos and neg pixels). 
        '''
        output = []
        for roi in self.ROIs:
            maxval = len(roi.ROI[roi.ROI])
            posRange = (2, 50)
            negRange = (59, 118)
            posVal = []
            negVal = []
            for j in range(self.sequence.shape[0]):
                cpVal = []
                cnVal = []
                for i in range(self.sequence.shape[1]):
                    pmask = (self.sequence[j, i, :, :] >= posRange[0]) & (
                        self.sequence[j, i, :, :] <= posRange[1]) & roi.ROI
                    nmask = (self.sequence[j, i, :, :] >= negRange[0]) & (
                        self.sequence[j, i, :, :] <= negRange[1]) & roi.ROI
                    cpVal.append(
                        float(len(self.sequence[j, i, :, :][pmask])) / maxval)
                    cnVal.append(
                        float(len(self.sequence[j, i, :, :][nmask])) / maxval)
                posVal.append(np.array(cpVal))
                negVal.append(np.array(cnVal))
            posVal = np.array(posVal)
            negVal = np.array(negVal)
            output.append(posVal)
            output.append(negVal)
        return output

    #########
    # Slots #
    #########
    def onDraw(self):
        '''
        Draws the plot on the MPL canvas widget
        '''
        self.axes.clear()
        fs = 83.0
        step = 1.0 / fs
        xt = np.arange(0, self.sequence.shape[1] * step, step)
        xt -= xt[self.onset]

        signals = self.getResults()

        for i in range(0, len(signals), 2):
            self.axes.plot(xt[:signals[i].shape[1]],
                           (signals[i].mean(axis=0)) + (i / 2), 'r-')
            self.axes.plot(xt[:signals[i].shape[1]],
                           (signals[i + 1].mean(axis=0)) + (i / 2), 'b-')

        if self.STD:
            for i in range(0, len(signals), 2):
                self.axes.plot(xt[:signals[i].shape[1]],
                               (signals[i].mean(axis=0)) +
                               (signals[i].std(axis=0)) + (i / 2),
                               'r--',
                               alpha=0.5)
                self.axes.plot(xt[:signals[i].shape[1]],
                               (signals[i].mean(axis=0)) -
                               (signals[i].std(axis=0)) + (i / 2),
                               'r--',
                               alpha=0.5)
                self.axes.plot(xt[:signals[i].shape[1]],
                               (signals[i + 1].mean(axis=0)) +
                               (signals[i + 1].std(axis=0)) + (i / 2),
                               'b--',
                               alpha=0.5)
                self.axes.plot(xt[:signals[i].shape[1]],
                               (signals[i + 1].mean(axis=0)) -
                               (signals[i + 1].std(axis=0)) + (i / 2),
                               'b--',
                               alpha=0.5)

        if self.TTEST:
            for i in range(0, len(signals), 2):
                t1, p1 = stats.ttest_ind(signals[i], signals[i + 1], axis=0)
                collection1 = collections.BrokenBarHCollection.span_where(
                    xt,
                    ymin=(i / 2),
                    ymax=(i / 2) + 1,
                    where=p1 < 0.05,
                    facecolor='0.5',
                    alpha=0.25)
                self.axes.add_collection(collection1)

        self.axes.hlines(range((len(signals) + 2) / 2),
                         xt[0],
                         xt[signals[0].shape[1] - 1],
                         color='black')
        self.axes.vlines(xt[self.onset],
                         0, (len(signals) + 1) / 2,
                         color='black',
                         linewidth=2)
        self.axes.set_xlim(xt[0], xt[signals[0].shape[1] - 1])
        self.axes.set_yticks(list(np.arange(len(signals) / 2) + 0.5))
        labels = []
        count = 1
        for i in range((len(signals) + 1) / 2):
            labels.append('ROI %d' % count)
            count += 1
        self.axes.set_yticklabels(labels)
        self.axes.set_ylim(-0.25, (len(signals) / 2) + 0.25)
        self.axes.set_title(self.title)

        self.canvas.draw()

    def onExport(self, fname):
        '''
        Exports the values used to create the current plot (unaveraged signals)
        to a comma-separated plaintext file.
        '''
        signals = self.getResults()
        out = open(fname, 'w')
        out.write('signalName,posNeg,')
        for i in range(signals[0].shape[1]):
            out.write('v%02d,' % (i + 1))
        out.write('\n')
        count = 0
        for s in range(len(signals)):
            if s % 2 == 0:
                count += 1
            for i in range(signals[s].shape[0]):
                if s % 2 == 0:
                    name = "ROI%d_pos" % count
                else:
                    name = "ROI%d_neg" % count
                out.write('%s,%s,' % (name, name[-3:]))
                for j in range(signals[s].shape[1]):
                    out.write('%0.6f,' % signals[s][i, j])
                out.write('\n')
        out.close()

    def onSequenceChanged(self, sequence, onset):
        '''
        Catches signal from ControlPanel when sequence has changed.
        '''
        self.sequence = sequence
        self.onset = onset
        self.onDraw()

    def onStdChecked(self):
        '''
        Catches the signal from the show standard deviations check box
        '''
        self.STD = not self.STD
        self.onDraw()

    def onTtestChecked(self):
        '''
        Catches the signal from the show significant differences check box
        '''
        self.TTEST = not self.TTEST
        self.onDraw()

    def onChangeTitle(self):
        '''
        Changes the title of the plot when the user changes the text
        '''
        title = str(self.titleText.text())
        if title != self.title:
            self.title = title
            self.onDraw()
예제 #44
0
class MyForm(QMainWindow):

    # The __init__ function is what everything the user wants to be initialized when the class is called.
    # Here we shall define the tring functions to corresponding variables.
    # The 'self' variable means that the function is part of the class and can be called inside and outside the class.
    def __init__(self, parent=None):

        # Standard GUI code
        QWidget.__init__(self, parent)

        # All the GUI data and widgets in the Ui_MainWindow() class is defined to "self.ui"
        # Thus to do anything on the GUI, the commands must go through this variable
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # For the canvas.
        self.canvas_general = FigureCanvas(self.ui.mplwidget_general.figure)
        self.canvas_general.setParent(self.ui.widget_general)
        # We need the toolbar widget for the canvas
        self.mpl_toolbar_general = NavigationToolbar(self.canvas_general,
                                                     self.ui.widget_general)

        # Create the QVBoxLayout object and add the widget into the layout
        vbox_general = QVBoxLayout()
        # The matplotlib canvas
        vbox_general.addWidget(self.canvas_general)
        # The matplotlib toolbar
        vbox_general.addWidget(self.mpl_toolbar_general)
        self.ui.widget_general.setLayout(vbox_general)

        # Connect the mplwidget with canvas
        self.ui.mplwidget_general = self.canvas_general

        self.connect(self.ui.actionArray_Builder, SIGNAL('triggered()'),
                     lambda: self.ui.stackedWidget.setCurrentIndex(0))
        self.connect(self.ui.actionKeithley_Single_scan, SIGNAL('triggered()'),
                     lambda: self.ui.stackedWidget.setCurrentIndex(1))
        self.connect(self.ui.actionAgilent_Single_scan, SIGNAL('triggered()'),
                     lambda: self.ui.stackedWidget.setCurrentIndex(2))
        self.connect(self.ui.actionKeithley_Stepper_Single_Scan,
                     SIGNAL('triggered()'),
                     lambda: self.ui.stackedWidget.setCurrentIndex(3))
        self.connect(self.ui.actionKeithley_Gate_Sweep, SIGNAL('triggered()'),
                     lambda: self.ui.stackedWidget.setCurrentIndex(4))
        self.connect(self.ui.actionLockIn_Single_Scan, SIGNAL('triggered()'),
                     lambda: self.ui.stackedWidget.setCurrentIndex(5))
        self.connect(self.ui.actionResonant_Single_Scan, SIGNAL('triggered()'),
                     lambda: self.ui.stackedWidget.setCurrentIndex(6))
        self.connect(self.ui.actionSee_Visa_List, SIGNAL('triggered()'),
                     lambda: self.ui.stackedWidget.setCurrentIndex(7))

        self.List_Visas = List_Visas(main=self, ui=self.ui)
        self.Array_Builder_programs = Array_Builder(main=self, ui=self.ui)

        self.Keithley_programs = Keithley(main=self, ui=self.ui)
        self.Keithley_programs.Refresh_visa()

        self.Values = []
        self.Step = []
        self.Peak = []
        self.round = 0
        self.new_start = 0

        self.ui.lineEdit_directory_save.setText(os.getcwd())

        self.Agilent_Yokogawa_programs = Agilent_Yokogawa(main=self,
                                                          ui=self.ui)

        self.Resonant_Sweeper_functions = Resonance_Sweep(main=self,
                                                          ui=self.ui)

        self.Resonant_Sweeper_functions.update_visa()

        self.Lock_In_programs = Lock_In(main=self, ui=self.ui)

        self.KeithleyGateSweep = KeithleyGateSweep(main=self, ui=self.ui)

    # This method is to transfer the array data from the Array Builder tab to the Keithley tab
    # If the array is valid, data_available is true and execute the data transfer
    # If the array is not valid, execution cannot be done
    def CopyDataFunc(self):
        if self.Array_Builder_programs.data_available == True:
            return self.Array_Builder_programs.Values
        else:
            return None

    def copyData(self):
        try:
            if self.Array_Builder_programs.data_available:
                return self.Array_Builder_programs.Values
            self.ui.output.setText('Array has been copied and plotted.')
        except:
            return False
            self.ui.output.setText('No valid array to copy.')

    # Make sure the user is going to quit the program
    def closeEvent(self, event):
        quit_msg = "Do you want to quit the program?"
        reply = QMessageBox.question(self, "Message", quit_msg,
                                     QMessageBox.Yes, QMessageBox.No)
        if reply == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()
예제 #45
0
파일: plk.py 프로젝트: stevertaylor/qtip
class PlkWidget(QtGui.QWidget):
    """
    The plk-emulator window.

    @param parent:      Parent window
    """
    def __init__(self, parent=None, **kwargs):
        super(PlkWidget, self).__init__(parent, **kwargs)

        self.initPlk()
        self.initPlkLayout()
        self.showVisibleWidgets()

        self.psr = None
        self.parent = parent

    def initPlk(self):
        self.setMinimumSize(650, 550)

        self.plkbox = QtGui.QVBoxLayout(
        )  # plkbox contains the whole plk widget
        self.xyplotbox = QtGui.QHBoxLayout(
        )  # plkbox contains the whole plk widget
        self.fitboxesWidget = PlkFitboxesWidget(
            parent=self)  # Contains all the checkboxes
        self.actionsWidget = PlkActionsWidget(parent=self)

        # We are creating the Figure here, so set the color scheme appropriately
        self.setColorScheme(True)

        # Create the mpl Figure and FigCanvas objects.
        # 5x4 inches, 100 dots-per-inch
        #
        self.plkDpi = 100
        self.plkFig = Figure((5.0, 4.0), dpi=self.plkDpi)
        self.plkCanvas = FigureCanvas(self.plkFig)
        self.plkCanvas.setParent(self)

        # Since we have only one plot, we can use add_axes
        # instead of add_subplot, but then the subplot
        # configuration tool in the navigation toolbar wouldn't
        # work.
        #
        self.plkAxes = self.plkFig.add_subplot(111)

        # Done creating the Figure. Restore color scheme to defaults
        self.setColorScheme(False)

        # Call-back functions for clicking and key-press.
        self.plkCanvas.mpl_connect('button_press_event', self.canvasClickEvent)
        self.plkCanvas.mpl_connect('key_press_event', self.canvasKeyEvent)

        # Create the navigation toolbar, tied to the canvas
        #
        #self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)

        # Draw an empty graph
        self.drawSomething()

        # Create the XY choice widget
        self.xyChoiceWidget = PlkXYPlotWidget(parent=self)

        # At startup, all the widgets are visible
        self.xyChoiceVisible = True
        self.fitboxVisible = True
        self.actionsVisible = True
        self.layoutMode = 1  # (0 = none, 1 = all, 2 = only fitboxes, 3 = fit & action)

    def setColorScheme(self, start=True):
        """
        Set the color scheme

        @param start:   When true, save the original scheme, and set to white
                        When False, restore the original scheme
        """
        # Obtain the Widget background color
        color = self.palette().color(QtGui.QPalette.Window)
        r, g, b = color.red(), color.green(), color.blue()
        rgbcolor = (r / 255.0, g / 255.0, b / 255.0)

        if start:
            # Copy of 'white', because of bug in matplotlib that does not allow
            # deep copies of rcParams. Store values of matplotlib.rcParams
            self.orig_rcParams = copy.deepcopy(constants.mpl_rcParams_white)
            for key, value in self.orig_rcParams.iteritems():
                self.orig_rcParams[key] = matplotlib.rcParams[key]

            rcP = copy.deepcopy(constants.mpl_rcParams_white)
            rcP['axes.facecolor'] = rgbcolor
            rcP['figure.facecolor'] = rgbcolor
            rcP['figure.edgecolor'] = rgbcolor
            rcP['savefig.facecolor'] = rgbcolor
            rcP['savefig.edgecolor'] = rgbcolor

            for key, value in rcP.iteritems():
                matplotlib.rcParams[key] = value
        else:
            for key, value in constants.mpl_rcParams_black.iteritems():
                matplotlib.rcParams[key] = value

    def drawSomething(self):
        """
        When we don't have a pulsar yet, but we have to display something, just draw
        an empty figure
        """
        self.setColorScheme(True)
        self.plkAxes.clear()
        self.plkAxes.grid(True)
        self.plkAxes.set_xlabel('MJD')
        self.plkAxes.set_ylabel('Residual ($\mu$s)')
        self.plkCanvas.draw()
        self.setColorScheme(False)

    def setPulsar(self, psr):
        """
        We've got a new pulsar!
        """
        self.psr = psr

        # Update the fitting checkboxes
        self.fitboxesWidget.setPulsar(psr)
        self.xyChoiceWidget.setPulsar(psr, self.updatePlot)
        self.actionsWidget.setPulsar(psr, self.updatePlot, self.reFit)

        # Draw the residuals
        self.xyChoiceWidget.updateChoice()
        # This screws up the show/hide logistics
        #self.show()

    def reFit(self):
        """
        We need to re-do the fit for this pulsar
        """
        if not self.psr is None:
            self.psr.fit()
            self.updatePlot()

    def newFitParameters(self):
        """
        This function is called when we have new fitparameters

        TODO: callback not used right now
        """
        pass

    def initPlkLayout(self):
        """
        Initialise the basic layout of this plk emulator emulator
        """
        # Initialise the plk box
        self.plkbox.addWidget(self.fitboxesWidget)

        self.xyplotbox.addWidget(self.xyChoiceWidget)
        self.xyplotbox.addWidget(self.plkCanvas)

        self.plkbox.addLayout(self.xyplotbox)

        self.plkbox.addWidget(self.actionsWidget)
        self.setLayout(self.plkbox)

    def showVisibleWidgets(self):
        """
        Show the correct widgets in the plk Window
        """
        self.xyChoiceWidget.setVisible(self.xyChoiceVisible)
        self.fitboxesWidget.setVisible(self.fitboxVisible)
        self.actionsWidget.setVisible(self.actionsVisible)

    def updatePlot(self):
        """
        Update the plot/figure
        """
        self.setColorScheme(True)
        self.plkAxes.clear()
        self.plkAxes.grid(True)

        if self.psr is not None:
            # Get a mask for the plotting points
            msk = self.psr.mask('plot')

            #print("Mask has {0} toas".format(np.sum(msk)))

            # Get the IDs of the X and Y axis
            xid, yid = self.xyChoiceWidget.plotids()

            # Retrieve the data
            x, xerr, xlabel = self.psr.data_from_label(xid)
            y, yerr, ylabel = self.psr.data_from_label(yid)

            if x is not None and y is not None and np.sum(msk) > 0:
                xp = x[msk]
                yp = y[msk]

                if yerr is not None:
                    yerrp = yerr[msk]
                else:
                    yerrp = None

                self.plotResiduals(xp, yp, yerrp, xlabel, ylabel,
                                   self.psr.name)

                if xid in ['mjd', 'year', 'rounded MJD']:
                    self.plotPhaseJumps(self.psr.phasejumps())
            else:
                raise ValueError("Nothing to plot!")

        self.plkCanvas.draw()
        self.setColorScheme(False)

    def plotResiduals(self, x, y, yerr, xlabel, ylabel, title):
        """
        Update the plot, given all the plotting info
        """
        xave = 0.5 * (np.max(x) + np.min(x))
        xmin = xave - 1.05 * (xave - np.min(x))
        xmax = xave + 1.05 * (np.max(x) - xave)
        if yerr is None:
            yave = 0.5 * (np.max(y) + np.min(y))
            ymin = yave - 1.05 * (yave - np.min(y))
            ymax = yave + 1.05 * (np.max(y) - yave)
            self.plkAxes.scatter(x, y, marker='.', c='g')
        else:
            yave = 0.5 * (np.max(y + yerr) + np.min(y - yerr))
            ymin = yave - 1.05 * (yave - np.min(y - yerr))
            ymax = yave + 1.05 * (np.max(y + yerr) - yave)
            self.plkAxes.errorbar(x, y, yerr=yerr, fmt='.', color='green')

        self.plkAxes.axis([xmin, xmax, ymin, ymax])
        self.plkAxes.get_xaxis().get_major_formatter().set_useOffset(False)
        self.plkAxes.set_xlabel(xlabel)
        self.plkAxes.set_ylabel(ylabel)
        self.plkAxes.set_title(title)

    def plotPhaseJumps(self, phasejumps):
        """
        Plot the phase jump lines, if we have any
        """
        xmin, xmax, ymin, ymax = self.plkAxes.axis()

        if len(phasejumps) > 0:
            phasejumps = np.array(phasejumps)

            for ii in range(len(phasejumps)):
                if phasejumps[ii, 1] != 0:
                    # TODO: Add the jump size on top of the plot
                    self.plkAxes.vlines(phasejumps[ii, 0],
                                        ymin,
                                        ymax,
                                        color='darkred',
                                        linestyle='--',
                                        linewidth=0.5)

    def setFocusToCanvas(self):
        """
        Set the focus to the plk Canvas
        """
        self.plkCanvas.setFocus()

    def coord2point(self, cx, cy, which='xy'):
        """
        Given data coordinates x and y, obtain the index of the observations
        that is closest to it
        
        @param cx:      x-value of the coordinates
        @param cy:      y-value of the coordinates
        @param which:   which axis to include in distance measure [xy/x/y]
        
        @return:    Index of observation
        """
        ind = None

        if self.psr is not None:
            # Get a mask for the plotting points
            msk = self.psr.mask('plot')

            # Get the IDs of the X and Y axis
            xid, yid = self.xyChoiceWidget.plotids()

            # Retrieve the data
            x, xerr, xlabel = self.psr.data_from_label(xid)
            y, yerr, ylabel = self.psr.data_from_label(yid)

            if np.sum(msk) > 0 and x is not None and y is not None:
                # Obtain the limits
                xmin, xmax, ymin, ymax = self.plkAxes.axis()

                if which == 'xy':
                    dist = ((x[msk] - cx) /
                            (xmax - xmin))**2 + ((y[msk] - cy) /
                                                 (ymax - ymin))**2
                elif which == 'x':
                    dist = ((x[msk] - cx) / (xmax - xmin))**2
                elif which == 'y':
                    dist = ((y[msk] - cy) / (ymax - ymin))**2
                else:
                    raise ValueError(
                        "Value {0} not a valid option for coord2point".format(
                            which))

                ind = np.arange(len(x))[msk][np.argmin(dist)]

        return ind

    def keyPressEvent(self, event, **kwargs):
        """
        A key is pressed. Handle all the shortcuts here.

        This function can be called as a callback from the Canvas, or as a
        callback from Qt. So first some parsing must be done
        """

        if hasattr(event.key, '__call__'):
            ukey = event.key()
            modifiers = int(event.modifiers())
            from_canvas = False

            print(
                "WARNING: call-back key-press, canvas location not available")

            xpos, ypos = None, None
        else:
            # Modifiers are noted as: key = 'ctrl+alt+F', or 'alt+control', or
            # 'shift+g'. Do some parsing
            fkey = event.key
            from_canvas = True

            xpos, ypos = event.xdata, event.ydata

            ukey = ord(fkey[-1])
            modifiers = QtCore.Qt.NoModifier
            if 'ctrl' in fkey:
                modifiers += QtCore.Qt.ControlModifier
            if 'shift' in fkey:
                modifiers += QtCore.Qt.ShiftModifier
            if 'alt' in fkey:
                modifiers += QtCore.Qt.ShiftModifier
            if 'meta' in fkey:
                modifiers += QtCore.Qt.MetaModifier
            if 'backspace' in fkey:
                ukey = QtCore.Qt.Key_Backspace

        #if int(e.modifiers()) == (QtCore.Qt.ControlModifier+QtCore.Qt.AltModifier)

        if ukey == QtCore.Qt.Key_Escape:
            if self.parent is None:
                self.close()
            else:
                self.parent.close()
        elif (ukey == ord('M') or ukey == ord('m')) and \
                modifiers == QtCore.Qt.ControlModifier:
            # Change the window
            self.layoutMode = (1 + self.layoutMode) % 4
            if self.layoutMode == 0:
                self.xyChoiceVisible = False
                self.fitboxVisible = False
                self.actionsVisible = False
            elif self.layoutMode == 1:
                self.xyChoiceVisible = True
                self.fitboxVisible = True
                self.actionsVisible = True
            elif self.layoutMode == 2:
                self.xyChoiceVisible = False
                self.fitboxVisible = True
                self.actionsVisible = True
            elif self.layoutMode == 3:
                self.xyChoiceVisible = False
                self.fitboxVisible = True
                self.actionsVisible = False
            self.showVisibleWidgets()
        elif ukey == ord('s'):
            # Set START flag at xpos
            # TODO: propagate back to the IPython shell
            self.psr['START'].set = True
            self.psr['START'].fit = True
            self.psr['START'].val = xpos
            self.updatePlot()
        elif ukey == ord('f'):
            # Set FINISH flag as xpos
            # TODO: propagate back to the IPython shell
            self.psr['FINISH'].set = True
            self.psr['FINISH'].fit = True
            self.psr['FINISH'].val = xpos
            self.updatePlot()
        elif ukey == ord('u'):
            # Unzoom
            # TODO: propagate back to the IPython shell
            self.psr['START'].set = True
            self.psr['START'].fit = False
            self.psr['START'].val = np.min(self.psr.toas)
            self.psr['FINISH'].set = True
            self.psr['FINISH'].fit = False
            self.psr['FINISH'].val = np.max(self.psr.toas)
            self.updatePlot()
        elif ukey == ord('d'):
            # Delete data point
            # TODO: propagate back to the IPython shell
            # TODO: Fix libstempo!
            ind = self.coord2point(xpos, ypos)
            #print("Deleted:", self.psr._psr.deleted)
            # TODO: fix this hack properly in libstempo
            tempdel = self.psr.deleted
            tempdel[ind] = True
            self.psr.deleted = tempdel
            self.updatePlot()
            #print("Index deleted = ", ind)
            #print("Deleted:", self.psr.deleted[ind])
        elif ukey == ord('+') or ukey == ord('-'):
            # Add/delete a phase jump
            jump = 1
            if ukey == ord('-'):
                jump = -1

            ind = self.coord2point(xpos, ypos, which='x')
            self.psr.add_phasejump(self.psr.stoas[ind], jump)
            self.updatePlot()
        elif ukey == QtCore.Qt.Key_Backspace:
            # Remove all phase jumps
            self.psr.remove_phasejumps()
            self.updatePlot()
        elif ukey == ord('<'):
            # Add a data point to the view on the left
            # TODO: Make this more Pythonic!
            if self.psr['START'].set and self.psr['START'].fit:
                start = self.psr['START'].val
                ltmask = self.psr.stoas < start

                if np.sum(ltmask) > 2:
                    ltind = np.arange(len(self.psr.stoas))[ltmask]
                    lttoas = self.psr.stoas[ltmask]
                    max_ltind = np.argmax(lttoas)

                    # Get maximum of selected TOAs
                    ltmax = ltind[max_ltind]
                    start_max = self.psr.stoas[ltmax]

                    # Get second-highest TOA value
                    ltmask[ltmax] = False
                    ltind = np.arange(len(self.psr.stoas))[ltmask]
                    lttoas = self.psr.stoas[ltmask]
                    max_ltind = np.argmax(lttoas)
                    ltmax = ltind[max_ltind]
                    start_max2 = self.psr.stoas[ltmax]

                    # Set the new START value
                    self.psr['START'].val = 0.5 * (start_max + start_max2)
                elif np.sum(ltmask) == 2:
                    idmin = np.argmin(self.psr.stoas)
                    stmin = self.psr.stoas[idmin]
                    mask = np.ones(len(self.psr.stoas), dtype=np.bool)
                    mask[idmin] = False
                    self.psr['START'].val = 0.5 * \
                            (np.min(self.psr.stoas[mask]) + stmin)
                elif np.sum(ltmask) == 1:
                    self.psr['START'].val = np.min(self.psr.stoas) - 1
                elif np.sum(ltmask) == 0:
                    pass
                self.updatePlot()
        elif ukey == ord('>'):
            # Add a data point to the view on the left
            # TODO: Make this more Pythonic!
            if self.psr['FINISH'].set and self.psr['FINISH'].fit:
                start = self.psr['FINISH'].val
                gtmask = self.psr.stoas > start

                if np.sum(gtmask) > 2:
                    gtind = np.arange(len(self.psr.stoas))[gtmask]
                    gttoas = self.psr.stoas[gtmask]
                    min_gtind = np.argmin(gttoas)

                    # Get maximum of selected TOAs
                    gtmin = gtind[min_gtind]
                    start_min = self.psr.stoas[gtmin]

                    # Get second-highest TOA value
                    gtmask[gtmin] = False
                    gtind = np.arange(len(self.psr.stoas))[gtmask]
                    gttoas = self.psr.stoas[gtmask]
                    min_gtind = np.argmin(gttoas)
                    gtmin = gtind[min_gtind]
                    start_min2 = self.psr.stoas[gtmin]

                    # Set the new FINISH value
                    self.psr['FINISH'].val = 0.5 * (start_min + start_min2)
                elif np.sum(gtmask) == 2:
                    idmax = np.argmax(self.psr.stoas)
                    stmax = self.psr.stoas[idmax]
                    mask = np.ones(len(self.psr.stoas), dtype=np.bool)
                    mask[idmax] = False
                    self.psr['FINISH'].val = 0.5 * \
                            (np.max(self.psr.stoas[mask]) + stmax)
                elif np.sum(gtmask) == 1:
                    self.psr['FINISH'].val = np.max(self.psr.stoas) + 1
                elif np.sum(gtmask) == 0:
                    pass
                self.updatePlot()
        elif ukey == ord('x'):
            # Re-do the fit, using post-fit values of the parameters
            self.reFit()
        elif ukey == QtCore.Qt.Key_Left:
            # print("Left pressed")
            pass
        else:
            #print("Other key: {0} {1} {2} {3}".format(ukey,
            #    modifiers, ord('M'), QtCore.Qt.ControlModifier))
            pass

        #print("PlkWidget: key press: ", ukey, xpos, ypos)

        if not from_canvas:
            if self.parent is not None:
                print("Propagating key press")
                self.parent.keyPressEvent(event)

            super(PlkWidget, self).keyPressEvent(event, **kwargs)

    def canvasClickEvent(self, event):
        """
        When one clicks on the Figure/Canvas, this function is called. The
        coordinates of the click are stored in event.xdata, event.ydata
        """
        #print('Canvas click, you pressed', event.button, event.xdata, event.ydata)
        pass

    def canvasKeyEvent(self, event):
        """
        When one presses a button on the Figure/Canvas, this function is called.
        The coordinates of the click are stored in event.xdata, event.ydata
        """
        # Callback to the plkWidget
        self.keyPressEvent(event)
예제 #46
0
class MyWidget(QWidget):

    # #{ init

    def __init__(self):
        super(MyWidget, self).__init__()
        self.brd = CvBridge()
        self.view = RGB
        ui_file = os.path.join(
            rospkg.RosPack().get_path('balloon_color_picker'), 'resource',
            'ColorPlugin.ui')
        rospy.loginfo('uifile {}'.format(ui_file))
        # self.log_info('uifile {}'.format(ui_file))
        loadUi(ui_file, self)
        # Give QObjects reasonable names
        self.setObjectName('ColorPluginUi')
        self.uav_name = os.environ['UAV_NAME']

        self.orig_h = 920
        self.orig_w = 1080
        self.hist_hsv_orig_h = 180
        self.hist_hsv_orig_w = 256
        self.hist_lab_orig_h = 256
        self.hist_lab_orig_w = 256
        self.hist_status = HSV
        self.select_status = HIST_SELECTION
        self.crop_stat = IMG
        self.hist_mask = np.zeros([self.hist_hsv_orig_h, self.hist_hsv_orig_w])
        self.hist_mask_lab = np.zeros(
            [self.hist_lab_orig_h, self.hist_lab_orig_w])
        self.cur_hist_hs = None
        self.cur_hist_ab = None
        self.selected_count = 0
        # ROS services

        # #{ ros services

        self.sigma_caller = rospy.ServiceProxy('change_sigma', ChangeSigma)
        self.sigma_lab_caller = rospy.ServiceProxy('change_sigma_lab',
                                                   ChangeSigmaLab)
        self.caller = rospy.ServiceProxy('capture', Capture)
        self.capture_cropped_srv = rospy.ServiceProxy('capture_cropped',
                                                      CaptureCropped)
        self.get_count = rospy.ServiceProxy('get_count', GetCount)
        self.clear_count = rospy.ServiceProxy('clear_count', ClearCount)
        self.get_config = rospy.ServiceProxy('get_config', GetConfig)
        self.get_params = rospy.ServiceProxy('get_params', Params)
        self.freeze_service = rospy.ServiceProxy('freeze', Freeze)
        self.update_service = rospy.ServiceProxy('change_obd', UpdateObd)
        self.change_callback = rospy.ServiceProxy('change_callback',
                                                  ChangeCallback)
        self.capture_hist = rospy.ServiceProxy('capture_hist', CaptureHist)

        # #} end of ros services        rospy.wait_for_service('capture')

        rospy.loginfo(
            'waiting for service "get_params" from computation module \n if this is more than 5 secs check for topic remapping'
        )
        # self.log_info('waiting for service')
        rospy.loginfo('uav_name {}'.format(os.environ['UAV_NAME']))
        # self.log_info('uav_name {}'.format(os.environ['UAV_NAME']))
        rospy.wait_for_service('get_params')

        self.config_path, self.save_path, self.circled_param, self.circle_filter_param, self.circle_luv_param, self.object_detect_param, self.save_to_drone = self.set_params(
        )
        # SUBS
        # #{ ros subs

        self.balloon_sub = rospy.Subscriber(self.circled_param,
                                            RosImg,
                                            self.img_callback,
                                            queue_size=1)
        self.filter_sub = rospy.Subscriber(self.circle_filter_param,
                                           RosImg,
                                           self.filter_callback,
                                           queue_size=1)
        self.filter_luv = rospy.Subscriber(self.circle_luv_param,
                                           RosImg,
                                           self.luv_callback,
                                           queue_size=1)
        self.obj_det_sb = rospy.Subscriber(self.object_detect_param,
                                           RosImg,
                                           self.obj_det_callback,
                                           queue_size=1)
        # self.hsv = message_filters.Subscriber(self.circle_filter_param, RosImg)
        # self.luv = message_filters.Subscriber(self.circle_luv_param, RosImg)

        # self.ts = message_filters.ApproximateTimeSynchronizer([self.luv,  self.hsv], 1, 0.5)
        # self.ts.registerCallback(self.both_callback)

        # #} end of ros subs

        self.colors = self.load_config(self.config_path)
        self.add_buttons(self.colors)

        # # DEFAULT IMAGE
        # img = cv2.imread('/home/mrs/balloon_workspace/src/ros_packages/balloon_color_picker/data/blue.png')

        # cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

        # h,w,c = img.shape
        # q_img = QImage(img.data, w,h,3*w, QImage.Format_RGB888)

        # q = QPixmap.fromImage(q_img)

        #DIRECTORY
        #default
        self.directory.setText(self.save_path + "Red.yaml")
        self.color_name = "red"
        self.save_button.clicked.connect(self.save_config)

        #PLOT

        self.figure = Figure()
        self.figure_luv = Figure()
        self.canvas = FigureCanvas(self.figure)
        self.canvas_luv = FigureCanvas(self.figure_luv)
        self.canvas.setParent(self.inner)
        # self.toolbar = NavigationToolbar(self.canvas,self)
        # self.toolbar_luv = NavigationToolbar(self.canvas_luv,self)
        # self.toolbar.setParent(self.inner)
        # self.toolbar_luv.setParent(self.inner_luv)
        self.canvas_luv.setParent(self.inner_luv)
        self.inner_luv.hide()
        self.inner_luv_hist.hide()

        #SLIDER CONFIG

        # #{ slider config

        self.sigma_slider.setRange(0, 100)
        self.sigma_slider.setSingleStep(1)
        self.sigma_slider.setValue(6)

        self.sigma_slider.valueChanged.connect(self.slider_event)

        self.sigma_slider_s.setRange(0, 100)
        self.sigma_slider_s.setSingleStep(1)
        self.sigma_slider_s.setValue(6)

        self.sigma_slider_s.valueChanged.connect(self.slider_event)

        self.sigma_slider_v.setRange(0, 100)
        self.sigma_slider_v.setSingleStep(1)
        self.sigma_slider_v.setValue(80)

        self.sigma_slider_v.valueChanged.connect(self.slider_event)

        self.sigma_slider_lab.setRange(0, 100)
        self.sigma_slider_lab.setSingleStep(1)
        self.sigma_slider_lab.setValue(80)

        self.sigma_slider_lab.valueChanged.connect(self.slider_event_lab)

        self.sigma_slider_a.setRange(0, 100)
        self.sigma_slider_a.setSingleStep(1)
        self.sigma_slider_a.setValue(6)

        self.sigma_slider_a.valueChanged.connect(self.slider_event_lab)

        self.sigma_slider_b.setRange(0, 100)
        self.sigma_slider_b.setSingleStep(1)
        self.sigma_slider_b.setValue(6)

        self.sigma_slider_b.valueChanged.connect(self.slider_event_lab)

        # #} end of slider config

        # #{ font configs

        #SIGMA TEXT
        font = self.font()
        font.setPointSize(16)
        self.sigma_value.setFont(font)
        self.sigma_value_s.setFont(font)
        self.sigma_value_v.setFont(font)
        self.sigma_value_lab.setFont(font)
        self.sigma_value_a.setFont(font)
        self.sigma_value_b.setFont(font)
        #IMAGE COUNT TEXT
        self.image_count.setFont(font)
        #BOX FOR BUTTONS font
        # self.color_buttons.setFont(font)
        font.setPointSize(14)
        self.sigma_value.setFont(font)
        self.log_text.setFont(font)

        #LAB HSV TEXT
        font.setPointSize(23)
        self.label_lab.setFont(font)
        self.label_lab.hide()
        self.label_hsv.setFont(font)
        self.label_hsv.hide()

        # #} end of font configs

        # BUTTONS
        self.change.clicked.connect(self.switch_view_hsv)
        self.change_both.clicked.connect(self.switch_view_both)
        self.change_luv.clicked.connect(self.switch_view_luv)
        self.change_object.clicked.connect(self.switch_view_object_detect)
        self.capture_button.clicked.connect(self.capture)
        self.clear_button.clicked.connect(self.clear)
        self.freeze_button.clicked.connect(self.freeze)
        self.update_button.clicked.connect(self.update_obd)
        # self.wdg_img.setPixmap(q)
        # self.box_layout.addWidget(self.toolbar)
        # self.inner.box_layout.addWidget(self.canvas)
        #shortcuts

        self.short_capture = QShortcut(QKeySequence("C"), self)
        self.short_capture.activated.connect(self.capture)
        self.short_hsv = QShortcut(QKeySequence("1"), self)
        self.short_hsv.activated.connect(self.switch_view_hsv)
        self.short_lab = QShortcut(QKeySequence("2"), self)
        self.short_lab.activated.connect(self.switch_view_luv)
        self.short_object_detect = QShortcut(QKeySequence("3"), self)
        self.short_object_detect.activated.connect(
            self.switch_view_object_detect)
        self.short_object_detect_update = QShortcut(QKeySequence("U"), self)
        self.short_object_detect_update.activated.connect(self.update_obd)
        self.short_both = QShortcut(QKeySequence("4"), self)
        self.short_both.activated.connect(self.switch_view_both)
        self.short_save = QShortcut(QKeySequence("S"), self)
        self.short_save.activated.connect(self.save_config)
        self.short_clear = QShortcut(QKeySequence("N"), self)
        self.short_clear.activated.connect(self.clear)
        self.short_freeze = QShortcut(QKeySequence("F"), self)
        self.short_freeze.activated.connect(self.freeze)

        vbx = QVBoxLayout()
        but_hsv = QRadioButton()
        but_hsv.setText('HSV')
        but_hsv.setChecked(True)
        self.color_space = 'HSV'
        but_hsv.clicked.connect(self.set_colorspace_hsv)
        vbx.addWidget(but_hsv)
        but_lab = QRadioButton()
        but_lab.setText('LAB')
        but_lab.clicked.connect(self.set_colorspace_lab)
        vbx.addWidget(but_lab)
        vbx.addStretch(1)

        self.radio_buttons.setLayout(vbx)
        vbx_method = QVBoxLayout()
        but_lut = QRadioButton()
        but_lut.setText('LUT')
        but_lut.setChecked(False)
        but_lut.clicked.connect(self.set_method_lut)
        vbx_method.addWidget(but_lut)

        but_thr = QRadioButton()
        but_thr.setText('Threshold')
        but_thr.setChecked(True)
        but_thr.clicked.connect(self.set_method_thr)
        vbx_method.addWidget(but_thr)
        vbx.addStretch(1)

        self.radio_buttons_method.setLayout(vbx_method)

        self.load_method = 'THR'

        # self.mousePressEvent.connect(self.mousePressEvent)
        self.plotted = False

        self._rubber = None

        self.frozen = False

# #} end of init

# #{ mouse events

    def mousePressEvent(self, QMouseEvent):
        cursor = QCursor()
        x = QMouseEvent.x()
        y = QMouseEvent.y()
        if (x < 1280 and y < 720) and (x > 15 and y > 15):
            if self._rubber == None:
                if not self.frozen:
                    self.freeze()
                    self.frozen_before = False
                else:
                    self.frozen_before = True
                self.rub_origin = QMouseEvent.pos()
                self._rubber = QRubberBand(QRubberBand.Rectangle, self)
                self._rubber.show()
                self.crop_stat = IMG
        elif (x > 1300 and y > 520) and (x < 1907 and y < 1010):
            self.rub_origin = QMouseEvent.pos()
            self._rubber = QRubberBand(QRubberBand.Rectangle, self)
            self._rubber.show()
            if QMouseEvent.button(
            ) == Qt.RightButton and self.selected_count != 0:
                self.select_status = HIST_DESELECTION
            else:
                self.select_status = HIST_SELECTION
            self.crop_stat = HIST
            self.log_info("hist status {}".format("HSV" if self.hist_status ==
                                                  HSV else "LAB"))

    def mouseMoveEvent(self, QMouseEvent):
        cursor = QCursor()
        x = QMouseEvent.x()
        y = QMouseEvent.y()
        # if in coords of image and crop status is image then draw the rect
        if self._rubber is None:
            return
        if (x < 1280 and y < 720) and (x > 15
                                       and y > 15) and self.crop_stat == IMG:
            self._rubber.setGeometry(
                QRect(self.rub_origin, QMouseEvent.pos()).normalized())
        # if in coords of hist and crop status is hist then draw the rect
        elif (x > 1300 and y > 520) and (x < 1907 and
                                         y < 1010) and self.crop_stat == HIST:
            self._rubber.setGeometry(
                QRect(self.rub_origin, QMouseEvent.pos()).normalized())

    def mouseReleaseEvent(self, QMouseEvent):
        cursor = QCursor()
        x = QMouseEvent.x()
        y = QMouseEvent.y()
        if self._rubber is None:
            return
        if (x < 1280 and y < 720) and (x > 15
                                       and y > 15) and self.crop_stat == IMG:

            if not self.frozen_before:
                self.freeze()

            a = self.mapToGlobal(self.rub_origin)
            b = QMouseEvent.globalPos()
            a = self.wdg_img.mapFromGlobal(a)
            b = self.wdg_img.mapFromGlobal(b)

            self._rubber.hide()
            self._rubber = None

            pix = QPixmap(self.wdg_img.pixmap())
            sx = float(self.wdg_img.rect().width())
            sy = float(self.wdg_img.rect().height())

            # h 1080 w 1920
            sx = self.orig_w / sx
            sy = self.orig_h / sy

            a.setX(int(a.x() * sx))
            a.setY(int(a.y() * sy))

            b.setX(int(b.x() * sx))
            b.setY(int(b.y() * sy))
            rect_ = QRect(a, b)

            h_ = rect_.height()
            w_ = rect_.width()

            y1, x1, y2, x2 = rect_.getCoords()
            rospy.loginfo('Img cropped x1 {} y1 {} x2 {} y2{}'.format(
                x1, y1, x2, y2))
            self.log_info('Img cropped x1 {} y1 {} x2 {} y2{}'.format(
                x1, y1, x2, y2))
            self.capture_cropped(x1, y1, x2, y2)
        elif (x > 1300 and y > 520) and (x < 1907 and
                                         y < 1010) and self.crop_stat == HIST:

            # h 1080 w 1920

            if self.hist_status == HSV:
                cur_hist = self.inner_hist
            elif self.hist_status == LUV:
                cur_hist = self.inner_luv_hist

        # if not self.frozen_before:
        #     self.freeze()
            a = self.mapToGlobal(self.rub_origin)
            b = QMouseEvent.globalPos()
            a = cur_hist.mapFromGlobal(a)
            b = cur_hist.mapFromGlobal(b)

            self._rubber.hide()
            self._rubber = None

            pix = QPixmap(cur_hist.pixmap())
            sx = float(cur_hist.rect().width())
            sy = float(cur_hist.rect().height())

            # h 1080 w 1920
            if self.hist_status == HSV:
                sx = self.hist_hsv_orig_w / sx
                sy = self.hist_hsv_orig_h / sy
            elif self.hist_status == LUV:
                sx = self.hist_lab_orig_w / sx
                sy = self.hist_lab_orig_h / sy

            a.setX(int(a.x() * sx))
            a.setY(int(a.y() * sy))

            b.setX(int(b.x() * sx))
            b.setY(int(b.y() * sy))
            rect_ = QRect(a, b)

            h_ = rect_.height()
            w_ = rect_.width()

            # y1,x1,y2,x2 = rect_.getCoords()
            x1, y1, x2, y2 = rect_.getCoords()
            rospy.loginfo('Hist cropped x1 {} y1 {} x2 {} y2 {}'.format(
                x1, y1, x2, y2))
            self.log_info('Hist cropped x1 {} y1 {} x2 {} y2 {}'.format(
                x1, y1, x2, y2))
            if self.select_status == HIST_SELECTION:
                self.select_hist(x1, y1, x2, y2, h_, w_, self.hist_status)
            elif self.select_status == HIST_DESELECTION:
                self.deselect_hist(x1, y1, x2, y2, self.hist_status)

        else:
            if self._rubber is not None:
                self._rubber.hide()
                self._rubber = None
                self.crop_stat = 0

# #} end of mouse events

# #{ set_colorspaces

    def set_colorspace_hsv(self):
        self.color_space = 'HSV'
        self.inner.show()
        self.inner_hist.show()
        self.hist_status = HSV
        self.log_info("hist status {}".format("HSV"))
        self.inner_luv.hide()
        self.inner_luv_hist.hide()
        if self.view == HSV:
            self.view = RGB
            self.set_view(self.view)
            return
        self.view = HSV
        self.log_info('HSV from radio button')
        self.set_view(self.view)

    def set_colorspace_lab(self):
        self.color_space = 'LAB'
        # but_lab.setChecked(True)
        self.inner_luv.show()
        self.inner_luv_hist.show()
        self.inner.hide()
        self.inner_hist.hide()
        self.hist_status = LUV
        self.log_info("hist status {}".format("LAB"))
        if self.view == LUV:
            self.view = RGB
            self.set_view(self.view)
            return
        rospy.loginfo('LAB from radio button')
        self.log_info('LAB from radio button')
        self.view = LUV
        self.set_view(self.view)

    def set_method_lut(self):
        self.load_method = 'LUT'
        self.log_info('Set method LUT')

    def set_method_thr(self):
        self.load_method = 'THR'
        self.log_info('Set method THR')

# #} end of set_colorspaces

# #{ plot

    def plot(self, h, s, v, l, u, lv, means, sigmas):
        self.mean_h, self.mean_s, self.mean_v, self.mean_l, self.mean_u, self.mean_lv = means
        self.std_h, self.std_s, self.std_v, self.std_l, self.std_u, self.std_lv = sigmas

        self.figure.suptitle('HSV', fontsize=20)
        ax = self.figure.add_subplot(221)
        ax.clear()
        ax.hist(h, normed=True)
        ax.set_title('H', fontsize=16)
        ax.set_xlim([0, 180])
        xmin, xmax = (0, 180)
        x = np.linspace(xmin, xmax, 180)
        y = norm.pdf(x, self.mean_h, self.std_h)
        ax.plot(x, y)
        #thresholds
        val = float(self.sigma_slider.value()) / 2

        ax.axvline(self.mean_h + self.std_h * val, color='r')
        ax.axvline(self.mean_h - self.std_h * val, color='g')

        sx = self.figure.add_subplot(222)
        sx.clear()
        sx.hist(s, normed=True)
        sx.set_title('S', fontsize=16)
        amin, xmax = (0, 255)
        sx.set_xlim([0, 255])
        x = np.linspace(xmin, xmax, 255)
        y = norm.pdf(x, self.mean_s, self.std_s)
        sx.plot(x, y)

        #thresholds
        val = float(self.sigma_slider_s.value()) / 2

        sx.axvline(self.mean_s + self.std_s * val, color='r')
        sx.axvline(self.mean_s - self.std_s * val, color='g')

        vx = self.figure.add_subplot(223)
        vx.clear()
        vx.hist(v, normed=True)
        vx.set_title('V', fontsize=16)
        xmin, xmax = (0, 255)
        vx.set_xlim([0, 255])
        # vx.set_ylim([0,max(v)])
        x = np.linspace(xmin, xmax, 255)
        y = norm.pdf(x, self.mean_v, self.std_v)
        vx.plot(x, y)

        #thresholds
        val = float(self.sigma_slider_v.value()) / 2

        vx.axvline(self.mean_v + self.std_v * val, color='r', ymax=1)
        vx.axvline(self.mean_v - self.std_v * val, color='g', ymax=1)

        # refresh canvas
        self.canvas.draw()

        self.figure_luv.suptitle('LAB', fontsize=20)
        ax = self.figure_luv.add_subplot(221)
        ax.clear()
        ax.set_title('L', fontsize=16)
        ax.hist(l, normed=True)
        xmin, xmax = (0, 255)
        ax.set_xlim([0, 255])
        x = np.linspace(xmin, xmax, 225)
        y = norm.pdf(x, self.mean_l, self.std_l)
        ax.plot(x, y)
        #thresholds
        val = float(self.sigma_slider_lab.value()) / 2

        ax.axvline(self.mean_l + self.std_l * val, color='r')
        ax.axvline(self.mean_l - self.std_l * val, color='g')

        sx = self.figure_luv.add_subplot(222)
        sx.clear()
        sx.set_title('A', fontsize=16)
        sx.hist(u, normed=True)
        xmin, xmax = (0, 256)
        x = np.linspace(xmin, xmax, 256)
        sx.set_xlim([0, 256])
        y = norm.pdf(x, self.mean_u, self.std_u)
        sx.plot(x, y)
        #thresholds
        val = float(self.sigma_slider_a.value()) / 2

        sx.axvline(self.mean_u + self.std_u * val, color='r')
        sx.axvline(self.mean_u - self.std_u * val, color='g')

        vx = self.figure_luv.add_subplot(223)
        vx.clear()
        vx.set_title('B', fontsize=16)
        vx.hist(lv, normed=True)
        xmin, xmax = (0, 223)
        vx.set_xlim([0, 223])
        x = np.linspace(xmin, xmax, 223)
        y = norm.pdf(x, self.mean_lv, self.std_lv)
        vx.plot(x, y)

        #thresholds
        val = float(self.sigma_slider_b.value()) / 2

        vx.axvline(self.mean_lv + self.std_lv * val, color='r')
        vx.axvline(self.mean_lv - self.std_lv * val, color='g')

        # refresh canvas
        self.canvas_luv.draw()
        self.plotted = True

# #} end of plot

# #{ update_plots

    def update_plots(self):
        ax = self.figure.get_axes()[0]
        sx = self.figure.get_axes()[1]
        vx = self.figure.get_axes()[2]
        # print(ax.lines)

        #thresholds
        del ax.lines[len(ax.lines) - 1]
        del ax.lines[len(ax.lines) - 1]

        up = self.mean_h + self.std_h * self.sigma_h
        if up > 180:
            up -= 180
        down = self.mean_h - self.std_h * self.sigma_h
        if down < 0:
            down += 180
        ax.axvline(up, color='r')
        ax.axvline(down, color='g')

        #thresholds

        del sx.lines[len(sx.lines) - 1]
        del sx.lines[len(sx.lines) - 1]
        sx.axvline(self.mean_s + self.std_s * self.sigma_s, color='r')
        sx.axvline(self.mean_s - self.std_s * self.sigma_s, color='g')

        #thresholds

        del vx.lines[len(vx.lines) - 1]
        del vx.lines[len(vx.lines) - 1]
        vx.axvline(self.mean_v + self.std_v * self.sigma_v, color='r', ymax=1)
        vx.axvline(self.mean_v - self.std_v * self.sigma_v, color='g', ymax=1)

        self.canvas.draw()

# #} end of update_plots

# #{ update_plots_lab

    def update_plots_lab(self):
        # refresh canvas
        ax = self.figure_luv.get_axes()[0]
        sx = self.figure_luv.get_axes()[1]
        vx = self.figure_luv.get_axes()[2]
        # print(ax.lines)
        #thresholds
        del ax.lines[len(ax.lines) - 1]
        del ax.lines[len(ax.lines) - 1]

        ax.axvline(self.mean_l + self.std_l * self.sigma_l, color='r')
        ax.axvline(self.mean_l - self.std_l * self.sigma_l, color='g')

        #thresholds
        del sx.lines[len(sx.lines) - 1]
        del sx.lines[len(sx.lines) - 1]

        sx.axvline(self.mean_u + self.std_u * self.sigma_a, color='r')
        sx.axvline(self.mean_u - self.std_u * self.sigma_a, color='g')

        #thresholds
        del vx.lines[len(vx.lines) - 1]
        del vx.lines[len(vx.lines) - 1]

        vx.axvline(self.mean_lv + self.std_lv * self.sigma_b, color='r')
        vx.axvline(self.mean_lv - self.std_lv * self.sigma_b, color='g')

        # refresh canvas
        self.canvas_luv.draw()

# #} end of update_plots_lab

# #{ img_callback

    def img_callback(self, data):
        if self.view != RGB:
            return
        img = self.brd.imgmsg_to_cv2(data, 'rgb8')
        h, w, c = img.shape
        self.orig_h = h
        self.orig_w = w
        # rospy.loginfo('h {} w {}'.format(h,w))
        # cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

        img = cv2.resize(img, dsize=(1280, 720), interpolation=cv2.INTER_CUBIC)
        h, w, c = img.shape
        q_img = QImage(img.data, w, h, 3 * w, QImage.Format_RGB888)

        q = QPixmap.fromImage(q_img)
        self.wdg_img.setFixedWidth(1280)
        self.wdg_img.setFixedHeight(720)
        self.wdg_img.setPixmap(q)

# #} end of img_callback

# #{ clear

    def clear(self):
        self.figure.clf()
        self.clear_count()
        self.image_count.setText('Samples: 0 ')
        print("cleared")
        self.log_info("cleared")

# #} end of clear

# #{ filter callback

    def filter_callback(self, data):
        if self.view != HSV:
            return
        img = self.brd.imgmsg_to_cv2(data, 'rgb8')
        # cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

        img = cv2.resize(img, dsize=(1280, 720), interpolation=cv2.INTER_CUBIC)
        h, w, c = img.shape

        q_img = QImage(img.data, w, h, 3 * w, QImage.Format_RGB888)

        q = QPixmap.fromImage(q_img)

        self.wdg_img.setFixedWidth(1280)
        self.wdg_img.setFixedHeight(720)
        self.wdg_img.setPixmap(q)

# #} end of filter callback

# #{ luv_callback

    def luv_callback(self, data):
        if self.view != LUV:
            return
        img = self.brd.imgmsg_to_cv2(data, 'rgb8')
        # cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

        img = cv2.resize(img, dsize=(1280, 720), interpolation=cv2.INTER_CUBIC)
        h, w, c = img.shape
        # rospy.loginfo('shape {}'.format(img.shape))

        q_img = QImage(img.data, w, h, 3 * w, QImage.Format_RGB888)

        q = QPixmap.fromImage(q_img)
        # self.wdg_img.setFixedWidth(w)
        # self.wdg_img.setFixedHeight(h)

        self.wdg_img.setPixmap(q)

# #} end of luv_callback

# #{ object_detect_callback

    def obj_det_callback(self, data):
        if self.view != OBD:
            return
        if self.frozen:
            return
        img = self.brd.imgmsg_to_cv2(data, 'rgb8')
        # cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

        img = cv2.resize(img, dsize=(1280, 720), interpolation=cv2.INTER_CUBIC)
        h, w, c = img.shape
        q_img = QImage(img.data, w, h, 3 * w, QImage.Format_RGB888)

        q = QPixmap.fromImage(q_img)
        self.wdg_img.setFixedWidth(w)
        self.wdg_img.setFixedHeight(h)
        self.wdg_img.setPixmap(q)

# #} end of luv_callback

# #{ both_callback

    def both_callback(self, luv, hsv):
        if self.view != BOTH:
            self.label_hsv.hide()
            self.label_lab.hide()
            return
        img_luv = self.brd.imgmsg_to_cv2(luv)
        img_hsv = self.brd.imgmsg_to_cv2(hsv)
        # cv2.cvtColor(img_luv, cv2.COLOR_BGR2RGB)
        # cv2.cvtColor(img_hsv, cv2.COLOR_BGR2RGB)

        h, w, c = img_luv.shape
        img = np.zeros([h, w, c])
        luv_2 = cv2.resize(img_luv, (0, 0), fx=0.5, fy=0.5)
        hsv_2 = cv2.resize(img_hsv, (0, 0), fx=0.5, fy=0.5)
        both = np.hstack((hsv_2, luv_2))
        dif = (img.shape[0] - both.shape[0]) // 2
        img[dif:img.shape[0] - dif, 0:img.shape[1]] = both
        q_img = QImage(both.data, both.shape[1], both.shape[0],
                       3 * both.shape[1], QImage.Format_RGB888)

        q = QPixmap.fromImage(q_img)
        self.wdg_img.setFixedWidth(both.shape[1])
        self.wdg_img.setFixedHeight(both.shape[0])
        self.wdg_img.setPixmap(q)

# #} end of both_callback

# #{ slider_event_hsv

    def slider_event(self):

        self.sigma_h = float(self.sigma_slider.value()) / 2
        self.sigma_s = float(self.sigma_slider_s.value()) / 2
        self.sigma_v = float(self.sigma_slider_v.value()) / 2
        res = self.sigma_caller(self.sigma_h, self.sigma_s, self.sigma_v)

        if len(self.figure.get_axes()) > 0:
            rospy.loginfo('axes {}'.format(self.figure.get_axes()))
            self.log_info('axes {}'.format(self.figure.get_axes()))
            self.update_plots()

        self.sigma_value.setText('Sigma H value: {}'.format(self.sigma_h))
        self.sigma_value_s.setText('Sigma S value: {}'.format(self.sigma_s))
        self.sigma_value_v.setText('Sigma V value: {}'.format(self.sigma_v))

# #} end of slider_event_hsv

# #{ slider_event_lab

    def slider_event_lab(self):

        self.sigma_l = float(self.sigma_slider_lab.value()) / 2
        self.sigma_a = float(self.sigma_slider_a.value()) / 2
        self.sigma_b = float(self.sigma_slider_b.value()) / 2
        if len(self.figure_luv.get_axes()) > 0:
            self.update_plots_lab()
        # rospy.loginfo('value {}'.format(self.sigma_l))
        # self.log_info('value {}'.format(self.sigma_l))
        self.sigma_lab_caller(self.sigma_l, self.sigma_a, self.sigma_b)
        self.sigma_value_lab.setText('Sigma L value: {}'.format(self.sigma_l))
        self.sigma_value_a.setText('Sigma A value: {}'.format(self.sigma_a))
        self.sigma_value_b.setText('Sigma B value: {}'.format(self.sigma_b))

# #} end of slider_event_lab

# #{ capture

    def capture(self):

        rospy.wait_for_service('capture')
        req = Capture()
        res = self.caller()
        # rospy.loginfo('response {}'.format(res))
        # self.log_info('response {}'.format(res))
        self.plot(res.h, res.s, res.v, res.l, res.u, res.lv, res.means,
                  res.sigmas)
        self.image_count.setText('Samples taken: {} '.format(res.count))
        return

# #} end of capture

# #{ capture_cropped

    def capture_cropped(self, x1, y1, x2, y2):
        t = time.time()

        res = self.capture_cropped_srv(x1, y1, x2, y2)
        rospy.loginfo('time for capture cropped {}'.format(time.time() - t))

        t = time.time()
        hist = self.capture_hist(x1, y1, x2, y2)

        self.set_hist(hist)
        rospy.loginfo('time for hist cropped {}'.format(time.time() - t))
        if res.success == False:
            rospy.loginfo('capture cropped returned false, NaNs are possible')
            return

        # rospy.loginfo('response {}'.format(res))

        t = time.time()
        self.plot(res.h, res.s, res.v, res.l, res.u, res.lv, res.means,
                  res.sigmas)

        rospy.loginfo('time for plot {}'.format(time.time() - t))
        self.image_count.setText('Samples: {} '.format(res.count))

# #} end of capture_cropped

# #{ switch_view_hsv

    def switch_view_hsv(self):
        if self.view == HSV:
            self.view = RGB
            self.set_view(self.view)
            return
        print("HSV")
        self.log_info("HSV")
        self.hist_status = HSV
        self.view = HSV
        # rospy.loginfo('HSV from radio button {}'.format(self.radio_buttons.buttonClicked()))
        self.set_view(self.view)
        self.inner.show()
        self.inner_hist.show()
        self.inner_luv.hide()
        self.inner_luv_hist.hide()

# #} end of switch_view_hsv

# #{ switch_view_luv

    def switch_view_luv(self):
        if self.view == LUV:
            self.view = RGB
            self.set_view(self.view)
            return
        print("LUV")
        self.hist_status = LUV
        self.log_info("LUV")
        self.view = LUV
        self.set_view(self.view)
        self.inner_luv.show()
        self.inner_luv_hist.show()
        self.inner.hide()
        self.inner_hist.hide()

# #} end of switch_view_luv

# #{ update object detect colors

    def update_obd(self):
        rospy.loginfo('Sending data to Object Detect:{}'.format(
            self.load_method))
        self.log_info('Sending data to Object Detect:{}'.format(
            self.load_method))
        ball_rad = String()
        ball_rad.data = self.ball_radius.text()
        if self.hist_status == HSV:
            hist = np.transpose(self.hist_mask).flatten().astype('uint8')
            shape = self.hist_mask.shape
        elif self.hist_status == LUV:
            hist = np.transpose(self.hist_mask_lab).flatten().astype('uint8')
            shape = self.hist_mask_lab.shape

        if self.ball_radius.text() == "":
            return
        method = String()
        method.data = self.load_method

        color = String()
        if self.load_method == 'LUT':
            rospy.loginfo('load method YES {}'.format(self.load_method))
            rospy.loginfo('color space {}'.format(self.color_space))
            if self.color_space == 'HSV':
                color.data = 'hs_lut'
            elif self.color_space == 'LAB':
                rospy.loginfo('Color space {}'.format(self.color_space))
                color.data = 'ab_lut'
        else:
            rospy.loginfo('load method is {}'.format(self.load_method))
            color.data = self.color_space
        rospy.loginfo('color {}'.format(color))

        try:
            rospy.loginfo('updating object detect {}'.format(
                self.update_service.call(color, ball_rad, method, hist,
                                         shape)))
            self.log_info('updating object detect {}'.format("OBD updated"))
        except:
            rospy.loginfo("Couldn't update the object detect")
            self.log_info("Couldn't update the object detect")

        if self.frozen:
            self.freeze()

# #} end of update object detect colors

# #{ switch_view_both

    def switch_view_both(self):
        if self.view == BOTH:
            self.view = RGB
            self.set_view(self.view)
            return
        print("BOTH")
        self.log_info("BOTH")
        self.view = BOTH
        self.set_view(self.view)

        self.label_hsv.show()
        self.label_lab.show()

# #} end of switch_view_both

# #{ switch_view_object_detect

    def switch_view_object_detect(self):
        if self.view == OBD:
            self.view = RGB
            return
        print("OBD")
        self.log_info("OBD")
        self.view = OBD

# #} end of switch_view_both

# #{ load_config

    def load_config(self, path):
        # rospy.loginfo('cur dir {}'.format(os.path.curdir))
        # path = os.path.join(os.path.curdir,'../../config/balloon_config.yaml')
        # f = file(path,'r')
        # print(path)
        # res = yaml.safe_load(f)
        # TODO: change to reading from a file
        colors = ['Red', 'Green', 'Blue', 'Yellow']
        return colors

# #} end of load_config

# #{ clicked

    def clicked(self, color):
        def clicker():
            self.color_name = color
            self.directory.setText(self.save_path + '/{}.yaml'.format(color))

        return clicker

# #} end of clicked

# #{ add_buttons

    def add_buttons(self, colors):
        vbx = QVBoxLayout()
        i = 1
        for color in colors:

            but = QPushButton('Color {} ({})'.format(color, i))
            but.clicked.connect(self.clicked(color))

            but_short = QShortcut(QKeySequence("Ctrl+" + str(i)), self)
            but_short.activated.connect(self.clicked(color))
            i += 1
            vbx.addWidget(but)

        vbx.addStretch(1)
        self.color_buttons.setLayout(vbx)

# #} end of add_buttons

# #{ freeze

    def freeze(self):
        self.freeze_service.call()
        if self.frozen:
            self.frozen = False
        else:
            self.frozen = True
        rospy.loginfo('Frozen {}'.format(self.frozen))
        self.log_info('Frozen {}'.format(self.frozen))
        return

# #} end of freeze

# #{ save_config

    def save_config(self):
        color = String()
        color.data = self.color_space
        save_dir = String()
        save_dir.data = self.directory.text()
        ball_rad = String()
        if self.ball_radius.text() == "":
            return
        if os.path.isdir(self.directory.text()):
            return
        ball_rad.data = self.ball_radius.text()
        color_name = String()
        rospy.loginfo('Saving with load method {}'.format(self.load_method))
        hist = None
        hist_shape = None
        if self.load_method == 'LUT':
            self.log_info('Saving lut type with color space : {}'.format(
                self.color_space))
            if self.color_space == 'HSV':
                rospy.loginfo('hs_lut')
                color.data = 'hs_lut'
                hist_shape = self.hist_mask.shape
                hist = np.transpose(self.hist_mask).flatten().astype('uint8')
            elif self.color_space == 'LAB':
                rospy.loginfo('ab_lut')
                color.data = 'ab_lut'
                hist = np.transpose(
                    self.hist_mask_lab).flatten().astype('uint8')
                hist_shape = self.hist_mask_lab.shape
        else:
            color_name.data = self.color_name
        rospy.loginfo('color space to SAVE {}'.format(color_name))

        resp = self.get_config(color, save_dir, ball_rad, color_name, hist,
                               hist_shape)

        #conf_obj = {}
        ##HSV
        #hsv = {}
        ## hsv['hist_bins_h'] = resp.hsv[0].bins
        ## hsv['hist_hist_h'] = resp.hsv[0].values
        ## hsv['hist_bins_s'] = resp.hsv[1].bins
        ## hsv['hist_hist_s'] = resp.hsv[1].values
        ## hsv['hist_bins_v'] = resp.hsv[2].bins
        ## hsv['hist_hist_v'] = resp.hsv[2].values
        ## hsv['hsv_roi'] = resp.hsv_roi
        #hsv['hue_center'] = resp.h[0]
        #hsv['hue_range'] = resp.h[1]
        #hsv['sat_center'] = resp.s[0]
        #hsv['sat_range'] = resp.s[1]
        #hsv['val_center'] = resp.v[0]
        #hsv['val_range'] = resp.v[1]
        #conf_obj['hsv'] = hsv
        ##LAB
        #lab = {}
        #lab['l_center'] = resp.l[0]
        #lab['l_range'] = resp.l[1]
        #lab['a_center'] = resp.a[0]
        #lab['a_range'] = resp.a[1]
        #lab['b_center'] = resp.b[0]
        #lab['b_range'] = resp.b[1]
        ## lab['hist_bins_l'] = resp.lab[0].bins
        ## lab['hist_hist_l'] = resp.lab[0].values
        ## lab['hist_bins_a'] = resp.lab[1].bins
        ## lab['hist_hist_a'] = resp.lab[1].values
        ## lab['hist_bins_b'] = resp.lab[2].bins
        ## lab['hist_hist_b'] = resp.lab[2].values
        ## lab['lab_roi'] = resp.lab_roi
        #conf_obj['lab'] = lab

        #conf_obj['binarization_method'] = self.color_space
        #if os.path.isdir(save_dir):
        #    return
        #f = file(save_dir,'w')
        #print('saved to dir {}'.format(save_dir))
        #yaml.safe_dump(conf_obj,f)

        #if self.save_to_drone:
        #    path_to_script = os.path.join(rospkg.RosPack().get_path('balloon_color_picker'), 'scripts', 'copy_to_uav.sh')
        #    print(path_to_script)
        #    print('exectuted command ')
        #    print(save_dir)
        #    print(subprocess.check_call([path_to_script,os.environ['UAV_NAME'], save_dir, name+'.yaml']))

# #} end of save_config

# #{ set_params

    def set_params(self):

        resp = self.get_params()
        print(resp)
        print('params loaded')
        return resp.config_path, resp.save_path, resp.circled, resp.circle_filter, resp.circle_luv, resp.object_detect, resp.save_to_drone

# #} end of set_params

# #{ set_view

    def set_view(self, view):
        self.change_callback(view)

# #} end of set_view

# #{ set_hist

    def set_hist(self, hist_resp):
        hist = np.array(hist_resp.hist_hsv)
        hist = np.reshape(hist, hist_resp.shape_hsv)
        self.selected_count = 0

        self.hist_hsv_orig_h = hist_resp.shape_hsv[0]
        self.hist_hsv_orig_w = hist_resp.shape_hsv[1]
        self.cur_hist_hs = hist
        # self.hist_mask = np.zeros(self.cur_hist_hs.shape)

        hist = np.array(hist_resp.hist_lab)
        hist = np.reshape(hist, hist_resp.shape_lab)

        self.hist_lab_orig_h = hist_resp.shape_lab[0]
        self.hist_lab_orig_w = hist_resp.shape_lab[1]
        self.cur_hist_ab = hist

        self.redraw(HSV)
        self.redraw(LUV)

# #} end of set_hist

# #{ draw_hist

    def draw_hist(self, histRGB):

        # histRGB = np.log2(histRGB)
        new_h = cv2.resize(histRGB.astype('uint8'),
                           dsize=(512, 360),
                           interpolation=cv2.INTER_CUBIC)
        # new_h = histRGB.copy().astype('uint8')

        # cv2.imshow("to draw", new_h)
        # cv2.waitKey(1)
        rospy.loginfo('new_h shape {}'.format(new_h.shape))

        h, w, c = new_h.shape
        total = new_h.nbytes
        perLine = int(total / h)
        if c == 3:
            q_img = QImage(new_h.data, w, h, perLine, QImage.Format_RGB888)
        elif c == 4:
            q_img = QImage(new_h.data, w, h, perLine, QImage.Format_RGBA8888)

        q = QPixmap.fromImage(q_img)
        self.inner_hist.setFixedWidth(512)
        self.inner_hist.setFixedHeight(360)
        self.inner_hist.setPixmap(q)

# #} end of draw_hist

# #{ draw_hist_lab

    def draw_hist_lab(self, histRGB):

        # histRGB = np.log2(histRGB)
        new_h = cv2.resize(histRGB.astype('uint8'),
                           dsize=(400, 400),
                           interpolation=cv2.INTER_CUBIC)
        # new_h = histRGB.copy().astype('uint8')

        # cv2.imshow("to draw", new_h)
        # cv2.waitKey(1)
        rospy.loginfo('new_h shape {}'.format(new_h.shape))

        h, w, c = new_h.shape
        total = new_h.nbytes
        perLine = int(total / h)
        if c == 3:
            q_img = QImage(new_h.data, w, h, perLine, QImage.Format_RGB888)
        elif c == 4:
            q_img = QImage(new_h.data, w, h, perLine, QImage.Format_RGBA8888)

        q = QPixmap.fromImage(q_img)
        self.inner_luv_hist.setFixedWidth(400)
        self.inner_luv_hist.setFixedHeight(400)
        self.inner_luv_hist.setPixmap(q)

# #} end of draw_hist

# #{ select_hist

    def select_hist(self, x1, y1, x2, y2, h, w, color_space):
        rospy.loginfo('select status {}'.format(self.select_status))
        self.selected_count += 1
        if color_space == HSV:
            cv2.rectangle(self.hist_mask, (x1, y1), (x2, y2), (1), -1)
        elif color_space == LUV:
            cv2.rectangle(self.hist_mask_lab, (x1, y1), (x2, y2), (1), -1)
        self.redraw(color_space)

    def redraw(self, color_space):
        if color_space == HSV:
            if self.cur_hist_hs is None:
                return
            hist = self.cur_hist_hs.copy()
        elif color_space == LUV:
            if self.cur_hist_ab is None:
                return
            hist = self.cur_hist_ab.copy()

        #normalizing the histogram
        minVal, maxVal, l, m = cv2.minMaxLoc(hist)
        hist = (hist - minVal) / (maxVal - minVal) * 255.0

        rospy.loginfo('hist shape {}'.format(hist.shape))

        hist = cv2.equalizeHist(hist.astype('uint8'))
        histRGB = cv2.cvtColor(hist.astype('uint8'), cv2.COLOR_GRAY2RGB)

        if color_space == HSV:
            maskRGB = cv2.cvtColor(self.hist_mask.astype('uint8'),
                                   cv2.COLOR_GRAY2RGB)

            maskRGB[self.hist_mask > 0, :] = np.array([255, 0, 0])
        elif color_space == LUV:
            maskRGB = cv2.cvtColor(self.hist_mask_lab.astype('uint8'),
                                   cv2.COLOR_GRAY2RGB)
            maskRGB[self.hist_mask_lab > 0, :] = np.array([255, 0, 0])

        alpha = 0.3
        selected_hist = alpha * maskRGB + (1.0 - alpha) * histRGB
        rospy.loginfo('to draw shape {}'.format(selected_hist.shape))

        if color_space == HSV:
            self.draw_hist(selected_hist)
        elif color_space == LUV:
            self.draw_hist_lab(selected_hist)

# #} end of select_hist

# #{ deselect_hist

    def deselect_hist(self, x1, y1, x2, y2, color_space):
        rospy.loginfo('deselect')
        self.log_info('deselect')
        if self.selected_count == 0:
            rospy.loginfo('nothing is selected, can"t deselect')
            self.log_info('nothing is selected, can"t deselect')
            return
        if color_space == HSV:
            cv2.rectangle(self.hist_mask, (x1, y1), (x2, y2), (0),
                          -1)  # A filled rectangle
        elif color_space == LUV:
            cv2.rectangle(self.hist_mask_lab, (x1, y1), (x2, y2), (0),
                          -1)  # A filled rectangle
        self.redraw(color_space)

# #} end of deselect_hist

# #{ get_mask

    def get_mask(self, arr, x1, y1, x2, y2):
        mask = np.zeros([arr.shape[0], arr.shape[1]])
        if x1 > x2:
            if y1 > y2:
                mask[x2:x1, y2:y1] = 1
            elif y1 < y2:
                mask[x2:x1, y1:y2] = 1
        elif x1 < x2:
            if y1 > y2:
                mask[x1:x2, y2:y1] = 1
            elif y1 < y2:
                mask[x1:x2, y1:y2] = 1

        return mask

# #} end of get_mask

# #{ keyPressEvent

    def keyPressEvent(self, event):
        pass

# #} end of keyPressEvent

# #{ default todo's

    def shutdown_plugin(self):
        # TODO unregister all publishers here
        pass

    def save_settings(self, plugin_settings, instance_settings):
        # TODO save intrinsic configuration, usually using:
        # instance_settings.set_value(k, v)
        pass

    def restore_settings(self, plugin_settings, instance_settings):
        # TODO restore intrinsic configuration, usually using:
        # v = instance_settings.value(k)
        pass

    #def trigger_configuration(self):
    # Comment in to signal that the plugin has a way to configure
    # This will enable a setting button (gear icon) in each dock widget title bar
    # Usually used to open a modal configuration dialog

# #} end of default todo's

    def log_info(self, text):
        self.log_text.setText("Last log message: {}".format(text))
예제 #47
0
class PlotWidget(QWidget):
    customizationTriggered = pyqtSignal()

    def __init__(self,
                 name,
                 plotFunction,
                 plot_condition_function_list,
                 plotContextFunction,
                 parent=None):
        QWidget.__init__(self, parent)

        self._name = name
        self._plotFunction = plotFunction
        self._plotContextFunction = plotContextFunction
        self._plot_conditions = plot_condition_function_list
        """:type: list of functions """

        self._figure = Figure()
        self._figure.set_tight_layout(True)
        self._canvas = FigureCanvas(self._figure)
        self._canvas.setParent(self)
        self._canvas.setFocusPolicy(Qt.StrongFocus)
        self._canvas.setFocus()

        vbox = QVBoxLayout()
        vbox.addWidget(self._canvas)
        self._toolbar = CustomNavigationToolbar(self._canvas, self)
        self._toolbar.customizationTriggered.connect(
            self.customizationTriggered)
        vbox.addWidget(self._toolbar)
        self.setLayout(vbox)

        self._dirty = True
        self._active = False
        self.resetPlot()

    def getFigure(self):
        """ :rtype: matplotlib.figure.Figure"""
        return self._figure

    def resetPlot(self):
        self._figure.clear()

    @property
    def name(self):
        """ @rtype: str """
        return self._name

    def updatePlot(self):
        if self.isDirty() and self.isActive():
            # print("Drawing: %s" % self._name)
            self.resetPlot()
            plot_context = self._plotContextFunction(self.getFigure())
            try:
                self._plotFunction(plot_context)
                self._canvas.draw()
            except StandardError as e:
                exc_type, exc_value, exc_tb = sys.exc_info()
                sys.stderr.write("%s\n" % ("-" * 80))
                traceback.print_tb(exc_tb)
                sys.stderr.write("Exception type: %s\n" % exc_type.__name__)
                sys.stderr.write("%s\n" % e.message)
                sys.stderr.write("%s\n" % ("-" * 80))
                sys.stderr.write(
                    "An error occurred during plotting. This stack trace is helpful for diagnosing the problem."
                )

            self.setDirty(False)

    def setDirty(self, dirty=True):
        self._dirty = dirty

    def isDirty(self):
        return self._dirty

    def setActive(self, active=True):
        self._active = active

    def isActive(self):
        return self._active

    def canPlotKey(self, key):
        return any([
            plotConditionFunction(key)
            for plotConditionFunction in self._plot_conditions
        ])
class drift_tracker(QtGui.QWidget):
    def __init__(self, reactor, clipboard = None, cxn = None, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.reactor = reactor
        self.clipboard = clipboard
        self.cxn = cxn
        self.subscribed = False
        #see if favoirtes are provided in the configuration. if not, use an empty dictionary
        try:
            self.favorites =  c.favorites
        except AttributeError:
            self.favorites = {}
        updater = LoopingCall(self.update_lines)
        updater.start(c.update_rate)
        self.create_layout()
        self.connect_labrad()
    
    def create_layout(self):
        layout = QtGui.QGridLayout()
        plot_layout = self.create_drift_layout()
        widget_layout = self.create_widget_layout()
        spectrum_layout = self.create_spectrum_layout()
        layout.addLayout(plot_layout, 0, 0, 1, 2)
        layout.addLayout(widget_layout, 1, 0, 1, 1)
        layout.addLayout(spectrum_layout, 1, 1, 1, 1)
        self.setLayout(layout)
   
    def create_drift_layout(self):
        layout = QtGui.QVBoxLayout()
        self.fig = Figure()
        self.drift_canvas = FigureCanvas(self.fig)
        self.drift_canvas.setParent(self)  
        gs = gridspec.GridSpec(1, 2, wspace=0.15, left = 0.05, right = 0.95)
        line_drift = self.fig.add_subplot(gs[0, 0])
        line_drift.set_xlabel('Time (min)')
        line_drift.set_ylabel('KHz')
        line_drift.set_title("Line Center Drift")
        self.line_drift = line_drift
        self.line_drift_lines = []
        self.line_drift_fit_line = []
        b_drift = self.fig.add_subplot(gs[0, 1], sharex=line_drift)
        b_drift.set_xlabel('Time (min)')
        b_drift.set_ylabel('mgauss')
        b_drift.set_title("B Field Drift")
        self.b_drift_twin = b_drift.twinx()
        self.b_drift_twin.set_ylabel('Effective Frequency (kHz)')
        self.b_drift_twin_lines = []
        self.b_drift_lines = []
        self.b_drift_fit_line = []
        self.b_drift = b_drift
        self.mpl_toolbar = NavigationToolbar(self.drift_canvas, self)
        layout.addWidget(self.mpl_toolbar)
        layout.addWidget(self.drift_canvas)
        return layout
    
    def create_spectrum_layout(self):
        layout = QtGui.QVBoxLayout()
        self.fig = Figure()
        self.spec_canvas = FigureCanvas(self.fig)
        self.spec_canvas.setParent(self)  
        gs = gridspec.GridSpec(1, 1, wspace=0.15, left = 0.05, right = 0.95)
        spec = self.fig.add_subplot(gs[0, 0])
        spec.set_xlim(left = c.frequency_limit[0], right = c.frequency_limit[1])
        spec.set_ylim(bottom = 0, top = 1)
        spec.set_xlabel('MHz')
        spec.set_ylabel('Arb')
        spec.set_title("Predicted Spectrum")
        self.spec = spec
        self.mpl_toolbar = NavigationToolbar(self.spec_canvas, self)
        self.spectral_lines = []
        layout.addWidget(self.mpl_toolbar)
        layout.addWidget(self.spec_canvas)
        return layout
    
    def create_widget_layout(self):
        layout = QtGui.QGridLayout()
        self.frequency_table = saved_frequencies_table(self.reactor, suffix = ' MHz', sig_figs = 4)
        self.entry_table = table_dropdowns_with_entry(self.reactor, limits = c.frequency_limit, suffix = ' MHz', sig_figs = 4, favorites = self.favorites)
        self.entry_button = QtGui.QPushButton("Submit")
        self.copy_clipboard_button = QtGui.QPushButton("Copy Info to Clipboard")
        self.remove_B_button = QtGui.QPushButton("Remove B")
        self.remove_line_center_button = QtGui.QPushButton("Remove Line Center")
        self.remove_B_count = QtGui.QSpinBox()
        self.remove_B_count.setRange(-20,20)
        self.remove_line_center_count = QtGui.QSpinBox()
        self.remove_line_center_count.setRange(-20,20)
        
        self.track_B_duration = QtGui.QSpinBox()
        self.track_B_duration.setKeyboardTracking(False)
        self.track_B_duration.setSuffix('min')
        self.track_B_duration.setRange(1, 1000)
        
        self.track_line_center_duration = QtGui.QSpinBox()
        self.track_line_center_duration.setKeyboardTracking(False)
        self.track_line_center_duration.setSuffix('min')
        self.track_line_center_duration.setRange(1, 1000)
        
        layout.addWidget(self.frequency_table, 0, 0, 1, 1)
        layout.addWidget(self.entry_table, 0, 1 , 1 , 1)
        layout.addWidget(self.entry_button, 1, 1, 1, 1)
        layout.addWidget(self.copy_clipboard_button, 1, 0, 1, 1)
        
        remove_B_layout = QtGui.QHBoxLayout() 
        remove_B_layout.addWidget(self.remove_B_count)
        remove_B_layout.addWidget(self.remove_B_button)    

        remove_line_center_layout = QtGui.QHBoxLayout() 
        remove_line_center_layout.addWidget(self.remove_line_center_count)
        remove_line_center_layout.addWidget(self.remove_line_center_button)    

        update_layout = QtGui.QHBoxLayout() 
        
        keep_B_layout = QtGui.QHBoxLayout()
        keep_B_layout.addWidget(QtGui.QLabel("Tracking Duration (B)"))
        keep_B_layout.addWidget(self.track_B_duration)

        keep_line_center_layout = QtGui.QHBoxLayout()
        keep_line_center_layout.addWidget(QtGui.QLabel("Tracking Duration (Line Center)"))
        keep_line_center_layout.addWidget(self.track_line_center_duration)
        
        layout.addLayout(update_layout, 2, 1, 1, 1)
        layout.addLayout(remove_B_layout, 2, 0, 1, 1)
        layout.addLayout(remove_line_center_layout, 3, 0, 1, 1)
        layout.addLayout(keep_B_layout, 2, 1, 1, 1)
        layout.addLayout(keep_line_center_layout, 3, 1, 1, 1)
        return layout
        
    def connect_layout(self):
        self.remove_B_button.clicked.connect(self.on_remove_B)
        self.remove_line_center_button.clicked.connect(self.on_remove_line_center)
        self.entry_button.clicked.connect(self.on_entry)
        self.track_B_duration.valueChanged.connect(self.on_new_B_track_duration)
        self.track_line_center_duration.valueChanged.connect(self.on_new_line_center_track_duration)
        self.copy_clipboard_button.pressed.connect(self.do_copy_info_to_clipboard)
    
    @inlineCallbacks
    def initialize_layout(self):
        server = yield self.cxn.get_server('SD Tracker')
        transitions = yield server.get_transition_names()
        self.entry_table.fill_out(transitions)
        duration_B, duration_line_center = yield server.history_duration()
        self.track_B_duration.blockSignals(True)
        self.track_line_center_duration.blockSignals(True)
        self.track_B_duration.setValue(duration_B['min'])
        self.track_line_center_duration.setValue(duration_line_center['min'])
        self.track_B_duration.blockSignals(False)
        self.track_line_center_duration.blockSignals(False)
        yield self.on_new_fit(None, None)
    
    @inlineCallbacks
    def do_copy_info_to_clipboard(self):
        try:
            server = yield self.cxn.get_server('SD Tracker')
            lines = yield server.get_current_lines()
            b_history, center_history =  yield server.get_fit_history()
            b_value =  b_history[-1][1]
            center_value = center_history[-1][1]
        except Exception as e:
            #no lines available
            pass
        else:
            date = time.strftime('%m/%d/%Y')
            d = dict(lines)
            text = '| {0} || {1:.4f} MHz || {2:.4f} MHz || {3:.4f} MHz || {4:.4f} MHz || {5:.4f} G || comment'.format(date, d['S+1/2D-3/2']['MHz'], d['S-1/2D-5/2']['MHz'], d['S-1/2D-1/2']['MHz'], center_value['MHz'], b_value['gauss'])
            if self.clipboard is not None:
                self.clipboard.setText(text)
    
    def on_update_enable(self, enable):
        rate = self.update_rate.value()
        if enable:
            self.updater.start(rate, now = True)
        else:
            self.updater.stop()
    
    def on_update_rate_change(self, rate):
        if self.updater.running:
            self.updater.stop()
            self.updater.start(rate, now = True)
            
    @inlineCallbacks
    def on_remove_B(self, clicked):
        to_remove = self.remove_B_count.value()
        server = yield self.cxn.get_server('SD Tracker')
        try:
            yield server.remove_b_measurement(to_remove)
            print to_remove
        except self.Error as e:
            self.displayError(e.msg)
    @inlineCallbacks
    def on_remove_line_center(self, clicked):
        to_remove = self.remove_line_center_count.value()
        server = yield self.cxn.get_server('SD Tracker')
        try:
            yield server.remove_line_center_measurement(to_remove)
        except self.Error as e:
            self.displayError(e.msg)    
    @inlineCallbacks
    def on_entry(self, clicked):
        server = yield self.cxn.get_server('SD Tracker')
        info = self.entry_table.get_info()
        with_units = [(name, self.WithUnit(val, 'MHz')) for name,val in info]
        try:
            yield server.set_measurements(with_units)
        except self.Error as e:
            self.displayError(e.msg)
    
    @inlineCallbacks
    def on_new_B_track_duration(self, value):
        server = yield self.cxn.get_server('SD Tracker')
        rate_B = self.WithUnit(value, 'min')
        rate_line_center = self.WithUnit(self.track_line_center_duration.value(), 'min')
        yield server.history_duration((rate_B, rate_line_center))
    
    @inlineCallbacks
    def on_new_line_center_track_duration(self, value):
        server = yield self.cxn.get_server('SD Tracker')
        rate_line_center = self.WithUnit(value, 'min')
        rate_B = self.WithUnit(self.track_B_duration.value(), 'min')
        yield server.history_duration((rate_B, rate_line_center))
        
    @inlineCallbacks
    def connect_labrad(self):
        from labrad.units import WithUnit
        from labrad.types import Error
        self.WithUnit = WithUnit
        self.Error = Error
        if self.cxn is None:
            from common.clients.connection import connection
            self.cxn = connection()
            yield self.cxn.connect()
        self.context = yield self.cxn.context()
        try:
            yield self.subscribe_tracker()
        except Exception as e:
            self.setDisabled(True)
        self.cxn.add_on_connect('SD Tracker', self.reinitialize_tracker)
        self.cxn.add_on_disconnect('SD Tracker', self.disable)
        self.connect_layout()
        
    @inlineCallbacks
    def subscribe_tracker(self):
        server = yield self.cxn.get_server('SD Tracker')
        yield server.signal__new_fit(c.ID, context = self.context)
        yield server.addListener(listener = self.on_new_fit, source = None, ID = c.ID, context = self.context)
        yield self.initialize_layout()
        self.subscribed = True
    
    @inlineCallbacks
    def reinitialize_tracker(self):
        self.setDisabled(False)
        server = yield self.cxn.get_server('SD Tracker')
        yield server.signal__new_fit(c.ID, context = self.context)
        if not self.subscribed:
            yield server.addListener(listener = self.on_new_fit, source = None, ID = c.ID, context = self.context)
            yield self.initialize_layout()
            self.subscribed = True
    
    @inlineCallbacks
    def on_new_fit(self, x, y):
        yield self.update_lines()
        yield self.update_fit()
    
    @inlineCallbacks
    def update_fit(self):
        try:
            server = yield self.cxn.get_server('SD Tracker')
            history_B, history_line_center = yield server.get_fit_history()
            excluded_B, excluded_line_center = yield server.get_excluded_points()
            fit_b = yield server.get_fit_parameters('bfield')
            fit_f = yield server.get_fit_parameters('linecenter')
        except Exception as e:
            #no fit available
            print e
            pass
        else:
            inunits_b = [(t['min'], b['mgauss']) for (t,b) in history_B]
            inunits_f = [(t['min'], freq['kHz']) for (t,freq) in history_line_center]
            inunits_b_nofit = [(t['min'], b['mgauss']) for (t,b) in excluded_B]
            inunits_f_nofit = [(t['min'], freq['kHz']) for (t,freq) in excluded_line_center]            
            self.update_track((inunits_b,inunits_b_nofit), self.b_drift, self.b_drift_lines)
            self.update_track((inunits_f,inunits_f_nofit), self.line_drift, self.line_drift_lines)

            
            self.plot_fit_b(fit_b)
            self.plot_fit_f(fit_f)
    
    def plot_fit_b(self, p):
        for i in range(len(self.b_drift_fit_line)):
            l = self.b_drift_fit_line.pop()
            l.remove()
        for i in range(len(self.b_drift_twin_lines)):
            l = self.b_drift_twin_lines.pop()
            l.remove()
        xmin,xmax = self.b_drift.get_xlim()
        xmin-= 10
        xmax+= 10
        
        points = 1000        
        x = numpy.linspace(xmin, xmax, points) 
        y = 1000 * numpy.polyval(p, 60*x)
        frequency_scale = 1.4 #KHz / mgauss
        l = self.b_drift.plot(x, y, '-r')[0]
        twin = self.b_drift_twin.plot(x, frequency_scale * y, alpha = 0)[0]
        self.b_drift_twin_lines.append(twin)
        label = self.b_drift.annotate('Slope {0:.1f} microgauss/sec'.format(10**6 * p[-2]), xy = (0.5, 0.8), xycoords = 'axes fraction', fontsize = 13.0)
        self.b_drift_fit_line.append(label)
        self.b_drift_fit_line.append(l)
        self.drift_canvas.draw()
    
    def plot_fit_f(self, p):
        for i in range(len(self.line_drift_fit_line)):
            l = self.line_drift_fit_line.pop()
            l.remove()
        xmin,xmax = self.b_drift.get_xlim()
        xmin-= 10
        xmax+= 10
        points = 1000
        x = numpy.linspace(xmin, xmax, points) 
        y = 1000 * numpy.polyval(p, 60*x)
        l = self.line_drift.plot(x, y, '-r')[0]
        label = self.line_drift.annotate('Slope {0:.1f} Hz/sec'.format(10**6 * p[-2]), xy = (0.5, 0.8), xycoords = 'axes fraction', fontsize = 13.0)
        self.line_drift_fit_line.append(l)
        self.line_drift_fit_line.append(label)
        self.drift_canvas.draw()
    
    @inlineCallbacks
    def update_lines(self):
        try:
            server = yield self.cxn.get_server('SD Tracker')
            lines = yield server.get_current_lines()
        except Exception as e:
            #no lines available
            returnValue(None)
        else:
            self.update_spectrum(lines)
            self.update_listing(lines)
            returnValue(lines)
    
    def update_track(self, meas, axes, lines):
        #clear all current lines
        for i in range(len(lines)):
            line = lines.pop()
            line.remove()
        fitted = meas[0]
        not_fitted = meas[1]
        x = numpy.array([m[0] for m in fitted])
        y = [m[1] for m in fitted]
        xnofit = numpy.array([m[0] for m in not_fitted])
        ynofit = [m[1] for m in not_fitted]
        
        #annotate the last point
        try:
            last = y[-1]
        except IndexError:
            pass
        else:
            label = axes.annotate('Last Point: {0:.2f} {1}'.format(last, axes.get_ylabel()), xy = (0.5, 0.9), xycoords = 'axes fraction', fontsize = 13.0)
            lines.append(label)
        line = axes.plot(x,y, 'b*')[0]
        line_nofit = axes.plot(xnofit,ynofit, 'ro')[0]
        
        lines.append(line)
        lines.append(line_nofit)
        
        #set window limits
        xmin = numpy.amin(x)
        xmax = numpy.amax(x)
        ymin = numpy.amin(y)
        ymax = numpy.amax(y)
        if xmin == xmax:
            xlims = [xmin-5,xmax+5]
            ylims = [ymin-2,ymax+2]
        else:
            xspan = xmax-xmin
            yspan = ymax-ymin
            xlims = [xmin-0.25*xspan,xmax+0.5*xspan]
            ylims = [ymin-0.5*yspan,ymax+0.5*yspan]
        axes.set_xlim(xlims)
        axes.set_ylim(ylims)
        
        self.drift_canvas.draw()
        
    def update_spectrum(self, lines):
        #clear all lines by removing them from the self.spectral_lines list
        for i in range(len(self.spectral_lines)):
            line = self.spectral_lines.pop()
            line.remove()
        #sort by frequency to add them in the right order
        srt = sorted(lines, key = lambda x: x[1])
        num = len(srt)
        for i, (linename, freq) in enumerate(srt):
            line = self.spec.axvline(freq['MHz'], linewidth=1.0, ymin = 0, ymax = 1)
            self.spectral_lines.append(line)
            #check to see if linename in the favorites dictionary, if not use the linename for display
            display_name = self.favorites.get(linename, linename)
            label = self.spec.annotate(display_name, xy = (freq['MHz'], 0.9 - i * 0.7 / num), xycoords = 'data', fontsize = 13.0)
            self.spectral_lines.append(label)
        self.spec_canvas.draw()

    def update_listing(self, lines):
        listing = [(self.favorites.get(line, line), freq) for line,freq in lines]
        self.frequency_table.fill_out_widget(listing)
        
    @inlineCallbacks
    def disable(self):
        self.setDisabled(True)
        yield None
        
    def displayError(self, text):
        #runs the message box in a non-blocking method
        message = QtGui.QMessageBox(self)
        message.setText(text)
        message.open()
        message.show()
        message.raise_()
    
    def closeEvent(self, x):
        self.reactor.stop()  
예제 #49
0
class PerformanceResultsAnalysisWidget(QtGui.QWidget):
    """ The main window of the performance results analysis GUI
    
    **Parameters**
    
        :swap: Switch between zero and one to change different
               between two different printing cases.
               
               This is yet implemented in nominal vs. nominal plots 
               to switch in the presentation which parameter defines the main
               differentiation
               and
               in numeric vs. nominal to activate some dependent display 
               of functions with a hidden parameter, to show performance
               differences in time and `Balanced_accuracy`.
    """
    
    def __init__(self, results_file=None, parent=None):
        super(PerformanceResultsAnalysisWidget, self).__init__(parent)
                
        # Load a results csv file
        self._load_results_collection_from_file(results_file)
        # Try to load collection of ROC curves (may not always be available)
        self._load_roc_curves()
        
        # Create elements of this widget
        self._create_elements()
        
        # The currently selected projection parameters (required for ROC)
        self.projection_parameters = {}
        
        # To be able to swap the role of the parameters in nom_vs_nom plots
        self.swap = 1
        self.swap2 = 1
        self.save_path = "./"

    def _load_results_collection_from_file(self, file_name=None):
        """ Load results collection from file  """
        if file_name is None:
            # Let the user specify a file to be loaded
            self.file_name = \
                str(QtGui.QFileDialog.getOpenFileName(
                    parent=self, caption="Select a results file",
                    filter="results files (*.csv)"))
        else:
            self.file_name = file_name
        # Try to load specified file 
        dirname, filename = os.path.split(self.file_name)      
        self.result_collection = PerformanceResultSummary(dataset_dir=dirname,
                                                          csv_filename=filename)
        # Create working copy that can be modified
        self.current_collection = copy.deepcopy(self.result_collection)

    def _load_roc_curves(self):
        """ Load the collection of ROC curves. Max not always be available. """
        self.roc_curves = ROCCurves(base_path=os.path.dirname(self.file_name))

    def _create_elements(self):
        """ Create elements of this widget"""
        from matplotlib.figure import Figure
        from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
        
        # Create model and view of the variable selection
        # NOTE: One or two variables can be selected
        self.variables_model = QtGui.QStandardItemModel()
        self.variables_items = []
        for variable_name in sorted(self.current_collection.get_gui_variables()):
            item = QtGui.QStandardItem('%s' % variable_name)
            item.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)
            item.setData(QtCore.QVariant(QtCore.Qt.Unchecked),
                         QtCore.Qt.CheckStateRole)
            self.variables_model.appendRow(item)
            self.variables_items.append(item)
        
        self.variables_view = QtGui.QListView(self)
        self.variables_view.setModel(self.variables_model)
        
        # Create metrics selection list widget
        self.metrics_view = QtGui.QListWidget(self)
        self.metrics_view.setSelectionMode(QtGui.QListView.SingleSelection)
        self.metrics_items = []
        if not self.roc_curves.is_empty():  # If we can plot ROC curves
            self.metrics_items.append(QtGui.QListWidgetItem("ROC Curve",
                                                            self.metrics_view))
        for metric_name in sorted(self.current_collection.get_gui_metrics()):
            item = QtGui.QListWidgetItem('%s' % metric_name, self.metrics_view)
            self.metrics_items.append(item)
        self.metrics_items.append(QtGui.QListWidgetItem("Cost function",
                                                        self.metrics_view))
        
        # Add cost function box
        self.fpcost_label = QtGui.QLabel("False Positive Cost")
        self.fpcost_line_edit = QtGui.QLineEdit("1.0")
        self.fncost_label = QtGui.QLabel("False Negative Cost")
        self.fncost_line_edit = QtGui.QLineEdit("1.0") 
        
        # Create various buttons and connect them with the handler functions
        self.load_button = QtGui.QPushButton("&Load")
        self.connect(self.load_button, QtCore.SIGNAL('clicked()'), 
                     self._reload) #self._load_results_collection_from_file)
        
        self.draw_button = QtGui.QPushButton("&Draw or Toggle")
        self.connect(self.draw_button, QtCore.SIGNAL('clicked()'), 
                     self._draw_plot)
        
        self.hist_button = QtGui.QPushButton("&Histogram")
        self.connect(self.hist_button, QtCore.SIGNAL('clicked()'), 
                     self._draw_histogram)
        
        self.project_button = QtGui.QPushButton("&Filter")
        self.connect(self.project_button, QtCore.SIGNAL('clicked()'), 
                     self._project_popup)
        
        self.save_button = QtGui.QPushButton("&Save")
        self.connect(self.save_button, QtCore.SIGNAL('clicked()'), self._save)
        
        self.reset_button = QtGui.QPushButton("&Reset")
        self.connect(self.reset_button, QtCore.SIGNAL('clicked()'), self._reset)
        
        # Create matplotlib canvas 
        self.fig = Figure((12.0, 8.0), dpi=100)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)
        
        # Create axes for plot
        self.axes = self.fig.add_subplot(111)
        
        # Text showing projection parameters
        self.project_params_label = QtGui.QLabel("No filtering.")
        self.project_params_label.setWordWrap(1)
        self.project_params_label.setFixedWidth(self.canvas.width())
        
        # Create layout of widget
        vlayout1 = QtGui.QVBoxLayout()
        hlayout1 = QtGui.QHBoxLayout()
        vlayout2 = QtGui.QVBoxLayout()
        vlayout2.addWidget(self.variables_view)
        vlayout2.addWidget(self.metrics_view)
        vlayout2.addWidget(self.fpcost_label)
        vlayout2.addWidget(self.fpcost_line_edit)
        vlayout2.addWidget(self.fncost_label)
        vlayout2.addWidget(self.fncost_line_edit)
        hlayout1.addLayout(vlayout2)
        hlayout1.addWidget(self.canvas)
        vlayout1.addLayout(hlayout1)
        
        hlayout2 = QtGui.QHBoxLayout()
        hlayout2.addWidget(self.load_button)
        hlayout2.addWidget(self.draw_button)
        hlayout2.addWidget(self.hist_button)
        hlayout2.addWidget(self.project_button)
        hlayout2.addWidget(self.save_button)
        hlayout2.addWidget(self.reset_button)
        
        vlayout1.addWidget(self.project_params_label)
        vlayout1.addLayout(hlayout2)
        
        self.setLayout(vlayout1)

    def _project_onto(self, selected_variable, selected_values):
        """ Project onto the data where selected_variable has the values selected_values."""
        self.current_collection = \
            self.current_collection.project_onto(selected_variable,
                                                 selected_values)
        # Try if we can evaluate the value
        try:
            selected_values = eval(selected_values)
        except:
            pass
        # Remember projection for ROC curves    
        self.projection_parameters[selected_variable] = selected_values
        
        # Update projections label
        self.project_params_label.setText("Filters: " +
                                          str(self.projection_parameters))
        self.project_params_label.adjustSize()
        
        # Update selection box
        self._update_variable_selection()

    def _update_variable_selection(self):
        """ Updates the selection box for variables"""
        self.variables_model.clear()
        self.variables_items = []
        
        for variable_name in sorted(self.current_collection.get_gui_variables()):
            item = QtGui.QStandardItem('%s' % variable_name)
            item.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)
            item.setData(QtCore.QVariant(QtCore.Qt.Unchecked),
                         QtCore.Qt.CheckStateRole)
            self.variables_model.appendRow(item)
            self.variables_items.append(item)

    def _save(self):
        """Stores the current figure to a file"""
        dic = self.fig.canvas.get_supported_filetypes()
        if "pdf" in dic:
            extensionList = ["%s (*.pdf)" % dic["pdf"]]
        else:
            extensionList = []

        for ext,desc in dic.items():
            if (ext != "pdf"):
                extensionList.append("%s (*.%s)" % (desc,ext))

        selectionList = ";;".join(extensionList)

        file_name = \
            str(QtGui.QFileDialog.getSaveFileName(
                self, "Select a name for the graphic", self.save_path,
                selectionList))
        self.save_path = os.path.dirname(file_name)
        self.fig.savefig(file_name, dpi=400)

    def _reset(self):
        """ Reset working collection to originally loaded one"""
        self.current_collection = copy.deepcopy(self.result_collection)
        self.projection_parameters = {}
        self.project_params_label.setText("No filtering.")
        self._update_variable_selection()

        self.metrics_items = []
        self.metrics_view.clear()
        if not self.roc_curves.is_empty():  # If we can plot ROC curves
            self.metrics_items.append(QtGui.QListWidgetItem("ROC Curve",
                                                            self.metrics_view))
        for metric_name in sorted(self.current_collection.get_gui_metrics()):
            item = QtGui.QListWidgetItem('%s' % metric_name, self.metrics_view)
            self.metrics_items.append(item)
        self.metrics_items.append(QtGui.QListWidgetItem("Cost function",
                                                        self.metrics_view))

    def _reload(self):
        """ Reinitialize and load new result file """
        self._load_results_collection_from_file()
        self._load_roc_curves()
        self._reset()

    def _draw_plot(self):
        """Draw a plot for the selected variable/metric combination. """
        # Determine selected metric
        selected_metric = None
        for item in self.metrics_items:
            if item.isSelected():
                selected_metric = str(item.text())
                break
            
        if selected_metric is None:
            warning_box = QtGui.QMessageBox()
            warning_box.setText("A metric must be selected.")
            warning_box.exec_()
            return
               
        # Determine selected variables
        selected_variables = self._get_selected_items(self.variables_items)
        if not 0 < len(selected_variables) <= 2 and selected_metric != "ROC Curve":
            warning_box = QtGui.QMessageBox()
            warning_box.setText("One or two variables must be selected.")
            warning_box.exec_()
            return
        if len(selected_variables) > 1 and selected_metric == "ROC Curve":
            warning_box = QtGui.QMessageBox()
            warning_box.setText("At most one variable can be selected for ROC curves.")
            warning_box.exec_()
            return

        # The "metric" ROC curve" needs a special treatment
        if selected_metric == "ROC Curve":
            selected_variable = None if selected_variables == [] else selected_variables[0]
            fpcost = eval(str(self.fpcost_line_edit.text()))
            fncost = eval(str(self.fncost_line_edit.text()))
            self.fig.clear()
            self.axes = self.fig.add_subplot(111) 
            self.roc_curves.plot(self.axes, selected_variable=selected_variable,
                                 projection_parameter=self.projection_parameters,
                                 fpcost=fpcost, fncost=fncost,
                                 collection=self.current_collection)
            self.canvas.draw()
            return
        elif selected_metric == "Cost function": # needs special treatment
            selected_metric = "#".join([str(self.fpcost_line_edit.text()),
                                       "False_positives",
                                       str(self.fncost_line_edit.text()),
                                       "False_negatives"])
        
        # Determine nominal and numeric parameters of the loaded table
        variables = self.current_collection.get_gui_variables()
        nominal_parameters = \
            list(self.current_collection.get_nominal_parameters(variables))
        numeric_parameters = \
            list(self.current_collection.get_numeric_parameters(variables))
        
        # Do the actual plotting
        self.fig.clear()
        self.axes = self.fig.add_subplot(111) 
        if len(selected_variables) == 1:
            if selected_variables[0] in nominal_parameters:
                self.current_collection.plot_nominal(self.axes,
                                                     selected_variables[0], 
                                                     selected_metric)
            else:
                self.current_collection.plot_numeric(self.axes,
                                                    selected_variables[0], 
                                                    selected_metric)
        else:
            # Canonical order: Numeric parameters have to be first
            if selected_variables[0] in nominal_parameters:
                selected_variables = [selected_variables[1], selected_variables[0]]
            # Plot for two nominal variables
            if selected_variables[0] in nominal_parameters:
                # For every click on Draw, swap the role of the parameters
                selected_variables=sorted(selected_variables)
                self.swap = 1 - self.swap
                if self.swap == 0:
                    selected_variables[0], selected_variables[1] = \
                    selected_variables[1], selected_variables[0]
                self.current_collection.plot_nominal_vs_nominal(self.axes,
                                                                selected_variables[0],
                                                                selected_variables[1],
                                                                selected_metric)
            elif selected_variables[1] in nominal_parameters:
                self.swap = 1 - self.swap
                if self.swap:
                    self.swap2 = 1 - self.swap2
                self.current_collection.plot_numeric_vs_nominal(self.axes,
                                                                selected_variables[0],
                                                                selected_variables[1], 
                                                                selected_metric,
                                                                self.swap,
                                                                self.swap2)
            else:
                self.swap = 1 - self.swap
                self.current_collection.plot_numeric_vs_numeric(self.axes,
                                                                selected_variables, 
                                                                selected_metric,
                                                                self.swap)
        self.canvas.draw()

    def _draw_histogram(self):
        """ Draw a histogram of the current collection for the specified metric """
        # Determine selected variables
        selected_variables = self._get_selected_items(self.variables_items)
        
        # Determine selected metric
        selected_metric = None
        for item in self.metrics_items:
            if item.isSelected():
                selected_metric = str(item.text())
                break

        if selected_metric is None:
            warning_box = QtGui.QMessageBox()
            warning_box.setText("A metric must be selected.")
            warning_box.exec_()
            return

        # Do the actual plotting
        self.fig.clear()
        self.axes = self.fig.add_subplot(111) 

        self.current_collection.plot_histogram(self.axes, selected_metric,
                                               selected_variables, [])
        self.canvas.draw()
        
    def _project_popup(self):
        """ Create 'Filter' pop up window """
        popup_frame = ProjectionPopup(self)
        
    def _get_selected_items(self, items):
        """ Determine selected items from a list of items """
        selected_items = []
        for item in items:
            if item.checkState() != 0:
                selected_items.append(str(item.text()))
        return selected_items
class AppForm(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.setWindowTitle('Vasculature Map Matching')

        self.create_menu()
        self.create_main_frame()
        self.create_status_bar()

        self.spinbox_Xoffset.setValue(0)
        self.spinbox_Yoffset.setValue(0)
        self.spinbox_rotation.setValue(0)

        self.Xoffset = 0
        self.Yoffset = 0
        self.rotation = 0
        self.zoom = 1.
        self.reference_contrast = 1.
        self.matching_contrast = 1.

        self.getAdjustment()

        self.ReferenceVasMap = None
        self.MatchingVasMap = None
        self.MatchingVasMapAfterChange = None
        self.trialDict = None

        self.connect(self.button_RPath, SIGNAL('clicked()'), self.get_RPath)
        self.connect(self.button_MPath, SIGNAL('clicked()'), self.get_MPath)
        self.connect(self.button_draw, SIGNAL('clicked()'), self.on_draw)

        self.spinbox_Xoffset.valueChanged.connect(self.adjustVasMap)
        self.spinbox_Yoffset.valueChanged.connect(self.adjustVasMap)
        self.spinbox_rotation.valueChanged.connect(self.adjustVasMap)
        self.doubleSpinbox_zoom.valueChanged.connect(self.adjustVasMap)

        self.radiobutton_reference.clicked.connect(self.on_draw)
        self.radiobutton_matching.clicked.connect(self.on_draw)
        self.radiobutton_both.clicked.connect(self.on_draw)

        self.reference_contrast_slider.valueChanged.connect(
            self._sliding_reference_contrast)
        self.matching_contrast_slider.valueChanged.connect(
            self._sliding_matching_contrast)

        self.currReferenceFolder = r'C:\JunZhuang\labwork\data\2014-04-30-vasculature-maps\147861'
        self.currMatchingFolder = r'C:\JunZhuang\labwork\data\2014-04-30-vasculature-maps\147861'
        self.currSaveFolder = r'E:\data2\2015-04-17-VasculatureMapMatching'

    def save_alignment_json(self):
        path = str(
            QFileDialog.getSaveFileName(self, 'Save file', self.currSaveFolder,
                                        '*.json'))

        if path:
            bigDict = {}

            if self.ReferenceVasMap is not None:
                bigDict.update({
                    'ReferencePathList':
                    str(self.textbrowser_RPath.toPlainText()).split(';'),
                    'ReferenceMapHeight':
                    self.ReferenceVasMap.shape[0],
                    'ReferenceMapWidth':
                    self.ReferenceVasMap.shape[1]
                })
            else:
                bigDict.update({
                    'ReferencePathList': None,
                    'ReferenceMapHeight': None,
                    'ReferenceMapWidth': None
                })

            if self.MatchingVasMap is not None:
                bigDict.update({
                    'MatchingPathList':
                    str(self.textbrowser_MPath.toPlainText()).split(';'),
                    'MatchingMapHeight':
                    self.MatchingVasMap.shape[0],
                    'MatchingMapWidth':
                    self.MatchingVasMap.shape[1],
                    'Zoom':
                    float(self.zoom),
                    'Rotation':
                    float(self.rotation),
                    'Xoffset':
                    self.Xoffset,
                    'Yoffset':
                    self.Yoffset
                })
            else:
                bigDict.update({
                    'MatchingPathList': None,
                    'MatchingMapHeight': None,
                    'MatchingMapWidth': None,
                    'Zoom': None,
                    'Rotation': None,
                    'Xoffset': None,
                    'Yoffset': None
                })

            if path[-5:] == '.json':
                path_surfix = path[:-5]
            else:
                path_surfix = path

            with open(path_surfix + '_VasculatureMapMatchingParameters.json',
                      'w') as f:
                json.dump(bigDict,
                          f,
                          sort_keys=True,
                          indent=4,
                          separators=(',', ': '))

            if self.MatchingVasMapRaw is not None:
                tf.imsave(path_surfix + '_VasculatureMapBeforeMatching.tif',
                          self.MatchingVasMapRaw)
                MatchVasMapAfterChange = rigid_transform(
                    self.MatchingVasMapRaw,
                    zoom=self.zoom,
                    rotation=self.rotation,
                    offset=(self.Xoffset, self.Yoffset),
                    outputShape=(self.ReferenceVasMap.shape[0],
                                 self.ReferenceVasMap.shape[1]))
                tf.imsave(path_surfix + '_VasculatureMapAfterMatching.tif',
                          MatchVasMapAfterChange)

            self.statusBar().showMessage('Saved to %s' % path, 2000)
            self.currSaveFolder = os.path.split(path)[0]

    def getAdjustment(self):
        self.Xoffset = self.spinbox_Xoffset.value()
        self.Yoffset = self.spinbox_Yoffset.value()
        self.rotation = self.spinbox_rotation.value()
        self.zoom = self.doubleSpinbox_zoom.value()

    def setZero(self):
        self.spinbox_Xoffset.setValue(0.)
        self.spinbox_Yoffset.setValue(0.)
        self.spinbox_rotation.setValue(0.)
        self.doubleSpinbox_zoom.setValue(1.)

    def on_about(self):
        msg = """ match two vasculature maps to get alignment:

         * input file fold and number list to get reference vasculature map
         * input retinotopic mapping trial dictionary to get matching vasculature map
         * Adjust X offset, Y offset and rotation to match two vasculature maps
         * hit menu -> File -> save alignment to save alignment parameter
        """
        QMessageBox.about(self, "About the GUI", msg.strip())

    def get_RPath(self):

        self.axes.clear()
        self.canvas.draw()

        self.button_RPath.setStyleSheet('QPushButton {color: #888888}')
        self.button_RPath.setEnabled(False)

        fnames = QFileDialog.getOpenFileNames(
            self,
            'Choose Retinotopic Mapping Dictionary of TIFF/JCam file(s):',
            self.currReferenceFolder)

        fnames = list(fnames)
        fnames = [str(x) for x in fnames]

        try:
            if len(fnames) == 0:  # no file is chosen

                print("no file is chosen! Setting reference map as None...")
                self.textbrowser_RPath.clear()
                self.ReferenceVasMap = None

            elif len(fnames) == 1:  # only one file is chosen
                filePath = fnames[0]
                if filePath[-3:] == 'pkl':  # mapping dictionary pkl file

                    self.trialDict = ft.loadFile(filePath)
                    self.ReferenceVasMap = pt.merge_normalized_images(
                        [self.trialDict['vasculatureMap']])
                    self.textbrowser_RPath.setText(filePath)

                elif filePath[-3:] == 'tif':  # tiff file
                    self.ReferenceVasMap = pt.merge_normalized_images(
                        [tf.imread(filePath)])
                    self.textbrowser_RPath.setText(filePath)

                else:  # Raw binary file
                    fileFolder, fileName = os.path.split(filePath)
                    if 'JCamF' in fileName:
                        currMap, _, _ = ft.importRawJCamF(filePath,
                                                          column=1024,
                                                          row=1024)
                        self.ReferenceVasMap = pt.merge_normalized_images(
                            [currMap[0]])
                        self.textbrowser_RPath.setText(filePath)
                    elif 'JCam' in fileName:
                        currMap, _ = ft.importRawJCam(filePath)
                        self.ReferenceVasMap = pt.merge_normalized_images(
                            [currMap[0]])
                        self.textbrowser_RPath.setText(filePath)
                    else:
                        print('Can not read reference map ' + filePath)
                        self.textbrowser_RPath.clear()
                        self.ReferenceVasMap = None

            else:  # more than one file is chosen

                displayText = ';'.join(fnames)
                mapList = []

                for i, filePath in enumerate(fnames):

                    if filePath[-3:] == 'tif':  # tiff file
                        mapList.append(tf.imread(filePath))

                    else:  # raw binary file
                        fileFolder, fileName = os.path.split(filePath)
                        if 'JCamF' in fileName:
                            currMap, _, _ = ft.importRawJCamF(filePath,
                                                              column=1024,
                                                              row=1024)
                        elif 'JCam' in fileName:
                            currMap, _ = ft.importRawJCam(filePath)
                        else:
                            print('Can not read ' + filePath)

                        mapList.append(currMap[0].astype(np.float32))

                if len(mapList) == 0:
                    print(
                        "no file can be read! Setting reference map as None..."
                    )
                    self.textbrowser_RPath.clear()
                    self.ReferenceVasMap = None
                else:
                    self.ReferenceVasMap = pt.merge_normalized_images(
                        mapList).astype(np.float32)
                    self.textbrowser_RPath.setText(displayText)

        except Exception as e:
            print(e, '\n\n')
            print('Can not load reference Map! Setting it as None...')
            self.textbrowser_RPath.clear()
            self.ReferenceVasMap = None

        self.button_RPath.setEnabled(True)
        self.button_RPath.setStyleSheet('QPushButton {color: #000000}')
        self.setZero()
        self.currReferenceFolder = os.path.split(fnames[0])[0]

    def get_MPath(self):

        self.axes.clear()
        self.canvas.draw()

        self.button_MPath.setStyleSheet('QPushButton {color: #888888}')
        self.button_MPath.setEnabled(False)

        fnames = QFileDialog.getOpenFileNames(
            self,
            'Choose Retinotopic Mapping Dictionary of TIFF/JCam file(s):',
            self.currMatchingFolder)

        fnames = list(fnames)
        fnames = [str(x) for x in fnames]

        try:
            if len(fnames) == 0:  # no file is chosen

                print("no file is chosen! Setting matching map as None...")
                self.textbrowser_MPath.clear()
                self.MatchingVasMap = None
                self.MatchingVasMapRaw = None
                self.MatchingVasMapAfterChange = None

            elif len(fnames) == 1:  # only one file is chosen
                filePath = fnames[0]
                if filePath[-3:] == 'pkl':  # mapping dictionary pkl file

                    self.trialDict = ft.loadFile(filePath)
                    self.MatchingVasMap = pt.merge_normalized_images(
                        [self.trialDict['vasculatureMap']])
                    self.MatchingVasMapRaw = self.trialDict['vasculatureMap']
                    self.textbrowser_MPath.setText(filePath)
                    self.MatchingVasMapAfterChange = None

                elif filePath[-3:] == 'tif':  # tiff file
                    self.MatchingVasMap = pt.merge_normalized_images(
                        [tf.imread(filePath)])
                    self.MatchingVasMapRaw = tf.imread(filePath)
                    self.textbrowser_MPath.setText(filePath)
                    self.MatchingVasMapAfterChange = None

                else:  # raw binary file
                    fileFolder, fileName = os.path.split(filePath)
                    if 'JCamF' in fileName:
                        currMap, _, _ = ft.importRawJCamF(filePath,
                                                          column=1024,
                                                          row=1024)
                        self.MatchingVasMap = pt.merge_normalized_images(
                            [currMap[0]])
                        self.MatchingVasMapRaw = currMap[0]
                        self.textbrowser_MPath.setText(filePath)
                    elif 'JCam' in fileName:
                        currMap, _ = ft.importRawJCam(filePath)
                        self.MatchingVasMap = pt.merge_normalized_images(
                            [currMap[0]])
                        self.MatchingVasMapRaw = currMap[0]
                        self.textbrowser_MPath.setText(filePath)
                    else:
                        print('Can not read matching map ' + filePath)
                        self.textbrowser_MPath.clear()
                        self.MatchingVasMap = None
                    self.MatchingVasMapAfterChange = None

            else:  # more than one file is chosen

                displayText = ';'.join(fnames)
                mapList = []

                for i, filePath in enumerate(fnames):

                    if filePath[-3:] == 'tif':  # tiff file
                        mapList.append(tf.imread(filePath))

                    else:  # raw binary file
                        fileFolder, fileName = os.path.split(filePath)
                        if 'JCamF' in fileName:
                            currMap, _, _ = ft.importRawJCamF(filePath,
                                                              column=1024,
                                                              row=1024)
                        elif 'JCam' in fileName:
                            currMap, _ = ft.importRawJCam(filePath)
                        else:
                            print('Can not read ' + filePath)

                        mapList.append(currMap[0].astype(np.float32))

                if len(mapList) == 0:
                    print(
                        "no file can be read! Setting matching map as None...")
                    self.textbrowser_MPath.clear()
                    self.MatchingVasMap = None
                    self.MatchingVasMapRaw = None
                    self.MatchingVasMapAfterChange = None
                else:
                    self.MatchingVasMap = pt.merge_normalized_images(
                        mapList, dtype=np.float32)
                    self.MatchingVasMapRaw = pt.merge_normalized_images(
                        mapList, dtype=np.float32, isFilter=False)
                    self.textbrowser_MPath.setText(displayText)
                    self.MatchingVasMapAfterChange = None

        except Exception as e:
            print(e, '\n\n')
            print('Can not load matching Map! Setting it as None...')
            self.textbrowser_MPath.clear()
            self.MatchingVasMap = None
            self.MatchingVasMapRaw = None
            self.MatchingVasMapAfterChange = None

        self.button_MPath.setEnabled(True)
        self.button_MPath.setStyleSheet('QPushButton {color: #000000}')
        self.setZero()
        self.currMatchingFolder = os.path.split(fnames[0])[0]

    def adjustVasMap(self):

        self.getAdjustment()

        if type(self.MatchingVasMap) != type(None):

            if type(self.ReferenceVasMap) != type(None):
                width = self.ReferenceVasMap.shape[1]
                height = self.ReferenceVasMap.shape[0]
            else:
                width = self.MatchingVasMap.shape[1]
                height = self.MatchingVasMap.shape[0]

            self.MatchingVasMapAfterChange = rigid_transform(
                self.MatchingVasMap,
                zoom=self.zoom,
                rotation=self.rotation,
                offset=(self.Xoffset, self.Yoffset),
                outputShape=(height, width))

            self.on_draw()

    def _sliding_reference_contrast(self):
        contrast_map = [1 / 4., 1 / 3., 1 / 2., 1., 2., 3., 4.]
        self.reference_contrast = contrast_map[
            self.reference_contrast_slider.value()]
        self.on_draw()

    def _sliding_matching_contrast(self):
        contrast_map = [1 / 4., 1 / 3., 1 / 2., 1., 2., 3., 4.]
        self.matching_contrast = contrast_map[
            self.matching_contrast_slider.value()]
        self.on_draw()

    def on_draw(self):
        """ Redraws the figure
        """

        self.axes.clear()

        if type(self.ReferenceVasMap) != type(None):
            width = self.ReferenceVasMap.shape[1]
            height = self.ReferenceVasMap.shape[0]
        elif type(self.MatchingVasMapAfterChange) != type(None):
            width = self.MatchingVasMapAfterChange.shape[1]
            height = self.MatchingVasMapAfterChange.shape[0]
        elif type(self.MatchingVasMap) != type(None):
            width = self.MatchingVasMap.shape[1]
            height = self.MatchingVasMap.shape[0]
        else:
            width = 1344
            height = 1024

        if (type(self.ReferenceVasMap) !=
                type(None)) and (self.radiobutton_reference.isChecked()
                                 or self.radiobutton_both.isChecked()):
            greenChannel = ia.resize_image(self.ReferenceVasMap,
                                           (height, width))
            greenChannel = (
                np.power(ia.array_nor(greenChannel), self.reference_contrast) *
                255).astype(np.uint8)
        else:
            greenChannel = np.zeros((height, width)).astype(np.uint8)

        if (self.radiobutton_matching.isChecked()
                or self.radiobutton_both.isChecked()):
            if type(self.MatchingVasMapAfterChange) != type(None):
                redChannel = ia.resize_image(self.MatchingVasMapAfterChange,
                                             (height, width))
                redChannel = (np.power(ia.array_nor(redChannel),
                                       self.matching_contrast) * 255).astype(
                                           np.uint8)
            elif type(self.MatchingVasMap) != type(None):
                redChannel = ia.resize_image(self.MatchingVasMap,
                                             (height, width))
                redChannel = (np.power(ia.array_nor(redChannel),
                                       self.matching_contrast) * 255).astype(
                                           np.uint8)
            else:
                redChannel = np.zeros((height, width)).astype(np.uint8)
        else:
            redChannel = np.zeros((height, width)).astype(np.uint8)

        blueChannel = np.zeros((height, width)).astype(np.uint8)
        pltImg = cv2.merge((redChannel, greenChannel, blueChannel))

        self.axes.imshow(pltImg)

        self.axes.set_xlim([0, width])
        self.axes.set_ylim([0, height])
        self.axes.invert_yaxis()

        self.canvas.draw()

    def create_main_frame(self):
        self.main_frame = QWidget()

        self.dpi = 300
        self.fig = Figure(dpi=self.dpi, )
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.main_frame)

        self.axes = self.fig.add_axes([0, 0, 1, 1])
        self.axes.set_aspect(1)
        self.axes.set_frame_on(False)
        self.axes.get_xaxis().set_visible(False)
        self.axes.get_yaxis().set_visible(False)

        self.mpl_toolbar = NavigationToolbar2QT(self.canvas, self.main_frame)

        # Other GUI controls

        self.reference_contrast_label = QLabel('reference contrast:')
        self.reference_contrast_slider = QSlider(Qt.Horizontal)
        self.reference_contrast_slider.setMinimumWidth(200)
        self.reference_contrast_slider.setRange(0, 6)
        self.reference_contrast_slider.setValue(3)
        self.matching_contrast_label = QLabel('matching contrast:')
        self.matching_contrast_slider = QSlider(Qt.Horizontal)
        self.matching_contrast_slider.setMinimumWidth(200)
        self.matching_contrast_slider.setMinimumWidth(200)
        self.matching_contrast_slider.setRange(0, 6)
        self.matching_contrast_slider.setValue(3)

        self.radiobutton_reference = QRadioButton('Reference')
        self.radiobutton_matching = QRadioButton('Matching')
        self.radiobutton_both = QRadioButton('Both')
        self.radiobutton_both.setChecked(True)

        self.label_Xoffset = QLabel('X offset:')
        self.spinbox_Xoffset = QSpinBox()
        self.spinbox_Xoffset.setRange(-2000, 2000)
        self.spinbox_Xoffset.setSingleStep(10)
        self.spinbox_Xoffset.setMinimumWidth(60)

        self.label_Yoffset = QLabel('Y offset:')
        self.spinbox_Yoffset = QSpinBox()
        self.spinbox_Yoffset.setRange(-2000, 2000)
        self.spinbox_Yoffset.setSingleStep(10)
        self.spinbox_Yoffset.setMinimumWidth(60)

        self.label_rotation = QLabel('Rotation:')
        self.spinbox_rotation = QSpinBox()
        self.spinbox_rotation.setRange(-180, 180)
        self.spinbox_rotation.setMinimumWidth(60)

        self.label_zoom = QLabel('Zoom:    ')
        self.doubleSpinbox_zoom = QDoubleSpinBox()
        self.doubleSpinbox_zoom.setRange(0.001, 64.)
        self.doubleSpinbox_zoom.setValue(1.)
        self.doubleSpinbox_zoom.setMinimumWidth(60)
        self.doubleSpinbox_zoom.setDecimals(3)

        self.label_RPath = QLabel('Reference Dictionary/Map Path(s):')
        self.textbrowser_RPath = QTextBrowser()
        self.textbrowser_RPath.setMinimumWidth(200)
        self.button_RPath = QPushButton('Get Path')

        self.label_MPath = QLabel('Matching Dictionary/Map Path(s):')
        self.textbrowser_MPath = QTextBrowser()
        self.textbrowser_MPath.setMinimumWidth(200)
        self.button_MPath = QPushButton('Get Path')

        self.button_draw = QPushButton('Draw')
        self.button_draw.setMinimumWidth(100)
        self.button_draw.setFixedHeight(100)

        #
        # Layout with box sizers
        #

        vbox_Reference = QVBoxLayout()
        for R in [self.label_RPath, self.textbrowser_RPath, self.button_RPath]:
            vbox_Reference.addWidget(R)
            vbox_Reference.setAlignment(R, Qt.AlignLeft)

        vbox_Match = QVBoxLayout()
        for M in [self.label_MPath, self.textbrowser_MPath, self.button_MPath]:
            vbox_Match.addWidget(M)
            vbox_Match.setAlignment(M, Qt.AlignLeft)

        vbox_checkbox = QVBoxLayout()
        for P in [
                self.radiobutton_reference, self.radiobutton_matching,
                self.radiobutton_both
        ]:
            vbox_checkbox.addWidget(P)
            vbox_checkbox.setAlignment(P, Qt.AlignLeft)

        vbox_contrast = QVBoxLayout()
        for P in [
                self.reference_contrast_label, self.reference_contrast_slider,
                self.matching_contrast_label, self.matching_contrast_slider
        ]:
            vbox_contrast.addWidget(P)
            vbox_contrast.setAlignment(P, Qt.AlignLeft)

        hbox_Zoom = QHBoxLayout()
        for Z in [self.label_zoom, self.doubleSpinbox_zoom]:
            hbox_Zoom.addWidget(Z)
            hbox_Zoom.setAlignment(Z, Qt.AlignVCenter)

        hbox_Xoffset = QHBoxLayout()
        for X in [self.label_Xoffset, self.spinbox_Xoffset]:
            hbox_Xoffset.addWidget(X)
            hbox_Xoffset.setAlignment(X, Qt.AlignVCenter)

        hbox_Yoffset = QHBoxLayout()
        for Y in [self.label_Yoffset, self.spinbox_Yoffset]:
            hbox_Yoffset.addWidget(Y)
            hbox_Yoffset.setAlignment(Y, Qt.AlignVCenter)

        hbox_Rotation = QHBoxLayout()
        for R in [self.label_rotation, self.spinbox_rotation]:
            hbox_Rotation.addWidget(R)
            hbox_Rotation.setAlignment(R, Qt.AlignVCenter)

        vbox_Adjustment = QVBoxLayout()
        for A in [hbox_Zoom, hbox_Xoffset, hbox_Yoffset, hbox_Rotation]:
            vbox_Adjustment.addLayout(A)
            vbox_Adjustment.setAlignment(A, Qt.AlignLeft)

        vbox_Adjustment2 = QHBoxLayout()
        for A in [vbox_Adjustment, self.button_draw]:
            try:
                vbox_Adjustment2.addLayout(A)
            except Exception:
                vbox_Adjustment2.addWidget(A)
            vbox_Adjustment2.setAlignment(A, Qt.AlignVCenter)

        vbox_right = QVBoxLayout()
        for RT in [
                vbox_Reference, vbox_Match, vbox_contrast, vbox_checkbox,
                vbox_Adjustment2
        ]:
            vbox_right.addLayout(RT)
            vbox_right.setAlignment(RT, Qt.AlignLeft)
        vbox_right.insertSpacing(1, 30)
        vbox_right.insertSpacing(3, 30)
        vbox_right.insertSpacing(5, 30)

        vbox_plot = QVBoxLayout()
        for P in [self.canvas, self.mpl_toolbar]:
            vbox_plot.addWidget(P)

        hbox = QHBoxLayout()
        for L in [vbox_plot, vbox_right]:
            hbox.addLayout(L)
            hbox.setAlignment(L, Qt.AlignVCenter)

        self.main_frame.setLayout(hbox)
        self.setCentralWidget(self.main_frame)

    def create_status_bar(self):
        self.status_text = QLabel("This is a demo")
        self.statusBar().addWidget(self.status_text, 1)

    def create_menu(self):
        self.file_menu = self.menuBar().addMenu("&File")

        save_action = self.create_action("&Save alignment",
                                         shortcut="Ctrl+S",
                                         slot=self.save_alignment_json,
                                         tip="Save the alignment alignment")

        quit_action = self.create_action("&Quit",
                                         slot=self.close,
                                         shortcut="Ctrl+Q",
                                         tip="Close the application")

        self.add_actions(self.file_menu, (save_action, None, quit_action))

        self.help_menu = self.menuBar().addMenu("&Help")
        about_action = self.create_action("&About",
                                          shortcut='F1',
                                          slot=self.on_about,
                                          tip='About the demo')

        self.add_actions(self.help_menu, (about_action, ))

    def add_actions(self, target, actions):
        for action in actions:
            if action is None:
                target.addSeparator()
            else:
                target.addAction(action)

    def create_action(self,
                      text,
                      slot=None,
                      shortcut=None,
                      icon=None,
                      tip=None,
                      checkable=False,
                      signal="triggered()"):
        action = QAction(text, self)
        if icon is not None:
            action.setIcon(QIcon(":/%s.png" % icon))
        if shortcut is not None:
            action.setShortcut(shortcut)
        if tip is not None:
            action.setToolTip(tip)
            action.setStatusTip(tip)
        if slot is not None:
            self.connect(action, SIGNAL(signal), slot)
        if checkable:
            action.setCheckable(True)
        return action
예제 #51
0
    class TransformEditor(QtGui.QMainWindow):
        """GUI to edit transformations.

        .. warning::

            Note that this module requires PyQt4.

        Parameters
        ----------
        transform_manager : TransformManager
            All nodes that are reachable from the base frame will be editable

        frame : string
            Name of the base frame

        xlim : tuple, optional (-1, 1)
            Lower and upper limit for the x position. Defines the range of the
            plot and the range of the slider.

        ylim : tuple, optional (-1, 1)
            Lower and upper limit for the y position. Defines the range of the
            plot and the range of the slider.

        zlim : tuple, optional (-1, 1)
            Lower and upper limit for the z position. Defines the range of the
            plot and the range of the slider.

        s : float, optional (default: 1)
            Scaling of the axis and angle that will be drawn

        figsize : tuple of integers, optional (default: (10, 10))
            Width, height in inches.

        dpi : integer, optional (default: 100)
            Resolution of the figure.

        parent : QtGui.QWidget, optional (default: None)
            Parent widget.

        Attributes
        ----------
        transform_manager : TransformManager
            Result, all frames are expressed in the base frame
        """
        def __init__(self,
                     transform_manager,
                     base_frame,
                     xlim=(-1.0, 1.0),
                     ylim=(-1.0, 1.0),
                     zlim=(-1.0, 1.0),
                     s=1.0,
                     figsize=(10, 10),
                     dpi=100,
                     window_size=(500, 600),
                     parent=None):
            self.app = QtGui.QApplication(sys.argv)

            super(TransformEditor, self).__init__(parent)
            self.transform_manager = self._init_transform_manager(
                transform_manager, base_frame)
            self.base_frame = base_frame
            self.xlim = xlim
            self.ylim = ylim
            self.zlim = zlim
            self.s = s
            self.figsize = figsize
            self.dpi = dpi
            self.window_size = window_size

            self.setWindowTitle("Transformation Editor")
            self.axis = None

            self._create_main_frame()
            self._on_node_changed([
                node for node in self.transform_manager.nodes
                if node != self.base_frame
            ][0])

        def _init_transform_manager(self, transform_manager, frame):
            """Transform all nodes into the reference frame."""
            tm = TransformManager()
            if frame not in transform_manager.nodes:
                raise KeyError("Unknown frame '%s'" % frame)

            for node in transform_manager.nodes:
                try:
                    node2frame = transform_manager.get_transform(node, frame)
                    tm.add_transform(node, frame, node2frame)
                except KeyError:
                    pass  # Frame is not connected to the reference frame

            return tm

        def _create_main_frame(self):
            """Create main frame and layout."""
            self.main_frame = QtGui.QWidget()

            self.frame_editor = PositionEulerEditor(self.base_frame, self.xlim,
                                                    self.ylim, self.zlim)
            self.connect(self.frame_editor, QtCore.SIGNAL("frameChanged()"),
                         self._on_update)

            frame_selection = self._create_frame_selector()

            plot = self._create_plot()

            vbox = QtGui.QVBoxLayout()
            vbox.addWidget(self.frame_editor)
            vbox.addWidget(frame_selection)
            vbox.addWidget(plot)

            main_layout = QtGui.QHBoxLayout()
            main_layout.addLayout(vbox)

            self.main_frame.setLayout(main_layout)
            self.setCentralWidget(self.main_frame)
            self.setGeometry(0, 0, *self.window_size)

        def _create_frame_selector(self):
            frame_selection = QtGui.QComboBox()
            for node in self.transform_manager.nodes:
                if node != self.base_frame:
                    frame_selection.addItem(node)
            self.connect(frame_selection,
                         QtCore.SIGNAL("activated(const QString&)"),
                         self._on_node_changed)
            return frame_selection

        def _create_plot(self):
            plot = QtGui.QWidget()
            canvas_group = QtGui.QGridLayout()
            self.fig = Figure(self.figsize, dpi=self.dpi)
            self.fig.subplots_adjust(left=0, right=1, bottom=0, top=1)
            self.canvas = FigureCanvas(self.fig)
            self.canvas.setParent(self.main_frame)
            canvas_group.addWidget(self.canvas, 1, 0)
            mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)
            canvas_group.addWidget(mpl_toolbar, 2, 0)
            plot.setLayout(canvas_group)
            return plot

        def _on_node_changed(self, node):
            """Slot: manipulatable node changed."""
            self.node = str(node)
            A2B = self.transform_manager.get_transform(self.node,
                                                       self.base_frame)
            self.frame_editor.set_frame(A2B)
            self._plot()

        def _on_update(self):
            """Slot: transformation changed."""
            self.transform_manager.add_transform(self.node, self.base_frame,
                                                 self.frame_editor.A2B)
            self._plot()

        def _plot(self):
            """Draw plot."""
            if self.axis is None:
                elev, azim = 30, 60
            else:
                elev, azim = self.axis.elev, self.axis.azim
                self.fig.delaxes(self.axis)

            self.axis = self.fig.add_subplot(111, projection="3d")
            self.axis.view_init(elev, azim)

            self.axis.set_xlim(self.xlim)
            self.axis.set_ylim(self.ylim)
            self.axis.set_zlim(self.zlim)

            p = self.transform_manager.get_transform(self.node,
                                                     self.base_frame)[:3, 3]
            self.axis.scatter(p[0], p[1], p[2], s=100)
            self.transform_manager.plot_frames_in(self.base_frame,
                                                  ax=self.axis,
                                                  s=self.s)

            self.canvas.draw()

        def show(self):
            """Start GUI."""
            super(TransformEditor, self).show()
            self.app.exec_()
예제 #52
0
class AppForm(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.setWindowTitle('Demo: PyQt with matplotlib')

        self.create_menu()
        self.create_main_frame()
        self.create_status_bar()

        self.textbox.setText('1 2 3 4')
        self.on_draw()

    def save_plot(self):
        file_choices = "PNG (*.png)|*.png"

        path = unicode(
            QFileDialog.getSaveFileName(self, 'Save file', '', file_choices))
        if path:
            self.canvas.print_figure(path, dpi=self.dpi)
            self.statusBar().showMessage('Saved to %s' % path, 2000)

    def on_about(self):
        msg = """ A demo of using PyQt with matplotlib:

         * Use the matplotlib navigation bar
         * Add values to the text box and press Enter (or click "Draw")
         * Show or hide the grid
         * Drag the slider to modify the width of the bars
         * Save the plot to a file using the File menu
         * Click on a bar to receive an informative message
        """
        QMessageBox.about(self, "About the demo", msg.strip())

    def on_pick(self, event):
        # The event received here is of the type
        # matplotlib.backend_bases.PickEvent
        #
        # It carries lots of information, of which we're using
        # only a small amount here.
        #
        box_points = event.artist.get_bbox().get_points()
        msg = "You've clicked on a bar with coords:\n %s" % box_points

        QMessageBox.information(self, "Click!", msg)

    def on_draw(self):
        """ Redraws the figure
        """
        str = 'sss'
        self.data = map(int, str.split())

        x = range(len(self.data))

        # clear the axes and redraw the plot anew
        #
        self.axes.clear()
        self.axes.grid(self.grid_cb.isChecked())

        self.axes.bar(left=x,
                      height=self.data,
                      width=self.slider.value() / 100.0,
                      align='center',
                      alpha=0.44,
                      picker=5)

        self.canvas.draw()

    def create_main_frame(self):
        self.main_frame = QWidget()

        # Create the mpl Figure and FigCanvas objects.
        # 5x4 inches, 100 dots-per-inch
        #
        self.dpi = 100
        self.fig = Figure((5.0, 4.0), dpi=self.dpi)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.main_frame)

        # Since we have only one plot, we can use add_axes
        # instead of add_subplot, but then the subplot
        # configuration tool in the navigation toolbar wouldn't
        # work.
        #
        self.axes = self.fig.add_subplot(111)

        # Bind the 'pick' event for clicking on one of the bars
        #
        self.canvas.mpl_connect('pick_event', self.on_pick)

        # Create the navigation toolbar, tied to the canvas
        #
        self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)

        # Other GUI controls
        #
        self.textbox = QLineEdit()
        self.textbox.setMinimumWidth(200)
        self.connect(self.textbox, SIGNAL('editingFinished ()'), self.on_draw)

        self.draw_button = QPushButton("&Draw")
        self.connect(self.draw_button, SIGNAL('clicked()'), self.on_draw)

        self.grid_cb = QCheckBox("Show &Grid")
        self.grid_cb.setChecked(False)
        self.connect(self.grid_cb, SIGNAL('stateChanged(int)'), self.on_draw)

        slider_label = QLabel('Bar width (%):')
        self.slider = QSlider(Qt.Horizontal)
        self.slider.setRange(1, 100)
        self.slider.setValue(20)
        self.slider.setTracking(True)
        self.slider.setTickPosition(QSlider.TicksBothSides)
        self.connect(self.slider, SIGNAL('valueChanged(int)'), self.on_draw)

        #
        # Layout with box sizers
        #
        hbox = QHBoxLayout()

        for w in [
                self.textbox, self.draw_button, self.grid_cb, slider_label,
                self.slider
        ]:
            hbox.addWidget(w)
            hbox.setAlignment(w, Qt.AlignVCenter)

        vbox = QVBoxLayout()
        vbox.addWidget(self.canvas)
        vbox.addWidget(self.mpl_toolbar)
        vbox.addLayout(hbox)

        self.main_frame.setLayout(vbox)
        self.setCentralWidget(self.main_frame)

    def create_status_bar(self):
        self.status_text = QLabel("This is a demo")
        self.statusBar().addWidget(self.status_text, 1)

    def create_menu(self):
        self.file_menu = self.menuBar().addMenu("&File")

        load_file_action = self.create_action("&Save plot",
                                              shortcut="Ctrl+S",
                                              slot=self.save_plot,
                                              tip="Save the plot")
        quit_action = self.create_action("&Quit",
                                         slot=self.close,
                                         shortcut="Ctrl+Q",
                                         tip="Close the application")

        self.add_actions(self.file_menu, (load_file_action, None, quit_action))

        self.help_menu = self.menuBar().addMenu("&Help")
        about_action = self.create_action("&About",
                                          shortcut='F1',
                                          slot=self.on_about,
                                          tip='About the demo')

        self.add_actions(self.help_menu, (about_action, ))

    def add_actions(self, target, actions):
        for action in actions:
            if action is None:
                target.addSeparator()
            else:
                target.addAction(action)

    def create_action(self,
                      text,
                      slot=None,
                      shortcut=None,
                      icon=None,
                      tip=None,
                      checkable=False,
                      signal="triggered()"):
        action = QAction(text, self)
        if icon is not None:
            action.setIcon(QIcon(":/%s.png" % icon))
        if shortcut is not None:
            action.setShortcut(shortcut)
        if tip is not None:
            action.setToolTip(tip)
            action.setStatusTip(tip)
        if slot is not None:
            self.connect(action, SIGNAL(signal), slot)
        if checkable:
            action.setCheckable(True)
        return action
예제 #53
0
class AppForm(QMainWindow):
    """The main program and UI class."""
    def __init__(self, parent=None):
        self.halo = 0.0
        self.dim = 2
        self.decomp = None
        self.particles = None
        self.datfpath = None
        self.subfpath = None

        QMainWindow.__init__(self, parent)
        self.setWindowTitle('PPM Debug Utility')

        self.create_menu()
        self.create_main_frame()
        self.create_status_bar()

    def load_data(self, subf, datf):
        """Read domain decomp and particles from file and store them."""
        l1 = subf.readline()
        self.dim = float(l1.strip())
        l2 = subf.readline()
        self.halo = float(l2.strip())
        self.decomp = DomainDecomp(self.dim)

        if self.dim == 2:
            for l in subf:
                r = l.strip().split()
                min_sub = [float(r[0]), float(r[1])]
                max_sub = [float(r[2]), float(r[3])]
                proc = int(r[4])
                bc = [int(r[5]), int(r[6]), int(r[7]), int(r[8])]
                self.decomp.addSub(min_sub, max_sub, proc, bc, self.halo)
        elif self.dim == 3:
            for l in subf:
                r = l.strip().split()
                min_sub = [float(r[0]), float(r[1]), float(r[2])]
                max_sub = [float(r[3]), float(r[4]), float(r[5])]
                proc = int(r[6])
                bc = [int(r[7]),int(r[8]),int(r[9]),\
                        int(r[10]),int(r[11]),int(r[12])]
                self.decomp.addSub(min_sub, max_sub, proc, bc, self.halo)

        self.particles = Particles(self.dim)
        if datf:
            if self.dim == 2:
                for l in datf:
                    r = l.strip().split()
                    xp = [float(r[0]), float(r[1])]
                    c = int(r[2])
                    self.particles.add(xp, c)
            elif self.dim == 3:
                for l in datf:
                    r = l.strip().split()
                    try:
                        xp = [float(r[0]), float(r[1]), float(r[2])]
                    except:
                        continue
                    c = int(r[3])
                    self.particles.add(xp, c)

    def on_pick(self):
        """ pick event handler for mpl canvas."""
        pass

    def on_wheel(self, event):
        zoom_factor = 0.8
        if event.step > 0:
            zoom = zoom_factor / event.step
        else:
            zoom = (-1 * event.step) / zoom_factor
        xlim = self.axes.get_xlim()
        ylim = self.axes.get_ylim()
        xdist = xlim[1] - xlim[0]
        ydist = ylim[1] - ylim[0]
        zoom_xdist = (xdist * zoom) / 2.0
        zoom_ydist = (ydist * zoom) / 2.0

        if self.dim == 2:
            zoom_center = (event.xdata, event.ydata)
            new_xlim = (zoom_center[0] - zoom_xdist, \
                        zoom_center[0] + zoom_xdist)
            new_ylim = (zoom_center[1] - zoom_ydist, \
                        zoom_center[1] + zoom_ydist)
        elif self.dim == 3:
            zlim = self.axes.get_zlim3d()
            zdist = (zlim[1] - zlim[0]) * zoom
            zoom_zdist = (zdist * zoom) / 2.0
            zoom_center = [xlim[0]+xdist/2.0, \
                           ylim[0]+ydist/2.0, \
                           zlim[0]+zdist/2.0]
            new_xlim = (zoom_center[0] - zoom_xdist, \
                        zoom_center[0] + zoom_xdist)
            new_ylim = (zoom_center[1] - zoom_ydist, \
                        zoom_center[1] + zoom_ydist)
            new_zlim = (zoom_center[1] - zoom_zdist, \
                        zoom_center[1] + zoom_zdist)
            self.axes.set_zlim3d(new_zlim)

        self.axes.set_xlim(new_xlim)
        self.axes.set_ylim(new_ylim)

        self.canvas.draw()
        if self.dim == 3:
            self.axes.mouse_init()

    def on_draw(self):
        """ Redraws the figure."""
        if self.dim == 3:
            elev = self.axes.elev
            azim = self.axes.azim
        self.axes.clear()
        if self.dim == 2:
            for el in self.decomp.getGhostFaces():
                self.plotgl2(el)
            for el, cpu in self.decomp.getFaces():
                self.plotsub2(el, cpu)
            if len(self.particles.x()) > 0:
                self.plotdat2(self.particles.x(),\
                        self.particles.y(),\
                        self.particles.c)
        elif self.dim == 3:
            for el in self.decomp.getGhostFaces():
                self.plotgl3(el)
            for el, cpu in self.decomp.getFaces():
                self.plotsub3(el, cpu)
            if len(self.particles.x()) > 0:
                self.plotdat3(self.particles.x(),\
                        self.particles.y(),\
                        self.particles.z(),\
                        self.particles.c)
        else:
            pass
        self.axes.set_xlabel('x')
        self.axes.set_ylabel('y')
        if self.dim == 3:
            self.axes.set_zlabel('z')
            self.axes.elev = elev
            self.axes.azim = azim

        self.canvas.draw()
        if self.dim == 3:
            self.axes.mouse_init()

    def on_pressDraw(self):
        subf = None
        datf = None

        try:
            subf = open(self.subfpath, 'r')
        except:
            pass
        try:
            datf = open(self.datfpath, 'r')
        except:
            pass
        if subf is None and datf is None:
            self.statusBar().showMessage('No file chosen', 2000)
            return

        self.statusBar().showMessage('Reloading %s' % self.subfpath, 2000)
        self.load_data(subf, datf)
        subf.close()
        try:
            datf.close()
        except:
            pass
        if self.dim == 2:
            self.axes = self.fig.add_subplot(111)
        else:
            self.axes = Axes3D(self.fig)
        self.on_draw()

    def open_data(self):
        """Open subdomain and data files chosen by the user."""
        file_choices = "*.sub"

        self.subfpath = unicode(
            QFileDialog.getOpenFileName(self, 'Open file', '', file_choices))
        if not self.subfpath:
            return
        self.datfpath = self.subfpath[:-4] + '.dat'

        self.statusBar().showMessage('Opening %s' % self.subfpath, 2000)

        subf = None
        datf = None

        try:
            subf = open(self.subfpath, 'r')
        except:
            pass
        try:
            datf = open(self.datfpath, 'r')
        except:
            pass
        self.load_data(subf, datf)
        subf.close()
        if datf != None:
            datf.close()
        if self.dim == 2:
            self.axes = self.fig.add_subplot(111)
        else:
            self.axes = Axes3D(self.fig)
        self.on_draw()

    def save_plot(self):
        """Save the current plot to a png file."""
        file_choices = "PNG (*.png)|*.png"

        path = unicode(
            QFileDialog.getSaveFileName(self, 'Save file', '', file_choices))
        if path:
            self.canvas.print_figure(path, dpi=self.dpi)
            self.statusBar().showMessage('Saved to %s' % path, 2000)

    def on_about(self):
        msg = """ PPM Debug Utility (c) 2011 MOSAIC Group
        Created by Omar Awile.
        
        """
        QMessageBox.about(self, "About ppmdbg", msg.strip())

    def create_main_frame(self):
        self.main_frame = QWidget()

        # Create the mpl Figure and FigCanvas objects.
        # 5x4 inches, 100 dots-per-inch
        #
        self.dpi = 100
        self.fig = Figure((5.0, 4.0), dpi=self.dpi)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.main_frame)

        # Since we have only one plot, we can use add_axes
        # instead of add_subplot, but then the subplot
        # configuration tool in the navigation toolbar wouldn't
        # work.
        #
        self.axes = self.fig.add_subplot(111)
        #self.axes = Axes3D(self.fig)

        # Bind the 'pick' event for clicking on one of the bars
        #
        self.canvas.mpl_connect('pick_event', self.on_pick)
        self.canvas.mpl_connect('scroll_event', self.on_wheel)

        # Create the navigation toolbar, tied to the canvas
        #
        self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)

        # Other GUI controls
        #
        self.draw_button = QPushButton("&Draw")
        self.connect(self.draw_button, SIGNAL('clicked()'), self.on_pressDraw)

        #
        # Layout with box sizers
        #
        hbox = QHBoxLayout()

        for w in [self.draw_button]:
            hbox.addWidget(w)
            hbox.setAlignment(w, Qt.AlignBottom)

        vbox = QVBoxLayout()
        vbox.addWidget(self.canvas, stretch=1)
        vbox.addWidget(self.mpl_toolbar)
        vbox.addLayout(hbox)

        self.main_frame.setLayout(vbox)
        self.setCentralWidget(self.main_frame)

    def create_menu(self):
        self.file_menu = self.menuBar().addMenu("&File")

        open_data_action = self.create_action("&Open data file",
                                              shortcut="Ctrl+O",
                                              slot=self.open_data,
                                              tip="Open set of debug files")
        save_plot_action = self.create_action("&Save plot",
                                              shortcut="Ctrl+S",
                                              slot=self.save_plot,
                                              tip="Save the plot")
        quit_action = self.create_action("&Quit",
                                         slot=self.close,
                                         shortcut="Ctrl+Q",
                                         tip="Close the application")

        self.add_actions(
            self.file_menu,
            (open_data_action, save_plot_action, None, quit_action))

        self.help_menu = self.menuBar().addMenu("&Help")
        about_action = self.create_action("&About",
                                          shortcut='F1',
                                          slot=self.on_about,
                                          tip='About the demo')

    def create_status_bar(self):
        self.status_text = QLabel("status")
        self.statusBar().addWidget(self.status_text, 1)

    def add_actions(self, target, actions):
        for action in actions:
            if action is None:
                target.addSeparator()
            else:
                target.addAction(action)

    def create_action(self,
                      text,
                      slot=None,
                      shortcut=None,
                      icon=None,
                      tip=None,
                      checkable=False,
                      signal="triggered()"):
        action = QAction(text, self)
        if icon is not None:
            action.setIcon(QIcon(":/%s.png" % icon))
        if shortcut is not None:
            action.setShortcut(shortcut)
        if tip is not None:
            action.setToolTip(tip)
            action.setStatusTip(tip)
        if slot is not None:
            self.connect(action, SIGNAL(signal), slot)
        if checkable:
            action.setCheckable(True)
        return action

    def plotsub3(self, f, cpu):
        """Plot a 3D subdomain."""
        nc = len(cmap.keys())
        for i in range(6):
            try:
                self.axes.plot_surface(f[i][0],f[i][1],f[i][2],alpha=0.05,\
                        color=cmap[cpu%(nc-1)+1])
            except KeyError:
                print "invalid color tag"

    def plotgl3(self, gl):
        """Plot a 3D subdomain ghostlayer."""
        for i in range(6):
            self.axes.plot_surface(gl[i][0],gl[i][1],gl[i][2],alpha=0.02,\
                    color='k',linewidth=0)

    def plotsub2(self, f, cpu):
        """Plot a 2D subdomain."""
        nc = len(cmap.keys())
        try:
            p = Polygon(f,
                        alpha=0.05,
                        color=cmap[cpu % (nc - 1) + 1],
                        linewidth=0)
        except KeyError:
            print "invalid color tag"
        self.axes.add_patch(p)
        p = Polygon(f, fill=False, linewidth=1, ec='k')
        self.axes.add_patch(p)

    def plotgl2(self, gl):
        """Plot a 2D subdomain ghostlayer."""
        p = Polygon(gl, alpha=0.01, color='k')
        self.axes.add_patch(p)
        p = Polygon(gl, fill=False, linewidth=0.4, linestyle='dashed', ec='k')
        self.axes.add_patch(p)

    def plotdat2(self, x, y, tag):
        """Plot 2D particle positions."""
        nc = len(cmap.keys())
        try:
            rx, ry, rtag = zip(*filter(isreal, zip(x, y, tag)))
            self.axes.scatter(rx,ry,s=5,c=[cmap[t%(nc-1)+1] for t in \
                rtag],linewidths=0)
        except KeyError:
            self.statusBar().showMessage('Invalid color tag', 2000)
        except ValueError:
            self.statusBar().showMessage('No real particles', 2000)
        try:
            gx, gy, gtag = zip(*filter(isghost, zip(x, y, tag)))
            self.axes.scatter(gx,gy,s=5,c=[cmap[t] for t in \
                gtag],linewidths=0,alpha=0.6,zorder=10)
        except KeyError:
            self.statusBar().showMessage('Invalid color tag', 2000)
        except ValueError:
            self.statusBar().showMessage('No ghosts', 2000)

    def plotdat3(self, x, y, z, tag):
        """Plot 3D particle positions."""
        nc = len(cmap.keys())
        try:
            rx, ry, rz, rtag = zip(*filter(isreal, zip(x, y, z, tag)))
            self.axes.scatter(rx,ry,rz,s=10,c=[cmap[t%(nc-1)+1] for t in \
                rtag],linewidths=0)
        except KeyError:
            self.statusBar().showMessage('Invalid color tag', 2000)
        except ValueError:
            self.statusBar().showMessage('No real particles', 2000)
        try:
            gx, gy, gz, gtag = zip(*filter(isghost, zip(x, y, z, tag)))
            self.axes.scatter(gx,gy,gz,s=10,c=[cmap[t] for t in \
                gtag],linewidths=0,alpha=0.6)
        except KeyError:
            self.statusBar().showMessage('Invalid color tag', 2000)
        except ValueError:
            self.statusBar().showMessage('No ghosts', 2000)
예제 #54
0
파일: ASLagain.py 프로젝트: Mauvaise/ASL
class QtPyApp():
    def __init__(self, sampleinterval=.01, timewindow=10.):
        self._interval = int(sampleinterval * 1000)

        ## Always start by initializing Qt (only once per application)
        self.app = QApplication(sys.argv)
        #self.setQuitOnLastWindowClosed(False)

        ## Define a top-level widget to hold everything
        self.w_pane = QWidget()
        self.w_pane.setGeometry(300, 300, 1200, 700)

        ## Create some widgets to be placed inside
        self.w_pane.setWindowTitle('ASL Learner')
        self.left_box = QWidget(self.w_pane)
        self.label_pic = QLabel(self.left_box)
        #self.listwidget = QListWidget()
        #self.listwidget.maximumSize(50,100)
        self.left_frame = QFrame(self.w_pane)
        #self.left_frame.setMinimumWidth(50)
        #self.left_frame.setMaximumWidth(100)
        self.label = QLabel(self.w_pane)
        self.fig = Figure((10, 8))
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.w_pane)
        self.canvas.setFocusPolicy(Qt.StrongFocus)
        self.canvas.setFocus()

        ## Create a grid layout to manage the widgets size and position
        self.layout = QGridLayout()
        self.layout_box = QVBoxLayout()
        #self.layout.setColumnMaxWidth(0, 50)
        #
        ## Set pics
        self.hand_over = QPixmap(
            "C:/Users/Tetris/Desktop/HCI 2016/images/leaphoverbest.png")
        self.hand_over = self.hand_over.scaledToHeight(400)
        self.thumbs_up = QPixmap(
            "C:/Users/Tetris/Desktop/HCI 2016/images/thumbsup.png")
        self.thumbs_up = self.thumbs_up.scaledToHeight(200)
        self.label.setPixmap(self.hand_over)
        self.hand_color = 'r'

        ## Add widgets to the layout in their proper positions
        self.layout_box.addWidget(self.label_pic)
        self.layout.addWidget(self.left_box, 1, 0, 1,
                              1)  # list widget goes in bottom-left
        self.layout.addWidget(self.canvas, 0, 1, 5,
                              20)  # plot goes on right side, spanning 3 rows
        self.layout.addWidget(self.label, 0, 1, 5,
                              20)  # plot goes on right side, spanning 3 rows
        #self.layout.addWidget(self.label,0,0)

        ## Display the widget as a new window
        self.w_pane.setLayout(self.layout)
        self.left_box.setLayout(self.layout_box)
        self.left_box.show()
        self.w_pane.show()

        #Initialize Leap
        self.controller = Leap.Controller()
        self.clf = pickle.load(
            open(
                'C:/Users/Tetris/Desktop/HCI 2016/Deliverable 7/userData/classifier.p',
                'r'))
        self.predictedNumArray = []

        # QTimer
        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.updateplot)
        self.timer.start(self._interval)
        self.lines = []
        self.on_draw()
        #
        #self.predictionDeque = collections.deque(30*[0], 30)


#Load clf pickle file
#clf = pickle.load(open('C:/Users/Tetris/Desktop/HCI 2016/Deliverable 7/userData/classifier.p','r'))

    def changeProgramState(self, state):
        if state == 0:
            self.label.setPixmap(self.hand_over)

        elif state == 1:
            self.label.setPixmap(self.thumbs_up)

        elif state == 2:
            self.hand_color = 'g'

    def on_draw(self):
        self.fig.clear()
        self.axes = self.fig.add_subplot(111, projection='3d')

        self.axes.set_xlim(-500, 500)
        self.axes.set_ylim(0, 500)
        self.axes.set_zlim(0, 500)
        #self.fig.axes.get_xaxis().set_ticks([])
        #self.fig.axes.get_yaxis().set_ticks([])
        #self.fig.axes.get_zaxis().set_ticks([])
        #self.axes.plot(self.x, self.y, 'ro')
        #self.axes.imshow(self.data, interpolation='nearest')
        #self.axes.plot([1,2,3])
        self.axes.view_init(azim=90)
        self.canvas.draw()

    def CenterData(testData):
        print "centering"
        allXCoordinates = testData[0, ::3]
        meanValue = allXCoordinates.mean()
        testData[0, ::3] = allXCoordinates - meanValue

        allYCoordinates = testData[0, 1::3]
        meanValue = allYCoordinates.mean()
        testData[0, 1::3] = allYCoordinates - meanValue

        allZCoordinates = testData[0, 2::3]
        meanValue = allZCoordinates.mean()
        testData[0, 2::3] = allZCoordinates - meanValue

        return (testData)

        self.changeProgramState(0)

    def updateplot(self):
        frame = self.controller.frame()

        #frame_center = frame.interaction_box.center
        #
        #if frame.hands.is_empty:
        #    self.changeProgramState(0)

        if not frame.hands.is_empty:
            self.changeProgramState(1)

            k = 0
            testData = np.zeros((1, 30), dtype='f')

            while (len(self.lines) > 0):  #
                ln = self.lines.pop()
                ln.pop(0).remove()
                del ln
                ln = []
            #self.w_pane.clear()

            hand = frame.hands[0]
            fingers = hand.fingers

            hand_center = hand.palm_position
            hand_x = hand_center[0]
            hand_z = hand_center[2]
            print hand_x, hand_z

            if abs(hand_x) < 30 and abs(hand_z) < 30:
                self.changeProgramState(2)

            else:
                self.hand_color = 'r'

            for i in range(0, 5):
                finger = fingers[i]

                for j in range(0, 4):
                    bone = finger.bone(j)
                    tip = bone.next_joint
                    base = bone.prev_joint
                    xBase = base[0]
                    yBase = base[1]
                    zBase = base[2]
                    xTip = tip[0]
                    yTip = tip[1]
                    zTip = tip[2]

                    if ((j == 0) or (j == 3)):
                        testData[0, k] = xTip
                        testData[0, k + 1] = yTip
                        testData[0, k + 2] = zTip
                        k = k + 3

                #    allXCoordinates = testData[0,::3]
                #    meanValue = allXCoordinates.mean()
                #    testData[0,::3] = allXCoordinates - meanValue
                #
                #
                #    allYCoordinates = testData[0,1::3]
                #    meanValue = allYCoordinates.mean()
                #    testData[0,1::3] = allYCoordinates - meanValue
                #
                #
                #    allZCoordinates = testData[0,2::3]
                #    meanValue = allZCoordinates.mean()
                #    testData[0,2::3] = allZCoordinates - meanValue

                    predictedNum = self.clf.predict(testData)
                    #self.predictionDeque.append(predictedNum)
                    #print predictedNum
                    #    self.predictedNumArray.append(int(predictedNum))
                    #    #print mode(self.predictedNumArray)
                    #    numpred = len(self.predictedNumArray)
                    #    if numpred >= 20:
                    #        self.predictedNumArray = self.predictedNumArray[-20:]
                    #
                    #    #print self.predictedNumArray
                    ##for i in range(20):
                    ##    self.predictedNumArray.append(predictedNum)
                    ##    print "got to here"
                    ##    if len(self.predictedNumArray) > 20:
                    ##        self.predictedNumArray[:] = []
                    ##
                    #    print mode(self.predictedNumArray)

                    #print mode(predictionDeque)

                    self.lines.append(
                        self.axes.plot([-xBase, -xTip], [zBase, zTip],
                                       [yBase, yTip], self.hand_color))

            self.canvas.draw()

    def run(self):
        self.app.exec_()
예제 #55
0
class plotWindow(QtGui.QMainWindow):
    def __init__(self, fpath, projectName):
        QtGui.QMainWindow.__init__(self)
        self.fpath = fpath  #+".cir.out"
        self.projectName = projectName
        self.obj_appconfig = Appconfig()
        print "Path : ", self.fpath
        print "Project Name : ", self.projectName
        self.obj_appconfig.print_info('Ngspice simulation is called : ' +
                                      self.fpath)
        self.obj_appconfig.print_info('PythonPlotting is called : ' +
                                      self.fpath)
        self.combo = []
        self.combo1 = []
        self.combo1_rev = []
        #Creating Frame
        self.createMainFrame()

    def createMainFrame(self):
        self.mainFrame = QtGui.QWidget()
        self.dpi = 100
        self.fig = Figure((7.0, 7.0), dpi=self.dpi)
        #Creating Canvas which will figure
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.mainFrame)
        self.axes = self.fig.add_subplot(111)
        self.navToolBar = NavigationToolbar(self.canvas, self.mainFrame)

        #LeftVbox hold navigation tool bar and canvas
        self.left_vbox = QtGui.QVBoxLayout()
        self.left_vbox.addWidget(self.navToolBar)
        self.left_vbox.addWidget(self.canvas)

        #right VBOX is main Layout which hold right grid(bottom part) and top grid(top part)
        self.right_vbox = QtGui.QVBoxLayout()
        self.right_grid = QtGui.QGridLayout()
        self.top_grid = QtGui.QGridLayout()

        #Get DataExtraction Details
        self.obj_dataext = DataExtraction()
        self.plotType = self.obj_dataext.openFile(self.fpath)

        self.obj_dataext.computeAxes()
        self.a = self.obj_dataext.numVals()

        self.chkbox = []

        ########### Generating list of colors :
        self.full_colors = [
            'r', 'b', 'g', 'y', 'c', 'm', 'k'
        ]  #,(0.4,0.5,0.2),(0.1,0.4,0.9),(0.4,0.9,0.2),(0.9,0.4,0.9)]
        self.color = []
        for i in range(0, self.a[0] - 1):
            if i % 7 == 0:
                self.color.append(self.full_colors[0])
            elif (i - 1) % 7 == 0:
                self.color.append(self.full_colors[1])
            elif (i - 2) % 7 == 0:
                self.color.append(self.full_colors[2])
            elif (i - 3) % 7 == 0:
                self.color.append(self.full_colors[3])
            elif (i - 4) % 7 == 0:
                self.color.append(self.full_colors[4])
            elif (i - 5) % 7 == 0:
                self.color.append(self.full_colors[5])
            elif (i - 6) % 7 == 0:
                self.color.append(self.full_colors[6])

        ###########Color generation ends here

        #Total number of voltage source
        self.volts_length = self.a[1]
        self.analysisType = QtGui.QLabel()
        self.top_grid.addWidget(self.analysisType, 0, 0)
        self.listNode = QtGui.QLabel()
        self.top_grid.addWidget(self.listNode, 1, 0)
        self.listBranch = QtGui.QLabel()
        self.top_grid.addWidget(self.listBranch, self.a[1] + 2, 0)
        for i in range(0, self.a[1]):  #a[0]-1
            self.chkbox.append(QtGui.QCheckBox(self.obj_dataext.NBList[i]))
            self.chkbox[i].setStyleSheet('color')
            self.chkbox[i].setToolTip('<b>Check To Plot</b>')
            self.top_grid.addWidget(self.chkbox[i], i + 2, 0)
            self.colorLab = QtGui.QLabel()
            self.colorLab.setText('____')
            self.colorLab.setStyleSheet(
                self.colorName(self.color[i]) + '; font-weight = bold;')
            self.top_grid.addWidget(self.colorLab, i + 2, 1)

        for i in range(self.a[1], self.a[0] - 1):  #a[0]-1
            self.chkbox.append(QtGui.QCheckBox(self.obj_dataext.NBList[i]))
            self.chkbox[i].setToolTip('<b>Check To Plot</b>')
            self.top_grid.addWidget(self.chkbox[i], i + 3, 0)
            self.colorLab = QtGui.QLabel()
            self.colorLab.setText('____')
            self.colorLab.setStyleSheet(
                self.colorName(self.color[i]) + '; font-weight = bold;')
            self.top_grid.addWidget(self.colorLab, i + 3, 1)

        self.clear = QtGui.QPushButton("Clear")
        self.warnning = QtGui.QLabel()
        self.funcName = QtGui.QLabel()
        self.funcExample = QtGui.QLabel()

        self.plotbtn = QtGui.QPushButton("Plot")
        self.plotbtn.setToolTip('<b>Press</b> to Plot')
        self.text = QtGui.QLineEdit()
        self.funcLabel = QtGui.QLabel()
        self.palette1 = QtGui.QPalette()
        self.palette2 = QtGui.QPalette()
        self.plotfuncbtn = QtGui.QPushButton("Plot Function")
        self.plotfuncbtn.setToolTip('<b>Press</b> to Plot the function')

        self.palette1.setColor(QtGui.QPalette.Foreground, QtCore.Qt.blue)
        self.palette2.setColor(QtGui.QPalette.Foreground, QtCore.Qt.red)
        self.funcName.setPalette(self.palette1)
        self.funcExample.setPalette(self.palette2)

        self.right_vbox.addLayout(self.top_grid)
        self.right_vbox.addWidget(self.plotbtn)

        self.right_grid.addWidget(self.funcLabel, 1, 0)
        self.right_grid.addWidget(self.text, 1, 1)
        self.right_grid.addWidget(self.plotfuncbtn, 2, 1)
        self.right_grid.addWidget(self.clear, 2, 0)
        self.right_grid.addWidget(self.warnning, 3, 0)
        self.right_grid.addWidget(self.funcName, 4, 0)
        self.right_grid.addWidget(self.funcExample, 4, 1)
        self.right_vbox.addLayout(self.right_grid)

        self.hbox = QtGui.QHBoxLayout()
        self.hbox.addLayout(self.left_vbox)
        self.hbox.addLayout(self.right_vbox)

        self.widget = QtGui.QWidget()
        self.widget.setLayout(self.hbox)  #finalvbox
        self.scrollArea = QtGui.QScrollArea()
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setWidget(self.widget)

        self.finalhbox = QtGui.QHBoxLayout()
        self.finalhbox.addWidget(self.scrollArea)

        self.mainFrame.setLayout(self.finalhbox)
        self.showMaximized()

        self.listNode.setText("<font color='indigo'>List of Nodes:</font>")
        self.listBranch.setText(
            "<font color='indigo'>List of Branches:</font>")
        self.funcLabel.setText("<font color='indigo'>Function:</font>")
        self.funcName.setText("<font color='indigo'>Examples:</font>\
                <br><br>Addition:<br>Subtraction:<br>Multiplication:<br>Division:<br>Comparison:"
                              )
        self.funcExample.setText(
            "\n\nV(1) + V(2)\nV(1) - V(2)\nV(1) * V(2)\nV(1) / V(2)\nV(1) vs V(2)"
        )

        #Connecting to plot and clear function
        self.connect(self.clear, QtCore.SIGNAL('clicked()'), self.pushedClear)
        self.connect(self.plotfuncbtn, QtCore.SIGNAL('clicked()'),
                     self.pushedPlotFunc)

        if self.plotType[0] == 0:
            self.analysisType.setText("<b>AC Analysis</b>")
            if self.plotType[1] == 1:
                self.connect(self.plotbtn, QtCore.SIGNAL('clicked()'),
                             self.onPush_decade)
            else:
                self.connect(self.plotbtn, QtCore.SIGNAL('clicked()'),
                             self.onPush_ac)

        elif self.plotType[0] == 1:
            self.analysisType.setText("<b>Transient Analysis</b>")
            self.connect(self.plotbtn, QtCore.SIGNAL('clicked()'),
                         self.onPush_trans)

        else:
            self.analysisType.setText("<b>DC Analysis</b>")
            self.connect(self.plotbtn, QtCore.SIGNAL('clicked()'),
                         self.onPush_dc)

        self.setCentralWidget(self.mainFrame)

    def pushedClear(self):
        #print "Calling Clear Canvas function"
        self.text.clear()
        self.axes.cla()
        self.canvas.draw()
        QtCore.SLOT('quit()')

    def pushedPlotFunc(self):
        #print "Calling Plot function"
        self.parts = str(self.text.text())
        self.parts = self.parts.split(" ")
        #print "Parts :",self.parts

        if self.parts[len(self.parts) - 1] == '':
            self.parts = self.parts[0:-1]

        self.values = self.parts
        self.comboAll = []
        self.axes.cla()

        self.plotType2 = self.obj_dataext.openFile(self.fpath)

        if len(self.parts) <= 2:
            self.warnning.setText("Too few arguments!\nRefer syntax below!")
            QtGui.QMessageBox.about(
                self, "Warning!!",
                "Too Few Arguments/SYNTAX Error!\n Refer Examples")
        else:
            self.warnning.setText("")

        a = []
        finalResult = []
        p = 0

        for i in range(len(self.parts)):
            #print "I",i
            if i % 2 == 0:
                #print "I'm in:"
                for j in range(len(self.obj_dataext.NBList)):
                    if self.parts[i] == self.obj_dataext.NBList[j]:
                        #print "I got you:",self.parts[i]
                        a.append(j)

        if len(a) != len(self.parts) // 2 + 1:
            QtGui.QMessageBox.about(
                self, "Warning!!",
                "One of the operands doesn't belong to the above list of Nodes!!"
            )

        for i in a:
            self.comboAll.append(self.obj_dataext.y[i])

        for i in range(len(a)):

            if a[i] == len(self.obj_dataext.NBList):
                QtGui.QMessageBox.about(
                    self, "Warning!!",
                    "One of the operands doesn't belong to the above list!!")
                self.warnning.setText(
                    "<font color='red'>To Err Is Human!<br>One of the operands doesn't belong to the above list!!</font>"
                )

        if self.parts[1] == 'vs':
            if len(self.parts) > 3:
                self.warnning.setText("Enter two operands only!!")
                QtGui.QMessageBox.about(self, "Warning!!",
                                        "Recheck the expression syntax!")

            else:
                self.axes.cla()

                for i in range(len(self.obj_dataext.y[a[0]])):
                    self.combo.append(self.obj_dataext.y[a[0]][i])
                    self.combo1.append(self.obj_dataext.y[a[1]][i])

                self.axes.plot(self.combo,
                               self.combo1,
                               c=self.color[1],
                               label=str(2))  #_rev

                if max(a) < self.volts_length:
                    self.axes.set_ylabel('Voltage(V)-->')
                    self.axes.set_xlabel('Voltage(V)-->')
                else:
                    self.axes.set_ylabel('Current(I)-->')
                    self.axes.set_ylabel('Current(I)-->')

        elif max(a) >= self.volts_length and min(a) < self.volts_length:
            QtGui.QMessageBox.about(self, "Warning!!",
                                    "Do not combine Voltage and Current!!")

        else:
            for j in range(len(self.comboAll[0])):
                for i in range(len(self.values)):
                    if i % 2 == 0:
                        self.values[i] = str(self.comboAll[i // 2][j])
                        re = " ".join(self.values[:])
                try:
                    finalResult.append(eval(re))
                except ArithmeticError:
                    QtGui.QMessageBox.about(self, "Warning!!",
                                            "Dividing by zero!!")

            if self.plotType2[0] == 0:
                #self.setWindowTitle('AC Analysis')
                if self.plotType2[1] == 1:
                    self.axes.semilogx(self.obj_dataext.x,
                                       finalResult,
                                       c=self.color[0],
                                       label=str(1))
                else:
                    self.axes.plot(self.obj_dataext.x,
                                   finalResult,
                                   c=self.color[0],
                                   label=str(1))

                self.axes.set_xlabel('freq-->')

                if max(a) < self.volts_length:
                    self.axes.set_ylabel('Voltage(V)-->')
                else:
                    self.axes.set_ylabel('Current(I)-->')

            elif self.plotType2[0] == 1:
                #self.setWindowTitle('Transient Analysis')
                self.axes.plot(self.obj_dataext.x,
                               finalResult,
                               c=self.color[0],
                               label=str(1))
                self.axes.set_xlabel('time-->')
                if max(a) < self.volts_length:
                    self.axes.set_ylabel('Voltage(V)-->')
                else:
                    self.axes.set_ylabel('Current(I)-->')

            else:
                #self.setWindowTitle('DC Analysis')
                self.axes.plot(self.obj_dataext.x,
                               finalResult,
                               c=self.color[0],
                               label=str(1))
                self.axes.set_xlabel('I/P Voltage-->')
                if max(a) < self.volts_length:
                    self.axes.set_ylabel('Voltage(V)-->')
                else:
                    self.axes.set_ylabel('Current(I)-->')

        self.axes.grid(True)
        self.canvas.draw()
        self.combo = []
        self.combo1 = []
        self.combo1_rev = []

    def onPush_decade(self):
        #print "Calling on push Decade"
        boxCheck = 0
        self.axes.cla()

        for i, j in zip(self.chkbox, range(len(self.chkbox))):
            if i.isChecked():
                boxCheck += 1
                self.axes.semilogx(self.obj_dataext.x,
                                   self.obj_dataext.y[j],
                                   c=self.color[j],
                                   label=str(j + 1))
                self.axes.set_xlabel('freq-->')
                if j < self.volts_length:
                    self.axes.set_ylabel('Voltage(V)-->')
                else:
                    self.axes.set_ylabel('Current(I)-->')

                self.axes.grid(True)
        if boxCheck == 0:
            QtGui.QMessageBox.about(
                self, "Warning!!", "Please select at least one Node OR Branch")
        self.canvas.draw()

    def onPush_ac(self):
        #print "Calling on push ac"
        self.axes.cla()
        boxCheck = 0
        for i, j in zip(self.chkbox, range(len(self.chkbox))):
            if i.isChecked():
                boxCheck += 1
                self.axes.plot(self.obj_dataext.x,
                               self.obj_dataext.y[j],
                               c=self.color[j],
                               label=str(j + 1))
                self.axes.set_xlabel('freq-->')
                if j < self.volts_length:
                    self.axes.set_ylabel('Voltage(V)-->')
                else:
                    self.axes.set_ylabel('Current(I)-->')
                self.axes.grid(True)
        if boxCheck == 0:
            QtGui.QMessageBox.about(
                self, "Warning!!", "Please select at least one Node OR Branch")
        self.canvas.draw()

    def onPush_trans(self):
        #print "Calling on push trans"
        self.axes.cla()
        boxCheck = 0
        for i, j in zip(self.chkbox, range(len(self.chkbox))):
            if i.isChecked():
                boxCheck += 1
                self.axes.plot(self.obj_dataext.x,
                               self.obj_dataext.y[j],
                               c=self.color[j],
                               label=str(j + 1))
                self.axes.set_xlabel('time-->')
                if j < self.volts_length:
                    self.axes.set_ylabel('Voltage(V)-->')
                else:
                    self.axes.set_ylabel('Current(I)-->')
                self.axes.grid(True)
        if boxCheck == 0:
            QtGui.QMessageBox.about(
                self, "Warning!!", "Please select at least one Node OR Branch")
        self.canvas.draw()

    def onPush_dc(self):
        #print "Calling on push dc"
        boxCheck = 0
        self.axes.cla()
        for i, j in zip(self.chkbox, range(len(self.chkbox))):
            if i.isChecked():
                boxCheck += 1
                self.axes.plot(self.obj_dataext.x,
                               self.obj_dataext.y[j],
                               c=self.color[j],
                               label=str(j + 1))
                self.axes.set_xlabel('Voltage Sweep(V)-->')

                if j < self.volts_length:
                    self.axes.set_ylabel('Voltage(V)-->')
                else:
                    self.axes.set_ylabel('Current(I)-->')
                self.axes.grid(True)
        if boxCheck == 0:
            QtGui.QMessageBox.about(
                self, "Warning!!", "Please select atleast one Node OR Branch")
        self.canvas.draw()

    def colorName(self, letter):
        return {
            'r': 'color:red',
            'b': 'color:blue',
            'g': 'color:green',
            'y': 'color:yellow',
            'c': 'color:cyan',
            'm': 'color:magenta',
            'k': 'color:black'
        }[letter]
예제 #56
0
class plothistogram(QFrame):
   def __init__(self, parent):
      print "__init__()"       # DEBUG
      QFrame.__init__(self)
      
      self.parent=parent
      #self.setModal(False)

      self.data1=self.parent.y1   # get plotted y values from solutions plot
      self.data2=self.parent.y2   # get plotted y values from parameter plot
      self.nbins=50               # default=50 bins
      self.parameter=self.parent.parent.parametersComboBox.currentText()
      self.data=self.parent.y2    # set histogram to solver parameter data

      #print "self.data = ", self.data   # DEBUG

      # Create canvas for plotting
      self.rim=0.1
      self.fig = Figure((5, 4), dpi=100)
      self.canvas = FigureCanvas(self.fig)
      self.canvas.setParent(self)
      self.fig.subplots_adjust(left=self.rim, right=1.0-self.rim, top=1.0-self.rim, bottom=self.rim)  # set a small rim

      self.mpl_toolbar = NavigationToolbar(self.canvas, self)
      self.mpl_toolbar.show()   # first hide the toolbar
      
      self.ax=self.fig.add_subplot(111)
      
      self.createWidgets()
      self.createLayout()
      self.connectSignals()
      self.setLabels()
      self.plot()
      
   def createWidgets(self):
      #print "createWidgets()"     # DEBUG
      
      self.closeButton=QPushButton("Close")
      self.closeButton.setToolTip("close this plotwindow")
      self.closeButton.show()

      self.histogramBinSpin=QSpinBox()            # spinbox for histogram binsize
      self.histogramBinSpin.setToolTip("Number of bins to histogram into")
      self.histogramBinSpin.setMinimum(5)
      #self.histogramBinSpin.setMaximum(150)        # set a maximum of 150 (reasonable?)
      self.histogramBinSpin.setSingleStep(10)       # allow only stepping by 10
      self.histogramBinSpin.setMaximumWidth(120)
      self.histogramBinSpin.setMinimumHeight(25)
      self.histogramBinSpin.setValue(self.nbins)
      self.histogramBinSpin.show()
      self.histogramBinLabel=QLabel("Bins")
      
      self.normedCheckBox=QCheckBox()
      self.normedCheckLabel=QLabel("Normalize")
      self.normedCheckBox.setToolTip("Normalize histogram")
      self.normedCheckBox.show()
      #self.dpi = 100
      
      self.dataComboBox=QComboBox()
      self.dataComboBox.addItem(self.parent.parent.parmValueComboBox.currentText())
      self.dataComboBox.addItem(self.parent.parent.parametersComboBox.currentText())
      self.dataComboBox.setMaximumWidth(120)
      self.dataComboBox.setMinimumHeight(25)
      self.dataComboBox.setCurrentIndex(1)

   def createLayout(self):
      #print "createLayout()"      # DEBUG
      
      self.normedLayout=QHBoxLayout()
      self.normedLayout.addWidget(self.normedCheckBox)
      self.normedLayout.addWidget(self.normedCheckLabel)
      self.buttonLayout=QVBoxLayout()
      self.plotLayout=QVBoxLayout()
      self.mainLayout=QHBoxLayout()
      self.buttonLayout.addLayout(self.normedLayout)
      #self.buttonLayout.addWidget(self.normedCheckBox)
      #self.buttonLayout.addWidget(self.normedCheckLabel)
      self.buttonLayout.addWidget(self.histogramBinSpin)
      self.buttonLayout.addWidget(self.dataComboBox)
      self.buttonLayout.insertStretch(-1)
      self.buttonLayout.addWidget(self.closeButton)
      self.plotLayout.addWidget(self.canvas)
      self.plotLayout.addWidget(self.mpl_toolbar)
      self.mainLayout.addLayout(self.buttonLayout)
      self.mainLayout.addLayout(self.plotLayout)
      
      self.setLayout(self.mainLayout)

   def setLabels(self):
      self.ax.xlabel="Bin"
      self.ax.ylabel="N"
      
   def setTitle(self):
      #=self.parent.parametersComboBox.currentText()
      #self.ax.xlabel=self.parmValueComboBox.currentText()
      #self.ax.xlabel="Bin No."
      #self.ax.ylabel="n"
      self.ax.title=self.parent.parent.parametersComboBox.currentText()
      
   def connectSignals(self):
      self.connect(self.closeButton, SIGNAL('clicked()'), SLOT('close()'))
      self.connect(self.histogramBinSpin, SIGNAL('valueChanged(int)'), self.on_changeBinSpin)      
      self.connect(self.normedCheckBox, SIGNAL('stateChanged(int)'), self.on_normedCheckBox)
      self.connect(self.dataComboBox, SIGNAL('currentIndexChanged(int)'), self.on_data)
      
   def on_changeBinSpin(self):
      self.nbins=self.histogramBinSpin.value()      
      # create histogram
      #n, bins = np.histogram(self.data, self.histogramBinSpin.value(), normed=self.normedCheckBox.isChecked())
      #hist, bins=np.histogram(self.data, self.nbins, normed=self.normedCheckBox.isChecked())
      
      #print "len(bins) = ", len(bins), " len(n) = ", len(n)
      
      #self.ax.plot(bins[1:], n, color='red')
      #self.canvas.draw()
      #self.ax.legend()
      #self.fig.draw_idle()        # redraw (preferably when idle)
      self.plot()

   def on_normedCheckBox(self):
      self.plot()

   def on_data(self):
      print "on_data()"       # DEBUG
      if self.dataComboBox.currentText()==self.parent.parent.parametersComboBox.currentText():
          self.data=self.data2
      else:
          self.data=self.data1
      self.plot()

   def plot(self):
      self.fig.delaxes(self.ax)            # delete all axes first
      self.ax=self.fig.add_subplot(111)
      
      n, bins = np.histogram(self.data, self.histogramBinSpin.value(), normed=self.normedCheckBox.isChecked())

      self.xmin=bins[1]
      self.xmax=bins[len(bins)-1]
      self.ax.bar(bins[1:], n, color='blue', width=(self.xmax-self.xmin)/len(bins))
      self.canvas.draw()
예제 #57
0
class QArkMplPlotWidget(QtGui.QWidget):
    """
    """
    VIEW_MODE__PLOT = 1
    VIEW_MODE__IMAGESHOW = 2
    VIEW_MODE__MATRIXSHOW = 4
    VIEW_MODE__WIREFRAME = 8
    VIEW_MODE__SURFACE = 16
    VIEW_MODE__COLORMESH = 32

    def __init__(self, parent=None):
        """
        """
        super(QArkMplPlotWidget, self).__init__(parent=parent)
        self.initUi()
        self.initConnection()
        self.t_axes = {}

    def initUi(self):
        """
        """
        self.setObjectName(_fromUtf8("qArkMplPlotWidget"))
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        vbox = QtGui.QVBoxLayout()

        #--------------------------------------------------------------------------------
        # Plot zone
        #--------------------------------------------------------------------------------
        self.dpi = 70
        #self.figure = plt.Figure((10.0, 10.0), dpi=self.dpi)
        self.figure = plt.figure()
        self.canvas = FigureCanvas(self.figure)
        print(self)
        self.canvas.setParent(self)
        self.mpl_toolbar = NavigationToolbar(self.canvas, self)
        vbox.addWidget(self.canvas)
        vbox.addWidget(self.mpl_toolbar)
        self.setLayout(vbox)

    def initConnection(self):
        """
        """
        pass

    def initAxe(self, _u_c, _u_mode):
        if _u_mode is self.__class__.VIEW_MODE__PLOT:
            self.t_axes[_u_c] = self.fig.add_subplot(_u_c)
        elif _u_mode is self.__class__.VIEW_MODE__IMAGESHOW:
            self.t_axes[_u_c] = self.fig.add_subplot(_u_c)
        elif _u_mode is self.__class__.VIEW_MODE__MATRIXSHOW:
            self.t_axes[_u_c] = self.fig.add_subplot(_u_c)
        elif _u_mode is self.__class__.VIEW_MODE__WIREFRAME:
            self.t_axes[_u_c] = self.fig.add_subplot(_u_c, projection='3d')
        elif _u_mode is self.__class__.VIEW_MODE__SURFACE:
            self.t_axes[_u_c] = self.fig.add_subplot(_u_c, projection='3d')
        elif _u_mode is self.__class__.VIEW_MODE__COLORMESH:
            self.t_axes[_u_c] = self.fig.add_subplot(_u_c)
        return self.t_axes[_u_c]

    def enableCurrentFigure(self):
        plt.figure(self.figure.number)

    def displayPlot(self):
        self.canvas.draw()

    def savePlot(self, _s_filename):
        self.canvas.print_figure(_s_filename)

    def setPlotter(self, _o_plotter):
        self.o_plotter = _o_plotter
        self.enableCurrentFigure()
        self.o_plotter.setFigure(self.figure)
        self.o_plotter.plot()
        self.displayPlot()

    @QtCore.pyqtSlot()
    def updatePlot(self):
        self.o_plotter.plot()
        self.displayPlot()
class AppForm(QMainWindow):
    def __init__(self, parent=None):
        # try:
        #     self.cpus = multiprocessing.cpu_count()
        # except NotImplementedError:
        #     self.cpus = 2   # arbitrary default

        # sys.stdout = EmittedStream(textWritten=self.normalOutputWritten)
        # sys.stderr = EmittedStream(textWritten=self.normalOutputWritten)
        QMainWindow.__init__(self, parent)
        self.showMaximized()

        self.create_menu()
        self.create_main_frame()
        self.create_status_bar()
        self.draw_results_1_7125()
        self.draw_results_2_417()

    def create_status_bar(self):
        self.status_text = QLabel(
            u"Расчет интерферометра.\nВычисление оптической разности хода лучей")
        self.statusBar().addWidget(self.status_text, 1)
    def add_actions(self, target, actions):
        for action in actions:
            if action is None:
                target.addSeparator()
            else:
                target.addAction(action)
    def on_about(self):
        msg = u""" Приложение - результаты моделирования интерферометра
        Автор: Яворский Александр ([email protected])
        Исходники: https://[email protected]/yavorskiy-av/plotting_of_3d_surfaces_by_dot_coords
        """
        #Встраивание matplotlib в GUI повзаимствовано от Eli Bendersky ([email protected])
        QMessageBox.about(self, u"О приложении 'Результаты матмоделирования иф-ра'", msg.strip())

    def save_plot(self):
        file_choices = "PNG (*.png)|*.png"

        path = unicode(QFileDialog.getSaveFileName(self,
                                                   u'Сохранить файл', '',
                                                   file_choices))
        if path:
            self.canvas.print_figure(path, dpi=self.dpi)
            self.statusBar().showMessage(u'Сохранено в %s' % path, 2000)

    def create_menu(self):
        self.file_menu = self.menuBar().addMenu(u"&Файл")

        load_file_action = self.create_action(u"&Сохранить построение",
                                              shortcut="Ctrl+S", slot=self.save_plot,
                                              tip=u"Сохранить рисунок")
        quit_action = self.create_action(u"&Выйти", slot=self.close,
                                         shortcut="Ctrl+Q", tip="Close the application")

        self.add_actions(self.file_menu,
                         (load_file_action, None, quit_action))

        self.help_menu = self.menuBar().addMenu(u"&Помощь")
        about_action = self.create_action(u"&О приложении",
                                          shortcut='F1', slot=self.on_about,
                                          tip=u'О приложении')

        self.add_actions(self.help_menu, (about_action,))
    def draw_results_1_7125(self):
        self.axes.clear()
        X = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             1e3, 1e3, 1e3, 1e3, 1e3, 1e3, 1e3, 1e3, 1e3, 1e3,
             5e3, 5e3, 5e3, 5e3, 5e3, 5e3, 5e3, 5e3, 5e3, 5e3,
             1e4, 1e4, 1e4, 1e4, 1e4, 1e4, 1e4, 1e4, 1e4, 1e4,
             1.5e4, 1.5e4, 1.5e4, 1.5e4, 1.5e4, 1.5e4, 1.5e4, 1.5e4, 1.5e4, 1.5e4,
             2e4, 2e4, 2e4, 2e4, 2e4, 2e4, 2e4, 2e4, 2e4, 2e4,
             2.5e4, 2.5e4, 2.5e4, 2.5e4, 2.5e4, 2.5e4, 2.5e4, 2.5e4, 2.5e4, 2.5e4,
             3e4, 3e4, 3e4, 3e4, 3e4, 3e4, 3e4, 3e4, 3e4, 3e4,
             5e4, 5e4, 5e4, 5e4, 5e4, 5e4, 5e4, 5e4, 5e4, 5e4,
             1e5, 1e5, 1e5, 1e5, 1e5, 1e5, 1e5, 1e5, 1e5, 1e5,
             1.5e5, 1.5e5, 1.5e5, 1.5e5, 1.5e5, 1.5e5, 1.5e5, 1.5e5, 1.5e5, 1.5e5,
             2e5, 2e5, 2e5, 2e5, 2e5, 2e5, 2e5, 2e5, 2e5, 2e5,
             2.5e5, 2.5e5, 2.5e5, 2.5e5, 2.5e5, 2.5e5, 2.5e5, 2.5e5, 2.5e5, 2.5e5,
             3e5, 3e5, 3e5, 3e5, 3e5, 3e5, 3e5, 3e5, 3e5, 3e5]
        Y = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45.0818,
             0, 5, 10, 15, 20, 25, 30, 35, 40, 45.0818,
             0, 5, 10, 15, 20, 25, 30, 35, 40, 45.0818,
             0, 5, 10, 15, 20, 25, 30, 35, 40, 45.0818,
             0, 5, 10, 15, 20, 25, 30, 35, 40, 45.0818,
             0, 5, 10, 15, 20, 25, 30, 35, 40, 45.0818,
             0, 5, 10, 15, 20, 25, 30, 35, 40, 45.0818,
             0, 5, 10, 15, 20, 25, 30, 35, 40, 45.0818,
             0, 5, 10, 15, 20, 25, 30, 35, 40, 45.0818,
             0, 5, 10, 15, 20, 25, 30, 35, 40, 45.0818,
             0, 5, 10, 15, 20, 25, 30, 35, 40, 45.0818,
             0, 5, 10, 15, 20, 25, 30, 35, 40, 45.0818,
             0, 5, 10, 15, 20, 25, 30, 35, 40, 45.0818,
             0, 5, 10, 15, 20, 25, 30, 35, 40, 45.0818]
        Z = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0.00000001359492565, 0.00000002745297888, 0.00000004139874132, 0.00000005516908536, 0.000000068764011, 0.0000000826220643, 0.0000000963046991, 0.0000001101627523, 0.0000001244593516,
             0, 0.00000006902713859, 0.0000001381419864, 0.0000002069937066, 0.0000002760208452, 0.0000003449602746, 0.0000004137242857, 0.0000004827514242, 0.000000551866272, 0.0000006222090486,
             0, 0.0000001381419864, 0.0000002761962636, 0.0000004140751224, 0.0000005521293996, 0.0000006900959675, 0.0000008280625355, 0.0000009661168127, 0.000001103907962, 0.000001244330388,
             0, 0.0000002066428698, 0.0000004139874132, 0.0000006209811198, 0.0000008279748264, 0.000001034880824, 0.000001241699112, 0.000001448605109, 0.000001655774234, 0.000001866100891,
             0, 0.0000002757577176, 0.0000005517785628, 0.0000008278871172, 0.000001103732544, 0.000001379577971, 0.000001655598816, 0.000001931619661, 0.000002207640506, 0.000002488046811,
             0, 0.0000003452234022, 0.0000006899205492, 0.000001034968533, 0.000001380016517, 0.000001724889082, 0.000002069937066, 0.000002414809631, 0.000002759857615, 0.000003110431278,
             0, 0.0000004139874132, 0.0000008278871172, 0.000001241699112, 0.000001655774234, 0.000002069849357, 0.000002483661351, 0.000002897648765, 0.000003311636178, 0.000003732201781,
             0, 0.00000068983284, 0.000001379841098, 0.000002069673938, 0.000002759769906, 0.000003449515037, 0.000004139698714, 0.000004829531554, 0.000005519364394, 0.00000622051172,
             0, 0.000001379841098, 0.000002759769906, 0.000004139611004, 0.000005519539812, 0.000006899205492, 0.000008279222009, 0.000009658975398, 0.00001103890421, 0.00001244146199,
             0, 0.000002069849357, 0.000004139698714, 0.00000620963578, 0.000008279397427, 0.00001034907137, 0.00001241900843, 0.00001448877008, 0.00001655844402, 0.00001866223683,
             0, 0.000002759682197, 0.000005519452103, 0.000008279309718, 0.00001103899191, 0.00001379876182, 0.00001655818089, 0.0000193180385, 0.00002207807154, 0.00002488266084,
             0, 0.000003449778164, 0.00000689946862, 0.00001034907137, 0.00001379867411, 0.0000172487154, 0.0000206978796, 0.00002414774548, 0.00002759743593, 0.00003110343569,
             0, 0.000004139523295, 0.00000827904659, 0.0000124187453, 0.00001655853173, 0.00002069796731, 0.00002483757832, 0.00002897710161, 0.00003311662491, 0.00003732412283]
        xi = np.linspace(np.min(X), np.max(X))
        yi = np.linspace(np.min(Y), np.max(Y))
        zi = griddata(X, Y, Z, xi, yi)
        plt.contour(xi, yi, zi)
        fig = plt.figure()
        self.axes.set_title(u"Без дисперсии с n1=1.7127, Umax = 45.0818 до beta=1E-3")
        self.axes.set_xlabel(u'Vo[м/с]')
        self.axes.set_ylabel(u'Vd[м/с]')
        self.axes.set_zlabel(u'ddle[ед]')
        zlabs = ['{:1.1E}'.format(i*1E-6) for i in xrange(0, 45, 5)]
        self.axes.set_zticklabels(zlabs)
        self.axes.set_zticks(zlabs)
        xlabs = ['{:1.1E}'.format(i) for i in xrange(0, 350000, 50000)]
        self.axes.set_xticklabels(xlabs)
        self.axes.set_xticks(xlabs)
        ylabs = ['{:1.0E}'.format(i*10) for i in xrange(0, 6, )]
        self.axes.set_yticklabels(ylabs)
        self.axes.set_yticks(ylabs)
        xim, yim = np.meshgrid(xi, yi)
        Gx, Gy = np.gradient(zi) #gradient with respect to x and y
        G = (Gx**2+Gy**2)**.5 #gradient magitude
        N = G/G.max()# normalize 0..1
        self.axes.plot_surface(xim, yim, zi, rstride=1, cstride=1, facecolors=cm.jet(N), linewidth=0, antialiased=False, shade=False)
        self.canvas.draw()

    def draw_results_2_417(self):
        self.axes1.clear()
        # self.axes.plot(list_x1_axis, list_y1_axis, c="r")
        X = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             1e4, 1e4, 1e4, 1e4, 1e4, 1e4, 1e4, 1e4, 1e4, 1e4, 1e4, 1e4, 1e4,
             1.5e4, 1.5e4, 1.5e4, 1.5e4, 1.5e4, 1.5e4, 1.5e4, 1.5e4, 1.5e4, 1.5e4, 1.5e4, 1.5e4, 1.5e4,
             2e4, 2e4, 2e4, 2e4, 2e4, 2e4, 2e4, 2e4, 2e4, 2e4, 2e4, 2e4, 2e4,
             2.5e4, 2.5e4, 2.5e4, 2.5e4, 2.5e4, 2.5e4, 2.5e4, 2.5e4, 2.5e4, 2.5e4, 2.5e4, 2.5e4, 2.5e4,
             3e4, 3e4, 3e4, 3e4, 3e4, 3e4, 3e4, 3e4, 3e4, 3e4,  3e4, 3e4, 3e4,
             5e4, 5e4, 5e4, 5e4, 5e4, 5e4, 5e4, 5e4, 5e4, 5e4, 5e4, 5e4, 5e4,
             1e5, 1e5, 1e5, 1e5, 1e5, 1e5, 1e5, 1e5, 1e5, 1e5, 1e5, 1e5, 1e5,
             1.5e5, 1.5e5, 1.5e5, 1.5e5, 1.5e5, 1.5e5, 1.5e5, 1.5e5, 1.5e5, 1.5e5, 1.5e5, 1.5e5, 1.5e5,
             2e5, 2e5, 2e5, 2e5, 2e5, 2e5, 2e5, 2e5, 2e5, 2e5, 2e5, 2e5, 2e5,
             2.5e5, 2.5e5, 2.5e5, 2.5e5, 2.5e5, 2.5e5, 2.5e5, 2.5e5, 2.5e5, 2.5e5, 2.5e5, 2.5e5, 2.5e5,
             3e5, 3e5, 3e5, 3e5, 3e5, 3e5, 3e5, 3e5, 3e5, 3e5, 3e5, 3e5, 3e5]
        Y = [0, 100, 300, 500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5152.2119,
             0, 100, 300, 500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5152.2119,
             0, 100, 300, 500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5152.2119,
             0, 100, 300, 500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5152.2119,
             0, 100, 300, 500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5152.2119,
             0, 100, 300, 500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5152.2119,
             0, 100, 300, 500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5152.2119,
             0, 100, 300, 500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5152.2119,
             0, 100, 300, 500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5152.2119,
             0, 100, 300, 500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5152.2119,
             0, 100, 300, 500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5152.2119,
             0, 100, 300, 500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5152.2119]
        Z = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
             0, 0.000004526408566, 0.00001357975195, 0.00002263335847, 0.00004526671694, 0.00006789981228, 0.0000851572986, 0.0000959176384, 0.0001066780659, 0.0001174384057, 0.0001281987455, 0.0001389589976, 0.0001529949251,
             0, 0.000006789919832, 0.0000203697595, 0.00003394994999, 0.00006789989999, 0.0001018494992, 0.0001357994491, 0.0001697487852, 0.0001915627643, 0.0002077034494, 0.000223843696, 0.0002399839425, 0.0002610376584,
             0, 0.000009053431097, 0.00002716003016, 0.00004526671694, 0.00009053334617, 0.0001357995368, 0.0001810658152, 0.0002263317428, 0.0002715978458, 0.0003168635102, 0.0003405197333, 0.000362039799, 0.0003901113908,
             0, 0.00001131667923, 0.0000339500377, 0.00005658357159, 0.0001131667046, 0.0001697498377, 0.0002263325322, 0.0002829150513, 0.0003394973072, 0.0003960793877, 0.0004526613806, 0.0005051269176, 0.0005402160347,
             0, 0.00001358010279, 0.00004074022066, 0.00006790007541, 0.0001357999754, 0.0002036996123, 0.0002715991614, 0.0003394979212, 0.0004073967687, 0.0004752952653, 0.0005431935865, 0.0006110913815, 0.0006996588137,
             0, 0.00002263344618, 0.00006790025083, 0.0001131667046, 0.0002263331461, 0.0003394991491, 0.0004526646258, 0.0005658297517, 0.0006789945267, 0.0007921584247, 0.0009053224103, 0.001018485782, 0.001166098081,
             0, 0.00004526680465, 0.0001358003262, 0.0002263335847, 0.0004526665554, 0.0006789984736, 0.0009053294271, 0.001131659591, 0.001357988966, 0.001584317726, 0.001810645171, 0.002036971827, 0.002332196601,
             0, 0.00006790025083, 0.0002037006648, 0.0003395006402, 0.0006789999647, 0.001018497798, 0.001357994404, 0.001697489957, 0.002036984282, 0.002376476677, 0.002715968283, 0.003055458399, 0.003498295384,
             0, 0.0000905336093, 0.0002716005648, 0.0004526676956, 0.000905333374, 0.001357997561, 0.001810659907, 0.002263320322, 0.002715979423, 0.003168636593, 0.003621291922, 0.004073945321, 0.004664395044,
             0, 0.0001131669678, 0.0003395013418, 0.0005658350142, 0.001131667134, 0.001697497324, 0.002263325497, 0.00282915139, 0.003394975265, 0.003960796597, 0.004526616174, 0.005092433559, 0.005830495581,
             0, 0.0001358005894, 0.0004074012418, 0.0006790018066, 0.001358001333, 0.002036997789, 0.002715991877, 0.003394983246, 0.004073971721, 0.004752957916, 0.005431941654, 0.006110922674, 0.006996597434]
        xi = np.linspace(np.min(X), np.max(X))
        yi = np.linspace(np.min(Y), np.max(Y))
        zi = griddata(X, Y, Z, xi, yi)
        plt.contour(xi, yi, zi)
        fig = plt.figure()
        #ax = Axes3D(fig)
        # ax = fig.add_subplot(111, projection='3d')
        self.axes1.set_title(u"Без дисперсии с n1=2.417, Umax = 5152.2119 до beta=1E-3")
        #ax.set_ylim(0,1)
        self.axes1.set_xlabel(u'Vo[м/с]')
        self.axes1.set_ylabel(u'Vd[м/с]')
        self.axes1.set_zlabel(u'ddle[ед]')
        zlabs = ['{:1.1E}'.format(i*1E-3) for i in xrange(0, 8, 1)]
        self.axes1.set_zticklabels(zlabs)
        self.axes1.set_zticks(zlabs)
        #xlabs = ['{:1.0E}'.format(i*1E2) for i in xrange(0, 350, 50)]
        xlabs = ['{:1.1E}'.format(i) for i in xrange(0, 350000, 50000)]
        self.axes1.set_xticklabels(xlabs)
        self.axes1.set_xticks(xlabs)
        ylabs = ['{:1.0E}'.format(i*1E3) for i in xrange(0, 7)]
        self.axes1.set_yticklabels(ylabs)
        self.axes1.set_yticks(ylabs)
        xim, yim = np.meshgrid(xi, yi)
        Gx, Gy = np.gradient(zi) #gradient with respect to x and y
        G = (Gx**2+Gy**2)**.5
         #gradient magitude
        N = G/G.max()# normalize 0..1
        self.axes1.plot_surface(xim, yim, zi, rstride=1, cstride=1, facecolors=cm.jet(N), linewidth=0, antialiased=False, shade=False)
        self.canvas1.draw()

    def on_pick(self, event):
        # The event received here is of the type
        # matplotlib.backend_bases.PickEvent
        #
        # It carries lots of information, of which we're using
        # only a small amount here.
        #
        box_points = event.artist.get_bbox().get_points()
        msg = "You've clicked on a bar with coords:\n %s" % box_points

        QMessageBox.information(self, "Click!", msg)
    def create_action(self, text, slot=None, shortcut=None,
                      icon=None, tip=None, checkable=False,
                      signal="triggered()"):
        action = QAction(text, self)
        if icon is not None:
            action.setIcon(QIcon(":/%s.png" % icon))
        if shortcut is not None:
            action.setShortcut(shortcut)
        if tip is not None:
            action.setToolTip(tip)
            action.setStatusTip(tip)
        if slot is not None:
            self.connect(action, QtCore.SIGNAL(signal), slot)
        if checkable:
            action.setCheckable(True)
        return action
    def create_main_frame(self):
        self.main_frame = QWidget()
        self.main_frame1 = QWidget()
        self.dpi = 100
        self.fig = Figure((5.0, 5.0), dpi=self.dpi)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.main_frame)
        self.dpi1 = 100
        self.fig1 = Figure((5.0, 5.0), dpi=self.dpi1)
        self.canvas1 = FigureCanvas(self.fig1)
        self.canvas1.setParent(self.main_frame1)
        self.axes = p3.Axes3D(self.fig)
        self.axes1 = p3.Axes3D(self.fig1)
        self.canvas.mpl_connect('pick_event', self.on_pick)
        self.canvas1.mpl_connect('pick_event', self.on_pick)
        self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)
        self.mpl_toolbar1 = NavigationToolbar(self.canvas1, self.main_frame1)
        tab_widget = QTabWidget()
        tab1 = QWidget()
        tab2 = QWidget()
        tab3 = QWidget()

        vbox1 = QVBoxLayout(tab1)

        vbox1.addWidget(self.canvas)
        vbox1.addWidget(self.mpl_toolbar)

        vbox2 = QVBoxLayout(tab2)
        vbox2.addWidget(self.canvas1)
        vbox2.addWidget(self.mpl_toolbar1)

        tab_widget.addTab(tab1, u"n=1.7125(ТФ3)")
        tab_widget.addTab(tab2, u"n=2.417")

        vbox = QVBoxLayout()
        vbox.addWidget(tab_widget)
        self.main_frame.setLayout(vbox)
        self.setCentralWidget(self.main_frame)

    def create_menu(self):
        self.file_menu = self.menuBar().addMenu(u"&Файл")

        load_file_action = self.create_action(u"&Сохранить построение",
                                              shortcut="Ctrl+S", slot=self.save_plot,
                                              tip=u"Сохранить рисунок")
        quit_action = self.create_action(u"&Выйти", slot=self.close,
                                         shortcut="Ctrl+Q", tip="Close the application")

        self.add_actions(self.file_menu,
                         (load_file_action, None, quit_action))

        self.help_menu = self.menuBar().addMenu(u"&Помощь")
        about_action = self.create_action(u"&О приложении",
                                          shortcut='F1', slot=self.on_about,
                                          tip=u'О приложении')

        self.add_actions(self.help_menu, (about_action,))
class Agilent_Yokogawa():
    def __init__(self, main, ui):
        self.ui = ui
        self.copyData = main.copyData
        self.collectDataThread = CollectData()
        self.save_thread = Save_Thread()

        self.update_visa()

        self.ui.pushButtonStart.setDisabled(True)
        self.ui.pushButtoncloseVisa1.setDisabled(True)
        self.ui.pushButtoncloseVisa2.setDisabled(True)
        self.ui.pushButtonStop.setEnabled(False)
        self.ui.pushButtonStart.setEnabled(False)

        self.x_value = []
        self.y_value = []
        self.item = 0
        self.Array = []

        self.timeStep = .1
        self.ui.lineEditTimeStep.setText(str(self.timeStep))

        self.directory = ''
        self.temp = []

        # Sets up Current v. Voltage guiqwt plot
        self.curve_item_ay = make.curve([], [], color='b', marker="o")
        self.ui.curvewidget_scanPlot_ay.plot.add_item(self.curve_item_ay)
        self.ui.curvewidget_scanPlot_ay.plot.set_antialiasing(True)

        # Sets up Voltage v. Time Step guiqwt plot
        self.curve_item_vt_ay = make.curve([], [], color='b', marker="o")
        self.ui.curvewidget_vt_ay.plot.add_item(self.curve_item_vt_ay)
        self.ui.curvewidget_vt_ay.plot.set_antialiasing(True)

        # Sets up Current v. Time Step guiqwt plot
        self.curve_item_ct_ay = make.curve([], [], color='b', marker="o")
        self.ui.curvewidget_ct_ay.plot.add_item(self.curve_item_ct_ay)
        self.ui.curvewidget_ct_ay.plot.set_antialiasing(True)

        # For the canvas.
        self.canvas_import_ay = FigureCanvas(
            self.ui.mplwidget_import_ay.figure)
        self.canvas_import_ay.setParent(self.ui.widget_import_ay)
        self.mpl_toolbar_import_ay = NavigationToolbar(
            self.canvas_import_ay, self.ui.widget_import_ay)
        self.canvas_analysis_ay = FigureCanvas(
            self.ui.mplwidget_analysis_ay.figure)
        self.canvas_analysis_ay.setParent(self.ui.widget_analysis_ay)
        self.mpl_toolbar_analysis_ay = NavigationToolbar(
            self.canvas_analysis_ay, self.ui.widget_analysis_ay)
        self.canvas_analysis_ct_ay = FigureCanvas(
            self.ui.mplwidget_analysis_ct_ay.figure)
        self.canvas_analysis_ct_ay.setParent(self.ui.widget_analysis_ct_ay)
        self.mpl_toolbar_analysis_ct_ay = NavigationToolbar(
            self.canvas_analysis_ct_ay, self.ui.widget_analysis_ct_ay)
        self.canvas_analysis_vt_ay = FigureCanvas(
            self.ui.mplwidget_analysis_vt_ay.figure)
        self.canvas_analysis_vt_ay.setParent(self.ui.widget_analysis_vt_ay)
        self.mpl_toolbar_analysis_vt_ay = NavigationToolbar(
            self.canvas_analysis_vt_ay, self.ui.widget_analysis_vt_ay)

        # Create the QVBoxLayout object and add the widget into the layout
        vbox_import_ay = QVBoxLayout()
        vbox_import_ay.addWidget(self.canvas_import_ay)
        vbox_import_ay.addWidget(self.mpl_toolbar_import_ay)
        self.ui.widget_import_ay.setLayout(vbox_import_ay)
        vbox_analysis_ay = QVBoxLayout()
        vbox_analysis_ay.addWidget(self.canvas_analysis_ay)
        vbox_analysis_ay.addWidget(self.mpl_toolbar_analysis_ay)
        self.ui.widget_analysis_ay.setLayout(vbox_analysis_ay)
        vbox_analysis_ct_ay = QVBoxLayout()
        vbox_analysis_ct_ay.addWidget(self.canvas_analysis_ct_ay)
        vbox_analysis_ct_ay.addWidget(self.mpl_toolbar_analysis_ct_ay)
        self.ui.widget_analysis_ct_ay.setLayout(vbox_analysis_ct_ay)
        vbox_analysis_vt_ay = QVBoxLayout()
        vbox_analysis_vt_ay.addWidget(self.canvas_analysis_vt_ay)
        vbox_analysis_vt_ay.addWidget(self.mpl_toolbar_analysis_vt_ay)
        self.ui.widget_analysis_vt_ay.setLayout(vbox_analysis_vt_ay)

        # Connect the mplwidget with canvass
        self.ui.mplwidget_import_ay = self.canvas_import_ay
        self.ui.mplwidget_analysis_ay = self.canvas_analysis_ay
        self.ui.mplwidget_analysis_ct_ay = self.canvas_analysis_ct_ay
        self.ui.mplwidget_analysis_vt_ay = self.canvas_analysis_vt_ay

        main.connect(self.ui.pushButtonselectVisa, SIGNAL('clicked()'),
                     self.select_visa)
        main.connect(self.ui.pushButtonupdateVisa, SIGNAL('clicked()'),
                     self.update_visa)
        main.connect(self.ui.pushButtoncloseVisa1, SIGNAL('clicked()'),
                     self.close_visaCurrent)
        main.connect(self.ui.pushButtoncloseVisa2, SIGNAL('clicked()'),
                     self.close_visaVoltage)

        main.connect(self.ui.pushButton_browse_ay, SIGNAL('clicked()'),
                     self.browse_ay)
        main.connect(self.ui.pushButton_import_ay, SIGNAL('clicked()'),
                     self.import_ay)
        main.connect(self.ui.pushButton_copy_ay, SIGNAL('clicked()'),
                     self.copy_ay)

        main.connect(self.ui.pushButtonStart, SIGNAL('clicked()'),
                     self.pre_start)
        main.connect(self.ui.pushButtonPause, SIGNAL('clicked()'),
                     self.collectDataThread.pause)
        main.connect(self.ui.pushButtonStop, SIGNAL('clicked()'), self.stop)
        main.connect(self.ui.pushButtonClear, SIGNAL('clicked()'),
                     self.clear_plots)
        main.connect(self.ui.pushButtonFit, SIGNAL('clicked()'), self.Fit)

        main.connect(self.collectDataThread, SIGNAL("Plot"), self.plotData)
        main.connect(self.collectDataThread, SIGNAL("Analyze"), self.Analyze)

        main.connect(self.ui.pushButton_browse_save_G_ay, SIGNAL('clicked()'),
                     self.Google_browse)
        main.connect(self.ui.pushButton_check_G_ay, SIGNAL('clicked()'),
                     self.Check)
        main.connect(self.ui.pushButton_Select_Directory_G_ay,
                     SIGNAL('clicked()'), self.Google_select_namefolder)
        main.connect(self.ui.radioButton_csv_G_ay, SIGNAL('clicked()'),
                     self.Select_type_G_ay)
        main.connect(self.ui.radioButton_txt_G_ay, SIGNAL('clicked()'),
                     self.Select_type_G_ay)
        main.connect(self.ui.radioButton_Timename_G_ay, SIGNAL('clicked()'),
                     self.Select_name_G_ay)
        main.connect(self.ui.radioButton_Custom_Name_G_ay, SIGNAL('clicked()'),
                     self.Select_name_G_ay)
        main.connect(self.ui.pushButton_Save_G_ay, SIGNAL('clicked()'),
                     self.G_save)

    def browse_ay(self):
        prev_dir = os.getcwd()
        print prev_dir
        fileDir = QFileDialog.getOpenFileName(None,
                                              'Select File to Import',
                                              prev_dir,
                                              filter="Array Files (*.array)")
        if fileDir != '':
            file_list = str(fileDir).split('/')
            for i in range(0, len(file_list) - 1):
                global open_dir
                open_dir = ''
                if i < len(file_list) - 1:
                    open_dir += file_list[i] + '\\'
                elif i == len(file_list) - 1:
                    open_dir += file_list[i]
            fileDir.replace('/', '\\')
            self.ui.lineEdit_directory_ay.setText(fileDir)
            self.ui.pushButton_import_ay.setEnabled(True)
            self.ui.lineEdit_condition_ay.setText('File: "' +
                                                  file_list[len(file_list) -
                                                            1] +
                                                  '" has been chosen.')

    def import_ay(self):
        divider_found = True
        count = 0
        temp = 0
        x_value = []
        y_value = []

        fileDir = self.ui.lineEdit_directory_ay.text()
        fp = open(fileDir)
        while True:
            if count == 5000:
                self.ui.lineEdit_condition_ay.setText(
                    "Data not found in file. Please check it.")
                divider_found = False
                break
            line = fp.readline()
            line_list = line.split(',')
            if line_list[0].upper() == "Array Data".upper() + '\n':
                break
            count += 1

        if divider_found == True:
            line = fp.readline()
            while True:
                line = fp.readline().replace('\n', '')
                if line == '':
                    break
                value = line.split(',')
                x_value.append(temp)
                x_value.append(temp + 1)
                y_value.append(value[1])
                y_value.append(value[1])
                self.Array.append(value[1])
                temp += 1

            self.plot_import(x_value, y_value)
            self.ui.output.setText("File was imported correctly.")

    def copy_ay(self):
        Values = self.copyData()
        if not Values == False:
            for i in range(0, len(Values)):
                for j in range(0, len(Values[i])):
                    self.x_value.append(self.item)
                    self.x_value.append(self.item + 1)
                    self.y_value.append(Values[i][j])
                    self.y_value.append(Values[i][j])
                    self.Array.append(Values[i][j])
                    self.item += 1
        self.plot_import(self.x_value, self.y_value)
        print self.Array

    def plot_import(self, x, y):
        self.reset_plot_import()
        self.ui.mplwidget_import_ay.figure.clear()
        self.axes_import = self.ui.mplwidget_import_ay.figure.add_subplot(111)
        self.axes_import.plot(x, y, marker='.', linestyle='-')
        self.axes_import.grid()
        self.axes_import.set_title("Array Import Plot")
        self.axes_import.set_xlabel("Steps")
        self.axes_import.set_ylabel("Values")
        self.ui.mplwidget_import_ay.draw()

    def update_visa(self):
        self.rm = visa.ResourceManager()

        try:
            visas = self.rm.list_resources()
        except:
            visas = ''

        self.ui.comboBoxSelectVisa1.clear()
        self.ui.comboBoxSelectVisa2.clear()

        check_current1 = False
        check_current2 = False

        for each_visa in visas:
            self.ui.comboBoxSelectVisa1.addItem(each_visa)

        for each_visa in visas:
            self.ui.comboBoxSelectVisa2.addItem(each_visa)

        if check_current1 == False:
            self.ui.labelVisa1.setText("None")
            self.ui.pushButtonStart.setDisabled(True)
            self.ui.pushButtoncloseVisa1.setDisabled(True)
        else:
            pass

        if check_current2 == False:
            self.ui.labelVisa2.setText("None")
            self.ui.pushButtonStart.setDisabled(True)
            self.ui.pushButtoncloseVisa2.setDisabled(True)
        else:
            pass

    def select_visa(self):
        self.rm = visa.ResourceManager()
        visa1 = str(self.ui.comboBoxSelectVisa1.currentText())
        visa2 = str(self.ui.comboBoxSelectVisa2.currentText())
        valid = False

        inst1 = self.rm.open_resource(visa1)
        inst2 = self.rm.open_resource(visa2)

        try:
            valid = self.check_Visa(inst1, inst2)
        except:
            self.ui.lineEditError.setText("Error In Selected Visas")

        if valid == True:
            visa1_name = str(inst1.ask("*IDN?"))
            visa2_name = str(inst2.ask("*IDN?"))
            self.ui.labelVisa1.setText(visa1_name)
            self.ui.labelVisa2.setText(visa2_name)
            self.visaCurrent = inst1
            self.visaVoltage = inst2
            self.ui.lineEditError.setText("None")
            self.ui.pushButtonStart.setDisabled(False)
            self.ui.pushButtonStop.setDisabled(False)
            self.ui.pushButtoncloseVisa1.setDisabled(False)
            self.ui.pushButtoncloseVisa2.setDisabled(False)
        else:
            self.ui.labelVisa1.setText("None")
            self.ui.labelVisa2.setText("None")
            self.ui.pushButtonStart.setDisabled(True)
            self.ui.pushButtoncloseVisa1.setDisabled(True)
            self.ui.pushButtoncloseVisa2.setDisabled(True)
            self.ui.lineEditError.setText("Invalid Visas")

    def check_Visa(self, inst1, inst2):
        try:
            inst1.ask('*IDN?')
            inst2.ask('*IDN?')
            valid = True
        except:
            valid = False

        return valid

    def close_visaCurrent(self):
        self.visaCurrent.close()
        self.ui.lineEditOutput.setText("Visa For Current Has Been Closed")

    def close_visaVoltage(self):
        self.visaVoltage.close()
        self.ui.lineEditOutput.setText("Visa For Voltage Has Been Closed")

    def pre_start(self):
        first_value = self.Array[0]
        i = 0
        while self.Array[i] == first_value:
            i = i + 1
        self.repeat = i

        if len(
                self.Array
        ) / self.repeat >= 200 and self.ui.radioButtonCurrent_mA.isChecked():
            self.ui.lineEditError.setText(
                "Please make sure that Array peak is less than 200 for mA current."
            )
        else:
            self.first_plot = True
            self.start()

    def start(self):
        self.ui.pushButtonStart.setEnabled(False)
        self.ui.pushButtonPause.setEnabled(True)
        self.ui.pushButtonStop.setEnabled(True)
        if float(self.ui.lineEditTimeStep.text()
                 ) > 0 or self.first_plot == True or self.clear_check == True:
            self.visaCurrent.write('OUTP ON')
            self.timeStep = float(self.ui.lineEditTimeStep.text())
            self.collectDataThread.input(self.ui, self.visaCurrent,
                                         self.visaVoltage, self.Array,
                                         self.timeStep, self.curve_item_ay,
                                         self.curve_item_vt_ay,
                                         self.curve_item_ct_ay)
            self.ui.pushButtonStart.setEnabled(True)
            self.ui.lineEditOutput.setText("Running")
            self.ui.tabWidget_plot_ay.setCurrentIndex(2)
        else:
            self.ui.lineEditError.setText("Error")

    def plotData(self):
        self.curve_item_ay.plot().replot()
        self.curve_item_ct_ay.plot().replot()
        self.curve_item_vt_ay.plot().replot()
        self.ui.curvewidget_ct_ay.plot.do_autoscale()
        self.ui.curvewidget_vt_ay.plot.do_autoscale()
        self.ui.curvewidget_scanPlot_ay.plot.do_autoscale()

    def Analyze(self, current, voltage, steps, time, date_value):
        self.ui.pushButtonStart.setEnabled(False)
        self.ui.pushButtonPause.setEnabled(False)
        self.ui.pushButtonStop.setEnabled(False)
        self.ui.pushButtonClear.setEnabled(True)

        self.ui.tabWidget_save_ay.setEnabled(True)

        self.ui.lineEditOutput.setText('Data Collection Is Done')
        self.current = current
        self.voltage = voltage
        self.steps = steps
        self.time = time
        self.date_value = date_value
        self.ui.mplwidget_analysis_ay.figure.clear()
        self.axes_analysis_ay = self.ui.mplwidget_analysis_ay.figure.add_subplot(
            111)
        self.axes_analysis_ay.grid()
        self.axes_analysis_ay.set_title('Voltage v. Current')
        self.axes_analysis_ay.set_ylabel("Voltage (V)")
        self.axes_analysis_ay.set_xlabel("Current (A)")
        self.axes_analysis_ay.plot(self.current,
                                   self.voltage,
                                   marker='.',
                                   linestyle='-')
        self.ui.mplwidget_analysis_ay.draw()

        if self.collectDataThread.time_scale == True:
            self.ui.mplwidget_analysis_ct_ay.figure.clear()
            self.axes_analysis_ct_ay = self.ui.mplwidget_analysis_ct_ay.figure.add_subplot(
                111)
            self.axes_analysis_ct_ay.grid()
            self.axes_analysis_ct_ay.set_title('Current v. Time')
            self.axes_analysis_ct_ay.set_ylabel("Current (A)")
            self.axes_analysis_ct_ay.set_xlabel("Time (s)")
            self.axes_analysis_ct_ay.plot(self.time,
                                          self.current,
                                          marker='.',
                                          linestyle='-')
            self.ui.mplwidget_analysis_ct_ay.draw()

            self.ui.mplwidget_analysis_vt_ay.figure.clear()
            self.axes_analysis_vt_ay = self.ui.mplwidget_analysis_vt_ay.figure.add_subplot(
                111)
            self.axes_analysis_vt_ay.grid()
            self.axes_analysis_vt_ay.set_title('Voltage v. Time')
            self.axes_analysis_vt_ay.set_ylabel("Voltage (V)")
            self.axes_analysis_vt_ay.set_xlabel("Time (s)")
            self.axes_analysis_vt_ay.plot(self.time,
                                          self.voltage,
                                          marker='.',
                                          linestyle='-')
            self.ui.mplwidget_analysis_vt_ay.draw()

        else:
            self.ui.mplwidget_analysis_ct_ay.figure.clear()
            self.axes_analysis_ct_ay = self.ui.mplwidget_analysis_ct_ay.figure.add_subplot(
                111)
            self.axes_analysis_ct_ay.grid()
            self.axes_analysis_ct_ay.set_title('Current v. Steps')
            self.axes_analysis_ct_ay.set_ylabel("Current (A)")
            self.axes_analysis_ct_ay.set_xlabel("Steps")
            self.axes_analysis_ct_ay.plot(self.steps,
                                          self.current,
                                          marker='.',
                                          linestyle='-')
            self.ui.mplwidget_analysis_ct_ay.draw()

            self.ui.mplwidget_analysis_vt_ay.figure.clear()
            self.axes_analysis_vt_ay = self.ui.mplwidget_analysis_vt_ay.figure.add_subplot(
                111)
            self.axes_analysis_vt_ay.grid()
            self.axes_analysis_vt_ay.set_title('Voltage v. Steps')
            self.axes_analysis_vt_ay.set_ylabel("Voltage (V)")
            self.axes_analysis_vt_ay.set_xlabel("Steps")
            self.axes_analysis_vt_ay.plot(self.steps,
                                          self.voltage,
                                          marker='.',
                                          linestyle='-')
            self.ui.mplwidget_analysis_vt_ay.draw()

    def stop(self):
        self.collectDataThread.pauseLoop = True
        self.collectDataThread.quit()
        self.ui.pushButtonStartLI.setEnabled(True)
        self.ui.pushButtonStopLI.setEnabled(False)
        self.ui.pushButtonPauseLI.setEnabled(False)
        self.ui.lineEditOutput.setText("Stopped")
        self.ui.pushButtonPauseLI.setText("Pause")
        self.visaCurrent.write('OUTP OFF')

    def reset_plot_import(self):
        self.ui.mplwidget_import_ay.figure.clear()
        self.axes_import = self.ui.mplwidget_import.figure.add_subplot(111)

    def clear_plots(self):
        self.ui.pushButtonStart.setEnabled(True)
        #Clears the analysis plots
        self.ui.mplwidget_analysis_ay.figure.clear()
        self.axes_analysis_ay = self.ui.mplwidget_analysis_ay.figure.add_subplot(
            111)
        self.axes_analysis_ay.grid()
        self.ui.mplwidget_analysis_ay.draw()
        self.ui.mplwidget_analysis_ct_ay.figure.clear()
        self.axes_analysis_ct_ay = self.ui.mplwidget_analysis_ct_ay.figure.add_subplot(
            111)
        self.axes_analysis_ct_ay.grid()
        self.ui.mplwidget_analysis_ct_ay.draw()
        self.ui.mplwidget_analysis_vt_ay.figure.clear()
        self.axes_analysis_vt_ay = self.ui.mplwidget_analysis_vt_ay.figure.add_subplot(
            111)
        self.axes_analysis_vt_ay.grid()
        self.ui.mplwidget_analysis_vt_ay.draw()
        #Clears the scan plots
        self.ui.curvewidget_scanPlot_ay.plot.set_titles('', '', '')
        self.ui.curvewidget_vt_ay.plot.set_titles('', '', '')
        self.ui.curvewidget_ct_ay.plot.set_titles('', '', '')
        self.curve_item_ay.set_data([], [])
        self.curve_item_ct_ay.set_data([], [])
        self.curve_item_vt_ay.set_data([], [])
        self.curve_item_ay.plot().replot()
        self.curve_item_ct_ay.plot().replot()
        self.curve_item_vt_ay.plot().replot()

        self.clear_check = True
        self.ui.lineEditOutput.setText("Plots have been cleared")

    def Fit(self):
        try:
            warnings.simplefilter('ignore', np.RankWarning)
            user_input = self.ui.lineEdit_fit_ay.text()
            input_list = user_input.split(',')
            start_input = float(input_list[0])
            end_input = float(input_list[1])
            if self.ui.radioButtonTimeScale.isChecked():
                # start point
                if start_input < self.time[0]:
                    start = 0
                elif start_input > self.time[len(self.time) - 1]:
                    start = len(self.time) - 1
                else:
                    for i in range(0, len(self.time)):
                        if start_input <= self.time[i]:
                            start = i
                            break
                # end point
                if end_input < self.time[0]:
                    end = 0
                elif end_input > self.time[len(self.time) - 1]:
                    end = len(self.time) - 1
                else:
                    for i in range(0, len(self.time)):
                        if end_input <= self.time[i]:
                            end = i + 1
                            break

            elif self.ui.radioButtonStepScale.isChecked():
                # start point
                if start_input < self.steps[0]:
                    start = 0
                elif start_input > self.steps[len(self.steps) - 1]:
                    start = len(self.steps) - 1
                else:
                    for i in range(0, len(self.steps)):
                        if start_input <= self.steps[i]:
                            start = i
                            break
                # end point
                if end_input < self.steps[0]:
                    end = 0
                elif end_input > self.steps[len(self.steps) - 1]:
                    end = len(self.steps) - 1
                else:
                    for i in range(0, len(self.steps)):
                        if end_input <= self.steps[i]:
                            end = i + 1
                            break

            numpy_fit = np.polyfit(self.current[start:end],
                                   self.voltage[start:end], 1)

            self.ui.label_VI_ay.setText(str(format(numpy_fit[0], '.5f')))
            self.ui.label_IV_ay.setText(str(format(1 / numpy_fit[0], '.5f')))
            self.ui.label_intercept_ay.setText(str(format(numpy_fit[1],
                                                          '.5f')))
            self.ui.lineEditOutput.setText('Linear fit done.')
            fit = np.poly1d(numpy_fit)
            self.axes_analysis_ay.plot(self.current, fit(self.current))
            self.ui.mplwidget_analysis_ay.draw()

        except Exception, e:
            self.ui.lineEditOutput.setText(
                'Please enter valid start/end value')
class StatisticGraph(PyQt4.QtGui.QWidget):
    def __init__(self, parent=None):
        self.parent = parent
        PyQt4.QtGui.QWidget.__init__(self, self.parent)
        self.create_main_frame()
        self.text_font = matplotlib.font_manager.FontProperties(size=8)
        # 0 means the only one dimension calculation
        # 1 means two dimensional calculation
        self.dimension = 0

        self.answer_set = []
        self.answer_map = {}

    def set_dimension(self, value):
        self.dimension = value

    def plot_graph(self, conf_info):
        self.conf_info = conf_info
        if (self.dimension == 0):
            if (conf_info.check_valid()):
                self.one_d_draw()
                return self.answer_map
        elif (self.dimension == 1):
            if (conf_info.check_valid()):
                self.two_d_draw()
                return self.answer_map

    def clear_graph(self):
        self.axes.clear()
        self.clear_data()
        self.canvas.draw()

    def clear_data(self):
        self.answer_set = []
        self.answer_map = {}

    def two_d_draw(self):
        self.clear_data()
        self.axes.clear()

        #self.axes.grid(self.grid_cb.isChecked())
        #       self.axes.xaxis.set_major_formatter(FormatStrFormatter('%0.0f'))
        #       self.axes.set_axes([0, 100, 0, 100])
        #        self.axes.set_ylim((0, 100))
        repeat_time = self.conf_info.repeat_time
        initial_state = self.conf_info.initial_state
        number_of_walkers = self.conf_info.random_walk_number
        upper_range = self.conf_info.upper_range
        lower_range = self.conf_info.lower_range
        range_of_walk = range(repeat_time + 1)
        self.axes.plot(
            self.one_d_walk("x", repeat_time, initial_state, upper_range,
                            lower_range),
            self.one_d_walk("y", repeat_time, initial_state, upper_range,
                            lower_range))
        for i in range(int(number_of_walkers) - 1):
            self.axes.plot(
                self.one_d_walk("x", repeat_time, initial_state, upper_range,
                                lower_range),
                self.one_d_walk("y", repeat_time, initial_state, upper_range,
                                lower_range))
        self.canvas.draw()

    def one_d_walk(self,
                   name,
                   T=10,
                   initial_state=1,
                   upper_range=1,
                   lower_range=1):
        """random one_d_walk with a fair coin"""
        x = initial_state
        answer = [x]
        for t in xrange(T):
            u = random.uniform(lower_range, upper_range)
            x += u
            if (t % 1 == 0):
                answer.append(x)
        self.answer_set.append(answer)
        self.answer_map[name] = deepcopy(self.answer_set)
        return answer

    def one_d_draw(self):

        self.axes.clear()
        self.answer_set = []
        #self.axes.grid(self.grid_cb.isChecked())
        #       self.axes.xaxis.set_major_formatter(FormatStrFormatter('%0.0f'))
        #       self.axes.set_axes([0, 100, 0, 100])
        #        self.axes.set_ylim((0, 100))
        repeat_time = self.conf_info.repeat_time
        initial_state = self.conf_info.initial_state
        number_of_walkers = self.conf_info.random_walk_number
        upper_range = self.conf_info.upper_range
        lower_range = self.conf_info.lower_range
        range_of_walk = range(repeat_time + 1)
        self.axes.plot(
            range_of_walk,
            self.one_d_walk("y", repeat_time, initial_state, upper_range,
                            lower_range))
        for i in range(int(number_of_walkers) - 1):
            self.axes.plot(
                range_of_walk,
                self.one_d_walk("y", repeat_time, initial_state, upper_range,
                                lower_range))
        print "enter one_d_draw"
        self.canvas.draw()

    def auto_label_lost_value(self, bars):
        # attach some text labels
        for i, bar in enumerate(bars):
            height = self.new_lost_height[i]
            self.axes.text(bar.get_x() - bar.get_width() / 4.0,
                           0.9 * height,
                           '%d' % int(self.lost_frame[i]),
                           ha='center',
                           va='bottom')

    def auto_label_value(self, bars):
        # attach some text labels
        for i, bar in enumerate(bars):
            height = self.new_height[i]
            self.axes.text(bar.get_x() - bar.get_width() / 4.0,
                           0.9 * height,
                           '%d' % int(self.total_frame[i]),
                           ha='center',
                           va='bottom')

    def label_percentage(self, bars):
        # attach some text labels
        for i, bar in enumerate(bars):
            height = self.new_height[i]
            #            print self.percentage
            #            print i, len(bars)
            # to ignore the disoder first serial times of reading
            try:
                self.axes.text(
                    bar.get_x() + bar.get_width() / 2.,
                    1.02 * height,
                    '%d' % height + '%',  #%self.percentage[i]
                    ha='center',
                    va='bottom').set_fontproperties(self.text_font)
            except:
                pass

    def create_main_frame(self):
        self.main_frame = PyQt4.QtGui.QWidget(self.parent)

        # Create the mpl Figure and FigCanvas objects.
        # 5x4 inches, 100 dots-per-inch
        #dpi = dots per inch
        self.dpi = 100
        self.fig = Figure((6.7, 3.5), dpi=self.dpi)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.main_frame)

        # Since we have only one plot, we can use add_axes
        # instead of add_subplot, but then the subplot
        # configuration tool in the navigation toolbar wouldn't
        # work.
        #
        self.axes = self.fig.add_subplot(111)

        # Bind the 'pick' event for clicking on one of the bars
        #
        #        self.canvas.mpl_connect('pick_event', self.on_pick)

        # Create the navigation toolbar, tied to the canvas
        #
        self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)

        # Other GUI controls
        #
        #        self.textbox = PyQt4.QtGui.QLineEdit()
        #        self.textbox.setMinimumWidth(200)
        #        #self.connect(self.textbox, PyQt4.QtCore.SIGNAL('editingFinished ()'), self.one_d_draw)
        #        #self.connect(self.draw_button, PyQt4.QtCore.SIGNAL('clicked()'), self.one_d_draw)
        #
        #        self.grid_cb = PyQt4.QtGui.QCheckBox("Show &Grid")
        #        self.grid_cb.setChecked(False)
        #        #self.connect(self.grid_cb, PyQt4.QtCore.SIGNAL('stateChanged(int)'), self.one_d_draw)
        #
        #        slider_label = PyQt4.QtGui.QLabel('Bar width (%):')
        #        self.slider = PyQt4.QtGui.QSlider(PyQt4.QtCore.Qt.Horizontal)
        #        self.slider.setRange(1, 100)
        #        self.slider.setValue(20)
        #        self.slider.setTracking(True)
        #        self.slider.setTickPosition(PyQt4.QtGui.QSlider.TicksBothSides)
        #        #self.connect(self.slider, PyQt4.QtCore.SIGNAL('valueChanged(int)'), self.one_d_draw)
        #
        #        #
        #        # Layout with box sizers
        #        #
        hbox = PyQt4.QtGui.QHBoxLayout()
        #
        #        for w in [ self.textbox, self.draw_button, self.grid_cb,
        #                    slider_label, self.slider]:
        #            hbox.addWidget(w)
        #            hbox.setAlignment(w, PyQt4.QtCore.Qt.AlignVCenter)
        #
        vbox = PyQt4.QtGui.QVBoxLayout()
        vbox.addWidget(self.canvas)
        vbox.addWidget(self.mpl_toolbar)
        vbox.addLayout(hbox)
        #
        self.main_frame.setLayout(vbox)