Beispiel #1
0
    def __create_fit_button(self) -> None:
        """Create a button widget to calls the 'model.fit' function."""

        # geometry
        width = 0.08  # of figure
        height = 0.05  # of figure
        x0 = self.bbox[0] + self.bbox[2] - width - 0.03
        y0 = self.bbox[1] - height  # under the bbox
        self.__fit_button_ax = self.figure.add_axes([x0, y0, width, height])
        self.__fit_button = widgets.Button(self.__fit_button_ax,
                                           label='Fit',
                                           color='steelblue',
                                           hovercolor='lightgray')

        self.__fit_button.on_clicked(self.__fit_button_on_clicked)
Beispiel #2
0
 def add_button_action(self, text, action_func):
     if not callable(action_func):
         raise ValueError("Invalid button action. Button '%s''s"
                          " action function is not a callable" % text)
     if text in self._buttonmap:
         raise ValueError("Button '%s' is already a button" % text)
     ax = self.fig.add_axes([
         len(self._buttonmap) * self._buttonwidth,
         0.99 - self._buttonheight, self._buttonwidth, self._buttonheight
     ])
     button = widgets.Button(ax, text)
     # Swallow the event parameter. We don't need it for these buttons
     func = lambda event: action_func()
     cid = button.on_clicked(func)
     self._buttonmap[text] = (cid, func, button)
Beispiel #3
0
    def add_reset_seed_button(self):
        """
        Add a button to the figure for reseting the random number generator to
        its intial state. For reproducible noise...
        """
        bax = self.ipp_fig.add_axes([0.825, 0.05, 0.125, 0.04])
        self.reset_seed_button = widgets.Button(bax,
                                                'Reset random stream',
                                                color=BUTTONCOLOUR,
                                                hovercolor=HOVERCOLOUR)

        def reset_seed(event):
            self.integrator.noise.trait["random_stream"].reset()

        self.reset_seed_button.on_clicked(reset_seed)
Beispiel #4
0
def create_generic_button(start_left: float, start_top: float, text: str, callback) -> widg.Button:
    """Creates a generic matplotlib Button using a width of 0.1 and height of 0.075.

    start_left: where on the figure you want to start the button at.
    start_top: where on the figure you want to start the button at.

    text: The text to display on the button.

    callback: a method with one argument that is executed when the button is clicked."""

    but_ax = plt.axes(arg=[start_left, start_top, 0.1, 0.075])
    button = widg.Button(but_ax, text)
    button.on_clicked(callback)

    return button
Beispiel #5
0
def taskA_plot_bifdiag2():
    fig = plt.figure(1, figsize=(6, 5))
    left, bottom = 0.1, 0.1
    width, height = 0.8, 0.8
    pl_axes = plt.axes([left, bottom, width, height])

    def do_plot(lmin=0.60115, lmax=2.20115, ymin=-1, ymax=1):
        times = 1000
        delta = 200
        x0 = 0.1
        ld = (lmax - lmin) / 1000
        x, y = allLambda(lmin, lmax, ld, stf.logistic_map, times, delta, x0)
        pl_axes.clear()
        pl_axes.set_ylim((ymin, ymax))
        pl_axes.plot(x, y, 'g.', alpha=0.1, markersize=2)

        print(lmin, lmax, ymin, ymax)
        return lmin, lmax, ymin, ymax

    def rescale(lmin, lmax, ymin, ymax, lcr):
        alpha = 2.5029
        delta = 4.6692
        nu = lmax - lcr
        mu = lcr - lmin
        nu = nu / delta
        mu = mu / delta
        newlmax = lcr + nu
        newlmin = lcr - mu
        ymin, ymax = ymax / alpha, ymin / alpha  # mirrored image
        return newlmin, newlmax, ymin, ymax

    lmin, lmax, ymin, ymax = do_plot()
    lcr = 1.40115
    plt.grid()

    b_axes = plt.axes([0.8, .025, 0.1, 0.04])
    scale_button = wgt.Button(b_axes, "Scale")

    def scale(event):

        nonlocal lmin, lmax, ymin, ymax, lcr
        newlmin, newlmax, ymin, ymax = rescale(lmin, lmax, ymin, ymax, lcr)
        lmin, lmax, ymin, ymax = do_plot(newlmin, newlmax, ymin, ymax)
        plt.draw()

    scale_button.on_clicked(scale)
    plt._auto_draw_if_interactive(fig, pl_axes)
    plt.show()
Beispiel #6
0
    def add_reset_axes_button(self):
        """
        Add a button to the figure for reseting the phase-plane axes to their
        default ranges.
        """
        bax = self.ipp_fig.add_axes([0.04, 0.87, 0.125, 0.04])
        self.reset_axes_button = widgets.Button(bax, 'Reset axes',
                                        color=BUTTONCOLOUR,
                                        hovercolor=HOVERCOLOUR)
        def reset_ranges(event):
            self.axes_range_sliders["sl_x_min"].reset()
            self.axes_range_sliders["sl_x_max"].reset()
            self.axes_range_sliders["sl_y_min"].reset()
            self.axes_range_sliders["sl_y_max"].reset()

        self.reset_axes_button.on_clicked(reset_ranges)
    def add_reset_param_button(self):
        """
        Add a button to the figure for reseting the model parameter values to
        their original values.
        """
        bax = self.ipp_fig.add_axes([0.825, 0.865, 0.125, 0.04])
        self.reset_param_button = widgets.Button(bax,
                                                 'Reset parameters',
                                                 color=BUTTONCOLOUR,
                                                 hovercolor=HOVERCOLOUR)

        def reset_parameters(event):
            for param_slider in self.param_sliders:
                self.param_sliders[param_slider].reset()

        self.reset_param_button.on_clicked(reset_parameters)
    def add_reset_sv_button(self):
        """
        Add a button to the figure for reseting the model state variables to
        their default values.
        """
        bax = self.ipp_fig.add_axes([0.04, 0.60, 0.125, 0.04])
        self.reset_sv_button = widgets.Button(bax,
                                              'Reset state-variables',
                                              color=BUTTONCOLOUR,
                                              hovercolor=HOVERCOLOUR)

        def reset_state_variables(event):
            for svsl in self.sv_sliders.itervalues():
                svsl.reset()

        self.reset_sv_button.on_clicked(reset_state_variables)
