Example #1
0
 def make_default_user_namespaces(self):
     user_namespaces = W.Textarea(
         placeholder="PREFIX ex: <https://www.example.org/>",
         layout=W.Layout(width="80%"),
     )
     T.link((user_namespaces, "value"), (self, "user_namespaces_value"))
     return user_namespaces
Example #2
0
    def _make_spin_box(self):
        checkbox_spin = Checkbox(self.spin, description='spin')
        spin_x_slide = IntSlider(self._spin_x,
                                 min=-1,
                                 max=1,
                                 description='spin_x')
        spin_y_slide = IntSlider(self._spin_y,
                                 min=-1,
                                 max=1,
                                 description='spin_y')
        spin_z_slide = IntSlider(self._spin_z,
                                 min=-1,
                                 max=1,
                                 description='spin_z')
        spin_speed_slide = FloatSlider(self._spin_speed,
                                       min=0,
                                       max=0.2,
                                       step=0.001,
                                       description='spin speed')
        # spin
        link((checkbox_spin, 'value'), (self, 'spin'))
        link((spin_x_slide, 'value'), (self, '_spin_x'))
        link((spin_y_slide, 'value'), (self, '_spin_y'))
        link((spin_z_slide, 'value'), (self, '_spin_z'))
        link((spin_speed_slide, 'value'), (self, '_spin_speed'))

        spin_box = VBox([
            checkbox_spin, spin_x_slide, spin_y_slide, spin_z_slide,
            spin_speed_slide
        ])
        spin_box = _relayout_master(spin_box, width='75%')
        return spin_box
Example #3
0
File: legacy.py Project: vusd/p55py
    def __init__(self, width=320, height=320, setupfn=empty_function, drawfn=empty_function, stepfn=empty_function, renderfn=empty_function):
        self.setup_func = setupfn
        self.draw_func = drawfn
        self.step_func = stepfn
        self.render_func = renderfn
        self.redrawFreq = 1
        self.randomSeed = int(calendar.timegm(time.gmtime()))
        self.incSeedOnStop = True
        self.settings_pane = None
        self.randomSeedWidget = None

        self.play = widgets.Play()
        self.p55_widget = P55CanvasWidget()
        self.p55_widget.canvas_width = width
        self.p55_widget.canvas_height = height
        self.p55_widget.value = 0
        self.reset_widget();
        self.step_label = widgets.Label(u"0", description='step');

        play_observer = get_p55_play_observer(self)
        self.p55_widget.observe(play_observer, names='value')
        traitlets.link((self.play, 'value'), (self.p55_widget, 'value'))
        label_observer = get_label_changer(self)
        self.p55_widget.observe(label_observer, names='value')

        self.play_row = widgets.HBox([self.play, self.step_label])
        self.display_pane = widgets.VBox([self.p55_widget, self.play_row])
        self.widget = widgets.HBox([self.display_pane])
Example #4
0
    def __init__(self, colors='red', gl=False, **kwargs):
        if isinstance(colors, str):
            colors = [colors]

        color_scale = ColorScale(scheme='plasma')

        scales = {
            'x': LinearScale(allow_padding=False),
            'y': LinearScale(allow_padding=False, orientation='vertical'),
            'color': color_scale,
            'size': LinearScale(min=0, max=1),
        }

        if gl:
            mark = ScatterGL(x=np.zeros((1, )),
                             y=np.zeros((1, )),
                             scales=scales,
                             colors=['red'])
        else:
            mark = Scatter(x=np.zeros((1, )),
                           y=np.zeros((1, )),
                           scales=scales,
                           colors=['red'])

        # link((self, 'color'), (mark, 'color'))

        super().__init__(mark=mark, **kwargs)

        link((self._mark, 'visible'), (self, 'visible'))
Example #5
0
    def slider_link(obj, attr):
        "Function to link one object to an attr of the slider."

        # pylint: disable=unused-argument
        def link_fn(name, new_value):
            "How to update the object's value given min/max on the slider. "
            if new_value >= slider.max:
                slider.max = new_value
            # if any value is greater than the max, the max slides up
            # however, this is not held true for the minimum, because
            # during typing the max or value will grow, and we don't want
            # to permanently anchor the minimum to unfinished typing
            if attr == "max" and new_value <= slider.value:
                if slider.max >= slider.min:
                    slider.value = new_value
                else:
                    pass  # bounds nonsensical, probably because we picked up
                    # a small value during user typing.
            elif attr == "min" and new_value >= slider.value:
                slider.value = new_value
            setattr(slider, attr, new_value)
            slider.step = (slider.max - slider.min) / 24.0

        obj.on_trait_change(link_fn, "value")
        link((slider, attr), (obj, "value"))
Example #6
0
    def __init__(self, *arg, **kwd):
        box_first = kwd.pop('box_first', False)
        description = kwd.pop('description', '')
        super(CheckboxPlus, self).__init__(*arg, **kwd)

        # Set the description to an empty string to ensure no space
        # is left for it.
        self._check = widgets.Checkbox(description='',
                                       style={'description_width': 'initial'})
        self._description = widgets.Label(value=description)
        children = [self._check, self._description]
        if not box_first:
            children.reverse()

        # Make this a flex-box
        self.layout.display = 'flex'

        # This ensures vertical alignment between the checkbox and its label.
        self.layout.align_items = 'center'

        # Keep the checkbox and description close together
        self.layout.justify_content = 'flex-start'

        # Tie this widget's value to the value of the actual checkbox.
        link((self, 'value'), (self._check, 'value'))
        # Tie this widget's disabled state to that of the actual checkbox.
        link((self, 'disabled'), (self._check, 'disabled'))

        self.children = children
Example #7
0
 def make_default_dropdown(self):
     dropdown = W.Dropdown(
         options=["SELECT", "SELECT DISTINCT", "ASK", "CONSTRUCT"],
         value="SELECT DISTINCT",
     )
     T.link((dropdown, "value"), (self, "dropdown_value"))
     return dropdown
