예제 #1
1
파일: tt4.py 프로젝트: imanmirzaie/qttests
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()
class dibujante2(QMainWindow):

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

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

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


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

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

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

    def draw(self):

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

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

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

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

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

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

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

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

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

    main_frame = QtGui.QWidget()

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

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

    main_frame.setLayout(vbox)

    axes.clear()

    # Plot the F-Distribution for dfB and dfW

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

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

    main_frame = QtGui.QWidget()

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

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

    main_frame.setLayout(vbox)

    axes.clear()

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

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

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

    canvas.draw()

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

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

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

        hbox = QtGui.QHBoxLayout()

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

        return main_frame
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
예제 #9
0
파일: histpanel.py 프로젝트: kjuraic/SAXS
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()
예제 #10
0
class PlotDialog(QDialog,Ui_Widget):
    def __init__(self, qApp, parent=None):
        super(PlotDialog, self).__init__(parent)
        
        self.server=Pyro4.Proxy("PYRONAME:simple_server")
        
        self.__app = qApp
        self.setupUi(self)
        self.setupTimer()
        
        self.dpi = 72
        self.fig = Figure((9.1, 5.2), dpi=self.dpi)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)
        self.verticalLayout.insertWidget(0,self.canvas)
        self.canvas.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Expanding)
        self.axes = self.fig.add_subplot(111)
        
    def update(self):
        list=self.server.fetch_data()
        self.axes.cla()
        if len(list)<51:
            self.axes.plot(list)
        else:
            self.axes.plot(list[-50:])
        self.canvas.draw()
        #print list
        #for debugging
        
    def setupTimer(self):
        #Create a QT Timer that will timeout every half-a-second
        #The timeout is connected to the update function
        self.timer = QTimer()
        self.timer.timeout.connect(self.update)
        self.timer.start(500)
예제 #11
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()
예제 #12
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)]
예제 #13
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()
예제 #14
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)
예제 #15
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()
예제 #17
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()
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)
예제 #19
0
class SimpleMplImageViewer(QtGui.QWidget):
    def __init__(self, parent=None):   
        QtGui.QWidget.__init__(self, parent)
        self.figure = Figure()
        self.figure.patch.set_alpha(0)
        self.canvas = FigureCanvasQTAgg(self.figure)
        self.axes = self.figure.add_subplot(1, 1, 1, axisbg='grey')
        self.axes.axis('off')
        self.axes.set_frame_on(False)
        
        layout = QtGui.QHBoxLayout()
        layout.addWidget(self.canvas)
        layout.setAlignment(QtCore.Qt.AlignLeft)
        self.setLayout(layout)
        self.rects = []
        self.normalize = False
  
    def show_image(self, img):
        print type(img), img.shape
        imgplot = self.axes.imshow(img, cm.Greys_r)
        if not self.normalize:
            imgplot.set_clim(0, 255)
        
        self.canvas.draw()  
        
    def highlight_cell(self, entries):
        for r in self.rects:
            r.remove()
        del self.rects
        self.rects = []
        for e in entries:
            m, q = e / 25, e % 25
            rect = self.axes.add_patch(Rectangle((q*60, m*60), 60, 60, facecolor='none', edgecolor="red"))
            self.rects.append(rect)
        self.canvas.draw()
예제 #20
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()
예제 #21
0
    def draw(self):
        """Override canvas draw method to support faster draw of overlays."""
        if self._plot._getDirtyPlot():  # Need a full redraw
            FigureCanvasQTAgg.draw(self)
            self._background = None  # Any saved background is dirty

        if (self._overlays or self._graphCursor or
                self._plot._getDirtyPlot() == 'overlay'):
            # There are overlays or crosshair, or they is just no more overlays

            # Specific case: called from resizeEvent:
            # avoid store/restore background, just draw the overlay
            if not self._insideResizeEventMethod:
                if self._background is None:  # First store the background
                    self._background = self.copy_from_bbox(self.fig.bbox)

                self.restore_region(self._background)

            # This assume that items are only on left/bottom Axes
            for item in self._overlays:
                self.ax.draw_artist(item)

            for item in self._graphCursor:
                self.ax.draw_artist(item)

            self.blit(self.fig.bbox)
예제 #22
0
파일: XRS_MainView.py 프로젝트: kif/Py2DeX
class MplAxes(object):
    def __init__(self, parent):
        self._parent = parent
        self._parent.resizeEvent = self.resize_graph
        self.create_axes()
        self.redraw_figure()

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

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

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

    def redraw_figure(self):
        self.figure.tight_layout(None, 0.8, None, None)
        self.canvas.draw()
예제 #23
0
class BarChart(QtGui.QDialog):
    """
        Implements mechanism for plotting of a bar chart for given data.
    """

    def __init__(self, bar_chart_name, ordinate_name, data_for_plotting, parent=None):
        """Make a instance of BarChart class.
        Args:
            bar_chart_name (str): It is a name of a bar chart.
            ordinate_name (str): It is a ordinate name of a bar chart.
            data_for_plotting (list): It is a data for plotting of a bar chart.
        """
        QtGui.QDialog.__init__(self, parent)
        self.data = data_for_plotting
        self.graph_name = bar_chart_name
        self.ordinate_name = ordinate_name

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

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

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

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

        self.setLayout(layout)
        self.plot()

    def plot(self):
        """Plot a bar chart on the window's frame."""
        # create an axis
        ax = self.figure.add_subplot(111)

        # discards the old graph
        ax.hold(False)
        # del data[0]

        number = len(self.data)
        x = np.arange(1, number + 1)
        y = [num for (s, num) in self.data]

        # labels = [ s for (s, num) in data ]
        width = 0.9
        self.figure = plt.bar(x, y, width, color="m")
        plt.title(_fromUtf8(self.graph_name))
        plt.ylabel(self.ordinate_name)
        plt.xlabel(u"Дата отправки пакета")
        labels = [s for (s, num) in self.data]
        plt.xticks(x + width / 2.0, labels)

        # refresh canvas
        self.canvas.draw()
예제 #24
0
class Window(QtGui.QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        # a figure instance to plot on

        self.fig = plt.subplots()
        self.ax = plt.subplots()

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

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

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



    def plot(self, x, y, label, color):

        # plot data
        self.ax.plot(x, y, label=label, color=color)

        # refresh canvas
        self.canvas.draw()

        self.ax.legend(loc=0)
예제 #25
0
class BarPlot():
    def __init__(self, parent=None):

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

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

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


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

        x = range(len(self.data))
        self.axes.bar(left=x, height=self.data, width=0.3, align='center',
                      alpha=0.44, picker=5)
        self.axes.lefend(loc="best")
        self.axes.xticks(x+w/2, ["image", "judge", "match"])
        self.canvas.draw()
예제 #26
0
class PlotOverview(qtgui.QWidget):
    def __init__(self, db):
        self.db = db
        self.fig = Figure()
        self.canvas = FigureCanvas(self.fig)
        super().__init__()

        lay_v = qtgui.QVBoxLayout()
        self.setLayout(lay_v)

        self.year = qtgui.QComboBox()
        self.year.currentIndexChanged.connect(self.plot)

        lay_h = qtgui.QHBoxLayout()
        lay_h.addWidget(self.year)
        lay_h.addStretch(1)
        lay_v.addLayout(lay_h)
        lay_v.addWidget(self.canvas)

        self.update()

    def update(self):
        constraints = self.db.get_constraints()
        current_year = self.year.currentText()
        self.year.clear()
        years = [y for y in range(min(constraints['start_date']).year, datetime.datetime.now().year + 1)]
        self.year.addItems([str(y) for y in years])
        try:
            self.year.setCurrentIndex(years.index(current_year))
        except ValueError:
            self.year.setCurrentIndex(len(years) - 1)

    def plot(self):
        self.fig.clf()
        ax = self.fig.add_subplot(111)

        worked = np.zeros((12, 34)) + np.nan

        year = int(self.year.currentText())
        for month in range(12):
            for day in range(calendar.monthrange(year, month + 1)[1]):
                date = datetime.date(year, month + 1, day + 1)
                if date < datetime.datetime.now().date():
                    t = self.db.get_worktime(date).total_seconds() / 60.0 - self.db.get_desiredtime(date)
                    worked[month, day] = t
                    ax.text(day, month, re.sub('0(?=[.])', '', ('{:.1f}'.format(t / 60))), ha='center', va='center')

        worked[:, 32:] = np.nansum(worked[:, :31], axis=1, keepdims=True)

        for month in range(12):
            ax.text(32.5, month, re.sub('0(?=[.])', '', ('{:.1f}'.format(worked[month, -1] / 60))), ha='center', va='center')

        ax.imshow(worked, vmin=-12*60, vmax=12*60, interpolation='none', cmap='coolwarm')
        ax.set_xticks(np.arange(31))
        ax.set_yticks(np.arange(12))
        ax.set_xticklabels(1 + np.arange(31))
        ax.set_yticklabels(calendar.month_name[1:])

        self.fig.tight_layout()
        self.canvas.draw()
예제 #27
0
class Main(QtGui.QMainWindow, _class_ui):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self,parent)
        self.setupUi(self)

       	self.widget = QtGui.QWidget()
        self.layout = QtGui.QVBoxLayout(self.widget)

        self.figure = plt.figure()
        self.canvas = FigureCanvas(self.figure)
        self.toolbar = NavigationToolbar(self.canvas, self)

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

        self.setLayout(self.layout)
        self.setCentralWidget(self.widget)

        self.data = data
        self.ancho = 0.3
        self.posicion = np.arange(len(self.data))

        self.ax = self.figure.add_subplot(111)
        self.bars = self.ax.bar(self.posicion, self.data, self.ancho, color='#6a7ea6')

        self.ax.set_yticks(range(0, 7)) #máximo de puntos eje Y
        self.ax.set_xticks(self.posicion +self.ancho /2) #posición eje X
        self.ax.set_xticklabels(labels) #mostrar etiquetas
        self.ax.set_xlim(-0.5, len(self.data)) #posición canvas

        self.canvas.draw()
