Esempio n. 1
0
    def __init__(self, parent, id=-1, pos=(-1, -1), size=(-1, -1), style=0):
        wx.Panel.__init__(self, parent, id, pos, size, style=style)

        self.fig = Figure((5, 4), 75)
        self.canvas = FigureCanvasWx(self, -1, self.fig)
        self.toolbar = Toolbar(self.canvas)
        self.toolbar.Realize()

        # On Windows, default frame size behaviour is incorrect
        # you don't need this under Linux
        tw, th = self.toolbar.GetSizeTuple()
        fw, fh = self.canvas.GetSizeTuple()
        self.toolbar.SetSize(wx.Size(fw, th))

        # Create a figure manager to manage things
        self.figmgr = FigureManager(self.canvas, 1, self)
        # Now put all into a sizer
        sizer = wx.BoxSizer(wx.VERTICAL)
        # This way of adding to sizer allows resizing
        sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        # Best to allow the toolbar to resize!
        sizer.Add(self.toolbar, 0, wx.GROW)
        self.SetSizer(sizer)
        self.Fit()

        # --- Инициализация графика
        self.init_graph()
Esempio n. 2
0
    def __init__(self):
        wxFrame.__init__(self, None, -1, "Test embedded wxFigure")

        self.fig = Figure((5, 4), 75)
        self.canvas = FigureCanvasWx(self, -1, self.fig)
        self.toolbar = NavigationToolbar2Wx(self.canvas)
        self.toolbar.Realize()

        # On Windows, default frame size behaviour is incorrect
        # you don't need this under Linux
        tw, th = self.toolbar.GetSizeTuple()
        fw, fh = self.canvas.GetSizeTuple()
        self.toolbar.SetSize(wxSize(fw, th))

        # Create a figure manager to manage things
        self.figmgr = FigureManager(self.canvas, 1, self)
        # Now put all into a sizer
        sizer = wxBoxSizer(wxVERTICAL)
        # This way of adding to sizer allows resizing
        sizer.Add(self.canvas, 1, wxLEFT | wxTOP | wxGROW)
        # Best to allow the toolbar to resize!
        sizer.Add(self.toolbar, 0, wxGROW)
        self.SetSizer(sizer)
        self.Fit()
        EVT_TIMER(self, TIMER_ID, self.onTimer)
    def __init__(self, *args, **kwds):

        wx.Frame.__init__(self, None, -1, "Test ReSo - Calibration graphs")

        #        self.fig = Figure((9,8), 75)
        self.fig = Figure()
        self.canvas = FigureCanvasWx(self, -1, self.fig)
        self.toolbar = Toolbar(self.canvas)
        self.toolbar.Realize()

        # On Windows, default frame size behaviour is incorrect
        # you don't need this under Linux
        tw, th = self.toolbar.GetSizeTuple()
        fw, fh = self.canvas.GetSizeTuple()
        self.toolbar.SetSize(wx.Size(fw, th))

        # Create a figure manager to manage things
        self.figmgr = FigureManager(self.canvas, 1, self)
        # Now put all into a sizer
        sizer = wx.BoxSizer(wx.VERTICAL)
        # This way of adding to sizer allows resizing
        sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        # Best to allow the toolbar to resize!
        sizer.Add(self.toolbar, 0, wx.GROW)
        self.SetSizer(sizer)
        self.Fit()
Esempio n. 4
0
 def draw_all(self, drawDC=None):
     ''' 
     draw everything from scratch 
     mostly debugging purpose
     '''
     print('draw_all')
     self.figure.figobj.reset_axesbmp_update()
     Canvas.draw(self)
Esempio n. 5
0
 def draw_all(self, drawDC=None):
     ''' 
     draw everything from scratch 
     mostly debugging purpose
     '''
     print('draw_all')
     self.figure.figobj.reset_axesbmp_update()
     Canvas.draw(self)
Esempio n. 6
0
    def __init__(self,
                 parent,
                 id=-1,
                 pos=(-1, -1),
                 size=(-1, -1),
                 style=0,
                 bWxAgg=False):
        wx.Panel.__init__(self, parent, id, pos, size, style=style)

        self.fig = Figure((5, 4), 75)

        if bWxAgg:
            self.canvas = FigureCanvasWxAgg(self, -1, self.fig)
        else:
            self.canvas = FigureCanvasWx(self, -1, self.fig)

        self.canvas.mpl_connect('motion_notify_event', self.OnMouseMove)
        self.canvas.mpl_connect('button_press_event', self.OnMouseLeftDown)

        self.toolbar = icPloterToolbar(self.canvas)
        self.toolbar.Realize()
        self.parent = parent
        self.legendLst = []

        # --- Атрибуты курсора
        #   Положение курсора
        self._cursor = None
        #   Значение курсора
        self._cursorVal = None
        #   Статический курсор - значение обновляется только при нажантии
        #   левой кнопки мыши
        self._statCursor = None

        # On Windows, default frame size behaviour is incorrect
        # you don't need this under Linux
        tw, th = self.toolbar.GetSizeTuple()
        fw, fh = self.canvas.GetSizeTuple()
        self.toolbar.SetSize(wx.Size(fw, th))

        # Create a figure manager to manage things
        self.figmgr = FigureManager(self.canvas, 1, self)
        # Now put all into a sizer
        sizer = wx.BoxSizer(wx.VERTICAL)
        # This way of adding to sizer allows resizing
        sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        # Best to allow the toolbar to resize!
        sizer.Add(self.toolbar, 0, wx.GROW)
        self.SetSizer(sizer)
        self.Fit()

        # --- Описание обработчиков
        self.Bind(wx.EVT_PAINT, self.OnPaint)

        # --- Инициализация графика
        self.init_graph()
Esempio n. 7
0
class CanvasFrame(Frame):

    def __init__(self):
        Frame.__init__(self, None, -1,
                         'CanvasFrame', size=(550, 350))

        self.SetBackgroundColour(NamedColor("WHITE"))

        self.figure = Figure(figsize=(5, 4), dpi=100)
        self.axes = self.figure.add_subplot(111)
        t = arange(0.0, 3.0, 0.01)
        s = sin(2 * pi * t)

        self.axes.plot(t, s)

        self.canvas = FigureCanvas(self, -1, self.figure)

        self.sizer = BoxSizer(VERTICAL)
        self.sizer.Add(self.canvas, 1, TOP | LEFT | EXPAND)
        # Capture the paint message
        EVT_PAINT(self, self.OnPaint)

        self.toolbar = MyNavigationToolbar(self.canvas, True)
        self.toolbar.Realize()
        if Platform == '__WXMAC__':
            # Mac platform (OSX 10.3, MacPython) does not seem to cope with
            # having a toolbar in a sizer. This work-around gets the buttons
            # back, but at the expense of having the toolbar at the top
            self.SetToolBar(self.toolbar)
        else:
            # On Windows platform, default window size is incorrect, so set
            # toolbar width to figure width.
            tw, th = self.toolbar.GetSizeTuple()
            fw, fh = self.canvas.GetSizeTuple()
            # By adding toolbar in sizer, we are able to put it at the bottom
            # of the frame - so appearance is closer to GTK version.
            # As noted above, doesn't work for Mac.
            self.toolbar.SetSize(Size(fw, th))
            self.sizer.Add(self.toolbar, 0, LEFT | EXPAND)

        # update the axes menu on the toolbar
        self.toolbar.update()
        self.SetSizer(self.sizer)
        self.Fit()


    def OnPaint(self, event):
        self.canvas.draw()
        event.Skip()
Esempio n. 8
0
class PlotFigure(wxFrame):

    def __init__(self):
        wxFrame.__init__(self, None, -1, "Test embedded wxFigure")

        self.fig = Figure((5,4), 75)
        self.canvas = FigureCanvasWx(self, -1, self.fig)
        self.toolbar = NavigationToolbar2Wx(self.canvas)
        self.toolbar.Realize()

        # On Windows, default frame size behaviour is incorrect
        # you don't need this under Linux
        tw, th = self.toolbar.GetSizeTuple()
        fw, fh = self.canvas.GetSizeTuple()
        self.toolbar.SetSize(wxSize(fw, th))

        # Create a figure manager to manage things
        self.figmgr = FigureManager(self.canvas, 1, self)
        # Now put all into a sizer
        sizer = wxBoxSizer(wxVERTICAL)
        # This way of adding to sizer allows resizing
        sizer.Add(self.canvas, 1, wxLEFT|wxTOP|wxGROW)
        # Best to allow the toolbar to resize!
        sizer.Add(self.toolbar, 0, wxGROW)
        self.SetSizer(sizer)
        self.Fit()
        EVT_TIMER(self, TIMER_ID, self.onTimer)
        
    def init_plot_data(self):
        a = self.figmgr.add_subplot(111)
        self.ind = numpy.arange(60)
        tmp = []
        for i in range(60):
            tmp.append(numpy.sin((self.ind+i)*numpy.pi/15))
        self.X = numpy.array(tmp)
        self.lines = a.plot(self.X[:,0],'o')
        self.count = 0

    def GetToolBar(self):
        # You will need to override GetToolBar if you are using an 
        # unmanaged toolbar in your frame
        return self.toolbar
		
    def onTimer(self, evt):
        self.count += 1
        if self.count >= 60: self.count = 0
        self.lines[0].set_data(self.ind, self.X[:,self.count])
        self.canvas.draw()
        self.canvas.gui_repaint()
Esempio n. 9
0
class PlotFigure(Frame):

    def __init__(self):
        Frame.__init__(self, None, -1, "Test embedded wxFigure")

        self.fig = Figure((5,4), 75)
        self.canvas = FigureCanvasWx(self, -1, self.fig)
        self.toolbar = NavigationToolbar2Wx(self.canvas)
        self.toolbar.Realize()

        # On Windows, default frame size behaviour is incorrect
        # you don't need this under Linux
        tw, th = self.toolbar.GetSizeTuple()
        fw, fh = self.canvas.GetSizeTuple()
        self.toolbar.SetSize(Size(fw, th))

        # Create a figure manager to manage things
        self.figmgr = FigureManager(self.canvas, 1, self)
        # Now put all into a sizer
        sizer = BoxSizer(VERTICAL)
        # This way of adding to sizer allows resizing
        sizer.Add(self.canvas, 1, LEFT|TOP|GROW)
        # Best to allow the toolbar to resize!
        sizer.Add(self.toolbar, 0, GROW)
        self.SetSizer(sizer)
        self.Fit()
        EVT_TIMER(self, TIMER_ID, self.onTimer)

    def init_plot_data(self):
        a = self.fig.add_subplot(111)
        self.ind = numpy.arange(60)
        tmp = []
        for i in range(60):
            tmp.append(numpy.sin((self.ind+i)*numpy.pi/15))
        self.X = numpy.array(tmp)
        self.lines = a.plot(self.X[:,0],'o')
        self.count = 0

    def GetToolBar(self):
        # You will need to override GetToolBar if you are using an
        # unmanaged toolbar in your frame
        return self.toolbar

    def onTimer(self, evt):
        self.count += 1
        if self.count >= 60: self.count = 0
        self.lines[0].set_data(self.ind, self.X[:,self.count])
        self.canvas.draw()
        self.canvas.gui_repaint()
Esempio n. 10
0
class View(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, title='QRS detect')
        self.SetBackgroundColour(wx.NamedColour("WHITE"))
        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)

        #self.axes.plot(t, s)
        self.canvas = FigureCanvas(self, -1, self.figure)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.Fit()

        self.add_toolbar()  

        
    def add_toolbar(self):
        self.toolbar = NavigationToolbar2Wx(self.canvas)
        self.toolbar.Realize()
        if wx.Platform == '__WXMAC__':
            self.SetToolBar(self.toolbar)
        else:
            # On Windows platform, default window size is incorrect, so set
            # toolbar width to figure width.
            tw, th = self.toolbar.GetSizeTuple()
            fw, fh = self.canvas.GetSizeTuple()
            # By adding toolbar in sizer, we are able to put it at the bottom
            # of the frame - so appearance is closer to GTK version.
            # As noted above, doesn't work for Mac.
            self.toolbar.SetSize(wx.Size(fw, th))
            self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
        # update the axes menu on the toolbar
        self.toolbar.update()


    def plot(ecg1, ecg2, marks=None):
        """
        Plot will show two ECG leads, each with the marks, if available
        Last row will be rr intervals
        """
        if marks == None:
            self.axes.plot(ecg1)

        
    def OnPaint(self, event):
        self.canvas.draw()
Esempio n. 11
0
    def __init__(self, title='', verb=1):
        wx.Frame.__init__(self, None, -1, title, size=(400, 300))
        self.verb = verb
        self.figure = Figure()
        self.canvas = FigureCanvas(self, -1, self.figure)
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.Fit()

        # toolbar?
        # self.toolbar = NavigationToolbar2Wx(self.canvas)
        # self.toolbar.Realize()
        # self.sizer.Add(self.toolbar, 0, wx.BOTTOM | wx.EXPAND)
        # self.toolbar.update()

        # axis plotting info
        self.ax = None
        self.xmin = 1.0
        self.xmax = 0.0
        self.ymin = 1.0
        self.ymax = 0.0
        self.xlabel = ''
        self.ylabel = ''
        self.style = 'graph'

        self.images = []

        self.toolbar = NavigationToolbar2Wx(self.canvas)
        self.toolbar.Realize()
        self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
        self.toolbar.update()
Esempio n. 12
0
    def __init__(self):
        wxFrame.__init__(self, None, -1, "Test embedded wxFigure")

        self.fig = Figure((5,4), 75)
        self.canvas = FigureCanvasWx(self, -1, self.fig)
        self.toolbar = NavigationToolbar2Wx(self.canvas)
        self.toolbar.Realize()

        # On Windows, default frame size behaviour is incorrect
        # you don't need this under Linux
        tw, th = self.toolbar.GetSizeTuple()
        fw, fh = self.canvas.GetSizeTuple()
        self.toolbar.SetSize(wxSize(fw, th))

        # Create a figure manager to manage things
        self.figmgr = FigureManager(self.canvas, 1, self)
        # Now put all into a sizer
        sizer = wxBoxSizer(wxVERTICAL)
        # This way of adding to sizer allows resizing
        sizer.Add(self.canvas, 1, wxLEFT|wxTOP|wxGROW)
        # Best to allow the toolbar to resize!
        sizer.Add(self.toolbar, 0, wxGROW)
        self.SetSizer(sizer)
        self.Fit()
        EVT_TIMER(self, TIMER_ID, self.onTimer)
