def interact(self, fig=None, axes=None, constraints=None, free_vars=None, caching=True, **kwargs): """ Display an interactive plot where all free variables can be manipulated, with the plot updating accordingly. The rest of the variables is considered as dependent. :param fig: matplotlib figure to update, can be omitted if axes should be created automatically :param axes: matplotlib axes to draw on, can be omitted if axes should be created automatically :param constraints: optional sympy (nx1)-matrix of eqns which should be fullfilled (will be "solved" via fmin) :param free_vars: optional sympy (rx1)-matrix of symbols which are treated as independent for the constraints :param caching: True (default) or False. Determines whether fmin results are cached in a dictionary :param kwargs: ipywidgets specifications using the SymPy symbol string representations as keys there are different syntax possibilities: vis_object.interact(x=(xmin, xmax)) vis_object.interact(x=(xmin, xmax, step)) vis_object.interact(x=(xmin, xmax, step, inistial_value)) """ assert in_ipython_context, "Interactive mode only works in an IPython notebook" \ "(maybe you need to install `ipywidgets`, see visualization_requirements.txt)" widget_dict = dict() if constraints is not None: assert isinstance(constraints, sp.MatrixBase) solve_constraints = True if free_vars is None: free_vars = [] # allow for scalar free var (convenience) if isinstance(free_vars, sp.Basic): free_vars = [free_vars] # distinguish between free and dependent variables var_list = list(self.variables) free_var_indices = [var_list.index(v) for v in free_vars] dependent_var_indices = [var_list.index(v) for v in self.variables if v not in free_vars] # dependent_vars = [v for v in self.variables if v not in free_vars] n_vars = len(self.variables) # expression which will be minimized min_expr = constraints.T*constraints assert min_expr.shape == (1, 1) constraint_norm_func = expr_to_func(self.variables, min_expr[0]) all_vars = np.zeros((n_vars,)) def min_target_func(dep_var_vals, free_var_vals): """ Target function for minimization, second argument is considered as a parameter """ all_vars[dependent_var_indices] = dep_var_vals all_vars[free_var_indices] = free_var_vals return constraint_norm_func(*all_vars) cbox = Checkbox(value=False, description='solve constraints (fmin)', icon='check', tooltip='solve constraints numerically via fmin') widget_dict["chk_solve_constraints"] = cbox else: solve_constraints = False for var in self.variables: var_str = repr(var) widget_dict[var_str] = self.make_slider_from_kwarg(var_str, kwargs) if fig is None or axes is None: fig, axes = self.create_default_axes() plt.close() is_initialized = False last_cbox_value = False fmin_cache = {} # last result for the dependet vars last_fmin_result = None # noinspection PyShadowingNames def interact_fun(**kwargs): nonlocal is_initialized nonlocal last_cbox_value nonlocal last_fmin_result widget_var_values = np.array([kwargs[repr(var_symbol)] for var_symbol in self.variables]) cbox_solve_constraints = kwargs.get("chk_solve_constraints", False) print("widget_var_values:", widget_var_values, "cbox:", cbox_solve_constraints) if solve_constraints and cbox_solve_constraints: free_var_values = [kwargs[repr(var_symbol)] for var_symbol in free_vars] # initialize the dep_var_values form widgets if we have no result yet or if the checkbox was unchecked if last_fmin_result is None: dep_var_values = widget_var_values[dependent_var_indices] x0_dep_vars = dep_var_values else: x0_dep_vars = last_fmin_result # dict lookup with the arguments of min_target # does not work because we never come to see this key again # key_tuple = (tuple(np.round(x0_dep_vars, decimals=5)), tuple(free_var_values)) key_tuple = tuple(free_var_values) cache_content = fmin_cache.get(key_tuple) print("cache:", key_tuple, cache_content) if caching and cache_content is not None: dep_var_values_result = cache_content else: print("calling fmin with x0=", x0_dep_vars, "args=", free_var_values) res = fmin(min_target_func, x0=x0_dep_vars, args=(free_var_values,), full_output=True) dep_var_values_result, fopt, n_it, fcalls, warnflag = res # fill the cache if we had these arguments for the first time (and no error occurred) if caching and warnflag == 0: fmin_cache[key_tuple] = dep_var_values_result last_fmin_result = dep_var_values_result all_vars[free_var_indices] = free_var_values all_vars[dependent_var_indices] = dep_var_values_result variables_values = all_vars * 1.0 # print all coordinates, convert to list for easy copy-pasting (commas) print("all coordinates:", list(variables_values)) else: # just use the values from the widgets variables_values = widget_var_values # reset the cache if checkbox is deactivated fmin_cache.clear() last_fmin_result = None if not is_initialized: self.plot_init(variables_values, axes) is_initialized = True last_cbox_value = cbox_solve_constraints self.plot_update(variables_values, axes) ip_display(fig) # TODO: Maybe return the control elements or something, so that they can be customized interact(interact_fun, **widget_dict)
def __perform_action(self): # generates statistic saved in json file # print(self.objects[self.current_class]) # if not self.objects[self.current_class][self.current_pos]['path'] in self.mapping["images"].keys(): # image = {} # image["path"] = self.objects[self.current_class][self.current_pos] # image["id"] = len(self.mapping["images"]) + 1 # image["categories"] = [] # self.dataset["images"].append(image) # self.mapping["images"][image["path"]] = len(self.dataset["images"]) - 1 # current_index = self.mapping["images"][self.objects[self.current_class][self.current_pos]] self.next_button.disabled = (self.current_pos == self.max_pos) self.previous_button.disabled = (self.current_pos == 0) current_class_id = self.objects[self.current_pos]['class_id'] current_gt_id = self.objects[self.current_pos]['gt_id'] # start to check for each type of metric if 'occ' in self.radiobuttons.keys(): cb = self.radiobuttons['occ'] rb_options = self.radiobuttons['occ'].options cb.unobserve(self.__checkbox_changed) cb.value = None #clear the current value if self.dataset_voc.annotations_gt['gt'][current_class_id]['details'][ current_gt_id]: # check if it is empty occ_level = self.dataset_voc.annotations_gt['gt'][current_class_id]['details'][current_gt_id][ 'occ_level'] cb.value = rb_options[occ_level - 1] cb.observe(self.__checkbox_changed) if 'truncated' in self.radiobuttons.keys(): #since this works for PASCAL VOC there's always a truncation value cb = self.radiobuttons['truncated'] rb_options = self.radiobuttons['truncated'].options cb.unobserve(self.__checkbox_changed) cb.value = rb_options[ int(self.dataset_voc.annotations_gt['gt'][current_class_id]['istrunc'][current_gt_id] == True)] cb.observe(self.__checkbox_changed) if 'views' in self.checkboxes.keys(): for cb_i, cb in enumerate(self.checkboxes['views']): cb.unobserve(self.__checkbox_changed) cb.value = False #clear the value if self.dataset_voc.annotations_gt['gt'][current_class_id]['details'][current_gt_id]: # check if it is empty cb.value = bool(self.dataset_voc.annotations_gt['gt'][current_class_id]['details'][current_gt_id][ 'side_visible'][cb.description]) cb.observe(self.__checkbox_changed) #need to create the output first for the buttons with self.dynamic_output_for_parts: self.dynamic_output_for_parts.clear_output() if self.objects[self.current_pos]['class_name'] in self.metrics_labels['parts']: self.cb_parts = [Checkbox(False, description='{}'.format(i), indent=False) for i in self.metrics_labels['parts'][self.objects[self.current_pos]['class_name']]] else: self.cb_parts = [HTML(value="No PARTS defined in Conf file")] display(VBox(children=[cb for cb in self.cb_parts])) with self.out: self.out.clear_output() image_record, obj_num = self.__get_image_record() self.image_display_function(image_record, obj_num) self.text_index.unobserve(self.__selected_index) self.text_index.value = self.current_pos + 1 self.text_index.observe(self.__selected_index)
def __init__(self): # tab_height = '520px' # tab_layout = Layout(width='900px', # border='2px solid black', # height=tab_height, overflow_y='scroll') self.output_dir = '.' constWidth = '180px' # self.fig = plt.figure(figsize=(6, 6)) # self.fig = plt.figure(figsize=(7, 7)) max_frames = 1 self.svg_plot = interactive(self.plot_svg, frame=(0, max_frames), continuous_update=False) # "plot_size" controls the size of the tab height, not the plot (rf. figsize for that) plot_size = '500px' # small: plot_size = '750px' # medium plot_size = '700px' # medium plot_size = '600px' # medium self.svg_plot.layout.width = plot_size self.svg_plot.layout.height = plot_size self.use_defaults = True self.show_nucleus = 1 # 0->False, 1->True in Checkbox! self.show_edge = 1 # 0->False, 1->True in Checkbox! self.show_tracks = 1 # 0->False, 1->True in Checkbox! self.trackd = { } # dictionary to hold cell IDs and their tracks: (x,y) pairs # self.scale_radius = 1.0 self.axes_min = 0.0 self.axes_max = 2000 # hmm, this can change (TODO?) self.max_frames = BoundedIntText( min=0, max=99999, value=max_frames, description='Max', layout=Layout(width='160px'), # layout=Layout(flex='1 1 auto', width='auto'), #Layout(width='160px'), ) self.max_frames.observe(self.update_max_frames) self.show_nucleus_checkbox = Checkbox( description='nucleus', value=True, disabled=False, layout=Layout(width=constWidth), # layout=Layout(flex='1 1 auto', width='auto'), #Layout(width='160px'), ) self.show_nucleus_checkbox.observe(self.show_nucleus_cb) self.show_edge_checkbox = Checkbox( description='edge', value=True, disabled=False, layout=Layout(width=constWidth), # layout=Layout(flex='1 1 auto', width='auto'), #Layout(width='160px'), ) self.show_edge_checkbox.observe(self.show_edge_cb) self.show_tracks_checkbox = Checkbox( description='tracks', value=True, disabled=False, layout=Layout(width=constWidth), # layout=Layout(flex='1 1 auto', width='auto'), #Layout(width='160px'), ) self.show_tracks_checkbox.observe(self.show_tracks_cb) # row1 = HBox([Label('(select slider: drag or left/right arrows)'), # self.max_frames, VBox([self.show_nucleus_checkbox, self.show_edge_checkbox])]) # self.max_frames, self.show_nucleus_checkbox], layout=Layout(width='500px')) # self.tab = VBox([row1,self.svg_plot], layout=tab_layout) items_auto = [ Label('select slider: drag or left/right arrows'), self.max_frames, self.show_nucleus_checkbox, self.show_edge_checkbox, self.show_tracks_checkbox, ] #row1 = HBox([Label('(select slider: drag or left/right arrows)'), # max_frames, show_nucleus_checkbox, show_edge_checkbox], # layout=Layout(width='800px')) box_layout = Layout(display='flex', flex_flow='row', align_items='stretch', width='70%') row1 = Box(children=items_auto, layout=box_layout) if (hublib_flag): self.download_button = Download( 'svg.zip', style='warning', icon='cloud-download', tooltip='You need to allow pop-ups in your browser', cb=self.download_cb) download_row = HBox([ self.download_button.w, Label("Download all cell plots (browser must allow pop-ups).") ]) # self.tab = VBox([row1, self.svg_plot, self.download_button.w], layout=tab_layout) # self.tab = VBox([row1, self.svg_plot, self.download_button.w]) self.tab = VBox([row1, self.svg_plot, download_row]) else: self.tab = VBox([row1, self.svg_plot])
def info(run_manager) -> None: """Display information about the `RunManager`. Returns an interactive ipywidget that can be visualized in a Jupyter notebook. """ from IPython.display import display from ipywidgets import HTML, Button, Layout, VBox status = HTML(value=_info_html(run_manager)) layout = Layout(width="200px") cancel_button = Button(description="cancel jobs", layout=layout, button_style="danger", icon="stop") cleanup_button = Button( description="cleanup log and batch files", layout=layout, button_style="danger", icon="remove", ) update_info_button = Button( description="update info", layout=layout, icon="refresh", ) update_info_button.style.button_color = "lightgreen" load_learners_button = Button( description="load learners", layout=layout, button_style="info", icon="download", ) show_logs_button = Button(description="show logs", layout=layout, button_style="info", icon="book") widgets = { "update info": update_info_button, "cancel": HBox([cancel_button], layout=layout), "cleanup": HBox([cleanup_button], layout=layout), "load learners": load_learners_button, "show logs": show_logs_button, } def switch_to(box, *buttons, _callable=None): def on_click(_): box.children = tuple(buttons) if _callable is not None: _callable() return on_click box = VBox([]) log_widget = None def update(_): status.value = _info_html(run_manager) def load_learners(_): run_manager.load_learners() def toggle_logs(_): nonlocal log_widget if log_widget is None: log_widget = log_explorer(run_manager) b = widgets["show logs"] if b.description == "show logs": b.description = "hide logs" box.children = (*box.children, log_widget) else: b.description = "show logs" box.children = box.children[:-1] def cancel(): run_manager.cancel() update(None) def cleanup(include_old_logs): def _callable(): run_manager.cleanup(include_old_logs.value) update(None) return _callable widgets["update info"].on_click(update) widgets["show logs"].on_click(toggle_logs) widgets["load learners"].on_click(load_learners) # Cancel button with confirm/deny option confirm_cancel_button = Button(description="Confirm", button_style="success", icon="check") deny_cancel_button = Button(description="Deny", button_style="danger", icon="close") cancel_button.on_click( switch_to(widgets["cancel"], confirm_cancel_button, deny_cancel_button)) deny_cancel_button.on_click(switch_to(widgets["cancel"], cancel_button)) confirm_cancel_button.on_click( switch_to(widgets["cancel"], cancel_button, _callable=cancel)) # Cleanup button with confirm/deny option include_old_logs = Checkbox( False, description=f"Remove {run_manager.move_old_logs_to}/ folder", indent=False, ) confirm_cleanup_button = Button(description="Confirm", button_style="success", icon="check") deny_cleanup_button = Button(description="Deny", button_style="danger", icon="close") cleanup_box = VBox([ HBox([confirm_cleanup_button, deny_cleanup_button]), include_old_logs ]) cleanup_button.on_click(switch_to(widgets["cleanup"], cleanup_box)) deny_cleanup_button.on_click(switch_to(widgets["cleanup"], cleanup_button)) confirm_cleanup_button.on_click( switch_to(widgets["cleanup"], cleanup_button, _callable=cleanup(include_old_logs))) box.children = (status, *tuple(widgets.values())) display(box)
def __init__(self, dataset, metrics_and_values, # properties{ name: ([possible values], just_one_value = True)} output_path=None, show_name=True, show_axis=False, fig_size=(10, 10), buttons_vertical=False, image_display_function=None, classes_to_annotate=None ): self.dataset_orig = dataset self.metrics_and_values = metrics_and_values self.show_axis = show_axis self.name = (self.dataset_orig.dataset_root_param.split('/')[-1]).split('.')[0] # get_original_file_name self.show_name = show_name if output_path is None: splitted_array = self.dataset_orig.dataset_root_param.split('/') n = len(splitted_array) self.output_directory = os.path.join(*(splitted_array[0:n - 1])) else: self.output_directory = output_path if classes_to_annotate is None: # if classes_to_annotate is None, all the classes would be annotated self.classes_to_annotate = self.dataset_orig.get_categories_names() # otherwise, the only the classes in the list self.file_path_for_json = os.path.join("/", self.output_directory, self.name + "_ANNOTATED.json") print("New dataset with meta_annotations {}".format(self.file_path_for_json)) self.mapping = None self.objects = self.dataset_orig.get_annotations_from_class_list(self.classes_to_annotate) self.max_pos = len(self.objects) - 1 self.current_pos = 0 self.mapping, self.dataset_annotated = self.__create_results_dict(self.file_path_for_json) self.fig_size = fig_size self.buttons_vertical = buttons_vertical if image_display_function is None: self.image_display_function = self.__show_image else: self.image_display_function = image_display_function # create buttons self.previous_button = self.__create_button("Previous", (self.current_pos == 0), self.__on_previous_clicked) self.next_button = self.__create_button("Next", (self.current_pos == self.max_pos), self.__on_next_clicked) self.save_button = self.__create_button("Download", False, self.__on_save_clicked) self.save_function = self.__save_function # save_function self.current_image = {} buttons = [self.previous_button, self.next_button] buttons.append(self.save_button) label_total = Label(value='/ {}'.format(len(self.objects))) self.text_index = BoundedIntText(value=1, min=1, max=len(self.objects)) self.text_index.layout.width = '80px' self.text_index.layout.height = '35px' self.text_index.observe(self.__selected_index) self.out = Output() self.out.add_class("my_canvas_class") self.checkboxes = {} self.radiobuttons = {} self.bounded_text = {} output_layout = [] for k_name, v in self.metrics_and_values.items(): if MetaPropertiesTypes.META_PROP_UNIQUE == v[1]: # radiobutton self.radiobuttons[k_name] = RadioButtons(name=k_name, options=v[0], disabled=False, indent=False) elif MetaPropertiesTypes.META_PROP_COMPOUND == v[1]: # checkbox self.checkboxes[k_name] = [Checkbox(False, description='{}'.format(prop_name), indent=False, name=k_name) for prop_name in v[0]] elif MetaPropertiesTypes.META_PROP_CONTINUE == v[1]: self.bounded_text[k_name] = BoundedFloatText(value=v[0][0], min=v[0][0], max=v[0][1]) self.check_radio_boxes_layout = {} for rb_k, rb_v in self.radiobuttons.items(): rb_v.layout.width = '180px' rb_v.observe(self.__checkbox_changed) rb_v.add_class(rb_k) html_title = HTML(value="<b>" + rb_k + "</b>") self.check_radio_boxes_layout[rb_k] = VBox([rb_v]) output_layout.append(VBox([html_title, self.check_radio_boxes_layout[rb_k]])) for cb_k, cb_i in self.checkboxes.items(): for cb in cb_i: cb.layout.width = '180px' cb.observe(self.__checkbox_changed) cb.add_class(cb_k) html_title = HTML(value="<b>" + cb_k + "</b>") self.check_radio_boxes_layout[cb_k] = VBox(children=[cb for cb in cb_i]) output_layout.append(VBox([html_title, self.check_radio_boxes_layout[cb_k]])) for bf_k, bf in self.bounded_text.items(): bf.layout.width = '80px' bf.layout.height = '35px' bf.observe(self.__checkbox_changed) bf.add_class(bf_k) html_title = HTML(value="<b>" + bf_k + "</b>") self.check_radio_boxes_layout[bf_k] = VBox([bf]) output_layout.append(VBox([html_title, self.check_radio_boxes_layout[bf_k]])) self.all_widgets = VBox(children= [HBox([self.text_index, label_total]), HBox(buttons), HBox([self.out, VBox(output_layout)])]) ## loading js library to perform html screenshots j_code = """ require.config({ paths: { html2canvas: "https://html2canvas.hertzen.com/dist/html2canvas.min" } }); """ display(Javascript(j_code))
def __init__(self): # micron_units = HTMLMath(value=r"$\mu M$") micron_units = Label( 'micron') # use "option m" (Mac, for micro symbol) # micron_units = Label('microns') # use "option m" (Mac, for micro symbol) constWidth = '180px' # tab_height = '400px' tab_height = '500px' # tab_layout = Layout(width='900px', # border='2px solid black', # tab_layout = Layout(width='850px', # border='2px solid black', # height=tab_height, overflow_y='scroll',) # np_tab_layout = Layout(width='800px', # border='2px solid black', # height='350px', overflow_y='scroll',) # my_domain = [0,0,-10, 2000,2000,10, 20,20,20] # [x,y,zmin, x,y,zmax, x,y,zdelta] # label_domain = Label('Domain ($\mu M$):') label_domain = Label('Domain (micron):') stepsize = 10 disable_domain = False self.xmin = FloatText( step=stepsize, # description='$X_{min}$', description='Xmin', disabled=disable_domain, layout=Layout(width=constWidth), ) self.ymin = FloatText( step=stepsize, description='Ymin', disabled=disable_domain, layout=Layout(width=constWidth), ) self.zmin = FloatText( step=stepsize, description='Zmin', disabled=disable_domain, layout=Layout(width=constWidth), ) self.xmax = FloatText( step=stepsize, description='Xmax', disabled=disable_domain, layout=Layout(width=constWidth), ) self.ymax = FloatText( step=stepsize, description='Ymax', disabled=disable_domain, layout=Layout(width=constWidth), ) self.zmax = FloatText( step=stepsize, description='Zmax', disabled=disable_domain, layout=Layout(width=constWidth), ) # description='$Time_{max}$', self.tmax = BoundedFloatText( min=0., max=100000000, step=stepsize, description='Max Time', layout=Layout(width=constWidth), ) self.xdelta = BoundedFloatText( min=1., description='dx', # '∆x', # Mac: opt-j for delta disabled=disable_domain, layout=Layout(width=constWidth), ) self.ydelta = BoundedFloatText( min=1., description='dy', disabled=True, layout=Layout(width=constWidth), ) self.zdelta = BoundedFloatText( min=1., description='dz', disabled=disable_domain, layout=Layout(width=constWidth), ) def xdelta_cb(b): self.ydelta.value = self.xdelta.value self.zdelta.value = 0.5 * (self.xdelta.value + self.ydelta.value) self.zmin.value = -0.5 * self.zdelta.value self.zmax.value = 0.5 * self.zdelta.value self.xdelta.observe(xdelta_cb) """ self.tdelta = BoundedFloatText( min=0.01, description='$Time_{delta}$', layout=Layout(width=constWidth), ) """ """ self.toggle2D = Checkbox( description='2-D', layout=Layout(width=constWidth), ) def toggle2D_cb(b): if (self.toggle2D.value): #zmin.disabled = zmax.disabled = zdelta.disabled = True zmin.disabled = True zmax.disabled = True zdelta.disabled = True else: zmin.disabled = False zmax.disabled = False zdelta.disabled = False self.toggle2D.observe(toggle2D_cb) """ x_row = HBox([self.xmin, self.xmax, self.xdelta]) y_row = HBox([self.ymin, self.ymax, self.ydelta]) z_row = HBox([self.zmin, self.zmax, self.zdelta]) self.omp_threads = BoundedIntText( min=1, max=4, description='# threads', layout=Layout(width=constWidth), ) # self.toggle_prng = Checkbox( # description='Seed PRNG', style={'description_width': 'initial'}, # e.g. 'initial' '120px' # layout=Layout(width=constWidth), # ) # self.prng_seed = BoundedIntText( # min = 1, # description='Seed', # disabled=True, # layout=Layout(width=constWidth), # ) # def toggle_prng_cb(b): # if (toggle_prng.value): # self.prng_seed.disabled = False # else: # self.prng_seed.disabled = True # self.toggle_prng.observe(toggle_prng_cb) #prng_row = HBox([toggle_prng, prng_seed]) self.toggle_svg = Checkbox( description='Cells', # SVG layout=Layout(width='150px')) # constWidth = '180px' # self.svg_t0 = BoundedFloatText ( # min=0, # description='$T_0$', # layout=Layout(width=constWidth), # ) self.svg_interval = BoundedIntText( min=1, max= 99999999, # TODO: set max on all Bounded to avoid unwanted default description='every', layout=Layout(width='160px'), ) self.mcds_interval = BoundedIntText( min=1, max=99999999, description='every', # disabled=True, layout=Layout(width='160px'), ) # don't let this be > mcds interval def svg_interval_cb(b): if (self.svg_interval.value > self.mcds_interval.value): self.svg_interval.value = self.mcds_interval.value self.svg_interval.observe( svg_interval_cb) # BEWARE: when fill_gui, this sets value = 1 ! # don't let this be < svg interval def mcds_interval_cb(b): if (self.mcds_interval.value < self.svg_interval.value): self.mcds_interval.value = self.svg_interval.value self.mcds_interval.observe( mcds_interval_cb) # BEWARE: see warning above def toggle_svg_cb(b): if (self.toggle_svg.value): # self.svg_t0.disabled = False self.svg_interval.disabled = False else: # self.svg_t0.disabled = True self.svg_interval.disabled = True self.toggle_svg.observe(toggle_svg_cb) self.toggle_mcds = Checkbox( # value=False, description='Subtrates', # Full layout=Layout(width='180px'), ) # self.mcds_t0 = FloatText( # description='$T_0$', # disabled=True, # layout=Layout(width=constWidth), # ) def toggle_mcds_cb(b): if (self.toggle_mcds.value): # self.mcds_t0.disabled = False #False self.mcds_interval.disabled = False else: # self.mcds_t0.disabled = True self.mcds_interval.disabled = True self.toggle_mcds.observe(toggle_mcds_cb) svg_mat_output_row = HBox([ Label('Plots:'), self.toggle_svg, HBox([self.svg_interval, Label('min')]), self.toggle_mcds, HBox([self.mcds_interval, Label('min')]) ]) # to sync, do this # svg_mat_output_row = HBox( [Label('Plots:'), self.svg_interval, Label('min')]) #write_config_row = HBox([write_config_button, write_config_file]) #run_sim_row = HBox([run_button, run_command_str, kill_button]) # run_sim_row = HBox([run_button, run_command_str]) # run_sim_row = HBox([run_button.w]) # need ".w" for the custom RunCommand widget label_blankline = Label('') # toggle_2D_seed_row = HBox([toggle_prng, prng_seed]) # toggle2D box_layout = Layout(border='1px solid') # domain_box = VBox([label_domain,x_row,y_row,z_row], layout=box_layout) domain_box = VBox([label_domain, x_row, y_row], layout=box_layout) self.tab = VBox([ domain_box, # label_blankline, HBox([self.tmax, Label('min')]), self.omp_threads, svg_mat_output_row, # HBox([self.substrate[3], self.diffusion_coef[3], self.decay_rate[3] ]), ]) # output_dir, toggle_2D_seed_
def __init__(self): self.output_dir = '.' # self.output_dir = 'tmpdir' # self.fig = plt.figure(figsize=(7.2,6)) # this strange figsize results in a ~square contour plot self.first_time = True self.modulo = 1 self.use_defaults = True self.svg_delta_t = 0 self.substrate_delta_t = 0 self.svg_frame = 1 self.substrate_frame = 1 self.svg_xmin = 0 # Probably don't want to hardwire these if we allow changing the domain size self.svg_xrange = 2000 self.xmin = -1000. self.xmax = 1000. self.ymin = -1000. self.ymax = 1000. self.x_range = 2000. self.y_range = 2000. self.show_nucleus = 0 self.show_edge = False # initial value self.field_index = 4 # self.field_index = self.mcds_field.value + 4 # define dummy size of mesh (set in the tool's primary module) self.numx = 0 self.numy = 0 self.title_str = '' tab_height = '600px' tab_height = '500px' constWidth = '180px' constWidth2 = '150px' tab_layout = Layout( width='900px', # border='2px solid black', height=tab_height, ) #overflow_y='scroll') max_frames = 1 # self.mcds_plot = interactive(self.plot_substrate, frame=(0, max_frames), continuous_update=False) # self.i_plot = interactive(self.plot_plots, frame=(0, max_frames), continuous_update=False) self.i_plot = interactive(self.plot_substrate, frame=(0, max_frames), continuous_update=False) # "plot_size" controls the size of the tab height, not the plot (rf. figsize for that) # NOTE: the Substrates Plot tab has an extra row of widgets at the top of it (cf. Cell Plots tab) svg_plot_size = '700px' svg_plot_size = '600px' svg_plot_size = '700px' svg_plot_size = '900px' self.i_plot.layout.width = svg_plot_size self.i_plot.layout.height = svg_plot_size self.fontsize = 20 self.max_frames = BoundedIntText( min=0, max=99999, value=max_frames, description='# cell frames', layout=Layout(width='160px'), ) self.max_frames.observe(self.update_max_frames) # self.field_min_max = {'dummy': [0., 1.]} # NOTE: manually setting these for now (vs. parsing them out of data/initial.xml) self.field_min_max = { 'director signal': [0., 1.], 'cargo signal': [0., 1.] } # hacky I know, but make a dict that's got (key,value) reversed from the dict in the Dropdown below # self.field_dict = {0:'dummy'} self.field_dict = {0: 'director signal', 1: 'cargo signal'} self.mcds_field = Dropdown( options={ 'director signal': 0, 'cargo signal': 1 }, value=0, # description='Field', layout=Layout(width=constWidth)) # print("substrate __init__: self.mcds_field.value=",self.mcds_field.value) # self.mcds_field.observe(self.mcds_field_cb) self.mcds_field.observe(self.mcds_field_changed_cb) # self.field_cmap = Text( # value='viridis', # description='Colormap', # disabled=True, # layout=Layout(width=constWidth), # ) self.field_cmap = Dropdown( options=['viridis', 'jet', 'YlOrRd'], value='YlOrRd', # description='Field', layout=Layout(width=constWidth)) # self.field_cmap.observe(self.plot_substrate) self.field_cmap.observe(self.mcds_field_cb) self.cmap_fixed = Checkbox( description='Fix', disabled=False, # layout=Layout(width=constWidth2), ) self.save_min_max = Button( description='Save', #style={'description_width': 'initial'}, button_style= 'success', # 'success', 'info', 'warning', 'danger' or '' tooltip='Save min/max for this substrate', disabled=True, layout=Layout(width='90px')) def save_min_max_cb(b): # field_name = self.mcds_field.options[] # field_name = next(key for key, value in self.mcds_field.options.items() if value == self.mcds_field.value) field_name = self.field_dict[self.mcds_field.value] # print(field_name) # self.field_min_max = {'oxygen': [0., 30.], 'glucose': [0., 1.], 'H+ ions': [0., 1.], 'ECM': [0., 1.], 'NP1': [0., 1.], 'NP2': [0., 1.]} self.field_min_max[field_name][0] = self.cmap_min.value self.field_min_max[field_name][1] = self.cmap_max.value # print(self.field_min_max) self.save_min_max.on_click(save_min_max_cb) self.cmap_min = FloatText( description='Min', value=0, step=0.1, disabled=True, layout=Layout(width=constWidth2), ) self.cmap_min.observe(self.mcds_field_cb) self.cmap_max = FloatText( description='Max', value=38, step=0.1, disabled=True, layout=Layout(width=constWidth2), ) self.cmap_max.observe(self.mcds_field_cb) def cmap_fixed_cb(b): if (self.cmap_fixed.value): self.cmap_min.disabled = False self.cmap_max.disabled = False self.save_min_max.disabled = False else: self.cmap_min.disabled = True self.cmap_max.disabled = True self.save_min_max.disabled = True # self.mcds_field_cb() self.cmap_fixed.observe(cmap_fixed_cb) field_cmap_row2 = HBox([self.field_cmap, self.cmap_fixed]) # field_cmap_row3 = HBox([self.save_min_max, self.cmap_min, self.cmap_max]) items_auto = [ self.save_min_max, #layout=Layout(flex='3 1 auto', width='auto'), self.cmap_min, self.cmap_max, ] box_layout = Layout(display='flex', flex_flow='row', align_items='stretch', width='80%') field_cmap_row3 = Box(children=items_auto, layout=box_layout) #--------------------- self.cell_edges_toggle = Checkbox( description='edges', disabled=False, value=False, # layout=Layout(width=constWidth2), ) def cell_edges_toggle_cb(b): # self.update() if (self.cell_edges_toggle.value): self.show_edge = True else: self.show_edge = False self.i_plot.update() self.cell_edges_toggle.observe(cell_edges_toggle_cb) self.cells_toggle = Checkbox( description='Cells', disabled=False, value=True, # layout=Layout(width=constWidth2), ) def cells_toggle_cb(b): # self.update() self.i_plot.update() if (self.cells_toggle.value): self.cell_edges_toggle.disabled = False else: self.cell_edges_toggle.disabled = True self.cells_toggle.observe(cells_toggle_cb) #--------------------- self.substrates_toggle = Checkbox( description='Substrates', disabled=False, value=True, # layout=Layout(width=constWidth2), ) def substrates_toggle_cb(b): if (self.substrates_toggle.value): # seems bass-ackwards self.cmap_fixed.disabled = False self.cmap_min.disabled = False self.cmap_max.disabled = False self.mcds_field.disabled = False self.field_cmap.disabled = False else: self.cmap_fixed.disabled = True self.cmap_min.disabled = True self.cmap_max.disabled = True self.mcds_field.disabled = True self.field_cmap.disabled = True self.substrates_toggle.observe(substrates_toggle_cb) self.grid_toggle = Checkbox( description='grid', disabled=False, value=True, # layout=Layout(width=constWidth2), ) def grid_toggle_cb(b): # self.update() self.i_plot.update() self.grid_toggle.observe(grid_toggle_cb) # field_cmap_row3 = Box([self.save_min_max, self.cmap_min, self.cmap_max]) # mcds_tab = widgets.VBox([mcds_dir, mcds_plot, mcds_play], layout=tab_layout) # mcds_params = VBox([self.mcds_field, field_cmap_row2, field_cmap_row3, self.max_frames]) # mcds_dir # mcds_params = VBox([self.mcds_field, field_cmap_row2, field_cmap_row3,]) # mcds_dir # self.tab = HBox([mcds_params, self.mcds_plot], layout=tab_layout) help_label = Label('select slider: drag or left/right arrows') # row1 = Box([help_label, Box( [self.max_frames, self.mcds_field, self.field_cmap], layout=Layout(border='0px solid black', row1a = Box([self.max_frames, self.mcds_field, self.field_cmap], layout=Layout(border='1px solid black', width='50%', height='', align_items='stretch', flex_direction='row', display='flex')) row1b = Box([self.cells_toggle, self.cell_edges_toggle], layout=Layout(border='1px solid black', width='50%', height='', align_items='stretch', flex_direction='row', display='flex')) row1 = HBox([row1a, Label('.....'), row1b]) row2a = Box([self.cmap_fixed, self.cmap_min, self.cmap_max], layout=Layout(border='1px solid black', width='50%', height='', align_items='stretch', flex_direction='row', display='flex')) # row2b = Box( [self.substrates_toggle, self.grid_toggle], layout=Layout(border='1px solid black', row2b = Box([ self.substrates_toggle, ], layout=Layout(border='1px solid black', width='50%', height='', align_items='stretch', flex_direction='row', display='flex')) # row2 = HBox( [row2a, self.substrates_toggle, self.grid_toggle]) row2 = HBox([row2a, Label('.....'), row2b]) if (hublib_flag): self.download_button = Download('mcds.zip', style='warning', icon='cloud-download', tooltip='Download data', cb=self.download_cb) self.download_svg_button = Download( 'svg.zip', style='warning', icon='cloud-download', tooltip='You need to allow pop-ups in your browser', cb=self.download_svg_cb) download_row = HBox([ self.download_button.w, self.download_svg_button.w, Label("Download all cell plots (browser must allow pop-ups).") ]) # box_layout = Layout(border='0px solid') controls_box = VBox([row1, row2]) # ,width='50%', layout=box_layout) self.tab = VBox([controls_box, self.i_plot, download_row]) else: # self.tab = VBox([row1, row2]) self.tab = VBox([row1, row2, self.i_plot])
def interact_distributions(): from ipywidgets import FloatSlider, Label, GridBox, interactive, Layout, VBox, \ HBox, Checkbox, IntSlider, Box, Button, widgets fx0 = FloatSlider(value=2, description=" ", min=.5, max=4., step=.2, continuous_update=False, layout=Layout(width='auto', grid_area='vx0')) fy0 = FloatSlider(value=3, description=" ", min=.5, max=4., step=.2, continuous_update=False, layout=Layout(width='auto', grid_area='vy0')) fs0 = FloatSlider(value=1, description=" ", min=.1, max=4., step=.2, continuous_update=False, layout=Layout(width='auto', grid_area='vs0')) fd0 = FloatSlider(value=.9, description=" ", min=-2., max=2., step=.1, continuous_update=False, layout=Layout(width='auto', grid_area='vd0')) fx1 = FloatSlider(value=2, description=" ", min=.5, max=4., step=.2, continuous_update=False, layout=Layout(width='auto', grid_area='vx1')) fy1 = FloatSlider(value=2, description=" ", min=.5, max=4., step=.2, continuous_update=False, layout=Layout(width='auto', grid_area='vy1')) fs1 = FloatSlider(value=1, description=" ", min=.1, max=4., step=.2, continuous_update=False, layout=Layout(width='auto', grid_area='vs1')) fd1 = FloatSlider(value=-.3, description=" ", min=-2., max=2., step=.1, continuous_update=False, layout=Layout(width='auto', grid_area='vd1')) fdummy = FloatSlider(value=2, description=" ", min=1, max=4, step=1) l = lambda s, p, w="auto": Label(s, layout=Layout(width=w, grid_area=p)) bay = Checkbox(value=False, description='show NATURAL frontiers', disabled=False, indent=False, layout=Layout(width="80%")) resample = Button(description="resample data points") from IPython.core.display import clear_output def resample_onclick(_): global do_resample_points do_resample_points = True tmp = fdummy.value fdummy.value = tmp + (1 if tmp < 3 else -1) do_resample_points = False resample.on_click(resample_onclick) w = interactive(display_distributions, x0=fx0, y0=fy0, s0=fs0, d0=fd0, x1=fx1, y1=fy1, s1=fs1, d1=fd1, show_bayesians=bay, dummy=fdummy, continuous_update=False) w.children[-1].layout = Layout(width='auto', grid_area='fig') controls = Box([bay, resample], layout=Layout(grid_area="ctr", display="flex-flow", justify_content="flex-start", flex_flow="column", align_items='flex-start')) gb = GridBox(children=[ fx0, fy0, fs0, fd0, fx1, fy1, fs1, fd1, l("AMERICAN TRILOBYTE", "h0"), l("AFRICAN TRILOBYTE", "h1"), l("size", "lx0"), l("weight", "ly0"), l("spread", "ls0"), l("tilt", "ld0"), l("size", "lx1"), l("weight", "ly1"), l("spread", "ls1"), l("tilt", "ld1"), controls ], layout=Layout( width='100%', grid_template_rows='auto auto auto auto auto auto auto', grid_template_columns='5% 30% 5% 30% 30%', grid_template_areas=''' "h0 h0 h1 h1 ." "lx0 vx0 lx1 vx1 ." "ly0 vy0 ly1 vy1 ctr" "ls0 vs0 ls1 vs1 ctr" "ld0 vd0 ld1 vd1 ctr" "fig fig fig fig fig" ''')) def limit_fd0(*args): fd0.max = fs0.value + fs0.value * 0.5 fd0.min = -fs0.value * 0.5 def limit_fd1(*args): fd1.max = fs1.value + fs1.value * 0.5 fd1.min = -fs1.value * 0.5 fs0.observe(limit_fd0, "value") fd0.observe(limit_fd0, "value") fs1.observe(limit_fd1, "value") fd1.observe(limit_fd1, "value") w.children[0].value = 1 widget1 = VBox([gb, w.children[-1]]) display(widget1) return fx0, fy0, fs0, fd0, fx1, fy1, fs1, fd1
def __init__(self, wvmin, wvmax, clouds, show_labels=True, widgets=('z', 'sigma', 'n', 'lyman', 'balmer', 'paschen'), zmin=0.00, zmax=0.10, smin=1, smax=500, nmin=0, nmax=0.1, Pmin=0, Pmax=10, vmin=1, vmax=100, tmin=0, tmax=20): self.clouds = clouds self.ncomponents = len(clouds) dv = (smax + smin) / 8.0 dlam = dv / c * (wvmax - wvmin) / 2.0 wv = np.linspace(wvmin, wvmax, int((wvmax - wvmin) / dlam)) self.wv = wv # set max height of graph cloud = clouds[0] old_sigma = cloud.sigma old_n = cloud.n cloud.sigma = (smin + smax) / 2.0 cloud.n = nmax self.ymax = 1.1 * np.amax(cloud.line_flux(wv)) cloud.sigma = old_sigma cloud.n = old_n # construct widget dictionary widget_dict = {} letter = cycle(ascii_lowercase) for i, cloud in enumerate(self.clouds): # float sliders keys = ['z', 'sigma', 'n', 'P', 'v', 't'] labels = [ 'Redshift: ', 'Dispersion: ', 'Density: ', 'Period: ', 'Amplitude: ', 'Time: ' ] widget_kwargs = { "disabled": False, "continuous_update": False, "orientation": "horizontal", "readout": True, "readout_format": ".4f" } values = [ cloud.z, cloud.sigma, cloud.n, cloud.P, cloud.vsini, cloud.t ] bounds = [(zmin, zmax), (smin, smax), (nmin, nmax), (Pmin, Pmax), (vmin, vmax), (tmin, tmax)] for j, key in enumerate(keys): value = values[j] if key not in widgets: widget_dict[key + str(i)] = fixed(value) continue if show_labels: label = labels[j] else: label = "({})".format(next(letter)) lower, upper = bounds[j] widget_dict[key + str(i)] = FloatSlider(value=value, min=lower, max=upper, step=(upper - lower) / 100, description=label, **widget_kwargs) # boolean checkboxes keys = ['lyman', 'balmer', 'paschen'] labels = [s.capitalize() + ": " for s in keys] widget_kwargs = {"disabled": False} values = [cloud.lyman, cloud.balmer, cloud.paschen] for j, key in enumerate(keys): value = values[j] if key not in widgets: widget_dict[key + str(i)] = fixed(value) continue if show_labels: label = labels[j] else: label = "({})".format(next(letter)) widget_dict[key + str(i)] = Checkbox(value=value, description=label, **widget_kwargs) super().__init__(self.plot, **widget_dict)
def __init__(self): tab_height = '520px' tab_height = '550px' tab_layout = Layout( width='900px', # border='2px solid black', height=tab_height) #, overflow_y='scroll') self.output_dir = '.' # self.output_dir = 'tmpdir' max_frames = 1 self.svg_plot = interactive(self.plot_svg, frame=(0, max_frames), continuous_update=False) svg_plot_size = '500px' self.svg_plot.layout.width = svg_plot_size self.svg_plot.layout.height = svg_plot_size self.use_defaults = True self.show_nucleus = 0 # 0->False, 1->True in Checkbox! self.show_edge = 1 # 0->False, 1->True in Checkbox! self.scale_radius = 1.0 self.axes_min = 0.0 self.axes_max = 2000 # hmm, this can change (TODO?) # self.fig = plt.figure(figsize=(6, 6)) # self.tab = HBox([svg_plot], layout=tab_layout) self.max_frames = BoundedIntText( min=0, max=99999, value=max_frames, description='Max', # layout=Layout(flex='0 1 auto', width='auto'), #Layout(width='160px'), ) self.max_frames.observe(self.update_max_frames) self.show_nucleus_checkbox = Checkbox( description='nucleus', value=False, disabled=False, # layout=Layout(flex='1 1 auto', width='auto'), #Layout(width='160px'), ) self.show_nucleus_checkbox.observe(self.show_nucleus_cb) self.show_edge_checkbox = Checkbox( description='edge', value=True, disabled=False, # layout=Layout(flex='1 1 auto', width='auto'), #Layout(width='160px'), ) self.show_edge_checkbox.observe(self.show_edge_cb) # row1 = HBox([Label('(select slider: drag or left/right arrows)'), # self.max_frames, VBox([self.show_nucleus_checkbox, self.show_edge_checkbox])]) # self.max_frames, self.show_nucleus_checkbox], layout=Layout(width='500px')) # self.tab = VBox([row1,self.svg_plot], layout=tab_layout) self.help_label = Label('select slider: drag or left/right arrows', layout=Layout(flex='0 1 auto', width='auto')) # layout=Layout(flex='3 1 auto', width='auto')) items_auto = [ self.help_label, self.max_frames, self.show_nucleus_checkbox, self.show_edge_checkbox, ] #row1 = HBox([Label('(select slider: drag or left/right arrows)'), # max_frames, show_nucleus_checkbox, show_edge_checkbox], # layout=Layout(width='800px')) box_layout = Layout(display='flex', flex_flow='row', align_items='stretch', width='90%') # row1 = Box(children=items_auto, layout=box_layout) #row1 = Box(children=items_auto) row1 = Box([ self.help_label, Box([ self.max_frames, self.show_nucleus_checkbox, self.show_edge_checkbox ], layout=Layout(border='0px solid black', width='60%', height='', align_items='stretch', flex_direction='row', display='flex')) ]) # self.download_button = Download('svg.zip', style='warning', icon='cloud-download', tooltip='Download results', cb=self.download_cb) #self.download_button = Download('svg.zip', style='warning', icon='cloud-download', tooltip='Download results') # self.tab = VBox([row1, self.svg_plot], layout=tab_layout) # self.tab = VBox([row1, self.svg_plot, self.download_button.w], layout=tab_layout) self.tab = VBox([row1, self.svg_plot], layout=tab_layout)
def __init__(self): self.output_dir = '.' # self.output_dir = 'tmpdir' self.figsize_width_substrate = 15.0 # allow extra for colormap self.figsize_height_substrate = 12.5 self.figsize_width_svg = 12.0 self.figsize_height_svg = 12.0 # self.fig = plt.figure(figsize=(self.figsize_width_substrate, self.figsize_height_substrate)) # self.fig = plt.figure() self.fig = None # self.fig = plt.figure(figsize=(7.2,6)) # this strange figsize results in a ~square contour plot self.first_time = True self.modulo = 1 self.use_defaults = True self.svg_delta_t = 1 self.substrate_delta_t = 1 self.svg_frame = 1 self.substrate_frame = 1 self.customized_output_freq = False self.therapy_activation_time = 1000000 self.max_svg_frame_pre_therapy = 1000000 self.max_substrate_frame_pre_therapy = 1000000 self.svg_xmin = 0 # Probably don't want to hardwire these if we allow changing the domain size # self.svg_xrange = 2000 # self.xmin = -1000. # self.xmax = 1000. # self.ymin = -1000. # self.ymax = 1000. # self.x_range = 2000. # self.y_range = 2000. self.show_nucleus = False self.show_edge = True # initial value self.field_index = 4 # self.field_index = self.mcds_field.value + 4 # define dummy size of mesh (set in the tool's primary module) self.numx = 0 self.numy = 0 self.title_str = '' tab_height = '600px' tab_height = '500px' constWidth = '180px' constWidth2 = '150px' tab_layout = Layout( width='900px', # border='2px solid black', height=tab_height, ) #overflow_y='scroll') max_frames = 2 # self.mcds_plot = interactive(self.plot_substrate, frame=(0, max_frames), continuous_update=False) # self.i_plot = interactive(self.plot_plots, frame=(0, max_frames), continuous_update=False) # self.i_plot = interactive(self.plot_substrate0, frame=(0, max_frames), continuous_update=False) self.i_plot = interactive(self.plot_substrate, frame=(0, max_frames), continuous_update=False) self.frame_slider = IntSlider( min=0, max=10, step=1, description='Test:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d', ) # self.frame_slider.observe(self.frame_slider_cb) self.frame_slider.observe(self.plot_substrate) # "plot_size" controls the size of the tab height, not the plot (rf. figsize for that) # NOTE: the Substrates Plot tab has an extra row of widgets at the top of it (cf. Cell Plots tab) svg_plot_size = '700px' svg_plot_size = '600px' svg_plot_size = '700px' svg_plot_size = '900px' self.i_plot.layout.width = svg_plot_size self.i_plot.layout.height = svg_plot_size self.fontsize = 20 # description='# cell frames', self.max_frames = BoundedIntText( min=0, max=99999, value=max_frames, description='# frames', layout=Layout(width='160px'), ) self.max_frames.observe(self.update_max_frames) # self.field_min_max = {'dummy': [0., 1.]} # NOTE: manually setting these for now (vs. parsing them out of data/initial.xml) self.field_min_max = { 'director signal': [0., 1.], 'cargo signal': [0., 1.] } # hacky I know, but make a dict that's got (key,value) reversed from the dict in the Dropdown below # self.field_dict = {0:'dummy'} self.field_dict = {0: 'director signal', 1: 'cargo signal'} self.mcds_field = Dropdown( options={ 'director signal': 0, 'cargo signal': 1 }, value=0, # description='Field', layout=Layout(width=constWidth)) # print("substrate __init__: self.mcds_field.value=",self.mcds_field.value) # self.mcds_field.observe(self.mcds_field_cb) self.mcds_field.observe(self.mcds_field_changed_cb) # self.field_cmap = Text( # value='viridis', # description='Colormap', # disabled=True, # layout=Layout(width=constWidth), # ) self.field_cmap = Dropdown( options=['viridis', 'jet', 'YlOrRd'], value='YlOrRd', # description='Field', layout=Layout(width=constWidth)) # self.field_cmap.observe(self.plot_substrate) self.field_cmap.observe(self.mcds_field_cb) self.cmap_fixed = Checkbox( description='Fix', disabled=False, # layout=Layout(width=constWidth2), ) self.save_min_max = Button( description='Save', #style={'description_width': 'initial'}, button_style= 'success', # 'success', 'info', 'warning', 'danger' or '' tooltip='Save min/max for this substrate', disabled=True, layout=Layout(width='90px')) def save_min_max_cb(b): # field_name = self.mcds_field.options[] # field_name = next(key for key, value in self.mcds_field.options.items() if value == self.mcds_field.value) field_name = self.field_dict[self.mcds_field.value] # print(field_name) # self.field_min_max = {'oxygen': [0., 30.], 'glucose': [0., 1.], 'H+ ions': [0., 1.], 'ECM': [0., 1.], 'NP1': [0., 1.], 'NP2': [0., 1.]} self.field_min_max[field_name][0] = self.cmap_min.value self.field_min_max[field_name][1] = self.cmap_max.value # print(self.field_min_max) self.save_min_max.on_click(save_min_max_cb) self.cmap_min = FloatText( description='Min', value=0, step=0.1, disabled=True, layout=Layout(width=constWidth2), ) self.cmap_min.observe(self.mcds_field_cb) self.cmap_max = FloatText( description='Max', value=38, step=0.1, disabled=True, layout=Layout(width=constWidth2), ) self.cmap_max.observe(self.mcds_field_cb) def cmap_fixed_cb(b): if (self.cmap_fixed.value): self.cmap_min.disabled = False self.cmap_max.disabled = False self.save_min_max.disabled = False else: self.cmap_min.disabled = True self.cmap_max.disabled = True self.save_min_max.disabled = True # self.mcds_field_cb() self.cmap_fixed.observe(cmap_fixed_cb) field_cmap_row2 = HBox([self.field_cmap, self.cmap_fixed]) # field_cmap_row3 = HBox([self.save_min_max, self.cmap_min, self.cmap_max]) items_auto = [ self.save_min_max, #layout=Layout(flex='3 1 auto', width='auto'), self.cmap_min, self.cmap_max, ] box_layout = Layout(display='flex', flex_flow='row', align_items='stretch', width='80%') field_cmap_row3 = Box(children=items_auto, layout=box_layout) #--------------------- self.cell_nucleus_toggle = Checkbox( description='nuclei', disabled=False, value=self.show_nucleus, # layout=Layout(width=constWidth2), ) def cell_nucleus_toggle_cb(b): # self.update() if (self.cell_nucleus_toggle.value): self.show_nucleus = True else: self.show_nucleus = False self.i_plot.update() self.cell_nucleus_toggle.observe(cell_nucleus_toggle_cb) #---- self.cell_edges_toggle = Checkbox( description='edges', disabled=False, value=self.show_edge, # layout=Layout(width=constWidth2), ) def cell_edges_toggle_cb(b): # self.update() if (self.cell_edges_toggle.value): self.show_edge = True else: self.show_edge = False self.i_plot.update() self.cell_edges_toggle.observe(cell_edges_toggle_cb) self.cells_toggle = Checkbox( description='Cells', disabled=False, value=True, # layout=Layout(width=constWidth2), ) def cells_toggle_cb(b): # self.update() self.i_plot.update() if (self.cells_toggle.value): self.cell_edges_toggle.disabled = False self.cell_nucleus_toggle.disabled = False else: self.cell_edges_toggle.disabled = True self.cell_nucleus_toggle.disabled = True self.cells_toggle.observe(cells_toggle_cb) #--------------------- self.substrates_toggle = Checkbox( description='Substrates', disabled=False, value=True, # layout=Layout(width=constWidth2), ) def substrates_toggle_cb(b): if (self.substrates_toggle.value): # seems bass-ackwards self.cmap_fixed.disabled = False self.cmap_min.disabled = False self.cmap_max.disabled = False self.mcds_field.disabled = False self.field_cmap.disabled = False else: self.cmap_fixed.disabled = True self.cmap_min.disabled = True self.cmap_max.disabled = True self.mcds_field.disabled = True self.field_cmap.disabled = True self.substrates_toggle.observe(substrates_toggle_cb) self.grid_toggle = Checkbox( description='grid', disabled=False, value=True, # layout=Layout(width=constWidth2), ) def grid_toggle_cb(b): # self.update() self.i_plot.update() self.grid_toggle.observe(grid_toggle_cb) # field_cmap_row3 = Box([self.save_min_max, self.cmap_min, self.cmap_max]) # mcds_tab = widgets.VBox([mcds_dir, mcds_plot, mcds_play], layout=tab_layout) # mcds_params = VBox([self.mcds_field, field_cmap_row2, field_cmap_row3, self.max_frames]) # mcds_dir # mcds_params = VBox([self.mcds_field, field_cmap_row2, field_cmap_row3,]) # mcds_dir # self.tab = HBox([mcds_params, self.mcds_plot], layout=tab_layout) help_label = Label('select slider: drag or left/right arrows') # row1 = Box([help_label, Box( [self.max_frames, self.mcds_field, self.field_cmap], layout=Layout(border='0px solid black', row1a = Box([self.max_frames, self.mcds_field, self.field_cmap], layout=Layout(border='1px solid black', width='50%', height='', align_items='stretch', flex_direction='row', display='flex')) row1b = Box([ self.cells_toggle, self.cell_nucleus_toggle, self.cell_edges_toggle ], layout=Layout(border='1px solid black', width='50%', height='', align_items='stretch', flex_direction='row', display='flex')) row1 = HBox([row1a, Label('.....'), row1b]) row2a = Box([self.cmap_fixed, self.cmap_min, self.cmap_max], layout=Layout(border='1px solid black', width='50%', height='', align_items='stretch', flex_direction='row', display='flex')) # row2b = Box( [self.substrates_toggle, self.grid_toggle], layout=Layout(border='1px solid black', row2b = Box([ self.substrates_toggle, ], layout=Layout(border='1px solid black', width='50%', height='', align_items='stretch', flex_direction='row', display='flex')) # row2 = HBox( [row2a, self.substrates_toggle, self.grid_toggle]) row2 = HBox([row2a, Label('.....'), row2b]) row3 = HBox([ self.frame_slider, ]) if (hublib_flag): self.download_button = Download('mcds.zip', style='warning', icon='cloud-download', tooltip='Download data', cb=self.download_cb) self.download_svg_button = Download( 'svg.zip', style='warning', icon='cloud-download', tooltip='You need to allow pop-ups in your browser', cb=self.download_svg_cb) download_row = HBox([ self.download_button.w, self.download_svg_button.w, Label("Download all cell plots (browser must allow pop-ups).") ]) # box_layout = Layout(border='0px solid') # controls_box = VBox([row1, row2]) # ,width='50%', layout=box_layout) controls_box = VBox([row1, row2, row3]) # ,width='50%', layout=box_layout) # self.tab = VBox([controls_box, self.i_plot, download_row]) # graph = GraphWidget() # iplot([{"x": [1, 2, 3], "y": [3, 1, 6]}]) # self.fig = go.FigureWidget(data=go.Bar(y=[2, 3, 1])) # x = np.random.randn(2000) # y = np.random.randn(2000) self.x = np.random.randn(2) self.y = np.random.randn(2) # iplot([go.Histogram2dContour(x=x, y=y, contours=dict(coloring='heatmap')), # self.fig = go.FigureWidget(data=go.Histogram2dContour(x=x, y=y, contours_showlines=False, contours=dict(coloring='heatmap'))) self.fig = go.FigureWidget(data=go.Histogram2dContour( x=self.x, y=self.y, contours=dict(coloring='heatmap'))) # self.fig = go.FigureWidget( data = [ # { # 'type' : 'Histogram2dContour', # 'x' : self.x, # 'y' : self.y, # 'contours' : { # 'coloring': 'heatmap' # } # }, # { # 'type' : 'scatter', # 'x' : self.x, # 'y' : self.y, # 'line' : { # 'color': 'red', # 'width': 3 # } # } # ], layout={}) # self.fig = go.FigureWidget(data=go.Contour(x=x, y=y, contours=dict(coloring='heatmap'))) # x = np.linspace(-10, 10, 400) # y = np.linspace(-5, 5, 400) # x, y = np.meshgrid(x, y) # a = 1 # b = 2 # z = x**2/a**2 - y**2/b**2 # contour = go.Contour( # z=z # ) # contour.contours.type = 'constraint' # contour.contours.value = 8 # data = [contour] # # self.fig = go.Figure(data=data) # self.fig = go.FigureWidget(data=data) # go.Scatter(x=x, y=y, mode='markers', marker=dict(color='white', size=3, opacity=0.3)), show_link=False) self.fig.update_layout( # square figure layout for plotly? autosize=True, margin=dict(l=20, r=20, t=30, b=20), width=800, height=800, # margin=dict( # l=50, # r=50, # b=100, # t=100, # pad=4 # ), # paper_bgcolor="White", # paper_bgcolor="LightSteelBlue", ) self.tab = VBox([controls_box, self.fig, download_row]) # plotly approach # app_layout = AppLayout( # center= self.fig.canvas, # # footer= self.frame_slider, # pane_heights=[0, 6, 1] # ) # self.tab = app_layout # self.tab = VBox([controls_box, self.fig.canvas, download_row]) # self.fig = plt.figure(figsize=(self.figsize_width_substrate, self.figsize_height_substrate)) else: # self.tab = VBox([row1, row2]) self.tab = VBox([row1, row2, self.i_plot])
) # Here we call the Optimization function that returns the initial optimal weights. # ************************************************************************************* GUI portion of the code that contains various labels,checkboxes etc. *********************** input_header = HBox([ Label(value='Ticker', layout=Layout(width='120px', height='22px')), Label(value='Name of Asset', layout=Layout(width='120px', height='22px')), Label(value='Weight', layout=Layout(width='120px', height='22px')) ]) list_sec_input = [input_header] lst_name = list(dict_settings['security'].keys()) lst_ticker = list(dict_settings['security'].values()) lst_weight = dict_settings['weight'] # Checkbox that determines the mktcap option. Places in python object's 'check_usemktcap' value field a true or false value check_usemktcap = Checkbox(description='Use Market Cap as Weight', value=dict_settings['usemktcap'], layout=Layout(min_width='15px'), style={'description_width': 'initial'}) label_usemktcap = Label(value=' ', layout={'height': '22px'}) # MktCap Label label_usemktcap2 = Label(value='(not recommended when using ETF as proxy)', layout=Layout(min_width='300px')) # MktCap Label # Option to load your own internal portfolio different from the original input. #port_dict = {x['name']: x['id'].split(':')[2].replace('-','U') + '-' + x['id'].split(':')[3] for x in bqport.list_portfolios()} #port_dict = {x['name']: x['id'].split(':')[2].replace('-','U') + '-' + x['id'].split(':')[3] for x in bq.port.list_portfolios()} #load_button = Button(description='Load members') #portfolio_dropdown = Dropdown(description='Portfolio:',options=sorted(set(port_dict.keys()))) #load_members_hbox = HBox([portfolio_dropdown, load_button]) for n in range(num_avail_ticker):
def build_options(self): grid = GridspecLayout(4, 2) options_map = {} style = {'description_width': '60%'} # plot_type plot_type = Dropdown( description='Plot:', options=['force', 'decision', 'both'], description_tooltip='Which plot to draw decision, force or both', style=style) options_map['plot_type'] = plot_type # background_data background_data = Dropdown( description='Background data:', options={ 'KMeans': 'kmeans', 'Custom variable': 'custom' }, value='kmeans', description_tooltip= 'What background data will be used to sample from, when simulating "missing" feature\n' ' - KMeans: use KMeans to sample from provided dataset\n' ' - Custom variable: provide variable with instances to use', style=style) options_map['background_data'] = background_data # kmeans_count (only show when KMeans is chosen) kmeans_count = BoundedIntText( value=100, min=1, max=len(self.X_train), description='Count of KMeans centers:', description_tooltip= 'Number of means to use when creating background data', style=style) options_map['kmeans_count'] = kmeans_count # data (only show when Custom variable is chosen) data = UpdatingCombobox( options_keys=self.globals_options, description='Background data variable:', options=list(self.globals_options), description_tooltip= 'Variable with background data from which the "missing" features will be sampled', style=style) options_map['data'] = data # set up swap of options def swap_kmeans(change): if change['new'] == 'kmeans': data.lookup_in_kernel = False grid[1, 1] = kmeans_count else: data.lookup_in_kernel = True grid[1, 1] = data background_data.observe(swap_kmeans, names=['value']) # link link = Dropdown( description='Link:', options=['identity', 'logit'], value='identity', description_tooltip= 'A generalized linear model link to connect the feature importance values ' 'to the model output.\n' 'Since the feature importance values, phi, sum up to the model output, ' 'it often makes sense to connect them to the ouput with a link function ' 'where link(outout) = sum(phi).\n ' 'If the model output is a probability then the LogitLink link function makes ' 'the feature importance values have log-odds units.', style=style) options_map['link'] = link # nsamples nsamples = BoundedIntText( min=1, max=999999, value=2048, disabled=True, description='Model sample size:', description_tooltip= 'Number of times to re-evaluate the model when explaining each prediction.\n' 'More samples lead to lower variance estimates of the SHAP values.\n' 'The "auto" setting uses nsamples = 2 * X.shape[1] + 2048.', style=style) options_map['nsamples'] = nsamples # auto_nsamples auto_nsamples = Checkbox(description='Auto choose model sample size', value=True, style={'description_width': 'auto'}) options_map['auto_nsamples'] = auto_nsamples def disable_nsamples(change): nsamples.disabled = change['new'] auto_nsamples.observe(disable_nsamples, names=['value']) # l1_reg l1_reg = Combobox( description='L1 regularization:', options=['auto', 'aic', 'bic'], value='auto', description_tooltip= 'The l1 regularization to use for feature selection ' '(the estimation procedure is based on a debiased lasso).\n' ' - The auto option currently uses "aic" when less that 20% ' 'of the possible sample space is enumerated, otherwise it uses no regularization.\n' ' - The "aic" and "bic" options use the AIC and BIC rules for regularization.\n' ' - Integer selects a fix number of top features.\n' ' - float directly sets the "alpha" parameter of the sklearn.linear_model.Lasso model ' 'used for feature selection', style=style) options_map['l1_reg'] = l1_reg # class_to_explain (only if classification) if self.is_classification: class_to_explain = Dropdown( description='Class to plot:', options={val: e for e, val in enumerate(self.class_names)}, description_tooltip= 'For classification select a class for which the prediction will be explained', style=style) options_map['class_to_explain'] = class_to_explain grid[3, 1] = class_to_explain grid[0, 0] = plot_type grid[1, 0] = background_data grid[1, 1] = kmeans_count grid[0, 1] = link grid[2, 0] = nsamples grid[2, 1] = auto_nsamples grid[3, 0] = l1_reg return options_map, grid
def __init__(self): micron_units = Label('micron') # use "option m" (Mac, for micro symbol) constWidth = '180px' tab_height = '500px' stepsize = 10 #style = {'description_width': '250px'} style = {'description_width': '25%'} layout = {'width': '400px'} name_button_layout={'width':'25%'} widget_layout = {'width': '15%'} units_button_layout ={'width':'15%'} desc_button_layout={'width':'45%'} param_name1 = Button(description='number_of_cells', disabled=True, layout=name_button_layout) param_name1.style.button_color = 'lightgreen' self.number_of_cells = IntText( value=3, step=0.1, style=style, layout=widget_layout) param_name2 = Button(description='is_motile', disabled=True, layout=name_button_layout) param_name2.style.button_color = 'tan' self.is_motile = Checkbox( value=False, style=style, layout=widget_layout) param_name3 = Button(description='persistence_time', disabled=True, layout=name_button_layout) param_name3.style.button_color = 'lightgreen' self.persistence_time = FloatText( value=30, step=1, style=style, layout=widget_layout) param_name4 = Button(description='migration_speed', disabled=True, layout=name_button_layout) param_name4.style.button_color = 'tan' self.migration_speed = FloatText( value=2, step=0.1, style=style, layout=widget_layout) param_name5 = Button(description='migration_bias', disabled=True, layout=name_button_layout) param_name5.style.button_color = 'lightgreen' self.migration_bias = FloatText( value=0.8, step=0.1, style=style, layout=widget_layout) param_name6 = Button(description='bias_migration_angle', disabled=True, layout=name_button_layout) param_name6.style.button_color = 'tan' self.bias_migration_angle = FloatText( value=30, step=1, style=style, layout=widget_layout) units_button1 = Button(description='', disabled=True, layout=units_button_layout) units_button1.style.button_color = 'lightgreen' units_button2 = Button(description='', disabled=True, layout=units_button_layout) units_button2.style.button_color = 'tan' units_button3 = Button(description='min', disabled=True, layout=units_button_layout) units_button3.style.button_color = 'lightgreen' units_button4 = Button(description='micron/min', disabled=True, layout=units_button_layout) units_button4.style.button_color = 'tan' units_button5 = Button(description='', disabled=True, layout=units_button_layout) units_button5.style.button_color = 'lightgreen' units_button6 = Button(description='degree', disabled=True, layout=units_button_layout) units_button6.style.button_color = 'tan' desc_button1 = Button(description='number of cell tracks to simulate', disabled=True, layout=desc_button_layout) desc_button1.style.button_color = 'lightgreen' desc_button2 = Button(description='true if cells are motile', disabled=True, layout=desc_button_layout) desc_button2.style.button_color = 'tan' desc_button3 = Button(description='mean persistence time', disabled=True, layout=desc_button_layout) desc_button3.style.button_color = 'lightgreen' desc_button4 = Button(description='migration speed', disabled=True, layout=desc_button_layout) desc_button4.style.button_color = 'tan' desc_button5 = Button(description='migration bias parameter', disabled=True, layout=desc_button_layout) desc_button5.style.button_color = 'lightgreen' desc_button6 = Button(description='migration bias angle respect to x-axis', disabled=True, layout=desc_button_layout) desc_button6.style.button_color = 'tan' row1 = [param_name1, self.number_of_cells, units_button1, desc_button1] row2 = [param_name2, self.is_motile, units_button2, desc_button2] row3 = [param_name3, self.persistence_time, units_button3, desc_button3] row4 = [param_name4, self.migration_speed, units_button4, desc_button4] row5 = [param_name5, self.migration_bias, units_button5, desc_button5] row6 = [param_name6, self.bias_migration_angle, units_button6, desc_button6] box_layout = Layout(display='flex', flex_flow='row', align_items='stretch', width='100%') box1 = Box(children=row1, layout=box_layout) box2 = Box(children=row2, layout=box_layout) box3 = Box(children=row3, layout=box_layout) box4 = Box(children=row4, layout=box_layout) box5 = Box(children=row5, layout=box_layout) box6 = Box(children=row6, layout=box_layout) self.tab = VBox([ box1, box2, box3, box4, box5, box6, ])
def __init__(self): micron_units = Label( 'micron') # use "option m" (Mac, for micro symbol) constWidth = '180px' tab_height = '500px' stepsize = 10 #style = {'description_width': '250px'} style = {'description_width': '25%'} layout = {'width': '400px'} name_button_layout = {'width': '25%'} widget_layout = {'width': '15%'} units_button_layout = {'width': '15%'} desc_button_layout = {'width': '45%'} divider_button_layout = {'width': '40%'} param_name1 = Button(description='random_seed', disabled=True, layout=name_button_layout) param_name1.style.button_color = 'lightgreen' self.random_seed = IntText(value=0, step=1, style=style, layout=widget_layout) div_row1 = Button(description='---Virus Replication---', disabled=True, layout=divider_button_layout) param_name2 = Button(description='virion_uncoating_rate', disabled=True, layout=name_button_layout) param_name2.style.button_color = 'tan' self.virion_uncoating_rate = FloatText(value=0.01, step=0.001, style=style, layout=widget_layout) param_name3 = Button(description='uncoated_to_RNA_rate', disabled=True, layout=name_button_layout) param_name3.style.button_color = 'lightgreen' self.uncoated_to_RNA_rate = FloatText(value=0.01, step=0.001, style=style, layout=widget_layout) param_name4 = Button(description='protein_synthesis_rate', disabled=True, layout=name_button_layout) param_name4.style.button_color = 'tan' self.protein_synthesis_rate = FloatText(value=0.01, step=0.001, style=style, layout=widget_layout) param_name5 = Button(description='virion_assembly_rate', disabled=True, layout=name_button_layout) param_name5.style.button_color = 'lightgreen' self.virion_assembly_rate = FloatText(value=0.01, step=0.001, style=style, layout=widget_layout) div_row2 = Button(description='---Virus Adsorption and Export---', disabled=True, layout=divider_button_layout) param_name6 = Button(description='virion_export_rate', disabled=True, layout=name_button_layout) param_name6.style.button_color = 'tan' self.virion_export_rate = FloatText(value=0.01, step=0.001, style=style, layout=widget_layout) div_row3 = Button( description='---ACE2 receptor dynamics with virus binding---', disabled=True, layout=divider_button_layout) param_name7 = Button(description='ACE2_receptors_per_cell', disabled=True, layout=name_button_layout) param_name7.style.button_color = 'lightgreen' self.ACE2_receptors_per_cell = FloatText(value=1000, step=100, style=style, layout=widget_layout) param_name8 = Button(description='ACE2_binding_rate', disabled=True, layout=name_button_layout) param_name8.style.button_color = 'tan' self.ACE2_binding_rate = FloatText(value=0.001, step=0.0001, style=style, layout=widget_layout) param_name9 = Button(description='ACE2_endocytosis_rate', disabled=True, layout=name_button_layout) param_name9.style.button_color = 'lightgreen' self.ACE2_endocytosis_rate = FloatText(value=0.01, step=0.001, style=style, layout=widget_layout) param_name10 = Button(description='ACE2_cargo_release_rate', disabled=True, layout=name_button_layout) param_name10.style.button_color = 'tan' self.ACE2_cargo_release_rate = FloatText(value=0.001, step=0.0001, style=style, layout=widget_layout) param_name11 = Button(description='ACE2_recycling_rate', disabled=True, layout=name_button_layout) param_name11.style.button_color = 'lightgreen' self.ACE2_recycling_rate = FloatText(value=0.01, step=0.001, style=style, layout=widget_layout) div_row4 = Button(description='---Apoptotic Response---', disabled=True, layout=divider_button_layout) param_name12 = Button(description='max_infected_apoptosis_rate', disabled=True, layout=name_button_layout) param_name12.style.button_color = 'tan' self.max_infected_apoptosis_rate = FloatText(value=0.001, step=0.0001, style=style, layout=widget_layout) param_name13 = Button(description='max_apoptosis_half_max', disabled=True, layout=name_button_layout) param_name13.style.button_color = 'lightgreen' self.max_apoptosis_half_max = FloatText(value=500, step=10, style=style, layout=widget_layout) param_name14 = Button(description='apoptosis_hill_power', disabled=True, layout=name_button_layout) param_name14.style.button_color = 'tan' self.apoptosis_hill_power = FloatText(value=1, step=0.1, style=style, layout=widget_layout) param_name15 = Button(description='virus_fraction_released_at_death', disabled=True, layout=name_button_layout) param_name15.style.button_color = 'lightgreen' self.virus_fraction_released_at_death = FloatText(value=0, step=0.01, style=style, layout=widget_layout) div_row5 = Button(description='---Initialization Options--', disabled=True, layout=divider_button_layout) param_name16 = Button(description='multiplicity_of_infection', disabled=True, layout=name_button_layout) param_name16.style.button_color = 'tan' self.multiplicity_of_infection = FloatText(value=0.01, step=0.001, style=style, layout=widget_layout) param_name17 = Button(description='use_single_infected_cell', disabled=True, layout=name_button_layout) param_name17.style.button_color = 'lightgreen' self.use_single_infected_cell = Checkbox(value=False, style=style, layout=widget_layout) div_row6 = Button(description='---Visualization Options---', disabled=True, layout=divider_button_layout) param_name18 = Button(description='color_variable', disabled=True, layout=name_button_layout) param_name18.style.button_color = 'tan' self.color_variable = Text(value='assembled virion', style=style, layout=widget_layout) units_button1 = Button(description='', disabled=True, layout=units_button_layout) units_button1.style.button_color = 'lightgreen' units_button2 = Button(description='', disabled=True, layout=units_button_layout) units_button2.style.button_color = 'lightgreen' units_button3 = Button(description='1/min', disabled=True, layout=units_button_layout) units_button3.style.button_color = 'tan' units_button4 = Button(description='1/min', disabled=True, layout=units_button_layout) units_button4.style.button_color = 'lightgreen' units_button5 = Button(description='1/min', disabled=True, layout=units_button_layout) units_button5.style.button_color = 'tan' units_button6 = Button(description='1/min', disabled=True, layout=units_button_layout) units_button6.style.button_color = 'lightgreen' units_button7 = Button(description='', disabled=True, layout=units_button_layout) units_button7.style.button_color = 'lightgreen' units_button8 = Button(description='1/min', disabled=True, layout=units_button_layout) units_button8.style.button_color = 'tan' units_button9 = Button(description='', disabled=True, layout=units_button_layout) units_button9.style.button_color = 'tan' units_button10 = Button(description='', disabled=True, layout=units_button_layout) units_button10.style.button_color = 'lightgreen' units_button11 = Button(description='1/min', disabled=True, layout=units_button_layout) units_button11.style.button_color = 'tan' units_button12 = Button(description='1/min', disabled=True, layout=units_button_layout) units_button12.style.button_color = 'lightgreen' units_button13 = Button(description='1/min', disabled=True, layout=units_button_layout) units_button13.style.button_color = 'tan' units_button14 = Button(description='1/min', disabled=True, layout=units_button_layout) units_button14.style.button_color = 'lightgreen' units_button15 = Button(description='', disabled=True, layout=units_button_layout) units_button15.style.button_color = 'lightgreen' units_button16 = Button(description='1/min', disabled=True, layout=units_button_layout) units_button16.style.button_color = 'tan' units_button17 = Button(description='virion', disabled=True, layout=units_button_layout) units_button17.style.button_color = 'lightgreen' units_button18 = Button(description='', disabled=True, layout=units_button_layout) units_button18.style.button_color = 'tan' units_button19 = Button(description='', disabled=True, layout=units_button_layout) units_button19.style.button_color = 'lightgreen' units_button20 = Button(description='', disabled=True, layout=units_button_layout) units_button20.style.button_color = 'lightgreen' units_button21 = Button(description='', disabled=True, layout=units_button_layout) units_button21.style.button_color = 'tan' units_button22 = Button(description='', disabled=True, layout=units_button_layout) units_button22.style.button_color = 'lightgreen' units_button23 = Button(description='', disabled=True, layout=units_button_layout) units_button23.style.button_color = 'lightgreen' units_button24 = Button(description='', disabled=True, layout=units_button_layout) units_button24.style.button_color = 'tan' desc_button1 = Button(description='', disabled=True, layout=desc_button_layout) desc_button1.style.button_color = 'lightgreen' desc_button2 = Button( description='rate at which an internalized virion is uncoated', disabled=True, layout=desc_button_layout) desc_button2.style.button_color = 'tan' desc_button3 = Button( description= 'rate at which uncoated virion makes its mRNA available', disabled=True, layout=desc_button_layout) desc_button3.style.button_color = 'lightgreen' desc_button4 = Button( description='rate at mRNA creates complete set of proteins', disabled=True, layout=desc_button_layout) desc_button4.style.button_color = 'tan' desc_button5 = Button( description= 'rate at which viral proteins are assembled into complete virion', disabled=True, layout=desc_button_layout) desc_button5.style.button_color = 'lightgreen' desc_button6 = Button( description='rate at which a virion is exported from a live cell', disabled=True, layout=desc_button_layout) desc_button6.style.button_color = 'tan' desc_button7 = Button(description='number of ACE2 receptors per cell', disabled=True, layout=desc_button_layout) desc_button7.style.button_color = 'lightgreen' desc_button8 = Button(description='ACE2 receptor-virus binding rate', disabled=True, layout=desc_button_layout) desc_button8.style.button_color = 'tan' desc_button9 = Button( description='ACE2 receptor-virus endocytosis rate', disabled=True, layout=desc_button_layout) desc_button9.style.button_color = 'lightgreen' desc_button10 = Button( description='ACE2 receptor-virus cargo release rate', disabled=True, layout=desc_button_layout) desc_button10.style.button_color = 'tan' desc_button11 = Button(description='ACE2 receptor recycling rate', disabled=True, layout=desc_button_layout) desc_button11.style.button_color = 'lightgreen' desc_button12 = Button( description='maximum rate of cell apoptosis due to viral infection', disabled=True, layout=desc_button_layout) desc_button12.style.button_color = 'tan' desc_button13 = Button( description= 'viral load at which cells reach half max apoptosis rate', disabled=True, layout=desc_button_layout) desc_button13.style.button_color = 'lightgreen' desc_button14 = Button( description='Hill power for viral load apoptosis response', disabled=True, layout=desc_button_layout) desc_button14.style.button_color = 'tan' desc_button15 = Button( description='fraction of internal virus released at cell death', disabled=True, layout=desc_button_layout) desc_button15.style.button_color = 'lightgreen' desc_button16 = Button( description='multiplicity of infection: virions/cells at t=0', disabled=True, layout=desc_button_layout) desc_button16.style.button_color = 'tan' desc_button17 = Button( description='Infect center cell with one virion (overrides MOI)', disabled=True, layout=desc_button_layout) desc_button17.style.button_color = 'lightgreen' desc_button18 = Button( description='color cells based on this variable', disabled=True, layout=desc_button_layout) desc_button18.style.button_color = 'tan' row1 = [param_name1, self.random_seed, units_button1, desc_button1] row2 = [ param_name2, self.virion_uncoating_rate, units_button3, desc_button2 ] row3 = [ param_name3, self.uncoated_to_RNA_rate, units_button4, desc_button3 ] row4 = [ param_name4, self.protein_synthesis_rate, units_button5, desc_button4 ] row5 = [ param_name5, self.virion_assembly_rate, units_button6, desc_button5 ] row6 = [ param_name6, self.virion_export_rate, units_button8, desc_button6 ] row7 = [ param_name7, self.ACE2_receptors_per_cell, units_button10, desc_button7 ] row8 = [ param_name8, self.ACE2_binding_rate, units_button11, desc_button8 ] row9 = [ param_name9, self.ACE2_endocytosis_rate, units_button12, desc_button9 ] row10 = [ param_name10, self.ACE2_cargo_release_rate, units_button13, desc_button10 ] row11 = [ param_name11, self.ACE2_recycling_rate, units_button14, desc_button11 ] row12 = [ param_name12, self.max_infected_apoptosis_rate, units_button16, desc_button12 ] row13 = [ param_name13, self.max_apoptosis_half_max, units_button17, desc_button13 ] row14 = [ param_name14, self.apoptosis_hill_power, units_button18, desc_button14 ] row15 = [ param_name15, self.virus_fraction_released_at_death, units_button19, desc_button15 ] row16 = [ param_name16, self.multiplicity_of_infection, units_button21, desc_button16 ] row17 = [ param_name17, self.use_single_infected_cell, units_button22, desc_button17 ] row18 = [ param_name18, self.color_variable, units_button24, desc_button18 ] box_layout = Layout(display='flex', flex_flow='row', align_items='stretch', width='100%') box1 = Box(children=row1, layout=box_layout) box2 = Box(children=row2, layout=box_layout) box3 = Box(children=row3, layout=box_layout) box4 = Box(children=row4, layout=box_layout) box5 = Box(children=row5, layout=box_layout) box6 = Box(children=row6, layout=box_layout) box7 = Box(children=row7, layout=box_layout) box8 = Box(children=row8, layout=box_layout) box9 = Box(children=row9, layout=box_layout) box10 = Box(children=row10, layout=box_layout) box11 = Box(children=row11, layout=box_layout) box12 = Box(children=row12, layout=box_layout) box13 = Box(children=row13, layout=box_layout) box14 = Box(children=row14, layout=box_layout) box15 = Box(children=row15, layout=box_layout) box16 = Box(children=row16, layout=box_layout) box17 = Box(children=row17, layout=box_layout) box18 = Box(children=row18, layout=box_layout) self.tab = VBox([ box1, div_row1, box2, box3, box4, box5, div_row2, box6, div_row3, box7, box8, box9, box10, box11, div_row4, box12, box13, box14, box15, div_row5, box16, box17, div_row6, box18, ])
def time_series(path): import matplotlib.pyplot as plt import matplotlib.dates as mdates from datetime import timedelta import pandas as pd import json import glob confvalues = config.read() inst = confvalues['set']['institution'] file_info = glob.glob(f"{path}*_information.json")[0] with open(file_info, 'r') as f: info_data = json.loads(f.read()) pid = info_data['ogc_fid'][0] crop_name = info_data['cropname'][0] area = info_data['area'][0] figure_dpi = 50 def plot_ts_s2(cloud): file_ts = glob.glob(f"{path}*_time_series_s2.csv")[0] df = pd.read_csv(file_ts, index_col=0) df['date'] = pd.to_datetime(df['date_part'], unit='s') start_date = df.iloc[0]['date'].date() end_date = df.iloc[-1]['date'].date() print(f"From '{start_date}' to '{end_date}'.") pd.set_option('max_colwidth', 200) pd.set_option('display.max_columns', 20) # Plot settings are confirm IJRS graphics instructions plt.rcParams['axes.titlesize'] = 16 plt.rcParams['axes.labelsize'] = 14 plt.rcParams['xtick.labelsize'] = 12 plt.rcParams['ytick.labelsize'] = 12 plt.rcParams['legend.fontsize'] = 14 df.set_index(['date'], inplace=True) dfB4 = df[df.band == 'B4'].copy() dfB8 = df[df.band == 'B8'].copy() datesFmt = mdates.DateFormatter('%-d %b %Y') if cloud is False: # Plot NDVI fig = plt.figure(figsize=(16.0, 10.0)) axb = fig.add_subplot(1, 1, 1) axb.set_title( f"Parcel {pid} (crop: {crop_name}, area: {area:.2f} ha)") axb.set_xlabel("Date") axb.xaxis.set_major_formatter(datesFmt) axb.set_ylabel(r'DN') axb.plot(dfB4.index, dfB4['mean'], linestyle=' ', marker='s', markersize=10, color='DarkBlue', fillstyle='none', label='B4') axb.plot(dfB8.index, dfB8['mean'], linestyle=' ', marker='o', markersize=10, color='Red', fillstyle='none', label='B8') axb.set_xlim(start_date, end_date + timedelta(1)) axb.set_ylim(0, 10000) axb.legend(frameon=False) # loc=2) return plt.show() else: # Plot Cloud free NDVI. dfSC = df[df.band == 'SC'].copy() dfNDVI = (dfB8['mean'] - dfB4['mean']) / \ (dfB8['mean'] + dfB4['mean']) cloudfree = ((dfSC['mean'] >= 4) & (dfSC['mean'] < 6)) fig = plt.figure(figsize=(16.0, 10.0)) axb = fig.add_subplot(1, 1, 1) axb.set_title( f"{inst}\nParcel {pid} (crop: {crop_name}, area: {area:.2f} sqm)" ) axb.set_xlabel("Date") axb.xaxis.set_major_formatter(datesFmt) axb.set_ylabel(r'NDVI') axb.plot(dfNDVI.index, dfNDVI, linestyle=' ', marker='s', markersize=10, color='DarkBlue', fillstyle='none', label='NDVI') axb.plot(dfNDVI[cloudfree].index, dfNDVI[cloudfree], linestyle=' ', marker='P', markersize=10, color='Red', fillstyle='none', label='Cloud free NDVI') axb.set_xlim(start_date, end_date + timedelta(1)) axb.set_ylim(0, 1.0) axb.legend(frameon=False) # loc=2) return plt.show() def plot_ts_bs(): import numpy as np file_ts = glob.glob(f"{path}*_time_series_bs.csv")[0] df = pd.read_csv(file_ts, index_col=0) df['date'] = pd.to_datetime(df['date_part'], unit='s') start_date = df.iloc[0]['date'].date() end_date = df.iloc[-1]['date'].date() print(f"From '{start_date}' to '{end_date}'.") pd.set_option('max_colwidth', 200) pd.set_option('display.max_columns', 20) # Plot settings are confirm IJRS graphics instructions plt.rcParams['axes.titlesize'] = 16 plt.rcParams['axes.labelsize'] = 14 plt.rcParams['xtick.labelsize'] = 12 plt.rcParams['ytick.labelsize'] = 12 plt.rcParams['legend.fontsize'] = 14 df.set_index(['date'], inplace=True) datesFmt = mdates.DateFormatter('%-d %b %Y') # Plot Backscattering coefficient datesFmt = mdates.DateFormatter('%-d %b %Y') df = df[df['mean'] >= 0] # to remove negative values dfVV = df[df.band == 'VV'].copy() dfVH = df[df.band == 'VH'].copy() fig = plt.figure(figsize=(16.0, 10.0)) axb = fig.add_subplot(1, 1, 1) dfVV['mean'] = dfVV['mean'].map(lambda s: 10.0 * np.log10(s)) dfVH['mean'] = dfVH['mean'].map(lambda s: 10.0 * np.log10(s)) axb.set_title( f"{inst}\nParcel {pid} (crop: {crop_name}, area: {area:.2f} sqm)") axb.set_xlabel("Date") axb.xaxis.set_major_formatter(datesFmt) axb.set_ylabel(r'Backscattering coefficient, $\gamma\degree$ (dB)') axb.plot(dfVH.index, dfVH['mean'], linestyle=' ', marker='s', markersize=10, color='DarkBlue', fillstyle='none', label='VH') axb.plot(dfVV.index, dfVV['mean'], linestyle=' ', marker='o', markersize=10, color='Red', fillstyle='none', label='VV') axb.set_xlim(start_date, end_date + timedelta(1)) axb.set_ylim(-25, 0) axb.legend(frameon=False) # loc=2) return plt.show() def plot_ts_c6(): file_ts = glob.glob(f"{path}*_time_series_c6.csv")[0] df = pd.read_csv(file_ts, index_col=0) df['date'] = pd.to_datetime(df['date_part'], unit='s') start_date = df.iloc[0]['date'].date() end_date = df.iloc[-1]['date'].date() print(f"From '{start_date}' to '{end_date}'.") pd.set_option('max_colwidth', 200) pd.set_option('display.max_columns', 20) datesFmt = mdates.DateFormatter('%-d %b %Y') # Plot settings are confirm IJRS graphics instructions plt.rcParams['axes.titlesize'] = 16 plt.rcParams['axes.labelsize'] = 14 plt.rcParams['xtick.labelsize'] = 12 plt.rcParams['ytick.labelsize'] = 12 plt.rcParams['legend.fontsize'] = 14 df.set_index(['date'], inplace=True) # Plot Coherence dfVV = df[df.band == 'VV'].copy() dfVH = df[df.band == 'VH'].copy() fig = plt.figure(figsize=(16.0, 10.0)) axb = fig.add_subplot(1, 1, 1) axb.set_title( f"{inst}\nParcel {pid} (crop: {crop_name}, area: {area:.2f} sqm)") axb.set_xlabel("Date") axb.xaxis.set_major_formatter(datesFmt) axb.set_ylabel(r'Coherence') axb.plot(dfVH.index, dfVH['mean'], linestyle=' ', marker='s', markersize=10, color='DarkBlue', fillstyle='none', label='VH') axb.plot(dfVV.index, dfVV['mean'], linestyle=' ', marker='o', markersize=10, color='Red', fillstyle='none', label='VV') axb.set_xlim(start_date, end_date + timedelta(1)) axb.set_ylim(0, 1) axb.legend(frameon=False) # loc=2) return plt.show() ts_cloud = Checkbox(value=True, description='Cloud free', disabled=False, indent=False) ts_files = glob.glob(f"{path}*time_series*.csv") ts_file_types = [b.split('_')[-1].split('.')[0] for b in ts_files] ts_types = [t for t in data_options.pts_tstype() if t[1] in ts_file_types] ts_type = Dropdown( options=ts_types, description='Select type:', disabled=False, ) btn_ts = Button(value=False, description='Plot TS', disabled=False, button_style='info', tooltip='Refresh output', icon='') ts_out = Output() @btn_ts.on_click def btn_ts_on_click(b): btn_ts.description = 'Refresh' btn_ts.icon = 'refresh' with ts_out: ts_out.clear_output() if ts_type.value == 's2': plot_ts_s2(ts_cloud.value) elif ts_type.value == 'bs': plot_ts_bs() elif ts_type.value == 'c6': plot_ts_c6() def on_ts_type_change(change): if ts_type.value == 's2': wbox_ts.children = [btn_ts, ts_type, ts_cloud] else: wbox_ts.children = [btn_ts, ts_type] ts_type.observe(on_ts_type_change, 'value') wbox_ts = HBox([btn_ts, ts_type, ts_cloud]) wbox = VBox([wbox_ts, ts_out]) return wbox
# You can select any time series and any forecast date, just click on `Run Interact` to generate the predictions from our served endpoint and see the plot. # In[99]: style = {'description_width': 'initial'} # In[100]: @interact_manual(customer_id=IntSlider(min=0, max=369, value=91, style=style), forecast_day=IntSlider(min=0, max=100, value=51, style=style), confidence=IntSlider(min=60, max=95, value=80, step=5, style=style), history_weeks_plot=IntSlider(min=1, max=20, value=1, style=style), show_samples=Checkbox(value=False), continuous_update=False) def plot_interact(customer_id, forecast_day, confidence, history_weeks_plot, show_samples): plot(predictor, target_ts=timeseries[customer_id], forecast_date=end_training + datetime.timedelta(days=forecast_day), show_samples=show_samples, plot_history=history_weeks_plot * 12 * 7, confidence=confidence)
def all_options(analysis=True): options = Dropdown(options={ 'confined': 1, 'leaky aquifer': 2, 'flow barrier': 3, 'recharge source': 4, 'unconfined': 5 }, value=1, description='Aquifer type') approx = Checkbox(value=True, description='approx.') semilog = Checkbox(value=False, description='SemiLog') image = Checkbox(value=False, description='image') Q = FloatSlider(value=1000, description=r'$Q$ [m$^3$/day]', min=500, max=1500, step=500, continuous_update=False) t = FloatLogSlider(value=1.0, description=r'$t$ [day]', base=10, min=-1, max=2, step=0.2, continuous_update=False) r = FloatSlider(value=200, description=r'$r$ [m]', min=100, max=500, step=100, continuous_update=False) T = FloatSlider(value=300, description=r'$T$ [m$^2$/day]', min=100, max=500, step=100, continuous_update=False) c = FloatLogSlider(value=1.e5, description=r'$c$ [day]', base=10, min=2, max=6, step=1, continuous_update=False) H = FloatSlider(value=2, description=r'$b$ [m]', min=2, max=5, step=1.5, continuous_update=False) io = interactive_output( plot_theis, { 'Q': Q, 't': t, 'r': r, 'T': T, 'approx': approx, 'semilog': semilog, 'itest': options, 'image': image, 'c': c, 'H': H, 'analysis': fixed(analysis) }) return VBox([ HBox([options]), HBox([Q, t, approx]), HBox([T, r, semilog]), HBox([H, c, image]), io ])
def __init__(self): micron_units = Label('micron') # use "option m" (Mac, for micro symbol) constWidth = '180px' tab_height = '500px' stepsize = 10 #style = {'description_width': '250px'} style = {'description_width': '25%'} layout = {'width': '400px'} name_button_layout={'width':'25%'} widget_layout = {'width': '15%'} units_button_layout ={'width':'15%'} desc_button_layout={'width':'45%'} # divider_button_layout={'width':'40%', 'align_items':'left'} divider_button_layout={'width':'40%'} self.cell_parent_dict = {'lung epithelium':'default', 'immune':'default', 'CD8 Tcell':'immune'} self.cell_type = Dropdown(description='Cell:', options={'default':'default', 'lung epithelium':'lung epithelium', 'immune':'immune', 'CD8 Tcell':'CD8 Tcell'}) self.cell_type.style = {'description_width': '%sch' % str(len(self.cell_type.description) + 1)} self.cell_type.observe(self.cell_type_cb) self.parent_name = Text(value='None',placeholder='Type something',description='Parent:',disabled=True) menv_var1 = Button(description='director_signal', disabled=True, layout=name_button_layout) menv_var1.style.button_color = 'tan' param_name1 = Button(description='cycle trans rate', disabled=True, layout=name_button_layout) self.cycle_trans_rate = FloatText(value=1000, step=100,style=style, layout=widget_layout) param_name2 = Button(description='decay_rate', disabled=True, layout=name_button_layout) self.director_signal_decay_rate = FloatText(value=.1, step=0.01,style=style, layout=widget_layout) param_name3 = Button(description='initial_condition', disabled=True, layout=name_button_layout) self.director_signal_initial_condition = FloatText(value=0,style=style, layout=widget_layout) param_name4 = Button(description='Dirichlet_boundary_condition', disabled=True, layout=name_button_layout) self.director_signal_Dirichlet_boundary_condition = FloatText(value=1,style=style, layout=widget_layout) self.director_signal_Dirichlet_boundary_condition_toggle = Checkbox(description='on/off', disabled=False,style=style, layout=widget_layout) menv_var2 = Button(description='cargo_signal', disabled=True, layout=name_button_layout) menv_var2.style.button_color = 'lightgreen' param_name5 = Button(description='diffusion_coefficient', disabled=True, layout=name_button_layout) self.cargo_signal_diffusion_coefficient = FloatText(value=1000, step=100,style=style, layout=widget_layout) param_name6 = Button(description='decay_rate', disabled=True, layout=name_button_layout) self.cargo_signal_decay_rate = FloatText(value=.4, step=0.1,style=style, layout=widget_layout) param_name7 = Button(description='initial_condition', disabled=True, layout=name_button_layout) self.cargo_signal_initial_condition = FloatText(value=0,style=style, layout=widget_layout) param_name8 = Button(description='Dirichlet_boundary_condition', disabled=True, layout=name_button_layout) self.cargo_signal_Dirichlet_boundary_condition = FloatText(value=1,style=style, layout=widget_layout) self.cargo_signal_Dirichlet_boundary_condition_toggle = Checkbox(description='on/off', disabled=False,style=style, layout=widget_layout) self.calculate_gradient = Checkbox(description='calculate_gradients', disabled=False, layout=desc_button_layout) self.track_internal = Checkbox(description='track_in_agents', disabled=False, layout=desc_button_layout) row_director_signal = [menv_var1, ] box_layout = Layout(display='flex', flex_flow='row', align_items='stretch', width='100%') """ box_director_signal = Box(children=row_director_signal, layout=box_layout) box1 = Box(children=row1, layout=box_layout) box_cargo_signal = Box(children=row_cargo_signal, layout=box_layout) box5 = Box(children=row5, layout=box_layout) """ #-------------------------- div_cycle = Button(description='Phenotype:cycle', disabled=True, layout=divider_button_layout) param_name1 = Button(description='transition rate: 0->1', disabled=True, layout=name_button_layout) param_name1.style.button_color = 'tan' param_name1_units = Button(description='1/min', disabled=True, layout=units_button_layout) param_name1_units.style.button_color = 'tan' self.cycle_trans_rate1 = FloatText( value=0.0001, step=0.00001, style=style, layout=widget_layout) row1 = [param_name1, self.cycle_trans_rate1, param_name1_units] box1 = Box(children=row1, layout=box_layout) param_name2 = Button(description='transition rate: 1->2', disabled=True, layout=name_button_layout) param_name2.style.button_color = 'lightgreen' param_name2_units = Button(description='1/min', disabled=True, layout=units_button_layout) param_name2_units.style.button_color = 'lightgreen' self.cycle_trans_rate2 = FloatText( value=0.0002, step=0.00001, style=style, layout=widget_layout) row2 = [param_name2, self.cycle_trans_rate2, param_name2_units] box2 = Box(children=row2, layout=box_layout) #-------------------------- div_death = Button(description='Phenotype:death', disabled=True, layout=divider_button_layout) #-------------------------- div_volume = Button(description='Phenotype:volume', disabled=True, layout=divider_button_layout) param_name9 = Button(description='volume', disabled=True, layout=name_button_layout) param_name9.style.button_color = 'tan' param_name9_units = Button(description='micron^3', disabled=True, layout=units_button_layout) param_name9_units.style.button_color = 'tan' self.volume = FloatText( value=2.15e3, step=100, style=style, layout=widget_layout) row9 = [param_name9, self.volume, param_name9_units] box9 = Box(children=row9, layout=box_layout) #-------------------------- #-------------------------- div_mechanics = Button(description='Phenotype:mechanics', disabled=True, layout=divider_button_layout) #-------------------------- div_motility = Button(description='Phenotype:motility', disabled=True, layout=divider_button_layout) #-------------------------- div_secretion = Button(description='Phenotype:secretion', disabled=True, layout=divider_button_layout) #-------------------------- div_intracellular = Button(description='Phenotype:intracellular', disabled=True, layout=divider_button_layout) #-------------------------- div_custom_data = Button(description='Custom data', disabled=True, layout=divider_button_layout) # <elastic_coefficient length=”1” units=”1/min”>1.0</elastic_coefficient> # <attachment_point length=”3” units=”micron”>-12.8,13.9,0.0</attachment_point> param_name31 = Button(description='elastic_coefficient', disabled=True, layout=name_button_layout) param_name31.style.button_color = 'tan' param_name31_units = Button(description='1/min', disabled=True, layout=units_button_layout) param_name31_units.style.button_color = 'tan' self.custom_elastic_coef = FloatText( value=1.0, step=0.1, style=style, layout=widget_layout) row31 = [param_name31, self.custom_elastic_coef, param_name31_units] box31 = Box(children=row31, layout=box_layout) param_name32 = Button(description='attachment_point', disabled=True, layout=name_button_layout) param_name32.style.button_color = 'lightgreen' param_name32_units = Button(description='micron', disabled=True, layout=units_button_layout) param_name32_units.style.button_color = 'lightgreen' self.custom_attachment_point = Text( value="-12.8,13.9,0.0", style=style, layout=widget_layout) row32 = [param_name32, self.custom_attachment_point, param_name32_units] box32 = Box(children=row32, layout=box_layout) #-------------------------- self.vbox1 = VBox([ div_cycle, box1, box2, div_death, div_volume, box9, div_mechanics, div_motility, div_secretion, div_intracellular, div_custom_data, box31, box32, ]) self.vbox2 = VBox([ box1, ]) self.cell_stuff = self.vbox1 self.tab = VBox([ HBox([self.cell_type, self.parent_name]), self.vbox1, self.vbox2 ])
def time_series_widget(aoi, year, pid): path = normpath( join(config.get_value(['paths', 'temp']), aoi, str(year), str(pid))) # confvalues = config.read() # inst = confvalues['set']['institution'] file_info = normpath(join(path, 'info.json')) with open(file_info, 'r') as f: info_data = json.loads(f.read()) pid = info_data['pid'][0] ts_cloud = Checkbox(value=True, description='Cloud free', disabled=False, indent=False) ts_files = glob.glob(normpath(join(path, '*time_series*.csv'))) ts_file_types = [b.split('_')[-1].split('.')[0] for b in ts_files] if 's2' in ts_file_types: ts_file_types.append('ndvi') ts_types = [t for t in data_options.pts_tstype() if t[1] in ts_file_types] ts_type = Dropdown( options=ts_types, description='Select type:', disabled=False, ) btn_ts = Button(value=False, description='Plot TS', disabled=False, button_style='info', tooltip='Refresh output', icon='') ts_out = Output() @btn_ts.on_click def btn_ts_on_click(b): btn_ts.description = 'Refresh' btn_ts.icon = 'refresh' with ts_out: ts_out.clear_output() if ts_type.value == 's2': time_series.s2(aoi, str(year), str(pid), bands=['B4', 'B8']) elif ts_type.value == 'ndvi': time_series.ndvi(aoi, str(year), str(pid)) elif ts_type.value == 'bs': time_series.s1(aoi, str(year), str(pid), 'bs') elif ts_type.value == 'c6': time_series.s1(aoi, str(year), str(pid), 'c6') def on_ts_type_change(change): if ts_type.value == 's2': wbox_ts.children = [btn_ts, ts_type] else: wbox_ts.children = [btn_ts, ts_type] ts_type.observe(on_ts_type_change, 'value') wbox_ts = HBox([btn_ts, ts_type, ts_cloud]) wbox = VBox([wbox_ts, ts_out]) return wbox
def log_explorer(run_manager) -> VBox: # noqa: C901 def _update_fname_dropdown( run_manager, fname_dropdown, only_running_checkbox, only_failed_checkbox, sort_by_dropdown, contains_text, ): def on_click(_): current_value = fname_dropdown.value fnames = _get_fnames(run_manager, only_running_checkbox.value) if only_failed_checkbox.value: fnames = _failed_job_logs(fnames, run_manager, only_running_checkbox.value) if contains_text.value.strip() != "": fnames = _files_that_contain(fnames, contains_text.value.strip()) fnames = _sort_fnames(sort_by_dropdown.value, run_manager, fnames) fname_dropdown.options = fnames with suppress(Exception): fname_dropdown.value = current_value fname_dropdown.disabled = not fnames return on_click def _last_editted(fname: Path) -> float: try: return fname.stat().st_mtime except FileNotFoundError: return -1.0 async def _tail_log(fname: Path, textarea: Textarea) -> None: T = -2.0 # to make sure the update always triggers while True: await asyncio.sleep(2) try: T_new = _last_editted(fname) if T_new > T: textarea.value = _read_file(fname) T = T_new except asyncio.CancelledError: return except Exception: pass def _tail( dropdown, tail_button, textarea, update_button, only_running_checkbox, only_failed_checkbox, ): tail_task = None ioloop = asyncio.get_running_loop() def on_click(_): nonlocal tail_task if tail_task is None: fname = dropdown.options[dropdown.index] tail_task = ioloop.create_task(_tail_log(fname, textarea)) tail_button.description = "cancel tail log" tail_button.button_style = "danger" tail_button.icon = "window-close" dropdown.disabled = True update_button.disabled = True only_running_checkbox.disabled = True only_failed_checkbox.disabled = True else: tail_button.description = "tail log" tail_button.button_style = "info" tail_button.icon = "refresh" dropdown.disabled = False only_running_checkbox.disabled = False only_failed_checkbox.disabled = False update_button.disabled = False tail_task.cancel() tail_task = None return on_click def _on_dropdown_change(textarea): def on_change(change): if (change["type"] == "change" and change["name"] == "value" and change["new"] is not None): textarea.value = _read_file(change["new"]) return on_change def _click_button_on_change(button): def on_change(change): if change["type"] == "change" and change["name"] == "value": button.click() return on_change fnames = _get_fnames(run_manager, only_running=False) # no need to sort `fnames` because the default sort_by option is alphabetical text = _read_file(fnames[0]) if fnames else "" textarea = Textarea(text, layout=dict(width="auto"), rows=20) sort_by_dropdown = Dropdown( description="Sort by", options=[ "Alphabetical", "CPU %", "Mem %", "Last editted", "Loss", "npoints" ], ) contains_text = Text(description="Has string") fname_dropdown = Dropdown(description="File name", options=fnames) fname_dropdown.observe(_on_dropdown_change(textarea)) only_running_checkbox = Checkbox(description="Only files of running jobs", indent=False) only_failed_checkbox = Checkbox( description="Only files of failed jobs (might include false positives)", indent=False, ) update_button = Button(description="update file list", button_style="info", icon="refresh") update_button.on_click( _update_fname_dropdown( run_manager, fname_dropdown, only_running_checkbox, only_failed_checkbox, sort_by_dropdown, contains_text, )) sort_by_dropdown.observe(_click_button_on_change(update_button)) only_running_checkbox.observe(_click_button_on_change(update_button)) only_failed_checkbox.observe(_click_button_on_change(update_button)) tail_button = Button(description="tail log", button_style="info", icon="refresh") tail_button.on_click( _tail( fname_dropdown, tail_button, textarea, update_button, only_running_checkbox, only_failed_checkbox, )) title = HTML("<h2><tt>adaptive_scheduler.widgets.log_explorer</tt></h2>") return VBox( [ title, only_running_checkbox, only_failed_checkbox, update_button, sort_by_dropdown, contains_text, fname_dropdown, tail_button, textarea, ], layout=Layout(border="solid 2px gray"), )
def __init__(self): micron_units = Label( 'micron') # use "option m" (Mac, for micro symbol) constWidth = '180px' tab_height = '500px' stepsize = 10 #style = {'description_width': '250px'} style = {'description_width': '25%'} layout = {'width': '400px'} name_button_layout = {'width': '25%'} widget_layout = {'width': '15%'} widget2_layout = {'width': '10%'} units_button_layout = {'width': '15%'} desc_button_layout = {'width': '45%'} menv_var1 = Button(description='oxygen (mmHg)', disabled=True, layout=name_button_layout) menv_var1.style.button_color = 'tan' param_name1 = Button(description='diffusion_coefficient', disabled=True, layout=name_button_layout) self.oxygen_diffusion_coefficient = FloatText(value=100000.0, step=10000, style=style, layout=widget_layout) param_name2 = Button(description='decay_rate', disabled=True, layout=name_button_layout) self.oxygen_decay_rate = FloatText(value=0.0, step=0.01, style=style, layout=widget_layout) param_name3 = Button(description='initial_condition', disabled=True, layout=name_button_layout) self.oxygen_initial_condition = FloatText(value=1.5, style=style, layout=widget_layout) param_name4 = Button(description='Dirichlet_boundary_condition', disabled=True, layout=name_button_layout) self.oxygen_Dirichlet_boundary_condition = FloatText( value=2.4, style=style, layout=widget_layout) self.oxygen_Dirichlet_boundary_condition_toggle = Checkbox( description='on/off', disabled=False, style=style, layout=widget_layout) self.calculate_gradient = Checkbox(description='calculate_gradients', disabled=False, layout=desc_button_layout) self.track_internal = Checkbox(description='track_in_agents', disabled=False, layout=desc_button_layout) # ------- micronenv info menv_units_button1 = Button(description='micron^2/min', disabled=True, layout=units_button_layout) menv_units_button2 = Button(description='1/min', disabled=True, layout=units_button_layout) menv_units_button3 = Button(description='mmHg', disabled=True, layout=units_button_layout) menv_units_button4 = Button(description='mmHg', disabled=True, layout=units_button_layout) row_oxygen = [ menv_var1, ] row1 = [ param_name1, self.oxygen_diffusion_coefficient, menv_units_button1 ] row2 = [param_name2, self.oxygen_decay_rate, menv_units_button2] row3 = [param_name3, self.oxygen_initial_condition, menv_units_button3] row4 = [ param_name4, self.oxygen_Dirichlet_boundary_condition, menv_units_button4, self.oxygen_Dirichlet_boundary_condition_toggle ] row5 = [ self.calculate_gradient, ] row6 = [ self.track_internal, ] box_layout = Layout(display='flex', flex_flow='row', align_items='stretch', width='100%') box_oxygen = Box(children=row_oxygen, layout=box_layout) box1 = Box(children=row1, layout=box_layout) box2 = Box(children=row2, layout=box_layout) box3 = Box(children=row3, layout=box_layout) box4 = Box(children=row4, layout=box_layout) box5 = Box(children=row5, layout=box_layout) box6 = Box(children=row6, layout=box_layout) self.tab = VBox([ box_oxygen, box1, box2, box3, box4, box5, box6, ])
def display_palette_for_models(self): """Display visual controls for color palettes applied to models""" def set_colormap(model_id, colormap_name, shading_mode): material_ids = self._be.get_material_ids(model_id)['ids'] nb_materials = len(material_ids) palette = sns.color_palette(colormap_name, nb_materials) self._be.set_materials_from_palette( model_ids=[model_id], material_ids=material_ids, palette=palette, specular_exponent=specular_exponent_slider.value, shading_mode=shading_mode, opacity=opacity_slider.value, refraction_index=refraction_index_slider.value, reflection_index=reflection_index_slider.value, glossiness=glossiness_slider.value, user_parameter=user_param_slider.value, emission=emission_slider.value, chameleon_mode=chameleon_combobox.index) self._client.set_renderer(accumulation=True) # Models model_names = list() for model in self._client.scene.models: model_names.append(model['name']) model_combobox = Select(options=model_names, description='Models:', disabled=False) # Shading modes shading_combobox = Select(options=SHADING_MODES, description='Shading:', disabled=False) # Colors palette_combobox = Select(options=COLOR_MAPS, description='Palette:', disabled=False) # Chameleon modes chameleon_combobox = Select(options=CHAMELEON_MODES, description='Chameleon:', disabled=False) # Events def update_materials_from_palette(value): """Update materials when palette is modified""" set_colormap(self._client.scene.models[model_combobox.index]['id'], value['new'], shading_combobox.index) def update_materials_from_shading_modes(_): """Update materials when shading is modified""" set_colormap(self._client.scene.models[model_combobox.index]['id'], palette_combobox.value, shading_combobox.index) def update_materials_from_chameleon_modes(_): """Update materials when chameleon mode is modified""" set_colormap(self._client.scene.models[model_combobox.index]['id'], palette_combobox.value, shading_combobox.index) shading_combobox.observe(update_materials_from_shading_modes, 'value') palette_combobox.observe(update_materials_from_palette, 'value') chameleon_combobox.observe(update_materials_from_chameleon_modes, 'value') horizontal_box_list = HBox( [model_combobox, shading_combobox, palette_combobox]) opacity_slider = FloatSlider(description='Opacity', min=0, max=1, value=1) opacity_slider.observe(update_materials_from_shading_modes) refraction_index_slider = FloatSlider(description='Refraction', min=1, max=5, value=1) refraction_index_slider.observe(update_materials_from_shading_modes) reflection_index_slider = FloatSlider(description='Reflection', min=0, max=1, value=0) reflection_index_slider.observe(update_materials_from_shading_modes) glossiness_slider = FloatSlider(description='Glossiness', min=0, max=1, value=1) glossiness_slider.observe(update_materials_from_shading_modes) specular_exponent_slider = FloatSlider(description='Specular exponent', min=1, max=100, value=1) specular_exponent_slider.observe(update_materials_from_shading_modes) user_param_slider = FloatSlider(description='User param', min=0, max=100, value=1) user_param_slider.observe(update_materials_from_shading_modes) emission_slider = FloatSlider(description='Emission', min=0, max=100, value=0) emission_slider.observe(update_materials_from_shading_modes) cast_simulation_checkbox = Checkbox(description='Simulation', value=False) cast_simulation_checkbox.observe(update_materials_from_shading_modes) horizontal_box_detail1 = HBox( [opacity_slider, refraction_index_slider, reflection_index_slider]) horizontal_box_detail2 = HBox( [glossiness_slider, specular_exponent_slider, user_param_slider]) horizontal_box_detail3 = HBox( [emission_slider, cast_simulation_checkbox, chameleon_combobox]) vertical_box = VBox([ horizontal_box_list, horizontal_box_detail1, horizontal_box_detail2, horizontal_box_detail3 ], layout=DEFAULT_GRID_LAYOUT) display(vertical_box)
def __init__(self): micron_units = Label( 'micron') # use "option m" (Mac, for micro symbol) constWidth = '180px' tab_height = '500px' stepsize = 10 #style = {'description_width': '250px'} style = {'description_width': '25%'} layout = {'width': '400px'} name_button_layout = {'width': '25%'} widget_layout = {'width': '15%'} units_button_layout = {'width': '15%'} desc_button_layout = {'width': '45%'} menv_var1 = Button(description='virion (virion/micron^3)', disabled=True, layout=name_button_layout) menv_var1.style.button_color = 'tan' param_name1 = Button(description='diffusion_coefficient', disabled=True, layout=name_button_layout) self.virion_diffusion_coefficient = FloatText(value=2.5, step=0.1, style=style, layout=widget_layout) param_name2 = Button(description='decay_rate', disabled=True, layout=name_button_layout) self.virion_decay_rate = FloatText(value=0, step=0.01, style=style, layout=widget_layout) param_name3 = Button(description='initial_condition', disabled=True, layout=name_button_layout) self.virion_initial_condition = FloatText(value=0, style=style, layout=widget_layout) param_name4 = Button(description='Dirichlet_boundary_condition', disabled=True, layout=name_button_layout) self.virion_Dirichlet_boundary_condition = FloatText( value=0, style=style, layout=widget_layout) self.virion_Dirichlet_boundary_condition_toggle = Checkbox( description='on/off', disabled=False, style=style, layout=widget_layout) menv_var2 = Button(description='assembled_virion (virion/micron^3)', disabled=True, layout=name_button_layout) menv_var2.style.button_color = 'lightgreen' param_name5 = Button(description='diffusion_coefficient', disabled=True, layout=name_button_layout) self.assembled_virion_diffusion_coefficient = FloatText( value=2.5, step=0.1, style=style, layout=widget_layout) param_name6 = Button(description='decay_rate', disabled=True, layout=name_button_layout) self.assembled_virion_decay_rate = FloatText(value=0, step=0.01, style=style, layout=widget_layout) param_name7 = Button(description='initial_condition', disabled=True, layout=name_button_layout) self.assembled_virion_initial_condition = FloatText( value=0, style=style, layout=widget_layout) param_name8 = Button(description='Dirichlet_boundary_condition', disabled=True, layout=name_button_layout) self.assembled_virion_Dirichlet_boundary_condition = FloatText( value=0, style=style, layout=widget_layout) self.assembled_virion_Dirichlet_boundary_condition_toggle = Checkbox( description='on/off', disabled=False, style=style, layout=widget_layout) menv_var3 = Button(description='interferon_1 (mol/micron^3)', disabled=True, layout=name_button_layout) menv_var3.style.button_color = 'tan' param_name9 = Button(description='diffusion_coefficient', disabled=True, layout=name_button_layout) self.interferon_1_diffusion_coefficient = FloatText( value=555.56, step=10, style=style, layout=widget_layout) param_name10 = Button(description='decay_rate', disabled=True, layout=name_button_layout) self.interferon_1_decay_rate = FloatText(value=1.02e-2, step=0.001, style=style, layout=widget_layout) param_name11 = Button(description='initial_condition', disabled=True, layout=name_button_layout) self.interferon_1_initial_condition = FloatText(value=0, style=style, layout=widget_layout) param_name12 = Button(description='Dirichlet_boundary_condition', disabled=True, layout=name_button_layout) self.interferon_1_Dirichlet_boundary_condition = FloatText( value=0, style=style, layout=widget_layout) self.interferon_1_Dirichlet_boundary_condition_toggle = Checkbox( description='on/off', disabled=False, style=style, layout=widget_layout) menv_var4 = Button( description='pro_inflammatory_cytokine (mol/micron^3)', disabled=True, layout=name_button_layout) menv_var4.style.button_color = 'lightgreen' param_name13 = Button(description='diffusion_coefficient', disabled=True, layout=name_button_layout) self.pro_inflammatory_cytokine_diffusion_coefficient = FloatText( value=555.56, step=10, style=style, layout=widget_layout) param_name14 = Button(description='decay_rate', disabled=True, layout=name_button_layout) self.pro_inflammatory_cytokine_decay_rate = FloatText( value=1.02e-2, step=0.001, style=style, layout=widget_layout) param_name15 = Button(description='initial_condition', disabled=True, layout=name_button_layout) self.pro_inflammatory_cytokine_initial_condition = FloatText( value=0, style=style, layout=widget_layout) param_name16 = Button(description='Dirichlet_boundary_condition', disabled=True, layout=name_button_layout) self.pro_inflammatory_cytokine_Dirichlet_boundary_condition = FloatText( value=0, style=style, layout=widget_layout) self.pro_inflammatory_cytokine_Dirichlet_boundary_condition_toggle = Checkbox( description='on/off', disabled=False, style=style, layout=widget_layout) menv_var5 = Button(description='chemokine (mol/micron^3)', disabled=True, layout=name_button_layout) menv_var5.style.button_color = 'tan' param_name17 = Button(description='diffusion_coefficient', disabled=True, layout=name_button_layout) self.chemokine_diffusion_coefficient = FloatText(value=555.56, step=10, style=style, layout=widget_layout) param_name18 = Button(description='decay_rate', disabled=True, layout=name_button_layout) self.chemokine_decay_rate = FloatText(value=1.02e-2, step=0.001, style=style, layout=widget_layout) param_name19 = Button(description='initial_condition', disabled=True, layout=name_button_layout) self.chemokine_initial_condition = FloatText(value=0, style=style, layout=widget_layout) param_name20 = Button(description='Dirichlet_boundary_condition', disabled=True, layout=name_button_layout) self.chemokine_Dirichlet_boundary_condition = FloatText( value=0, style=style, layout=widget_layout) self.chemokine_Dirichlet_boundary_condition_toggle = Checkbox( description='on/off', disabled=False, style=style, layout=widget_layout) menv_var6 = Button(description='debris (mol/micron^3)', disabled=True, layout=name_button_layout) menv_var6.style.button_color = 'lightgreen' param_name21 = Button(description='diffusion_coefficient', disabled=True, layout=name_button_layout) self.debris_diffusion_coefficient = FloatText(value=555.56, step=10, style=style, layout=widget_layout) param_name22 = Button(description='decay_rate', disabled=True, layout=name_button_layout) self.debris_decay_rate = FloatText(value=1.02e-2, step=0.001, style=style, layout=widget_layout) param_name23 = Button(description='initial_condition', disabled=True, layout=name_button_layout) self.debris_initial_condition = FloatText(value=0, style=style, layout=widget_layout) param_name24 = Button(description='Dirichlet_boundary_condition', disabled=True, layout=name_button_layout) self.debris_Dirichlet_boundary_condition = FloatText( value=0, style=style, layout=widget_layout) self.debris_Dirichlet_boundary_condition_toggle = Checkbox( description='on/off', disabled=False, style=style, layout=widget_layout) self.calculate_gradient = Checkbox(description='calculate_gradients', disabled=False, layout=desc_button_layout) self.track_internal = Checkbox(description='track_in_agents', disabled=False, layout=desc_button_layout) # ------- micronenv info menv_units_button1 = Button(description='micron^2/min', disabled=True, layout=units_button_layout) menv_units_button2 = Button(description='1/min', disabled=True, layout=units_button_layout) menv_units_button3 = Button(description='virion/micron^3', disabled=True, layout=units_button_layout) menv_units_button4 = Button(description='virion/micron^3', disabled=True, layout=units_button_layout) menv_units_button5 = Button(description='micron^2/min', disabled=True, layout=units_button_layout) menv_units_button6 = Button(description='1/min', disabled=True, layout=units_button_layout) menv_units_button7 = Button(description='virion/micron^3', disabled=True, layout=units_button_layout) menv_units_button8 = Button(description='virion/micron^3', disabled=True, layout=units_button_layout) menv_units_button9 = Button(description='micron^2/min', disabled=True, layout=units_button_layout) menv_units_button10 = Button(description='1/min', disabled=True, layout=units_button_layout) menv_units_button11 = Button(description='mol/micron^3', disabled=True, layout=units_button_layout) menv_units_button12 = Button(description='mol/micron^3', disabled=True, layout=units_button_layout) menv_units_button13 = Button(description='micron^2/min', disabled=True, layout=units_button_layout) menv_units_button14 = Button(description='1/min', disabled=True, layout=units_button_layout) menv_units_button15 = Button(description='mol/micron^3', disabled=True, layout=units_button_layout) menv_units_button16 = Button(description='mol/micron^3', disabled=True, layout=units_button_layout) menv_units_button17 = Button(description='micron^2/min', disabled=True, layout=units_button_layout) menv_units_button18 = Button(description='1/min', disabled=True, layout=units_button_layout) menv_units_button19 = Button(description='mol/micron^3', disabled=True, layout=units_button_layout) menv_units_button20 = Button(description='mol/micron^3', disabled=True, layout=units_button_layout) menv_units_button21 = Button(description='micron^2/min', disabled=True, layout=units_button_layout) menv_units_button22 = Button(description='1/min', disabled=True, layout=units_button_layout) menv_units_button23 = Button(description='mol/micron^3', disabled=True, layout=units_button_layout) menv_units_button24 = Button(description='mol/micron^3', disabled=True, layout=units_button_layout) row_virion = [ menv_var1, ] row1 = [ param_name1, self.virion_diffusion_coefficient, menv_units_button1 ] row2 = [param_name2, self.virion_decay_rate, menv_units_button2] row3 = [param_name3, self.virion_initial_condition, menv_units_button3] row4 = [ param_name4, self.virion_Dirichlet_boundary_condition, menv_units_button4, self.virion_Dirichlet_boundary_condition_toggle ] row_assembled_virion = [ menv_var2, ] row5 = [ param_name5, self.assembled_virion_diffusion_coefficient, menv_units_button5 ] row6 = [ param_name6, self.assembled_virion_decay_rate, menv_units_button6 ] row7 = [ param_name7, self.assembled_virion_initial_condition, menv_units_button7 ] row8 = [ param_name8, self.assembled_virion_Dirichlet_boundary_condition, menv_units_button8, self.assembled_virion_Dirichlet_boundary_condition_toggle ] row_interferon_1 = [ menv_var3, ] row9 = [ param_name9, self.interferon_1_diffusion_coefficient, menv_units_button9 ] row10 = [ param_name10, self.interferon_1_decay_rate, menv_units_button10 ] row11 = [ param_name11, self.interferon_1_initial_condition, menv_units_button11 ] row12 = [ param_name12, self.interferon_1_Dirichlet_boundary_condition, menv_units_button12, self.interferon_1_Dirichlet_boundary_condition_toggle ] row_pro_inflammatory_cytokine = [ menv_var4, ] row13 = [ param_name13, self.pro_inflammatory_cytokine_diffusion_coefficient, menv_units_button13 ] row14 = [ param_name14, self.pro_inflammatory_cytokine_decay_rate, menv_units_button14 ] row15 = [ param_name15, self.pro_inflammatory_cytokine_initial_condition, menv_units_button15 ] row16 = [ param_name16, self.pro_inflammatory_cytokine_Dirichlet_boundary_condition, menv_units_button16, self.pro_inflammatory_cytokine_Dirichlet_boundary_condition_toggle ] row_chemokine = [ menv_var5, ] row17 = [ param_name17, self.chemokine_diffusion_coefficient, menv_units_button17 ] row18 = [param_name18, self.chemokine_decay_rate, menv_units_button18] row19 = [ param_name19, self.chemokine_initial_condition, menv_units_button19 ] row20 = [ param_name20, self.chemokine_Dirichlet_boundary_condition, menv_units_button20, self.chemokine_Dirichlet_boundary_condition_toggle ] row_debris = [ menv_var6, ] row21 = [ param_name21, self.debris_diffusion_coefficient, menv_units_button21 ] row22 = [param_name22, self.debris_decay_rate, menv_units_button22] row23 = [ param_name23, self.debris_initial_condition, menv_units_button23 ] row24 = [ param_name24, self.debris_Dirichlet_boundary_condition, menv_units_button24, self.debris_Dirichlet_boundary_condition_toggle ] row25 = [ self.calculate_gradient, ] row26 = [ self.track_internal, ] box_layout = Layout(display='flex', flex_flow='row', align_items='stretch', width='100%') box_virion = Box(children=row_virion, layout=box_layout) box1 = Box(children=row1, layout=box_layout) box2 = Box(children=row2, layout=box_layout) box3 = Box(children=row3, layout=box_layout) box4 = Box(children=row4, layout=box_layout) box_assembled_virion = Box(children=row_assembled_virion, layout=box_layout) box5 = Box(children=row5, layout=box_layout) box6 = Box(children=row6, layout=box_layout) box7 = Box(children=row7, layout=box_layout) box8 = Box(children=row8, layout=box_layout) box_interferon_1 = Box(children=row_interferon_1, layout=box_layout) box9 = Box(children=row9, layout=box_layout) box10 = Box(children=row10, layout=box_layout) box11 = Box(children=row11, layout=box_layout) box12 = Box(children=row12, layout=box_layout) box_pro_inflammatory_cytokine = Box( children=row_pro_inflammatory_cytokine, layout=box_layout) box13 = Box(children=row13, layout=box_layout) box14 = Box(children=row14, layout=box_layout) box15 = Box(children=row15, layout=box_layout) box16 = Box(children=row16, layout=box_layout) box_chemokine = Box(children=row_chemokine, layout=box_layout) box17 = Box(children=row17, layout=box_layout) box18 = Box(children=row18, layout=box_layout) box19 = Box(children=row19, layout=box_layout) box20 = Box(children=row20, layout=box_layout) box_debris = Box(children=row_debris, layout=box_layout) box21 = Box(children=row21, layout=box_layout) box22 = Box(children=row22, layout=box_layout) box23 = Box(children=row23, layout=box_layout) box24 = Box(children=row24, layout=box_layout) box25 = Box(children=row25, layout=box_layout) box26 = Box(children=row26, layout=box_layout) self.tab = VBox([ box_virion, box1, box2, box3, box4, box_assembled_virion, box5, box6, box7, box8, box_interferon_1, box9, box10, box11, box12, box_pro_inflammatory_cytokine, box13, box14, box15, box16, box_chemokine, box17, box18, box19, box20, box_debris, box21, box22, box23, box24, box25, box26, ])
def __init__(self, dataset_voc, output_path_statistic, name, metrics, # this is an array of the following ['occ', 'truncated', 'side', 'part'] show_name=True, show_axis=False, fig_size=(10, 10), buttons_vertical=False, image_display_function=None, classes_to_annotate=None ): if dataset_voc.annotations_gt is None: # in case that dataset_voc has not been called dataset_voc.load() self.dataset_voc = dataset_voc self.metrics = metrics self.show_axis = show_axis self.name = name self.show_name = show_name if output_path_statistic is None: output_path_statistic = self.dataset_voc.dataset_root_param if classes_to_annotate is None: # if classes_to_annotate is None, all the classes would be annotated self.classes_to_annotate = self.dataset_voc.objnames_all # otherwise, the only the classes in the list self.output_path = output_path_statistic self.file_path = os.path.join(self.output_path, self.name + ".json") self.mapping, self.dataset = self.__create_results_dict(self.file_path, metrics) self.objects = dataset_voc.get_objects_index(self.classes_to_annotate) self.current_pos = 0 self.max_pos = len(self.objects) - 1 self.fig_size = fig_size self.buttons_vertical = buttons_vertical if image_display_function is None: self.image_display_function = self.__show_image else: self.image_display_function = image_display_function # create buttons self.previous_button = self.__create_button("Previous", (self.current_pos == 0), self.__on_previous_clicked) self.next_button = self.__create_button("Next", (self.current_pos == self.max_pos), self.__on_next_clicked) self.save_button = self.__create_button("Save", False, self.__on_save_clicked) self.save_function = self.__save_function # save_function self.current_image = {} buttons = [self.previous_button, self.next_button] buttons.append(self.save_button) label_total = Label(value='/ {}'.format(len(self.objects))) self.text_index = BoundedIntText(value=1, min=1, max=len(self.objects)) self.text_index.layout.width = '80px' self.text_index.layout.height = '35px' self.text_index.observe(self.__selected_index) self.out = Output() self.out.add_class(name) metrics_labels = self.dataset_voc.read_label_metrics_name_from_file() metrics_labels['truncated'] = {'0': 'False', '1': 'True'} self.metrics_labels = metrics_labels self.checkboxes = {} self.radiobuttons = {} output_layout = [] for m_i, m_n in enumerate(self.metrics): if 'parts' == m_n: # Special case continue if m_n in ['truncated', 'occ']: # radiobutton self.radiobuttons[m_n] = RadioButtons(options=[i for i in metrics_labels[m_n].values()], disabled=False, indent=False) else: # checkbox self.checkboxes[m_n] = [Checkbox(False, description='{}'.format(metrics_labels[m_n][i]), indent=False) for i in metrics_labels[m_n].keys()] self.check_radio_boxes_layout = {} for cb_k, cb_i in self.checkboxes.items(): for cb in cb_i: cb.layout.width = '180px' cb.observe(self.__checkbox_changed) html_title = HTML(value="<b>" + cb_k + "</b>") self.check_radio_boxes_layout[cb_k] = VBox(children=[cb for cb in cb_i]) output_layout.append(VBox([html_title, self.check_radio_boxes_layout[cb_k]])) for rb_k, rb_v in self.radiobuttons.items(): rb_v.layout.width = '180px' rb_v.observe(self.__checkbox_changed) html_title = HTML(value="<b>" + rb_k + "</b>") self.check_radio_boxes_layout[rb_k] = VBox([rb_v]) output_layout.append(VBox([html_title, self.check_radio_boxes_layout[rb_k]])) #create an output for the future dynamic SIDES_PARTS attributes self.dynamic_output_for_parts = Output() html_title = HTML(value="<b>" + "Parts" + "</b>") output_layout.append(VBox([html_title, self.dynamic_output_for_parts])) self.all_widgets = VBox(children= [HBox([self.text_index, label_total]), HBox(buttons), HBox(output_layout), self.out]) ## loading js library to perform html screenshots j_code = """ require.config({ paths: { html2canvas: "https://html2canvas.hertzen.com/dist/html2canvas.min" } }); """ display(Javascript(j_code))
def create_checkbox(self, kind, description, value, handler): checkbox = Checkbox(value=value, description=description, indent=False) checkbox.observe(handler, "value") checkbox.add_class("view_%s" % kind) return checkbox
def show_m(): multipoly = [] multycent = [] geom = view_spatial.trasform_geometry(info_data) poly = geom['coordinates'][0][0] # poly = view_spatial.swap_xy(geom['coordinates'][0])[0] multipoly.append(poly) cent = view_spatial.centroid(poly) multycent.append(cent) cent = view_spatial.centroid(multycent) m = Map(center=cent, zoom=16, basemap=basemaps.OpenStreetMap.Mapnik) polygon = Polygon(locations=multipoly, name='Parcel polygon', color="yellow", fill_color=None) m.add_layer(polygon) basemap2 = basemap_to_tiles(basemaps.Esri.WorldImagery) poly_text = HTML() poly_text.value = f"""Parcel ID: {pid}<br> Crop name: {crop_name}<br> Area: {area:.2f} sqm<br> Coordinates: {cent} """ poly_text.placeholder = "HTML" poly_text.description = "" # Popup with a given location on the map: poly_popup = Popup(child=poly_text, close_button=False, auto_close=False, close_on_escape_key=False) m.add_layer(poly_popup) # Popup associated to a layer polygon.popup = poly_popup # Layers control show_poly = Checkbox(value=True, description='Polygon', disabled=False, indent=False, layout=Layout(width='140px')) show_sat = Checkbox(value=False, description='High res basemap', disabled=False, indent=False, layout=Layout(width='140px')) def polygon_changed(b): try: if show_poly.value is True: m.add_layer(polygon) else: m.remove_layer(polygon) except Exception: pass show_poly.observe(polygon_changed) def show_sat_changed(b): try: if show_sat.value is True: m.add_layer(basemap2) else: m.remove_layer(basemap2) except Exception: pass show_sat.observe(show_sat_changed) try: csv_list = f"{ci_path}{pid}_images_list.{ci_band.value[0]}.csv" df = view_images.create_df(ci_path, pid, ci_band.value) geotiff = f"{ci_path}{df['imgs'][0]}.{ci_band.value[0]}.tif" bounds = view_spatial.bounds(geotiff) images = {} for i, row in df.iterrows(): str_date = str(row['date'].date()).replace('-', '') workdir = os.getcwd().split('/')[-1] img_tc = f"{ci_path}{('').join(ci_band.value)}_{str_date}.png" # Create false color image if it does not exist # Merge bands (images path, export image path, bands list) if not os.path.isfile(img_tc): imgs_path = f"{ci_path}{row['imgs']}" view_images.merge_bands(imgs_path, img_tc, ci_band.value) values = config.read() # Set the current environment if eval(values['set']['jupyterlab']) is True: image_path = f'files/{workdir}/{img_tc}' else: image_path = img_tc images[i] = ImageOverlay(url=image_path, name=str_date, bounds=(bounds)) # Time slider slider = IntSlider(value=1, min=1, max=len(images), step=1, description=str(df['date'][0].date()), disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d') show_chip = Checkbox(value=True, description='Chip image', disabled=False, indent=False, layout=Layout(width='140px')) def on_ci_band_change(change): pass ci_band.observe(on_ci_band_change, 'value') def show_chip_changed(b): try: if show_chip.value is True: m.add_layer(images[slider.value - 1]) else: m.remove_layer(images[slider.value - 1]) except Exception: pass show_chip.observe(show_chip_changed) # Slider control play = Play(value=1, min=1, max=len(images), step=1, interval=1000, description="Press play", disabled=False) def slider_changed(b): if show_chip.value is True: try: m.substitute_layer(images[b['old'] - 1], images[b['new'] - 1]) except Exception: pass slider.description = str(df['date'][slider.value - 1].date()) slider.observe(slider_changed) jslink((play, 'value'), (slider, 'value')) time_box = HBox([slider, play]) time_control = WidgetControl(widget=time_box, position='bottomleft') m.add_control(time_control) m.add_layer(images[0]) map_options = VBox([show_poly, show_chip, show_sat]) except Exception as err: map_options = VBox([show_poly, show_sat]) print(err) layers_control = WidgetControl(widget=map_options, position='topright', max_width=150) m.add_control(layers_control) return m
def __init__(self): tab_height = '520px' tab_layout = Layout( width='800px', # border='2px solid black', height=tab_height, overflow_y='scroll') self.output_dir = '.' max_frames = 505 # first time + 30240 / 60 self.svg_plot = interactive(self.plot_svg, frame=(0, max_frames), continuous_update=False) svg_plot_size = '500px' self.svg_plot.layout.width = svg_plot_size self.svg_plot.layout.height = svg_plot_size self.use_defaults = True self.show_nucleus = 0 # 0->False, 1->True in Checkbox! self.show_edge = 1 # 0->False, 1->True in Checkbox! self.scale_radius = 1.0 self.axes_min = 0.0 self.axes_max = 2000 # hmm, this can change (TODO?) # self.tab = HBox([svg_plot], layout=tab_layout) self.max_frames = BoundedIntText( min=0, max=99999, value=max_frames, description='Max', layout=Layout(flex='1 1 auto', width='auto'), #Layout(width='160px'), ) self.max_frames.observe(self.update_max_frames) self.show_nucleus_checkbox = Checkbox( description='nucleus', value=False, disabled=False, layout=Layout(flex='1 1 auto', width='auto'), #Layout(width='160px'), ) self.show_nucleus_checkbox.observe(self.show_nucleus_cb) self.show_edge_checkbox = Checkbox( description='edge', value=True, disabled=False, layout=Layout(flex='1 1 auto', width='auto'), #Layout(width='160px'), ) self.show_edge_checkbox.observe(self.show_edge_cb) # row1 = HBox([Label('(select slider: drag or left/right arrows)'), # self.max_frames, VBox([self.show_nucleus_checkbox, self.show_edge_checkbox])]) # self.max_frames, self.show_nucleus_checkbox], layout=Layout(width='500px')) # self.tab = VBox([row1,self.svg_plot], layout=tab_layout) items_auto = [ Label('(select slider: drag or left/right arrows)'), self.max_frames, self.show_nucleus_checkbox, self.show_edge_checkbox, ] #row1 = HBox([Label('(select slider: drag or left/right arrows)'), # max_frames, show_nucleus_checkbox, show_edge_checkbox], # layout=Layout(width='800px')) box_layout = Layout(display='flex', flex_flow='row', align_items='stretch', width='90%') row1 = Box(children=items_auto, layout=box_layout) self.tab = VBox([row1, self.svg_plot], layout=tab_layout)
def __init__(self): self.output_dir = '.' # self.output_dir = 'tmpdir' # self.fig = plt.figure(figsize=(7.2,6)) # this strange figsize results in a ~square contour plot # initial value self.field_index = 4 # self.field_index = self.mcds_field.value + 4 tab_height = '500px' constWidth = '180px' constWidth2 = '150px' tab_layout = Layout( width='900px', # border='2px solid black', height=tab_height, ) #overflow_y='scroll') max_frames = 1 self.mcds_plot = interactive(self.plot_substrate, frame=(0, max_frames), continuous_update=False) svg_plot_size = '700px' self.mcds_plot.layout.width = svg_plot_size self.mcds_plot.layout.height = svg_plot_size self.max_frames = BoundedIntText( min=0, max=99999, value=max_frames, description='Max', layout=Layout(width='160px'), ) self.max_frames.observe(self.update_max_frames) self.field_min_max = {'dummy': [0., 1.]} # hacky I know, but make a dict that's got (key,value) reversed from the dict in the Dropdown below self.field_dict = {0: 'dummy'} self.mcds_field = Dropdown( options={'dummy': 0}, value=0, # description='Field', layout=Layout(width=constWidth)) # print("substrate __init__: self.mcds_field.value=",self.mcds_field.value) # self.mcds_field.observe(self.mcds_field_cb) self.mcds_field.observe(self.mcds_field_changed_cb) # self.field_cmap = Text( # value='viridis', # description='Colormap', # disabled=True, # layout=Layout(width=constWidth), # ) self.field_cmap = Dropdown( options=['viridis', 'jet', 'YlOrRd'], value='viridis', # description='Field', layout=Layout(width=constWidth)) #self.field_cmap.observe(self.plot_substrate) # self.field_cmap.observe(self.plot_substrate) self.field_cmap.observe(self.mcds_field_cb) self.cmap_fixed = Checkbox( description='Fix', disabled=False, # layout=Layout(width=constWidth2), ) self.save_min_max = Button( description='Save', #style={'description_width': 'initial'}, button_style= 'success', # 'success', 'info', 'warning', 'danger' or '' tooltip='Save min/max for this substrate', disabled=True, layout=Layout(width='90px')) def save_min_max_cb(b): # field_name = self.mcds_field.options[] # field_name = next(key for key, value in self.mcds_field.options.items() if value == self.mcds_field.value) field_name = self.field_dict[self.mcds_field.value] # print(field_name) # self.field_min_max = {'oxygen': [0., 30.], 'glucose': [0., 1.], 'H+ ions': [0., 1.], 'ECM': [0., 1.], 'NP1': [0., 1.], 'NP2': [0., 1.]} self.field_min_max[field_name][0] = self.cmap_min.value self.field_min_max[field_name][1] = self.cmap_max.value # print(self.field_min_max) self.save_min_max.on_click(save_min_max_cb) self.cmap_min = FloatText( description='Min', value=0, step=0.1, disabled=True, layout=Layout(width=constWidth2), ) self.cmap_min.observe(self.mcds_field_cb) self.cmap_max = FloatText( description='Max', value=38, step=0.1, disabled=True, layout=Layout(width=constWidth2), ) self.cmap_max.observe(self.mcds_field_cb) def cmap_fixed_cb(b): if (self.cmap_fixed.value): self.cmap_min.disabled = False self.cmap_max.disabled = False self.save_min_max.disabled = False else: self.cmap_min.disabled = True self.cmap_max.disabled = True self.save_min_max.disabled = True # self.mcds_field_cb() self.cmap_fixed.observe(cmap_fixed_cb) field_cmap_row2 = HBox([self.field_cmap, self.cmap_fixed]) # field_cmap_row3 = HBox([self.save_min_max, self.cmap_min, self.cmap_max]) items_auto = [ self.save_min_max, #layout=Layout(flex='3 1 auto', width='auto'), self.cmap_min, self.cmap_max, ] box_layout = Layout(display='flex', flex_flow='row', align_items='stretch', width='80%') field_cmap_row3 = Box(children=items_auto, layout=box_layout) # field_cmap_row3 = Box([self.save_min_max, self.cmap_min, self.cmap_max]) # mcds_tab = widgets.VBox([mcds_dir, mcds_plot, mcds_play], layout=tab_layout) mcds_params = VBox([ self.mcds_field, field_cmap_row2, field_cmap_row3, self.max_frames ]) # mcds_dir # mcds_params = VBox([self.mcds_field, field_cmap_row2, field_cmap_row3,]) # mcds_dir # self.tab = HBox([mcds_params, self.mcds_plot], layout=tab_layout) # self.tab = HBox([mcds_params, self.mcds_plot]) help_label = Label('select slider: drag or left/right arrows') row1 = Box([ help_label, Box([self.max_frames, self.mcds_field, self.field_cmap], layout=Layout(border='0px solid black', width='50%', height='', align_items='stretch', flex_direction='row', display='flex')) ]) row2 = Box([self.cmap_fixed, self.cmap_min, self.cmap_max], layout=Layout(border='0px solid black', width='50%', height='', align_items='stretch', flex_direction='row', display='flex')) self.tab = VBox([row1, row2, self.mcds_plot])
def create_multi_answer_widget(question, options): question_widget = create_question_widget(question) # Need to make my own checkbox out of checkbox + label because LaTeX not displaying nicely in checkbox built in description label labels = [ widgets.HTML(value='<style>p{word-wrap: break-word}</style> <p>' + option['answer'] + ' </p>') for option in options ] checkboxes = [ HBox([ Checkbox(value=False, style={'description_width': 'initial'}, layout=Layout(width='30px')), lbl ], layout=Layout(display='flex', flex_flow='row wrap', align_items='stretch', width='auto')) for lbl in labels ] # for each option, create a feedback box on the left and a checkbox on the right vertical = [] for cb in checkboxes: new_hbox = widgets.HBox([Label(value=''), cb], layout=Layout(display='flex', flex_flow='row wrap', align_items='stretch', width='auto')) #new_hbox.box_style = 'info' vertical.append(new_hbox) # vertically laid out options with feedback on the left option_widget = widgets.VBox(vertical, layout=Layout(display='flex', flex_flow='column', align_items='stretch', width='100%')) score_widget = create_score_widget('#4DD0E1') multi_answer = VBox([question_widget, option_widget, score_widget], layout=Layout(display='flex', flex_flow='column', align_items='stretch', width='100%')) multi_answer.box_style = 'info' # compare checkbox value with original def check_answers(b): #run through each option, compare expected answer (checked/unchecked) with actual student answer num_options = len(options) incorrect = 0 missing = 0 option_widget = multi_answer.children[1] score_widget = multi_answer.children[2] submit_button = score_widget.children[0] for i in range(num_options): opt = option_widget.children[i] lbl = opt.children[0] cb = opt.children[1].children[0] actual_answer = cb.value expected_answer = options[i]['correct'] # clear feedback before giving new feedback opt.layout = Layout(border=None) lbl.value = '' lbl.layout = Layout(width='100px') # red border + 'incorrect' for incorrectly checked # green border + 'correct!' for correctly checked if (expected_answer and actual_answer): opt.layout = Layout(border='1px solid #81C784') lbl.value = 'Correct!' if (expected_answer and not actual_answer): missing += 1 if (not expected_answer and actual_answer): lbl.value = 'Incorrect' opt.layout = Layout(border='1px solid #e57373') incorrect += 1 # update the score label if incorrect + missing == 0: # Success! So disable checkboxes for i in range(num_options): opt = option_widget.children[i] cb = opt.children[1].children[0] cb.disabled = True if submit_button.description == 'Submit': text = '' else: text = 'Now you got it!' generate_feedback(multi_answer, score_widget, style='success', feedback_text=text, show_show_answer_btn=False) submit_button.layout.disable = True else: #Some incorrect answers, write feedback so they can try again if missing > 0: text = 'You missed some correct options, try again!' else: text = '' generate_feedback(multi_answer, score_widget, style='danger', feedback_text=text, show_show_answer_btn=False) submit_button = score_widget.children[0] submit_button.on_click(check_answers) return (multi_answer)