示例#1
0
文件: widgets.py 项目: Calysto/conx
 def make_controls(self):
     button_begin = Button(icon="fast-backward", layout=Layout(width='100%'))
     button_prev = Button(icon="backward", layout=Layout(width='100%'))
     button_next = Button(icon="forward", layout=Layout(width='100%'))
     button_end = Button(icon="fast-forward", layout=Layout(width='100%'))
     self.button_play = Button(icon="play", description="Play", layout=Layout(width="100%"))
     self.control_buttons = HBox([
         button_begin,
         button_prev,
         self.position_text,
         button_next,
         button_end,
         self.button_play,
     ], layout=Layout(width='100%', height="50px"))
     self.control_slider = IntSlider(description=self.title,
                                     continuous_update=False,
                                     min=0,
                                     max=max(self.length - 1, 0),
                                     value=0,
                                     style={"description_width": 'initial'},
                                     layout=Layout(width='100%'))
     ## Hook them up:
     button_begin.on_click(lambda button: self.goto("begin"))
     button_end.on_click(lambda button: self.goto("end"))
     button_next.on_click(lambda button: self.goto("next"))
     button_prev.on_click(lambda button: self.goto("prev"))
     self.button_play.on_click(self.toggle_play)
     self.control_slider.observe(self.update_slider_control, names='value')
     controls = VBox([HBox([self.control_slider, self.total_text], layout=Layout(height="40px")),
                      self.control_buttons], layout=Layout(width='100%'))
     controls.on_displayed(lambda widget: self.initialize())
     return controls
示例#2
0
class MultiProgressWidget(MultiProgressBar):
    """ Multiple progress bar Widget suitable for the notebook

    Displays multiple progress bars for a computation, split on computation
    type.

    See Also
    --------
    progress: User-level function <--- use this
    MultiProgress: Non-visualization component that contains most logic
    ProgressWidget: Single progress bar widget
    """
    def __init__(self, keys, scheduler=None, minimum=0, interval=0.1, func=key_split,
                 complete=False):
        super(MultiProgressWidget, self).__init__(keys, scheduler, func, interval, complete)
        from ipywidgets import VBox
        self.widget = VBox([])

    def make_widget(self, all):
        from ipywidgets import FloatProgress, HBox, VBox, HTML
        import cgi
        self.elapsed_time = HTML('')
        self.bars = {key: FloatProgress(min=0, max=1, description='', height = '10px')
                        for key in all}
        self.bar_texts = {key: HTML('', width = "140px") for key in all}
        self.bar_labels = {key: HTML('<div style=\"padding: 0px 10px 0px 10px; text-align:left; word-wrap: break-word;\">'
                                     + cgi.escape(key) + '</div>') for key in all}

        def key(kv):
            """ Order keys by most numerous, then by string name """
            return kv[::-1]

        key_order = [k for k, v in sorted(all.items(), key=key, reverse=True)]

        self.bar_widgets = VBox([ HBox([ self.bar_texts[key], self.bars[key], self.bar_labels[key] ]) for key in key_order ])
        self.widget.children = (self.elapsed_time, self.bar_widgets)

    def _ipython_display_(self, **kwargs):
        IOLoop.current().add_callback(self.listen)
        return self.widget._ipython_display_(**kwargs)

    def _draw_stop(self, remaining, status, exception=None, key=None, **kwargs):
        for k, v in remaining.items():
            if not v:
                self.bars[k].bar_style = 'success'

        """ TODO
        if status == 'error':
            self.bars[self.func(key)].bar_style = 'danger'
            self.elapsed_time.value = '<div style="padding: 0px 10px 5px 10px"><b>Warning:</b> the computation terminated due to an error after ' + format_time(self.elapsed) + '</div>'
        """

    def _draw_bar(self, remaining, all, status, **kwargs):
        if self.keys and not self.widget.children:
            self.make_widget(all)
        for k, ntasks in all.items():
            ndone = ntasks - remaining[k]
            self.elapsed_time.value = '<div style="padding: 0px 10px 5px 10px"><b>Elapsed time:</b> ' + format_time(self.elapsed) + '</div>'
            self.bars[k].value = ndone / ntasks if ntasks else 1.0
            self.bar_texts[k].value = '<div style="padding: 0px 10px 0px 10px; text-align: right">%d / %d</div>' % (ndone, ntasks)
示例#3
0
    def _make_repr_playground(self):
        vbox = VBox()
        children = []

        rep_names = REPRESENTATION_NAMES[:]
        excluded_names = ['ball+stick', 'distance']
        for name in excluded_names:
            rep_names.remove(name)

        repr_selection = Text(value='*')
        repr_selection.layout.width = default.DEFAULT_TEXT_WIDTH
        repr_selection_box  = HBox([Label('selection'), repr_selection])
        setattr(repr_selection_box, 'value', repr_selection.value)

        for index, name in enumerate(rep_names):
            button = ToggleButton(description=name)

            def make_func():
                def on_toggle_button_value_change(change, button=button):
                    selection = repr_selection.value
                    new = change['new'] # True/False
                    if new:
                        self._view.add_representation(button.description, selection=selection)
                    else:
                        self._view._remove_representations_by_name(button.description)
                return on_toggle_button_value_change

            button.observe(make_func(), names='value')
            children.append(button)

        button_clear = Button(description='clear', button_style='info',
                icon='fa-eraser')

        @button_clear.on_click
        def on_clear(button_clear):
            self._view.clear()
            for kid in children:
                # unselect
                kid.value = False

        vbox.children = children + [repr_selection, button_clear]
        _make_autofit(vbox)
        self.widget_quick_repr = vbox
        return self.widget_quick_repr
示例#4
0
    def __init__(self, keys, scheduler=None, interval='100ms',
                 complete=False, loop=None):
        super(ProgressWidget, self).__init__(keys, scheduler, interval,
                                             complete)

        from ipywidgets import FloatProgress, HBox, VBox, HTML
        self.elapsed_time = HTML('')
        self.bar = FloatProgress(min=0, max=1, description='')
        self.bar_text = HTML('')

        self.bar_widget = HBox([self.bar_text, self.bar])
        self.widget = VBox([self.elapsed_time, self.bar_widget])
示例#5
0
class ProgressWidget(ProgressBar):
    """ ProgressBar that uses an IPython ProgressBar widget for the notebook

    See Also
    --------
    progress: User function
    TextProgressBar: Text version suitable for the console
    """

    def __init__(self, keys, scheduler=None, interval='100ms',
                 complete=False, loop=None):
        super(ProgressWidget, self).__init__(keys, scheduler, interval,
                                             complete)

        from ipywidgets import FloatProgress, HBox, VBox, HTML
        self.elapsed_time = HTML('')
        self.bar = FloatProgress(min=0, max=1, description='')
        self.bar_text = HTML('')

        self.bar_widget = HBox([self.bar_text, self.bar])
        self.widget = VBox([self.elapsed_time, self.bar_widget])

    def _ipython_display_(self, **kwargs):
        IOLoop.current().add_callback(self.listen)
        return self.widget._ipython_display_(**kwargs)

    def _draw_stop(self, remaining, status, exception=None, **kwargs):
        if status == 'error':
            self.bar.bar_style = 'danger'
            self.elapsed_time.value = (
                    '<div style="padding: 0px 10px 5px 10px"><b>Exception</b> '
                    '<tt>' + repr(exception) + '</tt>:' +
                    format_time(self.elapsed) + ' ' +
                    '</div>'
            )
        elif not remaining:
            self.bar.bar_style = 'success'
            self.elapsed_time.value = '<div style="padding: 0px 10px 5px 10px"><b>Finished:</b> ' + \
                format_time(self.elapsed) + '</div>'

    def _draw_bar(self, remaining, all, **kwargs):
        ndone = all - remaining
        self.elapsed_time.value = '<div style=\"padding: 0px 10px 5px 10px\"><b>Computing:</b> ' + \
            format_time(self.elapsed) + '</div>'
        self.bar.value = ndone / all if all else 1.0
        self.bar_text.value = '<div style="padding: 0px 10px 0px 10px; text-align:right;">%d / %d</div>' % (ndone, all)
示例#6
0
文件: panel.py 项目: sangyy/billiocar
 def display(self):
     row1 = HBox([self.buttons[0], self.buttons[1], self.buttons[2]])
     row2 = HBox([self.buttons[3], self.buttons[4], self.buttons[5]])
     row3 = HBox([self.buttons[6], self.buttons[7], self.buttons[8]])
     return VBox([row1, row2, row3])
示例#7
0
    def __init__(self):
        
        self.output_dir = '.'
#        self.output_dir = 'tmpdir'

        # self.fig = plt.figure(figsize=(7.2,6))  # this strange figsize results in a ~square contour plot

        # initial value
        self.field_index = 4
        # self.field_index = self.mcds_field.value + 4

        tab_height = '500px'
        constWidth = '180px'
        constWidth2 = '150px'
        tab_layout = Layout(width='900px',   # border='2px solid black',
                            height=tab_height, ) #overflow_y='scroll')

        max_frames = 1   
        self.mcds_plot = interactive(self.plot_substrate, frame=(0, max_frames), continuous_update=False)  
        svg_plot_size = '700px'
        self.mcds_plot.layout.width = svg_plot_size
        self.mcds_plot.layout.height = svg_plot_size

        self.max_frames = BoundedIntText(
            min=0, max=99999, value=max_frames,
            description='Max',
           layout=Layout(width='160px'),
        )
        self.max_frames.observe(self.update_max_frames)

        self.field_min_max = {'dummy': [0., 1.]}
        # hacky I know, but make a dict that's got (key,value) reversed from the dict in the Dropdown below
        self.field_dict = {0:'dummy'}

        self.mcds_field = Dropdown(
            options={'dummy': 0},
            value=0,
            #     description='Field',
           layout=Layout(width=constWidth)
        )
        # print("substrate __init__: self.mcds_field.value=",self.mcds_field.value)
#        self.mcds_field.observe(self.mcds_field_cb)
        self.mcds_field.observe(self.mcds_field_changed_cb)

        # self.field_cmap = Text(
        #     value='viridis',
        #     description='Colormap',
        #     disabled=True,
        #     layout=Layout(width=constWidth),
        # )
        self.field_cmap = Dropdown(
            options=['viridis', 'jet', 'YlOrRd'],
            value='viridis',
            #     description='Field',
           layout=Layout(width=constWidth)
        )
        #self.field_cmap.observe(self.plot_substrate)
#        self.field_cmap.observe(self.plot_substrate)
        self.field_cmap.observe(self.mcds_field_cb)

        self.cmap_fixed = Checkbox(
            description='Fix',
            disabled=False,
#           layout=Layout(width=constWidth2),
        )

        self.save_min_max= Button(
            description='Save', #style={'description_width': 'initial'},
            button_style='success',  # 'success', 'info', 'warning', 'danger' or ''
            tooltip='Save min/max for this substrate',
            disabled=True,
           layout=Layout(width='90px')
        )

        def save_min_max_cb(b):
#            field_name = self.mcds_field.options[]
#            field_name = next(key for key, value in self.mcds_field.options.items() if value == self.mcds_field.value)
            field_name = self.field_dict[self.mcds_field.value]
#            print(field_name)
#            self.field_min_max = {'oxygen': [0., 30.], 'glucose': [0., 1.], 'H+ ions': [0., 1.], 'ECM': [0., 1.], 'NP1': [0., 1.], 'NP2': [0., 1.]}
            self.field_min_max[field_name][0] = self.cmap_min.value
            self.field_min_max[field_name][1] = self.cmap_max.value
#            print(self.field_min_max)

        self.save_min_max.on_click(save_min_max_cb)

        self.cmap_min = FloatText(
            description='Min',
            value=0,
            step = 0.1,
            disabled=True,
            layout=Layout(width=constWidth2),
        )
        self.cmap_min.observe(self.mcds_field_cb)

        self.cmap_max = FloatText(
            description='Max',
            value=38,
            step = 0.1,
            disabled=True,
            layout=Layout(width=constWidth2),
        )
        self.cmap_max.observe(self.mcds_field_cb)

        def cmap_fixed_cb(b):
            if (self.cmap_fixed.value):
                self.cmap_min.disabled = False
                self.cmap_max.disabled = False
                self.save_min_max.disabled = False
            else:
                self.cmap_min.disabled = True
                self.cmap_max.disabled = True
                self.save_min_max.disabled = True
#            self.mcds_field_cb()

        self.cmap_fixed.observe(cmap_fixed_cb)

        field_cmap_row2 = HBox([self.field_cmap, self.cmap_fixed])

#        field_cmap_row3 = HBox([self.save_min_max, self.cmap_min, self.cmap_max])
        items_auto = [
            self.save_min_max, #layout=Layout(flex='3 1 auto', width='auto'),
            self.cmap_min, 
            self.cmap_max,  
         ]
        box_layout = Layout(display='flex',
                    flex_flow='row',
                    align_items='stretch',
                    width='80%')
        field_cmap_row3 = Box(children=items_auto, layout=box_layout)

#        field_cmap_row3 = Box([self.save_min_max, self.cmap_min, self.cmap_max])

        # mcds_tab = widgets.VBox([mcds_dir, mcds_plot, mcds_play], layout=tab_layout)
        mcds_params = VBox([self.mcds_field, field_cmap_row2, field_cmap_row3, self.max_frames])  # mcds_dir
#        mcds_params = VBox([self.mcds_field, field_cmap_row2, field_cmap_row3,])  # mcds_dir

#        self.tab = HBox([mcds_params, self.mcds_plot], layout=tab_layout)
#        self.tab = HBox([mcds_params, self.mcds_plot])

        help_label = Label('select slider: drag or left/right arrows')
        row1 = Box([help_label, Box( [self.max_frames, self.mcds_field, self.field_cmap], layout=Layout(border='0px solid black',
                            width='50%',
                            height='',
                            align_items='stretch',
                            flex_direction='row',
                            display='flex'))] )
        row2 = Box([self.cmap_fixed, self.cmap_min, self.cmap_max], layout=Layout(border='0px solid black',
                            width='50%',
                            height='',
                            align_items='stretch',
                            flex_direction='row',
                            display='flex'))
        self.download_button = Download('mcds.zip', style='warning', icon='cloud-download', 
                                            tooltip='Download data', cb=self.download_cb)
        download_row = HBox([self.download_button.w, Label("Download all substrate data (browser must allow pop-ups).")])

#        self.tab = VBox([row1, row2, self.mcds_plot])
        self.tab = VBox([row1, row2, self.mcds_plot, download_row])
    def __init__(self,
                 dataset,
                 properties_and_values,  # properties { name: (MetaPropType, [possible values], optional label)}
                 output_path=None,
                 show_name=False,
                 show_axis=False,
                 fig_size=(10, 10),
                 buttons_vertical=False,
                 ds_name=None,
                 custom_display_function=None,
                 classes_to_annotate=None,
                 validate_function=None,
                 show_reset=True
                 ):

        for k, v in properties_and_values.items():
            if v[0] not in [MetaPropertiesType.UNIQUE, MetaPropertiesType.TEXT]:
                raise NotImplementedError(f"Cannot use {v[0]}!")

        self.dataset_orig = dataset
        self.properties_and_values = properties_and_values
        self.show_axis = show_axis
        self.show_reset = show_reset
        self.show_name = show_name

        if classes_to_annotate is None:  # if classes_to_annotate is None, all the classes would be annotated
            self.classes_to_annotate = self.dataset_orig.get_categories_names()  # otherwise, the only the classes in the list

        if ds_name is None:
            self.name = (self.dataset_orig.dataset_root_param.split('/')[-1]).split('.')[0]  # get_original_file_name
        else:
            self.name = ds_name

        self.set_output(output_path)

        print("{} {}".format(labels_str.info_new_ds, self.file_path_for_json))

        self.current_pos = 0
        self.mapping, self.dataset_annotated = self.create_results_dict(self.file_path_for_json)
        self.set_objects()

        self.fig_size = fig_size
        self.buttons_vertical = buttons_vertical

        self.current_image = {}

        label_total = self.create_label_total()

        # create buttons
        buttons = self.create_buttons()

        self.updated = False

        self.validation_show = HTML(value="")
        self.out = Output()
        self.out.add_class("my_canvas_class")

        self.checkboxes = {}
        self.radiobuttons = {}
        self.bounded_text = {}
        self.box_text = {}

        labels = self.create_check_radio_boxes()

        self.validate = not validate_function is None
        if self.validate:
            self.validate_function = validate_function

        self.set_display_function(custom_display_function)

        output_layout = self.set_check_radio_boxes_layout(labels)

        self.all_widgets = VBox(children=
                                [HBox([self.text_index, label_total]),
                                 HBox(buttons),
                                 self.validation_show,
                                 HBox([self.out,
                                       VBox(output_layout)])])

        self.load_js()
示例#9
0
    def __init__(self, player):

        self.widget = ipywidgets.HTML(
            value="",
            placeholder='',
            description='',
        )
        output = ipywidgets.Output()
        self.player = player

        def fast_backward_clicked(b):
            with output:
                self.player.begin()
                self.player.pause()

        def backward_clicked(b):
            with output:
                self.player.backward()

        def step_backward_clicked(b):
            with output:
                self.player.pause()
                self.player.step_backward()

        def pause_clicked(b):
            with output:
                self.player.pause()

        def step_forward_clicked(b):
            with output:
                self.player.pause()
                self.player.step_forward()

        def play_clicked(b):
            with output:
                self.player.play()

        def fast_forward_clicked(b):
            with output:
                self.player.pause()
                self.player.end()

        # self.slider_time=ipywidgets.IntSlider(
        # value=0,
        # min=0,
        # max=len(self.player.history),
        # step=1,
        #     description="time:"
        # )

        slider = ipywidgets.FloatSlider(value=1.0,
                                        min=0.0,
                                        max=6.0,
                                        step=1,
                                        description="Speed:")

        # 2puissance speed affiché ou alors nous affiché juste la valeur et pas "speed " 2** = puissance
        def on_value_change(change):
            value = int(change['new'])
            self.player.set_fps(2**value)

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

        play = ipywidgets.Button(description="",
                                 icon='play',
                                 layout=Layout(width='35px'))
        fast_backward = ipywidgets.Button(description="",
                                          icon='fast-backward',
                                          layout=Layout(width='35px'))
        backward = ipywidgets.Button(description="",
                                     icon='backward',
                                     layout=Layout(width='35px'))
        step_backward = ipywidgets.Button(description="",
                                          icon='step-backward',
                                          layout=Layout(width='35px'))
        pause = ipywidgets.Button(description="",
                                  icon='pause',
                                  layout=Layout(width='35px'))
        step_forward = ipywidgets.Button(description="",
                                         icon='step-forward',
                                         layout=Layout(width='35px'))
        fast_forward = ipywidgets.Button(description="",
                                         icon='fast-forward',
                                         layout=Layout(width='35px'))

        play.on_click(play_clicked)
        fast_backward.on_click(fast_backward_clicked)
        backward.on_click(backward_clicked)
        step_backward.on_click(step_backward_clicked)
        pause.on_click(pause_clicked)
        step_forward.on_click(step_forward_clicked)
        fast_forward.on_click(fast_forward_clicked)

        self.affichage = ipywidgets.HBox([
            fast_backward, backward, step_backward, pause, step_forward, play,
            fast_forward, slider
        ])
        VBox.__init__(
            self, [self.player.view, self.player.slider_time, self.affichage])
        #link((self.slider_time,'value'),(self.player,'time'))

        #self.widget_affichage=VBox([self.player.view,self.slider_time,self.affichage])
        #self.player.time=0
        self.player = player
示例#10
0
class MultiProgressWidget(MultiProgressBar):
    """Multiple progress bar Widget suitable for the notebook

    Displays multiple progress bars for a computation, split on computation
    type.

    See Also
    --------
    progress: User-level function <--- use this
    MultiProgress: Non-visualization component that contains most logic
    ProgressWidget: Single progress bar widget
    """
    def __init__(
        self,
        keys,
        scheduler=None,
        minimum=0,
        interval=0.1,
        func=key_split,
        complete=False,
        **kwargs,
    ):
        super().__init__(keys, scheduler, func, interval, complete)
        from ipywidgets import VBox

        self.widget = VBox([])

    def make_widget(self, all):
        from ipywidgets import HTML, FloatProgress, HBox, VBox

        self.elapsed_time = HTML("")
        self.bars = {
            key: FloatProgress(min=0, max=1, description="")
            for key in all
        }
        self.bar_texts = {key: HTML("") for key in all}
        self.bar_labels = {
            key:
            HTML('<div style="padding: 0px 10px 0px 10px;'
                 " text-align:left; word-wrap: "
                 'break-word;">' +
                 html.escape(key.decode() if isinstance(key, bytes) else key) +
                 "</div>")
            for key in all
        }

        def keyfunc(kv):
            """ Order keys by most numerous, then by string name """
            return kv[::-1]

        key_order = [
            k for k, v in sorted(all.items(), key=keyfunc, reverse=True)
        ]

        self.bar_widgets = VBox([
            HBox([self.bar_texts[key], self.bars[key], self.bar_labels[key]])
            for key in key_order
        ])
        self.widget.children = (self.elapsed_time, self.bar_widgets)

    def _ipython_display_(self, **kwargs):
        IOLoop.current().add_callback(self.listen)
        return self.widget._ipython_display_(**kwargs)

    def _draw_stop(self,
                   remaining,
                   status,
                   exception=None,
                   key=None,
                   **kwargs):
        for k, v in remaining.items():
            if not v:
                self.bars[k].bar_style = "success"
            else:
                self.bars[k].bar_style = "danger"

        if status == "error":
            # self.bars[self.func(key)].bar_style = 'danger'  # TODO
            self.elapsed_time.value = (
                '<div style="padding: 0px 10px 5px 10px"><b>Exception</b> ' +
                "<tt>" + repr(exception) + "</tt>:" +
                format_time(self.elapsed) + " " + "</div>")
        else:
            self.elapsed_time.value = (
                '<div style="padding: 0px 10px 5px 10px"><b>Finished:</b> ' +
                format_time(self.elapsed) + "</div>")

    def _draw_bar(self, remaining, all, status, **kwargs):
        if self.keys and not self.widget.children:
            self.make_widget(all)
        for k, ntasks in all.items():
            ndone = ntasks - remaining[k]
            self.elapsed_time.value = (
                '<div style="padding: 0px 10px 5px 10px"><b>Computing:</b> ' +
                format_time(self.elapsed) + "</div>")
            self.bars[k].value = ndone / ntasks if ntasks else 1.0
            self.bar_texts[k].value = (
                '<div style="padding: 0px 10px 0px 10px; text-align: right">%d / %d</div>'
                % (ndone, ntasks))
