Esempio n. 1
1
class TestDialog( QDialog, Ui_dlgMPLTest ):
    def __init__( self, parent = None ):
        super( TestDialog, self ).__init__( parent )
        self.setupUi( self )
        
        # initialize mpl plot
        self.figure = Figure()
        #self.figure.set_figsize_inches( ( 4.3, 4.2 ) )
        self.axes = self.figure.add_subplot( 111 )
        self.figure.suptitle( "Frequency distribution", fontsize = 12 )
        self.axes.grid( True )
        self.canvas = FigureCanvas( self.figure )
        
        layout = QVBoxLayout()
        self.widgetPlot.setLayout(layout)
        layout.addWidget(self.canvas)
        #self.canvas.setParent( self.widgetPlot )
        
        # draw mpl plot
        #self.axes.clear()
        #self.axes.grid( True )
        #self.figure.suptitle( "Frequency distribution", fontsize = 12 )
        self.axes.set_ylabel( "Count", fontsize = 8 )
        self.axes.set_xlabel( "Values", fontsize = 8 )
        x = [ 4, 1, 5, 3, 3, 2, 3, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1 ]
        n, bins, pathes = self.axes.hist( x, 18, alpha=0.5, histtype = "bar" )
        self.canvas.draw()
        
        self.setWindowTitle( self.tr( "MPL test" ) )
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()
Esempio n. 3
0
 def addSkeletonWindow(self):
     t_start = 1917 # start frame
     t_end = 2130 # end frame
     
     data = pd.read_csv('../inputs/Smart-first_phase_NaN-zeros.csv') # only coordinate data
     df = data.loc[t_start:t_end,'Shoulder_left_x':'Ankle_right_z']
     data = df.values.tolist()
     
     def chunks(l, n):
         return [l[i:i+n] for i in range(0, len(l), n)]
             
     newData = []
     for line in data:
         newData.append(chunks(line, 3))
     figure = render.renderSkeleton(newData)
     layout = QtGui.QVBoxLayout()
     canvas = FigureCanvas(figure)
     toolbar = NavigationToolbar(canvas, self)
     self.layout.addWidget(toolbar)
     self.layout.addWidget(canvas)
     button = QtGui.QPushButton('Plot')
     self.layout.addWidget(button)
     self.setLayout(self.layout)
     canvas.draw()
     plt.show()
    def __init__(self, parent=None, width=5, height=4, dpi=100):
        self.fig = Figure(figsize=(width, height), dpi=dpi)
        FigureCanvasQTAgg.__init__(self, self.fig)

        self.setParent(parent)
        FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)
Esempio n. 5
0
    def keyPressEvent(self, event):
        if self.redetecter:
            self.detecter()

        key = event.key()
        txt = event.text()
        modifiers = event.modifiers()
        accept = True
        debug(u"key: ", key)
        if key == Qt.Key_Delete and self.select:
            if shift_down(event):
                self.executer(u"%s.cacher()" %self.select.nom)
            else:
                self.executer(u"%s.supprimer()" %self.select.nom)
        elif key in (Qt.Key_Return, Qt.Key_Enter) and self.editeur.objet is not self.select:
            self.editer(shift_down(event))
        elif self.editeur and not self.editeur.key(key, txt, modifiers):
            accept = False

        if key == Qt.Key_Escape and self.interaction:
            print "ESCAPE !"
            self.interaction(special="ESC")
            accept = True

        if not accept:
            FigureCanvasQTAgg.keyPressEvent(self, event)
    def __init__(self, parent=None, width=5, height=5, dpi=72):
        self.fontsize = 10
        # fiugrueの生成
        # self.fig = plt.figure(figsize=(width, height), dpi=72, facecolor=(1, 1, 1), edgecolor=(0, 0, 0),
        #                       tight_layout=False)
        self.fig = plt.figure(figsize=(width, height), dpi=72,tight_layout=False)

        # axesハンドルの生成
        self.axes = self.fig.add_subplot(111)
        # 再描画では上書きしない
        self.axes.hold(False)
        # コンストラクタ
        FigureCanvas.__init__(self, self.fig)
        # 親のウィジェットを生成
        self.setParent(parent)
        # サイズの更新
        FigureCanvas.updateGeometry(self)

        # シークバーの格納
        self.seakbar_handle = None
        self.seakbar_xdata = [1, 1]
        self.seakbar_ydata = [-1, 1]

        # メインラインハンドルの格納
        self.mainline_handle = None

        # 画像の初期表示
        self.compute_initial_fiugre()
    def __init__(self, parent=None, width=5, height=4, dpi=72):
        # fiugrueの生成
        self.fig = Figure(figsize=(width, height), dpi=dpi,
                          facecolor=[0.5, 0.5, 0.5], edgecolor=None,
                          linewidth=1.0,
                          frameon=True, tight_layout=True)
        # axesハンドルの生成
        self.axes = self.fig.add_subplot(111)

        # 再描画では上書きしない
        self.axes.hold(False)

        # 画像の初期表示
        self.compute_initial_fiugre()

        # コンストラクタ
        FigureCanvas.__init__(self, self.fig)

        # 親のウィジェットを生成
        self.setParent(parent)

        # サイズの設定
        # FigureCanvas.setSizePolicy(self,
        #                            QtGui.QSizePolicy.Expanding,
        #                            QtGui.QSizePolicy.Expanding)

        # サイズの更新
        FigureCanvas.updateGeometry(self)
Esempio n. 8
0
class PlotWidget(QWidget):
    """
    matplotlib plot widget
    """
    def __init__(self,parent):
        super(PlotWidget,self).__init__(parent)
        
        self.figure = plt.figure()
        self.canvas = FigureCanvas(self.figure)
        self.toolbar = NavigationToolbar(self.canvas, self)
        
        self.ax = self.figure.add_subplot(111) # create an axis

        layout = QVBoxLayout()
        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        self.setLayout(layout)      
       
    def clear(self):
        self.ax.cla()
        
    def test(self):
        """ plot random data """
        
        df = fakeData()
        
        #self.ax.hold(False) # discard old data
        #self.ax.plot(df,'o-')
        self.clear()
        df.plot(ax=self.ax)        
        
        self.canvas.draw()
    def __init__(self, parent, ionCatalogArray, ionSwapCatalog):
        self.parent = parent
        self.fig = Figure()
        FigureCanvas.__init__(self, self.fig)

        self.ax1 = self.fig.add_subplot(141)
        self.ax2 = self.fig.add_subplot(142)
        self.ax3 = self.fig.add_subplot(143)
        self.ax4 = self.fig.add_subplot(144)
        
        self.setHist(self.ax1, ionCatalogArray[0], label = 'initial')
        self.setHist(self.ax2, ionCatalogArray[1], label = 'shine729')
        self.setHist(self.ax3, ionCatalogArray[2], label = 'final')
        
        self.ax1.set_xlabel('Number Of Bright Ions')
        self.ax2.set_xlabel('Number Of Dark Ions')
        self.ax2.text(.35, .75, str((len(np.where(np.array(ionCatalogArray[1]) == 1)[0])/float(len(ionCatalogArray[1])))*100) + ' percent w/ one ion dark', fontsize=12, transform = self.ax2.transAxes)
        self.ax2.text(.35, .8, 'Mean: ' + str(np.mean(ionCatalogArray[1])) + ' ions dark', transform = self.ax2.transAxes)
        self.ax2.set_ylim(0, 1)
        self.ax3.set_xlabel('Number Of Dark Ions')
        self.ax3.text(.35, .75, str((len(np.where(np.array(ionCatalogArray[2]) == 1)[0])/float(len(ionCatalogArray[2])))*100) + ' percent w/ one ion dark', fontsize=12, transform = self.ax3.transAxes)
        self.ax3.text(.35, .8, 'Mean: ' + str(np.mean(ionCatalogArray[2])) + ' ions dark', transform = self.ax3.transAxes)
        self.ax3.set_ylim(0, 1)

        self.ax4.hist(ionSwapCatalog, bins=range(self.parent.parent.expectedNumberOfIonsSpinBox.value()), align='left', normed = True, label = 'Ion Swaps' )
        self.ax4.legend(loc='best')
        self.ax4.set_xlabel('Distance of Ion Movement')
        self.ax4.text(.25, .8, 'Number Ion Swaps: ' + str(len(np.where(np.array(ionSwapCatalog) == 1)[0])), transform = self.ax4.transAxes)
        self.ax4.text(0.025, .75, '1 ion dark in both shine729 and final: ' + str(len(ionSwapCatalog)/float(len(ionCatalogArray[0]))*100) + ' %', transform = self.ax4.transAxes)
        self.ax4.text(0.10, .70, 'Probability of Ion Swap: ' + str(len(np.where(np.array(ionSwapCatalog) == 1)[0])/float(len(ionSwapCatalog))), transform = self.ax4.transAxes)
Esempio n. 10
0
    def __init__(self, parent):    
        # instantiate figure
        self.fig = Figure()
        FigureCanvas.__init__(self, self.fig)
        #self.parent = parent
        self.parent = parent      
        self.datasetLabelsDict = {}
        self.plotParametersDict = {}
        self.dataDict = {}
        self.plotDict = {}
        self.maxDatasetSizeReached = False
        self.data = None
        self.drawCounter = 0
        # create plot 
        self.ax = self.fig.add_subplot(111)
        self.ax.grid()
        colormap = pyplot.cm.gist_ncar
#        self.ax.set_color_cycle([colormap(i) for i in np.linspace(0, 0.9, 15)])
        colors = ['b', 'g', 'r', 'm', 'k']
        colors.extend([colormap(i) for i in np.linspace(.2, 0.9, 7)])
        colors.pop(8)
        self.ax.set_color_cycle(colors)
        lines = ["-"]#,"-","-","-","-","-.","-.","-.","-.","-.","--","--","--","--","--",":",":",":",":",":"]
        self.linecycler = cycle(lines)

        self.background = self.copy_from_bbox(self.ax.bbox)
Esempio n. 11
0
    def __init__(self, spurset, fef, parent):
        chart.__init__(self, spurset, fef, parent)

        # make the figure blend in with the native application look
        bgcol = parent.palette().window().color().toRgb()
        bgcol = [bgcol.redF(), bgcol.greenF(), bgcol.blueF()]

        self.fig = Figure()
        self.fig.set_facecolor(bgcol)
        
        # a FigureCanvas can be added as a QWidget, so we use that
        self.plot = FigureCanvas(self.fig)
        self.plot.setParent(parent)

        self.ax = self.fig.add_subplot(111)
        # TODO skip this, just do a redraw() after initialization?
        self.ax.set_xlim(self.spurset.RFmin, self.spurset.RFmax)
        self.ax.set_ylim(-0.5*self.spurset.dspan, 0.5*self.spurset.dspan)
        self.ax.grid(True)
        self.fig.tight_layout()

        # a second figure to hold the legend
        self.legendFig = Figure()
        self.legendFig.set_facecolor(bgcol)
        self.legendCanvas = FigureCanvas(self.legendFig)
        self.legendFig.legend(*self.ax.get_legend_handles_labels(),
                              loc='upper left')

        # connect up the picker watching
        self.picked_obj = None
        self._pick = self.plot.mpl_connect('pick_event', self.onpick)
        self._drag = self.plot.mpl_connect('motion_notify_event', self.ondrag)
        self._drop = self.plot.mpl_connect('button_release_event', self.ondrop)
class WireMap(QtGui.QWidget):

    def __init__(self, parent=None):
        super(WireMap,self).__init__(parent)
        self.parent = parent

        self.setup_widgets()

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

    def setup_widgets(self):
        # setting up dimensions
        self.fig = Figure((5.0, 4.0), dpi=100)
        #attaching the figure to the canvas
        self.canvas = FigureCanvas(self.fig)
        #attaching a toolbar to the canvas
        self.toolbar = NavigationToolbar(self.canvas, self.parent)

        self.axs = [[] for i in range(6)]
        self.pts = [[None]*6 for i in range(6)]

        sector_grid = gridspec.GridSpec(2,3,wspace=0.3,hspace=0.2)
        for sec in range(6):
            slyr_grid = gridspec.GridSpecFromSubplotSpec(6,1,
                wspace=0.0,hspace=0.1,
                subplot_spec=sector_grid[sec])
            for slyr in range(6):
                self.axs[sec].append(
                    self.fig.add_subplot(slyr_grid[5-slyr]))

    def update_plots(self):
        for sec in range(6):
            for slyr in range(6):
                self.pts[sec][slyr] = \
                    self.superlayer_plot(self.axs[sec][slyr],sec,slyr)
        self.canvas.draw()

    def superlayer_plot(self,ax,sec,slyr):
        if not hasattr(self,'data'):
            self.data = fetchCrateArray(session)
        pt = ax.imshow(self.data[sec][slyr],
            origin='lower',
            aspect='auto',
            interpolation='nearest',
            extent=[0.5,112.5,-0.5,5.5],
            vmin=0,
            cmap=cm.ocean)
        if slyr == 5:
            ax.set_title('Sector '+str(sec+1))
        if (sec > 2) and (slyr == 0):
            ax.xaxis.set_ticks([1]+list(range(32,113,32)))
            ax.xaxis.set_ticklabels([1]+list(range(32,113,32)))
        else:
            ax.xaxis.set_major_locator(pyplot.NullLocator())
        ax.set_ylabel(str(slyr+1))
        ax.yaxis.set_major_locator(pyplot.NullLocator())
        ax.hold(False)
        return pt
Esempio n. 13
0
class histpanel(QtGui.QWidget):
    def __init__(self,app):
        super(histpanel,self).__init__()
        self.layout =QtGui.QVBoxLayout()
        self.setLayout(self.layout )
        self.figure=plt.figure()
        self.canvas=FigureCanvas(self.figure)
   
        self.layout.addWidget(self.canvas)
        self.histdata=[]
        self.app=app
       
    def plot(self,datastr):
        data=json.loads(unicode(datastr))
        if "history" in data["data"]:
            self.histdata=np.array(data["data"]["history"])
            self.timestep(datastr)
         
    def timestep(self,resultstr):
        data=json.loads(unicode(resultstr))
        timestamp=data["data"]["stat"]["time"]
     
        if (   self.app.tab.currentIndex()==2 ):
            self.figure.clf()
            ax=self.figure.add_subplot(111)
            self.figure.set_frameon(False)
            ax.patch.set_alpha(0)
            ax.set_xlabel("Time [s]")
            ax.set_ylabel("Image Count")
            ppl.hist(ax,self.histdata-np.ceil(timestamp),bins=100,range=(-100,0))
            ax.set_xlim((-100,0))
            tstr= datetime.datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
            ax.set_title(tstr +", "+ str(data["data"]["stat"]['images processed'])+" Images Processed")

            self.canvas.draw()
 def __init__(self, filename):
     FigureCanvas.__init__(self, Figure())
     self.spike_axes = self.figure.add_subplot(131)
     self.spike_axes.set_title('Spike trains')
     self.vm_axes =  self.figure.add_subplot(132)
     self.vm_axes.set_title('Vm')
     self.ca_axes = self.figure.add_subplot(133)
     self.ca_axes.set_title('[Ca2+]')
     self.spike_axes_bg = self.copy_from_bbox(self.spike_axes.bbox)
     self.vm_axes_bg = self.copy_from_bbox(self.vm_axes.bbox)
     self.ca_axes_bg = self.copy_from_bbox(self.ca_axes.bbox)
     self.datafilename = filename
     self.spiketrain_dict = {}
     self.vm_dict = {}
     self.ca_dict = {}
     self.spike_matrix = None
     self.simtime = None
     self.simdt = None
     self.plotdt = None
     self.timestamp = None
     self.frame_count = 0
     self.timepoints = []
     self.cell_index_map = {}
     self.index_cell_map = {}
     self._read_data()
     self.draw()
Esempio n. 15
0
class TrimCanvas(QtGui.QWidget):
    def __init__(self):
        super(TrimCanvas, self).__init__()
        self.figure = plt.figure()
        self.canvas = FigureCanvas(self.figure)
        self.toolbar = NavigationToolbar2QT(self.canvas, self)
        self.frames = None
        self.data = None
        self.handles = None
        self.timedata = None
        self.interval = None

    def replot(self, mode):
        data = plots.raw(f_sampling, self.data)
        self.timedata = data['x_vector']
        data['legend'] = 'Tymczasowe nagranie'
        if mode == 'm':
            data['sliders'] = (self.timedata[-1]*0.1, self.timedata[-1]*0.1 + self.interval, self.interval)
            self.handles = plot_trimmable(self.figure, data)
        else:
            data['tight'] = True
            self.handles = plot_function(self.figure, data)
        self.canvas.draw()

    def clear_data(self):
        self.figure.clear()
        self.canvas.draw()
        self.frames = None
        self.data = None

    def data2frames(self):
        bytes = self.data.tobytes()
        self.frames = [bytes[i:i+2048] for i in range(0, len(bytes), 2048)]
Esempio n. 16
0
class MatplotlibWidget:
    def __init__(self, mainWidget, settingsWidget):
        self.settingsWidget = settingsWidget

        self.figure = Figure()
        self.figureCanvas = FigureCanvas(self.figure)

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

        font = {'family': 'Courier New'}
        self.axes.set_title(u'График веса', font)
        self.axes.set_xlabel(u'Дата', font)
        self.axes.set_ylabel(u'Вес, кг', font)
        self.set_mass_limits()

        mainWidget.verticalLayout.insertWidget(0, self.figureCanvas)

    def plot(self, x, y):
        self.line1 = self.axes.plot(x, y)
        self.axes.set_xticklabels([n.strftime('%d:%m:%Y') for i, n in enumerate(x)], rotation=15)
        # self.axes.clear()
        self.figureCanvas.draw()

    def set_mass_limits(self):
        self.axes.set_ylim(
            (self.settingsWidget.downMassDoubleSpinBox.value(), self.settingsWidget.upMassDoubleSpinBox.value()))
        self.figureCanvas.draw()
    def __init__(self, parent=None,
                 size = (7,3.5),
                 dpi = 100,
                 logx = False,
                 logy = False,
                 legends = True,
                 bw = False):

        self.fig = Figure(figsize=size, dpi=dpi) #in inches
        FigureCanvas.__init__(self, self.fig)
        FigureCanvas.setSizePolicy(self,
                                   qt.QSizePolicy.Expanding,
                                   qt.QSizePolicy.Expanding)
        self.curveTable = None
        self.dpi=dpi
        ddict = {'logx':logx,
                 'logy': logy,
                 'legends':legends,
                 'bw':bw}
        self.ax=None
        self.curveList = []
        self.curveDict = {}
        self.setParameters(ddict)
        #self.setBlackAndWhiteEnabled(bw)
        #self.setLogXEnabled(logx)
        #self.setLogYEnabled(logy)
        #self.setLegendsEnabled(legends)

        self.xmin = None
        self.xmax = None
        self.ymin = None
        self.ymax = None
        self.limitsSet = False
Esempio n. 18
0
class MathTextLabel(qt.QWidget):
    def __init__(self, mathText, parent=None, **kwargs):
        qt.QWidget.__init__(self, parent, **kwargs)

        l=qt.QVBoxLayout(self)
        l.setContentsMargins(0,0,0,0)

        r,g,b,a=self.palette().base().color().getRgbF()

        self._figure=Figure(edgecolor=(r,g,b), facecolor=(r,g,b))
        self._canvas=FigureCanvas(self._figure)
        l.addWidget(self._canvas)

        self._figure.clear()
        text=self._figure.suptitle(
            mathText,
            x=0.0,
            y=1.0,
            horizontalalignment='left',
            verticalalignment='top',
            size=qt.qApp.font().pointSize()*3)
        self._canvas.draw()
        (x0,y0),(x1,y1)=text.get_window_extent().get_points()
        w=x1-x0; h=y1-y0

        #self._figure.set_size_inches(w/4, h/4)
        self.setFixedSize(w,h)
Esempio n. 19
0
    def _setup_plot(self):
        # Image setup
        self.fig = Figure()

        FigureCanvas.__init__(self, self.fig)

        # Create plot, set x and y axes
        ax = self.fig.add_subplot(111)
        ax.set_ylim(0, 100)

        # Build up timestamps
        base = datetime.datetime.now()
        date_ranges = [base - datetime.timedelta(seconds=x) for x in range(0,self.window_size)]

        for pin in range(5):
            sensor_values = [0] * self.window_size

            s_plot, = ax.plot(date_ranges,sensor_values, label="Analog {}".format(pin))

            # Add the ax and plot to our monitor
            self.sensor_readings[pin] = sensor_values
            plot_dict = {'plot': s_plot, 'ax': ax}
            self.sensor_plots[pin] = plot_dict

        # Show legend
        ax.legend()

        # Fix date formatting
        self.fig.autofmt_xdate();

        # Draw the initial canvas
        self.fig.canvas.draw()
Esempio n. 20
0
    def __init__(self, data, parent=None):
        super(WaldoProcessPage, self).__init__(parent)

        self.data = data
        self.waldoProcessCompleted = False
        self.setTitle("Running WALDO")

        self.image_figure = plt.figure()
        self.image_canvas = FigureCanvas(self.image_figure)
        self.image_canvas.setMinimumSize(50, 50)
        self.image_canvas.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.ax_image = self.image_figure.add_subplot(111)
        self.ax_image.axis('off')

        self.report_figure = plt.figure()
        self.report_canvas = FigureCanvas(self.report_figure)
        self.report_canvas.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.report_canvas.setMinimumSize(50, 50)
        self.ax_report = self.report_figure.add_subplot(111)

        self.main_layout = QtGui.QHBoxLayout()
        self.showing_status = WaldoProcessPage.SHOWING_NOTHING

        layout = QtGui.QVBoxLayout()
        layout.addLayout(self.main_layout)
        self.setLayout(layout)
Esempio n. 21
0
 def __init__(self, dataGenerator, dtTimer=1000, ylim=None, xlim=None, startsWithZeroZero=False, title=''):
     self.fig = Figure()
     self.ax = self.fig.add_subplot(111)
     FigureCanvas.__init__(self, self.fig)
     self.title = title
     self.dataGen = dataGenerator
     x, t = self.dataGen.next()
     self.setTitle(t)
     self.counter = 1
     self.width = 0.8
     self.locs = np.arange(len(x))
     self.bars = self.ax.bar(self.locs, x, self.width, color='#6a7ea6')
     if not ylim: ylim = []
     if not xlim: xlim = []
     if (startsWithZeroZero):
         if (ylim):
             ylim[0] = 0
         else:
             ylim = [0, max(x * 1.1)]
         if (xlim):
             xlim[0] = -0.5
         else:
             xlim = [-0.5, len(x)]
     if (ylim): self.ax.set_ylim(ylim[0], ylim[1])
     if (xlim): self.ax.set_xlim(xlim[0], xlim[1])
     self.fig.canvas.draw()
     self.show()
     self.timer = self.startTimer(dtTimer)
Esempio n. 22
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()
Esempio n. 23
0
    def __init__(self, map_, width, height, parent=None, dpi=100, **matplot_args):  # pylint: disable=W0613
        # self._widthHint = width
        # self._heightHint = height

        self._origMap = map_
        self._map = map_.resample((width, height))

        # Old way (segfaults in some environements)
        # self.figure = self._map.plot_simple(**matplot_args)
        # FigureCanvas.__init__(self, self.figure)

        self.figure = Figure()
        self._map.plot(figure=self.figure, basic_plot=True, **matplot_args)
        self.axes = self.figure.gca()
        FigureCanvas.__init__(self, self.figure)

        # How can we get the canvas to preserve its aspect ratio when expanding?
        # sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)
        # sizePolicy.setHeightForWidth(True)
        # self.setSizePolicy(sizePolicy)

        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
        self.setSizePolicy(sizePolicy)
        self.setMinimumSize(QtCore.QSize(width, height))
        self.setMaximumSize(QtCore.QSize(width, height))
Esempio n. 24
0
class MainWidget(QtGui.QWidget):
    def __init__(self, parent=None):
        super(MainWidget, self).__init__(parent)

        # a figure instance to plot on
        self.figure = plt.figure()

        # this is the Canvas Widget that displays /embpyqt/python/the `figure`
        # it takes the `figure` instance as a parameter to __init__
        self.canvas = FigureCanvas(self.figure)

        # this is the Navigation widget
        # it takes the Canvas widget and a parent
        self.toolbar = NavigationToolbar(self.canvas, self)

        # Just some button connected to `plot` method
        self.button = QtGui.QPushButton('Plot')
        self.button.clicked.connect(self.plot)

        # set the layout
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        layout.addWidget(self.button)
        self.setLayout(layout)

    def plot(self):
        ''' plot some random stuff '''
        # random data
        '''data = [random.random() for i in range(2)]

        # create an axis
        ax = self.figure.add_subplot(111)

        # discards the old graph
        ax.hold(False)

        # plot data
        ax.plot(data, '*-')'''
        m = Basemap(projection='robin',lon_0=0,resolution='c')#,latlon=True)
        m.bluemarble(scale=0.2)
        for friend in rpc.bridge.getFriendList():
          print ''
          pd = rpc.bridge.getPeerDetails(friend)
          print pd['name']
          print pd['extAddr']
          ld = gi.record_by_addr(pd['extAddr'])
          print ld
          if ld:
            print ld['latitude'],ld['longitude']
            x, y = m(ld['longitude'],ld['latitude'])
            #m.scatter(x, y,30,marker='o',color='k')
            plt.plot(x, y,'ro')
            plt.text(x,y,pd['name'],fontsize=9,
                    ha='center',va='top',color='r',
                    bbox = dict(boxstyle="square",ec='None',fc=(1,1,1,0.5)))
            #plt.text(x,y,pd['name'],fontsize=14,fontweight='bold',
            #        ha='center',va='center',color='r')
        # refresh canvas
        self.canvas.draw()
class Window(QtGui.QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        # a figure instance to plot on
        self.figure = plt.figure()

        self.canvas = FigureCanvas(self.figure)
        self.plot()

        # set the layout
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.canvas)
        self.setLayout(layout)

    def plot(self):
        ''' plot some random stuff '''
        # random data
        data = [random.random() for i in range(10)]

        # create an axis
        ax = self.figure.add_subplot(111)

        # discards the old graph
        ax.hold(False)

        # plot data
        ax.plot(data, '*-')

        # refresh canvas
        self.canvas.draw()
class RewardWidget(QtGui.QWidget):
    def __init__(self, parent=None):
        super(RewardWidget, self).__init__(parent)
        self.samples = 0
        self.resize(1500, 100)

        self.figure = Figure()

        self.canvas = FigureCanvasQTAgg(self.figure)

        self.axes = self.figure.add_axes([0, 0, 1, 1])

        self.layoutVertical = QtGui.QVBoxLayout(self)
        self.layoutVertical.addWidget(self.canvas)

    def set_time_range(self, time_range):
    	self.time_range = time_range
    	range_length = int((time_range[1] - time_range[0]))
    	self.rewards = [0] * (range_length * 100)

    def add_data(self, data_range, data):
    	begin = int(round((data_range[0] - self.time_range[0]) * 100))
    	end = int(round((data_range[1] - self.time_range[0]) * 100)) + 1
    	self.rewards[begin:end] = [data for x in range(end-begin)]
    	

    	range_length = int((self.time_range[1] - self.time_range[0]))
    	self.axes.clear()
    	self.axes.set_xlim([0,range_length*100])
    	self.axes.set_ylim([-10.0,10.0])
        self.axes.plot(self.rewards)

        self.canvas.draw()
        #print(self.rewards)
Esempio n. 27
0
    def __init__(self, parent):

        self.parent = parent
        self.fig = Figure()
        self.ax = self.fig.add_subplot(111)
        FigureCanvas.__init__(self, self.fig)
        #self.cidPress = self.mpl_connect('button_press_event', self.onClick)
        #self.cidRelease = self.mpl_connect('button_release_event', self.onRelease)


        #self.X = np.random.rand(5,5)
        #rows,cols,self.slices = self.X.shape
        #self.Y = np.random.rand(5,5)
        #rows,cols,self.slices = self.X.shape
        
        newdata = np.ones(2*2)
        newarray = np.reshape(newdata, (2, 2))
        self.data = newarray

        
        #self.im = self.ax.matshow(self.X[:,:])
        #self.im = self.ax.matshow(self.data)
        self.update()
        
        self.fig.canvas.draw()

        self.cnt = 0
        
        self.setupSelector()
Esempio n. 28
0
 def __init__(self,parent=None,width=5,height=4,dpi=100):
     figure = Figure(figsize=(width,height),dpi=dpi)
     FigureCanvas.__init__(self,figure)
     self.setParent(parent)
     self.axes = figure.add_subplot(111)
     self.axes.hold(False)
     self.axeX = [0]
Esempio n. 29
0
    def paintEvent(self, event):
        Canvas.paintEvent(self, event)
        if not self.limit_mode:
            return

       # convert to data units
        height = self.figure.bbox.height
        t = lambda s: np.array(self.axes.transData.transform(s))

        qp = QPainter()
        qp.begin(self)
        qp.setPen(QColor(*self.limit_color))

        # Draw polygon
        if self.limit_mode and self.limit_type == 1:
            for i in range(len(self.limit_data) - 1):
                start = t(self.limit_data[i])
                end = t(self.limit_data[i + 1])
                qp.drawLine(start[0], height - start[1],
                        end[0], height - end[1])
            if self.limit_data:
                start = t(self.limit_data[-1])
                end = t((self._mouse_move_event.xdata,
                    self._mouse_move_event.ydata))
                qp.drawLine(start[0], height - start[1],
                        end[0], height - end[1])

        # Draw an ellipse
        if self.limit_mode and self.limit_type == 2 and self.limit_data:
            # convert to display coordinates
            startp = t(self.limit_data[0])
            mouse = t((self._mouse_move_event.xdata,
                    self._mouse_move_event.ydata))
            center = 0.5 * (startp + mouse)

            if len(self.limit_data) == 1:  # we've set the center, draw line
                eheight = 30
                angvec = mouse - center
                angle = np.arctan2(angvec[1], angvec[0])
                ewidth = np.linalg.norm(angvec)

            elif len(self.limit_data) > 1:  # we've also fixed the angle
                angleline = t(self.limit_data[1])
                center = 0.5 * (startp + angleline)
                angvec = angleline - center
                angle = np.arctan2(angvec[1], angvec[0])
                ewidth = np.linalg.norm(angvec)
                angvec = angvec / ewidth

                mvec = mouse - center
                eheight = np.linalg.norm(mvec - np.dot(mvec, angvec) * angvec)

            if self.limit_data:
                qp.translate(center[0], height - center[1])
                qp.rotate(-angle * 180.0 / np.pi)
                qp.drawEllipse(QPoint(0, 0), ewidth, eheight)
                qp.drawLine(-ewidth, 0, ewidth, 0)
                qp.drawLine(0, -eheight, 0, eheight)

        qp.end()
Esempio n. 30
0
 def __init__(self):
     """Constructor"""
     # Create the figure in the canvas
     self.fig = Figure()
     self.ax = self.fig.add_subplot(111)
     FigureCanvas.__init__(self, self.fig)
     # generates first "empty" plot
     t = [0.0]
     e = [0.0]
     self.line, = self.ax.plot(t,
                               e,
                               color="black",
                               linestyle="-",
                               linewidth=1.0)
     # Set some options
     self.T = {{L}} / {{U}}
     self.Ek = {{E_KIN}}
     self.ax.grid()
     self.ax.set_xlim(0, 10.0)
     self.ax.set_ylim(0.0, 1.1)
     self.ax.set_autoscale_on(False)
     self.ax.set_xlabel(r"$t U / L$", fontsize=21)
     self.ax.set_ylabel(r"$\mathcal{E}_{k}(t) / \mathcal{E}_{k}(0)$", fontsize=21)
     # force the figure redraw
     self.fig.canvas.draw()
     # call the update method (to speed-up visualization)
     self.timerEvent(None)
     # start timer, trigger event every 1000 millisecs (=1sec)
     self.timer = self.startTimer(1000)
Esempio n. 31
0
class GAUDInspectChartCanvas(QtGui.QWidget):

    def __init__(self, parent=None):
        super(GAUDInspectChartCanvas, self).__init__(parent)
        self.initUI()

    def initUI(self):
        plt.style.use('fivethirtyeight')
        plt.rc('font', size=12)
        self.figure = plt.figure()
        self.canvas = FigureCanvas(self.figure)

        self.figure.patch.set_alpha(0)
        self.ax1 = self.figure.add_subplot(
            111, axis_bgcolor='none',
            xlim=(0, 20), ylim=(0, 1000),
            xlabel='Generations')
        self.ax2 = self.ax1.twinx()
        self.legend = plt.legend(
            *self.ax1.get_legend_handles_labels(),
            loc='upper left', fancybox=True, framealpha=0.8)

        # set the layout
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.canvas)
        self.setLayout(layout)
        self.figure.tight_layout()

    def configure_plot(self, generations, objectives, population):
        # Clear eveything
        self.legend.remove()
        self.ax1.cla()
        self.ax2.cla()

        self.ax1.set_axis_bgcolor('none')
        self.ax1.set_xlabel('Generations')
        self.ax1.set_ylabel('Average score')
        self.ax1.set_autoscalex_on(False)
        self.ax1.set_xlim(1, generations)
        self.ax1.set_autoscaley_on(True)

        # Create a line plotter for each objective
        self.lines = []
        for obj in objectives:
            line, = self.ax1.plot([], label=obj['name'])
            self.lines.append(line)

        # Create legend for objectives
        self.legend = plt.legend(*self.ax1.get_legend_handles_labels(),
                                 loc='upper left', fancybox=True, framealpha=0.8)

        # Get a second Y axis for evaluations
        self.ax2.set_ylim(0, population)
        self.ax2.set_xlim(1, generations)
        self.ax2.set_ylabel('Individuals evaluated')
        self.ax2.grid(b=False)
        # Fix Z-ordering of axes
        self.ax1.set_zorder(self.ax2.get_zorder() + 1)

        # Draw evaluations per generation
        self.rects = self.ax2.bar(
            range(1, generations + 1), [0] * generations,
            align='center', color='0.85')

        # Move legend to top
        self.ax1.add_artist(self.legend)
        self.ax2.legend_ = None

        self.figure.tight_layout()
        self.canvas.draw()

    def plot(self, objectives, evals, gen):
        self.rects[gen - 1].set_height(evals)
        for line, obj in zip(self.lines, objectives):
            line.set_data(numpy.append(line.get_xdata(), gen),
                          numpy.append(line.get_ydata(), obj[0]))
        # Update view (yes, all these commands are compulsory)
        self.ax1.relim()
        self.ax1.autoscale_view()
        self.figure.tight_layout()
        self.canvas.draw()
