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
        ]
Exemplo n.º 2
0
    def append_msg(self, msg, section=False):
        """ 
        Append a message in a new parragraph, with or without divider

        Args: 
            msg (str): the message to display
            section (bool, optional): add a Divider before the added message
            
        Return:
            self
        """

        self.show()
        if self.children[0]:
            current_children = self.children[:]
            if section:
                # As the list is mutable, and the trait is only triggered when
                # the children is changed, so have to create a copy.
                divider = Divider(class_='my-4', style='opacity: 0.22')

                # link Alert type with divider type
                directional_link((self, 'type'), (divider, 'type_'))
                current_children.extend(
                    [divider, v.Html(tag='p', children=[msg])])
                self.children = current_children

            else:
                current_children.append(v.Html(tag='p', children=[msg]))
                self.children = current_children
        else:
            self.add_msg(msg)

        return self
    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
Exemplo n.º 4
0
    def __init__(
        self,
        iterable_or_max,
        title='',
        format_str='%(current)d/%(max)d (%(percent)d%%) in %(elapsed).1f s, %(last_iter_time).2f s last iter; eta %(eta_avg).0f+-%(eta_stddev).0f s'
    ):
        super(ProgressBarIPyNb, self).__init__(iterable_or_max, title)
        self.format_str = format_str

        self.progress_w = iw.FloatProgress(min=0,
                                           max=100,
                                           value=30,
                                           width='100%')
        self.title_w = iw.HTML(
            '<h3 style="display: inline">%(title)s</h3>&nbsp;' % self)
        self.info_w = iw.HTML()
        self.log_last_w = iw.HTML()

        self.log_check_w = iw.Checkbox(value=False,
                                       visible=False,
                                       description='Show Log')
        self.log_w = iw.HTML()
        self.log_header_w = iw.HTML('<h2><small>Log messages</small></h2>')
        directional_link((self.log_check_w, 'value'), (self.log_w, 'visible'))
        directional_link((self.log_check_w, 'value'),
                         (self.log_header_w, 'visible'))

        self.container_w = iw.VBox([
            iw.HBox([self.title_w, self.info_w, self.log_last_w]),
            iw.HBox([self.progress_w, self.log_check_w]), self.log_header_w,
            self.log_w,
            iw.HBox(height=20)
        ])

        self.displayed = False
Exemplo n.º 5
0
    def __init__(self, mol):
        super().__init__(mol)

        self._atomset = collections.OrderedDict()

        self.atom_listname = ipy.Label('Selected atoms:',
                                       layout=ipy.Layout(width='100%'))
        self.atom_list = ipy.SelectMultiple(options=list(
            self.viewer.selected_atom_indices),
                                            layout=ipy.Layout(height='150px'))
        traitlets.directional_link((self.viewer, 'selected_atom_indices'),
                                   (self.atom_list, 'options'),
                                   self._atom_indices_to_atoms)

        self.select_all_atoms_button = ipy.Button(
            description='Select all atoms')
        self.select_all_atoms_button.on_click(self.select_all_atoms)

        self.select_none = ipy.Button(description='Clear all selections')
        self.select_none.on_click(self.clear_selections)

        self.representation_buttons = ipy.ToggleButtons(
            options=['stick', 'ribbon', 'auto', 'vdw'], value='auto')
        self.representation_buttons.observe(self._change_representation,
                                            'value')
Exemplo n.º 6
0
    def construct_child(self):
        if self.child_spawner is None:
            self.child_spawner = self.child_class(
                user = self.user,
                db   = self.db,
                hub  = self.hub,
                authenticator = self.authenticator,
                oauth_client_id = self.oauth_client_id,
                server = self._server,
                config = self.config,
                **self.child_config
                )
            # initial state will always be wrong since it will see *our* state
            self.child_spawner.clear_state()
            if self.child_state:
                self.child_spawner.load_state(self.child_state)

            # link traits common between self and child
            common_traits = (
                set(self.trait_names()) &
                set(self.child_spawner.trait_names()) -
                set(self.child_config.keys())
            )
            for trait in common_traits:
                directional_link((self, trait), (self.child_spawner, trait))
        return self.child_spawner
Exemplo n.º 7
0
 def __init__(self, members, *args, **kwargs):
     super(MultipleNetworks, self).__init__(*args, **kwargs)
     self.members = members
     self.member_list = []
     self.holders = []
     self.width_slider = s = widgets.IntSlider(value=self.svg_width, min=100, max=2000, step=10)
     traitlets.directional_link((s, "value"), (self, "svg_width"))
     self.boxes = b = self.make_boxes(self.members)
     self.assembly = widgets.VBox(children=[s,b])
