Beispiel #1
0
 def __init__(self, rl_ch=12, ud_ch=13, bus=1):
     self.sg = ServoGroup(rl_ch=rl_ch, ud_ch=ud_ch, bus=bus)
     self.sg.reset()  #Pan and tilt go to default position
     #Setup various widgets
     self.panel_step_move = NineButton(
         button_list=['↖', '↑', '↗', '←', 'reset', '→', '↙', '↓', '↘'])
     self.panel_far_move = NineButton(
         button_list=['◤', '▲', '◥', '◄', 'reset', '►', '◣', '▼', '◢'])
     self.image_widget = widgets.Image(
         format='jpeg', width=400, height=300)  #Display resolution setting
     self.snap_count = widgets.IntText(description='count:',
                                       layout=widgets.Layout(width='140px'),
                                       value=0)
     self.rl_textbox = widgets.IntText(layout=widgets.Layout(width='140px'),
                                       value=self.sg.read()[0],
                                       description='rl:')
     self.ud_textbox = widgets.IntText(layout=widgets.Layout(width='140px'),
                                       value=self.sg.read()[1],
                                       description='ud:')
     self.rl_slider = widgets.FloatSlider(min=-1,
                                          max=1,
                                          value=0,
                                          step=0.02,
                                          description='rl')
     self.ud_slider = widgets.FloatSlider(min=-1,
                                          max=1,
                                          value=0,
                                          step=0.02,
                                          description='ud')
     self.snap_dir = 'snap'  #Folder name for saving snapshot
     self.camera_link = None
     self.press_count = 0
Beispiel #2
0
    def main(self):
        self.media_wid = widgets.ToggleButtons(options=['Lif', 'Images'],
                                               description='Media Input',
                                               value='Lif')
        self.media_wid.observe(self.media_update, ['value'])

        # self.mode_wid = widgets.ToggleButtons(options=['multi', 'single'], description='Tracking mode',tooltips=['Multiple frame tracking', 'Single frame tracking. Which singles must be specified'])
        # self.mode_wid.observe(self.mode_update, ['value'])

        self.fmt = widgets.Dropdown(options=['.tif', '.png', '.jpg'],
                                    description='Frame format')

        self.initial_frame = widgets.IntText(description='Initial frame')

        self.nframes = widgets.IntText(description='Z Frames', value=5)

        self.k = widgets.FloatSlider(min=1,
                                     max=10,
                                     step=0.2,
                                     description='k (Blur)',
                                     value=1.6)

        self.edge_cutoff = widgets.FloatText(description='Edge cut')

        self.plot = widgets.Checkbox(description='Show plots', value=True)

        self.options.children = [self.media_wid]
Beispiel #3
0
 def __init__(self, title="Graphics Window", width=320, height=240):
     super(GraphWin, self).__init__(size=(width, height))
     from calysto.display import display, Javascript
     self.background_color = None
     self.title = widgets.HTML("<b>%s</b>" % title)
     self.mouse_x = widgets.IntText()
     self.mouse_y = widgets.IntText()
     self.svg_canvas = widgets.HTML(
         self.get_html(onClick="window.clicked(evt, '%s', '%s')" %
                       (self.mouse_x.model_id, self.mouse_y.model_id)))
     self.window = widgets.HBox([self.title, self.svg_canvas])
     display(
         Javascript("""
     window.clicked = function (evt, x_model, y_model) {
         var e = evt.srcElement.farthestViewportElement || evt.target;
         var dim = e.getBoundingClientRect();
         var x = evt.clientX - dim.left;
         var y = evt.clientY - dim.top;
         var manager = IPython.WidgetManager._managers[0];
         var model_prom = manager.get_model(x_model);
         model_prom.then(function(model) {
             model.set('value', Math.round(x));
             model.save_changes();
         });
         model_prom = manager.get_model(y_model);
         model_prom.then(function(model) {
             model.set('value', Math.round(y));
             model.save_changes();
         });
     };
     """))
     display(self.window)
Beispiel #4
0
    def make_gui(self):
        self.signature = signature(self.process)

        label = f"<b>{self.name}</b>"

        display(widgets.HTML(value=label))

        for i, arg_name in enumerate(self.signature.parameters):
            if i == 0:
                continue

            arg_type = self.signature.parameters[arg_name].annotation

            wd = dict(description=arg_name, value=self.params[arg_name])

            if arg_type is str:
                w = widgets.Text(**wd)
            elif arg_type is int:
                w = widgets.IntText(**wd)
            elif arg_type is float:
                w = widgets.FloatText(**wd)
            else:
                return

            w.observe(self.set_param)

            display(w)
Beispiel #5
0
def jspecgram(snd, nt=1000, starttime=None, endtime=None,
                 nperseg=512, freqsmoothing=1, cmap='viridis', dynrange=(-90., -40.),
                 maxfreq=10e3):
    nfft = int(nperseg*freqsmoothing)
    d = sndplot.Spectrogram(snd, nt=nt, starttime=starttime, endtime=endtime,
                            nperseg=nperseg, nfft=nfft, cmap=cmap, dynrange=dynrange,
                            maxfreq=maxfreq)
    button_play = widgets.Button(description='play')
    button_play.on_click(d.play)
    button_stop = widgets.Button(description='stop')
    button_stop.on_click(d.stop_playing)
    display(widgets.HBox((button_play, button_stop)))
    drs = widgets.FloatRangeSlider(value=(-75, -35), min=-120, max=0, step=1, description='dynamic range (dB)')
    drs.observe(lambda change: d.set_clim(change['new']), names='value')
    display(drs)
    freqs = widgets.FloatRangeSlider(value=(0, 10), min=0, max=snd.fs/2e3, step=0.1,
                                     description='frequency range (kHz)')
    freqs.observe(lambda change: d.set_freqrange(change['new']), names='value')
    display(freqs)
    npersegw = widgets.IntText(value=nperseg, min=1, max=4096 * 2,
                               description='nperseg')
    npersegw.observe(lambda change: d.set_nperseg(change['new']),
                     names='value')
    display(npersegw)
    return d
Beispiel #6
0
 def get_widgets_per_param(param, value):
     if isinstance(value, float):
         return (param, widgets.FloatText(
             value=value,
             step=0.05,
             description=param.split('__')[1],
             continuous_update=False,
             disabled=False
         ))
     elif isinstance(value, int):
         return (param, widgets.IntText(
             value=value,
             step=1,
             description=param.split('__')[1],
             continuous_update=False,
             disabled=False
         ))
     elif isinstance(value, str):
         return (param, widgets.Text(
             value=value,
             description=param.split('__')[1],
             continuous_update=False,
             disabled=False
         ))
     else:
         return None
Beispiel #7
0
def DrawDecisionTree(fac, datasetName, methodName):
    m = GetMethodObject(fac, datasetName, methodName)
    if m == None:
        return None
    tr = TreeReader(str(m.GetWeightFileName()))

    variables = tr.getVariables()

    def clicked(b):
        if treeSelector.value > tr.getNTrees():
            treeSelector.value = tr.getNTrees()
        clear_output()
        toJs = {"variables": variables, "tree": tr.getTree(treeSelector.value)}
        json_str = json.dumps(toJs)
        JPyInterface.JsDraw.Draw(json_str, "drawDecisionTree", True)

    mx = str(tr.getNTrees() - 1)

    treeSelector = widgets.IntText(value=0, font_weight="bold")
    drawTree = widgets.Button(description="Draw", font_weight="bold")
    label = widgets.HTML(
        "<div style='padding: 6px;font-weight:bold;color:#333;'>Decision Tree [0-"
        + mx + "]:</div>")

    drawTree.on_click(clicked)
    container = widgets.HBox([label, treeSelector, drawTree])
    display(container)
    def full_list_elements(self):
        retrieve_material = RetrieveMaterialMetadata(material='all')
        self.list_returned = retrieve_material.full_list_material()

        # import pprint
        # pprint.pprint(list_returned)

        box4 = widgets.HBox([
            widgets.Label("List of elements",
                          layout=widgets.Layout(width=self.label_width)),
            widgets.Select(options=self.list_returned,
                           layout=widgets.Layout(width='20%'))
        ])

        box5 = widgets.HBox([
            widgets.Label("Nbr Bragg Edges",
                          layout=widgets.Layout(width=self.label_width)),
            widgets.IntText(8, layout=widgets.Layout(width='20%'))
        ])

        vertical_box = widgets.VBox([box4, box5])
        display(vertical_box)

        self.list_elements_ui = box4.children[1]
        self.nbr_bragg_edges_ui = box5.children[1]
Beispiel #9
0
def show_obs_plot_widget(data, display_fn):
    from IPython import display
    from ipywidgets import widgets

    text_wid = widgets.IntText(value=0,
                               placeholder='Frame number',
                               description='Frame number:',
                               disabled=False)
    slider_wid = widgets.IntSlider(value=0,
                                   min=0,
                                   max=len(data),
                                   step=1,
                                   description='Frames:',
                                   disabled=False,
                                   continuous_update=False,
                                   orientation='horizontal',
                                   readout=True,
                                   readout_format='d')
    widgets.jslink((text_wid, 'value'), (slider_wid, 'value'))

    output_widget = widgets.Output(layout={'height': '250px'})

    def on_value_change(change):
        frame_idx = change['new']
        display_fn(frame_idx)

    slider_wid.observe(on_value_change, names='value')

    frame_box = widgets.HBox([output_widget])
    control_box = widgets.HBox([text_wid, slider_wid])  # Controls

    main_box = widgets.VBox([frame_box, control_box])

    display.display(main_box)
    display_fn(0)
Beispiel #10
0
 def __init__(self, Notebook):
     super(Run_Dynamics_pMHC, self).__init__(Notebook)
     self.widget_nputs = widgets.IntText(value=1,
                                         description='N :',
                                         disabled=False)
     self.button_launchRun = widgets.Button(description="Run dynamics",
                                            disabled=True)
     self.notebook.dependencies_dict["generation"].append(self)
     self.notebook.dependencies_dict["dynamics"] = []
     self.notebook.extra_variables = {"ntries": None}