Esempio n. 32
0
class SquidGui(QMainWindow):
    defaults = {}
    defaults.update(SquidAxon.defaults)
    defaults.update(ClampCircuit.defaults)
    defaults.update({
        'runtime': 50.0,
        'simdt': 0.01,
        'plotdt': 0.1,
        'vclamp.holdingV': 0.0,
        'vclamp.holdingT': 10.0,
        'vclamp.prepulseV': 0.0,
        'vclamp.prepulseT': 0.0,
        'vclamp.clampV': 50.0,
        'vclamp.clampT': 20.0,
        'iclamp.baseI': 0.0,
        'iclamp.firstI': 0.1,
        'iclamp.firstT': 40.0,
        'iclamp.firstD': 5.0,
        'iclamp.secondI': 0.0,
        'iclamp.secondT': 0.0,
        'iclamp.secondD': 0.0
    })

    def __init__(self, *args):
        QMainWindow.__init__(self, *args)
        self.squid_setup = SquidSetup()
        self._plotdt = SquidGui.defaults['plotdt']
        self._plot_dict = defaultdict(list)
        self.setWindowTitle('Squid Axon simulation')
        self.setDockNestingEnabled(True)
        self._createRunControl()
        self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self._runControlDock)
        self._runControlDock.setFeatures(QDockWidget.AllDockWidgetFeatures)
        self._createChannelControl()
        self._channelCtrlBox.setWindowTitle('Channel properties')
        self._channelControlDock.setFeatures(QDockWidget.AllDockWidgetFeatures)
        self.addDockWidget(QtCore.Qt.LeftDockWidgetArea,
                           self._channelControlDock)
        self._createElectronicsControl()
        self._electronicsDock.setFeatures(QDockWidget.AllDockWidgetFeatures)
        self._electronicsDock.setWindowTitle('Electronics')
        self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self._electronicsDock)
        self._createPlotWidget()
        self.setCentralWidget(self._plotWidget)
        self._createStatePlotWidget()
        self._createHelpMessage()
        self._helpWindow.setVisible(False)
        self._statePlotWidget.setWindowFlags(QtCore.Qt.Window)
        self._statePlotWidget.setWindowTitle('State plot')
        self._initActions()
        self._createRunToolBar()
        self._createPlotToolBar()

    def getFloatInput(self, widget, name):
        try:
            return float(str(widget.text()))
        except ValueError:
            QMessageBox.critical(
                self, 'Invalid input',
                'Please enter a valid number for {}'.format(name))
            raise

    def _createPlotWidget(self):
        self._plotWidget = QWidget()
        self._plotFigure = Figure()
        self._plotCanvas = FigureCanvas(self._plotFigure)
        self._plotCanvas.setSizePolicy(QSizePolicy.Expanding,
                                       QSizePolicy.Expanding)
        self._plotCanvas.updateGeometry()
        self._plotCanvas.setParent(self._plotWidget)
        self._plotCanvas.mpl_connect('scroll_event', self._onScroll)
        self._plotFigure.set_canvas(self._plotCanvas)
        # Vm and command voltage go in the same subplot
        self._vm_axes = self._plotFigure.add_subplot(
            2, 2, 1, title='Membrane potential')
        self._vm_axes.set_ylim(-20.0, 120.0)
        # Channel conductances go to the same subplot
        self._g_axes = self._plotFigure.add_subplot(
            2, 2, 2, title='Channel conductance')
        self._g_axes.set_ylim(0.0, 0.5)
        # Injection current for Vclamp/Iclamp go to the same subplot
        self._im_axes = self._plotFigure.add_subplot(2,
                                                     2,
                                                     3,
                                                     title='Injection current')
        self._im_axes.set_ylim(-0.5, 0.5)
        # Channel currents go to the same subplot
        self._i_axes = self._plotFigure.add_subplot(2,
                                                    2,
                                                    4,
                                                    title='Channel current')
        self._i_axes.set_ylim(-10, 10)
        for axis in self._plotFigure.axes:
            axis.set_autoscale_on(False)
        layout = QVBoxLayout()
        layout.addWidget(self._plotCanvas)
        self._plotNavigator = NavigationToolbar(self._plotCanvas,
                                                self._plotWidget)
        layout.addWidget(self._plotNavigator)
        self._plotWidget.setLayout(layout)

    def _createStatePlotWidget(self):
        self._statePlotWidget = QWidget()
        self._statePlotFigure = Figure()
        self._statePlotCanvas = FigureCanvas(self._statePlotFigure)
        self._statePlotCanvas.setSizePolicy(QSizePolicy.Expanding,
                                            QSizePolicy.Expanding)
        self._statePlotCanvas.updateGeometry()
        self._statePlotCanvas.setParent(self._statePlotWidget)
        self._statePlotFigure.set_canvas(self._statePlotCanvas)
        self._statePlotFigure.subplots_adjust(hspace=0.5)
        self._statePlotAxes = self._statePlotFigure.add_subplot(
            2, 1, 1, title='State plot')
        self._state_plot, = self._statePlotAxes.plot([], [], label='state')
        self._activationParamAxes = self._statePlotFigure.add_subplot(
            2, 1, 2, title='H-H activation parameters vs time')
        self._activationParamAxes.set_xlabel('Time (ms)')
        #for axis in self._plotFigure.axes:
        #    axis.autoscale(False)
        self._stateplot_xvar_label = QLabel('Variable on X-axis')
        self._stateplot_xvar_combo = QComboBox()
        self._stateplot_xvar_combo.addItems(['V', 'm', 'n', 'h'])
        self._stateplot_xvar_combo.setCurrentText('V')
        self._stateplot_xvar_combo.setEditable(False)
        self._stateplot_xvar_combo.currentIndexChanged[str].connect(
            self._statePlotXSlot)
        self._stateplot_yvar_label = QLabel('Variable on Y-axis')
        self._stateplot_yvar_combo = QComboBox()
        self._stateplot_yvar_combo.addItems(['V', 'm', 'n', 'h'])
        self._stateplot_yvar_combo.setCurrentIndex(2)
        self._stateplot_yvar_combo.setEditable(False)
        self._stateplot_yvar_combo.currentIndexChanged[str].connect(
            self._statePlotYSlot)
        self._statePlotNavigator = NavigationToolbar(self._statePlotCanvas,
                                                     self._statePlotWidget)
        frame = QFrame()
        frame.setFrameStyle(QFrame.StyledPanel + QFrame.Raised)
        layout = QHBoxLayout()
        layout.addWidget(self._stateplot_xvar_label)
        layout.addWidget(self._stateplot_xvar_combo)
        layout.addWidget(self._stateplot_yvar_label)
        layout.addWidget(self._stateplot_yvar_combo)
        frame.setLayout(layout)
        self._closeStatePlotAction = QAction('Close', self)
        self._closeStatePlotAction.triggered.connect(
            self._statePlotWidget.close)
        self._closeStatePlotButton = QToolButton()
        self._closeStatePlotButton.setDefaultAction(self._closeStatePlotAction)
        layout = QVBoxLayout()
        layout.addWidget(frame)
        layout.addWidget(self._statePlotCanvas)
        layout.addWidget(self._statePlotNavigator)
        layout.addWidget(self._closeStatePlotButton)
        self._statePlotWidget.setLayout(layout)
        # Setting the close event so that when the help window is
        # closed the ``State plot`` button becomes unchecked
        self._statePlotWidget.closeEvent = lambda event: self._showStatePlotAction.setChecked(
            False)

    def _createRunControl(self):
        self._runControlBox = QGroupBox(self)
        self._runControlBox.setSizePolicy(QSizePolicy.Preferred,
                                          QSizePolicy.Preferred)
        self._runTimeLabel = QLabel("Run time (ms)", self._runControlBox)
        self._simTimeStepLabel = QLabel("Simulation time step (ms)",
                                        self._runControlBox)
        self._runTimeEdit = QLineEdit('%g' % (SquidGui.defaults['runtime']),
                                      self._runControlBox)
        set_default_line_edit_size(self._runTimeEdit)
        self._simTimeStepEdit = QLineEdit('%g' % (SquidGui.defaults['simdt']),
                                          self._runControlBox)
        set_default_line_edit_size(self._simTimeStepEdit)
        layout = QGridLayout()
        layout.addWidget(self._runTimeLabel, 0, 0)
        layout.addWidget(self._runTimeEdit, 0, 1)
        layout.addWidget(self._simTimeStepLabel, 1, 0)
        layout.addWidget(self._simTimeStepEdit, 1, 1)
        layout.setColumnStretch(2, 1.0)
        layout.setRowStretch(2, 1.0)
        self._runControlBox.setLayout(layout)
        self._runControlDock = QDockWidget('Simulation', self)
        self._runControlDock.setWidget(self._runControlBox)

    def _createChannelControl(self):
        self._channelControlDock = QDockWidget('Channels', self)
        self._channelCtrlBox = QGroupBox(self)
        self._naConductanceToggle = QCheckBox('Block Na+ channel',
                                              self._channelCtrlBox)
        self._naConductanceToggle.setToolTip('<html>%s</html>' %
                                             (tooltip_NaChan))
        self._kConductanceToggle = QCheckBox('Block K+ channel',
                                             self._channelCtrlBox)
        self._kConductanceToggle.setToolTip('<html>%s</html>' %
                                            (tooltip_KChan))
        self._kOutLabel = QLabel('[K+]out (mM)', self._channelCtrlBox)
        self._kOutEdit = QLineEdit('%g' % (self.squid_setup.axon.K_out),
                                   self._channelCtrlBox)
        self._kOutLabel.setToolTip('<html>%s</html>' % (tooltip_Nernst))
        self._kOutEdit.setToolTip('<html>%s</html>' % (tooltip_Nernst))
        set_default_line_edit_size(self._kOutEdit)
        self._naOutLabel = QLabel('[Na+]out (mM)', self._channelCtrlBox)
        self._naOutEdit = QLineEdit('%g' % (self.squid_setup.axon.Na_out),
                                    self._channelCtrlBox)
        self._naOutLabel.setToolTip('<html>%s</html>' % (tooltip_Nernst))
        self._naOutEdit.setToolTip('<html>%s</html>' % (tooltip_Nernst))
        set_default_line_edit_size(self._naOutEdit)
        self._kInLabel = QLabel('[K+]in (mM)', self._channelCtrlBox)
        self._kInEdit = QLineEdit('%g' % (self.squid_setup.axon.K_in),
                                  self._channelCtrlBox)
        self._kInEdit.setToolTip(tooltip_Nernst)
        self._naInLabel = QLabel('[Na+]in (mM)', self._channelCtrlBox)
        self._naInEdit = QLineEdit('%g' % (self.squid_setup.axon.Na_in),
                                   self._channelCtrlBox)
        self._naInEdit.setToolTip('<html>%s</html>' % (tooltip_Nernst))
        self._temperatureLabel = QLabel('Temperature (C)',
                                        self._channelCtrlBox)
        self._temperatureEdit = QLineEdit(
            '%g' % (self.defaults['temperature'] - CELSIUS_TO_KELVIN),
            self._channelCtrlBox)
        self._temperatureEdit.setToolTip('<html>%s</html>' % (tooltip_Nernst))
        set_default_line_edit_size(self._temperatureEdit)
        for child in self._channelCtrlBox.children():
            if isinstance(child, QLineEdit):
                set_default_line_edit_size(child)
        layout = QGridLayout(self._channelCtrlBox)
        layout.addWidget(self._naConductanceToggle, 0, 0)
        layout.addWidget(self._kConductanceToggle, 1, 0)
        layout.addWidget(self._naOutLabel, 2, 0)
        layout.addWidget(self._naOutEdit, 2, 1)
        layout.addWidget(self._naInLabel, 3, 0)
        layout.addWidget(self._naInEdit, 3, 1)
        layout.addWidget(self._kOutLabel, 4, 0)
        layout.addWidget(self._kOutEdit, 4, 1)
        layout.addWidget(self._kInLabel, 5, 0)
        layout.addWidget(self._kInEdit, 5, 1)
        layout.addWidget(self._temperatureLabel, 6, 0)
        layout.addWidget(self._temperatureEdit, 6, 1)
        layout.setRowStretch(7, 1.0)
        self._channelCtrlBox.setLayout(layout)
        self._channelControlDock.setWidget(self._channelCtrlBox)
        return self._channelCtrlBox

    def __get_stateplot_data(self, name):
        data = []
        if name == 'V':
            data = self.squid_setup.vm_table.vector
        elif name == 'm':
            data = self.squid_setup.m_table.vector
        elif name == 'h':
            data = self.squid_setup.h_table.vector
        elif name == 'n':
            data = self.squid_setup.n_table.vector
        else:
            raise ValueError('Unrecognized selection: %s' % name)
        return numpy.asarray(data)

    def _statePlotYSlot(self, selectedItem):
        ydata = self.__get_stateplot_data(str(selectedItem))
        self._state_plot.set_ydata(ydata)
        self._statePlotAxes.set_ylabel(selectedItem)
        if str(selectedItem) == 'V':
            self._statePlotAxes.set_ylim(-20, 120)
        else:
            self._statePlotAxes.set_ylim(0, 1)
        self._statePlotCanvas.draw()

    def _statePlotXSlot(self, selectedItem):
        xdata = self.__get_stateplot_data(str(selectedItem))
        self._state_plot.set_xdata(xdata)
        self._statePlotAxes.set_xlabel(selectedItem)
        if str(selectedItem) == 'V':
            self._statePlotAxes.set_xlim(-20, 120)
        else:
            self._statePlotAxes.set_xlim(0, 1)
        self._statePlotCanvas.draw()

    def _createElectronicsControl(self):
        """Creates a tabbed widget of voltage clamp and current clamp controls"""
        self._electronicsTab = QTabWidget(self)
        self._electronicsTab.addTab(self._getIClampCtrlBox(), 'Current clamp')
        self._electronicsTab.addTab(self._getVClampCtrlBox(), 'Voltage clamp')
        self._electronicsDock = QDockWidget(self)
        self._electronicsDock.setWidget(self._electronicsTab)

    def _getVClampCtrlBox(self):
        vClampPanel = QGroupBox(self)
        self._vClampCtrlBox = vClampPanel
        self._holdingVLabel = QLabel("Holding Voltage (mV)", vClampPanel)
        self._holdingVEdit = QLineEdit(
            '%g' % (SquidGui.defaults['vclamp.holdingV']), vClampPanel)
        self._holdingTimeLabel = QLabel("Holding Time (ms)", vClampPanel)
        self._holdingTimeEdit = QLineEdit(
            '%g' % (SquidGui.defaults['vclamp.holdingT']), vClampPanel)
        self._prePulseVLabel = QLabel("Pre-pulse Voltage (mV)", vClampPanel)
        self._prePulseVEdit = QLineEdit(
            '%g' % (SquidGui.defaults['vclamp.prepulseV']), vClampPanel)
        self._prePulseTimeLabel = QLabel("Pre-pulse Time (ms)", vClampPanel)
        self._prePulseTimeEdit = QLineEdit(
            '%g' % (SquidGui.defaults['vclamp.prepulseT']), vClampPanel)
        self._clampVLabel = QLabel("Clamp Voltage (mV)", vClampPanel)
        self._clampVEdit = QLineEdit(
            '%g' % (SquidGui.defaults['vclamp.clampV']), vClampPanel)
        self._clampTimeLabel = QLabel("Clamp Time (ms)", vClampPanel)
        self._clampTimeEdit = QLineEdit(
            '%g' % (SquidGui.defaults['vclamp.clampT']), vClampPanel)
        for child in vClampPanel.children():
            if isinstance(child, QLineEdit):
                set_default_line_edit_size(child)
        layout = QGridLayout(vClampPanel)
        layout.addWidget(self._holdingVLabel, 0, 0)
        layout.addWidget(self._holdingVEdit, 0, 1)
        layout.addWidget(self._holdingTimeLabel, 1, 0)
        layout.addWidget(self._holdingTimeEdit, 1, 1)
        layout.addWidget(self._prePulseVLabel, 2, 0)
        layout.addWidget(self._prePulseVEdit, 2, 1)
        layout.addWidget(self._prePulseTimeLabel, 3, 0)
        layout.addWidget(self._prePulseTimeEdit, 3, 1)
        layout.addWidget(self._clampVLabel, 4, 0)
        layout.addWidget(self._clampVEdit, 4, 1)
        layout.addWidget(self._clampTimeLabel, 5, 0)
        layout.addWidget(self._clampTimeEdit, 5, 1)
        layout.setRowStretch(6, 1.0)
        vClampPanel.setLayout(layout)
        return self._vClampCtrlBox

    def _getIClampCtrlBox(self):
        iClampPanel = QGroupBox(self)
        self._iClampCtrlBox = iClampPanel
        self._baseCurrentLabel = QLabel("Base Current Level (uA)", iClampPanel)
        self._baseCurrentEdit = QLineEdit(
            '%g' % (SquidGui.defaults['iclamp.baseI']), iClampPanel)
        self._firstPulseLabel = QLabel("First Pulse Current (uA)", iClampPanel)
        self._firstPulseEdit = QLineEdit(
            '%g' % (SquidGui.defaults['iclamp.firstI']), iClampPanel)
        self._firstDelayLabel = QLabel("First Onset Delay (ms)", iClampPanel)
        self._firstDelayEdit = QLineEdit(
            '%g' % (SquidGui.defaults['iclamp.firstD']), iClampPanel)
        self._firstPulseWidthLabel = QLabel("First Pulse Width (ms)",
                                            iClampPanel)
        self._firstPulseWidthEdit = QLineEdit(
            '%g' % (SquidGui.defaults['iclamp.firstT']), iClampPanel)
        self._secondPulseLabel = QLabel("Second Pulse Current (uA)",
                                        iClampPanel)
        self._secondPulseEdit = QLineEdit(
            '%g' % (SquidGui.defaults['iclamp.secondI']), iClampPanel)
        self._secondDelayLabel = QLabel("Second Onset Delay (ms)", iClampPanel)
        self._secondDelayEdit = QLineEdit(
            '%g' % (SquidGui.defaults['iclamp.secondD']), iClampPanel)
        self._secondPulseWidthLabel = QLabel("Second Pulse Width (ms)",
                                             iClampPanel)
        self._secondPulseWidthEdit = QLineEdit(
            '%g' % (SquidGui.defaults['iclamp.secondT']), iClampPanel)
        self._pulseMode = QComboBox(iClampPanel)
        self._pulseMode.addItem("Single Pulse")
        self._pulseMode.addItem("Pulse Train")
        for child in iClampPanel.children():
            if isinstance(child, QLineEdit):
                set_default_line_edit_size(child)
        layout = QGridLayout(iClampPanel)
        layout.addWidget(self._baseCurrentLabel, 0, 0)
        layout.addWidget(self._baseCurrentEdit, 0, 1)
        layout.addWidget(self._firstPulseLabel, 1, 0)
        layout.addWidget(self._firstPulseEdit, 1, 1)
        layout.addWidget(self._firstDelayLabel, 2, 0)
        layout.addWidget(self._firstDelayEdit, 2, 1)
        layout.addWidget(self._firstPulseWidthLabel, 3, 0)
        layout.addWidget(self._firstPulseWidthEdit, 3, 1)
        layout.addWidget(self._secondPulseLabel, 4, 0)
        layout.addWidget(self._secondPulseEdit, 4, 1)
        layout.addWidget(self._secondDelayLabel, 5, 0)
        layout.addWidget(self._secondDelayEdit, 5, 1)
        layout.addWidget(self._secondPulseWidthLabel, 6, 0)
        layout.addWidget(self._secondPulseWidthEdit, 6, 1)
        layout.addWidget(self._pulseMode, 7, 0, 1, 2)
        layout.setRowStretch(8, 1.0)
        # layout.setSizeConstraint(QLayout.SetFixedSize)
        iClampPanel.setLayout(layout)
        return self._iClampCtrlBox

    def _overlayPlots(self, overlay):
        if not overlay:
            for axis in (self._plotFigure.axes + self._statePlotFigure.axes):
                title = axis.get_title()
                axis.clear()
                axis.set_title(title)
            suffix = ''
        else:
            suffix = '_%d' % (len(self._plot_dict['vm']))
        self._vm_axes.set_xlim(0.0, self._runtime)
        self._g_axes.set_xlim(0.0, self._runtime)
        self._im_axes.set_xlim(0.0, self._runtime)
        self._i_axes.set_xlim(0.0, self._runtime)
        self._vm_plot, = self._vm_axes.plot([], [], label='Vm%s' % (suffix))
        self._plot_dict['vm'].append(self._vm_plot)
        self._command_plot, = self._vm_axes.plot([], [],
                                                 label='command%s' % (suffix))
        self._plot_dict['command'].append(self._command_plot)
        # Channel conductances go to the same subplot
        self._gna_plot, = self._g_axes.plot([], [], label='Na%s' % (suffix))
        self._plot_dict['gna'].append(self._gna_plot)
        self._gk_plot, = self._g_axes.plot([], [], label='K%s' % (suffix))
        self._plot_dict['gk'].append(self._gk_plot)
        # Injection current for Vclamp/Iclamp go to the same subplot
        self._iclamp_plot, = self._im_axes.plot([], [],
                                                label='Iclamp%s' % (suffix))
        self._vclamp_plot, = self._im_axes.plot([], [],
                                                label='Vclamp%s' % (suffix))
        self._plot_dict['iclamp'].append(self._iclamp_plot)
        self._plot_dict['vclamp'].append(self._vclamp_plot)
        # Channel currents go to the same subplot
        self._ina_plot, = self._i_axes.plot([], [], label='Na%s' % (suffix))
        self._plot_dict['ina'].append(self._ina_plot)
        self._ik_plot, = self._i_axes.plot([], [], label='K%s' % (suffix))
        self._plot_dict['ik'].append(self._ik_plot)
        # self._i_axes.legend()
        # State plots
        self._state_plot, = self._statePlotAxes.plot([], [],
                                                     label='state%s' %
                                                     (suffix))
        self._plot_dict['state'].append(self._state_plot)
        self._m_plot, = self._activationParamAxes.plot([], [],
                                                       label='m%s' % (suffix))
        self._h_plot, = self._activationParamAxes.plot([], [],
                                                       label='h%s' % (suffix))
        self._n_plot, = self._activationParamAxes.plot([], [],
                                                       label='n%s' % (suffix))
        self._plot_dict['m'].append(self._m_plot)
        self._plot_dict['h'].append(self._h_plot)
        self._plot_dict['n'].append(self._n_plot)
        if self._showLegendAction.isChecked():
            for axis in (self._plotFigure.axes + self._statePlotFigure.axes):
                axis.legend()

    def _updateAllPlots(self):
        self._updatePlots()
        self._updateStatePlot()

    def _updatePlots(self):
        if len(self.squid_setup.vm_table.vector) <= 0:
            return
        vm = numpy.asarray(self.squid_setup.vm_table.vector)
        cmd = numpy.asarray(self.squid_setup.cmd_table.vector)
        ik = numpy.asarray(self.squid_setup.ik_table.vector)

        #  tab = self.squid_setup.ina_table
        #  print(moose.showmsg(tab))

        ina = numpy.asarray(self.squid_setup.ina_table.vector)

        iclamp = numpy.asarray(self.squid_setup.iclamp_table.vector)
        vclamp = numpy.asarray(self.squid_setup.vclamp_table.vector)
        gk = numpy.asarray(self.squid_setup.gk_table.vector)
        gna = numpy.asarray(self.squid_setup.gna_table.vector)
        time_series = numpy.linspace(0, self._plotdt * len(vm), len(vm))
        self._vm_plot.set_data(time_series, vm)
        time_series = numpy.linspace(0, self._plotdt * len(cmd), len(cmd))
        self._command_plot.set_data(time_series, cmd)
        time_series = numpy.linspace(0, self._plotdt * len(ik), len(ik))
        self._ik_plot.set_data(time_series, ik)
        time_series = numpy.linspace(0, self._plotdt * len(ina), len(ina))
        self._ina_plot.set_data(time_series, ina)
        time_series = numpy.linspace(0, self._plotdt * len(iclamp),
                                     len(iclamp))
        self._iclamp_plot.set_data(time_series, iclamp)
        time_series = numpy.linspace(0, self._plotdt * len(vclamp),
                                     len(vclamp))
        self._vclamp_plot.set_data(time_series, vclamp)
        time_series = numpy.linspace(0, self._plotdt * len(gk), len(gk))
        self._gk_plot.set_data(time_series, gk)
        time_series = numpy.linspace(0, self._plotdt * len(gna), len(gna))
        self._gna_plot.set_data(time_series, gna)
        # self._vm_axes.margins(y=0.1)
        # self._g_axes.margin(y=0.1)
        # self._im_axes.margins(y=0.1)
        # self._i_axes.margins(y=0.1)
        if self._autoscaleAction.isChecked():
            for axis in self._plotFigure.axes:
                axis.relim()
                axis.margins(0.1, 0.1)
                axis.autoscale_view(tight=True)
        else:
            self._vm_axes.set_ylim(-20.0, 120.0)
            self._g_axes.set_ylim(0.0, 0.5)
            self._im_axes.set_ylim(-0.5, 0.5)
            self._i_axes.set_ylim(-10, 10)
        self._vm_axes.set_xlim(0.0, time_series[-1])
        self._g_axes.set_xlim(0.0, time_series[-1])
        self._im_axes.set_xlim(0.0, time_series[-1])
        self._i_axes.set_xlim(0.0, time_series[-1])
        self._plotCanvas.draw()

    def _updateStatePlot(self):
        if len(self.squid_setup.vm_table.vector) <= 0:
            return
        sx = str(self._stateplot_xvar_combo.currentText())
        sy = str(self._stateplot_yvar_combo.currentText())
        xdata = self.__get_stateplot_data(sx)
        ydata = self.__get_stateplot_data(sy)
        minlen = min(len(xdata), len(ydata))
        self._state_plot.set_data(xdata[:minlen], ydata[:minlen])
        self._statePlotAxes.set_xlabel(sx)
        self._statePlotAxes.set_ylabel(sy)
        if sx == 'V':
            self._statePlotAxes.set_xlim(-20, 120)
        else:
            self._statePlotAxes.set_xlim(0, 1)
        if sy == 'V':
            self._statePlotAxes.set_ylim(-20, 120)
        else:
            self._statePlotAxes.set_ylim(0, 1)
        self._activationParamAxes.set_xlim(0, self._runtime)
        m = self.__get_stateplot_data('m')
        n = self.__get_stateplot_data('n')
        h = self.__get_stateplot_data('h')
        time_series = numpy.linspace(0, self._plotdt * len(m), len(m))
        self._m_plot.set_data(time_series, m)
        time_series = numpy.linspace(0, self._plotdt * len(h), len(h))
        self._h_plot.set_data(time_series, h)
        time_series = numpy.linspace(0, self._plotdt * len(n), len(n))
        self._n_plot.set_data(time_series, n)
        if self._autoscaleAction.isChecked():
            for axis in self._statePlotFigure.axes:
                axis.relim()
                axis.set_autoscale_on(True)
                axis.autoscale_view(True)
        self._statePlotCanvas.draw()

    def _runSlot(self):
        if moose.isRunning():
            print('Stopping simulation in progress ...')
            moose.stop()
        self._runtime = self.getFloatInput(self._runTimeEdit,
                                           self._runTimeLabel.text())
        self._overlayPlots(self._overlayAction.isChecked())
        self._simdt = self.getFloatInput(self._simTimeStepEdit,
                                         self._simTimeStepLabel.text())
        clampMode = None
        singlePulse = True
        if self._electronicsTab.currentWidget() == self._vClampCtrlBox:
            clampMode = 'vclamp'
            baseLevel = self.getFloatInput(self._holdingVEdit,
                                           self._holdingVLabel.text())
            firstDelay = self.getFloatInput(self._holdingTimeEdit,
                                            self._holdingTimeLabel.text())
            firstWidth = self.getFloatInput(self._prePulseTimeEdit,
                                            self._prePulseTimeLabel.text())
            firstLevel = self.getFloatInput(self._prePulseVEdit,
                                            self._prePulseVLabel.text())
            secondDelay = firstWidth
            secondWidth = self.getFloatInput(self._clampTimeEdit,
                                             self._clampTimeLabel.text())
            secondLevel = self.getFloatInput(self._clampVEdit,
                                             self._clampVLabel.text())
            if not self._autoscaleAction.isChecked():
                self._im_axes.set_ylim(-10.0, 10.0)
        else:
            clampMode = 'iclamp'
            baseLevel = self.getFloatInput(self._baseCurrentEdit,
                                           self._baseCurrentLabel.text())
            firstDelay = self.getFloatInput(self._firstDelayEdit,
                                            self._firstDelayLabel.text())
            firstWidth = self.getFloatInput(self._firstPulseWidthEdit,
                                            self._firstPulseWidthLabel.text())
            firstLevel = self.getFloatInput(self._firstPulseEdit,
                                            self._firstPulseLabel.text())
            secondDelay = self.getFloatInput(self._secondDelayEdit,
                                             self._secondDelayLabel.text())
            secondLevel = self.getFloatInput(self._secondPulseEdit,
                                             self._secondPulseLabel.text())
            secondWidth = self.getFloatInput(
                self._secondPulseWidthEdit, self._secondPulseWidthLabel.text())
            singlePulse = (self._pulseMode.currentIndex() == 0)
            if not self._autoscaleAction.isChecked():
                self._im_axes.set_ylim(-0.4, 0.4)
        self.squid_setup.clamp_ckt.configure_pulses(baseLevel=baseLevel,
                                                    firstDelay=firstDelay,
                                                    firstWidth=firstWidth,
                                                    firstLevel=firstLevel,
                                                    secondDelay=secondDelay,
                                                    secondWidth=secondWidth,
                                                    secondLevel=secondLevel,
                                                    singlePulse=singlePulse)
        if self._kConductanceToggle.isChecked():
            self.squid_setup.axon.specific_gK = 0.0
        else:
            self.squid_setup.axon.specific_gK = SquidAxon.defaults[
                'specific_gK']
        if self._naConductanceToggle.isChecked():
            self.squid_setup.axon.specific_gNa = 0.0
        else:
            self.squid_setup.axon.specific_gNa = SquidAxon.defaults[
                'specific_gNa']
        self.squid_setup.axon.celsius = self.getFloatInput(
            self._temperatureEdit, self._temperatureLabel.text())
        self.squid_setup.axon.K_out = self.getFloatInput(
            self._kOutEdit, self._kOutLabel.text())
        self.squid_setup.axon.Na_out = self.getFloatInput(
            self._naOutEdit, self._naOutLabel.text())
        self.squid_setup.axon.K_in = self.getFloatInput(
            self._kInEdit, self._kInLabel.text())
        self.squid_setup.axon.Na_in = self.getFloatInput(
            self._naInEdit, self._naInLabel.text())
        self.squid_setup.axon.updateEk()
        self.squid_setup.schedule(self._simdt, self._plotdt, clampMode)
        # The following line is for use with Qthread
        self.squid_setup.run(self._runtime)
        self._updateAllPlots()

    def _toggleDocking(self, on):
        self._channelControlDock.setFloating(on)
        self._electronicsDock.setFloating(on)
        self._runControlDock.setFloating(on)

    def _restoreDocks(self):
        self._channelControlDock.setVisible(True)
        self._electronicsDock.setVisible(True)
        self._runControlDock.setVisible(True)

    def _initActions(self):
        self._runAction = QAction(self.tr('Run'), self)
        self._runAction.setShortcut(self.tr('F5'))
        self._runAction.setToolTip('Run simulation (F5)')
        self._runAction.triggered.connect(self._runSlot)
        self._resetToDefaultsAction = QAction(self.tr('Restore defaults'),
                                              self)
        self._resetToDefaultsAction.setToolTip(
            'Reset all settings to their default values')
        self._resetToDefaultsAction.triggered.connect(self._useDefaults)
        self._showLegendAction = QAction(self.tr('Display legend'), self)
        self._showLegendAction.setCheckable(True)
        self._showLegendAction.toggled.connect(self._showLegend)
        self._showStatePlotAction = QAction(self.tr('State plot'), self)
        self._showStatePlotAction.setCheckable(True)
        self._showStatePlotAction.setChecked(False)
        self._showStatePlotAction.toggled.connect(
            self._statePlotWidget.setVisible)
        self._autoscaleAction = QAction(self.tr('Auto-scale plots'), self)
        self._autoscaleAction.setCheckable(True)
        self._autoscaleAction.setChecked(False)
        self._autoscaleAction.toggled.connect(self._autoscale)
        self._overlayAction = QAction('Overlay plots', self)
        self._overlayAction.setCheckable(True)
        self._overlayAction.setChecked(False)
        self._dockAction = QAction('Undock all', self)
        self._dockAction.setCheckable(True)
        self._dockAction.setChecked(False)
        #  self._dockAction.toggle.connect( self._toggleDocking)
        self._restoreDocksAction = QAction('Show all', self)
        self._restoreDocksAction.triggered.connect(self._restoreDocks)
        self._quitAction = QAction(self.tr('&Quit'), self)
        self._quitAction.setShortcut(self.tr('Ctrl+Q'))
        self._quitAction.triggered.connect(qApp.closeAllWindows)

    def _createRunToolBar(self):
        self._simToolBar = self.addToolBar(self.tr('Simulation control'))
        self._simToolBar.addAction(self._quitAction)
        self._simToolBar.addAction(self._runAction)
        self._simToolBar.addAction(self._resetToDefaultsAction)
        self._simToolBar.addAction(self._dockAction)
        self._simToolBar.addAction(self._restoreDocksAction)

    def _createPlotToolBar(self):
        self._plotToolBar = self.addToolBar(self.tr('Plotting control'))
        self._plotToolBar.addAction(self._showLegendAction)
        self._plotToolBar.addAction(self._autoscaleAction)
        self._plotToolBar.addAction(self._overlayAction)
        self._plotToolBar.addAction(self._showStatePlotAction)
        self._plotToolBar.addAction(self._helpAction)
        self._plotToolBar.addAction(self._helpBiophysicsAction)

    def _showLegend(self, on):
        if on:
            for axis in (self._plotFigure.axes + self._statePlotFigure.axes):
                axis.legend().set_visible(True)
        else:
            for axis in (self._plotFigure.axes + self._statePlotFigure.axes):
                axis.legend().set_visible(False)
        self._plotCanvas.draw()
        self._statePlotCanvas.draw()

    def _autoscale(self, on):
        if on:
            for axis in (self._plotFigure.axes + self._statePlotFigure.axes):
                axis.relim()
                axis.set_autoscale_on(True)
                axis.autoscale_view(True)
        else:
            for axis in self._plotFigure.axes:
                axis.set_autoscale_on(False)
            self._vm_axes.set_ylim(-20.0, 120.0)
            self._g_axes.set_ylim(0.0, 0.5)
            self._im_axes.set_ylim(-0.5, 0.5)
            self._i_axes.set_ylim(-10, 10)
        self._plotCanvas.draw()
        self._statePlotCanvas.draw()

    def _useDefaults(self):
        self._runTimeEdit.setText('%g' % (self.defaults['runtime']))
        self._simTimeStepEdit.setText('%g' % (self.defaults['simdt']))
        self._overlayAction.setChecked(False)
        self._naConductanceToggle.setChecked(False)
        self._kConductanceToggle.setChecked(False)
        self._kOutEdit.setText('%g' % (SquidGui.defaults['K_out']))
        self._naOutEdit.setText('%g' % (SquidGui.defaults['Na_out']))
        self._kInEdit.setText('%g' % (SquidGui.defaults['K_in']))
        self._naInEdit.setText('%g' % (SquidGui.defaults['Na_in']))
        self._temperatureEdit.setText(
            '%g' % (SquidGui.defaults['temperature'] - CELSIUS_TO_KELVIN))
        self._holdingVEdit.setText('%g' %
                                   (SquidGui.defaults['vclamp.holdingV']))
        self._holdingTimeEdit.setText('%g' %
                                      (SquidGui.defaults['vclamp.holdingT']))
        self._prePulseVEdit.setText('%g' %
                                    (SquidGui.defaults['vclamp.prepulseV']))
        self._prePulseTimeEdit.setText('%g' %
                                       (SquidGui.defaults['vclamp.prepulseT']))
        self._clampVEdit.setText('%g' % (SquidGui.defaults['vclamp.clampV']))
        self._clampTimeEdit.setText('%g' %
                                    (SquidGui.defaults['vclamp.clampT']))
        self._baseCurrentEdit.setText('%g' %
                                      (SquidGui.defaults['iclamp.baseI']))
        self._firstPulseEdit.setText('%g' %
                                     (SquidGui.defaults['iclamp.firstI']))
        self._firstDelayEdit.setText('%g' %
                                     (SquidGui.defaults['iclamp.firstD']))
        self._firstPulseWidthEdit.setText('%g' %
                                          (SquidGui.defaults['iclamp.firstT']))
        self._secondPulseEdit.setText('%g' %
                                      (SquidGui.defaults['iclamp.secondI']))
        self._secondDelayEdit.setText('%g' %
                                      (SquidGui.defaults['iclamp.secondD']))
        self._secondPulseWidthEdit.setText(
            '%g' % (SquidGui.defaults['iclamp.secondT']))
        self._pulseMode.setCurrentIndex(0)

    def _onScroll(self, event):
        if event.inaxes is None:
            return
        axes = event.inaxes
        zoom = 0.0
        if event.button == 'up':
            zoom = -1.0
        elif event.button == 'down':
            zoom = 1.0
        if zoom != 0.0:
            self._plotNavigator.push_current()
            axes.get_xaxis().zoom(zoom)
            axes.get_yaxis().zoom(zoom)
        self._plotCanvas.draw()

    def closeEvent(self, event):
        qApp.closeAllWindows()

    def _showBioPhysicsHelp(self):
        self._createHelpMessage()
        self._helpMessageText.setText(
            '<html><p>%s</p><p>%s</p><p>%s</p><p>%s</p><p>%s</p></html>' %
            (tooltip_Nernst, tooltip_Erest, tooltip_KChan, tooltip_NaChan,
             tooltip_Im))
        self._helpWindow.setVisible(True)

    def _showRunningHelp(self):
        self._createHelpMessage()
        self._helpMessageText.setSource(QtCore.QUrl(self._helpBaseURL))
        self._helpWindow.setVisible(True)

    def _createHelpMessage(self):
        if hasattr(self, '_helpWindow'):
            return
        self._helpWindow = QWidget()
        self._helpWindow.setWindowFlags(QtCore.Qt.Window)
        layout = QVBoxLayout()
        self._helpWindow.setLayout(layout)
        self._helpMessageArea = QScrollArea()
        self._helpMessageText = QTextBrowser()
        self._helpMessageText.setOpenExternalLinks(True)
        self._helpMessageArea.setWidget(self._helpMessageText)
        layout.addWidget(self._helpMessageText)
        self._squidGuiPath = os.path.dirname(os.path.abspath(__file__))
        self._helpBaseURL = os.path.join(self._squidGuiPath, 'help.html')
        self._helpMessageText.setSource(QtCore.QUrl(self._helpBaseURL))
        self._helpMessageText.setSizePolicy(QSizePolicy.Expanding,
                                            QSizePolicy.Expanding)
        self._helpMessageArea.setSizePolicy(QSizePolicy.Expanding,
                                            QSizePolicy.Expanding)
        self._helpMessageText.setMinimumSize(800, 600)
        self._closeHelpAction = QAction('Close', self)
        self._closeHelpAction.triggered.connect(self._helpWindow.close)
        # Setting the close event so that the ``Help`` button is
        # unchecked when the help window is closed
        self._helpWindow.closeEvent = lambda event: self._helpAction.setChecked(
            False)
        self._helpTOCAction = QAction('Help running demo', self)
        self._helpTOCAction.triggered.connect(self._jumpToHelpTOC)
        # This panel is for putting two buttons using horizontal
        # layout
        panel = QFrame()
        panel.setFrameStyle(QFrame.StyledPanel + QFrame.Raised)
        layout.addWidget(panel)
        layout = QHBoxLayout()
        panel.setLayout(layout)
        self._helpAction = QAction('Help running', self)
        self._helpAction.triggered.connect(self._showRunningHelp)
        self._helpBiophysicsAction = QAction('Help biophysics', self)
        self._helpBiophysicsAction.triggered.connect(self._showBioPhysicsHelp)
        self._helpTOCButton = QToolButton()
        self._helpTOCButton.setDefaultAction(self._helpTOCAction)
        self._helpBiophysicsButton = QToolButton()
        self._helpBiophysicsButton.setDefaultAction(self._helpBiophysicsAction)
        layout.addWidget(self._helpTOCButton)
        layout.addWidget(self._helpBiophysicsButton)
        self._closeHelpButton = QToolButton()
        self._closeHelpButton.setDefaultAction(self._closeHelpAction)
        layout.addWidget(self._closeHelpButton)

    def _jumpToHelpTOC(self):
        self._helpMessageText.setSource(QtCore.QUrl(self._helpBaseURL))