예제 #28
0
class Window(QtGui.QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        self.figure = plt.figure()
        self.canvas = FigureCanvas(self.figure)
        self.toolbar = NavigationToolbar(self.canvas, self)
        self.button = QtGui.QPushButton('Plot')
        self.button.clicked.connect(self.plot)

        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(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()
예제 #29
0
def CreateLinePlot(x,y):

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

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

        hbox = QtGui.QHBoxLayout()

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

        return main_frame
예제 #30
0
class GraphView(qg.QWidget):
    def __init__(self, name='Name', title='Title', graph_title='Graph Title', parent = None):
        super(GraphView, self).__init__(parent)

        self.name = name
        self.graph_title = graph_title

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

    def clear(self):
        self.axes.clear()
    def plot(self,*args,**kwargs):
        self.axes.plot(*args,**kwargs)
    def draw(self):
        self.canvas.draw()
    def add_patch(self,patch):
        self.axes.add_patch(patch)
    def scatter(self,*args,**kwargs):
        self.axes.scatter(*args,**kwargs)
    def text(self,*args,**kwargs):
        self.axes.text(*args,**kwargs)
예제 #31
0
class PlotView(QFrame):
    """PlotView presents a matplotlib canvas with interaction possibilities. (picking and tooltip)"""
    def __init__(self):
        """Create a PlotView instance"""
        QFrame.__init__(self)
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        # setup some default data values
        self.data = PlotData()
        self.data.x_data_type = "number"
        self.data.setValid(False)

        self.plot_figure = PlotFigure()
        self.plot_settings = PlotSettings()

        self.canvas = FigureCanvas(self.plot_figure.getFigure())
        self.canvas.setParent(self)
        self.canvas.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        self.mouse_handler = MouseHandler(self)

    def toggleMember(self, line):
        gid = int(line.get_gid())
        if gid in self.plot_settings.getSelectedMembers():
            self.plot_settings.unselectMember(gid)
        else:
            self.plot_settings.selectMember(gid)

    @ert_gui.widgets.util.may_take_a_long_time
    def drawPlot(self):
        self.plot_figure.drawPlot(self.data, self.plot_settings)
        self.canvas.draw()

    def resizeEvent(self, event):
        QFrame.resizeEvent(self, event)
        self.canvas.resize(event.size().width(), event.size().height())

    def loadSettings(self, name):
        if self.data.isValid():
            plot_config_loader = PlotSettingsLoader()
            if not plot_config_loader.load(name, self.plot_settings):
                self.drawPlot()

    def saveSettings(self):
        if self.data.isValid():
            plot_config_saver = PlotSettingsSaver()
            plot_config_saver.save(self.data.getSaveName(), self.plot_settings)

    def setData(self, data):
        self.saveSettings()

        self.data = data

        self.loadSettings(self.data.getSaveName())

    def setXZoomFactors(self, xminf, xmaxf):
        self.plot_settings.setMinXZoom(xminf)
        self.plot_settings.setMaxXZoom(xmaxf)

    def setYZoomFactors(self, yminf, ymaxf):
        self.plot_settings.setMinYZoom(yminf)
        self.plot_settings.setMaxYZoom(ymaxf)

    def save(self):
        self.saveSettings()

        plot_generator = PlotGenerator(self.plot_settings.getPlotPath(),
                                       self.plot_settings.getPlotConfigPath())
        plot_generator.save(self.data)

    def saveAll(self):
        self.saveSettings()

        plot_generator = PlotGenerator(self.plot_settings.getPlotPath(),
                                       self.plot_settings.getPlotConfigPath())
        plot_generator.saveAll()

    def copyPlotSettings(self):
        plot_config_loader = PlotSettingsLoader()
        plot_config_loader.copy(self.plot_settings)

    def setPlotPath(self, plot_path):
        self.plot_settings.setPlotPath(plot_path)

    def setPlotConfigPath(self, path):
        self.plot_settings.setPlotConfigPath(path)

    def _selectedMemberIdentifier(self, artist):
        return artist.get_gid() in self.plot_settings.getSelectedMembers()

    def clearSelection(self):
        selected_lines = self.plot_figure.fig.findobj(
            self._selectedMemberIdentifier)
        for line in selected_lines:
            self.plot_settings.unselectMember(line.get_gid())

    def displayToolTip(self, event):
        if not self.data is None and not event.xdata is None and not event.ydata is None:
            if self.data.getXDataType() == "time":
                date = matplotlib.dates.num2date(event.xdata)
                self.setToolTip("x: %s y: %04f" %
                                (date.strftime("%d/%m-%Y"), event.ydata))
            else:
                self.setToolTip("x: %04f y: %04f" % (event.xdata, event.ydata))
        else:
            self.setToolTip("")

    def annotate(self, label, x, y, xt=None, yt=None):
        self.plot_settings.addAnnotation(label, x, y, xt, yt)

    def removeAnnotation(self, annotation_artist):
        annotations = self.plot_settings.getAnnotations()
        for annotation in annotations:
            if annotation.getUserData() == annotation_artist:
                self.plot_settings.removeAnnotation(annotation)

    def moveAnnotation(self, annotation_artist, xt, yt):
        annotations = self.plot_settings.getAnnotations()
        for annotation in annotations:
            if annotation.getUserData() == annotation_artist:
                annotation.xt = xt
                annotation.yt = yt

        annotation_artist.xytext = (xt, yt)

    def draw(self):
        self.canvas.draw()

    def setMinYLimit(self, value):
        self.plot_settings.setMinYLimit(value)

    def setMaxYLimit(self, value):
        self.plot_settings.setMaxYLimit(value)

    def setMinXLimit(self, value):
        self.plot_settings.setMinXLimit(value)

    def setMaxXLimit(self, value):
        self.plot_settings.setMaxXLimit(value)

    def getPlotConfigList(self):
        return self.plot_settings.getPlotConfigList()
예제 #32
0
class Plotter(QWidget, Ui_Plot):
    trigger = pyqtSignal()

    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.setupUi(self)

        self.btn_plot_update.clicked.connect(self.plot_data)
        self.plotter = Visualiser()
        self.start_figure()

        QToolTip.setFont(QFont("SansSerif", 11))
        self.label_51.setToolTip(
            "Wave direction expressed\nin the mesh coordinate system.\n0deg correspond to a wave travelling in the positive x-direction"
        )

        self.label_54.setToolTip(
            "Wave direction expressed\nin the North-South/West-East coordinate system.\n0deg correspond to a wave travelling from North to South"
        )

    def set_data(self, data):
        self._data = data
        if 'hyd' in data.keys() and not 'p_fit' in data.keys():
            self.enable_plot_area([1])
        elif 'p_fit' in data.keys():
            self.enable_plot_area([1, 2])
        else:
            self.enable_plot_area()

    def start_figure(self):
        fig = Figure()
        self.addmpl(fig)
        self.enable_plot_area()

    def rmmpl(self, ):
        self.mpl_vl.removeWidget(self.canvas)
        self.canvas.close()
        self.mpl_vl.removeWidget(self.toolbar)
        self.toolbar.close()

    def addmpl(self, fig):
        self.canvas = FigureCanvas(fig)
        self.mpl_vl.addWidget(self.canvas)
        self.canvas.draw()
        self.toolbar = NavigationToolbar(self.canvas,
                                         self.mpl_window,
                                         coordinates=True)
        self.mpl_vl.addWidget(self.toolbar)

    def plot_excitation(self):
        fig = self.plotter.show_diffraction_problem(
            int(self.cb_dofi.currentIndex()),
            float(self.cb_angle.currentIndex()))
        self.rmmpl()
        self.addmpl(fig)
#

    def plot_radiation(self):
        fig = self.plotter.show_radiation_problem(
            int(self.cb_dofi.currentIndex()),
            float(self.cb_dofj.currentIndex()))
        self.rmmpl()
        self.addmpl(fig)

    def plot_rao(self):
        fig = self.plotter.show_rao(int(self.cb_te.currentIndex()),
                                    int(self.cb_hm0.currentIndex()),
                                    int(self.cb_wavedir.currentIndex()),
                                    int(self.cb_dofi.currentIndex()),
                                    int(self.cb_angle.currentIndex()))
        self.rmmpl()
        self.addmpl(fig)

    def plot_power_matrix(self):
        fig = self.plotter.show_power_matrix(
            int(self.cb_wavedir.currentIndex()))
        self.rmmpl()
        self.addmpl(fig)

    def plot_k_fit(self):
        fig = self.plotter.show_k_fit(int(self.cb_te.currentIndex()),
                                      int(self.cb_hm0.currentIndex()),
                                      int(self.cb_wavedir.currentIndex()))
        self.rmmpl()
        self.addmpl(fig)

    def plot_c_fit(self):
        fig = self.plotter.show_c_fit(int(self.cb_te.currentIndex()),
                                      int(self.cb_hm0.currentIndex()),
                                      int(self.cb_wavedir.currentIndex()))
        self.rmmpl()
        self.addmpl(fig)

    def plot_original_power_matrix(self):
        fig = self.plotter.show_original_power_matrix(
            int(self.cb_wavedir.currentIndex()))
        self.rmmpl()
        self.addmpl(fig)

    def plot_user_power_matrix(self):
        fig = self.plotter.show_user_power_matrix(
            int(self.cb_wavedir.currentIndex()))
        self.rmmpl()
        self.addmpl(fig)

    def plot_mass(self):
        fig = self.plotter.show_mass()
        self.rmmpl()
        self.addmpl(fig)

    def plot_hydrostatic(self):
        fig = self.plotter.show_hst()
        self.rmmpl()
        self.addmpl(fig)

    def enable_plot_area(self, index=[]):
        self.plotter.set_hydrodynamic_data(None)
        self.plotter.set_performance_fit_data(None)
        if index:
            self.groupBox_11.setEnabled(True)
            self.groupBox_9.setEnabled(True)
            self.btn_plot_update.setEnabled(True)
            for ind in index:
                if ind == 1:
                    self.enable_hydrodynamic(True)
                    self.set_hydrodynamic_dimensions(True)
                    self.plotter.set_hydrodynamic_data(self._data['hyd'])
                elif ind == 2:
                    self.enable_motion(True)
                    self.set_motion_dimensions(True)
                    self.plotter.set_performance_fit_data(self._data['p_fit'])
                else:
                    pass
        else:
            self.groupBox_11.setEnabled(False)
            self.groupBox_9.setEnabled(False)
            self.btn_plot_update.setEnabled(False)
            self.enable_hydrodynamic(False)
            self.enable_motion(False)

    def enable_hydrodynamic(self, choice):
        self.rb_excitation.setEnabled(choice)
        self.rb_radiation.setEnabled(choice)
        self.rb_mass.setEnabled(choice)
        self.rb_stiffness.setEnabled(choice)
        self.rb_radiation.setChecked(True)

    def enable_motion(self, choice):
        self.c_fit.setEnabled(choice)
        self.k_fit.setEnabled(choice)
        self.rb_userpowermat.setEnabled(choice)
        self.rb_origpowermat.setEnabled(choice)
        self.rb_rao.setEnabled(choice)
        self.rb_powermat.setEnabled(choice)

    def set_motion_dimensions(self, stat):
        if stat:
            te = self._data['p_fit']['te'].tolist()
            te = [str(x) for x in te]
            hm0 = self._data['p_fit']['hm0'].tolist()
            hm0 = [str(x) for x in hm0]
            wave_dir = self._data['p_fit']['wave_dir']

            wave_dir_ne = angle_wrap(-wave_dir - np.pi / 2,
                                     'r2r') * 180 / np.pi
            wave_dir = [str(x) for x in wave_dir_ne.tolist()]

            self.cb_te.clear()
            self.cb_te.addItems(te)
            self.cb_hm0.clear()
            self.cb_hm0.addItems(hm0)
            self.cb_wavedir.clear()
            self.cb_wavedir.addItems(wave_dir)
        else:
            self.cb_te.clear()
            self.cb_hm0.clear()
            self.cb_wavedir.clear()

    def set_hydrodynamic_dimensions(self, stat):
        if stat:
            angle = self._data['hyd']['directions'].tolist()
            angle = [str(x) for x in angle]
            dofi = range(self._data['hyd']['m_m'].shape[0])
            dofi = [str(x) for x in dofi]
            self.cb_angle.clear()
            self.cb_angle.addItems(angle)
            self.cb_dofi.clear()
            self.cb_dofi.addItems(dofi)
            self.cb_dofj.clear()
            self.cb_dofj.addItems(dofi)
        else:
            self.cb_angle.clear()
            self.cb_dofi.clear()
            self.cb_dofj.clear()

    def plot_data(self):
        # check which tab is active first
        active_rb = [
            ix for ix, x in enumerate(self.groupBox_9.children())
            if ix > 0 and x.isChecked()
        ]

        if active_rb[0] == 1:
            self.plot_radiation()
        elif active_rb[0] == 2:
            self.plot_excitation()
        elif active_rb[0] == 3:
            self.plot_mass()
        elif active_rb[0] == 4:
            self.plot_hydrostatic()
        elif active_rb[0] == 5:
            self.plot_c_fit()
        elif active_rb[0] == 6:
            self.plot_k_fit()
        elif active_rb[0] == 7:
            self.plot_original_power_matrix()
        elif active_rb[0] == 8:
            self.plot_user_power_matrix()
        elif active_rb[0] == 9:
            self.plot_power_matrix()
        elif active_rb[0] == 10:
            self.plot_rao()
        elif active_rb[0] == 11:
            pass
예제 #33
0
class MatplotlibWidget(QtGui.QWidget):
    """This class is a QWidget for pyNEMO mask plot"""
    min_depth = 200.0
    shelfbreak_dist = 200.0
    mask_type = 0
    def __init__(self, parent=None, mask=None, min_depth = 200.0, shelfbreak_dist = 200.0,*args, **kwargs):
        """ Initialises the mask, matplot and the navigation toolbar """
        super(MatplotlibWidget, self).__init__(parent)
        #QtGui.QWidget.__init__(self, parent)
        self.figure = Figure(*args, **kwargs)
        self.canvas = FigureCanvas(self.figure)
        self.mask = mask
        self.min_depth = min_depth
        self.shelfbreak_dist = shelfbreak_dist
        if self.mask is not None:
            self.mask.min_depth = min_depth
            self.mask.shelfbreak_dist = shelfbreak_dist
        self.toolbar = NemoNavigationToolbar(self.canvas, self)
        self.toolbar.locLabel.setMinimumWidth(100)
        self.toolbar.locLabel.setMaximumWidth(170)
        self.toolbar.locLabel.setSizePolicy(QSizePolicy.Fixed,QSizePolicy.Fixed)
        self.toolbar.locLabel.setAlignment(Qt.AlignLeft|Qt.AlignTop)
        self.toolbar.drawing_tool.connect(self.drawing_tool_callback)
        self.axes = self.figure.add_subplot(111)
        self.cbar = None
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        self.setLayout(layout)
        self._drawing_tool = None
        self._drawing_tool_name = None
        self.create_basemap()

    @pyqtSlot(str)
    def drawing_tool_callback(self, toolname):
        """ callback for the drawing tool when the signal of change of drawing tool is
        received"""
        if self._drawing_tool_name != None and toolname == "": #if tool is disabled
            self._drawing_tool.disable()
            self._drawing_tool_name = None
            self._drawing_tool = None
            self.canvas.draw()
        else:
            self._drawing_tool_name = toolname
            if self._drawing_tool_name == "freehand": #if freehand tool is enabled
                self._drawing_tool = PolygonEditor(self.axes, self.canvas)
                self.canvas.draw()
            elif self._drawing_tool_name == "rectangle": #if rectange tool is enabled
                self._drawing_tool = BoxEditor(self.axes, self.canvas)
                self._drawing_tool.enable()
                self.canvas.draw()

    def create_basemap(self):
        """ Draws the basemap and contour with mask information"""
        if self.mask == None:
            return

        x = np.arange(0, self.mask.lon.shape[0])
        y = np.arange(0, self.mask.lon.shape[1])
        x_vals, y_vals = np.meshgrid(y, x)
        Z = self.mask.bathy_data[...].astype(np.float64)
        #Z[Z==0] = np.nan
        Z = np.ma.masked_where(Z==0, Z)
        cmap = plt.get_cmap('GnBu')
        cmap.set_bad('0.0')
        cmap.set_under('black',1.0)
        cmap.set_over('black',1.0)
        transcmap = plt.get_cmap('autumn')
        transcmap.set_bad(alpha=0.5)
        masklayer = np.ma.masked_where(self.mask.data==-1,self.mask.data)
        extent = (0, self.mask.lon.shape[1],0, self.mask.lon.shape[0])
        #cax = self.axes.pcolormesh(x_vals, y_vals, Z, cmap=cmap)#, extend='min')#cmap=plt.get_cmap('GnBu'))#cmap=cm.s3pcpn)
        cax = self.axes.imshow(Z, cmap = cmap, origin="lower",extent=extent,aspect='auto')
        #self.axes.contourf(x_vals, y_vals, masklayer, [-2, -1, 0, 1, 2], cmap=transcmap,\
        #                   alpha=mask_alpha)
        self.axes.imshow(masklayer, cmap=transcmap,alpha=0.3,origin="lower",extent=extent,aspect='auto')

        zmin = np.amin(Z)
        zmax = np.amax(Z)
        if self.cbar is not None:
            self.cbar.remove()
        self.cbar = self.figure.colorbar(cax,ticks=np.linspace(zmin,zmax,10),orientation='horizontal')
        self.cbar.set_label("Bathymetry (units=%s)"%self.mask.data_units)
        self.canvas.draw()

    
    def reset_mask(self):
        if self.mask == None:
            return             
        self.mask.reset_mask()
        self.axes.clear()
        self.create_basemap()
        
    def add_mask(self):
        """ adds the selected region in the drawing tool to the mask """
        if self._drawing_tool_name != "" and self.mask != None:
            if self._drawing_tool.polygon != None:
                x = np.arange(0, self.mask.lon.shape[0])
                y = np.arange(0, self.mask.lon.shape[1])
                x_vals, y_vals = np.meshgrid(y, x)
                grid = zip(x_vals.ravel(), y_vals.ravel())
                
                self._drawing_tool.polygon.set_linewidth(1.0)
                p_path = Path(self._drawing_tool.polygon.xy)
                index = p_path.contains_points(grid)
                index = index.reshape(self.mask.lon.shape)
                xmin, ymin = np.min(self._drawing_tool.polygon.xy, axis=0)
                xmax, ymax = np.max(self._drawing_tool.polygon.xy, axis=0)
                self.mask.add_mask(index,[xmin,xmax,ymin,ymax])
                self._drawing_tool.reset()
                self.axes.clear()
                self.create_basemap()

    def remove_mask(self):
        """ removes the selected region in the drawing tool from the mask """
        if self._drawing_tool_name != "" and self.mask != None:
            if self._drawing_tool.polygon != None:
                x = np.arange(0, self.mask.lon.shape[0])
                y = np.arange(0, self.mask.lon.shape[1])
                x_vals, y_vals = np.meshgrid(y, x)
                grid = zip(x_vals.ravel(), y_vals.ravel()) #check for the index

                self._drawing_tool.polygon.set_linewidth(1.0)
                p_path = Path(self._drawing_tool.polygon.xy)
                index = p_path.contains_points(grid)
                index = index.reshape(self.mask.lon.shape)
                xmin, ymin = np.min(self._drawing_tool.polygon.xy, axis=0)
                xmax, ymax = np.max(self._drawing_tool.polygon.xy, axis=0)                
                self.mask.remove_mask(index,[xmin,xmax,ymin,ymax])
                self._drawing_tool.reset()
                self.axes.clear()
                self.create_basemap()

    def apply_border_mask(self):
        """ This applies an mask of given number of pixels at the border of the mask"""
        pixels, ok_btn_pressed = QtGui.QInputDialog.getText(self, 'Mask: Border Input',
                                                            'Enter number of pixel of border \
                                                             to be added to mask:')
        if ok_btn_pressed:
            self.mask.apply_border_mask(int(pixels))
            self.axes.clear()
            self.create_basemap()

    def set_mask_type(self,type):
        """ Sets the mask type """
        self.mask_type = type
        self.mask.mask_type = type
        
    @pyqtSlot(str, str)
    def set_bathymetry_file(self, bathymetry_filename, mask_file):
        """ Set the bathymetry file """
        try:
            self.mask = Mask(bathymetry_filename, mask_file, self.min_depth, self.shelfbreak_dist)
            self.mask.mask_type = self.mask_type
            self.create_basemap()
        except RuntimeError:
            pass # couldn't set the new file name
        
    @pyqtSlot(str)
    def save_mask_file(self, mask_file):
        """ Save the mask data to mask_file """
        if self.mask is not None:
            self.mask.save_mask(mask_file)
            
    @pyqtSlot(float, float)
    def set_mask_settings(self, min_depth, shelfbreak_dist):
        """ Mask settings update """
        self.min_depth = min_depth
        self.shelfbreak_dist = shelfbreak_dist
        self.mask.min_depth = min_depth
        self.mask.shelfbreak_dist = shelfbreak_dist
예제 #34
0
class StatistDialog(QDialog, Ui_StatistDialog):
    def __init__(self, iface):
        QDialog.__init__(self)
        self.iface = iface
        self.setupUi(self)

        # add matplotlib figure to dialog
        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)
        self.canvas = FigureCanvas(self.figure)
        self.mpltoolbar = NavigationToolbar(self.canvas, self.widgetPlot)
        lstActions = self.mpltoolbar.actions()
        self.mpltoolbar.removeAction(lstActions[7])
        self.layoutPlot.addWidget(self.canvas)
        self.layoutPlot.addWidget(self.mpltoolbar)

        # and configure matplotlib params
        rcParams["font.serif"] = "Verdana, Arial, Liberation Serif"
        rcParams["font.sans-serif"] = "Tahoma, Arial, Liberation Sans"
        rcParams["font.cursive"] = "Courier New, Arial, Liberation Sans"
        rcParams["font.fantasy"] = "Comic Sans MS, Arial, Liberation Sans"
        rcParams["font.monospace"] = "Courier New, Liberation Mono"

        self.values = None

        self.btnOk = self.buttonBox.button(QDialogButtonBox.Ok)
        self.btnClose = self.buttonBox.button(QDialogButtonBox.Close)

        self.cmbLayers.currentIndexChanged.connect(self.reloadFields)
        self.chkUseTextFields.stateChanged.connect(self.reloadFields)

        self.chkShowGrid.stateChanged.connect(self.refreshPlot)
        self.chkAsPlot.stateChanged.connect(self.refreshPlot)
        self.btnRefresh.clicked.connect(self.refreshPlot)

        self.manageGui()
        self.axes.set_title(self.tr("Frequency distribution"))

    def manageGui(self):
        self.cmbLayers.clear()
        self.cmbLayers.addItems(utils.getVectorLayerNames())

        self.btnRefresh.setEnabled(False)

    def reloadFields(self):
        self.cmbFields.clear()

        self.axes.clear()
        self.lstStatistics.clearContents()
        self.lstStatistics.setRowCount(0)

        self.spnMinX.setValue(0.0)
        self.spnMaxX.setValue(0.0)

        layer = utils.getVectorLayerByName(self.cmbLayers.currentText())

        if layer.selectedFeatureCount() != 0:
            self.chkUseSelected.setCheckState(Qt.Checked)
        else:
            self.chkUseSelected.setCheckState(Qt.Unchecked)

        if self.chkUseTextFields.checkState():
            self.cmbFields.addItems(
                utils.getFieldNames(layer, [QVariant.String]))
        else:
            self.cmbFields.addItems(
                utils.getFieldNames(layer, [QVariant.Int, QVariant.Double]))

    def accept(self):
        self.axes.clear()
        self.spnMinX.setValue(0.0)
        self.spnMaxX.setValue(0.0)
        self.lstStatistics.clearContents()
        self.lstStatistics.setRowCount(0)

        layer = utils.getVectorLayerByName(self.cmbLayers.currentText())

        if self.chkUseSelected.isChecked() and \
                layer.selectedFeatureCount() == 0:
            QMessageBox.warning(
                self, self.tr('No selection'),
                self.tr('There is no selection in input '
                        'layer. Uncheck corresponding option '
                        'or select some features before '
                        'running analysis'))
            return

        self.workThread = statistthread.StatistThread(
            layer, self.cmbFields.currentText(),
            self.chkUseSelected.isChecked())
        self.workThread.rangeChanged.connect(self.setProgressRange)
        self.workThread.updateProgress.connect(self.updateProgress)
        self.workThread.processFinished.connect(self.processFinished)
        self.workThread.processInterrupted.connect(self.processInterrupted)

        self.btnOk.setEnabled(False)
        self.btnClose.setText(self.tr("Cancel"))
        self.buttonBox.rejected.disconnect(self.reject)
        self.btnClose.clicked.connect(self.stopProcessing)

        self.workThread.start()

    def reject(self):
        QDialog.reject(self)

    def setProgressRange(self, maxValue):
        self.progressBar.setRange(0, maxValue)

    def updateProgress(self):
        self.progressBar.setValue(self.progressBar.value() + 1)

    def processFinished(self, statData):
        self.stopProcessing()

        # populate table with results
        self.tableData = statData[0]
        self.values = statData[1]
        rowCount = len(self.tableData)
        self.lstStatistics.setRowCount(rowCount)
        for i in xrange(rowCount):
            tmp = self.tableData[i].split(":")
            item = QTableWidgetItem(tmp[0])
            self.lstStatistics.setItem(i, 0, item)
            item = QTableWidgetItem(tmp[1])
            self.lstStatistics.setItem(i, 1, item)

        self.lstStatistics.resizeRowsToContents()

        self.btnRefresh.setEnabled(True)

        # create histogram
        self.refreshPlot()

        self.restoreGui()

    def processInterrupted(self):
        self.restoreGui()

    def stopProcessing(self):
        if self.workThread is not None:
            self.workThread.stop()
            self.workThread = None

    def restoreGui(self):
        self.progressBar.setFormat("%p%")
        self.progressBar.setRange(0, 1)
        self.progressBar.setValue(0)

        self.buttonBox.rejected.connect(self.reject)
        self.btnClose.clicked.disconnect(self.stopProcessing)
        self.btnClose.setText(self.tr("Close"))
        self.btnOk.setEnabled(True)

    def refreshPlot(self):
        self.axes.clear()
        self.axes.set_title(self.tr("Frequency distribution"))
        interval = None

        if self.values is None:
            return

        if self.spnMinX.value() == self.spnMaxX.value():
            pass
        else:
            interval = []
            if self.spnMinX.value() > self.spnMaxX.value():
                interval.append(self.spnMaxX.value())
                interval.append(self.spnMinX.value())
            else:
                interval.append(self.spnMinX.value())
                interval.append(self.spnMaxX.value())

        if not self.chkAsPlot.isChecked():
            self.axes.hist(self.values,
                           18,
                           interval,
                           alpha=0.5,
                           histtype="bar")
        else:
            n, bins, pathes = self.axes.hist(self.values,
                                             18,
                                             interval,
                                             alpha=0.5,
                                             histtype="bar")
            self.axes.clear()
            c = []
            for i in range(len(bins) - 1):
                s = bins[i + 1] - bins[i]
                c.append(bins[i] + (s / 2))

            self.axes.plot(c, n, "ro-")

        self.axes.grid(self.chkShowGrid.isChecked())
        self.axes.set_ylabel(unicode(self.tr("Count")))
        self.axes.set_xlabel(unicode(self.cmbFields.currentText()))
        self.figure.autofmt_xdate()
        self.canvas.draw()

    def keyPressEvent(self, event):
        if event.modifiers() in [Qt.ControlModifier, Qt.MetaModifier
                                 ] and event.key() == Qt.Key_C:
            clipboard = QApplication.clipboard()
            clipboard.setText("\n".join(self.tableData))
        else:
            QDialog.keyPressEvent(self, event)
예제 #35
0
class Watcher(QMainWindow):
    """"""
    def __init__(self, freezer, parent=None):
        """Constructor for Viewer"""
        self.freezer = freezer
        self.numTrials = 0
        self.currTrialNum = 0
        self.allTrials = None
        self.allAlignedTrials = None
        self.allOnsets = None
        self.idList = None

        # # Useful stuff
        self.onsetLine1 = None
        self.onsetLine2 = None

        self.isDragging = False

        QMainWindow.__init__(self, parent)
        # self.showMaximized()
        self.createMainFrame()
        # self.drawTrial()

    def queryData(self, queryStr):
        """Query some data from freezer
        """

        self.idList = []

        self.allTrials = []
        self.allAlignedTrials = []
        self.allOnsets = []

        self.allQueryResults = {
        }  # {'idxxx': {'var1':value1, 'var2':value2...}}
        self.queryStr = queryStr

        # allDocs = self.freezer.processed.find(eval(self.queryStr))
        allDocs = self.freezer.posts.find(eval(self.queryStr))
        for doc in allDocs:
            s = StringIO.StringIO(doc['trialData'])
            tTrialData = pd.read_csv(s)
            self.allTrials.append(tTrialData)

            t = 0  #doc['timeOnset']
            self.allOnsets.append(t)

            tId = doc['_id']
            self.idList.append(tId)

            self.allQueryResults[tId] = {
                'isAccepted': doc['isAccepted'],
                'trialData': tTrialData,
                'timeOnset': int(0.0)
            }

        self.numTrials = len(self.allTrials)

        # self.allAlignedTrials = [t for t in self.allTrials]
        print "Found", self.numTrials, "trials."

    def freezeAllOnsets(self):
        """Freeze timeOnset field in Freezer
        """
        allDocs = self.freezer.processed.find(eval(self.queryStr))
        try:
            for onset, doc in zip(self.allOnsets, allDocs):
                self.freezer.processed.update({'_id': doc['_id']},
                                              {'$set': {
                                                  'timeOnset': onset
                                              }})
            print("Froze %d onsets" % len(self.allOnsets))
        except:
            print("Error updating")

    def freezeAllIsAccepted(self):
        """Freeze timeOnset field in Freezer
        """
        allDocs = self.freezer.processed.find(eval(self.queryStr))
        try:
            for isAccepted, doc in zip(
                    self.allQueryResults[self.idList[self.currTrialNum]]
                ['isAccepted'], allDocs):
                print isAccepted, doc['_id']
                self.freezer.processed.update(
                    {'_id': doc['_id']}, {'$set': {
                        'isAccepted': isAccepted
                    }})
            print("Froze %d isAccepted flags" % len(self.allIsAccepted))
        except:
            print("Error updating")

    def freezeAllQueryResults(self):
        """Freeze timeOnset field in Freezer
        """
        try:
            for id in self.idList:
                print id, {
                    'isAccepted': self.allQueryResults[id]['isAccepted']
                }
                self.freezer.processed.update({'_id': id}, {
                    '$set': {
                        'isAccepted': self.allQueryResults[id]['isAccepted'],
                        'timeOnset': int(self.allQueryResults[id]['timeOnset'])
                    }
                })
            print("Froze %d isAccepted flags" % len(self.idList))
        except:
            print("Error freezing")

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

        self.fig = Figure((5.0, 4.0), dpi=100)
        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)

        ### Linking some events
        self.canvas.mpl_connect('key_press_event', self.onKey)
        self.canvas.mpl_connect('pick_event', self.onPick)
        self.canvas.mpl_connect('button_press_event', self.onMouseDown)
        self.canvas.mpl_connect('button_release_event', self.onMouseUp)
        self.canvas.mpl_connect('motion_notify_event', self.onMouseMotion)

        self.textbox = QTextEdit("""{"analystName": "zcwaxs"}
                                 """)
        self.textbox.selectAll()
        self.textbox.setMinimumWidth(200)

        self.queryButton = QPushButton("&Query")
        self.connect(self.queryButton, SIGNAL('clicked()'), self.onSubmitQuery)

        self.fwdButton = QPushButton("&>>")
        self.connect(self.fwdButton, SIGNAL('clicked()'), self.onFwd)

        self.bwdButton = QPushButton("&<<")
        self.connect(self.bwdButton, SIGNAL('clicked()'), self.onBwd)

        self.alignButton = QPushButton("&Close")
        self.connect(self.alignButton, SIGNAL('clicked()'), self.onFinish)

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

        self.isAcceptedCB = QCheckBox("Accept?")
        self.isAcceptedCB.setChecked(False)
        self.connect(self.isAcceptedCB, SIGNAL('stateChanged(int)'),
                     self.onChangeIsAccepted)

        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.onSlider)

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

        for w in [
                self.textbox, self.queryButton, self.isAcceptedCB,
                self.bwdButton, self.fwdButton, self.alignButton, 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 drawCurrTrial(self):
        self.fig.clear()
        self.fig.hold(True)
        self.ax1 = self.fig.add_subplot(211)
        self.ax2 = self.fig.add_subplot(212)

        self.ax1.plot(self.currTrial['Left Shoulder Flex / Time'])
        self.ax1.set_ylim([20, 120])
        self.ax2.plot(self.currTrial['Biceps'])
        self.ax2.set_ylim([-1.0, 1.0])

        ### Draw timeOnset lines
        self.onsetLine1 = self.ax1.axvline(x=self.currOnset(),
                                           ymin=0,
                                           ymax=100,
                                           color='b',
                                           linewidth=5)
        self.onsetLine2 = self.ax2.axvline(x=self.currOnset(),
                                           ymin=0,
                                           ymax=100,
                                           color='r',
                                           linewidth=5)

        self.canvas.draw()

    def currOnset(self):
        return self.allQueryResults[self.idList[
            self.currTrialNum]]['timeOnset']

    def setOnset(self):
        """Add the field 'onset' to all documents"""
        l = self.currTrial['Left Shoulder Flex / Time'][0:800]
        base = sum(l) / float(len(l))
        th = base * 0.98
        f = lambda x: x <= th

        possible = indices(f, self.currTrial['Left Shoulder Flex / Time'])
        tOnset = possible[0]
        self.allOnsets[self.currTrialNum] = tOnset
        self.allQueryResults[self.idList[
            self.currTrialNum]]['timeOnset'] = int(tOnset)


#        self.allAlignedTrials[self.currTrialNum] = self.currTrial.drop(xrange(self.currOnset - 100))

    def setPickedOnsetLine(self, artist):
        self.onsetLine1 = artist
        self.onsetLine1.set_color('g')

    def setCurrTrial(self, n=0):
        self.currTrialNum = n
        # print(len(self.allTrials))
        # self.currTrial = self.allTrials[self.currTrialNum]
        self.currTrial = self.allQueryResults[self.idList[n]]['trialData']
        # print(self.currTrialNum, len(self.currTrial))
        self.isAcceptedCB.setChecked(
            self.allQueryResults[self.idList[n]]['isAccepted'])
        self.setOnset()

    def setOnsetLine(self, new_x):
        xs, ys = self.onsetLine1.get_data()
        #new_xs = [min(rbound, max(lbound, new_x)) for xx in xs]
        self.onsetLine1.set_data(new_x, ys)
        self.onsetLine2.set_data(new_x, ys)
        self.allQueryResults[self.idList[
            self.currTrialNum]]['timeOnset'] = new_x
        self.canvas.draw()

    def onPick(self, event):
        self.setPickedOnsetLine(event.artist)
        self.canvas.draw()

    def onMouseDown(self, event):
        self.isDragging = True

    def onMouseUp(self, event):
        self.isDragging = False

    def onMouseMotion(self, event):
        if self.isDragging:
            self.setOnsetLine(event.xdata)

    def onKey(self, event):
        if event.key in '[':
            xs, ys = self.onsetLine1.get_data()
            new_xs = [xx - 20 for xx in xs]
            self.onsetLine1.set_data(new_xs, ys)
        elif event.key in ']':
            xs, ys = self.onsetLine1.get_data()
            new_xs = [xx + 20 for xx in xs]
            self.onsetLine1.set_data(new_xs, ys)
        elif event.key in '{':
            xs, ys = self.onsetLine1.get_data()
            new_xs = [xx - 100 for xx in xs]
            self.onsetLine1.set_data(new_xs, ys)
        elif event.key in '}':
            xs, ys = self.onsetLine1.get_data()
            new_xs = [xx + 100 for xx in xs]
            self.onsetLine1.set_data(new_xs, ys)
        self.canvas.draw()

    def onFwd(self):
        """Go forward 1 trial"""
        self.setCurrTrial(min(self.currTrialNum + 1, self.numTrials - 1))
        self.drawCurrTrial()
        # self.setOnset()
        # self.setOnsetLine()

    def onBwd(self):
        """Go backward 1 trial"""
        self.setCurrTrial(max(self.currTrialNum - 1, 0))
        self.drawCurrTrial()
        # self.setOnset()
        # self.setOnsetLine()

    def onChangeIsAccepted(self, value):
        self.allQueryResults[self.idList[self.currTrialNum]]['isAccepted'] = \
            True if value == 2 else False

    def onFinish(self):
        # self.freezeAllOnsets()
        self.freezeAllQueryResults()
        self.close()

    def onSubmitQuery(self):
        self.queryData(str(self.textbox.toPlainText()))
        self.setCurrTrial()

        self.drawCurrTrial()
예제 #36
0
class imviu(QtGui.QWidget):
    def __init__(self):
        super(imviu, self).__init__()
        self.resize(1600, 800)
        self.setWindowTitle('Image Plot')
        self.browse = QtGui.QFileDialog
        self.figure = plt.figure()
        self.canvas = FigureCanvas(self.figure)
        self.btn = QtGui.QPushButton('open image file', self)
        self.btn.clicked.connect(self.openimg)
        self.btn.move(0, 50)
        self.btn1 = QtGui.QPushButton('plot rgb', self)
        self.btn1.clicked.connect(self.plotimg)
        self.btn1.move(1000, 50)
        self.grid = QtGui.QGridLayout()
        self.grid.setSpacing(10)
        self.grid.addWidget(self.canvas, 2, 2, 10, 1)
        self.grid.addWidget(self.btn, 1, 1)
        self.grid.addWidget(self.btn1, 1, 2)
        self.setLayout(self.grid)

    def plotimg(self):
        im = Image.open(self.nameF)
        pix = im.load()
        t = 0
        pixelr = []
        pixelb = []
        pixelg = []
        for i in range(im.size[0]):
            for j in range(im.size[1]):
                pixelr.append(pix[i, j][0])
                pixelb.append(pix[i, j][1])
                pixelg.append(pix[i, j][2])
        pixelr = Counter(pixelr)
        pixelry = pixelr.values()
        pixelrx = pixelr.keys()
        pixelb = Counter(pixelb)
        pixelby = pixelb.values()
        pixelbx = pixelb.keys()
        pixelg = Counter(pixelg)
        pixelgy = pixelg.values()
        pixelgx = pixelg.keys()

        ax = self.figure.add_subplot(311)
        ax.hold(False)
        ax.plot(pixelrx, pixelry, 'red')
        plt.xticks(range(0, 256, 10))
        ax1 = self.figure.add_subplot(312)
        ax1.hold(False)
        ax1.plot(pixelbx, pixelby, 'blue')
        ax2 = self.figure.add_subplot(313)
        ax2.hold(False)
        ax2.plot(pixelgx, pixelgy, 'green')
        self.canvas.draw()

    def openimg(self):
        filename = self.browse.getOpenFileNames(directory="./")
        self.nameF = str(list(filename)[0])
        pixmap = QtGui.QPixmap(self.nameF)
        lbl = QtGui.QLabel(self)
        lbl.setFixedSize(675, 650)
        lbl.setPixmap(pixmap)
        self.grid.addWidget(lbl, 2, 1, 3, 1)
예제 #37
0
class PrettyWidget(QtGui.QTabWidget):
    def __init__(self):
        super(PrettyWidget, self).__init__()
        self.initUI()

    def initUI(self):
        self.showMaximized()
        self.setWindowTitle('HK data')

        stylesheet = """QTabWidget::tab-bar {alignment: center;}"""
        self.setStyleSheet(stylesheet)

        #   adding tab1
        tab1 = QtGui.QWidget()
        self.addTab(tab1, 'House Keeping')
        grid = QtGui.QGridLayout()
        tab1.setLayout(grid)

        #   All below inserted into tab (Until new tab is inserted)
        #Inserting buttons
        btn1 = QtGui.QPushButton('Plot 1', self)
        btn1.resize(btn1.sizeHint())
        btn1.clicked.connect(self.plot1)
        grid.addWidget(btn1, 3, 0, 1, 1)

        btn2 = QtGui.QPushButton('Plot 2', self)
        btn2.resize(btn2.sizeHint())
        btn2.clicked.connect(self.plot2)
        grid.addWidget(btn2, 3, 1, 1, 1)

        btn3 = QtGui.QPushButton('Plot 3', self)
        btn3.resize(btn3.sizeHint())
        btn3.clicked.connect(self.plot3)
        grid.addWidget(btn3, 3, 2, 1, 1)

        btn4 = QtGui.QPushButton('Plot 4', self)
        btn4.resize(btn4.sizeHint())
        btn4.clicked.connect(self.plot4)
        grid.addWidget(btn4, 3, 3, 1, 1)

        #       Inserting canvasses on which the animated figures will be plottet
        self.figure1 = f1
        self.canvas1 = FigureCanvas(self.figure1)
        grid.addWidget(self.canvas1, 2, 0)

        self.figure2 = f2
        self.canvas2 = FigureCanvas(self.figure2)
        grid.addWidget(self.canvas2, 2, 1)

        self.figure3 = f3
        self.canvas3 = FigureCanvas(self.figure3)
        grid.addWidget(self.canvas3, 2, 2)

        self.figure4 = f4
        self.canvas4 = FigureCanvas(self.figure4)
        grid.addWidget(self.canvas4, 2, 3)

        #       Inserting main canvas
        self.figure = plt.figure(figsize=(50, 8))
        self.figure.patch.set_alpha(0)
        self.canvas = FigureCanvas(self.figure)
        grid.addWidget(self.canvas, 1, 0, 1, 4)
        self.show()

        #   Tab 2 - ErrorHandling
        #       Here tab2 is initiated
        tab2 = QtGui.QWidget()
        self.addTab(tab2, 'Error Handling')
        grid = QtGui.QGridLayout()
        tab2.setLayout(grid)
        grid.setSpacing(15)

        #       Labels for the two text editors were one can see and write regarding recorded errors.
        label_ed = QtGui.QLabel(self)
        label_ed.setText(
            'Here you see the amount of errors recorded in the Error-Testfile.txt'
        )
        grid.addWidget(label_ed, 2, 0, 1, 1)
        label_ev = QtGui.QLabel(self)
        label_ev.setText('Insert the integer of the error you want to display')
        grid.addWidget(label_ev, 1, 0, 1, 1)

        #       Here i design a textbox that can only be read (not accesed by user), it shows the # of errors
        global errordisplay
        errordisplay = QtGui.QLineEdit(self)
        errordisplay.setReadOnly(True)
        errordisplay.setText("recorded errors  =  " + str(recorded_errors))
        grid.addWidget(errordisplay, 2, 1, 1, 1)

        #       Here i design a textbox that will read the user input (An integer of #error)
        global errorvalue
        errorvalue = QtGui.QLineEdit(self)
        errorvalue.resize(1, 1)
        grid.addWidget(errorvalue, 1, 1, 1, 1)
        errorvalue.resize(1, 1)

        #       Here i design a button which will plot the error, assigned by the user input above
        ploterror = QtGui.QPushButton('Plot chosen error in the window above',
                                      self)
        ploterror.resize(ploterror.sizeHint())
        ploterror.clicked.connect(self.Perror)
        grid.addWidget(ploterror, 1, 2, 1, 1)

        #       Here i design a button that will display current number of recorded errors
        UpdateError = QtGui.QPushButton(
            'Update the display of recorded errors', self)
        UpdateError.resize(UpdateError.sizeHint())
        UpdateError.clicked.connect(self.Uerror)
        grid.addWidget(UpdateError, 2, 2, 1, 1)

        #       Here i design the canvas on which the recorded error will be drawn
        self.errorplot = plt.figure()
        self.errorplot.patch.set_alpha(0)
        self.errorcanvas = FigureCanvas(self.errorplot)
        grid.addWidget(self.errorcanvas, 0, 0, 1, 3)
        self.errorplot.add_subplot(111)
        self.errorcanvas.draw()

        #       A simple spacer to beautify the GUI
        my_spacer = QtGui.QSpacerItem(100, 1, QtGui.QSizePolicy.Minimum,
                                      QtGui.QSizePolicy.Expanding)
        grid.addItem(my_spacer, 0, 3, 1, 1)

        global errorinfo
        errorinfo = QtGui.QPlainTextEdit(self)
        grid.addWidget(errorinfo, 0, 4, 1, 2)
        errorinfo.insertPlainText(
            "The recorded error will be displayed below\n")

        #   Reset HK data on tab1 - All buttons that will reset the green color on the face of plot 1,2,3,4
        Reset1 = QtGui.QPushButton('Reset error in window 1', self)
        Reset1.resize(Reset1.sizeHint())
        Reset1.clicked.connect(self.R1)
        grid.addWidget(Reset1, 1, 4, 1, 1)

        Reset2 = QtGui.QPushButton('Reset error in window 2', self)
        Reset2.resize(Reset2.sizeHint())
        Reset2.clicked.connect(self.R2)
        grid.addWidget(Reset2, 1, 5, 1, 1)

        Reset3 = QtGui.QPushButton('Reset error in window 3', self)
        Reset3.resize(Reset3.sizeHint())
        Reset3.clicked.connect(self.R3)
        grid.addWidget(Reset3, 2, 4, 1, 1)

        Reset4 = QtGui.QPushButton('Reset error in window 4', self)
        Reset4.resize(Reset4.sizeHint())
        Reset4.clicked.connect(self.R4)
        grid.addWidget(Reset4, 2, 5, 1, 1)

#   From here i define all functions that will be called using the buttons on the tabs

#       This function will plot the recorded error, # specified by the user.

    def Perror(self):
        plt.cla()
        xerror = []
        yerror = []
        errorinfo.clear()
        errorinfo.insertPlainText(
            "The recorded error will be displayed below in the format\ntime,value,errornumber\n\n"
        )
        global errorwanted
        errorwanted = errorvalue.text()
        if not errorwanted:
            errorinfo.clear()
            errorinfo.insertPlainText(
                "Please insert an integer of the error you would like to display"
            )
        else:
            try:
                with open('Error-Testfile.txt', 'r') as ff:
                    for line in ff:
                        line = line.rstrip()
                        if line.endswith("," + errorwanted):
                            errorinfo.insertPlainText(line)
                            errorinfo.insertPlainText("\n")
                            xe, ye, num = line.split(',')
                            xerror.append(xe)
                            yerror.append(ye)
                    errorwindow = self.errorplot.add_subplot(111)
                    errorwindow.set_title(str(xerror[0]) + '    recorded: ' +
                                          str(xerror[1]) + ', ' +
                                          str(yerror[1]),
                                          fontweight="bold",
                                          size=32)  # Title
                    errorwindow.set_ylabel(yerror[0], fontsize=30)  # Y label
                    errorwindow.set_xlabel('real time', fontsize=30)  # X label
                    xerror.pop(0)
                    xerror.pop(0)
                    yerror.pop(0)
                    yerror.pop(0)
                    errorwindow.plot(xerror, yerror, 'ro-')
                    self.errorcanvas.draw()
            except:
                errorinfo.insertPlainText(
                    "\n\n ERROR: You have chosen an error number larger than amount of errors recorded"
                )

#       Updates # of recorded errors

    def Uerror(self):
        errordisplay.clear()
        errordisplay.setText("recorded errors  =  " + str(recorded_errors))

#       Resets the face color to green on button click, after potential error (figures tab 1)

    def R1(self):
        f1.patch.set_alpha(0.50)
        f1.set_facecolor('lime')

    def R2(self):
        f2.patch.set_alpha(0.50)
        f2.set_facecolor('lime')

    def R3(self):
        f3.patch.set_alpha(0.50)
        f3.set_facecolor('lime')

    def R4(self):
        f4.patch.set_alpha(0.50)
        f4.set_facecolor('lime')

#       The following plot functions will plot the last 200 HK datapoints from a file

    def plot1(self):
        self.figure.clf()
        mainwindow = self.figure.add_subplot(111)
        mainwindow.plot(xs1[-200:], ys1[-200:], 'bo-')

        timeofday = datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y")
        mainwindow.set_title('Temperature of... plottet:     ' + timeofday,
                             fontweight="bold",
                             size=20)  # Title
        mainwindow.set_ylabel('Temperature Celcius?', fontsize=20.0)  # Y label
        mainwindow.set_xlabel('Maybe real time?', fontsize=20)  # X label
        self.canvas.draw()

    def plot2(self):
        self.figure.clf()
        mainwindow = self.figure.add_subplot(111)
        mainwindow.plot(xs2[-200:], ys2[-200:], 'mo-')

        timeofday = datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y")
        mainwindow.set_title('Voltage of... plottet:     ' + timeofday,
                             fontweight="bold",
                             size=20)  # Title
        mainwindow.set_ylabel('Voltage?', fontsize=20.0)  # Y label
        mainwindow.set_xlabel('Maybe real time?', fontsize=20)  # X label
        self.canvas.draw()

    def plot3(self):
        self.figure.clf()
        mainwindow = self.figure.add_subplot(111)
        mainwindow.plot(xs3[-200:], ys3[-200:], 'ko-')

        timeofday = datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y")
        mainwindow.set_title('More?... plottet:     ' + timeofday,
                             fontweight="bold",
                             size=20)  # Title
        mainwindow.set_ylabel('Random?', fontsize=20.0)  # Y label
        mainwindow.set_xlabel('Maybe real time?', fontsize=20)  # X label
        self.canvas.draw()

    def plot4(self):
        self.figure.clf()
        mainwindow = self.figure.add_subplot(111)
        mainwindow.plot(xs4[-200:], ys4[-200:], 'yo-')

        timeofday = datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y")
        mainwindow.set_title('HK-DATA4. plottet:     ' + timeofday,
                             fontweight="bold",
                             size=20)  # Title
        mainwindow.set_ylabel('Random?', fontsize=20.0)  # Y label
        mainwindow.set_xlabel('Maybe real time?', fontsize=20)  # X label
        self.canvas.draw()
예제 #38
0
class Ui_MainWindow(object):
    def __init__(self):
        self.auth = 1
    def add_expense_routine(self):
        amount = self.addexp.text()
        try:
            float(amount)
        except:
            return
        t = time.ctime()
        date,month,year = t[8:10],t[4:7],t[-4:]
        some.lmm.cursor.execute( "SELECT * FROM stats WHERE Date=\'%s\' AND Month=\'%s\' AND Year=\'%s\' "%(date,month,year) )
        is_existant = some.lmm.cursor.fetchall()

        if is_existant:
            some.lmm.cursor.execute("UPDATE stats SET `Expense` = `Expense` + \'%s\' WHERE Date=\'%s\' AND Month=\'%s\' AND Year=\'%s\'"%(amount,date,month,year))
        else:
            some.lmm.cursor.execute("INSERT INTO stats (`Year`,`Month`,`Date`,`Expense`,`Profit Salewise`,`Tax`,`Key`) VALUES (?,?,?,?,?,?,?)",
                                        (year,month,date,amount,'0','0','0'))
        some.lmm.server.commit()
        self.addexp.clear()
    def __auth(self):
        key = self.pwd.text()
        self.__key_hash = '04a11c0ac3d39a7d59c2ee0cdcdcabb4'
        key_md5 = hashlib.md5(key.encode('utf-8')).hexdigest()
        if key_md5 == self.__key_hash:
            self.auth = 0
            print("Access")
        else:
            self.auth = 1

    def calc_profit(self):
        self.plot()
        isday,ismonth,isyear = [i.isChecked() for i in [self.isday,self.ismonth,self.isyear]]
        internal = not(self.auth) and self.internal.isChecked()
        day,month,year = self.day.currentText(),self.month.currentText(),self.year.currentText()
        half_query = 'SELECT `Expense`,`Profit Salewise`,`Tax`,`key` FROM stats WHERE '
        const = str('Date = \'%s\' AND '%day if isday else '') + str('Month = \'%s\' AND '%month if ismonth else '')
        const += 'Year = \'%s\''%year
        query = half_query + const
        #print(query)
        some.lmm.cursor.execute(query)
        data = some.lmm.cursor.fetchall()
        profit,tax,expense,hp = 0,0,0,0
        for i in data:
            profit+=float(i[1])
            tax+=float(i[2])
            expense+=float(i[0])
            hp+=float(i[3])
        #print(internal)
        #print("Profit: %f"%profit)
        #print("Tax: %f"%tax)
        #print("Expense: %f"%expense)
        #print("Hidden: %f\n\n"%hp)
        self.extraexpenses.setText(str(expense))
        self.profit.setText(str(profit))
        self.label_4.setText(_translate("MainWindow", "Stats for the Period", None))
        if internal:
            self.profit.setText(str(hp))
            self.tax.setText('0.0')
            self.label_4.setText('Stats for Internal Sales')
            return
        self.tax.setText(str(tax))
        return


    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(651, 497)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.horizontalLayout_6 = QtGui.QHBoxLayout(self.centralwidget)
        self.horizontalLayout_6.setObjectName(_fromUtf8("horizontalLayout_6"))
        self.verticalLayout = QtGui.QVBoxLayout()
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.verticalLayout_2 = QtGui.QVBoxLayout()
        self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
        self.label_9 = QtGui.QLabel(self.centralwidget)
        self.label_9.setAlignment(QtCore.Qt.AlignBottom|QtCore.Qt.AlignHCenter)
        self.label_9.setObjectName(_fromUtf8("label_9"))
        self.verticalLayout_2.addWidget(self.label_9)
        self.horizontalLayout_3 = QtGui.QHBoxLayout()
        self.horizontalLayout_3.setSizeConstraint(QtGui.QLayout.SetNoConstraint)
        self.horizontalLayout_3.setContentsMargins(-1, 0, -1, -1)
        self.horizontalLayout_3.setSpacing(6)
        self.horizontalLayout_3.setObjectName(_fromUtf8("horizontalLayout_3"))

        # expense additoon bar
        self.addexp = QtGui.QLineEdit(self.centralwidget)
        self.addexp.setObjectName(_fromUtf8("addexp"))
        self.horizontalLayout_3.addWidget(self.addexp)

        # Expense addition button
        self.appendexp = QtGui.QPushButton(self.centralwidget)
        self.appendexp.setObjectName(_fromUtf8("appendexp"))
        self.appendexp.clicked.connect(self.add_expense_routine)

        self.horizontalLayout_3.addWidget(self.appendexp)
        self.verticalLayout_2.addLayout(self.horizontalLayout_3)
        self.verticalLayout.addLayout(self.verticalLayout_2)
        self.line_4 = QtGui.QFrame(self.centralwidget)
        self.line_4.setFrameShape(QtGui.QFrame.HLine)
        self.line_4.setFrameShadow(QtGui.QFrame.Sunken)
        self.line_4.setObjectName(_fromUtf8("line_4"))
        self.verticalLayout.addWidget(self.line_4)
        self.horizontalLayout_4 = QtGui.QHBoxLayout()
        self.horizontalLayout_4.setObjectName(_fromUtf8("horizontalLayout_4"))
        # PWD field
        self.pwd = QtGui.QLineEdit(self.centralwidget)
        self.pwd.setObjectName(_fromUtf8("pwd"))
        self.pwd.setEchoMode(QtGui.QLineEdit.Password)
        self.horizontalLayout_4.addWidget(self.pwd)

        # Chk pwd Button
        self.chkpwd = QtGui.QPushButton(self.centralwidget)
        self.chkpwd.setObjectName(_fromUtf8("chkpwd"))
        self.chkpwd.clicked.connect(self.__auth)
        self.horizontalLayout_4.addWidget(self.chkpwd)
        self.verticalLayout.addLayout(self.horizontalLayout_4)
        self.line_3 = QtGui.QFrame(self.centralwidget)
        self.line_3.setFrameShape(QtGui.QFrame.HLine)
        self.line_3.setFrameShadow(QtGui.QFrame.Sunken)
        self.line_3.setObjectName(_fromUtf8("line_3"))
        self.verticalLayout.addWidget(self.line_3)
        self.label_5 = QtGui.QLabel(self.centralwidget)
        self.label_5.setAlignment(QtCore.Qt.AlignCenter)
        self.label_5.setObjectName(_fromUtf8("label_5"))
        self.verticalLayout.addWidget(self.label_5)
        self.horizontalLayout_5 = QtGui.QHBoxLayout()
        self.horizontalLayout_5.setObjectName(_fromUtf8("horizontalLayout_5"))
        # Stats type
        self.normal = QtGui.QRadioButton(self.centralwidget)
        self.normal.setObjectName(_fromUtf8("normal"))
        self.horizontalLayout_5.addWidget(self.normal)
        # stats type
        self.internal = QtGui.QRadioButton(self.centralwidget)
        self.internal.setObjectName(_fromUtf8("internal"))
        self.horizontalLayout_5.addWidget(self.internal)
        self.verticalLayout.addLayout(self.horizontalLayout_5)
        self.line_5 = QtGui.QFrame(self.centralwidget)
        self.line_5.setFrameShape(QtGui.QFrame.HLine)
        self.line_5.setFrameShadow(QtGui.QFrame.Sunken)
        self.line_5.setObjectName(_fromUtf8("line_5"))
        self.verticalLayout.addWidget(self.line_5)
        self.label_8 = QtGui.QLabel(self.centralwidget)
        self.label_8.setAlignment(QtCore.Qt.AlignBottom|QtCore.Qt.AlignHCenter)
        self.label_8.setObjectName(_fromUtf8("label_8"))
        self.verticalLayout.addWidget(self.label_8)
        self.horizontalLayout_2 = QtGui.QHBoxLayout()
        self.horizontalLayout_2.setSizeConstraint(QtGui.QLayout.SetMinimumSize)
        self.horizontalLayout_2.setContentsMargins(-1, 0, -1, -1)
        self.horizontalLayout_2.setSpacing(48)
        self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
        # is Day
        self.isday = QtGui.QCheckBox(self.centralwidget)
        self.isday.setObjectName(_fromUtf8("isday"))
        self.horizontalLayout_2.addWidget(self.isday)
        # Is month
        self.ismonth = QtGui.QCheckBox(self.centralwidget)
        self.ismonth.setObjectName(_fromUtf8("ismonth"))
        self.horizontalLayout_2.addWidget(self.ismonth)
        # Is year
        self.isyear = QtGui.QCheckBox(self.centralwidget)
        self.isyear.setObjectName(_fromUtf8("isyear"))
        self.horizontalLayout_2.addWidget(self.isyear)
        self.verticalLayout.addLayout(self.horizontalLayout_2)
        self.horizontalLayout = QtGui.QHBoxLayout()
        self.horizontalLayout.setContentsMargins(-1, 0, -1, -1)
        self.horizontalLayout.setSpacing(3)
        self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))

        # Day select
        self.day = QtGui.QComboBox(self.centralwidget)
        self.day.setObjectName(_fromUtf8("day"))
        self.horizontalLayout.addWidget(self.day)
        some.lmm.cursor.execute("SELECT Date FROM stats")
        days = sorted(set(some.lmm.cursor.fetchall()))
        self.day.clear()
        for text in days:
            self.day.addItem(str(text[0]))
        #self.comboBox.currentIndexChanged.connect(self.customer_change)


        # Month select
        some.lmm.cursor.execute("SELECT Month FROM stats")
        months = set(some.lmm.cursor.fetchall())
        self.month = QtGui.QComboBox(self.centralwidget)
        self.month.clear()
        for text in months:
            self.month.addItem(str(text[0]))
        self.month.setObjectName(_fromUtf8("month"))
        self.horizontalLayout.addWidget(self.month)



        # Year select
        some.lmm.cursor.execute("SELECT Year FROM stats")
        years = sorted(set(some.lmm.cursor.fetchall()))
        self.year = QtGui.QComboBox(self.centralwidget)
        self.year.clear()
        for text in years:
            self.year.addItem(str(text[0]))
        self.year.setObjectName(_fromUtf8("year"))


        self.horizontalLayout.addWidget(self.year)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.label_4 = QtGui.QLabel(self.centralwidget)
        self.label_4.setMaximumSize(QtCore.QSize(16777215, 17))
        self.label_4.setAlignment(QtCore.Qt.AlignCenter)
        self.label_4.setObjectName(_fromUtf8("label_4"))
        self.verticalLayout.addWidget(self.label_4)
        self.line_6 = QtGui.QFrame(self.centralwidget)
        self.line_6.setFrameShape(QtGui.QFrame.HLine)
        self.line_6.setFrameShadow(QtGui.QFrame.Sunken)
        self.line_6.setObjectName(_fromUtf8("line_6"))
        self.verticalLayout.addWidget(self.line_6)
        self.line_2 = QtGui.QFrame(self.centralwidget)
        self.line_2.setFrameShape(QtGui.QFrame.HLine)
        self.line_2.setFrameShadow(QtGui.QFrame.Sunken)
        self.line_2.setObjectName(_fromUtf8("line_2"))
        self.verticalLayout.addWidget(self.line_2)
        self.gridLayout = QtGui.QGridLayout()
        self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
        self.label = QtGui.QLabel(self.centralwidget)
        self.label.setObjectName(_fromUtf8("label"))
        self.gridLayout.addWidget(self.label, 0, 0, 1, 1)
        self.label_2 = QtGui.QLabel(self.centralwidget)
        self.label_2.setObjectName(_fromUtf8("label_2"))
        self.gridLayout.addWidget(self.label_2, 1, 0, 1, 1)
        # Expenses label
        self.extraexpenses = QtGui.QLabel(self.centralwidget)
        self.extraexpenses.setObjectName(_fromUtf8("extraexpenses"))
        self.gridLayout.addWidget(self.extraexpenses, 0, 1, 1, 1)
        # Tax label
        self.tax = QtGui.QLabel(self.centralwidget)
        self.tax.setObjectName(_fromUtf8("tax"))
        self.gridLayout.addWidget(self.tax, 2, 1, 1, 1)
        # Profit Label
        self.profit = QtGui.QLabel(self.centralwidget)
        self.profit.setObjectName(_fromUtf8("profit"))
        self.gridLayout.addWidget(self.profit, 1, 1, 1, 1)
        self.label_3 = QtGui.QLabel(self.centralwidget)
        self.label_3.setObjectName(_fromUtf8("label_3"))
        self.gridLayout.addWidget(self.label_3, 2, 0, 1, 1)
        # Update button
        self.update = QtGui.QPushButton(self.centralwidget)
        self.update.setObjectName(_fromUtf8("update"))
        self.gridLayout.addWidget(self.update, 3, 0, 1, 1)
        self.update.clicked.connect(self.calc_profit)
        # Back button
        self.back = QtGui.QPushButton(self.centralwidget)
        self.back.setObjectName(_fromUtf8("back"))
        #self.back.clicked.connect(exit)
        self.gridLayout.addWidget(self.back, 3, 1, 1, 1)
        self.verticalLayout.addLayout(self.gridLayout)
        self.horizontalLayout_6.addLayout(self.verticalLayout)
        self.line = QtGui.QFrame(self.centralwidget)
        self.line.setFrameShape(QtGui.QFrame.VLine)
        self.line.setFrameShadow(QtGui.QFrame.Sunken)
        self.line.setObjectName(_fromUtf8("line"))
        self.horizontalLayout_6.addWidget(self.line)


        self.graphicsView = QtGui.QGraphicsView(self.centralwidget)
        self.graphicsView.setObjectName(_fromUtf8("graphicsView"))

        self.figure = Figure()
        self.canvas = FigureCanvas(self.figure)
        self.toolbar = NavigationToolbar(self.canvas, self.centralwidget)
        self.verticalLayout_s = QtGui.QVBoxLayout()
        self.horizontalLayout_6.addLayout(self.verticalLayout_s)

        self.verticalLayout_s.addWidget(self.graphicsView)
        self.verticalLayout_s.addWidget(self.canvas)
        self.verticalLayout_s.addWidget(self.toolbar)
        #self.horizontalLayout_6.addWidget(self.canvas)
        #self.horizontalLayout_6.addWidget(self.graphicsView)
        #self.horizontalLayout_6.addWidget(self.toolbar)

        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 651, 25))
        self.menubar.setObjectName(_fromUtf8("menubar"))
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        MainWindow.setStatusBar(self.statusbar)
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def plot(self):
        ismonth,isyear = [i.isChecked() for i in [self.ismonth,self.isyear]]
        day,month,year = self.day.currentText(),self.month.currentText(),self.year.currentText()
        half_query = "select (`Profit Salewise` + `key`) as Total from stats " + ('WHERE ' if ismonth or isyear else '')
        const = str('`Month` = \'%s\' AND '%month if ismonth else '')
        const += '`Year` = \'%s\''%year if isyear else ''
        query = half_query + const
        #print(query)
        
        some.lmm.cursor.execute(query)
        data = some.lmm.cursor.fetchall()
        data = [int(i[0]) for i in data]
        #print(data)
        ax = self.figure.add_subplot(111)
        ax.clear()
        ax.set_xlabel('Relative Timeline')
        ax.set_ylabel('Relative Profit')
        #ax.set_rcParams["figure.figsize"] = (20,3)
        ax.plot(data)
        self.canvas.draw()

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(_translate("MainWindow", "EMS | STATS", None))
        self.label_9.setText(_translate("MainWindow", "Add Expense", None))
        self.appendexp.setText(_translate("MainWindow", "Add", None))
        self.chkpwd.setText(_translate("MainWindow", "Check", None))
        self.label_5.setText(_translate("MainWindow", "Calculation Method", None))
        self.normal.setText(_translate("MainWindow", "Precision", None))
        self.internal.setText(_translate("MainWindow", "Celling", None))
        self.label_8.setText(_translate("MainWindow", "Calculate Data For", None))
        self.isday.setText(_translate("MainWindow", "Day", None))
        self.ismonth.setText(_translate("MainWindow", "Month", None))
        self.isyear.setText(_translate("MainWindow", "Year", None))
        self.label_4.setText(_translate("MainWindow", "Stats for the Period", None))
        self.label.setText(_translate("MainWindow", "Extra Expenses", None))
        self.label_2.setText(_translate("MainWindow", "Profit", None))
        self.extraexpenses.setText(_translate("MainWindow", "0.0", None))
        self.tax.setText(_translate("MainWindow", "0.0", None))
        self.profit.setText(_translate("MainWindow", "0.0", None))
        self.label_3.setText(_translate("MainWindow", "Tax", None))
        self.update.setText(_translate("MainWindow", "Update", None))
        self.back.setText(_translate("MainWindow", "Back", None))
