def options(X): style = {'description_width': 'initial'} #general style settings #horizontal line widget HL = widgets.HTML( value= '<hr style="height:3px;border:none;color:#333;background-color:#333;" />' ) M_title = widgets.HTML(value='<h3>Select data type:</h3>') M_widge = widgets.RadioButtons( options=['Magnetisations', 'Lower branch subtracted'], value='Lower branch subtracted', style=style) ### Horizontal smoothing ### S_title = widgets.HTML(value='<h3>Set smoothing parameters:</h3>') #SC widgets Sc_widge = widgets.IntRangeSlider(value=[2, 10], min=2, max=10, step=1, description='Select $s_c$ range:', continuous_update=False, orientation='horizontal', readout=True, readout_format='.0f', style=style) Sb_widge = widgets.IntRangeSlider(value=[2, 10], min=2, max=10, step=1, description='Select $s_u$ range:', continuous_update=False, orientation='horizontal', readout=True, readout_format='.0f', style=style) lambda_widge = widgets.FloatRangeSlider( value=[0.0, 0.2], min=0, max=0.2, step=0.04, description='Select $\lambda$ range:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.2f', style=style) constraint_widge = widgets.Checkbox(value=False, description='Assume $Sc_0$ = $Su_0$', style=style) constraint_html = widgets.HTML( value= 'Check <a href="https://forcaist.github.io/FORCaist.github.io/dfaq.html#AssumeS" target="_blank">FORCsensei FAQ</a> for more information about the Sc<sub>0</sub> = Su<sub>0</sub> option' ) constraint_widge1 = widgets.Checkbox(value=False, description='Assume $Sc_1$ = $Su_1$', style=style) constraint_html1 = widgets.HTML( value= 'Check <a href="https://forcaist.github.io/FORCaist.github.io/dfaq.html#AssumeS1" target="_blank">FORCsensei FAQ</a> for more information about the Sc<sub>1</sub> = Su<sub>1</sub> option' ) pike_widge = widgets.Checkbox( value=False, description= 'Assume $Sc_0$ = $Su_0$ = $Sc_1$ = $Su_1$ and $\lambda$ = 0', style=style) #find number of points in window of interest X['Hc'] = 0.5 * (X['H'] - X['Hr']) X['Hb'] = 0.5 * (X['H'] + X['Hr']) Hidx = np.argwhere(in_window(X, X['Hc'], X['Hb']) == True) H0 = X['Hc'][Hidx] + X['Hb'][Hidx] Hr0 = X['Hb'][Hidx] - X['Hc'][Hidx] down_title = widgets.HTML(value='<h3>Specify downsampling:</h3>') Npts = int(np.sum((np.abs(H0) < X['Hopen']) & (np.abs(Hr0) < X['Hopen']))) down_widge = widgets.IntSlider(value=np.minimum(Npts, 2000), min=100, max=Npts, step=1, description='Number of points:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d', style=style) #display number of models to compare model_widge = widgets.interactive_output( variforc_array_size, { 'SC': Sc_widge, 'SB': Sb_widge, 'L': lambda_widge, 'CN': constraint_widge, 'CN1': constraint_widge1, 'PK': pike_widge }) #display FAQ information about progress bar progress_html = widgets.HTML( value= 'Model comparison can take some time, check <a href="https://forcaist.github.io/FORCaist.github.io/dfaq.html#progress" target="_blank">FORCsensei FAQ</a> for information about monitoring progress of the calculation' ) #combined widget DS = VBox([down_title, down_widge]) SC = VBox([ M_title, M_widge, HL, S_title, Sc_widge, Sb_widge, lambda_widge, HBox([constraint_widge, constraint_html]), HBox([constraint_widge1, constraint_html1]), pike_widge, model_widge, progress_html ]) ### Setup Multiprocessing tab #################### X['ncore'] = 4 #header dask_title = widgets.HTML(value='<h3>DASK multiprocessing:</h3>') #selection widget dask_widge = widgets.IntSlider(value=X['ncore'], min=1, max=20, step=1, description='Number of DASK workers:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d', style=style) dask_html = widgets.HTML( value= 'Check <a href="https://forcaist.github.io/FORCaist.github.io/dfaq.html#dask_workers" target="_blank">FORCsensei FAQ</a> for more information about selecting Dask workers' ) #final multiprocessing widget mpl_widge = VBox([dask_title, dask_widge, dask_html]) ### CONSTRUCT TAB MENU ############# method_nest = widgets.Tab() method_nest.children = [SC, DS, mpl_widge] method_nest.set_title(0, 'MODEL ENSEMBLE') method_nest.set_title(1, 'DOWNSAMPLING') method_nest.set_title(2, 'PROCESSING') display(method_nest) ### SETUP OUTPUT #### X['constraint'] = constraint_widge X['constraint1'] = constraint_widge1 X['pike'] = pike_widge X['Mtype'] = M_widge X['SC'] = Sc_widge X['SB'] = Sb_widge X['lambda'] = lambda_widge X['Ndown'] = down_widge X['workers'] = dask_widge return X
def setting_accord(): data_box = widgets.Box([ widgets.Text(value='example: test_dat.csv', description='Data Path:', style={'description_width': 'initial'}, layout=Layout(flex='3 1 0%', width='auto')), widgets.Text(value='example: ~/images/', description='Image Directory:', style={'description_width': 'initial'}, layout=Layout(flex='3 1 0%', width='auto')), widgets.Text(value='', description='Colname of Filename:', style={'description_width': 'initial'}), widgets.Text(value='', description='Colname of Label:', style={'description_width': 'initial'}) ], layout=Layout(display='flex', flex_flow='column', align_items='stretch', width='80%')) preprocess_box = widgets.Box([ widgets.HBox([ widgets.Checkbox(value=False, description='Save split data', disabled=False), widgets.Checkbox(value=True, description='Image Augmentation', disabled=False) ]), widgets.RadioButtons(options=[(224, 224, 3), (299, 299, 3)], description='resize:'), widgets.FloatRangeSlider(value=(-1.0, 1.0), min=-1.0, max=1.0, description='Range of Normalization:', style={'description_width': 'initial'}), widgets.FloatSlider(value=0.2, min=0.1, max=1.0, description='Validation Set:', style={'description_width': 'initial'}) ], layout=Layout(display='flex', flex_flow='column', align_items='stretch', width='80%')) model_box = widgets.Box([ widgets.Text(value='example: ./mymodel.h5', description='Model Path:', style={'description_width': 'initial'}, layout=Layout(flex='3 1 0%', width='auto')), widgets.Dropdown(options=['8', '16', '32', '64', '128'], description='Batch size:'), widgets.Text(value='', description='Prediction file path:', style={'description_width': 'initial'}, layout=Layout(flex='3 1 0%', width='auto')), ], layout=Layout(display='flex', flex_flow='column', align_items='stretch', width='50%')) tab_accord = widgets.Accordion(selected_index=None) tab_accord.children = [data_box, preprocess_box, model_box] tab_accord.set_title(0, 'Dataset') tab_accord.set_title(1, 'Preprocess') tab_accord.set_title(2, 'Model') return tab_accord
def interact(self, lc=None): """Display an interactive IPython Notebook widget to inspect the data. The widget will show both the lightcurve and pixel data. By default, the lightcurve shown is obtained by calling the `to_lightcurve()` method, unless the user supplies a custom `LightCurve` object. Note: at this time, this feature only works inside an active Jupyter Notebook, and tends to be too slow when more than ~30,000 cadences are contained in the TPF (e.g. short cadence data). Parameters ---------- lc : LightCurve object An optional pre-processed lightcurve object to show. """ try: from ipywidgets import interact import ipywidgets as widgets from bokeh.io import push_notebook, show, output_notebook from bokeh.plotting import figure, ColumnDataSource from bokeh.models import Span, LogColorMapper from bokeh.layouts import row from bokeh.models.tools import HoverTool from IPython.display import display output_notebook() except ImportError: raise ImportError( 'The quicklook tool requires Bokeh and ipywidgets. ' 'See the .interact() tutorial') ytitle = 'Flux' if lc is None: lc = self.to_lightcurve() ytitle = 'Flux (e/s)' # Bokeh cannot handle many data points # https://github.com/bokeh/bokeh/issues/7490 if len(lc.cadenceno) > 30000: raise RuntimeError( 'Interact cannot display more than 20000 cadences.') # Map cadence to index for quick array slicing. n_lc_cad = len(lc.cadenceno) n_cad, nx, ny = self.flux.shape lc_cad_matches = np.in1d(self.cadenceno, lc.cadenceno) if lc_cad_matches.sum() != n_lc_cad: raise ValueError( "The lightcurve provided has cadences that are not " "present in the Target Pixel File.") min_cadence, max_cadence = np.min(self.cadenceno), np.max( self.cadenceno) cadence_lookup = {cad: j for j, cad in enumerate(self.cadenceno)} cadence_full_range = np.arange(min_cadence, max_cadence, 1, dtype=np.int) missing_cadences = list(set(cadence_full_range) - set(self.cadenceno)) # Convert binary quality numbers into human readable strings qual_strings = [] for bitmask in lc.quality: flag_str_list = KeplerQualityFlags.decode(bitmask) if len(flag_str_list) == 0: qual_strings.append(' ') if len(flag_str_list) == 1: qual_strings.append(flag_str_list[0]) if len(flag_str_list) > 1: qual_strings.append("; ".join(flag_str_list)) # Convert time into human readable strings, breaks with NaN time # See https://github.com/KeplerGO/lightkurve/issues/116 if (self.time == self.time).all(): human_time = self.astropy_time.isot[lc_cad_matches] else: human_time = [' '] * n_lc_cad # Each data source will later become a hover-over tooltip source = ColumnDataSource(data=dict(time=lc.time, time_iso=human_time, flux=lc.flux, cadence=lc.cadenceno, quality_code=lc.quality, quality=np.array(qual_strings))) # Provide extra metadata in the title if self.mission == 'K2': title = "Quicklook lightcurve for EPIC {} (K2 Campaign {})".format( self.keplerid, self.campaign) elif self.mission == 'Kepler': title = "Quicklook lightcurve for KIC {} (Kepler Quarter {})".format( self.keplerid, self.quarter) # Figure 1 shows the lightcurve with steps, tooltips, and vertical line fig1 = figure(title=title, plot_height=300, plot_width=600, tools="pan,wheel_zoom,box_zoom,save,reset") fig1.yaxis.axis_label = ytitle fig1.xaxis.axis_label = 'Time - 2454833 days [BKJD]' fig1.step('time', 'flux', line_width=1, color='gray', source=source, nonselection_line_color='gray', mode="center") r = fig1.circle('time', 'flux', source=source, fill_alpha=0.3, size=8, line_color=None, selection_color="firebrick", nonselection_fill_alpha=0.0, nonselection_line_color=None, nonselection_line_alpha=0.0, fill_color=None, hover_fill_color="firebrick", hover_alpha=0.9, hover_line_color="white") fig1.add_tools( HoverTool(tooltips=[("Cadence", "@cadence"), ("Time (BKJD)", "@time{0,0.000}"), ("Time (ISO)", "@time_iso"), ("Flux", "@flux"), ("Quality Code", "@quality_code"), ("Quality Flag", "@quality")], renderers=[r], mode='mouse', point_policy="snap_to_data")) # Vertical line to indicate the cadence shown in Fig 2 vert = Span(location=0, dimension='height', line_color='firebrick', line_width=4, line_alpha=0.5) fig1.add_layout(vert) # Figure 2 shows the Target Pixel File stamp with log screen stretch fig2 = figure(plot_width=300, plot_height=300, tools="pan,wheel_zoom,box_zoom,save,reset", title='Pixel data (CCD {}.{})'.format( self.module, self.output)) fig2.yaxis.axis_label = 'Pixel Row Number' fig2.xaxis.axis_label = 'Pixel Column Number' pedestal = np.nanmin(self.flux[lc_cad_matches, :, :]) stretch_dims = np.prod(self.flux[lc_cad_matches, :, :].shape) screen_stretch = self.flux[lc_cad_matches, :, :].reshape( stretch_dims) - pedestal screen_stretch = screen_stretch[np.isfinite( screen_stretch)] # ignore NaNs screen_stretch = screen_stretch[screen_stretch > 0.0] vlo = np.min(screen_stretch) vhi = np.max(screen_stretch) vstep = (np.log10(vhi) - np.log10(vlo)) / 300.0 # assumes counts >> 1.0! lo, med, hi = np.nanpercentile(screen_stretch, [1, 50, 95]) color_mapper = LogColorMapper(palette="Viridis256", low=lo, high=hi) fig2_dat = fig2.image([self.flux[0, :, :] - pedestal], x=self.column, y=self.row, dw=self.shape[2], dh=self.shape[1], dilate=False, color_mapper=color_mapper) # The figures appear before the interactive widget sliders show(row(fig1, fig2), notebook_handle=True) # The widget sliders call the update function each time def update(cadence, log_stretch): """Function that connects to the interact widget slider values""" fig2_dat.glyph.color_mapper.high = 10**log_stretch[1] fig2_dat.glyph.color_mapper.low = 10**log_stretch[0] if cadence not in missing_cadences: index_val = cadence_lookup[cadence] vert.update(line_alpha=0.5) if self.time[index_val] == self.time[index_val]: vert.update(location=self.time[index_val]) else: vert.update(line_alpha=0.0) fig2_dat.data_source.data['image'] = [ self.flux[index_val, :, :] - pedestal ] else: vert.update(line_alpha=0) fig2_dat.data_source.data['image'] = [ self.flux[0, :, :] * np.NaN ] push_notebook() # Define the widgets that enable the interactivity play = widgets.Play(interval=10, value=min_cadence, min=min_cadence, max=max_cadence, step=1, description="Press play", disabled=False) play.show_repeat, play._repeat = False, False cadence_slider = widgets.IntSlider(min=min_cadence, max=max_cadence, step=1, value=min_cadence, description='Cadence', layout=widgets.Layout( width='40%', height='20px')) screen_slider = widgets.FloatRangeSlider( value=[np.log10(lo), np.log10(hi)], min=np.log10(vlo), max=np.log10(vhi), step=vstep, description='Pixel Stretch (log)', style={'description_width': 'initial'}, continuous_update=False, layout=widgets.Layout(width='30%', height='20px')) widgets.jslink((play, 'value'), (cadence_slider, 'value')) ui = widgets.HBox([play, cadence_slider, screen_slider]) out = widgets.interactive_output(update, { 'cadence': cadence_slider, 'log_stretch': screen_slider }) display(ui, out)
def create_widget(self): """Create widgets and their layout.""" # Offset slider. off = widgets.interactive( self.update_off, off=widgets.IntSlider( min=500, max=10000, description='Offset (m)', value=self.model['rec'][0], step=250, continuous_update=False, style={'description_width': '60px'}, layout={'width': '260px'}, ), ) # Pts/dec slider. pts_per_dec = widgets.interactive( self.update_pts_per_dec, pts_per_dec=widgets.IntSlider( min=1, max=10, description='pts/dec', value=self.pts_per_dec, step=1, continuous_update=False, style={'description_width': '60px'}, layout={'width': '260px'}, ), ) # Linear/logarithmic selection. linlog = widgets.interactive( self.update_linlog, linlog=widgets.ToggleButtons( value=self.linlog, options=['linear', 'log'], description='Display', style={'description_width': '60px', 'button_width': '100px'}, ), ) # Frequency-range slider. freq_range = widgets.interactive( self.update_freq_range, freq_range=widgets.FloatRangeSlider( value=[np.log10(self.fmin), np.log10(self.fmax)], description='f-range', min=-4, max=3, step=0.1, continuous_update=False, style={'description_width': '60px'}, layout={'width': '260px'}, ), ) # Signal selection (-1, 0, 1). signal = widgets.interactive( self.update_signal, signal=widgets.ToggleButtons( value=self.signal, options=[-1, 0, 1], description='Signal', style={'description_width': '60px', 'button_width': '65px'}, ), ) # Fourier transform method selection. def _get_init(): """Return initial choice of Fourier Transform.""" if self.ft == 'fftlog': return self.ft else: return self.ftarg['dlf'].savename ftfilt = widgets.interactive( self.update_ftfilt, ftfilt=widgets.Dropdown( options=['fftlog', 'key_81_CosSin_2009', 'key_241_CosSin_2009', 'key_601_CosSin_2009', 'key_101_CosSin_2012', 'key_201_CosSin_2012'], description='Fourier', value=_get_init(), # Initial value style={'description_width': '60px'}, layout={'width': 'max-content'}, ), ) # Group them together. t1col1 = widgets.VBox(children=[pts_per_dec, freq_range], layout={'width': '310px'}) t1col2 = widgets.VBox(children=[off, ftfilt], layout={'width': '310px'}) t1col3 = widgets.VBox(children=[signal, linlog], layout={'width': '310px'}) # Group them together. display(widgets.HBox(children=[t1col1, t1col2, t1col3]))
def play_inline(fPath, **kw): ''' For matplotlib inline mode. Generate an interactive 2D plot to play with x,y must be uniform spaced, autoflipped. ''' # Data x, y, w, labels = read2d(fPath, **kw) if 'labels' not in kw: kw['labels'] = labels x0 = x[0] y0 = y[:, 0] xmin, xmax, dx = x[0, 0], x[0, -1], x[0, 1] - x[0, 0] ymin, ymax, dy = y[0, 0], y[-1, 0], y[1, 0] - y[0, 0] wmin, wmax = np.min(w), np.max(w) dw = (wmax - wmin) / 20 # UI sxpos = widgets.FloatSlider(value=(xmin + xmax) / 2, min=xmin, max=xmax, step=dx, description='x') sypos = widgets.FloatSlider(value=(ymin + ymax) / 2, min=ymin, max=ymax, step=dy, description='y') vb1 = widgets.VBox([sxpos, sypos]) sgamma = widgets.IntSlider(value=0, min=-100, max=100, step=10, description='gamma') svlim = widgets.FloatRangeSlider(value=[wmin, wmax], min=wmin, max=wmax, step=dw, description='limit') vb2 = widgets.VBox([sgamma, svlim]) bexpMTX = widgets.Button(description='To mtx') htmlexp = widgets.HTML() vb3 = widgets.VBox([bexpMTX, htmlexp]) ui = widgets.Tab(children=[vb1, vb2, vb3]) [ ui.set_title(i, j) for i, j in zip(range(3), ['linecuts', 'color', 'export']) ] # interactive funcion indx, indy = 0, 0 def _play2d(xpos, ypos, gamma, vlim): nonlocal indx, indy # initialize the figure fig, axs = plt.subplots(1, 2, figsize=(6.5, 2.5), dpi=120) #main plot and h linecut plt.subplots_adjust(wspace=0.4) axs[1].yaxis.tick_right() axs[1].tick_params(axis='x', colors='tab:orange') axs[1].tick_params(axis='y', colors='tab:orange') axv = fig.add_axes(axs[1].get_position(), frameon=False) #ax vertical linecut axv.xaxis.tick_top() axv.tick_params(axis='x', colors='tab:blue') axv.tick_params(axis='y', colors='tab:blue') # plot 2D data kw = {} kw['gamma'], kw['vmin'], kw['vmax'] = gamma, vlim[0], vlim[1] Painter.plot2d(x, y, w, fig=fig, ax=axs[0], **kw) # vlinecut indx = np.abs(x0 - xpos).argmin() # x0 may be a non uniform array axs[0].plot(x[:, indx], y0, 'tab:blue') axv.plot(w[:, indx], y0, 'tab:blue') # hlinecut indy = np.abs(y0 - ypos).argmin() axs[0].plot(x0, y[indy, :], 'tab:orange') axs[1].plot(x0, w[indy, :], 'tab:orange') def _export(_): htmlexp.value = 'Saving...' fname = os.path.split(fPath)[1] fname = os.path.splitext(fname)[0] # vlincut fnamev = fname + '.vcut.%e.mtx' % x[0, indx] Data2d.saveMTX2d(fnamev, y0[np.newaxis], x[np.newaxis, :, indx], w[np.newaxis, :, indx], [labels[i] for i in [1, 0, 2]]) # hlincut fnameh = fname + '.hcut.%e.mtx' % y[indy, 0] Data2d.saveMTX2d(fnameh, x0[np.newaxis], y[[indy], :], w[[indy], :], labels) # 2d data fname2d = fname + '.mtx' Data2d.saveMTX2d(fname2d, x, y, w, labels) htmlexp.value = 'Files saved:<br>%s<br>%s<br>%s' % (fnamev, fnameh, fname2d) out = widgets.interactive_output(_play2d, { 'xpos': sxpos, 'ypos': sypos, 'gamma': sgamma, 'vlim': svlim }) bexpMTX.on_click(_export) display(ui, out)
def makeplot(fileNameList, scaleList=[1], LineoutDir=None, Show_theory=None, DiffDir=None, specify_title=''): # This is the first filename filename = fileNameList[0] # Depending on what kind of data we are plotting, the best range of the colorbar and lineout is different if ('Species' in filename): colorBarDefaultRange = [-5, 0] colorBarTotalRange = [-10, 0] lineoutAxisRange = [-10, 0] elif ('Beam' in filename): colorBarDefaultRange = [-10, 0] colorBarTotalRange = [-50, 0] lineoutAxisRange = [-100, 0] elif ('Fields' in filename): colorBarDefaultRange = [-1, 1] colorBarTotalRange = [-5, 5] lineoutAxisRange = [-2, 2] for i in range(len(fileNameList)): f = h5py.File(fileNameList[i], 'r') k = list(f.keys()) # k = ['AXIS', 'charge_slice_xz'] DATASET = f[k[1]] if (i == 0): data = np.array(DATASET) * scaleList[0] else: data += np.array(DATASET) * scaleList[i] AXIS = f[ k[0]] # AXIS is a group, which contains two datasets: AXIS1 and AXIS2 LONG_NAME = DATASET.attrs['LONG_NAME'] UNITS = DATASET.attrs['UNITS'] title = LONG_NAME[0].decode('UTF-8') unit = UNITS[0].decode('UTF-8') figure_title = title + ' [$' + unit + '$]' if (specify_title != ''): figure_title = specify_title #### Read the axis labels and the corresponding units AXIS1 = AXIS['AXIS1'] AXIS2 = AXIS['AXIS2'] LONG_NAME1 = AXIS1.attrs['LONG_NAME'] UNITS1 = AXIS1.attrs['UNITS'] LONG_NAME2 = AXIS2.attrs['LONG_NAME'] UNITS2 = AXIS2.attrs['UNITS'] axisLabel1 = LONG_NAME1[0].decode('UTF-8') unit1 = UNITS1[0].decode('UTF-8') axisLabel2 = LONG_NAME2[0].decode('UTF-8') unit2 = UNITS2[0].decode('UTF-8') label_bottom = '$' + axisLabel2 + '$' + ' $[' + unit2 + ']$' label_left = '$' + axisLabel1 + '$' + ' $[' + unit1 + ']$' axis = list(AXIS) # axis = ['AXIS1', 'AXIS2'] xRange = np.array(f['AXIS/AXIS1']) xiRange = np.array(f['AXIS/AXIS2']) xLengthTotal = xRange[1] - xRange[0] zLengthTotal = xiRange[1] - xiRange[0] xCellsTotal = data.shape[1] zCellsTotal = data.shape[0] x = np.linspace(xRange[0], xRange[1], xCellsTotal) xi = np.linspace(xiRange[0], xiRange[1], zCellsTotal) # Determine the range of the lineout, depending on the direction of the lineout lineoutRange = [0, 0] if (LineoutDir == 'transverse'): lineoutRange = xiRange elif (LineoutDir == 'longitudinal'): lineoutRange = xRange / 2 xLengthTotal = xRange[1] - xRange[0] zLengthTotal = xiRange[1] - xiRange[0] xCellsPerUnitLength = xCellsTotal / xLengthTotal zCellsPerUnitLength = zCellsTotal / zLengthTotal ##### If we need to take a derivative if (DiffDir == 'xi'): data = NDiff(data, xLengthTotal, zLengthTotal, Ddir='column') elif (DiffDir == 'r'): data = NDiff(data, xLengthTotal, zLengthTotal, Ddir='row') ##### dataT = data.transpose() colormap = 'viridis' def plot(colorBarRange, lineout_position): fig, ax1 = plt.subplots(figsize=(8, 5)) # Zoom in / zoom out the plot ax1.axis([xi.min(), xi.max(), x.min() / 2, x.max() / 2]) ### ax1.set_title(figure_title) cs1 = ax1.pcolormesh(xi, x, dataT, vmin=colorBarRange[0], vmax=colorBarRange[1], cmap=colormap) fig.colorbar(cs1, pad=0.15) ax1.set_xlabel(label_bottom) #Make the y-axis label, ticks and tick labels match the line color. ax1.set_ylabel(label_left, color='k') ax1.tick_params('y', colors='k') if (LineoutDir == 'longitudinal'): ax2 = ax1.twinx() middle_index = int(dataT.shape[0] / 2) lineout_index = int(middle_index + lineout_position * xCellsPerUnitLength) lineout = dataT[lineout_index, :] ax2.plot(xi, lineout, 'r') if (Show_theory == 'focus'): # plot the 1/2 slope line (theoretical focusing force) focusing_force_theory = -1 / 2 * lineout_position * np.ones( dataT.shape[1]) ax2.plot(xi, focusing_force_theory, 'r--', label='F = -1/2 r') ax2.legend() ax2.set_ylim(lineoutAxisRange) ax1.plot(xi, lineout_position * np.ones(dataT.shape[1]), 'b--') # Add a dashed line at the lineout position ax2.tick_params('y', colors='r') elif (LineoutDir == 'transverse'): ax2 = ax1.twiny() lineout_index = int(lineout_position * zCellsPerUnitLength) lineout = dataT[:, lineout_index] ax2.plot(lineout, x, 'r') if (Show_theory == 'focus'): # plot the 1/2 slope line (theoretical focusing force) focusing_force_theory = -1 / 2 * x ax2.plot(focusing_force_theory, x, 'r--', label='F = -1/2 r') ax2.legend() ax2.set_xlim(lineoutAxisRange) ax1.plot(lineout_position * np.ones(dataT.shape[0]), x, 'b--') ax2.tick_params('x', colors='r') if (Show_theory == 'bubble_boundary'): boundary = getBubbleBoundary(filename) ax1.plot(boundary[0], boundary[1], 'k--', label='bubble boundary') # if(Show_theory == 'Ez'): # boundary = getBubbleBoundary('rundir/Species0001/Charge_slice_0001/charge_slice_xz_00000001.h5') # xii = boundary[0] # rb = boundary[1] # Delta_l = 1.1 # Delta_s = 0.0 # alpha = Delta_l/rb + Delta_s # beta = ((1+alpha)**2 * np.log((1+alpha)**2))/((1+alpha)**2-1)-1 # psi0 = rb**2/4 * (1+beta) # Ez = Nd(xi,psi0) # Ez = smooth(Ez) # ax2.plot(xii,Ez,'r--',label='theory') # ax2.legend() fig.tight_layout() return i1 = interact(plot, colorBarRange=widgets.FloatRangeSlider( value=colorBarDefaultRange, min=colorBarTotalRange[0], max=colorBarTotalRange[1], step=0.1, description='Colorbar:', continuous_update=False), lineout_position=FloatSlider(min=lineoutRange[0], max=lineoutRange[1], step=0.05, description='lineout position:', continuous_update=False)) return
def __init__(self): img_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "") img_tstat = os.path.join(img_path, "thermostat.png") self._img_tstat_open = open(img_tstat, "rb").read() self._tstat = ipw.Image( value=self._img_tstat_open, format='png', width=240, height=240, ) form_item_layout = ipw.Layout(display='flex', flex_flow='row', width='100%', justify_content='flex-start') self.observe(self._updateslider, 'hsp') self.observe(self._updateslider, 'csp') self.spslider = ipw.FloatRangeSlider(min=60, max=85, step=1.0, value=[self.hsp, self.csp], continuous_update=True, orientation='horizontal') self.spslider.observe(self._updatesetpoints, 'value') self.tempsensor = ipw.Label(value='{0:.2f}'.format(self.temp)) self.observe(self._updatetemp, 'temp') self.oatsensor = ipw.Label(value='{0:.2f}'.format(self.oat)) self.statedisplay = ipw.Label(value=self.state) self.observe(self._updatestate, 'state') self.statedisplay.observe(self._updatestatedisplay, 'value') self.occupiedisplay = ipw.Label(value='{0}'.format(self.occupied)) self.observe(self._update_occupancy, 'occupied') def occupancy_square_wave(): i = 0 while True: i = (i + 1) % 20 time.sleep(1) self.occupied = i > 10 occthread = threading.Thread(target=occupancy_square_wave) occthread.start() def thermostat_temp_wave(): i = 0 while True: i = (i + 1) % 180 time.sleep(1) adjust = -.2 if self.state == 'Cooling' else .2 if self.state == 'Heating' else 0 self.oat = 80 + 20 * math.sin(math.radians(i)) self.temp = self.temp + adjust + (self.oat - self.temp) * .01 tempthread = threading.Thread(target=thermostat_temp_wave) tempthread.start() form_items = [ ipw.VBox([self._tstat]), ipw.VBox([ ipw.Box( [ipw.Label(value='Outside Temperature: '), self.oatsensor], layout=form_item_layout), ipw.Box( [ipw.Label(value='Inside Temperature: '), self.tempsensor], layout=form_item_layout), ipw.Box([ipw.Label(value='Setpoints: '), self.spslider], layout=form_item_layout), ipw.Box([ipw.Label(value='State: '), self.statedisplay], layout=form_item_layout), ipw.Box([ipw.Label(value='Occupied? '), self.occupiedisplay], layout=form_item_layout), ]), ] super(Thermostat, self).__init__() self.layout.display = 'flex' self.layout.flex_flow = 'row' self.layout.border = 'solid 2px' #self.layout.align_items = 'center' #self.width = '50%' self.children = form_items
class SpeckWidget: weights_W = ipywidgets.FloatRangeSlider(value=[0, 1], min=0, max=1, steps=0.01, description='Line Weight') weight_clipping_W = ipywidgets.FloatRangeSlider( value=[0, 1], min=0, max=1, steps=0.01, description='Weight Clipping') noise_profile_W = ipywidgets.Dropdown( value='parallel', options=['parallel', 'reflect', 'independent'], description='Noise Profile', ) noise_scale_W = ipywidgets.FloatSlider(value=0.5, min=0, max=2, steps=0.05, description='Noise Scale') noise_wave_count_W = ipywidgets.IntSlider(value=3, min=1, max=6, steps=1, description='Wave Count') noise_base_freq_W = ipywidgets.FloatSlider(value=3, min=1, max=10, steps=0.5, description='Base Frequency') noise_freq_factor_W = ipywidgets.FloatRangeSlider( value=[1, 3], min=0, max=10, steps=0.5, description='Frequency Multipliers') noise_phase_offset_range_W = ipywidgets.FloatRangeSlider( value=[0, 2], min=0, max=360, steps=15, description='Phase Offset (degrees)') colour_top_W = ipywidgets.ColorPicker(concise=True, description='Top Colour', value='white', disabled=False) colour_bot_W = ipywidgets.ColorPicker(concise=True, description='Bottom Colour', value='red', disabled=False) def __init__(self, speck_plot): self.speck_plot = speck_plot def _widget_func( self, weights, weight_clipping, noise_profile, noise_scale, noise_wave_count, noise_base_freq, noise_freq_factor, noise_phase_offset_range, colour_top, colour_bot, ): noise = SineNoise( profile=noise_profile, scale=noise_scale, wave_count=noise_wave_count, base_freq=noise_base_freq, freq_factor=noise_freq_factor, phase_offset_range=noise_phase_offset_range, ) colour = GradientColour((colour_top, colour_bot)) return self.speck_plot.draw( weights=weights, weight_clipping=weight_clipping, noise=noise, colour=colour, seed=1, ) def interact(self, plot_kwargs): return ipywidgets.interact( self._widget_func, weights=self.weights_W, weight_clipping=self.weight_clipping_W, noise_profile=self.noise_profile_W, noise_scale=self.noise_scale_W, noise_wave_count=self.noise_wave_count_W, noise_base_freq=self.noise_base_freq_W, noise_freq_factor=self.noise_freq_factor_W, noise_phase_offset_range=self.noise_phase_offset_range_W, colour_top=self.colour_top_W, colour_bot=self.colour_bot_W, )
description='Flat Model' ), 'flat_type': widgets.SelectMultiple( options=hdbdata['flat_type'].unique(), value=list(hdbdata['flat_type'].unique()), description='Flat Type' ), 'storey_range': widgets.SelectMultiple( options=hdbdata['storey_range'].unique(), value=list(hdbdata['storey_range'].unique()), description='Storeys' ), 'floor_area_sqm': widgets.FloatRangeSlider( value=[hdbdata['floor_area_sqm'].min(), hdbdata['floor_area_sqm'].max()], min=hdbdata['floor_area_sqm'].min(), max=hdbdata['floor_area_sqm'].max(), step=1, description='Floor Area (sqm):', layout=Layout(width='100%') ), 'remaining_lease': widgets.FloatRangeSlider( value=[hdbdata['remaining_lease'].min(), hdbdata['remaining_lease'].max()], min=hdbdata['remaining_lease'].min(), max=hdbdata['remaining_lease'].max(), step=1, description='Remaining Lease (years):', layout=Layout(width='100%') ), 'year': widgets.SelectionRangeSlider( options=[(i,i) for i in hdbdata['year'].unique()], index=(0, hdbdata['year'].unique().size-1), description='Year of transaction',
def image_constast_editor_ipy(obj, **kwargs): wdict = {} left = ipywidgets.FloatText(disabled=True, description="Vmin") right = ipywidgets.FloatText(disabled=True, description="Vmax") bins = ipywidgets.IntText(description="Bins") norm = ipywidgets.Dropdown(options=("Linear", "Power", "Log", "Symlog"), description="Norm", value=obj.norm) percentile = ipywidgets.FloatRangeSlider( value=[0.0, 100.0], min=0.0, max=100.0, step=0.1, description="Vmin/vmax percentile", readout_format='.1f') gamma = ipywidgets.FloatSlider(1.0, min=0.1, max=3.0, description="Gamma") linthresh = ipywidgets.FloatSlider(0.01, min=0.001, max=1.0, step=0.001, description="Linear threshold") linscale = ipywidgets.FloatSlider(0.1, min=0.001, max=10.0, step=0.001, description="Linear scale") auto = ipywidgets.Checkbox(True, description="Auto") help_text = ipywidgets.HTML(IMAGE_CONTRAST_EDITOR_HELP_IPYWIDGETS) wdict["help_text"] = help_text help = ipywidgets.Accordion(children=[help_text], selected_index=None) set_title_container(help, ["Help"]) close = ipywidgets.Button(description="Close", tooltip="Close widget.") apply = ipywidgets.Button( description="Apply", tooltip="Use the selected range to re-calculate the histogram.") reset = ipywidgets.Button( description="Reset", tooltip="Reset the settings to their initial values.") wdict["left"] = left wdict["right"] = right wdict["bins"] = bins wdict["norm"] = norm wdict["percentile"] = percentile wdict["gamma"] = gamma wdict["linthresh"] = linthresh wdict["linscale"] = linscale wdict["auto"] = auto wdict["close_button"] = close wdict["apply_button"] = apply wdict["reset_button"] = reset def transform_vmin(value): return (value, percentile.upper) def transform_vmin_inv(value): return value[0] def transform_vmax(value): return (percentile.lower, value) def transform_vmax_inv(value): return value[1] # Connect link((obj, "ss_left_value"), (left, "value")) link((obj, "ss_right_value"), (right, "value")) link((obj, "bins"), (bins, "value")) link((obj, "norm"), (norm, "value")) link((obj, "vmin_percentile"), (percentile, "value"), (transform_vmin, transform_vmin_inv)) link((obj, "vmax_percentile"), (percentile, "value"), (transform_vmax, transform_vmax_inv)) link((obj, "gamma"), (gamma, "value")) link((obj, "linthresh"), (linthresh, "value")) link((obj, "linscale"), (linscale, "value")) link((obj, "auto"), (auto, "value")) def display_parameters(change): # Necessary for the initialisation v = change if isinstance(change, str) else change.new if v == "Symlog": linthresh.layout.display = "" linscale.layout.display = "" else: linthresh.layout.display = "none" linscale.layout.display = "none" if v == "Power": gamma.layout.display = "" else: gamma.layout.display = "none" display_parameters(obj.norm) norm.observe(display_parameters, "value") def disable_parameters(change): # Necessary for the initialisation v = change if isinstance(change, bool) else change.new percentile.disabled = not v disable_parameters(obj.auto) auto.observe(disable_parameters, "value") def on_apply_clicked(b): obj.apply() apply.on_click(on_apply_clicked) def on_reset_clicked(b): obj.reset() reset.on_click(on_reset_clicked) box = ipywidgets.VBox([ left, right, auto, percentile, bins, norm, gamma, linthresh, linscale, help, ipywidgets.HBox((apply, reset, close)), ]) def on_close_clicked(b): obj.close() box.close() close.on_click(on_close_clicked) return { "widget": box, "wdict": wdict, }
from aicssegmentation.core.visual import blob2dExplorer_single, fila2dExplorer_single, random_colormap from aicssegmentation.core.seg_dot import dot_2d, logSlice from aicssegmentation.core.vessel import filament_2d_wrapper from aicssegmentation.core.utils import hole_filling from aicssegmentation.core.pre_processing_utils import intensity_normalization, suggest_normalization_param, edge_preserving_smoothing_3d fn = '/Users/claytonwandishin/UNC_PCNA/161124 u2os #5 ncs 6NCS_0_1c1.tif' os.path.isfile(fn) tif = TiffFile(fn) num_img = len(tif.pages) print(num_img) img_seq = [] for ii in range(num_img): img_seq.append(imread(fn, key=ii)) img = img_seq[135] suggest_normalization_param(img) img_norm = intensity_normalization(img, [0.5, 8.0]) img_smooth = edge_preserving_smoothing_3d(img_norm) interact(blob2dExplorer_single, im=fixed(img_smooth), \ sigma=widgets.FloatRangeSlider(value=(1,5), min=1, max=15,step=1,continuous_update=False), \ th=widgets.FloatSlider(value=0.02,min=0.01, max=0.1, step=0.01,continuous_update=False)) ksize = (65, 65) blur_smooth = cv2.blur(np.float32(img_smooth), ksize) nuc_detection = dot_2d(blur_smooth, 11) nuc_mask = nuc_detection > 0.0015 final_seg = hole_filling(remove_small_objects(nuc_mask), .5, 2500) plt.imshow(final_seg)
from ipywidgets import interact, interactive, fixed from IPython.core.display import HTML from IPython.display import display, clear_output from plotly.widgets import GraphWidget styles = '''<style>.widget-hslider { width: 100%; } .widget-hbox { width: 100% !important; } .widget-slider { width: 100% !important; }</style>''' HTML(styles) #this widget will display our plotly chart graph = GraphWidget("https://plot.ly/~chriddyp/674") fig = py.get_figure("https://plot.ly/~chriddyp/674") #find the range of the slider. xmin, xmax = fig['layout']['xaxis']['range'] # use the interact decorator to tie a widget to the listener function @interact(y=widgets.FloatRangeSlider(min=xmin, max=xmax, step=(xmax - xmin) / 1000.0, continuous_update=False)) def update_plot(y): graph.relayout({'xaxis.range[0]': y[0], 'xaxis.range[1]': y[1]}) #display the app graph
def plot_metrics_summary( # noqa: C901 metrics_results, target_meas_keys=[], target_meas_limits=[], n_bins_target=30, save_path=None, context="talk", interactive=False, ): """Plot metrics directly from the MetricsGenerator output. Args: metrics_results (dict): Output of a MetricsGenerator. target_meas_keys (list): List of the keys for the target measures. target_meas_limits (list): List of tuples indicating the limits for the plots of the target measures n_bins_target (int): Number of bins for the target measure plots save_path (str): Path to the folder where the figures should be saved. context (str): Context for seaborn; see seaborn documentation for details. Can be one of "paper", "notebook", "talk", and "poster". interactive (bool): Specifies if the plot should be interactive. """ sns.set_context(context) # Keys corresponding to the measure functions measure_keys = list(metrics_results["galaxy_summary"].keys()) # We need to handle the multiresolution case if isinstance(metrics_results["galaxy_summary"][measure_keys[0]], dict): survey_keys = list( metrics_results["galaxy_summary"][measure_keys[0]].keys()) gal_summary_keys = list(metrics_results["galaxy_summary"][ measure_keys[0]][survey_keys[0]].keys()) multiresolution = True # Limits for widgets min_mag = np.min(metrics_results["galaxy_summary"][measure_keys[0]][ survey_keys[0]]["ref_mag"]) max_mag = np.max(metrics_results["galaxy_summary"][measure_keys[0]][ survey_keys[0]]["ref_mag"]) min_size = np.min(metrics_results["galaxy_summary"][measure_keys[0]][ survey_keys[0]]["btk_size"]) max_size = np.max(metrics_results["galaxy_summary"][measure_keys[0]][ survey_keys[0]]["btk_size"]) else: gal_summary_keys = list( metrics_results["galaxy_summary"][measure_keys[0]].keys()) multiresolution = False min_mag = np.min( metrics_results["galaxy_summary"][measure_keys[0]]["ref_mag"]) max_mag = np.max( metrics_results["galaxy_summary"][measure_keys[0]]["ref_mag"]) min_size = np.min( metrics_results["galaxy_summary"][measure_keys[0]]["btk_size"]) max_size = np.max( metrics_results["galaxy_summary"][measure_keys[0]]["btk_size"]) plot_keys = ["reconstruction", "segmentation", "eff_matrix" ] + target_meas_keys + ["custom"] if interactive: layout = widgets.Layout(width="auto") # Checkboxes for selecting the measure function measure_functions_dict = { key: widgets.Checkbox(description=key, value=False, layout=layout) for key in measure_keys } measure_functions = [ measure_functions_dict[key] for key in measure_keys ] measure_functions_widget = widgets.VBox(measure_functions) measure_title_widget = widgets.HTML("<em>Measure functions</em>") measure_vbox = widgets.VBox( [measure_title_widget, measure_functions_widget]) # Checkboxes for selecting the survey (if multiresolution) if multiresolution: surveys_dict = { key: widgets.Checkbox(description=key, value=False, layout=layout) for key in survey_keys } surveys = [surveys_dict[key] for key in survey_keys] surveys_widget = widgets.VBox(surveys) surveys_title_widget = widgets.HTML("<em>Surveys</em>") surveys_vbox = widgets.VBox([surveys_title_widget, surveys_widget]) measure_surveys_widget = widgets.VBox([measure_vbox, surveys_vbox]) else: measure_surveys_widget = measure_vbox # Sliders to filter based on parameters blendedness_widget = widgets.FloatRangeSlider( description="Blendedness", value=[0, 1.0], min=0, max=1.0, step=0.01, continuous_update=False, ) magnitude_widget = widgets.FloatRangeSlider( description="Magnitude", value=[min_mag, max_mag], min=min_mag, max=max_mag, step=0.01, continuous_update=False, ) size_widget = widgets.FloatRangeSlider( description="Size", value=[min_size, max_size], min=min_size, max=max_size, step=0.01, continuous_update=False, ) filter_vbox = widgets.VBox( [blendedness_widget, magnitude_widget, size_widget]) # Checkboxes for selecting which metrics will be plotted plot_selection_dict = { key: widgets.Checkbox(description=key, value=False) for key in plot_keys } plot_selection = [plot_selection_dict[key] for key in plot_keys] plot_selection_widget = widgets.VBox(plot_selection) # Dropdowns for selecting the parameters for the custom plot custom_x_widget_drop = widgets.Dropdown( options=gal_summary_keys, description="X coordinate value", layout=layout, ) custom_y_widget_drop = widgets.Dropdown( options=gal_summary_keys, description="Y coordinate value", layout=layout, ) custom_x_widget_log = widgets.Checkbox(description="Log scale", value=False, layout=layout) custom_x_widget = widgets.HBox( [custom_x_widget_drop, custom_x_widget_log]) custom_y_widget_log = widgets.Checkbox(description="Log scale", value=False, layout=layout) custom_y_widget = widgets.HBox( [custom_y_widget_drop, custom_y_widget_log]) plot_selection_vbox = widgets.VBox(plot_selection + [custom_x_widget, custom_y_widget]) hbox = widgets.HBox( [measure_surveys_widget, filter_vbox, plot_selection_vbox]) display(hbox) # This function is called everytime the values of the widget change, and at the start def draw_plots(value): # If there are no widgets we use default values, else we get all the values if interactive: clear_output() display(hbox) meas_func_names = [ w.description for w in measure_functions_widget.children if w.value ] if multiresolution: surveys = [ w.description for w in surveys_widget.children if w.value ] blendedness_limits = blendedness_widget.value mag_limits = magnitude_widget.value size_limits = size_widget.value custom_x = custom_x_widget_drop.value custom_y = custom_y_widget_drop.value custom_x_log = custom_x_widget_log.value custom_y_log = custom_y_widget_log.value plot_selections = { w.description: w.value for w in plot_selection_widget.children } else: meas_func_names = measure_keys if multiresolution: surveys = survey_keys blendedness_limits = [0, 1] mag_limits = [min_mag, max_mag] size_limits = [min_size, max_size] plot_selections = {w: True for w in plot_keys} plot_selections["custom"] = False # If no measure function (or no surveys if multiresolution) is ticked, plot nothing if len(meas_func_names) == 0: return 0 if multiresolution and len(surveys) == 0: return 0 # Group all the data into a dataframe for using seaborn if multiresolution: dataframes = {} couples = [] for f_name in meas_func_names: for s_name in surveys: couples.append(f_name + "_" + s_name) dataframes[f_name + "_" + s_name] = metrics_results[ "galaxy_summary"][f_name][s_name].to_pandas() concatenated = pd.concat( [dataframes[c].assign(measure_function=c) for c in couples]) else: dataframes = {} for f_name in meas_func_names: dataframes[f_name] = metrics_results["galaxy_summary"][ f_name].to_pandas() concatenated = pd.concat([ dataframes[f_name].assign(measure_function=f_name) for f_name in meas_func_names ]) # Filter the data for the different parameters concatenated = concatenated.loc[ (concatenated["blendedness"] >= blendedness_limits[0]) & (concatenated["blendedness"] <= blendedness_limits[1])] concatenated = concatenated.loc[ (concatenated["ref_mag"] >= mag_limits[0]) & (concatenated["ref_mag"] <= mag_limits[1])] concatenated = concatenated.loc[ (concatenated["btk_size"] >= size_limits[0]) & (concatenated["btk_size"] <= size_limits[1])] for k in target_meas_keys: concatenated["delta_" + k] = concatenated[k] - concatenated[k + "_true"] # Custom scatter plot for the two chosen quantities if plot_selections["custom"]: fig, ax = plt.subplots(figsize=(15, 15)) sns.scatterplot(data=concatenated, x=custom_x, y=custom_y, hue="measure_function", ax=ax) if custom_x_log: ax.set_xscale("log") if custom_y_log: ax.set_yscale("log") plt.show() # Histograms for the reconstruction metrics if "msr" in concatenated and plot_selections["reconstruction"]: fig, ax = plt.subplots(3, 1, figsize=(20, 30)) fig.suptitle("Distribution of reconstruction metrics", fontsize=48) sns.histplot(concatenated, x="msr", hue="measure_function", bins=30, ax=ax[0], log_scale=True) ax[0].set_xlabel("Mean square residual") sns.histplot(concatenated, x="psnr", hue="measure_function", bins=30, ax=ax[1]) ax[1].set_xlabel("Peak Signal-to-Noise Ratio") sns.histplot(concatenated, x="ssim", hue="measure_function", bins=30, ax=ax[2]) ax[2].set_xlabel("Structure Similarity Index") if save_path is not None: plt.savefig( os.path.join(save_path, "distributions_reconstruction.png")) plt.show() # Histograms for the segmentation metrics if "iou" in concatenated and plot_selections["segmentation"]: fig, ax = plt.subplots(figsize=(20, 10)) fig.suptitle("Distribution of segmentation metrics", fontsize=48) sns.histplot(concatenated, x="iou", hue="measure_function", ax=ax, bins=30) ax.set_xlabel("Intersection-over-Union") if save_path is not None: plt.savefig( os.path.join(save_path, "distributions_segmentation.png")) plt.show() # Plots for the measure functions selected_target_meas = [ m for m in target_meas_keys if plot_selections[m] ] if selected_target_meas != []: n_target_meas = len(selected_target_meas) height_ratios = list( np.concatenate([[3, 1] for i in range(n_target_meas)])) fig, ax = plt.subplots( 2 * n_target_meas, 1, figsize=(10, 13.33 * n_target_meas), gridspec_kw={"height_ratios": height_ratios}, ) fig.suptitle("Target measures", fontsize=48) for i, k in enumerate(selected_target_meas): sns.scatterplot( data=concatenated, x=k, y=k + "_true", hue="measure_function", ax=ax[2 * i], marker="o", alpha=0.7, ) ax[2 * i].set( xlabel="Measured " + k, ylabel="True " + k, xlim=target_meas_limits[i], ylim=target_meas_limits[i], ) xlow, xhigh = ax[2 * i].get_xlim() x = np.linspace(xlow, xhigh, 10) ax[2 * i].plot(x, x, linestyle="--", color="black", zorder=-10) mag_low = np.min(concatenated["ref_mag"]) mag_high = np.max(concatenated["ref_mag"]) for meas_func in measure_keys: bins = np.linspace(mag_low, mag_high, n_bins_target) labels = np.digitize(concatenated["ref_mag"], bins) means = [] stds = [] to_delete = [] for j in range(1, n_bins_target): mean = np.mean(concatenated["delta_" + k][ (labels == j) & (concatenated["measure_function"] == meas_func)]) if not np.isnan(mean): means.append(mean) stds.append( np.std(concatenated["delta_" + k] [(labels == j) & (concatenated["measure_function"] == meas_func)])) else: to_delete.append(j) bins = np.delete(bins, to_delete) ax[2 * i + 1].errorbar( bins[1:] - (mag_high - mag_low) / n_bins_target, means, stds) ax[2 * i + 1].plot( np.linspace(mag_low, mag_high, 10), np.zeros((10)), linestyle="--", color="black", zorder=-10, ) ax[2 * i + 1].set_xlabel("Magnitude") # noqa: W605 ax[2 * i + 1].set_ylabel(f"$\\Delta${k}") # noqa: W605 plt.tight_layout() if save_path is not None: plt.savefig( os.path.join(save_path, "scatter_target_measures.png")) plt.show() # Plotting the efficiency matrices if plot_selections["eff_matrix"]: fig, ax = plt.subplots(1, len(meas_func_names), figsize=(15 * len(meas_func_names), 15)) fig.suptitle("Efficiency matrices", fontsize=48) if len(meas_func_names) == 1: ax = [ax] for i, k in enumerate(meas_func_names): if multiresolution: plot_efficiency_matrix(metrics_results["detection"][k][ survey_keys[0]]["eff_matrix"], ax=ax[i]) else: plot_efficiency_matrix( metrics_results["detection"][k]["eff_matrix"], ax=ax[i]) ax[i].set_title(k) if save_path is not None: plt.savefig(os.path.join(save_path, "efficiency_matrices.png")) plt.show() # Set the widgets to update the plots if modified if interactive: blendedness_widget.observe(draw_plots, "value") magnitude_widget.observe(draw_plots, "value") size_widget.observe(draw_plots, "value") for k in measure_keys: measure_functions_dict[k].observe(draw_plots, "value") if multiresolution: for k in survey_keys: surveys_dict[k].observe(draw_plots, "value") for k in plot_keys: plot_selection_dict[k].observe(draw_plots, "value") custom_x_widget_drop.observe(draw_plots, "value") custom_y_widget_drop.observe(draw_plots, "value") custom_x_widget_log.observe(draw_plots, "value") custom_y_widget_log.observe(draw_plots, "value") else: draw_plots(None)
def cfs_dsp(coeff, tables, n_eqn, y_lm, line_nms, tbl_horz=0): """ INPUTS tables (list of df's) summary table's ceoff (list of df's) input data line_nms (list of strings) legend entry names y_lm (int) upper y limit of the plot OUTPUTS Plot and Tables Displayed with interactive widgets """ # Layout of each widget box_hlayout = ipw.Layout(display='flex', flex_flow='row', align_items='stretch', width='95%') box_vlayout = ipw.Layout(display='flex', flex_flow='column', align_items='stretch', width='10%', height='auto', justify_content='space-between') if n_eqn == 1: # Coefficient selection widget coeff_sel = ipw.IntSlider(min=1, max=coeff[0].shape[1], value=1, step=1, description='Coefficient:', width='auto', layout=box_hlayout, style={'description_width': 'initial'}) elif n_eqn > 1: # Coefficient selection widget coeff_sel = ipw.IntSlider(min=1, max=coeff[0][0].shape[1], value=1, step=1, description='Coefficient:', width='auto', layout=box_hlayout, style={'description_width': 'initial'}) # Equation selection widget eqn_sel = ipw.IntSlider(min=1, max=n_eqn, value=1, step=1, description='Equation:', width='auto', layout=box_hlayout, style={'description_width': 'initial'}) # PU bandwidth constant selection widget ch_sel = ipw.FloatSlider(min=0.1, max=3, value=2.5, step=0.2, description='Bandwidth Constant', width='auto', layout=box_hlayout, style={'description_width': 'initial'}) # Horizontal display range slider widget xlim_sel = ipw.FloatRangeSlider(value=[-0.4, 0.4], min=-1, max=1, step=0.05, description='x limits:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.1f', width='auto', layout=box_hlayout, style={'description_width': 'initial'}) ylim_sel = ipw.FloatSlider(min=0, max=15, value=y_lm, step=1, description='y limits', orientation='vertical', length='auto', layout=box_vlayout, style={'description_length': 'initial'}, readout=False) # Interactive call of density function plot coeff_out = ipw.interactive_output( coeffden, { 'coeff': ipw.fixed(coeff), 'line_nms': ipw.fixed(line_nms), 'x_lm': xlim_sel, 'y_lm': ylim_sel, 'c_h': ch_sel, 'w': coeff_sel, 'n_eqn': ipw.fixed(n_eqn), 's_eqn': eqn_sel }) # Interactive call of table display function table_out = ipw.interactive_output( tbl_dsp, { 'tables': ipw.fixed(tables), 'n_eqn': ipw.fixed(n_eqn), 's_eqn': eqn_sel, 'line_nms': ipw.fixed(line_nms), 'horz': ipw.fixed(tbl_horz) }) # Return of the constructed block with widgetes and tables. if n_eqn == 1: return ipw.VBox([ table_out, ipw.HBox([coeff_out, ylim_sel]), coeff_sel, ch_sel, xlim_sel ]) else: return ipw.VBox([ table_out, ipw.HBox([coeff_out, ylim_sel]), coeff_sel, ch_sel, xlim_sel, eqn_sel ])
def Laplace(): """ Main function called by notebook to produce plots and UI """ # for ax lim sliders tAbsLim = 20 sAbsLim = 20 # define widgets tlim_sldr = widgets.FloatRangeSlider(value=[-10, 10], step=0.1, min=-tAbsLim, max=tAbsLim, description='t lim', continuous_update=False) slim_sldr = widgets.FloatRangeSlider(value=[-10, 10], step=0.1, min=-sAbsLim, max=sAbsLim, description='s lim', continuous_update=False) fslim_sldr = widgets.FloatRangeSlider(value=[0, 5], step=0.1, min=-5, max=5, description='F(s) lim', continuous_update=False) tShift_sldr = widgets.FloatSlider(value=0, step=0.1, min=-2, max=2, description='Shift t', continuous_updating=False) sShift_sldr = widgets.FloatSlider(value=0, step=0.1, min=-2, max=2, description='Shift s', continuous_updating=False) func_drop = widgets.Dropdown(options={ 't^n': 'Poly', 'sin(w*t)': 'Sine', 'cos(w*t)': 'Cos', 'exp(at)': 'exp' }, layout=widgets.Layout(width='220px'), description='$f(t)=$') # display display( widgets.VBox([ widgets.HBox([ widgets.VBox([tlim_sldr, slim_sldr]), widgets.VBox([tShift_sldr, sShift_sldr]), widgets.VBox([fslim_sldr, func_drop]) ]), widgets.interactive_output( showLaplace, { 'slim': slim_sldr, 'tlim': tlim_sldr, 'func': func_drop, 'tShift': tShift_sldr, 'fslim': fslim_sldr, 'sShift': sShift_sldr }) ]))
def islicer(data, direction, title="", slice_number=None, cmap='gray', minmax=None, size=None, axis_labels=None): '''Creates an interactive integer slider that slices a 3D volume along direction :param data: DataContainer or numpy array :param direction: slice direction, int, should be 0,1,2 or the axis label :param title: optional title for the display :slice_number: int start slice number, optional. If None defaults to center slice :param cmap: matplotlib color map :param minmax: colorbar min and max values, defaults to min max of container :param size: int or tuple specifying the figure size in inch. If int it specifies the width and scales the height keeping the standard matplotlib aspect ratio ''' if axis_labels is None: if hasattr(data, "dimension_labels"): axis_labels = [ data.dimension_labels[0], data.dimension_labels[1], data.dimension_labels[2] ] else: axis_labels = ['X', 'Y', 'Z'] if isinstance(data, numpy.ndarray): container = data elif hasattr(data, "__getitem__"): container = data elif hasattr(data, "as_array"): container = data.as_array() if not isinstance(direction, int): if direction in data.dimension_labels.values(): direction = data.get_dimension_axis(direction) if slice_number is None: slice_number = int(data.shape[direction] / 2) slider = widgets.IntSlider(min=0, max=data.shape[direction] - 1, step=1, value=slice_number, continuous_update=False, description=axis_labels[direction]) amax = container.max() amin = container.min() if minmax is None: cmax = amax cmin = amin else: cmin = min(minmax) cmax = max(minmax) if isinstance(size, (int, float)): default_ratio = 6. / 8. size = (size, size * default_ratio) min_max = widgets.FloatRangeSlider( value=[cmin, cmax], min=amin, max=amax, step=(amax - amin) / 100., description='display window', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.1e', ) interact( display_slice( container, direction, title=title, cmap=cmap, # minmax=(amin, amax), size=size, axis_labels=axis_labels), x=slider, minmax=min_max) return slider
def gradient(): func = widgets.Dropdown(\ options=['Ex_4','Ex_5'],\ value='Ex_4',\ description='Select Example') model = widgets.RadioButtons(\ options=['gradient descent (min)', 'gradient ascent(max)'],\ description='Model Option:',\ continuous_update=False,\ disabled=False) iteration = widgets.IntSlider(\ value = 0,\ min=0,\ max=20,\ step=1,\ description='Iteration number:',\ disabled=False,\ continuous_update=False) step = widgets.BoundedFloatText(\ value=0.1,\ min=0.01,\ max=0.2,\ step=0.01,\ description='step size for gradient ascent/descent',\ continuous_update=False,\ disabled=False) # spatial sliders xzoom = widgets.FloatRangeSlider(\ value=[-1.2,1.2],\ min=-2.,\ max=2.,\ step=0.1,\ continuous_update=False,\ description='x range for contour plot') yzoom = widgets.FloatRangeSlider(\ value=[-1.2,1.2],\ min=-2,\ max=2.,\ step=0.1,\ continuous_update=False,\ description='y range for contour plot') view_grad = widgets.Checkbox(\ value=False,\ description='View gradient vector field') # point at which to evaluate partial derivatives pt_x = widgets.BoundedFloatText(\ value=0.,\ min=-2.,\ max=2.,\ step=0.1,\ description='x coordinate of starting point',\ continuous_update=False,\ disabled=False) pt_y = widgets.BoundedFloatText(\ value=0.,\ min=-2.,\ max=2.,\ step=0.1,\ description='y coordinate of starting point',\ continuous_update=False,\ disabled=False) # interactive output return widgets.VBox([widgets.HBox([func]),\ widgets.HBox([model,iteration,step]),\ widgets.HBox([xzoom,yzoom,view_grad]),\ widgets.HBox([pt_x,pt_y]),\ widgets.interactive_output(gradient_run,\ {'func':func,'model':model,'iteration':iteration,'step':step,\ 'xzoom':xzoom,'yzoom':yzoom,'view_grad':view_grad,'pt_x':pt_x,'pt_y':pt_y})])
def setup_controls(self): down = ipywidgets.Button(icon="arrow-down", layout=ipywidgets.Layout(width='auto', grid_area="down")) up = ipywidgets.Button(icon="arrow-up", layout=ipywidgets.Layout(width='auto', grid_area="up")) right = ipywidgets.Button(icon="arrow-right", layout=ipywidgets.Layout(width='auto', grid_area="right")) left = ipywidgets.Button(icon="arrow-left", layout=ipywidgets.Layout(width='auto', grid_area="left")) zoom_start = 1./(self.view_width[0]) # By setting the dynamic range to be the ratio between coarsest and # finest, we ensure that at the fullest zoom, our smallest point will # be the size of our biggest point at the outermost zoom. dynamic_range = (max(self.pdx.max(), self.pdy.max()) / min(self.pdx.min(), self.pdy.min())) zoom = ipywidgets.FloatSlider(min=0.5, max=dynamic_range, step=0.1, value=zoom_start, description="Zoom", layout=ipywidgets.Layout(width="auto", grid_area="zoom")) is_log = ipywidgets.Checkbox(value=False, description="Log colorscale") colormaps = ipywidgets.Dropdown( options=list(self.colormaps.cmaps.keys()), description="colormap", value = "viridis") min_val = ipywidgets.BoundedFloatText(description="lower colorbar bound:", value=self.val.min(), min=self.val.min(), max=self.val.max()) max_val = ipywidgets.BoundedFloatText(description="upper colorbar bound:", value=self.val.max(), min=self.val.min(), max=self.val.max()) minmax = ipywidgets.FloatRangeSlider(min=self.val.min(), max=self.val.max()) down.on_click(self.on_ydownclick) up.on_click(self.on_yupclick) right.on_click(self.on_xrightclick) left.on_click(self.on_xleftclick) zoom.observe(self.on_zoom, names='value') # These can be jslinked, so we will do so. ipywidgets.jslink((is_log, 'value'), (self.colormaps, 'is_log')) ipywidgets.jslink((min_val, 'value'), (self.colormaps, 'min_val')) ipywidgets.jslink((max_val, 'value'), (self.colormaps, 'max_val')) # This one seemingly cannot be. ipywidgets.link((colormaps, 'value'), (self.colormaps, 'map_name')) nav_buttons = ipywidgets.GridBox(children = [up, left, right, down], layout=ipywidgets.Layout(width='100%', grid_template_columns = '33% 34% 33%', grid_template_rows = 'auto auto auto', grid_template_areas = ''' " . up . " " left . right " " . down . " ''', grid_area='nav_buttons')) all_navigation = ipywidgets.GridBox(children = [nav_buttons, zoom], layout=ipywidgets.Layout(width="300px", grid_template_columns="25% 50% 25%", grid_template_rows="auto auto", grid_template_areas=''' ". nav_buttons ." "zoom zoom zoom" ''' )) all_normalizers = ipywidgets.GridBox(children = [is_log, colormaps, min_val, max_val], layout=ipywidgets.Layout(width="auto") ) accordion = ipywidgets.Accordion(children=[all_navigation, all_normalizers]) accordion.set_title(0, 'navigation') accordion.set_title(1, 'colormap controls') return accordion
def plot_pupil_ipy(tx, sy, event_onsets=None, overlays=None, overlay_labels=None, blinks=None, interpolated=None, figsize=(16, 8), xlab="ms", nsteps=100): """ Plotting with interactive adjustment of plotting window. To use this, do $ pip install ipywidgets $ jupyter nbextension enable --py widgetsnbextension $ jupyter labextension install @jupyter-widgets/jupyterlab-manager Parameters ---------- tx : np.ndarray time-vector in seconds sy : np.ndarray raw pupil signal event_onsets : list onsets of events (stimuli/responses) in seconds overlays: tuple of np.array signals to overlay over the plot, given as tuple of arrays of same length as `tx` overlay_labels: tuple of strings labels for the overlays to be displayed in the legend figsize: tuple of int dimensions for the plot xlab: str label for x-axis nsteps: int number of steps for slider """ import pylab as plt from ipywidgets import interact, interactive, fixed, interact_manual, Layout import ipywidgets as widgets def draw_plot(plotxrange): xmin, xmax = plotxrange ixmin = np.argmin(np.abs(tx - xmin)) ixmax = np.argmin(np.abs(tx - xmax)) plt.figure(figsize=figsize) plt.plot(tx[ixmin:ixmax], sy[ixmin:ixmax], label="signal") if overlays is not None: if type(overlays) is np.ndarray: plt.plot(tx[ixmin:ixmax], overlays[ixmin:ixmax], label=overlay_labels) else: for i, overlay in enumerate(overlays): lab = overlay_labels[ i] if overlay_labels is not None else None plt.plot(tx[ixmin:ixmax], overlay[ixmin:ixmax], label=lab) for istart, iend in interpolated: plt.gca().axvspan(tx[istart], tx[iend], color="green", alpha=0.1) for istart, iend in blinks: plt.gca().axvspan(tx[istart], tx[iend], color="red", alpha=0.1) plt.vlines(event_onsets, *plt.ylim(), color="grey", alpha=0.5) plt.xlim(xmin, xmax) plt.xlabel(xlab) if overlay_labels is not None: plt.legend() wid_range = widgets.FloatRangeSlider(value=[tx.min(), tx.max()], min=tx.min(), max=tx.max(), step=(tx.max() - tx.min()) / nsteps, description=' ', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.1f', layout=Layout(width='100%', height='80px')) interact(draw_plot, plotxrange=wid_range)
def make_tab(image_fn): def generate_figure(highlight, vertical_range, contrast, invert, show_expected, window_size, notes): fig = plot_gel(image_fn, highlight=highlight, vertical_range=vertical_range, contrast=contrast, invert=invert, show_expected=show_expected, window_size=window_size, **kwargs) fig.axes[1].annotate(notes, xy=(0, 1), xycoords='axes fraction', xytext=(5, 2), textcoords='offset points', ha='left', va='bottom', size=8, ) plt.show() return fig annotations = load_annotations(image_fn) labels = annotations.get('labels', []) default_filename = str(Path.home() / Path(image_fn).with_suffix('.png').name) widgets = { 'vertical_range': ipywidgets.FloatRangeSlider( value=[0, 1], continuous_update=False, min=0, max=1, step=0.01, layout=ipywidgets.Layout(height='200px'), description='Vertical range:', style={'description_width': 'initial'}, orientation='vertical', ), 'window_size': ipywidgets.IntSlider( value=10, continuous_update=False, min=1, max=30, step=1, layout=ipywidgets.Layout(height='200px'), description='Window size:', style={'description_width': 'initial'}, orientation='vertical', ), 'highlight': ipywidgets.SelectMultiple( options=labels, value=[], layout=ipywidgets.Layout(height='200px'), description='Highlight:', ), 'contrast': ipywidgets.FloatSlider( value=1.0, continuous_update=False, min=0, max=1, step=0.05, layout=ipywidgets.Layout(height='200px'), description='Contrast:', style={'description_width': 'initial'}, orientation='vertical', ), 'invert': ipywidgets.ToggleButton( value=False, description='Invert', icon='check', ), 'show_expected': ipywidgets.Dropdown( options={'neither': False, 'plot': 'plot', 'image': 'image', 'both': 'both', }, value=False, description='Show expected', ), 'save': ipywidgets.Button( description='Save snapshot', ), 'file_name': ipywidgets.Text( value=default_filename, ), 'close': ipywidgets.Button( description='Close tab', ), 'notes': ipywidgets.Textarea( description='Notes:', layout=ipywidgets.Layout(height='200px', width='400px'), ), 'labels': ipywidgets.Textarea( description='Lane labels:', layout=ipywidgets.Layout(height='200px', width='400px'), ), 'expected': ipywidgets.Textarea( description='Expected:', layout=ipywidgets.Layout(height='200px', width='400px'), ), 'update': ipywidgets.Button( description='Update', ), } def save(_): fig = interactive.result fn = widgets['file_name'].value fig.savefig(fn, bbox_inches='tight') widgets['save'].on_click(save) def close(_): titles = [tabs.get_title(i) for i, c in enumerate(tabs.children) if i != tabs.selected_index] tabs.children = [c for i, c in enumerate(tabs.children) if i != tabs.selected_index] for i, title in enumerate(titles): tabs.set_title(i, title) widgets['close'].on_click(close) interactive = ipywidgets.interactive(generate_figure, **widgets) output = interactive.children[-1] interactive.update() widgets['invert'].value = annotations.get('invert', False) widgets['contrast'].value = annotations.get('contrast', 1.0) widgets['window_size'].value = annotations.get('window_size', 10) widgets['notes'].value = annotations.get('notes', '') widgets['labels'].value = '\n'.join(annotations.get('labels', [])) expected = annotations.get('expected', {}) lines = ['{0}: {1}'.format(length, name) for length, name in sorted(expected.items())] widgets['expected'].value = '\n'.join(lines) def update_annotations(_): def get_lines(key): lines = [str(v) for v in widgets[key].value.split('\n')] if lines == ['']: lines = [] return lines annotations['notes'] = str(widgets['notes'].value) labels = get_lines('labels') widgets['highlight'].options = labels expected = {} for line in get_lines('expected'): length, name = line.split(': ') length = int(length) expected[length] = name annotations['expected'] = expected annotations['labels'] = labels annotations['invert'] = widgets['invert'].value annotations['contrast'] = widgets['contrast'].value annotations['window_size'] = widgets['window_size'].value save_annotations(image_fn, annotations) interactive.update() widgets['update'].on_click(update_annotations) def group_widgets(keys, kind): if kind == 'row': Box = ipywidgets.HBox elif kind == 'col': Box = ipywidgets.VBox keys = [widgets.get(k, k) for k in keys] return Box(keys) make_row = lambda keys: group_widgets(keys, 'row') make_col = lambda keys: group_widgets(keys, 'col') layout = make_col([ make_row([output]), make_row(['highlight', 'vertical_range', 'contrast', 'window_size', make_col([ 'invert', ]), make_col([ 'save', 'close', 'update', ]), make_col([ 'file_name', 'show_expected', ]), ]), make_row(['labels', 'expected', 'notes', ]), ]) return layout
def controls(self): from .layers import VALID_STRETCHES, UI_COLORMAPS if self._controls is not None: return self._controls opacity = widgets.FloatSlider(description='Opacity:', value=self.opacity, min=0, max=1, readout=False, step=0.01, layout={'width': '200px'}) link((self, 'opacity'), (opacity, 'value')) stretch = widgets.Dropdown(description='Stretch:', options=VALID_STRETCHES, value=self.stretch, layout={'width': '200px'}) link((self, 'stretch'), (stretch, 'value')) # NB, this will crash if `self.cmap` is not one of our allowed values reverse_ui_colormaps = dict( (kv[1], kv[0]) for kv in UI_COLORMAPS.items()) colormap = widgets.Dropdown(description='Colormap:', options=UI_COLORMAPS.keys(), value=reverse_ui_colormaps[self.cmap.name], layout={'width': '200px'}) directional_link((colormap, 'label'), (self, 'cmap'), lambda x: UI_COLORMAPS[x]) directional_link((self, 'cmap'), (colormap, 'label'), lambda x: reverse_ui_colormaps[x.name]) vrange = widgets.FloatRangeSlider(description='Fine min/max:', value=[self.vmin, self.vmax], min=self._data_min, max=self._data_max, readout=True, layout={'width': '600px'}, step=(self.vmax - self.vmin) / 100, format='.3g') # Linkage must be manual since vrange uses a pair of values whereas we # have two separate traitlets. vrange.observe(self._vrange_slider_updated, names=['value']) def update_vrange(change): # Note: when this function is called, these values are indeed updated. vrange.value = (self.vmin, self.vmax) self.observe(update_vrange, names=['vmin', 'vmax']) def update_step(change): vrange.step = (vrange.max - vrange.min) / 100 vrange.observe(update_step, names=['min', 'max']) coarse_min = widgets.FloatText(description='Coarse min:', value=self._data_min, layout={'width': '300px'}) link((coarse_min, 'value'), (vrange, 'min')) coarse_max = widgets.FloatText(description='Coarse max:', value=self._data_max, layout={'width': '300px'}) link((coarse_max, 'value'), (vrange, 'max')) self._controls = widgets.VBox([ widgets.HBox([colormap, stretch, opacity]), widgets.HBox([coarse_min, coarse_max]), vrange, ]) return self._controls
def __init__(self, npkd, pkname): if not isinstance(npkd, FTMSData): raise Exception('This modules requires a FTMS Dataset') self.npkd = npkd self.pkname = pkname self.zoom = widgets.FloatRangeSlider( value=[npkd.axis1.lowmass, npkd.axis1.highmass], min=npkd.axis1.lowmass, max=npkd.axis1.highmass, step=0.1, layout=Layout(width='100%'), description='zoom', continuous_update=False, readout=True, readout_format='.1f', ) self.zoom.observe(self.display) self.tlabel = Label('threshold (x noise level):') self.thresh = widgets.FloatLogSlider(value=20.0, min=np.log10(3), max=2.0, base=10, step=0.01, layout=Layout(width='30%'), continuous_update=False, readout=True, readout_format='.1f') self.thresh.observe(self.pickpeak) self.peak_mode = widgets.Dropdown(options=['marker', 'bar'], value='marker', description='show as') self.peak_mode.observe(self.display) self.bexport = widgets.Button( description="Export", layout=Layout(width='7%'), button_style= 'success', # 'success', 'info', 'warning', 'danger' or '' tooltip='Export to csv file') self.bexport.on_click(self.pkexport) self.bprint = widgets.Button(description="Print", layout=Layout(width='7%'), button_style='success', tooltip='Print to screen') self.bprint.on_click(self.pkprint) self.bdone = widgets.Button(description="Done", layout=Layout(width='7%'), button_style='warning', tooltip='Fix results') self.bdone.on_click(self.done) # self.spec = Output(layout={'border': '1px solid black'}) self.out = Output(layout={'border': '1px solid red'}) display( VBox([ self.zoom, HBox([ self.tlabel, self.thresh, self.peak_mode, self.bprint, self.bexport, self.bdone ]) ])) self.fig, self.ax = plt.subplots() self.npkd.set_unit('m/z').peakpick(autothresh=self.thresh.value, verbose=False, zoom=self.zoom.value).centroid() self.display() display(self.out)
def __init__(self, path_or_url, **kw): # data self.path = path_or_url x, y, w, labels = read2d(path_or_url, **kw) if 'labels' not in kw: kw['labels'] = labels self.x = x self.y = y self.w = w self.kw = kw x0 = x[0] y0 = y[:, 0] xmin, xmax, dx = x[0, 0], x[0, -1], x[0, 1] - x[0, 0] ymin, ymax, dy = y[0, 0], y[-1, 0], y[1, 0] - y[0, 0] wmin, wmax = np.min(w), np.max(w) dw = (wmax - wmin) / 20 # UI self.s_xpos = widgets.FloatSlider(value=(xmin + xmax) / 2, min=xmin, max=xmax, step=dx, description='x') self.s_ypos = widgets.FloatSlider(value=(ymin + ymax) / 2, min=ymin, max=ymax, step=dy, description='y') vb1 = widgets.VBox([self.s_xpos, self.s_ypos]) self.s_gamma = widgets.IntSlider(value=0, min=-100, max=100, step=10, description='gamma') self.s_vlim = widgets.FloatRangeSlider(value=[wmin, wmax], min=wmin, max=wmax, step=dw, description='limit') self.c_cmap = widgets.Combobox(value='', placeholder='Choose or type', options=plt.colormaps(), description='colormap:', ensure_option=False, disabled=False) vb2 = widgets.VBox([self.s_gamma, self.s_vlim, self.c_cmap]) self.b_expMTX = widgets.Button(description='To mtx') self.html_exp = widgets.HTML() vb3 = widgets.VBox([self.b_expMTX, self.html_exp]) ui = widgets.Tab(children=[vb1, vb2, vb3]) [ ui.set_title(i, j) for i, j in zip(range(3), ['linecuts', 'color', 'export']) ] display(ui) # figure fig, axs = plt.subplots(1, 2, figsize=(6.5, 2.5)) #main plot and h linecut fig.canvas.header_visible = False fig.canvas.toolbar_visible = False fig.canvas.resizable = False plt.subplots_adjust(wspace=0.4, bottom=0.2) axs[1].yaxis.tick_right() axs[1].tick_params(axis='x', colors='tab:orange') axs[1].tick_params(axis='y', colors='tab:orange') axv = fig.add_axes(axs[1].get_position(), frameon=False) #ax vertical linecut axv.xaxis.tick_top() axv.tick_params(axis='x', colors='tab:blue') axv.tick_params(axis='y', colors='tab:blue') self.fig = fig self.ax = axs[0] self.axv = axv self.axh = axs[1] # plot 2D data g = self.s_gamma.value v0, v1 = self.s_vlim.value self.kw['gamma'], self.kw['vmin'], self.kw['vmax'] = g, v0, v1 Painter.plot2d(self.x, self.y, self.w, fig=self.fig, ax=self.ax, **self.kw) self.im = [ obj for obj in self.ax.get_children() if isinstance(obj, mpl.image.AxesImage) or isinstance(obj, mpl.collections.QuadMesh) ][0] # vlinecut xpos = self.s_xpos.value indx = np.abs(x0 - xpos).argmin() # x0 may be a non uniform array [self.linev1] = axs[0].plot(x[:, indx], y0, 'tab:blue') [self.linev2] = axv.plot(w[:, indx], y0, 'tab:blue') self.indx = indx # hlinecut ypos = self.s_ypos.value indy = np.abs(y0 - ypos).argmin() [self.lineh1] = axs[0].plot(x0, y[indy, :], 'tab:orange') [self.lineh2] = axs[1].plot(x0, w[indy, :], 'tab:orange') self.indy = indy self.s_gamma.observe(self.on_gamma_change, 'value') self.s_vlim.observe(self.on_vlim_change, 'value') self.c_cmap.observe(self.on_cmap_change, 'value') self.s_xpos.observe(self.on_xpos_change, 'value') self.s_ypos.observe(self.on_ypos_change, 'value') self.fig.canvas.mpl_connect('button_press_event', self.on_mouse_click) self.b_expMTX.on_click(self.exportMTX)
def __init__(self, drawable_mesh): self.drawable = drawable_mesh self.mesh = drawable_mesh.geometry self.mesh.attach(self) self.widgets = [] self.click_picker = self.__initialize_picker() self.old_picked_face = None self.old_picked_face_internal = False self.__clipping_in_queue = False self.__dont_update_clipping = False self.invisible_layout = {'display': 'none'} self.visible_layout = {'display': ''} self.flip_button_layout = { 'width': 'auto', 'margin': '0px 0px 0px 10px' } self.slider_layout = {} self.flip_x_button = widgets.ToggleButton( value=False, description='Flip x', disabled=False, button_style='info', tooltip='Flip the visualization range on x axis', layout=self.flip_button_layout) self.flip_y_button = widgets.ToggleButton( value=False, description='Flip y', disabled=False, button_style='info', # 'success', 'info', 'warning', 'danger' or '' tooltip='IFlip the visualization range on y axis', layout=self.flip_button_layout) self.flip_z_button = widgets.ToggleButton( value=False, description='Flip z', disabled=False, button_style='info', # 'success', 'info', 'warning', 'danger' or '' tooltip='Flip the visualization range on z axis', layout=self.flip_button_layout) x_range = self.mesh.bbox[0][0], self.mesh.bbox[1][0] x_step = abs(x_range[0] - x_range[1]) / 100 self.clipping_slider_x = widgets.FloatRangeSlider( value=x_range, min=x_range[0] - x_step, max=x_range[1] + x_step, step=x_step, description='X Clipping:', disabled=False, continuous_update=True, orientation='horizontal', readout=True, readout_format=".1f", layout=self.slider_layout) y_range = self.mesh.bbox[0][1], self.mesh.bbox[1][1] y_step = abs(y_range[0] - y_range[1]) / 100 self.clipping_slider_y = widgets.FloatRangeSlider( value=y_range, min=y_range[0] - y_step, max=y_range[1] + y_step, step=y_step, description='Y Clipping:', disabled=False, continuous_update=True, orientation='horizontal', readout=True, readout_format=".1f", layout=self.slider_layout) z_range = self.mesh.bbox[0][2], self.mesh.bbox[1][2] z_step = abs(z_range[0] - z_range[1]) / 100 self.clipping_slider_z = widgets.FloatRangeSlider( value=z_range, min=z_range[0] - z_step, max=z_range[1] + z_step, step=z_step, description='Z Clipping:', disabled=False, continuous_update=True, orientation='horizontal', readout=True, readout_format=".1f", layout=self.slider_layout) self.wireframe_opacity_slider = widgets.FloatSlider( value=0.4, min=0., max=1., step=0.1, continuous_update=True, readout_format=".1f", description='Wireframe', disable=False, ) self.color_wireframe = widgets.ColorPicker( concise=True, value=self.drawable.wireframe.material.color, disabled=False, layout={'margin': '0 0 0 10px'}) self.widgets += [ widgets.HBox([self.clipping_slider_x, self.flip_x_button]), widgets.HBox([self.clipping_slider_y, self.flip_y_button]), widgets.HBox([self.clipping_slider_z, self.flip_z_button]), widgets.HBox([self.wireframe_opacity_slider, self.color_wireframe]), ] self.picking_title = widgets.Label(value="Click informations:", layout={'margin': '0 0 0 20px'}, disabled=False, continuous_update=True) self.picking_label = widgets.Label(layout={'margin': '0 0 0 20px'}, disabled=False, continuous_update=True) tab_titles = ['Face', 'Vertex'] children = [ widgets.HTML(value="", layout={'margin': '0 0 0 10px'}, disabled=False, continuous_update=True) for title in tab_titles ] self.picking_tab = widgets.Tab(layout={'margin': '0 0 0 20px'}, disabled=True, width=300, height=400) self.picking_tab.children = children for i in range(len(children)): self.picking_tab.set_title(i, tab_titles[i]) self.color_picking_label = widgets.Label( value="Click Color ", layout={'margin': '0 0 0 20px'}, disabled=False, continuous_update=True) self.widgets += [ widgets.HBox([self.picking_title]), widgets.HBox([self.picking_label]), widgets.HBox([self.picking_tab]) ] self.color_map = widgets.Dropdown( options=[(i, idx) for idx, i in enumerate(ColorMap.color_maps.keys())], value=0, description='Color-Map:', layout=self.invisible_layout, ) self.widgets += [self.color_map] self.metric_menu = widgets.Dropdown( options=[(i, idx) for idx, i in enumerate(self.mesh.simplex_metrics.keys()) ], value=0, description='Metric:', layout=self.invisible_layout, ) self.widgets += [self.metric_menu] self.coloring_type_menu = widgets.Dropdown( options=[('Default', 0), ('Simplex Quality', 1), ('Label', 2)], value=0, description='Color Type:', ) self.widgets += [self.coloring_type_menu] mesh_colors = [] if hasattr(self.mesh, "internals"): self.color_internal = widgets.ColorPicker( concise=True, description='Internal', value=colors.rgb2hex(self.drawable._internal_color), disabled=False, ) mesh_colors += [self.color_internal] self.color_picking = widgets.ColorPicker( concise=True, description="Click Color", value=colors.rgb2hex(colors.purple), disabled=False, ) self.color_external = widgets.ColorPicker( concise=True, description='External', value=colors.rgb2hex(self.drawable._external_color), disabled=False, ) mesh_colors += [self.color_external] mesh_colors += [self.color_picking] self.widgets += [widgets.HBox(mesh_colors)] self.color_label_pickers = [ widgets.ColorPicker( concise=True, description='Label ' + str(i), value=colors.random_color(return_hex=True), disabled=False, layout=self.visible_layout, ) for i in np.unique(self.mesh.labels) ] self.color_label_pickers = widgets.HBox(self.color_label_pickers, layout=self.invisible_layout) self.widgets += [self.color_label_pickers] self.flip_x_button.observe(self.__update_clipping, names='value') self.flip_y_button.observe(self.__update_clipping, names='value') self.flip_z_button.observe(self.__update_clipping, names='value') self.clipping_slider_x.observe(self.__update_clipping, names='value') self.clipping_slider_y.observe(self.__update_clipping, names='value') self.clipping_slider_z.observe(self.__update_clipping, names='value') if hasattr(self.mesh, "internals"): self.color_internal.observe(self.__update_internal_color, names='value') self.color_external.observe(self.__update_external_color, names='value') self.color_wireframe.observe(self.__update_wireframe_color, names='value') self.wireframe_opacity_slider.observe(self.__update_wireframe_opacity, names='value') self.coloring_type_menu.observe(self.__change_color_type, names='value') self.color_map.observe(self.__change_color_map, names='value') self.metric_menu.observe(self.__change_metric, names='value') self.click_picker.observe(self.on_click, names=['point']) [ i.observe(self.__change_color_label, names='value') for i in self.color_label_pickers.children ] #self.wireframe_thickness_slider.observe(self.__update_wireframe_thickness, names='value') for widget in self.widgets: ipydisplay(widget)
sl_alg_manag ], layout={'align_items': 'stretch'}) sl_rep = widgets.IntSlider(value=1, min=1, max=10, step=1, disabled=True) rep = widgets.VBox( [widgets.Label('Simulation runs:', layout={'width': '95%'}), sl_rep], layout={'align_items': 'stretch'}) bt_start_simple = widgets.Button(description='Start', disabled=True) # Optimizer components sl_eta_range = widgets.FloatRangeSlider(value=[0.5, 0.7], min=0, max=1.0, step=0.01, disabled=True) eta_range = widgets.VBox([ widgets.Label('Frequency threshold (eta):', layout={'width': '95%'}), sl_eta_range ], layout={'align_items': 'stretch'}) sl_epsilon_range = widgets.FloatRangeSlider(value=[0.5, 0.7], min=0, max=1.0, step=0.01, disabled=True)
def wi9(muscle_emg): style = {'description_width': 'initial'} wi110 = wi.Checkbox(value=True, description='Plot moving RMS', layout=wi.Layout(width='400px'), continuous_update=False, style=style) wi111 = wi.IntSlider(value=100, min=1, max=500, layout=wi.Layout(width='400px'), style=style, continuous_update=False, description='Moving RMS window length [ms]:') wi112 = wi.Checkbox(value=True, description='Plot Spectrogram', continuous_update=False, style=style, layout=wi.Layout(width='400px')) wi113 = wi.Dropdown(options=['boxcar', 'hamming', 'hann'], value='hann', style=style, layout=wi.Layout(width='400px'), continuous_update=False, description='Window type:') wi114 = wi.IntSlider(value=120, min=2, max=3000, layout=wi.Layout(width='400px'), style=style, continuous_update=False, description='Window length [ms]:') wi115 = wi.IntSlider(value=60, min=1, max=1500, layout=wi.Layout(width='400px'), style=style, continuous_update=False, description='Window overlap [ms]:') wi116 = wi.Checkbox(value=False, continuous_update=False, description='Plot Welch \' s periodogram', layout=wi.Layout(width='400px'), style=style) wi117 = wi.Dropdown(options=['boxcar', 'hamming', 'hann'], value='hann', continuous_update=False, style=style, description='Window type:', layout=wi.Layout(width='400px')) wi118 = wi.IntSlider(value=120, min=2, max=3000, style=style, layout=wi.Layout(width='400px'), continuous_update=False, description='Window length [ms]:') wi119 = wi.IntSlider(value=60, min=1, max=1500, layout=wi.Layout(width='400px'), style=style, continuous_update=False, description='Window overlap [ms]:') end = muscle_emg.t[-1] wi1110 = wi.FloatRangeSlider(value=[0, end], min=0, max=end, step=50, style=style, layout=wi.Layout(width='500px'), continuous_update=False, description='Analysis interval [ms]') wi1111 = wi.Checkbox(value=False, style=style, description='Plot MU contribution', layout=wi.Layout(width='400px'), continuous_update=False) wi1112 = wi.BoundedIntText(value=1, min=1, max=muscle_emg.LR, step=1, description='MU index #:', continuous_update=False, style=style, layout=wi.Layout(width='400px')) ws11 = { 'add_rms': wi110, 'rms_length': wi111, 'add_spec': wi112, 'spec_w': wi113, 'spec_w_size': wi114, 'spec_ol': wi115, 'add_welch': wi116, 'welch_w': wi117, 'welch_w_size': wi118, 'welch_ol': wi119, 'a_interval': wi1110, 'add_mu_cont': wi1111, 'mu_c_index': wi1112 } mu_cont_acc = wi.VBox([wi1111, wi1112]) moving_average_acc = wi.VBox([wi110, wi111]) spectrogram_acc = wi.VBox([wi112, wi113, wi114, wi115]) welch_acc = wi.VBox([wi116, wi117, wi118, wi119]) acc11 = wi.Tab( children=[moving_average_acc, spectrogram_acc, welch_acc, mu_cont_acc]) acc11.set_title(0, 'Moving RMS') acc11.set_title(1, 'Spectrogram') acc11.set_title(2, 'Welch\'s periodogram') acc11.set_title(3, 'MUAP train') ui9 = wi.VBox([wi1110, acc11]) l11 = wi.link((ui9.children[1].children[1].children[2], 'value'), (ui9.children[1].children[1].children[3], 'max')) l12 = wi.link((ui9.children[1].children[1].children[3], 'value'), (ui9.children[1].children[1].children[2], 'min')) l21 = wi.link((ui9.children[1].children[2].children[2], 'value'), (ui9.children[1].children[2].children[3], 'max')) l22 = wi.link((ui9.children[1].children[2].children[3], 'value'), (ui9.children[1].children[2].children[2], 'min')) return ui9, ws11
def __init__(self): # define + and - buttons self.w_add_left = widgets.Button(icon="plus-square", layout=widgets.Layout(width='30px')) self.w_add_right = widgets.Button(icon="plus-square", layout=widgets.Layout(width='30px')) self.w_del_left = widgets.Button(icon="minus-square", layout=widgets.Layout(width='30px')) self.w_del_right = widgets.Button(icon="minus-square", layout=widgets.Layout(width='30px')) # define callbacks for + and - buttons self.w_add_left.on_click(self.add_section_to_the_left) self.w_add_right.on_click(self.add_section_to_the_right) self.w_del_left.on_click(self.del_section_to_the_left) self.w_del_right.on_click(self.del_section_to_the_right) self.output = widgets.Output() self.w_plot = widgets.Button(description='plot') self.w_plot.on_click(self.update_plot) self.f_vi = 55 # MHz # frequency for voltage and current plot self.f_vi_w = widgets.BoundedFloatText( value=self.f_vi, min=45, max=65, step=0.1, description='V/I plot frequency [MHz]', layout=widgets.Layout(width='150px')) self.f_vi_w.observe(self.update_f_vi) # frequency band for S11 plot self.frequency_band_w = widgets.FloatRangeSlider( value=[self.f_vi - 1, self.f_vi + 1], min=45, max=65, step=0.1, readout=True, readout_format=".1f", ) self.frequency_band_w.observe(self.update_frequency_band) # Input Power self.w_Pin = widgets.BoundedFloatText( value=50, min=1, max=200, description='Input Power [kW]', layout=widgets.Layout(width='150px')) self.w_Pin.observe(self.update_Pin) # Configuration Manager self.w_load = widgets.Button(description='Load Configuration') self.w_load.on_click(self.load_config) self.w_save = widgets.Button(description='Save Configuration') self.w_save.on_click(self.save_config) self.w_config_text = widgets.Textarea() self.w_config = widgets.Dropdown(options=[ 'Simple - 55 MHz', 'SSA50 - 62 MHz', 'SSA84 - FW Vmax', 'SSA84 - FW Imax' ], value='Simple - 55 MHz') self.w_config.observe(self.update_config) self.set_config() self.fig, self.axes = plt.subplots(figsize=(10, 6)) self.__update_display() super().__init__(children=self.UI)
def wi12(muscle_force): style = {'description_width': 'initial'} wi120 = wi.Checkbox(value=True, style=style, description='Plot standard deviation', layout=wi.Layout(width='400px')) wi122 = wi.Checkbox(value=True, style=style, description='Plot spectrogram', layout=wi.Layout(width='400px')) wi123 = wi.Dropdown(options=['boxcar', 'hamming', 'hann'], value='hann', layout=wi.Layout(width='400px'), style=style, description='Window type:') wi124 = wi.IntSlider(value=2000, min=2, max=5000, step=5, layout=wi.Layout(width='400px'), style=style, description='Window length [ms]:') wi125 = wi.IntSlider(value=60, min=1, max=2500, step=5, layout=wi.Layout(width='400px'), style=style, description='Window overlap [ms]:') wi126 = wi.Checkbox(value=False, style=style, description='Plot Welch \' s periodogram', layout=wi.Layout(width='400px')) wi127 = wi.Dropdown(options=['boxcar', 'hamming', 'hann'], value='hann', layout=wi.Layout(width='400px'), style=style, description='Window type:') wi128 = wi.IntSlider(value=2000, min=2, max=5000, step=5, layout=wi.Layout(width='400px'), style=style, description='Window length [ms]:') wi129 = wi.IntSlider(value=60, min=0, max=2500, step=5, layout=wi.Layout(width='400px'), style=style, description='Window overlap [ms]:') wi1210 = wi.FloatRangeSlider(value=[0, muscle_force.t[-1]], min=0, max=muscle_force.t[-1], step=50, layout=wi.Layout(width='600px'), style=style, description='Analysis interval [ms]') wi1211 = wi.Checkbox(value=False, description='Plot MU force', layout=wi.Layout(width='400px'), style=style) wi1212 = wi.BoundedIntText(value=1, min=1, max=muscle_force.LR, step=1, style=style, description='Motor unit index #:', layout=wi.Layout(width='400px')) ws = { 'add_rms': wi120, 'add_spec': wi122, 'spec_w': wi123, 'spec_w_size': wi124, 'spec_ol': wi125, 'add_welch': wi126, 'welch_w': wi127, 'welch_w_size': wi128, 'welch_ol': wi129, 'a_interval': wi1210, 'add_mu_c': wi1211, 'mu_index': wi1212 } moving_average_acc2 = wi.VBox([wi120]) spectrogram_acc2 = wi.VBox([wi122, wi123, wi124, wi125]) welch_acc2 = wi.VBox([wi126, wi127, wi128, wi129]) mu_c2 = wi.VBox([wi1211, wi1212]) acc12 = wi.Tab( children=[moving_average_acc2, spectrogram_acc2, welch_acc2, mu_c2]) acc12.set_title(0, 'Standard deviation') acc12.set_title(1, 'Spectrogram') acc12.set_title(2, 'Welch\'s periodogram') acc12.set_title(3, 'Motor unit force') ui12 = wi.VBox([wi1210, acc12]) l211 = wi.link((ui12.children[1].children[1].children[2], 'value'), (ui12.children[1].children[1].children[3], 'max')) l212 = wi.link((ui12.children[1].children[1].children[3], 'value'), (ui12.children[1].children[1].children[2], 'min')) l221 = wi.link((ui12.children[1].children[2].children[2], 'value'), (ui12.children[1].children[2].children[3], 'max')) l222 = wi.link((ui12.children[1].children[2].children[3], 'value'), (ui12.children[1].children[2].children[2], 'min')) return ui12, ws
def fitBySliders(geometryParams, xanes, exp): # normalize params geometryParamsMin = np.min(geometryParams.values, axis=0) geometryParamsMax = np.max(geometryParams.values, axis=0) geometryParams = 2 * (geometryParams - geometryParamsMin) / ( geometryParamsMax - geometryParamsMin) - 1 # machine learning estimator training estimator = makeQuadric(RidgeCV(alphas=[0.01, 0.1, 1, 10, 100])) estimator.fit(geometryParams.values, xanes.values) # need for smoothing by fdmnes xanesFolder = tempfile.mkdtemp(prefix='smooth_') e_names = xanes.columns xanes_energy = np.array( [float(e_names[i][2:]) for i in range(e_names.size)]) fig, ax = plt.subplots() ax2 = ax.twinx() fig.set_size_inches((16 * 0.6, 9 * 0.8)) def plotXanes(**params): geomArg = np.array([params[pName] for pName in geometryParams.columns ]).reshape([1, geometryParams.shape[1]]) geomArg = 2 * (geomArg - geometryParamsMin) / (geometryParamsMax - geometryParamsMin) - 1 # prediction absorbPrediction = estimator.predict(geomArg)[0] # smoothing xanesPrediction = utils.Xanes(xanes_energy, absorbPrediction, None, None) xanesPrediction.save(xanesFolder + '/out.txt', exp.defaultSmoothParams.fdmnesSmoothHeader) _, smoothedXanes = smoothLib.smooth_fdmnes( None, None, params['Gamma_hole'], params['Ecent'], params['Elarg'], params['Gamma_max'], params['Efermi'], xanesFolder) #plotting shift = params['shift'] exp_e = exp.xanes.energy exp_xanes = exp.xanes.absorb e_fdmnes = exp_e - shift absorbPredictionNormalized = utils.fit_arg_to_experiment( xanesPrediction.energy, exp_e, xanesPrediction.absorb, shift, lastValueNorm=True) smoothedPredictionNormalized = utils.fit_arg_to_experiment( xanesPrediction.energy, exp_e, smoothedXanes, shift, lastValueNorm=True) if params['notConvoluted']: ax.plot(e_fdmnes, absorbPredictionNormalized, label='initial') ax.clear() ax.plot(e_fdmnes, smoothedPredictionNormalized, label='convolution') ax.plot(e_fdmnes, exp_xanes, c='k', label="Experiment") if params['smoothWidth']: smoothWidth = smoothLib.YvesWidth(e_fdmnes, params['Gamma_hole'], params['Ecent'], params['Elarg'], params['Gamma_max'], params['Efermi']) ax2.clear() ax2.plot(e_fdmnes, smoothWidth, c='r', label='Smooth width') ax2.legend() ax.set_xlim([params['energyRange'][0], params['energyRange'][1]]) ax.set_ylim([0, np.max(exp_xanes) * 1.2]) ax.set_xlabel("Energy") ax.set_ylabel("Absorb") ax.legend() # plt.show() controls = [] o = 'vertical' for pName in exp.geometryParamRanges: p0 = exp.geometryParamRanges[pName][0] p1 = exp.geometryParamRanges[pName][1] controls.append( widgets.FloatSlider(description=pName, min=p0, max=p1, step=(p1 - p0) / 30, value=(p0 + p1) / 2, orientation=o)) shift = optimize.value(exp.defaultSmoothParams['fdmnes'], 'shift') controls.append( widgets.FloatSlider(description='shift', min=shift - 10.0, max=shift + 10.0, step=0.3, value=shift, orientation=o)) controls.append( widgets.FloatSlider(description='Gamma_hole', min=0.1, max=10, step=0.2, value=2, orientation=o)) controls.append( widgets.FloatSlider(description='Ecent', min=0, max=100, step=1, value=50, orientation=o)) controls.append( widgets.FloatSlider(description='Elarg', min=0, max=100, step=1, value=50, orientation=o)) controls.append( widgets.FloatSlider(description='Gamma_max', min=1, max=100, step=1, value=15, orientation=o)) controls.append( widgets.FloatSlider(description='Efermi', min=-30, max=30, step=1, value=0, orientation=o)) controls.append(widgets.Checkbox(description='smoothWidth', value=True)) controls.append(widgets.Checkbox(description='notConvoluted', value=True)) e0 = xanes_energy[0] e1 = xanes_energy[-1] controls.append( widgets.FloatRangeSlider(description='energyRange', min=e0, max=e1, step=(e1 - e0) / 30, value=[e0, e1], orientation='horizontal')) ui = widgets.HBox(tuple(controls)) ui.layout.flex_flow = 'row wrap' ui.layout.justify_content = 'space-between' ui.layout.align_items = 'flex-start' ui.layout.align_content = 'flex-start' controlsDict = {} for c in controls: controlsDict[c.description] = c out = widgets.interactive_output(plotXanes, controlsDict) # out.layout.min_height = '400px' display(ui, out)
def options(X): style = {'description_width': 'initial'} #general style settings #horizontal line widget HL = widgets.HTML( value= '<hr style="height:3px;border:none;color:#333;background-color:#333;" />' ) M_title = widgets.HTML(value='<h3>Select data type:</h3>') M_widge = widgets.RadioButtons( options=['Magnetisations', 'Lower branch subtracted'], value='Lower branch subtracted', style=style) ### Horizontal smoothing ### S_title = widgets.HTML(value='<h3>Set smoothing parameters:</h3>') #SC widgets Sc_widge = widgets.IntRangeSlider(value=[2, 8], min=2, max=10, step=1, description='Select $s_c$ range:', continuous_update=False, orientation='horizontal', readout=True, readout_format='.0f', style=style) Sb_widge = widgets.IntRangeSlider(value=[2, 8], min=2, max=10, step=1, description='Select $s_u$ range:', continuous_update=False, orientation='horizontal', readout=True, readout_format='.0f', style=style) lambda_widge = widgets.FloatRangeSlider( value=[0.0, 0.08], min=0, max=0.2, step=0.04, description='Select $\lambda$ range:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.2f', style=style) down_title = widgets.HTML(value='<h3>Specify downsampling:</h3>') down_widge = widgets.IntSlider(value=np.minimum(X['M'].size, 2000), min=100, max=X['M'].size, step=1, description='Number of points:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d', style=style) #display number of models to compare model_widge = widgets.interactive_output(variforc_array_size, { 'SC': Sc_widge, 'SB': Sb_widge, 'L': lambda_widge }) #combined widget DS = VBox([down_title, down_widge]) SC = VBox([ M_title, M_widge, HL, S_title, Sc_widge, Sb_widge, lambda_widge, model_widge ]) ### Setup Multiprocessing tab #################### X['ncore'] = 4 #header dask_title = widgets.HTML(value='<h3>DASK multiprocessing:</h3>') #selection widget dask_widge = widgets.IntSlider(value=X['ncore'], min=1, max=X['ncore'], step=1, description='Number of DASK workers:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='d', style=style) #final multiprocessing widget mpl_widge = VBox([dask_title, dask_widge]) ### CONSTRUCT TAB MENU ############# method_nest = widgets.Tab() method_nest.children = [SC, DS, mpl_widge] method_nest.set_title(0, 'MODEL ENSEMBLE') method_nest.set_title(1, 'DOWNSAMPLING') method_nest.set_title(2, 'PROCESSING') display(method_nest) ### SETUP OUTPUT #### X['Mtype'] = M_widge X['SC'] = Sc_widge X['SB'] = Sb_widge X['lambda'] = lambda_widge X['Ndown'] = down_widge X['workers'] = dask_widge return X