Esempio n. 33
0
    def __init__(self, plotter=None):

        if not plotter:
            plotter = plotting.Plotter()

        self.plotter = plotter

        self.canvas = FigureCanvas(self.plotter.f)
        self.canvas.mpl_connect('motion_notify_event', self.mouse_moved)

        # mcp hitmap type
        self.plot_with_cuts_button = QCheckBox()
        self.plot_with_cuts = 0
        self.plot_with_cuts_button.setCheckState(self.plot_with_cuts)
        self.plot_with_cuts_button.clicked.connect(self.plot_with_cuts_clicked)

        mcp_hitmap_buttons = QHBoxLayout()
        self.mcp_kde_button = QRadioButton('KDE')
        self.mcp_hist_button = QRadioButton('Hist')
        self.mcp_kde_button.clicked.connect(self.set_use_kde)
        self.mcp_hist_button.click()
        self.mcp_hist_button.clicked.connect(self.disable_use_kde)
        mcp_hitmap_buttons.addWidget(self.mcp_kde_button)
        mcp_hitmap_buttons.addWidget(self.mcp_hist_button)

        # mcp hitmap histo bin size and kde bandwidth
        # mcp_hitmap_settings = QHBoxLayout()
        hist_nbins_validator = QIntValidator(0, 10000)
        self.mcp_bin_width_entry = QLineEdit(str(self.plotter.mcp_bin_width))
        self.mcp_bin_width_entry.setValidator(QDoubleValidator(0., 10000., 10))
        self.mcp_bin_width_entry.setMaximumWidth(
            PLOTTER_WIDGET_QLINEEDIT_WIDTH)
        self.mcp_kde_bw_entry = QLineEdit(str(DEFAULT_KDE_BW))
        self.mcp_kde_bw_entry.setValidator(QDoubleValidator(0.0, 10000., 10))
        self.mcp_kde_bw_entry.setMaximumWidth(PLOTTER_WIDGET_QLINEEDIT_WIDTH)
        # mcp_hitmap_settings.addWidget( self.mcp_hist_bin_size_entry )
        # mcp_hitmap_settings.addWidget( self.mcp_kde_bw_entry )

        # mcp hitmap bounds inputs
        self.mcp_hitmap_left_xbound_entry = QLineEdit(str(-5))
        self.mcp_hitmap_right_xbound_entry = QLineEdit(str(5))
        self.mcp_hitmap_left_ybound_entry = QLineEdit(str(-5))
        self.mcp_hitmap_right_ybound_entry = QLineEdit(str(5))

        mcp_hitmap_bounds_validator = QDoubleValidator(-1000, 1000, 10)
        self.mcp_hitmap_left_xbound_entry.setValidator(
            mcp_hitmap_bounds_validator)
        self.mcp_hitmap_right_xbound_entry.setValidator(
            mcp_hitmap_bounds_validator)
        self.mcp_hitmap_left_ybound_entry.setValidator(
            mcp_hitmap_bounds_validator)
        self.mcp_hitmap_right_ybound_entry.setValidator(
            mcp_hitmap_bounds_validator)

        self.mcp_hitmap_left_xbound_entry.setMaximumWidth(
            PLOTTER_WIDGET_QLINEEDIT_WIDTH)
        self.mcp_hitmap_right_xbound_entry.setMaximumWidth(
            PLOTTER_WIDGET_QLINEEDIT_WIDTH)
        self.mcp_hitmap_left_ybound_entry.setMaximumWidth(
            PLOTTER_WIDGET_QLINEEDIT_WIDTH)
        self.mcp_hitmap_right_ybound_entry.setMaximumWidth(
            PLOTTER_WIDGET_QLINEEDIT_WIDTH)

        mcp_hitmap_xbounds_entry = QHBoxLayout()
        mcp_hitmap_ybounds_entry = QHBoxLayout()
        mcp_hitmap_xbounds_entry.addWidget(self.mcp_hitmap_left_xbound_entry)
        mcp_hitmap_xbounds_entry.addWidget(self.mcp_hitmap_right_xbound_entry)
        mcp_hitmap_ybounds_entry.addWidget(self.mcp_hitmap_left_ybound_entry)
        mcp_hitmap_ybounds_entry.addWidget(self.mcp_hitmap_right_ybound_entry)

        self.tof_hist_nbins_entry = QLineEdit(str(0))
        self.tof_hist_nbins_entry.setMaximumWidth(
            PLOTTER_WIDGET_QLINEEDIT_WIDTH)
        self.tof_hist_nbins_entry.setValidator(hist_nbins_validator)

        self.r_hist_nbins_entry = QLineEdit(str(0))
        self.r_hist_nbins_entry.setMaximumWidth(PLOTTER_WIDGET_QLINEEDIT_WIDTH)
        self.r_hist_nbins_entry.setValidator(hist_nbins_validator)

        self.angle_hist_nbins_entry = QLineEdit(str(0))
        self.angle_hist_nbins_entry.setMaximumWidth(
            PLOTTER_WIDGET_QLINEEDIT_WIDTH)
        self.angle_hist_nbins_entry.setValidator(hist_nbins_validator)

        # tof cut entry
        tof_bounds = QHBoxLayout()

        self.tof_lower_cut_entry = QLineEdit(
            str(self.plotter.cpt_data.tof_cut_lower))
        self.tof_lower_cut_entry.setMaximumWidth(
            PLOTTER_WIDGET_QLINEEDIT_WIDTH)
        self.tof_lower_cut_entry.setValidator(QDoubleValidator(0., 10000., 10))

        self.tof_upper_cut_entry = QLineEdit(
            str(self.plotter.cpt_data.tof_cut_upper))
        self.tof_upper_cut_entry.setMaximumWidth(
            PLOTTER_WIDGET_QLINEEDIT_WIDTH)
        self.tof_upper_cut_entry.setValidator(QDoubleValidator(0., 10000., 10))

        tof_bounds.addWidget(self.tof_lower_cut_entry)
        tof_bounds.addWidget(self.tof_upper_cut_entry)

        r_bounds = QHBoxLayout()

        self.r_lower_cut_entry = QLineEdit(str(0))
        self.r_lower_cut_entry.setMaximumWidth(PLOTTER_WIDGET_QLINEEDIT_WIDTH)
        self.r_lower_cut_entry.setValidator(QDoubleValidator(0, 10000, 3))

        self.r_upper_cut_entry = QLineEdit(str(0))
        self.r_upper_cut_entry.setMaximumWidth(PLOTTER_WIDGET_QLINEEDIT_WIDTH)
        self.r_upper_cut_entry.setValidator(QDoubleValidator(0, 10000, 3))

        r_bounds.addWidget(self.r_lower_cut_entry)
        r_bounds.addWidget(self.r_upper_cut_entry)

        layout = QVBoxLayout()

        controls_box = QGroupBox('Visualization Controls')
        controls_layout = QFormLayout()
        # subtitle.setFont( QFont( SUBTITLE_FONT, SUBTITLE_SIZE,
        #                                QFont.Bold ) )

        # controls_layout.addRow( subtitle )
        controls_layout.addRow('Plot with Cuts', self.plot_with_cuts_button)
        controls_layout.addRow('Hitmap Type:', mcp_hitmap_buttons)
        # controls_layout.addRow( mcp_hitmap_settings )
        controls_layout.addRow('MCP bin width (mm):', self.mcp_bin_width_entry)
        controls_layout.addRow('MCP KDE bandwidth:', self.mcp_kde_bw_entry)
        controls_layout.addRow('MCP X Bounds:', mcp_hitmap_xbounds_entry)
        controls_layout.addRow('MCP Y Bounds:', mcp_hitmap_ybounds_entry)
        controls_layout.addRow('TOF hist num bins:', self.tof_hist_nbins_entry)
        controls_layout.addRow('Radius hist num bins:',
                               self.r_hist_nbins_entry)
        controls_layout.addRow('Angle hist num bins:',
                               self.angle_hist_nbins_entry)
        reload_button = QPushButton('Reload Parameters')
        reload_button.clicked.connect(self.reload_visualization_params)
        controls_layout.addRow(reload_button)

        controls_box.setLayout(controls_layout)
        layout.addWidget(controls_box)

        # subtitle = QLabel( 'Data Cuts' )
        # subtitle.setFont( QFont( SUBTITLE_FONT, SUBTITLE_SIZE, QFont.Bold ) )
        # controls_layout.addRow( subtitle )

        cuts_box = QGroupBox('Data Cuts')
        cuts_layout = QFormLayout()
        cuts_layout.addRow('TOF lower / upper bounds:', tof_bounds)
        cuts_layout.addRow('Radius Cut:', r_bounds)
        cuts_box.setLayout(cuts_layout)
        layout.addWidget(cuts_box)

        fits_box = QGroupBox('Gaussian Fitting')
        # fits_layout = QVBoxLayout()
        # fits_layout.setSpacing(0)

        self.fit_widget = FitWidget(self.plotter.all_hists)

        # self.tof_fit_widget = FitWidget( 'TOF', self.plotter.tof_hist )
        # self.angle_fit_widget = FitWidget( 'Angle', self.plotter.angle_hist )
        # self.radius_fit_widget = FitWidget( 'Radius', self.plotter.radius_hist )

        # fits_layout.addLayout( self.tof_fit_widget.layout )
        # fits_layout.addLayout( self.angle_fit_widget.layout )
        # fits_layout.addLayout( self.radius_fit_widget.layout )

        fits_box.setLayout(self.fit_widget.layout)
        layout.addWidget(fits_box)

        self.metadata_widget = MetadataWidget(self.plotter.cpt_data)
        layout.addWidget(self.metadata_widget.box)

        canvas_layout = QVBoxLayout()
        canvas_layout.addWidget(self.canvas)

        self.coords_label = QLabel()

        canvas_layout.addWidget(self.coords_label)

        self.grid_layout = QGridLayout()
        self.grid_layout.addLayout(layout, 0, 0, 0, 1, QtCore.Qt.AlignLeft)
        self.grid_layout.setColumnStretch(0, 0.5)
        self.grid_layout.addLayout(canvas_layout, 0, 1, 1, 1)
        self.grid_layout.setColumnStretch(1, 1)
Esempio n. 34
0
    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)
Esempio n. 35
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 = unicode(self.textbox.text())
        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
Esempio n. 36
0
class TSPlot(QFrame):
    def __init__(self,
                 E,
                 T,
                 cell_flag,
                 feat_flag,
                 tSeek1,
                 DInt,
                 EDInt,
                 t_span=80,
                 t=1):
        super(TSPlot, self).__init__()
        self.E = E
        self.T = T
        self.E_norm = deepcopy(E)
        self.T_norm = deepcopy(T)
        self.t = t
        self.t_span = t_span
        self.tSeek1 = tSeek1
        self.DInt = DInt
        self.EDInt = EDInt

        self.cell_flag = cell_flag
        self.feat_flag = feat_flag

        #self.normalize_data()
        self.create_main_frame()

    def normalize_data(self):
        E_num = len(self.E.keys())
        T_num = len(self.T.keys())
        #only the speed and Death Marker needs to be normalized

        #First, Normalize E
        #The speed
        Max_speed_E = 0
        Max_DM_E = 0
        for i in range(1, E_num + 1):
            if max(self.E['E' + str(i)][3]) > Max_speed_E:
                Max_speed_E = max(self.E['E' + str(i)][3])

            if max(self.E['E' + str(i)][4]) > Max_DM_E:
                Max_DM_E = max(self.E['E' + str(i)][4])

        for i in range(1, E_num + 1):
            for t in range(0, self.t_span):
                self.E_norm['E' +
                            str(i)][3][t] = self.E['E' + str(i)][3][t] / (
                                Max_speed_E + 0.001)
                self.E_norm['E' +
                            str(i)][4][t] = self.E['E' + str(i)][4][t] / (
                                Max_DM_E + 0.001)

        #First, Normalize T
        #The speed
        Max_speed_T = 0
        Max_DM_T = 0
        for i in range(1, T_num + 1):
            if max(self.T['T' + str(i)][3]) > Max_speed_T:
                Max_speed_T = max(self.T['T' + str(i)][3])

            if max(self.T['T' + str(i)][4]) > Max_DM_T:
                Max_DM_T = max(self.T['T' + str(i)][4])

        for i in range(1, T_num + 1):
            for t in range(0, self.t_span):
                self.T_norm['T' +
                            str(i)][3][t] = self.T['T' + str(i)][3][t] / (
                                Max_speed_T + 0.001)
                self.T_norm['T' +
                            str(i)][4][t] = self.T['T' + str(i)][4][t] / (
                                Max_DM_T + 0.001)

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

        self.refresh()

        self.Box = QHBoxLayout()
        self.Box.addWidget(self.main_frame)
        self.setLayout(self.Box)
        self.setFixedSize(800, 500)
        self.setObjectName("myObject3")
        self.setStyleSheet("#myObject3 {border: 5px solid white}")
        self.show()

    def refresh(self):

        Thresh = 0

        tSeek1 = self.tSeek1
        mini = 0
        maxi = 200

        self.fig = plt.figure(figsize=(8, 5))

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

        ax = self.fig.add_subplot(1, 1, 1)

        cell_index = self.cell_flag.index(1)
        feat_index = self.feat_flag.index(1)

        if cell_index == 0:
            cell_key = 'E1'
            plot_title = 'Effector Cell 1 Feature Time Series'
            Thresh = self.EDInt
            try:
                feat_data = self.E[cell_key][feat_index]
                mini = min(feat_data)
                maxi = max(feat_data)
            except:
                print "No cell E1 or No given features"

        if cell_index == 1:
            cell_key = 'E2'
            plot_title = 'Effector Cell 2 Feature Time Series'
            Thresh = self.EDInt
            try:
                feat_data = self.E[cell_key][feat_index]
                mini = min(feat_data)
                maxi = max(feat_data)
            except:
                print "No cell E2 or No given features"

        if cell_index == 2:
            cell_key = 'E3'
            plot_title = 'Effector Cell 3 Feature Time Series'
            Thresh = self.EDInt
            try:
                feat_data = self.E[cell_key][feat_index]
                mini = min(feat_data)
                maxi = max(feat_data)
            except:
                print "No cell E3 or No given features"

        if cell_index == 3:
            cell_key = 'E4'
            plot_title = 'Effector Cell 4 Feature Time Series'
            Thresh = self.EDInt
            try:
                feat_data = self.E[cell_key][feat_index]
                mini = min(feat_data)
                maxi = max(feat_data)
            except:
                print "No cell E4 or No given features"

        if cell_index == 4:
            cell_key = 'T1'
            plot_title = 'Target Cell 1 Feature Time Series'
            Thresh = self.DInt
            try:
                feat_data = self.T[cell_key][feat_index]
                mini = min(feat_data)
                maxi = max(feat_data)
            except:
                print "No cell T1 or No given features"

        if cell_index == 5:
            cell_key = 'T2'
            plot_title = 'Target Cell 2 Feature Time Series'
            Thresh = self.DInt
            try:
                feat_data = self.T[cell_key][feat_index]
                mini = min(feat_data)
                maxi = max(feat_data)
            except:
                print "No cell T2 or No given features"

        if cell_index == 6:
            cell_key = 'T3'
            plot_title = 'Target Cell 3 Feature Time Series'
            Thresh = self.DInt
            try:
                feat_data = self.T[cell_key][feat_index]
                mini = min(feat_data)
                maxi = max(feat_data)
            except:
                print "No cell T3 or No given features"

        if cell_index == 7:
            cell_key = 'T4'
            plot_title = 'Target Cell 4 Feature Time Series'
            Thresh = self.DInt
            try:
                feat_data = self.T[cell_key][feat_index]
                mini = min(feat_data)
                maxi = max(feat_data)
            except:
                print "No cell T4 or No given features"

        if feat_index == 0:
            y_label = 'Position X'

        if feat_index == 1:
            y_label = 'Position Y'

        if feat_index == 2:
            y_label = 'Aspect Ratio'

        if feat_index == 3:
            y_label = 'Speed'

        if feat_index == 4:
            y_label = 'Death Marker'

        if feat_index == 5:
            y_label = 'Contact Ratio'

        try:
            plt.plot(feat_data)
            plt.plot(feat_data, 'ro')

            # plot contact line
            if tSeek1 > 0 and tSeek1 < self.t_span:
                plt.plot((tSeek1, tSeek1),
                         (int(mini * 0.95), int(maxi * 1.05)), 'r-')

            # plot deathmarker threshold
            if feat_index == 4:
                plt.plot((0, 80), (Thresh, Thresh), 'r-')

            plt.xlabel('Time')
            plt.ylabel(y_label)
            plt.title(plot_title)
        except:
            print "Can't Plot Time Series Left!"

    def update_main_frame(self):

        plt.close(self.fig)

        self.Box.removeWidget(self.main_frame)
        self.main_frame.deleteLater()
        self.main_frame = None

        self.main_frame = QWidget()

        self.refresh()

        self.Box.addWidget(self.main_frame)

        self.show()
Esempio n. 37
0
    def refresh(self):

        Thresh = 0

        tSeek1 = self.tSeek1
        mini = 0
        maxi = 200

        self.fig = plt.figure(figsize=(8, 5))

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

        ax = self.fig.add_subplot(1, 1, 1)

        cell_index = self.cell_flag.index(1)
        feat_index = self.feat_flag.index(1)

        if cell_index == 0:
            cell_key = 'E1'
            plot_title = 'Effector Cell 1 Feature Time Series'
            Thresh = self.EDInt
            try:
                feat_data = self.E[cell_key][feat_index]
                mini = min(feat_data)
                maxi = max(feat_data)
            except:
                print "No cell E1 or No given features"

        if cell_index == 1:
            cell_key = 'E2'
            plot_title = 'Effector Cell 2 Feature Time Series'
            Thresh = self.EDInt
            try:
                feat_data = self.E[cell_key][feat_index]
                mini = min(feat_data)
                maxi = max(feat_data)
            except:
                print "No cell E2 or No given features"

        if cell_index == 2:
            cell_key = 'E3'
            plot_title = 'Effector Cell 3 Feature Time Series'
            Thresh = self.EDInt
            try:
                feat_data = self.E[cell_key][feat_index]
                mini = min(feat_data)
                maxi = max(feat_data)
            except:
                print "No cell E3 or No given features"

        if cell_index == 3:
            cell_key = 'E4'
            plot_title = 'Effector Cell 4 Feature Time Series'
            Thresh = self.EDInt
            try:
                feat_data = self.E[cell_key][feat_index]
                mini = min(feat_data)
                maxi = max(feat_data)
            except:
                print "No cell E4 or No given features"

        if cell_index == 4:
            cell_key = 'T1'
            plot_title = 'Target Cell 1 Feature Time Series'
            Thresh = self.DInt
            try:
                feat_data = self.T[cell_key][feat_index]
                mini = min(feat_data)
                maxi = max(feat_data)
            except:
                print "No cell T1 or No given features"

        if cell_index == 5:
            cell_key = 'T2'
            plot_title = 'Target Cell 2 Feature Time Series'
            Thresh = self.DInt
            try:
                feat_data = self.T[cell_key][feat_index]
                mini = min(feat_data)
                maxi = max(feat_data)
            except:
                print "No cell T2 or No given features"

        if cell_index == 6:
            cell_key = 'T3'
            plot_title = 'Target Cell 3 Feature Time Series'
            Thresh = self.DInt
            try:
                feat_data = self.T[cell_key][feat_index]
                mini = min(feat_data)
                maxi = max(feat_data)
            except:
                print "No cell T3 or No given features"

        if cell_index == 7:
            cell_key = 'T4'
            plot_title = 'Target Cell 4 Feature Time Series'
            Thresh = self.DInt
            try:
                feat_data = self.T[cell_key][feat_index]
                mini = min(feat_data)
                maxi = max(feat_data)
            except:
                print "No cell T4 or No given features"

        if feat_index == 0:
            y_label = 'Position X'

        if feat_index == 1:
            y_label = 'Position Y'

        if feat_index == 2:
            y_label = 'Aspect Ratio'

        if feat_index == 3:
            y_label = 'Speed'

        if feat_index == 4:
            y_label = 'Death Marker'

        if feat_index == 5:
            y_label = 'Contact Ratio'

        try:
            plt.plot(feat_data)
            plt.plot(feat_data, 'ro')

            # plot contact line
            if tSeek1 > 0 and tSeek1 < self.t_span:
                plt.plot((tSeek1, tSeek1),
                         (int(mini * 0.95), int(maxi * 1.05)), 'r-')

            # plot deathmarker threshold
            if feat_index == 4:
                plt.plot((0, 80), (Thresh, Thresh), 'r-')

            plt.xlabel('Time')
            plt.ylabel(y_label)
            plt.title(plot_title)
        except:
            print "Can't Plot Time Series Left!"
Esempio n. 38
0
class line_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 = {}

        self.number_of_channel = 4

        self.create_layout()
        self.connect_labrad()

        updater = LoopingCall(self.update_lines)
        updater.start(c.update_rate)

    def create_layout(self):
        layout = QtGui.QGridLayout()
        plot_layout = self.create_drift_layout()
        layout.addLayout(plot_layout, 0, 0)

        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)
        #         layout.addLayout(spectrum_layout, 1, 1, 1, 1)
        self.setLayout(layout)

    def create_drift_layout(self):
        layout = QtGui.QVBoxLayout()
        self.fig = Figure()
        self.plot_canvas = FigureCanvas(self.fig)
        self.plot_canvas.setParent(self)
        #gs = gridspec.GridSpec(1, 2, wspace=0.15, left = 0.05, right = 0.95)
        line_drift = self.fig.add_subplot(1, 1, 1)
        line_drift.ticklabel_format(useOffset=False)
        line_drift.set_xlabel('Time (min)')
        line_drift.set_ylabel('kHz')
        line_drift.set_title("Line Drift")
        self.line_drift = line_drift
        self.line_drift_lines = []
        self.line_drift_fit_line = []
        self.line_all_line = []

        self.mpl_toolbar = NavigationToolbar2QT(self.plot_canvas, self)
        layout.addWidget(self.mpl_toolbar)
        layout.addWidget(self.plot_canvas)
        return layout

    def create_widget_layout(self):
        layout = QtGui.QGridLayout()
        self.submit_button = []
        self.freq_enter_box = []
        self.freq_label_id = []
        self.freq_label_current = []
        self.remove_button = []
        self.track_duration_box = []
        for i in range(self.number_of_channel):

            self.submit_button.append(QtGui.QPushButton("Submit"))

            spin_box = QtGui.QDoubleSpinBox()
            spin_box.setSuffix(' kHz')
            spin_box.setRange(-50000.0, 50000.0)
            spin_box.setDecimals(5)
            self.freq_enter_box.append(spin_box)

            label = QtGui.QLabel(str(i + 1))
            self.freq_label_id.append(label)

            freq_value = 0.000
            freq_value_label = QtGui.QLabel("%.5f kHz" % freq_value)
            self.freq_label_current.append(freq_value_label)

            self.remove_button.append(QtGui.QPushButton("Remove"))

            track_duration_spin_box = QtGui.QDoubleSpinBox()
            track_duration_spin_box.setSuffix(' min')
            track_duration_spin_box.setDecimals(1)
            self.track_duration_box.append(track_duration_spin_box)

            layout.addWidget(self.freq_label_id[i], i, 0)
            layout.addWidget(self.freq_enter_box[i], i, 1)
            layout.addWidget(self.submit_button[i], i, 2)
            layout.addWidget(self.freq_label_current[i], i, 3)
            layout.addWidget(self.remove_button[i], i, 4)
            layout.addWidget(self.track_duration_box[i], i, 5)

        return layout

    def connect_layout(self):

        for i in range(self.number_of_channel):
            #self.submit_button[i].clicked.connect(lambda i=i: self.on_entry(i))
            self.track_duration_box[i].valueChanged.connect(
                partial(self.on_duration_change, i, 9))
            self.submit_button[i].clicked.connect(partial(self.on_entry, i))
            self.remove_button[i].clicked.connect(partial(self.on_remove, i))

    @inlineCallbacks
    def initialize_layout(self):
        server = yield self.cxn.get_server('Line Tracker')
        #         transitions = yield server.get_transition_names()
        #         self.entry_table.fill_out(transitions)
        for i in range(self.number_of_channel):
            duration = yield server.history_duration(i + 1)
            self.track_duration_box[i].setValue(duration['min'])

        yield self.on_new_fit(None, None)

    @inlineCallbacks
    def on_entry(self, i, j):
        server = yield self.cxn.get_server('Line Tracker')
        freq = self.freq_enter_box[i].value()
        print freq
        print "submit button", i
        freq_with_units = self.WithUnit(freq, 'kHz')
        try:
            yield server.set_measurement(freq_with_units, i + 1)
        except self.Error as e:
            self.displayError(e.msg)

    @inlineCallbacks
    def on_duration_change(self, i, j, value):
        #print i, j, value
        server = yield self.cxn.get_server('Line Tracker')
        rate_line = self.WithUnit(value, 'min')
        print rate_line
        yield server.history_duration(i + 1, rate_line)

    @inlineCallbacks
    def on_remove(self, i, j):
        server = yield self.cxn.get_server('Line Tracker')
        try:
            yield server.remove_measurement(i + 1)
        except self.Error as e:
            self.displayError(e.msg)

    @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 clients.connection import connection
            self.cxn = connection()
            yield self.cxn.connect()
        self.context = yield self.cxn.context()
        try:
            yield self.subscribe_tracker()