예제 #39
0
class PlotDialog(cls_dialog, ui_dialog):
    def __init__(self, *args, **kwargs):
        super(PlotDialog, self).__init__(*args, **kwargs)
        self.setupUi(self)

        self.initmpl()
        self.inittree()
        self.initgui()
        self.show()

        self.selected_line = None
        self.annotations = []
        self.smoother_lookup = {
            'Box Filter': smoothing.boxcar,
            'Gaussian': smoothing.gaussian
        }

    def initgui(self):
        self.endpoint_slider_lower.valueChanged.connect(
            lambda i: self.endpoint_slider_lower_label.setText(
                '{'
                '}'.format(self.wavelengths[i])))
        self.endpoint_slider_upper.valueChanged.connect(
            lambda i: self.endpoint_slider_upper_label.setText(
                '{'
                '}'.format(self.wavelengths[i])))

        self.band_center_btn.clicked.connect(self.band_center)
        self.band_minima_btn.clicked.connect(self.band_minima)
        self.band_area_btn.clicked.connect(self.band_area)
        self.band_asymmetry_btn.clicked.connect(self.band_asymmetry)

    def get_endpoints_and_spectra(self):

        if self.selected_line:
            lower = float(self.endpoint_slider_lower_label.text())
            upper = float(self.endpoint_slider_upper_label.text())

            l = self.selected_line
            xd = l.get_xdata()
            yd = pd.Series(l.get_ydata(), index=xd)
            offset = l.offset
            return lower, upper, yd, offset

    def band_center(self):
        if self.selected_line is not None:
            lower, upper, yd, offset = self.get_endpoints_and_spectra()
            (min_idx, min_value), center_fit = analytics.band_center(
                yd, low_endmember=lower, high_endmember=upper)
            center_fit.plot(ax=self.ax,
                            color='k',
                            gid=4,
                            picker=5,
                            linewidth=4.0,
                            alpha=0.5)
            self.ax.plot(min_idx,
                         min_value,
                         marker='*',
                         markersize=DEFAULT_MARKER_SIZE,
                         color='k',
                         gid=3,
                         picker=5)
            self.canvas.draw()

            self.notes.insertPlainText(
                '> The band center between {} and {} is {} at {}\n'.format(
                    lower, upper, min_value, min_idx))

    def band_minima(self):
        if self.selected_line is not None:
            lower, upper, yd, offset = self.get_endpoints_and_spectra()
            min_idx, min_value = analytics.band_minima(yd,
                                                       low_endmember=lower,
                                                       high_endmember=upper)
            self.ax.plot(min_idx,
                         min_value,
                         marker='*',
                         markersize=DEFAULT_MARKER_SIZE,
                         color='k',
                         gid=3,
                         picker=5)
            self.canvas.draw()

            self.notes.insertPlainText(
                '> The band minima between {} and {} is {} at {}\n'.format(
                    lower, upper, min_value, min_idx))

    def band_area(self):
        if self.selected_line is not None:
            lower, upper, yd, offset = self.get_endpoints_and_spectra()
            area = analytics.band_area(yd - offset,
                                       low_endmember=lower,
                                       high_endmember=upper)
            fill = yd.loc[lower:upper]
            self.ax.fill_between(fill.index,
                                 fill.values,
                                 1.0 + offset,
                                 facecolor='b',
                                 alpha=0.25,
                                 gid=6,
                                 picker=5)
            self.canvas.draw()

            self.notes.insertPlainText(
                '> The band area between {} and {} is {}\n'.format(
                    lower, upper, area))

    def band_asymmetry(self):
        if self.selected_line is not None:
            lower, upper, yd, offset = self.get_endpoints_and_spectra()
            self.band_area()
            asymmetry = analytics.band_asymmetry(yd - offset,
                                                 low_endmember=lower,
                                                 high_endmember=upper)
            self.canvas.draw()

            self.notes.insertPlainText(
                '> The band asymmetry between {} and {} is {}\n'.format(
                    lower, upper, asymmetry))

    def initmpl(self):
        """
        Initialize the MatPlotLib Figure
        """
        self.figure = Figure()
        self.ax = self.figure.add_subplot(111)
        self.ax.grid(True)
        self.canvas = FigureCanvas(self.figure)
        self.ax.set_xlabel('Wavelength (nm)')
        self.mplvl.addWidget(self.canvas)

        # Add the toolbar
        self.toolbar = NavigationToolbar(self.canvas,
                                         self.mplwindow,
                                         coordinates=True)
        self.mplvl.addWidget(self.toolbar)

        self.figure.canvas.mpl_connect('pick_event', self.select_spectra)

        self.canvas.draw()

    def inittree(self):
        """
        Initialize the tree view
        """
        self.spectratree.setModel(QtGui.QStandardItemModel())

    def set_spectra(self, spectra):
        self.data = spectra
        for k, obs in self.data.iteritems():
            parent = QtGui.QStandardItem(k)
            for label, values in obs.iteritems():
                child = QtGui.QStandardItem('Observation {}'.format(label))
                child.setFlags(QtCore.Qt.ItemIsEnabled
                               | QtCore.Qt.ItemIsSelectable)
                parent.appendRow(child)
            self.spectratree.model().appendRow(parent)

    def select_spectra(self, event):
        def update_selection():
            for i, x in enumerate(self.ax.lines):
                if x != self.selected_line:
                    if x.get_gid() in [0, 1]:
                        x.set_linewidth(1.0)
                        x.set_markersize(2.0)
                    elif x.get_gid() in [4, 5]:
                        x.set_linewidth(4.0)
                        x.set_markersize(DEFAULT_MARKER_SIZE)
                    elif x.get_gid() in [6]:
                        x.set_alpha(0.25)

        geom = event.artist
        gid = geom.get_gid()
        self.selected_line = geom
        update_selection()

        try:
            lineidx = self.ax.lines.index(geom)
        except:
            return

        if event.mouseevent.button == 1:
            if gid in [0, 1]:
                self.ax.lines[lineidx].set_linewidth(2.0)
                self.ax.lines[lineidx].set_markersize(4.0)
            elif gid in [4, 5]:
                self.ax.lines[lineidx].set_linewidth(6.0)
                self.ax.lines[lineidx].set_markersize(SELECTED_MARKER_SIZE)
            elif gid in [6]:
                self.ax.lines[lineidx].set_alpha(0.75)

        elif event.mouseevent.button == 3:
            self.spectra_context_menu_event(self)

        self.canvas.draw()

    def spectra_context_menu_event(self, event):
        menu = QtGui.QMenu()
        try:
            gid = self.selected_line.get_gid()
        except:
            return

        if gid in [0, 5, 10]:
            delsp = menu.addAction('Delete Selected Spectra',
                                   self.delete_spectra)
            movesp = menu.addAction('Move Spectra', self.move_spectra)
            aspoint = menu.addAction('Show as Point', self.as_point)
            asline = menu.addAction('Show as Line', self.as_line)
            addsmooth = menu.addAction('Add Smoothed Spectra',
                                       self.smooth_spectra)
            ccorrect = menu.addAction('Continuum Correct',
                                      self.continuum_correct_spectra)

        if gid in [4]:
            delsp = menu.addAction('Delete Parameter', self.delete_spectra)

        menu.exec_(self.mapToGlobal(event.pos()))

    def delete_spectra(self):
        """
        Remove the selected spectra from the plot.
        """
        if self.selected_line is not None:
            self.ax.lines.remove(self.selected_line)
            self.canvas.draw()

    def move_spectra(self):
        if self.selected_line is not None:
            l = self.selected_line
            offset = float(self.offset.value())
            yd = l.get_ydata() + offset
            self.ax.plot(l.get_xdata(),
                         yd,
                         color=l.get_color(),
                         picker=l.get_picker(),
                         label=l.get_label())
            self.ax.lines.remove(l)
            self.canvas.draw()

    def as_point(self):
        """
        Convert the point to a line object
        """
        if self.selected_line is not None:
            l = self.selected_line
            l.set_linestyle('')
            l.set_marker('o')
            l.set_markersize(2)
            self.canvas.draw()

    def as_line(self):
        """
        Convert the line to a point object
        """
        if self.selected_line is not None:
            l = self.selected_line
            l.set_linestyle('-')
            l.set_marker('')
            self.canvas.draw()

    def smooth_spectra(self):
        if self.selected_line is not None:
            l = self.selected_line
            xd = l.get_xdata()
            yd = pd.Series(l.get_ydata(), index=xd)
            color = l.get_color()
            smooth_func = self.smoother_lookup[
                self.smooth_method.currentText()]
            window = int(self.smooth_window.value())

            smoothed = smooth_func(yd, window_size=window)

            self.ax.plot(xd, smoothed, color=color, picker=5, gid=5)

    def continuum_correct_spectra(self):
        pass

    def plot(self,
             continuum_endpoints,
             correction_method,
             smoothing_method,
             smoothing_window_size,
             offset,
             clipping_lower,
             clipping_upper,
             pcorrect=None):

        if pcorrect == 'Mare':
            key = 'REF2'
        elif pcorrect == 'Highlands':
            key = 'REF1'
        else:
            key = 'REF'

        offset_interval = 0

        for fname, panel in self.data.iteritems():
            for k, df in panel.iteritems():
                if key in df.columns:
                    spectra = df[key]
                else:
                    spectra = df['REF']

                # lrm

                #print "plot_dialog : plot : spectra = {}".format(spectra)

                if correction_method != 'None':
                    df['CC'], df['Continuum'] = continuum.continuum_correct(
                        spectra,
                        nodes=continuum_endpoints,
                        method=correction_method.lower())
                else:
                    df['CC'] = spectra

                mask = (df.index >= clipping_lower) & (df.index <=
                                                       clipping_upper)
                spectra = df['CC'][mask]

                if offset:
                    spectra += (offset + offset_interval)
                    offset_interval += offset

                if smoothing_method != 'None':
                    smooth_func = self.smoother_lookup[smoothing_method]
                    spectra = smooth_func(spectra,
                                          window_size=smoothing_window_size)

                print("plot_dialog : plot : Just before spectra.plot")
                spectra.plot(ax=self.ax, picker=5, gid=0)

                # Custom attr to get the offset as an attribute to the line.
                setattr(self.ax.lines[-1], 'offset',
                        (offset + offset_interval))
        self.ax.grid(True)
        self.canvas.draw()