Beispiel #11
0
def wdim_menu():
    '''
    generates menu for the molecules notebook in order to display and save data of specific dimers
    '''
    input = widgets.Dropdown(description='Input data',
                             options=['Dictionary', 'Pickle', 'Text file'],
                             value='Dictionary')
    which = widgets.IntText(description='Which dimmer')
    plot = widgets.Checkbox(description='Plot', value=True)
    save = widgets.Checkbox(description='Save', value=True)
    return widgets.VBox([input, which, plot, save])
Beispiel #12
0
def g6r_menu():
    '''
    generates a menu for specific parameters to compute and fit the time correlation of the hexagonal order. See src.characterisation.g6.py for details
    '''
    input = widgets.Dropdown(description='Input data',
                             options=['Dictionary', 'Pickle', 'Text file'],
                             value='Dictionary')
    nbins = widgets.IntText(description='Nbins', value=100)
    bs = widgets.FloatText(description='Binwidth', value=0.25)
    plot = widgets.Checkbox(description='Plot', value=True)
    save = widgets.Checkbox(description='Save', value=True)
    return widgets.VBox([input, nbins, bs, plot, save])
Beispiel #13
0
def ov_menu():
    '''
    generates a menu for specific parameters to compute and fit the overlap Q(t) functions. See src.characterisation.overlap.py for details
    '''
    input = widgets.Dropdown(description='Input data',
                             options=['Dictionary', 'Pickle', 'Text file'],
                             value='Dictionary')
    plot = widgets.Checkbox(description='Plot', value=True)
    fit = widgets.Checkbox(description='Fit', value=True)
    points = widgets.IntText(description='No. of points', value=100)
    tau = widgets.FloatText(description='$ \\tau $', value=1.)
    save = widgets.Checkbox(description='Save', value=True)
    return widgets.VBox([input, plot, fit, points, tau, save])
Beispiel #14
0
def msd_menu():
    input = widgets.Dropdown(description='Input data',
                             options=['Dictionary', 'Pickle', 'Text file'],
                             value='Dictionary')
    plot = widgets.Checkbox(description='Plot', value=True)
    fit = widgets.Checkbox(description='Fit MSD', value=True)
    points = widgets.IntText(description='Points', value=100)
    vel = widgets.FloatText(description='$ \\upsilon$ (px $s^{-1}$)',
                            value=100)
    tau = widgets.FloatText(description='$ \\tau $', value=0.5)
    refs = widgets.Checkbox(description='Slope reference', value=True)
    kind = widgets.Dropdown(options=['ABP', 'Quincke', 'Passive'],
                            description='MSD fit type',
                            value='ABP')
    save = widgets.Checkbox(description='Save', value=True)
    return widgets.VBox([input, plot, fit, kind, points, tau, vel, refs, save])
Beispiel #15
0
 def __init__(self, model, X, y, hist=True):
     self.min_value = -0.30
     self.max_value = +0.30
     self.step = 0.05
     self.sliders = {
         str(i): widgets.FloatSlider(min=self.min_value,
                                     max=self.max_value,
                                     step=self.step)
         for i in range(16)
     }
     self.text = widgets.IntText()
     self.sliders['index'] = self.text
     self.model = model
     self.X = X
     self.y = y
     self.hist = hist
Beispiel #16
0
def show_stamp_widget(masked_stamps):
    from IPython import display
    from ipywidgets import widgets

    text_wid = widgets.IntText(value=0,
                               placeholder='Frame number',
                               description='Frame number:',
                               disabled=False)
    slider_wid = widgets.IntSlider(value=0,
                                   min=0,
                                   max=len(masked_stamps),
                                   step=1,
                                   description='Frames:',
                                   disabled=False,
                                   continuous_update=False,
                                   orientation='horizontal',
                                   readout=True,
                                   readout_format='d')
    widgets.jslink((text_wid, 'value'), (slider_wid, 'value'))

    output_widget = widgets.Output(layout={'height': '250px'})

    def show_stamp(i):
        fig = make_sigma_aperture_plot(masked_stamps[i])
        #             fig.set_size_inches(9, 2.5)
        fig.suptitle(f'Frame {i:03d}', fontsize=14, y=1.06)
        fig.axes[1].grid(False)
        fig.axes[1].set_yticklabels([])
        fig.axes[1].set_facecolor('#bbbbbb')
        with output_widget:
            display.clear_output()
            display.display(fig)

    def on_value_change(change):
        frame_idx = change['new']
        show_stamp(frame_idx)

    slider_wid.observe(on_value_change, names='value')

    frame_box = widgets.HBox([output_widget])
    control_box = widgets.HBox([text_wid, slider_wid])  # Controls

    main_box = widgets.VBox([frame_box, control_box])

    display.display(main_box)
    show_stamp(0)
Beispiel #17
0
def appendPVWidgets (pv = ""):
    PVNameWidget = widgets.Text (description = "PV Name:", value = pv)

    PVBinsWidget = widgets.Checkbox(value = False, description = 'Optimized?')
    PVBinsIntWidget = widgets.IntText (value = "500", description = "# bins:", disabled = not PVBinsWidget.value)
    PVRemoveWidget = widgets.Button (description = "Remove")

    PVBinsWidget.observe (updateBinsText)
    PVRemoveWidget.on_click(removePVHandler) 

    newRow = widgets.HBox ([PVNameWidget, PVBinsWidget, PVBinsIntWidget, PVRemoveWidget])

    PVRemoveWidget.parent = newRow
    PVBinsWidget.parent = newRow

    PVWidgetList.append (newRow)

    appendPVVBox.children = PVWidgetList + [appendPVWidget]
Beispiel #18
0
    def __init__(self,
                 on_interact=None,
                 output=None,
                 overwrite_previous_output=True,
                 feedback=False,
                 run=True,
                 action_kws={},
                 *args,
                 **kwargs):
        super().__init__(on_interact=on_interact,
                         output=output,
                         overwrite_previous_output=overwrite_previous_output,
                         feedback=feedback,
                         action_kws=action_kws)

        self.widget = widgets.IntText(*args, **kwargs)

        if run:
            self.run()
Beispiel #19
0
def make_widgets_mat(m, n):
    """
        Makes a m rows x n columns 
        matriz of  integer Jupyter Widgets
        all values initialized to zero
    """
    list_elements = []
    for i in range(m):
        row = []
        for j in range(n):
            row.append(widgets.IntText(value=0))
        list_elements.append(row)

    rows = []
    for row in list_elements:
        rows.append(widgets.HBox(row))
        
    widgets_mat = widgets.VBox(rows)
        
    return list_elements, widgets_mat
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
        })
    ])
Beispiel #21
0
 def get_cluster_params_widgets(param, value):
     if isinstance(value, float):
         return (param, widgets.FloatText(
                 value=value,
                 step=0.1,
                 description=param.split('__')[1],
                 disabled=False
                 ))
     elif isinstance(value, int):
         return (param, widgets.IntText(
             value=value,
             step=1,
             description=param.split('__')[1],
             disabled=False
         ))
     elif isinstance(value, str):
         return (param, widgets.Text(
             value=value,
             description=param.split('__')[1],
             disabled=False
         ))
     else:
         return None
Beispiel #22
0
 def get_widgets_per_param(params):
     for key, value in params.items():
         style = {'description_width': 'initial'}
         description = key.split("__")[1] if "__" in key else key
         if isinstance(value, float):
             yield (key,
                    widgets.FloatText(value=value,
                                      step=0.05,
                                      description=description,
                                      continuous_update=False,
                                      disabled=False,
                                      layout=Layout(width="90%"),
                                      style=style))
         elif isinstance(value, bool):
             yield (key,
                    widgets.ToggleButton(value=value,
                                         description=description,
                                         disabled=False,
                                         layout=Layout(width="90%"),
                                         style=style))
         elif isinstance(value, int):
             yield (key,
                    widgets.IntText(value=value,
                                    step=1,
                                    description=description,
                                    continuous_update=False,
                                    disabled=False,
                                    layout=Layout(width="90%"),
                                    style=style))
         elif isinstance(value, str):
             yield (key,
                    widgets.Text(value=value,
                                 description=description,
                                 continuous_update=False,
                                 disabled=False,
                                 layout=Layout(width="90%"),
                                 style=style))
Beispiel #23
0
    def __init__(self, table: DynamicTable):
        super().__init__()
        self.dynamic_table = table

        self.col_names, self.categorical_cols = infer_columns_to_plot(
            self.dynamic_table)

        num_entries = len(self.dynamic_table)
        num_columns = len(self.dynamic_table.colnames)
        num_columns_to_plot = len(self.col_names)
        num_categorical = len(self.categorical_cols)

        self.name_text = widgets.Label(
            f"Table name: {self.dynamic_table.name}\n", layout=field_lay)
        self.entries_text = widgets.Label(
            f"Number of entries: {num_entries}\n", layout=field_lay)
        self.col_text = widgets.Label(
            f"Number of columns: {num_columns} - real (r): {num_columns - num_categorical}, "
            f"categorical (c): {num_categorical}",
            layout=field_lay)
        self.col_plot_text = widgets.Label(
            f"Number of inspectable columns: {num_columns_to_plot}")

        self.summary_text = widgets.VBox([
            self.name_text, self.entries_text, self.col_text,
            self.col_plot_text
        ])

        self.col_names_display = {}
        for col in self.col_names:
            if col in self.categorical_cols:
                self.col_names_display[f"(c) {col}"] = col
            else:
                self.col_names_display[f"(r) {col}"] = col

        self.column_dropdown = widgets.SelectMultiple(
            options=list(self.col_names_display),
            description="Inspect columns",
            layout=Layout(max_width="400px"),
            style={"description_width": "initial"},
            disabled=False,
            tooltip=
            "Select columns to inspect. You can select at most 1 categorical and 3 real columns."
        )
        self.column_dropdown.observe(self.max_selection)

        self.nbins = widgets.IntText(10,
                                     min=0,
                                     description="# bins",
                                     layout=Layout(max_width="400px"))
        self.nbins.layout.visibility = "hidden"

        self.show_labels = widgets.Checkbox(value=True,
                                            description="show labels")

        self.plot_controls = widgets.HBox(
            [self.column_dropdown, self.nbins, self.show_labels])

        self.controls = dict(col_names_display=self.column_dropdown,
                             nbins=self.nbins,
                             show_labels=self.show_labels)

        out_fig = interactive_output(self.plot_hist_bar, self.controls)
        bottom_panel = widgets.VBox([self.plot_controls, out_fig])

        self.children = [self.summary_text, bottom_panel]