Exemplo n.º 8
0
 def make_text_displays(self):
     self.row_text = widgets.Text(description="row", value="")
     self.row_text.width = "100px"
     self.col_text = widgets.Text(description="col", value="")
     self.col_text.width = "100px"
     sslider = self.size_slider = widgets.FloatSlider(value=550, min=550, max=3000,
         step=10, readout=False, width="100px")
     svg = self.svg
     traitlets.directional_link((sslider, "value"), (svg, "width"))
     traitlets.directional_link((sslider, "value"), (svg, "height"))
     assembly = widgets.HBox(children=[self.row_text, self.col_text, sslider])
     return assembly
Exemplo n.º 9
0
 def make_text_displays(self):
     self.row_text = widgets.Text(description="row", value="")
     self.row_text.layout.width = "200px"
     self.col_text = widgets.Text(description="col", value="")
     self.col_text.layout.width = "200px"
     sslider = self.size_slider = widgets.FloatSlider(value=550, min=550, max=3000,
         step=10, readout=False, width="100px")
     sslider.layout.width = "150px"
     svg = self.svg
     traitlets.directional_link((sslider, "value"), (svg, "svg_width"))
     traitlets.directional_link((sslider, "value"), (svg, "svg_height"))
     assembly = widgets.HBox(children=[self.row_text, self.col_text, sslider])
     return assembly
Exemplo n.º 10
0
 def debugging_display(self, tagline="debug message area for widget:", border='1px solid black'):
     if border:
         out = widgets.Output(layout={'border': border})
     else:
         out = widgets.Output()
     if tagline:
         with out:
             print (tagline)
     self.output = out
     status_text = widgets.Text(description="status:", value="")
     traitlets.directional_link((self, "status"), (status_text, "value"))
     error_text = widgets.Text(description="error", value="")
     traitlets.directional_link((self, "error_msg"), (error_text, "value"))
     assembly = widgets.VBox(children=[self, status_text, error_text, out])
     return assembly
Exemplo n.º 11
0
 def _link_dependent_props(self) -> None:
     """
     Ensure that RemoteKernelManager, when used as part of an EnterpriseGatewayApp,
     has certain necessary configuration stay in sync with the app's configuration.
     When RemoteKernelManager is used independently, this function is a no-op, and
     default values or configuration set on this class is used.
     """
     try:
         eg_instance = self.parent.parent
     except AttributeError:
         return
     dependent_props = [
         "authorized_users",
         "unauthorized_users",
         "port_range",
         "impersonation_enabled",
         "max_kernels_per_user",
         "client_envs",
         "inherited_envs",
         "yarn_endpoint",
         "alt_yarn_endpoint",
         "yarn_endpoint_security_enabled",
         "conductor_endpoint",
         "remote_hosts",
         "load_balancing_algorithm",
     ]
     self._links = [
         directional_link((eg_instance, prop), (self, prop))
         for prop in dependent_props
     ]
Exemplo n.º 12
0
    def test_link_different(self):
        """Verify two traitlets of different types can be linked together using link."""

        # 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)

        # Conenct the two classes.
        c = directional_link((a, 'value'), (b, 'count'))

        # Make sure the values are the same at the point of linking.
        self.assertEqual(a.value, b.count)

        # Change one the value of the source and check that it synchronizes the target.
        a.value = 5
        self.assertEqual(b.count, 5)
        # Change one the value of the target and check that it has no impact on the source
        b.value = 6
        self.assertEqual(a.value, 5)
Exemplo n.º 13
0
    def test_link_different(self):
        """Verify two traitlets of different types can be linked together using link."""

        # 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)

        # Conenct the two classes.
        c = directional_link((a, "value"), (b, "count"))

        # Make sure the values are the same at the point of linking.
        self.assertEqual(a.value, b.count)

        # Change one the value of the source and check that it synchronizes the target.
        a.value = 5
        self.assertEqual(b.count, 5)
        # Change one the value of the target and check that it has no impact on the source
        b.value = 6
        self.assertEqual(a.value, 5)
    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
Exemplo n.º 15
0
 def __init__(self, *args, **kwargs):
     super(LinkedExpressionNetwork, self).__init__(*args, **kwargs)
     self.network = dNetwork.NetworkDisplay()
     self.expression = dExpression.ExpressionDisplay()
     self.gene_button = self.make_button(u"\u21d3 Genes", self.gene_click)
     self.condition_button = self.make_button(u"\u21d1 Condition",
                                              self.condition_click)
     self.cluster_button = self.make_button(u"\u21d1 Cluster",
                                              self.cluster_click)
     buttons = [self.gene_button, self.condition_button, self.cluster_button]
     horizontal = widgets.HBox(children=buttons)
     self.hideable = widgets.VBox(children=[horizontal, self.expression.assembly])
     #traitlets.directional_link((self, "maximize"), (hideable, "visible"))
     #traitlets.directional_link((self, "maximize"), (self.network, "maximize"))
     self.on_trait_change(self.maximize_changed, "maximize")
     traitlets.directional_link((self, "svg_width"), (self.network, "svg_width"))
     self.assembly = widgets.VBox(children=[self.network.assembly, self.hideable])
