Exemplo n.º 1
0
    def __init__(self, size = (20, 200), inside = "random"):
        self.filter = fp = np.array([[1, 1, 1],
                                     [1, 0, 1],
                                     [1, 1, 1]], np.uint8)
        self.in_process = False
        self.fig = plt.figure()
        # self.fig, self.ax = plt.subplots(figsize=(6,7),)
        # self.animation_ax = plt.subplot2grid((6,7), (0, 0), colspan=6, rowspan=6)
        # button_ax = plt.subplot2grid((6,7), (0, 6), rowspan=1)
        # button_1ax = plt.subplot2grid((6,7), (1, 6), rowspan=1)
        self.animation_ax = self.fig.add_axes([.05, .05, .8, .9])
        self.animation_ax.axis('off')

        # sld_size_ax = self.fig.add_axes([.85, .3, .15, .03])
        # sld_size = Slider(sld_size_ax, 'Size', size[0], size[1], valinit=np.mean(size), valfmt=u'%0.0f', dragging=True)
        # sld_size.on_changed(self.sld_size_callback)

        btn_draw_ax = self.fig.add_axes([.85, .2, .1, .1])
        btn_draw = Button(btn_draw_ax, 'ginput')
        btn_draw.on_clicked(self.btn_draw_callback)

        button_1ax = self.fig.add_axes([.85, .1, .1, .1])
        goutput = Button(button_1ax, 'goutput')
        goutput.on_clicked(self.goutput_callback)
        self.size = np.mean(size)
        if inside == "random":
            self.field = np.random.randint(2, size=(self.size,self.size))
        elif inside == "empty":
            self.field = np.zeros((self.size, self.size))
        self.im = self.animation_ax.imshow(self.field, cmap=plt.cm.gray, interpolation='nearest')
Exemplo n.º 2
0
def pick_cest(args):

    if len(args.experiments) > 1:
        sys.exit(
            "\nError: Multiple experiment files were given. 'chemex pick_cest' "
            "should only be run with a single experiment files.\n"
        )

    # Read experimental setup and data
    data = datasets.read_data(args)

    if not data.data[0].experiment_name.startswith("cest"):
        sys.exit(
            "\nError: The command 'chemex pick_cest' only works with CEST "
            "experiments.\n"
        )

    callback = Buttons(data, args.out_dir)

    axprevious = plt.axes([0.825, 0.1, 0.075, 0.075])
    axnext = plt.axes([0.9, 0.1, 0.075, 0.075])

    bprevious = Button(axprevious, "Previous")
    bprevious.on_clicked(callback.previous)

    bnext = Button(axnext, "Next")
    bnext.on_clicked(callback.next)

    plt.show()
Exemplo n.º 3
0
    def setup_controls(self):
        """ Set up button axes"""
        buttons = [[('Auto levels', self.do_autolevels),
                   ('Levels1', self.do_levels_test),
                   ('Oldie', self.do_levels_old),
                   ('Clip', self.do_levels_clip)],
                   [('Blur uniform', self.do_blur),
                   ('Blur gaussian', self.do_blur_gaussian),
                   ('Sharpen', self.do_sharpen),
                   ('Unsharp', self.do_unsharp),
                   ('Edge detection', self.do_edges)],
                   [('Apply', self.apply),
                   ('Reset', self.reset),
                   ('Save', self.save),
                    ('Quit', self.quit)]]
        max_cols = max(len(row) for row in buttons)
        padding = 0.01
        start, end = 0.03, 0.97
        hspace = (end - start) / max_cols
        row_height = 0.03
        vspace = row_height + 0.003
        for j, row in enumerate(buttons):
            for i, b in enumerate(row):
                box = [start + i*hspace, 0.01 + j*vspace,
                       hspace - padding, row_height]
                print box
                axis = self.fig.add_axes(box)

                button = Button(axis, b[0])
                self.axes.append(axis)

                button.on_clicked(b[1])
                self.buttons.append(button)
Exemplo n.º 4
0
def setup_plot():
	global rate_slider, delta_slider, fig, ax, l, radio
	fig, ax = plt.subplots()
	ax.grid('on')
	plt.subplots_adjust(left=0.25, bottom=0.25)
	moneyFmt = FuncFormatter(money)
	ax.yaxis.set_major_formatter(moneyFmt)

	s = calc_compounding( rate, periods, principal, contribution, delta,inflation)
	t = np.arange(2014, (2014+periods))
	l, = plt.plot(t,s, lw=2, color='red')
	plt.ylabel("Investment Loss (FV)")
	plt.axis([2014, (2014+periods), 0, principal])
	plt.axis('tight')

	axfreq = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
	axamp  = plt.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor)

	rate_slider = Slider(axfreq, 'Avg.Returns', 4, 8, valinit=rate)
	delta_slider = Slider(axamp, 'Delta', 0.1, 1, valinit=delta)
	resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
	button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')
	rate_slider.on_changed(update)
	delta_slider.on_changed(update)
	button.on_clicked(reset)
	rax = plt.axes([0.015, 0.15, 0.15, 0.15], axisbg=axcolor)
	radio = RadioButtons(rax, ('0','3000', '6000', '9000'), active=0)
	radio.on_clicked(contribution_update)
	plt.show()
	return rate_slider,delta_slider,fig,ax,l,radio
Exemplo n.º 5
0
class slider():

    def __init__(self,res):
        
        self.res=res
    


    def slider_bar(self,res):
        #setupthe slider
        axcolor = 'lightgoldenrodyellow'
        self.axtime = plt.axes([0.1, 0.05, 0.8, 0.03], axisbg=axcolor)
        self.stime = Slider(self.axtime, 'Timestep', 0, len(res.resobj.fils.fid.dimensions['Time']), valinit=0)
        
        def update(val,res):
            t = self.stime.val
            res.refresh_plot(t)
        
        self.stime.on_changed(update(self,res))
        

    

    def foward_button(self,res):
        self.fwdax = plt.axes([0.1, 0.1, 0.1, 0.04])
        self.fwdb = Button(self.fwdax, 'forward', color='lightgoldenrodyellow', hovercolor='0.975')
        self.fwdb.on_clicked(slider.update(res.resobj.timestep-1,res))
Exemplo n.º 6
0
    def plot(self):
        self.update_current()
        # maximize window
        figManager = plt.get_current_fig_manager()
        figManager.window.showMaximized()

        self.fig.canvas.mpl_connect('button_press_event', self.onclick)
        self.fig.canvas.mpl_connect('key_press_event', self.onpress)
        finishax = plt.axes([0.83, 0.85, 0.15, 0.1])
        finishbutton = Button(finishax, 'Finish', hovercolor='0.975')
        finishbutton.on_clicked(self.finish)
        closeax = plt.axes([0.83, 0.65, 0.15, 0.1])
        button = Button(closeax, 'Replace (m)', hovercolor='0.975')
        button.on_clicked(self.replace_b)
        nextax = plt.axes([0.83, 0.45, 0.15, 0.1])
        nextbutton = Button(nextax, 'Next (n)', hovercolor='0.975')
        nextbutton.on_clicked(self.next_go)
        deleteax = plt.axes([0.83, 0.25, 0.15, 0.1])
        delete_button = Button(deleteax, 'Delete (j)', hovercolor='0.975')
        delete_button.on_clicked(self.delete_b)
        undoax = plt.axes([0.83, 0.1, 0.15, 0.1])
        undo_button = Button(undoax, 'Undo (u)', hovercolor='0.975')
        undo_button.on_clicked(self.undo_b)
        plt.show()
        return
Exemplo n.º 7
0
def debug_plot(a, b, nodes, fs, coeffs):
    global _debug_fig, _debug_cancelled
    if _debug_cancelled:
        return
    if 'show' not in locals():
        from pylab import axes, subplot, subplots_adjust, figure, draw, plot, axvline, xlim, title, waitforbuttonpress, gcf
        from matplotlib.widgets import Button
    if _debug_fig is None:
        #curfig = gcf()
        #print dir(curfig)
        _debug_fig = figure()
        ax = _debug_fig.add_subplot(111)
        #subplots_adjust(bottom=0.15)
        butax = axes([0.8, 0.015, 0.1, 0.04])
        button = Button(butax, 'Debug', hovercolor='0.975')
        def debug(event):
            import pdb; pdb.set_trace()
        button.on_clicked(debug)
        _debug_fig.sca(ax)
        draw()
        #figure(curfig)
    _debug_fig.gca().clear()
    plot(nodes, fs, linewidth=5, figure = _debug_fig)
    axvline(a, color="r", figure = _debug_fig)
    axvline(b, color="r", figure = _debug_fig)
    d = 0.05 * (b-a)
    _debug_fig.gca().set_xlim(a-d, b+d)
    title("press key in figure for next debugplot or close window to continue")
    try:
        while not _debug_cancelled and not _debug_fig.waitforbuttonpress(-1):
            pass
    except:
        _debug_cancelled = True
def param_gui(letter_name, shapeModeler):
    global sliders, mainPlot, fig, pca_params
    fig, ax = plt.subplots()
    whiteSpace = 0.15 + num_params*0.05
    plt.subplots_adjust( bottom=whiteSpace)
    plt.axis('equal')
    
    #plot of initial shape
    params = np.zeros((num_params,1))
    shape = shapeModeler.makeShape(params)
    shape = ShapeModeler.normaliseShape(shape)
    numPointsInShape = len(shape)/2
    x_shape = shape[0:numPointsInShape]
    y_shape = shape[numPointsInShape:]

    mainPlot, = plt.plot(x_shape, -y_shape)
    plt.axis([-1, 1, -1, 1],autoscale_on=False, aspect='equal')
    plt.title(letter_name)

    #add sliders to modify parameter values
    parameterVariances = shapeModeler.getParameterVariances()
    sliders = [0]*num_params
    for i in range(num_params):
        slider = Slider(plt.axes([0.25, 0.1+0.05*(num_params-i-1), 0.65, 0.03], axisbg=axcolor),
             'Parameter '+str(i+1), -5*parameterVariances[i], 5*parameterVariances[i], valinit=0)
        slider.on_changed(partial(update, shapeModeler))
        sliders[i] = slider
    
    resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
    button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')
    button.on_clicked(reset)
    plt.show()

    return pca_params
def main():
	global ax
	fig = plt.figure()

	bhandler = ButtonHandler()
	mhandler = MouseHandler()

	axclear = plt.axes([0.37, 0.02, 0.1, 0.075])
	axload = plt.axes([0.48, 0.02, 0.1, 0.075])
	axsave = plt.axes([0.59, 0.02, 0.1, 0.075])
	axcreate = plt.axes([0.7, 0.02, 0.1, 0.075])
	axrun = plt.axes([0.81, 0.02, 0.1, 0.075])

	bclear = Button(axclear, 'CLEAR')
	bclear.on_clicked(bhandler.clear)

	bload = Button(axload, 'LOAD')
	bload.on_clicked(bhandler.load_data)

	bsave = Button(axsave, 'SAVE')
	bsave.on_clicked(bhandler.save_data)

	bcreate = Button(axcreate, 'CREATE')
	bcreate.on_clicked(bhandler.create_polygon)

	brun = Button(axrun, 'RUN')
	brun.on_clicked(bhandler.run_triangulation)

	ax = fig.add_subplot(111, autoscale_on=False)
	cid = fig.canvas.mpl_connect('button_press_event', mhandler.onclick)

	plt.show()
Exemplo n.º 10
0
class NavField:
    def __init__(self, pltinfo):
        self.fld = -1
        self.nflds = len(pltinfo.selindices['field'])
        self.pltinfo = pltinfo
        prevwidth = 0.13
        nextwidth = 0.12
        butheight = 0.05
        butleft = 0.7
        butbot = 0.025
        butgap = 0.5 * butbot
        self.nextloc = [butleft + prevwidth + butgap,
                        butbot, nextwidth, butheight]
        self.prevloc = [butleft, butbot, prevwidth, butheight]
        self.inactivecolor = '#99aaff'
        self.activecolor = '#aaffcc'        

    def _draw_buts(self):
        if self.fld < self.nflds - 1:
            axnext = pl.axes(self.nextloc)
            self.bnext = Button(axnext, 'Next fld >',
                                color=self.inactivecolor,
                                hovercolor=self.activecolor)
            self.bnext.on_clicked(self.next)
        if self.fld > 0:
            axprev = pl.axes(self.prevloc)
            self.bprev = Button(axprev, '< Prev fld',
                                color=self.inactivecolor,
                                hovercolor=self.activecolor)
            self.bprev.on_clicked(self.prev)
        #pl.show()

    def _do_plot(self):
        didplot = plotfield(self.pltinfo.selindices['field'][self.fld],
                            self.pltinfo)
        if didplot:
            self._draw_buts()
        return didplot
    
    def next(self, event):
        didplot = False
        startfld = self.fld
        while self.fld < self.nflds - 1 and not didplot:
            self.fld += 1
            didplot = self._do_plot()
        if not didplot:
            print "You are on the last field with any selected baselines."
            self.fld = startfld
            #plotfield(self.pltinfo.selindices['field'][self.fld],
            #          self.pltinfo, self.mytb)

    def prev(self, event):
        didplot = False
        startfld = self.fld
        while self.fld > 0 and not didplot:
            self.fld -= 1
            didplot = self._do_plot()
        if not didplot:
            print "You are on the first field with any selected baselines."
            self.fld = startfld
Exemplo n.º 11
0
def preparePlot(shapeModeler):
    global sliders, mainPlot, fig
    fig, ax = plt.subplots();
    whiteSpace = 0.15 + numParams*0.05;
    plt.subplots_adjust( bottom=whiteSpace);
    plt.axis('equal');
    
    #plot of initial shape
    params = np.zeros((numParams,1));
    shape = shapeModeler.makeShape(params);
    shape = ShapeModeler.normaliseShape(shape);
    numPointsInShape = len(shape)/2;
    x_shape = shape[0:numPointsInShape];
    y_shape = shape[numPointsInShape:];

    mainPlot, = plt.plot(x_shape, -y_shape);
    plt.axis([-1, 1, -1, 1],autoscale_on=False, aspect='equal');

    #add sliders to modify parameter values
    parameterVariances = shapeModeler.getParameterVariances();
    sliders = [0]*numParams;
    for i in range(numParams):
        slider = Slider(plt.axes([0.25, 0.1+0.05*(numParams-i-1), 0.65, 0.03], axisbg=axcolor),
             'Parameter '+str(i+1), -5*parameterVariances[i], 5*parameterVariances[i], valinit=0);
        slider.on_changed(update);
        sliders[i] = slider;
    
    resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
    button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')
    button.on_clicked(reset)
    plt.show()
Exemplo n.º 12
0
def main():
    from matplotlib import pyplot as plt
    import utils

    fig = utils.createfig()
    a = WSin(fig, [0.1, 0.5, 0.8, 0.3] , nps=5)
    b = WSin(fig, [0.1, 0.1, 0.8, 0.3], nps=3, om=3)

    args11 = (dict(k=0, am=1, ph=0, t='v', n='1'), 
              dict(k=-1.5, am=0.1, ph=0.5, t='v', n='3'),)
    args12 = (dict(k=1,am=2,ph=1,t='i',n='2'),)
    args13 = (dict(k=100,am=3,ph=2,t='i',n='no',v=False),)
    args2 = (dict(k=0,am=1,ph=0,t='v',n='1'),dict(k=1,am=2,ph=1,t='i',n='2'),
             dict(k=-1.5,am=0.1,ph=0,t='v',n='3'),\
             dict(k=100,am=3,ph=2,t='i',n='no',v=False),)

    a.new(100, args11, args12, ())
    b.new(101, *args2)
    #b.set_anim(True)

    # bottone
    from matplotlib.widgets import Button
    box = fig.add_axes([0.05, 0.90, 0.05, 0.05])
    but = Button(box, 'next')
    def func(wtf):
        #args2 = _r_args(4)
        #print args2
        #b.new(100, *args2)
        b.set_anim(not b.get_anim())
    but.on_clicked(func)

    plt.show()
Exemplo n.º 13
0
    def __init__(self, image_sequence):

        # Fix the size of subplot
        self.fig, self.axes = plt.subplots(2, sharey=True, figsize=(10, 5))

        # Set background to be gray
        self.fig.patch.set_facecolor('#333333')

        # Store image sequence in self.seq and display the sequence
        self.seq = image_sequence
        self.image = self.seq.init_image()
        self.image2 = self.seq.init_image_original()

        self.image_figure = plt.subplot2grid((3, 3), (0, 0), colspan=3, rowspan=2)
        self.image_figure.axis('off')
        self.image_plot = self.image_figure.imshow(self.image)
        self.image_figure.set_title('Dinic', color='white')

        self.init_figure = plt.subplot2grid((3, 3), (2, 1))
        self.init_figure.axis('off')
        self.init_plot = plt.imshow(self.image2)
        self.init_figure.set_title('Flow Graph', color = 'white' )

        self.text_figure = plt.subplot2grid((3, 3), (2, 2))
        self.text_figure.axis('off')
        self.text_figure.set_title('',color = 'white')

        plt.subplots_adjust(bottom=0.2)
        axnext = plt.axes([0.81, 0.05, 0.1, 0.075])
        bnext = Button(axnext, 'Next')
        bnext.on_clicked(self.next)

        plt.show()
Exemplo n.º 14
0
    def __init__(self):
        '''variable definitions'''
        SEGMENTS = int(3) #number of segments
        #could probably make these lists instead of arrays
        self.l = np.array([0, 100, 100, 80])# actual measurements of segment length in mm
        self.w = np.array([0]*SEGMENTS,dtype=float) #horizontal coordinate
        self.z = np.array([0]*SEGMENTS,dtype=float) #vertical coordinate
        self.x = np.array([0]*SEGMENTS,dtype=float) #x axis components 
        self.y = np.array([0]*SEGMENTS,dtype=float) #y axis components
        self.a = np.array([np.pi]*SEGMENTS,dtype=float) #angle for the link, reference is previous link
        self.gripper_angle = np.array([0, -45, -90, 45, 90])#preselected gripper angles
        self.current_gripper = 2    #gripper angle selection
        self.tw = 30.0 # w axis position depth
        self.tz = 20.0 # z axis starting position height
        self.l12 = 0.0 # hypotenuse belween a1 & a2
        self.a12 = 0.0 #inscribed angle between hypotenuse, w    
        self.fig = plt.figure("CS 4TE3 Robot Simulator")  #create the frame     
        self.ax = plt.axes([0.05, 0.2, 0.90, .75], projection='3d') #3d ax panel 
        self.axe = plt.axes([0.25, 0.85, 0.001, .001])#panel for error message
        self.count = 0
        self.coords = ((20,30),(50,60),(30,40),(70,100),(70,150))
        
        self.display_error()
        self.draw_robot() 

        butval = plt.axes([0.35, 0.1, 0.1, 0.075])
        but = Button(butval, 'move')
        but.on_clicked(self.move_click)
        #error = dist(1,2);
        #print (error)

        plt.show()#end of constructor
Exemplo n.º 15
0
class ButtonClickProcessor(object):
    def __init__(self, axes, label, color, viewer):

        self.groups = viewer.groups
        self.fig_text = viewer.fig_text

        self.button = Button(axes, label=label, color=color)
        self.button.on_clicked(self.print_group)

    def print_group(self, event):

        print(self.button.label.get_text())

        group = self.groups[int(self.button.label.get_text())]

        self.fig_text.clf()
        self.ax_text = self.fig_text.add_subplot(111)
        # plt.rcParams['text.usetex'] = True

        y_write = np.linspace(0, 0.9, len(group.keys()))
        for ii, key in enumerate(group.keys()):
            self.ax_text.text(0, y_write[ii], str(key) + ' : ' + str(group[key]), fontsize=15, fontstyle='oblique')

        #Show it
        self.fig_text.canvas.draw()
Exemplo n.º 16
0
class MButton(object):
    """Custom button."""

    def __init__(self, fig, rect, label, func, fargs=None,
                 c='#0DE51B', hc='#5CFF67'):
        """init function

        Parameters:
            fig: matplotlib.figure.Figure instance
            rect: [left, bottom, width, height]
                each of which in 0-to-1-fraction i.e. 0<=x<=1
            label: string
                button label
            func: function
                function called when button is clicked
            fargs: array, optional, default: None
                (optional) arguments for func
            c: a matplotlib color i.e. string
                color i.e. background color
            hc: a matplotlib color i.e. string
                hovercolor i.e. background color when cursor is on button
        """
        self.fig = fig
        self._rect = rect
        self._label = label
        self._func = func
        self._fargs = fargs
        self.axes = self.fig.add_axes(rect)
        self.button = Button(self.axes, label, color=c, hovercolor=hc)
        self.button.label.set_fontsize('x-small')
        self.button.label.set_family('monospace')
        self.button.on_clicked(self._onclick)

    def _onclick(self, wtf):
        """Actual function called when button is clicked."""
        if self.get_visible():
            if self._func is not None: # not necessary
                if self._fargs is not None:
                    self._func(*self._fargs)
                else:
                    self._func()
            self.fig.canvas.draw()

    def set_visible(self, b):
        """Set its visibility.

        Parameters:
            b: boolean
        """
        self.axes.set_visible(b)

    def get_visible(self):
        """Get its visibility.

        Returns: b
            b: boolean
        """
        return self.axes.get_visible()
