def __init__(self): wxFrame.__init__(self, None, -1, "Test embedded wxFigure") self.fig = Figure((5, 4), 75) self.canvas = FigureCanvasWxAgg(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 # 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)
class PlotPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent, -1) self.fig = Figure((9,6), 100) self.canvas = FigureCanvasWxAgg(self, -1, self.fig) self.toolbar = Toolbar(self.canvas) #matplotlib toolbar self.toolbar.Realize() #self.toolbar.set_active([0,1]) # 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 init_plot_data(self): a = self.fig.add_subplot(111) t = np.arange(0,1,0.01) y = np.sin(2*np.pi*t) self.lines = a.plot(t,y) self.ax = a self.toolbar.update() # Not sure why this is needed - ADS def change_plot(self): self.ax.clear() t = np.arange(0,1,0.01) y2 = np.cos(2*np.pi*t) self.ax.plot(t,y2) self.canvas.draw() def GetToolBar(self): # You will need to override GetToolBar if you are using an # unmanaged toolbar in your frame return self.toolbar ## def OnWhiz(self,evt): ## self.x += np.pi/15 ## self.y += np.pi/20 ## z = np.sin(self.x) + np.cos(self.y) ## self.im.set_array(z) ## zmax = np.amax(z) - ERR_TOL ## ymax_i, xmax_i = np.nonzero(z >= zmax) ## if self.im.origin == 'upper': ## ymax_i = z.shape[0]-ymax_i ## self.lines[0].set_data(xmax_i,ymax_i) ## self.canvas.draw() def onEraseBackground(self, evt): # this is supposed to prevent redraw flicker on some X servers... pass
def __init__(self, parent): w, h = parent.GetSize() wx.Panel.__init__(self, parent=parent, size=(w, 0.7*h), style=wx.SUNKEN_BORDER) self.parent = parent self.legends = [] self.legendpos = [0.5, 1] self.fig = Figure(figsize=(12, 6), dpi=90) # create a figure size 8x6 inches, 80 dots per inches self.splts = [] self.canvas = FigureCanvasWxAgg(self, -1, self.fig) self.toolbar = Toolbar(self.canvas) # matplotlib toolbar # additional toolbar status_txt = wx.StaticText(self.toolbar, label=' Status on hover: ', pos=(230, 7), \ size=(100, 17)) self.status = wx.TextCtrl(self.toolbar, pos=(330,4), size=(300, 22), \ style=wx.TE_READONLY) self.toolbar.Realize() self.figw, self.figh = self.fig.get_window_extent().width, self.fig.get_window_extent().height sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.toolbar, 0, wx.GROW) sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW) self.SetSizer(sizer) self.box_width_fraction = 1.0 self.box_height_fraction = 0.9 self.lines = [] self.lined = dict() self.draggableList = ['Text', 'Legend'] # print(self.toolbar.GetBackgroundColour()) self.fig.canvas.mpl_connect('resize_event', self.squeeze_legend) self.fig.canvas.mpl_connect('pick_event', self.on_pick) self.fig.canvas.mpl_connect('motion_notify_event', self.on_motion) self.fig.canvas.mpl_connect('figure_leave_event', self.on_leave)
def __init__(self): wx.Frame.__init__(self, None, -1, "Test embedded wxFigure") self.fig = Figure((5, 4), 75) self.canvas = FigureCanvasWxAgg(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)) # Initialise the timer - wxPython requires this to be connected to # the receiving event handler self.t = wx.Timer(self, TIMER_ID) self.t.Start(10) # Create a figure manager to manage things # 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_TIMER, self.onTimer, id=TIMER_ID) self.Bind(wx.EVT_CLOSE, self.onClose)
class PlotPanel(wxPanel): def __init__(self, parent): wxPanel.__init__(self, parent, -1) self.fig = Figure((5, 4), 75) self.canvas = FigureCanvasWxAgg(self, -1, self.fig) self.toolbar = Toolbar(self.canvas) #matplotlib toolbar self.toolbar.Realize() #self.toolbar.set_active([0,1]) # 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 init_plot_data(self): a = self.fig.add_subplot(111) x = numerix.arange(120.0) * 2 * numerix.pi / 60.0 y = numerix.arange(100.0) * 2 * numerix.pi / 50.0 self.x, self.y = meshgrid(x, y) z = numerix.sin(self.x) + numerix.cos(self.y) self.im = a.imshow(z, cmap=cm.jet) #, interpolation='nearest') zmax = numerix.max(numerix.max(z)) - ERR_TOL ymax_i, xmax_i = numerix.nonzero(numerix.greater_equal(z, zmax)) if self.im.origin == 'upper': ymax_i = z.shape[0] - ymax_i self.lines = a.plot(xmax_i, ymax_i, 'ko') self.toolbar.update() # Not sure why this is needed - ADS def GetToolBar(self): # You will need to override GetToolBar if you are using an # unmanaged toolbar in your frame return self.toolbar def OnWhiz(self, evt): self.x += numerix.pi / 15 self.y += numerix.pi / 20 z = numerix.sin(self.x) + numerix.cos(self.y) self.im.set_array(z) zmax = numerix.max(numerix.max(z)) - ERR_TOL ymax_i, xmax_i = numerix.nonzero(numerix.greater_equal(z, zmax)) if self.im.origin == 'upper': ymax_i = z.shape[0] - ymax_i self.lines[0].set_data(xmax_i, ymax_i) self.canvas.draw() def onEraseBackground(self, evt): # this is supposed to prevent redraw flicker on some X servers... pass
class PlotPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent, -1) self.fig = Figure((5,4), 75) self.canvas = FigureCanvasWxAgg(self, -1, self.fig) self.toolbar = Toolbar(self.canvas) #matplotlib toolbar self.toolbar.Realize() #self.toolbar.set_active([0,1]) # 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 init_plot_data(self): a = self.fig.add_subplot(111) x = npy.arange(120.0)*2*npy.pi/60.0 y = npy.arange(100.0)*2*npy.pi/50.0 self.x, self.y = npy.meshgrid(x, y) z = npy.sin(self.x) + npy.cos(self.y) self.im = a.imshow( z, cmap=cm.jet)#, interpolation='nearest') zmax = npy.amax(z) - ERR_TOL ymax_i, xmax_i = npy.nonzero(z >= zmax) if self.im.origin == 'upper': ymax_i = z.shape[0]-ymax_i self.lines = a.plot(xmax_i,ymax_i,'ko') self.toolbar.update() # Not sure why this is needed - ADS def GetToolBar(self): # You will need to override GetToolBar if you are using an # unmanaged toolbar in your frame return self.toolbar def OnWhiz(self,evt): self.x += npy.pi/15 self.y += npy.pi/20 z = npy.sin(self.x) + npy.cos(self.y) self.im.set_array(z) zmax = npy.amax(z) - ERR_TOL ymax_i, xmax_i = npy.nonzero(z >= zmax) if self.im.origin == 'upper': ymax_i = z.shape[0]-ymax_i self.lines[0].set_data(xmax_i,ymax_i) self.canvas.draw() def onEraseBackground(self, evt): # this is supposed to prevent redraw flicker on some X servers... pass
class PlotPanel(wx.Panel): """This example is from something I found on the matplotlib webpage. They combined an embedded mpl plot with the wxPython xrc approach. They basically create a wx.Panel placeholder in the xrc file. See data_vis_gui.py for an example of using this class. Your really don't need anything other than the __init__ method. After that, just grab :py:attr:`self.fig` and use the matplotlib methods of the figure instance (the object-oriented API, not pylab).""" def __init__(self, parent, fig_size=(8, 6)): wx.Panel.__init__(self, parent, -1) self.fig = Figure(fig_size, 100) self.canvas = FigureCanvasWxAgg(self, -1, self.fig) self.toolbar = Toolbar(self.canvas) #matplotlib toolbar self.toolbar.Realize() #self.toolbar.set_active([0,1]) # 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 init_plot_data(self): """This just creates the starting graph.""" a = self.fig.add_subplot(111) t = np.arange(0, 1, 0.01) y = np.sin(2 * np.pi * t) self.lines = a.plot(t, y) self.ax = a self.toolbar.update() # Not sure why this is needed - ADS def change_plot(self): """This is just a method to show I can update the plot from a program. It doesn't really do anything else useful. It serves as an example of clearing the axis, plotting something, and refreshing the graph.""" self.ax.clear() t = np.arange(0, 1, 0.01) y2 = np.cos(2 * np.pi * t) self.ax.plot(t, y2) self.canvas.draw() def GetToolBar(self): """This is from the example; I don't know what it does.""" # You will need to override GetToolBar if you are using an # unmanaged toolbar in your frame return self.toolbar def onEraseBackground(self, evt): """I don't know what this does either (based on the comment below, I guess it prevents flicker).""" # this is supposed to prevent redraw flicker on some X servers... pass
class PlotFigure(wxFrame): def __init__(self): wxFrame.__init__(self, None, -1, "Test embedded wxFigure") self.fig = Figure((5,4), 75) self.canvas = FigureCanvasWxAgg(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 # 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): # jdh you can add a subplot directly from the fig rather than # the fig manager a = self.fig.add_subplot(111) self.x = numerix.arange(120.0)*2*numerix.pi/120.0 self.x.resize((100,120)) self.y = numerix.arange(100.0)*2*numerix.pi/100.0 self.y.resize((120,100)) self.y = numerix.transpose(self.y) z = numerix.sin(self.x) + numerix.cos(self.y) self.im = a.imshow( z, cmap=cm.jet)#, interpolation='nearest') 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.x += numerix.pi/15 self.y += numerix.pi/20 z = numerix.sin(self.x) + numerix.cos(self.y) self.im.set_array(z) self.canvas.draw() #self.canvas.gui_repaint() # jdh wxagg_draw calls this already def onEraseBackground(self, evt): # this is supposed to prevent redraw flicker on some X servers... pass
def __init__(self, parent): wx.Panel.__init__(self, parent) self.figure = Figure() self.axes = self.figure.add_subplot(111) self.canvas = FigureCanvas(self, -1, self.figure) self.toolbar = Toolbar(self.canvas) #matplotlib toolbar self.toolbar.Realize() self.sizer = wx.BoxSizer(wx.VERTICAL) #self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW) self.sizer.Add(self.canvas, 1, wx.EXPAND | wx.ALL) # Best to allow the toolbar to resize! self.sizer.Add(self.toolbar, 0, wx.GROW) self.SetSizer(self.sizer) self.Fit()
def __init__(self, parent, id=-1, dpi=None, **kwargs): wx.Panel.__init__(self, parent, id=id, **kwargs) self.figure = mpl.figure.Figure(dpi=dpi, figsize=(12, 10)) self.canvas = Canvas(self, -1, self.figure) self.l0 = wx.StaticText(self, -1, "Start at x=") self.t0 = wx.TextCtrl(self, 3, style=wx.TE_PROCESS_ENTER) #self.t0.SetRange(-1e10, 1e10) self.t0.Bind(wx.EVT_TEXT_ENTER, self.onUpdateT0, id=3) self.lv = wx.StaticText(self, -1, "") self.toolbar = Toolbar(self.canvas) self.toolbar.Realize() sizer1 = wx.BoxSizer(wx.HORIZONTAL) sizer1.Add(self.l0) sizer1.Add(self.t0) sizer1.Add(self.lv) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(sizer1, 1, wx.EXPAND) sizer.Add(self.canvas, 1, wx.EXPAND) sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND) self.SetSizer(sizer)
class CanvasPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent) self.figure = Figure() self.axes = self.figure.add_subplot(111) self.canvas = FigureCanvas(self, -1, self.figure) self.toolbar = Toolbar(self.canvas) #matplotlib toolbar self.toolbar.Realize() self.sizer = wx.BoxSizer(wx.VERTICAL) #self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW) self.sizer.Add(self.canvas, 1, wx.EXPAND | wx.ALL) # Best to allow the toolbar to resize! self.sizer.Add(self.toolbar, 0, wx.GROW) self.SetSizer(self.sizer) self.Fit() def GetToolBar(self): # You will need to override GetToolBar if you are using an # unmanaged toolbar in your frame return self.toolbar def draw(self): t = arange(0.0, 3.0, 0.01) s = sin(2 * pi * t) self.axes.plot(t, s) def OnPaint(self, event): self.canvas.draw()
def init_plot_panel(self): """Initializes the main panel of the AuxiliaryPage.""" # Instantiate a figure object that will contain our plots. self.figure = Figure() # Initialize the figure canvas, mapping the figure object to the plot # engine backend. canvas = FigureCanvas(self.pan1, wx.ID_ANY, self.figure) # Wx-Pylab magic ... # Make our canvas the active figure manager for pylab so that when # pylab plotting statements are executed they will operate on our # canvas and not create a new frame and canvas for display purposes. # This technique allows this application to execute code that uses # pylab stataments to generate plots and embed these plots in our # application window(s). self.fm = FigureManagerBase(canvas, self.fignum) _pylab_helpers.Gcf.set_active(self.fm) # Instantiate the matplotlib navigation toolbar and explicitly show it. mpl_toolbar = Toolbar(canvas) mpl_toolbar.Realize() # Create a vertical box sizer to manage the widgets in the main panel. sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(canvas, 1, wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border=10) sizer.Add(mpl_toolbar, 0, wx.EXPAND | wx.ALL, border=10) # Associate the sizer with its container. self.pan1.SetSizer(sizer) sizer.Fit(self.pan1)
def __init__(self, parent,config): panel1 = wx.Panel.__init__(self, parent) self.figure = Figure() self.canvas = FigureCanvasWxAgg(self, -1, self.figure) self.toolbar = Toolbar(self.canvas) # matplotlib toolbar self.toolbar.EnableTool(1,False) self.toolbar.Realize() # self.toolbar.set_active([0,1]) self.toolbar.update() 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.Refresh(eraseBackground=True)
def __init__(self, parent): wx.Panel.__init__(self, parent, -1) self.fig = Figure((5, 4), 75) self.canvas = FigureCanvasWxAgg(self, -1, self.fig) self.toolbar = Toolbar(self.canvas) # matplotlib toolbar self.toolbar.Realize() # self.toolbar.set_active([0,1]) # 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()
class PlotPanel(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent, -1) self.fig = Figure((5, 4), 75) self.canvas = FigureCanvasWxAgg(self, -1, self.fig) self.toolbar = Toolbar(self.canvas) # matplotlib toolbar self.toolbar.Realize() sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW) sizer.Add(self.toolbar, 0, wx.GROW) self.SetSizer(sizer) self.Fit() def init_plot_data(self): a = self.fig.add_subplot(111) x = npy.arange(120.0) * 2 * npy.pi / 60.0 y = npy.arange(100.0) * 2 * npy.pi / 50.0 self.x, self.y = npy.meshgrid(x, y) z = npy.sin(self.x) + npy.cos(self.y) self.im = a.imshow(z, cmap=cm.jet) # , interpolation='nearest') zmax = npy.amax(z) - ERR_TOL ymax_i, xmax_i = npy.nonzero(z >= zmax) if self.im.origin == "upper": ymax_i = z.shape[0] - ymax_i self.lines = a.plot(xmax_i, ymax_i, "ko") self.toolbar.update() # Not sure why this is needed - ADS def GetToolBar(self): return self.toolbar def OnWhiz(self, evt): self.x += npy.pi / 15 self.y += npy.pi / 20 z = npy.sin(self.x) + npy.cos(self.y) self.im.set_array(z) zmax = npy.amax(z) - ERR_TOL ymax_i, xmax_i = npy.nonzero(z >= zmax) if self.im.origin == "upper": ymax_i = z.shape[0] - ymax_i self.lines[0].set_data(xmax_i, ymax_i) self.canvas.draw() def onEraseBackground(self, evt): pass
def __init__(self, parent, id = -1, dpi = None, **kwargs): wx.Panel.__init__(self, parent, id=id, **kwargs) self.figure = mpl.figure.Figure(dpi=dpi, figsize=(2,2)) self.canvas = Canvas(self, -1, self.figure) self.toolbar = Toolbar(self.canvas) self.toolbar.Realize() sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.canvas,1,wx.EXPAND) sizer.Add(self.toolbar, 0 , wx.LEFT | wx.EXPAND) self.SetSizer(sizer)
def __init__(self, parent): wx.Panel.__init__(self, parent, -1) self.fig = Figure((5,4), 75) self.canvas = FigureCanvasWxAgg(self, -1, self.fig) self.toolbar = Toolbar(self.canvas) #matplotlib toolbar self.toolbar.Realize() sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.canvas, 1, wx.LEFT|wx.TOP|wx.GROW) sizer.Add(self.toolbar, 0, wx.GROW) self.SetSizer(sizer) self.Fit()
def __init__(self, parent, fig, id=-1, dpi=None, **kwargs): wx.Panel.__init__(self, parent, id=id, **kwargs) fig.set_figheight(2) fig.set_figwidth(2) self.canvas = Canvas(self, -1, fig) self.toolbar = Toolbar(self.canvas) self.toolbar.Realize() sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.canvas, 1, wx.EXPAND) sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND) self.SetSizer(sizer)
def __init__(self,parent): wx.Panel.__init__(self,parent,-1) self.fig = Figure(figsize=(2,2)) self.canvas = FigCanvas(self,-1,self.fig) self.toolbar = Toolbar(self.canvas) self.toolbar.Realize() sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.canvas, 1, wx.EXPAND) sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND) self.SetSizer(sizer)
def init_plot_panel(self): """Initializes the plotting panel of the SimulationPage.""" INTRO_TEXT = "Phase Reconstruction and Inversion Using Simulated Data:" # Instantiate a figure object that will contain our plots. figure = Figure() # Initialize the figure canvas, mapping the figure object to the plot # engine backend. canvas = FigureCanvas(self.pan2, wx.ID_ANY, figure) # Wx-Pylab magic ... # Make our canvas the active figure manager for pylab so that when # pylab plotting statements are executed they will operate on our # canvas and not create a new frame and canvas for display purposes. # This technique allows this application to execute code that uses # pylab stataments to generate plots and embed these plots in our # application window(s). self.fm = FigureManagerBase(canvas, self.fignum) _pylab_helpers.Gcf.set_active(self.fm) # Instantiate the matplotlib navigation toolbar and explicitly show it. mpl_toolbar = Toolbar(canvas) mpl_toolbar.Realize() # Display a title above the plots. self.pan2_intro_text = INTRO_TEXT self.pan2_intro = wx.StaticText(self.pan2, wx.ID_ANY, label=INTRO_TEXT) font = self.pan2_intro.GetFont() font.SetPointSize(font.GetPointSize() + 1) font.SetWeight(wx.BOLD) self.pan2_intro.SetFont(font) # Create a progress bar to be displayed during a lengthy computation. self.pan2_gauge = WorkInProgress(self.pan2) self.pan2_gauge.Show(False) # Create a horizontal box sizer to hold the title and progress bar. hbox1_sizer = wx.BoxSizer(wx.HORIZONTAL) hbox1_sizer.Add(self.pan2_intro, 0, wx.ALIGN_CENTER_VERTICAL) hbox1_sizer.Add((10, 25), 1) # stretchable whitespace hbox1_sizer.Add(self.pan2_gauge, 0) # Create a vertical box sizer to manage the widgets in the main panel. sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(hbox1_sizer, 0, wx.EXPAND|wx.ALL, border=10) sizer.Add(canvas, 1, wx.EXPAND|wx.LEFT|wx.RIGHT, border=10) sizer.Add(mpl_toolbar, 0, wx.EXPAND|wx.ALL, border=10) # Associate the sizer with its container. self.pan2.SetSizer(sizer) sizer.Fit(self.pan2)
def __init__(self, parent, id, size=(4, 3), dpi=75, **kwds): wx.Panel.__init__(self, parent, id) import wxmpl.wxmpl as wxmpl self.canvas = wxmpl.PlotPanel(self, -1, size=size, dpi=dpi) self.figure = self.canvas.figure self.figure.add_subplot(111) 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) # add a spacer between figure and toolbar sizer.AddSpacer((10, 10)) # Best to allow the toolbar to resize! sizer.Add(self.toolbar, 0, wx.GROW) self.SetSizer(sizer) self.sizer = sizer self.SetAutoLayout(1) sizer.Fit(self) #FigureCanvasWxAgg.__init__(self, parent, id, Figure(size, dpi) ) from histogram.plotter import HistogramMplPlotter as HMP self.plotter = HMP(self.figure) shelf = self.getShelf() shelf.update({"plot": Plot(self)}) return
def __init__(self, parent, figure, id=-1, **kwargs): wx.Panel.__init__(self, parent, id=id, **kwargs) self.figure = figure self.canvas = Canvas(self, -1, self.figure) self.toolbar = Toolbar(self.canvas) self.toolbar.Realize() sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.canvas,1,wx.EXPAND) sizer.Add(self.toolbar, 0 , wx.LEFT | wx.EXPAND) self.SetSizer(sizer)
def __init__(self, parent): wxPanel.__init__(self, parent, -1) self.fig = Figure((5,4), 75) self.canvas = FigureCanvasWxAgg(self, -1, self.fig) self.toolbar = Toolbar(self.canvas) #matplotlib toolbar self.toolbar.Realize() #self.toolbar.set_active([0,1]) # 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 __init__(self, *args, **kw): wx.Panel.__init__(self, *args, **kw) figure = Figure(figsize=(1, 1), dpi=72) canvas = FigureCanvas(self, wx.ID_ANY, figure) self.pylab_figure = PylabFigure(canvas) # Instantiate the matplotlib navigation toolbar and explicitly show it. mpl_toolbar = Toolbar(canvas) mpl_toolbar.Realize() # Create a vertical box sizer to manage the widgets in the main panel. sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(canvas, 1, wx.EXPAND | wx.LEFT | wx.RIGHT, border=0) sizer.Add(mpl_toolbar, 0, wx.EXPAND | wx.ALL, border=0) # Associate the sizer with its container. self.SetSizer(sizer) sizer.Fit(self)
def __init__(self, *args, **kw): wx.Panel.__init__(self, *args, **kw) # Can specify name on if 'title' in kw: self.title = kw['title'] # Instantiate a figure object that will contain our plots. figure = Figure(figsize=(1, 1), dpi=72) # Initialize the figure canvas, mapping the figure object to the plot # engine backend. canvas = FigureCanvas(self, wx.ID_ANY, figure) # Wx-Pylab magic ... # Make our canvas an active figure manager for pylab so that when # pylab plotting statements are executed they will operate on our # canvas and not create a new frame and canvas for display purposes. # This technique allows this application to execute code that uses # pylab stataments to generate plots and embed these plots in our # application window(s). Use _activate_figure() to set. self.pylab_interface = EmbeddedPylab(canvas) # Instantiate the matplotlib navigation toolbar and explicitly show it. mpl_toolbar = Toolbar(canvas) mpl_toolbar.Realize() # Create a vertical box sizer to manage the widgets in the main panel. sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(canvas, 1, wx.EXPAND | wx.LEFT | wx.RIGHT, border=0) sizer.Add(mpl_toolbar, 0, wx.EXPAND | wx.ALL, border=0) # Associate the sizer with its container. self.SetSizer(sizer) sizer.Fit(self) self._calculating = False self._need_plot = self._need_newmodel = False self.Bind(wx.EVT_SHOW, self.OnShow) self.plot_state = None self.model = None '''
def add_toolbar(self): self.toolbar = Toolbar(self.canvas) self.toolbar.Realize() if wx.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(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__(self, parent, id=-1, dpi=None, toolbar=True, **kwargs): wx.Panel.__init__(self, parent, id=id, **kwargs) self.figure = matplotlib.figure.Figure(dpi=dpi, facecolor=(0.9, 0.9, 0.9, 1)) self.canvas = Canvas(self, -1, self.figure) self.plot_sizer = wx.BoxSizer(wx.VERTICAL) if toolbar: self.toolbar = Toolbar(self.canvas) self.toolbar.Realize() self.plot_sizer.Add(self.toolbar, 0, wx.ALIGN_CENTER_VERTICAL | wx.EXPAND) self.plot_sizer.Add(self.canvas, 1, wx.EXPAND) self.sizer = wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.plot_sizer, 1, wx.EXPAND) self.SetSizer(self.sizer) self.setup_events()
def __init__(self, parent): wx.Panel.__init__(self, parent, style=wx.BORDER_SUNKEN) self.sliceFigure = Figure(frameon=True, figsize=(2, 3)) self.sliceFigure.set_facecolor('.82') self.sliceCanvas = FigureCanvas(self, -1, self.sliceFigure) self.sliceCanvas.SetAutoLayout(False) self.box = Toolbar(self.sliceCanvas) self.box.Hide() self.box.zoom() self.fm = FigureManagerBase(self.sliceCanvas, 1) _pylab_helpers.Gcf.set_active(self.fm) self.sliceAxis = self.sliceFigure.add_axes([0.1, 0.2, 0.8, 0.7]) sliceSizer = wx.BoxSizer(wx.VERTICAL) sliceSizer.Add(self.sliceCanvas, 1, wx.EXPAND | wx.RIGHT | wx.LEFT, border=1) self.SetSizer(sliceSizer) return
class Panel_Plotting_Helper(wx.Panel): def __init__(self, parent): w, h = parent.GetSize() wx.Panel.__init__(self, parent=parent, size=(w, 0.7*h), style=wx.SUNKEN_BORDER) self.parent = parent self.legends = [] self.legendpos = [0.5, 1] self.fig = Figure(figsize=(12, 6), dpi=90) # create a figure size 8x6 inches, 80 dots per inches self.splts = [] self.canvas = FigureCanvasWxAgg(self, -1, self.fig) self.toolbar = Toolbar(self.canvas) # matplotlib toolbar # additional toolbar status_txt = wx.StaticText(self.toolbar, label=' Status on hover: ', pos=(230, 7), \ size=(100, 17)) self.status = wx.TextCtrl(self.toolbar, pos=(330,4), size=(300, 22), \ style=wx.TE_READONLY) self.toolbar.Realize() self.figw, self.figh = self.fig.get_window_extent().width, self.fig.get_window_extent().height sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.toolbar, 0, wx.GROW) sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW) self.SetSizer(sizer) self.box_width_fraction = 1.0 self.box_height_fraction = 0.9 self.lines = [] self.lined = dict() self.draggableList = ['Text', 'Legend'] # print(self.toolbar.GetBackgroundColour()) self.fig.canvas.mpl_connect('resize_event', self.squeeze_legend) self.fig.canvas.mpl_connect('pick_event', self.on_pick) self.fig.canvas.mpl_connect('motion_notify_event', self.on_motion) self.fig.canvas.mpl_connect('figure_leave_event', self.on_leave) def plot_J(self, J, theta, format, r, count): index = count%3 + 3 self.splts[index].plot(np.arange(len(J)), J, color=format['color'], linewidth=format['linewidth'], linestyle=format['linestyle'], label=format['label'], picker=True) self.splts[index].set_xlabel("Number of Iteration", fontsize=FONT_SIZE) self.splts[index].set_ylabel("Cost value", fontsize = FONT_SIZE) self.set_ticks(self.splts[index], np.arange(len(J)), J) comment = r + ': [\n' for t in theta: comment += ' ' + str(t) + '\n' comment += ']' props = dict(boxstyle='round', facecolor='wheat', alpha=0.5) annotate = self.splts[index].annotate(comment, xy=(len(J)-1, J[len(J)-1]), xytext=(len(J)/2, (J[0]+J[len(J)-1])/2), \ arrowprops=dict(facecolor='black', shrink=0.05), bbox=props, fontsize=FONT_SIZE, picker=True) annotate.draggable(True) def plot_data_gradient_descent(self, X, y, format): print("Plotting data ...") for i in range(int(round(len(self.splts)/2))): self.plot_data(self.splts[i], X, y, format) self.update_canvas() def plot_data_minimize_cost_function(self, X, y, format): print("Plotting data ...") for i in range(int(round((len(self.splts)+1)/2))): self.plot_data(self.splts[i], X, y, format) self.update_canvas() def plot_data(self, splt, X, y, format): line, = splt.plot(X, y, 'ro', color=format['color'], label=format['label'], picker=True) self.set_ticks(splt, X, y) self.lines.append(line) splt.set_xlabel("X1", fontsize=FONT_SIZE) splt.set_ylabel("Y", fontsize=FONT_SIZE) def set_ticks(self, splt, X, y): xticks = self.make_ticks(X) yticks = self.make_ticks(y) splt.set_xticks(xticks) splt.set_yticks(yticks) for tick in splt.get_xticklabels(): tick.set_rotation(45) tick.set_fontsize(FONT_SIZE) for tick in splt.get_yticklabels(): tick.set_rotation(45) tick.set_fontsize(FONT_SIZE) def plot_all_gradient_descent(self, object): print("Plotting Linear-Regression (Gradient Descent) and J-Convergence ...") count = 0 for r in object: c = self.random_color() self.splts[count].plot(object[r]['data']['x'], object[r]['data']['y'], color=c, linestyle="-", label="Linear Regression (alpha="+r+")", picker=True) self.set_ticks(self.splts[count], object[r]['data']['x'], object[r]['data']['y']) self.plot_J(object[r]['J_history'], object[r]['theta'], {"color": c, "linewidth": 5, "linestyle": "-", "label": "Convergence of J"}, r, count) count += 1 self.show_legend() self.update_canvas() def plot_all_minimize_cost_function(self, object): print("Plotting Linear-Regression (Normal Equation) ...") count = 0 for r in object: c = self.random_color() line, = self.splts[count].plot(object[r]['data']['x'], object[r]['data']['y'], color=c, linestyle="-", label="Linear Regression (Normal Equation)", picker=True) self.lines.append(line) self.set_ticks(self.splts[count], object[r]['data']['x'], object[r]['data']['y']) comment = 'Theta: [\n' for t in object[r]['theta']: comment += ' ' + str(t[0]) + '\n' comment += ']' # place a text box in upper left in axes coords props = dict(boxstyle='round', facecolor='wheat', alpha=0.5) annotate = self.splts[count].annotate(comment, xy=(min(object[r]['data']['x']), max(object[r]['data']['y'])), \ xytext=(min(object[r]['data']['x']), max(object[r]['data']['y'])), bbox=props, fontsize=FONT_SIZE, picker=True) annotate.draggable(True) count += 1 self.show_legend() self.update_canvas() def show_legend(self): self.legends = [] for i in range(len(self.splts)): splt = self.splts[i] # Shrink current axis by 20% box = splt.get_position() splt.set_position([box.x0, box.y0, box.width * self.box_width_fraction, \ box.height * self.box_height_fraction]) # Now add the legend with some customizations. legend = splt.legend(loc='upper center', ncol=1, fancybox=True, shadow=True) legend.set_bbox_to_anchor((self.legendpos[0], \ self.legendpos[1] + legend.get_window_extent().height/self.figh + 0.25)) legend.figure.canvas.mpl_connect('pick_event', self.on_pick) legend.draggable(True) # lined = dict() # for legline, origline in zip(legend.get_lines(), self.lines): # legline.set_picker(5) # 5 pts tolerance # self.lined[legline] = origline self.legends.append(legend) if legend: # The frame is matplotlib.patches.Rectangle instance surrounding the legend. frame = legend.get_frame() frame.set_facecolor('0.90') # Set the fontsize for label in legend.get_texts(): label.set_fontsize(FONT_SIZE) for label in legend.get_lines(): label.set_linewidth(0.75) # the legend line width else: pass def make_ticks(self, data): minn = np.min(data) maxx = np.max(data) return np.arange(minn, maxx, int((maxx-minn)/3)) def squeeze_legend(self, evt): new_height = self.fig.get_window_extent().height self.box_height_fraction = new_height / self.figh self.figh = new_height new_width = self.fig.get_window_extent().width self.box_width_fraction = new_width / self.figw self.figw = new_width self.show_legend() self.update_canvas() def on_pick(self, evt): if isinstance(evt.artist, Text): # box_points = evt.artist.get_position() global TEXT_DRAGGABLE TEXT_DRAGGABLE = not TEXT_DRAGGABLE evt.artist.draggable(TEXT_DRAGGABLE) elif isinstance(evt.artist, Line2D): # box_points = evt.artist.get_clip_box() pass elif isinstance(evt.artist, Legend): # box_points = evt.artist.get_clip_box() global LEGEND_DRAGGABLE LEGEND_DRAGGABLE = not LEGEND_DRAGGABLE evt.artist.draggable(LEGEND_DRAGGABLE) else: print(evt.artist) pass # print("You've clicked on a bar with coords:\n %r, %r" % (box_points , evt.artist)) self.update_canvas() def on_motion(self, mouseevt): w, h = self.canvas.GetSize() if mouseevt.x in range(0, int(w+1)) and mouseevt.y in range(0, int(h+1)): self.status.SetValue('Click on %r for dragging On/Off' % self.draggableList) else: pass def on_leave(self, mouseevt): self.status.SetValue('') def make_figure(self, type): self.fig.clf() if type == 'gd': pass elif type == 'mc': gs = GridSpec(1, 1) gs.update(hspace=0.7, wspace=0.8) self.splts = [self.fig.add_subplot(gs[int(i/3), int(i%3)]) for i in range(1*1)] # grid nxn else: pass def random_color(self): rgbl = [0, random.random(), random.random()] return tuple(rgbl) def update_canvas(self): self.fig.canvas.draw() self.canvas.Refresh() self.toolbar.update()
class PlotPanel(wx.Panel): """This example is from something I found on the matplotlib webpage. They combined an embedded mpl plot with the wxPython xrc approach. They basically create a wx.Panel placeholder in the xrc file. See data_vis_gui.py for an example of using this class. Your really don't need anything other than the __init__ method. After that, just grab :py:attr:`self.fig` and use the matplotlib methods of the figure instance (the object-oriented API, not pylab).""" def __init__(self, parent, fig_size=(8,6)): wx.Panel.__init__(self, parent, -1) self.fig = Figure(fig_size, 100) self.canvas = FigureCanvasWxAgg(self, -1, self.fig) self.toolbar = Toolbar(self.canvas) #matplotlib toolbar self.toolbar.Realize() #self.toolbar.set_active([0,1]) # 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 init_plot_data(self): """This just creates the starting graph.""" a = self.fig.add_subplot(111) t = np.arange(0,1,0.01) y = np.sin(2*np.pi*t) self.lines = a.plot(t,y) self.ax = a self.toolbar.update() # Not sure why this is needed - ADS def change_plot(self): """This is just a method to show I can update the plot from a program. It doesn't really do anything else useful. It serves as an example of clearing the axis, plotting something, and refreshing the graph.""" self.ax.clear() t = np.arange(0,1,0.01) y2 = np.cos(2*np.pi*t) self.ax.plot(t,y2) self.canvas.draw() def GetToolBar(self): """This is from the example; I don't know what it does.""" # You will need to override GetToolBar if you are using an # unmanaged toolbar in your frame return self.toolbar def onEraseBackground(self, evt): """I don't know what this does either (based on the comment below, I guess it prevents flicker).""" # this is supposed to prevent redraw flicker on some X servers... pass
def __init__(self,parent,id): wx.Panel.__init__(self,parent,id,style=wx.BORDER_SUNKEN) self.scale_collection = array([]) self.real_data = flipud(parent.data.T) self.parent = parent self.raw_data = flipud(parent.model.T) self.scaled_data = copy(self.raw_data) self.plot_extent = parent.plot_extent lower_lim = amin(self.scaled_data[nonzero(self.scaled_data.real)]) finite_real = self.real_data[isfinite(self.real_data)] finite_real = finite_real[nonzero(finite_real)] #Hack #self.vmin = amin(log(finite_real.real)) self.vmax = amax(log(finite_real.real)) self.vmin = self.vmax - 12 self.figure = Figure() self.axes = self.figure.add_subplot(211) self.canvas = FigureCanvas(self, -1, self.figure) fm = FigureManagerBase(self.canvas, 0) _pylab_helpers.Gcf.set_active(fm) # Instantiate the matplotlib navigation toolbar and explicitly show it. mpl_toolbar = Toolbar(self.canvas) mpl_toolbar.Realize() self.myImage = self.showImage(log(abs(self.scaled_data)),self.axes) self.modelColor = self.figure.colorbar(self.myImage) self.dataaxes = self.figure.add_subplot(212) self.datamyImage = self.showImage(log(self.real_data),self.dataaxes) self.dataColor = self.figure.colorbar(self.datamyImage) self.scale = wx.TextCtrl(self,-1) self.updateButton = wx.Button(self,-1,'UPDATE') self.resetButton = wx.Button(self,-1,'RESET') self.areaScaleButton = wx.Button(self,-1,'AUTO SCALE') BotSize = wx.BoxSizer(wx.HORIZONTAL) vertSize = wx.BoxSizer(wx.VERTICAL) BotSize.Add(self.scale,0,wx.LEFT|wx.RIGHT,border = 5) BotSize.Add(self.updateButton,0,wx.LEFT|wx.RIGHT,border = 5) BotSize.Add(self.resetButton,0,wx.LEFT|wx.RIGHT,border = 5) BotSize.Add(self.areaScaleButton,0,wx.LEFT|wx.RIGHT, border = 5) vertSize.Add(self.canvas,-1,wx.EXPAND) vertSize.Add(mpl_toolbar,0) vertSize.Add(BotSize,0,wx.ALL, border = 10) self.SetSizer(vertSize) self.Fit() self.updateButton.Bind(wx.EVT_BUTTON,self.update) self.resetButton.Bind(wx.EVT_BUTTON,self.reset) self.areaScaleButton.Bind(wx.EVT_BUTTON,self.autoScale)
class Panel_Plotting_Helper(wx.Panel): def __init__(self, parent): w, h = parent.GetSize() wx.Panel.__init__(self, parent=parent, size=(w, 0.7 * h), style=wx.SUNKEN_BORDER) self.parent = parent self.legends = [] self.legendpos = [0.5, 1] self.fig = Figure( figsize=(12, 6), dpi=90) # create a figure size 8x6 inches, 80 dots per inches self.splts = [] self.canvas = FigureCanvasWxAgg(self, -1, self.fig) self.toolbar = Toolbar(self.canvas) # matplotlib toolbar # additional toolbar status_txt = wx.StaticText(self.toolbar, label=' Status on hover: ', pos=(230, 7), \ size=(100, 17)) self.status = wx.TextCtrl(self.toolbar, pos=(330,4), size=(300, 22), \ style=wx.TE_READONLY) self.toolbar.Realize() self.figw, self.figh = self.fig.get_window_extent( ).width, self.fig.get_window_extent().height sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.toolbar, 0, wx.GROW) sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW) self.SetSizer(sizer) self.box_width_fraction = 1.0 self.box_height_fraction = 0.9 self.lines = [] self.lined = dict() self.draggableList = ['Text', 'Legend'] # print(self.toolbar.GetBackgroundColour()) self.fig.canvas.mpl_connect('resize_event', self.squeeze_legend) self.fig.canvas.mpl_connect('pick_event', self.on_pick) self.fig.canvas.mpl_connect('motion_notify_event', self.on_motion) self.fig.canvas.mpl_connect('figure_leave_event', self.on_leave) def plot_J(self, J, theta, format, r, count): index = count % 3 + 3 self.splts[index].plot(np.arange(len(J)), J, color=format['color'], linewidth=format['linewidth'], linestyle=format['linestyle'], label=format['label'], picker=True) self.splts[index].set_xlabel("Number of Iteration", fontsize=FONT_SIZE) self.splts[index].set_ylabel("Cost value", fontsize=FONT_SIZE) self.set_ticks(self.splts[index], np.arange(len(J)), J) comment = r + ': [\n' for t in theta: comment += ' ' + str(t) + '\n' comment += ']' props = dict(boxstyle='round', facecolor='wheat', alpha=0.5) annotate = self.splts[index].annotate(comment, xy=(len(J)-1, J[len(J)-1]), xytext=(len(J)/2, (J[0]+J[len(J)-1])/2), \ arrowprops=dict(facecolor='black', shrink=0.05), bbox=props, fontsize=FONT_SIZE, picker=True) annotate.draggable(True) def plot_data_gradient_descent(self, X, y, format): print("Plotting data ...") for i in range(int(round(len(self.splts) / 2))): self.plot_data(self.splts[i], X, y, format) self.update_canvas() def plot_data_normal_equation(self, X, y, format): print("Plotting data ...") for i in range(int(round((len(self.splts) + 1) / 2))): self.plot_data(self.splts[i], X, y, format) self.update_canvas() def plot_data(self, splt, X, y, format): line, = splt.plot(X, y, 'ro', color=format['color'], label=format['label'], picker=True) self.set_ticks(splt, X, y) self.lines.append(line) splt.set_xlabel("X1", fontsize=FONT_SIZE) splt.set_ylabel("Y", fontsize=FONT_SIZE) def set_ticks(self, splt, X, y): xticks = self.make_ticks(X) yticks = self.make_ticks(y) splt.set_xticks(xticks) splt.set_yticks(yticks) for tick in splt.get_xticklabels(): tick.set_rotation(45) tick.set_fontsize(FONT_SIZE) for tick in splt.get_yticklabels(): tick.set_rotation(45) tick.set_fontsize(FONT_SIZE) def plot_all_gradient_descent(self, object): print( "Plotting Linear-Regression (Gradient Descent) and J-Convergence ..." ) count = 0 for r in object: c = self.random_color() self.splts[count].plot(object[r]['data']['x'], object[r]['data']['y'], color=c, linestyle="-", label="Linear Regression (alpha=" + r + ")", picker=True) self.set_ticks(self.splts[count], object[r]['data']['x'], object[r]['data']['y']) self.plot_J( object[r]['J_history'], object[r]['theta'], { "color": c, "linewidth": 5, "linestyle": "-", "label": "Convergence of J" }, r, count) count += 1 self.show_legend() self.update_canvas() def plot_all_normal_equation(self, object): print("Plotting Linear-Regression (Normal Equation) ...") count = 0 for r in object: c = self.random_color() line, = self.splts[count].plot( object[r]['data']['x'], object[r]['data']['y'], color=c, linestyle="-", label="Linear Regression (Normal Equation)", picker=True) self.lines.append(line) self.set_ticks(self.splts[count], object[r]['data']['x'], object[r]['data']['y']) comment = 'Theta: [\n' for t in object[r]['theta']: comment += ' ' + str(t[0]) + '\n' comment += ']' # place a text box in upper left in axes coords props = dict(boxstyle='round', facecolor='wheat', alpha=0.5) annotate = self.splts[count].annotate(comment, xy=(min(object[r]['data']['x']), max(object[r]['data']['y'])), \ xytext=(min(object[r]['data']['x']), max(object[r]['data']['y'])), bbox=props, fontsize=FONT_SIZE, picker=True) annotate.draggable(True) count += 1 self.show_legend() self.update_canvas() def show_legend(self): self.legends = [] for i in range(len(self.splts)): splt = self.splts[i] # Shrink current axis by 20% box = splt.get_position() splt.set_position([box.x0, box.y0, box.width * self.box_width_fraction, \ box.height * self.box_height_fraction]) # Now add the legend with some customizations. legend = splt.legend(loc='upper center', ncol=1, fancybox=True, shadow=True) legend.set_bbox_to_anchor((self.legendpos[0], \ self.legendpos[1] + legend.get_window_extent().height/self.figh + 0.25)) legend.figure.canvas.mpl_connect('pick_event', self.on_pick) legend.draggable(True) # lined = dict() # for legline, origline in zip(legend.get_lines(), self.lines): # legline.set_picker(5) # 5 pts tolerance # self.lined[legline] = origline self.legends.append(legend) if legend: # The frame is matplotlib.patches.Rectangle instance surrounding the legend. frame = legend.get_frame() frame.set_facecolor('0.90') # Set the fontsize for label in legend.get_texts(): label.set_fontsize(FONT_SIZE) for label in legend.get_lines(): label.set_linewidth(0.75) # the legend line width else: pass def make_ticks(self, data): minn = np.min(data) maxx = np.max(data) return np.arange(minn, maxx, int((maxx - minn) / 3)) def squeeze_legend(self, evt): new_height = self.fig.get_window_extent().height self.box_height_fraction = new_height / self.figh self.figh = new_height new_width = self.fig.get_window_extent().width self.box_width_fraction = new_width / self.figw self.figw = new_width self.show_legend() self.update_canvas() def on_pick(self, evt): if isinstance(evt.artist, Text): # box_points = evt.artist.get_position() global TEXT_DRAGGABLE TEXT_DRAGGABLE = not TEXT_DRAGGABLE evt.artist.draggable(TEXT_DRAGGABLE) elif isinstance(evt.artist, Line2D): # box_points = evt.artist.get_clip_box() pass elif isinstance(evt.artist, Legend): # box_points = evt.artist.get_clip_box() global LEGEND_DRAGGABLE LEGEND_DRAGGABLE = not LEGEND_DRAGGABLE evt.artist.draggable(LEGEND_DRAGGABLE) else: print(evt.artist) pass # print("You've clicked on a bar with coords:\n %r, %r" % (box_points , evt.artist)) self.update_canvas() def on_motion(self, mouseevt): w, h = self.canvas.GetSize() if mouseevt.x in range(0, int(w + 1)) and mouseevt.y in range( 0, int(h + 1)): self.status.SetValue('Click on %r for dragging On/Off' % self.draggableList) else: pass def on_leave(self, mouseevt): self.status.SetValue('') def make_figure(self, type): self.fig.clf() if type == 'gd': gs = GridSpec(2, 3) gs.update(hspace=0.7, wspace=0.8) self.splts = [ self.fig.add_subplot(gs[int(i / 3), int(i % 3)]) for i in range(2 * 3) ] # grid nxn elif type == 'ne': gs = GridSpec(1, 1) gs.update(hspace=0.7, wspace=0.8) self.splts = [ self.fig.add_subplot(gs[int(i / 3), int(i % 3)]) for i in range(1 * 1) ] # grid nxn else: pass def random_color(self): rgbl = [0, random.random(), random.random()] return tuple(rgbl) def update_canvas(self): self.fig.canvas.draw() self.canvas.Refresh() self.toolbar.update()
def __init__(self,parent,title): wx.Frame.__init__(self,None,title=title,size=(1200,900)) self.SaveEachImage = False ## initialise camera self.camera = MyCamera() # if the window is closed, exit self.Bind(wx.EVT_CLOSE,self.OnExit) # main panel for adding everything to panel = wx.Panel(self) panel.SetBackgroundColour(wx.Colour(230,230,230)) ## Statusbar at the bottom of the window #self.CreateStatusBar() - not used in the end, but could add live plot coordinates, tooltips or something similar # Plot panel - canvas and toolbar self.fig = plt.figure(1,(4.5/2,3./2),80,facecolor=(230./255,230./255,230./255)) self.fig.subplots_adjust(left=0.08, bottom=0.07, right=0.97, top=0.97,wspace=0.11,hspace=0.15) self.ax_im = plt.subplot2grid((12,6), (0,0),rowspan=6,colspan=5) self.axX = plt.subplot2grid((12,6), (6,0),colspan=5,sharex=self.ax_im) self.axY = plt.subplot2grid((12,6), (0,5),rowspan=6,sharey=self.ax_im) self.axXwidth = plt.subplot2grid((12,6), (8,0), rowspan=2,colspan=6) self.axYwidth = plt.subplot2grid((12,6), (10,0), rowspan=2,colspan=6,sharex=self.axXwidth) # Axis labels self.axX.set_xlabel('CCD x (mm)') self.ax_im.set_ylabel('CCD y (mm)') self.axYwidth.set_xlabel('Translation stage position (mm)') self.axXwidth.set_ylabel('Wx ($\mu$m)') self.axYwidth.set_ylabel('Wy ($\mu$m)') # Turn off unneeded labels plt.setp(self.ax_im.get_xticklabels(),visible=False) plt.setp(self.axY.get_yticklabels(),visible=False) plt.setp(self.axXwidth.get_xticklabels(),visible=False) ## Create initial dummy image to be updated with camera data later. ## Take x and y partial sums and add these to the plot too CM = cm_new.inferno #cm.PuOr_r #gist_heat #afmhot # binary_r im_array = np.zeros((300,400)) self.im_obj = self.ax_im.imshow(im_array,cmap=CM,aspect='auto', extent=self.camera.extent, interpolation='none', vmin = 0, vmax = 1023) #10-bit raw self.xfitdata = [[],[]] self.yfitdata = [[],[]] self.xslice, = self.axX.plot(np.linspace(0,3.67,400),im_array.sum(axis=0),'o',color=d_purple,ms=4,mec=d_purple,mfc='w') self.yslice, = self.axY.plot(im_array.sum(axis=1),np.linspace(0,2.74,300),'o',color=d_purple,ms=4,mec=d_purple,mfc='w') self.xfit, = self.axX.plot(np.linspace(0,3.67,400),np.zeros(400),'k--',lw=2) self.yfit, = self.axY.plot(np.zeros(300), np.linspace(0,2.74,300),'k--',lw=2) self.axX.set_xlim(0,3.67) self.axY.set_ylim(0,2.74) # Add dummy data to the width plots to be updated later (data and fit lines) self.xposdata = [] self.xwidthdata = [] self.yposdata = [] self.ywidthdata = [] self.xwidtherr = [] self.ywidtherr = [] self.xfitparams = [1,1,1] self.xfiterrs = [0,0,0] self.yfitparams = [1,1,1] self.yfiterrs = [0,0,0] self.xwfit, = self.axXwidth.plot([0],[0],'k-',lw=2) self.ywfit, = self.axYwidth.plot([0],[0],'k-',lw=2) self.xwline, self.xwcaplines, self.xwbarlines = \ self.axXwidth.errorbar([-1],[0],yerr=[0.1],linestyle='None', ms=5,marker='o',mec=d_purple,mfc='w',mew=2,color='k',lw=1.5,capsize=0) self.ywline, self.ywcaplines, self.ywbarlines = \ self.axYwidth.errorbar([-1],[0],yerr=[0.1],linestyle='None', ms=5,marker='o',mec=d_purple,mfc='w',mew=2,color='k',lw=1.5,capsize=0) self.axXwidth.set_xlim(0,25) self.axYwidth.set_xlim(0,25) self.canvas = FigureCanvasWxAgg(panel, wx.ID_ANY, self.fig) self.toolbar = Toolbar(self.canvas) #matplotlib toolbar (pan, zoom, save etc) # Plot text self.imagefitparams = [0,0,0,0] self.xfit_text = self.fig.text(0.85,0.48,r'$w_x =$ '+str(round(self.imagefitparams[0],1)) \ +r' $\pm$ '+str(round(self.imagefitparams[1],1))) self.yfit_text = self.fig.text(0.85,0.45,r'$w_y =$ '+str(round(self.imagefitparams[1],1)) \ +r' $\pm$ '+str(round(self.imagefitparams[2],1))) self.im_min = self.fig.text(0.2,0.4,'Min pixel value:' \ +str(int(self.camera.image.min()))) self.im_max = self.fig.text(0.5,0.4,'Max pixel value:'\ +str(int(self.camera.image.max()))) # Plot panel sizer: plotpanel = wx.BoxSizer(wx.VERTICAL) plotpanel.Add(self.canvas, 1, wx.LEFT|wx.RIGHT|wx.GROW,border=0) plotpanel.Add(self.toolbar, 0, wx.LEFT|wx.RIGHT|wx.EXPAND,border=0) # Standard button vertical size btnsize=30 ## Live View ImageSettingsLabel = wx.StaticText(panel,label='Image Setup',style=wx.ALIGN_LEFT) font = wx.Font(11,wx.DEFAULT, wx.NORMAL,wx.BOLD) ImageSettingsLabel.SetFont(font) self.LiveViewActive = False self.LiveViewButton = wx.ToggleButton(panel,label="Live View (off)",size=(180,30)) self.Bind(wx.EVT_TOGGLEBUTTON, lambda event: self.OnToggleLiveView(event, self.camera),self.LiveViewButton) #LiveViewRateText = wx.StaticText(panel,label="Update Delay") #LiveViewRateSlider = wx.Slider(panel, -1, 0, 0, 100, size=(120, -1)) LV_sizer = wx.BoxSizer(wx.VERTICAL) LV_sizer.Add((-1,10),0,wx.EXPAND) LV_sizer.Add(ImageSettingsLabel,0,wx.ALIGN_LEFT|wx.LEFT,border=30) LV_sizer.Add((-1,10),0,wx.EXPAND) LV_sizer.Add(wx.StaticLine(panel,-1,size=(250,1)),0,wx.ALIGN_CENTER_HORIZONTAL|wx.LEFT|wx.RIGHT,border=30) LV_sizer.Add((-1,10),0,wx.EXPAND) LV_sizer.Add(self.LiveViewButton,0,wx.ALIGN_LEFT|wx.LEFT,border=60) #LV_sizer.Add(LiveViewRateH,1,wx.EXPAND) ## Camera settings CS_sizer = wx.BoxSizer(wx.VERTICAL) CamSet = wx.Button(panel,label="Camera settings",size=(180,30)) self.Bind(wx.EVT_BUTTON,self.OnCamSet,CamSet) CS_sizer.Add(CamSet,0,wx.ALIGN_LEFT|wx.LEFT,border=60) ## Single acquisition ACQ_sizer = wx.BoxSizer(wx.VERTICAL) AcquisitionButton = wx.Button(panel,label="Analyse Single Image",size=(180,30)) self.Bind(wx.EVT_BUTTON,self.OnAcqSet,AcquisitionButton) ACQ_sizer.Add(AcquisitionButton,0,wx.ALIGN_LEFT|wx.LEFT,border=60) ACQ_sizer.Add((-1,10),0,wx.EXPAND) DarkFrame = wx.Button(panel,label="Capture Dark Frame", size=(180,30)) self.Bind(wx.EVT_BUTTON,self.OnGetDarkFrame,DarkFrame) ACQ_sizer.Add(DarkFrame,0,wx.ALIGN_LEFT|wx.LEFT,border=60) ## Scan settings Scan_sizer = wx.BoxSizer(wx.VERTICAL) ScanSettingsLabel = wx.StaticText(panel,label='Scan Setup',style=wx.ALIGN_LEFT) font = wx.Font(11,wx.DEFAULT, wx.NORMAL,wx.BOLD) ScanSettingsLabel.SetFont(font) Scan_sizer.Add(ScanSettingsLabel,0,wx.ALIGN_LEFT|wx.LEFT,border=30) Scan_sizer.Add((-1,10),0,wx.EXPAND) Scan_sizer.Add(wx.StaticLine(panel,-1,size=(250,1)),0,wx.ALIGN_CENTER_HORIZONTAL|wx.LEFT|wx.RIGHT,border=30) Scan_sizer.Add((-1,10),0,wx.EXPAND) ScanSettingsButton = wx.Button(panel,label="Translation settings",size=(180,30)) self.Bind(wx.EVT_BUTTON,self.OnScanSet,ScanSettingsButton) Scan_sizer.Add(ScanSettingsButton,0,wx.ALIGN_LEFT|wx.LEFT,border=60) Scan_sizer.Add((-1,10),0,wx.EXPAND) ScanStartStop = wx.BoxSizer(wx.HORIZONTAL) ScanStartButton = wx.Button(panel,label="Start Scan",size=(85,30)) self.Bind(wx.EVT_BUTTON,self.OnStartScan,ScanStartButton) ScanStopButton = wx.Button(panel,label="Stop Scan", size=(85,30)) self.Bind(wx.EVT_BUTTON,self.OnStopScan,ScanStopButton) ScanStartStop.Add(ScanStartButton,0,wx.LEFT,border=0) ScanStartStop.Add((10,-1),0,wx.EXPAND) ScanStartStop.Add(ScanStopButton,0,wx.EXPAND) Scan_sizer.Add(ScanStartStop,0,wx.ALIGN_LEFT|wx.LEFT,border=60) Scan_sizer.Add((-1,10),0,wx.EXPAND) ClearDataButton = wx.Button(panel,label="Clear Previous Data",size=(180,30)) self.Bind(wx.EVT_BUTTON,self.OnClearDataButton,ClearDataButton) Scan_sizer.Add(ClearDataButton,0,wx.ALIGN_LEFT|wx.LEFT,border=60) ## Post-acquisition - save fig, export data ... self.save_image = False PostAcq_sizer = wx.BoxSizer(wx.VERTICAL) PostAcqLabel = wx.StaticText(panel,label='Export options',style=wx.ALIGN_LEFT) font = wx.Font(11,wx.DEFAULT, wx.NORMAL,wx.BOLD) PostAcqLabel.SetFont(font) PostAcq_sizer.Add(PostAcqLabel,0,wx.ALIGN_LEFT|wx.LEFT,border=30) PostAcq_sizer.Add((-1,10),0,wx.EXPAND) PostAcq_sizer.Add(wx.StaticLine(panel,-1,size=(250,1)),0,wx.ALIGN_CENTER_HORIZONTAL|wx.LEFT|wx.RIGHT,border=30) PostAcq_sizer.Add((-1,10),0,wx.EXPAND) ExportDataButton = wx.Button(panel,label="Export Data as csv",size=(180,30)) self.Bind(wx.EVT_BUTTON,self.OnExport,ExportDataButton) ExportDataButton.SetToolTip(wx.ToolTip("Export width data to csv files")) ExportImageButton = wx.Button(panel,label='Export Image as pkl',size=(180,30)) self.Bind(wx.EVT_BUTTON,self.OnExportImage,ExportImageButton) ExportImageButton.SetToolTip(wx.ToolTip("Export current image as python pickled data file. \ This can be converted to 2d-csv data lataer. CAUTION - this takes a while to process!")) SaveFigButton = wx.Button(panel,label="Save 2D figure", size=(180,30)) self.Bind(wx.EVT_BUTTON,self.OnSaveFig,SaveFigButton) SaveFigButton.SetToolTip(wx.ToolTip("This does the same as the matplotlib toolbar button")) PostAcq_sizer.Add(ExportDataButton,0,wx.ALIGN_LEFT|wx.LEFT,border=60) PostAcq_sizer.Add((-1,10),0,wx.EXPAND) PostAcq_sizer.Add(ExportImageButton,0,wx.ALIGN_LEFT|wx.LEFT,border=60) #PostAcq_sizer.Add((-1,10),0,wx.EXPAND) #PostAcq_sizer.Add(Make3DplotButton,0,wx.ALIGN_LEFT|wx.LEFT,border=60) PostAcq_sizer.Add((-1,10),0,wx.EXPAND) PostAcq_sizer.Add(SaveFigButton,0,wx.ALIGN_LEFT|wx.LEFT,border=60) ## Logo jqclogo = wx.Image(os.path.join(bp_dir,'images/jqc-logo.png'),wx.BITMAP_TYPE_ANY) jqc_bmp = wx.StaticBitmap(panel,wx.ID_ANY,wx.BitmapFromImage(jqclogo),size=(191,-1)) image_sizer = wx.BoxSizer(wx.HORIZONTAL) image_sizer.Add((10,-1),1,wx.EXPAND) image_sizer.Add(jqc_bmp,0,wx.EXPAND) image_sizer.Add((10,-1),1,wx.EXPAND) ## Bottom Buttons / bar exitbutton = wx.Button(panel,wx.ID_CLOSE,size=(-1,btnsize)) self.Bind(wx.EVT_BUTTON,self.OnExit,exitbutton) AboutButton = wx.Button(panel,wx.ID_ABOUT) self.Bind(wx.EVT_BUTTON,self.OnAbout,AboutButton) shutdownbutton = wx.Button(panel,wx.ID_EXIT,label="Shutdown RPi", size=(-1,btnsize)) self.Bind(wx.EVT_BUTTON,self.OnShutdown,shutdownbutton) buttonbar = wx.BoxSizer(wx.HORIZONTAL) buttonbar.Add((20,-1),1,wx.EXPAND) buttonbar.Add(AboutButton,0,wx.RIGHT,border=20) buttonbar.Add(exitbutton,0,wx.RIGHT,border=20) buttonbar.Add(shutdownbutton,0,wx.RIGHT,border=20) ## Main sizer - do this last: place everything together and layout the entire panel ## two parts - left and right. ## left contains only the plot ## right contains all the menus/buttons etc left = wx.BoxSizer(wx.VERTICAL) left.Add(plotpanel,1,wx.EXPAND,border=5) right = wx.BoxSizer(wx.VERTICAL) right.Add((-1,40),0,wx.EXPAND) right.Add(image_sizer,0,wx.EXPAND) right.Add((-1,20),0,wx.EXPAND) right.Add(LV_sizer,0,wx.EXPAND) right.Add((-1,10),0,wx.EXPAND) right.Add(CS_sizer,0,wx.EXPAND) right.Add((-1,10),0,wx.EXPAND) right.Add(ACQ_sizer,0,wx.EXPAND) right.Add((-1,60),0,wx.EXPAND) right.Add(Scan_sizer,0,wx.EXPAND) right.Add((-1,60),0,wx.EXPAND) right.Add(PostAcq_sizer,0,wx.EXPAND) right.Add((-1,60),1,wx.EXPAND) right.Add(buttonbar,0,wx.EXPAND) right.Add((-1,10),0,wx.EXPAND) finalsizer = wx.BoxSizer(wx.HORIZONTAL) finalsizer.Add(left,1,wx.EXPAND) finalsizer.Add(wx.StaticLine(panel,-1,size=(1,-1),style=wx.LI_VERTICAL),0,wx.EXPAND) finalsizer.Add(right,0,wx.EXPAND) panel.SetSizer(finalsizer) panel.Layout() self.Center() # Initialise stepper motor self.Stepper = StepMotorControl(self) # Call stepper calibration after a small delay wx.FutureCall(500,self.TranslationStageCalibration) ## Show main window print 'Loading main window...' self.Show(True)
def __init__(self, images, parent=None, id=wx.ID_ANY, title='CellStar explorer', x=900, y=600): """ @type images: ImageRepo """ style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER | wx.MAXIMIZE_BOX | wx.MINIMIZE_BOX wx.Dialog.__init__(self, parent, id, title, style=style) self.Size = (x, y) self.figure = mpl.figure.Figure(dpi=300, figsize=(1, 1)) self.axes = self.figure.add_subplot(111) self.axes.margins(0, 0) self.canvas = Canvas(self, -1, self.figure) self.toolbar = Toolbar(self.canvas) self.toolbar.Realize() self.abort = False sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.canvas, 1, wx.EXPAND) sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND) self.SetSizer(sizer) self.layer0 = self.axes.imshow(images.image, cmap=mpl.cm.gray) def onclick_internal(event): if event.ydata is None: return print 'button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % ( event.button, event.x, event.y, event.xdata, event.ydata) if event.button != 1: self.onclick(event.button, event.xdata, event.ydata) self.figure.canvas.draw() def press_internal(event): print('press', event.key) if event.key == 'b': # abort self.EndModal(ExplorerFrame.ABORTED) if event.key in 'qwerxcv': self.layer0.remove() if event.key == 'q': # input self.layer0 = self.axes.imshow(images.image, cmap=mpl.cm.gray) elif event.key == 'w': # image clean self.layer0 = self.axes.imshow( images.image_back_difference, cmap=mpl.cm.gray) elif event.key == 'x': # image clean self.layer0 = self.axes.imshow( images.image_back_difference_blurred, cmap=mpl.cm.gray) elif event.key == 'c': # image clean self.layer0 = self.axes.imshow(images.foreground_mask, cmap=mpl.cm.gray) elif event.key == 'v': # image clean self.layer0 = self.axes.imshow(images.background_mask, cmap=mpl.cm.gray) elif event.key == 'e': # brighter self.layer0 = self.axes.imshow(images.brighter, cmap=mpl.cm.gray) elif event.key == 'r': # darker self.layer0 = self.axes.imshow(images.darker, cmap=mpl.cm.gray) self.figure.canvas.draw() else: self.press(event.key) self.figure.canvas.draw() self.figure.canvas.mpl_connect('button_press_event', onclick_internal) self.figure.canvas.mpl_connect('key_press_event', press_internal) self.Show(True)
def OnPlotBtn(self, event): print 'Plot Button Pressed' if not (self.AllOK): print 'Not ready to plot yet.' return self.t_plot_status.SetLabel(u'Not ready to plot yet :(') self.t_plot_status.SetLabel(u'Computations started') self.Update() # get only necessary data ilmin = int(self.m_text_il_min.GetValue()) ilmax = int(self.m_text_il_max.GetValue()) xlmin = int(self.m_text_xl_min.GetValue()) xlmax = int(self.m_text_xl_max.GetValue()) self.il_reverse = bool(self.m_checkBox_IL_rev.GetValue()) self.xl_reverse = bool(self.m_checkBox_XL_rev.GetValue()) ind_to_plot = ((self.xl >= xlmin) & (self.il >= ilmin) & (self.xl <= xlmax) & (self.il <= ilmax)) il = self.il[ind_to_plot] xl = self.xl[ind_to_plot] amp = self.amp[ind_to_plot] slice_stats = { 'ilmin': np.min(il), 'xlmin': np.min(xl), 'xlmax': np.max(xl), 'ilmax': np.max(il), 'dil': 1, 'dxl': 1, 'nil': ((np.max(il) - np.min(il)) / 1 + 1).astype(int), 'nxl': ((np.max(xl) - np.min(xl)) / 1 + 1).astype(int), 'aspect_ratio': float(self.m_text_il_xl_aspect.GetValue()) } self.amp_stats = { 'min': np.min(amp), 'max': np.max(amp), 'avg': np.mean(amp), 'rms': np.std(amp) } amp = amp - self.mean_amp_value datamat = self.AG_matrix_from_xyz(il, xl, amp, slice_stats) empty_points = np.isnan(datamat) datamat[empty_points] = 0 # datamat=datamat-self.mean_amp_value ilmat = np.linspace(slice_stats['ilmin'], slice_stats['ilmax'], slice_stats['nil']) xlmat = np.linspace(slice_stats['xlmin'], slice_stats['xlmax'], slice_stats['nxl']) ind_mid_il = np.floor(slice_stats['nil'] / 2).astype(int) ind_mid_xl = np.floor(slice_stats['nxl'] / 2).astype(int) self.t_plot_status.SetLabel(u'indexing complete. Starting FFT') self.Update() W_orig = np.fft.fft2(datamat) W = np.fft.fftshift(W_orig) S = abs(W) P = np.angle(W) self.t_plot_status.SetLabel(u'FFT complete') self.Update() damp_f = np.ones_like(S) pres_f = np.ones_like(S) # Set Gaussian Parameeres if not self.m_textGauIL.GetValue(): # est_f_il = np.floor(ind_mid_il/3).astype(int) est_f_il = 0 self.m_textGauIL.SetValue(str(est_f_il)) print 'No GauIL specified, autoset: ' + str(est_f_il) else: est_f_il = float(self.m_textGauIL.GetValue()) if not self.m_textGauXL.GetValue(): #check whether field is empty # est_f_xl=np.floor(ind_mid_xl/3).astype(int) est_f_xl = 0 self.m_textGauXL.SetValue(str(est_f_xl)) print 'No GauXL specified, autoset: ' + str(est_f_xl) else: est_f_xl = float(self.m_textGauXL.GetValue()) if not self.m_textGauILSize.GetValue(): #check whether field is empty stdil = np.floor(0.005 * slice_stats['nxl']).astype(int) self.m_textGauILSize.SetValue(str(stdil)) print 'No size Il specified, autoset: ' + str(stdil) else: stdil = float(self.m_textGauILSize.GetValue()) if not self.m_textGauXLSize.GetValue(): #check whether field is empty stdxl = np.floor(0.005 * slice_stats['nil']).astype(int) self.m_textGauXLSize.SetValue(str(stdxl)) print 'No SizeXl specified, autoset: ' + str(stdxl) else: stdxl = float(self.m_textGauXLSize.GetValue()) if not self.m_textGauILWid.GetValue(): #check whether field is empty wid_il = np.floor(slice_stats['nil']).astype(int) self.m_textGauILWid.SetValue(str(wid_il)) print 'No size Il specified, autoset: ' + str(wid_il) else: wid_il = float(self.m_textGauILWid.GetValue()) if not self.m_textGauXLWid.GetValue(): #check whether field is empty wid_xl = np.floor(slice_stats['nxl']).astype(int) self.m_textGauXLWid.SetValue(str(wid_xl)) print 'No SizeXl specified, autoset: ' + str(wid_xl) else: wid_xl = float(self.m_textGauXLWid.GetValue()) if not self.m_textGauIL_kdamp.GetValue( ): #check whether field is empty kdamp_il = 1000 self.m_textGauIL_kdamp.SetValue(str(kdamp_il)) print 'No size Il specified, autoset: ' + str(kdamp_il) else: kdamp_il = float(self.m_textGauIL_kdamp.GetValue()) if not self.m_textGauXL_kdamp.GetValue( ): #check whether field is empty kdamp_xl = 1000 self.m_textGauXL_kdamp.SetValue(str(kdamp_xl)) print 'No SizeXl specified, autoset: ' + str(kdamp_xl) else: kdamp_xl = float(self.m_textGauXL_kdamp.GetValue()) # Set Radial Notch Parameeres if not self.m_text_rad1IL.GetValue(): # est_f_il = np.floor(ind_mid_il/3).astype(int) rad1_il = np.floor(ind_mid_il / 2).astype(int) self.m_text_rad1IL.SetValue(str(rad1_il)) print 'No Rad1Il specified, autoset: ' + str(rad1_il) else: rad1_il = float(self.m_text_rad1IL.GetValue()) if not self.m_text_rad1XL.GetValue(): #check whether field is empty # est_f_xl=np.floor(ind_mid_xl/3).astype(int) rad1_xl = np.floor(ind_mid_xl / 2).astype(int) self.m_text_rad1XL.SetValue(str(rad1_xl)) print 'No Rad1Xl specified, autoset: ' + str(rad1_xl) else: rad1_xl = float(self.m_text_rad1XL.GetValue()) if not self.m_text_rad2IL.GetValue(): # est_f_il = np.floor(ind_mid_il/3).astype(int) rad2_il = np.floor(ind_mid_il / 2).astype(int) self.m_text_rad2IL.SetValue(str(rad2_il)) print 'No Rad2Il specified, autoset: ' + str(rad2_il) else: rad2_il = float(self.m_text_rad2IL.GetValue()) if not self.m_text_rad2XL.GetValue(): #check whether field is empty # est_f_xl=np.floor(ind_mid_xl/3).astype(int) rad2_xl = np.floor(ind_mid_xl / 2).astype(int) self.m_text_rad2XL.SetValue(str(rad2_xl)) print 'No Rad2Xl specified, autoset: ' + str(rad2_xl) else: rad2_xl = float(self.m_text_rad2XL.GetValue()) if not self.m_text_Rad1Size.GetValue(): #check whether field is empty # est_f_xl=np.floor(ind_mid_xl/3).astype(int) rad1_Size = 20 self.m_text_Rad1Size.SetValue(str(rad1_Size)) print 'No Rad1Size specified, autoset: ' + str(rad1_Size) else: rad1_Size = float(self.m_text_Rad1Size.GetValue()) if not self.m_text_Rad2Size.GetValue(): # est_f_il = np.floor(ind_mid_il/3).astype(int) rad2_Size = 20 self.m_text_Rad2Size.SetValue(str(rad2_Size)) print 'No Rad2Size specified, autoset: ' + str(rad2_Size) else: rad2_Size = float(self.m_text_Rad2Size.GetValue()) if not self.m_text_Rad1Asp.GetValue(): #check whether field is empty # est_f_xl=np.floor(ind_mid_xl/3).astype(int) rad1_Asp = 1 self.m_text_Rad1Asp.SetValue(str(rad1_Asp)) print 'No Rad1Asp specified, autoset: ' + str(rad1_Asp) else: rad1_Asp = float(self.m_text_Rad1Asp.GetValue()) if not self.m_text_Rad2Asp.GetValue(): # est_f_il = np.floor(ind_mid_il/3).astype(int) rad2_Asp = 1 self.m_text_Rad2Asp.SetValue(str(rad2_Asp)) print 'No Rad2Asp specified, autoset: ' + str(rad2_Asp) else: rad2_Asp = float(self.m_text_Rad2Asp.GetValue()) if not self.m_text_Rad1kdamp.GetValue(): #check whether field is empty # est_f_xl=np.floor(ind_mid_xl/3).astype(int) rad1_kdamp = 1.000 self.m_text_Rad1kdamp.SetValue(str(rad1_kdamp)) print 'No Rad1kdamp specified, autoset: ' + str(rad1_kdamp) else: rad1_kdamp = float(self.m_text_Rad1kdamp.GetValue()) if not self.m_text_Rad2kdamp.GetValue(): # est_f_il = np.floor(ind_mid_il/3).astype(int) rad2_kdamp = 1.000 self.m_text_Rad2kdamp.SetValue(str(rad2_kdamp)) print 'No Rad2kdamp specified, autoset: ' + str(rad2_kdamp) else: rad2_kdamp = float(self.m_text_Rad2kdamp.GetValue()) self.t_plot_status.SetLabel(u'Parameters set') self.Update() # self.m_textGauIL.SetValue(str(est_f_il)) # self.m_textGauXL.SetValue(str(est_f_xl)) # self.m_textGauILSize.SetValue(str(stdil)) # self.m_textGauXLSize.SetValue(str(stdxl)) # self.m_textGauILAsp.SetValue(str(aspect_gauss_il)) # self.m_textGauXLAsp.SetValue(str(aspect_gauss_xl)) # self.m_textGauIL_kdamp.SetValue(str(kdamp_il)) # self.m_textGauXL_kdamp.SetValue(str(kdamp_xl)) if bool(self.m_checkBox_rad_notch.GetValue()): damp_f = damp_f + rad1_kdamp * (1 - self.AG_smoothstep2d( ilmat - slice_stats['ilmin'], xlmat - slice_stats['xlmin'], rad1_il, rad1_xl, rad1_Size, rad1_Asp, rad1_Size / 10)) damp_f = damp_f + rad1_kdamp * (1 - self.AG_smoothstep2d( ilmat - slice_stats['ilmin'], xlmat - slice_stats['xlmin'], slice_stats['nil'] - rad1_il, slice_stats['nxl'] - rad1_xl, rad1_Size, rad1_Asp, rad1_Size / 10)) damp_f = damp_f + rad2_kdamp * (1 - self.AG_smoothstep2d( ilmat - slice_stats['ilmin'], xlmat - slice_stats['xlmin'], rad2_il, rad2_xl, rad2_Size, rad2_Asp, rad2_Size / 10)) damp_f = damp_f + rad2_kdamp * (1 - self.AG_smoothstep2d( ilmat - slice_stats['ilmin'], xlmat - slice_stats['xlmin'], slice_stats['nil'] - rad2_il, slice_stats['nxl'] - rad2_xl, rad2_Size, rad2_Asp, rad2_Size / 10)) print 'RadNotch: Success!' if bool(self.m_checkBox_gau1.GetValue()): damp_f = damp_f + kdamp_il * self.AG_gauss2d( ilmat - slice_stats['ilmin'], xlmat - slice_stats['xlmin'], slice_stats['nil'] - est_f_il, ind_mid_xl, wid_il / 3, stdil / 3) damp_f = damp_f + kdamp_il * self.AG_gauss2d( ilmat - slice_stats['ilmin'], xlmat - slice_stats['xlmin'], est_f_il, ind_mid_xl, wid_il / 3, stdil / 3) damp_f = damp_f + kdamp_xl * self.AG_gauss2d( ilmat - slice_stats['ilmin'], xlmat - slice_stats['xlmin'], ind_mid_il, est_f_xl, stdxl / 3, wid_xl / 3) damp_f = damp_f + kdamp_xl * self.AG_gauss2d( ilmat - slice_stats['ilmin'], xlmat - slice_stats['xlmin'], ind_mid_il, slice_stats['nxl'] - est_f_xl, stdxl / 3, wid_xl / 3) print 'Gaussian filter: Success!' # Set Radial Parameeres if not self.m_textRad_rad.GetValue(): #check whether field is empty radius = np.floor(slice_stats['nil'] * 0.01).astype(int) self.m_textRad_rad.SetValue(str(radius)) print 'No Radius specified, autoset: ' + str(radius) else: radius = float(self.m_textRad_rad.GetValue()) if not self.m_textRad_asp.GetValue(): #check whether field is empty rad_aspect = float(self.m_text_il_xl_aspect.GetValue()) self.m_textRad_asp.SetValue(str(rad_aspect)) print 'No RadialAspect specified, autoset: ' + str(rad_aspect) else: rad_aspect = float(self.m_textRad_asp.GetValue()) if not self.m_textRad_sm.GetValue(): #check whether field is empty sm_factor = 3 self.m_textRad_sm.SetValue(str(sm_factor)) print 'No SmFactor specified, autoset: ' + str(sm_factor) else: sm_factor = float(self.m_textRad_sm.GetValue()) # if not self.m_textRad_kdamp.GetValue(): #check whether field is empty # rad_kdamp=20 # self.m_textRad_kdamp.SetValue(str(rad_kdamp)) # print 'No RadialKdamp specified, autoset: '+str(rad_kdamp) # else: # rad_kdamp = float(self.m_textRad_kdamp.GetValue()) if bool(self.m_checkBox_rad.GetValue()): pres_f = self.AG_smoothstep2d(ilmat - slice_stats['ilmin'], xlmat - slice_stats['xlmin'], ind_mid_il, ind_mid_xl, radius, rad_aspect, sm_factor) # print np.min(rad_kdamp*self.AG_smoothstep2d(ilmat-slice_stats['ilmin'], xlmat-slice_stats['xlmin'],ind_mid_il,ind_mid_xl, radius, rad_aspect, sm_factor) ) # print np.max(rad_kdamp*self.AG_smoothstep2d(ilmat-slice_stats['ilmin'], xlmat-slice_stats['xlmin'],ind_mid_il,ind_mid_xl, radius, rad_aspect, sm_factor) ) # print np.min(damp_f) # print np.max(damp_f) print 'Radial filter: Success!' self.t_plot_status.SetLabel(u'Filter applied') self.Update() Snew = S / damp_f Sout = Snew * (pres_f) + S * (1 - pres_f) print 'Amp.Spectrum divided: Success!' Wout = Sout * np.exp(1j * P) print 'Amp&Phase multiplied' data_out = np.fft.ifft2(np.fft.ifftshift(Wout)) + self.mean_amp_value data_out[empty_points] = np.nan datamat[empty_points] = np.nan print 'Inverse 2D FFT: Success!' self.t_plot_status.SetLabel(u'Inverse 2D FFT: Success!') sp_rms = np.std(S) sp_mean = np.mean(S) #for export self.data_out = np.real(data_out) self.ilmat = ilmat self.xlmat = xlmat # if not self.winplot_exists: win_plot = FPT_combi.FramePlot(None) print 'win_plot created' self.fgr1 = plt.Figure(facecolor='w') print 'fgr1 created' win_plot.canvas = FigCanvas(win_plot.m_panel1, -1, self.fgr1) print 'canvas created' win_plot.toolbar = Toolbar(win_plot.canvas) print 'toolbar created' plot_box = wx.BoxSizer(wx.VERTICAL) print 'box created' plot_box.Add(win_plot.canvas, flag=wx.EXPAND, proportion=10) print 'canvas added' plot_box.Add(win_plot.toolbar, flag=wx.EXPAND) print 'toolbar added' win_plot.m_panel1.SetSizer(plot_box) print 'panel1 SizerSet' self.t_plot_status.SetLabel(u'Window ready to plot') self.Update() ax1 = self.fgr1.add_subplot(231) im1 = ax1.imshow(datamat + self.mean_amp_value, origin='lower', interpolation='none', cmap='Spectral_r', vmin=-2 * self.amp_stats['rms'] + self.mean_amp_value, vmax=2 * self.amp_stats['rms'] + self.mean_amp_value, extent=[ slice_stats['xlmin'], slice_stats['xlmax'], slice_stats['ilmin'], slice_stats['ilmax'] ]) print 'plot1 success' ax2 = self.fgr1.add_subplot(232, sharex=ax1, sharey=ax1) im2 = ax2.imshow(np.real(data_out), origin='lower', interpolation='none', cmap='Spectral_r', vmin=-2 * self.amp_stats['rms'] + self.mean_amp_value, vmax=2 * self.amp_stats['rms'] + self.mean_amp_value, extent=[ slice_stats['xlmin'], slice_stats['xlmax'], slice_stats['ilmin'], slice_stats['ilmax'] ]) print 'plot2 success' ax3 = self.fgr1.add_subplot(233, sharex=ax1, sharey=ax1) im3 = ax3.imshow(np.real(data_out) - datamat, origin='lower', interpolation='none', cmap='Spectral_r', extent=[ slice_stats['xlmin'], slice_stats['xlmax'], slice_stats['ilmin'], slice_stats['ilmax'] ]) print 'plot3 success' ax4 = self.fgr1.add_subplot(234) ax4.imshow(S, aspect=slice_stats['aspect_ratio'], origin='lower', interpolation='none', cmap='Spectral_r', vmin=0, vmax=sp_mean + 4 * sp_rms), print 'plot4 success' ax5 = self.fgr1.add_subplot(235, sharex=ax4, sharey=ax4) ax5.imshow(Sout, aspect=slice_stats['aspect_ratio'], origin='lower', interpolation='none', cmap='Spectral_r', vmin=0, vmax=sp_mean + 4 * sp_rms) print 'plot5 success' ax6 = self.fgr1.add_subplot(236, sharex=ax4, sharey=ax4) ax6.imshow(damp_f * pres_f + (1 - pres_f) * np.ones_like(S), aspect=slice_stats['aspect_ratio'], origin='lower', interpolation='none', cmap='Spectral_r') print 'plot6 success' for axi in (ax1, ax2, ax3, ax4, ax5, ax6): axi.set_adjustable('box-forced') axi.set_aspect(slice_stats['aspect_ratio']) if (self.il_reverse): ax1.set_xlim(ax1.get_xlim()[::-1]) ax2.set_xlim(ax2.get_xlim()[::-1]) ax3.set_xlim(ax3.get_xlim()[::-1]) if (self.xl_reverse): ax1.set_ylim(ax1.get_ylim()[::-1]) ax2.set_ylim(ax2.get_ylim()[::-1]) ax3.set_ylim(ax3.get_ylim()[::-1]) self.fgr1.tight_layout(pad=0.1) self.t_plot_status.SetLabel(u'Showing window...') win_plot.Show(True) self.winplot_exists = True self.t_plot_status.SetLabel(u'Done')
def __init__(self, parent): wx.Panel.__init__(self, parent) self.SetBackgroundColour('#DCE5EE') pub().subscribe(self.update_language, T.LANGUAGE_CHANGED) self.control_panel = None self.dframes = [] self.order_names = [] self.key_figure = 1 self.mode_run = False self.current_dataframes = None self.current_datacolors = None self.run_explorer = False self.figure_config_dialog_ref = None # ---- inicialización de figura self.fig = Figure() self.canvas = FigureCanvas(self, -1, self.fig) # ---- configuración de figura self.fig_config = FigureConfig() self.set_figure_config() # ---- configuración de axe self.ax_conf = AxesConfig() # ---- radar chard config self.radar_chard_con = RadarChadConfig() # ---- toolbar self.sizer_tool = wx.BoxSizer(wx.HORIZONTAL) _bitmap = play_fig.GetBitmap() self.b_play = wx.BitmapButton(self, -1, _bitmap, style=wx.NO_BORDER) self.sizer_tool.Add(self.b_play, flag=wx.ALIGN_CENTER_VERTICAL) self.b_play.Bind(wx.EVT_BUTTON, self.on_play) self.b_play.SetToolTipString(L('VISUALIZE_DATE_CLUSTER')) _bitmap = settings_fig.GetBitmap() self.b_setting = wx.BitmapButton(self, -1, _bitmap, style=wx.NO_BORDER) self.sizer_tool.Add(self.b_setting, flag=wx.ALIGN_CENTER_VERTICAL) self.b_setting.Bind(wx.EVT_BUTTON, self.on_config) self.b_setting.SetToolTipString(L('FIGURE_CONF')) _bitmap = sort_and_filter.GetBitmap() self.b_sorted = wx.BitmapButton(self, -1, _bitmap, style=wx.NO_BORDER) self.b_sorted.Bind(wx.EVT_BUTTON, self.on_sort_and_filter) self.b_sorted.SetToolTipString(L('BUTTON_ORDER_AND_FILTER')) self.b_sorted.Disable() self.sizer_tool.Add(self.b_sorted, 0, wx.ALIGN_CENTER_VERTICAL) _bp = line_highligh.GetBitmap() self.b_highligh = wx.BitmapButton(self, -1, _bp, style=wx.NO_BORDER) self.b_highligh.Bind(wx.EVT_BUTTON, self.on_highligh) self.b_highligh.SetToolTipString(L('BUTTON_HIGHLIGHT')) self.b_highligh.Disable() self.sizer_tool.Add(self.b_highligh, 0, wx.ALIGN_CENTER_VERTICAL) self.toolbar = Toolbar(self.canvas) self.toolbar.Realize() self.toolbar.SetBackgroundColour('#DCE5EE') self.sizer_tool.Add(self.toolbar, 0, wx.ALIGN_CENTER_VERTICAL) choice_grafic = self.get_choice_grafic() self.sizer_tool.Add(choice_grafic, wx.ALIGN_LEFT) self.sizer = wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.sizer_tool, 0, wx.EXPAND) self.sizer.Add(self.canvas, 1, wx.EXPAND) self.SetSizer(self.sizer) self.Fit() self._welcome()
def __init__(self,frame,id): wx.Panel.__init__(self,frame,id,style = wx.BORDER_RAISED) z_layer = 0 self.omf = frame.omf self.halfstep = (float(self.omf.parameters['zstepsize'])/2.0)*1.0e10 self.figure = Figure(frameon = True) self.figure.set_facecolor('.82') self.canvas = FigureCanvas(self, -1, self.figure) fm = FigureManagerBase(self.canvas, 0) _pylab_helpers.Gcf.set_active(fm) self.wheel_cmap = LinearSegmentedColormap.from_list('wheel_rgby', ['red', 'green', 'blue', 'yellow', 'red']) mpl_toolbar = Toolbar(self.canvas) mpl_toolbar.Realize() x,y = indices((100,100), dtype = float) - 50. wheel_angle = arctan2(x,y) self.ax1 = self.figure.add_axes([0.1,0.1,0.7,0.8]) self.angle = ma.array(arctan2(-self.omf.my[:,:,z_layer], self.omf.mx[:,:,z_layer]), mask=(self.omf.M[:,:,z_layer] == 0.0)) self.angle[self.angle==360] = 0.0 print ma.getdata(self.angle) xmax = (float(self.omf.parameters['xnodes']) * float(self.omf.parameters['xstepsize']) * 1.0e10) ymax = (float(self.omf.parameters['ynodes']) * float(self.omf.parameters['ystepsize']) * 1.0e10) self.extent = [0., xmax, 0., ymax] self.im = self.ax1.imshow(self.angle.T, origin='lower', interpolation = 'nearest', extent = self.extent, cmap = self.wheel_cmap, vmin = -pi, vmax = pi) self.ax1.set_title('Z Slice = ' + str(z_layer*float(self.omf.parameters['zstepsize'])* 1.0e10 + self.halfstep) +' Ang' ,size = 'xx-large') self.ax1.set_xlabel('$x (\AA)$', size = 'x-large') self.ax1.set_ylabel('$y (\AA)$', size = 'x-large') self.ax1w = self.figure.add_axes([0.75,0.4,0.3,0.2], polar=True) self.ax1w.yaxis.set_visible(False) self.ax1w.imshow(wheel_angle, cmap=self.wheel_cmap, extent=[0,2*pi,0,pi]) self.ax1w.set_title('M direction\n(in-plane)') self.zselect = wx.Slider(self,-1,size = [300,40],minValue = int(0), maxValue = int(self.omf.dims[2]-1), style = wx.SL_AUTOTICKS) self.datavalue = wx.StatusBar(self,-1) self.datavalue.SetStatusText('Angle Value: ') self.label = wx.StaticText(self,-1,'Select Z layer: ') self.minVal = wx.StaticText(self,-1, '0.0') self.maxVal = wx.StaticText(self,-1, str(self.omf.dims[2]* (float(self.omf.parameters['zstepsize'])* 1.0e10) -self.halfstep)) #Sizer Creation toolSize = wx.BoxSizer(wx.HORIZONTAL) BotSize = wx.BoxSizer(wx.HORIZONTAL) vertSize = wx.BoxSizer(wx.VERTICAL) BotSize.Add(self.label,0,wx.LEFT|wx.RIGHT,border = 5) BotSize.Add(self.minVal,0,wx.LEFT|wx.RIGHT,border = 5) BotSize.Add(self.zselect,0,wx.TOP|wx.LEFT|wx.RIGHT,border = 5) BotSize.Add(self.maxVal,0,wx.LEFT|wx.RIGHT,border = 5) toolSize.Add(mpl_toolbar,0,wx.RIGHT,border = 20) toolSize.Add(self.datavalue,0,wx.LEFT|wx.RIGHT|wx.TOP,border = 20) vertSize.Add(self.canvas,-1,wx.EXPAND|wx.LEFT|wx.RIGHT,border = 5) vertSize.Add(toolSize,0) vertSize.Add(BotSize,0,wx.ALL, border = 10) self.SetSizer(vertSize) self.Fit() self.zselect.Bind(wx.EVT_SCROLL,self.newMomentZ) self.canvas.mpl_connect('motion_notify_event',self.onMouseOver)