Example #1
0
def draw_main(bkplot, geo_df, y_var, y_type, geolabel, formatting):
    """ Adds choropleth based on specified y_var to an existing Bokeh plot.

    :param (Bokeh object) plot: pre-defined Bokeh figure
    :param (gpd.DataFrame) geo_df: merged geopandas DataFrame from merge_to_geodf()
    :param (str) y_var: column name of variable to plot
    :param (str) y_type: palette type: 'sequential', sequential_single', 'divergent', 'categorical'
    :param (str) geolabel: column name to use. default is county/state name from shapefile
    :param (dict) formatting: see DEFAULTFORMAT from params.py
    :return: None (adds to Bokeh object) """

    geo_src = models.GeoJSONDataSource(geojson=geo_df.to_json())
    cmap = make_color_mapper(geo_df[y_var], y_type, formatting)

    shapes = bkplot.patches('xs',
                            'ys',
                            fill_color={
                                'field': y_var,
                                'transform': cmap
                            },
                            fill_alpha=formatting['fill_alpha'],
                            line_color=formatting['line_color'],
                            line_width=formatting['line_width'],
                            source=geo_src)
    if y_type != 'categorical':
        cbar = make_color_bar(cmap, formatting)
        bkplot.add_layout(cbar)

    hover = models.HoverTool(renderers=[shapes])
    hover_ylabel = y_var if formatting['hover_ylabel'] is None else formatting[
        'hover_ylabel']
    hover.tooltips = [(formatting['hover_geolabel'], f'@{geolabel}'),
                      (hover_ylabel, f'@{y_var}{formatting["tooltip_text"]}')]
    bkplot.add_tools(hover)
Example #2
0
def plot_empty(geo='state', formatting=None, output=False):
    """Generate map outline (no fill).

    :param (str) geo: 'state' or 'county'
    :param (dict) formatting: if custom dict is passed, update DEFAULTFORMAT with those key-values
    :param (str) output: if specified, filepath to save html file. see save_plot().
    :return: if output is 'bokeh', returns Bokeh object; else None """

    ## get default plot formatting and update if necessary
    temp_format = DEFAULTFORMAT.copy()
    if formatting:
        temp_format.update(formatting)

    ## process data
    shape_df = prc.shape_geojson(geo,
                                 temp_format['simplify'],
                                 epsg=temp_format['epsg'])
    geo_src = models.GeoJSONDataSource(geojson=shape_df.to_json())

    ## plot and save choropleth
    bkplot = initialize_plot(temp_format)
    bkplot.patches('xs',
                   'ys',
                   fill_color=None,
                   line_color=temp_format['line_color'],
                   line_width=temp_format['line_width'],
                   source=geo_src)

    if temp_format['svg']:
        bkplot.output_backend = 'svg'
    save_plot(bkplot, output)
    ## return to original state
    io.reset_output()

    return bkplot
Example #3
0
def plot_bokeh(gdf, str_title):
    # geoJSON gdf
    geo_src = bm.GeoJSONDataSource(geojson=gdf.to_json())
    # colormap
    cmap = LinearColorMapper(palette=RdBu[5][::-1], low=0, high=4)  # reverse
    # define web tools
    TOOLS = "pan, wheel_zoom, box_zoom, reset, hover, save"
    # set up bokeh figure
    p = figure(title=str_title,
               tools=TOOLS,
               toolbar_location="below",
               x_axis_location=None,
               y_axis_location=None,
               width=900,
               height=800)
    # remove the grid
    p.grid.grid_line_color = None
    # add a patch for each polygon in the gdf
    p.patches('xs',
              'ys',
              fill_alpha=0.7,
              fill_color={
                  'field': 'label_mean',
                  'transform': cmap
              },
              line_color='black',
              line_width=0.5,
              source=geo_src)
    # set up mouse hover informations
    hover = p.select_one(bm.HoverTool)
    hover.point_policy = 'follow_mouse'
    hover.tooltips = [
        ("Control Label:", "@label_mean"),
        ("Label Predicted Probability:", "@prob_mean"),
    ]
    ticker = FixedTicker(ticks=[0, 1, 2, 3, 4])
    fixed_labels = dict({
        0: 'rebel control',
        1: 'leaning rebel control',
        2: 'contested',
        3: 'leaning government',
        4: 'government'
    })
    # add a color bar
    color_bar = bm.ColorBar(color_mapper=cmap,
                            ticker=ticker,
                            label_standoff=25,
                            major_label_overrides=fixed_labels,
                            location=(10, 0))
    p.add_layout(color_bar, 'right')
    return show(p)
Example #4
0
def draw_state(bkplot, formatting):
    """ Adds a state choropleth (default is transparent fill) to an existing Bokeh plot.

    :param (Bokeh object) plot: pre-defined Bokeh figure
    :param (dict) formatting: see DEFAULTFORMAT from params.py
    :return: None (adds to Bokeh object) """

    state_geojson = prc.shape_geojson('state',
                                      formatting['simplify'],
                                      epsg=formatting['epsg']).to_json()
    state_source = models.GeoJSONDataSource(geojson=state_geojson)
    bkplot.patches('xs',
                   'ys',
                   source=state_source,
                   fill_color=formatting['st_fill'],
                   fill_alpha=formatting['st_alpha'],
                   line_color=formatting['st_line_color'],
                   line_width=formatting['st_line_width'])