Beispiel #24
0
def interact(obj):
    tab = widgets.Tab()
    base_style = widgets.ButtonStyle()
    selected_style = widgets.ButtonStyle(button_color='#DDFFDD',
                                         font_weight='bold')

    if isinstance(obj, hl.Table):
        glob = widgets.Button(description='globals',
                              layout=widgets.Layout(width='150px',
                                                    height='30px'))
        rows = widgets.Button(description='rows',
                              layout=widgets.Layout(width='150px',
                                                    height='200px'))
        rows.style = selected_style

        globals_frames = []
        globals_frames.append(
            widgets.HTML(
                f'<p><big>Global fields, with one value in the dataset.</big></p>\n'
                f'<p>Commonly used methods:</p>\n'
                f'<ul>'
                f'<li>{html_link("annotate_globals", "https://hail.is/docs/0.2/hail.Table.html#hail.Table.annotate_globals")}: '
                f'add new global fields.</li>'
                f'</ul>'))
        append_struct_frames(obj.globals.dtype, globals_frames)

        row_frames = []
        row_frames.append(
            widgets.HTML(
                f'<p><big>Row fields, with one record per row of the table.</big></p>\n'
                f'<p>Commonly used methods:</p>\n'
                f'<ul>'
                f'<li>{html_link("annotate", "https://hail.is/docs/0.2/hail.Table.html#hail.Table.annotate")}: '
                f'add new fields.</li>'
                f'<li>{html_link("filter", "https://hail.is/docs/0.2/hail.Table.html#hail.Table.filter")}: '
                f'filter rows of the table.</li>'
                f'<li>{html_link("aggregate", "https://hail.is/docs/0.2/hail.Table.html#hail.Table.aggregate")}: '
                f'aggregate over rows to produce a single value.</li>'
                f'</ul>'))
        if len(obj.key) > 0:
            row_frames.append(
                widgets.HTML(f'<p><big>Key: {list(obj.key)}<big><p>'))
        append_struct_frames(obj.row.dtype, row_frames)

        tab.children = [
            widgets.VBox(frames) for frames in [globals_frames, row_frames]
        ]
        tab.set_title(0, 'globals')
        tab.set_title(1, 'row')
        tab.selected_index = 1

        box = widgets.VBox([glob, rows])
        buttons = [glob, rows]
    else:
        assert isinstance(obj, hl.MatrixTable)
        glob = widgets.Button(description='globals',
                              layout=widgets.Layout(width='65px',
                                                    height='30px'))
        cols = widgets.Button(description='cols',
                              layout=widgets.Layout(width='200px',
                                                    height='30px'))
        rows = widgets.Button(description='rows',
                              layout=widgets.Layout(width='65px',
                                                    height='200px'))
        entries = widgets.Button(description='entries',
                                 layout=widgets.Layout(width='200px',
                                                       height='200px'))
        entries.style = selected_style

        globals_frames = []
        globals_frames.append(
            widgets.HTML(
                f'<p><big>Global fields, with one value in the dataset.</big></p>\n'
                f'<p>Commonly used methods:</p>\n'
                f'<ul>'
                f'<li>{html_link("annotate_globals()", "https://hail.is/docs/0.2/hail.MatrixTable.html#hail.MatrixTable.annotate_globals")}: '
                f'add new global fields.</li>'
                f'</ul>'))
        append_struct_frames(obj.globals.dtype, globals_frames)

        row_frames = []
        row_frames.append(
            widgets.HTML(
                f'<p><big>Row fields, with one record per row in the dataset.</big></p>\n'
                f'<p>Commonly used methods:</p>\n'
                f'<ul>'
                f'<li>{html_link("annotate_rows()", "https://hail.is/docs/0.2/hail.MatrixTable.html#hail.MatrixTable.annotate_rows")}: '
                f'add new row fields. This method supports {html_link("aggregation", "https://hail.is/docs/0.2/aggregators.html")}, '
                f'aggregating over entries to compute one result per row, e.g. computing the mean depth per variant.</li>'
                f'<li>{html_link("filter_rows()", "https://hail.is/docs/0.2/hail.MatrixTable.html#hail.MatrixTable.filter_rows")}: '
                f'filter rows in the matrix table.</li>'
                f'<li>{html_link("aggregate_rows()", "https://hail.is/docs/0.2/hail.MatrixTable.html#hail.MatrixTable.aggregate_rows")}: '
                f'aggregate over rows (not including entries or columns) to produce a single value, e.g. counting the number of loss-of-function variants.</li>'
                f'<li>{html_link("rows()", "https://hail.is/docs/0.2/hail.MatrixTable.html#hail.MatrixTable.rows")}: '
                f'return the rows as a Hail {html_link("Table", "https://hail.is/docs/0.2/hail.Table.html")}.</li>'
                f'</ul>'))
        if len(obj.row_key) > 0:
            row_frames.append(
                widgets.HTML(f'<p><big>Row key: {list(obj.row_key)}<big><p>'))
        append_struct_frames(obj.row.dtype, row_frames)

        col_frames = []
        col_frames.append(
            widgets.HTML(
                f'<p><big>Column fields, with one record per column in the dataset.</big></p>\n'
                f'<p>Commonly used methods:</p>\n'
                f'<ul>'
                f'<li>{html_link("annotate_cols()", "https://hail.is/docs/0.2/hail.MatrixTable.html#hail.MatrixTable.annotate_cols")}: '
                f'add new column fields. This method supports {html_link("aggregation", "https://hail.is/docs/0.2/aggregators.html")}, '
                f'aggregating over entries to compute one result per column, e.g. computing the mean depth per sample.</li>'
                f'<li>{html_link("filter_cols()", "https://hail.is/docs/0.2/hail.MatrixTable.html#hail.MatrixTable.filter_cols")}: '
                f'filter columns in the matrix table.</li>'
                f'<li>{html_link("aggregate_cols()", "https://hail.is/docs/0.2/hail.MatrixTable.html#hail.MatrixTable.aggregate_cols")}: '
                f'aggregate over columns (not including entries or rows) to produce a single value, e.g. counting the number of samples with case status.</li>'
                f'<li>{html_link("cols()", "https://hail.is/docs/0.2/hail.MatrixTable.html#hail.MatrixTable.cols")}: '
                f'return the columns as a Hail {html_link("Table", "https://hail.is/docs/0.2/hail.Table.html")}.'
                f'</li>'
                f'</ul>'))
        if len(obj.col_key) > 0:
            col_frames.append(
                widgets.HTML(
                    f'<p><big>Column key: {list(obj.col_key)}<big><p>'))
        append_struct_frames(obj.col.dtype, col_frames)

        entry_frames = []
        entry_frames.append(
            widgets.HTML(
                f'<p><big>Entry fields, with one record per (row, column) pair in the dataset.</big></p>\n'
                f'<p>Commonly used methods:</p>\n'
                f'<ul>'
                f'<li>{html_link("annotate_entries()", "https://hail.is/docs/0.2/hail.MatrixTable.html#hail.MatrixTable.annotate_entries")}: '
                f'add new entry fields.</li>'
                f'<li>{html_link("filter_entries()", "https://hail.is/docs/0.2/hail.MatrixTable.html#hail.MatrixTable.filter_entries")}: '
                f'filter entries in the matrix table, removing them from downstream operations, like aggregations.</li>'
                f'<li>{html_link("aggregate_entries", "https://hail.is/docs/0.2/hail.MatrixTable.html#hail.MatrixTable.aggregate_entries")}: '
                f'aggregate over entries to produce a single value, e.g. computing mean depth across an entire dataset.</li>'
                f'</ul>'))
        append_struct_frames(obj.entry.dtype, entry_frames)

        tab.children = [
            widgets.VBox(frames) for frames in
            [globals_frames, row_frames, col_frames, entry_frames]
        ]
        tab.set_title(0, 'globals')
        tab.set_title(1, 'row')
        tab.set_title(2, 'col')
        tab.set_title(3, 'entry')
        tab.selected_index = 3

        box = widgets.VBox(
            [widgets.HBox([glob, cols]),
             widgets.HBox([rows, entries])])
        buttons = [glob, rows, cols, entries]

    selection_handler = widgets.IntText(tab.selected_index)
    button_idx = dict(zip(buttons, range(len(buttons))))

    def handle_selection(x):
        if x['name'] == 'value' and x['type'] == 'change':
            buttons[x['old']].style = base_style
            selection = x['new']
            buttons[selection].style = selected_style
            tab.selected_index = selection

    selection_handler.observe(handle_selection)
    widgets.jslink((tab, 'selected_index'), (selection_handler, 'value'))

    def button_action(b):
        selection_handler.value = button_idx[b]

    for button in button_idx:
        button.on_click(button_action)

    display(box, tab)