#             print "yes"
        except Exception as e:
            #             print e
            #             print 'no'
            self.setDisabled(True)
        self.cxn.add_on_connect('Line Tracker', self.reinitialize_tracker)
        self.cxn.add_on_disconnect('Line Tracker', self.disable)
        self.connect_layout()

    @inlineCallbacks
    def subscribe_tracker(self):
        server = yield self.cxn.get_server('Line Tracker')
        #print c.ID
        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('Line 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()
        #print x, y
        yield self.update_fit()

    @inlineCallbacks
    def update_fit(self):
        try:
            server = yield self.cxn.get_server('Line Tracker')
            #number = yield server.get_tracker_number()

        except Exception as e:
            #no fit available
            print e
            pass
        else:
            ## clear all curves
            self.clear_plot_canvas(self.line_drift_lines)
            self.clear_plot_canvas(self.line_drift_fit_line)
            self.line_drift.set_color_cycle(
                None
            )  # reset the color rotation such that line 1 is always the same color

            for i in range(self.number_of_channel):
                j = i + 1

                ## get all lines
                history_line = yield server.get_fit_history(j)
                all_history_line = yield server.get_all_history(j)

                ## plot if lines are not empty
                if len(history_line) > 0:
                    fit_param = yield server.get_fit_parameters(j)
                    inunits_f = [(t['min'], freq['kHz'])
                                 for (t, freq) in history_line]
                    self.update_track(inunits_f, self.line_drift,
                                      self.line_drift_lines)
                    self.plot_fit_f(
                        fit_param, inunits_f[0][0], inunits_f[-1]
                        [0])  ## send fit parameter and range to line fitter

                if len(all_history_line) > 0:
                    history_inunits_f = [(t['min'], freq['kHz'])
                                         for (t, freq) in all_history_line]
                    self.update_history_track(history_inunits_f,
                                              self.line_drift,
                                              self.line_drift_lines)

#

    def plot_fit_f(self, p, xmin, xmax):

        points = 1000
        x = numpy.linspace(xmin, xmax, points)
        y = 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.plot_canvas.draw()

    @inlineCallbacks
    def update_lines(self):
        try:
            server = yield self.cxn.get_server('Line Tracker')
            for i in range(self.number_of_channel):
                freq = yield server.get_current_line(i + 1)
                self.freq_label_current[i].setText("%.5f kHz" % freq['kHz'])
        except Exception as e:
            print e
            #no lines available
            returnValue(None)
        else:
            pass
            #self.update_spectrum(lines)
            #self.update_listing(lines)
            #returnValue(lines)
#

    def clear_plot_canvas(self, lines):
        #clear all current lines
        for i in range(len(lines)):
            line = lines.pop()
            line.remove()

    def update_history_track(self, meas, axes, lines):

        x = numpy.array([m[0] for m in meas])
        y = [m[1] for m in meas]
        #annotate the last point
        try:
            last = y[-1]
        except IndexError:
            pass
#         else:
#             label = axes.annotate('Last: {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 = axes.plot(x, y, 'b.')[0]
        lines.append(line)
        self.plot_canvas.draw()

    def update_track(self, meas, axes, lines):

        x = numpy.array([m[0] for m in meas])
        y = [m[1] for m in meas]
        #annotate the last point
        try:
            last = y[-1]
        except IndexError:
            pass
#         else:
#             label = axes.annotate('Last: {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 = axes.plot(x, y, '*')[0]
        lines.append(line)
        self.plot_canvas.draw()


#

    @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()
Esempio n. 39
0
class Form(QMainWindow):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)
        self.setWindowTitle('SHOGUN interactive demo')

        self.data = DataHolder()
        self.series_list_model = QStandardItemModel()

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

        self.on_show()

    def load_file(self, filename=None):
        filename = QFileDialog.getOpenFileName(self,
            'Open a data file', '.', 'CSV files (*.csv);;All Files (*.*)')

        if filename:
            self.data.load_from_file(filename)
            self.fill_series_list(self.data.series_names())
            self.status_text.setText("Loaded " + filename)

    def on_show(self):
        self.axes.clear()
        self.axes.grid(True)
        self.axes.plot(self.data.x1, self.data.x2, 'bo')
        self.axes.set_xlim((-5,5))
        self.axes.set_ylim((-5,5))
        self.canvas.draw()
        self.fill_series_list(self.data.get_stats())


    def on_about(self):
        msg = __doc__
        QMessageBox.about(self, "About the demo", msg.strip())

    def fill_series_list(self, names):
        self.series_list_model.clear()

        for name in names:
            item = QStandardItem(name)
            item.setCheckState(Qt.Unchecked)
            item.setCheckable(False)
            self.series_list_model.appendRow(item)

    def onclick(self, event):
        print 'button=%d, x=%d, y=%d, xdata=%f, ydata=%f'%(event.button, event.x, event.y, event.xdata, event.ydata)
        self.data.add_example(event.xdata, event.ydata)
        self.on_show()


    def clear(self):
        self.data.clear()
        self.on_show()

    def enable_widgets(self):
        kernel_name = self.kernel_combo.currentText()
        if kernel_name == "LinearKernel":
            self.sigma.setDisabled(True)
            self.degree.setDisabled(True)
        elif kernel_name == "PolynomialKernel":
            self.sigma.setDisabled(True)
            self.degree.setEnabled(True)
        elif kernel_name == "GaussianKernel":
            self.sigma.setEnabled(True)
            self.degree.setDisabled(True)

    def train_svm(self):

        width = float(self.sigma.text())
        degree = int(self.degree.text())

        self.axes.clear()
        self.axes.grid(True)
        self.axes.plot(self.data.x1, self.data.x2, 'bo')

        # train svm
        labels = self.data.get_labels()
        print type(labels)
        lab = RegressionLabels(labels)
        features = self.data.get_examples()
        train = RealFeatures(features)

        kernel_name = self.kernel_combo.currentText()
        print "current kernel is %s" % (kernel_name)

        if kernel_name == "LinearKernel":
            gk = LinearKernel(train, train)
            gk.set_normalizer(IdentityKernelNormalizer())
        elif kernel_name == "PolynomialKernel":
            gk = PolyKernel(train, train, degree, True)
            gk.set_normalizer(IdentityKernelNormalizer())
        elif kernel_name == "GaussianKernel":
            gk = GaussianKernel(train, train, width)

        cost = float(self.cost.text())
        tubeeps = float(self.tubeeps.text())

        print "cost", cost
        svm = LibSVR(cost, tubeeps, gk, lab)
        svm.train()
        svm.set_epsilon(1e-2)

        x=numpy.linspace(-5.0,5.0,100)
        y=svm.apply(RealFeatures(numpy.array([x]))).get_labels()

        self.axes.plot(x,y,'r-')

        self.axes.set_xlim((-5,5))
        self.axes.set_ylim((-5,5))


        self.canvas.draw()


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

        plot_frame = QWidget()

        self.dpi = 100
        self.fig = Figure((6.0, 6.0), dpi=self.dpi)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.main_frame)

        cid = self.canvas.mpl_connect('button_press_event', self.onclick)
        self.axes = self.fig.add_subplot(111)
        self.cax = None
        #self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)

        log_label = QLabel("Number of examples:")
        self.series_list_view = QListView()
        self.series_list_view.setModel(self.series_list_model)


        cost_label = QLabel('C')
        #self.cost = QSpinBox()#QLineEdit()
        self.cost = QLineEdit()
        self.cost.setText("1.0")
        #self.cost.setMinimum(1)
        spin_label2 = QLabel('tube')
        self.tubeeps = QLineEdit()
        self.tubeeps.setText("0.1")
        spin_label3 = QLabel('sigma')
        self.sigma = QLineEdit()
        self.sigma.setText("1.2")
        #self.sigma.setMinimum(1)
        spin_label4 = QLabel('d')
        self.degree = QLineEdit()
        self.degree.setText("2")
        #self.sigma.setMinimum(1)

        spins_hbox = QHBoxLayout()
        spins_hbox.addWidget(cost_label)
        spins_hbox.addWidget(self.cost)
        spins_hbox.addWidget(spin_label2)
        spins_hbox.addWidget(self.tubeeps)
        spins_hbox.addWidget(spin_label3)
        spins_hbox.addWidget(self.sigma)
        spins_hbox.addWidget(spin_label4)
        spins_hbox.addWidget(self.degree)
        spins_hbox.addStretch(1)

        self.legend_cb = QCheckBox("Show Support Vectors")
        self.legend_cb.setChecked(False)

        self.show_button = QPushButton("&Train SVR")
        self.connect(self.show_button, SIGNAL('clicked()'), self.train_svm)

        self.clear_button = QPushButton("&Clear")
        self.connect(self.clear_button, SIGNAL('clicked()'), self.clear)


        self.kernel_combo = QComboBox()
        self.kernel_combo.insertItem(-1, "GaussianKernel")
        self.kernel_combo.insertItem(-1, "PolynomialKernel")
        self.kernel_combo.insertItem(-1, "LinearKernel")
        self.kernel_combo.maximumSize = QSize(300, 50)
        self.connect(self.kernel_combo, SIGNAL("currentIndexChanged(QString)"), self.enable_widgets)


        left_vbox = QVBoxLayout()
        left_vbox.addWidget(self.canvas)
        #left_vbox.addWidget(self.mpl_toolbar)

        right0_vbox = QVBoxLayout()
        right0_vbox.addWidget(log_label)
        right0_vbox.addWidget(self.series_list_view)
        #right0_vbox.addWidget(self.legend_cb)
        right0_vbox.addStretch(1)

        right2_vbox = QVBoxLayout()
        right2_label = QLabel("Settings")
        right2_vbox.addWidget(right2_label)
        right2_vbox.addWidget(self.show_button)
        right2_vbox.addWidget(self.kernel_combo)
        right2_vbox.addLayout(spins_hbox)
        right2_clearlabel = QLabel("Remove Data")
        right2_vbox.addWidget(right2_clearlabel)

        right2_vbox.addWidget(self.clear_button)


        right2_vbox.addStretch(1)

        right_vbox = QHBoxLayout()
        right_vbox.addLayout(right0_vbox)
        right_vbox.addLayout(right2_vbox)


        hbox = QVBoxLayout()
        hbox.addLayout(left_vbox)
        hbox.addLayout(right_vbox)
        self.main_frame.setLayout(hbox)

        self.setCentralWidget(self.main_frame)
        self.enable_widgets()


    def create_status_bar(self):
        self.status_text = QLabel("")
        self.statusBar().addWidget(self.status_text, 1)

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

        load_action = self.create_action("&Load file",
            shortcut="Ctrl+L", slot=self.load_file, tip="Load a file")
        quit_action = self.create_action("&Quit", slot=self.close,
            shortcut="Ctrl+Q", tip="Close the application")

        self.add_actions(self.file_menu,
            (load_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
    def changePlotWidget(self, library, frame_for_plot):
        if library == "Qwt5" and has_qwt:
            plotWdg = QwtPlot(frame_for_plot)
            sizePolicy = QSizePolicy(QSizePolicy.Expanding,
                                     QSizePolicy.Expanding)
            sizePolicy.setHorizontalStretch(0)
            sizePolicy.setVerticalStretch(0)
            sizePolicy.setHeightForWidth(
                plotWdg.sizePolicy().hasHeightForWidth())
            plotWdg.setSizePolicy(sizePolicy)
            plotWdg.setMinimumSize(QSize(0, 0))
            plotWdg.setAutoFillBackground(False)
            #Decoration
            plotWdg.setCanvasBackground(Qt.white)
            plotWdg.plotLayout().setAlignCanvasToScales(True)
            zoomer = QwtPlotZoomer(QwtPlot.xBottom, QwtPlot.yLeft,
                                   QwtPicker.DragSelection,
                                   QwtPicker.AlwaysOff, plotWdg.canvas())
            zoomer.setRubberBandPen(QPen(Qt.blue))
            if platform.system() != "Windows":
                # disable picker in Windows due to crashes
                picker = QwtPlotPicker(QwtPlot.xBottom, QwtPlot.yLeft,
                                       QwtPicker.NoSelection,
                                       QwtPlotPicker.CrossRubberBand,
                                       QwtPicker.AlwaysOn, plotWdg.canvas())
                picker.setTrackerPen(QPen(Qt.green))
            #self.dockwidget.qwtPlot.insertLegend(QwtLegend(), QwtPlot.BottomLegend);
            grid = Qwt.QwtPlotGrid()
            grid.setPen(QPen(QColor('grey'), 0, Qt.DotLine))
            grid.attach(plotWdg)
            return plotWdg
        elif library == "Matplotlib" and has_mpl:
            from matplotlib.figure import Figure
            from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg

            fig = Figure((1.0, 1.0),
                         linewidth=0.0,
                         subplotpars=matplotlib.figure.SubplotParams(left=0,
                                                                     bottom=0,
                                                                     right=1,
                                                                     top=1,
                                                                     wspace=0,
                                                                     hspace=0))

            font = {'family': 'arial', 'weight': 'normal', 'size': 12}
            matplotlib.rc('font', **font)

            rect = fig.patch
            rect.set_facecolor((0.9, 0.9, 0.9))

            self.subplot = fig.add_axes((0.07, 0.15, 0.92, 0.82))
            self.subplot.set_xbound(0, 1000)
            self.subplot.set_ybound(0, 1000)
            self.manageMatplotlibAxe(self.subplot)
            canvas = FigureCanvasQTAgg(fig)
            sizePolicy = QSizePolicy(QSizePolicy.Expanding,
                                     QSizePolicy.Expanding)
            sizePolicy.setHorizontalStretch(0)
            sizePolicy.setVerticalStretch(0)
            canvas.setSizePolicy(sizePolicy)
            return canvas
Esempio n. 41
0
    def create_main_window(self):
        """
        This function creates the main window of the program.
        """
        self.main_frame = QWidget()
        self.main_frame.setMinimumSize(QSize(700, 700))

        self.dpi = 100
        self.fig = plt.Figure((6, 6),
                              dpi=self.dpi,
                              facecolor='w',
                              edgecolor='w')
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.main_frame)

        # Stuff for the preview map >>>>>>>>>>>>>>>>>>>>>>>>>
        self.preview_frame = QWidget()
        self.preview_fig = plt.Figure((3, 1.6),
                                      dpi=self.dpi,
                                      facecolor='w',
                                      edgecolor='w')
        self.preview = FigureCanvas(self.preview_fig)
        self.preview.setParent(self.preview_frame)
        self.preview_axes = self.preview_fig.add_subplot(111)

        self.preview_fig.canvas.mpl_connect('button_press_event', self.onclick)
        self.preview_fig.subplots_adjust(top=1, bottom=0, left=0, right=1)
        # Stuff for the preview map <<<<<<<<<<<<<<<<<<<<<<<<<

        # Stuff for the colorbar >>>>>>>>>>>>>>>>>>>>>>>>>
        self.colorbar_frame = QWidget()
        self.colorbar_fig = plt.Figure((3, 0.4),
                                       dpi=self.dpi,
                                       facecolor='w',
                                       edgecolor='w')
        self.colorbar = FigureCanvas(self.colorbar_fig)
        self.colorbar.setParent(self.colorbar_frame)
        self.colorbar_axes = self.colorbar_fig.add_subplot(111)
        self.colorbar_fig.subplots_adjust(
            top=1.0, bottom=0.35, left=0.02,
            right=0.97)  #Tightening the area around the subplot
        self.colorbar_fig.patch.set_facecolor(
            'none')  # Making the figure background transparent

        self.colorbar_axes.get_xaxis().set_visible(False)
        self.colorbar_axes.get_yaxis().set_visible(False)
        # Stuff for the colorbar <<<<<<<<<<<<<<<<<<<<<<<<<

        # 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)
        # Turning off the axes ticks to maximize space. Also the labels were meaningless
        # anyway because they were not representing the actual lat/lons.
        self.axes.get_xaxis().set_visible(False)
        self.axes.get_yaxis().set_visible(False)

        # Other GUI controls
        # Information section
        font = QFont("SansSerif", 14)

        # STATISTICS >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        self.statdisplay = QLabel("Statistics:")
        self.statgrid = QGridLayout()
        self.statgrid.setSpacing(5)
        w = QLabel("View")
        w.setFont(font)
        self.statgrid.addWidget(w, 1, 1, Qt.AlignCenter)
        w = QLabel("Global")
        w.setFont(font)
        self.statgrid.addWidget(w, 1, 2, Qt.AlignCenter)

        for i, name in enumerate(["Minimum", "Maximum", "Mean"]):
            w = QLabel(name)
            w.setFont(font)
            self.statgrid.addWidget(w, i + 2, 0, Qt.AlignLeft)

        self.statsarray = []
        for i in range(6):
            self.statsarray.append(QLabel(''))

        self.statsarray[3].setText("{0:3d}".format(int(self.dc.data.min())))
        self.statsarray[4].setText("{0:3d}".format(int(self.dc.data.max())))
        self.statsarray[5].setText("{0:3d}".format(int(self.dc.data.mean())))

        for i in range(3):
            self.statgrid.addWidget(self.statsarray[i], i + 2, 1,
                                    Qt.AlignCenter)
            self.statgrid.addWidget(self.statsarray[i + 3], i + 2, 2,
                                    Qt.AlignCenter)
            self.statsarray[i].setFont(font)
            self.statsarray[i + 3].setFont(font)

        # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

        # PIXEL INFO >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

        self.infodisplay = QLabel("Pixel Information:")
        self.infogrid = QGridLayout()
        self.infogrid.setSpacing(5)

        for i, name in enumerate(["Lat", "Lon", "KMT", "I, J"]):
            w = QLabel(name)
            w.setFont(font)
            # w.setLineWidth(1)
            # w.setFrameShape(QFrame.Box)
            self.infogrid.addWidget(w, i + 2, 0, Qt.AlignLeft)

        self.latdisplay = QLabel("")
        self.londisplay = QLabel("")
        self.valdisplay = QLabel("")
        self.idxdisplay = QLabel("")
        for i, w in enumerate([
                self.latdisplay, self.londisplay, self.valdisplay,
                self.idxdisplay
        ]):
            self.infogrid.addWidget(w, i + 2, 1, Qt.AlignLeft)
            w.setFont(font)
        # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

        # Colorscheme selector
        cmap_label = QLabel('Colorscheme:')
        self.colormaps = QComboBox(self)
        self.colormaps.addItems(self.maps)
        self.colormaps.setCurrentIndex(self.maps.index('Set1'))
        self.colormaps.currentIndexChanged.connect(self.render_view)

        # New value editor
        valhbox = QHBoxLayout()
        w = QLabel("Enter new value: ")
        w.setFont(font)
        valhbox.addWidget(w)
        self.inputbox = QLineEdit()
        self.inputbox.returnPressed.connect(self.update_value)
        valhbox.addWidget(self.inputbox)

        for item in [
                self.statdisplay, self.infodisplay, self.latdisplay,
                self.londisplay, self.valdisplay, self.idxdisplay, cmap_label
        ]:
            item.setFont(font)

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

        vbox2 = QVBoxLayout()
        vbox2.addWidget(self.preview)  # Adding preview window

        # Horizontal line
        fr = QFrame()
        fr.setLineWidth(0.5)
        fr.setFrameShape(QFrame.HLine)
        vbox2.addWidget(fr)
        vbox2.setAlignment(fr, Qt.AlignTop)

        # databox is a horizontal box for the displayed "information"
        databox = QHBoxLayout()
        statvbox = QVBoxLayout()  # This is the sub-box for the statistics
        statvbox.addWidget(self.statdisplay)
        statvbox.setAlignment(self.statdisplay, Qt.AlignTop)
        statvbox.addLayout(self.statgrid)
        databox.addLayout(statvbox)

        fr = QFrame()
        fr.setLineWidth(0.5)
        fr.setFrameShape(QFrame.VLine)
        databox.addWidget(fr)

        pixelvbox = QVBoxLayout(
        )  # This is another sub-box of databox for the pixel info
        pixelvbox.addWidget(self.infodisplay)
        pixelvbox.setAlignment(self.infodisplay, Qt.AlignTop)
        pixelvbox.addLayout(self.infogrid)
        databox.addLayout(pixelvbox)

        vbox2.addLayout(databox)

        # Horizontal line
        fr = QFrame()
        fr.setLineWidth(0.5)
        fr.setFrameShape(QFrame.HLine)
        vbox2.addWidget(fr)
        vbox2.setAlignment(fr, Qt.AlignTop)

        vbox2.addLayout(valhbox, Qt.AlignTop)

        vbox2.addStretch(1)
        vbox2.addWidget(cmap_label)  # Adding the colormap label
        vbox2.addWidget(self.colormaps)  # Adidng the colormap selector
        vbox2.addWidget(self.colorbar)
        vbox2.setAlignment(self.colorbar, Qt.AlignCenter)
        vbox2.addStretch(1)

        helpbox = QVBoxLayout()

        help_title = QLabel("Help")
        font = QFont("SansSerif", 14)
        font.setBold(True)
        help_title.setFont(font)

        helpbox.addWidget(help_title)
        helpbox.setAlignment(help_title, Qt.AlignTop)

        helpgrid = QGridLayout()
        helpgrid.setSpacing(5)

        helpgrid.addWidget(QLabel("Key"), 0, 0, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("Action"), 0, 1, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("up, down,left,right"), 1, 0, 1, 1,
                           Qt.AlignLeft)
        helpgrid.addWidget(QLabel("move cursor"), 1, 1, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("h,j,k,l"), 2, 0, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("move view"), 2, 1, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("a"), 3, 0, 1, 1, Qt.AlignLeft)
        # helpgrid.addWidget(QLabel("replace cell value with 9 point average"),         3, 1, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("replace cell value with 9\npoint average"),
                           3, 1, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("="), 4, 0, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("enter new value for cell"), 4, 1, 1, 1,
                           Qt.AlignLeft)
        helpgrid.addWidget(QLabel("c"), 5, 0, 1, 1, Qt.AlignLeft)
        # helpgrid.addWidget(QLabel("copy value under cursor into buffer"),         5, 1, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("copy value under cursor\ninto buffer"), 5,
                           1, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("v"), 6, 0, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("paste value in buffer"), 6, 1, 1, 1,
                           Qt.AlignLeft)
        helpgrid.addWidget(QLabel("m"), 7, 0, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("move focus to color selector"), 7, 1, 1, 1,
                           Qt.AlignLeft)
        helpgrid.addWidget(QLabel("Escape"), 8, 0, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("move focus to main view"), 8, 1, 1, 1,
                           Qt.AlignLeft)

        helpbox.addLayout(helpgrid)
        helpbox.setAlignment(helpgrid, Qt.AlignTop)

        vbox2.addLayout(helpbox)
        vbox2.setAlignment(helpbox, Qt.AlignBottom)

        hbox = QHBoxLayout()
        hbox.addLayout(vbox)
        hbox.addLayout(vbox2)

        self.main_frame.setLayout(hbox)
        self.setCentralWidget(self.main_frame)
        self.main_frame.setFocus()
Esempio n. 42
0
    def create_main_frame(self):
        self.main_frame = QWidget()

        plot_frame = QWidget()

        self.dpi = 100
        self.fig = Figure((6.0, 6.0), dpi=self.dpi)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.main_frame)

        cid = self.canvas.mpl_connect('button_press_event', self.onclick)
        self.axes = self.fig.add_subplot(111)
        self.cax = None
        #self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)

        log_label = QLabel("Number of examples:")
        self.series_list_view = QListView()
        self.series_list_view.setModel(self.series_list_model)


        cost_label = QLabel('C')
        #self.cost = QSpinBox()#QLineEdit()
        self.cost = QLineEdit()
        self.cost.setText("1.0")
        #self.cost.setMinimum(1)
        spin_label2 = QLabel('tube')
        self.tubeeps = QLineEdit()
        self.tubeeps.setText("0.1")
        spin_label3 = QLabel('sigma')
        self.sigma = QLineEdit()
        self.sigma.setText("1.2")
        #self.sigma.setMinimum(1)
        spin_label4 = QLabel('d')
        self.degree = QLineEdit()
        self.degree.setText("2")
        #self.sigma.setMinimum(1)

        spins_hbox = QHBoxLayout()
        spins_hbox.addWidget(cost_label)
        spins_hbox.addWidget(self.cost)
        spins_hbox.addWidget(spin_label2)
        spins_hbox.addWidget(self.tubeeps)
        spins_hbox.addWidget(spin_label3)
        spins_hbox.addWidget(self.sigma)
        spins_hbox.addWidget(spin_label4)
        spins_hbox.addWidget(self.degree)
        spins_hbox.addStretch(1)

        self.legend_cb = QCheckBox("Show Support Vectors")
        self.legend_cb.setChecked(False)

        self.show_button = QPushButton("&Train SVR")
        self.connect(self.show_button, SIGNAL('clicked()'), self.train_svm)

        self.clear_button = QPushButton("&Clear")
        self.connect(self.clear_button, SIGNAL('clicked()'), self.clear)


        self.kernel_combo = QComboBox()
        self.kernel_combo.insertItem(-1, "GaussianKernel")
        self.kernel_combo.insertItem(-1, "PolynomialKernel")
        self.kernel_combo.insertItem(-1, "LinearKernel")
        self.kernel_combo.maximumSize = QSize(300, 50)
        self.connect(self.kernel_combo, SIGNAL("currentIndexChanged(QString)"), self.enable_widgets)


        left_vbox = QVBoxLayout()
        left_vbox.addWidget(self.canvas)
        #left_vbox.addWidget(self.mpl_toolbar)

        right0_vbox = QVBoxLayout()
        right0_vbox.addWidget(log_label)
        right0_vbox.addWidget(self.series_list_view)
        #right0_vbox.addWidget(self.legend_cb)
        right0_vbox.addStretch(1)

        right2_vbox = QVBoxLayout()
        right2_label = QLabel("Settings")
        right2_vbox.addWidget(right2_label)
        right2_vbox.addWidget(self.show_button)
        right2_vbox.addWidget(self.kernel_combo)
        right2_vbox.addLayout(spins_hbox)
        right2_clearlabel = QLabel("Remove Data")
        right2_vbox.addWidget(right2_clearlabel)

        right2_vbox.addWidget(self.clear_button)


        right2_vbox.addStretch(1)

        right_vbox = QHBoxLayout()
        right_vbox.addLayout(right0_vbox)
        right_vbox.addLayout(right2_vbox)


        hbox = QVBoxLayout()
        hbox.addLayout(left_vbox)
        hbox.addLayout(right_vbox)
        self.main_frame.setLayout(hbox)

        self.setCentralWidget(self.main_frame)
        self.enable_widgets()
Esempio n. 43
0
class LFGui(QtGui.QMainWindow):
    proc = QtCore.Signal(int, infra.SplineCurve)
    open_file_sig = QtCore.Signal(backends.FilePath, dict)
    kill_thread = QtCore.Signal()
    redraw_sig = QtCore.Signal(bool, bool)
    draw_done_sig = QtCore.Signal()
    spinner_lst = [
        {
            'name': 's_width',
            'min': 0,
            'max': 99,
            'step': .5,
            'prec': 1,
            'type': np.float,
            'default': 10,
            'togglable': False
        },
        {
            'name': 's_num',
            'min': 1,
            'max': 9999,
            'step': 1,
            'type': np.int,
            'default': 100,
            'togglable': False
        },
        {
            'name': 'search_range',
            'min': .001,
            'max': 2 * np.pi,
            'step': .005,
            'prec': 3,
            'type': np.float,
            'default': .01,
            'togglable': False
        },
        {
            'name': 'memory',
            'min': 0,
            'max': 999,
            'step': 1,
            'type': np.int,
            'default': 0,
            'togglable': False
        },
        {
            'name': 'pix_err',
            'min': 0,
            'max': 9,
            'step': .1,
            'prec': 1,
            'type': np.float,
            'default': 0.5,
            'togglable': False
        },
        {
            'name': 'mix_in_count',
            'min': 0,
            'max': 100,
            'step': 1,
            'type': np.int,
            'default': 0,
            'togglable': False
        },
        {
            'name': 'min_tlen',
            'min': 0,
            'max': 999999,
            'step': 1,
            'type': np.int,
            'default': 15,
            'togglable': True,
            'default_state': True
        },
        {
            'name': 'fft_filter',
            'min': 0,
            'max': 999,
            'step': 1,
            'type': np.int,
            'default': 10,
            'togglable': True,
            'default_state': True
        },
        {
            'name': 'min_extent',
            'min': 0,
            'max': 999,
            'step': 1,
            'type': np.int,
            'default': 10,
            'togglable': True,
            'default_state': False,
            'tooltip': 'The minimum extent in q[pixel] of a track to be valid'
        },
        {
            'name':
            'max_gap',
            'min':
            0,
            'max':
            np.pi,
            'step':
            np.pi / 100,
            'type':
            np.float,
            'default':
            np.pi / 6,
            'prec':
            3,
            'togglable':
            True,
            'default_state':
            True,
            'tooltip':
            'The maximum gap (in rad) before the' +
            ' alternate gap handling is used'
        },
        {
            'name':
            'max_circ_change',
            'min':
            0,
            'max':
            1,
            'step':
            .0005,
            'prec':
            4,
            'type':
            np.float,
            'default':
            .002,
            'togglable':
            True,
            'default_state':
            True,
            'tooltip':
            """The maximum fractional change in the circumference of
successive rims.  If exceeded, the previous seed-curve is re-used"""
        },
        {
            'name': 'end_frame',
            'min': -1,
            'max': 2**31 - 1,
            'step': 1,
            'type': np.int,
            'default': -1,
            'togglable': True,
            'default_state': False,
            'tooltip': """The last frame to process to"""
        },
    ]

    toggle_lst = [{
        'name':
        'straddle',
        'default':
        True,
        'tooltip':
        'If checked, then tracks must cross' + ' the seed line to be valid'
    }]

    cap_lst = ['cine base path']

    @QtCore.Slot()
    def unlock_gui(self):
        """
        Forcable un-locks the gui
        """
        self.prog_bar.hide()
        self.diag.setEnabled(True)

    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        self.setWindowTitle('Fringe Finder')

        self.cine_fname = None

        self.cur_frame = 0

        self.draw_fringes = False

        default_params = dict(
            (d['name'], d['default']) for d in self.spinner_lst
            if ('default_state' not in d or d['default_state']))
        for tog in self.toggle_lst:
            default_params[tog['name']] = tog['default']

        self.thread = QtCore.QThread(parent=self)

        self.worker = LFWorker(parent=None)
        self.worker.moveToThread(self.thread)

        self.cur_curve = None
        self.next_curve = None

        self.fringe_lines = []

        self.all_fringes_flg = False

        self.paths_dict = defaultdict(lambda: None)
        self.directory_actions = {}
        self.param_spin_dict = {}
        self.param_checkbox_dict = {}

        self.create_actions()
        self.create_main_frame()
        self.create_menu_bar()
        self.create_diag()
        self.create_status_bar()

        self.on_draw(True, True)
        self.worker.frame_proced.connect(self.on_draw)
        self.worker.file_loaded.connect(self.redraw)
        self.proc.connect(self.worker.proc_frame)
        self.open_file_sig.connect(self.worker.set_new_fname)
        self.redraw_sig.connect(self.on_draw)

        self.kill_thread.connect(self.thread.quit)

        self.draw_done_sig.connect(self._play)
        self.draw_done_sig.connect(self.unlock_gui)

        self.show()
        self.thread.start()
        QtGui.qApp.exec_()

    def grab_sf_curve(self):
        try:
            self.cur_curve = self.sf.return_SplineCurve()
            if self.cur_curve is not None:
                self.proc_this_frame_acc.setEnabled(True)
                self.start_comp_acc.setEnabled(True)
            else:
                print('no spline!?')
        except:
            print('spline fitter not ready')
            self.cur_curve = None

    # def update_param(self, key, val):
    #     self.worker.update_param(key, val)

    def _proc_this_frame(self):

        print('entered _proc_this_frame')
        self.prog_bar.show()
        self.diag.setEnabled(False)
        self.draw_fringes = True
        self.proc_next_frame_acc.setEnabled(True)
        self.iterate_button.setEnabled(True)

        self.proc.emit(self.cur_frame, self.cur_curve)

    def _proc_next_frame(self):

        self.frame_spinner.setValue(self.cur_frame + 1)
        self.diag.setEnabled(False)
        #self._proc_this_frame()

    def set_fringes_visible(self, i):
        self.draw_fringes = bool(i)

        self.redraw_sig.emit(True, False)

    def set_all_friges(self, i):
        self.all_fringes_flg = bool(i)
        self.redraw_sig.emit(True, False)

    @QtCore.Slot(bool, bool)
    def on_draw(self, refresh_lines=True, refresh_img=True):
        """ Redraws the figure
        """
        self.fringe_grp_bx.setChecked(self.draw_fringes)

        # update the image
        if refresh_img and self.im is not None:
            img = self.worker.get_frame(self.cur_frame)
            if img is not None:
                self.im.set_data(img)

        # if we need to update the lines
        if refresh_lines:
            # clear the lines we have
            for ln in self.fringe_lines:
                ln.remove()
            # nuke all those objects
            self.fringe_lines = []

            if self.draw_fringes:
                # if we should draw new ones, do so

                # grab new mbe from thread object
                mbe = self.worker.get_mbe()
                # grab new next curve
                self.next_curve = self.worker.get_next_curve()
                if self.draw_fringes and mbe is not None:
                    self.fringe_lines.extend(
                        mbe.ax_plot_tracks(self.axes,
                                           min_len=0,
                                           all_tracks=self.all_fringes_flg))
                    self.fringe_lines.extend(
                        mbe.ax_draw_center_curves(self.axes))

        self.canvas.draw()
        self.status_text.setNum(self.cur_frame)
        self.draw_done_sig.emit()

    def clear_mbe(self):
        self.cur_curve = None
        self.next_curve = None
        self.proc_this_frame_acc.setEnabled(False)
        self.proc_next_frame_acc.setEnabled(False)
        self.start_comp_acc.setEnabled(False)
        self.iterate_button.setEnabled(False)
        self.fringe_grp_bx.setChecked(False)

    def set_spline_fitter(self, i):
        if i:
            self.sf.connect_sf()
            # if we can screw with it, make it visible
            self.sf_show.setChecked(True)
        else:
            self.sf.disconnect_sf()
        self.redraw_sig.emit(False, False)

    def set_spline_fitter_visible(self, i):
        self.sf.set_visible(i)
        # if we can't see it, don't let is screw with it
        if not bool(i):
            self.sf_check.setChecked(False)
        self.redraw_sig.emit(False, False)

    def set_cur_frame(self, i):
        old_frame, self.cur_frame = self.cur_frame, i
        if old_frame == self.cur_frame - 1:
            self.cur_curve = self.next_curve
            if self.draw_fringes:
                self._proc_this_frame()
            else:
                self.redraw_sig.emit(False, True)

        else:
            self.draw_fringes = False
            self.worker.clear()
            self.redraw_sig.emit(True, True)

    def iterate_frame(self):
        self.cur_curve = self.next_curve
        self._proc_this_frame()

    def clear_spline(self):
        self.sf.clear()

    def show_cntrls(self):
        self.diag.show()

    def start_comp(self):
        self.worker.start_comp(self.cur_curve,
                               self.output_template.path_template,
                               self.cur_frame, self.i_disk_dict)

    def open_file(self):

        fname, _ = QtGui.QFileDialog.getOpenFileName(
            self,
            caption='Select cine',
            dir=self.paths_dict['cine base path'],
            filter="cine (*.cine)")
        if len(fname) == 0:
            return

        self.fringe_grp_bx.setChecked(False)
        while (self.paths_dict['cine base path'] is None
               or (not (self.paths_dict['cine base path']
                        == fname[:len(self.paths_dict['cine base path'])]))):
            print('please set base_dir')
            self.directory_actions['cine base path'].trigger()

        self.prog_bar.show()

        tmp_params = self._get_cur_parametrs()
        self.diag.setEnabled(False)

        path_, fname_ = os.path.split(
            fname[(len(self.paths_dict['cine base path']) + 1):])

        new_cine_fname = backends.FilePath(self.paths_dict['cine base path'],
                                           path_, fname_)

        self.fname_text.setText('/'.join(new_cine_fname[1:]))
        self.clear_mbe()
        # reset spinners to default values
        # for p in self.spinner_lst:
        #     self.param_spin_dict[p['name']].setValue(p['default'])

        self.fname_text.setText(new_cine_fname[-1])
        self.open_file_sig.emit(new_cine_fname, tmp_params)

    def _get_cur_parametrs(self):
        tmp_dict = {}
        # get parameters out of spin boxes
        for key, sb in self.param_spin_dict.items():

            if sb.isEnabled():
                tmp_dict[key] = sb.value()

        # get toggle switch values
        for key, cb in self.param_checkbox_dict.items():

            tmp_dict[key] = bool(cb.checkState())

        return tmp_dict

    def update_all_params(self):
        tmp_dict = self._get_cur_parametrs()
        # shove them into the worker
        self.worker.update_all_params(tmp_dict)

        # re-draw
        if self.draw_fringes:
            self._proc_this_frame()

    def create_diag(self):
        # make top level stuff
        self.diag = QtGui.QDockWidget('controls', parent=self)
        self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.diag)
        diag_widget = QtGui.QWidget(self.diag)
        self.diag.setWidget(diag_widget)
        diag_layout = QtGui.QVBoxLayout()
        diag_widget.setLayout(diag_layout)

        # frame number lives on top
        self.frame_spinner = QtGui.QSpinBox()
        self.frame_spinner.setRange(0, len(self.worker) - 1)
        self.frame_spinner.valueChanged.connect(self.set_cur_frame)

        frame_selector_group = QtGui.QVBoxLayout()
        fs_form = QtGui.QHBoxLayout()
        fs_form.addWidget(QtGui.QLabel('frame #'))
        fs_form.addWidget(self.frame_spinner)
        fs_form.addWidget(QtGui.QLabel(' of '))
        self.max_cine_label = QtGui.QLabel(str(len(self.worker) - 1))
        fs_form.addWidget(self.max_cine_label)
        fs_stepbox = QtGui.QGroupBox("Frame step")
        fs_sb_rb = QtGui.QHBoxLayout()
        for j in [1, 10, 100, 1000, 10000]:
            tmp_rdo = QtGui.QRadioButton(str(j))
            tmp_rdo.toggled.connect(lambda x, j=j: self.frame_spinner.
                                    setSingleStep(j) if x else None)
            fs_sb_rb.addWidget(tmp_rdo)
            if j == 1:
                tmp_rdo.toggle()
            pass
        fs_stepbox.setLayout(fs_sb_rb)
        frame_selector_group.addLayout(fs_form)
        frame_selector_group.addWidget(fs_stepbox)
        diag_layout.addLayout(frame_selector_group)

        # play button
        play_button = QtGui.QPushButton('Play')
        self.play_button = play_button
        play_button.setCheckable(True)
        play_button.setChecked(False)
        self.play_button.pressed.connect(self.frame_spinner.stepUp)
        diag_layout.addWidget(play_button)

        meta_data_group = QtGui.QVBoxLayout()

        useful_button = QtGui.QPushButton('useful')
        useful_button.clicked.connect(self.worker.set_useful)
        useless_button = QtGui.QPushButton('useless')
        useless_button.clicked.connect(self.worker.set_useless)
        use_level = QtGui.QHBoxLayout()
        use_level.addWidget(useful_button)
        use_level.addWidget(useless_button)
        meta_data_group.addLayout(use_level)

        md_dict_disp = dict_display('cine md')
        self.worker.md_loadad.connect(md_dict_disp.update)
        meta_data_group.addWidget(md_dict_disp)

        diag_layout.addLayout(meta_data_group)

        # tool box for all the controls
        diag_tool_box = QtGui.QToolBox()
        diag_layout.addWidget(diag_tool_box)

        # section for dealing with fringe finding

        # the widget to shove into the toolbox
        fringe_cntrls_w = QtGui.QWidget()
        # vbox layout for this panel
        fc_vboxes = QtGui.QVBoxLayout()
        # set the widget layout

        fringe_cntrls_w.setLayout(fc_vboxes)
        # add to the tool box
        diag_tool_box.addItem(fringe_cntrls_w, "Fringe Finding Settings")

        # form layout to hold the spinners
        fringe_cntrls_spins = QtGui.QFormLayout()
        # add spinner layout
        fc_vboxes.addLayout(fringe_cntrls_spins)

        # fill the spinners
        for spin_prams in LFGui.spinner_lst:

            s_type = np.dtype(spin_prams['type']).kind

            if s_type == 'i':
                spin_box = QtGui.QSpinBox(parent=self)
            elif s_type == 'f':
                spin_box = QtGui.QDoubleSpinBox(parent=self)
                spin_box.setDecimals(spin_prams['prec'])
            else:
                print(s_type)
                continue

            # properties of spin box
            spin_box.setRange(spin_prams['min'], spin_prams['max'])
            spin_box.setSingleStep(spin_prams['step'])
            spin_box.setValue(spin_prams['default'])
            name = spin_prams['name']
            spin_box.setKeyboardTracking(False)

            # connect it to an action
            spin_box.valueChanged.connect(self.update_params_acc.trigger)

            l_label = QtGui.QLabel(spin_prams['name'])
            if 'tooltip' in spin_prams:
                l_label.setToolTip(spin_prams['tooltip'])
            # if it can be turned on or off
            if spin_prams['togglable']:
                l_checkbox = QtGui.QCheckBox('enable')
                l_checkbox.stateChanged.connect(spin_box.setEnabled)
                l_checkbox.setChecked(spin_prams['default_state'])
                spin_box.setEnabled(spin_prams['default_state'])
                l_checkbox.stateChanged.connect(self.update_params_acc.trigger)
                l_h_layout = QtGui.QHBoxLayout()
                l_h_layout.addWidget(spin_box)
                l_h_layout.addWidget(l_checkbox)
                fringe_cntrls_spins.addRow(l_label, l_h_layout)
            # if it can't
            else:
                fringe_cntrls_spins.addRow(l_label, spin_box)
            # add the spin box
            self.param_spin_dict[name] = spin_box

        for cb_param in self.toggle_lst:
            l_label = QtGui.QLabel(cb_param['name'])
            if 'tooltip' in cb_param:
                l_label.setToolTip(cb_param['tooltip'])

            l_checkbox = QtGui.QCheckBox('enable')
            l_checkbox.setChecked(cb_param['default'])
            self.param_checkbox_dict[cb_param['name']] = l_checkbox
            l_checkbox.stateChanged.connect(self.update_params_acc.trigger)
            fringe_cntrls_spins.addRow(l_label, l_checkbox)

        # button to grab initial spline
        grab_button = QtGui.QPushButton('Grab Spline')
        grab_button.clicked.connect(self.grab_sf_curve)
        fc_vboxes.addWidget(grab_button)
        # button to process this frame

        ptf_button = QtGui.QPushButton('Process This Frame')
        ptf_button.clicked.connect(self.proc_this_frame_acc.trigger)
        ptf_button.setEnabled(self.proc_this_frame_acc.isEnabled())
        self.proc_this_frame_acc.changed.connect(lambda: ptf_button.setEnabled(
            self.proc_this_frame_acc.isEnabled()))

        fc_vboxes.addWidget(ptf_button)

        # button to process next frame
        pnf_button = QtGui.QPushButton('Process Next Frame')
        pnf_button.clicked.connect(self.proc_next_frame_acc.trigger)
        pnf_button.setEnabled(self.proc_next_frame_acc.isEnabled())
        self.proc_next_frame_acc.changed.connect(lambda: pnf_button.setEnabled(
            self.proc_next_frame_acc.isEnabled()))

        fc_vboxes.addWidget(pnf_button)

        # nuke tracking data
        clear_mbe_button = QtGui.QPushButton('Clear fringes')
        clear_mbe_button.clicked.connect(self.clear_mbe)
        fc_vboxes.addWidget(clear_mbe_button)

        self.fringe_grp_bx = QtGui.QGroupBox("Draw Fringes")
        self.fringe_grp_bx.setCheckable(True)
        self.fringe_grp_bx.setChecked(False)
        self.fringe_grp_bx.toggled.connect(self.set_fringes_visible)

        #        self.proc_this_frame_acc.triggered.connect(
        #   lambda:self.fringe_grp_bx.setChecked(True))

        all_fringe_rb = QtGui.QRadioButton('All Fringes')
        valid_fringes_rb = QtGui.QRadioButton('Valid Fringes')
        rb_vbox = QtGui.QVBoxLayout()
        rb_vbox.addWidget(valid_fringes_rb)
        rb_vbox.addWidget(all_fringe_rb)
        self.fringe_grp_bx.setLayout(rb_vbox)
        all_fringe_rb.toggled.connect(self.set_all_friges)
        all_fringe_rb.setChecked(False)
        valid_fringes_rb.setChecked(True)
        fc_vboxes.addWidget(self.fringe_grp_bx)

        iterate_button = QtGui.QPushButton('Iterate fringes')
        iterate_button.clicked.connect(self.iterate_frame)
        iterate_button.setEnabled(False)
        fc_vboxes.addWidget(iterate_button)
        self.iterate_button = iterate_button

        start_comp_bttn = QtGui.QPushButton('Start Computation')
        start_comp_bttn.clicked.connect(self.start_comp_acc.trigger)

        start_comp_bttn.setEnabled(self.start_comp_acc.isEnabled())
        self.start_comp_acc.changed.connect(lambda: start_comp_bttn.setEnabled(
            self.start_comp_acc.isEnabled()))

        fc_vboxes.addWidget(start_comp_bttn)
        fc_vboxes.addStretch()

        # section for making spline fitting panel
        spline_cntrls = QtGui.QVBoxLayout()
        spline_cntrls_w = QtGui.QWidget()
        spline_cntrls_w.setLayout(spline_cntrls)

        self.sf_check = QtGui.QCheckBox('enabled input')
        self.sf_check.stateChanged.connect(self.set_spline_fitter)
        spline_cntrls.addWidget(self.sf_check)

        self.sf_show = QtGui.QCheckBox('display fitter')
        self.sf_show.stateChanged.connect(self.set_spline_fitter_visible)
        spline_cntrls.addWidget(self.sf_show)

        clear_spline_button = QtGui.QPushButton('Clear Spline')
        clear_spline_button.clicked.connect(self.clear_spline)
        spline_cntrls.addWidget(clear_spline_button)

        spline_cntrls.addStretch()

        diag_tool_box.addItem(spline_cntrls_w, "Manual Spline Fitting")

        # section for making spline fitting panel
        paths_layout = QtGui.QVBoxLayout()
        path_w = QtGui.QWidget()
        path_w.setLayout(paths_layout)

        for c in self.cap_lst:
            ds = directory_selector(caption=c)
            paths_layout.addWidget(ds)
            self.directory_actions[c].triggered.connect(ds.select_path)
            ds.selected.connect(
                lambda x, c=c: self.paths_dict.__setitem__(c, x))

        self.disk_widget = numbered_paths(2, self)
        paths_layout.addWidget(self.disk_widget)

        self.output_template = base_path_path_selector('output template')
        paths_layout.addWidget(self.output_template)

        paths_layout.addStretch()
        diag_tool_box.addItem(path_w, "Paths")

    def create_main_frame(self):
        self.main_frame = QtGui.QWidget()
        # create the mpl Figure and FigCanvas objects.
        # 5x4 inches, 100 dots-per-inch
        #

        self.fig = Figure((24, 24), tight_layout=True)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.main_frame)
        self.axes = self.fig.add_subplot(111,
                                         adjustable='datalim',
                                         aspect='equal')
        #      self.fig.tight_layout(.3, None, None, None)
        # 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.im = None

        #        tmp = self.worker.get_frame(self.cur_frame)

        #self.im = self.axes.imshow(tmp, cmap='gray', interpolation='nearest')
        #        self.axes.set_aspect('equal')
        #        self.im.set_clim([.5, 1.5])

        self.sf = infra.spline_fitter(self.axes)
        self.sf.disconnect_sf()

        #        self.axes.set_xlim(left=0)
        #self.axes.set_ylim(top=0)
        # this is because images are plotted upside down
        # Create the navigation toolbar, tied to the canvas
        #
        self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)

        # Other GUI controls
        #
        # lay out main panel

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

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

    @QtCore.Slot(bool, bool)
    def redraw(self, draw_img, draw_tracks):
        if self.im is not None:
            self.im.remove()
        self.im = None
        print('entered redraw')

        # clear the lines we have
        for ln in self.fringe_lines:
            ln.remove()
        self.fringe_lines = []

        mbe = self.worker.get_mbe()
        img = self.worker.get_frame(0)

        if img is None:
            img = 1.5 * np.ones((1, 1))

        extent = [0, img.shape[1], 0, img.shape[0]]

        self.im = self.axes.imshow(img,
                                   cmap='gray',
                                   extent=extent,
                                   origin='lower',
                                   interpolation='nearest')
        self.im.set_clim([.5, 1.5])
        self.axes.set_aspect('equal')

        if self.draw_fringes and mbe is not None:
            # if we should draw new ones, do so
            # grab new mbe from thread object
            # grab new next curve

            if self.draw_fringes and mbe is not None:
                self.fringe_lines.extend(
                    mbe.ax_plot_tracks(self.axes,
                                       min_len=0,
                                       all_tracks=self.all_fringes_flg))

        #self.status_text.setText(label)

        self.frame_spinner.setRange(0, len(self.worker) - 1)
        self.max_cine_label.setText(str(len(self.worker) - 1))
        self.frame_spinner.setValue(0)

        self.redraw_sig.emit(False, False)

    def create_status_bar(self):
        self.status_text = QtGui.QLabel(str(self.cur_frame))

        self.fname_text = QtGui.QLabel('')
        self.fname_text.setTextInteractionFlags(
            QtCore.Qt.TextSelectableByMouse)
        self.statusBar().addWidget(self.status_text)
        self.prog_bar = QtGui.QProgressBar()
        self.prog_bar.setRange(0, 0)
        self.prog_bar.hide()
        self.statusBar().addWidget(self.prog_bar, 1)
        self.statusBar().addPermanentWidget(self.fname_text)

    def closeEvent(self, ce):
        self.kill_thread.emit()
        #        QtGui.qApp.quit()
        #        self.thread.quit()
        self.diag.close()
        QtGui.QMainWindow.closeEvent(self, ce)

    def create_actions(self):
        self.show_cntrl_acc = QtGui.QAction(u'show controls', self)
        self.show_cntrl_acc.triggered.connect(self.show_cntrls)

        self.start_comp_acc = QtGui.QAction(u'Save Parameters', self)
        self.start_comp_acc.setEnabled(False)
        self.start_comp_acc.triggered.connect(self.start_comp)

        self.open_file_acc = QtGui.QAction(u'Open &File', self)
        self.open_file_acc.triggered.connect(self.open_file)

        self.proc_this_frame_acc = QtGui.QAction('Process this Frame', self)
        self.proc_this_frame_acc.setEnabled(False)
        self.proc_this_frame_acc.triggered.connect(self._proc_this_frame)

        self.proc_next_frame_acc = QtGui.QAction('Process next Frame', self)
        self.proc_next_frame_acc.setEnabled(False)
        self.proc_next_frame_acc.triggered.connect(self._proc_next_frame)

        self.directory_actions = {}
        cta_lst = ['Select ' + x for x in self.cap_lst]
        for cap, cta in zip(self.cap_lst, cta_lst):
            tmp_acc = QtGui.QAction(cta, self)
            self.directory_actions[cap] = tmp_acc

        self.update_params_acc = QtGui.QAction('Update Parameters', self)
        self.update_params_acc.triggered.connect(self.update_all_params)

    def create_menu_bar(self):
        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(self.show_cntrl_acc)
        fileMenu.addAction(self.start_comp_acc)

        fileMenu.addAction(self.open_file_acc)
        pathMenu = menubar.addMenu('&Path')
        for ac in self.directory_actions:
            pathMenu.addAction(ac)

        procMenu = menubar.addMenu('&Process')
        procMenu.addAction(self.proc_this_frame_acc)
        procMenu.addAction(self.proc_next_frame_acc)

    @QtCore.Slot()
    def _play(self):
        QtGui.qApp.processEvents()  # make sure all pending
        # events are cleaned up if we
        # don't do this, this gets
        # hit before the button is
        # marked as checked
        if self.play_button.isChecked():
            QtCore.QTimer.singleShot(30, self.frame_spinner.stepUp)

    @property
    def disk_dict(self):
        return self.disk_widget.path_dict

    @property
    def i_disk_dict(self):
        return {v: k for k, v in self.disk_widget.path_dict.items()}
