Example #1
0
def pages_pointschart():
    match = sme.EventDal.get_current_match()
    os.chdir(sc.output_path())
    chart = point_chart()
    div1 = blt.WidgetBox(bmw.Div(text='<a href="index.html">Home Page</a>'))
    div2 = blt.WidgetBox(
        bmw.Div(text='<h1>Points Chart</h1>' + 'updated at match:' + match))
    bokeh.io.output_file('pointschart.html')
    col = blt.column([div1, div2, chart])
    title = 'Ranking Table: Match ' + match
    # LocalResource needed to load JS and CSS files from local folder
    res = server.view.bokeh.LocalResource(
        os.path.join(sc.output_path(), 'static'))
    bokeh.io.save(col, title=title, resources=res)
    def __init__(self, position_plotter, duty_plotter, clear_button,
                 toggle_button, title, nest_level):
        """Initialize member variables."""
        super().__init__()

        self.position_plot = position_plotter.make_document_layout()
        self.duty_plot = duty_plotter.make_document_layout()
        self.duty_plot.duty_fig.x_range = self.position_plot.position_fig.x_range
        self.clear_button = clear_button.make_document_layout()
        self.toggle_button = toggle_button.make_document_layout()

        heading_level = 1 + nest_level
        column = []
        if title:
            column += [
                layouts.widgetbox([
                    widgets.Div(text='<h{}>{}</h{}>'.format(
                        heading_level, title, heading_level))
                ])
            ]
        column += [
            layouts.row([
                layouts.widgetbox([self.clear_button]),
                layouts.widgetbox([self.toggle_button])
            ]), self.position_plot.layout, self.duty_plot.layout
        ]
        self.column_layout = layouts.column(column)
Example #3
0
def main():
    history = load_data(
        '/home/mark/Dev/BachelorThesis/RegnetCheckpoints/[5][CROPPED][Matricies].pkl'
    )
    plots = list()

    title = 'Regnet results random dataset'
    title_div = widgets.Div(text="""<h1>{}</h1>""".format(title),
                            width=200,
                            height=20)
    plots.extend([title_div, None])

    plot1 = draw_euclidean_loss(history)
    plots.append(plot1)

    plot2 = draw_mae(history)
    plots.append(plot2)

    plot3 = draw_r2_score(history)
    plots.append(plot3)

    btn = make_callback()
    plots.extend([None, btn])

    reports_path = paths.reports.regnet()
    reports_path = reports_path.joinpath('figures', '{}.html'.format(title))
    reports_path.parent.mkdir(exist_ok=True, parents=True)

    plt.output_file(reports_path, title=title)
    plt.show(gridplot(children=plots, ncols=2, sizing_mode='scale_width'))
Example #4
0
def pages_6t(matches, num_matches=12):
    os.chdir(os.path.join(sc.output_path(), 'sixteam'))
    for match in matches:
        bokeh.io.output_file('6t' + match + '.html')
        div_top = bmw.Div(text='''
            <H1>Match {} Six Team Chart</H1>
        '''.format(match))
        div_all = bmw.Div(text='<h3>All Matches</h3>')
        row_all = blt.row(total_6t(match, num_matches))
        div_l3 = bmw.Div(text='<h3>Last 3 Matches</h3>')
        row_l3 = blt.row(total_6t(match, 3))

        col = blt.Column(div_top, div_all, row_all, div_l3, row_l3)
        title = 'Six Team Display: Match ' + match
        # LocalResource needed to load JS and CSS files from local folder
        res = server.view.bokeh.LocalResource(
            os.path.join(sc.output_path(), 'static'))
        bokeh.io.save(col, title=title, resources=res)
