Ejemplo n.º 1
0
 def __init__(self, *args, **kwargs):
     """Identical to Slider.__init__, except for the "increment" kwarg.
     "increment" specifies the step size that the slider will be discritized
     to."""
     self.inc = kwargs.pop('increment', 0.5)
     self.discrete_val = round(kwargs['valinit'] / self.inc) * self.inc
     Slider.__init__(self, *args, **kwargs)
Ejemplo n.º 2
0
    def loadFile(self, filename):
        self.filename = filename
        sms_openSF(filename, self.sh)
        sr = self.sh.iSamplingRate
        print "maxbin before: ", self.maxFreq * (self.sizeSpec*2) / sr
        self.maxBin = sms_power2(self.maxFreq * (self.sizeSpec*2) / sr)
        self.peakParams.iSamplingRate = sr

        self.maxFreq = self.maxBin * sr / (self.sizeSpec*2)
        self.peakParams.fHighestFreq = self.maxFreq
        print "maxbin after: ", self.maxBin
        print "maxfreq after: ", self.maxFreq
        self.specEnv = zeros(self.maxBin)
        # set up time slider
        nSeconds = self.sh.nSamples / float(sr) 
        axcolor = 'lightgoldenrodyellow'

        self.axtime = axes([0.2, 0.15, 0.65, 0.03], axisbg=axcolor)
        self.axorder = axes([0.2, 0.10, 0.65, 0.03], axisbg=axcolor)
        self.axlambda = axes([0.2, 0.05, 0.65, 0.03], axisbg=axcolor)

        self.stime = Slider(self.axtime, 'Time (seconds)', 0., nSeconds, valinit=0.05)
        self.stime.on_changed(self.updateFrame)

        self.sorder = Slider(self.axorder, 'Order (p)', 0., 100, valinit=20,  valfmt='%d')
        self.sorder.on_changed(self.updateOrder)

        self.slambda = Slider(self.axlambda, 'lambda (power)', -10., -2, valinit=-5)
        self.slambda.on_changed(self.updateLambda)
Ejemplo n.º 3
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()
Ejemplo n.º 4
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()
Ejemplo n.º 5
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.'
Ejemplo n.º 6
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
Ejemplo n.º 7
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()
Ejemplo n.º 8
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)
Ejemplo 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)
Ejemplo n.º 10
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()
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
Ejemplo n.º 12
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))
Ejemplo 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
Ejemplo n.º 14
0
  def __init__(self, image, low, high):
    self.image_name = image
    self.low = low
    self.high = high
    self.filter = None
    self.output = None
    self.filter_type = None
    self.padRows = None
    self.padCols = None

    original_input = cv2.imread(image,0)
    rows, cols = original_input.shape
    if(rows < cols):
      original_input = cv2.transpose(original_input)
      self.transposed = True
    else:
      self.transposed = False
      
    rows, cols = original_input.shape
    optimalRows = cv2.getOptimalDFTSize(rows)
    optimalCols = cv2.getOptimalDFTSize(cols)
    self.padRows = optimalRows - rows
    self.padCols = optimalCols - cols
    self.input = np.zeros((optimalRows,optimalCols))
    self.input[:rows,:cols] = original_input
    
    self.dftshift = get_dft_shift(self.input)

    plt.subplots_adjust(left=0, bottom=0.05, right=1, top=1, wspace=0, hspace=0)

    plt.subplot(131)
    plt.axis('off')
    plt.title('original image')
    plt.imshow(self.input, cmap = 'gray',interpolation='nearest')

    
    self.axslow = plt.axes([0.05, 0.01, 0.5, 0.02])
    self.slow = Slider(self.axslow, 'low', 0.01, 1, valinit=self.low)
    self.slow.on_changed(self.updateLow)

    self.axhigh = plt.axes([0.05, 0.03, 0.5, 0.02])
    self.shigh = Slider(self.axhigh, 'high', 0.01, 1, valinit=self.high)
    self.shigh.on_changed(self.updateHigh)

    self.slow.slidermax=self.shigh
    self.shigh.slidermin=self.slow


    self.axfilter = plt.axes([0.62, 0.01, 0.15, 0.04])
    self.rfilter = RadioButtons(self.axfilter, ('Gaussian Filter', 'Ideal Filter'))
    self.rfilter.on_clicked(self.updateFilterType)
    self.filter_type = self.rfilter.value_selected
    
    self.axprocess = plt.axes([0.8, 0.01, 0.08, 0.04])
    self.bprocess = Button(self.axprocess, 'Process')
    self.bprocess.on_clicked(self.process)

    self.axsave = plt.axes([0.88, 0.01, 0.08, 0.04])
    self.bsave = Button(self.axsave, 'Save')
    self.bsave.on_clicked(self.save)
Ejemplo 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)
Ejemplo n.º 16
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()
Ejemplo n.º 17
0
    def _create_controls(self):
        self._freq_ax = plt.axes([0.2, 0.19, 0.2, 0.03])
        self._freq_slider = Slider(self._freq_ax,
                                   'Frequency',
                                   0,
                                   self.samplerate / 2.0,
                                   valinit = self.frequency)
        self._freq_slider.on_changed(self.set_signal_frequency)

        self._ampl_ax = plt.axes([0.2, 0.1, 0.2, 0.03])
        self._ampl_slider = Slider(self._ampl_ax,
                                   'Amplitude',
                                   -100,
                                   0,
                                   valinit = dcv.lin2db(self.amplitude))
        self._ampl_slider.on_changed(self.set_signal_amplitude)

        self._signaltype_ax = plt.axes([0.5, 0.05, 0.15, 0.20])
        self._signaltype_radio = RadioButtons(self._signaltype_ax,
                                              ('Sine', 'Square', 'Sawtooth',
                                               'Triangle', 'Noise', 'Constant'))
        self._signaltype_radio.on_clicked(self.set_signal_type)

        self._windowtype_ax = plt.axes([0.7, 0.05, 0.15, 0.20])
        self._windowtype_radio = RadioButtons(self._windowtype_ax,
                                              ('Flat', 'Hanning', 'Hamming', 'Blackman'))
        self._windowtype_radio.on_clicked(self.set_window_type)
Ejemplo n.º 18
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()
Ejemplo n.º 19
0
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()
Ejemplo n.º 20
0
    def plot_fits(self, X, X_pred, plot_preds = True):
        self.plot_preds = plot_preds
        import matplotlib
        self.colors = ['r', 'g', 'b']
        more_colors = matplotlib.colors.cnames.keys()
        shuffle(more_colors)
        # print self.colors
        # print more_colors
        self.colors.extend(more_colors)

        self.trial_groups = self.split_trial_groups()
        self.X = X
        self.X_pred = X_pred

        # set-up the plot window
        self.fig, self.ax = plt.subplots(figsize=(12,8))
        plt.subplots_adjust(bottom=0.25)

        # make sliders
        axcolor = 'lightgoldenrodyellow'
        self.axtrial = plt.axes([0.25, 0.05, 0.65, 0.03], axisbg=axcolor)
        self.axspot = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
        self.axclass = plt.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor)

        # need to update to find the number of classes, trial_groups
        self.strial = Slider(self.axtrial, 'Trial', 0, self.n_trial_groups, valinit=0)
        self.sspot = Slider(self.axspot, 'Spot', 1, len(self.column_headers), valinit=1)
        self.sclass = Slider(self.axclass, 'Class', 0, len(self.groups), valinit=0)

        self.strial.on_changed(self.update_fits)
        self.sspot.on_changed(self.update_fits)
        self.sclass.on_changed(self.update_fits)

        self.plot_fit(spot=1, group=0, trial=0, averages=self.averages)
        plt.show()
Ejemplo n.º 21
0
 def __init__(self, *args, **kwargs):
     """Identical to Slider.__init__, except for the "increment" kwarg.
     "increment" specifies the step size that the slider will be discritized
     to."""
     self.inc = kwargs.pop("increment", 1.0)
     Slider.__init__(self, *args, **kwargs)
     self.dval = int(self.val + 0.5)
Ejemplo n.º 22
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
Ejemplo n.º 23
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()
Ejemplo n.º 24
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)
Ejemplo n.º 25
0
 def initUI(self):
     self.fig, self.ax = plt.subplots()
     self.fig.canvas.set_window_title('Numerik DGL 2 - Schattenprojektion')
     self.fig.suptitle('Vorwaertsproblem')
     plt.subplots_adjust(bottom=0.3)
     plt.axis([0, 200, -100, 100])
     plt.axis('equal')
     axColor = 'lightgoldenrodyellow'
     
     # Slider - Phi
     axPhi = plt.axes([0.18, 0.2, 0.65, 0.03], axisbg=axColor)                
     self.sliderPhi = Slider(axPhi, 'Phi', 0, 360, valinit=self.phi, valfmt='%1d')
     self.sliderPhi.on_changed(self.onUpdate)
     # Slider - Delta Phi
     axDeltaPhi = plt.axes([0.18, 0.15, 0.65, 0.03], axisbg=axColor)        
     self.sliderDeltaPhi = Slider(axDeltaPhi, 'Delta Phi', 5, 360, valinit=self.delta_phi, valfmt='%1d')        
     self.sliderDeltaPhi.on_changed(self.onUpdate)
     # Slider - Psi
     axPsi = plt.axes([0.18, 0.1, 0.65, 0.03], axisbg=axColor)        
     self.sliderPsi = Slider(axPsi, 'Psi', 0, 180, valinit=self.psi, valfmt='%1d')        
     self.sliderPsi.on_changed(self.onUpdate)
     # Button - Previous
     axPrev = plt.axes([0.18, 0.03, 0.1, 0.05])
     self.buttonPrev = Button(axPrev, 'Previous')
     self.buttonPrev.on_clicked(self.onPrevious)
     # Button - Next
     axNext = plt.axes([0.29, 0.03, 0.1, 0.05])
     self.buttonNext = Button(axNext, 'Next')
     self.buttonNext.on_clicked(self.onNext)        
     # Button - Reset        
     axReset = plt.axes([0.73, 0.03, 0.1, 0.05])
     self.buttonReset = Button(axReset, 'Reset')
     self.buttonReset.on_clicked(self.onReset)
     
     self.onDraw()
Ejemplo n.º 26
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()
Ejemplo n.º 27
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    
Ejemplo n.º 28
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)
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()
Ejemplo n.º 30
0
  def __init__(self, image, dragging=True, **kwargs):

    # init PointBrowser
    super(FindCenters,self).__init__(image,[[None,None]],**kwargs);
    self.axis.set_title('FitHexagonCenters: %s' % self.imginfo['desc']);
    self.fig.subplots_adjust(bottom=0.2);  # space for sliders

    # add slider for neighborhood size
    self.nbhd_size = 5;        # neighborhood size
    axNbhd = self.fig.add_axes([0.2, 0.05, 0.1, 0.04]);
    self.sNbhd = Slider(axNbhd,'neighbors ',2,20,valinit=self.nbhd_size,\
                                valfmt=' (%d)',dragging=dragging);
    self.sNbhd.on_changed(self.ChangeNeighborhood);

    # add slider for number of points
    self.num_points = 1e6;     # number of local maxima to find
    axNum  = self.fig.add_axes([0.45, 0.05, 0.3, 0.04]);
    self.sNum = Slider(axNum, 'points ',0,100,valinit=self.num_points,\
                               valfmt=' (%d)',dragging=dragging);
    self.sNum.on_changed(self.ChangeMaxPoints);

    # add buttons
    axRefine = self.fig.add_axes([0.85, 0.7, 0.1, 0.04]);
    self.bRefine = Button(axRefine,'Refine');
    self.bRefine.on_clicked(self.RefineCenters);

    # initial calculation of local maximas
    self.ChangeNeighborhood(self.nbhd_size);
Ejemplo n.º 31
0
ax.set_title(filename + "; total frames: " + str(num_frames))

ax2 = fig.add_subplot(111)
ax2.autoscale(True)

ax3 = fig.add_subplot(111)
ax3.autoscale(True)

# plot first data set
frame = 0
ln, = ax.plot(xdata[frame:frame_size], ydata[frame:frame_size])
ln2, = ax2.plot(xdata[frame:frame_size], samples2[frame:frame_size])
ln3, = ax3.plot(xdata[frame:frame_size], samples3[frame:frame_size], 'ro')

axframe = plt.axes([0.25, 0.1, 0.65, 0.03])
sframe = Slider(axframe, 'Frame', 0, num_frames, valinit=0, valfmt='%d')


def update(val):
    frame = numpy.floor(sframe.val)
    start, end = int(frame * frame_size), int((frame + 1) * frame_size)
    #print to_string(samples2[start:end])
    print "FRAME", start, end
    ln.set_xdata(xdata[start:end])
    ln.set_ydata(ydata[start:end])
    ln2.set_xdata(xdata[start:end])
    ln2.set_ydata(samples2[start:end])
    ln3.set_xdata(xdata[start:end])
    ln3.set_ydata(samples3[start:end])
    ax.relim()
    ax.autoscale_view()