Example #8
0
def show_vibs(calc, amplitude=1):
    import traitlets
    import nglview
    import ipywidgets as widgets
    from ipywidgets import Layout, HBox, VBox

    trajs = []
    freqs, modes = calc.get_vibrational_modes()
    freq_list = [
        '-%.2f' % (f.real * 1000) if np.iscomplexobj(f) else '%.2f' %
        (f * 1000) for f in freqs
    ]

    for n, mode in enumerate(modes):
        trajs.append(
            [a.positions for a in form_traj(calc.atoms, mode, amplitude)])

    v = nglview.show_asetraj([calc.atoms])
    v.clear_representations()
    v.add_spacefill(radius_type='vdw',
                    radius_scale=0.5,
                    roughness=1,
                    metalness=0)
    v._set_size('450px', '300px')
    v.camera = 'orthographic'
    v.parameters = dict(clipDist=0, sampleLevel=1)

    select = widgets.Select(options=freq_list,
                            value=freq_list[-1],
                            layout=Layout(width='100px', height='270px'),
                            disabled=False)

    play = widgets.Play(value=0,
                        min=-10,
                        max=10,
                        step=1,
                        _repeat=True,
                        description="Press play",
                        disabled=False)

    slider = widgets.IntSlider(
        value=0,
        min=-10,
        max=10,
    )

    class FnScope:
        traj = trajs[-1]

    def handle_slider_change(change):
        v.set_coordinates({0: FnScope.traj[change.new]})

    def handle_select_change(change):
        FnScope.traj = trajs[change.new]

    slider.observe(handle_slider_change, names='value')
    select.observe(handle_select_change, names='index')
    traitlets.link((play, 'value'), (slider, 'value'))
    vib_viewer = HBox([VBox([v, HBox([play, slider])]), select])
    display(vib_viewer)
    def __init__(self, description="Select computer:", path_to_root="../", **kwargs):
        """Dropdown for configured AiiDA Computers.

        description (str): Text to display before dropdown.

        path_to_root (str): Path to the app's root folder.
        """

        self.output = ipw.HTML()
        self._dropdown = ipw.Dropdown(
            options={},
            value=None,
            description=description,
            style={"description_width": "initial"},
            disabled=True,
        )
        link((self, "computers"), (self._dropdown, "options"))
        link((self._dropdown, "value"), (self, "selected_computer"))

        btn_refresh = ipw.Button(description="Refresh", layout=ipw.Layout(width="70px"))
        btn_refresh.on_click(self.refresh)

        self.observe(self.refresh, names="allow_select_disabled")

        self._setup_another = ipw.HTML(
            value=f"""<a href={path_to_root}aiidalab-widgets-base/notebooks/setup_computer.ipynb target="_blank">
            Setup new computer</a>"""
        )

        children = [
            ipw.HBox([self._dropdown, btn_refresh, self._setup_another]),
            self.output,
        ]
        self.refresh()
        super().__init__(children=children, **kwargs)
Example #10
0
    def __init__(self,
                 description="Select computer:",
                 path_to_root="../",
                 **kwargs):
        """Dropdown for configured AiiDA Computers.

        description (str): Text to display before dropdown.

        path_to_root (str): Path to the app's root folder.
        """

        self.output = ipw.HTML()
        self._dropdown = ipw.Dropdown(
            options={},
            value=None,
            description=description,
            style=STYLE,
            layout=LAYOUT,
            disabled=True,
        )
        traitlets.link((self, "computers"), (self._dropdown, "options"))
        traitlets.link((self._dropdown, "value"), (self, "value"))

        self.observe(self.refresh, names="allow_select_disabled")

        children = [
            ipw.HBox([
                self._dropdown,
            ]),
            self.output,
        ]
        self.refresh()
        super().__init__(children=children, **kwargs)
Example #11
0
 def make_default_select_header(self):
     header = W.Text(
         placeholder="*",
         # layout={"width":"80%"},
     )
     T.link((header, "value"), (self, "header_value"))
     return header
Example #12
0
    def __init__(self, statebar=None, **kwargs):

        super().__init__(**kwargs)

        self.gdf = None

        # Parameters
        self.out_path = Path('')
        self.json_path = None

        # Widgets
        self.shape_input = sw.FileInput(['.shp'], os.getcwd())

        self.w_state_bar = sw.StateBar(
            loading=True) if not statebar else statebar

        # Link behaviours

        link((self.shape_input, 'file'), (self, 'shapefile'))

        # View

        self.children = [v.Layout(row=True, children=[
            self.shape_input,
        ])]

        # Add a statebar if there is not provided an external one
        if not statebar: self.children = self.children + [self.w_state_bar]
Example #13
0
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self._selection_obj = widgets.widget_selection._MultipleSelection()
        traitlets.link((self, 'options'), (self._selection_obj, 'options'))
        traitlets.link((self, 'value'), (self._selection_obj, 'value'))

        @traitlets.observe(self, 'options')
        def _(*_):
            self.buttons = [
                widgets.ToggleButton(description=label,
                                     layout=widgets.Layout(margin='0',
                                                           width='auto'))
                for label in self._selection_obj._options_labels
            ]
            self.children = self.buttons

            @traitlets.observe(self.buttons, 'value')
            def _(*_):
                for btn in self.buttons:
                    btn.button_style = 'primary' if btn.value else ''
                self.value = tuple(value for btn, value in zip(
                    self.buttons, self._selection_obj._options_values)
                                   if btn.value)

        self.add_class('btn-group')
Example #14
0
    def __init__(self, **kwargs):
        super(DataArray, self).__init__(**kwargs)
        self.signal_slice = vaex.events.Signal()
        self.signal_regrid = vaex.events.Signal()
        self.signal_grid_progress = vaex.events.Signal()
        self.observe(lambda change: self.signal_regrid.emit(), 'selections')
        self._on_axis_status_change()

        # keep a set of axis that need new limits
        self._dirty_axes = set()
        for axis in self.axes:
            assert axis.df is self.df, "axes should have the same dataframe"
            traitlets.link((self, 'shape'), (axis, 'shape_default'))
            axis.observe(self._on_axis_status_change, 'status')
            axis.observe(lambda _: self.signal_slice.emit(self), ['slice'])

            def on_change_min_max(change):
                if change.owner.status == Axis.Status.READY:
                    # this indicates a user changed the min/max
                    self.status = DataArray.Status.NEEDS_CALCULATING_GRID

            axis.observe(on_change_min_max, ['min', 'max'])

        self._on_axis_status_change()
        self.df.signal_selection_changed.connect(self._on_change_selection)