Exemplo n.º 16
0
    def __init__(self, mol):
        super(SelBase, self).__init__(mol)

        self._atomset = collections.OrderedDict()

        self.atom_listname = ipy.HTML('<b>Selected atoms:</b>')
        self.atom_list = ipy.SelectMultiple(options=list(self.viewer.selected_atom_indices), height=150)
        traitlets.directional_link(
            (self.viewer, 'selected_atom_indices'),
            (self.atom_list, 'options'),
            self._atom_indices_to_atoms
        )

        self.select_all_atoms_button = ipy.Button(description='Select all atoms')
        self.select_all_atoms_button.on_click(self.select_all_atoms)

        self.select_none = ipy.Button(description='Clear all selections')
        self.select_none.on_click(self.clear_selections)
Exemplo n.º 17
0
    def __init__(self, mol):
        super(SelBase, self).__init__(mol)

        self._atomset = collections.OrderedDict()

        self.atom_listname = ipy.HTML('<b>Selected atoms:</b>')
        self.atom_list = ipy.SelectMultiple(options=list(
            self.viewer.selected_atom_indices),
                                            height=150)
        traitlets.directional_link((self.viewer, 'selected_atom_indices'),
                                   (self.atom_list, 'options'),
                                   self._atom_indices_to_atoms)

        self.select_all_atoms_button = ipy.Button(
            description='Select all atoms')
        self.select_all_atoms_button.on_click(self.select_all_atoms)

        self.select_none = ipy.Button(description='Clear all selections')
        self.select_none.on_click(self.clear_selections)
Exemplo n.º 18
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]
Exemplo n.º 19
0
 def __init__(self, *pargs, **kwargs):
     self.drawing = True
     self.last_draw_time = 0
     self.draw_lock = threading.Lock()
     super(Locations, self).__init__(*pargs, **kwargs)
     self.diagram = D = cartesian_svg.doodle(-3, -6, 6, 2, html_width=700)
     self.moving = None
     a_slider = widgets.FloatSlider(value=3.0, min=0.2, max=10.0, step=0.2,
         width="150px", description="Kim/Bob")
     b_slider = widgets.FloatSlider(value=4.0, min=0.2, max=10.0, step=0.2,
         width="150px", description="Jack/Janet")
     traitlets.directional_link((a_slider, "value"), (self, "a"))
     traitlets.directional_link((b_slider, "value"), (self, "b"))
     self.on_trait_change(self.redraw, "a")
     self.on_trait_change(self.redraw, "b")
     assembly = widgets.VBox(children = [a_slider, b_slider, D.target])
     display(assembly)
     #D.show()
     D.enable_events("click mousemove", self.event_callback)
     self.redraw()
    def __init__(self, mol):
        super(BondSelector, self).__init__(mol)

        self._bondset = collections.OrderedDict()
        self._drawn_bond_state = set()

        self.bond_listname = ipy.HTML('<b>Selected bonds:</b>')
        self.bond_list = ipy.SelectMultiple(options=list(), height=150)

        traitlets.directional_link((self.viewer, 'selected_atom_indices'),
                                   (self.bond_list, 'options'),
                                   self._atoms_to_bonds)

        self.atom_list.observe(self.remove_bondlist_highlight, 'value')

        self.subtools.children = [
            ipy.HBox([self.select_all_atoms_button, self.select_none])
        ]
        self.toolpane.children = (self.atom_listname, self.atom_list,
                                  self.bond_listname, self.bond_list)
    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