Esempio n. 44
0
class KMTEditor(QMainWindow):

    KMT_MIN_VAL = 0
    KMT_MAX_VAL = 60

    def __init__(self, fname, datavar, dwx=60, dwy=60):
        """
        ARGUMENTS:
            fname    - Name of the netcdf4 file
            datavar  - Name of the data variable in the file for which to plot
            dwx, dwy - size of the DataContainer in number of array elements
            scale    - A float that will be multiplied with the data to scale the data
        """
        super(KMTEditor, self).__init__(None)
        self.setWindowTitle('KMTEditor - {0}'.format(fname))

        #  Creating a variable that contains all the data
        self.dc = DataContainer(dwy, dwx, fname, datavar)

        self.cursor = self.dc.getCursor()  # Defining a cursor on the data
        # This is the Rectangle boundary drawn on the world map that bounds the region
        # under the view. At the start of the program it's value is None
        self.prvrect = None

        # This stores the matplotlib text objects used in the rendering of the colorbar
        # This is used by the function draw_colorbar()
        self.colorbarlabels = []
        # self.colorbar_gradient is used by the function draw_colorbar()
        self.colorbar_gradient = np.vstack(
            (np.linspace(0, 1, 256), np.linspace(0, 1, 256)))

        # The previously updated value
        self.buffer_value = None

        # Stuff for saving data
        self.ofile = None  # Name of output file
        self.asked_about_overwrite_permission = False
        self.unsaved_changes_exist = False

        self.maps = mpl.cm.datad.keys()  # The names of colormaps available
        self.maps.sort()  # Sorting them alphabetically for ease of use

        self.create_menu()
        self.create_main_window()

        self.set_stats_info(self.dc.updateView(
            0, 0))  # Set the initial view for the data container class

        self.draw_preview_worldmap()
        self.render_view()
        self.statusBar().showMessage('KMTEditor 2015')

    def keyPressEvent(self, e):
        if e.key() == Qt.Key_Equal:
            # Pressing = for edit
            self.inputbox.setFocus()
        elif e.key() == Qt.Key_V:
            self.update_value(self.buffer_value)
        elif e.key() == Qt.Key_C:
            self.buffer_value = self.dc.getValueUnderCursor()
            self.statusBar().showMessage(
                'Value copied: {0}'.format(self.buffer_value), 2000)
        elif e.key() == Qt.Key_A:
            # Get the 5-point average and update the value
            self.update_value_with_average(self.dc.getAverage())
        elif e.key() == Qt.Key_M:
            self.colormaps.setFocus()
        elif e.key() == Qt.Key_Escape:
            # Pressing escape to refocus back to the main frame
            self.main_frame.setFocus()
        elif e.key() in [Qt.Key_H, Qt.Key_J, Qt.Key_K, Qt.Key_L]:
            self.set_stats_info(self.dc.moveView(e.key()))
            self.render_view()
            self.render_edited_cells()
        else:
            self.dc.updateCursorPosition(e)
            self.draw_cursor()

    def create_main_window(self):
        """
        This function creates the main window of the program.
        """
        self.main_frame = QWidget()
        self.main_frame.setMinimumSize(QSize(700, 700))

        self.dpi = 100
        self.fig = plt.Figure((6, 6),
                              dpi=self.dpi,
                              facecolor='w',
                              edgecolor='w')
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.main_frame)

        # Stuff for the preview map >>>>>>>>>>>>>>>>>>>>>>>>>
        self.preview_frame = QWidget()
        self.preview_fig = plt.Figure((3, 1.6),
                                      dpi=self.dpi,
                                      facecolor='w',
                                      edgecolor='w')
        self.preview = FigureCanvas(self.preview_fig)
        self.preview.setParent(self.preview_frame)
        self.preview_axes = self.preview_fig.add_subplot(111)

        self.preview_fig.canvas.mpl_connect('button_press_event', self.onclick)
        self.preview_fig.subplots_adjust(top=1, bottom=0, left=0, right=1)
        # Stuff for the preview map <<<<<<<<<<<<<<<<<<<<<<<<<

        # Stuff for the colorbar >>>>>>>>>>>>>>>>>>>>>>>>>
        self.colorbar_frame = QWidget()
        self.colorbar_fig = plt.Figure((3, 0.4),
                                       dpi=self.dpi,
                                       facecolor='w',
                                       edgecolor='w')
        self.colorbar = FigureCanvas(self.colorbar_fig)
        self.colorbar.setParent(self.colorbar_frame)
        self.colorbar_axes = self.colorbar_fig.add_subplot(111)
        self.colorbar_fig.subplots_adjust(
            top=1.0, bottom=0.35, left=0.02,
            right=0.97)  #Tightening the area around the subplot
        self.colorbar_fig.patch.set_facecolor(
            'none')  # Making the figure background transparent

        self.colorbar_axes.get_xaxis().set_visible(False)
        self.colorbar_axes.get_yaxis().set_visible(False)
        # Stuff for the colorbar <<<<<<<<<<<<<<<<<<<<<<<<<

        # 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)
        # Turning off the axes ticks to maximize space. Also the labels were meaningless
        # anyway because they were not representing the actual lat/lons.
        self.axes.get_xaxis().set_visible(False)
        self.axes.get_yaxis().set_visible(False)

        # Other GUI controls
        # Information section
        font = QFont("SansSerif", 14)

        # STATISTICS >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        self.statdisplay = QLabel("Statistics:")
        self.statgrid = QGridLayout()
        self.statgrid.setSpacing(5)
        w = QLabel("View")
        w.setFont(font)
        self.statgrid.addWidget(w, 1, 1, Qt.AlignCenter)
        w = QLabel("Global")
        w.setFont(font)
        self.statgrid.addWidget(w, 1, 2, Qt.AlignCenter)

        for i, name in enumerate(["Minimum", "Maximum", "Mean"]):
            w = QLabel(name)
            w.setFont(font)
            self.statgrid.addWidget(w, i + 2, 0, Qt.AlignLeft)

        self.statsarray = []
        for i in range(6):
            self.statsarray.append(QLabel(''))

        self.statsarray[3].setText("{0:3d}".format(int(self.dc.data.min())))
        self.statsarray[4].setText("{0:3d}".format(int(self.dc.data.max())))
        self.statsarray[5].setText("{0:3d}".format(int(self.dc.data.mean())))

        for i in range(3):
            self.statgrid.addWidget(self.statsarray[i], i + 2, 1,
                                    Qt.AlignCenter)
            self.statgrid.addWidget(self.statsarray[i + 3], i + 2, 2,
                                    Qt.AlignCenter)
            self.statsarray[i].setFont(font)
            self.statsarray[i + 3].setFont(font)

        # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

        # PIXEL INFO >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

        self.infodisplay = QLabel("Pixel Information:")
        self.infogrid = QGridLayout()
        self.infogrid.setSpacing(5)

        for i, name in enumerate(["Lat", "Lon", "KMT", "I, J"]):
            w = QLabel(name)
            w.setFont(font)
            # w.setLineWidth(1)
            # w.setFrameShape(QFrame.Box)
            self.infogrid.addWidget(w, i + 2, 0, Qt.AlignLeft)

        self.latdisplay = QLabel("")
        self.londisplay = QLabel("")
        self.valdisplay = QLabel("")
        self.idxdisplay = QLabel("")
        for i, w in enumerate([
                self.latdisplay, self.londisplay, self.valdisplay,
                self.idxdisplay
        ]):
            self.infogrid.addWidget(w, i + 2, 1, Qt.AlignLeft)
            w.setFont(font)
        # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

        # Colorscheme selector
        cmap_label = QLabel('Colorscheme:')
        self.colormaps = QComboBox(self)
        self.colormaps.addItems(self.maps)
        self.colormaps.setCurrentIndex(self.maps.index('Set1'))
        self.colormaps.currentIndexChanged.connect(self.render_view)

        # New value editor
        valhbox = QHBoxLayout()
        w = QLabel("Enter new value: ")
        w.setFont(font)
        valhbox.addWidget(w)
        self.inputbox = QLineEdit()
        self.inputbox.returnPressed.connect(self.update_value)
        valhbox.addWidget(self.inputbox)

        for item in [
                self.statdisplay, self.infodisplay, self.latdisplay,
                self.londisplay, self.valdisplay, self.idxdisplay, cmap_label
        ]:
            item.setFont(font)

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

        vbox2 = QVBoxLayout()
        vbox2.addWidget(self.preview)  # Adding preview window

        # Horizontal line
        fr = QFrame()
        fr.setLineWidth(0.5)
        fr.setFrameShape(QFrame.HLine)
        vbox2.addWidget(fr)
        vbox2.setAlignment(fr, Qt.AlignTop)

        # databox is a horizontal box for the displayed "information"
        databox = QHBoxLayout()
        statvbox = QVBoxLayout()  # This is the sub-box for the statistics
        statvbox.addWidget(self.statdisplay)
        statvbox.setAlignment(self.statdisplay, Qt.AlignTop)
        statvbox.addLayout(self.statgrid)
        databox.addLayout(statvbox)

        fr = QFrame()
        fr.setLineWidth(0.5)
        fr.setFrameShape(QFrame.VLine)
        databox.addWidget(fr)

        pixelvbox = QVBoxLayout(
        )  # This is another sub-box of databox for the pixel info
        pixelvbox.addWidget(self.infodisplay)
        pixelvbox.setAlignment(self.infodisplay, Qt.AlignTop)
        pixelvbox.addLayout(self.infogrid)
        databox.addLayout(pixelvbox)

        vbox2.addLayout(databox)

        # Horizontal line
        fr = QFrame()
        fr.setLineWidth(0.5)
        fr.setFrameShape(QFrame.HLine)
        vbox2.addWidget(fr)
        vbox2.setAlignment(fr, Qt.AlignTop)

        vbox2.addLayout(valhbox, Qt.AlignTop)

        vbox2.addStretch(1)
        vbox2.addWidget(cmap_label)  # Adding the colormap label
        vbox2.addWidget(self.colormaps)  # Adidng the colormap selector
        vbox2.addWidget(self.colorbar)
        vbox2.setAlignment(self.colorbar, Qt.AlignCenter)
        vbox2.addStretch(1)

        helpbox = QVBoxLayout()

        help_title = QLabel("Help")
        font = QFont("SansSerif", 14)
        font.setBold(True)
        help_title.setFont(font)

        helpbox.addWidget(help_title)
        helpbox.setAlignment(help_title, Qt.AlignTop)

        helpgrid = QGridLayout()
        helpgrid.setSpacing(5)

        helpgrid.addWidget(QLabel("Key"), 0, 0, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("Action"), 0, 1, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("up, down,left,right"), 1, 0, 1, 1,
                           Qt.AlignLeft)
        helpgrid.addWidget(QLabel("move cursor"), 1, 1, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("h,j,k,l"), 2, 0, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("move view"), 2, 1, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("a"), 3, 0, 1, 1, Qt.AlignLeft)
        # helpgrid.addWidget(QLabel("replace cell value with 9 point average"),         3, 1, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("replace cell value with 9\npoint average"),
                           3, 1, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("="), 4, 0, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("enter new value for cell"), 4, 1, 1, 1,
                           Qt.AlignLeft)
        helpgrid.addWidget(QLabel("c"), 5, 0, 1, 1, Qt.AlignLeft)
        # helpgrid.addWidget(QLabel("copy value under cursor into buffer"),         5, 1, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("copy value under cursor\ninto buffer"), 5,
                           1, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("v"), 6, 0, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("paste value in buffer"), 6, 1, 1, 1,
                           Qt.AlignLeft)
        helpgrid.addWidget(QLabel("m"), 7, 0, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("move focus to color selector"), 7, 1, 1, 1,
                           Qt.AlignLeft)
        helpgrid.addWidget(QLabel("Escape"), 8, 0, 1, 1, Qt.AlignLeft)
        helpgrid.addWidget(QLabel("move focus to main view"), 8, 1, 1, 1,
                           Qt.AlignLeft)

        helpbox.addLayout(helpgrid)
        helpbox.setAlignment(helpgrid, Qt.AlignTop)

        vbox2.addLayout(helpbox)
        vbox2.setAlignment(helpbox, Qt.AlignBottom)

        hbox = QHBoxLayout()
        hbox.addLayout(vbox)
        hbox.addLayout(vbox2)

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

    def draw_preview_worldmap(self):
        """
        This function draws the world map in the preview window on the top right hand corner
        of the application.
        """
        m = Basemap(projection='cyl', lon_0=180, llcrnrlat=-90,urcrnrlat=90,\
            llcrnrlon=0,urcrnrlon=360,resolution='c', ax=self.preview_axes)
        self.preview_axes.set_xlim([0, 360])

        m.drawcoastlines(linewidth=0.5)
        m.fillcontinents()
        self.preview_axes.set_ylim([-90, 90])

    def draw_colorbar(self):
        """
        This function draws the colorbar and the labels for the colorbar. 
        """
        # First clear the colorbar axes
        self.colorbar_axes.cla()
        # Get the current selected colormap
        cmap = mpl.cm.get_cmap(self.maps[self.colormaps.currentIndex()])
        # Plot the colormap
        self.colorbar_axes.imshow(self.colorbar_gradient,
                                  aspect='auto',
                                  cmap=cmap)
        pos = list(self.colorbar_axes.get_position().bounds)
        dx = (pos[2]) / 6.  # The spacing between the labels

        if self.colorbarlabels != []:
            # Delete and clear the text labels
            while self.colorbarlabels:
                self.colorbarlabels.pop().remove()

        for i, l in enumerate([1, 10, 20, 30, 40, 50, 60]):
            self.colorbarlabels.append(
                self.colorbar_fig.text(pos[0] + (i * dx),
                                       0.01,
                                       str(l),
                                       va='bottom',
                                       ha='center',
                                       fontsize=10))
        self.colorbar.draw()

    def draw_cursor(self, noremove=False):
        if self.cursor.marker and (not noremove): self.cursor.marker.remove()
        # The increment by 0.5 below is done so that the center of the marker is shifted
        # so that the top left corner of the square marker conicides with the top right corner
        # of each pixel. The value of 0.5 comes simply because each pixel are offset by 1 in each dimension.
        _cx, _cy = self.cursor.x + 0.5, self.cursor.y + 0.5
        self.cursor.marker = self.axes.scatter(_cx,
                                               _cy,
                                               s=55,
                                               marker='s',
                                               edgecolor="k",
                                               facecolor='none',
                                               linewidth=2)
        self.set_information(self.cursor.y, self.cursor.x)
        self.canvas.draw()

    def render_edited_cells(self):
        """
        This function draws a box around cells that have been edited, thereby highlighting
        them from the other cells. 
        """
        changes_row_idx = self.dc.changes_row_idx

        # We only need to go ahead if a change has been made, i.e. changes_row_idx is larger than 0
        if changes_row_idx > 0:
            # We are creating simple views to make the code for this function simpler
            change_rows = self.dc.changes[:self.dc.changes_row_idx, 0].view(
            )  # A view on rows indices that have been changed
            change_cols = self.dc.changes[:self.dc.changes_row_idx, 1].view(
            )  # A view on column indices that have been changed

            # Retrieving some class variables and storing for speed
            si = self.dc.si
            sj = self.dc.sj
            nrows = self.dc.nrows
            ncols = self.dc.ncols

            # We select the indices that lie within the view box
            indices_of_interest = np.logical_and(
                np.logical_and(change_rows >= si, change_rows <= (si + nrows)),
                np.logical_and(change_cols >= sj, change_cols <= (sj + ncols)))

            _i = change_rows[indices_of_interest] + 0.5 - si
            _j = change_cols[indices_of_interest] + 0.5 - sj

            self.axes.scatter(_j,
                              _i,
                              s=38,
                              marker='s',
                              edgecolor="k",
                              facecolor='none',
                              linewidth=1)
            self.canvas.draw()

    def render_view(self):
        self.draw_colorbar()
        self.axes.clear()
        # Either select the colormap through the combo box or specify a custom colormap
        cmap = mpl.cm.get_cmap(self.maps[self.colormaps.currentIndex()])
        self.axes.pcolor(self.dc.view_masked,
                         cmap=cmap,
                         edgecolors='w',
                         linewidths=0.5,
                         vmin=KMTEditor.KMT_MIN_VAL,
                         vmax=KMTEditor.KMT_MAX_VAL)

        tmp1 = self.dc.nrows
        tmp2 = self.dc.ncols

        # This is for drawing the black contour line for the continents
        self.axes.contour(self.dc.view,
                          levels=[0],
                          colors='k',
                          linewidth=1.5,
                          interpolation="nearest",
                          origin="lower",
                          extents=[0.5, tmp2 + 0.5, 0.5, tmp1 + 0.5])

        # Setting the axes limits. This helps in setting the right orientation of the plot
        # and in clontrolling how much extra space we want around the scatter plot.
        # I am putting 4% space around the scatter plot
        self.axes.set_ylim([int(tmp1 * 1.02), 0 - int(tmp1 * 0.02)])
        self.axes.set_xlim([0 - int(tmp2 * 0.02), int(tmp2 * 1.02)])
        self.canvas.draw()
        self.fig.tight_layout()
        self.draw_cursor(noremove=True)

    def update_value(self, inp=None):
        if inp == None:
            inp = self.inputbox.text()  # Get the value in the text box

        if self.InputValueIsAcceptable(inp):
            self.dc.modifyValue(inp)  # Modify the data array
            self.unsaved_changes_exist = True
            self.buffer_value = inp
            self.statusBar().showMessage('Value changed: {0}'.format(inp),
                                         2000)
            self.set_stats_info(self.dc.getViewStatistics())
            self.inputbox.clear()  # Now clear the input box
            self.render_view(
            )  # Render the new view (which now contains the updated value)
            self.render_edited_cells()
            self.main_frame.setFocus()  # Bring focus back to the view

    def update_value_with_average(self, val):
        """
        Updates the value at the current cursor position using the input val.
        """
        self.dc.modifyValue(val)  # Modify the data array
        self.unsaved_changes_exist = True
        self.statusBar().showMessage('Value changed: {0}'.format(val), 2000)
        self.set_stats_info(self.dc.getViewStatistics())
        self.render_view(
        )  # Render the new view (which now contains the updated value)
        self.render_edited_cells()

    def InputValueIsAcceptable(self, inp):
        """ This functions checks to see if the user has entered a valid
            vlaue kmt value. Returns true if the input value is acceptable. """
        tt = float(inp)
        if (tt != int(tt)):
            msg = "KMT level must be an integer value\nYou entered {0}".format(
                inp)
            QMessageBox.critical(self, "Invalid Value", msg.strip())
            return False

        if ((tt < 0) or (tt > 60)):
            msg = "KMT level values must be between 0 and 60.\nYou entered {0}".format(
                inp)
            QMessageBox.critical(self, "Invalid Value", msg.strip())
            return False
        return True

    def set_information(self, i, j):
        """ Sets the displayed information about the pixel in the right sidebar.
        ARGUMENTS
            i, j : the local (i.e. DataContainer) 0-based indices for the element
        """
        i_global, j_global = self.dc.viewIndex2GlobalIndex(
            i, j)  # Convert local indices to global indices
        self.latdisplay.setText("{0:7.3f}".format(self.dc.kmt_lats[i_global,
                                                                   j_global]))
        self.londisplay.setText("{0:7.3f}".format(self.dc.kmt_lons[i_global,
                                                                   j_global]))
        self.valdisplay.setText("{0:3d}".format(
            int(self.dc.data[i_global, j_global])))
        self.idxdisplay.setText("{0:3d},{1:3d}".format(int(i_global),
                                                       int(j_global)))

    def set_stats_info(self, s):
        """
        Updates the statistics display panel with the stats for the view.
        ARGUMENTS
            s - a tuple with the min, max and mean of the view
        """
        self.statsarray[0].setText("{0:3d}".format(int(s[0])))
        self.statsarray[1].setText("{0:3d}".format(int(s[1])))
        self.statsarray[2].setText("{0:3d}".format(int(s[2])))

    def onclick(self, event):
        QMessageBox.information(
            self, "",
            "KMTEditor does not presently support mouse selection over the preview plot"
        )

    def on_about(self):
        msg = """ Edit KMT levels for the POP ocean model.  """
        QMessageBox.about(self, "About", msg.strip())

    def save_data(self):
        """
        Saves the data to a netCDF4 file. The program tries to construct a default format of
        output filename, but if it exists, it asks the user whether to overwrite it. If the
        user does not want to overwrite, she is asked to enter a new filename. 
        """

        # We construct a standard output name of the form: inputname_fixed.nc
        if self.ofile is None:
            self.ofile = self.dc.fname.split(".")[0] + "_fixed.nc"

        # Now we check if the file exists. Then we must ask the user if she wants to overwrite the file
        if not self.asked_about_overwrite_permission:
            clobber = False
            if os.path.exists(self.ofile):
                reply = QMessageBox.question(
                    self, 'Saving file...',
                    "The output file {0} exists. Overwrite?".format(
                        self.ofile), QMessageBox.Yes | QMessageBox.No,
                    QMessageBox.No)

                if reply == QMessageBox.Yes: clobber = True

                if not clobber:
                    # The use has responded to not overwrite, we must now ask for a new filename
                    ok = False
                    erromsg = ""
                    # This loop continues until an acceptable filename is entered, or the user presses cancel
                    while not ok:
                        _inp, ok = QInputDialog.getText(
                            self,
                            "Saving file...",
                            "{0}Enter name of a different output file:".format(
                                erromsg),
                        )
                        if ok:
                            try:
                                self.ofile = str(_inp)
                            except:
                                ok = False
                                erromsg = "File name not acceptable. "
                            if os.path.exists(self.ofile):
                                ok = False
                                erromsg = "File exists. "
                        else:
                            self.ofile = None
                            self.statusBar().showMessage(
                                'Save cancelled', 2000)
                            return

            # To simplify creation of the output filename, i first duplicate the original file, then overwrite
            # the kmt array.
            nccopy(self.dc.fname,
                   self.ofile,
                   quiet=True,
                   clobber=clobber,
                   zlib=False,
                   shuffle=False,
                   classic=1)

            # now we set this to True, so that next time we save, we are not prompted about existing file
            self.asked_about_overwrite_permission = True

        ncfile = Dataset(self.ofile, "a", format="NETCDF4")
        alldimensions = ncfile.dimensions
        allvariables = ncfile.variables
        if not "changes" in alldimensions:
            ncfile.createDimension("changes", None)
        if not "i" in alldimensions: ncfile.createDimension("i", 3)

        if not "original_kmt" in allvariables:
            okmt = ncfile.createVariable("original_kmt", "f4",
                                         ("latitude", "longitude"))
            okmt.description = "Original KMT data from which this file was created by KMTEditor.py"
            okmt[:, :] = np.flipud(self.dc.orig_data)

        if not "changes" in allvariables:
            cngvar = ncfile.createVariable("changes", "f8", ("changes", "i"))
            cngvar.description = "changes to original data leading to present data. (i,j,val)"
            cngvar[:, :] = self.dc.changes[0:self.dc.changes_row_idx, :]
        else:
            cngvar = allvariables["changes"]
            # s = cngvar.shape[0]
            cngvar[:, :] = self.dc.changes[0:self.dc.changes_row_idx, :]

        kmtvar = ncfile.variables["kmt"]
        kmtvar[:, :] = np.flipud(self.dc.data)
        kmtvar.description = "Created by KMTEditor.py"

        ncfile.history = "Created by KMTEditor.py"
        ncfile.input_file = self.dc.fname
        ncfile.created = time.ctime()
        ncfile.close()

        self.unsaved_changes_exist = False
        self.statusBar().showMessage('Saved to file: %s' % self.ofile, 2000)

    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 add_actions(self, target, actions):
        for action in actions:
            if action is None:
                target.addSeparator()
            else:
                target.addAction(action)

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

        load_file_action = self.create_action("&Save Data",
                                              shortcut="Ctrl+S",
                                              slot=self.save_data,
                                              tip="Save the data array")

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

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

    def closeEvent(self, event):
        if self.unsaved_changes_exist:
            reply = QMessageBox.question(
                self, 'Message',
                "There are unsaved changes. Are you sure you want to quit?",
                QMessageBox.Yes | QMessageBox.No, QMessageBox.No)

            if reply == QMessageBox.Yes:
                event.accept()
            else:
                event.ignore()
