class MultithreadedApp: def __init__(self): #Gui bootstrap: window and progressbar self.builder = gtk.Builder() self.builder.add_from_file("polarisation_analyser.glade") self.builder.connect_signals(self) self.window = self.builder.get_object("window") self.main_fig = Figure() self.main_axes = self.main_fig.add_axes((0.1, 0.1, 0.8, 0.84)) t = np.linspace(0, 360, 361) self.line, = self.main_axes.plot( t, 0.5 * np.sin(3 * np.pi * t / 360) + 0.5) self.main_axes.set_ylim(0, 1) self.main_canvas = FigureCanvas(self.main_fig) self.builder.get_object("plot_container").add(self.main_canvas) self.sphere_fig = Figure() self.sphere_axes = Axes3D(self.sphere_fig) u = np.linspace(0, 2 * np.pi, 100) v = np.linspace(0, np.pi, 100) x = 1 * np.outer(np.cos(u), np.sin(v)) y = 1 * np.outer(np.sin(u), np.sin(v)) z = 1 * np.outer(np.ones(np.size(u)), np.cos(v)) self.sphere_axes.plot_wireframe(x, y, z, rstride=4, cstride=4, color='lightgreen', linewidth=1) self.sphere_canvas = FigureCanvas(self.sphere_fig) self.sphere_axes.mouse_init() self.builder.get_object("sphere_container").add(self.sphere_canvas) self.s1 = self.s2 = self.s3 = self.dop = self.s0p = 0 #Creating and starting the thread self.pu = PlotUpdater(self) self.pu.start() gtk.idle_add(self.update_plot) self.window.show_all() gtk.main() def update_plot(self): #self.sphere_axes.plot3D([0,self.s1],[0,self.s2],[0,self.s3]) #self.main_axes.relim() #Update axis limits #self.main_axes.autoscale_view() #Updat self.main_canvas.draw() #Redraw main image #self.sphere_canvas.draw() return True def on_window_destroy(self, widget): self.pu.stop() gtk.main_quit()
class MultithreadedApp: def __init__(self): #Gui bootstrap: window and progressbar self.builder = gtk.Builder() self.builder.add_from_file("polarisation_analyser.glade") self.builder.connect_signals(self) self.window = self.builder.get_object("window") self.main_fig = Figure() self.main_axes = self.main_fig.add_axes((0.1,0.1,0.8,0.84)) t = np.linspace(0,360,361) self.line, = self.main_axes.plot(t,0.5*np.sin(3*np.pi*t/360)+0.5) self.main_axes.set_ylim(0,1 ) self.main_canvas = FigureCanvas(self.main_fig) self.builder.get_object("plot_container").add(self.main_canvas) self.sphere_fig = Figure() self.sphere_axes = Axes3D(self.sphere_fig) u = np.linspace(0, 2 * np.pi, 100) v = np.linspace(0, np.pi, 100) x = 1 * np.outer(np.cos(u), np.sin(v)) y = 1 * np.outer(np.sin(u), np.sin(v)) z = 1 * np.outer(np.ones(np.size(u)), np.cos(v)) self.sphere_axes.plot_wireframe(x, y, z, rstride=4, cstride=4, color='lightgreen',linewidth=1) self.sphere_canvas = FigureCanvas(self.sphere_fig) self.sphere_axes.mouse_init() self.builder.get_object("sphere_container").add(self.sphere_canvas) self.s1 = self.s2 = self.s3 = self.dop = self.s0p = 0 #Creating and starting the thread self.pu = PlotUpdater(self) self.pu.start() gtk.idle_add(self.update_plot) self.window.show_all() gtk.main() def update_plot(self): #self.sphere_axes.plot3D([0,self.s1],[0,self.s2],[0,self.s3]) #self.main_axes.relim() #Update axis limits #self.main_axes.autoscale_view() #Updat self.main_canvas.draw() #Redraw main image #self.sphere_canvas.draw() return True def on_window_destroy(self, widget): self.pu.stop() gtk.main_quit()
class EditAtomTypeView(BaseView): builder = resource_filename(__name__, "glade/atoms.glade") top = "edit_atom_type" widget_format = "atom_%s" # ------------------------------------------------------------ # Initialisation and other internals # ------------------------------------------------------------ def __init__(self, *args, **kwargs): BaseView.__init__(self, *args, **kwargs) self.graph_parent = self["view_graph"] self.setup_matplotlib_widget() def setup_matplotlib_widget(self): style = gtk.Style() self.figure = Figure(dpi=72, edgecolor=str(style.bg[2]), facecolor=str(style.bg[2])) self.plot = self.figure.add_subplot(111) self.figure.subplots_adjust(bottom=0.20) self.matlib_canvas = FigureCanvasGTK(self.figure) self.plot.autoscale_view() self.graph_parent.add(self.matlib_canvas) self.graph_parent.show_all() # ------------------------------------------------------------ # Methods & Functions # ------------------------------------------------------------ def update_figure(self, x, y): self.plot.cla() self.plot.plot(x, y, 'k-', aa=True) self.plot.set_ylabel('Scattering factor', size=14, weight="heavy") self.plot.set_xlabel('2θ', size=14, weight="heavy") self.plot.autoscale_view() if self.matlib_canvas is not None: self.matlib_canvas.draw()
class EditAtomTypeView(BaseView): builder = resource_filename(__name__, "glade/atoms.glade") top = "edit_atom_type" widget_format = "atom_%s" # ------------------------------------------------------------ # Initialisation and other internals # ------------------------------------------------------------ def __init__(self, *args, **kwargs): BaseView.__init__(self, *args, **kwargs) self.graph_parent = self["view_graph"] self.setup_matplotlib_widget() def setup_matplotlib_widget(self): style = gtk.Style() self.figure = Figure(dpi=72, edgecolor=str(style.bg[2]), facecolor=str(style.bg[2])) self.plot = self.figure.add_subplot(111) self.figure.subplots_adjust(bottom=0.20) self.matlib_canvas = FigureCanvasGTK(self.figure) self.plot.autoscale_view() self.graph_parent.add(self.matlib_canvas) self.graph_parent.show_all() # ------------------------------------------------------------ # Methods & Functions # ------------------------------------------------------------ def update_figure(self, x, y): self.plot.cla() self.plot.plot(x, y, 'k-', aa=True) self.plot.set_ylabel('Scattering factor', size=14, weight="heavy") self.plot.set_xlabel('2θ', size=14, weight="heavy") self.plot.autoscale_view() if self.matlib_canvas is not None: self.matlib_canvas.draw()
class EditCSDSDistributionView(BaseView): builder = resource_filename(__name__, "glade/csds.glade") top = "tbl_csds_distr" def __init__(self, *args, **kwargs): BaseView.__init__(self, *args, **kwargs) self.graph_parent = self["distr_plot_box"] self.setup_matplotlib_widget() def setup_matplotlib_widget(self): style = gtk.Style() self.figure = Figure(dpi=72, edgecolor=str(style.bg[2]), facecolor=str(style.bg[2])) self.plot = self.figure.add_subplot(111) self.figure.subplots_adjust(bottom=0.20) self.matlib_canvas = FigureCanvasGTK(self.figure) self.plot.autoscale_view() self.graph_parent.add(self.matlib_canvas) self.graph_parent.show_all() def update_figure(self, distr): self.plot.cla() self.plot.hist(list(range(len(distr))), len(distr), weights=distr, normed=1, ec='b', histtype='stepfilled') self.plot.set_ylabel('') self.plot.set_xlabel('CSDS', size=14, weight="heavy") self.plot.relim() self.plot.autoscale_view() if self.matlib_canvas is not None: self.matlib_canvas.draw() def reset_params(self): tbl = self["tbl_params"] for child in tbl.get_children(): tbl.remove(child) tbl.resize(1, 2) def add_param_widget(self, name, label, minimum, maximum): tbl = self["tbl_params"] rows = tbl.get_property("n-rows") + 1 tbl.resize(rows, 2) lbl = gtk.Label(label) lbl.set_alignment(1.0, 0.5) tbl.attach(lbl, 0, 1, rows - 1, rows, gtk.FILL, gtk.FILL) inp = ScaleEntry(minimum, maximum, enforce_range=True) tbl.attach(inp, 1, 2, rows - 1, rows, gtk.FILL, gtk.FILL) tbl.show_all() self[name] = inp inp.set_name(name) return inp
class Plot(Figure): def __init__(self, x_name, y_name, *args, **kwargs): Figure.__init__(self, *args, **kwargs) self.plot_axes = self.add_subplot(111, xlabel=x_name, ylabel=y_name.upper()) self.plot_line = None self.canvas = FigureCanvas(self) self.plot_xname = x_name self.plot_yname = y_name self.plot_xdata = [] self.plot_ydata = [] self.plot_line, = self.plot_axes.plot(self.plot_xdata, self.plot_ydata) self.plot_max_points = 200 def get_plot_line(self): return self.plot_line def get_canvas(self): return self.canvas def get_plot_var(self): return self.plot_yname def get_max_points(self): return self.plot_max_points def set_max_points(self, max_points): self.plot_max_points = max_points def __update_canvas(self): self.plot_axes.relim() self.plot_axes.autoscale_view(tight=False) if self.canvas is not None: self.canvas.draw() return False def update_plot(self, simThread, acquireLock=True): self.plot_xdata.append(simThread.var(self.plot_xname)) self.plot_ydata.append(simThread.var(self.plot_yname)) if len(self.plot_xdata) > self.plot_max_points: offset = len(self.plot_xdata) - self.plot_max_points self.plot_xdata = self.plot_xdata[offset:] if len(self.plot_ydata) > self.plot_max_points: offset = len(self.plot_ydata) - self.plot_max_points self.plot_ydata = self.plot_ydata[offset:] self.redraw_plot(acquireLock) def clear_plot(self, acquireLock=True): self.plot_xdata = [] self.plot_ydata = [] self.redraw_plot(acquireLock) def redraw_plot(self, acquireLock=True): self.plot_line.set_xdata(self.plot_xdata) self.plot_line.set_ydata(self.plot_ydata) if self.canvas is not None: if acquireLock: gtk.gdk.threads_enter() gobject.idle_add(self.__update_canvas) gtk.gdk.threads_leave() else: gobject.idle_add(self.__update_canvas)
class Backend( backend.Backend ): def init(self): self.layer_to_axes = {} self.axes_to_layer = {} self.layers_cache = [] # copy of self.plot.layers self.layer_cblists = {} self.line_caches = {} self.omaps = {} def connect(self): logger.debug("Opening matplotlib session.") self.figure = Figure(dpi=100, facecolor="white") # figsize=(5,4), dpi=100) self.canvas = FigureCanvas(self.figure) self.canvas.show() self.line_caches = {} self.layer_to_axes.clear() self.axes_to_layer.clear() backend.Backend.connect(self) logger.debug("Init finished") def set(self, project,plot): backend.Backend.set(self, project, plot) if self.project is not None: # TODO: connect to notify::layers of Plot pass def disconnect(self): logger.debug("Closing matplotlib session.") if not self.canvas is None: self.canvas.destroy() self.canvas = None if not self.figure is None: self.figure = None backend.Backend.disconnect(self) #---------------------------------------------------------------------- def arrange(self, rows=1, cols=1): layers = self.plot.layers n = len(layers) if n > (rows*cols): rows = int((rows*cols) / n) + 1 cols = rows * n #raise ValueError("Not enough rows and cols for all layers!") self.figure.clear() self.figure.axes = [] self.layer_to_axes.clear() self.axes_to_layer.clear() self.layers_cache = [] for cblist in self.layer_cblists.itervalues(): for cb in cblist: cb.disconnect() self.layer_cblists = {} j = 1 for layer in layers: print "Setting up layer", layer axes = self.figure.add_subplot("%d%d%d" % (rows,cols,j)) self.layer_to_axes[layer] = axes self.axes_to_layer[axes] = layer self.layers_cache.append(layer) print "Connecting to notify of ", layer self.layer_cblists[layer] = \ [layer.sig_connect('notify', self.on_update_layer), layer.sig_connect('notify::labels', self.on_update_labels) ] j += 1 def draw(self): self.check_connection() logger.debug("Matplotlib: draw()") if self.plot.layers != self.layers_cache: self.arrange() self.omaps = {} for layer in self.plot.layers: self.update_layer(layer) self.draw_canvas() def draw_canvas(self): self.canvas.draw() #---------------------------------------------------------------------- # Layer # def on_update_layer(self, sender, updateinfo={}): # updateinfo is ignored self.update_layer(sender) self.canvas.draw() def update_layer(self, layer, updateinfo={}): # updateinfo is ignored self.omaps[layer] = {} self.line_caches[layer] = {} axes = self.layer_to_axes[layer] axes.lines = [] line_cache = self.line_caches[layer] = [] #:layer.lines:OK for line in layer.lines: self.update_line(line, layer, axes=axes) #:layer.axes for (key, axis) in layer.axes.iteritems(): #:axis.label #:axis.scale #:axis.start #:axis.end label = axis.label scale = axis.scale start = axis.start end = axis.end #logger.debug("start = %s; end = %s" % (start, end)) if key == 'x': set_label = axes.set_xlabel set_scale = axes.set_xscale set_start = (lambda l: axes.set_xlim(xmin=l)) set_end = (lambda l: axes.set_xlim(xmax=l)) elif key == 'y': set_label = axes.set_ylabel set_scale = axes.set_yscale set_start = (lambda l: axes.set_ylim(ymin=l)) set_end = (lambda l: axes.set_ylim(ymax=l)) else: raise RuntimeError("Invalid axis key '%s'" % key) if label is not None: set_label(label) if scale is not None: set_scale(scale) if start is not None: set_start(start) if end is not None: set_end(end) #:layer.visible if layer.visible is False: return # TODO #:layer.title title = layer.title if title is not None: axes.set_title(title) #:layer.grid axes.grid(layer.grid) #:layer.legend:OK self.update_legend(layer) #:layer.labels:OK axes.texts = [] for label in layer.labels: self.update_textlabel(label, layer) #---------------------------------------------------------------------- # Line # def update_line(self, line, layer, axes=None, updateinfo={}): # updateinfo is ignored axes = axes or self.layer_to_axes[layer] omap = self.omaps[layer] line_cache = self.line_caches[layer] data_to_plot = [] #:line.visible if line.visible is False: if line in axes.lines: axes.lines.remove(line) line_cache.remove(line) omap[line] = None return ds = self.get_line_source(line) cx, cy = self.get_column_indices(line) try: xdata, ydata = self.get_dataset_data(ds, cx, cy) except backend.BackendError, msg: logger.error(msg) omap[line] = None return #:line.row_first #:line.row_last start, end = line.row_first, line.row_last try: xdata = self.limit_data(xdata, start, end) ydata = self.limit_data(ydata, start, end) except BackendError, msg: logger.error("Error when plotting line #%d: %s" % (line_index, msg)) omap[line] = None return