Exemplo n.º 22
0
    def __init__(self, cmap: str = "gray"):
        """Parameters
        ----------
        cmap
            Colormap to use for displaying images.
        """
        if plt.isinteractive():
            warnings.warn("Turning off matplotlib's interactive mode as it "
                          "is not compatible with this.")
            plt.ioff()

        # General options
        self._algo_sel = ipywidgets.Dropdown(
            options=[A.name for A in algorithms], description="algorithm")

        self._loc_options = [A() for A in algorithms]
        for lo in self._loc_options:
            lo.observe(self._options_changed, "options")

        # The figure
        ax = plt.subplots()[1]
        self.image_display = ImageDisplay(ax, cmap=cmap)
        traitlets.directional_link((self, "input"),
                                   (self.image_display, "input"))

        # Display preview
        self._show_loc_check = ipywidgets.Checkbox(
            description="Show loc.", indent=False, value=True)
        self._scatter_artist = None

        left_box = ipywidgets.VBox([self._algo_sel, *self._loc_options,
                                    self._show_loc_check])
        super().__init__([left_box, self.image_display])

        traitlets.link((self._algo_sel, "value"), (self, "algorithm"))
        self.observe(self._update, "options")
        self.observe(self._options_trait_changed, "options")
        self._show_loc_check.observe(self._update, "value")
    def __init__(self, mol):
        super().__init__(mol)

        self._atomset = collections.OrderedDict()

        self.atom_listname = ipy.Label('Selected atoms:', layout=ipy.Layout(width='100%'))
        self.atom_list = ipy.SelectMultiple(options=list(self.viewer.selected_atom_indices),
                                            layout=ipy.Layout(height='150px'))
        traitlets.directional_link(
            (self.viewer, 'selected_atom_indices'),
            (self.atom_list, 'options'),
            self._atom_indices_to_atoms
        )

        self.select_all_atoms_button = ipy.Button(description='Select all atoms')
        self.select_all_atoms_button.on_click(self.select_all_atoms)

        self.select_none = ipy.Button(description='Clear all selections')
        self.select_none.on_click(self.clear_selections)

        self.representation_buttons = ipy.ToggleButtons(options=['stick','ribbon', 'auto', 'vdw'],
                                                        value='auto')
        self.representation_buttons.observe(self._change_representation, 'value')
Exemplo n.º 24
0
    def __init__(self, mol):
        super(BondSelector, self).__init__(mol)

        self._bondset = collections.OrderedDict()
        self._drawn_bond_state = set()

        self.bond_listname = ipy.HTML('<b>Selected bonds:</b>')
        self.bond_list = ipy.SelectMultiple(options=list(),
                                            height=150)

        traitlets.directional_link(
            (self.viewer, 'selected_atom_indices'),
            (self.bond_list, 'options'),
            self._atoms_to_bonds
        )

        self.atom_list.observe(self.remove_bondlist_highlight, 'value')

        self.subtools.children = [ipy.HBox([self.select_all_atoms_button,
                                            self.select_none])]
        self.toolpane.children = (self.atom_listname,
                                  self.atom_list,
                                  self.bond_listname,
                                  self.bond_list)
Exemplo n.º 25
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 = directional_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)
Exemplo n.º 26
0
    def _src(self, proposal):
        src = proposal['value']
        # print(f'>> TransformTree {id(self)}: validate src = {src}')
        link = None

        if isinstance(src, Tree):
            self.src_tree = src
        elif isinstance(src, HasTraits) and src.has_trait('tree'):
            link = directional_link((src, 'tree'), (self, 'src_tree'))
        elif hasattr(src, 'tree'):
            self.src_tree = getattr(src, 'tree')
        elif src is None:
            self.src_tree = None
        else:
            raise TraitError('must be a tree or an owner of a tree')

        if self._link is not None:
            self._link.unlink()
        self._link = link
        # print(f'<< TransformTree {id(self)}: validate src = {src}')
        return src
Exemplo n.º 27
0
    def test_connect_same(self):
        """Verify two traitlets of the same type can be linked together using directional_link."""

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

        # Conenct the two classes.
        c = directional_link((a, 'value'), (b, 'value'))

        # Make sure the values are the same at the point of linking.
        self.assertEqual(a.value, b.value)

        # Change one the value of the source and check that it synchronizes the target.
        a.value = 5
        self.assertEqual(b.value, 5)
        # Change one the value of the target and check that it has no impact on the source
        b.value = 6
        self.assertEqual(a.value, 5)
