Exemplo n.º 1
0
def map_click(click_lat_lng, business_type, transportation_type, time_limit):
    if click_lat_lng is None:
        raise PreventUpdate
    if business_type is None:
        raise PreventUpdate
    if transportation_type is None:
        raise PreventUpdate
    if time_limit is None:
        raise PreventUpdate

    time_limit = time_limit * 60
    print(click_lat_lng, time_limit, transportation_type, business_type)
    df = hfa.get_data_around_point(click_lat_lng, time_limit,
                                   transportation_type, business_type)
    if df is None:
        raise PreventUpdate
    table = make_dash_table(df)
    center_marker = [
        dl.Marker(position=click_lat_lng, children=dl.Tooltip("You are here"))
    ]
    df = df.sort_values(by="travel")
    markers = [
        dl.Marker(
            position=row[1][["latitude", "longitude"]].values,
            children=dl.Tooltip(row[1]["name"]),
        ) for row in df.iterrows()
    ]

    return table, center_marker, markers
Exemplo n.º 2
0
def map_click(clicks, click_lat_lng, search_input):

    changed_id = [p['prop_id'] for p in dash.callback_context.triggered][0]
    empty = search_input == None

    if not empty and 'search-button' in changed_id:

        location = geolocator.geocode(search_input)
        if location == None:
            marker, location_string = None, 'Failed to find location based on search input'
        else:
            search_lat_long = [location.latitude, location.longitude]
            location_string = "Selected location: ({:.3f}, {:.3f})".format(
                *search_lat_long)
            marker = [
                dl.Marker(position=search_lat_long,
                          children=dl.Tooltip(location_string))
            ]

    elif not click_lat_lng == None:

        location_string = "Selected location: ({:.3f}, {:.3f})".format(
            *click_lat_lng)
        marker = [
            dl.Marker(position=click_lat_lng,
                      children=dl.Tooltip(location_string))
        ]

    return marker, location_string
Exemplo n.º 3
0
def map_click(coordinates, month):
    global last_valid

    if coordinates == None:
        coordinates = last_valid
    else:
        last_valid = coordinates

    if coordinates[0] < 32.534156 or coordinates[0] > 42.009518 or coordinates[1] <-124.409591 or coordinates[1] > -114.131211:
        return [dl.Marker(position=coordinates, children=dl.Tooltip("({:.3f}, {:.3f})".format(*coordinates))), 100, '#666']
    val = utils.pred_func_geo(geo_all_data, geo_county_coordinates, geo_model, geo_encodings, geo_extreames, coordinates[0], coordinates[1], month)
    return [dl.Marker(position=coordinates, children=dl.Tooltip("({:.3f}, {:.3f})".format(*coordinates))), 100*val, '#FF3300']
Exemplo n.º 4
0
def update_map(rows, viewData):
    dff = pd.DataFrame.from_dict(viewData)
    # get the lat and lon of the selected row
    lat = dff.iat[rows[0], 13]
    lon = dff.iat[rows[0], 14]
    return [
        dl.Map(
            style={
                'width': '1000px',
                'height': '500px'
            },
            center=[30.75, -97.48],
            zoom=10,
            children=[
                dl.TileLayer(id="base-layer-id"),
                # Marker with tool tip and popup
                dl.Marker(position=[lat, lon],
                          children=[
                              dl.Tooltip(dff.iat[rows[0], 4]),
                              dl.Popup([
                                  html.H1("Animal Name"),
                                  html.P(dff.iat[rows[0], 9])
                              ])
                          ])
            ])
    ]
Exemplo n.º 5
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'}),
     ])
Exemplo n.º 6
0
def generate_map_plot(df):
    if df is not None:
        lons = df.lons.values
        lats = df.lats.values
        trajectory = np.vstack([lats, lons]).T.tolist()
        start_point = df.source.values[0]
        end_point = df.destination.values[0]
        zoom, center = zoom_center(lons, lats, width_to_height=8)

        fig = [
            dl.Map(
                [
                    dl.TileLayer(url=mapURL,
                                 attribution=attribution,
                                 tileSize=512,
                                 zoomOffset=-1),
                    dl.LayerGroup(id="layer"),
                    dl.WMSTileLayer(url="https://maps.dwd.de/geoserver/ows?",
                                    layers="dwd:RX-Produkt",
                                    format="image/png",
                                    transparent=True,
                                    opacity=0.7),
                    dl.LocateControl(options={
                        'locateOptions': {
                            'enableHighAccuracy': True
                        }
                    }),
                    dl.Polyline(positions=trajectory),
                    dl.Marker(position=trajectory[0],
                              children=dl.Tooltip(start_point)),
                    dl.Marker(position=trajectory[-1],
                              children=dl.Tooltip(end_point))
                ],
                center=[center['lat'], center['lon']],
                zoom=zoom,
                style={
                    'width': '100%',
                    'height': '45vh',
                    'margin': "auto",
                    "display": "block"
                },
                id='map')
        ]
    else:  # make an empty map
        fig = make_empty_map()

    return fig
Exemplo n.º 7
0
def update_output(value):
    if 'stations' in value:
        return [
            dl.Marker(position=[row['lat'], row['lon']],
                      children=dl.Tooltip(row['location']))
            for i, row in stations_uganda.iterrows()
        ]
    else:
        return None
