def i_submit_jobs(): from ipywidgets import interact, widgets inodes = widgets.BoundedIntText(value=1, min=1, max=4394, step=1, description='nodes', disabled=False) iwall_minutes = widgets.BoundedIntText(value=10, min=10, max=1440, step=30, description='wall minutes', disabled=False) isave = widgets.Checkbox(value=False, description='save', indent=True) isubmit = widgets.ToggleButton( value=False, description='submit', disabled=False, button_style='success', # 'success', 'info', 'warning', 'danger' or '' tooltip='submit job', icon='') # ('check') im = interact( submit_jobs, project='', queue=['debug-flat-quad', 'debug-cache-quad', 'default', 'backfill'], nodes=inodes, wall_minutes=iwall_minutes, job_mode=['mpi', 'serial'], wf_filter='', save=isave, submit=isubmit)
def i_get_job_script(): from ipywidgets import widgets, Layout, interact_manual from IPython.display import display, clear_output from os.path import isfile inodes = widgets.BoundedIntText(value=1, min=1, max=4394, step=1, description='nodes', disabled=False) iranks_per_node = widgets.BoundedIntText(value=1, min=1, max=64, step=1, description='ranks/node', disabled=False) iaffinity = widgets.Text(value='-d 1 -j 1 --cc depth', description='affinity') icommand = widgets.Text(value='', description='executable and args') out = widgets.interactive_output( get_job_script, { 'nodes': inodes, 'ranks_per_node': iranks_per_node, 'affinity': iaffinity, 'command': icommand }) box = widgets.VBox( [widgets.VBox([inodes, iranks_per_node, iaffinity, icommand]), out]) display(box) return
def show_decomposition_traces(node: DecompositionSeries): # Produce figure def control_plot(x0, x1, ch0, ch1): fig, ax = plt.subplots(nrows=nBands, ncols=1, sharex=True, figsize=(14, 7)) for bd in range(nBands): data = node.data[x0:x1, ch0:ch1 + 1, bd] xx = np.arange(x0, x1) mu_array = np.mean(data, 0) sd_array = np.std(data, 0) offset = np.mean(sd_array) * 5 yticks = [i * offset for i in range(ch1 + 1 - ch0)] for i in range(ch1 + 1 - ch0): ax[bd].plot(xx, data[:, i] - mu_array[i] + yticks[i]) ax[bd].set_ylabel('Ch #', fontsize=20) ax[bd].set_yticks(yticks) ax[bd].set_yticklabels([str(i) for i in range(ch0, ch1 + 1)]) ax[bd].tick_params(axis='both', which='major', labelsize=16) ax[bd].set_xlabel('Time [ms]', fontsize=20) return fig nSamples = node.data.shape[0] nChannels = node.data.shape[1] nBands = node.data.shape[2] fs = node.rate # Controls field_lay = widgets.Layout(max_height='40px', max_width='100px', min_height='30px', min_width='70px') x0 = widgets.BoundedIntText(value=0, min=0, max=int(1000 * nSamples / fs - 100), layout=field_lay) x1 = widgets.BoundedIntText(value=nSamples, min=100, max=int(1000 * nSamples / fs), layout=field_lay) ch0 = widgets.BoundedIntText(value=0, min=0, max=int(nChannels - 1), layout=field_lay) ch1 = widgets.BoundedIntText(value=10, min=0, max=int(nChannels - 1), layout=field_lay) controls = {'x0': x0, 'x1': x1, 'ch0': ch0, 'ch1': ch1} out_fig = widgets.interactive_output(control_plot, controls) # Assemble layout box lbl_x = widgets.Label('Time [ms]:', layout=field_lay) lbl_ch = widgets.Label('Ch #:', layout=field_lay) lbl_blank = widgets.Label(' ', layout=field_lay) hbox0 = widgets.HBox(children=[lbl_x, x0, x1, lbl_blank, lbl_ch, ch0, ch1]) vbox = widgets.VBox(children=[hbox0, out_fig]) return vbox
def _update_navi(self, pos): """Add navigation buttons.""" posy_sel = widgets.BoundedIntText(value=0, min=-1000, max=1000, step=1, disabled=False, continuous_update=True, description='Horz.') posx_sel = widgets.BoundedIntText(value=0, min=-1000, max=1000, step=1, disabled=False, continuous_update=True, description='Vert.') posx_sel.observe(self._move_quadrants, names='value') posy_sel.observe(self._move_quadrants, names='value') if pos is None: self.buttons = [self.buttons[0]] elif len(self.buttons) == 1: self.buttons += [posx_sel, posy_sel] else: self.buttons[1] = posx_sel self.buttons[2] = posy_sel self.row1 = widgets.HBox(self.buttons) self.children = [self.row1, self.row2]
def __init__(self, instrument, mode): self.container = widgets.VBox(width="100%", background_color="#CCCCCC") self.instrument = instrument self.instrument.set_mode(mode) self.instrument.get_apertures() self.aper_box = widgets.HBox(padding='10px', width="100%") self.aperture = widgets.Dropdown(description="Aperture:", options=self.instrument.apertures) self.aper_box.children = [self.aperture] self.on_aperture_change(dummy) self.inst_box = widgets.HBox(padding='10px', width="100%") self.filt = widgets.Dropdown(description="Filter:", options=self.instrument.filters) self.disp = widgets.Dropdown(description="Disperser:", options=self.instrument.dispersers) self.inst_box.children = [self.filt, self.disp] self.det_box = widgets.HBox(padding='10px', width="100%") self.ngroups = widgets.BoundedIntText(description="Groups: ", min=3, max=999, value=6, width=30) self.nints = widgets.BoundedIntText(description="Integrations: ", min=1, max=999, value=1, width=30) self.nexps = widgets.BoundedIntText(description="Exposures: ", min=1, max=999, value=1, width=30) self.det_box.children = [self.ngroups, self.nints, self.nexps] self.advanced = widgets.VBox(width="100%", background_color="#CCCCCC") self.readmode = widgets.Dropdown(description="Readmode:", options=self.instrument.readmodes, value='medium8') self.subarray = widgets.Dropdown(description="Sub-array:", options=self.instrument.subarrays, value='1024x1024') self.advanced.children = [self.readmode, self.subarray] self.advanced_drop = widgets.Accordion(children=[self.advanced]) self.advanced_drop.set_title(0, "ADVANCED") self.advanced_drop.selected_index = None self.container.children = [ self.aper_box, self.inst_box, self.det_box, self.advanced_drop ] self.aperture.observe(self.on_aperture_change)
def _build_det_form(self): self.ngroups = widgets.BoundedIntText( description="Groups:", min=2, max=999, value=10) self.nints = widgets.BoundedIntText( description="Integrations:", min=1, max=999, value=1) self.nexps = widgets.BoundedIntText( description="Exposures:", min=1, max=999, value=1) return widgets.VBox([self.ngroups, self.nints, self.nexps])
def __init__(self, iterable, func, fig): self._iterable = iterable self.func = func self.fig = fig self.axes = np.array(self.fig.axes).flatten() self.idx = 0 self.btn_first = widgets.Button(description='First') self.btn_prev = widgets.Button(description='Prev') self.int_box = widgets.BoundedIntText(value=0, min=0, max=len(iterable) - 1) self.btn_next = widgets.Button(description='Next') self.btn_last = widgets.Button(description='Last') self.btn_random = widgets.Button(description='Random') self.int_box.observe(self.handle_int_box, names='value') self.btn_first.on_click(self.on_first) self.btn_prev.on_click(self.on_prev) self.btn_next.on_click(self.on_next) self.btn_last.on_click(self.on_last) self.btn_random.on_click(self.on_random) btn_hbox = widgets.HBox() btn_hbox.children = [ self.btn_first, self.btn_prev, self.int_box, self.btn_next, self.btn_last, self.btn_random ] self.update_graph() display(btn_hbox)
def updateBox(self): """ retrieve optional paramters and display them in the output cell""" for k in vars(self.ml_classifier_cls): if (not k.startswith('__')) and k != 'status' and k != 'model': value = getattr(self.ml_classifier_cls, k) self.parameters[k] = value rows = [ widgets.HTML( value='<h3>Configure your backend machine learning model</h3>' '<p>If you are not sure what the parameters are, just leave them as they are.</p>' '<p>There are <b>' + str(self.leftover) + '</b> samples left unreviewed. The ML model will retrain at a pace ' 'of once per <b>' + str(self.learning_pace) + '</b> samples.') ] for name, value in self.parameters.items(): if type(value) == int: self.parameter_inputs[name] = widgets.BoundedIntText( description=name, value=value, min=-1) rows.append(self.parameter_inputs[name]) elif type(value) == float: self.parameter_inputs[name] = widgets.BoundedFloatText( description=name, value=value) rows.append(self.parameter_inputs[name]) elif type(value) == str: self.parameter_inputs[name] = widgets.Text(description=name, value=value) rows.append(self.parameter_inputs[name]) rows += self.addSeparator(top='10px') + self.addSeparator( top='10px') + [ self.addPreviousNext(self.show_previous, self.show_next) ] self.box = widgets.VBox(rows) pass
def __init__(self, dynamic_table: DynamicTable, group_by=None, window=None, start_discard_rows=None): """ Parameters ---------- dynamic_table group_by window: None or bool, """ super().__init__(dynamic_table) groups = self.get_groups() self.discard_rows = start_discard_rows self.limit_bit = widgets.BoundedIntText(value=50, min=0, max=99999, disabled=True, layout=Layout(max_width='70px')) self.limit_bit.observe(self.limit_bit_observer) self.limit_cb = widgets.Checkbox(description='limit', style={'description_width': 'initial'}, disabled=True, indent=False, layout=Layout(max_width='70px')) self.limit_cb.observe(self.limit_cb_observer) self.order_dd = widgets.Dropdown(options=[None] + list(groups), description='order by', layout=Layout(max_width='120px'), style={'description_width': 'initial'}) self.order_dd.observe(self.order_dd_observer) self.ascending_dd = widgets.Dropdown(options=['ASC', 'DESC'], disabled=True, layout=Layout(max_width='70px')) self.ascending_dd.observe(self.ascending_dd_observer) range_controller_max = min(30, self.nitems) if window is None: self.range_controller = RangeController(0, self.nitems, start_value=(0, range_controller_max), dtype='int', description='units', orientation='vertical') self.range_controller.observe(self.range_controller_observer) self.window = self.range_controller.value elif window is False: self.window = (0, self.nitems) self.range_controller = widgets.HTML('') self.group_sm = widgets.SelectMultiple(layout=Layout(max_width='100px'), disabled=True, rows=1) self.group_sm.observe(self.group_sm_observer) if group_by is None: self.group_dd = widgets.Dropdown(options=[None] + list(groups), description='group by', style={'description_width': 'initial'}, layout=Layout(width='90%')) self.group_dd.observe(self.group_dd_observer) else: self.group_dd = None self.set_group_by(group_by) self.children = self.get_children() self.layout = Layout(width='280px') self.update_value()
def createTextInt(self, val=0.0, minVal=0, maxVal=100, stepSize=1, desc="d"): text = widgets.BoundedIntText( value=int(val), min=int(minVal), max=int(maxVal), step=int(stepSize), description=str(desc), disabled=False, style = self.style ) return text
def _create_int_range_widget(self, key, disabled): # type: (str, bool) -> widgets.HBox """Return an HBox containing two BoundedIntText widgets with the parameter's range values. The widgets are created to fulfill the "int range" type condition: lower_bound < upper_bound Keyword Arguments: key -- name of the parameter disabled -- is the parameter/widget disabled? """ lowerBound = widgets.BoundedIntText(value=self[key][0], description=key, min=self._min(key), max=self[key][1] - 1, style=self._style, layout=Layout(width='50%'), continuous_update=False, disabled=disabled) # Save the widget's value in case its constructor automatically # replaces an empty one given as argument self._parameters[key]['value'][0] = lowerBound.value # Add handler for when the "value" trait changes lowerBound.observe(self._range_handler, names='value') upperBound = widgets.BoundedIntText(value=self[key][1], description=key, min=self[key][0] + 1, max=self._max(key), style=self._style, layout=Layout(width='50%'), continuous_update=False, disabled=disabled) # Save the widget's value in case its constructor automatically # replaces an empty one given as argument self._parameters[key]['value'][1] = upperBound.value # Add handler for when the "value" trait changes upperBound.observe(self._range_handler, names='value') return widgets.HBox([lowerBound, upperBound], layout=Layout(width=self._inputWidth))
def i_get_job_script_manual(): from ipywidgets import widgets, Layout, interact_manual from IPython.display import display, clear_output from os.path import isfile inodes = widgets.BoundedIntText(value=1, min=1, max=4394, step=1, description='nodes', disabled=False) iranks_per_node = widgets.BoundedIntText(value=1, min=1, max=64, step=1, description='rank_per_nodes', disabled=False) im = interact_manual(get_job_script, nodes=inodes, ranks_per_node=irank_per_nodes) get_job_script_button = im.widget.children[4] get_job_script_button.description = 'get_job_script' return
def __init__(self, description='', name=str(Step.global_id + 1), sampler_cls: type = KeywordStratefiedSampler): super().__init__(name=name) self.toggle = widgets.ToggleButtons( options=sample_options, value=sample_options[-1], description='What to do with previously sampled data? ', style=dict(description_width='initial'), button_style='info') self.toggle.observe(self.onPreviousSampleHandleChange) self.sample_size_input = widgets.BoundedIntText( value=0, min=0, max=0, step=1, description='Total documents you want to sample:', style=dict(description_width='initial')) self.sample_size_input.observe(self.onSampleConfigChange) self.sampler_cls = sampler_cls self.sampled_summary = widgets.HTML(value='') self.percent_slider = widgets.IntSlider(value=70, min=0, max=100, step=5, description='', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d') self.percent_slider.observe(self.onSampleConfigChange) # save DOC_IDs that contain or not contain keywords filters (used in sampling strategy) self.samples = {"contain": [], "notcontain": []} self.box = None self.data = {'docs': [], 'annos': OrderedDict()} self.ready = False # reset, continue, addmore, self.move_next_option = '' self.total = None self.total_contains = None self.un_reviewed = 0 self.sampler = None self.samples = dict() self.current_stats = dict() self.max_threshold = ConfigReader.getValue("review/rb_model_threshold") self.sample_sizes = dict()
def show_spike_event_series(ses: SpikeEventSeries, **kwargs): def control_plot(spk_ind): fig, ax = plt.subplots(figsize=(9, 5)) data = ses.data[spk_ind] if nChannels > 1: for ch in range(nChannels): ax.plot(data[:, ch], color="#d9d9d9") else: ax.plot(data[:], color="#d9d9d9") ax.plot(np.mean(data, axis=1), color="k") ax.set_xlabel("Time") ax.set_ylabel("Amplitude") fig.show() return fig2widget(fig) if len(ses.data.shape) == 3: nChannels = ses.data.shape[2] else: nChannels = ses.data.shape[1] nSpikes = ses.data.shape[0] # Controls field_lay = widgets.Layout(max_height="40px", max_width="100px", min_height="30px", min_width="70px") spk_ind = widgets.BoundedIntText(value=0, min=0, max=nSpikes - 1, layout=field_lay) controls = {"spk_ind": spk_ind} out_fig = widgets.interactive_output(control_plot, controls) # Assemble layout box lbl_spk = widgets.Label("Spike ID:", layout=field_lay) lbl_nspks0 = widgets.Label("N° spikes:", layout=field_lay) lbl_nspks1 = widgets.Label(str(nSpikes), layout=field_lay) lbl_nch0 = widgets.Label("N° channels:", layout=field_lay) lbl_nch1 = widgets.Label(str(nChannels), layout=field_lay) hbox0 = widgets.HBox(children=[lbl_spk, spk_ind]) vbox0 = widgets.VBox(children=[ widgets.HBox(children=[lbl_nspks0, lbl_nspks1]), widgets.HBox(children=[lbl_nch0, lbl_nch1]), hbox0, ]) hbox1 = widgets.HBox(children=[vbox0, out_fig]) return hbox1
def browse_images_orig_prep(img_orig_py, img_prep_py, size, slice_ID, fig, ax1, ax2, image_data): # function for slider def view_image_1(slider_1): ax1.imshow(img_orig_py[:,:,slider_1], cmap=plt.cm.gray, origin='lower',interpolation=None) ax1.set_title(image_data["image_name_root"] + "_orig.mha") ax1.axis('off') #display(fig) ax2.imshow(img_prep_py[:,:,slider_1], cmap=plt.cm.gray, origin='lower',interpolation=None) ax2.set_title(image_data["image_name_root"] + "_prep.mha") ax2.axis('off') display(fig) # link function and sliders (created inside the interactive command) slider = interactive(view_image_1, slider_1 = widgets.IntSlider(min=0, max=size[2]-1, value=slice_ID, step=1, continuous_update=False, # avoids intermediate image display readout=False, layout=Layout(width='450px'), description='Slice n.') ) # show images before start interacting slider.update() # slice number scrolling text = widgets.BoundedIntText(description="", # BoundedIntText to avoid that displayed text goes outside of the range min=0, max=size[2]-1, value=slice_ID, step=1, continuous_update=False, layout=Layout(width='50px')) # link slider and text widgets.jslink((slider.children[:-1][0], 'value'), (text, 'value')) # layout slider_box = HBox(slider.children[:-1]) widget_box = HBox([slider_box, text]) whole_box = VBox([widget_box, slider.children[-1] ]) return whole_box
def BoundedIntText(question): start_time = time.time() widget = widgets.BoundedIntText(value=5, min=0, max=1000, step=1, description='Text:', disabled=False) display(widget) def on_value_change(change): # Appends to the dictionary answer Answer_Dict[question].append(change["new"]) widget.observe(on_value_change, names='value') button(question, start_time)
def __init__(self, on_interact=None, output=None, overwrite_previous_output=True, feedback=False, run=True, action_kws={}, *args, **kwargs): super().__init__(on_interact=on_interact, output=output, overwrite_previous_output=overwrite_previous_output, feedback=feedback, action_kws=action_kws) self.widget = widgets.BoundedIntText(*args, **kwargs) if run: self.run()
def show_spike_event_series(ses, **kwargs): def control_plot(spk_ind): fig, ax = plt.subplots(figsize=(9, 5)) data = ses.data[spk_ind, :, :] for ch in range(nChannels): ax.plot(data[:, ch], color='#d9d9d9') ax.plot(np.mean(data, axis=1), color='k') ax.set_xlabel('Time') ax.set_ylabel('Amplitude') plt.show() return fig2widget(fig) nChannels = ses.data.shape[2] nSpikes = ses.data.shape[0] # Controls field_lay = widgets.Layout(max_height='40px', max_width='100px', min_height='30px', min_width='70px') spk_ind = widgets.BoundedIntText(value=0, min=0, max=nSpikes - 1, layout=field_lay) controls = {'spk_ind': spk_ind} out_fig = widgets.interactive_output(control_plot, controls) # Assemble layout box lbl_spk = widgets.Label('Spike ID:', layout=field_lay) lbl_nspks0 = widgets.Label('N° spikes:', layout=field_lay) lbl_nspks1 = widgets.Label(str(nSpikes), layout=field_lay) lbl_nch0 = widgets.Label('N° channels:', layout=field_lay) lbl_nch1 = widgets.Label(str(nChannels), layout=field_lay) hbox0 = widgets.HBox(children=[lbl_spk, spk_ind]) vbox0 = widgets.VBox(children=[ widgets.HBox(children=[lbl_nspks0, lbl_nspks1]), widgets.HBox(children=[lbl_nch0, lbl_nch1]), hbox0 ]) hbox1 = widgets.HBox(children=[vbox0, out_fig]) return hbox1
def __init__(self, *args, slider=True, **kwargs): super(IterFigure, self).__init__(*args, **kwargs) self.idx = 0 self._btn_first = widgets.Button(description='First') self._btn_prev = widgets.Button(description='Prev') self._int_box = widgets.BoundedIntText(value=0, min=0, max=1) self._btn_next = widgets.Button(description='Next') self._btn_last = widgets.Button(description='Last') self._btn_random = widgets.Button(description='Random') self._int_box.observe(self.handle_int_box, names='value') self._btn_first.on_click(self.on_first) self._btn_prev.on_click(self.on_prev) self._btn_next.on_click(self.on_next) self._btn_last.on_click(self.on_last) self._btn_random.on_click(self.on_random) self.btn_hbox = widgets.HBox() self.btn_hbox.children = [ self._btn_first, self._btn_prev, self._int_box, self._btn_next, self._btn_last, self._btn_random ] if slider: self._slider = widgets.IntSlider(value=0, min=0, max=1, layout=dict(width='99%'), readout=False) widgets.jslink((self._int_box, 'value'), (self._slider, 'value')) self.vbox = widgets.VBox() self.vbox.children = [self.btn_hbox, self._slider] self.box = self.vbox else: self.box = self.btn_hbox
def _create_int_widget(self, key, disabled): # type: (str, bool) -> widgets.BoundedIntText """Return a BoundedIntText widget with the parameter's value. Keyword Arguments: key -- name of the parameter disabled -- is the parameter/widget disabled? """ inputWidget = widgets.BoundedIntText( value=self[key], description=key, min=self._min(key), max=self._max(key), style=self._style, layout=Layout(width=self._inputWidth), continuous_update=False, disabled=disabled) # Save the widget's value in case its constructor automatically # replaces an empty one given as argument self._parameters[key]['value'] = inputWidget.value # Add handler for when the "value" trait changes inputWidget.observe(self._default_handler, names='value') return inputWidget
description=r'Baseline quarantine rate ($\xi^u$)', style=style_med, layout=layout_med) A_rel = widgets.BoundedFloatText( value=0.5, min=0, max=1, step=0.001, disabled=False, description=r'Relative productivity of quarantined ($A_{rel}$)', style=style_med, layout=layout_med) d_vaccine = widgets.BoundedIntText(value=500, min=20, max=10000, step=1, disabled=False, description='Date of vaccine', style=style_med, layout=layout_med) rel_ρ = widgets.BoundedFloatText( value=1, min=0., max=1, step=0.001, disabled=False, description=r'Relative infectiousness ($\rho^A/\rho^S$)', style=style_med, layout=layout_med) δ_param = widgets.BoundedIntText( value=6, min=1,
def i_qsub(): """ Submits a job to the queue with the given parameters. """ from ipywidgets import widgets, Layout, interact_manual from IPython.display import display, clear_output from os.path import isfile inodes = widgets.BoundedIntText(value=1, min=1, max=4394, step=1, description='nodes', disabled=False) iranks_per_node = widgets.BoundedIntText(value=1, min=1, max=64, step=1, description='rank/nodes', disabled=False) iqueue = widgets.Dropdown( options=['debug-flat-quad', 'debug-cache-quad', 'default', 'backfill'], description='queue', value='debug-cache-quad') iwall_minutes = widgets.BoundedIntText(value=10, min=10, max=1440, step=10, description='wall minutes', disabled=False) iscript = widgets.Textarea(value='#!/bin/bash -x \n', description='job script', layout=Layout(flex='0 0 auto', width='auto', height='200px')) iscript_file = widgets.Text(value='', description='job script file name') iproject = widgets.Text(value='', description='project') isave = widgets.Checkbox(value=False, description='save', indent=True) isubmit = widgets.Button(value=False, description='submit', disabled=False, button_style='success', tooltip='submit job', icon='') output = widgets.Output() display(iproject, inodes, iqueue, iwall_minutes, iscript_file, iscript, isubmit, output) jobid = '' def submit_clicked(b): with output: clear_output() jobid = qsub(project=iproject.value, script=iscript.value, script_file=iscript_file.value, queue=iqueue.value, nodes=inodes.value, wall_minutes=iwall_minutes.value) isubmit.on_click(submit_clicked) return
def browse_images(moving_py, mask_py, ax_i, fig, moving_root, last_value, sliceID): # The code in this function has to be separate. If code directly into show_segmented_images, when using widgets, they update the last image # function for slider def view_image(slider): # get slice of moving image slice_moving_py = moving_py[:, :, slider] # get slice in mask slice_mask_py = mask_py[:, :, slider] slice_mask_masked = np.ma.masked_where(slice_mask_py == 0, slice_mask_py) # show both ax_i.imshow(slice_moving_py, cmap=plt.cm.gray, origin='lower', interpolation=None) ax_i.imshow(slice_mask_masked, 'hsv', interpolation=None, origin='lower', alpha=1, vmin=0, vmax=100) ax_i.set_title(moving_root) ax_i.axis('off') display(fig) # link sliders and its function slider_image = interactive( view_image, slider=widgets.IntSlider( min=0, max=last_value, value=sliceID[1], step=1, continuous_update=False, # avoids intermediate image display readout=False, layout=Layout(width='180px'), description='Slice n.')) # show figures before start interacting slider_image.update() # slice number scrolling text = widgets.BoundedIntText( description= "", # BoundedIntText to avoid that displayed text goes outside of the range min=0, max=last_value, value=sliceID[1], step=1, continuous_update=False, layout=Layout(width='50px')) # link slider and text widgets.jslink((slider_image.children[:-1][0], 'value'), (text, 'value')) # layout slider_box = HBox(slider_image.children[:-1]) widget_box = HBox([slider_box, text]) whole_box = VBox([widget_box, slider_image.children[-1]]) return whole_box
def browse_images(moving_py, mask_py, ax_i, fig, moving_root, last_value, sliceID): # The code in this function has to be separate. If code directly into show_segmented_images, when using widgets, they update the last image # function for slider def view_image(slider): # get slice of moving image slice_moving_py = moving_py[:,:,slider] # get slice in mask slice_mask_py = mask_py[:,:,slider] slice_mask_masked = np.ma.masked_where(slice_mask_py == 0, slice_mask_py) # show both ax_i.imshow(slice_moving_py, cmap=plt.cm.gray, origin='lower',interpolation=None) ren = ax_i.imshow(slice_mask_masked, 'jet' , interpolation=None, origin='lower', alpha=1, vmin=0, vmax=100) ax_i.set_title(moving_root) ax_i.axis('off') # colorbar cbar_ax = fig.add_axes([0.08, 0.4, 0.01, 0.2]) #[left, bottom, width, height] fig.colorbar(ren, cax=cbar_ax, orientation='vertical', shrink=0.60, ticks=[0, 20, 40, 60, 80, 100]) cbar_ax.set_title('[ms]') # The following two lines are to avoid this warning in the notebook: # Adding an axes using the same arguments as a previous axes currently reuses the earlier instance. In a future version, a new instance will always be created and returned. Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance. # To be fixed in following releases import warnings warnings.filterwarnings("ignore") # display display(fig) # link sliders and its function slider_image = interactive(view_image, slider = widgets.IntSlider(min=0, max=last_value, value=sliceID[1], step=1, continuous_update=False, # avoids intermediate image display readout=False, layout=Layout(width='250px'), description='Slice n.')) # show figures before start interacting slider_image.update() # slice number scrolling text = widgets.BoundedIntText(description="", # BoundedIntText to avoid that displayed text goes outside of the range min=0, max=last_value, value=sliceID[1], step=1, continuous_update=False, layout=Layout(width='50px')) # link slider and text widgets.jslink((slider_image.children[:-1][0], 'value'), (text, 'value')) # layout slider_box = HBox(slider_image.children[:-1]) widget_box = HBox([slider_box, text]) whole_box = VBox([widget_box, slider_image.children[-1] ]) return whole_box
# Host IP text widget hostIPWidget = widgets.Text (value = "10.0.6.57:8080", description = "IP address:" ) # Encryption preferences widgets - SSL and self-signed certificate isSSLWidget = widgets.Checkbox(value = True, description = 'Use HTTPS?') isSSLWidget.observe (update) isSelfSignedWidget = widgets.Checkbox(value = True, description = 'Self-signed SSL?', disabled = not isSSLWidget.value) encryptionWidgets = widgets.HBox([isSSLWidget, isSelfSignedWidget]) # Datetime widgets dateLayout = widgets.Layout(width='25%') startDateWidget = widgets.DatePicker (description = 'Start: ', layout = dateLayout) startHour = widgets.BoundedIntText (min = 0, max = 23, step = 1,description = 'Hour:', layout = dateLayout) startMinute = widgets.BoundedIntText (min = 0, max = 59, step = 1, description = 'Minute:', layout = dateLayout) startSecond = widgets.BoundedIntText(min = 0, max = 59, step = 1, description = 'Seconds:', layout = dateLayout) endDateWidget = widgets.DatePicker(description = 'End: ', layout = dateLayout) endHour = widgets.BoundedIntText(min = 0, max = 23, step = 1,description = 'Hour:', layout = dateLayout) endMinute = widgets.BoundedIntText(min = 0, max = 59, step = 1, description = 'Minute:', layout = dateLayout) endSecond = widgets.BoundedIntText(min = 0, max = 59, step = 1, description = 'Seconds:', layout = dateLayout) dateTimeWidgets = widgets.VBox([widgets.HBox([startDateWidget, startHour, startMinute, startSecond]), \ widgets.HBox([endDateWidget, endHour, endMinute, endSecond])]) # Set default initialization values for the datetime widgets now = datetime.datetime.now() startDateWidget.value = now - datetime.timedelta (minutes = 10)
def _build_instance_creation_widgets(self) -> Tuple[list, VBox]: """ Build widgets for creating instance and put them into their respective accordions :return: list of instance creation widgets (for easier manipulation and getting values from them), VBox (layout) to be displayed in a tab """ instance_widgets = [] style = {'description_width': '60%', 'width': 'auto'} # create widget for each variable for e, column in enumerate(self.feature_names): if e in self.categorical_names: # for categoricals make dropdown with name, but value as a number (from 0) options = { key: val for val, key in enumerate(self.categorical_names[e]) } instance_widgets.append( Dropdown(description=f"{column}:", options=options, style=style)) else: instance_widgets.append( FloatText(description=f"{column}: ", style=style)) # fill grid with widgets widgets_grid = GridspecLayout(ceil(self.X_train.shape[1] / 2), 2, layout=Layout(overflow='scroll', max_height='25em')) for e, item in enumerate(instance_widgets): widgets_grid[e // 2, e % 2] = item # add the selection of instance in train data fill_from_df = widgets.BoundedIntText( value=0, min=0, max=len(self.X_train) - 1, step=1, description='Instance id:', style=style, description_tooltip= 'When changed all values in "Build your own instance" will be set accordingly' ) # connect instance selection to builder widgets def on_value_change(change): instance = self.X_train[change['new']] for e, val in enumerate(instance): instance_widgets[e].value = val fill_from_df.observe(on_value_change, names='value') # importing instance from variable instance_variable = UpdatingCombobox( options_keys=self.kernel_globals.keys(), value='', description='Variable with instance:', description_tooltip= 'Variable with your instance as numpy array, pandas dataframe or series.\n' 'After clicking on "import instance", the values in "Build your own instance"' ' will be set accordingly.', style=style) def fill_from_variable(orig_btn): # param ignored instance = self._get_variable_from_kernel(instance_variable.value) try: for e, val in enumerate(instance): instance_widgets[e].value = val # reset to without error import_box.children = [instance_variable, import_btn] except: # add error to box import_box.children = [ instance_variable, import_btn, import_error ] import_error = HTML("Import from variable failed\n") import_btn = Button(description='Import') import_btn.on_click(fill_from_variable) import_box = VBox(children=(instance_variable, import_btn)) # put both into separate accordions to allow both opened at the same time accordion1 = Accordion(children=[fill_from_df, import_box]) accordion1.set_title(0, 'Select instance from dataset') accordion1.set_title(1, 'Import instance from variable') accordion2 = Accordion(children=[widgets_grid]) accordion2.set_title(0, 'Build your own instance') accordions = VBox([accordion1, accordion2]) # set everything to first instance on_value_change({'new': 0}) return instance_widgets, accordions
def __init__( self, dynamic_table: DynamicTable, group_by=None, window=None, keep_rows=None, control_order=True, control_limit=True, groups=None, ): """ Parameters ---------- dynamic_table: DynamicTable the table wrt which the grouping is performed group_by: str the column name from the dynamic table for which the grouping is performed window: None or bool, keep_rows: Iterable rows of dynamic table to consider in the grouping op control_limit: bool whether to control the limit of the displayed rows control_order: bool whether to control the order of the displayed rows based on other column groups: dict dict(column_name=column_values) to work with specific columns only """ super().__init__(dynamic_table, keep_rows) self.control_order = control_order self.control_limit = control_limit self.categorical_columns = self.get_groups( ) if groups is None else groups self.limit_bit = None self.limit_cb = None self.order_dd = None self.ascending_dd = None self.group_sm = None self.group_dd = None if len(self.categorical_columns) > 0: if control_limit: self.limit_cb = widgets.Checkbox( description="limit", style={"description_width": "initial"}, disabled=True, indent=False, layout=Layout(max_width="70px"), ) self.limit_cb.observe(self.limit_cb_observer) self.limit_bit = widgets.BoundedIntText( value=50, min=0, max=99999, disabled=True, layout=Layout(max_width="70px"), ) self.limit_bit.observe(self.limit_bit_observer) self.order_dd = widgets.Dropdown( options=[None] + list(self.categorical_columns), description="order by", layout=Layout(max_width="120px"), style={"description_width": "initial"}, disabled=not len(self.categorical_columns), ) self.order_dd.observe(self.order_dd_observer) self.ascending_dd = widgets.Dropdown( options=["ASC", "DESC"], disabled=True, layout=Layout(max_width="70px")) self.ascending_dd.layout.height = "0px" self.ascending_dd.layout.visibility = "hidden" self.ascending_dd.observe(self.ascending_dd_observer) self.group_sm = widgets.SelectMultiple(layout=Layout(width="0px"), disabled=True, rows=1) self.group_sm.layout.visibility = "hidden" self.group_sm.observe(self.group_sm_observer) if group_by is None and len(self.categorical_columns) > 0: self.group_dd = widgets.Dropdown( options=[None] + list(self.categorical_columns), description="group by", style={"description_width": "initial"}, layout=Layout(width="90%"), disabled=not len(self.categorical_columns), ) self.group_dd.observe(self.group_dd_observer) else: self.group_dd = None self.set_group_by(group_by) if window is None: range_controller_max = min(30, self.nitems) dt_desc_map = { "DynamicTable": "traces", "TimeIntervals": "trials", "Units": "units", "PlaneSegmentation": "image_planes", } desc = (dt_desc_map[dynamic_table.neurodata_type] if dynamic_table is not None else "traces") self.range_controller = RangeController( 0, self.nitems, start_value=(0, range_controller_max), dtype="int", description=desc, orientation="vertical", ) self.range_controller.layout = Layout(min_width="75px") self.range_controller.observe(self.range_controller_observer) self.window = self.range_controller.value elif window is False: self.window = (0, self.nitems) self.range_controller = widgets.HTML("") self.children = self.get_children() #self.layout = Layout(overflow_x='auto') self.update_value()
def orthoslices_3D(data, normalize=True, continuous_update=False, **kwargs): if not isnotebook: print('Function not suited for working outside of Jupyter notebooks!') else: get_ipython().magic('matplotlib notebook') get_ipython().magic('matplotlib notebook') e_range, x_range, y_range = data.shape dmin = np.amin(data) dmax = np.amax(data) w_e = widgets.IntSlider(value=e_range // 2, min=0, max=e_range - 1, step=1, description='Energy:', disabled=False, continuous_update=continuous_update, orientation='horizontal', readout=True, readout_format='d') w_kx = widgets.IntSlider(value=x_range // 2, min=0, max=x_range - 1, step=1, description='kx:', disabled=False, continuous_update=continuous_update, orientation='horizontal', readout=True, readout_format='d') w_ky = widgets.IntSlider(value=y_range // 2, min=0, max=y_range - 1, step=1, description='ky:', disabled=False, continuous_update=continuous_update, orientation='horizontal', readout=True, readout_format='d') w_clim = widgets.FloatRangeSlider(value=[.1, .9], min=0, max=1, step=0.001, description='Contrast:', disabled=False, continuous_update=continuous_update, orientation='horizontal', readout=True, readout_format='.1f') w_cmap = widgets.Dropdown(options=cmaps, value='terrain', description='colormap:', disabled=False) w_bin = widgets.BoundedIntText(value=1, min=1, max=min(data.shape), step=1, description='resample:', disabled=False) w_interpolate = widgets.Checkbox(value=True, description='Interpolate', disabled=False) w_grid = widgets.Checkbox(value=False, description='Grid', disabled=False) w_trackers = widgets.Checkbox(value=True, description='Trackers', disabled=False) w_trackercol = widgets.ColorPicker(concise=False, description='tracker line color', value='orange') ui_pos = widgets.HBox([w_e, w_kx, w_ky]) ui_color = widgets.HBox([ widgets.VBox([w_clim, w_cmap]), widgets.VBox([w_bin, w_interpolate, w_grid]), widgets.VBox([w_trackers, w_trackercol]), ]) children = [ui_pos, ui_color] tab = widgets.Tab(children=children, ) tab.set_title(0, 'data select') tab.set_title(1, 'colormap') figsize = kwargs.pop('figsize', (5, 5)) fig = plt.figure(figsize=figsize, **kwargs) plt.tight_layout() # [left, bottom, width, height] # fig.locator_params(nbins=4) # cbar_ax = fig.add_axes([.05,.4,.05,4], xticklabels=[], yticklabels=[]) # cbar_ax.yaxis.set_major_locator(plt.LinearLocator(5)) img_ax = fig.add_axes([.15, .4, .4, .4], xticklabels=[], yticklabels=[]) img_ax.xaxis.set_major_locator(plt.LinearLocator(5)) img_ax.yaxis.set_major_locator(plt.LinearLocator(5)) xproj_ax = fig.add_axes([.15, .1, .4, .28], xticklabels=[], yticklabels=[]) xproj_ax.set_xlabel('$k_x$') xproj_ax.xaxis.set_major_locator(plt.LinearLocator(5)) yproj_ax = fig.add_axes([.57, .4, .28, .4], xticklabels=[], yticklabels=[]) yproj_ax.yaxis.set_label_position("right") yproj_ax.set_ylabel('$k_y$') yproj_ax.yaxis.set_major_locator(plt.LinearLocator(5)) for ax in [img_ax, yproj_ax, xproj_ax]: # ,cbar_ax]: ax.tick_params(axis="both", direction="in", bottom=True, top=True, left=True, right=True, which='both') clim_ = 0.01, .99 e_img = norm_img(data[data.shape[0] // 2, :, :]) y_img = norm_img(data[:, data.shape[1] // 2, :]) x_img = norm_img(data[:, :, data.shape[2] // 2].T) e_plot = img_ax.imshow( e_img, cmap='terrain', aspect='auto', interpolation='gaussian', clim=clim_, ) # origin='lower') x_plot = yproj_ax.imshow( x_img, cmap='terrain', aspect='auto', interpolation='gaussian', clim=clim_, ) # origin='lower') y_plot = xproj_ax.imshow( y_img, cmap='terrain', aspect='auto', interpolation='gaussian', clim=clim_, ) # origin='lower') pe_x = img_ax.axvline(x_range / 2, c='orange') pe_y = img_ax.axhline(y_range / 2, c='orange') px_x = xproj_ax.axvline(x_range / 2, c='orange') px_e = xproj_ax.axhline(e_range / 2, c='orange') py_y = yproj_ax.axhline(y_range / 2, c='orange') py_e = yproj_ax.axvline(e_range / 2, c='orange') def update(e, kx, ky, clim, cmap, binning, interpolate, grid, trackers, trackerscol): if normalize: e_img = norm_img(data[e, :, :][::binning, ::binning]) y_img = norm_img(data[:, ky, :][::binning, ::binning]) x_img = norm_img(data[:, :, kx][::binning, ::binning]) else: e_img = data[e, :, :][::binning, ::binning] y_img = data[:, ky, :][::binning, ::binning] x_img = data[:, :, kx][::binning, ::binning] for axis, plot, img in zip([img_ax, yproj_ax, xproj_ax], [e_plot, x_plot, y_plot], [e_img, x_img.T, y_img]): plot.set_data(img) plot.set_clim(clim) plot.set_cmap(cmap) axis.grid(grid) if interpolate: plot.set_interpolation('gaussian') else: plot.set_interpolation(None) if trackers: pe_x.set_xdata(kx) pe_x.set_color(trackerscol) pe_y.set_ydata(ky) pe_y.set_color(trackerscol) px_x.set_xdata(kx) px_x.set_color(trackerscol) px_e.set_ydata(e) px_e.set_color(trackerscol) py_y.set_ydata(ky) py_y.set_color(trackerscol) py_e.set_xdata(e) py_e.set_color(trackerscol) interactive_plot = interactive_output( update, { 'e': w_e, 'kx': w_kx, 'ky': w_ky, 'clim': w_clim, 'cmap': w_cmap, 'binning': w_bin, 'interpolate': w_interpolate, 'grid': w_grid, 'trackers': w_trackers, 'trackerscol': w_trackercol, }) display(interactive_plot, tab)
def orthoslices_4D(data, axis_order=['E', 'kx', 'ky', 'kz'], normalize=True, continuous_update=True, **kwargs): if not isnotebook: raise EnvironmentError( 'Function not suited for working outside of Jupyter notebooks!') else: get_ipython().magic('matplotlib notebook') get_ipython().magic('matplotlib notebook') assert len( data.shape ) == 4, 'Data should be 4-dimensional, but data has {} dimensions'.format( data.shape) # make controls for data slicers # slicers = [] # for shape, name in zip(data.shape, axis_order): # slicers.append(widgets.IntSlider(value=shape // 2, # min=0, # max=shape - 1, # step=1, # description=name, # disabled=False, # continuous_update=False, # orientation='horizontal', # readout=True, # readout_format='d' # )) e_range, x_range, y_range, z_range = data.shape w_e = widgets.IntSlider(value=e_range // 2, min=0, max=e_range - 1, step=1, description='Energy:', disabled=False, continuous_update=continuous_update, orientation='horizontal', readout=True, readout_format='d') w_kx = widgets.IntSlider(value=x_range // 2, min=0, max=x_range - 1, step=1, description='kx:', disabled=False, continuous_update=continuous_update, orientation='horizontal', readout=True, readout_format='d') w_ky = widgets.IntSlider(value=y_range // 2, min=0, max=y_range - 1, step=1, description='ky:', disabled=False, continuous_update=continuous_update, orientation='horizontal', readout=True, readout_format='d') w_kz = widgets.IntSlider(value=z_range // 2, min=0, max=z_range - 1, step=1, description='kz:', disabled=False, continuous_update=continuous_update, orientation='horizontal', readout=True, readout_format='d') slicers = [w_e, w_kx, w_ky, w_kz] ui_slicers = widgets.HBox(slicers) # make controls for graphics appearance w_clim = widgets.FloatRangeSlider(value=[.1, .9], min=0, max=1, step=0.001, description='Contrast:', disabled=False, continuous_update=True, orientation='horizontal', readout=True, readout_format='.1f') w_cmap = widgets.Dropdown(options=cmaps, value='terrain', description='colormap:', disabled=False) w_bin = widgets.BoundedIntText(value=1, min=1, max=min(data.shape), step=1, description='resample:', disabled=False) w_interpolate = widgets.Checkbox(value=True, description='Interpolate', disabled=False) w_grid = widgets.Checkbox(value=False, description='Grid', disabled=False) w_trackers = widgets.Checkbox(value=True, description='Trackers', disabled=False) w_trackercol = widgets.ColorPicker(concise=False, description='tracker line color', value='orange') ui_color = widgets.HBox([ widgets.VBox([w_clim, w_cmap]), widgets.VBox([w_bin, w_interpolate, w_grid]), widgets.VBox([w_trackers, w_trackercol]), ]) tab = widgets.Tab(children=[ui_slicers, ui_color], ) tab.set_title(0, 'Data slicing') tab.set_title(1, 'Graphics') figsize = kwargs.pop('figsize', (5, 5)) fig = plt.figure(figsize=figsize, **kwargs) plt.tight_layout() img_ax = fig.add_axes([.15, .4, .4, .4], xticklabels=[], yticklabels=[]) img_ax.xaxis.set_major_locator(plt.LinearLocator(5)) img_ax.yaxis.set_major_locator(plt.LinearLocator(5)) xproj_ax = fig.add_axes([.15, .1, .4, .28], xticklabels=[], yticklabels=[]) xproj_ax.set_xlabel('$k_x$') xproj_ax.xaxis.set_major_locator(plt.LinearLocator(5)) yproj_ax = fig.add_axes([.57, .4, .28, .4], xticklabels=[], yticklabels=[]) yproj_ax.yaxis.set_label_position("right") yproj_ax.set_ylabel('$k_y$') yproj_ax.yaxis.set_major_locator(plt.LinearLocator(5)) for ax in [img_ax, yproj_ax, xproj_ax]: # ,cbar_ax]: ax.tick_params(axis="both", direction="in", bottom=True, top=True, left=True, right=True, which='both') clim_ = 0.01, .99 e_img = norm_img(data[data.shape[0] // 2, :, :, data.shape[3] // 2]) y_img = norm_img(data[:, data.shape[1] // 2, :, data.shape[3] // 2]) x_img = norm_img(data[:, :, data.shape[2] // 2, data.shape[3] // 2].T) e_plot = img_ax.imshow( e_img, cmap='terrain', aspect='auto', interpolation='gaussian', clim=clim_, ) # origin='lower') x_plot = yproj_ax.imshow( x_img, cmap='terrain', aspect='auto', interpolation='gaussian', clim=clim_, ) # origin='lower') y_plot = xproj_ax.imshow( y_img, cmap='terrain', aspect='auto', interpolation='gaussian', clim=clim_, ) # origin='lower') pe_x = img_ax.axvline(x_range / 2, c='orange') pe_y = img_ax.axhline(y_range / 2, c='orange') px_x = xproj_ax.axvline(x_range / 2, c='orange') px_e = xproj_ax.axhline(e_range / 2, c='orange') py_y = yproj_ax.axhline(y_range / 2, c='orange') py_e = yproj_ax.axvline(e_range / 2, c='orange') def update(e, kx, ky, kz, clim, cmap, binning, interpolate, grid, trackers, trackerscol): if normalize: e_img = norm_img(data[e, :, :, kz][::binning, ::binning]) y_img = norm_img(data[:, ky, :, kz][::binning, ::binning]) x_img = norm_img(data[:, :, kx, kz][::binning, ::binning]) else: e_img = data[e, :, :, kz][::binning, ::binning] y_img = data[:, ky, :, kz][::binning, ::binning] x_img = data[:, :, kx, kz][::binning, ::binning] for axis, plot, img in zip([img_ax, yproj_ax, xproj_ax], [e_plot, x_plot, y_plot], [e_img, x_img.T, y_img]): plot.set_data(img) plot.set_clim(clim) plot.set_cmap(cmap) axis.grid(grid) if interpolate: plot.set_interpolation('gaussian') else: plot.set_interpolation(None) if trackers: pe_x.set_xdata(kx) pe_x.set_color(trackerscol) pe_y.set_ydata(ky) pe_y.set_color(trackerscol) px_x.set_xdata(kx) px_x.set_color(trackerscol) px_e.set_ydata(e) px_e.set_color(trackerscol) py_y.set_ydata(ky) py_y.set_color(trackerscol) py_e.set_xdata(e) py_e.set_color(trackerscol) interactive_plot = interactive_output( update, { 'e': w_e, 'kx': w_kx, 'ky': w_ky, 'kz': w_kz, 'clim': w_clim, 'cmap': w_cmap, 'binning': w_bin, 'interpolate': w_interpolate, 'grid': w_grid, 'trackers': w_trackers, 'trackerscol': w_trackercol, }) display(interactive_plot, tab)
max=10, disabled=False, style=style_mini, layout=layout_mini) shock = widgets.Dropdown(options={'1', '2', '3', '4'}, value='1', description='Shock Number:', disabled=False, style={'description_width': '180px'}, layout=Layout(width='70%')) timeHorizon = widgets.BoundedIntText( ## death rate value=160, min=10, max=2000, step=10, disabled=False, description='Time Horizon (quarters)', style={'description_width': '180px'}, layout=Layout(width='70%')) folderName = widgets.Text(value='defaultModel', placeholder='defaultModel', description='Folder name', disabled=False, style={'description_width': '180px'}, layout=Layout(width='70%')) gammaSave = widgets.BoundedFloatText( ## death rate value=5, min=1, max=10,