Beispiel #9
0
    def _add_widgets(self):
        self.buttons = []
        for i in range(0,self.num_buttons):
            x = i*2
            #The i+1/10. is a bug that if you make two axes directly ontop of
            #one another then the divider doesn't work.
            self.buttons.append(self.fig.add_axes((0.,0.,0.+i/10.,1.)))
            locator = self.divider.new_locator(nx=x, ny=self.button_ny)
            self.buttons[-1].set_axes_locator(locator)
            self.buttons[-1]._button = widgets.Button(self.buttons[-1],
                                                         self.button_labels[i])
            self.buttons[-1]._button.on_clicked(self.button_func[i])

        self.sliders = []
        self.slider_buttons = []
        for i in range(self.num_sliders):
            x = i * 2
            self.sliders.append(self.fig.add_axes((0.,0.,0.01+i/10.,1.)))
            if self.num_buttons == 0:
                nx1 = 1
            else:
                nx1 = -3
            locator = self.divider.new_locator(nx=0, ny=x, nx1=nx1)
            self.sliders[-1].set_axes_locator(locator)
            sframe = SliderPB(self.sliders[-1], "%i"%i,
                                    self.slider_ranges[i][0],
                                    self.slider_ranges[i][1]-1,
                                    valinit=self.slider_ranges[i][0],
                                    valfmt = '%i')
            sframe.on_changed(self._slider_changed, sframe)
            sframe.slider_ind = i
            sframe.cval = sframe.val
            self.sliders[-1]._slider = sframe

            self.slider_buttons.append(self.fig.add_axes((0., 0., 0.05+x/10., 1.)))
            if self.num_buttons == 0:
                nx = 2
            else:
                nx = 2 + 2*(self.num_buttons-1)
            locator = self.divider.new_locator(nx=nx, ny=x)

            self.slider_buttons[-1].set_axes_locator(locator)
            butt = ButtonPB(self.slider_buttons[-1],">")
            butt.on_clicked(self._click_slider_button, butt, sframe)
            butt.clicked = False
            self.slider_buttons[-1]._button = butt
Beispiel #10
0
    def dot_marker(self, event):
        fig = plt.figure(facecolor='#ffff99', edgecolor='#666600')
        ax = fig.add_subplot(111, aspect="equal", facecolor='#ffff99')
        ax.set_title('Позначте точки ')
        ax.add_patch(
            patches.Rectangle((self.a, 0), self.b - self.a, self.T, fc='b'))
        dot, = ax.plot([self.a + self.b / 2], [self.T / 2], 'b.')
        dotbuilder = self.DotBuilder(dot, self.a, self.b, self.T)

        def confirm(event):
            self.marked_dots_ab = dotbuilder._dots_ab.copy()
            self.marked_dots_T = dotbuilder._dots_T.copy()
            plt.close(fig)

        conf_buuton = widg.Button(plt.axes([0.8, 0.05, 0.1, 0.05]), "ОК")
        conf_buuton.on_clicked(confirm)
        plt.show()
Beispiel #11
0
def data_plot_window(x_axis_data, y_axis_data, display_start, display_end):

    plt.clf()

    plt.plot(x_axis_data[display_start:display_end],
             y_axis_data[display_start:display_end])
    plt.xlim([
        centre - span * (0.5 - (float(display_start) / 200)),
        centre + span * ((float(display_end) / 200) - 0.5)
    ])
    #plt.ylim([0.4, 1])

    bexit = widget.Button(plt.axes([0.88, 0.91, 0.09, 0.07]),
                          'Quit',
                          image=None,
                          color=u'0.8',
                          hovercolor=u'1')
    bexit.on_clicked(exit_button)
    plt.show()
def createControlWidgets(fig):
    plt.subplots_adjust(bottom=0.2)
    smallIteController = EventController(fig)
    ringIteController = EventController(fig)
    bigIteController = EventController(fig)

    def __onSmallIteUpdate(fig, index):
        if index < 0 or index >= len(records[bigIteController.curIndex][
                ringIteController.curIndex]):
            return False
        refreshAxes(records[bigIteController.curIndex][
            ringIteController.curIndex][index])
        print(records[bigIteController.curIndex][ringIteController.curIndex]
              [index])
        return True

    def __onRingIteUpdate(fig, index):
        if index < 0 or index >= len(records[bigIteController.curIndex]):
            return False
        refreshAxes(records[bigIteController.curIndex][index][
            smallIteController.curIndex])
        print(records[bigIteController.curIndex][index][
            smallIteController.curIndex])
        return True

    def __onBigIteUpdate(fig, index):
        if index < 0 or index >= len(records):
            return False
        refreshAxes(records[index][ringIteController.curIndex][
            smallIteController.curIndex])
        return True

    smallIteController.setFunc(__onSmallIteUpdate)
    ringIteController.setFunc(__onRingIteUpdate)
    bigIteController.setFunc(__onBigIteUpdate)

    bprev = pltW.Button(plt.axes([0.75, 0.05, 0.1, 0.075]), 'Prev')
    bprev.on_clicked(smallIteController.prev)
    bnext = pltW.Button(plt.axes([0.85, 0.05, 0.1, 0.075]), 'Next')
    bnext.on_clicked(smallIteController.next)

    bPrevRing = pltW.Button(plt.axes([0.45, 0.05, 0.1, 0.075]), 'Prev ring')
    bPrevRing.on_clicked(ringIteController.prev)
    bNextRing = pltW.Button(plt.axes([0.55, 0.05, 0.1, 0.075]), 'Next ring')
    bNextRing.on_clicked(ringIteController.next)

    bPrevIte = pltW.Button(plt.axes([0.15, 0.05, 0.1, 0.075]), 'Prev ite')
    bPrevIte.on_clicked(bigIteController.prev)
    bNextIte = pltW.Button(plt.axes([0.25, 0.05, 0.1, 0.075]), 'Next ite')
    bNextIte.on_clicked(bigIteController.next)
