Пример #1
0
    lst.append(my_lst)

# List of countries
cty = []
for i in range(32):
    cty.append(data.country[i])
# print(cty)
# Generating Radar plot using plotly on the following categories
categories = [
    'Young Population', 'Health', 'Median Income', 'Hours worked', 'Avg temp',
    'Low savings', 'Crime', 'Life Satisfaction'
]
fig = go.Figure()
for i in range(32):
    fig.add_trace(
        go.Scatterpolar(r=lst[i], theta=categories, fill='none', name=cty[i]))

fig.update_layout(polar=dict(radialaxis=dict(visible=True, range=[0, 100])),
                  showlegend=True)
fig.show()

# Code for generating Geographically colored map of europe based on given column values
trace = [
    go.Choropleth(
        colorscale='YlOrRd',
        locationmode='country names',
        locations=data['country'],
        text=data['country'],
        z=data['avg_temp'],
    )
]
Пример #2
0
def gen_wind_direction(interval):
    """
    Generate the wind direction graph.

    :params interval: update the graph based on an interval
    """

    total_time = get_current_time()
    df = get_wind_data_by_id(total_time)
    val = df["Speed"].iloc[-1]
    direction = [0, (df["Direction"][0] - 20), (df["Direction"][0] + 20), 0]

    traces_scatterpolar = [
        {
            "r": [0, val, val, 0],
            "fillcolor": "#084E8A"
        },
        {
            "r": [0, val * 0.65, val * 0.65, 0],
            "fillcolor": "#B4E1FA"
        },
        {
            "r": [0, val * 0.3, val * 0.3, 0],
            "fillcolor": "#EBF5FA"
        },
    ]

    data = [
        go.Scatterpolar(
            r=traces["r"],
            theta=direction,
            mode="lines",
            fill="toself",
            fillcolor=traces["fillcolor"],
            line={
                "color": "rgba(32, 32, 32, .6)",
                "width": 1
            },
        ) for traces in traces_scatterpolar
    ]

    layout = go.Layout(
        height=350,
        plot_bgcolor=app_color["graph_bg"],
        paper_bgcolor=app_color["graph_bg"],
        font={"color": "#fff"},
        autosize=False,
        polar={
            "bgcolor": app_color["graph_line"],
            "radialaxis": {
                "range": [0, 45],
                "angle": 45,
                "dtick": 10
            },
            "angularaxis": {
                "showline": False,
                "tickcolor": "white"
            },
        },
        showlegend=False,
    )

    return go.Figure(data=data, layout=layout)
Пример #3
0
                      y='Name',
                      size='Skill Moves',
                      color='Penalties')


pl_skill = fifa.groupby(by='Position')['Dribbling', 'Curve', 'FKAccuracy',
                                       'LongPassing', 'BallControl',
                                       'Acceleration',
                                       'SprintSpeed'].mean().reset_index()

trace_a = go.Scatterpolar(theta=[
    'Dribbling', 'Curve', 'FKAccuracy', 'LongPassing', 'BallControl',
    'Acceleration', 'SprintSpeed'
],
                          r=pl_skill[pl_skill['Position'] == 'GK'][[
                              'Dribbling', 'Curve', 'FKAccuracy',
                              'LongPassing', 'BallControl', 'Acceleration',
                              'SprintSpeed'
                          ]].values[0],
                          fill='toself',
                          name='Goal Keepers')
