Beispiel #1
0
    def slider(self, value, min, max, step, description):
        label = Label(description)
        self.labels.append(label)
        ind = len(self.normals)
        button = ImageButton(width=36,
                             height=28,
                             image_path="%s/plane.png" % (self.image_path),
                             tooltip="Set clipping plane",
                             type=str(ind),
                             layout=Layout(margin="0px 10px 0px 0px"))
        button.on_click(self.handler)
        button.add_class("view_button")

        slider = FloatSlider(value=value,
                             min=min,
                             max=max,
                             step=step,
                             description="",
                             disabled=False,
                             continuous_update=False,
                             orientation='horizontal',
                             readout=True,
                             readout_format='.2f',
                             layout=Layout(width="%dpx" % (self.width - 20)))

        slider.observe(self.cq_view.clip(ind), "value")
        return [HBox([button, label]), slider]
Beispiel #2
0
    def _fill_folder(self):
        atoms = Button(description=' Fill', icon='adjust', layout=_wlo)
        opt = ['Ball and Stick', 'Van Der Waals Spheres', 'Covalent Spheres']
        #'High Performance']#,'Stick']
        fill = Select(options=opt, value=opt[0], layout=_wlo)
        bond_r = FloatSlider(max=1.0, description='Bond Radius')

        def _atoms(c):
            for scn in self.active():
                scn.atom_3d = not scn.atom_3d

        def _fill(c):
            for scn in self.active():
                scn.fill_idx = c.new
            bond_r.disabled = True if c.new == 1 else False

        def _bond_r(c):
            for scn in self.active():
                scn.bond_r = c.new

        atoms.on_click(_atoms)
        fill.observe(_fill, names='index')
        bond_r.observe(_bond_r, names='value')
        content = _ListDict([('opt', fill), ('bond_r', bond_r)])
        return Folder(atoms, content)
def MakePoseSlidersThatPublishOnCallback(publishing_system,
                                         root_context,
                                         my_callback,
                                         min_range=PoseSliders.MinRange(),
                                         max_range=PoseSliders.MaxRange(),
                                         value=PoseSliders.Value(),
                                         resolution=0.01,
                                         length=200,
                                         continuous_update=True):

    def value_to_pose(val):
        return RigidTransform(RollPitchYaw(val.roll, val.pitch, val.yaw),
                              [val.x, val.y, val.z])

    def pose_to_value(pose):
        rpy = RollPitchYaw(pose.rotation())
        xyz = pose.translation()
        return PoseSliders.Value(rpy.roll_angle(), rpy.pitch_angle(),
                                 rpy.yaw_angle(), xyz[0], xyz[1], xyz[2])

    if isinstance(value, RigidTransform):
        value = pose_to_value(value)

    publishing_context = publishing_system.GetMyContextFromRoot(root_context)

    # Publish once immediately.
    my_callback(root_context, value_to_pose(value))
    publishing_system.Publish(publishing_context)

    global v
    v = value

    def _slider_callback(change, var):
        global v
        v = v._replace(**{var: change.new})
        my_callback(root_context, value_to_pose(v))
        publishing_system.Publish(publishing_context)

    slider_widgets = []
    for var in ["roll", "pitch", "yaw", "x", "y", "z"]:
        slider = FloatSlider(min=getattr(min_range, var),
                             max=getattr(max_range, var),
                             value=getattr(value, var),
                             step=resolution,
                             continuous_update=continuous_update,
                             description=var,
                             layout=Layout(width='90%'))
        slider.observe(partial(_slider_callback, var=var), names='value')
        display(slider)
        slider_widgets.append(slider)

    return slider_widgets
Beispiel #4
0
    def notebook_interaction(self, display=True):

        from ipywidgets import (Checkbox, FloatSlider, VBox)
        from traitlets import TraitError as TraitletError
        from IPython.display import display as ip_display

        try:
            active = Checkbox(description='active', value=self.active)

            def on_active_change(change):
                self.active = change['new']

            active.observe(on_active_change, names='value')

            fine_structure = Checkbox(description='Fine structure',
                                      value=self.fine_structure_active)

            def on_fine_structure_active_change(change):
                self.fine_structure_active = change['new']

            fine_structure.observe(on_fine_structure_active_change,
                                   names='value')

            fs_smoothing = FloatSlider(description='Fine structure smoothing',
                                       min=0,
                                       max=1,
                                       step=0.001,
                                       value=self.fine_structure_smoothing)

            def on_fs_smoothing_change(change):
                self.fine_structure_smoothing = change['new']

            fs_smoothing.observe(on_fs_smoothing_change, names='value')

            container = VBox([active, fine_structure, fs_smoothing])
            for parameter in [
                    self.intensity, self.effective_angle, self.onset_energy
            ]:
                container.children += parameter.notebook_interaction(False),

            if not display:
                return container
            ip_display(container)
        except TraitletError:
            if display:
                print('This function is only avialable when running in a'
                      ' notebook')
            else:
                raise
Beispiel #5
0
    def _create_notebook_widget(self, index=None):

        from ipywidgets import (FloatSlider, FloatText, Layout, HBox)

        widget_bounds = self._interactive_slider_bounds(index=index)
        thismin = FloatText(
            value=widget_bounds['min'],
            description='min',
            layout=Layout(flex='0 1 auto', width='auto'),
        )
        thismax = FloatText(
            value=widget_bounds['max'],
            description='max',
            layout=Layout(flex='0 1 auto', width='auto'),
        )
        current_value = self.value if index is None else self.value[index]
        current_name = self.name
        if index is not None:
            current_name += '_{}'.format(index)
        widget = FloatSlider(value=current_value,
                             min=thismin.value,
                             max=thismax.value,
                             step=widget_bounds['step'],
                             description=current_name,
                             layout=Layout(flex='1 1 auto', width='auto'))

        def on_min_change(change):
            if widget.max > change['new']:
                widget.min = change['new']
                widget.step = np.abs(widget.max - widget.min) * 0.001

        def on_max_change(change):
            if widget.min < change['new']:
                widget.max = change['new']
                widget.step = np.abs(widget.max - widget.min) * 0.001

        thismin.observe(on_min_change, names='value')
        thismax.observe(on_max_change, names='value')

        this_observed = functools.partial(self._interactive_update,
                                          index=index)

        widget.observe(this_observed, names='value')
        container = HBox((thismin, widget, thismax))
        return container
            def _create_widgets(self):
                """Create widget in the current visual control"""
                for param in self._param_descriptors:
                    value = self._native_params[param]
                    parameter = self._param_descriptors[param]
                    props = parameter.__propinfo__['__literal__']
                    description = props['title']

                    if isinstance(value, float):
                        minimum = self._get_value(props, 'minimum', 0)
                        maximum = self._get_value(props, 'maximum', 1e4)
                        float_slider = FloatSlider(description=description,
                                                   min=minimum,
                                                   max=maximum,
                                                   value=value,
                                                   STYLE=STYLE,
                                                   layout=DEFAULT_LAYOUT)
                        float_slider.observe(self._update_params, 'value')
                        self._widgets_list[param] = float_slider
                    if isinstance(value, int):
                        minimum = self._get_value(props, 'minimum', 0)
                        maximum = self._get_value(props, 'maximum', 1e4)
                        int_slider = IntSlider(description=description,
                                               min=minimum,
                                               max=maximum,
                                               value=value,
                                               STYLE=STYLE,
                                               layout=DEFAULT_LAYOUT)
                        int_slider.observe(self._update_params, 'value')
                        self._widgets_list[param] = int_slider
                    if isinstance(value, bool):
                        check_box = Checkbox(description=description,
                                             value=bool(value),
                                             STYLE=STYLE,
                                             layout=DEFAULT_LAYOUT)
                        check_box.observe(self._update_params, 'value')
                        self._widgets_list[param] = check_box
                    if isinstance(value, str):
                        text_box = Text(description=description,
                                        value=value,
                                        STYLE=STYLE,
                                        layout=DEFAULT_LAYOUT)
                        text_box.observe(self._update_params, 'value')
                        self._widgets_list[param] = text_box
Beispiel #7
0
    def _create_notebook_widget(self, index=None):

        from ipywidgets import (FloatSlider, FloatText, Layout, HBox)

        widget_bounds = self._interactive_slider_bounds(index=index)
        thismin = FloatText(value=widget_bounds['min'],
                            description='min',
                            layout=Layout(flex='0 1 auto',
                                          width='auto'),)
        thismax = FloatText(value=widget_bounds['max'],
                            description='max',
                            layout=Layout(flex='0 1 auto',
                                          width='auto'),)
        current_value = self.value if index is None else self.value[index]
        current_name = self.name
        if index is not None:
            current_name += '_{}'.format(index)
        widget = FloatSlider(value=current_value,
                             min=thismin.value,
                             max=thismax.value,
                             step=widget_bounds['step'],
                             description=current_name,
                             layout=Layout(flex='1 1 auto', width='auto'))

        def on_min_change(change):
            if widget.max > change['new']:
                widget.min = change['new']
                widget.step = np.abs(widget.max - widget.min) * 0.001

        def on_max_change(change):
            if widget.min < change['new']:
                widget.max = change['new']
                widget.step = np.abs(widget.max - widget.min) * 0.001

        thismin.observe(on_min_change, names='value')
        thismax.observe(on_max_change, names='value')

        this_observed = functools.partial(self._interactive_update,
                                          index=index)

        widget.observe(this_observed, names='value')
        container = HBox((thismin, widget, thismax))
        return container
Beispiel #8
0
    def notebook_interaction(self, display=True):

        from ipywidgets import (Checkbox, FloatSlider, VBox)
        from traitlets import TraitError as TraitletError
        from IPython.display import display as ip_display

        try:
            active = Checkbox(description='active', value=self.active)

            def on_active_change(change):
                self.active = change['new']
            active.observe(on_active_change, names='value')

            fine_structure = Checkbox(description='Fine structure',
                                      value=self.fine_structure_active)

            def on_fine_structure_active_change(change):
                self.fine_structure_active = change['new']
            fine_structure.observe(on_fine_structure_active_change,
                                   names='value')

            fs_smoothing = FloatSlider(description='Fine structure smoothing',
                                       min=0, max=1, step=0.001,
                                       value=self.fine_structure_smoothing)

            def on_fs_smoothing_change(change):
                self.fine_structure_smoothing = change['new']
            fs_smoothing.observe(on_fs_smoothing_change, names='value')

            container = VBox([active, fine_structure, fs_smoothing])
            for parameter in [self.intensity, self.effective_angle,
                              self.onset_energy]:
                container.children += parameter.notebook_interaction(False),

            if not display:
                return container
            ip_display(container)
        except TraitletError:
            if display:
                print('This function is only avialable when running in a'
                      ' notebook')
            else:
                raise
Beispiel #9
0
    def _tensor_folder(self):
        alo = Layout(width='70px')
        rlo = Layout(width='220px')
        scale = FloatSlider(max=10.0, step=0.001, readout=True, value=1.0)
        tens = Button(description=' Tensor', icon='bank')

        def _tens(c):
            for scn in self.active():
                scn.tens = not scn.tens

        def _scale(c):
            for scn in self.active():
                scn.scale = c.new

        tens.on_click(_tens)
        scale.observe(_scale, names='value')
        content = _ListDict([
            ('scale', scale),
        ])
        return Folder(tens, content)