Beispiel #13
0
def interactiveSaveButton(filename, **kwargs):
    """Adds an interactive save button to a given figure.
    
    Parameters
    ----------
    filename : str
        A model filename, which must include full path.
    
    Other parameters
    ----------------
    overwrite=False : bool
        Says whether to overwrite files or not.
    sufix='' : str
        A sufix to be always added to the given filename.
    newformat='{}_v{}' : str
        A formatter that allows to make new filenames in order to avoid 
        overwriting. If 'F:\Hola.png' does already exist, new file is saved as 
        'F:\Hola_v2.png'.
    
    Returns
    -------
    save_button : wid.Button
        Interactive save button instance.
    """

    # Since I can, I would also like an interactive 'Save' button
    ax_save = plt.axes([0.8, 0.01, 0.1, 0.04])
    save_button = wid.Button(ax_save, 'Guardar')

    # For that, I'll need another callback function
    def check_save_callback(event):
        Tk().withdraw()
        #   tk.newfilename = askopenfilename()
        ax_save.set_visible(False)
        ivs.saveFig(filename, **kwargs)
        ax_save.set_visible(True)
        messagebox.showinfo('¡Listo!', 'Imagen guardada')

    save_button.on_clicked(check_save_callback)
    plt.show()

    return save_button
Beispiel #14
0
def random_sequences():

    create_window()

    callback = Index()

    global list_sequences
    list_sequences = []
    global ax
    global fig
    fig = plt.figure(figsize=(7, 5), dpi=100)
    ax = fig.add_subplot(121)
    fig.canvas.mpl_connect('button_press_event', callback.plot)

    ax_button_quit = plt.axes([0.89, 0.02, 0.1, 0.075])
    button_quit = mpw.Button(ax_button_quit, 'Save and quit')
    button_quit.label.set_fontsize(6.5)
    button_quit.on_clicked(callback.quit)

    plt.show()

    return list_sequences
Beispiel #15
0
    def __init__(self,
                 num_axes,
                 start,
                 width,
                 figsize=[10, 6],
                 button_show=True):
        self.change = True
        self.num_axes = num_axes
        self.fig, self.ax = plt.subplots(num_axes, figsize=figsize)
        self.fig.subplots_adjust(left=0.04, right=0.98, top=0.95, bottom=0.04)
        if button_show:
            self.forward = plt.axes([0.85, 0.01, 0.07, 0.05])
            self.backward = plt.axes([0.7, 0.01, 0.07, 0.05])
            self.wider = plt.axes([0.30, 0.01, 0.07, 0.05])
            self.tighter = plt.axes([0.15, 0.01, 0.07, 0.05])
            self.aut = plt.axes([0.47, 0.01, 0.07, 0.05])
            self.close = plt.axes([0.05, 0.01, 0.04, 0.05])

            self.but_forward = wd.Button(self.forward, "Вперед")
            self.but_backward = wd.Button(self.backward, 'Назад')
            self.but_wider = wd.Button(self.wider, 'Шире')
            self.but_tighter = wd.Button(self.tighter, 'Уже')
            self.but_auto = wd.Button(self.aut, 'Auto')
            self.but_close = wd.Button(self.close, 'Close')

            self.ma = ManageActs(self.ax, self)
            self.but_forward.on_clicked(self.ma.forward)
            self.but_backward.on_clicked(self.ma.backward)
            self.but_wider.on_clicked(self.ma.wider)
            self.but_tighter.on_clicked(self.ma.tighter)
            self.but_auto.on_clicked(self.ma.change_auto)
            self.but_close.on_clicked(self.ma.close)

        self.plot_array = []
        self.scatter_array = []
        self.text_array = []

        self.start = start  #datetime.datetime.strptime(start,'%Y-%m-%d %H:%M')
        self.width = width
        self.auto = False
        self.font = font
Beispiel #16
0
    def __init__(self,
                 input_unlabeled_elm_event_file=None,
                 output_labeled_elm_event_filename=None,
                 save_pdf=True,
                 manual_elm_list=None):
        self.manual_elm_list = manual_elm_list
        self.time_markers = [None, None, None, None]
        self.marker_label = [
            'Pre-ELM start', 'ELM start', 'ELM end', 'Post-ELM end'
        ]
        self.fig, self.axes = plt.subplots(nrows=3, figsize=[15, 8])
        # self.fig_num = self.fig.number
        self.fig.canvas.mpl_connect('close_event', self.on_close)
        for axes in self.axes:
            axes.set_xlabel('Time (ms)')
        self.axes[0].set_ylabel('Line avg dens (AU)')
        self.axes[1].set_ylabel('D alpha')
        self.axes[2].set_ylabel('BES')
        plt.suptitle('empty')
        plt.tight_layout(rect=(0, 0.08, 1, 1))

        self.fig.canvas.mpl_connect('button_press_event', self.axis_click)

        self.save_pdf = save_pdf

        self.skip_button = widgets.Button(plt.axes([0.01, 0.02, 0.07, 0.04]),
                                          'Skip ELM',
                                          color='lightsalmon',
                                          hovercolor='red')
        self.skip_button.on_clicked(self.skip)

        self.clear_button = widgets.Button(plt.axes([0.2, 0.02, 0.2, 0.04]),
                                           'Clear markers',
                                           color='lightgray',
                                           hovercolor='darkgray')
        self.clear_button.on_clicked(self.clear_markers)

        self.status_box = widgets.TextBox(plt.axes([0.5, 0.02, 0.2, 0.04]),
                                          'Status:',
                                          color='w',
                                          hovercolor='w')

        self.accept_button = widgets.Button(plt.axes([0.75, 0.02, 0.2, 0.04]),
                                            'Accept markers',
                                            color='whitesmoke',
                                            hovercolor='whitesmoke')
        self.accept_button.on_clicked(self.accept)

        self.multi = widgets.MultiCursor(self.fig.canvas,
                                         self.axes,
                                         color='r',
                                         lw=1)

        assert Path(input_unlabeled_elm_event_file).exists()
        self.unlabeled_elm_events_h5 = h5py.File(
            input_unlabeled_elm_event_file, 'r')
        self.n_elms = len(self.unlabeled_elm_events_h5)
        print(
            f'Unlabeled ELM event data file: {input_unlabeled_elm_event_file}')
        print(f'  Number of ELM events: {self.n_elms}')
        # shots = np.unique([elm_event.attrs['shot'] for elm_event in self.unlabeled_elm_events_h5.values()])
        # print(f'  Number of unique shots: {shots.size}')

        output_file = Path().resolve() / output_labeled_elm_event_filename
        print(f'Output labeled ELM event file: {output_file}')
        print(f'  File exists: {output_file.exists()}')
        self.labeled_elm_events_h5 = h5py.File(output_file.as_posix(), 'a')

        self.figures_dir = Path().resolve() / 'figures'
        self.figures_dir.mkdir(exist_ok=True)

        self.labeled_elms = self.labeled_elm_events_h5.attrs.setdefault(
            'labeled_elms', np.array([], dtype=int))
        self.skipped_elms = self.labeled_elm_events_h5.attrs.setdefault(
            'skipped_elms', np.array([], dtype=int))

        self.validate_data_file()

        self.rng = np.random.default_rng()
        self.elm_index = None
        self.shot = None
        self.start_time = None
        self.stop_time = None
        self.time = None
        self.signals = None
        self.connection = MDSplus.Connection('atlas.gat.com')

        self.vlines = []
        self.data_lines = []
        self.clear_and_get_new_elm()
        plt.show()