示例#11
0
def Heat1DExample():
    options = {
        "N":
        Dropdown(description='N',
                 index=1,
                 options=(2, 3, 4, 8, 16, 32, 64),
                 value=8),
        "order":
        Dropdown(description='order', index=1, options=(1, 2, 3, 4), value=1),
        "k1":
        FloatSlider(min=1,
                    max=100,
                    step=0.1,
                    continuous_update=False,
                    description=r'\(k_1 / [W/m K]\)',
                    value=50),
        "k2":
        FloatSlider(min=1,
                    max=100,
                    step=0.1,
                    continuous_update=False,
                    description=r'\(k_2 / [W/m K]\)',
                    value=50),
        "Q1":
        FloatSlider(min=0,
                    max=1e7,
                    step=1e4,
                    continuous_update=False,
                    description=r'\(q_Q^1 / [W/m^3]\)',
                    value=30000),
        "Q2":
        FloatSlider(min=0,
                    max=1e7,
                    step=1e4,
                    continuous_update=False,
                    description=r'\(q_Q^2 / [W/m^3]\)',
                    value=30000),
        "boundary_condition_left":
        Dropdown(description='bnd.cnd.left',
                 index=1,
                 options=("Dirichlet", "Neumann", "Robin"),
                 value="Dirichlet"),
        "boundary_condition_right":
        Dropdown(description='bnd.cnd.right',
                 index=1,
                 options=("Dirichlet", "Neumann", "Robin"),
                 value="Dirichlet"),
        "value_left":
        FloatSlider(min=0,
                    max=100,
                    step=0.5,
                    description=r'\(T_l/ [°C]\)',
                    continuous_update=False,
                    value=20),
        "value_right":
        FloatSlider(min=0,
                    max=100,
                    step=0.5,
                    description=r'\(T_r/ [°C]\)',
                    continuous_update=False,
                    value=20),
        "q_value_left":
        FloatSlider(min=0,
                    max=100,
                    step=0.5,
                    description=r'\(q_S^l/ [W/m^3]\)',
                    continuous_update=False),
        "q_value_right":
        FloatSlider(min=0,
                    max=100,
                    step=0.5,
                    description=r'\(q_S^r/ [W/m^3]\)',
                    continuous_update=False),
        "r_value_left":
        FloatSlider(min=0,
                    max=200,
                    step=0.1,
                    description=r'\(\alpha_l / [W\!/m^2 K]\)',
                    continuous_update=False,
                    value=1),
        "r_value_right":
        FloatSlider(min=0,
                    max=200,
                    step=0.1,
                    description=r'\(\alpha_{r\!} / [W\!/m^2 K]\)',
                    continuous_update=False,
                    value=1),
        "intervalsize":
        FloatSlider(min=0.01,
                    max=1,
                    step=0.01,
                    description=r'\(l / [m]\)',
                    continuous_update=False,
                    value=1),
    }

    out = interactive_output(Heat1DFEM, options)

    ui = VBox([
        options["intervalsize"],
        HBox([options["N"], options["order"]]),
        HBox([options["k1"], options["k2"]]),
        HBox([options["Q1"], options["Q2"]]),
        HBox([
            options["boundary_condition_left"],
            options["boundary_condition_right"]
        ]),
        HBox([options["q_value_left"], options["q_value_right"]]),
        HBox([options["value_left"], options["value_right"]]),
        HBox([options["r_value_left"], options["r_value_right"]])
    ])

    display.display(ui, out)
    save_settings()
    updateinputboxes()
    solve_intial_opt_weight()
    updateviewcontrol()
    updatecontrolinui()
    run_viewmodel({'new': 0.})


#display(button_reset)
#button_reset.on_click(onclickapplysettings)
button_applysettings.on_click(onclickapplysettings)

#UI_sec_input = HBox([VBox(list_sec_input),VBox([load_members_hbox,label_usemktcap,check_usemktcap,label_usemktcap2,button_applysettings],layout={'margin':'0px 0px 0px 10px'})])
UI_sec_input = HBox(
    [
        VBox(list_sec_input),
        VBox([
            label_usemktcap, check_usemktcap, label_usemktcap2,
            button_applysettings
        ],
             layout={'margin': '0px 0px 0px 10px'})
    ]
)  # Have taken load_members_hbox out because it requires a call to bloomberg's cde library which is not accessible to us.


def on_click_load_portfolio(obj=None):
    global df_portfolio_weight
    #portfolio_univ = bq.univ.members(port_dict[portfolio_dropdown.value],type='PORT') #Requires Bloomberg's Database and is henceforth unaccessible to us.
    #id_ = bq.data.id() #Requires Bloomberg's Database and is henceforth unaccessible to us.
    #df_portfolio_weight = pd.concat([x.df() for x in bq.execute(bql.Request(portfolio_univ, [bq.data.name(),id_['Weights']/100]))],axis=1).reset_index()  #******************** Directly TALKS TO Bloomberg's Database ************
    df_portfolio_weight = approximated_mkt_weight
示例#13
0
    def __init__(self):

        micron_units = Label(
            'micron')  # use "option m" (Mac, for micro symbol)

        constWidth = '180px'
        tab_height = '500px'
        stepsize = 10

        #style = {'description_width': '250px'}
        style = {'description_width': '25%'}
        layout = {'width': '400px'}

        name_button_layout = {'width': '25%'}
        widget_layout = {'width': '15%'}
        units_button_layout = {'width': '15%'}
        desc_button_layout = {'width': '45%'}
        divider_button_layout = {'width': '40%'}

        param_name1 = Button(description='choose_adhesion_function',
                             disabled=True,
                             layout=name_button_layout)
        param_name1.style.button_color = 'lightgreen'

        self.choose_adhesion_function = IntText(value=0,
                                                step=1,
                                                style=style,
                                                layout=widget_layout)

        param_name2 = Button(description='random_seed',
                             disabled=True,
                             layout=name_button_layout)
        param_name2.style.button_color = 'tan'

        self.random_seed = IntText(value=0,
                                   step=1,
                                   style=style,
                                   layout=widget_layout)

        param_name3 = Button(description='migration_bias',
                             disabled=True,
                             layout=name_button_layout)
        param_name3.style.button_color = 'lightgreen'

        self.migration_bias = FloatText(value=0.95,
                                        step=0.1,
                                        style=style,
                                        layout=widget_layout)

        param_name4 = Button(description='migration_speed',
                             disabled=True,
                             layout=name_button_layout)
        param_name4.style.button_color = 'tan'

        self.migration_speed = FloatText(value=0.7,
                                         step=0.1,
                                         style=style,
                                         layout=widget_layout)

        param_name5 = Button(description='persistence',
                             disabled=True,
                             layout=name_button_layout)
        param_name5.style.button_color = 'lightgreen'

        self.persistence = FloatText(value=5,
                                     step=0.1,
                                     style=style,
                                     layout=widget_layout)

        param_name6 = Button(description='motility_amplitude_min',
                             disabled=True,
                             layout=name_button_layout)
        param_name6.style.button_color = 'tan'

        self.motility_amplitude_min = FloatText(value=0.1,
                                                step=0.01,
                                                style=style,
                                                layout=widget_layout)

        param_name7 = Button(description='motility_amplitude_max',
                             disabled=True,
                             layout=name_button_layout)
        param_name7.style.button_color = 'lightgreen'

        self.motility_amplitude_max = FloatText(value=0.5,
                                                step=0.1,
                                                style=style,
                                                layout=widget_layout)

        param_name8 = Button(description='mode_motility',
                             disabled=True,
                             layout=name_button_layout)
        param_name8.style.button_color = 'tan'

        self.mode_motility = IntText(value=1,
                                     step=0.1,
                                     style=style,
                                     layout=widget_layout)

        param_name9 = Button(description='contact_cell_ECM_threshold',
                             disabled=True,
                             layout=name_button_layout)
        param_name9.style.button_color = 'lightgreen'

        self.contact_cell_ECM_threshold = FloatText(value=0.5,
                                                    step=0.1,
                                                    style=style,
                                                    layout=widget_layout)

        param_name10 = Button(description='contact_TGFB_threshold',
                              disabled=True,
                              layout=name_button_layout)
        param_name10.style.button_color = 'tan'

        self.contact_TGFB_threshold = FloatText(value=0.2,
                                                step=0.01,
                                                style=style,
                                                layout=widget_layout)

        param_name11 = Button(description='ECM_TGFbeta_ratio',
                              disabled=True,
                              layout=name_button_layout)
        param_name11.style.button_color = 'lightgreen'

        self.ECM_TGFbeta_ratio = FloatText(value=0.75,
                                           step=0.1,
                                           style=style,
                                           layout=widget_layout)

        param_name12 = Button(description='contact_cell_cell_threshold',
                              disabled=True,
                              layout=name_button_layout)
        param_name12.style.button_color = 'tan'

        self.contact_cell_cell_threshold = FloatText(value=0.9,
                                                     step=0.1,
                                                     style=style,
                                                     layout=widget_layout)

        param_name13 = Button(description='homotypic_adhesion_min',
                              disabled=True,
                              layout=name_button_layout)
        param_name13.style.button_color = 'lightgreen'

        self.homotypic_adhesion_min = FloatText(value=0,
                                                step=0.01,
                                                style=style,
                                                layout=widget_layout)

        param_name14 = Button(description='homotypic_adhesion_max',
                              disabled=True,
                              layout=name_button_layout)
        param_name14.style.button_color = 'tan'

        self.homotypic_adhesion_max = FloatText(value=0.8,
                                                step=0.1,
                                                style=style,
                                                layout=widget_layout)

        param_name15 = Button(description='heterotypic_adhesion_min',
                              disabled=True,
                              layout=name_button_layout)
        param_name15.style.button_color = 'lightgreen'

        self.heterotypic_adhesion_min = FloatText(value=0,
                                                  step=0.01,
                                                  style=style,
                                                  layout=widget_layout)

        param_name16 = Button(description='heterotypic_adhesion_max',
                              disabled=True,
                              layout=name_button_layout)
        param_name16.style.button_color = 'tan'

        self.heterotypic_adhesion_max = FloatText(value=0.8,
                                                  step=0.1,
                                                  style=style,
                                                  layout=widget_layout)

        param_name17 = Button(description='ecm_adhesion_min',
                              disabled=True,
                              layout=name_button_layout)
        param_name17.style.button_color = 'lightgreen'

        self.ecm_adhesion_min = FloatText(value=1,
                                          step=0.1,
                                          style=style,
                                          layout=widget_layout)

        param_name18 = Button(description='ecm_adhesion_max',
                              disabled=True,
                              layout=name_button_layout)
        param_name18.style.button_color = 'tan'

        self.ecm_adhesion_max = FloatText(value=2,
                                          step=0.1,
                                          style=style,
                                          layout=widget_layout)

        param_name19 = Button(description='cell_ecm_repulsion',
                              disabled=True,
                              layout=name_button_layout)
        param_name19.style.button_color = 'lightgreen'

        self.cell_ecm_repulsion = FloatText(value=5.0,
                                            step=0.1,
                                            style=style,
                                            layout=widget_layout)

        param_name20 = Button(description='ecm_cell_contact_factor',
                              disabled=True,
                              layout=name_button_layout)
        param_name20.style.button_color = 'tan'

        self.ecm_cell_contact_factor = FloatText(value=100,
                                                 step=10,
                                                 style=style,
                                                 layout=widget_layout)

        param_name21 = Button(description='initial_cell_contact_parameter',
                              disabled=True,
                              layout=name_button_layout)
        param_name21.style.button_color = 'lightgreen'

        self.initial_cell_contact_parameter = FloatText(value=20,
                                                        step=1,
                                                        style=style,
                                                        layout=widget_layout)

        param_name22 = Button(description='ecm_degradation',
                              disabled=True,
                              layout=name_button_layout)
        param_name22.style.button_color = 'tan'

        self.ecm_degradation = FloatText(value=0.7,
                                         step=0.1,
                                         style=style,
                                         layout=widget_layout)

        param_name23 = Button(description='TGFbeta_degradation',
                              disabled=True,
                              layout=name_button_layout)
        param_name23.style.button_color = 'lightgreen'

        self.TGFbeta_degradation = FloatText(value=0.0015,
                                             step=0.0001,
                                             style=style,
                                             layout=widget_layout)

        param_name24 = Button(description='cell_radius',
                              disabled=True,
                              layout=name_button_layout)
        param_name24.style.button_color = 'tan'

        self.cell_radius = FloatText(value=8.413,
                                     step=0.1,
                                     style=style,
                                     layout=widget_layout)

        param_name25 = Button(description='max_interaction_factor',
                              disabled=True,
                              layout=name_button_layout)
        param_name25.style.button_color = 'lightgreen'

        self.max_interaction_factor = FloatText(value=1.3,
                                                step=0.1,
                                                style=style,
                                                layout=widget_layout)

        param_name26 = Button(description='config_radius',
                              disabled=True,
                              layout=name_button_layout)
        param_name26.style.button_color = 'tan'

        self.config_radius = FloatText(value=100,
                                       step=10,
                                       style=style,
                                       layout=widget_layout)

        param_name27 = Button(description='tgfbeta_radius',
                              disabled=True,
                              layout=name_button_layout)
        param_name27.style.button_color = 'lightgreen'

        self.tgfbeta_radius = FloatText(value=90,
                                        step=1,
                                        style=style,
                                        layout=widget_layout)

        param_name28 = Button(description='node_to_visualize',
                              disabled=True,
                              layout=name_button_layout)
        param_name28.style.button_color = 'tan'

        self.node_to_visualize = Text(value='Single',
                                      style=style,
                                      layout=widget_layout)

        param_name29 = Button(description='color_function',
                              disabled=True,
                              layout=name_button_layout)
        param_name29.style.button_color = 'lightgreen'

        self.color_function = IntText(value=1,
                                      step=0.1,
                                      style=style,
                                      layout=widget_layout)

        units_button1 = Button(description='',
                               disabled=True,
                               layout=units_button_layout)
        units_button1.style.button_color = 'lightgreen'
        units_button2 = Button(description='',
                               disabled=True,
                               layout=units_button_layout)
        units_button2.style.button_color = 'tan'
        units_button3 = Button(description='',
                               disabled=True,
                               layout=units_button_layout)
        units_button3.style.button_color = 'lightgreen'
        units_button4 = Button(description='',
                               disabled=True,
                               layout=units_button_layout)
        units_button4.style.button_color = 'tan'
        units_button5 = Button(description='',
                               disabled=True,
                               layout=units_button_layout)
        units_button5.style.button_color = 'lightgreen'
        units_button6 = Button(description='',
                               disabled=True,
                               layout=units_button_layout)
        units_button6.style.button_color = 'tan'
        units_button7 = Button(description='',
                               disabled=True,
                               layout=units_button_layout)
        units_button7.style.button_color = 'lightgreen'
        units_button8 = Button(description='',
                               disabled=True,
                               layout=units_button_layout)
        units_button8.style.button_color = 'tan'
        units_button9 = Button(description='',
                               disabled=True,
                               layout=units_button_layout)
        units_button9.style.button_color = 'lightgreen'
        units_button10 = Button(description='',
                                disabled=True,
                                layout=units_button_layout)
        units_button10.style.button_color = 'tan'
        units_button11 = Button(description='',
                                disabled=True,
                                layout=units_button_layout)
        units_button11.style.button_color = 'lightgreen'
        units_button12 = Button(description='',
                                disabled=True,
                                layout=units_button_layout)
        units_button12.style.button_color = 'tan'
        units_button13 = Button(description='',
                                disabled=True,
                                layout=units_button_layout)
        units_button13.style.button_color = 'lightgreen'
        units_button14 = Button(description='',
                                disabled=True,
                                layout=units_button_layout)
        units_button14.style.button_color = 'tan'
        units_button15 = Button(description='',
                                disabled=True,
                                layout=units_button_layout)
        units_button15.style.button_color = 'lightgreen'
        units_button16 = Button(description='',
                                disabled=True,
                                layout=units_button_layout)
        units_button16.style.button_color = 'tan'
        units_button17 = Button(description='',
                                disabled=True,
                                layout=units_button_layout)
        units_button17.style.button_color = 'lightgreen'
        units_button18 = Button(description='',
                                disabled=True,
                                layout=units_button_layout)
        units_button18.style.button_color = 'tan'
        units_button19 = Button(description='',
                                disabled=True,
                                layout=units_button_layout)
        units_button19.style.button_color = 'lightgreen'
        units_button20 = Button(description='',
                                disabled=True,
                                layout=units_button_layout)
        units_button20.style.button_color = 'tan'
        units_button21 = Button(description='',
                                disabled=True,
                                layout=units_button_layout)
        units_button21.style.button_color = 'lightgreen'
        units_button22 = Button(description='',
                                disabled=True,
                                layout=units_button_layout)
        units_button22.style.button_color = 'tan'
        units_button23 = Button(description='',
                                disabled=True,
                                layout=units_button_layout)
        units_button23.style.button_color = 'lightgreen'
        units_button24 = Button(description='',
                                disabled=True,
                                layout=units_button_layout)
        units_button24.style.button_color = 'tan'
        units_button25 = Button(description='',
                                disabled=True,
                                layout=units_button_layout)
        units_button25.style.button_color = 'lightgreen'
        units_button26 = Button(description='',
                                disabled=True,
                                layout=units_button_layout)
        units_button26.style.button_color = 'tan'
        units_button27 = Button(description='',
                                disabled=True,
                                layout=units_button_layout)
        units_button27.style.button_color = 'lightgreen'
        units_button28 = Button(description='',
                                disabled=True,
                                layout=units_button_layout)
        units_button28.style.button_color = 'tan'
        units_button29 = Button(description='',
                                disabled=True,
                                layout=units_button_layout)
        units_button29.style.button_color = 'lightgreen'

        desc_button1 = Button(
            description='switch between default adhesion function or custom',
            tooltip='switch between default adhesion function or custom',
            disabled=True,
            layout=desc_button_layout)
        desc_button1.style.button_color = 'lightgreen'
        desc_button2 = Button(description='change seed of the simulation',
                              tooltip='change seed of the simulation',
                              disabled=True,
                              layout=desc_button_layout)
        desc_button2.style.button_color = 'tan'
        desc_button3 = Button(
            description=
            'change value of migration bias for cells with migration node active',
            tooltip=
            'change value of migration bias for cells with migration node active',
            disabled=True,
            layout=desc_button_layout)
        desc_button3.style.button_color = 'lightgreen'
        desc_button4 = Button(
            description=
            'change value of migration speed for cells with migration node active',
            tooltip=
            'change value of migration speed for cells with migration node active',
            disabled=True,
            layout=desc_button_layout)
        desc_button4.style.button_color = 'tan'
        desc_button5 = Button(
            description=
            'change value of persistence for cells with migration node active',
            tooltip=
            'change value of persistence for cells with migration node active',
            disabled=True,
            layout=desc_button_layout)
        desc_button5.style.button_color = 'lightgreen'
        desc_button6 = Button(
            description='change the min value of motility amplitude',
            tooltip='change the min value of motility amplitude',
            disabled=True,
            layout=desc_button_layout)
        desc_button6.style.button_color = 'tan'
        desc_button7 = Button(
            description='change the max value of motility amplitude',
            tooltip='change the max value of motility amplitude',
            disabled=True,
            layout=desc_button_layout)
        desc_button7.style.button_color = 'lightgreen'
        desc_button8 = Button(description='not used yet',
                              tooltip='not used yet',
                              disabled=True,
                              layout=desc_button_layout)
        desc_button8.style.button_color = 'tan'
        desc_button9 = Button(
            description=
            'change the threshold needed to trigger ECM interaction',
            tooltip='change the threshold needed to trigger ECM interaction',
            disabled=True,
            layout=desc_button_layout)
        desc_button9.style.button_color = 'lightgreen'
        desc_button10 = Button(
            description=
            'change the threshold needed to trigger TGFbeta interaction',
            tooltip=
            'change the threshold needed to trigger TGFbeta interaction',
            disabled=True,
            layout=desc_button_layout)
        desc_button10.style.button_color = 'tan'
        desc_button11 = Button(
            description=
            'change the threshold needed to start sensing TGFbeta inside a voxel with ECM (cell must degrades a certain amount of ECM before sensing TGFbeta)',
            tooltip=
            'change the threshold needed to start sensing TGFbeta inside a voxel with ECM (cell must degrades a certain amount of ECM before sensing TGFbeta)',
            disabled=True,
            layout=desc_button_layout)
        desc_button11.style.button_color = 'lightgreen'
        desc_button12 = Button(
            description=
            'change the treshold needed to trigger Neighbours and Neigh2 node',
            tooltip=
            'change the treshold needed to trigger Neighbours and Neigh2 node',
            disabled=True,
            layout=desc_button_layout)
        desc_button12.style.button_color = 'tan'
        desc_button13 = Button(description='not used yet',
                               tooltip='not used yet',
                               disabled=True,
                               layout=desc_button_layout)
        desc_button13.style.button_color = 'lightgreen'
        desc_button14 = Button(description='not used yet',
                               tooltip='not used yet',
                               disabled=True,
                               layout=desc_button_layout)
        desc_button14.style.button_color = 'tan'
        desc_button15 = Button(
            description=
            'used to set the min adhesion between cells of the same type',
            tooltip=
            'used to set the min adhesion between cells of the same type',
            disabled=True,
            layout=desc_button_layout)
        desc_button15.style.button_color = 'lightgreen'
        desc_button16 = Button(
            description=
            'used to set the max adhesion between cells of the same type',
            tooltip=
            'used to set the max adhesion between cells of the same type',
            disabled=True,
            layout=desc_button_layout)
        desc_button16.style.button_color = 'tan'
        desc_button17 = Button(
            description='used to set the min adhesion between cells and ECM',
            tooltip='used to set the min adhesion between cells and ECM',
            disabled=True,
            layout=desc_button_layout)
        desc_button17.style.button_color = 'lightgreen'
        desc_button18 = Button(
            description='used to set the min adhesion between cells and ECM',
            tooltip='used to set the min adhesion between cells and ECM',
            disabled=True,
            layout=desc_button_layout)
        desc_button18.style.button_color = 'tan'
        desc_button19 = Button(description='change the value of ECM repulsion',
                               tooltip='change the value of ECM repulsion',
                               disabled=True,
                               layout=desc_button_layout)
        desc_button19.style.button_color = 'lightgreen'
        desc_button20 = Button(
            description=
            'change the amount of ecm_contact needed to a cell to detach from the others',
            tooltip=
            'change the amount of ecm_contact needed to a cell to detach from the others',
            disabled=True,
            layout=desc_button_layout)
        desc_button20.style.button_color = 'tan'
        desc_button21 = Button(
            description=
            'set the initial amount of cell_contact allowing the immediate activation of Neighbours/Nei2 nodes in the boolean network',
            tooltip=
            'set the initial amount of cell_contact allowing the immediate activation of Neighbours/Nei2 nodes in the boolean network',
            disabled=True,
            layout=desc_button_layout)
        desc_button21.style.button_color = 'lightgreen'
        desc_button22 = Button(
            description=
            'chenage the amount of ECM degraded by the cells with Matrix_modifcation ON',
            tooltip=
            'chenage the amount of ECM degraded by the cells with Matrix_modifcation ON',
            disabled=True,
            layout=desc_button_layout)
        desc_button22.style.button_color = 'tan'
        desc_button23 = Button(
            description='chenage the amount of TGFbeta degraded by the cells',
            tooltip='chenage the amount of TGFbeta degraded by the cells',
            disabled=True,
            layout=desc_button_layout)
        desc_button23.style.button_color = 'lightgreen'
        desc_button24 = Button(description='initial radius of the cells',
                               tooltip='initial radius of the cells',
                               disabled=True,
                               layout=desc_button_layout)
        desc_button24.style.button_color = 'tan'
        desc_button25 = Button(
            description='used to set the max distance of interaction',
            tooltip='used to set the max distance of interaction',
            disabled=True,
            layout=desc_button_layout)
        desc_button25.style.button_color = 'lightgreen'
        desc_button26 = Button(
            description='change the initial radius of the tumor',
            tooltip='change the initial radius of the tumor',
            disabled=True,
            layout=desc_button_layout)
        desc_button26.style.button_color = 'tan'
        desc_button27 = Button(
            description='change radius of the tgfbeta substrate',
            tooltip='change radius of the tgfbeta substrate',
            disabled=True,
            layout=desc_button_layout)
        desc_button27.style.button_color = 'lightgreen'
        desc_button28 = Button(
            description=
            'change the node to visualize in the plot tab when coloring cells by custom data value',
            tooltip=
            'change the node to visualize in the plot tab when coloring cells by custom data value',
            disabled=True,
            layout=desc_button_layout)
        desc_button28.style.button_color = 'tan'
        desc_button29 = Button(
            description=
            'change the basic color function: 0 for ECM based color, 1 for phase based color, 2 for node based color',
            tooltip=
            'change the basic color function: 0 for ECM based color, 1 for phase based color, 2 for node based color',
            disabled=True,
            layout=desc_button_layout)
        desc_button29.style.button_color = 'lightgreen'

        row1 = [
            param_name1, self.choose_adhesion_function, units_button1,
            desc_button1
        ]
        row2 = [param_name2, self.random_seed, units_button2, desc_button2]
        row3 = [param_name3, self.migration_bias, units_button3, desc_button3]
        row4 = [param_name4, self.migration_speed, units_button4, desc_button4]
        row5 = [param_name5, self.persistence, units_button5, desc_button5]
        row6 = [
            param_name6, self.motility_amplitude_min, units_button6,
            desc_button6
        ]
        row7 = [
            param_name7, self.motility_amplitude_max, units_button7,
            desc_button7
        ]
        row8 = [param_name8, self.mode_motility, units_button8, desc_button8]
        row9 = [
            param_name9, self.contact_cell_ECM_threshold, units_button9,
            desc_button9
        ]
        row10 = [
            param_name10, self.contact_TGFB_threshold, units_button10,
            desc_button10
        ]
        row11 = [
            param_name11, self.ECM_TGFbeta_ratio, units_button11, desc_button11
        ]
        row12 = [
            param_name12, self.contact_cell_cell_threshold, units_button12,
            desc_button12
        ]
        row13 = [
            param_name13, self.homotypic_adhesion_min, units_button13,
            desc_button13
        ]
        row14 = [
            param_name14, self.homotypic_adhesion_max, units_button14,
            desc_button14
        ]
        row15 = [
            param_name15, self.heterotypic_adhesion_min, units_button15,
            desc_button15
        ]
        row16 = [
            param_name16, self.heterotypic_adhesion_max, units_button16,
            desc_button16
        ]
        row17 = [
            param_name17, self.ecm_adhesion_min, units_button17, desc_button17
        ]
        row18 = [
            param_name18, self.ecm_adhesion_max, units_button18, desc_button18
        ]
        row19 = [
            param_name19, self.cell_ecm_repulsion, units_button19,
            desc_button19
        ]
        row20 = [
            param_name20, self.ecm_cell_contact_factor, units_button20,
            desc_button20
        ]
        row21 = [
            param_name21, self.initial_cell_contact_parameter, units_button21,
            desc_button21
        ]
        row22 = [
            param_name22, self.ecm_degradation, units_button22, desc_button22
        ]
        row23 = [
            param_name23, self.TGFbeta_degradation, units_button23,
            desc_button23
        ]
        row24 = [param_name24, self.cell_radius, units_button24, desc_button24]
        row25 = [
            param_name25, self.max_interaction_factor, units_button25,
            desc_button25
        ]
        row26 = [
            param_name26, self.config_radius, units_button26, desc_button26
        ]
        row27 = [
            param_name27, self.tgfbeta_radius, units_button27, desc_button27
        ]
        row28 = [
            param_name28, self.node_to_visualize, units_button28, desc_button28
        ]
        row29 = [
            param_name29, self.color_function, units_button29, desc_button29
        ]

        box_layout = Layout(display='flex',
                            flex_flow='row',
                            align_items='stretch',
                            width='100%')
        box1 = Box(children=row1, layout=box_layout)
        box2 = Box(children=row2, layout=box_layout)
        box3 = Box(children=row3, layout=box_layout)
        box4 = Box(children=row4, layout=box_layout)
        box5 = Box(children=row5, layout=box_layout)
        box6 = Box(children=row6, layout=box_layout)
        box7 = Box(children=row7, layout=box_layout)
        box8 = Box(children=row8, layout=box_layout)
        box9 = Box(children=row9, layout=box_layout)
        box10 = Box(children=row10, layout=box_layout)
        box11 = Box(children=row11, layout=box_layout)
        box12 = Box(children=row12, layout=box_layout)
        box13 = Box(children=row13, layout=box_layout)
        box14 = Box(children=row14, layout=box_layout)
        box15 = Box(children=row15, layout=box_layout)
        box16 = Box(children=row16, layout=box_layout)
        box17 = Box(children=row17, layout=box_layout)
        box18 = Box(children=row18, layout=box_layout)
        box19 = Box(children=row19, layout=box_layout)
        box20 = Box(children=row20, layout=box_layout)
        box21 = Box(children=row21, layout=box_layout)
        box22 = Box(children=row22, layout=box_layout)
        box23 = Box(children=row23, layout=box_layout)
        box24 = Box(children=row24, layout=box_layout)
        box25 = Box(children=row25, layout=box_layout)
        box26 = Box(children=row26, layout=box_layout)
        box27 = Box(children=row27, layout=box_layout)
        box28 = Box(children=row28, layout=box_layout)
        box29 = Box(children=row29, layout=box_layout)

        self.tab = VBox([
            box1,
            box2,
            box3,
            box4,
            box5,
            box6,
            box7,
            box8,
            box9,
            box10,
            box11,
            box12,
            box13,
            box14,
            box15,
            box16,
            box17,
            box18,
            box19,
            box20,
            box21,
            box22,
            box23,
            box24,
            box25,
            box26,
            box27,
            box28,
            box29,
        ])