Ejemplo n.º 32
0
class Renderer:

    def __init__(self, file_name, hide, n, interval=100, hide_widgets=False):
        self.root = tkinter.Tk()
        if not file_name:
            file_name = askopenfilename(initialdir="output", title="Select param", filetypes=[
                ("param files", "*.param")])
        self.file_name = file_name
        X = pickle.load(open(file_name, 'rb'))
        self.plotter = Plotter(X, hide, n)
        self.interval = interval
        self.hide_widgets = hide_widgets

    def render(self):
        print(f'drawing with {self.plotter.n} circles')
        self.fig = Figure(figsize=(13, 13), dpi=100)
        self.ax = self.fig.subplots()
        self.root.wm_title(f"Render - {base_name(args.file_name, True)}")
        canvas = FigureCanvasTkAgg(self.fig, master=self.root)
        canvas.draw()
        canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
        if not self.hide_widgets:
            rax = self.fig.add_axes([0.05, 0.0, 0.1, 0.1])
            rax.axis('off')
            self.check = CheckButtons(rax, ('hide',), (self.plotter.hide,))
            self.check.on_clicked(lambda _: self.plotter.toggle_hide())

            nax = self.fig.add_axes([0.2, 0.07, 0.7, 0.02])
            self.nslider = Slider(nax, 'n', 2, self.plotter.frames,
                                  valinit=self.plotter.n, valstep=1)
            self.nslider.on_changed(self._update_n)
            fpsax = self.fig.add_axes([0.2, 0.03, 0.7, 0.02])
            self.fpsslider = Slider(fpsax, 'fps', 1, 50,
                                    valinit=10, valstep=1)
            self.fpsslider.on_changed(self._update_fps)
        self._init_animation()
        if args.save:
            self.save(args.out)
        else:
            tkinter.mainloop()

    def _init_animation(self):
        self.animation = FuncAnimation(self.fig,
                                       self.plotter.render_frame,
                                       frames=range(self.plotter.frames),
                                       interval=self.interval,
                                       repeat_delay=1000,
                                       init_func=partial(
                                           self.plotter.init_frame, self.ax),
                                       repeat=True)

    def _update_fps(self, fps):
        self.animation.event_source.stop()
        self.interval = int(1000 / fps)
        self._init_animation()

    def _update_n(self, n):
        self.animation.event_source.stop()
        self.plotter = Plotter(self.plotter.X, self.plotter.hide, int(n))
        self._init_animation()

    def save(self, out_fname):
        if not out_fname:
            out_fname = f'output/{base_name(self.file_name)}.mp4'
        print(f'saving to {out_fname}')
        self.animation.save(
            out_fname, writer=FFMpegWriter(fps=10, bitrate=1000))
Ejemplo n.º 33
0
#fig_manager = plot.get_current_fig_manager()
#if hasattr(fig_manager, 'window'):
#    fig_manager.window.showMaximized()
    

#creation de l' "Axes" et ajustement de sa position
ax = fig.add_subplot(111)
ax2 = ax.twinx()
fig.subplots_adjust(left=0.1,right=0.6, bottom=0.25)

    
# création des Sliders
V_slider_ax  = fig.add_axes([0.7, 0.25, 0.03, 0.65])
V_slider = VertSlider(V_slider_ax, "V0/E", -0.8, 2, valinit=0)
w_slider_ax = fig.add_axes([0.1, 0.1, 0.5, 0.03])
w_slider = Slider(w_slider_ax, 'width', 0.1, 5.0, valinit=w)
zoom_slider_ax = fig.add_axes([0.1, 0.05, 0.5, 0.03])
zoom_slider = Slider(zoom_slider_ax, 'zoom', 0.1, 2.0, valinit=zoom)
prec_slider_ax  = fig.add_axes([0.8, 0.25, 0.03, 0.65])
prec_slider = VertSlider(prec_slider_ax, "precision", 1, 500, valinit=precision)

#configuration des events handlers
V_slider.on_changed(sliders_on_changed)
w_slider.on_changed(sliders_on_changed)
zoom_slider.on_changed(sliders_on_changed)
prec_slider.on_changed(sliders_on_changed)


# création du Bouton reset
reset_button_ax = fig.add_axes([0.7, 0.1, 0.1, 0.04])
reset_button = Button(reset_button_ax, 'Reset', color = axisColor, hovercolor='0.975')
Ejemplo n.º 34
0
class VideoViewer(object):
    """
    A matplotlib-based video viewer.
    
    Parameters
    ----------
    video : list-like, iterator
        A list of a tuple of 2D arrays or a generator of a tuple of 2D arrays. 
        If an iterator is provided, you must set 'n' as well. 
    n: int
        Length of the video. When this is set it displays only first 'n' frames of the video.
    id : int, optional
        For multi-frame data specifies camera index.
    title : str, optional
        Plot title.
    """
    def __init__(self, video, n=None, id=0, title=""):

        if n is None:
            try:
                n = len(video)
            except TypeError:
                raise Exception("You must specify nframes!")
        self.id = id
        self.index = 0
        self.video = video
        self.fig, self.ax = plt.subplots()
        self.ax.set_title(title)
        plt.subplots_adjust(bottom=0.25)

        frame = next(iter(video))  #take first frame
        frame = self._prepare_image(frame)
        self.img = self.ax.imshow(frame)

        self.axframe = plt.axes([0.25, 0.1, 0.65, 0.03])
        self.sframe = Slider(self.axframe,
                             'Frame',
                             0,
                             n - 1,
                             valinit=0,
                             valstep=1,
                             valfmt='%i')

        def update(val):
            i = int(self.sframe.val)
            try:
                frame = self.video[i]  #assume list-like object
                self.index = i
            except TypeError:
                #assume generator
                frame = None
                if i > self.index:
                    for frame in self.video:
                        self.index += 1
                        if self.index >= i:
                            break
            if frame is not None:
                frame = self._prepare_image(frame)
                self.img.set_data(frame)
                self.fig.canvas.draw_idle()

        self.sframe.on_changed(update)

    def _prepare_image(self, im):
        if isinstance(im, tuple) or isinstance(im, list):
            return im[self.id]
        else:
            return im

    def show(self):
        """Shows video."""
        plt.show()
Ejemplo n.º 35
0
fig, ax = plt.subplots()
plt.subplots_adjust(left=0.25, bottom=0.25)
t = np.arange(0.0, 1.0, 0.001)
a0 = 5
f0 = 3
delta_f = 5.0
s = a0 * np.sin(2 * np.pi * f0 * t)
l, = plt.plot(t, s, lw=2)
plt.axis([0, 1, -10, 10])

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)

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


def update(val):
    amp = samp.val
    freq = sfreq.val
    l.set_ydata(amp*np.sin(2*np.pi*freq*t))
    fig.canvas.draw_idle()


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

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

xMiddleLine = ax.axvline(xInitial, color="orange")
# Text boxes
# Function
axbox = plt.axes([0.125, 0.05, 0.8, 0.0400])  #left bottom width height
text_box = TextBox(axbox, 'Function', initial=initial_function)
# X Lower
axbox2 = plt.axes([0.180, 0.13, 0.2, 0.0400])
xMiddleBox = TextBox(axbox2, 'Initial X guess', initial=str(xInitial))
# Slider
# Iteration count
axbox4 = plt.axes([0.125, 0.21, 0.3, 0.0400])
iterSlider = Slider(axbox4,
                    'Iteration',
                    0,
                    10,
                    valinit=initial_iteration - 1,
                    valstep=1)


# Update iteration
def updateIteration(val):
    # Get values from the slider
    iteration = iterSlider.val
    # Remove existing xMiddle
    ax.lines[-1].remove()
    # Get updated xMiddle
    xMiddle = newRaph(float(xMiddleBox.text), iteration)
    # Set the xMiddle
    xMiddleLine = ax.axvline((xMiddle), color="Orange")
    plt.draw()
Ejemplo n.º 37
0
class DoS():
    """
    Definition of the density of state class
    """
    def __init__(self,
                 bandarrays=None,
                 energies=None,
                 evals=None,
                 units='eV',
                 label='1',
                 sigma=0.2,
                 npts=2500,
                 fermi_level=None,
                 norm=1.0,
                 sdos=None,
                 e_min=None,
                 e_max=None):
        """
        Extract a quantity which is associated to the DoS, that can be plotted
        """
        import numpy as np
        self.ens = []
        self.labels = []
        self.ef = None
        # self.norms=[]
        self.npts = npts
        if e_min is not None:
            self.e_min = e_min
        else:
            self.e_min = 1.e100
        if e_max is not None:
            self.e_max = e_max
        else:
            self.e_max = -1.e100
        if bandarrays is not None:
            self.append_from_bandarray(bandarrays, label)
        if evals is not None:
            self.append_from_dict(evals, label)
        if energies is not None:
            self.append(
                np.array([energies]),
                label=label,
                units=units,
                norm=(np.array([norm]) if isinstance(norm, float) else norm))
        self.sigma = sigma
        self.fermi_level(fermi_level, units=units)
        if sdos is not None:
            self._embed_sdos(sdos)

    def _embed_sdos(self, sdos):
        self.sdos = []
        for i, xdos in enumerate(sdos):
            self.sdos.append({'coord': xdos['coord']})
            jdos = 0
            for subspin in xdos['dos']:
                if len(subspin[0]) == 0:
                    continue
                d = {'doslist': subspin}
                try:
                    self.ens[jdos]['sdos'].append(d)
                except KeyError:
                    self.ens[jdos]['sdos'] = [d]
                jdos += 1

    def append_from_bandarray(self, bandarrays, label):
        """
        Add a new band array to the previous DoS. Important for kpoints DOS
        """
        import numpy as np
        for jspin in range(2):
            kptlists, lbl = _bandarray_to_data(jspin, bandarrays)
            self.append(np.array(kptlists[0]),
                        label=label + lbl,
                        units='AU',
                        norm=np.array(kptlists[1]))

    def append_from_dict(self, evals, label):
        import numpy as np
        "Get the energies from the different flavours given by the dict"
        evs = [[], []]
        ef = None
        for ev in evals:
            occ = self.get_ev(ev, ['e_occ', 'e_occupied'])
            if occ:
                ef = max(occ)
            vrt = self.get_ev(ev, ['e_vrt', 'e_virt'])
            eigen = False
            if occ:
                eigen = occ
            if vrt:
                eigen = vrt
            if not eigen:
                eigen = self.get_ev(ev)
            if not occ and not vrt and eigen:
                ef = max(eigen)
            if not eigen:
                continue
            for i, e in enumerate(eigen):
                if e:
                    evs[i].append(e)
        for i, energs in enumerate(evs):
            if len(energs) == 0:
                continue
            self.append(np.array(energs),
                        label=label,
                        units='AU',
                        norm=1.0 - 2.0 * i)
        if ef:
            self.fermi_level(ef, units='AU')

    def get_ev(self, ev, keys=None):
        "Get the correct list of the energies for this eigenvalue"
        res = False
        if keys is None:
            ener = ev.get('e')
            spin = ev.get('s')
            if ener and spin == 1:
                res = [ener]
            elif ener and spin == -1:
                res = [None, ener]
        else:
            for k in keys:
                if k in ev:
                    res = ev[k]
                    if not isinstance(res, list):
                        res = [res]
                    break
        return res

    def append(self, energies, label=None, units='eV', norm=1.0):
        if not isinstance(norm, float) and len(norm) == 0:
            return
        dos = self.conversion_factor(units) * energies
        self.ens.append({'dos': DiracSuperposition(dos, wgts=norm)})
        lbl = label if label is not None else str(len(self.labels) + 1)
        self.labels.append(lbl)
        # self.norms.append(norm)
        self.range = self._set_range()

    def conversion_factor(self, units):
        if units == 'AU':
            fac = AU_eV
        elif units == 'eV':
            fac = 1.0
        else:
            raise ValueError('Unrecognized units (' + units + ')')
        return fac

    def fermi_level(self, fermi_level, units='eV'):
        if fermi_level is not None:
            self.ef = fermi_level * self.conversion_factor(units)

    def _set_range(self, npts=None, e_min=None, e_max=None):
        import numpy as np
        if npts is None:
            npts = self.npts
        if e_min is None:
            e_min = self.e_min
        if e_max is None:
            e_max = self.e_max
        for dos in self.ens:
            mn, mx = dos['dos'].xlim
            e_min = min(e_min, mn)
            e_max = max(e_max, mx)
        return np.arange(e_min, e_max, (e_max - e_min) / npts)

    def curve(self, dos, norm, sigma=None):
        import numpy as np
        if sigma is None:
            sigma = self.sigma
        nrm = np.sqrt(2.0 * np.pi) * sigma / norm
        dos_g = []
        for e_i in self.range:
            if len(dos.shape) == 2:
                nkpt = dos.shape[0]
                value = 0.0
                for ikpt in range(nkpt):
                    value += np.sum(
                        np.exp(-(e_i - dos[ikpt, :])**2 / (2.0 * sigma**2)) /
                        nrm[ikpt])
            else:
                value = np.sum(
                    np.exp(-(e_i - dos[:])**2 / (2.0 * sigma**2)) / nrm)
            # Append data corresponding to each energy grid
            dos_g.append(value)
        return np.array(dos_g)

    def dump(self, sigma=None):
        "For Gnuplot"
        if sigma is None:
            sigma = self.sigma
        # data=[self.curve(dos,norm=self.norms[i],sigma=sigma)
        #       for i,dos in enumerate(self.ens)]
        data = [
            dos['dos'].curve(self.range, sigma=sigma)[1] for dos in self.ens
        ]

        for i, e in enumerate(self.range):
            safe_print(e, ' '.join(map(str, [d[i] for d in data])))

    def plot(self,
             sigma=None,
             legend=True,
             xlmin=None,
             xlmax=None,
             ylmin=None,
             ylmax=None,
             width=6.4,
             height=4.8):
        import matplotlib.pyplot as plt
        from matplotlib.widgets import Slider  # , Button, RadioButtons
        if sigma is None:
            sigma = self.sigma
        self.fig, self.ax1 = plt.subplots(figsize=(width, height))
        self.plotl = []
        for i, dos in enumerate(self.ens):
            # self.plotl.append(self.ax1.plot(self.range,self.curve(dos,norm=self.norms[i],sigma=sigma),label=self.labels[i]))
            self.plotl.append(
                self.ax1.plot(*dos['dos'].curve(self.range, sigma=sigma),
                              label=self.labels[i]))
        if xlmax is not None:
            plt.xlim(xmax=xlmax)
        if xlmin is not None:
            plt.xlim(xmin=xlmin)
        if ylmax is not None:
            plt.ylim(ymax=ylmax)
        if ylmin is not None:
            plt.ylim(ymin=ylmin)
        plt.xlabel('Energy [eV]', fontsize=18)
        plt.ylabel('DoS', fontsize=18)
        if self.ef is not None:
            plt.axvline(self.ef, color='k', linestyle='--')
            # self.ax1.annotate('Fermi level', xy=(self.ef,2),
            #        xytext=(self.ef, 10),
            #    arrowprops=dict(facecolor='white', shrink=0.05),
            # )
        if len(self.labels) > 1 and legend:
            plt.legend(loc='best')
        axcolor = 'lightgoldenrodyellow'
        try:
            axsigma = plt.axes([0.2, 0.93, 0.65, 0.03], facecolor=axcolor)
        except AttributeError:
            axsigma = plt.axes([0.2, 0.93, 0.65, 0.03], axisbg=axcolor)

        self.ssig = Slider(axsigma, 'Smearing', 0.0, 0.4, valinit=sigma)
        self.ssig.on_changed(self.update)
        if hasattr(self, 'sdos') and self.sdos:
            self._set_sdos_selector()
            self._set_sdos()
        plt.show()

    def _set_sdos_selector(self):
        import matplotlib.pyplot as plt
        from matplotlib.widgets import RadioButtons
        self.sdos_selector = RadioButtons(plt.axes(
            [0.93, 0.05, 0.04, 0.11], axisbg='lightgoldenrodyellow'),
                                          ('x', 'y', 'z'),
                                          active=1)
        self.isdos = 1
        self.sdos_selector.on_clicked(self._update_sdos)

    def _set_sdos(self):
        import numpy
        xs = self.sdos[self.isdos]['coord']
        self._set_sdos_sliders(numpy.min(xs), numpy.max(xs))
        self._update_sdos(0.0)  # fake value as it is unused

    def _sdos_curve(self, sdos, vmin, vmax):
        import numpy
        xs = self.sdos[self.isdos]['coord']
        imin = numpy.argmin(numpy.abs(xs - vmin))
        imax = numpy.argmin(numpy.abs(xs - vmax))
        doslist = sdos[self.isdos]['doslist']
        # norms=self.sdos[self.isdos]['norms'][ispin]
        tocurve = [0.0 for i in doslist[imin]]
        for d in doslist[imin:imax + 1]:
            tocurve = [t + dd for t, dd in zip(tocurve, d)]
        # tocurve=numpy.sum([ d[ispin] for d in doslist[imin:imax+1]],axis=0)
        return tocurve
        # float(len(xs))/float(imax+1-imin)*tocurve,norms

    def _update_sdos(self, val):
        isdos = self.isdos
        if val == 'x':
            isdos = 0
        elif val == 'y':
            isdos = 1
        elif val == 'z':
            isdos = 2
        if isdos != self.isdos:
            self.isdos = isdos
            self._set_sdos()

        vmin, vmax = (s.val for s in self.ssdos)
        if vmax < vmin:
            self.ssdos[1].set_val(vmin)
            vmax = vmin
        if vmin > vmax:
            self.ssdos[0].set_val(vmax)
            vmin = vmax
        # now plot the sdos curve associated to the given value
        sig = self.ssig.val
        curves = []
        for dos in self.ens:
            if 'sdos' not in dos:
                continue
            renorms = self._sdos_curve(dos['sdos'], vmin, vmax)
            curve = dos['dos'].curve(self.range, sigma=sig, wgts=renorms)
            curves.append(curve)
        if hasattr(self, '_sdos_plots'):
            for pl, curve in zip(self._sdos_plots, curves):
                pl[0].set_ydata(curve[1])
        else:
            self._sdos_plots = []
            for c in curves:
                self._sdos_plots.append(self.ax1.plot(*c, label='sdos'))
        self.ax1.relim()
        self.ax1.autoscale_view()
        self.fig.canvas.draw_idle()

    def _set_sdos_sliders(self, cmin, cmax):
        import matplotlib.pyplot as plt
        from futile.Figures import VertSlider
        if hasattr(self, 'ssdos'):
            self.ssdos[0].ax.clear()
            self.ssdos[0].__init__(self.ssdos[0].ax,
                                   'SDos',
                                   cmin,
                                   cmax,
                                   valinit=cmin)
            self.ssdos[1].ax.clear()
            self.ssdos[1].__init__(self.ssdos[1].ax,
                                   '',
                                   cmin,
                                   cmax,
                                   valinit=cmax)
        else:
            axcolor = 'red'
            axmin = plt.axes([0.93, 0.2, 0.02, 0.65], axisbg=axcolor)
            axmax = plt.axes([0.95, 0.2, 0.02, 0.65], axisbg=axcolor)
            self.ssdos = [
                VertSlider(axmin, 'SDos', cmin, cmax, valinit=cmin),
                VertSlider(axmax, '', cmin, cmax, valinit=cmax)
            ]
        self.ssdos[0].valtext.set_ha('right')
        self.ssdos[1].valtext.set_ha('left')
        self.ssdos[0].on_changed(self._update_sdos)
        self.ssdos[1].on_changed(self._update_sdos)

    def update(self, val):
        sig = self.ssig.val
        for i, dos in enumerate(self.ens):
            self.plotl[i][0].set_ydata(dos['dos'].curve(self.range,
                                                        sigma=sig)[1])
            # self.plotl[i][0].set_ydata(self.curve(dos,norm=self.norms[i],sigma=sig))

        self.ax1.relim()
        self.ax1.autoscale_view()
        self.fig.canvas.draw_idle()
