def display(input, agc=1):
	
	def update(val):
		vmax = smax.val
		vmin = smin.val
		im.set_clim(vmax=vmax, vmin=vmin)
		fig.canvas.draw_idle()
	
	fig = pylab.figure()
	'''displays a gather using imshow'''
	dataset = toolbox.read(input)
	vmax = np.amax(dataset['trace'])
	vmin = np.amin(dataset['trace'])
	if agc:
		dataset = toolbox.agc(dataset)
	im = pylab.imshow(dataset['trace'].T, aspect='auto', cmap='spectral', vmax =vmax, vmin=vmin)
	pylab.colorbar()
	axcolor = 'lightgoldenrodyellow'
	axmax = pylab.axes([0.08, 0.06, 0.65, 0.01], axisbg=axcolor) #rect = [left, bottom, width, height] in normalized (0, 1) units
	smax = Slider(axmax, 'vmax', vmin, vmax, valinit=vmax)
	smax.on_changed(update)
	axmin = pylab.axes([0.08, 0.03, 0.65, 0.01], axisbg=axcolor) #rect = [left, bottom, width, height] in normalized (0, 1) units
	smin = Slider(axmin, 'vmin', vmin, vmax, valinit=vmin)
	smin.on_changed(update)	
	smin.on_changed(update)
	
	pylab.show()
def display(workspace, **params):
        
        def update(val):
                vmax = smax.val
                vmin = smin.val
                im.set_clim(vmax=vmax, vmin=vmin)
                fig.canvas.draw_idle()
        
        fig = pylab.figure()
        '''displays a gather using imshow'''

        vmax = np.amax(workspace)
        vmin = np.amin(workspace)

        im = pylab.imshow(workspace.T, aspect='auto', cmap='Greys', vmax =vmax, vmin=vmin)
        pylab.colorbar()
        axcolor = 'lightgoldenrodyellow'
        axmax = pylab.axes([0.08, 0.06, 0.65, 0.01], axisbg=axcolor) #rect = [left, bottom, width, height] in normalized (0, 1) units
        smax = Slider(axmax, 'vmax', vmin, vmax, valinit=vmax)
        smax.on_changed(update)
        axmin = pylab.axes([0.08, 0.03, 0.65, 0.01], axisbg=axcolor) #rect = [left, bottom, width, height] in normalized (0, 1) units
        smin = Slider(axmin, 'vmin', vmin, vmax, valinit=vmin)
        smin.on_changed(update)	
        smin.on_changed(update)
        
        pylab.show()
Esempio n. 3
0
def wave_recon_plot2():
    '''
        Plots the Fourier reconstruction of the wavefront as a function of time.  
    '''

    # create the figure
    fig = plt.figure()
    ax = fig.add_subplot(111)
    data = recon(0) #initial data 
    im = ax.imshow(data, interpolation='none')
    plt.colorbar(im, ax=ax, orientation='vertical')
    plt.show(block=False)

    # Add axes for time slider
    axes = fig.add_axes([0.25, 0.02, 0.5, 0.02])
    max_time = len(slope_x.data) - 1 # the maximum index that exists for the time 
    timeslider = Slider(axes, 'Time', 0, max_time, valinit=0, valfmt='%i')
    
    def update(val):
        # Update the data
        time_index = int(val)
        data = recon(time_index)
        # Set the image array to this
        im.set_array(data)
        # Redraw the plot
        fig.canvas.draw()
    # Whe the slider is slid, update the plot
    timeslider.on_changed(update)
    
    plt.show()
Esempio n. 4
0
    def sliders(limits, ax, cb, valinits=None):
        if valinits is None or not all([lim and len(lim) == 2
                                        for lim in valinits]):
            valinits = limits
        axcolor = "lightgoldenrodyellow"
        bottom = 0.1
        sliders = []
        plt.subplots_adjust(left=0.25, bottom=bottom*2+0.05*len(limits)*2)
        for i in range(len(limits)):
            axstime = plt.axes([0.25, bottom, 0.65, 0.03], axisbg=axcolor)
            bottom += 0.05
            axetime = plt.axes([0.25, bottom, 0.65, 0.03], axisbg=axcolor)
            bottom += 0.05

            stime = Slider(
                axstime,
                "Start {}".format(
                    i+1),
                limits[i][0],
                limits[i][1],
                valinit=valinits[i][0],
                valfmt="%.2f")
            etime = Slider(
                axetime,
                "End {}".format(
                    i+1),
                limits[i][0],
                limits[i][1],
                valinit=valinits[i][1],
                valfmt="%.2f")
            stime.on_changed(cb)
            etime.on_changed(cb)
            sliders.append([stime, etime])
        return sliders
Esempio n. 5
0
def plot_spin_lattice(spin_array, observables):
    """
    Shows the spin_array for all temperature values.
    """
    T_range = observables.T_range

    fig = plt.figure(figsize=(4.5, 5))
    ax = fig.add_subplot(111)
    plt.subplots_adjust(bottom=0.12, top=1)
    ax.set_title('$\\rm{\\bf Spin\,Lattice:}\;T= %.3f\,\\rm [K]$' % (T_range[-1]),
            fontsize=14, loc=('center'))
    im = ax.imshow(spin_array[:,:,-1], origin='lower', interpolation='none')
    slider_ax = plt.axes([0.2, 0.06, 0.6, 0.03], axisbg='#7F0000')
    spin_slider = Slider(slider_ax, '', 0, len(T_range)-1, len(T_range)-1, 
                            valfmt ='%u', facecolor='#00007F')

    def update(val):
        i = int(val)
        ax.set_title('$\\rm{\\bf Spin\,Lattice:}\;T= %.3f\,\\rm [K]$'
            % (T_range[i]), fontsize=14, loc=('center'))
        im.set_array(spin_array[:,:,i])

    spin_slider.on_changed(update)
    plt.annotate('Temperature Slider', xy=(0.32,0.025), xycoords='figure fraction', fontsize=12)
    plt.show()
Esempio n. 6
0
def plotter():
    '''
    This process is supposed to handle the graphs.
    Not pretty at the moment... but then matplotlib never is.
    '''
    signal.signal(signal.SIGINT, signal.SIG_IGN) # Ignore keyboard interrupt signal, parent process will handle.
    waterfall_size = 150 # This makes it about 75 seconds in theory. Drawing the graph sometimes takes a bit longer.
    fig = plt.figure(figsize=(20,15))
    plt.subplots_adjust(left = 0.1, bottom = 0.25)
    ax = plt.subplot(1, 1, 1)
    line_lcp, = ax.plot([], [], 'bo', lw=1)
    line_rcp, = ax.plot([], [], 'ro', lw=1)
    ax.set_xlim(0,400)

    vav_data_lcp = collections.deque(maxlen = waterfall_size)
    vav_data_rcp = collections.deque(maxlen = waterfall_size)

    slider_ax = plt.axes([0.25, 0.1, 0.65, 0.03])

    video_average_length_slider = Slider(slider_ax, 'VAv', 1, waterfall_size, valinit=video_average_length.value)
    def update(val):
        video_average_length.value = int(video_average_length_slider.val)
        fig.canvas.draw_idle()
    video_average_length_slider.on_changed(update)

    def init():
        x = np.zeros(data_width)
        y = np.zeros(data_width)
        line_lcp.set_data(x,y)
        line_rcp.set_data(x,y)
        return line,

    def animate(*args):
        if script_run.value != 1:
            sys.exit()
        x = np.arange(0, 400, 400.0 / 1024.0)
        vav_data_lcp.appendleft(data_stream_1[:])
        vav_data_rcp.appendleft(data_stream_2[:])
        lcp = np.zeros(data_width)
        rcp = np.zeros(data_width)
        for i in range(video_average_length.value):
            if i < len(vav_data):
                lcp += np.array(vav_data_lcp[i])
                rcp += np.array(vav_data_rcp[i])
        lcp /= video_average_length.value
        rcp /= video_average_length.value
        graph_max = 0
        if lcp.max() > rcp.max():
            graph_max = lcp.max()
        else:
            graph_max = rcp.max()
        ax.set_ylim(0,graph_max + 1)
        line_lcp.set_data(x,lcp)
        line_rcp.set_data(x.rcp)
        return line,

    # Set the animation off to a start...
    anim = animation.FuncAnimation(fig, animate, init_func=init, blit=True, interval=500)
    plt.show()
    print 'plotter process finished.'
Esempio n. 7
0
def plot_correlation_loglog(observables):
    """
    Currently only the Worm algorithm measures correlation data.
    """
    fig = plt.figure(figsize=(6,5))
    ax = fig.add_subplot(111)
    # make room for slider
    plt.subplots_adjust(bottom=0.22, top=0.9, right=0.95, left=0.15)
    ax.set_xlabel('$\log\,r_{ij}$', fontsize=14)
    ax.set_ylabel('$\\rm \log\,g\\left(r_{ij}\\right)$', fontsize=14)
    digits = int(np.log10(observables.Z[-1]))
    ax.set_title(r'$\rm{\bf Ising\,2D:}\,%s^2 Grid,\,%.1f\!\times 10^{%u}MCSteps$'
        % (observables.L, observables.Z[-1]/(10**digits), digits),
        fontsize=14, loc=('center'))
    r_range = np.linspace(1, observables.L+1, observables.L)
    correlation = observables.correlation
    #correlation = np.cumsum(correlation[::-1], axis=0)[::-1]
    # initialize correlation function plot.
    correlation_plot = ax.plot([], [], 'o', markersize=6, color='b')[0]
    # initialize least squares fit plot.
    least_squares_fit = ax.plot([], [], '-r', label='y=mx+b')[0]
    rcParams['legend.frameon'] = 'False'
    # create position index slider
    r_max = len(np.log(correlation[correlation[:, -1]>0, -1]))
    slider_axes = plt.axes([0.2, 0.03, 0.7, 0.03], axisbg='lightgoldenrodyellow')
    r_slider = Slider(slider_axes, '$r_{max}$', 3, r_max, valinit=r_max, 
        facecolor='b', valfmt ='%u')
    # create temperature index slider
    T_range = observables.T_range
    slider_axes = plt.axes([0.2, 0.07, 0.7, 0.03], axisbg='lightgoldenrodyellow')
    T_slider = Slider(slider_axes, '$T$', 1, len(T_range), valinit=len(T_range), 
        facecolor='b', valfmt ='%u')
    
    def slider_update(value):
        r_idx, T_idx = int(r_slider.val), int(T_slider.val)-1
        correlation_function = correlation[1:,T_idx]/correlation[0,T_idx]
        # use only nonzero correlation values for fitting
        r = np.log(r_range[correlation_function>0])
        y = np.log(correlation_function[correlation_function>0])
        correlation_plot.set_xdata(r[0:r_idx])
        correlation_plot.set_ydata(y[0:r_idx])
        # least squares fit using scipy package.
        fit_data = stats.linregress(correlation_plot.get_xdata(), correlation_plot.get_ydata())
        slope, intercept, r_value = fit_data[0], fit_data[1], fit_data[2]
        least_squares_fit.set_label(r'${\rmFit:}\; m = %.3f,\;r^2 = %.3f,\;T=%.3f$'
            % (slope, r_value**2, T_range[T_idx]))
        # plot least squares fit.
        least_squares_fit.set_ydata((slope*correlation_plot.get_xdata()+intercept))
        least_squares_fit.set_xdata(correlation_plot.get_xdata())
        # set new axes bounds.
        ax.set_xlim(min(correlation_plot.get_xdata()), max(correlation_plot.get_xdata()))
        ax.set_ylim(min(correlation_plot.get_ydata()), max(correlation_plot.get_ydata()))
        # refresh figure.
        ax.legend(loc='lower left')
        fig.canvas.draw_idle()
    
    r_slider.on_changed(slider_update) # set slider callback function.
    T_slider.on_changed(slider_update) # set slider callback function.
    slider_update(True) # initialize plot
    plt.show()
Esempio n. 8
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()
Esempio n. 9
0
def from_partial(plot_func,**kwargs):
    num_params = len(kwargs)

    fig = plt.figure()
    main_ax = fig.add_subplot(111)
    fig.subplots_adjust(bottom=bottom_pad + (num_params+1)*per_slider)

    param_vals = dict((param_name,(lo+hi)/2) for param_name, (lo,hi) in kwargs.items())
    plot_func = partial(plot_func,main_ax)
    plot_func(param_vals)

    def update(*args):
        for param_name, slider in zip(param_vals,sliders):
            param_vals[param_name] = slider.val
        main_ax.cla()
        plot_func(param_vals)

        # using autoscale_view makes the axes shrink *and* grow
        main_ax.relim()
        main_ax.autoscale_view()

        fig.canvas.draw()

    sliders = []
    for idx, (param_name, (lo,hi)) in enumerate(kwargs.items()):
        ax = fig.add_axes([0.25,bottom_pad+per_slider*idx,0.65,3/5*per_slider],axisbg=bgcolor)
        slider = Slider(ax, param_name, lo, hi, valinit=param_vals[param_name])
        slider.on_changed(update)
        sliders.append(slider)

    plt.axes(main_ax)
Esempio n. 10
0
class SinSlider():
	pi = 3.14159

	def __init__(self, num):
		self.init_plot(num)
		self.init_slider(num)

	def init_plot(self, num):
		pylab.subplot(111)
		pylab.subplots_adjust(bottom = 0.25)
		pylab.axis([0.0, 2 * self.pi, -1.0, 1.0])
		pylab.title("y = sin(num * x)")
		pylab.xlabel("x")
		pylab.ylabel("y")
		x, y = self.calc_xy(num)
		self.plot, = pylab.plot(x, y) # comma after 'self.plot'

	def init_slider(self, num):
		slider_axes = pylab.axes([0.1, 0.1, 0.8, 0.05]) # left, bottom, width, height
		self.slider = Slider(slider_axes, 'num', 0.0, 4.0, valinit = num)
		self.slider.on_changed(self.update)

	def update(self, num):
		_, new_y = self.calc_xy(num)
		self.plot.set_ydata(new_y)
		pylab.draw()

	def calc_xy(self, num):
		start = 0.0
		stop = 2 * self.pi
		step = 0.01
		x = pylab.arange(start, stop, step)
		y = pylab.sin(num * x)
		return x, y
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
Esempio n. 12
0
def mplot(func,x,**kwargs):
    num_params = len(kwargs)

    fig = plt.figure()
    main_ax = fig.add_subplot(111)
    fig.subplots_adjust(bottom=bottom_pad + (num_params+1)*per_slider)

    param_vals = dict((param_name,(lo+hi)/2) for param_name, (lo,hi) in kwargs.items())
    y = func(x,**param_vals)
    l, = main_ax.plot(x,y)

    def update(*args):
        for param_name, slider in zip(param_vals,sliders):
            param_vals[param_name] = slider.val
        vals = func(x,**param_vals)
        l.set_ydata(vals)

        # using autoscale_view makes the axes shrink *and* grow
        #main_ax.relim()
        #main_ax.autoscale_view()
        # setting ylim this way only lets the axes grow
        ymin, ymax = main_ax.get_ylim()
        main_ax.set_ylim(min(vals.min(),ymin),max(ymax,vals.max()))

        fig.canvas.draw()

    sliders = []
    for idx, (param_name, (lo,hi)) in enumerate(kwargs.items()):
        ax = fig.add_axes([0.25,bottom_pad+per_slider*idx,0.65,3/5*per_slider],axisbg=bgcolor)
        slider = Slider(ax, param_name, lo, hi, valinit=param_vals[param_name])
        slider.on_changed(update)
        sliders.append(slider)

    plt.axes(main_ax)
Esempio n. 13
0
def iplot_spectrum_ds(ds, init = True,
                      sigmarng = [0.05, 1.5], taurng = [0,4], **kwargs):
    """
    Plots spectrum from TlacDatSet interactively using matplotlib.
    NOT FINISHED >> see tlac_web instead
    
    Keyword Arguments:
    ds         -- TlacDatSet instance to plot
    init       --- If true (default) plot will be initialized first
    sigmarng   -- Range for intrinsic spectrum width. Measured in
                  units of the actual sigma_i (default [0,1.5])
    taurng     -- Range for dust optical depth tau_d (default [0, 4])
    **kwargs   -- Will be passes to `tlac_analysis.plot_spectrum`
    """
    if(not isinstance(ds, TlacDatSet)):
        raise ValueError("ds has to be a TlacDatSet instance")

    dat = ds['Lya','x']
    sigmar = ds.header['emission', 'frequency_param' ]

    if(init):
        plot_init()
        plt.gcf().subplots_adjust(top = 0.95, bottom = 0.05)
    
    plot_spectrum(dat, np.ones(len(dat)), **kwargs)

    fig   = plt.gcf()
    ax    = fig.axes[0]
    line  = ax.lines[-1]
    nbins = len(line.get_xdata())

    bm = fig.subplotpars.bottom
    fig.subplots_adjust(bottom = bm + 0.04)
    
    axsigma = plt.axes([0.2, bm - 0.03, 0.65, 0.03])
    ssigma  = Slider(axsigma, r"$\sigma_i$", sigmarng[0] * sigmar,
                     sigmarng[1] * sigmar, valinit=sigmar)
    
    def update(val):
        sigma = ssigma.val
        w = tlac_weights(ds, sigma, 0)
        x,y = plot_spectrum(dat, w, plot = False, **kwargs)
        line.set_xdata(x)
        line.set_ydata(y)
        ymax = ax.get_ylim()[1]
        if(np.max(y) > 1.1 * ymax):
            ax.set_ylim(ymax = 1.5 * ymax)
        elif(np.max(y) < 0.5 * ymax):
            ax.set_ylim(ymax = 0.5 * ymax)
        fig.canvas.draw_idle()
        

    ssigma.on_changed(update)

    # change current axis back
    plt.sca(ax)
    plt.show()
    
    # have to return ref to slider. otherwise unresponsive!
    return fig, ax, ssigma
Esempio n. 14
0
class ChangingPlot(object):
    """
    Gives a pyplot object with a slider that shows the complex roots of
    the truncated power series for the number of terms on the slider.
    """
    def __init__(self,poly,NUMTERMS):
        self.sols,self.NUMTERMS = solLists(poly,NUMTERMS)
        self.windowBounds = minmax(self.sols)
        self.inc = 1.0

        self.fig, self.ax = plt.subplots()
        self.sliderax = self.fig.add_axes([0.2, 0.02, 0.6, 0.03],
                                          axisbg='yellow')

        self.slider = Slider(self.sliderax, 'Value', 0, self.NUMTERMS-3, valinit=self.inc)
        self.slider.on_changed(self.update)
        self.slider.drawon = False

        self.dot, = self.ax.plot(self.sols[0][0],self.sols[0][1], 'bo')
        self.ax.axis(self.windowBounds)

    def update(self, value):
        value = int(value)
        self.dot.set_data(self.sols[value][0],self.sols[value][1])
        self.slider.valtext.set_text('{}'.format(value))
        self.fig.canvas.draw()

    def show(self):
        plt.show()