Exemplo n.º 8
0
def get_old_fire_positions(dpt_code=None):

    # As long as the user does not click on a department, dpt_code is None and we return no fire marker
    if not dpt_code:
        return None

    # We read the csv file that locates the old fires and filter for the department of interest
    old_fire_positions = pd.read_csv(
        Path(__file__).parent.joinpath('data', 'historic_fires.csv'), ',')
    # Below it allows us to filter by department with a click on the map
    old_fire_positions = old_fire_positions[old_fire_positions['Département']
                                            == int(dpt_code)].copy()

    icon = {
        "iconUrl": '../assets/pyro_oldfire_icon.png',
        "iconSize": [50, 50],  # Size of the icon
        "iconAnchor": [
            25, 45
        ],  # Point of the icon which will correspond to marker's and popup's location
        "popupAnchor":
        [0, -20
         ]  # Point from which the popup should open relative to the iconAnchor
    }

    # We build a list of dictionaries containing the coordinates of each fire
    fire_markers = []
    for i, row in old_fire_positions.iterrows():
        lat = row['latitude']
        lon = row['longitude']
        location = row['location']
        date = dt.datetime.strptime(row['acq_date'], '%Y-%m-%d')\
                          .strftime('%d %b %Y')

        if row['daynight'] == 'D':
            daynight = 'Diurne'
        elif row['daynight'] == 'N':
            daynight = 'Nocturne'
        else:
            daynight = None

        fire_markers.append(
            dl.Marker(
                id=
                f'historic_fire_{i}',  # Set an id for each marker to receive callbacks
                position=(lat, lon),
                icon=icon,
                children=[
                    dl.Tooltip(f"Date: {date}"),
                    dl.Popup([
                        html.H4(f'Incendie du {date}'),
                        html.P(f'Commune : {location}'),
                        html.P(f'Type : {daynight}')
                    ])
                ]))

    return fire_markers
Exemplo n.º 9
0
def build_historic_markers(dpt_code=None):
    """
    This function reads through the 'historic_fires.csv' file stored in the /data folder.

    It takes as input a department code (as a character string), which will correspond to the department
    on which the user chooses to click and it returns past fires (as markers on the map) for this area.

    More precisely, it returns a dl.LayerGroup object that gathers all relevant past fire markers.
    """

    # As long as the user does not click on a department, dpt_code is None and we return no fire marker
    if not dpt_code:
        return None

    # We read the csv file that locates the old fires
    old_fire_positions = pd.read_csv(Path(__file__).parent.joinpath('data', 'historic_fires.csv'), ',')

    # The line below allows us to filter for the department of interest
    old_fire_positions = old_fire_positions[old_fire_positions['Département'] == int(dpt_code)].copy()

    icon = {"iconUrl": '../assets/pyro_oldfire_icon.png',
            "iconSize": [50, 50],       # Size of the icon
            "iconAnchor": [25, 45],      # Point of the icon which will correspond to marker's and popup's location
            "popupAnchor": [0, -20]  # Point from which the popup should open relative to the iconAnchor
            }

    # We build a list of dictionaries containing the coordinates of each fire
    fire_markers = []
    for i, row in old_fire_positions.iterrows():
        lat = row['latitude']
        lon = row['longitude']
        location = row['location']
        date = datetime.datetime.strptime(row['acq_date'], '%Y-%m-%d')\
                                .strftime('%d %b %Y')

        if row['daynight'] == 'D':
            daynight = 'Diurne'
        elif row['daynight'] == 'N':
            daynight = 'Nocturne'
        else:
            daynight = None

        fire_markers.append(dl.Marker(id=f'historic_fire_{i}',  # Set an id for each marker to receive callbacks
                                      position=(lat, lon),
                                      icon=icon,
                                      children=[dl.Tooltip(f"Date: {date}"),
                                                dl.Popup([html.H4(f'Incendie du {date}'),
                                                          html.P(f'Commune : {location}'),
                                                          html.P(f'Type : {daynight}')])
                                                ]
                                      )
                            )

    # We gather all markers stored in the fire_markers list in a dl.LayerGroup object, which is returned
    return dl.LayerGroup(children=fire_markers,
                         id='historic_fires_markers')
Exemplo n.º 10
0
def map_hover(hover_feature):
    if hover_feature is not None:
        county = hover_feature['properties']['NAME']
        state = fips_to_state(hover_feature['properties']['STATE'],
                              FIPS_STATES_DICT)
        content = f'{county} County'
        if state:
            content = content + f' ({state})'
        return dl.Tooltip(content)
    return None