Exemplo n.º 28
0
    def controls(self):
        from .layers import VALID_STRETCHES, UI_COLORMAPS

        if self._controls is not None:
            return self._controls

        opacity = widgets.FloatSlider(
            description='Opacity:',
            value=self.opacity,
            min=0,
            max=1,
            readout=False,
            step=0.01,
            layout={'width': '200px'}
        )
        link((self, 'opacity'), (opacity, 'value'))

        stretch = widgets.Dropdown(
            description='Stretch:',
            options=VALID_STRETCHES,
            value=self.stretch,
            layout={'width': '200px'}
        )
        link((self, 'stretch'), (stretch, 'value'))

        # NB, this will crash if `self.cmap` is not one of our allowed values
        reverse_ui_colormaps = dict((kv[1], kv[0]) for kv in UI_COLORMAPS.items())
        colormap = widgets.Dropdown(
            description='Colormap:',
            options=UI_COLORMAPS.keys(),
            value=reverse_ui_colormaps[self.cmap.name],
            layout={'width': '200px'}
        )
        directional_link((colormap, 'label'), (self, 'cmap'), lambda x: UI_COLORMAPS[x])
        directional_link((self, 'cmap'), (colormap, 'label'), lambda x: reverse_ui_colormaps[x.name])

        vrange = widgets.FloatRangeSlider(
            description='Fine min/max:',
            value=[self.vmin, self.vmax],
            min=self._data_min,
            max=self._data_max,
            readout=True,
            layout={'width': '600px'},
            step=(self.vmax - self.vmin) / 100,
            format='.3g'
        )

        # Linkage must be manual since vrange uses a pair of values whereas we
        # have two separate traitlets.
        vrange.observe(self._vrange_slider_updated, names=['value'])

        def update_vrange(change):
            # Note: when this function is called, these values are indeed updated.
            vrange.value = (self.vmin, self.vmax)

        self.observe(update_vrange, names=['vmin', 'vmax'])

        def update_step(change):
            vrange.step = (vrange.max - vrange.min) / 100

        vrange.observe(update_step, names=['min', 'max'])

        coarse_min = widgets.FloatText(
            description='Coarse min:',
            value=self._data_min,
            layout={'width': '300px'}
        )
        link((coarse_min, 'value'), (vrange, 'min'))

        coarse_max = widgets.FloatText(
            description='Coarse max:',
            value=self._data_max,
            layout={'width': '300px'}
        )
        link((coarse_max, 'value'), (vrange, 'max'))

        self._controls = widgets.VBox([
            widgets.HBox([colormap, stretch, opacity]),
            widgets.HBox([coarse_min, coarse_max]),
            vrange,
        ])
        return self._controls
    def __init__(self, mol):
        super().__init__(mol)

        self._widgetshapes = {}
        self._atom_labels = []

        # All numbers here are assumed angstroms and radians for now ...
        self._highlighted_bonds = []
        self._highlighted_atoms = []

        self.original_position = self.mol.positions.copy()

        self.clear_button = ipy.Button(description='Clear selection')
        self.clear_button.on_click(self.clear_selection)

        self.label_box = ipy.Checkbox(description='Label atoms', value=False)
        self.label_box.observe(self.label_atoms, 'value')

        # Viewer
        self.selection_description = ipy.HTML()
        self.subtools.children = (HBox([self.clear_button, self.label_box]),
                                  self.selection_description)
        traitlets.directional_link(
            (self.viewer, 'selected_atom_indices'),
            (self.selection_description, 'value'),
            self.get_first_atom
        )

        # Atom manipulation tools - self.{x,y,z}_slider
        self.sliders = []
        for dim, name in enumerate('xyz'):
            slider = ReadoutFloatSlider(
                    min=-self.MAXDIST, max=self.MAXDIST,
                    description='<span style="color: {c}"><b>{n}</b><span>'.format(
                            n=name, c=self.viewer.AXISCOLORS[name]),
                    format=self.POSFMT)
            slider.dim = dim
            setattr(self, name + '_slider', slider)
            self.sliders.append(slider)
            slider.observe(self.set_atom_pos, 'value')

        # Bond manipulation tools
        self.rigid_mol_selector = ipy.ToggleButtons(description='Position adjustment',
                                                    options={'selected atoms only':False,
                                                             'rigid molecule':True},
                                                    value=True)

        self.length_slider = ReadoutFloatSlider(min=0.1, max=self.MAXDIST, format=self.POSFMT)
        self.length_slider.observe(self.set_distance, 'value')
        self.angle_slider = ReadoutFloatSlider(min=1.0, max=179.0, step=2.0, format=self.DEGFMT)
        self.angle_slider.observe(self.set_angle, 'value')
        self.dihedral_slider = ReadoutFloatSlider(min=-90.0, max=360.0, step=4.0,
                                                  format=self.DEGFMT)
        self.dihedral_slider.observe(self.set_dihedral, 'value')

        self.bond_tools = VBox((self.rigid_mol_selector,
                                self.length_slider,
                                self.angle_slider,
                                self.dihedral_slider))

        self.movement_selector = ipy.ToggleButtons(description='Move:',
                                                   value='atom',
                                                   options=['atom', 'residue', 'chain'])
        self.atom_tools = VBox((self.movement_selector,
                                self.x_slider,
                                self.y_slider,
                                self.z_slider))

        self.reset_button = ipy.Button(description='Reset geometry')
        self.reset_button.on_click(self.reset_geometry)

        self.tool_holder = VBox()
        self.toolpane.children = (self.tool_holder,
                                  self.reset_button)

        self.viewer.observe(self._set_tool_state,
                            names='selected_atom_indices')
    def __init__(self, mol):
        super(GeometryBuilder, self).__init__(mol)

        # All numbers here are assumed angstroms and radians for now ...
        self._highlighted_bonds = []
        self._highlighted_atoms = []

        self.original_position = self.mol.positions.copy()

        self.clear_button = ipy.Button(description='Clear selection')
        self.clear_button.on_click(self.clear_selection)

        self.label_box = ipy.Checkbox(description='Label atoms', value=False)
        self.label_box.observe(self.label_atoms, 'value')

        # Viewer
        self.selection_description = ipy.HTML()
        self.subtools.children = (ipy.HBox([self.clear_button, self.label_box
                                            ]), self.selection_description)
        traitlets.directional_link((self.viewer, 'selected_atom_indices'),
                                   (self.selection_description, 'value'),
                                   self.get_first_atom)

        # Atom manipulation tools
        self.x_slider = ReadoutFloatSlider(min=-self.MAXDIST,
                                           max=self.MAXDIST,
                                           description='<b>x</b>',
                                           format=self.POSFMT)
        self.x_slider.observe(self.set_atom_x, 'value')
        self.y_slider = ReadoutFloatSlider(min=-self.MAXDIST,
                                           max=self.MAXDIST,
                                           description='<b>y</b>',
                                           format=self.POSFMT)
        self.y_slider.observe(self.set_atom_y, 'value')

        self.z_slider = ReadoutFloatSlider(min=-self.MAXDIST,
                                           max=self.MAXDIST,
                                           description='<b>z</b>',
                                           format=self.POSFMT)
        self.z_slider.observe(self.set_atom_z, 'value')

        # Bond manipulation tools
        self.adjust_button = ipy.Checkbox(description='Adjust entire molecule',
                                          align='end',
                                          value=True)

        self.length_slider = ReadoutFloatSlider(min=0.1,
                                                max=self.MAXDIST,
                                                format=self.POSFMT)
        self.length_slider.observe(self.set_distance, 'value')
        self.angle_slider = ReadoutFloatSlider(min=1.0,
                                               max=179.0,
                                               step=2.0,
                                               format=self.DEGFMT)
        self.angle_slider.observe(self.set_angle, 'value')
        self.dihedral_slider = ReadoutFloatSlider(min=-90.0,
                                                  max=360.0,
                                                  step=4.0,
                                                  format=self.DEGFMT)
        self.dihedral_slider.observe(self.set_dihedral, 'value')

        self.bond_tools = ipy.VBox((self.adjust_button, self.length_slider,
                                    self.angle_slider, self.dihedral_slider))

        self.atom_tools = ipy.VBox(
            (self.adjust_button, self.x_slider, self.y_slider, self.z_slider))

        self.reset_button = ipy.Button(description='Reset geometry')
        self.reset_button.on_click(self.reset_geometry)

        self.tool_holder = ipy.VBox()
        self.toolpane.children = (self.tool_holder, self.reset_button)

        traitlets.directional_link((self.viewer, 'selected_atom_indices'),
                                   (self.tool_holder, 'children'),
                                   self._get_tool_state)
