Exemplo n.º 1
0
    def create_GUI(self) -> Tuple[widgets.VBox, widgets.interactive_output]:
        """Creates the two main components of the GUI: the qubit and plot option
        buttons and the interactive_output that connects the buttons with
        the main qubit plot.

        Returns
        -------
        Tuple[ widgets.VBox, widgets.interactive_output ]

        """
        qubit_choice_hbox = widgets.HBox([
            self.qubit_and_plot_choice_widgets["qubit_buttons"],
            self.qubit_and_plot_choice_widgets["show_qubitinfo_checkbox"],
        ])
        plot_choice_hbox = widgets.HBox(
            [self.qubit_and_plot_choice_widgets["plot_buttons"]])

        qubit_and_plot_choice_widgets = widgets.VBox(
            [qubit_choice_hbox, plot_choice_hbox])

        qubit_and_plot_choice_interactive = widgets.interactive_output(
            self.qubit_plot,
            {
                "qubit_value":
                self.qubit_and_plot_choice_widgets["qubit_buttons"],
                "qubit_info":
                self.qubit_and_plot_choice_widgets["show_qubitinfo_checkbox"],
                "plot_value":
                self.qubit_and_plot_choice_widgets["plot_buttons"],
            },
        )
        qubit_and_plot_choice_interactive.layout.width = "975px"

        return qubit_and_plot_choice_widgets, qubit_and_plot_choice_interactive
Exemplo n.º 2
0
def EvenOdd():
    funcs = {
        "cos(x)": np.cos,
        "cos(2x)": cos2,
        "cos(2x)": cos2,
        "sin(x)": np.sin,
        "x^2": quad,
        "Odd Square": oddSquare,
        "Even Square": evenSquare
    }
    f1_drop = widgets.Dropdown(options=funcs)
    f2_drop = widgets.Dropdown(options=funcs)
    sym_check = widgets.Checkbox(value=False, description="Check Symmetry")
    area_check = widgets.Checkbox(value=False,
                                  description="Integration Region")

    display(
        widgets.VBox([
            widgets.HBox([f1_drop, f2_drop, sym_check, area_check]),
            widgets.interactive_output(
                symmetryCheck, {
                    'f1': f1_drop,
                    'f2': f2_drop,
                    "showSym": sym_check,
                    "showArea": area_check
                })
        ]))
Exemplo n.º 3
0
def show_image_series(image_series: ImageSeries, neurodata_vis_spec: dict):
    if len(image_series.data.shape) == 3:
        return show_grayscale_image_series(image_series, neurodata_vis_spec)

    def show_image(index=0, mode='rgb'):
        fig, ax = plt.subplots(subplot_kw={'xticks': [], 'yticks': []})
        image = image_series.data[index]
        if mode == 'bgr':
            image = image[:, :, ::-1]
        ax.imshow(image, cmap='gray', aspect='auto')
        fig.show()
        return fig2widget(fig)

    slider = widgets.IntSlider(value=0,
                               min=0,
                               max=image_series.data.shape[0] - 1,
                               orientation='horizontal',
                               continuous_update=False,
                               description='index')
    mode = widgets.Dropdown(options=('rgb', 'bgr'),
                            layout=Layout(width='200px'),
                            description='mode')
    controls = {'index': slider, 'mode': mode}
    out_fig = widgets.interactive_output(show_image, controls)
    vbox = widgets.VBox(children=[out_fig, slider, mode])

    return vbox
Exemplo n.º 4
0
def i_get_job_script():
    from ipywidgets import widgets, Layout, interact_manual
    from IPython.display import display, clear_output
    from os.path import isfile
    inodes = widgets.BoundedIntText(value=1,
                                    min=1,
                                    max=4394,
                                    step=1,
                                    description='nodes',
                                    disabled=False)
    iranks_per_node = widgets.BoundedIntText(value=1,
                                             min=1,
                                             max=64,
                                             step=1,
                                             description='ranks/node',
                                             disabled=False)
    iaffinity = widgets.Text(value='-d 1 -j 1 --cc depth',
                             description='affinity')
    icommand = widgets.Text(value='', description='executable and args')
    out = widgets.interactive_output(
        get_job_script, {
            'nodes': inodes,
            'ranks_per_node': iranks_per_node,
            'affinity': iaffinity,
            'command': icommand
        })
    box = widgets.VBox(
        [widgets.VBox([inodes, iranks_per_node, iaffinity, icommand]), out])
    display(box)
    return