示例#14
0
def create_multi_answer_widget(question, options):

    question_widget = create_question_widget(question)

    # Need to make my own checkbox out of checkbox + label because LaTeX not displaying nicely in checkbox built in description label

    labels = [
        widgets.HTML(value='<style>p{word-wrap: break-word}</style> <p>' +
                     option['answer'] + ' </p>') for option in options
    ]
    checkboxes = [
        HBox([
            Checkbox(value=False,
                     style={'description_width': 'initial'},
                     layout=Layout(width='30px')), lbl
        ],
             layout=Layout(display='flex',
                           flex_flow='row wrap',
                           align_items='stretch',
                           width='auto')) for lbl in labels
    ]

    # for each option, create a feedback box on the left and a checkbox on the right
    vertical = []
    for cb in checkboxes:
        new_hbox = widgets.HBox([Label(value=''), cb],
                                layout=Layout(display='flex',
                                              flex_flow='row wrap',
                                              align_items='stretch',
                                              width='auto'))
        #new_hbox.box_style = 'info'
        vertical.append(new_hbox)

    # vertically laid out options with feedback on the left
    option_widget = widgets.VBox(vertical,
                                 layout=Layout(display='flex',
                                               flex_flow='column',
                                               align_items='stretch',
                                               width='100%'))
    score_widget = create_score_widget('#4DD0E1')

    multi_answer = VBox([question_widget, option_widget, score_widget],
                        layout=Layout(display='flex',
                                      flex_flow='column',
                                      align_items='stretch',
                                      width='100%'))

    multi_answer.box_style = 'info'

    # compare checkbox value with original
    def check_answers(b):

        #run through each option, compare expected answer (checked/unchecked) with actual student answer
        num_options = len(options)
        incorrect = 0
        missing = 0

        option_widget = multi_answer.children[1]
        score_widget = multi_answer.children[2]

        submit_button = score_widget.children[0]

        for i in range(num_options):

            opt = option_widget.children[i]

            lbl = opt.children[0]
            cb = opt.children[1].children[0]

            actual_answer = cb.value
            expected_answer = options[i]['correct']

            # clear feedback before giving new feedback
            opt.layout = Layout(border=None)
            lbl.value = ''
            lbl.layout = Layout(width='100px')

            # red border + 'incorrect' for incorrectly checked
            # green border + 'correct!' for correctly checked
            if (expected_answer and actual_answer):
                opt.layout = Layout(border='1px solid #81C784')
                lbl.value = 'Correct!'
            if (expected_answer and not actual_answer):
                missing += 1
            if (not expected_answer and actual_answer):
                lbl.value = 'Incorrect'
                opt.layout = Layout(border='1px solid #e57373')
                incorrect += 1

        # update the score label
        if incorrect + missing == 0:
            # Success! So disable checkboxes
            for i in range(num_options):
                opt = option_widget.children[i]
                cb = opt.children[1].children[0]
                cb.disabled = True

            if submit_button.description == 'Submit':
                text = ''
            else:
                text = 'Now you got it!'

            generate_feedback(multi_answer,
                              score_widget,
                              style='success',
                              feedback_text=text,
                              show_show_answer_btn=False)
            submit_button.layout.disable = True
        else:
            #Some incorrect answers, write feedback so they can try again
            if missing > 0:
                text = 'You missed some correct options, try again!'
            else:
                text = ''

            generate_feedback(multi_answer,
                              score_widget,
                              style='danger',
                              feedback_text=text,
                              show_show_answer_btn=False)

    submit_button = score_widget.children[0]
    submit_button.on_click(check_answers)

    return (multi_answer)
示例#15
0
def calendar_view_gui(**kwargs):

    default_search_window_start_date = kwargs.get(
        "default_search_window_start_date")
    default_search_window_end_date = kwargs.get(
        "default_search_window_end_date")
    default_index_graph_start_date = kwargs.get(
        "default_index_graph_start_date")
    default_index_graph_end_date = kwargs.get("default_index_graph_end_date")

    default_shapefile = kwargs.get("default_shapefile")
    default_out_tif_folder_base = kwargs.get("default_out_tif_folder_base")
    default_MS = kwargs.get("MS")
    default_year = kwargs.get("year")

    default_api_user = kwargs.get("api_user")
    default_api_pass = kwargs.get("api_pass")
    default_ptype = kwargs.get("ptype")

    layout1 = Layout(width='96%', height='35px')
    style1 = {'description_width': 'initial'}

    layout2 = widgets.Layout(width='auto',
                             height='40px')  #set width and height
    layout3 = widgets.Layout(width='auto',
                             height='200px')  #set width and height

    # function to run when Run button is clicked
    def on_button_clicked(b):
        #run the calendar view script with parameter defined here

        run_calendar_view_from_jupyter.run_calendar_view(
            #        rcvfj.run_calendar_view_from_jupyter(
            get_scl=w_get_scl.value,
            get_bands=w_get_bands.value,
            merge_bands=w_merge_bands.value,
            lut_stretch_magic=w_lut_stretch_magic.value,
            cv_lut_magic=w_cv_lut_magic.value,
            lut_stretch_dynamic=w_lut_stretch_dynamic.value,
            cv_lut_dynamic=w_cv_lut_dynamic.value,
            stats_band=w_stats_band.value,
            graphs_band=w_graphs_band.value,
            create_ndvi=w_create_ndvi.value,
            cv_ndvi=w_cv_ndvi.value,
            stats_ndvi=w_stats_ndvi.value,
            graphs_ndvi=w_graphs_ndvi.value,
            create_bsi=w_create_bsi.value,
            cv_bsi=w_cv_bsi.value,
            stats_bsi=w_stats_bsi.value,
            graphs_bsi=w_graphs_bsi.value,
            cv_ndvi_hist=w_cv_ndvi_hist.value,
            cv_red_nir_scatter=w_cv_red_nir_scatter.value,
            get_coh=w_get_coh.value,
            stats_coh=w_stats_coh.value,
            graph_coh=w_graph_coh.value,
            get_bs=w_get_bs.value,
            cv_bs=w_cv_bs.value,
            stats_bs=w_stats_bs.value,
            graph_bs=w_graph_bs.value,
            search_window_start_date=w_search_window_start_date.value.strftime(
                "%Y-%m-%d"),
            search_window_end_date=w_search_window_end_date.value.strftime(
                "%Y-%m-%d"),
            index_graph_start_date=w_index_graph_start_date.value.strftime(
                "%Y-%m-%d"),
            index_graph_end_date=w_index_graph_end_date.value.strftime(
                "%Y-%m-%d"),
            vector_file_name=w_select_vector.value,
            out_tif_folder_base=w_select_out_tif_folder_base.value,
            parcel_id_column=w_select_parcel_id_column.value,
            crop_name_column=w_select_crop_name_column.value,
            list_of_parcel_ids_to_process=w_select_parcel_ids.value,
            plot_title=w_plot_title.value,
            exclude_cirrus=w_exclude_cirrus.value,
            buffer_size_meter=w_buffer_size_meter.value,
            centroid_shift_degrees=w_centroid_shift_degrees.value,
            MS=default_MS,
            year=str(default_year),
            api_user=default_api_user,
            api_pass=default_api_pass,
            ptype=default_ptype)

