Example #1
0
def get_figure(outage_index,
               variable_to_show,
               outages=None,
               towers=None,
               discharges=None,
               centroid=None):
    outage_date = outages.loc[outage_index, "date"]
    minutes_animation = 35

    frames = get_frames(minutes_animation,
                        outage_date,
                        variable_to_show,
                        discharges=discharges)
    df = stats.Discharges_before_outage_by_time(outage_date,
                                                1,
                                                min_before=minutes_animation,
                                                discharges=discharges)

    fig = go.Figure(
        go.Scattermapbox(
            lat=df.latitude,
            lon=df.longitude,
            mode="markers",
        ))

    fig.add_trace(
        go.Scattermapbox(
            lat=towers.latitude,
            lon=towers.longitude,
            mode="markers",  # markers+lines
            marker=go.scattermapbox.Marker(size=7, color="black", opacity=0.7),
            name="Towers",
        ))
    fig.update(layout_showlegend=False)
    fig.update_layout(
        margin={
            "t": 0.2,
            "l": 0,
            "b": 0
        },
        height=700,
        mapbox=dict(  # accesstoken=mapbox_access_token,
            bearing=0,
            center=dict(lat=centroid[1], lon=centroid[0]),
            pitch=0,
            zoom=9,
            style="carto-positron",
        ),
    )

    fig.update(frames=frames)
    sliders = [
        dict(
            steps=[
                dict(
                    method="animate",
                    args=[
                        [f"frame{k}"],
                        dict(
                            mode="immediate",
                            frame=dict(duration=100, redraw=True),
                            transition=dict(duration=0),
                            label="C",
                        ),
                    ],
                    label="{:d}".format(k),
                ) for k in range(len(frames))
            ],
            transition=dict(duration=0),
            x=0.1,  # slider starting position
            y=0,
            len=0.9,
            ticklen=3,
            pad={
                "b": 10,
                "t": 0
            },
            font={"size": 10},
            currentvalue=dict(font=dict(size=12),
                              prefix="Minute: ",
                              visible=True,
                              xanchor="center"),
        )
    ]

    fig["layout"]["updatemenus"] = [{
        "buttons": [
            {
                "args": [
                    None,
                    {
                        "frame": {
                            "duration": 500,
                            "redraw": True
                        },
                        "fromcurrent": True,
                        "transition": {
                            "duration": 0,
                            "easing": "quadratic-in-out"
                        },
                    },
                ],
                "label":
                "Play",
                "method":
                "animate",
            },
            {
                "args": [
                    [None],
                    {
                        "frame": {
                            "duration": 0,
                            "redraw": True
                        },
                        "mode": "immediate",
                        "transition": {
                            "duration": 0
                        },
                    },
                ],
                "label":
                "Pause",
                "method":
                "animate",
            },
        ],
        "direction":
        "left",
        "pad": {
            "r": 10,
            "t": 20
        },
        "showactive":
        False,
        "type":
        "buttons",
        "x":
        0.1,
        "xanchor":
        "right",
        "y":
        0,
        "yanchor":
        "top",
    }]

    fig["layout"]["sliders"] = sliders

    return fig
def plot_map(end_year: int) -> None:
    """
    Plots a map showing the weather stations in the UK and their projected
    increase percentage in E.Coli cases.
    """
    total = projection.get_percentage_increase(end_year)
    temps = projection.temp_prediction_all(end_year)
    print(temps)

    mapbox_access_token = 'pk.eyJ1Ijoiam9qb29udGhhdCIsImEiOiJja2lta3Uzbnow' \
                          'YWRtMzVud3NrNjI3N2JjIn0.kYIFPU3HJbjDsNYyQFaGdA'
    df = pd.read_csv('plotly_map_station_locations.csv')
    site_lat = df.lat
    site_lon = df.lon
    locations_name = df.text.tolist()

    temp_values = temps['temp'].tolist()
    max_temp = max(temp_values)
    min_temp = min(temp_values)
    temp_diff = max_temp - min_temp
    location_colors = []

    for i in range(len(locations_name)):
        location = locations_name[i]
        locations_name[
            i] = "{}: Projected to have {:.4f}% of increase until {}".format(
                location.title(), total[location], end_year)
        temp_value = temps.loc[temps['location'] == location]['temp'][0][0]
        ratio = (temp_value - min_temp) / temp_diff
        gb_value = 255 - int(ratio * 255)
        rgb = 'rgb(255, {}, {})'.format(gb_value, gb_value)
        location_colors.append(rgb)

    fig = go.Figure()

    fig.add_trace(
        go.Scattermapbox(lat=site_lat,
                         lon=site_lon,
                         name='Weather Station Temperature',
                         mode='markers',
                         marker=dict(size=20,
                                     color=location_colors,
                                     colorscale=[[0, "rgb(255, 255, 255)"],
                                                 [1, "rgb(255, 0, 0)"]],
                                     showscale=False,
                                     opacity=0.75),
                         text=locations_name,
                         hoverinfo='text',
                         hoverlabel=dict(bgcolor='rgb(255, 217, 255)',
                                         font_size=40,
                                         font_family="Helvetica")))

    fig.add_trace(
        go.Scattermapbox(lat=site_lat,
                         lon=site_lon,
                         name='',
                         mode='markers',
                         marker=go.scattermapbox.Marker(
                             size=0,
                             color=temps['temp'],
                             colorscale=[[0, "rgb(255, 255, 255)"],
                                         [1, "rgb(255, 0, 0)"]],
                             showscale=True,
                             opacity=0.75),
                         text=locations_name,
                         hoverinfo='text',
                         hoverlabel=dict(bgcolor='rgb(182, 252, 213)',
                                         font_size=40,
                                         font_family="Helvetica")))

    fig.add_trace(
        go.Scattermapbox(
            lat=site_lat,
            lon=site_lon,
            name='',
            mode='markers',
            marker=go.scattermapbox.Marker(
                size=7,
                color='rgb(182, 252, 213)',  # percentage
                opacity=0.8),
            text=locations_name,
            hoverinfo='text',
            hoverlabel=dict(bgcolor='rgb(182, 252, 213)',
                            font_size=14,
                            font_family="Helvetica")))

    fig.update_layout(title={
        'text':
        'Percentage of Increase in E.Coli Cases for Weather Stations in the UK',
        'y': 0.9,
        'x': 0.5,
        'xanchor': 'center',
        'yanchor': 'top'
    },
                      autosize=True,
                      hovermode='closest',
                      font=dict(family="Helvetica", size=18),
                      mapbox=dict(accesstoken=mapbox_access_token,
                                  bearing=0,
                                  center=dict(lat=52, lon=0.12),
                                  pitch=10,
                                  zoom=3,
                                  style='dark'))

    fig.update_traces(showlegend=True, selector=dict(type='scattermapbox'))

    fig.update_layout(legend=dict(
        orientation="h", yanchor="top", y=1.00, xanchor="right", x=1.00))

    fig.show()
Example #3
0
def return_datatable(selected_date, selected_auth, selected_data,
                     selected_cases):
    # print(str(datetime.now()), '[1] start update_map...')

    df1 = df[df['date'].isin([selected_date])]

    if selected_data:
        if selected_cases:
            display = 'newCasesByPublishDate'
            marker_col = col_1
        else:
            display = 'newDeaths28DaysByPublishDate'
            marker_col = col_2
    else:
        if selected_cases:
            display = 'cumCasesByPublishDate'
            marker_col = col_3
        else:
            display = 'cumDeaths28DaysByPublishDate'
            marker_col = col_4

    if selected_auth is None or selected_auth == []:
        pass
    else:
        df1 = df1[df1['areaName'].isin(selected_auth)]

    df1 = df1.sort_values(by=[display], ascending=False)
    df1['Row'] = df1.reset_index().index
    df1['Row'] += 1

    lat_mean = pd.to_numeric(df1['Latitude']).mean()
    lon_mean = pd.to_numeric(df1['Longitude']).mean()

    df1.loc[(pd.isna(df1['newDeaths28DaysByPublishDate'])),
            'newDeaths28DaysByPublishDate'] = 0
    df1.loc[(pd.isna(df1['cumDeaths28DaysByPublishDate'])),
            'cumDeaths28DaysByPublishDate'] = 0

    fig = go.Figure(
        go.Scattermapbox(
            lat=df1['Latitude'],
            lon=df1['Longitude'],
            mode='text+markers',
            marker={'size': df1[display] * marker_calc_size / df1[display].max(),
                    'color': marker_col,
                    },
            name='',
            text=df1['areaName'],
            textposition='top center',
            customdata=np.stack(
                (
                    df1['date'],
                    df1['newCasesByPublishDate'],
                    df1['newDeaths28DaysByPublishDate'],
                    df1['cumCasesByPublishDate'],
                    df1['cumDeaths28DaysByPublishDate']
                ),
                axis=-1
            ),
            hovertemplate='<br><b>Date</b>: %{customdata[0]}' + \
                          '<br><b>Local Authority</b>: %{text}' + \
                          '<br><b>New Cases</b>: %{customdata[1]:,}' + \
                          '<br><b>New Deaths</b>: %{customdata[2]:,}' + \
                          '<br><b>Cumulative Cases</b>: %{customdata[3]:,}' + \
                          '<br><b>Cumulative Deaths</b>: %{customdata[4]:,}'
        )
    )

    fig.update_layout(
        hovermode='closest',
        mapbox=dict(
            accesstoken=mapbox_access_token,
            bearing=0,
            center=dict(lat=lat_mean, lon=lon_mean),
            pitch=0,
            zoom=5,
            style='light'  # satellite, outdoors, streets, dark
        ),
        hoverlabel=dict(bgcolor=bgcol_1, font_size=12, font_family='Rockwell'),
        margin=dict(t=0, b=0, l=0, r=0))

    # print(str(datetime.now()), '[1] finish update_map...')

    return fig  # df1.to_dict('records')
Example #4
0
def update_MapTotal(TipusMap, TempsSelected, geolocationUser, n):
    """lala"""
    mydfTracks=_MyDb.GetTracks(1)
    if mydfTracks is None:
        fig = go.Figure(go.Scattermapbox(
            mode = "markers+text",
            marker =dict(size=20, color='red'),
            textposition='top right',
            name='Basic')
        )
        fig.update_layout(
        margin ={'l':0,'t':0,'b':0,'r':0},
        height=750,
        mapbox = {
            'accesstoken':MapBoxToken,
            'style': TipusMap},
        title_text='Cercador de Babys')
        return "DB error", fig

    DateHour=datetime.now()+timedelta(minutes=-TempsSelected*10)
    dfSelected=mydfTracks[mydfTracks['LocDate']>=DateHour]
    if dfSelected.empty:
        dfSelected=mydfTracks.head(MAX_ITEMS_SELECTED)

    fig = go.Figure(go.Scattermapbox(
        mode = "markers+lines+text",
        lon = dfSelected.Longitude,
        lat = dfSelected.Latitude,
        textposition='top right',
        textfont=dict(size=MAX_TEXT_SIZE, color=COLOR_SERIE),
        text=dfSelected['LocDate'].dt.strftime('%H:%M:%S'),
        marker = {'size': 10, 'color':COLOR_SERIE},
        name='Trackers')
    )
     #si tenim la geocalització de l'usuari, la pintem i posicionem el mapa al centre entre la usr location y els tracks
    maxLatitude=mydfTracks['Latitude'].max()
    maxLongitude=mydfTracks['Longitude'].max()
    minLatitude=mydfTracks['Latitude'].min()
    minLongitude=mydfTracks['Longitude'].min()

    myloc=geolocationUser.split(",")
    if (len(myloc)==2):   
        fig.add_trace(go.Scattermapbox(
            mode = "markers+lines",
            lon =[myloc[1]],
            lat = [myloc[0]],
            textposition='top right',
            textfont=dict(size=MAX_TEXT_SIZE, color=COLOR_USR),
            text="MyLoc" + str(datetime.now()),
            marker =dict(size=20, color='green'),
            name='MyLoc')
        )
        maxLatitude=max(float(myloc[0]),maxLatitude)
        maxLongitude=max(float(myloc[1]),maxLongitude)
        minLatitude=min(float(myloc[0]),minLatitude)
        minLongitude=min(float(myloc[1]),minLongitude)
    
    fig.update_layout(
    margin ={'l':0,'t':0,'b':0,'r':0},
    height=750,
    mapbox = {
        'center': {'lon':(minLongitude+maxLongitude)/2, 'lat': (minLatitude+maxLatitude)/2},
        'accesstoken':MapBoxToken,
        'style': TipusMap,
        'zoom':calcZoom(minLongitude,maxLongitude,minLatitude,maxLatitude)}
    )
    #mydfTracks=_MyDb.GetTracks(1,HourValue)
    #fig = go.Figure(go.Scattermapbox(
    #    mode = "markers+lines",
    #    lon = mydfTracks.Longitude,
    #    lat = mydfTracks.Latitude,
    #    marker = {'size': 10, 'color':'fuchsia'},
    #    name='DadUpdated'))
    #fig.update_layout(
    #    margin ={'l':0,'t':0,'b':0,'r':0},
    #    height=750,
    #    mapbox = {
    #        'center': {'lon':(MIN_LONGITUDE+MAX_LONGITUDE)/2, 'lat': (MIN_LATITUDE+MAX_LATITUDE)/2},
    #        'style': "stamen-terrain",
    #        'zoom': CNST_ZOOM},
    #    title_text='Cercador de Babys')
    return  f" --Slider SELECT: {TempsSelected} -- GEOLOCATION: {myloc} --",fig