Exemplo n.º 5
0
def show_image_series(image_series: ImageSeries, neurodata_vis_spec: dict):
    if len(image_series.data.shape) == 3:
        return show_grayscale_image_series(image_series, neurodata_vis_spec)

    def show_image(index=0, mode="rgb"):
        fig, ax = plt.subplots(subplot_kw={"xticks": [], "yticks": []})
        image = image_series.data[index]
        if mode == "bgr":
            image = image[:, :, ::-1]
        ax.imshow(image.transpose([1, 0, 2]), cmap="gray", aspect="auto")
        fig.show()
        return fig2widget(fig)

    slider = widgets.IntSlider(
        value=0,
        min=0,
        max=image_series.data.shape[0] - 1,
        orientation="horizontal",
        continuous_update=False,
        description="index",
    )
    mode = widgets.Dropdown(options=("rgb", "bgr"),
                            layout=Layout(width="200px"),
                            description="mode")
    controls = {"index": slider, "mode": mode}
    out_fig = widgets.interactive_output(show_image, controls)
    vbox = widgets.VBox(children=[out_fig, slider, mode])

    return vbox
Exemplo n.º 6
0
def sdof_interact():
    """Create interactive plots of characteristics of SDOF system."""
    m_slide = widgets.FloatSlider(min=1e-5, max=20, step=.1, value=5,
                                  continuous_update=False)
    k_slide = FloatSlider(min=1e-5, max=1000, step=1., value=100,
                          continuous_update=False)
    c_slide = FloatSlider(min=-1, max=200, step=.1, value=2,
                          continuous_update=False)

    m_label = widgets.Label('Mass')
    c_label = Label('Damping')
    k_label = Label('Stiffness')

    m_slider = widgets.VBox([m_label, m_slide])
    c_slider = widgets.VBox([c_label, c_slide])
    k_slider = widgets.VBox([k_label, k_slide])

    ui = widgets.HBox([m_slider, c_slider, k_slider])

    out = widgets.interactive_output(plot_sdof_resp,
                                     {'m': m_slide,
                                      'c': c_slide, 'k': k_slide})

    sdof_responses = widgets.VBox([ui, out])
    return sdof_responses
Exemplo n.º 7
0
def show_decomposition_traces(node: DecompositionSeries):
    # Produce figure
    def control_plot(x0, x1, ch0, ch1):
        fig, ax = plt.subplots(nrows=nBands,
                               ncols=1,
                               sharex=True,
                               figsize=(14, 7))
        for bd in range(nBands):
            data = node.data[x0:x1, ch0:ch1 + 1, bd]
            xx = np.arange(x0, x1)
            mu_array = np.mean(data, 0)
            sd_array = np.std(data, 0)
            offset = np.mean(sd_array) * 5
            yticks = [i * offset for i in range(ch1 + 1 - ch0)]
            for i in range(ch1 + 1 - ch0):
                ax[bd].plot(xx, data[:, i] - mu_array[i] + yticks[i])
            ax[bd].set_ylabel('Ch #', fontsize=20)
            ax[bd].set_yticks(yticks)
            ax[bd].set_yticklabels([str(i) for i in range(ch0, ch1 + 1)])
            ax[bd].tick_params(axis='both', which='major', labelsize=16)
        ax[bd].set_xlabel('Time [ms]', fontsize=20)
        return fig

    nSamples = node.data.shape[0]
    nChannels = node.data.shape[1]
    nBands = node.data.shape[2]
    fs = node.rate

    # Controls
    field_lay = widgets.Layout(max_height='40px',
                               max_width='100px',
                               min_height='30px',
                               min_width='70px')
    x0 = widgets.BoundedIntText(value=0,
                                min=0,
                                max=int(1000 * nSamples / fs - 100),
                                layout=field_lay)
    x1 = widgets.BoundedIntText(value=nSamples,
                                min=100,
                                max=int(1000 * nSamples / fs),
                                layout=field_lay)
    ch0 = widgets.BoundedIntText(value=0,
                                 min=0,
                                 max=int(nChannels - 1),
                                 layout=field_lay)
    ch1 = widgets.BoundedIntText(value=10,
                                 min=0,
                                 max=int(nChannels - 1),
                                 layout=field_lay)

    controls = {'x0': x0, 'x1': x1, 'ch0': ch0, 'ch1': ch1}
    out_fig = widgets.interactive_output(control_plot, controls)

    # Assemble layout box
    lbl_x = widgets.Label('Time [ms]:', layout=field_lay)
    lbl_ch = widgets.Label('Ch #:', layout=field_lay)
    lbl_blank = widgets.Label('    ', layout=field_lay)
    hbox0 = widgets.HBox(children=[lbl_x, x0, x1, lbl_blank, lbl_ch, ch0, ch1])
    vbox = widgets.VBox(children=[hbox0, out_fig])
    return vbox