Beispiel #10
0
class Dashboard(VBox):
    """
    Build the dashboard for Jupyter widgets. Requires running
    in a notebook/jupyterlab.
    """
    def __init__(self, net, width="95%", height="550px", play_rate=0.5):
        self._ignore_layer_updates = False
        self.player = _Player(self, play_rate)
        self.player.start()
        self.net = net
        r = random.randint(1, 1000000)
        self.class_id = "picture-dashboard-%s-%s" % (self.net.name, r)
        self._width = width
        self._height = height
        ## Global widgets:
        style = {"description_width": "initial"}
        self.feature_columns = IntText(description="Feature columns:",
                                       value=self.net.config["dashboard.features.columns"],
                                       min=0,
                                       max=1024,
                                       style=style)
        self.feature_scale = FloatText(description="Feature scale:",
                                       value=self.net.config["dashboard.features.scale"],
                                       min=0.1,
                                       max=10,
                                       style=style)
        self.feature_columns.observe(self.regenerate, names='value')
        self.feature_scale.observe(self.regenerate, names='value')
        ## Hack to center SVG as justify-content is broken:
        self.net_svg = HTML(value="""<p style="text-align:center">%s</p>""" % ("",), layout=Layout(
            width=self._width, overflow_x='auto', overflow_y="auto",
            justify_content="center"))
        # Make controls first:
        self.output = Output()
        controls = self.make_controls()
        config = self.make_config()
        super().__init__([config, controls, self.net_svg, self.output])

    def propagate(self, inputs):
        """
        Propagate inputs through the dashboard view of the network.
        """
        if dynamic_pictures_check():
            return self.net.propagate(inputs, class_id=self.class_id, update_pictures=True)
        else:
            self.regenerate(inputs=input)

    def goto(self, position):
        if len(self.net.dataset.inputs) == 0 or len(self.net.dataset.targets) == 0:
            return
        if self.control_select.value == "Train":
            length = len(self.net.dataset.train_inputs)
        elif self.control_select.value == "Test":
            length = len(self.net.dataset.test_inputs)
        #### Position it:
        if position == "begin":
            self.control_slider.value = 0
        elif position == "end":
            self.control_slider.value = length - 1
        elif position == "prev":
            if self.control_slider.value - 1 < 0:
                self.control_slider.value = length - 1 # wrap around
            else:
                self.control_slider.value = max(self.control_slider.value - 1, 0)
        elif position == "next":
            if self.control_slider.value + 1 > length - 1:
                self.control_slider.value = 0 # wrap around
            else:
                self.control_slider.value = min(self.control_slider.value + 1, length - 1)
        self.position_text.value = self.control_slider.value


    def change_select(self, change=None):
        """
        """
        self.update_control_slider(change)
        self.regenerate()

    def update_control_slider(self, change=None):
        self.net.config["dashboard.dataset"] = self.control_select.value
        if len(self.net.dataset.inputs) == 0 or len(self.net.dataset.targets) == 0:
            self.total_text.value = "of 0"
            self.control_slider.value = 0
            self.position_text.value = 0
            self.control_slider.disabled = True
            self.position_text.disabled = True
            for child in self.control_buttons.children:
                if not hasattr(child, "icon") or child.icon != "refresh":
                    child.disabled = True
            return
        if self.control_select.value == "Test":
            self.total_text.value = "of %s" % len(self.net.dataset.test_inputs)
            minmax = (0, max(len(self.net.dataset.test_inputs) - 1, 0))
            if minmax[0] <= self.control_slider.value <= minmax[1]:
                pass # ok
            else:
                self.control_slider.value = 0
            self.control_slider.min = minmax[0]
            self.control_slider.max = minmax[1]
            if len(self.net.dataset.test_inputs) == 0:
                disabled = True
            else:
                disabled = False
        elif self.control_select.value == "Train":
            self.total_text.value = "of %s" % len(self.net.dataset.train_inputs)
            minmax = (0, max(len(self.net.dataset.train_inputs) - 1, 0))
            if minmax[0] <= self.control_slider.value <= minmax[1]:
                pass # ok
            else:
                self.control_slider.value = 0
            self.control_slider.min = minmax[0]
            self.control_slider.max = minmax[1]
            if len(self.net.dataset.train_inputs) == 0:
                disabled = True
            else:
                disabled = False
        self.control_slider.disabled = disabled
        self.position_text.disbaled = disabled
        self.position_text.value = self.control_slider.value
        for child in self.control_buttons.children:
            if not hasattr(child, "icon") or child.icon != "refresh":
                child.disabled = disabled

    def update_zoom_slider(self, change):
        if change["name"] == "value":
            self.net.config["svg_scale"] = self.zoom_slider.value
            self.regenerate()

    def update_position_text(self, change):
        # {'name': 'value', 'old': 2, 'new': 3, 'owner': IntText(value=3, layout=Layout(width='100%')), 'type': 'change'}
        self.control_slider.value = change["new"]

    def get_current_input(self):
        if self.control_select.value == "Train" and len(self.net.dataset.train_targets) > 0:
            return self.net.dataset.train_inputs[self.control_slider.value]
        elif self.control_select.value == "Test" and len(self.net.dataset.test_targets) > 0:
            return self.net.dataset.test_inputs[self.control_slider.value]

    def get_current_targets(self):
        if self.control_select.value == "Train" and len(self.net.dataset.train_targets) > 0:
            return self.net.dataset.train_targets[self.control_slider.value]
        elif self.control_select.value == "Test" and len(self.net.dataset.test_targets) > 0:
            return self.net.dataset.test_targets[self.control_slider.value]

    def update_slider_control(self, change):
        if len(self.net.dataset.inputs) == 0 or len(self.net.dataset.targets) == 0:
            self.total_text.value = "of 0"
            return
        if change["name"] == "value":
            self.position_text.value = self.control_slider.value
            if self.control_select.value == "Train" and len(self.net.dataset.train_targets) > 0:
                self.total_text.value = "of %s" % len(self.net.dataset.train_inputs)
                if self.net.model is None:
                    return
                if not dynamic_pictures_check():
                    self.regenerate(inputs=self.net.dataset.train_inputs[self.control_slider.value],
                                    targets=self.net.dataset.train_targets[self.control_slider.value])
                    return
                output = self.net.propagate(self.net.dataset.train_inputs[self.control_slider.value],
                                            class_id=self.class_id, update_pictures=True)
                if self.feature_bank.value in self.net.layer_dict.keys():
                    self.net.propagate_to_features(self.feature_bank.value, self.net.dataset.train_inputs[self.control_slider.value],
                                               cols=self.feature_columns.value, scale=self.feature_scale.value, html=False)
                if self.net.config["show_targets"]:
                    if len(self.net.output_bank_order) == 1: ## FIXME: use minmax of output bank
                        self.net.display_component([self.net.dataset.train_targets[self.control_slider.value]],
                                                   "targets",
                                                   class_id=self.class_id,
                                                   minmax=(-1, 1))
                    else:
                        self.net.display_component(self.net.dataset.train_targets[self.control_slider.value],
                                                   "targets",
                                                   class_id=self.class_id,
                                                   minmax=(-1, 1))
                if self.net.config["show_errors"]: ## minmax is error
                    if len(self.net.output_bank_order) == 1:
                        errors = np.array(output) - np.array(self.net.dataset.train_targets[self.control_slider.value])
                        self.net.display_component([errors.tolist()],
                                                   "errors",
                                                   class_id=self.class_id,
                                                   minmax=(-1, 1))
                    else:
                        errors = []
                        for bank in range(len(self.net.output_bank_order)):
                            errors.append( np.array(output[bank]) - np.array(self.net.dataset.train_targets[self.control_slider.value][bank]))
                        self.net.display_component(errors, "errors",  class_id=self.class_id, minmax=(-1, 1))
            elif self.control_select.value == "Test" and len(self.net.dataset.test_targets) > 0:
                self.total_text.value = "of %s" % len(self.net.dataset.test_inputs)
                if self.net.model is None:
                    return
                if not dynamic_pictures_check():
                    self.regenerate(inputs=self.net.dataset.test_inputs[self.control_slider.value],
                                    targets=self.net.dataset.test_targets[self.control_slider.value])
                    return
                output = self.net.propagate(self.net.dataset.test_inputs[self.control_slider.value],
                                            class_id=self.class_id, update_pictures=True)
                if self.feature_bank.value in self.net.layer_dict.keys():
                    self.net.propagate_to_features(self.feature_bank.value, self.net.dataset.test_inputs[self.control_slider.value],
                                               cols=self.feature_columns.value, scale=self.feature_scale.value, html=False)
                if self.net.config["show_targets"]: ## FIXME: use minmax of output bank
                    self.net.display_component([self.net.dataset.test_targets[self.control_slider.value]],
                                               "targets",
                                               class_id=self.class_id,
                                               minmax=(-1, 1))
                if self.net.config["show_errors"]: ## minmax is error
                    if len(self.net.output_bank_order) == 1:
                        errors = np.array(output) - np.array(self.net.dataset.test_targets[self.control_slider.value])
                        self.net.display_component([errors.tolist()],
                                                   "errors",
                                                   class_id=self.class_id,
                                                   minmax=(-1, 1))
                    else:
                        errors = []
                        for bank in range(len(self.net.output_bank_order)):
                            errors.append( np.array(output[bank]) - np.array(self.net.dataset.test_targets[self.control_slider.value][bank]))
                        self.net.display_component(errors, "errors", class_id=self.class_id, minmax=(-1, 1))

    def toggle_play(self, button):
        ## toggle
        if self.button_play.description == "Play":
            self.button_play.description = "Stop"
            self.button_play.icon = "pause"
            self.player.resume()
        else:
            self.button_play.description = "Play"
            self.button_play.icon = "play"
            self.player.pause()

    def prop_one(self, button=None):
        self.update_slider_control({"name": "value"})

    def regenerate(self, button=None, inputs=None, targets=None):
        ## Protection when deleting object on shutdown:
        if isinstance(button, dict) and 'new' in button and button['new'] is None:
            return
        ## Update the config:
        self.net.config["dashboard.features.bank"] = self.feature_bank.value
        self.net.config["dashboard.features.columns"] = self.feature_columns.value
        self.net.config["dashboard.features.scale"] = self.feature_scale.value
        inputs = inputs if inputs is not None else self.get_current_input()
        targets = targets if targets is not None else self.get_current_targets()
        features = None
        if self.feature_bank.value in self.net.layer_dict.keys() and inputs is not None:
            if self.net.model is not None:
                features = self.net.propagate_to_features(self.feature_bank.value, inputs,
                                                          cols=self.feature_columns.value,
                                                          scale=self.feature_scale.value, display=False)
        svg = """<p style="text-align:center">%s</p>""" % (self.net.to_svg(inputs=inputs, targets=targets,
                                                                           class_id=self.class_id),)
        if inputs is not None and features is not None:
            html_horizontal = """
<table align="center" style="width: 100%%;">
 <tr>
  <td valign="top" style="width: 50%%;">%s</td>
  <td valign="top" align="center" style="width: 50%%;"><p style="text-align:center"><b>%s</b></p>%s</td>
</tr>
</table>"""
            html_vertical = """
<table align="center" style="width: 100%%;">
 <tr>
  <td valign="top">%s</td>
</tr>
<tr>
  <td valign="top" align="center"><p style="text-align:center"><b>%s</b></p>%s</td>
</tr>
</table>"""
            self.net_svg.value = (html_vertical if self.net.config["svg_rotate"] else html_horizontal) % (
                svg, "%s features" % self.feature_bank.value, features)
        else:
            self.net_svg.value = svg

    def make_colormap_image(self, colormap_name):
        from .layers import Layer
        if not colormap_name:
            colormap_name = get_colormap()
        layer = Layer("Colormap", 100)
        minmax = layer.get_act_minmax()
        image = layer.make_image(np.arange(minmax[0], minmax[1], .01),
                                 colormap_name,
                                 {"pixels_per_unit": 1,
                                  "svg_rotate": self.net.config["svg_rotate"]}).resize((300, 25))
        return image

    def set_attr(self, obj, attr, value):
        if value not in [{}, None]: ## value is None when shutting down
            if isinstance(value, dict):
                value = value["value"]
            if isinstance(obj, dict):
                obj[attr] = value
            else:
                setattr(obj, attr, value)
            ## was crashing on Widgets.__del__, if get_ipython() no longer existed
            self.regenerate()

    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%'))
        #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(width="100%"))
        refresh_button = Button(icon="refresh", layout=Layout(width="25%"))

        self.position_text = IntText(value=0, layout=Layout(width="100%"))

        self.control_buttons = HBox([
            button_begin,
            button_prev,
            #button_train,
            self.position_text,
            button_next,
            button_end,
            self.button_play,
            refresh_button
        ], layout=Layout(width='100%', height="50px"))
        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()))
        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 make_config(self):
        layout = Layout()
        style = {"description_width": "initial"}
        checkbox1 = Checkbox(description="Show Targets", value=self.net.config["show_targets"],
                             layout=layout, style=style)
        checkbox1.observe(lambda change: self.set_attr(self.net.config, "show_targets", change["new"]), names='value')
        checkbox2 = Checkbox(description="Errors", value=self.net.config["show_errors"],
                             layout=layout, style=style)
        checkbox2.observe(lambda change: self.set_attr(self.net.config, "show_errors", change["new"]), names='value')

        hspace = IntText(value=self.net.config["hspace"], description="Horizontal space between banks:",
                         style=style, layout=layout)
        hspace.observe(lambda change: self.set_attr(self.net.config, "hspace", change["new"]), names='value')
        vspace = IntText(value=self.net.config["vspace"], description="Vertical space between layers:",
                         style=style, layout=layout)
        vspace.observe(lambda change: self.set_attr(self.net.config, "vspace", change["new"]), names='value')
        self.feature_bank = Select(description="Features:", value=self.net.config["dashboard.features.bank"],
                              options=[""] + [layer.name for layer in self.net.layers if self.net._layer_has_features(layer.name)],
                              rows=1)
        self.feature_bank.observe(self.regenerate, names='value')
        self.control_select = Select(
            options=['Test', 'Train'],
            value=self.net.config["dashboard.dataset"],
            description='Dataset:',
            rows=1
        )
        self.control_select.observe(self.change_select, names='value')
        column1 = [self.control_select,
                   self.zoom_slider,
                   hspace,
                   vspace,
                   HBox([checkbox1, checkbox2]),
                   self.feature_bank,
                   self.feature_columns,
                   self.feature_scale
        ]
        ## Make layer selectable, and update-able:
        column2 = []
        layer = self.net.layers[-1]
        self.layer_select = Select(description="Layer:", value=layer.name,
                                   options=[layer.name for layer in
                                            self.net.layers],
                                   rows=1)
        self.layer_select.observe(self.update_layer_selection, names='value')
        column2.append(self.layer_select)
        self.layer_visible_checkbox = Checkbox(description="Visible", value=layer.visible, layout=layout)
        self.layer_visible_checkbox.observe(self.update_layer, names='value')
        column2.append(self.layer_visible_checkbox)
        self.layer_colormap = Select(description="Colormap:",
                                     options=[""] + AVAILABLE_COLORMAPS,
                                     value=layer.colormap if layer.colormap is not None else "", layout=layout, rows=1)
        self.layer_colormap_image = HTML(value="""<img src="%s"/>""" % self.net._image_to_uri(self.make_colormap_image(layer.colormap)))
        self.layer_colormap.observe(self.update_layer, names='value')
        column2.append(self.layer_colormap)
        column2.append(self.layer_colormap_image)
        ## get dynamic minmax; if you change it it will set it in layer as override:
        minmax = layer.get_act_minmax()
        self.layer_mindim = FloatText(description="Leftmost color maps to:", value=minmax[0], style=style)
        self.layer_maxdim = FloatText(description="Rightmost color maps to:", value=minmax[1], style=style)
        self.layer_mindim.observe(self.update_layer, names='value')
        self.layer_maxdim.observe(self.update_layer, names='value')
        column2.append(self.layer_mindim)
        column2.append(self.layer_maxdim)
        output_shape = layer.get_output_shape()
        self.layer_feature = IntText(value=layer.feature, description="Feature to show:", style=style)
        self.svg_rotate = Checkbox(description="Rotate", value=layer.visible, layout=layout)
        self.layer_feature.observe(self.update_layer, names='value')
        column2.append(self.layer_feature)
        self.svg_rotate = Checkbox(description="Rotate network",
                                   value=self.net.config["svg_rotate"],
                                   style={"description_width": 'initial'},
                                   layout=Layout(width="52%"))
        self.svg_rotate.observe(lambda change: self.set_attr(self.net.config, "svg_rotate", change["new"]), names='value')
        self.save_config_button = Button(icon="save", layout=Layout(width="10%"))
        self.save_config_button.on_click(self.save_config)
        column2.append(HBox([self.svg_rotate, self.save_config_button]))
        config_children = HBox([VBox(column1, layout=Layout(width="100%")),
                                VBox(column2, layout=Layout(width="100%"))])
        accordion = Accordion(children=[config_children])
        accordion.set_title(0, self.net.name)
        accordion.selected_index = None
        return accordion

    def save_config(self, widget=None):
        self.net.save_config()

    def update_layer(self, change):
        """
        Update the layer object, and redisplay.
        """
        if self._ignore_layer_updates:
            return
        ## The rest indicates a change to a display variable.
        ## We need to save the value in the layer, and regenerate
        ## the display.
        # Get the layer:
        layer = self.net[self.layer_select.value]
        # Save the changed value in the layer:
        layer.feature = self.layer_feature.value
        layer.visible = self.layer_visible_checkbox.value
        ## These three, dealing with colors of activations,
        ## can be done with a prop_one():
        if "color" in change["owner"].description.lower():
            ## Matches: Colormap, lefmost color, rightmost color
            ## overriding dynamic minmax!
            layer.minmax = (self.layer_mindim.value, self.layer_maxdim.value)
            layer.minmax = (self.layer_mindim.value, self.layer_maxdim.value)
            layer.colormap = self.layer_colormap.value if self.layer_colormap.value else None
            self.layer_colormap_image.value = """<img src="%s"/>""" % self.net._image_to_uri(self.make_colormap_image(layer.colormap))
            self.prop_one()
        else:
            self.regenerate()

    def update_layer_selection(self, change):
        """
        Just update the widgets; don't redraw anything.
        """
        ## No need to redisplay anything
        self._ignore_layer_updates = True
        ## First, get the new layer selected:
        layer = self.net[self.layer_select.value]
        ## Now, let's update all of the values without updating:
        self.layer_visible_checkbox.value = layer.visible
        self.layer_colormap.value = layer.colormap if layer.colormap != "" else ""
        self.layer_colormap_image.value = """<img src="%s"/>""" % self.net._image_to_uri(self.make_colormap_image(layer.colormap))
        minmax = layer.get_act_minmax()
        self.layer_mindim.value = minmax[0]
        self.layer_maxdim.value = minmax[1]
        self.layer_feature.value = layer.feature
        self._ignore_layer_updates = False