Example #5
0
def make_map():

    with open("./countries.geo.json", "r") as f:
        countries = bkm.GeoJSONDataSource(geojson=f.read())

    p = bkp.figure(width=1000, height=600, tools=tools, title='World Countries',
                   x_axis_label='Longitude', y_axis_label='Latitude')
    p.background_fill_color = "aqua"
    p.x_range = bkm.Range1d(start=-180, end=180)
    p.y_range = bkm.Range1d(start=-90, end=90)
    p.patches("xs", "ys", color="white", line_color="black", source=countries)

    layout = row(p)

    # Make a tab with the layout
    tab = Panel(child=layout, title='Word frequency')

    return tab
Example #6
0
def outputMapDew(path, mapSelect):

    if mapSelect == 'dew_yield':
        moduleType = 'Sum of Yearly Dew(mmd-1)'
        htmlString = '_yearly_dew'
        colorSelector = "Viridis256"
        #Assign the upper and lower bounds of the map

    #Create the html to be exported
    output_file('Yearly_Dew_Yield_Map(mmd-1)' + htmlString + '.html')

    # Create the tools used for zooming and hovering on the map
    tools = "pan,wheel_zoom,box_zoom,reset,previewsave"

    #Access the .json file to create the map of countries and states
    # THe json files will create layers to overlap the data with
    with open(path + "/Map/countries.geojson", "r") as f:
        countries = bkm.GeoJSONDataSource(geojson=f.read())
    with open(path + "/Map/us-states.json", "r") as f:
        states = bkm.GeoJSONDataSource(geojson=f.read())

    #Access the processed summary data pickle
    level_1_df = pd.read_pickle(
        path + "\\Pandas_Pickle_DataFrames\\Pickle_Map\\Pickle_Map.pickle")

    # Bring in all the data to display on map

    #Radius is the size of the circle to be displayed on the map
    radiusList = []
    for i in range(0, len(level_1_df)):
        #Toggle size of circle
        radiusList.append(2)
    lat = level_1_df['N'].astype(float)  #Northing and easting if Needed
    lon = level_1_df['E'].astype(float)
    radius = radiusList
    dew = level_1_df[moduleType]
    station = level_1_df['Station name']
    latitude = level_1_df['Site latitude']
    longitude = level_1_df['Site longitude']
    moduleTemp = level_1_df[moduleType]
    uniqueID = level_1_df['Site Identifier Code']

    # The Boken map rendering package needs to store data in the ColumnDataFormat
    # Store the lat/lon from the Map_pickle.  Formatting for Lat/Lon has been
    # processed prior see "Map_Pickle_Processing.py" file for more details
    # Add other data to create hover labels
    source = ColumnDataSource(data=dict(Lat=latitude,
                                        Lon=longitude,
                                        radius=radius,
                                        dew=dew,
                                        Station=station,
                                        Latitude=latitude,
                                        Longitude=longitude,
                                        Module_Temp=moduleTemp,
                                        uniqueID=uniqueID))

    p = bkp.figure(width=1500,
                   height=900,
                   tools=tools,
                   title='IWEC, CWEC, and Average Dew Yield(mmd-1)',
                   x_axis_type="mercator",
                   y_axis_type="mercator",
                   x_axis_label='Longitude',
                   y_axis_label='Latitude')

    p.x_range = bkm.Range1d(start=-180, end=180)
    p.y_range = bkm.Range1d(start=-90, end=90)

    #Create the datapoints as overlapping circles
    p.circle(
        "Lon",
        "Lat",
        source=source,
        radius="radius",
        #fill color will use linear_cmap() to scale the colors of the circles being displayed
        fill_color=linear_cmap('dew', colorSelector, low=20, high=300),
        line_color=None,
        # Alpha is the transparency of the circle
        alpha=0.3)
    #Stations will be the black dots displayed on the map
    stations = p.circle(
        "Lon",
        "Lat",
        source=source,
        radius=.1,
        #fill color will use linear_cmap() to scale the colors of the circles being displayed
        fill_color='black',
        line_color=None,
        # Alpha is the transparency of the circle
        alpha=.99)

    #Create the scale bar to the right of the map

    # Create color mapper to make the scale bar on the right of the map
    # palette = color scheme of the mapo
    # low/high sets the scale of the data, use the minimum value and maximum value of the data we are analyzing
    color_mapper = LogColorMapper(palette=colorSelector, low=20, high=300)

    # color bar will be scale bar set to the right of the map
    color_bar = ColorBar(color_mapper=color_mapper,
                         ticker=LogTicker(),
                         label_standoff=12,
                         border_line_color=None,
                         location=(0, 0))
    # Assign the scale bar to " p " and put it to the right
    p.add_layout(color_bar, 'right')

    # These are the labels that are displayed when you hover over a spot on the map
    #( label , @data), data needs to be inside the ColumnDataSource()
    TOOLTIPS = [
        ("Station", "@Station"),
        ("Site ID", "@uniqueID"),
        ("Lat", "@Latitude"),
        ("Lon", "@Longitude"),
        ("Yearly_Dew_Yield", "@dew"),
    ]

    #Create a hover tool that will rinder only the weather stations i.e stations are small black circles
    hover_labels = bkm.HoverTool(renderers=[stations], tooltips=TOOLTIPS)
    #Add the hover tool to the map
    p.add_tools(hover_labels)
    #Overlay the Country and States boarders
    p.patches("xs",
              "ys",
              color="white",
              line_color="black",
              source=countries,
              fill_alpha=0,
              line_alpha=1)
    p.patches("xs",
              "ys",
              color="white",
              line_color="black",
              source=states,
              fill_alpha=0,
              line_alpha=1)
    #Display the plot
    show(p)
Example #7
0
            prop_vals.append(feat_prop[key])
"""# Print info - kommuner"""
print("\nThis is all kommuner:")
print("#####################")
kommuner_list = sorted(kommuner_list)
for kommune_i in kommuner_list:
    print(kommune_i)