Exemplo n.º 17
0
def image_interactive_plot(names, *callbacks):

    plt.figure()
    plt.subplots_adjust(bottom=0.2, top=0.95, right=0.8)
    #cax = plt.axes([0.8, 0.2, 0.2, 0.8])
    #im = cax.imshow(np.arange(21).reshape(3,7),cmap=clsscm, alpha=0.0,interpolation='bilinear',norm=mpl.colors.NoNorm(), vmin=0, vmax=255)
    #cb = mpl.colorbar.Colorbar(cax, im)
    #cb.set_ticks(range(21))
    #cb.set_ticklabels(ds.classnames)
    n = len(callbacks)
    y = int(np.ceil(np.sqrt(n)))
    x = int(np.ceil(float(n) / y))
    ax = []
    for i, c in enumerate(callbacks):
        ax.append(plt.gcf().add_subplot(x, y, i+1))
        c(names[0], ax[i])
    class Index:
        img_ind = 0
        axname = None
        def next(self, event):
            if (self.img_ind+1) in range(len(names)):
                self.img_ind += 1
            try:
                for i, c in enumerate(callbacks):
                    ax[i].clear()
                    c(names[self.img_ind], ax[i])
                self.axname.set_text(names[self.img_ind])
                
            except:
                self.img_ind -=1
            
            
            plt.draw()
    
        def prev(self, event):
            if (self.img_ind-1) in range(len(names)):
                self.img_ind -= 1
            try:
                for i, c in enumerate(callbacks):
                    ax[i].clear()
                    c(names[self.img_ind], ax[i])
                self.axname.set_text(names[self.img_ind])
            except:
                self.img_ind +=1
                
            
           

    cb = Index()
    cb.axname = plt.figtext(0.1, 0.05, names[0], fontsize=24)
    axprev = plt.axes([0.7, 0.05, 0.1, 0.075])
    axnext = plt.axes([0.81, 0.05, 0.1, 0.075])
    bnext = Button(axnext, 'Next')
    bnext.on_clicked(cb.next)
    bprev = Button(axprev, 'Previous')
    bprev.on_clicked(cb.prev)
    plt.show()
Exemplo n.º 18
0
def makeDisplay():
    global line1
    global line2
    a = moose.element( '/model/graphs/concA' )
    b = moose.element( '/model/graphs/concB' )
    img = mpimg.imread( 'simple_bistab.png' )
    #plt.ion()
    fig = plt.figure( figsize=(8,10) )
    png = fig.add_subplot(311)
    imgplot = plt.imshow( img )
    plt.axis('off')
    ax2 = fig.add_subplot(312)
    #ax.set_ylim( 0, 0.1 )
    plt.ylabel( 'Conc (mM)' )
    plt.xlabel( 'Time (s)' )
    ax2.autoscale( enable = True, axis = 'y' )
    plt.title( "States of system. Molecules a and b are swapped at t=100 and 200 to cause state flips." )
    t = numpy.arange( 0, a.vector.size, 1 ) #sec
    line1, = ax2.plot( t, a.vector, 'r-', label = 'a' )
    line2, = ax2.plot( t, b.vector, 'b-', label = 'b' )
    plt.legend()
    ax = fig.add_subplot(313)
    plt.axis('off')
    axcolor = 'palegreen'
    axReset = plt.axes( [0.25,0.05, 0.30,0.03], facecolor='blue' )
    axQuit = plt.axes( [0.60,0.05, 0.30,0.03], facecolor='blue' )
    axAinit = plt.axes( [0.25,0.1, 0.65,0.03], facecolor=axcolor )
    axBinit = plt.axes( [0.25,0.15, 0.65,0.03], facecolor=axcolor )
    axCinit = plt.axes( [0.25,0.20, 0.65,0.03], facecolor=axcolor )
    axKcat2 = plt.axes( [0.25,0.25, 0.65,0.03], facecolor=axcolor )
    axKcat1 = plt.axes( [0.25,0.30, 0.65,0.03], facecolor=axcolor )
    #aInit = Slider( axAinit, 'A init conc', 0, 10, valinit=1.0, valstep=0.2)
    reset = Button( axReset, 'Reset', color = 'cyan' )
    q = Button( axQuit, 'Quit', color = 'pink' )
    aInit = Slider( axAinit, 'A init conc', 0, 10, valinit=1.0 )
    bInit = Slider( axBinit, 'B init conc', 0, 10, valinit=0.0 )
    cInit = Slider( axCinit, 'C init conc', 0, 0.1, valinit=0.01 )
    kcat2 = Slider( axKcat2, 'Kcat for enz2', 0, 2, valinit=0.6 )
    kcat1 = Slider( axKcat1, 'Kcat for enz1', 0, 2, valinit=0.4 )
    def resetParms( event ):
        aInit.reset()
        bInit.reset()
        cInit.reset()
        kcat2.reset()
        kcat1.reset()


    reset.on_clicked( resetParms )
    q.on_clicked( doQuit )
    aInit.on_changed( updateAinit )
    bInit.on_changed( updateBinit )
    cInit.on_changed( updateCinit )
    kcat1.on_changed( updateKcat1 )
    kcat2.on_changed( updateKcat2 )

    plt.show()
Exemplo n.º 19
0
def interactive_predictions_plot(img_infos):
    plt.figure()
    plt.subplots_adjust(bottom=0.2, top=0.95, right=0.8)
    
    ax = []
    
    def show(info, axes):
        for a in axes:
            a.clear()
        axes[0].imshow(info.image)
        show_segmentation(info.ground_truth, axes[1], numclasses=info.ds.classnum)
        show_segmentation(info.prediction, axes[2], numclasses=info.ds.classnum)
        cb = mpl.colorbar.ColorbarBase(axes[3], cmap=label_colormap(info.ds.classnum), norm=mpl.colors.NoNorm())
        cb.set_ticks(np.arange(info.ds.classnum))
        cb.set_ticklabels(info.ds.classnames)
    for i in range(4):
        ax.append(plt.gcf().add_subplot(2, 2, i+1))
    show(img_infos[0], ax)
    
    class Index:
        img_ind = 0
        axname = None
        def next(self, event):
            if (self.img_ind+1) in range(len(img_infos)):
                self.img_ind += 1
            try:
                show(img_infos[self.img_ind], ax)
                self.axname.set_text(img_infos[self.img_ind].name)
                
            except:
                self.img_ind -=1
            
            
            plt.draw()
    
        def prev(self, event):
            if (self.img_ind-1) in range(len(img_infos)):
                self.img_ind -= 1
            try:
                show(img_infos[self.img_ind], ax)
                self.axname.set_text(img_infos[self.img_ind].name)
            except:
                self.img_ind +=1
                
            
           

    cb = Index()
    cb.axname = plt.figtext(0.1, 0.05, img_infos[0].name, fontsize=24)
    axprev = plt.axes([0.7, 0.05, 0.1, 0.075])
    axnext = plt.axes([0.81, 0.05, 0.1, 0.075])
    bnext = Button(axnext, 'Next')
    bnext.on_clicked(cb.next)
    bprev = Button(axprev, 'Previous')
    bprev.on_clicked(cb.prev)
    plt.show()
Exemplo n.º 20
0
def main(argv):
    """Test maximum density."""
    print(len(argv))
    if len(argv) < 1:
        shot_number=int(open('shot_number.txt','r').read())
    else:
        if (len(argv) == 1) & ("py" in argv[0]):
           shot_number=int(open('shot_number.txt','r').read())
        else:    
            shot_number = int(argv[1])
    fig, ax = plt.subplots()
    plt.subplots_adjust(bottom=0.25)
    shot = ppb.ProcProfile(shot_number)

    shot.reference_gd(all_shot=1)
    cluster = 20
    shot.plasma_gd(1, cluster, 1)

    ax.pcolormesh(shot.X['K'], shot.Y['K'], shot.matrix_k_mean)
    ax.pcolormesh(shot.X['Ka'], shot.Y['Ka'], shot.matrix_ka_mean)

    plt.plot(shot.X['K'], shot.Y['K'][shot.matrix_k_mean.argmax(axis=0)] - 3.36, color='b', linewidth=2.0)
    plt.plot(shot.X['Ka'], shot.Y['Ka'][shot.matrix_ka_mean.argmax(axis=0)] - 3.36, color='b', linewidth=2.0)
    plt.plot(shot.X['K'], shot.Y['K'][shot.matrix_k_mean.argmax(axis=0)], color='b', linewidth=2.0)
    plt.plot(shot.X['Ka'], shot.Y['Ka'][shot.matrix_ka_mean.argmax(axis=0)], color='b', linewidth=2.0)
    l, = plt.plot(shot.X['K'], shot.Y['K'][shot.matrix_k_mean.argmax(axis=0)], color='r', linewidth=2.0)
    m, = plt.plot(shot.X['Ka'], shot.Y['Ka'][shot.matrix_ka_mean.argmax(axis=0)], color='r', linewidth=2.0)
    plt.xlabel("freq (GHz)")
    plt.ylabel("group delay (ns)")
    plt.title("# %s - time: %s ms" % (shot.shot, shot.sweep2time(shot.sweep_cur)))
    plt.ylim(0, 12)
    plt.xlim(shot.X['K'].min(), shot.X['Ka'].max())

    axcolor = 'lightgoldenrodyellow'
    axfreq = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)

    sweep = Slider(axfreq, 'Sweep', 1, len(shot.points) - 1 - cluster, valinit=1, valfmt='%1.f')

    def update(val):
        shot.plasma_gd(int(sweep.val), cluster, 1)
        ax.pcolormesh(shot.X['K'], shot.Y['K'], shot.matrix_k_mean)
        ax.pcolormesh(shot.X['Ka'], shot.Y['Ka'], shot.matrix_ka_mean)
        l.set_ydata(shot.Y['K'][shot.matrix_k_mean.argmax(axis=0)])
        m.set_ydata(shot.Y['Ka'][shot.matrix_ka_mean.argmax(axis=0)])
        ax.set_title("# %s - time: %.3f ms" % (shot.shot, shot.sweep2time(shot.sweep_cur)))
        fig.canvas.draw_idle()
    sweep.on_changed(update)

    resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
    button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')

    def reset(event):
        sweep.reset()
    button.on_clicked(reset)

    plt.show()
Exemplo n.º 21
0
def figPause(fig):
    global gInPause
    buttonAxes = plt.axes([0.9, 0.9, 0.1, 0.05])
    button = Button(buttonAxes, '>>')
    button.on_clicked(onclick)
    gInPause = True
    print('Program paused in figure window...')
    while gInPause:
        plt.pause(0.2)
        plt.draw()
    button.disconnect_events()
Exemplo n.º 22
0
def interactive_dataset_plot(dataset):
    plt.figure()
    plt.subplots_adjust(bottom=0.2, top=0.95, right=0.8)
    
    ax = []
    
    def show(info, axes):
        for a in axes:
            a.clear()
        axes[0].imshow(info.image)
        show_segmentation(info.ground_truth, axes[1])
    
    for i in range(2):
        ax.append(plt.gcf().add_subplot(1, 2, i+1))
    show(dataset[0], ax)
    
    class Index:
        img_ind = 0
        axname = None
        def next(self, event):
            if (self.img_ind+1) in range(len(dataset)):
                self.img_ind += 1
            try:
                show(dataset[self.img_ind], ax)
                self.axname.set_text(dataset[self.img_ind].name)
                
            except:
                self.img_ind -=1
            
            
            plt.draw()
    
        def prev(self, event):
            if (self.img_ind-1) in range(len(dataset)):
                self.img_ind -= 1
            try:
                show(dataset[self.img_ind], ax)
                self.axname.set_text(dataset[self.img_ind].name)
            except:
                self.img_ind +=1
                
            
           

    cb = Index()
    cb.axname = plt.figtext(0.1, 0.05, dataset[0].name, fontsize=24)
    axprev = plt.axes([0.7, 0.05, 0.1, 0.075])
    axnext = plt.axes([0.81, 0.05, 0.1, 0.075])
    bnext = Button(axnext, 'Next')
    bnext.on_clicked(cb.next)
    bprev = Button(axprev, 'Previous')
    bprev.on_clicked(cb.prev)
    plt.show()
Exemplo n.º 23
0
    def build_interface(self, spec):
      gs0 = gridspec.GridSpecFromSubplotSpec(
                     self.r, self.c, 
                     subplot_spec=spec)

      k=0
      for i in range(1, self.c):
         for j in range(0, self.r):
            ax=self.fig.add_subplot(gs0[j, i])
            bt=Button(ax, self.collist[k])
            bt.on_clicked(self.hndl_event)    
            k=k+1
Exemplo n.º 24
0
def run_main(A,B,C,dA,dB,dC):
    
    plt.close()
    plt.figure()

    int_writer()
    var_writer_uncert(A,B,C)
    run_SPCAT()
    data = cat_reader()
    t = []
    s = []
    
    for x in data:
        s.append(0.0)
        s.append(str(10**float(x[1]))) 
        s.append(0.0)
        t.append(float(x[0])-0.0001)
        t.append(x[0])
        t.append(float(x[0])+0.0001)
    
    ax = plt.subplot(111)
    plt.subplots_adjust(left=0.25, bottom=0.25)
    
    a0 = 5
    f0 = 3
    global l
    l, = plt.plot(t,s, lw=2, color='red')
    #plt.axis([0, 1, -10, 10])
    
    axcolor = 'lightgoldenrodyellow'
    axA = plt.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor)
    axB  = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
    axC  = plt.axes([0.25, 0.05, 0.65, 0.03], axisbg=axcolor)
    global A_slider
    global B_slider
    global C_slider
    
    A_slider = Slider(axA, 'A', A-dA, A+dA, valinit=A)
    B_slider = Slider(axB, 'B', B-dB, B+dB, valinit=B)
    C_slider = Slider(axC, 'C', C-dC, C+dC, valinit=C)
    A_slider.on_changed(update)
    B_slider.on_changed(update)
    C_slider.on_changed(update)
    global button
    global radio
    resetax = plt.axes([0.1, 0.025, 0.1, 0.04])
    button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')
    button.on_clicked(reset)
    rax = plt.axes([0.025, 0.5, 0.15, 0.15], axisbg=axcolor)
    radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0)
    radio.on_clicked(colorfunc)
    plt.show()
Exemplo n.º 25
0
	def display3DBoardSingleFrame(self, grid):
		def drawGamePrism(ax):
			cube_corner = [[0, 0, 0], [self.rownum, 0, 0], [self.rownum, self.colnum, 0], [0, self.colnum, 0],
			[0, 0, self.height], [self.rownum, 0, self.height], [self.rownum, self.colnum, self.height], [0, self.colnum, self.height]]
			ax.plot3D(*zip(cube_corner[0], cube_corner[1]), color = "m")
			ax.plot3D(*zip(cube_corner[1], cube_corner[5]), color = "m")
			ax.plot3D(*zip(cube_corner[5], cube_corner[4]), color = "m")
			ax.plot3D(*zip(cube_corner[4], cube_corner[0]), color = "m")
			ax.plot3D(*zip(cube_corner[3], cube_corner[2]), color = "m")
			ax.plot3D(*zip(cube_corner[2], cube_corner[6]), color = "m")
			ax.plot3D(*zip(cube_corner[6], cube_corner[7]), color = "m")
			ax.plot3D(*zip(cube_corner[7], cube_corner[3]), color = "m")
			ax.plot3D(*zip(cube_corner[0], cube_corner[3]), color = "m")
			ax.plot3D(*zip(cube_corner[1], cube_corner[2]), color = "m")
			ax.plot3D(*zip(cube_corner[5], cube_corner[6]), color = "m")
			ax.plot3D(*zip(cube_corner[4], cube_corner[7]), color = "m")

		def drawThreadPoles(ax):
			for x in range(self.rownum):
				for y in range(self.colnum):
					minz, maxz = 0, self.height
					ax.plot3D(*zip([x,y,minz], [x,y,maxz]), color = "g")

		fig = plt.figure()
		ax = fig.add_subplot(111, projection = '3d')
		ax.set_xticks(np.arange(grid.shape[0]), minor = False)
		ax.set_yticks(np.arange(grid.shape[1]), minor = False)
		ax.set_zticks(np.arange(grid.shape[2]), minor = False)
		drawGamePrism(ax)
		drawThreadPoles(ax)
		
		for x in range(len(grid)):
			for y in range(len(grid[0])):
				for z in range(len(grid[0][0])):
					if(grid[x][y][z] == 0):
						continue
					elif(grid[x][y][z] == 1):
						color = 'b'
					elif(grid[x][y][z] == 2):
						color = 'r'
					ax.scatter([x], [y], [z], c = color, s = 80)
		ax.set_xlabel('X Label')
		ax.set_ylabel('Y Label')
		ax.set_zlabel('Z Label')
		axstop = plt.axes([0.9, 0.0, 0.1, 0.075])
		axnext = plt.axes([0.1, 0.0, 0.1, 0.075])
		button_stop = Button(axstop, 'Stop')
		button_next = Button(axnext, 'Next')
		button_stop.on_clicked(self.exiting)
		button_next.on_clicked(self.closeplt)
		plt.show()
Exemplo n.º 26
0
    def _GUI_display(self,redshift_est,ztest,corr_val,wave,flux_sc):
        '''Display the spectrum and reference lines.'''
        self.fig = plt.figure(figsize=(10, 8)) 
        gs = gridspec.GridSpec(2, 1, height_ratios=[2, 1])
        ax2 = plt.subplot(gs[0])
        ax = plt.subplot(gs[1])
        plt.subplots_adjust(right=0.8)

        ax.plot(ztest,corr_val,'b')
        ax.axvline(redshift_est,color='k',ls='--')
        ax.fill_between(self.ztest,np.zeros(self.ztest.size),self.corr_prior,facecolor='grey',alpha=0.6)
        ax.set_xlabel('Redshift')
        ax.set_ylabel('Correlation')

        self.pspec, = ax2.plot(wave,flux_sc)
        ax2.axvline(3725.0*(1+redshift_est),ls='--',alpha=0.7,c='blue')
        ax2.axvline(3968.5*(1+redshift_est),ls='--',alpha=0.7,c='red')
        ax2.axvline(3933.7*(1+redshift_est),ls='--',alpha=0.7,c='red')
        ax2.axvline(4102.9*(1+redshift_est),ls='--',alpha=0.7,c='orange')
        ax2.axvline(4304.0*(1+redshift_est),ls='--',alpha=0.7,c='orange')
        ax2.axvline(4862.0*(1+redshift_est),ls='--',alpha=0.7,c='orange')
        ax2.axvline(4959.0*(1+redshift_est),ls='--',alpha=0.7,c='blue')
        ax2.axvline(5007.0*(1+redshift_est),ls='--',alpha=0.7,c='blue')
        ax2.axvline(5175.0*(1+redshift_est),ls='--',alpha=0.7,c='orange')
        if self.first_pass:
            self.line_est = Estimateline(self.pspec,ax2,self.uline_n)
        rax = plt.axes([0.85, 0.5, 0.1, 0.2])
        if self.qualityval == 0:
            radio = RadioButtons(rax, ('Unclear', 'Clear'))
        else:
            radio = RadioButtons(rax, ('Unclear', 'Clear'),active=1)
        def qualfunc(label):
            if label == 'Clear':
                self.qualityval = 1
            else:
                self.qualityval = 0
        radio.on_clicked(qualfunc)
        closeax = plt.axes([0.83, 0.3, 0.15, 0.1])
        button = Button(closeax, 'Accept & Close', hovercolor='0.975')
        def closeplot(event):
            plt.close()
        button.on_clicked(closeplot)
        ax2.set_xlim(self.lower_w,self.upper_w)
        ax2.set_xlabel('Wavelength (A)')
        ax2.set_ylabel('Counts')
        if not self.first_pass:
            self.spectra2 = DragSpectra(self.pspec,flux_sc,ax2,self.fig)
            self.fig.canvas.mpl_connect('motion_notify_event',self.spectra2.on_motion)
            self.fig.canvas.mpl_connect('button_press_event',self.spectra2.on_press)
            self.fig.canvas.mpl_connect('button_release_event',self.spectra2.on_release)
        plt.show()
Exemplo n.º 27
0
def main():
    for i in range(-10,10):
         print(i,i%4)
    fig = plt.figure('ECG chart')
    callback = Index()
    data = spio.loadmat('s0026lrem_short.mat')
    data = data['val']
    print(data, len(data))
    print(len(data[1]))
    global axes
    for i in range(1,13):
         ax1 = plt.subplot(13, 1 , i)
         axes.append(ax1)
    


    for i in range(1,13):
         fft = []
         global axes_xlim
         #ecg_plot(data, prepare_array(read_file('samples1_long.csv')), axes[i-1],i)
         ecg_plot(data, axes[i-1],i)
         callback.update_genY(Y[i-1],0)
         print(len(Y[i-1]))
         callback.update_genX(X[i-1],0)
         axes_xlim[0] = ylen

         callback.update_genY(FFTaxes[i-1],1)
         callback.update_genX(frq,1)
         
         callback.update_genY(WTaxesA[i-1],2)
         callback.update_genX(range(0,len(WTaxesA[i-1])),2)
         axes_xlim[2] = len(WTaxesA[i-1])

         callback.update_genY(WTaxesD[i-1],3)
         callback.update_genX(range(0,len(WTaxesD[i-1])),3)
         axes_xlim[3]= len(WTaxesD[i-1])



    ecg_plot_info(axes)
    fig.subplots_adjust(hspace = 0.1, left = 0.05, right = 0.95, top = 0.95, bottom = 0.05)
    print("Uderzenia na sekunde: ")
    print(60000/calculate_bpm())

    axprev = plt.axes([0.7, 0.01, 0.1, 0.075])
    axnext = plt.axes([0.81, 0.01, 0.1, 0.075])
    bnext = Button(axnext, 'Next')
    bprev = Button(axprev, 'Previous')
    bprev.on_clicked(callback.prev)
    bnext.on_clicked(callback.next)
    plt.show()
