class PlotPanel(wx.Panel): """ The PlotPanel has a Figure and a Canvas. OnSize events simply set a flag, and the actual resizing of the figure is triggered by an Idle event. """ def __init__(self, parent, obj_id): # initialize Panel wx.Panel.__init__(self, parent, obj_id) # initialize matplotlib stuff self.figure = Figure(None, None) self.canvas = FigureCanvasWxAgg(self, wx.ID_ANY, self.figure) rgbtuple = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNFACE).Get() clr = [c / 255. for c in rgbtuple] self.figure.set_facecolor(clr) self.figure.set_edgecolor(clr) self.canvas.SetBackgroundColour(wx.Colour(*rgbtuple)) self.Bind(wx.EVT_SIZE, self._on_size) def _on_size(self, event): self._set_size() def _set_size(self): pixels = tuple(self.GetClientSize()) self.SetSize(pixels) self.canvas.SetSize(pixels) self.figure.set_size_inches( float(pixels[0]) / self.figure.get_dpi(), float(pixels[1]) / self.figure.get_dpi()) def draw(self): pass # abstract, to be overridden by child classes
class PlotPanel(wx.Panel): def __init__(self, parent, dpi=None, color=None, *args, **kwargs): from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg wx.Panel.__init__(self, parent, wx.ID_ANY, *args, **kwargs) self.parent = parent self.figure = mpl.figure.Figure(None, dpi) self.canvas = FigureCanvasWxAgg(self, -1, self.figure) self._resizeflag = False self._SetSize() self.Bind(wx.EVT_IDLE, self._onIdle) self.Bind(wx.EVT_SIZE, self._SetSize) def _SetSize(self, event=None): pixels = self.GetSize() self.SetSize(pixels) self.canvas.SetSize(pixels) self.figure.set_size_inches( float(pixels[0]) / self.figure.get_dpi(), float(pixels[1]) / self.figure.get_dpi()) def _onIdle(self, event): self.canvas.draw() if self._resizeflag: self._SetSize() self._resizeflag = False def draw(self): pass # To be overriden by children def make(self): pass # To be overriden by children
class PanelPlot(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent, style=wx.WS_EX_PROCESS_IDLE) ''', style = wx.NO_FULL_REPAINT_ON_RESIZE''' self.figure = Figure() self.canvas = FigureCanvasWxAgg(self, -1, self.figure) self.set_size() self.draw() self._resize_flag = False #self.Bind(wx.EVT_IDLE, self.on_idle) #self.Bind(wx.EVT_SIZE, self.on_size) def on_idle(self, event): #event.RequestMore() if self._resize_flag: self._resize_flag = False #wx.CallLater(500,self.set_size()) def on_size(self, event): self._resize_flag = True def set_size(self): pixels = tuple(self.GetSize()) self.SetSize(pixels) self.canvas.SetSize(pixels) self.figure.set_size_inches( [float(x) / self.figure.get_dpi() for x in pixels]) def draw(self): self.canvas.draw()
class PlotPanel(wx.Panel): """The PlotPanel has a Figure and a Canvas. OnSize events simply set a flag, and the actual resizing of the figure is triggered by an Idle event.""" def __init__(self, parent, color=None, dpi=None, **kwargs): from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg from matplotlib.figure import Figure # initialize Panel if 'id' not in kwargs.keys(): kwargs['id'] = wx.ID_ANY if 'style' not in kwargs.keys(): kwargs['style'] = wx.NO_FULL_REPAINT_ON_RESIZE wx.Panel.__init__(self, parent, **kwargs) # initialize matplotlib stuff self.figure = Figure(None, dpi) self.axes = self.figure.gca() self.canvas = FigureCanvasWxAgg(self, -1, self.figure) self.SetColor(color) self._SetSize() self.draw() self.axes.set_xlabel('T (s)') self.axes.set_ylabel('Alfa_max (g)') self.axes.set_title("wave curve") self.axes.grid(True) self._resizeflag = False self.Bind(wx.EVT_IDLE, self._onIdle) self.Bind(wx.EVT_SIZE, self._onSize) def SetColor(self, rgbtuple=None): """Set figure and canvas colours to be the same.""" if rgbtuple is None: rgbtuple = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNFACE).Get() clr = [c / 255. for c in rgbtuple] self.figure.set_facecolor(clr) self.figure.set_edgecolor(clr) self.canvas.SetBackgroundColour(wx.Colour(*rgbtuple)) def _onSize(self, event): self._resizeflag = True def _onIdle(self, evt): if self._resizeflag: self._resizeflag = False self._SetSize() def _SetSize(self): pixels = tuple(self.parent.GetClientSize()) self.SetSize(pixels) self.canvas.SetSize(pixels) self.figure.set_size_inches( float(pixels[0]) / self.figure.get_dpi(), float(pixels[1]) / self.figure.get_dpi()) def draw(self): pass # abstract, to be overridden by child classes
class dataGraph(wx.Panel): # Create plot area and axes def __init__(self, parent): wx.Panel.__init__(self, parent) fig_width_cm = 25.0 inches_per_cm = 1.0 / 2.54 fig_width = fig_width_cm * inches_per_cm golden_mean = (np.sqrt(5) - 1.0) / 2.0 fig_height = golden_mean * fig_width fig_size = (fig_width, fig_height) params = { 'backend': 'ps', 'axes.labelsize': 10, 'text.fontsize': 10, 'label.fontsize': 10, 'label.rotation': 45, 'legend.fontsize': 10, 'xtick.labelsize': 10, 'ytick.labelsize': 10, 'text.usetex': False, 'figure.subplot.left': 0.01, 'figure.subplot.bottom': 0.01, 'figure.subplot.right': 0.99, 'figure.subplot.top': 0.99, 'figure.subplot.wspace': 0.00, 'figure.subplot.hspace': 0.00, 'figure.figsize': fig_size } plt.rcParams.update(params) self.fig = plt.figure() self.canvas = FigureCanvasWxAgg(self, -1, self.fig) self.canvas.SetPosition((0, 0)) self.canvas.SetSize((640, 320)) self.ax = self.fig.add_axes([0.08, 0.17, 0.83, 0.8]) # left, bottom, right, top self.rax = self.ax.twinx() self.useAuto = True self.setup_axes() def setup_axes(self): self.ax.autoscale(True) self.formatter = plt.ScalarFormatter(useOffset=False, useMathText=True) self.ax.yaxis.set_major_formatter(self.formatter) self.rax.yaxis.set_major_formatter(self.formatter) self.ax.minorticks_on() self.rax.minorticks_on() self.ax.set_xlabel("Time") self.ax.set_ylabel("Temperature ($^\circ$C)") self.rax.set_ylabel("Humidity (% RH)") labels = self.ax.get_xticklabels() for label in labels: label.set_rotation(30)
class CMBWindow(wx.Window, Knob): def __init__(self, *args, **kwargs): wx.Window.__init__(self, *args, **kwargs) hdu = fits.open('cmb_maps.fits') # hdu = fits.open('einstein_pack.fits') # hdu = fits.open('planck-satellite_pack.fits') self.sky = np.transpose(hdu[0].data) hdu.close() self.A0 = Param(10., minimum=0., maximum=10., id=0) self.A1 = Param(10., minimum=0., maximum=10., id=1) self.A2 = Param(10., minimum=0., maximum=10., id=2) self.A3 = Param(10., minimum=0., maximum=10., id=3) self.A4 = Param(10., minimum=0., maximum=10., id=4) self.A5 = Param(10., minimum=0., maximum=10., id=5) self.A6 = Param(10., minimum=0., maximum=10., id=6) self.A7 = Param(10., minimum=0., maximum=10., id=7) self.figure = Figure() self.canvas = FigureCanvasWxAgg(self, -1, self.figure) self.draw() self.A0.attach(self) self.A1.attach(self) self.A2.attach(self) self.A3.attach(self) self.A4.attach(self) self.A5.attach(self) self.A6.attach(self) self.A7.attach(self) self.Bind(wx.EVT_SIZE, self.sizeHandler) def sizeHandler(self, *args, **kwargs): self.canvas.SetSize(self.GetSize()) def draw(self): # print 'draw' if not hasattr(self, 'subplot1'): self.subplot1 = self.figure.add_subplot(111) sky = np.sum((10-amp)*self.sky,axis=2)/2. ims = self.subplot1.imshow(sky,vmin=-100,vmax=100) # ims.set_cmap('gray') def repaint(self): self.canvas.draw() def setKnob(self, value): self.repaint()
class myWxPlot(wx.Panel): def __init__(self, parent): from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg from matplotlib.figure import Figure self.parent = parent wx.Panel.__init__(self, parent) #matplotlib figure self.figure = Figure(None) self.figure.set_facecolor((0.7, 0.7, 1.)) self.subplot = self.figure.add_subplot(111) #canvas self.canvas = FigureCanvasWxAgg(self, -1, self.figure) self.canvas.SetBackgroundColour(wx.Colour(100, 255, 255)) self._SetSize() self.draw2() def _SetSize(self): size = tuple(self.parent.GetClientSize()) self.SetSize(size) self.canvas.SetSize(size) self.figure.set_size_inches( float(size[0]) / self.figure.get_dpi(), float(size[1]) / self.figure.get_dpi()) def draw(self): from mpl_toolkits.mplot3d import Axes3D import numpy as np x = np.arange(-3, 3, 0.25) y = np.arange(-3, 3, 0.25) X, Y = np.meshgrid(x, y) Z = np.sin(X) + np.cos(Y) ax = Axes3D(self.figure) ax.plot_wireframe(X, Y, Z) def draw2(self): import numpy as np theta = np.arange(0, 200, 0.1) x = 2 * np.cos(theta / 7) y = 3 * np.sin(theta / 3) self.subplot.plot(x, y, '-r') self.subplot.set_title("Sample", fontsize=12) self.subplot.set_xlabel("x") self.subplot.set_ylabel("y") self.subplot.set_xlim([-4, 4]) self.subplot.set_ylim([-4, 4])
class MatplotlibPanel(wx.Panel): def __init__(self,parent,ID=-1,label="",pos=wx.DefaultPosition,size=(100,25)): self.parent = parent #(0) Initialize panel: wx.Panel.__init__(self,parent,ID,pos,size,wx.STATIC_BORDER,label) self.SetMinSize(size) #(1) Create Matplotlib figure: self.figure = Figure(facecolor=(0.8,)*3) self.canvas = FigureCanvasWxAgg(self, -1, self.figure) self._resize() self._create_axes() self.cidAxisEnter = self.canvas.mpl_connect('axes_enter_event', self.callback_enter_axes) self.cidAxisLeave = self.canvas.mpl_connect('axes_leave_event', self.callback_leave_axes) self.Bind(wx.EVT_ENTER_WINDOW, self.callback_enter_axes) self.Bind(wx.EVT_LEAVE_WINDOW, self.callback_leave_axes) def _create_axes(self): self.ax = self.figure.add_axes((0,0,1,1), axisbg=[0.5]*3) pyplot.setp(self.ax, xticks=[], yticks=[]) def _resize(self): szPixels = tuple( self.GetClientSize() ) self.canvas.SetSize(szPixels) szInches = float(szPixels[0])/self.figure.get_dpi() , float(szPixels[1])/self.figure.get_dpi() self.figure.set_size_inches( szInches[0] , szInches[1] ) def callback_enter_axes(self, event): self.parent.parent.panel_enter(event, panel=self.parent) def callback_leave_axes(self, event): self.parent.parent.panel_leave(event) def cla(self): self.ax.cla() self.ax.set_position([0,0,1,1]) self.ax.set_axis_bgcolor([0.5]*3) pyplot.setp(self.ax, xticks=[], yticks=[], xlim=(0,1), ylim=(0,1)) self.ax.axis('tight') self.canvas.draw() def plot(self, I, cmax=None): if I!=None: if cmax==None: cmax = I.max() I[I==0] = np.nan self.ax.imshow(I, interpolation='nearest', origin='lower', vmin=0, vmax=cmax) pyplot.setp(self.ax, xticks=[], yticks=[]) self.ax.set_axis_bgcolor([0.05]*3) self.ax.axis('image') self.canvas.draw()
class WXMatPlotLibPanel(wx.Panel): def __init__(self, parent, color=None, dpi=None, **kwargs): from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg from matplotlib.figure import Figure # initialize Panel if 'id' not in kwargs.keys(): kwargs['id'] = wx.ID_ANY if 'style' not in kwargs.keys(): kwargs['style'] = wx.NO_FULL_REPAINT_ON_RESIZE wx.Panel.__init__(self, parent, **kwargs) # initialize matplotlib stuff self.figure = Figure(None, dpi) self.canvas = FigureCanvasWxAgg(self, -1, self.figure) #self.SetColor( color ) self._SetSize() self.draw() self._resizeflag = False self.Bind(wx.EVT_IDLE, self._onIdle) self.Bind(wx.EVT_SIZE, self._onSize) def SetColor(self, rgbtuple=None): """Set figure and canvas colours to be the same.""" if rgbtuple is None: rgbtuple = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNFACE).Get() clr = [c / 255. for c in rgbtuple] self.figure.set_facecolor(clr) self.figure.set_edgecolor(clr) self.canvas.SetBackgroundColour(wx.Colour(*rgbtuple)) def _onSize(self, event): self._resizeflag = True def _onIdle(self, evt): if self._resizeflag: self._resizeflag = False self._SetSize() def _SetSize(self): pixels = tuple(self.parent.GetClientSize()) self.SetSize(pixels) self.canvas.SetSize(pixels) self.figure.set_size_inches( float(pixels[0]) / self.figure.get_dpi(), float(pixels[1]) / self.figure.get_dpi()) def draw(self): pass # abstract, to be overridden by child classes
class IdentifyMatplotlibPanel(wx.Panel): def __init__(self, parent, ID=-1, label="", pos=wx.DefaultPosition, size=(100, 25)): #(0) Initialize panel: wx.Panel.__init__(self, parent, ID, pos, size, wx.STATIC_BORDER, label) self.SetMinSize(size) #(1) Create Matplotlib figure: self.figure = Figure(facecolor=(0.8, ) * 3) self.canvas = FigureCanvasWxAgg(self, -1, self.figure) self._resize() self._create_axes() def _create_axes(self): self.ax = self.figure.add_axes((0, 0, 1, 1), axisbg=[0.5] * 3) # self.plot(None) # self.ax.plot( np.random.randn(10) ) pyplot.setp(self.ax, xticks=[], yticks=[]) def _resize(self): szPixels = tuple(self.GetClientSize()) self.canvas.SetSize(szPixels) szInches = float(szPixels[0]) / self.figure.get_dpi(), float( szPixels[1]) / self.figure.get_dpi() self.figure.set_size_inches(szInches[0], szInches[1]) def cla(self): self.ax.cla() self.ax.set_position([0, 0, 1, 1]) self.ax.set_axis_bgcolor([0.5] * 3) pyplot.setp(self.ax, xticks=[], yticks=[], xlim=(0, 1), ylim=(0, 1)) self.ax.axis('tight') self.canvas.draw() def plot(self, I, cmax=None): if I != None: if cmax == None: cmax = I.max() I[I == 0] = np.nan self.ax.imshow(I, interpolation='nearest', origin='lower', vmin=0, vmax=cmax) pyplot.setp(self.ax, xticks=[], yticks=[]) self.ax.set_axis_bgcolor([0.05] * 3) self.ax.axis('image') self.canvas.draw()
class plottingWindow(wx.Window): def __init__(self, *args, **kwargs): if "figsize" in kwargs: self.figure = Figure(figsize=kwargs["figsize"]) self._axes = [0.1, 0.1, 0.8, 0.8] del kwargs["figsize"] else: self.figure = Figure(figsize=[8, 2.5]) self.figure.set_facecolor('white') wx.Window.__init__(self, *args, **kwargs) self.canvas = FigureCanvasWxAgg(self, -1, self.figure) self.figure.set_facecolor('white') self.figure.set_edgecolor('white') self.canvas.SetBackgroundColour('white') # Create a resizer self.Bind(wx.EVT_SIZE, self.sizeHandler) self.resize = 1 # self.canvas.mpl_connect('motion_notify_event', self.onMotion) # Prepare for zoom self.zoom = None self.zoomtype = "box" def setupGetXAxies(self, plots): self.getxaxis = GetXValues(plots) def repaint(self): """ Redraw and refresh the plot. :return: None """ self.canvas.draw() def clearPlot(self, *args): """ Clear the plot and rest some of the parameters. :param args: Arguments :return: """ self.figure.clear() self.repaint() def sizeHandler(self, *args, **kwargs): if self.resize == 1: self.canvas.SetSize(self.GetSize())
class MatplotlibPanel(wx.Panel): # Adapted from http://www.scipy.org/Matplotlib_figure_in_a_wx_panel # Defines plot styles AXIS_LABEL = {'fontsize': 16, 'fontweight': 'bold'} PLOT_TEXT = {'fontsize': 10, 'fontweight': 'bold'} def __init__(self, parent, xlabel, ylabel, id=wx.ID_ANY, **kwargs): wx.Panel.__init__(self, parent, id=id, **kwargs) self.parent = parent self.figure = Figure(None, None) self.canvas = FigureCanvas(self, -1, self.figure) '''Need to force the matplotlib canvas to take characters which we can then process. For some reason, if interactive mode is turned on, we cannot detect keydown events. We don't really need interactive mode anyway, so we will leave it off. ''' style = self.canvas.GetWindowStyle() | wx.WANTS_CHARS self.canvas.SetWindowStyle(style) self.subplot = self.figure.add_axes([0.1, 0.1, 0.8, 0.8]) self._resizeflag = False self.Bind(wx.EVT_IDLE, self._onIdle) self.Bind(wx.EVT_SIZE, self._onSize) def _onIdle(self, evt): if self._resizeflag: self._resizeflag = False self._SetSize() def _onSize(self, evt): self._resizeflag = True def _SetSize(self): pixels = tuple(self.parent.GetClientSize()) self.SetSize(pixels) self.canvas.SetSize(pixels) dpi = self.figure.get_dpi() self.figure.set_size_inches( float(pixels[0]) / dpi, float(pixels[1]) / dpi) def set_ylabel(self, text): self.subplot.set_ylabel(text, self.AXIS_LABEL) def set_title(self, text): self.subplot.set_title(text, self.AXIS_LABEL)
class PiePanel (wx.Panel): def __init__( self, parent, color=None, dpi=None, explode=(0, 0.05, 0, 0), fracs=[15,30,45, 10], **kwargs ): from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg from matplotlib.figure import Figure if 'id' not in kwargs.keys(): kwargs['id'] = wx.ID_ANY if 'style' not in kwargs.keys(): kwargs['style'] = wx.NO_FULL_REPAINT_ON_RESIZE wx.Panel.__init__( self, parent, **kwargs ) self.parent=parent self.figure = Figure( None, dpi ) self.canvas = FigureCanvasWxAgg( self, -1, self.figure ) labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' self.SetColor( color ) self._SetSize() ax = self.figure.add_axes([0.1, 0.1, 0.8, 0.8]) pies=ax.pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True) self.draw() self._resizeflag = False self.Bind(wx.EVT_IDLE, self._onIdle) self.Bind(wx.EVT_SIZE, self._onSize) def SetColor( self, rgbtuple=None ): """Set figure and canvas colours to be the same.""" if rgbtuple is None: rgbtuple = wx.SystemSettings.GetColour( wx.SYS_COLOUR_BTNFACE ).Get() clr = [c/255. for c in rgbtuple] self.figure.set_facecolor( clr ) self.figure.set_edgecolor( clr ) self.canvas.SetBackgroundColour( wx.Colour( *rgbtuple ) ) def _onSize( self, event ): self._resizeflag = True def _onIdle( self, evt ): if self._resizeflag: self._resizeflag = False self._SetSize() def _SetSize( self ): pixels = tuple( self.parent.GetClientSize() ) self.SetSize( pixels ) self.canvas.SetSize( pixels ) self.figure.set_size_inches( float( pixels[0] )/self.figure.get_dpi(), float( pixels[1] )/self.figure.get_dpi() ) def draw( self ): print "Drawing" self.canvas.draw()
class PlotPlotPanel(wx.Panel): def __init__(self, parent, dpi=None, **kwargs): wx.Panel.__init__(self, parent, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, **kwargs) self.ztv_frame = self.GetTopLevelParent() self.figure = Figure(dpi=None, figsize=(1.,1.)) self.axes = self.figure.add_subplot(111) self.canvas = FigureCanvasWxAgg(self, -1, self.figure) self.Bind(wx.EVT_SIZE, self._onSize) def _onSize(self, event): self._SetSize() def _SetSize(self): pixels = tuple(self.GetClientSize()) self.SetSize(pixels) self.canvas.SetSize(pixels) self.figure.set_size_inches(float(pixels[0])/self.figure.get_dpi(), float(pixels[1])/self.figure.get_dpi())
class BymurPlot(object): _stat_to_plot = ['mean', 'quantile10', 'quantile50', 'quantile90'] _stat_colors = ['k', 'g', 'b', 'r'] def __init__(self, *args, **kwargs): self.x_points = None self.y_points = None self._parent = kwargs.get('parent', None) self._figure = pyplot.figure() self._canvas = FigureCanvasWxAgg(self._parent, -1, self._figure) self._toolbar = NavigationToolbar2WxAgg(self._canvas) self._figure.clf() # self._figure.subplots_adjust(left=None, bottom=None, right=None, # top=None, wspace=None, hspace=0.3) self._cmap = pyplot.cm.RdYlGn_r self._figure.hold(True) self._canvas.SetSize(self._parent.GetSize()) self._canvas.draw() def clear(self): self._figure.clf() self._canvas.draw()
class WxMatplotlibPanel(wx.Panel): def __init__(self, parent): from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg from matplotlib.figure import Figure self.parent = parent wx.Panel.__init__(self, parent) self.figure = Figure(None) self.figure.set_facecolor((0.7, 0.7, 1.)) self.subplot = self.figure.add_subplot(111) self.canvas = FigureCanvasWxAgg(self, -1, self.figure) self.canvas.SetBackgroundColour(wx.Colour(100, 255, 255)) self._SetSize() self.draw() def _SetSize(self): size = tuple(self.parent.GetClientSize()) self.SetSize(size) self.canvas.SetSize(size) self.figure.set_size_inches( float(size[0]) / self.figure.get_dpi(), float(size[1]) / self.figure.get_dpi()) def draw(self): from mpl_toolkits.mplot3d import Axes3D import numpy as np x = np.arange(-3, 3, 0.25) y = np.arange(-3, 3, 0.25) X, Y = np.meshgrid(x, y) Z = np.sin(X) + np.cos(Y) ax = Axes3D(self.figure) #ax.plot_wireframe(X, Y, Z) ax.plot_surface(X, Y, Z, rstride=1, cstride=1)
class MatPlot_Window(wx.Window): def __init__(self, *args, **kwargs): wx.Window.__init__(self, *args, **kwargs) self.signals = [] self.figure = Figure() self.canvas = FigureCanvasWxAgg(self, -1, self.figure) self.canvas.callbacks.connect('button_press_event', self.mouseDown) self.canvas.callbacks.connect('motion_notify_event', self.mouseMotion) self.canvas.callbacks.connect('button_release_event', self.mouseUp) self.state = None self.Bind(wx.EVT_SIZE, self.sizeHandler) def sizeHandler(self, *args, **kwargs): self.canvas.SetSize(self.GetSize()) def mouseDown(self, event): self.state = None for i, signal in enumerate(self.signals): if signal in self.figure.hitlist(event): self.state = i + 1 self.x0 = event.xdata self.y0 = event.ydata if abs(self.x0) < 1.e-8: self.x0 = 1.e-8 # get all the initial values self.CI = [] for C in self.Controls: self.CI.append(C.value) break def mouseUp(self, event): self.state = None def Set_Knob_Value(self, value): XY = self.compute() for i, xy in enumerate(XY): setp(self.signals[i], xdata=xy[0], ydata=xy[1]) self.canvas.draw()
class MyPlotNoBlit(wx.Panel): def __init__(self, parent): wx.Panel.__init__(self, parent, -1) self.fig = Figure() self.canvas = FigureCanvas(self, -1, self.fig) self.Bind(wx.EVT_IDLE, self._onIdle) self.Bind(wx.EVT_SIZE, self._onSize) self._resizeFlag = True sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.canvas, 1, wx.GROW) self.SetSizer(sizer) def _onSize(self, evt): self._resizeFlag = True def _onIdle(self, evt): if self._resizeFlag: self._resizeFlag = False self._SetSize() self.draw() def _SetSize(self, pixels=None): if not pixels: pixels = self.GetClientSize() self.canvas.SetSize(pixels) self.fig.set_size_inches(pixels[0] / self.fig.get_dpi(), pixels[1] / self.fig.get_dpi()) def Plot(self, y): a = self.fig.add_subplot(111) a.plot(y) def draw(self): print 'draw!'
class PlotPlotPanel(wx.Panel): def __init__(self, parent, dpi=None, **kwargs): wx.Panel.__init__(self, parent, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, **kwargs) self.ztv_frame = self.GetTopLevelParent() self.figure = Figure(dpi=None, figsize=(1., 1.)) self.axes = self.figure.add_subplot(111) self.canvas = FigureCanvasWxAgg(self, -1, self.figure) self.Bind(wx.EVT_SIZE, self._onSize) self.axes_widget = AxesWidget(self.figure.gca()) self.axes_widget.connect_event('motion_notify_event', self.on_motion) self.plot_point = None def on_motion(self, evt): if evt.xdata is not None: xarg = np.abs(self.ztv_frame.plot_panel.plot_positions - evt.xdata).argmin() ydata = self.ztv_frame.plot_panel.plot_im_values[xarg] self.ztv_frame.plot_panel.cursor_position_textctrl.SetValue( '{0:.6g},{1:.6g}'.format(evt.xdata, ydata)) if self.plot_point is None: self.plot_point, = self.axes.plot([evt.xdata], [ydata], 'xm') else: self.plot_point.set_data([[evt.xdata], [ydata]]) self.figure.canvas.draw() def _onSize(self, event): self._SetSize() def _SetSize(self): pixels = tuple(self.GetClientSize()) self.SetSize(pixels) self.canvas.SetSize(pixels) self.figure.set_size_inches( float(pixels[0]) / self.figure.get_dpi(), float(pixels[1]) / self.figure.get_dpi())
class ExposureView(wx.Panel): def __init__(self, *args, **kwargs): wx.Panel.__init__(self, *args, **kwargs) vbox = wx.BoxSizer(wx.VERTICAL) self.image_view = ImageView(self, ID_EXPOSURE_VIEW, size=(487, 195), style=wx.BORDER_SUNKEN) vbox.Add(self.image_view, 1, wx.EXPAND) self.figure = Figure() self.plot = FigureCanvas(self, wx.ID_ANY, self.figure) self.plot.SetSize((487, 195)) self.plot.SetWindowStyle(wx.BORDER_SUNKEN) vbox.Add(self.plot, 1, wx.EXPAND) self.plot.Hide() self.toolbar = NavigationToolbar2WxAgg(self.plot) vbox.Add(self.toolbar, 0, wx.EXPAND) self.plot.Hide() self.SetSizerAndFit(vbox) def SetViewMode(self, mode): if mode == VIEW_MODE_SPECTRUM: self.image_view.Hide() self.plot.Show() self.toolbar.Show() else: self.image_view.Show() self.plot.Hide() self.toolbar.Hide() self.Layout()
class PhotPlotPanel(wx.Panel): def __init__(self, parent, dpi=None, **kwargs): wx.Panel.__init__(self, parent, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, **kwargs) self.ztv_frame = self.GetTopLevelParent() self.figure = Figure(dpi=None, figsize=(1.,1.)) self.axes = self.figure.add_subplot(111) self.canvas = FigureCanvasWxAgg(self, -1, self.figure) self.Bind(wx.EVT_SIZE, self._onSize) self.axes_widget = AxesWidget(self.figure.gca()) self.axes_widget.connect_event('motion_notify_event', self.on_motion) self.axes_widget.connect_event('button_press_event', self.on_button_press) self.axes_widget.connect_event('button_release_event', self.on_button_release) self.axes_widget.connect_event('figure_leave_event', self.on_cursor_leave) self.button_down = False def on_button_press(self, event): self.aper_names = ['aprad', 'skyradin', 'skyradout'] self.aper_last_radii = np.array([self.ztv_frame.phot_panel.aprad, self.ztv_frame.phot_panel.skyradin, self.ztv_frame.phot_panel.skyradout]) self.button_press_xdata = event.xdata self.cur_aper_index = np.abs(self.aper_last_radii - event.xdata).argmin() self.cur_aper_name = self.aper_names[self.cur_aper_index] # but, click must be within +-N pix to be valid if np.abs(event.xdata - self.aper_last_radii[self.cur_aper_index]) <= 20: self.button_down = True def on_motion(self, event): if self.button_down: if event.xdata is not None: if self.cur_aper_name == 'aprad': self.ztv_frame.phot_panel.aprad = (self.aper_last_radii[self.cur_aper_index] + (event.xdata - self.button_press_xdata)) self.ztv_frame.phot_panel.aprad_textctrl.SetValue('{0:.2f}'.format(self.ztv_frame.phot_panel.aprad)) set_textctrl_background_color(self.ztv_frame.phot_panel.aprad_textctrl, 'ok') elif self.cur_aper_name == 'skyradin': self.ztv_frame.phot_panel.skyradin = (self.aper_last_radii[self.cur_aper_index] + (event.xdata - self.button_press_xdata)) self.ztv_frame.phot_panel.skyradin_textctrl.SetValue('{0:.2f}'.format( self.ztv_frame.phot_panel.skyradin)) set_textctrl_background_color(self.ztv_frame.phot_panel.skyradin_textctrl, 'ok') elif self.cur_aper_name == 'skyradout': self.ztv_frame.phot_panel.skyradout = (self.aper_last_radii[self.cur_aper_index] + (event.xdata - self.button_press_xdata)) self.ztv_frame.phot_panel.skyradout_textctrl.SetValue('{0:.2f}'.format( self.ztv_frame.phot_panel.skyradout)) set_textctrl_background_color(self.ztv_frame.phot_panel.skyradout_textctrl, 'ok') self.ztv_frame.phot_panel.recalc_phot() def on_button_release(self, event): if self.button_down: if event.xdata is not None: if self.cur_aper_name == 'aprad': self.ztv_frame.phot_panel.aprad = (self.aper_last_radii[self.cur_aper_index] + (event.xdata - self.button_press_xdata)) self.ztv_frame.phot_panel.aprad_textctrl.SetValue('{0:.2f}'.format(self.ztv_frame.phot_panel.aprad)) set_textctrl_background_color(self.ztv_frame.phot_panel.aprad_textctrl, 'ok') elif self.cur_aper_name == 'skyradin': self.ztv_frame.phot_panel.skyradin = (self.aper_last_radii[self.cur_aper_index] + (event.xdata - self.button_press_xdata)) self.ztv_frame.phot_panel.skyradin_textctrl.SetValue('{0:.2f}'.format( self.ztv_frame.phot_panel.skyradin)) set_textctrl_background_color(self.ztv_frame.phot_panel.skyradin_textctrl, 'ok') elif self.cur_aper_name == 'skyradout': self.ztv_frame.phot_panel.skyradout = (self.aper_last_radii[self.cur_aper_index] + (event.xdata - self.button_press_xdata)) self.ztv_frame.phot_panel.skyradout_textctrl.SetValue('{0:.2f}'.format( self.ztv_frame.phot_panel.skyradout)) set_textctrl_background_color(self.ztv_frame.phot_panel.skyradout_textctrl, 'ok') self.ztv_frame.phot_panel.recalc_phot() self.button_down = False def on_cursor_leave(self, event): if self.button_down: if self.cur_aper_name == 'aprad': self.ztv_frame.phot_panel.aprad = self.aper_last_radii[self.cur_aper_index] self.ztv_frame.phot_panel.aprad_textctrl.SetValue('{0:.2f}'.format(self.ztv_frame.phot_panel.aprad)) set_textctrl_background_color(self.ztv_frame.phot_panel.aprad_textctrl, 'ok') elif self.cur_aper_name == 'skyradin': self.ztv_frame.phot_panel.skyradin = self.aper_last_radii[self.cur_aper_index] self.ztv_frame.phot_panel.skyradin_textctrl.SetValue('{0:.2f}'.format( self.ztv_frame.phot_panel.skyradin)) set_textctrl_background_color(self.ztv_frame.phot_panel.skyradin_textctrl, 'ok') elif self.cur_aper_name == 'skyradout': self.ztv_frame.phot_panel.skyradout = self.aper_last_radii[self.cur_aper_index] self.ztv_frame.phot_panel.skyradout_textctrl.SetValue('{0:.2f}'.format( self.ztv_frame.phot_panel.skyradout)) set_textctrl_background_color(self.ztv_frame.phot_panel.skyradout_textctrl, 'ok') self.ztv_frame.phot_panel.recalc_phot() self.button_down=False def _onSize(self, event): self._SetSize() def _SetSize(self): pixels = tuple(self.GetClientSize()) self.SetSize(pixels) self.canvas.SetSize(pixels) self.figure.set_size_inches(float(pixels[0])/self.figure.get_dpi(), float(pixels[1])/self.figure.get_dpi())
class FourierDemoWindow(wx.Window, Knob): def __init__(self, *args, **kwargs): wx.Window.__init__(self, *args, **kwargs) self.lines = [] self.imgs = [] self.bkgrnd = [] self.mean = [] self.figure = Figure() self.canvas = FigureCanvasWxAgg(self, -1, self.figure) self.canvas.callbacks.connect('button_press_event', self.mouseDown) self.canvas.callbacks.connect('motion_notify_event', self.mouseMotion) self.canvas.callbacks.connect('button_release_event', self.mouseUp) self.state = '' self.mov = cb.load('movies/demoMovie.tif', fr=20) with np.load('results_analysis.npz') as ld: self.comps = np.transpose( np.reshape(ld['A2'], (ld['d1'], ld['d2'], -1), order='F'), [2, 0, 1]) self.mean = np.mean(self.mov, 0) self.mouseInfo = (None, None, None, None) self.f0 = Param(np.percentile(self.mean, 95), minimum=np.min(self.mean), maximum=np.max(self.mean)) self.A = Param(1, minimum=0, maximum=self.mov.shape[0], step=1) self.toggle_background = BoolParam(True) self.draw() # Not sure I like having two params attached to the same Knob, # but that is what we have here... it works but feels kludgy - # although maybe it's not too bad since the knob changes both params # at the same time (both f0 and A are affected during a drag) self.f0.attach(self) self.A.attach(self) self.toggle_background.attach(self) self.Bind(wx.EVT_SIZE, self.sizeHandler) def sizeHandler(self, *args, **kwargs): self.canvas.SetSize(self.GetSize()) def mouseDown(self, evt): if self.lines[0] in self.figure.hitlist(evt): self.state = 'frequency' elif self.lines[1] in self.figure.hitlist(evt): self.state = 'time' else: self.state = '' self.mouseInfo = (evt.xdata, evt.ydata, max(self.f0.value, .1), self.A.value) def mouseMotion(self, evt): if self.state == '': return x, y = evt.xdata, evt.ydata if x is None: # outside the axes return x0, y0, f0Init, AInit = self.mouseInfo self.A.set(AInit + (AInit * (y - y0) / y0), self) if self.state == 'frequency': self.f0.set(f0Init + (f0Init * (x - x0) / x0)) elif self.state == 'time': if (x - x0) / x0 != -1.: self.f0.set(1. / (1. / f0Init + (1. / f0Init * (x - x0) / x0))) def mouseUp(self, evt): self.state = '' def draw(self): if not hasattr(self, 'subplot1'): self.subplot1 = self.figure.add_subplot(121) self.subplot2 = self.figure.add_subplot(122) x1, y1, x2, y2 = self.compute(self.f0.value, self.A.value) color = (1., 0., 0.) self.bkgrnd = self.subplot1.imshow(self.mean, cmap='gray', vmax=self.f0.value) # self.lines += self.subplot2.plot(x2, y2, color=color, linewidth=2) self.img = self.subplot2.imshow(self.mov[0], cmap='gray') #Set some plot attributes self.subplot1.set_title("Overlaid components", fontsize=12) self.subplot2.set_title("Movie frames", fontsize=12) # self.subplot1.set_ylabel("Frequency Domain Waveform X(f)", fontsize = 8) # self.subplot1.set_xlabel("frequency f", fontsize = 8) # self.subplot2.set_ylabel("Time Domain Waveform x(t)", fontsize = 8) # self.subplot2.set_xlabel("time t", fontsize = 8) # self.subplot1.set_xlim([-6, 6]) # self.subplot1.set_ylim([0, 1]) # self.subplot2.set_xlim([-2, 2]) # self.subplot2.set_ylim([-2, 2]) # self.subplot1.text(0.05, .95, r'$X(f) = \mathcal{F}\{x(t)\}$', \ # verticalalignment='top', transform = self.subplot1.transAxes) # self.subplot2.text(0.05, .95, r'$x(t) = a \cdot \cos(2\pi f_0 t) e^{-\pi t^2}$', \ # verticalalignment='top', transform = self.subplot2.transAxes) def compute(self, f0, A): f = np.arange(-6., 6., 0.02) t = np.arange(-2., 2., 0.01) x = A * np.cos(2 * np.pi * f0 * t) * np.exp(-np.pi * t**2) X = A / 2 * (np.exp(-np.pi * (f - f0)**2) + np.exp(-np.pi * (f + f0)**2)) return f, X, t, x def repaint(self): self.canvas.draw() def setKnob(self, value): # Note, we ignore value arg here and just go by state of the params # x1, y1, x2, y2 = self.compute(self.f0.value, self.A.value) #setp(self.lines[0], xdata=np.arange(100), ydata=np.random.random((100,))) if self.toggle_background.value == True: self.bkgrnd.set_data(self.mean) self.bkgrnd.set_clim(vmax=self.f0.value) else: self.bkgrnd.set_data(self.mean * np.nan) self.img.set_data(self.mov[np.int(self.A.value)]) self.repaint()
class FourierDemoWindow(wx.Window, Knob): def __init__(self, *args, **kwargs): wx.Window.__init__(self, *args, **kwargs) self.lines = [] self.figure = Figure() self.canvas = FigureCanvasWxAgg(self, -1, self.figure) self.canvas.callbacks.connect('button_press_event', self.mouseDown) self.canvas.callbacks.connect('motion_notify_event', self.mouseMotion) self.canvas.callbacks.connect('button_release_event', self.mouseUp) self.state = '' self.mouseInfo = (None, None, None, None) self.f0 = Param(2., minimum=0., maximum=6.) self.A = Param(1., minimum=0.01, maximum=2.) self.draw() # Not sure I like having two params attached to the same Knob, # but that is what we have here... it works but feels kludgy - # although maybe it's not too bad since the knob changes both params # at the same time (both f0 and A are affected during a drag) self.f0.attach(self) self.A.attach(self) self.Bind(wx.EVT_SIZE, self.sizeHandler) def sizeHandler(self, *args, **kwargs): self.canvas.SetSize(self.GetSize()) def mouseDown(self, evt): if self.lines[0] in self.figure.hitlist(evt): self.state = 'frequency' elif self.lines[1] in self.figure.hitlist(evt): self.state = 'time' else: self.state = '' self.mouseInfo = (evt.xdata, evt.ydata, max(self.f0.value, .1), self.A.value) def mouseMotion(self, evt): if self.state == '': return x, y = evt.xdata, evt.ydata if x is None: # outside the axes return x0, y0, f0Init, AInit = self.mouseInfo self.A.set(AInit+(AInit*(y-y0)/y0), self) if self.state == 'frequency': self.f0.set(f0Init+(f0Init*(x-x0)/x0)) elif self.state == 'time': if (x-x0)/x0 != -1.: self.f0.set(1./(1./f0Init+(1./f0Init*(x-x0)/x0))) def mouseUp(self, evt): self.state = '' def draw(self): if not hasattr(self, 'subplot1'): self.subplot1 = self.figure.add_subplot(211) self.subplot2 = self.figure.add_subplot(212) x1, y1, x2, y2 = self.compute(self.f0.value, self.A.value) color = (1., 0., 0.) self.lines += self.subplot1.plot(x1, y1, color=color, linewidth=2) self.lines += self.subplot2.plot(x2, y2, color=color, linewidth=2) # Set some plot attributes self.subplot1.set_title("Click and drag waveforms to change frequency and amplitude", fontsize=12) self.subplot1.set_ylabel("Frequency Domain Waveform X(f)", fontsize=8) self.subplot1.set_xlabel("frequency f", fontsize=8) self.subplot2.set_ylabel("Time Domain Waveform x(t)", fontsize=8) self.subplot2.set_xlabel("time t", fontsize=8) self.subplot1.set_xlim([-6, 6]) self.subplot1.set_ylim([0, 1]) self.subplot2.set_xlim([-2, 2]) self.subplot2.set_ylim([-2, 2]) self.subplot1.text(0.05, .95, r'$X(f) = \mathcal{F}\{x(t)\}$', \ verticalalignment='top', transform=self.subplot1.transAxes) self.subplot2.text(0.05, .95, r'$x(t) = a \cdot \cos(2\pi f_0 t) e^{-\pi t^2}$', \ verticalalignment='top', transform=self.subplot2.transAxes) def compute(self, f0, A): f = np.arange(-6., 6., 0.02) t = np.arange(-2., 2., 0.01) x = A*np.cos(2*np.pi*f0*t)*np.exp(-np.pi*t**2) X = A/2*(np.exp(-np.pi*(f-f0)**2) + np.exp(-np.pi*(f+f0)**2)) return f, X, t, x def repaint(self): self.canvas.draw() def setKnob(self, value): # Note, we ignore value arg here and just go by state of the params x1, y1, x2, y2 = self.compute(self.f0.value, self.A.value) setp(self.lines[0], xdata=x1, ydata=y1) setp(self.lines[1], xdata=x2, ydata=y2) self.repaint()
class PlateViewer(object): '''The PlateViewer class lets the user view the files associated with plates The idea here is that the PlateViewer is given a list of image files with plate, well and site metadata. The plate viewer organizes the files and lets the user browse individual plates. ''' def __init__(self, frame, data): self.data = data self.palette = matplotlib.cm.jet data.register_for_updates(self.on_update) self.frame = frame self.plate_bitmap = None self.frame.Sizer = wx.BoxSizer(wx.VERTICAL) self.splitter = wx.SplitterWindow(self.frame) self.frame.Sizer.Add(self.splitter, 1, wx.EXPAND) self.sr_panel = wx.Panel(self.splitter) self.sr_panel.Sizer = wx.BoxSizer(wx.VERTICAL) self.plate_choice = wx.Choice(self.sr_panel) self.sr_panel.Sizer.Add(self.plate_choice, 0, wx.LEFT | wx.ALL, 4) self.plate_panel = wx.Panel(self.sr_panel) self.sr_panel.Sizer.Add(self.plate_panel, 1, wx.EXPAND) rows, cols = data.plate_layout w, h = self.plate_panel.GetTextExtent("".join(["00"] * cols)) h *= rows self.plate_panel.SetMinSize((w, h)) self.canvas_panel = wx.Panel(self.splitter) self.canvas_panel.Sizer = wx.BoxSizer(wx.VERTICAL) control_sizer = wx.BoxSizer(wx.HORIZONTAL) self.canvas_panel.Sizer.Add(control_sizer, 0, wx.EXPAND | wx.ALL, 2) self.site_grid = wx.grid.Grid(self.canvas_panel) self.site_grid.SetDefaultRenderer(wx.grid.GridCellFloatRenderer()) self.site_grid.SetDefaultEditor(wx.grid.GridCellFloatEditor()) self.site_grid.CreateGrid(1, 2) self.site_grid.SetColLabelValue(0, "X") self.site_grid.SetColLabelValue(1, "Y") control_sizer.Add(self.site_grid, 0, wx.ALIGN_LEFT | wx.ALIGN_TOP | wx.ALL, 5) self.channel_grid = wx.grid.Grid(self.canvas_panel) self.channel_grid.CreateGrid(1, 4) self.channel_grid.SetColLabelValue(0, "Red") self.channel_grid.SetColLabelValue(1, "Green") self.channel_grid.SetColLabelValue(2, "Blue") self.channel_grid.SetColLabelValue(3, "Alpha") self.channel_grid.SetDefaultEditor(wx.grid.GridCellNumberEditor()) self.channel_grid.SetDefaultRenderer(wx.grid.GridCellNumberRenderer()) control_sizer.Add(self.channel_grid, 0, wx.ALIGN_RIGHT | wx.ALIGN_TOP | wx.ALL, 5) self.figure = matplotlib.figure.Figure() self.axes = self.figure.add_axes((0.05, 0.05, .9, .9)) self.subcanvaspanel = wx.Panel(self.canvas_panel) self.canvas = FigureCanvasWxAgg(self.subcanvaspanel, -1, self.figure) self.canvas_panel.Sizer.Add(self.subcanvaspanel, 1, wx.EXPAND) # # The following is largely taken from the matplotlib examples: # http://matplotlib.sourceforge.net/examples/user_interfaces/embedding_in_wx2.html # self.navtoolbar = NavigationToolbar2Wx(self.canvas) self.navtoolbar.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.frame.SetToolBar(self.navtoolbar) # update the axes menu on the toolbar self.navtoolbar.update() self.image_dict = None self.image_dict_lock = multiprocessing.RLock() self.image_dict_generation = 0 self.splitter.SplitVertically(self.sr_panel, self.canvas_panel) self.plate_panel.Bind(wx.EVT_PAINT, self.on_paint_plate) self.plate_panel.Bind(wx.EVT_ERASE_BACKGROUND, self.on_erase_background) self.plate_panel.Bind(wx.EVT_SIZE, self.on_plate_size) self.plate_panel.Bind(wx.EVT_MOTION, self.on_plate_motion) self.plate_panel.Bind(wx.EVT_LEFT_DOWN, self.on_plate_click) self.plate_choice.Bind(wx.EVT_CHOICE, self.on_plate_choice_evt) self.site_grid.Bind(wx.grid.EVT_GRID_CELL_CHANGE, lambda event: self.update_figure()) self.channel_grid.Bind(wx.grid.EVT_GRID_CELL_CHANGE, lambda event: self.update_figure()) self.frame.Bind(wx.EVT_CLOSE, self.on_close) self.subcanvaspanel.Bind(wx.EVT_SIZE, self.on_subcanvaspanel_size) self.on_update() self.frame.Layout() def get_border_height(self): '''The border along the top of the plate''' return 20 def get_border_width(self): return 30 def on_close(self, event): self.frame.Hide() def on_plate_choice_evt(self, event): self.on_update() def on_plate_size(self, event): self.draw_plate() def on_subcanvaspanel_size(self, event): assert isinstance(event, wx.SizeEvent) tw, th = self.navtoolbar.GetSizeTuple() scw, sch = event.GetSize() ch = sch - th self.canvas.SetSize(wx.Size(scw, ch)) self.canvas.Move(wx.Point(0, 0)) self.navtoolbar.SetSize(wx.Size(scw, th)) self.navtoolbar.Move(wx.Point(0, ch)) def on_plate_click(self, event): assert isinstance(event, wx.MouseEvent) x, y = event.GetPositionTuple() hit = self.plate_hit_test(x, y) if hit is None or self.plate_data is None: return row, col = hit if self.plate_data[row, col] is None: return self.set_display_well(self.plate_data[row, col]) def on_plate_motion(self, event): assert isinstance(event, wx.MouseEvent) x, y = event.GetPositionTuple() hit = self.plate_hit_test(x, y) if hit is None or self.plate_data is None: self.plate_panel.SetToolTipString("") else: row, col = hit well_name = "%s%02d" % (well_row_name(row), col + 1) well = self.plate_data[row, col] if well is None: self.plate_panel.SetToolTipString("%s: no data" % well_name) else: text = "%s: %d files" % (well_name, sum([len(v) for v in well.values()])) self.plate_panel.SetToolTipString(text) def on_update(self): if (tuple(sorted(self.plate_choice.GetItems())) != tuple( sorted(self.data.get_plate_names()))): plate_names = self.data.get_plate_names() self.plate_choice.SetItems(plate_names) if len(plate_names) > 0: self.plate_choice.SetSelection(0) self.plate_name = self.plate_choice.GetStringSelection() if self.plate_name in self.data.get_plate_names(): self.plate_data = self.data.get_plate(self.plate_name) elif (len(self.data.get_plate_names()) == 0 and None in self.data.plate_well_site): self.plate_data = self.data.get_plate(None) else: self.plate_data = None self.draw_plate() # # Set up the site grid size # if self.plate_data is not None: site_names = set() channel_names = set() for well in self.plate_data.flatten(): if well is not None: site_names.update(well.keys()) for sd in well.values(): channel_names.update([ fd[PlateData.D_CHANNEL] if PlateData.D_CHANNEL in fd else str(i + 1) for i, fd in enumerate(sd) ]) if len(site_names) > 1 or None not in site_names: self.site_grid.Show(True) self.use_site_grid = True update_values = self.site_grid.GetNumberRows() != len( site_names) if (self.site_grid.GetNumberRows() < len(site_names)): self.site_grid.AppendRows( len(site_names) - self.site_grid.GetNumberRows()) elif (self.site_grid.GetNumberRows() > len(site_names)): self.site_grid.DeleteRows( numRows=self.site_grid.GetNumberRows() - len(site_names)) side = int(np.ceil(np.sqrt(float(len(site_names))))) for i, site_name in enumerate(sorted(site_names)): self.site_grid.SetRowLabelValue(i, site_name) if update_values: self.site_grid.SetCellValue(i, 0, str((i % side) + 1)) self.site_grid.SetCellValue(i, 1, str(int(i / side) + 1)) else: self.site_grid.Show(False) self.use_site_grid = False update_values = self.channel_grid.GetNumberRows() != len( channel_names) if (self.channel_grid.GetNumberRows() < len(channel_names)): self.channel_grid.AppendRows( len(channel_names) - self.channel_grid.GetNumberRows()) elif (self.channel_grid.GetNumberRows() > len(channel_names)): self.channel_grid.DeleteRows( numRows=self.channel_grid.GetNumberRows() - len(channel_names)) for i, channel_name in enumerate(sorted(channel_names)): self.channel_grid.SetRowLabelValue(i, channel_name) for j in range(4): if update_values or not \ self.channel_grid.GetCellValue(i, j).isdigit(): self.channel_grid.SetCellValue( i, j, str(255 if j == 3 or i == j else 0)) def get_well_side(self): size = self.plate_panel.GetClientSizeTuple() size = (size[0] - self.get_border_width(), size[1] - self.get_border_height()) w = size[0] / self.data.plate_layout[1] h = size[1] / self.data.plate_layout[0] return min(w, h) def get_center(self, row, column, side=None): if side is None: side = self.get_well_side() return (side * column + side / 2 + self.get_border_width(), side * row + side / 2 + self.get_border_height()) def get_fill(self, well): n_files = sum([len(x) for x in well.values()]) color = self.palette(float(n_files) / float(max(self.data.max_per_well, 1)), bytes=True) color = wx.Colour(*color) return color def on_paint_plate(self, evt): assert isinstance(evt, wx.PaintEvent) if self.plate_bitmap is None: dc = wx.PaintDC(self.plate_panel) return else: dc = wx.BufferedPaintDC(self.plate_panel, self.plate_bitmap) def on_erase_background(self, evt): pass def get_radius(self): return max(self.get_well_side() / 2 - 1, 1) def plate_hit_test(self, x, y): '''Return the row and column of the well or None if not hit x, y - coordinates of pixel on plate panel surface ''' side = self.get_well_side() col = (float(x) - self.get_border_width() - float(side) / 2) / side row = (float(y) - self.get_border_height() - float(side) / 2) / side irow, icol = [int(v + .5) for v in (row, col)] d = np.sqrt((row - irow)**2 + (col - icol)**2) * side if d > self.get_radius(): return None if (irow < 0 or irow >= self.data.plate_layout[0] or icol < 0 or icol >= self.data.plate_layout[1]): return None return irow, icol def draw_plate(self): if self.plate_bitmap is not None: self.plate_bitmap.Destroy() self.plate_bitmap = None self.plate_panel.Refresh() width, height = [max(x, 1) for x in self.plate_panel.GetClientSize()] self.plate_bitmap = wx.EmptyBitmap(width, height, 32) dc = wx.MemoryDC(self.plate_bitmap) dc.SetBackground(wx.Brush(self.plate_panel.GetBackgroundColour())) dc.Clear() gc = wx.GraphicsContext.Create(dc) gc.SetFont(self.plate_panel.GetFont()) if self.plate_data is None: return side = self.get_well_side() radius = self.get_radius() gc.SetPen(wx.BLACK_PEN) for row in range(self.data.plate_layout[0]): text = well_row_name(row) w, h = gc.GetTextExtent(text) y = self.get_center(row, 0, side)[1] - int(h / 2) gc.DrawText(text, 3, y) for col in range(self.data.plate_layout[1]): text = "%02d" % (col + 1) w, h, descent, leading = gc.GetFullTextExtent(text) x = self.get_center(0, col, side)[0] - w / 2 gc.DrawText(text, x, 3) for row in range(self.data.plate_layout[0]): for col in range(self.data.plate_layout[1]): x, y = self.get_center(row, col, side) if (row < self.plate_data.shape[0] and col < self.plate_data.shape[1]): well = self.plate_data[row, col] if well is None: brush = wx.NullBrush else: brush = wx.Brush(self.get_fill(well)) gc.SetBrush(brush) gc.DrawEllipse(x - radius, y - radius, radius * 2, radius * 2) def set_display_well(self, well): '''Set the display well and redraw the figure''' with self.image_dict_lock: self.image_dict = {} self.image_dict_generation += 1 def fn(): from bioformats import load_image_url import javabridge from scipy.io.matlab.mio import loadmat from cellprofiler.modules.loadimages import url2pathname javabridge.attach() with self.image_dict_lock: generation = self.image_dict_generation for k, v in well.iteritems(): sd = {} with self.image_dict_lock: if self.image_dict_generation > generation: return self.image_dict[k] = sd for c, fd in enumerate(v): if PlateData.D_CHANNEL in fd: channel = fd[PlateData.D_CHANNEL] else: channel = str(c + 1) url = fd[PlateData.D_FILENAME] try: if url.lower().endswith(".mat"): img = loadmat(url2pathname(url), struct_as_record=True)["Image"] else: img = load_image_url(url) with self.image_dict_lock: if self.image_dict_generation > generation: return sd[channel] = img except: traceback.print_exc() pass wx.CallAfter(self.update_figure) javabridge.static_call("java/lang/System", "gc", "()V") javabridge.detach() t = threading.Thread(target=fn) t.setDaemon(True) t.start() def update_figure(self): if self.image_dict is None: return with self.image_dict_lock: image_dict = dict([(x, y.copy()) for x, y in self.image_dict.iteritems()]) channel_dict = {} totals = np.zeros(4) for i in range(self.channel_grid.GetNumberRows()): channel_name = self.channel_grid.GetRowLabelValue(i) channel_dict[channel_name] = np.array( [int(self.channel_grid.GetCellValue(i, j)) for j in range(4)], float) totals += channel_dict[channel_name] site_dict = {} tile_dims = [0, 0] if self.use_site_grid: for i in range(self.site_grid.GetNumberRows()): site_name = self.site_grid.GetRowLabelValue(i) site_dict[site_name] = np.array([ float(self.site_grid.GetCellValue(i, j)) - 1 for j in range(2) ])[::-1] tile_dims = [ max(i0, i1) for i0, i1 in zip(site_dict[site_name], tile_dims) ] else: site_dict[None] = np.zeros(2) img_size = [0, 0] for sd in image_dict.values(): for channel in sd: img_size = [ max(i0, i1) for i0, i1 in zip(sd[channel].shape, img_size) ] if all([iii == 0 for iii in img_size]): return img_size = np.array(img_size) tile_dims = np.array(tile_dims) + 1 for k in site_dict: site_dict[k] *= img_size img_size = np.hstack([np.ceil(tile_dims * img_size).astype(int), [3]]) megapicture = np.zeros(img_size, np.uint8) for site, sd in image_dict.iteritems(): offs = site_dict[site].astype(int) # TO_DO - handle images that aren't scaled from 0 to 255 for channel, image in sd.iteritems(): imgmax = np.max(image) scale = 1 if imgmax <= 1 else 255 if imgmax < 256 \ else 4095 if imgmax < 4096 else 65535 a = channel_dict[channel][3] rgb = channel_dict[channel][:3] / 255. image = image * a / scale if image.ndim < 3: image = image[:, :, np.newaxis] * rgb[np.newaxis, np.newaxis, :] if image.shape[0] + offs[0] > megapicture.shape[0]: image = image[:(megapicture.shape[0] - offs[0]), :, :] if image.shape[1] + offs[1] > megapicture.shape[1]: image = image[:, :(megapicture.shape[1] - offs[1]), :] megapicture[offs[0]:(offs[0] + image.shape[0]), offs[1]:(offs[1] + image.shape[1]), :] += image self.axes.cla() self.axes.imshow(megapicture) self.canvas.draw() self.navtoolbar.update()
class GraphViewPanel(wx.Panel): def __init__(self, parent, dstack=None, do=None, xvals=None, xlabel=''): wx.Panel.__init__(self, parent) if (dstack == None and do == None): dstack = scipy.zeros((10, 10)) if do == None: self.do = DisplayOpts(dstack) self.do.Optimise() else: self.do = do self.do.WantChangeNotification.append(self.draw) self.xvals = xvals self.xlabel = xlabel sizer1 = wx.BoxSizer(wx.VERTICAL) self.figure = Figure() self.axes = self.figure.add_subplot(111) self.canvas = FigureCanvas(self, -1, self.figure) sizer1.Add(self.canvas, 1, wx.TOP | wx.LEFT | wx.EXPAND) #self.toolbar = NavigationToolbar2WxAgg(self.canvas) #self.toolbar = MyNavigationToolbar(self.canvas, self) #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)) # # sizer1.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND) self.Bind(wx.EVT_SIZE, self._onSize) #self.toolbar.update() self.SetSizer(sizer1) self.draw() def draw(self, event=None): self.axes.cla() if self.xvals == None: xvals = np.arange(self.do.ds.shape[0]) else: xvals = self.xvals for i in range(self.do.ds.shape[3]): self.axes.plot(xvals, self.do.ds[:, self.do.yp, self.do.zp, i].squeeze(), label=self.do.names[i]) if self.do.ds.shape[3] > 1: self.axes.legend() self.axes.set_xlabel(self.xlabel) self.canvas.draw() def _onSize(self, event): #self._resizeflag = True self._SetSize() def _SetSize(self): pixels = tuple(self.GetClientSize()) self.SetSize(pixels) self.canvas.SetSize(pixels) self.figure.set_size_inches( float(pixels[0]) / self.figure.get_dpi(), float(pixels[1]) / self.figure.get_dpi())
class Window(wx.Frame): def __init__(self): """ Creo la ventana con los botones y todo. """ wx.Frame.__init__(self, None, -1, "Servicio Meteorologico Nacional - VAyGeo", (100, 100), (940, 580)) self.SetBackgroundColour('#ece9d8') self.ReadStationData() # Variables self.DirPath = 'C:\\' self.OutPath = 'C:\\' self.cal_factor = 1 self.FileList = [] self.converted_file_list = [] # Create plot area and axes self.fig = Figure(facecolor='#ece9d8') self.canvas = FigureCanvasWxAgg(self, -1, self.fig) self.canvas.SetPosition((0, 0)) self.canvas.SetSize((640, 320)) self.ax = self.fig.add_axes([0.08, 0.1, 0.86, 0.8]) self.ax.autoscale(True) self.SL_data = SL.SL() # Create text box for event logging self.dataPath_text = wx.TextCtrl(self, -1, pos=(140, 320), size=(465, 25)) self.outPath_text = wx.TextCtrl(self, -1, pos=(140, 360), size=(465, 25)) # Texto para tomar el factor de calibración. wx.StaticText(self, -1, "Factor de calibración:", pos=(200, 400)) self.t_cal_factor = wx.TextCtrl(self, -1, '1', pos=(320, 400), size=(50, 25)) self.t_cal_factor.Bind(wx.EVT_KEY_UP, self.onCalFactorEdit) # Cuadro para listar archivos. self.t2 = wx.ListBox(self, -1, pos=(640, 32), size=(200, 300), style=wx.TE_MULTILINE | wx.TE_READONLY) self.t2.Bind(wx.EVT_LISTBOX_DCLICK, self.plotFile, self.t2) # Boton de directorio de datos: self.datadir_button = wx.Button(self, label='Datos', pos=(25, 320), size=(100, 25)) self.datadir_button.SetFont( wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.NORMAL, False)) self.datadir_button.Bind(wx.EVT_BUTTON, self.onDatadirButton) # Boton de directorio de salida de datos: self.outdir_button = wx.Button(self, label='Convertidos', pos=(25, 360), size=(100, 25)) self.outdir_button.SetFont( wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.NORMAL, False)) self.outdir_button.Bind(wx.EVT_BUTTON, self.onOutdirButton) # Create start/stop button self.convert_button = wx.Button(self, label='Convertir', pos=(25, 400), size=(100, 25)) self.convert_button.SetFont( wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.NORMAL, False)) self.convert_button.Bind(wx.EVT_BUTTON, self.onConvertButton) # Create start/stop button self.edit_button = wx.Button(self, label='Editar', pos=(25, 440), size=(100, 25)) self.edit_button.SetFont( wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.NORMAL, False)) self.edit_button.Bind(wx.EVT_BUTTON, self.onEditButton) # Texto para tomar el factor de calibración. estaciones = self.stations_data.Estacion.values wx.StaticText(self, -1, "Estación:", pos=(380, 400)) self.combo_est = wx.ComboBox(self, -1, '1', pos=(440, 400), size=(50, 25), choices=estaciones) self.combo_est.Bind(wx.EVT_TEXT, self.SetStationParameters) wx.StaticText(self, -1, "N° de sensor:", pos=(640, 360)) wx.StaticText(self, -1, "N° de estación:", pos=(640, 390)) wx.StaticText(self, -1, "GAW ID:", pos=(640, 420)) wx.StaticText(self, -1, "Latitud:", pos=(640, 450)) wx.StaticText(self, -1, "Longitud:", pos=(640, 480)) wx.StaticText(self, -1, "Altura:", pos=(640, 510)) self.t_sens_numb = wx.TextCtrl(self, -1, '-', pos=(740, 355), size=(70, 25)) self.t_station_numb = wx.TextCtrl(self, -1, '-', pos=(740, 385), size=(70, 25)) self.t_gawid = wx.TextCtrl(self, -1, '-', pos=(740, 415), size=(70, 25)) self.t_lat = wx.TextCtrl(self, -1, '-', pos=(740, 445), size=(70, 25)) self.t_long = wx.TextCtrl(self, -1, '-', pos=(740, 475), size=(70, 25)) self.t_alt = wx.TextCtrl(self, -1, '-', pos=(740, 505), size=(70, 25)) def onCalFactorEdit(self, event): self.cal_factor = float(self.t_cal_factor.GetValue()) def ReadStationData(self): self.stations_data = pd.read_csv('Estaciones.txt') def SetStationParameters(self, event): with open('Estaciones.txt') as stations_file: for line in stations_file: if line.startswith(self.combo_est.GetValue()): station_data = line[:-1].split(',') self.t_sens_numb.SetValue(station_data[1]) self.t_station_numb.SetValue(station_data[2]) self.t_gawid.SetValue(station_data[3]) self.t_lat.SetValue(station_data[4]) self.t_long.SetValue(station_data[5]) self.t_alt.SetValue(station_data[6]) self.cal_factor = station_data[7] self.t_cal_factor.SetValue(station_data[7]) def plotFile(self, event): self.SL_data, self.SL_date = SL.SL.load_solar_light_file( self.DirPath + '\\' + self.FileList[self.t2.GetSelection()]) self.ax.clear() self.SL_data['Sensor1'] = self.SL_data[ 'Sensor1'].values * 0.35 * float(self.cal_factor) # self.SL_data = self.SL_data.tz_localize('UTC').tz_convert('America/Buenos_Aires') position_text = self.SL_data.index.date[-1].strftime( '%Y-%m-%d') + ' 01:00' # Hago el grafico, cambio los limites, ajusto los ejes y pongo los titulos. self.ax.plot_date(self.SL_data.tz_localize('UTC').tz_convert( 'America/Buenos_Aires').index.time, self.SL_data.tz_localize('UTC').tz_convert( 'America/Buenos_Aires')['Sensor1'].values * 40, markersize=0.5, color='#00008D') self.ax.set_ylim(ymin=0, ymax=14) self.ax.set_yticks([0, 3, 6, 8, 11, 14], minor=False) self.ax.set_yticks([1, 2, 4, 5, 7, 9, 10, 12, 13], minor=True) self.ax.tick_params(axis='y', which='major', length=10, width=1.5) self.ax.tick_params(axis='y', which='minor', length=5, width=1) self.ax.grid(axis='y', b=None) self.ax.grid(axis='x') # Agrego los textos. self.ax.text(position_text, 1.5, 'Leve', verticalalignment='center') self.ax.text(position_text, 4.5, 'Moderado', verticalalignment='center') self.ax.text(position_text, 7, 'Alto', verticalalignment='center') self.ax.text(position_text, 9.5, 'Muy Alto', verticalalignment='center') self.ax.text(position_text, 12.5, 'Extremo', verticalalignment='center') # Pongo los colores del fondo self.ax.axhspan(0, 3, color='#329500') # Low self.ax.axhspan(3, 6, color='#F7E400') # Moderated self.ax.axhspan(6, 8, color='#F85900') # High self.ax.axhspan(8, 11, color='#D8001D') # Very High self.ax.axhspan(11, 14, color='#6B49c8') # Extreme # Agrego el mediodia solar localtz = timezone('America/Buenos_Aires') sun = SolarTime() solar_noon = sun.solar_noon_utc(self.SL_date, float(self.t_long.GetValue())) self.ax.axvline(solar_noon.astimezone(localtz).time(), ymin=0, ymax=14, color='r') # Dibujo todo self.fig.canvas.draw() def GetFilesList(self): """ Hago una lista con todos los archivos del Solar Light que hay en el directorio seleccionado. """ self.FileList = [] self.converted_file_list = [] for file in os.listdir(self.DirPath): if file.endswith('uvb') or file.endswith('UVB'): self.FileList.append(file) return def getData(self): """ Abro un archivo de Solar Light """ self.SL_data, self.SL_date = SL.load_solar_light_file('BA170101.uvb') return def onEditButton(self, event): os.startfile(self.DirPath + '\\' + self.FileList[self.t2.GetSelection()]) if not self.t2.GetStringSelection().endswith(' (Editado)'): self.t2.SetString(self.t2.GetSelection(), self.t2.GetStringSelection() + ' (Editado)') return def onConvertButton(self, event): """Convierto los datos al formato de WOUDC con una plantilla que es foo.txt""" if self.combo_est.GetValue() == '1': print('la') fi = open('foo.txt') fo_name = self.SL_date.strftime('%Y%m%d') + \ '.UV-Biometer.501.' + \ str(self.t_sens_numb.GetValue()) +\ '.smna.csv' fo = open(self.OutPath + '\\' + fo_name, 'w') src = Template(fi.read()) fi.close() d = { 'sensor_number': self.t_sens_numb.GetValue(), 'numero_estacion': self.t_station_numb.GetValue(), 'nombre_estacion': self.combo_est.GetValue(), 'gaw_id': self.t_gawid.GetValue(), 'lat': self.t_lat.GetValue(), 'long': self.t_long.GetValue(), 'altura': self.t_alt.GetValue(), 'date': self.SL_date.strftime('%Y-%m-%d') } result = src.substitute(d) fo.write(result) self.SL_data[['Sensor1']].to_csv(fo, na_rep='', date_format='%H:%M:%S', float_format='%.7f', header=None) if not self.t2.GetStringSelection().startswith('* '): self.t2.SetString(self.t2.GetSelection(), '* ' + self.t2.GetStringSelection()) self.t2.SetSelection(self.t2.GetSelection() + 1) self.plotFile(wx.EVT_LEFT_DOWN) fo.close() def onDatadirButton(self, event): """ Selecciono la carpeta donde estan los archivos a procesar """ dialog = wx.DirDialog(None, "Choose a directory:", style=wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON) if dialog.ShowModal() == wx.ID_OK: self.DirPath = dialog.GetPath() self.dataPath_text.WriteText(self.DirPath) dialog.Destroy() # Actualizo la lista de archivos. self.GetFilesList() self.t2.Set(self.FileList) def onOutdirButton(self, event): """ Selecciono la carpeta donde estan los archivos a procesar """ dialog = wx.DirDialog(None, "Choose a directory:", style=wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON) if dialog.ShowModal() == wx.ID_OK: self.OutPath = dialog.GetPath() self.outPath_text.WriteText(self.OutPath) dialog.Destroy()
class RegistrationPanel(wx.Panel): def __init__(self, parent, ID=-1, label="", pos=wx.DefaultPosition, size=(100, 25)): #(0) Initialize panel: wx.Panel.__init__(self, parent, ID, pos, size, style=wx.STATIC_BORDER | wx.WANTS_CHARS, name=label) self.SetMinSize(size) self.parent = parent self.q = [0, 0, 0, 1] self.th = 5 #(1) Create Matplotlib figure: self.figure = Figure(facecolor='0.8') self.canvas = FigureCanvasWxAgg(self, -1, self.figure) self._resize() self._create_axes() self.canvas.Bind(wx.EVT_KEY_DOWN, self.callback_key) self.canvas.Bind(wx.EVT_CHAR_HOOK, self.callback_key) def callback_key(self, event): keycode = event.GetKeyCode() #(0) Escape to exit: if keycode == wx.WXK_ESCAPE: ans = wx.MessageBox('Are you sure you want to quit?', '', wx.YES_NO | wx.CENTRE | wx.NO_DEFAULT, self) if ans == wx.YES: self.parent.quit() #(1) Enter to finish: if keycode == wx.WXK_RETURN: self.parent.forward() #(2) Update transformation parameters: amp = 0.1 + (event.ControlDown() * (1 - 0.1)) + (event.ShiftDown() * (5 - 0.1)) if keycode == wx.WXK_UP: self.q[1] += amp if keycode == wx.WXK_DOWN: self.q[1] -= amp if keycode == wx.WXK_LEFT: self.q[0] -= amp if keycode == wx.WXK_RIGHT: self.q[0] += amp if keycode == 328: self.q[0] -= amp if keycode == 330: self.q[0] += amp if keycode == 326: self.q[1] -= amp if keycode == 332: self.q[1] += amp if keycode in [91, 123]: self.q[2] += 0.2 * amp # '[' if keycode in [93, 125]: self.q[2] -= 0.2 * amp # ']' self.transform() def _create_axes(self): self.ax = self.figure.add_axes((0, 0, 1, 1), axisbg=[0.5] * 3) pyplot.setp(self.ax, xticks=[], yticks=[]) def _resize(self): szPixels = tuple(self.GetClientSize()) self.canvas.SetSize(szPixels) szInches = float(szPixels[0]) / self.figure.get_dpi(), float( szPixels[1]) / self.figure.get_dpi() self.figure.set_size_inches(szInches[0], szInches[1]) def cla(self): self.ax.cla() self.ax.set_position([0, 0, 1, 1]) self.ax.set_axis_bgcolor([0.5] * 3) pyplot.setp(self.ax, xticks=[], yticks=[], xlim=(0, 1), ylim=(0, 1)) self.ax.axis('tight') self.canvas.draw() def plot(self): #initial plot (after navigating to a new image) I = PM.transform2D(self.I, self.q) self.IT = I.copy() self.plot_source() # I[I==0] = np.nan # self.ax.imshow(I, interpolation='nearest', origin='lower', vmin=0, vmax=self.cmax) pyplot.setp(self.ax, xticks=[], yticks=[]) self.ax.set_axis_bgcolor([0.05] * 3) self.ax.axis('image') self.canvas.draw() def plot_source( self): #plot source (thresholded according to slider value) if self.ax.images: self.ax.images.pop(0) I = self.IT.copy() I[I <= self.th] = np.nan self.ax.imshow(I, interpolation='nearest', origin='lower', vmin=0, vmax=self.cmax) def plot_template( self, I0, th=0): #plot template (thresholded according to slider value) self.th = th if self.ax.collections: self.ax.collections.pop(0) self.ax.contour(I0 > th, 1, colors="0.5", linewidths=3) self.plot_source() self.canvas.draw() def set_Iq(self, I, q): self.I = I.copy() self.q = q self.cmax = 0.95 * I.max() def transform(self): #transform the source I = PM.transform2D(self.I, self.q) self.IT = I.copy() self.plot_source() self.canvas.draw()
class ASPanelWxMPL(wx.Panel): """ Encapsulate a matplotlib Figure and its toolbar """ DEFAULT_SIZE = (6.0, 3.70) DEFAULT_DPI = 96 def __init__(self, *args, **kwargs): super(ASPanelWxMPL, self).__init__(*args) self.figure = kwargs.pop('figure', None) if not self.figure: self.figure = Figure(ASPanelWxMPL.DEFAULT_SIZE, ASPanelWxMPL.DEFAULT_DPI) self.canvas = FigureCanvasWxAgg(self, -1, self.figure) self.toolbar = NavigationToolbar2WxAgg(self.canvas) self.toolbar.Hide() self.__set_size() self.Bind(wx.EVT_SIZE, self.on_resize) #self.Bind(wx.EVT_PAINT, self.on_redraw) self.canvas.mpl_connect('motion_notify_event', self.on_mouse_move) #self.canvas.mpl_connect('button_press_event', self.on_mouse_click) #self.canvas.mpl_connect('button_press_event', self.on_pick_event) def __set_size(self): self.canvas.SetSize(self.GetSize()) def __getattr__(self, name): attr = getattr(self.figure, name) if hasattr(attr, '__call__'): def newfunc(*args, **kwargs): wx.BeginBusyCursor() result = attr(*args, **kwargs) wx.EndBusyCursor() return result return newfunc else: return attr def get_figure(self): return self.figure def get_toolbar(self): return self.toolbar def resetToolbar(self): tb = self.toolbar if tb._active == 'PAN': tb.pan('off') tb.ToggleTool(tb.wx_ids['Pan'], False) if tb._active == 'ZOOM': tb.ToggleTool(tb.wx_ids['Zoom'], False) tb.zoom('off') def redraw(self): self.canvas.draw() def show(self, b): pass def on_mouse_move(self, evt): if (evt.inaxes is None): return if (evt.xdata is None): return wx.PostEvent(self, ASEventMotion(self.GetId(), xy=(evt.xdata, evt.ydata))) def on_pick_event(self, evt): if (evt.inaxes is None): return if (evt.xdata is None): return #thisline = event.artist #xdata, ydata = thisline.get_data() #ind = event.ind #print('on pick line:', zip(xdata[ind], ydata[ind])) #self.cb_on_pick_event(evt.xdata, evt.ydata) def on_btn_reset(self): self.toolbar.home() def on_btn_backward(self): self.toolbar.back() def on_btn_forward(self): self.toolbar.forward() def on_btn_pan(self, enable): self.toolbar.pan() def on_btn_zoom_to_rectangle(self, enable): self.toolbar.zoom() def on_resize(self, *args, **kwargs): self.__set_size() def on_redraw(self, *args, **kwargs): self.canvas.draw()
class MatplotlibPanel(wx.Panel): def __init__(self, parent, ID=-1, label="", pos=wx.DefaultPosition, size=(100, 25), panelnum=0): #(0) Initialize panel: wx.Panel.__init__(self, parent, ID, pos, size, wx.STATIC_BORDER, label) self.SetMinSize(size) self.parent = parent self.panelnum = panelnum #(1) Create Matplotlib figure: self.figure = Figure(facecolor=(0.8, ) * 3) self.canvas = FigureCanvasWxAgg(self, -1, self.figure) self._resize() self._create_axes() self.cidButtonDown = self.canvas.mpl_connect( 'button_press_event', self.callback_button_press) def _create_axes(self): self.ax = self.figure.add_axes((0, 0, 1, 1), axisbg=[0.5] * 3) pyplot.setp(self.ax, xticks=[], yticks=[]) def _resize(self): szPixels = tuple(self.GetClientSize()) self.canvas.SetSize(szPixels) szInches = float(szPixels[0]) / self.figure.get_dpi(), float( szPixels[1]) / self.figure.get_dpi() self.figure.set_size_inches(szInches[0], szInches[1]) def callback_button_press(self, event): xy = event.xdata, event.ydata shift = event.guiEvent.m_shiftDown if xy != (None, None): xy = tuple(np.round(xy, decimals=1)) if event.button == 1: if shift: self.parent.poi_select(xy, self.panelnum) else: #add POI self.parent.poi_add(xy, self.panelnum) else: #delete closest POI self.parent.poi_delete(xy, self.panelnum) def cla(self): self.ax.cla() self.ax.set_position([0, 0, 1, 1]) self.ax.set_axis_bgcolor([0.5] * 3) pyplot.setp(self.ax, xticks=[], yticks=[], xlim=(0, 1), ylim=(0, 1)) self.ax.axis('tight') self.canvas.draw() def plot(self, I, cmax=None): if I != None: if cmax == None: cmax = I.max() I[I == 0] = np.nan self.ax.imshow(I, interpolation='nearest', origin='lower', vmin=0, vmax=cmax) pyplot.setp(self.ax, xticks=[], yticks=[]) self.ax.set_axis_bgcolor([0.05] * 3) self.ax.axis('image') self.canvas.draw() def highlight_poi(self, ind): for i, line in enumerate(self.ax.lines): if i == ind: pyplot.setp(line, color='g', markersize=12) else: pyplot.setp(line, color='w', markersize=8) self.canvas.draw() def plot_poi(self, xy): x, y = xy i = len(self.ax.texts) + 1 self.ax.plot(x, y, 'wo', markersize=8) self.ax.text(x + 1, y + 1, '%d' % i, bbox=dict(facecolor='w')) def replot_pois(self, pois): self.ax.lines = [] self.ax.texts = [] if pois: [self.plot_poi(xy) for xy in pois] self.canvas.draw()
class PlottingWindow(wx.Window): """ Class for wx window with embedded matplotlib plots """ def __init__(self, *args, **kwargs): """ Initialize plot window parameters. Optional keywords: figsize: size of figure in inches integrate: 0 or 1 of whether the plot should send the integrate pubsub when a right click is activated. smash: 0 or 1 of whether the plot should send the integrate pubsub when a right click is activated. :param args: Arguments :param kwargs: Keywords :return: """ self.displaysize = wx.GetDisplaySize() self.defaultfigsize = (6. * 0.9, 5. * 0.9) if "figsize" in kwargs: figsize = kwargs["figsize"] del kwargs["figsize"] else: figsize = self.defaultfigsize if "axes" in kwargs: self._axes = kwargs["axes"] del kwargs["axes"] else: if figsize[0] < 5: self._axes = [0.2, 0.2, 0.7, 0.7] else: self._axes = [0.11, 0.11, 0.8, 0.8] self.figsize = figsize if "integrate" in kwargs: self.int = kwargs["integrate"] del kwargs["integrate"] else: self.int = 0 if "smash" in kwargs: self.smash = kwargs["smash"] del kwargs["smash"] else: self.smash = 0 wx.Window.__init__(self, *args, **kwargs) self.figure = Figure(figsize=figsize) # , dpi= self.subplot1 = None self.zoom = None self.subplot1 = None self.canvas = FigureCanvasWxAgg(self, -1, self.figure) self.Bind(wx.EVT_SIZE, self.size_handler) self.resize = 1 self.flag = False self.kda = False self.kdnorm = 1. self.normalticks = True self.nativez = [] self.text = [] self.lines = [] self.cbar = None self.datalims = None self.data = None self.cmap = None self.set_color() self.xlabel = "" self.ylabel = "" self.zoomtype = "box" self.tickcolor = "black" self.canvas.mpl_connect('button_release_event', self.on_release) self.canvas.mpl_connect('key_press_event', self.on_key) def on_release(self, event): """ Function triggered on button release event from plot. Currently wired to trigger on_save_figure_dialog on middle button. :param event: wx.Event :return: None """ if event.button == 1: if wx.GetKeyState(wx.WXK_ALT): try: self.zoom.switch_label() except: print("Could not switch on labels") if event.button == 2: if wx.GetKeyState(wx.WXK_CONTROL): dlg = DoubleInputDialog(self) dlg.initialize_interface("Matplotlib RC Parameters", "RC Param Name:", 'lines.markersize', "Value:", "6") dlg.ShowModal() rcname = dlg.value rcval = dlg.value2 print(rcname, rcval) rcParams[rcname] = rcval elif wx.GetKeyState(wx.WXK_ALT): dlg = DoubleInputDialog(self) dlg.initialize_interface("Set Plot X Range", "Min:", '', "Max:", "") dlg.ShowModal() minval = dlg.value maxval = dlg.value2 try: minval = float(minval) maxval = float(maxval) self.zoom.set_manual(minval, maxval) print("Manually Set Zoom:", minval, maxval) except: print("Error converting string to float:", minval, maxval) elif wx.GetKeyState(wx.WXK_SHIFT): dlg = DoubleInputDialog(self) dlg.initialize_interface("Set Plot Y Range", "Min:", '', "Max:", "") dlg.ShowModal() minval = dlg.value maxval = dlg.value2 try: minval = float(minval) maxval = float(maxval) self.zoom.set_manual_y(minval, maxval) print("Manually Set Zoom:", minval, maxval) except: print("Error converting string to float:", minval, maxval) elif wx.GetKeyState(wx.WXK_SPACE): try: self.zoom.switch_label() except: print("Could not switch on labels") else: self.on_save_fig_dialog(event) def on_key(self, evt): # print("you pressed", evt.key) if evt.key == "ctrl+c": self.copy_to_clipboard() if evt.key == "ctrl+u": self.on_write_dialog(evt) def on_save_fig_dialog(self, evt): """ Open a save figure dialog for specified plot. :param evt: wx.Event (unused) :return: None """ path = FileDialogs.save_file_dialog() if path is not None: self.save_figure(path) def on_save_fig(self, evt, path, **kwargs): """ Save figure to path. :param evt: wx.Event (unused) :param path: Path to save figure to :param kwargs: keywords passed to save_figure :return: None """ if path is not None: self.save_figure(path, **kwargs) def save_figure(self, path, **kwargs): """ Saves Figure to path. :param path: Path to save figure at. :param kwargs: Keywords passed to matplotlib.figure.savefig (note only specific ones are passed) :return: None """ if "transparent" in kwargs: t = kwargs["transparent"] else: t = True if "dpi" in kwargs: dpi = kwargs["dpi"] else: dpi = None self.figure.savefig(path, transparent=t, dpi=dpi) print("Saved Figure: ", path) def kda_test(self, xvals): """ Test whether the axis should be normalized to convert mass units from Da to kDa. Will use kDa if: xvals[int(len(xvals) / 2)] > 100000 or xvals[len(xvals) - 1] > 1000000 If kDa is used, self.kda=True and self.kdnorm=1000. Otherwise, self.kda=False and self.kdnorm=1. :param xvals: mass axis :return: None """ try: if xvals[int( len(xvals) / 2)] > 20000 or xvals[len(xvals) - 1] > 150000: self.kdnorm = 1000. self.xlabel = "Mass (kDa)" self.kda = True else: self.xlabel = "Mass (Da)" self.kda = False self.kdnorm = 1. except (TypeError, ValueError): self.xlabel = "Mass (Da)" self.kdnorm = 1. self.kda = False def plotadddot(self, x, y, colval, markval, label=""): """ Adds a scatter plot to the figure. May be one or more. :param x: x values :param y: y values :param colval: Color :param markval: Marker :return: None """ self.subplot1.plot(np.array(x) / self.kdnorm, y, color=colval, marker=markval, linestyle='None', clip_on=True, markeredgecolor="k", label=label) def addtext(self, txt, x, y, vlines=True, hlines=False, color="k", ymin=0, ymax=None, verticalalignment="top", xmin=0, xmax=None, nopaint=False, **kwargs): """ Adds text and lines. Puts things that have been added in self.lines and self.text lists. :param txt: String of text to add :param x: x position for where to add :param y: y position for where to add :param vlines: Whether to add vertical lines to the text as well. :param color: Color of text and lines :param kwargs: Keywords If range=(a,b) is specified, adds a line from a to b and vertical lines at a and b. :return: None """ if ymax is None: ymax = y if xmax is None: xmax = x text = self.subplot1.text(np.array(x) / self.kdnorm, y, txt, horizontalalignment="center", verticalalignment=verticalalignment, color=color) self.text.append(text) if vlines: if "range" in kwargs: line_range = kwargs["range"] line = self.subplot1.vlines(line_range[0] / self.kdnorm, ymin, y * 0.6, color=color) self.lines.append(line) line = self.subplot1.vlines(line_range[1] / self.kdnorm, ymin, y * 0.6, color=color) self.lines.append(line) line = self.subplot1.hlines(y * 0.3, line_range[0] / self.kdnorm, line_range[1] / self.kdnorm, linestyles="dashed", color=color) self.lines.append(line) pass else: line = self.subplot1.vlines(np.array(x) / self.kdnorm, ymin, y - 0.05 * ymax, linestyles="dashed", color=color) self.lines.append(line) if hlines: line = self.subplot1.hlines(y, xmin / self.kdnorm, xmax / self.kdnorm - 0.05 * xmax / self.kdnorm, linestyles="dashed", color=color) self.lines.append(line) if not nopaint: self.repaint() def textremove(self): """ Remove text and lines previous placed in the self.text and self.lines containers :return: None """ if len(self.text) > 0: for i in range(0, len(self.text)): self.text[i].remove() try: self.lines[i].remove() except: print(self.text[i]) self.text = [] self.lines = [] self.repaint() def repaint(self, setupzoom=False): """ Redraw and refresh the plot. :return: None """ if setupzoom: self.setup_zoom([self.subplot1], self.zoomtype) self.canvas.draw() def clear_plot(self, *args): """ Clear the plot and rest some of the parameters. :param args: Arguments :return: """ self.figure.clear() self.flag = False self.nativez = [] self.text = [] self.lines = [] self.kda = False self.kdnorm = 1. if "nopaint" not in args: self.repaint() def set_nticks(self, bins): """ Set the number of ticks in the x-axis. :param bins: Number of ticks in the x-axis :return: None """ if self.normalticks: self.subplot1.tick_params(axis="x", labelsize=12) self.subplot1.tick_params(axis="y", labelsize=12) self.subplot1.xaxis.set_major_locator(MaxNLocator(nbins=bins)) self.repaint() def add_legend(self, location=1, anchor=None): """ Adds a legend to the plot. :param location: Integer code for location :return: None """ handles, labels = self.subplot1.get_legend_handles_labels() if anchor is None: anchor = (1, 1) if location == 1: self.subplot1.legend(handles, labels, loc=location, bbox_to_anchor=anchor) else: self.subplot1.legend(handles, labels, loc=location) self.repaint() def add_title(self, title=""): self.subplot1.set_title(title) self.repaint() def set_color(self, rgbtuple=None): """ Sets background color :param rgbtuple: background color :return: """ # Set figure and canvas colours to be the same if not rgbtuple: rgbtuple = [255., 255., 255.] col = [c / 255.0 for c in rgbtuple] self.figure.set_facecolor(col) self.figure.set_edgecolor(col) # self.canvas.SetBackgroundColour(wx.Colour(*rgbtuple)) def set_tickcolor(self): """ Sets tick colors based on the colormap set at self.cmap :return: None """ if self.cmap[:2] == "b'": self.cmap = self.cmap[2:-1] try: self.cmap = str(self.cmap, encoding="utf-8") except: pass output = cm.ScalarMappable(norm=None, cmap=str(self.cmap)).to_rgba(0) if sum(output[:2]) > 0.9: self.tickcolor = u"black" else: self.tickcolor = u"white" ''' if self.cmap[-1] == "r": self.tickcolor = "black" else: self.tickcolor = "white" ''' def size_handler(self, *args, **kwargs): """ Resizes the plots :param args: :param kwargs: :return: None """ if self.resize == 1: self.canvas.SetSize(self.GetSize()) def copy_to_clipboard(self, *args, **kwargs): obj = tempfile.NamedTemporaryFile(delete=False) self.canvas.print_figure(obj, format="png", dpi=300) obj.close() img = wx.Image(obj.name) btm = wx.Bitmap(img) bobj = wx.BitmapDataObject(btm) if wx.TheClipboard.Open(): wx.TheClipboard.SetData(bobj) # wx.TheClipboard.SetData(wx.TextDataObject("Test")) wx.TheClipboard.Close() print("Image Copied") os.remove(obj.name) def on_write_dialog(self, evt): """ Open a save figure dialog for specified plot. :param evt: wx.Event (unused) :return: None """ if self.data is not None: path = FileDialogs.save_file_dialog() if path is not None: self.write_data(path) else: print( "Data object empty. Plot likely unsupported for text file output." ) def write_data(self, path): if self.data is not None: print("Saving Data to", path) print("Data Dimensions:", self.data.shape) np.savetxt(path, self.data) def setup_zoom(self, plots, zoom, data_lims=None, pad=0, groups=None): """ Set up zoom on axes. :param plots: Axes objects to setup :param zoom: Type of zoom ('span' or 'box') :param data_lims: Optional manual description of the data limits (where to go when fully zoomed out) :param groups: Group of axes to link zoom together for :return: None """ # setup for zoom box if groups is None: groups = [1, 2, 3, 4, 5, 6, 7, 8] if zoom == 'span': self.zoom = ZoomSpan(plots, None, useblit=True, onmove_callback=None, rectprops=dict(alpha=0.2, facecolor='yellow')) if zoom == 'box': self.zoom = ZoomBox( plots, None, groups=groups, drawtype='box', useblit=True, button=1, # so zoombox is left button onmove_callback=None, spancoords='data', rectprops=dict(alpha=0.2, facecolor='yellow'), data_lims=data_lims, integrate=self.int, smash=self.smash, pad=pad) if zoom == "fixed_span": self.zoom = NoZoomSpan(plots, None, minspan=0, useblit=True, onmove_callback=None, rectprops=dict(alpha=0.2, facecolor='yellow')) '''