Esempio n. 13
0
    def OnInit(self, *args, **kw):
        wxInitAllImageHandlers()
        self.frame = wxFrame(None, -1, "PyScope")

        self.frame.fig = Figure((5, 4), 75)
        self.frame.canvas = FigureCanvasWx(self.frame, -1, self.frame.fig)
        self.frame.toolbar = NavigationToolbar2Wx(self.frame.canvas)
        self.frame.toolbar.Realize()

        # On Windows, default frame size behaviour is incorrect
        # you don't need this under Linux
        tw, th = self.frame.toolbar.GetSizeTuple()
        fw, fh = self.frame.canvas.GetSizeTuple()
        self.frame.toolbar.SetSize(wxSize(fw, th))

        # Create a figure manager to manage things
        self.frame.figmgr = FigureManager(self.frame.canvas, 1, self)
        # Now put all into a sizer
        sizer = wxBoxSizer(wxVERTICAL)
        # This way of adding to sizer allows resizing
        sizer.Add(self.frame.canvas, 1, wxLEFT | wxTOP | wxGROW)
        # Best to allow the toolbar to resize!
        sizer.Add(self.frame.toolbar, 0, wxGROW)
        self.frame.SetSizer(sizer)
        self.frame.Fit()
        EVT_TRIG(self, self.OnTrig)

        # finalize wx stuff
        self.frame.SetAutoLayout(true)
        self.frame.Show()
        self.SetTopWindow(self.frame)
        return True
Esempio n. 14
0
   def __init__(self, title='', verb=1):
      wx.Frame.__init__(self, None, -1, title, size=(400,300))
      self.verb   = verb
      self.figure = Figure()
      self.canvas = FigureCanvas(self, -1, self.figure)
      self.sizer = wx.BoxSizer(wx.VERTICAL)
      self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
      self.SetSizer(self.sizer)
      self.Fit()

      # toolbar?
      # self.toolbar = NavigationToolbar2Wx(self.canvas)
      # self.toolbar.Realize()
      # self.sizer.Add(self.toolbar, 0, wx.BOTTOM | wx.EXPAND)
      # self.toolbar.update()

      # axis plotting info
      self.ax     = None
      self.xmin   = 1.0
      self.xmax   = 0.0
      self.ymin   = 1.0
      self.ymax   = 0.0
      self.xlabel = ''
      self.ylabel = ''
      self.style  = 'graph'

      self.images = []

      self.toolbar = NavigationToolbar2Wx(self.canvas)
      self.toolbar.Realize()
      self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
      self.toolbar.update()
Esempio n. 15
0
class Plotter(wx.Panel):
    " Simple plotter class"

    def __init__(self, parent):
        self.parent = parent
        wx.Panel.__init__(self, parent, -1, size=(50, 50))
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.figure = matplotlib.figure.Figure()
        self.axPhase = self.figure.add_subplot(211)
        self.axPhase.hold(False)
        self.axU = self.figure.add_subplot(212)
        self.axU.hold(False)
        self.figure.subplots_adjust(hspace=0.5)
        self.canvas = FigureCanvas(self, -1, self.figure)
        self.sizer.Add(self.canvas)
        self.navtoolbar = NavigationToolbar2Wx(self.canvas)
        self.sizer.Add(self.navtoolbar)
        self.SetSizer(self.sizer)
        self.Fit()

    def plotPhaseFunction(self, phasefunction):
        " Plot the phase function, requires a pure function "
        # create x-axis
        wavelength = np.linspace(600, 900, 1000)
        #phasefunction is dependent on frequency, not wavelength, so convert
        vFun = np.vectorize(phasefunction)
        phases = vFun(w2f(wavelength))
        #print np.array([wavelength,phases]).transpose()
        self.axPhase.plot(wavelength, phases)
        self.axPhase.set_xlabel("Wavelength [nm]")
        self.axPhase.set_ylabel("Phase [rad]")
        self.canvas.draw()

    def plotVoltages(self, phasefunction):
        " Plot the voltages as a function of pixel index "
        # create x-axis
        x = np.arange(640)
        # get the data: do apply_phase with simulateOnly=True
        print "     PATTERN"
        pattern = self.parent.slmCal.apply_phase_on_freq(phasefunction,
                                                         simulateOnly=True)
        self.axU.plot(x, pattern, '-x')
        self.axU.set_xlabel("Pixel index #")
        self.axU.set_ylabel("Voltage")
        self.canvas.draw()
Esempio n. 16
0
class View(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, title='QRS detect')
        self.SetBackgroundColour(wx.NamedColour("WHITE"))
        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)

        #self.axes.plot(t, s)
        self.canvas = FigureCanvas(self, -1, self.figure)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.Fit()

        self.add_toolbar()

    def add_toolbar(self):
        self.toolbar = NavigationToolbar2Wx(self.canvas)
        self.toolbar.Realize()
        if wx.Platform == '__WXMAC__':
            self.SetToolBar(self.toolbar)
        else:
            # On Windows platform, default window size is incorrect, so set
            # toolbar width to figure width.
            tw, th = self.toolbar.GetSizeTuple()
            fw, fh = self.canvas.GetSizeTuple()
            # By adding toolbar in sizer, we are able to put it at the bottom
            # of the frame - so appearance is closer to GTK version.
            # As noted above, doesn't work for Mac.
            self.toolbar.SetSize(wx.Size(fw, th))
            self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
        # update the axes menu on the toolbar
        self.toolbar.update()

    def plot(ecg1, ecg2, marks=None):
        """
        Plot will show two ECG leads, each with the marks, if available
        Last row will be rr intervals
        """
        if marks == None:
            self.axes.plot(ecg1)

    def OnPaint(self, event):
        self.canvas.draw()
Esempio n. 17
0
class Plotter(wx.Panel):
    " Simple plotter class"
    def __init__(self,parent):
        self.parent = parent
        wx.Panel.__init__(self,parent,-1,size=(50,50))
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.figure = matplotlib.figure.Figure()
        self.axPhase = self.figure.add_subplot(211)
        self.axPhase.hold(False)
        self.axU = self.figure.add_subplot(212)
        self.axU.hold(False)
        self.figure.subplots_adjust(hspace=0.5)
        self.canvas = FigureCanvas(self,-1,self.figure)
        self.sizer.Add(self.canvas)
        self.navtoolbar = NavigationToolbar2Wx(self.canvas)
        self.sizer.Add(self.navtoolbar)
        self.SetSizer(self.sizer)
        self.Fit()

    def plotPhaseFunction(self,phasefunction):
        " Plot the phase function, requires a pure function "
        # create x-axis
        wavelength = np.linspace(600,900,1000)
        #phasefunction is dependent on frequency, not wavelength, so convert
        vFun = np.vectorize(phasefunction)
        phases = vFun(w2f(wavelength))
        #print np.array([wavelength,phases]).transpose()
        self.axPhase.plot(wavelength,phases)
        self.axPhase.set_xlabel("Wavelength [nm]")
        self.axPhase.set_ylabel("Phase [rad]")
        self.canvas.draw()

    def plotVoltages(self,phasefunction):
        " Plot the voltages as a function of pixel index "
        # create x-axis
        x = np.arange(640)
        # get the data: do apply_phase with simulateOnly=True
        print "     PATTERN"
        pattern = self.parent.slmCal.apply_phase_on_freq(phasefunction,simulateOnly=True)
        self.axU.plot(x,pattern,'-x')
        self.axU.set_xlabel("Pixel index #")
        self.axU.set_ylabel("Voltage")
        self.canvas.draw()
Esempio n. 18
0
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, wx.ID_ANY,
                          _("Trader Calculator - Back-Lay Proportion Rule"))

        __f = mpl.figure.Figure(figsize=(1, 1), facecolor="white")
        __a = __f.add_subplot(111)
        __a.spines['left'].set_smart_bounds(True)
        __a.spines['bottom'].set_smart_bounds(True)
        __a.xaxis.set_ticks_position('bottom')
        __a.yaxis.set_ticks_position('left')
        __a.spines['left'].set_position('zero')
        __a.spines['bottom'].set_position('zero')
        __a.spines['right'].set_color('none')
        __a.spines['top'].set_color('none')
        __a.annotate(_("Bias"),
                     xy=(1, 0),
                     xycoords="figure fraction",
                     xytext=(.93, .1),
                     textcoords="figure fraction",
                     horizontalalignment="center",
                     verticalalignment="center",
                     fontsize="medium")
        __a.annotate(_("Bias"),
                     xy=(1, 0),
                     xycoords="figure fraction",
                     xytext=(.07, .1),
                     textcoords="figure fraction",
                     horizontalalignment="center",
                     verticalalignment="center",
                     fontsize="medium")
        __a.annotate(_("Amount"),
                     xy=(1, 0),
                     xycoords="figure fraction",
                     xytext=(.5, .93),
                     textcoords="figure fraction",
                     horizontalalignment="center",
                     verticalalignment="center",
                     fontsize="medium")
        __a.set_xlim((-1.1, 1.1))
        __a.set_ylim((-1., 10.))
        __a.grid(True)

        self.canvas = FigCanvas(self, wx.ID_ANY, __f)
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.canvas, 1, wx.EXPAND)
        self.SetSizer(sizer)
        self.canvas.draw()
        self.Fit()
        self.SetSize((500, 300))
        self.Bind(wx.EVT_CLOSE, self.OnClose)
Esempio n. 19
0
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, title='QRS detect')
        self.SetBackgroundColour(wx.NamedColour("WHITE"))
        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)

        #self.axes.plot(t, s)
        self.canvas = FigureCanvas(self, -1, self.figure)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.Fit()

        self.add_toolbar()  
Esempio n. 20
0
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, title='QRS detect')
        self.SetBackgroundColour(wx.NamedColour("WHITE"))
        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)

        #self.axes.plot(t, s)
        self.canvas = FigureCanvas(self, -1, self.figure)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.Fit()

        self.add_toolbar()
Esempio n. 21
0
    def __init__(self):
        Frame.__init__(self, None, -1, "Test embedded wxFigure")

        self.fig = Figure((9, 8), 75)
        self.canvas = FigureCanvasWx(self, -1, self.fig)
        self.toolbar = Toolbar(self.canvas)
        self.toolbar.Realize()

        # On Windows, default frame size behaviour is incorrect
        # you don't need this under Linux
        tw, th = self.toolbar.GetSizeTuple()
        fw, fh = self.canvas.GetSizeTuple()
        self.toolbar.SetSize(Size(fw, th))

        # Create a figure manager to manage things
        self.figmgr = FigureManager(self.canvas, 1, self)
        # Now put all into a sizer
        sizer = BoxSizer(VERTICAL)
        # This way of adding to sizer allows resizing
        sizer.Add(self.canvas, 1, LEFT | TOP | GROW)
        # Best to allow the toolbar to resize!
        sizer.Add(self.toolbar, 0, GROW)
        self.SetSizer(sizer)
        self.Fit()
Esempio n. 22
0
 def __init__(self, parent):
     self.parent = parent
     wx.Panel.__init__(self, parent, -1, size=(50, 50))
     self.sizer = wx.BoxSizer(wx.VERTICAL)
     self.figure = matplotlib.figure.Figure()
     self.axPhase = self.figure.add_subplot(211)
     self.axPhase.hold(False)
     self.axU = self.figure.add_subplot(212)
     self.axU.hold(False)
     self.figure.subplots_adjust(hspace=0.5)
     self.canvas = FigureCanvas(self, -1, self.figure)
     self.sizer.Add(self.canvas)
     self.navtoolbar = NavigationToolbar2Wx(self.canvas)
     self.sizer.Add(self.navtoolbar)
     self.SetSizer(self.sizer)
     self.Fit()
Esempio n. 23
0
 def __init__(self,parent):
     self.parent = parent
     wx.Panel.__init__(self,parent,-1,size=(50,50))
     self.sizer = wx.BoxSizer(wx.VERTICAL)
     self.figure = matplotlib.figure.Figure()
     self.axPhase = self.figure.add_subplot(211)
     self.axPhase.hold(False)
     self.axU = self.figure.add_subplot(212)
     self.axU.hold(False)
     self.figure.subplots_adjust(hspace=0.5)
     self.canvas = FigureCanvas(self,-1,self.figure)
     self.sizer.Add(self.canvas)
     self.navtoolbar = NavigationToolbar2Wx(self.canvas)
     self.sizer.Add(self.navtoolbar)
     self.SetSizer(self.sizer)
     self.Fit()
Esempio n. 24
0
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, title='QRS detect')
        self.SetBackgroundColour(wx.NamedColour("WHITE"))
        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)

        self.canvas = FigureCanvas(self, -1, self.figure)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.Fit()

        self.add_toolbar()
        # http://stackoverflow.com/questions/4740988/add-new-navigate-modes-in-matplotlib
        self.pan_tool = self.toolbar.FindById(self.toolbar._NTB2_PAN)
        self.zoom_tool = self.toolbar.FindById(self.toolbar._NTB2_ZOOM)
Esempio n. 25
0
   def __init__(self, title='', as_one=0, verb=1):
      wx.Frame.__init__(self, None, -1, title, size=(400,300))
      self.verb   = verb
      self.figure = Figure()
      self.canvas = FigureCanvas(self, -1, self.figure)
      self.sizer = wx.BoxSizer(wx.VERTICAL)
      self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
      self.SetSizer(self.sizer)
      self.Fit()

      self.canvas.mpl_connect('key_press_event', self.cb_keypress)
      self.as_one  = as_one

      self.toolbar = NavigationToolbar2Wx(self.canvas)
      self.toolbar.Realize()
      self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
      self.toolbar.update()
Esempio n. 26
0
    def __init__(self, title='', as_one=0, verb=1):
        wx.Frame.__init__(self, None, -1, title, size=(400, 300))
        self.counter += 1
        self.verb = verb
        self.figure = Figure()
        self.canvas = FigureCanvas(self, -1, self.figure)
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.Fit()

        self.canvas.mpl_connect('key_press_event', self.cb_keypress)
        self.as_one = as_one

        self.toolbar = NavigationToolbar2Wx(self.canvas)
        self.toolbar.Realize()
        self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
        self.toolbar.update()
Esempio n. 27
0
class PlotFigure(wxFrame):
    def __init__(self):
        wxFrame.__init__(self, None, -1, "Test embedded wxFigure")

        self.fig = Figure((5, 4), 75)
        self.canvas = FigureCanvasWx(self, -1, self.fig)
        self.toolbar = Toolbar(self.canvas)
        self.toolbar.Realize()

        # On Windows, default frame size behaviour is incorrect
        # you don't need this under Linux
        tw, th = self.toolbar.GetSizeTuple()
        fw, fh = self.canvas.GetSizeTuple()
        self.toolbar.SetSize(wxSize(fw, th))

        # Create a figure manager to manage things
        self.figmgr = FigureManager(self.canvas, 1, self)
        # Now put all into a sizer
        sizer = wxBoxSizer(wxVERTICAL)
        # This way of adding to sizer allows resizing
        sizer.Add(self.canvas, 1, wxLEFT | wxTOP | wxGROW)
        # Best to allow the toolbar to resize!
        sizer.Add(self.toolbar, 0, wxGROW)
        self.SetSizer(sizer)
        self.Fit()

    def plot_data(self):
        # Use ths line if using a toolbar
        a = self.figmgr.add_subplot(111)

        # Or this one if there is no toolbar
        #a = Subplot(self.fig, 111)

        t = numpy.arange(0.0, 3.0, 0.01)
        s = numpy.sin(2 * numpy.pi * t)
        c = numpy.cos(2 * numpy.pi * t)
        a.plot(t, s)
        a.plot(t, c)
        self.toolbar.update()

    def GetToolBar(self):
        # You will need to override GetToolBar if you are using an
        # unmanaged toolbar in your frame
        return self.toolbar