Exemplo n.º 8
0
def raster_grid_widget(units: Units):

    trials = units.get_ancestor('NWBFile').trials
    if trials is None:
        return widgets.HTML('No trials present')

    groups = infer_categorical_columns(trials)

    control_widgets = widgets.VBox(children=[])

    rows_controller = widgets.Dropdown(options=[None] + list(groups),
                                       description='rows: ',
                                       layout=Layout(width='95%'))
    cols_controller = widgets.Dropdown(options=[None] + list(groups),
                                       description='cols: ',
                                       layout=Layout(width='95%'))
    control_widgets.children = list(
        control_widgets.children) + [rows_controller, cols_controller]

    trial_event_controller = make_trial_event_controller(trials)
    control_widgets.children = list(
        control_widgets.children) + [trial_event_controller]

    unit_controller = int_controller(len(units['spike_times'].data) - 1)
    control_widgets.children = list(
        control_widgets.children) + [unit_controller]

    before_slider = widgets.FloatSlider(.5,
                                        min=0,
                                        max=5.,
                                        description='before (s)',
                                        continuous_update=False)
    control_widgets.children = list(control_widgets.children) + [before_slider]

    after_slider = widgets.FloatSlider(2.,
                                       min=0,
                                       max=5.,
                                       description='after (s)',
                                       continuous_update=False)
    control_widgets.children = list(control_widgets.children) + [after_slider]

    controls = {
        'units': fixed(units),
        'trials': fixed(trials),
        'index': unit_controller.children[0],
        'after': after_slider,
        'before': before_slider,
        'align_by': trial_event_controller,
        'rows_label': rows_controller,
        'cols_label': cols_controller
    }

    out_fig = widgets.interactive_output(raster_grid, controls)
    vbox = widgets.VBox(children=[control_widgets, out_fig])

    return vbox
Exemplo n.º 9
0
 def __init__(self, tfms=Blur, debug=False, image=coffee()):
     self.image = image
     self.debug = debug
     self.tfms = tfms
     self.interact_wds = {}
     k = get_default_args(tfms)
     if self.debug:
         print(k)
     ui = self.ui_prepare(k)
     out = widgets.interactive_output(self.f, self.interact_wds)
     display(ui, out)
Exemplo n.º 10
0
    def start(self):
        button = widgets.Button(description="Reset")
        button.on_click(self.on_button_clicked)

        main = widgets.HBox([self.text, button])
        u1 = widgets.HBox([self.sliders[str(i)] for i in range(0, 4)])
        u2 = widgets.HBox([self.sliders[str(i)] for i in range(4, 8)])
        u3 = widgets.HBox([self.sliders[str(i)] for i in range(8, 12)])
        u4 = widgets.HBox([self.sliders[str(i)] for i in range(12, 16)])

        out = widgets.interactive_output(self.affineTransform, self.sliders)

        display(main, u1, u2, u3, u4, out)
Exemplo n.º 11
0
def show_spike_event_series(ses: SpikeEventSeries, **kwargs):
    def control_plot(spk_ind):
        fig, ax = plt.subplots(figsize=(9, 5))
        data = ses.data[spk_ind]
        if nChannels > 1:
            for ch in range(nChannels):
                ax.plot(data[:, ch], color="#d9d9d9")
        else:
            ax.plot(data[:], color="#d9d9d9")
        ax.plot(np.mean(data, axis=1), color="k")
        ax.set_xlabel("Time")
        ax.set_ylabel("Amplitude")
        fig.show()
        return fig2widget(fig)

    if len(ses.data.shape) == 3:
        nChannels = ses.data.shape[2]
    else:
        nChannels = ses.data.shape[1]
    nSpikes = ses.data.shape[0]

    # Controls
    field_lay = widgets.Layout(max_height="40px",
                               max_width="100px",
                               min_height="30px",
                               min_width="70px")
    spk_ind = widgets.BoundedIntText(value=0,
                                     min=0,
                                     max=nSpikes - 1,
                                     layout=field_lay)
    controls = {"spk_ind": spk_ind}
    out_fig = widgets.interactive_output(control_plot, controls)

    # Assemble layout box
    lbl_spk = widgets.Label("Spike ID:", layout=field_lay)
    lbl_nspks0 = widgets.Label("N° spikes:", layout=field_lay)
    lbl_nspks1 = widgets.Label(str(nSpikes), layout=field_lay)
    lbl_nch0 = widgets.Label("N° channels:", layout=field_lay)
    lbl_nch1 = widgets.Label(str(nChannels), layout=field_lay)
    hbox0 = widgets.HBox(children=[lbl_spk, spk_ind])
    vbox0 = widgets.VBox(children=[
        widgets.HBox(children=[lbl_nspks0, lbl_nspks1]),
        widgets.HBox(children=[lbl_nch0, lbl_nch1]),
        hbox0,
    ])
    hbox1 = widgets.HBox(children=[vbox0, out_fig])

    return hbox1