Esempio n. 45
0
class RdfWindow(QtGui.QDialog):
    def __init__(self):
        super(RdfWindow, self).__init__()

        self.bft = []
        self.k = []
        self.kpow = 0
        #        self.rdf_r = []
        #        self.rdf = []
        self.params = []
        self.amp_orig = [[], []]  #0 - k, 1 - amp or pha
        self.pha_orig = [[], []]
        self.rdf_exafs = []
        self.rdf_exafs_k = []

        self.initUI()

    @QtCore.pyqtSlot(str)
    def on_myStream_message(self, message):
        self.textEdit.moveCursor(QtGui.QTextCursor.End)
        self.textEdit.insertPlainText(message)

    def initUI(self):

        self.fig = plt.figure(5, figsize=(18, 6))
        self.ax_bft = plt.subplot2grid((1, 3), (0, 0))
        self.ax_bftft = plt.subplot2grid((1, 3), (0, 1))
        self.ax_rdf = plt.subplot2grid((1, 3), (0, 2))

        self.ax_bft.set_xlabel('Wavevector k, $\AA^{-1}$')
        self.ax_bft.set_ylabel('EXAFS, $\AA^{-2}$')
        self.ax_bftft.set_xlabel('Distance R, $\AA$')
        self.ax_bftft.set_ylabel('Fourier transform, $\AA^{-3}$')
        self.ax_rdf.set_xlabel('Distance R, $\AA$')
        self.ax_rdf.set_ylabel('RDF G(R)')

        self.line1_bft, = self.ax_bft.plot([], [], label='BFT')
        self.line2_bft, = self.ax_bft.plot([], [], label='fit')
        self.line1_bft.set_color('b')
        self.line2_bft.set_color('g')
        self.ax_bft.legend(handles=[self.line1_bft, self.line2_bft])

        self.line1_bftft, self.line2_bftft = self.ax_bftft.plot([], [], [], [])
        self.line1_bftft.set_color('b')
        self.line2_bftft.set_color('b')
        self.line2_bftft.set_linestyle('dotted')

        self.line3_bftft, self.line4_bftft = self.ax_bftft.plot([], [], [], [])
        self.line3_bftft.set_color('g')
        self.line4_bftft.set_color('g')
        self.line4_bftft.set_linestyle('dotted')

        self.line1_rdf, = self.ax_rdf.plot([], [], marker='o')
        self.line2_rdf, = self.ax_rdf.plot([], [])

        self.fig.tight_layout()

        self.canv = FigureCanvas(self.fig)
        self.tbar = NavigationToolbar(self.canv, self)

        self.rdf_r = np.arange(0.8, 2.5, 0.01)

        self.rdf = np.zeros(len(self.rdf_r))

        #        self.lblNrShells = QtGui.QLabel("Number of shells")
        #        self.edtNrShells = QtGui.QLineEdit("1")

        self.lblkmin = QtGui.QLabel("K min")
        self.lblkmax = QtGui.QLabel("K max")
        self.lbldk = QtGui.QLabel("dK")
        self.lblrmin = QtGui.QLabel("Rmin")
        self.lblrmax = QtGui.QLabel("Rmax")
        self.lbldr = QtGui.QLabel("dR")
        self.edtkmin = QtGui.QLineEdit("0.5")
        self.edtkmax = QtGui.QLineEdit("15")
        self.edtdk = QtGui.QLineEdit("0.05")
        self.edtrmin = QtGui.QLineEdit("0.5")
        self.edtrmax = QtGui.QLineEdit("2.8")
        self.edtdr = QtGui.QLineEdit("0.01")

        self.edtrmin.editingFinished.connect(self.resetFit)
        self.edtrmax.editingFinished.connect(self.resetFit)
        self.edtdr.editingFinished.connect(self.resetFit)

        #        self.lblCentralDist = QtGui.QLabel("Central distance")
        #        self.edtCentralDist = QtGui.QLineEdit("1.8")
        #        self.lblWidth = QtGui.QLabel("Width")
        #        self.edtWidth = QtGui.QLineEdit("0.001")
        #        self.lblAmplitude = QtGui.QLabel("Amplitude")
        #        self.edtAmplitude = QtGui.QLineEdit("50")

        self.lblIterations = QtGui.QLabel("Max. number of iterations")
        self.edtIterations = QtGui.QLineEdit("20")
        self.chkFirstFit = QtGui.QCheckBox(
            "Start new fit (checked) / continue fit (unchecked)")
        self.chkFirstFit.setChecked(True)

        self.Amp = QtGui.QComboBox()
        self.Pha = QtGui.QComboBox()

        lblAmp = QtGui.QLabel("Amplitude")
        lblPha = QtGui.QLabel("Phase")

        self.Amp.addItem("")
        self.Amp.addItem("E:/work/development/xaslib/fit/amp0001.dat")
        self.Pha.addItem("")
        self.Pha.addItem("E:/work/development/xaslib/fit/pha0001.dat")

        self.lblFuncEval = QtGui.QLabel("Number of function evaluations done")
        self.edtFuncEval = QtGui.QLineEdit()

        self.lblFitMessage = QtGui.QLabel("Iterations done")
        self.edtFitMessage = QtGui.QLineEdit()

        self.lblOptimality = QtGui.QLabel("Residual")
        self.edtOptimality = QtGui.QLineEdit()

        lfit = QtGui.QGridLayout()
        lfit.addWidget(self.lblFitMessage, 0, 0)
        lfit.addWidget(self.edtFitMessage, 0, 1)
        lfit.addWidget(self.lblFuncEval, 1, 0)
        lfit.addWidget(self.edtFuncEval, 1, 1)
        lfit.addWidget(self.lblOptimality, 2, 0)
        lfit.addWidget(self.edtOptimality, 2, 1)

        self.btnFit = QtGui.QPushButton('Fit')
        self.btnFit.clicked.connect(self.Fit_rdf)

        self.btnSaveRdf = QtGui.QPushButton('Save RDF')
        self.btnSaveRdf.clicked.connect(self.saveRDF)

        self.btnApply = QtGui.QPushButton('Apply')
        self.btnApply.clicked.connect(self.apply)

        self.btnCancel = QtGui.QPushButton('Cancel')
        self.btnCancel.clicked.connect(self.cancel)

        self.btnOpenAmp = QtGui.QPushButton('Open amplitude file(s) ...')
        self.btnOpenAmp.clicked.connect(self.openamp)
        self.btnOpenPha = QtGui.QPushButton('Open phase file(s) ...')
        self.btnOpenPha.clicked.connect(self.openpha)
        self.btnOpenFeff = QtGui.QPushButton('Open feff file(s) ...')
        self.btnOpenFeff.clicked.connect(self.openfeff)

        #        self.textEdit = QtGui.QTextEdit(self)

        #        lb.addWidget(self.textEdit, 1, 0)

        lfig = QtGui.QGridLayout()
        lfig.addWidget(self.tbar, 0, 0, 1, 2)
        lfig.addWidget(self.canv, 1, 0, 1, 2)

        lfig.addLayout(lfit, 2, 0)

        lfig.addWidget(self.btnFit, 3, 0)
        lfig.addWidget(self.btnSaveRdf, 4, 0)
        lfig.addWidget(self.btnApply, 5, 0)
        lfig.addWidget(self.btnCancel, 6, 0)

        lp = QtGui.QGridLayout()
        lp.addWidget(self.lblkmin, 0, 0)
        lp.addWidget(self.edtkmin, 0, 1)
        lp.addWidget(self.lblkmax, 0, 2)
        lp.addWidget(self.edtkmax, 0, 3)
        lp.addWidget(self.lbldk, 0, 4)
        lp.addWidget(self.edtdk, 0, 5)

        lp.addWidget(self.lblrmin, 1, 0)
        lp.addWidget(self.edtrmin, 1, 1)
        lp.addWidget(self.lblrmax, 1, 2)
        lp.addWidget(self.edtrmax, 1, 3)
        lp.addWidget(self.lbldr, 1, 4)
        lp.addWidget(self.edtdr, 1, 5)

        #        lfig.addWidget(self.lblAmplitude, 2,1)
        #        lfig.addWidget(self.edtAmplitude, 2,2)
        #        lfig.addWidget(self.lblCentralDist, 2,3)
        #        lfig.addWidget(self.edtCentralDist, 2,4)
        #        lfig.addWidget(self.lblWidth, 2,5)
        #        lfig.addWidget(self.edtWidth, 2,6)

        lp.addWidget(self.lblIterations, 2, 0, 1, 3)
        lp.addWidget(self.edtIterations, 2, 3, 1, 3)
        lp.addWidget(self.chkFirstFit, 3, 0, 1, 6)

        lp.addWidget(lblAmp, 4, 0)
        lp.addWidget(self.Amp, 4, 1, 1, 4)
        lp.addWidget(lblPha, 5, 0)
        lp.addWidget(self.Pha, 5, 1, 1, 4)
        lp.addWidget(self.btnOpenAmp, 4, 5)
        lp.addWidget(self.btnOpenPha, 5, 5)
        lp.addWidget(self.btnOpenFeff, 6, 0)

        lfig.addLayout(lp, 2, 1, 5, 1)

        self.setLayout(lfig)

        self.canv.draw()

    def Fit_rdf(self):

        self.kstart = float(self.edtkmin.text())
        self.kend = float(self.edtkmax.text())
        self.dk = float(self.edtdk.text())
        self.common_k = np.arange(self.kstart, self.kend, self.dk)

        self.rstart = float(self.edtrmin.text())
        self.rend = float(self.edtrmax.text())
        self.dr = float(self.edtdr.text())

        self.rdf_r = np.arange(self.rstart, self.rend, self.dr)

        if self.chkFirstFit.isChecked():
            self.rdf = np.zeros(len(self.rdf_r))

        #prepare variable and parameter array

        splbft = InterpolatedUnivariateSpline(self.k, self.bft)
        self.common_bft = splbft(self.common_k)

        varbounds = [[], []]
        varbounds1 = []

        for i in range(len(self.rdf_r)):
            varbounds[0].append(0)
            varbounds[1].append(1E6)
            varbounds1.append((0, 1E6))
        varbounds[0] = tuple(varbounds[0])
        varbounds[1] = tuple(varbounds[1])

        par = []
        var_par = []
        edtVarBoxes = []

        if self.amp_orig[0] == [] or self.pha_orig[0] == []:

            kamp, amp_orig = np.genfromtxt(self.Amp.currentText(),
                                           usecols=(0, 1),
                                           unpack=True)
            kpha, pha_orig = np.genfromtxt(self.Pha.currentText(),
                                           usecols=(0, 1),
                                           unpack=True)
            self.amp_orig[0] = kamp
            self.pha_orig[0] = kpha
            self.amp_orig[1] = amp_orig
            self.pha_orig[1] = pha_orig
        else:
            kamp = self.amp_orig[0]
            amp_orig = self.amp_orig[1]
            kpha = self.pha_orig[0]
            pha_orig = self.pha_orig[1]

        print(kamp, amp_orig)
        splamp = InterpolatedUnivariateSpline(kamp, amp_orig)
        splpha = InterpolatedUnivariateSpline(kpha, pha_orig)

        amp = splamp(self.common_k)
        pha = splpha(self.common_k)

        pha_component = np.sin(2 * np.transpose(np.array([self.rdf_r])).dot(
            np.array([self.common_k])) + pha)

        rdf_r2 = self.rdf_r * self.rdf_r

        amp_component = amp * (1 / np.transpose(np.array([rdf_r2])).dot(
            np.array([self.common_k])))

        self.amptimespha = amp_component * pha_component

        options1 = {
            'disp': False,
            'maxls': 20,
            'iprint': -1,
            'gtol': 1e-05,
            'eps': 1e-08,
            'maxiter': int(self.edtIterations.text()),
            'ftol': 2.220446049250313e-09,
            'maxcor': 10,
            'maxfun': 15000
        }

        args = (self.common_k, self.common_bft, self.amptimespha, self.dr,
                self.kpow)

        self.rdffnd = RDFinder()
        self.rdffnd.args = args
        self.rdffnd.options1 = options1
        self.rdffnd.varbounds1 = varbounds1
        self.rdffnd.rdf = self.rdf

        self.wthread = QtCore.QThread(self)
        self.rdffnd.moveToThread(self.wthread)
        self.wthread.started.connect(self.rdffnd.calculate)
        self.rdffnd.finished.connect(self.RDFinished)
        self.rdffnd.updateProgress.connect(self.updateProgress)
        self.rdffnd.finished.connect(self.wthread.quit)
        print("Starting optimisation...")
        self.wthread.start()
        print("optimisation started...")

    def updateProgress(self, Xi):
        fresidual = exafsrdf_difeval(Xi, self.common_k, self.common_bft,
                                     self.amptimespha, self.dr, self.kpow)
        print("Step residual: ", fresidual)
        self.edtOptimality.setText("{:e}".format(fresidual))

        self.window = Window_Gauss10(self.common_k, self.kstart, self.kend)
        self.bftw = self.common_bft * self.window
        self.r, self.fr, self.fi = FT(self.common_k, self.bftw, 0, 4, 0.02)
        self.efr = np.sqrt(self.fr * self.fr + self.fi * self.fi)
        self.efi = self.fi * (-1)

        fit_result = exafsrdf(Xi, self.common_k, self.common_bft,
                              self.amptimespha, self.dr,
                              self.kpow) + self.common_bft
        fit_result_w = fit_result * self.window
        res_r, res_fr, res_fi = FT(self.common_k, fit_result_w, 0, 4, 0.02)
        res_efr = np.sqrt(res_fr * res_fr + res_fi * res_fi)
        res_efi = res_fi * (-1)

        self.line1_bft.set_xdata(self.k)
        self.line1_bft.set_ydata(self.bft)
        self.line2_bft.set_xdata(self.common_k)
        self.line2_bft.set_ydata(fit_result)

        self.line1_bftft.set_xdata(self.r)
        self.line1_bftft.set_ydata(self.efr)

        self.line2_bftft.set_xdata(self.r)
        self.line2_bftft.set_ydata(self.efi)

        self.line3_bftft.set_xdata(res_r)
        self.line3_bftft.set_ydata(res_efr)

        self.line4_bftft.set_xdata(res_r)
        self.line4_bftft.set_ydata(res_efi)

        self.line1_rdf.set_xdata(self.rdf_r)
        self.line1_rdf.set_ydata(Xi)
        self.ax_bft.relim()
        self.ax_bft.autoscale()
        self.ax_bftft.relim()
        self.ax_bftft.autoscale()
        self.ax_rdf.relim()
        self.ax_rdf.autoscale()

        self.canv.draw()

    def RDFinished(self, lsq_result):

        print("RDF finnished")

        optim = exafsrdf_difeval(lsq_result.x, self.common_k, self.common_bft,
                                 self.amptimespha, self.dr, self.kpow)

        self.edtFuncEval.setText("{:d}".format(lsq_result.nfev))
        self.edtOptimality.setText("{:e}".format(optim))
        self.edtFitMessage.setText("{:d}".format(lsq_result.nit))

        self.window = Window_Gauss10(self.common_k, self.kstart, self.kend)
        self.bftw = self.common_bft * self.window
        self.r, self.fr, self.fi = FT(self.common_k, self.bftw, 0, 4, 0.02)
        self.efr = np.sqrt(self.fr * self.fr + self.fi * self.fi)
        self.efi = self.fi * (-1)

        self.fit_result = exafsrdf(lsq_result.x, self.common_k,
                                   self.common_bft, self.amptimespha, self.dr,
                                   self.kpow) + self.common_bft
        fit_result_w = self.fit_result * self.window
        res_r, res_fr, res_fi = FT(self.common_k, fit_result_w, 0, 4, 0.02)
        res_efr = np.sqrt(res_fr * res_fr + res_fi * res_fi)
        res_efi = res_fi * (-1)

        self.rdf_exafs = self.fit_result
        self.rdf_exafs_k = self.common_k

        self.line1_bft.set_xdata(self.k)
        self.line1_bft.set_ydata(self.bft)
        self.line2_bft.set_xdata(self.common_k)
        self.line2_bft.set_ydata(self.fit_result)

        self.line1_bftft.set_xdata(self.r)
        self.line1_bftft.set_ydata(self.efr)

        self.line2_bftft.set_xdata(self.r)
        self.line2_bftft.set_ydata(self.efi)

        self.line3_bftft.set_xdata(res_r)
        self.line3_bftft.set_ydata(res_efr)

        self.line4_bftft.set_xdata(res_r)
        self.line4_bftft.set_ydata(res_efi)

        self.line1_rdf.set_xdata(self.rdf_r)
        self.line1_rdf.set_ydata(lsq_result.x)

        self.line2_rdf.set_xdata(self.rdf_r)
        self.line2_rdf.set_ydata(self.rdf)

        self.ax_bft.relim()
        self.ax_bft.autoscale()
        self.ax_bftft.relim()
        self.ax_bftft.autoscale()
        self.ax_rdf.relim()
        self.ax_rdf.autoscale()

        self.canv.draw()

        self.rdf = lsq_result.x
        self.chkFirstFit.setChecked(False)

    def saveRDF(self):
        fn = self.savefiledialog_qtgui()
        if fn == "":
            return
        column_captions = "#r rdf k"
        save_array = []
        save_array.append(self.rdf_r)
        save_array.append(self.rdf)
        np.savetxt(fn + ".rdf",
                   np.transpose(save_array),
                   header=column_captions)

        column_captions = "#k exafs_rdf"
        save_array = []
        save_array.append(self.common_k)
        save_array.append(self.fit_result)
        np.savetxt(fn + ".rdfexafs",
                   np.transpose(save_array),
                   header=column_captions)

        column_captions = "#r ft_real ft_im"
        save_array = []
        save_array.append(self.r)
        save_array.append(self.efr)
        save_array.append(self.efi)
        np.savetxt(fn + ".rdfft",
                   np.transpose(save_array),
                   header=column_captions)

    def apply(self):
        self.params = []
        self.params.append(float(self.edtkmin.text()))
        self.params.append(float(self.edtkmax.text()))
        self.params.append(float(self.edtdk.text()))
        self.params.append(float(self.edtrmin.text()))
        self.params.append(float(self.edtrmax.text()))
        self.params.append(float(self.edtdr.text()))
        self.params.append(float(self.edtIterations.text()))
        self.accept()

    def cancel(self):
        self.close()

    def bftft(self):
        self.window = Window_Gauss10(self.k, self.k[0],
                                     self.k[len(self.k) - 1])
        self.bftw = self.bft * self.window
        self.r, self.fr, self.fi = FT(self.k, self.bftw, 0, 4, 0.02)
        self.efr = np.sqrt(self.fr * self.fr + self.fi * self.fi)
        self.efi = self.fi * (-1)

    def plot(self):

        self.line1_bft.set_xdata(self.k)
        self.line1_bft.set_ydata(self.bft)

        self.line2_bft.set_xdata(self.rdf_exafs_k)
        self.line2_bft.set_ydata(self.rdf_exafs)

        self.line1_bftft.set_xdata(self.r)
        self.line1_bftft.set_ydata(self.efr)

        self.line2_bftft.set_xdata(self.r)
        self.line2_bftft.set_ydata(self.efi)

        self.line1_rdf.set_xdata(self.rdf_r)
        self.line1_rdf.set_ydata(self.rdf)

        print(len(self.rdf_exafs_k))
        print(len(self.rdf_exafs))

        self.ax_bft.relim()
        self.ax_bft.autoscale()
        self.ax_bftft.relim()
        self.ax_bftft.autoscale()
        self.ax_rdf.relim()
        self.ax_rdf.autoscale()

        self.canv.draw()

    def openamp(self):

        dlg = QtGui.QFileDialog()
        dlg.setFileMode(QtGui.QFileDialog.ExistingFiles)
        dlg.setAcceptMode(0)  # open dialog
        dlg.setNameFilters(["All files (*.*)", "Amplitude files (*.amp)"])
        dlg.setDirectory(os.getcwd())
        if dlg.exec_():
            self.fnamp = dlg.selectedFiles()
        else:
            return

        self.fnamp.sort()

        self.Amp.clear()
        self.Amp.addItems(self.fnamp)

    def openpha(self):

        dlg = QtGui.QFileDialog()
        dlg.setFileMode(QtGui.QFileDialog.ExistingFiles)
        dlg.setAcceptMode(0)  # open dialog
        dlg.setNameFilters(["All files (*.*)", "Amplitude files (*.pha)"])
        dlg.setDirectory(os.getcwd())
        if dlg.exec_():
            self.fnpha = dlg.selectedFiles()
        else:
            return
        self.fnpha.sort()

        self.Pha.clear()
        self.Pha.addItems(self.fnpha)

    def openfeff(self):
        dlg = QtGui.QFileDialog()
        dlg.setFileMode(QtGui.QFileDialog.ExistingFiles)
        dlg.setAcceptMode(0)  # open dialog
        dlg.setNameFilters(["All files (*.*)"])
        dlg.setDirectory(os.getcwd())
        if dlg.exec_():
            self.fnfeff = dlg.selectedFiles()
        else:
            return
        self.fnfeff.sort()

        #Extract amplitude and phase from feff files and save to disk

        for i in range(len(self.fnfeff)):
            state = 0
            data = []
            f = open(self.fnfeff[i])
            for line in f:
                cols = line.split()
                if cols[0] == '-----------------------------------------------------------------------':
                    state = 1
                    continue
                if cols[0] == 'k':
                    state = 2
                    continue
                if state == 1:
                    r = float(cols[2])
                    state = 0
                    continue
                if state == 2:
                    data.append(cols)

            new_data_amp = []
            new_data_pha = []
            for j in range(len(data)):
                k = float(data[j][0])
                pha = float(data[j][1]) + float(data[j][3])
                amp = float(data[j][2]) * np.exp(
                    -2 * r / float(data[j][5])) * float(data[j][4])
                new_data_amp.append([k, amp])
                new_data_pha.append([k, pha])

#            print(new_data_amp)
#            print(new_data_pha)
            np.savetxt(self.fnfeff[i] + '.amp', new_data_amp)
            np.savetxt(self.fnfeff[i] + '.pha', new_data_pha)

            self.Amp.clear()
            self.Amp.addItem(self.fnfeff[i] + '.amp')

            self.Pha.clear()
            self.Pha.addItem(self.fnfeff[i] + '.pha')

    def addshell(self):
        self.tabs.append(QtGui.QFrame())
        caption = "Shell" + str(self.shellnr + 1)
        self.tabShells.addTab(self.tabs[self.shellnr], caption)

        lblN = QtGui.QLabel("N")
        lblR = QtGui.QLabel("R")
        lblSigma = QtGui.QLabel("Sigma")
        lblC3 = QtGui.QLabel("C3")
        lblC4 = QtGui.QLabel("C4")
        lblC5 = QtGui.QLabel("C5")
        lblC6 = QtGui.QLabel("C6")
        lblE0 = QtGui.QLabel("E0")

        lblAmp = QtGui.QLabel("Amplitude")
        lblPha = QtGui.QLabel("Phase")

        self.ltShell.append(QtGui.QGridLayout())
        self.shellN.append([
            QtGui.QLineEdit("4"),
            QtGui.QLineEdit("0"),
            QtGui.QLineEdit("8"),
            QtGui.QLineEdit("0.00001"),
            QtGui.QCheckBox()
        ])
        self.shellR.append([
            QtGui.QLineEdit("2"),
            QtGui.QLineEdit("0"),
            QtGui.QLineEdit("4"),
            QtGui.QLineEdit("0.0000001"),
            QtGui.QCheckBox()
        ])
        self.shellSigma.append([
            QtGui.QLineEdit("0"),
            QtGui.QLineEdit("0"),
            QtGui.QLineEdit("1"),
            QtGui.QLineEdit("0.00000001"),
            QtGui.QCheckBox()
        ])
        self.shellC3.append([
            QtGui.QLineEdit("0"),
            QtGui.QLineEdit("0"),
            QtGui.QLineEdit("0.0001"),
            QtGui.QLineEdit("0.0001"),
            QtGui.QCheckBox()
        ])
        self.shellC4.append([
            QtGui.QLineEdit("0"),
            QtGui.QLineEdit("0"),
            QtGui.QLineEdit("0.0001"),
            QtGui.QLineEdit("0.0001"),
            QtGui.QCheckBox()
        ])
        self.shellC5.append([
            QtGui.QLineEdit("0"),
            QtGui.QLineEdit("0"),
            QtGui.QLineEdit("0.0001"),
            QtGui.QLineEdit("0.0001"),
            QtGui.QCheckBox()
        ])
        self.shellC6.append([
            QtGui.QLineEdit("0"),
            QtGui.QLineEdit("0"),
            QtGui.QLineEdit("0.0001"),
            QtGui.QLineEdit("0.0001"),
            QtGui.QCheckBox()
        ])
        self.shellE0.append([
            QtGui.QLineEdit("0"),
            QtGui.QLineEdit("0"),
            QtGui.QLineEdit("0"),
            QtGui.QLineEdit("0.0001"),
            QtGui.QCheckBox()
        ])
        self.shellAmp.append(QtGui.QComboBox())
        self.shellPha.append(QtGui.QComboBox())

        self.shellAmp[len(self.shellAmp) -
                      1].addItem("E:/work/development/xaslib/fit/amp0001.dat")
        self.shellPha[len(self.shellPha) -
                      1].addItem("E:/work/development/xaslib/fit/pha0001.dat")

        self.ltShell[self.shellnr].addWidget(lblN, 0, 0)
        self.ltShell[self.shellnr].addWidget(lblR, 1, 0)
        self.ltShell[self.shellnr].addWidget(lblSigma, 2, 0)
        self.ltShell[self.shellnr].addWidget(lblC3, 3, 0)
        self.ltShell[self.shellnr].addWidget(lblC4, 4, 0)
        self.ltShell[self.shellnr].addWidget(lblC5, 5, 0)
        self.ltShell[self.shellnr].addWidget(lblC6, 6, 0)
        self.ltShell[self.shellnr].addWidget(lblE0, 7, 0)
        self.ltShell[self.shellnr].addWidget(lblAmp, 8, 0)
        self.ltShell[self.shellnr].addWidget(lblPha, 9, 0)

        for i in range(5):
            self.ltShell[self.shellnr].addWidget(self.shellN[self.shellnr][i],
                                                 0, 2 * i + 1)
            self.ltShell[self.shellnr].addWidget(self.shellR[self.shellnr][i],
                                                 1, 2 * i + 1)
            self.ltShell[self.shellnr].addWidget(
                self.shellSigma[self.shellnr][i], 2, 2 * i + 1)
            self.ltShell[self.shellnr].addWidget(self.shellC3[self.shellnr][i],
                                                 3, 2 * i + 1)
            self.ltShell[self.shellnr].addWidget(self.shellC4[self.shellnr][i],
                                                 4, 2 * i + 1)
            self.ltShell[self.shellnr].addWidget(self.shellC5[self.shellnr][i],
                                                 5, 2 * i + 1)
            self.ltShell[self.shellnr].addWidget(self.shellC6[self.shellnr][i],
                                                 6, 2 * i + 1)
            self.ltShell[self.shellnr].addWidget(self.shellE0[self.shellnr][i],
                                                 7, 2 * i + 1)
        self.ltShell[self.shellnr].addWidget(self.shellAmp[self.shellnr], 8, 1,
                                             1, 8)
        self.ltShell[self.shellnr].addWidget(self.shellPha[self.shellnr], 9, 1,
                                             1, 8)

        for j in range(7):
            self.ltShell[self.shellnr].addWidget(QtGui.QLabel("Min. limit"), j,
                                                 2)
            self.ltShell[self.shellnr].addWidget(QtGui.QLabel("Max. limit"), j,
                                                 4)
            self.ltShell[self.shellnr].addWidget(QtGui.QLabel("Accuracy"), j,
                                                 6)

        self.tabs[self.shellnr].setLayout(self.ltShell[self.shellnr])

        self.shellnr = self.shellnr + 1

    def resetFit(self):
        self.chkFirstFit.setChecked(True)

    def savefiledialog_qtgui(self):
        dlg = QtGui.QFileDialog()
        dlg.setFileMode(QtGui.QFileDialog.AnyFile)
        dlg.setAcceptMode(1)  # save dialog
        dlg.setNameFilters(["All files (*.*)"])
        #        dlg.setDirectory(self.currentdir)
        if dlg.exec_():
            flist = dlg.selectedFiles()
            return flist[0]
        else:
            return ""
Esempio n. 46
0
    def initUI(self):

        self.fig = plt.figure(5, figsize=(18, 6))
        self.ax_bft = plt.subplot2grid((1, 3), (0, 0))
        self.ax_bftft = plt.subplot2grid((1, 3), (0, 1))
        self.ax_rdf = plt.subplot2grid((1, 3), (0, 2))

        self.ax_bft.set_xlabel('Wavevector k, $\AA^{-1}$')
        self.ax_bft.set_ylabel('EXAFS, $\AA^{-2}$')
        self.ax_bftft.set_xlabel('Distance R, $\AA$')
        self.ax_bftft.set_ylabel('Fourier transform, $\AA^{-3}$')
        self.ax_rdf.set_xlabel('Distance R, $\AA$')
        self.ax_rdf.set_ylabel('RDF G(R)')

        self.line1_bft, = self.ax_bft.plot([], [], label='BFT')
        self.line2_bft, = self.ax_bft.plot([], [], label='fit')
        self.line1_bft.set_color('b')
        self.line2_bft.set_color('g')
        self.ax_bft.legend(handles=[self.line1_bft, self.line2_bft])

        self.line1_bftft, self.line2_bftft = self.ax_bftft.plot([], [], [], [])
        self.line1_bftft.set_color('b')
        self.line2_bftft.set_color('b')
        self.line2_bftft.set_linestyle('dotted')

        self.line3_bftft, self.line4_bftft = self.ax_bftft.plot([], [], [], [])
        self.line3_bftft.set_color('g')
        self.line4_bftft.set_color('g')
        self.line4_bftft.set_linestyle('dotted')

        self.line1_rdf, = self.ax_rdf.plot([], [], marker='o')
        self.line2_rdf, = self.ax_rdf.plot([], [])

        self.fig.tight_layout()

        self.canv = FigureCanvas(self.fig)
        self.tbar = NavigationToolbar(self.canv, self)

        self.rdf_r = np.arange(0.8, 2.5, 0.01)

        self.rdf = np.zeros(len(self.rdf_r))

        #        self.lblNrShells = QtGui.QLabel("Number of shells")
        #        self.edtNrShells = QtGui.QLineEdit("1")

        self.lblkmin = QtGui.QLabel("K min")
        self.lblkmax = QtGui.QLabel("K max")
        self.lbldk = QtGui.QLabel("dK")
        self.lblrmin = QtGui.QLabel("Rmin")
        self.lblrmax = QtGui.QLabel("Rmax")
        self.lbldr = QtGui.QLabel("dR")
        self.edtkmin = QtGui.QLineEdit("0.5")
        self.edtkmax = QtGui.QLineEdit("15")
        self.edtdk = QtGui.QLineEdit("0.05")
        self.edtrmin = QtGui.QLineEdit("0.5")
        self.edtrmax = QtGui.QLineEdit("2.8")
        self.edtdr = QtGui.QLineEdit("0.01")

        self.edtrmin.editingFinished.connect(self.resetFit)
        self.edtrmax.editingFinished.connect(self.resetFit)
        self.edtdr.editingFinished.connect(self.resetFit)

        #        self.lblCentralDist = QtGui.QLabel("Central distance")
        #        self.edtCentralDist = QtGui.QLineEdit("1.8")
        #        self.lblWidth = QtGui.QLabel("Width")
        #        self.edtWidth = QtGui.QLineEdit("0.001")
        #        self.lblAmplitude = QtGui.QLabel("Amplitude")
        #        self.edtAmplitude = QtGui.QLineEdit("50")

        self.lblIterations = QtGui.QLabel("Max. number of iterations")
        self.edtIterations = QtGui.QLineEdit("20")
        self.chkFirstFit = QtGui.QCheckBox(
            "Start new fit (checked) / continue fit (unchecked)")
        self.chkFirstFit.setChecked(True)

        self.Amp = QtGui.QComboBox()
        self.Pha = QtGui.QComboBox()

        lblAmp = QtGui.QLabel("Amplitude")
        lblPha = QtGui.QLabel("Phase")

        self.Amp.addItem("")
        self.Amp.addItem("E:/work/development/xaslib/fit/amp0001.dat")
        self.Pha.addItem("")
        self.Pha.addItem("E:/work/development/xaslib/fit/pha0001.dat")

        self.lblFuncEval = QtGui.QLabel("Number of function evaluations done")
        self.edtFuncEval = QtGui.QLineEdit()

        self.lblFitMessage = QtGui.QLabel("Iterations done")
        self.edtFitMessage = QtGui.QLineEdit()

        self.lblOptimality = QtGui.QLabel("Residual")
        self.edtOptimality = QtGui.QLineEdit()

        lfit = QtGui.QGridLayout()
        lfit.addWidget(self.lblFitMessage, 0, 0)
        lfit.addWidget(self.edtFitMessage, 0, 1)
        lfit.addWidget(self.lblFuncEval, 1, 0)
        lfit.addWidget(self.edtFuncEval, 1, 1)
        lfit.addWidget(self.lblOptimality, 2, 0)
        lfit.addWidget(self.edtOptimality, 2, 1)

        self.btnFit = QtGui.QPushButton('Fit')
        self.btnFit.clicked.connect(self.Fit_rdf)

        self.btnSaveRdf = QtGui.QPushButton('Save RDF')
        self.btnSaveRdf.clicked.connect(self.saveRDF)

        self.btnApply = QtGui.QPushButton('Apply')
        self.btnApply.clicked.connect(self.apply)

        self.btnCancel = QtGui.QPushButton('Cancel')
        self.btnCancel.clicked.connect(self.cancel)

        self.btnOpenAmp = QtGui.QPushButton('Open amplitude file(s) ...')
        self.btnOpenAmp.clicked.connect(self.openamp)
        self.btnOpenPha = QtGui.QPushButton('Open phase file(s) ...')
        self.btnOpenPha.clicked.connect(self.openpha)
        self.btnOpenFeff = QtGui.QPushButton('Open feff file(s) ...')
        self.btnOpenFeff.clicked.connect(self.openfeff)

        #        self.textEdit = QtGui.QTextEdit(self)

        #        lb.addWidget(self.textEdit, 1, 0)

        lfig = QtGui.QGridLayout()
        lfig.addWidget(self.tbar, 0, 0, 1, 2)
        lfig.addWidget(self.canv, 1, 0, 1, 2)

        lfig.addLayout(lfit, 2, 0)

        lfig.addWidget(self.btnFit, 3, 0)
        lfig.addWidget(self.btnSaveRdf, 4, 0)
        lfig.addWidget(self.btnApply, 5, 0)
        lfig.addWidget(self.btnCancel, 6, 0)

        lp = QtGui.QGridLayout()
        lp.addWidget(self.lblkmin, 0, 0)
        lp.addWidget(self.edtkmin, 0, 1)
        lp.addWidget(self.lblkmax, 0, 2)
        lp.addWidget(self.edtkmax, 0, 3)
        lp.addWidget(self.lbldk, 0, 4)
        lp.addWidget(self.edtdk, 0, 5)

        lp.addWidget(self.lblrmin, 1, 0)
        lp.addWidget(self.edtrmin, 1, 1)
        lp.addWidget(self.lblrmax, 1, 2)
        lp.addWidget(self.edtrmax, 1, 3)
        lp.addWidget(self.lbldr, 1, 4)
        lp.addWidget(self.edtdr, 1, 5)

        #        lfig.addWidget(self.lblAmplitude, 2,1)
        #        lfig.addWidget(self.edtAmplitude, 2,2)
        #        lfig.addWidget(self.lblCentralDist, 2,3)
        #        lfig.addWidget(self.edtCentralDist, 2,4)
        #        lfig.addWidget(self.lblWidth, 2,5)
        #        lfig.addWidget(self.edtWidth, 2,6)

        lp.addWidget(self.lblIterations, 2, 0, 1, 3)
        lp.addWidget(self.edtIterations, 2, 3, 1, 3)
        lp.addWidget(self.chkFirstFit, 3, 0, 1, 6)

        lp.addWidget(lblAmp, 4, 0)
        lp.addWidget(self.Amp, 4, 1, 1, 4)
        lp.addWidget(lblPha, 5, 0)
        lp.addWidget(self.Pha, 5, 1, 1, 4)
        lp.addWidget(self.btnOpenAmp, 4, 5)
        lp.addWidget(self.btnOpenPha, 5, 5)
        lp.addWidget(self.btnOpenFeff, 6, 0)

        lfig.addLayout(lp, 2, 1, 5, 1)

        self.setLayout(lfig)

        self.canv.draw()
class MyTableWidget(QWidget):
    def __init__(self, parent):
        super(QWidget, self).__init__(parent)
        self.layout = QVBoxLayout(self)

        # The dataframe
        self.df = pd.DataFrame()
        self.gs = pd.DataFrame()
        self.gs1 = pd.DataFrame()
        self.gs2 = pd.DataFrame()

        # Initialize the labels for the first tab

        self.productLabel = QLabel("Product", self)
        self.countryLabel = QLabel("Country", self)
        self.stateLabel = QLabel("State", self)
        self.cityLabel = QLabel("City", self)

        # Initialise the textbox for all the labels along with the tooltips

        self.productTextBox = QLineEdit(self)

        self.productTextBox.setToolTip("Enter the product here")
        self.countryTextBox = QComboBox(self)
        self.countryTextBox.setToolTip("Enter the country here")

        self.stateTextBox = QComboBox(self)
        self.stateTextBox.setToolTip("Enter the state here")

        self.cityTextBox = QComboBox(self)
        self.cityTextBox.setToolTip("Enter the city here")

        # Canvas and Toolbar
        # a figure instance to plot on
        self.figure = Figure()
        self.figure3 = Figure()
        self.figure4 = Figure()

        # this is the Canvas Widget that displays the `figure`
        # it takes the `figure` instance as a parameter to __init__
        self.canvas = FigureCanvas(self.figure)
        self.canvas3 = FigureCanvas(self.figure3)
        self.canvas4 = FigureCanvas(self.figure4)

        self.submitButton = QPushButton("Submit")
        self.submitButton.setToolTip("To submit and get results")
        self.submitButton.resize(self.submitButton.sizeHint())
        self.submitButton.clicked.connect(self.on_click)
        self.show()
        #print(self.on_click)

        # Buttons to be added to the first tab
        self.clearAllButton = QPushButton("Clear All")
        self.clearAllButton.resize(self.clearAllButton.sizeHint())
        self.clearAllButton.setToolTip("To clear all the fields")
        self.clearAllButton.clicked.connect(self.clear_on_click)

        # Initialize tab screen
        self.tabs = QTabWidget()
        self.tab1 = QWidget()
        self.tab2 = QWidget()
        self.tab3 = QWidget()
        self.tab4 = QWidget()
        self.tabs.resize(480, 320)

        # Add tabs
        self.tabs.addTab(self.tab1, "The Input Tab")
        self.tabs.addTab(self.tab2, "The Graphs")
        self.tabs.addTab(self.tab3, "The Data")
        self.tabs.addTab(self.tab4, "The Recommendation")

        # Create first tab
        self.tab1.layout = QVBoxLayout(self)

        self.tab1.layout.addWidget(self.productLabel)
        self.tab1.layout.addWidget(self.productTextBox)
        self.tab1.layout.addWidget(self.submitButton)
        self.tab1.layout.addWidget(self.clearAllButton)
        self.tab1.layout.addWidget(self.countryLabel)
        self.tab1.layout.addWidget(self.countryTextBox)
        self.tab1.layout.addWidget(self.stateLabel)
        self.tab1.layout.addWidget(self.stateTextBox)
        self.tab1.layout.addWidget(self.cityLabel)
        self.tab1.layout.addWidget(self.cityTextBox)

        self.tab1.setLayout(self.tab1.layout)

        # Add tabs to widget
        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)

        # Canvas and Toolbar
        # a figure instance to plot on
        self.figure = Figure()

        # this is the Canvas Widget that displays the `figure`
        # it takes the `figure` instance as a parameter to __init__
        self.canvas = FigureCanvas(self.figure)

        # this is the Navigation widget
        # it takes the Canvas widget and a parent
        self.toolbar = NavigationToolbar(self.canvas, self)

        # set the layout
        tab2layout = QVBoxLayout()
        tab2layout.addWidget(self.toolbar)
        tab2layout.addWidget(self.canvas)

        self.tab2.setLayout(tab2layout)

        # Tab 3 The Data

        self.tab3Table = QFormLayout()

        self.tableWidget = QTableWidget()
        self.tab3Table.addWidget(self.tableWidget)

        self.tab3.setLayout(self.tab3Table)

        self.tab3Table.addRow(self.tableWidget)

        # Buttons to be added to the first tab
        self.exportCSVButton = QPushButton("Export Data to CSV")
        self.exportCSVButton.resize(self.clearAllButton.sizeHint())
        self.exportCSVButton.setToolTip("To export the above data to a CSV")
        self.exportCSVButton.clicked.connect(self.export_csv_connect)

        self.tab3Table.addRow(self.exportCSVButton)
        self.tab3.setLayout(self.tab3Table)

        #self.tab3.layout.addWidget(self.exportCSVButton)

        # Tab 4 The Recommendation

        self.tab4Form = QFormLayout()
        self.recommendationText = QTextEdit()
        self.recommendationText.setMinimumSize(480, 320)
        self.recommendationText.setToolTip(
            "This tab shows the recommendation ")
        self.tab4Form.addRow(self.recommendationText)

        self.tab4.setLayout(self.tab4Form)

        # call the function to get the recommendation and then load it into the textbox

    def onActivated(self, text):

        print(text + ' Is selected')
        #print(ScorceCode.forCountry(text,self.productName))
        CountrySelected = text
        print('breakpoint')
        ls1 = ScorceCode.forCountry(CountrySelected, self.productName)
        #ls1.to_csv('C:/Users/lakshay/Desktop/udemy/PRI_Exported_CSV_files/finlistState.csv')
        #print(ls1)
        finlistState = ls1.index.tolist()
        self.gs1 = ls1

        #print(finlistState)
        #self.textEdit3.setText(ls1.to_string())

        tableFor = "country"

        self.createTable(tableFor)
        print('breakpoint 1')

        self.stateTextBox.clear()
        self.cityTextBox.clear()
        self.stateTextBox.addItems(finlistState)

        print(self.stateTextBox.activated[str].connect(self.onActivated1))

        self.plot(ls1)

# have to pass the state value to this method !!!!!!!!!!!!!!!!!!

    def onActivated1(self, StateSelected):

        try:
            self.cityTextBox.clear()
            print("state selected is ")
            print(StateSelected)
            print('value in state box :')
            print(self.stateTextBox.currentText())
            print(self.countryTextBox.currentText())
            StateSelected = self.stateTextBox.currentText()
            CountrySelected = self.countryTextBox.currentText()

            ls2 = ScorceCode.forState(CountrySelected, StateSelected,
                                      self.productName)
            #ls2.to_csv('C:/Users/lakshay/Desktop/udemy/PRI_Exported_CSV_files/finlistCity.csv')
            self.gs2 = ls2
            finlistCity = ls2.index.tolist()

            #self.textEdit3.setText(ls2.to_string())
            tableFor = "state"
            self.createTable(tableFor)

            print('list of city')
            #print(finlistCity)

            self.cityTextBox.clear()
            self.cityTextBox.addItems(finlistCity)

            self.cityTextBox.activated[str].connect(self.onActivated2)
            self.plot(ls2)

        except:
            print(
                'An error occured while retrieving the cities of the states.')