Esempio n. 28
0
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, title='QRS detect')
        self.SetBackgroundColour(wx.NamedColour("WHITE"))
        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)

        self.canvas = FigureCanvas(self, -1, self.figure)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.Fit()
        
        self.add_toolbar()  
        # http://stackoverflow.com/questions/4740988/add-new-navigate-modes-in-matplotlib
        self.pan_tool  = self.toolbar.FindById(
                         self.toolbar._NTB2_PAN)
        self.zoom_tool = self.toolbar.FindById(
                         self.toolbar._NTB2_ZOOM)
Esempio n. 29
0
    def __init__(self, parent, id, style=0):
        wx.Frame.__init__(self, parent, id, "MCE Viewport", \
                          style=wx.DEFAULT_FRAME_STYLE & ~wx.CLOSE_BOX)

        #        self.SetWindowStyle(wx.SIMPLE_BORDER)

        self.fig = Figure((9, 8), 60)
        self.canvas = FigureCanvasWx(self, -1, self.fig)
        self.axes = self.fig.add_subplot(111)

        self.toolbar = Toolbar(self.canvas)
        self.toolbar.Realize()
        # Create a figure manager to manage things
        self.figmgr = FigureManager(self.canvas, 1, self)
        # Now put all into a sizer
        sizer = wx.BoxSizer(wx.VERTICAL)
        # This way of adding to sizer allows resizing
        sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        # Best to allow the toolbar to resize!
        sizer.Add(self.toolbar, 0, wx.GROW)
        self.SetSizer(sizer)
        self.Fit()
Esempio n. 30
0
class View(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, title='QRS detect')
        self.SetBackgroundColour(wx.NamedColour("WHITE"))
        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)

        self.canvas = FigureCanvas(self, -1, self.figure)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.Fit()

        self.add_toolbar()
        # http://stackoverflow.com/questions/4740988/add-new-navigate-modes-in-matplotlib
        self.pan_tool = self.toolbar.FindById(self.toolbar._NTB2_PAN)
        self.zoom_tool = self.toolbar.FindById(self.toolbar._NTB2_ZOOM)

    def add_toolbar(self):
        self.toolbar = NavigationToolbar2Wx(self.canvas)
        self.toolbar.Realize()
        if wx.Platform == '__WXMAC__':
            self.SetToolBar(self.toolbar)
        else:
            # On Windows platform, default window size is incorrect, so set
            # toolbar width to figure width.
            tw, th = self.toolbar.GetSizeTuple()
            fw, fh = self.canvas.GetSizeTuple()
            # By adding toolbar in sizer, we are able to put it at the bottom
            # of the frame - so appearance is closer to GTK version.
            # As noted above, doesn't work for Mac.
            self.toolbar.SetSize(wx.Size(fw, th))
            self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
        # update the axes menu on the toolbar
        self.toolbar.update()

    def init_plot(self, ecg1, ecg2, marks):
        """
        Plot will show two ECG leads, each with the marks, if available
        Last row will be rr intervals
        """
        ecg1 += (ecg2.max() - ecg2.min())

        self.axes.plot(ecg1, 'b')
        self.axes.plot(ecg2, 'b')
        if marks != None:
            for samp, label in marks:
                self.axes.plot(samp, ecg1[samp], 'ok')
                self.axes.plot(samp, ecg2[samp], 'ok')

    def add_mark(self, x, y1, y2):
        """
        New mark to be plotted.
        y1 and y2 are heights for lead1 and lead2
        """
        self.axes.plot(x, y1, 'ok')
        self.axes.plot(x, y2, 'ok')
        self.canvas.draw()

    def remove_mark(self, x, y1, y2):
        """
        Remove existing marks from leads 1 and 2
        Draw red cross over to denote remove
        """
        print 'plotting at', x, y1
        self.axes.plot(x, y1, 'xr')
        self.axes.plot(x, y2, 'xr')
        self.canvas.draw()

    def _get_xrange(self):
        xmin, xmax = self.axes.get_xbound()
        return xmax - xmin

    def OnPaint(self, event):
        self.canvas.draw()
Esempio n. 31
0
class icPlotPanel(wx.Panel):
    """
    """
    def __init__(self,
                 parent,
                 id=-1,
                 pos=(-1, -1),
                 size=(-1, -1),
                 style=0,
                 bWxAgg=False):
        wx.Panel.__init__(self, parent, id, pos, size, style=style)

        self.fig = Figure((5, 4), 75)

        if bWxAgg:
            self.canvas = FigureCanvasWxAgg(self, -1, self.fig)
        else:
            self.canvas = FigureCanvasWx(self, -1, self.fig)

        self.canvas.mpl_connect('motion_notify_event', self.OnMouseMove)
        self.canvas.mpl_connect('button_press_event', self.OnMouseLeftDown)

        self.toolbar = icPloterToolbar(self.canvas)
        self.toolbar.Realize()
        self.parent = parent
        self.legendLst = []

        # --- Атрибуты курсора
        #   Положение курсора
        self._cursor = None
        #   Значение курсора
        self._cursorVal = None
        #   Статический курсор - значение обновляется только при нажантии
        #   левой кнопки мыши
        self._statCursor = None

        # On Windows, default frame size behaviour is incorrect
        # you don't need this under Linux
        tw, th = self.toolbar.GetSizeTuple()
        fw, fh = self.canvas.GetSizeTuple()
        self.toolbar.SetSize(wx.Size(fw, th))

        # Create a figure manager to manage things
        self.figmgr = FigureManager(self.canvas, 1, self)
        # Now put all into a sizer
        sizer = wx.BoxSizer(wx.VERTICAL)
        # This way of adding to sizer allows resizing
        sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        # Best to allow the toolbar to resize!
        sizer.Add(self.toolbar, 0, wx.GROW)
        self.SetSizer(sizer)
        self.Fit()

        # --- Описание обработчиков
        self.Bind(wx.EVT_PAINT, self.OnPaint)

        # --- Инициализация графика
        self.init_graph()

    def draw_cursor(self, event):
        """
        event is a MplEvent.  Draw a cursor over the axes
        """
        if event.inaxes is None:
            self.erase_cursor()
            try:
                del self.lastInfo
            except AttributeError:
                pass
            return

        canvas = self.canvas
        figheight = canvas.figure.bbox.height()
        ax = event.inaxes
        left, bottom, width, height = ax.bbox.get_bounds()
        bottom = figheight - bottom
        top = bottom - height
        right = left + width
        x, y = event.x, event.y
        y = figheight - y

        dc = wx.ClientDC(canvas)
        dc.SetLogicalFunction(wx.XOR)
        wbrush = wx.Brush(wx.Colour(255, 255, 255), wx.TRANSPARENT)
        wpen = wx.Pen(wx.Colour(200, 200, 200), 1, wx.SOLID)
        dc.SetBrush(wbrush)
        dc.SetPen(wpen)

        dc.ResetBoundingBox()
        dc.BeginDrawing()

        x, y, left, right, bottom, top = [
            int(val) for val in x, y, left, right, bottom, top
        ]

        self.erase_cursor()
        line1 = (x, bottom, x, top)
        line2 = (left, y, right, y)
        self.lastInfo = line1, line2, ax, dc
        dc.DrawLine(*line1)  # draw new
        dc.DrawLine(*line2)  # draw new
        dc.EndDrawing()

        time, price = event.xdata, event.ydata

        try:
            tm = str(num2date(time))[:16]
        except:
            tm = time

        self._cursor = (time, price)
        self._cursorVal = (tm, price)

    def erase_cursor(self):
        try:
            lastline1, lastline2, lastax, lastdc = self.lastInfo
        except AttributeError:
            pass
        else:
            lastdc.DrawLine(*lastline1)  # erase old
            lastdc.DrawLine(*lastline2)  # erase old

    def GetToolBar(self):
        """
        You will need to override GetToolBar if you are using an unmanaged toolbar in your frame.
        """
        return self.toolbar

    def GetCursorPos(self):
        """
        Возвращает положение курсора.
        """
        return self._cursor

    def GetCursorVal(self):
        """
        Возвращает значение курсора - временная координата приведена в
        читаемый вид - YYYY-MM-DD HH:MM:SS.
        """
        return self._cursorVal

    def GetStaticCursor(self):
        """
        Возвращает значение статического курсора - значение которого обновляется
        только при нажантии левой кнопки мыши.
        """
        return self._statCursor

    def init_graph(self):
        """
        Инициализация графика.
        """
        self.canvas.figure.set_facecolor('#f5f5f5')
        self.subplot = a = self.fig.add_subplot(111)

        a.grid(True)
        self.toolbar.update()

    def OnMouseMove(self, evt):
        """
        """
        self.draw_cursor(evt)

    def OnMouseLeftDown(self, evt):
        """
        """
        self._statCursor = self.GetCursorPos()

    def OnPaint(self, evt):
        """
        """
        self.erase_cursor()
        try:
            del self.lastInfo
        except AttributeError:
            pass

        self.canvas.draw()
        evt.Skip()

    def plot_data(self):
        a = self.subplot
        t = numpy.arange(0.0, 3.0, 0.01)
        s = numpy.sin(2 * numpy.pi * t)
        c = numpy.cos(2 * numpy.pi * t)
        a.plot(t, c, 'r:o')

    def add_plot_date(self,
                      dates,
                      values,
                      format=None,
                      xlabel=None,
                      ylabel=None,
                      bClear=True,
                      titlePlot='Title',
                      legend='Legend'):
        """
        Наполняет график точками.
        
        @type dates: C{list | tuple}
        @param dates: Список дат в формате datetime.
        @type values: C{list | tuple}
        @param values: Список значений.
        @type dates: C{list | tuple}
        @param dates: Список дат в формате datetime.
        @type xlabel: C{string}
        @param xlabel: Подпись оси X.
        @type ylabel: C{string}
        @param ylabel: Подпись оси Y.
        @type bClear: C{bool}
        @param bClear: Признак того, что необходимо все предыдущие точки удалить
            из графика.
        @type titlePlot: C{string}
        @param titlePlot: Заголовок.
        @type legend: C{string}
        @param legend: Легенда.
        """
        if bClear:
            self.subplot.lines = []
            self.legendLst = []

        matplotlib.rcParams['timezone'] = 'US/Pacific'
        tz = timezone('US/Pacific')

        majorTick = HourLocator(range(0, 25, 3), tz=tz)

        line = self.subplot.plot_date(dates, values, format, tz=tz)

        self.subplot.xaxis.set_major_locator(majorTick)

        #   Устанавливаем легенду
        self.legendLst.append(legend)
        self.subplot.legend(self.subplot.lines,
                            self.legendLst,
                            'upper right',
                            shadow=True)

    def set_date_plot2(self, date1=None, date2=None):
        """
        """
        # --- Plot2
        matplotlib.rcParams['timezone'] = 'US/Pacific'
        tz = timezone('US/Pacific')

        if not date1:
            date1 = datetime.datetime(2000, 3, 2, 0, tzinfo=tz)
        else:
            date1 = datetime.datetime(date1[0],
                                      date1[1],
                                      date1[2],
                                      date1[3],
                                      tzinfo=tz)

        if not date2:
            date2 = datetime.datetime(2000, 3, 2, 23, tzinfo=tz)
        else:
            date2 = datetime.datetime(date2[0],
                                      date2[1],
                                      date2[2],
                                      date2[3],
                                      tzinfo=tz)

        delta = datetime.timedelta(minutes=20)
        dates = drange(date1, date2, delta)

        dd = 10
        yy = pylab.arrayrange(len(dates) * 1.0)
        ysq = [y * y / dd for y in yy]

        self.add_plot_date(dates,
                           ysq,
                           'bo',
                           'Время',
                           'Цена',
                           legend='Скорость')
        self.add_plot_date(dates, yy, 'r-d', bClear=False)

        labels = self.subplot.get_xticklabels()
        pylab.set(labels, 'rotation', 45, size=10)
Esempio n. 32
0
   def __init__(self, title='', verb=1):
      #Make a figure and axes with dimensions as desired------------------------------------
      wx.Frame.__init__(self, None, -1, title, size=(400,300),style=wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER)          #400x300 window
      self.verb     = verb
      self.figure   = Figure(figsize=(5,5))                             
      self.AxisRT   = self.figure.add_axes([0.1, 0.05, 0.2, 0.6])
      self.canvas   = FigureCanvas(self, -1, self.figure)
      self.sizer    = wx.BoxSizer(wx.VERTICAL)
      self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
      self.SetSizer(self.sizer)
      self.Fit()
      self.ax               = None
      
      pic = wx.Icon("brain.ico", wx.BITMAP_TYPE_ICO)
      self.SetIcon(pic)
      
      #Maximum euclidean norm of derivate of motion
      self.TRESHOLDRT       = 0.9
      #Number of motions that is acceptable
      self.NMotion          = 15
      #Number of TR's
      self.TRNumber         = 4
      #Number of motions in the exam
      self.ACCmotionstatus  = 0
      #Euclidean motion of derivative of motion values
      self.eucMotion = 0
      #open file that contain data to display
      self.adata = LAD.Afni1D('motion.1D', verb=self.verb)
      #write none values to file
      self.adata.mat[0][0] = 0
      self.adata.mat[0][1] = 0
      self.adata.write('motion.1D',overwrite=1)
      #Variable that indicate when excessive motion is detected
      self.MotionDetected   = 0
      #counter to blink Excessive motion text
      self.counter          = 0
      #Color Map
      self.colobarRT        = 0
      #Maximum and Minimun Values
      self.normRT           = 0 
      #Boundaries
      self.bounds           = 0
      #Real Time Bargraph
      self.bargraphRT       = 0
      #rectangle to fill real time bar
      self.rectangleRT      = 0
      #Color map to accumulative head motion
      self.colobarACC       = 0
      #Maximun and minimun values of acc head motion
      self.normACC          = 0
      #Boudn of acc bar
      self.boundsACC        = 0
      #Accumulative bar
      self.bargraphACC      = 0
      #Accumulated motion
      self.motiondetectionacc  = 0
      
      #CREATE SOME TEXTS--------------------------------------------------------------------
      self.AxisRT.text(-0.4, 1.48, 'fMRI Motion Viewer', fontdict=fonttitle)
      
      self.MotionConfig = self.AxisRT.text(-0.4, 1.4, 'Accumulated motion: 0.00', fontdict=fontmediun)
      self.NMotionsConfig = self.AxisRT.text(-0.4, 1.32,'Head motion trend: Waiting...', fontdict=fontmediun)
      
      self.AxisRT.text(-0.1, 1.15, 'RT Head Motion', fontdict=fontmediun)
      self.MotionLimitText = self.AxisRT.text(0.12, 1, "- - -", fontdict=fontTRNumber)
      
      self.AxisRT.text(2.8, 1.31, 'TR', fontdict=fontmediun)
      self.TRNumberText = self.AxisRT.text(3.3, 1.3, self.TRNumber, fontdict=fontTR)
        