Exemplo n.º 12
0
def preview_dataset(dataset,
                    preview_index=0,
                    show_hist=False,
                    use_transform=False):
    data, label = dataset.get_raw_item_with_label_filter(
        preview_index)  # equivalent dataset[preview_index]
    if use_transform:
        transform = get_dataset_transform()
        data, label = transform_input(data, label, transform)

    max_channels = label.shape[0]
    max_slices = label.shape[1]

    print(f'data max {data.max()}, min {data.min()}')
    print(f'label max {label.max()}, min {label.min()}')

    def f(slice_index, label_channel):
        plt.figure(figsize=(20, 10))
        plt.subplot(1, 2, 1)
        plt.imshow(data[0, slice_index], cmap="gray")
        plt.subplot(1, 2, 2)
        plt.imshow(label[label_channel, slice_index])
        plt.show()

        if show_hist:
            plt.figure(figsize=(20, 10))
            plt.subplot(1, 2, 1)
            plt.hist(data.flatten(), 128)
            plt.subplot(1, 2, 2)
            plt.hist(label.flatten(), 128)
            plt.show()

    sliceSlider = widgets.IntSlider(min=0,
                                    max=max_slices - 1,
                                    step=1,
                                    value=(max_slices - 1) / 2)
    labelChannelSlider = widgets.IntSlider(min=0,
                                           max=max_channels - 1,
                                           step=1,
                                           value=(max_channels - 1) / 2)
    ui = widgets.VBox([widgets.HBox([sliceSlider, labelChannelSlider])])
    out = widgets.interactive_output(f, {
        'slice_index': sliceSlider,
        'label_channel': labelChannelSlider
    })
    # noinspection PyTypeChecker
    display(ui, out)
Exemplo n.º 13
0
def FilterFreqs(audioData, freqDom, freqs):
    """
        Produces UI componants for user. Drives plotting of filtered signal (FilterFreqs)

        ----------

        Parameters

        ----------

        audioData: array_like
            raw audio data
        
        freqDom: array_like
            transformed frequnecy domain data
        
        freqs: array_like
        frequencies
    """
    filter_sldr = widgets.IntRangeSlider(value=[0, 0],
                                         min=0,
                                         max=23e3,
                                         step=1000,
                                         continuous_update=False,
                                         description='Freq Band')
    xlim_sldr = widgets.IntRangeSlider(value=[0, 22.5e3],
                                       min=0,
                                       max=22.5e3,
                                       step=1000,
                                       continuous_update=False,
                                       description='Ax. lim')
    export_btn = widgets.ToggleButton(value=False,
                                      description='Export to .wav')

    display(
        widgets.VBox([
            widgets.interactive_output(
                FilterBand, {
                    'audioData': widgets.fixed(audioData),
                    'freqDom': widgets.fixed(freqDom),
                    'freqs': widgets.fixed(freqs),
                    'filtFreq': filter_sldr,
                    'FALim': xlim_sldr,
                    'export': export_btn
                }),
            widgets.HBox([xlim_sldr, filter_sldr, export_btn])
        ]))
Exemplo n.º 14
0
def raster_widget(units: Units,
                  unit_controller=None,
                  time_window_controller=None):
    if time_window_controller is None:
        tmin = get_min_spike_time(units)
        tmax = get_max_spike_time(units)
        time_window_controller = float_range_controller(tmin, tmax)
    if unit_controller is None:
        unit_controller = int_range_controller(len(units['spike_times'].data) -
                                               1,
                                               start_range=(0, 100))

    candidate_cols = [
        x for x in units.colnames if not isinstance(units[x][0], Iterable)
        or isinstance(units[x][0], str)
    ]

    groups = infer_categorical_columns(units)
    group_controller = widgets.Dropdown(options=[None] + list(groups),
                                        description='color by',
                                        layout=Layout(width='90%'))

    features = [
        x for x in candidate_cols if len(robust_unique(units[x][:])) > 1
    ]
    order_by_controller = widgets.Dropdown(options=[None] + features,
                                           description='order by',
                                           layout=Layout(width='90%'))

    controls = {
        'units': fixed(units),
        'time_window': time_window_controller.children[0],
        'units_window': unit_controller.children[0],
        'group_by': group_controller,
        'order_by': order_by_controller,
    }

    out_fig = widgets.interactive_output(show_session_raster, controls)
    color_and_order_box = widgets.VBox(children=(group_controller,
                                                 order_by_controller),
                                       layout=Layout(width='250px'))
    control_widgets = widgets.HBox(children=(time_window_controller,
                                             unit_controller,
                                             color_and_order_box))
    vbox = widgets.VBox(children=[control_widgets, out_fig])
    return vbox
Exemplo n.º 15
0
def show_grayscale_image_series(image_series: ImageSeries,
                                neurodata_vis_spec: dict):
    def show_image(index=0):
        fig, ax = plt.subplots(subplot_kw={'xticks': [], 'yticks': []})
        ax.imshow(image_series.data[index], cmap='gray', aspect='auto')
        return fig

    slider = widgets.IntSlider(value=0,
                               min=0,
                               max=image_series.data.shape[0] - 1,
                               orientation='horizontal',
                               continuous_update=False,
                               description='index')
    controls = {'index': slider}
    out_fig = widgets.interactive_output(show_image, controls)
    vbox = widgets.VBox(children=[out_fig, slider])

    return vbox
