class Backend(backend.Backend): def init(self): self.painters = {} # == layers def connect(self): self.figure = Figure(dpi=100, facecolor="white") self.canvas = FigureCanvas(self.figure) backend.Backend.connect(self) def disconnect(self): if self.canvas is not None: self.canvas.destroy() self.canvas = None if self.figure is not None: self.figure = None backend.Backend.disconnect(self) def get_painter(self, obj, klass): _id = id(obj) if self.painters.has_key(_id) is False: self.painters[_id] = klass(obj, parent=self) return self.painters[_id] def draw(self): for layer in self.plot.layers: painter = self.get_painter(layer, LayerPainter) painter.paint()
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 PlotWidget(Widgets.WidgetBase): def __init__(self, plot, width=500, height=500): super(PlotWidget, self).__init__() self.widget = FigureCanvas(plot.get_figure()) self.plot = plot self.widget.set_size_request(width, height) self.widget.show_all() def configure_window(self, wd, ht): self.logger.debug("canvas resized to %dx%d" % (wd, ht)) fig = self.plot.get_figure() fig.set_size_inches(float(wd) / fig.dpi, float(ht) / fig.dpi)
def __init__(self, model, axis, fields, axis_data={}, attrs={}): self.widget = gtk.HBox() self._figure = Figure(figsize=(800, 600), dpi=100, facecolor="w") self._subplot = self._figure.add_subplot(111, axisbg="#eeeeee") self._canvas = FigureCanvas(self._figure) self.widget.pack_start(self._canvas, expand=True, fill=True) if attrs.get("type", "pie") == "bar": if attrs.get("orientation", "vertical") == "vertical": self._figure.subplots_adjust(left=0.08, right=0.98, bottom=0.25, top=0.98) else: self._figure.subplots_adjust(left=0.20, right=0.97, bottom=0.07, top=0.98) else: self._figure.subplots_adjust(left=0.03, right=0.97, bottom=0.03, top=0.97) self.fields = fields self.model = model self.axis = axis self.old_axis = axis self.editable = False self.key = False self.widget.editable = False self.axis_data = axis_data self.axis_group = {} for i in self.axis_data: self.axis_data[i]["string"] = self.fields[i]["string"] self.axis_data[i]["type"] = self.fields[i]["type"] if self.axis_data[i].get("group", False): self.axis_group[i] = 1 self.axis.remove(i) self.attrs = attrs
def __init__(self, model, axis, fields, axis_data={}, attrs={}): self.widget = gtk.HBox() self._figure = Figure(figsize=(800,600), dpi=100, facecolor='w') self._subplot = self._figure.add_subplot(111,axisbg='#eeeeee') self._canvas = FigureCanvas(self._figure) self.widget.pack_start(self._canvas, expand=True, fill=True) if attrs.get('type', 'pie')=='bar': if attrs.get('orientation', 'vertical')=='vertical': self._figure.subplots_adjust(left=0.08,right=0.98,bottom=0.25,top=0.98) else: self._figure.subplots_adjust(left=0.20,right=0.97,bottom=0.07,top=0.98) else: self._figure.subplots_adjust(left=0.03,right=0.97,bottom=0.03,top=0.97) self.fields = fields self.model = model self.axis = axis self.old_axis = axis self.editable = False self.key = False self.widget.editable = False self.axis_data = axis_data self.axis_group = {} for i in self.axis_data: self.axis_data[i]['string'] = self.fields[i]['string'] self.axis_data[i]['type'] = self.fields[i]['type'] if self.axis_data[i].get('group', False): self.axis_group[i]=1 self.axis.remove(i) self.attrs = attrs
def __init__(self, plot, width=500, height=500): super(PlotWidget, self).__init__() self.widget = FigureCanvas(plot.get_figure()) self.plot = plot self.widget.set_size_request(width, height) self.widget.show_all()
def __init__(self,gtkWindow,eventPipe): self.objects = {} self.window = gtkWindow self.eventPipe = eventPipe fileName = 'funo.brd' print "Loading PCB %s"%(fileName,) self.table = gtk.Table(rows=12, columns=1, homogeneous=True) window.add(self.table) self.table.show() self.pcb = PCB(fileName,usingMouse=noTracking,multimeter=multimeterObj, x=pcb_x, y=pcb_y, modeupdate=self.set_status_mode) self.table.attach(self.pcb, left_attach = 0, right_attach = 1, top_attach = 0, bottom_attach = 6, xpadding=0, ypadding=0) self.pcb.show( ) f = Figure(figsize=(5,4), dpi=100, facecolor='white') a = f.add_subplot(211) b = f.add_subplot(212) #t1 = arange(0.0, 3.0, 0.01) #t2 = arange(0.0, 5.0, 0.01) #s1 = sin(2*pi*t1) #s2 = sin(2*pi*t2) #a.plot(t1, s1) f.tight_layout() self.plot_figure = f self.top_plot = a self.bottom_plot = b canvas = FigureCanvas(f) self.table.attach(canvas, left_attach = 0, right_attach = 1, top_attach = 6, bottom_attach = 11, xpadding=0, ypadding=0) canvas.show() self.canvas = canvas self.status_bar = gtk.Statusbar() self.table.attach(self.status_bar, left_attach = 0, right_attach = 1, top_attach = 11, bottom_attach = 12, xpadding=0, ypadding=0) self.status_bar.show() self.cid = self.status_bar.get_context_id('') self.status_bar.push(self.cid,'Operation Mode: select')
def init_barchart(self): fig = Figure(facecolor='w') ax = fig.add_subplot(211,axisbg=NiceColors.lightgrey) self.bar_ax = ax self.err_ax = fig.add_subplot(212,axisbg=NiceColors.lightgrey) self.bar_canvas = FigureCanvas(fig) # a gtk.DrawingArea self.bar_canvas.show() self.barchart_box.pack_start(self.bar_canvas)
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()
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 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()
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()
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")
class Backend(backend.Backend): active_layer_painter = Instance(LayerPainter, init=None) def init(self): self.painters = {} # == layers self._redraw = False self._block_redraw = 0 self.sig_register('redraw') self.sig_connect('redraw', lambda sender: self.redraw()) def connect(self): self.figure = Figure(dpi=100, facecolor="white") self.canvas = FigureCanvas(self.figure) backend.Backend.connect(self) def disconnect(self): if self.canvas is not None: self.canvas.destroy() self.canvas = None if self.figure is not None: self.figure = None backend.Backend.disconnect(self) def get_painter(self, obj, klass=None): _id = id(obj) try: return self.painters[_id] except KeyError, msg: if klass is not None: new_painter = klass(obj, parent=self) self.painters[_id] = new_painter return new_painter else: raise
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 __init__(self, logger): Callback.Callbacks.__init__(self) self.logger = logger # For callbacks for name in ('close', ): self.enable_callback(name) self.fig = matplotlib.figure.Figure() self.ax = self.fig.add_subplot(111) self.ax.set_xlabel('X values') self.ax.set_ylabel('Y values') self.ax.set_title('') self.ax.grid(True) self.canvas = FigureCanvas(self.fig) self.canvas.show_all()
def __init__(self, logger): Callback.Callbacks.__init__(self) self.logger = logger # For callbacks for name in ('close', ): self.enable_callback(name) self.fig = matplotlib.figure.Figure() self.ax = self.fig.add_subplot(111) self.ax.set_xlabel('X values') self.ax.set_ylabel('Y values') self.ax.set_title('') self.ax.grid(True) self.canvas = FigureCanvas(self.fig) self.canvas.show_all()
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 __init__(self, model, axis, fields, axis_data={}, attrs={}): self.widget = gtk.HBox() self._figure = Figure(figsize=(800, 600), dpi=100, facecolor='w') self._subplot = self._figure.add_subplot(111, axisbg='#eeeeee') self._canvas = FigureCanvas(self._figure) self.widget.pack_start(self._canvas, expand=True, fill=True) if attrs.get('type', 'pie') == 'bar': if attrs.get('orientation', 'vertical') == 'vertical': self._figure.subplots_adjust(left=0.08, right=0.98, bottom=0.25, top=0.98) else: self._figure.subplots_adjust(left=0.20, right=0.97, bottom=0.07, top=0.98) else: self._figure.subplots_adjust(left=0.03, right=0.97, bottom=0.03, top=0.97) self.fields = fields self.model = model self.axis = axis self.old_axis = axis self.editable = False self.key = False self.widget.editable = False self.axis_data = axis_data self.axis_group = {} for i in self.axis_data: self.axis_data[i]['string'] = self.fields[i]['string'] self.axis_data[i]['type'] = self.fields[i]['type'] if self.axis_data[i].get('group', False): self.axis_group[i] = 1 self.axis.remove(i) self.attrs = attrs
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()
class ViewGraph(object): def __init__(self, model, axis, fields, axis_data={}, attrs={}): self.widget = gtk.HBox() self._figure = Figure(figsize=(800, 600), dpi=100, facecolor="w") self._subplot = self._figure.add_subplot(111, axisbg="#eeeeee") self._canvas = FigureCanvas(self._figure) self.widget.pack_start(self._canvas, expand=True, fill=True) if attrs.get("type", "pie") == "bar": if attrs.get("orientation", "vertical") == "vertical": self._figure.subplots_adjust(left=0.08, right=0.98, bottom=0.25, top=0.98) else: self._figure.subplots_adjust(left=0.20, right=0.97, bottom=0.07, top=0.98) else: self._figure.subplots_adjust(left=0.03, right=0.97, bottom=0.03, top=0.97) self.fields = fields self.model = model self.axis = axis self.old_axis = axis self.editable = False self.key = False self.widget.editable = False self.axis_data = axis_data self.axis_group = {} for i in self.axis_data: self.axis_data[i]["string"] = self.fields[i]["string"] self.axis_data[i]["type"] = self.fields[i]["type"] if self.axis_data[i].get("group", False): self.axis_group[i] = 1 self.axis.remove(i) self.attrs = attrs def display(self, models): datas = [] self.axis = copy.copy(self.old_axis) group_by = self.widget.screen.context.get("group_by", False) if group_by: if not self.key: del self.widget.screen.context["group_by"] self.key = True self.widget.screen.search_filter() models = self.widget.screen.models self.widget.screen.context["group_by"] = group_by self.axis[0] = group_by[0] self.axis_data[group_by[0]] = {} # This is to get the missing field. if the field is not available in the graph view # for use case :graph view loaded directly from a dashboard and user executes groupby if self.axis[0] not in models.mfields: missing_gb_field = rpc.session.rpc_exec_auth( "/object", "execute", self.model, "fields_get", [self.axis[0]], {} ) if missing_gb_field: models.add_fields(missing_gb_field, models) for m in models: res = {} for x in self.axis_data.keys(): if not self.axis_data[x]: self.axis_data[x] = self.fields[x] field_val = m[x].get_client(m) if self.fields[x]["type"] in ("many2one", "char", "time", "text"): res[x] = field_val and str(field_val) or "Undefined" elif self.fields[x]["type"] == "selection": selection = dict(m[x].attrs["selection"]) if field_val: val = str(field_val) res[x] = selection.get(val, val) else: res[x] = "Undefined" elif self.fields[x]["type"] == "date": if field_val: res[x] = datetime_util.server_to_local_timestamp( field_val, DT_FORMAT, user_locale_format.get_date_format(), tz_offset=False ) else: res[x] = "Undefined" elif self.fields[x]["type"] == "datetime": if field_val: res[x] = datetime_util.server_to_local_timestamp( field_val, DHM_FORMAT, user_locale_format.get_datetime_format(True) ) else: res[x] = "Undefined" else: res[x] = field_val and float(field_val) or 0.0 datas.append(res) tinygraph.tinygraph( self._subplot, self.attrs.get("type", "pie"), self.axis, self.axis_data, datas, axis_group_field=self.axis_group, orientation=self.attrs.get("orientation", "vertical"), ) # the draw function may generate exception but it is not a problem as it will be redraw latter try: self._subplot.draw(None) # XXX it must have some better way to force the redraw but this one works self._canvas.queue_resize() except: pass def destroy(self): pass
class ViewGraph(object): def __init__(self, model, axis, fields, axis_data={}, attrs={}): self.widget = gtk.HBox() self._figure = Figure(figsize=(800, 600), dpi=100, facecolor='w') self._subplot = self._figure.add_subplot(111, axisbg='#eeeeee') self._canvas = FigureCanvas(self._figure) self.widget.pack_start(self._canvas, expand=True, fill=True) if attrs.get('type', 'pie') == 'bar': if attrs.get('orientation', 'vertical') == 'vertical': self._figure.subplots_adjust(left=0.08, right=0.98, bottom=0.25, top=0.98) else: self._figure.subplots_adjust(left=0.20, right=0.97, bottom=0.07, top=0.98) else: self._figure.subplots_adjust(left=0.03, right=0.97, bottom=0.03, top=0.97) self.fields = fields self.model = model self.axis = axis self.editable = False self.widget.editable = False self.axis_data = axis_data self.axis_group = {} for i in self.axis_data: self.axis_data[i]['string'] = self.fields[i]['string'] if self.axis_data[i].get('group', False): self.axis_group[i] = 1 self.axis.remove(i) self.attrs = attrs def display(self, models): datas = [] for m in models: res = {} for x in self.axis_data.keys(): if self.fields[x]['type'] in ('many2one', 'char', 'time', 'text'): res[x] = str(m[x].get_client(m)) elif self.fields[x]['type'] == 'selection': selection = dict(m[x].attrs['selection']) val = str(m[x].get_client(m)) res[x] = selection.get(val, val) elif self.fields[x]['type'] == 'date': if m[x].get_client(m): date = time.strptime(m[x].get_client(m), DT_FORMAT) res[x] = time.strftime(LDFMT, date) else: res[x] = '' elif self.fields[x]['type'] == 'datetime': if m[x].get_client(m): date = time.strptime(m[x].get_client(m), DHM_FORMAT) if rpc.session.context.get('tz'): try: lzone = pytz.timezone( rpc.session.context['tz']) szone = pytz.timezone(rpc.session.timezone) dt = DT.datetime(date[0], date[1], date[2], date[3], date[4], date[5], date[6]) sdt = szone.localize(dt, is_dst=True) ldt = sdt.astimezone(lzone) date = ldt.timetuple() except pytz.UnknownTimeZoneError: # Timezones are sometimes invalid under Windows # and hard to figure out, so as a low-risk fix # in stable branch we will simply ignore the # exception and consider client in server TZ # (and sorry about the code duplication as well, # this is fixed properly in trunk) pass res[x] = time.strftime(LDFMT + ' %H:%M:%S', date) else: res[x] = '' else: res[x] = float(m[x].get_client(m)) datas.append(res) tinygraph.tinygraph(self._subplot, self.attrs.get('type', 'pie'), self.axis, self.axis_data, datas, axis_group_field=self.axis_group, orientation=self.attrs.get('orientation', 'vertical')) # the draw function may generate exception but it is not a problem as it will be redraw latter try: self._subplot.draw() #XXX it must have some better way to force the redraw but this one works self._canvas.queue_resize() except: pass
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 update::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 update of ", layer self.layer_cblists[layer] = \ [layer.sig_connect('update', self.on_update_layer), layer.sig_connect('update::labels', self.on_update_labels) ] j += 1
class ViewGraph(object): def __init__(self, model, axis, fields, axis_data={}, attrs={}): self.widget = gtk.HBox() self._figure = Figure(figsize=(800, 600), dpi=100, facecolor='w') self._subplot = self._figure.add_subplot(111, axisbg='#eeeeee') self._canvas = FigureCanvas(self._figure) self.widget.pack_start(self._canvas, expand=True, fill=True) if attrs.get('type', 'pie') == 'bar': if attrs.get('orientation', 'vertical') == 'vertical': self._figure.subplots_adjust(left=0.08, right=0.98, bottom=0.25, top=0.98) else: self._figure.subplots_adjust(left=0.20, right=0.97, bottom=0.07, top=0.98) else: self._figure.subplots_adjust(left=0.03, right=0.97, bottom=0.03, top=0.97) self.fields = fields self.model = model self.axis = axis self.old_axis = axis self.editable = False self.key = False self.widget.editable = False self.axis_data = axis_data self.axis_group = {} for i in self.axis_data: self.axis_data[i]['string'] = self.fields[i]['string'] self.axis_data[i]['type'] = self.fields[i]['type'] if self.axis_data[i].get('group', False): self.axis_group[i] = 1 self.axis.remove(i) self.attrs = attrs def display(self, models): datas = [] self.axis = copy.copy(self.old_axis) group_by = self.widget.screen.context.get('group_by', False) if group_by: if not self.key: del self.widget.screen.context['group_by'] self.key = True self.widget.screen.search_filter() models = self.widget.screen.models self.widget.screen.context['group_by'] = group_by self.axis[0] = group_by[0] self.axis_data[group_by[0]] = {} # This is to get the missing field. if the field is not available in the graph view # for use case :graph view loaded directly from a dashboard and user executes groupby if self.axis[0] not in models.mfields: missing_gb_field = rpc.session.rpc_exec_auth( '/object', 'execute', self.model, 'fields_get', [self.axis[0]], {}) if missing_gb_field: models.add_fields(missing_gb_field, models) for m in models: res = {} for x in self.axis_data.keys(): if not self.axis_data[x]: self.axis_data[x] = self.fields[x] field_val = m[x].get_client(m) if self.fields[x]['type'] in ('many2one', 'char', 'time', 'text'): res[x] = field_val and str(field_val) or 'Undefined' elif self.fields[x]['type'] == 'selection': selection = dict(m[x].attrs['selection']) if field_val: val = str(field_val) res[x] = selection.get(val, val) else: res[x] = 'Undefined' elif self.fields[x]['type'] == 'date': if field_val: res[x] = datetime_util.server_to_local_timestamp( field_val, DT_FORMAT, user_locale_format.get_date_format(), tz_offset=False) else: res[x] = 'Undefined' elif self.fields[x]['type'] == 'datetime': if field_val: res[x] = datetime_util.server_to_local_timestamp( field_val, DHM_FORMAT, user_locale_format.get_datetime_format(True)) else: res[x] = 'Undefined' else: res[x] = field_val and float(field_val) or 0.0 datas.append(res) tinygraph.tinygraph(self._subplot, self.attrs.get('type', 'pie'), self.axis, self.axis_data, datas, axis_group_field=self.axis_group, orientation=self.attrs.get('orientation', 'vertical')) # the draw function may generate exception but it is not a problem as it will be redraw latter try: self._subplot.draw(None) #XXX it must have some better way to force the redraw but this one works self._canvas.queue_resize() except: pass def destroy(self): pass
def __init__(self, gtkWindow, eventPipe): self.objects = {} self.window = gtkWindow self.eventPipe = eventPipe fileName = 'funo.brd' print "Loading PCB %s" % (fileName, ) self.table = gtk.Table(rows=12, columns=1, homogeneous=True) window.add(self.table) self.table.show() self.pcb = PCB(fileName, usingMouse=noTracking, multimeter=multimeterObj, x=pcb_x, y=pcb_y, modeupdate=self.set_status_mode) self.table.attach(self.pcb, left_attach=0, right_attach=1, top_attach=0, bottom_attach=4, xpadding=0, ypadding=0) self.pcb.show() f = Figure(figsize=(5, 4), dpi=100, facecolor='white') a = f.add_subplot(211) b = f.add_subplot(212) t1 = arange(0.0, 3.0, 0.01) t2 = arange(0.0, 5.0, 0.01) s1 = sin(2 * pi * t1) s2 = sin(2 * pi * t2) a.plot(t1, s1) a.set_title('Channel 1', fontsize=10) a.tick_params(labelsize=8) a.grid(True, which='both') b.plot(t2, s2) b.tick_params(labelsize=8) b.grid(True, which='both') b.set_title('Channel 2', fontsize=10) f.tight_layout() canvas = FigureCanvas(f) self.table.attach(canvas, left_attach=0, right_attach=1, top_attach=4, bottom_attach=11, xpadding=0, ypadding=0) canvas.show() self.status_bar = gtk.Statusbar() self.table.attach(self.status_bar, left_attach=0, right_attach=1, top_attach=11, bottom_attach=12, xpadding=0, ypadding=0) self.status_bar.show() self.cid = self.status_bar.get_context_id('') self.status_bar.push(self.cid, 'Operation Mode: select')
def connect(self): self.figure = Figure(dpi=100, facecolor="white") self.canvas = FigureCanvas(self.figure) backend.Backend.connect(self)
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 Plot(Callback.Callbacks): def __init__(self, logger): Callback.Callbacks.__init__(self) self.logger = logger # For callbacks for name in ('close', ): self.enable_callback(name) self.fig = matplotlib.figure.Figure() self.ax = self.fig.add_subplot(111) self.ax.set_xlabel('X values') self.ax.set_ylabel('Y values') self.ax.set_title('') self.ax.grid(True) self.canvas = FigureCanvas(self.fig) self.canvas.show_all() def get_widget(self): return self.canvas def getAxis(self): return self.ax def _sanity_check_window(self): pass def set_titles(self, xtitle=None, ytitle=None, title=None, rtitle=None): self._sanity_check_window() if xtitle != None: self.ax.set_xlabel(xtitle) if ytitle != None: self.ax.set_ylabel(ytitle) if title != None: self.ax.set_title(title) if rtitle != None: pass def clear(self): self._sanity_check_window() self.logger.debug('clearing canvas...') self.ax.cla() def show(self): self._sanity_check_window() self.logger.debug('raising window...') self.canvas.show() def hide(self): self._sanity_check_window() self.logger.debug('hiding window...') pass def close(self): self.logger.debug('closing window....') self.canvas.destroy() self.make_callback('close') return False def _draw(self): self.fig.canvas.draw() def plot(self, xarr, yarr, xtitle=None, ytitle=None, title=None, rtitle=None, color=None, alpha=1.0): self.set_titles(xtitle=xtitle, ytitle=ytitle, title=title, rtitle=rtitle) if not color: self.ax.plot(xarr, yarr, linewidth=1.0, alpha=alpha, linestyle='-') else: self.ax.plot(xarr, yarr, linewidth=1.0, color=color, alpha=alpha, linestyle='-') self.ax.grid(True) self._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 ColViewer: def __init__(self, coldir=None): self.equalize = False self.equalize_cutoff = 20 self.data_binary = True self.n_values = 2 self.n_bins = 10 self.n_bins_desired = self.n_bins self.tgt2color = {} builder = gtk.Builder() xmlfile = os.path.join(os.path.split(sys.argv[0])[0], "colviewer_main_window.xml") builder.add_from_file(xmlfile) self.window = builder.get_object("window") print builder.connect_signals(self) self.logbuffer = builder.get_object("textbuffer_info") # GtkTextBuffer self.append_to_log("initialized") self.coldir = coldir if not self.coldir: self.coldir = os.getcwd() self.filelist = builder.get_object("list_files") # GtkListStore self.fill_filelist() # scale and spinbutton to set number of bins self.n_bins_scale = builder.get_object("hscale_nbins") # GtkHScale self.n_bins_spinb = builder.get_object("spinbutton_nbins") # GtkSpinButton self.set_nbins_sensible() # label showing target filename self.target_label = builder.get_object("label_target_filename") self.barchart_box = builder.get_object("box_barchart") # GtkVBox self.init_barchart() ### GUI Tools ### def set_target_filename(self, filename): self.target_label.set_text(os.path.split(filename)[-1]) self.target_label.set_tooltip_text(filename) def update_barchart(self): self.histogram() self.plot_barchart() self.plot_errorbars() self.bar_canvas.draw() def fill_filelist(self): files = os.listdir(self.coldir) for filename in sorted(files): if filename.startswith("."): continue self.filelist.append([filename]) def append_to_log(self, text): self.logbuffer.insert(self.logbuffer.get_end_iter(),'# ' + text + "\n") def set_nbins_sensible(self): """ activate or deactivate interface elements that only make sense for data with binary / non-binary values """ self.n_bins_scale.set_sensitive(not self.data_binary) self.n_bins_spinb.set_sensitive(not self.data_binary) def show(self): self.window.show() ### Plotting ### def init_barchart(self): fig = Figure(facecolor='w') ax = fig.add_subplot(211,axisbg=NiceColors.lightgrey) self.bar_ax = ax self.err_ax = fig.add_subplot(212,axisbg=NiceColors.lightgrey) self.bar_canvas = FigureCanvas(fig) # a gtk.DrawingArea self.bar_canvas.show() self.barchart_box.pack_start(self.bar_canvas) def get_layers(self): " return one layer for each target in sorted order " for tgt in sorted(self.data.keys()): cnt = Counter(bin_id for val, bin_id in self.data[tgt]) layer = [cnt[b] for b in range(self.n_bins)] if self.equalize: mult = self.get_equalize_multiplicator() assert len(mult) == len(layer) layer = [c*f for c, f in zip(layer, mult)] yield (tgt, layer) def get_locations(self, limits): " locations of bars are in the middle between lower and upper bound" return [(u+l)/2.0 for l,u in izip(limits[:-1], limits[1:])] def get_width(self, locations=None, gap_factor=1.0): if locations == None: locations = self.get_locations(self.limits) if len(locations) < 3: return 1.0 return gap_factor * min( (l2-l1) for l1, l2 in zip(locations[:-1], locations[1:]) ) def get_equalize_multiplicator(self): return [1./float(c) if c > self.equalize_cutoff else 0. for c in self.col_counts] def plot_errorbars(self): #print len(locations) , len(self.cols) self.err_ax.cla() assert len(self.locations) == len(self.cols) err = [np.std(c) for c in self.cols] means = [np.mean(c) for c in self.cols] self.err_ax.errorbar(self.locations, means, yerr=err, ecolor="black") self.err_ax.set_xbound( self.bar_ax.get_xbound() ) self.err_ax.yaxis.grid(True) #for l,m,e in izip(self.locations, means, err): # self.err_ax.errorbar(l, m, yerr=e, ecolor="black") def plot_barchart(self): self.bar_ax.cla() assert len(self.limits) == self.n_bins + 1, "mismatch n_bins and limits" self.locations = self.get_locations(self.limits) width = self.get_width(self.locations, 0.8) colormap = NiceColors.cmap bottom = [0] * self.n_bins for tgt, layer in self.get_layers(): assert len(layer) == len(bottom) color = colormap(self.normalize(tgt, self.min_tgt, self.max_tgt)) self.bar_ax.bar(self.locations, layer, width, color=color, bottom=bottom, linewidth=0, align='center') bottom = [b+c for b,c in zip(bottom, layer)] #ax.set_xticks((0.0,1.0)) #ax.set_yticks([0,25,50,75,100],minor=False) #ax.yaxis.grid(True) #ax.set_xticklabels(('0', '1')) if self.equalize: self.bar_ax.set_ybound(lower=0.0, upper=1.05) ### Signal Handling ### def on_window_destroy(self, widget, data=None): gtk.main_quit() def on_treeview_filenames_cursor_changed(self, treeview): treeselection = treeview.get_selection() (treemodel, treeiter) = treeselection.get_selected() col = 0 filename = treemodel.get_value(treeiter, col) self.load_col(filename) def on_adjustment_nbins_value_changed(self, adjustment): self.n_bins_desired = int(adjustment.get_value()) self.update_barchart() def on_check_equal_toggled(self, checkbutton): self.equalize = checkbutton.get_active() self.update_barchart() ### Data Handling ### def load_bincol(self, filename): self.data = map(int, map(float,open(filename))) def load_col(self, filename): fname = os.path.join(self.coldir, filename) self.raw_data = [float(l) for l in open(fname) if l.strip()] if len(self.raw_data) > len(self.target): sys.stdout.write("WARN: more data than targets (%s vs %s)\n" %(len(self.raw_data), len(self.target))) self.raw_data = self.raw_data[:len(self.target)] self.n_values = len(set(self.raw_data)) self.data_binary = self.n_values == 2 self.set_nbins_sensible() self.append_to_log("loaded %s lines containing %s uniq values" %(len(self.raw_data), self.n_values)) if self.data_binary: self.append_to_log("%s zeros, %s ones" %(self.raw_data.count(0.0), self.raw_data.count(1.0))) self.update_barchart() def read_target(self, filename): # self.target = map(int, map(float, open(filename))) self.target = map(float, open(filename)) self.n_classes = len(set(self.target)) self.append_to_log("loaded target: %s lines containing %s classes" %(len(self.target), self.n_classes)) self.set_target_filename(filename) self.min_tgt = min(self.target) self.max_tgt = max(self.target) # redo histogram if data already read def reset_data(self): self.data = dict( (tgt, []) for tgt in set(self.target) ) ### Histogram ### def find_bin(self, val, bins): """ bins are given as bins=[x1 x2 x3 x4] returns largest i such that val <= bins[i+1] """ nbins = len(bins) assert nbins >= 2, "%s does not specify proper intervals" %(bins) assert val <= bins[-1], "value larger than end of last interval" assert val >= bins[0], "value smaller than start of first interval" for i in range(nbins-1): if val < bins[i+1]: assert val >= bins[i] return i return nbins - 2 def histogram(self): """ make histogram and update self.data with bin infos """ self.reset_data() self.n_bins = min(self.n_values, self.n_bins_desired) n, bins, patches = self.bar_ax.hist(self.raw_data, self.n_bins) self.col_counts = n self.cols = [[] for c in range(self.n_bins)] for val, tgt in izip(self.raw_data, self.target): bin_id = self.find_bin(val, bins) assert bin_id <= self.n_bins, "%s > %s" %(bin_id, self.n_bins) self.data[tgt].append((val, bin_id)) self.cols[bin_id].append(tgt) self.limits = bins def normalize(self, value, min_val=0.0, max_val=1.0): return float(value-min_val)/(max_val-min_val)
def build_gui(self, container): self.pickcenter = None vpaned = gtk.VPaned() nb = gtk.Notebook() #nb.set_group_id(group) #nb.connect("create-window", self.detach_page, group) nb.set_tab_pos(gtk.POS_RIGHT) nb.set_scrollable(True) nb.set_show_tabs(True) nb.set_show_border(False) self.w.nb1 = nb vpaned.pack1(nb, resize=True, shrink=True) cm, im = self.fv.cm, self.fv.im di = FitsImageCanvasGtk.FitsImageCanvas(logger=self.logger) di.enable_autozoom('off') di.enable_autocuts('off') di.enable_zoom(True) di.enable_cuts(True) di.zoom_to(3, redraw=False) di.set_callback('zoom-set', self.zoomset) di.set_cmap(cm, redraw=False) di.set_imap(im, redraw=False) di.set_callback('motion', self.detailxy) di.set_bg(0.4, 0.4, 0.4) self.pickimage = di iw = di.get_widget() width, height = 200, 200 iw.set_size_request(width, height) label = gtk.Label('Image') label.show() nb.append_page(iw, label) nb.set_tab_reorderable(iw, True) #nb.set_tab_detachable(iw, True) if have_mpl: self.w.fig = matplotlib.figure.Figure() self.w.ax = self.w.fig.add_subplot(111, axisbg='black') self.w.ax.set_aspect('equal', adjustable='box') self.w.ax.set_title('Contours') #self.w.ax.grid(True) canvas = FigureCanvas(self.w.fig) #canvas.set_size_request(width, height) self.w.canvas = canvas self.w.canvas.show_all() canvas.connect("scroll_event", self.plot_scroll) #canvas.connect("key_press_event", self.pan_plot) canvas.connect("motion_notify_event", self.plot_motion_notify) canvas.connect("button_press_event", self.plot_button_press) canvas.connect("button_release_event", self.plot_button_release) label = gtk.Label('Contour') label.show() nb.append_page(canvas, label) nb.set_tab_reorderable(canvas, True) #nb.set_tab_detachable(canvas, True) self.w.fig2 = matplotlib.figure.Figure() self.w.ax2 = self.w.fig2.add_subplot(111, axisbg='white') #self.w.ax2.set_aspect('equal', adjustable='box') self.w.ax2.set_ylabel('brightness') self.w.ax2.set_xlabel('pixels') self.w.ax2.set_title('FWHM') self.w.ax.grid(True) canvas = FigureCanvas(self.w.fig2) #canvas.set_size_request(width, height) self.w.canvas2 = canvas self.w.canvas2.show_all() label = gtk.Label('FWHM') label.show() nb.append_page(canvas, label) nb.set_tab_reorderable(canvas, True) #nb.set_tab_detachable(canvas, True) sw = gtk.ScrolledWindow() sw.set_border_width(2) sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) vbox = gtk.VBox() sw.add_with_viewport(vbox) self.msgFont = pango.FontDescription("Sans 14") tw = gtk.TextView() tw.set_wrap_mode(gtk.WRAP_WORD) tw.set_left_margin(4) tw.set_right_margin(4) tw.set_editable(False) tw.set_left_margin(4) tw.set_right_margin(4) tw.modify_font(self.msgFont) self.tw = tw fr = gtk.Frame(" Instructions ") fr.set_shadow_type(gtk.SHADOW_ETCHED_OUT) fr.set_label_align(0.1, 0.5) fr.add(tw) vbox.pack_start(fr, padding=4, fill=True, expand=False) fr = gtk.Frame(" Pick ") fr.set_shadow_type(gtk.SHADOW_ETCHED_OUT) fr.set_label_align(0.1, 0.5) nb = gtk.Notebook() #nb.set_group_id(group) #nb.connect("create-window", self.detach_page, group) nb.set_tab_pos(gtk.POS_BOTTOM) nb.set_scrollable(True) nb.set_show_tabs(True) nb.set_show_border(False) self.w.nb2 = nb fr.add(nb) vbox.pack_start(fr, padding=4, fill=True, expand=False) # Build report panel captions = ( ('Zoom', 'label', 'Contour Zoom', 'label'), ('Object_X', 'label', 'Object_Y', 'label'), ('RA', 'label', 'DEC', 'label'), ('Equinox', 'label', 'Background', 'label'), ('Sky Level', 'label', 'Brightness', 'label'), ('FWHM X', 'label', 'FWHM Y', 'label'), ('FWHM', 'label', 'Star Size', 'label'), ('Sample Area', 'label', 'Default Region', 'button'), ) w, b = GtkHelp.build_info(captions) self.w.update(b) b.zoom.set_text(self.fv.scale2text(di.get_scale())) self.wdetail = b b.default_region.connect('clicked', lambda w: self.reset_region()) self.w.tooltips.set_tip(b.default_region, "Reset region size to default") # Pick field evaluation status label = gtk.Label() label.set_alignment(0.05, 0.5) self.w.eval_status = label w.pack_start(self.w.eval_status, fill=False, expand=False, padding=2) # Pick field evaluation progress bar and stop button hbox = gtk.HBox() btn = gtk.Button("Stop") btn.connect('clicked', lambda w: self.eval_intr()) btn.set_sensitive(False) self.w.btn_intr_eval = btn hbox.pack_end(btn, fill=False, expand=False, padding=2) self.w.eval_pgs = gtk.ProgressBar() # GTK3 #self.w.eval_pgs.set_orientation(gtk.ORIENTATION_HORIZONTAL) #self.w.eval_pgs.set_inverted(False) hbox.pack_start(self.w.eval_pgs, fill=True, expand=True, padding=4) w.pack_start(hbox, fill=False, expand=False, padding=2) label = gtk.Label("Report") label.show() nb.append_page(w, label) nb.set_tab_reorderable(w, True) #nb.set_tab_detachable(w, True) # Build settings panel captions = ( ('Show Candidates', 'checkbutton'), ('Radius', 'xlabel', '@Radius', 'spinbutton'), ('Threshold', 'xlabel', '@Threshold', 'entry'), ('Min FWHM', 'xlabel', '@Min FWHM', 'spinbutton'), ('Max FWHM', 'xlabel', '@Max FWHM', 'spinbutton'), ('Ellipticity', 'xlabel', '@Ellipticity', 'entry'), ('Edge', 'xlabel', '@Edge', 'entry'), ('Max side', 'xlabel', '@Max side', 'spinbutton'), ('Redo Pick', 'button'), ) w, b = GtkHelp.build_info(captions) self.w.update(b) self.w.tooltips.set_tip(b.radius, "Radius for peak detection") self.w.tooltips.set_tip( b.threshold, "Threshold for peak detection (blank=default)") self.w.tooltips.set_tip(b.min_fwhm, "Minimum FWHM for selection") self.w.tooltips.set_tip(b.max_fwhm, "Maximum FWHM for selection") self.w.tooltips.set_tip(b.ellipticity, "Minimum ellipticity for selection") self.w.tooltips.set_tip(b.edge, "Minimum edge distance for selection") self.w.tooltips.set_tip(b.show_candidates, "Show all peak candidates") # radius control adj = b.radius.get_adjustment() b.radius.set_digits(2) b.radius.set_numeric(True) adj.configure(self.radius, 5.0, 200.0, 1.0, 10.0, 0) def chg_radius(w): self.radius = float(w.get_text()) self.w.lbl_radius.set_text(str(self.radius)) return True b.lbl_radius.set_text(str(self.radius)) b.radius.connect('value-changed', chg_radius) # threshold control def chg_threshold(w): threshold = None ths = w.get_text().strip() if len(ths) > 0: threshold = float(ths) self.threshold = threshold self.w.lbl_threshold.set_text(str(self.threshold)) return True b.lbl_threshold.set_text(str(self.threshold)) b.threshold.connect('activate', chg_threshold) # min fwhm adj = b.min_fwhm.get_adjustment() b.min_fwhm.set_digits(2) b.min_fwhm.set_numeric(True) adj.configure(self.min_fwhm, 0.1, 200.0, 0.1, 1, 0) def chg_min(w): self.min_fwhm = w.get_value() self.w.lbl_min_fwhm.set_text(str(self.min_fwhm)) return True b.lbl_min_fwhm.set_text(str(self.min_fwhm)) b.min_fwhm.connect('value-changed', chg_min) # max fwhm adj = b.max_fwhm.get_adjustment() b.max_fwhm.set_digits(2) b.max_fwhm.set_numeric(True) adj.configure(self.max_fwhm, 0.1, 200.0, 0.1, 1, 0) def chg_max(w): self.max_fwhm = w.get_value() self.w.lbl_max_fwhm.set_text(str(self.max_fwhm)) return True b.lbl_max_fwhm.set_text(str(self.max_fwhm)) b.max_fwhm.connect('value-changed', chg_max) # Ellipticity control def chg_ellipticity(w): minellipse = None val = w.get_text().strip() if len(val) > 0: minellipse = float(val) self.min_ellipse = minellipse self.w.lbl_ellipticity.set_text(str(self.min_ellipse)) return True b.lbl_ellipticity.set_text(str(self.min_ellipse)) b.ellipticity.connect('activate', chg_ellipticity) # Edge control def chg_edgew(w): edgew = None val = w.get_text().strip() if len(val) > 0: edgew = float(val) self.edgew = edgew self.w.lbl_edge.set_text(str(self.edgew)) return True b.lbl_edge.set_text(str(self.edgew)) b.edge.connect('activate', chg_edgew) adj = b.max_side.get_adjustment() b.max_side.set_digits(0) b.max_side.set_numeric(True) adj.configure(self.max_side, 5, 10000, 10, 100, 0) def chg_max_side(w): self.max_side = int(w.get_value()) self.w.lbl_max_side.set_text(str(self.max_side)) return True b.lbl_max_side.set_text(str(self.max_side)) b.max_side.connect('value-changed', chg_max_side) b.redo_pick.connect('clicked', lambda w: self.redo()) b.show_candidates.set_active(self.show_candidates) b.show_candidates.connect('toggled', self.show_candidates_cb) label = gtk.Label("Settings") label.show() nb.append_page(w, label) nb.set_tab_reorderable(w, True) #nb.set_tab_detachable(w, True) # Build controls panel captions = ( ('Sky cut', 'button', 'Delta sky', 'xlabel', '@Delta sky', 'entry'), ('Bright cut', 'button', 'Delta bright', 'xlabel', '@Delta bright', 'entry'), ) w, b = GtkHelp.build_info(captions) self.w.update(b) self.w.tooltips.set_tip(b.sky_cut, "Set image low cut to Sky Level") self.w.tooltips.set_tip(b.delta_sky, "Delta to apply to low cut") self.w.tooltips.set_tip(b.bright_cut, "Set image high cut to Sky Level+Brightness") self.w.tooltips.set_tip(b.delta_bright, "Delta to apply to high cut") b.sky_cut.set_sensitive(False) self.w.btn_sky_cut = b.sky_cut self.w.btn_sky_cut.connect('clicked', lambda w: self.sky_cut()) self.w.sky_cut_delta = b.delta_sky b.lbl_delta_sky.set_text(str(self.delta_sky)) b.delta_sky.set_text(str(self.delta_sky)) def chg_delta_sky(w): delta_sky = 0.0 val = w.get_text().strip() if len(val) > 0: delta_sky = float(val) self.delta_sky = delta_sky self.w.lbl_delta_sky.set_text(str(self.delta_sky)) return True b.delta_sky.connect('activate', chg_delta_sky) b.bright_cut.set_sensitive(False) self.w.btn_bright_cut = b.bright_cut self.w.btn_bright_cut.connect('clicked', lambda w: self.bright_cut()) self.w.bright_cut_delta = b.delta_bright b.lbl_delta_bright.set_text(str(self.delta_bright)) b.delta_bright.set_text(str(self.delta_bright)) def chg_delta_bright(w): delta_bright = 0.0 val = w.get_text().strip() if len(val) > 0: delta_bright = float(val) self.delta_bright = delta_bright self.w.lbl_delta_bright.set_text(str(self.delta_bright)) return True b.delta_bright.connect('activate', chg_delta_bright) label = gtk.Label("Controls") label.show() nb.append_page(w, label) nb.set_tab_reorderable(w, True) #nb.set_tab_detachable(w, True) btns = gtk.HButtonBox() btns.set_layout(gtk.BUTTONBOX_START) btns.set_spacing(3) btns.set_child_size(15, -1) btn = gtk.Button("Close") btn.connect('clicked', lambda w: self.close()) btns.add(btn) vbox.pack_start(btns, padding=4, fill=True, expand=False) vpaned.pack2(sw, resize=True, shrink=True) vpaned.set_position(280) vpaned.show_all() container.pack_start(vpaned, padding=0, fill=True, expand=True)
control_points = [[], []] update_title() for i in range(3): redraw_curve(curve[i], []) redraw_points(points[i], []) def update_title(): len1, len2 = len(control_points[0]), len(control_points[1]) ax.set_title("Blue: %d, Red: %d" % (len1, len2)) ax.figure.canvas.draw() control_points = [[], []] fig = plt.figure(facecolor = 'w') gtk_fig = FigureCanvasGTKCairo(fig) gtk_fig.mpl_connect('button_press_event', add_point) ax = fig.add_subplot(111) update_title() curve = ax.plot([], [], 'b', [], [], 'r', [], [], 'g') points = ax.plot([], [], 'ob', [], [], 'or', [], [], 'og') window = gtk.Window() window.set_title('Bezier curves transformation') window.set_default_size(500, 500) window.connect('destroy', gtk.main_quit) transform_btn = gtk.Button('Transform') transform_btn.connect('clicked', transform)
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
class Plot(Callback.Callbacks): def __init__(self, logger): Callback.Callbacks.__init__(self) self.logger = logger # For callbacks for name in ('close', ): self.enable_callback(name) self.fig = matplotlib.figure.Figure() self.ax = self.fig.add_subplot(111) self.ax.set_xlabel('X values') self.ax.set_ylabel('Y values') self.ax.set_title('') self.ax.grid(True) self.canvas = FigureCanvas(self.fig) self.canvas.show_all() def get_widget(self): return self.canvas def getAxis(self): return self.ax def _sanity_check_window(self): pass def set_titles(self, xtitle=None, ytitle=None, title=None, rtitle=None): self._sanity_check_window() if xtitle != None: self.ax.set_xlabel(xtitle) if ytitle != None: self.ax.set_ylabel(ytitle) if title != None: self.ax.set_title(title) if rtitle != None: pass def clear(self): self._sanity_check_window() self.logger.debug('clearing canvas...') self.ax.cla() def show(self): self._sanity_check_window() self.logger.debug('raising window...') self.canvas.show() def hide(self): self._sanity_check_window() self.logger.debug('hiding window...') pass def close(self): self.logger.debug('closing window....') self.canvas.destroy() self.make_callback('close') return False def _draw(self): self.fig.canvas.draw() def plot(self, xarr, yarr, xtitle=None, ytitle=None, title=None, rtitle=None, **kwdargs): self.set_titles(xtitle=xtitle, ytitle=ytitle, title=title, rtitle=rtitle) self.ax.plot(xarr, yarr, **kwdargs) self.ax.grid(True) self._draw()
def build_gui(self, container): assert iqcalc.have_scipy == True, \ Exception("Please install python-scipy to use this plugin") self.pickcenter = None vpaned = gtk.VPaned() nb = gtk.Notebook() #nb.set_group_id(group) #nb.connect("create-window", self.detach_page, group) nb.set_tab_pos(gtk.POS_RIGHT) nb.set_scrollable(True) nb.set_show_tabs(True) nb.set_show_border(False) self.w.nb1 = nb vpaned.pack1(nb, resize=True, shrink=True) cm, im = self.fv.cm, self.fv.im di = FitsImageCanvasGtk.FitsImageCanvas(logger=self.logger) di.enable_autozoom('off') di.enable_autocuts('off') di.enable_zoom(True) di.enable_cuts(True) di.zoom_to(3, redraw=False) di.set_callback('zoom-set', self.zoomset) di.set_cmap(cm, redraw=False) di.set_imap(im, redraw=False) di.set_callback('motion', self.detailxy) di.set_bg(0.4, 0.4, 0.4) self.pickimage = di iw = di.get_widget() width, height = 200, 200 iw.set_size_request(width, height) label = gtk.Label('Image') label.show() nb.append_page(iw, label) nb.set_tab_reorderable(iw, True) #nb.set_tab_detachable(iw, True) if have_mpl: self.w.fig = matplotlib.figure.Figure() self.w.ax = self.w.fig.add_subplot(111, axisbg='black') self.w.ax.set_aspect('equal', adjustable='box') self.w.ax.set_title('Contours') #self.w.ax.grid(True) canvas = FigureCanvas(self.w.fig) #canvas.set_size_request(width, height) self.w.canvas = canvas self.w.canvas.show_all() canvas.connect("scroll_event", self.plot_scroll) #canvas.connect("key_press_event", self.pan_plot) canvas.connect("motion_notify_event", self.plot_motion_notify) canvas.connect("button_press_event", self.plot_button_press) canvas.connect("button_release_event", self.plot_button_release) label = gtk.Label('Contour') label.show() nb.append_page(canvas, label) nb.set_tab_reorderable(canvas, True) #nb.set_tab_detachable(canvas, True) self.w.fig2 = matplotlib.figure.Figure() self.w.ax2 = self.w.fig2.add_subplot(111, axisbg='white') #self.w.ax2.set_aspect('equal', adjustable='box') self.w.ax2.set_ylabel('brightness') self.w.ax2.set_xlabel('pixels') self.w.ax2.set_title('FWHM') self.w.ax.grid(True) canvas = FigureCanvas(self.w.fig2) #canvas.set_size_request(width, height) self.w.canvas2 = canvas self.w.canvas2.show_all() label = gtk.Label('FWHM') label.show() nb.append_page(canvas, label) nb.set_tab_reorderable(canvas, True) #nb.set_tab_detachable(canvas, True) sw = gtk.ScrolledWindow() sw.set_border_width(2) sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) vbox = gtk.VBox() sw.add_with_viewport(vbox) self.msgFont = pango.FontDescription("Sans 14") tw = gtk.TextView() tw.set_wrap_mode(gtk.WRAP_WORD) tw.set_left_margin(4) tw.set_right_margin(4) tw.set_editable(False) tw.set_left_margin(4) tw.set_right_margin(4) tw.modify_font(self.msgFont) self.tw = tw fr = gtk.Frame(" Instructions ") fr.set_shadow_type(gtk.SHADOW_ETCHED_OUT) fr.set_label_align(0.1, 0.5) fr.add(tw) vbox.pack_start(fr, padding=4, fill=True, expand=False) fr = gtk.Frame(" Pick ") fr.set_shadow_type(gtk.SHADOW_ETCHED_OUT) fr.set_label_align(0.1, 0.5) nb = gtk.Notebook() #nb.set_group_id(group) #nb.connect("create-window", self.detach_page, group) nb.set_tab_pos(gtk.POS_BOTTOM) nb.set_scrollable(True) nb.set_show_tabs(True) nb.set_show_border(False) self.w.nb2 = nb fr.add(nb) vbox.pack_start(fr, padding=4, fill=True, expand=False) # Build report panel captions = (('Zoom', 'label', 'Contour Zoom', 'label'), ('Object_X', 'label', 'Object_Y', 'label'), ('RA', 'label', 'DEC', 'label'), ('Equinox', 'label', 'Background', 'label'), ('Sky Level', 'label', 'Brightness', 'label'), ('FWHM X', 'label', 'FWHM Y', 'label'), ('FWHM', 'label', 'Star Size', 'label'), ('Sample Area', 'label', 'Default Region', 'button'), ) w, b = GtkHelp.build_info(captions) self.w.update(b) b.zoom.set_text(self.fv.scale2text(di.get_scale())) self.wdetail = b b.default_region.connect('clicked', lambda w: self.reset_region()) self.w.tooltips.set_tip(b.default_region, "Reset region size to default") # Pick field evaluation status label = gtk.Label() label.set_alignment(0.05, 0.5) self.w.eval_status = label w.pack_start(self.w.eval_status, fill=False, expand=False, padding=2) # Pick field evaluation progress bar and stop button hbox = gtk.HBox() btn = gtk.Button("Stop") btn.connect('clicked', lambda w: self.eval_intr()) btn.set_sensitive(False) self.w.btn_intr_eval = btn hbox.pack_end(btn, fill=False, expand=False, padding=2) self.w.eval_pgs = gtk.ProgressBar() # GTK3 #self.w.eval_pgs.set_orientation(gtk.ORIENTATION_HORIZONTAL) #self.w.eval_pgs.set_inverted(False) hbox.pack_start(self.w.eval_pgs, fill=True, expand=True, padding=4) w.pack_start(hbox, fill=False, expand=False, padding=2) label = gtk.Label("Report") label.show() nb.append_page(w, label) nb.set_tab_reorderable(w, True) #nb.set_tab_detachable(w, True) # Build settings panel captions = (('Show Candidates', 'checkbutton'), ('Radius', 'xlabel', '@Radius', 'spinbutton'), ('Threshold', 'xlabel', '@Threshold', 'entry'), ('Min FWHM', 'xlabel', '@Min FWHM', 'spinbutton'), ('Max FWHM', 'xlabel', '@Max FWHM', 'spinbutton'), ('Ellipticity', 'xlabel', '@Ellipticity', 'entry'), ('Edge', 'xlabel', '@Edge', 'entry'), ('Max side', 'xlabel', '@Max side', 'spinbutton'), ('Redo Pick', 'button'), ) w, b = GtkHelp.build_info(captions) self.w.update(b) self.w.tooltips.set_tip(b.radius, "Radius for peak detection") self.w.tooltips.set_tip(b.threshold, "Threshold for peak detection (blank=default)") self.w.tooltips.set_tip(b.min_fwhm, "Minimum FWHM for selection") self.w.tooltips.set_tip(b.max_fwhm, "Maximum FWHM for selection") self.w.tooltips.set_tip(b.ellipticity, "Minimum ellipticity for selection") self.w.tooltips.set_tip(b.edge, "Minimum edge distance for selection") self.w.tooltips.set_tip(b.show_candidates, "Show all peak candidates") # radius control adj = b.radius.get_adjustment() b.radius.set_digits(2) b.radius.set_numeric(True) adj.configure(self.radius, 5.0, 200.0, 1.0, 10.0, 0) def chg_radius(w): self.radius = float(w.get_text()) self.w.lbl_radius.set_text(str(self.radius)) return True b.lbl_radius.set_text(str(self.radius)) b.radius.connect('value-changed', chg_radius) # threshold control def chg_threshold(w): threshold = None ths = w.get_text().strip() if len(ths) > 0: threshold = float(ths) self.threshold = threshold self.w.lbl_threshold.set_text(str(self.threshold)) return True b.lbl_threshold.set_text(str(self.threshold)) b.threshold.connect('activate', chg_threshold) # min fwhm adj = b.min_fwhm.get_adjustment() b.min_fwhm.set_digits(2) b.min_fwhm.set_numeric(True) adj.configure(self.min_fwhm, 0.1, 200.0, 0.1, 1, 0) def chg_min(w): self.min_fwhm = w.get_value() self.w.lbl_min_fwhm.set_text(str(self.min_fwhm)) return True b.lbl_min_fwhm.set_text(str(self.min_fwhm)) b.min_fwhm.connect('value-changed', chg_min) # max fwhm adj = b.max_fwhm.get_adjustment() b.max_fwhm.set_digits(2) b.max_fwhm.set_numeric(True) adj.configure(self.max_fwhm, 0.1, 200.0, 0.1, 1, 0) def chg_max(w): self.max_fwhm = w.get_value() self.w.lbl_max_fwhm.set_text(str(self.max_fwhm)) return True b.lbl_max_fwhm.set_text(str(self.max_fwhm)) b.max_fwhm.connect('value-changed', chg_max) # Ellipticity control def chg_ellipticity(w): minellipse = None val = w.get_text().strip() if len(val) > 0: minellipse = float(val) self.min_ellipse = minellipse self.w.lbl_ellipticity.set_text(str(self.min_ellipse)) return True b.lbl_ellipticity.set_text(str(self.min_ellipse)) b.ellipticity.connect('activate', chg_ellipticity) # Edge control def chg_edgew(w): edgew = None val = w.get_text().strip() if len(val) > 0: edgew = float(val) self.edgew = edgew self.w.lbl_edge.set_text(str(self.edgew)) return True b.lbl_edge.set_text(str(self.edgew)) b.edge.connect('activate', chg_edgew) adj = b.max_side.get_adjustment() b.max_side.set_digits(0) b.max_side.set_numeric(True) adj.configure(self.max_side, 5, 10000, 10, 100, 0) def chg_max_side(w): self.max_side = int(w.get_value()) self.w.lbl_max_side.set_text(str(self.max_side)) return True b.lbl_max_side.set_text(str(self.max_side)) b.max_side.connect('value-changed', chg_max_side) b.redo_pick.connect('clicked', lambda w: self.redo()) b.show_candidates.set_active(self.show_candidates) b.show_candidates.connect('toggled', self.show_candidates_cb) label = gtk.Label("Settings") label.show() nb.append_page(w, label) nb.set_tab_reorderable(w, True) #nb.set_tab_detachable(w, True) # Build controls panel captions = ( ('Sky cut', 'button', 'Delta sky', 'xlabel', '@Delta sky', 'entry'), ('Bright cut', 'button', 'Delta bright', 'xlabel', '@Delta bright', 'entry'), ) w, b = GtkHelp.build_info(captions) self.w.update(b) self.w.tooltips.set_tip(b.sky_cut, "Set image low cut to Sky Level") self.w.tooltips.set_tip(b.delta_sky, "Delta to apply to low cut") self.w.tooltips.set_tip(b.bright_cut, "Set image high cut to Sky Level+Brightness") self.w.tooltips.set_tip(b.delta_bright, "Delta to apply to high cut") b.sky_cut.set_sensitive(False) self.w.btn_sky_cut = b.sky_cut self.w.btn_sky_cut.connect('clicked', lambda w: self.sky_cut()) self.w.sky_cut_delta = b.delta_sky b.lbl_delta_sky.set_text(str(self.delta_sky)) b.delta_sky.set_text(str(self.delta_sky)) def chg_delta_sky(w): delta_sky = 0.0 val = w.get_text().strip() if len(val) > 0: delta_sky = float(val) self.delta_sky = delta_sky self.w.lbl_delta_sky.set_text(str(self.delta_sky)) return True b.delta_sky.connect('activate', chg_delta_sky) b.bright_cut.set_sensitive(False) self.w.btn_bright_cut = b.bright_cut self.w.btn_bright_cut.connect('clicked', lambda w: self.bright_cut()) self.w.bright_cut_delta = b.delta_bright b.lbl_delta_bright.set_text(str(self.delta_bright)) b.delta_bright.set_text(str(self.delta_bright)) def chg_delta_bright(w): delta_bright = 0.0 val = w.get_text().strip() if len(val) > 0: delta_bright = float(val) self.delta_bright = delta_bright self.w.lbl_delta_bright.set_text(str(self.delta_bright)) return True b.delta_bright.connect('activate', chg_delta_bright) label = gtk.Label("Controls") label.show() nb.append_page(w, label) nb.set_tab_reorderable(w, True) #nb.set_tab_detachable(w, True) btns = gtk.HButtonBox() btns.set_layout(gtk.BUTTONBOX_START) btns.set_spacing(3) btns.set_child_size(15, -1) btn = gtk.Button("Close") btn.connect('clicked', lambda w: self.close()) btns.add(btn) vbox.pack_start(btns, padding=4, fill=True, expand=False) vpaned.pack2(sw, resize=True, shrink=True) vpaned.set_position(280) vpaned.show_all() container.pack_start(vpaned, padding=0, fill=True, expand=True)
class ViewGraph(object): def __init__(self, model, axis, fields, axis_data={}, attrs={}): self.widget = gtk.HBox() self._figure = Figure(figsize=(800,600), dpi=100, facecolor='w') self._subplot = self._figure.add_subplot(111,axisbg='#eeeeee') self._canvas = FigureCanvas(self._figure) self.widget.pack_start(self._canvas, expand=True, fill=True) if attrs.get('type', 'pie')=='bar': if attrs.get('orientation', 'vertical')=='vertical': self._figure.subplots_adjust(left=0.08,right=0.98,bottom=0.25,top=0.98) else: self._figure.subplots_adjust(left=0.20,right=0.97,bottom=0.07,top=0.98) else: self._figure.subplots_adjust(left=0.03,right=0.97,bottom=0.03,top=0.97) self.fields = fields self.model = model self.axis = axis self.editable = False self.widget.editable = False self.axis_data = axis_data self.axis_group = {} for i in self.axis_data: self.axis_data[i]['string'] = self.fields[i]['string'] if self.axis_data[i].get('group', False): self.axis_group[i]=1 self.axis.remove(i) self.attrs = attrs def display(self, models): datas = [] for m in models: res = {} for x in self.axis_data.keys(): if self.fields[x]['type'] in ('many2one', 'char','time','text'): res[x] = str(m[x].get_client(m)) elif self.fields[x]['type'] == 'selection': selection = dict(m[x].attrs['selection']) val = str(m[x].get_client(m)) res[x] = selection.get(val, val) elif self.fields[x]['type'] == 'date': if m[x].get_client(m): date = time.strptime(m[x].get_client(m), DT_FORMAT) res[x] = time.strftime(LDFMT, date) else: res[x]='' elif self.fields[x]['type'] == 'datetime': if m[x].get_client(m): date = time.strptime(m[x].get_client(m), DHM_FORMAT) if rpc.session.context.get('tz'): try: lzone = pytz.timezone(rpc.session.context['tz']) szone = pytz.timezone(rpc.session.timezone) dt = DT.datetime(date[0], date[1], date[2], date[3], date[4], date[5], date[6]) sdt = szone.localize(dt, is_dst=True) ldt = sdt.astimezone(lzone) date = ldt.timetuple() except pytz.UnknownTimeZoneError: # Timezones are sometimes invalid under Windows # and hard to figure out, so as a low-risk fix # in stable branch we will simply ignore the # exception and consider client in server TZ # (and sorry about the code duplication as well, # this is fixed properly in trunk) pass res[x] = time.strftime(LDFMT + ' %H:%M:%S', date) else: res[x] = '' else: res[x] = float(m[x].get_client(m)) datas.append(res) tinygraph.tinygraph(self._subplot, self.attrs.get('type', 'pie'), self.axis, self.axis_data, datas, axis_group_field=self.axis_group, orientation=self.attrs.get('orientation', 'vertical')) # the draw function may generate exception but it is not a problem as it will be redraw latter try: self._subplot.draw() #XXX it must have some better way to force the redraw but this one works self._canvas.queue_resize() except: pass