Exemplo n.º 28
0
    def setup(self):
        self.fig, self.ax = plt.subplots()
        self.t = np.linspace(0, 10, 1000)
        self.line, = plt.plot(self.t, np.sin(self.t), lw=2)
        self.v = 0
        slider_ax = plt.axes([0.1, 0.1, 0.8, 0.02])
        slider = Slider(slider_ax, "Offset", -5, 5, valinit=0, color='#AAAAAA')
        slider.on_changed(self.on_change)
        ax1 = plt.axes([0.2, 0.5, 0.1, 0.075])
        #ax2 = plt.axes([0.7, 0.5, 0.1, 0.075])

        b1 = Button(ax1, 'Draw')
        b1.on_clicked(self.callback)
        plt.show()
class ButtonSet:
    def __init__(self, px, mx, kx):
        self.buttonP = Button(px, '+')
        self.buttonM = Button(mx, '-')
        self.stVal = kx

        self.buttonP.on_clicked(self.button_handler_p)
        self.buttonM.on_clicked(self.button_handler_m)

    def button_handler_p(self, event):
        self.stVal += 0.1

    def button_handler_m(self, event):
        self.stVal -= 0.1
Exemplo n.º 30
0
def main(argv=None):
	ani = animation.FuncAnimation(fig, run, data_gen, blit=True, interval=10,
		repeat=False)

	axprev = plt.axes([0.7, 0.05, 0.1, 0.075])
	axnext = plt.axes([0.81, 0.05, 0.1, 0.075])

	bnext = Button(axnext, 'Pause')
	bnext.on_clicked(pause_animation)

	bprev = Button(axprev, 'Play')
	bprev.on_clicked(play_animation)

	plt.show()
Exemplo n.º 31
0
    def submit(self):

        if (self.type == game.SheetType.MATCH):
            #If the match is empty, reset the data and display fields
            if self.matchData['Team'] == 0:
                print("Found an empty match, skipping")
                self.matchData = dict(game.SCOUT_FIELDS)
                self.display = cv2.cvtColor(self.sheet, cv2.COLOR_GRAY2BGR)
                return
            #Open the database and check if the match has already been processed
            datapath = 'data_' + CURRENT_EVENT + '.db'
            conn = sql.connect(datapath)
            conn.row_factory = sql.Row
            cursor = conn.cursor()
            history = cursor.execute(
                'SELECT * FROM scout WHERE Team=? AND Match=?',
                (str(self.matchData['Team']), str(
                    self.matchData['Match']))).fetchall()
            if history and not self.matchData['Replay']:
                print("Already processed this match, skipping")
                self.data = dict(game.SCOUT_FIELDS)
                self.display = cv2.cvtColor(self.sheet, cv2.COLOR_GRAY2BGR)
                return
        elif (self.type == game.SheetType.PIT):
            if self.pitData['Team'] == 0:
                print("Found an empty pit sheet, skipping")
                self.pitData = dict(game.PIT_SCOUT_FIELDS)
                self.display = cv2.cvtColor(self.sheet, cv2.COLOR_GRAY2BGR)
                return
            datapath = 'data_' + CURRENT_EVENT + '.db'
            conn = sql.connect(datapath)
            conn.row_factory = sql.Row
            cursor = conn.cursor()
            history = cursor.execute('SELECT * FROM pitScout WHERE Team=?',
                                     (str(self.pitData['Team']), )).fetchall()
            if history:
                print("Already processed this team, skipping")
                self.pitData = dict(game.PIT_SCOUT_FIELDS)
                self.display = cv2.cvtColor(self.sheet, cv2.COLOR_GRAY2BGR)
                return

        #Create and open the GUI to verify  data
        print("Found new data, opening")
        output = ''
        if self.type == game.SheetType.MATCH:
            for key, value in self.matchData.items():
                output += key + "=" + str(value) + '\n'
        elif self.type == game.SheetType.PIT:
            for key, value in self.pitData.items():
                output += key + "=" + str(value) + '\n'
        fig = plt.figure('PiScout')
        fig.subplots_adjust(left=0, right=0.6)
        plt.subplot(111)
        plt.imshow(self.display)
        plt.title('Scanned Sheet')
        plt.text(600, 784, output, fontsize=12)
        upload = Button(plt.axes([0.68, 0.31, 0.15, 0.07]), 'Upload Data')
        upload.on_clicked(self.upload)
        save = Button(plt.axes([0.68, 0.24, 0.15, 0.07]), 'Save Data Offline')
        save.on_clicked(self.save)
        edit = Button(plt.axes([0.68, 0.17, 0.15, 0.07]), 'Edit Data')
        edit.on_clicked(self.edit)
        cancel = Button(plt.axes([0.68, 0.1, 0.15, 0.07]), 'Cancel')
        cancel.on_clicked(self.cancel)
        mng = plt.get_current_fig_manager()
        try:
            mng.window.state('zoomed')
        except AttributeError:
            print("Window resizing exploded, oh well.")
        plt.show()
        self.matchData = dict(game.SCOUT_FIELDS)
        self.pitData = dict(game.PIT_SCOUT_FIELDS)
        self.display = cv2.cvtColor(self.sheet, cv2.COLOR_GRAY2BGR)
Exemplo n.º 32
0
def run(data_directory, output_file, data_set="SBC-17", start=0, n_events=5):

    ## Want to go through events and show the raw piezo trace, then click to select a t0.
    ## Display the t0, ask for confirmation, and then save to an output file.
    full_stop = False

    with open(output_file, "w") as f:
        try:
            fcntl.flock(
                f, fcntl.LOCK_EX
                | fcntl.LOCK_NB)  # <-- Locks the file until f.__exit__()
        except BlockingIOError:
            print(
                "Critical: File is currently locked by another user/process. Aborting."
            )
            return
        except:
            print("Unsupported on non-Linux/Mac OS's. Aborting.")
            return
        evs_processed = 0
        all_ids = [
            i for i in os.listdir(data_directory) if
            os.path.isdir(os.path.join(data_directory, i)) and i != "scratch"
        ]
        n_skip = 0
        _counter = 0
        for ev_id in all_ids:
            if data_set == "SBC-17":
                f_template = re.compile(
                    "^[0-9]{8}_[0-9]+"
                )  ## Until the year 10,000 this should work. . .
                f_match = re.match(f_template, ev_id)
                if f_match:
                    d = int(ev_id.split("_")[0])
                    if d < 20170630:
                        continue  # Skips all data that happened before June 30 2017.
                all_evs = [
                    i for i in os.listdir(os.path.join(data_directory, ev_id))
                    if os.path.isdir(os.path.join(data_directory, ev_id, i))
                ]
                all_evs = sorted(all_evs, key=int)
                for ev in all_evs:
                    if start > _counter:
                        _counter += 1
                        continue
                    if full_stop:
                        # f.write(_last_out_str)
                        print("Processed {} events ({}-{})".format(
                            evs_processed - 1, start,
                            start + evs_processed - 1))
                        return
                    if evs_processed >= n_events:
                        # f.write(_last_out_str)
                        print("Processed {} events ({}-{})".format(
                            evs_processed, start, start + evs_processed))
                        return

                    else:
                        ## We grab the event and extract the Piezo traces
                        print(os.path.join(RAW_DIRECTORY, ev_id, ev),
                              end=" >>>>> ")
                        ev_data = GE(os.path.join(RAW_DIRECTORY, ev_id), ev,
                                     "fastDAQ")
                        try:
                            piezo2 = ev_data["fastDAQ"]["Piezo2"]
                        except Exception as e:
                            print(
                                "********************Exception! Fix this.********************"
                            )
                            continue

                        ## We grab the timebase from the event data and find the mean time interval
                        timebase = ev_data["fastDAQ"]["time"]
                        xextent = (min(timebase), max(timebase))
                        dt = np.mean(np.diff(timebase))
                        plt.plot(timebase, piezo2)
                        drawing_ax = plt.gca()
                        plt.ioff()
                        actions = mplActions(timebase, piezo2, ev_id, ev, f,
                                             drawing_ax)
                        cid = plt.gcf().canvas.mpl_connect(
                            'button_press_event', actions.on_click)

                        g_fit = plt.axes([0.543, 0.05, 0.357, 0.15])
                        g_but = Button(g_fit, "Confirm", hovercolor="green")
                        g_but.label.set_fontsize(45)
                        g_but.on_clicked(actions.confirm)

                        b_fit = plt.axes([0.125, 0.05, 0.359, 0.15])
                        b_but = Button(b_fit, "Skip", hovercolor="red")
                        b_but.label.set_fontsize(45)
                        b_but.on_clicked(actions.skip)

                        close_fit = plt.axes([0.91, 0.05, .08, 0.15])
                        close_button = Button(close_fit,
                                              "Stop\nall",
                                              hovercolor="red")
                        close_button.label.set_fontsize(14)
                        close_button.on_clicked(actions.stop)

                        plt.show()
                        full_stop = actions.full_stop
                        evs_processed += 1
    return
Exemplo n.º 33
0
def do_plot(RES):
    '''
        Make sure
            %matplolib qt
        TODO: in future just setup once, and then update lines only
    '''
    # live plot https://stackoverflow.com/questions/11874767/how-do-i-plot-in-real-time-in-a-while-loop-using-matplotlib
    # see also pylive
    import matplotlib
    matplotlib.use('Qt5Agg')
    import matplotlib.pyplot as plt
    import pandas as pd
    import numpy as np
    from pyEPR.toolbox_plotting import legend_translucent
    from pyEPR.toolbox import combinekw, xarray_unravel_levels, floor_10

    plt.ion()

    fig = plt.figure(1, figsize=(25, 10))
    fig.clf()
    fig, axs = plt.subplots(2, 3, subplot_kw=dict(), num=1, sharex=True)

    kw = dict(marker='o')
    leg_kw = dict(fontsize=9, ncol=1)

    # Frequency
    ax = axs[0, 0]
    df = pd.DataFrame({x: 1000. * RES[x]['freq_hfss']
                       for x in RES}).transpose()
    df.plot(ax=ax, **kw)
    ax.set_title(
        'Linear mode, HFSS frequency $\omega_m/2\pi$ and dressed (MHz)')
    legend_translucent(ax, leg_kw=combinekw(
        leg_kw, dict(title='Mode #')))  #ax.legend(title= 'Mode #')
    # Dressed frequency
    ax.set_prop_cycle(None)
    df = pd.DataFrame({x: RES[x]['Hres']['f01'] for x in RES}).transpose()
    df.plot(ax=ax,
            legend=False,
            **combinekw(kw, dict(marker=None, alpha=0.5, ls='--')))

    # Pmj Norm
    ax = axs[1, 0]
    df = pd.DataFrame({x: RES[x]['_Pmj_norm'] for x in RES}).transpose()
    df.plot(ax=ax, **kw)
    ax.set_title('HFSS $p_{mj}$ norm')
    legend_translucent(ax, leg_kw=combinekw(leg_kw, dict(title='Mode #')))

    # Frequency
    ax = axs[0, 1]
    df = pd.DataFrame({x: RES[x]['alpha'] for x in RES}).transpose()
    df.plot(ax=ax, **kw)
    ax.set_title(r'Anharmonicity $\alpha_{mj}/2\pi$ (MHz)')
    legend_translucent(ax, leg_kw=combinekw(leg_kw, dict(title='Mode #')))
    if RES[pass_]['ND'] is not None:  # plot numerical solution
        ax.set_prop_cycle(None)
        df = pd.DataFrame({x: diag(RES[x]['ND']['CHI'])
                           for x in RES}).transpose()
        df.plot(ax=ax,
                legend=False,
                **combinekw(kw, dict(marker=None, alpha=0.5, ls='--')))

    ax = axs[0, 2]
    df = pd.DataFrame({x: RES[x]['chi'] for x in RES}).transpose()
    df.plot(ax=ax, **kw)
    ax.set_title(r'Cross-Kerr $\chi_{mm\prime}/2\pi$ (MHz)')
    legend_translucent(ax, leg_kw=combinekw(leg_kw, dict(title='Mode #')))
    #    if RES[pass_]['ND'] is not None: # plot numerical solution
    #        ax.set_prop_cycle(None)
    #        df = pd.DataFrame({x:-get_above_diagonal(RES[x]['ND']['CHI']) for x in RES}).transpose()
    ##        df = pd.DataFrame({x:RES[x]['Hres']['chi2'] for x in RES}).transpose()
    #        df.plot(ax=ax,legend=False,**combinekw(kw,dict(marker=None,alpha=0.5,ls='--')))

    ax = axs[1, 2]
    df = pd.DataFrame({x: RES[x]['Hres']['omega_zx'] for x in RES}).transpose()
    df.plot(ax=ax, **kw)
    ax.set_title(r'Cross-Resonance $\omega_{ZX}/2\pi$ (MHz)')
    legend_translucent(ax, leg_kw=combinekw(leg_kw, dict(title='C,T')))

    # Pmj normed plot
    ax = axs[1, 1]
    da = xarray_unravel_levels({x: RES[x]['Pmj_normed']
                                for x in RES},
                               names=['pass', 'mode', 'junction'])
    for mode in da.coords['mode']:
        for junc in da.coords['junction']:
            junc_name = str(junc.values)[2:]
            ys = da.sel(mode=mode, junction=junc)
            ys.plot.line(ax=ax,
                         label='%2s,%4s' % (str(mode.values), junc_name),
                         **kw)

    min_ = floor_10(min(abs(np.min(da.values)),
                        abs(np.max(da.values))))  # just in case
    ax.set_ylim(min_, 1.05)
    ax.set_yscale("log", nonposy='clip')
    legend_translucent(ax, leg_kw=combinekw(leg_kw, dict(title='$p_{mj}$')))
    ax.set_title('HFSS $p_{mj}$ normed')

    from matplotlib.widgets import Button

    class Index(object):
        ind = 0

        def __init__(self, button, ax):
            self.ax = ax
            self.button = button  # so it doesnt get erased

        def next(self, event):
            i = self.ind = (self.ind + 1) % 5
            ax = self.ax
            if i == 0:
                ax.set_ylim(min_, 1.05)
                ax.set_yscale("log", nonposy='clip')
            elif i == 1:
                ax.set_ylim(min_, 1.02)
                ax.set_yscale("linear", nonposy='clip')
            elif i == 2:
                ax.set_ylim(0.8, 1.02)
                ax.set_yscale("linear", nonposy='clip')
            elif i == 3:
                ax.set_ylim(10**-3, 10**-1)
                ax.set_yscale("log", nonposy='clip')
            elif i == 4:
                ax.set_ylim(5 * 10**-5, 2 * 10**-3)
                ax.set_yscale("log", nonposy='clip')
            self.button.label.set_text('Next %d' % (self.ind))
            fig.canvas.draw()
            fig.canvas.flush_events()

    pos1 = ax.get_position()
    pos2 = [pos1.x0 + 0., pos1.y0 + pos1.height + 0.002, 0.07, 0.04]
    axnext = plt.axes(pos2)
    bnext = Button(axnext, 'Next')
    callback = Index(bnext, ax)
    bnext.on_clicked(callback.next)

    for ax in np.ndarray.flatten(axs):
        ax.set_xlabel('Pass number')
        #ax.autoscale(tight=True)

    fig.tight_layout()  #pad=0.4, w_pad=0.5, h_pad=1.0)
    fig.show()
    plt.pause(0.01)
    return df