Beispiel #17
0
def free_run_plot_window(compensated):

    global CB_state
    CB_state = False
    global get_axis_state
    get_axis_state = True

    #adjust the plotted data to compensate for modulator RF and InGaAs detector response
    if compensated == 'Y':
        amplitude_offset = np.loadtxt(
            "C:\\Users\\Milos\Desktop\\Er_Experiment_Interface_Code\\amplitude_offset.csv",
            delimiter=",")

    while True:

        #freq = Burleigh_WM.query_ascii_values("FETC:SCAL:FREQ?")
        #frequency = freq[0]

        y_axis_data = HP_SpecAn.query_binary_values("OUTPDTRC?",
                                                    datatype=u'd',
                                                    is_big_endian=True)
        ##         print(len(y_axis_data))
        x_axis_data = HP_SpecAn.query_binary_values("OUTPSWPRM?",
                                                    datatype=u'd',
                                                    is_big_endian=True)
        ##         y_axis_data = y_axis_data[0::2]

        ##         print(len(x_axis_data))

        if compensated == 'Y':
            compensated_data = np.divide(y_axis_data, amplitude_offset)
            #we clear the figure before we plot, so that we dont replot over the
            #old data
            plt.clf()
            plt.plot(x_axis_data, compensated_data)
        else:
            #we clear the figure before we plot, so that we dont replot over the
            #old data
            plt.clf()
            plt.plot(x_axis_data, y_axis_data)

        #plt.title(str(frequency) + ' THz', fontsize = 100)

        if (CB_state == True):

            if (get_axis_state == True):
                axis_matrix = plt.axis()
                get_axis_state = False
            if (axis_matrix[3] < 0):
                plt.axis([
                    centre - span / 2, centre + span / 2,
                    axis_matrix[2] * 1.05, axis_matrix[3] * 0.9
                ])
            else:
                plt.axis([
                    centre - span / 2, centre + span / 2,
                    axis_matrix[2] * 0.95, axis_matrix[3] * 1.02
                ])

        #round the wavelength number and plot it as a button

        #bwavelength = Button(axes([0.3, 0.91, 0.25, 0.09]), str(frequency) + ' THz'

        #this generates an exit button to quit the scan and return the instrument
        #handle to prevent the spectrum analyser and OSA from freezing
        bexit = widget.Button(plt.axes([0.9, 0.91, 0.09, 0.07]),
                              'Quit',
                              image=None,
                              color=u'0.8',
                              hovercolor=u'1')
        bexit.on_clicked(exit_button)

        #this check box fixes the Y scale so that it doesnt fluctuate (makes looking at the data
        #a bit disorienting otherwise
        CB_fix_axis = CheckButtons(plt.axes([0.9, 0.8, 0.09, 0.07]),
                                   ('fix Axis', ), (CB_state, ))
        CB_fix_axis.on_clicked(fix_axis)

        #this pause statement is necessary as otherwise the plotting window
        #freezes. this seems to be a bug with the current version of python/matplotlib
        plt.pause(0.01)
Beispiel #18
0
    def print_clip(val):
        data = anim.data[anim.clip_idx *
                         anim.clip_len:anim.clip_idx * anim.clip_len +
                         anim.clip_len]
        print(data)
        np.savetxt("out.txt", data)

    fig = plt.figure("Controls", figsize=(
        3,
        3,
    ))
    textbox = widgets.TextBox(plt.axes([0.4, 0.8, 0.4, 0.1]), "Clip:", '0')
    lentextbox = widgets.TextBox(plt.axes([0.4, 0.7, 0.4, 0.1]),
                                 "Clip Length:", '240')

    prevbutton = widgets.Button(plt.axes([0.25, 0.4, 0.1, 0.1]), "$\u29CF$")
    pausebutton = widgets.Button(plt.axes([0.25 + 0.2, 0.4, 0.1, 0.1]),
                                 "$\u25A0$")
    nextbutton = widgets.Button(plt.axes([0.25 + 0.4, 0.4, 0.1, 0.1]),
                                "$\u29D0$")
    widgets.TextBox(plt.axes([0.1, 0.2, 0.8, 0.1]), "",
                    "Total number of clips: %d " % (len(data) / 240))
    frameslider = widgets.Slider(plt.axes([0.2, 0.55, 0.6, 0.06]), "", 0, 1, 0)
    printbutton = widgets.Button(plt.axes([0.25, 0.08, 0.2, 0.1]), "Print")

    # Drawing
    anim = Animation(data, frameslider)
    anim.select_clip(0)

    prevbutton.on_clicked(prev)
    pausebutton.on_clicked(pause)
Bslider = widgets.Slider(Baxe, 'B', -1.0, 1.0, valinit=Bi, valstep=0.05)


