def add_normalise_power_selector(self):
     """
     Add a radio button to chose whether or not the power of all spectra 
     shouold be normalised to 1.
     """
     pos_shp = [0.02, 0.8, 0.05, 0.104]
     rax = self.ifft_fig.add_axes(pos_shp,
                                  axisbg=AXCOLOUR,
                                  title="normalise")
     np_tuple = ("yes", "no")
     self.normalise_power_selector = widgets.RadioButtons(rax,
                                                          np_tuple,
                                                          active=1)
     self.normalise_power_selector.on_clicked(self.update_normalise_power)
Beispiel #2
0
    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.07, 0.05, 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 = widgets.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.14, 0.05, 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 = widgets.RadioButtons(rax, 
                                             tuple(self.model.state_variables), 
                                             active=svy_ind)
        self.state_variable_y.on_clicked(self.update_svy)
Beispiel #3
0
 def add_yscale_selector(self):
     """
     Add a radio button to the figure for selecting which scaling the y-axes
     should use.
     """
     pos_shp = [0.02, 0.5, 0.05, 0.104]
     rax = self.ifft_fig.add_axes(pos_shp,
                                  facecolor=AXCOLOUR,
                                  title="yscale")
     yscale_tuple = ("log", "linear")
     self.yscale_selector = widgets.RadioButtons(rax,
                                                 yscale_tuple,
                                                 active=0)
     self.yscale_selector.on_clicked(self.update_yscale)
 def add_window_length_selector(self):
     """
     Generate radio selector buttons to set the window length is seconds.
     """
     noc = self.possible_window_lengths.shape[0]  # number of choices
     #State variable for the x axis
     pos_shp = [0.88, 0.07, 0.1, 0.12 + 0.02 * noc]
     rax = self.ifft_fig.add_axes(pos_shp,
                                  facecolor=AXCOLOUR,
                                  title="Segment length")
     wl_tup = tuple(self.possible_window_lengths)
     self.window_length_selector = widgets.RadioButtons(rax,
                                                        wl_tup,
                                                        active=4)
     self.window_length_selector.on_clicked(self.update_window_length)
 def add_variable_selector(self):
     """
     Generate radio selector buttons to set which state variable is 
     displayed.
     """
     noc = self.data.shape[1]  # number of choices
     #State variable for the x axis
     pos_shp = [0.02, 0.22, 0.05, 0.12 + 0.008 * noc]
     rax = self.ifft_fig.add_axes(pos_shp,
                                  facecolor=AXCOLOUR,
                                  title="state variable")
     self.variable_selector = widgets.RadioButtons(rax,
                                                   tuple(range(noc)),
                                                   active=0)
     self.variable_selector.on_clicked(self.update_variable)
    def plotResModel(self, res_range=(0, 4), res_num=9):
        """
        plot the resistivity model with finite element mesh on and scale is
        in meters, which makes everything a lot easier to handle at the
        moment.

        """
        self._make_resisitivity_range(res_range[0], res_range[1], res_num)

        # call plot2DmModel to draw figure and plot mesh grid
        self.mesh_plot = self.plot2DModel(femesh="on", yscale="m")

        # connect to a button press event for changing resistivity values in
        # the plot
        self.cid = self.mesh_plot.ax.figure.canvas.mpl_connect(
            "button_press_event", self.get_mclick_xy
        )

        # connect to a key press event for changing resistivity values
        self.cid_pmres = self.mesh_plot.ax.figure.canvas.mpl_connect(
            "key_press_event", self.pmRes
        )

        # make a rectangular selector
        self.rect_selector = widgets.RectangleSelector(
            self.mesh_plot.ax, self.rect_onselect, drawtype="box", useblit=True
        )

        # make a radio boxe for changing the resistivity values easily
        self.radio_res_ax = self.mesh_plot.fig.add_axes(self.radio_res_loc)
        self.radio_res_labels = ["air", "sea"] + [
            "{0:.4g}".format(rr) for rr in self.res_range[2:]
        ]

        self.radio_res = widgets.RadioButtons(
            self.radio_res_ax, self.radio_res_labels, active=self.res_ii
        )
        self.radio_res.on_clicked(self.set_res_value)

        # calculate minimum block width
        self.mesh_width = np.min(
            [
                abs(om.meshx[0, ii + 1] - xx)
                for ii, xx in enumerate(self.meshx[0, 7:-7], 7)
            ]
        )

        self._caluculate_midpoints()
 def add_window_function_selector(self):
     """
     Generate radio selector buttons to set the windowing function.
     """
     #TODO: add support for kaiser, requiers specification of beta.
     wf_tup = ("None", "hamming", "bartlett", "blackman", "hanning")
     noc = len(wf_tup)  # number of choices
     #State variable for the x axis
     pos_shp = [0.88, 0.77, 0.085, 0.12 + 0.01 * noc]
     rax = self.ifft_fig.add_axes(pos_shp,
                                  facecolor=AXCOLOUR,
                                  title="Windowing function")
     self.window_function_selector = widgets.RadioButtons(rax,
                                                          wf_tup,
                                                          active=0)
     self.window_function_selector.on_clicked(self.update_window_function)
Beispiel #8
0
    def __init__(self, simulation):
        self.simulation = simulation

        self.fig = plt.figure()
        self.scale_axes = plt.axes([0.25, 0.90, 0.65, 0.03])
        self.scale_slider = wdg.Slider(self.scale_axes,
                                       "Scale",
                                       0.01,
                                       16,
                                       valinit=1)
        self.h_offset_axes = plt.axes([0.25, 0.80, 0.65, 0.03])
        self.h_offset_slider = wdg.Slider(self.h_offset_axes,
                                          "Horizontal offset",
                                          -math.pi,
                                          math.pi,
                                          valinit=0)
        self.v_offset_axes = plt.axes([0.25, 0.70, 0.65, 0.03])
        self.v_offset_slider = wdg.Slider(self.v_offset_axes,
                                          "Vertical offset",
                                          -math.pi,
                                          math.pi,
                                          valinit=0)
        self.color_range_axes = plt.axes([0.25, 0.60, 0.65, 0.03])
        self.color_range_slider = wdg.Slider(self.color_range_axes,
                                             "Color range",
                                             0,
                                             200,
                                             valinit=100)
        self.width_axes = plt.axes([0.25, 0.50, 0.65, 0.03])
        self.width_slider = wdg.Slider(self.width_axes,
                                       "Width",
                                       0,
                                       100,
                                       valinit=8,
                                       valstep=1)
        self.height_axes = plt.axes([0.25, 0.40, 0.65, 0.03])
        self.height_slider = wdg.Slider(self.height_axes,
                                        "Height",
                                        0,
                                        100,
                                        valinit=1,
                                        valstep=1)
        self.z_axes = plt.axes([0.25, 0.30, 0.65, 0.03])
        self.z_slider = wdg.Slider(self.z_axes, "z", -2, 2, valinit=0)
        self.plane_axes = plt.axes([0.25, 0.1, 0.15, 0.15])
        self.plane_radio = wdg.RadioButtons(self.plane_axes,
                                            ('XY', 'XZ', 'YZ'))
Beispiel #9
0
def setup():
    #Setup figure
    #Top, Bottom, Side with top and bottom plot sharing x axis
    fig = plt.figure()
    top = plt.subplot(221)
    bot = plt.subplot(223, sharex=top)
    sid = plt.subplot(122)

    stklst = sorted(('AMZN', 'GE', 'GOOG', 'MSFT', 'YHOO', 'EBAY'))
    fig = plot_data(stklst[0], fig, top, bot, sid)

    #Setup for radio bottoms
    axcolor = 'lightgoldenrodyellow'
    ylen = len(stklst)/50.0
    prop_radio = plt.axes([0.95, 1-ylen, 0.048, ylen], axisbg=axcolor)
    radio = wd.RadioButtons(prop_radio, stklst)

    return [fig, top, bot, sid, radio]
Beispiel #10
0
def setup():
    stklst = sorted(('ABB', 'AMZN', 'GE', 'GOOG', 'MSFT', 'YHOO', 'EBAY'))

    #Setup figure
    #Top, Bottom, Side with top and bottom plot sharing x axis
    fig = plt.figure()
    top = plt.subplot2grid((3, 3), (0, 0), colspan=2)
    bot = plt.subplot2grid((3, 3), (1, 0), colspan=2, sharex=top)
    mlrn = plt.subplot2grid((3, 3), (2, 0), colspan=2, sharex=top)
    sid = plt.subplot2grid((3, 3), (0, 2), rowspan=3)

    fig = plot_data(stklst[0], fig, top, bot, mlrn, sid)

    #Setup for radio bottoms
    axcolor = 'lightgoldenrodyellow'
    ylen = len(stklst) / 50.0
    prop_radio = plt.axes([0.95, 1 - ylen, 0.048, ylen], axisbg=axcolor)
    radio = wd.RadioButtons(prop_radio, stklst)

    return [fig, top, bot, sid, mlrn, radio]
def main():
    """
    Display a fits file choosen by a radio button
    and allows to change the threshold with a slider
    """

    # Display the canvas
    fig, axis = plt.subplots()
    plt.subplots_adjust(left=0.1, bottom=0.25)

    # Get list of fits files
    file_list = []
    for _, _, file_list in os.walk('../data'):
        break
    fits_files = [
        file_name for file_name in file_list
        if file_name.split(".")[-1] == "fits"
    ]

    # Define radio button
    radio_axis = plt.axes([0.02, 0.5, 0.2, 0.3])
    radio = widgets.RadioButtons(radio_axis, fits_files)

    # Define slider axis
    slider_axis = plt.axes([0.2, 0.1, 0.6, 0.105])

    # Initialize Action class, display the first fits file
    # and get the slider
    action = Action(slider_axis, fig, axis)
    action.radio_action(fits_files[0])
    my_widget = action.my_widget

    # Use event handler and show
    radio.on_clicked(action.radio_action)
    my_widget.on_changed(action.slider_action)
    plt.show()

    return 0
def radio_buttons(rax, labels, user_callback=None):
    """
    rab = radio_buttons(rax, labels, user_callback=None)

Puts up radio buttons (only one selected at a time) for the strings
passed in the vector of strings "labels", in the matplotlib axes given by "rax".  
On click, if the function user_callback is set, it will be called, with a string 
as its single parameter-- that string will be the label of the selected button. 

You can also access the string of the currently selected button through
    
    rab.value_selected
        
Or, in Julia, with the PyCall syntax

    rab[:value_selected]
     
    """
    radio = Wid.RadioButtons(rax, labels)
    if user_callback != None:
        radio.on_clicked(user_callback)

    return radio
Beispiel #13
0
def main():

    dirpath, interactive = lib_args.get_args()
    filepaths = scan_dir(dirpath)

    # batch console output
    if not interactive:

        for filepath in filepaths:
            print(filepath)

    # graphic interaction
    else:

        fig, img_axis = plt.subplots(figsize=(10, 5))
        plt.subplots_adjust(left=0.05, right=0.45, bottom=0.1, top=0.9)
        buttons_axis = plt.axes([0.55, 0.1, 0.4, 0.8])
        buttons = widgets.RadioButtons(buttons_axis, filepaths)
        callback = UpdateFile(img_axis, fig)
        buttons.on_clicked(callback)
        callback(filepaths[0])
        plt.show()

    return 0
Beispiel #14
0
    def __create_radio(self) -> None:
        """Build the radio widget."""

        # create new axis for radio widget
        x0 = self.bbox[0]
        y0 = self.bbox[1]
        width = self.bbox[2] / 3
        height = self.bbox[3]
        axis = self.figure.add_axes([x0, y0, width, height])

        # formatting
        axis.patch.set_facecolor('none')
        axis.patch.set_edgecolor('none')
        for edge in 'left', 'right', 'top', 'bottom':
            axis.spines[edge].set_visible(False)
        self.__radio_axis = axis

        # create widget
        options = {'activecolor': 'steelblue'}
        options.update(self.radio_options)
        self.__radio = widgets.RadioButtons(
            axis, tuple(model.label for model in self.models), **options)
        # update function
        self.__radio.on_clicked(self.__radio_on_clicked)