Exemplo n.º 11
0
def build_sites_markers(sites_with_live_alerts, dpt_code=None):
    """
    This function reads the site markers by making the API, that contains all the
    information about the sites equipped with detection units.

    It then returns a dl.MarkerClusterGroup object that gathers all relevant site markers.

    NB: certain parts of the function, which we do not use at the moment and that were initially
    designed to bind the display of site markers to a click on the corresponding department, are
    commented for now but could prove useful later on.
    """

    # Building alerts_markers objects and wraps them in a dl.LayerGroup object
    icon = {
        "iconUrl": '../assets/pyro_site_icon.png',
        "iconSize": [50, 50],  # Size of the icon
        "iconAnchor":
        [25,
         45],  # Point of the icon which will correspond to marker's location
        "popupAnchor":
        [0, -20
         ]  # Point from which the popup should open relative to the iconAnchor
    }

    # We build a list of markers containing the info of each site/camera
    markers = []
    for row in camera_positions:
        # We do not output a marker if the site is associated with a live alert being displayed
        if row['name'].replace('_', ' ').title() in sites_with_live_alerts:
            continue

        else:
            site_id = row['id']
            lat = round(row['lat'], 4)
            lon = round(row['lon'], 4)
            site_name = row['name'].replace('_', ' ').title()
            markers.append(
                dl.Marker(
                    id=
                    f'site_{site_id}',  # Necessary to set an id for each marker to receive callbacks
                    position=(lat, lon),
                    icon=icon,
                    children=[
                        dl.Tooltip(site_name),
                        dl.Popup([
                            html.H2(f'Site {site_name}'),
                            html.P(f'Coordonnées : ({lat}, {lon})'),
                            html.
                            P(f"Nombre de caméras : {len(site_devices.get(row['name']))}"
                              )
                        ])
                    ]))

    # We group all dl.Marker objects in a dl.MarkerClusterGroup object and return it
    return markers
Exemplo n.º 12
0
 def geotiff_marker(x):
     if x is not None:
         lat, lon, val = x
         return dl.Marker(position=[lat, lon],
                          icon={
                              "iconUrl": "/assets/thermometer.png",
                              "iconSize": [40, 40],
                              "iconAnchor": [20, 36]
                          },
                          children=[dl.Tooltip('{:.1f}°C'.format(val))])
     else:
         return None
Exemplo n.º 13
0
    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
Exemplo n.º 14
0
def update_routes(agregation_option, routes):
    # Routes Layer Map
    df = df_routes.copy()
    df = df[df[agregation_option].isin(routes)]
    map_routes_children = []
    for row in df.itertuples():
        map_routes_children.append(dl.Polygon(positions = [(p[1], p[0]) for p in row.geometry.exterior.coords],
                                              children = dl.Tooltip(row.Route),
                                              color = dict_colors[row.Route],
                                              fillColor = dict_colors[row.Route]
                                              )
                                   )
    
    return dl.LayerGroup(map_routes_children),
Exemplo n.º 15
0
 def geotiff_marker(x):
     if x is not None:
         lat, lon, val = x
         return dl.Marker(
             position=[lat, lon],
             icon={
                 "iconUrl":
                 "https://github.com/thedirtyfew/dash-leaflet/tree/master/assets/thermometer.png",
                 "iconSize": [40, 40],
                 "iconAnchor": [20, 36]
             },
             children=[dl.Tooltip('{:.1f}°C'.format(val))])
     else:
         return None
Exemplo n.º 16
0
def generate_map_plot(data):
    if data is not None:
        start_point = data['STATION_NAME'].item()
        point = [data['LAT'].item(), data['LON'].item()]

        fig = [
            dl.Map(
                [
                    dl.TileLayer(url=mapURL,
                                 attribution=attribution,
                                 tileSize=512,
                                 zoomOffset=-1),
                    dl.LayerGroup(id="layer"),
                    dl.WMSTileLayer(url="https://maps.dwd.de/geoserver/ows?",
                                    layers="dwd:SAT_WELT_KOMPOSIT",
                                    format="image/png",
                                    transparent=True,
                                    opacity=0.7,
                                    version='1.3.0',
                                    detectRetina=True),
                    dl.WMSTileLayer(url="https://maps.dwd.de/geoserver/ows?",
                                    layers="dwd:SAT_EU_RGB",
                                    format="image/png",
                                    transparent=True,
                                    opacity=0.7,
                                    version='1.3.0',
                                    detectRetina=True),
                    dl.LocateControl(options={
                        'locateOptions': {
                            'enableHighAccuracy': True
                        }
                    }),
                    dl.Marker(position=point,
                              children=dl.Tooltip(start_point)),
                ],
                center=point,
                zoom=4,
                style={
                    'width': '100%',
                    'height': '35vh',
                    'margin': "auto",
                    "display": "block"
                },
                id='map')
        ]
    else:  # make an empty map
        fig = make_empty_map()

    return fig
Exemplo n.º 17
0
def build_sites_markers(dpt_code=None):

    # As long as the user does not click on a department, dpt_code is None and we return no device
    # if not dpt_code:
    #     return None

    # We read the csv file that locates the cameras and filter for the department of interest
    camera_positions = pd.read_csv(
        Path(__file__).parent.joinpath('data', 'cameras.csv'), ';')
    # camera_positions = camera_positions[camera_positions['Département'] == int(dpt_code)].copy()

    # Building alerts_markers objects and wraps them in a dl.LayerGroup object
    icon = {
        "iconUrl": '../assets/pyro_site_icon.png',
        "iconSize": [50, 50],  # Size of the icon
        "iconAnchor":
        [25,
         45],  # Point of the icon which will correspond to marker's location
        "popupAnchor": [0, -20]
    }  # Point from which the popup should open relative to the iconAnchor

    # We build a list of markers containing the info of each site/camera
    markers = []
    for i, row in camera_positions.iterrows():
        lat = row['Latitude']
        lon = row['Longitude']
        site_name = row['Tours']
        nb_device = row['Nombres Devices']
        markers.append(
            dl.Marker(
                id=
                f'site_{i}',  # Necessary to set an id for each marker to reteive callbacks
                position=(lat, lon),
                icon=icon,
                children=[
                    dl.Tooltip(site_name),
                    dl.Popup([
                        html.H2(f'Site {site_name}'),
                        html.P(f'Coordonnées : ({lat}, {lon})'),
                        html.P(f'Nombre de caméras : {nb_device}')
                    ])
                ]))

    # We group all dl.Marker objects in a dl.LayerGroup object
    markers_cluster = dl.MarkerClusterGroup(children=markers,
                                            id='sites_markers')

    return markers_cluster