Example #15
0
    def __init__(self, *arg, **kwd):
        box_first = kwd.pop('box_first', False)
        description = kwd.pop('description', '')
        super(CheckboxPlus, self).__init__(*arg, **kwd)

        # Set the description to an empty string to ensure no space
        # is left for it.
        self._check = widgets.Checkbox(description='',
                                       style={'description_width': 'initial'})
        self._description = widgets.Label(value=description)
        children = [self._check, self._description]
        if not box_first:
            children.reverse()

        # Make this a flex-box
        self.layout.display = 'flex'

        # This ensures vertical alignment between the checkbox and its label.
        self.layout.align_items = 'center'

        # Keep the checkbox and description close together
        self.layout.justify_content = 'flex-start'

        # Tie this widget's value to the value of the actual checkbox.
        link((self, 'value'), (self._check, 'value'))
        # Tie this widget's disabled state to that of the actual checkbox.
        link((self, 'disabled'), (self._check, 'disabled'))

        self.children = children
Example #16
0
    def __init__(self, titles, content, **kwargs):

        self.background_color = "primary"
        self.dark = True

        self.tabs = [
            v.Tabs(v_model=self.current,
                   children=[
                       v.Tab(children=[title], key=key)
                       for key, title in enumerate(titles)
                   ])
        ]

        self.content = [
            v.TabsItems(v_model=self.current,
                        children=[
                            v.TabItem(children=[content], key=key)
                            for key, content in enumerate(content)
                        ])
        ]

        self.children = self.tabs + self.content

        link((self.tabs[0], 'v_model'), (self.content[0], 'v_model'))

        super().__init__(**kwargs)
Example #17
0
    def __init__(self, mol):
        super(ResidueSelector, self).__init__(mol)

        self.selection_type = ipy.Dropdown(description='Clicks select:',
                                           value=self.viewer.selection_type,
                                           options=('Atom', 'Residue',
                                                    'Chain'))

        traitlets.link((self.selection_type, 'value'),
                       (self.viewer, 'selection_type'))

        self.residue_listname = ipy.HTML('<b>Selected residues:</b>')
        self.residue_list = ipy.SelectMultiple(options=list(), height=150)
        traitlets.directional_link((self.viewer, 'selected_atom_indices'),
                                   (self.residue_list, 'options'),
                                   self._atoms_to_residues)
        self.residue_list.observe(self.remove_atomlist_highlight, 'value')
        self.atom_list.observe(self.remove_reslist_highlight, 'value')

        self.subtools.children = [
            ipy.HBox([self.select_all_atoms_button, self.select_none])
        ]
        self.toolpane.children = [
            self.selection_type, self.atom_listname, self.atom_list,
            self.residue_listname, self.residue_list
        ]
Example #18
0
def figure(key=None,
           width=400,
           height=500,
           lighting=True,
           controls=True,
           controls_vr=False,
           debug=False,
           **kwargs):
    """Create a new figure (if no key is given) or return the figure associated with key

    :param key: Python object that identifies this figure
    :param int width: pixel width of WebGL canvas
    :param int height:  .. height ..
    :param bool lighting: use lighting or not
    :param bool controls: show controls or not
    :param bool controls_vr: show controls for VR or not
    :param bool debug: show debug buttons or not
    :return: :any:`Figure`
    """
    if key is not None and key in current.figures:
        current.figure = current.figures[key]
        current.container = current.containers[key]
    elif isinstance(key, ipv.Figure) and key in current.figures.values():
        key_index = list(current.figures.values()).index(key)
        key = list(current.figures.keys())[key_index]
        current.figure = current.figures[key]
        current.container = current.containers[key]
    else:
        current.figure = ipv.Figure(volume_data=None,
                                    width=width,
                                    height=height,
                                    **kwargs)
        current.container = ipywidgets.VBox()
        current.container.children = [current.figure]
        if key is None:
            key = uuid.uuid4().hex
        current.figures[key] = current.figure
        current.containers[key] = current.container
        if controls:
            #stereo = ipywidgets.ToggleButton(value=current.figure.stereo, description='stereo', icon='eye')
            #l1 = ipywidgets.jslink((current.figure, 'stereo'), (stereo, 'value'))
            #current.container.children += (ipywidgets.HBox([stereo, ]),)
            pass  # stereo and fullscreen are now include in the js code (per view)
        if controls_vr:
            eye_separation = ipywidgets.FloatSlider(
                value=current.figure.eye_separation,
                min=-10,
                max=10,
                icon='eye')
            ipywidgets.jslink((eye_separation, 'value'),
                              (current.figure, 'eye_separation'))
            current.container.children += (eye_separation, )
        if debug:
            show = ipywidgets.ToggleButtons(
                options=["Volume", "Back", "Front"])
            current.container.children += (show, )
            #ipywidgets.jslink((current.figure, 'show'), (show, 'value'))
            traitlets.link((current.figure, 'show'), (show, 'value'))
    return current.figure
Example #19
0
    def __init__(self, model=None, *args, **kwargs):

        super(GeneratorCostView, self).__init__(*args, **kwargs)

        if model is not None:
            self.model = model
        else:
            self.model = Generator()

        self._scale_x = bq.LinearScale(min=self.model.minimum_real_power,
                                       max=self.model.maximum_real_power)

        self._scale_y = bq.LinearScale(
            min=0, max=(max(self.model.cost_curve_values) * 1.5 + 50))

        self._scales = {
            'x': self._scale_x,
            'y': self._scale_y,
        }

        self._scatter = bq.Scatter(x=self.model.cost_curve_points,
                                   y=self.model.cost_curve_values,
                                   scales=self._scales)

        self._lines = bq.Lines(x=self.model.cost_curve_points,
                               y=self.model.cost_curve_values,
                               scales=self._scales)

        self._axes_x = bq.Axis(scale=self._scale_x)
        self._axes_y = bq.Axis(scale=self._scale_y,
                               orientation='vertical',
                               padding_x=0.025)

        f = bq.Figure(marks=[
            self._lines,
            self._scatter,
        ],
                      axes=[
                          self._axes_x,
                          self._axes_y,
                      ])

        children = [f]

        self.children = children

        t.link((self.model, 'maximum_real_power'), (self._scale_x, 'max'))
        t.link((self.model, 'cost_curve_points'), (self._scatter, 'x'))
        t.link((self.model, 'cost_curve_values'), (self._scatter, 'y'))

        t.link((self._lines, 'x'), (self._scatter, 'x'))
        t.link((self._lines, 'y'), (self._scatter, 'y'))

        # self._scatter.observe(self._callback_ydata, names=['y'])

        with self._scatter.hold_sync():
            self._scatter.enable_move = True
            self._scatter.update_on_move = True
            self._scatter.interactions = {'click': None}
