Beispiel #1
0
def gen_select_state_county(state_name, county_name):
  state_list = list(us_counties["state"].unique())
  state_list.sort()
  counties_in_states = list(us_counties.loc[us_counties["state"] == state_name]['county'].unique())
  counties_in_states.sort()
  select_state = Select(title="State:", value="foo", options=state_list)
  select_county = Select(title="County:", value="foo", options=counties_in_states)

  select_state.value = state_name
  select_county.value = county_name

  return select_state, select_county
Beispiel #2
0
def get_selections():

    gates = [
        "IN - what to add on", "NOT IMPORTANT - what to drop off",
        "IMPORTANT - where to focus on"
    ]
    select_gate = Select(title="Gate",
                         value="IN - what to add on",
                         options=gates)

    if select_gate.value == "IN - what to add on":
        select_gate.value = "input_gate"
    elif select_gate.value == "NOT IMPORTANT - what to drop off":
        select_gate.value = "forget_gate"
    elif select_gate.value == "IMPORTANT - where to focus on":
        select_gate.value = "output_gate"

    return select_gate
    apply_thresholds(a,
                     threshold=threshold_slider.value,
                     cluster_size=clustersize_slider.value)
    update_guide()
    plot()


def apply_thresholds_calback(attr, old, new):
    apply_thresholds(a,
                     threshold=threshold_slider.value,
                     cluster_size=clustersize_slider.value)
    update_guide()
    plot()


def set_slice_callback(attr, old, new):
    plot()


subject_select.on_change('value', select_subject_callback)
select_subject_callback('', '', '')

slice_slider.on_change('value', set_slice_callback)
threshold_slider.on_change('value', apply_thresholds_calback)
clustersize_slider.on_change('value', apply_thresholds_calback)
transparency_slider.on_change('value', set_slice_callback)

# In[19]:

subject_select.value = sorted_xs[0]
Beispiel #4
0
ss_select_ed = Select(
    title="ss",
    value="59",
    options=['{:02d}'.format(ll) for ll in range(0, 60)],
    width=config_main['plot_config']['tab_aiaBrowser']['ss_select_wdth'])
Text_PlotID = TextInput(
    value='',
    title="Plot ID:",
    width=config_main['plot_config']['tab_aiaBrowser']['button_wdth'])

print database_dir + 'Trange_args.json'
try:
    with open(database_dir + 'Trange_args.json', 'r') as fp:
        trcfg = json.load(fp)
    print trcfg['aiaBrowser']['tst']
    YY_select_st.value, MM_select_st.value = trcfg['aiaBrowser']['tst'][
        0:4], trcfg['aiaBrowser']['tst'][5:7]
    DD_select_st.value, hh_select_st.value = trcfg['aiaBrowser']['tst'][
        8:10], trcfg['aiaBrowser']['tst'][11:13]
    mm_select_st.value, ss_select_st.value = trcfg['aiaBrowser']['tst'][
        14:16], trcfg['aiaBrowser']['tst'][17:19]
    YY_select_ed.value, MM_select_ed.value = trcfg['aiaBrowser']['ted'][
        0:4], trcfg['aiaBrowser']['ted'][5:7]
    DD_select_ed.value, hh_select_ed.value = trcfg['aiaBrowser']['ted'][
        8:10], trcfg['aiaBrowser']['ted'][11:13]
    mm_select_ed.value, ss_select_ed.value = trcfg['aiaBrowser']['ted'][
        14:16], trcfg['aiaBrowser']['ted'][17:19]
except:
    trcfg = {}