Beispiel #25
0
def cost_display(n_days=7):

    users = widgets.IntText(value=8, description='Number of total users')
    storage_per_user = widgets.IntText(value=10,
                                       description='Storage per user (GB)')
    mem_per_user = widgets.IntText(value=2, description="RAM per user (GB)")
    machines = widgets.Dropdown(
        description='Machine',
        options=machines_list['Machine type'].values.tolist())
    persistent = widgets.Dropdown(description="Persistent Storage?",
                                  options={
                                      'HDD': 'hdd',
                                      'SSD': 'ssd'
                                  },
                                  value='hdd')
    autoscaling = widgets.Checkbox(value=False, description='Autoscaling?')
    text_avg_num_machine = widgets.Text(value='',
                                        description='Average # Machines:')
    text_cost_machine = widgets.Text(value='', description='Machine Cost:')
    text_cost_storage = widgets.Text(value='', description='Storage Cost:')
    text_cost_total = widgets.Text(value='', description='Total Cost:')

    hr = widgets.HTML(value="---")

    # Define axes limits
    y_max = 100.
    date_stop, date_range = create_date_range(n_days)

    # Create axes and extra variables for the viz
    xs_hd = DateScale(
        min=date_start,
        max=date_stop,
    )
    ys_hd = LinearScale(min=0., max=y_max)

    # Shading for weekends
    is_weekend = np.where([ii in [6, 7] for ii in date_range.dayofweek], 1, 0)
    is_weekend = is_weekend * (float(y_max) + 50.)
    is_weekend[is_weekend == 0] = -10
    line_fill = Lines(x=date_range,
                      y=is_weekend,
                      scales={
                          'x': xs_hd,
                          'y': ys_hd
                      },
                      colors=['black'],
                      fill_opacities=[.2],
                      fill='bottom')

    # Set up hand draw widget
    line_hd = Lines(x=date_range,
                    y=10 * np.ones(len(date_range)),
                    scales={
                        'x': xs_hd,
                        'y': ys_hd
                    },
                    colors=['#E46E2E'])
    line_users = Lines(x=date_range,
                       y=10 * np.ones(len(date_range)),
                       scales={
                           'x': xs_hd,
                           'y': ys_hd
                       },
                       colors=['#e5e5e5'])
    line_autoscale = Lines(x=date_range,
                           y=10 * np.ones(len(date_range)),
                           scales={
                               'x': xs_hd,
                               'y': ys_hd
                           },
                           colors=['#000000'])
    handdraw = HandDraw(lines=line_hd)
    xax = Axis(scale=xs_hd,
               label='Day',
               grid_lines='none',
               tick_format='%b %d')
    yax = Axis(scale=ys_hd,
               label='Numer of Users',
               orientation='vertical',
               grid_lines='none')
    # FIXME add `line_autoscale` when autoscale is enabled
    fig = Figure(marks=[line_fill, line_hd, line_users],
                 axes=[xax, yax],
                 interaction=handdraw)

    def _update_cost(change):
        # Pull values from the plot
        max_users = max(handdraw.lines.y)
        max_buffer = max_users * 1.05  # 5% buffer
        line_users.y = [max_buffer] * len(handdraw.lines.y)
        if max_users > users.value:
            users.value = max_users

        autoscaled_users = autoscale(handdraw.lines.y)
        line_autoscale.y = autoscaled_users

        # Calculate costs
        active_machine = machines_list[machines_list['Machine type'] ==
                                       machines.value]
        machine_cost = active_machine['Price (USD / hr)'].values.astype(
            float) * 24  # To make it cost per day
        users_for_cost = autoscaled_users if autoscaling.value is True else [
            max_buffer
        ] * len(handdraw.lines.y)
        num_machines = calculate_machines_needed(users_for_cost,
                                                 mem_per_user.value,
                                                 active_machine)
        avg_num_machines = np.mean(num_machines)
        cost_machine = integrate_cost(num_machines, machine_cost)
        cost_storage = integrate_cost(
            num_machines,
            storage_cost[persistent.value] * storage_per_user.value)
        cost_total = cost_machine + cost_storage

        # Set the values
        for iwidget, icost in [(text_cost_machine, cost_machine),
                               (text_cost_storage, cost_storage),
                               (text_cost_total, cost_total),
                               (text_avg_num_machine, avg_num_machines)]:
            if iwidget is not text_avg_num_machine:
                icost = locale.currency(icost, grouping=True)
            else:
                icost = '{:.2f}'.format(icost)
            iwidget.value = icost

        # Set the color
        if autoscaling.value is True:
            line_autoscale.colors = ['#000000']
            line_users.colors = ['#e5e5e5']
        else:
            line_autoscale.colors = ['#e5e5e5']
            line_users.colors = ['#000000']

    line_hd.observe(_update_cost, names='y')
    # autoscaling.observe(_update_cost)  # FIXME Uncomment when we implement autoscaling
    persistent.observe(_update_cost)
    machines.observe(_update_cost)
    storage_per_user.observe(_update_cost)
    mem_per_user.observe(_update_cost)

    # Show it
    fig.title = 'Draw your usage pattern over time.'
    # FIXME autoscaling when it's ready
    display(users, machines, mem_per_user, storage_per_user, persistent, fig,
            hr, text_cost_machine, text_avg_num_machine, text_cost_storage,
            text_cost_total)
    return fig
Beispiel #26
0
    def old_initiate(self):

        tab_children = []
        ###########################
        # data 1 box
        d1_vbox_childs = []
        ##
        ###
        d1_button_next = widgets.Button(description='next measurement')
        d1_button_prev = widgets.Button(description='prev measurement')

        d1_button_next.on_click(self.on_d1_botton_next)
        d1_button_prev.on_click(self.on_d1_botton_prev)

        d1_box_h_1 = widgets.HBox([d1_button_prev, d1_button_next])
        ###
        d1_vbox_childs.append(d1_box_h_1)

        ##
        ###
        d1_text_path = widgets.Text(placeholder='path name', disabled=False)
        self.d1_text_path = d1_text_path
        d1_vbox_childs.append(d1_text_path)

        ##
        d1_vbox = widgets.VBox(d1_vbox_childs)
        tab_children.append({'element': d1_vbox, 'title': 'iMet'})

        ############################
        # data 2 box
        d2_vbox_childs = []
        ##
        ###
        d2_button_next = widgets.Button(description='next measurement')
        d2_button_prev = widgets.Button(description='prev measurement')

        self.d2_dropdown_fnames = widgets.Dropdown(
            options=[
                1
            ],  #[i.name for i in self.controller.data.dataset2.path2data_list],
            value=1,  #self.controller.data.dataset2.path2active.name,
            #     description='N',
            disabled=False,
        )

        d2_button_next.on_click(self.on_d2_botton_next)
        d2_button_prev.on_click(self.on_d2_botton_prev)
        self.d2_dropdown_fnames.observe(self.on_change_d2_dropdown_fnames)

        d2_box_h_1 = widgets.HBox(
            [d2_button_prev, d2_button_next, self.d2_dropdown_fnames])
        ###
        d2_vbox_childs.append(d2_box_h_1)

        ##
        ###
        # text field showing the path
        d2_text_path = widgets.Text(placeholder='path name', disabled=False)
        self.d2_text_path = d2_text_path

        d2_vbox_childs.append(d2_text_path)

        ##
        d2_vbox = widgets.VBox(d2_vbox_childs)
        tab_children.append({'element': d2_vbox, 'title': 'POPS'})

        # others box

        # Tab
        tab = widgets.Tab([child['element'] for child in tab_children])
        for e, child in enumerate(tab_children):
            tab.set_title(e, child['title'])

        # accordeon

        self.accordeon_assigned = widgets.Valid(
            value=False,
            description='bound?',
        )

        self.dropdown_popssn = widgets.Dropdown(
            options=['00', '14', '18'],
            # value='2',
            description='popssn',
            disabled=False,
        )

        self.inttext_deltat = widgets.IntText(value=0,
                                              description='deltat',
                                              disabled=False)
        self.inttext_deltat.observe(self.on_inttext_deltat)

        self.dropdown_gps_bar_bad = widgets.Dropdown(
            options=[
                'gps', 'baro', 'bad', 'bad_but_usable_gps',
                'bad_but_usable_baro'
            ],
            value='gps',
            description='which alt to use:',
            disabled=False,
        )

        self.button_bind_measurements = widgets.ToggleButton(
            description='bind/unbind measurements')
        # button_bind_measurements.on_click(self.deprecated_on_button_bind_measurements)
        self.button_bind_measurements.observe(self.on_button_bind_measurements)

        accordon_box = widgets.VBox([
            self.accordeon_assigned, self.dropdown_popssn, self.inttext_deltat,
            self.dropdown_gps_bar_bad, self.button_bind_measurements
        ])
        accordion_children = [accordon_box]
        accordion = widgets.Accordion(children=accordion_children)
        accordion.set_title(0, 'do_stuff')

        # messages
        self.messages = widgets.Textarea('\n'.join(self.controller._message),
                                         layout={'width': '100%'})
        # message_box = widgets.HBox([self.messages])
        # OverVbox

        overVbox = widgets.VBox([tab, accordion, self.messages])
        display(overVbox)
        ####################
        self.update_d1()
        self.update_d2()
        self.update_accordeon()