# have to pass the state value and city to this method !!!!!!!!!!

    def onActivated2(self, CitySelected):
        try:
            StateSelected = self.stateTextBox.currentText()
            CountrySelected = self.countryTextBox.currentText()
            print('final country selected')
            print(CountrySelected)
            print('final state selected')
            print(StateSelected)
            print("final city selected is ")
            print(CitySelected)
            print('Number of total internet users in ' + CitySelected + ' is:')
            print(ScorceCode.forTotalUsers(CountrySelected, CitySelected))

            ls2 = ScorceCode.forState(CountrySelected, StateSelected,
                                      self.productName)

            UserPercentage = int(ls2.loc[CitySelected, :])
            print(UserPercentage)

            totalUsers = ScorceCode.forTotalUsers(CountrySelected,
                                                  CitySelected)
            print(totalUsers)

            finalUsers = int((totalUsers * UserPercentage) / 100)

            totalPopulation = ScorceCode.forTotalPop(CitySelected)
            totalPenitration = ScorceCode.forTotalPenitration(CountrySelected)

            ratio = int((finalUsers / totalPopulation) * 100)

            self.recommendationText.setText(
                "There are total of " + str(finalUsers) +
                " people searching for the keyword out of " +
                str(totalPopulation) + " people in the city of " +
                CitySelected + " which gives us the ratio of " + str(ratio) +
                "% of users searching for this keyword and the percentage of internet penetration is "
                + str(totalPenitration) + "%")
            print('end')
        except:
            print(
                'An error occured while retrieving the population data of the city: '
                + CitySelected)
            self.recommendationText.setText(
                'No recommendation found due to lack of precise data for city: '
                + CitySelected)

    def createTable(self, tableFor):
        # Create table

        # print("Table data " + self.tableDf)PROGRAM RUNNING?????????

        # find the table length
        if (tableFor == "world"):
            self.lsTest = self.gs
        if (tableFor == "country"):
            self.lsTest = self.gs1

        if (tableFor == "state"):
            self.lsTest = self.gs2

        # print(self.lsTest)
        rows = self.lsTest.count()
        columns = 2
        # rows=10
        #print(rows)

        #print(columns)

        # set the rows and columns of the table
        self.tableWidget.setRowCount(rows)
        self.tableWidget.setColumnCount(columns)

        i = 0

        for index, value in self.lsTest.iterrows():
            #print(value[0])
            if i < int(rows):
                self.tableWidget.setItem(i, 0, QTableWidgetItem(index))
                self.tableWidget.setItem(i, 1, QTableWidgetItem(str(value[0])))
                i = i + 1
            ## self.tableWidget.setItem(index, 2, QTableWidgetItem(row['']))

        # for x in rows:
        # for y in columns:

        # if(y==0)
        # self.tableWidget.setItem(x, y, QTableWidgetItem(self.tableDf[x][y]))

        # self.tableWidget.setItem(0, 1, QTableWidgetItem("Cell (1,2)"))

    def show_model(self):
        font = QtGui.QFont()
        font.setFamily('Lucida')
        font.setFixedPitch(True)
        font.setPointSize(10)
        self.textEdit3.setCurrentFont(font)

        # selmodel = self.creSelectModel[str(self.comboBox.currentText())]
        self.textEdit3.setText("1234566465464")

    def export_csv_connect(self):
        print('Export data to CSV operation: ')

        self.gs.to_csv(
            'C:/Users/lakshay/Desktop/udemy/PRI_Exported_CSV_files/finlistWorld.csv'
        )

        self.gs1.to_csv(
            'C:/Users/lakshay/Desktop/udemy/PRI_Exported_CSV_files/finlistState.csv'
        )

        self.gs2.to_csv(
            'C:/Users/lakshay/Desktop/udemy/PRI_Exported_CSV_files/finlistCity.csv'
        )

        QMessageBox.about(self, "Export to CSV", "Files Exported Successfully")

    def on_click(self):
        print("\n")
        self.stateTextBox.clear()
        self.cityTextBox.clear()
        print(self.productTextBox.text())
        self.productName = self.productTextBox.text()

        self.countryTextBox.activated[str].connect(self.onActivated)

        ls = ScorceCode.forWorld(self.productName)
        #print(ls)
        #ls.to_csv('C:/Users/lakshay/Desktop/udemy/PRI_Exported_CSV_files/finlistWorld.csv')
        self.gs = ls
        finlist = ls.index.tolist()
        #print(finlist)
        print('someht')
        self.countryTextBox.clear()
        self.countryTextBox.addItems(finlist)
        self.countryTextBox.activated[str].connect(self.onActivated)
        #makeitastring = ''.join(map(str, finlist))

        #print('the string is')
        #print(makeitastring)

        tableFor = "world"
        #self.textEdit3.setText(ls.to_string())
        self.createTable(tableFor)

        self.plot(ls)

    def clear_on_click(self):
        self.countryTextBox.clear()
        self.stateTextBox.clear()
        self.cityTextBox.clear()
        self.productTextBox.clear()

        print('all clear')

    def plot(self, data):

        # hit only if we have values on all the four components
        if (self.productTextBox.text()):

            print("Inside the plot method")
            # Call the api #TODO

            #statisticsPerCountry = SourceCode.forCountry(self.selectedCountry,self.productTextBox.text())
            #statisticsPerState
            #statisticsPerUsers

            print('plotBreak')

            # create an axis
            ax = self.figure.add_subplot(111)

            # discards the old graph
            ax.clear()

            # plot data
            ax.plot(data, '*-')

            # refresh canvas
            self.canvas.draw()

        else:
            QMessageBox.about(self, "Inputs", "Please check your inputs")
    def __init__(self, parent):
        super(QWidget, self).__init__(parent)
        self.layout = QVBoxLayout(self)

        # The dataframe
        self.df = pd.DataFrame()
        self.gs = pd.DataFrame()
        self.gs1 = pd.DataFrame()
        self.gs2 = pd.DataFrame()

        # Initialize the labels for the first tab

        self.productLabel = QLabel("Product", self)
        self.countryLabel = QLabel("Country", self)
        self.stateLabel = QLabel("State", self)
        self.cityLabel = QLabel("City", self)

        # Initialise the textbox for all the labels along with the tooltips

        self.productTextBox = QLineEdit(self)

        self.productTextBox.setToolTip("Enter the product here")
        self.countryTextBox = QComboBox(self)
        self.countryTextBox.setToolTip("Enter the country here")

        self.stateTextBox = QComboBox(self)
        self.stateTextBox.setToolTip("Enter the state here")

        self.cityTextBox = QComboBox(self)
        self.cityTextBox.setToolTip("Enter the city here")

        # Canvas and Toolbar
        # a figure instance to plot on
        self.figure = Figure()
        self.figure3 = Figure()
        self.figure4 = Figure()

        # this is the Canvas Widget that displays the `figure`
        # it takes the `figure` instance as a parameter to __init__
        self.canvas = FigureCanvas(self.figure)
        self.canvas3 = FigureCanvas(self.figure3)
        self.canvas4 = FigureCanvas(self.figure4)

        self.submitButton = QPushButton("Submit")
        self.submitButton.setToolTip("To submit and get results")
        self.submitButton.resize(self.submitButton.sizeHint())
        self.submitButton.clicked.connect(self.on_click)
        self.show()
        #print(self.on_click)

        # Buttons to be added to the first tab
        self.clearAllButton = QPushButton("Clear All")
        self.clearAllButton.resize(self.clearAllButton.sizeHint())
        self.clearAllButton.setToolTip("To clear all the fields")
        self.clearAllButton.clicked.connect(self.clear_on_click)

        # Initialize tab screen
        self.tabs = QTabWidget()
        self.tab1 = QWidget()
        self.tab2 = QWidget()
        self.tab3 = QWidget()
        self.tab4 = QWidget()
        self.tabs.resize(480, 320)

        # Add tabs
        self.tabs.addTab(self.tab1, "The Input Tab")
        self.tabs.addTab(self.tab2, "The Graphs")
        self.tabs.addTab(self.tab3, "The Data")
        self.tabs.addTab(self.tab4, "The Recommendation")

        # Create first tab
        self.tab1.layout = QVBoxLayout(self)

        self.tab1.layout.addWidget(self.productLabel)
        self.tab1.layout.addWidget(self.productTextBox)
        self.tab1.layout.addWidget(self.submitButton)
        self.tab1.layout.addWidget(self.clearAllButton)
        self.tab1.layout.addWidget(self.countryLabel)
        self.tab1.layout.addWidget(self.countryTextBox)
        self.tab1.layout.addWidget(self.stateLabel)
        self.tab1.layout.addWidget(self.stateTextBox)
        self.tab1.layout.addWidget(self.cityLabel)
        self.tab1.layout.addWidget(self.cityTextBox)

        self.tab1.setLayout(self.tab1.layout)

        # Add tabs to widget
        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)

        # Canvas and Toolbar
        # a figure instance to plot on
        self.figure = Figure()

        # this is the Canvas Widget that displays the `figure`
        # it takes the `figure` instance as a parameter to __init__
        self.canvas = FigureCanvas(self.figure)

        # this is the Navigation widget
        # it takes the Canvas widget and a parent
        self.toolbar = NavigationToolbar(self.canvas, self)

        # set the layout
        tab2layout = QVBoxLayout()
        tab2layout.addWidget(self.toolbar)
        tab2layout.addWidget(self.canvas)

        self.tab2.setLayout(tab2layout)

        # Tab 3 The Data

        self.tab3Table = QFormLayout()

        self.tableWidget = QTableWidget()
        self.tab3Table.addWidget(self.tableWidget)

        self.tab3.setLayout(self.tab3Table)

        self.tab3Table.addRow(self.tableWidget)

        # Buttons to be added to the first tab
        self.exportCSVButton = QPushButton("Export Data to CSV")
        self.exportCSVButton.resize(self.clearAllButton.sizeHint())
        self.exportCSVButton.setToolTip("To export the above data to a CSV")
        self.exportCSVButton.clicked.connect(self.export_csv_connect)

        self.tab3Table.addRow(self.exportCSVButton)
        self.tab3.setLayout(self.tab3Table)

        #self.tab3.layout.addWidget(self.exportCSVButton)

        # Tab 4 The Recommendation

        self.tab4Form = QFormLayout()
        self.recommendationText = QTextEdit()
        self.recommendationText.setMinimumSize(480, 320)
        self.recommendationText.setToolTip(
            "This tab shows the recommendation ")
        self.tab4Form.addRow(self.recommendationText)

        self.tab4.setLayout(self.tab4Form)
Esempio n. 49
0
class AppForm(QtGui.QMainWindow):
    def __init__(self,
                 parent=None,
                 specterCenter=0,
                 columnNumber=0,
                 windowLength=0):
        QtGui.QMainWindow.__init__(self, parent)
        #self.x, self.y = self.get_data()
        self.create_main_frame()
        self.specter = []
        self.currentSpecter = 0
        self.abelData = []
        self.specterCenter = specterCenter
        self.columnNumber = columnNumber
        self.windowLength = windowLength

        exitAction = QtGui.QAction(QtGui.QIcon('icons/svg/power.svg'), '&Exit',
                                   self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(QtGui.qApp.quit)

        openAction = QtGui.QAction(QtGui.QIcon('icons/svg/folder-open.svg'),
                                   '&Open', self)
        openAction.setShortcut('Ctrl+O')
        openAction.setStatusTip('Open file sequence')
        openAction.triggered.connect(self.loadSpecterFromFiles)

        #plotAction = QtGui.QAction(QtGui.QIcon('icons/svg/chart-line-outline.svg'), '&Plot', self)
        #plotAction.setShortcut('Ctrl+P')
        #plotAction.setStatusTip('Plot')
        #plotAction.triggered.connect(self.on_draw)

        nextSpecterAction = QtGui.QAction(
            QtGui.QIcon('icons/svg/chevron-right-outline.svg'),
            '&Next specter', self)
        nextSpecterAction.setStatusTip('Next specter')
        nextSpecterAction.triggered.connect(self.nextSpecter)

        self.currentSpecterInput = QtGui.QLabel()
        #self.currentSpecterInput.setMaxLength(150)
        #self.currentSpecterInput.setValidator(QtGui.QIntValidator())
        self.currentSpecterInput.setFixedWidth(500)

        self.totalSpecterLabel = QtGui.QLabel()
        self.totalSpecterLabel.setFixedWidth(40)

        prevSpecterAction = QtGui.QAction(
            QtGui.QIcon('icons/svg/chevron-left-outline.svg'), '&Next specter',
            self)
        prevSpecterAction.setStatusTip('Prev specter')
        prevSpecterAction.triggered.connect(self.prevSpecter)

        self.statusBar().showMessage('Ready')

        self.setWindowTitle('Abel transform and temperature calculation')

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(openAction)
        #fileMenu.addAction(plotAction)
        fileMenu.addAction(exitAction)

        self.toolbar = self.addToolBar('Main')
        self.toolbar.addAction(openAction)
        self.toolbar.addAction(prevSpecterAction)
        self.toolbar.addAction(nextSpecterAction)
        self.toolbar.addWidget(self.currentSpecterInput)
        self.toolbar.addWidget(self.totalSpecterLabel)

        #self.toolbar.addAction(plotAction)
        #self.toolbar.addAction(exitAction)

    def create_main_frame(self):
        self.main_frame = QtGui.QWidget()
        self.fig = Figure((10.0, 8.0), dpi=72)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.main_frame)
        #self.canvas.setFocusPolicy(Qt.StrongFocus)
        self.canvas.setFocus()
        self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)
        self.canvas.mpl_connect('key_press_event', self.on_key_press)
        self.canvas.mpl_connect('motion_notify_event', self.mouse_moved)
        self.table = QtGui.QTableWidget()
        self.table.setColumnCount(6)
        self.table.setHorizontalHeaderLabels(
            ['L1', "L2", "LNIST", "Aki", "Ek", "g"])
        header = self.table.horizontalHeader()
        header.setResizeMode(QtGui.QHeaderView.Stretch)
        self.table.itemChanged.connect(self.setLine)
        self.buttonAddLine = QtGui.QPushButton("Add a line")
        self.buttonAddLine.clicked.connect(self.addLine)
        self.buttonComputeTemp = QtGui.QPushButton("Compute temperature")
        self.buttonComputeTemp.clicked.connect(self.computeTemp)
        self.lines = []

        vbox = QtGui.QGridLayout()
        vbox.addWidget(self.table, 0, 0, 1, 1)
        vbox.addWidget(self.buttonAddLine, 1, 0, 1, 1)
        vbox.addWidget(self.buttonComputeTemp, 2, 0, 1, 1)
        vbox.addWidget(self.canvas, 0, 1, 1, 4)  # the matplotlib canvas
        vbox.addWidget(self.mpl_toolbar, 1, 1, 1, 4)
        vbox.setColumnStretch(1, 5)

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

    def on_draw(self):
        self.fig.clear()
        gs = gridspec.GridSpec(2,
                               2,
                               width_ratios=[5, 1],
                               height_ratios=[4, 1],
                               wspace=0.12,
                               hspace=0.12,
                               left=0.05,
                               bottom=0.05,
                               right=0.95,
                               top=0.95)
        self.axes1 = self.fig.add_subplot(gs[0])
        self.axes2 = self.fig.add_subplot(gs[1])
        self.axes3 = self.fig.add_subplot(gs[2])
        self.drawSpecter()
        self.drawPlots()

    def drawSpecter(self):
        abelData = self.abelData[self.currentSpecter]
        self.axes1.imshow(np.transpose(abelData),
                          interpolation='nearest',
                          aspect='auto')
        self.axes11 = self.axes1.twiny()
        self.axes11.set_xticklabels(
            self.specter[self.currentSpecter].wavelength)

        majorLocator = FixedLocator(5)
        #majorFormatter = FormatStrFormatter('%d')
        minorLocator = MultipleLocator(5)

        #self.axes11.get_xaxis().set_major_locator(majorLocator)
        #self.axes11.get_xaxis().set_major_formatter(majorFormatter)
        self.canvas.draw()

    def drawPlots(self, x=0, y=0):
        abelData = self.abelData[self.currentSpecter]
        vertPixels = len(abelData[x])
        self.axes2.cla()
        self.axes2.set_ylim([vertPixels, 0])
        self.axes2.grid()
        self.axes2.plot(abelData[x], np.arange(0, vertPixels, 1))

        transp = np.transpose(abelData)[y]
        self.axes3.cla()
        self.axes3.set_xlim([0, len(transp)])
        self.axes3.grid()
        self.axes3.plot(transp)

        for line in self.lines:
            self.axes3.axvline(x=int(line[0]), color='r', linestyle='-')
            self.axes3.axvline(x=int(line[1]), color='r', linestyle='-')

        self.canvas.draw()

    def on_key_press(self, event):
        print('you pressed', event.key)

    def mouse_moved(self, mouse_event):
        if mouse_event.inaxes:
            x, y = int(round(mouse_event.xdata)), int(round(mouse_event.ydata))
            self.drawPlots(x, y)

    def loadSpecterFromFiles(self):
        self.dirPath = QtGui.QFileDialog.getExistingDirectory(
            self.main_frame, "Open Directory", "D:")
        fileList = glob.glob(self.dirPath + '\*.asc')
        for fileName in fileList:
            self.specter.append(
                Specter(np.loadtxt(fileName), fileName, self.specterCenter,
                        self.windowLength))

        if len(self.specter) > 0:
            self.currentSpecter = 0

        self.updateSpecterInput()
        for specNum in range(0, len(self.specter)):
            self.statusBar().showMessage('Busy...')
            self.computeAbelTransform(specNum)

        self.statusBar().showMessage('Ready')
        self.on_draw()

    def nextSpecter(self):
        if self.currentSpecter < (len(self.specter) - 1):
            self.currentSpecter += 1
            self.updateSpecterInput()
            self.on_draw()

    def prevSpecter(self):
        if self.currentSpecter > 1:
            self.currentSpecter -= 1
            self.updateSpecterInput()
            self.on_draw()

    def updateSpecterInput(self):
        self.currentSpecterInput.setText(
            str(self.currentSpecter + 1) + ' / ' + str(len(self.specter)) +
            ' (' + self.specter[self.currentSpecter].name + ')')

    def computeAbelTransform(self, specterNum):
        abelData = []
        for column in self.specter[specterNum].dataCombinedHalf:
            abelData.append(Abel.transform(column))

        self.abelData.append(np.array(abelData))

    def addLine(self):
        #self.lines.append((0,0,0,0,0,0))

        #test case
        self.lines.append((244, 265, 250, 10, 3000, 2))
        self.lines.append((305, 343, 325, 10, 2000, 2))
        self.updateTable()

    def setLine(self, item):
        lineNum = item.row()
        self.lines[lineNum] = (int(self.table.item(lineNum, 0).text()),
                               int(self.table.item(lineNum, 1).text()),
                               float(self.table.item(lineNum, 2).text()),
                               float(self.table.item(lineNum, 3).text()),
                               float(self.table.item(lineNum, 4).text()),
                               float(self.table.item(lineNum, 5).text()))

    def computeTemp(self):
        abelData = self.abelData[self.currentSpecter]
        Tempereture.compute(abelData, self.lines)

    def updateTable(self):
        self.table.setRowCount(0)
        for line in self.lines:
            currentRowCount = self.table.rowCount()
            self.table.insertRow(currentRowCount)
            for col, value in enumerate(line):
                self.table.setItem(currentRowCount, col,
                                   QtGui.QTableWidgetItem(str(value)))

    def saveDataToFile(self, data, fileName):
        np.savetxt(fileName, data, fmt='%10.5f')
Esempio n. 50
0
class SliceWidget(QtGui.QWidget):
    """
    Main widget holding the slice matplotlib Figure wrapped in FigureCanvasQTAgg.
    """
    index_changed = QtCore.pyqtSignal(int)

    def __init__(self, slices, indexes, dataset_title=None, default_cmap='seismic',
                 x_axis_indexes=None, y_axis_indexes=None,
                 show_h_indicator=False, show_v_indicator=False, v_min_max=None):
        super(SliceWidget, self).__init__()

        self.slices = slices
        self.indexes = indexes

        self.x_axis_name, self.x_axis_indexes = x_axis_indexes or (None, None)
        self.y_axis_name, self.y_axis_indexes = y_axis_indexes or (None, None)

        self.default_cmap = default_cmap

        self.show_h_indicator = show_h_indicator
        self.show_v_indicator = show_v_indicator

        self.palette().setColor(self.backgroundRole(), QtCore.Qt.white)

        self.current_index = 0

        # setting up the figure and canvas
        self.figure = Figure(figsize=(800, 200), dpi=20, facecolor='white')

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

        self.segy_plot = SegyPlot(self.slices,
                                  self.indexes,
                                  self.axes,
                                  self.default_cmap,
                                  x_axis_indexes=x_axis_indexes,
                                  y_axis_indexes=y_axis_indexes,
                                  display_horizontal_indicator=self.show_h_indicator,
                                  display_vertical_indicator=self.show_v_indicator,
                                  v_min_max=v_min_max)

        self.figure_canvas = FigureCanvas(self.figure)
        self.figure_canvas.setParent(self)

        # connect to mouse click events
        self.figure_canvas.mpl_connect('button_press_event', self._mouse_clicked)

        # widget layout
        self.layout = QtGui.QVBoxLayout(self)
        self.layout.addWidget(self.figure_canvas)

    def _mouse_clicked(self, evt):
        if evt.inaxes is not None:
            self.current_index = int(evt.xdata)
            self._signal_index_change(self.current_index)

    def _signal_index_change(self, x):
        if self.x_axis_indexes is not None:
            self.index_changed.emit(self.x_axis_indexes[x])


    def update_image(self, index):
        self.segy_plot.update_image(index)
        self.figure_canvas.draw()

    def set_cmap(self, action):
        self.segy_plot.set_colormap(str(action))
        self.figure_canvas.draw()

    def set_vertical_line_indicator(self, line):
        self.segy_plot.set_vertical_line_indicator(line)
        self.figure_canvas.draw()

    def set_horizontal_line_indicator(self, line):
        self.segy_plot.set_horizontal_line_indicator(line)
        self.figure_canvas.draw()
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        self.dirname = "E:/KaggleData/clips/Volumes/Seagate/seizure_detection/competition_data/clips"
        #tk = tkinter.Tk()
        #tk.withdraw()
        #self.dirname = askdirectory()
        self.dirname += "/"

        self.patient = "Dog_1"
        self.typ = "ictal"
        self.rang = "500"
        self.channel = "1"
        self.start = "0"
        self.end = "60"

        self.data = None

        self.graph = plt.figure()
        self.canvas = FigureCanvas(self.graph)

        layout = QtGui.QGridLayout()

        layout.setColumnMinimumWidth(0, 1200)

        layout.setRowMinimumHeight(0, 30)
        layout.setRowMinimumHeight(1, 400)

        layout.addWidget(self.canvas, 1, 0)

        # Directory text box
        dir_box = QtGui.QLineEdit()
        dir_box.setFixedWidth(200)
        layout.addWidget(dir_box)
        dir_box.move(5, 5)
        dir_box.textChanged[str].connect(self.dir_changed)
        dir_box.setText(self.dirname)

        # Patient combo box
        patient_box = QtGui.QComboBox()
        patient_box.setFixedWidth(100)
        layout.addWidget(patient_box)
        patient_box.move(215, 5)
        patient_box.addItem("Dog_1")
        patient_box.addItem("Dog_2")
        patient_box.addItem("Dog_3")
        patient_box.addItem("Dog_4")
        patient_box.addItem("Patient_1")
        patient_box.addItem("Patient_2")
        patient_box.addItem("Patient_3")
        patient_box.addItem("Patient_4")
        patient_box.addItem("Patient_5")
        patient_box.addItem("Patient_6")
        patient_box.addItem("Patient_7")
        patient_box.addItem("Patient_8")
        patient_box.activated[str].connect(self.patient_changed)

        # Type combo box
        type_box = QtGui.QComboBox()
        type_box.setFixedWidth(100)
        layout.addWidget(type_box)
        type_box.move(325, 5)
        type_box.addItem("ictal")
        type_box.addItem("interictal")
        type_box.addItem("test")
        type_box.activated[str].connect(self.type_changed)

        # Load button
        load_button = QtGui.QPushButton('Load')
        load_button.clicked.connect(self.load)
        load_button.setFixedWidth(70)
        layout.addWidget(load_button)
        load_button.move(435, 5)

        # Channel combo box
        channel_box = QtGui.QComboBox()
        channel_box.setFixedWidth(40)
        layout.addWidget(channel_box)
        channel_box.move(5, 5)
        channel_box.addItem("1")
        channel_box.addItem("2")
        channel_box.addItem("3")
        channel_box.addItem("4")
        channel_box.addItem("5")
        channel_box.addItem("6")
        channel_box.addItem("7")
        channel_box.addItem("8")
        channel_box.addItem("9")
        channel_box.addItem("10")
        channel_box.addItem("11")
        channel_box.addItem("12")
        channel_box.addItem("13")
        channel_box.addItem("14")
        channel_box.addItem("15")
        channel_box.addItem("16")
        channel_box.activated[str].connect(self.channel_changed)

        # Range combo box
        range_box = QtGui.QComboBox()
        range_box.setFixedWidth(50)
        layout.addWidget(range_box)
        range_box.move(5, 25)
        range_box.addItem("500")
        range_box.addItem("400")
        range_box.addItem("300")
        range_box.addItem("200")
        range_box.addItem("100")
        range_box.activated[str].connect(self.range_changed)

        # Start text box
        start_box = QtGui.QLineEdit()
        start_box.setFixedWidth(40)
        layout.addWidget(start_box)
        start_box.move(5, 5)
        start_box.textChanged[str].connect(self.start_changed)
        start_box.setText(self.start)

        # End text box
        end_box = QtGui.QLineEdit()
        end_box.setFixedWidth(40)
        layout.addWidget(end_box)
        end_box.move(1000, 1000)
        end_box.textChanged[str].connect(self.end_changed)
        end_box.setText(self.end)

        # Set layout
        self.setGeometry(8, 32, 100, 100)
        self.setLayout(layout)
Esempio n. 52
0
 def __init__(self):
     self.fig = Figure()
     FigureCanvas.__init__(self, self.fig)
     FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
     FigureCanvas.updateGeometry(self)
Esempio n. 53
0
    def changePlotWidget(self, library, frame_for_plot):

        if library == "PyQtGraph":
            plotWdg = pg.PlotWidget()
            plotWdg.showGrid(True, True, 0.5)
            datavline = pg.InfiniteLine(0,
                                        angle=90,
                                        pen=pg.mkPen('r', width=1),
                                        name='cross_vertical')
            datahline = pg.InfiniteLine(0,
                                        angle=0,
                                        pen=pg.mkPen('r', width=1),
                                        name='cross_horizontal')
            plotWdg.addItem(datavline)
            plotWdg.addItem(datahline)
            #cursor
            xtextitem = pg.TextItem('X : /',
                                    color=(0, 0, 0),
                                    border=pg.mkPen(color=(0, 0, 0), width=1),
                                    fill=pg.mkBrush('w'),
                                    anchor=(0, 1))
            ytextitem = pg.TextItem('Y : / ',
                                    color=(0, 0, 0),
                                    border=pg.mkPen(color=(0, 0, 0), width=1),
                                    fill=pg.mkBrush('w'),
                                    anchor=(0, 0))
            plotWdg.addItem(xtextitem)
            plotWdg.addItem(ytextitem)

            plotWdg.getViewBox().autoRange(items=[])
            plotWdg.getViewBox().disableAutoRange()
            plotWdg.getViewBox().border = pg.mkPen(color=(0, 0, 0), width=1)

            return plotWdg

        elif library == "Qwt5" and has_qwt:
            plotWdg = QwtPlot(frame_for_plot)
            sizePolicy = QSizePolicy(QSizePolicy.Expanding,
                                     QSizePolicy.Expanding)
            sizePolicy.setHorizontalStretch(0)
            sizePolicy.setVerticalStretch(0)
            sizePolicy.setHeightForWidth(
                plotWdg.sizePolicy().hasHeightForWidth())
            plotWdg.setSizePolicy(sizePolicy)
            plotWdg.setMinimumSize(QSize(0, 0))
            plotWdg.setAutoFillBackground(False)
            #Decoration
            plotWdg.setCanvasBackground(Qt.white)
            plotWdg.plotLayout().setAlignCanvasToScales(True)
            zoomer = QwtPlotZoomer(QwtPlot.xBottom, QwtPlot.yLeft,
                                   QwtPicker.DragSelection,
                                   QwtPicker.AlwaysOff, plotWdg.canvas())
            zoomer.setRubberBandPen(QPen(Qt.blue))
            if platform.system() != "Windows":
                # disable picker in Windows due to crashes
                picker = QwtPlotPicker(QwtPlot.xBottom, QwtPlot.yLeft,
                                       QwtPicker.NoSelection,
                                       QwtPlotPicker.CrossRubberBand,
                                       QwtPicker.AlwaysOn, plotWdg.canvas())
                picker.setTrackerPen(QPen(Qt.green))
            #self.dockwidget.qwtPlot.insertLegend(QwtLegend(), QwtPlot.BottomLegend);
            grid = Qwt.QwtPlotGrid()
            grid.setPen(QPen(QColor('grey'), 0, Qt.DotLine))
            grid.attach(plotWdg)
            return plotWdg

        elif library == "Matplotlib" and has_mpl:
            from matplotlib.figure import Figure
            if int(qgis.PyQt.QtCore.QT_VERSION_STR[0]) == 4:
                from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg
            elif int(qgis.PyQt.QtCore.QT_VERSION_STR[0]) == 5:
                from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg

            fig = Figure((1.0, 1.0),
                         linewidth=0.0,
                         subplotpars=matplotlib.figure.SubplotParams(left=0,
                                                                     bottom=0,
                                                                     right=1,
                                                                     top=1,
                                                                     wspace=0,
                                                                     hspace=0))

            font = {'family': 'arial', 'weight': 'normal', 'size': 12}
            rc('font', **font)

            rect = fig.patch
            rect.set_facecolor((0.9, 0.9, 0.9))

            self.subplot = fig.add_axes((0.05, 0.15, 0.92, 0.82))
            self.subplot.set_xbound(0, 1000)
            self.subplot.set_ybound(0, 1000)
            self.manageMatplotlibAxe(self.subplot)
            canvas = FigureCanvasQTAgg(fig)
            sizePolicy = QSizePolicy(QSizePolicy.Expanding,
                                     QSizePolicy.Expanding)
            sizePolicy.setHorizontalStretch(0)
            sizePolicy.setVerticalStretch(0)
            canvas.setSizePolicy(sizePolicy)
            return canvas
Esempio n. 54
0
 def addmpl(self, fig):
     self.canvas = FigureCanvas(fig)
     self.mplvl.addWidget(self.canvas)
     self.canvas.draw()
Esempio n. 55
0
class Statpage(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)

        self.parent = parent
        self.parent.statsInfo.connect(self.processStatsInfos)

        self.globalname = None
        self.globalforevername = None

        self.tabs = QTabWidget(self)

        self.setCentralWidget(self.tabs)

        self.setWindowTitle('Player statistics')

        self.mu, self.sigma = 1500, 500
        self.playermu, self.playersigma = 1500, 500
        self.name = "none"
        self.create_menu()
        self.create_global_frame()
        self.create_global_evolution_frame()
        self.create_global_evolution_forever_frame()
        #self.create_status_bar()

        self.tabs.currentChanged.connect(self.tabChanged)

        self.on_draw()

    def tabChanged(self, tab):

        if tab == 1:
            if self.name != "unknown" and self.globalname != self.name:
                self.parent.statsServer.send(
                    dict(command="stats",
                         player=self.name,
                         type="global_90_days"))
                #self.parent.send()
                self.evoaxes.clear()
                self.globalname = self.name

        if tab == 2:
            if self.name != "unknown" and self.globalforevername != self.name:
                self.parent.statsServer.send(
                    dict(command="stats",
                         player=self.name,
                         type="global_90_days"))
                self.evoaxesforever.clear()
                self.globalforevername = self.name

    def processStatsInfos(self, message):
        type = message['type']

        if not type == "global_forever" and not type == "global_90_days":
            return

        name = message['player']

        values = message['values']
        if name == self.name:

            if type == "global_forever":

                xaxis = []
                ymeanaxis = []
                ydevminaxis = []
                ydevmaxaxis = []

                for val in values:
                    ymeanaxis.append(val["mean"])
                    date = val["date"].split('.')
                    timing = val["time"].split(':')

                    ydevminaxis.append(val["mean"] - val["dev"])
                    ydevmaxaxis.append(val["mean"] + val["dev"])

                    date = datetime.datetime(int(date[2]), int(date[1]),
                                             int(date[0]), int(timing[0]),
                                             int(timing[1]))
                    xaxis.append(date)

                self.evoaxesforever.clear()
                self.evoaxesforever.set_ylabel("Skill")
                self.evoaxesforever.set_xlabel("Time")

                self.evoaxesforever.xaxis.set_major_formatter(
                    mdates.DateFormatter('%d/%m/%y'))
                self.evoaxesforever.plot(xaxis,
                                         ymeanaxis,
                                         '-,',
                                         linewidth=.5,
                                         color='black')
                self.evoaxesforever.fill_between(xaxis,
                                                 ymeanaxis,
                                                 ydevminaxis,
                                                 interpolate=True,
                                                 linewidth=0,
                                                 alpha=.5,
                                                 facecolor='red')
                self.evoaxesforever.fill_between(xaxis,
                                                 ymeanaxis,
                                                 ydevmaxaxis,
                                                 interpolate=True,
                                                 linewidth=0,
                                                 alpha=.5,
                                                 facecolor='red')
                #plt.fill(xaxis, ydevminaxis, 'r')

                self.evocanvasforever.draw()

            if type == "global_90_days":

                xaxis = []
                ymeanaxis = []
                ydevminaxis = []
                ydevmaxaxis = []

                for val in values:
                    ymeanaxis.append(val["mean"])
                    date = val["date"].split('.')
                    timing = val["time"].split(':')

                    ydevminaxis.append(val["mean"] - val["dev"])
                    ydevmaxaxis.append(val["mean"] + val["dev"])

                    date = datetime.datetime(int(date[2]), int(date[1]),
                                             int(date[0]), int(timing[0]),
                                             int(timing[1]))
                    xaxis.append(date)

                self.evoaxes.clear()
                self.evoaxes.set_ylabel("Skill")
                self.evoaxes.set_xlabel("Time")

                self.evoaxes.xaxis.set_major_formatter(
                    mdates.DateFormatter('%d %b'))
                self.evoaxes.plot(xaxis,
                                  ymeanaxis,
                                  '-,',
                                  linewidth=.5,
                                  color='black')
                self.evoaxes.fill_between(xaxis,
                                          ymeanaxis,
                                          ydevminaxis,
                                          interpolate=True,
                                          linewidth=0,
                                          alpha=.5,
                                          facecolor='red')
                self.evoaxes.fill_between(xaxis,
                                          ymeanaxis,
                                          ydevmaxaxis,
                                          interpolate=True,
                                          linewidth=0,
                                          alpha=.5,
                                          facecolor='red')
                #plt.fill(xaxis, ydevminaxis, 'r')

                self.evocanvas.draw()

    def setplayer(self, name):

        if name in self.parent.players:

            self.evoaxes.clear()
            self.evoaxesforever.clear()
            self.setWindowTitle('Rating analysis of %s' % name)
            self.name = name

            self.mu = self.parent.players[name]["rating_mean"]
            self.sigma = self.parent.players[name]["rating_deviation"]

            self.playermu = self.parent.players[
                self.parent.login]["rating_mean"]
            self.playersigma = self.parent.players[
                self.parent.login]["rating_deviation"]

            self.on_draw()

            if self.tabs.currentIndex() == 1:
                self.parent.send(
                    dict(command="stats",
                         player=self.name,
                         type="global_90_days"))
            if self.tabs.currentIndex() == 2:
                self.parent.send(
                    dict(command="stats",
                         player=self.name,
                         type="global_forever"))
        else:
            self.name = "unknown"
            self.mu = 0
            self.sigma = 0

    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_pick(self, event):

        box_points = event.artist.get_bbox().get_points()
        msg = "You've clicked on a bar with coords:\n %s" % box_points

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

    def on_draw(self):
        """ Redraws the figure
        """
        str = unicode(self.textbox.text())

        x = self.mu + self.sigma * np(50000)

        self.axes.clear()

        self.axes.grid(self.grid_cb.isChecked())

        self.axes.set_xlabel("Skill")
        self.axes.set_ylabel("Probability %")
        #self.ylabel('')
        self.axes.set_title("performance graph of %s" % self.name)

        #
        ## the histogram of the data
        n, bins, patches = self.axes.hist(x,
                                          100,
                                          normed=1,
                                          facecolor='green',
                                          alpha=0.55)

        y = normpdf(bins, self.mu, self.sigma) * 100

        text = "This is the potential rating of %s.\n66 percent chances to be between %i and %i." % (
            self.name, int(self.mu - self.sigma), int(self.mu + self.sigma))

        self.textbox.setText(text + "\n%.2f percent chances to be %i" %
                             (round((max(y) * 100), 2), int(self.mu)))
        self.textbox.setText(
            self.textbox.text() +
            "\nThe worst rating possible is the one in the leaderboard : %i" %
            int(self.mu - 3 * self.sigma))

        self.axes.axis([
            self.mu - 4 * self.sigma, self.mu + 4 * self.sigma, 0,
            (100 + (max(y) * 100) * 1.5) / 2
        ])
        #self.axes.hist(x, bins, normed=1, facecolor='green',)
        self.axes.plot(bins,
                       y * 100,
                       linewidth=.5,
                       linestyle='None',
                       color='red',
                       alpha=1.0)
        self.axes.fill(bins,
                       y * 100,
                       'r--',
                       linewidth=0,
                       alpha=.5,
                       facecolor='red')

        self.axes.annotate(('%s maximum rating (%i)' % (self.name, self.mu)),
                           xy=(self.mu, max(y) * 100),
                           xycoords='data',
                           xytext=(-50, 30),
                           textcoords='offset points',
                           arrowprops=dict(arrowstyle="wedge",
                                           facecolor='red',
                                           linewidth=0),
                           size=7,
                           alpha=0.5,
                           backgroundcolor='lightgrey')

        if not self.compare_cb.isChecked():
            self.axes.fill_between(bins,
                                   y * 100,
                                   0,
                                   where=bins > self.mu + self.sigma,
                                   facecolor='darkred',
                                   interpolate=True)
            self.axes.fill_between(bins,
                                   y * 100,
                                   0,
                                   where=bins < self.mu - self.sigma,
                                   facecolor='darkred',
                                   interpolate=True)

        if self.compare_cb.isChecked():

            self.axes.set_title("performance graph of %s VS you " % self.name)

            x = self.playermu + self.playersigma * np(50000)
            n, bins, patches = self.axes.hist(x,
                                              100,
                                              normed=1,
                                              facecolor='green',
                                              alpha=0.55)
            y2 = normpdf(bins, self.playermu, self.playersigma) * 100
            self.axes.axis([
                min(self.mu - 4 * self.sigma,
                    self.playermu - 4 * self.playersigma),
                max(self.mu + 4 * self.sigma,
                    self.playermu + 4 * self.playersigma), 0,
                max((100 + (max(y) * 100) * 1.5) / 2,
                    (100 + (max(y2) * 100) * 1.5) / 2)
            ])
            self.axes.plot(bins,
                           y2 * 100,
                           linewidth=.5,
                           linestyle='None',
                           color='blue',
                           alpha=1.0)
            self.axes.fill(bins,
                           y2 * 100,
                           'r--',
                           linewidth=0,
                           alpha=.5,
                           facecolor='blue')
            #self.axes.fill_between(bins, y2*100 ,0, where=bins>self.playermu+self.playersigma, facecolor='darkblue',  interpolate=True)
            #self.axes.fill_between(bins, y2*100 ,0, where=bins<self.playermu-self.playersigma, facecolor='darkblue', interpolate=True )

            self.axes.annotate('Your most probable rating (%i)' %
                               int(self.playermu),
                               xy=(self.playermu, max(y2) * 100),
                               xycoords='data',
                               xytext=(-50, 30),
                               textcoords='offset points',
                               arrowprops=dict(arrowstyle="wedge",
                                               facecolor='blue',
                                               linewidth=0),
                               size=7,
                               alpha=0.5,
                               backgroundcolor='lightgrey')

            text = "This is the potential rating of %s.\n66 percent chances to be between %i and %i. (you : between %i and %i)" % (
                self.name,
                int(self.mu - self.sigma), int(self.mu + self.sigma),
                int(self.playermu - self.playersigma),
                int(self.playermu + self.playersigma))
            self.textbox.setText(
                text +
                "\n%.2f percent chances to be %i (You : \n%.2f percent chances to be %i)"
                % (round((max(y) * 100), 2), int(self.mu),
                   round((max(y2) * 100), 2), int(self.playermu)))
            self.textbox.setText(
                self.textbox.text() +
                "\nThe worst rating possible is the one in the leaderboard : %i (you : %i)"
                % (int(self.mu - 3 * self.sigma),
                   int(self.playermu - 3 * self.playersigma)))

            teamsTrueskill = []
            Team1 = Team()
            Team1.addPlayer("1", Rating(self.mu, self.sigma))
            Team2 = Team()
            Team2.addPlayer("2", Rating(self.playermu, self.playersigma))
            teamsTrueskill.append(Team1)
            teamsTrueskill.append(Team2)
            gameInfo = GameInfo()
            calculator = FactorGraphTrueSkillCalculator()
            gamequality = calculator.calculateMatchQuality(
                gameInfo, teamsTrueskill) * 100
            self.textbox.setText(
                self.textbox.text() +
                "\nProbabilites of having a even match : %.2f percent" %
                gamequality)

        self.canvas.draw()

    def create_global_evolution_forever_frame(self):

        self.global_evolution_forever = QWidget()

        self.evoforeverfig = Figure((5.0, 4.0), dpi=self.dpi)
        self.evocanvasforever = FigureCanvas(self.evoforeverfig)
        self.evocanvasforever.setParent(self.global_evolution_forever)

        self.evoaxesforever = self.evoforeverfig.add_subplot(111)

        self.evotoolbarf = NavigationToolbar(self.evocanvasforever,
                                             self.global_evolution_forever)

        hbox = QHBoxLayout()

        vbox = QVBoxLayout()
        vbox.addWidget(self.evocanvasforever)
        vbox.addWidget(self.evotoolbarf)
        vbox.addLayout(hbox)

        self.global_evolution_forever.setLayout(vbox)

        self.tabs.addTab(self.global_evolution_forever,
                         "Global Rating Evolution for a year")

    def create_global_evolution_frame(self):

        self.global_evolution = QWidget()

        self.evofig = Figure((5.0, 4.0), dpi=self.dpi)
        self.evocanvas = FigureCanvas(self.evofig)
        self.evocanvas.setParent(self.global_evolution)

        self.evoaxes = self.evofig.add_subplot(111)

        self.evotoolbar = NavigationToolbar(self.evocanvas,
                                            self.global_evolution)

        hbox = QHBoxLayout()
        #        hbox.addWidget(self.textbox)
        #        hbox.addWidget(self.grid_cb)

        vbox = QVBoxLayout()
        vbox.addWidget(self.evocanvas)
        vbox.addWidget(self.evotoolbar)
        vbox.addLayout(hbox)

        self.global_evolution.setLayout(vbox)

        self.tabs.addTab(self.global_evolution,
                         "Global Rating Evolution for the last 90 days")

    def create_global_frame(self):

        self.global_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.global_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.fig.add_subplot(xlabel='Smarts')
        # 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.global_frame)

        # Other GUI controls
        #

        text = "This is the potential rating of %s.\n66 percent chances to be between %i and %i." % (
            self.name, int(self.mu - self.sigma), int(self.mu + self.sigma))
        self.textbox = QLabel(text)

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

        self.compare_cb = QCheckBox("&Compare to you")
        self.connect(self.compare_cb, SIGNAL('stateChanged(int)'),
                     self.on_draw)

        hbox = QHBoxLayout()

        hbox.addWidget(self.textbox)
        hbox.addWidget(self.grid_cb)
        hbox.addWidget(self.compare_cb)
        hbox.setAlignment(self.grid_cb, Qt.AlignVCenter)
        hbox.setAlignment(self.grid_cb, Qt.AlignRight)

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

        self.global_frame.setLayout(vbox)

        self.tabs.addTab(self.global_frame, "Global rating")

    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
