def setup_plot():
	global rate_slider, delta_slider, fig, ax, l, radio
	fig, ax = plt.subplots()
	ax.grid('on')
	plt.subplots_adjust(left=0.25, bottom=0.25)
	moneyFmt = FuncFormatter(money)
	ax.yaxis.set_major_formatter(moneyFmt)

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

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

	rate_slider = Slider(axfreq, 'Avg.Returns', 4, 8, valinit=rate)
	delta_slider = Slider(axamp, 'Delta', 0.1, 1, valinit=delta)
	resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
	button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')
	rate_slider.on_changed(update)
	delta_slider.on_changed(update)
	button.on_clicked(reset)
	rax = plt.axes([0.015, 0.15, 0.15, 0.15], axisbg=axcolor)
	radio = RadioButtons(rax, ('0','3000', '6000', '9000'), active=0)
	radio.on_clicked(contribution_update)
	plt.show()
	return rate_slider,delta_slider,fig,ax,l,radio
Example #2
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)
def slide_ddg(args):
    global new_df, radio, color_by, picked
    global scat, ax, sliders, sc_df, fig, cm, cbar
    sc_df = Rf.score_file2df(args['sc'], args['names'])
    args['logger'].log('score file has %i entries' % len(sc_df))
    if args['pc'] is not None:
        pc_df = get_rmsds_from_table(args['pc'])
        args['logger'].log('pc file had %i entries' % len(pc_df))
        a = sc_df.merge(pc_df, on='description')
        args['logger'].log('combined there are %i entries' % len(a))
        sc_df = a.copy()

    if args['percent'] != 100:
        threshold = np.percentile(sc_df[args['y']], args['percent'])
        sc_df = sc_df[ sc_df[args['y']] < threshold ]

    color_by = args['y']
    picked = False

    new_df = sc_df.copy()
    fig, ax = plt.subplots()
    plt.subplots_adjust(left=0.25, bottom=0.25)

    cm = plt.cm.get_cmap('RdYlBu')

    scat = ax.scatter(sc_df[args['x']].values, sc_df[args['y']].values, s=40, cmap=cm, c=sc_df[color_by], picker=True)
    cbar = plt.colorbar(scat)
    sliders = {}
    for i, term in enumerate(args['terms']):
        slider_ax = plt.axes([0.25, 0.01+i*0.035, 0.65, 0.03])
        sliders[term] = Slider(slider_ax, term, np.min(sc_df[term].values), np.max(sc_df[term].values), 0)
        sliders[term].on_changed(update)

    ax.set_xlim(np.min(new_df[args['x']].values)-1, np.max(new_df[args['x']].values)+1)
    ax.set_ylim(np.min(new_df[args['y']].values)-1, np.max(new_df[args['y']].values)+1)

    ax.set_xlabel(args['x'])
    ax.set_ylabel(args['y'])

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

    printax = plt.axes([0.025, 0.3, 0.15, 0.15])
    printbutton = Button(printax, 'Print', color='green', hovercolor='red')
    printbutton.on_clicked(print_table)

    logax = plt.axes([0.025, 0.1, 0.15, 0.15])
    logbutton = Button(logax, 'log table', color='blue', hovercolor='red')
    logbutton.on_clicked(log_table)

    rax = plt.axes([0.025, 0.5, 0.15, 0.15], axisbg='white')
    radio = RadioButtons(rax, args['terms'], active=0)
    radio.on_clicked(colorfunc)

    # cbar = plt.colorbar(scat)
    pl = PointLabel(new_df, ax, fig, args['x'], args['y'], ['description', 'a_sasa', 'a_res_solv', 'a_pack', 'a_span_topo', 'a_ddg', 'fa_elec'], args['logger'])
    fig.canvas.mpl_connect('pick_event', pl.onpick)

    plt.show()
Example #4
0
class WidgetsBasic(WidgetsSimple):
    def __init__(self, canvas=None, active_prop=None):
        super(WidgetsBasic, self).__init__(canvas, active_prop)

        self.colors_ifs = {}

    @property
    def prop_ifs(self):
        return self.active_prop

    def update_show_components(self, label):
        super(WidgetsBasic, self).update_show_components(label)
        if label == "hide ifs":
            if self.holder_actives[label]:
                self.prop_ifs.holder.set_linestyle(" ")
                self.prop_ifs.holder.set_visible(False)
                self.prop_ifs.set_visible_annotations(False)
                self.prop_ifs.topo_const.set_visible(False)
            else:
                self.prop_ifs.holder.set_linestyle(" ")
                self.prop_ifs.holder.set_visible(True)
                self.prop_ifs.set_visible_annotations(True)
                self.prop_ifs.topo_const.set_visible(True)

    # here is updated the active prop_ifs
    def recreate_widgets(self, idx_active, props, active_prop):
        super(WidgetsBasic, self).recreate_widgets_(active_prop)
        self._recreate_active_ifs_radiobutton(idx_active, props)

    def _recreate_active_ifs_radiobutton(self, idx_active, props):
        self.props = props
        axcolor = "lightgoldenrodyellow"
        if hasattr(self, "rax_activeifs"):
            self.rax_activeifs.cla()
        self.rax_activeifs = plt.axes(
            [0.2 + self.button_length__ + 0.01, 0.05, self.button_length__, self.button_height__], axisbg=axcolor
        )
        activecolor = self.active_prop.get_color()
        self.w_rad_active_ifs = RadioButtons(
            self.rax_activeifs, sorted(self.colors_ifs.keys()), active=idx_active, activecolor=activecolor
        )

        self.w_rad_active_ifs.on_clicked(self.colorfunc)
        return self.w_rad_active_ifs

    def colorfunc(self, label):
        idx = int(label)
        self.active_prop = self.props[idx]
        self.w_rad_active_ifs.activecolor = self.prop_ifs.get_color()
        self._recreate_radius_slider()
        self._recreate_show_lines_check_button()
        self._recreate_alpha_slider()
        self._recreate_textsize_slider()

        if self.canvas is None:
            self.canvas.draw()
Example #5
0
def run_main(A,B,C,dA,dB,dC):
    
    plt.close()
    plt.figure()

    int_writer()
    var_writer_uncert(A,B,C)
    run_SPCAT()
    data = cat_reader()
    t = []
    s = []
    
    for x in data:
        s.append(0.0)
        s.append(str(10**float(x[1]))) 
        s.append(0.0)
        t.append(float(x[0])-0.0001)
        t.append(x[0])
        t.append(float(x[0])+0.0001)
    
    ax = plt.subplot(111)
    plt.subplots_adjust(left=0.25, bottom=0.25)
    
    a0 = 5
    f0 = 3
    global l
    l, = plt.plot(t,s, lw=2, color='red')
    #plt.axis([0, 1, -10, 10])
    
    axcolor = 'lightgoldenrodyellow'
    axA = plt.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor)
    axB  = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
    axC  = plt.axes([0.25, 0.05, 0.65, 0.03], axisbg=axcolor)
    global A_slider
    global B_slider
    global C_slider
    
    A_slider = Slider(axA, 'A', A-dA, A+dA, valinit=A)
    B_slider = Slider(axB, 'B', B-dB, B+dB, valinit=B)
    C_slider = Slider(axC, 'C', C-dC, C+dC, valinit=C)
    A_slider.on_changed(update)
    B_slider.on_changed(update)
    C_slider.on_changed(update)
    global button
    global radio
    resetax = plt.axes([0.1, 0.025, 0.1, 0.04])
    button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')
    button.on_clicked(reset)
    rax = plt.axes([0.025, 0.5, 0.15, 0.15], axisbg=axcolor)
    radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0)
    radio.on_clicked(colorfunc)
    plt.show()
    def _create_plot_controls(self):
        self._dbrax = plt.axes([0.12, 0.05, 0.10, 0.10])
        self._dbradio = RadioButtons(self._dbrax, ('Amplitude', 'Phase'))
        self._dbradio.on_clicked(self.set_plot_style)

        self._rax = plt.axes([0.25, 0.03, 0.15, 0.20])
        self._radio = RadioButtons(self._rax, ('Low Pass', 'High Pass'))
        self._radio.on_clicked(self.set_biquad_type)

        self._sfax = plt.axes([0.6, 0.19, 0.2, 0.03])
        self._fcslider = Slider(self._sfax, 'Cut-off frequency', 0, self._bq_fs/2, valinit = self._bq_fc)

        self._fcslider.on_changed(self.set_biquad_frequency_cutoff)
    def _GUI_display(self,redshift_est,ztest,corr_val,wave,flux_sc):
        '''Display the spectrum and reference lines.'''
        self.fig = plt.figure(figsize=(10, 8)) 
        gs = gridspec.GridSpec(2, 1, height_ratios=[2, 1])
        ax2 = plt.subplot(gs[0])
        ax = plt.subplot(gs[1])
        plt.subplots_adjust(right=0.8)

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

        self.pspec, = ax2.plot(wave,flux_sc)
        ax2.axvline(3725.0*(1+redshift_est),ls='--',alpha=0.7,c='blue')
        ax2.axvline(3968.5*(1+redshift_est),ls='--',alpha=0.7,c='red')
        ax2.axvline(3933.7*(1+redshift_est),ls='--',alpha=0.7,c='red')
        ax2.axvline(4102.9*(1+redshift_est),ls='--',alpha=0.7,c='orange')
        ax2.axvline(4304.0*(1+redshift_est),ls='--',alpha=0.7,c='orange')
        ax2.axvline(4862.0*(1+redshift_est),ls='--',alpha=0.7,c='orange')
        ax2.axvline(4959.0*(1+redshift_est),ls='--',alpha=0.7,c='blue')
        ax2.axvline(5007.0*(1+redshift_est),ls='--',alpha=0.7,c='blue')
        ax2.axvline(5175.0*(1+redshift_est),ls='--',alpha=0.7,c='orange')
        if self.first_pass:
            self.line_est = Estimateline(self.pspec,ax2,self.uline_n)
        rax = plt.axes([0.85, 0.5, 0.1, 0.2])
        if self.qualityval == 0:
            radio = RadioButtons(rax, ('Unclear', 'Clear'))
        else:
            radio = RadioButtons(rax, ('Unclear', 'Clear'),active=1)
        def qualfunc(label):
            if label == 'Clear':
                self.qualityval = 1
            else:
                self.qualityval = 0
        radio.on_clicked(qualfunc)
        closeax = plt.axes([0.83, 0.3, 0.15, 0.1])
        button = Button(closeax, 'Accept & Close', hovercolor='0.975')
        def closeplot(event):
            plt.close()
        button.on_clicked(closeplot)
        ax2.set_xlim(self.lower_w,self.upper_w)
        ax2.set_xlabel('Wavelength (A)')
        ax2.set_ylabel('Counts')
        if not self.first_pass:
            self.spectra2 = DragSpectra(self.pspec,flux_sc,ax2,self.fig)
            self.fig.canvas.mpl_connect('motion_notify_event',self.spectra2.on_motion)
            self.fig.canvas.mpl_connect('button_press_event',self.spectra2.on_press)
            self.fig.canvas.mpl_connect('button_release_event',self.spectra2.on_release)
        plt.show()
    def _create_plot_controls(self):
        self._dbrax = plt.axes([0.12, 0.05, 0.15, 0.15])
        self._dbradio = RadioButtons(self._dbrax, ('Amplitude', 'Phase'))
        self._dbradio.on_clicked(self.set_plot_style)

        self._rax = plt.axes([0.30, 0.03, 0.15, 0.20])
        self._radio = RadioButtons(self._rax, ('feedback', 'feedforward', 'allpass'))
        self._radio.on_clicked(self.set_comb_type)

        self._sfax = plt.axes([0.6, 0.19, 0.2, 0.03])
        self._dlyslider = Slider(self._sfax, 'delay (ms)', 0, (self._size/2.0) * 1000.0 / self._fs, valinit = self._delay)
        self._dlyslider.on_changed(self.set_comb_delay)

        self._sfax = plt.axes([0.6, 0.10, 0.2, 0.03])
        self._gainslider = Slider(self._sfax, 'gain', -1, 1, valinit = self._gain)
        self._gainslider.on_changed(self.set_comb_gain)
    def ReadFluxLC(self,fluxLC):


        self.fluxes =  fluxLC.fluxes

        self.errors =  array(fluxLC.fluxErrors)
        self.tBins = fluxLC.tBins

        self.models = fluxLC.modelNames


        self.flcFlag =True


        axcolor = 'lightgoldenrodyellow'


 #       self.radioFig = plt.figure(2)
#
        ax = plt.axes([.01, 0.7, 0.2, 0.32], axisbg=axcolor)

        self.data = self.fluxes['total']

        if self.radio:
            del self.radio
            self.radioAx.cla()


        self.radio = RadioButtons(self.radioAx,tuple(self.fluxes.keys()))
        self.radio.on_clicked(self.Selector)
        
        self.PlotData()
Example #10
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)
Example #11
0
  def __init__(self,image=None,imginfo={},verbosity=0,cmap=None,**kwargs):
    """
    image  ... (opt) 2D Array 
    imginfo... (opt) dictionary with parameters of the image
    verbosity. (opt) quiet (0), verbose (3), debug (4)
    futher options are passed to the imshow method of matplotlib
    """
    self.kwargs = kwargs;
    self.verbosity=verbosity;

    # open new figure and draw image
    self.fig  = plt.figure();
    self.axis = self.fig.add_subplot(111); 
    self.fig.subplots_adjust(right=0.85);
    self.AxesImage=None;
      
    # add Switches and Buttons
    axStyle = self.fig.add_axes([0.85, 0.1, 0.12, 0.12]);
    self.rbStyle = RadioButtons(axStyle,["linear","log","contour"]);
    self.rbStyle.on_clicked(self.set_style);
    self.currentstyle = "linear";
    axLine = self.fig.add_axes([0.85, 0.3, 0.12, 0.05]);    
    self.bLine = Button(axLine,'Line Profile');
    self.bLine.on_clicked(self._toggle_line_profile);
    self.LineProfile=None;
    self.bLine.color_activated='red';

    # key pressed
    self.fig.canvas.mpl_connect('key_press_event', self._key_press_callback)
   
    # draw image if given
    self.set_cmap(cmap);
    if image is not None: 
      self.set_image(image,imginfo);
Example #12
0
    def LoadEFlux(self,fileName):

        flux  = pickle.load(open(fileName))
        
        self.fluxes = flux['energy fluxes']
        self.fluxErrors = flux['errors']
        self.tBins = flux['tBins']
        
        axcolor = 'lightgoldenrodyellow'


 #       self.radioFig = plt.figure(2)

        if self.radio:
            #del self.radio
            self.radioAx.cla()
#
        self.radioAx = plt.axes([.01, 0.7, 0.2, 0.32], axisbg=axcolor)

        self.data = self.fluxes['total']
        self.errors = self.fluxErrors['total']

        self.radio = RadioButtons(self.radioAx,tuple(self.fluxes.keys()))
        self.radio.on_clicked(self.Selector)
        
        self.PlotData()
def slider_radio():
    def update(val):
        amp = samp.val
        freq = sfreq.val
        l.set_ydata(amp*np.sin(2*np.pi*freq*t))
        fig.canvas.draw_idle()

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

    def colorfunc(label):
        l.set_color(label)
        fig.canvas.draw_idle()

    fig = figure()
    ax = fig.subplots()
    fig.subplots_adjust(left=0.25, bottom=0.25)
    t = np.arange(0.0, 1.0, 0.001)
    a0 = 5
    f0 = 3
    s = a0*np.sin(2*np.pi*f0*t)
    l, = ax.plot(t, s, lw=2, color='red')
    ax.axis([0, 1, -10, 10])
# %% plot axes
    axcolor = 'lightgoldenrodyellow'
    axfreq = fig.add_axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor)
    axamp = fig.add_axes([0.25, 0.15, 0.65, 0.03], facecolor=axcolor)
# %% freq slide
    sfreq = Slider(axfreq, 'Freq', 0.1, 30.0, valinit=f0)
    samp = Slider(axamp, 'Amp', 0.1, 10.0, valinit=a0)
    sfreq.on_changed(update)
    samp.on_changed(update)
# %% reset button
    resetax = fig.add_axes([0.8, 0.025, 0.1, 0.04])
    button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')

    button.on_clicked(reset)
# %% color buttons
    rax = fig.add_axes([0.025, 0.5, 0.15, 0.15], facecolor=axcolor)
    radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0)
    radio.on_clicked(colorfunc)
# %% scoping
    axw = [axfreq, axamp, sfreq, samp, button, radio]  # place to hold all the axesWidgets to keep in scope

    return axw  # MUST return ax or GUI will be non-responsive!
def plot_mapqs(folder):
    """Plots the Distribution of MAPQ Scores for the Inversion Regions in the respective species
       folder : input folder to look for the files
    """
    
    mapqs_counts = defaultdict(list)
    mapqs_labels = defaultdict(list)

    strain_matcher = re.compile('(.*) \(.*\)')  ## regex to get strain name from radio button click
 
    ## Parse the information from the mapq count files and store the information in a dictionary of lists 
    for mapq_file in glob.glob(folder+"*.count.txt"):
        strain = mapq_file.split("/")[-1].split(".")[0]
        TEMP_HANDLE = open(mapq_file,'r')
        for line in TEMP_HANDLE:
            line = line.strip('\n')
            mapqs_counts[strain].append(int(line.split(' ')[0]))
            mapqs_labels[strain].append(line.split(' ')[1])
    
    fig, ax = plt.subplots()
    indexes = np.arange(len(mapqs_counts[S]))
    rects = plt.bar(indexes,mapqs_counts[S],0.5)
    ax.set_xticks(indexes+1*0.2)
    ax.set_xticklabels(mapqs_labels[S],rotation=30)

    rax1 = plt.axes([0.92, 0.1, 0.08, 0.8])
    radio1 = RadioButtons(rax1, ('MC (Sand)','CL (Sand)','CM (Sand)','CN (Sand)','TI (Sand)','DC (Sand)','MS (Sand)','CV (Sand)','PN (Rock)','AC (Rock)','LF (Rock)','MP (Rock)','MZ (Rock)'), active=0)
    
    def update1(strain):
        match = re.match(strain_matcher,strain)
        strain = match.group(1)
        #indexes = np.arange(len(mapqs_counts[S]))
        for rect,h in zip(rects,mapqs_counts[strain]):
            rect.set_height(h)
        ax.set_xticks(indexes+1*0.2)
        ax.set_xticklabels(mapqs_labels[strain],rotation=30)
        ax.relim()
        ax.autoscale()
        fig.canvas.draw_idle()
        #global S 
        #print S
        #S = strain

    radio1.on_clicked(update1)
    plt.show()
Example #15
0
 def _init_radio(self):
     """
     Add radio buttons to the radio ax for color scale.
     self._make_radio_axes() needs to have been called.
     """
     self.radio = RadioButtons(
         self.radio_ax,
         labels=['log', 'linear'],
         active=1)
Example #16
0
def Slider():
    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.widgets import Slider, Button, RadioButtons
    
    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
    s = a0*np.sin(2*np.pi*f0*t)
    l, = plt.plot(t,s, lw=2, color='red')
    plt.axis([0, 1, -10, 10])
    
    axcolor = 'lightgoldenrodyellow'
    axfreq = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
    axamp  = plt.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor)
    
    sfreq = Slider(axfreq, 'Freq', 0.1, 30.0, valinit=f0)
    samp = Slider(axamp, 'Amp', 0.1, 10.0, valinit=a0)
    
    def update(val):
        amp = samp.val
        freq = sfreq.val
        l.set_ydata(amp*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')
    def reset(event):
        sfreq.reset()
        samp.reset()
    button.on_clicked(reset)
    
    rax = plt.axes([0.025, 0.5, 0.15, 0.15], axisbg=axcolor)
    radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0)
    def colorfunc(label):
        l.set_color(label)
        fig.canvas.draw_idle()
    radio.on_clicked(colorfunc)
    
    plt.show()
Example #17
0
class AnalyzeFrame(object):
    """
    A slider representing a floating point range

    """
    def __init__(self, fname, n=10, intraday=False):
        """ """
        self.fig = plt.figure(facecolor='white')
        self.fig.canvas.set_window_title(u'期货数据分析')
        self.nbar = n
        self.cursors = []
        self.data, = load_datas(n, intraday, fname)
        self.axes = []
        self.rax = plt.axes([0, 0.5, 0.08, 0.15])
        self.radio = RadioButtons(self.rax, ('scatter', 'summary', 'summary2', 'entry', 'exit', 'simple'), active=0)
        self.axes, self.cursors = scatter_analyze(self.fig, self.data)
        self.radio.on_clicked(self.update)

    def update(self, op):
        for ax in self.axes:
            self.fig.delaxes(ax)
        for c in self.cursors:
            del c
        if op == "scatter":
            print "scatter_analyze" 
            self.axes, self.cursors = scatter_analyze(self.fig, self.data)
        elif op == "summary":
            print "summary_analyze" 
            self.axes, self.cursors = summary_analyze(self.fig, self.data, self.nbar, 1)
        elif op == "summary2":
            print "summary2_analyze" 
            self.axes, self.cursors = summary_analyze(self.fig, self.data, self.nbar, 2)
        elif op == "entry":
            print "entry_analyze" 
            self.axes, self.cursors = entry_analyze(self.fig, self.data, self.nbar)
        elif op == "exit":
            print "exit_analyze" 
            self.axes, self.cursors = exit_analyze(self.fig, self.data, self.nbar)
        elif op == "simple":
            self.axes, self.cursors = simple_entry_analyze(self.fig, self.data, self.nbar)
        #elif op == "hm":
            #axes, cursors = follow_entry_analyze(fig, data)
            #print "hm" 
        self.fig.canvas.draw()
    def setup_canvas(self):
        """Create the figure and the axes for the plot and buttons."""

        # Initialise the figure.
        self.currentFigure = plt.figure()
        self.axes = self.currentFigure.add_subplot(1, 1, 1)

        # Create the image.
        self.start_plotting(self.originalDataset)

        # Create the class radio button.
        classAxesLoc = plt.axes([0.05, 0.05, 0.07, 0.1 * round(len(self.classToColorMapping) / 3)], axisbg='0.85')
        classAxesLoc.set_title('Class Options')
        classRadio = RadioButtons(classAxesLoc, active=0, activecolor='black', labels=[i for i in sorted(self.classToColorMapping)])
        classRadio.on_clicked(self.on_class_change)

        # Create the reset button.
        resetAxesLoc = plt.axes([0.05, 0.44, 0.07, 0.075], axisbg='white')
        resetButton = Button(resetAxesLoc, 'Reset')
        resetButton.on_clicked(self.on_reset)

        # Create the recompute boundaries button.
        recomputeAxesLoc = plt.axes([0.05, 0.54, 0.07, 0.075], axisbg='white')
        recomputeButton = Button(recomputeAxesLoc, 'Recompute')
        recomputeButton.on_clicked(self.on_recompute)

        # Create the k choice button.
        kAxesLoc = plt.axes([0.05, 0.65, 0.07, 0.15], axisbg='0.85')
        kAxesLoc.set_title('K Options')
        kRadio = RadioButtons(kAxesLoc, active=0, activecolor='black', labels=[1, 3, 5, 7])
        kRadio.on_clicked(self.on_k_change)

        # Create the add/delete radio button.
        addDeleteAxesLoc = plt.axes([0.05, 0.85, 0.07, 0.1], axisbg='0.85')
        addDeleteAxesLoc.set_title('Add/Delete Points')
        addDeleteRadio = RadioButtons(addDeleteAxesLoc, active=1, activecolor='black', labels=['Add', 'Delete'])
        addDeleteRadio.on_clicked(self.on_delete_change)

        # Attach the mouse click event.
        cid = self.currentFigure.canvas.mpl_connect('button_press_event', self.on_click)

        # Display the figure maximised. These commands to maximise the figure are for the Qt4Agg backend. If a different backend is being used, then
        # the maximisation command will likely need to be changed.
        figManager = plt.get_current_fig_manager()
        figManager.window.showMaximized()
        plt.show()

        # Disconnect the mouse click event.
        self.currentFigure.canvas.mpl_disconnect(cid)
 def _add_normalise_power_selector(self):
     """
     Add a radio button to chose whether or not the power of all spectra 
     should be normalized to 1.
     """
     pos_shp = [CONTOLS_START_X, 0.5, CONTROLS_WIDTH, CONTROLS_HEIGHT]
     rax = self.figure.add_axes(pos_shp, axisbg=AXCOLOUR, title="Normalise")
     np_tuple = ("yes", "no")
     self.normalise_power_selector = RadioButtons(rax, np_tuple, active=np_tuple.index(self.normalise_power))
     self.normalise_power_selector.on_clicked(self._update_normalise_power)