Beispiel #15
0
    def __init__(self):

        self.param = {
            "dust_type": "MW",
            "tau_V": 1,
            "geometry": "SHELL",
            "dust_distrib": "homogeneous",
        }

        # generate the curves and plot them
        # Use 1/microns for a better sampling
        self.x = np.arange(0.35, 10.0, 0.1) / u.micron

        self.x_Vband = 0.55

        self.fig, self.ax = plt.subplots(figsize=(15, 10))

        self.axatt = plt.subplot2grid((4, 2), (0, 0), colspan=2, rowspan=3)
        self.axFF = plt.subplot2grid((4, 2), (3, 0), colspan=1, rowspan=1)
        self.axalb = plt.subplot2grid((4, 2), (3, 1), colspan=1, rowspan=1)

        self.fig.canvas.set_window_title("widget for WG00 RT model")
        plt.subplots_adjust(bottom=0.15)
        plt.subplots_adjust(left=0.35)
        plt.subplots_adjust(hspace=0.8)

        axcolor = "lightgoldenrodyellow"

        self.rax_sketch = plt.axes([0.03, 0.68, 0.25, 0.32])
        self.rax_sketch.axis("off")

        rax = plt.axes([0.05, 0.52, 0.15, 0.15], facecolor=axcolor)
        dust_type = wgt.RadioButtons(rax, ("MW", "SMC"))
        dust_type.on_clicked(self.update_dust_type)

        rax = plt.axes([0.05, 0.335, 0.15, 0.15], facecolor=axcolor)
        geometry = wgt.RadioButtons(rax, ("SHELL", "CLOUDY", "DUSTY"))
        geometry.on_clicked(self.update_geometry)

        rax = plt.axes([0.05, 0.15, 0.15, 0.15], facecolor=axcolor)
        distrib = wgt.RadioButtons(rax, ("Homogeneous", "Clumpy"))
        distrib.on_clicked(self.update_dust_distrib)

        rax = plt.axes([0.05, 0.03, 0.12, 0.08], facecolor=axcolor)
        norm = wgt.CheckButtons(rax, (r"Normalised to A$_V$", ), (True, ))
        norm.on_clicked(self.update_norm)
        self.norm = True

        rax = plt.axes([0.3, 0.05, 0.6, 0.0275])
        tau_V = wgt.Slider(rax,
                           r"$\tau_V$",
                           0.5,
                           50,
                           valinit=self.param["tau_V"])
        tau_V.on_changed(self.update_tau_V)

        # Initialise WG00 model
        self.att_model = WG00(
            tau_V=self.param["tau_V"],
            geometry=self.param["geometry"],
            dust_type=self.param["dust_type"],
            dust_distribution=self.param["dust_distrib"],
        )

        self.update_sketch()
        self.update_att_curve()
        plt.show()
    def __init__(self):

        self.param = {
            'dust_type': 'MW',
            'tau_V': 1,
            'geometry': 'SHELL',
            'dust_distrib': 'homogeneous'
        }

        # generate the curves and plot them
        # Use 1/microns for a better sampling
        self.x = np.arange(0.35, 10.0, 0.1) / u.micron

        self.x_Vband = 0.55

        self.fig, self.ax = plt.subplots(figsize=(15, 10))

        self.axatt = plt.subplot2grid((4, 2), (0, 0), colspan=2, rowspan=3)
        self.axFF = plt.subplot2grid((4, 2), (3, 0), colspan=1, rowspan=1)
        self.axalb = plt.subplot2grid((4, 2), (3, 1), colspan=1, rowspan=1)

        self.fig.canvas.set_window_title('widget for WG00 RT model')
        plt.subplots_adjust(bottom=0.15)
        plt.subplots_adjust(left=0.35)
        plt.subplots_adjust(hspace=0.8)

        axcolor = 'lightgoldenrodyellow'

        self.rax_sketch = plt.axes([.03, .68, .25, .32])
        self.rax_sketch.axis('off')

        rax = plt.axes([0.05, 0.52, 0.15, 0.15], facecolor=axcolor)
        dust_type = wgt.RadioButtons(rax, ('MW', 'SMC'))
        dust_type.on_clicked(self.update_dust_type)

        rax = plt.axes([0.05, 0.335, 0.15, 0.15], facecolor=axcolor)
        geometry = wgt.RadioButtons(rax, ('SHELL', 'CLOUDY', 'DUSTY'))
        geometry.on_clicked(self.update_geometry)

        rax = plt.axes([0.05, 0.15, 0.15, 0.15], facecolor=axcolor)
        distrib = wgt.RadioButtons(rax, ('Homogeneous', 'Clumpy'))
        distrib.on_clicked(self.update_dust_distrib)

        rax = plt.axes([0.05, 0.03, 0.12, 0.08], facecolor=axcolor)
        norm = wgt.CheckButtons(rax, (r'Normalised to A$_V$', ), (True, ))
        norm.on_clicked(self.update_norm)
        self.norm = True

        rax = plt.axes([.3, .05, .6, .0275])
        tau_V = wgt.Slider(rax,
                           r'$\tau_V$',
                           0.5,
                           50,
                           valinit=self.param['tau_V'])
        tau_V.on_changed(self.update_tau_V)

        # Initialise WG00 model
        self.att_model = WG00(tau_V=self.param['tau_V'],
                              geometry=self.param['geometry'],
                              dust_type=self.param['dust_type'],
                              dust_distribution=self.param['dust_distrib'])

        self.update_sketch()
        self.update_att_curve()
        plt.show()
Beispiel #17
0
def kwargs_to_mpl_widgets(kwargs, params, update, slider_format_strings):
    n_opts = 0
    n_radio = 0
    n_sliders = 0
    for key, val in kwargs.items():
        if isinstance(val, set):
            new_opts = extract_num_options(val)
            if new_opts > 0:
                n_radio += 1
                n_opts += new_opts
        elif (not isinstance(val, mwidgets.AxesWidget)
              and not isinstance(val, widgets.fixed)
              and isinstance(val, Iterable) and len(val) > 1):
            n_sliders += 1

    # These are roughly the sizes used in the matplotlib widget tutorial
    # https://matplotlib.org/3.2.2/gallery/widgets/slider_demo.html#sphx-glr-gallery-widgets-slider-demo-py
    slider_in = 0.15
    radio_in = 0.6 / 3
    widget_gap_in = 0.1

    widget_inches = (n_sliders * slider_in + n_opts * radio_in +
                     widget_gap_in * (n_sliders + n_radio + 1) + 0.5
                     )  # half an inch for margin
    fig = None
    if not all(
            map(lambda x: isinstance(x, mwidgets.AxesWidget),
                kwargs.values())):
        # if the only kwargs are existing matplotlib widgets don't make a new figure
        with ioff:
            fig = figure()
        size = fig.get_size_inches()
        fig_h = widget_inches
        fig.set_size_inches(size[0], widget_inches)
        slider_height = slider_in / fig_h
        radio_height = radio_in / fig_h
        # radio
        gap_height = widget_gap_in / fig_h
    widget_y = 0.05
    slider_ax = []
    sliders = []
    radio_ax = []
    radio_buttons = []
    cbs = []
    for key, val in kwargs.items():
        if isinstance(val, set):
            if len(val) == 1:
                val = val.pop()
                if isinstance(val, tuple):
                    pass
                else:
                    params[key] = val
                    continue
            else:
                val = list(val)

            n = len(val)
            longest_len = max(list(map(lambda x: len(list(x)), map(str, val))))
            # should probably use something based on fontsize rather that .015
            width = max(0.15, 0.015 * longest_len)
            radio_ax.append(
                axes([
                    0.2, 0.9 - widget_y - radio_height * n, width,
                    radio_height * n
                ]))
            widget_y += radio_height * n + gap_height
            radio_buttons.append(
                mwidgets.RadioButtons(radio_ax[-1], val, active=0))
            cbs.append(radio_buttons[-1].on_clicked(
                partial(changeify, key=key, update=update)))
            params[key] = val[0]
        elif isinstance(val, mwidgets.RadioButtons):
            val.on_clicked(partial(changeify, key=key, update=update))
            params[key] = val.val
        elif isinstance(val, mwidgets.Slider):
            val.on_changed(partial(changeify, key=key, update=update))
            params[key] = val.val
        else:
            if isinstance(val, tuple):
                if len(val) == 2:
                    min_ = val[0]
                    max_ = val[1]
                elif len(val) == 3:
                    # should warn that that doesn't make sense with matplotlib sliders
                    min_ = val[0]
                    max_ = val[1]
            else:
                val = np.atleast_1d(val)
                if val.ndim > 1:
                    raise ValueError(
                        f"{key} is {val.ndim}D but can only be 1D or a scalar")
                if len(val) == 1:
                    # don't need to create a slider
                    params[key] = val[0]
                    continue
                else:
                    # list or numpy array
                    # should warn here as well
                    min_ = np.min(val)
                    max_ = np.max(val)

            slider_ax.append(
                axes([0.2, 0.9 - widget_y - gap_height, 0.65, slider_height]))
            sliders.append(
                mwidgets.Slider(
                    slider_ax[-1],
                    key,
                    min_,
                    max_,
                    valinit=min_,
                    valfmt=slider_format_strings[key],
                ))
            cbs.append(sliders[-1].on_changed(
                partial(changeify, key=key, update=update)))
            widget_y += slider_height + gap_height
            params[key] = min_
    controls = [fig, radio_ax, radio_buttons, slider_ax, sliders]
    return controls