Beispiel #11
0
class Player(VBox):
    def __init__(self, title, function, length, play_rate=0.1):
        """
        function - takes a slider value and returns displayables
        """
        self.player = _Player(self, play_rate)
        self.player.start()
        self.title = title
        self.function = function
        self.length = length
        self.output = Output()
        self.position_text = FloatText(value=0.0, layout=Layout(width="100%"))
        self.total_text = Label(value="of %s" % round(self.length * 0.1, 1),
                                layout=Layout(width="100px"))
        controls = self.make_controls()
        super().__init__([controls, self.output])

    def update_length(self, length):
        self.length = length
        self.total_text.value = "of %s" % round(self.length * 0.1, 1)
        self.control_slider.max = round(max(self.length * 0.1, 0), 1)

    def goto(self, position):
        #### Position it:
        if position == "begin":
            self.control_slider.value = 0.0
        elif position == "end":
            self.control_slider.value = round(self.length * 0.1, 1)
        elif position == "prev":
            if self.control_slider.value - 0.1 < 0:
                self.control_slider.value = round(self.length * 0.1,
                                                  1)  # wrap around
            else:
                self.control_slider.value = round(
                    max(self.control_slider.value - 0.1, 0), 1)
        elif position == "next":
            if round(self.control_slider.value + 0.1, 1) > round(
                    self.length * 0.1, 1):
                self.control_slider.value = 0  # wrap around
            else:
                self.control_slider.value = round(
                    min(self.control_slider.value + 0.1, self.length * 0.1), 1)
        self.position_text.value = round(self.control_slider.value, 1)

    def toggle_play(self, button):
        ## toggle
        if self.button_play.description == "Play":
            self.button_play.description = "Stop"
            self.button_play.icon = "pause"
            self.player.resume()
        else:
            self.button_play.description = "Play"
            self.button_play.icon = "play"
            self.player.pause()

    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 = FloatSlider(
            description=self.title,
            continuous_update=False,
            min=0.0,
            step=0.1,
            max=max(round(self.length * 0.1, 1), 0.0),
            value=0.0,
            readout_format=".1f",
            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

    def initialize(self):
        """
        Setup the displayer ids to map results to the areas.
        """
        results = self.function(self.control_slider.value)
        if not isinstance(results, (list, tuple)):
            results = [results]
        self.displayers = [display(x, display_id=True) for x in results]

    def update_slider_control(self, change):
        """
        If the slider changes the value, call the function
        and update display areas.
        """
        if change["name"] == "value":
            self.position_text.value = self.control_slider.value
            self.output.clear_output(wait=True)
            results = self.function(self.control_slider.value)
            if not isinstance(results, (list, tuple)):
                results = [results]
            for i in range(len(self.displayers)):
                self.displayers[i].update(results[i])
Beispiel #12
0

out = widgets.interactive_output(f, {'a': a, 'b': b, 'c': c})

display(ui, out)
"""#*observe : 相互に依存している引数"""

x_widget = FloatSlider(min=0.0, max=10.0, step=0.05)
y_widget = FloatSlider(min=0.5, max=10.0, step=0.05, value=5.0)


def update_x_range(*args):
    x_widget.max = 2.0 * y_widget.value


y_widget.observe(update_x_range, 'value')


def printer(x, y):
    print(x, y)


interact(printer, x=x_widget, y=y_widget)
"""#output.layout : ちらつきを防ぐ"""

# Commented out IPython magic to ensure Python compatibility.
# %matplotlib inline
from ipywidgets import interactive
import matplotlib.pyplot as plt
import numpy as np
def addLayer(inMap, path, name, clip=[0, 0.8], bands=None):
    #Check the filetype: netcdf or geotiff
    if path.split('.')[-1] == 'nc':
        da = xr.open_dataset(path)
        if 't' in da.dims:
            da = da.drop('t').squeeze('t').to_array().astype(np.float32)
        elif 'time' in da.dims:
            da = da.drop('time').squeeze('time').to_array().astype(np.float32)
        else:
            da = da.to_array().astype(np.float32)
        if 'variable' in da.dims and 'bands' in da.dims:
            da = da.drop('variable').squeeze('variable').rename(
                {'bands': 'variable'})
    else:
        da = xr.open_rasterio(path)
        if 't' in da.dims:
            da = da.rename({
                'band': 'variable'
            }).drop('t').squeeze('t').astype(np.float32)
        else:
            da = da.rename({'band': 'variable'}).astype(np.float32)
    rds4326 = da.rio.reproject("epsg:4326")
    rds4326.name = name
    rds4326 = rds4326.rio.write_crs(4326)  # WGS 84
    if bands is not None:
        rds4326 = rds4326.loc[dict(variable=bands)]
    opacity_slider = FloatSlider(description=name + ' opacity:',
                                 min=0,
                                 max=1,
                                 value=1)

    def set_opacity(change):
        l.opacity = change['new']

    if (len(rds4326.variable) == 3):
        rds4326 = rds4326.clip(clip[0], clip[1]) / clip[1] * 255
        rds4326 = rds4326.fillna(0).rio.write_nodata(0)
        rds4326 = rds4326.chunk((1000, 1000))
        l = rds4326.leaflet.plot(inMap.map, rgb_dim='variable')

        opacity_slider.observe(set_opacity, names='value')
        slider_control = WidgetControl(widget=opacity_slider,
                                       position='bottomleft')
        inMap.map.add_control(slider_control)
    elif (len(rds4326.variable) == 1):
        rds4326 = rds4326[0]
        rds4326 = rds4326.clip(clip[0], clip[1])
        rds4326 = rds4326.fillna(0).rio.write_nodata(0)
        rds4326 = rds4326.chunk((1000, 1000))
        cmap = plt.cm.get_cmap('Greys_r')
        l = rds4326.leaflet.plot(inMap.map, colormap=cmap)

        def set_opacity(change):
            l.opacity = change['new']

        opacity_slider.observe(set_opacity, names='value')
        slider_control = WidgetControl(widget=opacity_slider,
                                       position='bottomleft')
        inMap.map.add_control(slider_control)
    else:
        rds4326 = rds4326[0]
        rds4326 = rds4326.fillna(0).rio.write_nodata(0)
        rds4326 = rds4326.chunk((1000, 1000))
        rds4326 = rds4326.clip(clip[0], clip[1])
        cmap = plt.cm.get_cmap('Greys_r')
        l = rds4326.leaflet.plot(inMap.map, colormap=cmap)

        def set_opacity(change):
            l.opacity = change['new']

        opacity_slider.observe(set_opacity, names='value')
        slider_control = WidgetControl(widget=opacity_slider,
                                       position='bottomleft')
        inMap.map.add_control(slider_control)
    return
Beispiel #14
0
    def create_param_widget(self, param, value):
        from ipywidgets import Layout, HBox
        children = (HBox(),)
        if isinstance(value, bool):
            from ipywidgets import Label, ToggleButton
            p = Label(value=param, layout=Layout(width='10%'))
            t = ToggleButton(description=str(value), value=value)

            def on_bool_change(change):
                t.description = str(change['new'])
                self.params[self._method][param] = change['new']
                self.replot_peaks()

            t.observe(on_bool_change, names='value')

            children = (p, t)

        elif isinstance(value, float):
            from ipywidgets import FloatSlider, FloatText, BoundedFloatText, \
                Label
            from traitlets import link
            p = Label(value=param, layout=Layout(flex='0 1 auto', width='10%'))
            b = BoundedFloatText(value=0, min=1e-10,
                                 layout=Layout(flex='0 1 auto', width='10%'),
                                 font_weight='bold')
            a = FloatText(value=2 * value,
                          layout=Layout(flex='0 1 auto', width='10%'))
            f = FloatSlider(value=value, min=b.value, max=a.value,
                            step=np.abs(a.value - b.value) * 0.01,
                            layout=Layout(flex='1 1 auto', width='60%'))
            l = FloatText(value=f.value,
                          layout=Layout(flex='0 1 auto', width='10%'),
                          disabled=True)
            link((f, 'value'), (l, 'value'))

            def on_min_change(change):
                if f.max > change['new']:
                    f.min = change['new']
                    f.step = np.abs(f.max - f.min) * 0.01

            def on_max_change(change):
                if f.min < change['new']:
                    f.max = change['new']
                    f.step = np.abs(f.max - f.min) * 0.01

            def on_param_change(change):
                self.params[self._method][param] = change['new']
                self.replot_peaks()

            b.observe(on_min_change, names='value')
            f.observe(on_param_change, names='value')
            a.observe(on_max_change, names='value')
            children = (p, l, b, f, a)

        elif isinstance(value, int):
            from ipywidgets import IntSlider, IntText, BoundedIntText, \
                Label
            from traitlets import link
            p = Label(value=param, layout=Layout(flex='0 1 auto', width='10%'))
            b = BoundedIntText(value=0, min=1e-10,
                               layout=Layout(flex='0 1 auto', width='10%'),
                               font_weight='bold')
            a = IntText(value=2 * value,
                        layout=Layout(flex='0 1 auto', width='10%'))
            f = IntSlider(value=value, min=b.value, max=a.value,
                          step=1,
                          layout=Layout(flex='1 1 auto', width='60%'))
            l = IntText(value=f.value,
                        layout=Layout(flex='0 1 auto', width='10%'),
                        disabled=True)
            link((f, 'value'), (l, 'value'))

            def on_min_change(change):
                if f.max > change['new']:
                    f.min = change['new']
                    f.step = 1

            def on_max_change(change):
                if f.min < change['new']:
                    f.max = change['new']
                    f.step = 1

            def on_param_change(change):
                self.params[self._method][param] = change['new']
                self.replot_peaks()

            b.observe(on_min_change, names='value')
            f.observe(on_param_change, names='value')
            a.observe(on_max_change, names='value')
            children = (p, l, b, f, a)
        container = HBox(children)
        return container
    def display_palette_for_models(self):
        """Display visual controls for color palettes applied to models"""
        def set_colormap(model_id, colormap_name, shading_mode):
            material_ids = self._be.get_material_ids(model_id)['ids']
            nb_materials = len(material_ids)

            palette = sns.color_palette(colormap_name, nb_materials)
            self._be.set_materials_from_palette(
                model_ids=[model_id],
                material_ids=material_ids,
                palette=palette,
                specular_exponent=specular_exponent_slider.value,
                shading_mode=shading_mode,
                opacity=opacity_slider.value,
                refraction_index=refraction_index_slider.value,
                reflection_index=reflection_index_slider.value,
                glossiness=glossiness_slider.value,
                user_parameter=user_param_slider.value,
                emission=emission_slider.value,
                chameleon_mode=chameleon_combobox.index)
            self._client.set_renderer(accumulation=True)

        # Models
        model_names = list()
        for model in self._client.scene.models:
            model_names.append(model['name'])
        model_combobox = Select(options=model_names,
                                description='Models:',
                                disabled=False)

        # Shading modes
        shading_combobox = Select(options=SHADING_MODES,
                                  description='Shading:',
                                  disabled=False)

        # Colors
        palette_combobox = Select(options=COLOR_MAPS,
                                  description='Palette:',
                                  disabled=False)

        # Chameleon modes
        chameleon_combobox = Select(options=CHAMELEON_MODES,
                                    description='Chameleon:',
                                    disabled=False)

        # Events
        def update_materials_from_palette(value):
            """Update materials when palette is modified"""
            set_colormap(self._client.scene.models[model_combobox.index]['id'],
                         value['new'], shading_combobox.index)

        def update_materials_from_shading_modes(_):
            """Update materials when shading is modified"""
            set_colormap(self._client.scene.models[model_combobox.index]['id'],
                         palette_combobox.value, shading_combobox.index)

        def update_materials_from_chameleon_modes(_):
            """Update materials when chameleon mode is modified"""
            set_colormap(self._client.scene.models[model_combobox.index]['id'],
                         palette_combobox.value, shading_combobox.index)

        shading_combobox.observe(update_materials_from_shading_modes, 'value')
        palette_combobox.observe(update_materials_from_palette, 'value')
        chameleon_combobox.observe(update_materials_from_chameleon_modes,
                                   'value')

        horizontal_box_list = HBox(
            [model_combobox, shading_combobox, palette_combobox])

        opacity_slider = FloatSlider(description='Opacity',
                                     min=0,
                                     max=1,
                                     value=1)
        opacity_slider.observe(update_materials_from_shading_modes)
        refraction_index_slider = FloatSlider(description='Refraction',
                                              min=1,
                                              max=5,
                                              value=1)
        refraction_index_slider.observe(update_materials_from_shading_modes)
        reflection_index_slider = FloatSlider(description='Reflection',
                                              min=0,
                                              max=1,
                                              value=0)
        reflection_index_slider.observe(update_materials_from_shading_modes)
        glossiness_slider = FloatSlider(description='Glossiness',
                                        min=0,
                                        max=1,
                                        value=1)
        glossiness_slider.observe(update_materials_from_shading_modes)
        specular_exponent_slider = FloatSlider(description='Specular exponent',
                                               min=1,
                                               max=100,
                                               value=1)
        specular_exponent_slider.observe(update_materials_from_shading_modes)
        user_param_slider = FloatSlider(description='User param',
                                        min=0,
                                        max=100,
                                        value=1)
        user_param_slider.observe(update_materials_from_shading_modes)
        emission_slider = FloatSlider(description='Emission',
                                      min=0,
                                      max=100,
                                      value=0)
        emission_slider.observe(update_materials_from_shading_modes)

        cast_simulation_checkbox = Checkbox(description='Simulation',
                                            value=False)
        cast_simulation_checkbox.observe(update_materials_from_shading_modes)

        horizontal_box_detail1 = HBox(
            [opacity_slider, refraction_index_slider, reflection_index_slider])
        horizontal_box_detail2 = HBox(
            [glossiness_slider, specular_exponent_slider, user_param_slider])
        horizontal_box_detail3 = HBox(
            [emission_slider, cast_simulation_checkbox, chameleon_combobox])
        vertical_box = VBox([
            horizontal_box_list, horizontal_box_detail1,
            horizontal_box_detail2, horizontal_box_detail3
        ],
                            layout=DEFAULT_GRID_LAYOUT)
        display(vertical_box)
Beispiel #16
0
class NGLDisplay:
    """Structure display class

    Provides basic structure/trajectory display
    in the notebook and optional gui which can be used to enhance its
    usability.  It is also possible to extend the functionality of the
    particular instance of the viewer by adding further widgets
    manipulating the structure.
    """
    def __init__(self, atoms, xsize=500, ysize=500):
        import nglview
        from ipywidgets import Dropdown, FloatSlider, IntSlider, HBox, VBox
        self.atoms = atoms
        if isinstance(atoms[0], Atoms):
            # Assume this is a trajectory or struct list
            self.view = nglview.show_asetraj(atoms)
            self.frm = IntSlider(value=0, min=0, max=len(atoms) - 1)
            self.frm.observe(self._update_frame)
            self.struct = atoms[0]
        else:
            # Assume this is just a single structure
            self.view = nglview.show_ase(atoms)
            self.struct = atoms
            self.frm = None

        self.colors = {}
        self.view._remote_call('setSize', target='Widget',
                               args=['%dpx' % (xsize,), '%dpx' % (ysize,)])
        self.view.add_unitcell()
        self.view.add_spacefill()
        self.view.camera = 'orthographic'
        self.view.update_spacefill(radiusType='covalent', scale=0.7)
        self.view.center()

        self.asel = Dropdown(options=['All'] +
                             list(set(self.struct.get_chemical_symbols())),
                             value='All', description='Show')

        self.rad = FloatSlider(value=0.8, min=0.0, max=1.5, step=0.01,
                               description='Ball size')

        self.asel.observe(self._select_atom)
        self.rad.observe(self._update_repr)

        wdg = [self.asel, self.rad]
        if self.frm:
            wdg.append(self.frm)

        self.gui = HBox([self.view, VBox(wdg)])
        # Make useful shortcuts for the user of the class
        self.gui.view = self.view
        self.gui.control_box = self.gui.children[1]
        self.gui.custom_colors = self.custom_colors

    def _update_repr(self, chg=None):
        self.view.update_spacefill(radiusType='covalent', scale=self.rad.value)

    def _update_frame(self, chg=None):
        self.view.frame = self.frm.value
        return

    def _select_atom(self, chg=None):
        sel = self.asel.value
        self.view.remove_spacefill()
        for e in set(self.struct.get_chemical_symbols()):
            if (sel == 'All' or e == sel):
                if e in self.colors:
                    self.view.add_spacefill(selection='#' + e,
                                            color=self.colors[e])
                else:
                    self.view.add_spacefill(selection='#' + e)
        self._update_repr()

    def custom_colors(self, clr=None):
        """
        Define custom colors for some atoms. Pass a dictionary of the form
        {'Fe':'red', 'Au':'yellow'} to the function.
        To reset the map to default call the method without parameters.
        """
        if clr:
            self.colors = clr
        else:
            self.colors = {}
        self._select_atom()
def interactive_differences_with_probability(
    data,
    beta_time=-0.5,
    beta_cost=-0.8,
    likelihood=False,
    loglikelihood=False,
    correct=False,
    beta_bus=None,
):
    from plotly import graph_objects as go
    from ipywidgets import FloatSlider, HBox, Layout

    likelihood |= bool(loglikelihood)
    choose_car = data.query("choice == 'car'")
    choose_bus = data.query("choice == 'bus'")
    space = np.linspace(-11, 11)
    grid = np.meshgrid(space, space)
    b_cost = FloatSlider(
        value=beta_cost,
        max=2.5,
        min=-2.5,
        step=0.01,
        orientation="vertical",
        description=r"$\beta$ Cost",
    )
    b_time = FloatSlider(
        value=beta_time,
        max=2.5,
        min=-2.5,
        step=0.01,
        orientation="vertical",
        description=r"$\beta$ Time",
    )
    b_bus = FloatSlider(
        value=beta_bus or 0,
        max=2.5,
        min=-2.5,
        step=0.01,
        orientation="vertical",
        description=r"$\beta$ Bus",
    )

    field = 1 / (1 + np.exp(grid[0] * b_time.value + grid[1] * b_cost.value +
                            b_bus.value))
    fig = go.FigureWidget([
        go.Contour(
            name="Probability of Car",
            z=field,
            x=space,
            y=space,
            colorbar=dict(
                thickness=25,
                thicknessmode="pixels",
                len=0.65,
                lenmode="fraction",
                outlinewidth=0,
                yanchor="bottom",
                y=0,
                title="Probability of Car",
                titleside="right",
            ),
            colorscale="bluered_r",
            contours=dict(
                start=0,
                end=1.0,
                size=0.1,
            ),
        ),
        go.Scatter(
            x=choose_bus.timediff,
            y=choose_bus.costdiff,
            mode="markers",
            name="bus",
            marker_line_width=2,
            marker_line_color="white",
            marker_size=10,
            marker_color="red",
        ),
        go.Scatter(
            x=choose_car.timediff,
            y=choose_car.costdiff,
            mode="markers",
            name="car",
            marker_line_width=2,
            marker_line_color="white",
            marker_size=10,
            marker_symbol="square",
            marker_color="blue",
        ),
    ])
    fig.update_xaxes(
        range=[-11, 11],
        showline=True,
    )
    fig.update_yaxes(
        range=[-11, 11],
        showline=True,
    )
    fig.layout.margin = {"b": 5, "t": 5, "l": 5, "r": 5}
    fig.layout.width = 450
    fig.layout.height = 250
    fig.update_layout(
        xaxis_title="Car Time Advantage",
        yaxis_title="Car Cost Advantage",
        legend_title="Chosen",
        font=dict(size=11, ),
    )
    if likelihood:
        fig.update_layout(
            title=dict(
                text="Likelihood = ",
                y=0.98,
                x=0.5,
                xref="paper",
                xanchor="center",
                yanchor="top",
                font_size=11,
            ),
            margin={
                "b": 5,
                "t": 20,
                "l": 5,
                "r": 5
            },
        )

    def refield(*args):
        with fig.batch_update():
            field = 1 / (1 + np.exp(grid[0] * b_time.value +
                                    grid[1] * b_cost.value + b_bus.value))
            fig.data[0].z = field
            if correct or likelihood:
                likely2 = 1 / (
                    1 + np.exp(fig.data[2].x * b_time.value +
                               fig.data[2].y * b_cost.value + b_bus.value))
                likely1 = 1 - (
                    1 /
                    (1 + np.exp(fig.data[1].x * b_time.value +
                                fig.data[1].y * b_cost.value + b_bus.value)))
                if correct:
                    fig.data[2].marker.symbol = np.where(
                        likely2 > 0.5,
                        np.where(likely2 > 0.95, "square-dot", "square"),
                        "x",
                    )
                    fig.data[1].marker.symbol = np.where(
                        likely1 > 0.5,
                        np.where(likely1 > 0.95, "circle-dot", "circle"),
                        "x",
                    )
                if likelihood:
                    fig.data[2].marker.size = np.clip(15 * likely2, 3, 15)
                    fig.data[1].marker.size = np.clip(15 * likely1, 3, 15)
                    if loglikelihood:
                        fig.update_layout(
                            title_text=
                            f"Log Likelihood = {np.log(likely1).sum()+np.log(likely2).sum():.4g}",
                        )
                    else:
                        fig.update_layout(
                            title_text=
                            f"Likelihood = {likely1.prod()*likely2.prod():.4g}",
                        )

    refield()
    b_cost.observe(refield)
    b_time.observe(refield)
    b_bus.observe(refield)
    if beta_bus is None:
        parts = [fig, b_cost, b_time]
    else:
        parts = [fig, b_cost, b_time, b_bus]
    return HBox(parts, layout=Layout(display="flex", align_items="center"))
def interactive_differences_on_field(data, beta_time=-0.5, beta_cost=-0.8):
    from plotly import graph_objects as go
    from ipywidgets import FloatSlider, HBox, Layout

    choose_car = data.query("choice == 'car'")
    choose_bus = data.query("choice == 'bus'")
    space = np.linspace(-11, 11)
    grid = np.meshgrid(space, space)
    b_cost = FloatSlider(
        value=beta_cost,
        max=1.0,
        min=-1.0,
        step=0.05,
        orientation="vertical",
        description=r"$\beta$ Cost",
    )
    b_time = FloatSlider(
        value=beta_time,
        max=1.0,
        min=-1.0,
        step=0.05,
        orientation="vertical",
        description=r"$\beta$ Time",
    )
    field = grid[0] * -b_time.value + grid[1] * -b_cost.value
    fig = go.FigureWidget([
        go.Contour(
            name="Net Utility of Car",
            z=field,
            x=space,
            y=space,
            colorbar=dict(
                thickness=25,
                thicknessmode="pixels",
                len=0.65,
                lenmode="fraction",
                outlinewidth=0,
                yanchor="bottom",
                y=0,
                title="Net Utility of Car",
                titleside="right",
            ),
            colorscale="rdbu",
        ),
        go.Scatter(
            x=choose_bus.timediff,
            y=choose_bus.costdiff,
            mode="markers",
            name="bus",
            marker_line_width=2,
            marker_line_color="white",
            marker_size=10,
            marker_color="red",
        ),
        go.Scatter(
            x=choose_car.timediff,
            y=choose_car.costdiff,
            mode="markers",
            name="car",
            marker_line_width=2,
            marker_line_color="white",
            marker_size=10,
            marker_symbol="square",
            marker_color="blue",
        ),
    ])
    fig.update_xaxes(
        range=[-11, 11],
        showline=True,
    )
    fig.update_yaxes(
        range=[-11, 11],
        showline=True,
    )
    fig.layout.margin = {"b": 5, "t": 5, "l": 5, "r": 5}
    fig.layout.width = 450
    fig.layout.height = 250
    fig.update_layout(
        xaxis_title="Car Time Advantage",
        yaxis_title="Car Cost Advantage",
        legend_title="Chosen",
        font=dict(size=11, ),
    )

    def refield(*args):
        field = grid[0] * -b_time.value + grid[1] * -b_cost.value
        fig.data[0].z = field

    b_cost.observe(refield)
    b_time.observe(refield)
    return HBox([fig, b_cost, b_time],
                layout=Layout(display="flex", align_items="center"))
Beispiel #19
0
l = Label("update every text box every {}".format(s.value))


def update_text(change=None):
    t.value = str(float(s.value)**2)


def push_update_text():
    while True:
        time.sleep(s.value)
        t.value = str(datetime.datetime.now())
        l.value = "update every text box every {}".format(s.value)


s.observe(update_text, names='value')
update_text()
h_box = HBox([l, s])
vbox = VBox([h_box, t])

thread = Thread(target=push_update_text)
thread.daemon = True
thread.start()


@app.route('/')
def index():
    return render_template('example2.html', widget=vbox, widgets=vbox)


if __name__ == "__main__":
Beispiel #20
0
class NGLDisplay:
    """Structure display class

    Provides basic structure/trajectory display
    in the notebook and optional gui which can be used to enhance its
    usability.  It is also possible to extend the functionality of the
    particular instance of the viewer by adding further widgets
    manipulating the structure.
    """
    def __init__(self, atoms, xsize=500, ysize=500):
        import nglview
        import nglview.color

        from ipywidgets import Dropdown, FloatSlider, IntSlider, HBox, VBox
        self.atoms = atoms
        if isinstance(atoms[0], Atoms):
            # Assume this is a trajectory or struct list
            self.view = nglview.show_asetraj(atoms)
            self.frm = IntSlider(value=0, min=0, max=len(atoms) - 1)
            self.frm.observe(self._update_frame)
            self.struct = atoms[0]
        else:
            # Assume this is just a single structure
            self.view = nglview.show_ase(atoms)
            self.struct = atoms
            self.frm = None

        self.colors = {}
        self.view._remote_call('setSize',
                               target='Widget',
                               args=['%dpx' % (xsize, ),
                                     '%dpx' % (ysize, )])
        self.view.add_unitcell()
        self.view.add_spacefill()
        self.view.remove_ball_and_stick()
        self.view.camera = 'orthographic'
        self.view.parameters = {"clipDist": 0}

        self.view.center()

        self.asel = Dropdown(options=['All'] +
                             list(set(self.struct.get_chemical_symbols())),
                             value='All',
                             description='Show')

        self.csel = Dropdown(options=nglview.color.COLOR_SCHEMES,
                             value=' ',
                             description='Color scheme')

        self.rad = FloatSlider(value=0.8,
                               min=0.0,
                               max=1.5,
                               step=0.01,
                               description='Ball size')

        self.asel.observe(self._select_atom)
        self.csel.observe(self._update_repr)
        self.rad.observe(self._update_repr)

        self.view.update_spacefill(radiusType='covalent',
                                   scale=0.8,
                                   color_scheme=self.csel.value,
                                   color_scale='rainbow')

        wdg = [self.asel, self.csel, self.rad]
        if self.frm:
            wdg.append(self.frm)

        self.gui = HBox([self.view, VBox(wdg)])
        # Make useful shortcuts for the user of the class
        self.gui.view = self.view
        self.gui.control_box = self.gui.children[1]
        self.gui.custom_colors = self.custom_colors

    def _update_repr(self, chg=None):
        self.view.update_spacefill(radiusType='covalent',
                                   scale=self.rad.value,
                                   color_scheme=self.csel.value,
                                   color_scale='rainbow')

    def _update_frame(self, chg=None):
        self.view.frame = self.frm.value
        return

    def _select_atom(self, chg=None):
        sel = self.asel.value
        self.view.remove_spacefill()
        for e in set(self.struct.get_chemical_symbols()):
            if (sel == 'All' or e == sel):
                if e in self.colors:
                    self.view.add_spacefill(selection='#' + e,
                                            color=self.colors[e])
                else:
                    self.view.add_spacefill(selection='#' + e)
        self._update_repr()

    def custom_colors(self, clr=None):
        """
        Define custom colors for some atoms. Pass a dictionary of the form
        {'Fe':'red', 'Au':'yellow'} to the function.
        To reset the map to default call the method without parameters.
        """
        if clr:
            self.colors = clr
        else:
            self.colors = {}
        self._select_atom()
def MakeJointSlidersThatPublishOnCallback(plant,
                                          publishing_system,
                                          root_context,
                                          my_callback=None,
                                          lower_limit=-10.,
                                          upper_limit=10.,
                                          resolution=0.01,
                                          length=200,
                                          continuous_update=True,
                                          floating_base=True):
    """
    Creates an ipywidget slider for each joint in the plant.  Unlike the
    JointSliders System, we do not expect this to be used in a Simulator.  It
    simply updates the context and calls Publish directly from the slider
    callback.

    Args:
        plant:        A MultibodyPlant.
        publishing_system: The System whos Publish method will be called.  Can
                           be the entire Diagram, but can also be a subsystem.
        root_context: A mutable root Context of the Diagram containing both the
                      ``plant`` and the ``publishing_system``; we will extract
                      the subcontext's using `GetMyContextFromRoot`.
        my_callback:  An optional additional callback function that will be
                      called once immediately and again whenever the sliders
                      are moved, using ``my_callback(plant_context)``.  This
                      can be useful, e.g. for outputting text that prints the
                      current end-effector Jacobian, or for showing a rendered
                      image from a camera.
        lower_limit:  A scalar or vector of length robot.num_velocities().
                      The lower limit of the slider will be the maximum
                      value of this number and any limit specified in the
                      Joint.
        upper_limit:  A scalar or vector of length robot.num_velocities().
                      The upper limit of the slider will be the minimum
                      value of this number and any limit specified in the
                      Joint.
        resolution:   A scalar or vector of length robot.num_velocities()
                      that specifies the step argument of the FloatSlider.
        length:       The length of the sliders, which will be passed as a
                      string to the CSS width field and can be any valid CSS
                      entry (e.g. 100, 100px).
        continuous_update: The continuous_update field for the FloatSliders.
                      The default ``True`` means that this method will publish/
                      callback as the sliders are dragged.  ``False`` means
                      that the publish/callback will only happen once the user
                      finishes dragging the slider.
        floating_base: If True, then include XYZ/RPY sliders corresponding to
                      the pose of any floating joints.

    Returns:
        A list of the slider widget objects that are created.

    Note: Some publishers (like MeshcatVisualizer) use an initialization event
    to "load" the geometry.  You should call that *before* calling this method
    (e.g. with `meshcat.load()`).
    """
    def _broadcast(x, num):
        x = np.asarray(x)
        assert len(x.shape) <= 1
        return np.array(x) * np.ones(num)

    # Use num_velocities instead of num_positions because we want 6 per
    # floating base, not 7.
    lower_limit = _broadcast(lower_limit, plant.num_velocities())
    upper_limit = _broadcast(upper_limit, plant.num_velocities())
    resolution = _broadcast(resolution, plant.num_velocities())

    publishing_context = publishing_system.GetMyContextFromRoot(root_context)
    plant_context = plant.GetMyContextFromRoot(root_context)
    positions = plant.GetPositions(plant_context)

    # Publish once immediately.
    publishing_system.Publish(publishing_context)
    if my_callback:
        my_callback(plant_context)

    def _slider_callback(change, index, body=None):
        if body:  # Then it's a floating base
            pose = plant.GetFreeBodyPose(plant_context, body)
            vector_pose = np.concatenate(
                (RollPitchYaw(pose.rotation()).vector(), pose.translation()))
            vector_pose[index] = change.new
            plant.SetFreeBodyPose(
                plant_context, body,
                RigidTransform(RollPitchYaw(vector_pose[:3]), vector_pose[3:]))
        else:
            positions[index] = change.new
            plant.SetPositions(plant_context, positions)
        publishing_system.Publish(publishing_context)
        if my_callback:
            my_callback(plant_context)

    slider_widgets = []
    for i in range(plant.num_joints()):
        joint = plant.get_joint(JointIndex(i))
        low = joint.position_lower_limits()
        upp = joint.position_upper_limits()
        for j in range(joint.num_positions()):
            index = joint.position_start() + j
            description = joint.name()
            if joint.num_positions() > 1:
                description += f"[{j}]"
            slider = FloatSlider(value=positions[index],
                                 min=max(low[j], lower_limit[index]),
                                 max=min(upp[j], upper_limit[index]),
                                 step=resolution[index],
                                 continuous_update=continuous_update,
                                 description=description,
                                 style={'description_width': 'initial'},
                                 layout=Layout(width=f"'{length}'"))
            slider.observe(partial(_slider_callback, index=index),
                           names='value')
            display(slider)
            slider_widgets.append(slider)

    if floating_base:
        for bi in plant.GetFloatingBaseBodies():
            body = plant.get_body(bi)
            index = body.floating_velocities_start() - plant.num_positions()
            pose = plant.GetFreeBodyPose(plant_context, body)
            vector_pose = np.concatenate(
                (RollPitchYaw(pose.rotation()).vector(), pose.translation()))
            relative_index = 0
            for dof in ["roll", "pitch", "yaw", "x", "y", "z"]:
                slider = FloatSlider(min=lower_limit[index],
                                     max=upper_limit[index],
                                     value=vector_pose[relative_index],
                                     step=resolution[index],
                                     continuous_update=continuous_update,
                                     description=f"{body.name()}_{dof}",
                                     layout=Layout(width='90%'))
                slider.observe(partial(_slider_callback,
                                       index=relative_index,
                                       body=body),
                               names='value')
                display(slider)
                slider_widgets.append(slider)
                index += 1
                relative_index += 1

    return slider_widgets
Beispiel #22
0
def interact_distributions():
    from ipywidgets import FloatSlider, Label, GridBox, interactive, Layout, VBox, \
                           HBox, Checkbox, IntSlider, Box, Button, widgets
    fx0 = FloatSlider(value=2,
                      description=" ",
                      min=.5,
                      max=4.,
                      step=.2,
                      continuous_update=False,
                      layout=Layout(width='auto', grid_area='vx0'))
    fy0 = FloatSlider(value=3,
                      description=" ",
                      min=.5,
                      max=4.,
                      step=.2,
                      continuous_update=False,
                      layout=Layout(width='auto', grid_area='vy0'))
    fs0 = FloatSlider(value=1,
                      description=" ",
                      min=.1,
                      max=4.,
                      step=.2,
                      continuous_update=False,
                      layout=Layout(width='auto', grid_area='vs0'))
    fd0 = FloatSlider(value=.9,
                      description=" ",
                      min=-2.,
                      max=2.,
                      step=.1,
                      continuous_update=False,
                      layout=Layout(width='auto', grid_area='vd0'))

    fx1 = FloatSlider(value=2,
                      description=" ",
                      min=.5,
                      max=4.,
                      step=.2,
                      continuous_update=False,
                      layout=Layout(width='auto', grid_area='vx1'))
    fy1 = FloatSlider(value=2,
                      description=" ",
                      min=.5,
                      max=4.,
                      step=.2,
                      continuous_update=False,
                      layout=Layout(width='auto', grid_area='vy1'))
    fs1 = FloatSlider(value=1,
                      description=" ",
                      min=.1,
                      max=4.,
                      step=.2,
                      continuous_update=False,
                      layout=Layout(width='auto', grid_area='vs1'))
    fd1 = FloatSlider(value=-.3,
                      description=" ",
                      min=-2.,
                      max=2.,
                      step=.1,
                      continuous_update=False,
                      layout=Layout(width='auto', grid_area='vd1'))
    fdummy = FloatSlider(value=2, description=" ", min=1, max=4, step=1)

    l = lambda s, p, w="auto": Label(s, layout=Layout(width=w, grid_area=p))

    bay = Checkbox(value=False,
                   description='show NATURAL frontiers',
                   disabled=False,
                   indent=False,
                   layout=Layout(width="80%"))

    resample = Button(description="resample data points")

    from IPython.core.display import clear_output

    def resample_onclick(_):
        global do_resample_points
        do_resample_points = True
        tmp = fdummy.value
        fdummy.value = tmp + (1 if tmp < 3 else -1)
        do_resample_points = False

    resample.on_click(resample_onclick)

    w = interactive(display_distributions,
                    x0=fx0,
                    y0=fy0,
                    s0=fs0,
                    d0=fd0,
                    x1=fx1,
                    y1=fy1,
                    s1=fs1,
                    d1=fd1,
                    show_bayesians=bay,
                    dummy=fdummy,
                    continuous_update=False)

    w.children[-1].layout = Layout(width='auto', grid_area='fig')

    controls = Box([bay, resample],
                   layout=Layout(grid_area="ctr",
                                 display="flex-flow",
                                 justify_content="flex-start",
                                 flex_flow="column",
                                 align_items='flex-start'))

    gb = GridBox(children=[
        fx0, fy0, fs0, fd0, fx1, fy1, fs1, fd1,
        l("AMERICAN TRILOBYTE", "h0"),
        l("AFRICAN TRILOBYTE", "h1"),
        l("size", "lx0"),
        l("weight", "ly0"),
        l("spread", "ls0"),
        l("tilt", "ld0"),
        l("size", "lx1"),
        l("weight", "ly1"),
        l("spread", "ls1"),
        l("tilt", "ld1"), controls
    ],
                 layout=Layout(
                     width='100%',
                     grid_template_rows='auto auto auto auto auto auto auto',
                     grid_template_columns='5% 30% 5% 30% 30%',
                     grid_template_areas='''
                "h0 h0 h1 h1 ."
                "lx0 vx0 lx1 vx1 ."
                "ly0 vy0 ly1 vy1 ctr"
                "ls0 vs0 ls1 vs1 ctr"
                "ld0 vd0 ld1 vd1 ctr"
                "fig fig fig fig fig"
                '''))

    def limit_fd0(*args):
        fd0.max = fs0.value + fs0.value * 0.5
        fd0.min = -fs0.value * 0.5

    def limit_fd1(*args):
        fd1.max = fs1.value + fs1.value * 0.5
        fd1.min = -fs1.value * 0.5

    fs0.observe(limit_fd0, "value")
    fd0.observe(limit_fd0, "value")
    fs1.observe(limit_fd1, "value")
    fd1.observe(limit_fd1, "value")

    w.children[0].value = 1
    widget1 = VBox([gb, w.children[-1]])
    display(widget1)
    return fx0, fy0, fs0, fd0, fx1, fy1, fs1, fd1
    def display_focal_distance(self):
        """Display visual controls for setting camera focal distance"""
        x_slider = FloatSlider(description='X', min=0, max=1, value=0.5)
        y_slider = FloatSlider(description='Y', min=0, max=1, value=0.5)
        a_slider = FloatSlider(description='Aperture', min=0, max=1, value=0)
        f_slider = FloatSlider(description='Focus radius',
                               min=0,
                               max=1,
                               value=0.01)
        d_slider = FloatSlider(description='Focus distance',
                               min=0,
                               max=10000,
                               value=0,
                               disabled=True)
        f_button = Button(description='Refresh')

        class Updated:
            """Class object embedding communication with remote server"""
            def __init__(self, client):
                self._client = client
                self._widget_value = None
                self._x = 0.5
                self._y = 0.5
                self._aperture = 0.0
                self._focus_radius = 0.01
                self._focus_distance = 0.0
                self._nb_focus_points = 20

            def _update_camera(self):
                self._focus_distance = 0.0
                for _ in range(self._nb_focus_points):
                    self._focus_distance = self._focus_distance + self._get_focal_distance(
                        (self._x +
                         (random.random() - 0.5) * self._focus_radius,
                         self._y +
                         (random.random() - 0.5) * self._focus_radius))

                self._focus_distance = self._focus_distance / self._nb_focus_points
                params = self._client.BioExplorerPerspectiveCameraParams()
                params.focus_distance = self._focus_distance
                params.aperture_radius = self._aperture
                params.enable_clipping_planes = True
                d_slider.value = self._focus_distance
                self._client.set_camera_params(params)

            def update(self):
                """Update all settings of the camera"""
                self._update_camera()

            def update_focus_radius(self, val_dict) -> None:
                """Update camera focus radius"""
                self._widget_value = val_dict['new']
                self._focus_radius = self._widget_value
                self._update_camera()

            def update_aperture(self, val_dict) -> None:
                """Update camera aperture"""
                self._widget_value = val_dict['new']
                self._aperture = self._widget_value
                self._update_camera()

            def update_x(self, val_dict) -> None:
                """Update camera normalized horizontal focus location"""
                self._widget_value = val_dict['new']
                self._x = self._widget_value
                self._update_camera()

            def update_y(self, val_dict) -> None:
                """Update camera normalized vertical focus location"""
                self._widget_value = val_dict['new']
                self._y = self._widget_value
                self._update_camera()

            def _get_focal_distance(self, coordinates=(0.5, 0.5)):
                """
                Return the focal distance for the specified normalized coordinates in the image

                :param list coordinates: Coordinates in the image
                :return: The focal distance
                :rtype: float
                """
                target = self._client.inspect(array=coordinates)['position']
                origin = self._client.camera.position.data
                vector = [0, 0, 0]
                for k in range(3):
                    vector[k] = float(target[k]) - float(origin[k])
                return math.sqrt(vector[0] * vector[0] +
                                 vector[1] * vector[1] + vector[2] * vector[2])

        update_class = Updated(self._client)

        def update_x(value):
            update_class.update_x(value)

        def update_y(value):
            update_class.update_y(value)

        def update_aperture(value):
            update_class.update_aperture(value)

        def update_focus_radius(value):
            update_class.update_focus_radius(value)

        def update_button(_):
            update_class.update()

        x_slider.observe(update_x, 'value')
        y_slider.observe(update_y, 'value')
        a_slider.observe(update_aperture, 'value')
        f_slider.observe(update_focus_radius, 'value')
        f_button.on_click(update_button)

        position_box = VBox([x_slider, y_slider, f_button])
        parameters_box = VBox([a_slider, f_slider, d_slider])
        horizontal_box = HBox([position_box, parameters_box],
                              layout=DEFAULT_GRID_LAYOUT)
        display(horizontal_box)
Beispiel #24
0
fig.canvas.header_visible = False
fig.canvas.layout.min_height = '400px'
plt.title('Plotting of linear graph'.format(slider.value))

x = lin['campaign_id']
y = lin['campaign_count']

lines = plt.plot(x,y)

def update_lines(change):
    plt.title('Plotting of linear graph'.format(change.new))
    lines[0].set_data(x, y)
    fig.canvas.draw()
    fig.canvas.flush_events()

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

AppLayout(
    center=fig.canvas,
    footer=slider,
    pane_heights=[0, 6, 1]
)


# In[ ]:





# In[31]:
def draw_roaming_ui():
    global iter_slider, reset_button, color_it_button, juliabrot_button, canvases
    global drawing, uly_select, ulx_select, color_list, picker1, picker2, bump_ud_slider, hue_slider, sat_slider, val_slider
    global lry_select, lrx_select, color_it, modulo_slider, picker3, bump_lr_slider, zoom_slider, save_button

    # This establishes the size of the preview gui
    drawing = False
    color_it = True
    uly_select = 0
    ulx_select = 0
    lry_select = jgrid.settings.sizeY
    lrx_select = jgrid.settings.sizeX
    canvases = MultiCanvas(3,
                           width=jgrid.settings.sizeX * 2.5,
                           height=jgrid.settings.sizeY + 75)
    canvases[drawing_layer].font = '25px serif'
    canvases[drawing_layer].fill_style = '#aaaaaa'
    canvases[drawing_layer].line_width = 3
    canvases[interaction_layer].font = '35px serif'
    canvases[interaction_layer].fill_style = '#eee800'
    canvases[interaction_layer].stroke_style = '#ffffff'
    canvases[interaction_layer].line_width = 3
    iter_slider = FloatLogSlider(description='Iterations:',
                                 base=10,
                                 value=jgrid.settings.max_iterations,
                                 min=1,
                                 max=7,
                                 step=.01,
                                 continuous_update=False)
    iter_slider.observe(handler=iter_slider_handler, names='value')
    max_lr_bump = jgrid.settings.sizeX
    max_ud_bump = jgrid.settings.sizeY
    bump_ud_slider = IntSlider(description='Bump UD pix:',
                               value=1,
                               min=0,
                               max=max_ud_bump,
                               step=1,
                               continuous_update=False)
    bump_lr_slider = IntSlider(description='Bump LR pix:',
                               value=1,
                               min=0,
                               max=max_lr_bump,
                               step=1,
                               continuous_update=False)
    zoom_slider = FloatSlider(description='Zoom:',
                              value=2.0,
                              min=0.0,
                              max=1000.0,
                              step=.001,
                              continuous_update=False)
    #zoom_slider.observe(handler=zoom_button_handler, names='value')
    hue_slider = FloatSlider(description='Hue :',
                             value=jgrid.settings.hue,
                             min=0.0,
                             max=1.0,
                             step=.001,
                             continuous_update=False)
    sat_slider = FloatSlider(description='Sat:',
                             value=jgrid.settings.sat,
                             min=0.0,
                             max=1.0,
                             step=.01,
                             continuous_update=False)
    val_slider = FloatSlider(description='Val:',
                             value=jgrid.settings.val,
                             min=0.0,
                             max=1.0,
                             step=.02,
                             continuous_update=False)
    hue_slider.observe(handler=hue_slider_handler, names='value')
    sat_slider.observe(handler=sat_slider_handler, names='value')
    val_slider.observe(handler=val_slider_handler, names='value')
    modulo_slider = IntSlider(description='Modulo:',
                              value=jgrid.settings.modulo,
                              min=1,
                              max=1000000,
                              step=1,
                              continuous_update=False)
    modulo_slider.observe(handler=modulo_slider_handler, names='value')
    canvases[interaction_layer].on_mouse_down(on_mouse_down)
    canvases[interaction_layer].on_mouse_move(on_mouse_move)
    reset_button = Button(description='Zoom',
                          disabled=False,
                          button_style='',
                          tooltip='Click to use zoom slider setting for zoom',
                          icon='')
    reset_button.on_click(zoom_button_handler)
    save_button = Button(description='Save',
                         disabled=False,
                         button_style='',
                         tooltip='Click to save as JSON settings file',
                         icon='')
    save_button.on_click(save_button_handler)
    color_it_button = Button(description='Color/BW',
                             disabled=False,
                             button_style='',
                             tooltip='Click for BW or Color',
                             icon='')
    color_it_button.on_click(color_button_handler)
    juliabrot_button = Button(description='JM Mode',
                              disabled=False,
                              button_style='',
                              tooltip='Click for Julia or Mandelbrot',
                              icon='')
    juliabrot_button.on_click(juliabrot_button_handler)
    undo_button = Button(description='Undo',
                         disabled=False,
                         button_style='',
                         tooltip='Click to revert to last view',
                         icon='')
    undo_button.on_click(undo_button_handler)
    bleft_button = Button(description='Bump L',
                          disabled=False,
                          button_style='',
                          tooltip='Click to nudge left num bump LR pixels',
                          icon='')
    bleft_button.on_click(bleft_button_handler)
    bright_button = Button(description='Bump R',
                           disabled=False,
                           button_style='',
                           tooltip='Click to nudge right num bump LR pixels',
                           icon='')
    bright_button.on_click(bright_button_handler)
    bup_button = Button(description='Bump U',
                        disabled=False,
                        button_style='',
                        tooltip='Click to nudge up num bump UD pixels',
                        icon='')
    bup_button.on_click(bup_button_handler)
    bdown_button = Button(description='Bump D',
                          disabled=False,
                          button_style='',
                          tooltip='Click to nudge down bump UD pixels',
                          icon='')
    bdown_button.on_click(bdown_button_handler)
    picker1 = ColorPicker(description='M Color:', value=jgrid.settings.m_color)
    #picker2 = ColorPicker(description='Color 1:', value='#fff800')
    #picker3 = ColorPicker(description='Color 2:', value='#fff800')
    picker1.observe(color_picker1_handler, names='value')
    #picker2.observe(color_picker2_handler, names='value')
    #picker3.observe(color_picker3_handler, names='value')
    color_list = Dropdown(disabled=False,
                          options=[('Rainbow', 1), ('Classic', 2), ('Log', 3),
                                   ('RGB Max Iter', 4), ('Rainbow 2', 5)],
                          value=jgrid.settings.color_mode,
                          description='Color Mode:',
                          tooltip='Select built-in coloring options')
    color_list.observe(color_select_handler, names='value')
    draw_fractal(canvases, jgrid.tile_list)
    display_info(canvases, jgrid)
    return AppLayout(center=canvases,
                     header=HBox((iter_slider, bump_ud_slider, bump_lr_slider,
                                  zoom_slider)),
                     right_sidebar=VBox(
                         (picker1, color_list, hue_slider, sat_slider,
                          val_slider, modulo_slider)),
                     footer=HBox(
                         (bleft_button, bright_button, bup_button,
                          bdown_button, color_it_button, juliabrot_button,
                          reset_button, undo_button, save_button)))
def _get_value_widget(obj, index=None):
    wdict = {}
    widget_bounds = _interactive_slider_bounds(obj, index=index)
    thismin = FloatText(
        value=widget_bounds['min'],
        description='min',
        layout=Layout(flex='0 1 auto', width='auto'),
    )
    thismax = FloatText(
        value=widget_bounds['max'],
        description='max',
        layout=Layout(flex='0 1 auto', width='auto'),
    )
    current_value = obj.value if index is None else obj.value[index]
    if index is None:
        current_name = obj.name
    else:
        current_name = '{}'.format(index)
    widget = FloatSlider(value=current_value,
                         min=thismin.value,
                         max=thismax.value,
                         step=widget_bounds['step'],
                         description=current_name,
                         layout=Layout(flex='1 1 auto', width='auto'))

    def on_min_change(change):
        if widget.max > change['new']:
            widget.min = change['new']
            widget.step = np.abs(widget.max - widget.min) * 0.001

    def on_max_change(change):
        if widget.min < change['new']:
            widget.max = change['new']
            widget.step = np.abs(widget.max - widget.min) * 0.001

    thismin.observe(on_min_change, names='value')
    thismax.observe(on_max_change, names='value')
    # We store the link in the widget so that they are not deleted by the
    # garbage collector
    thismin._link = dlink((obj, "bmin"), (thismin, "value"))
    thismax._link = dlink((obj, "bmax"), (thismax, "value"))
    if index is not None:  # value is tuple, expanding

        def _interactive_tuple_update(value):
            """Callback function for the widgets, to update the value
            """
            obj.value = obj.value[:index] + (value['new'],) +\
                obj.value[index + 1:]

        widget.observe(_interactive_tuple_update, names='value')
    else:
        link((obj, "value"), (widget, "value"))

    container = HBox((thismin, widget, thismax))
    wdict["value"] = widget
    wdict["min"] = thismin
    wdict["max"] = thismax
    return {
        "widget": container,
        "wdict": wdict,
    }
Beispiel #27
0
class NasaGibsViewer(PanelObject):
  def __init__(self,ptype='time',*args,**kwargs):
    self.title = 'NASA GIBS Image Viewer'
    PanelObject.__init__(self,*args, **kwargs)
    self.url = 'https://gibs.earthdata.nasa.gov/wmts/epsg4326/best/wmts.cgi'  
    
    self.plat = 24.42
    self.plon = 54.43
    self.height = 1.0
    self.width = 1.0



  def getCP(self):
    self.setLabel()
    
    self.imgDate = datetime.now()
    
    self.selectVar ='MODIS_Terra_SurfaceReflectance_Bands143'
   
    self.dateSW = DatePicker(description='Date',
                              layout=Layout(width='220px'),
                              value = self.imgDate,
                              disabled=False)
    
    self.vardict = {'TerraRGB':'MODIS_Terra_SurfaceReflectance_Bands143',
                    'AquaRGB' :'MODIS_Aqua_SurfaceReflectance_Bands143',
                    'AquaLST Day':'MODIS_Aqua_Land_Surface_Temp_Day'}
 
    self.varSW   = Dropdown(options=['TerraRGB','AquaRGB','AquaLST Day'],
                            value='TerraRGB',
                            layout=Layout(width='220px'),
                            description='Var:',
                            disabled=False
                            )
  
    self.latSW = Text(description='Lat:',disabled=False,value='24.42',layout=Layout(width='220px'))

    self.lonSW = Text(description='Lon:',disabled=False,value='54.43',layout=Layout(width='220px')) 
                                  
    self.plotPB =Button(description='Plot',disabled=False,layout={'width':'auto','border':'3px outset'})

    self.latRS =     FloatSlider( value=5,
                                      min=2.0,
                                      max=15,
                                      step=0.2,
                                      description='Width',
                                      disabled=False,
                                      continuous_update=False,
                                      orientation='horizontal',
                                      readout=True,
                                      readout_format='.1f',
                                      )
    
    self.lonRS    =  FloatSlider( value=5.0,
                                      min=2.0,
                                      max=15.0,
                                      step=0.2,
                                      description='Height:',
                                      disabled=False,
                                      continuous_update=False,
                                      orientation='horizontal',
                                      readout=True,
                                      readout_format='.1f'
                                      )    
    self.inpUSR.children+= (HBox([
                                  VBox([self.plotPB]),
                                  VBox([self.dateSW,self.latSW,self.lonSW]),
                                  VBox([self.latRS,self.lonRS,self.varSW ])
                                  
                                 ],
                                 layout={'overflow':'visible'}
                                ),)
    
    
    self.dateSW.observe(self.dateSWCB)
    self.varSW.observe(self.varSWCB,names='value')
    self.latSW.observe(self.latSWCB,names='value')
    self.lonSW.observe(self.lonSWCB,names='value')
    self.latRS.observe(self.latRSCB,names='value')
    self.lonRS.observe(self.lonRSCB,names='value')
    self.plotPB.on_click(self.plotGIBS)
    return self.cp

  def dateSWCB(self,change):
    if change['type'] == 'change':
      self.imgDate = self.dateSW.value

  def varSWCB(self,b):
    self.selectVar = self.vardict[self.varSW.value]
  
  def latSWCB(self,change):
      self.plat = float(self.latSW.value)
      
  def lonSWCB(self,change):
      self.plon = float(self.lonSW.value)

  def latRSCB(self,change):
      self.height = self.latRS.value*0.5
      
  def lonRSCB(self,change):
      self.width = self.lonRS.value*0.5

       
 
  def plotGIBS(self,b):
    self.lat1 = self.plat - self.height
    self.lat2 = self.plat + self.height
    self.lon1 = self.plon - self.width
    self.lon2 = self.plon + self.width
    with self.out_cp:
      plt.ioff()
      layer = self.selectVar 
      
      date_str = '{}-{}-{}'.format(self.imgDate.strftime('%Y'),
                                   self.imgDate.strftime('%m'),
                                   self.imgDate.strftime('%d') 
                                   )
      print(layer,date_str)
      fig = plt.figure(figsize=(8, 8))
      ax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())
      ax.add_wmts(self.url, layer,wmts_kwargs={'time': date_str})
      self.out_cp.clear_output()
      ax.set_extent([self.lon1, self.lon2, self.lat1, self.lat2], crs=ccrs.PlateCarree())
      ax.coastlines(resolution='50m', color='yellow')
      plt.plot(self.plon, self.plat, marker='o', color='red', markersize=15,
         alpha=1.0)
      plt.show()