Exemplo n.º 34
0
class PointFixer:
    def __init__(self, clone, display):
        print "Reading image: " + clone.filebase
        print >> sys.stderr, "Current image: " + clone.filebase

        # read first image
        im = cv2.imread(clone.filepath, cv2.IMREAD_GRAYSCALE)

        if im is None:
            print "Image " + clone.filepath + " not found. Check your image filepath."
            raise IOError

        self.original_image = im
        self.image = im

        self.display = display
        self.clone = clone

        # set default editing properties

        self.edges = False
        self.edge_blur = 1.0

        hc = self.clone.high_contrast(self.original_image)

        self.original_edge_image = cv2.Canny(
            np.array(255 * gaussian(hc, self.edge_blur), dtype=np.uint8), 0,
            50) / 255
        self.edge_image = self.original_edge_image.copy()

        self.params = {}
        self.de = clone.dorsal_edge

        self.do_fit_dorsal = False
        self.show_dorsal_edge = True
        self.add_checkpoint = False
        self.mask_clicked = False
        self.unmask_clicked = False

        self.masked_regions = {}

        self.selected = None
        self.checkpoints = self.clone.checkpoints
        self.cid = self.display.figure.canvas.mpl_connect(
            'button_press_event', self)
        self.kid = self.display.figure.canvas.mpl_connect(
            'key_press_event', self.keypress)
        self.draw()

    def __call__(self, event):

        # handles mouse clicks given context

        if event.inaxes != self.display.axes: return

        # if add checkpoint is selected, handle click to add checkpoint
        if self.add_checkpoint:
            self.get_closest_checkpoint(event.ydata, event.xdata, n=2)
            self.insert_new_checkpoint(event.ydata, event.xdata)
            self.clone.checkpoints = self.checkpoints
            self.fit_dorsal()
            self.add_checkpoint = False
            self.selected = None
            self.draw()

        elif not (self.mask_clicked or self.unmask_clicked):

            if (self.selected is None):
                # select closest checkpoint to mouse click if none selected
                self.get_closest_checkpoint(event.ydata, event.xdata)
                self.display.scatter(self.selected[1],
                                     self.selected[0],
                                     c="green")
                self.display.figure.canvas.draw()

            else:

                # move checkpoint and update the dorsal fit
                self.display.clear()

                self.set_closest_checkpoint(event.ydata, event.xdata)
                self.clone.checkpoints = self.checkpoints
                if self.do_fit_dorsal:
                    self.fit_dorsal()
                    self.do_fit_dorsal = False
                self.selected = None

                self.draw()

    def keypress(self, event):

        if (event.key == "backspace") or (event.key == "delete"):
            self.delete_selected_checkpoint(event)

    def fit_dorsal(self):

        # re-fits dorsal edge and calcualtes all statistics

        self.clone.fit_dorsal_edge(self.original_image,
                                   dorsal_edge_blur=self.edge_blur,
                                   edges=self.edge_image)
        self.clone.tail_dorsal = tuple(self.checkpoints[-1, :])
        self.clone.remove_tail_spine()
        self.de = self.clone.interpolate(self.clone.dorsal_edge)
        self.checkpoints = self.clone.checkpoints
        self.clone.head = tuple(self.checkpoints[0, :])
        self.clone.get_animal_length()
        self.clone.get_animal_dorsal_area()
        self.clone.qscore()
        self.clone.analyze_pedestal()

    def flip_button_press(self, event):

        # flips the dorsal and ventral positions and updates all downstream statistics
        # and visualization

        self.display.imshow(self.image, cmap="gray")
        self.clone.flip = not self.clone.flip
        self.clone.find_eye(self.original_image)
        self.clone.find_features(self.original_image)
        self.clone.get_orientation_vectors()
        self.clone.eye_vertices()
        self.clone.find_head(self.original_image)
        self.clone.initialize_dorsal_edge(self.original_image)
        self.clone.fit_dorsal_edge(self.original_image)
        self.edge_image = self.clone.edges
        self.clone.find_tail(self.original_image)
        self.clone.remove_tail_spine()
        self.de = self.clone.interpolate(self.clone.dorsal_edge)
        self.checkpoints = self.clone.checkpoints
        self.draw()

    def edge_button_press(self, event):

        # switches view of the GUI from raw to edge or vice-versa,
        # depending on what is currently being shown

        self.edges = not self.edges
        if self.edges:
            self.image = self.edge_image
            self.draw()

        if not self.edges:
            self.image = self.original_image
            self.draw()

    def draw(self):

        # updates all visualizations depending on current state of the GUI,
        # and redraws the GUI image and buttons

        self.display.clear()
        buttoncolor = [0.792156862745098, 0.8823529411764706, 1.0]

        axaddcheck = plt.axes([0.025, 0.085, 0.1, 0.075])
        self.addcheckbutton = Button(axaddcheck,
                                     'Add Checkpoint',
                                     color=buttoncolor,
                                     hovercolor=buttoncolor)
        self.addcheckbutton.on_clicked(self.add_checkpoint_button_press)

        if self.add_checkpoint:
            self.addcheckbutton.color = "green"
            self.addcheckbutton.hovercolor = "green"

        self.display.imshow(self.image, cmap="gray")

        axaccept = plt.axes([0.875, 0.7, 0.1, 0.075])
        self.acceptbutton = Button(axaccept,
                                   'Accept Changes',
                                   color=buttoncolor,
                                   hovercolor=buttoncolor)
        self.acceptbutton.on_clicked(self.accept)

        if self.clone.accepted:
            self.acceptbutton.color = "blue"
            self.acceptbutton.hovercolor = "blue"

        axmodified = plt.axes([0.875, 0.6, 0.1, 0.075])
        self.modifiedbutton = Button(axmodified,
                                     'Mark as Modified',
                                     color=buttoncolor,
                                     hovercolor=buttoncolor)
        self.modifiedbutton.on_clicked(self.modified_clicked)

        if self.clone.modified:
            self.modifiedbutton.color = "blue"
            self.modifiedbutton.hovercolor = "blue"

        axmask = plt.axes([0.025, 0.185, 0.05, 0.075])
        self.maskbutton = Button(axmask,
                                 'Mask',
                                 color=buttoncolor,
                                 hovercolor=buttoncolor)
        self.maskbutton.on_clicked(self.mask)

        axunmask = plt.axes([0.075, 0.185, 0.05, 0.075])
        self.unmaskbutton = Button(axunmask,
                                   'Unmask',
                                   color=buttoncolor,
                                   hovercolor=buttoncolor)
        self.unmaskbutton.on_clicked(self.unmask)

        if self.mask_clicked:
            self.maskbutton.color = "green"
            self.maskbutton.hovercolor = "green"

        if self.unmask_clicked:
            self.unmaskbutton.color = "green"
            self.unmaskbutton.hovercolor = "green"

        if self.show_dorsal_edge:
            try:
                self.display.scatter(self.de[:, 1], self.de[:, 0], c="blue")
            except TypeError:
                pass

            if self.edges:
                checkpoint_color = "yellow"
            else:
                checkpoint_color = "black"

            try:
                self.display.scatter(self.checkpoints[:, 1],
                                     self.checkpoints[:, 0],
                                     c=checkpoint_color)
            except TypeError:
                pass

        self.display.scatter(self.clone.tail_tip[1],
                             self.clone.tail_tip[0],
                             c='red')
        self.display.text(self.clone.tail_tip[1],
                          self.clone.tail_tip[0],
                          'tail_tip',
                          color='red')
        self.display.scatter(self.clone.tail[1], self.clone.tail[0], c='red')
        self.display.text(self.clone.tail[1],
                          self.clone.tail[0],
                          'tail',
                          color='red')

        self.display.axis('off')
        self.display.set_title(self.clone.filepath, color="black")
        self.display.figure.canvas.draw()

    def get_closest_checkpoint(self, x, y, n=1):

        # finds the closest dorsal checkpoint to a given point
        #
        # input: x, y - x and y coordinates of a point

        self.selected = self.checkpoints[
            np.argsort(np.linalg.norm(self.checkpoints -
                                      (x, y), axis=1))[0:n], :]

        if n == 1:

            self.selected = self.selected[0]

            if self.clone.dist((x, y), self.selected) > self.clone.dist(
                (x, y), self.clone.tail_tip):
                if self.clone.dist(
                    (x, y), self.clone.tail_tip) > self.clone.dist(
                        (x, y), self.clone.tail):
                    self.selected = self.clone.tail
                else:
                    self.selected = self.clone.tail_tip

            elif self.clone.dist((x, y), self.selected) > self.clone.dist(
                (x, y), self.clone.tail):
                if self.clone.dist(
                    (x, y), self.clone.tail_tip) < self.clone.dist(
                        (x, y), self.clone.tail):
                    self.selected = self.clone.tail_tip
                else:
                    self.selected = self.clone.tail

    def set_closest_checkpoint(self, x, y):

        # finds closest checkpoint to x,y
        #
        # input: x,y - given point

        # if x,y is close enough to tail_tip, assume user
        # wants to set the tail tip and update

        if self.clone.dist(self.selected, self.clone.tail_tip) < 0.0001:
            self.clone.tail_tip = (x, y)
            self.clone.get_tail_spine_length(
            )  # calculate new tail_spine_length

        # if x,y is close enough to tail point, assume user
        # wants to set the tail point and update
        elif self.clone.dist(self.selected, self.clone.tail) < 0.0001:
            self.clone.tail = (x, y)
            self.clone.get_tail_spine_length()
            self.clone.get_animal_length()
        else:
            val = self.checkpoints[np.argmin(
                np.linalg.norm(self.checkpoints - self.selected, axis=1)), :]
            self.checkpoints[np.argmin(
                np.linalg.norm(self.checkpoints -
                               self.selected, axis=1)), :] = (x, y)

            self.do_fit_dorsal = True

    def insert_new_checkpoint(self, x, y):

        # inserts a new checkpoint at x,y

        idx1 = np.argwhere(self.checkpoints == self.selected[0])[0][0]
        idx2 = np.argwhere(self.checkpoints == self.selected[1])[0][0]

        x = int(x)
        y = int(y)

        if (np.min([idx1, idx2])
                == 0) and (np.dot(self.checkpoints[0, :] - np.array(
                    (x, y)), self.checkpoints[1, :] - np.array((x, y))) > 0):
            self.checkpoints = np.vstack([(x, y), self.checkpoints])
            self.clone.head = (x, y)
        elif (np.max([idx1, idx2]) == len(self.checkpoints) -
              1) and (np.dot(self.checkpoints[-1, :] - np.array(
                  (x, y)), self.checkpoints[-2, :] - np.array((x, y))) > 0):
            self.checkpoints = np.vstack([self.checkpoints, (x, y)])
            self.clone.tail_dorsal = np.array((x, y))

        else:
            self.checkpoints = np.vstack([
                self.checkpoints[0:np.min([idx1, idx2]) + 1, :], (x, y),
                self.checkpoints[np.max([idx1, idx2]):]
            ])

    def delete_selected_checkpoint(self, event):

        # removes the selected checkpoint from the list

        if self.selected is not None:
            self.checkpoints = np.delete(self.checkpoints,
                                         np.argmin(
                                             np.linalg.norm(self.checkpoints -
                                                            self.selected,
                                                            axis=1)),
                                         axis=0)
            self.clone.checkpoints = self.checkpoints
            self.fit_dorsal()
            self.selected = None
            self.draw()

    def toggle_dorsal_button_press(self, event):

        self.show_dorsal_edge = not self.show_dorsal_edge
        self.draw()

    def add_checkpoint_button_press(self, event):

        self.add_checkpoint = not self.add_checkpoint
        self.draw()

    def accept(self, event):

        if self.clone.accepted == 0:
            self.clone.accepted = 1
        else:
            self.clone.accepted = 0

        self.draw()

    def modified_clicked(self, event):

        if self.clone.modified == 0:
            self.clone.modified = 1
        else:
            self.clone.modified = 0

        self.draw()

    def lasso_then_mask(self, verts, add_to_metadata=True):

        # takes arbitrary ROI given by user and masks out edge pixels

        if add_to_metadata:
            try:
                nkeys = len(self.masked_regions.keys())
                self.masked_regions[nkeys] = ('m', np.vstack(verts))
            except AttributeError:
                self.masked_regions[0] = ('m', np.vstack(verts))

        path = Path(verts)

        x, y = np.where(self.edge_image)

        for i in xrange(len(x)):
            if path.contains_point([y[i], x[i]]):
                self.edge_image[x[i]][y[i]] = 0

        self.image = self.edge_image
        self.clone.initialize_dorsal_edge(self.original_image,
                                          dorsal_edge_blur=self.edge_blur,
                                          edges=self.edge_image)
        self.fit_dorsal()
        self.draw()

    def mask(self, event):

        self.mask_clicked = not self.mask_clicked

        if self.mask_clicked:

            self.unmask_clicked = False

            self.lasso = LassoSelector(self.display,
                                       onselect=self.lasso_then_mask)
            self.edges = False
            self.edge_button_press(1)
        else:
            self.lasso = 0

        self.draw()

    def lasso_then_unmask(self, verts, add_to_metadata=True):

        if add_to_metadata:
            try:
                nkeys = len(self.masked_regions.keys())
                self.masked_regions[nkeys] = ('u', np.vstack(verts))
            except AttributeError:
                self.masked_regions[0] = ('u', np.vstack(verts))

        path = Path(verts)

        x, y = np.where(self.original_edge_image)

        for i in xrange(len(x)):
            if path.contains_point([y[i], x[i]]):
                self.edge_image[x[i]][y[i]] = 1

        self.image = self.edge_image

        self.clone.initialize_dorsal_edge(self.original_image,
                                          dorsal_edge_blur=self.edge_blur,
                                          edges=self.edge_image)
        self.fit_dorsal()
        self.draw()

    def unmask(self, event):

        self.unmask_clicked = not self.unmask_clicked

        if self.unmask_clicked:

            self.mask_clicked = False
            self.lasso = LassoSelector(self.display,
                                       onselect=self.lasso_then_unmask)
            self.edges = False
            self.edge_button_press(1)

        else:
            self.lasso = 0

        self.draw()
Exemplo n.º 35
0
class SplitPrintWindow():
    def __init__(self,
                 print_manager,
                 combo_prints,
                 hulls_df,
                 print_numb,
                 vid_panel,
                 invert_axes=True):

        self.root = tk.Tk()
        self.root.wm_title("Split the Selected Print")

        self.fig = Figure(figsize=(10, 8), dpi=100)
        self.canvas = FigureCanvasTkAgg(self.fig,
                                        master=self.root)  # A tk.DrawingArea.
        self.canvas.draw()
        self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

        self.toolbar = NavigationToolbar2TkAgg(self.canvas, self.root)
        self.toolbar.update()
        self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
        self.print_manager = print_manager
        self.combo_prints = combo_prints
        self.print_numb = print_numb
        self.first_frame = self.combo_prints.first_frame[print_numb]
        n_frames = (self.combo_prints.last_frame[print_numb] -
                    self.first_frame) + 1
        grid_size = int(np.ceil(np.sqrt(n_frames)))
        self.axes = []
        self.fig.set_size_inches(16, 9)
        button_axes = self.fig.add_axes([.01, .01, .05, .05])
        self.button = Button(button_axes, 'Split')
        self.button.on_clicked(self.create_new_hulls)

        these_hulls = hulls_df[hulls_df.print_numb == print_numb]
        self.collections = {}
        self.xyes = {}
        for i in range(0, n_frames):
            ax = self.fig.add_subplot(grid_size, grid_size, i + 1)
            self.axes.append(ax)
            ax.set_axis_off()
            frame = vid_panel.get_frame(self.first_frame + i)
            X = self.combo_prints.X[print_numb]
            Y = self.combo_prints.Y[print_numb]
            ax.imshow(frame)
            xes = []
            yes = []
            for c in (these_hulls.contours[these_hulls.frame ==
                                           self.first_frame + i].values[0]):
                #add all to a single list to make one collection
                xes = xes + list(c[:, 0, 0])
                yes = yes + list(c[:, 0, 1])
            self.collections[ax] = ax.scatter(xes, yes)
            self.xyes[ax] = self.collections[ax].get_offsets()
            #set it to have list of facecolors so that selection works
            facecolors = self.collections[ax].get_facecolors()
            npts = len(self.xyes[ax])
            facecolors = np.tile(facecolors, npts).reshape(npts, -1)
            self.collections[ax].set_facecolor(facecolors)

            if invert_axes:
                ax.set_xlim(X + 50, X - 50)
            else:
                ax.set_xlim(X - 50, X + 50)
            ax.set_ylim(Y - 50, Y + 50)
            ax.set_title('Frame ' + str(self.first_frame + i))
        self.axes = np.asarray(self.axes)
        self.cid = self.canvas.mpl_connect('button_press_event', self.onpress)
        self.canvas.draw()
        tk.mainloop()

    def create_new_hulls(self, event):
        new_hull_points = []
        old_hull_points = []
        frame = []
        if (sys.version_info > (3, 0)):
            iterab = self.collections.items()
        else:
            iterab = self.collections.iteritems()
        for ax, collection in iterab:
            #make np array of bools with whether color matches the selection color for each point
            inds = np.asarray([
                True if np.array_equal(i, [.4, .4, .9, 1.0]) else False
                for i in collection.get_facecolors()
            ])
            #use np bool indexing to get x,y values for selected and unselected
            new_hull_points.append(self.xyes[ax][inds])
            old_hull_points.append(self.xyes[ax][~inds])
            frame.append(self.first_frame + np.where(self.axes == ax)[0])
        self.print_manager.split_print(new_hull_points, old_hull_points, frame,
                                       self.print_numb)
        self.root.destroy()

    def callback(self, verts):
        facecolors = self.collections[self.current_axes].get_facecolors()
        p = path.Path(verts)
        ind = p.contains_points(self.xyes[self.current_axes])
        for i in range(len(self.xyes[self.current_axes])):
            if ind[i]:
                facecolors[i] = [.4, .4, .9, 1.0]
            else:
                facecolors[i] = [.4, .4, .2, .5]
        self.collections[self.current_axes].set_facecolor(facecolors)
        self.fig.canvas.draw_idle()
        self.fig.canvas.widgetlock.release(self.lasso)
        del self.lasso

    #TODO: troubleshoot widget locks
    def onpress(self, event):
        if self.fig.canvas.widgetlock.locked(): return
        if event.inaxes is None: return
        self.current_axes = event.inaxes
        self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata),
                           self.callback)
        # acquire a lock on the widget drawing
        self.fig.canvas.widgetlock(self.lasso)
    def Start(self, even):
        if self.flag == False:
            self.flag = True
            t = Thread(target=self.TheadStart)
            t.start()

    def Stop(self, even):
        self.flag = False


#设置按钮
callback = ButtonHandler()
button_point = plt.axes([0.7, 0.05, 0.1, 0.075])
button_start = Button(button_point, '开始')
button_start.on_clicked(callback.Start)

button_point = plt.axes([0.81, 0.05, 0.1, 0.075])
button_stop = Button(button_point, '暂停')
button_stop.on_clicked(callback.Stop)

# def th():
#     while True:
#         sleep(1)
#         button_time.label = str(datetime.datetime.now())
#         button_time.ax.figure.c
#         # fig.draw()
#
# t_pre= Thread(target=th)
# t_pre.start()
Exemplo n.º 37
0
class gyro_ui(object):
    '''Classe pour interface graphique de visualisation des données de remuage
	'''
    format_date = "%d %b %Y %H:%M:%S"
    date_formatter = mdates.DateFormatter("%d %b")  # For axis
    #date_formatter =  ticker.FormatStrFormatter('%d %b') # for axis
    ratio_gyro = 131.0  #Gyro : 1/131 degrés/secondes
    ratio_acceleration = 16384.0  #Acceleration : 1/16384 g (g=9.81 N.s-2)
    seuil_gyro_mvt = 200.0 / 131.0  #Seuil au delà duquel une vitesse angulaire est considéré comme un mvt
    accel_detect = 1000.0 / 131.0
    trig_detect = datetime.timedelta(minutes=10)

    def __init__(self, bdd, images_folder=None):
        '''Initialisation
			- bdd			:	base de données gyro_db
		'''
        self.bdd = bdd
        self.dates = []
        self.acc_Xs = []
        self.acc_Ys = []
        self.acc_Zs = []
        self.gyro_Xs = []
        self.gyro_Ys = []
        self.gyro_Zs = []
        self.angle_Xs = []
        self.angle_Ys = []
        #self.angle_Zs = []
        self.angle_X = 0
        self.angle_Y = 0
        self.angle_Z = 0
        self.lecture_donnees()
        self.scan_images(images_folder)
        self.fig = plt.figure()
        self.fig.canvas.set_window_title('Fileurope - CMP - FGYRO')
        self.init_graphes()
        self.lecture = False
        self.th_lecture_image = None
        self.vitesse_lecture = 1

    def run(self):
        '''Run the ui
		'''
        plt.show()

    def lecture_donnees(self):
        '''lecture de la base de données et correction des données
		'''
        logging.info('Lecture des donnees')
        for data in self.bdd.mesures():
            try:
                self.dates.append(gyro_db.utc_to_local(data['date']))
                self.acc_Xs.append(data['acc_X'] / gyro_ui.ratio_acceleration)
                self.acc_Ys.append(data['acc_Y'] / gyro_ui.ratio_acceleration)
                self.acc_Zs.append(data['acc_Z'] / gyro_ui.ratio_acceleration)
                self.gyro_Xs.append(data['gyro_X'] / gyro_ui.ratio_gyro)
                self.gyro_Ys.append(data['gyro_Y'] / gyro_ui.ratio_gyro)
                self.gyro_Zs.append(data['gyro_Z'] / gyro_ui.ratio_gyro)

                ###Calculs angulaires

                # Accélération totale : c'est la pesanteur
                acc = sqrt(data['acc_X']**2 + data['acc_Y']**2 +
                           data['acc_Z']**2)
                #Rotation autour de l'axe de la bouteille (c'est le roulis)
                self.angle_Xs.append(asin(data['acc_Z'] / acc) * 180 / pi)
                #Inclinaison de la bouteille vers le bas (c'est le tanguage)
                self.angle_Ys.append(acos(data['acc_X'] / acc) * 180 / pi)
                #self.angle_Zs.append(0)
            except Exception as e:
                print(e)

        logging.info("%s mesures trouvees." % (len(self.dates)))

        #Moyenne des vitesses angulaires pour auto-calibration
        try:
            corr_gyro_Xs = sum(self.gyro_Xs) / len(self.gyro_Xs)
        except:
            corr_gyro_Xs = 0
        try:
            corr_gyro_Ys = sum(self.gyro_Ys) / len(self.gyro_Ys)
        except:
            corr_gyro_Ys = 0
        try:
            corr_gyro_Zs = sum(self.gyro_Zs) / len(self.gyro_Zs)
        except:
            corr_gyro_Zs = 0
        logging.info(
            "Correction des moyennes des vitesses angulaires : x:%s, y:%s, z:%s"
            % (corr_gyro_Xs, corr_gyro_Ys, corr_gyro_Zs))
        nb_supp_mesures_angle = 0
        for i in range(len(self.dates)):
            #Correction des vitesses angulaires
            self.gyro_Xs[i] -= corr_gyro_Xs
            self.gyro_Ys[i] -= corr_gyro_Ys
            self.gyro_Zs[i] -= corr_gyro_Zs
            # "Suppression" des mesures d'angle quand il y a une vitesses angulaire
            if i > 0 and (abs(self.gyro_Xs[i]) > gyro_ui.seuil_gyro_mvt
                          or abs(self.gyro_Ys[i]) > gyro_ui.seuil_gyro_mvt
                          or abs(self.gyro_Zs[i]) > gyro_ui.seuil_gyro_mvt):
                self.angle_Xs[i] = self.angle_Xs[i - 1]
                self.angle_Ys[i] = self.angle_Ys[i - 1]
                #self.angle_Zs[i] = self.angle_Zs[i-1]
                nb_supp_mesures_angle += 1
        logging.info("%s mesures d'angle supprimees" % nb_supp_mesures_angle)

        # Recherche des phases
        self.phases = []  # Un enregistrement par phase
        self.etapes = []  # A chaque point, la phase correspondante
        i = 0
        while i < len(self.dates):
            acceleration = sqrt(self.gyro_Xs[i]**2 + self.gyro_Ys[i]**2 +
                                self.gyro_Zs[i]**2)
            if acceleration > gyro_ui.accel_detect:
                acceleration_max = acceleration
                date_debut_mouvement = self.dates[i]
                date_fin_mouvement = date_debut_mouvement
                date_fin_trig = date_debut_mouvement + gyro_ui.trig_detect
                while self.dates[i] < date_fin_trig:
                    acceleration = sqrt(self.gyro_Xs[i]**2 +
                                        self.gyro_Ys[i]**2 +
                                        self.gyro_Zs[i]**2)
                    acceleration_max = max(acceleration_max, acceleration)
                    if acceleration > gyro_ui.accel_detect:
                        date_fin_phase = self.dates[i]
                    i += 1
                self.phases.append({
                    'debut_mvt': date_debut_mouvement,
                    'fin_mvt': date_fin_mouvement,
                    'acceleration_max': acceleration_max
                })
                logging.info("Phase detectee : no %s : debut = %s, fin = %s" %
                             (len(self.phases), date_debut_mouvement,
                              date_fin_mouvement))
            else:
                i += 1
            self.etapes.append(len(self.phases))
        self.export_xls()

    def export_xls(self, filename=None):
        '''Exporte les données vers un fichier excel
		'''
        #TODO mettre menu dans interface
        if filename is None:
            filename = "gyro.xlsx"
        import xlsxwriter
        workbook = xlsxwriter.Workbook(filename)
        worksheet = workbook.add_worksheet("phases")
        format_date = workbook.add_format({'num_format': 'dd/mm/yy hh:mm:ss'})
        col = 0
        for key in self.phases[0]:
            row = 0
            worksheet.write(row, col, key)
            row += 1
            for item in self.phases:
                if "date" in key:
                    worksheet.write_datetime(row, col,
                                             self.phases[row - 1][key],
                                             format_date)
                else:
                    worksheet.write(row, col, self.phases[row - 1][key])
                row += 1
            col += 1
        workbook.close()

    def init_graphes(self):
        ''' Inititialise les graphiques
		'''
        ### IMAGE REMUTRACE
        image_capteur = plt.imread('capteur.png')
        self.image_capteur_plot = self.fig.add_subplot(233)
        self.image_capteur_plot.set_axis_off()
        self.image_capteur_plot.imshow(image_capteur)

        ### 3D (non implementé)
        #self.3D = figure3D().add_subplot(233)
        #self.3D = self.fig.add_subplot(233)

        ### GRAPHE XYZ
        #self.xyz=self.fig.add_subplot(231)
        #self.xyz.set_xlabel('Temps')
        #self.xyz.set_ylabel('x,y,z')
        #self.xyz.plot(self.dates, self.acc_Xs, label='acc_X')
        #self.xyz.plot(self.dates, self.acc_Ys, label='acc_Y')
        #self.xyz.plot(self.dates, self.acc_Zs, label='acc_Z')
        #self.xyz.legend()
        #self.xyz_line = False

        ### GRAPHE GxGyGz
        self.GxGyGz = self.fig.add_subplot(231)  #, sharex = self.xyz)
        self.GxGyGz.set_title(u'Vitesse angulaire')
        self.GxGyGz.set_xlabel(u'Temps')
        self.GxGyGz.set_ylabel(u'Deg/s')
        self.GxGyGz.plot(self.dates, self.gyro_Xs, label='gyro_X')
        self.GxGyGz.plot(self.dates, self.gyro_Ys, label='gyro_Y')
        self.GxGyGz.plot(self.dates, self.gyro_Zs, label='gyro_Z')
        #self.GxGyGz.set_xticks(self.dates)
        self.GxGyGz.xaxis.set_major_locator(mdates.DayLocator())
        #self.GxGyGz.xaxis.set_minor_locator(mdates.HourLocator())
        self.GxGyGz.xaxis.set_major_formatter(
            ticker.FormatStrFormatter("%d %b"))
        self.GxGyGz.legend()
        self.GxGyGz_line = False
        #self.fig.autofmt_xdate()
        #plt.xticks(rotation=90)
        logging.debug("GRAPHE GxGyGz ok")

        ### GRAPHE INCLINAISON
        self.Inclinaison = self.fig.add_subplot(234, sharex=self.GxGyGz)
        self.Inclinaison.plot(self.dates, self.angle_Ys, label='Inclinaison')
        #self.Inclinaison.legend()
        self.Inclinaison.set_title(u'Inclinaison')
        self.Inclinaison.set_xlabel(u'Temps')
        self.Inclinaison.set_ylabel(u'Deg')
        self.Inclinaison_line = False

        ### GRAPHE ROTATION
        self.Rotation = self.fig.add_subplot(235, sharex=self.GxGyGz)
        self.Rotation.plot(self.dates, self.angle_Xs, label='Rotation')
        #self.Rotation.legend()
        self.Rotation.set_title(u'Rotation')
        self.Rotation.set_xlabel(u'Temps')
        self.Rotation.set_ylabel(u'Deg')
        self.Rotation_line = False

        ### PHOTO
        self.image_plot = self.fig.add_subplot(232)
        self.image_plot.set_axis_off()
        self.image_plot.set_title(u'Caméra')

        ### BOUTONS
        self.fig.canvas.mpl_connect('button_press_event', self.on_click)
        self.bt_lecture = Button(plt.axes([0.65, 0.3, 0.05, 0.03]), 'lecture')
        self.bt_lecture.on_clicked(self.on_bt_lecture_click)

        self.bt_lecture10 = Button(plt.axes([0.65, 0.2, 0.05, 0.03]),
                                   'lecturex10')
        self.bt_lecture10.on_clicked(self.on_bt_lecture_click10)
        #self.tb_vitesse = TextBox(plt.axes([0.9, 0.8, 0.05, 0.03]),'Vitesse', initial = '1')
        #self.tb_vitesse.on_submit(self.on_tb_vitesse_submit)

        ### Détail étape
        axe_etape = self.fig.add_axes([0.65, 0.4, 0.03, 0.03])
        axe_etape.set_axis_off()
        self.etape = plt.text(0, 3, u'Etape n° ?')
        self.etape_debut_mvt = plt.text(0, 2, u'Début : --')
        self.etape_fin_mvt = plt.text(0, 1, u'Fin : --')
        self.etape_acceleration_max = plt.text(0, 0, u'Accélération max : --')

        ### LEGENDE : FILEUROPE-CMP
        legende = self.fig.add_axes([0.75, 0.07, 0.2, 0.3])
        legende.set_axis_off()
        #rect = Rectangle((0,0),1,1,fill=True, color= 'blue')
        #legende.add_patch(rect)
        logo_img = plt.imread('logo.png')
        legende.imshow(logo_img)
        text_legende = plt.text(0.05, 0.05, u"Remutrace - Brevet déposé.")
        self.fig.canvas.mpl_connect('key_press_event', self.press)

    def scan_images(self, rep):
        '''Scan le repertoire des images
			et peuble le dict self.images : {date:nom_fichier _image}
		'''
        #logging.info("Scan du repertoir images : %s ..."%(rep))
        self.images = {}
        self.images_dates = {}
        if rep:
            for fichier in os.listdir(rep):
                if os.path.isfile(os.path.join(rep, fichier)):
                    try:
                        self.images[datetime.datetime.strptime(
                            fichier[3:-4],
                            "%Y-%m-%d %H-%M-%S.%f")] = os.path.join(
                                rep, fichier)
                    except:
                        pass
            self.images_dates = self.images.keys()
            self.images_dates.sort()
            logging.info("%s images trouvees." % (len(self.images)))
        self.xdate_index = 0

    def show_image(self):
        '''Update the image and the cursors and the etape
		'''
        if len(self.images) > 0:
            date = self.images_dates[self.xdate_index]
            image_path = self.images[date]
            #logging.debug("Image %s"%(image_path))
            image_file = cbook.get_sample_data(image_path)
            image = plt.imread(image_file)
            self.image_plot.clear()
            self.image_plot.set_axis_off()
            self.image_plot.imshow(image)
            self.image_plot.set_title(u'Caméra')
            self.image_plot.text(
                0, 800, "Date : " +
                self.dates[self.xdate_index].strftime(gyro_ui.format_date))
            if self.GxGyGz_line:
                self.GxGyGz_line.remove()
            self.GxGyGz_line = self.GxGyGz.vlines(
                date,
                self.GxGyGz.get_ylim()[0] * 0.75,
                self.GxGyGz.get_ylim()[1] * 0.75)
            if self.Inclinaison_line:
                self.Inclinaison_line.remove()
            self.Inclinaison_line = self.Inclinaison.vlines(
                date,
                self.Inclinaison.get_ylim()[0] * 0.75,
                self.Inclinaison.get_ylim()[1] * 0.75)
            if self.Rotation_line:
                self.Rotation_line.remove()
            self.Rotation_line = self.Rotation.vlines(
                date,
                self.Rotation.get_ylim()[0] * 0.75,
                self.Rotation.get_ylim()[1] * 0.75)
            etape = self.etapes[self.xdate_index]
            self.etape.set_text(u"Etape n° %s" % etape)
            self.etape_debut_mvt.set_text(
                u"Début : " +
                self.phases[etape]["debut_mvt"].strftime(gyro_ui.format_date))
            self.etape_fin_mvt.set_text(
                u"Fin : " +
                self.phases[etape]["fin_mvt"].strftime(gyro_ui.format_date))
            self.etape_acceleration_max.set_text(
                u"Accél. max : %s" % self.phases[etape]["acceleration_max"])
            # TODO et plus d'info
            self.fig.canvas.draw()  # C'est ici que c'est long (0.3 s)

    def on_click(self, event):
        '''callback function when click on graphe
		'''
        #logging.debug('button=%d, inaxes = %s, x=%d, y=%d, xdata=%f, ydata=%f' %(event.button, event.inaxes, event.x, event.y, event.xdata, event.ydata))
        if len(self.images) > 0:
            if event.inaxes in [self.GxGyGz, self.Inclinaison, self.Rotation]:
                date = mdates.num2date(event.xdata).replace(tzinfo=None)
                #try:
                self.xdate_index = self.images_dates.index(
                    min(self.images_dates, key=lambda d: abs(d - date)))
                logging.debug(self.xdate_index)
                self.show_image()
            #	except:
            #		pass

    # Attention : bricolage+++
    def on_bt_lecture_click10(self, event):
        self.vitesse_lecture = 10
        self.on_bt_lecture_click_all(event)

    def on_bt_lecture_click(self, event):
        '''
		'''
        self.vitesse_lecture = 1
        self.on_bt_lecture_click_all(event)

    def on_bt_lecture_click_all(self, event):
        if self.lecture:
            self.lecture = False
            self.bt_lecture.Label = matplotlib_text.Text(text='lecture')
            logging.info("Pause")
            self.th_lecture_image.stop()
            self.fig.canvas.draw()
        else:
            self.lecture = True
            self.bt_lecture.Label = matplotlib_text.Text(text='pause')
            logging.info("Lecture")
            self.fig.canvas.draw()
            self.th_lecture_image = f_thread(self.lecture_images)
            self.th_lecture_image.start()

    # Fin du bricolage
    def lecture_images(self, sens=1):
        ''' affichage de l'image suivante
			Utilisation : en threading  : f_thread(self.lecture_images)
		'''
        self.xdate_index += sens * self.vitesse_lecture
        if self.xdate_index > len(self.images_dates):
            self.xdate_index = 0
            self.lecture = False
        self.show_image()
        time.sleep(0.05)  #Pour donner la main à l'affichage

    def press(self, event):
        ''' Quand une fleche droite ou gauche est appuyée : image suivante ou précédente
		'''
        print("Key pressed : " + event.key)
        sys.stdout.flush()
        if event.key == "down":
            self.lecture_images(1)
        elif event.key == "up":
            self.lecture_images(-1)
        elif event.key == "pagedown":
            self.lecture_images(10)
        elif event.key == "pageup":
            self.lecture_images(-10)

    def on_tb_vitesse_submit(self, text):
        ''' quand changement vitesse de lecture
		'''
        try:
            self.vitesse_lecture = int(text)
        except:
            pass