def YY_select_st_select_update(attrname, old, new):
Beispiel #5
0
def buildPlot():
    #####################Setup
    # Grab graph colors, pop undesireable ones
    colors = SEABORN_PALETTES['bright']

    #Grab and sort the FQs
    quals = fruit_df.reset_index()
    quals = quals['FruitQuality'].unique().tolist()
    for idx, i in enumerate(list(quals)):
        if type(i) == type(0.5):
            quals.pop(idx)
    unique_FQs = quals

    #a little math to get the epoch time to set the initial x range
    minDate = ts_to_epoch(fruit_df['Date'].min())
    maxDate = ts_to_epoch(fruit_df['Date'].max())

    ###########Create and format the plot
    plot = figure(
        x_axis_type="datetime",
        plot_width=600,
        plot_height=400,
        tools=[PanTool(),
               WheelZoomTool(),
               SaveTool(),
               BoxZoomTool()],
        x_range=DataRange1d(
            start=minDate, end=maxDate
        ),  #sets the initial date range  to the limits of the data
        y_range=DataRange1d(start=0, end=1),
        name='the_plot',
        toolbar_location='above')
    #some styling
    plot.title.text = "Historical Volatility"
    plot.xaxis.axis_label = "Trade Date"
    plot.yaxis.axis_label = "Vol"
    plot.background_fill_color = '#EAEBF0'
    plot.xgrid.grid_line_color = 'white'
    plot.ygrid.grid_line_color = 'white'
    plot.xaxis.axis_line_color = 'white'
    plot.xaxis.major_tick_line_color = 'white'
    plot.xaxis.minor_tick_line_color = 'white'
    plot.yaxis.axis_line_color = 'white'
    plot.yaxis.major_tick_line_color = 'white'
    plot.yaxis.minor_tick_line_color = 'white'
    plot.toolbar.logo = None

    #a list for all of the lines to reside in
    lines = []
    legends = []

    ##############Create the widgets

    #a console style window to show debug messages TODO: add on/off functionality
    debug = PreText(text="", width=1200, height=500)

    #echos the debug in a place more visiable for the user
    user_message = Paragraph(text='')

    #Asset_Class, Product, and From dropdown boxes. Sets dropdown's initial value.
    asCls = Select(title="Asset Class",
                   options=ddOpts['Asset_Class'].unique().tolist())
    asCls.value = asCls.options[0]
    prod = Select(title="Products",
                  options=ddOpts[ddOpts['Asset_Class'] == asCls.value]
                  ['Product'].unique().tolist())
    prod.value = prod.options[0]
    whereFrom = Select(title="From",
                       options=ddOpts[(ddOpts['Asset_Class'] == asCls.value)
                                      & (ddOpts['Product'] == prod.value)]
                       ['From'].unique().tolist())
    whereFrom.value = whereFrom.options[0]
    FQslider = Slider(title='Fruit Quality',
                      start=min(unique_FQs),
                      end=max(unique_FQs),
                      step=1)

    #the amount of days back to look for the data
    days_back = TextInput(title='Days ago', value='365')
    days_back_buttons = RadioButtonGroup(
        labels=['10', '30', '90', '180', '365', '730'], active=4)

    #the date to linear fit to
    fixed_date_buttons = RadioButtonGroup(
        labels=['30', '60', '90', '120', '180', '365'], active=2)
    fixed_date = TextInput(title='Days to Exp', value='90')

    #the amount of days with which to calculate the rolling mean
    rolling_days_buttons = RadioButtonGroup(labels=['1', '2', '5', '10'],
                                            active=0)
    rolling_days = TextInput(title='Rolling Mean Days', value='1')

    #a dynamically resizing checkbox group that allows for the changing of the visablity of any line on the plot
    line_onOff = CheckboxGroup(width=400, name='line_onOff')

    #the associated colors to act as a legend for line_onOff
    legendDiv = Div(width=50)

    #button to add a line
    addLine = Button(label="Add Line")

    #an html rendered visualization of the data for each line
    descriptions = Div(text='', width=500)

    #resizes the plot
    rszButton = Button(label='resize')

    ##########Define functions associated with the widgets

    #concats any dubug call to the end of the current debug text, and changes the user message
    def updateDebug(inString):
        inString = str(inString)
        user_message.text = inString
        oldText = debug.text
        newText = ("*- " + str(datetime.now()) + " : " + inString)
        debug.text = oldText + '\n' + newText

    #changes the potential products and contract categories to match the user selected asset class
    def asClsChange(attrname, old, new):
        prod.options = ddOpts[ddOpts['Asset_Class'] ==
                              asCls.value]['Product'].unique().tolist()
        prod.value = prod.options[0]

    #changes the potential contract categories to match the user selected product
    def prodChange(attrname, old, new):
        whereFrom.options = ddOpts[(ddOpts['Asset_Class'] == asCls.value) & (
            ddOpts['Product'] == prod.value)]['From'].unique().tolist()
        whereFrom.value = whereFrom.options[0]

    #links the days back button and text box
    def days_back_buttonChange(attrname, old, new):
        days_back.value = days_back_buttons.labels[days_back_buttons.active]

    #checks that the users input is an int
    def days_backChange(attrname, old, new):
        try:
            days_back.value = str(int(days_back.value))
        except ValueError:
            days_back.value = '0'
            updateDebug('please type an integer')

    #links the fixed date button and text box
    def fixed_date_buttonChange(attrname, old, new):
        fixed_date.value = fixed_date_buttons.labels[fixed_date_buttons.active]

    #checks that the users input is an int
    def fixed_dateChange(attrname, old, new):
        try:
            fixed_date.value = str(int(fixed_date.value))
        except ValueError:
            fixed_date.value = '0'
            updateDebug('please type an integer')

    #links the rolling days button and text box
    def rolling_days_buttonsChange(attrname, old, new):
        rolling_days.value = rolling_days_buttons.labels[
            rolling_days_buttons.active]

    #checks that the users input is an int
    def rolling_daysChange(attrname, old, new):
        try:
            rolling_days.value = str(int(rolling_days.value))
        except ValueError:
            rolling_days.value = '0'
            updateDebug('please type an integer')

    #fits the plot to the currently visiable lines
    def resize():
        if len(line_onOff.active) == 0 or len(line_onOff.labels) == 0:

            plot.x_range.start = ts_to_epoch(fruit_df['Date'].min())
            plot.x_range.end = ts_to_epoch(fruit_df['Date'].max())
            plot.y_range.start = 0
            plot.y_range.end = 100
        else:
            xmin, xmax, ymin, ymax = calc_range(lines)
            plot.x_range.start = xmin
            plot.x_range.end = xmax
            plot.y_range.start = ymin
            plot.y_range.end = ymax

    #turn lines on or off
    def line_onOffChange(attrname, old, new):
        for i in range(len(line_onOff.labels)):
            if i in line_onOff.active:
                lines[i].glyph.visible = True
            else:
                lines[i].glyph.visible = False
        legendDiv.text = '<div>'
        for line in lines:
            legendDiv.text += '<br><div style="background-color: %s; float:up; padding: 4px 4px 4px 4px"></div><br>' % line.glyph.line_color
        legendDiv.text += '</div>'
        resize()

    #adds a line to the graph
    def grphUpdt():
        #adds some debug messages, grabs the current time as to later show the total time taken to calculate
        updateDebug("Starting")
        updateDebug("total dataframe size: " + str(fruit_df.shape))
        stTime = datetime.now()

        #the value to linear fit to
        fit_to = int(fixed_date.value)

        #instiantiate an empty dataframe that will eventually contain the graphs data
        graphData = pd.DataFrame({
            'Date': [],
            'PriceVolatility': [],
            'Days_to_Exp': []
        })

        #grab the appropriate subset of the whole dataframe based on the users input into the widgets
        updateDebug("querying the data..")

        try:
            workingDf = fruit_df.loc[asCls.value, prod.value, whereFrom.value]
        except KeyError:
            updateDebug(
                'no data with that combination of Asset Class, Product, From')
            return

        try:
            workingDf = workingDf[[
                'Date', 'PriceVolatility', 'Days_to_Exp'
            ]][(workingDf['Date'] >
                (date.today() - timedelta(days=int(days_back.value))))]
        except KeyError:
            updateDebug(
                'no data with that combination of Asset Class, Product, From, and days back'
            )
            return
        updateDebug("done breaking down df")

        #a hook in the case that the users inputs resulted in an empty dataframe
        if (workingDf.empty):
            updateDebug(
                'no data with that combination of Asset Class, Product, From, and days back'
            )
            return

        #widdle down the database to only contain the user specified FQ
        try:
            graphData = workingDf.loc[int(FQslider.value)].copy()
        except KeyError:
            updateDebug('no data with that FQ')

        #another empty graph hook
        if (graphData.empty):
            updateDebug(
                'no data with that combination of Asset Class, Product, Contract Category, FQ, and days back'
            )
            return
        updateDebug('grabed correct FQs')

        #calculate linear fit on the current subset
        updateDebug('calculating linear fit...')
        graphData = mu.linearFit(fit_to=fit_to,
                                 group_on_column='Date',
                                 df=graphData,
                                 fit_column='Days_to_Exp',
                                 on_columns=['PriceVolatility'])
        updateDebug('finished with linear fit')

        # a few more debug messages
        updateDebug(
            "working df qry: Asset_Class = %s and Product = %s and From = %s and Date > %s "
            % (asCls.value, prod.value, whereFrom.value,
               str(date.today() - timedelta(days=int(days_back.value)))))
        updateDebug("graph data shape: " + str(workingDf.shape))

        #makes sure graph data has at least 5 rows, so that rolling mean can be calculated
        if graphData.shape[0] > int(rolling_days.value):

            #make the graph legend, based on if there's a denominator specified or not
            this_legend = '%s - %s FQ: %s Days to Exp: %s From: %s Rolling Days: %s' % (
                prod.value, whereFrom.value, int(
                    FQslider.value), fixed_date.value,
                str(date.today() - timedelta(days=int(days_back.value))),
                rolling_days.value)

            #add a new line to the graph, and add the accosiated GlyphRenderer created by adding the line to the lines list.
            #Set the legend to the previously calculated legend, and set the color to the next color in the current theme (if there are more lines than colors, there will be multiple lines with the same color)
            #Calculates a 5 day rolling mean on the y values. Maybe add a slider/text box/other widget so the user can set the rolling mean themselves
            updateDebug('adding line to plot')
            lines.append(
                plot.line(graphData.index.values[int(rolling_days.value) - 1:],
                          graphData['PriceVolatility'].rolling(
                              window=int(rolling_days.value)).mean()
                          [int(rolling_days.value) - 1:],
                          line_width=3,
                          color=colors[len(lines) % len(colors)]))
            legends.append(this_legend)
            updateDebug("updated graph")

            global descDf

            #either creates, or adds to, a dataframe containing statistics about the data. stats come from pandas DataFrame.describe.
            if descDf is None:
                graphData[this_legend] = graphData['PriceVolatility']
                descDf = graphData[[
                    this_legend
                ]].rolling(window=int(rolling_days.value)).mean(
                )[int(rolling_days.value) -
                  1:].describe(percentiles=[]).transpose().copy()
            else:
                graphData[this_legend] = graphData['PriceVolatility']
                descDf = pd.concat([
                    descDf, graphData[[
                        this_legend
                    ]].rolling(window=int(rolling_days.value)).mean()
                    [int(rolling_days.value) -
                     1:].describe(percentiles=[]).transpose().copy()
                ])

            descDf = descDf.round(1)
            descriptions.text = descDf.to_html().replace('\\n', '')
            graphData.drop(this_legend, 1, inplace=True)

            #add the name of the line to the checkbox so that it can be turned off and o
            line_onOff.labels.append(this_legend)
            line_onOff.active.append(len(line_onOff.labels) - 1)
            legendDiv.text = '<div>'
            for line in lines:
                legendDiv.text += '<br><div style="background-color: %s; float:up; padding: 4px 4px 4px 4px"></div><br>' % line.glyph.line_color
            legendDiv.text += '</div>'
            ##leaving this in case we get around to figuring out the hover tool
            ##formats the date values for the hover tool, currently commented out until we, or bokeh, fix the hover tool for multiple lines
            #formDates= pd.to_datetime(graphData['Date'] ,format="%m-%d-%Y")
            #lines[-1].data_source.data['formDates'] = formDates.apply(lambda x: x.strftime('%m-%d-%Y'))

            ##Displays the amout of time it took to draw the line, as well as the number of points in the graph
            updateDebug("updated y vals, with rolling mean calculated")
            updateDebug(
                str(datetime.now() - stTime) + " FOR " +
                str(len(lines[-1].data_source.data['x'])) + " points")
        else:
            updateDebug("There's no data to display")
        del graphData
        del workingDf

    #######Link widgets to their associated functions
    asCls.on_change('value', asClsChange)
    prod.on_change('value', prodChange)
    days_back_buttons.on_change('active', days_back_buttonChange)
    days_back.on_change('value', days_backChange)
    fixed_date_buttons.on_change('active', fixed_date_buttonChange)
    fixed_date.on_change('value', fixed_dateChange)
    rolling_days_buttons.on_change('active', rolling_days_buttonsChange)
    rolling_days.on_change('value', rolling_daysChange)
    line_onOff.on_change('active', line_onOffChange)
    addLine.on_click(grphUpdt)
    rszButton.on_click(resize)

    #Formatting
    fixed_date_box = WidgetBox(fixed_date, fixed_date_buttons)
    days_back_box = WidgetBox(days_back, days_back_buttons)
    rolling_days_box = WidgetBox(rolling_days, rolling_days_buttons)
    widgets = [
        asCls, prod, whereFrom, FQslider, days_back_box, fixed_date_box,
        rolling_days_box, addLine, rszButton, user_message
    ]
    plot_w_description = VBox(plot, descriptions, width=700)
    pwd_w_leg = HBox(plot_w_description,
                     VBox(legendDiv),
                     VBox(line_onOff),
                     width=plot_w_description.width + line_onOff.width + 100,
                     name='div_to_save')
    input_box = VBox(*widgets, width=400, height=1200)
    total_box = HBox(VBox(input_box),
                     VBox(pwd_w_leg),
                     width=input_box.width + pwd_w_leg.width + 100,
                     height=1200)
    tot_w_debug = VBox(total_box, VBox(HBox(debug)))

    resize()
    return tot_w_debug
