Beispiel #1
0
p = figure(tools='box_select')
source = GeoJSONDataSource(geojson=original)
p.circle(line_color=None, fill_alpha=0.8, source=source)

# Open a session which will keep our local doc in sync with server
session = push_session(curdoc())

# Open the session in a browser
session.show()

is_original = True

while True:
    if is_original:
        # update to something else
        source.geojson = json.dumps(
            {'type': 'FeatureCollection',
             'features': [
                 {"type": "Feature",
                  "geometry": {"type": "Point",
                               "coordinates": [-2.1208465099334717, 51.4613151550293]},
                  "properties": {"OrganisationCode": "Q64"}}
             ]}
        )
        is_original = False
    else:
        # set back to original
        source.geojson = original
        is_original = True
    time.sleep(.5)
Beispiel #2
0
    tplot.add_layout(text_val5)
    tplot.add_layout(text_val6)
    tplot.add_layout(text_rate)
    tplot.add_layout(text_val7)
    tplot.add_layout(text_val8)
    tplot.add_layout(text_adults)
    tplot.add_layout(text_val9)
    tplot.add_layout(text_val10)
    tplot.add_layout(text_capita)
    tplot.add_layout(text_val11)
    tplot.add_layout(text_val12)

    def update_plot(attr, old, new):
        yr = slider.value
        new_data = get_json(str(yr), None)[0]
        geosource.geojson = new_data
        plot.title.text = 'State Craft Beer Sales, %d' %yr
    # Make a slider object: slider
    slider = Slider(title = 'Year',start = 2008, end = 2018, step = 1, value = 2018)
    slider.on_change('value', update_plot)
        def make_dataset(company_list):
        xs = []
        ys = []
        colors = []
        labels = []
        for i, company in enumerate(company_list):
            df_co = df_companies.loc[df_companies['company']==company]
            df_co = df_co.drop(['company', 'state'], axis=1)
            list_x = [int(i) for i in list(df_co)]
            list_y = df_co.values[0]
            xs.append(list_x)
Beispiel #3
0
    # if "1990s Shrubland" in add_this:
    #     shrub_1990_geosource.geojson = shrub_1990_json
    # elif "1990s Shrubland" in remove_this:
    #     shrub_1990_geosource.geojson = blank_json_data

    if "2010s Chaparral" in add_this:
        landfire_geosource.geojson = landfire_json
    elif "2010s Chaparral" in remove_this:
        landfire_geosource.geojson = blank_json_data

    old_list = new_list


### Set the layers to blank for the initial map
alt_geosource.geojson = blank_json_data
dMAT_geosource.geojson = blank_json_data_dmat  #because of the color fill, it's important to have the own blank here
chap_1930_geosource.geojson = blank_json_data
# shrub_1990_geosource.geojson = blank_json_data
landfire_geosource.geojson = blank_json_data

###Prep Color Bars for the environmental variables