def pages_rankingtable():
    df_all = ranking_df()
    autoTable = ranking_auto(df_all)
    generalTable = ranking_general(df_all)
    match = sme.EventDal.get_current_match()
    tab1 = bmw.Panel(child=generalTable, title='General Table')
    tab2 = bmw.Panel(child=autoTable, title='Auto Table')
    tabs = bmw.Tabs(tabs=[tab1, tab2])
    div1 = blt.WidgetBox(bmw.Div(text='<a href="index.html">Home Page</a>'))
    div2 = blt.WidgetBox(
        bmw.Div(text='<h1>Ranking Table</h1>' + 'updated at match:' + match))
    os.chdir(sc.output_path())
    bokeh.io.output_file('rankingtable.html')
    col = blt.column([div1, div2, tabs])
    title = 'Ranking Table: Match ' + match
    # LocalResource needed to load JS and CSS files from local folder
    res = server.view.bokeh_res.LocalResource(
        os.path.join(sc.output_path(), 'static'))
    bokeh.io.save(col, title=title, resources=res)
    def __init__(self, plotter, feedback_controller, title):
        """Initialize member variables."""
        super().__init__()

        self.plotter = plotter.make_document_layout()
        self.feedback_controller = feedback_controller.make_document_layout()

        self.column_layout = layouts.column([
            layouts.widgetbox([widgets.Div(text='<h1>{}</h1>'.format(title))]),
            self.plotter.layout,
            self.feedback_controller.layout
        ])
Example #7
0
def total_6t(match, num_matches=12):
    try:
        tasks = [
            'csHatch', 'rocketHatch1', 'rocketHatch2', 'rocketHatch3',
            'getHatch', 'getCargo', 'csCargo', 'rocketCargo1', 'rocketCargo2',
            'rocketCargo3'
        ]
        meas, sched, num_m = get_df_6t()
        cdsr = cds_new_6t("red", match, meas, sched, tasks, num_m, num_matches)
        cdsb = cds_new_6t("blue", match, meas, sched, tasks, num_m,
                          num_matches)
        rteams = cdsr.column_names[1:]
        bteams = cdsb.column_names[1:]

        hatch_cols = [
            'totalHatches', 'totalCargo', 'csHatch', 'rocketHatch1',
            'rocketHatch2', 'rocketHatch3', 'csCargo', 'rocketCargo1',
            'rocketCargo2', 'rocketCargo3'
        ]

        plt_all = plt.figure(title='Six Team: Match ' + match,
                             x_range=hatch_cols,
                             plot_width=800,
                             plot_height=350)

        plt_all.vbar_stack(rteams,
                           x=btransform.dodge('task',
                                              -0.17,
                                              range=plt_all.x_range),
                           width=0.3,
                           source=cdsr,
                           color=bpalettes.Reds3,
                           legend=[" " + x for x in rteams])
        plt_all.vbar_stack(bteams,
                           x=btransform.dodge('task',
                                              0.17,
                                              range=plt_all.x_range),
                           width=0.3,
                           source=cdsb,
                           color=bpalettes.Blues3,
                           legend=[" " + x for x in bteams])
    except:
        return bmw.Div(text="Chart construction Error")
    return plt_all
    def __init__(self,
                 limits_panel,
                 timeouts_panel,
                 pid_panel,
                 errors_plotter,
                 errors_plotter_clear_button,
                 title,
                 nest_level,
                 width=960):
        """Initialize member variables."""
        super().__init__()

        self.limits_panel = limits_panel.make_document_layout()
        self.timeouts_panel = timeouts_panel.make_document_layout()
        self.pid_panel = pid_panel.make_document_layout()
        self.errors_plotter = errors_plotter.make_document_layout()
        self.errors_plotter_clear_button = \
            errors_plotter_clear_button.make_document_layout()

        heading_level = 1 + nest_level
        column = []
        if title:
            column += [
                layouts.widgetbox([
                    widgets.Div(text='<h{}>Feedback Controller</h{}>'.format(
                        heading_level, heading_level))
                ])
            ]
        column += [
            widgets.Tabs(tabs=[
                widgets.Panel(title='Limits', child=self.limits_panel.layout),
                widgets.Panel(title='Timeouts',
                              child=self.timeouts_panel.layout),
                widgets.Panel(title='PID', child=self.pid_panel.layout),
                widgets.Panel(title='Errors',
                              child=layouts.column([
                                  self.errors_plotter.layout,
                                  self.errors_plotter_clear_button
                              ]))
            ],
                         width=width)
        ]
        self.column_layout = layouts.column(column)