trace_b = go.Scatterpolar(theta=[
    'Dribbling', 'Curve', 'FKAccuracy', 'LongPassing', 'BallControl',
    'Acceleration', 'SprintSpeed'
],
                          r=pl_skill[pl_skill['Position'] == 'F'][[
                              'Dribbling', 'Curve', 'FKAccuracy',
                              'LongPassing', 'BallControl', 'Acceleration',
                              'SprintSpeed'
                          ]].values[0],
                          fill='toself',
Пример #4
0
c_neg = len(c_neg_tweets) * 100 / len(cali['tweets'])
c_neu = len(c_neu_tweets) * 100 / len(cali['tweets'])

colors = {'background': '#111111'}

pizza = [
    'Dominos', 'PizzaHut', 'PapaJohns', 'LittleCaesars',
    'CaliforniaPizzaKitchen'
]

##################################################Radar Chart - user sentiments####################################################

fig = go.Figure()
fig.add_trace(
    go.Scatterpolar(r=[dom_neg, ph_neg, pj_neg, lt_neg, c_neg],
                    theta=pizza,
                    fill='toself',
                    name='Negative'))

fig.add_trace(
    go.Scatterpolar(r=[dom_neu, ph_neu, pj_neu, lt_neu, c_neu],
                    theta=pizza,
                    fill='toself',
                    name='Neutral'))

fig.add_trace(
    go.Scatterpolar(r=[dom_pos, ph_pos, pj_pos, lt_pos, c_pos],
                    theta=pizza,
                    fill='toself',
                    name='Positive'))

fig.update_layout(title_text="Users' sentiment towards the industry",
f, d_ij, P_ref, cop = parametros_base_wii()
wm = setup_wiimote()

wii_set = set_wii(wm, f, d_ij, P_ref, cop)
Pts = pts_wii(wm, f, d_ij, P_ref, cop, wii_set["fator_escala"],
              wii_set["origem"], wii_set["ang_origem"])

a = np.array(Pts["x"])
b = np.array(Pts["y"])

hip = np.array([0, 5])
ang = np.array([0, Pts["alfa"]])

initial_trace = go.Scatterpolar(r=hip,
                                theta=ang,
                                name='Scatter_polar',
                                mode='markers')

initial_trace_2 = go.Scatter(x=a, y=b, name='Scatter', mode='markers')

app = dash.Dash(__name__)
app.scripts.config.serve_locally = True
app.css.config.serve_locally = True

app.layout = html.Div([
    dcc.Graph(id='live-graph',
              animate=True,
              figure={
                  'data': [initial_trace, initial_trace_2],
                  'layout':
                  go.Layout(autosize=True,
Пример #6
0
        xaxis=dict(),
        yaxis=dict(title='aantal moties',gridcolor='#EEEEEE',zerolinecolor='#EEEEEE',tickformat='d'),
        bargap=0.5,
        barmode='stack',
        plot_bgcolor='#FFFFFF'
    )
)

#propose
propose=pd.DataFrame(propose,columns=['proposer','topic','pnum'])
propose=propose.groupby(['proposer','topic']).sum().reset_index()
propose=propose.pivot(index='proposer',columns='topic',values='pnum').fillna(0)

traces=[]
for p in propose.index:
    traces.append(go.Scatterpolar(r=propose.loc[p], theta=propose.columns, fill='toself', name=p))
fig_pro=go.Figure(
    data=traces,
    layout=go.Layout(
        title=dict(text='Verdeling onderwerpen van moties',x=0.5),
        polar=dict(radialaxis=dict(range=[0,2.1],gridcolor='#C6C6C6',tickformat='d'),
                    angularaxis=dict(gridcolor='#C6C6C6'),bgcolor='#FFFFFF'),
        height=487
))

#pvotes
pvotes=pd.DataFrame(pvotes,columns=['party','topic','attitude','vnum'])
pvotes=pvotes.groupby(['party','topic','attitude'])['vnum'].sum().unstack('party').fillna(0)

fig_PVs={}
for t in topics:
    def buildTrace(self):
        '''
        build the final trace calling the go.xxx plotly method
        this method here is the one performing the real job

        From the initial object created (e.g. p = Plot(plot_type, plot_properties,
        layout_properties)) this methods checks the plot_type and elaborates the
        plot_properties dictionary passed

        Console usage:
        # create the initial object
        p = Plot(plot_type, plot_properties, layout_properties)
        # call the method
        p.buildTrace()

        Returns the final Plot Trace (final Plot object, AKA go.xxx plot type)
        '''

        if self.plot_type == 'scatter':

            self.trace = [
                go.Scatter(
                    x=self.plot_properties['x'],
                    y=self.plot_properties['y'],
                    mode=self.plot_properties['marker'],
                    name=self.plot_properties['name'],
                    ids=self.plot_properties['featureIds'],
                    customdata=self.plot_properties['custom'],
                    text=self.plot_properties['additional_hover_text'],
                    hoverinfo=self.plot_properties['hover_text'],
                    marker=dict(
                        color=self.plot_properties['in_color'],
                        colorscale=self.plot_properties['colorscale_in'],
                        showscale=self.
                        plot_properties['show_colorscale_legend'],
                        reversescale=self.
                        plot_properties['invert_color_scale'],
                        colorbar=dict(len=0.8),
                        size=self.plot_properties['marker_size'],
                        symbol=self.plot_properties['marker_symbol'],
                        line=dict(color=self.plot_properties['out_color'],
                                  width=self.plot_properties['marker_width'])),
                    line=dict(color=self.plot_properties['in_color'],
                              width=self.plot_properties['marker_width'],
                              dash=self.plot_properties['line_dash']),
                    opacity=self.plot_properties['opacity'])
            ]

        elif self.plot_type == 'box':

            # flip the variables according to the box orientation
            if self.plot_properties['box_orientation'] == 'h':
                self.plot_properties['x'], self.plot_properties[
                    'y'] = self.plot_properties['y'], self.plot_properties['x']

            self.trace = [
                go.Box(x=self.plot_properties['x'],
                       y=self.plot_properties['y'],
                       name=self.plot_properties['name'],
                       customdata=self.plot_properties['custom'],
                       boxmean=self.plot_properties['box_stat'],
                       orientation=self.plot_properties['box_orientation'],
                       boxpoints=self.plot_properties['box_outliers'],
                       fillcolor=self.plot_properties['in_color'],
                       line=dict(color=self.plot_properties['out_color'],
                                 width=self.plot_properties['marker_width']),
                       opacity=self.plot_properties['opacity'])
            ]

        elif self.plot_type == 'bar':

            if self.plot_properties['box_orientation'] == 'h':
                self.plot_properties['x'], self.plot_properties[
                    'y'] = self.plot_properties['y'], self.plot_properties['x']

            self.trace = [
                go.Bar(x=self.plot_properties['x'],
                       y=self.plot_properties['y'],
                       name=self.plot_properties['name'],
                       ids=self.plot_properties['featureBox'],
                       customdata=self.plot_properties['custom'],
                       orientation=self.plot_properties['box_orientation'],
                       marker=dict(
                           color=self.plot_properties['in_color'],
                           colorscale=self.plot_properties['colorscale_in'],
                           showscale=self.
                           plot_properties['show_colorscale_legend'],
                           reversescale=self.
                           plot_properties['invert_color_scale'],
                           colorbar=dict(len=0.8),
                           line=dict(
                               color=self.plot_properties['out_color'],
                               width=self.plot_properties['marker_width'])),
                       opacity=self.plot_properties['opacity'])
            ]

        elif self.plot_type == 'histogram':

            self.trace = [
                go.Histogram(
                    x=self.plot_properties['x'],
                    y=self.plot_properties['x'],
                    name=self.plot_properties['name'],
                    orientation=self.plot_properties['box_orientation'],
                    nbinsx=self.plot_properties['bins'],
                    nbinsy=self.plot_properties['bins'],
                    marker=dict(
                        color=self.plot_properties['in_color'],
                        line=dict(color=self.plot_properties['out_color'],
                                  width=self.plot_properties['marker_width'])),
                    histnorm=self.plot_properties['normalization'],
                    opacity=self.plot_properties['opacity'],
                    cumulative=dict(
                        enabled=self.plot_properties['cumulative'],
                        direction=self.plot_properties['invert_hist']))
            ]

        elif self.plot_type == 'pie':

            self.trace = [
                go.Pie(
                    labels=self.plot_properties['x'],
                    values=self.plot_properties['y'],
                    name=self.plot_properties['custom'],
                )
            ]

        elif self.plot_type == '2dhistogram':

            self.trace = [
                go.Histogram2d(x=self.plot_properties['x'],
                               y=self.plot_properties['y'],
                               colorscale=self.plot_properties['color_scale'])
            ]

        elif self.plot_type == 'polar':

            self.trace = [
                go.Scatterpolar(
                    r=self.plot_properties['x'],
                    theta=self.plot_properties['y'],
                    mode=self.plot_properties['marker'],
                    name=self.plot_properties['y_name'],
                    marker=dict(
                        color=self.plot_properties['in_color'],
                        size=self.plot_properties['marker_size'],
                        symbol=self.plot_properties['marker_symbol'],
                        line=dict(color=self.plot_properties['out_color'],
                                  width=self.plot_properties['marker_width'])),
                    line=dict(color=self.plot_properties['in_color'],
                              width=self.plot_properties['marker_width'],
                              dash=self.plot_properties['line_dash']),
                    opacity=self.plot_properties['opacity'],
                )
            ]

        elif self.plot_type == 'ternary':

            # prepare the hover text to display if the additional combobox is empty or not
            # this setting is necessary to overwrite the standard hovering labels
            if self.plot_properties['additional_hover_text'] == []:
                text = [
                    self.plot_properties['x_name'] +
                    ': {}'.format(self.plot_properties['x'][k]) +
                    '<br>{}: {}'.format(self.plot_properties['y_name'],
                                        self.plot_properties['y'][k]) +
                    '<br>{}: {}'.format(self.plot_properties['z_name'],
                                        self.plot_properties['z'][k])
                    for k in range(len(self.plot_properties['x']))
                ]
            else:
                text = [
                    self.plot_properties['x_name'] +
                    ': {}'.format(self.plot_properties['x'][k]) +
                    '<br>{}: {}'.format(self.plot_properties['y_name'],
                                        self.plot_properties['y'][k]) +
                    '<br>{}: {}'.format(self.plot_properties['z_name'],
                                        self.plot_properties['z'][k]) +
                    '<br>{}'.format(
                        self.plot_properties['additional_hover_text'][k])
                    for k in range(len(self.plot_properties['x']))
                ]

            self.trace = [
                go.Scatterternary(
                    a=self.plot_properties['x'],
                    b=self.plot_properties['y'],
                    c=self.plot_properties['z'],
                    name=self.plot_properties['x_name'] + ' + ' +
                    self.plot_properties['y_name'] + ' + ' +
                    self.plot_properties['z_name'],
                    hoverinfo='text',
                    text=text,
                    mode='markers',
                    marker=dict(
                        color=self.plot_properties['in_color'],
                        colorscale=self.plot_properties['colorscale_in'],
                        showscale=self.
                        plot_properties['show_colorscale_legend'],
                        reversescale=self.
                        plot_properties['invert_color_scale'],
                        colorbar=dict(len=0.8),
                        size=self.plot_properties['marker_size'],
                        symbol=self.plot_properties['marker_symbol'],
                        line=dict(color=self.plot_properties['out_color'],
                                  width=self.plot_properties['marker_width'])),
                    opacity=self.plot_properties['opacity'])
            ]

        elif self.plot_type == 'contour':

            self.trace = [
                go.Contour(
                    z=[self.plot_properties['x'], self.plot_properties['y']],
                    contours=dict(
                        coloring=self.plot_properties['cont_type'],
                        showlines=self.plot_properties['show_lines']),
                    colorscale=self.plot_properties['color_scale'],
                    opacity=self.plot_properties['opacity'])
            ]

        elif self.plot_type == 'violin':

            # flip the variables according to the box orientation
            if self.plot_properties['box_orientation'] == 'h':
                self.plot_properties['x'], self.plot_properties[
                    'y'] = self.plot_properties['y'], self.plot_properties['x']

            self.trace = [
                go.Violin(x=self.plot_properties['x'],
                          y=self.plot_properties['y'],
                          name=self.plot_properties['name'],
                          customdata=self.plot_properties['custom'],
                          orientation=self.plot_properties['box_orientation'],
                          points=self.plot_properties['box_outliers'],
                          fillcolor=self.plot_properties['in_color'],
                          line=dict(
                              color=self.plot_properties['out_color'],
                              width=self.plot_properties['marker_width']),
                          opacity=self.plot_properties['opacity'],
                          meanline=dict(
                              visible=self.plot_properties['show_mean_line']),
                          side=self.plot_properties['violin_side'])
            ]

        return self.trace
Пример #8
0
def test_radar_player():
    '''
    This function plots the radar plot for players based on the  selected season and 5 players and 6 attributes
    
    Inputs- 
    season: Selected Season 
    name1-5: Player 1-5
    att1-6: Atrributes 1-6
    
    Output- 
    Radar plot for players
    '''

    # 1.Retrieve the correct .csv File first
    stats = pd.read_csv("2019-20.csv")
    assert isinstance(stats, pd.DataFrame)
    assert not stats is None
    assert ('PTS' and 'AST' and 'REB' and 'STL' and 'BLK' and 'TOV' and 'FGM'
            and 'FGA' and 'FG_PCT' and 'FTM' and 'FTA' and 'FT_PCT' and 'OREB'
            and 'DREB' and 'GP' and 'TEAM' and 'PLAYER') in stats

    # 2.Process Data from  .csv file and only maintain columns you need
    player_average = tdp.test_playerStats()
    assert isinstance(player_average, pd.DataFrame)
    assert not player_average is None
    assert ('PTS' and 'AST' and 'REB' and 'STL' and 'BLK' and 'TOV' and 'FGM'
            and 'FGA' and 'FG%' and 'FTM' and 'FTA' and 'FT%' and 'OREB'
            and 'DREB') in player_average

    names = [
        'James Harden', 'Jayson Tatum', 'Trae Young', 'Anthony Davis',
        'Ben Simmons'
    ]
    atributes = ['PTS', 'AST', 'REB', 'STL', 'BLK', 'TOV']
    assert isinstance(names, list)
    assert len(names) == 5
    assert isinstance(atributes, list)
    assert len(atributes) == 6

    # 3.Set up and extract data to be ploted - each row at a time (for each player)
    labels = np.array(atributes)
    assert isinstance(labels, np.ndarray)
    assert len(labels) == len(atributes)

    player_stats = np.zeros((len(names), len(labels)))
    for i in range(len(names)):
        player_stats[i] = [
            player_average[labels[0]][names[i]],
            player_average[labels[1]][names[i]],
            player_average[labels[2]][names[i]],
            player_average[labels[3]][names[i]],
            player_average[labels[4]][names[i]],
            player_average[labels[5]][names[i]]
        ]

    assert isinstance(player_stats, np.ndarray)
    assert np.shape(player_stats) == (len(names), len(labels))

    # 4.Loop the data around to be able to compatibale with radar plots
    player_stats_mod = np.zeros((len(names), len(labels) + 1))
    for i in range(len(names)):
        player_stats_mod[i] = np.concatenate(
            (player_stats[i], [player_stats[i][0]]))
    labels_mod = np.concatenate((labels, [labels[0]]))

    assert isinstance(player_stats_mod, np.ndarray)
    assert np.shape(player_stats_mod) == (len(names), (len(labels) + 1))

    assert isinstance(labels_mod, np.ndarray)
    assert len(labels_mod) == len(labels) + 1

    # Plot the data
    fig = go.Figure()

    for i in range(len(names)):
        fig.add_trace(
            go.Scatterpolar(r=player_stats_mod[i],
                            theta=labels_mod,
                            name=names[i]))

    fig.update_layout(polar=dict(radialaxis=dict(visible=True, range=[0, 1])),
                      showlegend=True)

    fig.show()

    return
Пример #9
0
             'label': 'Seattle',
             'value': 'Java'
         },
     ],
                  value=['MTL', 'SF'],
                  multi=True)
 ]),
 html.Div([
     html.Div([
         dcc.Graph(id='JavaPageRank',
                   figure={
                       'data': [
                           go.Scatterpolar(r=[8, 3.4, 5],
                                           theta=[
                                               'Github Age',
                                               'Page Rank Score',
                                               'Followers Number'
                                           ],
                                           fill='toself')
                       ],
                       'layout':
                       go.Layout(polar=dict(
                           radialaxis=dict(visible=True, range=[0, 10])),
                                 showlegend=False)
                   })
     ]),
     html.Div([
         html.Iframe(
             src=
             'https://storage.googleapis.com/pics-insight/ironman-cats.png',
             height=500,
Пример #10
0
                    textposition='inside',
                    hole=0.90,
                    domain={
                        "x": [0.02, 0.98],
                        "y": [0.02, 0.98]
                    },
                    direction='clockwise',
                    insidetextfont=dict(size=10),
                    marker=dict(colors=common.smallcolors,
                                line=dict(color='#000000', width=1)))

# Creation of the polar-data (max 6)
polardata = [
    go.Scatterpolar(r=common.rlist[0],
                    theta=common.tlist[0],
                    mode='lines',
                    fill='toself',
                    fillcolor=common.bigcolors[0],
                    line=dict(width=1, color='black')),
    go.Scatterpolar(r=common.rlist[1],
                    theta=common.tlist[1],
                    mode='lines',
                    fill='toself',
                    fillcolor=common.bigcolors[1],
                    line=dict(width=1, color='black')),
    go.Scatterpolar(r=common.rlist[2],
                    theta=common.tlist[2],
                    mode='lines',
                    fill='toself',
                    fillcolor=common.bigcolors[2],
                    line=dict(width=1, color='black')),
    go.Scatterpolar(r=common.rlist[3],
Пример #11
0
def test_radar_team():
    '''
    This function plots the radar plot for teams based on the selected season and 5 teams and 6 attributes
        
    Inputs- 
    season: Selected Season 
    name1-5: Teams 1-5
    att1-6: Atrributes 1-6
    teamA: the team for which you want to predict the win % 
    teamB: the team against which you want to predict the win % 
        
    Output- 
    Radar plot for teams
    '''
    #     season,name1,name2,name3,name4,name5,att1,att2,att3,att4,att5,att6,teamA,teamB

    # 1.Retrieve the correct .csv File first
    stats = pd.read_csv("Team_2019-20.csv")
    assert isinstance(stats, pd.DataFrame)
    assert not stats is None
    assert ('PTS' and 'AST' and 'REB' and 'STL' and 'BLK' and 'TOV' and 'FGM'
            and 'FGA' and 'FG_PCT' and 'FTM' and 'FTA' and 'FT_PCT' and 'OREB'
            and 'DREB' and 'GP' and 'TEAM_NAME' and 'W' and 'W_PCT' and 'L'
            and 'BLKA') in stats

    # 2.Process Data from  .csv file and only maintain columns you need
    team_average = tdp.test_teamStats()
    assert isinstance(team_average, pd.DataFrame)
    assert not team_average is None
    assert ('Win%' and 'PTS' and 'AST' and 'REB' and 'STL' and 'BLK' and 'TOV'
            and 'FGM' and 'FGA' and 'FG%' and 'FTM' and 'FTA' and 'FT%'
            and 'OREB' and 'DREB') in team_average

    names = [
        'Boston Celtics', 'Houston Rockets', 'Atlanta Hawks',
        'Toronto Raptors', 'Los Angeles Lakers'
    ]
    atributes = ['PTS', 'AST', 'REB', 'STL', 'BLK', 'TOV']
    assert isinstance(names, list)
    assert len(names) == 5
    assert isinstance(atributes, list)
    assert len(atributes) == 6

    # 3.Set up and extract data to be ploted - each row at a time (for each player)
    labels = np.array(atributes)
    assert isinstance(labels, np.ndarray)
    assert len(labels) == len(atributes)

    team_stats = np.zeros((len(names), len(labels)))
    for i in range(len(names)):
        team_stats[i] = [
            team_average[labels[0]][names[i]],
            team_average[labels[1]][names[i]],
            team_average[labels[2]][names[i]],
            team_average[labels[3]][names[i]],
            team_average[labels[4]][names[i]],
            team_average[labels[5]][names[i]]
        ]

    assert isinstance(team_stats, np.ndarray)
    assert np.shape(team_stats) == (len(names), len(labels))

    # 4.Loop the data around to be able to compatibale with radar plots
    team_stats_mod = np.zeros((len(names), len(labels) + 1))
    for i in range(len(names)):
        team_stats_mod[i] = np.concatenate((team_stats[i], [team_stats[i][0]]))

    assert isinstance(team_stats_mod, np.ndarray)
    assert np.shape(team_stats_mod) == (len(names), (len(labels) + 1))

    ###########################################
    ###########################################
    ###########################################

    arealist = [twp.test_TrangleArea() for li in team_stats_mod]
    assert isinstance(arealist, list)
    assert len(arealist) == len(team_stats_mod)

    teamID = twp.test_nametolist()
    assert isinstance(teamID, list)
    assert len(arealist) == len(names)

    wincomp = twp.test_teamComp1()
    assert isinstance(wincomp, float)

    print("Team A has a", str(round(wincomp * 100, 2)),
          "% chance to win over Team B")

    # print names + area pair
    TheAreapair = [
        a + ", Area under team radar = " + str(round(b, 3))
        for a, b in zip(names, arealist)
    ]
    assert isinstance(teamID, list)
    assert len(arealist) == len(team_stats_mod)

    ###########################################
    ###########################################
    ###########################################

    labels_mod = np.concatenate((labels, [labels[0]]))
    assert isinstance(labels_mod, np.ndarray)
    assert len(labels_mod) == len(labels) + 1

    # Plot the data
    fig = go.Figure()

    for i in range(len(names)):
        fig.add_trace(
            go.Scatterpolar(r=team_stats_mod[i],
                            theta=labels_mod,
                            name=TheAreapair[i]))

    fig.update_layout(polar=dict(radialaxis=dict(visible=True, range=[0, 1])),
                      showlegend=True)

    fig.show()

    return
Пример #12
0
for i in range(len(data)):
    user_list.append(data[i]['user'])
    temp_list.append(i)
    rank_list.append(float(data[i]['rank']))
'''

#create graph object
app.layout = html.Div([
    dcc.Graph(id='JavaPageRank',
              figure={
                  'data': [
                      go.Scatterpolar(r=[
                          user_github_age, user_pagerank_score,
                          user_followers_number
                      ],
                                      theta=[
                                          'Github Age', 'Page Rank Score',
                                          'Followers Number'
                                      ],
                                      fill='toself')
                  ],
                  'layout':
                  go.Layout(polar=dict(
                      radialaxis=dict(visible=True, range=[0, 100])),
                            showlegend=False)
              })
])

if __name__ == '__main__':
    app.run_server()
Пример #13
0
def parse_contents(contents, filename, date):
    content_type, content_string = contents.split(',')
    decoded = base64.b64decode(content_string)
    try:
        if 'csv' in filename:
            df = pd.read_csv(io.StringIO(decoded.decode('utf-8')))
            later = pd.read_csv(io.StringIO(decoded.decode('utf-8')))
        elif 'xls' in filename:
            df = pd.read_excel(io.BytesIO(decoded))
            later = pd.read_csv(io.StringIO(decoded.decode('utf-8')))
    except Exception as e:
        print(e)
        return html.Div([
            'There was an error processing this file.'
        ])

    df['waste_management'] = 0.0
    for x in ['bags','hazardous','large']:
        condition = df['Activity'].str.match(x) & df['Consumption']>0.0
        df.loc[condition, 'waste_management'] = 1.0
    df2 = carbon_p[['solar powered  water heater', 'gas water heater',
           'electric water heater - peak hours',
           'electric water heater - off peak hours', 'gas', 'natural gas','hybrid','electric - peak hours',
           'electric - off peak hours',
           'Jet Fuel','waste management']]

    df_part1 = df.iloc[:,5:].copy()
    df_part2 = df2
    data_cf = pd.DataFrame(df_part1.values*df_part2.values, columns=df_part1.columns, index=df_part1.index)

    data_complete = pd.concat([df.iloc[:,:5],data_cf], axis=1)
    data_complete['Consumption'] = data_complete['Consumption'].abs()
    data_complete['n_utils'] = data_complete.iloc[:, -11:].astype(bool).sum(axis=1)
    data_complete['sum_cf'] = data_complete.loc[:,'solar_powered__water_heater':'waste_management'].sum(axis = 1)
    data_complete['cf'] = ((data_complete['sum_cf']*data_complete['Consumption'])/data_complete['n_utils'])
    data_complete['cf'].fillna(0, inplace=True)

    new_data = data_complete.groupby('Group').mean()
    list_cf = list(new_data['cf'])

    df_final = pd.DataFrame(columns = ['Group1','Group2','Group3','Group4','Group5','Group6'])
    df_final.loc[0] = list_cf

    group = df_final.copy()
    group.columns = ['heating','bath','kitchen','TV','transportation','waste']
    df_p = pd.DataFrame(index=group.index)
    df_p['waste'] = group['waste']
    df_p['transportation'] = group['transportation']
    df_p['other'] = group['heating'] + group['bath'] + group['kitchen'] + group['TV']

    nana = df_p.iloc[0, :]
    labels = df_p.columns
    values = nana.values
    colors = ['#6B8E23', '#9ACD32','#98FB98']
    trace1 = go.Pie(labels=labels, values=values,
                hoverinfo='label+percent', textinfo='value',
                hole=.3,
                textfont=dict(size=15),
                marker=dict(colors=colors,
                line=dict(color='#000000', width=0.5)))

    big = data.copy()
    big = pd.concat([big, df_final], ignore_index=True)
    scaler = MinMaxScaler()
    big['Group1'] = 1 - scaler.fit_transform(big['Group1'].values.reshape(-1,1))
    big['Group2'] = 1 - scaler.fit_transform(big['Group2'].values.reshape(-1,1))
    big['Group3'] = 1 - scaler.fit_transform(big['Group3'].values.reshape(-1,1))
    big['Group4'] = 1 - scaler.fit_transform(big['Group4'].values.reshape(-1,1))
    big['Group5'] = 1 - scaler.fit_transform(big['Group5'].values.reshape(-1,1))
    big['Group6'] = 1 - scaler.fit_transform(big['Group6'].values.reshape(-1,1))
    import random
    rand = random.randint(1, 1000)
    user_min_max = big.iloc[rand, :]
    mean = big.mean()
    scatter1 = go.Scatterpolar(
        r = user_min_max,
        theta = ['Heating','Bath','Kitchen', 'TV', 'Transportation', 'Waste'],
        fill = 'toself',
        name = 'Current'
    )
    scatter2 = go.Scatterpolar(
        r = mean,
        theta = ['Heating','Bath','Kitchen', 'TV', 'Transportation', 'Waste'],
        fill = 'toself',
        name = 'Change'
    )
    layout = go.Layout(
        polar = dict(
            radialaxis = dict(
            visible = True,
            range = [0, 1]
            )
        )
    )

    temp = df_final.copy()
    temp['summation'] = data.sum(axis=1)
    user_sum = df_comp.iloc[0,:]
    trace2 = go.Histogram(
        x = df_comp['summation'],
        opacity=0.5,
        marker=dict(
            color='#9ACD32'
        ),
        name='Population'
    )
    trace3 = go.Scatter(
        x=[float(user_sum),float(user_sum)],
        y=[0,110],
        text = 'You',
        hoverinfo = 'text',
        mode = 'lines',
        marker=dict(
            color='#6B8E23'
        ),
        name='Where you stand'
    )

    clust = data.copy()
    clust = pd.concat([big, df_final], ignore_index=True)
    #clust.to_csv('./data/first_preprocess.csv')
    clust.columns = ['heating','bath','kitchen','TV','transportation','waste']
    clustering = SpectralClustering(n_clusters=4,
        assign_labels="discretize",
        random_state=0).fit(clust)
    clust['clusters'] = clustering.labels_+1

    id_num = clust.shape[0] - 1
    group_num = clust.loc[id_num]["clusters"]
    t = 50-1;
    dfp = pd.read_csv('./data/fillna_lifequality.csv')
    #dfp = pd.concat([dfp, later.iloc[:, :27]], ignore_index=True)
    cur_df = dfp.iloc[t*27:t*27+27,:]
    new = cur_df.iloc[:,6:16]
    new = new.reset_index()
    new = new.iloc[:, 1:]
    ddd = dd.iloc[:,2:12]
    ddd = ddd.reset_index()
    ddd = ddd.iloc[:, 1:]
    cols = dfp["Activity"].unique()
    result = pd.DataFrame(new.values*ddd.values, index=cols)
    result = result.sum(axis=1)

    def best_rec(high,low,diff,all_carbon,cons_h,cons_l):
        per_quality = abs((high-low)/low)
        per_carbonchange = abs(diff/all_carbon)
        proportion = per_carbonchange / (per_quality+per_carbonchange)
        return (cons_l*proportion)

    recom_keeper = []
    if group_num == 1:
        heat_h = cur_df.loc[cur_df.Activity=="shower - short", "Quality_of_Life_Importance__1_10"].values
        heat_l = cur_df.loc[cur_df.Activity=="shower - long (> 3 min)", "Quality_of_Life_Importance__1_10"].values
        diff1 = int(heat_h - heat_l)
        diff2 = float(result.loc["shower - short"] - result.loc["shower - long (> 3 min)"])
        cons_h = cur_df.loc[cur_df.Activity=="shower - short", "Consumption"].values
        cons_l = cur_df.loc[cur_df.Activity=="shower - long (> 3 min)", "Consumption"].values
        if (diff1>0 and cons_l!=0):
            recom_keeper.append(html.P('Change your long shower to short shower by {} times.'.format(int(cons_l))))
            if diff2>0:
                recom_keeper.append(html.P('Your carbon footprint will be reduced by {}.'.format(float(cons_l*diff2))))
            else:
                recom_keeper.append(html.P('Your carbon footprint will be successfully reduced.'))
            recom_keeper.append(html.P('And your life quality will be increased by {} percentage.'.format(int(100*float(diff1/heat_l)))))
        else:
            if (cons_l != 0 and diff2 > 0):
                carbon = result['shower - short'] + result['shower - long (> 3 min)']
                best_change = best_rec(heat_h,heat_l,diff2,carbon,cons_h,cons_l)
                recom_keeper.append(html.P('Change your long shower to short shower by {} times.'.format(int(best_change))))
                recom_keeper.append(html.P('Your carbon footprint will be reduced by {}.'.format(float(best_change*diff2))))
            else:
                if (cons_l != 0 and diff2 <= 0):
                    recom_keeper.append(html.P('Change your long shower to short shower by {} times.'.format(int(cons_h))))
                    recom_keeper.append(html.P('Your carbon footprint will be reduced by {}.'.format(float(cons_h*(-diff2)))))
    if group_num == 2:
        heat_h = cur_df.loc[cur_df.Activity=="Household heating => 70F", "Quality_of_Life_Importance__1_10"].values
        heat_l = cur_df.loc[cur_df.Activity=="Household heating < 70F", "Quality_of_Life_Importance__1_10"].values
        diff1 = int(heat_h - heat_l)
        diff2 = float(result.loc["Household heating < 70F"] - result.loc["Household heating => 70F"])

        cons_h = cur_df.loc[cur_df.Activity=="Household heating => 70F", "Consumption"].values
        cons_l = cur_df.loc[cur_df.Activity=="Household heating < 70F", "Consumption"].values
        if (diff1>0 and cons_l!=0):
            recom_keeper.append(html.P('Change your heating time with tempreture <70F to >=70F by {} hours.'.format(int(cons_l))))
            if diff2>0:
                recom_keeper.append(html.P('Your carbon footprint will be reduced by {}.'.format(float(cons_l*diff2))))
            else:
                recom_keeper.append(html.P('Your carbon footprint will be successfully reduced.'))
            recom_keeper.append(html.P('And your life quality will be increased by {} percentage.'.format(int(100*float(diff1/heat_l)))))

        else:
            if (cons_l != 0 and diff2 > 0):
                carbon = result['Household heating => 70F'] + result['Household heating < 70F']
                best_change = best_rec(heat_h,heat_l,diff2,carbon,cons_h,cons_l)
                recom_keeper.append(html.P('Change your heating time with tempreture <70F to >=70F by {} hours.'.format(int(best_change))))
                recom_keeper.append(html.P('Your carbon footprint will be reduced by {}.'.format(float(best_change*diff2))))
                recom_keeper.append(html.P('Your carbon footprint will be successfully reduced.'))
            else:
                if (cons_l != 0 and diff2 <= 0):
                    recom_keeper.append(html.P('Change your heating time with tempreture >=70F to <70F by {} hours.'.format(int(cons_h))))
                    recom_keeper.append(html.P('Your carbon footprint will be reduced by {}.'.format(float(cons_h*(-diff2)))))
                else:
                    cons = cur_df.loc[cur_df.Activity=="Use of air conditioner", "Consumption"].values
                    cost = result.loc["Use of air conditioner"]
                    recom_keeper.append(html.P('Reduce your use of air conditioner by {} hours.'.format(float(cons))))
                    recom_keeper.append(html.P('Your carbon footprint will be reduced by {}.'.format(float(cons*cost))))

        heat_h = cur_df.loc[cur_df.Activity=="car trips - 2+ people with multiple end points", "Quality_of_Life_Importance__1_10"].values
        heat_l = cur_df.loc[cur_df.Activity=="car trips- self only", "Quality_of_Life_Importance__1_10"].values
        diff1 = int(heat_h - heat_l)
        diff2 = float(result.loc["car trips- self only"] - result.loc["car trips - 2+ people with multiple end points"])
        cons_h = cur_df.loc[cur_df.Activity=="car trips - 2+ people with multiple end points", "Consumption"].values
        cons_l = cur_df.loc[cur_df.Activity=="car trips- self only", "Consumption"].values
        if (diff1>0 and cons_l!=0):
            recom_keeper.append(html.P('Adding number of people of your car trips to more than 2.'.format(int(cons_l))))
            if diff2>0:
                recom_keeper.append(html.P('Your carbon footprint will be reduced by {}.'.format(float(cons_l*diff2))))
            else:
                recom_keeper.append(html.P('Your carbon footprint will be successfully reduced.'))
            recom_keeper.append(html.P('And your life quality will be increased by {} percentage.'.format(int(100*float(diff1/heat_l)))))
        else:
            if (cons_l != 0 and diff2 > 0):
                carbon = result['car trips - 2+ people with multiple end points'] + result['car trips- self only']
                best_change = best_rec(heat_h,heat_l,diff2,carbon,cons_h,cons_l)
                recom_keeper.append(html.P('Adding number of people of your car trips to more than 2 for {} trips.'.format(int(best_change))))
                recom_keeper.append(html.P('Your carbon footprint will be reduced by {}.'.format(float(best_change*diff2))))
            else:
                if (cons_l != 0 and diff2 <= 0):
                    recom_keeper.append(html.P('Do self driving car trips for {} trips'.format(int(cons_h))))
                    recom_keeper.append(html.P('Your carbon footprint will be reduced by {}.'.format(float(cons_h*(-diff2)))))
    if group_num == 3:
        diff2 = float(0.0419*2)
        cons_l = cur_df.loc[cur_df.Activity=="bags of garbage disposed", "Consumption"].values
        if (cons_l!=0):
            recom_keeper.append(html.P('By recyclying your garbage.'))
            if diff2>0:
                recom_keeper.append(html.P('Your carbon footprint will be reduced by {}.'.format(float(cons_l*diff2))))
            else:
                recom_keeper.append(html.P('Your carbon footprint will be successfully reduced.'))
    if group_num == 4:
        heat_h = cur_df.loc[cur_df.Activity=="Household heating => 70F", "Quality_of_Life_Importance__1_10"].values
        heat_l = cur_df.loc[cur_df.Activity=="Household heating < 70F", "Quality_of_Life_Importance__1_10"].values
        diff1 = int(heat_h - heat_l)
        diff2 = float(result.loc["Household heating < 70F"] - result.loc["Household heating => 70F"])
        cons_h = cur_df.loc[cur_df.Activity=="Household heating => 70F", "Consumption"].values
        cons_l = cur_df.loc[cur_df.Activity=="Household heating < 70F", "Consumption"].values
        if (diff1>0 and cons_l!=0):
            recom_keeper.append(html.P('Change your heating time with tempreture <70F to >=70F by {} hours.'.format(int(cons_l))))
            if diff2>0:
                recom_keeper.append(html.P('Your carbon footprint will be reduced by {}.'.format(float(cons_l*diff2))))
            else:
                recom_keeper.append(html.P('Your carbon footprint will be successfully reduced'))
            recom_keeper.append(html.P('And your life quality will be increased by {} percentage.'.format(int(100*float(diff1/heat_l)))))
        else:
            if (cons_l != 0 and diff2>0):
                carbon = result['Household heating => 70F'] + result['Household heating < 70F']
                best_change = best_rec(heat_h,heat_l,diff2,carbon,cons_h,cons_l)
                recom_keeper.append(html.P('Change your heating time with tempreture <70F to >=70F by {} hours.'.format(int(best_change))))
                recom_keeper.append(html.P('Your carbon footprint will be reduced by {}.'.format(float(diff2*best_change))))
            else:
                if (cons_l != 0 and diff2 <= 0):
                    recom_keeper.append(html.P('Change your heating time with tempreture >=70F to <70F by {} hours.'.format(int(cons_h))))
                    recom_keeper.append(html.P('Your carbon footprint will be reduced by {}.'.format(float(cons_h*(-diff2)))))
                else:
                    cons = cur_df.loc[cur_df.Activity=="Use of air conditioner", "Consumption"].values
                    cost = result.loc["Use of air conditioner"]
                    recom_keeper.append(html.P('Reduce your use of air conditioner by {} hours.'.format(float(cons/2))))
                    recom_keeper.append(html.P('Your carbon footprint will be reduced by {}.'.format(float((cons/2)*cost))))

    group_num = int(clust.loc[id_num]["clusters"])
    val = products.iloc[group_num].values
    return html.Div([
                html.H5('Below are your results', style={'color': '#CA0009', 'marginLeft': '2%'}),
                #plotted graphs
                dcc.Graph(
                    figure={
                        'data': [trace2, trace3],
                        'layout': go.Layout(
                            hovermode='closest',
                            xaxis= dict(title='Cummulative Carbon Footprint'),
                            yaxis= dict(title='Population')
                        )
                    }
                ),
                html.Div(id='inter', children=[
                    dcc.Graph(id='pers_det1', figure={
                        'data': [trace1],
                        'layout': go.Layout(
                            hovermode='closest'
                        )
                    }),
                    dcc.Graph(id='performance1', figure={
                        'data': [scatter1, scatter2],
                        'layout': layout
                    })
                ], style={'columnCount': 2}),

                #recommendations
                html.H5('Recommendations', style={'color': '#CA0009', 'marginLeft': '2%'}),
                html.Div([
                    html.H6('Products', style=styles['sub-menu']),
                    html.Div([html.Div([
                            dcc.Checklist(
                                options=[
                                    {'label': '{} {}'.format(val[0], val[2]), 'value': 'prod1'},
                                    {'label': '{} {}'.format(val[1], val[3]), 'value': 'prod2'}
                                ],
                                values=["prod1"]
                            ),
                            html.Div([
                                html.A("Product 1", href=val[4]),
                                html.Br(),
                                html.A("Product 2", href=val[5])
                            ])
                        ], style={'columnCount': 2})], style=styles['sub-sub'])
                    ]),
                    html.H6('Tips', style=styles['sub-menu']),
                    html.Div(html.Div(children=recom_keeper),  style=styles['sub-sub'])
        ], style=styles['main'])
Пример #14
0
#start = datetime.now()

stats = stats_df(df_team)   #.loc[ 'HEBRAICA Y MACABI' , : ]


stats.reset_index(inplace=True)
#print(stats)

x = stats[stats["TEAM"] == "HEBRAICA Y MACABI"]
print(x)

data = [go.Scatterpolar(
  r = [x['DREB%'].values[0],x['OREB%'].values[0],x['eFG%'].values[0],x['OppeFG%'].values[0],x["FTRate"].values[0],x["OppFTRate"].values[0],],
  theta = ['DREB%','OREB%','eFG%','OppeFG%','FTRate', 'OppFTRate'],
  fill = 'toself',
     line =  dict(
            color = 'yellow'
        )
)]

layout = go.Layout(
  polar = dict(
    radialaxis = dict(
      visible = True,
      range = [0, 1]
    )
  ),
  showlegend = False,
  title = "{} stats distribution".format(x.TEAM.values[0])
)
fig = go.Figure(data=data, layout=layout)
                      options=update_dropdown_features_track(),
                      multi=False,
                      value=""),
     ],
              className='mdl-cell mdl-cell--6-col'),
     html.Div([], className='mdl-cell mdl-cell--3-col'),
     html.Div([
         dcc.Graph(
             id='radar-feature-track',
             figure={
                 'data': [
                     go.Scatterpolar(
                         r=[0, 0, 0, 0, 0, 0, 0],
                         theta=[
                             'Liveness',
                             'Speechness', 'Valence', 'Energy',
                             'Acousticness', 'Instrumentalness',
                             'Dancebility'
                         ],
                         fill='toself',
                         marker=dict(color='#4101c1'))
                 ],
                 'layout': [
                     go.Layout(polar=dict(radialaxis=dict(
                         visible=True, range=[0.0, 1.0])),
                               showlegend=True)
                 ]
             }),
     ],
              className='mdl-cell mdl-cell--12-col'),
 ],
          className='mdl-grid')
    xsec[i] = a[0][0]
    ysec[i] = a[1][0]

raio = 25

xr = xsec[(xsec >= (-raio)) & (xsec <= (raio)) & (ysec >= (-raio)) & (ysec <=
                                                                      (raio))]
yr = ysec[(xsec >= (-raio)) & (xsec <= (raio)) & (ysec >= (-raio)) & (ysec <=
                                                                      (raio))]

hip = np.sqrt(xr**2 + yr**2)
ang = np.arctan2(yr, xr) * (360 / (2 * np.pi))

initial_trace = go.Scatterpolar(
    r=hip,
    theta=ang,
    name='Scatter',
    mode='lines+markers',
)

initial_trace_2 = go.Scatter(
    x=xsec,
    y=ysec,
    name='Scatter',
    mode='lines+markers',
)

app.layout = html.Div([
    dcc.Graph(id='live-graph',
              animate=True,
              figure={
                  'data': [initial_trace, initial_trace_2],
Пример #17
0
date_mark = {i: dates[i] for i in range(len(dates))}

##############################################################################
## Calidad

calidad_data = pd.read_csv("/var/www/modelodatosabiertos/src/data/Quality_Indicators.csv", sep=";", encoding="UTF-8")
# calidad_data = pd.read_csv("src/data/Quality_Indicators.csv", sep=";", encoding="UTF-8")
calidad_data.columns = ["id", "entidad", "categoria", "nombre", "Completitud",
    "Credibilidad", "Actualidad", "Trazabilidad", "Disponibilidad", "Conformidad", "Comprensibilidad", "Portabilidad",
    "Consistencia", "Exactitud"]

dimensiones = ["Completitud", "Credibilidad", "Actualidad", "Trazabilidad", "Disponibilidad", "Conformidad", "Comprensibilidad", "Portabilidad", "Consistencia", "Exactitud"]
promedios = np.average(calidad_data.iloc[:, 4:], axis=0)

radar_promedio = go.Figure(data=go.Scatterpolar(r=promedios, 
    theta=dimensiones, 
    fill='toself'))

radar_promedio.update_layout(
    polar=dict(radialaxis=dict(visible=True)),
    showlegend=False,
    margin=go.layout.Margin(l=50, r=50, t=40, b=20, pad=1),
    legend=go.layout.Legend(orientation="h", xanchor = "center", x = 0.5, y=-0.2)
)

calidad_categoria = calidad_data.groupby(["categoria"], as_index=False).mean()

radar_categoria = go.Figure()

radar_categoria.add_trace(
    go.Scatterpolar(r=calidad_categoria[calidad_categoria["categoria"]=="Cultura"].iloc[:, :].values.tolist()[0][1:], 
Пример #18
0
def plot_category_bdc(filename, categories, bdc_vals_dict):
    #
    # `bdc_vals_dict` should of the form:
    #       bdc_vals_dict = {"cpu": [[a1, b1, ..., d1], [a1, b1, ..., d1], ..., [a1, b1, ..., d1]],
    #                         "gpu": [[a2, b2, ..., d2], [a2, b2, ..., d2], ..., [a2, b2, ..., d2]],
    #                                   ...
    #                         "gpu": [[aM, bM, ..., dM], [aM, bM, ..., dM], ..., [aM, bM, ..., dM]}
    #
    # `stages` should be of form:
    #       stages = ["S1", "S2", ..., "SN"]
    #

    # Squash individual stage BDCs into 1 bdc per category
    data = []
    for (_, hw) in bdc_vals_dict.items():
        accs = []
        for cat in hw:
            acc = 0
            for stage in cat:
                acc += stage
            accs.append(acc)
        data.append(accs)

    hws = list(bdc_vals_dict.keys())

    # Wrap around first category
    categories.append(categories[0])

    fig = go.Figure()
    for i in range(len(hws)):

        # Wrap around first data point
        data[i].append(data[i][0])

        fig.add_trace(
            go.Scatterpolar(name=hws[i],
                            r=data[i],
                            theta=categories,
                            mode='lines'))

    # Fonts
    axis_tick_font = dict(size=14, family='Calibri', color='black')
    legend_font = axis_tick_font

    fig.update_layout(polar=dict(radialaxis=dict(showticklabels=False,
                                                 showline=False,
                                                 showgrid=True,
                                                 gridwidth=1,
                                                 gridcolor='rgba(0,0,0,0.1)'),
                                 angularaxis=dict(showgrid=True,
                                                  gridwidth=1,
                                                  gridcolor='rgba(0,0,0,0.3)',
                                                  tickfont=axis_tick_font),
                                 bgcolor='white'),
                      showlegend=True)

    # To generate HTML output:
    pio.write_html(fig,
                   file=filename + ".html",
                   auto_open=False,
                   include_plotlyjs="cdn")

    logging.info("Plot generated at: {}".format(filename))

    # To generate image file output:
    fig.write_image(filename + ".pdf")
    fig.write_image(filename + ".png")

    logging.info("Plot generated at: {}".format(filename))