Beispiel #6
0
def create_layout():
    """Inclui o gráficos e os controles no curdoc do Bokeh Server."""
    plot_html = ColumnDataSource(dict(file_html=["Title"], html=[""]))
    plot = figure(
        title="Title",
        sizing_mode="stretch_both",
        tools="wheel_zoom,box_zoom,pan,,crosshair,reset,save",
        # tooltips=[("y", "$y"), ("x", "$x")],
        active_scroll="wheel_zoom",
        toolbar_location="above",
        output_backend="webgl",
    )
    plot.xaxis.axis_label = "X"
    plot.yaxis.axis_label = "Y"
    plot.add_layout(Legend())
    plot.legend.click_policy = "hide"
    plot.legend.background_fill_alpha = 0.6
    table_source = ColumnDataSource()
    side_controls = column(width=400, height=200)
    series_source_controls = row(sizing_mode="scale_width")
    tabs = Tabs()
    models.COLORS = cycle(Category10_10)
    models.Series.labels = []

    def upload_callback(attr, old, new):
        """Função que atualiza os dados do arquivo aberto."""
        file_contents = base64.b64decode(new)
        file_contents_bytes = io.BytesIO(file_contents)
        table_source.data = pd.read_csv(file_contents_bytes).to_dict("list")
        colmmns = list(table_source.data.keys())
        for widget in list(values_selectors.values()):
            widget.options = colmmns
        datatable.columns = [TableColumn(field=_, title=_) for _ in colmmns]

    def update_plot_html(event):
        title = plot.title.text
        file_name = title + ".html"
        # output_file(file_name, title=title, mode="inline")
        # save(plot)
        html = file_html(plot, INLINE, title)
        plot_html.data = dict(file_name=[file_name], html=[html])

    # Widgets (controls) ======================================================
    # Plot controls
    plot_title = TextInput(title="Plot title", value="Title")
    x_title = TextInput(title="X title", value="X")
    y_title = TextInput(title="Y title", value="Y")
    positions = [_.replace("_", "-") for _ in list(LegendLocation)]
    legend_position = Select(title="Legend position", options=positions)
    download_button = Button(label="Download saved",
                             button_type="success",
                             align="end")
    save_button = Button(label="Save", align="end")
    save_button.on_click(update_plot_html)
    with open("bokeh_chart_maker/download.js") as f:
        callback = CustomJS(args=dict(source=plot_html), code=f.read())
    download_button.js_on_click(callback)
    plot_controls = row(plot_title, x_title, y_title, legend_position,
                        save_button, download_button)

    def update_plot(attr, old, new):
        plot.title.text = plot_title.value
        plot.xaxis.axis_label = x_title.value
        plot.yaxis.axis_label = y_title.value
        plot.legend.location = legend_position.value.replace("-", "_")

    for widget in plot_controls.children:
        if hasattr(widget, "value"):
            widget.on_change("value", update_plot)
    legend_position.value = "top_left"

    # Series controls
    upload_button = FileInput(accept=".csv")
    upload_button.on_change("value", upload_callback)
    columns = [
        TableColumn(field=_, title=_, width=10)
        for _ in table_source.data.keys()
    ]
    datatable = DataTable(source=table_source,
                          columns=columns,
                          width=390,
                          height=200)
    values_selectors = {}
    glyph_type = Select(title="Glyph type",
                        options=["line", "scatter"],
                        width=100)

    def update_series_source_controls(attr, old, new):
        colmmns = list(table_source.data.keys())
        kw = dict(options=colmmns, width=80)
        values_selectors["x"] = Select(title=f"x-values", **kw)
        values_selectors["y"] = Select(title=f"y-values", **kw)
        series_source_controls.children = list(values_selectors.values())

    glyph_type.on_change("value", update_series_source_controls)
    glyph_type.value = "line"
    add_button = Button(label="Add glyph",
                        button_type="success",
                        width=50,
                        align="end")
    side_controls.children = [
        Div(text="<h3>Load file</h3>", height=35),
        upload_button,
        datatable,
        row(glyph_type, series_source_controls, add_button, width=390),
        Div(text="<h3>Glyphs</h3>", height=35),
        tabs,
    ]

    def add_series(event):
        any_col = list(table_source.data.keys())[0]
        source = ColumnDataSource()
        for key, selector in values_selectors.items():
            column_name = selector.value or any_col
            source.data[key] = table_source.data[column_name]
        vars_map = dict((k, str(k)) for k in values_selectors.keys())
        if glyph_type.value == "line":
            series = models.line_series(plot, source=source, **vars_map)
        elif glyph_type.value == "scatter":
            series = models.scatter_series(plot, source=source, **vars_map)

        def delete_series(event):
            plot.renderers = [
                r for r in plot.renderers if r.glyph != series.glyph
            ]
            legend_items = list(plot.legend.items)
            plot.legend.items = [
                item for item in legend_items
                if series.glyph != item.renderers[0].glyph
            ]
            tabs.tabs = [panel for panel in tabs.tabs if panel != series.panel]

        series.delete_button.on_click(delete_series)
        tabs.tabs.append(series.panel)

    add_button.on_click(add_series)
    return [
        side_controls,
        column(plot_controls, plot, sizing_mode="stretch_width")
    ]