Beispiel #28
0
    def _tensor_folder(self):
        alo = Layout(width='70px')
        rlo = Layout(width='220px')
        scale =  FloatSlider(max=10.0, step=0.001, readout=True, value=1.0)
        xs = [Text(layout=alo,disabled=True),
              Text(layout=alo,disabled=True),
              Text(layout=alo,disabled=True)]
        ys = [Text(layout=alo,disabled=True),
              Text(layout=alo,disabled=True),
              Text(layout=alo,disabled=True)]
        zs = [Text(layout=alo,disabled=True),
              Text(layout=alo,disabled=True),
              Text(layout=alo,disabled=True)]
        cs = [Text(layout=alo,disabled=True),
              Text(layout=alo,disabled=True),
              Text(layout=alo,disabled=True)]
        cidx = HBox([Text(disabled=True,description='Atom Index',layout=rlo)])
        xbox = HBox(xs, layout=rlo)
        ybox = HBox(ys, layout=rlo)
        zbox = HBox(zs, layout=rlo)
        cbox = HBox(cs, layout=rlo)
        tens = Button(description=' Tensor', icon='bank')
        tensor_cont = VBox([xbox,ybox,zbox])
        tensorIndex = Dropdown(options=[0],value=0,description='Tensor')
#        sceneIndex = Dropdown(options=[0],value=0,description='Scene')
        ten_label = Label(value="Change selected tensor:")
        sel_label = Label(value="Selected tensor in gray frame")
        cod_label = Label(value="Center of selected tensor: (x,y,z)")
        tensor = []
        self.coords = []

        def _changeTensor(tensor, tdx):
            carts = ['x','y','z']
            for i,bra in enumerate(carts):
                for j,ket in enumerate(carts):
                    tensor_cont.children[i].children[j].disabled=False
                    tensor_cont.children[i].children[j].value = \
                                            str(tensor[0][tdx][bra+ket])
                    tensor_cont.children[i].children[j].disabled=True
            adx = tensor[0][tdx]['atom']
            cidx.children[0].value = str(adx)
            cbox.children[0].value = str(self.coords[0][int(adx)])
            cbox.children[1].value = str(self.coords[1][int(adx)])
            cbox.children[2].value = str(self.coords[2][int(adx)])