Exemplo n.º 38
0
def show():
    depthmap.process(plt, input, depth[index], 0)  #rgb[index])
    if edges == 1:
        depthmap.showEdges()
    else:
        depthmap.showResult()
    ax = plt.gca()
    ax.text(0.5,
            1.075,
            depth[index],
            horizontalalignment='center',
            verticalalignment='center',
            transform=ax.transAxes)
    bprev = Button(plt.axes([0.0, 0.0, 0.1, 0.075]), '<<', color='gray')
    bprev.on_clicked(prev)
    bnext = Button(plt.axes([0.9, 0.0, 0.1, 0.075]), '>>', color='gray')
    bnext.on_clicked(next)
    bexportOBJ = Button(plt.axes([0.2, 0.0, 0.2, 0.05]),
                        'Export OBJ',
                        color='gray')
    bexportOBJ.on_clicked(exportOBJ)
    bexportPCD = Button(plt.axes([0.4, 0.0, 0.2, 0.05]),
                        'Export PCD',
                        color='gray')
    bexportPCD.on_clicked(exportPCD)
    bconvertPCDs = Button(plt.axes([0.6, 0.0, 0.2, 0.05]),
                          'Convert all PCDs',
                          color='gray')
    bconvertPCDs.on_clicked(convertAllPCDs)
    if edges == 0:
        bshowedges = Button(plt.axes([0.0, 0.94, 0.2, 0.05]),
                            'Show edges',
                            color='gray')
        bshowedges.on_clicked(swapEdges)
    else:
        bshowedges = Button(plt.axes([0.0, 0.94, 0.2, 0.05]),
                            'Hide edges',
                            color='gray')
        bshowedges.on_clicked(swapEdges)
    plt.show()
Exemplo n.º 39
0
def drawPeople(P=[]):
    plt.clf()  #清除数据
    drawFile()  #绘制高斯函数
    drawSecondFile()
    R_x = []  #向右移动的行人的x坐标
    R_y = []  #y坐标
    L_x = []  #向左移动的行人的x坐标
    L_y = []  #y坐标
    G_x_r = []
    G_y_r = []
    G_x_l = []
    G_y_l = []
    G_x = []
    G_y = []
    de_x = []
    de_y = []
    for p in P:  #遍历行人列表
        if p.logo == Data.LOGO_PEOPLE:  #此行可以省略?
            if p.debug == 1:
                de_x.append(p.x)
                de_y.append(p.y)
            else:

                if p.isInGrend:
                    if p.isNewDefine == 1:
                        G_x_r.append(p.x)
                        G_y_r.append(p.y)
                    elif p.isNewDefine == 2:
                        G_x_l.append(p.x)
                        G_y_l.append(p.y)
                    else:
                        G_x.append(p.x)
                        G_y.append(p.y)

                else:
                    if p.type:  #如果行人方向为 【右】
                        R_x.append(p.x)  #添加x坐标
                        R_y.append(p.y)  #添加y坐标
                    else:  #如果行人方向为【左】
                        L_x.append(p.x)
                        L_y.append(p.y)
        # R_x.append(p[0])
        # R_y.append(p[1])
    # plt.figure(figsize=(10,6))
    plt.subplot(1, 1, 1)  #绘图板布局  不知道怎么取消这一行
    plt.scatter(G_x_r, G_y_r, c='k', marker='<')
    plt.scatter(G_x_l, G_y_l, c='k', marker='>')
    plt.scatter(G_x, G_y, c='k', marker='s')
    plt.scatter(de_x, de_y, c='b', marker='D')
    plt.scatter(R_x, R_y, c='r', marker='<')  #绘制行人--散点图
    plt.scatter(L_x, L_y, c='b', marker='>')

    drawWallAndExit()  #绘制墙壁和出口
    # plt.show()
    '''由于无法右上角关闭 加了个关闭按钮'''
    closeFig = plt.axes([0.8, 0.025, 0.1, 0.04])  #关闭按钮
    closeFigbutton = Button(closeFig, 'close', hovercolor='0.5')  #按钮样式
    closeFigbutton.on_clicked(closeFigure)  #按钮按下去的动作
    #-------------------------------------------------
    pauseFig = plt.axes([0.2, 0.025, 0.1, 0.04])
    pauseFigbutton = Button(pauseFig, 'pause', hovercolor='0.5')
    pauseFigbutton.on_clicked(pauseFigure)
    # ---------------------------------------------------
    pauseResFig = plt.axes([0.6, 0.025, 0.1, 0.04])
    pauseFigResbutton = Button(pauseResFig, 'res', hovercolor='0.5')
    pauseFigResbutton.on_clicked(pauseResFigure)
    # ---------------------------------------------------
    while Data.figure_pause:
        plt.pause(1)  # 暂停1s
    plt.pause(1)  #暂停1s
Exemplo n.º 40
0
sd = Slider(axd, r'$d/\lambda$', 0., 10., valinit=d0)
st0 = Slider(axt, r'$(d/\lambda)\,\theta_0$', 0., 2., valinit=t00)


# Update plot using slider data
def update(val):
    d = sd.val
    t0 = st0.val
    l.set_ydata(2. * np.cos(np.pi * d * np.sin(t * np.pi)) *
                np.cos(np.pi * d * np.sin(t * np.pi)) * np.sinc(0.5 * t0) *
                np.sinc(0.5 * t0))
    fig.canvas.draw_idle()


sd.on_changed(update)
st0.on_changed(update)

# Generate reset button
resetax = plt.axes([0.8, 0.02, 0.1, 0.04])
button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')


def reset(event):
    sd.reset()
    st0.reset()


button.on_clicked(reset)

plt.show()
Exemplo n.º 41
0
class Animation:
    """The foundation of all animations.

    Parameters
    ----------
    blocks : list of animatplot.animations.Block
        A list of blocks to be animated
    timeline : Timeline or 1D array, optional
        If an array is passed in, it will be converted to a Timeline.
        If not given, a timeline will be created using the length of the
        first block.
    fig : matplotlib figure, optional
        The figure that the animation is to occur on

    Attributes
    ----------
    animation
        a matplotlib animation returned from FuncAnimation
    """
    def __init__(self, blocks, timeline=None, fig=None):
        if timeline is None:
            self.timeline = Timeline(range(len(blocks[0])))
        elif not isinstance(timeline, Timeline):
            self.timeline = Timeline(timeline)
        else:
            self.timeline = timeline

        _len_time = len(self.timeline)
        for block in blocks:
            if len(block) != _len_time:
                raise ValueError(
                    "All blocks must animate for the same amount of time")

        self.blocks = blocks
        self.fig = plt.gcf() if fig is None else fig
        self._has_slider = False
        self._pause = False

        def animate(i):
            updates = []
            for block in self.blocks:
                updates.append(block._update(self.timeline.index))
            if self._has_slider:
                self.slider.set_val(self.timeline.index)
            self.timeline._update()
            return updates

        self.animation = FuncAnimation(self.fig,
                                       animate,
                                       frames=self.timeline._len,
                                       interval=1000 / self.timeline.fps)

    def toggle(self, axis=None):
        """Creates a play/pause button to start/stop the animation

        Parameters
        ----------
        axis : optional
            A matplotlib axis to attach the button to.
        """
        if axis is None:
            adjust_plot = {'bottom': .2}
            rect = [.78, .03, .1, .07]

            plt.subplots_adjust(**adjust_plot)
            self.button_ax = plt.axes(rect)
        else:
            self.button_ax = axis

        self.button = Button(self.button_ax, "Pause")
        self.button.label2 = self.button_ax.text(
            0.5,
            0.5,
            'Play',
            verticalalignment='center',
            horizontalalignment='center',
            transform=self.button_ax.transAxes)
        self.button.label2.set_visible(False)

        def pause(event):
            if self._pause:
                self.animation.event_source.start()
                self.button.label.set_visible(True)
                self.button.label2.set_visible(False)
            else:
                self.animation.event_source.stop()
                self.button.label.set_visible(False)
                self.button.label2.set_visible(True)
            self.fig.canvas.draw()
            self._pause ^= True

        self.button.on_clicked(pause)

    def timeline_slider(self,
                        text='Time',
                        axis=None,
                        valfmt='%1.2f',
                        color=None):
        """Creates a timeline slider.

        Parameters
        ----------
        text : str, optional
            The text to display for the slider. Defaults to 'Time'
        axis : optional
            A matplotlib axis to attach the slider to
        valfmt : str, optional
            a format specifier used to print the time
            Defaults to '%1.2f'
        color :
            The color of the slider.
        """
        if axis is None:
            adjust_plot = {'bottom': .2}
            rect = [.18, .05, .5, .03]

            plt.subplots_adjust(**adjust_plot)
            self.slider_ax = plt.axes(rect)
        else:
            self.slider_ax = axis

        if self.timeline.log:
            valfmt = '$10^{%s}$' % valfmt

        self.slider = Slider(self.slider_ax,
                             text,
                             0,
                             self.timeline._len - 1,
                             valinit=0,
                             valfmt=(valfmt + self.timeline.units),
                             valstep=1,
                             color=color)
        self._has_slider = True

        def set_time(t):
            self.timeline.index = int(self.slider.val)
            self.slider.valtext.set_text(self.slider.valfmt %
                                         (self.timeline[self.timeline.index]))
            if self._pause:
                for block in self.blocks:
                    block._update(self.timeline.index)
                self.fig.canvas.draw()

        self.slider.on_changed(set_time)

    def controls(self, timeline_slider_args={}, toggle_args={}):
        """Creates interactive controls for the animation

        Creates both a play/pause button, and a time slider at once

        Parameters
        ----------
        timeline_slider_args : Dict, optional
            A dictionary of arguments to be passed to timeline_slider()
        toggle_args : Dict, optional
            A dictionary of argyments to be passed to toggle()
        """
        self.timeline_slider(**timeline_slider_args)
        self.toggle(**toggle_args)

    def save_gif(self, filename):
        """Saves the animation to a gif

        A convience function. Provided to let the user avoid dealing
        with writers.

        Parameters
        ----------
        filename : str
            the name of the file to be created without the file extension
        """
        self.timeline.index -= 1  # required for proper starting point for save
        self.animation.save(filename + '.gif',
                            writer=PillowWriter(fps=self.timeline.fps))

    def save(self, *args, **kwargs):
        """Saves an animation

        A wrapper around :meth:`matplotlib.animation.Animation.save`
        """
        self.timeline.index -= 1  # required for proper starting point for save
        self.animation.save(*args, **kwargs)
Exemplo n.º 42
0
ax[0].set_ylabel('Local Time')
ax[0].yaxis_date()
ax[0].yaxis.set_major_formatter(date_format)

cbar_ax = f.add_axes([0.85, 0.15, 0.05, 0.7])
c = f.colorbar(p[0], cax=cbar_ax)
c.set_label('Power (dB, arbitrary)')

from matplotlib.widgets import Slider, Button

rax = plt.axes([0.82, 0.03, 0.15, 0.04])
check = Button(rax, 'Med Subtract')


def func(event):
    global medsub, check, colorscale
    medsub = not medsub
    if medsub:
        check.label.set_text("Med Subtracted")
        colorscale = [-0.5, 0.5]
    else:
        check.label.set_text("Raw Power")
        colorscale = [-10, 10]


check.on_clicked(func)

ani = animation.FuncAnimation(f, updatefig, frames=100, interval=100)
f.show()
Exemplo n.º 43
0
def held_karp(dists):
	"""
	Implementation of Held-Karp, an algorithm that solves the Traveling
	Salesman Problem using dynamic programming with memoization.
	Parameters:
	dists: distance matrix
	Returns:
	A tuple, (cost, path).
	"""
	n = len(dists)

	C = {}

	for k in range(1, n):
		C[(1 << k, k)] = (dists[0][k], 0)

	for subset_size in range(2, n):
		for subset in itertools.combinations(range(1, n), subset_size):
		# Set bits for all nodes in this subset
		bits = 0
		for bit in subset:
			bits |= 1 << bit

		# Find the lowest cost to get to this subset
		for k in subset:
			prev = bits & ~(1 << k)

			res = []
			for m in subset:
				if m == 0 or m == k:
					continue
				res.append((C[(prev, m)][0] + dists[m][k], m))
			C[(bits, k)] = min(res)

	bits = (2**n - 1) - 1

	res = []
	for k in range(1, n):
		res.append((C[(bits, k)][0] + dists[k][0], k))
	opt, parent = min(res)

	path = []
	for i in range(n - 1):
		path.append(parent)
		new_bits = bits & ~(1 << parent)
		_, parent = C[(bits, parent)]
		bits = new_bits
	path.append(0)
	return opt, list(reversed(path))