Esempio n. 56
0
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1127, 665)
        
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
       
        self.QuitButton = QtWidgets.QPushButton(self.centralwidget)
        self.QuitButton.setGeometry(QtCore.QRect(10, 550, 161, 61))
        self.QuitButton.setObjectName("QuitButton")
        
        self.UpButton = QtWidgets.QPushButton(self.centralwidget)
        self.UpButton.setGeometry(QtCore.QRect(160, 20, 161, 61))
        self.UpButton.setObjectName("UpButton")
        
        self.RightButton = QtWidgets.QPushButton(self.centralwidget)
        self.RightButton.setGeometry(QtCore.QRect(310, 100, 161, 61))
        self.RightButton.setObjectName("RightButton")
        
        self.DownButton = QtWidgets.QPushButton(self.centralwidget)
        self.DownButton.setGeometry(QtCore.QRect(160, 180, 161, 61))
        self.DownButton.setObjectName("DownButton")
        
        self.LeftButton = QtWidgets.QPushButton(self.centralwidget)
        self.LeftButton.setGeometry(QtCore.QRect(10, 100, 161, 61))
        self.LeftButton.setObjectName("LeftButton")
        
        self.Control = QtWidgets.QPushButton(self.centralwidget)
        self.Control.setGeometry(QtCore.QRect(160, 310, 161, 61))
        self.Control.setObjectName("Control")
        
        self.RecordButton = QtWidgets.QPushButton(self.centralwidget)
        self.RecordButton.setGeometry(QtCore.QRect(160, 390, 161, 61))
        self.RecordButton.setObjectName("RecordButton")
        
        self.ReplayButton = QtWidgets.QPushButton(self.centralwidget)
        self.ReplayButton.setGeometry(QtCore.QRect(160, 470, 161, 61))
        self.ReplayButton.setObjectName("ReplayButton")
        
        self.GraphGui = QtWidgets.QWidget(self.centralwidget)
        self.GraphGui.setGeometry(QtCore.QRect(490, 10, 621, 601))
        
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.GraphGui.sizePolicy().hasHeightForWidth())
        
        self.GraphGui.setSizePolicy(sizePolicy)
        self.GraphGui.setObjectName("GraphGui")
        
        self.mplvl = QtWidgets.QVBoxLayout(self.GraphGui)
        self.mplvl.setContentsMargins(0, 0, 0, 0)
        self.mplvl.setObjectName("mplvl")
        
        MainWindow.setCentralWidget(self.centralwidget)
        
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1127, 21))
        self.menubar.setObjectName("menubar")
        
        MainWindow.setMenuBar(self.menubar)
        
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
        
        
        #setting up functions for buttons
        self.UpButton.clicked.connect(self.Up)
        self.DownButton.clicked.connect(self.Down)
        self.LeftButton.clicked.connect(self.Left)
        self.RightButton.clicked.connect(self.Right)
        self.QuitButton.clicked.connect(self.quit)
        self.RecordButton.clicked.connect(self.updateGraph)
        self.Control.clicked.connect(self.controlSwitch)
        
    def Up(self):
        if(self.Control.text == "Arm Control"): #arm up
            ser.write(0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)
        elif(self.Control.text == "Head Control"): #tilt up
            ser.write(0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)
            
    def Down(self):
        if(self.Control.text == "Arm Control"): #arm down
            ser.write(0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)
        elif(self.Control.text == "Head Control"): #tilt down
            ser.write(0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)
    
    def Left(self):
        if(self.Control.text == "Arm Control"): #arm left
            ser.write(0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)
        elif(self.Control.text == "Head Control"): #pan left
            ser.write(0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)
        
    def Right(self):
        if(self.Control.text == "Arm Control"): #arm right
            ser.write(0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)
        elif(self.Control.text == "Head Control"): #pan right
            ser.write(0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)

    def Out(self):
        if(self.Control.text == "Arm Control"): #arm out
            ser.write(0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)
        elif(self.Control.text == "Head Control"): #roll left
            ser.write(0x0b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)
            
    def In(self):
        if(self.Control.text == "Arm Control"): #arm in
            ser.write(0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)
        elif(self.Control.text == "Head Control"): #roll right
            ser.write(0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)

    def quit(self):
        ser.close()
        QtWidgets.QApplication.exit()
        MainWindow.close()

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.QuitButton.setText(_translate("MainWindow", "Quit"))
        self.UpButton.setText(_translate("MainWindow", "Up"))
        self.RightButton.setText(_translate("MainWindow", "Right"))
        self.DownButton.setText(_translate("MainWindow", "Down"))
        self.LeftButton.setText(_translate("MainWindow", "Left"))
        self.Control.setText(_translate("MainWindow", "Arm Control"))
        self.RecordButton.setText(_translate("MainWindow", "Record"))
        self.ReplayButton.setText(_translate("MainWindow", "Replay"))


    def addmpl(self, fig):
        self.canvas = FigureCanvas(fig)
        self.mplvl.addWidget(self.canvas)
        self.canvas.draw()

    def updateGraph(self):
        global zline
        global xline
        global yline
        
        print(ser.write(0x0C))
        for x in range (0,13):
            print(ser.write(0x00))
        newzline = np.append(zline, np.array([random.randint(0,100)]), 0)
        newxline = np.append(xline, np.array([random.randint(0,100)]), 0)
        newyline = np.append(yline, np.array([random.randint(0,100)]), 0)
        zline = newzline
        xline = newxline
        yline = newyline    
        fig1.clf()
        fig1.add_subplot(111, projection='3d').plot3D(xline, yline, zline, 'red')   
        self.addmpl(fig1)

    def controlSwitch(self):
        _translate = QtCore.QCoreApplication.translate
        if self.Control.text() == "Arm Control":
            self.Control.setText(_translate("Arm Control", "Head Control"))
            self.UpButton.setText(_translate("Up", "Tilt Up"))
            self.DownButton.setText(_translate("Down", "Tilt Down"))
            self.LeftButton.setText(_translate("Left", "Pan Left"))
            self.RightButton.setText(_translate("Right", "Pan Right"))
        elif self.Control.text() == "Head Control":
            self.Control.setText(_translate("Head Control", "Arm Control"))
            self.UpButton.setText(_translate("Tilt Up", "Up"))
            self.DownButton.setText(_translate("Tilt Down", "Down"))
            self.LeftButton.setText(_translate("Pan Left", "Left"))
            self.RightButton.setText(_translate("Pan Right", "Right"))
Esempio n. 57
0
    def __init__(self, spectrum_collec, gen_heatmap, map, path, parent=None):

        super(PlotDisplay, self).__init__(parent)

        # Set spectrum collection instance variable/member
        self.my_collec = spectrum_collec

        # a figure instance to plot on
        self.figure = plt.figure()

        # callback to gen heatmap
        self.gen_heatmap = gen_heatmap

        # callback to map images
        self.map = map

        #self.lin_reg = lin_reg

        # initializations for image stack creation
        self.path = path
        self.stack = ImageStack(self.my_collec, self.path)
        self.stack.setWindowTitle('TIFF Image Stack')

        self.ax = self.figure.add_subplot(111)

        # this is the Canvas Widget that displays the `figure`
        # it takes the `figure` instance as a parameter to __init__
        self.canvas = FigureCanvas(self.figure)

        # this is the Navigation widget
        # it takes the Canvas widget and a parent
        self.toolbar = NavigationToolbar(self.canvas, self)

        # a button connected to `plot` method
        self.button = QtGui.QPushButton('Plot Spectrum')
        self.button.clicked.connect(self.plot)

        # add a combobox for all X values
        self.drop_down_x = QtGui.QComboBox()
        x_list = list(self.my_collec.x_to_y.keys())
        x_list = [str(each) for each in x_list]
        self.drop_down_x.addItems(x_list)

        # add a combobox for Y's corresponding to first X
        self.drop_down_y = QtGui.QComboBox()
        y_list = list(self.my_collec.x_to_y.values())
        y_list = [str(each) for each in y_list[0]]
        self.drop_down_y.addItems(y_list)

        self.drop_down_x.currentIndexChanged.connect(self.selection_change)

        # create label
        self.label_x = QtGui.QLabel("Select X:")
        self.label_y = QtGui.QLabel("Select Y:")

        # create split layout for displaying combo boxes side by side
        splitter = QtGui.QSplitter(QtCore.Qt.Horizontal)
        splitter.addWidget(self.label_x)
        splitter.addWidget(self.drop_down_x)
        splitter.addWidget(self.label_y)
        splitter.addWidget(self.drop_down_y)

        # add left vertical line slider for peak selection
        self.sld = QtGui.QSlider(QtCore.Qt.Horizontal)
        self.sld.setMinimum(0)
        self.wavenums = self.get_wavenums()
        self.sld.setMaximum(len(self.wavenums) - 1)
        self.sld.setTickInterval(1)
        self.curr_sld = self.sld.sliderPosition()
        self.sld.valueChanged.connect(self.sld_change)

        # add right vertical line slider for peak selection
        self.sld_2 = QtGui.QSlider(QtCore.Qt.Horizontal)
        self.sld_2.setMinimum(0)
        self.wavenums = self.get_wavenums()
        self.sld_2.setMaximum(len(self.wavenums) - 1)
        self.sld_2.setTickInterval(1)
        self.curr_sld_2 = self.sld_2.sliderPosition()
        self.sld_2.valueChanged.connect(self.sld_change)

        # initialize left and right lines to start at None
        self.vert_line = None
        self.vert_line_2 = None

        # text edit to display wavenumber for left slider
        self.textedit = QtGui.QLabel()
        self.textedit.setStyleSheet('background-color: white')

        # text edit to display wavenumber for right slider
        self.textedit_2 = QtGui.QLabel()
        self.textedit_2.setStyleSheet('background-color: white')

        # horizontal layout to hold slider and text edit box
        hslider_text = QtGui.QHBoxLayout()
        hslider_text.addWidget(self.sld, 2)
        hslider_text.addWidget(self.textedit, 1)

        # group box to group left slider and text elements together
        gbox = QtGui.QGroupBox("Left")
        gbox.setLayout(hslider_text)
        qpalette = QtGui.QPalette()
        qpalette.setColor(QtGui.QPalette.Dark, QtCore.Qt.white)
        gbox.setPalette(qpalette)

        # set layout of left slider group box
        hslider_text_2 = QtGui.QHBoxLayout()
        hslider_text_2.addWidget(self.sld_2, 2)
        hslider_text_2.addWidget(self.textedit_2, 1)

        # group box to group right slider and text elements together
        gbox_2 = QtGui.QGroupBox("Right")
        gbox_2.setLayout(hslider_text_2)
        qpalette = QtGui.QPalette()
        qpalette.setColor(QtGui.QPalette.Dark, QtCore.Qt.white)
        gbox.setPalette(qpalette)

        # set layout of right slider group box
        slider_layout = QtGui.QVBoxLayout()
        slider_layout.addWidget(gbox)
        slider_layout.addWidget(gbox_2)

        slider_group = QtGui.QGroupBox("Peak Selection")
        slider_group.setLayout(slider_layout)

        # add button for heat map generation
        self.hm_button = QtGui.QPushButton('Generate Heatmap')
        self.hm_button.clicked.connect(self.hm_make)

        # add button for image stack pop out window
        self.map_img = QtGui.QPushButton('View Image Stack')
        self.map_img.clicked.connect(self.img_stack)

        # add baseline correction button
        self.bg_test = QtGui.QPushButton('Baseline Correction')
        self.bg_test.clicked.connect(self.rb_test)

        # set the layout of main window, adding all widgets
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        layout.addWidget(self.button)
        layout.addWidget(splitter)
        layout.addWidget(slider_group)
        layout.addWidget(self.hm_button)
        layout.addWidget(self.map_img)
        layout.addWidget(self.bg_test)
        self.setLayout(layout)
Esempio n. 58
0
class PlotWidget(QWidget):
    def __init__(self, parent=None, image=None, toolbar=True):
        QWidget.__init__(self, parent)
        self.data = image
        self.dpi = 100
        self.cmap = 'gray'
        self.toolbar = toolbar
        self.create_main_widget()
        if self.data is not None:
            self.on_draw()

    def create_main_widget(self):
        print self.data
        self.fig = Figure((10.0, 8.0), dpi=self.dpi)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setFocusPolicy(Qt.StrongFocus)
        self.canvas.setFocus()
        vbox = QVBoxLayout()
        vbox.addWidget(self.canvas)  # the matplotlib canvas
        if self.toolbar:
            self.mpl_toolbar = NavigationToolbar(self.canvas, self)
            vbox.addWidget(self.mpl_toolbar)
        self.canvas.mpl_connect('key_press_event', self.on_key_press)
        self.setLayout(vbox)

    def set_image(self, image):
        self.data = image
        self.on_draw()

    def on_key_press(self, event):
        if event.key == 'i':
            print('* image infos:')
            print('shape is (%dx%d)' %
                  (np.shape(self.data)[0], np.shape(self.data)[1]))
            print('min in image= %d, max in image=%d' %
                  (np.min(self.data), np.max(self.data)))
        elif event.key == 'right':
            # load next image
            self.parent().parent().on_next_image()
        elif event.key == 'left':
            # load previous image
            self.parent().parent().on_prev_image()
        elif event.key == 'h':
            # plot the image histogram
            hist(self.data,
                 data_range=(np.min(self.data), np.max(self.data)),
                 show=True)
        # implement the default mpl key press events described at
        # http://matplotlib.org/users/navigation_toolbar.html#navigation-keyboard-shortcuts
        key_press_handler(event, self.canvas, self.mpl_toolbar)

    def on_draw(self):
        if not hasattr(self.fig, 'subplot'):
            self.axes = self.fig.add_subplot(111)
        self.axes.imshow(self.data,
                         cmap=self.cmap,
                         origin='upper',
                         interpolation='nearest',
                         clim=[np.min(self.data),
                               np.max(self.data)])
        self.canvas.draw()
class Window(QtGui.QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        self.dirname = "E:/KaggleData/clips/Volumes/Seagate/seizure_detection/competition_data/clips"
        #tk = tkinter.Tk()
        #tk.withdraw()
        #self.dirname = askdirectory()
        self.dirname += "/"

        self.patient = "Dog_1"
        self.typ = "ictal"
        self.rang = "500"
        self.channel = "1"
        self.start = "0"
        self.end = "60"

        self.data = None

        self.graph = plt.figure()
        self.canvas = FigureCanvas(self.graph)

        layout = QtGui.QGridLayout()

        layout.setColumnMinimumWidth(0, 1200)

        layout.setRowMinimumHeight(0, 30)
        layout.setRowMinimumHeight(1, 400)

        layout.addWidget(self.canvas, 1, 0)

        # Directory text box
        dir_box = QtGui.QLineEdit()
        dir_box.setFixedWidth(200)
        layout.addWidget(dir_box)
        dir_box.move(5, 5)
        dir_box.textChanged[str].connect(self.dir_changed)
        dir_box.setText(self.dirname)

        # Patient combo box
        patient_box = QtGui.QComboBox()
        patient_box.setFixedWidth(100)
        layout.addWidget(patient_box)
        patient_box.move(215, 5)
        patient_box.addItem("Dog_1")
        patient_box.addItem("Dog_2")
        patient_box.addItem("Dog_3")
        patient_box.addItem("Dog_4")
        patient_box.addItem("Patient_1")
        patient_box.addItem("Patient_2")
        patient_box.addItem("Patient_3")
        patient_box.addItem("Patient_4")
        patient_box.addItem("Patient_5")
        patient_box.addItem("Patient_6")
        patient_box.addItem("Patient_7")
        patient_box.addItem("Patient_8")
        patient_box.activated[str].connect(self.patient_changed)

        # Type combo box
        type_box = QtGui.QComboBox()
        type_box.setFixedWidth(100)
        layout.addWidget(type_box)
        type_box.move(325, 5)
        type_box.addItem("ictal")
        type_box.addItem("interictal")
        type_box.addItem("test")
        type_box.activated[str].connect(self.type_changed)

        # Load button
        load_button = QtGui.QPushButton('Load')
        load_button.clicked.connect(self.load)
        load_button.setFixedWidth(70)
        layout.addWidget(load_button)
        load_button.move(435, 5)

        # Channel combo box
        channel_box = QtGui.QComboBox()
        channel_box.setFixedWidth(40)
        layout.addWidget(channel_box)
        channel_box.move(5, 5)
        channel_box.addItem("1")
        channel_box.addItem("2")
        channel_box.addItem("3")
        channel_box.addItem("4")
        channel_box.addItem("5")
        channel_box.addItem("6")
        channel_box.addItem("7")
        channel_box.addItem("8")
        channel_box.addItem("9")
        channel_box.addItem("10")
        channel_box.addItem("11")
        channel_box.addItem("12")
        channel_box.addItem("13")
        channel_box.addItem("14")
        channel_box.addItem("15")
        channel_box.addItem("16")
        channel_box.activated[str].connect(self.channel_changed)

        # Range combo box
        range_box = QtGui.QComboBox()
        range_box.setFixedWidth(50)
        layout.addWidget(range_box)
        range_box.move(5, 25)
        range_box.addItem("500")
        range_box.addItem("400")
        range_box.addItem("300")
        range_box.addItem("200")
        range_box.addItem("100")
        range_box.activated[str].connect(self.range_changed)

        # Start text box
        start_box = QtGui.QLineEdit()
        start_box.setFixedWidth(40)
        layout.addWidget(start_box)
        start_box.move(5, 5)
        start_box.textChanged[str].connect(self.start_changed)
        start_box.setText(self.start)

        # End text box
        end_box = QtGui.QLineEdit()
        end_box.setFixedWidth(40)
        layout.addWidget(end_box)
        end_box.move(1000, 1000)
        end_box.textChanged[str].connect(self.end_changed)
        end_box.setText(self.end)

        # Set layout
        self.setGeometry(8, 32, 100, 100)
        self.setLayout(layout)

    def load(self):
        print("loading files...")
        filestub = self.dirname + self.patient + "/" + self.patient + "_" + self.typ + "_segment_"
        cont = 1
        i = 2
        print("file", i)
        self.data = scipy.io.loadmat(filestub + "1.mat")['data']
        lats = [-1]
        while cont:
            try:
                f = scipy.io.loadmat(filestub + str(i) + ".mat")
                dat = f['data']
                lat = f['latency']
                self.data = concatenate((self.data, dat), 1)
                lats.append(int(lat[0]))
                print(filestub + str(i) + ".mat")
            except:
                cont = 0
            i += 1
        self.lens = []
        i = 0
        j = 0
        for i in range(0, len(lats)):
            if lats[i] == 0:
                self.lens.append(j)
                j = 0
            else:
                j += 1
        self.lens.append(j)
        if self.typ == 'interictal':
            self.lens = [len(self.data[0]) / 400]
        print(self.lens)
        self.display()
        print("load complete")

    def display(self):
        if self.data != None:
            print("generating display")
            axis = self.graph.add_subplot(1, 1, 1)
            axis.cla()
            axis.hold(True)
            length = len(self.data[int(self.channel) - 1])
            if int(self.end) > length:
                self.end = str(length / 400)
            s = int(self.start)
            e = int(self.end)
            c = int(self.channel) - 1
            xrange = np.arange(s, e * 400, 1 / 400)
            i = 0
            color = 0
            for j in range(0, len(self.lens)):
                end = i + self.lens[j]
                if end > e:
                    end = e - s
                tempx = xrange[i * 400:end * 400]
                tempy = self.data[c][i * 400:end * 400]
                axis.plot(tempx, tempy, colors[color])
                i += self.lens[j]
                if color % 8 == 7:
                    color = 0
                else:
                    color += 1
            axis.set_ylim([-1 * int(self.rang), int(self.rang)])
            self.canvas.draw()
            axis.hold(False)

    def dir_changed(self, dirname):
        self.dirname = dirname
        print("New directory:", self.dirname)

    def patient_changed(self, patient):
        self.patient = patient
        print("New patient:", self.patient)

    def type_changed(self, typ):
        self.typ = typ
        print("New data type:", self.typ)

    def channel_changed(self, channel):
        self.channel = channel
        print("Channel:", self.channel)
        self.display()

    def range_changed(self, rang):
        self.rang = rang
        print("Vertical range changed to +/-", self.rang)
        self.display()

    def start_changed(self, start):
        if start != "":
            self.start = start
            print("Start value:", self.start)
            self.display()

    def end_changed(self, end):
        if end != "":
            self.end = end
            print("End value:", self.end)
            self.display()
Esempio n. 60
0
class PlotDisplay(QtGui.QDialog):
    """Creates the main application window"""
    def __init__(self, spectrum_collec, gen_heatmap, map, path, parent=None):

        super(PlotDisplay, self).__init__(parent)

        # Set spectrum collection instance variable/member
        self.my_collec = spectrum_collec

        # a figure instance to plot on
        self.figure = plt.figure()

        # callback to gen heatmap
        self.gen_heatmap = gen_heatmap

        # callback to map images
        self.map = map

        #self.lin_reg = lin_reg

        # initializations for image stack creation
        self.path = path
        self.stack = ImageStack(self.my_collec, self.path)
        self.stack.setWindowTitle('TIFF Image Stack')

        self.ax = self.figure.add_subplot(111)

        # this is the Canvas Widget that displays the `figure`
        # it takes the `figure` instance as a parameter to __init__
        self.canvas = FigureCanvas(self.figure)

        # this is the Navigation widget
        # it takes the Canvas widget and a parent
        self.toolbar = NavigationToolbar(self.canvas, self)

        # a button connected to `plot` method
        self.button = QtGui.QPushButton('Plot Spectrum')
        self.button.clicked.connect(self.plot)

        # add a combobox for all X values
        self.drop_down_x = QtGui.QComboBox()
        x_list = list(self.my_collec.x_to_y.keys())
        x_list = [str(each) for each in x_list]
        self.drop_down_x.addItems(x_list)

        # add a combobox for Y's corresponding to first X
        self.drop_down_y = QtGui.QComboBox()
        y_list = list(self.my_collec.x_to_y.values())
        y_list = [str(each) for each in y_list[0]]
        self.drop_down_y.addItems(y_list)

        self.drop_down_x.currentIndexChanged.connect(self.selection_change)

        # create label
        self.label_x = QtGui.QLabel("Select X:")
        self.label_y = QtGui.QLabel("Select Y:")

        # create split layout for displaying combo boxes side by side
        splitter = QtGui.QSplitter(QtCore.Qt.Horizontal)
        splitter.addWidget(self.label_x)
        splitter.addWidget(self.drop_down_x)
        splitter.addWidget(self.label_y)
        splitter.addWidget(self.drop_down_y)

        # add left vertical line slider for peak selection
        self.sld = QtGui.QSlider(QtCore.Qt.Horizontal)
        self.sld.setMinimum(0)
        self.wavenums = self.get_wavenums()
        self.sld.setMaximum(len(self.wavenums) - 1)
        self.sld.setTickInterval(1)
        self.curr_sld = self.sld.sliderPosition()
        self.sld.valueChanged.connect(self.sld_change)

        # add right vertical line slider for peak selection
        self.sld_2 = QtGui.QSlider(QtCore.Qt.Horizontal)
        self.sld_2.setMinimum(0)
        self.wavenums = self.get_wavenums()
        self.sld_2.setMaximum(len(self.wavenums) - 1)
        self.sld_2.setTickInterval(1)
        self.curr_sld_2 = self.sld_2.sliderPosition()
        self.sld_2.valueChanged.connect(self.sld_change)

        # initialize left and right lines to start at None
        self.vert_line = None
        self.vert_line_2 = None

        # text edit to display wavenumber for left slider
        self.textedit = QtGui.QLabel()
        self.textedit.setStyleSheet('background-color: white')

        # text edit to display wavenumber for right slider
        self.textedit_2 = QtGui.QLabel()
        self.textedit_2.setStyleSheet('background-color: white')

        # horizontal layout to hold slider and text edit box
        hslider_text = QtGui.QHBoxLayout()
        hslider_text.addWidget(self.sld, 2)
        hslider_text.addWidget(self.textedit, 1)

        # group box to group left slider and text elements together
        gbox = QtGui.QGroupBox("Left")
        gbox.setLayout(hslider_text)
        qpalette = QtGui.QPalette()
        qpalette.setColor(QtGui.QPalette.Dark, QtCore.Qt.white)
        gbox.setPalette(qpalette)

        # set layout of left slider group box
        hslider_text_2 = QtGui.QHBoxLayout()
        hslider_text_2.addWidget(self.sld_2, 2)
        hslider_text_2.addWidget(self.textedit_2, 1)

        # group box to group right slider and text elements together
        gbox_2 = QtGui.QGroupBox("Right")
        gbox_2.setLayout(hslider_text_2)
        qpalette = QtGui.QPalette()
        qpalette.setColor(QtGui.QPalette.Dark, QtCore.Qt.white)
        gbox.setPalette(qpalette)

        # set layout of right slider group box
        slider_layout = QtGui.QVBoxLayout()
        slider_layout.addWidget(gbox)
        slider_layout.addWidget(gbox_2)

        slider_group = QtGui.QGroupBox("Peak Selection")
        slider_group.setLayout(slider_layout)

        # add button for heat map generation
        self.hm_button = QtGui.QPushButton('Generate Heatmap')
        self.hm_button.clicked.connect(self.hm_make)

        # add button for image stack pop out window
        self.map_img = QtGui.QPushButton('View Image Stack')
        self.map_img.clicked.connect(self.img_stack)

        # add baseline correction button
        self.bg_test = QtGui.QPushButton('Baseline Correction')
        self.bg_test.clicked.connect(self.rb_test)

        # set the layout of main window, adding all widgets
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        layout.addWidget(self.button)
        layout.addWidget(splitter)
        layout.addWidget(slider_group)
        layout.addWidget(self.hm_button)
        layout.addWidget(self.map_img)
        layout.addWidget(self.bg_test)
        self.setLayout(layout)

    def plot(self):
        """"Create matplotlib plot for specific X and Y contained in my_collec"""

        # discards the old graph
        self.ax.hold(False)

        # get data from combo box
        curr_x = self.drop_down_x.itemText(self.drop_down_x.currentIndex())
        curr_y = self.drop_down_y.itemText(self.drop_down_y.currentIndex())

        # plot data
        spectra_list = self.my_collec.spectra
        for i, spectrum in enumerate(spectra_list):
            if (spectrum.x == float(curr_x)) and (spectrum.y == float(curr_y)):
                self.ax.scatter(*zip(*self.my_collec.spectra[i].info_flipped))
                self.ax.grid('on')

        # add left vert line
        self.vert_line = self.ax.axvline(x=0)

        # add right vert line
        self.vert_line_2 = self.ax.axvline(x=0)

        # refresh canvas
        self.canvas.draw()

    def selection_change(self):
        """If the X drop down value changes, get the matching Y's corresponding to the new X"""

        curr_x = self.drop_down_x.itemText(self.drop_down_x.currentIndex())
        curr_ys = list(self.my_collec.x_to_y.get(float(curr_x)))
        curr_ys = [str(each) for each in curr_ys]

        self.drop_down_y.clear()
        self.drop_down_y.addItems(curr_ys)

    def get_wavenums(self):
        """"Makes a list of all wavenums in spectra"""
        wavenums = []
        for spectrum in self.my_collec.spectra:
            wavenums = spectrum.info[1]

        wavenums.sort()
        return wavenums

    def sld_change(self):
        """If left and/or right slider changes, set respective text to correct wavenumber, move line
        vertical line to correct position"""

        self.vert_line.remove()
        self.vert_line_2.remove()

        curr_pos = self.sld.sliderPosition()
        curr_wavenum = self.wavenums[curr_pos]

        curr_pos_2 = self.sld_2.sliderPosition()
        curr_wavenum_2 = self.wavenums[curr_pos_2]

        self.textedit.setText(str(curr_wavenum))
        self.textedit_2.setText(str(curr_wavenum_2))

        self.vert_line = self.ax.axvline(x=curr_wavenum)
        self.vert_line_2 = self.ax.axvline(x=curr_wavenum_2)

        self.canvas.draw()

    def hm_make(self):
        """
        Generate heatmap using values selected from left and right sliders
        """
        curr_pos = self.sld.sliderPosition()
        curr_wavenum = self.wavenums[curr_pos]

        curr_pos_2 = self.sld_2.sliderPosition()
        curr_wavenum_2 = self.wavenums[curr_pos_2]

        self.ax.grid('off')
        self.gen_heatmap(curr_wavenum, curr_wavenum_2)

    def img_stack(self):
        """
        Show scrollable set of TIFF images
        """
        file_names = [
            f for f in sorted(os.listdir(self.path)) if f.endswith(".tiff")
        ]
        if len(file_names) == 0:
            self.map()
        self.stack.show()

    def bg_sub_test(self):
        """
        Background subtraction using linear regression method
        """
        curr_pos = self.sld.sliderPosition()
        curr_wavenum = self.wavenums[curr_pos]

        curr_pos_2 = self.sld_2.sliderPosition()
        curr_wavenum_2 = self.wavenums[curr_pos_2]

        curr_x = self.drop_down_x.itemText(self.drop_down_x.currentIndex())
        curr_y = self.drop_down_y.itemText(self.drop_down_y.currentIndex())

        spectra_list = self.my_collec.spectra
        for i, spectrum in enumerate(spectra_list):
            if (spectrum.x == float(curr_x)) and (spectrum.y == float(curr_y)):

                intens = self.my_collec.spectra[i].info[0]

                wavenums = self.my_collec.spectra[i].info[1]

                btwn_wavenums = []
                btwn_intens = []

                for i, wavenum in enumerate(wavenums):
                    if wavenum <= curr_wavenum_2 and wavenum >= curr_wavenum:
                        btwn_wavenums.append(wavenum)
                        btwn_intens.append(intens[i])

                new_y_list = []

                slope, intercept = self.lin_reg(btwn_wavenums, btwn_intens)

                for i, y in enumerate(intens):
                    fit_y = slope * wavenums[i] + intercept
                    y -= fit_y
                    if y < 0:
                        y = 0
                    new_y_list.append(y)

                print(len(wavenums), len(new_y_list))

                new_plot = np.column_stack((wavenums, new_y_list))
                self.ax.scatter(*zip(*new_plot))

                self.canvas.draw()

    def rb_test(self):
        """
        Background/baseline subtraction using 'rubberband correction' method
        """
        # get data from combo box
        curr_x = self.drop_down_x.itemText(self.drop_down_x.currentIndex())
        curr_y = self.drop_down_y.itemText(self.drop_down_y.currentIndex())

        # get vertex points
        curr_spec = None
        curr_spec_plt = None
        spectra_list = self.my_collec.spectra
        for i, spectrum in enumerate(spectra_list):
            if (spectrum.x == float(curr_x)) and (spectrum.y == float(curr_y)):
                curr_spec = self.my_collec.spectra[i]

        # Separate x and y values into two separate lists
        x = curr_spec.info[1]
        y = curr_spec.info[0]

        # Zip to create np array of (x, y) tuples
        zipped = np.column_stack((x, y))

        # Find the convex hull, where array v contains the indices of the convex hull
        # vertex points arranged in a counter clockwise direction
        v = ConvexHull(zipped).vertices

        # Rotate convex hull vertices until v starts from the lowest one
        v = np.roll(v, -v.argmin())

        # Leave only the ascending part
        v = v[:v.argmax()]

        # Create baseline using linear interpolation between vertices
        bsln = np.interp(x, x[v], y[v])

        # Find new y values using baseline
        new_y = []
        for i, point in enumerate(y):
            point -= bsln[i]
            new_y.append(point)

        # convert list of x and new y's into an np array of tuples
        x_y = np.column_stack((x, new_y))

        # plot the new spectrum
        self.ax.scatter(*zip(*x_y))

        self.ax.grid(which='both')

        # add left vert line
        self.vert_line = self.ax.axvline(x=0)

        # add right vert line
        self.vert_line_2 = self.ax.axvline(x=0)

        self.canvas.draw()