Beispiel #27
0
    def slider(self, figsize=(10, 10), **kw):
        """
        Navigate the simulation using a slider

        Parameters :
        ------------
        figsize: tuple
            Size of the figures

        kw: dict
            Extra arguments to pass to matplotlib's imshow
        """

        # -----------------------
        # Define useful functions
        # -----------------------

        def refresh_field(force=False):
            "Refresh the current field figure"

            # Determine whether to do the refresh
            do_refresh = False
            if (self.avail_fields is not None):
                if force == True or fld_refresh_toggle.value == True:
                    do_refresh = True
            # Do the refresh
            if do_refresh == True:
                plt.figure(fld_figure_button.value, figsize=figsize)
                plt.clf()

                # When working in inline mode, in an ipython notebook,
                # clear the output (prevents the images from stacking
                # in the notebook)
                if 'inline' in matplotlib.get_backend():
                    clear_output()

                if fld_use_button.value == True:
                    i_power = fld_magnitude_button.value
                    vmin = fld_range_button.value[0] * 10**i_power
                    vmax = fld_range_button.value[1] * 10**i_power
                else:
                    vmin = None
                    vmax = None

                self.get_field(t=self.current_t,
                               output=False,
                               plot=True,
                               field=fieldtype_button.value,
                               coord=coord_button.value,
                               m=convert_to_int(mode_button.value),
                               slicing=slicing_button.value,
                               theta=theta_button.value,
                               slicing_dir=slicing_dir_button.value,
                               vmin=vmin,
                               vmax=vmax,
                               cmap=fld_color_button.value)

        def refresh_ptcl(force=False):
            "Refresh the current particle figure"

            # Determine whether to do the refresh
            do_refresh = False
            if self.avail_species is not None:
                if force == True or ptcl_refresh_toggle.value == True:
                    do_refresh = True
            # Do the refresh
            if do_refresh == True:
                plt.figure(ptcl_figure_button.value, figsize=figsize)
                plt.clf()

                # When working in inline mode, in an ipython notebook,
                # clear the output (prevents the images from stacking
                # in the notebook)
                if 'inline' in matplotlib.get_backend():
                    clear_output()

                if ptcl_use_button.value == True:
                    i_power = ptcl_magnitude_button.value
                    vmin = ptcl_range_button.value[0] * 10**i_power
                    vmax = ptcl_range_button.value[1] * 10**i_power
                else:
                    vmin = None
                    vmax = None

                if ptcl_yaxis_button.value == 'None':
                    # 1D histogram
                    self.get_particle(t=self.current_t,
                                      output=False,
                                      var_list=[ptcl_xaxis_button.value],
                                      select=ptcl_select_widget.to_dict(),
                                      species=ptcl_species_button.value,
                                      plot=True,
                                      vmin=vmin,
                                      vmax=vmax,
                                      cmap=ptcl_color_button.value,
                                      nbins=ptcl_bins_button.value)
                else:
                    # 2D histogram
                    self.get_particle(t=self.current_t,
                                      output=False,
                                      var_list=[
                                          ptcl_xaxis_button.value,
                                          ptcl_yaxis_button.value
                                      ],
                                      select=ptcl_select_widget.to_dict(),
                                      species=ptcl_species_button.value,
                                      plot=True,
                                      vmin=vmin,
                                      vmax=vmax,
                                      cmap=ptcl_color_button.value,
                                      nbins=ptcl_bins_button.value)

        def refresh_ptcl_now(b):
            "Refresh the particles immediately"
            refresh_ptcl(force=True)

        def refresh_fld_now(b):
            "Refresh the fields immediately"
            refresh_field(force=True)

        def change_t(name, value):
            "Plot the result at the required time"
            self.current_t = 1.e-15 * value
            refresh_field()
            refresh_ptcl()

        def step_fw(b):
            "Plot the result one iteration further"
            if self.current_i < len(self.t) - 1:
                self.current_t = self.t[self.current_i + 1]
            else:
                print("Reached last iteration.")
                self.current_t = self.t[self.current_i]
            slider.value = self.current_t * 1.e15

        def step_bw(b):
            "Plot the result one iteration before"
            if self.current_t > 0:
                self.current_t = self.t[self.current_i - 1]
            else:
                print("Reached first iteration.")
                self.current_t = self.t[self.current_i]
            slider.value = self.current_t * 1.e15

        # ---------------
        # Define widgets
        # ---------------

        # Slider
        slider = widgets.FloatSlider(
            min=math.ceil(1.e15 * self.tmin),
            max=math.ceil(1.e15 * self.tmax),
            step=math.ceil(1.e15 * (self.tmax - self.tmin)) / 20.,
            description="t (fs)")
        slider.on_trait_change(change_t, 'value')

        # Forward button
        button_p = widgets.Button(description="+")
        button_p.on_click(step_fw)

        # Backward button
        button_m = widgets.Button(description="-")
        button_m.on_click(step_bw)

        # Display the time widgets
        container = widgets.HBox(children=[button_m, button_p, slider])
        display(container)

        # Field widgets
        # -------------
        if (self.avail_fields is not None):

            # Field type
            # ----------
            # Field button
            fieldtype_button = widgets.ToggleButtons(
                description='Field:', options=sorted(self.avail_fields.keys()))
            fieldtype_button.on_trait_change(refresh_field)

            # Coord button
            if self.geometry == "thetaMode":
                coord_button = widgets.ToggleButtons(
                    description='Coord:', options=['x', 'y', 'z', 'r', 't'])
            elif self.geometry in ["2dcartesian", "3dcartesian"]:
                coord_button = widgets.ToggleButtons(description='Coord:',
                                                     options=['x', 'y', 'z'])
            coord_button.on_trait_change(refresh_field)
            # Mode and theta button (for thetaMode)
            mode_button = widgets.ToggleButtons(description='Mode:',
                                                options=self.avail_circ_modes)
            mode_button.on_trait_change(refresh_field)
            theta_button = widgets.FloatSlider(width=140,
                                               value=0.,
                                               description=r'Theta:',
                                               min=-math.pi / 2,
                                               max=math.pi / 2)
            theta_button.on_trait_change(refresh_field)
            # Slicing buttons (for 3D)
            slicing_dir_button = widgets.ToggleButtons(
                value='y',
                description='Slicing direction:',
                options=['x', 'y', 'z'])
            slicing_dir_button.on_trait_change(refresh_field)
            slicing_button = widgets.FloatSlider(width=150,
                                                 description='Slicing:',
                                                 min=-1.,
                                                 max=1.,
                                                 value=0.)
            slicing_button.on_trait_change(refresh_field)

            # Plotting options
            # ----------------
            # Figure number
            fld_figure_button = widgets.IntText(description='Figure ',
                                                value=0,
                                                width=50)
            # Range of values
            fld_range_button = widgets.FloatRangeSlider(min=-10,
                                                        max=10,
                                                        width=220)
            fld_range_button.on_trait_change(refresh_field)
            # Order of magnitude
            fld_magnitude_button = widgets.IntText(description='x 10^',
                                                   value=9,
                                                   width=50)
            fld_magnitude_button.on_trait_change(refresh_field)
            # Use button
            fld_use_button = widgets.Checkbox(description=' Use this range',
                                              value=False)
            fld_use_button.on_trait_change(refresh_field)
            # Colormap button
            fld_color_button = widgets.Select(options=sorted(
                plt.cm.datad.keys()),
                                              height=50,
                                              width=200,
                                              value='jet')
            fld_color_button.on_trait_change(refresh_field)
            # Resfresh buttons
            fld_refresh_toggle = widgets.ToggleButton(
                description='Always refresh', value=True)
            fld_refresh_button = widgets.Button(description='Refresh now!')
            fld_refresh_button.on_click(refresh_fld_now)

            # Containers
            # ----------
            # Field type container
            if self.geometry == "thetaMode":
                container_fields = widgets.VBox(width=260,
                                                children=[
                                                    fieldtype_button,
                                                    coord_button, mode_button,
                                                    theta_button
                                                ])
            elif self.geometry == "2dcartesian":
                container_fields = widgets.VBox(
                    width=260, children=[fieldtype_button, coord_button])
            elif self.geometry == "3dcartesian":
                container_fields = widgets.VBox(width=260,
                                                children=[
                                                    fieldtype_button,
                                                    coord_button,
                                                    slicing_dir_button,
                                                    slicing_button
                                                ])
            # Plotting options container
            container_fld_plots = widgets.VBox(width=260,
                                               children=[
                                                   fld_figure_button,
                                                   fld_range_button,
                                                   widgets.HBox(children=[
                                                       fld_magnitude_button,
                                                       fld_use_button
                                                   ],
                                                                height=50),
                                                   fld_color_button
                                               ])
            # Accordion for the field widgets
            accord1 = widgets.Accordion(
                children=[container_fields, container_fld_plots])
            accord1.set_title(0, 'Field type')
            accord1.set_title(1, 'Plotting options')
            # Complete field container
            container_fld = widgets.VBox(
                width=300,
                children=[
                    accord1,
                    widgets.HBox(
                        children=[fld_refresh_toggle, fld_refresh_button])
                ])

        # Particle widgets
        # ----------------
        if (self.avail_species is not None):

            # Particle quantities
            # -------------------
            # Species selection
            ptcl_species_button = widgets.Dropdown(width=250,
                                                   options=self.avail_species)
            ptcl_species_button.on_trait_change(refresh_ptcl)
            # Remove charge and mass (less interesting)
            avail_ptcl_quantities = [ q for q in self.avail_ptcl_quantities \
                        if (q in ['charge', 'mass'])==False ]
            # Particle quantity on the x axis
            ptcl_xaxis_button = widgets.ToggleButtons(
                value='z', options=avail_ptcl_quantities)
            ptcl_xaxis_button.on_trait_change(refresh_ptcl)
            # Particle quantity on the y axis
            ptcl_yaxis_button = widgets.ToggleButtons(
                value='x', options=avail_ptcl_quantities + ['None'])
            ptcl_yaxis_button.on_trait_change(refresh_ptcl)

            # Particle selection
            # ------------------
            # 3 selection rules at maximum
            ptcl_select_widget = ParticleSelectWidget(3, avail_ptcl_quantities,
                                                      refresh_ptcl)

            # Plotting options
            # ----------------
            # Figure number
            ptcl_figure_button = widgets.IntText(description='Figure ',
                                                 value=1,
                                                 width=50)
            # Number of bins
            ptcl_bins_button = widgets.IntSlider(description='nbins:',
                                                 min=50,
                                                 max=300,
                                                 value=100,
                                                 width=150)
            ptcl_bins_button.on_trait_change(refresh_ptcl)
            # Colormap button
            ptcl_color_button = widgets.Select(options=sorted(
                plt.cm.datad.keys()),
                                               height=50,
                                               width=200,
                                               value='Blues')
            ptcl_color_button.on_trait_change(refresh_ptcl)
            # Range of values
            ptcl_range_button = widgets.FloatRangeSlider(min=0,
                                                         max=10,
                                                         width=220,
                                                         value=(0, 5))
            ptcl_range_button.on_trait_change(refresh_ptcl)
            # Order of magnitude
            ptcl_magnitude_button = widgets.IntText(description='x 10^',
                                                    value=9,
                                                    width=50)
            ptcl_magnitude_button.on_trait_change(refresh_ptcl)
            # Use button
            ptcl_use_button = widgets.Checkbox(description=' Use this range',
                                               value=False)
            ptcl_use_button.on_trait_change(refresh_ptcl)
            # Resfresh buttons
            ptcl_refresh_toggle = widgets.ToggleButton(
                description='Always refresh', value=True)
            ptcl_refresh_button = widgets.Button(description='Refresh now!')
            ptcl_refresh_button.on_click(refresh_ptcl_now)

            # Containers
            # ----------
            # Particle quantity container
            container_ptcl_quantities = widgets.VBox(width=310,
                                                     children=[
                                                         ptcl_species_button,
                                                         ptcl_xaxis_button,
                                                         ptcl_yaxis_button
                                                     ])
            # Particle selection container
            container_ptcl_select = ptcl_select_widget.to_container()
            # Plotting options container
            container_ptcl_plots = widgets.VBox(width=310,
                                                children=[
                                                    ptcl_figure_button,
                                                    ptcl_bins_button,
                                                    ptcl_range_button,
                                                    widgets.HBox(children=[
                                                        ptcl_magnitude_button,
                                                        ptcl_use_button
                                                    ],
                                                                 height=50),
                                                    ptcl_color_button
                                                ])
            # Accordion for the field widgets
            accord2 = widgets.Accordion(children=[
                container_ptcl_quantities, container_ptcl_select,
                container_ptcl_plots
            ])
            accord2.set_title(0, 'Particle quantities')
            accord2.set_title(1, 'Particle selection')
            accord2.set_title(2, 'Plotting options')
            # Complete particle container
            container_ptcl = widgets.VBox(
                width=370,
                children=[
                    accord2,
                    widgets.HBox(
                        children=[ptcl_refresh_toggle, ptcl_refresh_button])
                ])

        # Global container
        if (self.avail_fields is not None) and \
          (self.avail_species is not None):
            global_container = widgets.HBox(
                children=[container_fld, container_ptcl])
            display(global_container)
        elif self.avail_species is None:
            display(container_fld)
        elif self.avail_fields is None:
            display(container_ptcl)