Exemplo n.º 18
0
def build_sites_markers(dpt_code=None):
    """
    This function reads the site markers by making the API, that contains all the
    information about the sites equipped with detection units.

    It then returns a dl.MarkerClusterGroup object that gathers all relevant site markers.

    NB: certain parts of the function, which we do not use at the moment and that were initially
    designed to bind the display of site markers to a click on the corresponding department, are
    commented for now but could prove useful later on.
    """

    # As long as the user does not click on a department, dpt_code is None and we return no device
    # if not dpt_code:
    #     return None

    # We filter for the department of interest
    # camera_positions = camera_positions[camera_positions['Département'] == int(dpt_code)].copy()

    # Building alerts_markers objects and wraps them in a dl.LayerGroup object
    icon = {
        "iconUrl": '../assets/pyro_site_icon.png',
        "iconSize": [50, 50],        # Size of the icon
        "iconAnchor": [25, 45],      # Point of the icon which will correspond to marker's location
        "popupAnchor": [0, -20]      # Point from which the popup should open relative to the iconAnchor
    }

    # We build a list of markers containing the info of each site/camera
    markers = []
    for row in camera_positions:
        site_id = row['id']
        lat = row['lat']
        lon = row['lon']
        site_name = row['name']
        # nb_device = row['Nombres Devices']
        markers.append(dl.Marker(id=f'site_{site_id}',    # Necessary to set an id for each marker to receive callbacks
                                 position=(lat, lon),
                                 icon=icon,
                                 children=[dl.Tooltip(site_name),
                                           dl.Popup([html.H2(f'Site {site_name}'),
                                                     html.P(f'Coordonnées : ({lat}, {lon})'),
                                                     html.P(f'Nombre de caméras : {4}')])]))

    # We group all dl.Marker objects in a dl.MarkerClusterGroup object and return it
    return dl.MarkerClusterGroup(children=markers, id='sites_markers')
Exemplo n.º 19
0
def update_map(viewData, derived_virtual_selected_rows):
    """ functionality for updating map. map always shows location of the animal at top of table's current page """

    dff = df if viewData is None else pd.DataFrame(viewData)
    selected_animal = None

    # if there are no selected rows yet, map default displays first animal of table's current page
    if not derived_virtual_selected_rows:
        selected_animal = dff.iloc[0]
    # else there is a selected row, map displays that animal
    else:
        selected_animal = dff.iloc[derived_virtual_selected_rows[0]]

    latitude = selected_animal[12]
    longitude = selected_animal[13]
    animal_breed = selected_animal[3]
    animal_name = selected_animal[8]

    return [
        dl.Map(
            style={
                'width': '700px',
                'height': '500px'
            },
            center=[latitude, longitude],
            zoom=10,
            children=[
                dl.TileLayer(id="base-layer-id"),
                # Marker with tool tip and popup
                dl.Marker(
                    position=[latitude, longitude],
                    children=[
                        # show breed of animal on hovering over marker
                        dl.Tooltip(animal_breed),
                        # show animal name on clicking marker
                        dl.Popup([html.H1("Animal Name"),
                                  html.P(animal_name)])
                    ])
            ])
    ]
Exemplo n.º 20
0
    def get_map_from_table(data, children):
        """Adds landmark location pin on map from landmark table

        Args:
            data (list): data of landmark table
            children (list): current map children

        Returns:
            (list): updated map children
        """
        children = [children[0]] + [
            dl.Marker(position=[landmark['lat'], landmark['lon']],
                      icon={
                          'iconUrl': '/assets/map-icon.svg',
                          'iconSize': [38, 100],
                          'iconAnchor': [19, 70]
                      },
                      children=[
                          dl.Tooltip(landmark['Landmark']),
                      ]) for landmark in data
        ]
        return children