Beispiel #7
0
def create_module(user):
    # start controller
    controller = Controller(user)
    # hover
    hover1 = create_hover(1)
    # module
    fig1 = figure(plot_width=600,
                  plot_height=300,
                  css_classes=['monitoring_fig1'],
                  tools='pan,box_zoom,reset',
                  name='fig1',
                  title='Cantidad de Clientes x día de Lectura')
    fig1.toolbar.logo = None
    fig1.toolbar_location = 'above'
    fig1.vbar(x=[1, 2, 3],
              width=1000 * 3600 * 24,
              bottom=0,
              top=[0, 0, 0],
              color='red',
              name='vbar2',
              alpha=0.2)
    line1 = fig1.line(x=[0, 1],
                      y=[0, 1],
                      line_color="darkgray",
                      line_width=2,
                      alpha=0.6,
                      legend='Planificación',
                      name='line1')
    line2 = fig1.line(x=[0, 1],
                      y=[0, 1],
                      line_color="blue",
                      line_width=2,
                      alpha=0.8,
                      legend='Real',
                      name='line1.2')
    fig1.legend.click_policy = "hide"
    fig1.legend.location = "top_left"
    fig1.legend.background_fill_color = "white"
    fig1.legend.background_fill_alpha = 0.5
    fig1.legend.label_text_color = "#505050"
    fig1.legend.orientation = "vertical"
    fig1.xaxis.axis_label = 'Días del mes'
    hover1.renderers = [line1, line2]
    fig1.add_tools(hover1)
    fig1.xaxis.formatter = DatetimeTickFormatter(days=["%d"])
    fig1.yaxis[0].formatter = NumeralTickFormatter(format="0.0a")

    fig2 = figure(plot_width=600,
                  plot_height=300,
                  css_classes=['monitoring_fig2'],
                  tools='pan,box_zoom,reset',
                  name='fig2',
                  title='Cantidad de Itinerarios x día de Lectura')
    fig2.toolbar.logo = None
    fig2.toolbar_location = 'above'
    fig2.vbar(x=[1, 2, 3],
              width=1000 * 3600 * 24,
              bottom=0,
              top=[0, 0, 0],
              color='red',
              name='vbar3',
              alpha=0.2)
    line3 = fig2.line(x=[0, 1],
                      y=[0, 1],
                      line_color="darkgray",
                      line_width=2,
                      alpha=0.6,
                      legend='Planificación',
                      name='line2')
    line4 = fig2.line(x=[0, 1],
                      y=[0, 1],
                      line_color="blue",
                      line_width=2,
                      alpha=0.8,
                      legend='Real',
                      name='line2.2')
    fig2.legend.click_policy = "hide"
    fig2.legend.location = "top_left"
    fig2.legend.background_fill_color = "white"
    fig2.legend.background_fill_alpha = 0.5
    fig2.legend.label_text_color = "#505050"
    fig2.legend.orientation = "vertical"
    fig2.xaxis.axis_label = 'Días del mes'
    hover2 = create_hover(1)
    hover2.renderers = [line3, line4]
    fig2.add_tools(hover2)
    fig2.xaxis.formatter = DatetimeTickFormatter(days=["%d"])

    map_options = GMapOptions(lat=10.032663,
                              lng=-74.042470,
                              map_type="roadmap",
                              zoom=7)
    fig3 = GMapPlot(x_range=Range1d(),
                    y_range=Range1d(),
                    map_options=map_options,
                    plot_width=600,
                    plot_height=450,
                    css_classes=['monitoring_fig3'],
                    name='fig3')
    fig3.toolbar.logo = None
    fig3.toolbar_location = 'above'
    fig3.add_tools(PanTool(), WheelZoomTool())
    fig3.title.text = 'Dispersión Geográfica de Itinerarios'
    fig3.api_key = 'AIzaSyATl81v4Wnm4udDvlNTcgw4oWMzWJndkfQ'
    x = np.linspace(-2, 2, 10)
    source = ColumnDataSource(data=dict(
        lat=x,
        lon=x**2,
        sizes=np.linspace(10, 20, 10),
        colors=controller.day_colors[0:10],
    ))
    circle = Circle(x="lon",
                    y="lat",
                    size='sizes',
                    fill_color='colors',
                    fill_alpha=0.6,
                    line_color='black')
    fig3.add_glyph(source, circle, name='circles1')
    fig3.add_tools(create_hover(2))

    menu1 = Select(title="Periodo:",
                   value="opt1",
                   name='menu1',
                   options=["opt1", "opt2", "opt3", "opt4"],
                   width=150,
                   css_classes=['monitoring_menu1'])
    menu1.options = controller.periodos_str
    menu1.value = controller.periodos_str[controller.now.month - 1]

    menu2 = Select(title="Delegación:",
                   value='TODOS',
                   name='menu2',
                   options=['TODOS'],
                   width=200,
                   css_classes=['monitoring_menu2'])

    menu3 = Select(title="Unicom:",
                   value="TODOS",
                   name='menu3',
                   options=["TODOS"],
                   width=150,
                   css_classes=['monitoring_menu3'])

    menu4 = Select(title="Día:",
                   value="TODOS",
                   name='menu4',
                   options=["TODOS"],
                   width=150,
                   css_classes=['monitoring_menu4'])

    menu5 = Select(title="Municipio:",
                   value="TODOS",
                   name='menu5',
                   options=["TODOS"],
                   width=200,
                   css_classes=['monitoring_menu5'])

    menu6 = Select(title="Tipología:",
                   value="TODOS",
                   name='menu6',
                   options=["TODOS"],
                   width=150,
                   css_classes=['monitoring_menu6'])

    fig4 = figure(plot_width=600,
                  plot_height=300,
                  css_classes=['monitoring_fig4'],
                  tools='pan,box_zoom,reset',
                  name='fig4',
                  title='Promedio de Días Facturados')
    fig4.toolbar.logo = None
    fig4.toolbar_location = 'above'
    fig4.line(x=[0, 1],
              y=[0, 1],
              line_color="darkgray",
              line_width=2,
              alpha=0.6,
              legend='Planificación',
              name='line4')
    fig4.line(x=[0, 1],
              y=[0, 1],
              line_color="blue",
              line_width=2,
              alpha=0.8,
              legend='Real',
              name='line4.2')
    fig4.legend.click_policy = "hide"
    fig4.legend.location = "top_left"
    fig4.legend.background_fill_color = "white"
    fig4.legend.background_fill_alpha = 0.5
    fig4.legend.label_text_color = "#505050"
    fig4.legend.orientation = "vertical"
    fig4.xaxis.axis_label = 'Mes del Año'
    fig4.add_tools(create_hover(4))
    fig4.yaxis[0].formatter = NumeralTickFormatter(format="0.0a")
    # TODO: visualizar el promedio y el total dias facturados al año

    fig5 = figure(plot_width=600,
                  plot_height=300,
                  css_classes=['monitoring_fig5'],
                  tools='pan,box_zoom,reset',
                  name='fig5',
                  title='Histograma de Días Facturados')
    fig5.toolbar.logo = None
    fig5.toolbar_location = 'above'
    fig5.vbar(x=[1, 2, 3],
              width=0.5,
              bottom=0,
              top=[1.2, 2.5, 3.7],
              color="darkcyan",
              fill_alpha=0.6,
              line_color='black',
              name='vbar1',
              legend='Planificación')
    fig5.line(x=[0, 1],
              y=[0, 1],
              line_color="blue",
              line_width=2,
              alpha=0.8,
              legend='Real',
              name='line5.2')
    fig5.legend.click_policy = "hide"
    fig5.legend.location = "top_left"
    fig5.legend.background_fill_color = "white"
    fig5.legend.background_fill_alpha = 0.5
    fig5.legend.label_text_color = "#505050"
    fig5.legend.orientation = "vertical"
    fig5.xaxis.axis_label = 'Días Facturados'
    fig5.add_tools(create_hover(3))
    fig5.yaxis[0].formatter = NumeralTickFormatter(format="0.0a")
    # TODO: agregar curva de suma acumulativa

    fig6 = figure(plot_width=600,
                  plot_height=300,
                  css_classes=['monitoring_fig6'],
                  tools='pan,box_zoom,reset',
                  name='fig6',
                  title='Traslados')
    fig6.toolbar.logo = None
    fig6.toolbar_location = 'above'
    fig6.line(x=[0, 1],
              y=[0, 1],
              line_color="darkgray",
              line_width=2,
              alpha=0.6,
              legend='Planificación',
              name='line6')
    fig6.line(x=[0, 1],
              y=[0, 1],
              line_color="blue",
              line_width=2,
              alpha=0.8,
              legend='Real',
              name='line6.2')
    fig6.legend.click_policy = "hide"
    fig6.legend.location = "top_left"
    fig6.legend.background_fill_color = "white"
    fig6.legend.background_fill_alpha = 0.5
    fig6.legend.label_text_color = "#505050"
    fig6.legend.orientation = "vertical"
    fig6.xaxis.axis_label = 'Mes del Año'
    fig6.add_tools(create_hover(4))
    fig6.yaxis[0].formatter = NumeralTickFormatter(format="0.0a")

    button_group1 = RadioButtonGroup(
        labels=["Itinerarios", "Energía", "Importe"],
        active=0,
        name='button_group1',
        css_classes=['monitoring_button_group1'])
    button_group1.on_change('active', controller.on_change_menus)

    widget1 = layout([[fig1], [fig2]], sizing_mode='fixed')
    widget2 = layout([
        [fig3],
        [menu1, menu2, menu3],
        [menu4, menu5, menu6],
    ],
                     sizing_mode='fixed')
    widget3 = layout([[fig6], [button_group1]], sizing_mode='fixed')
    dashboard = layout([
        [widget1, widget2],
        [fig4, fig5],
        [widget3],
    ],
                       sizing_mode='fixed')
    dashboard.name = 'monitoring'
    # ini module data
    curdoc().add_root(dashboard)
    controller.get_user_data()
    controller.populate_menus(controller.info_itin, controller.fechas_itin)
    menu1.on_change('value', controller.on_change_menus)
    menu2.on_change('value', controller.on_change_menus)
    menu3.on_change('value', controller.on_change_menus)
    menu4.on_change('value', controller.on_change_menus)
    menu5.on_change('value', controller.on_change_menus)
    menu6.on_change('value', controller.on_change_menus)
    controller.on_change_menus(None, None, None)
Beispiel #8
0
        print(e_i)
        for m_i, mention in enumerate(entity):
            print('\t', mention)
            if m_i == 0:
                entities[e_i] = mention['text']
            if mention['isRepresentative']:
                entities[e_i] = mention['text']
    print(entities)
    entities = [str(k) + ': ' + v for k, v in entities.items()]
    entity_select.options = entities
    selected_entity = 0
    entity_select.value = entities[selected_entity]


def update_selected_entity(attrname, old, new):
    print(new)
    div.update(text="")
    parts = new.split(':')
    index = parts[0]
    #entity_type = ' '.join(parts[1:])
    selected_entity = int(index)
    update_div(selected_entity)
"""

event_select.on_change('value', update_selected_event)
doc_select.on_change('value', update_selected_document)
#ner_select.on_change('value', update_selected_entity_type)
#entity_select.on_change('value', update_selected_entity)

doc_select.value = '0'