def solve(event):
	global n, trucks, solver, li, ax, warehouses, loc_x, loc_y, lines_x, lines_y, obj_value, exec_value
	global distances, distances2
	print("solving...")

	ax.clear()
	ax.set_xlim(0,1000)
	ax.set_ylim(0,1000)
	plot_data(ax, loc_x, loc_y, warehouses)
	ax.text(400, 1075, "solving...", family="serif", horizontalalignment='left', verticalalignment='top')
	plt.draw()
	fig.canvas.draw()

	start_time = time.time()

	# Calculate constraint for Li
	total_l = 0
	total_c = 0.0
	paths = 0
	slack = False
	while total_c < n or paths < trucks:
		c1 = min(c,n)
		total_c += c1
		total_l += c1*(c1+1)/2
		paths += 1

	if total_c > n:
		slack = True

	if solver=="cbc" or solver=="glpk" or solver=="gurobi":
		# Objective function
		z = pulp.LpProblem('Test', pulp.LpMinimize)

		# Generate decision variables
		x = {}
		y = {}
		variables = []
		l = {}
		s = {}
		for i in range(n+warehouses):
			for j in range(n+warehouses):
				if i==j:
					continue
				x[i,j] = pulp.LpVariable('x_' + str(i) + '_' + str(j), 0, 1, pulp.LpInteger)
			if i >= warehouses:
				l[i] = pulp.LpVariable('l_' + str(i), 1, min(n,c), pulp.LpInteger)

		# Objective function
		z += pulp.lpSum([distances[i][j] * x[i,j] for i in range(n+warehouses) for j in 
			list(range(i)) + list(range(i+1,n+warehouses))])

		# Constraints
		constraintSeq = []
		constraintTrucks = []
		for i in range(n+warehouses):
			if i>=warehouses:
				constraintSeq.append(l[i])
			constraintFrom = []

			constraintTo = []
			for j in range(n+warehouses):
				if i==j:
					continue
				if i>=warehouses and j>=warehouses:
					z += pulp.lpSum([l[i], -1*l[j], n*x[i,j], -n+1]) <= 0

				if i>=warehouses:
					constraintFrom.append(x[i,j])
					constraintTo.append(x[j,i])
				if i<warehouses:
					constraintTrucks.append(x[j,i])
				if i>=warehouses:
					z += pulp.lpSum(constraintFrom) == 1 # paths from location
					z += pulp.lpSum(constraintTo) == 1 # paths to location
				if i==warehouses and (paths > 1 or warehouses>1):
					z += pulp.lpSum(constraintTrucks) == paths # paths to warehouse

		if not slack:
		z += pulp.lpSum(constraintSeq) == total_l
		else:
		z += pulp.lpSum(constraintSeq) <= total_l

		# Solve
		if solver=="cbc":
			status = z.solve()
		if solver=="glpk":
			status = z.solve(pulp.GLPK())		
		if solver=="gurobi":
			status = z.solve(pulp.GUROBI_CMD())

		# should be 'Optimal'
		if pulp.LpStatus[status]!="Optimal":
			print("RESULT: ".pulp.LpStatus[status])
		print("Objective function value: "+str(z.objective.value()))

		# Print variables & save path
		lines_x = []
		lines_y = []
		li = [0] * n
		for i in range(n+warehouses):
			if i>=warehouses:
				li[i-warehouses] = pulp.value(l[i])
			for j in range(n+warehouses):
				if i==j:
					continue
				if pulp.value(x[i,j]) == 1:
					lines_x.append(loc_x[i])
					lines_x.append(loc_x[j])
					lines_y.append(loc_y[i])
					lines_y.append(loc_y[j])
					lines_x.append(np.nan)
					lines_y.append(np.nan)

		obj_value = "c=" + str(round(z.objective.value(),2))

	elif solver=="cut plane":
		model = Model("tsp")
		model.hideOutput()
		x = {}
		l = {}
		for i in range(n+warehouses):
			for j in range(n+warehouses):
				if i != j:
					x[i,j] = model.addVar(ub=1, name="x(%s,%s)"%(i,j))
			if (paths > 1 or warehouses > 1) and i >= warehouses:
				l[i] = model.addVar(ub=min(c,n),lb=1, name="l(%s)"%(i))

		if paths == 1 and warehouses == 1:

			# SYMMETRIC DISTANCE MATRIX ONLY
			#for i in range(n+warehouses):
			#model.addCons(quicksum(x[j,i] for j in range(n+warehouses) if j != i) + \
			# quicksum(x[i,j] for j in range(n+warehouses) if j != i) == 2,"Degree(%s)"%i)

			# ASYMMETRIC DISTANCE MATRIX
			for i in range(n+warehouses):
				model.addCons(quicksum(x[j,i] for j in range(n+warehouses) if j != i) == 1,"In(%s)"%i)
				model.addCons(quicksum(x[i,j] for j in range(n+warehouses) if j != i) == 1,"Out(%s)"%i)
		
		else:
			for i in range(warehouses, n+warehouses):
				model.addCons(quicksum(x[j,i] for j in range(n+warehouses) if j != i) == 1,"In(%s)"%i)
				model.addCons(quicksum(x[i,j] for j in range(n+warehouses) if j != i) == 1,"Out(%s)"%i)

			for i in range(warehouses, n+warehouses):
				for j in range(warehouses, n+warehouses):
					if i!=j:
						model.addCons(l[i] -l[j] +n*x[i,j] <= n-1, "Li(%s,%s)"%(i,j))
			model.addCons(quicksum(x[j,i] for i in range(warehouses) for j in range(n+warehouses) if i!=j) == paths, "Paths(%s)"%paths)

			if not slack:
				model.addCons(quicksum(l[i] for i in range(warehouses,n+warehouses)) == total_l,"TotalL")
			
			else:
				model.addCons(quicksum(l[i] for i in range(warehouses,n+warehouses)) <= total_l, "TotalL")
		
		model.setObjective(quicksum(distances2[i,j]*x[i,j] for (i,j) in x), "minimize")

		EPS = 1.e-6
		isMIP = False
		model.setPresolve(SCIP_PARAMSETTING.OFF)

		while True:
			model.optimize()
			#edges = []
			lines_x = []
			lines_y = []
			edges = []
			li = [0] * n
			for (i,j) in x:
				# i=j already skipped
				if model.getVal(x[i,j]) > EPS:
					#edges.append( (i,j) )
					lines_x.append(loc_x[i])
					lines_x.append(loc_x[j])
					lines_y.append(loc_y[i])
					lines_y.append(loc_y[j])
					lines_x.append(np.nan)
					lines_y.append(np.nan)
					edges.append( (i,j) )
			if paths>1 or warehouses>1:
				for i in range(warehouses, n+warehouses):
					li[i-warehouses] = int(model.getVal(l[i]))

			obj_value = "c=" + str(round(model.getObjVal(),2))

			ax.clear()
			ax.set_xlim(0,1000)
			ax.set_ylim(0,1000)

			plot_data_lines(lines_x,lines_y)
			plot_data(ax, loc_x, loc_y, warehouses)
			ax.text(400, 1075, "solving...", family="serif", horizontalalignment='left', verticalalignment='top')

			fig.canvas.draw()

			if addcut(edges,model,x,warehouses) == False:
				if isMIP: # integer variables, components connected: solution found
					break
				model.freeTransform()
				for (i,j) in x: # all components connected, switch to integer model
					model.chgVarType(x[i,j], "B")
				if paths > 1 or warehouses > 1:
					for i in range(warehouses,n+warehouses):
						model.chgVarType(l[i], "I")
				isMIP = True

		sol_li = [0] * (n+warehouses)
		sol_xij = {}

		print('solved.')
	elif solver == 'held-karp':
		li = [0] * n
		opt, path = held_karp(distances)
		print(path)
		obj_value = "c=" + str(round(opt,2))
		x = [[0 for x in range(n+warehouses)] for y in range(n+warehouses)]
		for idx, val in enumerate(path):
			if idx < (len(path)-1):
				x[val][path[idx+1]] = 1;
			elif idx == (len(path)-1):
				x[val][path[0]] = 1;

		for i in range(n+warehouses):
			for j in range(n+warehouses):
				if x[i][j] == 1:
					#edges.append( (i,j) )
					lines_x.append(loc_x[i])
					lines_x.append(loc_x[j])
					lines_y.append(loc_y[i])
					lines_y.append(loc_y[j])
					lines_x.append(np.nan)
					lines_y.append(np.nan)
					#edges.append( (i,j) )

	# Print computation time
	time2 = time.time() - start_time
	exec_value = time2
	units = 'secs'
	if time2 > 60:
		time2 /= 60
		units = 'mins'
	if time2 > 60:
		time2 /= 60
		units = 'hours'

	time2 = round(time2,2)

	exec_value = "exec=" + str(time2) + " " + units

	print("--- " + str(time2) + " " + units + " ---")

	# Redraw points
	ax.clear()
	ax.set_xlim(0,1000)
	ax.set_ylim(0,1000)

	plot_data_lines(lines_x,lines_y)
	plot_data(ax, loc_x, loc_y, warehouses)

	ax.text(350, 1075, obj_value, family="serif", horizontalalignment='right', verticalalignment='top')
	ax.text(450, 1075, exec_value, family="serif", horizontalalignment='left', verticalalignment='top')
	fig.canvas.draw()
	
axsolve = plt.axes([0.87, 0.905, 0.1, 0.075])
bsolve = Button(axsolve, 'Solve')
bsolve.on_clicked(solve)
plt.show()
Exemplo n.º 44
0
    T = Tvals[Tind]
    point.set_data(Tvals[Tind], states[Tind])

    val_slider.set_val(states[Tind])

    ax.set_ylim([
        np.min(W.States[0:N_slider.val]) - 1,
        np.max(W.States[0:N_slider.val]) + 1
    ])
    fig.canvas.draw_idle()


N_slider.on_changed(sliders_on_changed)
t_slider.on_changed(sliders_on_changed)

# Add a button for resetting the parameters
reset_button_ax = fig.add_axes([0.8, 0.02, 0.1, 0.01])
reset_button = Button(reset_button_ax,
                      'Reset',
                      color=axis_color,
                      hovercolor='0.975')


def reset_button_on_clicked(mouse_event):
    N_slider.reset()


reset_button.on_clicked(reset_button_on_clicked)

plt.show()
Exemplo n.º 45
0
            d = float(text)
        except ValueError:
            print("Вы пытаетесь ввести не число")

    #Create graph
    fig, graph_axes = plt.subplots()
    graph_axes.grid()
    graph_axes.set_title('Model Trays - Volterra')
    fig.subplots_adjust(left=0.06, right=0.80, top=0.95, bottom=0.23)

    #Create add button
    axes_button_add = plt.axes([0.55, 0.01, 0.4, 0.075])
    button_add = Button(axes_button_add,
                        'Добавить новый график',
                        hovercolor='#f0f0f0')
    button_add.on_clicked(onButtonAddClicked)

    #Create clear buttin
    axes_button_clear = plt.axes([0.05, 0.01, 0.4, 0.075])
    button_clear = Button(axes_button_clear,
                          'Очистить график',
                          hovercolor='#f0f0f0')
    button_clear.on_clicked(onButtonClearClicked)

    #Create textbox
    axbox = plt.axes([0.88, 0.90, 0.10, 0.075])
    x0_box = TextBox(axbox,
                     'Задача \n Коши \n x0 =',
                     initial="0.1",
                     hovercolor='#d9d9d9')
    x0 = 0.1
Exemplo n.º 46
0
# Add a time slider
if len(all_times) > 1:
    axfreq = plt.axes([0.1, 0.0, 0.5, 0.03])
    time_slider = Slider(axfreq, 'ix', 0., len(all_times) - 1, 0.)
    time_slider.on_changed(update)

# Add buttons to go to next/previous variable and snapshot, and one to switch
# between primitive
axprev_iw = plt.axes([0.8, 0.0, 0.075, 0.05])
axnext_iw = plt.axes([0.875, 0.0, 0.075, 0.05])
axprim = plt.axes([0.95, 0.0, 0.05, 0.05])
axprev_file = plt.axes([0.0, 0.0, 0.05, 0.05])
axnext_file = plt.axes([0.7, 0.0, 0.05, 0.05])

bnext_iw = Button(axnext_iw, '+iw')
bnext_iw.on_clicked(next_var)
bprev_iw = Button(axprev_iw, '-iw')
bprev_iw.on_clicked(prev_var)
bnext_file = Button(axnext_file, '+')
bnext_file.on_clicked(next_file)
bprev_file = Button(axprev_file, '-')
bprev_file.on_clicked(prev_file)
bprim = Button(axprim, 'P/C')
bprim.on_clicked(switch_cons_prim)

# Initial state
i_var = 1
i_file = 0
is_conservative = True

line, = ax.plot(all_cons[0][:, 0], all_cons[0][:, i_var])
Exemplo n.º 47
0
class Viewer:

    # GUI object

    def __init__(self, gui_params, params):

        # loads metadata from available xls files
        if gui_params['load_metadata']:

            self.curation_data = utils.load_manual_curation(
                params['curation_csvpath'])
            self.males_list = utils.load_male_list(params['male_listpath'])
            self.induction_dates = utils.load_induction_data(
                params['induction_csvpath'])
            self.season_data = utils.load_pond_season_data(
                params['pond_season_csvpath'])
            self.early_release = utils.load_release_data(
                params['early_release_csvpath'])
            self.late_release = utils.load_release_data(
                params['late_release_csvpath'])
            self.duplicate_data = utils.load_duplicate_data(
                params['duplicate_csvpath'])
            self.experimenter_data, self.inducer_data = utils.load_experimenter_data(
                params['experimenter_csvpath'])

        # loads in default params from txt files
        self.gui_params = gui_params
        self.params = params
        self.params.update(self.gui_params)
        self.auto_save_count = 0

        file_list = []
        metadata_list = []
        print "Reading in image file list"

        with open(self.params["image_list_filepath"], "rb") as f:
            line = f.readline().strip()
            while line:
                file_list.append(line)
                line = f.readline().strip()

        print "Reading in analysis file"

        self.data = utils.csv_to_df(self.params["input_analysis_file"])

        try:
            saved_data = utils.csv_to_df(self.params["output_analysis_file"])

            for row in saved_data.iterrows():
                i = np.where(self.data['filebase'] == row[1]['filebase'])
                for k, v in row[1].iteritems():
                    self.data.loc[i[0], k] = v

        except IOError:
            pass

        if not hasattr(self.data, 'accepted'):
            self.data['accepted'] = np.zeros(len(self.data))

        self.shape_data = utils.read_shape_long(
            self.params["input_shape_file"])

        try:
            saved_shape_data = utils.read_shape_long(
                self.params["output_shape_file"])
            fbs = np.unique(saved_shape_data['filebase'])
            self.shape_data = self.shape_data.drop(
                self.shape_data[self.shape_data['filebase'].isin(fbs)].index)
            self.shape_data = self.shape_data.append(saved_shape_data)
        except IOError:
            print("No output shape data")
            pass

        try:
            self.masked_regions = utils.read_masked_regions_long(
                self.params["masked_regions_output"])
        except IOError:
            self.masked_regions = {}

        all_clone_list = []

        for f in file_list:
            try:
                if os.name == "nt":
                    fileparts = f.split("\\")
                else:
                    fileparts = f.split("/")
                clone = utils.dfrow_to_clone(
                    self.data,
                    np.where(self.data.filebase == fileparts[-1])[0][0],
                    self.params)
                clone.filepath = f
                all_clone_list.append(clone)

            except IndexError:
                print "No entry found in datafile for " + str(f)

        for i in xrange(len(all_clone_list)):
            index = (self.shape_data.filebase == all_clone_list[i].filebase)
            all_clone_list[i].dorsal_edge = np.transpose(
                np.vstack((np.transpose(self.shape_data.loc[index].x),
                           np.transpose(self.shape_data.loc[index].y))))
            all_clone_list[i].q = np.array(self.shape_data.loc[index].q)
            all_clone_list[i].qi = np.array(self.shape_data.loc[index].qi)
            idx = self.shape_data.loc[index].checkpoint == 1
            all_clone_list[i].checkpoints = all_clone_list[i].dorsal_edge[
                idx, :]

        clone_list = []
        for clone in all_clone_list:
            print clone.dorsal_edge
            if len(clone.dorsal_edge) > 0:
                if not (int(self.params['skip_accepted']) and clone.accepted):
                    clone_list.append(clone)
            else:
                print "No shape data found for " + clone.filebase

        if len(clone_list) == 0:
            print "Either image list is empty or they have all been 'accepted'"
            return

        self.all_clone_list = all_clone_list
        self.clone_list = clone_list

        self.curr_idx = 0
        self.clone = self.clone_list[self.curr_idx]

        self.saving = 0
        self.fig = plt.figure(figsize=(15, 10))
        self.fig.patch.set_facecolor("lightgrey")
        self.display = self.fig.add_subplot(111)
        self.display.axis('off')

        try:
            self.obj = PointFixer(self.clone, self.display)

            try:
                self.obj.masked_regions = self.masked_regions[
                    self.clone.filebase]
                self.mask_all_regions()
            except (AttributeError, KeyError):
                pass

        except IOError:

            try:
                self.clone.modification_notes += " Image file not found."
            except TypeError:
                self.clone.modification_notes = "Image file not found."

            if self.curr_idx < len(self.clone_list) - 1:
                self.next_button_press(1)

        self.obj.clone.modifier = self.gui_params["default_modifier"]
        self.populate_figure()
        self.add_checkpoint = False

        return

    def populate_figure(self):

        # updates GUI button placement, colors, etc

        self.display.clear()

        button_color = [0.792156862745098, 0.8823529411764706, 1.0]

        if self.saving == 1:
            self.saving_text = self.fig.text(0.875,
                                             0.879,
                                             'Saving',
                                             fontsize=10,
                                             fontweight='bold',
                                             color=[0.933, 0.463, 0])
        else:
            try:
                self.saving_text.remove()
            except (ValueError, AttributeError):
                pass

        self.notes_text = self.fig.text(0.852,
                                        0.575,
                                        'Notes',
                                        fontsize=10,
                                        color="black")

        axmodnotes = plt.axes([0.852, 0.45, 0.125, 0.12])

        initial_modnotes = str(self.obj.clone.modification_notes)
        if initial_modnotes == "nan":
            initial_modnotes = ""

        self.notestextbox = TextBox(axmodnotes, '', initial=initial_modnotes)
        self.notestextbox.on_submit(self.set_notes)

        axmodifier = plt.axes([0.875, 0.37, 0.1, 0.035])
        self.modifiertextbox = TextBox(axmodifier,
                                       'Initials',
                                       initial=str(
                                           self.params['default_modifier']))
        self.modifiertextbox.on_submit(self.change_default_modifier)

        axflip = plt.axes([0.50, 0.01, 0.1, 0.075])
        self.flipbutton = Button(axflip,
                                 'Flip',
                                 color=button_color,
                                 hovercolor=button_color)
        self.flipbutton.on_clicked(self.obj.flip_button_press)

        axedges = plt.axes([0.60, 0.01, 0.1, 0.075])
        self.edgebutton = Button(axedges,
                                 'Toggle Edges',
                                 color=button_color,
                                 hovercolor=button_color)
        self.edgebutton.on_clicked(self.obj.edge_button_press)

        axtogdorsal = plt.axes([0.70, 0.01, 0.1, 0.075])
        self.togdorsalbutton = Button(axtogdorsal,
                                      'Toggle Dorsal Fit',
                                      color=button_color,
                                      hovercolor=button_color)
        self.togdorsalbutton.on_clicked(self.obj.toggle_dorsal_button_press)

        axdel = plt.axes([0.025, 0.01, 0.1, 0.075])
        self.delcheckbutton = Button(axdel,
                                     'Delete Checkpoint',
                                     color=button_color,
                                     hovercolor=button_color)
        self.delcheckbutton.on_clicked(self.obj.delete_selected_checkpoint)

        axsave = plt.axes([0.875, 0.8, 0.1, 0.075])
        self.savebutton = Button(axsave,
                                 'Save',
                                 color=button_color,
                                 hovercolor=button_color)
        self.savebutton.on_clicked(self.save)

        axblur = plt.axes([0.25, 0.01, 0.1, 0.035])
        self.blurtextbox = TextBox(axblur,
                                   'Gaussian Blur StDev',
                                   initial=str(self.obj.edge_blur))
        self.blurtextbox.on_submit(self.set_edge_blur)

        axreset = plt.axes([0.40, 0.01, 0.1, 0.075])
        self.resetbutton = Button(axreset,
                                  'Reset',
                                  color=button_color,
                                  hovercolor=button_color)
        self.resetbutton.on_clicked(self.reset_button_press)

        if self.curr_idx + 1 < len(self.clone_list):
            axnext = plt.axes([0.875, 0.01, 0.1, 0.075])
            self.nextbutton = Button(axnext,
                                     'Next',
                                     color=button_color,
                                     hovercolor=button_color)
            self.nextbutton.on_clicked(self.next_button_press)

        if self.curr_idx > 0:
            axprev = plt.axes([0.875, 0.085, 0.1, 0.075])
            self.prevbutton = Button(axprev,
                                     'Previous',
                                     color=button_color,
                                     hovercolor=button_color)
            self.prevbutton.on_clicked(self.prev_button_press)

        self.obj.draw()

    def set_notes(self, text):

        # saves any viable, user-added notes in text field

        try:
            self.obj.clone.modification_notes = str(text)
            self.obj.draw()
        except ValueError:
            print "Invalid value for notes"

    def set_edge_blur(self, text):

        # sets the edge blur value, updates the binary edge image

        try:
            self.obj.edge_blur = float(text)
        except ValueError:
            print "Invalid value for gaussian blur sigma"

        self.obj.clone.initialize_dorsal_edge(
            self.obj.original_image, dorsal_edge_blur=self.obj.edge_blur)
        self.obj.clone.fit_dorsal_edge(self.obj.original_image,
                                       dorsal_edge_blur=self.obj.edge_blur)
        self.obj.de = self.obj.clone.interpolate(self.obj.clone.dorsal_edge)
        self.obj.edge_image = self.obj.clone.edges

        self.mask_all_regions()

        self.obj.checkpoints = self.obj.clone.checkpoints

        self.obj.edges = False
        self.obj.edge_button_press(1)

        self.obj.clone.dorsal_edge_blur = self.obj.edge_blur

        self.obj.draw()

    def mask_all_regions(self):

        try:
            for region_id in xrange(len(self.obj.masked_regions.keys())):
                region = self.obj.masked_regions[region_id]
                if region[0] == "u":
                    self.obj.lasso_then_unmask(region[1],
                                               add_to_metadata=False)
                elif region[0] == "m":
                    self.obj.lasso_then_mask(region[1], add_to_metadata=False)

        except AttributeError:
            pass

    def change_default_modifier(self, text):

        self.gui_params['default_modifier'] = str(text)

        with open("gui_params.txt", "w+") as f:
            for k, v in gui_params.items():
                f.write(str(k) + ", " + str(v) + "\n")

        self.obj.clone.modifier = self.gui_params["default_modifier"]

    def prev_button_press(self, event):

        # moves to the previous image in the list relative to the current clone

        self.clone_list[self.curr_idx] = self.obj.clone
        self.masked_regions[self.obj.clone.filebase] = self.obj.masked_regions

        self.curr_idx -= 1
        self.clone = self.clone_list[self.curr_idx]

        self.fig.clear()

        self.display = self.fig.add_subplot(111)
        self.display.axis('off')

        self.obj = PointFixer(self.clone, self.display)
        self.obj.clone.modifier = self.gui_params["default_modifier"]

        try:
            self.obj.masked_regions = self.masked_regions[
                self.obj.clone.filebase]
            self.mask_all_regions()

        except KeyError:
            pass

        self.populate_figure()

        return

    def next_button_press(self, event):

        # moves to the next image in the list

        try:
            self.clone_list[self.curr_idx] = self.obj.clone
            self.masked_regions[
                self.obj.clone.filebase] = self.obj.masked_regions
        except AttributeError:
            self.clone_list[self.curr_idx] = self.clone

        self.auto_save_count += 1
        if self.gui_params["auto_save"]:
            if self.auto_save_count == self.gui_params["auto_save_number"]:
                self.save(1)
                self.auto_save_count = 0

        self.curr_idx += 1

        try:

            self.clone = self.clone_list[self.curr_idx]

            if os.path.isfile(self.clone.filepath):

                self.fig.clear()
                self.display = self.fig.add_subplot(111)
                self.display.axis('off')
                self.obj.clone.modifier = self.gui_params["default_modifier"]

                self.obj = PointFixer(self.clone, self.display)

                try:
                    self.obj.masked_regions = self.masked_regions[
                        self.obj.clone.filebase]
                    self.mask_all_regions()
                except KeyError:
                    pass

            else:
                print "Image " + self.clone.filepath + " not found. Check your image filepath."
                raise IOError

        except IOError:

            try:
                self.clone.modification_notes += " Image file not found."
            except TypeError:
                self.clone.modification_notes = "Image file not found."
            if self.curr_idx < len(self.clone_list) - 1:
                self.next_button_press(event)
            else:
                self.curr_idx -= 1
                self.clone = self.clone_list[self.curr_idx]

        self.populate_figure()

    def reset_button_press(self, event):

        # resets current clone to default and redraws

        if self.obj.clone.flip:
            self.obj.clone.flip = not self.obj.clone.flip

        self.obj.clone.find_features(self.obj.original_image,
                                     **self.obj.params)
        self.obj.clone.get_orientation_vectors()
        self.obj.clone.find_head(self.obj.original_image, **self.obj.params)
        self.obj.edge_blur = 1.0
        self.blurtextbox.set_val('1.0')
        self.obj.clone.dorsal_blur = 1.0
        self.obj.edge_image = self.obj.original_edge_image.copy()
        if self.obj.edges:
            self.obj.image = self.obj.edge_image
        self.obj.clone.initialize_dorsal_edge(self.obj.original_image,
                                              edges=self.obj.edge_image,
                                              **self.obj.params)
        self.obj.clone.fit_dorsal_edge(self.obj.original_image,
                                       **self.obj.params)
        self.obj.clone.find_tail(self.obj.original_image)
        self.obj.masked_regions = {}
        self.obj.clone.remove_tail_spine()
        self.obj.de = self.obj.clone.interpolate(self.obj.clone.dorsal_edge)
        self.obj.selected = None
        self.obj.checkpoints = self.obj.clone.checkpoints

        self.obj.draw()

    def save(self, event):

        # saves all data (modified and unmodofied) to new csv

        print "Saving..."

        self.clone_list[self.curr_idx] = self.obj.clone
        self.masked_regions[self.obj.clone.filebase] = self.obj.masked_regions

        for all_c in xrange(len(self.all_clone_list)):
            for c in xrange(len(self.clone_list)):
                if self.all_clone_list[all_c].filebase == self.clone_list[
                        c].filebase:
                    self.all_clone_list[all_c] = self.clone_list[c]
        self.saving = 1
        self.populate_figure()

        with open(self.params["input_analysis_file"],
                  "rb") as analysis_file_in, open(
                      self.params["output_analysis_file"],
                      "wb") as analysis_file_out:

            # read/write header and save column names
            line = analysis_file_in.readline()
            analysis_file_out.write(line)
            line = line.strip()
            DATA_COLS = line.split("\t")

            line = analysis_file_in.readline()
            while line:
                written = False
                for clone in self.all_clone_list:
                    if (line.split("\t")[0]
                            == clone.filebase) and clone.accepted:

                        analysis_file_out.write(
                            utils.clone_to_line(clone, DATA_COLS) + "\n")
                        written = True

                if (not written) and (not self.params['truncate_output']):
                    analysis_file_out.write(line)

                line = analysis_file_in.readline()

        with open(self.params["output_shape_file"], "wb") as shape_file_out:

            # read/write header
            line = "\t".join(
                ["filebase", "i", "x", "y", "qi", "q", "checkpoint"]) + "\n"
            shape_file_out.write(line)

            clone = None

            for c in self.all_clone_list:
                if c.accepted:
                    clone = c
                if clone is not None:

                    for i in np.arange(len(clone.dorsal_edge)):
                        if len(
                                np.where((clone.checkpoints
                                          == clone.dorsal_edge[i, :]).all(
                                              axis=1))[0]) > 0:
                            checkpoint = 1
                        else:
                            checkpoint = 0
                        shape_file_out.write('\t'.join([
                            clone.filebase,
                            str(i),
                            str(clone.dorsal_edge[i, 0]),
                            str(clone.dorsal_edge[i, 1]),
                            str(clone.qi[i]),
                            str(clone.q[i]),
                            str(checkpoint)
                        ]) + "\n")

                clone = None

        self.saving = 0
        self.populate_figure()

        with open(self.params["input_analysis_metadata_file"],
                  "rb") as analysis_file_in, open(
                      self.params["output_analysis_metadata_file"],
                      "wb") as analysis_file_out:

            line = analysis_file_in.readline()
            analysis_file_out.write(line)

            line = analysis_file_in.readline()

            while line:
                written = False
                for clone in self.all_clone_list:
                    if (line.split("\t")[0]
                            == clone.filebase) and clone.accepted:

                        metadata = [clone.filebase] + [
                            str(getattr(clone, mf))
                            for mf in ANALYSIS_METADATA_FIELDS
                        ]
                        analysis_file_out.write("\t".join(metadata + ["\n"]))
                        written = True

                if (not written) and (not self.params['truncate_output']):
                    analysis_file_out.write(line)

                line = analysis_file_in.readline()

        with open(self.params["masked_regions_output"], "wb") as file_out:

            file_out.write("\t".join(
                ["filebase", "i", "x", "y", "masking_or_unmasking"]) + "\n")

            for clone in self.all_clone_list:
                if clone.accepted:
                    try:
                        masked_regions = self.masked_regions[clone.filebase]
                        for i in xrange(len(masked_regions.keys())):
                            m_or_u, region = masked_regions[i]
                            for j in xrange(region.shape[0]):
                                file_out.write("\t".join([
                                    clone.filebase,
                                    str(i),
                                    str(region[j][0]),
                                    str(region[j][1]), m_or_u
                                ]) + "\n")
                    except KeyError:
                        continue
        print "Saving done."