##############################################################
### Define the elements of the "What to run?" tab
##############################################################

    def set_minimum_options_what_to_run():
        w_get_scl.value = False
        w_get_bands.value = True
        w_merge_bands.value = True
        w_lut_stretch_magic.value = True
        w_cv_lut_magic.value = True
        w_lut_stretch_dynamic.value = False
        w_cv_lut_dynamic.value = False
        w_stats_band.value = False
        w_graphs_band.value = False
        #second column
        w_create_ndvi.value = True
        w_cv_ndvi.value = False
        w_stats_ndvi.value = True
        w_graphs_ndvi.value = True
        w_create_bsi.value = False
        w_cv_bsi.value = False
        w_stats_bsi.value = False
        w_graphs_bsi.value = False
        w_cv_ndvi_hist.value = False
        w_cv_red_nir_scatter.value = False
        #third column
        w_get_coh.value = False
        w_stats_coh.value = False
        w_graph_coh.value = False
        w_get_bs.value = False
        w_cv_bs.value = False
        w_stats_bs.value = False
        w_graph_bs.value = False

    #define check box widgets for the first column
    w_get_scl = widgets.Checkbox(value=True,
                                 description='Force the use of SCL imagettes',
                                 disabled=False,
                                 indent=False)

    w_get_bands = widgets.Checkbox(
        value=True,
        description='Get and download band imagettes',
        disabled=False,
        indent=False)

    w_merge_bands = widgets.Checkbox(value=True,
                                     description='Merge band imagettes',
                                     disabled=False,
                                     indent=False)

    w_lut_stretch_magic = widgets.Checkbox(value=True,
                                           description='LUT stretch magic',
                                           disabled=False,
                                           indent=False)

    w_cv_lut_magic = widgets.Checkbox(value=True,
                                      description='Calendar view LUT magic',
                                      disabled=False,
                                      indent=False)

    w_lut_stretch_dynamic = widgets.Checkbox(value=True,
                                             description='LUT stretch dynamic',
                                             disabled=False,
                                             indent=False)

    w_cv_lut_dynamic = widgets.Checkbox(
        value=True,
        description='Calendar view LUT dynamic',
        disabled=False,
        indent=False)

    w_stats_band = widgets.Checkbox(value=True,
                                    description='Calculate band statistics',
                                    disabled=False,
                                    indent=False)

    w_graphs_band = widgets.Checkbox(value=True,
                                     description='Create band graphs',
                                     disabled=False,
                                     indent=False)

    #check boxes for second column
    w_create_ndvi = widgets.Checkbox(value=True,
                                     description='Create NDVI imagettes',
                                     disabled=False,
                                     indent=False)

    w_cv_ndvi = widgets.Checkbox(value=True,
                                 description='Calendar view of NDVI imagettes',
                                 disabled=False,
                                 indent=False)

    w_stats_ndvi = widgets.Checkbox(value=True,
                                    description='Calculate NDVI statistics',
                                    disabled=False,
                                    indent=False)

    w_graphs_ndvi = widgets.Checkbox(value=True,
                                     description='Create NDVI graphs',
                                     disabled=False,
                                     indent=False)

    w_create_bsi = widgets.Checkbox(value=True,
                                    description='Create BSI imagettes',
                                    disabled=False,
                                    indent=False)

    w_cv_bsi = widgets.Checkbox(value=True,
                                description='Calendar view of BSI imagettes',
                                disabled=False,
                                indent=False)

    w_stats_bsi = widgets.Checkbox(value=True,
                                   description='Calculate BSI statistics',
                                   disabled=False,
                                   indent=False)

    w_graphs_bsi = widgets.Checkbox(value=True,
                                    description='Create BSI graphs',
                                    disabled=False,
                                    indent=False)

    w_cv_ndvi_hist = widgets.Checkbox(
        value=True,
        description='Calendar view of NDVI histograms',
        disabled=False,
        indent=False)

    w_cv_red_nir_scatter = widgets.Checkbox(
        value=True,
        description='Calendar view of Red-NIR scatterplot',
        disabled=False,
        indent=False)

    # check boxes for third column
    w_get_coh = widgets.Checkbox(value=True,
                                 description='Get coherence imagettes',
                                 disabled=False,
                                 indent=False)

    w_stats_coh = widgets.Checkbox(
        value=True,
        description='Calculate coherence statistics',
        disabled=False,
        indent=False)

    w_graph_coh = widgets.Checkbox(value=True,
                                   description='Create coherence graphs',
                                   disabled=False,
                                   indent=False)

    w_get_bs = widgets.Checkbox(value=True,
                                description='Get backscatter imagettes',
                                disabled=False,
                                indent=False)

    w_cv_bs = widgets.Checkbox(value=True,
                               description='Calendar view of backscatter',
                               disabled=False,
                               indent=False)

    w_stats_bs = widgets.Checkbox(
        value=True,
        description='Calculate backscatter statistics',
        disabled=False,
        indent=False)

    w_graph_bs = widgets.Checkbox(value=True,
                                  description='Create backscatter graphs',
                                  disabled=False,
                                  indent=False)

    #define check box widget containers for the first, "What to run?" tab
    what_to_run_first_column = VBox(children=[
        w_get_scl, w_get_bands, w_merge_bands, w_lut_stretch_magic,
        w_cv_lut_magic, w_lut_stretch_dynamic, w_cv_lut_dynamic, w_stats_band,
        w_graphs_band
    ])

    what_to_run_second_column = VBox(children=[
        w_create_ndvi, w_cv_ndvi, w_stats_ndvi, w_graphs_ndvi, w_create_bsi,
        w_cv_bsi, w_stats_bsi, w_graphs_bsi, w_cv_ndvi_hist,
        w_cv_red_nir_scatter
    ])

    what_to_run_third_column = VBox(children=[
        w_get_coh, w_stats_coh, w_graph_coh, w_get_bs, w_cv_bs, w_stats_bs,
        w_graph_bs
    ])
    what_to_run_first_widget = HBox(children=[
        what_to_run_first_column, what_to_run_second_column,
        what_to_run_third_column
    ])

    w_set_minimum_options_for_what_to_run_button = widgets.Button(
        description='Select minimum',
        disabled=False,
        button_style='',  # 'success', 'info', 'warning', 'danger' or ''
        tooltip='Select a minimum set of what to run',
        layout=layout1)

    w_set_maximum_options_for_what_to_run_button = widgets.Button(
        description='Select all',
        disabled=False,
        button_style='',  # 'success', 'info', 'warning', 'danger' or ''
        tooltip='Select a maximum set of what to run',
        layout=layout1)

    what_to_run_second_widget = HBox(children=[
        w_set_minimum_options_for_what_to_run_button,
        w_set_maximum_options_for_what_to_run_button
    ])

    tab_what_to_run = VBox(
        children=[what_to_run_first_widget, what_to_run_second_widget])

    #set selected options for minimum at startup
    set_minimum_options_what_to_run()

    #call back functions for the what to run tab
    def w_set_minimum_options_for_what_to_run_button_clicked(b):
        #first column
        w_get_scl.value = True
        w_get_bands.value = True
        w_merge_bands.value = True
        w_lut_stretch_magic.value = True
        w_cv_lut_magic.value = True
        w_lut_stretch_dynamic.value = False
        w_cv_lut_dynamic.value = False
        w_stats_band.value = False
        w_graphs_band.value = False
        #second column
        w_create_ndvi.value = True
        w_cv_ndvi.value = False
        w_stats_ndvi.value = True
        w_graphs_ndvi.value = True
        w_create_bsi.value = False
        w_cv_bsi.value = False
        w_stats_bsi.value = False
        w_graphs_bsi.value = False
        w_cv_ndvi_hist.value = False
        w_cv_red_nir_scatter.value = False
        #third column
        w_get_coh.value = False
        w_stats_coh.value = False
        w_graph_coh.value = False
        w_get_bs.value = False
        w_cv_bs.value = False
        w_stats_bs.value = False
        w_graph_bs.value = False

    def w_set_maximum_options_for_what_to_run_button_clicked(b):
        #first column
        w_get_scl.value = True
        w_get_bands.value = True
        w_merge_bands.value = True
        w_lut_stretch_magic.value = True
        w_cv_lut_magic.value = True
        w_lut_stretch_dynamic.value = True
        w_cv_lut_dynamic.value = True
        w_stats_band.value = True
        w_graphs_band.value = True
        #second column
        w_create_ndvi.value = True
        w_cv_ndvi.value = True
        w_stats_ndvi.value = True
        w_graphs_ndvi.value = True
        w_create_bsi.value = True
        w_cv_bsi.value = True
        w_stats_bsi.value = True
        w_graphs_bsi.value = True
        w_cv_ndvi_hist.value = True
        w_cv_red_nir_scatter.value = True
        #third column
        w_get_coh.value = True
        w_stats_coh.value = True
        w_graph_coh.value = True
        w_get_bs.value = True
        w_cv_bs.value = True
        w_stats_bs.value = True
        w_graph_bs.value = True

    #event handlers within the "What to run?" tab
    w_set_maximum_options_for_what_to_run_button.on_click(
        w_set_maximum_options_for_what_to_run_button_clicked)
    w_set_minimum_options_for_what_to_run_button.on_click(
        w_set_minimum_options_for_what_to_run_button_clicked)

    ##############################################################
    ### Define the elements of the "Set dates" tab
    ##############################################################
    # define widgets for window parameters (start and end dates)
    w_search_window_start_date = widgets.DatePicker(
        description='Search window start date',
        disabled=False,
        value=datetime.datetime.strptime(default_search_window_start_date,
                                         '%Y-%m-%d').date(),
        layout=layout1,
        style=style1)

    w_search_window_end_date = widgets.DatePicker(
        description='Search window end date',
        disabled=False,
        value=datetime.datetime.strptime(default_search_window_end_date,
                                         '%Y-%m-%d').date(),
        layout=layout1,
        style=style1)

    w_index_graph_start_date = widgets.DatePicker(
        description='Index graph start date',
        disabled=False,
        value=datetime.datetime.strptime(default_index_graph_start_date,
                                         '%Y-%m-%d').date(),
        size=1,
        layout=layout1,
        style=style1)

    w_index_graph_end_date = widgets.DatePicker(
        description='Index graph end date',
        disabled=False,
        value=datetime.datetime.strptime(default_index_graph_end_date,
                                         '%Y-%m-%d').date(),
        size=1,
        layout=layout1,
        style=style1)

    # This will be the second tab with all the start and end dates
    search_window_column = VBox(
        children=[w_search_window_start_date, w_search_window_end_date])
    index_graph_column = VBox(
        children=[w_index_graph_start_date, w_index_graph_end_date])
    tab_dates = HBox(children=[search_window_column, index_graph_column])

    ##############################################################
    #### Define the elements of the Vector/Output folder selector tab
    ##############################################################
    #text widget holding the full path of the selected vector shapefile
    w_select_vector = widgets.Text(value=default_shapefile,
                                   placeholder='Type something',
                                   description='Vector filename:',
                                   disabled=False,
                                   style=style1,
                                   layout=layout2)

    #text widget holding the output base folders full path
    w_select_out_tif_folder_base = widgets.Text(
        value=default_out_tif_folder_base,
        placeholder='Type something',
        description='Base folder for outputs:',
        disabled=False,
        style=style1,
        layout=layout2)

    #dropdown widget for holding the list of columns in the shapefile
    options_list_of_tuples = get_options_for_column_selection(
        default_shapefile)
    w_select_parcel_id_column = widgets.Dropdown(
        options=options_list_of_tuples,
        value=options_list_of_tuples[0][1],
        description='Parcel id column:',
        style={'description_width': 'initial'})

    w_select_crop_name_column = widgets.Dropdown(
        options=options_list_of_tuples,
        value=options_list_of_tuples[0][1],
        description='Crop name column:',
        style={'description_width': 'initial'})

    if os.path.isfile(w_select_vector.value):
        parcels = geopandas.read_file(w_select_vector.value)
        parcel_id_column = w_select_parcel_id_column.value
        default_list_of_parcel_ids_to_process = parcels[
            parcel_id_column].to_list()
        default_list_of_parcel_ids_to_process.sort()
    else:
        default_list_of_parcel_ids_to_process = [""]

    #multiple select list widget holding the list of parcel ids
    w_select_parcel_ids = widgets.SelectMultiple(
        options=default_list_of_parcel_ids_to_process,
        #     value=['Oranges'],
        rows=10,
        description='Parcel ids',
        disabled=False,
        layout=layout3,
        tyle=style1,
    )

    # Create and display a FileChooser widget
    # fc = FileChooser('c:/Users/Csaba/ownCloud')
    default_shapefile_path = os.path.dirname(w_select_vector.value)
    default_out_tif_folder_base_path = os.path.dirname(
        w_select_out_tif_folder_base.value)

    fc_shapefile = FileChooser(default_shapefile_path)
    fc_shapefile.filter_pattern = ['*.shp', '*.geojson']

    if not os.path.exists(default_out_tif_folder_base_path):
        os.makedirs(default_out_tif_folder_base_path)
    fc_out_tif_folder_base = FileChooser(default_out_tif_folder_base_path)
    fc_out_tif_folder_base.show_only_dirs = True

    #put the 2 column selector dropdown list widgets in the HBox container
    select_columns_hbox = HBox(
        children=[w_select_parcel_id_column, w_select_crop_name_column])

    # vector_file_name selection tab
    tab_vector = VBox(children=[
        fc_shapefile, w_select_vector, fc_out_tif_folder_base,
        w_select_out_tif_folder_base, select_columns_hbox, w_select_parcel_ids
    ])

    #call back functions within the "Vector/Output folder" tab
    def select_parcel_ids(vector_file_name, parcel_id_column):
        parcels = geopandas.read_file(vector_file_name)
        selected_parcel_ids = parcels[parcel_id_column].to_list()
        selected_parcel_ids.sort()
        return selected_parcel_ids

    # callback functions for file selectors
    def add_selected_shapefile_to_widget_value(chooser):
        # Print the selected path, filename, or both
        vector_file_name = fc_shapefile.selected.replace("\\", "/")
        w_select_vector.value = vector_file_name

        parcel_id_column = w_select_parcel_id_column.value
        w_select_parcel_ids.options = select_parcel_ids(
            vector_file_name, parcel_id_column)

    def add_selected_out_tif_folder_base_to_widget_value(chooser):
        # Print the selected path, filename, or both
        #     print(fc.selected_path)
        out_tif_folder_base = fc_out_tif_folder_base.selected_path.replace(
            "\\", "/")
        w_select_out_tif_folder_base.value = out_tif_folder_base

    # Function to apply to drop box object
    def add_parcel_ids_to_widget_value(x):
        parcel_id_column = w_select_parcel_id_column.value
        vector_file_name = w_select_vector.value
        w_select_parcel_ids.options = select_parcel_ids(
            vector_file_name, parcel_id_column)

    def add_column_names_to_dropdowns(x):
        options_list_of_tuples = get_options_for_column_selection(
            w_select_vector.value)
        w_select_parcel_id_column.options = options_list_of_tuples
        w_select_crop_name_column.options = options_list_of_tuples

    #Register callback function for the file selector widgets
    fc_shapefile.register_callback(add_selected_shapefile_to_widget_value)
    fc_out_tif_folder_base.register_callback(
        add_selected_out_tif_folder_base_to_widget_value)

    #when parcel id column selector widget is changed (other value selected)
    w_select_parcel_id_column.observe(add_parcel_ids_to_widget_value,
                                      names='value')

    #if shapefile name in the shapefile text widget changes for some reason we have to update
    #2 things: the list of column names and the list of parcel ids
    #first we change the list of column names
    w_select_vector.observe(add_column_names_to_dropdowns)

    ##############################################################
    ### Define the elements of the "Other parameters" tab
    ##############################################################
    #text widget holding the title of the graphs
    w_plot_title = widgets.Text(
        value=default_MS + ' ' + default_year,
        #        placeholder='eg. DK 2019',
        description='Title for graphs:',
        disabled=False,
        style={'description_width': 'initial'})

    #define check box widget for cloud mask selection
    w_exclude_cirrus = widgets.Checkbox(
        value=True,
        description='Exclude cirrus from stats calculation',
        disabled=False,
        indent=False)

    w_buffer_size_meter = widgets.BoundedIntText(
        value=50,
        min=0,
        max=1000,
        step=50,
        description='Buffer size around parcel: ',
        disabled=False,
        style={'description_width': 'initial'})

    w_centroid_shift_degrees = widgets.BoundedFloatText(
        value=0.00001,
        min=0,
        max=0.0001,
        step=0.00001,
        description='Centroid shift (degrees): ',
        disabled=False,
        style={'description_width': 'initial'})

    # Other parametrs selection tab
    tab_other = VBox(children=[
        w_plot_title, w_exclude_cirrus, w_buffer_size_meter,
        w_centroid_shift_degrees
    ])

    ###########################################################
    #    Let's put together the main gui from the defined tabs
    ###########################################################
    w_title = widgets.HTML(value="<h1>Run calendar view script</h1")

    tab = widgets.Tab(
        children=[tab_what_to_run, tab_dates, tab_vector, tab_other])
    tab.set_title(0, 'What to run?')
    tab.set_title(1, 'Set dates')
    tab.set_title(2, 'Vector/Output folder')
    tab.set_title(3, 'Other parameters')

    # run button widget
    run_button = widgets.Button(description='Run', )

    main_first_widget = HBox(children=[w_title])
    main_second_widget = VBox(children=[tab, run_button])

    #event handler for Run button clicked
    run_button.on_click(on_button_clicked)

    return VBox(children=[main_first_widget, main_second_widget])
示例#16
0
    def __init__(self):
        
        micron_units = Label('micron')   # use "option m" (Mac, for micro symbol)

        constWidth = '180px'
        tab_height = '500px'
        stepsize = 10

        #style = {'description_width': '250px'}
        style = {'description_width': '25%'}
        layout = {'width': '400px'}

        name_button_layout={'width':'25%'}
        widget_layout = {'width': '15%'}
        units_button_layout ={'width':'15%'}
        desc_button_layout={'width':'45%'}

        param_name1 = Button(description='random_seed', disabled=True, layout=name_button_layout)
        param_name1.style.button_color = 'lightgreen'

        self.random_seed = IntText(
          value=0,
          step=1,
          style=style, layout=widget_layout)

        param_name2 = Button(description='civilian_initial_count', disabled=True, layout=name_button_layout)
        param_name2.style.button_color = 'tan'

        self.civilian_initial_count = IntText(
          value=500,
          step=10,
          style=style, layout=widget_layout)

        param_name3 = Button(description='civilian_speed', disabled=True, layout=name_button_layout)
        param_name3.style.button_color = 'lightgreen'

        self.civilian_speed = FloatText(
          value=.1,
          step=0.01,
          style=style, layout=widget_layout)

        param_name4 = Button(description='civilian_birth_rate', disabled=True, layout=name_button_layout)
        param_name4.style.button_color = 'tan'

        self.civilian_birth_rate = FloatText(
          value=.0007,
          step=0.0001,
          style=style, layout=widget_layout)

        param_name5 = Button(description='civilian_death_rate', disabled=True, layout=name_button_layout)
        param_name5.style.button_color = 'lightgreen'

        self.civilian_death_rate = FloatText(
          value=.000007,
          step=1e-06,
          style=style, layout=widget_layout)

        param_name6 = Button(description='civilian_strength', disabled=True, layout=name_button_layout)
        param_name6.style.button_color = 'tan'

        self.civilian_strength = FloatText(
          value=0.01,
          step=0.001,
          style=style, layout=widget_layout)

        param_name7 = Button(description='thanos_speed', disabled=True, layout=name_button_layout)
        param_name7.style.button_color = 'lightgreen'

        self.thanos_speed = FloatText(
          value=1.5,
          step=0.1,
          style=style, layout=widget_layout)

        param_name8 = Button(description='thanos_strength', disabled=True, layout=name_button_layout)
        param_name8.style.button_color = 'tan'

        self.thanos_strength = FloatText(
          value=1000,
          step=100,
          style=style, layout=widget_layout)

        param_name9 = Button(description='thanos_motility_bias', disabled=True, layout=name_button_layout)
        param_name9.style.button_color = 'lightgreen'

        self.thanos_motility_bias = FloatText(
          value=.85,
          step=0.1,
          style=style, layout=widget_layout)

        param_name10 = Button(description='avenger_initial_count', disabled=True, layout=name_button_layout)
        param_name10.style.button_color = 'tan'

        self.avenger_initial_count = IntText(
          value=25,
          step=1,
          style=style, layout=widget_layout)

        param_name11 = Button(description='avenger_speed', disabled=True, layout=name_button_layout)
        param_name11.style.button_color = 'lightgreen'

        self.avenger_speed = FloatText(
          value=4,
          step=0.1,
          style=style, layout=widget_layout)

        param_name12 = Button(description='avenger_strength', disabled=True, layout=name_button_layout)
        param_name12.style.button_color = 'tan'

        self.avenger_strength = FloatText(
          value=10,
          step=1,
          style=style, layout=widget_layout)

        param_name13 = Button(description='avenger_motility_bias', disabled=True, layout=name_button_layout)
        param_name13.style.button_color = 'lightgreen'

        self.avenger_motility_bias = FloatText(
          value=0.5,
          step=0.1,
          style=style, layout=widget_layout)

        param_name14 = Button(description='avenger_motility_bias_with_stone', disabled=True, layout=name_button_layout)
        param_name14.style.button_color = 'tan'

        self.avenger_motility_bias_with_stone = FloatText(
          value=0.2,
          step=0.01,
          style=style, layout=widget_layout)

        units_button1 = Button(description='', disabled=True, layout=units_button_layout) 
        units_button1.style.button_color = 'lightgreen'
        units_button2 = Button(description='', disabled=True, layout=units_button_layout) 
        units_button2.style.button_color = 'tan'
        units_button3 = Button(description='micron/min', disabled=True, layout=units_button_layout) 
        units_button3.style.button_color = 'lightgreen'
        units_button4 = Button(description='1/min', disabled=True, layout=units_button_layout) 
        units_button4.style.button_color = 'tan'
        units_button5 = Button(description='1/min', disabled=True, layout=units_button_layout) 
        units_button5.style.button_color = 'lightgreen'
        units_button6 = Button(description='', disabled=True, layout=units_button_layout) 
        units_button6.style.button_color = 'tan'
        units_button7 = Button(description='micron/min', disabled=True, layout=units_button_layout) 
        units_button7.style.button_color = 'lightgreen'
        units_button8 = Button(description='', disabled=True, layout=units_button_layout) 
        units_button8.style.button_color = 'tan'
        units_button9 = Button(description='', disabled=True, layout=units_button_layout) 
        units_button9.style.button_color = 'lightgreen'
        units_button10 = Button(description='', disabled=True, layout=units_button_layout) 
        units_button10.style.button_color = 'tan'
        units_button11 = Button(description='micron/min', disabled=True, layout=units_button_layout) 
        units_button11.style.button_color = 'lightgreen'
        units_button12 = Button(description='', disabled=True, layout=units_button_layout) 
        units_button12.style.button_color = 'tan'
        units_button13 = Button(description='', disabled=True, layout=units_button_layout) 
        units_button13.style.button_color = 'lightgreen'
        units_button14 = Button(description='', disabled=True, layout=units_button_layout) 
        units_button14.style.button_color = 'tan'

        desc_button1 = Button(description='', disabled=True, layout=desc_button_layout) 
        desc_button1.style.button_color = 'lightgreen'
        desc_button2 = Button(description='initial number of civilians', disabled=True, layout=desc_button_layout) 
        desc_button2.style.button_color = 'tan'
        desc_button3 = Button(description='civilian migration speed', disabled=True, layout=desc_button_layout) 
        desc_button3.style.button_color = 'lightgreen'
        desc_button4 = Button(description='civilian birth rate', disabled=True, layout=desc_button_layout) 
        desc_button4.style.button_color = 'tan'
        desc_button5 = Button(description='civilian death rate', disabled=True, layout=desc_button_layout) 
        desc_button5.style.button_color = 'lightgreen'
        desc_button6 = Button(description='civilian battle strength', disabled=True, layout=desc_button_layout) 
        desc_button6.style.button_color = 'tan'
        desc_button7 = Button(description='Thanos migration speed', disabled=True, layout=desc_button_layout) 
        desc_button7.style.button_color = 'lightgreen'
        desc_button8 = Button(description='Thanos battle strength', disabled=True, layout=desc_button_layout) 
        desc_button8.style.button_color = 'tan'
        desc_button9 = Button(description='Thanos migration bias (0 = Brownian)', disabled=True, layout=desc_button_layout) 
        desc_button9.style.button_color = 'lightgreen'
        desc_button10 = Button(description='number of Avengers', disabled=True, layout=desc_button_layout) 
        desc_button10.style.button_color = 'tan'
        desc_button11 = Button(description='Avengers migration speed', disabled=True, layout=desc_button_layout) 
        desc_button11.style.button_color = 'lightgreen'
        desc_button12 = Button(description='Avengers battle stregth', disabled=True, layout=desc_button_layout) 
        desc_button12.style.button_color = 'tan'
        desc_button13 = Button(description='Avengers migration bias (0 = Brownian)', disabled=True, layout=desc_button_layout) 
        desc_button13.style.button_color = 'lightgreen'
        desc_button14 = Button(description='Avengers migration bias when hiding Infinity Stone', disabled=True, layout=desc_button_layout) 
        desc_button14.style.button_color = 'tan'

        row1 = [param_name1, self.random_seed, units_button1, desc_button1] 
        row2 = [param_name2, self.civilian_initial_count, units_button2, desc_button2] 
        row3 = [param_name3, self.civilian_speed, units_button3, desc_button3] 
        row4 = [param_name4, self.civilian_birth_rate, units_button4, desc_button4] 
        row5 = [param_name5, self.civilian_death_rate, units_button5, desc_button5] 
        row6 = [param_name6, self.civilian_strength, units_button6, desc_button6] 
        row7 = [param_name7, self.thanos_speed, units_button7, desc_button7] 
        row8 = [param_name8, self.thanos_strength, units_button8, desc_button8] 
        row9 = [param_name9, self.thanos_motility_bias, units_button9, desc_button9] 
        row10 = [param_name10, self.avenger_initial_count, units_button10, desc_button10] 
        row11 = [param_name11, self.avenger_speed, units_button11, desc_button11] 
        row12 = [param_name12, self.avenger_strength, units_button12, desc_button12] 
        row13 = [param_name13, self.avenger_motility_bias, units_button13, desc_button13] 
        row14 = [param_name14, self.avenger_motility_bias_with_stone, units_button14, desc_button14] 

        box_layout = Layout(display='flex', flex_flow='row', align_items='stretch', width='100%')
        box1 = Box(children=row1, layout=box_layout)
        box2 = Box(children=row2, layout=box_layout)
        box3 = Box(children=row3, layout=box_layout)
        box4 = Box(children=row4, layout=box_layout)
        box5 = Box(children=row5, layout=box_layout)
        box6 = Box(children=row6, layout=box_layout)
        box7 = Box(children=row7, layout=box_layout)
        box8 = Box(children=row8, layout=box_layout)
        box9 = Box(children=row9, layout=box_layout)
        box10 = Box(children=row10, layout=box_layout)
        box11 = Box(children=row11, layout=box_layout)
        box12 = Box(children=row12, layout=box_layout)
        box13 = Box(children=row13, layout=box_layout)
        box14 = Box(children=row14, layout=box_layout)

        self.tab = VBox([
          box1,
          box2,
          box3,
          box4,
          box5,
          box6,
          box7,
          box8,
          box9,
          box10,
          box11,
          box12,
          box13,
          box14,
        ])