Ejemplo n.º 38
0
    def GUI(self):  # ,makefigs=True):
        print('I am here')

        mpl.rcParams['toolbar'] = 'None'

        self.Nphf = self.Npix / 2
        self.robfac = 0.0
        self.figSPEC = pl.figure(figsize=(20, 16))
        #    self.gs1 = self.figSPEC.add_gridspec(nrows=4, ncols=3, left=0.05, right=0.48,
        #                        wspace=0.05)
        if self.tks is None:
            self.canvas = self.figSPEC.canvas
        else:
            self.canvas = FigureCanvasTkAgg(self.figSPEC, master=self.tks)
            self.canvas.show()
            menubar = Tk.Menu(self.tks)
            menubar.add_command(label="Help", command=self._getHelp)
            menubar.add_command(label="Quit", command=self.quit)

            self.tks.config(menu=menubar)
            self.canvas.get_tk_widget().pack(side=Tk.TOP,
                                             fill=Tk.BOTH,
                                             expand=1)

        self.specPlot = self.figSPEC.add_subplot(221)
        self.freqPlot = self.figSPEC.add_subplot(222)
        self.timePlot = self.figSPEC.add_subplot(223)
        # self.eventprofilePlot = self.figSPEC.add_subplot(224)
        self.specPlot.set_position([0.1, 0.45, 0.45, 0.45])
        self.freqPlot.set_position([0.58, 0.45, 0.125, 0.45])
        self.timePlot.set_position([0.1, 0.28, 0.45, 0.15])
        # self.dirtyPlot = self.figUV.add_subplot(236,aspect='equal')

        #self.spherePlot = pl.axes([0.53,0.82,0.12,0.12],projection='3d',aspect='equal')

        u = np.linspace(0, 2 * np.pi, 100)
        v = np.linspace(0, np.pi, 100)
        x = 10 * np.outer(np.cos(u), np.sin(v))
        y = 10 * np.outer(np.sin(u), np.sin(v))
        z = 10 * np.outer(np.ones(np.size(u)), np.cos(v))
        #self.spherePlotPlot = self.spherePlot.plot_surface(x, y, z,  rstride=4, cstride=4, color=(0.8,0.8,1.0))
        #self.spherePlot._axis3don = False
        #self.spherePlot.patch.set_alpha(0.8)
        #beta = np.zeros(100)
        #self.arrayPath = [np.zeros(self.nH), np.zeros(self.nH), np.zeros(self.nH)]
        #self.sphereArray = self.spherePlot.plot([],[],[],'y',linewidth=3)
        #self.spherePlot.set_xlim3d((-6,6))
        #self.spherePlot.set_ylim3d((-6,6))
        #self.spherePlot.set_zlim3d((-6,6))
        #self.spherePlot.patch.set_alpha(0.8)
        #self.spherePlot.elev = 45.

        self.canvas.mpl_connect('button_press_event', self.on_press)

        #self.figSPEC.subplots_adjust(left=0.01,right=0.99,top=0.95,bottom=0.071,hspace=0.15)
        #self.canvas.mpl_connect('mouse_event', self.mouse_move)
        #self.canvas.mpl_connect('motion_notify_event', self._onAntennaDrag)
        #self.canvas.mpl_connect('button_release_event',self._onRelease)
        #self.canvas.mpl_connect('button_press_event',self._onPress)
        #self.canvas.mpl_connect('key_press_event', self._onKeyPress)
        self.pickAnt = False

        self.fmtH = r'$\phi = $ %3.1f$^\circ$   $\delta = $ %3.1f$^\circ$' "\n" r'H = %3.1fh / %3.1fh'
        self.fmtBas = r'Bas %i $-$ %i  at  H = %4.2fh'
        self.fmtVis = r'Amp: %.1e Jy.   Phase: %5.1f deg.'
        self.fmtA = 'N = %i'
        self.fmtA2 = '  Picked Ant. #%i'
        self.fmtA3 = '\n%6.1fm | %6.1fm'

        self.wax = {}
        self.widget = {}
        self.wax['freq'] = pl.axes([0.075, 0.15, 0.1, 0.04])
        self.wax['freq_min'] = pl.axes([0.4, 0.15, 0.1, 0.04])
        self.wax['freq_max'] = pl.axes([0.6, 0.15, 0.1, 0.04])
        self.wax['smooth'] = pl.axes([0.045, 0.25, 0.1, 0.04])
        self.wax['open'] = pl.axes([0.002, 0.90, 0.075, 0.04])
        self.wax['plot'] = pl.axes([0.003, 0.8, 0.075, 0.04])
        self.wax['reduce'] = pl.axes([0.07, 0.1, 0.25, 0.04])

        self.widget['freq'] = Slider(self.wax['freq'],
                                     r'frequency',
                                     self.st_freq,
                                     self.stp_freq,
                                     valinit=80.0)
        self.widget['freq_min'] = Slider(self.wax['freq_min'],
                                         r'frequency_min',
                                         self.st_freq,
                                         self.stp_freq,
                                         valinit=45.0)
        self.widget['freq_max'] = Slider(self.wax['freq_max'],
                                         r'frequency_max',
                                         self.st_freq,
                                         self.stp_freq,
                                         valinit=155.0)
        self.widget['smooth'] = Slider(self.wax['smooth'],
                                       r'smooth',
                                       valmin=1,
                                       valmax=101,
                                       valinit=51.0)
        self.widget['open'] = Button(self.wax['open'], r' Open File')
        self.widget['plot'] = Button(self.wax['plot'], r' plot')
        self.widget['reduce'] = Button(self.wax['reduce'], r'Reduce data')
        self.widget['freq'].on_changed(self.onFreq)
        self.widget['freq_min'].on_changed(self.onFreq_min_axis_change)
        self.widget['freq_max'].on_changed(self.onFreq_max_axis_change)
        self.widget['smooth'].on_changed(self.onSmooth)
        #   self.widget['loadfile'].on_clicked(self.loadFile)
        self.widget['open'].on_clicked(self.loadFile)
        self.widget['plot'].on_clicked(self.onPlot)

        self._prepareSpec_data()

        self.canvas.draw()
Ejemplo n.º 39
0
def draw(os,
         rays=None,
         hold_on=False,
         do_not_draw_surfaces=[],
         do_not_draw_raybundles=[],
         interactive=False,
         show_box=True,
         label=None,
         linewidth=1.0,
         export_type="pdf",
         export=None,
         **kwargs):
    """
    Convenience function for drawing optical system and list of raybundles
    Use figsize=(..,..) to control aspect ratio for export.

    :param os - OpticalSystem
    :param rb - list of raybundles

    """

    if export is not None:
        interactive = False
    if label is None:
        label = str(uuid.uuid4())

    axis_color = "lightgoldenrodyellow"

    dpi = kwargs.pop("dpi", None)
    figsize = kwargs.pop("figsize", None)

    fig = plt.figure(1, dpi=dpi, figsize=figsize)

    if not show_box:
        ax = plt.Axes(fig, [0., 0., 1., 1.], label=label)
        ax.set_axis_off()
        fig.add_axes(ax)
    else:
        ax = fig.add_subplot(1, 1, 1, label=label)

    if interactive:
        fig.subplots_adjust(left=0.25, bottom=0.25)

        xz_angle_slider_size = [0.25, 0.15, 0.65, 0.03]
        up_angle_slider_size = [0.25, 0.10, 0.65, 0.03]

        if StrictVersion(matplotlib.__version__) < StrictVersion("2.0.0"):
            xz_angle_slider_ax = fig.add_axes(xz_angle_slider_size,
                                              axisbg=axis_color)
            up_angle_slider_ax = fig.add_axes(up_angle_slider_size,
                                              axisbg=axis_color)
        else:
            xz_angle_slider_ax = fig.add_axes(xz_angle_slider_size,
                                              facecolor=axis_color)
            up_angle_slider_ax = fig.add_axes(up_angle_slider_size,
                                              facecolor=axis_color)

        xz_angle_slider = Slider(xz_angle_slider_ax,
                                 "XZ angle",
                                 0.0,
                                 360.0,
                                 valinit=0.0,
                                 valfmt="%0.0f")
        up_angle_slider = Slider(up_angle_slider_ax,
                                 "UP angle",
                                 0.0,
                                 360.0,
                                 valinit=0.0,
                                 valfmt="%0.0f")

    ax.axis("equal")
    if StrictVersion(matplotlib.__version__) < StrictVersion("2.0.0"):
        ax.set_axis_bgcolor("white")
    else:
        ax.set_facecolor("white")

    def draw_rays(ax, rays, do_not_draw_raybundles=[], **kwargs):
        if rays is not None:
            if isinstance(rays, list):
                for rpl in rays:
                    ray_color = tuple(np.random.random(3))
                    if isinstance(rpl, list):
                        for rp in rpl:
                            ray_color = tuple(np.random.random(3))
                            rp.draw2d(
                                ax,
                                color=ray_color,
                                do_not_draw_raybundles=do_not_draw_raybundles,
                                **kwargs)
                    elif isinstance(rpl, tuple):
                        (rl, ray_color) = rpl
                        if isinstance(rl, list):
                            # draw(s, [([rp1, ..], color1), (....)])
                            for r in rl:
                                r.draw2d(ax, color=ray_color, **kwargs)
                        else:
                            # draw(s, [(rp1, color1), (....)])
                            rl.draw2d(ax, color=ray_color, **kwargs)
                    else:
                        rpl.draw2d(
                            ax,
                            color=ray_color,
                            do_not_draw_raybundles=do_not_draw_raybundles,
                            **kwargs)
            elif isinstance(rays, RayPath):
                # draw(s, raypath)
                ray_color = tuple(np.random.random(3))
                rays.draw2d(ax,
                            color=ray_color,
                            do_not_draw_raybundles=do_not_draw_raybundles,
                            **kwargs)
            elif isinstance(rays, RayBundle):
                # draw(s, raybundle)
                ray_color = tuple(np.random.random(3))
                rays.draw2d(ax, color=ray_color, **kwargs)
            elif isinstance(rays, tuple):
                (rl, ray_color) = rays
                if isinstance(rl, list):
                    # draw(s, ([raypath1, ...], color))
                    for r in rl:
                        r.draw2d(ax, color=ray_color, **kwargs)
                else:
                    # draw(s, (raypath, color))
                    rl.draw2d(ax,
                              color=ray_color,
                              do_not_draw_raybundles=do_not_draw_raybundles,
                              **kwargs)

    def sliders_on_changed(val):
        ax.clear()

        round_val_xz = np.round(xz_angle_slider.val)
        round_val_up = np.round(up_angle_slider.val)

        phi = round_val_xz * degree
        theta = round_val_up * degree

        #        new_ex = np.array([np.cos(phi),
        #                           0,
        #                           np.sin(phi)])
        #        new_up = np.array([-np.sin(theta),
        #                           np.cos(theta),
        #                           0.])
        new_ex = np.array([
            np.cos(phi) * np.cos(theta),
            np.sin(theta),
            np.sin(phi) * np.cos(theta)
        ])
        new_up = np.array([
            -np.cos(phi) * np.sin(theta),
            np.cos(theta), -np.sin(phi) * np.sin(theta)
        ])
        inyzplane = np.abs(round_val_xz) < numerical_tolerance\
            and np.abs(round_val_up) < numerical_tolerance
        os.draw2d(ax,
                  color="grey",
                  inyzplane=inyzplane,
                  plane_normal=new_ex,
                  up=new_up,
                  **kwargs)
        draw_rays(ax, rays, plane_normal=new_ex, up=new_up, **kwargs)

    if interactive:
        xz_angle_slider.on_changed(sliders_on_changed)
        up_angle_slider.on_changed(sliders_on_changed)

    draw_rays(ax,
              rays,
              linewidth=linewidth,
              do_not_draw_raybundles=do_not_draw_raybundles,
              **kwargs)
    os.draw2d(ax,
              color="grey",
              linewidth=linewidth,
              do_not_draw_surfaces=do_not_draw_surfaces,
              **kwargs)

    if export is not None:
        # ax.autoscale(enable=True, axis='both', tight=True)
        fig.savefig(export,
                    format=export_type,
                    bbox_inches='tight',
                    pad_inches=0)

    if not hold_on:
        plt.show()