#       #REAL TIME HEAD MOTION BAR------------------------------------------------------------
      #self.colobarRT    = mpl.colors.ListedColormap(['c', 'y', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r'])
      #self.normRT       = mpl.colors.Normalize(vmin=0, vmax=5.0)
      #self.bounds       = [0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4.0, 4.5, 5]
      #self.normRT       = mpl.colors.BoundaryNorm(self.bounds, self.colobarRT.N)
      #self.bargraphRT   = mpl.colorbar.ColorbarBase(self.AxisRT, self.colobarRT,
       #                                 self.normRT,
       #                                 orientation='vertical')
      #self.bargraphRT.set_label('Real Time Head Motion')
      
      #Rectangle to fill the bar------------------------------------------------------------
      self.rectangleRT    = Rectangle((0.0, 0), 1, 1, facecolor='white')
      currentAxis         = self.figure.gca()
      currentAxis.add_patch(self.rectangleRT)
      
      #ACCUMULATIVE HEAD MOTION BAR---------------------------------------------------------
      self.AxisACC        = self.figure.add_axes([0.6, 0.05, 0.2, 0.6]) 
      
      #self.colobarACC   = mpl.colors.ListedColormap(['c', 'y', 'r'])
      #self.normACC      = mpl.colors.Normalize(vmin=0, vmax=25)
      
      #self.boundsACC    = [0, 5, 10, 15, 20, 25]
      #self.normACC      = mpl.colors.BoundaryNorm(self.boundsACC, self.colobarACC.N)
      #self.bargraphACC  = mpl.colorbar.ColorbarBase(self.AxisACC, cmap=self.colobarACC,
      #                             norm=self.normACC,
      #                             orientation='vertical')
      #self.bargraphACC.set_label('Number of motions detected')
      
      self.AxisACC.text(-0.1, 1.15, 'TR with motion', fontdict=fontmediun)
      self.NMotionText = self.AxisACC.text(0.18, 1, "- - -", fontdict=fontTRNumber)
      
      #Rectangle to fill the bar------------------------------------------------------------
      self.rectangleACC    = Rectangle((0.0, 0), 1, 1, facecolor='white')
      currentAxis          = self.figure.gca()
      currentAxis.add_patch(self.rectangleACC)
      
      #Excessive motion text----------------------------------------------------------------
      self.textExcessive = self.figure.text(0.1, 0.5, 'Excessive motion. Stop the Scan!', color='white', 
          bbox=dict(facecolor='red', edgecolor='red'))
      self.textExcessive.set_size('x-large')
      self.textExcessive.set_visible(False)
      
      TIMER_ID = 100  # pick a number
      self.timer = wx.Timer(self, TIMER_ID)
      self.Bind(wx.EVT_TIMER, self.OnTimer)
      
      # Add a panel so it looks correct on all platforms
      self.panel = wx.Panel(self, size=(400,400),pos=(0,0))
      
      self.labelInitText = wx.StaticText(self.panel, wx.ID_ANY, 'Please insert the exam info:', (85, 50), (160, -1), wx.ALIGN_CENTER)
      font2 = wx.Font(12, wx.DECORATIVE, wx.NORMAL, wx.NORMAL)
      self.labelInitText.SetFont(font2)
      self.labelInitText.SetForegroundColour((47,79,79)) # set text color
      
      self.TitlePanel = wx.StaticText(self.panel,-1,'fMRI Motion Viewer', (110, 10), (400, -1), wx.ALIGN_CENTER)
      font = wx.Font(14, wx.DECORATIVE, wx.NORMAL, wx.NORMAL)
      self.TitlePanel.SetFont(font)
      self.TitlePanel.SetForegroundColour((0,191,255)) # set text color
      
      self.labelInputOne = wx.StaticText(self.panel, wx.ID_ANY, 'Head Motion Limit [0 - 2.0]', (85, 80), (160, -1), wx.ALIGN_CENTER)
      font2 = wx.Font(12, wx.DECORATIVE, wx.NORMAL, wx.NORMAL)
      self.labelInputOne.SetFont(font2)
      self.labelInputOne.SetForegroundColour((47,79,79)) # set text color
      self.inputTxtOne = wx.TextCtrl(self.panel,wx.ID_ANY,'',pos=(85,100))
      self.inputTxtOne.WriteText('0.9')
      
      self.labelInputTwo = wx.StaticText(self.panel, wx.ID_ANY, 'Acceptable Head Motions [0 - 20]', (85, 140), (160, -1), wx.ALIGN_CENTER)
      self.labelInputTwo.SetFont(font2)
      self.labelInputTwo.SetForegroundColour((47,79,79)) # set text color
      self.inputTxtTwo = wx.TextCtrl(self.panel, wx.ID_ANY, '',pos=(85,160))
      self.inputTxtTwo.WriteText('15')
      
      self.labelHelp = wx.TextCtrl(parent = self.panel, id = -1, pos = (20, 210), size = (360, 100), style = wx.TE_MULTILINE|wx.TE_READONLY|wx.TE_AUTO_URL)
      self.labelHelp.AppendText("Note: This system was developed to detect excessive head motion in fMRI exams. For this it calculates the Euclidean norm of derivative of six degrees of freedom of the head.\n")
      
      self.okBtn = wx.Button(self.panel, wx.ID_ANY, 'Start   ',(85, 340), (60, -1), wx.ALIGN_CENTER)
      self.cancelBtn = wx.Button(self.panel, wx.ID_ANY, 'Quit   ',(255, 340), (60, -1), wx.ALIGN_CENTER)
      #self.HelpBtn = wx.Button(self.panel, wx.ID_ANY, 'Help  ',(255, 320), (60, -1), wx.ALIGN_CENTER)
      self.Bind(wx.EVT_BUTTON, self.onOK, self.okBtn)
      self.Bind(wx.EVT_BUTTON, self.onCancel, self.cancelBtn)

      self.Show(True)
class CanvasFrame(wx.Frame):
    """create a main plotting canvas
        title   : optional window title
        as_one  : plot as one overlapping graph
                  (else a list of scaled graphs)
        verb    : verbose level (default 1)
   """

    counter = 0

    def __init__(self, title="", as_one=0, verb=1):
        wx.Frame.__init__(self, None, -1, title, size=(400, 300))
        self.counter += 1
        self.verb = verb
        self.figure = Figure()
        self.canvas = FigureCanvas(self, -1, self.figure)
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.Fit()

        self.canvas.mpl_connect("key_press_event", self.cb_keypress)
        self.as_one = as_one

        self.toolbar = NavigationToolbar2Wx(self.canvas)
        self.toolbar.Realize()
        self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
        self.toolbar.update()

    def cb_keypress(self, event):
        if event.key == "q":
            self.Close()

    def plot_scaled_mat(self, amat, verb=1):
        """plot data scaled and shifted to fit on one graph

              data      - AfniMatrix, list of float lists, or 1D file
              title     - optional window title
              verb      - optional verbose level
      """

        # allow matlist, list of float lists,
        # if type(matlist) == type([]):
        #     e0 = matlist[0]
        #     if type

        if not matlist:
            return
        nmats = len(matlist)
        if nmats < 1:
            return

        yformat = FormatStrFormatter("%5.1f")

    def plot_matlist(self, matlist, title="", ylabels=[], ftcolors=0, verb=1):
        """plot AfniMatrix list, one graph per AfniMatrix
              matlist   - list of AfniMatrix elements
              title     - optional window title
              ylabels   - optional list of ylabel per mat
              ftcolors  - flag: use fit/timeseries colors (black blue)
              verb      - optional verbose level
      """

        if not matlist:
            return
        nmats = len(matlist)
        if nmats < 1:
            return

        yformat = FormatStrFormatter("%5.1f")
        matplotlib.rcParams["lines.linewidth"] = 2

        # make a label list, and get max length (among any label[0])
        if ylabels:
            labels = ylabels
        else:
            labels = []
        rlen = 0
        nruns = 0
        maxlen = 0
        for ind in range(nmats):
            if ylabels:
                lab = ylabels[ind]
            else:
                if matlist[ind].labels:
                    lab = matlist[ind].labels[0]
                else:
                    lab = ""
                labels.append(lab)
            if len(lab) > maxlen:
                maxlen = len(lab)

            # note run info
            if nruns == 0 and matlist[ind].nruns > 1:
                nruns = matlist[ind].nruns
                rlen = matlist[ind].run_len

        for ind in range(nmats):
            amat = matlist[ind]

            if ind == 0:
                tstr = title
            else:
                tstr = ""

            ax = self.figure.add_subplot(nmats, 1, ind + 1, title=tstr)
            # if ftcolors and amat.ncols == 2:   # use blue over black?
            #   ax.plot(amat.mat[:,0], 'k')
            #   ax.plot(amat.mat[:,1], 'b')
            ax.plot(amat.mat)

            # apply y tickmarks
            ymin, ymax = ax.get_ylim()
            width = ymax - ymin
            if ymin * ymax < 0.0:
                ymean = 0.0
            else:
                ymean = round((ymin + ymax) / 2.0, 2)

            ax.grid(True)

            ax.yaxis.set_major_formatter(yformat)

            # if there are many graphs, reduce the number of yticks
            if nmats > 10:
                ax.set_yticks(N.array([ymin, ymax]))
            elif nmats > 2:
                ax.set_yticks(N.array([ymin, ymean, ymax]))

            if rlen > 0:
                ax.set_xticks(N.array([r * rlen for r in range(nruns + 1)]))
            if ind < nmats - 1:
                ax.set_xticklabels([])
            else:
                ax.set_xlabel("TRs")

            if labels:
                if nmats > 1:
                    ax.set_ylabel("%-*s " % (maxlen, labels[ind]), rotation="horizontal")
                    rv, plist = self.axis_posn(ax)
                    if rv == 0:
                        ax.set_position((0.15, plist[1], 0.7, 0.7 / nmats))
                else:
                    ax.set_ylabel("%s" % labels[ind])
                    ax.set_position((0.15, 0.2, 0.7, 0.7))

        self.canvas.draw()

        matplotlib.rcParams["lines.linewidth"] = 1  # reset

    def axis_posn(self, ax):
        """return error code, posn array"""

        # first attempt is to look for simple array return
        try:
            posn = ax.get_position()
        except:
            if self.verb > 1:
                print "** failed ax.get_position()"
            return 1, None

        # have list, ready for some return
        if type(posn) == type([]):
            if len(posn) < 4:
                if self.verb > 1:
                    print "** get_position returns len %d list" % len(posn)
                return 1, None
            if self.verb > 2:
                print "-- get_position returns list %s" % UTIL.float_list_string(posn)
            return 0, posn

        # no list, assume Bbox and expect get_points() to return 2x2 numpy array
        try:
            plist = posn.get_points()
        except:
            if self.verb > 1:
                print "** failed posn.get_points()"
            return 1, None

        if type(plist) != type(N.array([])):
            if self.verb > 1:
                print "** posn.get_points() does not return N.array?"
            return 1, None

        try:
            pnlist = [plist[0][0], plist[0][1], plist[1][0], plist[1][1]]
        except:
            if self.verb > 1:
                print "** bad plist shape %s" % plist.shape
            return 1, None

        if self.verb > 2:
            print "-- get_position returns Bbox list: %s" % UTIL.float_list_string(pnlist)

        return 0, pnlist

    def plot_mat_by_cols(self, amat, cols=[]):
        """plot the given columns from a single AfniMatrix"""

        if not isinstance(amat, AM.AfniXmat):
            print "** plot_MBC: instance is not AfniXmat"
            return

        if not cols:
            if amat.verb > 1:
                print "-- plotting default of %d cols" % amat.ncols
            cols = [i for i in range(amat.ncols)]

        ncols = len(cols)
        if ncols < 1:
            return

        # create reduced matrix and column labels
        mat = amat.mat[:, cols]

        yformat = FormatStrFormatter("%5.1f")
        if amat.labels:
            labels = N.array(amat.labels)
            labels = labels[cols]
            labels = labels.tolist()

            # create axis formatter string

            striplabs = 1
            for label in labels:  # strip trailing '#' if indices are all 0
                ind = regress_index(label)
                if ind > 0:
                    striplabs = 0

            maxlen = 0
            for l in range(len(labels)):
                label = labels[l]
                if striplabs:
                    labels[l] = labels[l][0 : labels[l].rfind("#")]
                if len(labels[l]) > maxlen:
                    maxlen = len(labels[l])

        for i in range(ncols):
            if i == 0:
                title = "%s [%s]" % (os.path.basename(amat.fname), UTIL.encode_1D_ints(cols))
            else:
                title = ""

            if self.as_one:
                # then only create one axis
                if i == 0:
                    ax = self.figure.add_subplot(1, 1, 1, title=title)
            else:
                ax = self.figure.add_subplot(ncols, 1, i + 1, title=title)
            data = mat[:, i]
            ax.plot(data)

            # apply y tickmarks
            ymin, ymax = ax.get_ylim()
            width = ymax - ymin
            if ymin * ymax < 0.0:
                ymean = 0.0
            else:
                ymean = round((ymin + ymax) / 2.0, 2)

            ax.grid(True)

            ax.yaxis.set_major_formatter(yformat)
            amax = round(data.max(), 1)

            if self.as_one:
                pass  # use default yticks
            elif amax == 1.0 and ymin == 0.0:
                ax.set_yticks(N.array([ymin, amax]))
            elif ncols > 10:
                ax.set_yticks(N.array([ymin, ymax]))
            else:
                ax.set_yticks(N.array([ymin, ymean, ymax]))

            # now that yticks are set, prevent tight limits
            if not self.as_one:
                if ymin == data.min():
                    ymin -= 0.15 * width
                    ax.set_ylim((ymin, ymax))

                if ymax == data.max():
                    ymax += 0.15 * width
                    ax.set_ylim((ymin, ymax))

                if amat.run_len > 10 and amat.nruns > 1:
                    ax.set_xticks(N.array([r * amat.run_len for r in range(amat.nruns + 1)]))

            if i < ncols - 1:
                ax.set_xticklabels([])
            else:
                ax.set_xlabel("TRs")

            if self.as_one:
                ax.set_ylabel("")
            elif amat.labels:
                ax.set_ylabel("%-*s " % (maxlen, labels[i]), rotation="horizontal")
                rv, plist = self.axis_posn(ax)
                # rcr - fix
                # if rv == 0: ax.set_position((0.2, plist[1], plist[2], plist[3]))
                if rv == 0:
                    ax.set_position((0.15, plist[1], 0.7, 0.7 / ncols))

        self.Fit()
        self.canvas.draw()