Example #20
0
 def make_default_limit_check(self):
     limit_check = W.Checkbox(
         value=False,
         indent=False,
         layout=W.Layout(width="20px"),
     )
     T.link((limit_check, "value"), (self, "limit_enabled"))
     return limit_check
Example #21
0
    def _ui(self) -> List[W.Widget]:
        dropdown = W.Dropdown(
            description="Edge Label Placement", options=list(EDGE_LABEL_OPTIONS.items())
        )

        T.link((self, "value"), (dropdown, "value"))

        return [dropdown]
Example #22
0
 def make_default_style_picker(self) -> W.Dropdown:
     widget = W.Dropdown(
         description="Style",
         options=list(STYLE_MAP.keys()),
         layout=W.Layout(min_height="30px"),
     )
     T.link((self, "formatter_style"), (widget, "value"))
     return widget
Example #23
0
 def color_scheme_picker(self):
     schemes = [
         'Greys', 'viridis', 'inferno', 'plasma', 'magma', 'Spectral',
         'RdBu'
     ]
     dropdown = widgets.Dropdown(description='Scheme', options=schemes)
     link((self, 'color_scheme'), (dropdown, 'value'))
     return dropdown
Example #24
0
    def _ui(self) -> List[W.Widget]:
        dropdown = W.Dropdown(
            description="Edge Type", options=list(EDGE_TYPE_OPTIONS.items())
        )

        T.link((self, "value"), (dropdown, "value"))

        return [dropdown]
Example #25
0
    def __init__(self, q):
        self.widget = QuantityText(q)
        self.qvalue = q

        traitlets.link(
            (self.widget, "value"),
            (self, "qvalue"),
        )
Example #26
0
def index():
    slider_private = ipywidgets.FloatSlider(value=2,
                                            description='private slider')
    traitlets.link((slider_shared, 'value'), (slider_private, 'value'))
    return render_template('example1.html',
                           slider1=slider_private,
                           slider2=slider_shared,
                           widgets=[slider_private, slider_shared])
Example #27
0
 def _make_commit_selector(self):
     selector = ipyw.Dropdown(
         description="Commit:",
         options=self._get_commit_selector_options()
         if self.project_selector.options else {},
     )
     trt.link((selector, "value"), (self, "selected_commit"))
     return selector
Example #28
0
    def _ui(self) -> List[W.Widget]:
        checkboxes = []
        for attr, value in NODESIZE_OPTIONS_OPTIONS.items():
            cb = W.Checkbox(description=attr.replace("_", " ").title())
            T.link((self, attr), (cb, "value"))
            checkboxes.append(cb)

        return checkboxes
Example #29
0
    def _ui(self) -> List[W.Widget]:

        sliders = []
        for trait in self._traits:
            slider = W.FloatSlider(description=f"{trait.title()} Padding")
            T.link((self, trait), (slider, "value"))
            sliders.append(slider)
        return sliders
Example #30
0
    def __init__(self, has_traits, name):
        self.has_traits = has_traits
        trait = has_traits.traits()[name]

        widg = self.make_widg(trait, getattr(self.has_traits, trait.name))
        link((has_traits, name), (widg, "value"))

        super().__init__([widg])
Example #31
0
def kerbal_lpg() -> SysML2LabeledPropertyGraph:
    new_lpg = SysML2LabeledPropertyGraph()
    client = kerbal_model_loaded_client()
    trt.link(
        (client, "model"),
        (new_lpg, "model"),
    )
    return new_lpg
Example #32
0
 def __init__(self, *args, **kwargs):
     if kwargs.get('layout') is None:
         kwargs['layout'] = self._default_layout()
     super(Figure, self).__init__(*args, **kwargs)
     self._map.map_type = self.map_type
     link((self._map, 'map_type'), (self, 'map_type'))
     self._map.mouse_handling = self.mouse_handling
     link((self._map, 'mouse_handling'), (self, 'mouse_handling'))
Example #33
0
 def output_panel(self):
     download_link = HTML(value="")
     link((self, "download_link"), (download_link, "value"))
     results_table = HTML(value="")
     link((self, "results_table"), (results_table, "value"))
     content = VBox(children=[download_link, results_table])
     return ControlPanel(title="Results:", children=[content], border_width=2, border_radius=4, margin=10, padding=0)
     """<div style="height:100px;width:200px;overflow:auto;border:8px solid yellowgreen;padding:2%">This </div>"""
Example #34
0
 def __init__(self, scene, camera, controls=None, antialias=False, alpha=False, **kwargs):
     super(Renderer, self).__init__(
         scene=scene,
         camera=camera,
         controls=controls or [],
         _antialias=antialias,
         _alpha=alpha,
         **kwargs)
     link((self, 'width'), (self, '_width'))
     link((self, 'height'), (self, '_height'))
def gen_widget(anim):
    viewer = AnimationViewer(anim)
    clear_output(True)
    anim_widget = AnimationWidget()
    anim_widget.loop = True
    button = ToggleButton(description="run", default=False)
    link((button, 'value'), (anim_widget, 'run'))
    display(anim_widget)
    display(viewer.image)
    display(button)
    anim_widget.observe(lambda value: viewer.update(value["new"]), names="value")