Esempio n. 15
0
def plotInteractive( data ):
    ax = plt.subplot(111)
    plt.subplots_adjust(bottom=0.25)
    t = sorted(data.keys())
    
    pl = plt.scatter([0],[0],s=10,linewidths=(0,0,0))
    plt.axis([0, 2, 0, 2])        
    
    axTime = plt.axes([0.25, 0.1, 0.65, 0.03]) 
    sTime = Slider(axTime, 'Time', min(t), max(t), valinit=min(t))
    
    def updateTime(val):
        t0 = sTime.val
        dt = abs(np.array(t)-t0)
        t_in = t[dt.argmin()]
        px = getpx(data,t_in)
        pv = getpv(data,t_in)
        pl.set_offsets(px)  
        pl.set_array(pv)
        plt.draw()
        
    updateTime(min(t))
    sTime.on_changed(updateTime)
        
    plt.show(block=False)
Esempio n. 16
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))
Esempio n. 17
0
def slider_plot(sizes, xs, ys, dfc=91.0 / 48, tau=0.33):
    fig = pl.figure()
    pl.subplots_adjust(left=0.25, bottom=0.25)
    pl.clf()

    lines = []
    ox, oy = rescale(sizes, xs, ys, dfc, tau)
    for x, y, c in zip(ox.T, oy.T, colors):
        lines.append(pl.loglog(x, y, "o-", c=c)[0])

    axcolor = "white"
    axalpha = pl.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
    axtau = pl.axes([0.25, 0.20, 0.65, 0.03], axisbg=axcolor)

    print dfc, tau
    salpha = Slider(axalpha, r"$d_f$", 1.5, 2.0, valinit=dfc)
    stau = Slider(axtau, r"$\tau$", -1.0, 2.0, valinit=tau)

    def update(val):
        dfc = salpha.val
        tau = stau.val
        print "dfc =", dfc, "tau = ", tau

        ox, oy = rescale(sizes, xs, ys, dfc, tau)
        for line, x, y in zip(lines, ox.T, oy.T):
            line.set_xdata(x)
            line.set_ydata(y)

            fig.canvas.draw_idle()

    salpha.on_changed(update)
    stau.on_changed(update)
Esempio n. 18
0
def main():
  points = GeneratePoints(1000, 4.0)
  theta = np.pi / 4.0
  aspect = 0.5
  params = {"theta": theta,
            "aspect": aspect,
            "original_points": points,
            "points": points}

  TransformPoints(params)
  X0, Y0, Y = LinearRegressionOn2DPoints(params["points"])

  points_plot, = plt.plot(X0, Y0, 'o')
  line_plot, = plt.plot(X0, Y, 'r')
  plt.axis('equal')

  # Add UI Text and Sliders
  text = plt.text(-4.5, 3.5, "Corr(x,y) %f" % Correlation2DPoints(params["points"]), fontsize=15)
  ax_aspect = plt.axes([0.25, 0.1, 0.65, 0.03])
  ax_theta = plt.axes([0.25, 0.15, 0.65, 0.03])
  aspect_slider = Slider(ax_aspect, 'Aspect', 0.0, 1.0, valinit=aspect)
  theta_slider = Slider(ax_theta, 'Theta', -0.5 * np.pi, 0.5 * np.pi, valinit=theta)
  aspect_slider.on_changed(updateHandler("aspect", text, points_plot, line_plot, params))
  theta_slider.on_changed(updateHandler("theta", text, points_plot, line_plot, params))

  plt.show()
def getBubbleChart(d):
	def generateX():
		return np.repeat(np.arange(len(d.index.values)),len(d.index.values))

	def generateY():
		return np.tile(np.arange(len(d.index.values)),len(d.index.values))

	fig, ax = plt.subplots()
	plt.subplots_adjust(left=0.25, bottom=0.25)
	l = plt.scatter(generateX(),generateY(),s=d*50)
	basic_sizes = l._sizes
	plt.xticks(np.arange(0, len(d), 1.0),d.index.values,ha='right', rotation=45)
	plt.yticks(np.arange(0, len(d), 1.0),d.index.values)
	
	plt.grid()

	axcolor = 'lightgoldenrodyellow'
	axsize = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
	ssize = Slider(axsize, 'Size', 1, 20, valinit=50)

	def update(val):
	    new_coef = ssize.val/50
	    new_sizes = [x * new_coef for x in basic_sizes]
	    l._sizes = new_sizes
	    fig.canvas.draw_idle()
	ssize.on_changed(update)
	
	plt.show()
Esempio n. 20
0
def vis(gt,f,est=False,title=False):
    import matplotlib.pyplot as plt
    from matplotlib.widgets import Slider #, Button, RadioButtons
    from matplotlib.patches import Ellipse

    fig = plt.figure()
    if title :
        fig.suptitle(title, fontsize=14, fontweight='bold')

    ax = plt.subplot(111, aspect='equal')
    fig.subplots_adjust(left=0.25, bottom=0.25)
    ax.clear()

    axcolor = 'lightgoldenrodyellow'
    ax2 = fig.add_axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
    
   
    def update(val):  
        val=int(val)
        ax.clear()
        loc=find_locs(f[val])
        if est is not False:
            p=np.random.permutation(est[val].max()+1)
            p2=np.random.permutation(gt[val].max()+1)
            calc_distance_vis(loc,f[val],p[est[val]],3500,ax)
        ax.scatter(f[val][:,1],f[val][:,2], c=p2[gt[val]],vmin=0, vmax=gt[val].max(),s=100)
    update(0)
    slider = Slider(ax2, 'Frame', 0, gt.shape[0] - 1,
                    valinit=0, valfmt='%i')

    slider.on_changed(update)

    plt.show()
Esempio n. 21
0
class ChangingPlot(object):
    def __init__(self):

	data = np.genfromtxt('AR.csv', dtype=None, delimiter=',', skip_header=1) 
	[aa,bb]=data.shape
	self.bb=int(bb)
	self.freq=data[:,0]
	self.AR_sim=data[:,1]

        # change this for the stepsize
        self.inc = 1.0 

        self.fig, self.ax = plt.subplots()
        self.sliderax = self.fig.add_axes([0.2, 0.02, 0.6, 0.03], axisbg='yellow')

        self.slider = Slider(self.sliderax, 'Value', 0, self.bb, valinit=self.inc)
	
        self.slider.on_changed(self.update)
        self.slider.drawon = False
	
    	self.dot, = self.ax.plot(self.freq, self.AR_sim)
	self.ax.axhline(y=3,linestyle='-.',color='b',linewidth=0.5)
    def update(self, value):
        value = int(value / self.inc) * self.inc
	data = np.genfromtxt('AR.csv', dtype=None, delimiter=',', skip_header=1) 
	[aa,bb]=data.shape
	self.freq=data[:,0]
	self.AR_sim=data[:,[value]]
	self.dot.set_data([self.freq,self.AR_sim])
        self.slider.valtext.set_text('{}'.format(value))
        self.fig.canvas.draw()

    def show(self):
        plt.show()
Esempio n. 22
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
Esempio n. 23
0
    def run(self):
        for varname,range in self.ranges.iteritems():
            if range is None:
                raise ValueError("no range specified for slider %s." % varname)

        def update(val):
            d = dict([(k, self.sliders[k].val) for k in self.sliders.keys()])
            # pull members into current scope -> no self. in cutstring
            vars = self.vars
            weights = self.weights
            basemask = self.basemask

            # evaluate cutstring and combine with basemask
            mask = basemask & eval(self.cutstring % d)
            self.updatefunc(self, vars, weights, mask)

        self.sliderfig = p.figure(figsize=(3,len(self.ranges)*.4))
        self.sliders = dict()
        space = .05
        height = (1. - (len(self.ranges)+2)*space) / float(len(self.ranges))
        
        for i,(varname,range) in enumerate(self.ranges.iteritems()):
            ax = p.axes([0.25, 1-float(i+1)*(space+height), 0.5, height])
            slider = Slider(ax, varname, range[0],range[1], valinit=(range[1]-range[0])/2.)
            slider.on_changed(update)
            self.sliders[varname] = slider
        
        self.initfunc(self,self.vars,self.weights,self.basemask)
Esempio n. 24
0
def init():
    """ Set up the initial conditions """
    # Sets up initial dimensions
    M.figure(figsize=(8,8))
    
    density=N.loadtxt(os.path.join(sys.path[0], './densmesh.txt'))
    # Real Fourier transform of "density" 
    density_k = N.fft.rfftn(density*1e3) # 1e3 to enhance contrast

    global psi
    psi = zeldovich(density_k)
    # Zel'dovich displacement field

    global scale
    global slider_scale
    
    scale = 1.0
    slider_scale = 50.0

    axcolor = 'lightgoldenrodyellow'
    axScale = plt.axes([0.15, 0.1, 0.7, 0.03], axisbg=axcolor)
    slider_scale = Slider(axScale, 'Scale', 0.0, 50.0, 1.0)
    slider_scale.on_changed(update)    

    # Attempting to removed axes from the graph
    plt.axes([0.15, 0.15, 0.7, 0.7])
    plt.xticks([])
    plt.yticks([])        

    return density_k, psi    
Esempio n. 25
0
	def create_sliders(self):
		for i, name in enumerate(self.names):
			dim = self.def_dim + i * self.del_dim
			axes = self.f.add_axes(dim, axisbg = self.axcolor)
			slider = Slider(axes, name, 0, 10, valinit=1)
			slider.on_changed(self.update)
			self.cont_of_slid[name] = (axes, slider)
def interpolation(threshold, X_Smooth1, Smooth_Y_Coordinates):        
    Smooth_X_npy = np.asarray(X_Coordinates)
    Smooth_Y_npy = np.asarray(Smooth_Y_Coordinates)
    f = interp1d(Smooth_X_npy, Smooth_Y_npy, kind = "cubic" )
    temp = f(X_Coordinates)
    plt.close('all')
    fig, ax = plt.subplots(5)
    fig.suptitle("Neutron Imaging Curve Smoothing", fontsize="x-large")

    ax[0] = plt.subplot2grid((6,7), (0,0), rowspan=2, colspan=3)
    ax[0].plot(X_Coordinates, Y_Coordinates)
    ax[0].set_title('Original Plot')
    
    ax[1] = plt.subplot2grid((6,7), (3,0), rowspan=2, colspan=3)
    ax[1].plot(X_Coordinates, beta_list, 'r.-')
    ax[1].axhline(y=threshold, linewidth=1, color='k')
    ax[1].set_title('Peak Plot', )
    
    ax[2] = plt.subplot2grid((6,7), (0,4), rowspan=2, colspan=3)
    ax[2].plot(X_Coordinates, Smooth_Y_Coordinates)
    ax[2].set_title('Smoothed graph')

    ax[3] = plt.subplot2grid((6,7), (3,4), rowspan=2, colspan=3)
    ax[3].plot(X_Coordinates, f(X_Coordinates))
    ax[3].set_title('Interpolated')
    
    ax[4] = plt.subplot2grid((6,7), (5,0), colspan=7)
    ax[4].set_position([0.25, 0.1, 0.65, 0.03])    
    thres = Slider(ax[4], 'Threshold', 0.000, 0.005, valinit = threshold, valfmt='%1.5f')        
  
    workbook = xlwt.Workbook(encoding='ascii') 
    sheet = workbook.add_sheet("Sheet") 
    sheet.write(0, 0, "(Raw-OB)/OB")    
    sheet.write(0, 1, "wavelength (angs)")
    for i in range(len(X_Coordinates)):
        sheet.write(i+1, 0, X_Coordinates[i])        
        sheet.write(i+1, 1, temp[i])    
    workbook.save(outputfile)
    
    def update(val):
        threshold = thres.val
        print ("Threshold value: "), threshold
        smoothing_Plot(total_Span, threshold)
        fig.canvas.draw_idle()
    thres.on_changed(update)

    plt.show()

    fig2, ax2 = plt.subplots(2)
    ax2[0] = plt.subplot2grid((7,2), (0,0), rowspan=3, colspan=2)
    ax2[0].plot(X_Coordinates, Y_Coordinates)
    ax2[0].set_title('Original Plot')
    for i in X_Smooth1:
        plt.axvline(x = i, linewidth=1, color='k')    
    ax2[1] = plt.subplot2grid((7,2), (4,0), rowspan=3, colspan=2)
    ax2[1].plot(X_Coordinates, f(X_Coordinates))
    ax2[1].set_title('Interpolated')
    for i in X_Smooth1:
        plt.axvline(x = i, linewidth=1, color='k')
    plt.show()
Esempio n. 27
0
class Explorer(object):
    """A simple interactive slicer that "pans" a series of 2D slices along a 
    given axis of a 3D volume. Additional kwargs are passed to "imshow"."""
    def __init__(self, data, axis=2, **kwargs):
        self.data = data
        self.axis = axis
        self.start, self.stop = 0, data.shape[self.axis] - 1

        kwargs['cmap'] = kwargs.get('cmap', 'gray_r')
        
        self.fig, self.ax = plt.subplots()
        self.im = self.ax.imshow(self[self.start], **kwargs)
        self.ax.axis('off')

        self.sliderax = self.fig.add_axes([0.2, 0.02, 0.6, 0.03])
        self.slider = Slider(self.sliderax, 'Z-slice', self.start, self.stop,
                             valinit=self.start, valfmt='%i')
        self.slider.on_changed(self.update)

    def __getitem__(self, i):
        slices = self.data.ndim * [slice(None)]
        slices[self.axis] = i
        return self.data[slices].swapaxes(0, 1)

    def update(self, val):
        dat = self[int(val)]
        self.im.set(data=dat, clim=[dat.min(), dat.max()])
        self.fig.canvas.draw()

    def show(self):
        plt.show()
Esempio n. 28
0
def cal_threshold(image, tr):
    '''
    shows the before and after for thresholding, where the threshold can be set
    by a slider
    '''
    
    assert image.ndim ==2, 'This is not a single-channel image! Use single-channel images'
    im = image.astype('uint8')

    #create the axes for the slider
    axcolor = 'teal'
    ax1 = plt.axes([.15,.2,.65,.03],axisbg=axcolor)
    
    #create the slider
    s1 = Slider(ax1, 'Threshold', 0, 255, valinit=tr)

    #actual thresholding: compare each pixel in the image to the threshold
    trim = im > tr
    
    plt.subplot(221),plt.imshow(im),plt.title('Original')
    plt.subplot(222),plt.imshow(trim),plt.title('After thresholding')

    def update(val):
        vtr = s1.val
        trim = im > vtr 
        plt.subplot(222),plt.imshow(trim),plt.title('After thresholding')

    s1.on_changed(update)
    plt.show()
    #trim is a binary image - convert it to full colorscale by multiplying with
    #255
    return trim*255, s1.val
Esempio n. 29
0
def showimages(img1, img2, pathtosave):

    def press(event):
        sys.stdout.flush()
        if event.key == 'escape':
            sys.exit(0)
        elif event.key == ' ':
            plt.savefig(os.path.join(pathtosave, 'overlay.pdf'), bbox_inches='tight')
            print 'saved'

    fig, ax = plt.subplots()
    fig.canvas.mpl_connect('key_press_event', press)
    plt.subplots_adjust(0.15, 0.1, 0.9, 0.98)

    im = ax.imshow(img1)

    axcolor = 'lightgoldenrodyellow'
    BAR_HEIGHT = 0.03
    axalpha = plt.axes([0.2, 0.2 * BAR_HEIGHT, 0.7, BAR_HEIGHT], axisbg = axcolor)
    # axmax = plt.axes([0.2, BAR_HEIGHT + 0.4 * BAR_HEIGHT, 0.7, BAR_HEIGHT], axisbg = axcolor)
    salpha = Slider(axalpha, 'Alpha', 0.0, 1.0, valinit = 1.0)

    def update(event):
        curralpha = salpha.val
        ax.hold(False)
        ax.imshow(img1, alpha = curralpha)
        ax.hold(True)
        ax.imshow(img2, alpha = 1 - curralpha)
        plt.draw()
        return curralpha
    salpha.on_changed(update)

    plt.show()
Esempio n. 30
0
def cube_show_slider(cube, axis=2, **kwargs):
    import matplotlib.pyplot as plt
    from matplotlib.widgets import Slider, Button, RadioButtons
    # check dim
    if not cube.ndim == 3:
        raise ValueError("cube should be an ndarray with ndim == 3")
    # generate figure
    fig = plt.figure()
    ax = plt.subplot(111)
    fig.subplots_adjust(left=0.25, bottom=0.25)

    # select first image
    s = [slice(0, 1) if i == axis else slice(None) for i in xrange(3)]
    im = cube[s].squeeze()

    # display image
    l = ax.imshow(im, **kwargs)
    axcolor = 'lightgoldenrodyellow'
    ax = fig.add_axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
        
    slider = Slider(ax, 'Axis %i index' % axis, 0, cube.shape[axis] - 1,
                                        valinit=0, valfmt='%i')
            
    def update(val):
        ind = int(slider.val)
        s = [slice(ind, ind + 1) if i == axis else slice(None) for i in xrange(3)]
        im = cube[s].squeeze()
        l.set_data(im, **kwargs)
        fig.canvas.draw()
        
    slider.on_changed(update)
                                                                
    plt.show()
Esempio n. 31
0
def update_slider4(t):
    update(t=t)


t_val = [0.1]
x1_val = [0.1]
w_vector = [slider.val, slider2.val]


def update(w1=None, w2=None, x1=None, t=None):
    if x1 is not None: x1_val[0] = x1
    x_vector = [x, x1_val[0], 0 / 4, 0 / 3, 0, 0, 0 / 2, 0]
    if w1 is not None: w_vector[0] = w1
    if w2 is not None: w_vector[1] = w2
    if t is not None: t_val[0] = t
    y = P0_numpy(x_vector, w_vector, t_val[0])
    text.set_text(f'{round(max(y.real), 2)} \pm {round(np.std(y), 2)}')
    P0_plot.set_ydata(y)
    fig.canvas.draw_idle()


slider.on_changed(update_slider1)
slider2.on_changed(update_slider2)
slider3.on_changed(update_slider3)
slider4.on_changed(update_slider4)