"""# Print info - feature"""
print("\nThis is all features:")
print("#####################")
for prop_k, prop_v in zip(prop_keys, prop_vals):
    print("'%s'" % prop_k, "'%s'" % prop_v)
"""# Load data to bokeh"""
# Dump to json string, and read
jfd = json.dumps(jf)
gs = bm.GeoJSONDataSource(geojson=jfd)
"""# Make bokeh graph"""
wheel_zoom = bm.WheelZoomTool()
hover = bm.HoverTool(tooltips=[
    ("Navn", "@KOMNAVN"),
    ("KOMKODE", "@KOMKODE"),
    ("(Long, Lat)", "($x, $y)"),
    ("index", "@index"),
    ("REGIONNAVN", "@REGIONNAVN"),
    #("REGIONKODE", "@REGIONKODE"),
    ("AREAL", "@AREAL"),
])
hover.point_policy = "follow_mouse"
tools = [
    bm.PanTool(),
    bm.BoxZoomTool(), wheel_zoom,
    def mapGenerator(path, mapSelect, htmlString, title, scaleMin, scaleMax,
                     metric):
        '''
        HELPER FUNCTION
        
        mapGenerator()
        
        Generate a map from the processed level_1_dataframe and diplay as a 
            bokeh map of the earth for each weather station
        
        @param path        - String, of the current working directory                                  
        @param mapSelect   - String, string to select what map to generate
 
         'Annual Global Horizontal Irradiance (GJ/m^-2)',
         'Annual Direct Normal Irradiance (GJ/m^-2)',
         'Annual Diffuse Horizontal Irradiance (GJ/m^-2)',
         'Annual POA Global Irradiance (GJ/m^-2)',
         'Annual POA Direct Irradiance (GJ/m^-2)',
         'Annual POA Diffuse Irradiance (GJ/m^-2)',
         'Annual POA Sky Diffuse Irradiance (GJ/m^-2)',
         'Annual POA Ground Diffuse Irradiance (GJ/m^-2)',
         
         'Annual Global UV Dose (MJ/y^-1)',
         'Annual UV Dose at Latitude Tilt (MJ/y^-1)',
         
         'Annual Minimum Ambient Temperature (C)',
         'Annual Average Ambient Temperature (C)',
         'Annual Maximum Ambient Temperature (C)',
         'Annual Range Ambient Temperature (C)',
         'Average of Yearly Water Vapor Pressure(kPa)',
         'Sum of Yearly Water Vapor Pressure(kPa)',
         "Annual number of Hours Relative Humidity > to 85%",
         'Sum of Yearly Dew(mmd-1)'

        @param htmlString - String, what to name the html 
        @param title      - String, title of the map
        @param scaleMin   - Float,  minimum value of the scale
        @param scaleMax   - Float,  maximum value of the scale        
        @param metric     - String, metric of the value being measured        
        
        @return           -void, Bokeh map as a html
        '''
        colorSelector = "Viridis256"

        #Create the html to be exported
        output_file(htmlString + '.html')

        # Create the tools used for zooming and hovering on the map
        tools = "pan,wheel_zoom,box_zoom,reset,previewsave"

        #Access the .json file to create the map of countries and states
        # The json files will create layers to overlap the data with
        with open(path + "/Map/countries.geojson", "r") as f:
            countries = bkm.GeoJSONDataSource(geojson=f.read())
        with open(path + "/Map/us-states.json", "r") as f:
            states = bkm.GeoJSONDataSource(geojson=f.read())
        #Access the processed summary data pickle
        level_1_df = pd.read_pickle(
            path +
            "\\Pandas_Pickle_DataFrames\\Pickle_Level1_Summary\\Pickle_Level1_Summary.pickle"
        )

        #Radius is the size of the circle to be displayed on the map
        radiusList = []
        for i in range(0, len(level_1_df)):
            #Toggle size of circle
            radiusList.append(2)

        radius = radiusList
        selector = level_1_df[mapSelect]
        station = level_1_df['Station name']
        latitude = level_1_df['Site latitude']
        longitude = level_1_df['Site longitude']
        moduleTemp = level_1_df[mapSelect]
        uniqueID = level_1_df['Site Identifier Code']
        dataSource = level_1_df['Data Source']
        elevation = level_1_df['Site elevation (meters)'].astype(float)

        # The Boken map rendering package needs to store data in the ColumnDataFormat
        # Store the lat/lon from the Map_pickle.  Formatting for Lat/Lon has been
        # processed prior see "Map_Pickle_Processing.py" file for more details
        # Add other data to create hover labels
        source = ColumnDataSource(data=dict(Lat=latitude,
                                            Lon=longitude,
                                            radius=radius,
                                            selector=selector,
                                            Station=station,
                                            Latitude=latitude,
                                            Longitude=longitude,
                                            Module_Temp=moduleTemp,
                                            uniqueID=uniqueID,
                                            elevation=elevation,
                                            dataSource=dataSource))

        p = bkp.figure(width=1500,
                       height=900,
                       tools=tools,
                       title=title,
                       x_axis_type="mercator",
                       y_axis_type="mercator",
                       x_axis_label='Longitude',
                       y_axis_label='Latitude')

        p.x_range = bkm.Range1d(start=-180, end=180)
        p.y_range = bkm.Range1d(start=-90, end=90)

        #Create the datapoints as overlapping circles
        p.circle(
            "Lon",
            "Lat",
            source=source,
            radius="radius",
            #fill color will use linear_cmap() to scale the colors of the circles being displayed
            fill_color=linear_cmap('selector',
                                   colorSelector,
                                   low=scaleMin,
                                   high=scaleMax),
            line_color=None,
            # Alpha is the transparency of the circle
            alpha=0.3)
        #Stations will be the black dots displayed on the map
        stations = p.circle(
            "Lon",
            "Lat",
            source=source,
            radius=.1,
            #fill color will use linear_cmap() to scale the colors of the circles being displayed
            fill_color='black',
            line_color=None,
            # Alpha is the transparency of the circle
            alpha=.99)
        #Create the scale bar to the right of the map
        # Create color mapper to make the scale bar on the right of the map
        # palette = color scheme of the mapo
        # low/high sets the scale of the data, use the minimum value and maximum value of the data we are analyzing
        color_mapper = LinearColorMapper(palette=colorSelector,
                                         low=scaleMin,
                                         high=scaleMax)

        # color bar will be scale bar set to the right of the map
        color_bar = ColorBar(color_mapper=color_mapper,
                             ticker=LogTicker(),
                             label_standoff=12,
                             border_line_color=None,
                             location=(0, 0))
        # Assign the scale bar to " p " and put it to the right
        p.add_layout(color_bar, 'right')
        # These are the labels that are displayed when you hover over a spot on the map
        #( label , @data), data needs to be inside the ColumnDataSource()
        TOOLTIPS = [("Station", "@Station"), ("Site ID", "@uniqueID"),
                    ("Data Source", "@dataSource"), ("Lat", "@Latitude"),
                    ("Lon", "@Longitude"),
                    (htmlString, "@selector" + " " + metric),
                    ("Elevation", "@elevation" + " (m)")]
        #Create a hover tool that will rinder only the weather stations i.e stations are small black circles
        hover_labels = bkm.HoverTool(renderers=[stations], tooltips=TOOLTIPS)
        #Add the hover tool to the map
        p.add_tools(hover_labels)
        #Overlay the Country and States boarders
        p.patches("xs",
                  "ys",
                  color="white",
                  line_color="black",
                  source=countries,
                  fill_alpha=0,
                  line_alpha=1)
        p.patches("xs",
                  "ys",
                  color="white",
                  line_color="black",
                  source=states,
                  fill_alpha=0,
                  line_alpha=1)
        #Display the plot
        show(p)
Example #9
0
    "GBR": (-1, 52),
    "FIN": (26, 62),
    "NOR": (10, 60),
    "PRT": (-7, 38),
    "ITA": (10, 45),
}

