def __init__( self, title: str, res: Dict[str, NamedRelationalAlgebraFrozenSet], callback: Callable, *args, **kwargs, ): super().__init__(*args, **kwargs) self.loaded = False self.res = res self.callback = callback self._args = args self._kwargs = kwargs self._output = Output() self._output.layout = Layout(width="100%", min_height="400px")
def interactive_fwd(rho_sliders,dep_cells): button = Button(description="Acquire AEM data!") output = Output() display(button, output) def on_button_clicked(b): with output: clear_output(True) m_true,d_true,prob,TDsurvey = create_prob(rho_sliders,dep_cells) plot_data(d_true,TDsurvey) show_inline_matplotlib_plots() return button.on_click(on_button_clicked) show_inline_matplotlib_plots() return button,output
def rest_api(mode=None): """""" values = config.read() wt_url = Text( value=values['api']['url'], placeholder='Add URL', description='API URL:', disabled=False ) wt_user = Text( value=values['api']['user'], placeholder='Username', description='API User:'******'api']['pass'], placeholder='******', description='API Password:'******'Save', disabled=False, icon='save' ) progress = Output() def outlog(*text): with progress: print(*text) @wb_save.on_click def wb_save_on_click(b): config.update(['api', 'url'], str(wt_url.value)) config.update(['api', 'user'], str(wt_user.value)) if wt_pass.value != '': config.update(['api', 'pass'], str(wt_pass.value)) outlog("API information is updated") wbox = VBox([wt_url, wt_user, wt_pass, wb_save, progress]) return wbox
def display_notification(message='None', url='https://quantum-computing.ibm.com/'): options = {} options["body"] = message.lstrip("\'\"").rstrip("\'\"") options["icon"] = "/static/base/images/favicon.ico" notification_uuid = uuid.uuid4() # display our browser notification using javascript with open(resource_filename("ipyhi", "js/notify.js")) as jsFile: jsString = jsFile.read() out = Output() with out: display(Javascript(jsString % { "notification_uuid": notification_uuid, "url": url, "options": json.dumps(options), })) clear_output(wait=False)
def show_plot(filename=None): outdir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'output') if filename is None: _, tempfile_path = tempfile.mkstemp(dir=outdir, suffix='.pdf') else: tempfile_path = os.path.join(outdir, filename) pyplot.savefig(tempfile_path, type='pdf', bbox_inches='tight') output = Output() with output: pyplot.show() link = HTML() filename = str( os.path.join('../utils/output', os.path.basename(tempfile_path))) link.value = FileLink(filename)._format_path() display(VBox([output, link]))
def ipythontutor(self, line, cell): env = self.parse_line(line) pt_env = dict(code=cell, mode="display", origin="opt-frontend.js", textReferences="false") for pass_through in ('py', 'curInstr', 'verticalStack', 'heapPrimitives'): pt_env[pass_through] = env[pass_through] request = urlencode(pt_env) url = f"{env['proto']}://pythontutor.com/iframe-embed.html#{request}" # ----------------linkButton------------------------ if strtobool(env['linkButton']): button = Button(description='Ouvrir dans un onglet') output = Output() def open_in_new_tab(b): with output: webbrowser.open_new_tab(url) button.on_click(open_in_new_tab) display(button, output) # --------------------------------------------------- frameid = self.newid() # xxx the attempt of inserting a container is so that we can set # max-width and max-height, but in this version it's still not quite right # and some real estate gets lots in the mix... containerid = self.newid() fstyle = f"<style>#{frameid} {self.ratio_style(env)}</style>" ptwidth, ptheight = env['_ptwidth'], env['_ptheight'] iframe = (f'<iframe id="{frameid}" class="pythontutor"' f' width="{ptwidth}" height="{ptheight}"' f' src="{url}">') cstyle = ( f"<style>#{containerid} " f"{{ max-width:{env['width']}px; max-height:{env['height']}px; " f"box-sizing:border-box; }}" f"</style>") container = f'<div id={containerid}>{iframe}</div>' #print(fstyle); print(cstyle); print(container) return HTML(fstyle + cstyle + container)
def __init__(self, base=None, filetype='*.msh5', N=None): if N is None: N = int(input('how many spectra do you want to compare: ')) self.Chooser = FileChooser(base=base, filetype=filetype, mode='r', show=False) self.bsel = widgets.Button(description='Copy',layout=Layout(width='10%'), button_style='info', # 'success', 'info', 'warning', 'danger' or '' tooltip='copy selected data-set to entry below') self.to = widgets.IntText(value=1,min=1,max=N,layout=Layout(width='10%')) self.bsel.on_click(self.copy) self.bdisplay = widgets.Button(description='Display',layout=Layout(width='10%'), button_style='info', # 'success', 'info', 'warning', 'danger' or '' tooltip='display superimposition') self.bdisplay.on_click(self.display) self.spec = Output(layout={'border': '1px solid black'}) self.DataList = [SpforSuper(i+1,'None') for i in range(N)] self.DataList[0].color.value = 'black' self.DataList[0].fig = True # switches on the very first one
def __init__(self, tensor_rep): """ Constructor of the interactive dashboard Parameters ---------- tensor_rep : {TensorCPD, TensorTKD} """ self.tensor_rep = tensor_rep self.available_plots = _DEFAULT_1D_PLOTS.copy() self.out = Output() self.sliders = self._create_fmat_sliders() self.dropdown = self._create_fmat_dropdown() self.dashboard = VBox([self.out, HBox(self.sliders), HBox(self.dropdown) ]) self._start_interacting()
def clean_temp(hide=False): import shutil from IPython.display import display from ipywidgets import Button, Output, HBox progress = Output() def outlog(*text): progress.clear_output() with progress: print(*text) temppath = get_value(['paths', 'temp']) directory = os.listdir(temppath) if len(directory) > 0: outlog(f"Your temp folder '{temppath}' has old files:", f" '{directory}', do you want to delete them? ") clean_temp = Button( value=False, description='Empty temp folder', disabled=False, button_style='danger', tooltip='Delete all data from the temporary folder.', icon='trash' ) clean_box = HBox([clean_temp, progress]) @clean_temp.on_click def clean_temp_on_click(b): temppath = get_value(['paths', 'temp']) directory = os.listdir(temppath) for i in directory: try: shutil.rmtree(f'{temppath}{i}') except Exception: os.remove(f'{temppath}{i}') outlog(f"The '{temppath}' folder is now empty.") if hide is False: return clean_box elif hide is True and len(directory) > 0: return clean_box else: return HBox([])
def interactive_inversion(rho_sliders,dep_cells): button = Button(description="Run inversion!") output = Output() display(button, output) def on_button_clicked(b): print('Running inversion...') with output: clear_output(True) mopt = prob_and_run(rho_sliders,dep_cells) ax = plot_results(mopt,expmap,rho_sliders,dep_cells) show_inline_matplotlib_plots() return button.on_click(on_button_clicked) show_inline_matplotlib_plots() return button,output
def __init__(self, app_name: str, dev: bool = False, embedded_error_log: bool = False): self.dev = dev current_dir = os.path.dirname(os.path.abspath(__file__)) if dev: infile = os.path.join(current_dir, f"../../webapps/{app_name}/build/static/js/main.js") if not os.path.exists(infile): infile = os.path.join(current_dir, f"jscodes/{app_name}.js.gz") else: infile = os.path.join(current_dir, f"jscodes/{app_name}.js.gz") self.jscode = deserialize_text(infile) self.app_id = str(uuid4()) self.app_js_render_fn = "".join([s.capitalize() for s in app_name.replace("-", "_").split("_")]) + "." + ('renderDevApp' if self.dev else 'renderApp') self.tunnel = SlowTunnelWidget() self.tunnel.on_receive(self.communicate) self.app_is_loaded = False self.error_container = [] if embedded_error_log: self.error_container.append(Output())
def __enter__(self): from IPython.display import display from ipywidgets import Output if self.initial_plot: # close all previous plots import matplotlib.pyplot as plt plt.close('all') # create output widget for capturing all plotting self._ipython_out = Output() if self.show: # only show the widget if necessary display(self._ipython_out) # capture plots in the output widget self._ipython_out.__enter__()
def make_confusion_matrix(): def on_button_clicked(selection): with out: clear_output(wait=True) x = plot_confusion_matrix(selection['new']) x.show() button = widgets.ToggleButtons( options = list_model_name, description='CM:', disabled=False, index = None, button_style='') button.observe(on_button_clicked, names=['value']) dis(button) out = Output() dis(out)
def listen_to_interact(self, _range1, _range2, stopwords): if stopwords == 'Not included': if self.conflicts_dict["Not included"] is None: conflicts_not_included = remove_stopwords( self.sources["tokens_source"]["conflicts_all"], self.lng).reset_index(drop=True) self.conflicts_dict["Not included"] = self.add_columns( conflicts_not_included) self.conflicts_dict["Not included"] = self.get_displayed_df( _range1, _range2, self.conflicts_dict["Not included"]) conflicts = self.conflicts_dict["Not included"] else: conflicts = self.conflicts_dict["Not included"] else: if self.conflicts_dict["Included"] is None: link_df = self.sources["tokens_source"]["conflicts_all"] self.conflicts_dict["Included"] = link_df del link_df conflicts_included = self.add_columns( self.conflicts_dict["Included"]) self.conflicts_dict["Included"] = self.add_columns( conflicts_included) self.conflicts_dict["Not Included"] = self.get_displayed_df( _range1, _range2, self.conflicts_dict["Included"]) conflicts = self.conflicts_dict["Included"] else: conflicts = self.conflicts_dict["Included"] if len(conflicts) > 0: self.qgrid_token_obj = qgrid.show_grid( conflicts, grid_options={'forceFitColumns': False}) display(self.qgrid_token_obj) self.out21 = Output() display(self.out21) self.qgrid_token_obj.observe(self.on_selection_change, names=['_selected_rows']) else: display(md(f'**There are no conflicting tokens in this page.**')) display( HTML( f'<a href="{get_previous_notebook()}" target="_blank">Go back to the previous workbook</a>' ))
def __init__(self): self.tab = Output(layout={'height': '650px'}) #self.tab = Output(layout={'height': 'auto'}) #self.tab.append_display_data(HTML(filename='doc/fury_client.html')) #self.tab.append_display_data(Javascript( # filename='doc/FuryWebClient.js')) html = \ """ <iframe src='http://fury.grg.sice.indiana.edu/tumor/' height='650' width='50%'> </iframe> """ html = \ """ <iframe src='doc/fury_client.html' height='650' width='50%'> </iframe> """ html = \ """ <iframe src='doc/fury_client.html' height='650' width='50%' align="left" id="fury_frame"> </iframe> <iframe src='https://fury-server.hubzero.org/tumor/' height='650' width='50%' align="right" id="nh_frame"> </iframe> """ html = \ """ <iframe src='https://fury-server.hubzero.org/tumor/' height='650' width='50%' id="nh_frame" style="-webkit-transform:scale(0.8);-moz-transform-scale(0.8); -moz-transform-origin: top left; -webkit-transform-origin: top left; -o-transform-origin: top left; -ms-transform-origin: top left; transform-origin: top left;"> </iframe> """ # Integrated client does not work on Chrome. # html = \ # """ # <iframe src='doc/fury_client.html' height='650' width='50%' # align="left" id="nh_frame"> # </iframe> # """ self.tab.append_display_data(HTML(html)) js = \ """
def __init__(self, df, *args, **kwargs): self._df = df self.cur_frame = 0 if df.frame.astype(int).max() > 1 else -1 self.indexes = (df.index[0], df.index[-1]) self.start = df.index[0] self.columns = df.columns.tolist() self._controls = self._init_gui() gui = GUIBox(tuple(self._controls.values())) _ = kwargs.pop('layout', None) self._output = Output() children = [gui, self._output] self._update_output() super(DFBox, self).__init__(children, layout=_bboxlo, **kwargs)
def suspension_model(): rolldice = Button( description='ROLL THE DICE', tooltip='generate a random set of parameters for the model') out = Output() def on_button_clicked(b): with out: clear_output(True) plot_suspension_model() rolldice.on_click(on_button_clicked) with out: plot_suspension_model() #rolldice.on_click(lambda x: plot_suspension_model()) return VBox([out, rolldice])
def register(self): username_box = Text(value=None, placeholder="username", description="Username: "******"Suggested password : "******"Password: "******"") conf_password_box = Password(description="Confirm: ", placeholder="") register_button = Button(description="Register", button_style="primary", layout=Layout(width="10%")) status_text = HTML(value="<font color='blue'>Enter credentials</font>") output_box = Output() base_url = "https://hugs.acquire-aaai.com/t" def register_user(a): if password_box.value != conf_password_box.value: with output_box: status_text.value = ( "<font color='red'>Passwords do not match</font>") else: result = User.register( username=username_box.value, password=password_box.value, identity_url=f"{base_url}/identity", ) with output_box: status_text.value = "<font color='green'>Please scan QR code with authenticator app</font>" display(result["qrcode"]) register_button.on_click(register_user) return VBox(children=[ username_box, suggested_password, password_box, conf_password_box, register_button, status_text, output_box, ])
def create_text_scatter_plots(texts, labels, _vec, n_dimensions=2, dim_reduction=True, layout=None): assert n_dimensions in (2, 3) texts = np.asarray(texts) pipeline = [_vec] if dim_reduction: pipeline.extend([TruncatedSVD(50), Normalizer(copy=False)]) pipeline.append(TSNE(n_components=n_dimensions, random_state=0)) pipeline = make_pipeline(*pipeline) dim_names = ('x', 'y', 'z') X = pipeline.fit_transform(texts) plotly_scatter_class = go.Scatter if n_dimensions == 2 else go.Scatter3d out = Output() fig = go.FigureWidget() for label in labels.unique(): ix = labels == label X_label = X[ix] X_dims_named = dict(zip(dim_names, X_label.T)) fig.add_trace( plotly_scatter_class( **X_dims_named, mode='markers', marker=dict(size=10, symbol='circle', opacity=0.8), name=label, )) scatter = fig.data[-1] scatter.on_click(_create_scatter_on_click(texts[ix], out)) _layout = dict(margin=dict(l=0, r=0, b=0, t=0)) if layout is not None: _layout.update(layout) fig.update_layout(**_layout) return VBox([fig, out])
def __init__(self, corpus: VectorizedCorpus = None, name: str = "TopTokens", **opts): super().__init__(name=name, **opts) self.simple_display: bool = False self.corpus: VectorizedCorpus = corpus self._keyness: Dropdown = self.keyness_widget() self._placeholder: VBox = VBox() self._top_count: Dropdown = Dropdown( options=[10**i for i in range(0, 7)], value=100, placeholder='Record count limit', layout=Layout(width='auto'), ) self._compute: Button = Button(description="Compute", button_style='success', layout=Layout(width='auto')) self._save = Button(description='Save data', layout=Layout(width='auto')) self._download = Button(description='Download data', layout=Layout(width='auto')) self._download_output: Output = Output() self._alert: HTML = HTML('.') self._kind: Dropdown = Dropdown( options=['token', 'token/count', 'token+count'], value='token+count', description='', disabled=False, layout=Layout(width='100px'), ) self._temporal_key: Dropdown = Dropdown( options=['year', 'lustrum', 'decade'], value='decade', description='', disabled=False, layout=Layout(width='100px'), ) self.category_name = "time_period" self._table: gu.DataGridOutput = None self._output: Output = None
def __init__(self, T=2, a=2): self.out = Output(layout={'width': '980px', 'height': '400px'}) self.axs = [] self.samples = 81 self.T = T self.t = np.linspace(-10, 10, self.samples) self.a = a self.s = np.sinc(self.t / self.a)**2 self.s_FT = np.abs(np.fft.fftshift(np.fft.fft(self.s))) self.w = np.linspace(-np.pi, np.pi, len(self.s_FT)) self.undersample_signal() self.init_figure() self.T_slider = widgets.IntSlider(value=self.T, min=1, max=20, step=1, description='T') self.T_slider.observe(self.on_T_change, names='value') self.samples_slider = widgets.IntSlider(value=self.samples, min=21, max=501, step=20, description='Samples') self.samples_slider.observe(self.on_samples_change, names='value') self.a_slider = widgets.FloatSlider(value=self.a, min=1, max=5, step=0.1, description='a') self.a_slider.observe(self.on_a_change, names='value') display( VBox([ self.out, HBox([self.T_slider, self.samples_slider, self.a_slider]) ]))
def fast_model_selection(df_metrics, prediction_type, X_test, y_test): global confusion_matrix_dict out = Output() display.display(out) confusion_matrix_dict = {} for model in tqdm(models_list): model[0].fit(X_train, y_train) df_metrics = create_df_metrics(model, df_metrics, prediction_type, X_test, y_test) with out: html = (df_metrics.style .apply(highlight_min) .apply(highlight_max)) display.clear_output(wait=True) display.display(html) confusion_matrix_dict[model[1]] = [model[0], y_test, model[0].predict(X_test)] make_confusion_matrix()
def _build_highlights_accordion(self) -> DOMWidget: """ Creates a widget that displays highlights for this `Tier` in an `ipywidgets.Accordion` - which is nice! """ highlights = self.tier.get_highlights() if not highlights: return None widget = Accordion() for i, (name, highlight) in enumerate(highlights.items()): out = Output() widget.children = (*widget.children, out) with out: for item in highlight: publish_display_data(**item) widget.set_title(i, name) widget.selected_index = None return widget
def __init__(self, name: str = "Network", **opts): super().__init__(name=name, **opts) self.network: ipycytoscape.CytoscapeWidget = None self._view: Output = Output() self._node_spacing: IntSlider = IntSlider(description='', min=3, max=500, value=50, layout={'width': '200px'}) self._edge_length_val: IntSlider = IntSlider( description='', min=3, max=500, value=50, layout={'width': '200px'} ) self._padding: IntSlider = IntSlider(description='', min=3, max=500, value=50, layout={'width': '200px'}) self._label: HTML = HTML(value=' ', layout={'width': '200px'}) self._network_layout = Dropdown( description='', options=['cola', 'klay', 'circle', 'concentric'], value='cola', layout={'width': '115px'}, ) self._relayout = Button( description="Continue", button_style='Info', layout=Layout(width='115px', background_color='blue') ) self._animate: Checkbox = ToggleButton( description="Animate", icon='check', value=True, layout={'width': '115px'}, ) self._curve_style = Dropdown( description='', options=[ ('Straight line', 'haystack'), ('Curve, Bezier', 'bezier'), ('Curve, Bezier*', 'unbundled-bezier'), ], value='haystack', layout={'width': '115px'}, ) self._custom_styles: dict = None self._buzy: bool = False
def _distanceBox(self): #TODO: Find way to automatically update the table when there # is a change in the selected atoms on the javascript side. atom_df = Button(description='Distance', layout=_wlo) clear_selected = Button(description='Clear Sel.') get_selected = Button(description='Update out') select_opt = HBox([clear_selected, get_selected], layout=_wlo) out = Output(layout=_wlo) #selected = Dict().tag(sync=True) def _atom_df(c): c.value = not c.value if c.value: self._update_output(out) #link((self.scenes[0].selected, 'value'), (selected, 'value')) else: out.clear_output() def _clear_selected(c): for scn in self.active(): scn.clear_selected = not scn.clear_selected out.clear_output() def _get_selected(c): self._update_output(out) #selected = List(Dict()).tag(sync=True) #for scn in self.active(): # selected.append(scn.selected) # #@observe('selected') #def _selected(c): # print(c) atom_df.on_click(_atom_df) atom_df.value = False clear_selected.on_click(_clear_selected) get_selected.on_click(_get_selected) content = _ListDict([('out', out), ('select_opt', select_opt)]) return Folder(atom_df, content)
def __init__(self, atoms, data=[], xsize=1000, ysize=500): self.view = self._init_nglview(atoms, data, xsize, ysize) self.widgets = { 'radius': FloatSlider(value=0.8, min=0.0, max=1.5, step=0.01, description='Ball size'), 'color_scheme': Dropdown(description='Solor scheme:'), 'colorbar': Output() } self.show_colorbar(data) self.widgets['radius'].observe(self._update_repr) self.gui = VBox( [self.view, self.widgets['colorbar'], self.widgets['radius']])
def _on_cluster_button_clicked(self, _) -> None: self._buttons["cluster"].enabled = False self._routes.cluster(self._input["number_clusters"].value) self._buttons["cluster"].enabled = True outputs = [] for i, cluster in enumerate(self._routes.clusters or []): output = Output( layout={ "border": "1px solid silver", "width": "99%", "height": "500px", "overflow_y": "auto", }) with output: for image in cluster.images: print(f"Route {self._routes.images.index(image)+1}") display(image) outputs.append(output) self._output["clusters"].set_title(i, f"Cluster {i+1}") self._output["clusters"].children = outputs
def _create_input(self) -> None: self._input["number_clusters"] = BoundedIntText( continuous_update=True, min=1, max=len(self._routes) - 1, layout={"width": "80px"}, ) self._buttons["cluster"] = Button(description="Cluster") self._buttons["cluster"].on_click(self._on_cluster_button_clicked) box = HBox([ Label("Number of clusters to make"), self._input["number_clusters"], self._buttons["cluster"], ]) display(box) help_out = Output() with help_out: print( "Optimization is carried out if the number of given clusters are less than 2" ) display(help_out)
def _create_dendrogram(self) -> None: dend_out = Output(layout={ "width": "99%", "height": "310px", "overflow_y": "auto" }) with dend_out: print("This is the hierarchy of the routes") fig = plt.Figure() dendrogram( ClusteringHelper( self._routes.distance_matrix()).linkage_matrix(), color_threshold=0.0, labels=np.arange(1, len(self._routes) + 1), ax=fig.gca(), ) fig.gca().set_xlabel("Route") fig.gca().set_ylabel("Distance") display(fig) display(dend_out)
def interactive_output(f, controls, process_controls=lambda x: x): """Connect widget controls to a function. This function does not generate a user interface for the widgets (unlike `interact`). This enables customisation of the widget user interface layout. The user interface layout must be defined and displayed manually. """ out = Output() def observer(change): show_inline_matplotlib_plots() with out: clear_output(wait=True) f(**unpack_controls(controls, process_controls)) show_inline_matplotlib_plots() for k, w in controls.items(): w.observe(observer, 'value') show_inline_matplotlib_plots() observer(None) return out