Exemplo n.º 16
0
def single_trace_widget(timeseries: TimeSeries, time_window_controller=None):

    controls = dict(timeseries=fixed(timeseries))

    gen_time_window_controller = False
    if time_window_controller is None:
        gen_time_window_controller = True
        tmin = get_timeseries_mint(timeseries)
        tmax = get_timeseries_maxt(timeseries)
        time_window_controller = RangeController(tmin, tmax, start_value=[tmin, min(tmin+30, tmax)])

    controls.update(time_window=time_window_controller.slider)

    out_fig = widgets.interactive_output(show_trace, controls)

    if gen_time_window_controller:
        return widgets.VBox(children=[time_window_controller, out_fig])
    else:
        return widgets.VBox(children=[out_fig])
Exemplo n.º 17
0
def show_spike_event_series(ses, **kwargs):
    def control_plot(spk_ind):
        fig, ax = plt.subplots(figsize=(9, 5))
        data = ses.data[spk_ind, :, :]
        for ch in range(nChannels):
            ax.plot(data[:, ch], color='#d9d9d9')
        ax.plot(np.mean(data, axis=1), color='k')
        ax.set_xlabel('Time')
        ax.set_ylabel('Amplitude')
        plt.show()
        return fig2widget(fig)

    nChannels = ses.data.shape[2]
    nSpikes = ses.data.shape[0]

    # Controls
    field_lay = widgets.Layout(max_height='40px',
                               max_width='100px',
                               min_height='30px',
                               min_width='70px')
    spk_ind = widgets.BoundedIntText(value=0,
                                     min=0,
                                     max=nSpikes - 1,
                                     layout=field_lay)
    controls = {'spk_ind': spk_ind}
    out_fig = widgets.interactive_output(control_plot, controls)

    # Assemble layout box
    lbl_spk = widgets.Label('Spike ID:', layout=field_lay)
    lbl_nspks0 = widgets.Label('N° spikes:', layout=field_lay)
    lbl_nspks1 = widgets.Label(str(nSpikes), layout=field_lay)
    lbl_nch0 = widgets.Label('N° channels:', layout=field_lay)
    lbl_nch1 = widgets.Label(str(nChannels), layout=field_lay)
    hbox0 = widgets.HBox(children=[lbl_spk, spk_ind])
    vbox0 = widgets.VBox(children=[
        widgets.HBox(children=[lbl_nspks0, lbl_nspks1]),
        widgets.HBox(children=[lbl_nch0, lbl_nch1]), hbox0
    ])
    hbox1 = widgets.HBox(children=[vbox0, out_fig])

    return hbox1
Exemplo n.º 18
0
def traces_widget(node: TimeSeries,
                  neurodata_vis_spec: dict = None,
                  time_window_controller=None,
                  start=None,
                  dur=None,
                  trace_controller=None,
                  trace_starting_range=None,
                  **kwargs):

    if time_window_controller is None:
        tmax = get_timeseries_maxt(node)
        tmin = get_timeseries_mint(node)
        if start is None:
            start = tmin
        if dur is None:
            dur = min(tmax - tmin, 5)
        time_window_controller = make_time_window_controller(tmin,
                                                             tmax,
                                                             start=start,
                                                             duration=dur)
    if trace_controller is None:
        if trace_starting_range is None:
            trace_starting_range = (0, min(30, node.data.shape[1]))
        trace_controller = int_range_controller(
            node.data.shape[1], start_range=trace_starting_range)

    controls = {
        'time_series': widgets.fixed(node),
        'time_start': time_window_controller.children[0].children[0],
        'time_duration': time_window_controller.children[0].children[1],
        'trace_window': trace_controller.children[0],
    }
    controls.update({key: widgets.fixed(val) for key, val in kwargs.items()})

    out_fig = widgets.interactive_output(plot_traces, controls)

    control_widgets = widgets.HBox(children=(time_window_controller,
                                             trace_controller))
    vbox = widgets.VBox(children=[control_widgets, out_fig])

    return vbox
Exemplo n.º 19
0
def traces_widget(node: TimeSeries, neurodata_vis_spec: dict = None,
                  time_window_controller=None, start=None, dur=None,
                  trace_controller=None, trace_starting_range=None,
                  **kwargs):

    if time_window_controller is None:
        tmax = get_timeseries_maxt(node)
        tmin = get_timeseries_mint(node)
        if start is None:
            start = tmin
        if dur is None:
            dur = min(tmax-tmin, 5)
        time_window_controller = StartAndDurationController(tmax, tmin, start=start, duration=dur)
    if trace_controller is None:
        if trace_starting_range is None:
            trace_starting_range = (0, min(30, node.data.shape[1]))
        trace_controller = RangeController(0, node.data.shape[1], start_range=trace_starting_range,
                                           description='channels', dtype='int', orientation='vertical')

    controls = {
        'time_series': widgets.fixed(node),
        'time_window': time_window_controller,
        'trace_window': trace_controller.slider,
    }
    controls.update({key: widgets.fixed(val) for key, val in kwargs.items()})

    out_fig = widgets.interactive_output(plot_traces, controls)

    lower = widgets.HBox(children=[
        trace_controller,
        out_fig
    ])

    out = widgets.VBox(children=[
        time_window_controller,
        lower
    ])

    return out