for c_id, coord in coord_fixes.items():
    cid = c_abr_to_id[c_id]
    world_region["x"].loc[cid] = coord[0]
    world_region["y"].loc[cid] = coord[1]

if region_name:
    world_region = world_region.loc[world_region['continent'] == region_name]

plot_df = bm.GeoJSONDataSource(geojson=world_region.to_json())
p = bp.figure(title=value_to_draw, x_range=(-22, 40), y_range=(35, 72))
map_palette = colorcet.bkr

m = 20
color_mapper = bm.LinearColorMapper(palette=map_palette, low=-m, high=m)
p.patches('xs',
          'ys',
          fill_alpha=1.0,
          fill_color={
              'field': value_to_draw,
              'transform': color_mapper
          },
          line_color='black',
          line_width=1.0,
          source=plot_df)
Example #10
0
def outputMapTemp(path, mapSelect):

    #Select which solar module temperature calculation the user would like to see

    if mapSelect == 'open_rack_cell_glassback':
        moduleType = 'Average (98th Percentile) Module Temperature__open_rack_cell_glassback (C)'
        chartHeader = 'Open Rack Cell Glass Back'
        htmlString = '_open_rack_cell_glassback'
        colorSelector = 'Spectral6'
        #Assign the upper and lower bounds of the map
        mapScaleUpper = 100
        mapScaleLower = 20

    elif mapSelect == 'roof_mount_cell_glassback':
        moduleType = 'Average (98th Percentile) Module Temperature__roof_mount_cell_glassback (C)'
        chartHeader = 'Roof Mount Cell Glass Back'
        htmlString = '_roof_mount_cell_glassback'
        colorSelector = 'Spectral6'
        #Assign the upper and lower bounds of the map
        mapScaleUpper = 100
        mapScaleLower = 20

    elif mapSelect == 'open_rack_cell_polymerback':
        moduleType = 'Average (98th Percentile) Module Temperature__open_rack_cell_polymerback (C)'
        chartHeader = 'Open Rack Cell Polymer Back'
        htmlString = '_open_rack_cell_polymerback'
        colorSelector = 'Spectral6'
        #Assign the upper and lower bounds of the map
        mapScaleUpper = 100
        mapScaleLower = 20

    elif mapSelect == 'insulated_back_polymerback':
        moduleType = 'Average (98th Percentile) Module Temperature__insulated_back_polymerback (C)'
        chartHeader = 'Insulated Back Polymer Back'
        htmlString = '_insulated_back_polymerback'
        colorSelector = 'Spectral6'
        #Assign the upper and lower bounds of the map
        mapScaleUpper = 100
        mapScaleLower = 20

    elif mapSelect == 'open_rack_polymer_thinfilm_steel':
        moduleType = 'Average (98th Percentile) Module Temperature__open_rack_polymer_thinfilm_steel (C)'
        chartHeader = 'Open Rack Polymer Thin Film Steel'
        htmlString = '_open_rack_polymer_thinfilm_steel'
        colorSelector = 'Spectral6'
        #Assign the upper and lower bounds of the map
        mapScaleUpper = 100
        mapScaleLower = 20

    elif mapSelect == '22x_concentrator_tracker':
        moduleType = 'Average (98th Percentile) Module Temperature__22x_concentrator_tracker (C)'
        chartHeader = '22x Concentrator Tracker'
        htmlString = '_22x_concentrator_tracker'
        colorSelector = 'Spectral6'
        #Assign the upper and lower bounds of the map
        mapScaleUpper = 100
        mapScaleLower = 20

    #Create the html to be exported
    output_file('Module_Temperature_Map' + htmlString + '.html')

    # Create the tools used for zooming and hovering on the map
    tools = "pan,wheel_zoom,box_zoom,reset,previewsave"

    #Access the .json file to create the map of countries and states
    # THe json files will create layers to overlap the data with
    with open(path + "/Map/countries.geojson", "r") as f:
        countries = bkm.GeoJSONDataSource(geojson=f.read())
    with open(path + "/Map/us-states.json", "r") as f:
        states = bkm.GeoJSONDataSource(geojson=f.read())

    #Access the processed summary data pickle
    level_1_df = pd.read_pickle(
        path + "\\Pandas_Pickle_DataFrames\\Pickle_Map\\Pickle_Map.pickle")

    # Bring in all the data to display on map

    #Radius is the size of the circle to be displayed on the map
    radiusList = []
    for i in range(0, len(level_1_df)):
        #Toggle size of circle
        radiusList.append(2)
    lat = level_1_df['N'].astype(float)  #Northing and easting if Needed
    lon = level_1_df['E'].astype(float)
    radius = radiusList
    temperature = level_1_df[moduleType]
    station = level_1_df['Station name']
    latitude = level_1_df['Site latitude']
    longitude = level_1_df['Site longitude']
    moduleTemp = level_1_df[moduleType]
    uniqueID = level_1_df['Site Identifier Code']

    # The Boken map rendering package needs to store data in the ColumnDataFormat
    # Store the lat/lon from the Map_pickle.  Formatting for Lat/Lon has been
    # processed prior see "Map_Pickle_Processing.py" file for more details
    # Add other data to create hover labels
    source = ColumnDataSource(data=dict(Lat=latitude,
                                        Lon=longitude,
                                        radius=radius,
                                        temperature=temperature,
                                        Station=station,
                                        Latitude=latitude,
                                        Longitude=longitude,
                                        Module_Temp=moduleTemp,
                                        uniqueID=uniqueID))

    # Create the figure with the map parameters.  This controls the window
    p = bkp.figure(
        width=1500,
        height=900,
        tools=tools,
        title=
        'IWEC, CWEC, and TMY-3 98th Precentile of Module Temperature Celsius (King Model) '
        + chartHeader,
        x_axis_type="mercator",
        y_axis_type="mercator",
        x_axis_label='Longitude',
        y_axis_label='Latitude')

    p.x_range = bkm.Range1d(start=-180, end=180)
    p.y_range = bkm.Range1d(start=-90, end=90)

    #Create the datapoints as overlapping circles
    p.circle(
        "Lon",
        "Lat",
        source=source,
        radius="radius",
        #fill color will use linear_cmap() to scale the colors of the circles being displayed
        fill_color=linear_cmap('temperature',
                               colorSelector,
                               low=mapScaleLower,
                               high=mapScaleUpper),
        line_color=None,
        # Alpha is the transparency of the circle
        alpha=0.3)
    #Stations will be the black dots displayed on the map
    stations = p.circle(
        "Lon",
        "Lat",
        source=source,
        radius=.1,
        #fill color will use linear_cmap() to scale the colors of the circles being displayed
        fill_color='black',
        line_color=None,
        # Alpha is the transparency of the circle
        alpha=.99)

    #Create the scale bar to the right of the map

    # Create color mapper to make the scale bar on the right of the map
    # palette = color scheme of the mapo
    # low/high sets the scale of the data, use the minimum value and maximum value of the data we are analyzing
    color_mapper = LogColorMapper(palette=colorSelector,
                                  low=mapScaleLower,
                                  high=mapScaleUpper)

    # color bar will be scale bar set to the right of the map
    color_bar = ColorBar(color_mapper=color_mapper,
                         ticker=LogTicker(),
                         label_standoff=12,
                         border_line_color=None,
                         location=(0, 0))
    # Assign the scale bar to " p " and put it to the right
    p.add_layout(color_bar, 'right')

    # These are the labels that are displayed when you hover over a spot on the map
    #( label , @data), data needs to be inside the ColumnDataSource()
    TOOLTIPS = [
        ("Station", "@Station"),
        ("Site ID", "@uniqueID"),
        ("Lat", "@Latitude"),
        ("Lon", "@Longitude"),
        ("Module_Temp", "@Module_Temp"),
    ]

    #Create a hover tool that will rinder only the weather stations i.e stations are small black circles
    hover_labels = bkm.HoverTool(renderers=[stations], tooltips=TOOLTIPS)
    #Add the hover tool to the map
    p.add_tools(hover_labels)
    #Overlay the Country and States boarders
    p.patches("xs",
              "ys",
              color="white",
              line_color="black",
              source=countries,
              fill_alpha=0,
              line_alpha=1)
    p.patches("xs",
              "ys",
              color="white",
              line_color="black",
              source=states,
              fill_alpha=0,
              line_alpha=1)
    #Display the plot
    show(p)