Exemplo n.º 31
0
 def make_linkages(self):
     traitlets.link((self.width_slider, "value"), (self.network, "svg_width"))
     traitlets.directional_link((self.parent, "svg_width"), (self.network, "svg_width"))
     traitlets.directional_link((self.maximize_cb, "value"), (self.network, "maximize"))
Exemplo n.º 32
0
    def __init__(self, mol):
        super(GeometryBuilder, self).__init__(mol)

        # All numbers here are assumed angstroms and radians for now ...
        self._highlighted_bonds = []
        self._highlighted_atoms = []

        self.original_position = self.mol.positions.copy()

        self.clear_button = ipy.Button(description='Clear selection')
        self.clear_button.on_click(self.clear_selection)

        self.label_box = ipy.Checkbox(description='Label atoms', value=False)
        self.label_box.observe(self.label_atoms, 'value')

        # Viewer
        self.selection_description = ipy.HTML()
        self.subtools.children = (ipy.HBox([self.clear_button, self.label_box]),
                                  self.selection_description)
        traitlets.directional_link(
            (self.viewer, 'selected_atom_indices'),
            (self.selection_description, 'value'),
            self.get_first_atom
        )

        # Atom manipulation tools
        self.x_slider = ReadoutFloatSlider(min=-self.MAXDIST, max=self.MAXDIST,
                                           description='<b>x</b>', format=self.POSFMT)
        self.x_slider.observe(self.set_atom_x, 'value')
        self.y_slider = ReadoutFloatSlider(min=-self.MAXDIST, max=self.MAXDIST,
                                           description='<b>y</b>', format=self.POSFMT)
        self.y_slider.observe(self.set_atom_y, 'value')

        self.z_slider = ReadoutFloatSlider(min=-self.MAXDIST, max=self.MAXDIST,
                                           description='<b>z</b>', format=self.POSFMT)
        self.z_slider.observe(self.set_atom_z, 'value')

        # Bond manipulation tools
        self.adjust_button = ipy.Checkbox(description='Adjust entire molecule', align='end', value=True)

        self.length_slider = ReadoutFloatSlider(min=0.1, max=self.MAXDIST, format=self.POSFMT)
        self.length_slider.observe(self.set_distance, 'value')
        self.angle_slider = ReadoutFloatSlider(min=1.0, max=179.0, step=2.0, format=self.DEGFMT)
        self.angle_slider.observe(self.set_angle, 'value')
        self.dihedral_slider = ReadoutFloatSlider(min=-90.0, max=360.0, step=4.0, format=self.DEGFMT)
        self.dihedral_slider.observe(self.set_dihedral, 'value')

        self.bond_tools = ipy.VBox((self.adjust_button,
                                    self.length_slider,
                                    self.angle_slider,
                                    self.dihedral_slider))

        self.atom_tools = ipy.VBox((self.adjust_button,
                                    self.x_slider,
                                    self.y_slider,
                                    self.z_slider))

        self.reset_button = ipy.Button(description='Reset geometry')
        self.reset_button.on_click(self.reset_geometry)

        self.tool_holder = ipy.VBox()
        self.toolpane.children = (self.tool_holder,
                                  self.reset_button)

        traitlets.directional_link(
            (self.viewer, 'selected_atom_indices'),
            (self.tool_holder, 'children'),
            self._get_tool_state
        )