Example #20
0
	def filter_connect(self):
		# user to change default parameters
		self.cidSelectFreq = self.filterAxs['amVfreq'].get_figure().canvas.mpl_connect('button_press_event', self.getBandpassFreq)

		# get order
		self.bnorder = RadioButtons(self.filterAxs['ordr'], (1,2,3,4,5), active=1)
		self.cidorder = self.bnorder.on_clicked(self.getButterOrder)

		# get type of filter to use
		self.bnband = RadioButtons(self.filterAxs['band'], ('bandpass','lowpass','highpass'))
		self.cidband = self.bnband.on_clicked(self.getBandtype)

		#add apply button. causes the filtered data to be applied 
		self.bnapply = Button(self.filterAxs['apply'], 'Apply')
		self.cidapply = self.bnapply.on_clicked(self.applyFilter)

		#add unapply button. causes the filtered data to be applied 
		self.bnunapply = Button(self.filterAxs['unapply'], 'Unapply')
		self.cidunapply = self.bnunapply.on_clicked(self.unapplyFilter)
 def _add_xscale_selector(self):
     """
     Add a radio button to the figure for selecting which scaling the x-axes
     should use.
     """
     pos_shp = [CONTOLS_START_X, 0.8, CONTROLS_WIDTH, CONTROLS_HEIGHT]
     rax = self.figure.add_axes(pos_shp, axisbg=AXCOLOUR, title="X Scale")
     xscale_tuple = ("log", "linear")
     self.xscale_selector = RadioButtons(rax, xscale_tuple, active=xscale_tuple.index(self.xscale))
     self.xscale_selector.on_clicked(self._update_xscale)
 def _add_mode_selector(self):
     """
     Add a radio button to the figure for selecting which mode of the model
     should be displayed.
     """
     pos_shp = [CONTOLS_START_X, 0.07, CONTROLS_WIDTH, 0.1 + 0.002 * self.input_data.read_data_shape()[3]]
     rax = self.figure.add_axes(pos_shp, axisbg=AXCOLOUR, title="Mode")
     mode_tuple = tuple(range(self.input_data.read_data_shape()[3]))
     self.mode_selector = RadioButtons(rax, mode_tuple, active=mode_tuple.index(self.mode))
     self.mode_selector.on_clicked(self._update_mode)
    def _create_plot_controls(self):
        self._dbrax = plt.axes([0.12, 0.05, 0.13, 0.10])
        self._dbradio = RadioButtons(self._dbrax, ('Amplitude', 'Phase'))
        self._dbradio.on_clicked(self.set_plot_style)

        self._rax = plt.axes([0.27, 0.03, 0.15, 0.20])
        self._radio = RadioButtons(self._rax, ('Low Pass', 'High Pass', 'Band Pass', 'All Pass', 'Notch', 'Peak', 'Low Shelf', 'High Shelf'))
        self._radio.on_clicked(self.set_biquad_type)

        self._sfax = plt.axes([0.6, 0.19, 0.2, 0.03])
        self._sqax = plt.axes([0.6, 0.12, 0.2, 0.03])
        self._sdbax = plt.axes([0.6, 0.05, 0.2, 0.03])
        self._fcslider = Slider(self._sfax, 'Cut-off frequency', 0, self._bq_fs/2, valinit = self._bq_fc)
        self._qslider = Slider(self._sqax, 'Q factor', 0.01, 10.0, valinit = self._bq_q)
        self._dbslider = Slider(self._sdbax, 'dB gain', -20.0, 20.0, valinit = self._bq_dbgain)

        self._fcslider.on_changed(self.set_biquad_frequency_cutoff)
        self._qslider.on_changed(self.set_biquad_q_factor)
        self._dbslider.on_changed(self.set_biquad_dbgain)
 def _add_mode_selector(self):
     """
     Add a radio button to the figure for selecting which mode of the model
     should be displayed.
     """
     pos_shp = [0.02, 0.07, 0.04, 0.1 + 0.002 * self.model.number_of_modes]
     rax = self.ipp_fig.add_axes(pos_shp, axisbg=AXCOLOUR, title="Mode")
     mode_tuple = tuple(range(self.model.number_of_modes))
     self.mode_selector = RadioButtons(rax, mode_tuple, active=0)
     self.mode_selector.on_clicked(self._update_mode)
    def _add_state_variable_selector(self):
        """
        Generate radio selector buttons to set which state variable is
        displayed on the x and y axis of the phase-plane plot.
        """
        svx_ind = self.model.state_variables.index(self.svx)
        svy_ind = self.model.state_variables.index(self.svy)

        #State variable for the x axis
        pos_shp = [0.08, 0.07, 0.065, 0.12 + 0.006 * self.model.nvar]
        rax = self.ipp_fig.add_axes(pos_shp, axisbg=AXCOLOUR, title="x-axis")
        self.state_variable_x = RadioButtons(rax, tuple(self.model.state_variables), active=svx_ind)
        self.state_variable_x.on_clicked(self._update_svx)

        #State variable for the y axis
        pos_shp = [0.16, 0.07, 0.065, 0.12 + 0.006 * self.model.nvar]
        rax = self.ipp_fig.add_axes(pos_shp, axisbg=AXCOLOUR, title="y-axis")
        self.state_variable_y = RadioButtons(rax, tuple(self.model.state_variables), active=svy_ind)
        self.state_variable_y.on_clicked(self._update_svy)
def plot(Z):
    ax = plt.subplot(111)
    plt.subplots_adjust(bottom=0.25)
    ax.contour(flatperm2.pd(Z, 1, 1).T)
    
    ax1 = plt.axes([0.125, 0.15, 0.775, 0.03])
    ax2 = plt.axes([0.125, 0.05, 0.775, 0.03])

    s1 = Slider(ax1, r'$\omega_1$', 0.1, 30.0, valinit=1)
    s2 = Slider(ax2, r'$\omega_2$', 0.1, 10.0, valinit=1)
    
    plt.show()

    def update(val):
        w1 = s1.val
        w2 = s2.val
        print((w1, w2))
        ax.clear()
        ax.contour(flatperm2.pd(Z, w1, w2).T)
        # l.set_ydata(amp*sin(2*pi*freq*t))
        plt.draw()

    s1.on_changed(update)
    s2.on_changed(update)

    return

    resetax = axes([0.8, 0.025, 0.1, 0.04])
    button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')
    def reset(event):
        sfreq.reset()
        samp.reset()
    button.on_clicked(reset)

    rax = axes([0.025, 0.5, 0.15, 0.15], axisbg=axcolor)
    radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0)
    def colorfunc(label):
        l.set_color(label)
        draw()
    radio.on_clicked(colorfunc)

    show()
Example #27
0
	def setFigure(self):
		fig = py.figure(figsize=(5,5))
		axs = self.addAxes(fig)

		self.bntext = py.Button(axs['text'], 'Text')
		self.bnchange= py.Button(axs['change'], 'Change')
		self.bnband = RadioButtons(axs['band'], ('low','high','double'))

		self.bnBandLabel = py.Button(axs['band_label'], 'low')
		
		return fig, axs
Example #28
0
 def make_buttons(self):
     axcolor = 'lightgoldenrodyellow'
     rax = plt.axes([0.05, 0.05, 0.15, 0.15], axisbg=axcolor)
     radio = RadioButtons(rax, ('x1', 'x5', 'x10'))
     radio.on_clicked(self.set_multiplier)
     axprev = plt.axes([0.7, 0.05, 0.1, 0.075])
     axnext = plt.axes([0.81, 0.05, 0.1, 0.075])
     axup = plt.axes([0.59, 0.05, 0.1, 0.075])
     axdown = plt.axes([0.48, 0.05, 0.1, 0.075])
     axdone = plt.axes([0.30, 0.05, 0.1, 0.075])
     bnext = Button(axnext, 'Right')
     bnext.on_clicked(self.next)
     bprev = Button(axprev, 'Left')
     bprev.on_clicked(self.prev)
     bup = Button(axup, 'Up')
     bup.on_clicked(self.up)
     bdown = Button(axdown, 'Down')
     bdown.on_clicked(self.down)
     bdone = Button(axdone, 'Done')
     bdone.on_clicked(self.done)
 def _add_variable_selector(self):
     """
     Generate radio selector buttons to set which state variable is 
     displayed.
     """
     noc = self.input_data.read_data_shape()[1]  # number of choices
     #State variable for the x axis
     pos_shp = [CONTOLS_START_X, 0.22, CONTROLS_WIDTH, 0.12 + 0.008 * noc]
     rax = self.figure.add_axes(pos_shp, axisbg=AXCOLOUR, title="State Variable")
     self.variable_selector = RadioButtons(rax, tuple(range(noc)), active=0)
     self.variable_selector.on_clicked(self._update_variable)
 def _add_spectrum_mode_selector(self):
     """
     Add a radio button to the figure for selecting which part of the spectrum
     should be displayed: 0:real, 1:imag, 2:abs
     """
     pos_shp = [CONTOLS_START_X, 0.07, CONTROLS_WIDTH, 0.1 + 0.002 * 3]
     rax = self.figure.add_axes(pos_shp, axisbg=AXCOLOUR, title="Spectrum Mode")
     spectrum_mode_tuple = ("Re", "Imag", "Abs")
     self.spectrum_mode_selector = RadioButtons(rax, spectrum_mode_tuple,
                                                active=spectrum_mode_tuple.index(self.spectrum))
     self.spectrum_mode_selector.on_clicked(self._update_spectrum_mode)
Example #31
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()
Example #32
0
                states[0] = (x+1j*y)*k0 + z*k1
                arrows[0] = update_arrow(states[0],arrows[0])
                update_final_state()
        return True
    fig.canvas.mpl_connect('button_press_event',on_click_handler)

    axA = fig.add_axes([.2,.9,.6,.05])
    slA = Slider(axA,'Angle',-180,180,valinit=360*gate[1])
    def update_angle(value):
        gate[1] = value/360.
        update_final_state()
    slA.on_changed(update_angle)

    axR = fig.add_axes([.01,.88,.1,.1])
    gate_dict = odict([('X',GateX),('Y',GateY),('Z',GateZ)])
    rbR = RadioButtons(axR,tuple(gate_dict),active=2)
    def update_gate(value):
        gate[0] = gate_dict[value]
        update_final_state()
    rbR.on_clicked(update_gate)

    axI = fig.add_axes([.01,.6,.1,.25])
    sq2 = .5*np.sqrt(2.)
    vectors_dict = odict([('0',(ax0,0,1)),('1',(ax1,0,1)),\
            ('+',(ax0,0,sq2)),('-',(ax0,0,-sq2)),\
            ('0+i1',(ax0,sq2,0)),('0-i1',(ax0,-sq2,0))])
            # ('0+i1',(ax1,-sq2,0)),('0-i1',(ax1,sq2,0))])
    rbI = RadioButtons(axI,tuple(vectors_dict),active=0)
    def update_initial(value):
        ax,xd,yd=vectors_dict[value]
        update_initial_state(axes=ax,button=3,xdata=xd,ydata=yd)
plt.rcParams["figure.figsize"] = 16, 2
f2 = plt.figure(2)
f2.canvas.set_window_title('Harmonograph Controls')
ax2 = f2.add_subplot(111)
plt.axis('off')
plt.subplots_adjust(left=0.0, right=1.0, top=1.0, bottom=0.0)


def xprint(name, value):  # convenience function to print params.
    print(name + ' '.join(['%.3f' % x for x in value]))


# Radio buttons for pendulum selector
pend = plt.axes([0.0, 0.0, 0.1, 0.8])
radio = RadioButtons(pend, ('1', '2', '3', '4'))

p = 0
update = True


def pensel(label):  # Pendulum selector callback
    global p, update
    pendict = {'1': 0, '2': 1, '3': 2, '4': 3}
    p = pendict[label]
    update = False
    Xsa.set_val(ax[p])
    Xsf.set_val(fx[p])
    Xsp.set_val(px[p])
    Ysa.set_val(ay[p])
    Ysf.set_val(fy[p])
Example #34
0
        fig.canvas.draw_idle()

    sdist.on_changed(update)
    sangle.on_changed(update)

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

    def reset(event):
        sdist.reset()
        sangle.reset()

    button.on_clicked(reset)

    rax = plt.axes([0.025, 0.5, 0.15, 0.15], axisbg=axcolor)
    radio = RadioButtons(rax, (0, 1, 2, 3), active=0)

    def colorfunc(label):
        global currentLDR
        currentLDR = int(label)
        update(0)

    radio.on_clicked(colorfunc)

    plt.show()
    plt.close(fig)


def evaluateError(angle, distance, m1, m2, m3, m4):
    offset = 45.
    angle += offset
Example #35
0
        stemp.set_val(temp)
    l.set_ydata((331 + 0.6 * temp) / t)
    fig.canvas.draw_idle()


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

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


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


button.on_clicked(reset)

rax = plt.axes([0.01, 0.7, 0.15, 0.15], facecolor=axcolor)
radio = RadioButtons(rax, ('yellow', 'pink', 'green'), active=0)


def colorfunc(label):
    l.set_color(label)
    fig.canvas.draw_idle()


radio.on_clicked(colorfunc)

plt.show()
Example #36
0
button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')


def reset(event):
    global pwm, freq, activeButton
    pwm = a0
    freq = f0
    activeButton = 0
    ESP8266_send()
    sfreq.reset()
    srpm.reset()


button.on_clicked(reset)

rax = plt.axes([0.025, 0.5, 0.15, 0.15], facecolor=axcolor)
radio = RadioButtons(rax, ('BUZZER', 'LED'), active=0)


def colorfunc(label):
    global activeButton
    if label == "BUZZER":
        activeButton = 0
    else:
        activeButton = 1
    ESP8266_send()


radio.on_clicked(colorfunc)

plt.show()
Example #37
0
def reset(event):
    for i in np.arange(nbeads):
        slvec[i].reset()
        savec[i].reset()
        swvec[i].reset()


button.on_clicked(reset)

rax = axes([0.025, 0.3, 0.12, 0.50], axisbg=axcolor, aspect='equal')
blabs = []
for i in np.arange(1, ncases + 1):
    blabs.append('Case {0}'.format(i))

#radio = RadioButtons(rax, ['Case 1', 'Case 2', 'Case 3'], active=0)
radio = RadioButtons(rax, blabs, active=0)


def colorfunc(label):
    datakey = int(label[-2:])
    per0, dp0 = test_data(datakey - 1)
    l0.set_xdata(per0)
    l0.set_ydata(dp0)
    #l.set_color(label)
    draw()


radio.on_clicked(colorfunc)

show()
Example #38
0
def poly_plots(snrs):
    for snr in snrs:
        print "Fitting polygons and sources to " + snr.name
        white = fits.open("white/" + snr.name + ".fits")
        red = fits.open("red/rpj/" + snr.name + ".fits")
        green = fits.open("green/rpj/" + snr.name + ".fits")
        blue = fits.open("blue/rpj/" + snr.name + ".fits")
        white_data = white[0].data
        red_data = red[0].data
        green_data = green[0].data
        blue_data = blue[0].data

        #        rgb = np.dstack([red_data,green_data,blue_data])

        xmax = white[0].header["NAXIS1"]
        ymax = white[0].header["NAXIS2"]

        w = wcs.WCS(white[0].header)
        try:
            pix2deg = white[0].header["CD2_2"]
        except KeyError:
            pix2deg = white[0].header["CDELT2"]
        # Divide by maximum value to normalise
#        rgb = normalize(rgb, np.nanmin(rgb), np.nanmax(rgb))

# Percentile interval for image normalisation
        pct = 97.0
        interval = PercentileInterval(pct)
        #        vmin, vmax = interval.get_limits(data)
        #        stretch = AsinhStretch(a=0.1)

        i = interval.get_limits(red_data)
        r = normalize(red_data, *i)
        i = interval.get_limits(green_data)
        g = normalize(green_data, *i)
        i = interval.get_limits(blue_data)
        b = normalize(blue_data, *i)

        rgb = np.dstack([r, g, b])
        rgb[np.isnan(rgb)] = 0.0

        def update(val):
            vmin = svmin.val
            vmax = svmax.val
            img_white.set_clim([svmin.val, svmax.val])
            fig.canvas.draw()

        fig = newfigure(figsize=(10, 5))
        ax_white = fig.add_axes([0.05, 0.15, 0.4, 0.8])
        ax_rgb = fig.add_axes([0.55, 0.15, 0.4, 0.8])
        img_rgb = ax_rgb.imshow(rgb)
        img_white = ax_white.imshow(white_data, cmap="gray")
        cbaxes = fig.add_axes([0.45, 0.1, 0.03, 0.85])
        cb = plt.colorbar(img_white, cax=cbaxes, orientation="vertical")

        axcolor = 'white'
        axmin = fig.add_axes([0.05, 0.05, 0.1, 0.02], axisbg=axcolor)
        axmax = fig.add_axes([0.24, 0.05, 0.1, 0.02], axisbg=axcolor)

        #        vmin0 = np.min(white_data)
        #        vmax0 = np.max(white_data)
        vmin0, vmax0 = interval.get_limits(white_data)
        # include the slider: cribbed from https://stackoverflow.com/questions/5611805/using-matplotlib-slider-widget-to-change-clim-in-image
        svmin = Slider(axmin, "vmin", 2 * vmin0, -2 * vmin0, valinit=vmin0)
        svmax = Slider(axmax, "vmax", -2 * vmax0, 2 * vmax0, valinit=vmax0)

        svmin.on_changed(update)
        svmax.on_changed(update)

        fig.suptitle(
            'Left-click = select source, middle-click = source subtract, right-click = select region to exclude from background calculation'
        )

        centerx, centery = w.wcs_world2pix(snr.loc.fk5.ra.value,
                                           snr.loc.fk5.dec.value, 0)
        print centerx, centery

        major, minor = snr.maj / (2 * pix2deg), snr.min / (2 * pix2deg)
        for ax in ax_white, ax_rgb:
            # If you don't do this, it automatically zooms out when you first click on the plot
            ax.set_xlim(0, xmax)
            ax.set_ylim(0, ymax)
            # Plot rough size of SNR -- DAG doesn't include pa information so neither can I
            ax.plot([centerx, centerx], [centery - major, centery + major],
                    **reticsnr)
            ax.plot([centerx - minor, centerx + minor], [centery, centery],
                    **reticsnr)
        polypick = PolyPick(ax_white)

        rax = fig.add_axes([0.6, 0.0, 0.15, 0.10])
        radio = RadioButtons(rax, ("white", "rgb"), active=0)

        def changeax(axl):
            if axl == "white":
                polypick.ax = ax_white
                plt.sca(ax_white)
            elif axl == "rgb":
                polypick.ax = ax_rgb
                plt.sca(ax_rgb)
            fig.canvas.draw_idle()

        radio.on_clicked(changeax)

        plt.show()

        # Export pixel co-ordinates as WCS co-ordinates in order to use on any arbitrary image, and save for later
        polygon = Coords()
        sources = Coords()
        exclude = Coords()
        if len(polypick.coords.x):
            polygon.x, polygon.y = w.wcs_pix2world(
                zip(polypick.coords.x, polypick.coords.y), 0).transpose()
        else:
            # User has got bored of picking polygons and wants to exit this loop
            print "No polygon detected; leaving polygon-drawing mode."
            break

        if len(polypick.points.x):
            sources.x, sources.y = w.wcs_pix2world(
                zip(polypick.points.x, polypick.points.y), 0).transpose()
        if len(polypick.exclude.x):
            exclude.x, exclude.y = w.wcs_pix2world(
                zip(polypick.exclude.x, polypick.exclude.y), 0).transpose()


# NB: overwrites data for any old measurements for this live object
        snr.polygon = polygon
        snr.sources = sources
        snr.exclude = exclude

    return snrs
Example #39
0
    def plot_setup(self, pre_fig=None):

        # Setting the figure and unpacking the different subplots to variables

        if not self.parent.show_second:
            self.fig, ((self.pendulum_plot, self.angle_plot),
                       (self.phase_plot, self.vel_plot)) = subplots(
                           2, 2, gridspec_kw={'width_ratios': [1, 2.5]})
        else:
            self.fig = figure()
            self.gs = gridspec.GridSpec(ncols=5 * 4, nrows=3, figure=self.fig)
            self.pendulum_plot = self.fig.add_subplot(self.gs[0, 0:2 * 4])
            self.angle_plot = self.fig.add_subplot(self.gs[0, 2 * 4 + 1:])
            self.phase_plot = self.fig.add_subplot(self.gs[1, 0:2 * 4])
            self.vel_plot = self.fig.add_subplot(self.gs[1, 2 * 4 + 1:])
            self.angle_plot_diff = self.fig.add_subplot(self.gs[2, 1:10])
            self.vel_plot_diff = self.fig.add_subplot(self.gs[2, 11:])

        subplots_adjust(left=p_left,
                        right=p_right,
                        top=p_top,
                        bottom=p_bot,
                        hspace=h_space,
                        wspace=w_space)
        self.fig.set_facecolor(Color.BACKGROUND)
        self.pendulum_plot.set(aspect='equal')
        self.phase_plot.set(aspect='equal')

        # Setting axes for the sliders and buttons
        self.ax_rod_length = axes([
            0.815 + slider_pad, 0.73, slider_w - 0.005, p_top - p_bot -
            (0.75 - 0.10)
        ],
                                  facecolor=Color.SLIDER_INACTIVE)
        self.ax_bob_mass = axes([
            0.815 + slider_pad * 2 + slider_w - 0.005, 0.73, slider_w - 0.005,
            p_top - p_bot - (0.75 - 0.10)
        ],
                                facecolor=Color.SLIDER_INACTIVE)
        self.ax_dt = axes([
            0.815 + slider_pad * 3 + 2 * (slider_w - 0.005), 0.73,
            slider_w - 0.005, p_top - p_bot - (0.75 - 0.10)
        ],
                          facecolor=Color.SLIDER_INACTIVE)

        self.ax_Fd = axes([
            0.815 + slider_pad * 4 + 3 * (slider_w - 0.005), 0.73,
            slider_w - 0.005, p_top - p_bot - (0.75 - 0.10)
        ],
                          facecolor=Color.SLIDER_INACTIVE)

        self.ax_Om_d = axes([
            0.815 + slider_pad * 5 + 4 * (slider_w - 0.005), 0.73,
            slider_w - 0.005, p_top - p_bot - (0.75 - 0.10)
        ],
                            facecolor=Color.SLIDER_INACTIVE)

        self.ax_dampening = axes(
            [0.82 + slider_pad, p_bot + 0.315 + button_w, button_w, button_w],
            facecolor=Color.RADIO_BACKGROUND,
            title="Dampening type")
        self.ax_second_calc = axes(
            [0.82 + slider_pad, p_bot + 0.34, button_w, button_w - 0.065],
            facecolor=Color.RADIO_BACKGROUND,
            title="Second trajectory")

        self.ax_Dtheta = axes(
            [0.835 + slider_pad, p_bot + 0.30, button_w - 0.055, slider_w],
            facecolor=Color.SLIDER_INACTIVE)

        self.ax_anim_params = axes(
            [0.82 + slider_pad, p_bot + 0.105, button_w, button_w],
            facecolor=Color.RADIO_BACKGROUND,
            title="Animation speed")

        self.ax_apply_run = axes(
            [0.82 + slider_pad, p_bot + 0.05, button_w, slider_w * 2])
        self.ax_reset = axes(
            [0.82 + slider_pad, p_bot, button_w, slider_w * 2])

        self.slider_rod_length = Slider(self.ax_rod_length,
                                        "l",
                                        5,
                                        15,
                                        color=Color.SLIDER_ACTIVE,
                                        valinit=self.parent.rod_length,
                                        valstep=0.1,
                                        orientation="vertical")

        self.slider_bob_mass = Slider(self.ax_bob_mass,
                                      "m",
                                      0.1,
                                      10.0,
                                      color=Color.SLIDER_ACTIVE,
                                      valinit=self.parent.bob_mass,
                                      valstep=0.1,
                                      orientation="vertical")

        self.slider_dt = Slider(self.ax_dt,
                                "dt",
                                0.001,
                                0.3,
                                color=Color.SLIDER_ACTIVE,
                                valinit=self.parent.dt,
                                valstep=0.001,
                                orientation="vertical",
                                valfmt="%1.3f")

        self.slider_Fd = Slider(self.ax_Fd,
                                "$F_D$",
                                0.0,
                                2,
                                color=Color.SLIDER_ACTIVE,
                                valinit=self.parent.F_d,
                                valstep=0.1,
                                orientation="vertical",
                                valfmt="%1.1f")

        self.slider_Om_d = Slider(self.ax_Om_d,
                                  "$\Omega_D$",
                                  0.0,
                                  2 * np.pi,
                                  color=Color.SLIDER_ACTIVE,
                                  valinit=self.parent.Om_d,
                                  valstep=0.01,
                                  orientation="vertical",
                                  valfmt="%1.2f")

        self.radio_damping = RadioButtons(
            self.ax_dampening,
            ["underdamped", "overdamped", "critical damping", "none"],
            active=self.parent.dampening_index,
            activecolor=Color.RADIO_SELECTED)
        for i in self.radio_damping.labels:
            i.set_fontsize("small")

        self.radio_second_calc = RadioButtons(self.ax_second_calc,
                                              ["No", "Yes"],
                                              active=self.parent.show_second,
                                              activecolor=Color.RADIO_SELECTED)
        for i in self.radio_second_calc.labels:
            i.set_fontsize("small")

        self.slider_Dtheta = Slider(self.ax_Dtheta,
                                    "$\Delta\\theta$",
                                    0.0,
                                    0.01,
                                    color=Color.SLIDER_ACTIVE,
                                    valinit=self.parent.init_Dtheta,
                                    valstep=0.0001,
                                    orientation="horizontal",
                                    valfmt="%1.4f")

        self.radio_anim_params = RadioButtons(
            self.ax_anim_params, ["$1/2$x", "1x", "4x", "10x", "No animation"],
            active=self.parent.speed_index,
            activecolor=Color.RADIO_SELECTED)
        for i in self.radio_anim_params.labels:
            i.set_fontsize("small")

        self.button_apply_run = Button(self.ax_apply_run,
                                       "Apply and run..",
                                       color=Color.BUTTON_OFF_HOVER,
                                       hovercolor=Color.BUTTON_ON_HOVER)
        self.button_reset_apply = Button(self.ax_reset,
                                         "Reset and run..",
                                         color=Color.BUTTON_OFF_HOVER,
                                         hovercolor=Color.BUTTON_ON_HOVER)