Beispiel #28
0
    def slider(self,
               figsize=(6, 5),
               exclude_particle_records=['charge', 'mass'],
               **kw):
        """
        Navigate the simulation using a slider

        Parameters:
        -----------
        figsize: tuple
            Size of the figures

        exclude_particle_records: list of strings
            List of particle quantities that should not be displayed
            in the slider (typically because they are less interesting)

        kw: dict
            Extra arguments to pass to matplotlib's imshow (e.g. cmap, etc.).
            This will be applied both to the particle plots and field plots.
            Note that `kw` sets the initial plotting options, but the user
            can then still modify these options through the slider interface.
        """
        # Check that the dependencies have been installed
        if not dependencies_installed:
            raise RuntimeError(
                "Failed to load the openPMD-viewer slider.\n"
                "(Make sure that ipywidgets and matplotlib are installed.)")

        # -----------------------
        # Define useful functions
        # -----------------------

        def refresh_field(change=None, force=False):
            """
            Refresh the current field figure

            Parameters :
            ------------
            change: dictionary
                Dictionary passed by the widget to a callback functions
                whenever a change of a widget happens
                (see docstring of ipywidgets.Widget.observe)
                This is mainline a place holder ; not used in this function

            force: bool
                Whether to force the update
            """
            # Determine whether to do the refresh
            do_refresh = False
            if (self.avail_fields is not None):
                if force or fld_refresh_toggle.value:
                    do_refresh = True
            # Do the refresh
            if do_refresh:
                plt.figure(fld_figure_button.value, figsize=figsize)
                plt.clf()

                # When working in inline mode, in an ipython notebook,
                # clear the output (prevents the images from stacking
                # in the notebook)
                if 'inline' in matplotlib.get_backend():
                    if ipywidgets_version < 7:
                        clear_output()
                    else:
                        import warnings
                        warnings.warn(
                            "\n\nIt seems that you are using ipywidgets 7 and "
                            "`%matplotlib inline`. \nThis can cause issues when "
                            "using `slider`.\nIn order to avoid this, you "
                            "can either:\n- use `%matplotlib notebook`\n- or "
                            "downgrade to ipywidgets 6 (with `pip` or `conda`).",
                            UserWarning)

                # Handle plotting options
                kw_fld = kw.copy()
                vmin, vmax = fld_color_button.get_range()
                kw_fld['vmin'] = vmin
                kw_fld['vmax'] = vmax
                kw_fld['cmap'] = fld_color_button.cmap.value
                # Determine range of the plot from widgets
                plot_range = [
                    fld_hrange_button.get_range(),
                    fld_vrange_button.get_range()
                ]

                # Call the method get_field
                self.get_field(iteration=self.current_iteration,
                               output=False,
                               plot=True,
                               field=fieldtype_button.value,
                               coord=coord_button.value,
                               m=convert_to_int(mode_button.value),
                               slicing=slicing_button.value,
                               theta=theta_button.value,
                               slicing_dir=slicing_dir_button.value,
                               plot_range=plot_range,
                               **kw_fld)

        def refresh_ptcl(change=None, force=False):
            """
            Refresh the current particle figure

            Parameters :
            ------------
            change: dictionary
                Dictionary passed by the widget to a callback functions
                whenever a change of a widget happens
                (see docstring of ipywidgets.Widget.observe)
                This is mainline a place holder ; not used in this function

            force: bool
                Whether to force the update
            """
            # Determine whether to do the refresh
            do_refresh = False
            if self.avail_species is not None:
                if force or ptcl_refresh_toggle.value:
                    do_refresh = True
            # Do the refresh
            if do_refresh:
                plt.figure(ptcl_figure_button.value, figsize=figsize)
                plt.clf()

                # When working in inline mode, in an ipython notebook,
                # clear the output (prevents the images from stacking
                # in the notebook)
                if 'inline' in matplotlib.get_backend():
                    clear_output()

                # Handle plotting options
                kw_ptcl = kw.copy()
                vmin, vmax = ptcl_color_button.get_range()
                kw_ptcl['vmin'] = vmin
                kw_ptcl['vmax'] = vmax
                kw_ptcl['cmap'] = ptcl_color_button.cmap.value
                # Determine range of the plot from widgets
                plot_range = [
                    ptcl_hrange_button.get_range(),
                    ptcl_vrange_button.get_range()
                ]

                if ptcl_yaxis_button.value == 'None':
                    # 1D histogram
                    self.get_particle(
                        iteration=self.current_iteration,
                        output=False,
                        var_list=[ptcl_xaxis_button.value],
                        select=ptcl_select_widget.to_dict(),
                        species=ptcl_species_button.value,
                        plot=True,
                        nbins=ptcl_bins_button.value,
                        plot_range=plot_range,
                        use_field_mesh=ptcl_use_field_button.value,
                        **kw_ptcl)
                else:
                    # 2D histogram
                    self.get_particle(
                        iteration=self.current_iteration,
                        output=False,
                        var_list=[
                            ptcl_xaxis_button.value, ptcl_yaxis_button.value
                        ],
                        select=ptcl_select_widget.to_dict(),
                        species=ptcl_species_button.value,
                        plot=True,
                        nbins=ptcl_bins_button.value,
                        plot_range=plot_range,
                        use_field_mesh=ptcl_use_field_button.value,
                        **kw_ptcl)

        def refresh_field_type(change):
            """
            Refresh the field type and disable the coordinates buttons
            if the field is scalar.

            Parameter
            ---------
            change: dictionary
                Dictionary passed by the widget to a callback functions
                whenever a change of a widget happens
                (see docstring of ipywidgets.Widget.observe)
            """
            if self.avail_fields[change['new']] == 'scalar':
                coord_button.disabled = True
            elif self.avail_fields[change['new']] == 'vector':
                coord_button.disabled = False
            refresh_field()

        def refresh_species(change=None):
            """
            Refresh the particle species buttons by populating them
            with the available records for the current species

            Parameter
            ---------
            change: dictionary
                Dictionary passed by the widget to a callback functions
                whenever a change of a widget happens
                (see docstring of ipywidgets.Widget.observe)
            """
            # Deactivate the particle refreshing to avoid callback
            # while modifying the widgets
            saved_refresh_value = ptcl_refresh_toggle.value
            ptcl_refresh_toggle.value = False

            # Get available records for this species
            avail_records = [
                q for q in self.avail_record_components[
                    ptcl_species_button.value]
                if q not in exclude_particle_records
            ]
            # Update the plotting buttons
            ptcl_xaxis_button.options = avail_records
            ptcl_yaxis_button.options = avail_records + ['None']
            if ptcl_xaxis_button.value not in ptcl_xaxis_button.options:
                ptcl_xaxis_button.value = avail_records[0]
            if ptcl_yaxis_button.value not in ptcl_yaxis_button.options:
                ptcl_yaxis_button.value = 'None'

            # Update the selection widgets
            for dropdown_button in ptcl_select_widget.quantity:
                dropdown_button.options = avail_records

            # Put back the previous value of the refreshing button
            ptcl_refresh_toggle.value = saved_refresh_value

        def change_iteration(change):
            "Plot the result at the required iteration"
            # Find the closest iteration
            self._current_i = abs(self.iterations - change['new']).argmin()
            self.current_iteration = self.iterations[self._current_i]
            refresh_field()
            refresh_ptcl()

        def step_fw(b):
            "Plot the result one iteration further"
            if self._current_i < len(self.t) - 1:
                self.current_iteration = self.iterations[self._current_i + 1]
            else:
                self.current_iteration = self.iterations[self._current_i]
            slider.value = self.current_iteration

        def step_bw(b):
            "Plot the result one iteration before"
            if self._current_i > 0:
                self.current_iteration = self.iterations[self._current_i - 1]
            else:
                self.current_iteration = self.iterations[self._current_i]
            slider.value = self.current_iteration

        # ---------------
        # Define widgets
        # ---------------

        # Slider
        iteration_min = self.iterations.min()
        iteration_max = self.iterations.max()
        step = max(int((iteration_max - iteration_min) / 20.), 1)
        slider = widgets.IntSlider(description="iteration",
                                   min=iteration_min,
                                   max=iteration_max + step,
                                   step=step)
        slider.observe(change_iteration, names='value', type='change')
        set_widget_dimensions(slider, width=500)

        # Forward button
        button_p = widgets.Button(description="+")
        set_widget_dimensions(button_p, width=40)
        button_p.on_click(step_fw)

        # Backward button
        button_m = widgets.Button(description="-")
        set_widget_dimensions(button_m, width=40)
        button_m.on_click(step_bw)

        # Display the time widgets
        container = widgets.HBox(children=[button_m, button_p, slider])
        display(container)

        # Field widgets
        # -------------
        if (self.avail_fields is not None):

            # Field type
            # ----------
            # Field button
            fieldtype_button = create_toggle_buttons(
                description='Field:', options=sorted(self.avail_fields.keys()))
            fieldtype_button.observe(refresh_field_type, 'value', 'change')

            # Coord button
            if self.geometry == "thetaMode":
                coord_button = create_toggle_buttons(
                    description='Coord:', options=['x', 'y', 'z', 'r', 't'])
            elif self.geometry in \
                    ["1dcartesian", "2dcartesian", "3dcartesian"]:
                coord_button = create_toggle_buttons(description='Coord:',
                                                     options=['x', 'y', 'z'])
            coord_button.observe(refresh_field, 'value', 'change')
            # Mode and theta button (for thetaMode)
            mode_button = create_toggle_buttons(description='Mode:',
                                                options=self.avail_circ_modes)
            mode_button.observe(refresh_field, 'value', 'change')
            theta_button = widgets.FloatSlider(value=0.,
                                               min=-math.pi / 2,
                                               max=math.pi / 2)
            set_widget_dimensions(theta_button, width=190)
            theta_button.observe(refresh_field, 'value', 'change')
            # Slicing buttons (for 3D)
            slicing_dir_button = create_toggle_buttons(
                value=self.axis_labels[0],
                options=self.axis_labels,
                description='Slice normal:')
            slicing_dir_button.observe(refresh_field, 'value', 'change')
            slicing_button = widgets.FloatSlider(min=-1., max=1., value=0.)
            set_widget_dimensions(slicing_button, width=180)
            slicing_button.observe(refresh_field, 'value', 'change')

            # Plotting options
            # ----------------
            # Figure number
            fld_figure_button = widgets.IntText(value=0)
            set_widget_dimensions(fld_figure_button, width=50)
            # Colormap button
            fld_color_button = ColorBarSelector(
                refresh_field,
                default_cmap=kw.get('cmap', 'viridis'),
                default_vmin=kw.get('vmin', -5.e9),
                default_vmax=kw.get('vmax', 5.e9))
            # Range buttons
            fld_hrange_button = RangeSelector(refresh_field,
                                              default_value=10.,
                                              title='Horizontal axis:')
            fld_vrange_button = RangeSelector(refresh_field,
                                              default_value=10.,
                                              title='Vertical axis:')
            # Refresh buttons
            fld_refresh_toggle = widgets.ToggleButton(
                description='Always refresh', value=True)
            fld_refresh_button = widgets.Button(description='Refresh now!')
            fld_refresh_button.on_click(partial(refresh_field, force=True))

            # Containers
            # ----------
            # Field type container
            if self.geometry == "thetaMode":
                container_fields = widgets.VBox(children=[
                    fieldtype_button, coord_button, mode_button,
                    add_description('Theta:', theta_button)
                ])
            elif self.geometry in ["1dcartesian", "2dcartesian"]:
                container_fields = widgets.VBox(
                    children=[fieldtype_button, coord_button])
            elif self.geometry == "3dcartesian":
                container_fields = widgets.VBox(children=[
                    fieldtype_button, coord_button, slicing_dir_button,
                    add_description("Slicing:", slicing_button)
                ])
            set_widget_dimensions(container_fields, width=330)
            # Plotting options container
            container_fld_cbar = fld_color_button.to_container()
            container_fld_hrange = fld_hrange_button.to_container()
            container_fld_vrange = fld_vrange_button.to_container()
            if self.geometry == "1dcartesian":
                container_fld_plots = widgets.VBox(children=[
                    add_description("<b>Figure:</b>", fld_figure_button),
                    container_fld_vrange, container_fld_hrange
                ])
            else:
                container_fld_plots = widgets.VBox(children=[
                    add_description("<b>Figure:</b>",
                                    fld_figure_button), container_fld_cbar,
                    container_fld_vrange, container_fld_hrange
                ])
            set_widget_dimensions(container_fld_plots, width=330)
            # Accordion for the field widgets
            accord1 = widgets.Accordion(
                children=[container_fields, container_fld_plots])
            accord1.set_title(0, 'Field type')
            accord1.set_title(1, 'Plotting options')
            # Complete field container
            container_fld = widgets.VBox(children=[
                accord1,
                widgets.HBox(children=[fld_refresh_toggle, fld_refresh_button])
            ])
            set_widget_dimensions(container_fld, width=370)

        # Particle widgets
        # ----------------
        if (self.avail_species is not None):

            # Particle quantities
            # -------------------
            # Species selection
            ptcl_species_button = widgets.Dropdown(options=self.avail_species)
            set_widget_dimensions(ptcl_species_button, width=250)
            ptcl_species_button.observe(refresh_species, 'value', 'change')
            # Get available records for this species
            avail_records = [
                q for q in self.avail_record_components[
                    ptcl_species_button.value]
                if q not in exclude_particle_records
            ]
            # Particle quantity on the x axis
            ptcl_xaxis_button = create_toggle_buttons(options=avail_records)
            ptcl_xaxis_button.observe(refresh_ptcl, 'value', 'change')
            # Particle quantity on the y axis
            ptcl_yaxis_button = create_toggle_buttons(options=avail_records +
                                                      ['None'],
                                                      value='None')
            ptcl_yaxis_button.observe(refresh_ptcl, 'value', 'change')

            # Particle selection
            # ------------------
            # 3 selection rules at maximum
            ptcl_select_widget = ParticleSelectWidget(3, avail_records,
                                                      refresh_ptcl)

            # Plotting options
            # ----------------
            # Figure number
            ptcl_figure_button = widgets.IntText(value=1)
            set_widget_dimensions(ptcl_figure_button, width=50)
            # Number of bins
            ptcl_bins_button = widgets.IntText(value=100)
            set_widget_dimensions(ptcl_bins_button, width=60)
            ptcl_bins_button.observe(refresh_ptcl, 'value', 'change')
            # Colormap button
            ptcl_color_button = ColorBarSelector(
                refresh_ptcl,
                default_cmap=kw.get('cmap', 'Blues'),
                default_vmin=kw.get('vmin', -5.e9),
                default_vmax=kw.get('vmax', 5.e9))
            # Range buttons
            ptcl_hrange_button = RangeSelector(refresh_ptcl,
                                               default_value=10.,
                                               title='Horizontal axis:')
            ptcl_vrange_button = RangeSelector(refresh_ptcl,
                                               default_value=10.,
                                               title='Vertical axis:')
            # Use field mesh buttons
            ptcl_use_field_button = widgets.ToggleButton(
                description=' Use field mesh', value=True)
            ptcl_use_field_button.observe(refresh_ptcl, 'value', 'change')
            # Resfresh buttons
            ptcl_refresh_toggle = widgets.ToggleButton(
                description='Always refresh', value=True)
            ptcl_refresh_button = widgets.Button(description='Refresh now!')
            ptcl_refresh_button.on_click(partial(refresh_ptcl, force=True))

            # Containers
            # ----------
            # Particle quantity container
            container_ptcl_quantities = widgets.VBox(children=[
                ptcl_species_button, ptcl_xaxis_button, ptcl_yaxis_button
            ])
            set_widget_dimensions(container_ptcl_quantities, width=310)
            # Particle selection container
            container_ptcl_select = ptcl_select_widget.to_container()
            # Plotting options container
            container_ptcl_fig = widgets.HBox(children=[
                add_description("<b>Figure:</b>", ptcl_figure_button),
                add_description("Bins:", ptcl_bins_button)
            ])
            container_ptcl_cbar = ptcl_color_button.to_container()
            container_ptcl_hrange = ptcl_hrange_button.to_container()
            container_ptcl_vrange = ptcl_vrange_button.to_container()
            container_ptcl_plots = widgets.VBox(children=[
                container_ptcl_fig, container_ptcl_cbar, container_ptcl_vrange,
                container_ptcl_hrange, ptcl_use_field_button
            ])
            set_widget_dimensions(container_ptcl_plots, width=310)
            # Accordion for the field widgets
            accord2 = widgets.Accordion(children=[
                container_ptcl_quantities, container_ptcl_select,
                container_ptcl_plots
            ])
            accord2.set_title(0, 'Particle quantities')
            accord2.set_title(1, 'Particle selection')
            accord2.set_title(2, 'Plotting options')
            # Complete particle container
            container_ptcl = widgets.VBox(children=[
                accord2,
                widgets.HBox(
                    children=[ptcl_refresh_toggle, ptcl_refresh_button])
            ])
            set_widget_dimensions(container_ptcl, width=370)

        # Global container
        if (self.avail_fields is not None) and \
                (self.avail_species is not None):
            global_container = widgets.HBox(
                children=[container_fld, container_ptcl])
            display(global_container)
        elif self.avail_species is None:
            display(container_fld)
        elif self.avail_fields is None:
            display(container_ptcl)