#            scale.value = tensor[0][tdx]['scale']

        def _tens(c):
            for scn in self.active(): scn.tens = not scn.tens
            self.coords = self._filter_coords()
#            sceneIndex.options = [x for x in range(len(self.active()))]
#            sceneIndex.value = sceneIndex.options[0]
            tensor = self.active()[0].tensor_d
            tensorIndex.options = [x for x in range(len(tensor[0]))]
            tensorIndex.value = tensorIndex.options[0]
            tdx = tensorIndex.value
            _changeTensor(tensor, tdx)

        def _scale(c):
            for scn in self.active(): scn.scale = c.new
#            tdx = tensorIndex.value
#            tensor = self.active()[0].tensor_d
#            tensor[0][tdx]['scale'] = c.new

        def _idx(c):
            for scn in self.active(): scn.tidx = c.new
            tensor = self.active()[0].tensor_d
            tdx = c.new
            _changeTensor(tensor, tdx)

#        def _sdx(c):
#            tensor = self.active()[sceneIndex.value].tensor_d
#            tensorIndex.options = [x for x in range(len(tensor[0]))]
#            tensorIndex.value = tensorIndex.options[0]
#            tdx = tensorIndex.value
#            _changeTensor(tensor, tdx)

        tens.on_click(_tens)
        scale.observe(_scale, names='value')
        tensorIndex.observe(_idx, names='value')