Exemplo n.º 48
0
class SelectPanel():
    """Displays radio buttons for paw classification and the current paw number.
    Alse displays information on the combination process
    """
    def __init__(self, fig, outer):
        #you may want this to not be a title, for now seems good enough
        self.title_axes = fig.add_subplot(outer[1, 1])
        self.title_axes.set_axis_off()
        g = gspec.GridSpecFromSubplotSpec(1,
                                          2,
                                          subplot_spec=outer[1, 1],
                                          wspace=0.1,
                                          hspace=0.1)
        self.lr_axis = fig.add_subplot(g[0, 1])
        self.lr_axis.set_axis_off()
        self.fh_axis = fig.add_subplot(g[0, 0])
        self.fh_axis.set_axis_off()

        #button_holder = fig.add_subplot(outer[1,1])
        #button_holder.set_axis_off()
        g = gspec.GridSpecFromSubplotSpec(4,
                                          1,
                                          subplot_spec=outer[2, 1],
                                          wspace=0.1,
                                          hspace=0.1)
        #g.update(left=0.15, right=0.85, wspace=0.02, hspace=.04,
        #         bottom = .02, top = .98)
        self.del_but_ax = fig.add_subplot(g[1, 0])
        self.merge_but_ax = fig.add_subplot(g[2, 0])
        self.split_but_ax = fig.add_subplot(g[3, 0])
        self.del_but_ax.set_axis_off()
        self.split_but_ax.set_axis_off()

    def set_print_manager(self, pm):
        self.print_manager = pm

    def set_selected(self, print_numb, is_right, is_hind):
        """when a paw is selected, set the radio buttons and their callbacks
        """
        self.clear_axes()
        self.title_axes.set_title('Print ' + str(print_numb))
        self.lr_but = RadioButtons(self.lr_axis, ('Left', 'Right'),
                                   active=int(is_right))
        self.fh_but = RadioButtons(self.fh_axis, ('Front', 'Hind'),
                                   active=int(is_hind))
        self.lr_but.on_clicked(self.print_manager.change_print_classification)
        self.fh_but.on_clicked(self.print_manager.change_print_classification)
        self.del_but_ax.set_axis_on()
        self.del_but = Button(self.del_but_ax, 'Delete')
        self.del_but.on_clicked(
            lambda x: self.print_manager.delete_print(print_numb))
        self.merge_but = Button(self.merge_but_ax, 'Merge')
        self.merge_but.on_clicked(
            lambda x: self.print_manager.toggle_combo_state())
        self.split_but_ax.set_axis_on()
        self.split_but = Button(self.split_but_ax, 'Split Print')
        self.split_but.on_clicked(
            lambda x: self.print_manager.initiate_split_window())
        plt.draw()

    def clear_axes(self):
        self.title_axes.clear()
        self.title_axes.set_axis_off()
        self.title_axes.set_title('')
        self.lr_axis.clear()
        self.lr_axis.set_axis_off()
        self.fh_axis.clear()
        self.fh_axis.set_axis_off()
        self.del_but_ax.clear()
        self.del_but_ax.set_axis_off()
        self.merge_but_ax.clear()
        self.merge_but_ax.set_axis_off()
        self.split_but_ax.clear()
        self.split_but_ax.set_axis_off()
        self.lr_but = None
        self.fh_but = None
        plt.draw()

    def display_combo_text(self, print_numb):
        """Displays directions when combo state is active
        """
        self.clear_axes()
        props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)

        # place a text box in upper left in axes coords
        self.title_axes.text(0.05,
                             0.95,
                             "Left click on another print to \n" +
                             "combine with print " + str(print_numb) + "\n" +
                             "Or press c again to cancel",
                             transform=self.title_axes.transAxes,
                             fontsize=14,
                             verticalalignment='top',
                             bbox=props)

    def display_combo_text2(self, print_numb, print_numb2):
        """Displays directions when combo state is active
        """
        self.clear_axes()
        props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)

        # place a text box in upper left in axes coords
        self.title_axes.text(0.05,
                             0.95,
                             "To combine print " + str(print_numb) + "\n" +
                             "and print " + str(print_numb2) + "\n" +
                             "Press enter. \n Or press c again to cancel",
                             transform=self.title_axes.transAxes,
                             fontsize=14,
                             verticalalignment='top',
                             bbox=props)
Exemplo n.º 49
0
class FigureContainer():
    """instantiates figure and axes, creates all other objects. Holds the
    animation"""
    def __init__(self, file):
        #because I'm using keys that matplotlib also uses, remove some bindings
        plt.rcParams['keymap.fullscreen'] = '{'
        plt.rcParams['keymap.yscale'] = '}'
        self.fig = plt.figure(facecolor='w')
        self.fig.set_size_inches(16, 9)
        g = gspec.GridSpec(5,
                           2,
                           height_ratios=[2, 6, 4, 1, 6],
                           width_ratios=[10, 3])
        g.update(left=0.05,
                 right=0.95,
                 wspace=0.02,
                 hspace=.04,
                 bottom=.02,
                 top=.98)

        #add the axes in the subplot areas desired
        self.spatial_axis = self.fig.add_subplot(g[1, 0])
        self.vid_axis = self.fig.add_subplot(g[4, 0])
        self.temporal_axis = self.fig.add_subplot(g[2, 0])
        #self.select_axis = self.fig.add_subplot(g[:,1])
        self.sel_panel = SelectPanel(self.fig, g)
        #create an axes to hold space for the buttons
        #self.fig.add_subplot(g[0,0]).set_axis_off()
        g2 = gspec.GridSpecFromSubplotSpec(1,
                                           4,
                                           subplot_spec=g[0, 0],
                                           wspace=0.1,
                                           hspace=0.1)

        ax = self.fig.add_subplot(g2[0, 0])
        self.sav_but = Button(ax, 'Save Changes')
        ax = self.fig.add_subplot(g2[0, 2])
        self.pp_but = Button(ax, 'Pause Video')
        self.pp_but.on_clicked(self.toggle_play)
        #ax=self.fig.add_subplot(g2[0,3])
        #self.pick_file_but = Button(ax, 'Load File')
        #self.pick_file_but.on_clicked(self.load_new_file)

        self.is_playing = True
        #add a slider
        slid_ax = self.fig.add_subplot(g[3, 0])
        self.slide = Slider(slid_ax,
                            'Frame',
                            0,
                            100,
                            valinit=0,
                            valfmt='%0.0f')

        self.init_for_file(file)

        #and start the animation
        self.anim = animation.FuncAnimation(self.fig,
                                            self.update_func,
                                            fargs=(),
                                            interval=15,
                                            repeat=True)
        plt.show()

    def load_new_file(self, _):
        self.init_for_file(pick_file())

    def toggle_play(self, _):
        self.is_playing = not self.is_playing
        if self.is_playing:
            self.pp_but.label.set_text('Pause')  # works
        else:
            self.pp_but.label.set_text('Play')

    def update_func(self, j):
        """based on the value of the slider, update the video
        """
        if self.is_playing:
            #the min and max range don't seem to be working, so manually check
            i = int(self.slide.val) + 1
            if i < self.slide.valmin:
                i = self.slide.valmin
            if i > self.slide.valmax:
                i = self.slide.valmin
            self.print_manager.change_frame(self.prev_frame, i)
            #self.slide.set_val(i%len(self.left_panel.frames))
            self.slide.set_val(i)
            self.prev_frame = i
            return j

    def init_for_file(self, file):
        self.print_manager = PrintManager(self.temporal_axis,
                                          self.spatial_axis, self.sel_panel,
                                          self.vid_axis, self.slide, file)
        self.sel_panel.set_print_manager(self.print_manager)
        self.set_slider_range()
        self.prev_frame = self.slide.val
        #activate pick events
        self.fig.canvas.mpl_connect('pick_event', self.print_manager.on_pick)
        self.fig.canvas.mpl_connect('key_press_event',
                                    self.print_manager.on_key_press)
        #g2.update(left=0.05, right=0.95, wspace=0.02, hspace=.04,
        #         bottom = .2, top = .8)
        #ax=self.fig.add_subplot(g2[0,0])
        #Button(ax, 'Load File').on_clicked(
        #                            self.print_manager.initiate_split_window)

        self.sav_but.on_clicked(self.print_manager.save)

    def set_slider_range(self):
        """set the slider to range between combo_prints first frame and
        last frame"""
        self.slide.set_val(self.print_manager.combo_prints.first_frame.min())
        self.slide.valmin = self.print_manager.combo_prints.first_frame.min()
        self.slide.valmax = self.print_manager.combo_prints.last_frame.max()
        self.slide.ax.set_xlim(self.slide.valmin, self.slide.valmax)
Exemplo n.º 50
0
    def calibrate(self):

        plt.clf()
        self.img = cv2.cvtColor(self.img, cv2.COLOR_BGR2RGB)
        plt.imshow(self.img)

        self.anounce(
            'You will define a rectangle in the image \n by selecting its corners, click to begin'
        )
        plt.waitforbuttonpress()

        while True:
            pts = []
            while len(pts) < 3:
                self.anounce(
                    'Select 4 corners of the rectangle in the following order:\n top left, top right, bottom left, bottom right'
                )
                pts = np.asarray(plt.ginput(4, timeout=-1))
                if len(pts) < 4:
                    self.anounce('Too few points, starting over')

            self.anounce('Happy? Key click for yes, mouse click for no')

            fill_pts = np.copy(pts)
            fill_pts[[2, 3]] = fill_pts[[3, 2]]
            print(pts)
            print(fill_pts)
            ph = plt.fill(fill_pts[:, 0], fill_pts[:, 1], 'r', lw=2)

            if plt.waitforbuttonpress():
                break

            for p in ph:
                p.remove()

        pts = pts.tolist()
        for pt in pts:
            pt[0] = round(pt[0])
            pt[1] = round(pt[1])
        self.corners = pts

        def submitWidth(text):
            self.width = eval(text)

        def submitHeight(text):
            self.height = eval(text)

        def submit(event):
            print("Corners: {}".format(self.corners))
            print("Width is {}m".format(self.width))
            print("Height is {}m".format(self.height))
            print("Calibration is complete")
            plt.close('all')

        self.anounce(
            "Enter the width and height (in metres) in the fields below \n Width: top left corner to top right corner \n Height: top left corner to bottom left corner"
        )
        width_box = TextBox(plt.axes([0.2, 0.02, 0.2, 0.05]),
                            'Width:',
                            initial='')
        width_box.on_text_change(submitWidth)
        height_box = TextBox(plt.axes([0.6, 0.02, 0.2, 0.05]),
                             'Height:',
                             initial='')
        height_box.on_text_change(submitHeight)

        submit_button = Button(plt.axes([0.85, 0.02, 0.1, 0.05]), 'Submit')
        submit_button.on_clicked(submit)

        plt.show()
Exemplo n.º 51
0
class Chart(object):
	def __init__(self, plt):
		global current_temp
		global current_fan_speed

		self.plot = plt # create instance of plt
		self.fig = fig # create a figure (one figure per window)
		self.axes = axes # add a subplot to the figure. axes is of type Axes which contains most of the figure elements

		# working on the Axes object
		self.axes.set_title("GPU Fan Controller") # title for the chart
		self.axes.grid()

		# chart min/max display values
		self.x_min = -5
		self.x_max = 105
		self.y_min = 25
		self.y_max = 105
		self.axes.set_xlim(self.x_min, self.x_max)
		self.axes.set_ylim(self.y_min, self.y_max)

		# Save button
		saveFig = self.fig.add_axes([0.8, 0.015, 0.1, 0.04])
		self.saveFig = Button(saveFig, "Save")
		self.saveFig.on_clicked(self.saveToFile)

		# printAxes = self.fig.add_axes([0.2, 0.025, 0.1, 0.04])  #position rect [left, bottom, width, height] where all quantities are in fractions of figure width and height
		# self.printButton = Button(printAxes, "Print")
		# self.printButton.on_clicked(self.printData)

		# Reset button
		resetChart = self.fig.add_axes([0.125, 0.015, 0.1, 0.04])
		self.resetChart = Button(resetChart, "Reset")
		self.resetChart.on_clicked(self.resetData)

		# Apply button
		applyAxes = self.fig.add_axes([0.685, 0.015, 0.1, 0.04])
		self.applyAxes = Button(applyAxes, "Apply")
		self.applyAxes.on_clicked(self.applyData)

		#b=blue, o=circle, picker=max distance for considering point as clicked
		self.line, = axes.plot(x_values, y_values, linestyle='-', marker='o', color='b', picker=5) #tuple unpacking: this function returns a tuple, with the comma we take the first element

		self.dragHandler = DragHandler(self)
		self.dataController = DataController(x_values, y_values)

		#validate points from file!
		self.updatedCurve = nvfanspeed.updatedCurve
		self.nvidiaController = nvfanspeed.NvidiaFanController(x_values, y_values)
		self.nvidiaController.start()

		# signal traps
		signal.signal(signal.SIGINT, self.exit_signal_handler) #CTRL-C
		signal.signal(signal.SIGQUIT, self.exit_signal_handler) #CTRL-\
		signal.signal(signal.SIGHUP, self.exit_signal_handler) #terminal closed
		signal.signal(signal.SIGTERM, self.exit_signal_handler)

		# close app
		self.fig.canvas.mpl_connect("close_event", self.on_close)

	def on_close(self, event):
		self.nvidiaController.stop()

	def exit_signal_handler(self, signal, frame):
		self.close()

	def close(self):
		self.plot.close('all')
		self.nvidiaController.stop()

	def show(self):
		self.plot.show() #display ALL non closed figures
		#pyplot is stateful: usually self.plot.function() works on the current plot in the current figure

	# def printData(self, event):
	# 	xdata, ydata = self.dataController.getData()
	# 	print "---------------"
	# 	for index in range(0, len(xdata)):
	# 		print xdata[index], ydata[index]
	# 	print "---------------"

	def resetData(self, event):
		initChartValues() # reset to initial values
		xydata = [x_values, y_values]
		self.line.set_data(xydata) # update curve with values
		self.updateChart(x_values, y_values) # update chart to reflect values

	def updateChart(self, xdata, ydata):
		"""
		Due to how the NvidiaFanController run loop was structured to constantly update, there was an issue where updating the curve points could take anywhere from 3 to 10+ loop iterations
		By pausing the loop, updates to the curve points occur consistently between 1-3 loop iterations
		As a precaution, updating the chart with GPU temp/fan speed stats have also been paused, although may not be necessary.
		"""
		self.setUpdateStats(False) # temporarily stops live GPU updates
		self.updatedCurve(True) # pauses the nvfanspeed run loop
		self.nvidiaController.setCurve(xdata, ydata) # updates curve with new x and y data
		self.updatedCurve(False) # resumes nvfanspeed loop
		self.setUpdateStats(True) # enables live GPU updates

	def setUpdateStats(self, bool):
		global update_stats
		update_stats = bool

	def applyData(self, event):
		xdata = self.line.get_xdata() # grabs current curve y data
		ydata = self.line.get_ydata() # grabs current curve y data
		is_valid_curve = self.dataController.setData(xdata, ydata) # checks if curve is exponentially growing (returns bool)

		if is_valid_curve:
			self.updateChart(xdata, ydata) # updates nvfanspeed.NvidiaFanController() with new curve data
			displayDialogBox('Successfully applied the current curve to the fan settings!')
		else:
			xdata, ydata = self.dataController.getData() # gets previous data
			xydata = [xdata, ydata] 
			self.line.set_data(xydata) # resets line to previous curve

	def saveToFile(self, event):
		config = []
		xdata, ydata = self.dataController.getData() # get current curve points

		for index in range(0, len(xdata)):
			res = [xdata[index], ydata[index]] # combine x and y data
			config.append(res) # append it to config

		savedConfig = np.array(config) # convert config to numpy array (req'd to convert base10 to int)
		np.savetxt("config.csv", savedConfig.astype(int) , delimiter=",", fmt='%i') # saves array[temp, fspd] to config.csv
		displayDialogBox('Successfully saved the current curve configuration!')