Example #40
0
    def _GUI_display(self, redshift_est, ztest, corr_val, test_waveform,
                     template_waveform):
        wave = test_waveform.masked_wave
        flux_sci = test_waveform.masked_flux
        '''Display the spectrum and reference lines.'''
        self.fig = plt.figure(figsize=(10, 8))
        gs = gridspec.GridSpec(2, 1, height_ratios=[2, 1])
        ax2 = plt.subplot(gs[0])
        ax = plt.subplot(gs[1])
        plt.subplots_adjust(top=0.96, bottom=0.04, left=0.04, right=0.92)

        figManager = plt.get_current_fig_manager()
        figManager.window.showMaximized()

        ax.plot(ztest, corr_val, 'b')
        pspec_corr = ax.axvline(redshift_est, color='k', ls='--')
        ax.set_xlabel('Redshift')
        ax.set_ylabel('Correlation')

        self.pspec, = ax2.plot(wave, flux_sci)
        ax2.set_ylim(np.min(flux_sci), np.max(flux_sci))
        ax2.set_xlim(wave[0], wave[-1])
        ax2.plot()
        # Plot sky lines:
        # Red = HK
        # Purple = OII, Halpha
        # Black = sky
        # Blue = Emission
        # Orange = Absorption
        vlin_pspecs = plot_skylines(ax2, redshift_est)

        # Include information in plot
        self.fig.text(0.923,
                      0.9,
                      '%s' % template_waveform.name,
                      bbox=dict(facecolor='white', alpha=1.),
                      fontsize=18)
        self.fig.text(0.922,
                      0.8,
                      'Blue/ = Emission\nPurple   Lines',
                      bbox=dict(facecolor='white', alpha=1.))
        self.fig.text(0.922,
                      0.78,
                      'Red/   = Absorption\nOrange  Lines',
                      bbox=dict(facecolor='white', alpha=1.))
        self.fig.text(0.922,
                      0.74,
                      'Black = Sky\n         Lines',
                      bbox=dict(facecolor='white', alpha=1.))

        # from left, from bottom, width, height
        rax = plt.axes([0.925, 0.43, 0.07, 0.22])

        # Setup User input box on plot
        if self.qualityval == 1:
            radio = RadioButtons(
                rax, ('1 - No Clue      ', '2 - Slight\n    Chance',
                      '3 - Maybe', '4 - Probably', '5 - Clear'))
        else:
            radio = RadioButtons(
                rax, ('1 - No Clue      ', '2 - Slight\n    Chance',
                      '3 - Maybe', '4 - Probably', '5 - Clear'),
                active=1)

        def qualfunc(label):
            if label == '5 - Clear':
                self.qualityval = 5
            elif label == '4 - Probably':
                self.qualityval = 4
            elif label == '3 - Maybe':
                self.qualityval = 3
            elif label == '2 - Slight\n    Chance':
                self.qualityval = 2
            else:
                self.qualityval = 1

        radio.on_clicked(qualfunc)
        # from left, from bottom, width, height
        closeax = plt.axes([0.93, 0.18, 0.06, 0.08])
        button = Button(closeax, 'Accept & Close', hovercolor='0.975')

        def closeplot(event):
            plt.close()

        button.on_clicked(closeplot)

        skip_spec_ax = plt.axes([0.93, 0.94, 0.06, 0.04])
        skip_button = Button(skip_spec_ax, 'skip spectra', hovercolor='0.975')

        def skip_spec(event):
            plt.close()
            self.qualityval = 0

        skip_button.on_clicked(skip_spec)

        #ax2.set_xlim(self.lower_w,self.upper_w)
        ax2.set_xlabel('Wavelength (A)')
        ax2.set_ylabel('Counts')

        # Setup the classification
        if self.first_pass:
            line_est = Estimateline(self.pspec, ax2, self.uline_n)
        else:
            spectra2 = DragSpectra(vlin_pspecs, pspec_corr, redshift_est, ax2)
            self.fig.canvas.mpl_connect('motion_notify_event',
                                        spectra2.on_motion)
            self.fig.canvas.mpl_connect('button_press_event',
                                        spectra2.on_press)
            self.fig.canvas.mpl_connect('button_release_event',
                                        spectra2.on_release)
        plt.show()
        if self.qualityval == 0:
            return None
        elif self.first_pass:
            if line_est.lam == 0:
                return None
            else:
                return line_est.lam / self.uline - 1.0
        else:
            return spectra2.finalz
Example #41
0
class AlignmentInterface(BaseReviewInterface):
    """Custom interface for rating the quality of alignment between two 3d MR images"""
    def __init__(self,
                 fig,
                 rating_list=cfg.default_rating_list,
                 next_button_callback=None,
                 quit_button_callback=None,
                 change_vis_type_callback=None,
                 toggle_animation_callback=None,
                 show_first_image_callback=None,
                 show_second_image_callback=None,
                 alpha_seg=cfg.default_alpha_seg):
        """Constructor"""

        super().__init__(fig, None, next_button_callback, quit_button_callback)

        self.rating_list = rating_list

        self.latest_alpha_seg = alpha_seg
        self.prev_axis = None
        self.prev_ax_pos = None
        self.zoomed_in = False

        self.next_button_callback = next_button_callback
        self.quit_button_callback = quit_button_callback
        self.change_vis_type_callback = change_vis_type_callback
        self.toggle_animation_callback = toggle_animation_callback
        self.show_first_image_callback = show_first_image_callback
        self.show_second_image_callback = show_second_image_callback

        self.add_radio_buttons_rating()
        self.add_radio_buttons_comparison_method()

        # this list of artists to be populated later
        # makes to handy to clean them all
        self.data_handles = list()

        self.unzoomable_axes = [
            self.radio_bt_rating.ax,
            self.radio_bt_vis_type.ax,
            self.text_box.ax,
            self.bt_next.ax,
            self.bt_quit.ax,
        ]

    def add_radio_buttons_comparison_method(self):

        ax_radio = plt.axes(cfg.position_alignment_radio_button_method,
                            facecolor=cfg.color_rating_axis,
                            aspect='equal')
        self.radio_bt_vis_type = RadioButtons(ax_radio,
                                              cfg.choices_alignment_comparison,
                                              active=None,
                                              activecolor='orange')
        self.radio_bt_vis_type.on_clicked(self.change_vis_type_callback)
        for txt_lbl in self.radio_bt_vis_type.labels:
            txt_lbl.set(color=cfg.text_option_color, fontweight='normal')

        for circ in self.radio_bt_vis_type.circles:
            circ.set(radius=0.06)

    def add_radio_buttons_rating(self):

        ax_radio = plt.axes(cfg.position_alignment_radio_button_rating,
                            facecolor=cfg.color_rating_axis,
                            aspect='equal')
        self.radio_bt_rating = RadioButtons(ax_radio,
                                            self.rating_list,
                                            active=None,
                                            activecolor='orange')
        self.radio_bt_rating.on_clicked(self.save_rating)
        for txt_lbl in self.radio_bt_rating.labels:
            txt_lbl.set(color=cfg.text_option_color, fontweight='normal')

        for circ in self.radio_bt_rating.circles:
            circ.set(radius=0.06)

    def save_rating(self, label):
        """Update the rating"""

        # print('  rating {}'.format(label))
        self.user_rating = label

    def get_ratings(self):
        """Returns the final set of checked ratings"""

        return self.user_rating

    def allowed_to_advance(self):
        """
        Method to ensure work is done for current iteration,
        before allowing the user to advance to next subject.

        Returns False if atleast one of the following conditions are not met:
            Atleast Checkbox is checked
        """

        return self.radio_bt_rating.value_selected is not None

    def reset_figure(self):
        "Resets the figure to prepare it for display of next subject."

        self.clear_data()
        self.clear_radio_buttons()
        self.clear_notes_annot()

    def clear_data(self):
        """clearing all data/image handles"""

        if self.data_handles:
            for artist in self.data_handles:
                artist.remove()
            # resetting it
            self.data_handles = list()

    def clear_radio_buttons(self):
        """Clears the radio button"""

        # enabling default rating encourages lazy advancing without review
        # self.radio_bt_rating.set_active(cfg.index_freesurfer_default_rating)
        for index, label in enumerate(self.radio_bt_rating.labels):
            if label.get_text() == self.radio_bt_rating.value_selected:
                self.radio_bt_rating.circles[index].set_facecolor(
                    cfg.color_rating_axis)
                break
        self.radio_bt_rating.value_selected = None

    def clear_notes_annot(self):
        """clearing notes and annotations"""

        self.text_box.set_val(cfg.textbox_initial_text)
        # text is matplotlib artist
        self.annot_text.remove()

    def on_mouse(self, event):
        """Callback for mouse events."""

        if self.prev_axis is not None:
            # include all the non-data axes here (so they wont be zoomed-in)
            if event.inaxes not in self.unzoomable_axes:
                self.prev_axis.set_position(self.prev_ax_pos)
                self.prev_axis.set_zorder(0)
                self.prev_axis.patch.set_alpha(0.5)
                self.zoomed_in = False

        # right click undefined
        if event.button in [3]:
            pass
        # double click to zoom in to any axis
        elif event.dblclick and event.inaxes is not None and \
            event.inaxes not in self.unzoomable_axes:
            # zoom axes full-screen
            self.prev_ax_pos = event.inaxes.get_position()
            event.inaxes.set_position(cfg.zoomed_position)
            event.inaxes.set_zorder(1)  # bring forth
            event.inaxes.set_facecolor('black')  # black
            event.inaxes.patch.set_alpha(1.0)  # opaque
            self.zoomed_in = True
            self.prev_axis = event.inaxes

        else:
            pass

        plt.draw()

    def on_keyboard(self, key_in):
        """Callback to handle keyboard shortcuts to rate and advance."""

        # ignore keyboard key_in when mouse within Notes textbox
        if key_in.inaxes == self.text_box.ax or key_in.key is None:
            return

        key_pressed = key_in.key.lower()
        # print(key_pressed)
        if key_pressed in [
                'right',
        ]:
            self.next_button_callback()
        elif key_pressed in ['ctrl+q', 'q+ctrl']:
            self.quit_button_callback()
        elif key_pressed in [' ', 'space']:
            self.toggle_animation_callback()
        elif key_pressed in ['alt+1', '1+alt']:
            self.show_first_image_callback()
        elif key_pressed in ['alt+2', '2+alt']:
            self.show_second_image_callback()
        else:
            if key_pressed in cfg.default_rating_list_shortform:
                self.user_rating = cfg.map_short_rating[key_pressed]
                index_to_set = cfg.default_rating_list.index(self.user_rating)
                self.radio_bt_rating.set_active(index_to_set)
            else:
                pass

        plt.draw()
Example #42
0
class guiMenu:
    fig = None

    gauss_params = [33, 7]

    logTextLabels = []
    logText = []

    axMisc = None
    axAlgorithm = None
    axSaveOptions = None
    axGauss = None
    axLog = None
    axRadio = None
    axLogLabels = None

    line_gaussian = None

    ax_window_size = None
    slider_window_size = None

    ax_sigma = None
    slider_sigma = None

    originalStdOut = None

    #------------------------------------------------------------------------------
    # Class initialization
    #
    def __init__(self):
        self.strTitle = 'Gesture Analysis Configuration - ' + settings.appVersion
        self.fig = plt.figure()
        self.fig.canvas.set_window_title(self.strTitle)
        self.fig.set_size_inches((settings.screen_cx * 0.49) / self.fig.dpi,
                                 (settings.screen_cy * 0.465) / self.fig.dpi)

        self.fig.canvas.mpl_connect('resize_event', self.onresize)
        self.fig.canvas.mpl_connect('close_event', self.onclose)

        self.fig.edgecolor = 'blue'
        self.fig.set_facecolor('0.90')

        left = 0.03  # the left side of the subplots of the figure
        right = 0.97  # the right side of the subplots of the figure
        bottom = 0.04  # the bottom of the subplots of the figure
        top = 0.92  # the top of the subplots of the figure
        wspace = 0.3  # the amount of width reserved for blank space between subplots
        hspace = 0.7  # the amount of height reserved for white space between subplots

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

        self.axMisc = plt.subplot2grid((6, 4), (0, 0),
                                       rowspan=1,
                                       colspan=1,
                                       aspect='auto',
                                       anchor='NW')
        self.axAlgorithm = plt.subplot2grid((6, 4), (1, 0),
                                            rowspan=2,
                                            colspan=1,
                                            aspect='auto',
                                            anchor='NW')
        self.axSaveOptions = plt.subplot2grid((6, 4), (3, 0),
                                              rowspan=3,
                                              colspan=1,
                                              aspect='equal',
                                              anchor='NW')
        self.axGauss = plt.subplot2grid((6, 4), (0, 1), rowspan=4, colspan=3)
        self.axLog = plt.subplot2grid((6, 4), (5, 1),
                                      rowspan=1,
                                      colspan=3,
                                      aspect='auto',
                                      anchor='NW')

        # create the various groups of UI controls
        self.createUIMiscellaneous()
        self.createUILog()

        self.createUIAlgorithm()
        self.createUIGaussianFilterControls()
        self.createUIMiscellaneousControls()

        # set settings.tkGuiCanvas for use for modal dialogs
        try:
            if (self.fig is not None) and (self.fig.canvas is not None) and (
                    self.fig.canvas._tkcanvas is not None):
                settings.tkGuiCanvas = self.fig.canvas._tkcanvas
        except Exception as e:
            pass

    #------------------------------------------------------------------------------
    #
    def get_aspect(self, ax):
        # Total figure size
        figW, figH = ax.get_figure().get_size_inches()
        # Axis size on figure
        _, _, w, h = ax.get_position().bounds
        # Ratio of display units
        disp_ratio = (figH * h) / (figW * w)
        # Ratio of data units
        # Negative over negative because of the order of subtraction
        data_ratio = sub(*ax.get_ylim()) / sub(*ax.get_xlim())

        return disp_ratio / data_ratio

    #------------------------------------------------------------------------------
    #
    def createUIAlgorithm(self):
        algorithm = settings.application.algorithm.lower()
        defaultAlgoritmIdx = 0
        if (algorithm == 'total'):
            defaultAlgoritmIdx = 0
        elif (algorithm == 'parallel'):
            defaultAlgoritmIdx = 1
        elif (algorithm == 'naive'):
            defaultAlgoritmIdx = 2

        self.axAlgorithm.set_title('Algorithm',
                                   x=0,
                                   horizontalalignment='left')

        # create an axis to host to radio buttons. make its aspect ratio
        # equal so the radiobuttons stay round
        aspect = self.get_aspect(self.axAlgorithm)
        rect = [0, 0, 1.0 * aspect, 1.0]
        ip = InsetPosition(self.axAlgorithm, rect)
        self.axRadio = plt.axes(rect)
        self.axRadio.set_axes_locator(ip)
        self.axRadio.axis('off')

        self.radioAlgorithm = RadioButtons(
            self.axRadio,
            ('Total Energy', 'Parallel Energy', 'Naive (no filter)'),
            active=defaultAlgoritmIdx)
        self.radioAlgorithm.on_clicked(self.onClickAlgorithm)

    #------------------------------------------------------------------------------
    #
    def createUIGaussianFilterControls(self):
        axcolor = 'lightgoldenrodyellow'

        rect = [0.82, -0.158, 0.14, 0.07]
        ax_btnapply = plt.axes(rect)
        ip = InsetPosition(self.axGauss, rect)  #posx, posy, width, height
        ax_btnapply.set_axes_locator(ip)
        self.btnApply = Button(ax_btnapply, 'Apply')
        self.btnApply.on_clicked(self.onclickApply)

        rect = [0.82, -0.245, 0.14, 0.07]
        ax_btnreset = plt.axes(rect)
        ip = InsetPosition(self.axGauss, rect)  #posx, posy, width, height
        ax_btnreset.set_axes_locator(ip)
        self.btnReset = Button(ax_btnreset,
                               'Reset',
                               color='0.950',
                               hovercolor='0.975')
        self.btnReset.on_clicked(self.onclickReset)

        rect = [0.1, -0.155, 0.55, 0.04]
        self.ax_window_size = plt.axes(rect, facecolor=axcolor)
        ip = InsetPosition(self.axGauss, rect)  #posx, posy, width, height
        self.ax_window_size.set_axes_locator(ip)
        self.slider_window_size = Slider(self.ax_window_size,
                                         'Window Size',
                                         1, (self.gauss_params[0] + 1) * 2 + 1,
                                         valinit=self.gauss_params[0],
                                         valstep=2)
        self.slider_window_size.on_changed(self.updateGaussianFilter)

        rect = [0.1, -0.235, 0.55, 0.04]
        self.ax_sigma = plt.axes(rect, facecolor=axcolor)
        ip = InsetPosition(self.axGauss, rect)  #posx, posy, width, height
        self.ax_sigma.set_axes_locator(ip)
        self.slider_sigma = Slider(self.ax_sigma,
                                   'Sigma',
                                   1, (self.gauss_params[1] + 1) * 2,
                                   valinit=self.gauss_params[1],
                                   valstep=1)
        self.slider_sigma.on_changed(self.updateGaussianFilter)

        self.updateGaussianFilter()

    #------------------------------------------------------------------------------
    #
    def createUIMiscellaneous(self):
        self.axMisc.set_title('', x=0, horizontalalignment='left')

        # removing top and right borders
        self.axMisc.xaxis.set_visible(False)
        self.axMisc.yaxis.set_visible(False)

        # remove ticks
        self.axSaveOptions.set_xticks([])
        self.axSaveOptions.set_yticks([])

        # remove ticks
        self.axAlgorithm.set_xticks([])
        self.axAlgorithm.set_yticks([])

        bbox = self.axMisc.get_window_extent()
        self.axMisc.set_xlim(0, bbox.width)
        self.axMisc.set_ylim(0, bbox.height)

    #------------------------------------------------------------------------------
    #
    def createUILog(self):
        self.axLog.set_title('Console Log', x=0, horizontalalignment='left')

        # removing top and right borders
        self.axLog.xaxis.set_visible(False)
        self.axLog.yaxis.set_visible(False)

        self.resetLogLabels()

        # redirect console messages to gui's log
        self.originalStdOut = sys.stdout
        sys.stdout = CaptureOutput()

    # -----------------------------------------------------------------------------
    #
    def resetLogLabels(self):
        cnt = len(self.logTextLabels)
        for i in range(0, cnt):
            self.logTextLabels[i].remove()

        self.logTextLabels = []

        bbox = self.axLog.get_window_extent()
        self.axLog.set_xlim(0, bbox.width)
        self.axLog.set_ylim(0, bbox.height)

        aspect = self.get_aspect(self.axLog)
        rect = [0, 0, 1.0 * aspect, 1.0]
        ip = InsetPosition(self.axLog, rect)

        if (self.axLogLabels is None):
            self.axLogLabels = plt.axes(rect)
        else:
            self.axLogLabels.set_position(rect)

        self.axLogLabels.set_axes_locator(ip)
        self.axLogLabels.axis('off')

        aspectLog = 1.0 / self.get_aspect(self.axLog)
        strText = 'Tyg'
        tmp, self.logTextHeight = settings.getTextExtent(self.axLog, strText)
        self.logTextHeight = self.logTextHeight * aspectLog  # * self.fig.dpi

        # pre-create empty log label placeholders
        self.logTextLabels = []
        y = (self.logTextHeight / 4.0)
        cy = bbox.height
        idx = len(self.logText) - 1
        while (y < cy):
            str = self.logText[idx] if (idx >= 0) else ''
            idx = idx - 1

            lbl = self.axLogLabels.text(
                8.0,
                y,
                str,
                horizontalalignment='left',
                verticalalignment='bottom',
                color='dimgray',
                clip_on=True,
                transform=self.axLog.transData
            )  #, bbox={'facecolor':'lightgray', 'alpha':0.7, 'pad':0.0})

            self.logTextLabels.append(lbl)
            y += self.logTextHeight

    # -----------------------------------------------------------------------------
    #
    def createUIMiscellaneousControls(self):
        rect = [0.06, 0.30, 0.70, 0.40]
        ip = InsetPosition(self.axMisc, rect)  #posx, posy, width, height
        ax_btnbrowse = plt.axes(rect)
        ax_btnbrowse.set_axes_locator(ip)
        self.btnBrowse = Button(ax_btnbrowse, 'Input File')
        self.btnBrowse.on_clicked(self.onclickBrowse)

        self.axSaveOptions.set_title('Output Files',
                                     x=0,
                                     horizontalalignment='left')

        x = 0.06
        dx = 0.70  # 0.80
        dy = 0.10  # 0.17
        cy = 0.14  # 0.24
        y = 0.80
        rect = [x, y, dx, dy]
        ip = InsetPosition(self.axSaveOptions,
                           rect)  #posx, posy, width, height
        ax_btn = plt.axes(rect)
        ax_btn.set_axes_locator(ip)
        self.btnSaveJSON = Button(ax_btn, 'JSON')
        self.btnSaveJSON.on_clicked(self.onclickSaveJSON)

        rect = [x, y - 1 * cy, dx, dy]
        ip = InsetPosition(self.axSaveOptions,
                           rect)  #posx, posy, width, height
        ax_btn = plt.axes(rect)
        ax_btn.set_axes_locator(ip)
        self.btnSaveTXT = Button(ax_btn, 'Text')
        self.btnSaveTXT.on_clicked(self.onclickSaveTXT)

        rect = [x, y - 2 * cy, dx, dy]
        ip = InsetPosition(self.axSaveOptions,
                           rect)  #posx, posy, width, height
        ax_btn = plt.axes(rect)
        ax_btn.set_axes_locator(ip)
        self.btnSaveFilterView = Button(ax_btn, 'Filter Graph')
        self.btnSaveFilterView.on_clicked(self.onclickSaveFilterView)

        rect = [x, y - 3 * cy, dx, dy]
        ip = InsetPosition(self.axSaveOptions,
                           rect)  #posx, posy, width, height
        ax_btn = plt.axes(rect)
        ax_btn.set_axes_locator(ip)
        self.btnSaveSkeletonView = Button(ax_btn, '3D Joint Data')
        self.btnSaveSkeletonView.on_clicked(self.onclickSaveSkeletonView)

        rect = [x, y - 4 * cy, dx, dy]
        ip = InsetPosition(self.axSaveOptions,
                           rect)  #posx, posy, width, height
        ax_btn = plt.axes(rect)
        ax_btn.set_axes_locator(ip)
        self.btnSaveScoreView = Button(ax_btn, 'Score View')
        self.btnSaveScoreView.on_clicked(self.onclickSaveScoreView)

        rect = [x, y - 5 * cy, dx, dy]
        ip = InsetPosition(self.axSaveOptions,
                           rect)  #posx, posy, width, height
        ax_btn = plt.axes(rect)
        ax_btn.set_axes_locator(ip)
        self.btnSavePNG = Button(ax_btn, 'Full Score')
        self.btnSavePNG.on_clicked(self.onclickSaveImage)

    #------------------------------------------------------------------------------
    # canvas resize event
    #
    def onresize(self, event):
        # plt.tight_layout()

        # keep tha radio buttons round...
        if (self.axRadio is not None) and (self.axAlgorithm is not None):
            aspect = self.get_aspect(self.axAlgorithm)
            rect = [0, 0, 1.0 * aspect, 1.0]

            ip = InsetPosition(self.axAlgorithm, rect)
            self.axRadio.set_axes_locator(ip)
            self.axRadio.set_position(rect)

        self.resetLogLabels()

    # -----------------------------------------------------------------------------
    # canvas close event
    #
    def onclose(self, event):
        self.fig = None
        # if user closes this figure, let the main application know and to exit
        settings.application.close()

    # -----------------------------------------------------------------------------
    #
    def updateUIControls(self, algorithm):
        algorithm = algorithm.lower()
        fEnable = False if (algorithm == 'naive') else True
        alpha = 0.2 if (algorithm == 'naive') else 1.0

        self.btnApply.set_active(fEnable)
        self.btnReset.set_active(fEnable)

        self.btnApply.label.set_alpha(alpha)
        self.btnReset.label.set_alpha(alpha)

        fUpdateGaussianPlot = False
        if (self.gauss_params[0] != self.slider_window_size.val):
            self.ax_window_size.clear()
            self.slider_window_size.__init__(
                self.ax_window_size,
                'Window Size',
                valmin=1,
                valmax=(self.gauss_params[0] + 1) * 2 + 1,
                valinit=self.gauss_params[0],
                valstep=2)
            self.slider_window_size.on_changed(self.updateGaussianFilter)
            fUpdateGaussianPlot = True

        if (self.gauss_params[1] != self.slider_sigma.val):
            self.ax_sigma.clear()
            self.slider_sigma.__init__(self.ax_sigma,
                                       'Sigma',
                                       valmin=1,
                                       valmax=(self.gauss_params[1] + 1) * 2,
                                       valinit=self.gauss_params[1],
                                       valstep=1)
            self.slider_sigma.on_changed(self.updateGaussianFilter)
            fUpdateGaussianPlot = True

        if (fUpdateGaussianPlot):
            self.updateGaussianFilter()

        self.line_gaussian.set_alpha(alpha)

        self.ax_window_size.patch.set_alpha(alpha)
        if (self.slider_window_size.poly):
            self.slider_window_size.poly.set_alpha(alpha)
        self.slider_window_size.set_active(fEnable)
        for r in self.slider_window_size.ax.texts:
            r.set_alpha(alpha)

        self.ax_sigma.patch.set_alpha(alpha)
        if (self.slider_sigma.poly):
            self.slider_sigma.poly.set_alpha(alpha)
        self.slider_sigma.set_active(fEnable)
        for r in self.slider_sigma.ax.texts:
            r.set_alpha(alpha)

        self.fig.canvas.draw_idle()

    # -----------------------------------------------------------------------------
    #
    def updateInputName(self):
        self.fig.canvas.set_window_title(
            self.strTitle + ' - [' +
            settings.application.strBeautifiedInputFile + ']')

    # -----------------------------------------------------------------------------
    #
    def getAlgorithmSelection(self):
        if (self.radioAlgorithm.value_selected == 'Total Energy'):
            return 'Total'
        elif (self.radioAlgorithm.value_selected == 'Parallel Energy'):
            return 'Parallel'

        return 'Naive'

    # -----------------------------------------------------------------------------
    #
    def onClickAlgorithm(self, label):
        algorithm = self.getAlgorithmSelection()

        if (settings.application.labanotation is not None):
            self.gauss_params = settings.application.labanotation.getGaussianParameters(
                algorithm)

        self.updateUIControls(algorithm)
        settings.application.applyAlgoritm(algorithm)

    #------------------------------------------------------------------------------
    # updateGaussianFilter() has an unused parameter, though needs it because the
    # sliders use this function as their update callback...
    def updateGaussianFilter(self, val=0):
        # remove current gaussian lines
        if (self.line_gaussian is not None):
            self.line_gaussian.remove()
            del self.line_gaussian
            self.line_gaussian = None

        gauss_params = (int(self.slider_window_size.val),
                        int(self.slider_sigma.val))

        self._t = np.arange(-gauss_params[0] / 2.0 + 0.5,
                            gauss_params[0] / 2.0 + 0.5, 1.0)
        s = wf.gaussFilter(gauss_params[0], gauss_params[1])
        self.line_gaussian, = self.axGauss.plot(self._t,
                                                s,
                                                marker="o",
                                                linestyle='-',
                                                color='red',
                                                lw=1)

        # for i, txt in enumerate(s):
        #    self.axGauss.annotate("{:0.2f}".format(txt), (self._t[i], s[i]))

        wnd = int(gauss_params[0] / 2) + 1
        self.axGauss.set_xlim(-wnd, wnd)
        self.axGauss.set_ylim(0, 0.42)  # np.max(s))
        self.fig.canvas.draw_idle()

    #------------------------------------------------------------------------------
    #
    def onclickApply(self, event):
        algorithm = self.getAlgorithmSelection()

        self.gauss_params = (int(self.slider_window_size.val),
                             int(self.slider_sigma.val))

        if (settings.application.labanotation is not None):
            settings.application.labanotation.setGaussianParameters(
                algorithm, self.gauss_params)

        settings.application.applyAlgoritm(algorithm)

    #------------------------------------------------------------------------------
    #
    def onclickSaveJSON(self, event):
        settings.application.saveJSON()

    #------------------------------------------------------------------------------
    #
    def onclickSaveTXT(self, event):
        settings.application.saveTXT()

    #------------------------------------------------------------------------------
    #
    def onclickSaveImage(self, event):
        settings.application.saveImage()

    #------------------------------------------------------------------------------
    #
    def onclickSaveFilterView(self, event):
        settings.application.saveFilterView()

    #------------------------------------------------------------------------------
    #
    def onclickSaveSkeletonView(self, event):
        settings.application.saveSkeletonView()

    #------------------------------------------------------------------------------
    #
    def onclickSaveScoreView(self, event):
        settings.application.saveScoreView()

    #------------------------------------------------------------------------------
    #
    def onclickReset(self, event):
        self.slider_window_size.reset()
        self.slider_sigma.reset()

    #------------------------------------------------------------------------------
    #
    def onclickBrowse(self, event):
        file = self.selectInputFile()
        if (file is None):
            return

        settings.application.openAndProcessInputfile(file)

    #------------------------------------------------------------------------------
    #
    def selectInputFile(self):
        fTyp = [("Kinect Joint Data File", "*.csv")]

        splitInput = os.path.split(
            os.path.abspath(settings.application.inputFilePath))

        options = {}
        options['filetypes'] = fTyp
        options['initialdir'] = splitInput[0].replace('/', os.sep)

        if (settings.tkGuiCanvas is not None):
            options['parent'] = settings.tkGuiCanvas

        file = tkFileDialog.askopenfilename(**options)

        if not file:
            return None

        return file

    #------------------------------------------------------------------------------
    #
    def logMessage(self, str, ioRedirect=False):
        # also write message to console
        if (self.originalStdOut is not None):
            extra = "\r\n" if (ioRedirect is False) else ""
            self.originalStdOut.write(str + extra)

        self.logText.append(str)
        cnt = len(self.logTextLabels)
        if (cnt > 0):
            for i in range(cnt - 1, 0, -1):
                self.logTextLabels[i].set_text(
                    self.logTextLabels[i - 1].get_text())

            self.logTextLabels[0].set_text(str)

            self.fig.canvas.draw_idle()