Beispiel #29
0
    def __init__(self, nmrproblem=None):

        super().__init__()

        if not isinstance(nmrproblem, nmrProblem.NMRproblem):
            self.nmrproblem = nmrproblem
            self.df = pd.DataFrame()
        else:
            self.nmrproblem = nmrproblem
            self.df = nmrproblem.df

        # create debug label widget for output
        self.debugLabel = widgets.Label(value="",
                                        layout=widgets.Layout(width="400px"))

        # create save problem widgets
        self.saveProblemButtonW = widgets.Button(description="Save Problem")

        # widgets to obtain problem working directory
        self.prDirW = widgets.Text(value='',
                                   placeholder='problem directory',
                                   description='problem directory',
                                   disabled=False)

        self.prDirB = widgets.Button(description='Set Directory')

        self.upload_problemdir = ipywidgets.widgets.FileUpload(
            multiple=True,
            description="Open Existing Problem ",
            description_tooltip="choose all files in problem directory",
            layout=widgets.Layout(width='300px'))

        self.problemNameL = widgets.Label(value="    Problem Name",
                                          layout=widgets.Layout(width='100px'))

        self.spacerL = widgets.Label(value="    ",
                                     layout=widgets.Layout(width='50px'))

        self.problemNameW = widgets.Text(value="Problem Name",
                                         description="",
                                         layout=widgets.Layout(width='150px'))

        self.newproblemB = widgets.Button(description="Start New Problem")

        self.prDirLayout = widgets.HBox([
            self.upload_problemdir, self.spacerL, self.problemNameL,
            self.problemNameW, self.spacerL, self.newproblemB
        ])

        # widgets to obtain info on the molecule
        # number and tye of atoms in molecule
        # number of proton resonances in molecule
        # number of carbon resonance in molecule
        self.moleculeAtomsW = widgets.Text(value='',
                                           placeholder='atoms in molecule',
                                           description='atoms',
                                           disabled=False)

        self.pGrpsW = widgets.IntText(value=1,
                                      placeholder='H1 groups in spectrum',
                                      description='H1 groups',
                                      disabled=False)

        self.cGrpsW = widgets.IntText(value=1,
                                      description='C13 groups',
                                      disabled=False)

        self.moleculesSubmitB = widgets.Button(description="Update Molecule")

        self.moleculeLayout = widgets.VBox([
            self.moleculeAtomsW, self.pGrpsW, self.cGrpsW,
            self.moleculesSubmitB
        ])

        # widgets to set 1D spectral parameters for proton and carbon
        self.pLabelW = widgets.Label("$^{1}H$")

        self.pSpecWidthW = widgets.FloatText(value=12.0,
                                             tooltip='proton spectral width',
                                             description='sw (ppm)',
                                             disabled=False)

        self.pObsFreqW = widgets.FloatText(value=400.0,
                                           description='obs (MHz)',
                                           disabled=False)

        self.pTofW = widgets.FloatText(value=5.0,
                                       description='tof (ppm)',
                                       diabled=False)

        self.pSizeW = widgets.IntText(value=32768,
                                      description='size (pts)',
                                      disabled=False)

        self.pLineBroadeningW = widgets.FloatText(value=0.5,
                                                  description='lb (Hz)',
                                                  disabled=False)

        self.cLabelW = widgets.Label("$^{13}C$")

        self.cSpecWidthW = widgets.FloatText(value=210.0,
                                             description='sw (ppm)',
                                             disabled=False)

        self.cObsFreqW = widgets.FloatText(value=100.0,
                                           description='obs (MHz)',
                                           disabled=False)

        self.cTofW = widgets.FloatText(value=5.0,
                                       description='tof (ppm)',
                                       diabled=False)

        self.cSizeW = widgets.IntText(value=32768,
                                      description='size (pts)',
                                      disabled=False)

        self.cLineBroadeningW = widgets.FloatText(value=0.5,
                                                  description='lb (Hz)',
                                                  disabled=False)

        self.specSubmitB = widgets.Button(description="Update Spectra")

        self.specLayout = widgets.HBox([
            widgets.VBox([
                self.pLabelW, self.pObsFreqW, self.pSpecWidthW, self.pTofW,
                self.pSizeW, self.pLineBroadeningW, self.specSubmitB
            ]),
            widgets.VBox([
                self.cLabelW, self.cObsFreqW, self.cSpecWidthW, self.cTofW,
                self.cSizeW, self.cLineBroadeningW
            ])
        ])

        self.old = 'All'
        self.new = 'ALL'

        self.toggleDF = widgets.ToggleButtons(
            options=['All', 'integrals-ppm', 'COSY', 'HSQC-HMBC'],
            description='Display:',
            disabled=False,
            button_style='',
            tooltips=[
                'Show full Dataframe', 'Show COSY Input',
                'Show HSQC/HMBC Input'
            ])

        self.sheet1 = ipysheet.from_dataframe(self.df)

        self.toggleDF.observe(self.toggleValue)

        self.dfWarningTextW = widgets.Label("Table Messages:  OK")
        self.dfUpdateTableB = widgets.Button(description="update table")
        self.dfRunAnalysisB = widgets.Button(description="update and run")

        self.dfButtonsLayout = widgets.HBox(
            [self.dfUpdateTableB, self.dfRunAnalysisB])

        self.dfLayout = widgets.VBox([
            self.toggleDF, self.dfWarningTextW, self.sheet1,
            self.dfButtonsLayout
        ])

        self.accordion = widgets.Accordion(children=[
            self.prDirLayout, self.moleculeLayout, self.specLayout,
            self.dfLayout
        ])

        self.accordion.set_title(0, "Problem Directory")
        self.accordion.set_title(1, "Molecule")
        self.accordion.set_title(2, "Spectroscopy")
        self.accordion.set_title(3, "DataSet")
        self.page1 = widgets.VBox(
            [self.accordion, self.saveProblemButtonW, self.debugLabel])

        self.H1C131DplotsLayout = widgets.VBox(
            [widgets.Output(), self.saveProblemButtonW])

        self.ymlTitle = widgets.HTML("yml description of problem")
        self.ymlText = widgets.Textarea(
            layout=widgets.Layout(width="400px", height="500px"))
        self.problemYML = widgets.VBox([self.ymlTitle, self.ymlText])

        self.children = [self.page1, self.H1C131DplotsLayout, self.problemYML]

        self.set_title(0, 'Problem Setup')
        self.set_title(1, 'Problem Plots')
        self.set_title(2, 'Problem YML')

        self.upload_problemdir.observe(
            lambda change: self.on_upload_problemdir(change), names='value')
        self.moleculesSubmitB.on_click(self.onButtonClicked)
        self.specSubmitB.on_click(self.onButtonClicked)
        self.dfUpdateTableB.on_click(self.onButtonClicked)
        self.dfRunAnalysisB.on_click(self.onButtonClicked)
        self.saveProblemButtonW.on_click(self.onButtonClicked)
        self.newproblemB.on_click(self.onButtonClicked)