def update(val):
    A = Aslider.val
    B = Bslider.val
    C = 7
    w = 8
    l.set_ydata(A * np.exp(B * t) * np.sin(w * t + C))
    fig.canvas.draw_idle()


#relacionados el evento de cambio con la funcion
Aslider.on_changed(update)
Bslider.on_changed(update)

#añadimos un boton de reinicio
resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
button = widgets.Button(resetax, 'Reset', color=axescolor, hovercolor='0.975')


def reset(event):
    Aslider.reset()
    Bslider.reset()


#relacionamos el evento
button.on_clicked(reset)

plt.show()
    def __init__(self, hill):

        self.hill = hill

        # setup the figure
        plt.rcParams[
            'toolbar'] = 'None'  # turn off the matplotlib toolbar in the figure
        plt.rcParams['figure.figsize'] = 5, 7  # size of the figure in inches

        self.fig, self.ax = plt.subplots(
        )  # gives us a figure object and axes object to manipulate and plot things into
        self.fig.subplots_adjust(
            left=0.2, bottom=0.4, top=0.95,
            right=0.9)  # where do we want the limits of the axes object

        self.fig.canvas.set_window_title(
            'Hillslope model')  # title of the figure window

        self.ax.set_xlabel("x-distance")  # the axis xlabel
        self.ax.set_ylabel("elevation")  # the axis ylabel
        self.ax.set_ylim(0, 200)  # the axis y limits
        self.ax.set_xlim(hill.x.min(), hill.x.max())

        self.thesky, = self.ax.fill(np.array(
            [-1, -1, hill.x.max(), hill.x.max()]),
                                    np.array([-1, 250, 250, -1]),
                                    facecolor='aliceblue',
                                    edgecolor='none')
        x_fill, z_fill = xz_to_fill(hill.x, hill.z)
        self.thehill, = self.ax.fill(x_fill,
                                     z_fill,
                                     facecolor='forestgreen',
                                     edgecolor='k')

        self.thetext = self.ax.text(0.05,
                                    0.05,
                                    '$dz/dt_{x=0}$' +
                                    '= {:.2f}'.format(hill.dzdt),
                                    transform=self.ax.transAxes)

        # add sliders
        widget_color = 'lightgoldenrodyellow'

        self.slide_D_ax = plt.axes([0.2, 0.25, 0.4, 0.05],
                                   facecolor=widget_color)
        self.slide_D = widget.Slider(self.slide_D_ax,
                                     'diffusivity',
                                     hill.D_min,
                                     hill.D_max,
                                     valinit=hill.D,
                                     valstep=1,
                                     valfmt='%g',
                                     transform=self.ax.transAxes)

        self.slide_U_ax = plt.axes([0.2, 0.15, 0.4, 0.05],
                                   facecolor=widget_color)
        self.slide_U = widget.Slider(self.slide_U_ax,
                                     'uplift at\n crest',
                                     hill.U_min,
                                     hill.U_max,
                                     valinit=hill.U,
                                     valstep=0.05,
                                     valfmt='%g',
                                     transform=self.ax.transAxes)

        self.slide_C_ax = plt.axes([0.2, 0.05, 0.4, 0.05],
                                   facecolor=widget_color)
        self.slide_C = widget.Slider(self.slide_C_ax,
                                     'downcut at\n valley',
                                     hill.C_min,
                                     hill.C_max,
                                     valinit=hill.U,
                                     valstep=0.05,
                                     valfmt='%g',
                                     transform=self.ax.transAxes)

        self.btn_hill_reset_ax = plt.axes([0.7, 0.2, 0.25, 0.04])
        self.btn_hill_reset = widget.Button(self.btn_hill_reset_ax,
                                            'Reset hillslope',
                                            color=widget_color,
                                            hovercolor='0.975')

        self.btn_slide_reset_ax = plt.axes([0.7, 0.1, 0.25, 0.04])
        self.btn_slide_reset = widget.Button(self.btn_slide_reset_ax,
                                             'Reset sliders',
                                             color=widget_color,
                                             hovercolor='0.975')

        self.btn_hill_reset.on_clicked(self.reset_hillslope)
        self.btn_slide_reset.on_clicked(self.reset_sliders)
Beispiel #21
0
 def __init__(self, axes, label):
     self.button = widget.Button(axes, label)
     self.button.on_clicked(self.process)
     return
Beispiel #22
0
#    global logt,ax3,fig
#   logt = - np.log10(t)
#  fig3 = plt.figure()
# ax3 = fig3.add_subplot(1,1,1)
#ax3.plot(waves,logt)
#plt.show()
#print("Taken absorption")

callback = Index()

axref = plt.axes([0.5, 0.05, 0.1, 0.075])
axcap = plt.axes([0.61, 0.05, 0.1, 0.075])
#axtrans = plt.axes([0.72,0.05,0.1,0.075])
#axabsobs = plt.axes([0.83,0.05,0.1,0.075])

refs = Button.Button(axref, 'Ref')
refs.on_clicked(callback.ref)

captures = Button.Button(axcap, 'Capture')
captures.on_clicked(callback.capture)

#transs = Button.Button(axtrans,'Calculate transmission')
#transs.on_clicked(callback.trans)

#aborbss = Button.Button(axabsobs,'Calculate absorption')
#aborbss.on_clicked(callback.aborbs)