Ejemplo n.º 40
0
    def _add_teach_panel(self, robot):
        fig = self.fig

        # Add text to the plots
        def text_trans(text):  # pragma: no cover
            T = robot.fkine()
            t = np.round(T.t, 3)
            r = np.round(T.rpy(), 3)
            text[0].set_text("x: {0}".format(t[0]))
            text[1].set_text("y: {0}".format(t[1]))
            text[2].set_text("yaw: {0}".format(r[2]))

        # Update the self state in mpl and the text
        def update(val, text, robot):  # pragma: no cover
            for i in range(robot.n):
                robot.q[i] = self.sjoint[i].val * np.pi/180

            text_trans(text)

            # Step the environment
            self.step(0)

        fig.subplots_adjust(left=0.38)
        text = []

        x1 = 0.04
        x2 = 0.22
        yh = 0.04
        ym = 0.5 - (robot.n * yh) / 2 + 0.17/2

        self.axjoint = []
        self.sjoint = []

        qlim = np.copy(robot.qlim) * 180/np.pi

        if np.all(qlim == 0):    # pragma nocover
            qlim[0, :] = -180
            qlim[1, :] = 180

        # Set the pose text
        T = robot.fkine()
        t = np.round(T.t, 3)
        r = np.round(T.rpy(), 3)

        fig.text(
            0.02,  1 - ym + 0.25, "End-effector Pose",
            fontsize=9, weight="bold", color="#4f4f4f")
        text.append(fig.text(
            0.03, 1 - ym + 0.20, "x: {0}".format(t[0]),
            fontsize=9, color="#2b2b2b"))
        text.append(fig.text(
            0.03, 1 - ym + 0.16, "y: {0}".format(t[1]),
            fontsize=9, color="#2b2b2b"))
        text.append(fig.text(
            0.15, 1 - ym + 0.20, "yaw: {0}".format(r[0]),
            fontsize=9, color="#2b2b2b"))
        fig.text(
            0.02,  1 - ym + 0.06, "Joint angles",
            fontsize=9, weight="bold", color="#4f4f4f")

        for i in range(robot.n):
            ymin = (1 - ym) - i * yh
            self.axjoint.append(
                fig.add_axes([x1, ymin, x2, 0.03], facecolor='#dbdbdb'))

            self.sjoint.append(
                Slider(
                    self.axjoint[i], 'q' + str(i),
                    qlim[0, i], qlim[1, i], robot.q[i] * 180/np.pi))

            self.sjoint[i].on_changed(lambda x: update(x, text, robot))
Ejemplo n.º 41
0
    fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(8, 6))
    fig.subplots_adjust(bottom=0.25)

    ax.set_xlabel('Time', fontsize=14)
    ax.set_ylabel('', fontsize=14)
    ax.set_title('Michaelis Menten', fontsize=14)

    l1, l2, l3, l4 = ax.plot(time, res)
    l1.set_label('$dS$')
    l2.set_label('$dE$')
    l3.set_label('$dES$')
    l4.set_label('$dP$')

    ax.margins(x=0)

    axcolor = 'lightgoldenrodyellow'
    axkf = plt.axes([.25, .02, .65, .03], facecolor=axcolor)
    axkb = plt.axes([.25, .07, .65, .03], facecolor=axcolor)
    axki = plt.axes([.25, .12, .65, .03], facecolor=axcolor)

    skf = Slider(axkf, r'$k_f$', 0., 10., valinit=kf, valstep=.1)
    skb = Slider(axkb, r'$k_b$', 0., 10., valinit=kb, valstep=.1)
    ski = Slider(axki, r'Kirr', 0., 10., valinit=Kirr, valstep=.1)

    skf.on_changed(update)
    skb.on_changed(update)
    ski.on_changed(update)
    ax.legend(loc='best', fontsize=14)

    plt.show()
Ejemplo n.º 42
0
g1.set_xlabel("temps (s)")

ls,=g1.plot(t,resolution(0,1)[1],"r-",label="Amplitude du système")
lf,=g1.plot(t,sin(w_forcage*t),"g-",label="Force excitatrice")
legend()
show()


'''
ajuster la pulsation de l'excitateur par ui avec un curseur
'''

subplots_adjust(bottom=0.3)#réduit g1 pour laisser palce au slider

rect=f.add_axes([0.1,0.12,0.8,0.03])#emplacement du curseur
slider=Slider(rect,r"$\frac{\omega_{forçage}}{\omega _0}$",0.01,2,1)#paramètres du curseur
slider.label.set_size(30)

rect2=f.add_axes([0.1,0.05,0.8,0.03])#emplacement du curseur
slider2=Slider(rect2,r"$\Gamma$",0.01,2,1)#paramètres du curseur
slider2.label.set_size(30)
def maj(_):#met à jour l1 avec les valeurs du curseur
    global w_forcage
    global gamma
    w_forcage=slider.val
    gamma=slider2.val
    ls.set_ydata(resolution(0,1)[1]) 
    lf.set_ydata(sin(w_forcage*t)) 