update(slider.val, slider2.val)
plt.show()
input('')
Esempio n. 32
0
class TrackletVisualizer:
    def __init__(self, manager, videoname, trail_len=50):
        self.manager = manager
        self.cmap = plt.cm.get_cmap(manager.cfg["colormap"],
                                    len(set(manager.tracklet2id)))
        self.videoname = videoname
        self.video = VideoReader(videoname)
        self.nframes = len(self.video)
        # Take into consideration imprecise OpenCV estimation of total number of frames
        if abs(self.nframes - manager.nframes) >= 0.05 * manager.nframes:
            print(
                "Video duration and data length do not match. Continuing nonetheless..."
            )
        self.trail_len = trail_len
        self.help_text = ""
        self.draggable = False
        self._curr_frame = 0
        self.curr_frame = 0

        self.picked = []
        self.picked_pair = []
        self.cuts = []

        self.player = BackgroundPlayer(self)
        self.thread_player = Thread(target=self.player.run, daemon=True)
        self.thread_player.start()

        self.dps = []

    def _prepare_canvas(self, manager, fig):
        params = {
            "keymap.save": "s",
            "keymap.back": "left",
            "keymap.forward": "right",
            "keymap.yscale": "l",
        }
        for k, v in params.items():
            if v in plt.rcParams[k]:
                plt.rcParams[k].remove(v)

        self.dotsize = manager.cfg["dotsize"]
        self.alpha = manager.cfg["alphavalue"]

        if fig is None:
            self.fig = plt.figure(figsize=(13, 8))
        else:
            self.fig = fig
        gs = self.fig.add_gridspec(2, 2)
        self.ax1 = self.fig.add_subplot(gs[:, 0])
        self.ax2 = self.fig.add_subplot(gs[0, 1])
        self.ax3 = self.fig.add_subplot(gs[1, 1], sharex=self.ax2)
        plt.subplots_adjust(bottom=0.2)
        for ax in self.ax1, self.ax2, self.ax3:
            ax.axis("off")

        self.colors = self.cmap(manager.tracklet2id)
        self.colors[:, -1] = self.alpha

        img = self.video.read_frame()
        self.im = self.ax1.imshow(img)
        self.scat = self.ax1.scatter([], [], s=self.dotsize**2, picker=True)
        self.scat.set_offsets(manager.xy[:, 0])
        self.scat.set_color(self.colors)
        self.trails = sum(
            [self.ax1.plot([], [], "-", lw=2, c=c) for c in self.colors], [])
        self.lines_x = sum(
            [
                self.ax2.plot([], [], "-", lw=1, c=c, pickradius=5)
                for c in self.colors
            ],
            [],
        )
        self.lines_y = sum(
            [
                self.ax3.plot([], [], "-", lw=1, c=c, pickradius=5)
                for c in self.colors
            ],
            [],
        )
        self.vline_x = self.ax2.axvline(0, 0, 1, c="k", ls=":")
        self.vline_y = self.ax3.axvline(0, 0, 1, c="k", ls=":")
        custom_lines = [
            plt.Line2D([0], [0], color=self.cmap(i), lw=4)
            for i in range(len(manager.individuals))
        ]
        self.leg = self.fig.legend(
            custom_lines,
            manager.individuals,
            frameon=False,
            fancybox=None,
            ncol=len(manager.individuals),
            fontsize="small",
            bbox_to_anchor=(0, 0.9, 1, 0.1),
            loc="center",
        )
        for line in self.leg.get_lines():
            line.set_picker(5)

        self.ax_slider = self.fig.add_axes([0.1, 0.1, 0.5, 0.03],
                                           facecolor="lightgray")
        self.ax_slider2 = self.fig.add_axes([0.1, 0.05, 0.3, 0.03],
                                            facecolor="darkorange")
        self.slider = Slider(
            self.ax_slider,
            "# Frame",
            self.curr_frame,
            manager.nframes - 1,
            valinit=0,
            valstep=1,
            valfmt="%i",
        )
        self.slider.on_changed(self.on_change)
        self.slider2 = Slider(
            self.ax_slider2,
            "Marker size",
            1,
            30,
            valinit=self.dotsize,
            valstep=1,
            valfmt="%i",
        )
        self.slider2.on_changed(self.update_dotsize)
        self.ax_drag = self.fig.add_axes([0.65, 0.1, 0.05, 0.03])
        self.ax_lasso = self.fig.add_axes([0.7, 0.1, 0.05, 0.03])
        self.ax_flag = self.fig.add_axes([0.75, 0.1, 0.05, 0.03])
        self.ax_save = self.fig.add_axes([0.80, 0.1, 0.05, 0.03])
        self.ax_help = self.fig.add_axes([0.85, 0.1, 0.05, 0.03])
        self.save_button = Button(self.ax_save, "Save", color="darkorange")
        self.save_button.on_clicked(self.save)
        self.help_button = Button(self.ax_help, "Help")
        self.help_button.on_clicked(self.display_help)
        self.drag_toggle = CheckButtons(self.ax_drag, ["Drag"])
        self.drag_toggle.on_clicked(self.toggle_draggable_points)
        self.flag_button = Button(self.ax_flag, "Flag")
        self.flag_button.on_clicked(self.flag_frame)

        self.fig.canvas.mpl_connect("pick_event", self.on_pick)
        self.fig.canvas.mpl_connect("key_press_event", self.on_press)
        self.fig.canvas.mpl_connect("button_press_event", self.on_click)
        self.fig.canvas.mpl_connect("close_event", self.player.terminate)

        self.selector = PointSelector(self, self.ax1, self.scat, self.alpha)
        self.lasso_toggle = CheckButtons(self.ax_lasso, ["Lasso"])
        self.lasso_toggle.on_clicked(self.selector.toggle)
        self.display_traces(only_picked=False)
        self.ax1_background = self.fig.canvas.copy_from_bbox(self.ax1.bbox)
        plt.show()

    def show(self, fig=None):
        self._prepare_canvas(self.manager, fig)

    def fill_shaded_areas(self):
        self.clean_collections()
        if self.picked_pair:
            mask = self.manager.get_nonoverlapping_segments(*self.picked_pair)
            for ax in self.ax2, self.ax3:
                ax.fill_between(
                    self.manager.times,
                    *ax.dataLim.intervaly,
                    mask,
                    facecolor="darkgray",
                    alpha=0.2,
                )
            trans = mtransforms.blended_transform_factory(
                self.ax_slider.transData, self.ax_slider.transAxes)
            self.ax_slider.vlines(np.flatnonzero(mask),
                                  0,
                                  0.5,
                                  color="darkorange",
                                  transform=trans)

    def toggle_draggable_points(self, *args):
        self.draggable = not self.draggable
        if self.draggable:
            self._curr_frame = self.curr_frame
            self.scat.set_offsets(np.empty((0, 2)))
            self.add_draggable_points()
        else:
            self.save_coords()
            self.clean_points()
            self.display_points(self._curr_frame)
        self.fig.canvas.draw_idle()

    def add_point(self, center, animal, bodypart, **kwargs):
        circle = patches.Circle(center, **kwargs)
        self.ax1.add_patch(circle)
        dp = auxfun_drag.DraggablePoint(circle, bodypart, animal)
        dp.connect()
        self.dps.append(dp)

    def clean_points(self):
        for dp in self.dps:
            dp.annot.set_visible(False)
            dp.disconnect()
        self.dps = []
        for patch in self.ax1.patches[::-1]:
            patch.remove()

    def add_draggable_points(self):
        self.clean_points()
        xy, _, inds = self.manager.get_non_nan_elements(self.curr_frame)
        for i, (animal, bodypart) in enumerate(self.manager._label_pairs):
            if i in inds:
                coords = xy[inds == i].squeeze()
                self.add_point(
                    coords,
                    animal,
                    bodypart,
                    radius=self.dotsize,
                    fc=self.colors[i],
                    alpha=self.alpha,
                )

    def save_coords(self):
        coords, nonempty, inds = self.manager.get_non_nan_elements(
            self._curr_frame)
        prob = self.manager.prob[:, self._curr_frame]
        for dp in self.dps:
            label = dp.individual_names, dp.bodyParts
            ind = self.manager._label_pairs.index(label)
            nrow = np.flatnonzero(inds == ind)[0]
            if not np.array_equal(
                    coords[nrow],
                    dp.point.center):  # Keypoint has been displaced
                coords[nrow] = dp.point.center
                prob[ind] = 1
        self.manager.xy[nonempty, self._curr_frame] = coords

    def flag_frame(self, *args):
        self.cuts.append(self.curr_frame)
        self.ax_slider.axvline(self.curr_frame, color="r")
        if len(self.cuts) == 2:
            self.cuts.sort()
            mask = np.zeros_like(self.manager.times, dtype=bool)
            mask[self.cuts[0]:self.cuts[1] + 1] = True
            for ax in self.ax2, self.ax3:
                ax.fill_between(
                    self.manager.times,
                    *ax.dataLim.intervaly,
                    mask,
                    facecolor="darkgray",
                    alpha=0.2,
                )
            trans = mtransforms.blended_transform_factory(
                self.ax_slider.transData, self.ax_slider.transAxes)
            self.ax_slider.vlines(np.flatnonzero(mask),
                                  0,
                                  0.5,
                                  color="darkorange",
                                  transform=trans)
        self.fig.canvas.draw_idle()

    def on_scroll(self, event):
        cur_xlim = self.ax1.get_xlim()
        cur_ylim = self.ax1.get_ylim()
        xdata = event.xdata
        ydata = event.ydata
        if event.button == "up":
            scale_factor = 0.5
        elif event.button == "down":
            scale_factor = 2
        else:  # This should never happen anyway
            scale_factor = 1

        self.ax1.set_xlim([
            xdata - (xdata - cur_xlim[0]) / scale_factor,
            xdata + (cur_xlim[1] - xdata) / scale_factor,
        ])
        self.ax1.set_ylim([
            ydata - (ydata - cur_ylim[0]) / scale_factor,
            ydata + (cur_ylim[1] - ydata) / scale_factor,
        ])
        self.fig.canvas.draw()

    def on_press(self, event):
        if event.key == "n" or event.key == "right":
            self.move_forward()
        elif event.key == "b" or event.key == "left":
            self.move_backward()
        elif event.key == "s":
            self.swap()
        elif event.key == "i":
            self.invert()
        elif event.key == "x":
            self.flag_frame()
            if len(self.cuts) > 1:
                self.cuts.sort()
                if self.picked_pair:
                    self.manager.tracklet_swaps[self.picked_pair][
                        self.cuts] = ~self.manager.tracklet_swaps[
                            self.picked_pair][self.cuts]
                    self.fill_shaded_areas()
                    self.cuts = []
                    self.ax_slider.lines.clear()
        elif event.key == "backspace":
            if not self.dps:  # Last flag deletion
                try:
                    self.cuts.pop()
                    self.ax_slider.lines.pop()
                    if not len(self.cuts) == 2:
                        self.clean_collections()
                except IndexError:
                    pass
            else:  # Smart point removal
                i = np.nanargmin([
                    self.calc_distance(*dp.point.center, event.xdata,
                                       event.ydata) for dp in self.dps
                ])
                closest_dp = self.dps[i]
                label = closest_dp.individual_names, closest_dp.bodyParts
                closest_dp.disconnect()
                closest_dp.point.remove()
                self.dps.remove(closest_dp)
                ind = self.manager._label_pairs.index(label)
                self.manager.xy[ind, self._curr_frame] = np.nan
                self.manager.prob[ind, self._curr_frame] = np.nan
            self.fig.canvas.draw_idle()
        elif event.key == "l":
            self.lasso_toggle.set_active(not self.lasso_toggle.get_active)
        elif event.key == "d":
            self.drag_toggle.set_active(not self.drag_toggle.get_active)
        elif event.key == "alt+right":
            self.player.forward()
        elif event.key == "alt+left":
            self.player.rewind()
        elif event.key == " " or event.key == "tab":
            self.player.toggle()

    def move_forward(self):
        if self.curr_frame < self.manager.nframes - 1:
            self.curr_frame += 1
            self.slider.set_val(self.curr_frame)

    def move_backward(self):
        if self.curr_frame > 0:
            self.curr_frame -= 1
            self.slider.set_val(self.curr_frame)

    def swap(self):
        if self.picked_pair:
            swap_inds = self.manager.get_swap_indices(*self.picked_pair)
            inds = np.insert(swap_inds, [0, len(swap_inds)],
                             [0, self.manager.nframes - 1])
            if len(inds):
                ind = np.argmax(inds > self.curr_frame)
                self.manager.swap_tracklets(
                    *self.picked_pair, range(inds[ind - 1], inds[ind] + 1))
                self.display_traces()
                self.slider.set_val(self.curr_frame)

    def invert(self):
        if not self.picked_pair and len(self.picked) == 2:
            self.picked_pair = self.picked
        if self.picked_pair:
            self.manager.swap_tracklets(*self.picked_pair, [self.curr_frame])
            self.display_traces()
            self.slider.set_val(self.curr_frame)

    def on_pick(self, event):
        artist = event.artist
        if artist.axes == self.ax1:
            self.picked = list(event.ind)
        elif artist.axes == self.ax2:
            if isinstance(artist, plt.Line2D):
                self.picked = [self.lines_x.index(artist)]
        elif artist.axes == self.ax3:
            if isinstance(artist, plt.Line2D):
                self.picked = [self.lines_y.index(artist)]
        else:  # Click on the legend lines
            if self.picked:
                num_individual = self.leg.get_lines().index(artist)
                nrow = self.manager.tracklet2id.index(num_individual)
                inds = [
                    nrow + self.manager.to_num_bodypart(pick)
                    for pick in self.picked
                ]
                xy = self.manager.xy[self.picked]
                p = self.manager.prob[self.picked]
                mask = np.zeros(xy.shape[1], dtype=bool)
                if len(self.cuts) > 1:
                    mask[self.cuts[-2]:self.cuts[-1] + 1] = True
                    self.cuts = []
                    self.ax_slider.lines.clear()
                    self.clean_collections()
                else:
                    return
                sl_inds = np.ix_(inds, mask)
                sl_picks = np.ix_(self.picked, mask)
                old_xy = self.manager.xy[sl_inds].copy()
                old_prob = self.manager.prob[sl_inds].copy()
                self.manager.xy[sl_inds] = xy[:, mask]
                self.manager.prob[sl_inds] = p[:, mask]
                self.manager.xy[sl_picks] = old_xy
                self.manager.prob[sl_picks] = old_prob
        self.picked_pair = []
        if len(self.picked) == 1:
            for pair in self.manager.swapping_pairs:
                if self.picked[0] in pair:
                    self.picked_pair = pair
                    break
        self.clean_collections()
        self.display_traces()
        if self.picked_pair:
            self.fill_shaded_areas()
        self.slider.set_val(self.curr_frame)

    def on_click(self, event):
        if (event.inaxes in (self.ax2, self.ax3) and event.button == 1
                and not any(
                    line.contains(event)[0]
                    for line in self.lines_x + self.lines_y)):
            x = max(0, min(event.xdata, self.manager.nframes - 1))
            self.update_vlines(x)
            self.slider.set_val(x)
        elif event.inaxes == self.ax1 and not self.scat.contains(event)[0]:
            self.display_traces(only_picked=False)
            self.clean_collections()

    def clean_collections(self):
        for coll in (self.ax2.collections + self.ax3.collections +
                     self.ax_slider.collections):
            coll.remove()

    def display_points(self, val):
        data = self.manager.xy[:, val]
        self.scat.set_offsets(data)

    def display_trails(self, val):
        sl = slice(val - self.trail_len // 2, val + self.trail_len // 2)
        for n, trail in enumerate(self.trails):
            if n in self.picked:
                xy = self.manager.xy[n, sl]
                trail.set_data(*xy.T)
            else:
                trail.set_data([], [])

    def display_traces(self, only_picked=True):
        if only_picked:
            inds = self.picked + list(self.picked_pair)
        else:
            inds = self.manager.swapping_bodyparts
        for n, (line_x, line_y) in enumerate(zip(self.lines_x, self.lines_y)):
            if n in inds:
                line_x.set_data(self.manager.times, self.manager.xy[n, :, 0])
                line_y.set_data(self.manager.times, self.manager.xy[n, :, 1])
            else:
                line_x.set_data([], [])
                line_y.set_data([], [])
        for ax in self.ax2, self.ax3:
            ax.relim()
            ax.autoscale_view()

    def display_help(self, event):
        if not self.help_text:
            self.help_text = """
            Key D: activate "drag" so you can adjust bodyparts in that particular frame
            Key I: invert the position of a pair of bodyparts
            Key L: toggle the lasso selector
            Key S: swap two tracklets
            Key X: cut swapping tracklets
            Left/Right arrow OR Key B/Key N: navigate through the video (back/next)
            Tab or SPACE: play/pause the video
            Alt+Right/Left: fast forward/rewind - toggles through 5 speed levels
            Backspace: deletes last flag (if set) or deletes point
            Key P: toggles on pan/zoom tool - left button and drag to pan, right button and drag to zoom
            """
            self.text = self.fig.text(
                0.5,
                0.5,
                self.help_text,
                horizontalalignment="center",
                verticalalignment="center",
                fontsize=12,
                color="red",
            )
        else:
            self.help_text = ""
            self.text.remove()

    def update_vlines(self, val):
        self.vline_x.set_xdata([val, val])
        self.vline_y.set_xdata([val, val])

    def on_change(self, val):
        self.curr_frame = int(val)
        self.video.set_to_frame(self.curr_frame)
        img = self.video.read_frame()
        if img is not None:
            # Automatically disable the draggable points
            if self.draggable:
                self.drag_toggle.set_active(False)

            self.im.set_array(img)
            self.display_points(self.curr_frame)
            self.display_trails(self.curr_frame)
            self.update_vlines(self.curr_frame)

    def update_dotsize(self, val):
        self.dotsize = val
        self.scat.set_sizes([self.dotsize**2])

    @staticmethod
    def calc_distance(x1, y1, x2, y2):
        return np.sqrt((x1 - x2)**2 + (y1 - y2)**2)

    def save(self, *args):
        self.save_coords()
        self.manager.save()

    def export_to_training_data(self, pcutoff=0.1):
        import os
        from skimage import io

        inds = self.manager.find_edited_frames()
        if not len(inds):
            print("No frames have been manually edited.")
            return

        # Save additional frames to the labeled-data directory
        strwidth = int(np.ceil(np.log10(self.nframes)))
        tmpfolder = os.path.join(self.manager.cfg["project_path"],
                                 "labeled-data", self.video.name)
        if os.path.isdir(tmpfolder):
            print(
                "Frames from video",
                self.video.name,
                " already extracted (more will be added)!",
            )
        else:
            attempttomakefolder(tmpfolder)
        index = []
        for ind in inds:
            imagename = os.path.join(tmpfolder,
                                     "img" + str(ind).zfill(strwidth) + ".png")
            index.append(os.path.join(*imagename.rsplit(os.path.sep, 3)[-3:]))
            if not os.path.isfile(imagename):
                self.video.set_to_frame(ind)
                frame = self.video.read_frame()
                if frame is None:
                    print("Frame could not be read. Skipping...")
                    continue
                frame = frame.astype(np.ubyte)
                if self.manager.cfg["cropping"]:
                    x1, x2, y1, y2 = [
                        int(self.manager.cfg[key])
                        for key in ("x1", "x2", "y1", "y2")
                    ]
                    frame = frame[y1:y2, x1:x2]
                io.imsave(imagename, frame)

        # Store the newly-refined data
        data = self.manager.format_data()
        df = data.iloc[inds]

        # Uncertain keypoints are ignored
        def filter_low_prob(cols, prob):
            mask = cols.iloc[:, 2] < prob
            cols.loc[mask] = np.nan
            return cols

        df = df.groupby(level="bodyparts", axis=1).apply(filter_low_prob,
                                                         prob=pcutoff)
        df.index = index
        machinefile = os.path.join(
            tmpfolder,
            "machinelabels-iter" + str(self.manager.cfg["iteration"]) + ".h5")
        if os.path.isfile(machinefile):
            df_old = pd.read_hdf(machinefile)
            df_joint = pd.concat([df_old, df])
            df_joint = df_joint[~df_joint.index.duplicated(keep="first")]
            df_joint.to_hdf(machinefile, key="df_with_missing", mode="w")
            df_joint.to_csv(os.path.join(tmpfolder, "machinelabels.csv"))
        else:
            df.to_hdf(machinefile, key="df_with_missing", mode="w")
            df.to_csv(os.path.join(tmpfolder, "machinelabels.csv"))

        # Merge with the already existing annotated data
        df.columns.set_levels([self.manager.cfg["scorer"]],
                              level="scorer",
                              inplace=True)
        df.drop("likelihood", level="coords", axis=1, inplace=True)
        output_path = os.path.join(
            tmpfolder, f'CollectedData_{self.manager.cfg["scorer"]}.h5')
        if os.path.isfile(output_path):
            print(
                "A training dataset file is already found for this video. The refined machine labels are merged to this data!"
            )
            df_orig = pd.read_hdf(output_path)
            df_joint = pd.concat([df, df_orig])
            # Now drop redundant ones keeping the first one [this will make sure that the refined machine file gets preference]
            df_joint = df_joint[~df_joint.index.duplicated(keep="first")]
            df_joint.sort_index(inplace=True)
            df_joint.to_hdf(output_path, key="df_with_missing", mode="w")
            df_joint.to_csv(output_path.replace("h5", "csv"))
        else:
            df.sort_index(inplace=True)
            df.to_hdf(output_path, key="df_with_missing", mode="w")
            df.to_csv(output_path.replace("h5", "csv"))
Esempio n. 33
0
    circ10.set_edgecolor((0, 0, 0, 0.8))
    circ11.set_edgecolor((0, 0, 0, 0.8))
    circ12.set_edgecolor((0, 0, 0, 0.8))
    circ13.set_edgecolor((0, 0, 0, 0.8))
    circ14.set_edgecolor((0, 0, 0, 0.8))
    circ15.set_edgecolor((0, 0, 0, 0.8))
    circ16.set_edgecolor((0, 0, 0, 0.8))
    circ17.set_edgecolor((0, 0, 0, 0.8))
    circ18.set_edgecolor((0, 0, 0, 0.8))
    circ19.set_edgecolor((0, 0, 0, 0.8))
    circ20.set_edgecolor((0, 0, 0, 0.8))

    fig.canvas.draw_idle()


scont.on_changed(update)
surb.on_changed(update)
sviento.on_changed(update)

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


def reset(event):
    scont.reset()
    surb.reset()
    sviento.reset()


button.on_clicked(reset)
Esempio n. 34
0
plt.legend()

if len(laser.x()[0]) > 0:
    plt.figure(5)
    plt.subplot(2, 1, 1)
    plt.title("Laser")
    plt.subplots_adjust(bottom=0.2, left=0.1)
    l1, = plt.plot(laser.x()[0][0], laser.y()[0][0], '.')
    plt.axis('equal')
    plt.grid()
    plt.subplot(2, 1, 2, projection='polar')
    plt.subplots_adjust(bottom=0.2, left=0.1)
    l2, = plt.plot(laser.angle()[0][0], laser.dist()[0][0], '.')
    axcolor = 'lightgoldenrodyellow'  # slider的颜色
    om1 = plt.axes([0.1, 0.08, 0.8, 0.02], facecolor=axcolor)  # 第一slider的位置
    som1 = Slider(om1,
                  r'Time',
                  0,
                  len(laser.ts()[0]) - 1,
                  valinit=0,
                  valfmt='%i')  #产生第二slider

    def update(val):
        s1 = int(som1.val)
        l1.set_xdata(laser.x()[0][s1])
        l1.set_ydata(laser.y()[0][s1])
        l2.set_xdata(laser.angle()[0][s1])
        l2.set_ydata(laser.dist()[0][s1])

    som1.on_changed(update)
plt.show()
Esempio n. 35
0
        # k1 = h * f(x0, y0)
        # k2 = h * f(x0 + h, y0 + k1)
        # y1 = y0 + (h/2) * (k1 + k2)
        #    = y0 + (h/2) * (f(x0, y0) + f(x0 + h, y0 + k1))
        #    = y0 + (h/2) * (2 * x0 + y0 + 2 * (x0 + h) + y0 + h * (2 * x0 + y0))
        y = y + (h / 2) * (2 * x + y + 2 * (x + h) + y + h * (2 * x + y))
        ndsolve = np.append(ndsolve, y)
    ndsolve = np.delete(ndsolve, -1)
    interval = np.arange(lower, upper, h)
    return interval, ndsolve


interval0, ndsolve0 = RKM_2(h0, y0, lower0, upper0)
l, = plt.plot(interval0, ndsolve0, 'rx')
plt.plot(np.arange(0, 1, 0.001), analytic(np.arange(0, 1, 0.001)), '--')

axcolor = 'lightgoldenrodyellow'
axh = plt.axes([0.25, 0.1, 0.5, 0.1], facecolor=axcolor)
sh = Slider(axh, 'h', 0.001, 1., valinit=0.2)


def update(val):
    h0 = sh.val
    interval0, ndsolve0 = RKM_2(h0, y0, lower0, upper0)
    l.set_data(interval0, ndsolve0)
    fig.canvas.draw_idle()


sh.on_changed(update)
plt.show()
Esempio n. 36
0
                                  "Left temp", -2, 2)