#Need to store graph to keep it alive
ani = animation.FuncAnimation(fig, animate, interval=100)
plt.show()
Beispiel #23
0
def add_controls(axes=None, slider=False):
    """ Adds Start/Stop controls to an axes having been given a animation
    instance. """

    #If No axes specified use current axes.
    if not axes:
        axes = plt.gca()
    fig = axes.get_figure()

    #Split up the current axes so there is space for a start and a stop button
    divider = make_axes_locatable(axes)
    pad = 0.1  # Padding between axes
    pad_size = Size.Fraction(pad, Size.AxesX(axes))

    #Define size of usefult axes cells, 50% each in x 20% for buttons in y.
    xsize = Size.Fraction((1. - 2. * pad) / 3., Size.AxesX(axes))
    ysize = Size.Fraction((1. - 2. * pad) / 15., Size.AxesY(axes))

    #Set up grid, 3x3 with cells for padding.
    divider.set_horizontal([xsize, pad_size, xsize, pad_size, xsize])
    if slider:
        divider.set_vertical(
            [ysize, pad_size, ysize, pad_size,
             Size.AxesY(axes)])
        bny = 2
    else:
        divider.set_vertical([ysize, pad_size, Size.AxesY(axes)])
        bny = 0

    #Main figure spans all horiz and is in the top (2) in vert.
    axes.set_axes_locator(
        divider.new_locator(0, len(divider.get_vertical()) - 1, nx1=-1))

    #Add two axes for buttons and make them 50/50 spilt at the bottom.
    bax1 = fig.add_axes((0., 0., 1., 1.))
    locator = divider.new_locator(nx=0, ny=bny)
    bax1.set_axes_locator(locator)
    bax2 = fig.add_axes((0., 0., 0.8, 1.))
    locator = divider.new_locator(nx=2, ny=bny)
    bax2.set_axes_locator(locator)
    bax3 = fig.add_axes((0., 0., 0.7, 1.))
    locator = divider.new_locator(nx=4, ny=bny)
    bax3.set_axes_locator(locator)

    start = widgets.Button(bax1, "Start")
    stop = widgets.Button(bax2, "Stop")
    step = widgets.Button(bax3, "Step")
    #Make dummy refernce to prevent garbage collection
    bax1._button = start
    bax2._button = stop
    bax3._button = step

    if slider:
        bax4 = fig.add_axes((0., 0., 0.6, 1.))
        locator = divider.new_locator(nx=0, ny=0, nx1=-1)
        bax4.set_axes_locator(locator)
        sframe = widgets.Slider(bax4, 'Frame', 0, 10, valinit=0, valfmt='%i')
        bax4._slider = sframe

        return axes, bax1, bax2, bax3, bax4
    return axes, bax1, bax2, bax3
Beispiel #24
0
    def run(self):
        # Start thread for serial communication:
        self._serialThread.start()

        # Initialize plot:
        fig = pyplot.figure()
        gs = gridspec.GridSpec(9, 6, figure=fig)
        ax0 = fig.add_subplot(gs[:6, :])
        ax1 = fig.add_subplot(gs[6:8, :], sharex=ax0)
        ax2 = fig.add_subplot(gs[8, :2])
        ax3 = fig.add_subplot(gs[8, 2:4])
        ax4 = fig.add_subplot(gs[8, 4])
        ax5 = fig.add_subplot(gs[8, 5])
        axs = (ax0, ax1, ax2, ax3, ax4, ax5)
        box1 = widgets.TextBox(axs[2], 'Lower Limit (°C)')
        box1.on_text_change(self._changeLower)
        box2 = widgets.TextBox(axs[3], 'Upper Limit (°C)')
        box2.on_text_change(self._changeUpper)
        submit = widgets.Button(axs[5], 'Set')
        submit.on_clicked(self._setLimits)
        pyplot.ion()
        pyplot.show()

        # Start main loop:
        while True:
            # Check for messages:
            with self._serialLock:
                while True:
                    try:
                        print(self._serialData['messages'].pop(0))
                    except IndexError:
                        break

            # Acquire data:
            with self._serialLock:
                t = [v[0] for v in self._serialData['history']]
                Tc = [v[1] for v in self._serialData['history']]
                Tl = [v[2] for v in self._serialData['history']]
                Th = [v[3] for v in self._serialData['history']]
                Hs = [v[4] for v in self._serialData['history']]

            # Convert time to seconds relative to the last status:
            if len(t) > 0:
                t = [(v - t[-1]) / 1000. for v in t]

            # Clear plots:
            axs[0].clear()
            axs[1].clear()
            axs[4].clear()
            axs[4].axis('off')

            # Plot new data:
            axs[0].plot(t, Tc, c='tab:blue')
            axs[0].plot(t, Tl, c='tab:red')
            axs[0].plot(t, Th, c='tab:red')
            axs[0].set_ylabel('temperature / °C')
            axs[1].plot(t, Hs, c='tab:blue')
            axs[1].set_xlabel('time / s')
            axs[1].set_ylabel('heater')
            axs[1].set_yticks([0, 1])
            axs[1].set_yticklabels(['off', 'on'])

            # Set status:
            with self._serialLock:
                statusText = self._serialData['status']
            if len(t) > 0:
                statusText += ', %s, %s, %s' % (
                    '%.2f' % Tc[-1] if Tc[-1] is not None else '-',
                    '%.2f' % Tl[-1] if Tl[-1] is not None else '-',
                    '%.2f' % Th[-1] if Th[-1] is not None else '-')
            axs[4].text(0, 0, statusText)

            # Draw plots:
            fig.tight_layout()
            fig.canvas.draw_idle()
            fig.canvas.start_event_loop(2)