Beispiel #18
0
    def __init__(self, datapath):
        """Initialization"""

        # object that handles output data
        self._data = OutputData.OutputData(datapath)

        # time dependent data for plotting
        self._scalar_t = self._data.get_scalar_t()
        self._mode_t = self._data.get_mode_t()

        # initial parameters
        self._iscalar = 0  # scalar index
        self._imode = 0  # mode index
        self._itime = 0  # time index
        self._itime1 = 0  # time range index 1
        self._itime2 = self._data.ntime  # time range index 2
        self._ispecies = self._data.nspecies  # species index
        self._iptcldist = 0  # 0: g; 1: f; 2: delta f
        self._ani_playing = False  # whether animation is playing

        # colormap
        cdict = {
            'red': [(0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 1.0, 1.0)],
            'green': [(0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 0.0, 0.0)],
            'blue': [(0.0, 1.0, 1.0), (0.5, 1.0, 1.0), (1.0, 0.0, 0.0)]
        }

        self._cmap = mpl.colors.LinearSegmentedColormap('BWR', cdict, 256)
        self._levels = (np.arange(64) - 31.5) / 31.5

        # layout
        self._fig = plt.figure(figsize=(22, 11))
        self._fig.canvas.set_window_title(os.path.abspath(datapath))
        # plots
        self._ax_scalar_t = self._fig.add_axes([0.04, 0.53, 0.18, 0.44])
        self._ax_mode_t = self._fig.add_axes([0.04, 0.045, 0.18, 0.44])
        self._ax_mode_amp_t = self._fig.add_axes([0.26, 0.53, 0.18, 0.44])
        self._ax_mode_norm_t = self._fig.add_axes([0.26, 0.045, 0.18, 0.44])
        self._ax_field_x = self._fig.add_axes([0.58, 0.53, 0.18, 0.44])
        #self._ax_chargeden_x = self._fig.add_axes([0.54, 0.045, 0.22, 0.44])
        self._ax_ptcldist_xv = self._fig.add_axes([0.8, 0.53, 0.16, 0.44])
        self._ax_ptcldist_xv_colorbar = self._fig.add_axes(
            [0.965, 0.53, 0.01, 0.44])
        self._ax_ptcldist_v = self._fig.add_axes([0.8, 0.045, 0.18, 0.44])
        # widgets
        self._ax_scalar_chooser = self._fig.add_axes([0.45, 0.85, 0.08, 0.1])
        self._ax_scalar_chooser.set_title('Scalar')
        self._ax_mode_chooser = self._fig.add_axes([0.45, 0.7, 0.08, 0.1])
        self._ax_mode_chooser.set_title('Fourier mode')
        self._ax_ptcldist_chooser = self._fig.add_axes([0.45, 0.55, 0.08, 0.1])
        self._ax_ptcldist_chooser.set_title('Distribution')
        self._ax_species_chooser = self._fig.add_axes([0.45, 0.4, 0.08, 0.1])
        self._ax_species_chooser.set_title('Species')
        self._ax_ani_playpause = self._fig.add_axes([0.45, 0.25, 0.08, 0.04])

        # clicking on window: time chooser and time range chooser
        self._fig.canvas.mpl_connect('button_press_event',
                                     self._canvas_on_press)
        self._fig.canvas.mpl_connect('button_release_event',
                                     self._canvas_on_release)

        # scalar chooser
        self._scalar_labels = ['$\int E^2 \mathrm{d} x$', \
            '$\int \, (g|f|\delta f) v^2 \mathrm{d} v \mathrm{d} x$']
        self._scalar_chooser = widgets.RadioButtons(self._ax_scalar_chooser, \
            self._scalar_labels, active = self._iscalar)
        self._scalar_chooser.on_clicked(self._scalar_chooser_on_click)

        # mode chooser
        self._mode_labels = []
        for i in range(self._data.nmode):
            self._mode_labels.append(str(self._data.mode[i]))
        self._mode_chooser = widgets.RadioButtons(self._ax_mode_chooser, \
            self._mode_labels, active = self._imode)
        self._mode_chooser.on_clicked(self._mode_chooser_on_click)

        # particle distribution chooser
        self._ptcldist_labels = ['$g$', '$f$', '$\delta f$']
        self._ptcldist_chooser = widgets.RadioButtons( \
            self._ax_ptcldist_chooser, self._ptcldist_labels, \
            active = self._iptcldist)
        self._ptcldist_chooser.on_clicked(self._ptcldist_chooser_on_click)

        # species chooser
        self._species_labels = []
        for ispecies in range(self._data.nspecies):
            self._species_labels.append(str(ispecies + 1))
        self._species_labels.append('Sum')
        self._species_chooser = widgets.RadioButtons( \
            self._ax_species_chooser, self._species_labels, \
            active = self._ispecies)
        self._species_chooser.on_clicked(self._species_chooser_on_click)

        # animation play/pause button
        self._ani_playpause = widgets.Button(self._ax_ani_playpause,
                                             'Play animation')
        self._ani_playpause.on_clicked(self._ani_playpause_on_click)

        # timer for animation
        self._timer = self._fig.canvas.new_timer(interval=200)
        self._timer.add_callback(self._ani_advance)
        self._timer.start()

        # update all plots
        self.update_plot_all()
Beispiel #19
0
    def __init__(self,
                 data_filter_change=None,
                 data_fir_n_change=None,
                 der_filter_change=None,
                 der_fir_n_change=None,
                 file_change=None,
                 refresh_button_click=None,
                 sh_click=None,
                 icg_click=None,
                 file_list: List[str] = None):

        self.fig, self.axs = plt.subplots(3, 2, constrained_layout=True)
        self.lines = numpy.ndarray(shape=(3, 2), dtype=plt.Line2D)
        plt.subplots_adjust(bottom=0.25)

        widgets.TextBox(plt.axes([0, 0.17, 0.12, 0.02]),
                        "",
                        initial="Data filter")
        self.data_filter_widget = widgets.RadioButtons(
            plt.axes([0, 0.01, 0.12, 0.15]), ["savgol", "FIR", "None"], 2)
        self.data_filter_widget.on_clicked(data_filter_change)

        self.data_fir_n_widget = widgets.Slider(plt.axes(
            [0.4, 0.08, 0.25, 0.05]),
                                                "Data FIR N",
                                                5,
                                                100,
                                                20,
                                                valstep=1)
        self.data_fir_n_widget.on_changed(data_fir_n_change)

        widgets.TextBox(plt.axes([0.12, 0.17, 0.12, 0.02]),
                        "",
                        initial="Derivative filter")
        self.der_filter_widget = widgets.RadioButtons(
            plt.axes([0.12, 0.01, 0.12, 0.15]), ["savgol", "FIR", "None"], 2)
        self.der_filter_widget.on_clicked(der_filter_change)

        self.der_fir_n_widget = widgets.Slider(plt.axes(
            [0.4, 0.02, 0.25, 0.05]),
                                               "Deriv FIR N",
                                               5,
                                               100,
                                               50,
                                               valstep=1)
        self.der_fir_n_widget.on_changed(der_fir_n_change)

        self.refresh_button = widgets.Button(
            plt.axes([0.40, 0.15, 0.08, 0.05]), "Measure")
        self.refresh_button.on_clicked(refresh_button_click)

        self.sh_widget = widgets.TextBox(plt.axes([0.5, 0.15, 0.05, 0.05]), "",
                                         "200")
        self.sh_plus_btn = widgets.Button(plt.axes([0.55, 0.175, 0.02, 0.025]),
                                          "+")
        self.sh_minus_btn = widgets.Button(plt.axes([0.55, 0.15, 0.02, 0.025]),
                                           "-")

        def sh_pl_cl(_):
            new_val = int(self.sh_widget.text) + 50
            self.sh_widget.set_val(str(new_val))
            sh_click(new_val)

        def sh_mn_cl(_):
            new_val = int(self.sh_widget.text) - 50
            self.sh_widget.set_val(str(new_val))
            sh_click(new_val)

        self.sh_plus_btn.on_clicked(sh_pl_cl)
        self.sh_minus_btn.on_clicked(sh_mn_cl)
        self.sh_widget.on_text_change(
            lambda _: sh_click(int(self.sh_widget.text)))

        self.icg_widget = widgets.TextBox(plt.axes([0.6, 0.15, 0.05, 0.05]),
                                          "", "100000")
        self.icg_plus_btn = widgets.Button(
            plt.axes([0.65, 0.175, 0.02, 0.025]), "+")
        self.icg_minus_btn = widgets.Button(
            plt.axes([0.65, 0.15, 0.02, 0.025]), "-")
        self.icg_widget.on_text_change(
            lambda _: icg_click(int(self.icg_widget.text)))

        def icg_pl_cl(_):
            new_val = int(self.icg_widget.text) + 1000
            self.icg_widget.set_val(str(new_val))
            sh_click(new_val)

        def icg_mn_cl(_):
            new_val = int(self.icg_widget.text) - 1000
            self.icg_widget.set_val(str(new_val))
            sh_click(new_val)

        self.icg_plus_btn.on_clicked(icg_pl_cl)
        self.icg_minus_btn.on_clicked(icg_mn_cl)

        if file_list is not None:
            self.file_list_widget = widgets.RadioButtons(
                plt.axes([0.7, 0.01, 0.28, 0.15]), file_list)
            self.file_list_widget.on_clicked(file_change)
Beispiel #20
0
    #ax2 = plt.axes([0.05, 0.15, 0.9, 0.80], projection='3d')
    ax_slider_1 = plt.axes([0.1, 0.01, 0.2, 0.02])
    ax_slider_2 = plt.axes([0.1, 0.04, 0.2, 0.02])
    ax_slider_3 = plt.axes([0.1, 0.07, 0.2, 0.02])
    ax_slider_4 = plt.axes([0.1, 0.1, 0.2, 0.02])
    ax_slider_5 = plt.axes([0.1, 0.13, 0.2, 0.02])
    ax_slider_6 = plt.axes([0.5, 0.01, 0.2, 0.02])
    ax_slider_7 = plt.axes([0.5, 0.04, 0.2, 0.02])
    ax_slider_8 = plt.axes([0.5, 0.07, 0.2, 0.02])
    ax_slider_9 = plt.axes([0.5, 0.1, 0.2, 0.02])
    ax_slider_10 = plt.axes([0.5, 0.13, 0.2, 0.02])
    rax = plt.axes([0.0, 0.8, 0.1, 0.15])
    ax_slider_11 = plt.axes([0.2, 0.97, 0.1, 0.02])
    ax_slider_12 = plt.axes([0.6, 0.97, 0.1, 0.02])
    ax_slider_13 = plt.axes([0.8, 0.97, 0.2, 0.02])
    radio = widgets.RadioButtons(rax, ('CW', 'Pulsed'))
    slider_1 = widgets.Slider(ax_slider_1, 'qwp_1', 0., 360)
    slider_2 = widgets.Slider(ax_slider_2, 'hwp_2', 0., 360)
    slider_3 = widgets.Slider(ax_slider_3, 'qwp_2', 0., 360)
    slider_4 = widgets.Slider(ax_slider_4, 'hwp_3', 0., 360)
    slider_5 = widgets.Slider(ax_slider_5, 'qwp_3', 0., 360)
    slider_6 = widgets.Slider(ax_slider_6, 'delay_2', -2, 2)
    slider_7 = widgets.Slider(ax_slider_7, 'delay_3', -2, 2)
    slider_8 = widgets.Slider(ax_slider_8, 'ampl_1', 0, 1)
    slider_9 = widgets.Slider(ax_slider_9, 'ampl_2', 0, 1)
    slider_10 = widgets.Slider(ax_slider_10, 'ampl_3', 0, 1)
    slider_11 = widgets.Slider(ax_slider_11, 'x-size', 0, 4)
    slider_12 = widgets.Slider(ax_slider_12, 'x-start', -2, 2)
    slider_13 = widgets.Slider(ax_slider_13, 'close', 0, 1)
    #start
Beispiel #21
0
    axe_rayon = plt.axes([0.7, 0.92, 0.2, 0.03])
    axe_infiny = plt.axes([0.025, 0.7, 0.1, 0.1])
    axe_r = plt.axes([0.025, 0.5, 0.1, 0.1])

    slider_teta = wdg.Slider(axe_teta,
                             'Ouverture',
                             0,
                             np.pi / 4,
                             valinit=np.pi / 6)
    slider_diametre = wdg.Slider(axe_dia,
                                 'Diamètre',
                                 0,
                                 np.pi / 2,
                                 valinit=np.pi / 6)
    slider_rayon = wdg.Slider(axe_rayon, "Rayon", 0.1, 15, valinit=10)
    button_inf = wdg.RadioButtons(axe_infiny, ('Infinie', 'Non'))
    button_type = wdg.RadioButtons(axe_r, ("Concave", "Convexe"))

    def mise_a_jour(val=None):

        #On enlève tous les rayon/miroirs/sources des listes pour en créer des nouveaux
        for rayon in lst_ray:
            lst_ray.remove(rayon)
        for sourcee in lst_source:
            lst_source.remove(sourcee)
        for miroire in lst_miroir:
            lst_miroir.remove(miroire)
        fig[1].cla()  #Clear de la figure

        #On récupère la valeur des widgets
        ouverture = slider_teta.val
Beispiel #22
0
def test_check_bunch_of_radio_buttons():
    rax = plt.axes([0.05, 0.1, 0.15, 0.7])
    widgets.RadioButtons(rax, ('B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B8',
                               'B9', 'B10', 'B11', 'B12', 'B13', 'B14', 'B15'))