Esempio n. 34
0
class PlotFigure(wx.Panel):
    def __init__(self, parent, id=-1, pos=(-1, -1), size=(-1, -1), style=0):
        wx.Panel.__init__(self, parent, id, pos, size, style=style)

        self.fig = Figure((5, 4), 75)
        self.canvas = FigureCanvasWx(self, -1, self.fig)
        self.toolbar = Toolbar(self.canvas)
        self.toolbar.Realize()

        # On Windows, default frame size behaviour is incorrect
        # you don't need this under Linux
        tw, th = self.toolbar.GetSizeTuple()
        fw, fh = self.canvas.GetSizeTuple()
        self.toolbar.SetSize(wx.Size(fw, th))

        # Create a figure manager to manage things
        self.figmgr = FigureManager(self.canvas, 1, self)
        # Now put all into a sizer
        sizer = wx.BoxSizer(wx.VERTICAL)
        # This way of adding to sizer allows resizing
        sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        # Best to allow the toolbar to resize!
        sizer.Add(self.toolbar, 0, wx.GROW)
        self.SetSizer(sizer)
        self.Fit()

        # --- Инициализация графика
        self.init_graph()

    def GetToolBar(self):
        """
        You will need to override GetToolBar if you are using an unmanaged toolbar in your frame.
        """
        return self.toolbar

    def init_graph(self):
        """
        Инициализация графика. 
        """
        self.subplot = a = self.fig.add_subplot(111)
        a.set_ylabel(u'Цена ($)\n')
        a.set_xlabel(u'Время')
        self.toolbar.update()

    def plot_data(self):
        a = self.subplot
        t = numpy.arange(0.0, 3.0, 0.01)
        s = numpy.sin(2 * numpy.pi * t)
        c = numpy.cos(2 * numpy.pi * t)
        a.plot(t, c, 'r:o')

    def add_plot_date(self,
                      dates,
                      values,
                      format=None,
                      xlabel=None,
                      ylabel=None,
                      bClear=True):
        """
        Наполняет график точками.
        
        @type dates: C{list | tuple}
        @param dates: Список дат в формате datetime.
        @type values: C{list | tuple}
        @param values: Список значений.
        @type dates: C{list | tuple}
        @param dates: Список дат в формате datetime.
        @type xlabel: C{string}
        @param xlabel: Подпись оси X.
        @type ylabel: C{string}
        @param ylabel: Подпись оси Y.
        @type bClear: C{bool}
        @param bClear: Признак того, что необходимо все предыдущие точки удалить
            из графика.
        """
        if bClear:
            self.subplot.lines = []

        matplotlib.rcParams['timezone'] = 'US/Pacific'
        tz = timezone('US/Pacific')

        majorTick = HourLocator(range(0, 25, 1), tz=tz)

        line, = self.subplot.plot_date(dates, values, format, tz=tz)
        line.set_markersize(3)

        self.subplot.xaxis.set_major_locator(majorTick)
        if xlabel:
            self.subplot.set_xlabel(xlabel)

        if ylabel:
            self.subplot.set_ylabel(ylabel + '\n')

    def set_date_plot2(self, date1=None, date2=None):
        """
        """
        # --- Plot2
        matplotlib.rcParams['timezone'] = 'US/Pacific'
        tz = timezone('US/Pacific')

        date1 = datetime.datetime(2000, 3, 2, 10, tzinfo=tz)
        date2 = datetime.datetime(2000, 3, 2, 15, tzinfo=tz)
        delta = datetime.timedelta(minutes=5)
        dates = drange(date1, date2, delta)

        dd = 10
        yy = pylab.arrayrange(len(dates) * 1.0)
        ysq = [y * y / dd for y in yy]

        self.add_plot_date(dates, ysq, 'b-o', u'Время', u'Цена')
        self.add_plot_date(dates, yy, 'r-d', bClear=False)
Esempio n. 35
0
class CanvasFrame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, wx.ID_ANY,
                          _("Trader Calculator - Back-Lay Proportion Rule"))

        __f = mpl.figure.Figure(figsize=(1, 1), facecolor="white")
        __a = __f.add_subplot(111)
        __a.spines['left'].set_smart_bounds(True)
        __a.spines['bottom'].set_smart_bounds(True)
        __a.xaxis.set_ticks_position('bottom')
        __a.yaxis.set_ticks_position('left')
        __a.spines['left'].set_position('zero')
        __a.spines['bottom'].set_position('zero')
        __a.spines['right'].set_color('none')
        __a.spines['top'].set_color('none')
        __a.annotate(_("Bias"),
                     xy=(1, 0),
                     xycoords="figure fraction",
                     xytext=(.93, .1),
                     textcoords="figure fraction",
                     horizontalalignment="center",
                     verticalalignment="center",
                     fontsize="medium")
        __a.annotate(_("Bias"),
                     xy=(1, 0),
                     xycoords="figure fraction",
                     xytext=(.07, .1),
                     textcoords="figure fraction",
                     horizontalalignment="center",
                     verticalalignment="center",
                     fontsize="medium")
        __a.annotate(_("Amount"),
                     xy=(1, 0),
                     xycoords="figure fraction",
                     xytext=(.5, .93),
                     textcoords="figure fraction",
                     horizontalalignment="center",
                     verticalalignment="center",
                     fontsize="medium")
        __a.set_xlim((-1.1, 1.1))
        __a.set_ylim((-1., 10.))
        __a.grid(True)

        self.canvas = FigCanvas(self, wx.ID_ANY, __f)
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.canvas, 1, wx.EXPAND)
        self.SetSizer(sizer)
        self.canvas.draw()
        self.Fit()
        self.SetSize((500, 300))
        self.Bind(wx.EVT_CLOSE, self.OnClose)

    def Clear(self):
        ax = self.canvas.figure.axes[0]
        while ax.lines:
            del (ax.lines[0])
        ax.set_xlim((-1.1, 1.1))
        ax.set_ylim((-1., 10.))
        ax.set_visible(False)
        self.canvas.draw()
        self.Refresh()

    def Plot(self, *args, **kargs):
        ax = self.canvas.figure.axes[0]
        for idx in range(len(ax.lines)):
            if ax.lines[idx].get_label() == kargs["label"]:
                del (ax.lines[idx])
                break
        ax.plot(*args, **kargs)
        ax.set_visible(True)

    def Mark(self, bias, amount):
        ax = self.canvas.figure.axes[0]
        if len(ax.texts) > 3: del (ax.texts[-1])
        ax.annotate("%.02f" % amount,
                    xy=(bias, amount),
                    xycoords='data',
                    xytext=(6, 24),
                    textcoords='offset points',
                    weight="bold",
                    fontsize="large",
                    bbox=dict(boxstyle="round", fc="1.0"),
                    arrowprops=dict(arrowstyle="->",
                                    lw=2,
                                    connectionstyle="arc3"))

    def Autoscale(self):
        ax = self.canvas.figure.axes[0]
        ymin = min([line.get_data()[1].min() for line in ax.lines])
        ymin = (1.1 if ymin < 0.0 else .9) * ymin
        ymax = max([line.get_data()[1].max() for line in ax.lines])
        ymax = (1.1 if ymin > 0.0 else .9) * ymax
        ax.set_ylim((ymin, ymax))
        ax.legend(bbox_to_anchor=(0, 0, 1, 1),
                  bbox_transform=self.canvas.figure.transFigure)
        self.canvas.draw()
        self.Refresh()

    def OnClose(self, evt):
        mbar = self.GetParent().GetMenuBar()
        menu = mbar.GetMenu(1)
        idx = menu.FindItem("Show Plot")
        menu.Check(idx, False)
        self.Show(False)
class cls_CalibGraph(wx.Frame):
    def __init__(self, *args, **kwds):

        wx.Frame.__init__(self, None, -1, "Test ReSo - Calibration graphs")

        #        self.fig = Figure((9,8), 75)
        self.fig = Figure()
        self.canvas = FigureCanvasWx(self, -1, self.fig)
        self.toolbar = Toolbar(self.canvas)
        self.toolbar.Realize()

        # On Windows, default frame size behaviour is incorrect
        # you don't need this under Linux
        tw, th = self.toolbar.GetSizeTuple()
        fw, fh = self.canvas.GetSizeTuple()
        self.toolbar.SetSize(wx.Size(fw, th))

        # Create a figure manager to manage things
        self.figmgr = FigureManager(self.canvas, 1, self)
        # Now put all into a sizer
        sizer = wx.BoxSizer(wx.VERTICAL)
        # This way of adding to sizer allows resizing
        sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        # Best to allow the toolbar to resize!
        sizer.Add(self.toolbar, 0, wx.GROW)
        self.SetSizer(sizer)
        self.Fit()

##    def plot_data(self):
##        # Use ths line if using a toolbar
##        a = self.fig.add_subplot(111)
##
##        # Or this one if there is no toolbar
##        #a = Subplot(self.fig, 111)
##
##        t = numpy.arange(0.0,3.0,0.01)
##        s = numpy.sin(2*numpy.pi*t)
##        c = numpy.cos(2*numpy.pi*t)
##        a.plot(t,s)
##        a.plot(t,c)
##        self.toolbar.update()

    def calibGRAPH(self, DateInput, S, h, hmeas, Smeas, Sm, Sr):
        """
        calibGRAPH: GRAPH the computed data and the calibration one, that it h and S
        Use Matplotlib
        _______________________________________________________________________________

        INPUTS
                STATE VARIABLES
                    TS              Time step
                    S               Daily soil moisture
                    Smeas           Daily measured soil moisture
                    h               Daily water level
                    hmeas           Daily measured water level
        ______________________________________________________________________________
        ______________________________________________________________________________
        """

        months = MonthLocator()
        monthsFmt = DateFormatter('%y-%m')

        #__________________Create outputs plots______________________#

        #        figCalib=figure()
        #        figCalib.Title='Calibration graphs'

        ax2 = self.fig.add_subplot(212)
        setp(ax2.get_xticklabels(), fontsize=8)
        setp(ax2.get_yticklabels(), fontsize=8)
        ax2.plot_date(DateInput, h, '-')
        ax2.yaxis.set_major_formatter(FormatStrFormatter('%1.1f'))
        labels = ax2.get_yticklabels()
        setp(labels, 'rotation', 90)
        ax2.xaxis.set_major_locator(months)
        ax2.xaxis.set_major_formatter(monthsFmt)
        xlim((DateInput[0], DateInput[len(S) - 1]))
        hmax = hmin = h[0]
        labels = ax2.get_xticklabels()
        setp(labels, 'rotation', 90)
        for i in range(0, len(DateInput)):
            if h[i] > hmax:
                hmax = h[i]
            elif h[i] < hmin:
                hmin = h[i]
        ax2.plot_date(DateInput, hmeas, 'mo', markersize=4)
        if hmeas[0] == -999:
            hmmax = -999
            hmmin = 999
        else:
            hmmax = hmmin = hmeas[0]
        for i in range(0, len(DateInput)):
            if hmeas[i] != -999:
                if hmeas[i] > hmmax:
                    hmmax = h[i]
                if hmeas[i] < hmmin:
                    hmmin = h[i]
        if hmin > hmmin:
            hmin = hmmin
        if hmax < hmmax:
            hmax = hmmax
        ybuffer = 0.1 * (hmax - hmin)
        ylim((hmin - ybuffer, hmax + ybuffer))
        ax2yaxis.set_major_formatter(FormatStrFormatter('%.1f'))
        ylabel('m')
        legend((r'h', r'hmeas'), loc=0)
        leg = gca().get_legend()
        ltext = leg.get_texts()  # all the text.Text instance in the legend
        setp(ltext, fontsize='small')  # the legend text fontsize
        xlabel(r'Date')
        grid(True)

        ax1 = self.fig.add_subplot(211, sharex=ax2)
        setp(ax1.get_xticklabels(), visible=False)
        setp(ax1.get_yticklabels(), fontsize=8)
        ax1.plot_date(DateInput, S, '-')
        ax1.plot_date(DateInput, Smeas, 'mo', markersize=4)
        legend((r'S', r'Smeas'), loc=0)
        leg = gca().get_legend()
        ltext = leg.get_texts()  # all the text.Text instance in the legend
        setp(ltext, fontsize='small')  # the legend text fontsize
        #        ybuffer=0.1*(float(Sm)-float(Sr))
        #        ylim((float(Sr) - ybuffer,float(Sm) + ybuffer))
        ylim(0, 1)
        ylabel('mm')
        ax1.yaxis.set_major_formatter(FormatStrFormatter('%1.2f'))
        labels = ax1.get_yticklabels()
        setp(labels, 'rotation', 90)
        grid(True)

#        subplots_adjust(left=0.05, bottom=0.1, right=0.95, top=0.95, wspace=0.1, hspace=0.05)

    def GetToolBar(self):
        # You will need to override GetToolBar if you are using an
        # unmanaged toolbar in your frame
        return self.toolbar