Beispiel #25
0
    def __init__( self, data=[], figure=-1, slices=[], \
       startP=[0.0,0.0,0.0], voxSize=[1.0,1.0,1.0], cmap=cm.bone, \
       im1_data=-1, im1_startP=-1, im1_voxSize=-1, im1_cmap=-1, \
       im2_data=-1, im2_startP=-1, im2_voxSize=-1, im2_cmap=-1, \
       interpType='linear'):
        """
		Create a GUI displaying the desired data in 3 orthogonal views.
		The user can click to select a view and then press keys n and p to move between slices
		and press keys a, s and c to switch between views.
		Arguments:
			data	The data as a 3D numpy array to be displayed.
			figure	Plot axes in an existing figure along the right hand side
						(default is to create a new figure window)
			slices	A 3 element list of slice indices to initialize the 3 viewing axes
						(default to centre of data cube in each direction)
			startP	A 3 element list indicating the start position for the slice position axes.
						(default to [0,0,0])
			voxSize	A 3 element list indicating the voxel size along each axes.
						(default to [1,1,1])
			
			cmap	A matplotlib colormap used to display the image (default is cm.bone)
			
		----------------------------------
		When supplying two or three data arrays the following arguments replace the single data equivalents
			im1_data	The data as a 3D numpy array to be displayed as the first imageset.
			im1_startP	A 3 element list for the start position of im1_data
			im1_voxSize	A 3 element list for the voxel size of im1_data
			im1_cmap	A matplotlib colormap to be assigned to im1_data
			
			im2_data	The data as a 3D numpy array to be displayed as the second imageset.
			im2_startP	A 3 element list for the start position of im2_data
			im2_voxSize	A 3 element list for the voxel size of im2_data
			im2_cmap	A matplotlib colormap to be assigned to im2_data
		"""

        # If we've been given a figure then use it otherwise make a new figure
        if type(figure) is int and figure < 0:
            self._fig = pylab.figure()
        else:
            self._fig = figure

        # Disable native keyboard shortcuts
        for key in pyplot.rcParams:
            if 'keymap.' in key:
                pyplot.rcParams[key] = ''

        figWidth, figHeight = self._fig.get_size_inches()

        btmBrdr = 0.02  # 0.05
        topBrdr = 0.02  # 0.05
        midBrdrH = 0.02  # 0.05
        midBrdrW = 0.05  # 0.05
        lftBrdr = 0.2
        rtBrdr = 0.05
        btmFigHeightShare = 0.4

        topFigH = 1.0 - topBrdr - btmBrdr - midBrdrH
        btmFigH = topFigH * btmFigHeightShare
        topFigH -= btmFigH
        btmFigW = btmFigH
        topFigW = btmFigW * 2.0 + midBrdrW

        self.connect()

        self._ax = []
        self._ax.append(
            self._fig.add_axes(
                [lftBrdr, btmBrdr + btmFigH + midBrdrH, topFigW, topFigH]))
        self._ax.append(
            self._fig.add_axes([lftBrdr, btmBrdr, btmFigW, btmFigH]))
        self._ax.append(
            self._fig.add_axes(
                [lftBrdr + btmFigW + midBrdrW, btmBrdr, btmFigW, btmFigH]))

        self.processArguments(data, slices, startP, voxSize, cmap, im1_data, im1_startP, im1_voxSize, \
            im1_cmap, im2_data, im2_startP, im2_voxSize, im2_cmap, interpType)

        self.initializeImageSlices()

        self._widetAx = []
        for aa in self._ax:
            aa.get_xaxis().set_visible(False)
            aa.get_yaxis().set_visible(False)
            self._widetAx.append(widgets.Button(aa, ''))

        self._widetAx[0].on_clicked(self.clickAx1)
        self._widetAx[1].on_clicked(self.clickAx2)
        self._widetAx[2].on_clicked(self.clickAx3)

        for ax in range(3):
            self.refreshIm(ax)
        self.clickAx1('')

        pylab.show()