def slide_ddg(args):
    global new_df, radio, color_by, picked
    global scat, ax, sliders, sc_df, fig, cm, cbar
    sc_df = Rf.score_file2df(args['sc'], args['names'])
    args['logger'].log('score file has %i entries' % len(sc_df))
    if args['pc'] is not None:
        pc_df = get_rmsds_from_table(args['pc'])
        args['logger'].log('pc file had %i entries' % len(pc_df))
        a = sc_df.merge(pc_df, on='description')
        args['logger'].log('combined there are %i entries' % len(a))
        sc_df = a.copy()

    if args['percent'] != 100:
        threshold = np.percentile(sc_df[args['y']], args['percent'])
        sc_df = sc_df[sc_df[args['y']] < threshold]

    color_by = args['y']
    picked = False

    new_df = sc_df.copy()
    fig, ax = plt.subplots()
    plt.subplots_adjust(left=0.25, bottom=0.25)

    cm = plt.cm.get_cmap('RdYlBu')

    scat = ax.scatter(sc_df[args['x']].values,
                      sc_df[args['y']].values,
                      s=40,
                      cmap=cm,
                      c=sc_df[color_by],
                      picker=True)
    cbar = plt.colorbar(scat)
    sliders = {}
    for i, term in enumerate(args['terms']):
        slider_ax = plt.axes([0.25, 0.01 + i * 0.035, 0.65, 0.03])
        sliders[term] = Slider(slider_ax, term, np.min(sc_df[term].values),
                               np.max(sc_df[term].values), 0)
        sliders[term].on_changed(update)

    ax.set_xlim(
        np.min(new_df[args['x']].values) - 1,
        np.max(new_df[args['x']].values) + 1)
    ax.set_ylim(
        np.min(new_df[args['y']].values) - 1,
        np.max(new_df[args['y']].values) + 1)

    ax.set_xlabel(args['x'])
    ax.set_ylabel(args['y'])

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

    printax = plt.axes([0.025, 0.3, 0.15, 0.15])
    printbutton = Button(printax, 'Print', color='green', hovercolor='red')
    printbutton.on_clicked(print_table)

    logax = plt.axes([0.025, 0.1, 0.15, 0.15])
    logbutton = Button(logax, 'log table', color='blue', hovercolor='red')
    logbutton.on_clicked(log_table)

    rax = plt.axes([0.025, 0.5, 0.15, 0.15], axisbg='white')
    radio = RadioButtons(rax, args['terms'], active=0)
    radio.on_clicked(colorfunc)

    # cbar = plt.colorbar(scat)
    pl = PointLabel(new_df, ax, fig, args['x'], args['y'], [
        'description', 'a_sasa', 'a_res_solv', 'a_pack', 'a_span_topo',
        'a_ddg', 'fa_elec'
    ], args['logger'])
    fig.canvas.mpl_connect('pick_event', pl.onpick)

    plt.show()
Example #44
0
z0_slider.on_changed(update)

# angle slider
angle_valinit = 0
angax = axes([0.25, 0.035, 0.5, 0.025], axisbg='slategray')
angslider = Slider(angax, 'theta', 0, pi, valinit=0)


def upangle(val):
    global theta
    theta = angslider.val
    plot1d()


angslider.on_changed(upangle)

# radio buttons
ffax = axes([0.01, 0.1, 0.04, 0.2], axisbg='slategray')
ffbutt = RadioButtons(ffax, ('.1', '.2', '.3', '.4', '.5'), active=2)


def updateff(label):
    global ff
    ff = float(label)
    make_plots()


ffbutt.on_clicked(updateff)