Esempio n. 37
0
class CanvasFrame(wx.Frame):
    """create a main plotting canvas
        title   : optional window title
        as_one  : plot as one overlapping graph
                  (else a list of scaled graphs)
        verb    : verbose level (default 1)
   """

    counter = 0

    def __init__(self, title='', as_one=0, verb=1):
        wx.Frame.__init__(self, None, -1, title, size=(400, 300))
        self.counter += 1
        self.verb = verb
        self.figure = Figure()
        self.canvas = FigureCanvas(self, -1, self.figure)
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.Fit()

        self.canvas.mpl_connect('key_press_event', self.cb_keypress)
        self.as_one = as_one

        self.toolbar = NavigationToolbar2Wx(self.canvas)
        self.toolbar.Realize()
        self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
        self.toolbar.update()

    def cb_keypress(self, event):
        if event.key == 'q':
            self.Close()

    def plot_scaled_mat(self, amat, verb=1):
        """plot data scaled and shifted to fit on one graph

              data      - AfniMatrix, list of float lists, or 1D file
              title     - optional window title
              verb      - optional verbose level
      """

        # allow matlist, list of float lists,
        # if type(matlist) == type([]):
        #     e0 = matlist[0]
        #     if type

        if not matlist: return
        nmats = len(matlist)
        if nmats < 1: return

        yformat = FormatStrFormatter('%5.1f')

    def plot_matlist(self, matlist, title='', ylabels=[], ftcolors=0, verb=1):
        """plot AfniMatrix list, one graph per AfniMatrix
              matlist   - list of AfniMatrix elements
              title     - optional window title
              ylabels   - optional list of ylabel per mat
              ftcolors  - flag: use fit/timeseries colors (black blue)
              verb      - optional verbose level
      """

        if not matlist: return
        nmats = len(matlist)
        if nmats < 1: return

        yformat = FormatStrFormatter('%5.1f')
        matplotlib.rcParams['lines.linewidth'] = 2

        # make a label list, and get max length (among any label[0])
        if ylabels: labels = ylabels
        else: labels = []
        rlen = 0
        nruns = 0
        maxlen = 0
        for ind in range(nmats):
            if ylabels: lab = ylabels[ind]
            else:
                if matlist[ind].labels: lab = matlist[ind].labels[0]
                else: lab = ''
                labels.append(lab)
            if len(lab) > maxlen: maxlen = len(lab)

            # note run info
            if nruns == 0 and matlist[ind].nruns > 1:
                nruns = matlist[ind].nruns
                rlen = matlist[ind].run_len

        for ind in range(nmats):
            amat = matlist[ind]

            if ind == 0: tstr = title
            else: tstr = ''

            ax = self.figure.add_subplot(nmats, 1, ind + 1, title=tstr)
            #if ftcolors and amat.ncols == 2:   # use blue over black?
            #   ax.plot(amat.mat[:,0], 'k')
            #   ax.plot(amat.mat[:,1], 'b')
            ax.plot(amat.mat)

            # apply y tickmarks
            ymin, ymax = ax.get_ylim()
            width = ymax - ymin
            if ymin * ymax < 0.0: ymean = 0.0
            else: ymean = round((ymin + ymax) / 2.0, 2)

            ax.grid(True)

            ax.yaxis.set_major_formatter(yformat)

            # if there are many graphs, reduce the number of yticks
            if nmats > 10: ax.set_yticks(N.array([ymin, ymax]))
            elif nmats > 2: ax.set_yticks(N.array([ymin, ymean, ymax]))

            if rlen > 0:
                ax.set_xticks(N.array([r * rlen for r in range(nruns + 1)]))
            if ind < nmats - 1: ax.set_xticklabels([])
            else: ax.set_xlabel('TRs')

            if labels:
                if nmats > 1:
                    ax.set_ylabel('%-*s ' % (maxlen, labels[ind]),
                                  rotation='horizontal')
                    rv, plist = self.axis_posn(ax)
                    if rv == 0:
                        ax.set_position((0.15, plist[1], 0.7, 0.7 / nmats))
                else:
                    ax.set_ylabel('%s' % labels[ind])
                    ax.set_position((0.15, 0.2, 0.7, 0.7))

        self.canvas.draw()

        matplotlib.rcParams['lines.linewidth'] = 1  # reset

    def axis_posn(self, ax):
        """return error code, posn array"""

        # first attempt is to look for simple array return
        try:
            posn = ax.get_position()
        except:
            if self.verb > 1: print '** failed ax.get_position()'
            return 1, None

        # have list, ready for some return
        if type(posn) == type([]):
            if len(posn) < 4:
                if self.verb > 1:
                    print '** get_position returns len %d list' % len(posn)
                return 1, None
            if self.verb > 2:                print '-- get_position returns list %s' % \
              UTIL.float_list_string(posn)
            return 0, posn

        # no list, assume Bbox and expect get_points() to return 2x2 numpy array
        try:
            plist = posn.get_points()
        except:
            if self.verb > 1: print '** failed posn.get_points()'
            return 1, None

        if type(plist) != type(N.array([])):
            if self.verb > 1:
                print '** posn.get_points() does not return N.array?'
            return 1, None

        try:
            pnlist = [plist[0][0], plist[0][1], plist[1][0], plist[1][1]]
        except:
            if self.verb > 1: print '** bad plist shape %s' % plist.shape
            return 1, None

        if self.verb > 2:            print '-- get_position returns Bbox list: %s' % \
            UTIL.float_list_string(pnlist)

        return 0, pnlist

    def plot_mat_by_cols(self, amat, cols=[]):
        """plot the given columns from a single AfniMatrix"""

        if not isinstance(amat, AM.AfniXmat):
            print '** plot_MBC: instance is not AfniXmat'
            return

        if not cols:
            if amat.verb > 1:
                print '-- plotting default of %d cols' % amat.ncols
            cols = [i for i in range(amat.ncols)]

        ncols = len(cols)
        if ncols < 1: return

        # create reduced matrix and column labels
        mat = amat.mat[:, cols]

        yformat = FormatStrFormatter('%5.1f')
        if amat.labels:
            labels = N.array(amat.labels)
            labels = labels[cols]
            labels = labels.tolist()

            # create axis formatter string

            striplabs = 1
            for label in labels:  # strip trailing '#' if indices are all 0
                ind = regress_index(label)
                if ind > 0: striplabs = 0

            maxlen = 0
            for l in range(len(labels)):
                label = labels[l]
                if striplabs:
                    labels[l] = labels[l][0:labels[l].rfind('#')]
                if len(labels[l]) > maxlen: maxlen = len(labels[l])

        for i in range(ncols):
            if i == 0:
                title = '%s [%s]' % (os.path.basename(
                    amat.fname), UTIL.encode_1D_ints(cols))
            else:
                title = ''

            if self.as_one:
                # then only create one axis
                if i == 0: ax = self.figure.add_subplot(1, 1, 1, title=title)
            else:
                ax = self.figure.add_subplot(ncols, 1, i + 1, title=title)
            data = mat[:, i]
            ax.plot(data)

            # apply y tickmarks
            ymin, ymax = ax.get_ylim()
            width = ymax - ymin
            if ymin * ymax < 0.0: ymean = 0.0
            else: ymean = round((ymin + ymax) / 2.0, 2)

            ax.grid(True)

            ax.yaxis.set_major_formatter(yformat)
            amax = round(data.max(), 1)

            if self.as_one: pass  # use default yticks
            elif amax == 1.0 and ymin == 0.0:
                ax.set_yticks(N.array([ymin, amax]))
            elif ncols > 10:
                ax.set_yticks(N.array([ymin, ymax]))
            else:
                ax.set_yticks(N.array([ymin, ymean, ymax]))

            # now that yticks are set, prevent tight limits
            if not self.as_one:
                if ymin == data.min():
                    ymin -= 0.15 * width
                    ax.set_ylim((ymin, ymax))

                if ymax == data.max():
                    ymax += 0.15 * width
                    ax.set_ylim((ymin, ymax))

                if amat.run_len > 10 and amat.nruns > 1:
                    ax.set_xticks(
                        N.array(
                            [r * amat.run_len for r in range(amat.nruns + 1)]))

            if i < ncols - 1: ax.set_xticklabels([])
            else: ax.set_xlabel('TRs')

            if self.as_one: ax.set_ylabel('')
            elif amat.labels:
                ax.set_ylabel('%-*s ' % (maxlen, labels[i]),
                              rotation='horizontal')
                rv, plist = self.axis_posn(ax)
                # rcr - fix
                #if rv == 0: ax.set_position((0.2, plist[1], plist[2], plist[3]))
                if rv == 0: ax.set_position((0.15, plist[1], 0.7, 0.7 / ncols))

        self.Fit()
        self.canvas.draw()
Esempio n. 38
0
 def get_canvas(self, frame, fig):
     return FigureCanvasWx(frame, -1, fig)
Esempio n. 39
0
class CanvasFrame(wx.Frame):
   """create a main plotting canvas
        title   : optional window title
        verb    : verbose level (default 1)
   """

   counter = 0
   def __init__(self, title='', verb=1):
      wx.Frame.__init__(self, None, -1, title, size=(400,300))
      self.verb   = verb
      self.figure = Figure()
      self.canvas = FigureCanvas(self, -1, self.figure)
      self.sizer = wx.BoxSizer(wx.VERTICAL)
      self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
      self.SetSizer(self.sizer)
      self.Fit()

      # toolbar?
      # self.toolbar = NavigationToolbar2Wx(self.canvas)
      # self.toolbar.Realize()
      # self.sizer.Add(self.toolbar, 0, wx.BOTTOM | wx.EXPAND)
      # self.toolbar.update()

      # axis plotting info
      self.ax     = None
      self.xmin   = 1.0
      self.xmax   = 0.0
      self.ymin   = 1.0
      self.ymax   = 0.0
      self.xlabel = ''
      self.ylabel = ''
      self.style  = 'graph'

      self.images = []

      self.toolbar = NavigationToolbar2Wx(self.canvas)
      self.toolbar.Realize()
      self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
      self.toolbar.update()

   def cb_keypress(self, event):
      if event.key == 'q':
         self.Close()

   def set_limits(self, xmin=1.0, xmax=0.0, ymin=1.0, ymax=0.0):
      """if xmin < xmax: apply, and similarly for y"""
      if xmin < xmax:
         self.xmin = xmin
         self.xmax = xmax
         if self.verb > 2: print '-- resetting xlimits to:', xmin, xmax
      if ymin < ymax:
         self.ymin = ymin
         self.ymax = ymax
         if self.verb > 2: print '-- resetting ylimits to:', ymin, ymax

   def plot_data(self, data, title=''):
      """plot data
         style can be 'graph' or 'bar'"""

      if self.ax == None:
         self.ax = self.figure.add_subplot(1,1,1,title=title)

      self.ax.clear()

      if self.style == 'graph':
         self.ax.plot(data)
         self.ax.grid(True)
      else:     # bars of width 1
         offsets = N.arange(len(data))
         bars = self.ax.bar(offsets, data, 1)

      self.ax.set_xlabel(self.xlabel)
      self.ax.set_ylabel(self.ylabel)

      # after data is plotted, set limits
      if self.xmin < self.xmax: self.ax.set_xlim((self.xmin, self.xmax))
      if self.ymin < self.ymax: self.ax.set_ylim((self.ymin, self.ymax))

      self.Fit()        # maybe not applied without a running app loop
      self.canvas.draw()

   def exit(self):
      self.Destroy()
Esempio n. 40
0
class CanvasFrame(wx.Frame):
   """create a main plotting canvas
        title   : optional window title
        verb    : verbose level (default 1)
   """
   def __init__(self, title='', verb=1):
      #Make a figure and axes with dimensions as desired------------------------------------
      wx.Frame.__init__(self, None, -1, title, size=(400,300),style=wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER)          #400x300 window
      self.verb     = verb
      self.figure   = Figure(figsize=(5,5))                             
      self.AxisRT   = self.figure.add_axes([0.1, 0.05, 0.2, 0.6])
      self.canvas   = FigureCanvas(self, -1, self.figure)
      self.sizer    = wx.BoxSizer(wx.VERTICAL)
      self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
      self.SetSizer(self.sizer)
      self.Fit()
      self.ax               = None
      
      pic = wx.Icon("brain.ico", wx.BITMAP_TYPE_ICO)
      self.SetIcon(pic)
      
      #Maximum euclidean norm of derivate of motion
      self.TRESHOLDRT       = 0.9
      #Number of motions that is acceptable
      self.NMotion          = 15
      #Number of TR's
      self.TRNumber         = 4
      #Number of motions in the exam
      self.ACCmotionstatus  = 0
      #Euclidean motion of derivative of motion values
      self.eucMotion = 0
      #open file that contain data to display
      self.adata = LAD.Afni1D('motion.1D', verb=self.verb)
      #write none values to file
      self.adata.mat[0][0] = 0
      self.adata.mat[0][1] = 0
      self.adata.write('motion.1D',overwrite=1)
      #Variable that indicate when excessive motion is detected
      self.MotionDetected   = 0
      #counter to blink Excessive motion text
      self.counter          = 0
      #Color Map
      self.colobarRT        = 0
      #Maximum and Minimun Values
      self.normRT           = 0 
      #Boundaries
      self.bounds           = 0
      #Real Time Bargraph
      self.bargraphRT       = 0
      #rectangle to fill real time bar
      self.rectangleRT      = 0
      #Color map to accumulative head motion
      self.colobarACC       = 0
      #Maximun and minimun values of acc head motion
      self.normACC          = 0
      #Boudn of acc bar
      self.boundsACC        = 0
      #Accumulative bar
      self.bargraphACC      = 0
      #Accumulated motion
      self.motiondetectionacc  = 0
      
      #CREATE SOME TEXTS--------------------------------------------------------------------
      self.AxisRT.text(-0.4, 1.48, 'fMRI Motion Viewer', fontdict=fonttitle)
      
      self.MotionConfig = self.AxisRT.text(-0.4, 1.4, 'Accumulated motion: 0.00', fontdict=fontmediun)
      self.NMotionsConfig = self.AxisRT.text(-0.4, 1.32,'Head motion trend: Waiting...', fontdict=fontmediun)
      
      self.AxisRT.text(-0.1, 1.15, 'RT Head Motion', fontdict=fontmediun)
      self.MotionLimitText = self.AxisRT.text(0.12, 1, "- - -", fontdict=fontTRNumber)
      
      self.AxisRT.text(2.8, 1.31, 'TR', fontdict=fontmediun)
      self.TRNumberText = self.AxisRT.text(3.3, 1.3, self.TRNumber, fontdict=fontTR)
        
