def notebook_interaction(self, display=True): from ipywidgets import (Checkbox, FloatSlider, VBox) from traitlets import TraitError as TraitletError from IPython.display import display as ip_display try: active = Checkbox(description='active', value=self.active) def on_active_change(change): self.active = change['new'] active.observe(on_active_change, names='value') fine_structure = Checkbox(description='Fine structure', value=self.fine_structure_active) def on_fine_structure_active_change(change): self.fine_structure_active = change['new'] fine_structure.observe(on_fine_structure_active_change, names='value') fs_smoothing = FloatSlider(description='Fine structure smoothing', min=0, max=1, step=0.001, value=self.fine_structure_smoothing) def on_fs_smoothing_change(change): self.fine_structure_smoothing = change['new'] fs_smoothing.observe(on_fs_smoothing_change, names='value') container = VBox([active, fine_structure, fs_smoothing]) for parameter in [self.intensity, self.effective_angle, self.onset_energy]: container.children += parameter.notebook_interaction(False), if not display: return container ip_display(container) except TraitletError: if display: print('This function is only avialable when running in a' ' notebook') else: raise
def _create_notebook_widget(self, index=None): from ipywidgets import (FloatSlider, FloatText, Layout, HBox) widget_bounds = self._interactive_slider_bounds(index=index) thismin = FloatText(value=widget_bounds['min'], description='min', layout=Layout(flex='0 1 auto', width='auto'),) thismax = FloatText(value=widget_bounds['max'], description='max', layout=Layout(flex='0 1 auto', width='auto'),) current_value = self.value if index is None else self.value[index] current_name = self.name if index is not None: current_name += '_{}'.format(index) widget = FloatSlider(value=current_value, min=thismin.value, max=thismax.value, step=widget_bounds['step'], description=current_name, layout=Layout(flex='1 1 auto', width='auto')) def on_min_change(change): if widget.max > change['new']: widget.min = change['new'] widget.step = np.abs(widget.max - widget.min) * 0.001 def on_max_change(change): if widget.min < change['new']: widget.max = change['new'] widget.step = np.abs(widget.max - widget.min) * 0.001 thismin.observe(on_min_change, names='value') thismax.observe(on_max_change, names='value') this_observed = functools.partial(self._interactive_update, index=index) widget.observe(this_observed, names='value') container = HBox((thismin, widget, thismax)) return container
def setup_toposim_widgets(self): self.toposim_labels = { 'kf': Label(value='River incision coefficient'), 'g': Label(value='River transport coefficient'), 'kd': Label(value='Hillslope diffusivity'), 'p': Label(value='Flow partition exponent'), 'u': Label(value='Plateau uplift rate') } self.toposim_widgets = { 'kf': FloatSlider(value=1e-4, min=5e-5, max=3e-4, step=1e-5, readout_format='.1e'), 'g': FloatSlider(value=1., min=0.5, max=1.5, step=0.1, readout_format='.1f'), 'kd': FloatSlider( value=0.02, min=0., max=0.1, step=0.01, ), 'p': FloatSlider(value=1., min=0., max=10., step=0.2, readout_format='.1f'), 'u': FloatSlider(value=0., min=0., max=1e-3, step=1e-5, readout_format='.1e') }
def ChooseSepDistance_Mode(mode): settings["Help"]["Separation"] = mode if mode == "auto": Low_Diam_slider_start = settings["Help"]["GuessLowestDiameter_nm"] Low_Diam_slider = IntSlider(min = 1, max = 100, step = 1, \ value = Low_Diam_slider_start, description = "Guess lowest diameter [nm]") def CalcSepDistance(Low_Diam): Min_Separation, Max_displacement = \ nd.ParameterEstimation.FindMaxDisplacementTrackpy(ParameterJsonFile, GuessLowestDiameter_nm = Low_Diam) settings["Find"]["Separation data"] = Min_Separation settings["Link"]["Max displacement"] = Max_displacement settings["Help"]["GuessLowestDiameter_nm"] = Low_Diam nd.handle_data.WriteJson(ParameterJsonFile, settings) interact(CalcSepDistance, Low_Diam = Low_Diam_slider) else: Min_Separation_slider = FloatSlider(min = 0, max = 100, step = 0.5, \ value = settings["Find"]["Separation data"],\ description = "Separation distance [Px]") Max_displacement_slider = FloatSlider(min = 0, max = 50, step = 0.5, \ value = settings["Link"]["Max displacement"],\ description = "Maximal Displacement [Px]") def ChooseSepDistance_Value(Min_Separation, Max_displacement): settings["Find"]["Separation data"] = Min_Separation settings["Link"]["Max displacement"] = Max_displacement nd.handle_data.WriteJson(ParameterJsonFile, settings) interact(ChooseSepDistance_Value, \ Min_Separation = Min_Separation_slider, Max_displacement = Max_displacement_slider) nd.handle_data.WriteJson(ParameterJsonFile, settings)
def show(): style = dict(description_width='initial') r = FloatSlider(value=0, min=-1, max=1, step=0.1, description='相関係数 (目安)', continuous_update=False, readout_format='.1f', style=style) interact(plot, r=r)
def show(): style = dict(description_width='initial') interact(plot, mean=FloatSlider(value=1.0, min=0.1, max=5.0, step=0.1, description=r'期待値 (平均) $( p\times n)$:', continuous_update=False, readout_format='.1f', style=style))
def non_convex_gradient_descent_demo(): o = {'curr_x': -6.0} interact_manual(run_sgd_step, learning_rate=FloatSlider(min=0.01, max=2.0, step=0.01, value=0.01), o=fixed(o), name=fixed('non-convex-1'), range_def=fixed([-20, 20, 100000]))
def _tensor_folder(self): alo = Layout(width='70px') rlo = Layout(width='220px') scale = FloatSlider(max=10.0, step=0.001, readout=True, value=1.0) tens = Button(description=' Tensor', icon='bank') def _tens(c): for scn in self.active(): scn.tens = not scn.tens def _scale(c): for scn in self.active(): scn.scale = c.new tens.on_click(_tens) scale.observe(_scale, names='value') content = _ListDict([ ('scale', scale), ]) return Folder(tens, content)
def lpm_structural(): c = FloatSlider(value=0, description=r'$c$', min=0., max=1.2e-2, step=1.e-3, continuous_update=False) #dlog*=5 reveal = Checkbox(value=False, description='reveal future!') io = interactive_output(plot_lpm_structural, {'c': c, 'reveal': reveal}) return VBox([HBox([c, reveal]), io])
def interact(self): """ 获取交互式控制专题图样式部件 """ radiusintslider = IntSlider(value=self.radius, min=1, max=100, step=1, description='半径:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d', layout=Layout(width="350px")) link((radiusintslider, 'value'), (self, 'radius')) minopacityslider = FloatSlider(value=self.min_opacity, min=0, max=1.0, step=0.05, description='透明度:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.1f', layout=Layout(width="350px")) link((minopacityslider, 'value'), (self, 'min_opacity')) blurintslider = IntSlider(value=self.blur, min=1, max=100, step=1, description='模糊:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d', layout=Layout(width="350px")) link((blurintslider, 'value'), (self, 'blur')) maxslider = IntSlider(value=1, min=0, max=math.ceil(self.max), step=1, description='max:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d', layout=Layout(width="350px")) link((maxslider, 'value'), (self, 'max')) return VBox( [radiusintslider, minopacityslider, blurintslider, maxslider])
def FS(name): ''' Generate a FloatSlider to our specifications ''' return FloatSlider(description=name, min=-1, max=1, value=0, step=0.01, continuous_update=False)
def _sigma_sld(value=0.0, min=0.0, max=0.4, step=0.01, description=r'\(\sigma\)'): """Create a slider for sigma.""" return FloatSlider(value=value, min=min, max=max, step=step, description=description)
def plot_parabola(): a_koef = FloatSlider(min=-5, max=10, step=0.5, value=1, description='a') b_koef = FloatSlider(min=-5, max=10, step=0.5, value=1, description='b') c_koef = FloatSlider(min=-5, max=10, step=0.5, value=1, description='c') @interact(a=a_koef, b=b_koef, c=c_koef) def interact_plot_parabol(a, b, c): x = np.linspace(-10, 10, num=200) y = a * x**2 + b * x + c plt.figure(figsize=(16, 10)) plt.plot(x, y, color='black') plt.xlim((-10, 10)) plt.ylim((-10, 100)) plt.xlabel("X") plt.ylabel("Y") plt.grid() plt.title("$y(X) = a X^2 + b X + c$") plt.show()
def leaky_aquifer(): Q = FloatSlider(value=1000, description=r'$Q$ [m$^3$/day]', min=500, max=1500, step=500, continuous_update=False) t = FloatLogSlider(value=1.0, description=r'$t$ [day]', base=10, min=-1, max=2, step=0.2, continuous_update=False) r = FloatSlider(value=200, description=r'$r$ [m]', min=100, max=500, step=100, continuous_update=False) T = FloatSlider(value=300, description=r'$T$ [m$^2$/day]', min=100, max=500, step=100, continuous_update=False) c = FloatLogSlider(value=1.e5, description=r'$c$ [day]', base=10, min=2, max=6, step=1, continuous_update=False) io = interactive_output(show_hantushjacob, { 'Q': Q, 't': t, 'r': r, 'T': T, 'c': c }) return VBox([HBox([Q, t, c]), HBox([T, r]), io])
def bgd_simple_lr_dataset_demo(): x, y = make_regression(n_features=1, n_samples=100, noise=30.5, random_state=10, bias=200) x = x[:, 0] y /= 100 y *= 2.0 params = {'b0': -1, 'b1': -5, 'path': []} interact_manual(run_multiple_bgd_for_simple_lr, x=fixed(x), y=fixed(y), params=fixed(params), n_iter=FloatSlider(min=1, max=100, step=1, value=1), learning_rate=FloatSlider(min=0.01, max=100.0, step=0.01, value=0.01))
def interact_plot_inversion(self, maxIter=30): Q = interact( self.plot_inversion, maxIter=IntText(value=maxIter), m0=FloatSlider(min=-2, max=2, step=0.05, value=0., continuous_update=False), mref=FloatSlider(min=-2, max=2, step=0.05, value=0., continuous_update=False), percentage=FloatText(value=self.percentage), floor=FloatText(value=self.floor), chifact=FloatText(value=1.), beta0_ratio=FloatText(value=100), coolingFactor=FloatSlider(min=0.1, max=10, step=1, value=2, continuous_update=False), coolingRate=IntSlider(min=1, max=10, step=1, value=1, continuous_update=False), alpha_s=FloatText(value=1e-10), alpha_x=FloatText(value=0), run = True, target = False, option=ToggleButtons( options=["misfit", "tikhonov"], value="misfit" ), i_iteration=IntSlider(min=0, max=maxIter, step=1, value=0, continuous_update=False) )
def __init__(self, ref, attr, func, widget=None): self._attr = None self.monitored = None self.func = func self.widget = widget if widget is not None else FloatSlider( min=0, max=1, step=0.01) self.value = self.widget.value self.label = Label() super().__init__(ref) self.attr = attr self.widget.observe(self.update, names='value') self.update(None)
def choose_diverging(name=opts, n=(2, 16), desat=FloatSlider(min=0, max=1, value=1), variant=variants): if variant == "reverse": name += "_r" if as_cmap: colors = color_palette(name, 256, desat) _update_lut(cmap, np.c_[colors, np.ones(256)]) _show_cmap(cmap) else: pal[:] = color_palette(name, n, desat) palplot(pal)
def streamflow_depletion(): Q = FloatSlider(value=1000, description=r'$Q$ [m$^3$/day]', min=500, max=1500, step=500, continuous_update=False) t = FloatLogSlider(value=1.0, description=r'$t$ [day]', base=10, min=-1, max=2, step=0.2, continuous_update=False) r = FloatSlider(value=200, description=r'$r$ [m]', min=100, max=500, step=100, continuous_update=False) T = FloatSlider(value=300, description=r'$T$ [m$^2$/day]', min=100, max=500, step=100, continuous_update=False) H = FloatSlider(value=2, description=r'$b$ [m]', min=2, max=5, step=1.5, continuous_update=False) io = interactive_output(show_hunt2003, { 'Q': Q, 't': t, 'r': r, 'T': T, 'H': H }) return VBox([HBox([Q, t, H]), HBox([T, r]), io])
def widget(self, params=None, model=False, auto=False, *args, **kwargs): """ Let set the params in a widget and the posterior visualization Args: params (dict): The hyperparams of the gp model (pymc3 model): The model to display auto (bool): If the display its automatic of it is not. *args: Variable length argument list, used in the plot function. **kwargs: Arbitrary keyword arguments, used in the plot function. """ if params is None: params = self.params_widget intervals = dict() for k, v in params.items(): v = np.squeeze(v) if v > 0.1: intervals[k] = FloatSlider(min=0.0, max=2 * v, value=v, step=1e-2) elif v < -0.1: intervals[k] = FloatSlider(min=2 * v, max=0.0, value=v, step=1e-2) else: intervals[k] = FloatSlider(min=-5.0, max=5.0, value=v, step=1e-2) self._widget_args = args self._widget_kwargs = kwargs if model: widget_plot = self._widget_plot_model else: widget_plot = self._widget_plot if auto: interact(widget_plot, **intervals) else: interact_manual(widget_plot, **intervals)
def interact_gravity_sphere(): Q = interactive( drawfunction, delta_rho=FloatSlider( description=r"$\Delta\rho$", min=-5.0, max=5.0, step=0.1, value=1.0, continuous_update=False, ), a=FloatSlider(min=0.1, max=4.0, step=0.1, value=1.0, continuous_update=False), z=FloatSlider(min=0.1, max=5.0, step=0.1, value=1.0, continuous_update=False), stationSpacing=FloatSlider( description="Step", min=0.005, max=0.1, step=0.005, value=0.01, continuous_update=False, readout_format=".3f", ), B=ToggleButton( value=True, description="keep previous plots", disabled=False, button_style="", tooltip="Click me", layout=Layout(width="20%"), ), ) return Q
def _make_widget(self): fig = GridBox(children=[self.voigt_fig, self.abs_fig, self.int_fig, self.source_fig], layout=Layout(width='100%', min_height='600px', height='100%', grid_template_rows='49% 49%', grid_template_columns='49% 49%', grid_gap='0px 0px')) a_slider = FloatSlider(min=-5, max=0., step=0.01, value=self.a, description='lg(a)') opa_cont_slider = FloatSlider(min=0., max=6., step=0.01, value=self.opa_cont, description=r"$\kappa_c / \kappa_{500}$") opa_line_slider = FloatSlider(min=0., max=7., step=0.01, value=self.opa_line, description=r"$\kappa_l / \kappa_{500}$") mu_slider = FloatSlider(min=0.01, max=1., step=0.01, value=self.mu, description=r'$\mu$') xmax_slider = IntSlider(min=1, max=100, step=1, value=self.xmax, description='xmax') source_slider = Dropdown(options=self.SFUNCTIONS.keys(), value=self.source, description='Source Function', style={'description_width': 'initial'}) w = interactive(self._update_plot, a=a_slider, opa_cont=opa_cont_slider, opa_line=opa_line_slider, mu=mu_slider, xmax=xmax_slider, source=source_slider) controls = GridBox(children=[w.children[5], w.children[0], w.children[2], w.children[4], w.children[3], w.children[1]], layout=Layout(min_height='80px', min_width='600px', grid_template_rows='49% 49%', grid_template_columns='31% 31% 31%', grid_gap='10px')) self.widget = GridBox(children=[controls, fig], layout=Layout(grid_template_rows='8% 90%', width='100%', min_height='650px', height='100%', grid_gap='10px'))
def travel_time_fun(): center = [-43.51876443245584, 172.66858981519297] m = GroundwaterMap(basemap=basemaps.Esri.WorldImagery, center=center, zoom=14) t = IntSlider(value=100, description=r'$t_t$ [day]', min=10, max=365, step=20, continuous_update=False, layout=Layout(max_width='250px')) Q = FloatSlider(value=100, description=r'pumping [L/s]', min=0, max=200, step=20, continuous_update=False, layout=Layout(max_width='250px')) q = FloatSlider(value=1.5, description=r'$dh/dx$ [m/km]', min=0.5, max=3, step=0.5, continuous_update=False, layout=Layout(max_width='270px')) th = BoundedFloatText(value=135, min=0, max=180, description='flow dir. [$^{\circ}$]', layout=Layout(max_width='150px')) m.add_well(center) m.configure(widgets={ 't': t, 'Q': Q, 'q': q, 'th': th }, func=partial(m.travel_time, 1.e-4, 0.03, 10.)) return VBox([m, HBox([Q, t, q, th])])
def manipulation_LJ_force(potentiel, force): font = { 'family': 'serif', 'color': 'darkred', 'weight': 'normal', 'size': 16, } r_m, epsilon = 1, 1 def f(d): fig, ax = plt.subplots(figsize=(5, 5)) circle1 = plt.Circle((0, 2), 0.2, color='b') circle2 = plt.Circle((d, 2), 0.2, color='r') ax.add_artist(circle1) ax.add_artist(circle2) st = np.array([d, 2]) if d != r_m: end = np.array([force(d, r_m, epsilon), 2]) nnn = end - st ax.arrow(st[0], st[1], 2 * nnn[0] / force(r_m - 0.3, r_m, epsilon), nnn[1], head_width=0.25, head_length=0.15, fc='k', ec='k', width=0.05) plt.text(2, 0.65, r'$F_{LJ}=$' + '{val:.1f}'.format(val=end[0]), fontdict=font) else: plt.text(2, 0.65, r'$F_{LJ}=$' + '{val:.1f}'.format(val=0), fontdict=font) r = np.linspace(0.01, 4, num=1000) plt.plot(r, potentiel(r, r_m, epsilon)) plt.xlim(-0.5, 4) plt.ylim(-1.5, 3) plt.show() return interactive(f, d=FloatSlider(min=r_m - 0.3, max=4, step=0.1, description=r'\(d\)', value=r_m))
def confined_aquifer(analysis=False): approx = Checkbox(value=True, description='approx.') semilog = Checkbox(value=False, description='SemiLog') Q = FloatSlider(value=1000, description=r'$Q$ [m$^3$/day]', min=500, max=1500, step=500, continuous_update=False) t = FloatLogSlider(value=1.0, description=r'$t$ [day]', base=10, min=-1, max=2, step=0.2, continuous_update=False) r = FloatSlider(value=200, description=r'$r$ [m]', min=100, max=500, step=100, continuous_update=False) T = FloatSlider(value=300, description=r'$T$ [m$^2$/day]', min=100, max=500, step=100, continuous_update=False) io = interactive_output( show_theis, { 'Q': Q, 't': t, 'r': r, 'T': T, 'approx': approx, 'semilog': semilog, 'analysis': fixed(analysis) }) return VBox([HBox([Q, t, approx]), HBox([T, r, semilog]), io])
def __init__(self, server, t=0.0, verbose=False): self.server = server self.request = FloatText(description="Request [s]", disabled=True) self.predict = FloatText(description="Prediction [s]", disabled=True) self.render = FloatText(description="Rendering [s]", disabled=True) self.time = FloatSlider(description="Time [s]", min=0.0, max=1.0, step=0.01, value=t, continuous_update=False) self.status = Text(description="Status", disabled=True) self.output = Output() ui = (self.time, self.output, self.status) if verbose: ui = ui + (self.request, self.predict, self.render) super(Widget, self).__init__((VBox(ui), )) self.time.observe(self.update, names=['value']) self.update({'new': t})
def interactive_responseFct(): app = interactive( plot_ResponseFct, h_boom=FloatSlider( min=h_boom, max=h_boom_max, step=0.1, value=h_boom, continuous_update=False, description="$h_{boom}$", ), h_1=FloatSlider( min=0.0, max=zmax, value=0.1, step=0.1, continuous_update=False, description="$h_{1}$", ), sigma_1=FloatSlider( min=sigmin, max=sigmax, value=sigmin, step=sigmin, continuous_update=False, description="$\sigma_{1}$", ), sigma_2=FloatSlider( min=sigmin, max=sigmax, value=sigmin, step=sigmin, continuous_update=False, description="$\sigma_{2}$", ), orientation=ToggleButtons(options=["HCP", "VCP"], description="configuration"), ) return app
def __init__(self, layer_state): self.state = layer_state self.widget_visible = Checkbox(description='visible', value=self.state.visible) link((self.state, 'visible'), (self.widget_visible, 'value')) self.widget_attribute = LinkedDropdown(self.state, 'attribute', label='attribute') self.widget_opacity = FloatSlider(min=0, max=1, step=0.01, value=self.state.alpha, description='opacity') link((self.state, 'alpha'), (self.widget_opacity, 'value')) self.widget_contrast = FloatSlider(min=0, max=4, step=0.01, value=self.state.contrast, description='contrast') link((self.state, 'contrast'), (self.widget_contrast, 'value')) self.widget_bias = FloatSlider(min=0, max=1, step=0.01, value=self.state.bias, description='bias') link((self.state, 'bias'), (self.widget_bias, 'value')) self.widget_stretch = LinkedDropdown(self.state, 'stretch', label='stretch') self.widget_percentile = LinkedDropdown(self.state, 'percentile', ui_name='limits', label='percentile') self.widget_v_min = FloatText(description='min', value=self.state.v_min) link((self.state, 'v_min'), (self.widget_v_min, 'value')) self.widget_v_max = FloatText(description='max', value=self.state.v_max) link((self.state, 'v_max'), (self.widget_v_max, 'value')) self.widget_color = ColorPicker(description='color') link((self.state, 'color'), (self.widget_color, 'value'), color2hex) self.widget_colormap = Dropdown(options=colormaps.members, description='colormap') link((self.state, 'cmap'), (self.widget_colormap, 'value')) super().__init__() self.state.viewer_state.add_callback('color_mode', self.setup_widgets) self.setup_widgets()
def __init__(self, layer_state): self.state = layer_state self.widget_visible = Checkbox(description='visible', value=self.state.visible) link((self.state, 'visible'), (self.widget_visible, 'value')) self.widget_opacity = FloatSlider(min=0, max=1, step=0.01, value=self.state.alpha, description='opacity') link((self.state, 'alpha'), (self.widget_opacity, 'value')) self.widget_color = Color(state=self.state) self.widget_size = Size(state=self.state) self.widget_vector = Checkbox(description='show vectors', value=self.state.vector_visible) link((self.state, 'vector_visible'), (self.widget_vector, 'value')) self.widget_vector_x = LinkedDropdown(self.state, 'vx_att', ui_name='vx', label='vx attribute') self.widget_vector_y = LinkedDropdown(self.state, 'vy_att', ui_name='vy', label='vy attribute') dlink((self.widget_vector, 'value'), (self.widget_vector_x.layout, 'display'), lambda value: None if value else 'none') dlink((self.widget_vector, 'value'), (self.widget_vector_y.layout, 'display'), lambda value: None if value else 'none') # TODO: the following shouldn't be necessary ideally if hasattr(self.state, 'bins'): self.widget_bins = IntSlider(min=0, max=1024, value=self.state.bins, description='bin count') link((self.state, 'bins'), (self.widget_bins, 'value')) super().__init__([ self.widget_visible, self.widget_opacity, self.widget_size, self.widget_color, self.widget_vector, self.widget_vector_x, self.widget_vector_y ])
def InteractLogs( d2=50, d3=100, rho1=2300, rho2=2300, rho3=2300, v1=500, v2=1000, v3=1500 ): logs = interactive( plotLogsInteract, d2=FloatSlider(min=0.0, max=100.0, step=5, value=d2), d3=FloatSlider(min=100.0, max=200.0, step=5, value=d3), rho1=FloatSlider(min=2000.0, max=5000.0, step=50.0, value=rho1), rho2=FloatSlider(min=2000.0, max=5000.0, step=50.0, value=rho2), rho3=FloatSlider(min=2000.0, max=5000.0, step=50.0, value=rho3), v1=FloatSlider(min=300.0, max=4000.0, step=50.0, value=v1), v2=FloatSlider(min=300.0, max=4000.0, step=50.0, value=v2), v3=FloatSlider(min=300.0, max=4000.0, step=50.0, value=v3), ) return logs
def plot_data_and_loss(X, y, with_der=False): plt.rcParams.update({'font.size': 20}) k_slider = FloatSlider(min=0, max=40, step=2, value=10) @interact(k=k_slider) def plot_data_and_hyp_with_error(k): fig, axis = plt.subplots(1, 2, figsize=(18, 6)) c = 'black' length = len(X) axis[0].plot(np.linspace(0, 0.6, length), k * np.linspace(0, 0.6, length), label="k={0}".format(k), color=c) axis[0].set_title("Полученная линейная функция") for x_i, y_i in zip(X, y): axis[0].plot([x_i, x_i], [x_i * k, y_i], color='red') axis[0].scatter(X, y, color='black', marker="o", s=50) axis[0].set_xlabel("Доля свободного времени потраченного на учебу") axis[0].set_ylabel("Средняя оценка") axis[0].set_xlim(0, X_LIM) axis[0].set_ylim(0, Y_LIM) axis[0].legend() axis[0].grid() axis[1].set_title("Значение ошибки\nдля гипотезы", fontsize=24) axis[1].set_ylabel("Значение функции потерь", fontsize=20) axis[1].set_xlabel("Значение коэффициента $k$") axis[1].scatter(k, J(X, y, k), marker="+", label="$Loss({0})={1}$".format(k, round(J(X, y, k), 3)), s=50, color=c) if with_der: der_label = "$\dfrac{d Loss(" + str(k) + ")}{dk}$=" + str( round(der_J(X, y, k), 3)) axis[1].text(-1, 0, s=der_label, color=c, ha='left', va='bottom') axis[1].set_xlim([-1, 41]) axis[1].set_ylim([0, 49]) axis[1].legend() # We change the fontsize of minor ticks label axis[1].tick_params(axis='both', which='major', labelsize=20) axis[1].tick_params(axis='both', which='minor', labelsize=20) axis[1].grid() plt.show()
def plate_app(): app = widgetify(plot_Surface_Potentials, survey = ToggleButtons(options =['Dipole-Dipole','Dipole-Pole','Pole-Dipole','Pole-Pole'],value='Dipole-Dipole'), dx = FloatSlider(min=1.,max=1000.,step=1.,value=10., continuous_update=False), dz = FloatSlider(min=1.,max=200.,step=1.,value=10., continuous_update=False), xc = FloatSlider(min=-30.,max=30.,step=1.,value=0., continuous_update=False), zc = FloatSlider(min=-30.,max=0.,step=1.,value=-10., continuous_update=False), rotAng = FloatSlider(min=-90.,max=90.,step=1.,value=0., continuous_update=False,description='$\\theta$'), rhoplate = FloatText(min=1e-8,max=1e8, value = 500., continuous_update=False,description='$\\rho_2$'), rhohalf = FloatText(min=1e-8,max=1e8, value = 500., continuous_update=False,description='$\\rho_1$'), A = FloatSlider(min=-30.25,max=30.25,step=0.5,value=-30.25, continuous_update=False), B = FloatSlider(min=-30.25,max=30.25,step=0.5,value=30.25, continuous_update=False), M = FloatSlider(min=-30.25,max=30.25,step=0.5,value=-10.25, continuous_update=False), N = FloatSlider(min=-30.25,max=30.25,step=0.5,value=10.25, continuous_update=False), Field = ToggleButtons(options =['Model','Potential','E','J','Charge','Sensitivity'],value='Model'), Type = ToggleButtons(options =['Total','Primary','Secondary'],value='Total'), Scale = ToggleButtons(options =['Linear','Log'],value='Linear') ) return app
def __init__(self, atoms, xsize=500, ysize=500): import nglview from ipywidgets import Dropdown, FloatSlider, IntSlider, HBox, VBox self.atoms = atoms if isinstance(atoms[0], Atoms): # Assume this is a trajectory or struct list self.view = nglview.show_asetraj(atoms) self.frm = IntSlider(value=0, min=0, max=len(atoms) - 1) self.frm.observe(self._update_frame) self.struct = atoms[0] else: # Assume this is just a single structure self.view = nglview.show_ase(atoms) self.struct = atoms self.frm = None self.colors = {} self.view._remote_call('setSize', target='Widget', args=['%dpx' % (xsize,), '%dpx' % (ysize,)]) self.view.add_unitcell() self.view.add_spacefill() self.view.camera = 'orthographic' self.view.update_spacefill(radiusType='covalent', scale=0.7) self.view.center() self.asel = Dropdown(options=['All'] + list(set(self.struct.get_chemical_symbols())), value='All', description='Show') self.rad = FloatSlider(value=0.8, min=0.0, max=1.5, step=0.01, description='Ball size') self.asel.observe(self._select_atom) self.rad.observe(self._update_repr) wdg = [self.asel, self.rad] if self.frm: wdg.append(self.frm) self.gui = HBox([self.view, VBox(wdg)]) # Make useful shortcuts for the user of the class self.gui.view = self.view self.gui.control_box = self.gui.children[1] self.gui.custom_colors = self.custom_colors
class Dashboard(VBox): """ Build the dashboard for Jupyter widgets. Requires running in a notebook/jupyterlab. """ def __init__(self, net, width="95%", height="550px", play_rate=0.5): self._ignore_layer_updates = False self.player = _Player(self, play_rate) self.player.start() self.net = net r = random.randint(1, 1000000) self.class_id = "picture-dashboard-%s-%s" % (self.net.name, r) self._width = width self._height = height ## Global widgets: style = {"description_width": "initial"} self.feature_columns = IntText(description="Detail columns:", value=self.net.config["dashboard.features.columns"], min=0, max=1024, style=style) self.feature_scale = FloatText(description="Detail scale:", value=self.net.config["dashboard.features.scale"], min=0.1, max=10, style=style) self.feature_columns.observe(self.regenerate, names='value') self.feature_scale.observe(self.regenerate, names='value') ## Hack to center SVG as justify-content is broken: self.net_svg = HTML(value="""<p style="text-align:center">%s</p>""" % ("",), layout=Layout( width=self._width, overflow_x='auto', overflow_y="auto", justify_content="center")) # Make controls first: self.output = Output() controls = self.make_controls() config = self.make_config() super().__init__([config, controls, self.net_svg, self.output]) def propagate(self, inputs): """ Propagate inputs through the dashboard view of the network. """ if dynamic_pictures_check(): return self.net.propagate(inputs, class_id=self.class_id, update_pictures=True) else: self.regenerate(inputs=input) def goto(self, position): if len(self.net.dataset.inputs) == 0 or len(self.net.dataset.targets) == 0: return if self.control_select.value == "Train": length = len(self.net.dataset.train_inputs) elif self.control_select.value == "Test": length = len(self.net.dataset.test_inputs) #### Position it: if position == "begin": self.control_slider.value = 0 elif position == "end": self.control_slider.value = length - 1 elif position == "prev": if self.control_slider.value - 1 < 0: self.control_slider.value = length - 1 # wrap around else: self.control_slider.value = max(self.control_slider.value - 1, 0) elif position == "next": if self.control_slider.value + 1 > length - 1: self.control_slider.value = 0 # wrap around else: self.control_slider.value = min(self.control_slider.value + 1, length - 1) self.position_text.value = self.control_slider.value def change_select(self, change=None): """ """ self.update_control_slider(change) self.regenerate() def update_control_slider(self, change=None): self.net.config["dashboard.dataset"] = self.control_select.value if len(self.net.dataset.inputs) == 0 or len(self.net.dataset.targets) == 0: self.total_text.value = "of 0" self.control_slider.value = 0 self.position_text.value = 0 self.control_slider.disabled = True self.position_text.disabled = True for child in self.control_buttons.children: if not hasattr(child, "icon") or child.icon != "refresh": child.disabled = True return if self.control_select.value == "Test": self.total_text.value = "of %s" % len(self.net.dataset.test_inputs) minmax = (0, max(len(self.net.dataset.test_inputs) - 1, 0)) if minmax[0] <= self.control_slider.value <= minmax[1]: pass # ok else: self.control_slider.value = 0 self.control_slider.min = minmax[0] self.control_slider.max = minmax[1] if len(self.net.dataset.test_inputs) == 0: disabled = True else: disabled = False elif self.control_select.value == "Train": self.total_text.value = "of %s" % len(self.net.dataset.train_inputs) minmax = (0, max(len(self.net.dataset.train_inputs) - 1, 0)) if minmax[0] <= self.control_slider.value <= minmax[1]: pass # ok else: self.control_slider.value = 0 self.control_slider.min = minmax[0] self.control_slider.max = minmax[1] if len(self.net.dataset.train_inputs) == 0: disabled = True else: disabled = False self.control_slider.disabled = disabled self.position_text.disbaled = disabled self.position_text.value = self.control_slider.value for child in self.control_buttons.children: if not hasattr(child, "icon") or child.icon != "refresh": child.disabled = disabled def update_zoom_slider(self, change): if change["name"] == "value": self.net.config["svg_scale"] = self.zoom_slider.value self.regenerate() def update_position_text(self, change): # {'name': 'value', 'old': 2, 'new': 3, 'owner': IntText(value=3, layout=Layout(width='100%')), 'type': 'change'} self.control_slider.value = change["new"] def get_current_input(self): if self.control_select.value == "Train" and len(self.net.dataset.train_targets) > 0: return self.net.dataset.train_inputs[self.control_slider.value] elif self.control_select.value == "Test" and len(self.net.dataset.test_targets) > 0: return self.net.dataset.test_inputs[self.control_slider.value] def get_current_targets(self): if self.control_select.value == "Train" and len(self.net.dataset.train_targets) > 0: return self.net.dataset.train_targets[self.control_slider.value] elif self.control_select.value == "Test" and len(self.net.dataset.test_targets) > 0: return self.net.dataset.test_targets[self.control_slider.value] def update_slider_control(self, change): if len(self.net.dataset.inputs) == 0 or len(self.net.dataset.targets) == 0: self.total_text.value = "of 0" return if change["name"] == "value": self.position_text.value = self.control_slider.value if self.control_select.value == "Train" and len(self.net.dataset.train_targets) > 0: self.total_text.value = "of %s" % len(self.net.dataset.train_inputs) if self.net.model is None: return if not dynamic_pictures_check(): self.regenerate(inputs=self.net.dataset.train_inputs[self.control_slider.value], targets=self.net.dataset.train_targets[self.control_slider.value]) return output = self.net.propagate(self.net.dataset.train_inputs[self.control_slider.value], class_id=self.class_id, update_pictures=True) if self.feature_bank.value in self.net.layer_dict.keys(): self.net.propagate_to_features(self.feature_bank.value, self.net.dataset.train_inputs[self.control_slider.value], cols=self.feature_columns.value, scale=self.feature_scale.value, html=False) if self.net.config["show_targets"]: if len(self.net.output_bank_order) == 1: ## FIXME: use minmax of output bank self.net.display_component([self.net.dataset.train_targets[self.control_slider.value]], "targets", class_id=self.class_id, minmax=(-1, 1)) else: self.net.display_component(self.net.dataset.train_targets[self.control_slider.value], "targets", class_id=self.class_id, minmax=(-1, 1)) if self.net.config["show_errors"]: ## minmax is error if len(self.net.output_bank_order) == 1: errors = np.array(output) - np.array(self.net.dataset.train_targets[self.control_slider.value]) self.net.display_component([errors.tolist()], "errors", class_id=self.class_id, minmax=(-1, 1)) else: errors = [] for bank in range(len(self.net.output_bank_order)): errors.append( np.array(output[bank]) - np.array(self.net.dataset.train_targets[self.control_slider.value][bank])) self.net.display_component(errors, "errors", class_id=self.class_id, minmax=(-1, 1)) elif self.control_select.value == "Test" and len(self.net.dataset.test_targets) > 0: self.total_text.value = "of %s" % len(self.net.dataset.test_inputs) if self.net.model is None: return if not dynamic_pictures_check(): self.regenerate(inputs=self.net.dataset.test_inputs[self.control_slider.value], targets=self.net.dataset.test_targets[self.control_slider.value]) return output = self.net.propagate(self.net.dataset.test_inputs[self.control_slider.value], class_id=self.class_id, update_pictures=True) if self.feature_bank.value in self.net.layer_dict.keys(): self.net.propagate_to_features(self.feature_bank.value, self.net.dataset.test_inputs[self.control_slider.value], cols=self.feature_columns.value, scale=self.feature_scale.value, html=False) if self.net.config["show_targets"]: ## FIXME: use minmax of output bank self.net.display_component([self.net.dataset.test_targets[self.control_slider.value]], "targets", class_id=self.class_id, minmax=(-1, 1)) if self.net.config["show_errors"]: ## minmax is error if len(self.net.output_bank_order) == 1: errors = np.array(output) - np.array(self.net.dataset.test_targets[self.control_slider.value]) self.net.display_component([errors.tolist()], "errors", class_id=self.class_id, minmax=(-1, 1)) else: errors = [] for bank in range(len(self.net.output_bank_order)): errors.append( np.array(output[bank]) - np.array(self.net.dataset.test_targets[self.control_slider.value][bank])) self.net.display_component(errors, "errors", class_id=self.class_id, minmax=(-1, 1)) def toggle_play(self, button): ## toggle if self.button_play.description == "Play": self.button_play.description = "Stop" self.button_play.icon = "pause" self.player.resume() else: self.button_play.description = "Play" self.button_play.icon = "play" self.player.pause() def prop_one(self, button=None): self.update_slider_control({"name": "value"}) def regenerate(self, button=None, inputs=None, targets=None): ## Protection when deleting object on shutdown: if isinstance(button, dict) and 'new' in button and button['new'] is None: return ## Update the config: self.net.config["dashboard.features.bank"] = self.feature_bank.value self.net.config["dashboard.features.columns"] = self.feature_columns.value self.net.config["dashboard.features.scale"] = self.feature_scale.value inputs = inputs if inputs is not None else self.get_current_input() targets = targets if targets is not None else self.get_current_targets() features = None if self.feature_bank.value in self.net.layer_dict.keys() and inputs is not None: if self.net.model is not None: features = self.net.propagate_to_features(self.feature_bank.value, inputs, cols=self.feature_columns.value, scale=self.feature_scale.value, display=False) svg = """<p style="text-align:center">%s</p>""" % (self.net.to_svg( inputs=inputs, targets=targets, class_id=self.class_id, highlights={self.feature_bank.value: { "border_color": "orange", "border_width": 30, }})) if inputs is not None and features is not None: html_horizontal = """ <table align="center" style="width: 100%%;"> <tr> <td valign="top" style="width: 50%%;">%s</td> <td valign="top" align="center" style="width: 50%%;"><p style="text-align:center"><b>%s</b></p>%s</td> </tr> </table>""" html_vertical = """ <table align="center" style="width: 100%%;"> <tr> <td valign="top">%s</td> </tr> <tr> <td valign="top" align="center"><p style="text-align:center"><b>%s</b></p>%s</td> </tr> </table>""" self.net_svg.value = (html_vertical if self.net.config["svg_rotate"] else html_horizontal) % ( svg, "%s details" % self.feature_bank.value, features) else: self.net_svg.value = svg def make_colormap_image(self, colormap_name): from .layers import Layer if not colormap_name: colormap_name = get_colormap() layer = Layer("Colormap", 100) minmax = layer.get_act_minmax() image = layer.make_image(np.arange(minmax[0], minmax[1], .01), colormap_name, {"pixels_per_unit": 1, "svg_rotate": self.net.config["svg_rotate"]}).resize((300, 25)) return image def set_attr(self, obj, attr, value): if value not in [{}, None]: ## value is None when shutting down if isinstance(value, dict): value = value["value"] if isinstance(obj, dict): obj[attr] = value else: setattr(obj, attr, value) ## was crashing on Widgets.__del__, if get_ipython() no longer existed self.regenerate() def make_controls(self): layout = Layout(width='100%', height="100%") button_begin = Button(icon="fast-backward", layout=layout) button_prev = Button(icon="backward", layout=layout) button_next = Button(icon="forward", layout=layout) button_end = Button(icon="fast-forward", layout=layout) #button_prop = Button(description="Propagate", layout=Layout(width='100%')) #button_train = Button(description="Train", layout=Layout(width='100%')) self.button_play = Button(icon="play", description="Play", layout=layout) step_down = Button(icon="sort-down", layout=Layout(width="95%", height="100%")) step_up = Button(icon="sort-up", layout=Layout(width="95%", height="100%")) up_down = HBox([step_down, step_up], layout=Layout(width="100%", height="100%")) refresh_button = Button(icon="refresh", layout=Layout(width="25%", height="100%")) self.position_text = IntText(value=0, layout=layout) self.control_buttons = HBox([ button_begin, button_prev, #button_train, self.position_text, button_next, button_end, self.button_play, up_down, refresh_button ], layout=Layout(width='100%', height="100%")) length = (len(self.net.dataset.train_inputs) - 1) if len(self.net.dataset.train_inputs) > 0 else 0 self.control_slider = IntSlider(description="Dataset index", continuous_update=False, min=0, max=max(length, 0), value=0, layout=Layout(width='100%')) if self.net.config["dashboard.dataset"] == "Train": length = len(self.net.dataset.train_inputs) else: length = len(self.net.dataset.test_inputs) self.total_text = Label(value="of %s" % length, layout=Layout(width="100px")) self.zoom_slider = FloatSlider(description="Zoom", continuous_update=False, min=0, max=1.0, style={"description_width": 'initial'}, layout=Layout(width="65%"), value=self.net.config["svg_scale"] if self.net.config["svg_scale"] is not None else 0.5) ## Hook them up: button_begin.on_click(lambda button: self.goto("begin")) button_end.on_click(lambda button: self.goto("end")) button_next.on_click(lambda button: self.goto("next")) button_prev.on_click(lambda button: self.goto("prev")) self.button_play.on_click(self.toggle_play) self.control_slider.observe(self.update_slider_control, names='value') refresh_button.on_click(lambda widget: (self.update_control_slider(), self.output.clear_output(), self.regenerate())) step_down.on_click(lambda widget: self.move_step("down")) step_up.on_click(lambda widget: self.move_step("up")) self.zoom_slider.observe(self.update_zoom_slider, names='value') self.position_text.observe(self.update_position_text, names='value') # Put them together: controls = VBox([HBox([self.control_slider, self.total_text], layout=Layout(height="40px")), self.control_buttons], layout=Layout(width='100%')) #net_page = VBox([control, self.net_svg], layout=Layout(width='95%')) controls.on_displayed(lambda widget: self.regenerate()) return controls def move_step(self, direction): """ Move the layer stepper up/down through network """ options = [""] + [layer.name for layer in self.net.layers] index = options.index(self.feature_bank.value) if direction == "up": new_index = (index + 1) % len(options) else: ## down new_index = (index - 1) % len(options) self.feature_bank.value = options[new_index] self.regenerate() def make_config(self): layout = Layout() style = {"description_width": "initial"} checkbox1 = Checkbox(description="Show Targets", value=self.net.config["show_targets"], layout=layout, style=style) checkbox1.observe(lambda change: self.set_attr(self.net.config, "show_targets", change["new"]), names='value') checkbox2 = Checkbox(description="Errors", value=self.net.config["show_errors"], layout=layout, style=style) checkbox2.observe(lambda change: self.set_attr(self.net.config, "show_errors", change["new"]), names='value') hspace = IntText(value=self.net.config["hspace"], description="Horizontal space between banks:", style=style, layout=layout) hspace.observe(lambda change: self.set_attr(self.net.config, "hspace", change["new"]), names='value') vspace = IntText(value=self.net.config["vspace"], description="Vertical space between layers:", style=style, layout=layout) vspace.observe(lambda change: self.set_attr(self.net.config, "vspace", change["new"]), names='value') self.feature_bank = Select(description="Details:", value=self.net.config["dashboard.features.bank"], options=[""] + [layer.name for layer in self.net.layers], rows=1) self.feature_bank.observe(self.regenerate, names='value') self.control_select = Select( options=['Test', 'Train'], value=self.net.config["dashboard.dataset"], description='Dataset:', rows=1 ) self.control_select.observe(self.change_select, names='value') column1 = [self.control_select, self.zoom_slider, hspace, vspace, HBox([checkbox1, checkbox2]), self.feature_bank, self.feature_columns, self.feature_scale ] ## Make layer selectable, and update-able: column2 = [] layer = self.net.layers[-1] self.layer_select = Select(description="Layer:", value=layer.name, options=[layer.name for layer in self.net.layers], rows=1) self.layer_select.observe(self.update_layer_selection, names='value') column2.append(self.layer_select) self.layer_visible_checkbox = Checkbox(description="Visible", value=layer.visible, layout=layout) self.layer_visible_checkbox.observe(self.update_layer, names='value') column2.append(self.layer_visible_checkbox) self.layer_colormap = Select(description="Colormap:", options=[""] + AVAILABLE_COLORMAPS, value=layer.colormap if layer.colormap is not None else "", layout=layout, rows=1) self.layer_colormap_image = HTML(value="""<img src="%s"/>""" % self.net._image_to_uri(self.make_colormap_image(layer.colormap))) self.layer_colormap.observe(self.update_layer, names='value') column2.append(self.layer_colormap) column2.append(self.layer_colormap_image) ## get dynamic minmax; if you change it it will set it in layer as override: minmax = layer.get_act_minmax() self.layer_mindim = FloatText(description="Leftmost color maps to:", value=minmax[0], style=style) self.layer_maxdim = FloatText(description="Rightmost color maps to:", value=minmax[1], style=style) self.layer_mindim.observe(self.update_layer, names='value') self.layer_maxdim.observe(self.update_layer, names='value') column2.append(self.layer_mindim) column2.append(self.layer_maxdim) output_shape = layer.get_output_shape() self.layer_feature = IntText(value=layer.feature, description="Feature to show:", style=style) self.svg_rotate = Checkbox(description="Rotate", value=layer.visible, layout=layout) self.layer_feature.observe(self.update_layer, names='value') column2.append(self.layer_feature) self.svg_rotate = Checkbox(description="Rotate network", value=self.net.config["svg_rotate"], style={"description_width": 'initial'}, layout=Layout(width="52%")) self.svg_rotate.observe(lambda change: self.set_attr(self.net.config, "svg_rotate", change["new"]), names='value') self.save_config_button = Button(icon="save", layout=Layout(width="10%")) self.save_config_button.on_click(self.save_config) column2.append(HBox([self.svg_rotate, self.save_config_button])) config_children = HBox([VBox(column1, layout=Layout(width="100%")), VBox(column2, layout=Layout(width="100%"))]) accordion = Accordion(children=[config_children]) accordion.set_title(0, self.net.name) accordion.selected_index = None return accordion def save_config(self, widget=None): self.net.save_config() def update_layer(self, change): """ Update the layer object, and redisplay. """ if self._ignore_layer_updates: return ## The rest indicates a change to a display variable. ## We need to save the value in the layer, and regenerate ## the display. # Get the layer: layer = self.net[self.layer_select.value] # Save the changed value in the layer: layer.feature = self.layer_feature.value layer.visible = self.layer_visible_checkbox.value ## These three, dealing with colors of activations, ## can be done with a prop_one(): if "color" in change["owner"].description.lower(): ## Matches: Colormap, lefmost color, rightmost color ## overriding dynamic minmax! layer.minmax = (self.layer_mindim.value, self.layer_maxdim.value) layer.minmax = (self.layer_mindim.value, self.layer_maxdim.value) layer.colormap = self.layer_colormap.value if self.layer_colormap.value else None self.layer_colormap_image.value = """<img src="%s"/>""" % self.net._image_to_uri(self.make_colormap_image(layer.colormap)) self.prop_one() else: self.regenerate() def update_layer_selection(self, change): """ Just update the widgets; don't redraw anything. """ ## No need to redisplay anything self._ignore_layer_updates = True ## First, get the new layer selected: layer = self.net[self.layer_select.value] ## Now, let's update all of the values without updating: self.layer_visible_checkbox.value = layer.visible self.layer_colormap.value = layer.colormap if layer.colormap != "" else "" self.layer_colormap_image.value = """<img src="%s"/>""" % self.net._image_to_uri(self.make_colormap_image(layer.colormap)) minmax = layer.get_act_minmax() self.layer_mindim.value = minmax[0] self.layer_maxdim.value = minmax[1] self.layer_feature.value = layer.feature self._ignore_layer_updates = False
def _tensor_folder(self): alo = Layout(width='70px') rlo = Layout(width='220px') scale = FloatSlider(max=10.0, step=0.001, readout=True, value=1.0) xs = [Text(layout=alo,disabled=True), Text(layout=alo,disabled=True), Text(layout=alo,disabled=True)] ys = [Text(layout=alo,disabled=True), Text(layout=alo,disabled=True), Text(layout=alo,disabled=True)] zs = [Text(layout=alo,disabled=True), Text(layout=alo,disabled=True), Text(layout=alo,disabled=True)] cs = [Text(layout=alo,disabled=True), Text(layout=alo,disabled=True), Text(layout=alo,disabled=True)] cidx = HBox([Text(disabled=True,description='Atom Index',layout=rlo)]) xbox = HBox(xs, layout=rlo) ybox = HBox(ys, layout=rlo) zbox = HBox(zs, layout=rlo) cbox = HBox(cs, layout=rlo) tens = Button(description=' Tensor', icon='bank') tensor_cont = VBox([xbox,ybox,zbox]) tensorIndex = Dropdown(options=[0],value=0,description='Tensor') # sceneIndex = Dropdown(options=[0],value=0,description='Scene') ten_label = Label(value="Change selected tensor:") sel_label = Label(value="Selected tensor in gray frame") cod_label = Label(value="Center of selected tensor: (x,y,z)") tensor = [] self.coords = [] def _changeTensor(tensor, tdx): carts = ['x','y','z'] for i,bra in enumerate(carts): for j,ket in enumerate(carts): tensor_cont.children[i].children[j].disabled=False tensor_cont.children[i].children[j].value = \ str(tensor[0][tdx][bra+ket]) tensor_cont.children[i].children[j].disabled=True adx = tensor[0][tdx]['atom'] cidx.children[0].value = str(adx) cbox.children[0].value = str(self.coords[0][int(adx)]) cbox.children[1].value = str(self.coords[1][int(adx)]) cbox.children[2].value = str(self.coords[2][int(adx)]) # scale.value = tensor[0][tdx]['scale'] def _tens(c): for scn in self.active(): scn.tens = not scn.tens self.coords = self._filter_coords() # sceneIndex.options = [x for x in range(len(self.active()))] # sceneIndex.value = sceneIndex.options[0] tensor = self.active()[0].tensor_d tensorIndex.options = [x for x in range(len(tensor[0]))] tensorIndex.value = tensorIndex.options[0] tdx = tensorIndex.value _changeTensor(tensor, tdx) def _scale(c): for scn in self.active(): scn.scale = c.new # tdx = tensorIndex.value # tensor = self.active()[0].tensor_d # tensor[0][tdx]['scale'] = c.new def _idx(c): for scn in self.active(): scn.tidx = c.new tensor = self.active()[0].tensor_d tdx = c.new _changeTensor(tensor, tdx) # def _sdx(c): # tensor = self.active()[sceneIndex.value].tensor_d # tensorIndex.options = [x for x in range(len(tensor[0]))] # tensorIndex.value = tensorIndex.options[0] # tdx = tensorIndex.value # _changeTensor(tensor, tdx) tens.on_click(_tens) scale.observe(_scale, names='value') tensorIndex.observe(_idx, names='value') # sceneIndex.observe(_sdx, names='value') content = _ListDict([ ('scale', scale), ('ten', ten_label), # ('sdx', sceneIndex), ('tdx', tensorIndex), ('tensor', tensor_cont), ('sel', sel_label), ('cidx', cidx), ('center', cod_label), ('coord', cbox)]) return Folder(tens, content)
def make_controls(self): layout = Layout(width='100%', height="100%") button_begin = Button(icon="fast-backward", layout=layout) button_prev = Button(icon="backward", layout=layout) button_next = Button(icon="forward", layout=layout) button_end = Button(icon="fast-forward", layout=layout) #button_prop = Button(description="Propagate", layout=Layout(width='100%')) #button_train = Button(description="Train", layout=Layout(width='100%')) self.button_play = Button(icon="play", description="Play", layout=layout) step_down = Button(icon="sort-down", layout=Layout(width="95%", height="100%")) step_up = Button(icon="sort-up", layout=Layout(width="95%", height="100%")) up_down = HBox([step_down, step_up], layout=Layout(width="100%", height="100%")) refresh_button = Button(icon="refresh", layout=Layout(width="25%", height="100%")) self.position_text = IntText(value=0, layout=layout) self.control_buttons = HBox([ button_begin, button_prev, #button_train, self.position_text, button_next, button_end, self.button_play, up_down, refresh_button ], layout=Layout(width='100%', height="100%")) length = (len(self.net.dataset.train_inputs) - 1) if len(self.net.dataset.train_inputs) > 0 else 0 self.control_slider = IntSlider(description="Dataset index", continuous_update=False, min=0, max=max(length, 0), value=0, layout=Layout(width='100%')) if self.net.config["dashboard.dataset"] == "Train": length = len(self.net.dataset.train_inputs) else: length = len(self.net.dataset.test_inputs) self.total_text = Label(value="of %s" % length, layout=Layout(width="100px")) self.zoom_slider = FloatSlider(description="Zoom", continuous_update=False, min=0, max=1.0, style={"description_width": 'initial'}, layout=Layout(width="65%"), value=self.net.config["svg_scale"] if self.net.config["svg_scale"] is not None else 0.5) ## Hook them up: button_begin.on_click(lambda button: self.goto("begin")) button_end.on_click(lambda button: self.goto("end")) button_next.on_click(lambda button: self.goto("next")) button_prev.on_click(lambda button: self.goto("prev")) self.button_play.on_click(self.toggle_play) self.control_slider.observe(self.update_slider_control, names='value') refresh_button.on_click(lambda widget: (self.update_control_slider(), self.output.clear_output(), self.regenerate())) step_down.on_click(lambda widget: self.move_step("down")) step_up.on_click(lambda widget: self.move_step("up")) self.zoom_slider.observe(self.update_zoom_slider, names='value') self.position_text.observe(self.update_position_text, names='value') # Put them together: controls = VBox([HBox([self.control_slider, self.total_text], layout=Layout(height="40px")), self.control_buttons], layout=Layout(width='100%')) #net_page = VBox([control, self.net_svg], layout=Layout(width='95%')) controls.on_displayed(lambda widget: self.regenerate()) return controls
def test_construction_readout_format(self): slider = FloatSlider(readout_format='$.1f') assert slider.get_state()['readout_format'] == '$.1f'
class NGLDisplay: """Structure display class Provides basic structure/trajectory display in the notebook and optional gui which can be used to enhance its usability. It is also possible to extend the functionality of the particular instance of the viewer by adding further widgets manipulating the structure. """ def __init__(self, atoms, xsize=500, ysize=500): import nglview from ipywidgets import Dropdown, FloatSlider, IntSlider, HBox, VBox self.atoms = atoms if isinstance(atoms[0], Atoms): # Assume this is a trajectory or struct list self.view = nglview.show_asetraj(atoms) self.frm = IntSlider(value=0, min=0, max=len(atoms) - 1) self.frm.observe(self._update_frame) self.struct = atoms[0] else: # Assume this is just a single structure self.view = nglview.show_ase(atoms) self.struct = atoms self.frm = None self.colors = {} self.view._remote_call('setSize', target='Widget', args=['%dpx' % (xsize,), '%dpx' % (ysize,)]) self.view.add_unitcell() self.view.add_spacefill() self.view.camera = 'orthographic' self.view.update_spacefill(radiusType='covalent', scale=0.7) self.view.center() self.asel = Dropdown(options=['All'] + list(set(self.struct.get_chemical_symbols())), value='All', description='Show') self.rad = FloatSlider(value=0.8, min=0.0, max=1.5, step=0.01, description='Ball size') self.asel.observe(self._select_atom) self.rad.observe(self._update_repr) wdg = [self.asel, self.rad] if self.frm: wdg.append(self.frm) self.gui = HBox([self.view, VBox(wdg)]) # Make useful shortcuts for the user of the class self.gui.view = self.view self.gui.control_box = self.gui.children[1] self.gui.custom_colors = self.custom_colors def _update_repr(self, chg=None): self.view.update_spacefill(radiusType='covalent', scale=self.rad.value) def _update_frame(self, chg=None): self.view.frame = self.frm.value return def _select_atom(self, chg=None): sel = self.asel.value self.view.remove_spacefill() for e in set(self.struct.get_chemical_symbols()): if (sel == 'All' or e == sel): if e in self.colors: self.view.add_spacefill(selection='#' + e, color=self.colors[e]) else: self.view.add_spacefill(selection='#' + e) self._update_repr() def custom_colors(self, clr=None): """ Define custom colors for some atoms. Pass a dictionary of the form {'Fe':'red', 'Au':'yellow'} to the function. To reset the map to default call the method without parameters. """ if clr: self.colors = clr else: self.colors = {} self._select_atom()