def debug_preview_model_output(low_res_data_img, low_res_label_img, model_output_img):
    # preview of 32x32 segmentation and his expanded 512x512 version
    def f(slice_index):
        plt.figure(figsize=(18, 12))

        plt.subplot(1, 3, 1).set_title('low res data')
        plt.imshow(low_res_data_img[0, slice_index], cmap="gray")

        plt.subplot(1, 3, 2).set_title('low res label')
        plt.imshow(low_res_label_img[slice_index], cmap="gray")

        plt.subplot(1, 3, 3).set_title('low res model output')
        plt.imshow(model_output_img[0, 0, slice_index], cmap="gray", vmin=0, vmax=1)

        plt.show()

    slices_count = model_output_img[0, 0].shape[0] - 1
    sliceSlider = widgets.IntSlider(min=0, max=slices_count, step=1, value=slices_count // 2)
    ui = widgets.VBox([widgets.HBox([sliceSlider])])
    out = widgets.interactive_output(f, {'slice_index': sliceSlider})
    # noinspection PyTypeChecker
    display(ui, out)
Exemplo n.º 21
0
def symmetryCheck(f1, f2, showSym, showArea):

    a_slider = widgets.FloatSlider(value=1,
                                   min=0,
                                   max=np.pi,
                                   step=0.1,
                                   continuous_update=False)

    if not showSym:
        displayEvenOdd(f1, f2, showArea)
    else:
        display(
            widgets.VBox([
                a_slider,
                widgets.interactive_output(
                    displayEvenOdd, {
                        "f1": widgets.fixed(f1),
                        "f2": widgets.fixed(f2),
                        "showArea": widgets.fixed(showArea),
                        "a": a_slider
                    })
            ]))
Exemplo n.º 22
0
        def interact():
            from ipywidgets import interactive, fixed, widgets, interact_manual
            from IPython.display import display
            from ipywidgets import AppLayout, Button, Layout

            target_values_options = list(df["{}"].unique())

            features_options = list(df.columns.values)
            features_options.remove("{}")
            w1 = widgets.SelectMultiple(
                options=target_values_options,
                value=target_values_options,
                rows=len(target_values_options),
                description="Target Values (column: {})",
                style={{
                    "description_width": "initial"
                }},
                disabled=False,
            )
            w2 = widgets.SelectMultiple(
                options=features_options,
                value=features_options[0:min(len(features_options), 2)],
                rows=len(features_options),
                description="Features",
                disabled=False,
            )

            ui = widgets.HBox([w1, w2])
            out = widgets.interactive_output(
                pairwise_scatter_plots,
                {{
                    "df": fixed(df),
                    "target_values": w1,
                    "features": w2
                }},
            )

            display(ui, out)
Exemplo n.º 23
0
def FourierSeries():
    """ 
        Main function called by notebook
    """
    terms_sldr = widgets.IntSlider(value=3,
                                   description='Terms',
                                   min=2,
                                   max=100,
                                   display=False,
                                   continuous_update=False)
    func_drp = widgets.Dropdown(options=['Linear', 'Square Wave', 'Cubic'],
                                description='Function')
    prevTerm_check = widgets.Checkbox(value=False,
                                      description='Show most recent term')
    return widgets.VBox([
        widgets.HBox([terms_sldr, func_drp, prevTerm_check]),
        widgets.interactive_output(
            fourierMain, {
                'function': func_drp,
                'nMax': terms_sldr,
                'showPrevTerm': prevTerm_check
            })
    ])
Exemplo n.º 24
0
def RandomWave():
    """ Main function called by notebook
    """
    noWaves_sldr = widgets.IntSlider(value=10,
                                     min=2,
                                     max=20,
                                     step=1,
                                     description='No. Waves',
                                     continuous_update=False)
    seed_Text = widgets.IntText(123, description='Seed')
    filter_sldr = widgets.FloatRangeSlider(value=[minf, minf],
                                           min=minf,
                                           max=maxf,
                                           description="Filter Range",
                                           continuous_update=False)
    return widgets.VBox([
        widgets.HBox([noWaves_sldr, filter_sldr, seed_Text]),
        widgets.interactive_output(runWaves, {
            'noWaves': noWaves_sldr,
            'seed': seed_Text,
            'filterRange': filter_sldr
        })
    ])
Exemplo n.º 25
0
def preview_3d_image(img,
                     figsize=(16, 16),
                     show_slice=None,
                     show_unique=False,
                     minmax=False):
    if type(img) is sitk.SimpleITK.Image:
        img = sitk.GetArrayFromImage(img)

    max_slices = img.shape[0]

    def f(slice_index):
        plt.figure(figsize=figsize)
        if minmax:
            plt.imshow(img[slice_index], vmin=np.min(img), vmax=np.max(img))
        else:
            plt.imshow(img[slice_index])
        plt.show()

        if show_unique:
            print(f"debug: {img.min()}, {img.max()}")
            print(f"debug: unique {np.unique(img[slice_index])}")

    if show_slice:
        sliceSlider = widgets.IntSlider(min=0,
                                        max=max_slices - 1,
                                        step=1,
                                        value=show_slice)
    else:
        sliceSlider = widgets.IntSlider(min=0,
                                        max=max_slices - 1,
                                        step=1,
                                        value=(max_slices - 1) / 2)

    ui = widgets.VBox([widgets.HBox([sliceSlider])])
    out = widgets.interactive_output(f, {'slice_index': sliceSlider})
    # noinspection PyTypeChecker
    display(ui, out)
Exemplo n.º 26
0
def show_email_draft_area():
    field_map = {
        r['prop']: make_text_input(r)
        for r in TakedownStore.input_fields
    }
    inputs = list(field_map.values())

    def make_email_draft(**kwargs):
        letter_date = datetime.date.isoformat(datetime.date.today())
        #         doc_urls = make_html_url_list(TakedownStore.data_store.infringing_docs)
        doc_urls = make_infringing_lists(
            TakedownStore.data_store.infringing_doc_tuples)
        with open('{}/takedown_request.html'.format(env.TEMPLATE_FOLDER),
                  'r') as o:
            template = o.read()

        formatted = template.format(letter_date=letter_date,
                                    doc_urls=doc_urls,
                                    **kwargs)
        return display(widgets.HTML(value=formatted))

    # Show the email draft and fields to fill it in
    email_out = widgets.interactive_output(make_email_draft, field_map)
    return display(widgets.VBox([widgets.VBox(inputs), email_out]))
Exemplo n.º 27
0
def MusicNote(audioData, freqDom, freqs):
    """
        Produces UI componants for user. Drives plotting of PlotFourierAnalysis

        ----------

        Parameters

        ----------

        audioData: array_like
            raw audio data
        
        freqDom: array_like
            transformed frequency domain data
        
        freqs: array_like
            frequencies
    """
    xlim_sldr = widgets.IntRangeSlider(value=[0, 22.5e3],
                                       min=0,
                                       max=22.5e3,
                                       step=1000,
                                       continuous_update=False,
                                       description='Ax. lim')

    return widgets.VBox([
        widgets.interactive_output(
            PlotSignal, {
                'signal': widgets.fixed(audioData),
                'amps': widgets.fixed(freqDom),
                'freqs': widgets.fixed(freqs),
                'FALim': xlim_sldr
            }),
        widgets.HBox([xlim_sldr])
    ])
def debug_preview_cuts(exp_model_output_img, new_bounding_box, data_cut, label_cut):
    def f(slice_index):
        tmp_cut = exp_model_output_img[0, 0, new_bounding_box[0]:new_bounding_box[1] + 1,
                  new_bounding_box[2]:new_bounding_box[3] + 1, new_bounding_box[4]:new_bounding_box[5] + 1]

        plt.figure(figsize=(18, 12))

        plt.subplot(1, 3, 1).set_title('low res model output')
        plt.imshow(tmp_cut[slice_index], cmap="gray", vmin=0, vmax=1)

        plt.subplot(1, 3, 2).set_title('data cut')
        plt.imshow(data_cut[0, slice_index], cmap="gray")

        plt.subplot(1, 3, 3).set_title('label cut')
        plt.imshow(label_cut[slice_index])

        plt.show()

    slices_count = label_cut.shape[0] - 1
    sliceSlider = widgets.IntSlider(min=0, max=slices_count, step=1, value=slices_count // 2)
    ui = widgets.VBox([widgets.HBox([sliceSlider])])
    out = widgets.interactive_output(f, {'slice_index': sliceSlider})
    # noinspection PyTypeChecker
    display(ui, out)
Exemplo n.º 29
0
    def interact_plot_model_prism(self):
        plot = widgets.RadioButtons(
            options=["field", "model"],
            value="field",
            description="plot",
            disabled=False,
        )
        component = widgets.RadioButtons(
            options=["Bt", "Bx", "By", "Bz"],
            value="Bt",
            description="field",
            disabled=False,
        )

        inclination = widgets.FloatSlider(description="I",
                                          continuous_update=False,
                                          min=-90,
                                          max=90,
                                          step=1,
                                          value=90)
        declination = widgets.FloatSlider(description="D",
                                          continuous_update=False,
                                          min=-180,
                                          max=180,
                                          step=1,
                                          value=0)
        length = widgets.FloatSlider(
            description="length",
            continuous_update=False,
            min=2,
            max=200,
            step=1,
            value=72,
        )
        dx = widgets.FloatSlider(
            description="data spacing",
            continuous_update=False,
            min=0.1,
            max=15,
            step=0.1,
            value=2,
        )
        kappa = widgets.FloatText(description="$\kappa$", value=0.1)
        B0 = widgets.FloatText(description="B$_0$", value=56000)
        depth = widgets.FloatSlider(
            description="depth",
            continuous_update=False,
            min=0,
            max=50,
            step=1,
            value=10,
        )
        profile = widgets.RadioButtons(
            options=["East", "North", "None"],
            value="East",
            description="profile",
            disabled=False,
        )
        fixed_scale = widgets.Checkbox(value=False,
                                       description="fixed scale",
                                       disabled=False)

        show_halfwidth = widgets.Checkbox(value=False,
                                          description="half width",
                                          disabled=False)
        prism_dx = widgets.FloatText(description="$\\triangle x$", value=1)
        prism_dy = widgets.FloatText(description="$\\triangle y$", value=1)
        prism_dz = widgets.FloatText(description="$\\triangle z$", value=1)
        prism_inclination = widgets.FloatSlider(
            description="I$_{prism}$",
            continuous_update=False,
            min=-90,
            max=90,
            step=1,
            value=0,
        )
        prism_declination = widgets.FloatSlider(
            description="D$_{prism}$",
            continuous_update=False,
            min=0,
            max=180,
            step=1,
            value=0,
        )

        out = widgets.interactive_output(
            self.magnetic_prism_applet,
            {
                "plot": plot,
                "component": component,
                "inclination": inclination,
                "declination": declination,
                "length": length,
                "dx": dx,
                "kappa": kappa,
                "B0": B0,
                "depth": depth,
                "profile": profile,
                "fixed_scale": fixed_scale,
                "show_halfwidth": show_halfwidth,
                "prism_dx": prism_dx,
                "prism_dy": prism_dy,
                "prism_dz": prism_dz,
                "prism_inclination": prism_inclination,
                "prism_declination": prism_declination,
            },
        )
        left = widgets.VBox(
            [plot, component, profile],
            layout=Layout(width="20%",
                          height="400px",
                          margin="60px 0px 0px 0px"),
        )
        right = widgets.VBox(
            [
                inclination,
                declination,
                length,
                dx,
                B0,
                kappa,
                depth,
                prism_dx,
                prism_dy,
                prism_dz,
                prism_inclination,
                prism_declination,
                fixed_scale,
                show_halfwidth,
            ],
            layout=Layout(width="50%",
                          height="400px",
                          margin="20px 0px 0px 0px"),
        )
        widgets.VBox([out],
                     layout=Layout(width="70%",
                                   height="400px",
                                   margin="0px 0px 0px 0px"))
        return widgets.HBox([left, out, right])
Exemplo n.º 30
0
    def interact_plot_model_two_monopole(self):
        component = widgets.RadioButtons(
            options=["Bt", "Bx", "By", "Bz", "Bg"],
            value="Bt",
            description="field",
            disabled=False,
        )

        inclination = widgets.FloatSlider(description="I",
                                          continuous_update=False,
                                          min=-90,
                                          max=90,
                                          step=1,
                                          value=90)
        declination = widgets.FloatSlider(description="D",
                                          continuous_update=False,
                                          min=-180,
                                          max=180,
                                          step=1,
                                          value=0)
        length = widgets.FloatSlider(
            description="length",
            continuous_update=False,
            min=2,
            max=200,
            step=1,
            value=10,
        )
        dx = widgets.FloatSlider(
            description="data spacing",
            continuous_update=False,
            min=0.1,
            max=15,
            step=0.1,
            value=0.1,
        )
        moment = widgets.FloatText(description="M", value=30)
        depth_n = widgets.FloatSlider(
            description="depth$_{-Q}$",
            continuous_update=False,
            min=0,
            max=200,
            step=1,
            value=0,
        )
        depth_p = widgets.FloatSlider(
            description="depth$_{+Q}$",
            continuous_update=False,
            min=0,
            max=200,
            step=1,
            value=1,
        )
        profile = widgets.RadioButtons(
            options=["East", "North", "None"],
            value="East",
            description="profile",
            disabled=False,
        )
        fixed_scale = widgets.Checkbox(value=False,
                                       description="fixed scale",
                                       disabled=False)
        show_halfwidth = widgets.Checkbox(value=False,
                                          description="half width",
                                          disabled=False)

        out = widgets.interactive_output(
            self.magnetic_two_monopole_applet,
            {
                "component": component,
                "inclination": inclination,
                "declination": declination,
                "length": length,
                "dx": dx,
                "moment": moment,
                "depth_n": depth_n,
                "depth_p": depth_p,
                "profile": profile,
                "fixed_scale": fixed_scale,
                "show_halfwidth": show_halfwidth,
            },
        )
        left = widgets.VBox(
            [component, profile],
            layout=Layout(width="20%",
                          height="400px",
                          margin="60px 0px 0px 0px"),
        )
        right = widgets.VBox(
            [
                inclination,
                declination,
                length,
                dx,
                moment,
                depth_n,
                depth_p,
                fixed_scale,
                show_halfwidth,
            ],
            layout=Layout(width="50%",
                          height="400px",
                          margin="20px 0px 0px 0px"),
        )
        widgets.VBox([out],
                     layout=Layout(width="70%",
                                   height="400px",
                                   margin="0px 0px 0px 0px"))
        return widgets.HBox([left, out, right])