Beispiel #1
0
 def create_map(self):
     self.ns = Namespace("dlx", "scatter")
     self.markers = [
         dl.Marker(
             dl.Tooltip(f"({pos[0]}, {pos[1]}), time:{self.times[i]}"),
             position=pos,
             id="marker{}".format(i))
         for i, pos in enumerate(self.locations)
     ]
     self.cluster = dl.MarkerClusterGroup(
         id="markers",
         children=self.markers,
         options={"polygonOptions": {
             "color": "red"
         }})
     self.app = dash.Dash(external_scripts=[
         "https://cdnjs.cloudflare.com/ajax/libs/chroma-js/2.1.0/chroma.min.js"
     ])
     self.polyline = dl.Polyline(positions=self.locations)
     self.app.layout = html.Div([
         dl.Map([
             dl.TileLayer(), self.cluster, self.polyline,
             dl.LayerGroup(id="layer")
         ],
                id="map",
                center=(40.4259, -86.9081),
                zoom=8,
                style={'height': '100vh'}),
     ])
Beispiel #2
0
def get_map_panel_zip_layout():
    classes = [0, 100, 500, 1000, 2000, 5000, 10000, 20000]
    colorscale = [
        "#FFEDA0",
        "#FED976",
        "#FEB24C",
        "#FD8D3C",
        "#FC4E2A",
        "#E31A1C",
        "#BD0026",
        "#800026",
    ]
    style = {
        "weight": 2,
        "opacity": 1,
        "color": "white",
        "dashArray": 3,
        "fillOpacity": 0.7,
    }

    ctg = ["{}+".format(cls, classes[i + 1]) for i, cls in enumerate(classes[:-1])] + [
        "{}+".format(classes[-1])
    ]
    colorbar = dlx.categorical_colorbar(
        categories=ctg,
        colorscale=colorscale,
        width=400,
        height=30,
        position="bottomright",
    )

    ns = Namespace("dlx", "choropleth")
    zip_geojson = dl.GeoJSON(
        data=None,  # url to geojson file
        options=dict(style=ns("style")),  # how to style each polygon
        zoomToBounds=False,  # when true, zooms to bounds when data changes (e.g. on load)
        zoomToBoundsOnClick=True,  # when true, zooms to bounds of feature (e.g. polygon) on click
        hoverStyle=arrow_function(
            dict(weight=5, color="#666", dashArray="")
        ),  # style applied on hover
        hideout=dict(
            colorscale=colorscale, classes=classes, style=style, colorProp="Amount"
        ),
        id="zips-geojson",
    )

    stl_center = [38.648, -90.253]
    city_map_style = {"height": "100vh", "margin": "none", "display": "block"}
    city_map = html.Div(
        dl.Map(
            children=[get_base_toner_tile_layer(), zip_geojson, colorbar],
            zoom=12,
            center=stl_center,
        ),
        style=city_map_style,
        id="map",
    )
    map_panel_style = {"width": "100%", "height": "100vh", "display": "block"}
    map_panel = html.Div(id="map-panel", children=city_map, style=map_panel_style)
    return map_panel
Beispiel #3
0
def get_neighborhood_geojson():
    ns = Namespace("dlx", "choropleth")
    neighborhoods_geobuf_path = "static/geobuf/neighborhoods-and-municipalities.pbf"
    neighborhoods_geojson = dl.GeoJSON(
        format="geobuf",
        options=dict(style=ns("style")),
        hoverStyle=arrow_function(dict(weight=5, color="#666", dashArray="")),
        hideout=bootstrap_stuff.build_choropleth_hideout(
            "total_monetary_donations"),
        id="neighborhood-geojson",
    )
    return neighborhoods_geojson
Beispiel #4
0
def get_precinct_geojson():
    ns = Namespace("dlx", "choropleth")
    precincts_geobuf_path = "dsadata/static/geobuf/stl-city-and-county-precincts.pbf"
    precincts_geojson = dl.GeoJSON(
        format="geobuf",
        options=dict(style=ns("style")),
        hoverStyle=arrow_function(dict(weight=5, color="#666", dashArray="")),
        hideout=bootstrap_stuff.build_choropleth_hideout(
            "total_monetary_donations"),
        id="precincts-geojson",
    )
    return precincts_geojson