right_t_slider = make_temp_sliders(-1, plt.axes([0.05, 0.6, 0.15, 0.03]),
                                   "Right temp", -2, 2)

radio.on_clicked(radio_on_click)
plt.subplots_adjust(left=0.3)


def change_r(val):
    global r
    r = val


def change_s(val):
    global s
    s = val


axs = plt.axes([0.05, 0.4, 0.15, 0.03])
axr = plt.axes([0.05, 0.3, 0.15, 0.03])

r_slide = Slider(axs, 'R', 0, 2)
s_slide = Slider(axr, 'S', 0, 2)

r_slide.on_changed(change_r)
s_slide.on_changed(change_s)

radio.on_clicked(radio_on_click)
plt.subplots_adjust(left=0.3)
plt.show()
	r_o.set_text(r'$R_O$={:.2f}'.format(a/b))

	fig.canvas.draw_idle()

def updateMaxTime(newVal):
	global susceptible, infected, recovered

	newData = genData(a, b, int(newVal.item()))

	del ax.lines[:3]

	susceptible, = ax.plot(newData[0], newData[1], label='Susceptible', color='b')
	infected, = ax.plot(newData[0], newData[2], label='Infected', color='r')
	recovered, = ax.plot(newData[0], newData[3], label='Recovered/Removed', color='g')

transmissionSlider.on_changed(updateTransmission)
recoverySlider.on_changed(updateRecovery)
timeSlider.on_changed(updateMaxTime)

resetAxes = plt.axes([0.8, 0.025, 0.1, 0.05])
resetButton = Button(resetAxes, 'Reset', color='white')

r_o = plt.text(0.1, 1.5, r'$R_O$={:.2f}'.format(a/b), fontsize=12)

def reset(event):
    transmissionSlider.reset()
    recoverySlider.reset()
    timeSlider.reset()

resetButton.on_clicked(reset)
sn2 = Slider(axn2, 'n2', 1, 10, valinit=2, valstep=0.01)


def update(val):
    global Mat1, Mat2
    n1 = sn1.val
    n2 = sn2.val
    Mat1 = MaterialTable.fromValue(n1)
    Mat2 = MaterialTable.fromValue(n2)
    i = 1
    while True:
        stack, d = getThicknesses(0.633, i)
        RT = TransferMatrix(stack, d).solveTransmission(0.633, 0, True)
        Rprime = RT[0] / (RT[0] + RT[1])
        if Rprime > 0.9999:
            print(Rprime, 'at', i)
            break
        if i > 100:
            break
        i += 1
    transmissions = TransferMatrix(stack, d).solveTransmission(wl, 0, True)
    reflectance = transmissions[:, 0] / (transmissions[:, 0] +
                                         transmissions[:, 1])
    l.set_ydata(reflectance)


sn1.on_changed(update)
sn2.on_changed(update)

plt.show()
Esempio n. 39
0
axcolor = 'lightgoldenrodyellow'
axfreq = axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
axamp = axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor)

sfreq = Slider(axfreq, 'Freq', 0.1, 30.0, valinit=f0)
samp = Slider(axamp, 'Amp', 0.1, 10.0, valinit=a0)


def update(val):
    amp = samp.val
    freq = sfreq.val
    l.set_ydata(amp * sin(2 * pi * freq * t))
    draw()


sfreq.on_changed(update)
samp.on_changed(update)

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


def reset(event):
    sfreq.reset()
    samp.reset()


button.on_clicked(reset)

rax = axes([0.025, 0.5, 0.15, 0.15], axisbg=axcolor)
radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0)
Esempio n. 40
0
class PVSlicer(object):
    def __init__(self, filename, backend="Qt4Agg", clim=None):

        self.filename = filename

        try:
            from spectral_cube import SpectralCube
            cube = SpectralCube.read(filename, format='fits')
            self.array = cube._data
        except:
            warnings.warn(
                "spectral_cube package is not available - using astropy.io.fits directly"
            )
            from astropy.io import fits
            self.array = fits.getdata(filename)
            if self.array.ndim != 3:
                raise ValueError(
                    "dataset does not have 3 dimensions (install the spectral_cube package to avoid this error)"
                )

        self.backend = backend

        import matplotlib as mpl
        mpl.use(self.backend)
        import matplotlib.pyplot as plt

        self.fig = plt.figure(figsize=(14, 8))

        self.ax1 = self.fig.add_axes([0.1, 0.1, 0.4, 0.7])

        if clim is None:
            warnings.warn(
                "clim not defined and will be determined from the data")
            # To work with large arrays, sub-sample the data
            n1 = self.array.shape[0] / 10
            n2 = self.array.shape[1] / 10
            n3 = self.array.shape[2] / 10
            sub_array = self.array[::n1, ::n2, ::n3]
            cmin = np.min(sub_array[~np.isnan(sub_array)
                                    & ~np.isinf(sub_array)])
            cmax = np.max(sub_array[~np.isnan(sub_array)
                                    & ~np.isinf(sub_array)])
            crange = cmax - cmin
            self._clim = (cmin - crange, cmax + crange)
        else:
            self._clim = clim

        self.slice = int(round(self.array.shape[0] / 2.))

        from matplotlib.widgets import Slider

        self.slice_slider_ax = self.fig.add_axes([0.1, 0.95, 0.4, 0.03])
        self.slice_slider_ax.set_xticklabels("")
        self.slice_slider_ax.set_yticklabels("")
        self.slice_slider = Slider(self.slice_slider_ax,
                                   "3-d slice",
                                   0,
                                   self.array.shape[0],
                                   valinit=self.slice,
                                   valfmt="%i")
        self.slice_slider.on_changed(self.update_slice)
        self.slice_slider.drawon = False

        self.image = self.ax1.imshow(self.array[self.slice, :, :],
                                     origin='lower',
                                     interpolation='nearest',
                                     vmin=self._clim[0],
                                     vmax=self._clim[1],
                                     cmap=plt.cm.gray)

        self.vmin_slider_ax = self.fig.add_axes([0.1, 0.90, 0.4, 0.03])
        self.vmin_slider_ax.set_xticklabels("")
        self.vmin_slider_ax.set_yticklabels("")
        self.vmin_slider = Slider(self.vmin_slider_ax,
                                  "vmin",
                                  self._clim[0],
                                  self._clim[1],
                                  valinit=self._clim[0])
        self.vmin_slider.on_changed(self.update_vmin)
        self.vmin_slider.drawon = False

        self.vmax_slider_ax = self.fig.add_axes([0.1, 0.85, 0.4, 0.03])
        self.vmax_slider_ax.set_xticklabels("")
        self.vmax_slider_ax.set_yticklabels("")
        self.vmax_slider = Slider(self.vmax_slider_ax,
                                  "vmax",
                                  self._clim[0],
                                  self._clim[1],
                                  valinit=self._clim[1])
        self.vmax_slider.on_changed(self.update_vmax)
        self.vmax_slider.drawon = False

        self.grid1 = None
        self.grid2 = None
        self.grid3 = None

        self.ax2 = self.fig.add_axes([0.55, 0.1, 0.4, 0.7])

        # Add slicing box
        self.box = SliceCurve(colors=(0.8, 0.0, 0.0))
        self.ax1.add_collection(self.box)
        self.movable = MovableSliceBox(self.box, callback=self.update_pv_slice)
        self.movable.connect()

        # Add save button
        from matplotlib.widgets import Button
        self.save_button_ax = self.fig.add_axes([0.65, 0.90, 0.20, 0.05])
        self.save_button = Button(self.save_button_ax, 'Save slice to FITS')
        self.save_button.on_clicked(self.save_fits)

        self.pv_slice = None

        self.cidpress = self.fig.canvas.mpl_connect('button_press_event',
                                                    self.click)

    def click(self, event):

        if event.inaxes != self.ax2:
            return

        self.slice_slider.set_val(event.ydata)

    def save_fits(self, *args, **kwargs):

        if self.backend == 'Qt4Agg':
            from matplotlib.backends.backend_qt4 import _getSaveFileName
            plot_name = _getSaveFileName(
                self.fig.canvas.manager.window, "Choose filename",
                os.path.dirname(os.path.abspath(self.filename)), "", None)
            plot_name = str(plot_name)
        else:
            print("Enter filename: ", end='')
            plot_name = raw_input()

        if self.pv_slice is None:
            return

        from astropy.io import fits
        fits.writeto(plot_name, self.pv_slice, clobber=True)
        print("Saved file to: ", plot_name)

    def update_pv_slice(self, box):

        path = Path(zip(box.x, box.y))
        path.width = box.width

        self.pv_slice = extract_pv_slice(self.array, path)

        self.ax2.cla()
        self.ax2.imshow(self.pv_slice,
                        origin='lower',
                        aspect='auto',
                        interpolation='nearest')

        self.fig.canvas.draw()

    def show(self):
        import matplotlib.pyplot as plt
        plt.show()

    def update_slice(self, pos=None):

        if self.array.ndim == 2:
            self.image.set_array(self.array)
        else:
            self.slice = int(round(pos))
            self.image.set_array(self.array[self.slice, :, :])

        self.fig.canvas.draw()

    def update_vmin(self, vmin):
        if vmin > self._clim[1]:
            self._clim = (self._clim[1], self._clim[1])
        else:
            self._clim = (vmin, self._clim[1])
        self.image.set_clim(*self._clim)
        self.fig.canvas.draw()

    def update_vmax(self, vmax):
        if vmax < self._clim[0]:
            self._clim = (self._clim[0], self._clim[0])
        else:
            self._clim = (self._clim[0], vmax)
        self.image.set_clim(*self._clim)
        self.fig.canvas.draw()
Esempio n. 41
0
        30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
        30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
        30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 0, 0,
        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
    ]

    Istwert = [0.0, 0.0]

    Fehler = [0.0, 0.0]

    IFehler = 0

    for i in range(1, len(Sollwert)):
        t.append(i * 0.1)
        IFehler += Sollwert[i] - Istwert[i]
        Fehler.append(Sollwert[i] - Istwert[i])
        Istwert.append(Istwert[i] + PGain * Fehler[i] + DGain *
                       (Fehler[i] - Fehler[i - 1]) + IGain * IFehler)
    fig.canvas.draw_idle()

    ax.cla()
    ax.plot(Sollwert, label='Sollwert')
    ax.plot(Istwert, label='Istwert')
    ax.legend()


PSild.on_changed(update)
ISild.on_changed(update)
DSild.on_changed(update)

plt.show()
Esempio n. 42
0
class DisplayKNN(AbstractDisplayKNN):
    def __init__(self, classifier: AbstractKNN, x, y, classes: int, title='Training set'):
        self.__classifier: AbstractKNN = classifier
        self.__classes: int = classes
        self.__title: str = title
        self.__l = None
        self.__fig = None
        self.__slider_k = None
        self.__slider_size = None
        self.__x = x
        self.__y = y

    def render_map(self) -> None:
        colors = [tuple(np.random.random(3)) for _ in range(1, self.__classes)]

        x_1, x_2 = np.meshgrid(
            np.arange(start=self.__x[:, 0].min() - 1,
                      stop=self.__x[:, 0].max() + 1,
                      step=0.01),
            np.arange(start=self.__x[:, 1].min() - 1,
                      stop=self.__x[:, 1].max() + 1,
                      step=0.01))

        plt.contourf(x_1, x_2, self.__classifier.predict(
            np.array([x_1.ravel(), x_2.ravel()]).T).reshape(x_1.shape),
            alpha=0.75,
            cmap=ListedColormap(colors))

        plt.xlim(x_1.min(), x_1.max())
        plt.ylim(x_2.min(), x_2.max())

        for i, j in enumerate(np.unique(self.__y)):
            plt.scatter(self.__x[self.__y == j, 0], self.__x[self.__y == j, 1],
                        c=ListedColormap(colors)(i),
                        label=j)

        plt.title(self.__title)
        plt.xlabel('X')
        plt.ylabel('Y')
        plt.legend()
        plt.show()

    def render_graph(self) -> None:

        def update(val) -> None:
            """
            Inner method for update tracking
            :return: None
            """
            k = self.__slider_k.val
            size = self.__slider_size.val
            self.__l.set_ydata(self.__y)
            # Re-drawing the figure
            self.__fig.canvas.draw()
            return None

        # Plotting
        self.__fig = plt.figure()

        plt.subplots_adjust(bottom=0.25)
        ax = self.__fig.subplots()

        # Create and plot current xs, ys
        l, = ax.plot(self.__x[0], self.__x[1], label=self.__title)
        self.__l = l

        ax_k    = plt.axes([0.25, 0.15, 0.65, 0.03])
        ax_size = plt.axes([0.25, 0.1, 0.65, 0.03])

        self.__slider_k    = Slider(ax_k, 'K', 1, 50, valinit=1)
        self.__slider_size = Slider(ax_size, 'Size', 1, 2500, valinit=1000)

        self.__slider_k.on_changed(update)
        self.__slider_size.on_changed(update)

        plt.grid()
        plt.xlabel('X')
        plt.ylabel('Y')
        plt.legend()
        plt.show()

        return None