Example #11
0
    def outputMapTemp(path , mapSelect):
        '''
        EXECUTION METHOD
        
        outputMapTemp()
        
        Method to create a map of the Dew Yield around the world.
        This method will use a package called Bokeh that generates a html file 
        containing the map.  User will have thier defualt browser open and display the map
        
        @param path         - String, of the current working directory                                  
        @param mapSelect    - String, string to select what map to generate
                                    ACCEPTABLE STRINGS AS PARAMETERS
                                       - 'open_rack_cell_glassback'
                                       - 'roof_mount_cell_glassback'
                                       - 'open_rack_cell_polymerback'
                                       - 'insulated_back_polymerback'
                                       - 'open_rack_polymer_thinfilm_steel'
                                       - '22x_concentrator_tracker'                               
        
        @return void        - Generates a html Bokeh map
        '''        
        #Select which solar module temperature calculation the user would like to see
        
        ### 98th percentile maps
        if mapSelect == 'open_rack_cell_glassback98th':
            moduleType = 'Annual Average (98th Percentile) Module Temperature__open_rack_cell_glassback (C)'            
            minTemp = 'Annual Minimum Module Temperature__open_rack_cell_glassback (C)'
            maxTemp = 'Annual Maximum Module Temperature__open_rack_cell_glassback (C)'
            avgTemp = 'Annual Average Module Temperature__open_rack_cell_glassback (C)'
            module98 = 'Annual Average (98th Percentile) Module Temperature__open_rack_cell_glassback (C)'                        
            chartHeader = '98th Percentile Module Temperature Open Rack Cell Glass Back (C)'
            htmlString = '_open_rack_cell_glassback'
            colorSelector = 'Spectral6'
            #Assign the upper and lower bounds of the map 
            mapScaleUpper = 100
            mapScaleLower = 20
            
        elif mapSelect == 'roof_mount_cell_glassback98th':
            moduleType = 'Annual Average (98th Percentile) Module Temperature__roof_mount_cell_glassback (C)'            
            minTemp = 'Annual Minimum Module Temperature__roof_mount_cell_glassback (C)'
            maxTemp = 'Annual Maximum Module Temperature__roof_mount_cell_glassback (C)'
            avgTemp = 'Annual Average Module Temperature__roof_mount_cell_glassback (C)'
            module98 = 'Annual Average (98th Percentile) Module Temperature__roof_mount_cell_glassback (C)'                        
            chartHeader = '98th Percentile Module Temperature Roof Mount Cell Glass Back (C)'
            htmlString = '_roof_mount_cell_glassback'
            colorSelector = 'Spectral6'
            #Assign the upper and lower bounds of the map 
            mapScaleUpper = 100
            mapScaleLower = 20
            
        elif mapSelect == 'open_rack_cell_polymerback98th':
            moduleType = 'Annual Average (98th Percentile) Module Temperature__open_rack_cell_polymerback (C)'            
            minTemp = 'Annual Minimum Module Temperature__open_rack_cell_polymerback (C)'
            maxTemp = 'Annual Maximum Module Temperature__open_rack_cell_polymerback (C)'
            avgTemp = 'Annual Average Module Temperature__open_rack_cell_polymerback (C)'
            module98 = 'Annual Average (98th Percentile) Module Temperature__open_rack_cell_polymerback (C)'                        
            chartHeader = '98th Percentile Module Temperature Open Rack Cell Polymer Back (C)'
            htmlString = '_open_rack_cell_polymerback'
            colorSelector = 'Spectral6'
            #Assign the upper and lower bounds of the map 
            mapScaleUpper = 100
            mapScaleLower = 20
            
        elif mapSelect == 'insulated_back_polymerback98th':
            moduleType = 'Annual Average (98th Percentile) Module Temperature__insulated_back_polymerback (C)'            
            minTemp = 'Annual Minimum Module Temperature__insulated_back_polymerback (C)'
            maxTemp = 'Annual Maximum Module Temperature__insulated_back_polymerback (C)'
            avgTemp = 'Annual Average Module Temperature__insulated_back_polymerback (C)'
            module98 = 'Annual Average (98th Percentile) Module Temperature__insulated_back_polymerback (C)'                        
            chartHeader = '98th Percentile Module Temperature Insulated Back Polymer Back (C)'
            htmlString = '_insulated_back_polymerback'
            colorSelector = 'Spectral6'
            #Assign the upper and lower bounds of the map 
            mapScaleUpper = 100
            mapScaleLower = 20
            
        elif mapSelect == 'open_rack_polymer_thinfilm_steel98th':
            moduleType = 'Annual Average (98th Percentile) Module Temperature__open_rack_polymer_thinfilm_steel (C)'            
            minTemp = 'Annual Minimum Module Temperature__open_rack_polymer_thinfilm_steel (C)'
            maxTemp = 'Annual Maximum Module Temperature__open_rack_polymer_thinfilm_steel (C)'
            avgTemp = 'Annual Average Module Temperature__open_rack_polymer_thinfilm_steel (C)'
            module98 = 'Annual Average (98th Percentile) Module Temperature__open_rack_polymer_thinfilm_steel (C)'        
            chartHeader = '98th Percentile Module Temperature Open Rack Polymer Thin Film Steel (C)'
            htmlString = '_open_rack_polymer_thinfilm_steel'
            colorSelector = 'Spectral6' 
            #Assign the upper and lower bounds of the map 
            mapScaleUpper = 100
            mapScaleLower = 20
            
        elif mapSelect == '22x_concentrator_tracker98th':
            moduleType = 'Annual Average (98th Percentile) Module Temperature__22x_concentrator_tracker (C)'            
            minTemp = 'Annual Minimum Module Temperature__22x_concentrator_tracker (C)'
            maxTemp = 'Annual Maximum Module Temperature__22x_concentrator_tracker (C)'
            avgTemp = 'Annual Average Module Temperature__22x_concentrator_tracker (C)'
            module98 = 'Annual Average (98th Percentile) Module Temperature__22x_concentrator_tracker (C)'            
            chartHeader = '98th Percentile Module Temperature 22x Concentrator Tracker (C)'
            htmlString = '_22x_concentrator_tracker'
            colorSelector = 'Spectral6'
            #Assign the upper and lower bounds of the map 
            mapScaleUpper = 100
            mapScaleLower = 20
            
            
        ### Average Temp Maps  
        elif mapSelect == 'AverageModuleTemperature__open_rack_cell_glassback':
            moduleType = 'Annual Average Module Temperature__open_rack_cell_glassback (C)'
            minTemp = 'Annual Minimum Module Temperature__open_rack_cell_glassback (C)'
            maxTemp = 'Annual Maximum Module Temperature__open_rack_cell_glassback (C)'
            avgTemp = 'Annual Average Module Temperature__open_rack_cell_glassback (C)'
            module98 = 'Annual Average (98th Percentile) Module Temperature__open_rack_cell_glassback (C)'
            chartHeader = 'Annual Average Module Temperature Open Rack Cell Glassback (C)'
            htmlString = 'Average_Temp_open_rack_cell_glassback'
            colorSelector = 'Spectral6'
            #Assign the upper and lower bounds of the map 
            mapScaleUpper = 35
            mapScaleLower = 1
            
        elif mapSelect == 'AverageModuleTemperature__roof_mount_cell_glassback':
            moduleType = 'Annual Average Module Temperature__roof_mount_cell_glassback (C)'
            minTemp = 'Annual Minimum Module Temperature__roof_mount_cell_glassback (C)'
            maxTemp = 'Annual Maximum Module Temperature__roof_mount_cell_glassback (C)'
            avgTemp = 'Annual Average Module Temperature__roof_mount_cell_glassback (C)'
            module98 = 'Annual Average (98th Percentile) Module Temperature__roof_mount_cell_glassback (C)'
            chartHeader = 'Annual Average Module Temperature Roof Mount Cell Glassback (C)'
            htmlString = 'Average_Temp_roof_mount_cell_glassback'
            colorSelector = 'Spectral6'
            #Assign the upper and lower bounds of the map 
            mapScaleUpper = 35
            mapScaleLower = 1 
            
        elif mapSelect == 'AverageModuleTemperature__open_rack_cell_polymerback':
            moduleType = 'Annual Average Module Temperature__open_rack_cell_polymerback (C)'
            minTemp = 'Annual Minimum Module Temperature__open_rack_cell_polymerback (C)'
            maxTemp = 'Annual Maximum Module Temperature__open_rack_cell_polymerback (C)'
            avgTemp = 'Annual Average Module Temperature__open_rack_cell_polymerback (C)'
            module98 = 'Annual Average (98th Percentile) Module Temperature__open_rack_cell_polymerback (C)'
            chartHeader = 'Annual Average Module Temperature Open Rack Cell Polymerback (C)'
            htmlString = 'Average_Temp_open_rack_cell_polymerback'
            colorSelector = 'Spectral6'
            #Assign the upper and lower bounds of the map 
            mapScaleUpper = 35
            mapScaleLower = 1    
            
        elif mapSelect == 'AverageModuleTemperature__insulated_back_polymerback':
            moduleType = 'Annual Average Module Temperature__insulated_back_polymerback (C)'
            minTemp = 'Annual Minimum Module Temperature__insulated_back_polymerback (C)'
            maxTemp = 'Annual Maximum Module Temperature__insulated_back_polymerback (C)'
            avgTemp = 'Annual Average Module Temperature__insulated_back_polymerback (C)'
            module98 = 'Annual Average (98th Percentile) Module Temperature__insulated_back_polymerback (C)'
            chartHeader = 'Annual Average Module Temperature Insulated Back Polymerback (C)'
            htmlString = 'Average_Temp_insulated_back_polymerback'
            colorSelector = 'Spectral6'
            #Assign the upper and lower bounds of the map 
            mapScaleUpper = 35
            mapScaleLower = 1   
            
        elif mapSelect == 'AverageModuleTemperature__open_rack_polymer_thinfilm_steel':
            moduleType = 'Annual Average Module Temperature__open_rack_polymer_thinfilm_steel (C)'
            minTemp = 'Annual Minimum Module Temperature__open_rack_polymer_thinfilm_steel (C)'
            maxTemp = 'Annual Maximum Module Temperature__open_rack_polymer_thinfilm_steel (C)'
            avgTemp = 'Annual Average Module Temperature__open_rack_polymer_thinfilm_steel (C)'
            module98 = 'Annual Average (98th Percentile) Module Temperature__open_rack_polymer_thinfilm_steel (C)'
            chartHeader = 'Annual Average Module Temperature Open Rack Polymer Thinfilm Steel (C)'
            htmlString = 'Average_Temp_open_rack_polymer_thinfilm_steel'
            colorSelector = 'Spectral6'
            #Assign the upper and lower bounds of the map 
            mapScaleUpper = 35
            mapScaleLower = 1   
            
        elif mapSelect == 'AverageModuleTemperature__22x_concentrator_tracker':
            moduleType = 'Annual Average Module Temperature__22x_concentrator_tracker (C)'
            minTemp = 'Annual Minimum Module Temperature__22x_concentrator_tracker (C)'
            maxTemp = 'Annual Maximum Module Temperature__22x_concentrator_tracker (C)'
            avgTemp = 'Annual Average Module Temperature__22x_concentrator_tracker (C)'
            module98 = 'Annual Average (98th Percentile) Module Temperature__22x_concentrator_tracker (C)'
            chartHeader = 'Annual Average Module Temperature 22x Concentrator Tracker (C)'
            htmlString = 'Average_Temp_22x_concentrator_tracker'
            colorSelector = 'Spectral6'
            #Assign the upper and lower bounds of the map 
            mapScaleUpper = 35
            mapScaleLower = 1        
        

        
        
        



        #Create the html to be exported
        output_file('Module_Temperature_Map' + htmlString + '.html') 
        
        # Create the tools used for zooming and hovering on the map
        tools = "pan,wheel_zoom,box_zoom,reset,previewsave"
        
        #Access the .json file to create the map of countries and states
        # THe json files will create layers to overlap the data with
        with open(path + "/Map/countries.geojson", "r") as f:
            countries = bkm.GeoJSONDataSource(geojson=f.read())  
        with open(path + "/Map/us-states.json", "r") as f:
            states = bkm.GeoJSONDataSource(geojson=f.read())      
        
        #Access the processed summary data pickle
        level_1_df = pd.read_pickle(path + "\\Pandas_Pickle_DataFrames\\Pickle_Level1_Summary\\Pickle_Level1_Summary.pickle")
    
        # Bring in all the data to display on map
        
        #Radius is the size of the circle to be displayed on the map
        radiusList = []
        for i in range(0, len(level_1_df)):
            #Toggle size of circle
            radiusList.append(2)
        radius = radiusList
        selector = level_1_df[moduleType]
        station = level_1_df['Station name']
        latitude = level_1_df['Site latitude']
        longitude = level_1_df['Site longitude']
        
        uniqueID = level_1_df['Site Identifier Code']
        dataSource = level_1_df['Data Source']
        
        moduleTemp98 = level_1_df[module98]
        moduleMinTemp = level_1_df[minTemp]            
        moduleMaxTemp = level_1_df[maxTemp]
        moduleAvgTemp = level_1_df[avgTemp]
    
    
    
        # The Boken map rendering package needs to store data in the ColumnDataFormat
        # Store the lat/lon from the Map_pickle.  Formatting for Lat/Lon has been 
        # processed prior see "Map_Pickle_Processing.py" file for more details 
        # Add other data to create hover labels
        source = ColumnDataSource(
            data = dict(
                Lat = latitude,
                Lon = longitude,
                radius = radius,
                selector = selector,
                Station = station,
                Latitude = latitude,
                Longitude = longitude,
                Module_Temp98 = moduleTemp98,
                Module_Min_Temp = moduleMinTemp,
                Module_Avg_Temp = moduleAvgTemp,
                Module_Max_Temp = moduleMaxTemp,
                uniqueID = uniqueID,
                dataSource = dataSource
                ) )
        
        # Create the figure with the map parameters.  This controls the window
        p = bkp.figure(width=1500, 
                   height=900, 
                   tools=tools, 
                   title= chartHeader ,
                   
                   x_axis_type="mercator",
                   y_axis_type="mercator",
    
                   x_axis_label='Longitude', 
                   y_axis_label='Latitude')
    
        p.x_range = bkm.Range1d(start=-180, end=180)
        p.y_range = bkm.Range1d(start=-90, end=90)
    
    
        #Create the datapoints as overlapping circles
        p.circle("Lon",
                 "Lat", 
                 source= source , 
                 radius="radius" , 
                 #fill color will use linear_cmap() to scale the colors of the circles being displayed
                 fill_color = linear_cmap('selector', colorSelector, low= mapScaleLower, high= mapScaleUpper),
                 line_color =None,  
                 # Alpha is the transparency of the circle
                 alpha=0.3)
        #Stations will be the black dots displayed on the map
        stations = p.circle("Lon",
                 "Lat", 
                 source=source , 
                 radius= .1 , 
                 #fill color will use linear_cmap() to scale the colors of the circles being displayed
                 fill_color = 'black',
                 line_color = None,
                 # Alpha is the transparency of the circle
                  alpha=.99)   
    
    
        #Create the scale bar to the right of the map
        
        # Create color mapper to make the scale bar on the right of the map
        # palette = color scheme of the mapo
        # low/high sets the scale of the data, use the minimum value and maximum value of the data we are analyzing
        color_mapper = LinearColorMapper(palette= colorSelector,  low= mapScaleLower, high=mapScaleUpper)
        
        # color bar will be scale bar set to the right of the map
        color_bar = ColorBar(color_mapper=color_mapper, ticker=LogTicker(),
                         label_standoff=12, border_line_color=None, location=(0,0))
        # Assign the scale bar to " p " and put it to the right
        p.add_layout(color_bar, 'right')
        
    
        # These are the labels that are displayed when you hover over a spot on the map
        #( label , @data), data needs to be inside the ColumnDataSource()
        TOOLTIPS = [
        ("Station","@Station") ,
        ("Site ID","@uniqueID"),
        ("Data Source", "@dataSource"),
        ("Lat","@Latitude"),
        ("Lon","@Longitude"),
        
        ("Module Minimum Temp","@Module_Min_Temp" + " (C)"),
        ("Module Average Temp","@Module_Avg_Temp" + " (C)"),
        ("Module Maximum Temp","@Module_Max_Temp" + " (C)"),
        ("98 Percentile Module Temp","@Module_Temp98" + " (C)")
        ]
        
        #Create a hover tool that will rinder only the weather stations i.e stations are small black circles
        hover_labels = bkm.HoverTool(renderers=[stations],
                             tooltips= TOOLTIPS )
        #Add the hover tool to the map
        p.add_tools(hover_labels)
        #Overlay the Country and States boarders
        p.patches("xs", "ys", color="white", line_color="black", source=countries , fill_alpha = 0 , line_alpha = 1)
        p.patches("xs", "ys", color="white", line_color="black", source=states , fill_alpha = 0 , line_alpha = 1)
        #Display the plot
        show(p)