예제 #40
0
class CutePlot(QMainWindow):
    def __init__(self, parent=None):
        super(CutePlot, self).__init__(parent)

        # Default values for lower and upper bound
        self.LB_default = -10
        self.UB_default = 10
        # Create main plot area + menus + status bar
        self.create_main_frame()
        #self.textbox.setText()
        self.LB_UB_defaults()
        self.on_draw()
        self.statusBar()
        self.setWindowTitle('Graficador')
        self.create_menu()
        self.guardarImagen()

    def LB_UB_defaults(self):
        # Set default values for lower bound and upper bound
        self.lowerbound.setText(str(self.LB_default))
        self.upperbound.setText(str(self.UB_default))

    def create_main_frame(self):
        self.main_frame = QWidget()
        # 7x5 inches, 80 dots-per-inch
        self.dpi = 80
        self.fig = Figure((5, 3), dpi=self.dpi)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.main_frame)

        self.is_data = False

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

        # axis_state keeps track of how many subplots are present
        # axis_state = 0: main plot only
        # axis_state = 1: horizontal split (quadrants 1 and 2)
        # axis_state = 2: vertical split (quadrants 1 and 4)
        # axis_state = 3: show all 4 subplots
        self.axis_state = 0

        self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)

        # f(x) textbox
        self.title = QLabel('<font size=4><em>f</em> (<em>x </em>) =</font>')
        self.textbox = QLineEdit()
        self.textbox.setMinimumWidth(200)
        self.connect(self.textbox, SIGNAL('returnPressed()'), self.on_draw)

        # Lowerbound and upperbound textboxes
        self.LB_title = QLabel('<font size=4>Min:</font>')
        self.lowerbound = QLineEdit()
        self.lowerbound.setMaximumWidth(30)
        self.connect(self.lowerbound, SIGNAL('returnPressed()'), self.on_draw)

        self.UB_title = QLabel('<font size=4>Max:</font>')
        self.upperbound = QLineEdit()
        self.upperbound.setMaximumWidth(30)
        self.connect(self.upperbound, SIGNAL('returnPressed()'), self.on_draw)

        # Plot button
        self.draw_button = QPushButton("&Plot")
        self.connect(self.draw_button, SIGNAL('clicked()'), self.on_draw)

        # Hold checkbox
        self.hold_cb = QCheckBox("&Hold")
        self.hold_cb.setChecked(False)
        self.connect(self.hold_cb, SIGNAL('stateChanged(int)'),
                     self.on_minor_change)
        self.hold_cb.setToolTip('Prevent new plots from replacing old ones')
        self.hold_cb.setStatusTip('Prevent new plots from replacing old ones')

        # Log-x and log-y checkboxes
        self.logx_cb = QCheckBox("Log-&x")
        self.logx_cb.setChecked(False)
        self.connect(self.logx_cb, SIGNAL('stateChanged(int)'), self.on_draw)
        self.logx_cb.setToolTip('Change x-axis to logarithmic scale')
        self.logx_cb.setStatusTip('Change x-axis to logarithmic scale')

        self.logy_cb = QCheckBox("Log-&y")
        self.logy_cb.setChecked(False)
        self.connect(self.logy_cb, SIGNAL('stateChanged(int)'), self.on_draw)
        self.logy_cb.setToolTip('Change y-axis to logarithmic scale')
        self.logy_cb.setStatusTip('Change y-axis to logarithmic scale')

        # Truncated-log checkbox
        self.trunc_cb = QCheckBox("Show &Negative")
        self.trunc_cb.setChecked(False)
        self.connect(self.trunc_cb, SIGNAL('stateChanged(int)'), self.on_draw)
        self.trunc_cb.setToolTip(
            'Plot negative values of log-transformed functions')
        self.trunc_cb.setStatusTip(
            'Plot negative values of log-transformed functions')

        # Grid checkbox
        self.grid_cb = QCheckBox("&Grid")
        self.grid_cb.setChecked(False)
        self.connect(self.grid_cb, SIGNAL('stateChanged(int)'),
                     self.on_minor_change)
        self.grid_cb.setToolTip('Show grid')
        self.grid_cb.setStatusTip('Show grid')

        # Grid layout
        grid = QGridLayout()
        grid.setSpacing(10)

        gridCol = 0
        for w in [
                self.title, self.textbox, self.LB_title, self.lowerbound,
                self.UB_title, self.upperbound, self.draw_button
        ]:
            grid.addWidget(w, 0, gridCol)
            gridCol += 1

        grid2 = QGridLayout()
        grid2.setSpacing(10)
        gridCol = 0
        for w in [
                self.logx_cb, self.logy_cb, self.trunc_cb, self.hold_cb,
                self.grid_cb
        ]:
            grid2.addWidget(w, 0, gridCol)
            gridCol += 1

        vbox = QVBoxLayout()
        vbox.addLayout(grid)
        vbox.addLayout(grid2)
        vbox.addWidget(self.canvas)
        vbox.addWidget(self.mpl_toolbar)

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

    def on_minor_change(self):
        self.on_draw(self.is_data)

    def on_draw(self, *args):
        # Get x-domain from user input
        self.LB_input = unicode(self.lowerbound.text())
        self.UB_input = unicode(self.upperbound.text())

        # Message box error if the domain inputs aren't int or float types
        # If float, round to the nearest 0.1
        round_to = 10
        try:
            self.LB_float = int(self.LB_input) * round_to
            self.UB_float = int(self.UB_input) * round_to
        except:
            self.LB_UB_defaults()
            QMessageBox.question(
                self, 'Error',
                '<center>Minimum and maximum values must be<br />\
                integer or floating-point numbers.</center>', QMessageBox.Ok)

        # Make sure UB > LB
        if self.UB_float <= self.LB_float:
            self.LB_UB_defaults()
            QMessageBox.question(
                self, 'Error', '<center>Maximum must be greater\
                than minimum value.</center>', QMessageBox.Ok)

        # If plotting a function, then get x and y values
        if len(args) == 0:
            self.is_data = False

            # Set x values (/round_to is to use range() with floating-point numbers)
            self.input_x = range(self.LB_float, self.UB_float + 1)
            self.input_x = [i / float(round_to) for i in self.input_x]

            # Calculate f(x) values for specified function
            fx = unicode(self.textbox.text())
            # If the f(x) field is empty, then default to y = 0 plot
            if fx == '':
                self.y = [0 for i in self.input_x]
            # Otherwise, evaluate the specified function and get ready to plot
            else:
                # Replace exp with numbers
                fx = fx.replace('exp', str(exp(1)) + '**')
                # Allow users to enter ^ for powers (replace ^ with **)
                fx = fx.replace('^', '**')
                # Try and evaluate; if there is an error, then shift slightly to the right
                try:
                    self.y = [eval(fx) for x in self.input_x]
                except:
                    fx = fx.replace('x', '(x + 10**(-6))')
                    self.y = [eval(fx) for x in self.input_x]
            self.plot_symbol = '-'
        if self.is_data:
            self.plot_symbol = 'o'

        # If the hold box is checked, then new plots do not erase old ones
        new_state = self.quad_check()
        if self.axis_state == 0:
            self.axes.hold(self.hold_cb.isChecked())
        else:
            if self.hold_cb.isChecked():
                # If 'hold' is checked, see what quadrants will be shown
                # - if the quadrant state changes, remove subplots
                # - otherwise retain subplots
                if self.axis_state == 0 and new_state == 0:
                    self.axes.hold(self.hold_cb.isChecked())
                elif self.axis_state == 3 and new_state == 3:
                    self.axes_Q1.hold(self.hold_cb.isChecked())
                    self.axes_Q2.hold(self.hold_cb.isChecked())
                    self.axes_Q3.hold(self.hold_cb.isChecked())
                    self.axes_Q4.hold(self.hold_cb.isChecked())
                elif self.axis_state == 1 and new_state == 1:
                    self.axes_Q1.hold(self.hold_cb.isChecked())
                    self.axes_Q2.hold(self.hold_cb.isChecked())
                elif self.axis_state == 2 and new_state == 2:
                    self.axes_Q1.hold(self.hold_cb.isChecked())
                    self.axes_Q4.hold(self.hold_cb.isChecked())
                else:
                    self.remove_subplots()
            else:
                self.remove_subplots()

        # If show negative box is unchecked
        if not self.trunc_cb.isChecked():
            self.add_main()
            self.axes.plot(self.input_x, self.y, self.plot_symbol)
            if not self.logx_cb.isChecked() and not self.logy_cb.isChecked():
                self.axes.set_xscale('linear')
                self.axes.set_yscale('linear')
            elif self.logx_cb.isChecked() and not self.logy_cb.isChecked():
                self.axes.set_xscale('log')
                self.axes.set_yscale('linear')
            elif not self.logx_cb.isChecked() and self.logy_cb.isChecked():
                self.axes.set_xscale('linear')
                self.axes.set_yscale('log')
            else:
                self.axes.set_xscale('log')
                self.axes.set_yscale('log')
        else:
            # Linear plot
            #if not self.logx_cb.isChecked() and not self.logy_cb.isChecked():
            if new_state == 0:
                self.add_main()
                self.axes.plot(self.input_x, self.y, self.plot_symbol)

            # Log x, linear y plot
            #elif self.logx_cb.isChecked() and not self.logy_cb.isChecked():
            elif new_state == 1:
                if not self.trunc_cb.isChecked():
                    self.add_main()
                    self.axes.semilogx(self.input_x, self.y, self.plot_symbol)
                else:
                    self.trunc_logx()

            # Linear x, log y plot
            #elif not self.logx_cb.isChecked() and self.logy_cb.isChecked():
            elif new_state == 2:
                if not self.trunc_cb.isChecked():
                    self.add_main()
                    self.axes.semilogy(self.input_x, self.y, self.plot_symbol)
                else:
                    self.trunc_logy()

            # Log-log plot
            else:
                if not self.trunc_cb.isChecked():
                    self.add_main()
                    self.axes.loglog(self.input_x, self.y, self.plot_symbol)
                else:
                    self.trunc_loglog()

        # Add grid if grid checkbox is checked
        if self.axis_state == 0:
            self.axes.grid(self.grid_cb.isChecked())
        else:
            if hasattr(self, 'axes_Q1'):
                self.axes_Q1.grid(self.grid_cb.isChecked())
            if hasattr(self, 'axes_Q2'):
                self.axes_Q2.grid(self.grid_cb.isChecked())
            if hasattr(self, 'axes_Q3'):
                self.axes_Q3.grid(self.grid_cb.isChecked())
            if hasattr(self, 'axes_Q4'):
                self.axes_Q4.grid(self.grid_cb.isChecked())

        self.axes.set_xlabel('$x$')
        self.axes.set_ylabel('$f(x)$')
        self.canvas.draw()
        self.guardarImagen()

    def remove_subplots(self):
        # Remove all subplots and axis flip flags
        if hasattr(self, 'axes_Q1'):
            self.fig.delaxes(self.axes_Q1)
            del self.axes_Q1
        if hasattr(self, 'axes_Q2'):
            self.fig.delaxes(self.axes_Q2)
            del self.axes_Q2
            if hasattr(self, 'flip_Q2'):
                del self.flip_Q2
        if hasattr(self, 'axes_Q3'):
            self.fig.delaxes(self.axes_Q3)
            del self.axes_Q3
            del self.flip_Q3
        if hasattr(self, 'axes_Q4'):
            self.fig.delaxes(self.axes_Q4)
            del self.axes_Q4
            if hasattr(self, 'flip_Q4'):
                del self.flip_Q4

    def add_main(self):
        # Reinsert the main plot
        if self.axis_state > 0:
            self.remove_subplots()
            self.axes = self.fig.add_subplot(111)
            self.axis_state = 0

    def create_menu(self):
        exitAction = QAction('Quit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(self.close)

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')

        save_plot_action = self.create_action("&Save plot",
                                              shortcut="Ctrl+S",
                                              slot=self.save_plot,
                                              tip="Save image to file")
        import_data_action = self.create_action("&Import data",
                                                shortcut="Ctrl+I",
                                                slot=self.import_data,
                                                tip="Import data from file")
        fileMenu.addAction(save_plot_action)
        fileMenu.addAction(import_data_action)
        fileMenu.addAction(exitAction)

        helpMenu = self.menuBar().addMenu("&Help")
        about_action = self.create_action("&About",
                                          shortcut='F1',
                                          slot=self.on_about,
                                          tip='About CutePlot')
        helpMenu.addAction(about_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 save_plot(self):
        file_choices = "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 import_data(self):
        file_choices = "*.csv;;*.txt;;*.tab;;*.dat;;*.*"
        self.path = QFileDialog.getOpenFileName(self, 'Import data', '',
                                                file_choices)
        if self.path:
            datafile = open(self.path[0], 'r')
            if datafile:
                self.is_data = True
                delimiter = ','
                input_xy = [
                    map(float,
                        line.strip().split(delimiter)) for line in datafile
                ]
                self.input_x, self.y = [[row[col] for row in input_xy]
                                        for col in [0, 1]]
                datafile.close()
                self.statusBar().showMessage('Imported data', 2000)
                self.on_draw(self.is_data)

    def on_about(self):
        msg = """<center><b>CutePlot v. 0.1</b></center>
        <center>Free, open-source plotting program,<br />
        written in Python (PySide/Qt + matplotlib).</center>
        <center>(c) Jack Peterson, 2012</center>
        """
        QMessageBox.about(self, "About", msg.strip())

    def quad_check(self):
        # Q = quadrant
        Q1 = False
        Q2 = False
        Q3 = False
        Q4 = False

        # Split the x and y values by sign
        for j in range(0, len(self.input_x)):
            if self.input_x[j] > 0 and self.y[j] > 0:
                Q1 = True
            elif self.input_x[j] < 0 and self.y[j] > 0:
                Q2 = True
            elif self.input_x[j] < 0 and self.y[j] < 0:
                Q3 = True
            elif self.input_x[j] > 0 and self.y[j] < 0:
                Q4 = True

        if (Q3 or (Q2 and Q4) or ((Q2 or Q4) and self.axis_state == 3)
            ) and self.logx_cb.isChecked() and self.logy_cb.isChecked():
            new_state = 3
        elif (Q2 and self.logx_cb.isChecked()) or (self.hold_cb.isChecked()
                                                   and self.axis_state == 1):
            new_state = 1
        elif (Q4 and self.logy_cb.isChecked()) or (self.hold_cb.isChecked()
                                                   and self.axis_state == 2):
            new_state = 2
        else:
            new_state = 0

        return new_state

    def trunc_logx(self):
        # Q = quadrant
        Q1_x = []
        Q1_y = []
        Q2_x = []
        Q2_y = []

        # Split the x and y values by sign
        for j in range(0, len(self.input_x)):
            if self.input_x[j] > 0 and self.y[j] > 0:
                Q1_x.append(self.input_x[j])
                Q1_y.append(self.y[j])
            elif self.input_x[j] < 0 and self.y[j] > 0:
                Q2_x.append(-self.input_x[j])
                Q2_y.append(self.y[j])

        # If only Q1 is populated, then use an ordinary semilogx plot
        if Q2_x == [] and not self.hold_cb.isChecked():
            self.add_main()
            self.axes.semilogx(self.input_x, self.y, self.plot_symbol)

        # Otherwise, create a truncated plot
        else:
            # Remove main axes
            if self.axis_state == 0:
                self.fig.delaxes(self.axes)

            if self.axis_state == 2 or self.axis_state == 3:
                self.axis_state = 3
            else:
                self.axis_state = 1

            # Create 2 subplots
            self.axes_Q1 = self.fig.add_subplot(122)
            self.axes_Q2 = self.fig.add_subplot(121)
            self.axes_Q1.autoscale(enable=True)
            self.axes_Q2.autoscale(enable=True)
            self.axes_Q1.semilogx(Q1_x, Q1_y, self.plot_symbol)
            self.axes_Q2.semilogx(Q2_x, Q2_y, self.plot_symbol)

            # Reverse Q2 x-axis
            if not hasattr(self, 'flip_Q2'):
                self.flip_Q2 = True
                self.axes_Q2.set_xlim(self.axes_Q2.get_xlim()[::-1])

            # Set axis tickmarks at powers of 10
            # Q1 axes
            if Q1_x == [] and not self.hold_cb.isChecked():
                self.axes_Q1.set_xticklabels([])
            else:
                try:
                    x_UB_Q1 = int(ceil(log10(max(Q1_x))))
                    x_LB_Q1 = int(floor(log10(min(Q1_x))))
                except:
                    x_UB_Q1 = 2
                    x_LB_Q1 = -1
                Q1_xlabels = []
                for i in range(x_LB_Q1, x_UB_Q1 + 1):
                    Q1_xlabels.append('$10^{%s}$' % str(i))
                self.axes_Q1.set_xticklabels(Q1_xlabels)
            self.axes_Q1.xaxis.tick_bottom()
            self.axes_Q1.yaxis.tick_right()

            # Q2 axes
            if Q2_x == [] and not self.hold_cb.isChecked():
                self.axes_Q2.set_xticklabels([])
            else:
                try:
                    x_UB_Q2 = int(ceil(log10(max(Q2_x))))
                    x_LB_Q2 = int(floor(log10(min(Q2_x))))
                except:
                    x_UB_Q2 = 2
                    x_LB_Q2 = -1
                Q2_xlabels = []
                for i in range(x_LB_Q2, x_UB_Q2 + 1):
                    Q2_xlabels.append('$-10^{%s}$' % str(i))
                self.axes_Q2.set_xticklabels(Q2_xlabels)
            self.axes_Q2.xaxis.tick_bottom()
            self.axes_Q2.yaxis.tick_left()

    def trunc_logy(self):
        # Q = quadrant
        Q1_x = []
        Q1_y = []
        Q4_x = []
        Q4_y = []

        # Split the x and y values by sign
        for j in range(0, len(self.input_x)):
            if self.input_x[j] > 0 and self.y[j] > 0:
                Q1_x.append(self.input_x[j])
                Q1_y.append(self.y[j])
            elif self.input_x[j] > 0 and self.y[j] < 0:
                Q4_x.append(self.input_x[j])
                Q4_y.append(-self.y[j])

        # If only Q1 is populated, then use an ordinary semilogy plot
        if Q4_x == [] and not self.hold_cb.isChecked():
            self.add_main()
            self.axes.semilogy(self.input_x, self.y, self.plot_symbol)

        # Otherwise, create a truncated plot
        else:
            # Remove main axes
            if self.axis_state == 0:
                self.fig.delaxes(self.axes)

            if self.axis_state == 1 or self.axis_state == 3:
                self.axis_state = 3
            else:
                self.axis_state = 2

            # Create 2 subplots
            self.axes_Q1 = self.fig.add_subplot(211)
            self.axes_Q4 = self.fig.add_subplot(212)
            self.axes_Q1.autoscale(enable=True)
            self.axes_Q4.autoscale(enable=True)
            self.axes_Q1.semilogy(Q1_x, Q1_y, self.plot_symbol)
            self.axes_Q4.semilogy(Q4_x, Q4_y, self.plot_symbol)

            # Reverse Q4 y-axis
            if not hasattr(self, 'flip_Q4'):
                self.flip_Q4 = True
                self.axes_Q4.set_ylim(self.axes_Q4.get_ylim()[::-1])

            # Set axis tickmarks at powers of 10
            # Q1 axes
            if Q1_x == [] and not self.hold_cb.isChecked():
                self.axes_Q1.set_yticklabels([])
            else:
                try:
                    y_UB_Q1 = int(ceil(log10(max(Q1_y))))
                    y_LB_Q1 = int(floor(log10(min(Q1_y))))
                except:
                    y_UB_Q1 = 2
                    y_LB_Q1 = -1
                Q1_ylabels = []
                for i in range(y_LB_Q1, y_UB_Q1 + 1):
                    Q1_ylabels.append('$10^{%s}$' % str(i))
                self.axes_Q1.set_yticklabels(Q1_ylabels)
            self.axes_Q1.xaxis.tick_top()
            self.axes_Q1.yaxis.tick_right()

            # Q4 axes
            if Q4_x == [] and not self.hold_cb.isChecked():
                self.axes_Q4.set_yticklabels([])
            else:
                try:
                    y_UB_Q4 = int(ceil(log10(max(Q4_y))))
                    y_LB_Q4 = int(floor(log10(min(Q4_y))))
                except:
                    y_UB_Q4 = 2
                    y_LB_Q4 = -1
                Q4_ylabels = []
                for i in range(y_LB_Q4, y_UB_Q4 + 1):
                    Q4_ylabels.append('$-10^{%s}$' % str(i))
                self.axes_Q4.set_yticklabels(Q4_ylabels)
            self.axes_Q4.xaxis.tick_bottom()
            self.axes_Q4.yaxis.tick_right()

    def trunc_loglog(self):
        # Q = quadrant
        Q1_x = []
        Q1_y = []
        Q2_x = []
        Q2_y = []
        Q3_x = []
        Q3_y = []
        Q4_x = []
        Q4_y = []

        # Split the x and y values by sign
        for j in range(0, len(self.input_x)):
            if self.input_x[j] > 0 and self.y[j] > 0:
                Q1_x.append(self.input_x[j])
                Q1_y.append(self.y[j])
            elif self.input_x[j] < 0 and self.y[j] > 0:
                Q2_x.append(-self.input_x[j])
                Q2_y.append(self.y[j])
            elif self.input_x[j] < 0 and self.y[j] < 0:
                Q3_x.append(-self.input_x[j])
                Q3_y.append(-self.y[j])
            elif self.input_x[j] > 0 and self.y[j] < 0:
                Q4_x.append(self.input_x[j])
                Q4_y.append(-self.y[j])

        # If only Q1 is populated, then use an ordinary loglog plot
        if Q2_x == [] and Q3_x == [] and Q4_x == [] and not self.hold_cb.isChecked(
        ):
            self.add_main()
            self.axes.loglog(self.input_x, self.y, self.plot_symbol)

        # Otherwise, create a truncated plot
        else:
            # Remove main axes
            if self.axis_state == 0:
                self.fig.delaxes(self.axes)
            self.axis_state = 3

            # Create 4 subplots
            self.axes_Q1 = self.fig.add_subplot(222)
            self.axes_Q2 = self.fig.add_subplot(221)
            self.axes_Q3 = self.fig.add_subplot(223)
            self.axes_Q4 = self.fig.add_subplot(224)
            self.axes_Q1.autoscale(enable=True)
            self.axes_Q2.autoscale(enable=True)
            self.axes_Q3.autoscale(enable=True)
            self.axes_Q4.autoscale(enable=True)
            self.axes_Q1.loglog(Q1_x, Q1_y, self.plot_symbol)
            self.axes_Q2.loglog(Q2_x, Q2_y, self.plot_symbol)
            self.axes_Q3.loglog(Q3_x, Q3_y, self.plot_symbol)
            self.axes_Q4.loglog(Q4_x, Q4_y, self.plot_symbol)

            if not hasattr(self, 'flip_Q3'):
                self.flip_Q3 = True

                # Reverse Q2 x-axis
                self.axes_Q2.set_xlim(self.axes_Q2.get_xlim()[::-1])

                # Reverse Q3 x- and y-axes
                self.axes_Q3.set_xlim(self.axes_Q3.get_xlim()[::-1])
                self.axes_Q3.set_ylim(self.axes_Q3.get_ylim()[::-1])

                # Reverse Q4 y-axis
                self.axes_Q4.set_ylim(self.axes_Q4.get_ylim()[::-1])

            # Set axis tickmarks at powers of 10
            # Q1 axes
            if Q1_x == [] and not self.hold_cb.isChecked():
                self.axes_Q1.set_xticklabels([])
                self.axes_Q1.set_yticklabels([])
            else:
                try:
                    x_UB_Q1 = int(ceil(log10(max(Q1_x))))
                    y_UB_Q1 = int(ceil(log10(max(Q1_y))))
                    x_LB_Q1 = int(floor(log10(min(Q1_x))))
                    y_LB_Q1 = int(floor(log10(min(Q1_y))))
                except:
                    x_UB_Q1 = 2
                    y_UB_Q1 = 2
                    x_LB_Q1 = -1
                    y_LB_Q1 = -1
                Q1_xlabels = []
                Q1_ylabels = []
                for i in range(x_LB_Q1, x_UB_Q1 + 1):
                    Q1_xlabels.append('$10^{%s}$' % str(i))
                for i in range(y_LB_Q1, y_UB_Q1 + 1):
                    Q1_ylabels.append('$10^{%s}$' % str(i))
                self.axes_Q1.set_xticklabels(Q1_xlabels)
                self.axes_Q1.set_yticklabels(Q1_ylabels)
            self.axes_Q1.xaxis.tick_top()
            self.axes_Q1.yaxis.tick_right()

            # Q2 axes
            if Q2_x == [] and not self.hold_cb.isChecked():
                self.axes_Q2.set_xticklabels([])
                self.axes_Q2.set_yticklabels([])
            else:
                try:
                    x_UB_Q2 = int(ceil(log10(max(Q2_x))))
                    y_UB_Q2 = int(ceil(log10(max(Q2_y))))
                    x_LB_Q2 = int(floor(log10(min(Q2_x))))
                    y_LB_Q2 = int(floor(log10(min(Q2_y))))
                except:
                    x_UB_Q2 = 2
                    y_UB_Q2 = 2
                    x_LB_Q2 = -1
                    y_LB_Q2 = -1
                Q2_xlabels = []
                Q2_ylabels = []
                for i in range(x_LB_Q2, x_UB_Q2 + 1):
                    Q2_xlabels.append('$-10^{%s}$' % str(i))
                for i in range(y_LB_Q2, y_UB_Q2 + 1):
                    Q2_ylabels.append('$10^{%s}$' % str(i))
                self.axes_Q2.set_xticklabels(Q2_xlabels)
                self.axes_Q2.set_yticklabels(Q2_ylabels)
            self.axes_Q2.xaxis.tick_top()
            self.axes_Q2.yaxis.tick_left()

            # Q3 axes
            if Q3_x == [] and not self.hold_cb.isChecked():
                self.axes_Q3.set_xticklabels([])
                self.axes_Q3.set_yticklabels([])
            else:
                try:
                    x_UB_Q3 = int(ceil(log10(max(Q3_x))))
                    y_UB_Q3 = int(ceil(log10(max(Q3_y))))
                    x_LB_Q3 = int(floor(log10(min(Q3_x))))
                    y_LB_Q3 = int(floor(log10(min(Q3_y))))
                except:
                    x_UB_Q3 = 2
                    y_UB_Q3 = 2
                    x_LB_Q3 = -1
                    y_LB_Q3 = -1
                Q3_xlabels = []
                Q3_ylabels = []
                for i in range(x_LB_Q3, x_UB_Q3 + 1):
                    Q3_xlabels.append('$-10^{%s}$' % str(i))
                for i in range(y_LB_Q3, y_UB_Q3 + 1):
                    Q3_ylabels.append('$-10^{%s}$' % str(i))
                self.axes_Q3.set_xticklabels(Q3_xlabels)
                self.axes_Q3.set_yticklabels(Q3_ylabels)
            self.axes_Q3.xaxis.tick_bottom()
            self.axes_Q3.yaxis.tick_left()

            # Q4 axes
            if Q4_x == [] and not self.hold_cb.isChecked():
                self.axes_Q4.set_xticklabels([])
                self.axes_Q4.set_yticklabels([])
            else:
                try:
                    x_UB_Q4 = int(ceil(log10(max(Q4_x))))
                    y_UB_Q4 = int(ceil(log10(max(Q4_y))))
                    x_LB_Q4 = int(floor(log10(min(Q4_x))))
                    y_LB_Q4 = int(floor(log10(min(Q4_y))))
                except:
                    x_UB_Q4 = 2
                    y_UB_Q4 = 2
                    x_LB_Q4 = -1
                    y_LB_Q4 = -1
                Q4_xlabels = []
                Q4_ylabels = []
                for i in range(x_LB_Q4, x_UB_Q4 + 1):
                    Q4_xlabels.append('$10^{%s}$' % str(i))
                for i in range(y_LB_Q4, y_UB_Q4 + 1):
                    Q4_ylabels.append('$-10^{%s}$' % str(i))
                self.axes_Q4.set_xticklabels(Q4_xlabels)
                self.axes_Q4.set_yticklabels(Q4_ylabels)
            self.axes_Q4.xaxis.tick_bottom()
            self.axes_Q4.yaxis.tick_right()

    def guardarImagen(self):
        path = os.path.abspath("untitled.png")
        self.canvas.resize(460, 261)
        self.canvas.print_figure(path, dpi=self.dpi)
        self.statusBar().showMessage('Saved to %s' % path, 2000)
        self.canvas.resize(560, 361)
예제 #41
0
class CoLocation(QMainWindow, Ui_MainWindow):
    flag = True
    categories = {}
    valid_images = ["jpg","png","tga", "pgm", "jpeg"]
    valid_videos = ["mp4", "avi"]
    edge_threshold = 100
    to_disp = [] 
    
    def __init__(self, ):
        super(CoLocation, self).__init__()        #initialise from the ui designed by Designer App
        self.setupUi(self)
        self.setupUi_custom()
        
    def update_categories(self):
        #update selected categories
        for radiobox in self.findChildren(QtGui.QRadioButton):
            self.categories[radiobox.text()] = radiobox.isChecked()
    
    def setupUi_custom(self,):    
        
        self.scene = QGraphicsScene()
        self.scene2 = QGraphicsScene()
        #TODO [WEIRD PROBLEM] QPixmap needs to be called at least once with JPG image before tensorFlow, otherwise program crashes
        self.scene.addPixmap(QPixmap(os.getcwd()+"/demo.jpg").scaled(self.graphicsView.size(), QtCore.Qt.KeepAspectRatio))
        self.graphicsView.setScene(self.scene)  
        
        import Yolo_module as yolo
        self.classifier = yolo.YOLO_TF()
        #Create thread for heavy processing and tensorflow, pass the instance of itself to modify GUI
        self.image_thread = ImageThread(self, self.classifier)
        #add connect SIGNAL here 
                
        self.pushButton.clicked.connect(self.selectFile)        
        self.horizontalSlider.valueChanged.connect(self.updateLCD)
        self.pushButton_2.clicked.connect(self.image_thread.disp_graph)
        self.pushButton_3.clicked.connect(self.selectFile_from_folder)
        
        #Add blank canvas initially
        fig1 = Figure()            
        self.addmpl(fig1)

    def updateLCD(self):
        #update edge_threshold variable based on slider
        self.edge_threshold = self.horizontalSlider.value()
        self.lcdNumber.display(self.edge_threshold)        
        
    def selectFile(self):  
        #Clear previous image displays        
        self.scene.clear()
        self.scene2.clear()
        self.update_categories()
             
        filename = QFileDialog.getOpenFileName(directory = '/home/yash/Downloads/Pascal VOC 2012/samples')
        self.lineEdit.setText(filename)
        
        if filename.split('.')[1] in self.valid_videos:
            self.image_thread.temp = filename #disp_video(filename)
            self.image_thread.start()
        
        elif filename.split('.')[1] in self.valid_images:
            self.image_thread.disp_img(filename = filename)
            self.image_thread.disp_graph()
            
        else:
            print("Invalid file format")
        
    def selectFile_from_folder(self):
        #Read all the images in the folder
        path = QFileDialog.getExistingDirectory(None, 'Select a folder:', '/home/yash/Downloads/Pascal VOC 2012', QtGui.QFileDialog.ShowDirsOnly)
        self.lineEdit_2.setText(path)
        
        for f in os.listdir(path):              #list all the files in the folder
            ext = f.split('.')[1]        #get the file extension
            if ext.lower() not in self.valid_images: #check if the extension is valid for the image
                continue
            filename = path+'/'+f               #create the path of the image
            print(filename)
            
            self.image_thread.tag_image(filename, batch = True)
        
        #clear the image regions during batch upload
        self.scene.clear()
        self.scene2.clear()    
        
        self.image_thread.disp_graph(batch = True)
        
    def addmpl(self, fig):
        #Add figure to canvas and widget
        self.canvas = FigureCanvas(fig)
        self.mplvl.addWidget(self.canvas)
        self.canvas.draw()
 
    def rmmpl(self,):
        #remove the canvas and widget
        self.mplvl.removeWidget(self.canvas)
        self.canvas.close()
예제 #42
0
class ProfileDockWidget(QDockWidget):
    """
    DockWidget class to display the profile
    """

    closeSignal = pyqtSignal()

    def __init__(self, iface, geometry, mntButton=False, zerosButton=False):
        """
        Constructor
        :param iface: interface
        :param width: dock widget geometry
        """
        QDockWidget.__init__(self)
        self.setWindowTitle(
            QCoreApplication.translate("VDLTools", "Profile Tool"))
        self.__iface = iface
        self.__geom = geometry
        self.__canvas = self.__iface.mapCanvas()
        self.__types = ['PDF', 'PNG']  # ], 'SVG', 'PS']
        self.__libs = []
        if Qwt5_loaded:
            self.__lib = 'Qwt5'
            self.__libs.append('Qwt5')
            if matplotlib_loaded:
                self.__libs.append('Matplotlib')
        elif matplotlib_loaded:
            self.__lib = 'Matplotlib'
            self.__libs.append('Matplotlib')
        else:
            self.__lib = None
            self.__iface.messageBar().pushMessage(QCoreApplication.translate(
                "VDLTools", "No graph lib available (qwt5 or matplotlib)"),
                                                  level=QgsMessageBar.CRITICAL,
                                                  duration=0)

        self.__doTracking = False
        self.__vline = None

        self.__profiles = None
        self.__numLines = None
        self.__mntPoints = None

        self.__marker = None
        self.__tabmouseevent = None

        if self.__geom is not None:
            self.setGeometry(self.__geom)

        self.__contentWidget = QWidget()
        self.setWidget(self.__contentWidget)

        self.__boxLayout = QHBoxLayout()
        self.__contentWidget.setLayout(self.__boxLayout)

        self.__plotFrame = QFrame()
        self.__frameLayout = QHBoxLayout()
        self.__plotFrame.setLayout(self.__frameLayout)

        self.__printLayout = QHBoxLayout()
        self.__printLayout.addWidget(self.__plotFrame)

        self.__legendLayout = QVBoxLayout()
        self.__printLayout.addLayout(self.__legendLayout)

        self.__printWdg = QWidget()
        self.__printWdg.setLayout(self.__printLayout)

        self.__plotWdg = None
        self.__scaleButton = None
        self.__changePlotWidget()

        size = QSize(150, 20)

        self.__boxLayout.addWidget(self.__printWdg)

        self.__vertLayout = QVBoxLayout()

        self.__libCombo = QComboBox()
        self.__libCombo.setFixedSize(size)
        self.__libCombo.addItems(self.__libs)
        self.__vertLayout.addWidget(self.__libCombo)
        self.__libCombo.currentIndexChanged.connect(self.__setLib)

        if mntButton:
            self.__displayMnt = False
            self.__mntButton = QPushButton(
                QCoreApplication.translate("VDLTools", "Display MNT"))
            self.__mntButton.setFixedSize(size)
            self.__mntButton.clicked.connect(self.__mnt)
            self.__vertLayout.addWidget(self.__mntButton)

        if zerosButton:
            self.__displayZeros = False
            self.__zerosButton = QPushButton(
                QCoreApplication.translate("VDLTools", "Display Zeros"))
            self.__zerosButton.setFixedSize(size)
            self.__zerosButton.clicked.connect(self.__zeros)
            self.__vertLayout.addWidget(self.__zerosButton)
        else:
            self.__displayZeros = True

        self.__scale11 = False
        self.__scaleButton = QPushButton(
            QCoreApplication.translate("VDLTools", "Scale 1:1"))
        self.__scaleButton.setFixedSize(size)
        self.__scaleButton.clicked.connect(self.__scale)
        if self.__lib == 'Qwt5':
            self.__scaleButton.setVisible(True)
        else:
            self.__scaleButton.setVisible(False)
        self.__vertLayout.addWidget(self.__scaleButton)

        self.__maxLabel = QLabel("y max")
        self.__maxLabel.setFixedSize(size)
        self.__vertLayout.addWidget(self.__maxLabel)
        self.__maxSpin = QSpinBox()
        self.__maxSpin.setFixedSize(size)
        self.__maxSpin.setRange(-10000, 10000)
        self.__maxSpin.valueChanged.connect(self.__reScalePlot)
        self.__vertLayout.addWidget(self.__maxSpin)
        self.__vertLayout.insertSpacing(10, 20)

        self.__minLabel = QLabel("y min")
        self.__minLabel.setFixedSize(size)
        self.__vertLayout.addWidget(self.__minLabel)
        self.__minSpin = QSpinBox()
        self.__minSpin.setFixedSize(size)
        self.__minSpin.setRange(-10000, 10000)
        self.__minSpin.valueChanged.connect(self.__reScalePlot)
        self.__vertLayout.addWidget(self.__minSpin)
        self.__vertLayout.insertSpacing(10, 40)

        self.__typeCombo = QComboBox()
        self.__typeCombo.setFixedSize(size)
        self.__typeCombo.addItems(self.__types)
        self.__vertLayout.addWidget(self.__typeCombo)
        self.__saveButton = QPushButton(
            QCoreApplication.translate("VDLTools", "Save"))
        self.__saveButton.setFixedSize(size)
        self.__saveButton.clicked.connect(self.__save)
        self.__vertLayout.addWidget(self.__saveButton)

        self.__boxLayout.addLayout(self.__vertLayout)

        self.__maxSpin.setEnabled(False)
        self.__minSpin.setEnabled(False)

        self.__colors = []
        for cn in QColor.colorNames():
            qc = QColor(cn)
            val = qc.red() + qc.green() + qc.blue()
            if 0 < val < 450:
                self.__colors.append(cn)

    def mntButton(self):
        """
        To get the mnt button instance
        :return: mnt button instance
        """
        return self.__mntButton

    def zerosButton(self):
        """
        To get the zeros button instance
        :return: zeros button instance
        """
        return self.__zerosButton

    def scaleButton(self):
        """
        To get the scale button instance
        :return: scale button instance
        """
        return self.__scaleButton

    def displayMnt(self):
        """
        To get if we want to display mnt
        :return: true or false
        """
        return self.__displayMnt

    def __scale(self):
        if self.__scale11:
            self.__scale11 = False
            self.__scaleButton.setText(
                QCoreApplication.translate("VDLTools", "Scale 1:1"))
        else:
            self.__scale11 = True
            self.__scaleButton.setText(
                QCoreApplication.translate("VDLTools", "Auto scale"))

    def __mnt(self):
        """
        To toggle mnt display choice
        """
        if self.__displayMnt:
            self.__displayMnt = False
            self.__mntButton.setText(
                QCoreApplication.translate("VDLTools", "Display MNT"))
        else:
            self.__displayMnt = True
            self.__mntButton.setText(
                QCoreApplication.translate("VDLTools", "Remove MNT"))

    def __zeros(self):
        """
        To toggle if we want to display zero elevations or not
        """
        if self.__displayZeros:
            self.__displayZeros = False
            self.__zerosButton.setText(
                QCoreApplication.translate("VDLTools", "Display Zeros"))
        else:
            self.__displayZeros = True
            self.__zerosButton.setText(
                QCoreApplication.translate("VDLTools", "Remove Zeros"))

    def __changePlotWidget(self):
        """
        When plot widget is change (qwt <-> matplotlib)
        """
        self.__activateMouseTracking(False)
        while self.__frameLayout.count():
            child = self.__frameLayout.takeAt(0)
            child.widget().deleteLater()
        self.__plotWdg = None

        if self.__lib == 'Qwt5':
            self.__plotWdg = QwtPlot(self.__plotFrame)
            sizePolicy = QSizePolicy(QSizePolicy.Expanding,
                                     QSizePolicy.Expanding)
            sizePolicy.setHorizontalStretch(10)
            sizePolicy.setVerticalStretch(0)
            self.__plotWdg.setSizePolicy(sizePolicy)
            self.__plotWdg.setAutoFillBackground(False)
            # Decoration
            self.__plotWdg.setCanvasBackground(Qt.white)
            self.__plotWdg.plotLayout().setAlignCanvasToScales(False)
            self.__plotWdg.plotLayout().setSpacing(100)
            self.__plotWdg.plotLayout().setCanvasMargin(10, QwtPlot.xBottom)
            self.__plotWdg.plotLayout().setCanvasMargin(10, QwtPlot.yLeft)
            title = QwtText(
                QCoreApplication.translate("VDLTools", "Distance [m]"))
            title.setFont(QFont("Helvetica", 10))
            self.__plotWdg.setAxisTitle(QwtPlot.xBottom, title)
            title.setText(
                QCoreApplication.translate("VDLTools", "Elevation [m]"))
            title.setFont(QFont("Helvetica", 10))
            self.__plotWdg.setAxisTitle(QwtPlot.yLeft, title)
            self.__zoomer = QwtPlotZoomer(QwtPlot.xBottom, QwtPlot.yLeft,
                                          QwtPicker.DragSelection,
                                          QwtPicker.AlwaysOff,
                                          self.__plotWdg.canvas())
            self.__zoomer.zoomed.connect(self.__scaleZoom)
            self.__zoomer.setRubberBandPen(QPen(Qt.blue))
            grid = QwtPlotGrid()
            grid.setPen(QPen(QColor('grey'), 0, Qt.DotLine))
            grid.attach(self.__plotWdg)
            self.__frameLayout.addWidget(self.__plotWdg)
            if self.__scaleButton is not None:
                self.__scaleButton.setVisible(True)

        elif self.__lib == 'Matplotlib':
            fig = Figure((1.0, 1.0),
                         linewidth=0.0,
                         subplotpars=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.__axes = fig.add_axes((0.07, 0.16, 0.92, 0.82))
            self.__axes.set_xbound(0, 1000)
            self.__axes.set_ybound(0, 1000)
            self.__manageMatplotlibAxe(self.__axes)
            self.__plotWdg = FigureCanvasQTAgg(fig)
            sizePolicy = QSizePolicy(QSizePolicy.Expanding,
                                     QSizePolicy.Expanding)
            sizePolicy.setHorizontalStretch(0)
            sizePolicy.setVerticalStretch(0)
            self.__plotWdg.setSizePolicy(sizePolicy)
            self.__frameLayout.addWidget(self.__plotWdg)
            if self.__scaleButton is not None:
                self.__scaleButton.setVisible(False)

    def setProfiles(self, profiles, numLines):
        """
        To set the profiles
        :param profiles: profiles : positions with elevations (for line and points)
        :param numLines: number of selected connected lines
        """
        self.__numLines = numLines
        self.__profiles = profiles
        if self.__lib == 'Matplotlib':
            self.__prepare_points()

    def __getLinearPoints(self):
        """
        To extract the linear points of the profile
        """
        profileLen = 0
        self.__profiles[0]['l'] = profileLen
        for i in range(0, len(self.__profiles) - 1):
            x1 = float(self.__profiles[i]['x'])
            y1 = float(self.__profiles[i]['y'])
            x2 = float(self.__profiles[i + 1]['x'])
            y2 = float(self.__profiles[i + 1]['y'])
            profileLen += sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1) *
                                                          (y2 - y1)))
            self.__profiles[i + 1]['l'] = profileLen

    def __getMnt(self, settings):
        """
        To get the MNT data for the profile
        :param settings: settings containing MNT url
        """
        if settings is None or settings.mntUrl is None or settings.mntUrl == "None":
            url = 'https://map.lausanne.ch/prod/wsgi/profile.json'
        elif settings.mntUrl == "":
            return
        else:
            url = settings.mntUrl
        names = ['MNT', 'MNS', 'Rocher (approx.)']
        data = "layers=MNT%2CMNS%2CRocher%20(approx.)&geom=%7B%22type%22%3A%22LineString%22%2C%22coordinates%22%3A%5B"

        pos = 0
        for i in range(len(self.__profiles)):
            if pos > 0:
                data += "%2C"
            pos += 1
            data += "%5B" + str(self.__profiles[i]['x']) + "%2C" + str(
                self.__profiles[i]['y']) + "%5D"
        data += "%5D%7D&nbPoints=" + str(
            int(self.__profiles[len(self.__profiles) - 1]['l'] + 1))
        try:
            response = requests.post(url, data=data)
            j = response.text
            j_obj = json.loads(j)
            profile = j_obj['profile']
            self.__mntPoints = []
            self.__mntPoints.append(names)
            mnt_l = []
            mnt_z = []
            for p in range(len(names)):
                z = []
                mnt_z.append(z)
            for pt in profile:
                mnt_l.append(float(pt['dist']))
                values = pt['values']
                for p in range(len(names)):
                    if names[p] in values:
                        mnt_z[p].append(float(values[names[p]]))
                    else:
                        mnt_z[p].append(None)
            self.__mntPoints.append(mnt_l)
            self.__mntPoints.append(mnt_z)
        except HTTPError as e:
            self.__iface.messageBar().pushMessage(
                QCoreApplication.translate("VDLTools", "HTTP Error"),
                QCoreApplication.translate("VDLTools", "status error") + "[" +
                str(e.code) + "] : " + e.reason,
                level=QgsMessageBar.CRITICAL,
                duration=0)
        except URLError as e:
            self.__iface.messageBar().pushMessage(QCoreApplication.translate(
                "VDLTools", "URL Error"),
                                                  e.reason,
                                                  level=QgsMessageBar.CRITICAL,
                                                  duration=0)
        except ValueError as e:
            self.__iface.messageBar().pushMessage(QCoreApplication.translate(
                "VDLTools", "No MNT values here"),
                                                  level=QgsMessageBar.CRITICAL,
                                                  duration=0)

    def attachCurves(self, names, settings, usedMnts):
        """
        To attach the curves for the layers to the profile
        :param names: layers names
        :param settings: project settings
        :param usedMnts: if use mnt or not
        """
        if (self.__profiles is None) or (self.__profiles == 0):
            return

        self.__getLinearPoints()
        if usedMnts is not None and (usedMnts[0] or usedMnts[1]
                                     or usedMnts[2]):
            self.__getMnt(settings)

        c = 0

        if self.__mntPoints is not None:
            for p in range(len(self.__mntPoints[0])):
                if usedMnts[p]:
                    legend = QLabel("<font color='" + self.__colors[c] + "'>" +
                                    self.__mntPoints[0][p] + "</font>")
                    self.__legendLayout.addWidget(legend)

                    if self.__lib == 'Qwt5':

                        xx = [
                            list(g) for k, g in itertools.groupby(
                                self.__mntPoints[1], lambda x: x is None)
                            if not k
                        ]
                        yy = [
                            list(g) for k, g in itertools.groupby(
                                self.__mntPoints[2][p], lambda x: x is None)
                            if not k
                        ]

                        for j in range(len(xx)):
                            curve = QwtPlotCurve(self.__mntPoints[0][p])
                            curve.setData(xx[j], yy[j])
                            curve.setPen(QPen(QColor(self.__colors[c]), 3))
                            curve.attach(self.__plotWdg)

                    elif self.__lib == 'Matplotlib':
                        qcol = QColor(self.__colors[c])
                        self.__plotWdg.figure.get_axes()[0].plot(
                            self.__mntPoints[1],
                            self.__mntPoints[2][p],
                            gid=self.__mntPoints[0][p],
                            linewidth=3)
                        tmp = self.__plotWdg.figure.get_axes()[0].get_lines()
                        for t in range(len(tmp)):
                            if self.__mntPoints[0][p] == tmp[t].get_gid():
                                tmp[c].set_color((old_div(qcol.red(), 255.0),
                                                  old_div(qcol.green(), 255.0),
                                                  old_div(qcol.blue(), 255.0),
                                                  old_div(qcol.alpha(),
                                                          255.0)))
                                self.__plotWdg.draw()
                                break
                    c += 1

        if 'z' in self.__profiles[0]:
            for i in range(len(self.__profiles[0]['z'])):
                if i < self.__numLines:
                    v = 0
                else:
                    v = i - self.__numLines + 1
                name = names[v]
                xx = []
                yy = []
                for prof in self.__profiles:
                    if isinstance(prof['z'][i], list):
                        for z in prof['z'][i]:
                            xx.append(prof['l'])
                            yy.append(z)
                    else:
                        xx.append(prof['l'])
                        yy.append(prof['z'][i])

                for j in range(len(yy)):
                    if yy[j] is None:
                        xx[j] = None

                if i == 0 or i > (self.__numLines - 1):
                    legend = QLabel("<font color='" + self.__colors[c] + "'>" +
                                    name + "</font>")
                    self.__legendLayout.addWidget(legend)

                if self.__lib == 'Qwt5':

                    # Split xx and yy into single lines at None values
                    xx = [
                        list(g)
                        for k, g in itertools.groupby(xx, lambda x: x is None)
                        if not k
                    ]
                    yy = [
                        list(g)
                        for k, g in itertools.groupby(yy, lambda x: x is None)
                        if not k
                    ]

                    # Create & attach one QwtPlotCurve per one single line
                    for j in range(len(xx)):
                        curve = QwtPlotCurve(name)
                        curve.setData(xx[j], yy[j])
                        curve.setPen(QPen(QColor(self.__colors[c]), 3))
                        if i > (self.__numLines - 1):
                            curve.setStyle(QwtPlotCurve.Dots)
                            pen = QPen(QColor(self.__colors[c]), 8)
                            pen.setCapStyle(Qt.RoundCap)
                            curve.setPen(pen)
                        curve.attach(self.__plotWdg)

                elif self.__lib == 'Matplotlib':
                    qcol = QColor(self.__colors[c])
                    if i < self.__numLines:
                        self.__plotWdg.figure.get_axes()[0].plot(xx,
                                                                 yy,
                                                                 gid=name,
                                                                 linewidth=3)
                    else:
                        self.__plotWdg.figure.get_axes()[0].plot(
                            xx,
                            yy,
                            gid=name,
                            linewidth=5,
                            marker='o',
                            linestyle='None')
                    tmp = self.__plotWdg.figure.get_axes()[0].get_lines()
                    for t in range(len(tmp)):
                        if name == tmp[t].get_gid():
                            tmp[c].set_color(
                                (old_div(qcol.red(),
                                         255.0), old_div(qcol.green(), 255.0),
                                 old_div(qcol.blue(),
                                         255.0), old_div(qcol.alpha(), 255.0)))
                            self.__plotWdg.draw()
                            break
                c += 1

        # scaling this
        try:
            self.__reScalePlot(None, True)
        except:
            self.__iface.messageBar().pushMessage(QCoreApplication.translate(
                "VDLTools", "Rescale problem... (trace printed)"),
                                                  level=QgsMessageBar.CRITICAL,
                                                  duration=0)
            print(sys.exc_info()[0], traceback.format_exc())
        if self.__lib == 'Qwt5':
            self.__plotWdg.replot()
        elif self.__lib == 'Matplotlib':
            self.__plotWdg.figure.get_axes()[0].redraw_in_frame()
            self.__plotWdg.draw()
            self.__activateMouseTracking(True)
            self.__marker.show()

    def __scaleZoom(self):
        if self.__scale11:
            rect = self.__zoomer.zoomRect()
            plot = self.__zoomer.plot()
            width = plot.canvas().width()
            height = plot.canvas().height()
            length = rect.right() - rect.left()
            density = length / width
            interval = density * height
            middle = (rect.top() + rect.bottom()) / 2
            maximumValue = middle + (interval / 2)
            minimumValue = middle - (interval / 2)

            inter = pow(10, floor(log10(length)))
            if length / inter > 5:
                inter = 2 * inter
            step = inter / 2
            plot.setAxisScale(2, rect.left(), rect.right(), step)
            plot.setAxisScale(0, minimumValue, maximumValue, step)
            plot.replot()

    def __reScalePlot(self, value=None, auto=False):
        """
        To rescale the profile plot depending to the bounds
        :param value: juste because connections give value
        :param auto: if automatic ranges calcul is wanted
        """
        if (self.__profiles is None) or (self.__profiles == 0):
            self.__plotWdg.replot()
            return

        length = 0
        for i in range(len(self.__profiles)):
            if (ceil(self.__profiles[i]['l'])) > length:
                length = ceil(self.__profiles[i]['l'])
        if self.__lib == 'Qwt5':
            self.__plotWdg.setAxisScale(2, 0, length, 0)
        elif self.__lib == 'Matplotlib':
            self.__plotWdg.figure.get_axes()[0].set_xbound(0, length)

        minimumValue = self.__minSpin.value()
        maximumValue = self.__maxSpin.value()

        # to set max y and min y displayed
        if auto:
            minimumValue = 1000000000
            maximumValue = -1000000000
            for i in range(len(self.__profiles)):
                if 'z' in self.__profiles[i]:
                    mini = self.__minTab(self.__profiles[i]['z'])
                    if (mini > 0
                            or self.__displayZeros) and mini < minimumValue:
                        minimumValue = ceil(mini) - 1
                    maxi = self.__maxTab(self.__profiles[i]['z'])
                    if maxi > maximumValue:
                        maximumValue = floor(maxi) + 1
                if self.__mntPoints is not None:
                    for pts in self.__mntPoints[2]:
                        miniMnt = self.__minTab(pts)
                        if (miniMnt > 0 or self.__displayZeros
                            ) and miniMnt < minimumValue:
                            minimumValue = ceil(miniMnt) - 1
                        maxiMnt = self.__maxTab(pts)
                        if maxiMnt > maximumValue:
                            maximumValue = floor(maxiMnt) + 1

        if self.__scale11:
            width = self.__plotWdg.canvas().width()
            height = self.__plotWdg.canvas().height()
            density = length / width
            interval = density * height
            middle = (maximumValue + minimumValue) / 2
            maximumValue = middle + (interval / 2)
            minimumValue = middle - (interval / 2)

        self.__maxSpin.valueChanged.disconnect(self.__reScalePlot)
        self.__maxSpin.setValue(maximumValue)
        self.__maxSpin.valueChanged.connect(self.__reScalePlot)
        self.__minSpin.valueChanged.disconnect(self.__reScalePlot)
        self.__minSpin.setValue(minimumValue)
        self.__minSpin.valueChanged.connect(self.__reScalePlot)
        self.__maxSpin.setEnabled(True)
        self.__minSpin.setEnabled(True)

        # to draw vertical lines
        for i in range(len(self.__profiles)):
            zz = []
            for j in range(self.__numLines):
                if self.__profiles[i]['z'][j] is not None:
                    zz.append(j)
            color = None
            if len(zz) == 2:
                width = 3
                color = QColor('red')
            else:
                width = 1

            if self.__lib == 'Qwt5':
                vertLine = QwtPlotMarker()
                vertLine.setLineStyle(QwtPlotMarker.VLine)
                pen = vertLine.linePen()
                pen.setWidth(width)
                if color is not None:
                    pen.setColor(color)
                vertLine.setLinePen(pen)
                vertLine.setXValue(self.__profiles[i]['l'])
                label = vertLine.label()
                label.setText(str(i))
                vertLine.setLabel(label)
                vertLine.setLabelAlignment(Qt.AlignLeft)
                vertLine.attach(self.__plotWdg)
            elif self.__lib == 'Matplotlib':
                self.__plotWdg.figure.get_axes()[0].vlines(
                    self.__profiles[i]['l'],
                    minimumValue,
                    maximumValue,
                    linewidth=width)

        if minimumValue < maximumValue:
            if self.__lib == 'Qwt5':
                step = 0
                if self.__scale11:
                    inter = pow(10, floor(log10(length)))
                    if length / inter > 5:
                        inter = 2 * inter
                    step = inter / 2
                    self.__plotWdg.setAxisScale(2, 0, length, step)
                self.__plotWdg.setAxisScale(0, minimumValue, maximumValue,
                                            step)
                self.__plotWdg.replot()
            elif self.__lib == 'Matplotlib':
                self.__plotWdg.figure.get_axes()[0].set_ybound(
                    minimumValue, maximumValue)
                self.__plotWdg.figure.get_axes()[0].redraw_in_frame()
                self.__plotWdg.draw()

        if self.__lib == 'Qwt5':
            rect = QRectF(0, minimumValue, length, maximumValue - minimumValue)
            self.__zoomer.setZoomBase(rect)

    @staticmethod
    def __minTab(tab):
        """
        To get the minimum value in a table
        :param tab: table to scan
        :return: minimum value
        """
        mini = 1000000000
        for t in tab:
            if isinstance(t, list):
                for ti in t:
                    if ti is None:
                        continue
                    if ti < mini:
                        mini = ti
            else:
                if t is None:
                    continue
                if t < mini:
                    mini = t
        return mini

    @staticmethod
    def __maxTab(tab):
        """
        To get the maximum value in a table
        :param tab: table to scan
        :return: maximum value
        """
        maxi = -1000000000
        for t in tab:
            if isinstance(t, list):
                for ti in t:
                    if ti is None:
                        continue
                    if ti > maxi:
                        maxi = ti
            else:
                if t is None:
                    continue
                if t > maxi:
                    maxi = t
        return maxi

    def __setLib(self):
        """
        To set the new widget library (qwt <-> matplotlib)
        """
        self.__lib = self.__libs[self.__libCombo.currentIndex()]
        self.__changePlotWidget()

    def __save(self):
        """
        To save the profile in a file, on selected format
        """
        idx = self.__typeCombo.currentIndex()
        if idx == 0:
            self.__outPDF()
        elif idx == 1:
            self.__outPNG()
        else:
            self.__iface.messageBar().pushMessage(
                QCoreApplication.translate("VDLTools", "Invalid index ") +
                str(idx),
                level=QgsMessageBar.CRITICAL,
                duration=0)

    def __outPDF(self):
        """
        To save the profile as pdf file
        """
        fileName = QFileDialog.getSaveFileName(
            self.__iface.mainWindow(),
            QCoreApplication.translate("VDLTools", "Save As"),
            QCoreApplication.translate("VDLTools", "Profile.pdf"),
            "Portable Document Format (*.pdf)")
        if fileName is not None:
            if self.__lib == 'Qwt5':
                printer = QPrinter()
                printer.setCreator(
                    QCoreApplication.translate("VDLTools",
                                               "QGIS Profile Plugin"))
                printer.setOutputFileName(fileName)
                printer.setOutputFormat(QPrinter.PdfFormat)
                printer.setOrientation(QPrinter.Landscape)
                self.__plotWdg.print_(printer)
            elif self.__lib == 'Matplotlib':
                self.__plotWdg.figure.savefig(str(fileName))

    def __outPNG(self):
        """
        To save the profile as png file
        """
        fileName = QFileDialog.getSaveFileName(
            self.__iface.mainWindow(),
            QCoreApplication.translate("VDLTools", "Save As"),
            QCoreApplication.translate("VDLTools", "Profile.png"),
            "Portable Network Graphics (*.png)")
        if fileName is not None:
            QPixmap.grabWidget(self.__printWdg).save(fileName, "PNG")

    def clearData(self):
        """
        To clear the displayed data
        """
        if self.__profiles is None:
            return
        if self.__lib == 'Qwt5':
            self.__plotWdg.clear()
            self.__profiles = None
            temp1 = self.__plotWdg.itemList()
            for j in range(len(temp1)):
                if temp1[j].rtti() == QwtPlotItem.Rtti_PlotCurve:
                    temp1[j].detach()
        elif self.__lib == 'Matplotlib':
            self.__plotWdg.figure.get_axes()[0].cla()
            self.__manageMatplotlibAxe(self.__plotWdg.figure.get_axes()[0])
        self.__maxSpin.setEnabled(False)
        self.__minSpin.setEnabled(False)
        self.__maxSpin.valueChanged.disconnect(self.__reScalePlot)
        self.__maxSpin.setValue(0)
        self.__maxSpin.valueChanged.connect(self.__reScalePlot)
        self.__minSpin.valueChanged.disconnect(self.__reScalePlot)
        self.__minSpin.setValue(0)
        self.__minSpin.valueChanged.connect(self.__reScalePlot)

        # clear legend
        while self.__legendLayout.count():
            child = self.__legendLayout.takeAt(0)
            child.widget().deleteLater()

    def __manageMatplotlibAxe(self, axe):
        """
        To manage the axes for matplotlib library
        :param axe: the axes element
        """
        axe.grid()
        axe.tick_params(axis="both",
                        which="major",
                        direction="out",
                        length=10,
                        width=1,
                        bottom=True,
                        top=False,
                        left=True,
                        right=False)
        axe.minorticks_on()
        axe.tick_params(axis="both",
                        which="minor",
                        direction="out",
                        length=5,
                        width=1,
                        bottom=True,
                        top=False,
                        left=True,
                        right=False)
        axe.set_xlabel(QCoreApplication.translate("VDLTools", "Distance [m]"))
        axe.set_ylabel(QCoreApplication.translate("VDLTools", "Elevation [m]"))

    def __activateMouseTracking(self, activate):
        """
        To (de)activate the mouse tracking on the profile for matplotlib library
        :param activate: true to activate, false to deactivate
        """
        if activate:
            self.__doTracking = True
            self.__loadRubber()
            self.cid = self.__plotWdg.mpl_connect('motion_notify_event',
                                                  self.__mouseevent_mpl)
        elif self.__doTracking:
            self.__doTracking = False
            self.__plotWdg.mpl_disconnect(self.cid)
            if self.__marker is not None:
                self.__canvas.scene().removeItem(self.__marker)
            try:
                if self.__vline is not None:
                    self.__plotWdg.figure.get_axes()[0].lines.remove(
                        self.__vline)
                    self.__plotWdg.draw()
            except Exception as e:
                self.__iface.messageBar().pushMessage(
                    QCoreApplication.translate(
                        "VDLTools", "Tracking exception : ") + str(e),
                    level=QgsMessageBar.CRITICAL,
                    duration=0)

    def __mouseevent_mpl(self, event):
        """
        To manage matplotlib mouse tracking event
        :param event: mouse tracking event
        """
        if event.xdata is not None:
            try:
                if self.__vline is not None:
                    self.__plotWdg.figure.get_axes()[0].lines.remove(
                        self.__vline)
            except Exception as e:
                self.__iface.messageBar().pushMessage(
                    QCoreApplication.translate(
                        "VDLTools", "Mouse event exception : ") + str(e),
                    level=QgsMessageBar.CRITICAL,
                    duration=0)
            xdata = float(event.xdata)
            self.__vline = self.__plotWdg.figure.get_axes()[0].axvline(
                xdata, linewidth=2, color='k')
            self.__plotWdg.draw()
            i = 1
            while i < len(self.__tabmouseevent
                          ) - 1 and xdata > self.__tabmouseevent[i][0]:
                i += 1
            i -= 1

            x = self.__tabmouseevent[i][1] + (
                self.__tabmouseevent[i + 1][1] - self.__tabmouseevent[i][1]
            ) / (self.__tabmouseevent[i + 1][0] - self.__tabmouseevent[i][0]
                 ) * (xdata - self.__tabmouseevent[i][0])
            y = self.__tabmouseevent[i][2] + (
                self.__tabmouseevent[i + 1][2] - self.__tabmouseevent[i][2]
            ) / (self.__tabmouseevent[i + 1][0] - self.__tabmouseevent[i][0]
                 ) * (xdata - self.__tabmouseevent[i][0])
            self.__marker.show()
            self.__marker.setCenter(QgsPoint(x, y))

    def __loadRubber(self):
        """
        To load te rubber band for mouse tracking on map
        """
        self.__marker = QgsVertexMarker(self.__canvas)
        self.__marker.setIconSize(5)
        self.__marker.setIconType(QgsVertexMarker.ICON_BOX)
        self.__marker.setPenWidth(3)

    def __prepare_points(self):
        """
        To prepare the points on map for mouse tracking on profile
        """
        self.__tabmouseevent = []
        length = 0
        for i, point in enumerate(self.__profiles):
            if i == 0:
                self.__tabmouseevent.append([0, point['x'], point['y']])
            else:
                length += ((self.__profiles[i]['x'] -
                            self.__profiles[i - 1]['x'])**2 +
                           (self.__profiles[i]['y'] -
                            self.__profiles[i - 1]['y'])**2)**0.5
                self.__tabmouseevent.append(
                    [float(length),
                     float(point['x']),
                     float(point['y'])])

    def closeEvent(self, event):
        """
        When the dock widget is closed
        :param event: close event
        """
        if self.__maxSpin is not None:
            Signal.safelyDisconnect(self.__maxSpin.valueChanged,
                                    self.__reScalePlot)
            self.__maxSpin = None
        if self.__minSpin is not None:
            Signal.safelyDisconnect(self.__minSpin.valueChanged,
                                    self.__reScalePlot)
            self.__minSpin = None
        if self.__saveButton is not None:
            Signal.safelyDisconnect(self.__saveButton.clicked, self.__save)
            self.__saveButton = None
        if self.__libCombo is not None:
            Signal.safelyDisconnect(self.__libCombo.currentIndexChanged,
                                    self.__setLib)
            self.__libCombo = None
        self.closeSignal.emit()
        if self.__marker is not None:
            self.__marker.hide()
        QDockWidget.closeEvent(self, event)