Beispiel #23
0
def interactive_ui(base_path: str):
    # Load all array file
    print("Loading data")

    FILE_STABILITY_F     = "sampo.stability_f.array"
    FILE_STABILITY_E     = "sampo.stability_e.array"
    FILE_STABILITY_D     = "sampo.stability_d.array"
    FILE_PRESSURE_SELF   = "sampo.pressure_self.array"
    FILE_PRESSURE_ENEMY  = "sampo.pressure_enemy.array"
    FILE_BARRAGE_SELF    = "sampo.barrage_self.array"
    FILE_BARRAGE_ENEMY   = "sampo.barrage_enemy.array"
    FILE_PROXIMITY_SELF  = "sampo.proximity_self.array"
    FILE_PROXIMITY_ENEMY = "sampo.proximity_enemy.array"

    FILE_PATH1_SELF      = "sampo.path1_self.array"
    FILE_PATH1_ENEMY     = "sampo.path1_enemy.array"

    stability_F     = _load_field_from_file(base_path + '/' + FILE_STABILITY_F)
    stability_E     = _load_field_from_file(base_path + '/' + FILE_STABILITY_E)
    stability_D     = _load_field_from_file(base_path + '/' + FILE_STABILITY_D)
    pressure_self   = _load_field_from_file(base_path + '/' + FILE_PRESSURE_SELF)
    pressure_enemy  = _load_field_from_file(base_path + '/' + FILE_PRESSURE_ENEMY)
    barrage_self    = _load_field_from_file(base_path + '/' + FILE_BARRAGE_SELF)
    barrage_enemy   = _load_field_from_file(base_path + '/' + FILE_BARRAGE_ENEMY)
    proximity_self  = _load_field_from_file(base_path + '/' + FILE_PROXIMITY_SELF)
    proximity_enemy = _load_field_from_file(base_path + '/' + FILE_PROXIMITY_ENEMY)

    path1_self = _load_paths_from_file(base_path + '/' + FILE_PATH1_SELF)
    path1_enemy = _load_paths_from_file(base_path + '/' + FILE_PATH1_ENEMY)

    nTurns = len(stability_F)
    print("Turns: {}".format(nTurns))


    fig = pyplot.figure(figsize=(12,6))
    fig.subplots_adjust(hspace=0.05)
    nRows = 1
    nCols = 2
    heat_axis = fig.add_subplot(nRows, nCols, 1)

    grid = numpy.zeros((transform.ARENA_SIZE, transform.ARENA_SIZE))
    heat_im = heat_axis.imshow(grid.T,
            origin='lower', aspect='equal')
    path_axis = fig.add_subplot(nRows, nCols, 2)
    path_im = path_axis.imshow(grid.T,
            origin='lower', aspect='equal')

    def update_heat(a):
        #print("update_heat Called")
        grid = numpy.zeros((transform.ARENA_SIZE, transform.ARENA_SIZE))
        v_min = 0
        v_max = 1
        for p in range(transform.ARENA_VOL):
            x,y = transform.pos2_decode(p)
            grid[x][y] = a[p]
            v = a[p]
            if v == float('-inf') or v == float('inf'):
                v = -1
            if v < v_min: v_min = v
            if v > v_max: v_max = v
        heat_im.set_clim(vmin=v_min, vmax=v_max)
        heat_im.set_data(grid.T)
        #heat_im.set_clim()
        #print("Min: {}, Max: {}".format(v_min,v_max))

    update_heat(stability_F[0])

    def update_path(path, ty):
        grid = -numpy.ones((transform.ARENA_SIZE, transform.ARENA_SIZE))
        v_min = -1
        v_max = 1

        # Note: Enemy hazard is not computed.
        if path and not (ty == 2 and 'Enemy'== player_radio.value_selected):
            n = len(path)
            for i in range(n):
                x = path.px[i]
                y = path.py[i]
                if ty == 0:
                    grid[x][y] = path.damage_dp[i]
                elif ty == 1:
                    grid[x][y] = path.shield_dp[i]
                else:
                    grid[x][y] = path.hazard_dp[i]
                v = grid[x][y]
                if v < v_min: v_min = v
                if v > v_max: v_max = v
        
        path_im.set_clim(vmin=v_min, vmax=v_max)
        path_im.set_data(grid.T)



    fig.subplots_adjust(left=0.3,bottom=0.5,right=1.0)

    path_axis_bbox = path_axis.get_position()
    feasibility_plot_axis = fig.add_axes(
            [path_axis_bbox.xmin,0.3,path_axis_bbox.width,0.05])
            
    feasibility_plot_axis.set_autoscale_on(True)
    feasibility_plot_axis.get_xaxis().set_visible(False)
    feasibility_plot_axis.get_yaxis().set_visible(False)
    feasibility_plot, = feasibility_plot_axis.plot( \
        range(transform.ARENA_SIZE), [0] * transform.ARENA_SIZE)


    player_radio_axis = fig.add_axes([0,0.85,0.25,0.15])
    player_radio = widgets.RadioButtons(player_radio_axis,
            ('Self', 'Enemy'))

    fields_radio_axis = fig.add_axes([0,0.4,0.25,0.45])
    fields_radio = widgets.RadioButtons(fields_radio_axis,
            ('stability_F', 'stability_E', 'stability_D',
             'pressure', 'barrage', 'proximity'))
    path_radio_axis = fig.add_axes([0,0.2,0.25,0.2])
    path_radio = widgets.RadioButtons(path_radio_axis,
            ('Damage', 'Shield', 'Hazard'))

    turn_slider_axis = fig.add_axes([0.3,0.2,0.3,0.03])
    turn_slider = DiscreteSlider(turn_slider_axis, 'Turns', 0, nTurns-1,
            valinit=0, valfmt='%0.0f')
    colorbar_axis = fig.add_axes([0.3,0.3,0.3,0.03])
    fig.colorbar(heat_im, cax=colorbar_axis, orientation='horizontal')

    abscissa_slider_axis = fig.add_axes(
            [path_axis_bbox.xmin,0.2,path_axis_bbox.width,0.03])
    abscissa_slider = DiscreteSlider(abscissa_slider_axis, 'Ab.',
            0, transform.ARENA_SIZE - 1,
            valinit=0, valfmt='%0.0f')
    
    primal_button_axis = fig.add_axes([0.65,0.23, 0.05, 0.05])
    primal_button = widgets.Button(primal_button_axis, 'Primal')


    def onChange_field(val):
        turn = int(turn_slider.val)
        pname = player_radio.value_selected
        aname = fields_radio.value_selected
        #print("Event! aname: {}".format(aname))
        try:
            if   aname == 'stability_F': update_heat(stability_F[turn])
            elif aname == 'stability_E': update_heat(stability_E[turn])
            elif aname == 'stability_D': update_heat(stability_D[turn])
            elif aname == 'pressure':
                if pname == 'Self': update_heat(pressure_self[turn])
                else:               update_heat(pressure_enemy[turn])
            elif aname == 'barrage':
                if pname == 'Self': update_heat(barrage_self[turn])
                else:               update_heat(barrage_enemy[turn])
            elif aname == 'proximity':
                if pname == 'Self': update_heat(proximity_self[turn])
                else:               update_heat(proximity_enemy[turn])
            else: print("Unknown aname: {}".format(aname))
        except Exception as e:
            print(e)
        fig.canvas.draw_idle()
    def onChange_path(val):
        turns = int(turn_slider.val)
        ab = int(abscissa_slider.val)
        pname = player_radio.value_selected
        aname = path_radio.value_selected
        try:
            if   aname == 'Damage':
                if pname == 'Self': update_path(path1_self[turns][ab], ty=0)
                else:               update_path(path1_enemy[turns][ab], ty=0)
            elif aname == 'Shield':
                if pname == 'Self': update_path(path1_self[turns][ab], ty=1)
                else:               update_path(path1_enemy[turns][ab], ty=1)
            elif aname == 'Hazard':
                if pname == 'Self': update_path(path1_self[turns][ab], ty=2)
                else:               update_path(path1_enemy[turns][ab], ty=2)
            else: print("Unknown aname: {}".format(aname))
        except Exception as e:
            print(e)
        fig.canvas.draw_idle()
    def onClick_primal(event):
        turns = int(turn_slider.val)
        pname = player_radio.value_selected
        aname = path_radio.value_selected

        try:
            assert len(path1_self[turns]) == transform.ARENA_SIZE
            max_i = 0
            max_feasibility = float('-inf')
            for i in range(transform.ARENA_SIZE):
                if pname == 'Self':
                    p = path1_self[turns][i]
                else:
                    p = path1_enemy[turns][i]
                if not p:
                    continue
                assert p.evaluated
                if p.feasibility > max_feasibility:
                    max_i = i
                    max_feasibility = p.feasibility
            print("Primal at: {}".format(max_i))
            abscissa_slider.set_val(float(max_i))
        except Exception as e:
            raise
        onChange_path(None)


    def onChange(val):
        pname = player_radio.value_selected
        turns = int(turn_slider.val)
        if pname == 'Self': path_array = path1_self[turns]
        else:               path_array = path1_enemy[turns]

        feas = [(i,p.feasibility) for i,p in enumerate(path_array) if p]
        feas_x, feas_y = zip(*feas)
        feasibility_plot.set_data(feas_x, feas_y)
        feasibility_plot_axis.relim()
        feasibility_plot_axis.autoscale_view(True, True, True)

        onChange_field(val)
        onChange_path(val)

    player_radio.on_clicked(onChange)
    turn_slider.on_changed(onChange)
    fields_radio.on_clicked(onChange_field)
    abscissa_slider.on_changed(onChange_path)
    path_radio.on_clicked(onChange_path)
    primal_button.on_clicked(onClick_primal)




    pyplot.show()
    print('Plot closing')
    def __init__(self, blocksize, samplerate):
        # choosing style
        plt.style.use('dark_background')

        # creating figure and gridspec instance
        self.fig = plt.figure(figsize=(16, 9))
        self.gs = self.fig.add_gridspec(90, 160)

        def on_close(event):
            sys.exit()

        # connecting on_close event
        self.fig.canvas.mpl_connect('close_event', on_close)

        # creating and formatting axes for waveform
        self.ax1 = self.fig.add_subplot(self.gs[5:44, 0:63])
        self.ax1.grid(True, lw=0.2)

        self.x_max_span = np.round(blocksize * 1000 / samplerate, 1)

        self.ax1.set_xlim(-np.round(self.x_max_span / 8, 1),
                          np.round(self.x_max_span / 8, 1))
        self.ax1.set_xticks(
            np.linspace(-np.round(self.x_max_span / 8, 1),
                        np.round(self.x_max_span / 8, 1),
                        11,
                        endpoint=True))
        self.ax1.set_xticklabels([])

        self.ax1.set_ylim(-1, 1)
        self.ax1.set_yticks(np.linspace(-1, 1, 9, endpoint=True))
        self.ax1.set_yticklabels([])

        self.ax1.tick_params(axis='both', length=0)

        # creating and formatting axes for spectrum
        self.ax2 = self.fig.add_subplot(self.gs[45:84, 0:63])
        self.ax2.grid(True, lw=0.2)

        self.ax2.set_xlim(0, 22050)
        self.ax2.set_xticks(np.linspace(0, 22050, 11, endpoint=True))
        self.ax2.set_xticklabels([])

        self.ax2.set_ylim(0, 0.5)
        self.ax2.set_yticks(np.linspace(0, 0.5, 9, endpoint=True))
        self.ax2.set_yticklabels([])

        self.ax2.tick_params(axis='both', length=0)

        # creating text boxes for distances between cursors
        self.ax_t_1_l = self.fig.add_subplot(self.gs[0:4, 8:23])
        self.ax_t_1_l.set_xticklabels([])
        self.ax_t_1_l.set_yticklabels([])
        self.ax_t_1_l.tick_params(axis='both', length=0)
        self.t_1_l = self.ax_t_1_l.text(0.5, 0.5, '', ha='center', va='center')

        self.ax_t_1_r = self.fig.add_subplot(self.gs[0:4, 40:55])
        self.ax_t_1_r.set_xticklabels([])
        self.ax_t_1_r.set_yticklabels([])
        self.ax_t_1_r.tick_params(axis='both', length=0)
        self.t_1_r = self.ax_t_1_r.text(0.5, 0.5, '', ha='center', va='center')

        self.ax_t_2_l = self.fig.add_subplot(self.gs[85:89, 8:23])
        self.ax_t_2_l.set_xticklabels([])
        self.ax_t_2_l.set_yticklabels([])
        self.ax_t_2_l.tick_params(axis='both', length=0)
        self.t_2_l = self.ax_t_2_l.text(0.5, 0.5, '', ha='center', va='center')

        self.ax_t_2_r = self.fig.add_subplot(self.gs[85:89, 40:55])
        self.ax_t_2_r.set_xticklabels([])
        self.ax_t_2_r.set_yticklabels([])
        self.ax_t_2_r.tick_params(axis='both', length=0)
        self.t_2_r = self.ax_t_2_r.text(0.5, 0.5, '', ha='center', va='center')

        # creating text boxes for cell scales
        self.ax_t_y_ch_1 = self.fig.add_subplot(self.gs[9:13, 90:101])
        self.ax_t_y_ch_1.set_xticklabels([])
        self.ax_t_y_ch_1.set_yticklabels([])
        self.ax_t_y_ch_1.tick_params(axis='both', length=0)
        self.t_y_ch_1 = self.ax_t_y_ch_1.text(0.5,
                                              0.5,
                                              '0.25',
                                              ha='center',
                                              va='center')

        self.ax_t_y_ch_2 = self.fig.add_subplot(self.gs[9:13, 108:119])
        self.ax_t_y_ch_2.set_xticklabels([])
        self.ax_t_y_ch_2.set_yticklabels([])
        self.ax_t_y_ch_2.tick_params(axis='both', length=0)
        self.t_y_ch_2 = self.ax_t_y_ch_2.text(0.5,
                                              0.5,
                                              '0.25',
                                              ha='center',
                                              va='center')

        self.ax_t_y_ch_3 = self.fig.add_subplot(self.gs[9:14, 126:138])
        self.ax_t_y_ch_3.set_xticklabels([])
        self.ax_t_y_ch_3.set_yticklabels([])
        self.ax_t_y_ch_3.tick_params(axis='both', length=0)
        self.t_y_ch_3 = self.ax_t_y_ch_3.text(0.5,
                                              0.5,
                                              '0.25',
                                              ha='center',
                                              va='center')

        self.ax_t_y_ch_4 = self.fig.add_subplot(self.gs[9:13, 144:157])
        self.ax_t_y_ch_4.set_xticklabels([])
        self.ax_t_y_ch_4.set_yticklabels([])
        self.ax_t_y_ch_4.tick_params(axis='both', length=0)
        self.t_y_ch_4 = self.ax_t_y_ch_4.text(0.5,
                                              0.5,
                                              '0.25',
                                              ha='center',
                                              va='center')

        self.ax_t_x = self.fig.add_subplot(self.gs[54:58, 104:115])
        self.ax_t_x.set_xticklabels([])
        self.ax_t_x.set_yticklabels([])
        self.ax_t_x.tick_params(axis='both', length=0)
        self.t_x = self.ax_t_x.text(0.5,
                                    0.5,
                                    str(np.round(self.x_max_span / 40, 1)) +
                                    ' ms',
                                    ha='center',
                                    va='center')

        # creating X-scale slider
        self.ax_sl_x_sc = self.fig.add_subplot(self.gs[54:57, 66:97])
        self.ax_sl_x_sc.set_title('X-scale', {'fontsize': 10})
        self.sl_x_sc = wdgt.Slider(self.ax_sl_x_sc,
                                   '',
                                   -4,
                                   0,
                                   -2,
                                   valstep=0.5,
                                   facecolor='0.95')
        self.sl_x_sc.valtext.set_visible(False)

        # making X-scale slider work
        def scale_x(event):
            xcur1pos = (
                (self.xcur1.line.get_xdata()[0] - self.ax1.get_xlim()[0]) /
                (self.ax1.get_xlim()[1] - self.ax1.get_xlim()[0]))
            xcur2pos = (
                (self.xcur2.line.get_xdata()[0] - self.ax1.get_xlim()[0]) /
                (self.ax1.get_xlim()[1] - self.ax1.get_xlim()[0]))

            self.ax1.set_xlim(
                -np.round(self.x_max_span * 2.0**(self.sl_x_sc.val - 1), 1) -
                self.sl_x_sh.val,
                np.round(self.x_max_span * 2.0**(self.sl_x_sc.val - 1), 1) -
                self.sl_x_sh.val)
            self.ax1.set_xticks(
                np.linspace(
                    -np.round(self.x_max_span * 2.0**(self.sl_x_sc.val - 1), 1)
                    - self.sl_x_sh.val,
                    np.round(self.x_max_span * 2.0**(self.sl_x_sc.val - 1),
                             1) - self.sl_x_sh.val,
                    11,
                    endpoint=True))

            self.xcur1.line.set_xdata([
                xcur1pos * (self.ax1.get_xlim()[1] - self.ax1.get_xlim()[0]) +
                self.ax1.get_xlim()[0],
                xcur1pos * (self.ax1.get_xlim()[1] - self.ax1.get_xlim()[0]) +
                self.ax1.get_xlim()[0]
            ])
            self.xcur2.line.set_xdata([
                xcur2pos * (self.ax1.get_xlim()[1] - self.ax1.get_xlim()[0]) +
                self.ax1.get_xlim()[0],
                xcur2pos * (self.ax1.get_xlim()[1] - self.ax1.get_xlim()[0]) +
                self.ax1.get_xlim()[0]
            ])

            self.t_x.set_text(
                str(np.round(self.x_max_span *
                             (2.0**self.sl_x_sc.val) / 10, 1)) + ' ms')

        self.sl_x_sc.on_changed(scale_x)

        # creating X-shift slider
        self.ax_sl_x_sh = self.fig.add_subplot(self.gs[62:65, 66:97])
        self.ax_sl_x_sh.set_title('X-shift', {'fontsize': 10})
        self.sl_x_sh = wdgt.Slider(self.ax_sl_x_sh,
                                   '',
                                   -np.round(self.x_max_span / 2, 1),
                                   np.round(self.x_max_span / 2, 1),
                                   0.0,
                                   facecolor='0.95')
        self.sl_x_sh.valtext.set_visible(False)

        # making X-shift slider work
        def shift_x(event):
            xcur1pos = (self.xcur1.line.get_xdata()[0] -
                        self.ax1.get_xlim()[0])
            xcur2pos = (self.xcur2.line.get_xdata()[0] -
                        self.ax1.get_xlim()[0])

            self.ax1.set_xlim(
                -np.round(self.x_max_span * 2.0**(self.sl_x_sc.val - 1), 1) -
                self.sl_x_sh.val,
                np.round(self.x_max_span * 2.0**(self.sl_x_sc.val - 1), 1) -
                self.sl_x_sh.val)

            self.ax1.set_xticks(
                np.linspace(self.ax1.get_xlim()[0],
                            self.ax1.get_xlim()[1],
                            11,
                            endpoint=True))

            self.xcur1.line.set_xdata([
                xcur1pos + self.ax1.get_xlim()[0],
                xcur1pos + self.ax1.get_xlim()[0]
            ])
            self.xcur2.line.set_xdata([
                xcur2pos + self.ax1.get_xlim()[0],
                xcur2pos + self.ax1.get_xlim()[0]
            ])

        self.sl_x_sh.on_changed(shift_x)

        # creating on/off button for channel 1
        self.ax_b_on_off_1 = self.fig.add_subplot(self.gs[47:50, 96:99])
        self.b_on_off_1 = wdgt.Button(self.ax_b_on_off_1, '1', None, '#f4bb32',
                                      '#efc35b')
        self.b_on_off_1.label.set_color('0')

        # making on/off button for channel 1 change color on click
        def button_change_1(event):
            if self.b_on_off_1.color == '#f4bb32':
                self.b_on_off_1.color = '0.85'
                self.line1.set_linestyle('')
                self.line_fft_1.set_linestyle('')
            else:
                self.b_on_off_1.color = '#f4bb32'
                self.line1.set_linestyle('-')
                if self.b_on_off_s.color == '0.95':
                    self.line_fft_1.set_linestyle('-')

        self.b_on_off_1.on_clicked(button_change_1)

        # creating Y-scale slider for channel 1
        self.ax_sl_y_sc_1 = self.fig.add_subplot(self.gs[17:40, 94:97])
        self.ax_sl_y_sc_1.set_title('Y-scale', {'fontsize': 10})
        self.sl_y_sc_1 = wdgt.Slider(self.ax_sl_y_sc_1,
                                     '',
                                     -2,
                                     2,
                                     0,
                                     orientation='vertical',
                                     valstep=0.5,
                                     facecolor='#f4bb32')
        self.sl_y_sc_1.valtext.set_visible(False)

        # making Y-scale slider for channel 1 affect scale box
        def scale_1(event):
            self.t_y_ch_1.set_text(
                str(np.round(0.25 / (2**self.sl_y_sc_1.val), 3)))
            if self.data1 is not None:
                self.line1.set_ydata((self.data1 * (2**self.sl_y_sc_1.val)) +
                                     self.sl_y_sh_1.val)

        self.sl_y_sc_1.on_changed(scale_1)

        # creating Y-shift slider for channel 1
        self.ax_sl_y_sh_1 = self.fig.add_subplot(self.gs[5:44, 102:105])
        self.ax_sl_y_sh_1.set_title('Y-shift', {'fontsize': 10})
        self.sl_y_sh_1 = wdgt.Slider(self.ax_sl_y_sh_1,
                                     '',
                                     -1.0,
                                     1.0,
                                     0.0,
                                     orientation='vertical',
                                     facecolor='#f4bb32')
        self.sl_y_sh_1.valtext.set_visible(False)

        # making Y-shift slider for channel 1 move trigger
        # self.prev1 = 0

        # def shift_1(event):
        #     if self.b_on_off_tr.color == '0.95' and self.r_b.value_selected == 'Channel 1':
        #         if self.sl_tr.val + self.sl_y_sh_1.val - self.prev1 > 1:
        #             self.sl_tr.set_val(1)
        #         elif self.sl_tr.val + self.sl_y_sh_1.val - self.prev1 < -1:
        #             self.sl_tr.set_val(-1)
        #         else:
        #             self.sl_tr.set_val(self.sl_tr.val + self.sl_y_sh_1.val - self.prev1)

        #     self.prev1 = self.sl_y_sh_1.val

        # self.sl_y_sh_1.on_changed(shift_1)

        # creating on/off button for channel 2
        self.ax_b_on_off_2 = self.fig.add_subplot(self.gs[47:50, 114:117])
        self.b_on_off_2 = wdgt.Button(self.ax_b_on_off_2, '2', None, '0.85',
                                      '#9fd1ac')
        self.b_on_off_2.label.set_color('0')

        # making on/off button for channel 2 change color on click
        def button_change_2(event):
            if self.b_on_off_2.color == '#81b78f':
                self.b_on_off_2.color = '0.85'
                self.line2.set_linestyle('')
                self.line_fft_2.set_linestyle('')
            else:
                self.b_on_off_2.color = '#81b78f'
                self.line2.set_linestyle('-')
                if self.b_on_off_s.color == '0.95':
                    self.line_fft_2.set_linestyle('-')

        self.b_on_off_2.on_clicked(button_change_2)

        # creating Y-scale slider for channel 2
        self.ax_sl_y_sc_2 = self.fig.add_subplot(self.gs[17:40, 112:115])
        self.ax_sl_y_sc_2.set_title('Y-scale', {'fontsize': 10})
        self.sl_y_sc_2 = wdgt.Slider(self.ax_sl_y_sc_2,
                                     '',
                                     -2,
                                     2,
                                     0,
                                     orientation='vertical',
                                     valstep=0.5,
                                     facecolor='#81b78f')
        self.sl_y_sc_2.valtext.set_visible(False)

        # making Y-scale slider for channel 2 affect scale box
        def scale_2(event):
            self.t_y_ch_2.set_text(
                str(np.round(0.25 / (2**self.sl_y_sc_2.val), 3)))
            if self.data2 is not None:
                self.line2.set_ydata((self.data2 * (2**self.sl_y_sc_2.val)) +
                                     self.sl_y_sh_2.val)

        self.sl_y_sc_2.on_changed(scale_2)

        # creating Y-shift slider for channel 2
        self.ax_sl_y_sh_2 = self.fig.add_subplot(self.gs[5:44, 120:123])
        self.ax_sl_y_sh_2.set_title('Y-shift', {'fontsize': 10})
        self.sl_y_sh_2 = wdgt.Slider(self.ax_sl_y_sh_2,
                                     '',
                                     -1.0,
                                     1.0,
                                     0.0,
                                     orientation='vertical',
                                     facecolor='#81b78f')
        self.sl_y_sh_2.valtext.set_visible(False)

        # making Y-shift slider for channel 2 move trigger
        self.prev2 = 0

        def shift_2(event):
            if self.b_on_off_tr.color == '0.95' and self.r_b.value_selected == 'Channel 2':
                if self.sl_tr.val + self.sl_y_sh_2.val - self.prev2 > 1:
                    self.sl_tr.set_val(1)
                elif self.sl_tr.val + self.sl_y_sh_2.val - self.prev2 < -1:
                    self.sl_tr.set_val(-1)
                else:
                    self.sl_tr.set_val(self.sl_tr.val + self.sl_y_sh_2.val -
                                       self.prev2)

            self.prev2 = self.sl_y_sh_2.val

        self.sl_y_sh_2.on_changed(shift_2)

        # creating on/off button for channel 3
        self.ax_b_on_off_3 = self.fig.add_subplot(self.gs[47:50, 132:135])
        self.b_on_off_3 = wdgt.Button(self.ax_b_on_off_3, '3', None, '0.85',
                                      '#89a8db')
        self.b_on_off_3.label.set_color('0')

        # making on/off button for channel 3 change color on click
        def button_change_3(event):
            if self.b_on_off_3.color == '#6590d8':
                self.b_on_off_3.color = '0.85'
                self.line3.set_linestyle('')
                self.line_fft_3.set_linestyle('')
            else:
                self.b_on_off_3.color = '#6590d8'
                self.line3.set_linestyle('-')
                if self.b_on_off_s.color == '0.95':
                    self.line_fft_3.set_linestyle('-')

        self.b_on_off_3.on_clicked(button_change_3)

        # creating Y-scale slider for channel 3
        self.ax_sl_y_sc_3 = self.fig.add_subplot(self.gs[17:40, 130:133])
        self.ax_sl_y_sc_3.set_title('Y-scale', {'fontsize': 10})
        self.sl_y_sc_3 = wdgt.Slider(self.ax_sl_y_sc_3,
                                     '',
                                     -2,
                                     2,
                                     0,
                                     orientation='vertical',
                                     valstep=0.5,
                                     facecolor='#6590d8')
        self.sl_y_sc_3.valtext.set_visible(False)

        # making Y-scale slider for channel 3 affect scale box
        def scale_3(event):
            self.t_y_ch_3.set_text(
                str(np.round(0.25 / (2**self.sl_y_sc_3.val), 3)))
            if self.data3 is not None:
                self.line3.set_ydata((self.data3 * (2**self.sl_y_sc_3.val)) +
                                     self.sl_y_sh_3.val)

        self.sl_y_sc_3.on_changed(scale_3)

        # creating Y-shift slider for channel 3
        self.ax_sl_y_sh_3 = self.fig.add_subplot(self.gs[5:44, 138:141])
        self.ax_sl_y_sh_3.set_title('Y-shift', {'fontsize': 10})
        self.sl_y_sh_3 = wdgt.Slider(self.ax_sl_y_sh_3,
                                     '',
                                     -1.0,
                                     1.0,
                                     0.0,
                                     orientation='vertical',
                                     facecolor='#6590d8')
        self.sl_y_sh_3.valtext.set_visible(False)

        # making Y-shift slider for channel 3 move trigger
        self.prev3 = 0

        def shift_3(event):
            if self.b_on_off_tr.color == '0.95' and self.r_b.value_selected == 'Channel 3':
                if self.sl_tr.val + self.sl_y_sh_3.val - self.prev3 > 3:
                    self.sl_tr.set_val(1)
                elif self.sl_tr.val + self.sl_y_sh_3.val - self.prev3 < -1:
                    self.sl_tr.set_val(-1)
                else:
                    self.sl_tr.set_val(self.sl_tr.val + self.sl_y_sh_3.val -
                                       self.prev3)

            self.prev3 = self.sl_y_sh_3.val

        self.sl_y_sh_3.on_changed(shift_3)

        # creating on/off button for channel 4
        self.ax_b_on_off_4 = self.fig.add_subplot(self.gs[47:50, 150:153])
        self.b_on_off_4 = wdgt.Button(self.ax_b_on_off_4, '4', None, '0.85',
                                      '#f5b8d8')
        self.b_on_off_4.label.set_color('0')

        # making on/off button for channel 4 change color on click
        def button_change_4(event):
            if self.b_on_off_4.color == '#de8fb9':
                self.b_on_off_4.color = '0.85'
                self.line4.set_linestyle('')
                self.line_fft_4.set_linestyle('')
            else:
                self.b_on_off_4.color = '#de8fb9'
                self.line4.set_linestyle('-')
                if self.b_on_off_s.color == '0.95':
                    self.line_fft_4.set_linestyle('-')

        self.b_on_off_4.on_clicked(button_change_4)

        # creating Y-scale slider for channel 4
        self.ax_sl_y_sc_4 = self.fig.add_subplot(self.gs[17:40, 148:151])
        self.ax_sl_y_sc_4.set_title('Y-scale', {'fontsize': 10})
        self.sl_y_sc_4 = wdgt.Slider(self.ax_sl_y_sc_4,
                                     '',
                                     -2,
                                     2,
                                     0,
                                     orientation='vertical',
                                     valstep=0.5,
                                     facecolor='#de8fb9')
        self.sl_y_sc_4.valtext.set_visible(False)

        # making Y-scale slider for channel 4 affect scale box
        def scale_4(event):
            self.t_y_ch_4.set_text(
                str(np.round(0.25 / (2**self.sl_y_sc_4.val), 3)))
            if self.data4 is not None:
                self.line4.set_ydata((self.data4 * (2**self.sl_y_sc_4.val)) +
                                     self.sl_y_sh_4.val)

        self.sl_y_sc_4.on_changed(scale_4)

        # creating Y-shift slider for channel 4
        self.ax_sl_y_sh_4 = self.fig.add_subplot(self.gs[5:44, 156:159])
        self.ax_sl_y_sh_4.set_title('Y-shift', {'fontsize': 10})
        self.sl_y_sh_4 = wdgt.Slider(self.ax_sl_y_sh_4,
                                     '',
                                     -1.0,
                                     1.0,
                                     0.0,
                                     orientation='vertical',
                                     facecolor='#de8fb9')
        self.sl_y_sh_4.valtext.set_visible(False)

        # making Y-shift slider for channel 4 move trigger
        self.prev4 = 0

        def shift_4(event):
            if self.b_on_off_tr.color == '0.95' and self.r_b.value_selected == 'Channel 4':
                if self.sl_tr.val + self.sl_y_sh_4.val - self.prev4 > 1:
                    self.sl_tr.set_val(1)
                elif self.sl_tr.val + self.sl_y_sh_4.val - self.prev4 < -1:
                    self.sl_tr.set_val(-1)
                else:
                    self.sl_tr.set_val(self.sl_tr.val + self.sl_y_sh_4.val -
                                       self.prev4)

            self.prev4 = self.sl_y_sh_4.val

        self.sl_y_sh_4.on_changed(shift_4)

        # creating on/off button spectrum
        self.ax_b_on_off_s = self.fig.add_subplot(self.gs[70:74, 66:77])
        self.b_on_off_s = wdgt.Button(self.ax_b_on_off_s, 'Spectrum', None,
                                      '0.85', 'w')
        self.b_on_off_s.label.set_color('0')

        # making on/off button for spectrum change color on click
        def button_change_s(event):
            if self.b_on_off_s.color == '0.95':
                self.b_on_off_s.color = '0.85'
                self.line_fft_1.set_linestyle('')
                self.line_fft_2.set_linestyle('')
            else:
                self.b_on_off_s.color = '0.95'
                if self.b_on_off_1.color == '#f4bb32':
                    self.line_fft_1.set_linestyle('-')
                if self.b_on_off_2.color == '#81b78f':
                    self.line_fft_2.set_linestyle('-')

        self.b_on_off_s.on_clicked(button_change_s)

        # creating lin/log button for spectrum

        # self.ax_b_lin_log = self.fig.add_subplot(self.gs[70:74, 82:93])
        # self.b_lin_log = wdgt.Button(self.ax_b_lin_log, 'Lin/Log', None, '0.85', 'w')
        # self.b_lin_log.label.set_color('0')

        # self.flag2 = False

        # making lin/log button for spectrum work
        # def lin_log_switch(event):
        #     if self.flag2:
        #         self.flag2 = False

        #         self.ax2.set_ylim(0, 0.2)
        #         self.ax2.set_yticks(np.linspace(0, 0.2, 9, endpoint=True))
        #         self.ax2.set_yscale('linear')
        #         self.ax2.set_yticklabels([])
        #     else:
        #         self.flag2 = True

        #         self.ax2.set_ylim(0, 1)
        #         self.ax2.set_yticks(np.linspace(0, 1, 9, endpoint=True))
        #         self.ax2.set_yscale('log')
        #         # self.ax2.set_yticklabels([])
        #         self.ax2.tick_params(axis='y', length=0)
        #         print(self.ax2.get_yticks())
        #         print(self.ax2.get_ylim())

        # self.b_lin_log.on_clicked(lin_log_switch)

        # creating range slider for spectrum
        self.ax_r_sl = self.fig.add_subplot(self.gs[79:82, 66:97])
        self.ax_r_sl.set_title('Frequency range, Hz', fontsize=10)
        self.r_sl = wdgt.RangeSlider(self.ax_r_sl,
                                     '',
                                     0.0,
                                     22050.0,
                                     facecolor='0.95')
        self.r_sl.set_val([0.0, 22050.0])

        # making range slider for spectrum work
        def change_size(event):
            xfftcur1pos = (
                (self.xfftcur1.line.get_xdata()[0] - self.ax2.get_xlim()[0]) /
                (self.ax2.get_xlim()[1] - self.ax2.get_xlim()[0]))
            xfftcur2pos = (
                (self.xfftcur2.line.get_xdata()[0] - self.ax2.get_xlim()[0]) /
                (self.ax2.get_xlim()[1] - self.ax2.get_xlim()[0]))

            self.ax2.set_xlim(self.r_sl.val[0], self.r_sl.val[1])
            self.ax2.set_xticks(
                np.linspace(self.r_sl.val[0],
                            self.r_sl.val[1],
                            11,
                            endpoint=True))

            self.xfftcur1.line.set_xdata([
                xfftcur1pos *
                (self.ax2.get_xlim()[1] - self.ax2.get_xlim()[0]) +
                self.ax2.get_xlim()[0], xfftcur1pos *
                (self.ax2.get_xlim()[1] - self.ax2.get_xlim()[0]) +
                self.ax2.get_xlim()[0]
            ])
            self.xfftcur2.line.set_xdata([
                xfftcur2pos *
                (self.ax2.get_xlim()[1] - self.ax2.get_xlim()[0]) +
                self.ax2.get_xlim()[0], xfftcur2pos *
                (self.ax2.get_xlim()[1] - self.ax2.get_xlim()[0]) +
                self.ax2.get_xlim()[0]
            ])

        self.r_sl.on_changed(change_size)

        # creating on/off button for waveform cursors
        self.ax_b_on_off_cur = self.fig.add_subplot(self.gs[54:58, 125:136])
        self.b_on_off_cur = wdgt.Button(self.ax_b_on_off_cur,
                                        'Waveform \ncursors', None, '0.85',
                                        '0.95')
        self.b_on_off_cur.label.set_color('0')

        # making on/off button for waveform cursors change color on click
        def button_change_cur(event):
            if self.b_on_off_cur.color == '#4cd147':
                self.b_on_off_cur.color = '0.85'
                self.b_on_off_cur.hovercolor = '0.95'
                self.xcur1.line.set_linestyle('')
                self.xcur2.line.set_linestyle('')
                self.ycur1.line.set_linestyle('')
                self.ycur2.line.set_linestyle('')
            else:
                self.b_on_off_cur.color = '#4cd147'
                self.b_on_off_cur.hovercolor = '#2fff27'
                self.xcur1.line.set_linestyle('--')
                self.xcur2.line.set_linestyle('--')
                self.ycur1.line.set_linestyle('--')
                self.ycur2.line.set_linestyle('--')

        self.b_on_off_cur.on_clicked(button_change_cur)

        # creating on/off button for spectrum cursors
        self.ax_b_on_off_fft_cur = self.fig.add_subplot(self.gs[63:67,
                                                                125:136])
        self.b_on_off_fft_cur = wdgt.Button(self.ax_b_on_off_fft_cur,
                                            'Spectrum \ncursors', None, '0.85',
                                            '0.95')
        self.b_on_off_fft_cur.label.set_color('0')

        # making on/off button for cursors change color on click
        def button_change_fft_cur(event):
            if self.b_on_off_fft_cur.color == '#4cd147':
                self.b_on_off_fft_cur.color = '0.85'
                self.b_on_off_fft_cur.hovercolor = '0.95'
                self.xfftcur1.line.set_linestyle('')
                self.xfftcur2.line.set_linestyle('')
                self.yfftcur1.line.set_linestyle('')
                self.yfftcur2.line.set_linestyle('')
            else:
                self.b_on_off_fft_cur.color = '#4cd147'
                self.b_on_off_fft_cur.hovercolor = '#2fff27'
                self.xfftcur1.line.set_linestyle('--')
                self.xfftcur2.line.set_linestyle('--')
                self.yfftcur1.line.set_linestyle('--')
                self.yfftcur2.line.set_linestyle('--')

        self.b_on_off_fft_cur.on_clicked(button_change_fft_cur)

        # creating reset button
        self.ax_b_reset = self.fig.add_subplot(self.gs[72:76, 133:144])
        self.b_reset = wdgt.Button(self.ax_b_reset, 'Reset', None, '#f96b6b',
                                   '#fa9494')

        # making reset button reset all sliders' and cursors' positions
        def reset(event):
            self.sl_x_sc.reset()
            self.sl_x_sh.reset()
            self.sl_y_sc_1.reset()
            self.sl_y_sh_1.reset()
            self.sl_y_sc_2.reset()
            self.sl_y_sh_2.reset()
            self.sl_y_sc_3.reset()
            self.sl_y_sh_3.reset()
            self.sl_y_sc_4.reset()
            self.sl_y_sh_4.reset()
            self.sl_tr.reset()
            self.r_sl.set_val([0.0, 22050.0])
            self.r_b.set_active(0)

            self.xcur1.line.set_xdata([
                -np.round(self.x_max_span * 2.0**(self.sl_x_sc.val - 2), 1),
                -np.round(self.x_max_span * 2.0**(self.sl_x_sc.val - 2), 1)
            ])
            self.xcur2.line.set_xdata([
                np.round(self.x_max_span * 2.0**(self.sl_x_sc.val - 2), 1),
                np.round(self.x_max_span * 2.0**(self.sl_x_sc.val - 2), 1)
            ])
            self.ycur1.line.set_ydata([-0.5, -0.5])
            self.ycur2.line.set_ydata([0.5, 0.5])

            xfftcur1pos = self.ax2.get_xlim()[0] + (self.ax2.get_xlim()[1] -
                                                    self.ax2.get_xlim()[0]) / 4
            xfftcur2pos = self.ax2.get_xlim()[1] - (self.ax2.get_xlim()[1] -
                                                    self.ax2.get_xlim()[0]) / 4
            yfftcur1pos = self.ax2.get_ylim()[0] + (self.ax2.get_ylim()[1] -
                                                    self.ax2.get_ylim()[0]) / 4
            yfftcur2pos = self.ax2.get_ylim()[1] - (self.ax2.get_ylim()[1] -
                                                    self.ax2.get_ylim()[0]) / 4
            self.xfftcur1.line.set_xdata([xfftcur1pos, xfftcur1pos])
            self.xfftcur2.line.set_xdata([xfftcur2pos, xfftcur2pos])
            self.yfftcur1.line.set_ydata([yfftcur1pos, yfftcur1pos])
            self.yfftcur2.line.set_ydata([yfftcur2pos, yfftcur2pos])

        self.b_reset.on_clicked(reset)

        # creating single frame button
        self.ax_b_single = self.fig.add_subplot(self.gs[54:58, 141:152])
        self.b_single = wdgt.Button(self.ax_b_single, 'Single', None, '0.85',
                                    'w')
        self.b_single.label.set_color('0')

        self.flag1 = False

        # making single frame button work
        def single(event):
            if self.b_run_stop.color == '#4cd147':
                self.b_run_stop.color = '0.85'
                self.b_run_stop.hovercolor = '0.95'
            else:
                self.b_run_stop.color = '#4cd147'
                self.b_run_stop.hovercolor = '#2fff27'
                self.flag1 = True

        self.b_single.on_clicked(single)

        # creating run/stop button
        self.ax_b_run_stop = self.fig.add_subplot(self.gs[63:67, 141:152])
        self.b_run_stop = wdgt.Button(self.ax_b_run_stop, 'Run/Stop', None,
                                      '0.85', 'w')
        self.b_run_stop.label.set_color('0')

        # making run/stop button work
        def run_stop(event):
            if self.b_run_stop.color == '#4cd147':
                self.b_run_stop.color = '0.85'
                self.b_run_stop.hovercolor = '0.95'
            else:
                self.b_run_stop.color = '#4cd147'
                self.b_run_stop.hovercolor = '#2fff27'

        self.b_run_stop.on_clicked(run_stop)

        # creating trigger on/off button
        self.ax_b_on_off_tr = self.fig.add_subplot(self.gs[47:51, 66:77])
        self.b_on_off_tr = wdgt.Button(self.ax_b_on_off_tr, 'Trigger', None,
                                       '0.85', 'w')
        self.b_on_off_tr.label.set_color('0')

        # making trigger on/off button work
        def trigger_on_off(event):
            if self.b_on_off_tr.color == '0.95':
                self.b_on_off_tr.color = '0.85'
                self.trigger.set_linestyle('')
            else:
                self.b_on_off_tr.color = '0.95'
                self.trigger.set_linestyle('-')

        self.b_on_off_tr.on_clicked(trigger_on_off)

        # creating trigger position slider
        self.ax_sl_tr = self.fig.add_subplot(self.gs[5:44, 66:69])
        self.ax_sl_tr.set_title('Trigger \nposition', fontsize=10)
        self.sl_tr = wdgt.Slider(self.ax_sl_tr,
                                 '',
                                 -1,
                                 1,
                                 0,
                                 orientation='vertical',
                                 facecolor='0.95')
        self.sl_tr.valtext.set_visible(False)

        # making trigger position slider work
        def trigger_move(event):
            self.trigger.set_ydata([self.sl_tr.val, self.sl_tr.val])

        self.sl_tr.on_changed(trigger_move)

        # creating radio buttons for channel selection
        self.ax_r_b = self.fig.add_subplot(self.gs[17:40, 72:89])
        self.ax_r_b.set_title('Channel \nselection', fontsize=10)
        self.r_b = wdgt.RadioButtons(
            self.ax_r_b, ('Channel 1', 'Channel 2', 'Channel 3', 'Channel 4'),
            0, '#4cd147')

        # creating starter plots for all channels
        self.line1, = self.ax1.plot(
            np.linspace(-np.round(self.x_max_span / 2, 1),
                        np.round(self.x_max_span / 2, 1), blocksize),
            np.zeros(blocksize), '#f4bb32')
        self.line2, = self.ax1.plot(
            np.linspace(-np.round(self.x_max_span / 2, 1),
                        np.round(self.x_max_span / 2, 1), blocksize),
            np.zeros(blocksize), '#81b78f')
        self.line3, = self.ax1.plot(
            np.linspace(-np.round(self.x_max_span / 2, 1),
                        np.round(self.x_max_span / 2, 1), blocksize),
            np.zeros(blocksize), '#6590d8')
        self.line4, = self.ax1.plot(
            np.linspace(-np.round(self.x_max_span / 2, 1),
                        np.round(self.x_max_span / 2, 1), blocksize),
            np.zeros(blocksize), '#de8fb9')
        self.line2.set_linestyle('')
        self.line3.set_linestyle('')
        self.line4.set_linestyle('')

        self.line_fft_1, = self.ax2.plot(np.linspace(0, 22050, blocksize),
                                         np.zeros(blocksize), '#f4bb32')
        self.line_fft_2, = self.ax2.plot(np.linspace(0, 22050, blocksize),
                                         np.zeros(blocksize), '#81b78f')
        self.line_fft_3, = self.ax2.plot(np.linspace(0, 22050, blocksize),
                                         np.zeros(blocksize), '#6590d8')
        self.line_fft_4, = self.ax2.plot(np.linspace(0, 22050, blocksize),
                                         np.zeros(blocksize), '#de8fb9')
        self.line_fft_1.set_linestyle('')
        self.line_fft_2.set_linestyle('')
        self.line_fft_3.set_linestyle('')
        self.line_fft_4.set_linestyle('')

        self.trigger = self.ax1.axhline(0, c='0.95', ls='', lw=0.5)

        self.xcur1 = Cc.Cursor(
            self.ax1.axvline(-self.x_max_span / 16, c='r', ls='',
                             pickradius=2), self.b_on_off_cur)
        self.xcur2 = Cc.Cursor(
            self.ax1.axvline(self.x_max_span / 16, c='r', ls='', pickradius=2),
            self.b_on_off_cur)
        self.ycur1 = Cc.Cursor(
            self.ax1.axhline(-0.5, c='r', ls='', pickradius=2),
            self.b_on_off_cur)
        self.ycur2 = Cc.Cursor(
            self.ax1.axhline(0.5, c='r', ls='', pickradius=2),
            self.b_on_off_cur)

        self.xfftcur1 = Cc.Cursor(
            self.ax2.axvline(
                self.ax2.get_xlim()[0] +
                (self.ax2.get_xlim()[1] - self.ax2.get_xlim()[0]) / 4,
                c='r',
                ls='',
                pickradius=2), self.b_on_off_fft_cur)
        self.xfftcur2 = Cc.Cursor(
            self.ax2.axvline(
                self.ax2.get_xlim()[1] -
                (self.ax2.get_xlim()[1] - self.ax2.get_xlim()[0]) / 4,
                c='r',
                ls='',
                pickradius=2), self.b_on_off_fft_cur)
        self.yfftcur1 = Cc.Cursor(
            self.ax2.axhline(
                self.ax2.get_ylim()[0] +
                (self.ax2.get_ylim()[1] - self.ax2.get_ylim()[0]) / 4,
                c='r',
                ls='',
                pickradius=2), self.b_on_off_fft_cur)
        self.yfftcur2 = Cc.Cursor(
            self.ax2.axhline(
                self.ax2.get_ylim()[1] -
                (self.ax2.get_ylim()[1] - self.ax2.get_ylim()[0]) / 4,
                c='r',
                ls='',
                pickradius=2), self.b_on_off_fft_cur)

        self.data1 = None
        self.data2 = None
        self.data3 = None
        self.data4 = None

        # creating blitting manager
        self.bm = BMc.BlitManager(self.fig.canvas, [
            self.line1, self.line2, self.line3, self.line4, self.line_fft_1,
            self.line_fft_2, self.line_fft_3, self.line_fft_4, self.trigger,
            self.xcur1.line, self.xcur2.line, self.ycur1.line, self.ycur2.line,
            self.xfftcur1.line, self.xfftcur2.line, self.yfftcur1.line,
            self.yfftcur2.line, self.t_1_l, self.t_1_r, self.t_2_l, self.t_2_r
        ])

        # making plot visible
        plt.show(block=False)
        plt.pause(.1)