#        sceneIndex.observe(_sdx, names='value')
        content = _ListDict([
                ('scale', scale),
                ('ten', ten_label),
#               ('sdx', sceneIndex),
                ('tdx', tensorIndex),
                ('tensor', tensor_cont),
                ('sel', sel_label),
                ('cidx', cidx),
                ('center', cod_label),
                ('coord', cbox)])
        return Folder(tens, content)
Beispiel #29
0
class Dashboard(VBox):
    """
    Build the dashboard for Jupyter widgets. Requires running
    in a notebook/jupyterlab.
    """
    def __init__(self, net, width="95%", height="550px", play_rate=0.5):
        self._ignore_layer_updates = False
        self.player = _Player(self, play_rate)
        self.player.start()
        self.net = net
        r = random.randint(1, 1000000)
        self.class_id = "picture-dashboard-%s-%s" % (self.net.name, r)
        self._width = width
        self._height = height
        ## Global widgets:
        style = {"description_width": "initial"}
        self.feature_columns = IntText(description="Detail columns:",
                                       value=self.net.config["dashboard.features.columns"],
                                       min=0,
                                       max=1024,
                                       style=style)
        self.feature_scale = FloatText(description="Detail scale:",
                                       value=self.net.config["dashboard.features.scale"],
                                       min=0.1,
                                       max=10,
                                       style=style)
        self.feature_columns.observe(self.regenerate, names='value')
        self.feature_scale.observe(self.regenerate, names='value')
        ## Hack to center SVG as justify-content is broken:
        self.net_svg = HTML(value="""<p style="text-align:center">%s</p>""" % ("",), layout=Layout(
            width=self._width, overflow_x='auto', overflow_y="auto",
            justify_content="center"))
        # Make controls first:
        self.output = Output()
        controls = self.make_controls()
        config = self.make_config()
        super().__init__([config, controls, self.net_svg, self.output])

    def propagate(self, inputs):
        """
        Propagate inputs through the dashboard view of the network.
        """
        if dynamic_pictures_check():
            return self.net.propagate(inputs, class_id=self.class_id, update_pictures=True)
        else:
            self.regenerate(inputs=input)

    def goto(self, position):
        if len(self.net.dataset.inputs) == 0 or len(self.net.dataset.targets) == 0:
            return
        if self.control_select.value == "Train":
            length = len(self.net.dataset.train_inputs)
        elif self.control_select.value == "Test":
            length = len(self.net.dataset.test_inputs)
        #### Position it:
        if position == "begin":
            self.control_slider.value = 0
        elif position == "end":
            self.control_slider.value = length - 1
        elif position == "prev":
            if self.control_slider.value - 1 < 0:
                self.control_slider.value = length - 1 # wrap around
            else:
                self.control_slider.value = max(self.control_slider.value - 1, 0)
        elif position == "next":
            if self.control_slider.value + 1 > length - 1:
                self.control_slider.value = 0 # wrap around
            else:
                self.control_slider.value = min(self.control_slider.value + 1, length - 1)
        self.position_text.value = self.control_slider.value


    def change_select(self, change=None):
        """
        """
        self.update_control_slider(change)
        self.regenerate()

    def update_control_slider(self, change=None):
        self.net.config["dashboard.dataset"] = self.control_select.value
        if len(self.net.dataset.inputs) == 0 or len(self.net.dataset.targets) == 0:
            self.total_text.value = "of 0"
            self.control_slider.value = 0
            self.position_text.value = 0
            self.control_slider.disabled = True
            self.position_text.disabled = True
            for child in self.control_buttons.children:
                if not hasattr(child, "icon") or child.icon != "refresh":
                    child.disabled = True
            return
        if self.control_select.value == "Test":
            self.total_text.value = "of %s" % len(self.net.dataset.test_inputs)
            minmax = (0, max(len(self.net.dataset.test_inputs) - 1, 0))
            if minmax[0] <= self.control_slider.value <= minmax[1]:
                pass # ok
            else:
                self.control_slider.value = 0
            self.control_slider.min = minmax[0]
            self.control_slider.max = minmax[1]
            if len(self.net.dataset.test_inputs) == 0:
                disabled = True
            else:
                disabled = False
        elif self.control_select.value == "Train":
            self.total_text.value = "of %s" % len(self.net.dataset.train_inputs)
            minmax = (0, max(len(self.net.dataset.train_inputs) - 1, 0))
            if minmax[0] <= self.control_slider.value <= minmax[1]:
                pass # ok
            else:
                self.control_slider.value = 0
            self.control_slider.min = minmax[0]
            self.control_slider.max = minmax[1]
            if len(self.net.dataset.train_inputs) == 0:
                disabled = True
            else:
                disabled = False
        self.control_slider.disabled = disabled
        self.position_text.disbaled = disabled
        self.position_text.value = self.control_slider.value
        for child in self.control_buttons.children:
            if not hasattr(child, "icon") or child.icon != "refresh":
                child.disabled = disabled

    def update_zoom_slider(self, change):
        if change["name"] == "value":
            self.net.config["svg_scale"] = self.zoom_slider.value
            self.regenerate()

    def update_position_text(self, change):
        # {'name': 'value', 'old': 2, 'new': 3, 'owner': IntText(value=3, layout=Layout(width='100%')), 'type': 'change'}
        self.control_slider.value = change["new"]

    def get_current_input(self):
        if self.control_select.value == "Train" and len(self.net.dataset.train_targets) > 0:
            return self.net.dataset.train_inputs[self.control_slider.value]
        elif self.control_select.value == "Test" and len(self.net.dataset.test_targets) > 0:
            return self.net.dataset.test_inputs[self.control_slider.value]

    def get_current_targets(self):
        if self.control_select.value == "Train" and len(self.net.dataset.train_targets) > 0:
            return self.net.dataset.train_targets[self.control_slider.value]
        elif self.control_select.value == "Test" and len(self.net.dataset.test_targets) > 0:
            return self.net.dataset.test_targets[self.control_slider.value]

    def update_slider_control(self, change):
        if len(self.net.dataset.inputs) == 0 or len(self.net.dataset.targets) == 0:
            self.total_text.value = "of 0"
            return
        if change["name"] == "value":
            self.position_text.value = self.control_slider.value
            if self.control_select.value == "Train" and len(self.net.dataset.train_targets) > 0:
                self.total_text.value = "of %s" % len(self.net.dataset.train_inputs)
                if self.net.model is None:
                    return
                if not dynamic_pictures_check():
                    self.regenerate(inputs=self.net.dataset.train_inputs[self.control_slider.value],
                                    targets=self.net.dataset.train_targets[self.control_slider.value])
                    return
                output = self.net.propagate(self.net.dataset.train_inputs[self.control_slider.value],
                                            class_id=self.class_id, update_pictures=True)
                if self.feature_bank.value in self.net.layer_dict.keys():
                    self.net.propagate_to_features(self.feature_bank.value, self.net.dataset.train_inputs[self.control_slider.value],
                                                   cols=self.feature_columns.value, scale=self.feature_scale.value, html=False)
                if self.net.config["show_targets"]:
                    if len(self.net.output_bank_order) == 1: ## FIXME: use minmax of output bank
                        self.net.display_component([self.net.dataset.train_targets[self.control_slider.value]],
                                                   "targets",
                                                   class_id=self.class_id,
                                                   minmax=(-1, 1))
                    else:
                        self.net.display_component(self.net.dataset.train_targets[self.control_slider.value],
                                                   "targets",
                                                   class_id=self.class_id,
                                                   minmax=(-1, 1))
                if self.net.config["show_errors"]: ## minmax is error
                    if len(self.net.output_bank_order) == 1:
                        errors = np.array(output) - np.array(self.net.dataset.train_targets[self.control_slider.value])
                        self.net.display_component([errors.tolist()],
                                                   "errors",
                                                   class_id=self.class_id,
                                                   minmax=(-1, 1))
                    else:
                        errors = []
                        for bank in range(len(self.net.output_bank_order)):
                            errors.append( np.array(output[bank]) - np.array(self.net.dataset.train_targets[self.control_slider.value][bank]))
                        self.net.display_component(errors, "errors",  class_id=self.class_id, minmax=(-1, 1))
            elif self.control_select.value == "Test" and len(self.net.dataset.test_targets) > 0:
                self.total_text.value = "of %s" % len(self.net.dataset.test_inputs)
                if self.net.model is None:
                    return
                if not dynamic_pictures_check():
                    self.regenerate(inputs=self.net.dataset.test_inputs[self.control_slider.value],
                                    targets=self.net.dataset.test_targets[self.control_slider.value])
                    return
                output = self.net.propagate(self.net.dataset.test_inputs[self.control_slider.value],
                                            class_id=self.class_id, update_pictures=True)
                if self.feature_bank.value in self.net.layer_dict.keys():
                    self.net.propagate_to_features(self.feature_bank.value, self.net.dataset.test_inputs[self.control_slider.value],
                                               cols=self.feature_columns.value, scale=self.feature_scale.value, html=False)
                if self.net.config["show_targets"]: ## FIXME: use minmax of output bank
                    self.net.display_component([self.net.dataset.test_targets[self.control_slider.value]],
                                               "targets",
                                               class_id=self.class_id,
                                               minmax=(-1, 1))
                if self.net.config["show_errors"]: ## minmax is error
                    if len(self.net.output_bank_order) == 1:
                        errors = np.array(output) - np.array(self.net.dataset.test_targets[self.control_slider.value])
                        self.net.display_component([errors.tolist()],
                                                   "errors",
                                                   class_id=self.class_id,
                                                   minmax=(-1, 1))
                    else:
                        errors = []
                        for bank in range(len(self.net.output_bank_order)):
                            errors.append( np.array(output[bank]) - np.array(self.net.dataset.test_targets[self.control_slider.value][bank]))
                        self.net.display_component(errors, "errors", class_id=self.class_id, minmax=(-1, 1))

    def toggle_play(self, button):
        ## toggle
        if self.button_play.description == "Play":
            self.button_play.description = "Stop"
            self.button_play.icon = "pause"
            self.player.resume()
        else:
            self.button_play.description = "Play"
            self.button_play.icon = "play"
            self.player.pause()

    def prop_one(self, button=None):
        self.update_slider_control({"name": "value"})

    def regenerate(self, button=None, inputs=None, targets=None):
        ## Protection when deleting object on shutdown:
        if isinstance(button, dict) and 'new' in button and button['new'] is None:
            return
        ## Update the config:
        self.net.config["dashboard.features.bank"] = self.feature_bank.value
        self.net.config["dashboard.features.columns"] = self.feature_columns.value
        self.net.config["dashboard.features.scale"] = self.feature_scale.value
        inputs = inputs if inputs is not None else self.get_current_input()
        targets = targets if targets is not None else self.get_current_targets()
        features = None
        if self.feature_bank.value in self.net.layer_dict.keys() and inputs is not None:
            if self.net.model is not None:
                features = self.net.propagate_to_features(self.feature_bank.value, inputs,
                                                          cols=self.feature_columns.value,
                                                          scale=self.feature_scale.value, display=False)
        svg = """<p style="text-align:center">%s</p>""" % (self.net.to_svg(
            inputs=inputs,
            targets=targets,
            class_id=self.class_id,
            highlights={self.feature_bank.value: {
                "border_color": "orange",
                "border_width": 30,
            }}))
        if inputs is not None and features is not None:
            html_horizontal = """
<table align="center" style="width: 100%%;">
 <tr>
  <td valign="top" style="width: 50%%;">%s</td>
  <td valign="top" align="center" style="width: 50%%;"><p style="text-align:center"><b>%s</b></p>%s</td>
</tr>
</table>"""
            html_vertical = """
<table align="center" style="width: 100%%;">
 <tr>
  <td valign="top">%s</td>
</tr>
<tr>
  <td valign="top" align="center"><p style="text-align:center"><b>%s</b></p>%s</td>
</tr>
</table>"""
            self.net_svg.value = (html_vertical if self.net.config["svg_rotate"] else html_horizontal) % (
                svg, "%s details" % self.feature_bank.value, features)
        else:
            self.net_svg.value = svg

    def make_colormap_image(self, colormap_name):
        from .layers import Layer
        if not colormap_name:
            colormap_name = get_colormap()
        layer = Layer("Colormap", 100)
        minmax = layer.get_act_minmax()
        image = layer.make_image(np.arange(minmax[0], minmax[1], .01),
                                 colormap_name,
                                 {"pixels_per_unit": 1,
                                  "svg_rotate": self.net.config["svg_rotate"]}).resize((300, 25))
        return image

    def set_attr(self, obj, attr, value):
        if value not in [{}, None]: ## value is None when shutting down
            if isinstance(value, dict):
                value = value["value"]
            if isinstance(obj, dict):
                obj[attr] = value
            else:
                setattr(obj, attr, value)
            ## was crashing on Widgets.__del__, if get_ipython() no longer existed
            self.regenerate()

    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 move_step(self, direction):
        """
        Move the layer stepper up/down through network
        """
        options = [""] + [layer.name for layer in self.net.layers]
        index = options.index(self.feature_bank.value)
        if direction == "up":
            new_index = (index + 1) % len(options)
        else: ## down
            new_index = (index - 1) % len(options)
        self.feature_bank.value = options[new_index]
        self.regenerate()

    def make_config(self):
        layout = Layout()
        style = {"description_width": "initial"}
        checkbox1 = Checkbox(description="Show Targets", value=self.net.config["show_targets"],
                             layout=layout, style=style)
        checkbox1.observe(lambda change: self.set_attr(self.net.config, "show_targets", change["new"]), names='value')
        checkbox2 = Checkbox(description="Errors", value=self.net.config["show_errors"],
                             layout=layout, style=style)
        checkbox2.observe(lambda change: self.set_attr(self.net.config, "show_errors", change["new"]), names='value')

        hspace = IntText(value=self.net.config["hspace"], description="Horizontal space between banks:",
                         style=style, layout=layout)
        hspace.observe(lambda change: self.set_attr(self.net.config, "hspace", change["new"]), names='value')
        vspace = IntText(value=self.net.config["vspace"], description="Vertical space between layers:",
                         style=style, layout=layout)
        vspace.observe(lambda change: self.set_attr(self.net.config, "vspace", change["new"]), names='value')
        self.feature_bank = Select(description="Details:", value=self.net.config["dashboard.features.bank"],
                              options=[""] + [layer.name for layer in self.net.layers],
                              rows=1)
        self.feature_bank.observe(self.regenerate, names='value')
        self.control_select = Select(
            options=['Test', 'Train'],
            value=self.net.config["dashboard.dataset"],
            description='Dataset:',
            rows=1
        )
        self.control_select.observe(self.change_select, names='value')
        column1 = [self.control_select,
                   self.zoom_slider,
                   hspace,
                   vspace,
                   HBox([checkbox1, checkbox2]),
                   self.feature_bank,
                   self.feature_columns,
                   self.feature_scale
        ]
        ## Make layer selectable, and update-able:
        column2 = []
        layer = self.net.layers[-1]
        self.layer_select = Select(description="Layer:", value=layer.name,
                                   options=[layer.name for layer in
                                            self.net.layers],
                                   rows=1)
        self.layer_select.observe(self.update_layer_selection, names='value')
        column2.append(self.layer_select)
        self.layer_visible_checkbox = Checkbox(description="Visible", value=layer.visible, layout=layout)
        self.layer_visible_checkbox.observe(self.update_layer, names='value')
        column2.append(self.layer_visible_checkbox)
        self.layer_colormap = Select(description="Colormap:",
                                     options=[""] + AVAILABLE_COLORMAPS,
                                     value=layer.colormap if layer.colormap is not None else "", layout=layout, rows=1)
        self.layer_colormap_image = HTML(value="""<img src="%s"/>""" % self.net._image_to_uri(self.make_colormap_image(layer.colormap)))
        self.layer_colormap.observe(self.update_layer, names='value')
        column2.append(self.layer_colormap)
        column2.append(self.layer_colormap_image)
        ## get dynamic minmax; if you change it it will set it in layer as override:
        minmax = layer.get_act_minmax()
        self.layer_mindim = FloatText(description="Leftmost color maps to:", value=minmax[0], style=style)
        self.layer_maxdim = FloatText(description="Rightmost color maps to:", value=minmax[1], style=style)
        self.layer_mindim.observe(self.update_layer, names='value')
        self.layer_maxdim.observe(self.update_layer, names='value')
        column2.append(self.layer_mindim)
        column2.append(self.layer_maxdim)
        output_shape = layer.get_output_shape()
        self.layer_feature = IntText(value=layer.feature, description="Feature to show:", style=style)
        self.svg_rotate = Checkbox(description="Rotate", value=layer.visible, layout=layout)
        self.layer_feature.observe(self.update_layer, names='value')
        column2.append(self.layer_feature)
        self.svg_rotate = Checkbox(description="Rotate network",
                                   value=self.net.config["svg_rotate"],
                                   style={"description_width": 'initial'},
                                   layout=Layout(width="52%"))
        self.svg_rotate.observe(lambda change: self.set_attr(self.net.config, "svg_rotate", change["new"]), names='value')
        self.save_config_button = Button(icon="save", layout=Layout(width="10%"))
        self.save_config_button.on_click(self.save_config)
        column2.append(HBox([self.svg_rotate, self.save_config_button]))
        config_children = HBox([VBox(column1, layout=Layout(width="100%")),
                                VBox(column2, layout=Layout(width="100%"))])
        accordion = Accordion(children=[config_children])
        accordion.set_title(0, self.net.name)
        accordion.selected_index = None
        return accordion

    def save_config(self, widget=None):
        self.net.save_config()

    def update_layer(self, change):
        """
        Update the layer object, and redisplay.
        """
        if self._ignore_layer_updates:
            return
        ## The rest indicates a change to a display variable.
        ## We need to save the value in the layer, and regenerate
        ## the display.
        # Get the layer:
        layer = self.net[self.layer_select.value]
        # Save the changed value in the layer:
        layer.feature = self.layer_feature.value
        layer.visible = self.layer_visible_checkbox.value
        ## These three, dealing with colors of activations,
        ## can be done with a prop_one():
        if "color" in change["owner"].description.lower():
            ## Matches: Colormap, lefmost color, rightmost color
            ## overriding dynamic minmax!
            layer.minmax = (self.layer_mindim.value, self.layer_maxdim.value)
            layer.minmax = (self.layer_mindim.value, self.layer_maxdim.value)
            layer.colormap = self.layer_colormap.value if self.layer_colormap.value else None
            self.layer_colormap_image.value = """<img src="%s"/>""" % self.net._image_to_uri(self.make_colormap_image(layer.colormap))
            self.prop_one()
        else:
            self.regenerate()

    def update_layer_selection(self, change):
        """
        Just update the widgets; don't redraw anything.
        """
        ## No need to redisplay anything
        self._ignore_layer_updates = True
        ## First, get the new layer selected:
        layer = self.net[self.layer_select.value]
        ## Now, let's update all of the values without updating:
        self.layer_visible_checkbox.value = layer.visible
        self.layer_colormap.value = layer.colormap if layer.colormap != "" else ""
        self.layer_colormap_image.value = """<img src="%s"/>""" % self.net._image_to_uri(self.make_colormap_image(layer.colormap))
        minmax = layer.get_act_minmax()
        self.layer_mindim.value = minmax[0]
        self.layer_maxdim.value = minmax[1]
        self.layer_feature.value = layer.feature
        self._ignore_layer_updates = False