Example #9
0
def pages_1t(teams):
    try:
        for team in teams:
            os.chdir(server.config.output_path() + r'/oneteam')
            bokeh.io.output_file('1t{0}.html'.format(team))
            title = 'One Team Display: Match ' + team
            graph = oneteam_plot(team)
            # LocalResource needed to load JS and CSS files from local folder
            res = server.view.bokeh_res.LocalResource(
                os.path.join(server.config.output_path(), 'static'))
            div = blt.WidgetBox(
                bwd.Div(
                    text=
                    '<h1>One Team Graphs</h1><a href="../index.html"><h4>Main Page</h4></a>'
                    + '<h3> Last Updated at Match: {} </h3>'.format(
                        sme.EventDal.get_previous_match())))
            col = blt.column(div, graph)
            bokeh.io.save(col, title=title, resources=res)
    except:
        print("Wasn't able to make this chart")
Example #10
0
def ranking_general(df_all):
    try:
        Rank_cds = bmodels.ColumnDataSource(df_all)
        fixed2 = bmw.NumberFormatter(format='0.00')
        cols = [
            bmw.TableColumn(field='team', title='Team'),
            bmw.TableColumn(field='avgCargo',
                            title='Average Cargo',
                            formatter=fixed2),
            bmw.TableColumn(field='avgHatch',
                            title='Average Hatches',
                            formatter=fixed2),
            bmw.TableColumn(field='avgHatchPoints',
                            title='Hatch Points',
                            formatter=fixed2),
            bmw.TableColumn(field='avgCargoPoints',
                            title='Cargo Points',
                            formatter=fixed2),
            bmw.TableColumn(field='avgPoints',
                            title='Average Points',
                            formatter=fixed2),
            bmw.TableColumn(field='climb1',
                            title='Total Lvl1 Climbs',
                            formatter=fixed2),
            bmw.TableColumn(field='climb2',
                            title='Total Lvl2 Climbs',
                            formatter=fixed2),
            bmw.TableColumn(field='climb3',
                            title='Total Lvl3 Climbs',
                            formatter=fixed2),
            bmw.TableColumn(field='Defense',
                            title='Avg Defense',
                            formatter=fixed2),
        ]
        data_table = bmw.DataTable(source=Rank_cds,
                                   columns=cols,
                                   width=900,
                                   height=380)
    except:
        return bmw.Div(text="Error with general ranking table")
    return data_table
Example #11
0
def ranking_auto(df_all):
    try:
        Rank_cds = bmodels.ColumnDataSource(df_all)
        fixed2 = bmw.NumberFormatter(format='0.00')
        cols = [
            bmw.TableColumn(field='team', title='Team'),
            bmw.TableColumn(field='level2hab',
                            title='Move lvl2',
                            formatter=fixed2),
            bmw.TableColumn(field='level1hab',
                            title='Move lvl1',
                            formatter=fixed2),
            bmw.TableColumn(field='dontMove',
                            title='Don\'t Move',
                            formatter=fixed2),
            bmw.TableColumn(field='rocketHatch',
                            title='Rocket Hatch',
                            formatter=fixed2),
            bmw.TableColumn(field='frontBay',
                            title='CS Front Hatch',
                            formatter=fixed2),
            bmw.TableColumn(field='closeHatch',
                            title='CS Close Hatch',
                            formatter=fixed2),
            bmw.TableColumn(field='centerHatch',
                            title='CS Center Hatch',
                            formatter=fixed2),
            bmw.TableColumn(field='farHatch',
                            title='CS Far Hatch',
                            formatter=fixed2),
        ]
        data_table = bmw.DataTable(source=Rank_cds,
                                   columns=cols,
                                   width=900,
                                   height=380)
    except:
        return bmw.Div(text="Error with auto ranking table")
    return data_table
Example #12
0
def grab_HTML():
    global introPara
    global backgroundPara
    global foldPara
    global dmPara
    global ScatterPara
    global LastPara

    try:
        #Load all the HTML paragraphs as bokeh objects
        with open(
                "PsrSigSim_TeachingApp/HTMLBits/introParagraph.html") as file:
            s = file.read()
            introPara = widgets.Div(text=s)

        with open("PsrSigSim_TeachingApp/HTMLBits/backgroundParagraph.html"
                  ) as file:
            s = file.read()
            backgroundPara = widgets.Div(text=s)

        with open("PsrSigSim_TeachingApp/HTMLBits/foldingParagraph.html"
                  ) as file:
            s = file.read()
            foldPara = widgets.Div(text=s)

        with open("PsrSigSim_TeachingApp/HTMLBits/dispersionParagraph.html"
                  ) as file:
            s = file.read()
            dmPara = widgets.Div(text=s)

        with open("PsrSigSim_TeachingApp/HTMLBits/scatteringParagraph.html"
                  ) as file:
            s = file.read()
            ScatterPara = widgets.Div(text=s)

        with open(
                "PsrSigSim_TeachingApp/HTMLBits/endingParagraph.html") as file:
            s = file.read()
            LastPara = widgets.Div(text=s)

    except:
        print("HTML Files not found")
        exit()
