def test_updates_when_visibility_is_toggled(self, single_plot_page) -> None: source = ColumnDataSource(dict(x=[1, 2], y1=[0, 1], y2=[10, 11])) plot = Plot(plot_height=400, plot_width=400, x_range=DataRange1d(), y_range=DataRange1d(only_visible=True), min_border=0) plot.add_glyph(source, Circle(x='x', y='y1')) glyph = plot.add_glyph(source, Circle(x='x', y='y2')) code = RECORD("yrstart", "p.y_range.start", final=False) + RECORD( "yrend", "p.y_range.end") plot.add_tools( CustomAction(callback=CustomJS(args=dict(p=plot), code=code))) plot.toolbar_sticky = False button = Button(css_classes=['foo']) button.js_on_click( CustomJS(args=dict(glyph=glyph), code="glyph.visible=false")) page = single_plot_page(column(plot, button)) page.click_custom_action() results = page.results assert results['yrstart'] <= 0 assert results['yrend'] >= 11 button = page.driver.find_element_by_css_selector('.foo .bk-btn') button.click() page.click_custom_action() results = page.results assert results['yrstart'] <= 0 assert results['yrend'] < 5 assert page.has_no_console_errors()
def initialize(self, plot_id=None): plot = self.plot stream = self.streams[0] element = self.plot.current_frame vertex_tool = None if all(s.shared for s in self.streams): tools = [tool for tool in plot.state.tools if isinstance(tool, PolyEditTool)] vertex_tool = tools[0] if tools else None renderer = plot.handles['glyph_renderer'] if vertex_tool is None: vertex_style = dict({'size': 10, 'alpha': 0.8}, **stream.vertex_style) r1 = plot.state.scatter([], [], **vertex_style) tooltip = '%s Edit Tool' % type(element).__name__ vertex_tool = PolyVertexEditTool( vertex_renderer=r1, custom_tooltip=tooltip, node_style=stream.node_style, end_style=stream.feature_style) action = CustomAction(action_tooltip='Split path', icon=self.icon) plot.state.add_tools(vertex_tool, action) self._create_vertex_split_link(action, renderer, r1, vertex_tool) vertex_tool.renderers.append(renderer) self._update_cds_vdims() CDSCallback.initialize(self, plot_id)
def _make_plot(): data = {"xs": [[1, 2], [1.6, 2.45]], "ys": [[1, 1], [1.5, 0.75]]} source = ColumnDataSource(data) plot = Plot(height=400, width=400, x_range=Range1d(0, 3), y_range=Range1d(0, 3), min_border=0) renderer = plot.add_glyph(source, MultiLine(xs='xs', ys='ys', line_width=10)) tool = PolyEditTool(renderers=[renderer]) psource = ColumnDataSource(dict(x=[], y=[])) prenderer = plot.add_glyph(psource, Circle(x='x', y='y', size=10)) tool.vertex_renderer = prenderer plot.add_tools(tool) plot.toolbar.active_multi = tool code = RECORD("xs", "source.data.xs", final=False) + RECORD( "ys", "source.data.ys") plot.add_tools( CustomAction(callback=CustomJS(args=dict(source=source), code=code))) plot.toolbar_sticky = False return plot
def modify_doc(doc): source = ColumnDataSource(dict(x=[1, 2], y=[1, 1], val=["a", "b"])) plot = Plot(height=400, 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")))) slider = DateSlider(start=start, end=end, value=value, css_classes=["foo"], width=300, step=24 * 3600 * 1000) def cb(attr, old, new): source.data['val'] = [slider.value_as_date.isoformat()] slider.on_change('value', cb) doc.add_root(column(slider, plot))
def _make_plot(dimensions="both", num_objects=0): source = ColumnDataSource( dict(x=[1, 2], y=[1, 1], width=[0.5, 0.5], height=[0.5, 0.5])) plot = Plot(height=400, width=400, x_range=Range1d(0, 3), y_range=Range1d(0, 3), min_border=0) renderer = plot.add_glyph( source, Rect(x='x', y='y', width='width', height='height')) tool = BoxEditTool(dimensions=dimensions, num_objects=num_objects, renderers=[renderer]) plot.add_tools(tool) plot.toolbar.active_multi = tool code = RECORD("x", "source.data.x", final=False) + \ RECORD("y", "source.data.y", final=False) + \ RECORD("width", "source.data.width", final=False) + \ RECORD("height", "source.data.height") plot.add_tools( CustomAction(callback=CustomJS(args=dict(source=source), code=code))) plot.toolbar_sticky = False return plot
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")))) slider = RangeSlider(start=0, end=10, value=(1, 9), title="bar", css_classes=["foo"], width=300) def cb(attr, old, new): source.data['val'] = [old, new] slider.on_change('value', cb) doc.add_root(column(slider, plot))
def modify_doc(doc): source = ColumnDataSource(dict(x=[1, 2], y=[1, 1], val=["a", "b"])) plot = Plot(height=400, width=400, x_range=Range1d(0, 1), y_range=Range1d(0, 1), min_border=0) plot.add_tools( CustomAction(callback=CustomJS(args=dict(s=source), code=RECORD("data", "s.data")))) plot.add_glyph(source, Circle(x='x', y='y', size=20)) dp = DatePicker(title='Select date', value=date(2019, 9, 20), min_date=date(2019, 9, 1), max_date="2019-09-30", css_classes=["foo"]) def cb(attr, old, new): source.data['val'] = [old, new] dp.disabled_dates = ["2019-09-15"] dp.on_change('value', cb) doc.add_root(column(dp, plot))
def _make_plot(num_objects=0, drag=True, vertices=False): source = ColumnDataSource(dict(xs=[[1, 2]], ys=[[1, 1]])) plot = Plot(plot_height=400, plot_width=400, x_range=Range1d(0, 3), y_range=Range1d(0, 3), min_border=0) renderer = plot.add_glyph(source, MultiLine(xs='xs', ys='ys')) tool = PolyDrawTool(num_objects=num_objects, drag=drag, renderers=[renderer]) if vertices: psource = ColumnDataSource(dict(x=[], y=[])) prenderer = plot.add_glyph(psource, Circle(x='x', y='y', size=10)) tool.vertex_renderer = prenderer plot.add_tools(tool) plot.toolbar.active_multi = tool code = RECORD("xs", "source.data.xs", final=False) + RECORD( "ys", "source.data.ys") plot.add_tools( CustomAction(callback=CustomJS(args=dict(source=source), code=code))) plot.toolbar_sticky = False return plot
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")))) input_box = AutocompleteInput(css_classes=["foo"]) input_box.title = "title" input_box.value = "400" input_box.completions = [ "100001", "12344556", "12344557", "3194567289", "209374209374" ] def cb(attr, old, new): source.data['val'] = [old, new] input_box.on_change('value', cb) doc.add_root(column(input_box, plot))
def test_ranges_udpate(self, single_plot_page) -> None: source = ColumnDataSource(dict(x=[1, 2], y=[1, 1])) 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, Rect(x='x', y='y', width=0.9, height=0.9)) plot.add_tools(ResetTool(), ZoomInTool()) code = RECORD("event_name", "cb_obj.event_name", final=False) + \ RECORD("x0", "cb_obj.x0", final=False) + \ RECORD("x1", "cb_obj.x1", final=False) + \ RECORD("y0", "cb_obj.y0", final=False) + \ RECORD("y1", "cb_obj.y1") plot.js_on_event(RangesUpdate, CustomJS(code=code)) plot.add_tools(CustomAction(callback=CustomJS(code=""))) plot.toolbar_sticky = False page = single_plot_page(plot) button = page.get_toolbar_button('zoom-in') button.click() button = page.get_toolbar_button('reset') button.click() page.click_custom_action() results = page.results assert results['event_name'] == "rangesupdate" assert results['x0'] == 0 assert results['x1'] == 1 assert results['y0'] == 0 assert results['y1'] == 1 assert page.has_no_console_errors()
type : "POST", url: "/updateplot", x_min: xmin, x_max: xmax, y_min: ymin, y_max: ymax, success: alert("???"), error: alert("broken") }); ''' nextAnnotation = CustomAction( name="Next Annotation", icon= "C:/Users/Will/Desktop/LAHacks19/191-LeicaBiosystems/Templates/img/anteater.jpeg", callback=CustomJS(args=dict(xmin=getRegionBounds(region)['min_x'], xmax=getRegionBounds(region)['max_x'], ymin=getRegionBounds(region)['min_y'], ymax=getRegionBounds(region)['max_y']), code=jscode)) from flask import Flask, render_template, request #import requests app = Flask(__name__) @app.route("/updateplot", methods=['POST', 'GET']) def updateplot(): if request.method == 'POST':
def __init__( self, title: str, plot: Figure, state: AppState, included_settings: Optional[List[str]] = None, default_values: Optional[Dict[str, Any]] = None, ) -> None: """Initializes a PlotSettings instance. Args: title (str): The title of the plot settings modal. plot (Figure): The plot to apply the settings to. state (AppState): Bokeh application state. included_settings (Optional[List[str]], optional): A list of setting IDs to include in the settings modal. The order in which the settings widgets are rendered matches the order they appear in this list. Defaults to None. default_values (Optional[Dict[str, Any]], optional): A dictionary that maps settings to their default values. For example, {"show_legend": False}. Defaults to None. configure_jinja_env (bool, optional): Whether to configure the jinja environment or not. Defaults to True. """ self._title = title self._plot = plot self._state = state self._included_settings = included_settings or BASE_SETTINGS self._plot_tool_description = "Plot Settings" # Update settings' default values if default_values: self.default_values.update(default_values) # Initialize settings' widgets self._init_included_widgets() # Create a dummy widget to allow invoking a backend callback (python) from the frontend (javascript) self._backend_callback_invoker = Toggle() self._backend_callback_invoker.on_change("active", self._update_widgets_values) # Add the settings tool to the plot self._settings_plot_tool = CustomAction( description=self._plot_tool_description, icon=os.path.join(BASE_DIR, "../assets/img/settings-icon.png"), callback=self._get_settings_button_click_js_callback(), ) self._plot.add_tools(self._settings_plot_tool) # "Apply" button self._apply_dialog_btn = Button( label="Apply", width=75, css_classes=["apply-plot-settings"], name="apply_btn", ) self._apply_dialog_btn.on_click(self.on_apply_dialog) # "Cancel" button self._cancel_dialog_btn = Button( label="Cancel", width=75, css_classes=["cancel-plot-settings"], name="cancel_btn", ) self._cancel_dialog_btn.on_click(self._on_cancel_dialog) # "Reset" button # Note! This button is an icon button that uses google fonts. # the "label" property holds the name of the icon that is used. # More info can be found in "https://google.github.io/material-design-icons". self._reset_btn = Button( label="restart_alt", width=42, css_classes=["reset-plot-settings"], name="reset_btn", ) self._reset_btn.on_click(self._on_reset_settings) # Layout the widgets self.layout = Column( *(self._get_setting_widget(setting_id) for setting_id in self._included_settings), self._apply_dialog_btn, self._cancel_dialog_btn, self._reset_btn, ) # Set plot properties' initial values self._init_plot_settings_values() self._configure_jinja_environment()
def fit(filename): def pvoigt(x, A, mu, sigma, alpha, K): sigmag = sigma * math.sqrt(2 * math.log(2)) return ((1 - alpha) * A / (sigmag * math.sqrt(2 * math.pi))) * (np.exp(-(x - mu) ** 2 / (2 * sigmag ** 2))) + ( alpha * A / math.pi) * (sigma / ((x - mu) ** 2 + sigma ** 2)) + K filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename) def search_string_in_file(file_name, string_to_search): line_number = 0 list_of_results = [] with open(file_name, 'r') as read_obj: for line in read_obj: line_number += 1 if string_to_search in line: list_of_results.append((line_number, line.rstrip())) return list_of_results matched_lines = search_string_in_file(filepath, '[Data]') elem = () for elem in matched_lines: break df = pd.read_csv(filepath, skipinitialspace=True, skiprows=elem[0]) df.dropna(axis=1, inplace=True) source = ColumnDataSource(df) p = figure(plot_height=700, plot_width=1000, toolbar_location="right", tools="save,xwheel_zoom," ",reset,crosshair", x_axis_type="linear", x_axis_location="below", background_fill_color=None, x_range=(df['Angle'].iloc[0], df['Angle'].iloc[-1])) p.add_tools(BoxSelectTool(dimensions='width')) p.add_tools(CustomAction(icon="/home/cleber/Documentos/GitHub/fitdrx/site2/static/icon.png", callback=CustomJS(code='alert("foo")'))) legend = filename[0:-4] # p.scatter('Angle', 'Det1Disc1', source=source, legend_label=legend, color='red', size=0.2, alpha=0) # p.line('Angle', 'Det1Disc1', source=source, legend_label=legend, line_color='#0020C2') p.yaxis.axis_label = 'I (U.A.)' p.xaxis.axis_label = '2-theta (degree)' guess = [max(df['Det1Disc1']), np.mean(df['Angle']), 0.5, 0, min(df['Det1Disc1'])] n = len(df['Angle']) ponto_a = 32 ponto_b = 39 # n = 0 y = np.empty(n) # for i in range(n): # y[i] = pvoigt(df['Angle'][i], guess[0], guess[1], guess[2], guess[3], guess[4]) # # # p.scatter(df['Angle'], df['Int']) # p.line(df['Angle'], y, 'r') a = df['Angle'].values s = df['Det1Disc1'].values c, cov = curve_fit(pvoigt, a, s, guess) for i in range(n): y[i] = pvoigt(df['Angle'][i], c[0], c[1], c[2], c[3], c[4]) # plt.scatter(df['Angle'], df['Int'], alpha=0.5, color='black') # p.line('Angle', y, legend_label='Cu2teste', line_color='red') plt.scatter(df['Angle'], df['Det1Disc1']) plt.plot(df['Angle'], y, 'r') generatedfilename = 'plot_' + filename + '.png' plt.savefig(os.path.join('static', generatedfilename)) return render_template('page3.html', value=generatedfilename, amp=c[0], media=c[1], sigma=c[2], alpha=c[3], offset=c[4])