def modify_doc(doc): source = ColumnDataSource(dict(x=[1, 2], y=[1, 1], val=["a", "b"])) plot = Plot(plot_height=400, plot_width=400, x_range=Range1d(0, 1), y_range=Range1d(0, 1), min_border=0) plot.add_glyph(source, Circle(x='x', y='y', size=20)) plot.add_tools(CustomAction(callback=CustomJS(args=dict(s=source), code=RECORD("data", "s.data")))) group = RadioGroup(labels=LABELS, css_classes=["foo"]) def cb(active): source.data['val'] = [active, "b"] group.on_click(cb) doc.add_root(column(group, plot))
def __init__(self, image_views, disp_min=0, disp_max=1000, colormap="plasma"): """Initialize a colormapper. Args: image_views (ImageView): Associated streamvis image view instances. disp_min (int, optional): Initial minimal display value. Defaults to 0. disp_max (int, optional): Initial maximal display value. Defaults to 1000. colormap (str, optional): Initial colormap. Defaults to 'plasma'. """ lin_colormapper = LinearColorMapper( palette=cmap_dict[colormap], low=disp_min, high=disp_max ) log_colormapper = LogColorMapper(palette=cmap_dict[colormap], low=disp_min, high=disp_max) for image_view in image_views: image_view.image_glyph.color_mapper = lin_colormapper color_bar = ColorBar( color_mapper=lin_colormapper, location=(0, -5), orientation="horizontal", height=15, width=100, padding=5, ) self.color_bar = color_bar # ---- selector def select_callback(_attr, _old, new): if new in cmap_dict: lin_colormapper.palette = cmap_dict[new] log_colormapper.palette = cmap_dict[new] high_color.color = cmap_dict[new][-1] select = Select( title="Colormap:", value=colormap, options=list(cmap_dict.keys()), default_size=100 ) select.on_change("value", select_callback) self.select = select # ---- auto toggle button def auto_toggle_callback(state): if state: display_min_spinner.disabled = True display_max_spinner.disabled = True else: display_min_spinner.disabled = False display_max_spinner.disabled = False auto_toggle = CheckboxGroup(labels=["Auto Colormap Range"], default_size=145) auto_toggle.on_click(auto_toggle_callback) self.auto_toggle = auto_toggle # ---- scale radiobutton group def scale_radiobuttongroup_callback(selection): if selection == 0: # Linear for image_view in image_views: image_view.image_glyph.color_mapper = lin_colormapper color_bar.color_mapper = lin_colormapper color_bar.ticker = BasicTicker() else: # Logarithmic if self.disp_min > 0: for image_view in image_views: image_view.image_glyph.color_mapper = log_colormapper color_bar.color_mapper = log_colormapper color_bar.ticker = LogTicker() else: scale_radiobuttongroup.active = 0 scale_radiobuttongroup = RadioGroup( labels=["Linear", "Logarithmic"], active=0, default_size=145 ) scale_radiobuttongroup.on_click(scale_radiobuttongroup_callback) self.scale_radiobuttongroup = scale_radiobuttongroup # ---- display max value def display_max_spinner_callback(_attr, _old_value, new_value): self.display_min_spinner.high = new_value - STEP if new_value <= 0: scale_radiobuttongroup.active = 0 lin_colormapper.high = new_value log_colormapper.high = new_value display_max_spinner = Spinner( title="Max Display Value:", low=disp_min + STEP, value=disp_max, step=STEP, disabled=bool(auto_toggle.active), default_size=145, ) display_max_spinner.on_change("value", display_max_spinner_callback) self.display_max_spinner = display_max_spinner # ---- display min value def display_min_spinner_callback(_attr, _old_value, new_value): self.display_max_spinner.low = new_value + STEP if new_value <= 0: scale_radiobuttongroup.active = 0 lin_colormapper.low = new_value log_colormapper.low = new_value display_min_spinner = Spinner( title="Min Display Value:", high=disp_max - STEP, value=disp_min, step=STEP, disabled=bool(auto_toggle.active), default_size=145, ) display_min_spinner.on_change("value", display_min_spinner_callback) self.display_min_spinner = display_min_spinner # ---- high color def high_color_callback(_attr, _old_value, new_value): lin_colormapper.high_color = new_value log_colormapper.high_color = new_value high_color = ColorPicker( title="High Color:", color=cmap_dict[colormap][-1], default_size=90 ) high_color.on_change("color", high_color_callback) self.high_color = high_color # ---- mask color def mask_color_callback(_attr, _old_value, new_value): lin_colormapper.nan_color = new_value log_colormapper.nan_color = new_value mask_color = ColorPicker(title="Mask Color:", color="gray", default_size=90) mask_color.on_change("color", mask_color_callback) self.mask_color = mask_color
data161subset = data161.iloc[startPt:startPt+slot:space,:] dataSource.data.update(ColumnDataSource(data161subset).data) slider.on_change('value', callback) # Radio buttons to choose time scale radioLabels = ['day','week','month'] radio = RadioGroup(labels=radioLabels,active=1) def radioCallback(active): timerange = radioLabels[active] print(timerange) global slot global space tooltips,slot, space = updateToolTips(timerange) data161subset = data161.iloc[startPt:startPt+slot:space,:] dataSource.data.update(ColumnDataSource(data161subset).data) radio.on_click(radioCallback) # Buttons to choose which sources are shown checkbuttons = CheckboxButtonGroup(labels=zlist, active=[0,1,2]) def checkboxCallback(active): global showcols showcols=[] print(active) for activeItem in active: showcols.append(' '+zlist[activeItem].lower()) print(showcols) for colRef,line in enumerate(ylist,1): if line in showcols: dictOfLines[line].visible = True else: dictOfLines[line].visible = False
class BokehSPE(Tool): name = "BokehSPE" description = "Interactively explore the steps in obtaining and fitting " \ "SPE spectrum" aliases = Dict( dict( r='EventFileReaderFactory.reader', f='EventFileReaderFactory.input_path', max_events='EventFileReaderFactory.max_events', ped='CameraR1CalibratorFactory.pedestal_path', tf='CameraR1CalibratorFactory.tf_path', pe='CameraR1CalibratorFactory.pe_path', fitter='ChargeFitterFactory.fitter', )) classes = List([ EventFileReaderFactory, CameraR1CalibratorFactory, ChargeFitterFactory, ]) def __init__(self, **kwargs): super().__init__(**kwargs) self._event = None self._event_index = None self._event_id = None self._active_pixel = 0 self.w_event_index = None self.w_goto_event_index = None self.w_hoa = None self.w_fitspectrum = None self.w_fitcamera = None self.layout = None self.reader = None self.r1 = None self.dl0 = None self.dl1 = None self.dl1_height = None self.area = None self.height = None self.n_events = None self.n_pixels = None self.n_samples = None self.cleaner = None self.extractor = None self.extractor_height = None self.dead = None self.fitter = None self.neighbours2d = None self.stage_names = None self.p_camera_area = None self.p_camera_fit_gain = None self.p_camera_fit_brightness = None self.p_fitter = None self.p_stage_viewer = None self.p_fit_viewer = None self.p_fit_table = None def setup(self): self.log_format = "%(levelname)s: %(message)s [%(name)s.%(funcName)s]" kwargs = dict(config=self.config, tool=self) reader_factory = EventFileReaderFactory(**kwargs) reader_class = reader_factory.get_class() self.reader = reader_class(**kwargs) r1_factory = CameraR1CalibratorFactory(origin=self.reader.origin, **kwargs) r1_class = r1_factory.get_class() self.r1 = r1_class(**kwargs) self.dl0 = CameraDL0Reducer(**kwargs) self.cleaner = CHECMWaveformCleanerAverage(**kwargs) self.extractor = AverageWfPeakIntegrator(**kwargs) self.extractor_height = SimpleIntegrator(window_shift=0, window_width=1, **kwargs) self.dl1 = CameraDL1Calibrator(extractor=self.extractor, cleaner=self.cleaner, **kwargs) self.dl1_height = CameraDL1Calibrator(extractor=self.extractor_height, cleaner=self.cleaner, **kwargs) self.dead = Dead() fitter_factory = ChargeFitterFactory(**kwargs) fitter_class = fitter_factory.get_class() self.fitter = fitter_class(**kwargs) self.n_events = self.reader.num_events first_event = self.reader.get_event(0) self.n_pixels = first_event.inst.num_pixels[0] self.n_samples = first_event.r0.tel[0].num_samples geom = CameraGeometry.guess(*first_event.inst.pixel_pos[0], first_event.inst.optical_foclen[0]) self.neighbours2d = get_neighbours_2d(geom.pix_x, geom.pix_y) # Get stage names self.stage_names = [ '0: raw', '1: baseline_sub', '2: no_pulse', '3: smooth_baseline', '4: smooth_wf', '5: cleaned' ] # Init Plots self.p_camera_area = Camera(self, self.neighbours2d, "Area", geom) self.p_camera_fit_gain = Camera(self, self.neighbours2d, "Gain", geom) self.p_camera_fit_brightness = Camera(self, self.neighbours2d, "Brightness", geom) self.p_fitter = FitterWidget(fitter=self.fitter, **kwargs) self.p_stage_viewer = StageViewer(**kwargs) self.p_fit_viewer = FitViewer(**kwargs) self.p_fit_table = FitTable(**kwargs) def start(self): # Prepare storage array self.area = np.zeros((self.n_events, self.n_pixels)) self.height = np.zeros((self.n_events, self.n_pixels)) source = self.reader.read() desc = "Looping through file" for event in tqdm(source, total=self.n_events, desc=desc): index = event.count self.r1.calibrate(event) self.dl0.reduce(event) self.dl1.calibrate(event) peak_area = np.copy(event.dl1.tel[0].image) self.dl1_height.calibrate(event) peak_height = np.copy(event.dl1.tel[0].image) self.area[index] = peak_area self.height[index] = peak_height # Setup Plots self.p_camera_area.enable_pixel_picker() self.p_camera_area.add_colorbar() self.p_camera_fit_gain.enable_pixel_picker() self.p_camera_fit_gain.add_colorbar() self.p_camera_fit_brightness.enable_pixel_picker() self.p_camera_fit_brightness.add_colorbar() self.p_fitter.create() self.p_stage_viewer.create(self.neighbours2d, self.stage_names) self.p_fit_viewer.create(self.p_fitter.fitter.subfit_labels) self.p_fit_table.create() # Setup widgets self.create_event_index_widget() self.create_goto_event_index_widget() self.event_index = 0 self.create_hoa_widget() self.create_fitspectrum_widget() self.create_fitcamera_widget() # Get bokeh layouts l_camera_area = self.p_camera_area.layout l_camera_fit_gain = self.p_camera_fit_gain.layout l_camera_fit_brightness = self.p_camera_fit_brightness.layout l_fitter = self.p_fitter.layout l_stage_viewer = self.p_stage_viewer.layout l_fit_viewer = self.p_fit_viewer.layout l_fit_table = self.p_fit_table.layout # Setup layout self.layout = layout([ [self.w_hoa, self.w_fitspectrum, self.w_fitcamera], [l_camera_fit_brightness, l_fit_viewer, l_fitter], [l_camera_fit_gain, l_fit_table], [l_camera_area, self.w_goto_event_index, self.w_event_index], [Div(text="Stage Viewer")], [l_stage_viewer], ]) def finish(self): curdoc().add_root(self.layout) curdoc().title = "Event Viewer" def fit_spectrum(self, pix): if self.w_hoa.active == 0: spectrum = self.area else: spectrum = self.height success = self.p_fitter.fit(spectrum[:, pix]) if not success: self.log.warning("Pixel {} couldn't be fit".format(pix)) return success def fit_camera(self): gain = np.ma.zeros(self.n_pixels) gain.mask = np.zeros(gain.shape, dtype=np.bool) brightness = np.ma.zeros(self.n_pixels) brightness.mask = np.zeros(gain.shape, dtype=np.bool) fitter = self.p_fitter.fitter.fitter_type if fitter == 'spe': coeff = 'lambda_' elif fitter == 'bright': coeff = 'mean' else: self.log.error("No case for fitter type: {}".format(fitter)) raise ValueError desc = "Fitting pixels" for pix in trange(self.n_pixels, desc=desc): if not self.fit_spectrum(pix): gain.mask[pix] = True continue if fitter == 'spe': gain[pix] = self.p_fitter.fitter.coeff['spe'] brightness[pix] = self.p_fitter.fitter.coeff[coeff] gain = np.ma.masked_where(np.isnan(gain), gain) gain = self.dead.mask1d(gain) brightness = np.ma.masked_where(np.isnan(brightness), brightness) brightness = self.dead.mask1d(brightness) self.p_camera_fit_gain.image = gain self.p_camera_fit_brightness.image = brightness @property def event(self): return self._event @event.setter def event(self, val): self._event = val self.r1.calibrate(val) self.dl0.reduce(val) self.dl1.calibrate(val) peak_area = val.dl1.tel[0].image self._event_index = val.count self._event_id = val.r0.event_id self.update_event_index_widget() stages = self.dl1.cleaner.stages pulse_window = self.dl1.cleaner.stages['window'][0] int_window = val.dl1.tel[0].extracted_samples[0] self.p_camera_area.image = peak_area self.p_stage_viewer.update_stages(np.arange(self.n_samples), stages, pulse_window, int_window) @property def event_index(self): return self._event_index @event_index.setter def event_index(self, val): self._event_index = val self.event = self.reader.get_event(val, False) @property def active_pixel(self): return self._active_pixel @active_pixel.setter def active_pixel(self, val): if not self._active_pixel == val: self._active_pixel = val self.fit_spectrum(val) self.p_camera_area.active_pixel = val self.p_camera_fit_gain.active_pixel = val self.p_camera_fit_brightness.active_pixel = val self.p_stage_viewer.active_pixel = val self.p_fit_viewer.update(self.p_fitter.fitter) self.p_fit_table.update(self.p_fitter.fitter) def create_event_index_widget(self): self.w_event_index = TextInput(title="Event Index:", value='') def update_event_index_widget(self): if self.w_event_index: self.w_event_index.value = str(self.event_index) def create_goto_event_index_widget(self): self.w_goto_event_index = Button(label="GOTO Index", width=100) self.w_goto_event_index.on_click(self.on_goto_event_index_widget_click) def on_goto_event_index_widget_click(self): self.event_index = int(self.w_event_index.value) def on_event_index_widget_change(self, attr, old, new): if self.event_index != int(self.w_event_index.value): self.event_index = int(self.w_event_index.value) def create_hoa_widget(self): self.w_hoa = RadioGroup(labels=['area', 'height'], active=0) self.w_hoa.on_click(self.on_hoa_widget_select) def on_hoa_widget_select(self, active): self.fit_spectrum(self.active_pixel) self.p_fit_viewer.update(self.p_fitter.fitter) self.p_fit_table.update(self.p_fitter.fitter) def create_fitspectrum_widget(self): self.w_fitspectrum = Button(label='Fit Spectrum') self.w_fitspectrum.on_click(self.on_fitspectrum_widget_select) def on_fitspectrum_widget_select(self): t = time() self.fit_spectrum(self.active_pixel) self.log.info("Fit took {} seconds".format(time() - t)) self.p_fit_viewer.update(self.p_fitter.fitter) self.p_fit_table.update(self.p_fitter.fitter) def create_fitcamera_widget(self): self.w_fitcamera = Button(label='Fit Camera') self.w_fitcamera.on_click(self.on_fitcamera_widget_select) def on_fitcamera_widget_select(self): self.fit_camera() self.fit_spectrum(self.active_pixel) self.p_fit_viewer.update(self.p_fitter.fitter) self.p_fit_table.update(self.p_fitter.fitter)