Example #13
0
    def tool_handler(self, doc):
        from bokeh import events
        from bokeh.layouts import row, column, widgetbox
        from bokeh.models.mappers import LinearColorMapper
        from bokeh.models import widgets
        from bokeh.plotting import figure

        if len(self.arr.shape) != 2:
            raise AnalysisError(
                'Cannot use the band tool on non image-like spectra')

        self.data_for_display = self.arr
        x_coords, y_coords = self.data_for_display.coords[
            self.data_for_display.dims[0]], self.data_for_display.coords[
                self.data_for_display.dims[1]]

        default_palette = self.default_palette

        self.app_context.update({
            'data': self.arr,
            'data_range': {
                'x': (np.min(x_coords.values), np.max(x_coords.values)),
                'y': (np.min(y_coords.values), np.max(y_coords.values)),
            },
        })

        figures, plots = self.app_context['figures'], self.app_context['plots']

        self.cursor = [
            np.mean(self.data_range['x']),
            np.mean(self.data_range['y'])
        ]

        self.color_maps['main'] = LinearColorMapper(
            default_palette,
            low=np.min(self.data_for_display.values),
            high=np.max(self.data_for_display.values),
            nan_color='black')

        main_tools = ["wheel_zoom", "tap", "reset"]
        main_title = '{} Tool: WARNING Unidentified'.format(
            self.analysis_fn.__name__)

        try:
            main_title = '{} Tool: {}'.format(
                self.analysis_fn.__name__, self.data_for_display.S.label[:60])
        except:
            pass

        figures['main'] = figure(tools=main_tools,
                                 plot_width=self.app_main_size,
                                 plot_height=self.app_main_size,
                                 min_border=10,
                                 min_border_left=50,
                                 toolbar_location='left',
                                 x_axis_location='below',
                                 y_axis_location='right',
                                 title=main_title,
                                 x_range=self.data_range['x'],
                                 y_range=self.data_range['y'])
        figures['main'].xaxis.axis_label = self.data_for_display.dims[0]
        figures['main'].yaxis.axis_label = self.data_for_display.dims[1]
        figures['main'].toolbar.logo = None
        figures['main'].background_fill_color = "#fafafa"
        plots['main'] = figures['main'].image(
            [self.data_for_display.values.T],
            x=self.app_context['data_range']['x'][0],
            y=self.app_context['data_range']['y'][0],
            dw=self.app_context['data_range']['x'][1] -
            self.app_context['data_range']['x'][0],
            dh=self.app_context['data_range']['y'][1] -
            self.app_context['data_range']['y'][0],
            color_mapper=self.app_context['color_maps']['main'])

        # Create the bottom marginal plot
        bottom_marginal = self.data_for_display.sel(**dict(
            [[self.data_for_display.dims[1], self.cursor[1]]]),
                                                    method='nearest')
        bottom_marginal_original = self.arr.sel(**dict(
            [[self.data_for_display.dims[1], self.cursor[1]]]),
                                                method='nearest')
        figures['bottom_marginal'] = figure(
            plot_width=self.app_main_size,
            plot_height=200,
            title=None,
            x_range=figures['main'].x_range,
            y_range=(np.min(bottom_marginal.values),
                     np.max(bottom_marginal.values)),
            x_axis_location='above',
            toolbar_location=None,
            tools=[])
        plots['bottom_marginal'] = figures['bottom_marginal'].line(
            x=bottom_marginal.coords[self.data_for_display.dims[0]].values,
            y=bottom_marginal.values)
        plots['bottom_marginal_original'] = figures['bottom_marginal'].line(
            x=bottom_marginal_original.coords[self.arr.dims[0]].values,
            y=bottom_marginal_original.values,
            line_color='red')

        # Create the right marginal plot
        right_marginal = self.data_for_display.sel(**dict(
            [[self.data_for_display.dims[0], self.cursor[0]]]),
                                                   method='nearest')
        right_marginal_original = self.arr.sel(**dict(
            [[self.data_for_display.dims[0], self.cursor[0]]]),
                                               method='nearest')
        figures['right_marginal'] = figure(
            plot_width=200,
            plot_height=self.app_main_size,
            title=None,
            y_range=figures['main'].y_range,
            x_range=(np.min(right_marginal.values),
                     np.max(right_marginal.values)),
            y_axis_location='left',
            toolbar_location=None,
            tools=[])
        plots['right_marginal'] = figures['right_marginal'].line(
            y=right_marginal.coords[self.data_for_display.dims[1]].values,
            x=right_marginal.values)
        plots['right_marginal_original'] = figures['right_marginal'].line(
            y=right_marginal_original.coords[
                self.data_for_display.dims[1]].values,
            x=right_marginal_original.values,
            line_color='red')

        # add lines
        self.add_cursor_lines(figures['main'])
        _ = figures['main'].multi_line(xs=[],
                                       ys=[],
                                       line_color='white',
                                       line_width=1)  # band lines

        # prep the widgets for the analysis function
        signature = inspect.signature(self.analysis_fn)

        # drop the first which has to be the input data, we can revisit later if this is too limiting
        parameter_names = list(signature.parameters)[1:]
        named_widgets = dict(zip(parameter_names, self.widget_specification))
        built_widgets = {}

        def update_marginals():
            right_marginal_data = self.data_for_display.sel(**dict(
                [[self.data_for_display.dims[0], self.cursor[0]]]),
                                                            method='nearest')
            bottom_marginal_data = self.data_for_display.sel(**dict(
                [[self.data_for_display.dims[1], self.cursor[1]]]),
                                                             method='nearest')
            plots['bottom_marginal'].data_source.data = {
                'x': bottom_marginal_data.coords[
                    self.data_for_display.dims[0]].values,
                'y': bottom_marginal_data.values,
            }
            plots['right_marginal'].data_source.data = {
                'y': right_marginal_data.coords[
                    self.data_for_display.dims[1]].values,
                'x': right_marginal_data.values,
            }

            right_marginal_data = self.arr.sel(**dict(
                [[self.data_for_display.dims[0], self.cursor[0]]]),
                                               method='nearest')
            bottom_marginal_data = self.arr.sel(**dict(
                [[self.data_for_display.dims[1], self.cursor[1]]]),
                                                method='nearest')
            plots['bottom_marginal_original'].data_source.data = {
                'x': bottom_marginal_data.coords[
                    self.data_for_display.dims[0]].values,
                'y': bottom_marginal_data.values,
            }
            plots['right_marginal_original'].data_source.data = {
                'y': right_marginal_data.coords[
                    self.data_for_display.dims[1]].values,
                'x': right_marginal_data.values,
            }
            figures['bottom_marginal'].y_range.start = np.min(
                bottom_marginal_data.values)
            figures['bottom_marginal'].y_range.end = np.max(
                bottom_marginal_data.values)
            figures['right_marginal'].x_range.start = np.min(
                right_marginal_data.values)
            figures['right_marginal'].x_range.end = np.max(
                right_marginal_data.values)

        def click_main_image(event):
            self.cursor = [event.x, event.y]
            update_marginals()

        error_msg = widgets.Div(text='')

        @Debounce(0.25)
        def update_data_for_display():
            try:
                self.data_for_display = self.analysis_fn(
                    self.arr, *[
                        built_widgets[p].value for p in parameter_names
                        if p in built_widgets
                    ])
                error_msg.text = ''
            except Exception as e:
                error_msg.text = '{}'.format(e)

            # flush + update
            update_marginals()
            plots['main'].data_source.data = {
                'image': [self.data_for_display.values.T]
            }

        def update_data_change_wrapper(attr, old, new):
            if old != new:
                update_data_for_display()

        for parameter_name in named_widgets.keys():
            specification = named_widgets[parameter_name]

            widget = None
            if specification == int:
                widget = widgets.Slider(start=-20,
                                        end=20,
                                        value=0,
                                        title=parameter_name)
            if specification == float:
                widget = widgets.Slider(start=-20,
                                        end=20,
                                        value=0.,
                                        step=0.1,
                                        title=parameter_name)

            if widget is not None:
                built_widgets[parameter_name] = widget
                widget.on_change('value', update_data_change_wrapper)

        update_main_colormap = self.update_colormap_for('main')

        self.app_context['run'] = lambda x: x

        main_color_range_slider = widgets.RangeSlider(start=0,
                                                      end=100,
                                                      value=(
                                                          0,
                                                          100,
                                                      ),
                                                      title='Color Range')

        # Attach callbacks
        main_color_range_slider.on_change('value', update_main_colormap)

        figures['main'].on_event(events.Tap, click_main_image)

        layout = row(
            column(figures['main'], figures['bottom_marginal']),
            column(figures['right_marginal']),
            column(
                widgetbox(*[
                    built_widgets[p] for p in parameter_names
                    if p in built_widgets
                ]),
                widgetbox(
                    self._cursor_info,
                    main_color_range_slider,
                    error_msg,
                )))

        doc.add_root(layout)
        doc.title = 'Band Tool'