slider.on_changed(maj)
slider2.on_changed(maj)
Ejemplo n.º 43
0
class NormalizedWormPlottable(animation.TimedAnimation):
    """
    A class that renders matplotlib plots of worm measurement and 
    feature data.
      
    This follows the [animated subplots example]
    (http://matplotlib.org/1.3.0/examples/animation/subplots.html)
    in inheriting from TimedAnimation rather than 
    using PyLab-shell-type calls to construct the animation.

    """
    def __init__(self,
                 normalized_worm,
                 motion_mode=None,
                 interactive=False,
                 interpolate_nan_frames=False):
        """ 
        Initialize the animation of the worm's attributes.

        Parameters
        ---------------------------------------
        normalized_worm: NormalizedWorm
          the NormalizedWorm object to be plotted.

        motion_mode: 1-dimensional numpy array (optional)
          The motion mode of the worm over time.  Must have 
          length = normalized_worm.num_frames

        interactive: boolean (optional)
          if interactive is set to False, then:
            suppress the drawing of the figure, until an explicit plt.show()
            is called.  this allows NormalizedWormPlottable to be instantiated 
            without just automatically being displayed.  Instead, the user 
            must call NormalizedWormPlottable.show() to have plt.show() be 
            called.
            
        interpolate_nan_frames: interpolate the flickering nan frames
            Note: this is currently not implemented

        Notes
        ---------------------------------------
        To initialize the animation, we must do six things:
          1. set up the data to be used from the normalized_worm
          2. create the figure
          3. create subplots in the figure, assigning them Axis handles
          4. create Artist objects for all objects in the subplots 
          5. assign the Artist objects to the correct Axis handle
          6. call the base class __init__

        """
        # A NormalizedWormPlottable instance can be instantiated to be
        # interactive, or by default it is set to NOT interactive, which
        # means that NormalizedWormPlottable.show() must be called to get
        # it to display.
        plt.interactive(interactive)

        self._paused = False

        # 1. set up the data to be used
        self.nw = normalized_worm
        self.motion_mode = motion_mode
        self.motion_mode_options = {-1: 'backward', 0: 'paused', 1: 'forward'}
        self.motion_mode_colours = {
            -1: 'b',  # blue
            0: 'r',  # red
            1: 'g'
        }  # green

        # 2. create the figure
        fig = plt.figure(figsize=(5, 5))

        # We have blit=True, so the animation only redraws the elements that
        # have changed.  This means that if the window is resized, everything
        # other than the plot area will be black.  To fix this, here we have
        # matplotlib explicitly redraw everything if a resizing event occurs.
        # DEBUG: this actually doesn't appear to work.
        def refresh_plot(event):
            print("refresh_plot called")

            # We must reset this or else repetitive expanding and contracting
            # of the window will cause the view to zoom in on the subplots
            self.set_axes_extents()

            fig.canvas.draw()

        self.refresh_connection_id = fig.canvas.mpl_connect(
            'resize_event', refresh_plot)

        fig.suptitle('C. elegans attributes', fontsize=20)

        # 3. Add the subplots
        self.ax1 = plt.subplot2grid((3, 3), (0, 0), rowspan=2, colspan=2)
        self.ax1.set_title('Position')
        self.ax1.plot(self.nw.skeleton[0, 0, :], self.nw.skeleton[0, 1, :])
        self.ax1.set_xlabel('x')
        self.ax1.set_ylabel('y')
        #ax1.set_aspect(aspect='equal', adjustable='datalim')
        # ax1.set_autoscale_on()

        self.annotation1a = \
                       self.ax1.annotate("(motion mode data not available)",
                                         xy=(-10, 10), xycoords='axes points',
                                         horizontalalignment='right',
                                         verticalalignment='top',
                                         fontsize=10)

        self.annotation1b = \
                       self.ax1.annotate("bottom right (points)",
                                         xy=(-10, 10), xycoords='axes points',
                                         horizontalalignment='right',
                                         verticalalignment='bottom',
                                         fontsize=10)

        # WIDGETS
        # [left,botton,width,height] as a proportion of
        # figure width and height
        frame_slider_axes = fig.add_axes([0.2, 0.02, 0.33, 0.02],
                                         axisbg='lightgoldenrodyellow')
        self.frame_slider = Slider(frame_slider_axes,
                                   label='Frame#',
                                   valmin=1,
                                   valmax=self.nw.num_frames,
                                   valinit=1,
                                   valfmt=u'%d')

        def frame_slider_update(val):
            print("Slider value: %d" % round(val, 0))
            self.frame_seq = self.new_frame_seq(int(round(val, 0)))

            fig.canvas.draw()

        self.frame_slider.on_changed(frame_slider_update)

        button_axes = fig.add_axes([0.8, 0.025, 0.1, 0.04])
        #ax4 = plt.subplot2grid((3, 3), (2, 2))
        button = Button(button_axes,
                        'Pause',
                        color='lightgoldenrodyellow',
                        hovercolor='0.975')

        def pause(event):
            if not self._paused:
                self._stop()
            else:
                self.event_source = fig.canvas.new_timer()
                self.event_source.interval = self._interval
                self._start()

            # Toggle the paused state
            self._paused = 1 - self._paused

        button.on_clicked(pause)

        self.ax2 = plt.subplot2grid((3, 3), (0, 2))
        self.ax2.set_title('Morphology')
        self.ax2.set_aspect(aspect='equal', adjustable='datalim')
        self.annotation2 = self.ax2.annotate(
            "Worm head",
            xy=(0, 0),
            xycoords='data',
            xytext=(10, 10),
            textcoords='data',
            arrowprops=dict(arrowstyle="fancy", connectionstyle="arc3,rad=.2"))

        self.ax3 = plt.subplot2grid((3, 3), (1, 2))
        self.ax3.set_title('Orientation-free')
        # DON'T USE set_xbound, it changes dynmically
        self.ax3.set_aspect(aspect='equal', adjustable='datalim')

        # Length and Area over time
        self.ax4a = plt.subplot2grid((3, 3), (2, 0), rowspan=1, colspan=2)
        self.ax4a.plot(self.nw.length, 'o-')
        self.ax4a.set_title('Length and Area over time')
        self.ax4a.set_ylabel('Microns')

        self.ax4b = self.ax4a.twinx()
        self.ax4b.plot(self.nw.area, 'xr-')
        self.ax4b.set_ylabel('Microns ^ 2')

        # Widths and Angles
        self.ax5a = plt.subplot2grid((3, 3), (2, 2))
        self.ax5a.set_title('Widths and Angles')
        self.ax5a.set_xlabel('Skeleton point')
        self.widths = Line2D([], [])
        self.ax5a.set_ylabel('Microns')

        self.ax5b = self.ax5a.twinx()
        self.angles = Line2D([], [])
        self.ax5b.set_ylabel('Degrees')

        # 4. create Artist objects
        self.time_marker = Line2D([], [])

        self.line1W = Line2D([], [],
                             color='green',
                             linestyle='point marker',
                             marker='o',
                             markersize=5)
        self.line1W_head = Line2D([], [],
                                  color='red',
                                  linestyle='point marker',
                                  marker='o',
                                  markersize=7)
        self.line1C = Line2D([], [],
                             color='yellow',
                             linestyle='point marker',
                             marker='o',
                             markersize=5)
        self.patch1E = Ellipse(xy=(0, 0),
                               width=1000,
                               height=500,
                               angle=0,
                               alpha=0.3)

        self.line2W = Line2D([], [], color='black', marker='o', markersize=5)
        self.line2W_head = Line2D([], [],
                                  color='red',
                                  linestyle='point marker',
                                  marker='o',
                                  markersize=7)
        self.line2C = Line2D([], [], color='blue')
        self.line2C2 = Line2D([], [], color='orange')

        self.line3W = Line2D([], [], color='black', marker='o', markersize=5)
        self.line3W_head = Line2D([], [],
                                  color='red',
                                  linestyle='point marker',
                                  marker='o',
                                  markersize=7)

        self.artists_with_data = [
            self.line1W, self.line1W_head, self.line1C, self.line2W,
            self.line2W_head, self.line2C, self.line2C2, self.line3W,
            self.line3W_head, self.widths, self.angles, self.time_marker
        ]

        # This list is a superset of self.artists_with_data
        self.artists_to_be_drawn = ([
            self.patch1E, self.annotation1a, self.annotation1b,
            self.annotation2
        ] + self.artists_with_data)

        self.set_axes_extents()

        # 5. assign Artist objects to the relevant subplot
        self.ax1.add_line(self.line1W)
        self.ax1.add_line(self.line1W_head)
        self.ax1.add_line(self.line1C)
        self.ax1.add_artist(self.patch1E)

        self.ax2.add_line(self.line2W)
        self.ax2.add_line(self.line2W_head)
        self.ax2.add_line(self.line2C)
        self.ax2.add_line(self.line2C2)

        self.ax3.add_line(self.line3W)
        self.ax3.add_line(self.line3W_head)

        self.ax4a.add_line(self.time_marker)

        self.ax5a.add_line(self.widths)
        self.ax5b.add_line(self.angles)

        # So labels don't overlap:
        #plt.tight_layout()

        # 6. call the base class __init__

        # TimedAnimation draws a new frame every *interval* milliseconds.
        # so this is how we convert from FPS to interval:
        interval = 1000 / self.nw.video_info.fps

        return animation.TimedAnimation.__init__(self,
                                                 fig,
                                                 interval=interval,
                                                 blit=True)

    def set_axes_extents(self):
        # DON'T USE set_xbound; it changes dynamically
        self.ax1.set_xlim(self.nw.position_limits(0))
        self.ax1.set_ylim(self.nw.position_limits(1))
        self.ax2.set_xlim((-500, 500))
        self.ax2.set_ylim((-500, 500))
        self.ax3.set_xlim((-800, 800))
        self.ax3.set_ylim((-500, 500))
        self.ax4a.set_xlim((0, self.nw.num_frames))
        self.ax5a.set_xlim((0, 49))
        self.ax5a.set_ylim((0, np.nanmax(self.nw.widths)))
        self.ax5b.set_ylim(
            (np.nanmin(self.nw.angles), np.nanmax(self.nw.angles)))

    def set_frame_data(self, frame_index):
        self._current_frame = frame_index

        i = frame_index
        if self._paused:
            return

        self.line1W.set_data(self.nw.skeleton[:, 0, i], self.nw.skeleton[:, 1,
                                                                         i])
        self.line1W_head.set_data(self.nw.skeleton[0, 0, i],
                                  self.nw.skeleton[0, 1, i])
        self.line1C.set_data(self.nw.ventral_contour[:, 0, i],
                             self.nw.ventral_contour[:, 1, i])
        self.patch1E.center = (self.nw.centre[:, i])  # skeleton centre
        self.patch1E.angle = self.nw.angle[i]  # orientation

        # Set the values of our annotation text in the main subplot:

        if self.motion_mode is not None:
            if np.isnan(self.motion_mode[i]):
                self.patch1E.set_facecolor('w')
                self.annotation1a.set_text("Motion mode: {}".format('NaN'))
            else:
                # Set the colour of the ellipse surrounding the worm to a
                # colour corresponding to the current motion mode of the worm
                self.patch1E.set_facecolor(
                    self.motion_mode_colours[self.motion_mode[i]])
                # Annotate the current motion mode of the worm in text
                self.annotation1a.set_text("Motion mode: {}".format(
                    self.motion_mode_options[self.motion_mode[i]]))

        self.annotation1b.set_text("Frame {} of {}".format(i, self.num_frames))

        self.line2W.set_data(self.nw.centred_skeleton[:, 0, i],
                             self.nw.centred_skeleton[:, 1, i])
        self.line2W_head.set_data(self.nw.centred_skeleton[0, 0, i],
                                  self.nw.centred_skeleton[0, 1, i])
        self.line2C.set_data(self.nw.centred_skeleton[:, 0, i] + \
            (self.nw.ventral_contour[:, 0, i] - self.nw.skeleton[:, 0, i]),
                             self.nw.centred_skeleton[:, 1, i] + \
            (self.nw.ventral_contour[:, 1, i] - self.nw.skeleton[:, 1, i]))
        self.line2C2.set_data(
            self.nw.centred_skeleton[:, 0, i] +
            (self.nw.dorsal_contour[:, 0, i] - self.nw.skeleton[:, 0, i]),
            self.nw.centred_skeleton[:, 1, i] +
            (self.nw.dorsal_contour[:, 1, i] - self.nw.skeleton[:, 1, i]))
        self.annotation2.xy = (self.nw.centred_skeleton[0, 0, i],
                               self.nw.centred_skeleton[0, 1, i])

        self.line3W.set_data(self.nw.orientation_free_skeleton[:, 0, i],
                             self.nw.orientation_free_skeleton[:, 1, i])
        self.line3W_head.set_data(self.nw.orientation_free_skeleton[0, 0, i],
                                  self.nw.orientation_free_skeleton[0, 1, i])

        self.widths.set_data(np.arange(49), self.nw.widths[:, i])
        self.angles.set_data(np.arange(49), self.nw.angles[:, i])

        # Draw a vertical line to mark the passage of time
        self.time_marker.set_data([i, i], [0, 10000])

    @property
    def num_frames(self):
        """
          Return the total number of frames in the animation

        """
        return self.nw.num_frames

    def show(self):
        """ 
        Draw the figure in a window on the screen

        """
        plt.show()

    def _draw_frame(self, frame_index):
        """ 
        Called sequentially for each frame of the animation.  Thus
        we must set our plot to look like it should for the given frame.

        Parameters
        ---------------------------------------
        frame_index: int
          An integer between 0 and the number of frames, giving
          the current frame.

        """
        # Make the canvas elements visible now
        # (We made them invisible in _init_draw() so that the first
        # frame of the animation wouldn't remain stuck on the canvas)
        for l in self.artists_to_be_drawn:
            l.set_visible(True)

        self.set_frame_data(frame_index)

        self._drawn_artists = self.artists_to_be_drawn

    def new_frame_seq(self, start_frame=0):
        """ 
        Returns an iterator that iterates over the frames 
        in the animation
        
        Parameters
        ---------------
        start_frame: int
            Start the sequence at this frame then loop back around 
            to start_frame-1.
    
        """
        s = start_frame
        n = self.num_frames
        return iter(np.mod(np.arange(s, s + n), n))

    def _init_draw(self):
        """ 
        Called when first drawing the animation.
        It is an abstract method in Animation, to be implemented here for
        the first time.

        """
        for l in self.artists_with_data:
            l.set_data([], [])

        # Keep the drawing elements invisible for the first frame to avoid
        # the first frame remaining on the canvas
        for l in self.artists_to_be_drawn:
            l.set_visible(False)

    def save(self,
             filename,
             file_title='C. elegans movement video',
             file_comment='C. elegans movement video from Schafer lab'):
        """ 
        Save the animation as an mp4.

        Parameters
        ---------------------------------------
        filename: string
          The name of the file to be saved as an mp4.

        file_title: string (optional)
          A title to be embedded in the file's saved metadata.

        file_comment: string (optional)
          A comment to be embedded in the file's saved metadata.

        Notes
        ---------------------------------------
        Requires ffmpeg or mencoder to be installed.  To install ffmpeg 
        on Windows, see:
        http://www.wikihow.com/Install-FFmpeg-on-Windows

        The code specifies extra_args=['-vcodec', 'libx264'], to ensure
        that the x264 codec is used, so that the video can be embedded 
        in html5.  You may need to adjust this for your system.  For more 
        information, see:
        http://matplotlib.sourceforge.net/api/animation_api.html

        """
        fps = self.nw.video_info.fps
        FFMpegWriter = animation.writers['ffmpeg']
        metadata = dict(title=file_title,
                        artist='matplotlib',
                        comment=file_comment)
        writer = FFMpegWriter(fps=fps, metadata=metadata)
        animation.TimedAnimation.save(self,
                                      filename,
                                      writer=writer,
                                      fps=fps,
                                      extra_args=['-vcodec', 'libx264'])
Ejemplo n.º 44
0
# plotting code snippet taken from
# https://stackoverflow.com/questions/31001713/plotting-the-data-with-scrollable-x-time-horizontal-axis-on-linux

fig, ax = plt.subplots(figsize=(12, 5))
plt.subplots_adjust(bottom=0.25, left=0.1)

t = np.arange(0.0, length / 10, 0.1)
l1, = plt.plot(t, xs, color='blue', label="xs")
l2, = plt.plot(t, ys, color='green', label="ys")
l3, = plt.plot(t, zs, color='red', label="zs")
plt.legend(loc="lower left")
plt.xlabel("Time (sec)")
plt.ylabel("Acceleration (cm/s^2)")
plt.grid()
plt.axis([0, 5, -3000, 3000])

axcolor = 'lightgoldenrodyellow'
axpos = plt.axes([0.2, 0.1, 0.65, 0.03], facecolor=axcolor)

spos = Slider(axpos, 'Second', 0.1, float((length / 10) - 5))


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


spos.on_changed(update)

plt.show()
Ejemplo n.º 45
0
        l.append(0)
        v.append(0)
        l[k] = ax.plot(omega/(2*np.pi), var_plot, '-') #, label='Mismatch phase = {}°'.format(phase_mm[k] * 180 / np.pi)
#        plt.legend()
        v[k] = ax.plot(omega/(2*np.pi), var_plot_vac, '--', color='black', linewidth=1)
        
    if sliders:
        
        axcolor = 'lightgoldenrodyellow'
        axangle = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor)
        axdetuning = plt.axes([0.25, 0.15, 0.65, 0.03], facecolor=axcolor)
        axtransmission = plt.axes([0.25, 0.2, 0.65, 0.03], facecolor=axcolor)
        axfreqmin = plt.axes([0.25, 0.25, 0.1, 0.05], facecolor=axcolor)
        axfreqmax = plt.axes([0.6, 0.25, 0.1, 0.05], facecolor=axcolor)
        
        sangle = Slider(axangle, 'Homodyne angle (°)', 0, 180, valinit=angle_init, valstep=angle_step)
        sdetuning = Slider(axdetuning, 'Detuning (MHz)', detuning_min, detuning_max, valinit=detuning_init, valstep=detuning_step)
        stransmission = Slider(axtransmission, 'Input mirror transmission', transmission_min, transmission_max, valinit=transmission_init, valstep=transmission_step)
        sfreqmin = TextBox(axfreqmin, 'Min frequency (MHz)', initial=str(freq_min * 1e-6), color='.95', hovercolor='1')
        sfreqmax = TextBox(axfreqmax, 'Max frequency (MHz)', initial=str(freq_max * 1e-6), color='.95', hovercolor='1')
        
        def update(val):
            angle = np.pi * sangle.val /180
            detuning = 2 * np.pi * sdetuning.val * 1e6
            transmission = stransmission.val
            omega_min = 2 * np.pi * float(sfreqmin.text) * 1e6 #s-1
            omega_max = 2 * np.pi * float(sfreqmax.text) * 1e6 #s-1 <- range of sideband frequencies observed
    #        nb_freq = 1000 # <- freq resolution
            omega = np.linspace(omega_min, omega_max, nb_freq)
            for k in range(len(phase_mm)):
                var_plot = np.zeros(nb_freq)