Beispiel #30
0
    p4.value = softmax(3)


def on_value_change(change):
    if change.owner == s1:
        values[0] = change.new
    if change.owner == s2:
        values[1] = change.new
    if change.owner == s3:
        values[2] = change.new
    if change.owner == s4:
        values[3] = change.new
    set_values()


s1.observe(on_value_change, names='value')
s2.observe(on_value_change, names='value')
s3.observe(on_value_change, names='value')
s4.observe(on_value_change, names='value')


def main():
    set_values()
    left_box = VBox([s1, s2, s3, s4], layout=Layout(width='50%'))
    middle_box = VBox([p1, p2, p3, p4])
    right_box = VBox([l1, l2, l3, l4])
    return HBox([left_box, middle_box, right_box])


if __name__ == "__main__":
    main()
        value_1 = A_1.value * np.sin(w_1.value * t)
        value_2 = A_2.value * np.cos(w_2.value * t)
    else:
        value_1 = A_1.value * np.sin(2 * math.pi * f_1.value*t - Phi_1.value * np.pi/180)
        value_2 = A_2.value * np.cos(2 * math.pi * f_2.value*t - Phi_2.value * np.pi/180)
    return value_1, value_2

# parameters
t = np.arange(0.0, 10.0, 0.001)
y_1, y_2 = calculate()

# figure
data = [go.Scatter(y = y_1, x = t, opacity = 0.75, name = 'Trace 1'), go.Scatter(y = y_2, x = t, opacity = 0.75, name = 'Trace 2')]
layout = {'yaxis': {'range': [-2, 2], 'title': "CALCULATED VALUE"}, 'xaxis': {'range': [0, 10], 'title': "TIME"}}
fig = go.FigureWidget(data, layout)

def recalculate(value):
    global fig
    fig.data[0].y, fig.data[1].y = calculate()
        
A_1.observe(recalculate, 'value')
A_2.observe(recalculate, 'value')
f_1.observe(recalculate, 'value')
f_2.observe(recalculate, 'value')
w_1.observe(recalculate, 'value')
w_2.observe(recalculate, 'value')
Phi_1.observe(recalculate, 'value')
Phi_2.observe(recalculate, 'value')
use.observe(recalculate, 'value')

fig
def MakeJointSlidersThatPublishOnCallback(plant,
                                          publishing_system,
                                          root_context,
                                          my_callback=None,
                                          lower_limit=-10.,
                                          upper_limit=10.,
                                          resolution=0.01,
                                          length=200,
                                          continuous_update=True):
    """
    Creates an ipywidget slider for each joint in the plant.  Unlike the
    JointSliders System, we do not expect this to be used in a Simulator.  It
    simply updates the context and calls Publish directly from the slider
    callback.

    Args:
        plant:        A MultibodyPlant.
        publishing_system: The System whose Publish method will be called.  Can
                           be the entire Diagram, but can also be a subsystem.
        root_context: A mutable root Context of the Diagram containing both the
                      ``plant`` and the ``publishing_system``; we will extract
                      the subcontext's using `GetMyContextFromRoot`.
        my_callback:  An optional additional callback function that will be
                      called once immediately and again whenever the sliders
                      are moved, using ``my_callback(plant_context)``.  This
                      can be useful, e.g. for outputting text that prints the
                      current end-effector Jacobian, or for showing a rendered
                      image from a camera.
        lower_limit:  A scalar or vector of length robot.num_positions().
                      The lower limit of the slider will be the maximum
                      value of this number and any limit specified in the
                      Joint.
        upper_limit:  A scalar or vector of length robot.num_positions().
                      The upper limit of the slider will be the minimum
                      value of this number and any limit specified in the
                      Joint.
        resolution:   A scalar or vector of length robot.num_positions()
                      that specifies the step argument of the FloatSlider.
        length:       The length of the sliders, which will be passed as a
                      string to the CSS width field and can be any valid CSS
                      entry (e.g. 100, 100px).
        continuous_update: The continuous_update field for the FloatSliders.
                      The default ``True`` means that this method will publish/
                      callback as the sliders are dragged.  ``False`` means
                      that the publish/callback will only happen once the user
                      finishes dragging the slider.

    Returns:
        A list of the slider widget objects that are created.

    Note: Some publishers (like MeshcatVisualizer) use an initialization event
    to "load" the geometry.  You should call that *before* calling this method
    (e.g. with `meshcat.load()`).
    """
    def _broadcast(x, num):
        x = np.array(x)
        assert len(x.shape) <= 1
        return np.array(x) * np.ones(num)

    lower_limit = _broadcast(lower_limit, plant.num_positions())
    upper_limit = _broadcast(upper_limit, plant.num_positions())
    resolution = _broadcast(resolution, plant.num_positions())

    publishing_context = publishing_system.GetMyContextFromRoot(root_context)
    plant_context = plant.GetMyContextFromRoot(root_context)
    positions = plant.GetPositions(plant_context)

    # Publish once immediately.
    publishing_system.Publish(publishing_context)
    if my_callback:
        my_callback(plant_context)

    def _slider_callback(change, index):
        positions[index] = change.new
        plant.SetPositions(plant_context, positions)
        publishing_system.Publish(publishing_context)
        if my_callback:
            my_callback(plant_context)

    slider_widgets = []
    slider_num = 0
    for i in range(plant.num_joints()):
        joint = plant.get_joint(JointIndex(i))
        low = joint.position_lower_limits()
        upp = joint.position_upper_limits()
        for j in range(joint.num_positions()):
            index = joint.position_start() + j
            description = joint.name()
            if joint.num_positions() > 1:
                description += f"[{j}]"
            slider = FloatSlider(value=positions[index],
                                 min=max(low[j], lower_limit[slider_num]),
                                 max=min(upp[j], upper_limit[slider_num]),
                                 step=resolution[slider_num],
                                 continuous_update=continuous_update,
                                 description=description,
                                 style={'description_width': 'initial'},
                                 layout=Layout(width=f"'{length}'"))
            slider.observe(partial(_slider_callback, index=index),
                           names='value')
            display(slider)
            slider_widgets.append(slider)
            slider_num += 1

    return slider_widgets