Example #5
0
#Read CSV File
import pandas as pd 
import config_p24
mapbox_token = (config_p24.mapbox_token)
sta_df = pd.read_excel(config_p24.dash_ready)
# TO DO refine marker color based on price and add more info in text box (Title, address, size etc.) like here https://docs.mapbox.com/mapbox-gl-js/example/popup-on-hover/
 
# this data trace shows the listings
from plotly.offline import plot
import plotly.graph_objects as go

scatt = go.Scattermapbox(
                        lat = list(sta_df["lat"]),
                        lon = list(sta_df["lon"]),                        
                        mode='markers',
                        hoverinfo='text',
                        marker=dict(symbol ='marker', size=5, color='white'),
                        textposition='top right',
                        textfont=dict(size=16, color='black'),
                        text = list(sta_df["Address"] + " Location: " + sta_df["Location"] + " Price: " + sta_df["Price"].astype(str))
                        )

# TO DO add trace with crime stats per region chlorochart

layout = go.Layout(hovermode = "closest",
                    mapbox = dict(           
                                 accesstoken= mapbox_token,
                                 zoom=8,
                                 center=dict(lat = sta_df["lat"].median(),
                                             lon = sta_df["lon"].median()
                                             )
                               )
Example #6
0
def update_cards(n_clicks, dummy_clicks):
	sum_conf,sum_deat,sum_rec,countries,df_name,df_lat,df_lon,midpoint,df_country,recent,summary,dff_conf,dff_rec = data_parse()
	
	card1 = do.Figure(do.Indicator(
			mode= 'number',
			value= sum_conf,
			number={'valueformat':'.%f', 'font':{'size':30,'family':'Nunito Sans','color':'#d9534f'}},
			title = {"text": 'Confirmed', 'font':{'size':25,'family':'Nunito Sans'}}))
	card1.update_layout(margin= do.layout.Margin(t=35,b=0), plot_bgcolor='#ffffff', paper_bgcolor='#ffffff')
	
	card2 = do.Figure(do.Indicator(
			mode= 'number',
			value= sum_deat,
			number={'valueformat':'.%f', 'font':{'size':30,'family':'Nunito Sans','color':'#d9534f'}},
			title = {"text": 'Deaths', 'font':{'size':25,'family':'Nunito Sans'}}))
	card2.update_layout(margin= do.layout.Margin(t=35,b=0), plot_bgcolor='#ffffff', paper_bgcolor='#ffffff')
	
	card3 = do.Figure(do.Indicator(
			mode= 'number',
			value= sum_rec,
			number={'valueformat':'.%f', 'font':{'size':30,'family':'Nunito Sans','color':'#4bbf73'}},
			title = {"text": 'Recovered', 'font':{'size':25,'family':'Nunito Sans'}}))
	card3.update_layout(margin= do.layout.Margin(t=35,b=0), plot_bgcolor='#ffffff', paper_bgcolor='#ffffff')
	
	card4 = do.Figure(do.Indicator(
			mode= 'number',
			value= len(countries),
			number={'valueformat':'.%f', 'font':{'size':30,'family':'Nunito Sans','color':'#d9534f'}},
			title = {"text": 'Countries with cases', 'font':{'size':20,'family':'Nunito Sans'}}))
	card4.update_layout(margin= do.layout.Margin(t=35,b=0), plot_bgcolor='#ffffff', paper_bgcolor='#ffffff')
	
	hover_text = ['Province/State: '+'{}'.format(x) + '<br>Country: '+'{}'.format(y) + '<br>Confirmed: '+'{}'.format(z) + '<br>Deaths: '+'{}'.format(v) + '<br>Recovered: '+'{}'.format(w) for x,y,z,v,w in zip(df_name,df_country,list(summary['Confirmed']),list(summary['Deaths']),list(summary['Recovered']))]
	
	map1 = do.Figure()
	map1.add_trace(
		do.Scattermapbox(
			lat=df_lat,
			lon=df_lon,
			mode='markers',
			marker=do.scattermapbox.Marker(
				size=5,
				color='#c94631',
				opacity=0.7
				),
			text= hover_text,
			hoverinfo='text',
			showlegend= False
		)
	)
	map1.update_layout(
		mapbox= do.layout.Mapbox(
			accesstoken= map_token,
			center= do.layout.mapbox.Center(
				lat= 30.3753,
				lon= 69.3451
			),
			zoom= 1.3,
			style= map_style
		),
		margin= do.layout.Margin(
			l=0,
			r=0,
			t=0,
			b=0
		)
	)
	
	desc = html.P(["Click 'Refresh' to fetch new data & update charts. Featured data are as of {}.".format(recent)], style={'textAlign':'center'})
	
	table = do.Figure(
		do.Table(
			header={'values':list(summary.columns),'fill':{'color':'#017cbf'},'font':{'family':'Nunito Sans','color':'#ffffff'}},
			cells={'values':[summary.State,summary.Country,summary.Confirmed,summary.Deaths,summary.Recovered],
				'fill':{'color':'#f5f4ef'},'font':{'family':'Nunito Sans'}}
		)
	)
	table.update_layout(margin= do.layout.Margin(t=0,b=0,l=0,r=0), plot_bgcolor='#ffffff', paper_bgcolor='#ffffff')
	
	line1 = do.Figure(
		do.Scatter(
			x= dff_conf.index,
			y= dff_conf[0],
			marker_color='#d9534f',
		)
	)
	line1.update_layout(
		margin= do.layout.Margin(t=35,b=0,l=0,r=0), plot_bgcolor='#ffffff', paper_bgcolor='#ffffff',
		xaxis={'showgrid':False,'showticklabels':False},yaxis={'showgrid':False,'showticklabels':False},
		title={'text':'Confirmed (previous 15-day range)','font':{'family':'Nunito Sans','size':12}}
	)
	
	line2 = do.Figure(
		do.Scatter(
			x= dff_rec.index,
			y= dff_rec[0],
			marker_color='#4bbf73',
		)
	)
	line2.update_layout(
		margin= do.layout.Margin(t=35,b=0,l=0,r=0), plot_bgcolor='#ffffff', paper_bgcolor='#ffffff',
		xaxis={'showgrid':False,'showticklabels':False},yaxis={'showgrid':False,'showticklabels':False},
		title={'text':'Recovered (previous 15-day range)','font':{'family':'Nunito Sans','size':12}}
	)
	
	
	return card1,card2,card3,card4,map1,desc,table,line1,line2
Example #7
0
def generate_geo_map(df):

    lat = df["latitude"].tolist()
    lon = df["longitude"].tolist()
    state_list = df["State"].tolist()
    nation_list = df["Country"].tolist()
    confirmed_list = df["Confirmed"].tolist()
    deaths_list = df["Deaths"].tolist()
    recovered_list = df["Recovered"].tolist()
    #average_confirmed = df["Confirmed"]["mean"].tolist()

    colors = ["#21c7ef", "#76f2ff", "#ff6969", "#ff1717"]

    confirmed_metric_data = {}
    confirmed_metric_data["min"] = df["Confirmed"].min()
    confirmed_metric_data["max"] = sorted(confirmed_list, reverse=True)[1]
    confirmed_metric_data["mid"] = (confirmed_metric_data["min"] +
                                    confirmed_metric_data["max"]) / 2
    confirmed_metric_data["low_mid"] = (confirmed_metric_data["min"] +
                                        confirmed_metric_data["mid"]) / 2
    confirmed_metric_data["high_mid"] = (confirmed_metric_data["mid"] +
                                         confirmed_metric_data["max"]) / 2

    countries = []

    for i in range(len(lat)):
        #print("CHECK POINT 1 - {}".format(i))
        state = state_list[i]
        nation = nation_list[i]
        confirmed = confirmed_list[i]
        deaths = deaths_list[i]
        recovered = recovered_list[i]

        if confirmed <= confirmed_metric_data["low_mid"]:
            color = colors[0]
        elif confirmed_metric_data[
                "low_mid"] < confirmed <= confirmed_metric_data["mid"]:
            color = colors[1]
        elif confirmed_metric_data["mid"] < confirmed <= confirmed_metric_data[
                "high_mid"]:
            color = colors[2]
        else:
            color = colors[3]

        country = go.Scattermapbox(
            lat=[lat[i]],
            lon=[lon[i]],
            mode="markers",
            marker=dict(color=color,
                        showscale=False,
                        colorscale=[
                            [0, "#21c7ef"],
                            [0.33, "#76f2ff"],
                            [0.66, "#ff6969"],
                            [1, "#ff1717"],
                        ],
                        size=math.log(confirmed, 6) * 10,
                        opacity=0.7),
            selected=dict(marker={"color": "#ffff00"}),
            hoverinfo="text",
            text=nation + "<br>" + state + "<br>" +
            "Confirmed : {}".format(confirmed) + "<br>" +
            "Deaths : {}".format(deaths) + "<br>" +
            "Recoverd : {}".format(recovered),
        )
        countries.append(country)

    layout = go.Layout(
        title="Global Map",
        margin=dict(l=10, r=10, t=30, b=10, pad=3),
        plot_bgcolor="white",
        paper_bgcolor="white",
        clickmode="event+select",
        hovermode="closest",
        showlegend=False,
        mapbox=go.layout.Mapbox(
            accesstoken=mapbox_access_token,
            bearing=0,
            center=go.layout.mapbox.Center(lat=25, lon=120),
            pitch=20,
            zoom=2,
            #style="mapbox://styles/plotlymapbox/cjvppq1jl1ips1co3j12b9hex",
            style="light"),
    )

    figure = dict(data=countries, layout=layout)

    return figure
Example #8
0
fig.show()

manh_df = crime[crime.BOROUGH_NAME==2]
manh_m_df = manh_df[manh_df.LEVEL_OF_OFFENSE==-1]
manh_f_df = manh_df[manh_df.LEVEL_OF_OFFENSE==1]

pip install geopandas

import geopandas as gpd 
import plotly.offline as py

mapbox_access_token = 'pk.eyJ1IjoiZmlzaGVlcCIsImEiOiJjazgwcXd5amIwMnRtM2ZwNDR5OHRjb2Q1In0.wUN67xk4G_3OYy9-tqoqgA'

d = [   go.Scattermapbox(
        lat=manh_m_df.Latitude[m_kmeans.labels_==0],
        lon=manh_m_df.Longitude[m_kmeans.labels_==0],
        mode='markers',
        name='Mis_red',
        marker=go.scattermapbox.Marker(size=5,color='Red')),
     
        go.Scattermapbox(
        lat=manh_m_df.Latitude[m_kmeans.labels_==1],
        lon=manh_m_df.Longitude[m_kmeans.labels_==1],
        mode='markers',
        name='Mis_green',
        marker=go.scattermapbox.Marker(size=5,color='Green')),
     
        go.Scattermapbox(
        lat=manh_m_df.Latitude[m_kmeans.labels_==2],
        lon=manh_m_df.Longitude[m_kmeans.labels_==2],
        mode='markers',
        name='Mis_blue',
Example #9
0
# this is the token used to generate the plotly map, may have to be regenerated
token = "pk.eyJ1IjoidWdoaXRzc2lkIiwiYSI6ImNrNm54Z3I5cTE1aDIzbW55MjcwdWp4MnEifQ.xylSSPUA0Yt9ly6jOBMg4w"

# the latitutes, longitudes, and names of the respective points. First lat corresponds to first lon and text, second to second, and so on
lats = [rep.codeDay.lat, rep.sb1.lat, rep.chpt1.lat, rep.pnbrd1.lat]
lons = [rep.codeDay.lon, rep.sb1.lon, rep.chpt1.lon, rep.pnbrd1.lon]
texts = [rep.codeDay.text, rep.sb1.text, rep.chpt1.text, rep.pnbrd1.text]

# create a new figure using plotly
# initialize the longitudes, latitudes, and texs as points
fig = go.Figure(
    go.Scattermapbox(
        lat=lats,
        lon=lons,
        mode='markers',
        marker=go.scattermapbox.Marker(size=14),
        text=texts,
    ))

# create the map with needed visual attributes
fig.update_layout(
    autosize=True,
    hovermode='closest',
    mapbox=dict(
        accesstoken=token,
        bearing=0,
        center=go.layout.mapbox.Center(
            # center the map at a calculated average of the points' positions
            lat=rep.avgLat,
            lon=rep.avgLon),
Example #10
0
    def animedPlot(self, solution, time_res, costmap, start, goal, region, obstacle,scenario, filename):
        #colorscale to be used in the contour plot
        colorscale=[[0, '#ffffff'],
                    [0.25, '#a0ff7d'],
                    [0.5, '#c5c400'],
                    [0.75, '#dc8000'],
                    [1, '#e10000']]
        colorscale = 'dense'
        #Create the plot Structure
        fig = make_subplots(
            rows=1, cols=2,
            column_widths=[0.45,0.45],
            row_heights=[1],
            subplot_titles=("Solution Path in a Real Map","2D CostMap"),
            specs=[[{"type": "Scattermapbox"},{"type": "contour"}]])
        
        #0
        #Trace for solution  
        fig.append_trace(go.Scattermapbox(
            lat=solution['lat'],
            lon=solution['lon'],
            #lat=[],
            #lon=[],
            name='Solution Path',
            mode='markers+lines',
            marker=dict(size=5, color='blue')
            ),row=1,col=1)

        #1
        #Trace for area of flight
        lat_aux = [reg[0] for reg in region]
        lon_aux = [reg[1] for reg in region]
        fig.append_trace(go.Scattermapbox(
            lon = lon_aux, 
            lat = lat_aux,
            fill = "toself",
            name='Area of Flight',
            marker = { 'size': 5, 'color': "rgba(123, 239, 178, 1)" }),row=1,col=1)

        #2
        #Start position
        fig.append_trace(go.Scattermapbox(
            mode = "markers",
            lon = [start[1]],
            lat = [start[0]],
            marker = {'size':5,'color':"black"},
            name='Start'
            ),row=1,col=1)

        #3
        #goal position
        fig.append_trace(go.Scattermapbox(
            mode = "markers",
            lon = [goal[1]],
            lat = [goal[0]],
            marker = {'size':5,'color':"black"},
            name='Goal'
            ),row=1,col=1)

        #4
        #Solution trace for contour
        fig.append_trace(go.Scatter(
            x = solution['lon'], 
            y = solution['lat'],
            #x = [], 
            #y = [],
            mode='markers+lines',
            name='Solution Path',
            marker=dict(size=5, color='red')
            ),row=1,col=2)

        #5
        #Contour plot
        lat,lon = zip(*region)
        lat = list(lat)
        lon = list(lon)
        costmap_y = np.linspace(min(lat),max(lat), len(costmap.y))
        costmap_x = np.linspace(min(lon),max(lon), len(costmap.x))
        fig.append_trace(go.Contour(
            z=costmap.z_time[0],
            x=costmap_x, 
            y=costmap_y, 
            ids=costmap.z_time,
            name='Cost Time: 0',
            line_smoothing=0,
            colorscale=colorscale,
            contours=dict(
                start=costmap.z_time[0].min(), 
                end=costmap.z_time[0].max(), 
                size=1, 
                showlines=False)
            ), row=1, col=2)
        #Fixa o eixo dos plots
        fig.update_xaxes(range=[min(lon),max(lon)],showgrid=False,constrain="domain")
        fig.update_yaxes(range=[min(lat),max(lat)],showgrid=False,constrain="domain")

        #Trace for area of flight
        if obstacle != [] :
            for idx, polygon in enumerate(obstacle):
                lat,lon = zip(*polygon[0])
                lat = list(lat)
                lon = list(lon)
                fig.append_trace(go.Scattermapbox(
                    lon = lon, 
                    lat = lat,
                    fill = "toself",
                    name=polygon[3],
                    marker = { 'size': 5, 'color': "rgba(255, 0, 0, 0)" }),row=1,col=1)
        
        #Cria o perimetro ao redor dos vertiports
        if costmap.verti_perimeters != []:
            vertiport_lat, vertiport_lon = zip(*scenario.vertiports_real)
            fig.append_trace(go.Scattermapbox(
                    lon = vertiport_lon, 
                    lat = vertiport_lat,
                    mode='markers',
                    name='Vertiport',
                    marker=dict(size=5, color='yellow')
                    ),row=1,col=1)
            fig.append_trace(go.Scatter(
                    x = vertiport_lon, 
                    y = vertiport_lat,
                    mode='markers',
                    name='Vertiports',
                    marker=dict(size=5, color='yellow')
                    ),row=1,col=2)
            verti_r_lat = []
            verti_r_lon = []
            for idx, verti_region in enumerate(costmap.verti_perimeters):
                r_lon = verti_region[1]*scenario.lon_range + min(scenario.lon_region)
                r_lat = verti_region[0]*scenario.lat_range + min(scenario.lat_region)

                verti_r_lon.extend(r_lon)
                verti_r_lat.extend(r_lat)
            fig.append_trace(go.Scattermapbox(
                mode = "markers",
                lon = verti_r_lon,
                lat = verti_r_lat,
                marker = {'size':5,'color':"green"},
                name='Vertiport Region'
                ),row=1,col=1)
            fig.append_trace(go.Scatter(
                x = verti_r_lon, 
                y = verti_r_lat,
                mode='markers',
                name='Vertiport Region',
                marker=dict(size=5, color='green')
                ),row=1,col=2)
                
                
                

        #Atualiza o layout
        token = 'pk.eyJ1Ijoiam9zdWVoZmEiLCJhIjoiY2tldnNnODB3MDBtdDJzbXUxMXowMTY5MyJ9.Vwj9BTqB1z9RLKlyh70RHw'  
        fig.update_layout(
            mapbox = {
                #'style': "outdoors",
                'style': "stamen-terrain",
                'center': {'lon': -43.9520, 'lat': -19.8997 },
                #'accesstoken': token,
                'zoom': 11},
            title_text="UAS Path Generation", hovermode="closest",
            legend=dict(
                orientation="h",
                yanchor="top",
                #y=1.02,
                xanchor="right",
                x=1
            ),
            updatemenus=[dict( type="buttons",
                showactive= False,
                buttons=[
                    dict(label="Play",
                        method="animate",
                        args=[[None], 
                            dict(frame= { "duration": 100},
                                fromcurrent= True,
                                mode='immediate', 
                                transition= {"duration":0, "easing": "linear"}
                                )]),
                    dict(label='Pause',
                        method='animate',
                        args= [ [None],
                            dict(frame= { "duration": 0},
                                fromcurrent= True,
                                mode='immediate', 
                                transition= {"duration": 0, "easing": "linear"}
                                        )]
                    )]
                )])

        frames = []
        #for idx, t in enumerate(time_res):
        #    frames.append(go.Frame(data=[go.Scattermapbox(
        #                               lat=solution['lat'][:idx+1], 
        #                               lon=solution['lon'][:idx+1],mode='markers+lines')],traces=[0]))
             
        #    frames.append(go.Frame(data=[go.Scatter(
        #                               x=solution['lon'][:idx], 
        #                               y=solution['lat'][:idx],mode='markers+lines')],traces=[4]))
        #    frames.append(go.Frame(data=[go.Contour(x=costmap_x, y=costmap_y, z=costmap.z_time[t], line_smoothing=0, 
        #                            colorscale=colorscale,
        #                            name='Cost Time: '+str(t),
        #                            contours=dict(
        #                                start=costmap.z_time[t].min(), 
        #                                end=costmap.z_time[t].max(), 
        #                                size=1, 
        #                                showlines=False))],traces=[5]))
        #fig.update(frames=frames)
        plotly.offline.plot(fig, filename=filename,auto_open=False)
Example #11
0
def createFigureWithOptimalPointsAndBubbleFlows(D_res,
                                                D_res_optimal,
                                                latCol,
                                                lonCol,
                                                descrCol='PERIOD'):
    '''
    generates the map with the optimal location of a network.
    Optimal locations for each period are in D_res_optimal. Period are prepresented
    as animation frames of the figure
    
    #D_res is a dataframe with flows defined by the function calculateOptimalLocation
    #D_res_optimal is a dataframe with optimal locations defined by the function calculateOptimalLocation
    #latCol is a string with column name for latitude
    #lonCol is a string with column name for longitude
    #descrCol is a string with column name for node description
    '''

    #assign color for the optimal points
    #aaa=pd.factorize(D_res['YEAR'])
    D_res_optimal['COLOR'] = pd.factorize(D_res_optimal['YEAR'])[0]

    ########################################
    ######### DEFINE RAW FIGURE ############
    ########################################
    #define raw figure
    fig_dict = {"data": [], "layout": {}, "frames": []}

    ########################################
    ######### DEFINE BASE LAYOUT ###########
    ########################################

    # Identify all the years
    years = list(set(D_res_optimal["YEAR"]))
    years.sort()

    # define layout hovermode
    fig_dict["layout"]["hovermode"] = "closest"

    # define sliders
    fig_dict["layout"]["sliders"] = {
        "args": ["transition", {
            "duration": 400,
            "easing": "cubic-in-out"
        }],
        "initialValue": "1952",
        "plotlycommand": "animate",
        "values": years,
        "visible": True
    }

    #define menus and buttons
    fig_dict["layout"]["updatemenus"] = [{
        "buttons": [{
            "args": [
                None, {
                    "frame": {
                        "duration": 500,
                        "redraw": True
                    },
                    "fromcurrent": True,
                    "transition": {
                        "duration": 300,
                        "easing": "quadratic-in-out"
                    }
                }
            ],
            "label":
            "Play",
            "method":
            "animate"
        }, {
            "args": [[None], {
                "frame": {
                    "duration": 0,
                    "redraw": True
                },
                "mode": "immediate",
                "transition": {
                    "duration": 0
                }
            }],
            "label":
            "Pause",
            "method":
            "animate"
        }],
        "direction":
        "left",
        "pad": {
            "r": 10,
            "t": 87
        },
        "showactive":
        False,
        "type":
        "buttons",
        "x":
        0.1,
        "xanchor":
        "right",
        "y":
        0,
        "yanchor":
        "top"
    }]

    #define slider dictionary
    sliders_dict = {
        "active": 0,
        "yanchor": "top",
        "xanchor": "left",
        "currentvalue": {
            "font": {
                "size": 20
            },
            "prefix": "Year:",
            "visible": True,
            "xanchor": "right"
        },
        "transition": {
            "duration": 300,
            "easing": "cubic-in-out"
        },
        "pad": {
            "b": 10,
            "t": 50
        },
        "len": 0.9,
        "x": 0.1,
        "y": 0,
        "steps": []
    }

    ########################################
    ######### DEFINE DATA ##################
    ########################################

    #start from the first frame and define the figure
    year = years[0]

    ########################################
    ######### DEFINE FIGURE ################
    ########################################

    #define the trace with optimal point
    currentColor = 0

    data_dict = go.Scattermapbox(
        lat=D_res_optimal[D_res_optimal['YEAR'] == year][latCol],
        lon=D_res_optimal[D_res_optimal['YEAR'] == year][lonCol],
        mode='markers',
        marker=go.scattermapbox.Marker(
            size=14,
            #color='red',
            #color=currentColor,
            #color=cm.Reds(colore),
            color=[i for i in range(0, len(D_res_optimal['YEAR'] == year))],
            opacity=1,
            colorscale="Reds"),
        text=D_res_optimal[D_res_optimal['YEAR'] == year]['PERIOD'],
        name='optimal')

    fig_dict["data"].append(data_dict)

    #define the trace with bubbles of the other flows
    data_dict = go.Scattermapbox(
        lat=D_res[D_res['YEAR'] == year][latCol],
        lon=D_res[D_res['YEAR'] == year][lonCol],
        #color=,
        text=D_res[D_res['YEAR'] == year][descrCol],
        marker=go.scattermapbox.Marker(
            size=D_res[D_res['YEAR'] == year]['FLOW_norm'],
            color=D_res[D_res['YEAR'] == year]['COST_TOBE'],
            opacity=0.5,
            showscale=True,
            colorscale='Viridis',
        ),
        name='flow intensity')
    #projection="natural earth")
    fig_dict["data"].append(data_dict)

    ########################################
    ######### DEFINE FRAMES ################
    ########################################

    for year in years:
        frame = {"data": [], "name": year}

        #count the current color to have a gradient in the optimal point
        currentColor = currentColor + 1

        #define the trace with optimal point
        data_dict = go.Scattermapbox(
            lat=D_res_optimal[D_res_optimal['YEAR'] <= year][latCol],
            lon=D_res_optimal[D_res_optimal['YEAR'] <= year][lonCol],
            mode='markers',
            marker=go.scattermapbox.Marker(
                size=14,
                #color='red',
                #color=currentColor,
                #color=cm.Reds(colore),
                color=D_res_optimal[D_res_optimal['YEAR'] <= year]['COLOR'],
                #color=[i for i in range(0,len(D_res_optimal['YEAR']==year))],
                opacity=1,
                colorscale="Reds"),
            text=D_res_optimal[D_res_optimal['YEAR'] <= year]['PERIOD'],
            name='optimal')
        frame["data"].append(data_dict)

        #define the trace with bubbles of the other flows
        data_dict = go.Scattermapbox(
            lat=D_res[D_res['YEAR'] == year][latCol],
            lon=D_res[D_res['YEAR'] == year][lonCol],
            #color=,
            text=D_res[D_res['YEAR'] == year][descrCol],
            marker=go.scattermapbox.Marker(
                size=D_res[D_res['YEAR'] == year]['FLOW_norm'],
                color=D_res[D_res['YEAR'] == year]['COST_TOBE'],
                opacity=0.5,
                showscale=True,
                colorscale='Viridis',
            ),
            name='flow intensity')
        #projection="natural earth")
        frame["data"].append(data_dict)
        fig_dict["frames"].append(frame)

        # update the slider
        slider_step = {
            "args": [[year], {
                "frame": {
                    "duration": 300,
                    "redraw": True
                },
                "mode": "immediate",
                "transition": {
                    "duration": 300
                }
            }],
            "label":
            year,
            "method":
            "animate"
        }
        sliders_dict["steps"].append(slider_step)

    #update the layout
    fig_dict["layout"]["sliders"] = [sliders_dict]
    #create the figure
    fig = go.Figure(fig_dict)

    #update with openStreetMap style
    fig.update_layout(mapbox_style="open-street-map")
    return fig
Example #12
0
    def simplePlot(self, solution, final_solution, obstacle, costmap, start, goal, region):
        #Generate a simple solution plot using plotly

        t = np.linspace(-1, 1, 100)
        x = t + t ** 2
        y = t - t ** 2
        xm = np.min(x) - 1.5
        xM = np.max(x) + 1.5
        ym = np.min(y) - 1.5
        yM = np.max(y) + 1.5
        N = 200
        s = np.linspace(-1, 1, N)
        xx = s + s ** 2
        yy = s - s ** 2
        

        def get_sliders(n_frames, fr_duration=100, x_pos=0.0, slider_len=1.0):
            # n_frames= number of frames
            #fr_duration=the duration in milliseconds of each frame
            #x_pos x-coordinate where the slider starts
            #slider_len is a number in (0,1] giving the slider length as a fraction of x-axis length 
            return [dict(steps= [dict(method= 'animate',#Sets the Plotly method to be called when the slider value is changed.
                                    args= [ [ 'frame{}'.format(k) ],#Sets the arguments values to be passed to the Plotly,
                                                                    #method set in method on slide
                                            dict(mode= 'immediate',
                                                frame= dict( duration=fr_duration, redraw= True ),
                                                transition=dict( duration= 0)
                                                )
                                            ],
                                    label='fr{}'.format(k)
                                    ) for k in range(n_frames)], 
                        transition= { 'duration': 0 },
                        x=x_pos,
                        len=slider_len)]



        #Create a Plot Structure
        fig = make_subplots(
            rows=1, cols=2,
            column_widths=[0.45,0.45],
            row_heights=[1],
            subplot_titles=("Solution Path in a Real Map","2D CostMap"),
            specs=[[{"type": "Scattermapbox"},{"type": "contour"}]])
        
            
    
        #data_fig.append(go.Scattermapbox(
        #    mode = "markers+lines",
        #    lon = [],
        #    lat = [],
        #    marker = {'size': 5},
        #    name='test'))

        #data_fig.append(go.Scattermapbox(
        #    mode = "markers+lines",
        #    lon = [],
        #    lat = [],
        #    marker = {'size': 5},
        #    name='FinalResult'))
        

        
        z =    [[2, 4, 7, 12, 13, 14, 15, 16],
                [3, 1, 6, 11, 12, 13, 16, 17],
                [4, 2, 7, 7, 11, 14, 17, 18],
                [5, 3, 8, 8, 13, 15, 18, 19],
                [7, 4, 10, 9, 16, 18, 20, 19],
                [9, 10, 5, 27, 23, 21, 21, 21],
                [11, 14, 17, 26, 25, 24, 23, 22]]
        
        nrows = 80
        ncols = 80
        time = 10
        z_t = []
        for t in range(time):
            z = np.zeros((nrows+1, ncols+1), dtype=np.uint8) + 1
            xx,yy = disk((0.5*nrows,0.5*nrows),0.5*nrows)
            z[xx,yy] = 10

            xx,yy = disk((0.5*nrows,0.5*nrows),0.25*nrows)
            z[xx,yy] = 20

            xx,yy = disk((0.5*nrows,0.5*nrows),0.125*nrows)
            z[xx,yy] = 50

            #Region Clearece
            xx, yy = ellipse(0.5*nrows+t*(0.5*nrows/time), 0.5*ncols-t*(0.5*ncols/time), 0.15*nrows, 0.25*ncols, rotation=np.deg2rad(10))
            x_del = np.argwhere( (xx <= 0) | (xx >= nrows) )
            y_del = np.argwhere( (yy <= 0) | (yy >= ncols) )
            xx = np.delete(xx, np.concatenate((x_del, y_del), axis=0))
            yy = np.delete(yy, np.concatenate((x_del, y_del), axis=0))
            z[xx,yy] = 50

                #Region Clearece
            xx, yy = ellipse(0.5*nrows-t*(0.5*nrows/time), 0.5*ncols+t*(0.5*ncols/time), 0.15*nrows, 0.25*ncols, rotation=np.deg2rad(10))
            x_del = np.argwhere( (xx <= 0) | (xx >= nrows) )
            y_del = np.argwhere( (yy <= 0) | (yy >= ncols) )
            xx = np.delete(xx, np.concatenate((x_del, y_del), axis=0))
            yy = np.delete(yy, np.concatenate((x_del, y_del), axis=0))
            z[xx,yy] = 50

            z = np.asarray(z,dtype=np.double)
            z_t.append(z)

        X=np.linspace(-1,1, 80)
        Y=np.linspace(-1,1, 80)
        colorscale=[[0, '#e1ebec'],
                    [0.25, '#b1d3e3'],
                    [0.5, '#72a5d3'],
                    [0.75, '#3b6ba5'],
                    [1, '#193f6e']]
        colorscale=[[0, '#ffffff'],
                    [0.25, '#a0ff7d'],
                    [0.5, '#c5c400'],
                    [0.75, '#dc8000'],
                    [1, '#e10000']]

        y=np.arange(100) 
        #fig.append_trace(go.Scatter(x=[1,2,3,4,5,1,2,3,4,5,1,2,3,4,5], y=[1,1,1,1,1,2,2,2,2,2,3,3,3,3,3], marker_size = 100,mode='markers',marker_symbol='square', marker=dict(
        #            color=z,
        #            line_width=1)),row=1,col=1)

        #filename = "https://github.com/CSSEGISandData/COVID-19/blob/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv"
        #df = pd.read_csv(filename, encoding='utf-8')
        #df = df.head(100)
        lat=np.arange(50)
        lon=np.arange(50)
        fig.append_trace(go.Scattermapbox(
               lat=lat,
               lon=lon,
               mode='markers+lines',
               marker=dict(size=5, color='red')
            ),row=1,col=1)

        lat_aux = [reg[0] for reg in region]
        lon_aux = [reg[1] for reg in region]
        fig.append_trace(go.Scattermapbox(
            lon = lon_aux, 
            lat = lat_aux,
            fill = "toself",
            name='Area of Flight',
            marker = { 'size': 5, 'color': "rgba(123, 239, 178, 1)" }),row=1,col=1)

        fig.append_trace(go.Scattermapbox(
            mode = "markers",
            lon = [start[1]],
            lat = [start[0]],
            marker = {'size':5,'color':"black"},
            name='Start'
            ),row=1,col=1)

        fig.append_trace(go.Scattermapbox(
            mode = "markers",
            lon = [goal[1]],
            lat = [goal[0]],
            marker = {'size':5,'color':"black"},
            name='Goal'
            ),row=1,col=1)

        fig.append_trace(go.Scatter(
            x = [], 
            y = [],
            ids=X,
            mode='markers+lines',
            marker=dict(size=5, color='black')
            ),row=1,col=2)
        fig.append_trace(go.Contour(x=X, y=Y, z=z_t[0], ids=z_t,
                                    name='testcolormap',
                                    line_smoothing=0, 
                                    colorscale=colorscale,
                                    contours=dict(
                                        start=0, 
                                        end=50, 
                                        size=1, 
                                        showlines=False)
                                    ), row=1, col=2)


        fig.update_xaxes(range=[-1,1],showgrid=False,constrain="domain")
        fig.update_yaxes(range=[-1,1],showgrid=False,constrain="domain")
        fig.update_layout(
                mapbox = {
                    'style': "stamen-terrain",
                    'center': {'lon': 0, 'lat': 0 },
                    'zoom': 5},
                title_text="UAS Path Generation", hovermode="closest",
                legend=dict(
                    orientation="h",
                    yanchor="top",
                    #y=1.02,
                    xanchor="right",
                    x=1
                ),
                updatemenus=[dict(  #x=0,
                                    #y=0,
                                    #yanchor='top',
                                    #xanchor= 'right',
                                    #pad= dict(r= 10, t=40 ),
                                    type="buttons",
                                    showactive= False,
                                    buttons=[dict(label="Play",
                                            method="animate",
                                            args=[[None], dict(frame= { "duration": 50},
                                                                fromcurrent= True,
                                                                mode='immediate'#, 
                                                                #transition= {"duration":10, "easing": "linear"}
                                                                )]),
                                            dict(label='Pause',
                                                method='animate',
                                                args= [ [None],
                                                        dict(frame= { "duration": 0},
                                                                fromcurrent= True,
                                                                mode='immediate'#, 
                                                                #transition= {"duration": 0, "easing": "linear"}
                                                                )
                                      ]
                                )])]#,
                #sliders=get_sliders(n_frames=100)
                            )

        #frames = [go.Frame(
        #            data=[go.Scattermapbox(
        #                lon=solution[k][1],
        #                lat=solution[k][0],
        #                mode="markers",
        #                marker=dict(color="orange", size=10),
        #                name='test'),
        #                go.Scattermapbox(
        #                lon=final_solution[1][:k],
        #                lat=final_solution[1][:k],
        #                mode="lines",
        #                marker=dict(color="red", size=10),
        #                name='FinalResult')]) for k in range(len(solution))]

        move = 0
        frames = []
        
        for i in range(1, 50):
            frames.append(go.Frame(data=[go.Scattermapbox(
                                       lat=lat[:i], 
                                       lon=lon[:i],mode='markers+lines')],traces=[0]))
             
            frames.append(go.Frame(data=[go.Scatter(
                                       x=X[:i], 
                                       y=Y[:i],mode='markers+lines')],traces=[4]))
            frames.append(go.Frame(data=[go.Contour(x=X, y=Y, z=z_t[move], line_smoothing=0, 
                                    colorscale=colorscale,
                                    contours=dict(
                                        start=0, 
                                        end=50, 
                                        size=1, 
                                        showlines=False))],traces=[5]))
            
            if i%10 == 0 and i < 100:
                move = move + 1
                
        #frames= [go.Frame(data=[go.Scatter(y=y[:i],name='Testing Points'),go.Contour(z=z, line_smoothing=0, colorscale='dense',name='testcolormap')]) for i in range(1, 100)]



        fig.update(frames=frames)
        
        plotly.offline.plot(fig, filename='path.html')
        #fig.show()
        print()
Example #13
0
    def get_states_cases_plot(self):
        coord_dict = {
            'AC': [-8.77, -70.55],
            'AL': [-9.71, -35.73],
            'AM': [-3.07, -61.66],
            'AP': [1.41, -51.77],
            'BA': [-12.96, -38.51],
            'CE': [-3.71, -38.54],
            'DF': [-15.83, -47.86],
            'ES': [-19.19, -40.34],
            'GO': [-16.64, -49.31],
            'MA': [-2.55, -44.30],
            'MT': [-12.64, -55.42],
            'MS': [-20.51, -54.54],
            'MG': [-18.10, -44.38],
            'PA': [-5.53, -52.29],
            'PB': [-7.06, -35.55],
            'PR': [-24.89, -51.55],
            'PE': [-8.28, -35.07],
            'PI': [-8.28, -43.68],
            'RJ': [-22.84, -43.15],
            'RN': [-5.22, -36.52],
            'RO': [-11.22, -62.80],
            'RS': [-30.01, -51.22],
            'RR': [1.89, -61.22],
            'SC': [-27.33, -49.44],
            'SE': [-10.90, -37.07],
            'SP': [-23.55, -46.64],
            'TO': [-10.25, -48.25]
        }

        _, siglas_df = self.get_state_cases()
        list_states = [state for state in coord_dict.keys()]
        lat_coords = [coord[0] for coord in coord_dict.values()]
        long_coords = [coord[1] for coord in coord_dict.values()]
        coord_df = pd.DataFrame({
            'state': list_states,
            'lat': lat_coords,
            'long': long_coords
        })
        coord_states_cases = pd.merge(coord_df,
                                      siglas_df,
                                      how='inner',
                                      left_on='state',
                                      right_on='uf')
        coord_states_cases['hover_text'] = coord_states_cases.apply(
            lambda row: row.state + ': ' + str(row.cases), axis=1)

        api_key = 'pk.eyJ1IjoiYWxleG1hZ25vIiwiYSI6ImNrODU5d2pveDA0b28zaW95a2p6cHhydnAifQ.YiOEJwtD28loQ2d4txK6dg'

        fig = go.Figure(
            go.Scattermapbox(lat=coord_states_cases['lat'],
                             lon=coord_states_cases['long'],
                             mode='markers',
                             marker=go.scattermapbox.Marker(
                                 size=coord_states_cases['cases'] / 30),
                             text=coord_states_cases['hover_text'],
                             hoverinfo='text'))

        fig.update_layout(
            title={
                'text':
                '<b>Total de casos por estado</b><br>(Explore com o mouse)',
                'x': 0.5,
                'xanchor': 'center',
                'yanchor': 'top'
            },
            autosize=True,
            hovermode='closest',
            mapbox=dict(accesstoken=api_key,
                        bearing=0,
                        center=dict(lat=-15, lon=-55),
                        pitch=5,
                        zoom=2.5),
        )

        return fig
Example #14
0
def update_alarms(tab, n_intervals, type_connection, sta):
    # COUNTING THE ALARMS WHATEVER THE TAB
    i = 0
    try:

        with open(f'log/{type_connection}/alarms.xml', 'r', encoding='utf-8') as fp:
            content = fp.read()
            bs_alarms = BS(content, 'lxml-xml')

        bs_ongoing = bs_alarms.find('ongoing')

        if bs_ongoing is not None:
            i = len(bs_ongoing.find_all('alarm'))

    except FileNotFoundError:
        pass

    if tab == 'map':
        fig = go.Figure(data=go.Scattermapbox(lat=LIST_LAT_STA, lon=LIST_LON_STA,
                                              text=LIST_NAME_STA, mode='markers',
                                              hovertemplate='<b>Sta:</b> %{text}<br>' +
                                                            '<b>Pos:</b> (%{lat}, %{lon})<extra></extra>',
                                              marker=dict(size=12, color='rgba(17, 119, 51, 0.6)')))
        fig.update_layout(height=450, margin={"r": 0, "t": 0, "l": 0, "b": 0},
                          mapbox=dict(zoom=ZOOM_MAP, style='stamen-terrain', bearing=0,
                                      center=go.layout.mapbox.Center(lat=LAT_MAP, lon=LON_MAP), pitch=0))

        return html.Div([
            dcc.Graph(figure=fig, config={'displaylogo': False}),
            html.Div(id='number-alarms', children=i, hidden=True)
        ])
    elif tab == 'soh':
        states_xat = []
        states_xat_table = []
        states_soh = []
        states_soh_table = []
        try:
            with open(f'log/{type_connection}/states_xat.xml', 'r', encoding='utf-8') as fp:
                content = fp.read()
                bs_states_xat = BS(content, 'lxml-xml')
            bs_station = bs_states_xat.find('station', {'name': sta})
            if bs_station is not None:
                for state in bs_station.find_all('state'):
                    state_dt = state.get('datetime')
                    state_datetime = state_dt[1:5] + '-' + state_dt[5:7] + '-' + \
                                     state_dt[7:9] + ' ' + state_dt[10:12] + ':' + \
                                     state_dt[12:14] + ':' + state_dt[14:]
                    states_xat_table.append(html.Tr(
                        [html.Td(state_datetime),
                         html.Td(state.get('name')),
                         html.Td(state.get('value'))
                         ]
                    ))

                table_body = [html.Tbody(states_xat_table)]

                states_xat = dbc.Table(table_body,
                                       bordered=True,
                                       dark=True,
                                       hover=True,
                                       responsive=True,
                                       striped=True
                                       )
        except FileNotFoundError:
            print(f'states_xat.xml file not found in log/{type_connection}')

        try:
            with open(f'log/{type_connection}/states_soh.xml', 'r', encoding='utf-8') as fp:
                content = fp.read()
                bs_states_soh = BS(content, 'lxml-xml')
            bs_station = bs_states_soh.find('station', {'name': sta})
            if bs_station is not None:
                for state in bs_station.find_all('state'):
                    state_dt = state.get('datetime')
                    state_datetime = state_dt[1:5] + '-' + state_dt[5:7] + '-' + \
                                     state_dt[7:9] + ' ' + state_dt[10:12] + ':' + \
                                     state_dt[12:14] + ':' + state_dt[14:]
                    states_soh_table.append(html.Tr(
                        [html.Td(state_datetime),
                         html.Td(state.get('name')),
                         html.Td(state.get('value'))
                         ]
                    ))

                table_body = [html.Tbody(states_soh_table)]

                states_soh = dbc.Table(table_body,
                                       bordered=True,
                                       dark=True,
                                       hover=True,
                                       responsive=True,
                                       striped=True
                                       )
        except FileNotFoundError:
            print(f'states_soh.xml file not found in log/{type_connection}')

        return [html.Div(id='tabs-content-inline', children=[states_xat, states_soh]),
                html.Div(id='number-alarms', children=i, hidden=True)]

    elif tab == 'alarms_in_progress':
        nc_alarms_list = []
        i = 0
        try:
            with open(f'log/{type_connection}/alarms.xml', 'r', encoding='utf-8') as fp:
                content = fp.read()
                bs_alarms = BS(content, 'lxml-xml')

            bs_ongoing = bs_alarms.find('ongoing')

            # display all the ongoing alarms
            nc_alarms_inside = []

            if bs_ongoing is not None:
                for alarm in bs_ongoing.find_all('alarm'):
                    i = i + 1
                    alarm_station = alarm.get('station')
                    alarm_state = alarm.get('state')
                    alarm_detail = alarm.get('detail')
                    alarm_id = alarm.get('id')

                    alarm_problem = int(alarm.get('problem'))
                    if alarm_problem == 1:
                        text_badge = "Warning"
                        color = "warning"
                    else:
                        text_badge = "Critic"
                        color = "danger"

                    alarm_dt = alarm.get('datetime')
                    alarm_datetime = alarm_dt[1:5] + '-' + alarm_dt[5:7] + '-' + \
                                     alarm_dt[7:9] + ' ' + alarm_dt[10:12] + ':' + \
                                     alarm_dt[12:14] + ':' + alarm_dt[14:]

                    nc_alarms_inside.append(html.Tr([html.Td(alarm_datetime),
                                                     html.Td(alarm_station),
                                                     html.Td(alarm_state),
                                                     html.Td(alarm_detail),
                                                     html.Td(dbc.Badge(text_badge, color=color, className="mr-1")),
                                                     html.Td([dbc.Button('Complete Alarm?',
                                                                         id={'type': 'btn-alarm',
                                                                             'id_alarm': alarm_id},
                                                                         className="mr-1", n_clicks=0)
                                                              ]),
                                                     ]))

            table_body = [html.Tbody(nc_alarms_inside)]

            nc_alarms_list = dbc.Table(table_body,
                                       bordered=True,
                                       dark=True,
                                       hover=True,
                                       responsive=True,
                                       striped=True
                                       )
        except FileNotFoundError:
            pass

        return [html.Div(id='tabs-content-inline', children=nc_alarms_list),
                html.Div(id='number-alarms', children=i, hidden=True)]
    elif tab == 'alarms_completed':
        c_alarms_list = []
        try:

            with open(f'log/{type_connection}/alarms.xml', 'r', encoding='utf-8') as fp:
                content = fp.read()
                bs_alarms = BS(content, 'lxml-xml')

            bs_completed = bs_alarms.find('completed')
            # display all the ongoing alarms
            c_alarms_inside = []
            if bs_completed is not None:
                for alarm in bs_completed.find_all('alarm'):
                    alarm_station = alarm.get('station')
                    alarm_state = alarm.get('state')
                    alarm_detail = alarm.get('detail')

                    alarm_problem = int(alarm.get('problem'))
                    if alarm_problem == 1:
                        text_badge = "Warning"
                        color = "warning"
                    else:
                        text_badge = "Critic"
                        color = "danger"

                    alarm_dt = alarm.get('datetime')
                    alarm_datetime = alarm_dt[1:5] + '-' + alarm_dt[5:7] + '-' + \
                                     alarm_dt[7:9] + ' ' + alarm_dt[10:12] + ':' + \
                                     alarm_dt[12:14] + ':' + alarm_dt[14:]

                    c_alarms_inside.append(html.Tr([html.Td(alarm_datetime),
                                                    html.Td(alarm_station),
                                                    html.Td(alarm_state),
                                                    html.Td(alarm_detail),
                                                    html.Td(dbc.Badge(text_badge, color=color, className="mr-1"))]))

            table_body = [html.Tbody(c_alarms_inside)]

            c_alarms_list = dbc.Table(table_body,
                                      bordered=True,
                                      dark=True,
                                      hover=True,
                                      responsive=True,
                                      striped=True
                                      )
        except FileNotFoundError:
            pass

        return [html.Div(id='tabs-content-inline', children=c_alarms_list),
                html.Div(id='number-alarms', children=i, hidden=True)]
Example #15
0
def update_figures(derived_virtual_selected_rows):
    # When the table is first rendered, `derived_virtual_data` and
    # `derived_virtual_selected_rows` will be `None`. This is due to an
    # idiosyncracy in Dash (unsupplied properties are always None and Dash
    # calls the dependent callbacks when the component is first rendered).
    # So, if `rows` is `None`, then the component was just rendered
    # and its value will be the same as the component's dataframe.
    # Instead of setting `None` in here, you could also set
    # `derived_virtual_data=df.to_rows('dict')` when you initialize
    # the component.
    if derived_virtual_selected_rows is None:
        derived_virtual_selected_rows = []

    dff = dfSum

    mapbox_access_token = "pk.eyJ1IjoicGxvdGx5bWFwYm94IiwiYSI6ImNqdnBvNDMyaTAxYzkzeW5ubWdpZ2VjbmMifQ.TXcBE-xg9BFdV2ocecc_7g"

    # Generate a list for hover text display
    textList = []
    for area, region in zip(dfs[keyList[0]]['Province/State'],
                            dfs[keyList[0]]['Country/Region']):

        if type(area) is str:
            if region == "Hong Kong" or region == "Macau" or region == "Taiwan":
                textList.append(area)
            else:
                textList.append(area + ', ' + region)
        else:
            textList.append(region)

    fig2 = go.Figure(
        go.Scattermapbox(
            lat=dfs[keyList[0]]['lat'],
            lon=dfs[keyList[0]]['lon'],
            mode='markers',
            marker=go.scattermapbox.Marker(
                color='#ca261d',
                size=dfs[keyList[0]]['Confirmed'].tolist(),
                sizemin=4,
                sizemode='area',
                sizeref=2. * max(dfs[keyList[0]]['Confirmed'].tolist()) /
                (150.**2),
            ),
            text=textList,
            hovertext=[
                'Comfirmed: {}<br>Recovered: {}<br>Death: {}'.format(i, j, k)
                for i, j, k in zip(dfs[keyList[0]]['Confirmed'], dfs[
                    keyList[0]]['Recovered'], dfs[keyList[0]]['Deaths'])
            ],
            hovertemplate="<b>%{text}</b><br><br>" + "%{hovertext}<br>" +
            "<extra></extra>"))
    fig2.update_layout(
        plot_bgcolor='#151920',
        paper_bgcolor='#cbd2d3',
        margin=go.layout.Margin(l=10, r=10, b=10, t=0, pad=40),
        hovermode='closest',
        transition={'duration': 1000},
        mapbox=go.layout.Mapbox(
            accesstoken=mapbox_access_token,
            style="light",
            # The direction you're facing, measured clockwise as an angle from true north on a compass
            bearing=0,
            center=go.layout.mapbox.Center(
                lat=3.684188 if len(derived_virtual_selected_rows) == 0 else
                dff['lat'][derived_virtual_selected_rows[0]],
                lon=148.374024 if len(derived_virtual_selected_rows) == 0 else
                dff['lon'][derived_virtual_selected_rows[0]]),
            pitch=0,
            zoom=1.2 if len(derived_virtual_selected_rows) == 0 else 4))

    return fig2
Example #16
0
def update_figures(row_ids, selected_row_ids):
    # When the table is first rendered, `derived_virtual_data` and
    # `derived_virtual_selected_rows` will be `None`. This is due to an
    # idiosyncracy in Dash (unsupplied properties are always None and Dash
    # calls the dependent callbacks when the component is first rendered).
    # So, if `rows` is `None`, then the component was just rendered
    # and its value will be the same as the component's dataframe.
    # Instead of setting `None` in here, you could also set
    # `derived_virtual_data=df.to_rows('dict')` when you initialize
    # the component.

    if row_ids is None:
        row_ids = []

    dff = dfSum

    mapbox_access_token = "pk.eyJ1IjoicGxvdGx5bWFwYm94IiwiYSI6ImNqdnBvNDMyaTAxYzkzeW5ubWdpZ2VjbmMifQ.TXcBE-xg9BFdV2ocecc_7g"

    # Generate a list for hover text display
    textList = []
    for area, region in zip(dfs[keyList[0]]['Province/State'],
                            dfs[keyList[0]]['Country/Region']):

        if type(area) is str:
            if region == "Hong Kong" or region == "Macau" or region == "Taiwan":
                textList.append(area)
            else:
                textList.append(area + ', ' + region)
        else:
            textList.append(region)

    # Generate a list for color gradient display
    colorList = []

    for comfirmed, recovered, deaths in zip(dfs[keyList[0]]['Confirmed'],
                                            dfs[keyList[0]]['Recovered'],
                                            dfs[keyList[0]]['Deaths']):
        remaining = recovered / (comfirmed - deaths)
        colorList.append(remaining)

    fig2 = go.Figure(
        go.Scattermapbox(
            lat=dfs[keyList[0]]['lat'],
            lon=dfs[keyList[0]]['lon'],
            mode='markers',
            marker=go.scattermapbox.Marker(
                color=['#d7191c' if i < 1 else '#1a9622' for i in colorList],
                size=[i**(1 / 3) for i in dfs[keyList[0]]['Confirmed']],
                sizemin=1,
                sizemode='area',
                sizeref=2. *
                max([math.sqrt(i)
                     for i in dfs[keyList[0]]['Confirmed']]) / (100.**2),
            ),
            text=textList,
            hovertext=[
                'Comfirmed: {}<br>Recovered: {}<br>Death: {}'.format(i, j, k)
                for i, j, k in zip(dfs[keyList[0]]['Confirmed'], dfs[
                    keyList[0]]['Recovered'], dfs[keyList[0]]['Deaths'])
            ],
            hovertemplate="<b>%{text}</b><br><br>" + "%{hovertext}<br>" +
            "<extra></extra>"))
    fig2.update_layout(
        plot_bgcolor='#151920',
        paper_bgcolor='#cbd2d3',
        margin=go.layout.Margin(l=10, r=10, b=10, t=0, pad=40),
        hovermode='closest',
        transition={'duration': 50},
        annotations=[
            dict(
                x=.5,
                y=-.01,
                align='center',
                showarrow=False,
                text=
                "Points are placed based on data geolocation levels.<br><b>Province/State level<b> - China, Australia, United States, and Canada; <b>Country level<b> - other countries.",
                xref="paper",
                yref="paper",
                font=dict(size=10, color='#292929'),
            )
        ],
        mapbox=go.layout.Mapbox(
            accesstoken=mapbox_access_token,
            style="light",
            # The direction you're facing, measured clockwise as an angle from true north on a compass
            bearing=0,
            center=go.layout.mapbox.Center(
                lat=14.056159
                if len(row_ids) == 0 else dff.loc[selected_row_ids[0]].lat,
                lon=22.920039
                if len(row_ids) == 0 else dff.loc[selected_row_ids[0]].lon),
            pitch=0,
            zoom=1.03 if len(row_ids) == 0 else 4))

    return fig2
Example #17
0
def plot_movement(df, selected_numbers):
    data = []
    colors = [
        '#636EFA', '#EF553B', '#00CC96', '#AB63FA', '#FFA15A', '#19D3F3',
        '#FF6692', '#B6E880', '#FF97FF', '#FECB52'
    ]
    color_no = 0
    df = pd.merge(df, towers[['lat', 'lon', 'TowerID']], on='TowerID')
    for number in selected_numbers:

        df['Date'] = pd.to_datetime(df['Date'], format='%d-%m-%Y')
        #df=df[df['Date'].isin(pd.date_range('2020/06/05','2020/06/06'))].sort_values(['Date','Time']).reset_index()

        filtered_df = df[df['Caller'] == number].sort_values(['Date', 'Time'
                                                              ]).reset_index()
        all_lat = []
        all_lon = []
        locs = []
        duration_hover = []
        duration_output = []

        l1 = filtered_df['Date'].dt.date.apply(
            str) + ' ' + filtered_df['Time'].apply(str)
        for i in range(len(l1)):
            l1[i] = pd.to_datetime(l1[i], format='%Y-%m-%d %H:%M:%S')

        for i in range(len(l1) - 1):
            x = l1[i + 1] - l1[i]
            duration_hover.append(x)

        dura_op = []  # Will hold str(transitduration) to be hovered per edge
        for i in range(len(duration_output)):
            dura_op.append(str(duration_output[i]))

        for (index, row) in filtered_df.iterrows():
            locs.append([row['lat'], row['lon']])

        for i in range(len(locs) - 1):
            all_lat, all_lon, duration_output = addEdgemap(
                locs[i], locs[i + 1], duration_hover[i], all_lat, all_lon,
                duration_output, 0.7, "end", 0.009, 30, 10)
            data.append(
                go.Scattermapbox(
                    lat=all_lat,
                    lon=all_lon,
                    mode="lines",
                    hovertext=duration_output,
                    marker=go.scattermapbox.Marker(size=17,
                                                   color=colors[color_no],
                                                   opacity=1),
                ))
        color_no += 1
        color_no %= len(colors)
    fig = go.Figure(data,
                    layout={
                        'mapbox_style':
                        'open-street-map',
                        'showlegend':
                        False,
                        'margin':
                        dict(l=0, r=0, t=0, b=0),
                        'mapbox':
                        dict(bearing=0,
                             center=dict(lat=23.2599, lon=77.4126),
                             pitch=0,
                             zoom=10)
                    })
    return fig
Example #18
0
# mapbox_access_token = open(".mapbox_token").read()

df = pd.read_csv(
    'https://raw.githubusercontent.com/plotly/datasets/master/Nuclear%20Waste%20Sites%20on%20American%20Campuses.csv'
)
site_lat = df.lat
site_lon = df.lon
locations_name = df.text

fig = go.Figure()

fig.add_trace(
    go.Scattermapbox(lat=site_lat,
                     lon=site_lon,
                     mode='markers',
                     marker=go.scattermapbox.Marker(size=17,
                                                    color='rgb(255, 0, 0)',
                                                    opacity=0.7),
                     text=locations_name,
                     hoverinfo='text'))

fig.add_trace(
    go.Scattermapbox(lat=site_lat,
                     lon=site_lon,
                     mode='markers',
                     marker=go.scattermapbox.Marker(size=8,
                                                    color='rgb(242, 177, 172)',
                                                    opacity=0.7),
                     hoverinfo='none'))

fig.update_layout(
    title='Nuclear Waste Sites on Campus',
Example #19
0
years = [
    2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2018, 2019, 2020
]

maps = go.Figure()

access = (
    "pk.eyJ1Ijoiam5kaXRpZmVpIiwiYSI6ImNrbHVwN2o4NDA5NmgybnBsNzI3Z3c1dWYifQ.971IMEJSB-BBVl575_HH3w"
)

maps.add_trace(
    go.Scattermapbox(lat=teamsStats['lat'],
                     lon=teamsStats['lon'],
                     mode='markers',
                     hovertext=teamsStats['short'],
                     hoverinfo="text",
                     marker=go.scattermapbox.Marker(size=20,
                                                    color='#e83e8c',
                                                    opacity=0.7)))

maps.update_layout(autosize=True,
                   hovermode='closest',
                   showlegend=False,
                   mapbox=dict(accesstoken=access,
                               bearing=0,
                               center=dict(lat=38, lon=-94),
                               pitch=0,
                               zoom=3,
                               style='light'),
                   mapbox_style="light",
                   margin=dict(
Example #20
0
mapbox_style = "mapbox://styles/neeharikak/ck3yt0g624vwr1clm0itq8t5r"

listvolcanos = []
lats = []
lons = []
for obj in volc.find():
    listvolcanos.append(db["volcanos"].find().sort([("PEI", -1)]))
    lats.append(obj["latitude"])
    lons.append(obj["longitude"])
fig = go.Figure()

fig.add_trace(
    go.Scattermapbox(lat=lats,
                     lon=lons,
                     mode="markers",
                     marker={
                         "size": [30, 20, 10],
                         "color": ["Red", "Orange", "Yellow"]
                     }))

fig.update_layout(autosize=True,
                  hovermode='closest',
                  mapbox=go.layout.Mapbox(accesstoken=token,
                                          bearing=0,
                                          style=mapbox_style,
                                          center=go.layout.mapbox.Center(
                                              lat=33.930828, lon=-98.484879),
                                          pitch=0,
                                          zoom=3))

fig.show()
Example #21
0
    xWidth=maxLong-minLong
    yZoom=-1.446*math.log(yWidth)+7.2753
    xZoom=-1.415*math.log(yWidth)+8.7068
    #yZoom=CNST_ZOOM
    #xZoom=CNST_ZOOM
    return min(round(yZoom,2),round(xZoom,2))

_MyDb=db.BabyTrackerDB(Params.DB_USER, Params.DB_PASS, Params.DB_SERVER, Params.DB_DATABASE, Params.DB_PORT)
mydfTracks=_MyDb.GetTracks(1)

#mydfTracksA=_MyDb.GetTracks(1,2,datetime.strptime('03/01/2021','%d/%m/%Y'))
#Dibuixem el mapa base amb la posició de l'usuari
if mydfTracks is None:
    fig = go.Figure(go.Scattermapbox(
        mode = "markers+text",
        marker =dict(size=20, color='red'),
        textposition='top right',
        name='Basic')
    )
    fig.update_layout(
    margin ={'l':0,'t':0,'b':0,'r':0},
    height=750,
    mapbox = {
        'accesstoken':MapBoxToken,
        'style': 'stamen-watercolor',
        'zoom': CNST_ZOOM},
    title_text='Cercador de Babys')
else:    
    fig = go.Figure(go.Scattermapbox(
        mode = "markers+text",
        lon =mydfTracks,
Example #22
0
def generate_map():
    json_data = request.get_json(force=True)

    offenders_co_ordinates = json_data[
        'offenders'] if 'offenders' in json_data else {
            'lats': [],
            'lons': []
        }
    citizens_co_ordinates = json_data[
        'citizens'] if 'citizens' in json_data else {
            'lats': [],
            'lons': []
        }
    victims_co_ordinates = json_data['victims'] if 'victims' in json_data else {
        'lats': [],
        'lons': []
    }
    cameras_co_ordinates = json_data['cameras'] if 'cameras' in json_data else {
        'lats': [],
        'lons': []
    }
    campaigns_co_ordinates = json_data[
        'campaigns'] if 'campaigns' in json_data else {
            'lats': [],
            'lons': []
        }
    stations_co_ordinates = json_data[
        'stations'] if 'stations' in json_data else {
            'lats': [],
            'lons': []
        }
    parks_co_ordinates = json_data['parks'] if 'parks' in json_data else {
        'lats': [],
        'lons': []
    }

    whether_night_time = json_data[
        'whether_night_time'] if 'whether_night_time' in json_data else False

    style = 'light'

    if (whether_night_time):
        style = 'dark'

    offenders = len(offenders_co_ordinates['lats'])
    citizens = len(citizens_co_ordinates['lats'])
    victims = len(victims_co_ordinates['lats'])
    cameras = len(cameras_co_ordinates['lats'])
    campaigns = len(campaigns_co_ordinates['lats'])
    stations = len(stations_co_ordinates['lats'])
    parks = len(parks_co_ordinates['lats'])

    mapbox_access_token = open(".mapbox_token").read()

    fig = go.Figure()

    fig.add_trace(
        go.Scattermapbox(
            name="Offenders",
            lat=offenders_co_ordinates['lats'],
            lon=offenders_co_ordinates['lons'],
            mode='markers',
            hoverinfo='text',
            marker=go.scattermapbox.Marker(
                size=size_of_the_markers['offenders'],
                color=colors_of_the_markers['offenders'],
                opacity=0.7),
            text=generate_names("Offender", offenders, 'offender'),
        ))

    fig.add_trace(
        go.Scattermapbox(
            name="Citizens",
            lat=citizens_co_ordinates['lats'],
            lon=citizens_co_ordinates['lons'],
            mode='markers',
            hoverinfo='text',
            marker=go.scattermapbox.Marker(
                size=size_of_the_markers['citizens'],
                color=colors_of_the_markers['citizens'],
                opacity=0.7),
            text=generate_names("Citizen", offenders),
        ))

    fig.add_trace(
        go.Scattermapbox(
            name="Victims",
            lat=victims_co_ordinates['lats'],
            lon=victims_co_ordinates['lons'],
            mode='markers',
            hoverinfo='text',
            marker=go.scattermapbox.Marker(
                size=size_of_the_markers['victims'],
                color=colors_of_the_markers['victims'],
                opacity=0.7),
            text=generate_names("Victim", victims, 'victim'),
        ))

    # Cameras to the map
    fig.add_trace(
        go.Scattermapbox(
            name="Cameras",
            lat=cameras_co_ordinates['lats'],
            lon=cameras_co_ordinates['lons'],
            mode='markers',
            hoverinfo='text',
            marker=go.scattermapbox.Marker(
                size=size_of_the_markers['cameras'],
                color=colors_of_the_markers['cameras'],
                opacity=0.7),
            text=generate_names("Camera", cameras),
        ))

    # Campaigns to the map
    fig.add_trace(
        go.Scattermapbox(
            name="Campaigns",
            lat=campaigns_co_ordinates['lats'],
            lon=campaigns_co_ordinates['lons'],
            mode='markers',
            hoverinfo='text',
            marker=go.scattermapbox.Marker(
                size=size_of_the_markers['campaigns'],
                color=colors_of_the_markers['campaigns'],
                opacity=0.7),
            text=generate_names("Campaign", campaigns),
        ))

    # Stations to the map
    fig.add_trace(
        go.Scattermapbox(
            name="Stations",
            lat=stations_co_ordinates['lats'],
            lon=stations_co_ordinates['lons'],
            mode='markers',
            hoverinfo='text',
            marker=go.scattermapbox.Marker(
                size=size_of_the_markers['station'],
                color=colors_of_the_markers['station'],
                opacity=0.7),
            text=generate_names("Station", stations),
        ))

    # Parks to the map
    fig.add_trace(
        go.Scattermapbox(
            name="Parks",
            lat=parks_co_ordinates['lats'],
            lon=parks_co_ordinates['lons'],
            mode='markers',
            hoverinfo='text',
            marker=go.scattermapbox.Marker(size=size_of_the_markers['park'],
                                           color=colors_of_the_markers['park'],
                                           opacity=0.7),
            text=generate_names("Park", parks),
        ))

    fig.update_layout(
        title="Westminster Crime Simulator",
        autosize=True,
        hovermode='closest',
        showlegend=True,
        mapbox=go.layout.Mapbox(accesstoken=mapbox_access_token,
                                bearing=0,
                                center=go.layout.mapbox.Center(lat=lat,
                                                               lon=lon),
                                pitch=0,
                                zoom=11.5,
                                style=style),
    )

    fig.write_html('templates/map.html')
    return {'status': True, 'message': "Successfully created Map"}
Example #23
0
                obj["TotalFatalInjuries"]) >= 100:
            Lats_3.append(obj["Latitude"])
            Lons_3.append(obj["Longitude"])
        else:
            Lats_4.append(obj["Latitude"])
            Lons_4.append(obj["Longitude"])
    else:
        Lats_4.append(obj["Latitude"])
        Lons_4.append(obj["Longitude"])

L4 = [
    go.Scattermapbox(lat=Lats_1,
                     lon=Lons_1,
                     mode='markers',
                     marker=dict(
                         size=20,
                         color='red',
                         opacity=1,
                     ),
                     name="Greater than 300")
]

L3 = [
    go.Scattermapbox(lat=Lats_2,
                     lon=Lons_2,
                     mode='markers',
                     marker=dict(
                         size=15,
                         color='orange',
                         opacity=1,
                     ),
Example #24
0
def run_simulation():

    json_data = request.get_json(force=True)

    max_effective_distance['campaigns'] = int(
        json_data['campaigns_effective_distance']
    ) if 'campaigns_effective_distance' in json_data else max_effective_distance[
        'cameras']
    max_effective_distance['cameras'] = int(
        json_data['cameras_effective_distance']
    ) if 'cameras_effective_distance' in json_data else max_effective_distance[
        'campaigns']

    whether_night_time = json_data[
        'whether_night_time'] if 'whether_night_time' in json_data else False

    day = json_data['day']

    print("day: ", day)

    style = 'light'

    if (whether_night_time):
        max_effective_distance['campaigns'] = max_effective_distance[
            'campaigns'] * night_effectiveness_reduction_factor
        max_effective_distance['cameras'] = max_effective_distance[
            'cameras'] * night_effectiveness_reduction_factor
        style = 'dark'
    print("type", type(max_effective_distance['cameras']))

    sim.env.setCameraEffective(max_effective_distance['cameras'])
    sim.env.setCampaignEffective(max_effective_distance['campaigns'])

    happened_attacks, attackpositions = sim.runStep()
    mapbox_access_token = open(".mapbox_token").read()

    attackPostion['lat'] = attackPostion['lat'] + happened_attacks['lats']
    attackPostion['lon'] = attackPostion['lon'] + happened_attacks['lons']

    fig = go.Figure()

    fig.add_trace(
        go.Scattermapbox(
            lat=happened_attacks['lats'],
            lon=happened_attacks['lons'],
            mode='markers',
            hoverinfo='text',
            marker=go.scattermapbox.Marker(
                size=size_of_the_markers['offenders'],
                color=colors_of_the_markers['offenders'],
                opacity=0.7),
            text=happened_attacks['texts'],
        ))

    fig.update_layout(
        title="Westminster Crime Simulator",
        autosize=True,
        hovermode='closest',
        showlegend=False,
        mapbox=go.layout.Mapbox(accesstoken=mapbox_access_token,
                                bearing=0,
                                center=go.layout.mapbox.Center(lat=lat,
                                                               lon=lon),
                                pitch=0,
                                zoom=11.5,
                                style=style),
    )
    print("day: ", day)
    fig.write_html('templates/attacks-day-' + str(day) + '.html')
    return {
        'status': True,
        'message': "Successfully created Attack",
        'attacks': attackpositions,
    }
     marker_line_width=5,
     marker_line_color="rgb(0,0,0)",
     showscale=False),
 go.Choroplethmapbox(
     geojson=choropleth_bg.set_index('GEOID').__geo_interface__,
     locations=choropleth_bg.GEOID,
     z=choropleth_bg.over_60,
     text=choropleth_bg.NAMELSAD,
     hoverinfo="text+z",
     colorscale="Viridis",
     marker_opacity=0.3,
     marker_line_width=2,
     marker_line_color="#C6C6C6"),
 go.Scattermapbox(lat=sampled_bgs.Sampled_Point_Latitude,
                  lon=sampled_bgs.Sampled_Point_Longitude,
                  mode='markers',
                  name='Patient Location',
                  marker=go.scattermapbox.Marker(color='rgb(0,0,0)')),
 go.Scattermapbox(lat=comprehensives.Latitude,
                  lon=comprehensives.Longitude,
                  name='Comprehensive',
                  text=comprehensives.OrganizationName,
                  hoverinfo='text',
                  mode='markers',
                  marker=go.scattermapbox.Marker(size=15,
                                                 color='rgb(255,0,0)')),
 go.Scattermapbox(lat=primaries.Latitude,
                  lon=primaries.Longitude,
                  text=primaries.OrganizationName,
                  hoverinfo='text',
                  name='Primary',
            orangelat200.append(obj["Latitude"])
            orangelon200.append(obj["Longitude"])
        elif (int(obj["TotalFatalInjuries"]) > 100):
            yellowlat100.append(obj["Latitude"])
            yellowlon100.append(obj["Longitude"])
        else:
            bluelat.append(obj["Latitude"])
            bluelon.append(obj["Longitude"])

fig = go.Figure()

fig.add_trace(
    go.Scattermapbox(lat=redlat300,
                     lon=redlon300,
                     mode="markers",
                     marker={
                         "size": 10,
                         "color": "red"
                     }))

fig.add_trace(
    go.Scattermapbox(lat=orangelat200,
                     lon=orangelon200,
                     mode="markers",
                     marker={
                         "size": 10,
                         "color": "orange"
                     }))

fig.add_trace(
    go.Scattermapbox(lat=yellowlat100,
Example #27
0
def plot_path(lat, long, origin_point, destination_point):
    """
    Given a list of latitudes and longitudes, origin 
    and destination point, plots a path on a map
    
    Parameters
    ----------
    lat, long: list of latitudes and longitudes
    origin_point, destination_point: co-ordinates of origin
    and destination
    Returns
    -------
    Nothing. Only shows the map.
    """
    # adding the lines joining the nodes
    fig = go.Figure(
        go.Scattermapbox(name="Path",
                         mode="lines",
                         lon=long,
                         lat=lat,
                         marker={'size': 10},
                         line=dict(width=4.5, color='blue')))
    # adding source marker
    fig.add_trace(
        go.Scattermapbox(name="Source",
                         mode="markers",
                         lon=[origin_point[1]],
                         lat=[origin_point[0]],
                         marker={
                             'size': 12,
                             'color': "red"
                         }))

    # adding destination marker
    fig.add_trace(
        go.Scattermapbox(name="Destination",
                         mode="markers",
                         lon=[destination_point[1]],
                         lat=[destination_point[0]],
                         marker={
                             'size': 12,
                             'color': 'green'
                         }))

    # getting center for plots:
    lat_center = np.mean(lat)
    long_center = np.mean(long)
    # defining the layout using mapbox_style
    fig.update_layout(mapbox_style="stamen-terrain",
                      mapbox_center_lat=30,
                      mapbox_center_lon=-80)
    fig.update_layout(margin={
        "r": 0,
        "t": 0,
        "l": 0,
        "b": 0
    },
                      mapbox={
                          'center': {
                              'lat': lat_center,
                              'lon': long_center
                          },
                          'zoom': 13
                      })
    fig.show()
Example #28
0
mapbox_token = ""

# using pymongo to interface with my mongo database image (mongodb) in docker
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["armageddon"]
uf = db["ufos"]

# iterate through mongodb collection and create a pandas dataframe with the collection data
cursor_ufos = uf.find()
df = pd.DataFrame(list(cursor_ufos))

# sets the geospatial data up
figure = go.Figure(
    go.Scattermapbox(lat=df["latitude"],
                     lon=df["longitude"],
                     text=df["city"],
                     mode="markers",
                     marker=dict(size=4, color="blue", opacity=.8)))

# sets the layout for plotting
figure.update_layout(autosize=True,
                     hovermode="closest",
                     template="plotly_dark",
                     mapbox=go.layout.Mapbox(accesstoken=mapbox_token,
                                             bearing=0,
                                             center=go.layout.mapbox.Center(
                                                 lat=33.9137, lon=-98.4934),
                                             pitch=0,
                                             zoom=5),
                     title="UFO sightings around the world")
Example #29
0
    columns=['totalCasesMS', 'deathsMS', 'country', 'URL', 'notConfirmedByMS'])
df_table = df_table.rename(columns={
    'id': 'Local',
    'totalCases': 'Total',
    'deaths': 'Fatais'
})
trace_size = result.Confirmados * 100

fig = go.Figure(
    go.Scattermapbox(
        lat=result.lat,
        lon=result.lon,
        mode='markers',
        marker=go.scattermapbox.Marker(sizemode='area',
                                       size=result.Confirmados,
                                       sizeref=2),
        text=result.id,
        customdata=result.Mortes,
        hovertemplate="<b>%{text}</b><br><br>" +
        "Confirmados: %{marker.size}<br>" + "Óbitos: %{customdata}<br>" +
        "<extra></extra>",
    ))
fig.update_layout(mapbox=dict(
    center=go.layout.mapbox.Center(lat=-15, lon=-47),
    zoom=3,
))
fig.update_layout(mapbox_style="carto-positron")

fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})

map_layout = html.Div(children=[
Example #30
0
def iplot(n,
          fig=None,
          bus_colors='blue',
          bus_colorscale=None,
          bus_colorbar=None,
          bus_sizes=10,
          bus_text=None,
          line_colors='green',
          line_widths=2,
          line_text=None,
          layouter=None,
          title="",
          size=None,
          branch_components=['Line', 'Link'],
          iplot=True,
          jitter=None,
          mapbox=False,
          mapbox_style='open-street-map',
          mapbox_token="",
          mapbox_parameters={}):
    """
    Plot the network buses and lines interactively using plotly.

    Parameters
    ----------
    fig : dict, default None
        If not None, figure is built upon this fig.
    bus_colors : dict/pandas.Series
        Colors for the buses, defaults to "b"
    bus_colorscale : string
        Name of colorscale if bus_colors are floats, e.g. 'Jet', 'Viridis'
    bus_colorbar : dict
        Plotly colorbar, e.g. {'title' : 'my colorbar'}
    bus_sizes : dict/pandas.Series
        Sizes of bus points, defaults to 10
    bus_text : dict/pandas.Series
        Text for each bus, defaults to bus names
    line_colors : dict/pandas.Series
        Colors for the lines, defaults to "g" for Lines and "cyan" for
        Links. Colors for branches other than Lines can be
        specified using a pandas Series with a MultiIndex.
    line_widths : dict/pandas.Series
        Widths of lines, defaults to 2. Widths for branches other
        than Lines can be specified using a pandas Series with a
        MultiIndex.
    line_text : dict/pandas.Series
        Text for lines, defaults to line names. Text for branches other
        than Lines can be specified using a pandas Series with a
        MultiIndex.
    layouter : networkx.drawing.layout function, default None
        Layouting function from `networkx <https://networkx.github.io/>`_ which
        overrules coordinates given in ``n.buses[['x','y']]``. See
        `list <https://networkx.github.io/documentation/stable/reference/drawing.html#module-networkx.drawing.layout>`_
        of available options.
    title : string
        Graph title
    size : None|tuple
        Tuple specifying width and height of figure; e.g. (width, heigh).
    branch_components : list of str
        Branch components to be plotted, defaults to Line and Link.
    iplot : bool, default True
        Automatically do an interactive plot of the figure.
    jitter : None|float
        Amount of random noise to add to bus positions to distinguish
        overlapping buses
    mapbox : bool, default False
        Switch to use Mapbox.
    mapbox_style : str, default 'open-street-map'
        Define the mapbox layout style of the interactive plot. If this is set
        to a mapbox layout, the argument ``mapbox_token`` must be a valid Mapbox
        API access token.

        Valid open layouts are:
            open-street-map, white-bg, carto-positron, carto-darkmatter,
            stamen-terrain, stamen-toner, stamen-watercolor

        Valid mapbox layouts are:
            basic, streets, outdoors, light, dark, satellite, satellite-streets

    mapbox_token : string
        Mapbox API access token. Obtain from https://www.mapbox.com.
        Can also be included in mapbox_parameters as `accesstoken=mapbox_token`.
    mapbox_parameters : dict
        Configuration parameters of the Mapbox layout.
        E.g. {"bearing": 5, "pitch": 10, "zoom": 1, "style": 'dark'}.


    Returns
    -------
    fig: dictionary for plotly figure
    """

    defaults_for_branches = {
        'Link': dict(color="cyan", width=2),
        'Line': dict(color="blue", width=2),
        'Transformer': dict(color='green', width=2)
    }

    if fig is None:
        fig = dict(data=[], layout={})

    if bus_text is None:
        bus_text = 'Bus ' + n.buses.index

    x, y = _get_coordinates(n, layouter=layouter)

    if jitter is not None:
        x = x + np.random.uniform(low=-jitter, high=jitter, size=len(x))
        y = y + np.random.uniform(low=-jitter, high=jitter, size=len(y))

    bus_trace = dict(
        x=x,
        y=y,
        text=bus_text,
        type="scatter",
        mode="markers",
        hoverinfo="text",
        marker=dict(color=bus_colors, size=bus_sizes),
    )

    if bus_colorscale is not None:
        bus_trace['marker']['colorscale'] = bus_colorscale

    if bus_colorbar is not None:
        bus_trace['marker']['colorbar'] = bus_colorbar

    def as_branch_series(ser):
        if isinstance(ser, dict) and set(ser).issubset(branch_components):
            return pd.Series(ser)
        elif isinstance(ser, pd.Series):
            if isinstance(ser.index, pd.MultiIndex):
                return ser
            index = ser.index
            ser = ser.values
        else:
            index = n.lines.index
        return pd.Series(ser,
                         index=pd.MultiIndex(levels=(["Line"], index),
                                             labels=(np.zeros(len(index)),
                                                     np.arange(len(index)))))

    line_colors = as_branch_series(line_colors)
    line_widths = as_branch_series(line_widths)

    if line_text is not None:
        line_text = as_branch_series(line_text)

    shapes = []

    shape_traces = []

    for c in n.iterate_components(branch_components):
        l_defaults = defaults_for_branches[c.name]
        l_widths = line_widths.get(c.name, l_defaults['width'])
        l_colors = line_colors.get(c.name, l_defaults['color'])

        if line_text is None:
            l_text = c.name + ' ' + c.df.index
        else:
            l_text = line_text.get(c.name)

        if isinstance(l_colors, pd.Series):
            if issubclass(l_colors.dtype.type, np.number):
                l_colors = None
            else:
                l_colors.fillna(l_defaults['color'], inplace=True)

        x0 = c.df.bus0.map(x)
        x1 = c.df.bus1.map(x)

        y0 = c.df.bus0.map(y)
        y1 = c.df.bus1.map(y)

        for line in c.df.index:
            color = l_colors if isinstance(l_colors,
                                           string_types) else l_colors[line]
            width = l_widths if isinstance(l_widths,
                                           (int, float)) else l_widths[line]

            shapes.append(
                dict(type='line',
                     x0=x0[line],
                     y0=y0[line],
                     x1=x1[line],
                     y1=y1[line],
                     opacity=0.7,
                     line=dict(color=color, width=width)))

        shape_traces.append(
            dict(x=0.5 * (x0 + x1),
                 y=0.5 * (y0 + y1),
                 text=l_text,
                 type="scatter",
                 mode="markers",
                 hoverinfo="text",
                 marker=dict(opacity=0.)))

    if mapbox:
        shape_traces_latlon = []
        for st in shape_traces:
            st['lon'] = st.pop('x')
            st['lat'] = st.pop('y')
            shape_traces_latlon.append(go.Scattermapbox(st))
        shape_traces = shape_traces_latlon

        shapes_mapbox = []
        for s in shapes:
            s['lon'] = [s.pop('x0'), s.pop('x1')]
            s['lat'] = [s.pop('y0'), s.pop('y1')]
            shapes_mapbox.append(go.Scattermapbox(s, mode='lines'))
        shapes = shapes_mapbox

        bus_trace['lon'] = bus_trace.pop('x')
        bus_trace['lat'] = bus_trace.pop('y')
        bus_trace = go.Scattermapbox(bus_trace)

        fig['data'].extend(shapes + shape_traces + [bus_trace])
    else:
        fig['data'].extend([bus_trace] + shape_traces)

    fig['layout'].update(
        dict(title=title, hovermode='closest', showlegend=False))

    if size is not None:
        assert len(
            size) == 2, "Parameter size must specify a tuple (width, height)."
        fig['layout'].update(dict(width=size[0], height=size[1]))

    if mapbox:
        if mapbox_token != "":
            mapbox_parameters['accesstoken'] = mapbox_token

        mapbox_parameters.setdefault('style', mapbox_style)

        if mapbox_parameters['style'] in _token_required_mb_styles:
            assert 'accesstoken' in mapbox_parameters.keys(), (
                "Using Mapbox "
                "layout styles requires a valid access token from https://www.mapbox.com/, "
                f"style which do not require a token are:\n{', '.join(_open__mb_styles)}."
            )

        if 'center' not in mapbox_parameters.keys():
            lon = (n.buses.x.min() + n.buses.x.max()) / 2
            lat = (n.buses.y.min() + n.buses.y.max()) / 2
            mapbox_parameters['center'] = dict(lat=lat, lon=lon)

        if 'zoom' not in mapbox_parameters.keys():
            mapbox_parameters['zoom'] = 2

        fig['layout']['mapbox'] = mapbox_parameters
    else:
        fig['layout']['shapes'] = shapes

    if iplot:
        if not pltly_present:
            logger.warning(
                "Plotly is not present, so interactive plotting won't work.")
        else:
            pltly.iplot(fig)

    return fig