예제 #43
0
class mGraph(QtGui.QWidget):
    def __init__(self, device, parent=None):
        QtGui.QWidget.__init__(self, parent)
        # Create a matplotlib figure.
        self.figure = plt.figure()
        self.figure.set_facecolor('r')
        # Create a QFrame to house the plot. This is not necessary,
        # just makes it look nice.
        self.matframe = QtGui.QFrame()
        self.matLayout = QtGui.QVBoxLayout()
        self.matLayout.setSpacing(0)
        self.matframe.setLayout(self.matLayout)
        self.matframe.setFrameShape(QtGui.QFrame.Panel)
        self.matframe.setFrameShadow(QtGui.QFrame.Plain)
        self.matframe.setStyleSheet("background-color: rgb(70,80,88); "
                                    "margin:0px; border:2px solid rgb(0, 0, 0); ")
        self.canvas = FigureCanvas(self.figure)
        self.canvas.setSizePolicy(QtGui.QSizePolicy.Preferred,
                                  QtGui.QSizePolicy.Preferred)
        # This is the device we want to use.
        self.device = device
        # This sets up axis on which to plot.
        color = (189. / 255, 195. / 255, 199. / 255)
        self.ax = self.figure.add_subplot(111, axisbg=color)
        ax = self.ax
        # Add the matplotlib canvas to the QFrame.
        self.matLayout.addWidget(self.canvas)
        # The following lines set up all the colors, makes it look nice.
        # The code to do it is far from pretty and I am planning
        # on cleaning this up a bit.
        self.figure.patch.set_color((70. / 255, 80. / 255, 88. / 255))
        self.figure.patch.set_edgecolor((70. / 255, 80. / 255, 88. / 255))
        ax.spines['bottom'].set_color(color)
        ax.spines['top'].set_color(color)
        ax.spines['right'].set_color(color)
        ax.spines['left'].set_color(color)
        ax.tick_params(axis='x', colors=color)
        ax.tick_params(axis='y', colors=color)
        ax.title.set_color(color)
        ax.yaxis.label.set_color(color)
        ax.xaxis.label.set_color(color)
        ax.xaxis.get_offset_text().set_color(color)
        ax.yaxis.get_offset_text().set_color(color)
        # This is an array of all the lines on the plot. A line for
        # every parameter.
        self.line = []
        self.mins = 0
        self.maxes = 1
        # Each element of line holds a plot, to be combined onto
        # the same graph.
        self.line.append(ax.plot(1, 1, label="Getting Data...")[0])

        # In order to handle interactivity, I had to do some odd stuff
        # with the toolbar buttons: self.home holds the original
        # function called when the home button on the toolbar
        # is clicked.
        self.home = NavigationToolbar.home
        # We now change the function that is called when the toolbar is
        # clicked.
        NavigationToolbar.home = self.enableAutoScaling
        self.toolbar = NavigationToolbar(self.canvas, self)

        self.cid = self.canvas.mpl_connect('button_press_event',
                                           self.disableAutoScaling)
        self.setStyleSheet("QPushButton{\
                    color:rgb(189,195, 199); \
                    background:rgb(70, 80, 88)};")
        self.fullGraphBtn = QtGui.QPushButton("Show Interactive Graph")
        self.fullGraphBtn.clicked.connect(self.openFullGraphGui)
        self.toolbarFrame = QtGui.QFrame()
        toolbarFrameLayout = QtGui.QVBoxLayout()
        toolbarFrameLayout.addWidget(self.toolbar)
        self.toolbar.setParent(None)
        self.toolbarFrame.setLayout(toolbarFrameLayout)
        self.toolbarFrame.setStyleSheet("\
                   border:2px solid rgb(0,0,0);\
                   color:rgb(189,195,199); \
                   background:rgb(70, 80, 88);")
        self.toolbar.setStyleSheet("\
                   border:0px solid rgb(0,0,0);\
                   QDialog{background:rgb(70, 80, 88)}")
        self.matPlotInfo = QtGui.QLabel()
        self.alertFont = QtGui.QFont()
        self.alertFont.setPointSize(12)
        self.matPlotInfo.setStyleSheet("color:rgb(200, 69, 50);")
        self.matPlotInfo.setText("Auto refresh disabled, "
                                 "click HOME button to enable.")
        self.matPlotInfo.setFont(self.alertFont)

        #self.refreshRateSec = device.getFrame().getPlotRefreshRate()
        self.refreshRateSec = device.getFrame().getPlotRefreshRate()
        self.timer = QtCore.QTimer(self)

        self.hidden = True
        self.home = True
        self.initialized = False
        self.currTimeRange = 120
        self.lineSelect = MCheckableComboBox()
        self.lineSelect.setSizeAdjustPolicy(0)
        self.lineSelect.setStyleSheet("\
                    background-color:rgb(70, 80, 88);\
                    color:rgb(189,195, 199);")
        self.plot(self.currTimeRange)

        self.timer.timeout.connect(partial(self.plot, self.currTimeRange))
        self.timer.start(self.refreshRateSec * 1000)

        # Did it store data?
        self.dataOk = True
        self.hideButton = QtGui.QPushButton("Show Plot")
        self.hideButton.clicked.connect(self.togglePlot)
        self.oneMinButton = QtGui.QPushButton("1 min")
        self.oneMinButton.clicked.connect(partial(self.plot, 60))
        self.tenMinButton = QtGui.QPushButton("10 min")
        self.tenMinButton.clicked.connect(partial(self.plot, 600))
        self.twoHrButton = QtGui.QPushButton("2 hr")
        self.twoHrButton.clicked.connect(partial(self.plot, 7200))
        self.twelveHrButton = QtGui.QPushButton("12 hr")
        self.twelveHrButton.clicked.connect(partial(self.plot, 43200))
        self.threeDayButton = QtGui.QPushButton("3 day")
        self.threeDayButton.clicked.connect(partial(self.plot, 259200))
        self.oneWkButton = QtGui.QPushButton("1 week")
        self.oneWkButton.clicked.connect(partial(self.plot, 604800))
        self.allButton = QtGui.QPushButton("All Time")
        self.allButton.clicked.connect(partial(self.plot, None))

        self.canvas.hide()
        self.toolbar.hide()

        # Set the layout.
        buttonLayout1 = QtGui.QHBoxLayout()
        buttonLayout1.addWidget(self.hideButton)
        buttonLayout1.addWidget(self.fullGraphBtn)
        buttonLayout1.addStretch(0)
        buttonLayout2 = QtGui.QHBoxLayout()
        settingsbuttons1 = QtGui.QHBoxLayout()

        buttonLayout2.addWidget(self.oneMinButton)
        buttonLayout2.addWidget(self.tenMinButton)
        buttonLayout2.addWidget(self.twoHrButton)
        buttonLayout2.addWidget(self.twelveHrButton)
        buttonLayout2.addWidget(self.threeDayButton)
        buttonLayout2.addWidget(self.oneWkButton)
        buttonLayout2.addWidget(self.allButton)
        buttonLayout2.addStretch(0)
        self.oneMinButton.hide()
        self.tenMinButton.hide()
        self.twoHrButton.hide()
        self.twelveHrButton.hide()
        self.threeDayButton.hide()
        self.oneWkButton.hide()
        self.allButton.hide()
        self.lineSelect.hide()
        self.matframe.hide()
        self.matPlotInfo.hide()
        self.toolbarFrame.hide()

        settingsbuttons1.addWidget(self.lineSelect)
        layout = QtGui.QVBoxLayout()
        allButtonsLayout = QtGui.QHBoxLayout()
        timeButtonsLayout = QtGui.QVBoxLayout()
        allButtonsLayout.addLayout(timeButtonsLayout)
        layout.addLayout(allButtonsLayout)
        allButtonsLayout.addLayout(settingsbuttons1)
        timeButtonsLayout.addLayout(buttonLayout1)
        timeButtonsLayout.addLayout(buttonLayout2)
        timeButtonsLayout.addWidget(self.matPlotInfo)
        layout.addWidget(self.matframe)
        layout.addWidget(self.toolbarFrame)

        self.setLayout(layout)

    def enableAutoScaling(self):
        self.timer.start(self.refreshRateSec * 1000)
        self.home = True
        self.matPlotInfo.hide()
        self.plot(self.currTimeRange)

    def disableAutoScaling(self, event):
        self.home = False
        self.matPlotInfo.show()
        self.canvas.update()
        self.timer.stop()

    def togglePlot(self):
        if not self.hidden:
            self.canvas.hide()
            self.toolbar.hide()
            self.oneMinButton.hide()
            self.tenMinButton.hide()
            self.twoHrButton.hide()
            self.twelveHrButton.hide()
            self.threeDayButton.hide()
            self.oneWkButton.hide()
            self.allButton.hide()
            self.matPlotInfo.hide()
            self.matframe.hide()
            self.lineSelect.hide()
            self.toolbarFrame.hide()
            self.timer.stop()
            self.hideButton.setText("Show Plot")
            self.hidden = True
        elif self.hidden:
            self.canvas.show()
            self.toolbar.show()
            self.oneMinButton.show()
            self.tenMinButton.show()
            self.twoHrButton.show()
            self.twelveHrButton.show()
            self.threeDayButton.show()
            self.oneWkButton.show()
            self.allButton.show()
            self.plot(self.currTimeRange)
            self.matframe.show()
            self.lineSelect.show()
            self.toolbarFrame.show()
            self.timer.start(self.refreshRateSec * 1000)
            self.hideButton.setText("Hide Plot")
            self.enableAutoScaling()
            self.hidden = False

    def initializePlot(self, dataSet):
        if dataSet:
            varNames = dataSet.getVariables()
            varNames = [varNames[1][i][0] for i in range(len(varNames[1]))]
            self.dropdownFont = QtGui.QFont()
            self.dropdownFont.setPointSize(12)
        if dataSet is not None:
            self.initialized = True
            self.line[0].remove()
            self.line = []

            for i in range(len(varNames)):
                self.line.append(self.ax.plot(1, 1, label=varNames[i])[0])
                text = QtCore.QString(varNames[i])
                self.lineSelect.addItem(text)
                self.lineSelect.setFont(self.dropdownFont)
                self.lineSelect.setChecked(i, True)

    def changeIndependenVarRange(self, timeRange):
        if not self.hidden:
            if timeRange != self.currTimeRange:
                self.timer.stop()
                self.timer.timeout.disconnect()
                self.currTimeRange = timeRange
                self.timer.timeout.connect(lambda:
                                           self.plot(self.currTimeRange))
                self.timer.start(self.refreshRateSec * 1000)
            plotRefreshRate = self.device.getFrame().getPlotRefreshRate()
            if self.refreshRateSec != plotRefreshRate:
                self.refreshRateSec = plotRefreshRate
                self.timer.stop()
                self.timer.timeout.disconnect()
                self.currTimeRange = timeRange
                self.timer.timeout.connect(lambda:
                                           self.plot(self.currTimeRange))
                self.timer.start(self.refreshRateSec * 1000)

    def getDataRangeFromDataSet(self, dataSet, time):
        if dataSet:
            data = dataSet.getData()
            i = len(data) - 1
            if time:
                while data[i][0] > (data[-1][0] - time):
                    i -= 1
                    if -1 * i > len(data):
                        return data
                data = data[i:-1]
            return data
        else:
            return None

    def openFullGraphGui(self):
        # print "opening full graph gui."
        dataSet = self.device.getFrame().getDataSet().getData()
        # print dataSet
        times = [dt.datetime.fromtimestamp(elem[0]) for elem in dataSet]
        vars = self.device.getFrame().getDataSet().getVariables()

        self.fullgraphcont = fullGraphContainer(times, vars, dataSet)
        self.fullgraphcont.show()

    def plot(self, time):
        times = None
        self.changeIndependenVarRange(time)
        dataSet = self.device.getFrame().getDataSet()

        if not self.initialized:
            self.initializePlot(dataSet)
            self.legend = self.ax.legend(loc='upper left')
            # This is the ONLY time canvas.draw is called. It should
            # NOT be called anywhere else if the graphing speed is
            # to be fast.
            self.canvas.draw()
        else:
            data = self.getDataRangeFromDataSet(dataSet, time)
            for i in range(len(data[0]) - 1):
                if self.lineSelect.isChecked(i):
                    times = [dt.datetime.fromtimestamp(row[0])
                             for row in data]
                    column = [row[i + 1] for row in data]
                    if not self.line[i].get_visible():
                        self.line[i].set_visible(True)
                    self.line[i].set_data(times, column)
                    self.legend = self.ax.legend(loc='upper left')
                    self.ax.grid(True)
                    self.ax.hold(True)
                else:
                    self.line[i].set_visible(False)
                pass
            self.ax.set_title(self.device.getFrame().getTitle(),
                              color=(189. / 255, 195. / 255, 199. / 255))
            if self.home and times:
                self.ax.set_xlim(times[0], times[-1])
                self.ax.relim(visible_only=True)
                self.ax.autoscale(axis='y')

            frame = self.device.getFrame()
            yLabel = frame.getYLabel()
            if yLabel is not None:
                if frame.getCustomUnits():
                    self.ax.set_ylabel("%s (%s)" % (yLabel,
                                                    frame.getCustomUnits()))
                elif frame.getUnits()[i - 1]:
                    self.ax.set_ylabel("%s (%s)" % (yLabel,
                                                    frame.getUnits()[i - 1]))

            locator = AutoDateLocator()

            self.ax.xaxis.set_major_locator(locator)
            self.ax.xaxis.set_major_formatter(DateFormatter('%m/%d %H:%M:%S'))
            self.figure.autofmt_xdate()
            self.ax.draw_artist(self.figure)
            self.ax.draw_artist(self.ax.patch)
            self.ax.draw_artist(self.ax.yaxis)
            self.ax.draw_artist(self.ax.xaxis)

            for i, line in enumerate(self.line):
                self.ax.draw_artist(line)

            self.ax.set_xlabel("Time")
            self.ax.draw_artist(self.legend)

            self.canvas.update()

            self.canvas.flush_events()
예제 #44
0
class IndicSelectWindow(QDialog):
    def __init__(self, parent=None):
        super(IndicSelectWindow, self).__init__(parent=parent)
        self.resize(1000, 800)

        self.target = None
        self.setAcceptDrops(True)
        self.layout = QHBoxLayout(self)
        self.scrollArea = QScrollArea(self)
        self.scrollArea.setWidgetResizable(True)
        self.scrollAreaWidgetContents = QWidget()
        self.gridLayout = QGridLayout(self.scrollAreaWidgetContents)
        self.scrollArea.setWidget(self.scrollAreaWidgetContents)
        self.layout.addWidget(self.scrollArea)

        for i in range(3):
            for j in range(3):
                self.Frame = QFrame(self)
                self.Frame.setStyleSheet("background-color: white;")
                self.Frame.setFrameStyle(QFrame.Panel | QFrame.Raised)
                self.Frame.setLineWidth(2)
                self.layout = QHBoxLayout(self.Frame)

                self.figure = Figure()  # a figure to plot on
                self.canvas = FigureCanvas(self.figure)
                self.ax = self.figure.add_subplot(111)  # create an axis
                data = [random.random() for i in range(10)]
                self.ax.plot(data, '*-')  # plot data
                self.canvas.draw()  # refresh canvas
                self.canvas.installEventFilter(self)

                self.layout.addWidget(self.canvas)

                Box = QVBoxLayout()

                Box.addWidget(self.Frame)

                self.gridLayout.addLayout(Box, i, j)
                self.gridLayout.setColumnStretch(i % 3, 1)
                self.gridLayout.setRowStretch(j, 1)

    def eventFilter(self, watched, event):
        if event.type() == QEvent.MouseButtonPress:
            self.mousePressEvent(event)
        elif event.type() == QEvent.MouseMove:
            self.mouseMoveEvent(event)
        elif event.type() == QEvent.MouseButtonRelease:
            self.mouseReleaseEvent(event)
        return super().eventFilter(watched, event)

    def get_index(self, pos):
        for i in range(self.gridLayout.count()):
            if self.gridLayout.itemAt(i).geometry().contains(
                    pos) and i != self.target:
                return i

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.target = self.get_index(event.windowPos().toPoint())
        else:
            self.target = None

    def mouseMoveEvent(self, event):
        if event.buttons() & Qt.LeftButton and self.target is not None:
            drag = QDrag(self.gridLayout.itemAt(self.target))
            pix = self.gridLayout.itemAt(self.target).itemAt(0).widget().grab()
            mimedata = QMimeData()
            mimedata.setImageData(pix)
            drag.setMimeData(mimedata)
            drag.setPixmap(pix)
            drag.setHotSpot(event.pos())
            drag.exec_()

    def mouseReleaseEvent(self, event):
        self.target = None

    def dragEnterEvent(self, event):
        if event.mimeData().hasImage():
            event.accept()
        else:
            event.ignore()

    def dropEvent(self, event):
        if not event.source().geometry().contains(event.pos()):
            source = self.get_index(event.pos())
            if source is None:
                return

            i, j = max(self.target, source), min(self.target, source)
            p1, p2 = self.gridLayout.getItemPosition(
                i), self.gridLayout.getItemPosition(j)

            self.gridLayout.addItem(self.gridLayout.takeAt(i), *p2)
            self.gridLayout.addItem(self.gridLayout.takeAt(j), *p1)
예제 #45
0
class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)

        # load the UI
        self.ui = uic.loadUi("interface.ui", self)

        # customize the UI
        self.initUI()

        # init class data
        self.initData()

        # connect slots
        self.connectSlots()

    def initUI(self):
        # generate the plot
        self.fig = Figure(figsize=(300, 300),
                          dpi=72,
                          facecolor=(1, 1, 1),
                          edgecolor=(0, 0, 0))
        self.ax = self.fig.add_subplot(111)
        # generate the canvas to display the plot
        self.canvas = FigureCanvas(self.fig)
        self.ui.centralwidget.layout().addWidget(self.canvas)

    def initData(self):
        self.timer = QtCore.QBasicTimer()
        self.database = {}

    def connectSlots(self):
        QtCore.QObject.connect(self.ui.pushButton, QtCore.SIGNAL('clicked()'),
                               self.startAcquisition)

        QtCore.QObject.connect(self.ui.pushButton_2,
                               QtCore.SIGNAL('clicked()'),
                               self.stopAcquisition)

    def startAcquisition(self):
        if not self.timer.isActive():
            self.timer.start(int(self.ui.spinBox.value()) * 1000, self)
            self.ui.checkBox.setChecked(True)

    def stopAcquisition(self):
        self.timer.stop()
        self.ui.checkBox.setChecked(False)

    def timerEvent(self, event):
        if event.timerId() == self.timer.timerId():
            self.updateStations()

    def updateStations(self):
        self.ui.textBrowser.setText("")
        station = 14019
        self.getStationData(station)
        self.ui.textBrowser.setText(QtCore.QString(
            self.getStatusText(station)))
        self.updatePlot(station)

    def getStationData(self, station):
        data = get_station_data(station)
        if station not in self.database:
            self.database[station] = [data]
        else:
            if self.database[station][-1][0] != data[0]:
                self.database[station].append(data)

    def getStatusText(self, station):
        if station in self.database:
            return "Station %s: last update %s, bikes: %s, free: %s, total: %s." % (
                (station, ) + self.database[station][-1])
        else:
            return ""

    def updatePlot(self, station):
        if station in self.database:
            items = self.database[station]

            t = [item[0] for item in items]

            bikes = [item[1] for item in items]
            free = [item[2] for item in items]
            total = [item[3] for item in items]

            self.ax.plot(t, bikes, 'ro-')
            self.ax.plot(t, free, 'bo-')
            self.ax.plot(t, total, 'go-')

            self.ax.set_ylim(ymin=0)
            self.canvas.draw()

    def writeToDatabase(self):
        station = 14019
        conn = sqlite3.connect("database.sqlite")
        cursor = conn.cursor()
        data = self.database[station]
        for row in data:
            cursor.execute('INSERT INTO velib VALUES (?,?,?,?,?)',
                           (station, ) + row)
        conn.commit()
        conn.close()

    def closeEvent(self, e):
        pass
예제 #46
0
class MatplotDisplay2(gpi.GenericWidgetGroup):
    valueChanged = gpi.Signal()

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

        #self.data = self.get_data2()
        self._data = None
        self.create_main_frame()
        self.on_draw()

    # setters
    def set_val(self, data):
        '''Takes a list of npy arrays.
        '''
        if isinstance(data, list):
            self._data = data
            self.on_draw()
        else:
            return

    # getters
    def get_val(self):
        return self._data

    # support
    def create_main_frame(self):

        self.fig = Figure((5.0, 4.0), dpi=100)
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)
        self.canvas.setFocusPolicy(QtCore.Qt.StrongFocus)
        self.canvas.setFocus()

        self.mpl_toolbar = NavigationToolbar(self.canvas, self)

        self.canvas.mpl_connect('key_press_event', self.on_key_press)

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

    def get_data2(self):
        return np.arange(20).reshape([4, 5]).copy()

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

        if self._data is None:
            return

        self.fig.hold(True)

        # plot each set
        # print "--------------------plot the data"
        for data in self._data:

            # check for x, y data
            if data.shape[-1] == 2:
                self.axes.plot(data[..., 0], data[..., 1], alpha=0.8, lw=2.0)
            else:
                self.axes.plot(data, alpha=0.8, lw=2.0)

        self.canvas.draw()

    def on_key_press(self, event):
        # print 'Matplotlib-> you pressed:' + str(event.key)
        # implement the default mpl key press events described at
        # http://matplotlib.org/users/navigation_toolbar.html#navigation-
        # keyboard-shortcuts
        try:
            from matplotlib.backend_bases import key_press_handler
            key_press_handler(event, self.canvas, self.mpl_toolbar)
        except:
            print("key_press_handler import failed. -old matplotlib version.")
class Window(QtGui.QDialog):
    def __init__(self, tx, ty, trig, parent=None):
        super(Window, self).__init__(parent)

        # a figure instance to plot on
        self.tx = tx
        self.ty = ty
        self.trig = trig
        self.figure = Figure()
        self.canvas = FigureCanvas(self.figure)

        plt.ylim(-1, 1)
        plt.xlim(0, 100)
        print("Please click")
        res = plt.ginput(0)
        plt.close()
        x = []
        y = []
        for i in res:
            x = x + [i[0]]
            y = y + [i[1]]

        x = np.array(x)
        sort_index = np.argsort(x)
        x = x[sort_index]
        y = np.array(y)
        y = y[sort_index]
        f = interp1d(x, y)
        xnew = np.linspace(x[0], x[len(x) - 1], num=100, endpoint=True)
        ax = self.figure.add_subplot(111)

        #coord=self.figure2.ginput(0)

        self.figure = Figure()

        self.xnew = xnew
        self.ynew = f(xnew)
        # refresh canvas
        print("here")
        b, a = signal.butter(2, 1)

        res = signal.filtfilt(b, a, self.ynew)

        # this is the Canvas Widget that displays the `figure`
        # it takes the `figure` instance as a parameter to __init__
        self.canvas = FigureCanvas(self.figure)
        ax = self.figure.add_subplot(111)
        ax.set_xlim(0, 100)
        ax.set_ylim(-1, 1)
        ax.plot(self.xnew, res, '--')

        self.tx[0] = self.xnew.copy()
        self.ty[0] = self.ynew.copy()
        self.button = QtGui.QPushButton('Plot')
        self.button.clicked.connect(self.plot)

        # set the layout
        self.toolbar = NavigationToolbar(self.canvas, self)
        self.frSB = QDoubleSpinBox()
        self.frSB.setMinimum(0.01)
        self.frSB.setSingleStep(0.01)
        self.frSB.setMaximum(1)
        self.frSB.setValue(1)
        self.frSB.valueChanged.connect(self.plot)
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        layout.addWidget(self.frSB)

        self.setLayout(layout)

        self.canvas.draw()
        # this is the Navigation widget
        # it takes the Canvas widget and a parent

        # Just some button connected to `plot` method

    def closeEvent(self, event):
        tempx = self.tx[0]
        self.trig(name="drawnGraph",
                  d=datetime.datetime.now(),
                  dur=(tempx[len(tempx) - 1] - tempx[0]))
        #self.trig(name="drawnGraph", d=datetime.datetime.now())
    def plot(self):
        ''' plot some random stuff '''
        # random data

        b, a = signal.butter(2, self.frSB.value())

        res = signal.filtfilt(b, a, self.ynew)
        ax = self.figure.add_subplot(111)

        self.tx[0] = self.xnew.copy()
        self.ty[0] = res.copy()
        # discards the old graph
        ax.clear()

        # plot data
        ax.set_xlim(0, 100)
        ax.set_ylim(-1, 1)
        ax.plot(self.xnew, res, '--')

        # refresh canvas
        self.canvas.draw()