示例#17
0
    def __init__(self,
                 l=1600,
                 v_courant=0.8,
                 v_ramer=1.5,
                 v_course=3.0,
                 beta=90,
                 calcul_temps_rame=calcul_temps_rame,
                 calcul_temps_course=calcul_temps_course,
                 calcul_distance=calcul_distance,
                 calcul_vecteurs=calcul_vecteurs):

        # paramètres du problème
        self.l = l  # largeur de la rivière (m)
        self.v_courant = v_courant  # vitesse du courant (m/s)
        self.v_ramer = v_ramer  # vitesse à la rame (m/s)
        self.v_course = v_course  # vitesse de course (m/s)

        self.beta = beta  # angle choisi en degrés
        self.beta_rad = degre_rad(self.beta)  # angle choisi en radians

        # fonction pour réaliser les différents calculs
        self.calcul_temps_rame = calcul_temps_rame
        self.calcul_temps_course = calcul_temps_course
        self.calcul_distance = calcul_distance
        self.calcul_vecteurs = calcul_vecteurs

        ### Calculs
        # calcul du temps
        t_r = self.calcul_temps_rame(self.l, self.v_ramer, self.beta_rad)
        t_c = self.calcul_temps_course(self.l, self.v_ramer, self.v_courant,
                                       self.v_course, self.beta_rad)
        t = t_r + t_c

        # calcul de la trajectoire
        b_prime_x = self.calcul_distance(self.l, self.v_ramer, self.v_courant,
                                         self.beta_rad)

        # calcul des différents vecteurs
        vects = self.calcul_vecteurs(self.v_ramer, self.v_courant,
                                     self.beta_rad)

        ### Creation de l'IHM
        # input
        self.beta_slider = widgets.FloatSlider(min=70,
                                               max=160,
                                               step=1,
                                               value=90,
                                               description='$Beta$:')
        self.beta_slider.observe(self.beta_event_handler, names='value')

        self.v_course_slider = widgets.FloatSlider(
            min=0.5,
            max=5.0,
            step=0.05,
            value=3.0,
            description='$v_{course} [m/s]$:')
        self.v_course_slider.observe(self.v_course_event_handler,
                                     names='value')

        self.v_ramer_slider = widgets.FloatSlider(
            min=0.5,
            max=5,
            step=0.05,
            value=1.5,
            description='$v_{rame} [m/s]$:')
        self.v_ramer_slider.observe(self.v_ramer_event_handler, names='value')

        self.v_courant_slider = widgets.FloatSlider(
            min=0.1, max=3, step=0.05, value=0.8, description='$v_{c} [m/s]$:')
        self.v_courant_slider.observe(self.v_courant_event_handler,
                                      names='value')

        # output
        self.text_output = widgets.Output()

        ### Creation du graphique rivière
        fig_riviere = figure(title="Logan",
                             plot_height=500,
                             plot_width=980,
                             y_range=(-100, 1900),
                             x_range=(-2000, 3000),
                             background_fill_color='#ffffff',
                             toolbar_location="below")
        fig_riviere.ygrid.visible = False

        # rives
        fig_riviere.line([-5000, 5000], [0, 0], color="#5A2806", line_width=5)
        fig_riviere.line([-5000, 5000], [self.l, self.l],
                         color="#5A2806",
                         line_width=5)

        # fond de l'image
        fig_riviere.add_layout(
            BoxAnnotation(bottom=0,
                          top=self.l,
                          fill_alpha=0.1,
                          fill_color='blue'))
        fig_riviere.add_layout(
            BoxAnnotation(bottom=-100,
                          top=0,
                          fill_alpha=0.1,
                          fill_color='green'))
        fig_riviere.add_layout(
            BoxAnnotation(bottom=self.l,
                          top=1900,
                          fill_alpha=0.1,
                          fill_color='green'))

        # point initial A (fixe)
        fig_riviere.circle([0], [0],
                           size=10,
                           fill_color='#e32020',
                           line_color='#e32020',
                           legend="Point initial")

        # point final B (fixe)
        fig_riviere.circle([0], [self.l],
                           size=10,
                           fill_color='#e32020',
                           line_color='#e32020',
                           legend="Point final")

        # point d'arrivée reel B prime (variable)
        self.circle_b_prime = fig_riviere.circle([b_prime_x], [self.l],
                                                 size=10,
                                                 fill_color='#0A0451',
                                                 line_color='#0A0451',
                                                 legend="Point d'arrivée")

        # trajectoire (variable)
        self.line_traj_rame = fig_riviere.line([0, b_prime_x], [0, self.l],
                                               color='#ccce2b',
                                               line_width=2.5,
                                               alpha=0.8,
                                               line_dash='dashed',
                                               legend="Trajectoire")
        self.line_traj_course = fig_riviere.line([b_prime_x, 0],
                                                 [self.l, self.l],
                                                 color='#ccce2b',
                                                 line_width=2.5,
                                                 alpha=0.8,
                                                 line_dash='dashed',
                                                 legend="Trajectoire")

        # vecteur vitesse à la rame
        self.vect_v_ramer = Arrow(end=OpenHead(line_color='red',
                                               size=10,
                                               line_width=1.5),
                                  x_start=0,
                                  y_start=0,
                                  x_end=vects['end_ramer']['x'],
                                  y_end=vects['end_ramer']['y'],
                                  line_color='red',
                                  line_width=1.5)
        fig_riviere.add_layout(self.vect_v_ramer)

        # vecteur vitesse du courant
        self.vect_v_courant = Arrow(end=OpenHead(line_color='blue',
                                                 size=10,
                                                 line_width=1.5),
                                    x_start=vects['end_ramer']['x'],
                                    y_start=vects['end_ramer']['y'],
                                    x_end=vects['end_total']['x'],
                                    y_end=vects['end_total']['y'],
                                    line_color='blue',
                                    line_width=1.5)
        fig_riviere.add_layout(self.vect_v_courant)

        # vecteur vitesse résultant
        self.vect_v_total = Arrow(end=OpenHead(line_color='green',
                                               size=10,
                                               line_width=1.5),
                                  x_start=0,
                                  y_start=0,
                                  x_end=vects['end_total']['x'],
                                  y_end=vects['end_total']['y'],
                                  line_color='green',
                                  line_width=1.5)
        fig_riviere.add_layout(self.vect_v_total)

        # legend
        fig_riviere.legend.orientation = 'horizontal'

        ### Creation du graphique de temps
        fig_temps = figure(title="Temps",
                           plot_height=200,
                           plot_width=980,
                           y_range=(-10, 10),
                           x_range=(0, 3000),
                           background_fill_color='#ffffff',
                           toolbar_location=None)
        fig_temps.yaxis.visible = None
        fig_temps.xaxis.axis_label = 'Temps [s]'

        # temps à la rame (variable)
        self.line_t_r = fig_temps.line([0, t_r], [0, 0],
                                       color='#6DD3DB',
                                       line_width=25,
                                       legend='Temps navigation [s]')

        # temps à la course (variable)
        self.line_t_c = fig_temps.line([t_r, t], [0, 0],
                                       color='#4a8d5c',
                                       line_width=25,
                                       legend='Temps course [s]')

        # legend
        fig_temps.legend.orientation = 'horizontal'

        # afficher valeurs temps
        with self.text_output:
            print('Temps de navigation: \t{:0.1f}s'.format(t_r))
            print('Temps de course à pieds: {:0.1f}s'.format(t_c))
            print('Temps total: \t\t{:0.1f}s'.format(t))

        ### On affiche
        # Les graphiques
        show(gridplot([[fig_riviere], [fig_temps]]), notebook_handle=True)

        # Et l'interface pour l'interaction
        display(
            VBox([self.beta_slider, self.v_course_slider, self.text_output]))
示例#18
0
    def _widget(self):
        """ Create IPython widget for display within a notebook """
        try:
            return self._cached_widget
        except AttributeError:
            pass

        try:
            from ipywidgets import Layout, VBox, HBox, IntText, Button, HTML, Accordion
        except ImportError:
            self._cached_widget = None
            return None

        layout = Layout(width="150px")

        if self.dashboard_link:
            link = '<p><b>Dashboard: </b><a href="%s" target="_blank">%s</a></p>\n' % (
                self.dashboard_link,
                self.dashboard_link,
            )
        else:
            link = ""

        title = "<h2>%s</h2>" % self._cluster_class_name
        title = HTML(title)
        dashboard = HTML(link)

        status = HTML(self._widget_status(), layout=Layout(min_width="150px"))

        if self._supports_scaling:
            request = IntText(0, description="Workers", layout=layout)
            scale = Button(description="Scale", layout=layout)

            minimum = IntText(0, description="Minimum", layout=layout)
            maximum = IntText(0, description="Maximum", layout=layout)
            adapt = Button(description="Adapt", layout=layout)

            accordion = Accordion(
                [HBox([request, scale]),
                 HBox([minimum, maximum, adapt])],
                layout=Layout(min_width="500px"),
            )
            accordion.selected_index = None
            accordion.set_title(0, "Manual Scaling")
            accordion.set_title(1, "Adaptive Scaling")

            def adapt_cb(b):
                self.adapt(minimum=minimum.value, maximum=maximum.value)
                update()

            adapt.on_click(adapt_cb)

            def scale_cb(b):
                with log_errors():
                    n = request.value
                    with ignoring(AttributeError):
                        self._adaptive.stop()
                    self.scale(n)
                    update()

            scale.on_click(scale_cb)
        else:
            accordion = HTML("")

        box = VBox([title, HBox([status, accordion]), dashboard])

        self._cached_widget = box

        def update():
            status.value = self._widget_status()

        cluster_repr_interval = parse_timedelta(
            dask.config.get("distributed.deploy.cluster-repr-interval",
                            default="ms"))
        pc = PeriodicCallback(update, cluster_repr_interval * 1000)
        self.periodic_callbacks["cluster-repr"] = pc
        pc.start()

        return box
示例#19
0
    def __init__(self,
                 images,
                 name="iterator",
                 show_name=True,
                 show_axis=False,
                 show_random=True,
                 fig_size=(10, 10),
                 buttons_vertical=False,
                 image_display_function=None):
        if len(images) == 0:
            raise Exception("No images provided")

        self.show_axis = show_axis
        self.name = name
        self.show_name = show_name
        self.show_random = show_random
        self.images = images
        self.max_pos = len(self.images) - 1
        self.pos = 0
        self.fig_size = fig_size
        self.buttons_vertical = buttons_vertical

        if image_display_function is None:
            self.image_display_function = self.__show_image
        else:
            self.image_display_function = image_display_function

        self.previous_button = self.__create_button("Previous",
                                                    (self.pos == 0),
                                                    self.__on_previous_clicked)
        self.next_button = self.__create_button("Next",
                                                (self.pos == self.max_pos),
                                                self.__on_next_clicked)
        self.save_button = self.__create_button("Save", False,
                                                self.__on_save_clicked)
        self.save_function = self.__save_function  # save_function

        buttons = [self.previous_button, self.next_button]

        if self.show_random:
            self.random_button = self.__create_button("Random", False,
                                                      self.__on_random_clicked)
            buttons.append(self.random_button)

        buttons.append(self.save_button)

        label_total = Label(value='/ {}'.format(len(self.images)))
        self.text_index = BoundedIntText(value=1, min=1, max=len(self.images))
        self.text_index.layout.width = '80px'
        self.text_index.layout.height = '35px'
        self.text_index.observe(self.__selected_index)
        self.out = Output()
        self.out.add_class(name)

        if self.buttons_vertical:
            self.all_widgets = HBox(children=[
                VBox(children=[HBox([self.text_index, label_total])] +
                     buttons), self.out
            ])
        else:
            self.all_widgets = VBox(children=[
                HBox([self.text_index, label_total]),
                HBox(children=buttons), self.out
            ])
        ## loading js library to perform html screenshots
        j_code = """
                require.config({
                    paths: {
                        html2canvas: "https://html2canvas.hertzen.com/dist/html2canvas.min"
                    }
                });
            """
        display(Javascript(j_code))
    def __init__(self):
        
        micron_units = Label('micron')   # use "option m" (Mac, for micro symbol)

        constWidth = '180px'
        tab_height = '500px'
        stepsize = 10

        #style = {'description_width': '250px'}
        style = {'description_width': '25%'}
        layout = {'width': '400px'}

        name_button_layout={'width':'25%'}
        widget_layout = {'width': '15%'}
        units_button_layout ={'width':'15%'}
        desc_button_layout={'width':'45%'}

        param_name1 = Button(description='number_of_cells', disabled=True, layout=name_button_layout)
        param_name1.style.button_color = 'lightgreen'

        self.number_of_cells = IntText(
          value=3,
          step=0.1,
          style=style, layout=widget_layout)

        param_name2 = Button(description='is_motile', disabled=True, layout=name_button_layout)
        param_name2.style.button_color = 'tan'

        self.is_motile = Checkbox(
          value=False,
          style=style, layout=widget_layout)

        param_name3 = Button(description='persistence_time', disabled=True, layout=name_button_layout)
        param_name3.style.button_color = 'lightgreen'

        self.persistence_time = FloatText(
          value=30,
          step=1,
          style=style, layout=widget_layout)

        param_name4 = Button(description='migration_speed', disabled=True, layout=name_button_layout)
        param_name4.style.button_color = 'tan'

        self.migration_speed = FloatText(
          value=2,
          step=0.1,
          style=style, layout=widget_layout)

        param_name5 = Button(description='migration_bias', disabled=True, layout=name_button_layout)
        param_name5.style.button_color = 'lightgreen'

        self.migration_bias = FloatText(
          value=0.8,
          step=0.1,
          style=style, layout=widget_layout)

        param_name6 = Button(description='bias_migration_angle', disabled=True, layout=name_button_layout)
        param_name6.style.button_color = 'tan'

        self.bias_migration_angle = FloatText(
          value=30,
          step=1,
          style=style, layout=widget_layout)

        units_button1 = Button(description='', disabled=True, layout=units_button_layout) 
        units_button1.style.button_color = 'lightgreen'
        units_button2 = Button(description='', disabled=True, layout=units_button_layout) 
        units_button2.style.button_color = 'tan'
        units_button3 = Button(description='min', disabled=True, layout=units_button_layout) 
        units_button3.style.button_color = 'lightgreen'
        units_button4 = Button(description='micron/min', disabled=True, layout=units_button_layout) 
        units_button4.style.button_color = 'tan'
        units_button5 = Button(description='', disabled=True, layout=units_button_layout) 
        units_button5.style.button_color = 'lightgreen'
        units_button6 = Button(description='degree', disabled=True, layout=units_button_layout) 
        units_button6.style.button_color = 'tan'

        desc_button1 = Button(description='number of cell tracks to simulate', disabled=True, layout=desc_button_layout) 
        desc_button1.style.button_color = 'lightgreen'
        desc_button2 = Button(description='true if cells are motile', disabled=True, layout=desc_button_layout) 
        desc_button2.style.button_color = 'tan'
        desc_button3 = Button(description='mean persistence time', disabled=True, layout=desc_button_layout) 
        desc_button3.style.button_color = 'lightgreen'
        desc_button4 = Button(description='migration speed', disabled=True, layout=desc_button_layout) 
        desc_button4.style.button_color = 'tan'
        desc_button5 = Button(description='migration bias parameter', disabled=True, layout=desc_button_layout) 
        desc_button5.style.button_color = 'lightgreen'
        desc_button6 = Button(description='migration bias angle respect to x-axis', disabled=True, layout=desc_button_layout) 
        desc_button6.style.button_color = 'tan'

        row1 = [param_name1, self.number_of_cells, units_button1, desc_button1] 
        row2 = [param_name2, self.is_motile, units_button2, desc_button2] 
        row3 = [param_name3, self.persistence_time, units_button3, desc_button3] 
        row4 = [param_name4, self.migration_speed, units_button4, desc_button4] 
        row5 = [param_name5, self.migration_bias, units_button5, desc_button5] 
        row6 = [param_name6, self.bias_migration_angle, units_button6, desc_button6] 

        box_layout = Layout(display='flex', flex_flow='row', align_items='stretch', width='100%')
        box1 = Box(children=row1, layout=box_layout)
        box2 = Box(children=row2, layout=box_layout)
        box3 = Box(children=row3, layout=box_layout)
        box4 = Box(children=row4, layout=box_layout)
        box5 = Box(children=row5, layout=box_layout)
        box6 = Box(children=row6, layout=box_layout)

        self.tab = VBox([
          box1,
          box2,
          box3,
          box4,
          box5,
          box6,
        ])
示例#21
0
def create_fill_in_the_blanks_widget(question, sections):

    question_widget = create_question_widget(question)
    num_sections = len(sections)

    paragraph = HBox([],
                     layout=Layout(display='flex',
                                   flex_flow='row wrap',
                                   align_items='stretch',
                                   width='auto'))
    for i in range(num_sections):
        section = sections[i]
        # Because row-wrap still not working. See https://stackoverflow.com/questions/58405678/text-wrapping-in-ipywidgets
        prefix = widgets.HTML(
            value='<style>p{word-wrap: break-word}</style> <p>' +
            section['prefix'] + ' </p>')
        #prefix = Label(value = section['prefix'], layout=Layout(width='auto'))
        blank = Text(value='',
                     placeholder='',
                     description='',
                     disabled=False,
                     layout=(Layout(width='auto')))

        suffix = widgets.HTML(
            value='<style>p{word-wrap: break-word}</style> <p>' +
            section['suffix'] + ' </p>')
        #suffix = Label(value=section['suffix'], layout=Layout(width='auto'))

        new_hbox = widgets.HBox([prefix, blank, suffix],
                                layout=Layout(display='flex',
                                              flex_flow='row wrap',
                                              align_items='stretch',
                                              width='auto'))

        # new_hbox.box_style = 'info'
        paragraph.children += (new_hbox, )

    # please G-d of programmers forgive me for I don't yet know how to get that colour from css.
    score_widget = create_score_widget('#4DD0E1')
    #    fill_in = AppLayout(header=question_widget,
    #                             left_sidebar=paragraph,
    #                             center=None,
    #                             right_sidebar=None,
    #                             footer=score_widget, layout=Layout(display='flex', flex_flow='column', #align_items='stretch', width='100%'))
    fill_in = VBox([question_widget, paragraph, score_widget],
                   layout=Layout(display='flex',
                                 flex_flow='column',
                                 align_items='stretch',
                                 width='100%'))

    fill_in.box_style = 'info'

    # compare checkbox value with original
    def check_answers(b):
        # run through each option, compare expected answer (checked/unchecked) with actual student answer
        num_sections = len(sections)
        incorrect = 0
        missing = 0

        paragraph_widget = fill_in.children[1]
        feedback_widget = fill_in.children[2]

        submit_button = feedback_widget.children[0]

        for i in range(num_sections):
            blank = paragraph_widget.children[i].children[1]

            actual_answer = blank.value
            expected_answer = sections[i]['answer']

            # clear feedback before giving new feedback
            blank.layout = Layout(border='None', width='auto', height='32px')

            # red border + 'incorrect' for incorrectly checked
            # green border + 'correct!' for correctly checked
            if (actual_answer == ''):
                missing += 1
            elif (expected_answer == actual_answer):
                blank.layout = Layout(border='1px solid #81C784',
                                      width='auto',
                                      height='31px')
            else:
                blank.layout = Layout(border='1px solid #e57373',
                                      width='auto',
                                      height='31px')
                incorrect += 1

        # update the score label
        if incorrect + missing == 0:
            # Success! So disable checkboxes
            for i in range(num_sections):
                blank = paragraph_widget.children[i].children[1]
                blank.disabled = True

            if submit_button.description == 'Submit':
                text = ''
            else:
                text = 'Now you got it!'

            generate_feedback(fill_in,
                              score_widget,
                              style='success',
                              feedback_text=text,
                              show_show_answer_btn=False)
            submit_button.layout.disable = True
        else:
            # Some incorrect answers, write feedback so they can try again
            if missing > 0:
                text = 'Fill in all the blanks!'
            else:
                text = ''

            generate_feedback(fill_in,
                              score_widget,
                              style='danger',
                              feedback_text=text,
                              show_show_answer_btn=True)

    def show_answers(b):
        num_sections = len(sections)

        paragraph_widget = fill_in.children[1]
        feedback_widget = fill_in.children[2]
        submit_button = feedback_widget.children[0]

        for i in range(num_sections):

            blank = paragraph_widget.children[i].children[1]
            # clear feedback before giving the answers
            blank.value = ''
            blank.layout = Layout(border='None', width='auto', height='32px')

            blank.placeholder = sections[i]['answer']

        generate_feedback(fill_in, score_widget, style='warning')

    submit_button = score_widget.children[0]
    submit_button.on_click(check_answers)
    show_answer_button = score_widget.children[2]
    show_answer_button.on_click(show_answers)

    return (fill_in)