Ejemplo n.º 46
0
    def __init__(self,
                 normalized_worm,
                 motion_mode=None,
                 interactive=False,
                 interpolate_nan_frames=False):
        """ 
        Initialize the animation of the worm's attributes.

        Parameters
        ---------------------------------------
        normalized_worm: NormalizedWorm
          the NormalizedWorm object to be plotted.

        motion_mode: 1-dimensional numpy array (optional)
          The motion mode of the worm over time.  Must have 
          length = normalized_worm.num_frames

        interactive: boolean (optional)
          if interactive is set to False, then:
            suppress the drawing of the figure, until an explicit plt.show()
            is called.  this allows NormalizedWormPlottable to be instantiated 
            without just automatically being displayed.  Instead, the user 
            must call NormalizedWormPlottable.show() to have plt.show() be 
            called.
            
        interpolate_nan_frames: interpolate the flickering nan frames
            Note: this is currently not implemented

        Notes
        ---------------------------------------
        To initialize the animation, we must do six things:
          1. set up the data to be used from the normalized_worm
          2. create the figure
          3. create subplots in the figure, assigning them Axis handles
          4. create Artist objects for all objects in the subplots 
          5. assign the Artist objects to the correct Axis handle
          6. call the base class __init__

        """
        # A NormalizedWormPlottable instance can be instantiated to be
        # interactive, or by default it is set to NOT interactive, which
        # means that NormalizedWormPlottable.show() must be called to get
        # it to display.
        plt.interactive(interactive)

        self._paused = False

        # 1. set up the data to be used
        self.nw = normalized_worm
        self.motion_mode = motion_mode
        self.motion_mode_options = {-1: 'backward', 0: 'paused', 1: 'forward'}
        self.motion_mode_colours = {
            -1: 'b',  # blue
            0: 'r',  # red
            1: 'g'
        }  # green

        # 2. create the figure
        fig = plt.figure(figsize=(5, 5))

        # We have blit=True, so the animation only redraws the elements that
        # have changed.  This means that if the window is resized, everything
        # other than the plot area will be black.  To fix this, here we have
        # matplotlib explicitly redraw everything if a resizing event occurs.
        # DEBUG: this actually doesn't appear to work.
        def refresh_plot(event):
            print("refresh_plot called")

            # We must reset this or else repetitive expanding and contracting
            # of the window will cause the view to zoom in on the subplots
            self.set_axes_extents()

            fig.canvas.draw()

        self.refresh_connection_id = fig.canvas.mpl_connect(
            'resize_event', refresh_plot)

        fig.suptitle('C. elegans attributes', fontsize=20)

        # 3. Add the subplots
        self.ax1 = plt.subplot2grid((3, 3), (0, 0), rowspan=2, colspan=2)
        self.ax1.set_title('Position')
        self.ax1.plot(self.nw.skeleton[0, 0, :], self.nw.skeleton[0, 1, :])
        self.ax1.set_xlabel('x')
        self.ax1.set_ylabel('y')
        #ax1.set_aspect(aspect='equal', adjustable='datalim')
        # ax1.set_autoscale_on()

        self.annotation1a = \
                       self.ax1.annotate("(motion mode data not available)",
                                         xy=(-10, 10), xycoords='axes points',
                                         horizontalalignment='right',
                                         verticalalignment='top',
                                         fontsize=10)

        self.annotation1b = \
                       self.ax1.annotate("bottom right (points)",
                                         xy=(-10, 10), xycoords='axes points',
                                         horizontalalignment='right',
                                         verticalalignment='bottom',
                                         fontsize=10)

        # WIDGETS
        # [left,botton,width,height] as a proportion of
        # figure width and height
        frame_slider_axes = fig.add_axes([0.2, 0.02, 0.33, 0.02],
                                         axisbg='lightgoldenrodyellow')
        self.frame_slider = Slider(frame_slider_axes,
                                   label='Frame#',
                                   valmin=1,
                                   valmax=self.nw.num_frames,
                                   valinit=1,
                                   valfmt=u'%d')

        def frame_slider_update(val):
            print("Slider value: %d" % round(val, 0))
            self.frame_seq = self.new_frame_seq(int(round(val, 0)))

            fig.canvas.draw()

        self.frame_slider.on_changed(frame_slider_update)

        button_axes = fig.add_axes([0.8, 0.025, 0.1, 0.04])
        #ax4 = plt.subplot2grid((3, 3), (2, 2))
        button = Button(button_axes,
                        'Pause',
                        color='lightgoldenrodyellow',
                        hovercolor='0.975')

        def pause(event):
            if not self._paused:
                self._stop()
            else:
                self.event_source = fig.canvas.new_timer()
                self.event_source.interval = self._interval
                self._start()

            # Toggle the paused state
            self._paused = 1 - self._paused

        button.on_clicked(pause)

        self.ax2 = plt.subplot2grid((3, 3), (0, 2))
        self.ax2.set_title('Morphology')
        self.ax2.set_aspect(aspect='equal', adjustable='datalim')
        self.annotation2 = self.ax2.annotate(
            "Worm head",
            xy=(0, 0),
            xycoords='data',
            xytext=(10, 10),
            textcoords='data',
            arrowprops=dict(arrowstyle="fancy", connectionstyle="arc3,rad=.2"))

        self.ax3 = plt.subplot2grid((3, 3), (1, 2))
        self.ax3.set_title('Orientation-free')
        # DON'T USE set_xbound, it changes dynmically
        self.ax3.set_aspect(aspect='equal', adjustable='datalim')

        # Length and Area over time
        self.ax4a = plt.subplot2grid((3, 3), (2, 0), rowspan=1, colspan=2)
        self.ax4a.plot(self.nw.length, 'o-')
        self.ax4a.set_title('Length and Area over time')
        self.ax4a.set_ylabel('Microns')

        self.ax4b = self.ax4a.twinx()
        self.ax4b.plot(self.nw.area, 'xr-')
        self.ax4b.set_ylabel('Microns ^ 2')

        # Widths and Angles
        self.ax5a = plt.subplot2grid((3, 3), (2, 2))
        self.ax5a.set_title('Widths and Angles')
        self.ax5a.set_xlabel('Skeleton point')
        self.widths = Line2D([], [])
        self.ax5a.set_ylabel('Microns')

        self.ax5b = self.ax5a.twinx()
        self.angles = Line2D([], [])
        self.ax5b.set_ylabel('Degrees')

        # 4. create Artist objects
        self.time_marker = Line2D([], [])

        self.line1W = Line2D([], [],
                             color='green',
                             linestyle='point marker',
                             marker='o',
                             markersize=5)
        self.line1W_head = Line2D([], [],
                                  color='red',
                                  linestyle='point marker',
                                  marker='o',
                                  markersize=7)
        self.line1C = Line2D([], [],
                             color='yellow',
                             linestyle='point marker',
                             marker='o',
                             markersize=5)
        self.patch1E = Ellipse(xy=(0, 0),
                               width=1000,
                               height=500,
                               angle=0,
                               alpha=0.3)

        self.line2W = Line2D([], [], color='black', marker='o', markersize=5)
        self.line2W_head = Line2D([], [],
                                  color='red',
                                  linestyle='point marker',
                                  marker='o',
                                  markersize=7)
        self.line2C = Line2D([], [], color='blue')
        self.line2C2 = Line2D([], [], color='orange')

        self.line3W = Line2D([], [], color='black', marker='o', markersize=5)
        self.line3W_head = Line2D([], [],
                                  color='red',
                                  linestyle='point marker',
                                  marker='o',
                                  markersize=7)

        self.artists_with_data = [
            self.line1W, self.line1W_head, self.line1C, self.line2W,
            self.line2W_head, self.line2C, self.line2C2, self.line3W,
            self.line3W_head, self.widths, self.angles, self.time_marker
        ]

        # This list is a superset of self.artists_with_data
        self.artists_to_be_drawn = ([
            self.patch1E, self.annotation1a, self.annotation1b,
            self.annotation2
        ] + self.artists_with_data)

        self.set_axes_extents()

        # 5. assign Artist objects to the relevant subplot
        self.ax1.add_line(self.line1W)
        self.ax1.add_line(self.line1W_head)
        self.ax1.add_line(self.line1C)
        self.ax1.add_artist(self.patch1E)

        self.ax2.add_line(self.line2W)
        self.ax2.add_line(self.line2W_head)
        self.ax2.add_line(self.line2C)
        self.ax2.add_line(self.line2C2)

        self.ax3.add_line(self.line3W)
        self.ax3.add_line(self.line3W_head)

        self.ax4a.add_line(self.time_marker)

        self.ax5a.add_line(self.widths)
        self.ax5b.add_line(self.angles)

        # So labels don't overlap:
        #plt.tight_layout()

        # 6. call the base class __init__

        # TimedAnimation draws a new frame every *interval* milliseconds.
        # so this is how we convert from FPS to interval:
        interval = 1000 / self.nw.video_info.fps

        return animation.TimedAnimation.__init__(self,
                                                 fig,
                                                 interval=interval,
                                                 blit=True)
ax1.set_ylim(-0.1, 1)
ax.set_xlabel('Time')
ax.set_ylabel('Synaptic Paramter')

axcolor = 'lightgoldenrodyellow'
axsInject = plt.axes([0.6, 0.7, 0.35, 0.04], facecolor=axcolor)
axsg_AM_E = plt.axes([0.6, 0.65, 0.35, 0.04], facecolor=axcolor)
axsg_AM_I = plt.axes([0.6, 0.6, 0.35, 0.04], facecolor=axcolor)
axsg_GABA_E = plt.axes([0.6, 0.55, 0.35, 0.04], facecolor=axcolor)
axsg_GABA_I = plt.axes([0.6, 0.50, 0.35, 0.04], facecolor=axcolor)
axstau_G = plt.axes([0.6, 0.45, 0.35, 0.04], facecolor=axcolor)
axstau_A = plt.axes([0.6, 0.40, 0.35, 0.04], facecolor=axcolor)
axh = plt.axes([-1, -1, 1, 1])

# Make sliders that control parameters
sInj = Slider(axsInject, r'Current', 0, 2, valinit=0.14, color='maroon')
sg_AM_E = Slider(axsg_AM_E,
                 r'AM E',
                 0,
                 10.0,
                 valinit=1.8,
                 color='midnightblue')
sg_AM_I = Slider(axsg_AM_I,
                 r'AM I',
                 0.0,
                 10.0,
                 valinit=1,
                 color='midnightblue')