Example #36
0
    def __init__(self, nrows, ncols, make_widget, description=u"", transform=None):
        """
        Create a :class:`Grid` widget.

        INPUT:

        - ``nrows``, ``ncols`` -- number of rows and columns in the grid

        - ``make_widget`` -- a function of two arguments ``(i,j)``
          returning the widget to be placed at position ``(i,j)``.

        - ``description`` -- an optional label.

        - ``transform`` -- an optional transformation, see :class:`TransformWidget`.

        EXAMPLES::

            sage: from sage.repl.ipython_kernel.widgets import Grid, EvalText
            sage: w = Grid(2, 2, lambda i,j: EvalText(str(j+4*i)),
            ....:         description="2x2 matrix", transform=matrix)
            sage: w
            Grid(value=[[0, 1], [4, 5]], children=(Label(value=u'2x2 matrix'), VBox(children=(EvalText(value=u'0'), EvalText(value=u'4'))), VBox(children=(EvalText(value=u'1'), EvalText(value=u'5')))))
            sage: w.get_interact_value()
            [0 1]
            [4 5]

        TESTS::

            sage: w = Grid(0, 1, lambda i,j: EvalText())
            Traceback (most recent call last):
            ...
            ValueError: Grid requires a positive number of rows and columns
        """
        if nrows < 1 or ncols < 1:
            raise ValueError("Grid requires a positive number of rows and columns")
        super(Grid, self).__init__(transform=transform)

        label = Label(description)
        link((label, "value"), (self, "description"))

        self.cols = []
        for j in range(ncols):
            col = VBox()
            widgets = []
            for i in range(nrows):
                w = make_widget(i, j)
                w.observe(self._update, names="value")
                widgets.append(w)
            col.children = widgets
            self.cols.append(col)
        self.children = [label] + self.cols
        self._update()
Example #37
0
def create_settings(box):
    "Creates a widget Container for settings and info of a particular slider."
    _, slider, sl_units = box.children

    enable = widgets.Checkbox(value=box.visible, width="3ex")
    link((box, 'visible'), (enable, 'value'))

    def slider_link(obj, attr):
        "Function to link one object to an attr of the slider."
        # pylint: disable=unused-argument
        def link_fn(name, new_value):
            "How to update the object's value given min/max on the slider. "
            if new_value >= slider.max:
                slider.max = new_value
            # if any value is greater than the max, the max slides up
            # however, this is not held true for the minimum, because
            # during typing the max or value will grow, and we don't want
            # to permanently anchor the minimum to unfinished typing
            if attr == "max" and new_value <= slider.value:
                if slider.max >= slider.min:
                    slider.value = new_value
                else:
                    pass  # bounds nonsensical, probably because we picked up
                          # a small value during user typing.
            elif attr == "min" and new_value >= slider.value:
                slider.value = new_value
            setattr(slider, attr, new_value)
            slider.step = (slider.max - slider.min)/24.0
        obj.on_trait_change(link_fn, "value")
        link((slider, attr), (obj, "value"))

    text_html = "<span class='form-control' style='width: auto;'>"
    setvalue = widgets.FloatText(value=slider.value,
                                 description=slider.description)
    slider_link(setvalue, "value")
    fromlabel = widgets.HTML(text_html + "from")
    setmin = widgets.FloatText(value=slider.min, width="10ex")
    slider_link(setmin, "min")
    tolabel = widgets.HTML(text_html + "to")
    setmax = widgets.FloatText(value=slider.max, width="10ex")
    slider_link(setmax, "max")

    units = widgets.Label()
    units.width = "6ex"
    units.font_size = "1.165em"
    link((sl_units, 'value'), (units, 'value'))
    descr = widgets.HTML(text_html + slider.varkey.descr.get("label", ""))
    descr.width = "40ex"

    return widgets.HBox(children=[enable, setvalue, units, descr,
                                  fromlabel, setmin, tolabel, setmax],
                        width="105ex")
Example #38
0
    def _make_pre_widget(self, description, values):
        box = widgets.HBox()
        box.description = description
        text = widgets.Label(value=description)
        style = {'button_width': 'initial'}
        toggles = widgets.ToggleButtons(options=values, style=style)
        # Vertically align text and toggles.
        box.layout.align_items = 'center'
        box.children = [text, toggles]
        box.add_traits(value=Any(sync=True, default_value=toggles.value))

        link((box, 'value'), (toggles, 'value'))
        return box
Example #39
0
    def __init__(self, coordinate_frames, topology, width=500, height=500):
        '''Display a trajectory in the IPython notebook.

        :param list coordinate_frames: A list containing the positions of the atoms (as np.ndarray) for each frame.
        :param dict topology: A dictionary specifying the topology

        .. seealso:: :class:`MolecularViewer`

        '''
        self.coordinate_frames = coordinate_frames
        super(TrajectoryViewer, self).__init__(coordinate_frames[0], topology, width=width, height=height)

        self.controls = TrajectoryControls(len(coordinate_frames))
        link((self, 'frame'), (self.controls, 'frame'))
    def make_controls(self):
        self.playbutton = ipy.Play(value=0,
                                   min=0,
                                   max=self.traj.num_frames-1)

        self.slider = ipy.IntSlider(value_selects='framenum', value=0,
                                    description='Frame:', min=0, max=len(self.traj)-1,
                                    readout=False)
        self.readout = ipy.HTML(value='/%d' % (self.traj.num_frames - 1))
        self.annotation = ipy.HTML()

        traitlets.link((self.playbutton, 'value'), (self.slider, 'value'))
        traitlets.link((self.slider, 'value'), (self, 'current_frame'))
        return VBox((self.annotation,
                     HBox((self.playbutton, self.slider, self.readout))))
Example #41
0
def modelcontrolpanel(model, *args, **kwargs):
    """Easy model control in IPython / Jupyter

    Like interact(), but with the ability to control sliders and their ranges
    live. args and kwargs are passed on to interact()
    """

    sliders = model.interact(*args, **kwargs)
    sliderboxes = []
    for sl in sliders.children:
        cb = widgets.Checkbox(value=True)
        unit_latex = sl.varkey.unitstr
        if unit_latex:
            unit_latex = "$\scriptsize"+unit_latex+"$"
        units = widgets.Latex(value=unit_latex)
        units.font_size = "1.16em"
        box = widgets.HBox(children=[cb, sl, units])
        link((box, 'visible'), (cb, 'value'))
        sliderboxes.append(box)

    widgets_css = widgets.HTML("""<style>
    [style="font-size: 1.16em;"] { padding-top: 0.25em; }
    [style="width: 3ex; font-size: 1.165em;"] { padding-top: 0.2em; }
    .widget-numeric-text { width: auto; }
    .widget-numeric-text .widget-label { width: 20ex; }
    .widget-numeric-text .form-control { background: #fbfbfb; width: 8.5ex; }
    .widget-slider .widget-label { width: 20ex; }
    .widget-checkbox .widget-label { width: 15ex; }
    .form-control { border: none; box-shadow: none; }
    </style>""")
    settings = [widgets_css]
    for sliderbox in sliderboxes:
        settings.append(create_settings(sliderbox))
    # model_latex = "$"+model.latex(show_subs=False)+"$"
    # model_eq = widgets.Latex(model_latex)
    tabs = widgets.Tab(children=[widgets.Box(children=sliderboxes,
                                             padding="1.25ex"),
                                 widgets.Box(children=settings,
                                             padding="1.25ex")])
                                # TODO: fix model equation display
                                # widgets.Box(children=[model_eq],
                                #             padding="1.25ex")])

    tabs.set_title(0, 'Variable Sliders')
    tabs.set_title(1, 'Slider Settings')
    #tabs.set_title(2, 'Model Equations')

    return tabs
