Python traitlets.link() Examples

The following are 10 code examples of traitlets.link(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module traitlets , or try the search function .
Example #1
Source File: selection.py    From notebook-molecular-visualization with Apache License 2.0 6 votes vote down vote up
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 #2
Source File: components.py    From notebook-molecular-visualization with Apache License 2.0 6 votes vote down vote up
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(layout=ipy.Layout(width='100px'))
        self.readout.on_submit(self.parse_value)

        kwargs.setdefault('readout', False)
        self.slider = ipy.FloatSlider(*args, **process_widget_kwargs(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 = 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().__init__([self.header,
                                                  self.readout,
                                                  self.sliderbox]) 
Example #3
Source File: widgets.py    From paramnb with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        self._select = Dropdown(*args,**kwargs)
        self._edit = Button(description='...',
                            layout=Layout(width='15px'))
        self._composite = HBox([self._select,self._edit])
        super(DropdownWithEdit, self).__init__()
        self.layout = self._composite.layout
        # so that others looking at this widget's value get the
        # dropdown's value
        traitlets.link((self._select,'value'),(self,'value'))
        self._edit.on_click(lambda _: editor(self._select.value))
        self._select.observe(lambda e: self._set_editable(e['new']),'value')
        self._set_editable(self._select.value) 
Example #4
Source File: trajectory_viewer.py    From notebook-molecular-visualization with Apache License 2.0 5 votes vote down vote up
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 #5
Source File: model.py    From lddmm-ot with MIT License 5 votes vote down vote up
def show_training(self, div_id, div_costs_curve, cost_values) :
		#div_id = self.show(*args, **kwargs)
		
		def change_frame(w) :
			#print(w)
			updates = self.get_frame(w-1)
			script = ''
			for i in range(len(updates[0])) :
				jupdate      = json.dumps(updates[0][i], cls=utils.PlotlyJSONEncoder)
				jupdate_cost = json.dumps(dict(x = [[w]], y = [[cost_values[w-1]]]), cls=utils.PlotlyJSONEncoder)
				script = script \
					+ 'Plotly.restyle("{id}", {update}, [{index}]);'.format(
					id=div_id,
					update=jupdate, index = updates[1][i]) \
					+ 'Plotly.restyle("{id}", {update}, [{index}]);'.format(
					id=div_costs_curve,
					update=jupdate_cost, index = 1)
			update_str = (
				'<script type="text/javascript">' +
				'window.PLOTLYENV=window.PLOTLYENV || {{}};' +
				'window.PLOTLYENV.BASE_URL="' + 'https://plot.ly' + '";' +
				'{script}' +
				'</script>').format(script=script)
			#print(script)
			display(HTML(update_str))
		#print(self.frames)
		maxframe = len(self.frames) - 1
		play = Play(value=maxframe)
		slider = IntSlider(min=1, max=maxframe, step=1, value=maxframe,continuous_update=False)
		slider.layout.width = '100%'
		#jslink((play, 'value'), (slider, 'value'))
		traitlets.link((play, 'value'), (slider, 'value'))
		hb = HBox([play, slider])
		slider.observe((lambda iteration : change_frame(iteration['new'])), names='value')
		change_frame(maxframe)
		#play.observe((lambda iteration : print(iteration['new'])), names='value')
		#display(hb)
		return hb 
Example #6
Source File: interactive_riemannian_geometry.py    From lddmm-ot with MIT License 5 votes vote down vote up
def link_widgets(self) :
		self.w_manifold_type.observe(self.on_manifold_type_change, names='value')
		self.w_create_manifold.on_click(self.create_manifold)
		self.w_choose_hypertemplate.on_click(self.choose_hypertemplate)
		self.w_choose_data.on_click(self.choose_data)
		self.w_create_model.on_click(self.create_model)
		self.w_train.on_click(self.train_model)
		self.w_show.on_click(self.show_model)
		traitlets.link((self.w_niterations, 'value'), (self.w_iterations, 'max'))
		
		# Energy update
		self.w_template_type.observe(self.update_energy_latex, names='value')
		self.w_reg_hypertemplate.observe(self.update_energy_latex, names='value')
		self.w_sigma_reg_hypertemplate.observe(self.update_energy_latex, names='value')
		self.w_gamma_V0.observe(self.update_energy_latex, names='value')
		self.w_sigma_V0.observe(self.update_energy_latex, names='value')
		self.w_shooting_dim_constraint.observe(self.update_energy_latex, names='value')
		self.w_gamma_V.observe(self.update_energy_latex, names='value')
		self.w_frechet_exponent.observe(self.update_energy_latex, names='value')
		self.w_data_attachment.observe(self.update_energy_latex, names='value')
		self.w_gamma_W.observe(self.update_energy_latex, names='value')
		
		
		# Algorithm update
		self.w_X0_gradient_distribution.observe(self.update_algorithm_latex, names='value')
		self.w_X0_descent_mode.observe(self.update_algorithm_latex, names='value')
		self.w_X0_descent_speed.observe(self.update_algorithm_latex, names='value')
		self.w_Xi_gradient_distribution.observe(self.update_algorithm_latex, names='value')
		self.w_Xi_descent_mode.observe(self.update_algorithm_latex, names='value')
		self.w_Xi_descent_speed.observe(self.update_algorithm_latex, names='value')
		self.w_Ei_gradient_distribution.observe(self.update_algorithm_latex, names='value')
		self.w_Ei_descent_mode.observe(self.update_algorithm_latex, names='value')
		self.w_Ei_descent_speed.observe(self.update_algorithm_latex, names='value')
		self.w_descent_stopping_criterion.observe(self.update_algorithm_latex, names='value')
		self.w_niterations.observe(self.update_algorithm_latex, names='value')
		self.w_descent_threshold.observe(self.update_algorithm_latex, names='value')
		
		
		self.update_energy_latex()
		self.update_algorithm_latex() 
Example #7
Source File: widgets.py    From gpkit with MIT License 4 votes vote down vote up
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 #8
Source File: pylab.py    From ipyvolume with MIT License 4 votes vote down vote up
def figure(
    key=None,
    width=400,
    height=500,
    lighting=True,
    controls=True,
    controls_vr=False,
    controls_light=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(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 controls_light:
            globals()['controls_light']()
        if debug:
            show = ipywidgets.ToggleButtons(options=["Volume", "Back", "Front", "Coordinate"])
            current.container.children += (show,)
            # ipywidgets.jslink((current.figure, 'show'), (show, 'value'))
            traitlets.link((current.figure, 'show'), (show, 'value'))
    return current.figure 
Example #9
Source File: atomgroups.py    From notebook-molecular-visualization with Apache License 2.0 4 votes vote down vote up
def draw(group, width=None, height=None, show_2dhydrogens=None, display=False,
         **kwargs):
    """ Visualize this molecule (Jupyter only).

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

    Args:
        width (str or int): css width spec (if str) or width in pixels (if int)
        height (str or int): css height spec (if str) or height in pixels (if int)
        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
        **kwargs (dict): keyword arguments for GeometryViewer only

    Returns:
        moldesign.ui.SelectionGroup
    """

    atom_inspector = AtomInspector(group.atoms)

    if group.num_atoms < 40:
        width = width if width is not None else 500
        height = height if height is not None else 500
        viz2d = draw2d(group, width=width, height=height,
                       display=False,
                       show_hydrogens=show_2dhydrogens)
        viz3d = draw3d(group, width=width, height=height,
                       display=False, **kwargs)
        traitlets.link((viz3d, 'selected_atom_indices'), (viz2d, 'selected_atom_indices'))
        views = HBox([viz2d, viz3d])
    else:
        viz2d = None
        viz3d = draw3d(group, display=False, **kwargs)
        views = viz3d

    traitlets.link((viz3d, 'selected_atom_indices'),
                   (atom_inspector, 'selected_atom_indices'))

    if viz2d:
        traitlets.link((viz2d, 'selected_atom_indices'),
                       (atom_inspector, 'selected_atom_indices'))

    displayobj = viewers.ViewerContainer([views, atom_inspector],
                                         viewer=viz3d,
                                         graphviewer=viz2d)

    if display:
        dsp(displayobj)
    return displayobj 
Example #10
Source File: orbital_viewer.py    From notebook-molecular-visualization with Apache License 2.0 4 votes vote down vote up
def _make_ui_pane(self, hostheight):
        layout = ipy.Layout(width='325px',
                            height=str(int(hostheight.rstrip('px')) - 50) + 'px')
        #element_height = str(int(hostheight.rstrip('px')) - 125) + 'px'
        element_height = None
        # NOTE - element_height was used for the listbox-style orblist.
        #   HOWEVER ipywidgets 6.0 only displays those as a dropdown.
        #   This is therefore disabled until we can display listboxes again. -- AMV 7/16

        # Orbital set selector
        self.status_element = ipy.HTML(layout=ipy.Layout(width='inherit', height='20px'))
        orbtype_label = ipy.Label("Orbital set:")
        self.type_dropdown = ipy.Dropdown(options=list(self.wfn.orbitals.keys()))
        initialtype = 'canonical'
        if initialtype not in self.type_dropdown.options:
            initialtype = next(iter(self.type_dropdown.options.keys()))
        self.type_dropdown.value = initialtype
        self.type_dropdown.observe(self.new_orb_type, 'value')

        # List of orbitals in this set
        orblist_label = ipy.Label("Orbital:")
        self.orblist = ipy.Dropdown(options={None: None},
                                    layout=ipy.Layout(width=layout.width, height=element_height))
        traitlets.link((self.orblist, 'value'), (self, 'current_orbital'))

        # Isovalue selector
        isoval_label = ipy.Label('Isovalue:')
        self.isoval_selector = ipy.FloatSlider(min=0.0, max=0.075,
                                               value=0.01, step=0.00075,
                                               readout_format='.4f',
                                               layout=ipy.Layout(width=layout.width))
        traitlets.link((self.isoval_selector, 'value'), (self, 'isoval'))

        # Opacity selector
        opacity_label = ipy.Label('Opacity:')
        self.opacity_selector = ipy.FloatSlider(min=0.0, max=1.0,
                                               value=0.8, step=0.01,
                                               readout_format='.2f',
                                               layout=ipy.Layout(width=layout.width))
        traitlets.link((self.opacity_selector, 'value'), (self, 'orb_opacity'))

        # Resolution selector
        resolution_label = ipy.Label("Grid resolution:", layout=ipy.Layout(width=layout.width))
        self.orb_resolution = ipy.Text(layout=ipy.Layout(width='75px',
                                                         positioning='bottom'))
        self.orb_resolution.value = str(self.numpoints)
        self.resolution_button = ipy.Button(description='Update resolution')
        self.resolution_button.on_click(self.change_resolution)
        traitlets.directional_link((self, 'numpoints'), (self.orb_resolution, 'value'),
                                   transform=str)

        self.uipane = ipy.VBox([self.status_element,
                                orbtype_label, self.type_dropdown,
                                orblist_label, self.orblist,
                                isoval_label, self.isoval_selector,
                                opacity_label, self.opacity_selector,
                                resolution_label, self.orb_resolution, self.resolution_button])
        self.new_orb_type()
        self.type_dropdown.observe(self.new_orb_type, 'value')
        return self.uipane