def Show3dImage(image, title = ''): [max_f, max_y, max_x] = np.asarray(image.shape) - 1 def ShowRawImage(frame, y_range, x_range, my_gamma): plt.figure(figsize=(15,10)) y_min = y_range[0] y_max = y_range[1]+1 x_min = x_range[0] x_max = x_range[1]+1 plt.imshow(image[frame,:, :], cmap = 'gray', norm=colors.PowerNorm(gamma=my_gamma)) # plt.imshow(image[frame,y_min:y_max, x_min:x_max], cmap = 'gray', norm=colors.PowerNorm(gamma=my_gamma)) plt.title(title) plt.xlim([x_min, x_max]) plt.ylim([y_min, y_max]) plt.xlabel("x [Px]") plt.ylabel("y [Px]") # plt.colorbar() plt.tight_layout() frame_slider = IntSlider(min = 1, max = max_f, step = 1, description = "Frame") y_range_slider = IntRangeSlider(value=[0, max_y], min=0, max=max_y, step = 5, description = "ROI - y") x_range_slider = IntRangeSlider(value=[0, max_x], min=0, max=max_x, step = 5, description = "ROI - x") gamma_slider = FloatSlider(min = 0.1, max = 2, step = 0.05, value = 0.5) interact(ShowRawImage, frame = frame_slider, y_range = y_range_slider, x_range = x_range_slider, my_gamma = gamma_slider)
def Show2dImage(image, title = '', ShowSlider = True, gamma = 1): [max_y, max_x] = np.asarray(image.shape) - 1 def ShowImage(y_range, x_range, my_gamma): plt.figure(figsize=(15,10)) y_min = y_range[0] y_max = y_range[1]+1 x_min = x_range[0] x_max = x_range[1]+1 #plt.imshow(image[y_min:y_max, x_min:x_max], cmap = 'gray', norm=colors.PowerNorm(gamma=my_gamma)) plt.imshow(image, cmap = 'gray', norm=colors.PowerNorm(gamma=my_gamma)) plt.title(title) plt.xlim([x_min, x_max]) plt.ylim([y_min, y_max]) plt.xlabel("x [Px]") plt.ylabel("y [Px]") plt.tight_layout() y_range_slider = IntRangeSlider(value=[0, max_y], min=0, max=max_y, step = 5, description = "ROI - y") x_range_slider = IntRangeSlider(value=[0, max_x], min=0, max=max_x, step = 5, description = "ROI - x") gamma_slider = FloatSlider(min = 0.1, max = 2, step = 0.05, value = 0.5) if ShowSlider == True: interact(ShowImage, y_range = y_range_slider, x_range = x_range_slider, my_gamma = gamma_slider) else: ShowImage(y_range = [0, max_y], x_range = [0, max_x], my_gamma = gamma)
def plot_calibrate_time(self, *args, **kwargs): """Experimental viewer for time calibration in a jupyter notebook. Args: accepts the same arguments as `SpatialEncoder.calibrate_time` function """ scan_pos_fs, edge_pos_pix, fit_coeff = self.calibrate_time( *args, **kwargs) source_results = ColumnDataSource( data=dict(x=scan_pos_fs, y=edge_pos_pix)) source_fit = ColumnDataSource(data=dict( x=[scan_pos_fs[0], scan_pos_fs[-1]], y=np.polyval(fit_coeff, [scan_pos_fs[0], scan_pos_fs[-1]]), )) p_time = figure( height=400, width=800, title='Time calibration', x_axis_label='Stage position, fs', y_axis_label='Edge position, pix', ) p_time.scatter('x', 'y', source=source_results) p_time.line('x', 'y', line_color='red', source=source_fit) layout = gridplot([p_time], ncols=1, toolbar_options=dict(logo=None)) handle = show(layout, notebook_handle=True) # Slider def slider_callback(change): left = change['new'][0] right = change['new'][1] fit_coeff = np.polyfit(scan_pos_fs[left:right + 1], edge_pos_pix[left:right + 1], 1) self.pix_per_fs = fit_coeff[0] source_fit.data.update( x=[scan_pos_fs[left], scan_pos_fs[right]], y=np.polyval(fit_coeff, [scan_pos_fs[left], scan_pos_fs[right]]), ) push_notebook(handle=handle) slider = IntRangeSlider( min=0, max=len(scan_pos_fs) - 1, value=[0, len(scan_pos_fs) - 1], step=1, description="Fit range", continuous_update=False, layout=Layout(width='800px'), ) slider.observe(slider_callback, names='value') return slider
def ChooseROI(ApplyROI): settings = nd.handle_data.ReadJson(ParameterJsonFile) settings["ROI"]["Apply"] = ApplyROI if ApplyROI == 0: print("ROI not applied") else: [max_f, max_y, max_x] = np.asarray(rawframes_np.shape) - 1 def ShowImageROI(frame_range, y_range, x_range, my_gamma): settings = nd.handle_data.ReadJson(ParameterJsonFile) fig, axes = plt.subplots(2,1, sharex = True,figsize=(15,6)) frame_min = frame_range[0] frame_max = frame_range[1] y_min = y_range[0] y_max = y_range[1] x_min = x_range[0] x_max = x_range[1] settings["ROI"]["frame_min"] = frame_min settings["ROI"]["frame_max"] = frame_max settings["ROI"]["y_min"] = y_min settings["ROI"]["y_max"] = y_max settings["ROI"]["x_min"] = x_min settings["ROI"]["x_max"] = x_max nd.handle_data.WriteJson(ParameterJsonFile, settings) axes[0].imshow(rawframes_np[frame_min,y_min:y_max+1, x_min:x_max+1], cmap = 'gray', norm=colors.PowerNorm(gamma=my_gamma)) axes[0].set_title("First Frame") axes[0].set_xlabel("x [Px]") axes[0].set_ylabel("y [Px]") axes[1].imshow(rawframes_np[frame_max,y_min:y_max+1, x_min:x_max+1], cmap = 'gray', norm=colors.PowerNorm(gamma=my_gamma)) axes[1].set_title("Last Frame") axes[1].set_xlabel("x [Px]") axes[1].set_ylabel("y [Px]") plt.tight_layout() #insert the starting values from the json file frames_range_slider = IntRangeSlider(value=[settings["ROI"]["frame_min"], settings["ROI"]["frame_max"]], min=0, max=max_f, step = 10, description = "ROI - frames") y_range_slider = IntRangeSlider(value=[settings["ROI"]["y_min"], settings["ROI"]["y_max"]], min=0, max=max_y, step = 10, description = "ROI - y") x_range_slider = IntRangeSlider(value=[settings["ROI"]["x_min"], settings["ROI"]["x_max"]], min=0, max=max_x, step = 10, description = "ROI - x") gamma_slider = FloatSlider(min = 0.1, max = 2, step = 0.05, value = 0.5) interact(ShowImageROI, frame_range = frames_range_slider, y_range = y_range_slider, x_range = x_range_slider, my_gamma = gamma_slider) nd.handle_data.WriteJson(ParameterJsonFile, settings)
def __get_widgets(self, chromosomes, browser, frame=None): if frame is None: frame = HTML() tracks = self.__get_tracks_name(browser) widgets = OrderedDict([ ("chromosomes_list", Dropdown(options=chromosomes)), ("left_button", Button(icon="arrow-left")), ("right_button", Button(icon="arrow-right")), ("zoom_out_button", Button(icon="search-minus")), ("zoom_in_button", Button(icon="search-plus")), ("range_textbox", Text(placeholder="genome range like: 'chr1:10000-20000'")), ("go_button", Button(description="Go")), ("range_slider", IntRangeSlider(continuous_update=False, readout=False, layout=Layout(width='90%'))), ("range_min_label", Label("", layout=Layout(width='2%'))), ("range_max_label", Label("", layout=Layout(width='20%'))), ("auto_check_box", Checkbox(value=True, description="Auto Range", layout=Layout(width='120px'), style={'description_width': 'initial'})), ("track_min_val_float_text", FloatText(value=0.0001, description="Track's min value:", step=0.5, disabled=True, layout=Layout(width='30%'), style={'description_width': 'initial'})), ("track_max_val_float_text", FloatText(value=10, description="Track's max value:", step=0.5, disabled=True, layout=Layout(width='30%'), style={'description_width': 'initial'})), ("track_dropdown", Dropdown(options=[ALL_BW_MARK] + tracks, value=ALL_BW_MARK, description="Select track", disabled=True, )), ("frame", frame) ]) return widgets
def widget_histograms(self): return interact( self.show_histograms, size=FloatSlider(value=0.5, min=0, max=1, step=0.01, continuous_update=False, description="Size fraction"), bin_width=IntSlider(value=5, min=1, max=32, description='Bin width'), hist_range=IntRangeSlider(value=[-50, 50], min=-255, max=256, description='Range:', continuous_update=False), width=IntSlider(value=15, min=5, max=50, step=1, continuous_update=False, description="Subplot width"), height=IntSlider(value=10, min=5, max=50, step=1, continuous_update=False, description="Subplot height") )
def show(): interact( plot, int_range=IntRangeSlider( value=[1, 6], min=events[0], max=events[-1], step=1, description='$事象の範囲$:', continuous_update=False))
def _init_gui(self): close = Button(description=' Close', icon='trash', layout=_wlo) def _close(b): self.close() close.on_click(_close) frame = IntSlider(min=self._df.frame.astype(int).min(), max=self._df.frame.astype(int).max(), value=-1, description='Frame', layout=_wlo) cbut = Button(description=' Columns', icon='barcode') cols = self._df.columns.tolist() cols = SelectMultiple(options=cols, value=cols) def _cols(c): self.columns = c.new self._update_output() cols.observe(_cols, names='value') cfol = Folder(cbut, _ListDict([('cols', cols)])) rbut = Button(description=' Rows', icon='bars') rows = IntRangeSlider(min=self.indexes[0], max=self.indexes[1], value=[0, 50]) def _rows(c): self.indexes = c.new print(self.indexes) self._update_output() rows.observe(_rows, names='value') rfol = Folder(rbut, _ListDict([('rows', rows)])) return _ListDict([('close', close), ('frame', frame), ('cols', cfol), ('rows', rfol)])
def __init__(self, src=None, auto=True, x=None, y=None, **kwargs): super().__init__(**kwargs) self._filters = {} self.box = VBox() self._links = [] self._group_filter = GroupUIFilter() self._trigger = Trigger(self._group_filter, func=self._apply_filter) self._filters = {} self._auto = auto self._auto_filter = None self.show_measure = False # setup controls self._ctrls = HBox() self._menu = widgets.Dropdown( options=self.options, description='Attribute:', value=self.attr, disabled=False, ) self.x_slider = IntRangeSlider(min=0, max=1, value=(0, 1), description='Points:') self.y_slider = FloatRangeSlider(min=0, max=1, value=(0, 1), description='Persistence:', step=0.001) self._ctrls = HBox([self._menu, self.y_slider, self.x_slider]) link((self, 'x_value'), (self.x_slider, 'value')) link((self, 'y_value'), (self.y_slider, 'value')) self._auto_filter = AttrFilter(attr=self._menu.value) if self._auto: self._group_filter.add(self._auto_filter, name='auto') widgets.link((self, 'attr'), (self._menu, 'value')) self.observe(self._auto_update, names=['attr']) # setup view self._links = [ widgets.link((self, 'x'), (self.x_slider, 'value')), widgets.link((self, 'y'), (self.y_slider, 'value')), ] self._update_children() if src is not None: self.src = src if x is not None: self.x = x if y is not None: self.y = y
def show_amino_acid_on_protein(self, assembly_name, name, sequence_id=0, palette_name='Set1', palette_size=2): """ Display visual controls for showing amino acid sequence on a protein of the scene :param: assembly_name: Name of the assembly containing the protein :param: name: Name of the protein :param: sequence_id: ID of the protein sequence :param: palette_name: Name of the color palette :param: palette_size: Size of the color palette """ sequences = self._be.get_protein_amino_acid_sequences( assembly_name, name) if sequence_id >= len(sequences): raise RuntimeError('Invalid sequence Id') sequence_as_list = sequences[0].split(',') value_range = [int(sequence_as_list[0]), int(sequence_as_list[1])] irs = IntRangeSlider(value=[value_range[0], value_range[1]], min=value_range[0], max=value_range[1]) lbl = Label(value="AA sequence") def update_slider(value): self._be.set_protein_amino_acid_sequence_as_range( assembly_name, name, value['new']) self._be.set_protein_color_scheme( assembly_name, name, self._be.COLOR_SCHEME_AMINO_ACID_SEQUENCE, palette_name, palette_size) lbl.value = sequence_as_list[2][value['new'][0] - value_range[0]:value['new'][1] - value_range[0]] irs.observe(update_slider, 'value') display(irs) display(lbl)
def __init__(self): self._top_n_terms: IntSlider = IntSlider( description='#terms', min=10, max=1000, value=100, tooltip= 'The total number of most discriminating terms to return for each group', ) self._max_n_terms: IntSlider = IntSlider( description='#top', min=1, max=2000, value=2000, tooltip= 'Only consider terms whose document frequency is within the top # terms out of all terms', ) self._period1: IntRangeSlider = IntRangeSlider( description='Period', min=1900, max=2099, value=(2001, 2002), layout={'width': '250px'}, ) self._period2 = IntRangeSlider( description='Period', min=1900, max=2099, value=(2001, 2002), layout={'width': '250px'}, ) self._compute = Button(description='Compute', icon='', button_style='Success', layout={'width': '120px'}) self.compute_callback: Callable = None self.done_callback: Callable = None self.corpus: dtm.VectorizedCorpus = None
def interact(self): """ 获取交互式控制专题图样式部件 """ codomainslider = IntRangeSlider( value=[self.codomain[0], self.codomain[1]], min=self._codomainmin, max=self._codomainmax, step=1, description='值域范围:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d', layout=Layout(width="350px")) link((codomainslider, 'value'), (self, 'codomain')) rslider = IntRangeSlider(value=[self.rrange[0], self.rrange[1]], min=self._min_r, max=self._max_r, step=1, description='半径范围:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d', layout=Layout(width="350px")) link((rslider, 'value'), (self, 'rrange')) color = ColorPicker(concise=False, description='填充颜色:', value=self.color, disabled=False, layout=Layout(width="350px")) link((color, 'value'), (self, 'color')) return VBox([codomainslider, rslider, color])
def __init__(self): self.run_bt = Button(description='Demo_deprec', button_style='info') self.mod_add_bt = Button(description='Add model', button_style='info') self.mod_remove_bt = Button(description='Remove model', button_style='warning') # self.dts_selector = Dropdown(options=SUPPORTED_DATASETS, # value=SUPPORTED_DATASETS[0], # description='Dataset:') self.dts_selector = self.get_default_dts_selector() self.size_selector = RadioButtons(options=[1000, 2000, 5000, 10000], value=1000, description='Size') self.features_selector = IntRangeSlider(value=[30, 100], min=30, max=2000, step=1, layout=Layout(width='950px')) self.model_name_column = VBox([Label(value='Model')]) self.sampler_name_column = VBox([Label(value='Sampler')]) self.box_type_column = VBox([Label(value='Box Type')]) self.n_estim_column = VBox([Label(value='Number Estimators')]) self.pca_column = VBox([Label(value='PCA?')]) self.models_bar = HBox([ self.model_name_column, self.sampler_name_column, self.box_type_column, self.n_estim_column, self.pca_column, ], layout=Layout(border='3px solid black')) self.gui = VBox([ self.dts_selector, self.size_selector, self.mod_add_bt, self.mod_remove_bt, self.features_selector, self.models_bar, self.run_bt, ]) self.mod_add_bt.on_click(self.insert_model_bar) self.mod_remove_bt.on_click(self.remove_model_bar) self.insert_model_bar() # self.box_type_changed() self.sampler_changed() super().__init__()
def __init__(self, tree=None, auto=True, **kwargs): super().__init__(**kwargs) self._filters = {} self._treeview = None self._links = [] self._group_filter = GroupUIFilter() self._trigger = Trigger(self._group_filter, func=self._apply_filter) self._filters = {} self._auto = auto self._auto_filter = None # setup controls self._ctrls = HBox() self._menu = widgets.Dropdown( options=self.attr_opts, description='Attribute:', value=self.attr, disabled=False, ) self._x = IntRangeSlider(min=0, max=100, value=(0, 100), description='Points:') self._y = FloatRangeSlider(min=0, max=1, value=(0, 1), description='Persistence:', step=0.001) self._ctrls = HBox([self._menu, self._y, self._x]) self._auto_filter = AttrFilter(attr=self._menu.value) if self._auto: self._group_filter.add(self._auto_filter, name='auto') widgets.link((self._menu, 'value'), (self, 'attr')) self.observe(self._auto_update, names=['attr']) # setup view self._treeview = BaseTreeView(None, attr=self.attr) self._treeview.show_attr = False self._links = [ widgets.link((self, 'attr'), (self._treeview, 'attr')), widgets.link((self._x, 'value'), (self._treeview, 'x')), widgets.link((self._y, 'value'), (self._treeview, 'y')) ] self._update_children() if tree is not None: self.tree = tree
def slide_plot(self): '''Interactive plot for use in jupyter notebook Provides plot of UV spectrum with sliders to change wavelength domain range and homogeneous broadening''' @interact(domain=IntRangeSlider(value=[200, 900], min=100, max=1000, step=25, description='Spectrum Range: '), width=FloatSlider(value=0.3, min=0.1, max=0.5, step=0.05, description='Broadening: ')) def _plot(domain, width): x = np.linspace(1242 / domain[1], 1242 / domain[0], 1000) self.gen_spectrum(X=x, width=width) self.gen_plot('spec')
def _contour_folder(self, folder): control = Button(description=' Contours', icon='dot-circle-o') def _cshow(b): for scn in self.active(): scn.cont_show = not scn.cont_show control.on_click(_cshow) content = _ListDict([ ('fopts', folder['fopts']), ('axis', Dropdown(options=['x', 'y', 'z'], value='z')), ('num', IntSlider(description='N', min=5, max=20, value=10, step=1)), ('lim', IntRangeSlider(description='10**Limits', min=-8, max=0, step=1, value=[-7, -1])), ('val', FloatSlider(description='Value', min=-5, max=5, value=0)) ]) def _cont_axis(c): for scn in self.active(): scn.cont_axis = c.new def _cont_num(c): for scn in self.active(): scn.cont_num = c.new def _cont_lim(c): for scn in self.active(): scn.cont_lim = c.new def _cont_val(c): for scn in self.active(): scn.cont_val = c.new content['axis'].observe(_cont_axis, names='value') content['num'].observe(_cont_num, names='value') content['lim'].observe(_cont_lim, names='value') content['val'].observe(_cont_val, names='value') contour = Folder(control, content) folder.insert(2, 'contour', contour, active=True, update=True)
def __init__(self, storage, setup): self.storage = storage self.setup = setup self.nans = None self.play = Play() self.step_slider = IntSlider() self.fps_slider = IntSlider(min=100, max=1000, description="1000/fps") self.product_select = Select() self.plots_box = Box() self.slider = {} self.lines = {'x': [{}, {}], 'y': [{}, {}]} for xy in ('x', 'y'): self.slider[xy] = IntRangeSlider(min=0, max=1, description=f'spectrum_{xy}', orientation='horizontal' if xy == 'x' else 'vertical') self.reinit({})
def __init__(self, storage, setup): self.storage = storage self.setup = setup self.play = Play(interval=1000) self.step_slider = IntSlider(continuous_update=False, description='t/dt:') self.product_select = Dropdown() self.plots_box = Box() self.slider = {} self.lines = {'X': [{}, {}], 'Z': [{}, {}]} for xz in ('X', 'Z'): self.slider[xz] = IntRangeSlider( min=0, max=1, description=f'{xz}', continuous_update=False, orientation='horizontal' if xz == 'X' else 'vertical') self.reinit({})
def _make_constrast_slider(): min_ = stack.min() max_ = stack.max() init_min = min_ init_max = max_ if (init_minval != None): init_min = init_minval if (init_maxval != None): init_max = init_maxval contrast_slider = IntRangeSlider( value=[init_min, init_max], min=min_, max=max_, step=1, description='Contrast', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d', ) return contrast_slider
def initialize_sliders(self, box_universe=None, box_name=None): if box_universe is not None: self._box_universe = box_universe if box_name is not None: self._box_name = box_name logger.info(f"initialize_sliders( {self._box_name} )") try: self.joint_filters = pandas.DataFrame( numpy.ones_like(self.joint_data, dtype=bool), index=self.joint_data.index, columns=self.joint_data.columns, ) clusterdef = ChainedBox(self._box_universe, self._box_name) self.sliders = [] self.outboxes = [] for i in self.joint_data.columns: i_dtype = self.scope.get_dtype(i) or 'real' if i_dtype == 'real': current_setting = clusterdef.get(i, (None, None)) logger.info(f" initial setting {i} = {current_setting}") current_min = self.joint_data[i].min( ) if current_setting[0] is None else current_setting[0] current_max = self.joint_data[i].max( ) if current_setting[1] is None else current_setting[1] controller = FloatRangeSlider( value=[current_min, current_max], min=self.joint_data[i].min(), max=self.joint_data[i].max(), step=(self.joint_data[i].max() - self.joint_data[i].min()) / 20, disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.2f', description=i, style=slider_style, layout=slider_layout, ) elif i_dtype == 'int': current_setting = clusterdef.get(i, (None, None)) logger.info(f" initial setting {i} = {current_setting}") current_min = self.joint_data[i].min( ) if current_setting[0] is None else current_setting[0] current_max = self.joint_data[i].max( ) if current_setting[1] is None else current_setting[1] controller = IntRangeSlider( value=[current_min, current_max], min=self.joint_data[i].min(), max=self.joint_data[i].max(), #step=(self.joint_data[i].max()-self.joint_data[i].min())/20, disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d', description=i, style=slider_style, layout=slider_layout, ) elif i_dtype == 'cat': cats = self.scope.get_cat_values(i) controller = MultiToggleButtons( description=i, style=slider_style, options=cats, disabled=False, button_style= '', # 'success', 'info', 'warning', 'danger' or '' layout=slider_layout, ) controller.values = cats elif i_dtype == 'bool': cats = [False, True] controller = MultiToggleButtons( description=i, style=slider_style, options=cats, disabled=False, button_style= '', # 'success', 'info', 'warning', 'danger' or '' layout=slider_layout, ) controller.values = cats else: # buttons raise NotImplementedError(f"filters for {i}:{i_dtype}") controller = ToggleButtons( description=i, style=slider_style, options=['Off', 'On', 'Both'], value='Both', disabled=False, button_style= '', # 'success', 'info', 'warning', 'danger' or '' tooltips=['Definitely off', 'Definitely on', 'Maybe'], layout=slider_layout, ) self.sliders.append(controller) self.outboxes.append( Output(layout=Layout( height='1in', width='3in', ), )) for s in range(len(self.sliders)): self.sliders[s].observe(self.replot_many) self.ui_risks = VBox([ HBox([s, ob]) for s, ob in zip(self.sliders, self.outboxes) if s.description in self.data.all_risk_factors_ ], ) self.ui_strategies = VBox([ HBox([s, ob]) for s, ob in zip(self.sliders, self.outboxes) if s.description in self.data.all_strategy_names_ ], ) self.ui_perform = VBox([ HBox([s, ob]) for s, ob in zip(self.sliders, self.outboxes) if s.description in self.data.all_performance_measures_ ], ) self.accordion = Accordion( children=[self.ui_strategies, self.ui_risks, self.ui_perform]) self.accordion.set_title(0, 'Policy Levers') self.accordion.set_title(1, 'Exogenous Uncertainties') self.accordion.set_title(2, 'Performance Measures') #self.footer = Output(layout={ 'border': '1px solid red', } ) self.stack = VBox([ self.header_area, self.accordion, self.footer, ]) self.set_header(clusterdef.names) self.replot_many(None) # initial interactive plots except: logger.exception("error in initialize_sliders") raise
def ChooseFindObjParameters(rawframes_pre, ParameterJsonFile): #read in settings settings = nd.handle_data.ReadJson(ParameterJsonFile) # SEPARATION DISTANCE # select if help is required help_sep_distance = Dropdown(options=['0', 'auto'], value=settings["Help"]["Separation"], description='Help separation distance') def ChooseSepDistance_Mode(mode): settings["Help"]["Separation"] = mode if mode == "auto": Low_Diam_slider_start = settings["Help"]["GuessLowestDiameter_nm"] Low_Diam_slider = IntSlider(min = 1, max = 100, step = 1, \ value = Low_Diam_slider_start, description = "Guess lowest diameter [nm]") def CalcSepDistance(Low_Diam): Min_Separation, Max_displacement = \ nd.ParameterEstimation.FindMaxDisplacementTrackpy(ParameterJsonFile, GuessLowestDiameter_nm = Low_Diam) settings["Find"]["Separation data"] = Min_Separation settings["Link"]["Max displacement"] = Max_displacement settings["Help"]["GuessLowestDiameter_nm"] = Low_Diam nd.handle_data.WriteJson(ParameterJsonFile, settings) interact(CalcSepDistance, Low_Diam=Low_Diam_slider) else: Min_Separation_slider = FloatSlider(min = 0, max = 100, step = 0.5, \ value = settings["Find"]["Separation data"],\ description = "Separation distance [Px]") Max_displacement_slider = FloatSlider(min = 0, max = 50, step = 0.5, \ value = settings["Link"]["Max displacement"],\ description = "Maximal Displacement [Px]") def ChooseSepDistance_Value(Min_Separation, Max_displacement): settings["Find"]["Separation data"] = Min_Separation settings["Link"]["Max displacement"] = Max_displacement nd.handle_data.WriteJson(ParameterJsonFile, settings) interact(ChooseSepDistance_Value, \ Min_Separation = Min_Separation_slider, Max_displacement = Max_displacement_slider) nd.handle_data.WriteJson(ParameterJsonFile, settings) interact(ChooseSepDistance_Mode, mode=help_sep_distance) # BEAD DIAMETER # select if help is required help_diameter = Dropdown(options=['0', 'manual', 'auto'], value=settings["Help"]["Bead size"], description='Help bead diameter') diameter_slider = IntSlider(min = 1, max = 31, step = 2, \ value = settings["Find"]["tp_diameter"],\ # value = 15,\ description = "Diameter of bead [Px]") def OptimizeBeadDiameter(mode, diameter): settings = nd.handle_data.ReadJson(ParameterJsonFile) settings["Find"]["tp_diameter"] = diameter settings["Help"]["Bead size"] = mode if mode == "manual": settings["Find"]["tp_diameter"] = \ nd.AdjustSettings.SpotSize_manual(rawframes_pre, settings, AutoIteration = False) elif settings["Help"]["Bead size"] == "auto": settings["Find"]["tp_diameter"] = nd.AdjustSettings.SpotSize_auto( settings) else: print( "Bead size not adjusted. Use 'manual' or 'auto' if you want to do it." ) nd.handle_data.WriteJson(ParameterJsonFile, settings) interact(OptimizeBeadDiameter, mode=help_diameter, diameter=diameter_slider) # MINMASS # optimize minmass to identify particle help_minmass = Dropdown(options=['0', 'manual', 'auto'], value=settings["Help"]["Bead brightness"], description='Help bead minmass') # minmass_slider = FloatLogSlider(min = 1, max = 4, step = 0.1, \ minmass_slider = IntText(value = settings["Find"]["Minimal bead brightness"],\ description = "Minimal bead brightness", min = 1, step = 10) [max_f, max_y, max_x] = np.asarray(rawframes_pre.shape) - 1 # frame_min = 1 # frame_max = settings["ROI"]["frame_max"] - settings["ROI"]["frame_min"] #IntText # frame_slider = IntText(value = 0,\ # description = "Frame", step = 1, \ # min = frame_min, max = frame_max) frame_slider = IntSlider(min=1, max=max_f, step=1, description="Frame") y_range_slider = IntRangeSlider(value=[0, max_y], min=0, max=max_y, step=5, description="y") x_range_slider = IntRangeSlider(value=[0, max_x], min=0, max=max_x, step=5, description="x") gamma_slider = FloatSlider(min=0.1, max=2, step=0.05, value=0.5) def OptimizeMinmass(mode, minmass, frame, y_range, x_range, gamma): settings = nd.handle_data.ReadJson(ParameterJsonFile) settings["Find"]["Minimal bead brightness"] = minmass settings["Help"]["Bead brightness"] = mode y_min = y_range[0] y_max = y_range[1] + 1 x_min = x_range[0] x_max = x_range[1] + 1 nd.handle_data.WriteJson(ParameterJsonFile, settings) if mode == "manual": nd.AdjustSettings.FindSpot_manual(rawframes_pre[frame:frame+1, y_min:y_max, x_min:x_max], ParameterJsonFile, \ ExternalSlider = True, gamma = gamma) elif settings["Help"]["Bead size"] == "auto": minmass, num_particles_trackpy = nd.ParameterEstimation.MinmassMain( rawframes_pre, settings) settings["Find"]["Minimal bead brightness"] = minmass else: print( "Bead size not adjusted. Use 'manual' or 'auto' if you want to do it." ) nd.handle_data.WriteJson(ParameterJsonFile, settings) interact(OptimizeMinmass, mode = help_minmass, minmass = minmass_slider, \ frame = frame_slider, y_range = y_range_slider, x_range = x_range_slider, gamma = gamma_slider)
def ChoosePreProcessingParameters(rawframes_np, ParameterJsonFile): #read in settings settings = nd.handle_data.ReadJson(ParameterJsonFile) # LASER FLUCTUATIONS # select if Laser Fluctuations are applied process_laser_fluctuations = IntSlider(min = 0, max = 1, \ value = settings["PreProcessing"]["Remove_Laserfluctuation"],\ description = "Correct Laser fluctuations (0 - no, 1 - yes)") def RemoveLaserFluctuations(process_laser_fluctuations): settings = nd.handle_data.ReadJson(ParameterJsonFile) settings["PreProcessing"][ "Remove_Laserfluctuation"] = process_laser_fluctuations if process_laser_fluctuations == 0: print("Laser Fluctuations not corrected") else: settings["Plot"]['Laserfluctuation_Show'] = True nd.PreProcessing.RemoveLaserfluctuation(rawframes_np, settings) nd.handle_data.WriteJson(ParameterJsonFile, settings) interact(RemoveLaserFluctuations, process_laser_fluctuations=process_laser_fluctuations) # CAMERA OFFSET process_camera_offset = IntSlider(min = 0, max = 1, \ value = settings["PreProcessing"]["Remove_CameraOffset"],\ description = "Correct camera offset (0 - no, 1 - yes)") def RemoveCameraOffset(process_camera_offset): settings = nd.handle_data.ReadJson(ParameterJsonFile) settings["PreProcessing"][ "Remove_CameraOffset"] = process_camera_offset if process_camera_offset == 0: print("Camera Offset not corrected") else: nd.PreProcessing.SubtractCameraOffset(rawframes_np, settings) nd.handle_data.WriteJson(ParameterJsonFile, settings) interact(RemoveCameraOffset, process_camera_offset=process_camera_offset) # # STATIC BACKGROUND # process_static_background_slider = IntSlider(min = 0, max = 1, \ # value = settings["PreProcessing"]["Remove_StaticBackground"],\ # description = "Correct static background (0 - no, 1 - yes)") # # def RemoveStaticBackground(process_static_background): # settings = nd.handle_data.ReadJson(ParameterJsonFile) # settings["PreProcessing"]["Remove_CameraOffset"] = process_static_background # # if process_static_background == 0: # print("Static Background not corrected") # else: # settings["Plot"]['Background_Show'] = True # rawframes_np_no_bg, static_background = nd.PreProcessing.Remove_StaticBackground(rawframes_np, settings, ShowColorBar = False, ExternalSlider = True) # Show2dImage(static_background, title = 'Background', ShowSlider = True) # # nd.handle_data.WriteJson(ParameterJsonFile, settings) # # # # interact(RemoveStaticBackground, process_static_background = process_static_background_slider) # # # CALCULATE BACKGROUND AND ENHANCE SNR BY CONVOLVING WITH PSF process_static_background_slider = IntSlider(min = 0, max = 1, \ value = settings["PreProcessing"]["Remove_StaticBackground"],\ description = "Correct static background (0 - no, 1 - yes)") EnhanceSNR_Slider = IntSlider(min = 0, max = 1, \ value = settings["PreProcessing"]["EnhanceSNR"],\ description = "Enhance SNR by convolving with the PSF (0 - no, 1 - yes)") KernelSize = settings["PreProcessing"]["KernelSize"] if KernelSize == 'auto': KernelSize = 0 KernelSize_Slider = FloatSlider(min = 0, max = 10, \ value = KernelSize,\ description = "Kernelsize (0 - auto)") [max_f, max_y, max_x] = np.asarray(rawframes_np.shape) - 1 frame_slider = IntSlider(min=1, max=max_f, step=1, description="Frame") y_range_slider = IntRangeSlider(value=[0, max_y], min=0, max=max_y, step=5, description="ROI - y") x_range_slider = IntRangeSlider(value=[0, max_x], min=0, max=max_x, step=5, description="ROI - x") gamma_slider = FloatSlider(min=0.1, max=2, step=0.05, value=0.5) def ConvolveWithPSF(process_static_background, EnhanceSNR, KernelSize, frame, y_range, x_range, my_gamma): settings = nd.handle_data.ReadJson(ParameterJsonFile) settings["PreProcessing"][ "Remove_CameraOffset"] = process_static_background plt.figure(figsize=(15, 10)) y_min = y_range[0] y_max = y_range[1] + 1 x_min = x_range[0] x_max = x_range[1] + 1 image_roi_bg = rawframes_np[:, y_min:y_max, x_min:x_max] image_roi = rawframes_np[frame, y_min:y_max, x_min:x_max] # Here comes the background if process_static_background == 0: print("Static Background not corrected") else: settings["Plot"]['Background_Show'] = True image_roi_no_bg, static_background = nd.PreProcessing.Remove_StaticBackground( image_roi_bg, settings, ShowColorBar=False, ExternalSlider=True) Show2dImage(static_background, title='Background', ShowSlider=False) #switch the sliders on if they are required if (EnhanceSNR == False) and (process_static_background == False): KernelSize_Slider.layout.visibility = 'hidden' frame_slider.layout.visibility = 'hidden' y_range_slider.layout.visibility = 'hidden' x_range_slider.layout.visibility = 'hidden' gamma_slider.layout.visibility = 'hidden' else: KernelSize_Slider.layout.visibility = 'visible' frame_slider.layout.visibility = 'visible' y_range_slider.layout.visibility = 'visible' x_range_slider.layout.visibility = 'visible' gamma_slider.layout.visibility = 'visible' # def ConvolveWithPSF(EnhanceSNR, KernelSize, frame, my_gamma): # image_roi = rawframes_np[frame, :, :] settings = nd.handle_data.ReadJson(ParameterJsonFile) settings["PreProcessing"]["EnhanceSNR"] = EnhanceSNR if KernelSize == 0: KernelSize = 'auto' settings["PreProcessing"]["KernelSize"] = KernelSize if EnhanceSNR == 0: print("SNR not enhanced by a convolution with the PSF") else: settings["Plot"]['Background_Show'] = True if process_static_background == 0: rawframes_filtered = nd.PreProcessing.ConvolveWithPSF( image_roi, settings, ShowFirstFrame=True, ShowColorBar=False, ExternalSlider=True) else: rawframes_filtered = nd.PreProcessing.ConvolveWithPSF( image_roi_no_bg[frame, :, :], settings, ShowFirstFrame=True, ShowColorBar=False, ExternalSlider=True) Show2dImage(rawframes_filtered, ShowSlider=False, gamma=my_gamma) nd.handle_data.WriteJson(ParameterJsonFile, settings) # interact(ConvolveWithPSF, EnhanceSNR = EnhanceSNR_Slider, KernelSize = KernelSize_Slider\ # , frame = frame_slider, my_gamma = gamma_slider) interact(ConvolveWithPSF, process_static_background=process_static_background_slider, EnhanceSNR=EnhanceSNR_Slider, KernelSize=KernelSize_Slider, frame=frame_slider, y_range=y_range_slider, x_range=x_range_slider, my_gamma=gamma_slider) # Rest is not implemented, yet print("RollingPercentilFilter not inserted yet") print("Clipping negative values not inserted yet. Clipping is bad") print( "Rotating the image is not inserted yet. Rotate your camera if that is a problem." )
def create_parameter_widgets(self, augmentation_name): """ augmentation_name - name of the augmentation you want to test """ function = partial(self.test_aug, augmentation_name=augmentation_name) ui_s = [] widget_dict = {} for param_name, values in self.aug_dict[augmentation_name].items(): if values[-2] == "width": lower = values[1] upper = self.shape[1] elif values[-2] == "height": lower = values[1] upper = self.shape[0] elif values[-2] == "channels-1": lower = values[1] upper = self.channels - 1 elif values[-1] == "max": lower = values[1] upper = max(self.shape) else: lower = values[1] upper = values[2] if values[-1] == "odd" and values[0] in ["int" "int_range"]: step = 2 elif values[-1] != "odd" and (values[0] == "int" or values[0] == "int_range"): step = 1 elif values[0] == "float" or values[0] == "float_range": step = 0.01 if values[0] == "int": widget = IntSlider( min=lower, max=upper, step=step, orientation="horizontal", # description=f'{param_name}:', continuous_update=False, ) widget_ = IntText( description="", continuous_update=False, readout=True, readout_format="d", ) widgets.link((widget, "value"), (widget_, "value")) widgets_linked = VBox([widget, widget_]) widgets_linked_with_description = HBox( [Label(param_name), widgets_linked]) ui_s.append(widgets_linked_with_description) setattr(widgets_linked_with_description, "value", widget.value) elif values[0] == "int_range": widget = IntRangeSlider( value=[1, 1] if values[-1] == "odd" else [0, 0], min=lower, max=upper, step=step, # description=f'{param_name}:', disabled=False, continuous_update=False, orientation="horizontal", readout=True, readout_format="d", ) widget_with_description = HBox([Label(param_name), widget]) setattr(widget_with_description, "value", widget.value) ui_s.append(widget_with_description) elif values[0] == "float": widget = FloatSlider( value=0, min=lower, max=upper, step=step, # description=f'{param_name}:', disabled=False, continuous_update=False, orientation="horizontal", readout=True, readout_format=".2f", ) widget_ = FloatText( description="", continuous_update=False, readout=True, readout_format=".2f", ) widgets.link((widget, "value"), (widget_, "value")) widgets_linked = VBox([widget, widget_]) widgets_linked_with_description = HBox( [Label(param_name), widgets_linked]) ui_s.append(widgets_linked_with_description) setattr(widgets_linked_with_description, "value", widget.value) elif values[0] == "float_range": widget = FloatRangeSlider( value=[0, 0], min=lower, max=upper, step=step, disabled=False, continuous_update=False, orientation="horizontal", readout=True, readout_format=".2f", ) widget_with_description = HBox([Label(param_name), widget]) ui_s.append(widget_with_description) setattr(widget_with_description, "value", widget.value) elif values[0] == "str" or values[0] == "bool": widget = RadioButtons(options=[*values[1]], value=values[1][1], disabled=False) widget_with_description = HBox([Label(param_name), widget]) setattr(widget_with_description, "value", widget.value) ui_s.append(widget_with_description) # ui_s.append(widget) widget_dict[f"{param_name}"] = widget out = interactive_output(function, widget_dict) display(*ui_s, out)
def file_interface(fu, fworker, kpt_density): try: for filename in fu.keys(): file_str = list(fu.values())[0]["content"].decode("utf-8") spl = filename.split(".") if len(spl) == 1: file_fmt = "poscar" else: file_fmt = spl[-1] structure = Structure.from_str(input_string=file_str, fmt=file_fmt) except UnicodeDecodeError: print("Issue with geometry input file.") return except UnboundLocalError: print("Please select an input file.") return except ValueError: print("Incorrect format for input file.") return static = BulkStaticSet( structure, user_incar_settings=user_incar_settings, user_kpoints_settings={"reciprocal_density": kpt_density}) nions = len(structure) nelect = static.nelect ispin = int(static.incar.get("ISPIN", 1)) if ispin == 1: nbands = int(round(nelect / 2 + nions / 2)) elif ispin == 2: nbands = int(nelect * 3 / 5 + nions) else: raise ValueError("ISPIN Value is not set to 1 or 2!") cores_per_node = CLUSTER_DICT[fworker]["cores_per_node"] nbands = (nbands // cores_per_node + 1) * cores_per_node kpoints = static.kpoints spg = SpacegroupAnalyzer(structure, symprec=1e-5) max_kpts = len(spg.get_ir_reciprocal_mesh(kpoints.kpts)) selection = interactive(selection_interface, structure=fixed(structure), fworker=fixed(fworker), kpt_density=fixed(kpt_density), functional=Select( options=['pbe', 'hse06'], value='pbe', rows=2, description='Functional:', ), nodes_list=Text( value="1, 2, 4", placeholder='Nodes (comma separated)', description='Node List:', ), nbands=BoundedIntText(value=nbands, min=1, max=10000, step=1, description='NBANDS:'), max_kpt_range=IntRangeSlider( value=[1, max_kpts], min=1, max=max_kpts + cores_per_node // 2, step=1, description='Max KPAR range:', )) display(HBox(selection.children[:2])) display(HBox(selection.children[2:])) display(button) return selection
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=(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 = 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) frame_slider = IntRangeSlider( value=[5, 7], min=0, max=10, step=1, description='Test:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d', ) # "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]) 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])
# <h1><center>Teoría de Perturbaciones</center></h1> # Consiste en resolver un sistema perturbado(se conoce la solución al no perturbado), y donde el interés es conocer la contribución de la parte perturbada $H'$ al nuevo sistema total. # $$ H = H^{0}+H'$$ # La resolución adecuada del problema, depende en gran parte, de una correcta elección de $H'$. # In[151]: form_item_layout = Layout(display='flex',flex_flow='row',justify_content='space-between') PType=Dropdown(options=['Particle in a one-dimensional box', 'Harmonic oscilator', 'Hydrogen atom (Helium correction)']) Pert=Text() Rang=IntRangeSlider(min=0, max=20, step=1, disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d') M=Text() Correc=Dropdown(options=['1', '2']) hbarra=Dropdown(options=[1, 1.0545718e-34]) form_items = [ Box([Label(value='Problem'),PType], layout=form_item_layout), Box([Label(value='Perturbation'),Pert], layout=form_item_layout), Box([Label(value='Correction order'),Correc], layout=form_item_layout), Box([Label(value='n Range'),Rang], layout=form_item_layout), Box([Label(value='Mass'),M], layout=form_item_layout), Box([Label(value='Hbar'),hbarra], layout=form_item_layout),] form = Box(form_items, layout=Layout(display='flex',flex_flow='column',border='solid 2px',align_items='stretch',width='40%')) form
def resetSpGCheckBoxes(b): for k in spgSelector: if type(k) == int: spgSelector[k].value = False spgSelector[1].value = True spgSelector['reset'].on_click(resetSpGCheckBoxes) spgSelectorLayout = HBox([ VBox([spgSelector[i] for i in range(1, 6)]), VBox([spgSelector[i] for i in range(6, 11)]), VBox([spgSelector[i] for i in [11, 21, 31, 'which', 'reset']]) ]) bottLine = HBox([AOGenus, ATspecies, spgSelectorLayout]) startEnd = IntRangeSlider(value=[1, 10], min=1, max=10, step=1, description='Ranks') aggWidg = VBox([topRowGroup, midLine, bottLine, startEnd]) kind = Tab() kind.children = [aggWidg, unaggWidg] for i, name in enumerate(['Aggregated', 'Unaggregated']): kind.set_title(i, name)
def imgs_grid(path): def show_imgs(): print(f"Crop name: {crop_name}, Area: {area:.2f} sqm") def multi_bands_imgs(bands, fname): df = raster_utils.create_df(ci_path, pid, ci_band.value) rows = round((df.shape[0] / columns) + 0.5) fig = plt.figure(figsize=(16, 4 * rows)) for i, row in df.iterrows(): fig.add_subplot(rows, columns, i + 1) str_date = str(row['date'].date()).replace('-', '') img_png = normpath(join(ci_path, f'{fname}_{str_date}.png')) # Create color image if it does not exist # Merge bands (images path, export image path, bands list) if not isfile(img_png): imgs_path = normpath(join(ci_path, row['imgs'])) raster_utils.merge_bands(imgs_path, img_png, bands) with rasterio.open(img_png, format='PNG') as img: overlay_date(img, row['date'].date()) # Add date overlay. ax = plt.gca() if show_parcel.value: ax.add_patch(overlay_parcel(img, info_data)) plt.axis('off') # Turn of axis. pA, pB = np.percentile(img.read(1), tuple(ci_percent.value)) # Strech image to A - B percentile. stack = [ exposure.rescale_intensity(img.read()[i, :, :], in_range=(pA, pB)) for i in range(len(bands)) ] rgb_enhanced = np.dstack(stack) show(np.uint16(rgb_enhanced.transpose(2, 0, 1) / 300), ax=ax, transform=img.transform) return plt.show() def ndvi_imgs(bands, fname): df = raster_utils.create_df(ci_path, pid, ci_band.value) rows = round((df.shape[0] / columns) + 0.5) fig = plt.figure(figsize=(16, 4 * rows)) for i, row in df.iterrows(): fig.add_subplot(rows, columns, i + 1) str_date = str(row['date'].date()).replace('-', '') img_png = normpath(join(ci_path, f'{fname}_{str_date}.png')) imgs_path = normpath(join(ci_path, row['imgs'])) b4f = f"{imgs_path}.B04.tif" b4 = rasterio.open(b4f, format='GTiff') ndvi = raster_utils.calc_ndvi(imgs_path, img_png, bands) overlay_date(b4, row['date'].date()) # Add date overlay. ax = plt.gca() if show_parcel.value: ax.add_patch(overlay_parcel(b4, info_data)) plt.axis('off') # Turn of axis. pA, pB = np.percentile(ndvi, tuple(ci_percent.value)) show(ndvi, ax=ax, transform=b4.transform, cmap=ci_cmaps.value, vmin=pA, vmax=pB) b4.close() return plt.show() def single_band(band): df = raster_utils.create_df(ci_path, pid, ci_band.value) rows = round((df.shape[0] / columns) + 0.5) fig = plt.figure(figsize=(16, 4 * rows)) for i, row in df.iterrows(): img_gtif = normpath( join(ci_path, f"{row['imgs']}.{ci_band.value[0]}.tif")) with rasterio.open(img_gtif, format='GTiff') as img: fig.add_subplot(rows, columns, i + 1) overlay_date(img, row['date'].date()) plt.axis('off') ax = plt.gca() if show_parcel.value: ax.add_patch(overlay_parcel(img, info_data)) img_read = img.read(1) pA, pB = np.percentile(img_read, tuple(ci_percent.value)) show(img.read(1), ax=ax, transform=img.transform, cmap=data_options.cmaps(ci_band.value[0]), vmin=pA, vmax=pB) return plt.show() if len(ci_band.value) == 1: single_band(ci_band.value[0]) elif ci_band.value == ['B04', 'B08']: ndvi_imgs(ci_band.value, 'NDVI') else: multi_bands_imgs(ci_band.value, ('').join(ci_band.value)) def overlay_date(img, date): date_text = plt.text( img.bounds.left + ((img.bounds.right - img.bounds.left) / 6.5), img.bounds.top - ((img.bounds.top - img.bounds.bottom) / 6.5), date, color='yellow', weight='bold', size=12, bbox=dict(boxstyle="round", ec='yellow', fc='black', alpha=0.2)) return date_text def overlay_parcel(img, geom): with open(file_info, 'r') as f: info_data = json.loads(f.read()) img_epsg = img.crs.to_epsg() geo_json = spatial_utils.transform_geometry(info_data, img_epsg) patche = [ PolygonPatch(feature, edgecolor="yellow", facecolor="none", linewidth=2) for feature in [geo_json['geom'][0]] ] return patche[0] # Images options. file_info = normpath(join(path, 'info.json')) with open(file_info, 'r') as f: info_data = json.loads(f.read()) # print(info_data) pid = info_data['pid'][0] crop_name = info_data['cropname'][0] area = info_data['area'][0] ci_path = normpath(join(path, 'chip_images')) columns = 4 available_options = raster_utils.available_options(path, pid) ci_band = Dropdown( options=available_options, description='Select band:', disabled=False, ) ci_cmaps = Dropdown(options=data_options.color_maps(), value='RdYlGn_r', description='Color map:', disabled=False, layout=Layout(width='15%')) ci_percent = IntRangeSlider( value=[2, 98], min=0, max=100, step=1, description='%:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d', ) show_parcel = Checkbox(value=True, description='Show parcel', disabled=False, indent=False, layout=Layout(width='100px')) ci_cloud = Checkbox(value=False, description='Cloud free', disabled=True, indent=False, layout=Layout(width='140px')) btn_ci = Button(value=False, description='Show images', disabled=False, button_style='info', tooltip='Refresh output', icon='') ci_out = Output() @btn_ci.on_click def btn_ci_on_click(b): btn_ci.description = 'Refresh' btn_ci.icon = 'refresh' with ci_out: ci_out.clear_output() show_imgs() wbox_ci_cloud = HBox([]) if len([val for key, val in available_options if 'SCL' in val]) > 0: wbox_ci_cloud = HBox([ci_cloud]) wbox_ci = HBox([btn_ci, ci_band, show_parcel, ci_percent, wbox_ci_cloud]) def ci_band_change(change): if len(ci_band.value) == 1: if ci_band.value[0] in ['B02', 'B03', 'B04', 'B08']: wbox_ci.children = [btn_ci, ci_band, show_parcel, ci_percent] show_parcel.value = True else: wbox_ci.children = [btn_ci, ci_band, ci_percent] show_parcel.value = False elif ci_band.value == ['B04', 'B08']: wbox_ci.children = [ btn_ci, ci_band, show_parcel, ci_cmaps, ci_percent, wbox_ci_cloud ] show_parcel.value = True else: wbox_ci.children = [ btn_ci, ci_band, show_parcel, ci_percent, wbox_ci_cloud ] show_parcel.value = True ci_band.observe(ci_band_change, 'value') wbox = VBox([wbox_ci, ci_out]) return wbox
def load_UI(self): '''Setting up the interactive visualization tool''' # UI elements range_slider = IntRangeSlider(value=[1, self.time_window], min=1, max=self.time_window, description="Range: ", continuous_update=False) view_ftr_i = IntSlider(min=1, max=self.num_features, default_value=2, description="View Feature: ", continuous_update=False) self.modify_ftr_i = IntSlider(min=1, max=self.num_features, default_value=2, description="Mod Feature: ", continuous_update=False) uniform_slider = FloatSlider(value=0, min=-1, max=1, step=0.05, description='Value:', continuous_update=False) radio_button_uni = RadioButtons(options=[('Positive Weights', 1), ('Negative Weights', -1)], description='Affect:') select_target = BoundedFloatText( value=(self.min_target + self.max_target) / 2, min=self.min_target, max=self.max_target, layout={'width': '150px'}) radio_button_xyz7 = RadioButtons(options=[ ('Present (' + str(self.forecast_window) + '-last values)', 0), ('Future (' + str(self.forecast_window) + '-next values)', 1) ], description='Affect:') enable_iPCA = Checkbox(value=False, description='Enable iPCA') iml_method = ToggleButtons(options=['LioNets', 'Lime']) self.forecast = Dropdown(options=[('Neural', 6), ('Static', 7), ('N-Beats', 8)], description="Forecast: ") mod = Dropdown(options=[('Original', 0), ('Uniform', 1), ('Mean (Local)', 2), ('Mean (Global)', 3), ('Zeros', 4), ('Noise', 5), ('Forecast (Neural)', 6), ('Forecast (Static)', 7), ('Forecast (N-Beats)', 8), ('Forecast (XYZ7)', 9)], description="Mods: ") jsdlink((self.modify_ftr_i, 'value'), (view_ftr_i, 'value')) # UI layout interpretable_settings = HBox( [Label('Interpretation method:'), iml_method, enable_iPCA]) enable_iPCA.layout.margin = '0 0 0 -50px' interpretable_settings.layout.margin = '20px 0 20px 0' standard_settings = VBox([self.modify_ftr_i, view_ftr_i]) xyz7_settings = VBox([ HBox([Label('Desired Target:'), select_target]), radio_button_xyz7 ]) xyz7_settings.layout.margin = '0 0 0 30px' self.opt1_settings = VBox([mod]) self.opt2_settings = VBox([mod, range_slider]) self.opt3_settings = HBox([ VBox([mod, range_slider]), VBox([uniform_slider, radio_button_uni]) ]) self.opt4_settings = HBox([VBox([mod, self.forecast]), xyz7_settings]) self.mod_settings = VBox([]) ui = VBox([ interpretable_settings, HBox([standard_settings, self.mod_settings]) ]) # Starting the interactive tool inter = interactive_output( self.plot_feature, { 'ftr_i': view_ftr_i, 'mod_ftr_i': self.modify_ftr_i, 'mod': mod, 'rng_sldr': range_slider, 'uni_sldr': uniform_slider, 'rd_btn_uni': radio_button_uni, 'select_target': select_target, 'rd_btn_xyz7': radio_button_xyz7, 'forecast_optns': self.forecast, 'iml_method': iml_method, 'enable_ipca': enable_iPCA }) display(ui, inter)