Esempio n. 43
0
    def GUIfit(self, sl_delay_margin=(-1., 1.), refine_results=False):
        '''
        automatic fit with possible user interaction to crop the data and 
        modify the electric delay f1,f2,delay are determined in the GUI. Then,
        data is cropped and autofit with delay is performed
        '''
        if sl_delay_margin[0] > sl_delay_margin[1]:
            sl_delay_margin = sl_delay_margin[::-1]
        #copy data
        fmin, fmax = self.f_data.min(), self.f_data.max()
        self.autofit(refine_results=refine_results)
        self.__delay = self._delay
        #prepare plot and slider
        import matplotlib.pyplot as plt
        from matplotlib.widgets import Slider, Button
        fig, ((ax2, ax0), (ax1, ax3)) = plt.subplots(nrows=2, ncols=2)
        plt.suptitle(
            'Normalized data. Use the silders to improve the fitting if '
            'necessary.')
        plt.subplots_adjust(left=0.25, bottom=0.25)
        l0, = ax0.plot(self.f_data * 1e-9, np.absolute(self.z_data))
        l1, = ax1.plot(self.f_data * 1e-9, np.angle(self.z_data))
        l2, = ax2.plot(np.real(self.z_data), np.imag(self.z_data))
        l0s, = ax0.plot(self.f_data * 1e-9, np.absolute(self.z_data_sim_norm))
        l1s, = ax1.plot(self.f_data * 1e-9, np.angle(self.z_data_sim_norm))
        l2s, = ax2.plot(np.real(self.z_data_sim_norm),
                        np.imag(self.z_data_sim_norm))
        ax0.set_xlabel('f (GHz)')
        ax1.set_xlabel('f (GHz)')
        ax2.set_xlabel('real')
        ax0.set_ylabel('amp')
        ax1.set_ylabel('phase (rad)')
        ax2.set_ylabel('imagl')
        fr_ann = ax3.annotate(
            'fr = %e Hz +- %e Hz' %
            (self.fitresults['fr'], self.fitresults['fr_err']),
            xy=(0.1, 0.8),
            xycoords='axes fraction')
        Ql_ann = ax3.annotate(
            'Ql = %e +- %e' %
            (self.fitresults['Ql'], self.fitresults['Ql_err']),
            xy=(0.1, 0.6),
            xycoords='axes fraction')
        Qc_ann = ax3.annotate(
            'Qc = %e +- %e' %
            (self.fitresults['absQc'], self.fitresults['absQc_err']),
            xy=(0.1, 0.4),
            xycoords='axes fraction')
        Qi_ann = ax3.annotate('Qi = %e +- %e' %
                              (self.fitresults['Qi_dia_corr'],
                               self.fitresults['Qi_dia_corr_err']),
                              xy=(0.1, 0.2),
                              xycoords='axes fraction')
        axcolor = 'lightgoldenrodyellow'
        axdelay = plt.axes([0.25, 0.05, 0.65, 0.03], facecolor=axcolor)
        axf2 = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor)
        axf1 = plt.axes([0.25, 0.15, 0.65, 0.03], facecolor=axcolor)
        sscale = 10.
        sl_delay = self.__delay / (sscale * self.__delay)
        sdelay = Slider(axdelay,
                        'delay',
                        max(-1., sl_delay - abs(sl_delay_margin[0])),
                        min(1., sl_delay + abs(sl_delay_margin[1])),
                        valinit=sl_delay,
                        valfmt='%f')
        df = (fmax - fmin) * 0.05
        sf2 = Slider(axf2,
                     'f2', (fmin - df) * 1e-9, (fmax + df) * 1e-9,
                     valinit=fmax * 1e-9,
                     valfmt='%.10f GHz')
        sf1 = Slider(axf1,
                     'f1', (fmin - df) * 1e-9, (fmax + df) * 1e-9,
                     valinit=fmin * 1e-9,
                     valfmt='%.10f GHz')

        def update(val):
            self.autofit(electric_delay=sdelay.val * sscale * self.__delay,
                         fcrop=(sf1.val * 1e9, sf2.val * 1e9),
                         refine_results=refine_results)
            l0.set_data(self.f_data * 1e-9, np.absolute(self.z_data))
            l1.set_data(self.f_data * 1e-9, np.angle(self.z_data))
            l2.set_data(np.real(self.z_data), np.imag(self.z_data))
            l0s.set_data(self.f_data[self._fid] * 1e-9,
                         np.absolute(self.z_data_sim_norm[self._fid]))
            l1s.set_data(self.f_data[self._fid] * 1e-9,
                         np.angle(self.z_data_sim_norm[self._fid]))
            l2s.set_data(np.real(self.z_data_sim_norm[self._fid]),
                         np.imag(self.z_data_sim_norm[self._fid]))
            fr_ann.set_text('fr = %e Hz +- %e Hz' %
                            (self.fitresults['fr'], self.fitresults['fr_err']))
            Ql_ann.set_text('Ql = %e +- %e' %
                            (self.fitresults['Ql'], self.fitresults['Ql_err']))
            Qc_ann.set_text(
                '|Qc| = %e +- %e' %
                (self.fitresults['absQc'], self.fitresults['absQc_err']))
            Qi_ann.set_text('Qi_dia_corr = %e +- %e' %
                            (self.fitresults['Qi_dia_corr'],
                             self.fitresults['Qi_dia_corr_err']))
            fig.canvas.draw_idle()

        def btnclicked(event):
            self.autofit(electric_delay=None,
                         fcrop=(sf1.val * 1e9, sf2.val * 1e9),
                         refine_results=refine_results)
            self.__delay = self._delay
            sdelay.reset()
            update(event)

        sf1.on_changed(update)
        sf2.on_changed(update)
        sdelay.on_changed(update)
        btnax = plt.axes([0.05, 0.1, 0.1, 0.04])
        button = Button(btnax, 'auto-delay', color=axcolor, hovercolor='0.975')
        button.on_clicked(btnclicked)
        plt.show()
        plt.close()
g1.set_xlabel(r"$d(m)$", fontsize=20, labelpad=0)
g1.set_ylabel(r"$\frac{I}{I_{max}}$", rotation=0, fontsize=20, labelpad=20)
ligne, = g1.plot(list_X,
                 intensité(list_X, list_x, D) /
                 m)  #pour rafraichir le graphique
g1.set_title("Diffraction Fresnel- diffraction de Fraunhoffer", fontsize=20)

axD = plt.axes([0.2, 0.01, 0.6, 0.02])
cD = Slider(axD, "$D$", -3, 1)


def maj(_):
    D = 5 * 10**cD.val
    largeur_écran = 100 * a * D
    list_X = np.linspace(-largeur_écran / 2, largeur_écran / 2, points_ecran)
    m = max(intensité(list_X, list_x, D))  #pour normaliser y
    ligne.set_data(list_X, intensité(list_X, list_x, D) / m)
    g1.set_xlim(
        list_X[0],
        list_X[-1])  #car pas de redimensionnement automatique avec set_data
    F = (str(a * a / (4 * D * lamb)))[0:4]
    affichage = r"$F=\frac{a^2}{\lambda D}=$" + F + "\nD=" + (
        str(D))[0:5] + "m\na=1,00mm"
    #g1.set_title(affichage)
    txt.set_position([0.9 * list_X[0], 0.8])
    txt.set_text(affichage)


cD.on_changed(maj)

plt.show()
    ax.set_title(r'Approx-ratio: ' + ('%.3f' % approx_ratio) +
                 r', makespan: ' + ('%.3f' % makespan) + r', natural: ' +
                 ('%.3f' % nat_t))
    ax.margins(x=0)

    axcolor = 'lightgoldenrodyellow'
    #axfreq = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor)
    #axamp = plt.axes([0.25, 0.15, 0.65, 0.03], facecolor=axcolor)
    ax_v0 = plt.axes([0.25, 0.05, 0.65, 0.03], facecolor=axcolor)
    ax_v1 = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor)
    ax_delay = plt.axes([0.25, 0.15, 0.65, 0.03], facecolor=axcolor)

    v0_slider = Slider(ax_v0, 'v0', 0.1, 30.0, valinit=v0_init)
    v1_slider = Slider(ax_v1, 'v1', 0.1, 10.0, valinit=v1_init)
    delay_slider = Slider(ax_delay, 'delay', 0, 10, valinit=delay_init)

    v0_slider.on_changed(update)
    v1_slider.on_changed(update)
    delay_slider.on_changed(update)

    resetax = plt.axes([0.8, 0.00, 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], facecolor=axcolor)
    radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0)

    radio.on_clicked(colorfunc)
    fig.canvas.mpl_connect('button_press_event', on_press)
    plt.show()
Esempio n. 46
0
File: test.py Progetto: Ketchp/Test
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider


data_path = 'Ja/linear_acceleration.csv'
with open(data_path, 'r') as f:
    reader = csv.reader(f, delimiter=',')
    data = np.array(list(reader)).astype(float)


fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.25)

shift = 10000
l, = plt.plot(data[:,0],data[:,3])
plt.axis([1601038483787, 1601038483787+shift, -4, 4])

axpos = plt.axes([0.2, 0.1, 0.65, 0.03])

spos = Slider(axpos, 'Pos', 1601038483787, 1601041037019-shift)

def update(val):
    pos = spos.val
    ax.axis([pos,pos+shift,-4,4])
    fig.canvas.draw_idle()

spos.on_changed(update)

plt.show()
Esempio n. 47
0

#Update Function
def update(val,firstTime=0):
    plot(int(val) )

#Animate Function
def animate(val):
    slider_z.set_val(val)



#Slider
sliderAxes_z = plt.axes([0.3, 0.01, 0.5, 0.05])
slider_z = Slider(sliderAxes_z, 'Event', 0, len(events), valinit=0)
slider_z.on_changed(update)




if __name__ == '__main__':

    if options.save:
        outputDirectory = "Output"
        if not os.path.exists(outputDirectory):
            os.makedirs(outputDirectory)

    # FuncAnimation will call the 'update' function for each frame; here
    # animating over N frames, with an interval of 200ms between frames.
    if options.animate:
        anim = FuncAnimation(fig, animate, frames=np.arange(0, len(events)), interval=500)
Esempio n. 48
0
    except:
        print("Error Sending Data")

    return


def update(val):
    global pwm, freq
    pwm = int(srpm.val)
    ESP8266_send()
    freq = int(sfreq.val)
    l.set_ydata(np.sin(2 * np.pi * freq * t))
    fig.canvas.draw_idle()


sfreq.on_changed(update)
srpm.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):
    global pwm, freq, activeButton
    pwm = a0
    freq = f0
    activeButton = 0
    ESP8266_send()
    sfreq.reset()
    srpm.reset()
Esempio n. 49
0
File: gui.py Progetto: jbednar/viscm
class viscm_editor(object):
    def __init__(self, uniform_space="CAM02-UCS",
                 min_Jp=15, max_Jp=95, xp=None, yp=None):
        from .bezierbuilder import BezierModel, BezierBuilder

        self._uniform_space = uniform_space

        self.figure = plt.figure()
        axes = _viscm_editor_axes(self.figure)

        ax_btn_wireframe = plt.axes([0.7, 0.15, 0.1, 0.025])
        self.btn_wireframe = Button(ax_btn_wireframe, 'Show 3D gamut')
        self.btn_wireframe.on_clicked(self.plot_3d_gamut)

        ax_btn_wireframe = plt.axes([0.81, 0.15, 0.1, 0.025])
        self.btn_save = Button(ax_btn_wireframe, 'Save colormap')
        self.btn_save.on_clicked(self.save_colormap)

        ax_btn_props = plt.axes([0.81, 0.1, 0.1, 0.025])
        self.btn_props = Button(ax_btn_props, 'Properties')
        self.btn_props.on_clicked(self.show_viscm)
        self.prop_windows = []

        axcolor = 'None'
        ax_jp_min = plt.axes([0.1, 0.1, 0.5, 0.03], axisbg=axcolor)
        ax_jp_min.imshow(np.linspace(0, 100, 101).reshape(1, -1), cmap='gray')
        ax_jp_min.set_xlim(0, 100)

        ax_jp_max = plt.axes([0.1, 0.15, 0.5, 0.03], axisbg=axcolor)
        ax_jp_max.imshow(np.linspace(0, 100, 101).reshape(1, -1), cmap='gray')

        self.jp_min_slider = Slider(ax_jp_min,
                                    r"$J'_\mathrm{min}$",
                                    0, 100,
                                    valinit=min_Jp)
        self.jp_max_slider = Slider(ax_jp_max,
                                    r"$J'_\mathrm{max}$",
                                    0, 100,
                                    valinit=max_Jp)

        self.jp_min_slider.on_changed(self._jp_update)
        self.jp_max_slider.on_changed(self._jp_update)

        if xp is None:
            xp = [-2.0591553836234482, 59.377014829142524,
                  43.552546744036135, 4.7670857511283202,
                  -9.5059638942617539]

        if yp is None:
            yp = [-25.664893617021221, -21.941489361702082,
                  38.874113475177353, 20.567375886524871,
                  32.047872340425585]

        self.bezier_model = BezierModel(xp, yp)
        self.cmap_model = BezierCMapModel(self.bezier_model,
                                          self.jp_min_slider.val,
                                          self.jp_max_slider.val,
                                          uniform_space)
        self.highlight_point_model = HighlightPointModel(self.cmap_model, 0.5)

        self.bezier_builder = BezierBuilder(axes['bezier'], self.bezier_model)
        self.bezier_gamut_viewer = GamutViewer2D(axes['bezier'],
                                                 self.highlight_point_model,
                                                 uniform_space)
        tmp = HighlightPoint2DView(axes['bezier'],
                                   self.highlight_point_model)
        self.bezier_highlight_point_view = tmp

        # draw_pure_hue_angles(axes['bezier'])
        axes['bezier'].set_xlim(-100, 100)
        axes['bezier'].set_ylim(-100, 100)

        self.cmap_view = CMapView(axes['cm'], self.cmap_model)
        self.cmap_highlighter = HighlightPointBuilder(
            axes['cm'],
            self.highlight_point_model)

        print("Click sliders at bottom to change min/max lightness")
        print("Click on colorbar to adjust gamut view")
        print("Click-drag to move control points, ")
        print("  shift-click to add, control-click to delete")

    def plot_3d_gamut(self, event):
        fig, ax = plt.subplots(subplot_kw=dict(projection='3d'))
        self.wireframe_view = WireframeView(ax,
                                            self.cmap_model,
                                            self.highlight_point_model,
                                            self._uniform_space)
        plt.show()

    def save_colormap(self, event):
        import textwrap

        template = textwrap.dedent('''
        from matplotlib.colors import ListedColormap
        from numpy import nan, inf

        # Used to reconstruct the colormap in viscm
        parameters = {{'xp': {xp},
                      'yp': {yp},
                      'min_Jp': {min_Jp},
                      'max_Jp': {max_Jp}}}

        cm_data = {array_list}

        test_cm = ListedColormap(cm_data, name=__file__)


        if __name__ == "__main__":
            import matplotlib.pyplot as plt
            import numpy as np

            try:
                from viscm import viscm
                viscm(test_cm)
            except ImportError:
                print("viscm not found, falling back on simple display")
                plt.imshow(np.linspace(0, 100, 256)[None, :], aspect='auto',
                           cmap=test_cm)
            plt.show()
        ''')

        rgb, _ = self.cmap_model.get_sRGB(num=256)
        with open('/tmp/new_cm.py', 'w') as f:
            array_list = np.array2string(rgb, max_line_width=78,
                                         prefix='cm_data = ',
                                         separator=',')

            xp, yp = self.cmap_model.bezier_model.get_control_points()

            data = dict(array_list=array_list,
                        xp=xp,
                        yp=yp,
                        min_Jp=self.cmap_model.min_Jp,
                        max_Jp=self.cmap_model.max_Jp)

            f.write(template.format(**data))

            print("*" * 50)
            print("Saved colormap to /tmp/new_cm.py")
            print("*" * 50)

    def show_viscm(self, event):
        cm = LinearSegmentedColormap.from_list(
            'test_cm',
            self.cmap_model.get_sRGB(num=256)[0])
        self.prop_windows.append(viscm(cm, name='test_cm'))
        plt.show()

    def _jp_update(self, val):
        jp_min = self.jp_min_slider.val
        jp_max = self.jp_max_slider.val

        smallest, largest = min(jp_min, jp_max), max(jp_min, jp_max)
        if (jp_min > smallest) or (jp_max < largest):
            self.jp_min_slider.set_val(smallest)
            self.jp_max_slider.set_val(largest)

        self.cmap_model.set_Jp_minmax(smallest, largest)
Esempio n. 50
0
def test_reverse_warp():
    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.widgets import Slider, Button, RadioButtons
    import cv2

    global timg, depth, pose, intrinsic, sx, sy, sz, rx, ry, rz

    h, w = 100, 100
    f = 4.
    depth = torch.ones(1, h, w)
    depth[0, 40:60, 40:60] = 0.5

    intrinsic = torch.tensor([[w / f, 0., w / 2.], [0., w / f, h / 2.],
                              [0., 0., 1.]]).unsqueeze(0)
    pose = torch.tensor([0, 0, 0, 0, 0, 0]).float().unsqueeze(0)

    img = cv2.imread(
        "/home/nemodrive0/workspace/andrein/path_generation/dataset/0001.png")
    img = cv2.resize(img, (h, w))
    timg = torch.tensor(img).float().permute(2, 0, 1).unsqueeze(0)

    def test_warp(timg, depth, pose, intrinsic):
        new_img, _ = reverse_warp(timg, depth, pose, intrinsic)
        new_img = new_img.squeeze(0).permute(1, 2, 0).numpy().astype(np.uint8)
        return new_img

    fig, ax = plt.subplots()
    plt.subplots_adjust(left=0.25, bottom=0.40)

    l = plt.imshow(img)

    axcolor = 'lightgoldenrodyellow'
    ax_x = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor)
    ax_y = plt.axes([0.25, 0.15, 0.65, 0.03], facecolor=axcolor)
    ax_z = plt.axes([0.25, 0.20, 0.65, 0.03], facecolor=axcolor)

    ax_rx = plt.axes([0.25, 0.25, 0.65, 0.03], facecolor=axcolor)
    ax_ry = plt.axes([0.25, 0.30, 0.65, 0.03], facecolor=axcolor)
    ax_rz = plt.axes([0.25, 0.35, 0.65, 0.03], facecolor=axcolor)

    f0 = 0.
    delta_f = 0.1
    interval = [-5, 5]
    sx = Slider(ax_x,
                'X',
                interval[0],
                interval[1],
                valinit=f0,
                valstep=delta_f)
    sy = Slider(ax_y,
                'Y',
                interval[0],
                interval[1],
                valinit=f0,
                valstep=delta_f)
    sz = Slider(ax_z,
                'Z',
                interval[0],
                interval[1],
                valinit=f0,
                valstep=delta_f)
    rx = Slider(ax_rx,
                'Rx',
                interval[0],
                interval[1],
                valinit=f0,
                valstep=delta_f)
    ry = Slider(ax_ry,
                'Ry',
                interval[0],
                interval[1],
                valinit=f0,
                valstep=delta_f)
    rz = Slider(ax_rz,
                'Rz',
                interval[0],
                interval[1],
                valinit=f0,
                valstep=delta_f)

    def update(val):
        global timg, depth, pose, intrinsic, sx, sy, sz, rx, ry, rz
        x = sx.val
        y = sy.val
        z = sz.val
        vrx = rx.val
        vry = ry.val
        vrz = rz.val
        pose[0, 0] = x
        pose[0, 1] = y
        pose[0, 2] = z
        pose[0, 3] = vrx
        pose[0, 4] = vry
        pose[0, 5] = vrz

        new_img = test_warp(timg, depth, pose, intrinsic)
        l.set_data(new_img)
        fig.canvas.draw_idle()

    sx.on_changed(update)
    sy.on_changed(update)
    sz.on_changed(update)
    rx.on_changed(update)
    ry.on_changed(update)
    rz.on_changed(update)

    plt.show()