Exemplo n.º 21
0
def render_example1():
    comment = """ Marker with default icon, marker with custom icon, circle marker (fixed pixel radius), 
    circle (fixed physical radius), polyline, polygon and rectangle, all supporting tooltips and popups. """
    return [
        html.H1("Example 1: Basic components"),
        html.P(comment),
        dl.Map(
            id=MAP_ID,
            style={
                'width': '1000px',
                'height': '500px'
            },
            center=[56.05, 10.25],
            zoom=10,
            children=[
                dl.TileLayer(id=BASE_LAYER_ID),
                # Marker with tool tip and popup.
                dl.Marker(position=[56, 9.8],
                          children=[
                              dl.Tooltip("Marker tooltip"),
                              dl.Popup([
                                  html.H1("Marker popup"),
                                  html.P("with inline html")
                              ])
                          ]),
                # Marker with custom icon.
                dl.Marker(position=[55.94, 9.96],
                          icon={
                              "iconUrl": "/assets/149059.svg",
                              "iconSize": [25, 25]
                          },
                          children=[dl.Tooltip("Marker with custom icon")]),
                # Circle marker (with fixed radius in pixel).
                dl.CircleMarker(center=[56.05, 10.15],
                                radius=20,
                                children=[dl.Popup('Circle marker, 20px')]),
                # Circle with fixed radius in meters.
                dl.Circle(center=[56.145, 10.21],
                          radius=2000,
                          color='rgb(255,128,0)',
                          children=[dl.Tooltip('Circle, 2km radius')]),
                # Polyline marker.
                dl.Polyline(id='polyline',
                            positions=[[56.06, 10.0], [56.056, 10.01],
                                       [56.064, 10.028], [56.0523, 10.0717],
                                       [56.044, 10.073]],
                            children=[dl.Tooltip('Polyline')]),
                # Polygon marker.
                dl.Polygon(id='polygon',
                           positions=[[56.013, 9.84], [56.0544, 9.939],
                                      [56.003, 10.001]],
                           children=[dl.Tooltip('Polygon')]),
                # Rectangle marker.
                dl.Rectangle(id='rectangle',
                             bounds=[[55.9, 10.2], [56.0, 10.5]],
                             children=[dl.Tooltip('Rectangle')])
            ]),
        dcc.RadioItems(id=BASE_LAYER_DROPDOWN_ID,
                       options=[{
                           "label":
                           i,
                           "value":
                           mapbox_url.format(id=i, access_token=mapbox_token)
                       } for i in mapbox_ids],
                       labelStyle={'display': 'inline-block'},
                       value=mapbox_url.format(id="light-v9",
                                               access_token=mapbox_token)),
        html.P("Coordinate (click on map):"),
        html.Div(id=COORDINATE_CLICK_ID),
    ]
Exemplo n.º 22
0
def update_graph(click_lat_lng, departure_month, traffic, covid):
    global myloc
    if click_lat_lng is not None:
        myloc = click_lat_lng
    elif myloc is not None:
        click_lat_lng = myloc
    if click_lat_lng is not None:
        ##################
        #Construct query string based on facts of whether COVID and other inputs
        if covid:
            mysql_weekday = 'SELECT avg(rate) as rate from rates where traffic=' + str(
                traffic
            ) + ' AND iscovid=1 AND isweekend=0 AND zoneid in (SELECT locationid from taxi_zones where ST_intersects(ST_SetSRID( ST_Point(' + str(
                click_lat_lng[1]
            ) + ', ' + str(
                click_lat_lng[0]
            ) + '),4326),geom))  group by target_hour order by target_hour;'
            mysql_weekend = 'SELECT avg(rate) as rate from rates where traffic=' + str(
                traffic
            ) + ' AND iscovid=1 AND isweekend=1 AND zoneid in (SELECT locationid from taxi_zones where ST_intersects(ST_SetSRID( ST_Point(' + str(
                click_lat_lng[1]
            ) + ', ' + str(
                click_lat_lng[0]
            ) + '),4326),geom))  group by target_hour order by target_hour;'
            mysql_holiday = 'SELECT avg(rate) as rate from rates where traffic=' + str(
                traffic
            ) + ' AND iscovid=1 AND isholiday=1 AND zoneid in (SELECT locationid from taxi_zones where ST_intersects(ST_SetSRID( ST_Point(' + str(
                click_lat_lng[1]
            ) + ', ' + str(
                click_lat_lng[0]
            ) + '),4326),geom))  group by target_hour order by target_hour;'
            month_slider_disabled = True
        else:
            mysql_weekday = 'SELECT avg(rate) as rate from rates where target_month = ' + str(
                departure_month
            ) + ' AND traffic=' + str(
                traffic
            ) + ' AND iscovid=0 AND isweekend=0 AND zoneid in (SELECT locationid from taxi_zones where ST_intersects(ST_SetSRID( ST_Point(' + str(
                click_lat_lng[1]
            ) + ', ' + str(
                click_lat_lng[0]
            ) + '),4326),geom))  group by target_hour order by target_hour;'
            mysql_weekend = 'SELECT avg(rate) as rate from rates where target_month = ' + str(
                departure_month
            ) + ' AND traffic=' + str(
                traffic
            ) + ' AND iscovid=0 AND isweekend=1 AND zoneid in (SELECT locationid from taxi_zones where ST_intersects(ST_SetSRID( ST_Point(' + str(
                click_lat_lng[1]
            ) + ', ' + str(
                click_lat_lng[0]
            ) + '),4326),geom))  group by target_hour order by target_hour;'
            mysql_holiday = 'SELECT avg(rate) as rate from rates where traffic=' + str(
                traffic
            ) + ' AND iscovid=0 AND isholiday=1 AND zoneid in (SELECT locationid from taxi_zones where ST_intersects(ST_SetSRID( ST_Point(' + str(
                click_lat_lng[1]
            ) + ', ' + str(
                click_lat_lng[0]
            ) + '),4326),geom))  group by target_hour order by target_hour;'
            month_slider_disabled = False
        #####################
        #Grab data
        result_weekday = getdata(mysql_weekday)
        result_weekend = getdata(mysql_weekend)
        result_holiday = getdata(mysql_holiday)
        #####################
        #Show the graph, plot the graph, place marker on map.
        return [
            month_slider_disabled, {
                'display': 'block'
            },
            plotresult(result_weekday, result_weekend, result_holiday),
            dl.Marker(position=click_lat_lng,
                      children=dl.Tooltip(
                          "({:.3f}, {:.3f})".format(*click_lat_lng)))
        ]