示例#22
0
    def _widget(self):
        """ Create IPython widget for display within a notebook """
        try:
            return self._cached_widget
        except AttributeError:
            pass

        if self.asynchronous:
            return None

        try:
            from ipywidgets import Layout, VBox, HBox, IntText, Button, HTML, Accordion
        except ImportError:
            self._cached_widget = None
            return None

        layout = Layout(width="150px")

        title = HTML("<h2>GatewayCluster</h2>")

        status = HTML(self._widget_status(), layout=Layout(min_width="150px"))

        request = IntText(0, description="Workers", layout=layout)
        scale = Button(description="Scale", layout=layout)

        minimum = IntText(0, description="Minimum", layout=layout)
        maximum = IntText(0, description="Maximum", layout=layout)
        adapt = Button(description="Adapt", layout=layout)

        accordion = Accordion(
            [HBox([request, scale]),
             HBox([minimum, maximum, adapt])],
            layout=Layout(min_width="500px"),
        )
        accordion.selected_index = None
        accordion.set_title(0, "Manual Scaling")
        accordion.set_title(1, "Adaptive Scaling")

        @scale.on_click
        def scale_cb(b):
            with log_errors():
                self.scale(request.value)

        @adapt.on_click
        def adapt_cb(b):
            self.adapt(minimum=minimum.value, maximum=maximum.value)

        name = HTML("<p><b>Name: </b>{0}</p>".format(self.name))

        elements = [title, HBox([status, accordion]), name]

        if self.dashboard_link is not None:
            link = HTML(
                '<p><b>Dashboard: </b><a href="{0}" target="_blank">{0}'
                "</a></p>\n".format(self.dashboard_link))
            elements.append(link)

        self._cached_widget = box = VBox(elements)
        self._status_widget = status

        return box
示例#23
0
    def __init__(self):
        
        micron_units = Label('micron')   # use "option m" (Mac, for micro symbol)

        constWidth = '180px'
        tab_height = '500px'
        stepsize = 10

        #style = {'description_width': '250px'}
        style = {'description_width': '25%'}
        layout = {'width': '400px'}

        name_button_layout={'width':'25%'}
        widget_layout = {'width': '15%'}
        units_button_layout ={'width':'15%'}
        desc_button_layout={'width':'45%'}


        menv_var1 = Button(description='oxygen (mmHg)', disabled=True, layout=name_button_layout)
        menv_var1.style.button_color = 'tan'

        param_name1 = Button(description='diffusion_coefficient', disabled=True, layout=name_button_layout)

        self.oxygen_diffusion_coefficient = FloatText(value=100000.000000,
          step=10000,style=style, layout=widget_layout)

        param_name2 = Button(description='decay_rate', disabled=True, layout=name_button_layout)

        self.oxygen_decay_rate = FloatText(value=.1,
          step=0.01,style=style, layout=widget_layout)
        param_name3 = Button(description='initial_condition', disabled=True, layout=name_button_layout)

        self.oxygen_initial_condition = FloatText(value=38,style=style, layout=widget_layout)
        param_name4 = Button(description='Dirichlet_boundary_condition', disabled=True, layout=name_button_layout)

        self.oxygen_Dirichlet_boundary_condition = FloatText(value=38,style=style, layout=widget_layout)
        self.oxygen_Dirichlet_boundary_condition_toggle = Checkbox(description='on/off', disabled=False,style=style, layout=widget_layout)
        self.calculate_gradient = Checkbox(description='calculate_gradients', disabled=False, layout=desc_button_layout)
        self.track_internal = Checkbox(description='track_in_agents', disabled=False, layout=desc_button_layout)


         #  ------- micronenv info
        menv_units_button1 = Button(description='micron^2/min', disabled=True, layout=units_button_layout) 
        menv_units_button2 = Button(description='1/min', disabled=True, layout=units_button_layout) 
        menv_units_button3 = Button(description='mmHg', disabled=True, layout=units_button_layout) 
        menv_units_button4 = Button(description='mmHg', disabled=True, layout=units_button_layout) 




        row_oxygen = [menv_var1,  ] 
        row1 = [param_name1, self.oxygen_diffusion_coefficient, menv_units_button1]
        row2 = [param_name2, self.oxygen_decay_rate, menv_units_button2]
        row3 = [param_name3, self.oxygen_initial_condition, menv_units_button3]
        row4 = [param_name4, self.oxygen_Dirichlet_boundary_condition, menv_units_button4, self.oxygen_Dirichlet_boundary_condition_toggle]
        row5 = [self.calculate_gradient,]
        row6 = [self.track_internal,]


        box_layout = Layout(display='flex', flex_flow='row', align_items='stretch', width='100%')
        box_oxygen = Box(children=row_oxygen, layout=box_layout)
        box1 = Box(children=row1, layout=box_layout)
        box2 = Box(children=row2, layout=box_layout)
        box3 = Box(children=row3, layout=box_layout)
        box4 = Box(children=row4, layout=box_layout)
        box5 = Box(children=row5, layout=box_layout)
        box6 = Box(children=row6, layout=box_layout)

        self.tab = VBox([
          box_oxygen,
          box1,
          box2,
          # box3,
          # box4,
          box5,
          box6,
        ])
示例#24
0
文件: log.py 项目: InsightLab/PyMove
def _log_progress(
    sequence: Iterable,
    desc: str | None = None,
    total: int | None = None,
    miniters: int | None = None
):
    """
    Make and display a progress bar.

    Parameters
    ----------
    sequence : iterable
        Represents a sequence of elements.
    desc : str, optional
        Represents the description of the operation, by default None.
    total : int, optional
        Represents the total/number elements in sequence, by default None.
    miniters : int, optional
        Represents the steps in which the bar will be updated, by default None.

    """
    if desc is None:
        desc = ''
    is_iterator = False
    if total is None:
        try:
            total = len(sequence)  # type: ignore
        except TypeError:
            is_iterator = True
    if total is not None:
        if miniters is None:
            if total <= 200:
                miniters = 1
            else:
                miniters = int(total / 200)
    else:
        if miniters is None:
            miniters = 1

    if is_iterator:
        progress = IntProgress(min=0, max=1, value=1)
        progress.bar_style = 'info'
    else:
        progress = IntProgress(min=0, max=total, value=0)
    label = HTML()
    box = VBox(children=[label, progress])
    display(box)

    index = 0
    try:
        for index, record in enumerate(sequence, 1):
            if index == 1 or index % miniters == 0:
                if is_iterator:
                    label.value = f'{desc}: {index} / ?'
                else:
                    progress.value = index
                    label.value = f'{desc}: {index} / {total}'
            yield record
    except Exception:
        progress.bar_style = 'danger'
        raise
    else:
        progress.bar_style = 'success'
        progress.value = index
        label.value = '{}: {}'.format(desc, str(index or '?'))
示例#25
0
文件: widgets.py 项目: Calysto/conx
    def make_controls(self):
        layout = Layout(width='100%', height="100%")
        button_begin = Button(icon="fast-backward", layout=layout)
        button_prev = Button(icon="backward", layout=layout)
        button_next = Button(icon="forward", layout=layout)
        button_end = Button(icon="fast-forward", layout=layout)
        #button_prop = Button(description="Propagate", layout=Layout(width='100%'))
        #button_train = Button(description="Train", layout=Layout(width='100%'))
        self.button_play = Button(icon="play", description="Play", layout=layout)
        step_down = Button(icon="sort-down", layout=Layout(width="95%", height="100%"))
        step_up = Button(icon="sort-up", layout=Layout(width="95%", height="100%"))
        up_down = HBox([step_down, step_up], layout=Layout(width="100%", height="100%"))
        refresh_button = Button(icon="refresh", layout=Layout(width="25%", height="100%"))

        self.position_text = IntText(value=0, layout=layout)

        self.control_buttons = HBox([
            button_begin,
            button_prev,
            #button_train,
            self.position_text,
            button_next,
            button_end,
            self.button_play,
            up_down,
            refresh_button
        ], layout=Layout(width='100%', height="100%"))
        length = (len(self.net.dataset.train_inputs) - 1) if len(self.net.dataset.train_inputs) > 0 else 0
        self.control_slider = IntSlider(description="Dataset index",
                                   continuous_update=False,
                                   min=0,
                                   max=max(length, 0),
                                   value=0,
                                   layout=Layout(width='100%'))
        if self.net.config["dashboard.dataset"] == "Train":
            length = len(self.net.dataset.train_inputs)
        else:
            length = len(self.net.dataset.test_inputs)
        self.total_text = Label(value="of %s" % length, layout=Layout(width="100px"))
        self.zoom_slider = FloatSlider(description="Zoom",
                                       continuous_update=False,
                                       min=0, max=1.0,
                                       style={"description_width": 'initial'},
                                       layout=Layout(width="65%"),
                                       value=self.net.config["svg_scale"] if self.net.config["svg_scale"] is not None else 0.5)

        ## Hook them up:
        button_begin.on_click(lambda button: self.goto("begin"))
        button_end.on_click(lambda button: self.goto("end"))
        button_next.on_click(lambda button: self.goto("next"))
        button_prev.on_click(lambda button: self.goto("prev"))
        self.button_play.on_click(self.toggle_play)
        self.control_slider.observe(self.update_slider_control, names='value')
        refresh_button.on_click(lambda widget: (self.update_control_slider(),
                                                self.output.clear_output(),
                                                self.regenerate()))
        step_down.on_click(lambda widget: self.move_step("down"))
        step_up.on_click(lambda widget: self.move_step("up"))
        self.zoom_slider.observe(self.update_zoom_slider, names='value')
        self.position_text.observe(self.update_position_text, names='value')
        # Put them together:
        controls = VBox([HBox([self.control_slider, self.total_text], layout=Layout(height="40px")),
                         self.control_buttons], layout=Layout(width='100%'))

        #net_page = VBox([control, self.net_svg], layout=Layout(width='95%'))
        controls.on_displayed(lambda widget: self.regenerate())
        return controls
def updateviewcontrol():
    global UI_viewcontrol, list_slider, confidence_list_slider, security_list, list_relative_controls, floattext_uncertainty

    list_slider = []
    confidence_list_slider = []
    security_list = []
    #list_security=list(dict_settings['security'].keys()) # Original line
    list_security = list(dict_settings['security'].values()
                         )  # Changed the name next to sliders to ticker name.
    for n in range(len(dict_settings['security'])):
        #temp_slider=FloatSlider(value=Pi[n], description=list_security[n], continuous_update=False, max=0.2, min=-0.2, readout_format='.2%', step=0.2/100,style={'description_width':'100PX'})
        temp_slider = FloatSlider(
            value=Pi[n],
            description='View on Asset',
            max=0.2,
            min=-0.2,
            readout_format='.2%',
            step=0.2 / 100,
            style={'description_width': '100PX'}
        )  #Slider Specficiations. Pi[n] contains the [primary 'view'] and is the starting point of the slider. max,min specify the maximum amount of return you can spec on an asset class. description=list_security[n]--> contains the name attached to the left of each slider.
        #display(temp_slider) # this command was required to forcefully display sliders when bqplot did not use to work. It is no longer required as Bqplot now works on the jupyter notebook.
        temp_slider.observe(run_viewmodel)
        list_slider.append(temp_slider)

        floattext_confidence = FloatSlider(
            description='Confidence of View',
            value=0.8,
            style={'description_width': '150PX'},
            readout_format='.2%',
            max=1,
            min=0,
            step=0.5 / 100)
        floattext_confidence.observe(run_viewmodel)
        confidence_list_slider.append(floattext_confidence)

        security_label = Label(list_security[n])
        security_label.observe(run_viewmodel)
        security_list.append(security_label)

    list_relative_controls = []
    sec_dropdown_options = OrderedDict(
        zip(['None'] + list(dict_settings['security'].keys()),
            range(len(dict_settings['security']) + 1)))

    for n in range(3):
        dropdown1 = Dropdown(options=sec_dropdown_options,
                             layout={'width': '100px'})
        dropdown2 = Dropdown(options=sec_dropdown_options,
                             layout={'width': '100px'})
        label = Label(value='over', layout={'width': '30px'})
        float_value = FloatSlider(description='by',
                                  value=0,
                                  readout_format='.2%',
                                  max=0.2,
                                  min=0,
                                  style={'description_width': 'initial'},
                                  step=0.1 / 100,
                                  layout={'width': '200px'})
        float_value.observe(run_viewmodel)
        relative_box = HBox([dropdown1, label, dropdown2, float_value])
        list_relative_controls.append(relative_box)

    header_abs_html = HTML(
        '<p style="color: white;">{}</p>'.format('Absolute Views'))
    header_rel_html = HTML(
        '<p style="color: white;">{}</p>'.format('Relative Views'),
        layout={'margin': '20px 0px 0px 0px'})
    UI_viewcontrol = [
        header_abs_html,
        VBox([
            HBox([
                VBox(security_list),
                VBox(list_slider),
                VBox(confidence_list_slider)
            ])
        ]), header_rel_html
    ]  #, VBox(list_relative_controls), VBox([floattext_confidence])]
示例#27
0
    def __init__(self, model, opt, maxiters, verbose=False, current_iteration=0, ipython_notebook=True, clear_after_finish=False):
        self.verbose = verbose
        if self.verbose:
            self.model = model
            self.iteration = current_iteration
            self.p_iter = self.iteration
            self.maxiters = maxiters
            self.len_maxiters = len(str(maxiters))
            self.opt_name = opt.opt_name
            self.model.add_observer(self, self.print_status)
            self.status = 'running'
            self.clear = clear_after_finish

            self.update()

            try:
                from IPython.display import display
                from ipywidgets import IntProgress, HTML, Box, VBox, HBox, FlexBox
                self.text = HTML(width='100%')
                self.progress = IntProgress(min=0, max=maxiters)
                #self.progresstext = Text(width='100%', disabled=True, value='0/{}'.format(maxiters))
                self.model_show = HTML()
                self.ipython_notebook = ipython_notebook
            except:
                # Not in Ipython notebook
                self.ipython_notebook = False

            if self.ipython_notebook:
                left_col = VBox(children=[self.progress, self.text], padding=2, width='40%')
                right_col = Box(children=[self.model_show], padding=2, width='60%')
                self.hor_align = FlexBox(children = [left_col, right_col], width='100%', orientation='horizontal')

                display(self.hor_align)

                try:
                    self.text.set_css('width', '100%')
                    left_col.set_css({
                             'padding': '2px',
                             'width': "100%",
                             })

                    right_col.set_css({
                             'padding': '2px',
                             })

                    self.hor_align.set_css({
                             'width': "100%",
                             })

                    self.hor_align.remove_class('vbox')
                    self.hor_align.add_class('hbox')

                    left_col.add_class("box-flex1")
                    right_col.add_class('box-flex0')

                except:
                    pass

                #self.text.add_class('box-flex2')
                #self.progress.add_class('box-flex1')
            else:
                self.exps = exponents(self.fnow, self.current_gradient)
                print('Running {} Code:'.format(self.opt_name))
                print('  {3:7s}   {0:{mi}s}   {1:11s}    {2:11s}'.format("i", "f", "|g|", "runtime", mi=self.len_maxiters))
示例#28
0
 def ext_box(self):
     "defines the interactive tools for 1D"
     wf = widgets.BoundedFloatText
     wi = widgets.BoundedIntText
     ref = self.data[0]
     style = {'description_width': 'initial'}
     lay = Layout(width='120px', height='30px')
     lay2 = Layout(width='50px', height='30px')
     self.z1 = wf( value=300.0, min=ref.axis1.lowmass, max=ref.highmass[0], description='F1', style=style, layout=lay)
     self.z2 = wf( value=300.0,  min=ref.axis2.lowmass, max=ref.highmass[1], description='F2', style=style, layout=lay)
     self.horiz = wi( value=1, min=1, max=20, style=style, layout=lay2)
     self.vert = wi( value=1, min=1, max=20, style=style, description="/", layout=lay2)
     def lrow(b, inc=0):
         rint = int(round(ref.axis1.mztoi(self.z1.value)))
         if inc !=0:
             rint += inc
         self.z1.value = ref.axis1.itomz(rint)
         if self.t1D == 'col':
             self.pltaxe1D.clear()
             self.r1D = None
         if self.b_accu.value == 'sum' and self.r1D is not None:
             self.r1D += ref.row(rint)
         else:
             self.r1D = ref.row(rint)
         self.t1D = 'row'
         self.i1D = rint
         self.display1D()
     def lrowp1(b):
         lrow(b,-1)
     def lrowm1(b):
         lrow(b,1)
     def lcol(b, inc=0):
         rint = int(round(ref.axis2.mztoi(self.z2.value)))
         if inc !=0:
             rint += inc
         self.z2.value = ref.axis2.itomz(rint)
         if self.t1D == 'row':
             self.pltaxe1D.clear()
             self.r1D = None
         if self.b_accu.value == 'sum' and self.r1D is not None:
             self.r1D += ref.col(rint)
         else:
             self.r1D = ref.col(rint)
         self.t1D = 'col'
         self.i1D = rint
         self.display1D()
     def lcolp1(b):
         lcol(b,-1)
     def lcolm1(b):
         lcol(b,1)
     self.bb('b_row', 'horiz', lrow, layout=Layout(width='60px'), tooltip='extract an horizontal row')
     self.bb('b_rowp1', '+1', lrowp1, layout=Layout(width='30px'), tooltip='next row up')
     self.bb('b_rowm1', '-1', lrowm1, layout=Layout(width='30px'), tooltip='next row down')
     self.bb('b_col', 'vert', lcol, layout=Layout(width='60px'), tooltip='extract a vertical col')
     self.bb('b_colp1', '+1', lcolp1, layout=Layout(width='30px'), tooltip='next col right')
     self.bb('b_colm1', '-1', lcolm1, layout=Layout(width='30px'), tooltip='next col left')
     self.b_accu = widgets.Dropdown(options=['off', 'graphic', 'sum'],
             value='off', description='Accumulate plots while scanning:', style=style)
     return VBox([ HTML('Extract 1D MS Spectrum passing by F1-F2 coordinates'),
                 HBox([HTML("<B>coord:</B>"),self.z1, self.z2,
                       self.b_row, self.b_rowp1, self.b_rowm1,HTML("&nbsp;/&nbsp;"),
                       self.b_col, self.b_colp1, self.b_colm1, self.b_accu])])
dd['Losses'] = {}
dd['Losses']['loss'] = widgets.Text(value='-Inf dB', disabled=False)
dd['Losses']['loss'].add_class("ui_power")
dd['Losses']['label_top'] = widgets.Label(value="Losses:")
dd['Losses']['label_top'].add_class("ui_label_losses")
dd['Losses']['label_bottom'] = widgets.Label(value="")
dd['Losses']['label_bottom'].add_class("ui_label_losses")

dd['running'] = widgets.Checkbox(value=True, description="Running")
dd['running'].add_class("ui_running")
ui = _dic2struct(dd)

IN = HBox([
    ui.IN.λ, ui.IN.fact,
    VBox([ui.IN.Det, ui.IN.Cnct]),
    VBox([ui.IN.P, ui.IN.Prgs])
])

OUT = HBox([
    ui.OUT.λ, ui.OUT.fact,
    VBox([ui.OUT.Det, ui.OUT.Cnct]),
    VBox([ui.OUT.P, ui.OUT.Prgs])
])
LOSS = VBox([ui.Losses.label_top, ui.Losses.loss, ui.Losses.label_bottom])

grid = VBox(
    [ui.running,
     HBox([VBox([ui.IN.label, IN, ui.OUT.label, OUT]), LOSS])])

