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 = RadioButtonGroup(labels=LABELS, css_classes=["foo"]) def cb(active): source.data['val'] = [active, "b"] group.on_click(cb) doc.add_root(column(group, plot))
class Figure: def __init__(self, X, Y, patch_xs, patch_ys): self.workspace = figure(x_range=[x_low-2,x_high+2], y_range=[0,.6], toolbar_location=None) self.plot = self.workspace.line(x=X, y=Y, line_width=4) self.point = self.workspace.circle(x=[0], y=[-1], size=10, color="red") self.fx = self.workspace.circle(x=[0], y=[-1], size=10, color="red") self.sample_y = self.workspace.circle(x=[0], y=[-1], size=10, color="black") self.vertical = self.workspace.line(x=[0,0], y=[0,0], color="red", line_width=2) self.horizontal = self.workspace.line(x=[0,0], y=[0,0], color="red", line_width=2) self.slice = self.workspace.line(x=[0,0], y=[0,0], color="black", line_width=4) self.patches = self.workspace.patches(patch_xs, patch_ys, alpha=.3, line_width=2) self.filler1 = PreText(text='', width=200, height=250) self.filler2 = PreText(text='', width=200, height=250) ## for choosing update function self.radio = RadioButtonGroup( labels=['Stepping out', 'Doubling'], active=0) self.radio.on_click(self.radio_handler) ## for progressing demo self.button = Button(label="Next") self.button.on_click(self.callback) curdoc().add_root(row(column(self.filler1, self.button), self.workspace, column(self.filler2, self.radio))) def radio_handler(self, new): sampler.change_update_fn(new) def refresh(self, X, Y, curr_x, fx, curr_y, horizontal, slice_endpoints, patch_xs, patch_ys, mode): self.point.data_source.data = {'x': [curr_x], 'y': [0]} self.fx.data_source.data = {'x': [curr_x], 'y': [fx]} self.sample_y.data_source.data = {'x': [curr_x], 'y': [curr_y]} self.vertical.data_source.data = {'x': [curr_x, curr_x], 'y': [0, fx]} self.horizontal.data_source.data = {'x': [-100, 100], 'y': [horizontal, horizontal]} self.slice.data_source.data = {'x': slice_endpoints, 'y': [curr_y, curr_y]} self.patches.data_source.data = {'xs': patch_xs, 'ys': patch_ys} def callback(self): sampler.next_step()
class ConnectionButtons: def __init__(self, secondary): self.secondary = secondary self.handler = server_thread.SERVER_HANDLER self.b_connect = RadioButtonGroup(labels=['DISCONNECT', 'CONNECT'], active=0) self.b_connect.on_click(self.connect) self.layout = self.b_connect def connect(self, index): if self.b_connect.active == 0: self.handler.disconnect() elif self.b_connect.active == 1: self.handler.connect() self.secondary.update_time_input()
def create(): config = pyzebra.AnatricConfig() def _load_config_file(file): config.load_from_file(file) logfile_textinput.value = config.logfile logfile_verbosity_select.value = config.logfile_verbosity filelist_type.value = config.filelist_type filelist_format_textinput.value = config.filelist_format filelist_datapath_textinput.value = config.filelist_datapath filelist_ranges_textareainput.value = "\n".join( map(str, config.filelist_ranges)) crystal_sample_textinput.value = config.crystal_sample lambda_textinput.value = config.crystal_lambda zeroOM_textinput.value = config.crystal_zeroOM zeroSTT_textinput.value = config.crystal_zeroSTT zeroCHI_textinput.value = config.crystal_zeroCHI ub_textareainput.value = config.crystal_UB dataFactory_implementation_select.value = config.dataFactory_implementation dataFactory_dist1_textinput.value = config.dataFactory_dist1 reflectionPrinter_format_select.value = config.reflectionPrinter_format set_active_widgets(config.algorithm) if config.algorithm == "adaptivemaxcog": threshold_textinput.value = config.threshold shell_textinput.value = config.shell steepness_textinput.value = config.steepness duplicateDistance_textinput.value = config.duplicateDistance maxequal_textinput.value = config.maxequal aps_window_textinput.value = str( tuple(map(int, config.aps_window.values()))) elif config.algorithm == "adaptivedynamic": adm_window_textinput.value = str( tuple(map(int, config.adm_window.values()))) border_textinput.value = str( tuple(map(int, config.border.values()))) minWindow_textinput.value = str( tuple(map(int, config.minWindow.values()))) reflectionFile_textinput.value = config.reflectionFile targetMonitor_textinput.value = config.targetMonitor smoothSize_textinput.value = config.smoothSize loop_textinput.value = config.loop minPeakCount_textinput.value = config.minPeakCount displacementCurve_textinput.value = "\n".join( map(str, config.displacementCurve)) else: raise ValueError("Unknown processing mode.") def set_active_widgets(implementation): if implementation == "adaptivemaxcog": mode_radio_button_group.active = 0 disable_adaptivemaxcog = False disable_adaptivedynamic = True elif implementation == "adaptivedynamic": mode_radio_button_group.active = 1 disable_adaptivemaxcog = True disable_adaptivedynamic = False else: raise ValueError( "Implementation can be either 'adaptivemaxcog' or 'adaptivedynamic'" ) threshold_textinput.disabled = disable_adaptivemaxcog shell_textinput.disabled = disable_adaptivemaxcog steepness_textinput.disabled = disable_adaptivemaxcog duplicateDistance_textinput.disabled = disable_adaptivemaxcog maxequal_textinput.disabled = disable_adaptivemaxcog aps_window_textinput.disabled = disable_adaptivemaxcog adm_window_textinput.disabled = disable_adaptivedynamic border_textinput.disabled = disable_adaptivedynamic minWindow_textinput.disabled = disable_adaptivedynamic reflectionFile_textinput.disabled = disable_adaptivedynamic targetMonitor_textinput.disabled = disable_adaptivedynamic smoothSize_textinput.disabled = disable_adaptivedynamic loop_textinput.disabled = disable_adaptivedynamic minPeakCount_textinput.disabled = disable_adaptivedynamic displacementCurve_textinput.disabled = disable_adaptivedynamic upload_div = Div(text="Open XML configuration file:") def upload_button_callback(_attr, _old, new): with io.BytesIO(base64.b64decode(new)) as file: _load_config_file(file) upload_button = FileInput(accept=".xml") upload_button.on_change("value", upload_button_callback) # General parameters # ---- logfile def logfile_textinput_callback(_attr, _old, new): config.logfile = new logfile_textinput = TextInput(title="Logfile:", value="logfile.log", width=520) logfile_textinput.on_change("value", logfile_textinput_callback) def logfile_verbosity_select_callback(_attr, _old, new): config.logfile_verbosity = new logfile_verbosity_select = Select(title="verbosity:", options=["0", "5", "10", "15", "30"], width=70) logfile_verbosity_select.on_change("value", logfile_verbosity_select_callback) # ---- FileList def filelist_type_callback(_attr, _old, new): config.filelist_type = new filelist_type = Select(title="File List:", options=["TRICS", "SINQ"], width=100) filelist_type.on_change("value", filelist_type_callback) def filelist_format_textinput_callback(_attr, _old, new): config.filelist_format = new filelist_format_textinput = TextInput(title="format:", width=490) filelist_format_textinput.on_change("value", filelist_format_textinput_callback) def filelist_datapath_textinput_callback(_attr, _old, new): config.filelist_datapath = new filelist_datapath_textinput = TextInput(title="datapath:") filelist_datapath_textinput.on_change( "value", filelist_datapath_textinput_callback) def filelist_ranges_textareainput_callback(_attr, _old, new): ranges = [] for line in new.splitlines(): ranges.append(re.findall(r"\b\d+\b", line)) config.filelist_ranges = ranges filelist_ranges_textareainput = TextAreaInput(title="ranges:", height=100) filelist_ranges_textareainput.on_change( "value", filelist_ranges_textareainput_callback) # ---- crystal def crystal_sample_textinput_callback(_attr, _old, new): config.crystal_sample = new crystal_sample_textinput = TextInput(title="Sample Name:") crystal_sample_textinput.on_change("value", crystal_sample_textinput_callback) def lambda_textinput_callback(_attr, _old, new): config.crystal_lambda = new lambda_textinput = TextInput(title="lambda:", width=140) lambda_textinput.on_change("value", lambda_textinput_callback) def ub_textareainput_callback(_attr, _old, new): config.crystal_UB = new ub_textareainput = TextAreaInput(title="UB matrix:", height=100) ub_textareainput.on_change("value", ub_textareainput_callback) def zeroOM_textinput_callback(_attr, _old, new): config.crystal_zeroOM = new zeroOM_textinput = TextInput(title="zeroOM:", width=140) zeroOM_textinput.on_change("value", zeroOM_textinput_callback) def zeroSTT_textinput_callback(_attr, _old, new): config.crystal_zeroSTT = new zeroSTT_textinput = TextInput(title="zeroSTT:", width=140) zeroSTT_textinput.on_change("value", zeroSTT_textinput_callback) def zeroCHI_textinput_callback(_attr, _old, new): config.crystal_zeroCHI = new zeroCHI_textinput = TextInput(title="zeroCHI:", width=140) zeroCHI_textinput.on_change("value", zeroCHI_textinput_callback) # ---- DataFactory def dataFactory_implementation_select_callback(_attr, _old, new): config.dataFactory_implementation = new dataFactory_implementation_select = Select( title="DataFactory implementation:", options=DATA_FACTORY_IMPLEMENTATION, width=300, ) dataFactory_implementation_select.on_change( "value", dataFactory_implementation_select_callback) def dataFactory_dist1_textinput_callback(_attr, _old, new): config.dataFactory_dist1 = new dataFactory_dist1_textinput = TextInput(title="dist1:", width=290) dataFactory_dist1_textinput.on_change( "value", dataFactory_dist1_textinput_callback) # ---- BackgroundProcessor # ---- DetectorEfficency # ---- ReflectionPrinter def reflectionPrinter_format_select_callback(_attr, _old, new): config.reflectionPrinter_format = new reflectionPrinter_format_select = Select( title="ReflectionPrinter format:", options=REFLECTION_PRINTER_FORMATS, width=300, ) reflectionPrinter_format_select.on_change( "value", reflectionPrinter_format_select_callback) # Adaptive Peak Detection (adaptivemaxcog) # ---- threshold def threshold_textinput_callback(_attr, _old, new): config.threshold = new threshold_textinput = TextInput(title="Threshold:") threshold_textinput.on_change("value", threshold_textinput_callback) # ---- shell def shell_textinput_callback(_attr, _old, new): config.shell = new shell_textinput = TextInput(title="Shell:") shell_textinput.on_change("value", shell_textinput_callback) # ---- steepness def steepness_textinput_callback(_attr, _old, new): config.steepness = new steepness_textinput = TextInput(title="Steepness:") steepness_textinput.on_change("value", steepness_textinput_callback) # ---- duplicateDistance def duplicateDistance_textinput_callback(_attr, _old, new): config.duplicateDistance = new duplicateDistance_textinput = TextInput(title="Duplicate Distance:") duplicateDistance_textinput.on_change( "value", duplicateDistance_textinput_callback) # ---- maxequal def maxequal_textinput_callback(_attr, _old, new): config.maxequal = new maxequal_textinput = TextInput(title="Max Equal:") maxequal_textinput.on_change("value", maxequal_textinput_callback) # ---- window def aps_window_textinput_callback(_attr, _old, new): config.aps_window = dict( zip(("x", "y", "z"), re.findall(r"\b\d+\b", new))) aps_window_textinput = TextInput(title="Window (x, y, z):") aps_window_textinput.on_change("value", aps_window_textinput_callback) # Adaptive Dynamic Mask Integration (adaptivedynamic) # ---- window def adm_window_textinput_callback(_attr, _old, new): config.adm_window = dict( zip(("x", "y", "z"), re.findall(r"\b\d+\b", new))) adm_window_textinput = TextInput(title="Window (x, y, z):") adm_window_textinput.on_change("value", adm_window_textinput_callback) # ---- border def border_textinput_callback(_attr, _old, new): config.border = dict(zip(("x", "y", "z"), re.findall(r"\b\d+\b", new))) border_textinput = TextInput(title="Border (x, y, z):") border_textinput.on_change("value", border_textinput_callback) # ---- minWindow def minWindow_textinput_callback(_attr, _old, new): config.minWindow = dict( zip(("x", "y", "z"), re.findall(r"\b\d+\b", new))) minWindow_textinput = TextInput(title="Min Window (x, y, z):") minWindow_textinput.on_change("value", minWindow_textinput_callback) # ---- reflectionFile def reflectionFile_textinput_callback(_attr, _old, new): config.reflectionFile = new reflectionFile_textinput = TextInput(title="Reflection File:") reflectionFile_textinput.on_change("value", reflectionFile_textinput_callback) # ---- targetMonitor def targetMonitor_textinput_callback(_attr, _old, new): config.targetMonitor = new targetMonitor_textinput = TextInput(title="Target Monitor:") targetMonitor_textinput.on_change("value", targetMonitor_textinput_callback) # ---- smoothSize def smoothSize_textinput_callback(_attr, _old, new): config.smoothSize = new smoothSize_textinput = TextInput(title="Smooth Size:") smoothSize_textinput.on_change("value", smoothSize_textinput_callback) # ---- loop def loop_textinput_callback(_attr, _old, new): config.loop = new loop_textinput = TextInput(title="Loop:") loop_textinput.on_change("value", loop_textinput_callback) # ---- minPeakCount def minPeakCount_textinput_callback(_attr, _old, new): config.minPeakCount = new minPeakCount_textinput = TextInput(title="Min Peak Count:") minPeakCount_textinput.on_change("value", minPeakCount_textinput_callback) # ---- displacementCurve def displacementCurve_textinput_callback(_attr, _old, new): maps = [] for line in new.splitlines(): maps.append(re.findall(r"\d+(?:\.\d+)?", line)) config.displacementCurve = maps displacementCurve_textinput = TextAreaInput( title="Displacement Curve (twotheta, x, y):", height=100) displacementCurve_textinput.on_change( "value", displacementCurve_textinput_callback) def mode_radio_button_group_callback(active): if active == 0: config.algorithm = "adaptivemaxcog" set_active_widgets("adaptivemaxcog") else: config.algorithm = "adaptivedynamic" set_active_widgets("adaptivedynamic") mode_radio_button_group = RadioButtonGroup( labels=["Adaptive Peak Detection", "Adaptive Dynamic Integration"], active=0) mode_radio_button_group.on_click(mode_radio_button_group_callback) set_active_widgets("adaptivemaxcog") def process_button_callback(): with tempfile.TemporaryDirectory() as temp_dir: temp_file = temp_dir + "/temp.xml" config.save_as(temp_file) pyzebra.anatric(temp_file) with open(config.logfile) as f_log: output_log.value = f_log.read() process_button = Button(label="Process", button_type="primary") process_button.on_click(process_button_callback) output_log = TextAreaInput(title="Logfile output:", height=700, disabled=True) output_config = TextAreaInput(title="Current config:", height=700, width=400, disabled=True) tab_layout = row( column( upload_div, upload_button, row(logfile_textinput, logfile_verbosity_select), row(filelist_type, filelist_format_textinput), filelist_datapath_textinput, filelist_ranges_textareainput, crystal_sample_textinput, row(lambda_textinput, zeroOM_textinput, zeroSTT_textinput, zeroCHI_textinput), ub_textareainput, row(dataFactory_implementation_select, dataFactory_dist1_textinput), reflectionPrinter_format_select, process_button, ), column( mode_radio_button_group, row( column( threshold_textinput, shell_textinput, steepness_textinput, duplicateDistance_textinput, maxequal_textinput, aps_window_textinput, ), column( adm_window_textinput, border_textinput, minWindow_textinput, reflectionFile_textinput, targetMonitor_textinput, smoothSize_textinput, loop_textinput, minPeakCount_textinput, displacementCurve_textinput, ), ), ), output_config, output_log, ) async def update_config(): config.save_as("debug.xml") with open("debug.xml") as f_config: output_config.value = f_config.read() curdoc().add_periodic_callback(update_config, 1000) return Panel(child=tab_layout, title="Anatric")
def __init__(self, n_nodes): self.i = 0 kps = [crypto_sign_keypair() for _ in range(n_nodes)] stake = {kp[0]: 1 for kp in kps} network = {} self.nodes = [Node(kp, network, n_nodes, stake) for kp in kps] for n in self.nodes: network[n.pk] = n.ask_sync self.ids = {kp[0]: i for i, kp in enumerate(kps)} self.main_its = [n.main() for n in self.nodes] for m in self.main_its: next(m) def toggle(): if play.label == '► Play': play.label = '❚❚ Pause' curdoc().add_periodic_callback(self.animate, 50) else: play.label = '► Play' curdoc().remove_periodic_callback(self.animate) play = Button(label='► Play', width=60) play.on_click(toggle) def sel_node(new): self.active = new node = self.nodes[new] self.tbd = {} self.tr_src.data, self.links_src.data = self.extract_data( node, bfs((node.head, ), lambda u: node.hg[u].p), 0) for u, j in tuple(self.tbd.items()): self.tr_src.data['line_alpha'][j] = 1 if node.famous.get( u) else 0 if u in node.idx: self.tr_src.data['round_color'][j] = idx_color(node.idx[u]) self.tr_src.data['idx'][j] = node.idx.get(u) if u in node.idx and u in node.famous: del self.tbd[u] print('updated') self.tr_src.trigger('data', None, self.tr_src.data) selector = RadioButtonGroup( labels=['Node %i' % i for i in range(n_nodes)], active=0, name='Node to inspect') selector.on_click(sel_node) plot = figure( plot_height=700, plot_width=900, y_range=(0, 30), tools=[ PanTool(), HoverTool(tooltips=[('round', '@round'), ( 'hash', '@hash'), ('timestamp', '@time'), ('payload', '@payload'), ('number', '@idx')]) ]) plot.xgrid.grid_line_color = None plot.xaxis.minor_tick_line_color = None plot.ygrid.grid_line_color = None plot.yaxis.minor_tick_line_color = None self.links_src = ColumnDataSource(data={ 'x0': [], 'y0': [], 'x1': [], 'y1': [], 'width': [] }) #self.links_rend = plot.add_layout( # Arrow(end=NormalHead(fill_color='black'), x_start='x0', y_start='y0', x_end='x1', # y_end='y1', source=self.links_src)) self.links_rend = plot.segment(color='#777777', x0='x0', y0='y0', x1='x1', y1='y1', source=self.links_src, line_width='width') self.tr_src = ColumnDataSource( data={ 'x': [], 'y': [], 'round_color': [], 'idx': [], 'line_alpha': [], 'round': [], 'hash': [], 'payload': [], 'time': [] }) self.tr_rend = plot.circle(x='x', y='y', size=20, color='round_color', line_alpha='line_alpha', source=self.tr_src, line_width=5) sel_node(0) curdoc().add_root( row([widgetbox(play, selector, width=300), plot], sizing_mode='fixed'))
class TrimerFigure: order_functions: Dict[str, Any] = { "None": None, "Orient": create_orient_ordering(threshold=0.75), "Num Neighs": create_neigh_ordering(neighbours=6), } controls_width = 400 _frame = None plot = None _temperatures = None _pressures = None _crystals = None _iter_index = None _callback = None def __init__(self, doc, directory: Path = None, models=None) -> None: self._doc = doc self._trajectory = [None] if directory is None: directory = Path.cwd() self._source = ColumnDataSource({ "x": [], "y": [], "orientation": [], "colour": [], "radius": [] }) if models is not None: if not isinstance(models, (list, tuple)): raise ValueError( "The argument models has to have type list or tuple") logger.debug("Found additional models: %s", models) for model in models: model = Path(model) self.order_functions[model.stem] = create_ml_ordering(model) self.directory = directory self.initialise_directory() self._filename_div = Div(text="", width=self.controls_width) self.initialise_trajectory_interface() self.update_current_trajectory(None, None, None) self._playing = False # Initialise user interface self.initialise_media_interface() self.initialise_doc() def initialise_directory(self) -> None: self.variable_selection = parse_directory(self.directory, glob="dump*.gsd") logger.debug("Pressures present: %s", self.variable_selection.keys()) self._pressures = sorted(list(self.variable_selection.keys())) self._pressure_button = RadioButtonGroup( name="Pressure ", labels=self._pressures, active=0, width=self.controls_width, ) self._pressure_button.on_change("active", self.update_temperature_button) pressure = self._pressures[self._pressure_button.active] self._temperatures = sorted( list(self.variable_selection[pressure].keys())) self._temperature_button = Select( name="Temperature", options=self._temperatures, value=self._temperatures[0], width=self.controls_width, ) self._temperature_button.on_change("value", self.update_crystal_button) temperature = self._temperature_button.value self._crystals = sorted( list(self.variable_selection[pressure][temperature].keys())) self._crystal_button = RadioButtonGroup(name="Crystal", labels=self._crystals, active=0, width=self.controls_width) self._crystal_button.on_change("active", self.update_index_button) crystal = self._crystals[self._crystal_button.active] self._iter_index = sorted( list(self.variable_selection[pressure][temperature] [crystal].keys())) self._iter_index_button = Select( name="Iteration Index", options=self._iter_index, value=self._iter_index[0], width=self.controls_width, ) self._iter_index_button.on_change("value", self.update_current_trajectory) @property def pressure(self) -> Optional[str]: if self._pressures is None: return None return self._pressures[self._pressure_button.active] @property def temperature(self) -> Optional[str]: if self._temperatures is None: return None return self._temperature_button.value @property def crystal(self) -> Optional[str]: logger.debug("Current crystal %s from %s", self._crystal_button.active, self._crystals) if self._crystals is None: return None return self._crystals[self._crystal_button.active] @property def iter_index(self) -> Optional[str]: logger.debug("Current index %s from %s", self._iter_index_button.value, self._iter_index) return self._iter_index_button.value def update_temperature_button(self, attr, old, new): self._temperatures = sorted( list(self.variable_selection[self.pressure].keys())) self._temperature_button.options = self._temperatures self._temperature_button.value = self._temperatures[0] self.update_crystal_button(None, None, None) def update_crystal_button(self, attr, old, new): self._crystals = sorted( list(self.variable_selection[self.pressure][ self.temperature].keys())) self._crystal_button.labels = self._crystals self._crystal_button.active = 0 self.update_index_button(None, None, None) def update_index_button(self, attr, old, new): self._iter_index = sorted( list(self.variable_selection[self.pressure][self.temperature][ self.crystal].keys())) self._iter_index_button.options = self._iter_index self._iter_index_button.value = self._iter_index[0] self.update_current_trajectory(None, None, None) def create_files_interface(self) -> None: directory_name = Div( text=f"<b>Current Directory:</b><br/>{self.directory}", width=self.controls_width, ) self._filename_div = Div(text="", width=self.controls_width) current_file = self.get_selected_file() if current_file is not None: self._filename_div.text = f"<b>Current File:</b><br/>{current_file.name}" file_selection = column( directory_name, self._filename_div, Div(text="<b>Pressure:</b>"), self._pressure_button, Div(text="<b>Temperature:</b>"), self._temperature_button, Div(text="<b>Crystal Structure:</b>"), self._crystal_button, Div(text="<b>Iteration Index:</b>"), self._iter_index_button, ) return file_selection def get_selected_file(self) -> Optional[Path]: if self.pressure is None: return None if self.temperature is None: return None return self.variable_selection[self.pressure][self.temperature][ self.crystal][self.iter_index] def update_frame(self, attr, old, new) -> None: self._frame = HoomdFrame(self._trajectory[self.index]) self.update_data(None, None, None) def radio_update_frame(self, attr) -> None: self.update_frame(attr, None, None) @property def index(self) -> int: try: return self._trajectory_slider.value except AttributeError: return 0 def initialise_trajectory_interface(self) -> None: logger.debug("Loading Models: %s", self.order_functions.keys()) self._order_parameter = RadioButtonGroup( name="Classification algorithm:", labels=list(self.order_functions.keys()), active=0, width=self.controls_width, ) self._order_parameter.on_click(self.radio_update_frame) def create_trajectory_interface(self) -> None: return column( Div(text="<b>Classification Algorithm:<b>"), self._order_parameter, Div(text="<hr/>", width=self.controls_width, height=10), height=120, ) def update_current_trajectory(self, attr, old, new) -> None: if self.get_selected_file() is not None: logger.debug("Opening %s", self.get_selected_file()) self._trajectory = gsd.hoomd.open(str(self.get_selected_file()), "rb") num_frames = len(self._trajectory) try: if self._trajectory_slider.value > num_frames: self._trajectory_slider.value = num_frames - 1 self._trajectory_slider.end = len(self._trajectory) - 1 except AttributeError: pass self.update_frame(attr, old, new) current_file = self.get_selected_file() if current_file is not None: self._filename_div.text = ( f"<b>Current File:</b><br/>{current_file.name}") else: self._filename_div.text = f"<b>Current File:</b><br/>None" def initialise_media_interface(self) -> None: self._trajectory_slider = Slider( title="Trajectory Index", value=0, start=0, end=max(len(self._trajectory), 1), step=1, width=self.controls_width, ) self._trajectory_slider.on_change("value", self.update_frame) self._play_pause = Toggle(name="Play/Pause", label="Play/Pause", width=int(self.controls_width / 3)) self._play_pause.on_click(self._play_pause_toggle) self._nextFrame = Button(label="Next", width=int(self.controls_width / 3)) self._nextFrame.on_click(self._incr_index) self._prevFrame = Button(label="Previous", width=int(self.controls_width / 3)) self._prevFrame.on_click(self._decr_index) self._increment_size = Slider( title="Increment Size", value=10, start=1, end=100, step=1, width=self.controls_width, ) def _incr_index(self) -> None: if self._trajectory_slider.value < self._trajectory_slider.end: self._trajectory_slider.value = min( self._trajectory_slider.value + self._increment_size.value, self._trajectory_slider.end, ) def _decr_index(self) -> None: if self._trajectory_slider.value > self._trajectory_slider.start: self._trajectory_slider.value = max( self._trajectory_slider.value - self._increment_size.value, self._trajectory_slider.start, ) def create_media_interface(self): # return widgetbox([prevFrame, play_pause, nextFrame, increment_size], width=300) return column( Div(text="<b>Media Controls:</b>"), self._trajectory_slider, row( [self._prevFrame, self._play_pause, self._nextFrame], width=int(self.controls_width), ), self._increment_size, ) # When using webgl as the backend the save option doesn't work for some reason. def _update_source(self, data): logger.debug("Data Keys: %s", data.keys()) self._source.data = data def get_order_function(self) -> Optional[Callable]: return self.order_functions[list( self.order_functions.keys())[self._order_parameter.active]] def update_data(self, attr, old, new): if self.plot and self._frame is not None: self.plot.title.text = f"Timestep {self._frame.timestep:,}" if self._frame is not None: data = frame2data(self._frame, order_function=self.get_order_function(), molecule=Trimer()) self._update_source(data) def update_data_attr(self, attr): self.update_data(attr, None, None) def _play_pause_toggle(self, attr): if self._playing: self._doc.remove_periodic_callback(self._callback) self._playing = False else: self._callback = self._doc.add_periodic_callback( self._incr_index, 100) self._playing = True @staticmethod def create_legend(): cm_orient = LinearColorMapper(palette=DARK_COLOURS, low=-np.pi, high=np.pi) cm_class = LinearColorMapper( palette=[hpluv_to_hex((0, 0, 60)), hpluv_to_hex((0, 0, 80))], low=0, high=2) plot = figure(width=200, height=250) plot.toolbar_location = None plot.border_fill_color = "#FFFFFF" plot.outline_line_alpha = 0 cb_orient = ColorBar( title="Orientation", major_label_text_font_size="10pt", title_text_font_style="bold", color_mapper=cm_orient, orientation="horizontal", ticker=FixedTicker(ticks=[-np.pi, 0, np.pi]), major_label_overrides={ -np.pi: "-π", 0: "0", np.pi: "π" }, width=100, major_tick_line_color=None, location=(0, 120), ) cb_class = ColorBar( color_mapper=cm_class, title="Classification", major_label_text_font_size="10pt", title_text_font_style="bold", orientation="vertical", ticker=FixedTicker(ticks=[0.5, 1.5]), major_label_overrides={ 0.5: "Crystal", 1.5: "Liquid" }, label_standoff=15, major_tick_line_color=None, width=20, height=80, location=(0, 0), ) plot.add_layout(cb_orient) plot.add_layout(cb_class) return plot def initialise_doc(self): self.plot = figure( width=920, height=800, aspect_scale=1, match_aspect=True, title=f"Timestep {0:.5g}", output_backend="webgl", active_scroll="wheel_zoom", ) self.plot.xgrid.grid_line_color = None self.plot.ygrid.grid_line_color = None self.plot.x_range.start = -30 self.plot.x_range.end = 30 self.plot.y_range.start = -30 self.plot.y_range.end = 30 plot_circles(self.plot, self._source) def create_doc(self): self.update_data(None, None, None) controls = column( [ self.create_files_interface(), self.create_trajectory_interface(), self.create_media_interface(), ], width=int(self.controls_width * 1.1), ) self._doc.add_root(row(controls, self.plot, self.create_legend())) self._doc.title = "Configurations"
data = pd.Series(languages).reset_index(name='value').rename( columns={'index': 'lang'}) data['angle'] = data['value'] / data['value'].sum() * 2 * pi data['color'] = ["#1f77b4"] pie = figure(plot_height=400, title=repoNames[0], toolbar_location=None, tools="hover", tooltips="@lang: @value", x_range=(-0.5, 1.0)) pie.wedge(x=0, y=1, radius=0.4, start_angle=cumsum('angle', include_zero=True), end_angle=cumsum('angle'), line_color="white", fill_color='color', legend_field='lang', source=data) pie.axis.axis_label = None pie.axis.visible = False pie.grid.grid_line_color = None # UPDATE USER text.on_change('value', update_user) radio.on_click(specific_repo) graphs = column(text, radio, row(p, pie), width=1000) curdoc().add_root(graphs) curdoc().title = "BIG WORKY"
def __init__(self, n_nodes): self.i = 0 kps = [crypto_sign_keypair() for _ in range(n_nodes)] stake = {kp[0]: 1 for kp in kps} network = {} self.nodes = [Node(kp, network, n_nodes, stake) for kp in kps] for n in self.nodes: network[n.pk] = n.ask_sync self.ids = {kp[0]: i for i, kp in enumerate(kps)} self.main_its = [n.main() for n in self.nodes] for m in self.main_its: next(m) def toggle(): if play.label == '► Play': play.label = '❚❚ Pause' curdoc().add_periodic_callback(self.animate, 50) else: play.label = '► Play' curdoc().remove_periodic_callback(self.animate) play = Button(label='► Play', width=60) play.on_click(toggle) def sel_node(new): self.active = new node = self.nodes[new] self.tbd = {} self.tr_src.data, self.links_src.data = self.extract_data( node, bfs((node.head,), lambda u: node.hg[u].p), 0) for u, j in tuple(self.tbd.items()): self.tr_src.data['line_alpha'][j] = 1 if node.famous.get(u) else 0 if u in node.idx: self.tr_src.data['round_color'][j] = idx_color(node.idx[u]) self.tr_src.data['idx'][j] = node.idx.get(u) if u in node.idx and u in node.famous: del self.tbd[u] print('updated') self.tr_src.trigger('data', None, self.tr_src.data) selector = RadioButtonGroup( labels=['Node %i' % i for i in range(n_nodes)], active=0, name='Node to inspect') selector.on_click(sel_node) plot = figure( plot_height=700, plot_width=900, y_range=(0, 30), tools=[PanTool(dimensions=['height']), HoverTool(tooltips=[ ('round', '@round'), ('hash', '@hash'), ('timestamp', '@time'), ('payload', '@payload'), ('number', '@idx')])]) plot.xgrid.grid_line_color = None plot.xaxis.minor_tick_line_color = None plot.ygrid.grid_line_color = None plot.yaxis.minor_tick_line_color = None self.links_src = ColumnDataSource(data={'x0': [], 'y0': [], 'x1': [], 'y1': [], 'width': []}) #self.links_rend = plot.add_layout( # Arrow(end=NormalHead(fill_color='black'), x_start='x0', y_start='y0', x_end='x1', # y_end='y1', source=self.links_src)) self.links_rend = plot.segment(color='#777777', x0='x0', y0='y0', x1='x1', y1='y1', source=self.links_src, line_width='width') self.tr_src = ColumnDataSource( data={'x': [], 'y': [], 'round_color': [], 'idx': [], 'line_alpha': [], 'round': [], 'hash': [], 'payload': [], 'time': []}) self.tr_rend = plot.circle(x='x', y='y', size=20, color='round_color', line_alpha='line_alpha', source=self.tr_src, line_width=5) sel_node(0) curdoc().add_root(row([widgetbox(play, selector, width=300), plot], sizing_mode='fixed'))
############## # radio group gmap radio_group_gmap = RadioButtonGroup(labels=["GMap", "Blank"], #title='Background Map', active=0, name='Select Plot Options') def radio_group_handler_gmap(active): # need to update skipnodes too global gmap_background # detault to empty datasources if active == 0: gmap_background = True elif active == 1: gmap_background = False radio_group_gmap.on_click(radio_group_handler_gmap) ############## ############# # Run new button_run_new = Button(label="Download, Show, Run GUI", type='success') def on_run_new_click(): global download_new_osm, filenames download_new_osm = True filenames = define_files() #load_data() #init_plots() #run_gui() button_run_new.on_click(on_run_new_click)
# T2.3 Add circles at the locations of capital cities for each canton, and the sizes are proportional to daily new cases per capita sites = p1.circle(...) # T2.4 Create a radio button group with labels 'Density', and 'BedsPerCapita' buttons = RadioButtonGroup(...) # Define a function to update color mapper used in both patches and colorbar def update_bar(new): for i, d in enumerate(labels): if i == new: ... buttons.on_click(...) # T2.5 Add a dateslider to control which per capita daily new cases information to display # Define a dateslider using maximum and mimimum dates, set value to be the latest date timeslider = DateSlider(...) # Complete the callback function # Hints: # convert the timestamp value from the slider to datetime and format it in the form of '%Y-%m-%d' # update columns 'size', 'dnc' with the column named '%Y-%m-%d' in merged # update geosource with new merged def callback(attr, old, new): # Convert timestamp to datetime
res=args.res, geo_dir=args.geodir, no_antarctica=args.no_antarctica, percentile=args.percentile, log_color_bar=args.log) show(ds.fig) else: # Interactive mode. # bokeh serve --show choropleth.py # to-do: can we make it standalone mode? which means we have to write javascript from bokeh.io import curdoc from bokeh.layouts import widgetbox from bokeh.layouts import column from bokeh.models import RadioButtonGroup ds = DataSource() def radio_buttons_on_click(idx): global ds ds.set_key(_KEYS[idx]) radio_buttons = RadioButtonGroup( labels=_KEYS, active=_KEYS.index('active'), ) radio_buttons.on_click(radio_buttons_on_click) layout = column(ds.fig, column(radio_buttons)) curdoc().add_root(layout)
data_counties = pd.concat([data_counties, raw_df], axis=1) # getting quantile values for categorising counties top_qtl = raw_df.quantile(0.66) middle_qtl = raw_df.quantile(0.33) session = Session() document = Document() session.use_doc('python_project') session.load_document(document) source = ColumnDataSource(data=dict(x=[], y=[], c=[], i=[])) inf_source = ColumnDataSource(data=dict(facs=[])) # radio buttons intialization radio = RadioButtonGroup(labels=['Cancer Deaths', 'Heart Disease Deaths', 'Respiratory Disease Deaths', 'Diabetes Deaths'], active=0) radio.on_click(update) # calling update function to intialize the plot update(0) if __name__ == '__main__': link = session.object_link(document.context) print("Please visit %s to see the plots" % link) view(link) session.poll_document(document)
background_fill_color="#1E1E1E" ) setup_vol_plot() # DEBUG trace debug_banner = Paragraph(text="Streaming Stopped", width=150, height=100) # to reset all plot together terminate_button = Button(label='Terminate', width=100, css_classes=['bk-terminate-btn']) terminate_button.on_click(button_terminate) LABELS = ["OFF", "ON"] radio_button_group = RadioButtonGroup(labels=LABELS, active=0, button_type="success", width=150) radio_button_group.on_click(button_subscribe) MODE_LABELS = ["Historical", "Live"] mode_radio_button_group = RadioButtonGroup(labels=MODE_LABELS, active=0, button_type="success", width=150) request_button = Button(label='Simulate', width=100, css_classes=['bk-run-btn']) request_button.on_click(button_request_data) reset_button = Button(label='Reset', width=100, css_classes=['bk-custom-btn']) reset_button.on_click(button_reset) download_button = Button(label='Download', width=100, css_classes=['bk-custom-btn']) download_button.on_click(button_download_data)
def accelerator_tab(acc): '''Creating an accelerator with parameters ''' length = RangeSlider(start=0, end=25, value=(0, 1), step=.1, title='Length [m]', format='0[.]0') pre = PreText(text='''Here you can compile an accelerator.''') compile_button = Button(label='Compile', button_type="success", height=45) element_button = RadioButtonGroup( labels=['Accels', 'Solenoids', 'Quadrupoles'], active=0) name_input = TextInput(value="Acc. ", title="Name:", width=100) z_input = TextInput(value="0", title="z [m]:", width=100) field_input = TextInput(value="0", title="MaxField [MV/m]:", width=100) file_input = FileInput(accept='.csv, .dat, .txt') parameters_input = column(file_input, row(name_input, z_input, field_input)) source = ColumnDataSource(data={'z': acc.z, 'Fz': acc.Ez(acc.z)}) field_plot = figure(x_axis_label='z [m]', y_axis_label='Ez [MV/m]', width=650, height=250) field_plot.line('z', 'Fz', source=source, line_color='#3A5785', line_alpha=0.7, line_width=1) controls = row(column(pre, length, compile_button), column(element_button, parameters_input)) # Create a row layout layout = column(controls, field_plot) tab = Panel(child=layout, title='Accelerator') def compile_handler(new, acc=acc): (acc.z_start, acc.z_stop) = length.value acc.z = acc.parameter = np.arange(acc.z_start, acc.z_stop, acc.dz) name = name_input.value file_name = dirname(__file__) + '/data/' + file_input.filename position = float(z_input.value) max_field = float(field_input.value) if element_button.active == 0: acc.add_accel(name, position, max_field, file_name) acc.compile() source.data = {'z': acc.z, 'Fz': acc.Ez(acc.z)} field_input.title = 'MaxField [MV/m]:' field_plot.yaxis.axis_label = 'Ez [MV/m]' if element_button.active == 1: acc.add_solenoid(name, position, max_field, file_name) acc.compile() source.data = {'z': acc.z, 'Fz': acc.Bz(acc.z)} field_input.title = 'MaxField [T]:' field_plot.yaxis.axis_label = 'Bz [T]' if element_button.active == 2: acc.add_quad(name, position, max_field, file_name) acc.compile() source.data = {'z': acc.z, 'Fz': acc.Gz(acc.z)} field_input.title = 'MaxField [T/m]:' field_plot.yaxis.axis_label = 'Gz [T/m]' print(acc) def element_handler(new): if new == 0: source.data = {'z': acc.z, 'Fz': acc.Ez(acc.z)} field_input.title = 'MaxField [MV/m]:' name_input.value = 'Acc. ' field_plot.yaxis.axis_label = 'Ez [MV/m]' if new == 1: source.data = {'z': acc.z, 'Fz': acc.Bz(acc.z)} field_input.title = 'MaxField [T]:' name_input.value = 'Sol. ' field_plot.yaxis.axis_label = 'Bz [T]' if new == 2: source.data = {'z': acc.z, 'Fz': acc.Gz(acc.z)} field_input.title = 'MaxField [T/m]:' name_input.value = 'Quad. ' field_plot.yaxis.axis_label = 'Gz [T/m]' compile_button.on_click(compile_handler) element_button.on_click(element_handler) return tab
def create(): det_data = {} roi_selection = {} upload_div = Div(text="Open .cami file:") def upload_button_callback(_attr, _old, new): with io.StringIO(base64.b64decode(new).decode()) as file: h5meta_list = pyzebra.parse_h5meta(file) file_list = h5meta_list["filelist"] filelist.options = file_list filelist.value = file_list[0] upload_button = FileInput(accept=".cami") upload_button.on_change("value", upload_button_callback) def update_image(index=None): if index is None: index = index_spinner.value current_image = det_data["data"][index] proj_v_line_source.data.update(x=np.arange(0, IMAGE_W) + 0.5, y=np.mean(current_image, axis=0)) proj_h_line_source.data.update(x=np.mean(current_image, axis=1), y=np.arange(0, IMAGE_H) + 0.5) image_source.data.update( h=[np.zeros((1, 1))], k=[np.zeros((1, 1))], l=[np.zeros((1, 1))], ) image_source.data.update(image=[current_image]) if auto_toggle.active: im_max = int(np.max(current_image)) im_min = int(np.min(current_image)) display_min_spinner.value = im_min display_max_spinner.value = im_max image_glyph.color_mapper.low = im_min image_glyph.color_mapper.high = im_max def update_overview_plot(): h5_data = det_data["data"] n_im, n_y, n_x = h5_data.shape overview_x = np.mean(h5_data, axis=1) overview_y = np.mean(h5_data, axis=2) overview_plot_x_image_source.data.update(image=[overview_x], dw=[n_x]) overview_plot_y_image_source.data.update(image=[overview_y], dw=[n_y]) if frame_button_group.active == 0: # Frame overview_plot_x.axis[1].axis_label = "Frame" overview_plot_y.axis[1].axis_label = "Frame" overview_plot_x_image_source.data.update(y=[0], dh=[n_im]) overview_plot_y_image_source.data.update(y=[0], dh=[n_im]) elif frame_button_group.active == 1: # Omega overview_plot_x.axis[1].axis_label = "Omega" overview_plot_y.axis[1].axis_label = "Omega" om = det_data["rot_angle"] om_start = om[0] om_end = (om[-1] - om[0]) * n_im / (n_im - 1) overview_plot_x_image_source.data.update(y=[om_start], dh=[om_end]) overview_plot_y_image_source.data.update(y=[om_start], dh=[om_end]) def filelist_callback(_attr, _old, new): nonlocal det_data det_data = pyzebra.read_detector_data(new) index_spinner.value = 0 index_spinner.high = det_data["data"].shape[0] - 1 update_image(0) update_overview_plot() filelist = Select() filelist.on_change("value", filelist_callback) def index_spinner_callback(_attr, _old, new): update_image(new) index_spinner = Spinner(title="Image index:", value=0, low=0) index_spinner.on_change("value", index_spinner_callback) plot = Plot( x_range=Range1d(0, IMAGE_W, bounds=(0, IMAGE_W)), y_range=Range1d(0, IMAGE_H, bounds=(0, IMAGE_H)), plot_height=IMAGE_H * 3, plot_width=IMAGE_W * 3, toolbar_location="left", ) # ---- tools plot.toolbar.logo = None # ---- axes plot.add_layout(LinearAxis(), place="above") plot.add_layout(LinearAxis(major_label_orientation="vertical"), place="right") # ---- grid lines plot.add_layout(Grid(dimension=0, ticker=BasicTicker())) plot.add_layout(Grid(dimension=1, ticker=BasicTicker())) # ---- rgba image glyph image_source = ColumnDataSource( dict( image=[np.zeros((IMAGE_H, IMAGE_W), dtype="float32")], h=[np.zeros((1, 1))], k=[np.zeros((1, 1))], l=[np.zeros((1, 1))], x=[0], y=[0], dw=[IMAGE_W], dh=[IMAGE_H], )) h_glyph = Image(image="h", x="x", y="y", dw="dw", dh="dh", global_alpha=0) k_glyph = Image(image="k", x="x", y="y", dw="dw", dh="dh", global_alpha=0) l_glyph = Image(image="l", x="x", y="y", dw="dw", dh="dh", global_alpha=0) plot.add_glyph(image_source, h_glyph) plot.add_glyph(image_source, k_glyph) plot.add_glyph(image_source, l_glyph) image_glyph = Image(image="image", x="x", y="y", dw="dw", dh="dh") plot.add_glyph(image_source, image_glyph, name="image_glyph") # ---- projections proj_v = Plot( x_range=plot.x_range, y_range=DataRange1d(), plot_height=200, plot_width=IMAGE_W * 3, toolbar_location=None, ) proj_v.add_layout(LinearAxis(major_label_orientation="vertical"), place="right") proj_v.add_layout(LinearAxis(major_label_text_font_size="0pt"), place="below") proj_v.add_layout(Grid(dimension=0, ticker=BasicTicker())) proj_v.add_layout(Grid(dimension=1, ticker=BasicTicker())) proj_v_line_source = ColumnDataSource(dict(x=[], y=[])) proj_v.add_glyph(proj_v_line_source, Line(x="x", y="y", line_color="steelblue")) proj_h = Plot( x_range=DataRange1d(), y_range=plot.y_range, plot_height=IMAGE_H * 3, plot_width=200, toolbar_location=None, ) proj_h.add_layout(LinearAxis(), place="above") proj_h.add_layout(LinearAxis(major_label_text_font_size="0pt"), place="left") proj_h.add_layout(Grid(dimension=0, ticker=BasicTicker())) proj_h.add_layout(Grid(dimension=1, ticker=BasicTicker())) proj_h_line_source = ColumnDataSource(dict(x=[], y=[])) proj_h.add_glyph(proj_h_line_source, Line(x="x", y="y", line_color="steelblue")) # add tools hovertool = HoverTool(tooltips=[("intensity", "@image"), ("h", "@h"), ("k", "@k"), ("l", "@l")]) box_edit_source = ColumnDataSource(dict(x=[], y=[], width=[], height=[])) box_edit_glyph = Rect(x="x", y="y", width="width", height="height", fill_alpha=0, line_color="red") box_edit_renderer = plot.add_glyph(box_edit_source, box_edit_glyph) boxedittool = BoxEditTool(renderers=[box_edit_renderer], num_objects=1) def box_edit_callback(_attr, _old, new): if new["x"]: h5_data = det_data["data"] x_val = np.arange(h5_data.shape[0]) left = int(np.floor(new["x"][0])) right = int(np.ceil(new["x"][0] + new["width"][0])) bottom = int(np.floor(new["y"][0])) top = int(np.ceil(new["y"][0] + new["height"][0])) y_val = np.sum(h5_data[:, bottom:top, left:right], axis=(1, 2)) else: x_val = [] y_val = [] roi_avg_plot_line_source.data.update(x=x_val, y=y_val) box_edit_source.on_change("data", box_edit_callback) wheelzoomtool = WheelZoomTool(maintain_focus=False) plot.add_tools( PanTool(), BoxZoomTool(), wheelzoomtool, ResetTool(), hovertool, boxedittool, ) plot.toolbar.active_scroll = wheelzoomtool # shared frame range frame_range = DataRange1d() det_x_range = DataRange1d() overview_plot_x = Plot( title=Title(text="Projections on X-axis"), x_range=det_x_range, y_range=frame_range, plot_height=400, plot_width=400, toolbar_location="left", ) # ---- tools wheelzoomtool = WheelZoomTool(maintain_focus=False) overview_plot_x.toolbar.logo = None overview_plot_x.add_tools( PanTool(), BoxZoomTool(), wheelzoomtool, ResetTool(), ) overview_plot_x.toolbar.active_scroll = wheelzoomtool # ---- axes overview_plot_x.add_layout(LinearAxis(axis_label="Coordinate X, pix"), place="below") overview_plot_x.add_layout(LinearAxis(axis_label="Frame", major_label_orientation="vertical"), place="left") # ---- grid lines overview_plot_x.add_layout(Grid(dimension=0, ticker=BasicTicker())) overview_plot_x.add_layout(Grid(dimension=1, ticker=BasicTicker())) # ---- rgba image glyph overview_plot_x_image_source = ColumnDataSource( dict(image=[np.zeros((1, 1), dtype="float32")], x=[0], y=[0], dw=[1], dh=[1])) overview_plot_x_image_glyph = Image(image="image", x="x", y="y", dw="dw", dh="dh") overview_plot_x.add_glyph(overview_plot_x_image_source, overview_plot_x_image_glyph, name="image_glyph") det_y_range = DataRange1d() overview_plot_y = Plot( title=Title(text="Projections on Y-axis"), x_range=det_y_range, y_range=frame_range, plot_height=400, plot_width=400, toolbar_location="left", ) # ---- tools wheelzoomtool = WheelZoomTool(maintain_focus=False) overview_plot_y.toolbar.logo = None overview_plot_y.add_tools( PanTool(), BoxZoomTool(), wheelzoomtool, ResetTool(), ) overview_plot_y.toolbar.active_scroll = wheelzoomtool # ---- axes overview_plot_y.add_layout(LinearAxis(axis_label="Coordinate Y, pix"), place="below") overview_plot_y.add_layout(LinearAxis(axis_label="Frame", major_label_orientation="vertical"), place="left") # ---- grid lines overview_plot_y.add_layout(Grid(dimension=0, ticker=BasicTicker())) overview_plot_y.add_layout(Grid(dimension=1, ticker=BasicTicker())) # ---- rgba image glyph overview_plot_y_image_source = ColumnDataSource( dict(image=[np.zeros((1, 1), dtype="float32")], x=[0], y=[0], dw=[1], dh=[1])) overview_plot_y_image_glyph = Image(image="image", x="x", y="y", dw="dw", dh="dh") overview_plot_y.add_glyph(overview_plot_y_image_source, overview_plot_y_image_glyph, name="image_glyph") def frame_button_group_callback(_active): update_overview_plot() frame_button_group = RadioButtonGroup(labels=["Frames", "Omega"], active=0) frame_button_group.on_click(frame_button_group_callback) roi_avg_plot = Plot( x_range=DataRange1d(), y_range=DataRange1d(), plot_height=IMAGE_H * 3, plot_width=IMAGE_W * 3, toolbar_location="left", ) # ---- tools roi_avg_plot.toolbar.logo = None # ---- axes roi_avg_plot.add_layout(LinearAxis(), place="below") roi_avg_plot.add_layout(LinearAxis(major_label_orientation="vertical"), place="left") # ---- grid lines roi_avg_plot.add_layout(Grid(dimension=0, ticker=BasicTicker())) roi_avg_plot.add_layout(Grid(dimension=1, ticker=BasicTicker())) roi_avg_plot_line_source = ColumnDataSource(dict(x=[], y=[])) roi_avg_plot.add_glyph(roi_avg_plot_line_source, Line(x="x", y="y", line_color="steelblue")) cmap_dict = { "gray": Greys256, "gray_reversed": Greys256[::-1], "plasma": Plasma256, "cividis": Cividis256, } def colormap_callback(_attr, _old, new): image_glyph.color_mapper = LinearColorMapper(palette=cmap_dict[new]) overview_plot_x_image_glyph.color_mapper = LinearColorMapper( palette=cmap_dict[new]) overview_plot_y_image_glyph.color_mapper = LinearColorMapper( palette=cmap_dict[new]) colormap = Select(title="Colormap:", options=list(cmap_dict.keys())) colormap.on_change("value", colormap_callback) colormap.value = "plasma" radio_button_group = RadioButtonGroup(labels=["nb", "nb_bi"], active=0) STEP = 1 # ---- colormap 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 update_image() auto_toggle = Toggle(label="Auto Range", active=True, button_type="default") auto_toggle.on_click(auto_toggle_callback) # ---- colormap display max value def display_max_spinner_callback(_attr, _old_value, new_value): display_min_spinner.high = new_value - STEP image_glyph.color_mapper.high = new_value display_max_spinner = Spinner( title="Maximal Display Value:", low=0 + STEP, value=1, step=STEP, disabled=auto_toggle.active, ) display_max_spinner.on_change("value", display_max_spinner_callback) # ---- colormap display min value def display_min_spinner_callback(_attr, _old_value, new_value): display_max_spinner.low = new_value + STEP image_glyph.color_mapper.low = new_value display_min_spinner = Spinner( title="Minimal Display Value:", high=1 - STEP, value=0, step=STEP, disabled=auto_toggle.active, ) display_min_spinner.on_change("value", display_min_spinner_callback) def hkl_button_callback(): index = index_spinner.value setup_type = "nb_bi" if radio_button_group.active else "nb" h, k, l = calculate_hkl(det_data, index, setup_type) image_source.data.update(h=[h], k=[k], l=[l]) hkl_button = Button(label="Calculate hkl (slow)") hkl_button.on_click(hkl_button_callback) selection_list = TextAreaInput(rows=7) def selection_button_callback(): nonlocal roi_selection selection = [ int(np.floor(det_x_range.start)), int(np.ceil(det_x_range.end)), int(np.floor(det_y_range.start)), int(np.ceil(det_y_range.end)), int(np.floor(frame_range.start)), int(np.ceil(frame_range.end)), ] filename_id = filelist.value[-8:-4] if filename_id in roi_selection: roi_selection[f"{filename_id}"].append(selection) else: roi_selection[f"{filename_id}"] = [selection] selection_list.value = str(roi_selection) selection_button = Button(label="Add selection") selection_button.on_click(selection_button_callback) # Final layout layout_image = column( gridplot([[proj_v, None], [plot, proj_h]], merge_tools=False), row(index_spinner)) colormap_layout = column(colormap, auto_toggle, display_max_spinner, display_min_spinner) hkl_layout = column(radio_button_group, hkl_button) layout_overview = column( gridplot( [[overview_plot_x, overview_plot_y]], toolbar_options=dict(logo=None), merge_tools=True, ), frame_button_group, ) tab_layout = row( column( upload_div, upload_button, filelist, layout_image, row(colormap_layout, hkl_layout), ), column( roi_avg_plot, layout_overview, row(selection_button, selection_list), ), ) return Panel(child=tab_layout, title="Data Viewer")
class SecondaryButtons: def __init__(self): self.handler = server_thread.SERVER_HANDLER self.latest_status = None self.hv_options = list(OnOffState.__members__.keys()) self.b_hv_updating = False self.b_hv = RadioButtonGroup(labels=self.hv_options, active=self.hv_options.index("MAYBEON")) self.b_hv.on_click(self.hv_change) t_hv = Div(text="<h3>HV</h3>") self.b_hv_level = RadioButtonGroup( labels=['UNKNOWN', 'LOW', 'MED', 'HIGH'], active=0) self.b_hv_level.on_click(self.hv_level_change) self.t_hv_level = Div(text="<h3>HV LEVEL (requires ready)</h3>") options = list(GUITriggerSettings.__members__.keys()) self.b_trigger = Select(title="", value=options[0], options=options) self.t_trigger = Div(text="<h3>TRIGGER (requires ready)</h3>") self.b_trigger_apply = Button(label="APPLY", width=100) self.b_trigger_apply.on_click(self.trigger_change) self.w_time_input = TextInput() self.w_time_input_apply = Button(label="APPLY", width=100) self.w_time_input_apply.on_click(self.time_input_change) self.w_time_input_refresh = Button(label="REFRESH", width=100) self.w_time_input_refresh.on_click(self.update_time_input) self.t_time_input = Div( text="<h3>Observation Time (requires ready):</h3>") self.tk = tk.Tk() self.tk.withdraw() self.tk.lift() self.tk.attributes('-topmost', True) wb_list = [[t_hv], [self.b_hv], [self.t_hv_level], [self.b_hv_level], [self.t_trigger], [self.b_trigger], [self.b_trigger_apply], [self.t_time_input], [self.w_time_input], [self.w_time_input_apply, self.w_time_input_refresh]] self.layout = layout(wb_list) def hv_change(self, index): if not self.b_onoff_updating: state = OnOffState[self.hv_options[index]] if state == OnOffState['ON']: msg = "Are you sure it is safe to turn on HV? " result = messagebox.askquestion("TURNON", msg, icon='warning', parent=self.tk) if not result == 'yes': return self.handler.set_hv_state(state) def hv_level_change(self, index): if not self.b_hv_level_updating: if not self.b_hv_level.disabled: state = LowMedHighState(index) self.handler.set_hv_level(state) def trigger_change(self): if not self.b_trigger_updating: if not self.b_trigger.disabled: self.b_trigger_apply.button_type = 'warning' self.b_trigger_apply.disabled = True state = GUITriggerSettings[self.b_trigger.value] self.handler.set_trigger(state) def time_input_change(self): self.handler.set_observation_time_from_string(self.w_time_input.value) def update(self): new = self.handler.server_status if not self.latest_status == new: self.latest_status = new self._update_hv(new) self._update_hv_level(new) self._update_trigger(new) self._update_time_input_buttons(new) def _update_hv(self, new): self.b_onoff_updating = True self.b_hv.active = self.hv_options.index(new.hv.name) self.b_onoff_updating = False if new.hv.name == "ON": self.b_hv.button_type = 'danger' elif new.hv.name == "OFF": self.b_hv.button_type = 'success' else: self.b_hv.button_type = 'warning' def _update_hv_level(self, new): self.b_hv_level_updating = True self.b_hv_level.active = new.hv_level.value self.b_hv_level_updating = False fp = shorten_path(new.hvpath) self.t_hv_level.text = "<b>HV LEVEL (requires ready):</b><br>{}".format( fp) if new.state == CameraState.READY: if new.hv_level > 0: self.b_hv_level.button_type = 'success' else: self.b_hv_level.button_type = 'warning' self.b_hv_level.disabled = False else: self.b_hv_level.button_type = 'default' self.b_hv_level.disabled = True def _update_trigger(self, new): self.b_trigger_updating = True # self.b_trigger.value = new.gui_trigger.name self.b_trigger_updating = False fp = shorten_path(new.triggerpath) self.t_trigger.text = """ <b>TRIGGER (requires ready):</b><br> {}<br> Current: {} """.format(fp, new.gui_trigger.name) if new.state == CameraState.READY: self.b_trigger.disabled = False self.b_trigger_apply.disabled = False self.b_trigger_apply.button_type = 'success' else: self.b_trigger.disabled = True self.b_trigger_apply.disabled = True self.b_trigger_apply.button_type = 'default' def update_time_input(self): self.w_time_input.value = self.handler.get_observation_time() def _update_time_input_buttons(self, new): time = self.handler.get_observation_time() self.t_time_input.text = """ <b>Observation Time (requires ready):</b> <br>{} """.format(time) if new.state == CameraState.READY: self.w_time_input_apply.disabled = False self.w_time_input_apply.button_type = 'success' self.w_time_input_refresh.disabled = False self.w_time_input_refresh.button_type = 'success' else: self.w_time_input_apply.disabled = True self.w_time_input_apply.button_type = 'default' self.w_time_input_refresh.disabled = True self.w_time_input_refresh.button_type = 'default'
class ExpertButtons: def __init__(self): self.handler = server_thread.SERVER_HANDLER self.latest_status = None self.flasher_list = list(OnOffState.__members__.keys()) self.ds_list = list(OnOffState.__members__.keys()) self.b_flasher_updating = False self.b_ds_updating = False self.b_flasher = RadioButtonGroup( labels=self.flasher_list, active=self.flasher_list.index("MAYBEON")) self.b_flasher.on_click(self.flasher_change) t_flasher = Div(text="<h3>Flasher</h3>") self.b_ds = RadioButtonGroup(labels=self.ds_list, active=self.ds_list.index("MAYBEON")) self.b_ds.on_click(self.ds_change) t_ds = Div(text="<h3>Data Sending</h3>") t_expert = Div(text="<h1><u>EXPERT</u></h1>") wb_list = [ [t_expert], [t_flasher], [self.b_flasher], [t_ds], [self.b_ds], ] self.layout = layout(wb_list) def flasher_change(self, index): if not self.b_flasher_updating: state = OnOffState[self.flasher_list[index]] self.handler.set_flasher_state(state) def ds_change(self, index): if not self.b_ds_updating: state = OnOffState[self.ds_list[index]] self.handler.set_data_sending_state(state) def update(self): new = self.handler.server_status if not self.latest_status == new: self.latest_status = new self._update_flasher(new) self._update_ds(new) def _update_flasher(self, new): self.b_flasher_updating = True self.b_flasher.active = self.flasher_list.index(new.flasher.name) self.b_flasher_updating = False if new.flasher.name == "ON": self.b_flasher.button_type = 'danger' elif new.flasher.name == "OFF": self.b_flasher.button_type = 'success' else: self.b_flasher.button_type = 'warning' def _update_ds(self, new): self.b_ds_updating = True self.b_ds.active = self.ds_list.index(new.data_sending.name) self.b_ds_updating = False if new.data_sending.name == "ON": self.b_ds.button_type = 'danger' elif new.data_sending.name == "OFF": self.b_ds.button_type = 'success' else: self.b_ds.button_type = 'warning'
time = time_button_group.active times = miniVis.splitTime(gdf, 10) gdf = gdf[(gdf['timenums'] > times[time - 1]) & (gdf['timenums'] < times[time])] print(gdf) source = ColumnDataSource(data=gdf) r.data_source.data = source.data color_mapper.low = min(r.data_source.data['timenums']) color_mapper.high = max(r.data_source.data['timenums']) radio_button_group = RadioButtonGroup( labels=[i for i in df['disaster.event'].unique()], active=12) radio_button_group.on_click(disasterUpdate) time_button_group = RadioButtonGroup(labels=[str(i) for i in range(0, 11)], active=0) time_button_group.on_click(timeUpdate) #add slider #def callback(attr, old, new): #gdf = df[df['disaster.event'] == df['disaster.event'].unique()[radio_button_group.active]][['latitude','longitude.anon', 'timenums']] #smalData = miniVis.splitTime(gdf, 3) #gdf = smalData[0] #source.data = ColumnDataSource(data = gdf[gdf['timenums'] < new]).data #slider = Slider(start=min(gdf.timenums), end=max(gdf.timenums), value=max(gdf.timenums), step=50000, title="time") #slider.on_change('value', callback)
class BokehGainMatching(Tool): name = "BokehGainMatching" description = "Interactively explore the steps in obtaining charge vs hv" input_path = Unicode('', help='Path to the numpy array containing the ' 'gain and hv').tag(config=True) aliases = Dict(dict(f='BokehGainMatching.input_path')) classes = List([]) def __init__(self, **kwargs): super().__init__(**kwargs) self._active_pixel = None self.dead = Dead() self.charge = None self.charge_error = None self.hv = None self.n_hv = None self.n_pixels = None self.n_tmpix = 64 self.modules = None self.tmpix = None self.n_tm = None self.m_pix = None self.c_pix = None self.m_tm = None self.c_tm = None self.m_tm2048 = None self.c_tm2048 = None self.p_camera_pix = None self.p_plotter_pix = None self.p_camera_tm = None self.p_plotter_tm = None self.w_view_radio = None self.layout = None def setup(self): self.log_format = "%(levelname)s: %(message)s [%(name)s.%(funcName)s]" kwargs = dict(config=self.config, tool=self) arrays = np.load(self.input_path) self.charge = self.dead.mask2d(arrays['charge']) self.charge = np.ma.masked_where(self.charge <= 0, self.charge) self.charge_error = np.ma.array(arrays['charge_error'], mask=self.charge.mask) self.hv = arrays['rundesc'] self.n_hv, self.n_pixels = self.charge.shape assert (self.n_hv == self.hv.size) geom = CameraGeometry.guess(*checm_pixel_pos * u.m, optical_foclen * u.m) self.modules = np.arange(self.n_pixels) // self.n_tmpix self.tmpix = np.arange(self.n_pixels) % self.n_tmpix self.n_tm = np.unique(self.modules).size # Init Plots self.p_camera_pix = Camera(self, "Gain Matching Pixels", geom) self.p_camera_tm = Camera(self, "Gain Matching TMs", geom) self.p_plotter_pix = Plotter(**kwargs) self.p_plotter_tm = Plotter(**kwargs) def start(self): # Overcomplicated method instead of just reshaping... # gain_modules = np.zeros((self.n_hv, self.n_tm, self.n_tmpix)) # hv_r = np.arange(self.n_hv, dtype=np.int)[:, None] # hv_z = np.zeros(self.n_hv, dtype=np.int)[:, None] # tm_r = np.arange(self.n_tm, dtype=np.int)[None, :] # tm_z = np.zeros(self.n_tm, dtype=np.int)[None, :] # tmpix_r = np.arange(self.n_tmpix, dtype=np.int)[None, :] # tmpix_z = np.zeros(self.n_tmpix, dtype=np.int)[None, :] # hv_i = (hv_r + tm_z)[..., None] + tmpix_z # tm_i = (hv_z + tm_r)[..., None] + tmpix_z # tmpix_i = (hv_z + tm_z)[..., None] + tmpix_r # gain_rs = np.reshape(self.charge, (self.n_hv, self.n_tm, self.n_tmpix)) # modules_rs = np.reshape(self.modules, (self.n_tm, self.n_tmpix)) # tmpix_rs = np.reshape(self.tmpix, (self.n_tm, self.n_tmpix)) # tm_j = hv_z[..., None] + modules_rs[None, ...] # tmpix_j = hv_z[..., None] + tmpix_rs[None, ...] # gain_modules[hv_i, tm_i, tmpix_i] = gain_rs[hv_i, tm_j, tmpix_j] # gain_modules_mean = np.mean(gain_modules, axis=2) shape = (self.n_hv, self.n_tm, self.n_tmpix) gain_tm = np.reshape(self.charge, shape) gain_error_tm = np.reshape(self.charge_error, shape) gain_tm_mean = np.mean(gain_tm, axis=2) gain_error_tm_mean = np.sqrt(np.sum(gain_error_tm**2, axis=2)) self.m_pix = np.ma.zeros(self.n_pixels, fill_value=0) self.c_pix = np.ma.zeros(self.n_pixels, fill_value=0) self.m_tm = np.ma.zeros(self.n_tm, fill_value=0) self.c_tm = np.ma.zeros(self.n_tm, fill_value=0) p0 = [0, 5] bounds = (-np.inf, np.inf) # ([-2000, -10], [2000, 10]) for pix in range(self.n_pixels): x = self.hv[~self.charge.mask[:, pix]] y = self.charge[:, pix][~self.charge.mask[:, pix]] if x.size == 0: continue try: coeff, _ = curve_fit( gain_func, x, y, p0=p0, bounds=bounds, # sigma=y_err[:, pix], # absolute_sigma=True ) self.c_pix[pix], self.m_pix[pix] = coeff except RuntimeError: self.log.warning("Unable to fit pixel: {}".format(pix)) for tm in range(self.n_tm): x = self.hv y = gain_tm_mean[:, tm] try: coeff, _ = curve_fit( gain_func, x, y, p0=p0, bounds=bounds, # sigma=y_err_tm[:, tm], # absolute_sigma=True ) self.c_tm[tm], self.m_tm[tm] = coeff except RuntimeError: self.log.warning("Unable to fit tm: {}".format(tm)) self.m_tm2048 = self.m_tm[:, None] * np.ones((self.n_tm, self.n_tmpix)) self.c_tm2048 = self.c_tm[:, None] * np.ones((self.n_tm, self.n_tmpix)) self.m_pix = self.dead.mask1d(self.m_pix) self.c_pix = self.dead.mask1d(self.c_pix) self.m_tm2048 = self.dead.mask1d(self.m_tm2048.ravel()) self.c_tm2048 = self.dead.mask1d(self.c_tm2048.ravel()) # Setup Plots self.p_camera_pix.enable_pixel_picker() self.p_camera_pix.add_colorbar() self.p_camera_tm.enable_pixel_picker() self.p_camera_tm.add_colorbar() self.p_plotter_pix.create(self.hv, self.charge, self.charge_error, self.m_pix, self.c_pix) self.p_plotter_tm.create(self.hv, gain_tm_mean, gain_error_tm_mean, self.m_tm, self.c_tm) # Setup widgets self.create_view_radio_widget() self.set_camera_image() self.active_pixel = 0 # Get bokeh layouts l_camera_pix = self.p_camera_pix.layout l_camera_tm = self.p_camera_tm.layout l_plotter_pix = self.p_plotter_pix.layout l_plotter_tm = self.p_plotter_tm.layout # Setup layout self.layout = layout([[self.w_view_radio], [l_camera_pix, l_plotter_pix], [l_camera_tm, l_plotter_tm]]) def finish(self): curdoc().add_root(self.layout) curdoc().title = "Charge Vs HV" output_dir = dirname(self.input_path) output_path = join(output_dir, 'gain_matching_coeff.npz') np.savez(output_path, alpha_pix=np.ma.filled(self.m_pix), C_pix=np.ma.filled(self.c_pix), alpha_tm=np.ma.filled(self.m_tm), C_tm=np.ma.filled(self.c_tm)) self.log.info("Numpy array saved to: {}".format(output_path)) @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.p_camera_pix.active_pixel = val self.p_camera_tm.active_pixel = val self.p_plotter_pix.active_pixel = val self.p_plotter_pix.fig.title.text = 'Pixel {}'.format(val) module = self.modules[val] self.p_plotter_tm.active_pixel = module self.p_plotter_tm.fig.title.text = 'TM {}'.format(module) def set_camera_image(self): if self.w_view_radio.active == 0: self.p_camera_pix.image = self.m_pix self.p_camera_tm.image = self.m_tm2048 self.p_camera_pix.fig.title.text = 'Gain Matching Pixels (gradient)' self.p_camera_tm.fig.title.text = 'Gain Matching TMs (gradient)' elif self.w_view_radio.active == 1: self.p_camera_pix.image = self.c_pix self.p_camera_tm.image = self.c_tm2048 self.p_camera_pix.fig.title.text = 'Gain Matching Pixels (intercept)' self.p_camera_tm.fig.title.text = 'Gain Matching TMs (intercept)' def create_view_radio_widget(self): self.w_view_radio = RadioButtonGroup(labels=["gradient", "intercept"], active=0) self.w_view_radio.on_click(self.on_view_radio_widget_click) def on_view_radio_widget_click(self, active): self.set_camera_image()
alpha=0.33) # T2.4 Create a radio button group with labels 'Density', and 'BedsPerCapita' buttons = RadioButtonGroup(labels=['Density', 'BedPerCapita'], active=0) # Define a function to update color mapper used in both patches and colorbar def update_bar(new): for i, d in enumerate(labels): if i == new: color_bar.color_mapper = mappers[d]["transform"] color_bar.title = d cantons.glyph.fill_color = mappers[d] buttons.on_click(update_bar) # T2.5 Add a dateslider to control which per capita daily new cases information to display # Define a dateslider using maximum and mimimum dates, set value to be the latest date timeslider = DateSlider(title='Date', start=dates.min(), end=dates.max(), value=dates.max()) # Complete the callback function # Hints: # convert the timestamp value from the slider to datetime and format it in the form of '%Y-%m-%d' # update columns 'size', 'dnc' with the column named '%Y-%m-%d' in merged # update geosource with new merged
def tuning_tab(beam, acc): '''Tuning accelerator ''' pre = PreText(text='''You can configure accelerator elements.''') element_button = RadioButtonGroup( labels=['Accels', 'Solenoids', 'Quadrupoles'], active=0) tune_button = Button(label='Tune', button_type="success") select = Select(options=[itm.name for itm in acc.Ez_beamline.values()]) select_maxfield = Slider(start=-5.0, end=5.0, step=0.1, value=0.0, title='MaxField [MV/m]', format='0[.]0') line_source = ColumnDataSource(data={'z': [0, 0], 'x': [-0.1, 0.1]}) field_source = ColumnDataSource(data={'z': acc.z, 'Fz': acc.Ez(acc.z)}) field_plot = figure(x_axis_label='z [m]', y_axis_label='Ez [MV/m]', width=330, height=210) field_plot.line('z', 'Fz', source=field_source, line_color='#3A5785', line_alpha=0.7, line_width=1) envelope_plot = figure(x_axis_label='z [m]', y_axis_label='Envelope, x [m]', width=650, height=250) envelope_source = ColumnDataSource(data={'z': acc.z, 'x': 0*acc.z, '-x': 0*acc.z}) centroid_source = ColumnDataSource(data={'z': acc.z, 'x': 0*acc.z}) envelope_plot.line('z', 'x', source=envelope_source, line_color='#3A5785', line_alpha=0.7, line_width=1) envelope_plot.line('z', '-x', source=envelope_source, line_color='#3A5785', line_alpha=0.7, line_width=1) envelope_plot.line('z', 'x', source=line_source, line_color='#3A5785', line_alpha=0.1, line_width=10) envelope_plot.line('z', 'x', source=centroid_source, line_color='#3A5785', line_alpha=0.7, line_width=1, line_dash=[3,5]) controls = row(column(pre, element_button, select, select_maxfield, tune_button), field_plot) tab = Panel(child=column(controls, envelope_plot), title='Tuning') def element_handler(new, acc=acc): if new == 0: select.options=[itm.name for itm in acc.Ez_beamline.values()] select_maxfield.start = -5.0 select_maxfield.end = 5.0 select_maxfield.step = 0.1 if select.options == []: select_maxfield.value = 0.0 select.value = '' else: select_maxfield.value = acc.Ez_beamline[select.options[0]].max_field select.value = [itm.name for itm in acc.Ez_beamline.values()][0] select_maxfield.format='0[.]0' select_maxfield.title = 'MaxField [MV/m]' field_source.data = {'z': acc.z, 'Fz': acc.Ez(acc.z)} field_plot.yaxis.axis_label = 'Ez [MV/m]' if new == 1: select.options=[itm.name for itm in acc.Bz_beamline.values()] select_maxfield.start = 0.000 select_maxfield.end = 0.500 select_maxfield.step = 0.001 if select.options == []: select_maxfield.value = 0.000 select.value = '' else: select_maxfield.value = acc.Bz_beamline[select.options[0]].max_field select.value = [itm.name for itm in acc.Bz_beamline.values()][0] select_maxfield.format='0[.]000' select_maxfield.title = 'MaxField [T]' field_source.data = {'z': acc.z, 'Fz': acc.Bz(acc.z)} field_plot.yaxis.axis_label = 'Bz [T]' if new == 2: select.options=[itm.name for itm in acc.Gz_beamline.values()] select_maxfield.start = -10.0 select_maxfield.end = 10.0 select_maxfield.step = 0.1 if select.options == []: select_maxfield.value = 0.0 select.value = '' else: select_maxfield.value = acc.Gz_beamline[select.options[0]].max_field select.value = [itm.name for itm in acc.Gz_beamline.values()][0] select_maxfield.format='0[.]0' select_maxfield.title = 'MaxField [T/m]' field_source.data = {'z': acc.z, 'Fz': acc.Gz(acc.z)} field_plot.yaxis.axis_label = 'Gz [T/m]' def update_select_maxfield(attrname, old, new, acc=acc): if new != '': if element_button.active == 0: select_maxfield.value = acc.Ez_beamline[new].max_field line_source.data = {'z': [acc.Ez_beamline[new].z0, acc.Ez_beamline[new].z0], 'x': [-0.1, 0.1]} if element_button.active == 1: select_maxfield.value = acc.Bz_beamline[new].max_field line_source.data = {'z': [acc.Bz_beamline[new].z0, acc.Bz_beamline[new].z0], 'x': [-0.1, 0.1]} if element_button.active == 2: select_maxfield.value = acc.Gz_beamline[new].max_field line_source.data = {'z': [acc.Gz_beamline[new].z0, acc.Gz_beamline[new].z0], 'x': [-0.1, 0.1]} def tune_handler(new, beam=beam, acc=acc): if select.value != '': if element_button.active == 0: acc.Ez_beamline[select.value].max_field = select_maxfield.value acc.compile() field_source.data = {'z': acc.z, 'Fz': acc.Ez(acc.z)} if element_button.active == 1: acc.Bz_beamline[select.value].max_field = select_maxfield.value acc.compile() field_source.data = {'z': acc.z, 'Fz': acc.Bz(acc.z)} if element_button.active == 2: acc.Gz_beamline[select.value].max_field = select_maxfield.value acc.compile() field_source.data = {'z': acc.z, 'Fz': acc.Gz(acc.z)} beam.df['p2'] = beam.df['pz']*beam.df['pz'] + beam.df['px']*beam.df['px'] + beam.df['py']*beam.df['py'] E = beam.df['p2'].mean()**0.5 - beam.type.mass*rp.c**2/rp.e/1e6 I = np.sign(beam.type.charge) * beam.charge * rp.c / (beam.df['z'].max()-beam.df['z'].min()) X = beam.df['x'].max() Y = beam.df['y'].max() Xp = beam.df['px'].max() / beam.df['pz'].max() Yp = beam.df['py'].max() / beam.df['pz'].max() X_off = beam.df['x'].mean() Y_off = beam.df['x'].mean() Xp_off = beam.df['px'].mean() / beam.df['pz'].max() Yp_off = beam.df['py'].mean() / beam.df['pz'].max() beta = beam.df['pz'].max() / (E + beam.type.mass*rp.c**2/rp.e/1e6) gamma = 1/(1-beta**2)**0.5 df = beam.df df['xp'] = df['px']/df['pz'] df['yp'] = df['py']/df['pz'] df['xp2'] = df['xp']*df['xp'] df['yp2'] = df['yp']*df['yp'] df['x xp'] = df['x']*df['xp'] df['y yp'] = df['y']*df['yp'] df['x2'] = df['x']*df['x'] df['y2'] = df['y']*df['y'] df['rms x'] = df['x2'].mean()**0.5 df['rms y'] = df['y2'].mean()**0.5 df['rms x Emittance'] = (df['x2'].mean()*df['xp2'].mean() - df['x xp'].mean()**2)**0.5 df['rms y Emittance'] = (df['y2'].mean()*df['yp2'].mean() - df['y yp'].mean()**2)**0.5 Emitt_x = df['rms x Emittance'].max()*gamma*beta Emitt_y = df['rms y Emittance'].max()*gamma*beta kv_beam = kv.Beam(energy=E, current=I, radius_x=X, radius_y=Y, radius_xp=Xp, radius_yp=Yp, normalized_emittance_x=Emitt_x, normalized_emittance_y=Emitt_y, x=X_off, y=Y_off, xp=Xp_off, yp=Yp_off, charge=np.sign(beam.type.charge)) kv_sim = kv.Simulation(kv_beam, acc) kv_sim.track() envelope_source.data = {'z': acc.z, 'x': kv_sim.envelope_x(acc.z), '-x': -kv_sim.envelope_x(acc.z)} centroid_source.data = {'z': acc.z, 'x': kv_sim.centroid_x(acc.z)} element_button.on_click(element_handler) select.on_change('value', update_select_maxfield) tune_button.on_click(tune_handler) return tab