def make_colorbar(shapefile_values, color_value_string, color_bar_title):

    #get the min and max values of shapefile
    min_range = min(shapefile_values)
    max_range = max(shapefile_values)

    palette = brewer[color_value_string][
Beispiel #4
0
#th=list(set(purpose['C']))
#th=[str(i) for i in th]

#mapper=factor_cmap('C', RdYlGn[5],th )
#mapper=linear_cmap('C', RdYlGn[5], 0, max(purpose.C))

color_mapper = LinearColorMapper(palette=RdYlGn[5])

#color_mapper.high=max(df_aggreg['value'])
#color_mapper.low=min(df_aggreg['value'])



geo_source = GeoJSONDataSource()

geo_source.geojson=json.dumps({"type":"FeatureCollection","features":[{"type":"Feature","id":"832830fffffffff","geometry":{"type":"Polygon","coordinates":[[[] for x in range(1)]]},"properties":{'Hex_Count': 1, 'Hex_No': '27'}}]})
 
p.patches('xs', 'ys', fill_alpha=0.7, fill_color={'field': 'Hex_Count', 'transform': color_mapper},
          line_color='white', line_width=0.5, source=geo_source)



color_bar = ColorBar(color_mapper=color_mapper, ticker= BasicTicker(),
                     location=(0,0))

#color_bar.click_policy="hide"

p.add_layout(color_bar, 'right')


#output_file("hex_tile.html")
Beispiel #5
0
def output_res():

    with open(r'./twgeo_easy_rates.json', 'r') as file:
        json_str = file.read()
        geo_source = GeoJSONDataSource(geojson=json_str)
        twgeo_json = json.loads(json_str)

    pred_4week = pd.read_csv('prediction_4week.csv')

    areas = ['南區', '北區', '東區', '高屏區', '台北區', '中區']
    models = ['CatBoost', 'XGB', 'ConvLSTM', 'GRU', 'LGBM', 'truth']

    color_list = ['black', 'red', 'blue', 'green', 'cyan', 'purple']

    area_dict = {}
    for idx, area in enumerate(areas):
        area_dict[area] = {}

        temp = pd.read_csv('./data/{}.csv'.format(area))
        area_dict[area]['df'] = temp
        area_dict[area]['DT'] = pd.to_datetime(temp['DT'].values)
        area_idx = []
        for i in range(22):
            if twgeo_json['features'][i]['properties']['area'] == area:
                area_idx.append(i)
        area_dict[area]['area_idx'] = area_idx

    def fig_config(fig):
        fig.grid.grid_line_color = None
        fig.toolbar.logo = None
        fig.toolbar_location = None
        fig.legend.location = "top_left"
        fig.legend.click_policy = "hide"
        fig.xaxis.axis_label = 'Date'
        fig.yaxis.axis_label = '腸病毒人數'

    future_4_weeks = []
    data_dict = {}
    model_cds = {}

    pred_4week = pd.read_csv('prediction_4week.csv')

    pred_64week = pd.read_csv('prediction_64week.csv')

    pred_4week_mae = pd.read_csv('mae_4week.csv')
    pred_64week_mae = pd.read_csv('mae_64week.csv')

    for area in areas:
        for model in models:
            data_dict['{}_{}_4week'.format(area,
                                           model)] = pred_4week['{}_{}'.format(
                                               area, model)].values
            data_dict['{}_{}_64week'.format(
                area, model)] = pred_64week['{}_{}'.format(area, model)].values
            data_dict['{}_{}_4week_mae'.format(area, model)] = pred_4week_mae

    data_dict['x_4week'] = pd.to_datetime(pred_4week['x'].values)
    data_dict['x_64week'] = pd.to_datetime(pred_64week['x'].values)
    dates = data_dict['x_64week']

    fig_predict = figure(title="predictions",
                         tools=TOOLS,
                         width=600,
                         height=300,
                         x_axis_type='datetime')

    mae_source_4week = ColumnDataSource(data=dict())
    mae_source_64week = ColumnDataSource(data=dict())
    columns = [
        TableColumn(field="model", title="model Name"),
        TableColumn(field="mae", title="MAE")
    ]

    data_table_4week = DataTable(source=mae_source_4week,
                                 columns=columns,
                                 width=800)
    data_table_64week = DataTable(source=mae_source_64week,
                                  columns=columns,
                                  width=800)

    stats_4week = PreText(text='', width=500)
    stats_64week = PreText(text='', width=500)

    fig_predict_1year = figure(title="predictions_1year",
                               tools=TOOLS,
                               width=1000,
                               height=300,
                               x_axis_type='datetime',
                               x_axis_location="above",
                               background_fill_color="#efefef",
                               x_range=(dates[0], dates[20]))

    select = figure(
        title=
        "Drag the middle and edges of the selection box to change the range above",
        plot_height=130,
        plot_width=1000,
        y_range=fig_predict_1year.y_range,
        x_axis_type="datetime",
        y_axis_type=None,
        tools="",
        toolbar_location=None,
        background_fill_color="#efefef")

    range_rool = RangeTool(x_range=fig_predict_1year.x_range)
    range_rool.overlay.fill_color = "navy"
    range_rool.overlay.fill_alpha = 0.2

    for i, model in enumerate(models):
        model_cds[model] = {}
        model_cds[model]['cds_4week'] = ColumnDataSource(data={
            'x': [],
            'y': []
        })
        model_cds[model]['cds_64week'] = ColumnDataSource(data={
            'x': [],
            'y': []
        })

        fig_predict.line(x='x',
                         y='y',
                         source=model_cds[model]['cds_4week'],
                         line_color=color_list[i],
                         muted_color=color_list[i],
                         line_width=2,
                         line_alpha=0.7,
                         legend=model)

        fig_predict_1year.line(x='x',
                               y='y',
                               source=model_cds[model]['cds_64week'],
                               line_color=color_list[i],
                               muted_color=color_list[i],
                               line_width=2,
                               line_alpha=0.7,
                               legend=model)
        select.line('x',
                    'y',
                    source=model_cds[model]['cds_64week'],
                    line_color=color_list[i],
                    muted_color=color_list[i])

    select.ygrid.grid_line_color = None
    select.add_tools(range_rool)
    select.toolbar.active_multi = range_rool

    fig_config(fig_predict)
    fig_config(fig_predict_1year)

    p = figure(title="Taiwan",
               tools=TOOLS,
               x_axis_location=None,
               y_axis_location=None,
               width=600,
               height=800)
    p.background_fill_color = 'beige'
    p.border_fill_color = 'black'
    p.border_fill_alpha = 0.05
    p.grid.grid_line_color = None
    p.toolbar.logo = None
    p.toolbar_location = None

    for i in range(22):
        twgeo_json['features'][i]['properties']['line_width'] = 0.5
        twgeo_json['features'][i]['properties']['line_color'] = 'white'

    geo_source.geojson = json.dumps(twgeo_json)

    selected_g = Patches(fill_color='blue',
                         line_color='white',
                         line_width=4,
                         line_alpha=0.5)

    renderer = p.patches('xs',
                         'ys',
                         fill_alpha=0.7,
                         fill_color='blue',
                         line_color='line_color',
                         line_width='line_width',
                         line_alpha=1,
                         source=geo_source)
    renderer.selection_glyph = selected_g

    p.add_tools(TapTool())
    p.add_tools(
        HoverTool(tooltips=[("name",
                             "@name"), ("index",
                                        "$index"), ("(Lon,Lat)", "($x, $y)")]))

    def my_tap_handler(attr, old, new):

        fig_config(fig_predict)

        idx = geo_source.selected.indices[0]

        area = twgeo_json['features'][idx]['properties']['area']

        geo_source.selected.indices = area_dict[area]['area_idx']

        for i in range(22):
            if twgeo_json['features'][i]['properties']['area'] == area:
                twgeo_json['features'][i]['properties']['line_width'] = 4
                twgeo_json['features'][i]['properties']['line_color'] = 'black'

            else:
                twgeo_json['features'][i]['properties']['line_width'] = 0.5
                twgeo_json['features'][i]['properties']['line_color'] = 'white'

        geo_source.geojson = json.dumps(twgeo_json)

        if area:

            temp_date_4week = data_dict['x_4week']
            temp_date_64week = data_dict['x_64week']
            temp_text_4week = ''

            for i, model in enumerate(models):
                temp_y_4week = data_dict['{}_{}_4week'.format(area, model)]
                temp_y_64week = data_dict['{}_{}_64week'.format(area, model)]

                model_cds[model]['cds_4week'].data = {
                    'x': temp_date_4week,
                    'y': temp_y_4week
                }
                model_cds[model]['cds_64week'].data = {
                    'x': temp_date_64week,
                    'y': temp_y_64week
                }

            stats_4week.text = area + '(last 4 weeks mae):\n'
            stats_64week.text = area + '(last one year mae):\n'
            mae_source_4week.data = {
                'model': [model for model in models if model != 'truth'],
                'mae': [
                    pred_4week_mae['{}_{}'.format(area, model)]
                    for model in models if model != 'truth'
                ],
            }
            mae_source_64week.data = {
                'model': [model for model in models if model != 'truth'],
                'mae': [
                    pred_64week_mae['{}_{}'.format(area, model)]
                    for model in models if model != 'truth'
                ],
            }

    geo_source.on_change('selected', my_tap_handler)

    layouts = column(fig_predict, stats_4week, data_table_4week)
    layouts = row(p, layouts)
    layouts = column(layouts, fig_predict_1year, select, stats_64week,
                     data_table_64week)

    return layouts
Beispiel #6
0
    if "1930s Chaparral" in add_this:
        chap_1930_geosource.geojson = chap_1930_json
    elif "1930s Chaparral" in remove_this:
        chap_1930_geosource.geojson = blank_json_data

    if "1990s Shrubland" in add_this:
        shrub_1990_geosource.geojson = shrub_1990_json
    elif "1990s Shrubland" in remove_this:
        shrub_1990_geosource.geojson = blank_json_data

    old_list = new_list


### Set the layers to blank for the initial map
alt_geosource.geojson = blank_json_data
dMAT_geosource.geojson = blank_json_data_dmat  #because of the color fill, it's important to have the own blank here
chap_1930_geosource.geojson = blank_json_data
shrub_1990_geosource.geojson = blank_json_data

###Prep Color Bars for the environmental variables


def make_colorbar(shapefile_values, color_value_string, color_bar_title):

    #get the min and max values of shapefile
    min_range = min(shapefile_values)
    max_range = max(shapefile_values)

    palette = brewer[color_value_string][
        8]  #Define a sequential multi-hue color palette.