Exemplo n.º 33
0
 def __init__(self):
     self.title_html = widgets.HTML("Gene network")
     self.zoom_button = self.make_button("zoom", self.zoom_click, True)
     self.trim_button = self.make_button("trim", self.trim_click)
     self.layout_button = self.make_button("layout", self.layout_click)
     self.expand_button = self.make_button("expand", self.expand_click)
     self.regulates_button = self.make_button("regulates", self.regulates_click)
     self.targeted_button = self.make_button("targeted by", self.targeted_click)
     self.focus_button = self.make_button("focus", self.focus_click)
     self.restore_button = self.make_button("restore", self.restore_click)
     self.ignore_button = self.make_button("ignore", self.ignore_click)
     self.nodes_button = self.make_button("list nodes", self.nodes_click)
     self.edges_button = self.make_button("list edges", self.edges_click)
     self.layout_dropdown = self.make_layout_dropdown()
     self.labels_button = self.make_checkbox("labels", self.labels_click)
     self.colors_button = self.make_checkbox("colors", self.colors_click)
     self.draw_button = self.make_button("draw", self.draw_click)
     # Assemble the layout
     self.threshhold_assembly = self.make_threshhold_assembly()
     self.pattern_assembly = self.make_pattern_assembly()
     self.info_area = widgets.Textarea(description="status")
     self.colors_assembly = self.make_colors_assembly()
     self.dialog = self.make_dialog()
     self.colors_assembly.visible = False
     svg = self.svg = canvas.SVGCanvasWidget()
     sslider = self.size_slider = widgets.FloatSlider(value=500, min=500, max=2000, step=10,
         readout=False, width="150px")
     self.depth_slider = widgets.IntSlider(
         description="depth", value=0, min=0, max=5, width="50px")
     traitlets.directional_link((sslider, "value"), (svg, "width"))
     traitlets.directional_link((sslider, "value"), (svg, "height"))
     #self.svg = widgets.Button(description="dummy button")
     svg.add_style("background-color", "white")
     svg.watch_event = "click mousedown mouseup mousemove mouseover"
     svg.default_event_callback = self.svg_callback
     left_panel = [self.title_html,
                   self.svg, 
                   self.threshhold_assembly, 
                   self.pattern_assembly,
                   self.info_area]
     self.vertical = widgets.VBox(children=left_panel)
     buttons = [self.zoom_button,
                self.focus_button,
                self.ignore_button,
                self.trim_button,
                self.expand_button,
                self.regulates_button,
                self.targeted_button,
                self.layout_dropdown,
                self.layout_button,
                self.nodes_button,
                self.edges_button,
                self.labels_button,
                self.restore_button,
                self.size_slider,
                self.draw_button,
                self.depth_slider,
                self.colors_button,
                self.colors_assembly,
                self.dialog]
     self.inputs = widgets.VBox(children=buttons)
     self.assembly = widgets.HBox(children=[self.inputs, self.vertical])
     self.select_start = None
     self.select_end = None
     self.selection_id = None
     self.selecting = False
     self.data_graph = None
     self.data_positions = None
     self.display_positions = None
     self.display_graph = None
     self.selected_nodes = None
     self.svg_origin = dGraph.pos(0, 0)
     self.moving_node = None