Beispiel #30
0
    def __init__(
        self,
        input_data: Units,
        trials: pynwb.epoch.TimeIntervals = None,
        unit_index=0,
        unit_controller=None,
        ntt=1000,
    ):

        self.units = input_data

        super().__init__()

        if trials is None:
            self.trials = self.get_trials()
            if self.trials is None:
                self.children = [widgets.HTML("No trials present")]
                return
        else:
            self.trials = trials

        if unit_controller is None:
            self.unit_ids = self.units.id.data[:]
            n_units = len(self.unit_ids)
            self.unit_controller = widgets.Dropdown(
                options=[(str(self.unit_ids[x]), x) for x in range(n_units)],
                value=unit_index,
                description="unit",
                layout=Layout(width="200px"),
            )

        self.trial_event_controller = make_trial_event_controller(
            self.trials, layout=Layout(width="200px")
        )
        self.start_ft = widgets.FloatText(
            -0.5, step=0.1, description="start (s)", layout=Layout(width="200px"),
            description_tooltip = 'Start time for calculation before or after (negative or positive) the reference point (aligned to)'
        )
        
        self.end_ft = widgets.FloatText(
            1.0, step=0.1, description="end (s)", layout=Layout(width="200px"),
            description_tooltip = 'End time for calculation before or after (negative or positive) the reference point (aligned to).'
        )
        

        self.psth_type_radio = widgets.RadioButtons(
            options=["histogram", "gaussian"], layout=Layout(width="100px")
        )
        self.bins_ft = widgets.IntText(
            30, min=0, description="# bins", layout=Layout(width="150px")
        )
        self.gaussian_sd_ft = widgets.FloatText(
            0.05,
            min=0.001,
            description="sd (s)",
            layout=Layout(width="150px"),
            active=False,
            step=0.01,
        )

        self.gas = self.make_group_and_sort(window=False, control_order=False)

        self.controls = dict(
            ntt=fixed(ntt),
            index=self.unit_controller,
            end=self.end_ft,
            start=self.start_ft,
            start_label=self.trial_event_controller,
            gas=self.gas,
            plot_type=self.psth_type_radio,
            sigma_in_secs=self.gaussian_sd_ft,
            nbins=self.bins_ft
            # progress_bar=fixed(progress_bar)
        )

        out_fig = interactive_output(self.update, self.controls)

        self.children = [
            widgets.HBox(
                [
                    widgets.VBox(
                        [
                            self.gas,
                            widgets.HBox(
                                [
                                    self.psth_type_radio,
                                    widgets.VBox([self.gaussian_sd_ft, self.bins_ft]),
                                ]
                            ),
                        ]
                    ),
                    widgets.VBox(
                        [
                            self.unit_controller,
                            self.trial_event_controller,
                            self.start_ft,
                            self.end_ft,
                        ]
                    ),
                ]
            ),
            out_fig,
        ]