Beispiel #5
0
def get_neighborhood_geojson():
    ns = Namespace("dlx", "choropleth")
    neighborhoods_geojson = dl.GeoJSON(
        format="geobuf",
        options=dict(style=ns("style")),
        hoverStyle=arrow_function(dict(weight=5, color="#666", dashArray="")),
        zoomToBoundsOnClick=
        False,  # when true, zooms to bounds of feature (e.g. polygon) on click
        hideout=bootstrap_stuff.build_choropleth_hideout(
            "total_monetary_donations"),
        id="neighborhood-geojson",
    )
    return neighborhoods_geojson
Beispiel #6
0
def get_zip_geojson():
    ns = Namespace("dlx", "choropleth")
    zip_geojson = dl.GeoJSON(
        format="geobuf",
        options=dict(style=ns("style")),  # how to style each polygon
        # options=dict(style=dict(color="blue")),
        zoomToBounds=
        False,  # when true, zooms to bounds when data changes (e.g. on load)
        zoomToBoundsOnClick=
        False,  # when true, zooms to bounds of feature (e.g. polygon) on click
        hoverStyle=arrow_function(dict(weight=5, color="#666", dashArray="")),
        hideout=bootstrap_stuff.build_choropleth_hideout(
            "total_monetary_donations"),
        id="zip-geojson",
    )
    return zip_geojson
Beispiel #7
0
def get_precinct_overlay():
    # original file was wrong hand rule, whis one was rewound with geojson-rewind:
    precinct_pbf_url = "dsadata/static/geobuf/stl-city-precincts.pbf"
    ns = Namespace("dlx", "choropleth")
    precincts = dl.GeoJSON(
        url=precinct_pbf_url,
        format="geobuf",
        options=dict(style=ns("style")),
        zoomToBoundsOnClick=True,
        hoverStyle=arrow_function(dict(weight=4, fillOpacity=0.2,
                                       dashArray="")),
        hideout=bootstrap_stuff.build_choropleth_hideout("total_donations"),
        id="precincts-geojson",
    )
    precinct_overlay = dl.Overlay(precincts, name="precincts", checked=False)
    return precinct_overlay
Beispiel #8
0
encoded_quaa_sound = base64.b64encode(open(quaa_sound, 'rb').read())
encoded_moan_sound = base64.b64encode(open(moan_sound, 'rb').read())

app = dash.Dash(__name__,
                suppress_callback_exceptions=True,
                external_stylesheets=[dbc.themes.BOOTSTRAP])
app.title = 'SQURL'
server = app.server

# Find Lat Long center to set map center
lat_center = sum(squirrel_census['lat']) / len(squirrel_census['lat'])
long_center = sum(squirrel_census['lon']) / len(squirrel_census['lon'])

data = dlx.geojson_to_geobuf(dlx.dicts_to_geojson(squirrel_data))

ns = Namespace("myNamespace", "mySubNamespace")
nz = Namespace("dlx", "scatter")

# get map style
url = 'https://tiles.stadiamaps.com/tiles/alidade_smooth_dark/{z}/{x}/{y}{r}.png'
attribution = '&copy; <a href="https://stadiamaps.com/">Stadia Maps</a> '