예제 #48
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()
예제 #49
0
class AceViewer(QMainWindow):
    def __init__(self, parent=None):
        super(AceViewer, self).__init__(parent)

        # Create GUI elements
        self._create_gui()

        # Initial data structures
        self.tables = []

        self.populate_reactions()

    def _create_gui(self):
        # Set title of window
        self.setWindowTitle("ACE Data Viewer")

        # Create widgets
        self.main = QWidget()
        self.setCentralWidget(self.main)

        # Create reaction list view
        self.reactionTree = MyTreeWidget()
        self.reactionTree.setColumnCount(1)
        self.reactionTree.setHeaderLabels(["Nuclides/Reactions"])
        self.reactionTree.setMinimumWidth(200)
        self.reactionTree.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.reactionTree.setContextMenuPolicy(Qt.DefaultContextMenu)

        # Create canvas
        self.fig = Figure(dpi=72, facecolor=(1, 1, 1), edgecolor=(0, 0, 0))
        self.canvas = FigureCanvas(self.fig)

        # Create toolbar
        self.mplToolbar = NavigationToolbar(self.canvas, self.main)

        # Create layout for canvas and toolbar
        drawLayout = QVBoxLayout()
        drawLayout.addWidget(self.canvas)
        drawLayout.addWidget(self.mplToolbar)

        layout = QHBoxLayout()
        layout.addWidget(self.reactionTree)
        layout.addLayout(drawLayout)

        # Set layout
        self.main.setLayout(layout)

        # Create menu bar
        self.menubar = QMenuBar(self)
        self.menuFile = QMenu("&File", self.menubar)
        self.menuHelp = QMenu("&Help", self.menubar)
        self.menubar.addActions([self.menuFile.menuAction()])
        self.setMenuBar(self.menubar)

        # File menu
        self.actionOpen = QAction("&Open Library...", self)
        self.actionOpenPartial = QAction("Open &Partial Library...", self)
        self.actionExit = QAction("E&xit", self)
        self.menuFile.addActions(
            [self.actionOpen, self.actionOpenPartial, self.actionExit])

        # Actions
        self.connect(self.actionOpen, SIGNAL("triggered()"), self.open_library)
        self.connect(self.actionOpenPartial, SIGNAL("triggered()"),
                     self.open_partial_library)
        self.connect(self.actionExit, SIGNAL("triggered()"), self.close)
        self.connect(self.reactionTree, SIGNAL("itemSelectionChanged()"),
                     self.draw_plot)

    def open_library(self):
        """Select and open an ACE file and store data in memory."""

        filename = QFileDialog.getOpenFileName(self, "Load ACE Library", "./",
                                               "ACE Libraries (*)")

        try:
            if filename:
                # Parse ACE library
                lib = ace.Library(filename)
                lib.read()

                # Append tables into self.tables object
                for table in lib.tables.values():
                    self.tables.append(table)
        except:
            pass

        # Sort tables based on name
        self.tables.sort(key=lambda table: table.name)

        # Reset combo box
        self.populate_reactions()

    def open_partial_library(self):
        """Select and open an ACE file and store data in memory."""

        filename = QFileDialog.getOpenFileName(self, "Load ACE Library", "./",
                                               "ACE Libraries (*)")

        table_names, completed = QInputDialog.getText(self, "Nuclides",
                                                      "Enter nuclides:")
        if completed:
            table_names = str(table_names).split()
        else:
            return

        try:
            if filename:
                # Parse ACE library
                lib = ace.Library(filename)
                lib.read(table_names)

                # Append tables into self.tables object
                for table in lib.tables.values():
                    self.tables.append(table)
        except:
            pass

        # Sort tables based on name
        self.tables.sort(key=lambda table: table.name)

        # Reset combo box
        self.populate_reactions()

    def populate_reactions(self):
        self.reactionTree.clear()

        for table in self.tables:
            # Add top-level item
            tableItem = QTreeWidgetItem(self.reactionTree, [table.name])
            tableItem.setData(0, Qt.UserRole, table)

            # Add item for total reaction
            item = QTreeWidgetItem(tableItem, ["(n,total)"])

            for reaction in table:
                # Add sub-item
                try:
                    reactionName = ace.reaction_names[reaction.MT]
                except:
                    reactionName = "MT = {0}".format(reaction.MT)
                item = QTreeWidgetItem(tableItem, [reactionName])
                item.setData(0, Qt.UserRole, reaction)

        self.draw_plot()

    def draw_plot(self):
        # Clears the current figure
        self.fig.clear()

        # Get all selected reactions
        items = self.reactionTree.selectedItems()

        if len(items) > 0:
            # Create instance of Axes on the Figure
            self.axes = self.fig.add_subplot(111)

            for item in items:
                # Get Reaction object stored in QTreeWidgetItem
                reaction = item.data(0, Qt.UserRole).toPyObject()

                # Handle total reaction separately
                if item.text(0) == "(n,total)":
                    # Get NeutronTable object
                    table = item.parent().data(0, Qt.UserRole).toPyObject()

                    # Plot total cross section
                    self.axes.loglog(table.energy, table.sigma_t)
                    continue

                # Make sure that the data stored in QTreeWidgetItem is actually
                # a Reaction instance
                if not isinstance(reaction, ace.Reaction):
                    continue

                # Get reference to NeutronTable containing Reaction
                table = reaction.table

                # Plot reaction cross section
                self.axes.loglog(table.energy[reaction.IE:], reaction.sigma)

            # Customize plot
            self.axes.grid(True)
            self.axes.set_xlabel('Energy (MeV)')
            self.axes.set_ylabel('Cross section (barns)')

            # Display plot on FigureCanvas
            self.canvas.draw()
예제 #50
0
class BluetoothWindow(QMainWindow):
    def __init__(self, in_buf, out_buf, parent=None):

        super(BluetoothWindow, self).__init__(parent)

        self.receive_buffer = in_buf
        self.send_buffer = out_buf

        self.compass = Compass()
        self.ai = Attitude()

        self.hor = QHBoxLayout()
        self.hor.addWidget(self.compass)
        self.hor.addWidget(self.ai)

        self.figure = plt.figure()
        self.canvas = FigureCanvas(self.figure)
        self.lines = []
        self.xdata = range(100)
        self.buffers = [[0 for y in range(100)] for x in range(4)]
        self.prepare_plots()

        self.ver2 = QVBoxLayout()
        self.prepare_updaters()

        self.ver = QVBoxLayout()
        self.ver.addLayout(self.hor, 1)
        self.ver.addWidget(self.canvas, 1)

        self.main_hor = QHBoxLayout()
        self.main_hor.addLayout(self.ver, 3)
        self.main_hor.addLayout(self.ver2, 1)

        w = QWidget()
        w.setLayout(self.main_hor)
        self.setCentralWidget(w)

    def prepare_updaters(self):
        def update_value(key, value):
            pidvalues[key] = float(value)
            data = [1]
            for element in pidvalues:
                if element == "PID_SAMPLE_TIME":
                    continue
                data.append(pidvalues[element])
            self.send_buffer.append(data)
            print key, "updated to", pidvalues[key]

        from collections import OrderedDict

        helper = OrderedDict(sorted(pidvalues.items(), key=lambda t: t[0]))

        for k, v in helper.iteritems():
            label = QLabel(k)
            edit = QLineEdit(str(v))
            button = QPushButton("Update")
            l = QHBoxLayout()
            l.addWidget(label, 2)
            l.addWidget(edit, 5)
            l.addWidget(button, 2)
            self.ver2.addLayout(l)
            button.clicked.connect(lambda clicked, label=label, edit=edit: update_value(label.text(), edit.text()))

    def prepare_plots(self):
        # throttle
        ax = plt.subplot(2, 2, 1)
        ax.set_xlim(0, 100)
        ax.set_ylim(1500, 4000)
        plt.title("Throttle")
        line = Line2D([], [], color='black')
        ax.add_line(line)
        self.lines.append(line)
        line.set_data(self.xdata, self.buffers[0][0:100])
        # pitch
        ax = plt.subplot(2, 2, 2)
        ax.set_xlim(0, 100)
        ax.set_ylim(1500, 4000)
        plt.title("Pitch")
        line = Line2D([], [], color='black')
        ax.add_line(line)
        self.lines.append(line)
        line.set_data(self.xdata, self.buffers[1][0:100])
        # roll
        ax = plt.subplot(2, 2, 3)
        ax.set_xlim(0, 100)
        ax.set_ylim(1500, 4000)
        plt.title("Roll")
        line = Line2D([], [], color='black')
        ax.add_line(line)
        self.lines.append(line)
        line.set_data(self.xdata, self.buffers[2][0:100])
        # yaw
        ax = plt.subplot(2, 2, 4)
        ax.set_xlim(0, 100)
        ax.set_ylim(1500, 4000)
        plt.title("Yaw")
        line = Line2D([], [], color='black')
        ax.add_line(line)
        self.lines.append(line)
        line.set_data(self.xdata, self.buffers[3][0:100])

    def plot(self, throttle, pitch, roll, yaw):
        self.buffers[0].append(throttle)
        self.buffers[0].pop(0)
        self.buffers[1].append(pitch)
        self.buffers[1].pop(0)
        self.buffers[2].append(roll)
        self.buffers[2].pop(0)
        self.buffers[3].append(yaw)
        self.buffers[3].pop(0)

        for i in range(4):
            self.lines[i].set_ydata(self.buffers[i])

        self.canvas.draw()

    def receive_text(self):

        # | 2-5   | Roll    | [-pi, pi]   |
        # | 6-9   | Pitch   | [-pi, pi]   |
        # | 10-13 | Yaw     | [-pi, pi]   |
        # | 14-17 | Height  | [0, 10m]  |
        # | 18-21 | Battery | [0, 100%] |

        new_status = []
        while len(self.receive_buffer) != 0:
            new_status = self.receive_buffer.pop(0)

        roll, pitch, yaw, height, battery = struct.unpack('fffff', ''.join(new_status))

        self.ai.set_pitch(math.degrees(pitch))
        self.ai.set_roll(math.degrees(roll))
        self.compass.set_orientation(math.degrees(yaw))

        # TODO fill in with proper values when they are sent correctly
        self.plot(3000 + 100 * (pitch + roll + yaw), pitch, roll, yaw)

        self.repaint()

    def reset(self):
        self.compass.reset()
        self.ai.reset()
예제 #51
0
class PomoWindow(QtGui.QWidget):
    def __init__(self, pomo):
        """
        Makes necessary variable initializations and calls other init methods.
        """
        super(PomoWindow, self).__init__()
        self.pomo = pomo
        # Enhance readability
        self.getString = self.pomo.getString
        self.initUI()
        if useAudio:
            self.initAudio()
        self.timerActive = False
        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.tick)

    def initUI(self):
        """
        Initializes the UI.
        """
        # Set some general window settings.
        self.setFixedSize(480, 310)
        self.move(250, 250)
        self.setWindowTitle(self.getString("app_name"))
        self.setWindowIcon(QtGui.QIcon('/usr/share/icons/pomodorino.png'))
        self.trayIcon = QtGui.QSystemTrayIcon(
            QtGui.QIcon('/usr/share/icons/pomodorino.png'), self)
        self.trayIcon.setVisible(True)
        self.trayIcon.activated.connect(self.trayClick)

        # Add a minimal context menu for the tray icon.
        #trayMenu = QtGui.QMenu(self)
        #trayMenu.addAction("Quit", self.close)
        #self.trayIcon.setContextMenu(trayMenu)

        # Initialize and display the tabs
        pomoTab = self.initPomoTab()
        tasksTab = self.initTasksTab()
        activityTab = self.initActivityTab()

        tabWidget = QtGui.QTabWidget(self)
        tabWidget.resize(479, 309)

        tabWidget.addTab(pomoTab, self.getString("tab_pomo"))
        tabWidget.addTab(tasksTab, self.getString("tab_tasks"))
        tabWidget.addTab(activityTab, self.getString("tab_activity"))

        self.show()

    def initAudio(self):
        """
        Detects an ALSA audio device and buffers our ringtone.
        """
        # Detect an ALSA audio device
        self.audioDevice = alsaaudio.PCM()

        # Open the ringtone and set some audio settings.
        ring = wave.open("/usr/share/pomodorino/ring.wav", 'rb')
        self.audioDevice.setchannels(ring.getnchannels())
        self.audioDevice.setrate(ring.getframerate())
        self.audioDevice.setformat(alsaaudio.PCM_FORMAT_S16_LE)
        self.audioDevice.setperiodsize(320)

        # Read the audio data of the ringtone.
        self.audioData = list()
        buf = ring.readframes(320)
        while buf:
            self.audioData.append(buf)
            buf = ring.readframes(320)

    def closeEvent(self, event):
        """
        Prevents accidental shutdowns by asking the user.
        """
        if self.timerActive:
            self.stopTimer()

            if self.promptUser("ask_paused"):
                event.accept()
            else:
                event.ignore()
                self.startTimer(0, restart=True)
        else:
            event.accept()

    def setTitle(self, title):
        """
        Sets the window title.
        """
        if title is None:
            title = self.getString("app_name")
        else:
            title += " - " + self.getString("app_name")

        self.window().setWindowTitle(title)

    def startTimer(self, timeSpan, restart=False):
        """
        Starts the timer.
        """
        if restart is False:
            self.timerType = timeSpan
            self.timerCount = timeSpan * 60
        self.timerActive = True
        self.timer.start(1000)

    def stopTimer(self):
        """
        Stops the timer.
        """
        self.timerActive = False
        self.timer.stop()

    def resetTimer(self):
        """
        Resets the timer.
        """
        self.stopTimer()
        self.timerCount = 0

    def finishTimer(self, task):
        """
        Is called once the timer finished.
        """
        self.resetTimer()
        # Define the regular length of a pomodoro. Purely for debugging reasons
        POMO_CONST = 25
        pomos = math.floor(self.timerType / POMO_CONST)
        self.setVisible(True)
        if pomos >= 1 and task != '':
            newTask = self.pomo.pomoData.addPomo(task, pomos)
            if newTask is True:
                self.pomoTaskBar.addItem(task, None)
            self.fillActivityTab()
            self.updateTasksTab()

    def trayClick(self, reason):
        """
        Is called when the user clicks on the tray icon.
        """
        if reason == 2 or reason == 3:
            if self.isVisible():
                self.setVisible(False)
            else:
                self.setVisible(True)

    def promptUser(self, identifier, additional=None):
        """
        Creates predefined confirmation/warning dialogs.
        """
        if identifier == 'ask_paused':
            reply = QtGui.QMessageBox.question(
                self, self.getString("ask_paused_title"),
                self.getString("ask_paused_text"),
                QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
                QtGui.QMessageBox.No)
            if reply == QtGui.QMessageBox.Yes:
                return True
            else:
                return False

        elif identifier == 'warn_notask':
            QtGui.QMessageBox.warning(self,
                                      self.getString("warn_notask_title"),
                                      self.getString("warn_notask_text"))
            return

        elif identifier == 'ask_taskdel' and additional != None:
            askText = self.getString("ask_taskdel_text")
            askText = str.replace(askText, "%taskname%", str(additional))

            reply = QtGui.QMessageBox.question(
                self, self.getString("ask_taskdel_title"), askText,
                QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
                QtGui.QMessageBox.No)

            if reply == QtGui.QMessageBox.Yes:
                return True
            else:
                return False

        raise KeyError

    ##############
    ## Pomo Tab ##
    ##############

    def initPomoTab(self):
        """
        Creates the layout of the pomodoro tab
        """
        pomoTab = QtGui.QWidget()

        # Create a combobox with a lineedit for task selection.
        taskBar = QtGui.QComboBox()
        taskBar.setEditable(True)
        taskBarLine = taskBar.lineEdit()
        taskBarLine.setMaxLength(64)
        taskBarLine.setPlaceholderText(self.getString("input_task"))
        taskBar.setFixedSize(375, 32)
        taskBar.setInsertPolicy(QtGui.QComboBox.InsertAlphabetically)
        taskBar.setStyleSheet('font-size: 11pt;')
        taskBar.addItem("", None)
        self.pomoTaskBar = taskBar

        # Add all the task names.
        tasks = self.pomo.pomoData.tasks
        for taskID, taskName, pomoCount, pomoLast in tasks:
            taskBar.addItem(taskName, None)

        # Create the main button.
        mainBtn = QtGui.QPushButton(self.getString("btn_start"), pomoTab)
        mainBtn.setFixedSize(180, 60)
        mainBtn.setStyleSheet('font-size: 17pt;')

        # Create the 25 min button.
        timeBtn = QtGui.QPushButton(self.getString("lbl_regularpomo"), pomoTab)
        timeBtn.setToolTip(self.getString("ttp_regularpomo"))
        timeBtn.setFixedSize(50, 25)
        timeBtn.setStyleSheet('font-size: 9pt;')

        # Create the 50 min button.
        longTimeBtn = QtGui.QPushButton(self.getString("lbl_longpomo"),
                                        pomoTab)
        longTimeBtn.setToolTip(self.getString("ttp_longpomo"))
        longTimeBtn.setFixedSize(50, 25)
        longTimeBtn.setStyleSheet('font-size: 9pt;')

        # Create the 5 min button.
        pauseBtn = QtGui.QPushButton(self.getString("lbl_shortpause"), pomoTab)
        pauseBtn.setToolTip(self.getString("ttp_shortpause"))
        pauseBtn.setFixedSize(50, 25)
        pauseBtn.setStyleSheet('font-size: 9pt;')

        # Create the 10 min button.
        longPauseBtn = QtGui.QPushButton(self.getString("lbl_longpause"),
                                         pomoTab)
        longPauseBtn.setToolTip(self.getString("ttp_longpause"))
        longPauseBtn.setFixedSize(50, 25)
        longPauseBtn.setStyleSheet('font-size: 9pt;')

        # Select 25 min button as default on startup.
        timeBtn.setDisabled(True)
        self.pomoButtonActive = timeBtn

        # Save button references for later usage.
        self.pomoBtns = dict()
        self.pomoBtns['main'] = mainBtn
        self.pomoBtns['time'] = timeBtn
        self.pomoBtns['longTime'] = longTimeBtn
        self.pomoBtns['pause'] = pauseBtn
        self.pomoBtns['longPause'] = longPauseBtn

        # Connect the buttons to the handler function.
        for name, button in self.pomoBtns.items():
            button.clicked.connect(self.onClicked)

        # Create and set the layout.
        firstRow = QtGui.QHBoxLayout()
        firstRow.addWidget(taskBar)

        secondRow = QtGui.QHBoxLayout()
        secondRow.addStretch()
        secondRow.addWidget(pauseBtn)
        secondRow.addWidget(longPauseBtn)
        secondRow.addStretch()
        secondRow.addWidget(timeBtn)
        secondRow.addWidget(longTimeBtn)
        secondRow.addStretch()

        thirdRow = QtGui.QHBoxLayout()
        thirdRow.addWidget(mainBtn)

        vbox = QtGui.QVBoxLayout()
        vbox.addStretch()
        vbox.addLayout(firstRow)
        vbox.addStretch()
        vbox.addLayout(secondRow)
        vbox.addStretch()
        vbox.addLayout(thirdRow)
        vbox.addStretch()

        pomoTab.setLayout(vbox)

        return pomoTab

    def onClicked(self):
        """
        Main function for catching button clicks in the pomo tab.
        """
        sender = self.sender()
        if sender == self.pomoBtns['main']:
            return self.onClickedPomoMain()

        elif (sender == self.pomoBtns['pause']
              or sender == self.pomoBtns['longPause']
              or sender == self.pomoBtns['time']
              or sender == self.pomoBtns['longTime']):
            return self.onClickedPomoTime()

        raise ValueError()

    def onClickedPomoMain(self):
        """
        Starts/Stops the timer depending on the state of the button.
        """
        sender = self.sender()

        if self.timerActive:
            self.stopTimer()
            # Ask the user whether he wants to reset the running timer.
            if self.promptUser("ask_paused"):
                self.resetPomoTab()
                self.resetTimer()
            else:
                self.startTimer(0, restart=True)
        else:
            newText = self.pomoTaskBar.currentText().strip()
            self.pomoTaskBar.setEditText(newText)

            if newText != "" or self.pomoTaskBar.isEnabled() is False:
                self.pomoTaskBar.setDisabled(True)
                for k, v in self.pomoBtns.items():
                    if k != 'main':
                        v.setDisabled(True)
                timeSpan = int(self.pomoButtonActive.text())
                title = "{0:0>2}:00".format(timeSpan)
                sender.setText(title)
                self.setTitle(title)
                self.startTimer(timeSpan)
            else:
                self.promptUser("warn_notask")

    def onClickedPomoTime(self):
        """
        Toggles the state of the timer buttons in the pomo tab.
        """
        sender = self.sender()

        if self.pomoBtns['main'].text() == 'start':
            self.pomoButtonActive.setDisabled(False)
            sender.setDisabled(True)
            self.pomoButtonActive = sender

            if sender == self.pomoBtns['pause'] or sender == self.pomoBtns[
                    'longPause']:
                self.pomoTaskBar.setDisabled(True)
            else:
                self.pomoTaskBar.setDisabled(False)

    def resetPomoTab(self):
        """
        Resets the button states in the pomo tab.
        """
        if self.pomoButtonActive != self.pomoBtns[
                'pause'] and self.pomoButtonActive != self.pomoBtns[
                    'longPause']:
            self.pomoTaskBar.setDisabled(False)

        self.pomoBtns['main'].setText("start")
        for k, v in self.pomoBtns.items():
            if k != 'main' and v is not self.pomoButtonActive:
                v.setDisabled(False)

        # Also reset the window title.
        self.setTitle(None)

    def tick(self):
        """
        Updates the GUI every second when the timer is running.
        """
        self.timerCount -= 1

        timeStr = "{0:0>2}:{1:0>2}".format(math.floor(self.timerCount / 60),
                                           self.timerCount % 60)
        self.pomoBtns['main'].setText(timeStr)
        # Show current time in the title.
        self.setTitle(timeStr)

        # Timer finished?
        if self.timerCount == 0:
            self.playRingtone()
            self.finishTimer(self.pomoTaskBar.currentText())
            self.resetPomoTab()

    def playRingtone(self):
        """
        Creates a thread for playing the ringtone.
        """
        t = threading.Thread(target=self.playRingThread)
        # Kill the thread once it finishes.
        t.daemon = True
        t.start()

    def playRingThread(self):
        """
        Plays the Ringtone.
        """
        for data in self.audioData:
            self.audioDevice.write(data)

    ###############
    ## tasks tab ##
    ###############

    def initTasksTab(self):
        """
        Creates the layout of the tasks tab.
        """
        tasksTab = QtGui.QWidget()

        self.tasksTable = self.fillTasksTable()
        self.tasksVBox = QtGui.QVBoxLayout()
        self.tasksVBox.addWidget(self.tasksTable)
        self.tasksTable.sortItems(0)

        tasksTab.setLayout(self.tasksVBox)
        return tasksTab

    def fillTasksTable(self):
        """
        Fills the table in the tasks tab.
        """
        tasks = self.pomo.pomoData.tasks
        self.taskTableSelChange = False

        # Create a table with three columns.
        table = QtGui.QTableWidget(len(tasks), 3)
        table.itemSelectionChanged.connect(self.taskListSelectionChanged)
        table.itemClicked.connect(self.taskListClick)
        table.setShowGrid(True)
        table.setSelectionMode(QtGui.QAbstractItemView.SingleSelection)
        table.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
        table.setFocusPolicy(QtCore.Qt.NoFocus)
        table.setHorizontalHeaderLabels([
            self.getString("lbl_stats_task"),
            self.getString("lbl_stats_pomos"),
            self.getString("lbl_stats_last")
        ])
        table.verticalHeader().setVisible(False)
        table.horizontalHeader().setHighlightSections(False)

        # Create a context menu for the table.
        def ctMenuEvent(event):
            self.taskTableSelChange = False
            menu = QtGui.QMenu(table)
            rnAct = menu.addAction("Rename", self.renameTask)
            dlAct = menu.addAction("Delete", self.deleteTask)
            menu.popup(QtGui.QCursor.pos())
            if self.timerActive and self.pomoTaskBar.currentText(
            ) == self.tasksTable.selectedItems()[0].text():
                rnAct.setEnabled(False)
                dlAct.setEnabled(False)

        table.contextMenuEvent = ctMenuEvent

        # Columwidth depends on the existence of a scrollbar.
        if len(tasks) <= 7:
            table.setColumnWidth(0, 345)
        else:
            table.setColumnWidth(0, 329)
        table.setColumnWidth(1, 48)
        table.setColumnWidth(2, 60)

        # There must be a row counter since the taskID can be different.
        rowCount = 0

        # Fill the table rows.
        for taskID, taskName, pomoCount, pomoLast in tasks:
            # First column: taskName
            item = QtGui.QTableWidgetItem()
            item.setText(taskName)
            item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable)
            table.setItem(rowCount, 0, item)

            # Second column: pomoCount
            item = QtGui.QTableWidgetItem()
            item.setText(str(pomoCount))
            item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable)
            item.setToolTip("~" + str(round((pomoCount * 25) / 60, 1)) + "h")
            table.setItem(rowCount, 1, item)

            # Third column: pomoLast
            pomoLastDate = datetime.datetime.fromtimestamp(pomoLast)
            item = QtGui.QTableWidgetItem()
            item.setText(pomoLastDate.strftime("%x"))
            item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable)
            table.setItem(rowCount, 2, item)

            rowCount += 1
        return table

    def updateTasksTab(self):
        """
        Updates the pomodoro statistics in the tasks tab.
        """
        self.tasksVBox.removeWidget(self.tasksTable)
        self.tasksTable.close()
        self.tasksTable = self.fillTasksTable()
        self.tasksVBox.insertWidget(0, self.tasksTable)

    def taskListSelectionChanged(self):
        """
        Sets a flag when the selection in the task table was changed.
        """
        if self.tasksTable.selectedItems() != []:
            self.taskTableSelChange = True

    def taskListClick(self, item):
        """
        Detects when an item in the task table was clicked and clears selection if necessary.
        """
        if self.taskTableSelChange == False:
            self.tasksTable.clearSelection()
        self.taskTableSelChange = False

    def deleteTask(self):
        """
        Deletes a task by the users request.
        """
        taskName = self.tasksTable.selectedItems()[0].text()
        okay = self.promptUser("ask_taskdel", additional=taskName)
        if okay:
            # Delete entry from GUI
            pbID = self.pomoTaskBar.findText(taskName)
            self.pomoTaskBar.removeItem(pbID)

            stID = self.activitySelTask.findText(taskName)
            self.activitySelTask.removeItem(stID)

            rownum = self.tasksTable.row(self.tasksTable.selectedItems()[0])
            self.tasksTable.removeRow(rownum)

            if self.tasksTable.rowCount() <= 7:
                self.tasksTable.setColumnWidth(0, 345)

            # Delete entry from db and cache
            taskID = self.pomo.pomoData.getTaskID(taskName)
            self.pomo.pomoData.delTask(taskID)

            # Reset the activity tab
            self.fillActivityTab()

    def renameTask(self, warn=""):
        """
        Renames a task by the users request.
        """
        oldname = self.tasksTable.selectedItems()[0].text()
        name, okay = QtGui.QInputDialog.getText(
            self, self.getString("lbl_rename_task"), warn, text=oldname)
        if okay and name != '' and name != oldname:
            try:
                self.pomo.pomoData.getTaskID(name)
                self.renameTask(self.getString("lbl_rename_taken"))
            except KeyError:
                # Update entry in GUI
                self.tasksTable.selectedItems()[0].setText(name)

                pbID = self.pomoTaskBar.findText(oldname)
                self.pomoTaskBar.setItemText(pbID, name)

                stID = self.activitySelTask.findText(oldname)
                self.activitySelTask.setItemText(stID, name)

                # Update entry in db and cache
                tID = self.pomo.pomoData.getTaskID(oldname)
                self.pomo.pomoData.renameTask(tID, name)

    ##################
    ## activity tab ##
    ##################

    def initActivityTab(self):
        """
        Creates the layout of the activity tab and prepares the graph.
        """
        activityTab = QtGui.QWidget()

        # Get the background color of the window to make the graph fit in.
        color = self.palette().color(QtGui.QPalette.Background)

        # Create a fixed-size canvas for the graph.
        self.figure = plt.figure(facecolor=color.name(), tight_layout=False)
        self.canvas = FigureCanvas(self.figure)
        self.canvas.setFixedSize(460, 236)

        # Set default values for some attributes used in fillActivityTab
        self.lockYLim = False
        self.intervalShift = 0
        self.intervalScale = 3  # [3] days - [2] weeks - [1] months
        self.activityTaskID = 0

        # Combobox for selecting the active task to be displayed.
        selTask = QtGui.QComboBox()
        selTask.insertItem(0, self.getString("lbl_stats_all"), None)
        for tID, tskName, pomoCount, pomoLast in self.pomo.pomoData.tasks:
            selTask.addItem(tskName, None)

        selTask.currentIndexChanged['QString'].connect(self.onChangeTask)
        # Save handle for later use.
        self.activitySelTask = selTask

        # Navigation buttons to change the active timespan.
        farLeftButton = QtGui.QPushButton("<<", activityTab)
        farLeftButton.setStyleSheet('font-size: 12pt;')
        farLeftButton.setFixedSize(30, 20)
        farLeftButton.clicked.connect(self.timeNavigate)
        # Save the handle for toggling the button state
        self.farLeftButtonHandle = farLeftButton

        farRightButton = QtGui.QPushButton(">>", activityTab)
        farRightButton.setStyleSheet('font-size: 12pt;')
        farRightButton.setFixedSize(30, 20)
        farRightButton.setDisabled(True)
        farRightButton.clicked.connect(self.timeNavigate)
        # Save the handle for toggling the button state.
        self.farRightButtonHandle = farRightButton

        leftButton = QtGui.QPushButton("<", activityTab)
        leftButton.setStyleSheet('font-size: 12pt;')
        leftButton.setFixedSize(30, 20)
        leftButton.clicked.connect(self.timeNavigate)
        # Save the handle for toggling the button state
        self.leftButtonHandle = leftButton

        rightButton = QtGui.QPushButton(">", activityTab)
        rightButton.setStyleSheet('font-size: 12pt;')
        rightButton.setFixedSize(30, 20)
        rightButton.setDisabled(True)
        rightButton.clicked.connect(self.timeNavigate)
        # Save the handle for toggling the button state.
        self.rightButtonHandle = rightButton

        # Disable left navigation buttons when there are no finished pomos.
        if self.pomo.pomoData.firstPomo == 0:
            leftButton.setDisabled(True)
            farLeftButton.setDisabled(True)

        # Zoom buttons to change the active timespan.
        zoomOutButton = QtGui.QPushButton("−", activityTab)
        zoomOutButton.setStyleSheet('font-size: 12pt;')
        zoomOutButton.setFixedSize(30, 20)
        zoomOutButton.clicked.connect(self.timeZoom)
        # Save the handle for toggling the button state.
        self.zoomOutButtonHandle = zoomOutButton

        zoomInButton = QtGui.QPushButton("+", activityTab)
        zoomInButton.setStyleSheet('font-size: 12pt;')
        zoomInButton.setFixedSize(30, 20)
        zoomInButton.setDisabled(True)
        zoomInButton.clicked.connect(self.timeZoom)
        # Save the handle for toggling the button state.
        self.zoomInButtonHandle = zoomInButton

        # Get highest pomo count on a single day.
        self.highestPomoCount = list()

        self.highestPomoCount.append(
            self.pomo.pomoData.getHighestPomoCountMonthly())
        self.highestPomoCount.append(
            self.pomo.pomoData.getHighestPomoCountWeekly())
        self.highestPomoCount.append(
            self.pomo.pomoData.getHighestPomoCountDaily())

        # Draw the graph.
        self.fillActivityTab()

        # Create and set the layout.
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.canvas)
        layout2 = QtGui.QHBoxLayout()
        layout2.addWidget(farLeftButton)
        layout2.addWidget(leftButton)
        layout2.addWidget(rightButton)
        layout2.addWidget(farRightButton)
        layout2.addStretch()
        layout2.addWidget(zoomOutButton)
        layout2.addWidget(zoomInButton)
        layout2.addStretch()
        layout2.addWidget(selTask)
        layout.addLayout(layout2)

        activityTab.setLayout(layout)
        return activityTab

    def fillActivityTab(self):
        """
        Fills and displays the bar graph in the activity tab.
        """
        taskID = self.activityTaskID

        # First get the absolute value of today.
        today = datetime.date.today()
        delta = datetime.timedelta(days=1)

        # Now construct shiftable intervals.
        beginInt = datetime.datetime
        endInt = datetime.datetime

        # Default scale (days): Begin interval at midnight of today.
        beginInt = datetime.datetime(today.year, today.month, today.day, 0, 0,
                                     0)
        shiftDelta = delta

        if self.intervalScale == 2:  # Scale: Weeks
            # Begin interval at midnight of this weeks monday.
            weekDayNum = calendar.weekday(today.year, today.month, today.day)
            beginInt = beginInt - delta * weekDayNum
            shiftDelta = 7 * delta
        elif self.intervalScale == 1:  # Scale: Months
            # Begin interval at midnight of the first day of the month.
            beginInt = datetime.datetime(today.year, today.month, 1, 0, 0, 0)
            shiftDelta = 30 * delta
        self.shiftDelta = shiftDelta

        # Get the data of the last units since today.
        units = list()
        values = list()
        size = 6 + self.intervalScale

        for i in range(size):
            # Shift
            offset = (size - i - 1 - self.intervalShift)
            shiftedBegin = beginInt - offset * shiftDelta
            # When scaled to months, an arithmetical shift is not practical.
            if self.intervalScale == 1:
                yearDiff, monDiff = divmod(offset, 12)
                newMon = beginInt.month - monDiff
                if newMon < 0:
                    newMon = 12 + newMon
                    yearDiff += 1

                if newMon == 0:
                    newMon = 12
                    yearDiff += 1

                shiftedBegin = datetime.datetime(beginInt.year - yearDiff,
                                                 newMon, 1, 0, 0, 0)
            shiftedEnd = datetime.datetime

            if self.intervalScale == 3:
                units.append(
                    str(shiftedBegin.month) + "/" + str(shiftedBegin.day))
                shiftedEnd = datetime.datetime(shiftedBegin.year,
                                               shiftedBegin.month,
                                               shiftedBegin.day, 23, 59, 59)
            elif self.intervalScale == 2:
                units.append(shiftedBegin.strftime("CW %W"))
                shiftedEnd = datetime.datetime(shiftedBegin.year,
                                               shiftedBegin.month,
                                               shiftedBegin.day, 23, 59, 59)
                shiftedEnd = shiftedEnd + delta * 6
            else:
                units.append(shiftedBegin.strftime("%b %y"))
                lastDay = calendar.monthrange(shiftedBegin.year,
                                              shiftedBegin.month)[1]
                shiftedEnd = datetime.datetime(shiftedBegin.year,
                                               shiftedBegin.month, lastDay, 23,
                                               59, 59)
            timeInt = [
                int(shiftedBegin.timestamp()),
                int(shiftedEnd.timestamp())
            ]
            values.append(self.pomo.pomoData.getPomoCount(timeInt, taskID))

        # Disable left buttons once we scrolled far enough
        if self.pomo.pomoData.firstPomo != 0:
            shiftedBegin = beginInt - (size - 1 -
                                       self.intervalShift) * shiftDelta
            self.shiftedBegin = shiftedBegin
            if shiftedBegin.timestamp() <= self.pomo.pomoData.firstPomo:
                self.leftButtonHandle.setDisabled(True)
                self.farLeftButtonHandle.setDisabled(True)
            else:
                self.leftButtonHandle.setDisabled(False)
                self.farLeftButtonHandle.setDisabled(False)

        # Create a new subplot.
        ax = self.figure.add_subplot(111)
        ax.hold(False)

        # Create the bar graphs
        bars = ax.bar(list(range(1, size + 1)),
                      values,
                      width=0.4,
                      align="center",
                      color="#E04B3F")
        for bar in bars:
            height = bar.get_height()
            plt.text(bar.get_x() + bar.get_width() / 2.,
                     height + 0.08,
                     '%d' % int(height),
                     ha='center',
                     va='bottom',
                     weight="medium")
        plt.xticks(list(range(1, size + 1)), units)

        # y-Limit of the graph depends on the maximum bar height.
        yLim = self.highestPomoCount[self.intervalScale - 1] * 1.24

        # To avoid rescaling the graph when changing the task, we lock the
        # y-Limit to the first one generated after startup.
        if self.lockYLim is False:
            if yLim == 0:
                # When no pomodoros have been done, use a constant y-Limit.
                yLim = 15
            else:
                self.lockYLim = True
            self.yLim = yLim
        else:
            # Update the y-Limit when it exceeds the saved one.
            if yLim > self.yLim:
                self.yLim = yLim

        # Set the graph limits.
        ax.set_ylim([0, self.yLim])
        ax.set_xlim([0.5, size + 0.5])

        # Additional plot and graph settings.
        plt.subplots_adjust(left=0, right=0.99, top=1, bottom=0.087)
        ax.get_yaxis().set_visible(False)
        plt.minorticks_off()
        for tick in ax.get_xticklines():
            tick.set_visible(False)

        # Write currently viewed month and year in the upper right corner,
        # when zoomed out, only display the year.
        if self.intervalScale != 1:
            tempDate = beginInt - (size - 1 - self.intervalShift) * shiftDelta
            dateString = tempDate.strftime("%b %Y")
            if self.intervalScale != 3:
                dateString = tempDate.strftime("%Y")

            plt.text(0.99,
                     0.937,
                     dateString,
                     horizontalalignment='right',
                     verticalalignment='center',
                     transform=ax.transAxes,
                     weight="bold")

        # Show.
        self.canvas.draw()

    def timeNavigate(self):
        """
        Handling function for the navigation buttons in the activity tab.
        """
        sender = self.sender()

        if sender.text() == '<':
            self.intervalShift -= 6
            self.rightButtonHandle.setDisabled(False)
            self.farRightButtonHandle.setDisabled(False)
        elif sender.text() == '>':
            self.intervalShift += 6
            self.leftButtonHandle.setDisabled(False)
            self.farLeftButtonHandle.setDisabled(False)
            if self.intervalShift == 0:
                # Once we hit todays date, disable the right button.
                sender.setDisabled(True)
                self.farRightButtonHandle.setDisabled(True)
        elif sender.text() == '<<':
            sender.setDisabled(True)
            self.leftButtonHandle.setDisabled(True)
            self.rightButtonHandle.setDisabled(False)
            self.farRightButtonHandle.setDisabled(False)

            date = self.shiftedBegin
            while date.timestamp() >= self.pomo.pomoData.firstPomo:
                self.intervalShift -= 6
                date -= 6 * self.shiftDelta
        elif sender.text() == '>>':
            self.intervalShift = 0
            sender.setDisabled(True)
            self.rightButtonHandle.setDisabled(True)
            self.leftButtonHandle.setDisabled(False)
            self.farLeftButtonHandle.setDisabled(False)

        self.fillActivityTab()

    def timeZoom(self):
        """
        Handling function for the zoom buttons in the activity tab.
        """
        sender = self.sender()

        # Always reset the navigation while zooming
        self.intervalShift = 0
        self.lockYLim = False

        if self.pomo.pomoData.firstPomo != 0:
            self.leftButtonHandle.setDisabled(False)
            self.farLeftButtonHandle.setDisabled(False)
        self.rightButtonHandle.setDisabled(True)
        self.farRightButtonHandle.setDisabled(True)

        # Zoom Out:
        if sender.text() == '−':
            self.intervalScale -= 1
            if self.intervalScale == 1:
                self.zoomOutButtonHandle.setDisabled(True)
            self.zoomInButtonHandle.setDisabled(False)
        # Zoom In:
        else:
            self.intervalScale += 1
            if self.intervalScale == 3:
                sender.setDisabled(True)
            self.zoomOutButtonHandle.setDisabled(False)

        self.fillActivityTab()

    def onChangeTask(self, string=str()):
        """
        Will be called when the user changes the task in the activity tab.
        """
        try:
            self.activityTaskID = self.pomo.pomoData.getTaskID(string)
        except KeyError:
            self.activityTaskID = 0
        self.fillActivityTab()