Example #14
0
def build_widgets(df_source, cols, defaults, init_load=False, init_config={}):
    '''
    Use a dataframe and its columns to set widget options. Widget values may
    be set by URL parameters via init_config.

    Args:
        df_source (pandas dataframe): Dataframe of the csv source.
        cols (dict): Keys are categories of columns of df_source, and values are a list of columns of that category.
        defaults (dict): Keys correspond to widgets, and values (str) are the default values of those widgets.
        init_load (boolean, optional): If this is the initial page load, then this will be True, else False.
        init_config (dict): Initial widget configuration passed via URL.

    Returns:
        wdg (ordered dict): Dictionary of bokeh.model.widgets.
    '''
    #Add widgets
    wdg = collections.OrderedDict()
    wdg['data'] = bmw.TextInput(title='Data Source (required)', value=defaults['data_source'], css_classes=['wdgkey-data'])
    wdg['x_dropdown'] = bmw.Div(text='X-Axis (required)', css_classes=['x-dropdown'])
    wdg['x'] = bmw.Select(title='X-Axis (required)', value=defaults['x'], options=['None'] + cols['all'], css_classes=['wdgkey-x', 'x-drop'])
    wdg['x_group'] = bmw.Select(title='Group X-Axis By', value=defaults['x_group'], options=['None'] + cols['seriesable'], css_classes=['wdgkey-x_group', 'x-drop'])
    wdg['y_dropdown'] = bmw.Div(text='Y-Axis (required)', css_classes=['y-dropdown'])
    wdg['y'] = bmw.Select(title='Y-Axis (required)', value=defaults['y'], options=['None'] + cols['all'], css_classes=['wdgkey-y', 'y-drop'])
    wdg['y_agg'] = bmw.Select(title='Y-Axis Aggregation', value='Sum', options=AGGREGATIONS, css_classes=['wdgkey-y_agg', 'y-drop'])
    wdg['series_dropdown'] = bmw.Div(text='Series', css_classes=['series-dropdown'])
    wdg['series'] = bmw.Select(title='Separate Series By', value=defaults['series'], options=['None'] + cols['seriesable'],
        css_classes=['wdgkey-series', 'series-drop'])
    wdg['series_legend'] = bmw.Div(text='', css_classes=['series-drop'])
    wdg['explode_dropdown'] = bmw.Div(text='Explode', css_classes=['explode-dropdown'])
    wdg['explode'] = bmw.Select(title='Explode By', value=defaults['explode'], options=['None'] + cols['seriesable'], css_classes=['wdgkey-explode', 'explode-drop'])
    wdg['explode_group'] = bmw.Select(title='Group Exploded Charts By', value=defaults['explode_group'], options=['None'] + cols['seriesable'],
        css_classes=['wdgkey-explode_group', 'explode-drop'])
    wdg['filters'] = bmw.Div(text='Filters', css_classes=['filters-dropdown'])
    for j, col in enumerate(cols['filterable']):
        val_list = [str(i) for i in sorted(df_source[col].unique().tolist())]
        wdg['heading_filter_'+str(j)] = bmw.Div(text=col, css_classes=['filter-head'])
        wdg['filter_'+str(j)] = bmw.CheckboxGroup(labels=val_list, active=list(range(len(val_list))), css_classes=['wdgkey-filter_'+str(j), 'filter'])
    wdg['update'] = bmw.Button(label='Update Filters', button_type='success', css_classes=['filters-update'])
    wdg['adjustments'] = bmw.Div(text='Plot Adjustments', css_classes=['adjust-dropdown'])
    wdg['chart_type'] = bmw.Select(title='Chart Type', value=defaults['chart_type'], options=CHARTTYPES, css_classes=['wdgkey-chart_type', 'adjust-drop'])
    wdg['plot_width'] = bmw.TextInput(title='Plot Width (px)', value=str(PLOT_WIDTH), css_classes=['wdgkey-plot_width', 'adjust-drop'])
    wdg['plot_height'] = bmw.TextInput(title='Plot Height (px)', value=str(PLOT_HEIGHT), css_classes=['wdgkey-plot_height', 'adjust-drop'])
    wdg['plot_title'] = bmw.TextInput(title='Plot Title', value='', css_classes=['wdgkey-plot_title', 'adjust-drop'])
    wdg['plot_title_size'] = bmw.TextInput(title='Plot Title Font Size', value=str(PLOT_FONT_SIZE), css_classes=['wdgkey-plot_title_size', 'adjust-drop'])
    wdg['opacity'] = bmw.TextInput(title='Opacity (0-1)', value=str(OPACITY), css_classes=['wdgkey-opacity', 'adjust-drop'])
    wdg['x_scale'] = bmw.TextInput(title='X Scale', value=str(X_SCALE), css_classes=['wdgkey-x_scale', 'adjust-drop'])
    wdg['x_min'] = bmw.TextInput(title='X Min', value='', css_classes=['wdgkey-x_min', 'adjust-drop'])
    wdg['x_max'] = bmw.TextInput(title='X Max', value='', css_classes=['wdgkey-x_max', 'adjust-drop'])
    wdg['x_title'] = bmw.TextInput(title='X Title', value='', css_classes=['wdgkey-x_title', 'adjust-drop'])
    wdg['x_title_size'] = bmw.TextInput(title='X Title Font Size', value=str(PLOT_FONT_SIZE), css_classes=['wdgkey-x_title_size', 'adjust-drop'])
    wdg['x_major_label_size'] = bmw.TextInput(title='X Labels Font Size', value=str(PLOT_AXIS_LABEL_SIZE), css_classes=['wdgkey-x_major_label_size', 'adjust-drop'])
    wdg['x_major_label_orientation'] = bmw.TextInput(title='X Labels Degrees', value=str(PLOT_LABEL_ORIENTATION),
        css_classes=['wdgkey-x_major_label_orientation', 'adjust-drop'])
    wdg['y_scale'] = bmw.TextInput(title='Y Scale', value=str(Y_SCALE), css_classes=['wdgkey-y_scale', 'adjust-drop'])
    wdg['y_min'] = bmw.TextInput(title='Y  Min', value='', css_classes=['wdgkey-y_min', 'adjust-drop'])
    wdg['y_max'] = bmw.TextInput(title='Y Max', value='', css_classes=['wdgkey-y_max', 'adjust-drop'])
    wdg['y_title'] = bmw.TextInput(title='Y Title', value='', css_classes=['wdgkey-y_title', 'adjust-drop'])
    wdg['y_title_size'] = bmw.TextInput(title='Y Title Font Size', value=str(PLOT_FONT_SIZE), css_classes=['wdgkey-y_title_size', 'adjust-drop'])
    wdg['y_major_label_size'] = bmw.TextInput(title='Y Labels Font Size', value=str(PLOT_AXIS_LABEL_SIZE), css_classes=['wdgkey-y_major_label_size', 'adjust-drop'])
    wdg['circle_size'] = bmw.TextInput(title='Circle Size (Dot Only)', value=str(CIRCLE_SIZE), css_classes=['wdgkey-circle_size', 'adjust-drop'])
    wdg['bar_width'] = bmw.TextInput(title='Bar Width (Bar Only)', value=str(BAR_WIDTH), css_classes=['wdgkey-bar_width', 'adjust-drop'])
    wdg['line_width'] = bmw.TextInput(title='Line Width (Line Only)', value=str(LINE_WIDTH), css_classes=['wdgkey-line_width', 'adjust-drop'])
    wdg['download'] = bmw.Button(label='Download csv', button_type='success')
    wdg['export_config'] = bmw.Div(text='Export Config to URL', css_classes=['export-config', 'bk-bs-btn', 'bk-bs-btn-success'])

    #use init_config (from 'widgets' parameter in URL query string) to configure widgets.
    if init_load:
        for key in init_config:
            if key in wdg:
                if hasattr(wdg[key], 'value'):
                    wdg[key].value = str(init_config[key])
                elif hasattr(wdg[key], 'active'):
                    wdg[key].active = init_config[key]

    #Add update functions for widgets
    wdg['data'].on_change('value', update_data)
    wdg['update'].on_click(update_plots)
    wdg['download'].on_click(download)
    for name in wdg_col:
        wdg[name].on_change('value', update_wdg_col)
    for name in wdg_non_col:
        wdg[name].on_change('value', update_wdg)

    return wdg
