def test_return_type(self): plot1 = figure() plot1.circle([], []) plot2 = figure() plot2.circle([], []) # This is a testing artefact, users dont' have to do this in practice curdoc().add_root(plot1) curdoc().add_root(plot2) r = bes.components(plot1) assert len(r) == 2 _, divs = bes.components((plot1, plot2)) assert isinstance(divs, tuple) _, divs = bes.components([plot1, plot2]) assert isinstance(divs, tuple) _, divs = bes.components({"Plot 1": plot1, "Plot 2": plot2}) assert isinstance(divs, dict) assert all(isinstance(x, string_types) for x in divs.keys()) _, divs = bes.components(OrderedDict([("Plot 1", plot1), ("Plot 2", plot2)])) assert isinstance(divs, OrderedDict) assert all(isinstance(x, string_types) for x in divs.keys())
def test_return_type(self) -> None: plot1 = figure() plot1.circle([], []) plot2 = figure() plot2.circle([], []) # This is a testing artefact, users don't have to do this in practice curdoc().add_root(plot1) curdoc().add_root(plot2) r = bes.components(plot1) assert len(r) == 2 _, divs0 = bes.components((plot1, plot2)) assert isinstance(divs0, tuple) _, divs1 = bes.components([plot1, plot2]) assert isinstance(divs1, tuple) _, divs2 = bes.components({"Plot 1": plot1, "Plot 2": plot2}) assert isinstance(divs2, dict) assert all(isinstance(x, str) for x in divs2.keys()) # explict test for OrderedDict (don't replace with dict) _, divs3 = bes.components( OrderedDict([("Plot 1", plot1), ("Plot 2", plot2)])) assert isinstance(divs3, OrderedDict) assert all(isinstance(x, str) for x in divs3.keys())
def test_return_type(self): plot1 = figure() plot1.circle([], []) plot2 = figure() plot2.circle([], []) # This is a testing artefact, users dont' have to do this in practice curdoc().add_root(plot1) curdoc().add_root(plot2) r = bes.components(plot1) assert len(r) == 2 _, divs = bes.components((plot1, plot2)) assert isinstance(divs, tuple) _, divs = bes.components([plot1, plot2]) assert isinstance(divs, tuple) _, divs = bes.components({"Plot 1": plot1, "Plot 2": plot2}) assert isinstance(divs, dict) assert all(isinstance(x, str) for x in divs.keys()) _, divs = bes.components( OrderedDict([("Plot 1", plot1), ("Plot 2", plot2)])) assert isinstance(divs, OrderedDict) assert all(isinstance(x, str) for x in divs.keys())
def test_plot_dict_returned_when_wrap_plot_info_is_false( self, mock_make_id: MagicMock) -> None: doc = Document() plot1 = figure() plot1.circle([], []) doc.add_root(plot1) plot2 = figure() plot2.circle([], []) doc.add_root(plot2) expected_plotdict_1 = RenderRoot(elementid=ID("ID"), id=ID("ID")) expected_plotdict_2 = RenderRoot(elementid=ID("ID"), id=ID("ID")) _, plotdict = bes.components(plot1, wrap_plot_info=False) assert plotdict == expected_plotdict_1 _, plotids = bes.components((plot1, plot2), wrap_plot_info=False) assert plotids == (expected_plotdict_1, expected_plotdict_2) _, plotiddict = bes.components({ 'p1': plot1, 'p2': plot2 }, wrap_plot_info=False) assert plotiddict == { 'p1': expected_plotdict_1, 'p2': expected_plotdict_2 }
def test_output_is_without_script_tag_when_wrap_script_is_false(self, mock_make_id, test_plot): script, div = bes.components(test_plot) html = bs4.BeautifulSoup(script, "lxml") scripts = html.findAll(name='script') assert len(scripts) == 1 script_content = scripts[0].getText() rawscript, div = bes.components(test_plot, wrap_script=False) self.maxDiff = None assert rawscript.strip() == script_content.strip()
def __init__(self, contents, **kwargs): """ Writes out the content as raw text or HTML. :param contents: Bokeh plotting figure. :param kwargs: Optional styling arguments. The `style` keyword argument has special meaning in that it allows styling to be grouped as one argument. It is also useful in case a styling parameter name clashes with a standard block parameter. """ self.resource_deps = [ JScript(script_string=s, name='bokeh_js') for s in JSResources().js_raw ] self.resource_deps += [ Css(css_string=s, name='bokeh_css') for s in CSSResources().css_raw ] super(BokehPlotBlock, self).__init__(**kwargs) if not isinstance(contents, BokehFigure): raise ValueError( "Expected bokeh.plotting.figure.Figure type but got %s", type(contents)) script, div = components(contents) self._contents = script + div
def test_div_attrs(self, test_plot): script, div = bes.components(test_plot) html = bs4.BeautifulSoup(div, "lxml") divs = html.findAll(name='div') assert len(divs) == 1 div = divs[0] assert set(div.attrs) == set(['class', 'id']) assert div.attrs['class'] == ['bk-root'] assert div.text == ''
def test_plot_dict_returned_when_wrap_plot_info_is_false(self, mock_make_id): plot1 = figure() plot1.circle([], []) plot2 = figure() plot2.circle([], []) # This is a testing artefact, users dont' have to do this in practice curdoc().add_root(plot1) curdoc().add_root(plot2) expected_plotdict_1 = {"modelid": plot1.ref["id"], "elementid": "ID", "docid": "ID"} expected_plotdict_2 = {"modelid": plot2.ref["id"], "elementid": "ID", "docid": "ID"} _, plotdict = bes.components(plot1, wrap_plot_info=False) assert plotdict == expected_plotdict_1 _, plotids = bes.components((plot1, plot2), wrap_plot_info=False) assert plotids == (expected_plotdict_1, expected_plotdict_2) _, plotiddict = bes.components({'p1': plot1, 'p2': plot2}, wrap_plot_info=False) assert plotiddict == {'p1': expected_plotdict_1, 'p2': expected_plotdict_2}
def test_plot_dict_returned_when_wrap_plot_info_is_false(self, mock_make_id): doc = Document() plot1 = figure() plot1.circle([], []) doc.add_root(plot1) plot2 = figure() plot2.circle([], []) doc.add_root(plot2) expected_plotdict_1 = RenderRoot(elementid="ID", id="ID") expected_plotdict_2 = RenderRoot(elementid="ID", id="ID") _, plotdict = bes.components(plot1, wrap_plot_info=False) assert plotdict == expected_plotdict_1 _, plotids = bes.components((plot1, plot2), wrap_plot_info=False) assert plotids == (expected_plotdict_1, expected_plotdict_2) _, plotiddict = bes.components({'p1': plot1, 'p2': plot2}, wrap_plot_info=False) assert plotiddict == {'p1': expected_plotdict_1, 'p2': expected_plotdict_2}
def test_div_attrs(self, test_plot) -> None: script, div = bes.components(test_plot) html = bs4.BeautifulSoup(div, "html.parser") divs = html.findAll(name='div') assert len(divs) == 1 div = divs[0] assert set(div.attrs) == set(['class', 'id', 'data-root-id']) assert div.attrs['class'] == ['bk-root'] assert div.attrs['id'] == 'ID' assert div.attrs['data-root-id'] == test_plot.id assert div.string is None
def test_div_attrs(self, test_plot: figure) -> None: _, div = bes.components(test_plot) html = bs4.BeautifulSoup(div, "html.parser") els = html.find_all(name='div') assert len(els) == 1 el = els[0] assert set(el.attrs) == {"class", "id", "data-root-id"} assert el.attrs["class"] == ["bk-root"] assert el.attrs["id"] == "ID" assert el.attrs["data-root-id"] == test_plot.id assert el.string is None
def test_div_attrs(self, test_plot) -> None: script, div = bes.components(test_plot) html = bs4.BeautifulSoup(div, "html.parser") divs = html.findAll(name='div') assert len(divs) == 1 div = divs[0] assert set(div.attrs) == {"class", "id", "data-root-id"} assert div.attrs["class"] == ["bk-root"] assert div.attrs["id"] == "ID" assert div.attrs["data-root-id"] == test_plot.id assert div.string is None
def product_graph(request, cde): item = ProductDetailExp.objects.get(code=cde) c_data = ConsumptionData.objects.filter(productDetail=item) items_list = [] for p in c_data: items_list.append([p.consumptionDate, p.consumptionQty]) items_columns = ['consumptionDate', 'consumptionQty'] items_df = pd.DataFrame(items_list, columns=items_columns) items_df['consumptionQty'] = items_df['consumptionQty'].astype( float) # Convert from str to float plt = figure(width=1200, height=550, title="CONSUMPTION GRAPH", x_axis_type="datetime") plt.line(x=items_df.consumptionDate, y=items_df.consumptionQty, line_color='green') plt.title.text_color = "olive" plt.title.text_font = "times" plt.title.text_font_style = "italic" plt.xaxis.axis_label = "Consumption Quantity" plt.xaxis.axis_line_width = 1 plt.xaxis.axis_line_color = "red" plt.xaxis.axis_label_text_color = "brown" plt.yaxis.axis_label = "Consumption Date" plt.yaxis.axis_line_width = 1 plt.yaxis.axis_line_color = "yellow" plt.yaxis.axis_label_text_color = "red" plt.yaxis.major_label_text_color = "blue" plt.yaxis.major_label_orientation = "vertical" plt.toolbar.autohide = True div, script = components(plt) context = { 'title': 'ANALYSIS|' + str(cde) + 'GRAPH', 'the_div': div, 'the_script': script, 'resources': INLINE.render(), } return render(request, 'analysis/product_graph.html', context)
def test_script_is_utf8_encoded(self, test_plot: figure) -> None: script, _ = bes.components(test_plot) assert isinstance(script, str)
def test_result_attrs(self, test_plot: figure) -> None: script, _ = bes.components(test_plot) html = bs4.BeautifulSoup(script, "html.parser") scripts = html.find_all(name='script') assert len(scripts) == 1 assert scripts[0].attrs == {'type': 'text/javascript'}
def all_current_stock_single_stats(request, cde): item = ProductDetailExp.objects.get(code=cde) c_data = ConsumptionData.objects.filter(productDetail=item) items_list = [] for p in c_data: items_list.append([p.consumptionDate, p.consumptionQty]) items_columns = ['consumptionDate', 'consumptionQty'] items_df = pd.DataFrame(items_list, columns=items_columns) items_df['Date'] = pd.to_datetime(items_df['consumptionDate']) items_df['Year'] = pd.DatetimeIndex(items_df['Date']).year items_df['Month'] = pd.DatetimeIndex(items_df['Date']).strftime("%b") items_df['Day'] = pd.DatetimeIndex(items_df['Date']).strftime("%a") items_df['consumptionQty'] = items_df['consumptionQty'].astype( float) # Convert from str to float items_df['Year'] = items_df['Year'].apply(str) # From integer to string plt = figure(width=500, height=400, title="CONSUMPTION GRAPHS", x_axis_type="datetime") plt.line(x=items_df.consumptionDate, y=items_df.consumptionQty, line_color='green') plt.title.text_color = "olive" plt.title.text_font = "times" plt.title.text_font_style = "italic" plt.xaxis.axis_label = "Consumption Date" plt.xaxis.axis_line_width = 1 plt.xaxis.axis_line_color = "red" plt.xaxis.axis_label_text_color = "brown" plt.yaxis.axis_label = "Consumption Quantity" plt.yaxis.axis_line_width = 1 plt.yaxis.axis_line_color = "yellow" plt.yaxis.axis_label_text_color = "red" plt.yaxis.major_label_text_color = "blue" plt.yaxis.major_label_orientation = "vertical" plt.toolbar.autohide = True by_year = items_df.groupby('Year')['consumptionQty'].mean() by_month = items_df.groupby('Month')['consumptionQty'].mean() by_year_df = pd.DataFrame(by_year).reset_index().sort_values( by='consumptionQty', ascending=True) by_month_df = pd.DataFrame(by_month).reset_index().sort_values( by='consumptionQty', ascending=True) years = by_year_df['Year'].unique() source1 = ColumnDataSource(data=by_year_df) plt1 = figure(title="AVERAGE YEARLY CONSUMPTION", y_range=by_year_df['Year'], plot_height=350, plot_width=500, toolbar_location="left", x_axis_label="Mean", y_axis_label="Year", tooltips=[("Year", "@Year"), ("Mean", "@consumptionQty")]) plt1.hbar(y='Year', right='consumptionQty', height=0.7, source=source1, color=factor_cmap('Year', Spectral5, years)) months = by_month_df['Month'].unique() source2 = ColumnDataSource(data=by_month_df) plt2 = figure(title="AVERAGE MONTHLY CONSUMPTION", y_range=by_month_df['Month'], plot_height=350, plot_width=500, toolbar_location="left", x_axis_label="Mean", y_axis_label="Months", tooltips=[("Month", "@Month"), ("Mean", "@consumptionQty")]) plt1.x_range.start = 0 plt1.outline_line_color = "brown" plt1.xgrid.grid_line_color = None plt1.ygrid.grid_line_color = None plt1.toolbar.autohide = True plt1.outline_line_color = None plt2.hbar(y='Month', right='consumptionQty', height=0.7, source=source2, color=factor_cmap('Month', Set3_12, months)) plt2.x_range.start = 0 plt2.outline_line_color = "brown" plt2.xgrid.grid_line_color = None plt2.ygrid.grid_line_color = None plt2.toolbar.autohide = True plt2.outline_line_color = None plots = Column(plt, plt2, plt1) div, script = components(plots) s_type = 'STATISTICS' qty_stats = calc_stats(item) context = { 'title': 'ANALYSIS |STATS|' + str(cde), 'productData': item, 'qty_stats': qty_stats, 's_type': s_type, 'the_div': div, 'the_script': script, 'resources': INLINE.render(), } return render(request, 'analysis/visuals_product.html', context)
def product_visual(request): products = ProductDetailExp.objects.all() if request.method == 'POST': var_stat = request.POST['stat'] var_time = request.POST['time'] item = ProductDetailExp.objects.get(code=request.POST['productSelect']) data = ProductDetailExp.objects.get(code=request.POST['productSelect']) c_data = ConsumptionData.objects.filter(productDetail=item) items_list = [] for p in c_data: items_list.append([p.consumptionDate, p.consumptionQty]) items_columns = ['consumptionDate', 'consumptionQty'] items_df = pd.DataFrame(items_list, columns=items_columns) items_df['Date'] = pd.to_datetime(items_df['consumptionDate']) items_df['Year'] = pd.DatetimeIndex(items_df['Date']).year items_df['Month'] = pd.DatetimeIndex(items_df['Date']).strftime("%b") items_df['Day'] = pd.DatetimeIndex(items_df['Date']).strftime("%a") items_df['consumptionQty'] = items_df['consumptionQty'].astype( float) # Convert from str to float items_df['Year'] = items_df['Year'].apply( str) # From integer to string if var_stat == 'stats': s_type = 'STATISTICS' qty_stats = calc_stats(data) plt = figure(width=400, height=400, title="CONSUMPTION GRAPH", x_axis_type="datetime") plt.line(x=items_df.consumptionDate, y=items_df.consumptionQty, line_color='green') plt.title.text_color = "olive" plt.title.text_font = "times" plt.title.text_font_style = "italic" plt.xaxis.axis_label = "Consumption Quantity" plt.xaxis.axis_line_width = 1 plt.xaxis.axis_line_color = "red" plt.xaxis.axis_label_text_color = "brown" plt.yaxis.axis_label = "Consumption Date" plt.yaxis.axis_line_width = 1 plt.yaxis.axis_line_color = "yellow" plt.yaxis.axis_label_text_color = "red" plt.yaxis.major_label_text_color = "blue" plt.yaxis.major_label_orientation = "vertical" plt.toolbar.autohide = True div, script = components(plt) context = { 'title': 'ANALYSIS | PRODUCTS', 'allProducts': products, 'productData': item, 'qty_stats': qty_stats, 's_type': s_type, 'the_div': div, 'the_script': script, 'resources': INLINE.render(), } return render(request, 'analysis/visuals.html', context) elif var_stat == 'Sum': s_type = 'SUM' if var_time == 'Year': v_type = 'Year' by_group = items_df.groupby('Year')['consumptionQty'].sum() result_df = pd.DataFrame(by_group).reset_index() elif var_time == 'YMonth': v_type = 'YMonth' by_group = items_df.groupby(['Year', 'Month'])['consumptionQty'].sum() result_df = pd.DataFrame(by_group).reset_index() elif var_time == 'Month': v_type = 'Month' by_group = items_df.groupby('Month')['consumptionQty'].sum() result_df = pd.DataFrame(by_group).reset_index() else: v_type = 'Day' # For the day json_records = result_df.to_json(orient='records') data = [] data = json.loads(json_records) context = { 'title': 'ANALYSIS | PRODUCTS', 'allProducts': products, 'productData': c_data, 's_type': s_type, 'v_type': v_type, 'data_df': data, } return render(request, 'analysis/visuals.html', context) else: s_type = 'MEAN' if var_time == 'Year': v_type = 'Year' by_group = items_df.groupby('Year')['consumptionQty'].mean() result_df = pd.DataFrame(by_group).reset_index() elif var_time == 'YMonth': v_type = 'YMonth' by_group = items_df.groupby(['Year', 'Month' ])['consumptionQty'].mean() result_df = pd.DataFrame(by_group).reset_index() elif var_time == 'Month': v_type = 'Month' by_group = items_df.groupby('Month')['consumptionQty'].mean() result_df = pd.DataFrame(by_group).reset_index() else: v_type = 'Day' json_records = result_df.to_json(orient='records') data = [] data = json.loads(json_records) context = { 'title': 'ANALYSIS | PRODUCTS', 'allProducts': products, 'productData': c_data, 's_type': s_type, 'v_type': v_type, 'data_df': data, } return render(request, 'analysis/visuals.html', context) context = { 'title': 'ANALYSIS | PRODUCTS', 'allProducts': products, } return render(request, 'analysis/visuals.html', context)
def test_output_is_without_script_tag_when_wrap_script_is_false( self, test_plot): script, div = bes.components(test_plot) html = bs4.BeautifulSoup(script, "lxml") scripts = html.findAll(name='script') assert len(scripts) == 1
def test_script_is_utf8_encoded(self, test_plot): script, div = bes.components(test_plot) assert isinstance(script, str)
def test_result_attrs(self, test_plot): script, div = bes.components(test_plot) html = bs4.BeautifulSoup(script, "lxml") scripts = html.findAll(name='script') assert len(scripts) == 1 assert scripts[0].attrs == {'type': 'text/javascript'}
def admin_dashboard(request): products = ProductDetailExp.objects.all() items = [] items_columns = [ 'CODE', 'DESCRIPTION', 'VEN', 'PRICE', 'CURRENT_STOCK', 'STAT', ] for p in products: data = get_initial_graphs_data(p) if data is not None: items.append([ data['code'], data['description'], data['ven'], data['price'], data['current_stock'], data['stat'] ]) products_df = pd.DataFrame(items, columns=items_columns) df = get_df_to_make_graphs(products_df) df1 = df.reset_index() factors = np.array(df1.CODE) factors2 = ['V', 'E', 'N'] source = ColumnDataSource(data=df1) tools = "pan,wheel_zoom, box_zoom,reset,box_select,lasso_select, hover" p = figure( title= "Average Consumption of Drugs At Fort Portal Regional Referral Hospital", y_range=factors, plot_height=2000, plot_width=2000, tools=tools, toolbar_location="left", x_axis_label="MEAN CONSUMPTION", y_axis_label="PRODUCT CODE", tooltips=[("PRODUCT CODE", "@CODE"), ("DESCRIPTION", "@DESCRIPTION"), ("VEN", "@VEN"), ("PRICE", "@PRICE"), ("CURRENT STOCK", "@CURRENT_STOCK"), ("MEAN VALUE", "@STAT")]) p.hbar(y='CODE', right='STAT', height=0.7, source=source, color=factor_cmap('VEN', ['red', 'yellow', 'black'], factors2), legend_field='VEN') p.title.text_color = "olive" p.title.text_font = "times" p.title.text_font_style = "italic" p.xaxis.major_label_orientation = 1.5 p.outline_line_color = "brown" p.xgrid.grid_line_color = None p.ygrid.grid_line_color = None p.x_range.start = 0 p.legend.location = "top_center" div, script = components(p) context = { 'the_div': div, 'the_script': script, 'resources': INLINE.render(), } return render(request, 'analysis/productdashboard.html', context)
def test_output_is_without_script_tag_when_wrap_script_is_false(self, test_plot): script, div = bes.components(test_plot) html = bs4.BeautifulSoup(script, "lxml") scripts = html.findAll(name='script') assert len(scripts) == 1
def test_quoting(self, test_plot: figure) -> None: script, _ = bes.components(test_plot) assert """ not in script assert "'foo'" not in script assert "'foo'" in script
def get_graphs_1_month_consumption(request): if request.method == 'GET': stat = request.GET.get('stat') else: stat = 'mean' products = ProductDetailExp.objects.all() items = [] items_columns = [ 'CODE', 'DESCRIPTION', 'VEN', 'PRICE', 'CURRENT_STOCK', 'STAT' ] for p in products: data = get_graphs_consumption_method_1_month_cycle(p, stat) if data is not None: items.append([ data['code'], data['description'], data['ven'], data['PRICE'], data['current_stock'], data['stat'] ]) products_df = pd.DataFrame(items, columns=items_columns) df = get_df_to_make_graphs(products_df) df1 = df.reset_index() factors = np.array(df1.CODE) factors2 = ['V', 'E', 'N'] if stat is None: stat = 'mean' source = ColumnDataSource(data=df1) tools = "pan,wheel_zoom, box_zoom,reset,box_select,lasso_select, hover" p = figure(title=str(stat), y_range=factors, plot_height=2000, plot_width=2000, tools=tools, toolbar_location="left", x_axis_label=str(stat), y_axis_label="PRODUCT CODE", tooltips=[("PRODUCT CODE", "@CODE"), ("DESCRIPTION", "@DESCRIPTION"), ("VEN", "@VEN"), (str(stat), "@STAT")]) p.hbar(y='CODE', right='STAT', height=0.7, source=source, color=factor_cmap('VEN', ['red', 'yellow', 'black'], factors2), legend_field='VEN') p.title.text_color = "olive" p.title.text_font = "times" p.title.text_font_style = "italic" p.xaxis.major_label_orientation = 1.5 p.outline_line_color = "brown" p.xgrid.grid_line_color = None p.ygrid.grid_line_color = None p.x_range.start = 0 # p.xaxis.visible = False p.legend.location = "top_center" div, script = components(p) context = { 'the_div': div, 'the_script': script, 'resources': INLINE.render(), } return render(request, 'analysis/graphs_1_c_method.html', context)
def test_output_is_without_script_tag_when_wrap_script_is_false( self, test_plot: figure) -> None: script, _ = bes.components(test_plot) html = bs4.BeautifulSoup(script, "html.parser") scripts = html.find_all(name='script') assert len(scripts) == 1