stop_threads = False
示例#30
0
    def __init__(self):
        
        micron_units = Label('micron')   # use "option m" (Mac, for micro symbol)

        constWidth = '180px'
        tab_height = '500px'
        stepsize = 10

        #style = {'description_width': '250px'}
        style = {'description_width': '25%'}
        layout = {'width': '400px'}

        name_button_layout={'width':'25%'}
        widget_layout = {'width': '15%'}
        units_button_layout ={'width':'15%'}
        desc_button_layout={'width':'45%'}

        param_name1 = Button(description='cargo_signal_D', disabled=True, layout=name_button_layout)
        param_name1.style.button_color = 'lightgreen'

        self.cargo_signal_D = FloatText(
          value=1e3,
          step=100,
          style=style, layout=widget_layout)

        param_name2 = Button(description='cargo_signal_decay', disabled=True, layout=name_button_layout)
        param_name2.style.button_color = 'tan'

        self.cargo_signal_decay = FloatText(
          value=.4,
          step=0.1,
          style=style, layout=widget_layout)

        param_name3 = Button(description='director_signal_D', disabled=True, layout=name_button_layout)
        param_name3.style.button_color = 'lightgreen'

        self.director_signal_D = FloatText(
          value=1e3,
          step=100,
          style=style, layout=widget_layout)

        param_name4 = Button(description='director_signal_decay', disabled=True, layout=name_button_layout)
        param_name4.style.button_color = 'tan'

        self.director_signal_decay = FloatText(
          value=.1,
          step=0.01,
          style=style, layout=widget_layout)

        param_name5 = Button(description='elastic_coefficient', disabled=True, layout=name_button_layout)
        param_name5.style.button_color = 'lightgreen'

        self.elastic_coefficient = FloatText(
          value=0.05,
          step=0.01,
          style=style, layout=widget_layout)

        param_name6 = Button(description='worker_motility_persistence_time', disabled=True, layout=name_button_layout)
        param_name6.style.button_color = 'tan'

        self.worker_motility_persistence_time = FloatText(
          value=5.0,
          step=0.1,
          style=style, layout=widget_layout)

        param_name7 = Button(description='worker_migration_speed', disabled=True, layout=name_button_layout)
        param_name7.style.button_color = 'lightgreen'

        self.worker_migration_speed = FloatText(
          value=5.0,
          step=0.1,
          style=style, layout=widget_layout)

        param_name8 = Button(description='attached_worker_migration_bias', disabled=True, layout=name_button_layout)
        param_name8.style.button_color = 'tan'

        self.attached_worker_migration_bias = FloatText(
          value=1.0,
          step=0.1,
          style=style, layout=widget_layout)

        param_name9 = Button(description='unattached_worker_migration_bias', disabled=True, layout=name_button_layout)
        param_name9.style.button_color = 'lightgreen'

        self.unattached_worker_migration_bias = FloatText(
          value=0.5,
          step=0.1,
          style=style, layout=widget_layout)

        param_name10 = Button(description='number_of_directors', disabled=True, layout=name_button_layout)
        param_name10.style.button_color = 'tan'

        self.number_of_directors = IntText(
          value=15,
          step=1,
          style=style, layout=widget_layout)

        param_name11 = Button(description='number_of_cargo_clusters', disabled=True, layout=name_button_layout)
        param_name11.style.button_color = 'lightgreen'

        self.number_of_cargo_clusters = IntText(
          value=100,
          step=10,
          style=style, layout=widget_layout)

        param_name12 = Button(description='number_of_workers', disabled=True, layout=name_button_layout)
        param_name12.style.button_color = 'tan'

        self.number_of_workers = IntText(
          value=50,
          step=1,
          style=style, layout=widget_layout)

        param_name13 = Button(description='drop_threshold', disabled=True, layout=name_button_layout)
        param_name13.style.button_color = 'lightgreen'

        self.drop_threshold = FloatText(
          value=0.4,
          step=0.1,
          style=style, layout=widget_layout)

        param_name14 = Button(description='worker_color', disabled=True, layout=name_button_layout)
        param_name14.style.button_color = 'tan'

        self.worker_color = Text(
          value='red',
          style=style, layout=widget_layout)

        param_name15 = Button(description='cargo_color', disabled=True, layout=name_button_layout)
        param_name15.style.button_color = 'lightgreen'

        self.cargo_color = Text(
          value='blue',
          style=style, layout=widget_layout)

        param_name16 = Button(description='director_color', disabled=True, layout=name_button_layout)
        param_name16.style.button_color = 'tan'

        self.director_color = Text(
          value='limegreen',
          style=style, layout=widget_layout)

        units_button1 = Button(description='micron/min^2', disabled=True, layout=units_button_layout) 
        units_button1.style.button_color = 'lightgreen'
        units_button2 = Button(description='1/min', disabled=True, layout=units_button_layout) 
        units_button2.style.button_color = 'tan'
        units_button3 = Button(description='micron/min^2', disabled=True, layout=units_button_layout) 
        units_button3.style.button_color = 'lightgreen'
        units_button4 = Button(description='1/min', disabled=True, layout=units_button_layout) 
        units_button4.style.button_color = 'tan'
        units_button5 = Button(description='1/min', disabled=True, layout=units_button_layout) 
        units_button5.style.button_color = 'lightgreen'
        units_button6 = Button(description='min', disabled=True, layout=units_button_layout) 
        units_button6.style.button_color = 'tan'
        units_button7 = Button(description='micron/min', disabled=True, layout=units_button_layout) 
        units_button7.style.button_color = 'lightgreen'
        units_button8 = Button(description='', disabled=True, layout=units_button_layout) 
        units_button8.style.button_color = 'tan'
        units_button9 = Button(description='', disabled=True, layout=units_button_layout) 
        units_button9.style.button_color = 'lightgreen'
        units_button10 = Button(description='', disabled=True, layout=units_button_layout) 
        units_button10.style.button_color = 'tan'
        units_button11 = Button(description='', disabled=True, layout=units_button_layout) 
        units_button11.style.button_color = 'lightgreen'
        units_button12 = Button(description='', disabled=True, layout=units_button_layout) 
        units_button12.style.button_color = 'tan'
        units_button13 = Button(description='', disabled=True, layout=units_button_layout) 
        units_button13.style.button_color = 'lightgreen'
        units_button14 = Button(description='', disabled=True, layout=units_button_layout) 
        units_button14.style.button_color = 'tan'
        units_button15 = Button(description='', disabled=True, layout=units_button_layout) 
        units_button15.style.button_color = 'lightgreen'
        units_button16 = Button(description='', disabled=True, layout=units_button_layout) 
        units_button16.style.button_color = 'tan'

        desc_button1 = Button(description='cargo signal diffusion coefficient', disabled=True, layout=desc_button_layout) 
        desc_button1.style.button_color = 'lightgreen'
        desc_button2 = Button(description='cargo signal decay rate', disabled=True, layout=desc_button_layout) 
        desc_button2.style.button_color = 'tan'
        desc_button3 = Button(description='director signal diffusion coefficient', disabled=True, layout=desc_button_layout) 
        desc_button3.style.button_color = 'lightgreen'
        desc_button4 = Button(description='director signal decay rate', disabled=True, layout=desc_button_layout) 
        desc_button4.style.button_color = 'tan'
        desc_button5 = Button(description='elastic coefficient of cells', disabled=True, layout=desc_button_layout) 
        desc_button5.style.button_color = 'lightgreen'
        desc_button6 = Button(description='persistance time for worker motility', disabled=True, layout=desc_button_layout) 
        desc_button6.style.button_color = 'tan'
        desc_button7 = Button(description='speed of worker cells', disabled=True, layout=desc_button_layout) 
        desc_button7.style.button_color = 'lightgreen'
        desc_button8 = Button(description='migration bias of attached workers', disabled=True, layout=desc_button_layout) 
        desc_button8.style.button_color = 'tan'
        desc_button9 = Button(description='migration bias of unattached workers', disabled=True, layout=desc_button_layout) 
        desc_button9.style.button_color = 'lightgreen'
        desc_button10 = Button(description='# of director cells', disabled=True, layout=desc_button_layout) 
        desc_button10.style.button_color = 'tan'
        desc_button11 = Button(description='# of cargo clusters', disabled=True, layout=desc_button_layout) 
        desc_button11.style.button_color = 'lightgreen'
        desc_button12 = Button(description='# of worker cells', disabled=True, layout=desc_button_layout) 
        desc_button12.style.button_color = 'tan'
        desc_button13 = Button(description='threshold to drop cargo', disabled=True, layout=desc_button_layout) 
        desc_button13.style.button_color = 'lightgreen'
        desc_button14 = Button(description='color of worker cells', disabled=True, layout=desc_button_layout) 
        desc_button14.style.button_color = 'tan'
        desc_button15 = Button(description='color of cargo cells', disabled=True, layout=desc_button_layout) 
        desc_button15.style.button_color = 'lightgreen'
        desc_button16 = Button(description='color of director cells', disabled=True, layout=desc_button_layout) 
        desc_button16.style.button_color = 'tan'

        row1 = [param_name1, self.cargo_signal_D, units_button1, desc_button1] 
        row2 = [param_name2, self.cargo_signal_decay, units_button2, desc_button2] 
        row3 = [param_name3, self.director_signal_D, units_button3, desc_button3] 
        row4 = [param_name4, self.director_signal_decay, units_button4, desc_button4] 
        row5 = [param_name5, self.elastic_coefficient, units_button5, desc_button5] 
        row6 = [param_name6, self.worker_motility_persistence_time, units_button6, desc_button6] 
        row7 = [param_name7, self.worker_migration_speed, units_button7, desc_button7] 
        row8 = [param_name8, self.attached_worker_migration_bias, units_button8, desc_button8] 
        row9 = [param_name9, self.unattached_worker_migration_bias, units_button9, desc_button9] 
        row10 = [param_name10, self.number_of_directors, units_button10, desc_button10] 
        row11 = [param_name11, self.number_of_cargo_clusters, units_button11, desc_button11] 
        row12 = [param_name12, self.number_of_workers, units_button12, desc_button12] 
        row13 = [param_name13, self.drop_threshold, units_button13, desc_button13] 
        row14 = [param_name14, self.worker_color, units_button14, desc_button14] 
        row15 = [param_name15, self.cargo_color, units_button15, desc_button15] 
        row16 = [param_name16, self.director_color, units_button16, desc_button16] 

        box_layout = Layout(display='flex', flex_flow='row', align_items='stretch', width='100%')
        box1 = Box(children=row1, layout=box_layout)
        box2 = Box(children=row2, layout=box_layout)
        box3 = Box(children=row3, layout=box_layout)
        box4 = Box(children=row4, layout=box_layout)
        box5 = Box(children=row5, layout=box_layout)
        box6 = Box(children=row6, layout=box_layout)
        box7 = Box(children=row7, layout=box_layout)
        box8 = Box(children=row8, layout=box_layout)
        box9 = Box(children=row9, layout=box_layout)
        box10 = Box(children=row10, layout=box_layout)
        box11 = Box(children=row11, layout=box_layout)
        box12 = Box(children=row12, layout=box_layout)
        box13 = Box(children=row13, layout=box_layout)
        box14 = Box(children=row14, layout=box_layout)
        box15 = Box(children=row15, layout=box_layout)
        box16 = Box(children=row16, layout=box_layout)

        self.tab = VBox([
          box1,
          box2,
          box3,
          box4,
          box5,
          box6,
          box7,
          box8,
          box9,
          box10,
          box11,
          box12,
          box13,
          box14,
          box15,
          box16,
        ])
示例#31
0
    def __init__(self,
                 citation_var=None,
                 citation_file=None,
                 articles=None,
                 backward=True,
                 force_citation_file=True):
        reload()
        self.force_citation_file = force_citation_file
        self.citation_var = citation_var
        self.citation_file = citation_file or citation_var
        self.disable_show = False
        self.work = work_by_varname(citation_var) if citation_var else None
        self.backward = backward
        self.to_display = []
        self.custom_widgets = []

        self.next_article_widget = Button(description='Next Article',
                                          icon='fa-caret-right')
        self.previous_article_widget = Button(description='Previous Article',
                                              icon='fa-caret-left')
        self.selector_widget = IntSlider(value=0, min=0, max=20, step=1)
        self.reload_article_widget = Button(description='Reload Article',
                                            icon='fa-refresh')

        self.file_field_widget = ToggleButton(value=False, description="File")
        self.due_widget = Text(value="", description="Due")
        self.place_widget = Text(value="", description="Place")
        self.year_widget = Text(value="", description="Year")
        self.prefix_widget = Text(value="", description="Prefix Var")
        self.pdfpage_widget = Text(value="", description="PDFPage")

        self.work_type_widget = Dropdown(
            options=[tup[0] for tup in config.CLASSES],
            value=config.DEFAULT_CLASS,
            description="Type")
        self.article_number_widget = Label(value="")
        self.output_widget = Output()

        self.next_article_widget.on_click(self.next_article)
        self.previous_article_widget.on_click(self.previous_article)
        self.selector_widget.observe(self.show)
        self.reload_article_widget.on_click(self.show)

        self.due_widget.observe(self.write_due)
        self.place_widget.observe(self.write_place)

        widgets = [
            self.work_type_widget,
            self.file_field_widget,
            self.due_widget,
            self.place_widget,
            self.year_widget,
            self.prefix_widget,
            self.pdfpage_widget,
        ]

        hboxes = [
            HBox([
                self.previous_article_widget, self.reload_article_widget,
                self.next_article_widget
            ]),
        ]

        for row in config.FORM_BUTTONS:
            hboxes.append(HBox([self.create_custom_button(tup)
                                for tup in row]))

        for tup in config.FORM_TEXT_FIELDS:
            self.create_custom_text(tup)

        widgets += self.custom_widgets

        iterable = iter(widgets)
        for w1, w2 in zip_longest(iterable, iterable):
            hboxes.append(HBox([w1] + ([w2] if w2 else [])))

        hboxes.append(
            HBox([
                self.reload_article_widget, self.selector_widget,
                self.article_number_widget
            ]))

        hboxes.append(self.output_widget)

        self.view = VBox(hboxes)

        self.set_articles(articles)
        self.erase_article_form()
示例#32
0
    def _widget(self):
        """ Create IPython widget for display within a notebook """
        try:
            return self._cached_widget
        except AttributeError:
            pass

        from ipywidgets import Layout, VBox, HBox, IntText, Button, HTML, Accordion

        layout = Layout(width='150px')

        if 'bokeh' in self.scheduler.services:
            template = config.get('diagnostics-link', 'http://{host}:{port}/status')

            host = self.scheduler.address.split('://')[1].split(':')[0]
            port = self.scheduler.services['bokeh'].port
            link = template.format(host=host, port=port, **os.environ)
            link = '<p><b>Dashboard: </b><a href="%s" target="_blank">%s</a></p>\n' % (link, link)
        else:
            link = ''

        title = '<h2>%s</h2>' % type(self).__name__
        title = HTML(title)
        dashboard = HTML(link)

        status = HTML(self._widget_status(), layout=Layout(min_width='150px'))

        request = IntText(0, description='Workers', layout=layout)
        scale = Button(description='Scale', layout=layout)

        minimum = IntText(0, description='Minimum', layout=layout)
        maximum = IntText(0, description='Maximum', layout=layout)
        adapt = Button(description='Adapt', layout=layout)

        accordion = Accordion([HBox([request, scale]),
                               HBox([minimum, maximum, adapt])],
                               layout=Layout(min_width='500px'))
        accordion.selected_index = None
        accordion.set_title(0, 'Manual Scaling')
        accordion.set_title(1, 'Adaptive Scaling')

        box = VBox([title,
                    HBox([status,
                          accordion]),
                    dashboard])

        self._cached_widget = box

        def adapt_cb(b):
            self.adapt(minimum=minimum.value, maximum=maximum.value)

        adapt.on_click(adapt_cb)

        def scale_cb(b):
            print('Hello!')
            with log_errors():
                n = request.value
                with ignoring(AttributeError):
                    self._adaptive.stop()
                self.scale(n)

        scale.on_click(scale_cb)

        scheduler_ref = ref(self.scheduler)

        def update():
            status.value = self._widget_status()

        pc = PeriodicCallback(update, 500, io_loop=self.scheduler.loop)
        self.scheduler.periodic_callbacks['cluster-repr'] = pc
        pc.start()

        return box
    def buildOutputWidgets(self):

        if  self.showDebug:
            return VBox([self.debug, self.debugText, self.stdout, self.stderr, self.argsOutput])
        else:
            return VBox([self.debug, self.stdout, self.stderr, self.argsOutput])
示例#34
0
文件: gui.py 项目: getmolmap/ipynb
    def settings_panel(self):
        # getMolMap calulation settings.  NOTE: should only be called once.
        margin = 2

        num_angles_slider_text = "Number of Inverse Cone Angles to calculate:"
        num_angles_slider_widget = IntSlider(value=1, min=1, max=5)
        num_angles_slider = VBox(
            children=[HTML(value=num_angles_slider_text), num_angles_slider_widget], margin=margin, width="100%"
        )
        link((self.model, "num_angles"), (num_angles_slider_widget, "value"))
        sub_slider_text = "Subdivision value of the icosphere for numerical calculation:"
        sub_slider_widget = IntSlider(value=5, min=1, max=9)
        link((self.model, "sub"), (sub_slider_widget, "value"))
        sub_slider = VBox(children=[HTML(value=sub_slider_text), sub_slider_widget], margin=margin, width="100%")
        #        link((sub_slider, 'value'), (i, 'value'))
        #        print(self.width)
        #        sub_slider.align = 'center'
        #        sub_slider.width = '100%'
        #        sub_slider.border_color = 'black'
        #        sub_slider.border_width = 2

        radius_slider_text = "Cut radius measured from the central atom:"
        radius_slider_widget = FloatSlider(value=0, min=0, max=10)
        link((self.model, "radius"), (radius_slider_widget, "value"))
        radius_slider = VBox(children=[HTML(value=radius_slider_text), radius_slider_widget], margin=margin)

        atomradscale_slider_text = "Atomic radius scaling factor:"
        atomradscale_slider_widget = FloatSlider(value=1, min=0, max=4)
        link((self.model, "rad_scale"), (atomradscale_slider_widget, "value"))
        atomradscale_slider = VBox(
            children=[HTML(value=atomradscale_slider_text), atomradscale_slider_widget], margin=margin
        )

        excludeH_button = Checkbox(description="Exclude H from every geometry:")
        link((self.model, "excludeH"), (excludeH_button, "value"))
        excludeH_button.on_trait_change(self.excludeH_changed, "value")

        dont = "Don't exclude any elements"
        self.dont = dont
        # TODO: Syncronize exclude_list_widget with excludeH button and define an event on the
        # model to filter out the `dont` text.
        # Alternatevily, separate this option into a checkbox and hide the exclude options
        # while the button is selected.
        exclude_list_text = "Exclude elements from every geometry:"
        exclude_list_widget = SelectMultiple(
            options=[dont] + [e.symbol for e in ELEMENTS],
            selected_labels=[dont],
            color="Black",
            font_size=14,
            height=120,
        )
        link((exclude_list_widget, "value"), (self.model, "excludes"))
        # The dirty old SelectMultiple widget does not have an .on_trait_change method.
        # So we create a new traitlet (excludes_notifier), which has an .on_trait_change method
        # because it inherits HasTraits. We link the 'value' trait to excludes_notifier.excludes;
        # and we bind the event handler to excludes_notifier.on_trait_change
        self.excludes_notifier = ExcludesNotifier()
        link((exclude_list_widget, "value"), (self.excludes_notifier, "excludes"))
        self.excludes_notifier.on_trait_change(self.excludes_changed)

        exclude_list = VBox(children=[HTML(value=exclude_list_text), exclude_list_widget], margin=margin)

        atomrad_button = ToggleButtons(
            description="Atomic radius type:",
            options=["vdwrad", "covrad", "atmrad"],
            background_color="AliceBlue",
            margin=margin,
        )
        link((self.model, "rad_type"), (atomrad_button, "value"))
        runbutton = Button(
            description="Run calculation!",
            tooltip="Click here to calculate Buried Volumes and Inverse Cone Angles!",
            margin=margin * 3,
            border_color="#9acfea",
            # border_radius=5,
            border_width=3,
            font_size=20,
        )
        runbutton.on_click(self.run_button_clicked)

        basic_tab = VBox(children=[atomrad_button, excludeH_button])
        sliders = VBox(children=[num_angles_slider, atomradscale_slider, radius_slider, sub_slider])
        sliders.width = "100%"
        sliders.pack = "center"

        advanced_tab = VBox(children=[atomrad_button, sliders, exclude_list])
        main_window = Tab(children=[basic_tab, advanced_tab])
        main_window.set_title(0, "Basic")
        main_window.set_title(1, "Advanced")

        return ControlPanel(
            title="getMolMap Settings:",
            children=[main_window, runbutton],
            border_width=2,
            border_radius=4,
            margin=10,
            padding=0,
        )
