def __init__(self, addenda, key, default_key=None, *pargs, **kwargs): super(GraphDiagramWidget, self).__init__(*pargs, **kwargs) initialize() self.addenda = addenda self.key = key self.default_key = default_key self.history = [] self.count = 0 self.selected_edge = None self.selected_node = None self.label_id = None w = self.configure_widget() lt = self.label_text = widgets.Text(value="", width="200px") lt.layout.width = "200px" lt.on_trait_change(self.label_change, "value") n = self.new_button = widgets.Button(description="O") ly = self.layout_button = widgets.Button(description="layout") dl = self.delete_button = widgets.Button(description="X") sv = self.save_button = widgets.Button(description="save") rv = self.revert_button = widgets.Button(description="revert") sn = self.snap_button = widgets.Button(description="snap") sv.on_click(self.save_click) rv.on_click(self.revert_click) sn.on_click(self.snap_click) dl.on_click(self.delete_click) dl.layout.width = "50px" n.layout.width = "50px" n.on_click(self.new_click) ly.on_click(self.layout_click) info = self.info_area = widgets.Textarea(description="status") info.visible = False # node details ns = self.node_shape = widgets.Dropdown(description="shape", options=SHAPES, value="ellipse") ns.layout.width = "100px" #nbc = self.node_background_color = widgets.Text(description="color", width="200px") nbc_html = widgets.HTML("node color") nbc = self.node_background_color = color_widget.ColorPicker() nbc.draw() nbi = self.node_background_image = widgets.Text(description="image", width="200px") nbi.layout.width = "200px" # label details #lbc = self.label_color = widgets.Text(description="label color", width="200px") lbc_html = widgets.HTML("label color") lbc = self.label_color = color_widget.ColorPicker() lbc.draw() lfs = self.label_font_size = widgets.IntSlider(description="font size", value=0, min=0, max=50, width="50px") lfs.layout.width = "150px" lal = self.label_align = widgets.Dropdown( description="align", options=["", "top", "center", "bottom"], value="center") lal.layout.width = "150px" # edge details #edc = self.edge_color = widgets.Text(description="edge color", width="200px") edc_html = widgets.HTML("edge color") edc = self.edge_color = color_widget.ColorPicker() edc.draw() eds = self.edge_style = widgets.Dropdown( description="edge style", options=["", "solid", "dotted", "dashed"], value="solid") eds.width = "150px" # detail control buttons applyb = self.apply_button = widgets.Button(description="apply") resetb = self.reset_button = widgets.Button(description="reset") resetb.on_click(self.reset_inputs) applyb.on_click(self.apply_click) # scaffolding dcb = self.details_checkbox = widgets.Checkbox(description="details", value=False) top = widgets.HBox(children=[n, lt, ly, dl, sn, sv, rv, dcb]) dlabel = widgets.VBox(children=[lbc_html, lbc.svg, lfs, lal]) dnode = widgets.VBox(children=[ns, nbc_html, nbc.svg, nbi]) dedge = widgets.VBox(children=[edc_html, edc.svg, eds]) detail = widgets.VBox(children=[dlabel, dnode, dedge, applyb, resetb]) detail.visible = False traitlets.link((detail, "visible"), (dcb, "value")) middle = widgets.HBox(children=[w, detail]) hideable = widgets.VBox(children=[top, middle, info]) self.view_checkbox = vcb = widgets.Checkbox(description="view", value=True) traitlets.link((vcb, "value"), (hideable, "visible")) a = self.assembly = widgets.VBox(children=[vcb, hideable]) # make the assembly big enough hideable.height = 650
def _volume_widets(v, lighting=False): import ipywidgets #angle1 = ipywidgets.FloatSlider(min=0, max=np.pi*2, value=v.angle1, description="angle1") #angle2 = ipywidgets.FloatSlider(min=0, max=np.pi*2, value=v.angle2, description="angle2") #ipywidgets.jslink((v, 'angle1'), (angle1, 'value')) #ipywidgets.jslink((v, 'angle2'), (angle2, 'value')) if lighting: ambient_coefficient = ipywidgets.FloatSlider( min=0, max=1, step=0.001, value=v.ambient_coefficient, description="ambient") diffuse_coefficient = ipywidgets.FloatSlider( min=0, max=1, step=0.001, value=v.diffuse_coefficient, description="diffuse") specular_coefficient = ipywidgets.FloatSlider( min=0, max=1, step=0.001, value=v.specular_coefficient, description="specular") specular_exponent = ipywidgets.FloatSlider(min=0, max=10, step=0.001, value=v.specular_exponent, description="specular exp") #angle2 = ipywidgets.FloatSlider(min=0, max=np.pi*2, value=v.angle2, description="angle2") ipywidgets.jslink((v, 'ambient_coefficient'), (ambient_coefficient, 'value')) ipywidgets.jslink((v, 'diffuse_coefficient'), (diffuse_coefficient, 'value')) ipywidgets.jslink((v, 'specular_coefficient'), (specular_coefficient, 'value')) ipywidgets.jslink((v, 'specular_exponent'), (specular_exponent, 'value')) widgets_bottom = [ ipywidgets.HBox([ambient_coefficient, diffuse_coefficient]), ipywidgets.HBox([specular_coefficient, specular_exponent]) ] else: widgets_bottom = [] v.ambient_coefficient = 1 v.diffuse_coefficient = 0 v.specular_coefficient = 0 if 1: stereo = widgets.ToggleButton(value=v.stereo, description='stereo', icon='eye') fullscreen = widgets.ToggleButton(value=v.stereo, description='fullscreen', icon='arrows-alt') ipywidgets.jslink((v, 'stereo'), (stereo, 'value')) ipywidgets.jslink((v, 'fullscreen'), (fullscreen, 'value')) widgets_bottom += [ipywidgets.HBox([stereo, fullscreen])] return ipywidgets.VBox([ v.tf.control(), v, ] + widgets_bottom # , ipywidgets.HBox([angle1, angle2]) )
def plot_sas(sas_data): """ Returns a widget object to plot one or more SasData class objects. Parameters: ----------- sas_data: SasData or iterable of SasData Scattering data provided as a single SasData object or iterable of SasData objects. """ try: sas_data = list(sas_data) except: sas_data = [sas_data] else: pass keys = [x for x in range(0, len(sas_data))] data_dict = dict(zip(keys, sas_data)) names = [x.label for x in sas_data] name_dict = dict(zip(keys, names)) # Widget Components select = widgets.SelectMultiple(options=[(v, k) for k, v in name_dict.items()], description='Samples (select multiple):', style={'description_width': 'initial'}, layout=widgets.Layout(flex='1 1 0%', width='auto', height='120px'), disabled=False) update_button = widgets.Button( description='Update Plot', disabled=False, layout=widgets.Layout(flex='1 1 0%', width='auto'), button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltip='Update Plot') add_button = widgets.Button( description='Add to Plot', disabled=False, layout=widgets.Layout(flex='1 1 0%', width='auto'), button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltip='Add to Plot') clear_button = widgets.Button( description='Clear Plot', disabled=False, layout=widgets.Layout(flex='1 1 0%', width='auto'), button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltip='Clear Plot') buttons = widgets.VBox([update_button, add_button, clear_button]) selection = widgets.HBox([select, buttons]) fig = go.FigureWidget() fig = fig.update_layout(xaxis_type="log", yaxis_type="log", height=500, showlegend=True, margin=dict(t=30)) fig = fig.update_xaxes(exponentformat='e', showexponent='all') fig = fig.update_yaxes(exponentformat='e', showexponent='all') widget = widgets.VBox([selection, fig]) widget # Interactive Widget Functions def update_plot(b): fig.data = [] for value in select.value: data = data_dict[value] fig.add_scatter(x=data.q, y=data.Iq, error_y=dict(array=data.dIq), mode='markers', name=data.label) def add_to_plot(b): current_data = [] for trace in fig.data: current_data.append(trace['name']) for value in select.value: data = data_dict[value] if data.label not in current_data: fig.add_scatter(x=data.q, y=data.Iq, error_y=dict(array=data.dIq), mode='markers', name=data.label) def clear_plot(b): fig.data = [] # Define Widget Responses update_button.on_click(update_plot) add_button.on_click(add_to_plot) clear_button.on_click(clear_plot) return (widget)
def __init__(self, scipp_obj=None, bins=None, masks=None, cmap=None, log=None, vmin=None, vmax=None, aspect=None, size=1, projection=None, nan_color=None, filename=None, continuous_update=None, dim=None): self.fig2d = None self.fig3d = None self.scatter2d = None self.scatter3d = None self.outline = None self.size = size self.aspect = aspect self.do_update = None self.figurewidget = widgets.Output() self.figure2d = False self.figure3d = False self.image = None self.nan_color = nan_color self.log = log self.current_projection = None self.dim = dim self.data_arrays = {} tp = type(scipp_obj) if tp is sc.Dataset or tp is sc.DatasetProxy: for key in sorted(scipp_obj.keys()): var = scipp_obj[key] if self.dim in var.dims: self.data_arrays[key] = var elif tp is sc.DataArray or tp is sc.DataProxy: self.data_arrays[scipp_obj.name] = scipp_obj else: raise RuntimeError("Unknown input type: {}. Allowed inputs " "are a Dataset or a DataArray (and their " "respective proxies).".format(tp)) self.globs = {"cmap": cmap, "log": log, "vmin": vmin, "vmax": vmax} self.params = {} self.hist_data_array = {} self.scalar_map = {} self.minmax = {} # Find the min/max time-of-flight limits and store them self.minmax["tof"] = [np.Inf, np.NINF, 1] for key, data_array in self.data_arrays.items(): bins_here = bins if data_array.sparse_dim is not None and bins_here is None: bins_here = True if bins_here is not None: dim = None if data_array.sparse_dim is not None else self.dim spdim = None if data_array.sparse_dim is None else self.dim var = make_bins(data_array=data_array, sparse_dim=spdim, dim=dim, bins=bins_here, padding=(data_array.sparse_dim is not None)) else: var = data_array.coords[self.dim] self.minmax["tof"][0] = min(self.minmax["tof"][0], var.values[0]) self.minmax["tof"][1] = max(self.minmax["tof"][1], var.values[-1]) self.minmax["tof"][2] = var.shape[0] # Rebin all DataArrays to common Tof axis self.rebin_data(np.linspace(*self.minmax["tof"])) # Create dropdown menu to select the DataArray keys = list(self.hist_data_array.keys()) self.dropdown = widgets.Dropdown(options=keys, description="Select entry:", layout={"width": "initial"}) self.dropdown.observe(self.change_data_array, names="value") # Store current active data entry (DataArray) self.key = keys[0] # Create a Tof slider and its label self.tof_dim_indx = self.hist_data_array[self.key].dims.index(self.dim) self.slider = widgets.IntSlider( value=0, min=0, step=1, description=str(self.dim).replace("Dim.", ""), max=self.hist_data_array[self.key].shape[self.tof_dim_indx] - 1, continuous_update=continuous_update, readout=False) self.slider.observe(self.update_colors, names="value") self.label = widgets.Label() # Add text boxes to change number of bins/bin size self.nbins = widgets.Text(value=str( self.hist_data_array[self.key].shape[self.tof_dim_indx]), description="Number of bins:", style={"description_width": "initial"}) self.nbins.on_submit(self.update_nbins) tof_values = self.hist_data_array[self.key].coords[self.dim].values self.bin_size = widgets.Text(value=str(tof_values[1] - tof_values[0]), description="Bin size:") self.bin_size.on_submit(self.update_bin_size) projections = [ "3D", "Cylindrical X", "Cylindrical Y", "Cylindrical Z", "Spherical X", "Spherical Y", "Spherical Z" ] # Create toggle buttons to change projection self.buttons = {} for p in projections: self.buttons[p] = widgets.Button( description=p, disabled=False, button_style=("info" if (p == projection) else "")) self.buttons[p].on_click(self.change_projection) items = [self.buttons["3D"]] for x in "XYZ": items.append(self.buttons["Cylindrical {}".format(x)]) items.append(self.buttons["Spherical {}".format(x)]) if x != "Z": items.append(widgets.Label()) self.togglebuttons = widgets.GridBox( items, layout=widgets.Layout(grid_template_columns="repeat(3, 150px)")) # Place widgets in boxes self.vbox = widgets.VBox([ widgets.HBox([self.dropdown, self.slider, self.label]), widgets.HBox([self.nbins, self.bin_size]), self.togglebuttons ]) self.box = widgets.VBox([self.figurewidget, self.vbox]) self.box.layout.align_items = "center" # Protect against uninstalled ipyvolume if ipv is None and projection == "3D": print("Warning: 3D projection requires ipyvolume to be " "installed. Use conda/pip install ipyvolume. Reverting to " "2D projection.") self.buttons[projections[1]].button_style = "info" self.buttons["3D"].button_style = "" self.buttons["3D"].disabled = True # Render the plot here instead of at the top level because to capture # the matplotlib output (if a 2D projection is requested to begin with, # the output widget needs to be displayed first, before any mpl figure # is displayed. render_plot(widgets=self.box, filename=filename, ipv=ipv) # Get detector positions self.det_pos = np.array( sn.position(self.hist_data_array[self.key]).values) # Find extents of the detectors for i, x in enumerate("xyz"): self.minmax[x] = [ np.amin(self.det_pos[:, i]), np.amax(self.det_pos[:, i]) ] # Update the figure self.change_projection(self.buttons[projection]) # Create members object self.members = { "widgets": { "sliders": self.slider, "buttons": self.buttons, "text": { "nbins": self.nbins, "bin_size": self.bin_size }, "dropdown": self.dropdown }, "fig2d": self.fig2d, "fig3d": self.fig3d, "scatter2d": self.scatter2d, "scatter3d": self.scatter3d, "outline": self.outline } return
def display(self, corpus=None): def buzy(is_buzy): self.model_widgets.compute.disabled = is_buzy self.model_widgets.spinner.layout.visibility = 'visible' if is_buzy else 'hidden' def compute_topic_model_handler(*args): self.model_widgets.output.clear_output() buzy(True) gensim_logger.setLevel(logging.INFO if self.model_widgets. show_trace.value else logging.WARNING) with self.model_widgets.output: try: vectorizer_args = dict( apply_idf=self.model_widgets.apply_idf.value) topic_modeller_args = dict( n_topics=self.model_widgets.n_topics.value, max_iter=self.model_widgets.max_iter.value, learning_method='online', n_jobs=1) method = self.model_widgets.method.value terms = list(self.get_corpus_terms(corpus)) self.state.data = compute_topic_model( self.data_folder, method, terms, self.document_index, vectorizer_args, topic_modeller_args) topics = topic_model_utility.get_topics_unstacked( self.state.topic_model, n_tokens=100, id2term=self.state.id2term, topic_ids=self.state.relevant_topics) display(topics) except Exception as ex: logger.error(ex) self.state.data = None raise finally: buzy(False) self.model_widgets.compute.on_click(compute_topic_model_handler) def method_change_handler(*args): with self.model_widgets.output: self.model_widgets.compute.disabled = True method = self.model_widgets.method.value self.model_widgets.apply_idf.disabled = False self.model_widgets.apply_idf.description = 'Apply TF-IDF' if method.startswith( 'gensim') else 'Apply IDF' if 'MALLET' in method: self.model_widgets.apply_idf.description = 'TF-IDF N/A' self.model_widgets.apply_idf.disabled = True self.model_widgets.n_topics.disabled = False if 'HDP' in method: self.model_widgets.n_topics.value = self.model_widgets.n_topics.max self.model_widgets.n_topics.disabled = True self.model_widgets.compute.disabled = False self.model_widgets.method.observe(method_change_handler, 'value') method_change_handler() display( widgets.VBox( [widgets.HBox(self.widget_boxes), self.model_widgets.output]))
def get_data_tab_net(self): refresh_button = widgets.Button(description='Refresh', tooltip='Refresh region dropdown menu') region_dropdown = widgets.Dropdown(description='Region:', options=['None'], disabled=False) download_button = widgets.Button(description='Download', optiona=['None'], tooltip='Download and load model') def refresh(b): self.open_data_output.clear_output() success = True try: folders_resp = requests.get( 'http://data.ipypm.ca/list_data_folders/covid19') except requests.exceptions.RequestException as error: with self.open_data_output: print('Error retrieving data folder list over network:') print() print(error) success = False if success: self.region_data_folders = folders_resp.json() region_list = list(self.region_data_folders.keys()) region_list.sort() region_dropdown.options = ['None'] + region_list refresh_button.on_click(refresh) def download(b): self.open_data_output.clear_output() self.region_data_output.clear_output() region = region_dropdown.value if region != 'None': data_folder = self.region_data_folders[region] success = True try: data_desc_resp = requests.get( 'http://data.ipypm.ca/get_data_desc/' + data_folder) except requests.exceptions.RequestException as error: with self.open_data_output: print('Error retrieving data description over network:') print() print(error) success = False if success: self.data_description = data_desc_resp.json() self.data_description['folder'] = data_folder with self.open_data_output: print(self.data_description['description']) print('Source: ' + self.data_description['source']) print('URL: ' + self.data_description['source_url']) with self.region_data_output: for region_name in list( self.data_description['regional_data'].keys()): print(region_name) # tell the explorer that a new data file was loaded self.new_data_opened() # load the data into a panda dictionary self.pd_dict = {} for filename in self.data_description['files']: path = data_folder + '/' + filename success = True try: csv_resp = requests.get( 'http://data.ipypm.ca/get_csv/' + path, stream=True) except requests.exceptions.RequestException as error: with self.open_data_output: print('Error retrieving data over network:') print() print(error) success = False if success: self.pd_dict[filename] = pd.read_csv(csv_resp.raw) download_button.on_click(download) v_box1 = widgets.VBox([ refresh_button, region_dropdown, download_button, self.open_data_output ]) items = [v_box1, self.region_data_output] h_box = widgets.HBox(items) return h_box
def get_model_tab_net(self): refresh_button = widgets.Button(description='Refresh Regions', tooltip='Refresh region dropdown menu') region_dropdown = widgets.Dropdown(description='Region:', options=['None'], disabled=False) model_dropdown = widgets.Dropdown(description='Model:', options=['None'], disabled=False) download_button = widgets.Button(description='Download', tooltip='Load model for explore/analysis') def refresh(b): self.open_model_output.clear_output() success = True try: folders_resp = requests.get( 'http://data.ipypm.ca/list_model_folders/covid19') except requests.exceptions.RequestException as error: with self.open_model_output: print('Error retrieving model folders over network:') print() print(error) success = False if success: self.region_model_folders = folders_resp.json() region_list = list(self.region_model_folders.keys()) region_list.sort() region_dropdown.options = ['None'] + region_list refresh_button.on_click(refresh) def region_dropdown_eventhandler(change): self.open_model_output.clear_output() region = region_dropdown.value if region != 'None': folder = self.region_model_folders[region] success = True try: models_resp = requests.get( 'http://data.ipypm.ca/list_models/' + folder) except requests.exceptions.RequestException as error: with self.open_model_output: print('Error retrieving model list over network:') print() print(error) success = False if success: self.model_filenames = models_resp.json() model_list = list(self.model_filenames.keys()) model_list.sort() model_dropdown.options = model_list region_dropdown.observe(region_dropdown_eventhandler, names='value') def download(b): self.open_model_output.clear_output() model = model_dropdown.value if model != 'None': model_fn = self.model_filenames[model] success = True try: pypm_resp = requests.get('http://data.ipypm.ca/get_pypm/' + model_fn, stream=True) except requests.exceptions.RequestException as error: with self.open_model_output: print('Error retrieving model over network:') print() print(error) success = False if success: my_pickle = pypm_resp.content filename = model_fn.split('/')[-1] model = self.open_model(filename, my_pickle) if model is not None: self.model = model self.model_name.value = self.model.name self.model_description.value = self.model.description self.model_t0.value = self.model.t0 self.model_time_step.value = self.model.get_time_step() self.all_tabs() download_button.on_click(download) download_label = widgets.Label(value='Open model for analysis:') v_box_1 = widgets.VBox([ refresh_button, region_dropdown, model_dropdown, widgets.HBox([download_label, download_button]), self.model_name, self.model_description ]) # Compare A and B model loaded here: download_buttons = [ widgets.Button(description='Download - A', tooltip='Load model for Compare A'), widgets.Button(description='Download - B', tooltip='Load model for Compare B') ] def download_0(b): self.open_model_output.clear_output() model = model_dropdown.value if model != 'None': model_fn = self.model_filenames[model] success = True try: pypm_resp = requests.get('http://data.ipypm.ca/get_pypm/' + model_fn, stream=True) except requests.exceptions.RequestException as error: with self.open_model_output: print('Error retrieving model over network:') print() print(error) success = False if success: my_pickle = pypm_resp.content filename = model_fn.split('/')[-1] model = self.open_model(filename, my_pickle) if model is not None: self.models_compare['a'] = model self.model_names[0].value = self.models_compare['a'].name self.model_descriptions[0].value = self.models_compare[ 'a'].description self.models_total_population['a'] = get_total_population( self.models_compare['a']) def download_1(b): self.open_model_output.clear_output() model = model_dropdown.value if model != 'None': model_fn = self.model_filenames[model] success = True try: pypm_resp = requests.get('http://data.ipypm.ca/get_pypm/' + model_fn, stream=True) except requests.exceptions.RequestException as error: with self.open_model_output: print('Error retrieving model over network:') print() print(error) success = False if success: my_pickle = pypm_resp.content filename = model_fn.split('/')[-1] model = self.open_model(filename, my_pickle) if model is not None: self.models_compare['b'] = model self.model_names[1].value = self.models_compare['b'].name self.model_descriptions[1].value = self.models_compare[ 'b'].description self.models_total_population['b'] = get_total_population( self.models_compare['b']) download_buttons[0].on_click(download_0) download_buttons[1].on_click(download_1) download_label_A = widgets.Label(value='Open model for compare A:') download_label_B = widgets.Label(value='Open model for compare B:') v_box_A = widgets.VBox([ widgets.HBox([download_label_A, download_buttons[0]]), self.model_names[0], self.model_descriptions[0] ]) v_box_B = widgets.VBox([ widgets.HBox([download_label_B, download_buttons[1]]), self.model_names[1], self.model_descriptions[1] ]) hspace = widgets.HTML(value=" " * 4, placeholder='Some HTML', description='') return widgets.HBox([ widgets.VBox([v_box_1, v_box_A, v_box_B]), hspace, self.open_model_output ])
# write_config_button.on_click(write_config_file_cb) # write_config_box = widgets.Text( # placeholder='my_nanobio_settings.xml', # description='', # ) # write_config_row = widgets.HBox([write_config_button, write_config_box]) titles = [ 'Config Basics', 'Cell Properties', 'Nanoparticles', 'Out: Cell Plots', 'Out: Substrate Plots' ] tabs = widgets.Tab( children=[config_tab.tab, cells.tab, nanopart.tab, svg.tab, sub.tab], _titles={i: t for i, t in enumerate(titles)}, layout=tab_layout) homedir = os.getcwd() if nanoHUB_flag: remote_cb = widgets.Checkbox( indent=False, value=False, description='Submit as Batch Job to Clusters/Grid') #gui = widgets.VBox(children=[read_config, tabs, write_config_row, remote_cb, run_button.w]) gui = widgets.VBox(children=[read_config, tabs, remote_cb, run_button.w]) else: #gui = widgets.VBox(children=[read_config, tabs, write_config_row, run_button.w]) gui = widgets.VBox(children=[read_config, tabs, run_button.w]) fill_gui_params(read_config.options['DEFAULT'])
def plot_solution(path, filename): coarse_vecs = [] coarse_files = glob(path + '/coarse_vec*.vts') for i in range(len(coarse_files)): coarse_vecs.append( read_coarse_vec(path + '/coarse_vec_{}.vts'.format(i))) cg_ites = [] cg_files = glob(path + '/cg_ite_*.vts') for i in range(len(cg_files)): cg_ites.append(read_coarse_vec(path + '/cg_ite_{}.vts'.format(i))) dim, coords, index, numpy_arrays, fieldnames = read_data(path + '/' + filename) work = np.zeros_like(coords) faces_, edges_ = get_faces_and_edges(index) irank = fieldnames.index('rank') faces_by_rank = [] edges_by_rank = [] for i in range(int(numpy_arrays[irank].max()) + 1): mask = numpy_arrays[irank] == i ranges = np.arange(mask.size)[mask] indices = np.in1d(faces_, ranges) indices = np.all(indices.reshape(faces_.shape), axis=1) faces_by_rank.append(faces_[indices]) indices = np.in1d(edges_, ranges) indices = np.all(indices.reshape(edges_.shape), axis=1) edges_by_rank.append(edges_[indices]) bcolor = BufferAttribute(array=scalar2rgb(numpy_arrays[0])[faces_], normalized=False) vertices = BufferAttribute(array=coords[faces_].reshape(-1, 3), normalized=False) geometry = BufferGeometry(attributes={ 'position': vertices, 'color': bcolor }) material = MeshBasicMaterial(color='0xffffff', wireframe=True) material_color = MeshLambertMaterial(side='DoubleSide', color='0xF5F5F5', vertexColors='VertexColors', transparent=True, opacity=0.5) mesh_color = Mesh(geometry, material_color) edges = BufferAttribute(array=coords[edges_].reshape(-1, 3), normalized=False) geom_edges = BufferGeometry(attributes={'position': edges}) material = LineBasicMaterial(color='0xffffff', linewidth=1) mesh = LineSegments(geom_edges, material) view_width = 600 view_height = 600 camera = PerspectiveCamera(fov=50, position=[0, 0, 13], aspect=view_width / view_height) ambient_light = AmbientLight() scene = Scene() scene.add(mesh_color) scene.add(mesh) scene.add(ambient_light) minCoords = coords.min(axis=0) maxCoords = coords.max(axis=0) midCoords = 0.5 * (minCoords + maxCoords) scene.position = tuple(-midCoords) scene.background = 'black' controller = OrbitControls(controlling=camera) if dim == 2: controller.enableRotate = False renderer = Renderer(camera=camera, scene=scene, controls=[controller], width=view_width, height=view_height) fields = OrderedDict() for v, k in enumerate(fieldnames): fields[k] = v select = widgets.Dropdown(options=fields, value=0, description='Fields') irank = fieldnames.index('rank') domain = OrderedDict({'all': -1}) for i in range(int(numpy_arrays[irank].max()) + 1): domain[('domain {}').format(i)] = i select_dom = widgets.Dropdown(options=domain, value=-1, description='domains') coarse_vecs_label = OrderedDict({'none': -1}) for i in range(len(coarse_vecs)): coarse_vecs_label[('coarse vec {}').format(i)] = i for i in range(len(cg_ites)): coarse_vecs_label[('cg iteration {}').format(i)] = len(coarse_vecs) + i select_coarse_vecs = widgets.Dropdown(options=coarse_vecs_label, value=-1, description='coarse vecs') show_displacement = widgets.Checkbox(value=False, description='Show displacement', disabled=False) show_mesh = widgets.Checkbox(value=True, description='Show mesh', disabled=False) scale = widgets.IntSlider( value=100, min=1, max=1000, step=1, description='Scale factor for coarse vec displacement', disabled=False, continuous_update=False, orientation='horizontal') def draw_mesh(change): mesh.visible = not mesh.visible def update_domain(change): rank = select_dom.value work[:] = coords if show_displacement.value: if select_coarse_vecs.value == -1: for i in range(dim): work[(..., i)] += scale.value * numpy_arrays[i] else: if select_coarse_vecs.value < len(coarse_vecs): for i in range(dim): work[(..., i)] += scale.value * coarse_vecs[ select_coarse_vecs.value][i] else: for i in range(dim): work[(..., i)] += scale.value * cg_ites[ select_coarse_vecs.value - len(coarse_vecs)][i] if rank >= 0: new_coords = work[faces_by_rank[rank]].reshape(-1, 3) minCoords = new_coords.min(axis=0) maxCoords = new_coords.max(axis=0) midCoords = 0.5 * (minCoords + maxCoords) scene.position = tuple(-midCoords) vertices.array = work[faces_by_rank[rank]].reshape(-1, 3) bcolor.array = scalar2rgb( numpy_arrays[select.value])[faces_by_rank[rank]] edges.array = work[edges_by_rank[rank]].reshape(-1, 3) else: vertices.array = work[faces_].reshape(-1, 3) bcolor.array = scalar2rgb(numpy_arrays[select.value])[faces_] edges.array = work[edges_].reshape(-1, 3) minCoords = work.min(axis=0) maxCoords = work.max(axis=0) midCoords = 0.5 * (minCoords + maxCoords) scene.position = tuple(-midCoords) select.observe(update_domain, names=['value']) select_dom.observe(update_domain, names=['value']) select_coarse_vecs.observe(update_domain, names=['value']) scale.observe(update_domain, names=['value']) show_displacement.observe(update_domain, names=['value']) show_mesh.observe(draw_mesh, names=['value']) show_displacement.value = True return widgets.HBox([ renderer, widgets.VBox([ select, select_dom, select_coarse_vecs, show_displacement, show_mesh, scale ]) ])
def qiskit_backend_overview(self, line='', cell=None): """A Jupyter magic function to monitor backends. """ del cell # Unused args = magic_arguments.parse_argstring(self.qiskit_backend_overview, line) unique_hardware_backends = get_unique_backends() _value = "<h2 style ='color:#ffffff; background-color:#000000;" _value += "padding-top: 1%; padding-bottom: 1%;padding-left: 1%;" _value += "margin-top: 0px'>Backend Overview</h2>" backend_title = widgets.HTML( value=_value, layout=widgets.Layout(margin='0px 0px 0px 0px')) build_back_widgets = [ backend_widget(b) for b in unique_hardware_backends ] _backends = [] # Sort backends by operational or not oper_ord_backends = [] for n, back in enumerate(unique_hardware_backends): if back.status().operational: oper_ord_backends = [build_back_widgets[n]] + oper_ord_backends _backends = [back] + _backends else: oper_ord_backends = oper_ord_backends + [build_back_widgets[n]] _backends = _backends + [back] qubit_label = widgets.Label(value='Num. Qubits') qv_label = widgets.Label(value='Quantum Vol.') pend_label = widgets.Label( value='Pending Jobs', layout=widgets.Layout(margin='5px 0px 0px 0px')) least_label = widgets.Label( value='Least Busy', layout=widgets.Layout(margin='10px 0px 0px 0px')) oper_label = widgets.Label( value='Operational', layout=widgets.Layout(margin='5px 0px 0px 0px')) t12_label = widgets.Label( value='Avg. T1 / T2', layout=widgets.Layout(margin='10px 0px 0px 0px')) cx_label = widgets.Label( value='Avg. CX Err.', layout=widgets.Layout(margin='8px 0px 0px 0px')) meas_label = widgets.Label( value='Avg. Meas. Err.', layout=widgets.Layout(margin='8px 0px 0px 0px')) labels_widget = widgets.VBox([ qubit_label, qv_label, pend_label, oper_label, least_label, t12_label, cx_label, meas_label ], layout=widgets.Layout( margin='295px 0px 0px 0px', min_width='100px')) backend_grid = GridBox_with_thread( children=oper_ord_backends, layout=widgets.Layout(grid_template_columns='250px ' * len(unique_hardware_backends), grid_template_rows='auto', grid_gap='0px 25px')) backend_grid._backends = _backends # pylint: disable=attribute-defined-outside-init backend_grid._update = types.MethodType( # pylint: disable=attribute-defined-outside-init update_backend_info, backend_grid) backend_grid._thread = threading.Thread( # pylint: disable=attribute-defined-outside-init target=backend_grid._update, args=(args.interval, )) backend_grid._thread.start() back_box = widgets.HBox([labels_widget, backend_grid]) back_monitor = widgets.VBox([backend_title, back_box]) display(back_monitor)
def gate_demo(gates='full', qsphere=False): from qiskit import QuantumCircuit, execute, Aer from qiskit.visualization import plot_bloch_multivector, plot_state_qsphere gate_list = [] showing_rz = False if 'pauli' in gates: gate_list += ['X', 'Y', 'Z'] if '+h' in gates: gate_list.append('H') if '+rz' in gates: showing_rz = True if gate_list == [] or gates == 'full': gate_list = ['I', 'X', 'Y', 'Z', 'H', 'S', 'Sdg', 'T', 'Tdg'] showing_rz = True backend = Aer.get_backend('statevector_simulator') qc = QuantumCircuit(1) button_list = [ widgets.Button(description=gate, layout=widgets.Layout(width='3em', height='3em')) for gate in gate_list ] button_list.append( widgets.Button(description='Reset', layout=widgets.Layout(width='6em', height='3em'))) image = _img() def update_output(): out_state = execute(qc, backend).result().get_statevector() if qsphere: image.value = plot_state_qsphere(out_state) else: image.value = plot_bloch_multivector(out_state) def apply_gates(b, qc): functionmap = { 'X': qc.x, 'Y': qc.y, 'Z': qc.z, 'H': qc.h, 'S': qc.s, 'T': qc.t, 'Sdg': qc.sdg, 'Tdg': qc.tdg, } if b.description == 'I': pass elif b.description == 'Reset': qc.data = [] elif b.description == 'Rz': qc.rz(zrot_slider.value, 0) else: functionmap[b.description](0) def on_button_click(b): apply_gates(b, qc) update_output() for button in button_list: button.on_click(on_button_click) if showing_rz: rz_button = widgets.Button(description='Rz', layout=widgets.Layout(width='3em', height='3em')) rz_button.on_click(on_button_click) zrot_slider = widgets.FloatSlider(value=pi, min=-pi, max=pi, disabled=False, readout_format='.2f') qc = QuantumCircuit(1) update_output() if showing_rz: top_box = widgets.HBox(button_list) bottom_box = widgets.HBox([rz_button, zrot_slider]) main_box = widgets.VBox([top_box, bottom_box]) else: main_box = widgets.HBox(button_list) display(main_box) display(image.widget)
def backend_widget(backend): """Creates a backend widget. """ config = backend.configuration().to_dict() props = backend.properties().to_dict() name = widgets.HTML(value="<h4>{name}</h4>".format(name=backend.name()), layout=widgets.Layout()) num_qubits = config['n_qubits'] qv_val = '-' if 'quantum_volume' in config.keys(): if config['quantum_volume']: qv_val = config['quantum_volume'] qubit_count = widgets.HTML( value="<h5><b>{qubits}</b></h5>".format(qubits=num_qubits), layout=widgets.Layout(justify_content='center')) qv_value = widgets.HTML(value="<h5>{qubits}</h5>".format(qubits=qv_val), layout=widgets.Layout(justify_content='center')) cmap = widgets.Output(layout=widgets.Layout(min_width='250px', max_width='250px', max_height='250px', min_height='250px', justify_content='center', align_items='center', margin='0px 0px 0px 0px')) with cmap: _cmap_fig = plot_gate_map(backend, plot_directed=False, label_qubits=False) if _cmap_fig is not None: display(_cmap_fig) # Prevents plot from showing up twice. plt.close(_cmap_fig) pending = generate_jobs_pending_widget() is_oper = widgets.HTML(value="<h5></h5>", layout=widgets.Layout(justify_content='center')) least_busy = widgets.HTML(value="<h5></h5>", layout=widgets.Layout(justify_content='center')) t1_units = props['qubits'][0][0]['unit'] avg_t1 = round( sum([q[0]['value'] for q in props['qubits']]) / num_qubits, 1) avg_t2 = round( sum([q[1]['value'] for q in props['qubits']]) / num_qubits, 1) t12_widget = widgets.HTML(value="<h5>{t1} / {t2} {units}</h5>".format( t1=avg_t1, t2=avg_t2, units=t1_units), layout=widgets.Layout()) avg_cx_err = 'NA' if config['coupling_map']: sum_cx_err = 0 num_cx = 0 for gate in props['gates']: if gate['gate'] == 'cx': for param in gate['parameters']: if param['name'] == 'gate_error': # Value == 1.0 means gate effectively off if param['value'] != 1.0: sum_cx_err += param['value'] num_cx += 1 avg_cx_err = round(sum_cx_err / (num_cx), 4) cx_widget = widgets.HTML( value="<h5>{cx_err}</h5>".format(cx_err=avg_cx_err), layout=widgets.Layout()) avg_meas_err = 0 for qub in props['qubits']: for item in qub: if item['name'] == 'readout_error': avg_meas_err += item['value'] avg_meas_err = round(avg_meas_err / num_qubits, 4) meas_widget = widgets.HTML( value="<h5>{meas_err}</h5>".format(meas_err=avg_meas_err), layout=widgets.Layout()) out = widgets.VBox([ name, cmap, qubit_count, qv_value, pending, is_oper, least_busy, t12_widget, cx_widget, meas_widget ], layout=widgets.Layout(display='inline-flex', flex_flow='column', align_items='center')) out._is_alive = True return out
ip_z = ipw.FloatSlider(min=0, max=360, value=0, step=1, description="z") def randomize(button): x, y, z = np.random.random((3, 1000)) scatter = ipv_plot.scatters[0] with ipv_plot.hold_sync(): scatter.x = x scatter.y = y scatter.z = z ip_randomize = ipw.Button(description="Randomize") ip_randomize.on_click(randomize) ip_vbox = ipw.VBox([ip_x, ip_y, ip_z, ip_randomize]) def change_anglex(change): bk_x.value = round(np.degrees(change["new"])) def change_angley(change): bk_y.value = round(np.degrees(change["new"])) def change_anglez(change): bk_z.value = round(np.degrees(change["new"])) ipv_plot.observe(change_anglex, names="anglex")
def _common_control_generator(self): fc_widgets = self.carrier_frequency() mod_widgets = self.modulation_type() return ipw.VBox([fc_widgets, mod_widgets])
def createPanel(self, curdir): self.header = ipyw.Label(self.instruction, layout=self.label_layout) self.footer = ipyw.HTML("") self.body = self.createBody(curdir) self.panel = ipyw.VBox(children=[self.header, self.body, self.footer]) return
df1 = pd.DataFrame('', index=x.index, columns=x.columns) df1.iloc[:, 4] = y df1.iloc[:, 5] = r df1.iloc[:, 6] = g return df1 def show_latest_cases(TOP): TOP = int(TOP) return country_df.sort_values('confirmed', ascending= False).head(TOP).style.apply(highlight_col, axis=None) interact(show_latest_cases, TOP='10') ipywLayout = widgets.Layout(border='solid 2px green') ipywLayout.display='none' # uncomment this, run cell again - then the graph/figure disappears widgets.VBox([fig], layout=ipywLayout) world_map = folium.Map(location=[11,0], tiles="cartodbpositron", zoom_start=2, max_zoom = 6, min_zoom = 2) for i in range(0,len(confirmed_df)): folium.Circle( location=[confirmed_df.iloc[i]['lat'], confirmed_df.iloc[i]['long']], fill=True, radius=(int((np.log(confirmed_df.iloc[i,-1]+1.00001)))+0.2)*50000, color='red', fill_color='indigo', tooltip = "<div style='margin: 0; background-color: black; color: white;'>"+ "<h4 style='text-align:center;font-weight: bold'>"+confirmed_df.iloc[i]['country'] + "</h4>" "<hr style='margin:10px;color: white;'>"+ "<ul style='color: white;;list-style-type:circle;align-item:left;padding-left:20px;padding-right:20px'>"+
def get_model_tab_local(self): model_upload = widgets.FileUpload(decription='Open model', accept='.pypm', multiple=False) def model_upload_eventhandler(change): filename = list(model_upload.value.keys())[0] my_pickle = model_upload.value[filename]['content'] model = self.open_model(filename, my_pickle) if model is not None: self.model = model self.model_name.value = self.model.name self.model_description.value = self.model.description self.model_t0.value = self.model.t0 self.model_time_step.value = self.model.get_time_step() self.all_tabs() model_upload.observe(model_upload_eventhandler, names='value') open_label = widgets.Label(value='Open model for analysis:') v_box_1 = widgets.VBox([ widgets.HBox([open_label, model_upload]), self.model_name, self.model_description ]) # Compare A and B model loaded here: model_uploads = [ widgets.FileUpload(accept='.pypm', multiple=False), widgets.FileUpload(accept='.pypm', multiple=False) ] def model0_upload_eventhandler(change): filename = list(model_uploads[0].value.keys())[0] my_pickle = model_uploads[0].value[filename]['content'] model = self.open_model(filename, my_pickle) if model is not None: self.models_compare['a'] = model self.model_names[0].value = self.models_compare['a'].name self.model_descriptions[0].value = self.models_compare[ 'a'].description self.models_total_population['a'] = get_total_population( self.models_compare['a']) def model1_upload_eventhandler(change): filename = list(model_uploads[1].value.keys())[0] my_pickle = model_uploads[1].value[filename]['content'] model = self.open_model(filename, my_pickle) if model is not None: self.models_compare['b'] = model self.model_names[1].value = self.models_compare['b'].name self.model_descriptions[1].value = self.models_compare[ 'b'].description self.models_total_population['b'] = get_total_population( self.models_compare['b']) model_uploads[0].observe(model0_upload_eventhandler, names='value') model_uploads[1].observe(model1_upload_eventhandler, names='value') open_label_A = widgets.Label(value='Open model for compare A:') open_label_B = widgets.Label(value='Open model for compare B:') v_box_A = widgets.VBox([ widgets.HBox([open_label_A, model_uploads[0]]), self.model_names[0], self.model_descriptions[0] ]) v_box_B = widgets.VBox([ widgets.HBox([open_label_B, model_uploads[1]]), self.model_names[1], self.model_descriptions[1] ]) hspace = widgets.HTML(value=" " * 4, placeholder='Some HTML', description='') return widgets.HBox([ widgets.VBox([v_box_1, v_box_A, v_box_B]), hspace, self.open_model_output ])
arm_lower_file = open(script_dir+"/machine/slot_handle_lower.png", "rb") arm__lower_image = arm_lower_file.read() arm_lower = widgets.Image( value=arm__lower_image, format='png', width='auto') arm_button = widgets.Button(description='PUSH', button_style='danger', layout=widgets.Layout(width='120px', height='auto', margin='0px 35px')) arm_button.style.font_weight = 'bold' arm = widgets.VBox(children=[arm_upper, arm_button, arm_lower], layout=widgets.Layout(width='auto', margin='0px 0px 0px 0px')) items = [left, slot0, mid, slot1, mid, slot2, right, arm] box_layout = widgets.Layout(display='flex', flex_flow='row', align_items='center', width='auto', margin='0px 0px 0px 0px') slot_middle = widgets.Box(children=items, layout=box_layout) slot = widgets.VBox(children=[slot_top, slot_middle, slot_bottom], layout=widgets.Layout(display='flex', flex_flow='column', align_items='center', width='auto',
def get_data_tab_local(self): parent_folder_text = widgets.Text( value='/', placeholder='Enter folder path to data area', description='Parent Folder:', disabled=False, continuous_update=False) folder_dropdown = widgets.Dropdown( description='Data Folder:', disabled=False, ) def folder_text_eventhandler(change): folder_list = os.listdir(parent_folder_text.value) folder_dropdown.options = folder_list parent_folder_text.observe(folder_text_eventhandler, names='value') open_button = widgets.Button( description=' Open', disabled=False, button_style='', # 'success', 'info', 'warning', 'danger' or '' tooltip='Open data folder', icon='folder') def open_folder(b): self.open_data_output.clear_output(True) self.region_data_output.clear_output(True) data_folder = parent_folder_text.value + '/' + folder_dropdown.value data_py = data_folder + '/data.py' module = imp.load_source('module_name', data_py) self.data_description = module.get_data_description() self.data_description['folder'] = data_folder with self.open_data_output: print(self.data_description['description']) print('Source: ' + self.data_description['source']) print('URL: ' + self.data_description['source_url']) with self.region_data_output: for region_name in list( self.data_description['regional_data'].keys()): print(region_name) # tell the explorer that a new data file was loaded self.new_data_opened() # load the data into a panda dictionary self.pd_dict = {} for filename in self.data_description['files']: self.pd_dict[filename] = pd.read_csv(data_folder + '/' + filename) def folder_eventhandler(change): file_list = os.listdir(change['new']) folder_dropdown.options = file_list parent_folder_text.observe(folder_eventhandler, names='value') open_button.on_click(open_folder) v_box1 = widgets.VBox([ parent_folder_text, folder_dropdown, open_button, self.open_data_output ]) items = [v_box1, self.region_data_output] h_box = widgets.HBox(items) return h_box
button.on_click(submit_search) # linking text box to search function - called when user hits ENTER. text.on_submit(submit_search) # linking drop-down menu and search function - called when the value of the drop-down menu changes sortby.observe(submit_search, 'value') # linking the maximum hits box and search function - called when the value changes maxhits.observe(update_maxhits, 'value') # ### 2.4.2.9.4 Layout of User Interface and output. # In[18]: # displaying the widgets and output together col1 = widgets.VBox([text, links, button]) # first column: text box, checkbox, and button col2 = widgets.VBox([maxhits, sortby]) # second column: Maximum Hits and drop-down menu. box = widgets.HBox([col1, col2]) # put first and second column next to each other in a row widgets.VBox([box,out]) # add ouput below the widgets. # ## 2.4.2.10 Alternative Interface # The following alterative interface is much simpler in its coding (essentially letting the `interact` function do all the work). To be useful, this interface requires a fairly fast machine because the search will update live while you type. The interface uses the same search function as above, so search instructions and results are the same. # In[19]: interact(search, Search = '', Max_hits = widgets.BoundedIntText( value=25, min=0,
defaultloc = 'chr5:142,903,034-142,906,867' defaultgeneid = 'Actb' defaultrefseqid = 'NM_007393' defaultstrand = "-" #### Accordian Change File Locations #### w_default_folder = widgets.Text( description='RnaSeq Folder', value=default_track_folder, ) w_default_folder.width="80%" w_default_folder_valid = widgets.Valid(value=True) hboxdefaultfolder = widgets.HBox([w_default_folder,w_default_folder_valid]) page1 = widgets.VBox(children=[hboxdefaultfolder]) accord = widgets.Accordion(children=[page1], width="80%") display(accord) accord.set_title(0, 'Defaults') #### Define Widgets ### lookuptype_widget = widgets.RadioButtons( options={'By location':'location','By geneid (3\'UTR only)':"geneid"}, value='location', description='Lookup:', disabled=False )
def createBody(self): self.form_factory = eval(self.context.shape_type.capitalize())() form = self.form_factory.createForm() widgets = [form] return ipyw.VBox(children=widgets)
def __init__(self, sim, **kwargs): import matplotlib.pyplot as plt super().__init__() self._kwargs = kwargs self.simulation = sim self._kwargs['timestep'] = self._kwargs.get( 'timestep', list(self.simulation.fields.keys())[0]) projections = list( self.simulation.fields[self._kwargs['timestep']].data.keys()) variables = list(self.simulation.fields[self._kwargs['timestep']].data[ projections[0]].keys()) self._kwargs['var'] = self._kwargs.get('var', variables[0]) self._kwargs['proj'] = self._kwargs.get('proj', projections[0]) self._kwargs['cmap'] = self._kwargs.get('cmap', 'viridis') self._kwargs['vmin'] = self._kwargs.get('vmin', None) self._kwargs['vmax'] = self._kwargs.get('vmax', None) self._kwargs['logplot'] = self._kwargs.get('logplot', False) self._kwargs['controls'] = self._kwargs.get('controls', True) self._kwargs['figsize'] = self._kwargs.get('figsize', (6, 4)) self._kwargs['zoomQ'] = self._kwargs.get('zoomQ', False) self._kwargs['interpolation'] = self._kwargs.get('interpolation', None) if (self._kwargs['vmin'] is None): self._kwargs['vmin'], _ = self.findMinMax() if (self._kwargs['vmax'] is None): _, self._kwargs['vmax'] = self.findMinMax() if self._kwargs['controls']: self.obj_var = ipyW.Dropdown(options=variables, description='var:', value=self._kwargs['var'], layout={'width': 'max-content'}) self.obj_proj = ipyW.Dropdown(options=projections, description='proj:', value=self._kwargs['proj'], layout={'width': 'max-content'}) self.obj_cmap = ipyW.Dropdown(options=plt.colormaps(), description='cmap:', value=self._kwargs['cmap'], layout={'width': 'max-content'}) self.obj_minval = ipyW.FloatText(description='min:', value=self._kwargs['vmin'], layout={'width': '200px'}) self.obj_maxval = ipyW.FloatText(description='max:', value=self._kwargs['vmax'], layout={'width': '200px'}) self.obj_logplot = ipyW.Checkbox(value=self._kwargs['logplot'], description='logplot') self.controls = ipyW.Box([ ipyW.VBox([self.obj_var, self.obj_minval, self.obj_maxval]), ipyW.VBox([self.obj_proj, self.obj_cmap, self.obj_logplot]), ]) self.obj_cmap.value = self._kwargs['cmap'] self.obj_cmap.observe(self.update_cmap, 'value') self.obj_var.observe(self.update_var, 'value') self.obj_proj.observe(self.update_proj, 'value') self.obj_logplot.observe(self.update_logplot, 'value') self.obj_minval.observe(self.update_minval, 'value') self.obj_maxval.observe(self.update_maxval, 'value') output = ipyW.Output() with output: self.fig, self.ax = plt.subplots(figsize=self._kwargs['figsize']) self.fig.canvas.toolbar_visible = self._kwargs['zoomQ'] self.fig.canvas.header_visible = False self.fig.canvas.footer_visible = False self.generatePlot() if self._kwargs['controls']: self.children = [self.controls, output] else: self.children = [output]
def qubits_tab(backend): """The qubits properties widget Args: backend (IBMQBackend | FakeBackend): The backend. Returns: VBox: A VBox widget. """ props = backend.properties() header_html = "<div><font style='font-weight:bold'>{key}</font>: {value}</div>" update_date = props.last_update_date.strftime("%a %d %B %Y at %H:%M %Z") header_html = header_html.format(key='last_update_date', value=update_date) update_date_widget = widgets.HTML(value=header_html) qubit_html = "<table>" qubit_html += """<style> table { border-collapse: collapse; width: auto; } th, td { text-align: left; padding: 8px; } tr:nth-child(even) {background-color: #f6f6f6;} </style>""" qubit_html += "<tr><th></th><th>Frequency</th><th>T1</th><th>T2</th>" qubit_footer = "</table>" gate_error_title = "" for index, qubit_data in enumerate(props.qubits): name = 'Q%s' % index gate_data = [gate for gate in props.gates if gate.qubits == [index]] cal_data = dict.fromkeys(['T1', 'T2', 'frequency', 'readout_error'], 'Unknown') for nduv in qubit_data: if nduv.name in cal_data.keys(): cal_data[nduv.name] = str(round(nduv.value, 5)) + ' ' + nduv.unit gate_names = [] gate_error = [] for gd in gate_data: if gd.gate in ['id']: continue try: gate_error.append(str(round(props.gate_error(gd.gate, index), 5))) gate_names.append(gd.gate.upper()) except QiskitError: pass if not gate_error_title: for gname in gate_names: gate_error_title += f"<th>{gname}</th>" qubit_html += gate_error_title + "<th>Readout error</th></tr>" qubit_html += f"<tr><td><font style='font-weight:bold'>{name}</font></td>" qubit_html += f"<td>{cal_data['frequency']}</td>" \ f"<td>{cal_data['T1']}</td><td>{cal_data['T2']}</td>" for gerror in gate_error: qubit_html += f"<td>{gerror}</td>" qubit_html += f"<td>{cal_data['readout_error']}</td>" qubit_html += qubit_footer qubit_widget = widgets.HTML(value=qubit_html) out = widgets.VBox([update_date_widget, qubit_widget]) return out
def prepare_textacy_widgets(self): item_layout = dict( display='flex', flex_flow='row', justify_content='space-between', ) pos_options = get_pos_options(self.tagset) normalize_options = {'None': False, 'Lemma': 'lemma', 'Lower': 'lower'} ngrams_options = {'1': [1], '1, 2': [1, 2], '1,2,3': [1, 2, 3]} default_include_pos = ['NOUN', 'PROPN'] frequent_words = ['_mask_'] # widgets.Label( gui = types.SimpleNamespace( #min_freq=widgets.IntSlider(description='Min word freq',min=0, max=10, value=2, step=1, layout=widgets.Layout(width='240px', **item_layout)), #max_doc_freq=widgets.IntSlider(description='Min doc %', min=75, max=100, value=100, step=1, layout=widgets.Layout(width='240px', **item_layout)), min_freq=widgets.Dropdown(description='Min word freq', options=list(range(0, 11)), value=2, layout=widgets.Layout(width='200px', **item_layout)), max_doc_freq=widgets.Dropdown(description='Min doc %', options=list(range(75, 101)), value=100, layout=widgets.Layout( width='200px', **item_layout)), ngrams=widgets.Dropdown(description='n-grams', options=ngrams_options, value=[1], layout=widgets.Layout(width='200px')), normalize=widgets.Dropdown(description='Normalize', options=normalize_options, value='lemma', layout=widgets.Layout(width='200px')), filter_stops=widgets.ToggleButton(value=True, description='Remove stopword', tooltip='Filter out stopwords', icon='check'), named_entities=widgets.ToggleButton(value=False, description='Merge entities', tooltip='Merge entities', icon='check', disabled=False), substitute_terms=widgets.ToggleButton(value=False, description='Map words', tooltip='Substitute words', icon='check'), include_pos=widgets.SelectMultiple( options=pos_options, value=default_include_pos, rows=7, layout=widgets.Layout(width='60px', **item_layout)), stop_words=widgets.SelectMultiple( options=frequent_words, value=list([]), rows=7, layout=widgets.Layout(width='120px', **item_layout)), ) boxes = [ widgets.VBox([ gui.min_freq, gui.max_doc_freq, gui.normalize, gui.ngrams, ]), widgets.VBox( [gui.filter_stops, gui.named_entities, gui.substitute_terms], layout=widgets.Layout(margin='0px 0px 0px 10px')), widgets.HBox([ widgets.Label(value='POS', layout=widgets.Layout( width='40px')), gui.include_pos ], layout=widgets.Layout(margin='0px 0px 0px 10px')), widgets.HBox([widgets.Label(value='STOP'), gui.stop_words], layout=widgets.Layout(margin='0px 0px 0px 10px')) ] return gui, boxes
with out: w.script = 'load http://localhost:8888/tree/Crystallography/jmol_AMS_DATA_(2).cif' def rotate(self): with out: w.script = 'rotate y 90 90' def invert(self): with out: w.script = 'invertSelected' def rotoinversion(self): with out: w.script = 'rotate y 90 90; delay 0.5; invertSelected' def symops(self): with out: w.script = 'show SYMOP' load_button.on_click(load_structure) rotate_button.on_click(rotate) invert_button.on_click(invert) rotoinversion_button.on_click(rotoinversion) reset_button.on_click(load_structure) symops_button.on_click(symops) bottom_row = widgets.HBox([rotate_button, invert_button, rotoinversion_button, out]) top_row = widgets.HBox([load_button, reset_button, out]) widgets.VBox([top_row, bottom_row])
def __init__( self, features: Optional[Any] = None, labels: Optional[Any] = None, options: Tuple[str] = (), other_option: bool = True, max_buttons: int = 12, display_func: Callable = None, keyboard_shortcuts: bool = False, hint_function: Optional[Callable] = None, hints: Optional[Dict[str, Any]] = None, ): """ Make a class that allows you to label data points. """ # the widget elements self.layout = widgets.VBox([]) self.feature_output = widgets.Output() self.feature_display = widgets.Box( (self.feature_output,), layout=widgets.Layout( justify_content="center", padding="5% 0", display="flex", width="100%", min_height="150px", ), ) self.input_widget = controls.Submitter( hint_function=hint_function, hints=hints, options=options, other_option=other_option, max_buttons=max_buttons, ) self.input_widget.on_submission(self._apply_annotation) self.options = self.input_widget.options traitlets.link((self, "options"), (self.input_widget, "options")) # self.features = validation.valid_data(features) self.features = features # if labels is not None: # self.labels = validation.valid_data(labels) # elif self.features is not None: # self.labels = np.full( # self.features.shape[0], np.nan, dtype=float) self.labels = labels self.progressbar = widgets.FloatProgress( max=1, description="Progress:" ) self.top_bar = widgets.HBox([]) self.top_bar.children = [self.progressbar] if display_func is not None: self._display_func = display_func else: self._display_func = display.functions["default"] if keyboard_shortcuts: self.event_manager = ipyevents.Event( source=self.layout, watched_events=["keydown", "keyup"] ) self.event_manager.on_dom_event(self.input_widget._on_key_down) else: self.event_manager = None self.timer = controls.Timer()
def __init__( self, name=None, catalog_item=None, display_value=False, display_widget=False, ): self.catalog_item = catalog_item self.columns = Columns(spec=self.catalog_item['spec'], display_widget=False) self.filters = Filters(spec=self.catalog_item['spec'], display_widget=False) self.sample_ratio = Sampling(display_widget=False) self.value = widgets.ValueWidget() # self.download_button = widgets.Button( # description="Download", # icon='plus' # ) # self.generator = widgets.interactive_output(generate_cell, {}) # def on_button_clicked(b): # with self.generator: # get_ipython().set_next_input(f'spec = 1')#{self.spec}') # pass # self.download_button.on_click(on_button_clicked) self.widgets = [ self.columns.widget_container, self.filters.widget_container, self.sample_ratio.widget_container, # self.download_button, # self.generator, ] def update_output(*args): self.value.value = self.spec update_output() self.columns.value.observe(update_output, 'value') self.filters.value.observe(update_output, 'value') self.sample_ratio.value.observe(update_output, 'value') if display_value: def display_value(spec): download_spec = json.dumps( { 'id': catalog_item['id'], 'executor_type': catalog_item['executor_type'], 'spec': spec }, indent=4) print('to get date copy to next cell:\n\n' f"""df = lakey.download({download_spec})""") self.output = widgets.interactive_output(display_value, {'spec': self.value}) self.widgets.append(self.output) self.widget_container = widgets.VBox(self.widgets) if display_widget: display(self.widget_container)
def __init__(self): self.ignore_update = False def select_experiment_change_callback(change): if self.ignore_update: return if change.name == 'value' and change.new is not None: self.edit_experiment.children = [ self.widget_mapping[change.new]] def name_update_callback(_): self.update_selector() def save_callback(_): result_dict = {} for x in self.widget_mapping: root = self.widget_mapping[x].experiment_root.value model_name = self.widget_mapping[x].model_name.value result_dict[x] = [root, model_name] with open(DataReader.EXPERIMENTS_MAPPING_FILE, 'w') as f: json.dump(result_dict, f) def delete_callback(_): del self.widget_mapping[self.select_experiment.value] self.update_selector() def add_callback(_): self.widget_mapping['new'] = ExperimentEntryView('new', '', '') self.update_selector() self.select_experiment.value = 'new' with open(DataReader.EXPERIMENTS_MAPPING_FILE, 'r') as f: self.mapping = json.load(f) self.select_experiment = widgets.Select( options=self.mapping.keys(), disabled=False ) self.save_button = widgets.Button( description='Save', disabled=False, layout=widgets.Layout(width='auto'), ) self.delete_button = widgets.Button( description='Delete', disabled=False, ) self.add_button = widgets.Button( description='Add', disabled=False, ) self.buttons_hbox = widgets.HBox([self.add_button, self.delete_button]) self.widget_mapping = {} for key in self.mapping: self.widget_mapping[key] = ExperimentEntryView( key, self.mapping[key][0], self.mapping[key][1] ) self.widget_mapping[key].experiment_name.observe( name_update_callback) self.left_column = widgets.VBox( [ self.select_experiment, self.buttons_hbox, self.save_button, ]) self.edit_experiment = widgets.Box([]) self.edit_experiment.layout.width = 'auto' self.select_experiment.observe( select_experiment_change_callback, type='change') self.add_button.on_click(add_callback) self.save_button.on_click(save_callback) self.delete_button.on_click(delete_callback) super(ExperimentsDirectoryTab, self).__init__( [self.left_column, self.edit_experiment], layout=widgets.Layout(width='100%', align_items='stretch'))
def interactive_conveyor_belt(conveyorBelt=None, numsys: int = 8, nbins: int = 100, steps: int = 100): """ This provides a nice widget for jupyter notebooks to play around with the conveyor belt. Parameters ---------- conveyorBelt numsys nbins steps Returns ------- """ # if none given build cvb if (isinstance(conveyorBelt, type(None))): lam = np.linspace(0, 1, nbins) ene = lam * np.sin(lam * np.pi) + lam**2 else: (cvb_traj, systrajs) = conveyorBelt.get_trajs() if (len(cvb_traj) == 0): raise IOError( "Could not find any conveyor belt simulation in conveyorbelt traj. Please simulate first." ) bins = np.zeros(nbins) dhdlbins = np.zeros(nbins) for i in systrajs: for j in range(systrajs[i].shape[0]): index = int(np.floor(systrajs[i].lam[j] / nbins)) if index == nbins: index = nbins - 1 bins[index] += 1 dhdlbins[index] += systrajs[i].dhdlam[j] for i, b in enumerate(bins): if b > 0: dhdlbins[i] /= b ene = np.cumsum(dhdlbins) / nbins lam = np.linspace(0, 1, nbins) def redraw(CapLam, M): plotEnsembler(lam, ene, CapLam=np.deg2rad(CapLam), M=M) # build layout and components player = ipywidgets.Play(value=0, min=0, max=360, step=1, description="rotate") capLam_slider = ipywidgets.IntSlider(value=0, min=0, max=360, step=1, orientation='vertical', description="Capital Lambda", continous_update=True) nReplicas_slider = ipywidgets.IntSlider(value=8, min=2, max=20, step=1, orientation='vertical', description="number of Replicas") ipywidgets.jslink((capLam_slider, 'value'), (player, 'value')) interactive_plot = ipywidgets.interactive_output(redraw, { 'CapLam': capLam_slider, 'M': nReplicas_slider }) controls = ipywidgets.VBox( [player, ipywidgets.HBox([capLam_slider, nReplicas_slider])]) app = ipywidgets.AppLayout(header=None, left_sidebar=controls, center=interactive_plot, right_sidebar=None, footer=None, align_items="center") return app """ This provides a nice widget for jupyter notebooks to play around with the conveyor belt. Parameters ---------- conveyorBelt numsys nbins steps Returns ------- """ # if none given build cvb if (isinstance(conveyorBelt, type(None))): lam = np.linspace(0, 1, nbins) ene = lam * np.sin(lam * np.pi) + lam**2 else: (cvb_traj, systrajs) = conveyorBelt.get_trajs() if (len(cvb_traj) == 0): raise IOError( "Could not find any conveyor belt simulation in conveyorbelt traj. Please simulate first." ) bins = np.zeros(nbins) dhdlbins = np.zeros(nbins) for i in systrajs: for j in range(systrajs[i].shape[0]): index = int(np.floor(systrajs[i].lam[j] / nbins)) if index == nbins: index = nbins - 1 bins[index] += 1 dhdlbins[index] += systrajs[i].dhdlam[j] for i, b in enumerate(bins): if b > 0: dhdlbins[i] /= b ene = np.cumsum(dhdlbins) / nbins lam = np.linspace(0, 1, nbins) def redraw(CapLam, M): plotEnsembler(lam, ene, CapLam=np.deg2rad(CapLam), M=M) # build layout and components player = ipywidgets.Play(value=0, min=0, max=360, step=1, description="rotate") capLam_slider = ipywidgets.IntSlider(value=0, min=0, max=360, step=1, orientation='vertical', description="Capital Lambda", continous_update=True) nReplicas_slider = ipywidgets.IntSlider(value=8, min=2, max=20, step=1, orientation='vertical', description="number of Replicas") ipywidgets.jslink((capLam_slider, 'value'), (player, 'value')) interactive_plot = ipywidgets.interactive_output(redraw, { 'CapLam': capLam_slider, 'M': nReplicas_slider }) controls = ipywidgets.VBox( [player, ipywidgets.HBox([capLam_slider, nReplicas_slider])]) app = ipywidgets.AppLayout(header=None, left_sidebar=controls, center=interactive_plot, right_sidebar=None, footer=None, align_items="center") return app