def create_navigator_1d(self):
import ipywidgets as ipyw
x_min, x_max = 0, self.signal.axes_manager.navigation_size - 1
x_text = ipyw.BoundedIntText(value=self.indices[0],
description="Coordinate", min=x_min,
max=x_max,
layout=ipyw.Layout(flex='0 1 auto',
width='auto'))
randomize = ipyw.Button(description="Randomize",
layout=ipyw.Layout(flex='0 1 auto',
width='auto'))
container = ipyw.HBox((x_text, randomize))
def on_index_change(change):
self.indices = (x_text.value,)
self.replot_image()
def on_randomize(change):
from random import randint
x = randint(x_min, x_max)
x_text.value = x
x_text.observe(on_index_change, names='value')
randomize.on_click(on_randomize)
return container
python类Layout()的实例源码
visualization.py 文件源码
项目:notebook-molecular-visualization
作者: Autodesk
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
def __init__(self, parent, props):
super().__init__(layout=ipywidgets.Layout(align_items='flex-end'))
self.parent = parent
self.props = props
self.install_button = ipywidgets.Button()
self.install_button.add_class('nbv-table-row')
self.remove_button = ipywidgets.Button(description='remove')
self.remove_button.add_class('nbv-table-row')
self.html = ipywidgets.HTML()
if self.props['writable'] == 'INSTALLED':
self.chidlren = (self.html,)
else:
self.children = (self.html, self.install_button, self.remove_button)
self.install_button.on_click(self.install)
self.remove_button.on_click(self.uninstall)
self.rerender()
def __init__(self, image, client):
self._err = False
self._client = client
self.image = image
self.status = ipy.HTML(layout=ipy.Layout(width="20px"))
self.html = ipy.HTML(value=image, layout=ipy.Layout(width="400px"))
self.html.add_class('nbv-monospace')
self.msg = ipy.HTML(layout=ipy.Layout(width='300px'))
self.button = ipy.Button(layout=ipy.Layout(width='100px'))
if mdt.compute.config.devmode:
self.button.on_click(self.rebuild)
else:
self.button.on_click(self.pull)
self._reactivate_button()
self._set_status_value()
super().__init__(children=[self.status, self.html, self.button, self.msg])
def __init__(self, value=None, units=None, **kwargs):
kwargs.setdefault('display', 'flex')
kwargs.setdefault('flex_flow','row wrap')
super().__init__(layout=ipy.Layout(display='flex', flex_flow='row wrap'),
**process_widget_kwargs(kwargs))
self.textbox = ipy.Text()
self.textbox.observe(self._validate, 'value')
self._error_msg = None
if units is not None:
self.dimensionality = u.get_units(units).dimensionality
else:
self.dimensionality = None
self._validated_value = None
self.validated = ipy.HTML(self.INVALID)
self.children = [self.textbox, self.validated]
self._is_valid = False
if value is not None:
self.value = value
def __init__(self, mol):
super().__init__(mol)
self._bondset = collections.OrderedDict()
self._drawn_bond_state = set()
self.bond_listname = ipy.Label('Selected bonds:', layout=ipy.Layout(width='100%'))
self.bond_list = ipy.SelectMultiple(options=list(),
layout=ipy.Layout(height='150px'))
self.viewer.observe(self._update_bondlist, 'selected_atom_indices')
self.atom_list.observe(self.remove_bondlist_highlight, 'value')
self.subtools.children = [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 __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]
def render_string(self):
height = '%spx' % min(self._string.count('\n') * 16 + 36, 600)
try:
self.textarea = ipy.Textarea(self._string[:self.CHUNK],
layout=Layout(width='100%', height=height))
except traitlets.TraitError:
self.textarea = ipy.Textarea('[NOT SHOWN - UNABLE TO DECODE FILE]',
layout=Layout(height='300px',
**self.TEXTAREA_KWARGS))
return
finally:
self.children = [self.textarea]
self._current_pos = self.CHUNK
if len(self._string) > self.CHUNK:
self.textarea.value += self.TRUNCATE_MESSAGE
self.load_more_button = ipy.Button(description='See more')
self.load_more_button.on_click(self.load_more)
self.children = self.children + (self.load_more_button,)
def create_navigator_2d(self):
import ipywidgets as ipyw
x_min, y_min = 0, 0
x_max, y_max = self.signal.axes_manager.navigation_shape
x_max -= 1
y_max -= 1
x_text = ipyw.BoundedIntText(value=self.indices[0], description="x",
min=x_min, max=x_max,
layout=ipyw.Layout(flex='0 1 auto',
width='auto'))
y_text = ipyw.BoundedIntText(value=self.indices[1], description="y",
min=y_min, max=y_max,
layout=ipyw.Layout(flex='0 1 auto',
width='auto'))
randomize = ipyw.Button(description="Randomize",
layout=ipyw.Layout(flex='0 1 auto',
width='auto'))
container = ipyw.HBox((x_text, y_text, randomize))
def on_index_change(change):
self.indices = (x_text.value, y_text.value)
self.replot_image()
def on_randomize(change):
from random import randint
x = randint(x_min, x_max)
y = randint(y_min, y_max)
x_text.value = x
y_text.value = y
x_text.observe(on_index_change, names='value')
y_text.observe(on_index_change, names='value')
randomize.on_click(on_randomize)
return container
def __init__(self, base_url='https://hydro1.gesdisc.eosdis.nasa.gov/data/NLDAS/', **layout_kwargs):
self.base_url = base_url
self.selected_url = None
if 'min_width' not in layout_kwargs:
layout_kwargs['min_width'] = '30%'
self.label_layout = Layout(**layout_kwargs)
dd = widgets.Select(
options=self.get_links(
base_url,
href_filter=self.dir_and_not_data,
),
description='', #urlparse(base_url).path,
)
dd.observe(partial(self.on_value_change, url=self.base_url), names='value')
lbl = widgets.Label(urlparse(self.base_url).path, layout=self.label_layout)
hbox = widgets.HBox([lbl, dd])
self.elts = [hbox, lbl, dd]
display(hbox)
def _default_ui_intslider(self):
return IntSlider(
continuous_update=False,
orientation="horizontal",
step=1,
min=0,
value=self.frame,
max=1,
layout=Layout(flex="2 2 auto")
)
def _update(self, box):
def on_click(b):
if b.description == '..':
self.path = os.path.split(self.path)[0]
else:
self.path = os.path.join(self.path, b.description)
self._update_files()
self._update(box)
buttons = []
for f in self.dirs:
button = widgets.Button(description=f, background_color='#d0d0ff', layout=widgets.Layout(width='50%'))
button.on_click(on_click)
buttons.append(button)
for f in self.files:
button = widgets.Button(description=f, layout=widgets.Layout(width='50%'))
button.style.button_color = 'powderblue'
button.on_click(on_click)
buttons.append(button)
box.children = tuple([widgets.HTML("%s" % (self.path,))] + buttons)
# example usage:
# f = FileBrowser()
# f.widget()
# <interact with widget, select a path>
# in a separate cell:
# f.path # returns the selected path
graph_viewer.py 文件源码
项目:notebook-molecular-visualization
作者: Autodesk
项目源码
文件源码
阅读 22
收藏 0
点赞 0
评论 0
def __init__(self, atoms,
carbon_labels=True,
names=None,
width=400, height=350,
display=False,
_forcebig=False,
**kwargs):
self.atoms = getattr(atoms, 'atoms', atoms)
if not _forcebig and len(self.atoms) > self.MAXATOMS:
raise ValueError('Refusing to draw more than 200 atoms in 2D visualization. '
'Override this with _forcebig=True')
if names is None:
names = []
for atom in self.atoms:
if atom.formal_charge == 0:
names.append(atom.name)
else:
names.append(atom.name + _charge_str(atom.formal_charge))
self.names = names
self.atom_indices = {atom: i for i, atom in enumerate(self.atoms)}
self.selection_group = None
self.selection_id = None
self.width = width
self.height = height
self.uuid = 'mol2d'+str(uuid.uuid4())
self.carbon_labels = carbon_labels
self._clicks_enabled = False
self.graph = self.to_graph(self.atoms)
super().__init__(layout=ipy.Layout(width=str(width), height=str(height)))
if display: dsp.display(self)
viewercontainer.py 文件源码
项目:notebook-molecular-visualization
作者: Autodesk
项目源码
文件源码
阅读 22
收藏 0
点赞 0
评论 0
def __init__(self, children, viewer=None, graphviewer=None, **kwargs):
if 'layout' not in kwargs:
kwargs['layout'] = ipy.Layout(flex_flow='column', width='100%')
super().__init__(children=children, **kwargs)
self.viewer = viewer
self.graphviewer = graphviewer
def __init__(self):
self.client = None
self.warning = ipy.HTML(description='<b>Engine status:</b>', value=SPINNER)
self.devmode_label = ipy.Label('Use local docker images (developer mode)',
layout=ipy.Layout(width='100%'))
self.devmode_button = ipy.Checkbox(value=mdt.compute.config.devmode,
layout=ipy.Layout(width='15px'))
self.devmode_button.observe(self.set_devmode, 'value')
self.engine_config_description = ipy.HTML('Docker host with protocol and port'
' (e.g., <code>http://localhost:2375</code>).'
' If blank, this'
' defaults to the docker engine configured at '
'your command line.',
layout=ipy.Layout(width='100%'))
self.engine_config_value = ipy.Text('blank', layout=ipy.Layout(width='100%'))
self.engine_config_value.add_class('nbv-monospace')
self.image_box = ipy.Box()
self._reset_config_button = ipy.Button(description='Reset',
tooltip='Reset to applied value')
self._apply_changes_button = ipy.Button(description='Apply',
tooltip='Apply for this session')
self._save_changes_button = ipy.Button(description='Make default',
tooltip='Make this the default for new sessions')
self._reset_config_button.on_click(self.reset_config)
self._apply_changes_button.on_click(self.apply_config)
self._save_changes_button.on_click(self.save_config)
self.children = [self.warning,
VBox([self.engine_config_description,
self.engine_config_value]),
HBox([self._reset_config_button,
self._apply_changes_button,
self._save_changes_button]),
HBox([self.devmode_button, self.devmode_label]),
self.image_box]
self.reset_config()
super().__init__(children=self.children)
self.connect_to_engine()
def __init__(self):
from pip._vendor.packaging import version
super().__init__()
self.version = ipy.HTML('<div class="nbv-loader"></div>')
self.textarea = ipy.Textarea(layout=ipy.Layout(width='700px', height='300px'))
threading.Thread(target=self.version_check).start()
p1 = os.path.join(mdt.PACKAGEPATH, "HISTORY.rst")
p2 = os.path.join(mdt.PACKAGEPATH, "..", "HISTORY.rst")
if os.path.exists(p1):
path = p1
elif os.path.exists(p2):
path = p2
else:
path = None
if path is not None:
with open(path, 'r') as infile:
self.textarea.value = infile.read()
else:
self.textarea.value = 'HISTORY.rst not found'
self.textarea.disabled = True
self.children = (self.version, self.textarea)
def __init__(self, xface):
self.xface = xface
if xface.is_installed():
if xface.version_flag:
v = xface.get_installed_version()
else:
v = INSTALLED
else:
v = MISSING
self.maintext = ipy.HTML(
('<span class="nbv-table-row nbv-width-med nbv-monospace">'
' {xface.name}</span> '
'<span class="nbv-table-row nbv-monospace nbv-width-sm">'
' {localversion}</span> '
'<span class="nbv-table-row nbv-monospace nbv-width-sm">'
' {xface.expectedversion}</span>'
'<span class="nbv-width-sm nbv-table-row"> </span>' # empty space
)
.format(xface=xface, localversion=v))
self.selector = ipy.ToggleButtons(options=['in docker', 'locally'],
value='in docker',
button_style='info')
self.selector.add_class('nbv-width-lg')
self.selector.add_class("nbv-table-row")
self.selector.observe(self._toggle, 'value')
self.path = ipy.HTML(layout=ipy.Layout(width='150px', font_size='x-small'),
value=xface.path if xface.path is not None else '',)
self.save_button = ipy.Button(description='Make default', layout=ipy.Layout(width='100px'))
self.save_button.on_click(self.save_selection)
self.save_button.add_class('nbv-table-row')
children = [self.maintext, self.selector, self.save_button]
super().__init__(children=children,
layout=ipy.Layout(width='100%', align_items='flex-end'))
def __init__(self, client):
self.client = client
images = self._get_images()
self.header = ipy.HTML(
'<span class="nbv-table-header" style="width:950px"">Image status</span>',
layout=ipy.Layout(align_items='flex-end'))
super().__init__([self.header] + [DockerImageView(im, client) for im in sorted(images)])
configurator.py 文件源码
项目:notebook-molecular-visualization
作者: Autodesk
项目源码
文件源码
阅读 40
收藏 0
点赞 0
评论 0
def __init__(self, paramlist, paramdefs, title=None):
super(Configurator, self).__init__(layout=ipy.Layout(display='flex',
flex_flow='column',
align_self='flex-start',
align_items='stretch',
max_width='100%'))
self.paramlist = paramlist
self.paramdefs = paramdefs
self.apply_button = ipy.Button(description='Apply')
self.apply_button.on_click(self.apply_values)
self.reset_button = ipy.Button(description='Reset')
self.reset_button.on_click(self.reset_values)
self.buttons = ipy.Box([self.reset_button, self.apply_button],
layout=ipy.Layout(align_self='center'))
self.selectors = collections.OrderedDict([(p.name, ParamSelector(p)) for p in paramdefs])
self.reset_values()
title = utils.if_not_none(title, 'Configuration')
self.title = ipy.HTML('<center><h4>%s</h4></center><hr>' % title,
align_self='center')
self.currentconfig = ipy.Textarea(description='<i>Current params</i>',
disabled=True,
value=self._pretty_print_config(),
layout=ipy.Layout(width='350px', min_height='300px',
max_height='500px',
display='flex', flex_flow='column'))
self.middle = HBox([VBox(list(self.selectors.values())), self.currentconfig])
self.children = [self.title, self.middle, self.buttons]
def __init__(self, *args, **kwargs):
if 'layout' not in kwargs:
kwargs['layout'] = ipy.Layout()
kwargs['layout'].flex_flow = self._fflow
super().__init__(*args, **kwargs)
parameterization.py 文件源码
项目:notebook-molecular-visualization
作者: Autodesk
项目源码
文件源码
阅读 18
收藏 0
点赞 0
评论 0
def __init__(self, errormessages, molin, molout=None):
self.molin = molin
self.molout = molout
self.msg = errormessages
self.status = ipy.HTML('<h4>Forcefield assignment: %s</h4>' %
('Success' if molout else 'FAILED'))
self.listdesc = ipy.HTML('<b>Errors / warnings:</b>')
error_display = collections.OrderedDict((e.short, e) for e in self.msg)
if len(error_display) == 0:
error_display['No errors or warnings.'] = StructureOk()
self.errorlist = ipy.Select(options=error_display)
self.errmsg = ipy.HTML('-')
self.viewer = self.molin.draw3d()
self.viewer.ribbon(opacity=0.7)
if self.errorlist.value is not None:
self.switch_display({'old': self.errorlist.value, 'new': self.errorlist.value})
self.errorlist.observe(self.switch_display, 'value')
children = (self.status,
HBox([self.viewer, VBox([self.listdesc, self.errorlist])]),
self.errmsg)
super().__init__(children=children, layout=ipy.Layout(display='flex', flex_flow='column'))
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')
def make_layout(layout=None, **kwargs):
from ipywidgets import Layout
import traitlets
if layout is None:
layout = Layout()
for key, val in kwargs.items():
# note that this is the type of the class descriptor, not the instance attribute
if isinstance(getattr(Layout, key), traitlets.Unicode):
val = in_pixels(val)
setattr(layout, key, val)
return layout
def __init__(self, job, **kwargs):
super(JobStatusDisplay, self).__init__(layout=ipy.Layout(flex_flow='column'))
self._job = job
self.update()
self.on_displayed(self.update)
def __call__(self, parameterized, **params):
self.p = param.ParamOverrides(self, params)
if self.p.initializer:
self.p.initializer(parameterized)
self._widgets = {}
self.parameterized = parameterized
widgets, views = self.widgets()
layout = ipywidgets.Layout(display='flex', flex_flow=self.p.layout)
if self.p.close_button:
layout.border = 'solid 1px'
widget_box = ipywidgets.VBox(children=widgets, layout=layout)
if views:
view_box = ipywidgets.VBox(children=views, layout=layout)
layout = self.p.view_position
if layout in ['below', 'right']:
children = [widget_box, view_box]
else:
children = [view_box, widget_box]
box = ipywidgets.VBox if layout in ['below', 'above'] else ipywidgets.HBox
widget_box = box(children=children)
display(Javascript(WIDGET_JS))
display(widget_box)
self._widget_box = widget_box
for view in views:
p_obj = self.parameterized.params(view.name)
value = getattr(self.parameterized, view.name)
if value is not None:
self._update_trait(view.name, p_obj.renderer(value))
# Keeps track of changes between button presses
self._changed = {}
if self.p.on_init:
self.execute()
def text_window():
text = widgets.Textarea(
value="""This movie was a well-written story of Intel's history, from its highs to its lows. I especially liked the character development. They should have gotten Brad Pitt to play Robert Noyce though, the actor's acting was bad. For example, that scene where they left Fairchild to start Intel was way too exaggerated and melodramatic. The pace of the movie was exciting enough to overlook those issues.""",
placeholder='Type something',
description='Review:',
disabled=False,
layout=widgets.Layout(height='200px', width='50%'))
return text
def create_map_obj(center = [30,5], zoom = 2):
"""
Creates a new ipyleaflet map object that defaults to a view of the entire world.
Can specify center
"""
if leaflet_enabled is False:
return "IPywidgets and ipyleaflet support disabled."
else:
m = Map(default_tiles=TileLayer(opacity=1.0), center=center, zoom=zoom, layout=ipywidgets.Layout(height="600px"))
return m
def _default_image_layout(self):
return Layout(max_width="100%", height="auto")
def _default_layout(self):
return {
'html': Layout(display="none"),
'image': Layout(display="inline")
}
def __init__(self, clip=None, *args, **kwargs):
super(Preview, self).__init__(*args, **kwargs, clip=clip)
self.links = [directional_link((self._ui_intslider, 'value'), (self, 'frame'))]
prev = Button(icon="fa-step-backward", layout=Layout(width="50px"))
prev.on_click(lambda s: self.step(-1))
next = Button(icon="fa-step-forward", layout=Layout(width="50px"))
next.on_click(lambda s: self.step(1))
self.children = [
HBox([prev, next, self._ui_intslider]),
self._current
]
britecharts_jupyter_widget.py 文件源码
项目:jupyter_britecharts_widget_tutorial
作者: kazuar
项目源码
文件源码
阅读 18
收藏 0
点赞 0
评论 0
def _default_layout(self):
return widgets.Layout(height='400px', align_self='stretch')