sg_GABA_E = Slider(axsg_GABA_E,
                   r'GABA E',
                   0.0,
Ejemplo n.º 48
0
# Add the first image
ax.imshow(img)
ax.set_xticks([])
ax.set_yticks([])
ax.set_title("Original Image")
# add the first image again (since initially there should be no filtering)
ax2.imshow(img)
ax2.set_xticks([])
ax2.set_yticks([])
ax2.set_title("Blurred Image")

# Add a slider for our blurring Kernel

# Define an axes area and draw a slider in it
kernel_slider_ax = fig.add_axes([0.25, 0.15, 0.65, 0.03])
kernel_slider = Slider(kernel_slider_ax, 'Kernel Size', 1, 10)


# When the slider changes, we replace the original image (ax2 version) with the blurred image
def sliders_on_changed(val):
    # Have to cast the slider value as an int to properly calculate the kernel
    ax2.imshow(blurred_image((int)(kernel_slider.val)))
    fig.canvas.draw_idle()


kernel_slider.on_changed(sliders_on_changed)

# Add a button for resetting the parameters
reset_button_ax = fig.add_axes([0.8, 0.025, 0.1, 0.04])
reset_button = Button(reset_button_ax, 'Reset', hovercolor='0.975')
Ejemplo n.º 49
0
def main(argv=None):
    if argv is None:
        argv = sys.argv

    if len(argv) != 2:
        print("usage: %s SIMNAME" % os.path.basename(sys.argv[0]))
        return 2

    # process arguments
    simname = argv[1]

    tslice = 0

    # read elapsed hour/datetime key file
    dts, hrs = pltutils.timekeys(simname)
    nts = len(dts)
    datetimes = []
    for dt in dts:
        datetimes.append(datetime.strftime(dt, "%Y-%m-%d %H:%M:%S"))

    # read data files

    # cair
    z, acair = pltutils.get1Dvar(simname, "met", "cair")
    cair = acair[:, tslice]

    # h2o
    z, ah2o = pltutils.get1Dvar(simname, "met", "h2o")
    h2o = ah2o[:, tslice]

    # kv
    z, akv = pltutils.get1Dvar(simname, "met", "kv")
    kv = akv[:, tslice]

    # pmb
    z, apmb = pltutils.get1Dvar(simname, "met", "pmb")
    pmb = apmb[:, tslice]

    # ppfd
    z, appfd = pltutils.get1Dvar(simname, "met", "ppfd")
    ppfd = appfd[:, tslice]

    # qh
    z, aqh = pltutils.get1Dvar(simname, "met", "qh")
    qh = aqh[:, tslice]

    # rh
    z, arh = pltutils.get1Dvar(simname, "met", "rh")
    rh = arh[:, tslice]

    # tk
    z, atk = pltutils.get1Dvar(simname, "met", "tk")
    tk = atk[:, tslice]

    # ubar
    z, aubar = pltutils.get1Dvar(simname, "met", "ubar")
    ubar = aubar[:, tslice]

    # create the plots
    fig = plt.figure(figsize=(12, 12))

    # air density (molec/cm3)
    ax1 = fig.add_subplot(2, 4, 1)
    pcair, = ax1.plot(cair,
                      z,
                      color=colors[3],
                      linestyle="-",
                      marker="None",
                      linewidth=lnwdth,
                      label="c$_{air}$")
    pltutils.setstdfmts(ax1, tlmaj, tlmin, tlbsize, tlbpad)
    plt.legend(loc=4, fontsize=lfsize, bbox_to_anchor=(0.85, 0.05))
    #  plt.xlim(xmax=1.0, xmin=0.0)
    plt.ylim(ymax=43.0, ymin=0.0)

    # water density (molecules/cm3)
    ax2 = fig.add_subplot(2, 4, 2)
    ph2o, = ax2.plot(h2o,
                     z,
                     color=colors[3],
                     linestyle="-",
                     marker="None",
                     linewidth=lnwdth,
                     label="H$_2$O")
    pltutils.setstdfmts(ax2, tlmaj, tlmin, tlbsize, tlbpad)
    plt.legend(loc=4, fontsize=lfsize, bbox_to_anchor=(0.55, 0.05))
    #  plt.xlim(xmax=1200.0, xmin=-100.0)
    plt.ylim(ymax=43.0, ymin=0.0)

    # eddy diffusivity (cm2/s)
    ax3 = fig.add_subplot(2, 4, 3)
    pkv, = ax3.plot(kv,
                    z,
                    color=colors[4],
                    linestyle="-",
                    marker="None",
                    linewidth=lnwdth,
                    label="K$_{v}$")
    pltutils.setstdfmts(ax3, tlmaj, tlmin, tlbsize, tlbpad)
    plt.legend(loc=4, fontsize=lfsize, bbox_to_anchor=(0.95, 0.05))
    plt.ylim(ymax=43.0, ymin=0.0)

    # air pressure (mb)
    ax4 = fig.add_subplot(2, 4, 4)
    ppmb, = ax4.plot(pmb,
                     z,
                     color=colors[3],
                     linestyle="-",
                     marker="None",
                     linewidth=lnwdth,
                     label="p$_{air}$")
    pltutils.setstdfmts(ax4, tlmaj, tlmin, tlbsize, tlbpad)
    #  plt.xlabel("$\mu$mol m$^{-2}$ s$^{-1}$", fontsize=xfsize, labelpad=xtpad)
    plt.legend(loc=4, fontsize=lfsize, bbox_to_anchor=(0.95, 0.05))
    #  plt.xlim(xmax=20., xmin=-1.)
    plt.ylim(ymax=43.0, ymin=0.0)

    # ppfd
    ax5 = fig.add_subplot(2, 4, 5)
    pppfd, = ax5.plot(ppfd,
                      z,
                      color=colors[3],
                      linestyle="-",
                      marker="None",
                      linewidth=lnwdth,
                      label="PPFD")
    pltutils.setstdfmts(ax5, tlmaj, tlmin, tlbsize, tlbpad)
    #  plt.xlabel("W/m$^2$", fontsize=xfsize, labelpad=xtpad)
    plt.legend(loc=4, fontsize=lfsize, bbox_to_anchor=(0.65, 0.05))
    #  plt.xlim(xmax=1200.0, xmin=-100.0)
    plt.ylim(ymax=43.0, ymin=0.0)

    # qh
    ax6 = fig.add_subplot(2, 4, 6)
    pqh, = ax6.plot(qh,
                    z,
                    color=colors[3],
                    linestyle="-",
                    marker="None",
                    linewidth=lnwdth,
                    label="q$_h$")
    pltutils.setstdfmts(ax6, tlmaj, tlmin, tlbsize, tlbpad)
    #  plt.xlabel("W/m$^2$", fontsize=xfsize, labelpad=xtpad)
    plt.legend(loc=4, fontsize=lfsize, bbox_to_anchor=(0.65, 0.05))
    #  plt.xlim(xmax=1200.0, xmin=-100.0)
    plt.ylim(ymax=43.0, ymin=0.0)

    # rh
    ax7 = fig.add_subplot(2, 4, 7)
    prh, = ax7.plot(rh,
                    z,
                    color=colors[3],
                    linestyle="-",
                    marker="None",
                    linewidth=lnwdth,
                    label="RH")
    pltutils.setstdfmts(ax7, tlmaj, tlmin, tlbsize, tlbpad)
    #  plt.xlabel("W/m$^2$", fontsize=xfsize, labelpad=xtpad)
    plt.legend(loc=4, fontsize=lfsize, bbox_to_anchor=(0.65, 0.05))
    #  plt.xlim(xmax=500.0, xmin=-20.0)
    plt.ylim(ymax=43.0, ymin=0.0)

    # ubar
    ax8 = fig.add_subplot(2, 4, 8)
    pubar, = ax8.plot(ubar,
                      z,
                      color=colors[3],
                      linestyle="-",
                      marker="None",
                      linewidth=lnwdth,
                      label="u$_{mean}$")
    #  xmin, xmax = ax8.get_xlim()
    #  plt.xticks(np.arange(xmin, xmax+1, 1000.))
    pltutils.setstdfmts(ax8, tlmaj, tlmin, tlbsize, tlbpad)
    #  plt.xlabel("s m$^{-1}$", fontsize=xfsize, labelpad=xtpad)
    plt.legend(loc=4, fontsize=lfsize, bbox_to_anchor=(0.95, 0.05))
    #  plt.xlim(xmax=2000., xmin=-100.)
    plt.ylim(ymax=43.0, ymin=0.0)

    psupttle = plt.suptitle(simname + " - " + datetimes[tslice],
                            fontsize=tfsize,
                            y=tyloc)

    # make room for the slider
    plt.subplots_adjust(bottom=0.15)

    # make a slider to control the time slice
    slidercolor = "cyan"
    axtime = plt.axes([0.25, 0.03, 0.55, 0.02], facecolor=slidercolor)
    time_slider = Slider(ax=axtime,
                         label="Time",
                         valmin=0,
                         valmax=nts - 1,
                         valstep=1,
                         valinit=0)

    # update function for the slider
    def update(val):
        tslice = int(time_slider.val)
        psupttle.set_text(simname + " - " + datetimes[tslice])
        xmax = np.amax(acair[:, tslice])
        xmin = np.amin(acair[:, tslice])
        pcair.set_xdata(acair[:, tslice])
        ax1.set_xlim(xmax=xmax * 1.1, xmin=xmin * 0.95)

        xmax = np.amax(ah2o[:, tslice])
        xmin = np.amin(ah2o[:, tslice])
        ph2o.set_xdata(ah2o[:, tslice])
        ax2.set_xlim(xmax=xmax * 1.1, xmin=xmin * 0.95)

        xmax = np.amax(akv[:, tslice])
        pkv.set_xdata(akv[:, tslice])
        ax3.set_xlim(xmax=xmax * 1.1, xmin=-20.0)

        xmax = np.amax(apmb[:, tslice])
        xmin = np.amin(apmb[:, tslice])
        ppmb.set_xdata(apmb[:, tslice])
        ax4.set_xlim(xmax=xmax * 1.1, xmin=xmin * 0.95)

        xmax = np.amax(appfd[:, tslice])
        xmin = np.amin(appfd[:, tslice])
        pppfd.set_xdata(appfd[:, tslice])
        ax5.set_xlim(xmax=2500., xmin=-20.0)

        xmax = np.amax(aqh[:, tslice])
        xmin = np.amin(aqh[:, tslice])
        pqh.set_xdata(aqh[:, tslice])
        ax6.set_xlim(xmax=xmax * 1.1, xmin=xmin * 0.95)

        xmax = np.amax(arh[:, tslice])
        xmin = np.amin(arh[:, tslice])
        prh.set_xdata(arh[:, tslice])
        ax7.set_xlim(xmax=100., xmin=0.0)

        xmax = np.amax(aubar[:, tslice])
        xmin = np.amin(aubar[:, tslice])
        pubar.set_xdata(aubar[:, tslice])
        ax8.set_xlim(xmax=xmax * 1.1, xmin=0.0)

        fig.canvas.draw_idle()

    # register the update function with the slider
    time_slider.on_changed(update)

    # allow slider to be moved by "left" and "right" arrow keys
    def onarrow(event):
        if event.key == "left":
            if (time_slider.val == 0):
                val = 0
            else:
                val = time_slider.val - 1
            time_slider.set_val(val)
        elif event.key == "right":
            if (time_slider.val == (nts - 1)):
                val = nts - 1
            else:
                val = time_slider.val + 1
            time_slider.set_val(val)
        else:
            pass

    # bind key event to the arrow key handler
    kid = fig.canvas.mpl_connect("key_press_event", onarrow)

    plt.show()

    return 0
Ejemplo n.º 50
0
    def __init__(self, name):

        self.name = name
        self.data = None
        self.xspace = None
        self.fit = None
        self.peak = {}
        self.bounds = {
            'Background': [-np.inf, np.inf],
        }
        self.current_peak = None
        self.background = 0

        self.fig = plt.figure("Curvefit", figsize=(8, 8))
        self.mainAx = self.fig.add_axes([0.1, 0.3, 0.7, 0.6])
        #self.mainAx.plot(data[0], data[1], ".")

        ##button axes#####
        self.buttonAx = {}
        self.button = {}
        self.buttonState = {
            'Add': False,
            'Gauss': False,
            'Lorentz': False,
        }

        self.buttonAx['Add'] = plt.axes([0.83, 0.82, 0.1, 0.075])
        self.button['Add'] = Button(self.buttonAx['Add'], 'Add', color='grey')
        self.button['Add'].on_clicked(self.add_clicked)

        self.buttonAx['Gauss'] = plt.axes([0.83, 0.72, 0.1, 0.075])
        self.button['Gauss'] = Button(self.buttonAx['Gauss'],
                                      'Gauss',
                                      color='grey')
        self.button['Gauss'].on_clicked(self.gauss_clicked)

        self.buttonAx['Lorentz'] = plt.axes([0.83, 0.62, 0.1, 0.075])
        self.button['Lorentz'] = Button(self.buttonAx['Lorentz'],
                                        'Lorentz',
                                        color='grey')
        self.button['Lorentz'].on_clicked(self.lorentz_clicked)

        ###

        #        self.buttonAx['AmpBound'] = plt.axes([0.65, 0.2, 0.065, 0.03])
        #        self.button['AmpBound'] = Button(self.buttonAx['AmpBound'] ,'Bound', color='grey')
        #
        #        self.buttonAx['MeanBound'] = plt.axes([0.65, 0.15, 0.065, 0.03])
        #        self.button['MeanBound'] = Button(self.buttonAx['MeanBound'] ,'Bound', color='grey')

        #        self.buttonAx['StdBound+'] = plt.axes([0.65, 0.10, 0.04, 0.03])
        #        self.button['StdBound+'] = Button(self.buttonAx['StdBound+'] ,'+', color='grey')
        #        self.button['StdBound+'].on_clicked(self.std_up_bound_clicked)
        #        self.buttonAx['StdBound-'] = plt.axes([0.60, 0.10, 0.04, 0.03])
        #        self.button['StdBound-'] = Button(self.buttonAx['StdBound-'] ,'-', color='grey')
        #        self.button['StdBound-'].on_clicked(self.std_low_bound_clicked)

        #        self.buttonAx['BgBound+'] = plt.axes([0.65, 0.05, 0.04, 0.03])
        #        self.button['BgBound+'] = Button(self.buttonAx['BgBound+'], '+', color ='grey')
        #        self.button['BgBound+'].on_clicked(self.bg_up_bound_clicked)
        #        self.buttonAx['BgBound-'] = plt.axes([0.60, 0.05, 0.04, 0.03])
        #        self.button['BgBound-'] = Button(self.buttonAx['BgBound-'], '-', color ='grey')
        #        self.button['BgBound-'].on_clicked(self.bg_low_bound_clicked)
        #        ###
        #
        self.buttonAx['Peak-'] = plt.axes([0.83, 0.5, 0.035, 0.03])
        self.button['Peak-'] = Button(self.buttonAx['Peak-'],
                                      '<',
                                      color='grey')
        self.button['Peak-'].on_clicked(self.toggle_peaks_left)

        self.peak_number_ax = plt.axes([0.85, 0.54, 0.06, 0.03])
        self.peak_number_ax.set_axis_off()
        self.buttonAx['Peak+'] = plt.axes([0.895, 0.5, 0.035, 0.03])
        self.button['Peak+'] = Button(self.buttonAx['Peak+'],
                                      '>',
                                      color='grey')
        self.button['Peak+'].on_clicked(self.toggle_peaks_right)

        self.buttonAx['Save'] = plt.axes([0.83, 0.32, 0.1, 0.075])
        self.button['Save'] = Button(self.buttonAx['Save'],
                                     "Save",
                                     color='grey')
        self.button['Save'].on_clicked(self.save_fit)

        ##sliders#####
        self.sliderAx = {}
        self.slider = {}
        self.sliderVals = {'Amp': 0.5, 'Mean': 0.5, 'Std': 0.5}

        self.sliderAx['Amp'] = plt.axes([0.15, 0.2, 0.25, 0.03])
        self.slider['Amp'] = Slider(self.sliderAx['Amp'],
                                    "Amp",
                                    0,
                                    1,
                                    valinit=0.5,
                                    color='grey')
        self.slider['Amp'].on_changed(self.amp_slider_changed)

        self.sliderAx['Mean'] = plt.axes([0.15, 0.15, 0.25, 0.03])
        self.slider['Mean'] = Slider(self.sliderAx['Mean'],
                                     "Mean",
                                     0,
                                     1,
                                     valinit=0.5,
                                     color='grey')

        self.sliderAx['Std'] = plt.axes([0.15, 0.10, 0.25, 0.03])
        self.slider['Std'] = Slider(self.sliderAx['Std'],
                                    "Std",
                                    0,
                                    4,
                                    valinit=2,
                                    color='grey')
        self.slider['Std'].on_changed(self.std_slider_changed)

        self.sliderAx['Bg'] = plt.axes([0.15, 0.05, 0.25, 0.03])
        self.slider['Bg'] = Slider(self.sliderAx['Bg'],
                                   "Bg",
                                   0,
                                   1,
                                   valinit=0.5,
                                   color='grey')
        self.slider['Bg'].on_changed(self.bg_slider_changed)

        #TEXT BOX

        self.textboxAx = {}
        self.textbox = {}

        self.textboxAx['Bg'] = plt.axes([0.5, 0.05, 0.06, 0.03])
        self.textbox['Bg'] = TextBox(self.textboxAx['Bg'], "", "0")
        self.textbox['Bg'].on_submit(self.bg_submit)

        self.textboxAx['Std'] = plt.axes([0.5, 0.10, 0.06, 0.03])
        self.textbox['Std'] = TextBox(self.textboxAx['Std'], "", "0")
        self.textbox['Std'].on_submit(self.std_submit)

        self.textboxAx['Mean'] = plt.axes([0.5, 0.15, 0.06, 0.03])
        self.textbox['Mean'] = TextBox(self.textboxAx['Mean'], "", "0")
        self.textbox['Mean'].on_submit(self.mean_submit)

        self.textboxAx['Amp'] = plt.axes([0.5, 0.2, 0.06, 0.03])
        self.textbox['Amp'] = TextBox(self.textboxAx['Amp'], "", "0")
        self.textbox['Amp'].on_submit(self.amp_submit)

        self.clickid = self.fig.canvas.mpl_connect('button_press_event',
                                                   self.mainAx_click)

        ####
        self.datapoints = None
Ejemplo n.º 51
0
        plt.draw  # redraw the plot


#button_declaration
axButton = plt.axes([0.92, 0.6, 0.06, 0.06])  #xloc,yloc,width,heights
btn = Button(axButton, ' ADD ')

#button on click callback function
btn.on_clicked(setValue)

#Sliders declaration
axSlider1 = plt.axes([0.1, 0.20, 0.55, 0.02])  #xloc,yloc,width,height
slider1 = Slider(ax=axSlider1,
                 label='Tox',
                 valmin=1 * 10**(-9),
                 valmax=5 * 10**(-9),
                 valinit=tox,
                 valfmt='tox is ' + '%1.11f' + ' in m',
                 color="green")

axSlider2 = plt.axes([0.1, 0.15, 0.55, 0.02])  #xloc,yloc,width,height
slider2 = Slider(axSlider2,
                 'NA',
                 valmin=1,
                 valmax=20,
                 valinit=NA / (10**23),
                 valfmt='NA is ' + '%1.2f' + ' in 10**23 m^-3')

axSlider3 = plt.axes([0.1, 0.10, 0.55, 0.02])  #xloc,yloc,width,height
slider3 = Slider(axSlider3,
                 'Phi_m',
Ejemplo n.º 52
0
edges = camimg
edges = cv2.Canny(edges, 50, 100)

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

plt.subplot(1, 2, 1), plt.imshow(camimg, cmap='gray')
plt.title('Original'), plt.xticks([]), plt.yticks([])

plt.subplot(1, 2, 2)
edge_plot = plt.imshow(edges, cmap='gray')
plt.title('Edges'), plt.xticks([]), plt.yticks([])

axcolor = 'lightgoldenrodyellow'
axupper = plt.axes([0.15, 0.15, 0.7, 0.03], axisbg=axcolor)
upper = Slider(axupper, 'Upper', 0, 255, valinit=100)

axlower = plt.axes([0.15, 0.1, 0.7, 0.03], axisbg=axcolor)
lower = Slider(axlower, 'Lower', 0, 255, valinit=50)


def update(val):
    global edges

    edges = camimg
    edges = cv2.Canny(edges, lower.val, upper.val)
    """
    contours = measure.find_contours(edges, 0.5)
    contours.sort(key=lambda x: -len(x))
    final = []
    for cont in contours[:ncont]:
Ejemplo n.º 53
0
vcirc_tot = np.sqrt(vcirc_bulge**2 + vcirc_disk**2 + vcirc_halo**2)

plot4_disk, = ax4.plot(mymdar.r, vcirc_disk, label='disk')
plot4_halo, = ax4.plot(mymdar.r, vcirc_halo, label='halo')
plot4_bulge, = ax4.plot(mymdar.r, vcirc_bulge, label='bulge')
plot4_tot, = ax4.plot(mymdar.r, vcirc_tot, label='total')

ax4.set_xlim(0, 40)
ax4.set_ylim(0, 300)

#a.plot_galaxy(ax=ax3)

#mymdar.plot_vcirc(ax=ax4)
#ax4.legend(loc='upper left', ncol=2, frameon=False)

s_Mgal = Slider(ax_Mgal, 'Mbar', 3, 15.0, valinit=np.log10(Mgal))
s_Rh = Slider(ax_Rh, 'R50', 0.01, 15.0, valinit=Rh)
s_m200 = Slider(ax_m200, 'M200', 10, 14, valinit=np.log10(M200))
s_fmbulge = Slider(ax_fmbulge, 'Bul_frac', 0.01, 1.0, valinit=f_mbulge)
s_fabulge = Slider(ax_fabulge, 'Bul_size', 0.01, 3.0, valinit=f_abulge)

data_behroozi = np.loadtxt('m200-mstr.txt')
ax1.plot(np.log10(data_behroozi[:, 0]),
         np.log10(data_behroozi[:, 1] * data_behroozi[:, 0]),
         ls='--')

galaxy_mstr_mhalo, = ax1.plot(np.log10(mymdar.M200), np.log10(mymdar.Mgal),
                              'o')

mass_concentration = np.loadtxt('mass_concentration.txt')
get_concentration = interp1d(
Ejemplo n.º 54
0
        print 'flip map left and right'
    if inps.flip_ud:
        ax_v.invert_yaxis()
        print 'flip map up and down'

    # Colorbar
    cbar = fig_v.colorbar(img, orientation='vertical')
    cbar.set_label('Displacement [%s]' % inps.disp_unit)

    # Axes 2 - Time Slider
    ax_time = fig_v.add_axes([0.125, 0.1, 0.6, 0.07],
                             axisbg='lightgoldenrodyellow',
                             yticks=[])
    tslider = Slider(ax_time,
                     'Years',
                     tims[0],
                     tims[-1],
                     valinit=tims[inps.epoch_num])
    tslider.ax.bar(tims,
                   np.ones(len(tims)),
                   facecolor='black',
                   width=0.01,
                   ecolor=None)
    tslider.ax.set_xticks(
        np.round(np.linspace(tims[0], tims[-1], num=5) * 100) / 100)

    def time_slider_update(val):
        '''Update Displacement Map using Slider'''
        global fig_v, ax_v, img, mask, inps, tims
        timein = tslider.val
        idx_nearest = np.argmin(np.abs(np.array(tims) - timein))
ax1.set_xlim(0, 1)
ax1.set_ylim(0, 100)

axcolor = 'lightgoldenrodyellow'
axs_I = plt.axes([0.7, 0.85, 0.2, 0.03], axisbg=axcolor)
axs_A = plt.axes([0.7, 0.5, 0.2, 0.03], axisbg=axcolor)
axs_R = plt.axes([0.7, 0.6, 0.2, 0.03], axisbg=axcolor)
axs_C = plt.axes([0.7, 0.55, 0.2, 0.03], axisbg=axcolor)
axs_vl = plt.axes([0.7, 0.65, 0.2, 0.03], axisbg=axcolor)
axs_vth = plt.axes([0.7, 0.8, 0.2, 0.03], axisbg=axcolor)
axs_vres = plt.axes([0.7, 0.75, 0.2, 0.03], axisbg=axcolor)
axs_tref = plt.axes([0.7, 0.7, 0.2, 0.03], axisbg=axcolor)

# Make sliders that control parameters

s_I = Slider(axs_I, r'$I \, [nA]$', 0, 1.0, valinit=0.5, color='maroon')
s_A = Slider(axs_A,
             r'$A \, [mm^2\!]$',
             0.01,
             0.2,
             valinit=0.05,
             color='midnightblue')
s_R = Slider(axs_R,
             r'$r \, [M\Omega\ mm^2\!]$',
             0.1,
             10.0,
             valinit=2,
             color='midnightblue')
s_C = Slider(axs_C,
             r'$c \, [nF/mm^2\!]$',
             1.,
Ejemplo n.º 56
0
    def ishow(self):
        """
            interactive show of trajectories

        Examples
        --------

        .. plot::
            :include-source:

            >>> from pylayers.mobility.trajectory import *
            >>> T=Trajectories()
            >>> T.loadh5()
            >>> T.ishow()

        """

        fig, ax = plt.subplots()
        fig.subplots_adjust(bottom=0.2, left=0.3)

        t = np.arange(0, len(self[0].index), self[0].ts)
        L = Layout(self.Lfilename)
        fig, ax = L.showG('s', fig=fig, ax=ax)

        valinit = 0
        lines = []
        labels = []
        colors = "bgrcmykw"

        for iT, T in enumerate(self):
            if T.typ == 'ag':
                lines.extend(
                    ax.plot(T['x'][0:valinit],
                            T['y'][0:valinit],
                            'o',
                            color=colors[iT],
                            visible=True))
                labels.append(T.name + ':' + T.ID)
            else:
                lines.extend(
                    ax.plot(T['x'][0],
                            T['y'][0],
                            '^',
                            ms=12,
                            color=colors[iT],
                            visible=True))
                labels.append(T.name + ':' + T.ID)

        t = self[0].time()

        # init boolean value for visible in checkbutton
        blabels = [True] * len(labels)

        ########
        # slider
        ########
        slider_ax = plt.axes([0.1, 0.1, 0.8, 0.02])
        slider = Slider(slider_ax,
                        "time",
                        self[0].tmin,
                        self[0].tmax,
                        valinit=valinit,
                        color='#AAAAAA')

        def update(val):
            if val >= 1:
                pval = np.where(val > t)[0]
                ax.set_title(str(
                    self[0].index[pval[-1]].time())[:11].ljust(12),
                             loc='left')
                for iT, T in enumerate(self):
                    if T.typ == 'ag':
                        lines[iT].set_xdata(T['x'][pval])
                        lines[iT].set_ydata(T['y'][pval])
                fig.canvas.draw()

        slider.on_changed(update)

        ########
        # choose
        ########
        rax = plt.axes([0.02, 0.5, 0.3, 0.2], aspect='equal')
        # check (ax.object, name of the object , bool value for the obsject)
        check = CheckButtons(rax, labels, tuple(blabels))

        def func(label):
            i = labels.index(label)
            lines[i].set_visible(not lines[i].get_visible())
            fig.canvas.draw()

        check.on_clicked(func)
        fig.canvas.draw()
        plt.show(fig)
"""cuantas veces presentamos el estimulo y cuantas veces el sujeto responde al estimulo"""

ensayos = 60
estimulo = numpy.linspace(0, ensayos, ensayos)
valor_ud = numpy.zeros(len(estimulo))  #len dice longitud
"""parametros de la ley de weber"""

k = 1
c = [k] * ensayos  #constante de Weber repitela cuantas veces ensayos haya
S0 = 10  #umbral debajo del cual el estimulo es percibido
"""plots"""
fig, ax = plt.subplots(2)
plt.subplots_adjust(left=0.15, bottom=0.25)

ax_k = plt.axes([0.15, 0.1, 0.65, 0.03], axisbg='lightgoldenrodyellow')
slider_k = Slider(ax_k, 'k', .5, 1.5, valinit=k)

for i in range(len(estimulo)):
    if estimulo[i] <= S0:
        valor_ud[i] = 0
    else:
        valor_ud[i] = S0 + k * estimulo[i - S0]


def update(var):
    k = slider_k.val
    c = [k] * ensayos
    for i in range(len(estimulo)):
        if estimulo[i] <= S0:
            valor_ud[i] = 0
        else:
Ejemplo n.º 58
0
##########################################################################################################
fig, ax = plt.subplots()
plt.subplots_adjust(left=0.25, bottom=0.25)

f0 = 1
delta_f = 1

g = nx.random_k_out_graph(n=f0, k=2, alpha=0.5)

axcolor = 'lightgray'
axfreq = plt.axes([0.25, 0.06, 0.65, 0.03], facecolor=axcolor)

sfreq = Slider(axfreq,
               'noise',
               1,
               20,
               valinit=f0,
               valstep=delta_f,
               valfmt='%0.0f')

active_nodes = []
non_active_nodes = []

for i in range(number_of_clusters):
    Net.nodes[control_nodes[i]] = 1
for i in range(len(Net.nodes)):
    if Net.nodes[i] == 1:
        active_nodes.append(i)
    else:
        non_active_nodes.append(i)
Ejemplo n.º 59
0
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
for i in range(xlin.shape[0]):
    ax.plot(xlin[i], ylin[i], zlin[i])
s = np.zeros(v.shape[0])
c = np.zeros(v.shape[0])
val = 1
s = np.absolute(v[:, val - 1])
s = s * 300
c = np.where(v[:, val - 1] > 0, 0, 1)
Stateplot = ax.scatter(xyz[:, 0], xyz[:, 1], xyz[:, 2], zdir='z', s=s)
Stateplot.set_cmap("bwr")
plt.subplots_adjust(bottom=0.25)
axcolor = 'lightgoldenrodyellow'
axfreq = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor)
state = Slider(axfreq, 'State', 1, v.shape[0], valinit=1, valstep=1)


def update(val):
    val = state.val
    val = int(val)
    s = np.absolute(v[:, val - 1])
    s = s * 300
    print(s)
    c = np.where(v[:, val - 1] > 0, 0, 1)
    print(c)
    Stateplot._sizes = s
    Stateplot.set_array(c)
    fig.canvas.draw_idle()

Ejemplo n.º 60
0
def main():    
    fig, ax = plt.subplots()
    
    plt.subplots_adjust(left=0.12, bottom=0.4,top=0.8)
    phasesample = np.linspace(0,1,101)
    l, = ax.plot(phasesample,phasesample, lw=2)
    ax.set_ylabel("rel. flux (%)")
    ax.set_xlabel("phase")
    ax.set_ylim(-10,10)
    ax.margins(x=0)
    
    topax = ax.twiny()
    topax.set_xticks([0,0.25,0.5,0.75,1])
    topax.set_xticklabels(['farthest','toward','nearest','away','farthest'])
    
    axcolor = 'lightgoldenrodyellow'
    
    axteff = plt.axes([0.25, 0.05, 0.6, 0.03], facecolor=axcolor)
    axlogg = plt.axes([0.25, 0.1, 0.6, 0.03], facecolor=axcolor)
    axporb = plt.axes([0.25, 0.15, 0.6, 0.03], facecolor=axcolor)
    axk = plt.axes([0.25, 0.2, 0.6, 0.03], facecolor=axcolor)
    axinc = plt.axes([0.25, 0.25, 0.6, 0.03], facecolor=axcolor)
    
    steff = Slider(axteff, 'Teff (K)', 8300, 30000, valinit=10000, valfmt=u'%1.0f') #valstep=50, 
    slogg = Slider(axlogg, 'log(g) (cgs)', 4, 7.4, valinit=5.5, valfmt=u'%1.1f') #valstep = 0.1, 
    sporb = Slider(axporb, 'P_orb (hours)', 0.25, 24, valinit=2 ) #valstep = 0.05
    sk = Slider(axk, 'K (km/s)', 20, 620, valinit=200,  valfmt=u'%1.0f') #valstep = 10,
    sinc = Slider(axinc, 'inc (deg)', 1, 90, valinit=45, valfmt=u'%1.0f') #valstep = 1, 
    
    def update(val):
        df = calc(teff=steff.val,logg=slogg.val,porb=sporb.val,k=sk.val,inc=sinc.val)
        l.set_ydata(-df["EV (%)"][0]*np.cos(phasesample*4*np.pi) + 
                    df["DB (%)"][0]*np.sin(phasesample*2*np.pi))
        
        for i in range(len(df.values[0])):
            mpl_table._cells[(1, i)]._text.set_text('%.4f' % df.values[0][i])
            
        fig.canvas.draw_idle()
    
    df = calc(teff=steff.val,logg=slogg.val,porb=sporb.val,k=sk.val,inc=sinc.val)

    axvals = plt.axes([0.12, 0.88, 0.78, 0.1], facecolor=axcolor)
    font_size=8
    bbox=[0, 0, 1, 1]
    axvals.axis('off')
    mpl_table = axvals.table(cellText = [['%.4f' % j for j in i] for i in df.values],
                             bbox=bbox, colLabels=df.columns)
    mpl_table.auto_set_font_size(False)
    mpl_table.set_fontsize(font_size)
    
    update(1)
    
    
    steff.on_changed(update)
    slogg.on_changed(update)
    sporb.on_changed(update)
    sk.on_changed(update)
    sinc.on_changed(update)
    
    plt.show()