Example #42
0
 def assemble(self):
     guide = self.guide
     wigs = self.wigs
     vertical = []
     for wig in wigs:
         svg = wig.svg = canvas.SVGCanvasWidget()
         vertical.append(svg)
         svg.width = self.width
         svg.height = self.height
         svg.set_view_box(0, 0, self.width, self.height)
         svg.add_style("background-color", "cyan")
         traitlets.link((guide, "start_position"), (wig, "start_position"))
         traitlets.link((guide, "end_position"), (wig, "end_position"))
     vertical.append(self.guide.assembly)
     self.assembly = widgets.VBox(children=vertical)
     wig.on_trait_change(self.draw, "start_position")
     self.assembled = True
Example #43
0
def create_shelf_view(model, columns, types):
    opts = list(zip(["-"] + columns, [""] + columns))
    column_view = w.Dropdown(options=opts, description=model.shelf_name, value="")
    type_view = w.Dropdown(options={"Q": "Q", "T": "T", "O": "O", "N": "N"}, value="Q")
    shelf_view = w.HBox([column_view, type_view])

    def on_column_changed(name, value):
        if value == "":
            type_view.value = "Q"
        else:
            index = columns.index(value)
            type_view.value = types[index]

    column_view.on_trait_change(on_column_changed, "value")
    T.link((model, "name"), (column_view, "value"))
    T.link((type_view, "value"), (model, "type"))
    return shelf_view
def multi_text_match():
    t = widgets.Text()
    submitted = []
    s_box = widgets.VBox()

    def update_s_box():
        s_box.children = tuple(map(list_entry, submitted))

    @t.on_submit
    def on_submit(sender):
        if not t.value:
            return
        submitted.append(t.value)
        update_s_box()
        t.value = ''

    def list_entry(value):
        e = widgets.HTML(
            html.escape(value),
            padding='5px',
            background_color='gray',
            color='white')
        rm_button = widgets.Button(
            description='✖',
            margin='5px',
            padding='1px')
        traitlets.link((t, 'disabled'), (rm_button, 'disabled'))
        le = widgets.HBox(children=[e, rm_button])

        @rm_button.on_click
        def remove(b):
            submitted.remove(value)
            update_s_box()
        return le

    root = widgets.VBox(children=[s_box, t])
    root.add_traits(
        value=traitlets.Any(),
        disabled=traitlets.Any(),
        filter_type=traitlets.Any())
    root.value = submitted
    root.disabled = False
    root.filter_type = 'text'
    traitlets.link((root, 'disabled'), (t, 'disabled'))
    return root
    def list_entry(value):
        e = widgets.HTML(
            html.escape(value),
            padding='5px',
            background_color='gray',
            color='white')
        rm_button = widgets.Button(
            description='✖',
            margin='5px',
            padding='1px')
        traitlets.link((t, 'disabled'), (rm_button, 'disabled'))
        le = widgets.HBox(children=[e, rm_button])

        @rm_button.on_click
        def remove(b):
            submitted.remove(value)
            update_s_box()
        return le
Example #46
0
def test_player_link_to_ipywidgets():
    traj = pt.datafiles.load_tz2()
    view = nv.show_pytraj(traj)

    int_text = IntText(2)
    float_text = BoundedFloatText(40, min=10)
    HBox([int_text, float_text])
    link((int_text, 'value'), (view.player, 'step'))
    link((float_text, 'value'), (view.player, 'delay'))

    assert view.player.step == 2
    assert view.player.delay == 40

    float_text.value = 100
    assert view.player.delay == 100

    float_text.value= 0.00
    # we set min=10
    assert view.player.delay == 10
Example #47
0
 def __init__(self, *args, **kwargs):
     super(ExonExplorer, self).__init__(*args, **kwargs)
     self.genome_zoom = genome_bar.GenomeBar()
     z = self.zoom_svg = self.canvas()
     z.watch_event = "mousemove"
     z.default_event_callback = self.zoom_callback
     self.genome_guide = genome_bar.GenomeBar()
     g = self.guide_svg = self.canvas()
     g.watch_event = "mousemove click"
     g.default_event_callback = self.guide_callback
     self.info = widgets.Text(value="", width=500)
     self.assembly = widgets.VBox(children=[self.zoom_svg,
                                            self.guide_svg,
                                            self.info])
     self.data = gtf_format.GTFData()
     self.name_to_feature = {}
     self.select_name = "SELECTION"
     self.selected_svg_x = None
     traitlets.link((self, "start_position"), (self.genome_zoom, "minLocation"))
     traitlets.link((self, "end_position"), (self.genome_zoom, "maxLocation"))
    def __init__(self, mol):
        super(ResidueSelector, self).__init__(mol)

        self.selection_type = ipy.Dropdown(description='Clicks select:',value=self.viewer.selection_type,
                                           options=('Atom', 'Residue', 'Chain'))

        traitlets.link((self.selection_type, 'value'), (self.viewer, 'selection_type'))

        self.residue_listname = ipy.HTML('<b>Selected residues:</b>')
        self.residue_list = ipy.SelectMultiple(options=list(), height=150)
        traitlets.directional_link((self.viewer, 'selected_atom_indices'), (self.residue_list, 'options'), self._atoms_to_residues)
        self.residue_list.observe(self.remove_atomlist_highlight, 'value')
        self.atom_list.observe(self.remove_reslist_highlight, 'value')

        self.subtools.children = [ipy.HBox([self.select_all_atoms_button, self.select_none])]
        self.toolpane.children = [self.selection_type,
                                  self.atom_listname,
                                  self.atom_list,
                                  self.residue_listname,
                                  self.residue_list]