show()
Example #45
0
class PickPhaseMenuMore:
	""" Pick phase for multiple seismograms and array stack
		Button: Sync
	"""
	def __init__(self, gsac, opts, axs):
		self.gsac = gsac
		self.opts = opts
		self.axs = axs
		self.axstk = self.axs['Fstk']
		if not 'stkdh' in gsac.__dict__:
			if opts.filemode == 'sac' and os.path.isfile(opts.fstack):
				gsac.stkdh = SacDataHdrs(opts.fstack, opts.delta)
			else:
				hdrini, hdrmed, hdrfin = opts.qcpara.ichdrs
				self.cchdrs = [hdrini, hdrmed]
				self.twcorr = opts.ccpara.twcorr
				# check data coverage
				opts.ipick = hdrini
				opts.twcorr = opts.ccpara.twcorr
				checkCoverage(gsac, opts) 
				gsac.selist = gsac.saclist
				self.ccStack()
		self.initPlot()
		self.plotStack()
		self.addEarthquakeInfo()
		self.setLabels()
		self.connect()

	def initPlot(self):
		""" Plot waveforms """
		gsac = self.gsac
		opts = self.opts
		sortSeis(gsac, opts)
		self.ppm = PickPhaseMenu(gsac, opts, self.axs)
		# make the legend box invisible
		if self.opts.pick_on:
			self.ppm.axpp.get_legend().set_visible(False)

	def addEarthquakeInfo(self):
		""" Set Earthquake Info
		  * Magnitude
		  * Location (Lat and Long)
		  * Depth
		"""
		gsac = self.gsac

		# get required parameters
		locationLat = round(gsac.event[6],2)
		locationLon = round(gsac.event[7],2)
		depth = round(gsac.event[8],2)
		magnitude = round(gsac.event[9],2)
		all_gcarc = []
		[all_gcarc.append(hdr.gcarc) for hdr in gsac.selist ]
		avg_gcarc = round(np.mean(all_gcarc),2)

		infoaxis = self.axs['Info']

		# remove axes markings
		infoaxis.axes.get_xaxis().set_ticks([])
		infoaxis.axes.get_yaxis().set_visible(False)

		# write the info into the axis plot
		infoaxis.text(0.1,0.85,'Magnitude: '+str(magnitude))
		infoaxis.text(0.1,0.65,'Lat: '+str(locationLat))
		infoaxis.text(0.1,0.45,'Lon: '+str(locationLon))
		infoaxis.text(0.1,0.25,'Depth: '+str(depth))
		infoaxis.text(0.1,0.05,'Gcarc: '+str(avg_gcarc))

	def setLabels(self):
		""" Set plot attributes """
		self.ppm.axpp.set_title('Seismograms')
		if self.opts.filemode == 'pkl':
			axstk = self.axstk
			trans = transforms.blended_transform_factory(axstk.transAxes, axstk.transAxes)
			axstk.text(1,1.01,self.opts.pklfile,transform=trans, va='bottom', ha='right',color='k')
		axpp = self.ppm.axpp
		trans = transforms.blended_transform_factory(axpp.transAxes, axpp.transData)
		font = FontProperties()
		font.set_family('monospace')
		axpp.text(1.025, 0, ' '*8+'qual= CCC/SNR/COH', transform=trans, va='center', 
			color='k', fontproperties=font)

	def plotStack(self):
		""" Plot array stack and span """
		colorwave = self.opts.pppara.colorwave
		stkybase = 0

		ppstk = PickPhase(self.gsac.stkdh, self.opts, self.axstk, stkybase, colorwave, 1) 

		ppstk.plotPicks()
		ppstk.disconnectPick()
		self.ppstk = ppstk
		self.axstk.set_title('Array Stack')
		self.ppstk.stalabel.set_visible(False)
		if self.opts.ynorm == 1.0:
			self.axstk.set_ylim(stkybase-0.5, stkybase+0.5)
		self.axstk.set_yticks([stkybase])
		self.axstk.set_yticklabels([])
		self.axstk.axvline(x=0, color='k', ls=':')
		# plot legend
		pppara = self.opts.pppara
		pickLegend(self.axstk, pppara.npick, pppara.pickcolors, pppara.pickstyles, False)
		self.plotSpan()

	def plotSpan(self):
		""" Span for array stack """
		axstk = self.axstk
		self.xzoom = [axstk.get_xlim(),]
		def on_select(xmin, xmax):
			""" Mouse event: select span. """
			if self.span.visible:
				print('span selected: %6.1f %6.1f ' % (xmin, xmax))
				xxlim = (xmin, xmax)
				axstk.set_xlim(xxlim)
				self.xzoom.append(xxlim)
				if self.opts.upylim_on:
					print ('upylim')
					self.ppstk.updateY(xxlim) ##
				axstk.figure.canvas.draw()
		pppara = self.opts.pppara
		a, col = pppara.alphatwsele, pppara.colortwsele
		mspan = pppara.minspan * self.opts.delta
		self.span = TimeSelector(axstk, on_select, 'horizontal', minspan=mspan, useblit=False,
			rectprops=dict(alpha=a, facecolor=col))

		#self.replot()
		#self.ppm.axpp.figure.canvas.draw()

	# -------------------------------- SORTING ---------------------------------- #

	# Sort seismograms by 
	#    --------------
	# * | file indices |
	#    --------------
	#                   ----- ----- ----- -----
	# * quality factor | all | ccc | snr | coh |
	#                   ----- ----- ----- -----
	#                 ---- ----- ------
	# * given header | az | baz | dist | ...
	#                 ---- ----- ------
	
	def sorting(self, event):
		""" Sort the seismograms in particular order """
		self.getSortAxes()
		self.summarize_sort()
		self.sort_connect()
		plt.show()		

	def getSortAxes(self):
		figsort = plt.figure('SortSeismograms',figsize=(15, 12))

		x0 = 0.05
		xx = 0.10
		yy = 0.04
		#xm = 0.02
		dy = 0.15
		dx = 0.12
		y0 = 0.90

		"""Allocating size of buttons"""
		# file indices (filenames)
		rectfile = [x0, y0-dy*1, xx, yy]
		# quality
		rectqall = [x0+dx*0, y0-2*dy, xx, yy]
		rectqccc = [x0+dx*1, y0-2*dy, xx, yy]
		rectqsnr = [x0+dx*2, y0-2*dy, xx, yy]
		rectqcoh = [x0+dx*3, y0-2*dy, xx, yy]
		# headers
		recthnpts = [x0+dx*0, y0-3*dy, xx, yy]
		recthb = [x0+dx*1, y0-3*dy, xx, yy]
		recthe = [x0+dx*2, y0-3*dy, xx, yy]
		recthdelta = [x0+dx*3, y0-3*dy, xx, yy]
		recthstla = [x0+dx*0, y0-3.5*dy, xx, yy]
		recthstlo = [x0+dx*1, y0-3.5*dy, xx, yy]
		recthdist = [x0+dx*2, y0-3.5*dy, xx, yy]
		recthaz = [x0+dx*3, y0-3.5*dy, xx, yy]
		recthbaz = [x0+dx*0, y0-4*dy, xx, yy]
		recthgcarc = [x0+dx*1, y0-4*dy, xx, yy]
		# quit
		rectquit = [0.2, y0-5*dy, 0.2, yy]

		"""writing buttons to axis"""
		sortAxs = {}
		figsort.text(0.1,y0-dy*0.5,'Sort by file Index Name: ')
		sortAxs['file'] = figsort.add_axes(rectfile)
		figsort.text(0.1,y0-dy*1.5,'Sort by Quality: ')
		sortAxs['qall'] = figsort.add_axes(rectqall)
		sortAxs['qccc'] = figsort.add_axes(rectqccc)
		sortAxs['qsnr'] = figsort.add_axes(rectqsnr)
		sortAxs['qcoh'] = figsort.add_axes(rectqcoh)
		figsort.text(0.1,y0-dy*2.5,'Sort by Header: ')
		sortAxs['hnpts'] = figsort.add_axes(recthnpts)
		sortAxs['hb'] = figsort.add_axes(recthb)
		sortAxs['he'] = figsort.add_axes(recthe)
		sortAxs['hdelta'] = figsort.add_axes(recthdelta)
		sortAxs['hstla'] = figsort.add_axes(recthstla)
		sortAxs['hstlo'] = figsort.add_axes(recthstlo)
		sortAxs['hdist'] = figsort.add_axes(recthdist)
		sortAxs['haz'] = figsort.add_axes(recthaz)
		sortAxs['hbaz'] = figsort.add_axes(recthbaz)
		sortAxs['hgcarc'] = figsort.add_axes(recthgcarc)
		sortAxs['quit'] = figsort.add_axes(rectquit)

		""" size of text summary box """
		rectsumm = [0.55, 0.05, 0.40, 0.90]
		sortAxs['summary'] = figsort.add_axes(rectsumm)
		# remove axes markings on summary field
		sortAxs['summary'].get_xaxis().set_ticks([])
		sortAxs['summary'].get_yaxis().set_visible([])

		self.sortAxs = sortAxs
		self.figsort = figsort

	def summarize_sort(self):
		sortAxs = self.sortAxs

		# define constants
		x0 = 0.03
		x1 = 0.20
		y0 = 0.95
		dy = 0.03

		# explain what the summaries are
		sortAxs['summary'].text(x0,y0-dy*0,'FILENAMES')
		sortAxs['summary'].text(x0,y0-dy*1,'File: ')
		sortAxs['summary'].text(x1,y0-dy*1,'Sort in alphabetical order by filename')

		sortAxs['summary'].text(x0,y0-dy*3,'QUALITY:')
		sortAxs['summary'].text(x0,y0-dy*4,'All: ')
		sortAxs['summary'].text(x1,y0-dy*4,'Weighted Ratio of all quality measures')
		sortAxs['summary'].text(x0,y0-dy*5,'CCC: ')
		sortAxs['summary'].text(x1,y0-dy*5,'Cross-coefficient Coefficient')
		sortAxs['summary'].text(x0,y0-dy*6,'SNR: ')
		sortAxs['summary'].text(x1,y0-dy*6,'Signal-to-noise Ratio')
		sortAxs['summary'].text(x0,y0-dy*7,'COH: ')
		sortAxs['summary'].text(x1,y0-dy*7,'time domain coherence')

		sortAxs['summary'].text(x0,y0-dy*9,'OTHER HEADERS:')
		sortAxs['summary'].text(x0,y0-dy*10,'NPTS: ')
		sortAxs['summary'].text(x1,y0-dy*10,'Number of points per data component')
		sortAxs['summary'].text(x0,y0-dy*11,'B: ')
		sortAxs['summary'].text(x1,y0-dy*11,'Beginning value of the independent variable')
		sortAxs['summary'].text(x0,y0-dy*12,'E: ')
		sortAxs['summary'].text(x1,y0-dy*12,'Ending value of the independent variable')
		sortAxs['summary'].text(x0,y0-dy*13,'Delta: ')
		sortAxs['summary'].text(x1,y0-dy*13,'Increment between evenly spaced samples')
		sortAxs['summary'].text(x0,y0-dy*14,'STLA: ')
		sortAxs['summary'].text(x1,y0-dy*14,'Station latitude (deg, north positive)')
		sortAxs['summary'].text(x0,y0-dy*15,'STLO: ')
		sortAxs['summary'].text(x1,y0-dy*15,'Station longitude (deg, east positive)')
		sortAxs['summary'].text(x0,y0-dy*16,'DIST: ')
		sortAxs['summary'].text(x1,y0-dy*16,'Station to event distance (km)')
		sortAxs['summary'].text(x0,y0-dy*17,'AZ: ')
		sortAxs['summary'].text(x1,y0-dy*17,'Event to station azimuth (deg)')
		sortAxs['summary'].text(x0,y0-dy*18,'BAZ: ')
		sortAxs['summary'].text(x1,y0-dy*18,'Station to event azimuth (deg)')
		sortAxs['summary'].text(x0,y0-dy*19,'GCARC: ')
		sortAxs['summary'].text(x1,y0-dy*19,'Station to event great circle arc length (deg)')

	""" Connect button events. """
	def sort_connect(self):
		"""write the position for the buttons into self"""
		self.axfile = self.sortAxs['file']
		self.axqall = self.sortAxs['qall']
		self.axqccc = self.sortAxs['qccc']
		self.axqsnr = self.sortAxs['qsnr']
		self.axqcoh = self.sortAxs['qcoh']
		self.axqcoh = self.sortAxs['qcoh']
		self.axhnpts = self.sortAxs['hnpts']
		self.axhb = self.sortAxs['hb']
		self.axhe = self.sortAxs['he']
		self.axhdelta = self.sortAxs['hdelta']
		self.axhstla = self.sortAxs['hstla']
		self.axhstlo = self.sortAxs['hstlo']
		self.axhdist = self.sortAxs['hdist']
		self.axhaz = self.sortAxs['haz']
		self.axhbaz = self.sortAxs['hbaz']
		self.axhgcarc = self.sortAxs['hgcarc']
		self.axquit = self.sortAxs['quit']

		"""add a button to the correct place as defined by the axes
		   Also label the buttons here, as seen in the GUI
		"""
		self.bnfile = Button(self.axfile, 'File')
		self.bnqall = Button(self.axqall, 'All')
		self.bnqccc = Button(self.axqccc, 'CCC')
		self.bnqsnr = Button(self.axqsnr, 'SNR')
		self.bnqcoh = Button(self.axqcoh, 'COH')
		self.bnhnpts = Button(self.axhnpts, 'NPTS')
		self.bnhb = Button(self.axhb, 'B')
		self.bnhe = Button(self.axhe, 'E')
		self.bnhdelta = Button(self.axhdelta, 'Delta')
		self.bnhstla = Button(self.axhstla, 'STLA')
		self.bnhstlo = Button(self.axhstlo, 'STLO')
		self.bnhdist = Button(self.axhdist, 'Dist')
		self.bnhaz = Button(self.axhaz, 'AZ')
		self.bnhbaz = Button(self.axhbaz, 'BAZ')
		self.bnhgcarc = Button(self.axhgcarc, 'GCARC')
		self.bnquit = Button(self.axquit, 'Waiting for User input')

		""" each button changes the way the seismograms are sorted """
		self.cidfile = self.bnfile.on_clicked(self.sort_file)
		self.cidqall = self.bnqall.on_clicked(self.sort_qall)
		self.cidqccc = self.bnqccc.on_clicked(self.sort_qccc)
		self.cidqsnr = self.bnqsnr.on_clicked(self.sort_qsnr)
		self.cidqcoh = self.bnqcoh.on_clicked(self.sort_qcoh)
		self.cidhnpts = self.bnhnpts.on_clicked(self.sort_hnpts)
		self.cidhb = self.bnhb.on_clicked(self.sort_hb)
		self.cidhe = self.bnhe.on_clicked(self.sort_he)
		self.cidhdelta = self.bnhdelta.on_clicked(self.sort_hdelta)
		self.cidhstla = self.bnhstla.on_clicked(self.sort_hstla)
		self.cidhstlo = self.bnhstlo.on_clicked(self.sort_hstlo)
		self.cidhdist = self.bnhdist.on_clicked(self.sort_hdist)
		self.cidhaz = self.bnhaz.on_clicked(self.sort_haz)
		self.cidhbaz = self.bnhbaz.on_clicked(self.sort_hbaz)
		self.cidhgcarc = self.bnhgcarc.on_clicked(self.sort_hgcarc)

		# dismiss window when done
		self.bnquit.on_clicked(self.dismiss_sort)

	def sort_disconnect(self):
		self.bnfile.disconnect(self.cidfile)
		self.bnqall.disconnect(self.cidqall)
		self.bnqccc.disconnect(self.cidqccc)
		self.bnqsnr.disconnect(self.cidqsnr)
		self.bnqcoh.disconnect(self.cidqcoh)
		self.bnhnpts.disconnect(self.cidhnpts)
		self.bnhb.disconnect(self.cidhb)
		self.bnhe.disconnect(self.cidhe)
		self.bnhdelta.disconnect(self.cidhdelta)
		self.bnhstla.disconnect(self.cidhstla)
		self.bnhstlo.disconnect(self.cidhstlo)
		self.bnhdist.disconnect(self.cidhdist)
		self.bnhaz.disconnect(self.cidhaz)
		self.bnhbaz.disconnect(self.cidhbaz)
		self.bnhgcarc.disconnect(self.cidhgcarc)

	def sort_file(self, event):
		self.bnquit.label.set_text('Processing...')
		event.canvas.draw()

		self.opts.sortby = 'i';
		self.replot_seismograms()
		self.ppm.axpp.figure.canvas.draw()

		self.bnquit.label.set_text('Done! Click to Exit.')
		event.canvas.draw()
		return

	def sort_qall(self, event):
		self.bnquit.label.set_text('Processing...')
		event.canvas.draw()

		self.opts.sortby = 'all';
		self.replot_seismograms()
		self.ppm.axpp.figure.canvas.draw()

		self.bnquit.label.set_text('Done! Click to Exit.')
		event.canvas.draw()
		return

	def sort_qccc(self, event):
		self.bnquit.label.set_text('Processing...')
		event.canvas.draw()

		self.opts.sortby = '1';
		self.replot_seismograms()
		self.ppm.axpp.figure.canvas.draw()

		self.bnquit.label.set_text('Done! Click to Exit.')
		event.canvas.draw()
		return

	def sort_qsnr(self, event):
		self.bnquit.label.set_text('Processing...')
		event.canvas.draw()

		self.opts.sortby = '2';
		self.replot_seismograms()
		self.ppm.axpp.figure.canvas.draw()

		self.bnquit.label.set_text('Done! Click to Exit.')
		event.canvas.draw()
		return

	def sort_qcoh(self, event):
		self.bnquit.label.set_text('Processing...')
		event.canvas.draw()

		self.opts.sortby = '3';
		self.replot_seismograms()
		self.ppm.axpp.figure.canvas.draw()

		self.bnquit.label.set_text('Done! Click to Exit.')
		event.canvas.draw()
		return

	def sort_hnpts(self, event):
		self.bnquit.label.set_text('Processing...')
		event.canvas.draw()

		self.opts.sortby = 'npts';
		self.replot_seismograms()
		self.ppm.axpp.figure.canvas.draw()

		self.bnquit.label.set_text('Done! Click to Exit.')
		event.canvas.draw()
		return

	def sort_hb(self, event):
		self.bnquit.label.set_text('Processing...')
		event.canvas.draw()

		self.opts.sortby = 'b';
		self.replot_seismograms()
		self.ppm.axpp.figure.canvas.draw()

		self.bnquit.label.set_text('Done! Click to Exit.')
		event.canvas.draw()
		return

	def sort_he(self, event):
		self.bnquit.label.set_text('Processing...')
		event.canvas.draw()

		self.opts.sortby = 'e';
		self.replot_seismograms()
		self.ppm.axpp.figure.canvas.draw()

		self.bnquit.label.set_text('Done! Click to Exit.')
		event.canvas.draw()
		return

	def sort_hdelta(self, event):
		self.bnquit.label.set_text('Processing...')
		event.canvas.draw()

		self.opts.sortby = 'delta';
		self.replot_seismograms()
		self.ppm.axpp.figure.canvas.draw()

		self.bnquit.label.set_text('Done! Click to Exit.')
		event.canvas.draw()
		return

	def sort_hkstnm(self, event):
		self.bnquit.label.set_text('Processing...')
		event.canvas.draw()

		self.opts.sortby = 'kstnm';
		self.replot_seismograms()
		self.ppm.axpp.figure.canvas.draw()

		self.bnquit.label.set_text('Done! Click to Exit.')
		event.canvas.draw()
		return

	def sort_hstla(self, event):
		self.bnquit.label.set_text('Processing...')
		event.canvas.draw()

		self.opts.sortby = 'stla';
		self.replot_seismograms()
		self.ppm.axpp.figure.canvas.draw()

		self.bnquit.label.set_text('Done! Click to Exit.')
		event.canvas.draw()
		return

	def sort_hstlo(self, event):
		self.bnquit.label.set_text('Processing...')
		event.canvas.draw()

		self.opts.sortby = 'stlo';
		self.replot_seismograms()
		self.ppm.axpp.figure.canvas.draw()

		self.bnquit.label.set_text('Done! Click to Exit.')
		event.canvas.draw()
		return

	def sort_hdist(self, event):
		self.bnquit.label.set_text('Processing...')
		event.canvas.draw()

		self.opts.sortby = 'dist';
		self.replot_seismograms()
		self.ppm.axpp.figure.canvas.draw()

		self.bnquit.label.set_text('Done! Click to Exit.')
		event.canvas.draw()
		return

	def sort_haz(self, event):
		self.bnquit.label.set_text('Processing...')
		event.canvas.draw()

		self.opts.sortby = 'az';
		self.replot_seismograms()
		self.ppm.axpp.figure.canvas.draw()

		self.bnquit.label.set_text('Done! Click to Exit.')
		event.canvas.draw()
		return

	def sort_hbaz(self, event):
		self.bnquit.label.set_text('Processing...')
		event.canvas.draw()

		self.opts.sortby = 'baz';
		self.replot_seismograms()
		self.ppm.axpp.figure.canvas.draw()

		self.bnquit.label.set_text('Done! Click to Exit.')
		event.canvas.draw()
		return

	def sort_hgcarc(self, event):
		self.bnquit.label.set_text('Processing...')
		event.canvas.draw()

		self.opts.sortby = 'gcarc';
		self.replot_seismograms()
		self.ppm.axpp.figure.canvas.draw()

		self.bnquit.label.set_text('Done! Click to Exit.')
		event.canvas.draw()
		return

	def dismiss_sort(self, event):
		"""Dismiss the sorting selection popup Window"""
		self.sort_disconnect()
		close()

	# -------------------------------- SORTING ---------------------------------- #

	# --------------------------------- Filtering ------------------------------- #
	# Implement Butterworth filter
	#

	def filtering(self,event):
		filterAxes = self.getFilterAxes()
		self.spreadButter()
		self.filter_connect()
		plt.show()		

	def filter_connect(self):
		# user to change default parameters
		self.cidSelectFreq = self.filterAxs['amVfreq'].get_figure().canvas.mpl_connect('button_press_event', self.getBandpassFreq)

		# get order
		self.bnorder = RadioButtons(self.filterAxs['ordr'], (1,2,3,4), active=1)
		self.cidorder = self.bnorder.on_clicked(self.getButterOrder)

		# get type of filter to use
		self.bnband = RadioButtons(self.filterAxs['band'], ('bandpass','lowpass','highpass'))
		self.cidband = self.bnband.on_clicked(self.getBandtype)

		# get reverse pass option
		self.bnreversepass = RadioButtons(self.filterAxs['reversepass'], ('yes', 'no'), active=1)
		self.cidreversepass = self.bnreversepass.on_clicked(self.getReversePassOption)

		#add apply button. causes the filtered data to be applied 
		self.bnapply = Button(self.filterAxs['apply'], 'Apply')
		self.cidapply = self.bnapply.on_clicked(self.applyFilter)

		#add unapply button. causes the filtered data to be applied 
		self.bnunapply = Button(self.filterAxs['unapply'], 'Unapply')
		self.cidunapply = self.bnunapply.on_clicked(self.unapplyFilter)

	def getReversePassOption(self, event):
		if event == 'yes':
			self.opts.filterParameters['reversepass'] = True
		else:
			self.opts.filterParameters['reversepass'] = False
		self.spreadButter()

	def getBandtype(self, event):
		self.opts.filterParameters['band'] = event
		if event=='bandpass':
			self.filterAxs['amVfreq'].figure.canvas.mpl_disconnect(self.cidSelectFreq)
			# set defaults
			self.opts.filterParameters['lowFreq'] = 0.05
			self.opts.filterParameters['highFreq'] = 0.25
			self.opts.filterParameters['advance'] = False
			self.spreadButter()
			#execute
			self.cidSelectFreq = self.filterAxs['amVfreq'].get_figure().canvas.mpl_connect('button_press_event', self.getBandpassFreq)
		elif event=='lowpass':
			self.filterAxs['amVfreq'].figure.canvas.mpl_disconnect(self.cidSelectFreq)
			# set defaults
			self.opts.filterParameters['lowFreq'] = 0.05
			self.opts.filterParameters['highFreq'] = np.nan
			self.opts.filterParameters['advance'] = False
			self.spreadButter()
			#execute
			self.cidSelectFreq = self.filterAxs['amVfreq'].get_figure().canvas.mpl_connect('button_press_event', self.getLowFreq)
		elif event=='highpass':
			self.filterAxs['amVfreq'].figure.canvas.mpl_disconnect(self.cidSelectFreq)
			# set defaults
			self.opts.filterParameters['lowFreq'] = np.nan
			self.opts.filterParameters['highFreq'] = 0.25
			self.opts.filterParameters['advance'] = False
			self.spreadButter()
			#execute
			self.cidSelectFreq = self.filterAxs['amVfreq'].get_figure().canvas.mpl_connect('button_press_event', self.getHighFreq)

	def getLowFreq(self, event):
		if event.inaxes == self.filterAxs['amVfreq']:
			self.opts.filterParameters['lowFreq'] = event.xdata
			self.spreadButter()

	def getHighFreq(self, event):
		if event.inaxes == self.filterAxs['amVfreq']:
			self.opts.filterParameters['highFreq'] = event.xdata
			self.spreadButter()

	def getButterOrder(self, event):
		self.opts.filterParameters['order'] = int(event)
		self.spreadButter()

	def getBandpassFreq(self,event):
		if event.inaxes == self.filterAxs['amVfreq']:
			if self.opts.filterParameters['advance']: # low and high frequencies recorded
				self.opts.filterParameters['highFreq'] = event.xdata
				if self.opts.filterParameters['lowFreq']<self.opts.filterParameters['highFreq']:
					self.opts.filterParameters['advance'] = False
					self.spreadButter()
				else:
					print('Value chose must be higher than lower frequency of %f' % self.opts.filterParameters['lowFreq'])
			else:
				self.opts.filterParameters['lowFreq'] = event.xdata
				self.opts.filterParameters['advance'] = True

	def modifyFilterTextLabels(self):
		self.filterAxs['Info'].clear()
		self.filterAxs['Info'].text(0.1,0.7,'Low Freq: '+str(self.opts.filterParameters['lowFreq']))
		self.filterAxs['Info'].text(0.1,0.4,'High Freq: '+str(self.opts.filterParameters['highFreq']))
		self.filterAxs['Info'].text(0.1,0.1,'Order: '+str(self.opts.filterParameters['order']))

	"""Apply the butterworth filter to the data """
	def spreadButter(self):
		# clear axes
		self.filterAxs['amVtime'].clear()
		self.filterAxs['amVfreq'].clear()

		#set axes limit
		self.filterAxs['amVtime'].set_xlim(-30,30)
		self.filterAxs['amVfreq'].set_xlim(0,1.50)

		self.modifyFilterTextLabels()

		originalTime = self.ppstk.time - self.ppstk.sacdh.reftime
		originalSignalTime = self.ppstk.sacdh.data

		originalFreq, originalSignalFreq = ftr.time_to_freq(originalTime, originalSignalTime, self.opts.delta)
		filteredSignalTime, filteredSignalFreq, adjusted_w, adjusted_h = ftr.filtering_time_freq(originalTime, originalSignalTime, self.opts.delta, self.opts.filterParameters['band'], self.opts.filterParameters['highFreq'], self.opts.filterParameters['lowFreq'], self.opts.filterParameters['order'], self.opts.filterParameters['reversepass'])

		# PLOT TIME
		self.filterAxs['amVtime'].plot(originalTime, originalSignalTime, label='Original')
		self.filterAxs['amVtime'].plot(originalTime, filteredSignalTime, label='Filtered')
		self.filterAxs['amVtime'].legend(loc="upper right")
		self.filterAxs['amVtime'].set_title('Signal vs Time')
		self.filterAxs['amVtime'].set_xlabel('Time (s)', fontsize = 12)
		self.filterAxs['amVtime'].set_ylabel('Signal', fontsize = 12)

		# PLOT FREQUENCY
		self.filterAxs['amVfreq'].plot(originalFreq, np.abs(originalSignalFreq), label='Original')
		self.filterAxs['amVfreq'].plot(originalFreq, np.abs(filteredSignalFreq), label='Filtered')
		self.filterAxs['amVfreq'].plot(adjusted_w, adjusted_h, label='Butterworth Filter')
		self.filterAxs['amVfreq'].legend(loc="upper right")
		self.filterAxs['amVfreq'].set_title('Amplitude vs frequency')
		self.filterAxs['amVfreq'].set_xlabel('Frequency (Hz)', fontsize = 12)
		self.filterAxs['amVfreq'].set_ylabel('Amplitude Signal', fontsize = 12)

		# redraw the plots on the popup window
		self.figfilter.canvas.draw()

	def applyFilter(self, event):
		#should we write filtered data for individual seismograms
		self.opts.filterParameters['apply'] = True

		# replot filtered stuff
		self.axstk.clear()
		self.ppm.axpp.clear()
		self.axs['Fron'].clear()
		self.axs['Prev'].clear()
		self.axs['Next'].clear()
		self.axs['Last'].clear()
		self.axs['Zoba'].clear()
		self.axs['Shdo'].clear()
		self.axs['Shfp'].clear()
		self.axs['Shod'].clear()
		self.axs['Quit'].clear()

		self.ppm = PickPhaseMenu(self.gsac, self.opts, self.axs)

		# make the legend box invisible
		if self.opts.pick_on:
			self.ppm.axpp.get_legend().set_visible(False)
		self.plotStack()

		# redraw figures
		self.ppm.axpp.figure.canvas.draw()
		self.axstk.figure.canvas.draw()

		# disconnect
		self.bnorder.disconnect(self.cidorder)
		self.bnunapply.disconnect(self.cidunapply)
		self.bnband.disconnect(self.cidband)
		self.filterAxs['amVfreq'].figure.canvas.mpl_disconnect(self.cidSelectFreq)

		plt.close()

	def unapplyFilter(self, event):
		# do not write filtered data for individual seismograms
		self.opts.filterParameters['apply'] = False

		#reset back to original defaults
		self.opts.filterParameters['band'] = 'bandpass'
		self.opts.filterParameters['lowFreq'] = 0.05
		self.opts.filterParameters['highFreq'] = 0.25
		self.opts.filterParameters['order'] = 2

		# replot filtered stuff
		self.axstk.clear()
		self.ppm.axpp.clear()
		self.axs['Fron'].clear()
		self.axs['Prev'].clear()
		self.axs['Next'].clear()
		self.axs['Last'].clear()
		self.axs['Zoba'].clear()
		self.axs['Shdo'].clear()
		self.axs['Shfp'].clear()
		self.axs['Shod'].clear()
		self.axs['Quit'].clear()
		self.initPlot()
		self.plotStack()

		# redraw figures
		self.ppm.axpp.figure.canvas.draw()
		self.axstk.figure.canvas.draw()

		# disconnect
		self.bnorder.disconnect(self.cidorder)
		self.bnapply.disconnect(self.cidapply)
		self.bnband.disconnect(self.cidband)
		self.filterAxs['amVfreq'].figure.canvas.mpl_disconnect(self.cidSelectFreq)

		plt.close()

	def getFilterAxes(self):
		figfilter = plt.figure(figsize=(15, 12))
		self.figfilter = figfilter

		rect_amVtime = [0.10, 0.50, 0.80, 0.35]
		rect_amVfreq = [0.10, 0.07, 0.80, 0.35]
		rectinfo = [0.8, 0.86, 0.15, 0.10]
		rectordr = [0.3, 0.86, 0.10, 0.10]
		rectunapply = [0.42, 0.90, 0.07, 0.04]
		rectapply = [0.5, 0.90, 0.05, 0.04]
		rectband = [0.6, 0.86, 0.10, 0.10]
		rectreversepass = [0.72, 0.86, 0.07, 0.10]

		filterAxs = {}
		self.figfilter.text(0.03,0.95,'Butterworth Filter', {'weight':'bold', 'size':21})
		filterAxs['amVtime'] = figfilter.add_axes(rect_amVtime) 
		filterAxs['amVfreq'] = figfilter.add_axes(rect_amVfreq) 
		filterAxs['ordr'] = figfilter.add_axes(rectordr)
		filterAxs['unapply'] = figfilter.add_axes(rectunapply)
		filterAxs['apply'] = figfilter.add_axes(rectapply)
		filterAxs['band'] = figfilter.add_axes(rectband)
		filterAxs['reversepass'] = figfilter.add_axes(rectreversepass)

		self.figfilter.text(0.3, 0.97, 'Order:')
		self.figfilter.text(0.6, 0.97, 'Filter Type:')
		self.figfilter.text(0.72, 0.97, 'Run Reverse:')

		# frequencies used to compute butterworth filter displayed here
		filterAxs['Info'] = figfilter.add_axes(rectinfo)
		filterAxs['Info'].axes.get_xaxis().set_visible(False)
		filterAxs['Info'].axes.get_yaxis().set_visible(False)

		self.filterAxs = filterAxs

	# --------------------------------- Filtering ------------------------------- #

	def plot_stations(self, event):
		event_name = 'event'
		if hasattr(self.opts, 'pklfile'):
			event_name = self.opts.pklfile
		PlotStations(event_name, self.gsac)

	def on_zoom(self, event):
		""" Zoom back to previous xlim when event is in event.inaxes.
		"""
		evkey = event.key
		axstk = self.axstk
		if not axstk.contains(event)[0] or evkey is None: return
		xzoom = self.xzoom
		if evkey.lower() == 'z' and len(xzoom) > 1:
			del xzoom[-1]
			axstk.set_xlim(xzoom[-1])
			print('Zoom back to: %6.1f %6.1f ' % tuple(xzoom[-1]))
			if self.opts.upylim_on:
				for pp in self.pps:
					del pp.ynorm[-1]
					plt.setp(pp.lines[0], ydata=pp.ybase+pp.sacdh.data*pp.ynorm[-1])
			axstk.figure.canvas.draw()

	def replot_seismograms(self):
		""" Replot seismograms and array stack after running iccs.
		"""
		sortSeis(self.gsac, self.opts)
		self.ppm.initIndex()
		self.ppm.replot(0)
		self.setLabels()

	def replot(self):
		""" Replot seismograms and array stack after running iccs.
		"""
		self.ppstk.disconnect()
		self.ppstk.axpp.cla()
		self.plotStack()
		sortSeis(self.gsac, self.opts)
		self.ppm.initIndex()
		self.ppm.replot(0)
		self.setLabels()

	def connect(self):
		""" Connect button events. """
		# write the position for the buttons into self
		self.axccim = self.axs['CCIM']
		self.axccff = self.axs['CCFF']
		self.axsync = self.axs['Sync']
		self.axmccc = self.axs['MCCC']
		self.axsac2 = self.axs['SAC2']
		self.axsort = self.axs['Sort']
		self.axfilter = self.axs['Filter']
		self.axplotsta = self.axs['plotsta']

		# name the buttons
		self.bnccim = Button(self.axccim, 'Align')
		self.bnccff = Button(self.axccff, 'Refine')
		self.bnsync = Button(self.axsync, 'Sync')
		self.bnmccc = Button(self.axmccc, 'Finalize')
		self.bnsac2 = Button(self.axsac2, 'SAC P2')
		self.bnsort = Button(self.axsort, 'Sort')
		self.bnfilter = Button(self.axfilter, 'Filter')
		self.bnplotsta = Button(self.axplotsta, 'Map of\n stations')

		self.cidccim = self.bnccim.on_clicked(self.ccim)
		self.cidccff = self.bnccff.on_clicked(self.ccff)
		self.cidsync = self.bnsync.on_clicked(self.sync)
		self.cidmccc = self.bnmccc.on_clicked(self.mccc)
		self.cidsac2 = self.bnsac2.on_clicked(self.plot2)

		self.cidsort = self.bnsort.on_clicked(self.sorting)
		self.cidfilter = self.bnfilter.on_clicked(self.filtering)
		self.cidplotsta = self.bnplotsta.on_clicked(self.plot_stations)

		self.cidpress = self.axstk.figure.canvas.mpl_connect('key_press_event', self.on_zoom)

	def disconnect(self):
		""" Disconnect button events. """
		self.bnccim.disconnect(self.cidccim)
		self.bnccff.disconnect(self.cidccff)
		self.bnsync.disconnect(self.cidsync)
		self.bnmccc.disconnect(self.cidmccc)
		self.bnsac2.disconnect(self.cidsac2)
		self.bnsort.disconnect(self.cidsort)
		self.bnfilter.disconnect(self.cidfilter)

		self.axccim.cla()
		self.axccff.cla()
		self.axsync.cla()
		self.axmccc.cla()
		self.axsac2.cla()
		self.axsort.cla()
		self.axfilter.cla()

	def syncPick(self):
		""" Sync final time pick hdrfin from array stack to all traces. 
		"""
		self.getPicks()
		tshift = self.tfin - self.tmed
		hdrini, hdrmed, hdrfin = self.opts.qcpara.ichdrs
		for sacdh in self.gsac.saclist:
			tfin = sacdh.gethdr(hdrmed) + tshift
			sacdh.sethdr(hdrfin, tfin)

	def syncWind(self):
		""" Sync time window relative to hdrfin from array stack to all traces. 
			Times saved to twhdrs are alway absolute.
		"""
		wh0, wh1 = self.opts.qcpara.twhdrs
		hdrini, hdrmed, hdrfin = self.opts.qcpara.ichdrs
		self.getWindow(hdrfin)
		twfin = self.twcorr
		for sacdh in self.gsac.saclist:
			tfin = sacdh.gethdr(hdrfin)
			th0 = tfin + twfin[0]
			th1 = tfin + twfin[1]
			sacdh.sethdr(wh0, th0)
			sacdh.sethdr(wh1, th1)
			
	def sync(self, event):
		""" Sync final time pick and time window from array stack to each trace and update current page.
		"""
		hdrini, hdrmed, hdrfin = self.opts.qcpara.ichdrs
		wh0, wh1 = self.opts.qcpara.twhdrs
		if self.ppstk.sacdh.gethdr(hdrfin) == -12345.:
			print('*** hfinal %s is not defined. Pick at array stack first! ***' % hdrfin)
			return
		self.syncPick()
		self.syncWind()
		twfin = self.twcorr
		for pp in self.ppm.pps:
			sacdh = pp.sacdh
			tfin = sacdh.gethdr(hdrfin)
			ipk = int(hdrfin[1])
			tpk = tfin - sacdh.reftime
			pp.timepicks[ipk].set_xdata(tpk)
			th0 = tfin + twfin[0]
			th1 = tfin + twfin[1]
			pp.twindow = [th0, th1]
			pp.resetWindow()
		print('--> Sync final time picks and time window... You can now run CCFF to refine final picks.')
	
	def getWindow(self, hdr):
		""" Get time window twcorr (relative to hdr) from array stack, which is from last run. 
		"""
		ppstk = self.ppstk
		tw0, tw1 = ppstk.twindow
		t0 = ppstk.sacdh.gethdr(hdr)
		if t0 == -12345.:
			print(('Header {0:s} not defined'.format(hdr)))
			return
		twcorr = [tw0-t0, tw1-t0]
		self.twcorr = twcorr

	def getPicks(self):
		""" Get time picks of stack
		"""
		hdrini, hdrmed, hdrfin = self.opts.qcpara.ichdrs
		self.tini = self.gsac.stkdh.gethdr(hdrini)
		self.tmed = self.gsac.stkdh.gethdr(hdrmed)
		self.tfin = self.gsac.stkdh.gethdr(hdrfin)

	def ccim(self, event):
		# running ICCS-A will erase everything you did. Make sure the user did not hit it by mistake
		shouldRun = tkinter.messagebox.askokcancel("Will Erase Work!","This will erase any picks past t1. \nAre you sure?")

		if shouldRun:
			""" Run iccs with time window from final stack. Time picks: hdrini, hdrmed.
			"""
			hdrini, hdrmed, hdrfin = self.opts.qcpara.ichdrs
			self.cchdrs = hdrini, hdrmed
			self.getWindow(self.cchdrs[0])
			self.ccStack()
			self.getPicks()
			self.replot()

	def ccff(self, event):
		""" Run iccs with time window from final stack. Time picks: hdrfin, hdrfin.
		"""
		hdrini, hdrmed, hdrfin = self.opts.qcpara.ichdrs

		if self.gsac.stkdh.gethdr(hdrfin) == -12345.:
			print('*** hfinal %s is not defined. Sync first! ***' % hdrfin)
			return

		"""running ICCS-B will erase everything you did. Make sure the user did not hit it by mistake"""
		shouldRun = tkinter.messagebox.askokcancel("Will Erase Work!","This will erase any picks past t2 and will recalculate all t2 values. \nAre you sure?")
		
		if shouldRun:
			self.cchdrs = hdrfin, hdrfin
			self.getWindow(self.cchdrs[0])
			self.getPicks()
			self.ccStack()
			stkdh = self.gsac.stkdh
			stkdh.sethdr(hdrini, self.tini)
			stkdh.sethdr(hdrmed, self.tmed)
			self.replot()

	def ccStack(self):
		""" 
		Call iccs.ccWeightStack. 
		Change reference time pick to the input pick before ICCS and to the output pick afterwards.
		"""
		opts = self.opts
		ccpara = opts.ccpara
		opts.ccpara.twcorr = self.twcorr
		ccpara.cchdrs = self.cchdrs
		hdr0, hdr1 = int(ccpara.cchdrs[0][1]), int(ccpara.cchdrs[1][1])
		stkdh, stkdata, quas = ccWeightStack(self.gsac.selist, self.opts)
		stkdh.selected = True
		stkdh.sethdr(opts.qcpara.hdrsel, b'True    ')
		self.gsac.stkdh = stkdh
		if opts.reltime != hdr1:
			out = '\n--> change opts.reltime from %i to %i'
			print(out % (opts.reltime, hdr1))
		opts.reltime = hdr1

	def mccc(self, event):
		""" Run mccc.py  """
		gsac = self.gsac
		mcpara = self.opts.mcpara
		#rcfile = mcpara.rcfile
		ipick = mcpara.ipick
		wpick = mcpara.wpick
		self.getWindow(ipick)
		timewindow = self.twcorr
		#tw = timewindow[1]-timewindow[0]
		taperwindow = taperWindow(timewindow, mcpara.taperwidth)
		mcpara.timewindow = timewindow
		mcpara.taperwindow = taperwindow
		evline, mcname = eventListName(gsac.event, mcpara.phase)
		mcpara.evline = evline
		mcpara.mcname = mcname
		mcpara.kevnm = gsac.kevnm
		solution, solist_LonLat, delay_times = mccc(gsac, mcpara)
		self.gsac.solist_LonLat = solist_LonLat
		self.gsac.delay_times = delay_times

		wpk = int(wpick[1])
		if self.opts.reltime != wpk:
			out = '\n--> change opts.reltime from %i to %i'
			print(out % (self.opts.reltime, wpk))
		self.opts.reltime = wpk
		self.replot()

	def plot2(self, event):
		""" Plot P2 stack of seismograms for defined time picks (ichdrs + wpick).
		"""
		opts = copy.copy(self.opts)
		twin_on = opts.twin_on
		pick_on = opts.pick_on
		reltime = opts.reltime
		ynorm = opts.ynorm
		fill = opts.fill
		selist = self.gsac.selist

		tpicks = opts.qcpara.ichdrs + [opts.mcpara.wpick,]
		npick = len(tpicks)
		tlabs = 'ABCDE'

		fig2 = plt.figure(figsize=(9,12))
		fig2.clf()
		plt.subplots_adjust(bottom=.05, top=0.96, left=.1, right=.97, wspace=.5, hspace=.24)
		opts.twin_on = False
		opts.pick_on = False
		ax0 = fig2.add_subplot(npick,1,1)
		axsacs = [ ax0 ] + [ fig2.add_subplot(npick,1,i+1, sharex=ax0) for i in list(range(1, npick)) ]
		for i in list(range(npick)):
			opts.reltime = int(tpicks[i][1])
			ax = axsacs[i]
			sacp2(selist, opts, ax)
			tt = '(' + tlabs[i] + ')'
			trans = transforms.blended_transform_factory(ax.transAxes, ax.transAxes)
			ax.text(-.05, 1, tt, transform=trans, va='center', ha='right', size=16)	

		opts.ynorm = ynorm
		opts.twin_on = twin_on
		opts.pick_on = pick_on
		opts.reltime = reltime
		opts.fill = fill
		opts.zero_on = False

		plt.show()		