Exemplo n.º 52
0
    global_path = os.getcwd()
    out_name = global_path + '/../../data/ParteII/sujetos'

    path = out_name + '/' + meta_sub

    n_time = time.asctime(time.localtime(time.time()))

    _today = str(datetime.date.today())
    today = _today.replace('-', '')
    _time = n_time.split()
    save_time = today + '_' + _time[3].replace(':', '')[:-2]

    try:
        os.mkdir(path)
    except OSError:
        print("Creation of the directory %s failed" % path)
    else:
        print("Successfully created the directory %s " % path)

    np.savetxt(path + '/' + meta_sub + '_' + save_time + '.csv',
               np.c_[res_values, elapsed_time],
               delimiter=';',
               fmt='%s',
               header="Resultado VAS")
    plt.close()


sVAS.on_changed(update)
reset_button.on_clicked(reset)
save_button.on_clicked(save)
Exemplo n.º 53
0
DAx = plt.axes([0.25, 0.20, 0.65, 0.03])
DSlider = Slider(DAx, 'Days to transition (E->A orA->M) (1/Gamma) (1/Gamma)', 1, 15, valinit = 10, valstep = 1, color = sliderColor)

deltaAx = plt.axes([0.25, 0.05, 0.65, 0.03])
deltaSlider = Slider(deltaAx, 'Days of incubation (delta)', 1, 15, valinit = 3, valstep = 1, color = sliderColor)

def reset(event):
	'''Reset all of the sliders'''
	betaSlider.reset()
	DSlider.reset()
	deltaSlider.reset()
	muSlider.reset()

resetAx = fig.add_axes([0.45, 0.025, 0.1, 0.04])
resetButton = Button(resetAx, 'Reset', color = 'gray')
resetButton.on_clicked(reset)

def model(event):
	'''Update the parameters and plots'''
	beta1 = betaSlider.val
	gamma1 = gamma2 = eta = 1/DSlider.val
	delta = deltaSlider.val
	mu = muSlider.val

	#Differentiate the equations again
	sol = generateData(time, initVec, N, beta1, beta2, tLock, gamma1, gamma2, eta, mu, delta, alpha, rho)
	S, E, A, M, R, D = sol

	#Change the y-data on each of the plots
	Splt.set_ydata(S)
	Eplt.set_ydata(E)
Exemplo n.º 54
0
    def __init__(self, images, shape):
        fig = plt.figure(figsize=(10, 6))

        # subplot positions
        h_nav = [Size.Fixed(0.5), Size.Fixed(2.5)]
        v_nav = [Size.Fixed(0.5), Size.Scaled(1.0), Size.Fixed(0.5)]
        h_im = [Size.Fixed(0.5), Size.Scaled(1.0), Size.Fixed(0.5)]
        v_im = [Size.Fixed(0.5), Size.Scaled(1.0), Size.Fixed(0.5)]
        nav = Divider(fig, (0.0, 0.0, 0.2, 1.), h_nav, v_nav, aspect=False)
        image = Divider(fig, (0.2, 0.0, 0.8, 1.), h_im, v_im, aspect=True)
        image.set_anchor('C')

        # Toolbar menu box
        ax1 = LocatableAxes(fig, nav.get_position())
        ax1.set_axes_locator(nav.new_locator(nx=1, ny=1))
        ax1.get_xaxis().set_visible(False)
        ax1.get_yaxis().set_visible(False)
        fig.add_axes(ax1, label='toolbar')

        ax1.text(0.05, 0.45, "Filter", weight='heavy',
                 transform=ax1.transAxes)

        # Image space
        ax2 = LocatableAxes(fig, image.get_position())
        ax2.set_axes_locator(image.new_locator(nx=1, ny=1))
        fig.add_axes(ax2, label='image_space')

        self.callback = ImageIndex(images, shape, fig)

        # Navigation
        ## Go to
        ax_text_index = plt.axes([0.59, 0.05, 0.1, 0.075])
        ip = InsetPosition(ax1, [0.2, 0.84, 0.3, 0.05])
        ax_text_index.set_axes_locator(ip)
        entry_index = TextBox(ax_text_index, 'Go to', initial="0")
        entry_index.on_submit(self.callback.submit_index)
        ## Previous
        ax_prev = plt.axes([0.7, 0.05, 0.075, 0.075])
        ip = InsetPosition(ax1, [0.55, 0.84, 0.15, 0.05])
        ax_prev.set_axes_locator(ip)
        bprev = Button(ax_prev, '<<')
        bprev.on_clicked(self.callback.prev)
        ## Next
        ax_next = plt.axes([0.81, 0.05, 0.075, 0.075])
        ip = InsetPosition(ax1, [0.75, 0.84, 0.15, 0.05])
        ax_next.set_axes_locator(ip)
        bnext = Button(ax_next, '>>')
        bnext.on_clicked(self.callback.next)

        # Bounding Boxes
        ax_chec = plt.axes([0.1, 0.05, 0.35, 0.075])
        ip = InsetPosition(ax1, [0.05, 0.5, 0.9, 0.3])
        ax_chec.set_axes_locator(ip)
        ax_chec.text(0.05, 0.85, "Bounding Boxes", transform=ax_chec.transAxes)
        check = CheckButtons(ax_chec,
                             ('characters', 'lines'),
                             (False, False))
        check.on_clicked(self.callback.update_bboxes)

        # Filtering
        ## Image
        ax_text_image = plt.axes([0.1, 0.1, 0.1, 0.075])
        ip = InsetPosition(ax1, [0.26, 0.38, 0.64, 0.05])
        ax_text_image.set_axes_locator(ip)
        entry_image = TextBox(ax_text_image, 'images',
                              initial="image_id,image_id")
        entry_image.on_submit(self.callback.submit_images)
        ## Characters
        ax_text_char = plt.axes([0.1, 0.2, 0.1, 0.075])
        ip = InsetPosition(ax1, [0.21, 0.3, 0.69, 0.05])
        ax_text_char.set_axes_locator(ip)
        entry_char = TextBox(ax_text_char, 'chars',
                             initial="U+3055,U+3056")
        entry_char.on_submit(self.callback.submit_chars)
        ## Reset
        ax_reset = plt.axes([0., 0., 1., 1.])
        ip = InsetPosition(ax1, [0.05, 0.2, 0.2, 0.05])
        ax_reset.set_axes_locator(ip)
        breset = Button(ax_reset, 'Reset')
        breset.on_clicked(self.callback.reset)

        plt.show()
Exemplo n.º 55
0
class DiagramInfo:
    '''Manages the plot that displays diagram info.'''
    precision = 2

    def __init__(self, ax, on_auto_clicked):
        self.ax = ax
        self.on_auto_clicked_callback = on_auto_clicked

        kwargs = {
            'horizontalalignment': 'center',
            'verticalalignment': 'center',
            'transform': self.ax.transAxes
        }

        self.A_text = self.ax.text(.05, .5, "A =", fontsize=25, **kwargs)
        self.matrix_text = self.ax.text(.7,
                                        .5,
                                        "(No Matrix)",
                                        fontsize=25,
                                        **kwargs)
        self.trace_text = self.ax.text(.5,
                                       .15,
                                       "(No Data)",
                                       fontsize=14,
                                       **kwargs)
        self.det_text = self.ax.text(.5,
                                     .05,
                                     "(No Data)",
                                     fontsize=14,
                                     **kwargs)

        # AUTO Button setup
        warnings.filterwarnings(
            "ignore",
            message=
            "This figure includes Axes that are not compatible with tight_layout, so results might be incorrect."
        )

        button_axes = plt.axes([0, 0, 1, 1])
        ip = InsetPosition(self.ax, [0.2, 0.88, 0.6, 0.1])
        button_axes.set_axes_locator(ip)
        self.auto_button = Button(button_axes,
                                  'RUN AUTO ELLIPSE',
                                  color='gray')
        self.auto_button.on_clicked(lambda event: self.on_auto_clicked(event))

        # Don't draw the axes
        self.ax.axis('off')

    def update(self, trace, det, A):
        A_ = np.around(A, self.precision)
        txt = "{}  {} \n{}  {} ".format(A_[0, 0], A_[0, 1], A_[1, 0], A_[1, 1])
        #A_txt=r"$ \begin{matrix} a & b \\ d & e \end{matrix} $"
        self.matrix_text.set_text(txt)

        txt = r"$\tau = {0:.2f}$".format(trace)
        self.trace_text.set_text(txt)

        txt = r"$\Delta = {0:.2f}$".format(det)
        self.det_text.set_text(txt)

    def on_auto_clicked(self, event):
        self.on_auto_clicked_callback()
Exemplo n.º 56
0
 def draw(self):
     while True:
         try:
             _ = self.xMl
             break
         except:
             time.sleep(5)
     self.fig = plt.figure()
     self.ax = self.fig.add_subplot(1, 1, 1)
     plt.subplots_adjust(bottom=0.25)
     axnext = plt.axes([0.6, 0.05, 0.1, 0.075])
     bnext = Button(axnext, 'Refresh')
     bnext.on_clicked(self.refresh_func)
     while True:
         if self.refresh:
             self.ax.lines = list()
             self.ax.texts = list()
             self.ax.plot(self.xM, self.yM, color="black", linewidth=1)
             for n, xpos, ypos, value in zip(self.Nl, self.xMl, self.yMl,
                                             self.slope_list):
                 self.ax.text(xpos - 1,
                              ypos + 0.0005,
                              str(abs(value)),
                              fontsize=6,
                              color="gray",
                              fontweight="bold")
             for x_slice, y_slice, x_point, y_point, sig_type in self.signal_list:
                 self.ax.plot(x_slice,
                              y_slice,
                              color="steelblue",
                              linewidth=1)
                 self.ax.text(x_point,
                              self.y_min - 0.002,
                              sig_type,
                              fontsize=5,
                              color="steelblue",
                              fontweight="bold")
             for xpos, ypos, close_type, x, start_price in self.close_list:
                 self.ax.plot([
                     xpos,
                 ], [
                     ypos,
                 ], "*k", markersize=5)
                 if ypos != start_price:
                     if close_type == "long":
                         color = "red" if ypos > start_price else "green"
                         y_2_points = [start_price, ypos]
                     else:
                         color = "red" if ypos < start_price else "green"
                         y_2_points = [start_price, 2 * start_price - ypos]
                     self.ax.plot([x, x + 0.001],
                                  y_2_points,
                                  color=color,
                                  linewidth=2)
             if self.long_trigger_price is not None:
                 self.ax.plot(self.xM, [
                     self.long_trigger_price,
                 ] * len(self.xM),
                              "--r",
                              linewidth=0.5)
             if self.short_trigger_price is not None:
                 self.ax.plot(self.xM, [
                     self.short_trigger_price,
                 ] * len(self.xM),
                              "--g",
                              linewidth=0.5)
             self.ax.set_title(str(round(self.pnl, 3)))
             plt.pause(30)
         else:
             plt.pause(120)
Exemplo n.º 57
0
class IncrInsert_2d:
    def __init__(self, fn, initial_points, n_steps=1):
        self.plot3d = None
        self.title = None
        self.n_steps = n_steps
        self.N = 2
        self.initial_points = initial_points
        self.fn = fn
        self.triang = _delaunay2.DelaunayInterp2(fn)
        # insert the initial points
        for x in initial_points:
            f_val = fn(x)
            self.triang.insert(x, f_val)
        print("inserted %d initial points" % len(initial_points))

        self.init_draw()

    def init_draw(self):
        self.fig = plt.figure()
        self.ax = Axes3D(self.fig)
        self.update_plot()

        self.axbutton = plt.axes([0.81, 0.05, 0.1, 0.075])
        self.button = Button(self.axbutton, 'Insert')
        self.button.on_clicked(self.on_insert_click)
        plt.draw()

    def update_plot(self):
        t0 = time.time()
        if (self.plot3d != None):
            for item in self.plot3d:
                [x.remove() for x in item]
            self.plot3d = None
        [item.remove() for item in self.ax.collections]
        del self.ax.collections[:]

        t1 = time.time()
        (all_segments, min_coords,
         max_coords) = self.triang.get_line_segments()
        t2 = time.time()
        self.plot3d = []

        for segment in all_segments:
            (p0, p1, is_concave) = segment
            color = ('b' if (is_concave) else 'r')
            (xpair, ypair, zpair) = zip(p0, p1)
            self.plot3d.append(self.ax.plot3D(xpair, ypair, zpair,
                                              color=color))
        t3 = time.time()
        error_queue = self.triang.get_error_queue()
        if (len(error_queue) > 0):
            (err, f_val, x) = error_queue[0]
            self.next_point = self.ax.scatter([x[0]], [x[1]], [f_val],
                                              color='r')

        self.ax.set_xlim(min_coords[0], max_coords[0])
        self.ax.set_ylim(min_coords[1], max_coords[1])
        self.ax.set_zlim(min_coords[2], max_coords[2])

    def on_insert_click(self, event):
        t1 = time.time()
        for i in range(self.n_steps):
            self.triang.insert_largest_error_point()
        t2 = time.time()
        #print("time of insertion: %f, %d points, avg %f" % (t2-t1, self.n_steps, (t2-t1)/self.n_steps))

        self.update_plot()
        plt.draw()
Exemplo n.º 58
0
class RotatableAxes:
    def __init__(self, fig: mpl.figure.Figure, axes: mpl.axes.Axes,
                 rect_angle: list, rect_reset: list):
        self.fig = fig
        # Suppose that there exists an image in the axes
        self.axes = axes
        self.renderer = self.axes.figure.canvas.get_renderer()
        self.axes_img_instance = self.axes.get_images()[0]
        self.original_axes_img = self.axes_img_instance.make_image(
            self.renderer, unsampled=True)[0]

        self.axes_for_angle_slider = self.fig.add_axes(rect_angle)
        self.axes_for_reset_button = self.fig.add_axes(rect_reset)
        self.angle_slider = Slider(self.axes_for_angle_slider,
                                   'Angle(Degree)',
                                   0.0,
                                   359.0,
                                   valinit=0.0,
                                   valstep=0.1)
        self.angle_slider.on_changed(self.update_img)
        self.reset_button = Button(self.axes_for_reset_button, 'Reset')
        self.reset_button.on_clicked(self.reset)

    def connect(self) -> None:
        # connect to all the events we need
        self.fig.canvas.mpl_connect('button_press_event', self.onclick)

    def disconnect(self) -> None:
        # disconnect all the stored connection ids
        self.fig.canvas.mpl_disconnect(self.onclick)

    def update_la_img(self):
        self.axes_img_instance = self.axes.get_images()[0]
        self.original_axes_img = self.axes_img_instance.make_image(
            self.renderer, unsampled=True)[0]
        self.angle_slider.reset()

    def onclick(self, event: mpl.backend_bases.Event) -> None:
        if self.axes == event.inaxes:
            cur_img = self.axes_img_instance.make_image(self.renderer,
                                                        unsampled=True)[0]
            if event.button == mpl.backend_bases.MouseButton.LEFT and event.inaxes is not None:
                rotated_image = ndimage.rotate(cur_img, 90.0, reshape=False)
                self.axes_img_instance.set_data(rotated_image)
            elif event.button == mpl.backend_bases.MouseButton.RIGHT and event.inaxes is not None:
                flipped_img = cur_img[:, ::-1]
                self.axes_img_instance.set_data(flipped_img)
            self.axes.figure.canvas.draw()
            self.axes.figure.canvas.flush_events()

    def update_img(self, new_angle: float) -> None:
        axes_images_list = self.axes.get_images()
        rotated_img = ndimage.rotate(self.original_axes_img,
                                     new_angle,
                                     reshape=False)
        axes_images_list[0].set_data(rotated_img)
        self.axes.figure.canvas.update()
        self.axes.figure.canvas.flush_events()

    def reset(self, event: mpl.backend_bases.Event):
        self.angle_slider.reset()
Exemplo n.º 59
0
        movie_cbar = movie_fig.colorbar(movie_plot)
        movie_cbar.ax.set_ylabel(r'log $\Sigma$  [ g/cm$^2$ ]')
        movie_cbar.set_ticks(cbar_ticks)
        plt.grid(b=True)
        img_name = 'movie_plot_%05i%s' % (i, img_format)
        plt.savefig(dir_name + '/' + img_name)
        print 'Saving image: ' + dir_name + '/' + img_name
        plt.close(movie_fig)
    # Create movie
    movie_name = 'movie.mp4'
    dummy_name = movie_name
    dummy_i = 0
    while os.path.isfile(dummy_name):
        dummy_i += 1
        dummy_name = movie_name.replace('.', '_%03i.' % dummy_i)
    movie_name = dummy_name
    subprocess.call([
        'ffmpeg', '-start_number',
        repr(i_start), '-i',
        dir_name + os.sep + 'movie_plot_%05d' + img_format, '-c:v', 'libx264',
        '-crf', '0', '-pix_fmt', 'yuv420p', movie_name
    ])
    print 'Saving movie ' + movie_name
    # Delete folder
    shutil.rmtree(dir_name)


slider_time.on_changed(update)  # This is executed when changing the slider
button_movie.on_clicked(
    create_movie)  # This is done by click on the movie button
Exemplo n.º 60
0
    def __init__(self):

        # Ask the user for data file, image, train..
        self.args = parseArgs()

        (self.numRows, self.numCols) = (32, 128)

        # Set X and Y ticks to match data size
        (xStart, xStop, xStep) = (16, 128, 16)
        (yStart, yStop, yStep) = (8, 32, 8)
        (self.xlist, self.ylist) = ([], [])
        # Generate list of xticks to label the x axis
        for i in range(xStart, xStop, xStep):
            self.xlist.append(i)

        # Generate yticks for the y-axis
        for i in range(yStart, yStop, yStep):
            self.ylist.append(i)

        (imgOffset, timeStamp, run_number, trainNumber, image_number,
         imageData) = self.obtainImageWithInfo()

        # Create the figure and title
        self.fig = plt.figure(1)
        self.ax = self.fig.add_subplot(111)
        self.mainTitle = plt.title("")

        # Previous, next buttons inspired by example: matplotlib.org/1.3.1/examples/widgets/buttons.html

        # Previous, Next ASIC module buttons..
        decModule = plt.axes([0.85, 0.115, 0.07, 0.045])
        incModule = plt.axes([0.92, 0.115, 0.07,
                              0.045])  #  [left, bottom, width, height]
        incrementModule = Button(incModule, '+M')
        incrementModule.on_clicked(self.nextModule)
        decrementModule = Button(decModule, '-M')
        decrementModule.on_clicked(self.prevModule)

        # Previous, Next image buttons..
        decImage = plt.axes([0.85, 0.06, 0.07, 0.045])
        incImage = plt.axes([0.92, 0.06, 0.07,
                             0.045])  #  [left, bottom, width, height]
        incrementImg = Button(incImage, '+I')
        incrementImg.on_clicked(self.nextImage)
        decrementImg = Button(decImage, '-I')
        decrementImg.on_clicked(self.prevImage)

        # Previous, Next train buttons..
        decTrain = plt.axes([0.85, 0.005, 0.07, 0.045])
        incTrain = plt.axes([0.92, 0.005, 0.07,
                             0.045])  #  [left, bottom, width, height]
        incrementTrain = Button(incTrain, '+T')
        incrementTrain.on_clicked(self.nextTrain)
        decrementTrain = Button(decTrain, '-T')
        decrementTrain.on_clicked(self.prevTrain)

        # Determine row/col coordinates according to selected ASIC module
        (rowStart, colStart) = self.asicStartingRowColumn(self.args.module)
        self.img = self.ax.imshow(imageData[rowStart:rowStart + self.numRows,
                                            colStart:colStart + self.numCols],
                                  interpolation='nearest',
                                  vmin='0',
                                  vmax='4095')
        self.ax.set_xticks(self.xlist)
        self.ax.set_yticks(self.ylist)

        dateStr = time.strftime('%d/%m/%y %H:%M:%S', time.localtime(timeStamp))
        titleText = 'Run %d Train %d Image %d Module %d : %s' % (
            run_number, trainNumber, image_number, self.args.module, dateStr)
        self.mainTitle.set_text(titleText)

        # Add a colour bar
        axc, kw = matplotlib.colorbar.make_axes(self.ax)
        cb = matplotlib.colorbar.Colorbar(axc, self.img)
        self.img.colorbar = cb

        self.artist = self.fig.get_children()

        DataCursor(
            self.artist[1], imageData[rowStart:rowStart + self.numRows,
                                      colStart:colStart + self.numCols])

        plt.show()