class PeriodGraph(QtGui.QDialog):
    def __init__(self, tx, ty, trig, parent=None):
        super(PeriodGraph, self).__init__(parent)
        # a figure instance to plot on
        self.tx = tx
        self.ty = ty
        self.trig = trig
        self.figure = Figure()
        self.canvas = FigureCanvas(self.figure)

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

        self.frSB = QDoubleSpinBox()
        self.frSB.setMinimum(0.1)
        self.frSB.setMaximum(15)
        self.frSB.setSingleStep(.1)
        self.frSB.valueChanged.connect(self.graphPlot)
        self.vbox = QVBoxLayout()
        self.vbox.addWidget(self.canvas)

        self.hbox1 = QHBoxLayout()

        self.label1 = QLabel("Freqency")
        self.hbox1.addWidget(self.label1)
        self.hbox1.addWidget(self.frSB)

        self.label1 = QLabel("Shape of Signal")
        self.shapeTypeCB = QComboBox()
        self.shapeTypeCB.addItem("Sine")
        self.shapeTypeCB.addItem("Saw")
        self.shapeTypeCB.addItem("Square")
        self.shapeTypeCB.currentIndexChanged.connect(self.graphPlot)
        #        self.graphButton=QPushButton("Draw")
        #
        #        self.graphButton.clicked.connect(self.graphPlot)
        #
        self.hbox2 = QHBoxLayout()
        self.hbox2.addWidget(self.label1)
        self.hbox2.addWidget(self.shapeTypeCB)

        self.label2 = QLabel("Time")
        self.timeSB = QSpinBox()
        self.timeSB.setMinimum(5)
        self.timeSB.setMaximum(100)
        self.timeSB.valueChanged.connect(self.graphPlot)

        self.hbox3 = QHBoxLayout()
        self.hbox3.addWidget(self.label2)
        self.hbox3.addWidget(self.timeSB)

        self.magnitude = QDoubleSpinBox()
        self.label3 = QLabel("Magnitude")
        self.magnitude.setMinimum(0.01)
        self.magnitude.setMaximum(1)
        self.magnitude.setSingleStep(0.01)
        self.magnitude.valueChanged.connect(self.graphPlot)

        self.hbox4 = QHBoxLayout()
        self.hbox4.addWidget(self.label3)
        self.hbox4.addWidget(self.magnitude)

        self.vbox.addLayout(self.hbox1)
        self.vbox.addLayout(self.hbox2)
        self.vbox.addLayout(self.hbox3)
        self.vbox.addLayout(self.hbox4)
        #        self.vbox.addWidget(self.graphButton)

        self.setLayout(self.vbox)
        self.graphPlot()

    def graphPlot(self):
        xnew = np.linspace(0,
                           self.timeSB.value(),
                           num=(self.timeSB.value() * 100),
                           endpoint=True)
        ynew = np.sin(xnew * self.frSB.value())
        print(ynew)
        print("here")
        if self.shapeTypeCB.currentIndex() == 0:
            #    xnew = np.linspace(0, self.timeSB.value(), num=(self.timeSB.value()*100), endpoint=True)
            ynew = np.sin(xnew * self.frSB.value())

        elif self.shapeTypeCB.currentIndex() == 2:
            #   xnew = np.linspace(0, self.timeSB.value(), num=(self.timeSB.value()*100), endpoint=True)
            ynew = self.squareWave(self.frSB.value(), xnew)
        elif self.shapeTypeCB.currentIndex() == 1:
            ynew = signal.sawtooth(2 * np.pi * self.frSB.value() * xnew,
                                   width=0.5)

        ynew = ynew * self.magnitude.value()
        self.ax.clear()
        self.ax.set_xlim(0, 100)
        self.ax.set_ylim(-1, 1)
        self.ax.plot(xnew, ynew, '--')
        self.canvas.draw()

        self.tx[0] = xnew.copy()
        self.ty[0] = ynew.copy()

    def squareWave(self, f, t):
        return signal.square(2 * np.pi * f * t)
        #return (4/pi)*(np.sin(2*pi*f*t)+(1/3)*np.sin(6*pi*f*t)+(1/5)*np.sin(10*pi*f*t))
    def closeEvent(self, event):
        tempx = self.tx[0]
        self.trig(name="PeriodGraph",
                  d=datetime.datetime.now(),
                  dur=(tempx[len(tempx) - 1] - tempx[0]))
예제 #53
0
class smileiQt(QtGui.QMainWindow):
    
    def __init__(self):
        super(smileiQt, self).__init__()

        self.field_dims = 0
            
        self.ui=uic.loadUi(os.path.dirname(os.path.realpath(__file__))+'/smileiQt.ui',self)
        
        self.ui.actionQuit.triggered.connect(QtGui.qApp.quit)
        
        self.ui.timeStep.currentIndexChanged.connect(self.on_draw)
        self.ui.field1.currentIndexChanged.connect(self.on_draw)
        self.ui.field2.currentIndexChanged.connect(self.on_draw)
        
        validator=QtGui.QDoubleValidator()
        self.ui.mini.setValidator(validator)
        self.ui.maxi.setValidator(validator)
        
        self.ui.mini.editingFinished.connect(self.on_draw)
        self.ui.maxi.editingFinished.connect(self.on_draw)
        
        self.ui.actionOpen_File.triggered.connect(self.on_file_change)
        self.logBox.stateChanged.connect(self.on_draw)

        self.h5data1 = []
        self.h5data2 = []
        self.filename = "" 
        
        self.fig1 = Figure()
        self.canvas1 = FigureCanvas(self.fig1)
                
	if self.field_dims == 2 :
	       self.canvas1.mpl_connect('motion_notify_event', self.on_movement)
        self.ui.grid1.addWidget(self.canvas1,0,0)

        self.fig2 = Figure()
        self.canvas2 = FigureCanvas(self.fig2)
	if self.field_dims == 2 :
	       self.canvas2.mpl_connect('motion_notify_event', self.on_movement)
        self.ui.grid2.addWidget(self.canvas2,0,0)

        self.load_settings()
        self.update_files()
        self.show()
        self.raise_()

    def load_settings(self):
        settings=QtCore.QSettings("smilePy","");
        settings.beginGroup("Preferences");
        #self.filename=str(settings.value("filename","").toString());
        self.filename=str("Fields.h5");
        #self.filename=str("");
        settings.endGroup();
        self.update_files()

    def save_settings(self):
        settings=QtCore.QSettings("smilePy","");
        settings.beginGroup("Preferences");
        settings.setValue("filename",self.filename);
        settings.endGroup();

    def on_movement(self, event):
        if not (event.inaxes is None) :
            zval1=self.h5data1[int(event.ydata),int(event.xdata)]
            zval2=self.h5data2[int(event.ydata),int(event.xdata)]
            msg = "(%d,%d) %.3f %.3f" % (int(event.xdata), int(event.ydata), zval1, zval2)
            self.statusBar().showMessage(msg)

    def on_file_change(self):
        filename = QtGui.QFileDialog.getOpenFileName(self,"Open File", self.filename, "HDF5 Files (*.h5)")
        if os.path.isfile(filename) :
            self.filename=str(filename)
            self.update_files()
    
    def update_files (self):
        self.ui.timeStep.currentIndexChanged.disconnect(self.on_draw)
        self.ui.field1.currentIndexChanged.disconnect(self.on_draw)
        self.ui.field2.currentIndexChanged.disconnect(self.on_draw)

        if os.path.isfile(self.filename) : 
            self.setWindowTitle("Smilei "+self.filename);
            self.save_settings()
            self.field1.clear()
            self.field2.clear()
            self.timeStep.clear()
            
            fieldlist = []
            #self.h5file=tables.open_file(self.filename, mode = "r")
            if hasattr(self,'h5file'):
                self.h5file.close()
                
            self.h5file=tables.openFile(self.filename, mode = "r")

            first=True
            for time in self.h5file.root:
                self.timeStep.addItem(time._v_name)
                if first:
                    first=False
                    for field in time :
                        if len(field.shape)==2 and np.prod(np.absolute(np.array(field.shape)-1)) > 0 : 
                            self.field1.addItem(str(field._v_name))
                            self.field2.addItem(str(field._v_name))
			    self.field_dims=2
			else :
			    if len(field.shape)==1:
		            	self.field1.addItem(str(field._v_name))
        		    	self.field2.addItem(str(field._v_name))
				self.field_dims=1
	                    else :
        	        	print "rejected", time._v_name
                        
            self.ui.timeStep.currentIndexChanged.connect(self.on_draw)
            self.ui.field1.currentIndexChanged.connect(self.on_draw)
            self.ui.field2.currentIndexChanged.connect(self.on_draw)
            
            self.res_time=self.h5file.root._v_attrs.res_time
            self.sim_length=self.h5file.root._v_attrs.sim_length

            self.on_draw()

    def on_draw(self):
        """display dir
        """        
        
        name1=""
        name2=""
        if not (self.timeStep.currentText().isEmpty()) : 
            if not (self.field1.currentText().isEmpty()) : 
                name1=str("/"+self.timeStep.currentText()+"/"+self.field1.currentText())
                self.h5data1 = self.h5file.getNode(name1)[:].T
             
            if not (self.field2.currentText().isEmpty()) : 
                name2=str("/"+self.timeStep.currentText()+"/"+self.field2.currentText())
                self.h5data2 = self.h5file.getNode(name2)[:].T

        
        if name1 != "" and name2 != "" :
        
            self.fig1.clear()
            self.fig2.clear()
            self.axes1 = self.fig1.add_subplot(111)
            self.axes2 = self.fig2.add_subplot(111)
        
            mini=self.mini.text().toDouble()
            maxi=self.maxi.text().toDouble()
            
	    if self.field_dims == 1 :
                if mini[1] and maxi[1] :
                    self.axes1.set_ylim(mini[0],maxi[0])
                    self.img1 = self.axes1.plot(self.h5data1)
                    self.axes2.set_ylim(mini[0],maxi[0])
                    self.img2 = self.axes2.plot(self.h5data2)   
                else:
                    self.img1 = self.axes1.plot(self.h5data1)    
                    self.img2 = self.axes2.plot(self.h5data2)    


        if self.field_dims == 2 :
            print self.sim_length
            if mini[1] and maxi[1] :
                if self.ui.logBox.isChecked() and mini[0]>0 and maxi[0]>0:
                    self.img1 = self.axes1.imshow(self.h5data1,norm=LogNorm(vmin=mini[0],vmax=maxi[0]),origin='lower')
                    self.img2 = self.axes2.imshow(self.h5data2,norm=LogNorm(vmin=mini[0],vmax=maxi[0]),origin='lower')
                else:
                    self.img1 = self.axes1.imshow(self.h5data1,vmin=mini[0],vmax=maxi[0],origin='lower')
                    self.img2 = self.axes2.imshow(self.h5data2,vmin=mini[0],vmax=maxi[0],origin='lower')
            else :
                self.img1 = self.axes1.imshow(self.h5data1,origin='lower')    
                self.img2 = self.axes2.imshow(self.h5data2,origin='lower')    

            self.fig1.colorbar(self.img1)
            self.fig2.colorbar(self.img2)
	            

        
        title="%.3f" % (self.timeStep.currentText().toInt()[0]/self.res_time)
        self.fig1.suptitle(title)
        self.fig2.suptitle(title)

        self.canvas1.draw()
        self.canvas2.draw()
예제 #54
0
class DecayWindow(QMainWindow):
    def __init__(self, rpi):
        super(DecayWindow, self).__init__()
        self.rpi = rpi
        self.sdecay = SpectralDecay()
        self.couts = None
        self.setGeometry(30, 30, 700, 700)
        self.setWindowTitle("Lifetime Measurement with Red Pitaya")
        # Define a new window for the layout
        self.window = QWidget()
        self.setCentralWidget(self.window)
        # Plot window configuration
        # a figure instance to plot on
        self.figure = Figure()
        self.canvas = FigureCanvas(self.figure)
        self.toolbar = NavigationToolbar(self.canvas, self)
        # pg.setConfigOption('background', 'w')
        # self.graphicsView = pg.PlotWidget(self.window)
        # self.graphicsView.addLegend()
        # Buttons
        # self.lifetime_button = QPushButton("Lifetime")
        # Button events
        # self.lifetime_button.clicked.connect(self.lifetime)
        # Adding labels and linedits
        self.info_label = QLabel('Ready to calibrate.')
        self.wlen_ledit = QLineEdit(self)
        self.freq_ledit = QLineEdit(self)
        self.duty_ledit = QLineEdit(self)
        self.lpower_ledit = QLineEdit(self)
        self.filter_ledit = QLineEdit(self)

        # Using a Grid layout
        grid = QGridLayout()
        grid.setSpacing(5)
        # Line edits
        self.addLinedit(grid, QLabel('Wavelength'), self.wlen_ledit, 0, 0)
        self.addLinedit(grid, QLabel('Frequency'), self.freq_ledit, 1, 0)
        self.addLinedit(grid, QLabel('Duty Cycle'), self.duty_ledit, 2, 0)
        self.addLinedit(grid, QLabel('Laser power'), self.lpower_ledit, 0, 2)
        self.addLinedit(grid, QLabel('Optical filter'), self.filter_ledit, 1,
                        2)
        # Buttons
        # grid.addWidget(self.lifetime_button,3,2,1,1)
        # Graphics
        # grid.addWidget(self.graphicsView, 3, 0, 2, 4)
        grid.addWidget(self.toolbar, 3, 0, 1, 4)
        grid.addWidget(self.canvas, 4, 0, 2, 4)
        grid.addWidget(self.info_label, 6, 0, 1, 1)
        # To avoid resizing of grid cells
        self.window.setLayout(grid)
        # Munu configuration
        self.menuInit()
        self.show()

    def menuInit(self):
        # File saving
        self.savefile = QAction("&Save File", self)
        self.savefile.setShortcut("Ctrl+S")
        self.savefile.setStatusTip('Save File')
        self.savefile.triggered.connect(self.saveFile)
        # Calibration
        self.calibrate = QAction("&Calibrate", self)
        self.calibrate.setStatusTip('Calibrate')
        self.calibrate.triggered.connect(self.calibrateTrigger)
        # Acquisition
        self.acquire = QAction("&Acquire", self)
        self.acquire.setStatusTip('Acquire')
        self.acquire.triggered.connect(self.acquire_channel)
        # Lifetime meassurement
        self.lifetime = QAction("&Lifetime", self)
        self.lifetime.setShortcut("Ctrl+L")
        # self.lifetime.setStatusTip('Lifetime')
        self.lifetime.triggered.connect(self.lifetime_meassure)
        # Configurate
        self.configurate = QAction("&Configurate", self)
        # self.lifetime.setStatusTip('Configurate')
        self.configurate.triggered.connect(self.configurateAcquisition)
        # Adding the menu
        mainMenu = self.menuBar()
        fileMenu = mainMenu.addMenu('&File')
        operationsMenu = mainMenu.addMenu('&Operations')
        fileMenu.addAction(self.savefile)
        operationsMenu.addAction(self.calibrate)
        operationsMenu.addAction(self.acquire)
        operationsMenu.addAction(self.lifetime)
        operationsMenu.addAction(self.configurate)

    def plot_data(self, t, v, **kwargs):
        #        self.graphicsView.clear()
        #        handler = self.graphicsView.plot(t, v)
        ax = self.figure.add_subplot(111)
        ax.clear()
        ax.plot(t, v, **kwargs)
        self.canvas.draw()
        return ax

    def addLinedit(self, grid, label, linedit, row, col):
        grid.addWidget(label, row, col, 1, 1)
        grid.addWidget(linedit, row, col + 1, 1, 1)

    def acquire_channel(self):
        t, v1 = self.rpi.acquire_triggered()
        ax = self.figure.add_subplot(111)
        ax.clear()
        ax.plot(t, v1, 'r')
        self.canvas.draw()

    def calibrateTrigger(self):
        t, v1, status = self.rpi.calibration_run()
        ax = self.plot_data(t, v1, color='r')
        return

    def lifetime_meassure(self):
        for hist, bins, counts, status in self.rpi.acquire_decay():
            ax = self.plot_data(bins[:-1] * 1000,
                                hist,
                                marker='o',
                                linestyle='None',
                                markersize=2)
            self.info_label.setText(status)
            QApplication.processEvents()
        ax.set_xlabel('Time (ms)')
        ax.set_ylabel('Counts (A.U.)')
        self.sdecay.time = bins[:-1] * 1000
        self.sdecay.idata = hist
        self.counts = counts
        return

    def saveFile(self):
        fileDialog = QFileDialog
        try:
            set_wlen = int(self.wlen_ledit.text())
            if set_wlen < 200 or set_wlen > 900:
                self.info_label.setText(
                    'Please, specify a wavelength in the valid range (200 - 900 nm).'
                )
                QApplication.processEvents()
                return
        except:
            self.info_label.setText('Please, enter wavelength in nm.')
            QApplication.processEvents()
            return
        timestamp = '{:%Y%m%d-%H%M%S}'.format(datetime.datetime.now())
        defaultName = '%i-%s.hdf' % (set_wlen, timestamp)
        name = fileDialog.getSaveFileName(self, 'Save File', defaultName)
        filename = name[0]
        frequency = self.freq_ledit.text()
        duty_cycle = self.duty_ledit.text()
        laser_power = self.lpower_ledit.text()
        optical_filter = self.filter_ledit.text()
        if self.sdecay.isEmpty():
            time = self.sdecay.time
            idata = self.sdecay.idata
            data.save_h5f_data(filename, counts, time, idata, set_wlen,
                               laser_power, frequency, duty_cycle,
                               optical_filter)
            self.info_label.setText('File saved as %s.' % filename)
            self.wlen_ledit.clear()
            self.lpower_ledit.clear()
            QApplication.processEvents()
        return

    def configurateAcquisition(self):
        configDialog = Dialog(self.rpi.opts, self.rpi.host, self.rpi.channel)
        configDialog.exec_()
        return

    def clearplot_clk(self):
        self.graphicsView.clear()
        self.l.scene().removeItem(self.l)
        self.graphicsView.plotItem.addLegend()
예제 #55
0
class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        #Button Function Link Setup
        self.updateSettings.clicked.connect(self.getSettings)
        self.antennaCenter.clicked.connect(moveToCenterPos)
        self.motionTest.clicked.connect(panBothServos)
        self.trackerLaunch.clicked.connect(self.setAutotrack)
        self.PointButton.clicked.connect(self.pointToTarget)
        #self.tempOverride.clicked.connect(self.setOverride)
        #        self.cutdownCmd.clicked.connect(self.cutdownEmail)
        #        self.abortCmd.clicked.connect(self.abortEmail)
        #This allows for updating tables as a thread type funciton via refresh
        self.refreshtimer = QtCore.QTimer()
        self.refreshtimer.timeout.connect(self.refresh)
        self.refreshtimer.start(5000)
        #Get Data Timer
        self.datatimer = QtCore.QTimer()
        self.datatimer.timeout.connect(getData)
        self.datatimer.start(5000)
        #Antenna Movement Enable
        self.antennatimer = QtCore.QTimer()
        self.antennatimer.timeout.connect(self.antennaOnline)
        self.antennatimer.start(5000)
        #Manual Control Slider
        self.hSlider.valueChanged.connect(self.valueChange)
        self.vSlider.valueChanged.connect(self.valueChange)

        ##        #Animation Timer
        ##        self.anitimer = QtCore.QTimer()
        ##        self.anitimer.timeout.connect(self.trackerAnimation)
        ##        self.anitimer.start(500)
        ##        #Email Timer
        ##        self.email = QtCore.QTimer()
        ##        self.email.timeout.connect(self.dummy)
        ##        self.email.start(1000)

        self.tl = QtCore.QTimeLine(1000)
        self.tl2 = QtCore.QTimeLine(1000)
        self.tl.setFrameRange(0, 100)
        self.tl2.setFrameRange(0, 100)
        self.a = QtGui.QGraphicsItemAnimation()
        self.b = QtGui.QGraphicsItemAnimation()
        self.c = QtGui.QGraphicsItemAnimation()
        self.d = QtGui.QGraphicsItemAnimation()
        self.e = QtGui.QGraphicsItemAnimation()

        self.scene = QtGui.QGraphicsScene(self)

        self.balloon = QtGui.QGraphicsEllipseItem(-40, -50, 40, 50)
        self.balloon.setBrush(QColor(Qt.white))
        self.payload = QtGui.QGraphicsRectItem(-10, -10, 10, 10)
        self.payload.setBrush(QColor(Qt.darkRed))

        self.payloadString1 = QtGui.QGraphicsRectItem(-10, -5, 10, 10)

        self.antenna = QtGui.QGraphicsEllipseItem(-70, -70, 70, 70)

        self.balLoc = QtGui.QGraphicsTextItem("Balloon Loc")
        self.antLoc = QtGui.QGraphicsTextItem("Antenna Loc")

        self.origin = QtGui.QGraphicsEllipseItem(-2, -2, 2, 2)

        #self.installEventFilter(self)

        #Graphing

        #self.figure = plt.figure()
        self.figure = Figure()
        self.canvas = FigureCanvas(self.figure)

        layout = QtGui.QVBoxLayout()

        layout.addWidget(self.canvas)

        self.widget.setLayout(layout)

##        self.plotAlt.plot(receivedTime,receivedAlt,pen = 'r',title = "Altitude (ft)")
##        self.plotAlt.showGrid(x=True,y = True,alpha = 1)
##
##        self.plotLOS.plot(receivedTime,losLog,pen = 'g',title = "Line-of-Sight (km)")
##        self.plotLOS.showGrid(x=True,y = True,alpha = 1)
##
##        self.plotElevation.plot(receivedTime,elevationLog,pen = 'y',title = "Elevation")
##        self.plotElevation.showGrid(x=True,y = True,alpha = 1)
##
##        self.plotBear.plot(receivedTime,bearingLog,pen = 'b',title = "Bearing")
##        self.plotBear.showGrid(x=True,y = True,alpha = 1)
##

    def valueChange(self):
        global antennaEle, antennaBear
        global panOffset, tiltOffset, centerBear, trackTiltOffset, trackBearOffset
        panOffset = self.hSlider.value()
        trackBearOffset = self.hSlider.value()
        tiltOffset = 0 - self.vSlider.value()
        trackTiltOffset = self.vSlider.value()
        moveToTarget(antennaBear, antennaEle)
        self.refresh()

##    def eventFilter(self,widget,event):         #This sets up a keyboard event listener that allows arrow key controls of the dish after clicking on the animation frame in the second tab.
##        global antennaEle, antennaBear
##        global panOffset, tiltOffset, centerBear, trackTiltOffset, trackBearOffset
##        if(event.type() == QtCore.QEvent.KeyPress):
##            key = event.key()
##            if key == QtCore.Qt.Key_Up:
##                tiltOffset -= moveIncrement
##                trackTiltOffset -= moveIncrement
##                moveToTarget(antennaBear, antennaEle)
##            elif key == QtCore.Qt.Key_Down:
##                tiltOffset += moveIncrement
##                trackTiltOffset += moveIncrement
##                moveToTarget(antennaBear, antennaEle)
##            elif key == QtCore.Qt.Key_Left:
##                centerBear += moveIncrement
##                trackBearOffset += moveIncrement
##                moveToTarget(antennaBear, antennaEle)
##            elif key == QtCore.Qt.Key_Right:
##                centerBear -= moveIncrement
##                trackBearOffset -= moveIncrement
##                moveToTarget(antennaBear, antennaEle)
##            self.refresh()
##            return True
##        return QtGui.QWidget.eventFilter(self,widget,event)

    def pointToTarget(self):
        global groundAlt, groundLat, groungLon
        if (self.pointAlt.text() == ""):
            pointtoAlt = float(self.pointAlt.placeholderText())
        else:
            pointtoAlt = float(ast.literal_eval(self.pointAlt.text()))

        if (self.pointLat.text() == ""):
            pointtoLat = float(self.pointLat.placeholderText())
        else:
            pointtoLat = float(ast.literal_eval(self.pointLat.text()))

        if (self.pointLong.text() == ""):
            pointtoLon = float(self.pointLong.placeholderText())
        else:
            pointtoLon = float(ast.literal_eval(self.pointLong.text()))
        deltaAlt = float(pointtoAlt) - groundAlt
        distanceToTarget = 0.87 * haversine(groundLat, groundLon, pointtoLat,
                                            pointtoLon)
        bearingToTarget = bearing(groundLat, groundLon, pointtoLat, pointtoLon)
        elevationAngle = math.degrees(math.atan2(deltaAlt, distanceToTarget))
        moveToTarget(bearingToTarget, elevationAngle)

    def trackerAnimation(self):
        self.scene.addItem(self.balloon)
        self.scene.addItem(self.antenna)
        self.scene.addItem(self.balLoc)
        self.scene.addItem(self.antLoc)
        self.scene.addItem(self.payload)
        self.scene.addItem(self.origin)

        self.a.setItem(self.balloon)
        self.a.setTimeLine(self.tl)
        self.b.setItem(self.antenna)
        self.b.setTimeLine(self.tl2)
        self.c.setItem(self.balLoc)
        self.c.setTimeLine(self.tl)
        self.d.setItem(self.antLoc)
        self.d.setTimeLine(self.tl2)
        self.e.setItem(self.payload)
        self.e.setTimeLine(self.tl)

        self.trackerAni.setScene(self.scene)
        if useRFD:
            self.a.setPosAt(1, QtCore.QPointF(0, -10))
        else:
            #balloonEle = 500 - (iridiumEle*(500/90.00))
            #pointEle = 500 - (antennaEle*(500/90.00))
            #balloonBear = (iridiumBear-centerBear)*(500/180.00)
            #pointBear = (antennaBear-centerBear)*(500/180.00)
            #print pointEle
            #print pointBear

            self.a.setPosAt(
                1, QtCore.QPointF(float(iridiumBear), -float(iridiumEle)))
            self.b.setPosAt(
                1,
                QtCore.QPointF(
                    float(antennaBear) + 15, -(float(antennaEle) - 10)))
            self.c.setPosAt(
                1, QtCore.QPointF(float(iridiumBear),
                                  -(float(iridiumEle) - 30)))
            self.d.setPosAt(
                1,
                QtCore.QPointF(float(antennaBear), -(float(antennaEle) + 100)))
            self.e.setPosAt(
                1,
                QtCore.QPointF(
                    float(iridiumBear) - 15, -float(iridiumEle) + 12))

            self.balLoc.setPlainText("Balloon\nBear:{:.1f}\nEle:{:.1f}".format(
                iridiumBear, iridiumEle))
            self.antLoc.setPlainText("Antenna\nBear:{:.1f}\nEle:{:.1f}".format(
                antennaBear, antennaEle))
        self.tl.start()
        self.tl2.start()

    def setAutotrack(self):
        global autotrackOnline
        if autotrackOnline:
            autotrackOnline = False
        else:
            autotrackOnline = True
            global receivedTime, receivedLat, receivedLon, receivedAlt, bearingLog, elevationLog, losLog
            receivedTime = np.array([])
            receivedLat = np.array([])
            receivedLon = np.array([])
            receivedAlt = np.array([])
            losLog = np.array([])
            elevationLog = np.array([])
            bearingLog = np.array([])
            self.tabs.setCurrentIndex(1)

    def setOverride(self):
        global manualOverride
        if manualOverride:
            manualOverride = False
        else:
            manualOverride = True

    def updateIncoming(self, row, column, value):
        self.incomingData.setItem(column, row,
                                  QtGui.QTableWidgetItem(str(value)))

    def updateGround(self, row, column, value):
        self.groundData.setItem(column, row,
                                QtGui.QTableWidgetItem(str(value)))

    def refresh(self):
        global recievedTime, losLog, bearingLog, elevationLog
        if (useRFD):
            self.updateIncoming(0, 0, rfdTime)
            self.updateIncoming(0, 1, rfdLat)
            self.updateIncoming(0, 2, rfdLon)
            self.updateIncoming(0, 3, round(rfdAlt, 2))
            self.updateIncoming(0, 4, round(rfdEle, 2))
            self.updateIncoming(0, 5, round(rfdBear, 2))
            self.updateIncoming(0, 6, round(rfdLOS, 2))
            self.updateIncoming(
                0, 7,
                round(
                    float(
                        geomag.declination(dlat=rfdLat, dlon=rfdLon,
                                           h=rfdAlt))), 2)
        else:
            #Incoming Data Table
            self.updateIncoming(0, 0, iridiumTime)
            self.updateIncoming(0, 1, iridiumLat)
            self.updateIncoming(0, 2, iridiumLon)
            self.updateIncoming(0, 3, round(iridiumAlt, 2))
            self.updateIncoming(0, 4, round(iridiumEle, 2))
            self.updateIncoming(0, 5, round(iridiumBear, 2))
            self.updateIncoming(0, 6, round(iridiumLOS, 2))
            self.updateIncoming(
                0, 7,
                round(
                    geomag.declination(dlat=iridiumLat,
                                       dlon=iridiumLon,
                                       h=iridiumAlt), 2))

        #Ground Station Data Table (unlikely to change but what the heck)
        self.updateGround(0, 0, groundLat)
        self.updateGround(0, 1, groundLon)
        self.updateGround(0, 2, groundAlt)
        self.updateGround(0, 3, centerBear)
        #Antenna current "intended" position
        self.updateGround(0, 4, trackBearOffset)
        self.updateGround(0, 5, trackTiltOffset)
        self.updateGround(0, 6, antennaBear)
        self.updateGround(0, 7, antennaEle)
        if settingsUpdated:
            testarray = np.array([
                0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
                18, 19, 20, 21, 22, 23
            ])
            testdata = np.array([
                0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4,
                5, 6, 7
            ])
            if len(receivedAlt) > 0:

                # create an axis
                ALTPLOT = self.figure.add_subplot(221)
                LOSPLOT = self.figure.add_subplot(222)
                ELEPLOT = self.figure.add_subplot(223)
                BEARPLOT = self.figure.add_subplot(224)

                # discards the old graph
                ALTPLOT.hold(False)
                LOSPLOT.hold(False)
                ELEPLOT.hold(False)
                BEARPLOT.hold(False)

                # plot data
                ALTPLOT.plot(receivedTime - receivedTime[0], receivedAlt, 'r-')
                ALTPLOT.set_ylabel('Altitude (ft)')
                LOSPLOT.plot(receivedTime - receivedTime[0], losLog, 'g-')
                LOSPLOT.set_ylabel('Line-of-Sight (km)')
                ELEPLOT.plot(receivedTime - receivedTime[0], elevationLog,
                             'b-')
                ELEPLOT.set_ylabel('Elevation Angle')
                BEARPLOT.plot(receivedTime - receivedTime[0], bearingLog, 'y-')
                BEARPLOT.set_ylabel('Bearing Angle')

                # refresh canvas
                self.canvas.draw()

    def getSettings(self):
        global servoAttached, rfdAttached, arduinoAttached, manualOverride
        global settingsUpdated, useIridium, useRFD, usePrediction, useSim, useHybrid
        global centerBear, getLocal, manualLocal, manualOverride, calibrationGoal
        global groundLat, groundLon, groundAlt
        global servoCOM, rfdCOM, arduinoCOM
        global simDate, simStartAlt
        global s
        global receivedTime, receivedLat, receivedLon, receivedAlt, bearingLog, elevationLog, losLog
        settingsUpdated = True
        useIridium = self.autoIridium.isChecked()
        useRFD = self.autoRFD.isChecked()
        usePrediction = self.autoIridiumPredict.isChecked()
        useSim = self.autoSimulation.isChecked()
        if useSim:
            receivedTime = np.array([])
            receivedLat = np.array([])
            receivedLon = np.array([])
            receivedAlt = np.array([])
            losLog = np.array([])
            elevationLog = np.array([])
            bearingLog = np.array([])
        useHybrid = self.autoHybrid.isChecked()
        servoAttached = self.servoAttached.isChecked()
        rfdAttached = self.rfdAttached.isChecked()
        arduinoAttached = self.arduinoAttached.isChecked()
        #manualOverride = self.manualOverride.isChecked()
        if (self.servoAttached.isChecked()):
            if (self.servoCOM.text() == ""):
                servoCOM = self.servoCOM.placeholderText()
            else:
                servoCOM = self.servoCOM.text()
            s = serial.Serial(str(servoCOM),
                              baudrate=servoBaud,
                              timeout=servoTimeout)
            setServoAccel()
            setServoSpeed()
            s.close()
        if (self.rfdAttached.isChecked()):
            if (self.rfdCOM.text() == ""):
                rfdCOM = self.rfdCOM.placeholderText()
            else:
                rfdCOM = self.rfdCOM.text()
        if (self.arduinoAttached.isChecked()):
            if (self.arduinoCOM.text() == ""):
                arduinoCOM = self.arduinoCOM.placeholderText()
            else:
                arduinoCOM = self.arduinoCOM.text()
        if (self.calibrationGoalVal.text() == ""):
            calibrationGoal = self.calibrationGoalVal.placeholderText()
        else:
            calibrationGoal = int(
                ast.literal_eval(self.calibrationGoalVal.text()))
        #manualOverride = self.manualOverride.isChecked()
        if (self.simDate.text() == ""):
            simDate = self.simDate.placeholderText()
        else:
            simDate = self.simDate.text()
        if (self.simAlt.text() == ""):
            simStartAlt = self.simAlt.placeholderText()
        else:
            simStartAlt = self.simAlt.text()

        if (self.getLocal.isChecked()):
            getLocal = True
            manualLocal = False
            arduinoGround()
        else:
            manualLocal = True
            getLocal = False
            if (self.bearingNorth.isChecked()):
                centerBear = 0
            elif (self.bearingEast.isChecked()):
                centerBear = 90
            elif (self.bearingSouth.isChecked()):
                centerBear = 180
            elif (self.bearingWest.isChecked()):
                centerBear = 270
            else:
                centerBear = 0
                print "Error with manual bearing setup"
            groundLat = self.manualLat.text()
            groundLon = self.manualLon.text()
            groundAlt = self.manualAlt.text()
            if (groundLat == ""):
                groundLat = self.manualLat.placeholderText()
            if (groundLon == ""):
                groundLon = self.manualLon.placeholderText()
            if (groundAlt == ""):
                groundAlt = self.manualAlt.placeholderText()
            groundLat = float(groundLat)
            groundLon = float(groundLon)
            groundAlt = float(groundAlt)

            #Graphing and Data Logging
            if (self.graphSQL.isChecked()):
                receivedTime = np.array([])
                receivedLat = np.array([])
                receivedLon = np.array([])
                receivedAlt = np.array([])
                losLog = np.array([])
                elevationLog = np.array([])
                bearingLog = np.array([])
                retrieveDate = time.strftime("%Y-%m-%d")
                while (getSQLArray(retrieveDate)):
                    pass

    def antennaOnline(self):
        global autotrackOnline
        global useIridium, useRFD, usePrediction, useSim, useHybrid
        global receivedTime, receivedLat, receivedLon, receivedAlt, bearingLog, elevationLog, losLog
        if autotrackOnline:
            #Update a nice and pretty status indicator in green
            self.status.setText("Online")
            palette = QtGui.QPalette()
            brush = QtGui.QBrush(QtGui.QColor(21, 255, 5))
            brush.setStyle(QtCore.Qt.SolidPattern)
            palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText,
                             brush)
            brush = QtGui.QBrush(QtGui.QColor(21, 255, 5))
            brush.setStyle(QtCore.Qt.SolidPattern)
            palette.setBrush(QtGui.QPalette.Inactive,
                             QtGui.QPalette.WindowText, brush)
            brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
            brush.setStyle(QtCore.Qt.SolidPattern)
            palette.setBrush(QtGui.QPalette.Disabled,
                             QtGui.QPalette.WindowText, brush)
            self.status.setPalette(palette)
            #Move Antenna to correct position based on settings
            if manualOverride:
                moveToTarget(antennaBear, antennaEle)
            else:
                if useIridium or useSim:
                    moveToTarget(iridiumBear, iridiumEle)
                if useRFD:
                    moveToTarget(rfdBear, rfdEle)
        else:

            #Graphing Arrays - wipe them
            receivedTime = []
            receivedLat = []
            receivedLon = []
            receivedAlt = []
            losLog = []
            elevationLog = []
            bearingLog = []
            #Update a nice and pretty status indicator in red
            self.status.setText("Offline")
            palette = QtGui.QPalette()
            brush = QtGui.QBrush(QtGui.QColor(243, 0, 0))
            brush.setStyle(QtCore.Qt.SolidPattern)
            palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText,
                             brush)
            brush = QtGui.QBrush(QtGui.QColor(243, 0, 0))
            brush.setStyle(QtCore.Qt.SolidPattern)
            palette.setBrush(QtGui.QPalette.Inactive,
                             QtGui.QPalette.WindowText, brush)
            brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))
            brush.setStyle(QtCore.Qt.SolidPattern)
            palette.setBrush(QtGui.QPalette.Disabled,
                             QtGui.QPalette.WindowText, brush)
            self.status.setPalette(palette)