Esempio n. 51
0
a0 = 10
f0 = 45
axcolor = 'lightgoldenrodyellow'
angle = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor)
iter = plt.axes([0.25, 0.15, 0.65, 0.03], facecolor=axcolor)

sangle = Slider(angle, 'Angle', 1, 75, valinit=f0)
siter = Slider(iter, 'Iterations', 1, 15, valinit=a0)


def update_angle(val):
    fig.canvas.draw_idle()


sangle.on_changed(update_angle)


def update_iter(val):
    fig.canvas.draw_idle()


siter.on_changed(update_iter)

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


def reset(event):
    sangle.reset()
    siter.reset()
Esempio n. 52
0
    if speed != sspeed.val:
        sspeed.set_val(speed)
    l.set_ydata(speed / t)
    fig.canvas.draw_idle()


def updateSpeed(val):
    speed = sspeed.val
    temp = (speed - 331) / 0.6
    if (temp != stemp.val):
        stemp.set_val(temp)
    l.set_ydata((331 + 0.6 * temp) / t)
    fig.canvas.draw_idle()


sspeed.on_changed(updateSpeed)
stemp.on_changed(updateTemp)

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


def reset(event):
    sspeed.reset()
    stemp.reset()


button.on_clicked(reset)

rax = plt.axes([0.01, 0.7, 0.15, 0.15], facecolor=axcolor)
radio = RadioButtons(rax, ('yellow', 'pink', 'green'), active=0)
Esempio n. 53
0
class FitPlot():

    plt_time = 0
    plt_radius = 0
    fsize3d = 16
    fsize = matplotlib.rcParams['font.size']

    #ts_revisions = []
    edge_discontinuties = []
    core_discontinuties = []

    tbeg = 0
    tend = 7
    picked = False
    grid = False
    logy = False
    m2g = None

    def __init__(self, parent, fit_frame):
        self.parent = parent

        self.fit_frame = fit_frame

        self.rstride = 1
        self.cstride = 3

        self.tstep = None
        self.xlab = ''
        self.ylab = ''
        self.ylab_diff = ''

    def isfloat(self, num):

        if num == '':
            return True
        try:
            float(num)
            return True
        except:
            return False

    def update_axis_range(self, tbeg, tend):
        if tbeg is None or tend is None:
            return
        self.main_slider.valmin = tbeg
        self.main_slider.valmax = tend
        self.sl_ax_main.set_xlim(tbeg, tend)
        self.ax_main.set_xlim(self.options['rho_min'], self.options['rho_max'])
        self.tbeg = tbeg
        self.tend = tend

    def change_set_prof_load(self):
        #update fit figure if the fitted quantity was changed

        self.sl_eta.set_val(self.options['eta'])
        self.sl_lam.set_val(self.options['lam'])

        if self.options['data_loaded']:
            self.init_plot()
            self.changed_fit_slice()
        else:
            self.ax_main.cla()
            self.ax_main.grid(self.grid)
            self.fig.canvas.draw_idle()

    def init_plot_data(self, prof, data_d, elms, mhd_modes):

        #merge all diagnostics together
        unit, labels = '', []
        data_rho, plot_rho, data, data_err,weights, data_tvec, plot_tvec,diags = [],[],[],[],[],[],[],[]
        #channel and point index for later identification
        ind_channels, ind_points = [], []
        n_ch, n_points = 0, 0
        for ch in data_d['data']:
            if prof not in ch: continue
            d = ch[prof].values
            data.append(d)
            err = np.copy(ch[prof + '_err'].values)
            #NOTE negative values are set to be masked
            mask = err <= 0
            #negative infinite ponts will not be shown
            err[np.isfinite(err) & mask] *= -1
            data_err.append(np.ma.array(err, mask=mask))
            data_rho.append(ch['rho'].values)
            data_tvec.append(
                np.tile(ch['time'].values,
                        data_rho[-1].shape[:0:-1] + (1, )).T)
            plot_tvec.append(np.tile(ch['time'].values, d.shape[1:] + (1, )).T)

            s = d.shape
            dch = 1 if len(s) == 1 else s[1]
            ind_channels.append(
                np.tile(np.arange(dch, dtype='uint32') + n_ch, (s[0], 1)))
            n_ch += dch
            ind_points.append(
                np.tile(
                    n_points +
                    np.arange(d.size, dtype='uint32').reshape(d.shape).T,
                    data_rho[-1].shape[d.ndim:] + ((1, ) * d.ndim)).T)
            n_points += d.size

            if 'weight' in ch:
                #non-local measurements
                weights.append(ch['weight'].values)
                plot_rho.append(ch['rho_tg'].values)
            else:
                weights.append(np.ones_like(d))
                plot_rho.append(ch['rho'].values)

            diags.append(ch['diags'].values)
            labels.append(ch[prof].attrs['label'])

        unit = ch[prof].attrs['units']

        if n_ch == 0 or n_points == 0:
            print('No data !! Try to extend time range')
            return

        diag_names = data_d['diag_names']
        label = ','.join(np.unique(labels))

        self.elms = elms
        self.mhd_modes = mhd_modes

        self.options['data_loaded'] = True
        self.options['fitted'] = False
        rho = np.hstack([r.ravel() for r in data_rho])
        y = np.hstack([d.ravel() for d in data])
        yerr = np.ma.hstack([de.ravel() for de in data_err])

        self.channel = np.hstack([ch.ravel() for ch in ind_channels])
        points = np.hstack([p.ravel() for p in ind_points])
        weights = np.hstack([w.ravel() for w in weights])
        tvec = np.hstack([t.ravel() for t in data_tvec])
        diags = np.hstack([d.ravel() for d in diags])
        self.plot_tvec = np.hstack([t.ravel() for t in plot_tvec])
        self.plot_rho = np.hstack([r.ravel() for r in plot_rho])
        self.options['rho_min'] = np.minimum(
            0, np.maximum(-1.1, self.plot_rho.min()))
        diag_dict = {d: i for i, d in enumerate(diag_names)}
        self.ind_diag = np.array([diag_dict[d] for d in diags])
        self.diags = diag_names

        if self.parent.elmsphase:
            #epl phase
            self.plot_tvec = np.interp(self.plot_tvec, self.elms['tvec'],
                                       self.elms['data'])
            tvec = np.interp(tvec, self.elms['tvec'], self.elms['data'])

        if self.parent.elmstime:
            #time from nearest ELM
            self.plot_tvec -= self.elms['elm_beg'][
                self.elms['elm_beg'].searchsorted(self.plot_tvec) - 1]
            tvec -= self.elms['elm_beg'][
                self.elms['elm_beg'].searchsorted(tvec) - 1]

        tstep = 'None'
        if self.tstep is None:
            tstep = float(data_d['tres'])

        self.parent.set_trange(np.amin(tvec), np.amax(tvec), tstep)

        self.tres = self.tstep

        #plot timeslice nearest to the original location where are some data
        self.plt_time = tvec[np.argmin(abs(self.plt_time - tvec))]

        self.ylab = r'$%s\ [\mathrm{%s}]$' % (label, unit)
        xlab = self.options['rho_coord'].split('_')
        self.xlab = xlab[0]
        if self.options['rho_coord'][:3] in ['Psi', 'rho']:
            self.xlab = '\\' + self.xlab
        if len(xlab) > 1:
            self.xlab += '_{' + xlab[1] + '}'
        self.xlab = '$' + self.xlab + '$'

        self.ylab_diff = r'$R/L_{%s}/\rho\ [-]$' % label

        #create object of the fitting routine
        self.m2g = map2grid(rho, tvec, y, yerr, points, weights,
                            self.options['nr_new'], self.tstep)
        self.options['fit_prepared'] = False
        self.options['zeroed_outer'] = False
        self.options['elmrem_ind'] = False

        self.init_plot()
        self.changed_fit_slice()

    def init_plot(self):
        #clear and inicialize the main plot with the fits

        self.ax_main.cla()
        self.ax_main.grid(self.grid)

        self.ax_main.ticklabel_format(style='sci', scilimits=(-2, 2), axis='y')

        self.ax_main.set_ylabel(self.ylab, fontsize=self.fsize + 2)
        self.ax_main.set_xlabel(self.xlab, fontsize=self.fsize + 2)

        #the plots inside
        colors = matplotlib.cm.brg(np.linspace(0, 1, len(self.diags)))
        self.plotline, self.caplines, self.barlinecols = [], [], []
        self.replot_plot = [
            self.ax_main.plot([], [], '+', c=c)[0] for c in colors
        ]

        for i, d in enumerate(self.diags):
            plotline, caplines, barlinecols = self.ax_main.errorbar(
                0,
                np.nan,
                0,
                fmt='.',
                capsize=4,
                label=d,
                c=colors[i],
                zorder=1)
            self.plotline.append(plotline)
            self.caplines.append(caplines)
            self.barlinecols.append(barlinecols)

        self.fit_plot, = self.ax_main.plot([], [],
                                           'k-',
                                           linewidth=.5,
                                           zorder=2)
        nr = self.options['nr_new']
        self.fit_confidence = self.ax_main.fill_between(np.arange(nr),
                                                        np.zeros(nr),
                                                        np.zeros(nr),
                                                        alpha=.2,
                                                        facecolor='k',
                                                        edgecolor='None',
                                                        zorder=0)

        self.lcfs_line = self.ax_main.axvline(1, ls='--', c='k', visible=False)
        self.zero_line = self.ax_main.axhline(0, ls='--', c='k', visible=False)

        self.core_discontinuties = [
            self.ax_main.axvline(t, ls='-', lw=.5, c='k', visible=False)
            for t in eval(self.fit_options['sawteeth_times'].get())
        ]
        self.edge_discontinuties = [
            self.ax_main.axvline(t, ls='-', lw=.5, c='k', visible=False)
            for t in self.elms['elm_beg']
        ]

        if self.mhd_modes is not None:
            self.mhd_locations = {
                mode: self.ax_main.axvline(np.nan,
                                           ls='-',
                                           lw=.5,
                                           c='k',
                                           visible=False)
                for mode in self.mhd_modes['modes']
            }
            self.mhd_labels = {
                mode: self.ax_main.text(np.nan, 0, mode, visible=False)
                for mode in self.mhd_modes['modes']
            }

        self.spline_mean, = self.ax_main.plot([], [],
                                              '--',
                                              c='.5',
                                              linewidth=1,
                                              visible=False)
        self.spline_min, = self.ax_main.plot([], [],
                                             ':',
                                             c='.5',
                                             linewidth=1,
                                             visible=False)
        self.spline_max, = self.ax_main.plot([], [],
                                             ':',
                                             c='.5',
                                             linewidth=1,
                                             visible=False)

        leg = self.ax_main.legend(fancybox=True, loc='upper right')
        leg.get_frame().set_alpha(0.9)
        try:
            leg.set_draggable(True)
        except:
            leg.draggable()

        #make the legend interactive
        self.leg_diag_ind = {}
        for idiag, legline in enumerate(leg.legendHandles):
            legline.set_picker(20)  # 20 pts tolerance
            self.leg_diag_ind[legline] = idiag

        description = self.parent.device + ' %d' % self.shot
        self.plot_description = self.ax_main.text(
            1.01,
            .05,
            description,
            rotation='vertical',
            transform=self.ax_main.transAxes,
            verticalalignment='bottom',
            size=10,
            backgroundcolor='none',
            zorder=100)

        title_template = '%s, time: %.3fs'  # prints running simulation time
        self.time_text = self.ax_main.text(.05,
                                           .95,
                                           '',
                                           transform=self.ax_main.transAxes)
        self.chi2_text = self.ax_main.text(.05,
                                           .90,
                                           '',
                                           transform=self.ax_main.transAxes)

        self.fit_options['dt'].set('%.2g' % (self.tres * 1e3))
        self.click_event = {1: None, 2: None, 3: None}

        def line_select_callback(eclick, erelease):
            #'eclick and erelease are the press and release events'

            click_event = self.click_event[eclick.button]
            #make sure that this event is "unique", due to some bug in matplolib
            if click_event is None or click_event.xdata != eclick.xdata:
                self.click_event[eclick.button] = eclick
                x1, y1 = eclick.xdata, eclick.ydata
                x2, y2 = erelease.xdata, erelease.ydata

                #delete/undelet selected points
                undelete = eclick.button == 3
                what = 'channel' if self.ctrl else 'point'
                self.delete_points(eclick, (x1, x2), (y1, y2), what, undelete)

            self.RS_delete.set_visible(False)
            self.RS_undelete.set_visible(False)
            self.RS_delete.visible = True
            self.RS_undelete.visible = True

        rectprops = dict(facecolor='red',
                         edgecolor='red',
                         alpha=0.5,
                         fill=True,
                         zorder=99)

        self.RS_delete = RectangleSelector(
            self.ax_main,
            line_select_callback,
            drawtype='box',
            useblit=True,
            button=[1],  # don't use middle button
            minspanx=5,
            minspany=5,
            rectprops=rectprops,
            spancoords='pixels',
            interactive=True)
        rectprops = dict(facecolor='blue',
                         edgecolor='blue',
                         alpha=0.5,
                         fill=True,
                         zorder=99)

        self.RS_undelete = RectangleSelector(
            self.ax_main,
            line_select_callback,
            drawtype='box',
            useblit=True,
            button=[3],  # don't use middle button
            minspanx=5,
            minspany=5,
            rectprops=rectprops,
            spancoords='pixels',
            interactive=True)

    def changed_fit_slice(self):
        #switch between time/radial slice or gradient

        if self.plot_type.get() in [1, 2]:
            #radial slice, radial gradient
            self.view_step.config(textvariable=self.fit_options['dt'])
            self.view_step_lbl.config(text='Plot step [ms]')
            self.main_slider.label = 'Time:'
            self.parent.set_trange(self.tbeg, self.tend)
            self.ax_main.set_xlim(self.options['rho_min'],
                                  self.options['rho_max'])
            self.ax_main.set_xlabel(self.xlab, fontsize=self.fsize + 2)
            if self.plot_type.get() == 1:
                self.ax_main.set_ylabel(self.ylab, fontsize=self.fsize + 2)
            if self.plot_type.get() == 2:
                self.ax_main.set_ylabel(self.ylab_diff,
                                        fontsize=self.fsize + 2)

        if self.plot_type.get() in [0]:
            #time slice
            self.view_step.config(
                textvariable=self.fit_options.get('dr', 0.02))
            self.view_step_lbl.config(text='Radial step [-]')
            self.main_slider.label = 'Radius:'
            self.main_slider.valmin = self.options['rho_min']
            self.main_slider.valmax = self.options['rho_max']
            self.sl_ax_main.set_xlim(self.options['rho_min'],
                                     self.options['rho_max'])
            self.ax_main.set_xlim(self.tbeg, self.tend)
            self.ax_main.set_xlabel('time [s]', fontsize=self.fsize + 2)
            self.ax_main.set_ylabel(self.ylab)

        self.lcfs_line.set_visible(self.plot_type.get() in [1, 2])
        self.zero_line.set_visible(self.plot_type.get() in [0, 2])

        self.updateMainSlider()
        self.PreparePloting()
        self.plot_step()
        self.plot3d(update=True)

    def init_fit_frame(self):

        #frame with the navigation bar for the main plot

        fit_frame_up = tk.Frame(self.fit_frame)
        fit_frame_down = tk.LabelFrame(self.fit_frame, relief='groove')
        fit_frame_up.pack(side=tk.TOP, fill=tk.BOTH)
        fit_frame_down.pack(side=tk.BOTTOM, fill=tk.BOTH, expand=tk.Y)

        self.plot_type = tk.IntVar(master=self.fit_frame)
        self.plot_type.set(1)
        r_buttons = 'Radial slice', 'Time slice', 'Gradient'
        for nbutt, butt in enumerate(r_buttons):
            button = tk.Radiobutton(fit_frame_up,
                                    text=butt,
                                    variable=self.plot_type,
                                    command=self.changed_fit_slice,
                                    value=nbutt)
            button.pack(anchor='w', side=tk.LEFT, pady=2, padx=2)

        # canvas frame

        self.fig = Figure(figsize=(10, 10), dpi=75)
        self.fig.patch.set_facecolor((.93, .93, .93))
        self.ax_main = self.fig.add_subplot(111)

        self.canvasMPL = tkagg.FigureCanvasTkAgg(self.fig,
                                                 master=fit_frame_down)
        self.toolbar = NavigationToolbar2Tk(self.canvasMPL, fit_frame_down)

        def print_figure(filename, **kwargs):
            #cheat print_figure function to save only the plot without the sliders.
            if 'bbox_inches' not in kwargs:
                fig = self.ax_main.figure
                extent = self.ax_main.get_tightbbox(
                    fig.canvas.renderer).transformed(
                        fig.dpi_scale_trans.inverted())
                extent.y1 += .3
                extent.x1 += .3
                kwargs['bbox_inches'] = extent
            self.canvas_print_figure(filename, **kwargs)

        self.canvas_print_figure = self.toolbar.canvas.print_figure
        self.toolbar.canvas.print_figure = print_figure

        self.canvasMPL.get_tk_widget().pack(side=tk.TOP,
                                            fill=tk.BOTH,
                                            expand=1)
        self.canvasMPL._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)

        self.lcfs_line = self.ax_main.axvline(1, ls='--', c='k', visible=False)
        self.zero_line = self.ax_main.axhline(0, ls='--', c='k', visible=False)

        hbox1 = tk.Frame(fit_frame_down)
        hbox1.pack(side=tk.BOTTOM, fill=tk.X)
        mouse_help = tk.Label(hbox1, text='Mouse: ')
        mouse_left = tk.Label(hbox1,
                              text='Left (+Ctrl): del point (Channel)  ',
                              fg="#900000")
        mouse_mid = tk.Label(hbox1, text='Mid: re-fit  ', fg="#009000")
        mouse_right = tk.Label(hbox1,
                               text='Right: undelete point  ',
                               fg="#000090")
        mouse_wheel = tk.Label(hbox1, text='Wheel: shift', fg="#905090")

        for w in (mouse_help, mouse_left, mouse_mid, mouse_right, mouse_wheel):
            w.pack(side=tk.LEFT)

        hbox2 = tk.Frame(fit_frame_down)
        hbox2.pack(side=tk.BOTTOM, fill=tk.X)

        helv36 = tkinter.font.Font(family='Helvetica', size=10, weight='bold')
        calc_button = tk.Button(hbox2,
                                text='Fit',
                                bg='red',
                                command=self.calculate,
                                font=helv36)
        calc_button.pack(side=tk.LEFT)

        self.playfig = tk.PhotoImage(file=icon_dir + 'play.gif',
                                     master=self.fit_frame)
        self.pausefig = tk.PhotoImage(file=icon_dir + 'pause.gif',
                                      master=self.fit_frame)
        self.forwardfig = tk.PhotoImage(file=icon_dir + 'forward.gif',
                                        master=self.fit_frame)
        self.backwardfig = tk.PhotoImage(file=icon_dir + 'backward.gif',
                                         master=self.fit_frame)

        self.backward_button = tk.Button(hbox2,
                                         command=self.Backward,
                                         image=self.backwardfig)
        self.backward_button.pack(side=tk.LEFT)
        self.play_button = tk.Button(hbox2,
                                     command=self.Play,
                                     image=self.playfig)
        self.play_button.pack(side=tk.LEFT)
        self.forward_button = tk.Button(hbox2,
                                        command=self.Forward,
                                        image=self.forwardfig)
        self.forward_button.pack(side=tk.LEFT)

        self.button_3d = tk.Button(hbox2,
                                   command=self.plot3d,
                                   text='3D',
                                   font=helv36)
        self.button_3d.pack(side=tk.LEFT)

        self.stop = True
        self.ctrl = False
        self.shift = False

        def stop_handler(event=None, self=self):
            self.stop = True

        self.forward_button.bind("<Button-1>", stop_handler)
        self.backward_button.bind("<Button-1>", stop_handler)

        vcmd = hbox2.register(self.isfloat)

        self.view_step = tk.Entry(hbox2,
                                  width=4,
                                  validate="key",
                                  validatecommand=(vcmd, '%P'),
                                  justify=tk.CENTER)
        self.view_step_lbl = tk.Label(hbox2, text='Plot step [ms]')
        self.view_step.pack(side=tk.RIGHT, padx=10)
        self.view_step_lbl.pack(side=tk.RIGHT)

        axcolor = 'lightgoldenrodyellow'

        self.fig.subplots_adjust(left=.10,
                                 bottom=.20,
                                 right=.95,
                                 top=.95,
                                 hspace=.1,
                                 wspace=0)
        from numpy.lib import NumpyVersion
        kargs = {
            'facecolor': axcolor
        } if NumpyVersion(
            matplotlib.__version__) > NumpyVersion('2.0.0') else {
                'axisbg': axcolor
            }
        self.sl_ax_main = self.fig.add_axes([.1, .10, .8, .03], **kargs)
        self.main_slider = Slider(self.sl_ax_main,
                                  '',
                                  self.tbeg,
                                  self.tend,
                                  valinit=self.tbeg)

        sl_ax = self.fig.add_axes([.1, .03, .35, .03], **kargs)
        self.sl_eta = Slider(sl_ax, '', 0, 1, valinit=self.options['eta'])

        sl_ax2 = self.fig.add_axes([.55, .03, .35, .03], **kargs)
        self.sl_lam = Slider(sl_ax2, '', 0, 1, valinit=self.options['lam'])

        self.fig.text(.1, .075, 'Time smoothing -->:')
        self.fig.text(.55, .075, 'Radial smoothing -->:')

        createToolTip(self.forward_button, 'Go forward by one step')
        createToolTip(self.backward_button, 'Go backward by one step')
        createToolTip(self.play_button,
                      'Go step by step forward, pause by second press')
        createToolTip(
            self.view_step,
            'Plotting time/radial step, this option influences only the plotting, not fitting!'
        )

        createToolTip(calc_button, 'Calculate the 2d fit of the data')

        def update_eta(eta):
            self.options['eta'] = eta
            stop_handler()

        def update_lam(lam):
            stop_handler()
            self.options['lam'] = lam

        def update_slider(val):
            try:
                if self.plot_type.get() in [1, 2]:
                    self.plt_time = val
                if self.plot_type.get() in [0]:
                    self.plt_radius = val

                self.updateMainSlider()
                self.plot_step()
            except:
                print(
                    '!!!!!!!!!!!!!!!!!!!!!main_slider error!!!!!!!!!!!!!!!!!!!!!!!!!!!'
                )
                raise

        self.main_slider.on_changed(update_slider)

        self.cid1 = self.fig.canvas.mpl_connect('button_press_event',
                                                self.MouseInteraction)
        self.cid2 = self.fig.canvas.mpl_connect('scroll_event',
                                                self.WheelInteraction)
        self.cid3 = self.fig.canvas.mpl_connect('key_press_event', self.on_key)
        self.cid4 = self.fig.canvas.mpl_connect('key_release_event',
                                                self.off_key)
        self.cid5 = self.fig.canvas.mpl_connect(
            'button_press_event',
            lambda event: self.fig.canvas._tkcanvas.focus_set())
        self.cid6 = self.fig.canvas.mpl_connect('pick_event', self.legend_pick)

        self.sl_eta.on_changed(update_eta)
        self.sl_lam.on_changed(update_lam)

    def calculate(self):

        if self.shot is None:
            print('Set shot number first!')
            tkinter.messagebox.showerror('Missing shot number',
                                         'Shot number is not defined')

        if self.m2g is None:
            #print("No data to fit, let's try to load them first...")
            self.parent.init_data()

            if self.m2g is None:
                raise Exception('Loading of data failed!')

        if self.elms['signal'] != self.fit_options['elm_signal'].get():
            print('Load new ELM signal ' +
                  self.fit_options['elm_signal'].get())
            self.elms = self.parent.data_loader(
                'elms', {'elm_signal': self.fit_options['elm_signal']})
            self.edge_discontinuties = [
                self.ax_main.axvline(t, ls='-', lw=.2, c='k', visible=False)
                for t in self.elms['elm_beg']
            ]

        sys.stdout.write('  * Fitting  ... \t ')
        sys.stdout.flush()
        T = time.time()
        #make the fit of the data
        self.fit_frame.config(cursor="watch")
        self.fit_frame.update()

        self.saved_profiles = False

        sawteeth = eval(self.fit_options['sawteeth_times'].get()
                        ) if self.fit_options['sawteeth'].get() else []

        elms = self.elms['elm_beg'] if self.fit_options['elmsync'].get(
        ) else []
        elm_phase = (
            self.elms['tvec'],
            self.elms['data']) if self.fit_options['elmsync'].get() else None

        robust_fit = self.fit_options['robustfit'].get()
        zeroedge = self.fit_options['zeroedge'].get()

        pedestal_rho = float(self.fit_options['pedestal_rho'].get())

        #get functions for profile transformation
        transform = transformations[self.fit_options['transformation'].get()]

        even_fun = self.options['rho_coord'] not in ['Psi', 'Psi_N']

        if self.m2g is None:
            return

        if not self.options['fit_prepared']:
            #print 'not yet prepared! in calculate'
            self.m2g.PrepareCalculation(zero_edge=zeroedge,
                                        core_discontinuties=sawteeth,
                                        edge_discontinuties=elms,
                                        transformation=transform,
                                        pedestal_rho=pedestal_rho,
                                        robust_fit=robust_fit,
                                        elm_phase=elm_phase,
                                        even_fun=even_fun)
            self.m2g.corrected = False

            #remove points affected by elms
            if self.fit_options['elmrem'].get() and len(self.elms['tvec']) > 2:
                elm_phase = np.interp(self.plot_tvec, self.elms['tvec'],
                                      self.elms['data'])
                elm_ind = (elm_phase < 0.1) | (
                    (elm_phase > 0.95) &
                    (elm_phase < 1))  #remove also data shortly before an elm
                self.options['elmrem_ind'] = (self.plot_rho > .8) & elm_ind
                self.m2g.Yerr.mask |= self.options['elmrem_ind']
            elif np.any(self.options['elmrem_ind']):
                try:
                    self.m2g.Yerr.mask[self.options['elmrem_ind']] = False
                except:
                    print(
                        'np.shape(self.options[elmrem_inds]),self.m2g.Yerr.mask.shape ',
                        np.shape(self.options['elmrem_ind']),
                        self.m2g.Yerr.mask.shape, self.plot_rho.shape,
                        self.plot_tvec.shape)

                self.options['elmrem_ind'] = False

            #remove points in outer regions
            zeroed_outer = self.options['zeroed_outer']
            if self.fit_options['null_outer'].get():
                if np.any(zeroed_outer):
                    self.m2g.Yerr.mask[zeroed_outer] = False
                rho_lim = float(self.fit_options['outside_rho'].get())
                zeroed_outer = self.plot_rho > rho_lim
                self.m2g.Yerr.mask |= zeroed_outer
            elif np.any(zeroed_outer):
                self.m2g.Yerr.mask[zeroed_outer] = False
                zeroed_outer = False
            self.options['zeroed_outer'] = zeroed_outer
            self.options['fit_prepared'] = True

        lam = self.sl_lam.val
        eta = self.sl_eta.val
        self.m2g.Calculate(lam, eta)

        print('\t done in %.1fs' % (time.time() - T))

        self.options['fitted'] = True
        self.chi2_text.set_text('$\chi^2/doF$: %.2f' % self.m2g.chi2)

        self.plot_step()
        self.plot3d(update=True)

        self.fit_frame.config(cursor="")

    def Pause(self):
        self.stop = True
        self.play_button['image'] = self.playfig
        self.play_button['command'] = self.Play

    def Forward(self, mult=1):
        try:
            dt = self.fit_options['dt'].get()
        except:
            dt = ''

        if not self.isfloat(dt) or dt == '':
            return

        if self.ctrl: mult /= 5

        if self.plot_type.get() in [1, 2]:
            dt = float(dt) / 1e3
            self.plt_time += dt * mult
        if self.plot_type.get() in [0]:
            dr = float(self.fit_options['dr'].get())
            self.plt_radius += dr * mult

        self.updateMainSlider()
        self.plot_step()

    def Backward(self):
        self.Forward(-1)

    def Play(self):
        #animated plot
        self.stop = False
        self.play_button['image'] = self.pausefig
        self.play_button['command'] = self.Pause
        try:
            dt = float(self.fit_options['dt'].get()) / 1e3
        except:
            print('Invalid time step value!')
            dt = .01

        try:
            dr = float(self.fit_options['dr'].get())
        except:
            print('Invalid radial step value!')
            dr = .05

        while True:

            if self.plot_type.get() in [0]:
                self.plt_radius += dr

            if self.plot_type.get() in [1, 2]:
                self.plt_time += dt

            if not (self.m2g.t_min <= self.plt_time <= self.m2g.t_max):
                self.stop = True
            if not (self.options['rho_min'] <= self.plt_radius <=
                    self.options['rho_max']):
                self.stop = True

            self.fit_frame.after(1, self.plot_step)
            time.sleep(1e-3)
            try:
                self.canvasMPL.get_tk_widget().update()
            except:
                return

            self.updateMainSlider()

            if self.stop:
                break

        self.Pause()

    def PreparePloting(self):
        #set the limits and title of the plots
        if hasattr(self.parent, 'BRIEF'):
            self.ax_main.set_title(self.parent.BRIEF)

        minlim, maxlim = 0, 1
        if self.plot_type.get() in [0, 1] and self.options['data_loaded']:
            valid = ~self.m2g.Yerr.mask & (self.m2g.Y.data >
                                           self.m2g.Yerr.data)
            minlim, maxlim = mquantiles(self.m2g.Y[valid], [.001, .995])
        if self.plot_type.get() in [
                2
        ] and self.options['data_loaded'] and self.m2g.prepared:
            minlim, maxlim = mquantiles(self.m2g.K[self.m2g.g_r < .8],
                                        [.02, .98])
            maxlim *= 2
        elif self.plot_type.get() in [2]:
            minlim, maxlim = 0, 10  #just guess of the range

        minlim = min(0, minlim)
        if minlim != 0:
            minlim -= (maxlim - minlim) * .1
        maxlim += (maxlim - minlim) * .2
        self.ax_main.set_ylim(minlim, maxlim)

    def updateMainSlider(self):

        if self.plot_type.get() in [0]:
            self.plt_radius = min(
                max(self.plt_radius, self.options['rho_min']),
                self.options['rho_max'])
            val = self.plt_radius
        if self.plot_type.get() in [1, 2]:
            self.plt_time = min(max(self.plt_time, self.tbeg), self.tend)
            val = self.plt_time

        self.main_slider.val = val
        poly = self.main_slider.poly.get_xy()
        poly[2:4, 0] = val
        self.main_slider.poly.set_xy(poly)
        self.main_slider.valtext.set_text('%.3f' % val)

    def plot_step(self):
        #single step plotting routine
        if not self.options['data_loaded']:
            return

        t = self.plt_time
        r = self.plt_radius
        try:
            dt = float(self.fit_options['dt'].get()) / 1e3
        except:
            print('Invalid time step value!')
            dt = .01
        #dt = float(self.fit_options['dt'].get())/1e3
        dr = float(self.fit_options['dr'].get())
        plot_type = self.plot_type.get()
        kinprof = self.parent.kin_prof

        if plot_type in [0]:
            self.time_text.set_text('rho: %.3f' % r)
            self.select = abs(self.plot_rho - r) <= abs(dr) / 2
            X = self.plot_tvec

        if plot_type in [1, 2]:
            self.time_text.set_text('time: %.4fs' % t)
            self.select = abs(self.plot_tvec - t) <= abs(dt) / 2
            X = self.plot_rho

        for idiag, diag in enumerate(self.diags):
            dind = self.select & (self.ind_diag
                                  == idiag) & (self.m2g.Yerr.data > 0)

            if any(dind) and plot_type in [0, 1]:
                self.replot_plot[idiag].set_visible(True)
                self.plotline[idiag].set_visible(True)
                for c in self.caplines[idiag]:
                    c.set_visible(True)
                self.barlinecols[idiag][0].set_visible(True)
                x = X[dind]
                y = self.m2g.Y[dind]

                yerr = self.m2g.Yerr.data[dind]
                yerr[self.m2g.Yerr.mask[dind]] = np.infty

                ry = self.m2g.retro_f[dind]
                self.replot_plot[idiag].set_data(x, ry)

                # Replot the data first
                self.plotline[idiag].set_data(x, y)

                # Find the ending points of the errorbars
                error_positions = (x, y - yerr), (x, y + yerr)

                # Update the caplines
                for j, pos in enumerate(error_positions):
                    self.caplines[idiag][j].set_data(pos)

                #Update the error bars
                self.barlinecols[idiag][0].set_segments(
                    list(zip(list(zip(x, y - yerr)), list(zip(x, y + yerr)))))
            else:
                self.replot_plot[idiag].set_visible(False)
                self.plotline[idiag].set_visible(False)
                for c in self.caplines[idiag]:
                    c.set_visible(False)
                self.barlinecols[idiag][0].set_visible(False)

            #plot fit of teh data with uncertainty
            if self.options['fitted'] and hasattr(self.m2g, 'g_t'):
                if plot_type == 0:  #time slice
                    y, x = self.m2g.g_t[:, 0], self.m2g.g_r[0]
                    p = r
                    profiles = self.m2g.g.T, self.m2g.g_d.T, self.m2g.g_u.T

                if plot_type == 1:  #radial slice
                    profiles = self.m2g.g, self.m2g.g_d, self.m2g.g_u
                    x, y = self.m2g.g_t[:, 0], self.m2g.g_r[0]
                    p = t

                if plot_type == 2:  #radial slice of the gradient/rho
                    profiles = self.m2g.K, self.m2g.Kerr_d, self.m2g.Kerr_u
                    x, y = self.m2g.g_t[:, 0], self.m2g.g_r[0]
                    p = t

                prof = []
                for d in profiles:
                    if self.m2g.g_t.shape[0] == 1:
                        prof.append(d[0])
                    else:
                        prof.append(
                            interp1d(x,
                                     d,
                                     axis=0,
                                     copy=False,
                                     assume_sorted=True)(np.clip(
                                         p, x[0], x[-1])))

                self.fit_plot.set_data(y, prof[0])
                self.fit_confidence = update_fill_between(
                    self.fit_confidence, y, prof[1], prof[2], -np.infty,
                    np.infty)

        #show discontinuties in time
        for d in self.core_discontinuties:
            d.set_visible(r < .3 and plot_type == 0)
        for d in self.edge_discontinuties:
            d.set_visible(r > .7 and plot_type == 0)

        #MHD modes
        if self.mhd_modes is not None:
            for name, rho_loc in self.mhd_modes['modes'].items():
                loc = np.nan
                if plot_type in [1, 2] and kinprof in ['omega', 'Ti']:
                    it = np.argmin(abs(self.mhd_modes['tvec'] - t))
                    loc = rho_loc[it]

                if np.isfinite(loc):
                    self.mhd_locations[name].set_data([loc, loc], [0, 1])
                    self.mhd_labels[name].set_x(loc)
                    self.mhd_locations[name].set_visible(True)
                    self.mhd_labels[name].set_visible(True)
                else:
                    self.mhd_locations[name].set_visible(False)
                    self.mhd_labels[name].set_visible(False)

            #self.mhd_locations = [self.ax_main.axvline(np.nan, ls='-',lw=.5,c='k',visible=False) for mode in self.mhd_modes]
            #self.mhd_labels = [self.ax_main.text(0, np.nan,  mode) for mode in self.mhd_modes]

            #for txt in

            #set_x
            #axvline1.set_data([event.xdata, event.xdata], [0, 1])
            #axvline2.set_data([event.xdata, event.xdata], [0, 1])

        #show also zipfit profiles
        #BUG how to avoid access of parent class?
        show_splines = self.parent.show_splines.get() == 1

        if show_splines and kinprof in self.parent.splines:
            splines = self.parent.splines[kinprof]

            y = splines['time'].values
            x = splines['rho'].values
            z = splines[kinprof].values
            ze = z * 0

            if kinprof + '_err' in splines:
                ze = splines[kinprof + '_err'].values

            y0 = t

            if plot_type == 0:  #temporal profiles
                z, ze, x = z.T, ze.T, x.T
                y, x = x, y
                y0 = r

            if np.ndim(y) == 2:
                y = y.mean(1)

            i = np.argmin(np.abs(y - y0))

            if np.ndim(x) == 2:
                x = x[i]

            z = z[i]
            ze = ze[i]

            if plot_type in [2]:
                #BUG!!!!
                a0 = 0.6
                R0 = 1.7
                z_ = (z[1:] + z[:-1]) / 2
                x_ = (x[1:] + x[:-1]) / 2
                z = -(np.diff(z) / np.diff(x * a0) * R0 /
                      x_)[z_ != 0] / z_[z_ != 0]
                ze = 0
                x = x_[z_ != 0]

            self.spline_mean.set_data(x, z)
            self.spline_min.set_data(x, z - ze)
            self.spline_max.set_data(x, z + ze)

        self.spline_mean.set_visible(show_splines)
        self.spline_min.set_visible(show_splines)
        self.spline_max.set_visible(show_splines)

        self.fig.canvas.draw_idle()

    def plot3d(self, update=False):

        if not self.options['fitted']:
            return

        if plt.fignum_exists('3D plot'):
            try:
                ax = self.fig_3d.gca()
                ax.collections.remove(self.wframe)
            except:
                return
        elif not update:
            self.fig_3d = plt.figure('3D plot')
            ax = p3.Axes3D(self.fig_3d)
            ax.set_xlabel(self.xlab, fontsize=self.fsize3d)
            ax.set_ylabel('Time [s]', fontsize=self.fsize3d)
        else:
            return

        ax.set_zlabel(self.ylab, fontsize=self.fsize3d)
        self.wframe = ax.plot_wireframe(self.m2g.g_r,
                                        self.m2g.g_t,
                                        self.m2g.g,
                                        linewidth=.3,
                                        rstride=self.rstride,
                                        cstride=self.cstride)

        self.fig_3d.show()

    def MouseInteraction(self, event):
        if self.picked:  #legend_pick was called first
            self.picked = False
            return

        if event.button == 1 and self.ctrl:
            self.delete_channel(event)
        elif event.button == 1:
            self.delete_point(event)
        elif event.button == 2:
            self.calculate()
        elif event.button == 3 and self.ctrl:
            self.undelete_channel(event)
        elif event.button == 3:
            self.undelete_point(event)

    def legend_pick(self, event):

        if not event.mouseevent.dblclick:
            return

        if event.mouseevent.button == 1:
            undelete = False

        elif event.mouseevent.button == 3:
            undelete = True
        else:
            return

        if not event.artist in self.leg_diag_ind:
            return

        i_diag = self.leg_diag_ind[event.artist]

        ind = np.in1d(self.ind_diag, i_diag)

        self.m2g.Yerr.mask[ind] = not undelete

        self.plot_step()
        self.m2g.corrected = False  #force the upgrade
        self.picked = True

    def WheelInteraction(self, event):
        self.Forward(int(event.step))

    def delete_channel(self, event):
        self.delete_point(event, 'channel')

    def undelete_channel(self, event):
        self.delete_point(event, 'channel', True)

    def undelete_point(self, event):
        self.delete_point(event, 'point', True)

    def delete_point(self, event, what='point', undelete=False):
        if not event.dblclick:
            return

        self.delete_points(event,
                           event.xdata,
                           event.ydata,
                           what=what,
                           undelete=undelete)

    def delete_points(self, event, xc, yc, what='point', undelete=False):
        #delete point closest to xc,yc or in the rectangle decribed by xc,yc
        # what - point, channel, diagnostic

        if self.ax_main != event.inaxes or not self.options['data_loaded']:
            return
        if undelete:
            affected = self.select & self.m2g.Yerr.mask
        else:
            affected = self.select & ~self.m2g.Yerr.mask

        if not any(affected):
            return

        if self.plot_type.get() == 1:
            x = self.plot_rho[affected]
        elif self.plot_type.get() == 0:
            x = self.plot_tvec[affected]
        else:
            return

        y = self.m2g.Y[affected]
        if np.size(xc) == 1:
            #get range within the plot
            sx = np.ptp(self.ax_main.get_xlim())
            sy = np.ptp(self.ax_main.get_ylim())

            dist = np.hypot((x - xc) / sx, (y - yc) / sy)
            selected = np.argmin(dist)
        else:
            selected = (x >= min(xc)) & (x <= max(xc)) & (y >= min(yc)) & (
                y <= max(yc))
            if not any(selected):
                return

        i_ind = np.where(affected)[0]
        ind = i_ind[selected]

        action = 'recovered ' if undelete else 'deleted'

        if what == 'channel':
            ch = np.unique(self.channel[ind])
            ind = np.in1d(self.channel, ch)
            print('Channel %s was ' % ch + action)

        elif what == 'diagnostic':
            i_diag = self.ind_diag[ind]
            ind = np.in1d(self.ind_diag, i_diag)
            print('diagnostic %s was ' % i_diag + action)

        elif what == 'point':
            pass
        else:
            print('Removing of "%s" is not supported' % (str(what)))

        self.m2g.Yerr.mask[ind] = not undelete

        self.plot_step()
        self.m2g.corrected = False  #force the upgrade

    def on_key(self, event):
        if 'control' == event.key and hasattr(self, 'RS_delete'):
            self.ctrl = True
            if self.RS_delete.eventpress is not None:
                self.RS_delete.eventpress.key = None
            if self.RS_undelete.eventpress is not None:
                self.RS_undelete.eventpress.key = None

        if 'shift' == event.key:
            self.shift = True

        if 'left' == event.key:
            self.Backward()

        if 'right' == event.key:
            self.Forward()

        if 'g' == event.key:
            self.grid = not self.grid
            self.ax_main.grid(self.grid)
            self.fig.canvas.draw_idle()

        if 'l' == event.key:

            self.logy = not self.logy
            if self.logy:
                if self.ax_main.get_ylim()[0] <= 0:
                    self.ax_main.set_ylim(1, None)
                self.ax_main.set_yscale('log')
            else:
                self.ax_main.set_yscale('linear')
            self.fig.canvas.draw_idle()

        if ' ' == event.key:
            if self.stop:
                self.Play()
            else:
                self.Pause()

    def off_key(self, event):
        if event.key in ('ctrl+control', 'control'):
            self.ctrl = False
        if 'shift' == event.key:
            self.shift = False