Example #15
0
def build_map_legend(max_value=200):
    map_legend_string = '<div class="legend-header">Map ranges</div><div class="legend-body">'
    for legend_index in range(map_legend_steps):
        map_legend_string += '<div class="legend-entry"><span class="legend-color" style="background-color:' + scenario_colors[
            legend_index] + ';"></span>'
        map_legend_string += '<span class="legend-text">' + str(
            int(legend_index * max_value / map_legend_steps)) + ' - ' + str(
                int((legend_index + 1) * max_value /
                    map_legend_steps)) + '</span></div>'
    map_legend_string += '</div>'
    return map_legend_string


widgets = col.OrderedDict((
    ('legends_heading', bmw.Div(text='Legends', id='legends_heading')),
    ('techs_legend', bmw.Div(text=tech_legend_string, id='techs_legend')),
    ('scenarios_legend',
     bmw.Div(text=scenario_legend_string, id='scenarios_legend')),
    ('maps_legend', bmw.Div(text=build_map_legend(), id='maps_legend')),
    ('show_heading', bmw.Div(text='Show', id='show_heading')),
    ('scenarios_compare',
     bmw.Select(value='Show All',
                options=['Show All', 'Show Difference with Base'],
                id='scenarios_compare')),
    ('result',
     bmw.Select(value=gdx_structure.keys()[0],
                options=gdx_structure.keys(),
                id='result')),
    ('format',
     bmw.Select(value='Chart', options=['Figure', 'Table', 'Map'],
Example #16
0
        with open(
                "PsrSigSim_TeachingApp/HTMLBits/endingParagraph.html") as file:
            s = file.read()
            LastPara = widgets.Div(text=s)

    except:
        print("HTML Files not found")
        exit()


setup(
)  #------------------------------------------Reading/Genning Data---------

#Folding question---------------------------------------------------------------
question1Para = widgets.Div(text="""<h3>Question 1</h3>
                                   <p>Shown to the right is a plot of folded data at double the true period of a pulsar (i.e. the x-axis is 2 periods long).
                                   If you were to change that folding period to match the period of the pulsar, what would the plot look like?</p>"""
                            )

question1RightPara = widgets.Div(text="""<h3>Correct!</h3>
                                        <p>When folded at the correct period, the two pulses that are visible overlap and become one pulse that sticks out farther from
                                        the noise (larger Signal to Noise ratio).</p>"""
                                 )

question1WrongPara1 = widgets.Div(text="""<h3>Not quite.</h3>
                                        <p>Would there still be two pulses visible if this plot is over two periods, and it's asking for a single period?</p>"""
                                  )

question1WrongPara2 = widgets.Div(text="""<h3>Close.</h3>
                                        <p>If the same amount of noise is present for all folding periods, would two pulses overlapping cause a difference in the signal?</p>"""
                                  )
#-------------------------------------------------------------------------------
 def _init_controller_widgets(self):
     """Initialize the webcam capture button."""
     self.controller_widgets = layouts.widgetbox(
         [widgets.Div(text='<h1>Webcam</h1>'), self.capture_button])