Exemplo n.º 23
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)
Exemplo n.º 24
0
def map_click(click_lat_lng, steps, min_perc):
    lat_min = np.floor(click_lat_lng[0] * 10) / 10
    lat_max = np.ceil(click_lat_lng[0] * 10) / 10
    lon_min = np.floor(click_lat_lng[1] * 10) / 10
    lon_max = np.ceil(click_lat_lng[1] * 10) / 10

    poi_start = str(round(
        (lat_min + 0.05), 2)) + '_' + str(round((lon_min + 0.05), 2))
    df_output = select_neighbours_percentages(poi_start=poi_start,
                                              steps=steps,
                                              limit=int(min_perc))

    # All points of interest (cells with % larger than minimal percentage)
    new_pois = df_output.poi.unique().tolist()
    # Add column with lat and lon to df_selection
    lat = [x.split('_')[0] for x in new_pois]
    lon = [x.split('_')[1] for x in new_pois]
    df_pois = pd.DataFrame(columns=["lat", "lon"],
                           data=np.column_stack((lat, lon)))

    # Get disctricts connected to POIS
    districts_df = get_districts(df=df_pois, districts=admin_boundaries)
    if len(districts_df) > 0:
        districts_return = 'The connected disctricts are: ' + str(
            districts_df).strip('[]')
    else:
        districts_return = 'No connected districts found.'

    # All neighbours
    new_nbrs = df_output.neighbour.unique().tolist()
    # Add column with lat and lon to df_selection
    lat = [x.split('_')[0] for x in new_nbrs]
    lon = [x.split('_')[1] for x in new_nbrs]
    perc = [str(round(x)) for x in df_output.percentage.tolist()]
    df_nbr = pd.DataFrame(columns=["lat_lon", "lat", "lon", "perc"],
                          data=np.column_stack((new_nbrs, lat, lon, perc)))

    # Add number of pois
    df_nr_pois = df_output[['poi', 'nbr_poi']].drop_duplicates()
    df_nr_pois['nbr_poi'] = 'order nr: ' + df_nr_pois['nbr_poi'].astype(
        int).astype(str)
    df_nbr = df_nbr.merge(df_nr_pois,
                          how='left',
                          left_on='lat_lon',
                          right_on='poi').drop(['poi'], axis=1)
    df_nbr = df_nbr.fillna('')

    # Create: the selected colored path of POIs and their neighbours
    return [
        dl.Marker(
            position=click_lat_lng,
            children=dl.Tooltip('start ' +
                                "({:.2f}, {:.2f})".format(*click_lat_lng)))
    ], [
        dl.Rectangle(bounds=[[
            round(float(row['lat']) - 0.05, 2),
            round(float(row['lon']) - 0.05, 2)
        ],
                             [
                                 round(float(row['lat']) + 0.05, 2),
                                 round(float(row['lon']) + 0.05, 2)
                             ]],
                     stroke=False,
                     fillColor=get_color(float(row['perc'])),
                     weight=1,
                     opacity=1,
                     fillOpacity=.7,
                     children=dl.Tooltip(row['perc'] + '%   ' +
                                         row['nbr_poi']))
        for i, row in df_nbr.iterrows()
    ], [
        dl.Rectangle(bounds=[[
            round(float(row['lat']) - 0.05, 2),
            round(float(row['lon']) - 0.05, 2)
        ],
                             [
                                 round(float(row['lat']) + 0.05, 2),
                                 round(float(row['lon']) + 0.05, 2)
                             ]],
                     fill=False,
                     opacity=.65,
                     color='blue') for i, row in df_pois.iterrows()
    ], districts_return
Exemplo n.º 25
0
        </footer>
    </body>