예제 #56
0
class App(QMainWindow):
    def __init__(self):
        super(App, self).__init__()

        self.window = QWidget(self)
        self.setCentralWidget(self.window)

        self.inputBox = QGroupBox('Input')
        inputLayout = QVBoxLayout()
        self.inputBox.setLayout(inputLayout)

        self.targetBox = QGroupBox('Target')
        targetLAyout = QVBoxLayout()
        self.targetBox.setLayout(targetLAyout)

        self.resultBox = QGroupBox('Result')
        resultLayout = QVBoxLayout()
        self.resultBox.setLayout(resultLayout)

        self.layout = QGridLayout()
        self.layout.addWidget(self.inputBox, 0, 0)
        self.layout.addWidget(self.targetBox, 0, 1)
        self.layout.addWidget(self.resultBox, 0, 2)

        self.window.setLayout(self.layout)

        self.image = None
        self.image2 = None
        self.outputImage = None
        #self.outputImage = None
        self.figure = Figure()
        self.figure2 = Figure()
        self.figure3 = Figure()
        self.canvas = FigureCanvas(self.figure)
        self.canvas2 = FigureCanvas(self.figure2)
        self.canvas3 = FigureCanvas(self.figure3)
        self.qImg = None
        self.qImg2 = None
        self.qImg3 = None
        self.pixmap01 = None
        self.pixmap_image = None
        self.pixmap03 = None

        self.createActions()
        self.createMenu()

        self.setWindowTitle("Histogram")
        self.showMaximized()
        self.show()

    def createActions(self):
        self.open_inputAct = QAction(' &Open Input', self)
        self.open_inputAct.triggered.connect(self.open_Input)
        self.open_targetAct = QAction(' &Open Target', self)
        self.open_targetAct.triggered.connect(self.open_Target)
        self.open_equalizeAct = QAction('&Equalize Histogram', self)
        self.open_equalizeAct.triggered.connect(self.equalize_Histogram)
        self.exitAct = QAction(' &Exit', self)
        self.exitAct.triggered.connect(self.exit)

    def createMenu(self):
        self.mainMenu = self.menuBar()
        self.fileMenu = self.mainMenu.addMenu('File')
        self.fileMenu.addAction(self.open_inputAct)
        self.fileMenu.addAction(self.open_targetAct)
        self.fileMenu.addAction(self.open_equalizeAct)
        self.fileMenu.addAction(self.exitAct)

    def createHistogram(self):
        red = self.image[:, :, 2]
        green = self.image[:, :, 1]
        blue = self.image[:, :, 0]
        width, height = blue.shape

        blueArray = [0] * 256
        redArray = [0] * 256
        greenArray = [0] * 256

        for w in range(0, width):
            for h in range(0, height):
                temp = blue[w][h]
                blueArray[temp] += 1
        for w in range(0, width):
            for h in range(0, height):
                temp = red[w][h]
                redArray[temp] += 1
        for w in range(0, width):
            for h in range(0, height):
                temp = green[w][h]
                greenArray[temp] += 1
        blueplot = self.figure.add_subplot(313)
        redplot = self.figure.add_subplot(311)
        greenplot = self.figure.add_subplot(312)

        blueplot.bar(range(256), blueArray, color='blue')
        redplot.bar(range(256), redArray, color='red')
        greenplot.bar(range(256), greenArray, color='green')
        self.canvas.draw()
        self.inputBox.layout().addWidget(self.canvas)

    def createHistogram2(self):
        red = self.image2[:, :, 2]
        green = self.image2[:, :, 1]
        blue = self.image2[:, :, 0]
        width, height = blue.shape

        blueArray = [0] * 256
        redArray = [0] * 256
        greenArray = [0] * 256

        for w in range(0, width):
            for h in range(0, height):
                temp = blue[w][h]
                blueArray[temp] += 1
        for w in range(0, width):
            for h in range(0, height):
                temp = red[w][h]
                redArray[temp] += 1
        for w in range(0, width):
            for h in range(0, height):
                temp = green[w][h]
                greenArray[temp] += 1
        blueplot = self.figure2.add_subplot(313)
        redplot = self.figure2.add_subplot(311)
        greenplot = self.figure2.add_subplot(312)

        blueplot.bar(range(256), blueArray, color='blue')
        redplot.bar(range(256), redArray, color='red')
        greenplot.bar(range(256), greenArray, color='green')
        self.canvas2.draw()
        self.targetBox.layout().addWidget(self.canvas2)

    def open_Input(self):
        #fileName, _ = QFileDialog.getOpenFileName(self, "Open File",QDir.currentPath())
        fileName, _ = QFileDialog.getOpenFileName(self, 'Open Input', '.')
        if fileName:
            self.image = cv2.imread(fileName)
            height, width, channels = self.image.shape
            bytesPerLine = 3 * width
            if not self.image.data:
                QMessageBox.information(self, "Image Viewer",
                                        "Cannot load %s." % fileName)
                return

        self.qImg = QImage(self.image.data, width, height, bytesPerLine,
                           QImage.Format_RGB888).rgbSwapped()
        #self.pixmap01 = QPixmap.fromImage(self.qImg)

        imageLabel = QLabel('image')
        imageLabel.setPixmap(QPixmap.fromImage(self.qImg))
        imageLabel.setAlignment(Qt.AlignCenter)

        self.inputBox.layout().addWidget(imageLabel)
        self.createHistogram()

    # self.updateActions()

    def open_Target(self):
        fileName, _ = QFileDialog.getOpenFileName(self, 'Open Input', '.')
        if fileName:
            self.image2 = cv2.imread(fileName)
            height, width, channels = self.image2.shape
            bytesPerLine = 3 * width
            if not self.image2.data:
                QMessageBox.information(self, "Image Viewer",
                                        "Cannot load %s." % fileName)
                return

        self.qImg2 = QImage(self.image2.data, width, height, bytesPerLine,
                            QImage.Format_RGB888).rgbSwapped()
        #self.pixmap01 = QPixmap.fromImage(self.qImg)

        imageLabel = QLabel('image')
        imageLabel.setPixmap(QPixmap.fromImage(self.qImg2))
        imageLabel.setAlignment(Qt.AlignCenter)

        self.targetBox.layout().addWidget(imageLabel)
        self.createHistogram2()

    def equalize_Histogram(self):
        #:Input için Cdf hesapla
        red = self.image[:, :, 2]
        width, height = red.shape
        size = width * height

        redArray = np.zeros(256)
        pdfRedArray = np.zeros(256)
        cdfRedArrayInput = np.zeros(256)
        for w in range(0, width):
            for h in range(0, height):
                temp = red[w][h]
                redArray[temp] += 1

        pdfRedArray = redArray / size
        cdfRedArrayInput = np.cumsum(pdfRedArray)
        #Target için Cdf hesapla
        red = self.image2[:, :, 2]
        width, height = red.shape
        size = width * height

        redArray = np.zeros(256)
        pdfRedArray = np.zeros(256)
        cdfRedArrayTarget = np.zeros(256)
        for w in range(0, width):
            for h in range(0, height):
                temp = red[w][h]
                redArray[temp] += 1

        pdfRedArray = redArray / size
        cdfRedArrayTarget = np.cumsum(pdfRedArray)

        LUTArrayRed = np.zeros(256)
        j = 0  #target
        for i in range(0, 256):
            while (cdfRedArrayTarget[j] < cdfRedArrayInput[i]) and (j < 255):
                j = j + 1

            LUTArrayRed[i] = j
#GREEEEEEEENNNNNNN
        green = self.image[:, :, 1]
        width, height = green.shape
        size = width * height

        greenArray = np.zeros(256)
        pdfGreenArray = np.zeros(256)
        cdfGreenArrayInput = np.zeros(256)
        for w in range(0, width):
            for h in range(0, height):
                temp = green[w][h]
                greenArray[temp] += 1

        pdfGreenArray = greenArray / size
        cdfGreenArrayInput = np.cumsum(pdfGreenArray)
        #Target için Cdf hesapla
        green = self.image2[:, :, 1]
        width, height = green.shape
        size = width * height

        greenArray = np.zeros(256)
        pdfGreenArray = np.zeros(256)
        cdfGreenArrayTarget = np.zeros(256)
        for w in range(0, width):
            for h in range(0, height):
                temp = green[w][h]
                greenArray[temp] += 1

        pdfGreenArray = greenArray / size
        cdfGreenArrayTarget = np.cumsum(pdfGreenArray)

        LUTArrayGreen = np.zeros(256)
        j = 0  #target
        for i in range(0, 256):
            while (cdfGreenArrayTarget[j] < cdfGreenArrayInput[i]) and (j <
                                                                        255):
                j = j + 1

            LUTArrayGreen[i] = j


#BLUEEEEEEEEEEE
        blue = self.image[:, :, 0]
        width, height = blue.shape
        size = width * height

        blueArray = np.zeros(256)
        pdfBlueArray = np.zeros(256)
        cdfBlueArrayInput = np.zeros(256)
        for w in range(0, width):
            for h in range(0, height):
                temp = blue[w][h]
                blueArray[temp] += 1

        pdfBlueArray = blueArray / size
        cdfBlueArrayInput = np.cumsum(pdfBlueArray)
        #Target için Cdf hesapla
        blue = self.image2[:, :, 0]
        width, height = blue.shape
        size = width * height

        blueArray = np.zeros(256)
        pdfBlueArray = np.zeros(256)
        cdfBlueArrayTarget = np.zeros(256)
        for w in range(0, width):
            for h in range(0, height):
                temp = blue[w][h]
                blueArray[temp] += 1

        pdfBlueArray = blueArray / size
        cdfBlueArrayTarget = np.cumsum(pdfBlueArray)

        LUTArrayBlue = np.zeros(256)
        j = 0  #target
        for i in range(0, 256):
            while (cdfBlueArrayTarget[j] < cdfBlueArrayInput[i]) and (j < 255):
                j = j + 1

            LUTArrayBlue[i] = j

        outputImage = np.zeros(np.shape(self.image))
        outputImage[:, :, 0] = LUTArrayBlue[self.image[:, :, 0]]
        outputImage[:, :, 1] = LUTArrayGreen[self.image[:, :, 1]]
        outputImage[:, :, 2] = LUTArrayRed[self.image[:, :, 2]]
        #self.pixmap01 = QPixmap.fromImage(self.qImg)

        #    imageLabel.setPixmap(QPixmap.fromImage(self.outputImage))
        red = outputImage[:, :, 2]
        green = outputImage[:, :, 1]
        blue = outputImage[:, :, 0]
        width, height = blue.shape

        blueArray = [0] * 256
        redArray = [0] * 256
        greenArray = [0] * 256

        for w in range(0, width):
            for h in range(0, height):
                temp = mt.floor(blue[w][h])
                blueArray[temp] += 1
        for w in range(0, width):
            for h in range(0, height):
                temp = mt.floor(red[w][h])
                redArray[temp] += 1
        for w in range(0, width):
            for h in range(0, height):
                temp = mt.floor(green[w][h])
                greenArray[temp] += 1

        blueplot = self.figure3.add_subplot(313)
        redplot = self.figure3.add_subplot(311)
        greenplot = self.figure3.add_subplot(312)

        blueplot.bar(range(256), blueArray, color='blue')
        redplot.bar(range(256), redArray, color='red')
        greenplot.bar(range(256), greenArray, color='green')
        self.canvas3.draw()
        self.resultBox.layout().addWidget(self.canvas3)

        #return NotImplementedError

    def exit(self):
        sys.exit()
예제 #57
0
class Main(QMainWindow, Ui_MainWindow):
    fig = Figure()
    plot = fig.add_subplot(111)
     
    def __init__(self, *argv):
        super(Main, self).__init__()
        self.setupUi(self)

        self.TabPot.setTabText(0,"Infinite")
        self.TabPot.setTabText(1,"Finite")
        self.TabPot.setTabText(2,"Harmonic")

        self.TabPot.currentChanged.connect(self.TabChanged)
        
        self.canvas = FigureCanvas(self.fig)
        self.MainGrid.addWidget(self.canvas)
        self.UpdatePlot("Infinite")
        
        self.WidthSpinBoxInfinite.valueChanged.connect(self.UpdateWidthSpinBox)
        self.WidthSliderInfinite.valueChanged.connect(self.UpdateWidthSlider)


    def TabChanged(self, index):
        self.UpdatePlot(self.TabPot.tabText(index))
        print(index)
        
    def UpdatePlot(self, potential):
        self.plot.clear()
        
        if potential == "Infinite":
            a = self.WidthSpinBoxInfinite.value()
            self.x = np.arange(-a/2,a/2, a/100)
            self.plot.fill_between([-a-5,-a/2,-a/2+0.01,a/2+0.01,a/2,a+5], [6,6,0,0,6,6], facecolor='black')
            self.plot.fill_between([-a-5,a+5], [-1]*2, facecolor="black")
            
            for i in range(3):
                self.plot.plot(self.x, 2*i-1 + np.sqrt(2/a)*np.sin(i*2*np.pi/a*self.x), color="black")
                self.plot.plot(self.x,2*i + np.sqrt(2/a)*np.cos((2*i+1)*np.pi/a*self.x), color="black")

            self.plot.set_xlim([-(a+1),a+1])
            self.plot.set_ylim([-0.5,5])
            
        if potential == "Finite":
            """
            a = self.WidthSpinBoxFinite.value()
            m = self.MassSpinBoxFinite.value()
            V = self.DepthSpinBoxFinite.value()
            
            self.x = np.arange(-a/2, a/2, a/100)
            modes = finite.finite(a, V, m)

            self.plot.fill_between([-a-5,-a/2,-a/2+0.01,a/2+0.01,a/2,a+5], [V,V,0,0,V,V], facecolor='black')
            self.plot.fill_between([-a-5,a+5], [-1]*2, facecolor="black")
            
            for i in modes:
                self.plot.plot(self.x,

            self.plot.set_xlim([-(a+6),a+6])
            self.plot.set_ylim([-0.5,1.1*V])
            """
            pass
            
        self.plot.set_xlabel("X-Coordinate")
        self.plot.set_ylabel("Wavefunction")
        self.canvas.draw()

    def UpdateWidthSpinBox(self):
        a = self.WidthSpinBoxInfinite.value()
        self.WidthSliderInfinite.setValue(a)
        self.UpdatePlot("Infinite")
        
    def UpdateWidthSlider(self):
        a = self.WidthSliderInfinite.value()
        self.WidthSpinBoxInfinite.setValue(a)
예제 #58
0
class Plot(QtGui.QWidget):
    def __init__(self,
                 winTitle="plot",
                 parent=None,
                 flags=QtCore.Qt.WindowFlags(0)):
        """Construct a new plot widget.

        Keyword arguments:
        winTitle -- Tab title.
        parent -- Widget parent.
        flags -- QWidget flags
        """
        QtGui.QWidget.__init__(self, parent, flags)
        self.setWindowTitle(winTitle)
        # Create matplotlib canvas
        self.fig = Figure()
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)
        # Get axes
        self.axes = self.fig.add_subplot(111)
        self.axesList = [self.axes]
        self.axes.xaxis.set_ticks_position('bottom')
        self.axes.spines['top'].set_color('none')
        self.axes.yaxis.set_ticks_position('left')
        self.axes.spines['right'].set_color('none')
        # Setup layout
        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(self.canvas)
        self.setLayout(vbox)
        # Active series
        self.series = []
        # Indicators
        self.skip = False
        self.legend = False
        self.legPos = (1.0, 1.0)
        self.legSiz = 14
        self.grid = False

    def plot(self, x, y, name=None):
        """Plot a new line and return it.

        Keyword arguments:
        x -- X values
        y -- Y values
        name -- Serie name (for legend). """
        l = Line(self.axes, x, y, name)
        self.series.append(l)
        # Update window
        self.update()
        return l

    def update(self):
        """Update the plot, redrawing the canvas."""
        if not self.skip:
            self.skip = True
            if self.legend:
                legend(self.legend, self.legPos, self.legSiz)
            self.canvas.draw()
            self.skip = False

    def isGrid(self):
        """Return True if Grid is active, False otherwise."""
        return bool(self.grid)

    def isLegend(self):
        """Return True if Legend is active, False otherwise."""
        return bool(self.legend)

    def setActiveAxes(self, index):
        """Change the current active axes.

        Keyword arguments:
        index -- Index of the new active axes set.
        """
        self.axes = self.axesList[index]
        self.fig.sca(self.axes)
예제 #59
0
class asaplotgui(asaplotbase):
    """
    ASAP plotting class based on matplotlib.
    """

    def __init__(self, rows=1, cols=0, title='', size=None, buffering=False):
	"""
	Create a new instance of the ASAPlot plotting class.

	If rows < 1 then a separate call to set_panels() is required to define
	the panel layout; refer to the doctext for set_panels().
	"""
        v = vars()
        del v['self']

        asaplotbase.__init__(self, **v)
        matplotlib.rcParams["interactive"] = True

        _pylab_helpers.Gcf.destroy(0)
        self.canvas = FigureCanvasQTAgg(self.figure)
        # Simply instantiating this is enough to get a working toolbar.
        self.figmgr = FigureManagerQTAgg(self.canvas, 0)
        self.window = self.figmgr.window
        self._set_window_title('ASAP Plotter - Qt4')
        # Register this plot to matplotlib without activating it
        #_pylab_helpers.Gcf.set_active(self.figmgr)
        _pylab_helpers.Gcf.figs[self.figmgr.num] = self.figmgr

        #############
        ### DO WE HAVE TO DO SOMETHING FOR WINDOW CLOSE CALL?
        #############
        def dest_callback():
            try:
                self.is_dead = True
            except NameError:
                pass

        qt.QtCore.QObject.connect(self.window, qt.QtCore.SIGNAL('destroyed()'),dest_callback)

        self.unmap()
	#self.canvas.show()

    def map(self):
	"""
	Reveal the ASAPlot graphics window and bring it to the top of the
	window stack.
	"""
        if self.is_dead:
            raise RuntimeError( "No plotter to show. Not yet plotted or plotter is closed." )
        self.window.activateWindow()
        #To raise this window to the top of the stacking order
        self.window.raise_()
        self.window.show()

    def quit(self):
	"""
	Destroy the ASAPlot graphics window.
	"""
        self.is_dead = True
        if not self.figmgr:
            return
        try:
            #self.window.close()
            # TODO destroy casabar
            _pylab_helpers.Gcf.destroy(self.figmgr.num)
            del self.window, self.canvas, self.figmgr
            self.window = None
            self.canvas = None
            self.figmgr = None
        except RuntimeError: pass # the window may already be closed by user

    def show(self, hardrefresh=True):
	"""
	Show graphics dependent on the current buffering state.
	"""
        if self.is_dead:
            raise RuntimeError( "No plotter to show (not yet plotted or closed)." )
	if not self.buffering:
            if hardrefresh:
                asaplotbase.show(self)
            self.window.activateWindow()
            self.canvas.draw()
	    #self.canvas.show()
	    self.window.show()

    def terminate(self):
	"""
	Clear the figure.
	"""
        if not self.window:
            asaplog.push( "No plotter window to terminate." )
            asaplog.post( "WARN" )
            return
	self.window.close()

    def unmap(self):
	"""
	Hide the ASAPlot graphics window.
	"""
        if not self.window:
            asaplog.push( "No plotter window to unmap." )
            asaplog.post( "WARN" )
            return
        self.window.hide()

    def _set_window_title(self,title):
        # Set title to main window title bar
        self.window.setWindowTitle(title)
예제 #60
0
class Linecut(QtGui.QDialog):
    def __init__(self, main=None):
        super(Linecut, self).__init__(None)

        self.main = main

        self.fig, self.ax = plt.subplots()
        self.x, self.y = None, None
        self.linetraces = []
        self.marker = None
        self.colors = cycle('bgrcmykw')

        self.ax.xaxis.set_major_formatter(FixedOrderFormatter())
        self.ax.yaxis.set_major_formatter(FixedOrderFormatter())

        self.init_ui()

    def init_ui(self):
        self.setWindowTitle("Linecut")
        # Don't show this window in the taskbar
        self.setWindowFlags(QtCore.Qt.Tool)

        self.canvas = FigureCanvasQTAgg(self.fig)
        self.canvas.mpl_connect('pick_event', self.on_pick)
        self.canvas.mpl_connect('button_press_event', self.on_press)
        self.toolbar = NavigationToolbar2QT(self.canvas, self)

        hbox_export = QtGui.QHBoxLayout()

        self.cb_reset_cmap = QtGui.QCheckBox('Reset on plot')
        self.cb_reset_cmap.setCheckState(QtCore.Qt.Checked)
        hbox_export.addWidget(self.cb_reset_cmap)

        self.b_save = QtGui.QPushButton('Copy data', self)
        self.b_save.clicked.connect(self.on_data_to_clipboard)
        hbox_export.addWidget(self.b_save)

        self.b_copy = QtGui.QPushButton('Copy figure', self)
        self.b_copy.clicked.connect(self.on_figure_to_clipboard)
        QtGui.QShortcut(QtGui.QKeySequence("Ctrl+C"), self,
                        self.on_figure_to_clipboard)
        hbox_export.addWidget(self.b_copy)

        self.b_to_ppt = QtGui.QPushButton('To PPT (Win)', self)
        self.b_to_ppt.clicked.connect(self.on_to_ppt)
        hbox_export.addWidget(self.b_to_ppt)

        self.b_save_dat = QtGui.QPushButton('Save data...', self)
        self.b_save_dat.clicked.connect(self.on_save)
        hbox_export.addWidget(self.b_save_dat)

        self.b_toggle_info = QtGui.QPushButton('Toggle info')
        self.b_toggle_info.clicked.connect(self.on_toggle_datapoint_info)
        hbox_export.addWidget(self.b_toggle_info)

        # Linecuts
        hbox_linecuts = QtGui.QHBoxLayout()

        hbox_linecuts.addWidget(QtGui.QLabel('Linecuts'))

        self.cb_incremental = QtGui.QCheckBox('Incremental')
        self.cb_incremental.setCheckState(QtCore.Qt.Unchecked)
        hbox_linecuts.addWidget(self.cb_incremental)

        hbox_linecuts.addWidget(QtGui.QLabel('Offset:'))

        self.le_offset = QtGui.QLineEdit('0', self)
        hbox_linecuts.addWidget(self.le_offset)

        self.b_clear_lines = QtGui.QPushButton('Clear', self)
        self.b_clear_lines.clicked.connect(self.on_clear_lines)
        hbox_linecuts.addWidget(self.b_clear_lines)

        # Lines
        hbox_style = QtGui.QHBoxLayout()

        hbox_style.addWidget(QtGui.QLabel('Line style'))
        self.cb_linestyle = QtGui.QComboBox(self)
        self.cb_linestyle.addItems(['None', 'solid', 'dashed', 'dotted'])
        hbox_style.addWidget(self.cb_linestyle)

        hbox_style.addWidget(QtGui.QLabel('Linewidth'))
        self.le_linewidth = QtGui.QLineEdit('0.5', self)
        hbox_style.addWidget(self.le_linewidth)

        # Markers
        hbox_style.addWidget(QtGui.QLabel('Marker style'))
        self.cb_markerstyle = QtGui.QComboBox(self)
        self.cb_markerstyle.addItems(['None', '.', 'o', 'x'])
        hbox_style.addWidget(self.cb_markerstyle)

        hbox_style.addWidget(QtGui.QLabel('Size'))
        self.le_markersize = QtGui.QLineEdit('0.5', self)
        hbox_style.addWidget(self.le_markersize)

        self.cb_include_z = QtGui.QCheckBox('Include Z')
        self.cb_include_z.setCheckState(QtCore.Qt.Checked)
        hbox_style.addWidget(self.cb_include_z)

        self.row_tree = QtGui.QTreeWidget(self)
        self.row_tree.setHeaderLabels(['Parameter', 'Value'])
        self.row_tree.setColumnWidth(0, 100)
        self.row_tree.setHidden(True)

        hbox_plot = QtGui.QHBoxLayout()
        hbox_plot.addWidget(self.canvas)
        hbox_plot.addWidget(self.row_tree)

        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.toolbar)
        layout.addLayout(hbox_plot)
        layout.addLayout(hbox_export)
        layout.addLayout(hbox_linecuts)
        layout.addLayout(hbox_style)
        self.setLayout(layout)

        self.resize(700, 500)
        self.move(630, 100)

        # This flag is used to reposition the window next to the main window
        # when drawing the first linecut
        self.first_linecut = True
        self.hide()

    def populate_ui(self):
        profile = self.main.profile_settings

        idx = self.cb_linestyle.findText(profile['line_style'])
        self.cb_linestyle.setCurrentIndex(idx)
        self.le_linewidth.setText(profile['line_width'])

        idx = self.cb_markerstyle.findText(profile['marker_style'])
        self.cb_markerstyle.setCurrentIndex(idx)
        self.le_markersize.setText(profile['marker_size'])

    def get_line_kwargs(self):
        return {
            'linestyle': str(self.cb_linestyle.currentText()),
            'linewidth': float(self.le_linewidth.text()),
            'marker': str(self.cb_markerstyle.currentText()),
            'markersize': float(self.le_markersize.text()),
        }

    def on_reset(self):
        if self.x is not None and self.y is not None:
            minx, maxx = np.min(self.x), np.max(self.x)
            miny, maxy = np.min(self.y), np.max(self.y)

            xdiff = (maxx - minx) * .1
            ydiff = (maxy - miny) * .1

            self.ax.axis(
                [minx - xdiff, maxx + xdiff, miny - ydiff, maxy + ydiff])

            self.canvas.draw()

    def on_pick(self, event):
        if event.mouseevent.button == 1:
            line = self.linetraces[0]

            ind = event.ind[int(len(event.ind) / 2)]
            x = line.get_xdata()[ind]
            y = line.get_ydata()[ind]

            row = int(line.row_numbers[ind])
            data = self.main.dat_file.get_row_info(row)

            # Also show the datapoint index
            data['N'] = ind

            # Fill the treeview with data
            self.row_tree.clear()
            widgets = []
            for name, value in data.items():
                if name == 'N':
                    val = str(value)
                else:
                    val = eng_format(value, 1)

                widgets.append(QtGui.QTreeWidgetItem(None, [name, val]))

            self.row_tree.insertTopLevelItems(0, widgets)

            # Remove the previous datapoint marker
            if self.marker is not None:
                self.marker.remove()
                self.marker = None

            # Plot a new datapoint marker
            self.marker = self.ax.plot(x, y, '.', markersize=15,
                                       color='black')[0]

        self.fig.canvas.draw()

    def on_press(self, event):
        if event.button == 3:
            self.row_tree.clear()

            if self.marker is not None:
                self.marker.remove()
                self.marker = None

            self.fig.canvas.draw()

    def on_toggle_datapoint_info(self):
        self.row_tree.setHidden(not self.row_tree.isHidden())

    def on_data_to_clipboard(self):
        if self.x is None or self.y is None:
            return

        data = pd.DataFrame(np.column_stack((self.x, self.y)),
                            columns=[self.xlabel, self.ylabel])

        data.to_clipboard(index=False)

    def on_figure_to_clipboard(self):
        path = os.path.dirname(os.path.realpath(__file__))
        path = os.path.join(path, 'test.png')
        self.fig.savefig(path, bbox_inches='tight')

        img = QtGui.QImage(path)
        QtGui.QApplication.clipboard().setImage(img)

    def on_to_ppt(self):
        """ Some win32 COM magic to interact with powerpoint """
        try:
            import win32com.client
        except ImportError:
            print('ERROR: The win32com library needs to be installed')
            return

        # First, copy to the clipboard
        self.on_figure_to_clipboard()

        # Connect to an open PowerPoint application
        app = win32com.client.Dispatch('PowerPoint.Application')

        # Get the current slide and paste the plot
        slide = app.ActiveWindow.View.Slide
        shape = slide.Shapes.Paste()

        # Add a hyperlink to the data location to easily open the data again
        shape.ActionSettings[0].Hyperlink.Address = self.main.abs_filename

    def on_save(self):
        if self.x is None or self.y is None:
            return

        path = os.path.dirname(os.path.realpath(__file__))
        filename = QtGui.QFileDialog.getSaveFileName(self, 'Save file', path,
                                                     '.dat')

        if filename != '':
            data = pd.DataFrame(np.column_stack((self.x, self.y)),
                                columns=[self.xlabel, self.ylabel])

            data.to_csv(filename, sep='\t', index=False)

    def on_clear_lines(self):
        for line in self.linetraces:
            line.remove()

        self.linetraces = []

        self.fig.canvas.draw()

    def plot_linetrace(self, x, y, z, row_numbers, type, position, title,
                       xlabel, ylabel, otherlabel):
        # Don't draw lines consisting of one point
        if np.count_nonzero(~np.isnan(y)) < 2:
            return

        self.xlabel, self.ylabel, self.otherlabel = xlabel, ylabel, otherlabel
        self.title = title
        self.x, self.y, self.z = x, y, z

        if self.cb_include_z.checkState() == QtCore.Qt.Checked:
            title = '{0}\n{1} = {2}'.format(title, otherlabel,
                                            eng_format(z, 1))

        title = '\n'.join(textwrap.wrap(title, 40, replace_whitespace=False))
        self.ax.set_title(title)

        self.ax.set_xlabel(xlabel)
        self.ax.set_ylabel(ylabel)

        # Remove all the existing lines and only plot one if we uncheck
        # the incremental box. Else, add a new line to the collection
        if self.cb_incremental.checkState() == QtCore.Qt.Unchecked:
            for line in self.linetraces:
                line.remove()

            self.linetraces = []

            line = Linetrace(x,
                             y,
                             row_numbers,
                             type,
                             position,
                             color='red',
                             picker=5,
                             **self.get_line_kwargs())

            self.linetraces.append(line)
            self.ax.add_line(line)

            self.total_offset = 0
        else:
            if len(self.ax.lines) > 0:
                if self.linetraces[-1].position == position:
                    return

            index = len(self.linetraces) - 1

            offset = float(self.le_offset.text())
            line = Linetrace(x, y + index * offset, row_numbers, type,
                             position)
            line.set_color(next(self.colors))

            self.linetraces.append(line)
            self.ax.add_line(line)

        if self.cb_reset_cmap.checkState() == QtCore.Qt.Checked:
            x, y = np.ma.masked_invalid(x), np.ma.masked_invalid(y)
            minx, maxx = np.min(x), np.max(x)
            miny, maxy = np.min(y), np.max(y)

            xdiff = (maxx - minx) * .05
            ydiff = (maxy - miny) * .05

            self.ax.axis(
                [minx - xdiff, maxx + xdiff, miny - ydiff, maxy + ydiff])

        self.ax.set_aspect('auto')
        self.fig.tight_layout()

        self.fig.canvas.draw()

        if self.isHidden():
            self.show_window()

    def resizeEvent(self, event):
        self.fig.tight_layout()
        self.canvas.draw()

    def show_window(self):
        if self.first_linecut:
            self.move(630, 100)

        self.show()
        self.raise_()

    def closeEvent(self, event):
        self.hide()
        event.ignore()