Beispiel #25
0
    def __init__(self,
                 inst,
                 controls=True,
                 xlim=None,
                 ylim=None,
                 zlim=None,
                 focus=None,
                 style='dark_background',
                 **kwargs):
        plt.style.use(style)

        self.inst = inst
        self.controls = controls
        self._populate_offset_dict()

        self.fig = plt.figure(**kwargs)
        self.ax_zx = self.fig.add_subplot(2, 2, 1)
        self.ax_zy = self.fig.add_subplot(2, 2, 2)
        self.ax_xy = self.fig.add_subplot(2, 2, 3)
        self.ax_or = self.fig.add_subplot(2, 2, 4, projection='3d')
        self._draw_labels()

        self.offset = [0, 0, 0]

        if self.controls:
            plt.subplots_adjust(left=0.05, right=0.7)

            rectprops = dict(facecolor='blue', alpha=0.5)
            self.xlim_span_ax = plt.axes([0.72, 0.3, 0.25, 0.03])
            self.xlim_span_ax.set_yticks([])
            self.xlim_span = wid.SpanSelector(self.xlim_span_ax,
                                              self._inst_xlim_change,
                                              'horizontal',
                                              rectprops=rectprops)
            xlim_span_label = self._create_text("xlim",
                                                [0.72, 0.25, 0.25, 0.03])

            self.ylim_span_ax = plt.axes([0.72, 0.2, 0.25, 0.03])
            self.ylim_span_ax.set_yticks([])
            self.ylim_span = wid.SpanSelector(self.ylim_span_ax,
                                              self._inst_ylim_change,
                                              'horizontal',
                                              rectprops=rectprops)
            ylim_span_label = self._create_text("ylim",
                                                [0.72, 0.15, 0.25, 0.03])

            self.zlim_span_ax = plt.axes([0.72, 0.1, 0.25, 0.03])
            self.zlim_span_ax.set_yticks([])
            self.zlim_span = wid.SpanSelector(self.zlim_span_ax,
                                              self._inst_zlim_change,
                                              'horizontal',
                                              rectprops=rectprops)
            zlim_span_label = self._create_text("zlim",
                                                [0.72, 0.05, 0.25, 0.03])

            self.comp_focus_textbox_ax = plt.axes([0.72, 0.35, 0.25, 0.63],
                                                  facecolor='grey')
            self.comp_focus_buttons = wid.RadioButtons(
                self.comp_focus_textbox_ax,
                tuple(kr.comp_name for kr in self.inst.kernel_refs))
            self.comp_focus_buttons.on_clicked(self._inst_comp_focus)
            #self.comp_focus_textbox = wid.TextBox(self.comp_focus_textbox_ax, "", color='.1', hovercolor='.15')
            #self.comp_focus_textbox.on_text_change(self._inst_comp_focus)
            #comp_focus_label = self._create_text("Focussed component", [0.72, 0.45, 0.25, 0.03]

        if focus:
            self._inst_comp_focus(focus)

        if xlim:
            self._inst_xlim_change(xlim[0], xlim[1])

        if ylim:
            self._inst_ylim_change(ylim[0], ylim[1])

        if zlim:
            self._inst_zlim_change(zlim[0], zlim[1])
            targetNameList.append('No pillar')