Example #49
0
 def interact(self, **kwargs):
     c = []
     for name, abbrev in kwargs.items():
         default = getattr(self, name)
         widget = _widget_from_abbrev(abbrev, default)
         if not widget.description:
             widget.description = name
         widget.link = link((widget, 'value'), (self, name))
         c.append(widget)
     cont = Box(children=c)
     return cont
Example #50
0
 def slider_link(obj, attr):
     def link_fn(name, new_value):
         if new_value >= slider.max:
             slider.max = new_value
         # if any value is greater than the max, the max slides up
         # however, this is not held true for the minimum, because
         # during typing the max or value will grow, and we don't want
         # to permanently anchor the minimum to unfinished typing
         if attr is "max" and new_value <= slider.value:
             if slider.max >= slider.min:
                 slider.value = new_value
             else:
                 pass  # bounds nonsensical, probably because we picked up
                       # a small value during user typing.
         elif attr is "min" and new_value >= slider.value:
             slider.value = new_value
         setattr(slider, attr, new_value)
         slider.step = (slider.max - slider.min)/24.0
     obj.on_trait_change(link_fn, "value")
     link((slider, attr), (obj, "value"))
    def draw(self, width=500, height=500, show_2dhydrogens=None, display=False):
        """ Visualize this molecule (Jupyter only).

        Creates a 3D viewer, and, for small molecules, a 2D viewer).

        Args:
            width (int): width of the viewer in pixels
            height (int): height of the viewer in pixels
            show_2dhydrogens (bool): whether to show the hydrogens in 2d (default: True if there
                   are 10 or less heavy atoms, false otherwise)
            display (bool): immediately display this viewer

        Returns:
            moldesign.ui.SelectionGroup
        """

        viz2d = None
        if self.num_atoms < 40:

            viz2d = self.draw2d(width=width, height=height,
                                display=False,
                                show_hydrogens=show_2dhydrogens)
            viz3d = self.draw3d(width=width, height=height,
                                display=False)
            traitlets.link((viz3d, 'selected_atom_indices'), (viz2d, 'selected_atom_indices'))
            views = ipy.HBox([viz2d, viz3d])
        else:
            views = self.draw3d(display=False)

        atom_inspector = uibase.components.AtomInspector()
        traitlets.directional_link(
            (viz2d or views, 'selected_atom_indices'),
            (atom_inspector, 'value'),
            lambda selected_atom_indices: atom_inspector.indices_to_value(selected_atom_indices, self.atoms)
        )

        displayobj = uibase.SelectionGroup([views, atom_inspector])

        if display:
            IPython.display.display(displayobj)
        return displayobj
Example #52
0
    def __init__(self, *args, **kwd):
        super(ToggleGo, self).__init__(*args, **kwd)
        self._go_container = widgets.HBox()
        traits = {
            'visible': Bool(),
            '_visible_layout_display': Unicode(allow_none=True, default_value=None)
        }
        self._go_container.add_traits(**traits)
        self._go_container.observe(_set_visibility, 'visible')
        self._go_button = widgets.Button(description="Lock settings and Go!",
                                         disabled=True)
        self._go_button.layout.display = 'none'
        self._change_settings = widgets.Button(description="Unlock settings",
                                               disabled=True)
        self._change_settings.layout.display = 'none'
        self._go_container.children = [self._go_button, self._change_settings]
        self._progress_container = widgets.Box()
        self._progress_bar = widgets.FloatProgress(min=0, max=1.0,
                                                   step=0.01, value=0.0)
        self._progress_bar.layout.display = 'none'
        self._progress_container.children = [self._progress_bar]
        # we want the go button to be in a container below the
        #  ToggleContainer's container -- actually, no, want these
        # buttons controlled by toggle...wait, no, I really do want that, but
        # I also want to tie their visibility to the toggle.
        kids = list(self.children)
        kids.append(self._go_container)
        kids.append(self._progress_container)
        self.children = kids

        # Tie visibility of go button to toggle state. Needs to be separate
        # from the container.
        link((self._go_container, str('visible')), (self.toggle, str('value')))

        self._go_button.on_click(self.go())
        self._change_settings.on_click(self.unlock())

        # Tie self._state_monitor to both go button and color of toggle button
        self._state_monitor.on_trait_change(self.state_change_handler(),
                                            str('value'))
        self._state_monitor.on_trait_change(set_color_for(self), str('value'))
    def __init__(self, format=None, *args, **kwargs):
        description = kwargs.pop('description', 'FloatSlider')
        min = kwargs.setdefault('min', 0.0)
        max = kwargs.setdefault('max', 10.0)
        self.formatstring = format
        self.header = ipy.HTML()
        self.readout = ipy.Text(width=100)
        self.readout.on_submit(self.parse_value)

        kwargs.setdefault('readout', False)
        self.slider = ipy.FloatSlider(*args, **kwargs)
        self.minlabel = ipy.HTML(u'<font size=1.5>{}</font>'.format(self.formatstring.format(min)))
        self.maxlabel = ipy.HTML(u'<font size=1.5>{}</font>'.format(self.formatstring.format(max)))
        self.sliderbox = ipy.HBox([self.minlabel, self.slider, self.maxlabel])
        traitlets.link((self, 'description'), (self.header, 'value'))
        traitlets.link((self, 'value'), (self.slider, 'value'))
        self.description = description
        self.update_readout()
        super(ReadoutFloatSlider, self).__init__([self.header,
                                                  self.readout,
                                                  self.sliderbox])