Exemplo n.º 34
0
    def __init__(self, mol):
        super().__init__(mol)

        self._widgetshapes = {}
        self._atom_labels = []

        # All numbers here are assumed angstroms and radians for now ...
        self._highlighted_bonds = []
        self._highlighted_atoms = []

        self.original_position = self.mol.positions.copy()

        self.clear_button = ipy.Button(description='Clear selection')
        self.clear_button.on_click(self.clear_selection)

        self.label_box = ipy.Checkbox(description='Label atoms', value=False)
        self.label_box.observe(self.label_atoms, 'value')

        # Viewer
        self.selection_description = ipy.HTML()
        self.subtools.children = (HBox([self.clear_button, self.label_box]),
                                  self.selection_description)
        traitlets.directional_link((self.viewer, 'selected_atom_indices'),
                                   (self.selection_description, 'value'),
                                   self.get_first_atom)

        # Atom manipulation tools - self.{x,y,z}_slider
        self.sliders = []
        for dim, name in enumerate('xyz'):
            slider = ReadoutFloatSlider(
                min=-self.MAXDIST,
                max=self.MAXDIST,
                description='<span style="color: {c}"><b>{n}</b><span>'.format(
                    n=name, c=self.viewer.AXISCOLORS[name]),
                format=self.POSFMT)
            slider.dim = dim
            setattr(self, name + '_slider', slider)
            self.sliders.append(slider)
            slider.observe(self.set_atom_pos, 'value')

        # Bond manipulation tools
        self.rigid_mol_selector = ipy.ToggleButtons(
            description='Position adjustment',
            options={
                'selected atoms only': False,
                'rigid molecule': True
            },
            value=True)

        self.length_slider = ReadoutFloatSlider(min=0.1,
                                                max=self.MAXDIST,
                                                format=self.POSFMT)
        self.length_slider.observe(self.set_distance, 'value')
        self.angle_slider = ReadoutFloatSlider(min=1.0,
                                               max=179.0,
                                               step=2.0,
                                               format=self.DEGFMT)
        self.angle_slider.observe(self.set_angle, 'value')
        self.dihedral_slider = ReadoutFloatSlider(min=-90.0,
                                                  max=360.0,
                                                  step=4.0,
                                                  format=self.DEGFMT)
        self.dihedral_slider.observe(self.set_dihedral, 'value')

        self.bond_tools = VBox((self.rigid_mol_selector, self.length_slider,
                                self.angle_slider, self.dihedral_slider))

        self.movement_selector = ipy.ToggleButtons(
            description='Move:',
            value='atom',
            options=['atom', 'residue', 'chain'])
        self.atom_tools = VBox((self.movement_selector, self.x_slider,
                                self.y_slider, self.z_slider))

        self.reset_button = ipy.Button(description='Reset geometry')
        self.reset_button.on_click(self.reset_geometry)

        self.tool_holder = VBox()
        self.toolpane.children = (self.tool_holder, self.reset_button)

        self.viewer.observe(self._set_tool_state,
                            names='selected_atom_indices')
Exemplo n.º 35
0
 def __init__(self, dataset, *args, **kwargs):
     super(Nearest, self).__init__(*args, **kwargs)
     self.dataset = dataset
     feature_names = list(dataset.feature_names)
     self.x_name = feature_names[0]
     self.y_name = feature_names[1]
     sc = self.scatter_plot = js_proxy.ProxyWidget()
     xd = self.x_dropdown = widgets.Dropdown(
         options=list(feature_names), value=self.x_name)
     yd = self.y_dropdown = widgets.Dropdown(
         options=list(feature_names), value=self.y_name)
     bc = self.border_checkbox = widgets.Checkbox(description="border", value=True)
     ic = self.interior_checkbox = widgets.Checkbox(description="interior", value=True)
     tc = self.training_checkbox = widgets.Checkbox(description="training", value=True)
     tstc = self.test_checkbox = widgets.Checkbox(description="test", value=True)
     ns = self.n_slider = widgets.IntSlider(value=self.n_neighbors, min=1, max=20,
         description="neighbors", width="50px")
     ss = self.n_slider = widgets.FloatSlider(value=self.n_neighbors, min=0.2, max=0.5,
         description="test size", width="50px", step=0.1)
     traitlets.directional_link((ss, "value"), (self, "test_size"))
     traitlets.directional_link((xd, "value"), (self, "x_name"))
     traitlets.directional_link((yd, "value"), (self, "y_name"))
     traitlets.directional_link((bc, "value"), (self, "show_borders"))
     traitlets.directional_link((ic, "value"), (self, "prediction_grid"))
     traitlets.directional_link((ns, "value"), (self, "n_neighbors"))
     traitlets.directional_link((tc, "value"), (self, "show_training"))
     traitlets.directional_link((tstc, "value"), (self, "show_test"))
     xd.on_trait_change(self.redraw, "value")
     ss.on_trait_change(self.redraw, "value")
     yd.on_trait_change(self.redraw, "value")
     bc.on_trait_change(self.redraw, "value")
     tc.on_trait_change(self.redraw, "value")
     ic.on_trait_change(self.redraw, "value")
     tstc.on_trait_change(self.redraw, "value")
     ns.on_trait_change(self.redraw, "value")
     controls = widgets.VBox(children=[xd, yd, bc, ic, tc, tstc, ns, ss])
     self.assembly = widgets.HBox(children=[controls, sc])