fig = plt.figure(figsize=(6, 3))
fig.canvas.set_window_title('Data Labelling Software (Mirsaidov Lab)')
fig.canvas.mpl_connect('key_press_event', press)
axImage = fig.add_axes([0.05, 0.1, 0.4, 0.8])
axRadio = fig.add_axes([0.55, 0.3, 0.40, 0.6])
axSubmitButton = fig.add_axes([0.55, 0.1, 0.1, 0.1])
axSkipButton = fig.add_axes([0.7, 0.1, 0.1, 0.1])
axExitButton = fig.add_axes([0.85, 0.1, 0.1, 0.1])

axImage.imshow(gImgStack[:, :, 0], cmap='Greys_r')
if (method == 'useClassificationResult'):
    axImage.set_title(targetNameList[0])
    axImage.set_xlabel('Frame %d/%d' % (counter + 1, numFrames))
elif (method == 'makeNewDataset'):
    axImage.set_title("C = %d, NC = %d, NP = %d" %
                      (collapseCounter, notcollapseCounter, nopillarCounter))
axImage.set_xticks([]), axImage.set_yticks([])
radio = widgets.RadioButtons(axRadio,
                             ('Collapse', 'Not collapse', 'No pillar'))
submit = widgets.Button(axSubmitButton, 'Submit')
skip = widgets.Button(axSkipButton, 'Skip')
exitSoftware = widgets.Button(axExitButton, 'Exit')
plt.show()