def num_range_filter():
    c_min = widgets.Checkbox(description='Min:', value=False)
    f_min = widgets.FloatText()
    l_min = traitlets.link((c_min, 'value'), (f_min, 'visible'))
    min_box = widgets.HBox(children=[c_min, f_min])

    c_max = widgets.Checkbox(description='Max:', value=False)
    f_max = widgets.FloatText()
    l_max = traitlets.link((c_max, 'value'), (f_max, 'visible'))
    max_box = widgets.HBox(children=[c_max, f_max])

    def min_change(name, value):
        if f_max.value < value:
            f_max.value = value
    f_min.on_trait_change(min_change, 'value')
            
    def max_change(name, value):
        if f_min.value > value:
            f_min.value = value
    f_max.on_trait_change(max_change, 'value')
            
    root = widgets.VBox(children=[min_box, max_box])
    root.add_traits(
        min_enabled=traitlets.Any(),
        min_value=traitlets.Any(),
        max_enabled=traitlets.Any(),
        max_value=traitlets.Any(),
        filter_type=traitlets.Any()
    )
    root.filter_type = 'num_range'

    traitlets.link((c_min, 'value'), (root, 'min_enabled'))
    traitlets.link((f_min, 'value'), (root, 'min_value'))

    traitlets.link((c_max, 'value'), (root, 'max_enabled'))
    traitlets.link((f_max, 'value'), (root, 'max_value'))

    return root

    
Example #55
0
 def slider_link(obj, attr):
     "Function to link one object to an attr of the slider."
     # pylint: disable=unused-argument
     def link_fn(name, new_value):
         "How to update the object's value given min/max on the slider. "
         if new_value >= slider.max:
             slider.max = new_value
         # if any value is greater than the max, the max slides up
         # however, this is not held true for the minimum, because
         # during typing the max or value will grow, and we don't want
         # to permanently anchor the minimum to unfinished typing
         if attr == "max" and new_value <= slider.value:
             if slider.max >= slider.min:
                 slider.value = new_value
             else:
                 pass  # bounds nonsensical, probably because we picked up
                       # a small value during user typing.
         elif attr == "min" and new_value >= slider.value:
             slider.value = new_value
         setattr(slider, attr, new_value)
         slider.step = (slider.max - slider.min)/24.0
     obj.on_trait_change(link_fn, "value")
     link((slider, attr), (obj, "value"))
Example #56
0
    def _make_spin_box(self):
        checkbox_spin = Checkbox(self.spin, description='spin')
        spin_x_slide = IntSlider(
            self._spin_x,
            min=-1,
            max=1,
            description='spin_x')
        spin_y_slide = IntSlider(
            self._spin_y,
            min=-1,
            max=1,
            description='spin_y')
        spin_z_slide = IntSlider(
            self._spin_z,
            min=-1,
            max=1,
            description='spin_z')
        spin_speed_slide = FloatSlider(
            self._spin_speed,
            min=0,
            max=0.2,
            step=0.001,
            description='spin speed')
        # spin
        link((checkbox_spin, 'value'), (self, 'spin'))
        link((spin_x_slide, 'value'), (self, '_spin_x'))
        link((spin_y_slide, 'value'), (self, '_spin_y'))
        link((spin_z_slide, 'value'), (self, '_spin_z'))
        link((spin_speed_slide, 'value'), (self, '_spin_speed'))

        spin_box= VBox([checkbox_spin,
                   spin_x_slide,
                   spin_y_slide,
                   spin_z_slide,
                   spin_speed_slide])
        spin_box = _relayout_master(spin_box, width='75%')
        return spin_box
    def __init__(self, mol):
        super().__init__(mol)

        self.selection_type = ipy.Dropdown(description='Clicks select:',
                                           value=self.viewer.selection_type,
                                           options=('Atom', 'Residue', 'Chain'))

        traitlets.link((self.selection_type, 'value'), (self.viewer, 'selection_type'))

        self.residue_listname = ipy.Label('Selected residues:', layout=ipy.Layout(width='100%'))
        self.residue_list = ipy.SelectMultiple(options=list(), height='150px')
        self.viewer.observe(self._update_reslist, 'selected_atom_indices')

        self.residue_list.observe(self.remove_atomlist_highlight, 'value')
        self.atom_list.observe(self.remove_reslist_highlight, 'value')

        self.subtools.children = [self.representation_buttons]
        self.subtools.layout.flex_flow = 'column'
        self.toolpane.children = [self.selection_type,
                                  HBox([self.select_all_atoms_button, self.select_none]),
                                  self.atom_listname,
                                  self.atom_list,
                                  self.residue_listname,
                                  self.residue_list]
Example #58
0
    def test_unlink(self):
        """Verify two linked traitlets can be unlinked."""

        # Create two simple classes with Int traitlets.
        class A(HasTraits):
            value = Int()
        a = A(value=9)
        b = A(value=8)

        # Connect the two classes.
        c = link((a, 'value'), (b, 'value'))
        a.value = 4
        c.unlink()

        # Change one of the values to make sure they don't stay in sync.
        a.value = 5
        self.assertNotEqual(a.value, b.value)
Example #59
0
    def __init__(self, *args, **kwargs):
        if kwargs.get('layout') is None:
            kwargs['layout'] = self._default_layout()
        super(Figure, self).__init__(*args, **kwargs)
        self._map.map_type = self.map_type
        link((self._map, 'map_type'), (self, 'map_type'))

        self._map.tilt = self.tilt
        link((self._map, 'tilt'), (self, 'tilt'))

        self._map.mouse_handling = self.mouse_handling
        link((self._map, 'mouse_handling'), (self, 'mouse_handling'))
Example #60
0
    def test_callbacks(self):
        """Verify two linked traitlets have their callbacks called once."""

        # Create two simple classes with Int traitlets.
        class A(HasTraits):
            value = Int()

        class B(HasTraits):
            count = Int()

        a = A(value=9)
        b = B(count=8)

        # Register callbacks that count.
        callback_count = []

        def a_callback(name, old, new):
            callback_count.append("a")

        a.on_trait_change(a_callback, "value")

        def b_callback(name, old, new):
            callback_count.append("b")

        b.on_trait_change(b_callback, "count")

        # Connect the two classes.
        c = link((a, "value"), (b, "count"))

        # Make sure b's count was set to a's value once.
        self.assertEqual("".join(callback_count), "b")
        del callback_count[:]

        # Make sure a's value was set to b's count once.
        b.count = 5
        self.assertEqual("".join(callback_count), "ba")
        del callback_count[:]

        # Make sure b's count was set to a's value once.
        a.value = 4
        self.assertEqual("".join(callback_count), "ab")
        del callback_count[:]