Esempio n. 54
0
class mySlider:
    def __init__(self,
                 num_of_sliders=1,
                 slider_number=1,
                 maxV=1,
                 minV=-1,
                 intV=0,
                 gain=1,
                 name='Slider'):
        # num_of_sliders - The number of Sliders that you will use
        # slider_number - This number starts at 1 and its max value
        #                 should be num_of_sliders . This variable
        #                 determines the location of the Slider in
        #                 the axes; 1 corresponds to the top Slider
        #                 in the axes and largest number corresponds
        #                 to the bottom of the axes. Each Slider
        #                 object needs a unique slider_number.

        self.data = 0  # Current value of Slider
        self.name = name  # Name of Slider
        self.maxValue = maxV  # Max value of the Slider
        self.minValue = minV  # Min value of the Slider
        self.initValue = intV  # Initial value of Slider
        self.gain = gain  # The gain of the Slider can be used for
        # conversion purposes. EX, If you want the
        # Slider to be in terms of degrees but the
        # value passed in radians. The max and min
        # values will in terms of degrees and the
        # gain would be pi/180 to convert
        # the Slider's value from degrees to radians.
        self.Slider_length = 0.5  # This is the length of the Slider in terms
        # of the percentage of the figure's length
        self.Slider_width = 0.03  # This is the width of the Slider in terms
        # of the percentage of the figure's width

        # Sets the position and color of the Slider

        # The horizontal position of the Slider in the figure.
        hpos = 0.8 - 0.6 / (num_of_sliders + 1) * slider_number

        # Specify a subsection of the current axes where the slider will go.
        self.axSlider = plt.axes([
            0.5 - self.Slider_length / 2, hpos, self.Slider_length,
            self.Slider_width
        ],
                                 axisbg='orange')

        # Instantiate a slider, and create a handle to it
        self.SliderHandle = Slider(self.axSlider,
                                   self.name,
                                   self.minValue,
                                   self.maxValue,
                                   valinit=self.initValue)
        self.data = self.initValue

        # When a change occurs on the slider, the function self.update
        # will be called.
        self.SliderHandle.on_changed(self.update)

    # Updates the value of the Slider when the Slider is changed
    def update(self, val):
        self.data = self.SliderHandle.val

    # Returns the current value of the Slider(s)
    def getValue(self):
        return self.data * self.gain