</html>""",
)
server = app.server

starting_position = (
    float(city_lookup.iloc[[starting_city_id]]["lat"]),
    float(city_lookup.iloc[[starting_city_id]]["lng"]),
)

print("starting_position", starting_position)

markers = [
    dl.Marker(
        dl.Tooltip(city_row.city + ", " + city_row.country),
        position=(
            float(city_row["lat"]),
            float(city_row["lng"]),
        ),
        id="city_id_" + str(i),
    ) for i, city_row in city_lookup.iterrows()
]
cluster = dl.MarkerClusterGroup(id="markers",
                                children=markers,
                                options={"polygonOptions": {
                                    "color": "red"
                                }})

app.layout = html.Div([
    # represents the URL bar, doesn't render anything
Exemplo n.º 26
0
def tabulate(activetabs,hashkey):
    global df,params
    #
    # print
    # (activetabs,hashkey)

    if activetabs == 'filter':
        info('enabling filter options')
        params['precompute']= True
        return None,None,None


    if type(df) != type(None):

        # '''
        # table
        # '''

        if activetabs == 'table_tab':

            message = md('''
            # Table Sample
            Showing a *random* sample of *500* values from the selected dataframe
            ''')


            newdf = df
            if len(df)>500: newdf = newdf.sample(500).reset_index()

            try: newdf.drop(['UNIXTIME'],inplace=True)
            except: None

            print(newdf)
            return [message,br,table(newdf,'tab_table',{'width':'80%','margin':'auto'})],None,None


        # '''
        # scatter_tab
        # '''
        elif activetabs == 'scatter_tab':

            gc = 'PM1 PM3 PM2.5 PM10 UNIXTIME'.split()
            cols = list(filter(lambda x:x in gc ,df.columns))

            dfp = df[cols]
            dfp['hour'] = df.index.hour + (df.index.minute/15)//4


            dfp = dfp.groupby('hour').mean().reset_index()


            print(dfp)

            sizes = {'PM1':2,'PM2.5':3, 'PM3':3, 'PM10':10}
            alpha = 0.8


            for i in 'PM1 PM3 PM2.5 PM10'.split()[::-1]:
                if i in dfp.columns:
                    # print(i)
                    try:
                        ax = dfp.plot(kind='scatter',x='hour', y=i, c='UNIXTIME',colormap='viridis',ax=ax,colorbar=False,label=i, s = sizes[i],alpha = alpha)
                    except:
                        ax = dfp.plot(kind='scatter',x='hour', y=i, c='UNIXTIME',colormap='viridis', label=i, s = sizes[i],alpha=alpha)


            plt.legend()
            plt.tight_layout()
            plt.xlabel('HOUR')
            plt.ylabel('Avg value')

            '''
            save to a base 64str
            '''
            import base64
            import io
            IObytes = io.BytesIO()
            plt.savefig(IObytes,  format='png')
            plt.close()
            IObytes = base64.b64encode(IObytes.getvalue()).decode("utf-8").replace("\n", "")
            plot = html.Img(src="data:image/png;base64,{}".format(IObytes))


            return None,[md('# A grouped summary of the following dataframe:'),br,br,table(dfp.describe().reset_index(),'descplot'), br,br,plot],None


        elif activetabs == 'map_tab':

            dfp = df['LAT LON'.split()].dropna(subset=['LON'])
            if len(dfp)>1000: dfp.dfp.sample(1000)

            print(dfp)


            desc = md('''
            # Location overview
            An interactive map showing a *random* subset of *1000* datapoints from the selected subset.
            These vary between each initiation due to the above reason.

            The centre of the map is calculated by taking the median latitude and Longitude, the colour shows the time of day, and the tooltip produces the index value from the dataset.
            ''')


            log.critical('Known: -ves on Longitude are lost!!!!!')


            mid = (dfp.LAT.median(), -dfp.LON.median())

            dfp.columns = ['lat','lon']

            print(mid)

            cc = [dl.CircleMarker( dl.Tooltip(str(row[0])), center=(row[1].lat,-row[1].lon), radius=5, stroke=True,color='none',weight=0,fillColor='blue' ) for row in dfp.iterrows()]
            circles = dl.LayerGroup(cc,id='markers')


            ''' when the regeneratorRuntime issue is solved '''
            log.critical(' Known: cannot show superCluster due to regeneratorRuntime issue')
            # ll = dlx.dicts_to_geojson(dfp.to_dict('records'))
            #
            # # markers = dl.GeoJSON(data=ll, cluster=True, zoomToBoundsOnClick=True,
            # #        # superClusterOptions={"radius": 100}
            # #        )
            # markers = []




            plot =  html.Div(
                id="bibmap",
                children=[ desc,br,br,



                dl.Map([dl.TileLayer(),circles], center=mid, zoom=12,style={'width': '90vw', 'height': '50vh'})


            ],

            # style={'width': '100vw', 'height': '50vh', 'margin': "auto", "display": "block"}
            )


            return None,None,plot






        else:
            return None,None,None

    else:
        return None,None,None
Exemplo n.º 27
0
Keyword arguments:
 |  - children (a list of or a singular dash component, string or number; option
al): The children of this component
 |  - center (list of numbers; required): The center of the circle (lat, lon)
 |  - radius (number; required): Radius of the circle, in meters.
 |  - stroke (boolean; optional): Whether to draw stroke along the path. Set it 
to false to disable borders 
 |  on polygons or circles.
 |  - color (string; optional): Stroke color
 |  - weight (number; optional): Stroke width in pixels
 |  - opacity (number; optional): Stroke opacity
 etc... 
'''

markers = [
    dl.CircleMarker(dl.Tooltip(str(row)),
                    center=[row[1].LAT, row[1].LON],
                    radius=25 * row[1][what] / mx,
                    stroke=True,
                    weight=1,
                    color='red',
                    fillColor=cols[row[1]['cat']],
                    fillOpacity=0.7) for row in df.iterrows()
]

#fillColor
#color fillOpacity

app = dash.Dash()
app.layout = html.Div(
    id="BornInBradford",
Exemplo n.º 28
0
def map_click(dbl_click_lat_lng):
    click_positions.append(dbl_click_lat_lng)
    print(click_positions[-2:])
    popup = "Start ({:.3f}, {:.3f})".format(*dbl_click_lat_lng)
    return [dl.Marker(position=dbl_click_lat_lng, children=dl.Tooltip(popup))]
Exemplo n.º 29
0
def load_results(n_clicks, postal):

    #df = get_results('CCBDEV7')
    df = data

    if postal is not None:
        df = df[df.POSTAL.isin([postal])]

    #df[['ACCT_ID','PREM_ID','ETOR_NUM']] = df[['ACCT_ID','PREM_ID','ETOR_NUM']].astype('int64')
    #df[['PREMLAT','PREMLONG']] = df[['PREMLAT','PREMLONG']].astype(float)

    positions = df[['PREMLAT', 'PREMLONG']].values.tolist()
    premiseId = df[['PREM_ID']].values.tolist()
    accountId = df[['ACCT_ID']].values.tolist()
    etorNoList = df[['ETOR_NUM']].values.tolist()

    Row_list = []
    # Iterate over each row
    for index, rows in df.iterrows():
        # Create list for the current row
        my_list = [rows.PREMLAT, rows.PREMLONG]
        Row_list.append(my_list)

    marker = []
    for row, premise, account, etorNo in zip(Row_list, premiseId, accountId,
                                             etorNoList):
        etor = int(''.join(map(str, etorNo)))
        if etor < 11:
            marker_temp = dl.Marker(
                position=row,
                icon={
                    "iconUrl": "/assets/smile3.png",
                    "iconSize": [35, 35]
                },
                children=[
                    dl.Tooltip("Premise - " + ' '.join(map(str, premise))),
                    dl.Popup([
                        html.H1("Details"),
                        html.P("Customer Outage Experience"),
                        html.P("Location = " + ' '.join(map(str, row))),
                        html.P("Premise Id = " + ' '.join(map(str, premise))),
                        html.P("Account Id = " + ' '.join(map(str, account))),
                    ])
                ])
            marker.append(marker_temp)

        elif etor > 10 and etor < 21:
            marker_temp = dl.Marker(
                position=row,
                icon={
                    "iconUrl": "/assets/sad.png",
                    "iconSize": [35, 35]
                },
                children=[
                    dl.Tooltip("Premise - " + ' '.join(map(str, premise))),
                    dl.Popup([
                        html.H1("Details"),
                        html.P("Customer Outage Experience"),
                        html.P("Location = " + ' '.join(map(str, row))),
                        html.P("Premise Id = " + ' '.join(map(str, premise))),
                        html.P("Account Id = " + ' '.join(map(str, account))),
                    ])
                ])
            marker.append(marker_temp)

        elif etor > 20:
            marker_temp = dl.Marker(
                position=row,
                icon={
                    "iconUrl": "/assets/angry.png",
                    "iconSize": [35, 35]
                },
                children=[
                    dl.Tooltip("Premise - " + ' '.join(map(str, premise))),
                    dl.Popup([
                        html.H1("Details"),
                        html.P("Customer Outage Experience"),
                        html.P("Location = " + ' '.join(map(str, row))),
                        html.P("Premise Id = " + ' '.join(map(str, premise))),
                        html.P("Account Id = " + ' '.join(map(str, account))),
                    ])
                ])
            marker.append(marker_temp)

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

    result = [
        dl.TileLayer(url="https://a.tile.openstreetmap.org/{z}/{x}/{y}.png"),
        dl.LocateControl(
            options={'locateOptions': {
                'enableHighAccuracy': True
            }}), cluster
    ]

    return [result]
Exemplo n.º 30
0
def update_plots(click_lat_lng, average_speed, trip_time):
    global census_data, cudf_nodes, cudf_edges
    colorscale_name = 'Blugrn'
    t0 = time.time()

    if click_lat_lng is not None:
        lat, lon = click_lat_lng
        marker = dl.Marker(position=click_lat_lng,
                           children=dl.Tooltip(
                               "({:.3f}, {:.3f})".format(*click_lat_lng)))

        polygons, df, times = get_nearest_polygons_from_selected_point(
            lat, lon, average_speed, trip_time, cudf_nodes, cudf_edges,
            census_data)
        polygon_data = json.loads(polygons.to_json())
    else:
        marker, polygon_data, df = None, None, None
        times = [0, 0, 0, 0]

    if df is None:
        len_df = len(census_data)
        figures = delayed(build_updated_figures)(census_data,
                                                 colorscale_name).compute()

    else:
        len_df = len(df)
        figures = build_updated_figures(df, colorscale_name)

    (education_histogram, income_histogram, cow_histogram,
     age_histogram) = figures

    barchart_config = {
        'displayModeBar':
        True,
        'modeBarButtonsToRemove': [
            'zoom2d', 'pan2d', 'select2d', 'lasso2d', 'zoomIn2d', 'zoomOut2d',
            'resetScale2d', 'hoverClosestCartesian', 'hoverCompareCartesian',
            'toggleSpikelines'
        ]
    }
    n_selected_indicator = {
        'data': [{
            'domain': {
                'x': [0, 1],
                'y': [0, 0.5]
            },
            'type': 'indicator',
            'value': len_df,
            'number': {
                'font': {
                    'color': text_color,
                    'size': '24px'
                },
                "valueformat": ","
            }
        }],
        'layout': {
            'template': template,
            'height': row_heights[0] - 30,
            'margin': {
                'l': 10,
                'r': 10,
                't': 10,
                'b': 10
            }
        }
    }
    compute_time = round(time.time() - t0, 4)
    print(f"Update time: {compute_time}")
    np.append(times, [compute_time - np.sum(times)])
    query_time_stacked_bar = get_stacked_bar(
        np.append(times, [compute_time - np.sum(times)]), colorscale_name)

    return (n_selected_indicator, query_time_stacked_bar, marker, polygon_data,
            education_histogram, income_histogram, cow_histogram,
            age_histogram, barchart_config, barchart_config, barchart_config,
            barchart_config)