Beispiel #33
0
def show_plot():
    plt.close('all')
    plt.ioff()

    # load in the trace
    from glob import glob
    import os
    global df, trace_o, trace_n, title
    df = pd.read_csv('merged_data.csv')

    # read in the models
    fit_o = models.oocyte_model(df)
    fit_n = models.oocyte_model(df)

    # read in the traces
    trace_o = pm.load_trace('trace_o', fit_o)
    trace_n = pm.load_trace('trace_n', fit_n)

    fig, ax = plt.subplots(1, 1, figsize=(8, 6))
    out = widgets.Output()

    #res_df = pd.read_pickle("res.pkl")
    def click(b):
        global o_obs, o_x, n_obs, n_x, df

        mask = df['i_ind'] == choice.value
        if (sum(mask) > 0):
            title_comp = df.loc[mask, 'ucode'].values[0].split('_')
            fig.suptitle("{}".format(title_comp[0]))
            ax.set_title("day {}.rep {}, str {}".format(*title_comp[1:]))

        Vmax_o = Vmax_o_slide.value
        ao = ao_slide.value
        to = to_slide.value
        Vmin_o = Vmin_o_slide.value

        Vmax_n = Vmax_n_slide.value
        a0 = a0_slide.value
        t0 = t0_slide.value
        a1 = a1_slide.value
        t1 = t1_slide.value
        Vmin_n = Vmin_n_slide.value
        #plt.figure(2)

        ax.clear()
        ax.plot(-o_x, o_obs, 'o', color='red')
        ax.plot(-n_x, n_obs, 'o', color='blue')
        if (True):
            x = np.linspace(-2, 16, num=100)
            ax.plot(-x,
                    bu.rise_only(x, Vmax_o, to, ao, 1.0, Vmin_o),
                    color='red')
            ax.plot(-x,
                    bu.rise_and_fall(x, Vmax_n, t0, a0, 1.0, t1, a1, 1,
                                     Vmin_n),
                    color='blue')

            ax.plot([-to, -to],
                    [0, bu.rise_only(to, Vmax_o, to, ao, 1.0, Vmin_o)],
                    ls='--',
                    color='red',
                    lw=1.5)
            ax.plot([-t0, -t0], [
                0,
                bu.rise_and_fall(t0, Vmax_n, t0, a0, 1.0, t1, a1, 1, Vmin_n)
            ],
                    ls='--',
                    color='blue',
                    lw=1.5)
            ax.plot([-t1, -t1], [
                0,
                bu.rise_and_fall(t1, Vmax_n, t0, a0, 1.0, t1, a1, 1, Vmin_n)
            ],
                    ls='--',
                    color='blue',
                    lw=1.5)

            ax.set_xticks(range(-14, 2, 2))
            ax.set_ylim(0, 200)
            ax.axhline(Vmax_o, ls='--', color='red')
            ax.axvline(0, ls='--', color='grey', lw=1)

            [xmin, xmax] = ax.get_xlim()
            [ymin, ymax] = ax.get_ylim()
            ax.annotate(r'$t_o$', (to + 0.2, ymax - 10))
            ax.annotate(r'$Vmax_{o}}$', (xmax - 2, Vmax_o + 10))

        with out:
            clear_output(wait=True)
            display(ax.figure)

    #choice=Dropdown(
    #
    #	options='cont_r1 cont_r2 cont_r3 caged_d04_r1 caged_d07_r1'.split(),
    #	value='cont_r1',
    #	description='Number:',
    #	disabled=False,
    #)
    choice = widgets.IntText(value=0,
                             min=0,
                             max=len(df['i_ind'].unique()),
                             step=1,
                             description='Test:',
                             disabled=False,
                             continuous_update=False,
                             readout=True,
                             readout_format='d')

    Vmax_o_slide = FloatSlider(description=r'$V$max$_o$',
                               value=150,
                               min=0,
                               max=300,
                               continuous_update=False)
    Vmax_o_slide.observe(click, names='value')
    Vmin_o_slide = FloatSlider(description=r'$V$min$_o$',
                               value=15,
                               min=0,
                               max=30,
                               continuous_update=False)
    Vmin_o_slide.observe(click, names='value')
    ao_slide = FloatSlider(description=r'$a_o$',
                           value=0.2,
                           min=0.,
                           max=0.75,
                           continuous_update=False)
    ao_slide.observe(click, names='value')
    to_slide = FloatSlider(description=r'$t_o$',
                           value=1,
                           min=-2,
                           max=6,
                           continuous_update=False)
    to_slide.observe(click, names='value')

    Vmax_n_slide = FloatSlider(description=r'$V$max$_{n}$',
                               value=150,
                               min=0,
                               max=300,
                               continuous_update=False)
    Vmax_n_slide.observe(click, names='value')
    Vmin_n_slide = FloatSlider(description=r'$V$min$_n$',
                               value=15,
                               min=0,
                               max=30,
                               continuous_update=False)
    Vmin_n_slide.observe(click, names='value')
    a0_slide = FloatSlider(description=r'$a_0$',
                           value=0.4,
                           min=0.0,
                           max=1.5,
                           continuous_update=False)
    a0_slide.observe(click, names='value')
    t0_slide = FloatSlider(description=r'$t_0$',
                           value=0,
                           min=-4,
                           max=8,
                           continuous_update=False)
    t0_slide.observe(click, names='value')

    a1_slide = FloatSlider(description=r'$a_1$',
                           value=0.4,
                           min=0.0,
                           max=8,
                           continuous_update=False)
    a1_slide.observe(click, names='value')
    t1_slide = FloatSlider(description=r'$t_1$',
                           value=0.5,
                           min=-2,
                           max=6,
                           continuous_update=False)
    t1_slide.observe(click, names='value')

    def choice_selected(b):
        global o_obs, o_x, n_obs, n_x, df, trace_o, trace_n
        if (False):
            name = choice.value
            df = pd.read_csv("results_analyse/{}.csv".format(name))
            o_obs = dh.unpack_results(df, 1, 'o', volume=False)
            o_x = np.arange(len(o_obs))
            n_obs = dh.unpack_results(df, 1, 'n', volume=False)
            n_x = np.arange(len(n_obs))
        else:
            iexp = choice.value
            mask = df['i_ind'] == iexp
            if (sum(mask) > 0):
                o_obs = df.loc[mask, 'Oc_size']
                o_x = df.loc[mask, 'pos']
                n_obs = df.loc[mask, 'Ns_size']
                n_x = o_x

                vars_o = 'Vmax_o,t_o,a_o,Vmin_o'.split(',')
                vars_n = 'Vmax_n t0 a0 t1 a1 Vmin_n'.split()
                theta_o = np.median(bu.pull_post(trace_o, vars_o, iexp),
                                    axis=0)
                theta_n = np.median(bu.pull_post(trace_n, vars_n, iexp),
                                    axis=0)
                for slide, val in zip(
                    [Vmax_o_slide, to_slide, ao_slide, Vmin_o_slide], theta_o):
                    slide.value = val
                for slide, val in zip([
                        Vmax_n_slide, t0_slide, a0_slide, t1_slide, a1_slide,
                        Vmin_n_slide
                ], theta_n):
                    slide.value = val

        #rown = "{}_1".format(name)
        #Vmax_n_slide.value= res_df.loc[rown,('Vmax_n','m')]
        #a0_slide.value= res_df.loc[rown,('a0','m')]
        #t0_slide.value= -res_df.loc[rown,('t0','m')]
        #a1_slide.value= res_df.loc[rown,('a1','m')]
        #t1_slide.value= -res_df.loc[rown,('t1','m')]

        #Vmax_o_slide.value= res_df.loc[rown,('Vmax_o','m')]
        #ao_slide.value= res_df.loc[rown,('a_o','m')]
        #to_slide.value= -res_df.loc[rown,('t_o','m')]
        click(None)
        #f(Vmax_slide.value, a0_slide.value, t0_slide.value)
        return

    choice_selected(None)
    choice.observe(choice_selected)

    #display(VBox([mslide,cslide]))
    oocyte_params = widgets.VBox([
        Label(value="Oocyte"), Vmax_o_slide, ao_slide, to_slide, Vmin_o_slide
    ])
    nurse_params = widgets.VBox(
        [Vmax_n_slide, a0_slide, t0_slide, a1_slide, t1_slide, Vmin_n_slide])
    box = widgets.VBox(
        [choice, widgets.HBox([oocyte_params, nurse_params]), out])
    display(box)

    click(None)
Beispiel #34
0
    def __init__(self,
                 position: str = "bottomleft",
                 attr_name: str = "style",
                 kind: str = "stroke",
                 orientation: str = "horizontal",
                 transparent: bool = False,
                 a_map: Map = None,
                 layer: Layer = None,
                 place_control: bool = True):
        """Add a widget to the map that allows styling some given layer.

        At the moment only the stroke color, opacity and weight can be changed
        using a color picker and sliders. Dash array might follow later.

        :param m: The map object to which to add a styling widget.
        :param layer: The layer object which is to be styled.
        :param attr_name: The layer's attribute name storing the style object.
            This is usually one of: "style", "hover_style", and "point_style"
        :param kind: The kind of style, either "stroke" or "fill".
        :param orientation: The orientation of the UI elements, either "horizontal"
            (default) or "vertical".
        :param transparent: A flag to indicate if the widget background should be
            transparent (default: ``False``). 
        :param position: The map corner where this widget will be placed. 

        TODO: The UI elements should reflect changes to the layer triggered by
              others. 
        """
        assert kind in ["stroke", "fill"]
        assert orientation in ["horizontal", "vertical"]

        def restyle(change):
            if change["type"] != "change":
                return
            owner = change["owner"]
            style_copy = copy.copy(getattr(layer, attr_name))
            attr_map = {
                p: "color" if kind == "stroke" else "fillColor",
                o: "opacity" if kind == "stroke" else "fillOpacity",
                w: "weight"
            }
            if owner in [p, o, w]:
                style_copy[attr_map[owner]] = owner.value
                setattr(layer, attr_name, style_copy)

        def close(button):
            a_map.remove_control(wc)

        attr = getattr(layer, attr_name)
        style = getattr(layer, "style")

        b = ToggleButton(description="Stroke",
                         value=True,
                         tooltip="Stroke or not?")
        dummy = ToggleButton(value=not b.value)
        b.layout.width = "80px"

        name = "color" if kind == "stroke" else "fillColor"
        p = ColorPicker(value=attr.get(name, style.get(name, "#3885ff")))
        p.layout.width = "100px"

        name = "opacity" if kind == "stroke" else "fillOpacity"
        o = FloatSlider(min=0,
                        max=1,
                        value=attr.get(name, style.get(name, 0.5)))
        o.layout.width = "200px"

        w = IntSlider(min=0,
                      max=50,
                      value=attr.get("weight", style.get("weight", 5)))
        w.layout.width = "200px"

        layout = Layout(width="28px", height="28px", padding="0px 0px 0px 4px")
        q = Button(tooltip="Close",
                   icon="close",
                   button_style="info",
                   layout=layout)

        for el in [p, o, w] if kind == "stroke" else [p, o]:
            link((dummy, "value"), (el, "disabled"))

        p.observe(restyle)
        o.observe(restyle)
        if kind == "stroke":
            w.observe(restyle)
        else:
            w.disabled = True
        q.on_click(close)

        desc = HTML(f"{kind} {attr_name}")

        if orientation == "horizontal":
            self.widget = HBox([desc, p, w, o, q])
        elif orientation == "vertical":
            self.widget = VBox([HBox([desc, q]), p, w, o])

        wc = WidgetControl(widget=self.widget,
                           position=position,
                           transparent_bg=transparent)
        a_map.add_control(wc)
Beispiel #35
0
    def display_focal_distance(self, with_preview=False):
        """Display visual controls for setting camera focal distance"""
        x_slider = FloatSlider(description='X', min=0, max=1, value=0.5)
        y_slider = FloatSlider(description='Y', min=0, max=1, value=0.5)
        a_slider = FloatSlider(description='Aperture', min=0, max=1, value=0)
        f_slider = FloatSlider(description='Focus radius',
                               min=0,
                               max=1,
                               value=0.01)
        d_slider = FloatSlider(description='Focus distance',
                               min=0,
                               max=10000,
                               value=0,
                               disabled=True)
        f_button = Button(description='Refresh')
        f_target = Button(description='Target')

        class Updated:
            """Class object embedding communication with remote server"""
            def __init__(self, client, with_preview):
                self._client = client
                self._widget_value = None
                self._x = 0.5
                self._y = 0.5
                self._aperture = 0.0
                self._focus_radius = 0.01
                self._focus_distance = 0.0
                self._nb_focus_points = 20
                self._snapshot = None
                self._with_preview = with_preview

            def _update_camera(self):
                self._focus_distance = 1e6
                for _ in range(self._nb_focus_points):
                    self._focus_distance = min(
                        self._focus_distance,
                        self._get_focal_distance(
                            (self._x + random.random() * self._focus_radius,
                             self._y + random.random() * self._focus_radius)))

                params = self._client.BioExplorerPerspectiveCameraParams()
                params.focus_distance = self._focus_distance
                params.aperture_radius = self._aperture
                params.enable_clipping_planes = True
                d_slider.value = self._focus_distance
                self._client.set_camera_params(params)

                if self._with_preview:
                    self._get_preview(False)

            def update(self):
                """Update all settings of the camera"""
                self._update_camera()

                if self._with_preview:
                    self._get_preview(True)

            def update_target(self):
                """Update camera target"""
                inspection = self._client.inspect([self._x, self._y])
                if inspection['hit']:
                    position = inspection['position']
                    self._client.set_camera(target=position)
                    self._client.set_renderer()

            def update_focus_radius(self, val_dict) -> None:
                """Update camera focus radius"""
                self._widget_value = val_dict['new']
                self._focus_radius = self._widget_value
                self._update_camera()

            def update_aperture(self, val_dict) -> None:
                """Update camera aperture"""
                self._widget_value = val_dict['new']
                self._aperture = self._widget_value
                self._update_camera()

            def update_x(self, val_dict) -> None:
                """Update camera normalized horizontal focus location"""
                self._widget_value = val_dict['new']
                self._x = self._widget_value
                self._update_camera()

            def update_y(self, val_dict) -> None:
                """Update camera normalized vertical focus location"""
                self._widget_value = val_dict['new']
                self._y = self._widget_value
                self._update_camera()

            def _get_focal_distance(self, coordinates=(0.5, 0.5)):
                """
                Return the focal distance for the specified normalized coordinates in the image

                :param list coordinates: Coordinates in the image
                :return: The focal distance
                :rtype: float
                """
                target = self._client.inspect(array=coordinates)['position']
                origin = self._client.camera.position.data
                vector = [0, 0, 0]
                for k in range(3):
                    vector[k] = float(target[k]) - float(origin[k])
                return math.sqrt(vector[0] * vector[0] +
                                 vector[1] * vector[1] + vector[2] * vector[2])

            def _get_preview(self, update_image):
                viewport = self._client.get_application_parameters(
                )['viewport']
                ratio = viewport[1] / viewport[0]
                size = [256, int(256.0 * ratio)]
                if update_image:
                    self._snapshot = self._client.image(size=size,
                                                        samples_per_pixel=4)

                if self._snapshot is None:
                    return

                x = self._x * size[0]
                y = (1.0 - self._y) * size[1]
                rx = self._focus_radius * size[0]
                ry = self._focus_radius * size[1]
                byte_io = io.BytesIO()
                snapshot = self._snapshot.copy()
                draw = ImageDraw.Draw(snapshot)
                draw.ellipse((x - rx, y - ry, x + rx, y + ry))
                draw.ellipse((x - 5, y - 5, x + 5, y + 5))
                snapshot.save(byte_io, 'png')
                preview.width = size[0]
                preview.height = size[1]
                preview.value = byte_io.getvalue()

        update_class = Updated(self._client, with_preview)

        def update_x(value):
            update_class.update_x(value)

        def update_y(value):
            update_class.update_y(value)

        def update_aperture(value):
            update_class.update_aperture(value)

        def update_focus_radius(value):
            update_class.update_focus_radius(value)

        def update_button(_):
            update_class.update()

        def update_target(_):
            update_class.update_target()

        x_slider.observe(update_x, 'value')
        y_slider.observe(update_y, 'value')
        a_slider.observe(update_aperture, 'value')
        f_slider.observe(update_focus_radius, 'value')
        f_button.on_click(update_button)
        f_target.on_click(update_target)

        position_box = VBox([x_slider, y_slider, f_button, f_target])
        parameters_box = VBox([a_slider, f_slider, d_slider])
        horizontal_box = HBox([position_box, parameters_box],
                              layout=DEFAULT_GRID_LAYOUT)
        display(horizontal_box)

        if with_preview:
            byte_io = io.BytesIO()
            preview = Image(value=byte_io.getvalue(),
                            format='png',
                            width=1,
                            height=1)
            display(preview)