示例#35
0
    def __init__(self):

        #        micron_units = HTMLMath(value=r"$\mu M$")
        micron_units = Label(
            'micron')  # use "option m" (Mac, for micro symbol)
        #        micron_units = Label('microns')   # use "option m" (Mac, for micro symbol)

        constWidth = '180px'
        # tab_height = '400px'
        tab_height = '500px'
        #        tab_layout = Layout(width='900px',   # border='2px solid black',
        #        tab_layout = Layout(width='850px',   # border='2px solid black',
        #                            height=tab_height, overflow_y='scroll',)
        #        np_tab_layout = Layout(width='800px',  # border='2px solid black',
        #                               height='350px', overflow_y='scroll',)

        # my_domain = [0,0,-10, 2000,2000,10, 20,20,20]  # [x,y,zmin,  x,y,zmax, x,y,zdelta]
        #        label_domain = Label('Domain ($\mu M$):')
        label_domain = Label('Domain (micron):')
        stepsize = 10
        disable_domain = False
        self.xmin = FloatText(
            step=stepsize,
            # description='$X_{min}$',
            description='Xmin',
            disabled=disable_domain,
            layout=Layout(width=constWidth),
        )
        self.ymin = FloatText(
            step=stepsize,
            description='Ymin',
            disabled=disable_domain,
            layout=Layout(width=constWidth),
        )
        self.zmin = FloatText(
            step=stepsize,
            description='Zmin',
            disabled=disable_domain,
            layout=Layout(width=constWidth),
        )
        self.xmax = FloatText(
            step=stepsize,
            description='Xmax',
            disabled=disable_domain,
            layout=Layout(width=constWidth),
        )
        self.ymax = FloatText(
            step=stepsize,
            description='Ymax',
            disabled=disable_domain,
            layout=Layout(width=constWidth),
        )
        self.zmax = FloatText(
            step=stepsize,
            description='Zmax',
            disabled=disable_domain,
            layout=Layout(width=constWidth),
        )
        #            description='$Time_{max}$',
        self.tmax = BoundedFloatText(
            min=0.,
            max=100000000,
            step=stepsize,
            description='Max Time',
            layout=Layout(width=constWidth),
        )
        self.xdelta = BoundedFloatText(
            min=1.,
            description='dx',  # 'dx',  # Mac: opt-j for delta
            disabled=disable_domain,
            layout=Layout(width=constWidth),
        )

        self.ydelta = BoundedFloatText(
            min=1.,
            description='dy',
            disabled=True,
            layout=Layout(width=constWidth),
        )
        self.zdelta = BoundedFloatText(
            min=1.,
            description='dz',
            disabled=disable_domain,
            layout=Layout(width=constWidth),
        )

        def xdelta_cb(b):
            self.ydelta.value = self.xdelta.value
            self.zdelta.value = 0.5 * (self.xdelta.value + self.ydelta.value)
            self.zmin.value = -0.5 * self.zdelta.value
            self.zmax.value = 0.5 * self.zdelta.value

        self.xdelta.observe(xdelta_cb)
        """
        self.tdelta = BoundedFloatText(
            min=0.01,
            description='$Time_{delta}$',
            layout=Layout(width=constWidth),
        )
        """
        """
        self.toggle2D = Checkbox(
            description='2-D',
            layout=Layout(width=constWidth),
        )
        def toggle2D_cb(b):
            if (self.toggle2D.value):
                #zmin.disabled = zmax.disabled = zdelta.disabled = True
                zmin.disabled = True
                zmax.disabled = True
                zdelta.disabled = True
            else:
                zmin.disabled = False
                zmax.disabled = False
                zdelta.disabled = False
            
        self.toggle2D.observe(toggle2D_cb)
        """

        x_row = HBox([self.xmin, self.xmax, self.xdelta])
        y_row = HBox([self.ymin, self.ymax, self.ydelta])
        z_row = HBox([self.zmin, self.zmax, self.zdelta])

        self.omp_threads = BoundedIntText(
            min=1,
            max=4,
            description='# threads',
            layout=Layout(width=constWidth),
        )

        # self.toggle_prng = Checkbox(
        #     description='Seed PRNG', style={'description_width': 'initial'},  # e.g. 'initial'  '120px'
        #     layout=Layout(width=constWidth),
        # )
        # self.prng_seed = BoundedIntText(
        #     min = 1,
        #     description='Seed',
        #     disabled=True,
        #     layout=Layout(width=constWidth),
        # )
        # def toggle_prng_cb(b):
        #     if (toggle_prng.value):
        #         self.prng_seed.disabled = False
        #     else:
        #         self.prng_seed.disabled = True

        # self.toggle_prng.observe(toggle_prng_cb)
        #prng_row = HBox([toggle_prng, prng_seed])

        self.toggle_svg = Checkbox(
            description='Cells',  # SVG
            layout=Layout(width='150px'))  # constWidth = '180px'
        # self.svg_t0 = BoundedFloatText (
        #     min=0,
        #     description='$T_0$',
        #     layout=Layout(width=constWidth),
        # )
        self.svg_interval = BoundedIntText(
            min=1,
            max=
            99999999,  # TODO: set max on all Bounded to avoid unwanted default
            description='every',
            layout=Layout(width='160px'),
        )
        self.mcds_interval = BoundedIntText(
            min=1,
            max=99999999,
            description='every',
            #            disabled=True,
            layout=Layout(width='160px'),
        )

        # don't let this be > mcds interval
        def svg_interval_cb(b):
            if (self.svg_interval.value > self.mcds_interval.value):
                self.svg_interval.value = self.mcds_interval.value

        self.svg_interval.observe(
            svg_interval_cb)  # BEWARE: when fill_gui, this sets value = 1 !

        # don't let this be < svg interval
        def mcds_interval_cb(b):
            if (self.mcds_interval.value < self.svg_interval.value):
                self.mcds_interval.value = self.svg_interval.value

        self.mcds_interval.observe(
            mcds_interval_cb)  # BEWARE: see warning above

        def toggle_svg_cb(b):
            if (self.toggle_svg.value):
                # self.svg_t0.disabled = False
                self.svg_interval.disabled = False
            else:
                # self.svg_t0.disabled = True
                self.svg_interval.disabled = True

        self.toggle_svg.observe(toggle_svg_cb)

        self.toggle_mcds = Checkbox(
            #     value=False,
            description='Subtrates',  # Full
            layout=Layout(width='180px'),
        )

        # self.mcds_t0 = FloatText(
        #     description='$T_0$',
        #     disabled=True,
        #     layout=Layout(width=constWidth),
        # )
        def toggle_mcds_cb(b):
            if (self.toggle_mcds.value):
                # self.mcds_t0.disabled = False #False
                self.mcds_interval.disabled = False
            else:
                # self.mcds_t0.disabled = True
                self.mcds_interval.disabled = True

        self.toggle_mcds.observe(toggle_mcds_cb)

        svg_mat_output_row = HBox([
            Label('Plots:'), self.toggle_svg,
            HBox([self.svg_interval, Label('min')]), self.toggle_mcds,
            HBox([self.mcds_interval, Label('min')])
        ])

        # to sync, do this
        # svg_mat_output_row = HBox( [Label('Plots:'), self.svg_interval, Label('min')])

        #write_config_row = HBox([write_config_button, write_config_file])
        #run_sim_row = HBox([run_button, run_command_str, kill_button])
        # run_sim_row = HBox([run_button, run_command_str])
        # run_sim_row = HBox([run_button.w])  # need ".w" for the custom RunCommand widget

        label_blankline = Label('')
        # toggle_2D_seed_row = HBox([toggle_prng, prng_seed])  # toggle2D

        box_layout = Layout(border='1px solid')
        #        domain_box = VBox([label_domain,x_row,y_row,z_row], layout=box_layout)
        domain_box = VBox([label_domain, x_row, y_row], layout=box_layout)
        self.tab = VBox([
            domain_box,
            #                         label_blankline,
            HBox([self.tmax, Label('min')]),
            self.omp_threads,
            svg_mat_output_row,
            #                         HBox([self.substrate[3], self.diffusion_coef[3], self.decay_rate[3] ]),
        ])  # output_dir, toggle_2D_seed_
示例#36
0
                            max=1.0,
                            step=.005,
                            value=0,
                            style=style,
                            description='mu: Natural death rate'),
        widgets.FloatSlider(min=0,
                            max=1.0,
                            step=.005,
                            value=0.005,
                            style=style,
                            description='delta: re-incorporation rate')
    ]

    # Button widget
    CD_button1 = widgets.Button(button_style='success',
                                description="Run Simulations",
                                layout=Layout(width='15%', height='30px'),
                                style=style)

    # Connect widget to function - run subsequent cells
    CD_button1.on_click(plot_model_and_data)

    # user menu using categories found above
    tab4 = VBox(children=[
        HBox(children=all_the_widgets1[0:3]),
        HBox(children=all_the_widgets1[3:6]),
        HBox(children=all_the_widgets1[6:]), CD_button1
    ])
    tab1 = widgets.Tab(children=[tab4])
    tab1.set_title(0, 'Choose Parameters')
    def __init__(self):
        
        self.output_dir = '.'
        # self.output_dir = 'tmpdir'

        self.figsize_width_substrate = 15.0  # allow extra for colormap
        self.figsize_height_substrate = 12.5
        self.figsize_width_svg = 12.0
        self.figsize_height_svg = 12.0

        # self.fig = plt.figure(figsize=(7.2,6))  # this strange figsize results in a ~square contour plot

        self.first_time = True
        self.modulo = 1

        self.use_defaults = True

        self.svg_delta_t = 1
        self.substrate_delta_t = 1
        self.svg_frame = 1
        self.substrate_frame = 1

        self.customized_output_freq = False
        self.therapy_activation_time = 1000000
        self.max_svg_frame_pre_therapy = 1000000
        self.max_substrate_frame_pre_therapy = 1000000

        self.svg_xmin = 0

        # Probably don't want to hardwire these if we allow changing the domain size
        # self.svg_xrange = 2000
        # self.xmin = -1000.
        # self.xmax = 1000.
        # self.ymin = -1000.
        # self.ymax = 1000.
        # self.x_range = 2000.
        # self.y_range = 2000.

        self.cells_alpha = 0.7  
        self.show_nucleus = False
        self.show_edge = True
        self.show_vectors = True

        # initial value
        self.field_index = 4
        # self.field_index = self.mcds_field.value + 4

        # define dummy size of mesh (set in the tool's primary module)
        self.numx = 0
        self.numy = 0

        self.title_str = ''

        tab_height = '600px'
        tab_height = '500px'
        constWidth = '180px'
        constWidth2 = '150px'
        tab_layout = Layout(width='900px',   # border='2px solid black',
                            height=tab_height, ) #overflow_y='scroll')

        max_frames = 1   
        # self.mcds_plot = interactive(self.plot_substrate, frame=(0, max_frames), continuous_update=False)  
        # self.i_plot = interactive(self.plot_plots, frame=(0, max_frames), continuous_update=False)  
        self.i_plot = interactive(self.plot_substrate, frame=(0, max_frames), continuous_update=False)  

        # "plot_size" controls the size of the tab height, not the plot (rf. figsize for that)
        # NOTE: the Substrates Plot tab has an extra row of widgets at the top of it (cf. Cell Plots tab)
        svg_plot_size = '700px'
        svg_plot_size = '600px'
        svg_plot_size = '700px'
        svg_plot_size = '900px'
        self.i_plot.layout.width = svg_plot_size
        self.i_plot.layout.height = svg_plot_size

        self.fontsize = 20

            # description='# cell frames',
        self.max_frames = BoundedIntText(
            min=0, max=99999, value=max_frames,
            description='# frames',
           layout=Layout(width='160px'),
        )
        self.max_frames.observe(self.update_max_frames)

        # self.field_min_max = {'dummy': [0., 1.]}
        # NOTE: manually setting these for now (vs. parsing them out of data/initial.xml)
        self.field_min_max = {'director signal':[0.,1.], 'cargo signal':[0.,1.] }
        # hacky I know, but make a dict that's got (key,value) reversed from the dict in the Dropdown below
        # self.field_dict = {0:'dummy'}
        self.field_dict = {0:'director signal', 1:'cargo signal'}

        self.mcds_field = Dropdown(
            options={'director signal': 0, 'cargo signal':1},
            value=0,
            #     description='Field',
           layout=Layout(width=constWidth)
        )
        # print("substrate __init__: self.mcds_field.value=",self.mcds_field.value)
#        self.mcds_field.observe(self.mcds_field_cb)
        self.mcds_field.observe(self.mcds_field_changed_cb)

        # self.field_cmap = Text(
        #     value='viridis',
        #     description='Colormap',
        #     disabled=True,
        #     layout=Layout(width=constWidth),
        # )
        self.field_cmap = Dropdown(
            options=['viridis', 'jet', 'YlOrRd'],
            value='YlOrRd',
            #     description='Field',
           layout=Layout(width=constWidth)
        )
#        self.field_cmap.observe(self.plot_substrate)
        self.field_cmap.observe(self.mcds_field_cb)

        self.cmap_fixed = Checkbox(
            description='Fix',
            disabled=False,
#           layout=Layout(width=constWidth2),
        )

        self.save_min_max= Button(
            description='Save', #style={'description_width': 'initial'},
            button_style='success',  # 'success', 'info', 'warning', 'danger' or ''
            tooltip='Save min/max for this substrate',
            disabled=True,
           layout=Layout(width='90px')
        )

        def save_min_max_cb(b):
#            field_name = self.mcds_field.options[]
#            field_name = next(key for key, value in self.mcds_field.options.items() if value == self.mcds_field.value)
            field_name = self.field_dict[self.mcds_field.value]
#            print(field_name)
#            self.field_min_max = {'oxygen': [0., 30.], 'glucose': [0., 1.], 'H+ ions': [0., 1.], 'ECM': [0., 1.], 'NP1': [0., 1.], 'NP2': [0., 1.]}
            self.field_min_max[field_name][0] = self.cmap_min.value
            self.field_min_max[field_name][1] = self.cmap_max.value
#            print(self.field_min_max)

        self.save_min_max.on_click(save_min_max_cb)

        self.cmap_min = FloatText(
            description='Min',
            value=0,
            step = 0.1,
            disabled=True,
            layout=Layout(width=constWidth2),
        )
        self.cmap_min.observe(self.mcds_field_cb)

        self.cmap_max = FloatText(
            description='Max',
            value=38,
            step = 0.1,
            disabled=True,
            layout=Layout(width=constWidth2),
        )
        self.cmap_max.observe(self.mcds_field_cb)

        def cmap_fixed_cb(b):
            if (self.cmap_fixed.value):
                self.cmap_min.disabled = False
                self.cmap_max.disabled = False
                self.save_min_max.disabled = False
            else:
                self.cmap_min.disabled = True
                self.cmap_max.disabled = True
                self.save_min_max.disabled = True
#            self.mcds_field_cb()

        self.cmap_fixed.observe(cmap_fixed_cb)

        field_cmap_row2 = HBox([self.field_cmap, self.cmap_fixed])

#        field_cmap_row3 = HBox([self.save_min_max, self.cmap_min, self.cmap_max])
        items_auto = [
            self.save_min_max, #layout=Layout(flex='3 1 auto', width='auto'),
            self.cmap_min, 
            self.cmap_max,  
         ]
        box_layout = Layout(display='flex',
                    flex_flow='row',
                    align_items='stretch',
                    width='80%')
        field_cmap_row3 = Box(children=items_auto, layout=box_layout)

        #---------------------
        self.cell_nucleus_toggle = Checkbox(
            description='nuclei',
            disabled=False,
            value = self.show_nucleus,
#           layout=Layout(width=constWidth2),
        )
        def cell_nucleus_toggle_cb(b):
            # self.update()
            if (self.cell_nucleus_toggle.value):  
                self.show_nucleus = True
            else:
                self.show_nucleus = False
            self.i_plot.update()

        self.cell_nucleus_toggle.observe(cell_nucleus_toggle_cb)

        #----
        self.cell_edges_toggle = Checkbox(
            description='edges',
            disabled=False,
            value=self.show_edge,
#           layout=Layout(width=constWidth2),
        )
        def cell_edges_toggle_cb(b):
            # self.update()
            if (self.cell_edges_toggle.value):  
                self.show_edge = True
            else:
                self.show_edge = False
            self.i_plot.update()

        self.cell_edges_toggle.observe(cell_edges_toggle_cb)

        self.cells_toggle = Checkbox(
            description='Cells',
            disabled=False,
            value=True,
#           layout=Layout(width=constWidth2),
        )
        def cells_toggle_cb(b):
            # self.update()
            self.i_plot.update()
            if (self.cells_toggle.value):
                self.cell_edges_toggle.disabled = False
                self.cell_nucleus_toggle.disabled = False
            else:
                self.cell_edges_toggle.disabled = True
                self.cell_nucleus_toggle.disabled = True

        self.cells_toggle.observe(cells_toggle_cb)

        #---------------------
        self.substrates_toggle = Checkbox(
            description='Substrates',
            disabled=False,
            value=True,
#           layout=Layout(width=constWidth2),
        )
        def substrates_toggle_cb(b):
            if (self.substrates_toggle.value):  # seems bass-ackwards
                self.cmap_fixed.disabled = False
                self.cmap_min.disabled = False
                self.cmap_max.disabled = False
                self.mcds_field.disabled = False
                self.field_cmap.disabled = False
            else:
                self.cmap_fixed.disabled = True
                self.cmap_min.disabled = True
                self.cmap_max.disabled = True
                self.mcds_field.disabled = True
                self.field_cmap.disabled = True

        self.substrates_toggle.observe(substrates_toggle_cb)

        #------
        self.vectors_toggle = Checkbox(
            description='Vectors',
            disabled=False,
            value=True,
#           layout=Layout(width=constWidth2),
        )
        def vectors_toggle_cb(b):
            # self.update()
            self.i_plot.update()
            self.show_vectors = self.vectors_toggle.value
            # if (self.vectors_toggle.value):
            #     self.show_vectors = False
            # else:
            #     self.show_vectors = True

        self.vectors_toggle.observe(vectors_toggle_cb)

        #--------------
        self.grid_toggle = Checkbox(
            description='grid',
            disabled=False,
            value=True,
#           layout=Layout(width=constWidth2),
        )
        def grid_toggle_cb(b):
            # self.update()
            self.i_plot.update()

        self.grid_toggle.observe(grid_toggle_cb)

#        field_cmap_row3 = Box([self.save_min_max, self.cmap_min, self.cmap_max])

        # mcds_tab = widgets.VBox([mcds_dir, mcds_plot, mcds_play], layout=tab_layout)
        # mcds_params = VBox([self.mcds_field, field_cmap_row2, field_cmap_row3, self.max_frames])  # mcds_dir
#        mcds_params = VBox([self.mcds_field, field_cmap_row2, field_cmap_row3,])  # mcds_dir

#        self.tab = HBox([mcds_params, self.mcds_plot], layout=tab_layout)

        help_label = Label('select slider: drag or left/right arrows')
        # row1 = Box([help_label, Box( [self.max_frames, self.mcds_field, self.field_cmap], layout=Layout(border='0px solid black',
        row1a = Box( [self.max_frames, self.mcds_field, self.field_cmap], layout=Layout(border='1px solid black',
                            width='50%',
                            height='',
                            align_items='stretch',
                            flex_direction='row',
                            display='flex')) 
        row1b = Box( [self.cells_toggle, self.cell_nucleus_toggle, self.cell_edges_toggle], layout=Layout(border='1px solid black',
                            width='50%',
                            height='',
                            align_items='stretch',
                            flex_direction='row',
                            display='flex')) 
        row1 = HBox( [row1a, Label('.....'), row1b])

        row2a = Box([self.cmap_fixed, self.cmap_min, self.cmap_max], layout=Layout(border='1px solid black',
                            width='50%',
                            height='',
                            align_items='stretch',
                            flex_direction='row',
                            display='flex'))
        # row2b = Box( [self.substrates_toggle, self.grid_toggle], layout=Layout(border='1px solid black',
        # row2b = Box( [self.substrates_toggle, ], layout=Layout(border='1px solid black',
        row2b = Box( [self.substrates_toggle, self.vectors_toggle], layout=Layout(border='1px solid black',
                            width='50%',
                            height='',
                            align_items='stretch',
                            flex_direction='row',
                            display='flex')) 
        # row2 = HBox( [row2a, self.substrates_toggle, self.grid_toggle])
        row2 = HBox( [row2a, Label('.....'), row2b])

        if (hublib_flag):
            self.download_button = Download('mcds.zip', style='warning', icon='cloud-download', 
                                                tooltip='Download data', cb=self.download_cb)

            self.download_svg_button = Download('svg.zip', style='warning', icon='cloud-download', 
                                            tooltip='You need to allow pop-ups in your browser', cb=self.download_svg_cb)
            download_row = HBox([self.download_button.w, self.download_svg_button.w, Label("Download all cell plots (browser must allow pop-ups).")])

            # box_layout = Layout(border='0px solid')
            controls_box = VBox([row1, row2])  # ,width='50%', layout=box_layout)
            self.tab = VBox([controls_box, self.i_plot, download_row])
        else:
            # self.tab = VBox([row1, row2])
            self.tab = VBox([row1, row2, self.i_plot])
示例#38
0
 def __init__(self, keys, scheduler=None, minimum=0, interval=0.1, func=key_split,
              complete=False):
     super(MultiProgressWidget, self).__init__(keys, scheduler, func, interval, complete)
     from ipywidgets import VBox
     self.widget = VBox([])
    def __init__(self):
        self.out = Output(layout={'width': '2000px', 'height': '450px'})
        self.axs = []
        #I change this because it is going to be the discrete zero pole plot demo
        self.discrete_mode = True  #not continuous
        self.show_phase = True  #not self.discrete_mode if show_phase is None else show_phase
        self.actual_change = True
        self.real_filter = False
        self.show_dB = False
        # Initialize zeros and poles
        z_x = [1 / 3]
        z_y = [-1 / 3]
        p_x = [4, 0]
        p_y = [0, 4 / 5]

        self.collapsed_points = []

        # Initialize the figure with the initial number of zeros and poles
        self.init_figure(z_x, z_y, p_x, p_y)
        # Call the super class with the zero pole axis to enable the draggable markers
        super().__init__(ax=self.axs[0],
                         lines=self.axs[0].lines[1:],
                         update_func=self.change_freq_res)

        # Non causal text field
        self.tx_deb = self.axs[0].text(-4.75,
                                       4.2,
                                       '',
                                       fontdict={
                                           'color': 'red',
                                           'size': 12
                                       })

        # Debug text field
        self.tx_debug = self.axs[0].text(-1.75,
                                         1,
                                         '',
                                         fontdict={
                                             'color': 'red',
                                             'size': 15,
                                             'font': 'Arial'
                                         })

        # 'Calculation not possible' text fields
        self.cnp_gain = None
        self.cnp_ph = None

        # Text field numbers
        self.lastzeroRe = 0
        self.lastzeroIm = 0

        # Init frequency response plot
        self.change_freq_res(init=True)

        # Widgets
        # Zeros
        self.zero_range = widgets.IntSlider(value=1,
                                            min=1,
                                            max=2,
                                            step=1,
                                            description='Zeros:')

        self.zero_range.observe(self.on_zero_change, names='value')
        # Poles
        self.pole_range = widgets.IntSlider(value=2,
                                            min=2,
                                            max=4,
                                            step=1,
                                            description='Poles:')

        self.pole_range.observe(self.on_pole_change, names='value')

        # Check box to show phase plot
        self.phase_check = widgets.Checkbox(value=self.show_phase,
                                            description='Show phase')
        self.phase_check.observe(self.show_phase_callback, names='value')

        # Float text widgets
        self.input_Zero_RE = widgets.FloatText(value=self.lastzeroRe,
                                               description='Re:')
        self.input_Zero_RE.observe(self.Zero_RE_Caller, names='value')

        self.input_Zero_IM = widgets.FloatText(value=self.lastzeroIm,
                                               description='Im:')
        self.input_Zero_IM.observe(self.Zero_IM_Caller, names='value')

        self.collapsing = False

        # Display widgets and plot
        display(
            VBox([
                self.out,
                HBox([self.zero_range, self.pole_range, self.phase_check]),
                HBox([self.input_Zero_RE, self.input_Zero_IM])
            ]))
        plt.tight_layout(pad=0.4, w_pad=1.5, h_pad=1.0)