Esempio n. 55
0
plt.grid()

ax.set_title(
    'interactive peak static overpressure and dynamic pressure calculator')

ax.set_xlabel('distance ($m$)')
ax.set_ylabel('peak static overpressure / dynamic pressure ($kg/cm^2$)')
ax.legend()

axyield = plt.axes([0.25, 0.05, 0.65, 0.03])
axheight = plt.axes([0.25, 0.01, 0.65, 0.03])

syield = Slider(axyield, 'Yield ($kT$):', 1.0, 1000.0, valinit=y0)
sheight = Slider(axheight, 'Burst height ($m$):', 0.0, 5000.0, valinit=h0)


def update(val):
    bomb_yield = syield.val
    burst_height = sheight.val
    l1.set_ydata(static_overpressure(bomb_yield, t, burst_height))
    l2.set_ydata(dynamic_pressure(bomb_yield, t, burst_height))
    fig.canvas.draw_idle()


syield.on_changed(update)
sheight.on_changed(update)

cursor = Cursor(ax, useblit=False, color='red', linewidth=2)

plt.show()
Esempio n. 56
0
def view_patches_bar(Yr, A, C, b, f, d1, d2, YrA=None, img=None):
    """view spatial and temporal components interactively

     Parameters:
     -----------
     Yr:    np.ndarray
            movie in format pixels (d) x frames (T)

     A:     sparse matrix
                matrix of spatial components (d x K)

     C:     np.ndarray
                matrix of temporal components (K x T)

     b:     np.ndarray
                spatial background (vector of length d)

     f:     np.ndarray
                temporal background (vector of length T)

     d1,d2: np.ndarray
                frame dimensions

     YrA:   np.ndarray
                 ROI filtered residual as it is given from update_temporal_components
                 If not given, then it is computed (K x T)

     img:   np.ndarray
                background image for contour plotting. Default is the image of all spatial components (d1 x d2)

    """

    pl.ion()
    if 'csc_matrix' not in str(type(A)):
        A = csc_matrix(A)
    if 'array' not in str(type(b)):
        b = b.toarray()

    nr, T = C.shape
    nb = f.shape[0]
    nA2 = np.sqrt(np.array(A.power(2).sum(axis=0))).squeeze()

    if YrA is None:
        Y_r = spdiags(old_div(1, nA2), 0, nr, nr) * (A.T.dot(Yr) -
                                                     (A.T.dot(b)).dot(f) -
                                                     (A.dot(A)).dot(C)) + C
    else:
        Y_r = YrA + C

    if img is None:
        img = np.reshape(np.array(A.mean(axis=1)), (d1, d2), order='F')

    fig = pl.figure(figsize=(10, 10))

    axcomp = pl.axes([0.05, 0.05, 0.9, 0.03])

    ax1 = pl.axes([0.05, 0.55, 0.4, 0.4])
    ax3 = pl.axes([0.55, 0.55, 0.4, 0.4])
    ax2 = pl.axes([0.05, 0.1, 0.9, 0.4])

    s_comp = Slider(axcomp, 'Component', 0, nr + nb - 1, valinit=0)
    vmax = np.percentile(img, 98)

    def update(val):
        i = np.int(np.round(s_comp.val))
        print(('Component:' + str(i)))

        if i < nr:

            ax1.cla()
            imgtmp = np.reshape(A[:, i].toarray(), (d1, d2), order='F')
            ax1.imshow(imgtmp, interpolation='None', cmap=pl.cm.gray)
            ax1.set_title('Spatial component ' + str(i + 1))
            ax1.axis('off')

            ax2.cla()
            ax2.plot(np.arange(T), Y_r[i], 'c', linewidth=3)
            ax2.plot(np.arange(T), C[i], 'r', linewidth=2)
            ax2.set_title('Temporal component ' + str(i + 1))
            ax2.legend(labels=['Filtered raw data', 'Inferred trace'])

            ax3.cla()
            ax3.imshow(img, interpolation='None', cmap=pl.cm.gray, vmax=vmax)
            imgtmp2 = imgtmp.copy()
            imgtmp2[imgtmp2 == 0] = np.nan
            ax3.imshow(imgtmp2,
                       interpolation='None',
                       alpha=0.5,
                       cmap=pl.cm.hot)
            ax3.axis('off')
        else:
            ax1.cla()
            bkgrnd = np.reshape(b[:, i - nr], (d1, d2), order='F')
            ax1.imshow(bkgrnd, interpolation='None')
            ax1.set_title('Spatial background ' + str(i + 1 - nr))
            ax1.axis('off')

            ax2.cla()
            ax2.plot(np.arange(T), np.squeeze(np.array(f[i - nr, :])))
            ax2.set_title('Temporal background ' + str(i + 1 - nr))

    def arrow_key_image_control(event):

        if event.key == 'left':
            new_val = np.round(s_comp.val - 1)
            if new_val < 0:
                new_val = 0
            s_comp.set_val(new_val)

        elif event.key == 'right':
            new_val = np.round(s_comp.val + 1)
            if new_val > nr + nb:
                new_val = nr + nb
            s_comp.set_val(new_val)
        else:
            pass

    s_comp.on_changed(update)
    s_comp.set_val(0)
    fig.canvas.mpl_connect('key_release_event', arrow_key_image_control)
    pl.show()
Esempio n. 57
0
from scipy import misc
import numpy
import rof

im = misc.lena()
#im = im + 20 * numpy.random.standard_normal(im.shape)

U, _ = rof.denoise(im, im, tv_weight=30, tolerance=0.01)

gray()
subplot(1, 2, 1)
imshow(im)

subplot(1, 2, 2)
imshow(U)

axrof = axes([0.15, 0.15, 0.65, 0.03])
srof = Slider(axrof, 'rof', 0.0, 255.0, valinit=30)


def update(val):
    U, _ = rof.denoise(im, im, tv_weight=srof.val, tolerance=0.01)
    subplot(1, 2, 2)
    imshow(U)
    draw()


srof.on_changed(update)

show()
            for i in range(num_layers):
                subplt2 = plt.subplot2grid((3, num_layers), (2, i))
                scale_min = np.floor(np.min(W_core[i]))
                scale_max = np.ceil(np.max(W_core[i]))
                subplt2.matshow(W_core[i],
                                cmap=matplotlib.cm.binary,
                                vmin=scale_min,
                                vmax=scale_max)
                subplt2.set_xticks(np.array([]))
                subplt2.set_yticks(np.array([]))
                subplt2.set_xlabel("({0:.3f}, {1:.3f})".format(
                    scale_min, scale_max),
                                   fontsize=10)
            fig.canvas.draw_idle()

        s0.on_changed(update)
        s1.on_changed(update)
        s2.on_changed(update)
        s3.on_changed(update)

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

        def reset(event):
            s0.reset()
            s1.reset()
            s2.reset()
            s3.reset()

        button.on_clicked(reset)
Esempio n. 59
0
def update(val):
    alpha = salpha.val
    sol=odeint(func, x0, t, args=(alpha, ))
    x=sol[:,0]*np.cos(sol[:,1])
    y=sol[:,0]*np.sin(sol[:,1])
    l.set_xdata(x)
    l.set_ydata(y)
    fig.canvas.draw()
def reset(event):
    salpha.reset()

fig, ax=plt.subplots(figsize=(15, 10))
plt.plot([0], [0], 'x', color='black', ms=3)
l,=plt.plot(x,y,color='b', linewidth=0.8)
plt.xlim(-10, 10)
plt.ylim(-5, 5)
plt.axis('off')

plt.subplots_adjust(left=0.25, bottom=0.25)

axalpha = plt.axes([0.25, 0.1, 0.65, 0.03])
salpha = Slider(axalpha, '$\\alpha$', 0.8, 1.2, valinit=alpha0)
salpha.on_changed(update)

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

plt.show()
Esempio n. 60
0
class PulseSequence:
    """
    Object which hold information about the pulse sequence used to acquire the dataset
    (in case of pulsed experiments). This object is constructed from the pulse channel
    tables "Psd1", "Psd2", etc, in the descriptor layer.
    """

    def __init__(self, dset: "XeprData") -> None:
        self._dset = dset
        self._pulse_channels = []
        self._fig = None

        ft_epr = self._dset.dsl.groups.get("ftEpr")

        self._is_pulsed = ft_epr is not None

        if ft_epr:
            for name, par in ft_epr.pars.items():
                if name.startswith("Psd"):
                    self._pulse_channels.append(PulseChannel(par))

        self._pulse_channels.sort(key=lambda x: x.number)

    @property
    def pulse_channels(self) -> List[PulseChannel]:
        """Returns a list of pulse channels present in the instrument."""
        return self._pulse_channels

    def plot(self) -> None:
        """
        Plots the pulse sequence used to acquire the data.

        :raises: :class:`RuntimeError` if the experiment is not pulsed.
        :raises: :class:`ImportError` if matplotlib is not installed.
        """

        if len(self._pulse_channels) == 0:
            raise RuntimeError("No pulse channels to plot")

        try:
            import matplotlib.pyplot as plt
            from matplotlib.widgets import Slider
        except ImportError:
            raise ImportError("Install matplotlib to support plotting.")

        # set up axes and appearance
        self._fig = plt.figure()

        self._ax = self._fig.add_axes([0.1, 0.1, 0.8, 0.8])
        self._ax.set_xlabel("Time [ns]")

        self._ax.get_yaxis().set_visible(False)

        self._ax.spines["top"].set_visible(False)
        self._ax.spines["right"].set_visible(False)
        self._ax.spines["bottom"].set_visible(True)
        self._ax.spines["left"].set_visible(False)

        # determine number of time steps with potentially different pulse sequences

        if self._dset.pars["XAxisQuant"].value == "Time":
            n_steps = self._dset.pars["XSpecRes"].value
        else:
            n_steps = 1

        # determine the maximum total pulse sequence duration

        xlim = 0

        for channel in self.pulse_channels:
            for pulse in channel.pulses:

                xlim = max(
                    xlim,
                    pulse.position
                    + pulse.length
                    + n_steps * (pulse.position_increment + pulse.length_increment),
                )

        self._plot_xlim = xlim * 1.1

        # plot the first sequence

        self._plot_step(0)

        # create slider to show subsequent sequences

        if n_steps > 1:
            self._ax.set_position([0.1, 0.2, 0.8, 0.7])
            ax_slider = self._fig.add_axes([0.1, 0.05, 0.8, 0.05])
            self._plot_slider = Slider(
                ax_slider, "Step", 0, n_steps, valinit=0, valstep=1
            )
            self._plot_slider.on_changed(self._plot_step)

        self._fig.show()

    def _plot_step(self, slider_val):

        self._ax.clear()

        for channel in self.pulse_channels:

            # plot only channels 5 to 13:
            # Acquisition Trigger and MW pulses
            if channel.number in range(5, 14):

                channel_x_data = [0]
                channel_y_data = [0]

                for pulse in channel.pulses:
                    x_start = pulse.position + slider_val * pulse.position_increment
                    x_length = pulse.length + slider_val * pulse.length_increment
                    x_stop = x_start + x_length

                    channel_x_data.extend([x_start, x_start])
                    channel_y_data.extend([0, 1])
                    channel_x_data.extend([x_stop, x_stop])
                    channel_y_data.extend([1, 0])

                self._ax.fill(
                    channel_x_data,
                    channel_y_data,
                    alpha=0.8,
                    label=f"{channel.name}: {channel.description}",
                )

        self._ax.set_xlim(0, self._plot_xlim)
        self._ax.set_ylim(0, 3)
        self._ax.legend(loc="best")