Example #46
0
    def __init__(self, fileDir):
        self.damage_Tag = ''
        self.lines = []  # 生成的成果list
        self.log = las.LASReader(fileDir, null_subs=np.nan)
        self.fig1 = plt.figure('MIT油套管快速评价系统', figsize=(12, 8))
        xls = xlrd.open_workbook(".\\casing_data.xls")
        table = xls.sheet_by_name('Sheet1')
        # 注意下面几个的类型为excel单元格对象
        self.outer_diameter = table.cell(0, 2)
        self.inner_diameter = table.cell(0, 3)
        self.thickness = table.cell(0, 4)

        self.scale_left = float(self.inner_diameter.value) / 2 - 20
        self.scale_right = float(self.inner_diameter.value) / 2 + 120

        self.scale_left_min = float(self.inner_diameter.value) - 30
        self.scale_right_max = float(self.inner_diameter.value) + 30

        # 定义RadioButtons
        axcolor = 'lightgoldenrodyellow'
        rax = plt.axes([0.75, 0.05, 0.12, 0.07], facecolor=axcolor)
        radio = RadioButtons(rax, (u'Penetration', u'Projection', u'Transformation'), active=-1, activecolor='purple')
        plt.subplots_adjust(bottom=0.15, top=0.95, right=0.9, left=0.10, wspace=0.60)
        radio.on_clicked(self.actionfunc)
        #####################################################################################
        # 坐标轴1
        self.ax1 = plt.subplot(141)
        # 下面赋值加逗号是为了使得type(self.line1)为matplotlib.lines.Line2D对象,而不是list
        self.line1, = self.ax1.plot(self.log.data['D01'], self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax1.plot(self.log.data['D02'] + 2.5, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax1.plot(self.log.data['D03'] + 5, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax1.plot(self.log.data['D04'] + 7.5, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax1.plot(self.log.data['D05'] + 10, self.log.data['DEPT'], 'r-', lw=0.3)
        self.ax1.plot(self.log.data['D06'] + 12.5, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax1.plot(self.log.data['D07'] + 15, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax1.plot(self.log.data['D08'] + 17.5, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax1.plot(self.log.data['D09'] + 20, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax1.plot(self.log.data['D10'] + 22.5, self.log.data['DEPT'], 'r-', lw=0.3)
        self.ax1.plot(self.log.data['D11'] + 25, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax1.plot(self.log.data['D12'] + 27.5, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax1.plot(self.log.data['D13'] + 30, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax1.plot(self.log.data['D14'] + 32.5, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax1.plot(self.log.data['D15'] + 35, self.log.data['DEPT'], 'r-', lw=0.3)
        self.ax1.plot(self.log.data['D16'] + 37.5, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax1.plot(self.log.data['D17'] + 40, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax1.plot(self.log.data['D18'] + 42.5, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax1.plot(self.log.data['D19'] + 45, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax1.plot(self.log.data['D20'] + 47.5, self.log.data['DEPT'], 'r-', lw=0.3)
        self.ax1.plot(self.log.data['D21'] + 50, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax1.plot(self.log.data['D22'] + 52.5, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax1.plot(self.log.data['D23'] + 55, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax1.plot(self.log.data['D24'] + 57.5, self.log.data['DEPT'], 'g-', lw=0.3)

        self.ax1.set_xlim(self.scale_left, self.scale_right)
        self.ax1.set_ylim(self.log.start, self.log.stop)
        self.ax1.invert_yaxis()

        span1 = SpanSelector(self.ax1, self.onselect1, 'vertical', useblit=False,
                             rectprops=dict(alpha=0.5, facecolor='yellow'), span_stays=True)
        # plt.ylabel(self.log.curves.DEPT.descr + " (%s)" % self.log.curves.DEPT.units)
        # plt.xlabel(self.log.curves.D01.descr + " (%s)" % self.log.curves.D01.units)
        # plt.title(self.log.well.WELL.data)
        plt.ylabel('Measured Depth(m)')
        plt.title('Original')

        plt.gca().spines['bottom'].set_position(('data', 0))
        plt.gca().spines['top'].set_position(('data', 0))
        plt.grid()
        #####################################################################################
        # 坐标轴2
        self.ax2 = plt.subplot(142)
        self.line2, = self.ax2.plot(self.log.data['D01'], self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax2.plot(self.log.data['D02'] + 2.5, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax2.plot(self.log.data['D03'] + 5, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax2.plot(self.log.data['D04'] + 7.5, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax2.plot(self.log.data['D05'] + 10, self.log.data['DEPT'], 'r-', lw=0.3)
        self.ax2.plot(self.log.data['D06'] + 12.5, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax2.plot(self.log.data['D07'] + 15, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax2.plot(self.log.data['D08'] + 17.5, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax2.plot(self.log.data['D09'] + 20, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax2.plot(self.log.data['D10'] + 22.5, self.log.data['DEPT'], 'r-', lw=0.3)
        self.ax2.plot(self.log.data['D11'] + 25, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax2.plot(self.log.data['D12'] + 27.5, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax2.plot(self.log.data['D13'] + 30, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax2.plot(self.log.data['D14'] + 32.5, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax2.plot(self.log.data['D15'] + 35, self.log.data['DEPT'], 'r-', lw=0.3)
        self.ax2.plot(self.log.data['D16'] + 37.5, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax2.plot(self.log.data['D17'] + 40, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax2.plot(self.log.data['D18'] + 42.5, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax2.plot(self.log.data['D19'] + 45, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax2.plot(self.log.data['D20'] + 47.5, self.log.data['DEPT'], 'r-', lw=0.3)
        self.ax2.plot(self.log.data['D21'] + 50, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax2.plot(self.log.data['D22'] + 52.5, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax2.plot(self.log.data['D23'] + 55, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax2.plot(self.log.data['D24'] + 57.5, self.log.data['DEPT'], 'g-', lw=0.3)

        self.ax2.set_xlim(self.scale_left, self.scale_right)
        self.ax2.set_ylim(self.log.start, self.log.stop)
        self.ax2.invert_yaxis()

        span2 = SpanSelector(self.ax2, self.onselect2, 'vertical', useblit=False,
                             rectprops=dict(alpha=0.5, facecolor='yellow'), span_stays=True)
        plt.title('Middle')
        plt.gca().spines['bottom'].set_position(('data', 0))
        plt.gca().spines['top'].set_position(('data', 0))
        self.ax2.grid()
        #####################################################################################
        # 坐标轴3
        self.ax3 = plt.subplot(143)
        self.line3, = self.ax3.plot(self.log.data['D01'], self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax3.plot(self.log.data['D02'] + 2.5, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax3.plot(self.log.data['D03'] + 5, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax3.plot(self.log.data['D04'] + 7.5, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax3.plot(self.log.data['D05'] + 10, self.log.data['DEPT'], 'r-', lw=0.3)
        self.ax3.plot(self.log.data['D06'] + 12.5, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax3.plot(self.log.data['D07'] + 15, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax3.plot(self.log.data['D08'] + 17.5, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax3.plot(self.log.data['D09'] + 20, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax3.plot(self.log.data['D10'] + 22.5, self.log.data['DEPT'], 'r-', lw=0.3)
        self.ax3.plot(self.log.data['D11'] + 25, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax3.plot(self.log.data['D12'] + 27.5, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax3.plot(self.log.data['D13'] + 30, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax3.plot(self.log.data['D14'] + 32.5, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax3.plot(self.log.data['D15'] + 35, self.log.data['DEPT'], 'r-', lw=0.3)
        self.ax3.plot(self.log.data['D16'] + 37.5, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax3.plot(self.log.data['D17'] + 40, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax3.plot(self.log.data['D18'] + 42.5, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax3.plot(self.log.data['D19'] + 45, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax3.plot(self.log.data['D20'] + 47.5, self.log.data['DEPT'], 'r-', lw=0.3)
        self.ax3.plot(self.log.data['D21'] + 50, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax3.plot(self.log.data['D22'] + 52.5, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax3.plot(self.log.data['D23'] + 55, self.log.data['DEPT'], 'g-', lw=0.3)
        self.ax3.plot(self.log.data['D24'] + 57.5, self.log.data['DEPT'], 'g-', lw=0.3)

        self.ax3.set_xlim(self.scale_left, self.scale_right)
        self.ax3.set_ylim(self.log.start, self.log.stop)
        self.ax3.invert_yaxis()

        # self.span3_cyan = SpanSelector(self.ax3, self.onselect3, 'vertical', useblit=True,
        #                           rectprops=dict(alpha=0.5, facecolor='cyan'), span_stays=True)

        plt.title('Large')
        plt.gca().spines['bottom'].set_position(('data', 0))
        plt.gca().spines['top'].set_position(('data', 0))
        self.ax3.grid()
        #####################################################################################
        # 坐标轴4
        self.ax4 = plt.subplot(144)
        self.ax4.plot(self.log.data['IDMX'], self.log.data['DEPT'], 'r--', lw=0.3)
        self.ax4.plot(self.log.data['IDMN'], self.log.data['DEPT'], 'b-', lw=0.3)
        self.ax4.plot(self.log.data['IDAV'], self.log.data['DEPT'], 'k--', lw=0.3)

        self.ax4.set_xlim(self.scale_left_min, self.scale_right_max)
        self.ax4.set_ylim(self.log.start, self.log.stop)
        self.ax4.invert_yaxis()

        plt.title('Min-Max')
        plt.gca().spines['bottom'].set_position(('data', 0))
        plt.gca().spines['top'].set_position(('data', 0))
        self.ax4.grid()

        multi = MultiCursor(plt.gcf().canvas, (self.ax1, self.ax2, self.ax3, self.ax4), color='r', lw=1,
                            horizOn=True, vertOn=False)
        #########################

        plt.show()
Example #47
0
def _setup_browser_selection(raw, kind, selector=True):
    """Organize browser selections."""
    import matplotlib.pyplot as plt
    from matplotlib.widgets import RadioButtons
    from ..selection import (read_selection, _SELECTIONS, _EEG_SELECTIONS,
                             _divide_to_regions)
    from ..utils import _get_stim_channel
    _check_option('group_by', kind, ('position, selection'))
    if kind == 'position':
        order = _divide_to_regions(raw.info)
        keys = _SELECTIONS[1:]  # no 'Vertex'
        kind = 'position'
    else:  # kind == 'selection'
        from ..io import RawFIF, RawArray
        if not isinstance(raw, (RawFIF, RawArray)):
            raise ValueError("order='selection' only works for Neuromag data. "
                             "Use order='position' instead.")
        order = dict()
        try:
            stim_ch = _get_stim_channel(None, raw.info)
        except ValueError:
            stim_ch = ['']
        keys = np.concatenate([_SELECTIONS, _EEG_SELECTIONS])
        stim_ch = pick_channels(raw.ch_names, stim_ch)
        for key in keys:
            channels = read_selection(key, info=raw.info)
            picks = pick_channels(raw.ch_names, channels)
            if len(picks) == 0:
                continue  # omit empty selections
            order[key] = np.concatenate([picks, stim_ch])

    misc = pick_types(raw.info,
                      meg=False,
                      eeg=False,
                      stim=True,
                      eog=True,
                      ecg=True,
                      emg=True,
                      ref_meg=False,
                      misc=True,
                      resp=True,
                      chpi=True,
                      exci=True,
                      ias=True,
                      syst=True,
                      seeg=False,
                      bio=True,
                      ecog=False,
                      fnirs=False,
                      exclude=())
    if len(misc) > 0:
        order['Misc'] = misc
    keys = np.concatenate([keys, ['Misc']])
    if not selector:
        return order
    fig_selection = figure_nobar(figsize=(2, 6), dpi=80)
    fig_selection.canvas.set_window_title('Selection')
    rax = plt.subplot2grid((6, 1), (2, 0), rowspan=4, colspan=1)
    topo_ax = plt.subplot2grid((6, 1), (0, 0), rowspan=2, colspan=1)
    keys = np.concatenate([keys, ['Custom']])
    order.update({'Custom': list()})  # custom selection with lasso
    plot_sensors(raw.info,
                 kind='select',
                 ch_type='all',
                 axes=topo_ax,
                 ch_groups=kind,
                 title='',
                 show=False)
    fig_selection.radio = RadioButtons(
        rax, [key for key in keys if key in order.keys()])

    for circle in fig_selection.radio.circles:
        circle.set_radius(0.02)  # make them smaller to prevent overlap
        circle.set_edgecolor('gray')  # make sure the buttons are visible

    return order, fig_selection
Example #48
0
    def __init__(self):
        ''' The constructor creates instances of the walker, biker, and driver
        objects from the 'modes' module, sets a default distance and trip
        number, and then calculates the time, cost, calories,
        and CO2 emissions for all modes of tranit. Then it sets up graphs
        for displaying the information, as well as sliders, buttons, and
        RadioButtons for gathering user input. The functions that those
        buttons execute are defined internally.
        '''
        # Create instances of the driver, biker, and walker objects
        # Whose instance variables will be used heavily in calculations.
        self.d = Driver()
        self.b = Biker()
        self.w = Walker()

        # Default vaulues
        self.dist = 1
        self.trips = 1

        # Do initial calculations (calcualte returns calcDict)
        self.calcDict = self.calculate()

        # Create figure object which we will place everything on
        # of dimensions 14" by 10"
        self.fig = plt.figure(figsize=(14, 10))

        # Create 4 axes objects evenly spaced in a column. These will
        # hold the four graphs/figures (time, cost, calories, and CO2.)
        self.ax1 = self.fig.add_subplot(411)
        self.ax2 = self.fig.add_subplot(412)
        self.ax3 = self.fig.add_subplot(413)
        self.ax4 = self.fig.add_subplot(414)

        # Adjust the location of subplots (the axes holding graphs)
        self.fig.subplots_adjust(left=.74,
                                 right=.94,
                                 bottom=.18,
                                 top=.98,
                                 hspace=.25)

        ### Set up Buttons, RadioButtons, Sliders and their fcns! ###

        # The structure of setting up the temporary rax axes, then making
        # the RadioButton, then defining it's function, then adding the
        # on_clicked statement is taken from this example:
        # http://matplotlib.org/examples/widgets/radio_buttons.html

        axcolor = 'lightgoldenrodyellow'

        def getRadioPosList(ax):
            ''' This function is simply for positioning the 4 radio buttons
            used to change units approporatiely, vertically centered in
            relation to the adjacent graph. '''
            # Width and height are the same for each radio button
            widthRax = 0.12
            heightRax = 0.10

            # Find the lower (left) x value of adjacent graph
            # And construct appropriate x value for radio axes
            x0Ax = ax.get_position().get_points()[0, 0]
            xRax = x0Ax - (widthRax * 1.8)

            # Find lower and upper y values of the adjacent graph,
            # average them, and add half the height of the radiobutton axes
            # to determine a y value that will vertically center the radiobutton
            y0Ax = ax.get_position().get_points()[0, 1]
            y1Ax = ax.get_position().get_points()[1, 1]
            yRax = ((y0Ax + y1Ax) / 2) - (heightRax / 2)

            return [xRax, yRax, widthRax, heightRax]

        # Unit Change RadioButton 1: Change Time Units
        rax = plt.axes(getRadioPosList(self.ax1), axisbg=axcolor)
        self.radioTime = RadioButtons(rax, ('Hours', 'Minutes', 'Audiobooks'))

        def timeChange(label):
            self.updateGraph()
            plt.draw()

        self.radioTime.on_clicked(timeChange)

        # Unit Change RadioButton 2: Change Money Units
        rax = plt.axes(getRadioPosList(self.ax2), axisbg=axcolor)
        self.radioCost = RadioButtons(rax, ('Dollars', 'Coffees'))

        def costChange(label):
            self.updateGraph()
            plt.draw()

        self.radioCost.on_clicked(costChange)

        # Unit Change RadioButton 3: Change calorie burn units
        rax = plt.axes(getRadioPosList(self.ax3), axisbg=axcolor)
        self.radioCal = RadioButtons(rax, ('Cal (total)', 'Cal (/hour)'))

        def calChange(label):
            self.updateGraph()
            plt.draw()

        self.radioCal.on_clicked(calChange)

        # Unit Change RadioButton 4: Change CO2 Emissions Units
        rax = plt.axes(getRadioPosList(self.ax4), axisbg=axcolor)
        self.radioCO2 = RadioButtons(rax, ('CO2 (lbs)', 'CO2 (trees)'))

        def CO2Change(label):
            self.updateGraph()
            plt.draw()

        self.radioCO2.on_clicked(CO2Change)

        # Sliders 1 and 2: Distnace and Number of Trips
        # Axes and instance of slider for distance control
        axslideDist = plt.axes([0.17, 0.10, 0.77, 0.03], axisbg=axcolor)
        self.slideDist = Slider(axslideDist,
                                'Distance (miles)',
                                0.0,
                                100.0,
                                valinit=self.dist,
                                valfmt='%4.2f')
        # Axes and instance of slider for number of trips control
        axslideTrip = plt.axes([0.17, 0.05, 0.77, 0.03], axisbg=axcolor)
        self.slideTrip = Slider(axslideTrip,
                                'Trips',
                                0.0,
                                100.0,
                                valinit=self.trips,
                                valfmt='%4.2f')

        # Function for updating values after either slider is moved.
        def sliderUpdate(val):
            self.trips = self.slideTrip.val
            self.dist = self.slideDist.val
            self.calcDict = self.calculate()
            self.updateGraph()

        self.slideTrip.on_changed(sliderUpdate)
        self.slideDist.on_changed(sliderUpdate)

        axcolor = 'gold'

        # Customization RadioButton 1: Car - Car Type
        rax = plt.axes([.06, .72, .15, 0.2], axisbg=axcolor)
        rax.text(0, 1.15, "Customize Driving Info", fontsize=11)
        rax.text(0, 1.05, "Car Type", fontsize=11)
        self.radioCarType = RadioButtons(
            rax, ('Average', 'Small Sedan', 'Medium Sedan', 'Large Sedan',
                  '4WD/Sport', 'Minivan'))

        def carTypeChange(label):
            ''' Adjusts instance of driver object based on the category selected
            using the driver object's setCat function.'''
            if label == 'Average':
                self.d.setCat('average')
            elif label == 'Small Sedan':
                self.d.setCat('smallSedan')
            elif label == ('Medium Sedan'):
                self.d.setCat('mediumSedan')
            elif label == 'Large Sedan':
                self.d.setCat('largeSedan')
            elif label == '4WD/Sport':
                self.d.setCat('4wdSport')
            elif label == 'Minivan':
                self.d.setCat('minivan')
            else:
                print('Error!')
            self.updateGraph()
            plt.draw()

        self.radioCarType.on_clicked(carTypeChange)

        # Customization RadioButton 2: Bike - Spend on Bike
        rax = plt.axes([.26, .72, .15, 0.2], axisbg=axcolor)
        rax.text(0, 1.15, "Customize Biking Info:", fontsize=11)
        rax.text(0, 1.05, "Spend on parts/maintenance ($/year)", fontsize=11)
        self.radioBikeSpend = RadioButtons(
            rax,
            ('$0-25', '$25-50', '$50-100', '$100-150', '$150-200', '>$200'),
            active=2)

        def bikeSpendChange(label):
            ''' Adjusts instance of biker object based on selected spending,
            using the biker object's setSpend fcn. Then updates graph.'''
            if label == '$0-25':
                self.b.setSpend(12.5)
            elif label == '$25-50':
                self.b.setSpend(37.5)
            elif label == '$50-100':
                self.b.setSpend(75)
            elif label == ('$100-150'):
                self.b.setSpend(125)
            elif label == '$150-200':
                self.b.setSpend(175)
            elif label == '>$200':
                self.b.setSpend(250)
            else:
                print('Error!')
            self.updateGraph()
            plt.draw()

        self.radioBikeSpend.on_clicked(bikeSpendChange)

        # Customization RadioButton 3: Walk - Spend on Shoes
        rax = plt.axes([.06, .424, .15, 0.2], axisbg=axcolor)
        rax.text(0, 1.15, "Customize Walking Info:", fontsize=11)
        rax.text(0, 1.05, "Spend on a new pair of shoes", fontsize=11)
        self.radioWalkSpend = RadioButtons(
            rax,
            ('$0-25', '$25-50', '$50-100', '$100-150', '$150-200', '>$200'),
            active=1)

        def walkSpendChange(label):
            ''' Changes instance of walker object based on spending.'''
            if label == '$0-25':
                self.w.setSpend(12.5)
            elif label == '$25-50':
                self.w.setSpend(37.5)
            elif label == '$50-100':
                self.w.setSpend(75)
            elif label == ('$100-150'):
                self.w.setSpend(125)
            elif label == '$150-200':
                self.w.setSpend(175)
            elif label == '>$200':
                self.w.setSpend(250)
            else:
                print('Error!')
            self.updateGraph()
            plt.draw()

        self.radioWalkSpend.on_clicked(walkSpendChange)

        # Customization RadioButton 4: Person - Sex
        rax = plt.axes([.26, .424, .15, 0.2], axisbg=axcolor)
        rax.text(0, 1.15, "Customize Calorie Burn Info:", fontsize=11)
        rax.text(0, 1.05, "Sex", fontsize=11)
        self.radioPersonSex = RadioButtons(rax, ('Male', 'Female'), active=0)

        def personSexChange(label):
            ''' Changes the sex of the person instance of the current instnace
            of the driver, biker, and walker objects. So much OOP!!!!'''
            if label == 'Male':
                self.d.person.setSex('M', True)
                self.b.person.setSex('M', True)
                self.w.person.setSex('M', True)
            elif label == 'Female':
                self.d.person.setSex('F', True)
                self.b.person.setSex('F', True)
                self.w.person.setSex('F', True)
            else:
                print('Error!')
            self.updateGraph()
            plt.draw()

        self.radioPersonSex.on_clicked(personSexChange)

        # Reset Button
        axReset = plt.axes([0.17, 0.25, 0.15, 0.10])
        bReset = Button(axReset, 'Reset Defaults')

        def resetDefaults(event):
            ''' Resets all buttons/sliders to their default position,
            which triggers recalculations and redrawing of the
            graphs. This function is a little slow.'''
            self.slideDist.set_val(1)
            self.slideTrip.set_val(1)
            self.radioTime.set_active(0)
            self.radioCost.set_active(0)
            self.radioCal.set_active(0)
            self.radioCO2.set_active(0)
            self.radioCarType.set_active(0)
            self.radioBikeSpend.set_active(2)
            self.radioWalkSpend.set_active(1)
            self.radioPersonSex.set_active(0)
            plt.draw()

        bReset.on_clicked(resetDefaults)

        # These keep the current drawing current.
        self.updateGraph()
        plt.show()
        button.label.set_fontsize(8)

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

        button.on_clicked(reset)

        rax = plt.axes([
            0.025, 0.5 - 0.01 * num_tasks_sampled, 0.18,
            0.03 * num_tasks_sampled
        ],
                       facecolor=axcolor)
        radio = RadioButtons(rax, sample_task_ids, active=0)

        def update_y_test(label):
            # Update the target_data:
            (X_train, y_train), (X_test, y_test) = task_dict[label]
            l_button.set_ydata(y_train.data.numpy())
            l_button.set_xdata(X_train.data.numpy())
            l_button_test.set_ydata(y_test.data.numpy())
            l_button_test.set_xdata(X_test.data.numpy())

            # Update the fitted data:
            if is_VAE:
                statistics = statistics_Net(torch.cat([X_train, y_train],
                                                      1))[0][0]
            else:
                statistics = statistics_Net(torch.cat([X_train, y_train],
Example #50
0
class RunSim:
    ''' This class is the core of the program. It uses matplotlib to gather
    user input and dispaly results, and also preforms requisite calculations.'''
    def __init__(self):
        ''' The constructor creates instances of the walker, biker, and driver
        objects from the 'modes' module, sets a default distance and trip
        number, and then calculates the time, cost, calories,
        and CO2 emissions for all modes of tranit. Then it sets up graphs
        for displaying the information, as well as sliders, buttons, and
        RadioButtons for gathering user input. The functions that those
        buttons execute are defined internally.
        '''
        # Create instances of the driver, biker, and walker objects
        # Whose instance variables will be used heavily in calculations.
        self.d = Driver()
        self.b = Biker()
        self.w = Walker()

        # Default vaulues
        self.dist = 1
        self.trips = 1

        # Do initial calculations (calcualte returns calcDict)
        self.calcDict = self.calculate()

        # Create figure object which we will place everything on
        # of dimensions 14" by 10"
        self.fig = plt.figure(figsize=(14, 10))

        # Create 4 axes objects evenly spaced in a column. These will
        # hold the four graphs/figures (time, cost, calories, and CO2.)
        self.ax1 = self.fig.add_subplot(411)
        self.ax2 = self.fig.add_subplot(412)
        self.ax3 = self.fig.add_subplot(413)
        self.ax4 = self.fig.add_subplot(414)

        # Adjust the location of subplots (the axes holding graphs)
        self.fig.subplots_adjust(left=.74,
                                 right=.94,
                                 bottom=.18,
                                 top=.98,
                                 hspace=.25)

        ### Set up Buttons, RadioButtons, Sliders and their fcns! ###

        # The structure of setting up the temporary rax axes, then making
        # the RadioButton, then defining it's function, then adding the
        # on_clicked statement is taken from this example:
        # http://matplotlib.org/examples/widgets/radio_buttons.html

        axcolor = 'lightgoldenrodyellow'

        def getRadioPosList(ax):
            ''' This function is simply for positioning the 4 radio buttons
            used to change units approporatiely, vertically centered in
            relation to the adjacent graph. '''
            # Width and height are the same for each radio button
            widthRax = 0.12
            heightRax = 0.10

            # Find the lower (left) x value of adjacent graph
            # And construct appropriate x value for radio axes
            x0Ax = ax.get_position().get_points()[0, 0]
            xRax = x0Ax - (widthRax * 1.8)

            # Find lower and upper y values of the adjacent graph,
            # average them, and add half the height of the radiobutton axes
            # to determine a y value that will vertically center the radiobutton
            y0Ax = ax.get_position().get_points()[0, 1]
            y1Ax = ax.get_position().get_points()[1, 1]
            yRax = ((y0Ax + y1Ax) / 2) - (heightRax / 2)

            return [xRax, yRax, widthRax, heightRax]

        # Unit Change RadioButton 1: Change Time Units
        rax = plt.axes(getRadioPosList(self.ax1), axisbg=axcolor)
        self.radioTime = RadioButtons(rax, ('Hours', 'Minutes', 'Audiobooks'))

        def timeChange(label):
            self.updateGraph()
            plt.draw()

        self.radioTime.on_clicked(timeChange)

        # Unit Change RadioButton 2: Change Money Units
        rax = plt.axes(getRadioPosList(self.ax2), axisbg=axcolor)
        self.radioCost = RadioButtons(rax, ('Dollars', 'Coffees'))

        def costChange(label):
            self.updateGraph()
            plt.draw()

        self.radioCost.on_clicked(costChange)

        # Unit Change RadioButton 3: Change calorie burn units
        rax = plt.axes(getRadioPosList(self.ax3), axisbg=axcolor)
        self.radioCal = RadioButtons(rax, ('Cal (total)', 'Cal (/hour)'))

        def calChange(label):
            self.updateGraph()
            plt.draw()

        self.radioCal.on_clicked(calChange)

        # Unit Change RadioButton 4: Change CO2 Emissions Units
        rax = plt.axes(getRadioPosList(self.ax4), axisbg=axcolor)
        self.radioCO2 = RadioButtons(rax, ('CO2 (lbs)', 'CO2 (trees)'))

        def CO2Change(label):
            self.updateGraph()
            plt.draw()

        self.radioCO2.on_clicked(CO2Change)

        # Sliders 1 and 2: Distnace and Number of Trips
        # Axes and instance of slider for distance control
        axslideDist = plt.axes([0.17, 0.10, 0.77, 0.03], axisbg=axcolor)
        self.slideDist = Slider(axslideDist,
                                'Distance (miles)',
                                0.0,
                                100.0,
                                valinit=self.dist,
                                valfmt='%4.2f')
        # Axes and instance of slider for number of trips control
        axslideTrip = plt.axes([0.17, 0.05, 0.77, 0.03], axisbg=axcolor)
        self.slideTrip = Slider(axslideTrip,
                                'Trips',
                                0.0,
                                100.0,
                                valinit=self.trips,
                                valfmt='%4.2f')

        # Function for updating values after either slider is moved.
        def sliderUpdate(val):
            self.trips = self.slideTrip.val
            self.dist = self.slideDist.val
            self.calcDict = self.calculate()
            self.updateGraph()

        self.slideTrip.on_changed(sliderUpdate)
        self.slideDist.on_changed(sliderUpdate)

        axcolor = 'gold'

        # Customization RadioButton 1: Car - Car Type
        rax = plt.axes([.06, .72, .15, 0.2], axisbg=axcolor)
        rax.text(0, 1.15, "Customize Driving Info", fontsize=11)
        rax.text(0, 1.05, "Car Type", fontsize=11)
        self.radioCarType = RadioButtons(
            rax, ('Average', 'Small Sedan', 'Medium Sedan', 'Large Sedan',
                  '4WD/Sport', 'Minivan'))

        def carTypeChange(label):
            ''' Adjusts instance of driver object based on the category selected
            using the driver object's setCat function.'''
            if label == 'Average':
                self.d.setCat('average')
            elif label == 'Small Sedan':
                self.d.setCat('smallSedan')
            elif label == ('Medium Sedan'):
                self.d.setCat('mediumSedan')
            elif label == 'Large Sedan':
                self.d.setCat('largeSedan')
            elif label == '4WD/Sport':
                self.d.setCat('4wdSport')
            elif label == 'Minivan':
                self.d.setCat('minivan')
            else:
                print('Error!')
            self.updateGraph()
            plt.draw()

        self.radioCarType.on_clicked(carTypeChange)

        # Customization RadioButton 2: Bike - Spend on Bike
        rax = plt.axes([.26, .72, .15, 0.2], axisbg=axcolor)
        rax.text(0, 1.15, "Customize Biking Info:", fontsize=11)
        rax.text(0, 1.05, "Spend on parts/maintenance ($/year)", fontsize=11)
        self.radioBikeSpend = RadioButtons(
            rax,
            ('$0-25', '$25-50', '$50-100', '$100-150', '$150-200', '>$200'),
            active=2)

        def bikeSpendChange(label):
            ''' Adjusts instance of biker object based on selected spending,
            using the biker object's setSpend fcn. Then updates graph.'''
            if label == '$0-25':
                self.b.setSpend(12.5)
            elif label == '$25-50':
                self.b.setSpend(37.5)
            elif label == '$50-100':
                self.b.setSpend(75)
            elif label == ('$100-150'):
                self.b.setSpend(125)
            elif label == '$150-200':
                self.b.setSpend(175)
            elif label == '>$200':
                self.b.setSpend(250)
            else:
                print('Error!')
            self.updateGraph()
            plt.draw()

        self.radioBikeSpend.on_clicked(bikeSpendChange)

        # Customization RadioButton 3: Walk - Spend on Shoes
        rax = plt.axes([.06, .424, .15, 0.2], axisbg=axcolor)
        rax.text(0, 1.15, "Customize Walking Info:", fontsize=11)
        rax.text(0, 1.05, "Spend on a new pair of shoes", fontsize=11)
        self.radioWalkSpend = RadioButtons(
            rax,
            ('$0-25', '$25-50', '$50-100', '$100-150', '$150-200', '>$200'),
            active=1)

        def walkSpendChange(label):
            ''' Changes instance of walker object based on spending.'''
            if label == '$0-25':
                self.w.setSpend(12.5)
            elif label == '$25-50':
                self.w.setSpend(37.5)
            elif label == '$50-100':
                self.w.setSpend(75)
            elif label == ('$100-150'):
                self.w.setSpend(125)
            elif label == '$150-200':
                self.w.setSpend(175)
            elif label == '>$200':
                self.w.setSpend(250)
            else:
                print('Error!')
            self.updateGraph()
            plt.draw()

        self.radioWalkSpend.on_clicked(walkSpendChange)

        # Customization RadioButton 4: Person - Sex
        rax = plt.axes([.26, .424, .15, 0.2], axisbg=axcolor)
        rax.text(0, 1.15, "Customize Calorie Burn Info:", fontsize=11)
        rax.text(0, 1.05, "Sex", fontsize=11)
        self.radioPersonSex = RadioButtons(rax, ('Male', 'Female'), active=0)

        def personSexChange(label):
            ''' Changes the sex of the person instance of the current instnace
            of the driver, biker, and walker objects. So much OOP!!!!'''
            if label == 'Male':
                self.d.person.setSex('M', True)
                self.b.person.setSex('M', True)
                self.w.person.setSex('M', True)
            elif label == 'Female':
                self.d.person.setSex('F', True)
                self.b.person.setSex('F', True)
                self.w.person.setSex('F', True)
            else:
                print('Error!')
            self.updateGraph()
            plt.draw()

        self.radioPersonSex.on_clicked(personSexChange)

        # Reset Button
        axReset = plt.axes([0.17, 0.25, 0.15, 0.10])
        bReset = Button(axReset, 'Reset Defaults')

        def resetDefaults(event):
            ''' Resets all buttons/sliders to their default position,
            which triggers recalculations and redrawing of the
            graphs. This function is a little slow.'''
            self.slideDist.set_val(1)
            self.slideTrip.set_val(1)
            self.radioTime.set_active(0)
            self.radioCost.set_active(0)
            self.radioCal.set_active(0)
            self.radioCO2.set_active(0)
            self.radioCarType.set_active(0)
            self.radioBikeSpend.set_active(2)
            self.radioWalkSpend.set_active(1)
            self.radioPersonSex.set_active(0)
            plt.draw()

        bReset.on_clicked(resetDefaults)

        # These keep the current drawing current.
        self.updateGraph()
        plt.show()

    def calculate(self):
        ''' This function does all the calculating behind the program. It uses
        attributes of the driver, walker, and biker object's to calculate
        values for time, cost, calorie burn, and CO2 emitted in various units.
        This information is stored in the handy-dandy dictionary: calcDict.'''

        # Dictionary that holds calculations for different categories in the form
        # of lists, where [0]=driver, [1]=biker, [2]=walker
        calcDict = {
            'time': [],
            'cost': [],
            'cal': [],
            'time-mins': [],
            'time-audio': [],
            'cost-coffee': [],
            'cal-hour': [],
            'cal-sansBMR': [],
            'CO2': 0.0,
            'CO2-tree': 0.0
        }

        # Time in hours
        calcDict['time'].append(self.dist * self.trips / self.d.getMPH())
        calcDict['time'].append(self.dist * self.trips / self.b.getMPH())
        calcDict['time'].append(self.dist * self.trips / self.w.getMPH())

        # Cost in US dollars
        calcDict['cost'].append(self.d.getCost() * self.dist * self.trips)
        calcDict['cost'].append(self.b.getCost() * self.dist * self.trips)
        calcDict['cost'].append(self.w.getCost() * self.dist * self.trips)

        # Total calories burned
        calcDict['cal'].append(self.d.person.getCal() * calcDict['time'][0])
        calcDict['cal'].append(self.b.person.getCal() * calcDict['time'][1])
        calcDict['cal'].append(self.w.person.getCal() * calcDict['time'][2])

        ## Alternative units for above categories

        # Time in audiobooks (based on avg len of 12.59 hours)
        # Note: avg length determined from sample of 25 bestsellers on Audible.com
        calcDict['time-mins'].append(calcDict['time'][0] * 60)
        calcDict['time-mins'].append(calcDict['time'][1] * 60)
        calcDict['time-mins'].append(calcDict['time'][2] * 60)

        # Time in audiobooks (based on avg len of 12.59 hours)
        # Note: avg length determined from sample of 25 bestsellers on Audible.com
        calcDict['time-audio'].append(calcDict['time'][0] / 12.59)
        calcDict['time-audio'].append(calcDict['time'][1] / 12.59)
        calcDict['time-audio'].append(calcDict['time'][2] / 12.59)

        #Cost in terms of coffee at blue Mondays burned per hour
        calcDict['cost-coffee'].append(calcDict['cost'][0] / 2.60)
        calcDict['cost-coffee'].append(calcDict['cost'][1] / 2.60)
        calcDict['cost-coffee'].append(calcDict['cost'][2] / 2.60)

        #Cal burned per hour
        calcDict['cal-hour'].append(self.d.person.getCal())
        calcDict['cal-hour'].append(self.b.person.getCal())
        calcDict['cal-hour'].append(self.w.person.getCal())

        # CO2 emissions in lbs
        calcDict['CO2'] = self.d.getCO2() * (self.dist * self.trips)

        # CO2 emissions in terms of trees planted
        # A single tree planted thru americanforests.org sequesters 911 pounds of CO2
        # This value reflects the number of trees one should plant to sequester the carbon
        # emitted by driving
        calcDict['CO2-tree'] = (calcDict['CO2'] / 911)

        return calcDict

    def makeGraph(self, ax, data, ylab):
        ''' makeGraph is called by updateGraph and redraws the 3 graphs
        every time it is called. The x labels are always the same but the
        y values are passed in as 'data'. '''

        ax.clear()

        N = 3  # 3 divisions of x axis
        maxNum = max(data)  # determine max y value

        ind = np.arange(N)  # the x locations for the groups
        width = 0.5  # the width of the bars

        ## the bars
        rects1 = ax.bar(ind, data, width, color=['cyan', 'yellow', 'magenta'])

        # axes and labels
        ax.set_xlim(-.1, len(ind) - .4)
        ax.set_ylim(0, maxNum + (maxNum / 10) * 2)

        xTickMarks = ['Drive', 'Bike', 'Walk']
        ax.set_xticks(ind + (width / 2))
        xtickNames = ax.set_xticklabels(xTickMarks)
        ax.set_ylabel(ylab)

        def autolabel(rects):
            ''' Adds labels above bars. Code adapted from matplotlib demo code:
            http://matplotlib.org/examples/api/barchart_demo.html'''
            # attach some text labels
            for rect in rects:
                height = rect.get_height()
                ax.text(rect.get_x() + rect.get_width() / 2.,
                        1.05 * height,
                        '%4.2f' % (height),
                        fontsize=11,
                        ha='center',
                        va='bottom')

        autolabel(rects1)

    def showInfo(self, ax, data, msg):
        ''' The forth subplot (axes) holds text instead of a bar plot
        and it gets updated using this function.'''

        # Erase any existing information to avoid redrawing
        ax.clear()

        # Remove labels
        ax.set_xticklabels('')
        ax.set_yticklabels('')

        ax.text(.08, .70, "By not driving...", fontsize=11)

        ax.text(.4,
                .45,
                '%4.2f' % (data),
                style='italic',
                bbox={
                    'facecolor': 'lightgreen',
                    'alpha': 0.65,
                    'pad': 10
                })
        ax.text(.08, .20, msg, fontsize=11)

    def updateGraph(self):
        ''' This is called whenever the graph needs to be updated. It calls
        self.calculate to make sure self.calcDate is up to date and it uses
        the values of the radio buttons and sliders as well as the values stored
        in calcDict to determine which y values to pass into makeGraph to
        make the 3 graphs and which values to pass to showInfo.'''

        self.calcDict = self.calculate()

        if self.radioTime.value_selected == 'Hours':
            self.makeGraph(self.ax1, self.calcDict['time'], 'Time (Hours)')
        elif self.radioTime.value_selected == 'Minutes':
            self.makeGraph(self.ax1, self.calcDict['time-mins'],
                           'Time (Minutes)')
        elif self.radioTime.value_selected == 'Audiobooks':
            self.makeGraph(self.ax1, self.calcDict['time-audio'],
                           'Time (Audiobooks)')

        if self.radioCost.value_selected == 'Dollars':
            self.makeGraph(self.ax2, self.calcDict['cost'], 'Cost ($)')
        elif self.radioCost.value_selected == 'Coffees':
            self.makeGraph(self.ax2, self.calcDict['cost-coffee'],
                           'Cost (Coffees)')
        else:
            print('Error!')

        if self.radioCal.value_selected == 'Cal (total)':
            self.makeGraph(self.ax3, self.calcDict['cal'], 'Calories (total)')
        elif self.radioCal.value_selected == 'Cal (/hour)':
            self.makeGraph(self.ax3, self.calcDict['cal-hour'],
                           'Calories (/hour)')
        else:
            print('Error!')

        if self.radioCO2.value_selected == 'CO2 (lbs)':
            self.showInfo(self.ax4, self.calcDict['CO2'],
                          'Pounds of CO2 not emitted')
        elif self.radioCO2.value_selected == 'CO2 (trees)':
            self.showInfo(self.ax4, self.calcDict['CO2-tree'],
                          'Trees planted!')
        else:
            print('Error!')
Example #51
0
dust_slider = Slider(ax_dust, 'Dust', -1, 2.5, valinit=0)
hot_gas_slider = Slider(ax_hot_gas, 'Hot Gas', -1, 2.5, valinit=0)
cold_gas_slider = Slider(ax_cold_gas, 'Cold Gas', -1, 2.5, valinit=0)

###############################################################################

#### Radio Buttons ####

radio_length = 0.10
radio_height = 0.10
radio_separation = 0.12
ax_y = plot.axes([
    0.05, slider_y + slider_height - radio_height, radio_length, radio_height
])
radio_y = RadioButtons(ax_y, ('linear', 'log'), active=0)

ax_norm = plot.axes([
    0.05, slider_y + slider_height - radio_height - radio_separation,
    radio_length + 0.10, radio_height
])
radio_norm = RadioButtons(ax_norm, ('normalize blue', 'normalize red'),
                          active=0)

###############################################################################

### Slider Listeners ###


def update(val):
    num_b = b_slider.val
Example #52
0
def change_capa(event):
    amplifier.set_cap_neut_enable(True, 0)
    amplifier.set_cap_neut_level(capa_button.val, 0)


def change_gain(event):
    amplifier.set_loop_gain(gain_button.val, 1)


def change_lag(event):
    amplifier.set_loop_lag(lag_button.val, 1)


ax_mode = plt.axes([0.05, 0.025, 0.2, 0.125], frameon=False)
mode_button = RadioButtons(ax_mode, ['CC', 'TEVC'])
mode_button.on_clicked(change_mode)

ax_bridge = plt.axes([0.5, 0.025, 0.3, 0.05])
bridge_button = Slider(ax_bridge, 'Bridge', 0, 100, 0)
bridge_button.on_changed(change_bridge)

range = amplifier.get_cap_neut_range(0)
ax_capa = plt.axes([0.5, 0.075, 0.3, 0.05])
capa_button = Slider(ax_capa, 'Capacitance', range.dValMin, range.dValMax, 0)
capa_button.on_changed(change_capa)

ax_gain = plt.axes([0.5, 0.125, 0.3, 0.05])
gain_button = Slider(ax_gain, 'Gain', 20, 500, 20)
gain_button.on_changed(change_gain)
Example #53
0
            global mask, visibility
            if visibility:
                mask = mask_base
                visibility = False

            else:
                mask = mask_vel
                visibility = True

        check.on_clicked(func)

    #%% Radio buttom for velocity selection
    axrad_vel = pv.add_axes([0.01, 0.65, 0.1, 0.1])

    if cumfile2:
        radio_vel = RadioButtons(axrad_vel, ('vel', 'vel2'))
        mapdict_vel = {'vel': vel, 'vel2': vel2}
    else:
        radio_vel = RadioButtons(axrad_vel, ('vel', ))
        mapdict_vel = {'vel': vel}

    def show_vel(val):
        global vmin, vmax
        data = mapdict_vel[val] * mask
        data = data - np.nanmean(data[refy1:refy2, refx1:refx2])

        if vlimauto:  ## auto
            vmin = np.nanpercentile(data * mask, 100 - auto_crange)
            vmax = np.nanpercentile(data * mask, auto_crange)

        cax.set_data(data)
Example #54
0
    fig, axSimPlot = plt.subplots(1, 1,  figsize=(8, 7))
    # レーダの検知可能範囲を描画
    axSimPlot.plot(simObject.leftScanBoundary[0,:]/1000, simObject.leftScanBoundary[1,:]/1000, c='#212121')
    axSimPlot.plot(simObject.rightScanBoundary[0,:]/1000, simObject.rightScanBoundary[1,:]/1000, c='#212121')
    axSimPlot.set_xlabel('X [m]')
    axSimPlot.set_ylabel('Y [m]')
    axSimPlot.set_xlim([0, 140])
    axSimPlot.set_ylim([-80, 80])
    axSimPlot.grid()
    axSimPlot.axis('equal')
    fig.tight_layout()
    fig.subplots_adjust(left=0.25, bottom=0.2, right=None, top=None)

    # シミュレーションを終了させるラジオボタンオブジェクト
    axQuitBttn  = plt.axes([0.05, 0.7, 0.1, 0.1], facecolor=radioButtonColor)
    quitBttnObj = RadioButtons(axQuitBttn, ('Run', 'Quit'))
    # 動作フラグを定義
    global simRunFlag
    simRunFlag = True
    # ボタンが押された時の動作を制御する関数
    def SwitchSimRunOrQuit(label):
        global simRunFlag
        if label == 'Run':
            simRunFlag = True
        elif label == 'Quit':
            simRunFlag = False
        else:
            simRunFlag = True
    # ボタンが押されたら関数を呼び出す
    quitBttnObj.on_clicked(SwitchSimRunOrQuit)
sxamp = Slider(xamp, 'A', 0, 3, valinit=A)
syamp = Slider(yamp, 'B', 0, 3, valinit=B)
sxfreq = Slider(xfreq, 'a', 0, 4, valinit=a)
syfreq = Slider(yfreq, 'c', 0, 4, valinit=c)
sxphase = Slider(xphase, 'b', 0, 7, valinit=b)
syphase = Slider(yphase, 'd', 0, 7, valinit=d)
sphase_diff = Slider(phase_diff, 'Rotate', 0, 1, valinit=r)

#Text in window
plt.text(0.40, -0.90, 'controlers', fontsize=14)

#Radio button for graphs
radio = RadioButtons(
    rax, ('(0,0)', 'y=0', 'x=0', 'y=x(/)', 'y=-x(\)', 'y=x^2(∪)', 'y=-x^2(∩)',
          'x=y^2(⊂)', 'x=-y^2(⊃)', 'x^2+y^2=1(o)', 'Eight(8)', 'Infinity(∞)',
          'N', 'И', 'Z', 'S', 'Alpha(∝)', 'Mirror of ∝', 'Gujarati four',
          'Mirror of Gujarati four', 'Rotation(∪,∩)3D', 'Rotation(⊂,⊃)3D',
          'Rotation(N,И)3D', 'Rotation(Z,S)3D', 'Bangles_X', 'Bangles_Y',
          'Crown_X', 'Crown_Y', 'Atom'),
    active=3)


#animation function
def animate(i):
    #not creating exctra variable using global variables
    global A
    global B
    global a
    global b
    global c
    global d
    global r
Example #56
0
    regularization_strenght = (np.exp(val) - 1) / 40000
    if regularized and init:
        update_graph(1)


def change_reg_type(label):
    global reg_type
    reg_type = label


btn_axes = plt.axes([0.75, 0.20, 0.2, 0.06])
fit_button = Button(btn_axes, 'fit')

radio_axes = plt.axes([0.75, 0.68, 0.2, 0.2])
radio_axes.set_title('basis function')
radio_buttons = RadioButtons(radio_axes, ('polynomial', 'gaussian'))
radio_buttons.on_clicked(change_basis_function)

reg_radio_axes = plt.axes([0.75, 0.5, 0.2, 0.15])
reg_button = RadioButtons(reg_radio_axes,
                          ('no regularization', 'regularization'))
reg_button.on_clicked(reg_button_click)

reg_type_axes = plt.axes([0.75, 0.32, 0.2, 0.15])
reg_type_button = RadioButtons(reg_type_axes,
                               ('regularization', 'curvature penalty'))
reg_type_button.on_clicked(change_reg_type)

slider_axes = plt.axes([0.2, 0.08, 0.65, 0.04])
reg_slider = Slider(slider_axes,
                    'regularization stenght',
Example #57
0
class ObjFindGUI(object):
    """
    GUI to interactively identify object traces. The GUI can be run within
    PypeIt during data reduction, or as a standalone script outside of
    PypeIt. To initialise the GUI, call the initialise() function in this
    file.
    """
    def __init__(self,
                 canvas,
                 image,
                 frame,
                 det,
                 sobjs,
                 trace_dict,
                 axes,
                 profdict,
                 slit_ids=None,
                 printout=False,
                 runtime=False):
        """Controls for the interactive Object ID tasks in PypeIt.

        The main goal of this routine is to interactively add/delete/modify
        object apertures.

        Args:
            canvas (Matploltib figure canvas): The canvas on which all axes are contained
            image (AxesImage): The image plotted to screen
            frame (ndarray): The image data
            det (int): Detector to add a slit on
            sobjs (SpecObjs, None): An instance of the SpecObjs class
            trace_dict (dict): A dictionary containing information about the object traces
            axes (dict): Dictionary of four Matplotlib axes instances (Main spectrum panel, two for residuals, one for information)
            profdict (dict): Dictionary containing profile information (profile data, and the left/right lines displayinf the FWHM)
            slit_ids (list, None): List of slit ID numbers
            printout (bool): Should the results be printed to screen
            runtime (bool): Is the GUI being launched during data reduction?
        """
        # Store the axes
        self._det = det
        self.image = image
        self.frame = frame
        self.nspec, self.nspat = frame.shape[0], frame.shape[1]
        self._spectrace = np.arange(self.nspec)
        self.profile = profdict
        self._printout = printout
        self._runtime = runtime
        self._slit_ids = slit_ids
        self._trcdict = trace_dict
        self.axes = axes
        self.specobjs = sobjs
        self.objtraces = []
        self._object_traces = ObjectTraces()
        self.anchors = []
        self._obj_idx = -1
        self._spatpos = np.arange(frame.shape[1])[np.newaxis, :].repeat(
            frame.shape[0], axis=0)  # Spatial coordinate (as the frame shape)
        self.empty_mantrace()
        if sobjs is None:
            self._object_traces.from_dict(self._trcdict['objtrc'], det)
        else:
            self._object_traces.from_specobj(sobjs, det)

        # Unset some of the matplotlib keymaps
        matplotlib.pyplot.rcParams[
            'keymap.fullscreen'] = ''  # toggling fullscreen (Default: f, ctrl+f)
        #matplotlib.pyplot.rcParams['keymap.home'] = ''              # home or reset mnemonic (Default: h, r, home)
        matplotlib.pyplot.rcParams[
            'keymap.back'] = ''  # forward / backward keys to enable (Default: left, c, backspace)
        matplotlib.pyplot.rcParams[
            'keymap.forward'] = ''  # left handed quick navigation (Default: right, v)
        #matplotlib.pyplot.rcParams['keymap.pan'] = ''              # pan mnemonic (Default: p)
        matplotlib.pyplot.rcParams[
            'keymap.zoom'] = ''  # zoom mnemonic (Default: o)
        matplotlib.pyplot.rcParams[
            'keymap.save'] = ''  # saving current figure (Default: s)
        matplotlib.pyplot.rcParams[
            'keymap.quit'] = ''  # close the current figure (Default: ctrl+w, cmd+w)
        matplotlib.pyplot.rcParams[
            'keymap.grid'] = ''  # switching on/off a grid in current axes (Default: g)
        matplotlib.pyplot.rcParams[
            'keymap.yscale'] = ''  # toggle scaling of y-axes ('log'/'linear') (Default: l)
        matplotlib.pyplot.rcParams[
            'keymap.xscale'] = ''  # toggle scaling of x-axes ('log'/'linear') (Default: L, k)
        matplotlib.pyplot.rcParams[
            'keymap.all_axes'] = ''  # enable all axes (Default: a)

        # Initialise the main canvas tools
        canvas.mpl_connect('draw_event', self.draw_callback)
        canvas.mpl_connect('button_press_event', self.button_press_callback)
        canvas.mpl_connect('key_press_event', self.key_press_callback)
        canvas.mpl_connect('button_release_event',
                           self.button_release_callback)
        canvas.mpl_connect('motion_notify_event', self.mouse_move_callback)
        self.canvas = canvas

        # Interaction variables
        self._respreq = [
            False, None
        ]  # Does the user need to provide a response before any other operation will be permitted? Once the user responds, the second element of this array provides the action to be performed.
        self._qconf = False  # Confirm quit message
        self._changes = False
        self._use_updates = True
        self._trcmthd = 'object'
        self.mmx, self.mmy = 0, 0
        self._inslit = 0  # Which slit is the mouse in

        # Draw the spectrum
        self.canvas.draw()

        # Initialise buttons and menu options
        self._ax_meth_default = 'Object'
        self._methdict = dict({
            'Object': [0, 'object'],
            'Standard Star': [1, 'std'],
            'Slit Edges': [2, 'slit']
        })
        #                               'Manual': [3, 'manual']
        self.initialise_menu()

    def print_help(self):
        """Print the keys and descriptions that can be used for Identification
        """
        keys = operations.keys()
        print(
            "===============================================================")
        print(
            "Add/remove object traces until you are happy with the resulting")
        print("traces. When you've finished, click one of the exit buttons on")
        print(
            "the right side of the page. If you click 'Continue (and save changes)'"
        )
        print(
            "the object traces will be printed to the terminal, where you can")
        print("copy them into your .pypeit file.")
        print("")
        print("thick coloured dashed lines = object traces")
        print("thick coloured solid line   = currently selected object trace")
        print("thin green/blue lines       = slit edges")
        print("")
        print("Meanings of the different coloured dashed lines:")
        print(" green = user-defined object trace")
        print(" blue  = trace automatically generated with PypeIt")
        print(" red   = trace automatically generated with PypeIt (deleted)")
        print(
            "===============================================================")
        print("       OBJECT ID OPERATIONS")
        for key in keys:
            print("{0:6s} : {1:s}".format(key, operations[key]))
        print(
            "---------------------------------------------------------------")

    def initialise_menu(self):
        """Initialise the menu buttons
        """
        axcolor = 'lightgoldenrodyellow'
        # Continue with reduction (using updated specobjs)
        ax_cont = plt.axes([0.82, 0.85, 0.15, 0.05])
        self._ax_cont = Button(ax_cont,
                               "Continue (and save changes)",
                               color=axcolor,
                               hovercolor='y')
        self._ax_cont.on_clicked(self.button_cont)
        # Continue with reduction (using original specobjs)
        ax_exit = plt.axes([0.82, 0.79, 0.15, 0.05])
        self._ax_exit = Button(ax_exit,
                               "Continue (don't save changes)",
                               color=axcolor,
                               hovercolor='y')
        self._ax_exit.on_clicked(self.button_exit)
        # Button to select trace method
        rax = plt.axes([0.82, 0.59, 0.15, 0.15], facecolor=axcolor)
        rax.set_title("Select trace method:")
        self._ax_meth = RadioButtons(
            rax, ('Object', 'Standard Star', 'Slit Edges'))  #, 'Manual'))
        self._ax_meth.on_clicked(self.radio_meth)
        # Determine the best default to use:
        if self._trcdict["trace_model"]["object"]["trace_model"] is not None:
            self._ax_meth_default = 'Object'
        elif self._trcdict["trace_model"]["std"]["trace_model"] is not None:
            self._ax_meth_default = 'Standard Star'
        elif self._trcdict["trace_model"]["slit"]["trace_model"] is not None:
            self._ax_meth_default = 'Slit Edges'
#        elif self._trcdict["trace_model"]["manual"]["trace_model"] is not None:
#            self._ax_meth_default = 'Manual'
# Set the active method
        self._ax_meth.set_active(self._methdict[self._ax_meth_default][0])

    def radio_meth(self, label, infobox=True):
        """Tell the code what to do when a different trace method is selected

        Args:
            label (str): The label of the radio button that was clicked
        """
        # Update the radio button
        if self._methdict[label][1]:
            self._trcmthd = self._methdict[label][1]
        # Check if the method is available, if not, change to the default (manual is always allowed)
        if self._trcmthd != "manual":
            if self._trcdict["trace_model"][
                    self._trcmthd]["trace_model"] is None:
                self.update_infobox(
                    message=
                    "That option is not available - changing to default",
                    yesno=False)
                self._ax_meth.set_active(
                    self._methdict[self._ax_meth_default][0])
                self._trcmthd = self._methdict[self._ax_meth_default][1]
            else:
                if infobox:
                    self.update_infobox(
                        message="Trace method set to: {0:s}".format(label),
                        yesno=False)
        else:
            if infobox:
                self.update_infobox(
                    message="Trace method set to: {0:s}".format(label),
                    yesno=False)

    def button_cont(self, event):
        """What to do when the 'exit and save' button is clicked
        """
        self._respreq = [True, "exit_update"]
        self.update_infobox(
            message=
            "Are you sure you want to exit and use the updated object traces?",
            yesno=True)

    def button_exit(self, event):
        """What to do when the 'exit and do not save changes' button is clicked
        """
        self._respreq = [True, "exit_restore"]
        self.update_infobox(
            message=
            "Are you sure you want to exit and use the original object traces?",
            yesno=True)

    def replot(self):
        """Redraw the entire canvas
        """
        self.canvas.restore_region(self.background)
        self.draw_objtraces()
        self.draw_anchors()
        self.canvas.draw()

    def draw_objtraces(self):
        """Draw the object traces
        """
        for i in self.objtraces:
            i.pop(0).remove()
        self.objtraces = []
        # Plot the object traces
        allcols = ['DodgerBlue', 'LimeGreen',
                   'r']  # colors mean: [original, added, deleted]
        for iobj in range(self._object_traces.nobj):
            color = allcols[self._object_traces._add_rm[iobj]]
            if iobj == self._obj_idx:
                self.objtraces.append(self.axes['main'].plot(
                    self._object_traces._trace_spat[iobj],
                    self._object_traces._trace_spec[iobj],
                    color=color,
                    linestyle='-',
                    linewidth=4,
                    alpha=0.5))
            else:
                self.objtraces.append(self.axes['main'].plot(
                    self._object_traces._trace_spat[iobj],
                    self._object_traces._trace_spec[iobj],
                    color=color,
                    linestyle='--',
                    linewidth=3,
                    alpha=0.5))

    def draw_anchors(self):
        """Draw the anchors for manual tracing
        """
        for i in self.anchors:
            i.pop(0).remove()
        self.anchors = []
        # Plot the best fitting trace, if it exists
        if self._mantrace["spat_trc"] is not None:
            self.anchors.append(self.axes['main'].plot(
                self._mantrace["spat_trc"],
                self._mantrace["spec_trc"],
                'g-',
                linewidth=3,
                alpha=0.5))
        # Plot the anchor points on top
        self.anchors.append(self.axes['main'].plot(self._mantrace["spat_a"],
                                                   self._mantrace["spec_a"],
                                                   'ro',
                                                   alpha=0.5))

    def draw_profile(self):
        """Draw the object profile
        """
        if self._obj_idx == -1:
            sz = self.profile['profile'].get_xdata.size
            self.profile['profile'].set_ydata(np.zeros(sz))
        else:
            # Plot the extent of the FWHM
            self.profile['fwhm'][0].set_xdata(
                -self._object_traces._fwhm[self._obj_idx] / 2.0)
            self.profile['fwhm'][1].set_xdata(
                +self._object_traces._fwhm[self._obj_idx] / 2.0)
            # Update the data shown
            objprof = self.make_objprofile()
            self.profile['profile'].set_ydata(objprof)
            self.axes['profile'].set_xlim([
                -self._object_traces._fwhm[self._obj_idx],
                +self._object_traces._fwhm[self._obj_idx]
            ])
            omin, omax = objprof.min(), objprof.max()
            self.axes['profile'].set_ylim(
                [omin - 0.1 * (omax - omin), omax + 0.1 * (omax - omin)])

    def draw_callback(self, event):
        """Draw callback (i.e. everytime the canvas is being drawn/updated)

        Args:
            event (Event): A matplotlib event instance
        """
        # Get the background
        self.background = self.canvas.copy_from_bbox(self.axes['main'].bbox)
        self.draw_objtraces()

    def get_ind_under_point(self, event):
        """Get the index of the object trace closest to the cursor

        Args:
            event (Event): Matplotlib event instance containing information about the event
        """
        mindist = self._spatpos.shape[0]**2
        self._obj_idx = -1
        for iobj in range(self._object_traces.nobj):
            dist = (event.xdata-self._object_traces._trace_spat[iobj])**2 +\
                   (event.ydata-self._object_traces._trace_spec[iobj])**2
            if np.min(dist) < mindist:
                mindist = np.min(dist)
                self._obj_idx = iobj
        if self._obj_idx != -1:
            self.draw_profile()
        return

    def get_axisID(self, event):
        """Get the ID of the axis where an event has occurred

        Args:
            event (Event): Matplotlib event instance containing information about the event

        Returns:
            int, None: Axis where the event has occurred
        """
        if event.inaxes == self.axes['main']:
            return 0
        elif event.inaxes == self.axes['info']:
            return 1
        elif event.inaxes == self.axes['profile']:
            return 2
        return None

    def mouse_move_callback(self, event):
        """Store the locations of mouse as it moves across the canvas
        """
        if event.inaxes is None:
            return
        axisID = self.get_axisID(event)
        if event.inaxes == self.axes['main']:
            self.mmx, self.mmy = event.xdata, event.ydata

    def button_press_callback(self, event):
        """What to do when the mouse button is pressed

        Args:
            event (Event): Matplotlib event instance containing information about the event
        """
        if event.inaxes is None:
            return
        if self.canvas.toolbar.mode != "":
            return
        if event.button == 1:
            self._addsub = 1
        elif event.button == 3:
            self._addsub = 0
        if event.inaxes == self.axes['main']:
            self._start = [event.x, event.y]
        elif event.inaxes == self.axes['profile']:
            self._start = [event.x, event.y]

    def button_release_callback(self, event):
        """What to do when the mouse button is released

        Args:
            event (Event): Matplotlib event instance containing information about the event
        """
        if event.inaxes is None:
            return
        if event.inaxes == self.axes['info']:
            if (event.xdata > 0.8) and (event.xdata < 0.9):
                answer = "y"
            elif event.xdata >= 0.9:
                answer = "n"
            else:
                return
            self.operations(answer, -1)
            self.update_infobox(default=True)
            return
        elif event.inaxes == self.axes['profile']:
            if (event.x == self._start[0]) and (event.y == self._start[1]):
                self.set_fwhm(event.xdata)
                self.update_infobox(
                    message="FWHM updated for the selected object",
                    yesno=False)
            return
        elif self._respreq[0]:
            # The user is trying to do something before they have responded to a question
            return
        if self.canvas.toolbar.mode != "":
            return
        # Draw an actor
        axisID = self.get_axisID(event)
        if axisID is not None:
            if axisID <= 2:
                self._end = [event.x, event.y]
                if (self._end[0] == self._start[0]) and (self._end[1]
                                                         == self._start[1]):
                    # The mouse button was pressed (not dragged)
                    self.get_ind_under_point(event)
                    self.update_infobox(message="Object selected", yesno=False)
                    pass
                elif self._end != self._start:
                    # The mouse button was dragged
                    if axisID == 0:
                        if self._start > self._end:
                            tmp = self._start
                            self._start = self._end
                            self._end = tmp
                        # Now do something
                        pass
        # Now plot
        self.canvas.restore_region(self.background)
        self.draw_objtraces()
        self.canvas.draw()

    def key_press_callback(self, event):
        """What to do when a key is pressed

        Args:
            event (Event): Matplotlib event instance containing information about the event
        """
        # Check that the event is in an axis...
        if not event.inaxes:
            return
        # ... but not the information box!
        if event.inaxes == self.axes['info']:
            return
        axisID = self.get_axisID(event)
        self.operations(event.key, axisID)

    def operations(self, key, axisID):
        """Canvas operations

        Args:
            key (str): Which key has been pressed
            axisID (int): The index of the axis where the key has been pressed (see get_axisID)
        """
        # Check if the user really wants to quit
        if key == 'q' and self._qconf:
            if self._changes:
                self.update_infobox(
                    message=
                    "WARNING: There are unsaved changes!!\nPress q again to exit",
                    yesno=False)
                self._qconf = True
            else:
                msgs.bug(
                    "Need to change this to kill and return the results to PypeIt"
                )
                plt.close()
        elif self._qconf:
            self.update_infobox(default=True)
            self._qconf = False

        # Manage responses from questions posed to the user.
        if self._respreq[0]:
            if key != "y" and key != "n":
                return
            else:
                # Switch off the required response
                self._respreq[0] = False
                # Deal with the response
                if self._respreq[1] == "delete_object" and key == "y":
                    self.delete_object()
                elif self._respreq[1] == "clear_anchors" and key == "y":
                    self.empty_mantrace()
                    self.replot()
                elif self._respreq[1] == "exit_update" and key == "y":
                    self._use_updates = True
                    self.print_pypeit_info()
                    self.operations("qu", None)
                elif self._respreq[1] == "exit_restore" and key == "y":
                    self._use_updates = False
                    self.operations("qr", None)
                else:
                    return
            # Reset the info box
            self.update_infobox(default=True)
            return

        if key == '?':
            self.print_help()
        elif key == 'a':
            self.add_object()
        elif key == 'c':
            if axisID == 0:
                # If this is pressed on the main window
                self.recenter()
#        elif key == 'c':
#            self._respreq = [True, "clear_anchors"]
#            self.update_infobox(message="Are you sure you want to clear the anchors", yesno=True)
        elif key == 'd':
            if self._obj_idx != -1:
                self._respreq = [True, "delete_object"]
                self.update_infobox(
                    message="Are you sure you want to delete this object trace",
                    yesno=True)
#        elif key == 'm':
#            if self._trcmthd != 'manual':
#                self.update_infobox(message="To add an anchor point, set the 'manual' trace method", yesno=False)
#            else:
#                self.add_anchor()
#        elif key == 'n':
#            self.remove_anchor()
        elif key == 'qu' or key == 'qr':
            if self._changes:
                self.update_infobox(
                    message=
                    "WARNING: There are unsaved changes!!\nPress q again to exit",
                    yesno=False)
                self._qconf = True
            else:
                plt.close()


#        elif key == '+':
#            if self._mantrace["polyorder"] < 10:
#                self._mantrace["polyorder"] += 1
#                self.update_infobox(message="Polynomial order = {0:d}".format(self._mantrace["polyorder"]), yesno=False)
#                self.fit_anchors()
#            else:
#                self.update_infobox(message="Polynomial order must be <= 10", yesno=False)
#        elif key == '-':
#            if self._mantrace["polyorder"] > 1:
#                self._mantrace["polyorder"] -= 1
#                self.update_infobox(message="Polynomial order = {0:d}".format(self._mantrace["polyorder"]), yesno=False)
#                self.fit_anchors()
#            else:
#                self.update_infobox(message="Polynomial order must be >= 1", yesno=False)
        self.replot()

    def add_anchor(self):
        """Add a manual anchor point
        """
        self._mantrace['spat_a'].append(self.mmx)
        self._mantrace['spec_a'].append(self.mmy)
        self.fit_anchors()

    def remove_anchor(self):
        """Remove a manual anchor point
        """
        # Find the anchor closest to the mouse position
        if len(self._mantrace['spat_a']) != 0:
            mindist = (self._mantrace['spat_a'][0] - self.mmx)**2 + (
                self._mantrace['spec_a'][0] - self.mmy)**2
            minidx = 0
            for ianc in range(1, len(self._mantrace['spat_a'])):
                dist = (self._mantrace['spat_a'][ianc] - self.mmx)**2 + (
                    self._mantrace['spec_a'][ianc] - self.mmy)**2
                if dist < mindist:
                    mindist = dist
                    minidx = ianc
            del self._mantrace['spat_a'][minidx]
            del self._mantrace['spec_a'][minidx]
        self.fit_anchors()

    def fit_anchors(self):
        """Fit the manual anchor points
        """
        if len(self._mantrace['spat_a']) <= self._mantrace['polyorder']:
            self.update_infobox(
                message=
                "You need to select more trace points before manually adding\n"
                + "a manual object trace. To do this, use the 'm' key",
                yesno=False)
        else:
            # Fit a polynomial to the anchor points
            coeff = np.polyfit(self._mantrace['spec_a'],
                               self._mantrace['spat_a'],
                               self._mantrace['polyorder'])
            self._mantrace['spat_trc'] = np.polyval(coeff,
                                                    self._mantrace['spec_trc'])
        # Replot, regardless of whether a fit is done (a point might have been added/removed)
        self.replot()

    def get_slit(self):
        """Find the slit that the mouse is currently in
        """
        ypos = int(self.mmy)
        for sl in range(self._trcdict['slit_left'].shape[1]):
            if (self.mmx > self._trcdict['slit_left'][ypos, sl]) and (
                    self.mmx < self._trcdict['slit_righ'][ypos, sl]):
                self._inslit = sl
                return

    def add_object(self):
        if self._trcmthd == 'manual' and len(
                self._mantrace['spat_a']) <= self._mantrace['polyorder']:
            self.update_infobox(
                message=
                "You need to select more trace points before manually adding\n"
                + "a manual object trace. To do this, use the 'm' key",
                yesno=False)
            return
        # Add an object trace
        spec_vec = self._mantrace['spec_trc']
        if self._trcmthd == 'manual':
            trace_model = self._mantrace['spat_trc'].copy()
            # Now empty the manual tracing
            self.empty_mantrace()
        else:
            if self._trcmthd == 'slit':
                self.get_slit()
                trace_model = self._trcdict["trace_model"][
                    self._trcmthd]["trace_model"][:, self._inslit].copy()
            else:
                trace_model = self._trcdict["trace_model"][
                    self._trcmthd]["trace_model"].copy()
            spat_0 = np.interp(self.mmy, spec_vec, trace_model)
            shift = self.mmx - spat_0
            trace_model += shift
        # Determine the FWHM
        if self._object_traces.nobj != 0:
            fwhm = self._object_traces._fwhm[0]
        else:  # Otherwise just use the fwhm parameter input to the code (or the default value)
            fwhm = 2

        # Finally, add this object to the list
        self._object_traces.add_object(self._det, self.mmx,
                                       self.mmy, trace_model,
                                       self._spectrace.copy(), fwhm)

    def add_object_sobj(self):
        """Add an object to specobjs
        """
        if self._trcmthd == 'manual' and len(
                self._mantrace['spat_a']) <= self._mantrace['polyorder']:
            self.update_infobox(
                message=
                "You need to select more trace points before manually adding\n"
                + "a manual object trace. To do this, use the 'm' key",
                yesno=False)
            return
        # Add an object trace
        spec_vec = self._mantrace['spec_trc']
        if self._trcmthd == 'manual':
            trace_model = self._mantrace['spat_trc'].copy()
            # Now empty the manual tracing
            self.empty_mantrace()
        else:
            trace_model = self._trcdict["trace_model"][
                self._trcmthd]["trace_model"].copy()
            spat_0 = np.interp(self.mmy, spec_vec, trace_model)
            shift = self.mmx - spat_0
            trace_model += shift
        xsize = self._trcdict["slit_righ"] - self._trcdict["slit_left"]
        nsamp = np.ceil(xsize.max())
        # Extract the SpecObj parameters
        par = self._trcdict['sobj_par']
        # Create a SpecObj
        thisobj = specobjs.SpecObj(par['frameshape'],
                                   par['slit_spat_pos'],
                                   par['slit_spec_pos'],
                                   det=par['det'],
                                   setup=par['setup'],
                                   slitid=par['slitid'],
                                   orderindx=par['orderindx'],
                                   objtype=par['objtype'])
        thisobj.hand_extract_spat = self.mmx
        thisobj.hand_extract_spec = self.mmy
        thisobj.hand_extract_det = par['det']
        thisobj.hand_extract_fwhm = None
        thisobj.hand_extract_flag = True
        f_ximg = RectBivariateSpline(spec_vec, np.arange(self.nspat),
                                     par["ximg"])
        thisobj.spat_fracpos = f_ximg(thisobj.hand_extract_spec,
                                      thisobj.hand_extract_spat,
                                      grid=False)  # interpolate from ximg
        thisobj.smash_peakflux = np.interp(
            thisobj.spat_fracpos * nsamp, np.arange(nsamp),
            self._trcdict['profile'])  # interpolate from fluxconv
        # assign the trace
        thisobj.trace_spat = trace_model
        thisobj.trace_spec = spec_vec
        thisobj.spat_pixpos = thisobj.trace_spat[self.nspec // 2]
        thisobj.set_idx()
        if self._object_traces.nobj != 0:
            thisobj.fwhm = self._object_traces._fwhm[0]
        else:  # Otherwise just use the fwhm parameter input to the code (or the default value)
            thisobj.fwhm = 2
        # Finally, add new object
        self.specobjs.add_sobj(thisobj)

    def delete_object(self):
        """Delete an object trace
        """
        self._object_traces.delete_object(self._obj_idx)
        self._obj_idx = -1
        self.replot()

    def delete_object_sobj(self):
        """Delete a specobj
        """
        self.specobjs.remove_sobj(self._obj_idx)
        self._obj_idx = -1

    def print_pypeit_info(self):
        """print text that the user should insert into their .pypeit file
        """
        if 1 in self._object_traces._add_rm:
            msgs.info(
                "Include the following info in the manual_extract column in your .pypeit file:\n"
            )
            print(self._object_traces.get_pypeit_string())

    def recenter(self):
        xlim = self.axes['main'].get_xlim()
        ylim = self.axes['main'].get_ylim()
        xmin = self.mmx - 0.5 * (xlim[1] - xlim[0])
        xmax = self.mmx + 0.5 * (xlim[1] - xlim[0])
        ymin = self.mmy - 0.5 * (ylim[1] - ylim[0])
        ymax = self.mmy + 0.5 * (ylim[1] - ylim[0])
        self.axes['main'].set_xlim([xmin, xmax])
        self.axes['main'].set_ylim([ymin, ymax])

    def make_objprofile(self):
        """Generate an object profile from the traces
        """
        coords = self._spatpos - self._object_traces._trace_spat[
            self._obj_idx][:, np.newaxis]
        ww = np.where(
            np.abs(coords) < 4 * self._object_traces._fwhm[self._obj_idx])
        bincent = self.profile['profile'].get_xdata()
        offs = 0.5 * (bincent[1] - bincent[0])
        edges = np.append(bincent[0] - offs, bincent + offs)
        prof, _ = np.histogram(coords[ww], bins=edges, weights=self.frame[ww])
        return prof / ww[0].size

    def set_fwhm(self, xdata):
        """Set the FWHM using the available panel

        Args:
            xdata (float): The x coordinate selected by the user
        """
        self._object_traces._fwhm[self._obj_idx] = 2.0 * np.abs(xdata)
        self.draw_profile()
        self.replot()
        return

    def get_specobjs(self):
        """Get the updated version of SpecObjs

        Returns:
            SpecObjs: SpecObjs Class
        """
        if self._use_updates:
            msgs.work("Have not updated SpecObjs yet")
            return self.specobjs
        else:
            return None

    def update_infobox(self,
                       message="Press '?' to list the available options",
                       yesno=True,
                       default=False):
        """Send a new message to the information window at the top of the canvas

        Args:
            message (str): Message to be displayed
        """
        self.axes['info'].clear()
        if default:
            self.axes['info'].text(0.5,
                                   0.5,
                                   "Press '?' to list the available options",
                                   transform=self.axes['info'].transAxes,
                                   horizontalalignment='center',
                                   verticalalignment='center')
            self.canvas.draw()
            return
        # Display the message
        self.axes['info'].text(0.5,
                               0.5,
                               message,
                               transform=self.axes['info'].transAxes,
                               horizontalalignment='center',
                               verticalalignment='center')
        if yesno:
            self.axes['info'].fill_between(
                [0.8, 0.9],
                0,
                1,
                facecolor='green',
                alpha=0.5,
                transform=self.axes['info'].transAxes)
            self.axes['info'].fill_between(
                [0.9, 1.0],
                0,
                1,
                facecolor='red',
                alpha=0.5,
                transform=self.axes['info'].transAxes)
            self.axes['info'].text(0.85,
                                   0.5,
                                   "YES",
                                   transform=self.axes['info'].transAxes,
                                   horizontalalignment='center',
                                   verticalalignment='center')
            self.axes['info'].text(0.95,
                                   0.5,
                                   "NO",
                                   transform=self.axes['info'].transAxes,
                                   horizontalalignment='center',
                                   verticalalignment='center')
        self.axes['info'].set_xlim((0, 1))
        self.axes['info'].set_ylim((0, 1))
        self.canvas.draw()

    def empty_mantrace(self):
        """Generate an empty dictionary for the manual tracing
        """
        self._mantrace = dict(spat_a=[],
                              spec_a=[],
                              spat_trc=None,
                              spec_trc=np.arange(self.nspec),
                              polyorder=0)
        return
Example #58
0
        "Leapfrog": Leapfrog
    }
    if plot_animation is None:
        plot_animation = animation.FuncAnimation(fig,
                                                 animate,
                                                 init_func=init,
                                                 interval=animation_interval,
                                                 blit=False)

    method_scheme = d[label](init_temp, s, r)
    plt.draw()


rax = plt.axes([0.05, 0.7, 0.15, 0.15])
radio = RadioButtons(rax,
                     ("Explicit Downstream", "Explicit Upstream",
                      "Implicit Downstream", "Implicit Upstream", "Leapfrog"))


def make_temp_sliders(index, ax, label, valmin, valmax):
    def slider_on_change(val):
        init_temp[index] = val

    t_slider = Slider(ax, label, valmin, valmax, valinit=init_temp[index])
    t_slider.on_changed(slider_on_change)
    return t_slider


left_t_slider = make_temp_sliders(0, plt.axes([0.05, 0.5, 0.15, 0.03]),
                                  "Left temp", -2, 2)
right_t_slider = make_temp_sliders(-1, plt.axes([0.05, 0.6, 0.15, 0.03]),
Example #59
0
# In[62]:

fig = plt.figure(figsize=(20, 10))
main = plt.axes([0.1, 0.1, 0.8, 0.8])
ax1 = plt.axes([0.125, 0.05, 0.75, 0.03])
ax2 = plt.axes([0, 0.125, 0.08, 0.75])
slider1 = MyRadioButtons(ax1, [
    'pop', 'old_proportion', 'poverty_rate', 'white', 'black', 'hispanic',
    'asian', 'house_owner_rate', 'internet', 'gsp', 'household_with_baby',
    'unemployment', 'tax', 'democratic_party'
],
                         orientation="horizontal")
slider2 = RadioButtons(ax2, [
    'pop', 'old_proportion', 'poverty_rate', 'white', 'black', 'hispanic',
    'asian', 'house_owner_rate', 'internet', 'gsp', 'household_with_baby',
    'unemployment', 'tax', 'democratic_party'
])
dot, = main.plot(state[slider1.value_selected], state[slider2.value_selected],
                 'o')


def updata1(label):
    dot.set_data(state[label], state[slider2.value_selected])
    lab = np.max(state[label]) - np.min(state[label])
    main.set_xlim(
        np.min(state[label]) - 0.1 * lab,
        np.max(state[label]) + 0.1 * lab)
    fig.canvas.draw_idle()

Example #60
0
    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')


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


button.on_clicked(reset)

rax = plt.axes([0.025, 0.5, 0.15, 0.15], facecolor=axcolor)
radio = RadioButtons(rax, ('red', 'blue', 'green'), active=0)


def colorfunc(label):
    l.set_color(label)
    fig.canvas.draw_idle()


radio.on_clicked(colorfunc)

plt.show()