app.layout = html.Div(
    children=[

        # HEADER
        html.Div(
            children=[
                html.H1('SQURL', id='header-text'),

                # SOUNDS
Beispiel #9
0
        item['tooltip'] = item['project_nickname']
        item['popup'] = item['cpa_name']
    geojson = dlx.dicts_to_geojson(dicts,
                                   lat='coordinate_x',
                                   lon="coordinate_y")
    geobuf = dlx.geojson_to_geobuf(geojson)
    return geobuf


# create cpa dropdown
cpas = df['cpa_name'].unique()
cpa_options = [{'label': cpa, 'value': cpa} for cpa in cpas]
dd_cpa = dcc.Dropdown(options=cpa_options, id='dd_cpa')

# set up scatter points
ns = Namespace('dlx', 'scatter')
geojson = dl.GeoJSON(
    data=get_data(None),
    id='geojson',
    format='geobuf',
    zoomToBounds=True,
    cluster=True,
    #  clusterToLayer=ns("clusterToLayer"),
    zoomToBoundsOnClick=True,
    #  options=dict(pointToLayer=ns('pointToLayer')),
    superClusterOptions=dict(radius=150))
#  hideout=dict(colorscale='Viridis', colorProp='cpa'))

# add cpa boundaries
cpa_boundaries = dl.GeoJSON(
    id='rfmp',
default_variable = "temperature"
variable_options = [
    {'label': 'Temp.', 'value': 'temperature'},
    {'label': 'MSLP', 'value': 'smlp'},
    {'label': 'Hum.', 'value': 'rh'},
    {'label': 'Wind Sp.', 'value': 'wind_speed'},
    {'label': 'Wind G.', 'value': 'wind_gust'},
    {'label': 'Rain', 'value': 'rain_rate'},
    {'label': 'Daily Rain', 'value': 'daily_rain'},
    {'label': 'Dewp', 'value': 'dew_point'},
    {'label': 'Rad', 'value': 'rad'},
]


ns = Namespace("myNamespace", "mySubNamespace")
geojson_countries = dl.GeoJSON(data=statesData, id="geojson_countries",
                               options=dict(style=dict(weight=1, opacity=0.7, color='white', fillOpacity=0)))

# Create the app.
chroma = "https://cdnjs.cloudflare.com/ajax/libs/chroma-js/2.1.0/chroma.min.js"
app = Dash(__name__,
           external_scripts=[chroma],
           prevent_initial_callbacks=True,
           url_base_pathname='/weathermap-it/')
server = app.server


cache = Cache(server, config={'CACHE_TYPE': 'filesystem',
                             'CACHE_DIR': '/tmp'})
Beispiel #11
0
state_names = df.groupby('nbhid').first()['nbh_name'].dropna().to_dict()
state_options = [
    dict(label=state_names[state], value=state) for state in states
]
default_state = ["76"]
dd_state = dcc.Dropdown(options=state_options,
                        value=default_state,
                        id="dd_state",
                        clearable=False,
                        multi=True)

# endregion

minmax = get_minmax(default_state)
# Create geojson.
ns = Namespace("dlx", "scatter")
geojson = dl.GeoJSON(
    data=get_data(default_state, [2015, 2020]),
    id="geojson",
    format="geobuf",
    zoomToBounds=False,  # when true, zooms to bounds when data changes
    cluster=True,  # when true, data are clustered
    # how to draw clusters
    clusterToLayer=ns("clusterToLayer"),
    # when true, zooms to bounds of feature (e.g. cluster) on click
    zoomToBoundsOnClick=False,
    # how to draw points
    options=dict(pointToLayer=ns("pointToLayer")),
    superClusterOptions=dict(radius=150),  # adjust cluster size
    hideout=dict(colorscale=csc_map[default_csc],
                 colorProp=color_prop,
Beispiel #12
0
    df[df["nbhid"] == state]["nbh_name"].iloc[0] for state in states
]
state_options = [
    dict(label=state_names[i], value=state) for i, state in enumerate(states)
]
default_state = "76"
dd_state = dcc.Dropdown(options=state_options,
                        value=default_state,
                        id="dd_state",
                        clearable=False)

# endregion

minmax = get_minmax(default_state)
# Create geojson.
ns = Namespace("dlx", "scatter")
geojson = dl.GeoJSON(
    data=get_data(default_state, [2015, 2020]),
    id="geojson",
    format="geobuf",
    zoomToBounds=True,  # when true, zooms to bounds when data changes
    cluster=True,  # when true, data are clustered
    clusterToLayer=ns("clusterToLayer"),  # how to draw clusters
    zoomToBoundsOnClick=
    True,  # when true, zooms to bounds of feature (e.g. cluster) on click
    options=dict(pointToLayer=ns("pointToLayer")),  # how to draw points
    superClusterOptions=dict(radius=150),  # adjust cluster size
    hideout=dict(colorscale=csc_map[default_csc],
                 colorProp=color_prop,
                 **minmax))
# Create a colorbar.
Beispiel #13
0
def generate_choropleth(metric, violation, subcategory, year):
    """Updates the choropleth map on tab 1 when triggered
    
    Parameters
    -------
    String
        The name of the metric selected from the dropdown
    String
        The violation selected from the dropdown
    String
        The subcategory selected from the dropdown
    Int
        The year selected from the slider
    
    Returns
    -------
    html
        A leaflet choropleth map
    """

    geojson = PROVINCES
    df = DATA[(DATA["Metric"] == metric)
              & (DATA["Level1 Violation Flag"] == violation) &
              (DATA["Violation Description"] == subcategory) &
              (DATA["Year"] == year) & (DATA['Geo_Level'] == "PROVINCE")]

    data_dict = dict(zip(df['Geography'], df['Value']))

    for location in geojson['features']:
        try:
            lookup_val = data_dict[location['properties']['PRENAME']]
        except:
            lookup_val = None
        location['properties']['Value'] = lookup_val

    num = 13  # number of provinces and territories in Canada
    vals = pd.Series(data_dict.values())
    classes = list(
        np.linspace(int(vals.min()) - 0.01, int(vals.max()) + 0.01, num=num))
    mm = dict(min=vals.min(), max=vals.max())

    viridis = cm.get_cmap('viridis', num)
    colorscale = []
    for i in range(viridis.N):
        rgba = viridis(i)
        colorscale.append(matplotlib.colors.rgb2hex(rgba))

    style = dict(weight=1, color='black', fillOpacity=0.7)
    hover_style = dict(weight=5, color='orange', dashArray='')
    ns = Namespace("dlx", "choropleth")

    return [
        dl.TileLayer(),
        dl.GeoJSON(data=geojson,
                   id="provinces",
                   options=dict(style=ns("style")),
                   hideout=dict(colorscale=colorscale[::-1],
                                classes=classes,
                                style=style,
                                colorProp="Value"),
                   hoverStyle=arrow_function(hover_style)),
        dl.Colorbar(colorscale=colorscale[::-1],
                    id="colorbar",
                    width=20,
                    height=150,
                    **mm,
                    position="bottomleft")
    ]
Beispiel #14
0
def run():
    # defining the number of steps
    n = 500

    #creating two array for containing x and y coordinate
    #of size equals to the number of size and filled up with 0's
    x = numpy.zeros(n)
    y = numpy.zeros(n)
    global locations

    locations = []  #used in map generator
    locations_base = []  #the base data.
    start_location = [40.4259, -86.9081]
    at_risk = numpy.random.uniform(low=0.0, high=1.1, size=(n, ))
    start_time = 0
    map_dir = "index.html"
    MINUTES_IN_DAY = 1440
    start_date = datetime.datetime.now()

    times = list(range(0, n))
    time_index = 0
    datetimes = []

    for i in range(len(times)):
        noise = random.randint(1, 5)
        times[i] = (times[i] + noise)
        datetimes.append(start_date + timedelta(minutes=times[i]))

    datetimeindex = pd.Series(range(0, n), index=datetimes)

    #filling the coordinates with random variables
    for i in range(1, n):
        val = random.randint(1, 4)
        if val == 1:
            x[i] = x[i - 1] + 0.001
            y[i] = y[i - 1]
        elif val == 2:
            x[i] = x[i - 1] - 0.001
            y[i] = y[i - 1]
        elif val == 3:
            x[i] = x[i - 1]
            y[i] = y[i - 1] + 0.001
        else:
            x[i] = x[i - 1]
            y[i] = y[i - 1] - 0.001
        locations_base.append(
            [x[i] + start_location[0], y[i] + start_location[1]])

    ns = Namespace("dlx", "scatter")

    new_markers = [
        dl.Marker(dl.Tooltip(f"({pos[0]}, {pos[1]}), time:{times[i]}"),
                  position=pos,
                  id="marker{}".format(i)) for i, pos in enumerate(locations)
    ]

    cluster = dl.MarkerClusterGroup(
        id="new_markers",
        children=new_markers,
        options={"polygonOptions": {
            "color": "red"
        }})

    patterns = [dict(offset='0%', repeat='0', marker={})]
    polyline = dl.Polyline(positions=[locations], id="id_polyline")
    marker_pattern = dl.PolylineDecorator(id="id_marker_pattern",
                                          children=polyline,
                                          patterns=patterns)

    app = dash.Dash(external_scripts=[
        "https://cdnjs.cloudflare.com/ajax/libs/chroma-js/2.1.0/chroma.min.js"
    ])
    app.layout = html.Div(
        html.Div([
            dl.Map([
                dl.TileLayer(), cluster, marker_pattern,
                dl.LayerGroup(id="layer")
            ],
                   id="map",
                   center=(40.4259, -86.9081),
                   zoom=8,
                   style={'height': '100vh'}),
            #html.Div(id='live-update-text'),
            dcc.Interval(
                id="interval",
                interval=1 * 1000,  # in milliseconds
                n_intervals=0)
        ]))

    @app.callback(Output('id_marker_pattern', 'children'),
                  [Input('interval', 'n_intervals')])
    def update_polyline(b):
        polyline = dl.Polyline(positions=locations)
        return polyline

    @app.callback(Output('new_markers', 'children'),
                  [Input('interval', 'n_intervals')])
    def update_metrics(a):

        locations.append([locations_base[a][0], locations_base[a][1]])
        if (len(locations) >= 100):
            locations.pop(0)
        new_markers = [
            dl.Marker(dl.Tooltip(f"({pos[0]}, {pos[1]}), time:{times[i]}"),
                      position=pos,
                      id="marker{}".format(i))
            for i, pos in enumerate(locations)
        ]
        return new_markers

    def rgb_to_hex(rgb):
        return ('%02x%02x%02x' % rgb)

    def get_time_interval(sd, ed):
        indices = datetimeindex[sd:ed].to_numpy()
        print(indices)

    def change_color_to_time():
        for i in range(len(locations)):
            time = times[i]
            r = 255 - math.trunc(255 * (time / MINUTES_IN_DAY))
            color_tuple = (r, r, r)
            rgb = rgb_to_hex(color_tuple)
            icon = {
                "iconUrl":
                f"http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|{rgb}&chf=a,s,ee00FFFF",
                "iconSize": [20, 30],  # size of the icon
            }
            markers[i].icon = icon

    def change_color_to_risk():
        for i in range(len(locations)):
            time = times[i]
            risk = math.trunc(at_risk[i])
            if (risk == 1):
                icon = {
                    "iconUrl":
                    "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|FF0000&chf=a,s,ee00FFFF",
                    "iconSize": [20, 30],  # size of the icon
                }
            else:
                icon = {
                    "iconUrl":
                    "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|00FF00&chf=a,s,ee00FFFF",
                    "iconSize": [20, 30],  # size of the icon
                }
            markers[i].icon = icon
            print("risk")

    def clamp(n, minn, maxn):
        return max(min(maxn, n), minn)

    def change_color_to_speed():
        speed = 0
        avewalk = 0.084
        speeddiff = 0

        for i in range(len(locations)):
            if i == 0:
                speed = 0
            elif (times[i] - times[i - 1]) == 0:
                speed = 0
            else:
                #coords_1 = [locations[i][0], locations[i][1]]
                #coords_2 = [locations[i-1][0], locations[i-1][1]]
                #distance = h3.point_dist(coords_1,coords_2)
                R = 6373.0
                lat1 = radians(locations[i][0])
                lon1 = radians(locations[i][1])
                lat2 = radians(locations[i - 1][0])
                lon2 = radians(locations[i - 1][1])
                dlon = lon2 - lon1
                dlat = lat2 - lat1
                a = 2
                ##sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
                c = 2
                ##2 * atan2(sqrt(a), sqrt(1 - a))
                distance = R * c
                speed = abs(distance / (times[i] - times[i - 1]))

            speeddiff = speed * 1000 / 60 - 1.4
            r = clamp(100 + speeddiff * 300, 0,
                      255)  #grey normal, yellow fast, blue slow
            g = clamp(100 + speeddiff * 100, 0, 255)
            b = clamp(100 - speeddiff * 100, 0, 255)
            color_tuple = (int(r), int(g), int(b))
            rgb = rgb_to_hex(color_tuple)
            icon = {
                "iconUrl":
                f"http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|{rgb}&chf=a,s,ee00FFFF",
                "iconSize": [20, 30],  # size of the icon
            }
            markers[i].icon = icon

    app.run_server(port=8050)
Beispiel #15
0
import pandas as pd

import dash
from dash import html, dcc
import dash_bootstrap_components as dbc
from dash_extensions.javascript import Namespace
from dash.dependencies import Input, Output, State
from dash.exceptions import PreventUpdate

from dash_tabulator import DashTabulator

from . import tools as T


ns = Namespace("myNamespace", "tabulator")

tabulator_options = {
           "groupBy": "Label", 
           "selectable": True,
           "headerFilterLiveFilterDelay":3000,
           "layout": "fitDataFill",
           "height": "900px",
           }

downloadButtonType = {"css": "btn btn-primary", "text":"Export", "type":"csv", "filename":"Metadata"}

clearFilterButtonType = {"css": "btn btn-outline-dark", "text":"Clear Filters"}

meta_table = html.Div(id='meta-table-container', 
    style={'minHeight':  100, 'margin': '0%'},
    children=[
Beispiel #16
0

##options
quantiles = cases_per_city["cases"].quantile([0,.25,.5,.75, 0.9])

quantiles = [int(n) for n in quantiles.values]

classes = quantiles
colorscale = ['#FED976', '#FEB24C', '#FD8D3C', '#FC4E2A', '#800026']
style = dict(weight=2, opacity=1, color='white', dashArray='3', fillOpacity = 0.7)

# Create colorbar.
ctg = ["{}+".format(cls, classes[i + 1]) for i, cls in enumerate(classes[:-1])] + ["{}+".format(classes[-1])]
colorbar = dlx.categorical_colorbar(categories=ctg, colorscale=colorscale, width=300, height=30, position="bottomleft")

ns = Namespace("dlx", "choropleth")
### Define layouts
geojson = dl.GeoJSON(
    data = json_data,
    options=dict(style=ns("style")),
    zoomToBoundsOnClick = False,
    hoverStyle=arrow_function(dict(weight=2, color='#666', dashArray='', fillOpacity=0.2)),  # style applied on hover
    hideout=dict(colorscale=colorscale, classes=classes, style=style, colorProp = "cases"),
    id = "geojson")




cont = dbc.Card(
    [
        dbc.CardImg(src = "assets/form.svg", top = True, className = "card-img"),
Beispiel #17
0
            pills=True)
    ],
    style=SIDEBAR_STYLE)

# Setting urls to fetch tiles from for the map
keys = [
    'https://tiles.stadiamaps.com/tiles/alidade_smooth/{z}/{x}/{y}{r}.png',
    'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
    'https://tiles.stadiamaps.com/tiles/alidade_smooth_dark/{z}/{x}/{y}{r}.png'
]
# labels for the urls
names = ['Standaard', 'Detailed', 'Dark']
# The url will be put here when formatted
url = '{}'

namespaceSelected = Namespace("namespace", "namespaceSub")
layout2 = dl.Map(
    center=(52.377956, 4.897070),
    zoom=11,
    zoomControl=True,
    children=[
        dl.LayersControl(
            [
                dl.BaseLayer(dl.TileLayer(opacity=0.8, url=url.format(key)),
                             name=names[keys.index(key)],
                             checked=key == keys[0]) for key in keys
            ] + [
                dl.GeoJSON(data=get_data(df),
                           format='geobuf',
                           cluster=True,
                           clusterToLayer=namespaceSelected('clusterToLayer'),