Beispiel #26
0
 def init(self):
   import matplotlib.gridspec as gridspec
   gs = gridspec.GridSpec(TvaPlot.rows, TvaPlot.cols,
       left=0.07, right=0.95, bottom=0.04, top=0.96, wspace=1.2, hspace=0.5)
   # Create TD plots
   self.IQA = []
   for r in (0, 1):
     ax = plt.subplot(gs[2*r:2*(r+1),:TvaPlot.cols//2])
     l_iq = ax.plot([], [], 'b-', [], [], 'r-.', lw=1)
     plt.locator_params(axis='y', nbins=5)
     ax.set_ylabel('RX {}: TD IQA'.format(r))
     ax.grid(True)
     ax_t = ax.twinx()
     l_acf = ax_t.plot([], [], 'y-', lw=1, alpha=0.8)
     plt.locator_params(axis='y', nbins=5)
     ax_t.set_xlim(0, self.args.sam_len/self.args.rsam_mhz)
     ax_t.set_ylim(0, 1.0)
     ax_t.yaxis.set_ticklabels([])
     self.IQA.extend(l_iq + l_acf)
   # Create PSD plots
   ax = plt.subplot(gs[0:4,TvaPlot.cols//2:])
   plt.locator_params(axis='y', nbins=5)
   ax.yaxis.tick_right()
   ax.yaxis.set_ticks_position('both')
   ax.yaxis.set_label_position('right')
   ax.set_ylabel('Spectrum')
   ax.set_xlim(-self.args.rsam_mhz/2, self.args.rsam_mhz/2)
   ax.grid(True)
   self.PSD = ax.semilogy([], [], 'b-', [], [], 'g-', lw=2)
   # Create ERG maps
   self.ERG = []
   for p in range(2):
     ax = plt.subplot(gs[p+4:(p+1)+4,:-1])
     plt.locator_params(axis='y', nbins=2)
     ax.set_ylabel('RX {}'.format(p))
     self.ERG.append(ax)
     ax = plt.subplot(gs[p+4:(p+1)+4,-1])
     self.ERG.append(ax)
   # Create DMRS plots
   mrks = 'b+', 'rx', 'g^', 'yv'
   K = len(mrks)
   self.DMRS = []
   for p in range(2):
     for q in range(0, TvaPlot.cols//2, TvaPlot.cols//8):
       ax = plt.subplot(gs[2*p+6:2*(p+1)+6,q:q+TvaPlot.cols//8])
       plt.locator_params(axis='y', nbins=5)
       plt.locator_params(axis='x', nbins=3)
       if q > 0: ax.yaxis.set_ticklabels([])
       if p == 0: ax.xaxis.set_ticklabels([])
       ax.grid(True)
       k = 0
       for s in range(self.args.slot_len):
         l = ax.scatter([], [], c=mrks[k][0], marker=mrks[k][1], alpha=0.5)
         self.DMRS.append(l)
         k = (k + 1) % K
   # Control buttons
   import matplotlib.widgets as wgt
   self.Controls = {}
   ax = plt.subplot(gs[-1,-3:])
   wg = wgt.Button(ax, 'RESTART')
   self.set_btn_color(wg, False)
   self.Controls['restart'] = wg
   ax = plt.subplot(gs[-2,-3:])
   wg = wgt.Button(ax, 'STATS')
   self.set_btn_color(wg, False)
   self.Controls['stats'] = wg
   ax = plt.subplot(gs[-3,-3:])
   wg = wgt.Button(ax, 'PAUSE')
   self.set_btn_color(wg, False)
   self.Controls['pause'] = wg
   # Other properties
   self.connected = True
   self.pause = False
   return None #self.IQA + self.PSD + self.DMRS
                        valfmt='%g',
                        transform=ax.transAxes)

slide_C_ax = plt.axes([0.2, 0.05, 0.4, 0.05], facecolor=widget_color)
slide_C = widget.Slider(slide_C_ax,
                        'downcut at\n valley',
                        C_min,
                        C_max,
                        valinit=U,
                        valstep=0.05,
                        valfmt='%g',
                        transform=ax.transAxes)

btn_hill_reset_ax = plt.axes([0.7, 0.2, 0.25, 0.04])
btn_hill_reset = widget.Button(btn_hill_reset_ax,
                               'Reset hillslope',
                               color=widget_color,
                               hovercolor='0.975')

btn_slide_reset_ax = plt.axes([0.7, 0.1, 0.25, 0.04])
btn_slide_reset = widget.Button(btn_slide_reset_ax,
                                'Reset sliders',
                                color=widget_color,
                                hovercolor='0.975')


# reset functions
def reset_hillslope(event):
    z[:] = z_init[:]


def reset_sliders(event):
                '{}_{}_{}.png'.format(gen_time_str(),
                                      feature_name[idx_feature],
                                      ('pos' if step_size > 0 else 'neg'))))

    def set_feature_lock(self, event, idx_feature):
        self.feature_lock_status[idx_feature] = np.logical_not(
            self.feature_lock_status[idx_feature])
        self.feature_directoion_disentangled = feature_axis.disentangle_feature_axis_by_idx(
            self.feature_direction,
            idx_base=np.flatnonzero(self.feature_lock_status))


callback = GuiCallback()

ax_randgen = plt.axes([0.55, 0.90, 0.15, 0.05])
b_randgen = widgets.Button(ax_randgen, 'Random Generate')
b_randgen.on_clicked(callback.random_gen)


def get_loc_control(idx_feature,
                    nrows=8,
                    ncols=5,
                    xywh_range=(0.51, 0.05, 0.48, 0.8)):
    r = idx_feature // ncols
    c = idx_feature % ncols
    x, y, w, h = xywh_range
    xywh = x + c * w / ncols, y + (nrows - r -
                                   1) * h / nrows, w / ncols, h / nrows
    return xywh

Beispiel #29
0
                              gsMin,
                              gsMax,
                              valinit=gsInit,
                              valstep=1,
                              valfmt='%i',
                              transform=ax_nondim.transAxes)

ax_ustar = plt.axes([0.125, 0.0875, 0.3, 0.05], facecolor=widget_color)
slide_ustar = utils.MinMaxSlider(ax_ustar,
                                 'shear velocity [cm/s]',
                                 ustarMin,
                                 ustarMax,
                                 valinit=ustarInit,
                                 valstep=1,
                                 valfmt='%i',
                                 transform=ax_nondim.transAxes)

btn_reset_ax = plt.axes([0.8, 0.08, 0.1, 0.04])
btn_reset = widget.Button(btn_reset_ax,
                          'Reset',
                          color=widget_color,
                          hovercolor='0.975')

# connect widgets
slide_gs.on_changed(run_model)
slide_ustar.on_changed(run_model)
btn_reset.on_clicked(reset)

# show the results
plt.show()
Beispiel #30
0
def diff_viewer(repo, key, repo_fname, phash, status, expected_fname,
                result_fname, diff_fname):
    fig = plt.figure(figsize=(14, 12))
    plt.suptitle(os.path.basename(expected_fname))
    ax = plt.subplot(221)
    ax.imshow(mimg.imread(expected_fname))
    ax = plt.subplot(222, sharex=ax, sharey=ax)
    ax.imshow(mimg.imread(result_fname))
    ax = plt.subplot(223, sharex=ax, sharey=ax)
    ax.imshow(mimg.imread(diff_fname))

    result_dir = os.path.dirname(result_fname)
    fname = '{}.png'.format(phash)
    base_uri = 'https://scitools.github.io/test-iris-imagehash/images/{}'
    uri = base_uri.format(fname)
    phash_fname = os.path.join(result_dir, fname)

    def accept(event):
        if uri not in repo[key]:
            # Ensure to maintain strict time order where the first uri
            # associated with the repo key is the oldest, and the last
            # uri is the youngest
            repo[key].append(uri)
            # Update the image repo.
            with open(repo_fname, 'wb') as fo:
                json.dump(repo,
                          codecs.getwriter('utf-8')(fo),
                          indent=4,
                          sort_keys=True)
            os.rename(result_fname, phash_fname)
            msg = 'ACCEPTED:  {} -> {}'
            print(
                msg.format(os.path.basename(result_fname),
                           os.path.basename(phash_fname)))
        else:
            msg = 'DUPLICATE: {} -> {} (ignored)'
            print(
                msg.format(os.path.basename(result_fname),
                           os.path.basename(phash_fname)))
            os.remove(result_fname)
        os.remove(diff_fname)
        plt.close()

    def reject(event):
        if uri not in repo[key]:
            print('REJECTED:  {}'.format(os.path.basename(result_fname)))
        else:
            msg = 'DUPLICATE: {} -> {} (ignored)'
            print(
                msg.format(os.path.basename(result_fname),
                           os.path.basename(phash_fname)))
        os.remove(result_fname)
        os.remove(diff_fname)
        plt.close()

    def skip(event):
        # Let's keep both the result and the diff files.
        print('SKIPPED:   {}'.format(os.path.basename(result_fname)))
        plt.close()

    ax_accept = plt.axes([0.59, 0.05, 0.1, 0.075])
    ax_reject = plt.axes([0.7, 0.05, 0.1, 0.075])
    ax_skip = plt.axes([0.81, 0.05, 0.1, 0.075])
    baccept = mwidget.Button(ax_accept, 'Accept')
    baccept.on_clicked(accept)
    breject = mwidget.Button(ax_reject, 'Reject')
    breject.on_clicked(reject)
    bskip = mwidget.Button(ax_skip, 'Skip')
    bskip.on_clicked(skip)
    plt.text(0.59, 0.15, status, transform=fig.transFigure)
    plt.show()