def __init__(self, splotter, xscale = 'linear', yscale = 'linear'): # self.splotter = splotter self.full_data = splotter.data self.separated_vars = splotter.separated_vars self.separated_values = splotter.get_separated_values() self.separated_selection = self.separated_values[0] self.coalesced_vars = splotter.coalesced_vars self.coalesced_values = splotter.get_coalesced_values() self.output_columns = splotter.output_columns self.dependent_var = self.output_columns[0] self.independent_var = splotter.independent_var self.figure, self.axis = plt.subplots(1, 1, figsize=(12, 6)) self.settings = splotter.settings if len(self.separated_vars) == 0: vec_labels = ["all values"] else: vec_labels = [(", ".join(map(str, ou)), ou) for ou in self.separated_values] # print vec_labels self.dd_filter = ipyw.Dropdown( options=vec_labels) # , # description = "%s :"%(self.separated_vars) ) self.dd_output = ipyw.Dropdown( options=self.output_columns) # , self.select_xscale = ipyw.Checkbox( value= xscale == "log", description='x log scale', icon='check' ) self.select_yscale = ipyw.Checkbox( value= yscale == "log", description='y log scale', icon='check' ) # description = "Output columns: ") self.xscale = xscale self.yscale = yscale self.dd_filter.observe(self.on_dd_filter_value_change, names='value') self.dd_output.observe(self.on_dd_output_value_change, names='value') self.select_yscale.observe(self.on_select_scale, names=['value', 'owner']) self.select_xscale.observe(self.on_select_scale, names=['value', 'owner']) self.__separated_value_change() display( ipyw.HBox([ ipyw.HBox([ipyw.Label("%s: " % (self.separated_vars)), self.dd_filter]), ipyw.HBox([ipyw.Label("Output columns: "), self.dd_output]) ]), ipyw.HBox([self.select_xscale, self.select_yscale]) ) self.draw()
def gif_folder(): accepted_extensions = ["png"] filenames = [fn for fn in os.listdir(SAVE_FOLDER_IMAGES) if fn.split(".")[-1] in accepted_extensions] temp = [int(fn.split('.')[0]) for fn in filenames] temp = sorted(temp) final_filenames = [f'{elt}.png' for elt in temp] k = len(final_filenames) plt.figure(figsize=(25, 20)) columns = 5 i = 0 for file in final_filenames: plt.subplot(k / columns + 1, columns, i + 1) plt.title(file) i += 1 plt.imshow(Image.open(f"{SAVE_FOLDER_IMAGES}{file}")) file_widget = widgets.Dropdown( options=final_filenames, description='File To Delete', ) button_del = widgets.Button(description='Delete this file') out_wid_del = widgets.Output() duration_widget = widgets.IntText( value=5, description='GIF Duration (in seconds)', disabled=False ) end_gif_duration_widget = widgets.IntText( value=3, description='End GIF Duration (last image rep times)', disabled=False ) output_name_widget = widgets.Text( value='output.gif', placeholder='Output Name', description='File Name', disabled=False ) button_widget = widgets.Button( description='Generate GIF', disabled=False, button_style='', tooltip='Click me', ) out_wid_create = widgets.Output() box_layout = widgets.Layout( border='', margin='0px 20px 20px 0px', padding='5px 60px 5px 60px') vbox1 = widgets.VBox([widgets.Label('Delete some img'), file_widget, button_del, out_wid_del]) vbox1.layout = box_layout vbox2 = widgets.VBox( [widgets.Label('Generate the GIF'), duration_widget, end_gif_duration_widget, output_name_widget, button_widget, out_wid_create]) vbox2.layout = box_layout display(widgets.HBox([vbox1, vbox2])) def click_file(b): with out_wid_del: clear_output(wait=True) os.remove(f'{SAVE_FOLDER_IMAGES}{file_widget.value}') print(f'File {file_widget.value} deleted') def click_generate(b): with out_wid_create: generate_gif_from_folder(duration_widget.value, output_name_widget.value, end_gif_duration_widget.value) button_del.on_click(click_file) button_widget.on_click(click_generate)
height=tab_height, overflow_y='scroll', ) # border='2px solid black', titles = [ 'About', 'Config Basics', 'User Params', 'Out: Cell Plots', 'Out: Substrate Plots' ] tabs = widgets.Tab( children=[about_tab.tab, config_tab.tab, user_tab.tab, svg.tab, sub.tab], _titles={i: t for i, t in enumerate(titles)}, layout=tab_layout) homedir = os.getcwd() tool_title = widgets.Label(r'\(\textbf{pc4cancerbots}\)') if nanoHUB_flag: # define this, but don't use (yet) remote_cb = widgets.Checkbox( indent=False, value=False, description='Submit as Batch Job to Clusters/Grid') top_row = widgets.HBox(children=[read_config, tool_title]) gui = widgets.VBox(children=[top_row, tabs, run_button.w]) else: top_row = widgets.HBox(children=[tool_title]) gui = widgets.VBox(children=[top_row, tabs, run_button.w]) fill_gui_params(read_config.options['DEFAULT'])
def task_timeline(): path_input = widgets.Button(description="View task timeline") breakdown_basic = "Basic" breakdown_task = "Task Breakdowns" breakdown_opt = widgets.Dropdown( options=["Basic", "Task Breakdowns"], value="Basic", disabled=False, ) obj_dep = widgets.Checkbox(value=True, disabled=False, layout=widgets.Layout(width='20px')) task_dep = widgets.Checkbox(value=True, disabled=False, layout=widgets.Layout(width='20px')) # Labels to bypass width limitation for descriptions. label_tasks = widgets.Label(value='Task submissions', layout=widgets.Layout(width='110px')) label_objects = widgets.Label(value='Object dependencies', layout=widgets.Layout(width='130px')) label_options = widgets.Label(value='View options:', layout=widgets.Layout(width='100px')) start_box, end_box, range_slider, time_opt = get_sliders(False) display(widgets.HBox([label_tasks, task_dep, label_objects, obj_dep])) display(widgets.HBox([label_options, breakdown_opt])) display(path_input) def handle_submit(sender): json_tmp = tempfile.mktemp() + ".json" # Determine whether task components should be displayed or not. if breakdown_opt.value == breakdown_basic: breakdown = False elif breakdown_opt.value == breakdown_task: breakdown = True else: raise ValueError("Unexpected breakdown value '{}'".format( breakdown_opt.value)) low, high = map(lambda x: x / 100., range_slider.value) smallest, largest, num_tasks = ray.global_state._job_length() diff = largest - smallest if time_opt.value == total_time_value: tasks = ray.global_state.task_profiles(start=smallest + diff * low, end=smallest + diff * high) elif time_opt.value == total_tasks_value: if range_slider.value[0] == 0: tasks = ray.global_state.task_profiles(num_tasks=int( num_tasks * high), fwd=True) else: tasks = ray.global_state.task_profiles(num_tasks=int( num_tasks * (high - low)), fwd=False) else: raise ValueError("Unexpected time value '{}'".format( time_opt.value)) # Write trace to a JSON file print("{} tasks to trace".format(len(tasks))) print("Dumping task profiling data to " + json_tmp) ray.global_state.dump_catapult_trace(json_tmp, tasks, breakdowns=breakdown, obj_dep=obj_dep.value, task_dep=task_dep.value) print("Opening html file in browser...") # Check that the catapult repo is cloned to the correct location print(_setup_trace_dependencies()) catapult_home, trace_viewer_path = _setup_trace_dependencies() html_file_path = _get_temp_file_path(suffix=".html") json_file_path = _get_temp_file_path(suffix=".json") print("Pointing to {} named {}".format(json_tmp, json_file_path)) shutil.copy(json_tmp, json_file_path) with open(trace_viewer_path) as f: data = f.read() # Replace the demo data path with our own # https://github.com/catapult-project/catapult/blob/ # 33a9271eb3cf5caf925293ec6a4b47c94f1ac968/tracing/bin/index.html#L107 data = data.replace("../test_data/big_trace.json", json_file_path) with open(html_file_path, "w+") as f: f.write(data) # Display the task trace within the Jupyter notebook clear_output(wait=True) display(IFrame(html_file_path, 900, 800)) print("Displaying {}".format(html_file_path)) path_input.on_click(handle_submit)
def kwargs_to_ipywidgets(kwargs, params, update, slider_format_strings, play_buttons=False, play_button_pos="right"): """ this will break if you pass a matplotlib slider. I suppose it could support mixed types of sliders but that doesn't really seem worthwhile? parameters ---------- play_button: boolean or dict if boolean it will be applied to all sliders. If a dict it should have the same keys as kwargs and the values should be True or False. Or an iterable of strings of parameter names """ labels = [] sliders = [] controls = [] players = [] if isinstance(play_buttons, bool): has_play_button = defaultdict(lambda: play_buttons) elif isinstance(play_buttons, defaultdict): has_play_button = play_buttons elif isinstance(play_buttons, dict): has_play_button = defaultdict(lambda: False, play_buttons) elif isinstance(play_buttons, Iterable) and all( [isinstance(p, str) for p in play_buttons]): has_play_button = defaultdict( lambda: False, dict(zip(play_buttons, [True] * len(play_buttons)))) else: has_play_button = play_buttons for key, val in kwargs.items(): if isinstance(val, set): if len(val) == 1: val = val.pop() if isinstance(val, tuple): # want the categories to be ordered pass else: # fixed parameter params[key] = val else: val = list(val) # categorical if len(val) <= 3: selector = widgets.RadioButtons(options=val) else: selector = widgets.Select(options=val) params[key] = val[0] controls.append(selector) selector.observe(partial(update, key=key, label=None), names=["value"]) elif isinstance(val, widgets.Widget) or isinstance(val, widgets.fixed): if not hasattr(val, "value"): raise TypeError( "widgets passed as parameters must have the `value` trait." "But the widget passed for {key} does not have a `.value` attribute" ) if isinstance(val, widgets.fixed): params[key] = val.value else: params[key] = val.value controls.append(val) val.observe(partial(update, key=key, label=None), names=["value"]) else: if isinstance(val, tuple) and len(val) in [2, 3]: # treat as an argument to linspace # idk if it's acceptable to overwrite kwargs like this # but I think at this point kwargs is just a dict like any other val = np.linspace(*val) kwargs[key] = val val = np.atleast_1d(val) if val.ndim > 1: raise ValueError( f"{key} is {val.ndim}D but can only be 1D or a scalar") if len(val) == 1: # don't need to create a slider params[key] = val else: params[key] = val[0] labels.append( widgets.Label( value=slider_format_strings[key].format(val[0]))) sliders.append( widgets.IntSlider(min=0, max=val.size - 1, readout=False, description=key)) if has_play_button[key]: players.append( widgets.Play(min=0, max=val.size - 1, step=1)) widgets.jslink((players[-1], "value"), (sliders[-1], "value")) if play_button_pos == "left": controls.append( widgets.HBox( [players[-1], sliders[-1], labels[-1]])) else: controls.append( widgets.HBox( [sliders[-1], labels[-1], players[-1]])) else: controls.append(widgets.HBox([sliders[-1], labels[-1]])) sliders[-1].observe(partial(update, key=key, label=labels[-1]), names=["value"]) return sliders, labels, controls, players
def interactive_overlay_images(file_list): ''' Main widget to create overlay images from multiple channels input: file_list - a list of strings containing file names ''' # dummy parameters to initialize sliders img_min=0 img_max=10000 # load XKCD color dictionaries: XKCD_hex2color_dict, XKCD_hex2RGB_dict, XKCD_color2hex_dict, XKCD_color2RGB_dict = load_XKCD_colors() # widgets for the overlay column save_button = widgets.Button(description="Save Image", layout=widgets.Layout(width='98%')) save_name = widgets.Text(value='', description="Save Name", continuous_update=False) inverted_check = widgets.Checkbox(description='Invert Colormaps') blank = widgets.Label(value='') # functions to have update between sliders/colornames/hex colors def color_name2RGB_c1(color_name): '''sets RGB slider from the color textbox name''' (R1.value, G1.value, B1.value) = XKCD_color2RGB_dict[color_name.lower()] def color_name2RGB_c2(color_name): '''sets RGB slider from the color textbox name''' (R2.value, G2.value, B2.value) = XKCD_color2RGB_dict[color_name.lower()] def color_name2RGB_c3(color_name): '''sets RGB slider from the color textbox name''' (R3.value, G3.value, B3.value) = XKCD_color2RGB_dict[color_name.lower()] def hex_to_rgb_c1(hex_string): '''sets RGB slider from the hex string textbox''' (R1.value, G1.value, B1.value) = tuple(int(hex_string[i:i+2], 16) for i in (0, 2, 4)) def hex_to_rgb_c2(hex_string): '''sets RGB slider from the hex string textbox''' (R2.value, G2.value, B2.value) = tuple(int(hex_string[i:i+2], 16) for i in (0, 2, 4)) def hex_to_rgb_c3(hex_string): '''sets RGB slider from the hex string textbox''' (R3.value, G3.value, B3.value) = tuple(int(hex_string[i:i+2], 16) for i in (0, 2, 4)) def color_name_fromRGB_c1(change): '''Takes the RGB slider values for channel 1 and checks if they correspond to names from the XKCD color dictionary''' hex_string = rgb_to_hex((R1.value, G1.value, B1.value)) color_hex_c1.value = hex_string if hex_string in XKCD_hex2RGB_dict: color_text_c1.value = XKCD_hex2color_dict[hex_string] else: color_text_c1.value = '' def color_name_fromRGB_c2(change): '''Takes the RGB slider values for channel 2 and checks if they correspond to names from the XKCD color dictionary''' hex_string = rgb_to_hex((R2.value, G2.value, B2.value)) color_hex_c2.value = hex_string if hex_string in XKCD_hex2RGB_dict: color_text_c2.value = XKCD_hex2color_dict[hex_string] else: color_text_c2.value = '' def color_name_fromRGB_c3(change): '''Takes the RGB slider values for channel 3 and checks if they correspond to names from the XKCD color dictionary''' hex_string = rgb_to_hex((R3.value, G3.value, B3.value)) color_hex_c3.value = hex_string if hex_string in XKCD_hex2RGB_dict: color_text_c3.value = XKCD_hex2color_dict[hex_string] else: color_text_c3.value = '' # actual widgets channel 1 channel_check_c1 = widgets.Checkbox(description="Channel 1") R1 = widgets.IntSlider(value=123, min = 0, max = 255, step = 1, description = 'R', continuous_update = False) G1 = widgets.IntSlider(value=123, min = 0, max = 255, step = 1, description = 'G', continuous_update = False) B1 = widgets.IntSlider(value=123, min = 0, max = 255, step = 1, description = 'B', continuous_update = False) time_pt = widgets.IntSlider(value=0, min=0, max=0, step=1, description='Time pt', continuous_update = False) color_text_c1 = widgets.Text(value='', description="color name", continuous_update = False) color_hex_c1 = widgets.Text(value='', description="hex color",continuous_update = False) file_name_c1 = widgets.Dropdown(options = file_list, description='File') inten_min_c1 = widgets.IntSlider(value = img_min, min = img_min, max = img_max, step = 1, description = 'Min Inten', continuous_update = False) inten_max_c1 = widgets.IntSlider(value = img_max, min = img_min, max = img_max, step = 1, description = 'Max Inten', continuous_update = False) # actual widgets channel 2 channel_check_c2 = widgets.Checkbox(description="Channel 2") R2 = widgets.IntSlider(value=123, min = 0, max = 255, step = 1, description = 'R', continuous_update = False) G2 = widgets.IntSlider(value=123, min = 0, max = 255, step = 1, description = 'G', continuous_update = False) B2 = widgets.IntSlider(value=123, min = 0, max = 255, step = 1, description = 'B', continuous_update = False) color_text_c2 = widgets.Text(value='', description="color name", continuous_update = False) color_hex_c2 = widgets.Text(value='', description="hex color",continuous_update = False) file_name_c2 = widgets.Dropdown(options = file_list, description='File') inten_min_c2 = widgets.IntSlider(value = img_min, min = img_min, max = img_max, step = 1, description = 'Min Inten', continuous_update = False) inten_max_c2 = widgets.IntSlider(value = img_max, min = img_min, max = img_max, step = 1, description = 'Max Inten', continuous_update = False) # actual widgets channel 3 channel_check_c3 = widgets.Checkbox(description="Channel 3") R3 = widgets.IntSlider(value=123, min = 0, max = 255, step = 1, description = 'R', continuous_update = False) G3 = widgets.IntSlider(value=123, min = 0, max = 255, step = 1, description = 'G', continuous_update = False) B3 = widgets.IntSlider(value=123, min = 0, max = 255, step = 1, description = 'B', continuous_update = False) color_text_c3 = widgets.Text(value='', description="color name", continuous_update = False) color_hex_c3 = widgets.Text(value='', description="hex color",continuous_update = False) file_name_c3 = widgets.Dropdown(options = file_list, description='File') inten_min_c3 = widgets.IntSlider(value = img_min, min = img_min, max = img_max, step = 1, description = 'Min Inten', continuous_update = False) inten_max_c3 = widgets.IntSlider(value = img_max, min = img_min, max = img_max, step = 1, description = 'Max Inten', continuous_update = False) # function comes after the sliders because it calls on variables established in the sliders def read_image_c1(file_name): ''' Read in the image from the file list for channel 1''' # read in the image if type(file_name) == str: if file_name[-3:] == 'tif': img = io.imread(file_name) elif file_name[-3:] == 'czi': img = czifile.imread(file_name) img = img[0,0,0,:,0,:,:,0] else: raise Exception("Not a valid string") # if the image is a timelapse reset the time slider max if len(img.shape) > 2: time_pt.max = img.shape[0] - 1 # set min and maximum values on the sliders based on the image img_min = np.min(img) img_max = np.max(img) inten_min_c1.value = img_min inten_max_c1.value = img_max inten_min_c1.min = img_min inten_min_c1.max = img_max inten_max_c1.min = img_min inten_max_c1.max = img_max return img, img_min, img_max # function comes after the sliders because it calls on variables established in the sliders def read_image_c2(file_name): ''' Read in the image from the file list for channel 2''' # read in the image if type(file_name) == str: if file_name[-3:] == 'tif': img = io.imread(file_name) elif file_name[-3:] == 'czi': img = czifile.imread(file_name) img = img[0,0,1,:,0,:,:,0] else: raise Exception("Not a valid string") # if the image is a timelapse reset the time slider max if len(img.shape) > 2: time_pt.max = img.shape[0] - 1 # set min and maximum values on the sliders based on the image img_min = np.min(img) img_max = np.max(img) inten_min_c2.value = img_min inten_max_c2.value = img_max inten_min_c2.min = img_min inten_min_c2.max = img_max inten_max_c2.min = img_min inten_max_c2.max = img_max return img, img_min, img_max def read_image_c3(file_name): ''' Read in the image from the file list for channel 3''' # read in the image if type(file_name) == str: if file_name[-3:] == 'tif': img = io.imread(file_name) elif file_name[-3:] == 'czi': img = czifile.imread(file_name) img = img[0,0,2,:,0,:,:,0] else: raise Exception("Not a valid string") # if the image is a timelapse reset the time slider max if len(img.shape) > 2: time_pt.max = img.shape[0] - 1 # set min and maximum values on the sliders based on the image img_min = np.min(img) img_max = np.max(img) inten_min_c3.value = img_min inten_max_c3.value = img_max inten_min_c3.min = img_min inten_min_c3.max = img_max inten_max_c3.min = img_min inten_max_c3.max = img_max return img, img_min, img_max # update color name based on rgb values R1.observe(color_name_fromRGB_c1, names="value") G1.observe(color_name_fromRGB_c1, names="value") B1.observe(color_name_fromRGB_c1, names="value") # update color name based on rgb values R2.observe(color_name_fromRGB_c2, names="value") G2.observe(color_name_fromRGB_c2, names="value") B2.observe(color_name_fromRGB_c2, names="value") # update color name based on rgb values R3.observe(color_name_fromRGB_c3, names="value") G3.observe(color_name_fromRGB_c3, names="value") B3.observe(color_name_fromRGB_c3, names="value") # update sliders based on color name or hex value color_mapper_c1 = widgets.interactive_output(color_name2RGB_c1, {'color_name' : color_text_c1}) color_mapperhex_c1 = widgets.interactive_output(hex_to_rgb_c1, {'hex_string' : color_hex_c1}) # update sliders based on color name or hex value color_mapper_c2 = widgets.interactive_output(color_name2RGB_c2, {'color_name' : color_text_c2}) color_mapperhex_c2 = widgets.interactive_output(hex_to_rgb_c2, {'hex_string' : color_hex_c2}) # update sliders based on color name or hex value color_mapper_c3 = widgets.interactive_output(color_name2RGB_c3, {'color_name' : color_text_c3}) color_mapperhex_c3 = widgets.interactive_output(hex_to_rgb_c3, {'hex_string' : color_hex_c3}) # update min/max sliders based on choosing a new image in the list file_chooser_c1 = widgets.interactive_output(read_image_c1, {'file_name' : file_name_c1}) # update min/max sliders based on choosing a new image in the list file_chooser_c2 = widgets.interactive_output(read_image_c2, {'file_name' : file_name_c2}) # update min/max sliders based on choosing a new image in the list file_chooser_c3 = widgets.interactive_output(read_image_c3, {'file_name' : file_name_c3}) # this is the actual widget to display the proper image based on the sliders/textboxes/etc channel1 = widgets.interactive_output(interactive_plot, {'channel_check' : channel_check_c1, 'R' : R1, 'G' : G1, 'B' : B1, 'img' : file_name_c1, 't' : time_pt, 'intensity_minimum' : inten_min_c1, 'intensity_maximum' : inten_max_c1, 'c' : widgets.fixed(0), 'inverted_check' : inverted_check}) # this is the actual widget to display the proper image based on the sliders/textboxes/etc channel2 = widgets.interactive_output(interactive_plot, {'channel_check' : channel_check_c2, 'R' : R2, 'G' : G2, 'B' : B2, 'img' : file_name_c2, 't' : time_pt, 'intensity_minimum' : inten_min_c2, 'intensity_maximum' : inten_max_c2, 'c' : widgets.fixed(1), 'inverted_check' : inverted_check}) # this is the actual widget to display the proper image based on the sliders/textboxes/etc channel3 = widgets.interactive_output(interactive_plot, {'channel_check' : channel_check_c3, 'R' : R3, 'G' : G3, 'B' : B3, 'img' : file_name_c3, 't' : time_pt, 'intensity_minimum' : inten_min_c3, 'intensity_maximum' : inten_max_c3, 'c' : widgets.fixed(2), 'inverted_check' : inverted_check}) # overlay channel channel_overlay = widgets.interactive_output(overlay_interactive, {'inverted_check' : inverted_check, 't' : time_pt, 'img1_check' : channel_check_c1, 'img2_check' : channel_check_c2, 'img3_check' : channel_check_c3, 'img1' : file_name_c1, 'img2' : file_name_c2, 'img3' : file_name_c3, 'R1' : R1, 'G1' : G1, 'B1' : B1, 'R2' : R2, 'G2' : G2, 'B2' : B2, 'R3' : R3, 'G3' : G3, 'B3' : B3, 'img1_min' : inten_min_c1, 'img2_min' : inten_min_c2, 'img3_min' : inten_min_c3, 'img1_max' : inten_max_c1, 'img2_max' : inten_max_c2, 'img3_max' : inten_max_c3,}) def save_image(yup): '''function to save the overlay image''' channel_list, cmap_list, icmap_list, img_min_list, img_max_list = [], [], [], [], [] if channel_check_c1.value: channel_list.append(file_name_c1.value) cmp1, icmp1 = make_colormap((R1.value,G1.value,B1.value),'COLOR',False) cmap_list.append(cmp1) icmap_list.append(icmp1) img_min_list.append(inten_min_c1.value) img_max_list.append(inten_max_c1.value) if channel_check_c2.value: channel_list.append(file_name_c2.value) cmp2, icmp2 = make_colormap((R2.value,G2.value,B2.value),'COLOR',False) cmap_list.append(cmp2) icmap_list.append(icmp2) img_min_list.append(inten_min_c2.value) img_max_list.append(inten_max_c2.value) if channel_check_c3.value: channel_list.append(file_name_c3.value) cmp3, icmp3 = make_colormap((R3.value,G3.value,B3.value),'COLOR',False) cmap_list.append(cmp3) icmap_list.append(icmp3) img_min_list.append(inten_min_c3.value) img_max_list.append(inten_max_c3.value) if inverted_check.value: overlay_im = overlay_image_widget(channel_list,icmap_list,img_min_list,img_max_list, True) else: overlay_im = overlay_image_widget(channel_list,cmap_list,img_min_list,img_max_list, False) curr_path = file_name_c1.value[:file_name_c1.value.rfind('/')+1] io.imsave(curr_path + save_name.value + '.tif' ,overlay_im) # save button save_button.on_click(save_image) # display the widgets display( widgets.HBox([ widgets.VBox([channel_check_c1,file_name_c1,time_pt,color_text_c1,color_hex_c1,R1,G1,B1, inten_min_c1,inten_max_c1,channel1]), widgets.VBox([channel_check_c2,file_name_c2,time_pt,color_text_c2,color_hex_c2,R2,G2,B2, inten_min_c2,inten_max_c2,channel2]), widgets.VBox([channel_check_c3,file_name_c3,time_pt,color_text_c3,color_hex_c3,R3,G3,B3, inten_min_c3,inten_max_c3,channel3]), widgets.VBox([blank,blank,blank,inverted_check, blank,save_name, blank, save_button,blank,blank,channel_overlay]) ]) )
def collect_samples(m): full_widget = widgets.VBox() layout = widgets.Layout(width="100px") prop_label = widgets.Label( value="Property", layout=widgets.Layout(display="flex", justify_content="center", width="100px"), ) value_label = widgets.Label( value="Value", layout=widgets.Layout(display="flex", justify_content="center", width="100px"), ) color_label = widgets.Label( value="Color", layout=widgets.Layout(display="flex", justify_content="center", width="100px"), ) prop_text1 = widgets.Text(layout=layout, placeholder="Required") value_text1 = widgets.Text(layout=layout, placeholder="Integer") prop_text2 = widgets.Text(layout=layout, placeholder="Optional") value_text2 = widgets.Text(layout=layout, placeholder="String") color = widgets.ColorPicker( concise=False, value="#3388ff", layout=layout, style={"description_width": "initial"}, ) buttons = widgets.ToggleButtons( value=None, options=["Apply", "Clear", "Close"], tooltips=["Apply", "Clear", "Close"], button_style="primary", ) buttons.style.button_width = "99px" def button_clicked(change): if change["new"] == "Apply": if len(color.value) != 7: color.value = "#3388ff" draw_control = DrawControl( marker={"shapeOptions": {"color": color.value}}, rectangle={"shapeOptions": {"color": color.value}}, polygon={"shapeOptions": {"color": color.value}}, circlemarker={}, polyline={}, edit=False, remove=False, ) controls = [] old_draw_control = None for control in m.controls: if isinstance(control, DrawControl): controls.append(draw_control) old_draw_control = control else: controls.append(control) m.controls = tuple(controls) old_draw_control.close() m.draw_control = draw_control train_props = {} if prop_text1.value != "" and value_text1.value != "": train_props[prop_text1.value] = int(value_text1.value) if prop_text2.value != "" and value_text2.value != "": train_props[prop_text2.value] = value_text2.value if color.value != "": train_props["color"] = color.value # Handles draw events def handle_draw(target, action, geo_json): from .geemap import ee_tile_layer try: geom = geojson_to_ee(geo_json, False) m.user_roi = geom if len(train_props) > 0: feature = ee.Feature(geom, train_props) else: feature = ee.Feature(geom) m.draw_last_json = geo_json m.draw_last_feature = feature if action == "deleted" and len(m.draw_features) > 0: m.draw_features.remove(feature) m.draw_count -= 1 else: m.draw_features.append(feature) m.draw_count += 1 collection = ee.FeatureCollection(m.draw_features) m.user_rois = collection ee_draw_layer = ee_tile_layer( collection, {"color": "blue"}, "Drawn Features", False, 0.5 ) draw_layer_index = m.find_layer_index("Drawn Features") if draw_layer_index == -1: m.add_layer(ee_draw_layer) m.draw_layer = ee_draw_layer else: m.substitute_layer(m.draw_layer, ee_draw_layer) m.draw_layer = ee_draw_layer except Exception as e: m.draw_count = 0 m.draw_features = [] m.draw_last_feature = None m.draw_layer = None m.user_roi = None m.roi_start = False m.roi_end = False print("There was an error creating Earth Engine Feature.") raise Exception(e) draw_control.on_draw(handle_draw) elif change["new"] == "Clear": prop_text1.value = "" value_text1.value = "" prop_text2.value = "" value_text2.value = "" color.value = "#3388ff" elif change["new"] == "Close": m.toolbar_reset() if m.training_ctrl is not None and m.training_ctrl in m.controls: m.remove_control(m.training_ctrl) full_widget.close() buttons.value = None buttons.observe(button_clicked, "value") full_widget.children = [ widgets.HBox([prop_label, value_label, color_label]), widgets.HBox([prop_text1, value_text1, color]), widgets.HBox([prop_text2, value_text2, color]), buttons, ] widget_control = WidgetControl(widget=full_widget, position="topright") m.add_control(widget_control) m.training_ctrl = widget_control
def init_layout_reshaper(self): # COLUMN TO INDEX col2idx_header = ipw.Label("Column to index") self.col2idx_select = ipw.SelectMultiple(description='', options=self.column_names, value=(), layout=self._base_layout) col2idx_btn_apply = ipw.Button( description="Add", layout=ipw.Layout(width=self._btn_width)) col2idx_btn_apply.on_click(self.on_add_col) col2idx_btn_apply.tooltip = "Add selected columns to Multiindex" col2idx_btn_apply.style.button_color = 'lightgreen' col2idx_layout = ipw.VBox([ col2idx_header, self.col2idx_select, ipw.HBox([col2idx_btn_apply]) ]) # UNSTACKING unstack_header = ipw.Label("Unstack index") self.unstack_select = ipw.SelectMultiple( description='', options=self.index_level_names, value=(), layout=self._base_layout) unstack_btn_apply = ipw.Button( description="Apply", layout=ipw.Layout(width=self._btn_width)) unstack_btn_apply.on_click(self.on_unstack) unstack_btn_apply.style.button_color = 'lightgreen' unstack_btn_apply.tooltip = "Put selected indices into columns" unstack_layout = ipw.VBox([ unstack_header, self.unstack_select, ipw.HBox([unstack_btn_apply]) ]) # STACKING stack_header = ipw.Label("Stack index") self.stack_select = ipw.SelectMultiple( description='', options=self.index_level_col_names, value=(), layout=self._base_layout) stack_btn_apply = ipw.Button(description="Apply", layout=ipw.Layout(width=self._btn_width)) stack_btn_apply.on_click(self.on_stack) stack_btn_apply.style.button_color = 'lightgreen' stack_btn_apply.tooltip = "Put selected indices into rows" stack_layout = ipw.VBox( [stack_header, self.stack_select, ipw.HBox([stack_btn_apply])]) # SELECT COLUMN extract_header = ipw.Label("Extract column") self.extract_select = ipw.Select(description='', options=self.data_column_names, layout=self._base_layout) extract_btn_apply = ipw.Button( description="Apply", layout=ipw.Layout(width=self._btn_width)) extract_btn_apply.on_click(self.on_extract) extract_btn_apply.style.button_color = 'lightgreen' extract_btn_apply.tooltip = "Extract currently selected column" extract_btn_undo = ipw.Button(description="Undo", layout=ipw.Layout(width=self._btn_width)) extract_btn_undo.on_click(self.on_extract_undo) extract_btn_undo.tooltip = "Undo last column extraction" extract_layout = ipw.VBox([ extract_header, self.extract_select, ipw.HBox([extract_btn_undo, extract_btn_apply]) ]) self.layout_reshaper = ipw.HBox( [col2idx_layout, unstack_layout, stack_layout, extract_layout]) self._buttons_edit_df.extend([ col2idx_btn_apply, unstack_btn_apply, stack_btn_apply, extract_btn_apply ])
def __init__(self, description='Terminal', height='200px', width='400px'): super().__init__() # Create the text area object that acts as a terminal self._text_terminal = ipw.Textarea(value='', placeholder='', description='', layout={ 'height': height, 'width': width }, disabled=True) # Create label for terminal description self._label_terminal = ipw.Label( value=description, style={'description_width': 'initial'}, ) self._counter = 0 self._auto_clear = True # Create a autoclear button for our text terminal self._auto_clear_button = ipw.Button(description='Auto Clear', layout=ipw.Layout( margin='auto', border='solid white')) self._auto_clear_button.on_click(lambda _: self.autoclear()) self._auto_clear_button.style.button_color = 'lightblue' # Create a clear button for our text terminal self._clear_button = ipw.Button(description='Clear', layout=ipw.Layout( margin='auto', border='solid white')) self._clear_button.on_click(lambda _: self.clear()) self._clear_button.style.button_color = 'lightgray' # Create a start button to enable listening self._start_button = ipw.Button(description=u'\u25B6', layout=ipw.Layout( margin='auto', border='solid white')) self._start_button.on_click(lambda _: self.start()) self._start_button.style.button_color = 'lightgray' # Create a stop button to disable listening self._stop_button = ipw.Button(description=u'\u25A0', layout=ipw.Layout(margin='auto', border='solid white')) self._stop_button.on_click(lambda _: self.stop()) self._stop_button.style.button_color = 'tomato' # Set listening to false self._listening = False # Create Accordion self._accordion = ipw.Accordion(children=[ ipw.HBox([ ipw.VBox([self._text_terminal]), ipw.VBox([ self._start_button, self._stop_button, self._clear_button, self._auto_clear_button ], layout=ipw.Layout(align_self='flex-start')) ]) ]) self._accordion.set_title(0, description)
layout=tab_layout) else: titles = [ 'About', 'Config Basics', 'Microenvironment', 'User Params', 'Out: Plots' ] tabs = widgets.Tab(children=[ about_tab.tab, config_tab.tab, microenv_tab.tab, user_tab.tab, sub.tab ], _titles={i: t for i, t in enumerate(titles)}, layout=tab_layout) homedir = os.getcwd() tool_title = widgets.Label(r'\(\textbf{tool4nanobio}\)') if nanoHUB_flag or hublib_flag: # define this, but don't use (yet) remote_cb = widgets.Checkbox( indent=False, value=False, description='Submit as Batch Job to Clusters/Grid') top_row = widgets.HBox(children=[read_config, tool_title]) gui = widgets.VBox(children=[top_row, tabs, run_button.w]) fill_gui_params(read_config.options['DEFAULT']) else: top_row = widgets.HBox(children=[tool_title]) gui = widgets.VBox(children=[top_row, tabs, run_button]) fill_gui_params("data/PhysiCell_settings.xml")
def __init__(self): apt.progress.base.InstallProgress.__init__(self) self._label = ipywidgets.Label() display(self._label) self._float_progress = ipywidgets.FloatProgress(min = 0.0, max = 1.0, layout = {'border':'1px solid #118800'}) display(self._float_progress)
def actualiza_layout(): if animacion_on: anim.event_source.stop() clear() #Mostrar estadisticas de las variables max_value = "Max value: " + str(propiedades[4]) min_value = "Min value: " + str(propiedades[3]) mean_value = "Mean value: " + str(propiedades[5]) #Muestra, si la hay, la descripcion de las variables des = "" try: des = (variables[0][propiedades[0]] + ": " + dataset.variables[variables[0][propiedades[0]]].long_name) except: des = ("Variable sin descripción") label = widgets.Label(des) label_min = widgets.Label(min_value) label_max = widgets.Label(max_value) label_mean = widgets.Label(mean_value) hb_max_min = HBox([label_min, label_max, label_mean]) hb_range = HBox([min_range, max_range, boton_range]) #Comprueba de que depende las variables, y escoge que pasarle dependiendo de eso if variables[1][propiedades[0]] == 4: depth_wid.max = dataset.variables[variables[0][ propiedades[0]]].shape[-3] - 1 display(hb_3d, label, hb_max_min, hb_range) prof = propiedades[2] if tipo == 0: dimz = dataset.variables[variables[0][ propiedades[0]]].shape[-3] - 1 prof = dimz - prof aux = dataset.variables[variables[0][propiedades[0]]][propiedades[1], prof, :, :] ev = vb_ev_3d if variables[1][propiedades[0]] == -1: depth_wid.max = dataset.variables["R1"].shape[-3] - 1 display(hb_3d, label, hb_max_min, hb_range) prof = propiedades[2] dimz = dataset.variables["R1"].shape[-3] - 1 prof = dimz - prof aux = dataset.variables["R1"][propiedades[1], 1, prof, :, :] ev = vb_ev_3d if variables[1][propiedades[0]] == 3: display(hb_2d, label, hb_max_min, hb_range) aux = dataset.variables[variables[0][propiedades[0]]][ propiedades[1], :, :] ev = vb_ev_2d aux = np.transpose(aux) #Convierte los valores de relleno en nan para que no se pinten en el mapa v_m = np.nanmin(aux[:]) try: aux[aux == v_m] = np.nan except: print("fallo") fig = imshow_rango(aux, min_range.value, max_range.value) #Se crea un evento para coger las coordenadas escogidas cid = fig.canvas.mpl_connect('button_press_event', onclick) display(ev)
def set_widgets(): global drop_var, drop_date, depth_wid, hb_3d, hb_2d, vb_ev_2d, vb_ev_3d, valor_x, valor_y, date, drop_date_range2, drop_date_range1 #widgets para escoger que datos mostrar drop_var = widgets.Dropdown( options=[(variables[2][n], n) for n in range(len(variables[2]))], value=0, description='Variables:', ) date = set_date() drop_date = widgets.Dropdown( options=[(str(date[i]), i) for i in range(len(date))], value=0, description='Date:', ) drop_date.observe(date_on_change, names='value') drop_var.observe(variable_on_change, names='value') hb_3d = HBox([drop_var, drop_date, depth_wid]) hb_2d = HBox([drop_var, drop_date]) #cuadro de texto para donde se escoge el valor de coordenada x e y valor_x = widgets.BoundedFloatText( value=0, min=0, max=dataset.variables[variables[0][propiedades[0]]].shape[-2] - 1, step=1, description='x:') valor_y = widgets.BoundedFloatText( value=0, min=0, max=dataset.variables[variables[0][propiedades[0]]].shape[-1] - 1, step=1, description='y:') #widgets para ver más info boton_tiempo = widgets.Button(description='Tiempo') boton_animacion = widgets.Button(description='Animación evolución') boton_prof = widgets.Button(description='Profundidad') boton_corte_lon = widgets.Button(description='Longitudinal') boton_corte_lat = widgets.Button(description='Latitudinal') Label_cor = widgets.Label("Clicar en el mapa para escoger coordenadas:") Label_display = widgets.Label("Mostrar:") Label_date = widgets.Label("Rango de fechas:") Label_section = widgets.Label("Mapa con corte:") Label_plot = widgets.Label("Diagrama con evolución en función:") drop_date_range1 = widgets.Dropdown( options=[(str(date[i]), i) for i in range(0, len(date) - range_index)], value=0, description='Desde:', ) drop_date_range2 = widgets.Dropdown( options=[(str(date[i]), i) for i in range(range_index, len(date))], value=len(date) - range_index, description='Hasta:', ) vb_cor = VBox([Label_cor, valor_x, valor_y]) vb_date_range = VBox([Label_date, drop_date_range1, drop_date_range2]) hb_options = HBox([vb_cor, vb_date_range]) hb_corte = HBox([boton_corte_lat, boton_corte_lon], layout=box_layout) hb_plot = HBox([boton_tiempo, boton_prof], layout=box_layout) hb_time = HBox([boton_tiempo], layout=box_layout) vb_ev_3d = VBox([ hb_options, Label_display, boton_animacion, Label_section, hb_corte, Label_plot, hb_plot ]) vb_ev_2d = VBox( [hb_options, Label_display, boton_animacion, Label_plot, hb_time]) widgets.interact(drop_date_range1=drop_date_range1, drop_date_range2=drop_date_range2) drop_date_range1.observe(range_on_change, names='value') boton_prof.on_click(on_button_clicked_ev_prof) boton_tiempo.on_click(on_button_clicked_ev_time) boton_animacion.on_click(on_button_clicked_animacion) boton_corte_lat.on_click(on_button_clicked_corte_lat) boton_corte_lon.on_click(on_button_clicked_corte_lon)
def add_current_to_map(self): """ Add the currently-selected `~.Workflow` to ``wf.map`` or ``self.map``, if possible. The `~.Workflow` must be one of these types: * `~.geospatial.Image` * `~.ImageCollection` * `~.Function`, in which case it must return an `~.geospatial.Image` or `~.ImageCollection`, and only take `~.Int`, `~.Float`, `~.Str`, `~.Bool`, or `~.Datetime` as parameters. A widget will be added to the map to control the function arguments interactively. If the version has `~.VersionedGraft.viz_options`, the first `.VizOption` will be used to style the layer on the map. If ``self.map`` is None, the layer will be added to ``wf.map``, otherwise to ``self.map``. Returns ------- lyr: WorkflowsLayer The layer added to the map Raises ------ ValueError If a Workflow and version are not currently selected. If the currently-selected Workflow and version is incompatible with this client version. TypeError If the selected version is not one of the supported types. """ flow = self.current_flow vg = self.current_vg if not (flow and vg): raise ValueError("No Workflow and version currently selected") params = vg._make_params() # ^ NOTE(gabe): use `._make_params()` instead of `.params` so we get new params objects every time, # meaning new widget instances. otherwise, if the object was added to the map multiple times, # the widgets for every layer would seem to be linked (because they'd actually be the same objects). try: param_overrides = { p._name: proxytype_to_widget[type(p)]( name=p._name, **( # omg this is terrible. find a better way. dict(hide_deps_of=p) if isinstance( p, (types.Image, types.ImageCollection)) else {}), ) for p in params if not hasattr(p, "widget") } except KeyError as e: raise TypeError(f"Cannot create interactive control for type {e}") obj = vg.object if isinstance(obj, types.Function): obj = obj(*params) if isinstance(obj, (types.Image, types.ImageCollection)): if vg.viz_options: viz_option = vg.viz_options[0] if viz_option.bands: obj = obj.pick_bands(viz_option.bands) visualize_kwargs = { "checkerboard": viz_option.checkerboard, "colormap": viz_option.colormap, "scales": viz_option.scales, } if isinstance(obj, types.ImageCollection): visualize_kwargs["reduction"] = viz_option.reduction else: visualize_kwargs = {} map_ = self.map if isinstance(map_, MapApp): map_ = map_.map # if layer name already exists, don't overwrite it layer_name = f"{flow.name}:{vg.version}" i = 2 while any(layer.name == layer_name for layer in map_.layers): layer_name = f"{flow.name}:{vg.version} ({i})" i += 1 lyr = obj.visualize( layer_name, map=map_, **visualize_kwargs, **param_overrides, ) if len(params) > 0: # hack to display layer params on map labels = ipywidgets.VBox(children=[ ipywidgets.Label(getattr(p, "_label", "") or p._name) for p in params ]) widgets = ipywidgets.VBox(children=[ param_overrides.get(p._name, None) or p.widget for p in params ]) content = ipywidgets.HBox(children=[labels, widgets]) widget = ipywidgets.VBox( children=[ipywidgets.HTML(f"<b>{lyr.name}<b>"), content]) ctrl = ipyleaflet.WidgetControl(widget=widget, position="bottomleft") map_.add_control(ctrl) def remove_ctrl_obs(layers_change): if lyr not in layers_change["new"]: map_.remove_control(ctrl) map_.unobserve(remove_ctrl_obs, names="layers") map_.observe(remove_ctrl_obs, names="layers") return lyr raise TypeError( f"Can only visualize Image, ImageCollection, and Functions that return those, not {vg.type.__name__}" )
def sqlm(self, line, cell=None): """ Execute SQL code (either from line, cell, or file), print returned DataFrame (if not noprint in first line; only for cell), and store DataFrame in local variable. """ # check connection if not self.cursor: print('not connected') return # prepare sql if cell is None: sql = line self.noprint = False self.output_varname = 'df' else: # line parsing line = line.split(' ') # file or cell SQL if 'file' in line: with open(file=cell.strip(), encoding='utf-8') as f: sql = f.read() else: sql = cell # check noprint self.noprint = 'noprint' in line # output variable name from line self.output_varname = next( filter(lambda x: x.startswith('var='), line), None) if self.output_varname: self.output_varname = self.output_varname.split('=')[1] else: self.output_varname = 'df' # counter, button, layout, & display self.lbl_counter = ipywidgets.Label(value='initialising ...', layout=ipywidgets.Layout( height='initial', margin='0')) self.btn_cancel = ipywidgets.Button(description='Cancel', button_style='danger', layout=ipywidgets.Layout( width='initial', margin='0 0 0 10px')) self.stmt_info = ipywidgets.HBox( children=[self.lbl_counter, self.btn_cancel], layout=ipywidgets.Layout(margin='0 0 5px 0')) display(self.stmt_info) # reset vars self.event_stop_counter = threading.Event() self.event_cell_waiting = threading.Event() self.cancelled = False self.start_time = time.perf_counter() # start statement in new thread future = self.pool.submit(self.exec_statement, sql) future.add_done_callback(self.statement_done) # update counter self.pool.submit(self.update_counter) # cancel button self.btn_cancel.on_click(self.onclick_cancel_statement) # using the fantastic https://github.com/Kirill888/jupyter-ui-poll to process UI events, but block further cell execution with ui_events() as poll: while not self.event_cell_waiting.is_set(): poll(1) time.sleep(0.1)
dividers = {"a": 16380, "b": 8192, "c": 4096, "d": 2048} rates = { "a": "1 Hz", "b": "10 Hz", "c": "25 Hz", "d": "50 Hz", "e": "100 Hz", "f": "200 Hz", "g": "400 Hz" } ranges = {"a": "2G", "b": "4G", "c": "8G", "d": "16G"} # UI elements that need global access sample_count_labels = dict() status_labels = dict() milliseconds_label = widgets.Label(value="0", layout=widgets.Layout(width="100%")) _main_tabs = None _status_panel = None _export_panel = None _settings_panel = None # UDP Helper functions def udp_send(ip, data): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0) s.connect((ip, PORT)) s.send(data) s.close() def udp_broadcast(data):
def manage_log(self, line): line = line or "" if line or not __CAN_USE_WIDGET__: params = line.split(" ") if len(params) == 5: print(u"连接中...") endpoint, key_id, key_val, project, logstore = params result, detail = self.verify_sls_connection( endpoint, key_id, key_val, project, logstore) if result: clear_output() print(u"连接成功.") _save_config(endpoint, key_id, key_val, project, logstore) self.client(reset=True) else: print(detail) else: print( u"参数错误,请使用GUI配置(无参)或遵循格式:%manage_log <endpoint> <ak_id> <ak_key> <project> <logstore>" ) return import ipywidgets as widgets w_1 = widgets.ToggleButtons(options=[u'基本配置', u"高级配置"]) w_endpoint = widgets.Text(description=u'服务入口', value=g_default_region) w_key_id = widgets.Password(description=u'秘钥ID', value=g_default_ak_id) w_key_val = widgets.Password(description=u'秘钥Key', value=g_default_ak_key) w_project = widgets.Text(description=u'默认项目', value=g_default_project) w_logstore = widgets.Text(description=u'默认日志库', value=g_default_logstore) w_confirm = widgets.Button( description=u'修改' if g_default_region else u'确认', button_style='info', icon='confirm') w_result = widgets.Label(value='') hide_layout = widgets.Layout(height="0px") show_layout = widgets.Layout(height='auto') progress = widgets.FloatProgress(description="", value=0.0, min=0.0, max=1.0, layout=hide_layout) def work(progress): global result total = 100 for i in range(total): time.sleep(0.2) if result is None: progress.value = float(i + 1) / total else: progress.value = 100 progress.description = u"完成" if result else u"失败" break def on_button_clicked(b): global result, detail progress.layout = show_layout progress.description = u"连接中..." progress.value = 0 w_result.value = "" result = None detail = "" thread = threading.Thread(target=work, args=(progress, )) thread.start() result, detail = self.verify_sls_connection( w_endpoint.value, w_key_id.value, w_key_val.value, w_project.value, w_logstore.value) if result: w_result.value = u"连接成功." _save_config(w_endpoint.value, w_key_id.value, w_key_val.value, w_project.value, w_logstore.value) self.client(reset=True) else: w_result.value = str(detail) w_confirm.on_click(on_button_clicked) p = widgets.VBox(children=[ w_1, w_endpoint, w_key_id, w_key_val, w_project, w_logstore, w_confirm, progress, w_result ]) return p
else: titles = [ 'About', 'Config Basics', 'Microenvironment', 'User Params', 'Out: Plots', 'Fury' ] tabs = widgets.Tab(children=[ about_tab.tab, config_tab.tab, microenv_tab.tab, user_tab.tab, sub.tab, fury_tab.tab ], _titles={i: t for i, t in enumerate(titles)}, layout=tab_layout) homedir = os.getcwd() tool_title = widgets.Label( r'\(\textbf{PhysiCell 3D tumor and Fury visualization}\)') if nanoHUB_flag or hublib_flag: # define this, but don't use (yet) remote_cb = widgets.Checkbox( indent=False, value=False, description='Submit as Batch Job to Clusters/Grid') top_row = widgets.HBox(children=[read_config, tool_title]) gui = widgets.VBox(children=[top_row, tabs, run_button.w]) fill_gui_params(read_config.options['DEFAULT']) else: top_row = widgets.HBox(children=[tool_title]) gui = widgets.VBox(children=[top_row, tabs, run_button]) fill_gui_params("data/PhysiCell_settings.xml")
def movie_maker_widget(timelapse_path): ''' Widget to make a move from a timelapse input: timelapse_path - a string that points to a multipage tif timelapse ''' # read in the image and get it's dimensions overlay_timelapse = io.imread(timelapse_path) N_frames, img_h, img_w, N_notused = overlay_timelapse.shape def update_scaleposition(change): '''function to update scalebar position text in the widget''' if scaleposition_r.value == 20: if scaleposition_c.value == 20: scaleposition.value = 'top_left' elif scaleposition_c.value == int(img_w - 20 - scalebar_length.value/um_per_pix.value): scaleposition.value = 'top_right' else: scaleposition.value = '' elif scaleposition_r.value == (img_h - 20): if scaleposition_c.value == int(img_w - 20 - scalebar_length.value/um_per_pix.value): scaleposition.value = 'bottom_right' elif scaleposition_c.value == 20: scaleposition.value = 'bottom_left' else: scaleposition.value = '' else: scaleposition.value = '' def update_scaleposition_rc(change): '''function to update scalebar position sliders based on text input''' if scaleposition.value == 'bottom_right': scaleposition_r.value = img_h - scaleheight.value - 20 scaleposition_c.value = int(img_w - 20 - scalebar_length.value/um_per_pix.value) scalefontposition_r.value = int(scaleposition_r.value - scalefontsize.value - 5) scalefontposition_c.value = scaleposition_c.value if scaleposition.value == 'bottom_left': scaleposition_r.value = img_h - scaleheight.value - 20 scaleposition_c.value = 20 scalefontposition_r.value = int(scaleposition_r.value - scalefontsize.value - 5) scalefontposition_c.value = scaleposition_c.value if scaleposition.value == 'top_left': scaleposition_r.value = 20 scaleposition_c.value = 20 scalefontposition_r.value = int(scaleposition_r.value + scaleheight.value + 5) scalefontposition_c.value = 20 if scaleposition.value == 'top_right': scaleposition_r.value = 20 scaleposition_c.value = int(img_w - 20 - scalebar_length.value/um_per_pix.value) scalefontposition_r.value = int(scaleposition_r.value + scaleheight.value + 5) scalefontposition_c.value = scaleposition_c.value def update_timeposition(change): '''function to update the timestampe text in the widget''' if timeposition_r.value == 30: if timeposition_c.value == 30: timeposition.value = 'top_left' elif timeposition_c.value == (img_w - 3 * timefontsize.value - 30): timeposition.value = 'top_right' else: timeposition.value = '' elif timeposition_r.value == (img_h - 1 * timefontsize.value): if timeposition_c.value == (img_w - 3 * timefontsize.value - 30): timeposition.value = 'bottom_right' elif timeposition_c.value == 30: timeposition.value = 'bottom_left' else: timeposition.value = '' else: timeposition.value = '' def update_timeposition_rc(change): '''function to update timestamp position sliders based on text input''' if change.new == 'bottom_right': timeposition_r.value = img_h - 1 * timefontsize.value timeposition_c.value = img_w - 3 * timefontsize.value - 30 if change.new == 'bottom_left': timeposition_r.value = img_h - 1 * timefontsize.value timeposition_c.value = 30 if change.new == 'top_left': timeposition_r.value = 30 timeposition_c.value = 30 if change.new == 'top_right': timeposition_r.value = 30 timeposition_c.value = img_w - 3 * timefontsize.value - 30 def update_scalebar_length(change): '''updates the scalebar based on the text input''' label_str = scalelabel.value if len(label_str) > 0: numbers = [] for word in label_str.split(): if word.isdigit(): numbers.append(int(word)) scalebar_length.value = int(numbers[0]) def save_image(yup): '''Saves the image and a parameter file ''' # get the main path of the file to make the movie from curr_path = timelapse_path[:timelapse_path.rfind('/')+1] # make a string for the filename savename = curr_path + filesavename.value + '.mp4' # write out the parameters as a csv file for reference later if save_params_check.value: param_dict = { 'time_interval' : time_interval.value, 'um_per_pix' : um_per_pix.value, 'scalebar_check' : scalebar_check.value, 'scalebar_length' : scalebar_length.value, 'scaleheight' : scaleheight.value, 'scalecolor' : scalecolor.value, 'scaleposition_r' : scaleposition_r.value, 'scaleposition_c' : scaleposition_c.value, 'scalelabel' : scalelabel.value, 'scalefontsize' : scalefontsize.value, 'scalefont_r' : scalefontposition_r.value, 'scalefont_c' : scalefontposition_c.value, 'timestamp_check' : timestamp_check.value, 'timeposition_r' : timeposition_r.value, 'timeposition_c' : timeposition_c.value, 'timefontsize' : timefontsize.value, 'framerate' : framerate.value, 'quality' : quality.value } # write out the csv file with the parameters with open(curr_path + filesavename.value + '_params.csv', 'w', newline="") as csv_file: writer = csv.writer(csv_file) for key, value in param_dict.items(): writer.writerow([key, value]) # determine the parameters to pass to the save function if timestamp_check.value: # figure out the format if (time_interval.value * N_frames) < 60: fmt = 'sec:' elif (time_interval.value * N_frames) < 3600: fmt = 'min:sec' else: fmt = 'hr:min:sec' # make the timestamps time_pts = make_timestamp_list(time_interval.value, N_frames, fmt) if scalebar_check.value: save_timelapse_as_movie(savename, overlay_timelapse, scalebar_length = int(scalebar_length.value / um_per_pix.value), scaleheight = scaleheight.value, scalecolor = scalecolor.value, scaleposition = (scaleposition_r.value, scaleposition_c.value), scalelabel = scalelabel.value, scalefontsize = scalefontsize.value, scalefontposition = (scalefontposition_r.value, scalefontposition_c.value), time_pts = time_pts, timeposition = (timeposition_r.value, timeposition_c.value), timefontsize = timefontsize.value, framerate = framerate.value, quality = quality.value) else: save_timelapse_as_movie(savename, overlay_timelapse, scalecolor = scalecolor.value, time_pts = time_pts, timeposition = (timeposition_r.value, timeposition_c.value), timefontsize = timefontsize.value, framerate = framerate.value, quality = quality.value) elif scalebar_check.value: save_timelapse_as_movie(savename, overlay_timelapse, scalebar_length = int(scalebar_length.value / um_per_pix.value), scaleheight = scaleheight.value, scalecolor = scalecolor.value, scaleposition = (scaleposition_r.value, scaleposition_c.value), scalelabel = scalelabel.value, scalefontsize = scalefontsize.value, scalefontposition = (scalefontposition_r.value, scalefontposition_c.value), framerate = framerate.value, quality = quality.value) else: save_timelapse_as_movie(savename, overlay_timelapse, framerate = framerate.value, quality = quality.value) def preview_overlay(imstack, movie_frame, time_interval, um_per_pix, scalebar_check, scalebar_length, scaleheight, scalecolor, scaleposition_r, scaleposition_c, scalelabel, scalefontsize, scalefont_r, scalefont_c, timestamp_check, timeposition_r, timeposition_c, timefontsize, framerate, quality, N_frames): '''preview the overlay by writing only the given image from the time series''' # make tuples from the row/column values from the sliders scaleposition = (scaleposition_r,scaleposition_c) scalefontposition = (scalefont_r, scalefont_c) timeposition = (timeposition_r,timeposition_c) scalebar_length_um = int(scalebar_length / um_per_pix) # check if a timestamp is included if timestamp_check: # figure out the format if (time_interval * N_frames) < 60: fmt = 'sec:' elif (time_interval * N_frames) < 3600: fmt = 'min:sec' else: fmt = 'hr:min:sec' # make the timestamps time_pts = make_timestamp_list(time_interval, N_frames, fmt) # if so save with metadata tag io.imsave('first_frame.tif',imstack[movie_frame], plugin='tifffile', extratags=[(306, 's', 0, str(time_pts[movie_frame]), True )]) else: # just save normally io.imsave('first_frame.tif',imstack[movie_frame]) # generate the ffmpeg command if scalebar_check: if timestamp_check: command_string, params = ffmpeg_str('first_frame_overlay.tif', imstack, fmt = 't', scalebar_length=scalebar_length_um, scaleheight=scaleheight, scalecolor=scalecolor, scaleposition=scaleposition, scalelabel=scalelabel, scalefontsize=scalefontsize, scalefontposition = scalefontposition, time_pts = time_pts, timeposition=timeposition, timefontsize=timefontsize, framerate=framerate, quality=quality) else: command_string, params = ffmpeg_str('first_frame_overlay.tif', imstack, fmt = 't', scalebar_length=scalebar_length_um, scaleheight=scaleheight, scalecolor=scalecolor, scaleposition=scaleposition, scalelabel=scalelabel, scalefontsize=scalefontsize, scalefontposition = scalefontposition, framerate=framerate, quality=quality) elif timestamp_check: command_string, params = ffmpeg_str('first_frame_overlay.tif', imstack, fmt = 't', time_pts = time_pts, timeposition=timeposition,timecolor=scalecolor, timefontsize=timefontsize, framerate=framerate, quality=quality) else: command_string, params = ffmpeg_str('first_frame_overlay.tif', imstack, fmt = 't', framerate=framerate, quality=quality) # run ffmpeg subprocess.call(command_string, shell=True) # delete the first frame os.remove('first_frame.tif') # read in the overlay first_frame_overlay = io.imread('first_frame_overlay.tif') # plot the overlay fig = plt.figure(figsize=(8,8)) plt.imshow(first_frame_overlay) plt.axis('off') # widgets for the main movie section blank = widgets.Label(value = '') input_details = widgets.Label(value = 'Timelapse Movie Details') time_interval = widgets.FloatText(value = 1, description = 'timestep (s)', continuous_update = False) um_per_pix = widgets.FloatText(value = .17460, description='µm/pixel', continuous_update = False) movie_frame = widgets.IntSlider(value=0, min=0, max=N_frames-1, description='Frame', continuous_update = False) save_params_check = widgets.Checkbox(description = 'Save Parameters Text File') # widgets related to the scalebar scalebar_details = widgets.Label(value = 'Scalebar Parameters') scalebar_check = widgets.Checkbox(description = 'Include Scalebar') scalebar_length = widgets.IntSlider(value=10, min=0, max= int(img_w * 0.5 * um_per_pix.value), description='length (µm)', continuous_update=False) scaleheight = widgets.IntSlider(value=int(img_h * 0.015), min = 1, max = 100, step = 1, description = 'scaleheight', continuous_update = False) scaleposition = widgets.Dropdown(options=['','bottom_right','bottom_left','top_left','top_right'],value='bottom_right', description='scale position') scaleposition_r = widgets.IntSlider(value=(img_h - 20), min=0, max=img_h, description='scalebar row', continuous_update=False) scaleposition_c = widgets.IntSlider(value=int(img_w - 20 - scalebar_length.value/um_per_pix.value), min=0, max=img_w, description='scalebar col', continuous_update=False) scalelabel = widgets.Text(value='10 µm', placeholder = '10 µm', description = 'scale label', continuous_update = False) scalefontsize = widgets.IntSlider(value=(int(scalebar_length.value / um_per_pix.value / 3)), min = 6, max=130, step = 1, description = 'fontsize', continuous_update = False) scalefontposition_r = widgets.IntSlider(value=(scaleposition_r.value - scalefontsize.value - 5), min=0, max=img_h, description='font row', continuous_update=False) scalefontposition_c = widgets.IntSlider(value=int(img_w - 20 - scalebar_length.value/um_per_pix.value), min=0, max=img_w, description='font col', continuous_update=False) # widgets related to the timestamp timestamp_details = widgets.Label(value = 'Time Stamp Parameters') timestamp_check = widgets.Checkbox(description = 'Include Time Stamp') timefontsize = widgets.IntSlider(value=(3 * scalefontsize.value), min = 6, max=130, step = 1, description = 'fontsize', continuous_update = False) timeposition = widgets.Dropdown(options=['','bottom_right','bottom_left','top_left','top_right'], value='top_right', description='time position') timeposition_r = widgets.IntSlider(value=30, min=0, max=img_h, description='time row', continuous_update=False) timeposition_c = widgets.IntSlider(value=(img_w - 3 * timefontsize.value - 30), min=0, max=img_w, description='time col', continuous_update=False) # widgets related to saving the movie movie_details = widgets.Label(value = 'Output Movie Parameters') quality = widgets.IntSlider(value=25, min = 15, max = 30, step = 1, description = 'quality', continuous_update = False) framerate = widgets.IntSlider(value=10, min = 1, max = 60, step = 1, description = 'framerate', continuous_update = False) scalecolor = widgets.Dropdown(options=['black', 'white', 'gray'], description='Text color') filesavename = widgets.Text(value='', description='Save Name', continuous_update = False) savebutton = widgets.Button(description="Save Movie", layout=widgets.Layout(width='98%')) preview_overlay_button = widgets.Button(description="Preview Overlay", layout=widgets.Layout(width='98%')) # widgets to update values based on the scalebar and timstamp position sliders text inputs scaleposition_r.observe(update_scaleposition, names="value") scaleposition_c.observe(update_scaleposition, names="value") timeposition_r.observe(update_timeposition, names="value") timeposition_c.observe(update_timeposition, names="value") # widgets to update the row column sliders based on the text inputs scaleposition.observe(update_scaleposition_rc, names="value") timeposition.observe(update_timeposition_rc, names="value") # widget to update scale bar length scalebar_length.observe(update_scaleposition_rc, names="value") # widget to update the scalebar length and label based on the microns per pixel input um_per_pix.observe(update_scalebar_length, names="value") scalelabel.observe(update_scalebar_length, names="value") # save button and preview button savebutton.on_click(save_image) preview_overlay_button.on_click(preview_overlay) # overlay channel overlay_preview = widgets.interactive_output(preview_overlay, {'imstack' : widgets.fixed(overlay_timelapse), 'movie_frame' : movie_frame, 'time_interval' : time_interval, 'um_per_pix' : um_per_pix, 'scalebar_check' : scalebar_check, 'scalebar_length' : scalebar_length, 'scaleheight' : scaleheight, 'scalecolor' : scalecolor, 'scaleposition_r' : scaleposition_r, 'scaleposition_c' : scaleposition_c, 'scalelabel' : scalelabel, 'scalefontsize' : scalefontsize, 'scalefont_r': scalefontposition_r, 'scalefont_c' : scalefontposition_c, 'timestamp_check' : timestamp_check, 'timeposition_r' : timeposition_r, 'timeposition_c' : timeposition_c, 'timefontsize' : timefontsize, 'framerate' : framerate, 'quality' : quality, 'N_frames' : widgets.fixed(N_frames)}) # display thw widget display(widgets.HBox([widgets.VBox([input_details,time_interval,um_per_pix, movie_frame, blank, scalebar_details, scalebar_check, scaleposition, scaleposition_r, scaleposition_c,scalebar_length, scaleheight,scalelabel,scalefontsize, scalefontposition_r, scalefontposition_c], layout=widgets.Layout(display='flex' ,align_items='center')), widgets.VBox([movie_details, quality, framerate, scalecolor,blank, timestamp_details, timestamp_check, timeposition, timeposition_r, timeposition_c, timefontsize,blank,blank,filesavename,save_params_check,savebutton], layout=widgets.Layout(display='flex' , align_items='center')), widgets.VBox([overlay_preview]) ]) )
def inputwidget(model,df,slidedef={},radiodef=[],checkdef=[],modelopt={},varpat='RFF XGDPN RFFMIN GFSRPN DMPTRSH XXIBDUMMY' ,showout=1,trans={}): '''Creates an input widgets for updating variables :df: Baseline dataframe :slidedef: dict with definition of variables to be updated by slider :radiodef: dict of lists. each at first level defines a collection of radiobuttoms second level defines the text for each leved and the variable to set or reset to 0 :varpat: the variables to show in the output widget :showout: 1 if the output widget is to be called ''' lradiodef= len(radiodef) lslidedef = len(slidedef) lcheckdef = len(checkdef) basename ='Baseline' if lradiodef: wradiolist = [widgets.RadioButtons(options=[i for i,j in cont],description=des,layout={'width':'70%'}, style={'description_width':'37%'}) for des,cont in radiodef.items()] if len(wradiolist) <=2: wradio = widgets.HBox(wradiolist) else: wradio = widgets.VBox(wradiolist) # define slidesets if lslidedef: wexp = widgets.Label(value="Input new parameter ",layout={'width':'41%'}) walt = widgets.Label(value="Alternative",layout={'width':'8%'}) wbas = widgets.Label(value="Baseline",layout={'width':'8%'}) whead = widgets.HBox([wexp,walt,wbas]) wset = [widgets.FloatSlider(description=des, min=cont['min'],max=cont['max'],value=cont['value'],step=cont.get('step',0.01), layout={'width':'60%'},style={'description_width':'40%'}) for des,cont in slidedef.items()] waltval= [widgets.Label(value=f"{cont['value']:>.2f}",layout={'width':'8%'}) for des,cont in slidedef.items()] wslide = [widgets.HBox([s,v]) for s,v in zip(wset,waltval)] # cheklist if lcheckdef: wchecklist = [widgets.Checkbox(description=des,value=val) for des,var,val in checkdef] wcheck = widgets.HBox(wchecklist) # some buttons and text wname = widgets.Text(value='Alternative',placeholder='Type something',description='Name of experiment:', layout={'width':'30%'},style={'description_width':'50%'}) wpat = widgets.Text(value=varpat,placeholder='Type something',description='Output variables:', layout={'width':'65%'},style={'description_width':'30%'}) winputstring = widgets.HBox([wname,wpat]) wgo = widgets.Button(description="Run") wreset = widgets.Button(description="Reset to default") wsetbas = widgets.Button(description="Use as baseline") wbut = widgets.HBox([wgo,wreset,wsetbas]) wvar = [whead]+wslide if lslidedef else [] if lradiodef: wvar = wvar + [wradio] if lcheckdef: wvar = wvar + [wcheck] w = widgets.VBox(wvar+[winputstring] +[wbut]) # This function is run when the button is clecked def run(b): mulstart = model.basedf.copy() # First update from the sliders if lslidedef: for i,(des,cont) in enumerate(slidedef.items()): op = cont.get('op','=') var = cont['var'] for var in cont['var'].split(): if op == '+': mulstart.loc[model.current_per,var] = mulstart.loc[model.current_per,var] + wset[i].value elif op == '+impulse': mulstart.loc[model.current_per[0],var] = mulstart.loc[model.current_per[0],var] + wset[i].value elif op == '=': mulstart.loc[model.current_per,var] = wset[i].value elif op == '=impuse': mulstart.loc[model.current_per,var] = wset[i].value else: print(f'Wrong operator in {cont}.\nNot updated') # now update from the radio buttons if lradiodef: for wradio,(des,cont) in zip(wradiolist,radiodef.items()): print(des,wradio.value,wradio.index,cont[wradio.index]) for v in cont: mulstart.loc[model.current_per,v[1]] = 0.0 mulstart.loc[model.current_per,cont[wradio.index][1]] = 1.0 if lcheckdef: for box,(des,var,_) in zip(wchecklist,checkdef): mulstart.loc[model.current_per,var] = 1.0 * box.value #with out: clear_output() mul = model(mulstart,**modelopt) clear_output() display(w) #_ = mfrbus['XGDPN RFF RFFMIN GFSRPN'].dif.rename(trans).plot(colrow=1,sharey=0) if showout: a = vis_alt3(get_alt(model,wpat.value),model,basename=basename,altname=wname.value,trans=trans) def reset(b): if lslidedef: for i,(des,cont) in enumerate(slidedef.items()): wset[i].value = cont['value'] if lradiodef: for wradio in wradiolist: wradio.index = 0 if lcheckdef: for box,(des,var,defvalue) in zip(wchecklist,checkdef): box.value = defvalue def setbas(b): nonlocal basename model.basedf = model.lastdf.copy(deep=True) basename = wname.value # Assign the function to the button wgo.on_click(run) wreset.on_click(reset) wsetbas.on_click(setbas) out = widgets.Output() return w
def job_monitor(): header_box = ipywidgets.HBox([ ipywidgets.Label('Job ID'), ipywidgets.Label('Duration'), ipywidgets.Label('Progress'), ipywidgets.Label('Status') ]) boxes = [header_box] job_status_list = Job.get_all().get_as_dict_list() progress_bars = [] status_labels = [] for job_status_dict in job_status_list: progress = ipywidgets.FloatProgress(value=job_status_dict["progress"], min=0.0, max=1.0) status_label = ipywidgets.Label(str(job_status_dict["status"])) box = ipywidgets.HBox([ ipywidgets.Label(str(job_status_dict["id"])), ipywidgets.Label(str(job_status_dict["duration"])), progress, status_label ]) progress_bars.append(progress) status_labels.append(status_label) boxes.append(box) def monitor(boxes, progress_bars, status_labels): while True: job_status_list = Job.get_all().get_as_dict_list() num_progress_bars = len(progress_bars) for index, job_status_dict in enumerate(job_status_list): if index < num_progress_bars: if status_labels[index].value == "new": if job_status_dict["status"] == "new": continue progress_bars[index].value = job_status_dict[ "progress"] status_labels[index].value = job_status_dict["status"] elif status_labels[ index].value == "cancelled" and job_status_dict[ "status"] != "cancelled": progress_bars[index].value = job_status_dict[ "progress"] status_labels[index].value = "cancelled" elif status_labels[ index].value == "success" and job_status_dict[ "status"] != "success": progress_bars[index].value = job_status_dict[ "progress"] status_labels[index].value = "success" elif status_labels[index].value == "running": progress_bars[index].value = job_status_dict[ "progress"] status_labels[index].value = job_status_dict["status"] else: progress = ipywidgets.FloatProgress( value=job_status_dict["progress"], min=0.0, max=1.0) status_label = ipywidgets.Label( str(job_status_dict["status"])) box = ipywidgets.HBox([ ipywidgets.Label(str(job_status_dict["id"])), ipywidgets.Label(str(job_status_dict["duration"])), progress, status_label ]) progress_bars.append(progress) status_labels.append(status_label) boxes.append(box) time.sleep(0.5) job_monitor = ipywidgets.VBox(boxes) monitor_thread = threading.Thread(target=monitor, args=(boxes, progress_bars, status_labels)) display(job_monitor) monitor_thread.start()
def bag_player(bagfile=''): """ Create a form widget for playing ROS bags. This function takes the bag file path, extracts the bag summary and play the bag with the given arguments. @param bagfile The ROS bag file path @return jupyter widget for display """ widget_list = [] bag_player.sp = None ###### Fields ######################################################### bgpath_txt = widgets.Text() bgpath_box = widgets.HBox([widgets.Label("Bag file path:"), bgpath_txt]) bgpath_txt.value = bagfile play_btn = widgets.Button(description="Play", icon='play') pause_btn = widgets.Button(description="Pause", icon='pause', disabled=True) step_btn = widgets.Button(description="Step", icon='step-forward', disabled=True) ibox = widgets.Checkbox(description="Immediate") lbox = widgets.Checkbox(description="Loop") clockbox = widgets.Checkbox(description="Clock") dzbox = widgets.Checkbox(description="Duration") kabox = widgets.Checkbox(description="Keep alive") start_float = widgets.FloatText(value=0) start_box = widgets.HBox([widgets.Label("Start time:"), start_float]) que_int = widgets.IntText(value=100) que_box = widgets.HBox([widgets.Label("Queue size:"), que_int]) factor_float = widgets.FloatText(value=1) factor_box = widgets.HBox([widgets.Label("Multiply the publish rate by:"), factor_float]) delay_float = widgets.FloatText(value=0) delay_box = widgets.HBox([widgets.Label("Delay after every advertise call:"), delay_float]) duration_float = widgets.FloatText(value=0) duration_box = widgets.HBox([dzbox, widgets.Label("Duration in secs:"), duration_float]) out_box = widgets.Output(layout={'border': '1px solid black'}) ######## Play Button ################################################## def ply_clk(arg): if play_btn.description == "Play": info_dict = yaml.load(subprocess.Popen(['rosbag', 'info', '--yaml', bgpath_txt.value], stdout=subprocess.PIPE).communicate()[0]) if info_dict is None: raise FileNotFoundError("Bag file not found!") else: cmd = ['rosbag', 'play', bgpath_txt.value] if ibox.value: cmd.append('-i') if lbox.value: cmd.append('-l') if kabox.value: cmd.append('-k') if clockbox.value: cmd.append('--clock') if dzbox.value: cmd.append("--duration={}".format(max(0, duration_float.value))) cmd.append("--rate={}".format(max(0, factor_float.value))) cmd.append("--start={}".format(max(0, start_float.value))) cmd.append("--queue={}".format(max(0, que_int.value))) cmd.append("--delay={}".format(max(0, delay_float.value))) play_btn.description = "Stop" play_btn.icon = 'stop' pause_btn.disabled = False bag_player.sp = subprocess.Popen(cmd, stdin=subprocess.PIPE) with out_box: print("Bag summary:") for key, val in info_dict.items(): print(key, ":", val) else: try: os.killpg(os.getpgid(bag_player.sp.pid), subprocess.signal.SIGINT) except KeyboardInterrupt: pass play_btn.description = "Play" play_btn.icon = 'play' pause_btn.disabled = True pause_btn.description = 'Pause' pause_btn.icon = 'pause' step_btn.disabled = True play_btn.on_click(ply_clk) ###################### Pause Button ######################### def pause_clk(arg): bag_player.sp.stdin.write(b' \n') bag_player.sp.stdin.flush() if pause_btn.description == 'Pause': pause_btn.description = 'Continue' pause_btn.icon = 'play' step_btn.disabled = False else: pause_btn.description = 'Pause' pause_btn.icon = 'pause' step_btn.disabled = True pause_btn.on_click(pause_clk) ################## step Button ############################### def step_clk(arg): bag_player.sp.stdin.write(b's\n') bag_player.sp.stdin.flush() step_btn.on_click(step_clk) options_hbox = widgets.HBox([ibox, lbox, clockbox, kabox]) buttons_hbox = widgets.HBox([play_btn, pause_btn, step_btn]) btm_box = widgets.VBox([bgpath_box, options_hbox, duration_box, start_box, que_box, factor_box, delay_box, buttons_hbox, out_box]) widget_list.append(btm_box) vbox = widgets.VBox(children=widget_list) return vbox
def labeled(widget): if widget.description is None or widget.description == '': return widget label = widget.description widget.style.description_width = '0' return widgets.VBox([widgets.Label(value=label), widget])
value=[16, 80], min=16, max=80, step=1, description='Age Range:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d', ) actual_data_widget = widgets.Checkbox(value=True, description='Actual LFPR', disabled=False, style={'description_width': 'initial'}) forecast_label = widgets.Label('Include Forecast with Kernel:') forecast_widget = widgets.Dropdown( options=OrderedDict( sorted({ 'None': 0, '1 - Krueger': 1, '2 - Local Trends': 2, '3 - Cohort Trends': 3, '4 - Local Trends + Cohort': 4, '5 - Age/Gender/Cohort FE': 5, '6 - Local Trends + UR': 6, '7 - Local Trends + UR & Lags': 7 }.items())), value=0, description='', disabled=False,
) # border='2px solid black', #titles = ['About', 'Config Basics', 'Microenvironment', 'User Params', 'Out: Cell Plots', 'Out: Substrate Plots'] titles = [ 'About', 'Config Basics', 'Microenvironment', 'User Params', 'Out: Plots' ] #tabs = widgets.Tab(children=[about_tab.tab, config_tab.tab, microenv_tab.tab, user_tab.tab, svg.tab, sub.tab], tabs = widgets.Tab(children=[ about_tab.tab, config_tab.tab, microenv_tab.tab, user_tab.tab, sub.tab ], _titles={i: t for i, t in enumerate(titles)}, layout=tab_layout) homedir = os.getcwd() tool_title = widgets.Label(r'\(\textbf{liver2gui}\)') if nanoHUB_flag or hublib_flag: # define this, but don't use (yet) remote_cb = widgets.Checkbox( indent=False, value=False, description='Submit as Batch Job to Clusters/Grid') top_row = widgets.HBox(children=[read_config, tool_title]) gui = widgets.VBox(children=[top_row, tabs, run_button.w]) fill_gui_params(read_config.options['DEFAULT']) else: top_row = widgets.HBox(children=[tool_title]) gui = widgets.VBox(children=[top_row, tabs, run_button]) fill_gui_params("data/PhysiCell_settings.xml")
def tool_template(m): widget_width = "250px" padding = "0px 0px 0px 5px" # upper, right, bottom, left toolbar_button = widgets.ToggleButton( value=False, tooltip="Toolbar", icon="gear", layout=widgets.Layout(width="28px", height="28px", padding="0px 0px 0px 4px"), ) close_button = widgets.ToggleButton( value=False, tooltip="Close the tool", icon="times", button_style="primary", layout=widgets.Layout(height="28px", width="28px", padding="0px 0px 0px 4px"), ) checkbox = widgets.Checkbox( description="Checkbox", indent=False, layout=widgets.Layout(padding=padding, width=widget_width), ) dropdown = widgets.Dropdown( options=["Option 1", "Option 2", "Option 3"], value=None, description="Dropdown:", layout=widgets.Layout(width=widget_width, padding=padding), style={"description_width": "initial"}, ) int_slider = widgets.IntSlider( min=1, max=100, description="Int Slider: ", readout=False, continuous_update=True, layout=widgets.Layout(width="220px", padding=padding), style={"description_width": "initial"}, ) int_slider_label = widgets.Label() widgets.jslink((int_slider, "value"), (int_slider_label, "value")) float_slider = widgets.FloatSlider( min=1, max=100, description="Float Slider: ", readout=False, continuous_update=True, layout=widgets.Layout(width="220px", padding=padding), style={"description_width": "initial"}, ) float_slider_label = widgets.Label() widgets.jslink((float_slider, "value"), (float_slider_label, "value")) color = widgets.ColorPicker( concise=False, description="Color:", value="white", style={"description_width": "initial"}, layout=widgets.Layout(width=widget_width, padding=padding), ) text = widgets.Text( value="", description="Textbox:", placeholder="Placeholder", style={"description_width": "initial"}, layout=widgets.Layout(width=widget_width, padding=padding), ) textarea = widgets.Textarea( placeholder="Placeholder", layout=widgets.Layout(width=widget_width), ) buttons = widgets.ToggleButtons( value=None, options=["Apply", "Reset", "Close"], tooltips=["Apply", "Reset", "Close"], button_style="primary", ) buttons.style.button_width = "80px" output = widgets.Output( layout=widgets.Layout(width=widget_width, padding=padding)) toolbar_widget = widgets.VBox() toolbar_widget.children = [toolbar_button] toolbar_header = widgets.HBox() toolbar_header.children = [close_button, toolbar_button] toolbar_footer = widgets.VBox() toolbar_footer.children = [ checkbox, widgets.HBox([int_slider, int_slider_label]), widgets.HBox([float_slider, float_slider_label]), dropdown, text, color, textarea, buttons, output, ] toolbar_event = ipyevents.Event( source=toolbar_widget, watched_events=["mouseenter", "mouseleave"]) def handle_toolbar_event(event): if event["type"] == "mouseenter": toolbar_widget.children = [toolbar_header, toolbar_footer] elif event["type"] == "mouseleave": if not toolbar_button.value: toolbar_widget.children = [toolbar_button] toolbar_button.value = False close_button.value = False toolbar_event.on_dom_event(handle_toolbar_event) def toolbar_btn_click(change): if change["new"]: close_button.value = False toolbar_widget.children = [toolbar_header, toolbar_footer] else: if not close_button.value: toolbar_widget.children = [toolbar_button] toolbar_button.observe(toolbar_btn_click, "value") def close_btn_click(change): if change["new"]: toolbar_button.value = False if m.tool_control is not None and m.tool_control in m.controls: m.remove_control(m.tool_control) m.tool_control = None toolbar_widget.close() close_button.observe(close_btn_click, "value") def button_clicked(change): if change["new"] == "Apply": with output: output.clear_output() print("Running ...") elif change["new"] == "Reset": textarea.value = "" output.clear_output() elif change["new"] == "Close": m.toolbar_reset() if m.tool_control is not None and m.tool_control in m.controls: m.remove_control(m.tool_control) m.tool_control = None toolbar_widget.close() buttons.value = None buttons.observe(button_clicked, "value") toolbar_control = WidgetControl(widget=toolbar_widget, position="topright") if toolbar_control not in m.controls: m.add_control(toolbar_control) m.tool_control = toolbar_control toolbar_button.value = True
)] for i in range(3): m += [widgets.FloatSlider(value=0.2, min=0., max=1., step=0.01, disabled=False, continuous_update=False, description='M' + str(i + 10), orientation='vertical', readout=True, readout_format='f', slider_color='white' )] params_box = [] params_box += [widgets.Label(value='$$\Delta t$$', layout=Layout(width='3%'))] params_box += [widgets.FloatSlider(value = default_params['D_t'], min=0.01, max = 1, step = 0.01, orientation='horizontal',layout=Layout(width='20%'))] params_box += [widgets.Label(value='$$\omega _0$$', layout=Layout(width='3%'))] params_box += [widgets.FloatSlider(value=default_params['w0'], min=0.5, max = 30, step = 0.5, orientation='horizontal',layout=Layout(width='20%'))] params_box += [widgets.Label(value='$$\zeta $$', layout=Layout(width='3%'))] params_box += [widgets.FloatSlider(value=default_params['damping_factor'], min=0.5, max = 2, step = 0.02, orientation='horizontal',layout=Layout(width='20%'))]
def minicomposer(nqubits=5, bloch=False, dirac=False, qsphere=False): out = widgets.Output single_gates = ['I', 'X', 'Y', 'Z', 'H', 'T', 'Tdg', 'S', 'Sdg'] multi_gates = ['CX', 'CZ', 'SWAP'] qc = QuantumCircuit(nqubits) if bloch or dirac or qsphere: backend = Aer.get_backend('statevector_simulator') class CircuitWidget: def __init__(self): self.waiting_for = 'gate' self.current_gate = '' self.qubits = [''] self.code = "" self.statevec = [] widget_state = CircuitWidget() cell_pretext = """def create_circuit():\n qc = QuantumCircuit({})\n""".format( nqubits) cell_ending = " return qc" def on_sqg_click(btn): """On single-qubit-gate button click""" if widget_state.waiting_for == 'gate': widget_state.waiting_for = 'sqg_qubit' update_output() widget_state.current_gate = btn.description def on_mqg_click(btn): """On multi-qubit-gate button click""" if widget_state.waiting_for == 'gate': widget_state.waiting_for = 'mqg_qubit_0' update_output() widget_state.current_gate = btn.description def on_qubit_click(btn): """On qubit button click""" if widget_state.waiting_for == 'sqg_qubit': widget_state.qubits[0] = int(btn.description) apply_gate() widget_state.waiting_for = 'gate' update_output() elif widget_state.waiting_for == 'mqg_qubit_0': widget_state.qubits[0] = int(btn.description) widget_state.waiting_for = 'mqg_qubit_1' update_output() elif widget_state.waiting_for == 'mqg_qubit_1': widget_state.qubits.append(int(btn.description)) widget_state.waiting_for = 'gate' apply_gate() update_output() def on_clear_click(btn): """On Clear button click""" widget_state.current_gate = 'Clear' widget_state.waiting_for = 'gate' apply_gate() update_output() def apply_gate(): """Uses widget_state to apply the last selected gate, update the code cell and prepare widget_state for the next selection""" functionmap = { 'I': 'qc.iden', 'X': 'qc.x', 'Y': 'qc.y', 'Z': 'qc.z', 'H': 'qc.h', 'S': 'qc.s', 'T': 'qc.t', 'Sdg': 'qc.sdg', 'Tdg': 'qc.tdg', 'CX': 'qc.cx', 'CZ': 'qc.cz', 'SWAP': 'qc.swap' } gate = widget_state.current_gate qubits = widget_state.qubits widget_state.code += " " if len(qubits) == 2: widget_state.code += functionmap[gate] widget_state.code += "({0}, {1})\n".format(qubits[0], qubits[1]) widget_state.qubits.pop() elif widget_state.current_gate == 'Clear': widget_state.code = "" else: widget_state.code += functionmap[gate] + "({})\n".format(qubits[0]) qc = QuantumCircuit(nqubits) # This is especially awful I know, please don't judge me exec(widget_state.code.replace(" ", "")) qc.draw('mpl').savefig('circuit_widget_temp.svg', format='svg') if bloch or dirac or qsphere: ket = execute(qc, backend).result().get_statevector() if bloch: plot_bloch_multivector(ket, show_state_labels=True).savefig( 'circuit_widget_temp_bs.svg', format='svg') if qsphere: plot_state_qsphere(ket, show_state_labels=True).savefig( 'circuit_widget_temp_qs.svg', format='svg') if dirac: widget_state.statevec = ket # Create buttons for single qubit gates sqg_btns = [widgets.Button(description=gate) for gate in single_gates] # Link these to the on_sqg_click function for button in sqg_btns: button.on_click(on_sqg_click) # Create buttons for qubits qubit_btns = [ widgets.Button(description=str(qubit)) for qubit in range(nqubits) ] # Register these too for button in qubit_btns: button.on_click(on_qubit_click) # Create & register buttons for multi-qubit gates, clear mqg_btns = [widgets.Button(description=gate) for gate in multi_gates] for button in mqg_btns: button.on_click(on_mqg_click) clear_btn = widgets.Button(description="Clear") clear_btn.on_click(on_clear_click) instruction = widgets.Label(value="Select a gate to add to the circuit:") qc.draw('mpl').savefig('circuit_widget_temp.svg', format='svg') if bloch or dirac or qsphere: ket = execute(qc, backend).result().get_statevector() if bloch: plot_bloch_multivector(ket).savefig('circuit_widget_temp_bs.svg', format='svg') with open('circuit_widget_temp_bs.svg', 'r') as img: bloch_sphere = widgets.HTML(value=img.read()) if qsphere: plot_state_qsphere(ket).savefig('circuit_widget_temp_qs.svg', format='svg') with open('circuit_widget_temp_qs.svg', 'r') as img: qsphere = widgets.HTML(value=img.read()) if dirac: widget_state.statevec = ket latex_statevec = widgets.HTMLMath(vec_in_text_braket(ket)) qiskit_code = widgets.HTML(value='') with open('circuit_widget_temp.svg', 'r') as img: drawing = widgets.HTML(value=img.read()) def display_widget(): sqg_box = widgets.HBox(sqg_btns) mqg_box = widgets.HBox(mqg_btns + [clear_btn]) qubit_box = widgets.HBox(qubit_btns) main_box = widgets.VBox([sqg_box, mqg_box, qubit_box]) visuals = [drawing] if bloch: visuals.append(bloch_sphere) if qsphere: visuals.append(qsphere) if dirac: visuals.append(latex_statevec) vis_box = widgets.VBox(visuals) display(instruction, main_box, vis_box) display(qiskit_code) def update_output(): """Changes the availability of buttons depending on the state of widget_state.waiting_for, updates displayed image""" if widget_state.waiting_for == 'gate': for button in sqg_btns: button.disabled = False for button in mqg_btns: if nqubits > 1: button.disabled = False else: button.disabled = True for button in qubit_btns: button.disabled = True instruction.value = "Select a gate to add to the circuit:" else: for button in sqg_btns: button.disabled = True for button in mqg_btns: button.disabled = True for button in qubit_btns: button.disabled = False if widget_state.waiting_for == 'sqg_qubit': instruction.value = "Select a qubit to perform the gate on:" elif widget_state.waiting_for == 'mqg_qubit_0': instruction.value = "Select the control qubit:" elif widget_state.waiting_for == 'mqg_qubit_1': instruction.value = "Select the target qubit:" qubit_btns[widget_state.qubits[0]].disabled = True with open('circuit_widget_temp.svg', 'r') as img: drawing.value = img.read() if bloch: with open('circuit_widget_temp_bs.svg', 'r') as img: bloch_sphere.value = img.read() if qsphere: with open('circuit_widget_temp_qs.svg', 'r') as img: qsphere.value = img.read() if dirac: latex_statevec.value = vec_in_text_braket(widget_state.statevec) complete_code = cell_pretext + widget_state.code + cell_ending qiskit_code.value = f""" <div class="output_html" style="line-height: 1.21429em; font-size: 14px"> {Code(complete_code, language='python')._repr_html_()} </div> """ display_widget() update_output()
def __init__(self, backend, dataset, x, y=None, z=None, w=None, grid=None, limits=None, shape=128, what="count(*)", f=None, vshape=16, selection=None, grid_limits=None, normalize=None, colormap="afmhot", figure_key=None, fig=None, what_kwargs={}, grid_before=None, vcount_limits=None, show_drawer=False, controls_selection=True, **kwargs): super(PlotBase, self).__init__(x=x, y=y, z=z, w=w, what=what, vcount_limits=vcount_limits, grid_limits=grid_limits, f=f, **kwargs) self.backend = backend self.vgrids = [None, None, None] self.vcount = None self.dataset = dataset self.limits = self.get_limits(limits) self.shape = shape self.selection = selection #self.grid_limits = grid_limits self.grid_limits_visible = None self.normalize = normalize self.colormap = colormap self.what_kwargs = what_kwargs self.grid_before = grid_before self.figure_key = figure_key self.fig = fig self.vshape = vshape self._new_progressbar() self.output = widgets.Output() def output_changed(*ignore): self.widget.new_output = True self.output.observe(output_changed, 'outputs') # with self.output: if 1: self._cleanups = [] self.progress = widgets.FloatProgress(value=0.0, min=0.0, max=1.0, step=0.01) self.progress.layout.width = "95%" self.progress.layout.max_width = '500px' self.progress.description = "progress" self.control_widget = v.Layout(pa_1=True, column=True, children=[]) self.backend.create_widget(self.output, self, self.dataset, self.limits) # self.create_tools() # self.widget = widgets.VBox([widgets.HBox([self.backend.widget, self.control_widget]), self.progress, self.output]) self.widget = PlotTemplate(components={ 'main-widget': widgets.VBox([self.backend.widget, self.progress, self.output]), 'control-widget': self.control_widget, 'output-widget': self.output }, model=show_drawer) if grid is None: self.update_grid() else: self.grid = grid self.widget_f = v.Select( items=['identity', 'log', 'log10', 'log1p', 'log1p'], v_model='log', label='Transform') widgets.link((self, 'f'), (self.widget_f, 'v_model')) self.observe(lambda *__: self.update_image(), 'f') self.add_control_widget(self.widget_f) self.widget_grid_limits_min = widgets.FloatSlider( value=0, min=0, max=100, step=0.1, description='vmin%') self.widget_grid_limits_max = widgets.FloatSlider( value=100, min=0, max=100, step=0.1, description='vmax%') widgets.link((self.widget_grid_limits_min, 'value'), (self, 'grid_limits_min')) widgets.link((self.widget_grid_limits_max, 'value'), (self, 'grid_limits_max')) #widgets.link((self.widget_grid_limits_min, 'f'), (self.widget_f, 'value')) self.observe(lambda *__: self.update_image(), ['grid_limits_min', 'grid_limits_max']) self.add_control_widget(self.widget_grid_limits_min) self.add_control_widget(self.widget_grid_limits_max) self.widget_grid_limits = None selections = _ensure_list(self.selection) selections = [_translate_selection(k) for k in selections] selections = [k for k in selections if k] self.widget_selection_active = widgets.ToggleButtons( options=list(zip(selections, selections)), description='selection') self.controls_selection = controls_selection modes = ['replace', 'and', 'or', 'xor', 'subtract'] self.widget_selection_mode = widgets.ToggleButtons(options=modes, description='mode') if self.controls_selection: self.add_control_widget(self.widget_selection_active) self.add_control_widget(self.widget_selection_mode) self.widget_selection_undo = widgets.Button(options=modes, description='undo', icon='arrow-left') self.widget_selection_redo = widgets.Button(options=modes, description='redo', icon='arrow-right') self.add_control_widget( widgets.HBox([ widgets.Label('history', layout={'width': '80px'}), self.widget_selection_undo, self.widget_selection_redo ])) def redo(*ignore): selection = _translate_selection( self.widget_selection_active.value) self.dataset.selection_redo(name=selection) check_undo_redo() self.widget_selection_redo.on_click(redo) def undo(*ignore): selection = _translate_selection( self.widget_selection_active.value) self.dataset.selection_undo(name=selection) check_undo_redo() self.widget_selection_undo.on_click(undo) def check_undo_redo(*ignore): selection = _translate_selection( self.widget_selection_active.value) self.widget_selection_undo.disabled = not self.dataset.selection_can_undo( selection) self.widget_selection_redo.disabled = not self.dataset.selection_can_redo( selection) self.widget_selection_active.observe(check_undo_redo, 'value') check_undo_redo() callback = self.dataset.signal_selection_changed.connect( check_undo_redo) callback = self.dataset.signal_selection_changed.connect( lambda *x: self.update_grid()) def _on_limits_change(*args): self._progressbar.cancel() self.update_grid() self.backend.observe(_on_limits_change, "limits") for attrname in "x y z vx vy vz".split(): def _on_change(change, attrname=attrname): limits_index = {'x': 0, 'y': 1, 'z': 2}.get(attrname) if limits_index is not None: self.backend.limits[limits_index] = None self.update_grid() self.observe(_on_change, attrname) self.observe(lambda *args: self.update_grid(), "what") self.observe(lambda *args: self.update_image(), "vcount_limits")
else: titles = [ 'About', 'Config Basics', 'Microenvironment', 'User Params', 'Out: Plots', 'Animate' ] tabs = widgets.Tab(children=[ about_tab.tab, config_tab.tab, microenv_tab.tab, user_tab.tab, sub.tab, animate_tab.tab ], _titles={i: t for i, t in enumerate(titles)}, layout=tab_layout) homedir = os.getcwd() tool_title = widgets.Label(r'\(\textbf{pc4cancerimmune3D}\)') if nanoHUB_flag or hublib_flag: # define this, but don't use (yet) remote_cb = widgets.Checkbox( indent=False, value=False, description='Submit as Batch Job to Clusters/Grid') top_row = widgets.HBox(children=[read_config, tool_title]) gui = widgets.VBox(children=[top_row, tabs, run_button.w]) fill_gui_params(read_config.options['DEFAULT']) else: top_row = widgets.HBox(children=[tool_title]) gui = widgets.VBox(children=[top_row, tabs, run_button]) fill_gui_params("data/PhysiCell_settings.xml")