submit.on_clicked(updateLabel)
skip.on_clicked(loadNewImage)
exitSoftware.on_clicked(quitProgram)
############################################################
def kwarg_to_mpl_widget(
    fig,
    heights,
    widget_y,
    key,
    val,
    update,
    slider_format_string,
    play_button=False,
    play_button_pos="right",
):
    """
    heights : tuple
        with slider_height, radio_height, gap_height
    returns
    -------
    init_val
    widget
    cb
        the callback id
    new_y
        The widget_y to use for the next pass
    """
    slider_height, radio_height, gap_height = heights

    # widget_y = 0.05
    slider_ax = []
    sliders = []
    radio_ax = []
    radio_buttons = []
    cbs = []
    if isinstance(val, set):
        if len(val) == 1:
            val = val.pop()
            if isinstance(val, tuple):
                pass
            else:
                return val, None, None, widget_y
        else:
            val = list(val)

        n = len(val)
        longest_len = max(list(map(lambda x: len(list(x)), map(str, val))))
        # should probably use something based on fontsize rather that .015
        width = max(0.15, 0.015 * longest_len)
        radio_ax = fig.add_axes(
            [0.2, 0.9 - widget_y - radio_height * n, width, radio_height * n])
        widget_y += radio_height * n + gap_height
        radio_buttons = mwidgets.RadioButtons(radio_ax, val, active=0)
        cb = radio_buttons.on_clicked(
            partial(changeify_radio, labels=val, update=update))
        return val[0], radio_buttons, cb, widget_y
    elif isinstance(val, mwidgets.AxesWidget):
        val, widget, cb = process_mpl_widget(val, update)
        return val, widget, cb, widget_y
    else:
        slider = None
        update_fxn = None
        if isinstance(val, tuple) and val[0] in ["r", "range", "rang", "rage"]:
            if isinstance(val[1], (np.ndarray, list)):
                vals = val[1]
            else:
                vals = np.linspace(*val[1:])
            slider_ax = fig.add_axes(
                [0.2, 0.9 - widget_y - gap_height, 0.65, slider_height])
            slider = create_mpl_range_selection_slider(slider_ax, key, vals,
                                                       slider_format_string)
            cb = slider.on_changed(
                partial(changeify, update=partial(update, values=vals)))
            widget_y += slider_height + gap_height
            return vals[[0, -1]], slider, cb, widget_y

        if isinstance(val, tuple):
            if len(val) == 2:
                min_ = float(val[0])
                max_ = float(val[1])
                slider_ax = fig.add_axes(
                    [0.2, 0.9 - widget_y - gap_height, 0.65, slider_height])
                slider = mwidgets.Slider(slider_ax, key, min_, max_)

                def update_text(val):
                    slider.valtext.set_text(slider_format_string.format(val))

                # make sure the initial value also gets formatted
                update_text(slider.valinit)
                slider.on_changed(update_text)
                cb = slider.on_changed(
                    partial(changeify, update=partial(update, values=None)))
                widget_y += slider_height + gap_height
                return min_, slider, cb, widget_y
            elif len(val) == 3:
                # should warn that that doesn't make sense with matplotlib sliders
                min_ = val[0]
                max_ = val[1]
                val = np.linspace(*val)
        val = np.atleast_1d(val)
        if val.ndim > 1:
            raise ValueError(
                f"{key} is {val.ndim}D but can only be 1D or a scalar")
        if len(val) == 1:
            # don't need to create a slider
            return val[0], None, None, widget_y
        else:
            slider_ax = fig.add_axes(
                [0.2, 0.9 - widget_y - gap_height, 0.65, slider_height])
            slider = create_mpl_selection_slider(slider_ax, key, val,
                                                 slider_format_string)
            slider.on_changed(
                partial(changeify, update=partial(update, values=val)))
            widget_y += slider_height + gap_height
            return val[0], slider, None, widget_y
    def __init__(self):

        self.fig = plt.figure(figsize=(18, 9))
        self.ax1 = plt.axes([0.05, 0.8, 0.9, 0.15])
        self.ax2 = plt.axes([0.05, 0.5, 0.9, 0.25])
        self.axpow = plt.axes([0.125, 0.28, 0.05, 0.1])
        self.powerHandle = widgets.RadioButtons(self.axpow, ('On', 'Off'))
        self.axshape = plt.axes([0.2, 0.28, 0.08, 0.12])
        self.shapeHandle = widgets.RadioButtons(self.axshape,
                                                ('Sine', 'Sawtooth', 'Square'))
        self.axpoint = plt.axes([0.1, 0.07, 0.8, 0.05])
        self.pointHandle = widgets.Slider(self.axpoint,
                                          'Number of points',
                                          10,
                                          2000,
                                          valstep=1,
                                          valinit=300)
        self.N = int(self.pointHandle.val)
        self.axfreq = plt.axes([0.1, 0.19, 0.8, 0.05])
        self.freqHandle = widgets.Slider(self.axfreq,
                                         'Frequency (Hz)',
                                         0.5,
                                         100,
                                         valinit=30)
        self.f = self.freqHandle.val
        self.axtime = plt.axes([0.1, 0.13, 0.8, 0.05])
        self.timeHandle = widgets.Slider(self.axtime,
                                         'Time (s)',
                                         1,
                                         10,
                                         valinit=1)
        self.t = self.timeHandle.val
        self.time = np.linspace(0, self.t, self.N)
        self.axphase = plt.axes([0.1, 0.01, 0.8, 0.05])
        self.phaseHandle = widgets.Slider(self.axphase,
                                          'Phase',
                                          0,
                                          2 * np.pi,
                                          valinit=0)
        self.p_shift = self.phaseHandle.val
        self.axnoise = plt.axes([0.4, 0.36, 0.15, 0.05])
        self.noiseHandle = widgets.Slider(self.axnoise,
                                          'Noise',
                                          0,
                                          1,
                                          valinit=0)
        self.deviation = self.noiseHandle.val
        self.noise = np.random.normal(0, self.deviation, self.N)
        self.axleft = plt.axes([0.4, 0.28, 0.15, 0.05])
        self.leftHandle = widgets.Slider(self.axleft,
                                         'Left cut',
                                         0,
                                         1,
                                         valinit=0)
        self.t0 = self.leftHandle.val
        self.axright = plt.axes([0.65, 0.28, 0.15, 0.05])
        self.rightHandle = widgets.Slider(self.axright,
                                          'Right cut',
                                          0,
                                          1,
                                          valinit=self.t)
        self.t1 = self.rightHandle.val
        self.shape = "Sine"
        self.status = "On"
        self.max = 0
        self.max_pos = 0
        self.leftcut = self.ax1.plot([self.t0, self.t0], [-1, 1], 'r--')
        self.rightcut = self.ax1.plot([self.t1, self.t1], [-1, 1], 'r--')
        self.sigsin = np.sin(2 * np.pi * self.f * self.time + self.p_shift)
        self.sigsaw = signal.sawtooth(2 * np.pi * self.f * self.time +
                                      self.p_shift)
        self.sigsq = signal.square(2 * np.pi * self.f * self.time +
                                   self.p_shift)
        self.sig = self.sigsin
        self.Fourier = fft(self.sig)
        self.f_array = np.linspace(1 / self.t,
                                   int(self.N // 2) / self.t, int(self.N // 2))
        self.pow_spec = self.Fourier * np.conj(self.Fourier) / self.N
        self.max = np.where(self.pow_spec == np.amax(self.pow_spec))
        self.max_pos = self.max[0]
        self.f_max = self.f_array[self.max_pos[0]]
        self.f_diff = self.f_max - self.f
        self.f_array_correct = self.f_array - self.f_diff
        self.ax1.set_xlim([0, self.t])
        self.ax2.set_xlim(0, 2 * self.f_array_correct[int(self.max_pos[0])])
        self.sigplot = self.ax1.plot(self.time, self.sig)
        self.fplot = self.ax2.plot(self.f_array_correct,
                                   self.pow_spec[0:int(self.N // 2)])