#       #REAL TIME HEAD MOTION BAR------------------------------------------------------------
      #self.colobarRT    = mpl.colors.ListedColormap(['c', 'y', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r'])
      #self.normRT       = mpl.colors.Normalize(vmin=0, vmax=5.0)
      #self.bounds       = [0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4.0, 4.5, 5]
      #self.normRT       = mpl.colors.BoundaryNorm(self.bounds, self.colobarRT.N)
      #self.bargraphRT   = mpl.colorbar.ColorbarBase(self.AxisRT, self.colobarRT,
       #                                 self.normRT,
       #                                 orientation='vertical')
      #self.bargraphRT.set_label('Real Time Head Motion')
      
      #Rectangle to fill the bar------------------------------------------------------------
      self.rectangleRT    = Rectangle((0.0, 0), 1, 1, facecolor='white')
      currentAxis         = self.figure.gca()
      currentAxis.add_patch(self.rectangleRT)
      
      #ACCUMULATIVE HEAD MOTION BAR---------------------------------------------------------
      self.AxisACC        = self.figure.add_axes([0.6, 0.05, 0.2, 0.6]) 
      
      #self.colobarACC   = mpl.colors.ListedColormap(['c', 'y', 'r'])
      #self.normACC      = mpl.colors.Normalize(vmin=0, vmax=25)
      
      #self.boundsACC    = [0, 5, 10, 15, 20, 25]
      #self.normACC      = mpl.colors.BoundaryNorm(self.boundsACC, self.colobarACC.N)
      #self.bargraphACC  = mpl.colorbar.ColorbarBase(self.AxisACC, cmap=self.colobarACC,
      #                             norm=self.normACC,
      #                             orientation='vertical')
      #self.bargraphACC.set_label('Number of motions detected')
      
      self.AxisACC.text(-0.1, 1.15, 'TR with motion', fontdict=fontmediun)
      self.NMotionText = self.AxisACC.text(0.18, 1, "- - -", fontdict=fontTRNumber)
      
      #Rectangle to fill the bar------------------------------------------------------------
      self.rectangleACC    = Rectangle((0.0, 0), 1, 1, facecolor='white')
      currentAxis          = self.figure.gca()
      currentAxis.add_patch(self.rectangleACC)
      
      #Excessive motion text----------------------------------------------------------------
      self.textExcessive = self.figure.text(0.1, 0.5, 'Excessive motion. Stop the Scan!', color='white', 
          bbox=dict(facecolor='red', edgecolor='red'))
      self.textExcessive.set_size('x-large')
      self.textExcessive.set_visible(False)
      
      TIMER_ID = 100  # pick a number
      self.timer = wx.Timer(self, TIMER_ID)
      self.Bind(wx.EVT_TIMER, self.OnTimer)
      
      # Add a panel so it looks correct on all platforms
      self.panel = wx.Panel(self, size=(400,400),pos=(0,0))
      
      self.labelInitText = wx.StaticText(self.panel, wx.ID_ANY, 'Please insert the exam info:', (85, 50), (160, -1), wx.ALIGN_CENTER)
      font2 = wx.Font(12, wx.DECORATIVE, wx.NORMAL, wx.NORMAL)
      self.labelInitText.SetFont(font2)
      self.labelInitText.SetForegroundColour((47,79,79)) # set text color
      
      self.TitlePanel = wx.StaticText(self.panel,-1,'fMRI Motion Viewer', (110, 10), (400, -1), wx.ALIGN_CENTER)
      font = wx.Font(14, wx.DECORATIVE, wx.NORMAL, wx.NORMAL)
      self.TitlePanel.SetFont(font)
      self.TitlePanel.SetForegroundColour((0,191,255)) # set text color
      
      self.labelInputOne = wx.StaticText(self.panel, wx.ID_ANY, 'Head Motion Limit [0 - 2.0]', (85, 80), (160, -1), wx.ALIGN_CENTER)
      font2 = wx.Font(12, wx.DECORATIVE, wx.NORMAL, wx.NORMAL)
      self.labelInputOne.SetFont(font2)
      self.labelInputOne.SetForegroundColour((47,79,79)) # set text color
      self.inputTxtOne = wx.TextCtrl(self.panel,wx.ID_ANY,'',pos=(85,100))
      self.inputTxtOne.WriteText('0.9')
      
      self.labelInputTwo = wx.StaticText(self.panel, wx.ID_ANY, 'Acceptable Head Motions [0 - 20]', (85, 140), (160, -1), wx.ALIGN_CENTER)
      self.labelInputTwo.SetFont(font2)
      self.labelInputTwo.SetForegroundColour((47,79,79)) # set text color
      self.inputTxtTwo = wx.TextCtrl(self.panel, wx.ID_ANY, '',pos=(85,160))
      self.inputTxtTwo.WriteText('15')
      
      self.labelHelp = wx.TextCtrl(parent = self.panel, id = -1, pos = (20, 210), size = (360, 100), style = wx.TE_MULTILINE|wx.TE_READONLY|wx.TE_AUTO_URL)
      self.labelHelp.AppendText("Note: This system was developed to detect excessive head motion in fMRI exams. For this it calculates the Euclidean norm of derivative of six degrees of freedom of the head.\n")
      
      self.okBtn = wx.Button(self.panel, wx.ID_ANY, 'Start   ',(85, 340), (60, -1), wx.ALIGN_CENTER)
      self.cancelBtn = wx.Button(self.panel, wx.ID_ANY, 'Quit   ',(255, 340), (60, -1), wx.ALIGN_CENTER)
      #self.HelpBtn = wx.Button(self.panel, wx.ID_ANY, 'Help  ',(255, 320), (60, -1), wx.ALIGN_CENTER)
      self.Bind(wx.EVT_BUTTON, self.onOK, self.okBtn)
      self.Bind(wx.EVT_BUTTON, self.onCancel, self.cancelBtn)

      self.Show(True)

   def onOK(self, event):
        self.NMotion = int(self.inputTxtTwo.GetValue())
        self.TRESHOLDRT = float(self.inputTxtOne.GetValue())
        
        if self.TRESHOLDRT == 0.1:
           self.colobarRT    = mpl.colors.ListedColormap(['r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r'])
        elif self.TRESHOLDRT == 0.2:    
           self.colobarRT    = mpl.colors.ListedColormap(['y', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r'])
        elif self.TRESHOLDRT == 0.3:    
           self.colobarRT    = mpl.colors.ListedColormap(['c', 'y', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r'])
        elif self.TRESHOLDRT == 0.4:    
           self.colobarRT    = mpl.colors.ListedColormap(['c', 'c', 'y', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r'])
        elif self.TRESHOLDRT == 0.5:    
           self.colobarRT    = mpl.colors.ListedColormap(['c', 'c', 'y', 'y', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r'])
        elif self.TRESHOLDRT == 0.6:    
           self.colobarRT    = mpl.colors.ListedColormap(['c', 'c', 'c', 'y', 'y', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r'])
        elif self.TRESHOLDRT == 0.7:    
           self.colobarRT    = mpl.colors.ListedColormap(['c', 'c', 'c', 'c', 'y', 'y', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r'])
        elif self.TRESHOLDRT == 0.8:    
           self.colobarRT    = mpl.colors.ListedColormap(['c', 'c', 'c', 'c', 'y', 'y', 'y', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r'])
        elif self.TRESHOLDRT == 0.9:    
           self.colobarRT    = mpl.colors.ListedColormap(['c', 'c', 'c', 'c', 'c', 'y', 'y', 'y', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r'])
        elif self.TRESHOLDRT == 1.0:    
           self.colobarRT    = mpl.colors.ListedColormap(['c', 'c', 'c', 'c', 'c', 'c', 'y', 'y', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r'])
        elif self.TRESHOLDRT == 1.1:    
           self.colobarRT    = mpl.colors.ListedColormap(['c', 'c', 'c', 'c', 'c', 'c', 'c', 'y', 'y', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r'])
        elif self.TRESHOLDRT == 1.2:    
           self.colobarRT    = mpl.colors.ListedColormap(['c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'y', 'y', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r'])
        elif self.TRESHOLDRT == 1.3:    
           self.colobarRT    = mpl.colors.ListedColormap(['c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'y', 'y', 'y', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r'])
        elif self.TRESHOLDRT == 1.4:    
           self.colobarRT    = mpl.colors.ListedColormap(['c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'y', 'y', 'y', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r'])
        elif self.TRESHOLDRT == 1.5:    
           self.colobarRT    = mpl.colors.ListedColormap(['c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'y', 'y', 'y', 'r', 'r', 'r', 'r', 'r', 'r', 'r'])
        elif self.TRESHOLDRT == 1.6:    
           self.colobarRT    = mpl.colors.ListedColormap(['c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'y', 'y', 'y', 'r', 'r', 'r', 'r', 'r', 'r'])
        elif self.TRESHOLDRT == 1.7:    
           self.colobarRT    = mpl.colors.ListedColormap(['c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'y', 'y', 'y', 'r', 'r', 'r', 'r', 'r'])
        elif self.TRESHOLDRT == 1.8:    
           self.colobarRT    = mpl.colors.ListedColormap(['c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'y', 'y', 'y', 'r', 'r', 'r', 'r'])
        elif self.TRESHOLDRT == 1.9:    
           self.colobarRT    = mpl.colors.ListedColormap(['c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'y', 'y', 'y', 'r', 'r', 'r'])
        elif self.TRESHOLDRT == 2.0:    
           self.colobarRT    = mpl.colors.ListedColormap(['c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'y', 'y', 'y', 'y', 'r', 'r'])
        else: 
           self.colobarRT    = mpl.colors.ListedColormap(['c', 'c', 'c', 'y', 'y', 'y', 'y', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r'])
        #REAL TIME HEAD MOTION BAR------------------------------------------------------------
        self.normRT       = mpl.colors.Normalize(vmin=0, vmax=2.0)
        self.bounds       = [0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0]
        self.normRT       = mpl.colors.BoundaryNorm(self.bounds, self.colobarRT.N)
        self.bargraphRT   = mpl.colorbar.ColorbarBase(self.AxisRT, self.colobarRT,
                                       self.normRT,
                                       orientation='vertical')
        self.bargraphRT.set_label('Real Time Head Motion')
        
        if self.NMotion == 1:
           self.colobarACC    = mpl.colors.ListedColormap(['r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r'])
        elif self.NMotion == 2:    
           self.colobarACC    = mpl.colors.ListedColormap(['y', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r'])
        elif self.NMotion == 3:    
           self.colobarACC    = mpl.colors.ListedColormap(['c', 'y', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r'])
        elif self.NMotion == 4:    
           self.colobarACC    = mpl.colors.ListedColormap(['c', 'c', 'y', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r'])
        elif self.NMotion == 5:    
           self.colobarACC    = mpl.colors.ListedColormap(['c', 'c', 'y', 'y', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r'])
        elif self.NMotion == 6:    
           self.colobarACC    = mpl.colors.ListedColormap(['c', 'c', 'c', 'y', 'y', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r'])
        elif self.NMotion == 7:    
           self.colobarACC    = mpl.colors.ListedColormap(['c', 'c', 'c', 'c', 'y', 'y', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r'])
        elif self.NMotion == 8:    
           self.colobarACC    = mpl.colors.ListedColormap(['c', 'c', 'c', 'c', 'y', 'y', 'y', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r'])
        elif self.NMotion == 9:    
           self.colobarACC    = mpl.colors.ListedColormap(['c', 'c', 'c', 'c', 'c', 'y', 'y', 'y', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r'])
        elif self.NMotion == 10:    
           self.colobarACC    = mpl.colors.ListedColormap(['c', 'c', 'c', 'c', 'c', 'c', 'y', 'y', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r'])
        elif self.NMotion == 11:    
           self.colobarACC    = mpl.colors.ListedColormap(['c', 'c', 'c', 'c', 'c', 'c', 'c', 'y', 'y', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r'])
        elif self.NMotion == 12:    
           self.colobarACC    = mpl.colors.ListedColormap(['c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'y', 'y', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r'])
        elif self.NMotion == 13:    
           self.colobarACC    = mpl.colors.ListedColormap(['c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'y', 'y', 'y', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r'])
        elif self.NMotion == 14:    
           self.colobarACC    = mpl.colors.ListedColormap(['c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'y', 'y', 'y', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r'])
        elif self.NMotion == 15:    
           self.colobarACC    = mpl.colors.ListedColormap(['c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'y', 'y', 'y', 'r', 'r', 'r', 'r', 'r', 'r', 'r'])
        elif self.NMotion == 16:    
           self.colobarACC    = mpl.colors.ListedColormap(['c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'y', 'y', 'y', 'r', 'r', 'r', 'r', 'r', 'r'])
        elif self.NMotion == 17:    
           self.colobarACC    = mpl.colors.ListedColormap(['c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'y', 'y', 'y', 'r', 'r', 'r', 'r', 'r'])
        elif self.NMotion == 18:    
           self.colobarACC    = mpl.colors.ListedColormap(['c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'y', 'y', 'y', 'r', 'r', 'r', 'r'])
        elif self.NMotion == 19:    
           self.colobarACC    = mpl.colors.ListedColormap(['c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'y', 'y', 'y', 'r', 'r', 'r'])
        elif self.NMotion == 20:    
           self.colobarACC    = mpl.colors.ListedColormap(['c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'y', 'y', 'y', 'y', 'r', 'r'])
        else: 
           self.colobarACC    = mpl.colors.ListedColormap(['c', 'c', 'c', 'y', 'y', 'y', 'y', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r', 'r'])

        self.normACC      = mpl.colors.Normalize(vmin=0, vmax=20)
      
        self.boundsACC    = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
        self.normACC      = mpl.colors.BoundaryNorm(self.boundsACC, self.colobarACC.N)
        self.bargraphACC  = mpl.colorbar.ColorbarBase(self.AxisACC, cmap=self.colobarACC,
                                     norm=self.normACC,
                                     orientation='vertical')
        self.bargraphACC.set_label('Number of motions detected')
        
        #N-MOTIONS TRESHOLD-------------------------------------------------------------------
        self.pointsACC = np.ones(5)
        self.AxisACC.plot((self.NMotion/20.0) * self.pointsACC, linestyle='-', color='blue', linewidth=3)
        
        #self.MotionConfig.set_text('Head Motion Limit: %2.1f' % float(self.inputTxtOne.GetValue()))
        #self.NMotionsConfig.set_text('Acceptable Head Motions: %d' % int(self.inputTxtTwo.GetValue()))
             
        #Treshold configured to RT Motion bar-------------------------------------------------
        self.points       = np.ones(5)
        self.AxisRT.plot((self.TRESHOLDRT/2.0)*self.points, linestyle='-', color='blue', linewidth=3)
        
        self.timer.Start(100)    # 1 second interval  
        self.panel.Show(False)

   def onCancel(self, event):
        self.Close()
        
   def cb_keypress(self, event):
      if event.key == 'q':
         self.Close()
         
   def set_TR(self, data):
      self.TRNumber = data
      self.TRNumberText.set_text('%d' % self.TRNumber)
      
   def set_ACCmotionBar(self, data):
      self.rectangleACC.set_y(data)

   def set_limits(self, xmin=1.0, xmax=0.0, ymin=1.0, ymax=0.0):
      """if xmin < xmax: apply, and similarly for y"""
      if xmin < xmax:
         self.xmin = xmin
         self.xmax = xmax
         if self.verb > 2: print '-- resetting xlimits to:', xmin, xmax
      if ymin < ymax:
         self.ymin = ymin
         self.ymax = ymax
         if self.verb > 2: print '-- resetting ylimits to:', ymin, ymax

   def plot_data(self, data, title=''):
      """plot data
         style can be 'graph' or 'bar'"""
      if self.ax == None:
         self.ax = self.rectangleRT.set_y(data/2.0)
         self.MotionLimitText.set_text('%1.2f' % data)
      
      print data
      
      if data > self.TRESHOLDRT:
         self.ACCmotionstatus += 1
         self.NMotionText.set_text("%3d" % self.ACCmotionstatus)
         if self.ACCmotionstatus < 26:
             self.rectangleACC.set_y(self.ACCmotionstatus/20.0)
             
             if self.ACCmotionstatus > self.NMotion:
                 self.MotionDetected = 1

      #else: 
      #   self.textExcessive.set_visible(False)
         
      self.canvas.draw()

   def exit(self):
      self.Destroy()
      
   def OnTimer(self, event):
      self.adata = LAD.Afni1D('motion.1D', verb=self.verb)
      #print '-- TR: %d' % self.adata.mat[0][0]
      if self.adata.mat[0][0] != self.TRNumber:  
          self.eucMotion = self.adata.mat[0][1]
          self.set_TR(self.adata.mat[0][0])
          self.motiondetectionacc = self.motiondetectionacc + self.eucMotion
          self.MotionConfig.set_text('Accumulated motion: %2.2f' % float(self.motiondetectionacc))
          print '-- Euclidean Motion: %f' % self.adata.mat[0][1]
          self.plot_data(self.eucMotion)

      if self.TRNumber == 37 and self.motiondetectionacc < (self.TRESHOLDRT*17):
         self.NMotionsConfig.set_text('Head motion trend: PASS')
      elif self.TRNumber == 37 and self.motiondetectionacc > (self.TRESHOLDRT*17):
         self.NMotionsConfig.set_text('Head motion trend: FAIL')
      elif self.TRNumber < 37:
         self.NMotionsConfig.set_text('Head motion trend: Analyzing...') 


      if self.TRNumber <= 2:
         self.textExcessive.set_visible(False)
         self.ACCmotionstatus = 0
         self.rectangleACC.set_y(self.ACCmotionstatus/20.0)
         self.MotionDetected = 0 
         self.NMotionText.set_text("%3d" % self.ACCmotionstatus)   
         self.motiondetectionacc = 0 
         self.MotionConfig.set_text('Accumulated motion: 0.00')
         self.NMotionsConfig.set_text('Head motion trend: Waiting...')

      if self.MotionDetected == 1:
          #self.counter += 1
          #if self.counter < 10:
              self.textExcessive.set_visible(True)
Esempio n. 41
0
class View(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, title='QRS detect')
        self.SetBackgroundColour(wx.NamedColour("WHITE"))
        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)

        self.canvas = FigureCanvas(self, -1, self.figure)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.Fit()
        
        self.add_toolbar()  
        # http://stackoverflow.com/questions/4740988/add-new-navigate-modes-in-matplotlib
        self.pan_tool  = self.toolbar.FindById(
                         self.toolbar._NTB2_PAN)
        self.zoom_tool = self.toolbar.FindById(
                         self.toolbar._NTB2_ZOOM)
        

        
    def add_toolbar(self):
        self.toolbar = NavigationToolbar2Wx(self.canvas)
        self.toolbar.Realize()
        if wx.Platform == '__WXMAC__':
            self.SetToolBar(self.toolbar)
        else:
            # On Windows platform, default window size is incorrect, so set
            # toolbar width to figure width.
            tw, th = self.toolbar.GetSizeTuple()
            fw, fh = self.canvas.GetSizeTuple()
            # By adding toolbar in sizer, we are able to put it at the bottom
            # of the frame - so appearance is closer to GTK version.
            # As noted above, doesn't work for Mac.
            self.toolbar.SetSize(wx.Size(fw, th))
            self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
        # update the axes menu on the toolbar
        self.toolbar.update()


    def init_plot(self, ecg1, ecg2, marks):
        """
        Plot will show two ECG leads, each with the marks, if available
        Last row will be rr intervals
        """
        ecg1 += (ecg2.max() -  ecg2.min())

        self.axes.plot(ecg1, 'b')
        self.axes.plot(ecg2, 'b')
        if marks != None:
            for samp, label in marks:
                self.axes.plot(samp, ecg1[samp], 'ok')
                self.axes.plot(samp, ecg2[samp], 'ok')

    def add_mark(self, x, y1, y2):
        """
        New mark to be plotted.
        y1 and y2 are heights for lead1 and lead2
        """
        self.axes.plot(x, y1, 'ok')
        self.axes.plot(x, y2, 'ok')
        self.canvas.draw()
        
    def remove_mark(self, x, y1, y2):
        """
        Remove existing marks from leads 1 and 2
        Draw red cross over to denote remove
        """
        print 'plotting at', x, y1
        self.axes.plot(x, y1, 'xr')
        self.axes.plot(x, y2, 'xr')
        self.canvas.draw()
        

    def _get_xrange(self):
        xmin, xmax = self.axes.get_xbound()
        return xmax - xmin
        
                
    def OnPaint(self, event):
        self.canvas.draw()
Esempio n. 42
0
 def __init__(self, *args, **kargs):
     Canvas.__init__(self, *args, **kargs)
     CanvasMod.__init__(self, *args, **kargs)
Esempio n. 43
0
class CanvasFrame(wx.Frame):
    """create a main plotting canvas
        title   : optional window title
        verb    : verbose level (default 1)
   """

    counter = 0

    def __init__(self, title='', verb=1):
        wx.Frame.__init__(self, None, -1, title, size=(400, 300))
        self.verb = verb
        self.figure = Figure()
        self.canvas = FigureCanvas(self, -1, self.figure)
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.Fit()

        # toolbar?
        # self.toolbar = NavigationToolbar2Wx(self.canvas)
        # self.toolbar.Realize()
        # self.sizer.Add(self.toolbar, 0, wx.BOTTOM | wx.EXPAND)
        # self.toolbar.update()

        # axis plotting info
        self.ax = None
        self.xmin = 1.0
        self.xmax = 0.0
        self.ymin = 1.0
        self.ymax = 0.0
        self.xlabel = ''
        self.ylabel = ''
        self.style = 'graph'

        self.images = []

        self.toolbar = NavigationToolbar2Wx(self.canvas)
        self.toolbar.Realize()
        self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
        self.toolbar.update()

    def cb_keypress(self, event):
        if event.key == 'q':
            self.Close()

    def set_limits(self, xmin=1.0, xmax=0.0, ymin=1.0, ymax=0.0):
        """if xmin < xmax: apply, and similarly for y"""
        if xmin < xmax:
            self.xmin = xmin
            self.xmax = xmax
            if self.verb > 2: print '-- resetting xlimits to:', xmin, xmax
        if ymin < ymax:
            self.ymin = ymin
            self.ymax = ymax
            if self.verb > 2: print '-- resetting ylimits to:', ymin, ymax

    def plot_data(self, data, title=''):
        """plot data
         style can be 'graph' or 'bar'"""

        if self.ax == None:
            self.ax = self.figure.add_subplot(1, 1, 1, title=title)

        self.ax.clear()

        if self.style == 'graph':
            self.ax.plot(data)
            self.ax.grid(True)
        else:  # bars of width 1
            offsets = N.arange(len(data))
            bars = self.ax.bar(offsets, data, 1)

        self.ax.set_xlabel(self.xlabel)
        self.ax.set_ylabel(self.ylabel)

        # after data is plotted, set limits
        if self.xmin < self.xmax: self.ax.set_xlim((self.xmin, self.xmax))
        if self.ymin < self.ymax: self.ax.set_ylim((self.ymin, self.ymax))

        self.Fit()  # maybe not applied without a running app loop
        self.canvas.draw()

    def exit(self):
        self.Destroy()
Esempio n. 44
0
class View(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, title='QRS detect')
        self.SetBackgroundColour(wx.NamedColour("WHITE"))
        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)

        self.canvas = FigureCanvas(self, -1, self.figure)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.Fit()

        self.add_menubar()

        self.add_toolbar()
        # http://stackoverflow.com/questions/4740988/add-new-navigate-modes-in-matplotlib
        self.pan_tool = self.toolbar.FindById(self.toolbar._NTB2_PAN)
        self.zoom_tool = self.toolbar.FindById(self.toolbar._NTB2_ZOOM)

        self.Bind(wx.EVT_CLOSE, self.on_close)

    def on_close(self, event):
        pub.sendMessage("VIEW CLOSED")

    def add_toolbar(self):
        self.toolbar = NavigationToolbar2Wx(self.canvas)
        self.toolbar.Realize()
        if wx.Platform == '__WXMAC__':
            self.SetToolBar(self.toolbar)
        else:
            # On Windows platform, default window size is incorrect, so set
            # toolbar width to figure width.
            tw, th = self.toolbar.GetSizeTuple()
            fw, fh = self.canvas.GetSizeTuple()
            # By adding toolbar in sizer, we are able to put it at the bottom
            # of the frame - so appearance is closer to GTK version.
            # As noted above, doesn't work for Mac.
            self.toolbar.SetSize(wx.Size(fw, th))
            self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
        # update the axes menu on the toolbar
        self.toolbar.update()

    def add_menubar(self):
        """
        Loading and saving will be available in the menu
        """
        menubar = wx.MenuBar()

        file_menu = wx.Menu()
        file_menu.Append(ID_LOAD, "&Load", "Load ECG and/or annotation")
        file_menu.Append(ID_MARK, "&Annotate", "Generate new annotation")
        file_menu.Append(ID_SAVE, "&Save", "Save annotations")

        channel_menu = wx.Menu()
        channel_menu.Append(ID_CHANGE_CHANNEL, "&Change Chan 1",
                            "Change channel 1")

        menubar.Append(file_menu, "&File")
        menubar.Append(channel_menu, "&Channel")

        self.SetMenuBar(menubar)

    def init_plot(self, ecg1, ecg2, marks):
        """
        Plot will show two ECG leads, each with the marks, if available
        Last row will be rr intervals
        """
        print 'Plotting'
        ecg1, ecg2 = self.remove_overlap(ecg1, ecg2)

        # if zoomed in, maintain x axis zoom
        minx, maxx = self.axes.get_xlim()

        self.axes.clear()
        self.axes.plot(ecg1, 'b')
        self.axes.plot(ecg2, 'b')
        if marks != None:
            for samp, label in marks:
                self.axes.plot(samp, ecg1[samp], 'ok')
                self.axes.plot(samp, ecg2[samp], 'ok')

        if maxx != 1.0:  # which is the default without a plot
            self.axes.set_xlim(minx, maxx)

        self.canvas.draw()

    def remove_overlap(self, ecg1, ecg2):
        """
        Adjust baseline of ecg1 so that it doesnt overlap
        with ecg2
        """
        ht_ecg2 = ecg2.max() - ecg2.mean()
        depth_ecg1 = ecg1.mean() - ecg1.min()
        offset = ecg1.mean() - ecg2.mean()
        min_offset = ht_ecg2 + depth_ecg1
        if offset < min_offset:
            ecg1 += min_offset

        return ecg1, ecg2

    def add_mark(self, x, y1, y2):
        """
        New mark to be plotted.
        y1 and y2 are heights for lead1 and lead2
        """
        self.axes.plot(x, y1, 'ok')
        self.axes.plot(x, y2, 'ok')
        self.canvas.draw()

    def remove_mark(self, x, y1, y2):
        """
        Remove existing marks from leads 1 and 2
        Draw red cross over to denote remove
        """
        print 'plotting at', x, y1
        self.axes.plot(x, y1, 'xr')
        self.axes.plot(x, y2, 'xr')
        self.canvas.draw()

    def _get_xrange(self):
        xmin, xmax = self.axes.get_xbound()
        return xmax - xmin

    def OnPaint(self, event):
        self.canvas.draw()
Esempio n. 45
0
class View(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, title='QRS detect')
        self.SetBackgroundColour(wx.NamedColour("WHITE"))
        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)

        self.canvas = FigureCanvas(self, -1, self.figure)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.Fit()

        self.add_menubar()
        
        self.add_toolbar()  
        # http://stackoverflow.com/questions/4740988/add-new-navigate-modes-in-matplotlib
        self.pan_tool  = self.toolbar.FindById(
                         self.toolbar._NTB2_PAN)
        self.zoom_tool = self.toolbar.FindById(
                         self.toolbar._NTB2_ZOOM)

        self.Bind(wx.EVT_CLOSE, self.on_close)


    def on_close(self, event):
        pub.sendMessage("VIEW CLOSED")
        
        
    def add_toolbar(self):
        self.toolbar = NavigationToolbar2Wx(self.canvas)
        self.toolbar.Realize()
        if wx.Platform == '__WXMAC__':
            self.SetToolBar(self.toolbar)
        else:
            # On Windows platform, default window size is incorrect, so set
            # toolbar width to figure width.
            tw, th = self.toolbar.GetSizeTuple()
            fw, fh = self.canvas.GetSizeTuple()
            # By adding toolbar in sizer, we are able to put it at the bottom
            # of the frame - so appearance is closer to GTK version.
            # As noted above, doesn't work for Mac.
            self.toolbar.SetSize(wx.Size(fw, th))
            self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
        # update the axes menu on the toolbar
        self.toolbar.update()


    def add_menubar(self):
        """
        Loading and saving will be available in the menu
        """
        menubar = wx.MenuBar()

        file_menu = wx.Menu()
        file_menu.Append(ID_LOAD, "&Load", "Load ECG and/or annotation")
        file_menu.Append(ID_MARK, "&Annotate", "Generate new annotation")
        file_menu.Append(ID_SAVE, "&Save", "Save annotations")

        channel_menu = wx.Menu()
        channel_menu.Append(ID_CHANGE_CHANNEL, "&Change Chan 1",
                            "Change channel 1")
        
        menubar.Append(file_menu, "&File")
        menubar.Append(channel_menu, "&Channel")
        
        self.SetMenuBar(menubar)
        

    def init_plot(self, ecg1, ecg2, marks):
        """
        Plot will show two ECG leads, each with the marks, if available
        Last row will be rr intervals
        """
        print 'Plotting'
        ecg1, ecg2 = self.remove_overlap(ecg1, ecg2)

        # if zoomed in, maintain x axis zoom
        minx, maxx =  self.axes.get_xlim()

        self.axes.clear()
        self.axes.plot(ecg1, 'b')
        self.axes.plot(ecg2, 'b')
        if marks != None:
            for samp, label in marks:
                self.axes.plot(samp, ecg1[samp], 'ok')
                self.axes.plot(samp, ecg2[samp], 'ok')

        if maxx != 1.0: # which is the default without a plot
            self.axes.set_xlim(minx, maxx)
                
        self.canvas.draw()


    def remove_overlap(self, ecg1, ecg2):
        """
        Adjust baseline of ecg1 so that it doesnt overlap
        with ecg2
        """
        ht_ecg2 = ecg2.max() - ecg2.mean()
        depth_ecg1 = ecg1.mean() - ecg1.min()
        offset = ecg1.mean() - ecg2.mean()
        min_offset = ht_ecg2 + depth_ecg1
        if offset < min_offset:
            ecg1 += min_offset

        return ecg1, ecg2
        
        
    def add_mark(self, x, y1, y2):
        """
        New mark to be plotted.
        y1 and y2 are heights for lead1 and lead2
        """
        self.axes.plot(x, y1, 'ok')
        self.axes.plot(x, y2, 'ok')
        self.canvas.draw()
        
    def remove_mark(self, x, y1, y2):
        """
        Remove existing marks from leads 1 and 2
        Draw red cross over to denote remove
        """
        print 'plotting at', x, y1
        self.axes.plot(x, y1, 'xr')
        self.axes.plot(x, y2, 'xr')
        self.canvas.draw()
        

    def _get_xrange(self):
        xmin, xmax = self.axes.get_xbound()
        return xmax - xmin
        
                
    def OnPaint(self, event):
        self.canvas.draw()
Esempio n. 46
0
 def __init__(self, *args, **kargs):
     Canvas.__init__(self, *args, **kargs)
     CanvasMod.__init__(self, *args, **kargs)