Beispiel #1
0
 html.Section(
     id="nav-bar",
     children=[
         html.Nav(
             className="navbar navbar-expand-lg navbar-light",
             children=[
                 html.A(className="navbar-brand", children=['''DayaData'''
                                                            ]),
                 html.Div(
                     id="navbarNav",
                     className="collapse navbar-collapse",
                     children=[
                         html.Ul(
                             className="navbar-nav ml-auto",
                             children=[
                                 html.Li(
                                     className="nav-item",
                                     children=[
                                         html.A(className="nav-link",
                                                href="#",
                                                children=['''Beranda'''])
                                     ]),
                                 html.Li(className="nav-item",
                                         children=[
                                             html.A(
                                                 className="nav-link",
                                                 href="#",
                                                 children=['''Tentang'''])
                                         ]),
                                 html.Li(className="nav-item",
                                         children=[
                                             html.A(className="nav-link",
                                                    href="#",
                                                    children=['''Kontak'''])
                                         ]),
                                 html.Li(className="nav-item",
                                         children=[
                                             html.A(className="nav-link",
                                                    href="#",
                                                    children=['''Login'''])
                                         ]),
                             ])
                     ])
             ])
     ]),
def serve_layout():

    return [
        html.Div([
            html.Br(),
            html.Br(),
            html.H1("Why We Don't Live Together",
                    style={
                        'font-size': '4.5rem',
                        'font-weight': 'bold',
                        'color': '#26BE81'
                    }),
            html.Br(),
            html.
            H3("Replicating residential segregation using agent-based modeling"
               ),
            html.Br(),
            html.Br(),
            html.Img(src='/assets/philadelphia_segregation_dark.png',
                     style={'max-width': '100%'}),
            html.Div([
                html.Section(
                    '''Figure 1: Ethnic populations in Philadelphia using data from the 2010 Census.
                Source:'''),
                html.
                A('''WashingtonPost''',
                  href=
                  'https://www.washingtonpost.com/graphics/2018/national/segregation-us-cities/',
                  style={'display': 'inline'})
            ]),
            html.Br(),
            html.Br(),
            html.Ul([
                html.
                Li('''We reproduce a landmark experiment from the 1970s that demonstrates housing segregation patterns
                using agent-based modeling (ABM).'''),
                html.
                Li('''This experiment shows that housing segregation, where individuals cluster with similar people,
                 can result even if all people have a preference for living in integrated neighborhoods.'''
                   ),
                html.
                Li('''This experiment is often used as an introduction to agent-based modeling and demonstrates that
                counter-intuitive results can emerge at the societal level due to the complexities of group dynamics.'''
                   ),
            ],
                    style={'font-size': '1.25rem'}),
            html.Br(),
            html.Br(),
        ],
                 style={
                     'margin': 'auto',
                     'text-align': 'left',
                     'max-width': '750px'
                 }),
        html.Br(),
        html.Br(),

        # intro
        html.Div(
            [
                html.H3('''Introduction'''),
                html.
                P('''Social scientists have observed that people of similar race tend to cluster together,
            leading to predominantly white, black or Hispanic neighborhoods rather than a multiracial mixed
            alternative. Why is this the case? The causes of this residential segregation are likely complex
            and motivated by social, economic and political factors but as a starting point let’s consider a
            simplifying thought experiment.'''),
                html.
                P('''Imagine that people are motivated solely by a personal preference to not be too much of an
            outsider. For example, say that a white household would be happy to live in a neighborhood as long as at
            least one out of every three of the residents in the neighborhood were also white. In this case,
            the white household would be perfectly content if the majority of his neighbors were “dissimilar” to
            him just so long as he wasn’t too heavily outnumbered.'''),
                html.
                P('''Now imagine the entire population, individuals of all races, held similar preferences.
            What do we think would happen? A perfectly intuitive line of thought would be that since everyone is
            accepting of people of other races in their neighborhood, even going so far as to be willing to be a
            minority, that neighborhoods would generally be mixed. Unfortunately, this is an example when our
            intuition fails us and a perfectly plausible theory fails to reflect the complexity of even an extremely
            simplified reality.'''),
                html.
                P('''This tool will demonstrate the application of agent-based modeling (ABM) to explaining
            residential segregation and also expose the concept and process of ABM itself.  Agent-based modeling
            is a bottom-up framework that involves programming individual agents with behavior and goals and
            simulating their interactions with each other and the environment. The goal of this app is to show
            how ABM is often used to analyze group behavior and can reveal unexpected dynamics that emerge from
            seemingly simple setups.'''),
                html.Br(),
                html.H3('''Residential Segregation'''),
                html.
                P('''Chicago is one of the most diverse metropolises in America with nearly 3 million residents
            and large proportions from each major ethnic group (56% White, 32% Black, 29% Hispanic and 7% Asian).
            Chicago however, is also one of the most segregated big cities in America. For example, a map of
            demographic information using the latest 2010 census shows distinct neighborhoods bounded by ethnic
            composition.'''),
                html.Br(),
            ],
            style={
                'font-size': '1.1rem',
                'margin': 'auto',
                'max-width': '750px',
                'text-align': 'left',
            }),

        # example real segregation maps
        html.Div([
            html.Hr(),
            html.H5('Figure 1: Observed Segregation Across Two Cities'),
            html.Br(),
            dbc.Row([
                dbc.Col([
                    html.Div(
                        [html.Img(src='/assets/chicago_segregation_dark.png')],
                        style={
                            'height': '200px',
                            'width': '300px'
                        }),
                ],
                        width=6),
                dbc.Col([html.Img(src='/assets/nyc_segregation_dark.png')],
                        width=6),
            ],
                    no_gutters=False),
            html.Br(),
            html.Div(
                '''Each dot represents 150 people from the 2010 Census. Source: WashingtonPost'''
            ),
            html.Hr(),
        ],
                 style={
                     'margin': 'auto',
                     'text-align': 'left',
                     'max-width': '1000px'
                 }),
        html.Br(),
        html.Div(
            [
                html.
                P('''The reality of racial segregation has many contributing factors, including deliberate government
            policies that have historically segregated minorities into localized neighborhoods via land use regulations
            or mortgage discrimination. Furthermore, a more passive phenomena that has been documented has been
            racial steering whereby real estate brokers are likely to steer clients towards particular neighborhoods
            based on race.'''),
                html.
                P('''In addition to these external factors, housing choices may of course also stem from personal
            preferences which may include favoring neighborhoods due to proximity to family, the availability of
            familiar food options or the possibility of forming social networks with people of similar values.
            Collectively these preferences for amount to what social scientists call an in-group preference, or
            a preference for one’s own culture, and which will be the focus of this app.'''
                  ),
                html.
                P('''Though this app will use residential segregation as a way to discuss ABM, it is not a
            comprehensive overview of the complex social, political and economic dynamics. While computer scientists
            are able to contribute to the conversation, as will be demonstrated in this app, a serious discussion of
            this topic deserves a multidisciplinary approach with perspectives from historians, statisticians and
            economists.''',
                  style={
                      'background-color': 'lightyellow',
                      'border': '2px solid black',
                      'border-radius': '20px',
                      'padding': '6px'
                  }),
                html.Br(),
                html.H3('''Agent-based Modeling Methodology'''),
                html.
                P('''The objective of agent-based modeling is to replicate reality using a programmed computer
            simulation that is as simple as possible. In our case, we want to simulate residential evolutions that
            reproduce observed segregation patterns, or the clustering of different groups, based on as few factors
            in our computer program as possible. If we are able to replicate observed reality, we will have “explained”
            housing segregation in the sense that our simulation shows that housing segregation is an outcome of our
            programmed assumptions. '''),
                html.
                P('''It’s important to note that within the ABM framework “explanation” has a different meaning
            than in statistics. Where in statistics explanation is associated with correlation, within ABM the
            meaning of explanation has connotations of causality since we explicitly define cause and effect dynamics
            within our simulation (the challenge however is to encode accurate cause and effect relationships).
            Furthermore, whereas in statistics we usually try to control for many different factors by including
            different variables in the analysis, within ABM it is preferable to construct a parsimonious model to
            show the minimum required assumptions that would be required to reproduce reality. '''
                  ),
                html.Br(),
                html.H3('''Simulation'''),
                html.
                P('''To program our segregation simulation we model a simplified reality. We represent a city as a
            2D grid, like a checkerboard, and each square in the grid represents a residence that can be occupied by
            a household. Our course, real neighborhoods do not physically look like a crowded checkboard but we assume
            that this simplification, amongst many assumptions we’ll make, is not material to the analysis.'''
                  ),
                html.
                P('''Next we assume in our model that there are two types of households (say White and Asian or
            Lannister and Targaryen) and that each household is primarily concerned about belonging to a neighborhood
            filled with similar neighbors. To measure the similarity of a neighborhood for a given household, we define
            a neighborhood as the adjacent houses within some radius and then calculate the proportion of households
            that belong to the “same” group and the proportion of households belonging to the “other” group. Depending
            on a household’s tolerance level, the household can then either decide to move to a new neighborhood or to
            stay.'''),
            ],
            style={
                'font-size': '1.1rem',
                'margin': 'auto',
                'max-width': '750px',
                'text-align': 'left',
            }),
        html.Br(),

        # interactive tool: example neighborhood similarity calculation
        html.Div(
            [
                html.Hr(),
                html.Br(),
                html.H4('Figure 2: Sample Similarity Calculation'),
                html.Br(),
                dbc.Row([

                    # left column
                    dbc.Col([html.Div(id='sample-calc-grid')], width=6),

                    # right column
                    dbc.Col([
                        html.Div(
                            '''We calculate the comfort of the center household, marked by the X,
                        by counting the number of similar and dissimilar households in the surrounding
                        neighborhood. In this example, assume that a household would prefer to live
                        in a neighborhood where at least 51% of her neighbors are like her.'''
                        ),
                        html.Br(),
                        dbc.Row([
                            dbc.Col([
                                html.Div('Select neighborhood:',
                                         style={'color': 'grey'}),
                                dcc.Dropdown(
                                    id='radius-input',
                                    options=[{
                                        'label': "Radius {}".format(i),
                                        'value': i
                                    } for i in range(1, 5)],
                                    value=2,
                                    clearable=False,
                                ),
                            ],
                                    width=5),
                            dbc.Col('', width=1),
                            dbc.Col([
                                html.Div([
                                    dt.DataTable(id='sample-table',
                                                 columns=sample_columns,
                                                 style_cell_conditional=
                                                 sample_style_cell_conditional,
                                                 style_data_conditional=
                                                 sample_style_data_conditional,
                                                 style_as_list_view=True)
                                ])
                            ],
                                    width=6),
                        ]),
                        html.Br(),
                        html.Div(id='sample-conclusion',
                                 style={'font-weight': 'bold'})
                    ],
                            width=6),
                ]),
            ],
            style={
                'margin': 'auto',
                'text-align': 'left',
                'max-width': '900px'
            }),
        html.Br(),
        html.Br(),

        # Introduction
        html.Div([
            html.Hr(),
            html.H4('Figure 1: Migration Simulation'),
            dbc.Row([
                dbc.Col([
                    html.Img(src='/assets/test_gif.gif'),
                ], width=7),
                dbc.Col([
                    html.
                    H5('''From an initial integrated state, two populations eventually segregate over
                    time.'''),
                    html.Br(),
                    html.
                    P('''Each square represents a household that considers whether to remain or move to a different
                    spot in the grid. Households make the decision based on a simple logic: Stay if at least 40% of
                    its neighbors are a similar color, or else move otherwise. Even though everyone is content
                    to be a minority and live in an integrated neighborhood, over time the grid becomes
                    segregated.''')
                ],
                        width=5),
            ]),
            html.Hr(),
        ],
                 style={
                     'margin': 'auto',
                     'text-align': 'left',
                     'max-width': '1100px'
                 }),
        html.Br(),
        html.Br(),

        # interactive tool: example neighborhood similarity calculation
        html.Div([
            html.Hr(),
            html.Br(),
            html.H3('Segregation Simulation'),
            html.Br(),
            dbc.Row([
                dbc.Col([html.Div('simulator here'),
                         html.Div(id='simulator')],
                        width=9),
                dbc.Col([
                    html.Div(
                        '''Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
                    incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation
                    ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit
                    in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat
                    non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'''
                    ),
                    html.Br(),
                ],
                        width=3),
            ]),
        ],
                 style={
                     'margin': 'auto',
                     'text-align': 'left',
                     'max-width': '1000px'
                 }),
    ]
Beispiel #3
0
def Card(children, **kwargs):
    return html.Section(children, className="card-style")
Beispiel #4
0
        ])
      ])
    ]),
    # End Header **************************************************
    
    dcc.Tabs(parent_className='custom-tabs',
             className='custom-tabs-container', children=[

        # Start HOME  Tab*********************************************
        dcc.Tab(label=' HOME', className='tab-icon fa fa-home',selected_className='custom-tab--selected',  children=[

            # Start Overlay Section *********************************
            html.Section(className='row overlay-img', children=[
                html.Div(className='overlay', children=[
                    html.Div(className='banner', children=[
                        html.H1('Student Admission Predicion'),
                        html.P('SAP is the best place for the bachelor students to understand their chances of getting accepted into shortlisted universities')
                    ])
                ])
            ]),
            # End Overlay Section *************************************

            # INTRODUCTION ***************************************
            html.Div(className='container' , children=[
                html.Div(className='row', children=[
                    # LOGO
                    html.Div(className='three columns', children=[
                        html.Img(src=app.get_asset_url('logo.jpg'), style={'width': '220px','padding-top':'20px'}),
                    ]),
                    # TEXT
                    html.Div(className='nine columns', children=[
                        html.H2('Motivation', className='block-caption'),
 html.Section(
     className='sidebar',
     children=[
         html.Div(
             className='user-panel',
             children=[
                 html.Div(
                     className='pull-left image',
                     children=[
                         html.Img(
                             className='img-circle',
                             src='./assets/hat.png')
                     ]),
                 html.Div(className='pull-left info',
                          children='MADS Hatters')
             ]),
         html.
         Ul(className='sidebar-menu',
            children=[
                html.
                Li(className='header',
                   children='MAIN NAVIGATION'),
                html.
                Li(children=[
                    dcc.Tabs(
                        id="menu-tabs",
                        vertical=True,
                        parent_style={'float': 'left'},
                        value='menu-item-home',
                        className="treeview-menu",
                        style=menu_tabs_styles,
                        children=[
                            dcc.Tab(
                                label='Home',
                                value='menu-item-home',
                                style=menu_tab_style,
                                selected_style=
                                menu_tab_selected_style
                            ),
                            dcc.Tab(
                                label='All Satellites',
                                value=
                                'menu-item-allsats',
                                style=menu_tab_style,
                                selected_style=
                                menu_tab_selected_style
                            ),
                            dcc.Tab(
                                label='History',
                                value=
                                'menu-item-history',
                                style=menu_tab_style,
                                selected_style=
                                menu_tab_selected_style
                            ),
                            dcc.Tab(
                                label='Intercepts',
                                value=
                                'menu-item-intercepts',
                                style=menu_tab_style,
                                selected_style=
                                menu_tab_selected_style
                            ),
                            dcc.Tab(
                                label='Starlink',
                                value=
                                'menu-item-starlink',
                                style=menu_tab_style,
                                selected_style=
                                menu_tab_selected_style
                            ),
                            dcc.Tab(
                                label=
                                'Maneuver Detection',
                                value=
                                'menu-item-maneuvers',
                                style=menu_tab_style,
                                selected_style=
                                menu_tab_selected_style
                            ),
                            dcc.Tab(
                                label='Gabbard Diagram',
                                value=
                                'menu-item-gabbard',
                                style=menu_tab_style,
                                selected_style=
                                menu_tab_selected_style
                            ),
                        ]),
                    html.Div(id='ui_dummy',
                             style={'display': 'none'}),
                    html.Div(
                        id='csk',
                        style={'display': 'none'},
                        children=
                        "ZXlKaGJHY2lPaUpJVXpJMU5pSXNJblI1Y0NJNklrcFhWQ0o5LmV5SnFkR2tpT2lJd05tSXdORGN5WkMwNE5tUTBMVFExTnpRdFltVTNOeTAxWVRabFpUVTRNRFUzWkRVaUxDSnBaQ0k2TkRBeE5ESXNJbWxoZENJNk1UWXdPRE0xTkRZNE9IMC5uT1pBQ291ay0tZnhQX2V1cXRnRmt3d05TMi02NEJaODFBTWVNbzlwZ1lj"
                    )
                ])
            ])
     ])
Beispiel #6
0
app.layout = html.Div(
    style = {
        "background-image" : 'url("/assets/smiley-pattern1.jpg")',
        "background-repeate" : "repeat",
        "background-size" : "200px 200px"
        },
    
    children = [
        
        html.Section([
            html.Div([
                html.Div([
                    html.H1(children = "Tracklist Analyzer",
                            className = "title is-1"),
                    html.H2(children = "Discover how a set or playlist progresses",
                            className = "subtitle is-2")
                ], className='container'),
                
 			], className='hero-body')
		], className='hero is-small is-black'),
        
        html.Div([
            html.Div([
                html.Div([
                    html.H4(children = "Enter a tracklist URL from ",
                            className = "title is-4",
                            style = {"display" : "inline"}),
                    
                    html.A(children = "1001Tracklists.com",
                            href = "https://www.1001tracklists.com/",
def Card(children, **kwargs):
    return html.Section(className="card",
                        children=children,
                        **_omit(["style"], kwargs))
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.graph_objs as go

app = dash.Dash()
server = app.server

app.layout = html.Div([
    html.Section(id="slideshow",
                 children=[
                     html.Div(id="slideshow-container",
                              children=[
                                  html.Div(id="image"),
                                  dcc.Interval(id='interval', interval=3000)
                              ])
                 ])
])


@app.callback(Output('image', 'children'), [Input('interval', 'n_intervals')])
def display_image(n):
    if n == None or n % 3 == 1:
        img = html.Img(src="http://placeimg.com/625/225/any")
    elif n % 3 == 2:
        img = html.Img(src="http://placeimg.com/625/225/animals")
    elif n % 3 == 0:
        img = html.Img(src="http://placeimg.com/625/225/arch")
    else:
        img = "None"
Beispiel #9
0
app.layout = html.Section(children=[
    html.Div(
        className='calculPart',
        children=[
            html.Div(html.Img(className='test', src=img_top_url,
                              height="150")),
            html.H1("Application de calcul du Bonus à destination des Sales"),
            html.
            P("Conformément à la politique établie par l'entreprise, cette page vous permettra de faire la simulation de votre bonus annuel."
              ),
            html.Br(),
            html.Div('Entrez votre salaire brut'),
            html.Div(
                dcc.Input(id='input-box-1', type="number", placeholder=40000),
                # html.P("€"),
            ),
            html.P('Entrez votre coefficient de grade'),
            html.Div(
                dcc.Input(
                    id='input-box-2',
                    type='number',
                    placeholder=3,
                ), ),
            html.P('Entrez votre nombre de contrat signé'),
            html.Div(
                dcc.Input(
                    id='input-box-3',
                    type='number',
                    placeholder=5,
                )),
            html.P(),
            html.Button('Calcul de votre bonus', id='button'),
            html.P(),
        ]),
    html.P(),
    html.Div(className='resultPart',
             children=[
                 html.Div(
                     id='output-container-button',
                     children='Remplissez les champs précédents et validez')
             ])
])
Beispiel #10
0
 html.Div([
     html.Div([
         html.Br(),
         html.H1('Cooking Recipe Dashboard',
                 style={
                     'color': '#003B73',
                     'textAlign': 'left'
                 }),
         html.Blockquote('Individual MA705 Project | Kremena Ivanov',
                         style={'textAlign': 'left'}),
         html.B('What is this dashboard about?',
                style={
                    'color': '#003B73',
                    'textAlign': 'left'
                }),
         html.Section(text, style={'textAlign': 'left'}),
         html.Section(text_l1),
         html.Section(text_l2),
         html.Section(text_l3),
     ]),
     html.Hr(),
     html.Div([
         html.B('How to use this dashboard?',
                style={
                    'color': '#003B73',
                    'textAlign': 'left'
                }),
         html.Div(text_filters),
         html.Br(),
         html.Label("Select a category: "),
         dcc.Dropdown(id='filter_dropdown',
def get_layout():
    global __store__
    __store__ = recommender.DataStore()
    return html.Div(
        id="app",
        className="container",
        children=[
            dcc.Input(id="thumb_btn_timestamp",
                      value="",
                      style={"display": "none"}),
            html.Div(id="thumb_btn_timestamp_debug", style={"display":
                                                            "none"}),
            html.Section(
                className="jumbotron text-center",
                children=[
                    html.H1("Y•E•S MENTORING MATCHER",
                            className="text-center jumbotron-heading"),
                ],
            ),
            html.Div(className="row",
                     children=[mentees_table(),
                               mentors_table()]),
            html.Section(
                className="jumbotron",
                children=[
                    html.Div(
                        className="form text-right",
                        children=[
                            dcc.Link("Download Updated CSV Files",
                                     href="/download",
                                     refresh=True,
                                     id="DBUTTON",
                                     className="btn btn-primary",
                                     style={
                                         "fontSize": "18px",
                                     }),
                        ],
                    ),
                    html.Div(children=[
                        html.Label("Sort By",
                                   style={
                                       "padding": "5px",
                                       "fontSize": "18px",
                                       "fontWeight": "bold"
                                   }),
                        dcc.Dropdown(
                            style={
                                "textAlign": "center",
                            },
                            options=[
                                {
                                    "label": "Mentor Name",
                                    "value": "mentor_name"
                                },
                                {
                                    "label": "Mentee Name",
                                    "value": "mentee_name"
                                },
                                {
                                    "label": "Score",
                                    "value": "score"
                                },
                                {
                                    "label": "Distance",
                                    "value": "distance"
                                },
                                {
                                    "label": "Ethnicity Match",
                                    "value": "ethnicity_match"
                                },
                            ],
                            id="SORTBY",
                            placeholder="Select",
                        ),
                        html.Label("Filter By",
                                   style={
                                       "padding-top": "10px",
                                       "fontSize": "18px",
                                       "fontWeight": "bold"
                                   }),
                        html.Div(
                            #className="form-check form-check-inline",
                            dcc.RadioItems(
                                options=[
                                    {
                                        "label": "By Mentor",
                                        "value": "mentor_name"
                                    },
                                    {
                                        "label": "By Mentee",
                                        "value": "mentee_name"
                                    },
                                    {
                                        "label": "By Score",
                                        "value": "score"
                                    },
                                    {
                                        "label": "Max Distance",
                                        "value": "distance"
                                    },
                                    {
                                        "label": "Ethnicity Match",
                                        "value": "ethnicity_match"
                                    },
                                    {
                                        "label": "None",
                                        "value": "none"
                                    },
                                ],
                                id="FILTER",
                                style={
                                    "width": "100%",
                                    "margin": "auto",
                                    "paddingBottom": "30px"
                                },
                                labelStyle={
                                    "paddingRight": "20px",
                                    "fontSize": "14px"
                                },
                                #inputStyle = {"width": "100%", "padding": "10px", "margin": "auto"},
                                className="form-check form-check-inline",
                                inputClassName="form-check-input",
                                labelClassName="form-check-label")),
                        html.Div(
                            #className="form text-left",
                            children=[
                                html.Label("Used For Filtering:",
                                           style={
                                               "padding": "5px",
                                               "fontSize": "18px",
                                               "fontWeight": "bold"
                                           }),
                                dcc.Input(
                                    id="get-specifics",
                                    value="Enter Here",
                                    type="text",
                                ),
                            ],
                            id="get-specifics-container",
                            className="col text-center",
                        ),
                        # dcc.Input(id='get-specifics', value='initial value', type='text'),
                        html.Div(html.Button("Get Matches", id="btn-filter"),
                                 className="col text-center",
                                 style={"padding": "10px"}),
                    ]),
                    matches_sorted_container(),
                ],
            ),
        ],
    )
Beispiel #12
0
layout = html.Section(
    id="main-content",
    children=[
        html.Section(
            className="wrapper",
            children=[
                html.Div(
                    className="row",
                    children=[
                        html.Div(
                            className="col-lg-9 main-chart",
                            children=[
                                html.Div(children=[
                                    html.Div(
                                        className="border-head",
                                        children=[
                                            html.
                                            H3("Análisis de Reincidencia en Colombia"
                                               )
                                        ]),
                                    geographic.geographic_output,
                                    html.Div(className="row mt",
                                             children=[
                                                 cards.card1, cards.card2,
                                                 cards.card3
                                             ]),
                                ])
                            ]), rightpanel.rightpanel
                    ])
            ])
    ])
Beispiel #13
0
    html.Section(
        style={
            'width': '100%',
            'height': '100%',
            'background-color': colors['background']
        },
        children=[
            # Left Side
            html.Div(
                id='left_container',
                children=[
                    html.H1(
                        children='CS405 - Visualization Project',
                        style={
                            'font-family':
                            '-apple-system, BlinkMacSystemFont, sans-serif;',
                            'textAlign': 'center',
                            'color': colors['header'],
                            'margin': '30px'
                        }),
                    html.Div(
                        children='made by Yagiz Ismet Ugur',
                        style={
                            'font-family':
                            '-apple-system, BlinkMacSystemFont, sans-serif;',
                            'textAlign': 'center',
                            'color': colors['text']
                        }),
                    html.H2(
                        "NY Taxi Trip",
                        style={
                            'font-family':
                            '-apple-system, BlinkMacSystemFont, sans-serif;',
                            'textAlign': 'center',
                            'color': colors['header'],
                            'margin': '30px'
                        }),
                    html.Div(
                        className="dropdown_date",
                        children=[
                            dcc.DatePickerSingle(
                                id="datepicker",
                                min_date_allowed=datetime.datetime(
                                    df['tpep_pickup_datetime'].min().year,
                                    df['tpep_pickup_datetime'].min().month,
                                    df['tpep_pickup_datetime'].min().day),
                                max_date_allowed=datetime.datetime(
                                    df['tpep_pickup_datetime'].max().year,
                                    df['tpep_pickup_datetime'].max().month,
                                    df['tpep_pickup_datetime'].max().day),
                                initial_visible_month=datetime.datetime(
                                    df['tpep_pickup_datetime'].min().year,
                                    df['tpep_pickup_datetime'].min().month,
                                    df['tpep_pickup_datetime'].min().day),
                                date=datetime.datetime(
                                    df['tpep_pickup_datetime'].min().year,
                                    df['tpep_pickup_datetime'].min().month,
                                    df['tpep_pickup_datetime'].min().day).date(
                                    ),
                                display_format="MMMM D, YYYY",
                                style={
                                    "border": "0px solid black",
                                    "margin": "200px",
                                    "align-content": "center",
                                    "width": "50%"
                                },
                            )
                        ]),
                ],
                style={
                    'width': '40vh',
                    'height': '100vh',
                    'float': 'left',
                    'background-color': colors['background']
                }),

            # Right Side
            html.Div(
                id='right_container',
                children=[
                    html.H2(
                        children='NYC Yellow Trip Data Table(2017)',
                        style={
                            'color': colors['header'],
                            'font-family':
                            '-apple-system, BlinkMacSystemFont, sans-serif;',
                            'margin-left': '30px',
                            'margin-right': '30px',
                            'text-decoration': 'underline solid'
                        }),

                    # TODO: IDEAS --> Aylara gore total odeme dagilimlari
                    # generate_scatter_graph(df)
                    html.Div(children=[
                        html.Div(
                            [html.H1("Scatter Graph")],
                            style={
                                "text-align": "center",
                                "color": colors['header'],
                                "backgorund-color": colors['background']
                            }),
                        html.Div(
                            dcc.Graph(id="myScatterGraph"),
                            style={"background-color": colors['background']}),
                        # html.Div([dcc.RangeSlider(id="month-slider", min=1, max=df['tpep_pickup_datetime'].max().month, marks={
                        #    1: 'Jan', 2: 'Feb', 3: 'Mar', 4: 'Apr', 5: 'May', 6: 'Jun', 7: 'Jul', 8: 'Aug',
                        #    9: 'Sep',
                        #    10: 'Oct', 11: 'Nov', 12: 'Dec'
                        # }, value=[1, 2])], style={"margin": "20", "padding": "20"})
                    ]),
                    html.Div(children=[
                        dcc.Graph(id="map-graph", figure=fig),
                        # dcc.Graph(id="histogram"),
                        # dcc.Graph(id="doughnut-chart")
                    ])

                    # TODO: IDEAS --> Aylara gore tip dagilimlari

                    # TODO: IDEAS --> Aylara gore trip distancelar

                    # TODO: IDEAS -->

                    # TODO: Call Graph Function Here.

                    # generate_figure(df_1, len(df_1))
                ],
                style={
                    'background-color': '#444444',
                    # 'margin-left': '40vh',
                    'height': '100vh',
                    'width': 'auto',
                    # 'width': '70vh'
                    'overflow': 'scroll',
                }),
        ]),
Beispiel #14
0
 html.Section(
     id='barplot-section',
     children=html.Div(
         className='screen-height',
         children=[
             html.
             Div(style={'text-align': 'center'},
                 children=[
                     html.
                     Div(children=[
                         html.
                         H1(children=
                            'Ilukrotnie wzrosło zadłużenie między okresem styczniowym a listopadowym?',
                            style={
                                'font-weight': 'bold',
                                'padding': '10px'
                            }),
                         html.Div(children=[
                             dcc.RadioItems(
                                 id='barplot-input',
                                 options=[
                                     {
                                         'label': ' 2-krotnie',
                                         'value': 'a'
                                     },
                                     {
                                         'label': ' O około 10%',
                                         'value': 'b'
                                     },
                                     {
                                         'label':
                                         ' Nie da się określić',
                                         'value': 'c'
                                     },
                                 ],
                                 value="",
                                 labelClassName='mr-2')
                         ]),
                         dbc.Button(
                             'Sprawdź odpowiedź',
                             color='primary',
                             id="barplot-check-answer-button",
                         ),
                         html.Div(id='barplot-number-of-clicks',
                                  style={'display': 'none'},
                                  children='0'),
                         html.Div(children=[
                             dbc.Alert("Źle!",
                                       id="barplot-wrong-answer",
                                       style={'display': 'none'},
                                       color='danger'),
                             dbc.Alert("Dobrze!",
                                       id="barplot-good-answer",
                                       style={'display': 'none'})
                         ])
                     ]),
                     html.Div(children=[
                         html.Div(children=[
                             html.Div([
                                 dcc.Graph(
                                     style={'height': '350px'},
                                     figure=barplot_bad_graph),
                             ],
                                      id='barplot-bad-graph',
                                      style={
                                          'display': 'inline-block'
                                      }),
                             html.Div(
                                 id='barplot-good-graph',
                                 style={'display': 'inline-block'})
                         ]),
                         html.Div(id='barplot-explanation',
                                  className='explain'),
                     ],
                              style={'display': 'inline-block'})
                 ])
         ])),
Beispiel #15
0
                        value="經濟學系",
                        )
        ],
        style={"width": "30%", "margin": "auto", "align-items": "center", "justify-content": "center"},
    ),
    html.Section (
        id="container",
        children=[
            html.Section(
                id="sum-stat-pane",
                className="pane",
                children=[
                    html.Div(className="sum_stat", children=[html.H1(id='one_sem_pct'), html.P("% 的學生交換一學期")]),
                    html.Div(className="sum_stat", children=[html.H1(id='num_students'), html.P("個學生參加交換")]),
                    html.Div(className="sum_stat", children=[html.H1(id='num_countries'), html.P("個國家")]),
                    html.Div(className="sum_stat", children=[html.H1(id='num_schools'), html.P("個學校")]),
                    # html.Div(className="sum_stat", id='num_students', children=[]),
                    # html.Div(className="sum_stat", id='num_countries', children=[]),
                    # html.Div(className="sum_stat", id='num_schools', children=[]),
                ]
            ),
            html.Div(className="pane", children=dcc.Graph(id='hist_year', figure={})),
            html.Div(className="pane", children=dcc.Graph(id='hist_country', figure={})),
            html.Div(className="pane", children=dcc.Graph(id='hist_school', figure={})),
        ]
    )
])
# ------------------------------------------------------------------------------
# Connect the Plotly graphs with Dash Components
@app.callback(
    [Output(component_id='one_sem_pct', component_property='children'),
def serve_layout():

    custom_tab_selected = {'borderTop': '6px solid #26BE81'}

    return [
        html.Div([
            html.Br(),
            html.Br(),
            html.H1("Why We Don't Live Together",
                    style={
                        'font-size': '4.5rem',
                        'font-weight': 'bold',
                        'color': '#26BE81'
                    }),
            html.Br(),
            html.
            H3("Replicating residential segregation using agent-based modeling"
               ),
            html.Br(),
            html.Br(),
            html.Img(src='/assets/philadelphia_segregation_dark.png',
                     style={'max-width': '100%'}),
            html.Div([
                html.Section(
                    '''Figure 1: Ethnic populations in Philadelphia using data from the 2010 Census.
                Source:'''),
                html.
                A('''WashingtonPost''',
                  href=
                  'https://www.washingtonpost.com/graphics/2018/national/segregation-us-cities/',
                  style={'display': 'inline'})
            ]),
            html.Br(),
            html.Br(),
            html.Ul([
                html.
                Li('''We reproduce Thomas Schelling's landmark experiment from the 1970s that demonstrates housing
                segregation patterns using agent-based modeling (ABM).'''),
                html.
                Li('''This experiment shows that housing segregation, where individuals cluster with similar people,
                 can result even if all people have a preference for living in integrated neighborhoods.'''
                   ),
                html.
                Li('''This experiment is often used as an introduction to agent-based modeling and demonstrates
                that counter-intuitive results can emerge at the societal level due to the complexities of group
                dynamics.'''),
            ],
                    style={'font-size': '1.25rem'}),
            html.Br(),
            html.Br(),
        ],
                 style={
                     'margin': 'auto',
                     'text-align': 'left',
                     'max-width': '750px'
                 }),

        # intro
        html.Div(
            [
                html.Br(),
                html.H3('''Introduction'''),
                html.
                P('''Social scientists have observed that people of similar ethnicities tend to cluster together,
            leading to predominantly White, Black or Hispanic neighborhoods rather than a multiracial mixed
            alternative. Why is this the case? Some might argue that racial progress, while volatile, has increased
            over the decades and that enduring segregation must therefore be the result of structural disparities.'''
                  ),
                html.
                P('''But do inclusive racial attitudes necessarily imply integrated racial outcomes? A perfectly
            intuitive line of thought would be if people were tolerant and inclusive in their individual outlooks,
            that the population as a whole would in turn develop into an integrated society.  Unfortunately, this
            may be an example of when our intuition is faulty and a perfectly plausible theory fails to reflect
            a complex reality.'''),
                html.
                P('''This tool will demonstrate the application of agent-based modeling (ABM) in explaining
            residential segregation and also expose the concept and process of ABM itself.  Agent-based modeling
            is a bottom-up framework that involves programming individual agents with behavior and goals and
            simulating their interactions with each other and the environment. The goal of this app is to show
            how ABM is often used to analyze group behavior and how ABM can reveal unexpected dynamics that emerge from
            seemingly simple setups.'''),
                html.Br(),
                html.H3('''Residential Segregation'''),
                html.
                P('''Chicago is one of the most diverse metropolises in America with nearly 3 million residents
            and large proportions from each major ethnic group (56% White, 32% Black, 29% Hispanic and 7% Asian).
            Chicago however, is also one of the most segregated big cities in America. For example, a map of
            demographic information using the latest 2010 census shows distinct neighborhoods bounded by ethnic
            composition.'''),
                html.Br(),
            ],
            style={
                'font-size': '1.1rem',
                'margin': 'auto',
                'max-width': '750px',
                'text-align': 'left',
            }),

        # example real segregation maps
        html.Div([
            html.Hr(),
            html.H5('Figure 1: Observed Segregation Across Two Cities'),
            html.Br(),
            dbc.Row([
                dbc.Col([
                    html.Div(
                        [html.Img(src='/assets/chicago_segregation_dark.png')],
                        style={
                            'height': '200px',
                            'width': '300px'
                        }),
                ],
                        width=6),
                dbc.Col([html.Img(src='/assets/nyc_segregation_dark.png')],
                        width=6),
            ],
                    no_gutters=False),
            html.Br(),
            html.Div(
                '''Each dot represents 150 people from the 2010 Census. Source: WashingtonPost'''
            ),
            html.Hr(),
        ],
                 style={
                     'margin': 'auto',
                     'text-align': 'left',
                     'max-width': '1000px'
                 }),
        html.Br(),
        html.Div(
            [
                html.
                P('''The reality of racial segregation has many contributing factors, including deliberate government
            policies that have historically segregated minorities via land use regulations
            or mortgage discrimination. Furthermore, a more passive phenomena has been racial steering whereby real
            estate brokers are likely to steer clients towards particular neighborhoods based on race.'''
                  ),
                html.
                P('''In addition to these external factors however, housing patterns may also stem from personal
            preferences. These include households favoring certain neighborhoods due to proximity to family, the
            availability of familiar food options or the possibility of forming social networks with people of similar
            values. Collectively these preferences for amount to what social scientists call an in-group preference, or
            a preference for one’s own culture, and which will be the focus of this app.'''
                  ),
                html.
                P('''Though this app will use residential segregation as a way to discuss ABM, it is not a
            comprehensive overview of all the applicable social, political and economic dynamics. While computer
            scientists are able to contribute to the conversation, as will be demonstrated in this app, a serious
            discussion of this topic deserves a multidisciplinary approach with perspectives from historians,
            statisticians, economists and others.''',
                  style={
                      'background-color': 'lightyellow',
                      'border': '2px solid black',
                      'border-radius': '20px',
                      'padding': '6px'
                  }),
                html.Br(),
                html.H3('''Agent-based Modeling Philosophy'''),
                html.
                P('''The objective of agent-based modeling is to replicate reality using a computer
            simulation that is as simple as possible. In our case, we want to simulate residential dynamics that
            reproduce observed segregation patterns, or the clustering of different groups, based on as few factors
            as possible. If we are able to replicate observed reality we will have “explained”
            housing segregation in the sense that our simulation shows that housing segregation is an outcome of our
            programmed assumptions. '''),
                html.
                P('''It’s important to note that within the ABM framework “explanation” has a different meaning
            than in statistics. Whereas in statistics explanation is associated with correlation, within ABM the
            meaning of explanation has connotations of causality since we explicitly define cause and effect dynamics
            within our simulation (the challenge however is to encode accurate cause and effect relationships).
            Furthermore, whereas in statistics we usually try to control for many factors by including
            different variables in the analysis, within ABM it is preferable to construct a parsimonious model to
            show the minimum required assumptions that would be required to reproduce reality. '''
                  ),
                html.Br(),
                html.H3('''Simulation Methodology'''),
                html.
                P('''To program our segregation simulation we model a simplified reality. We represent a city as a
            2D grid, like a checkerboard, and each square in the grid represents a residence that can be occupied by
            a household. Our course, real neighborhoods do not physically look like a crowded checkerboard but we assume
            that this simplification, amongst many assumptions we’ll make, is not material to the analysis.'''
                  ),
                html.
                P('''Next we assume in our model that there are two types of households (say White and Asian)
            and that each household is primarily concerned about belonging to a neighborhood filled with families
            similar to themselves. To measure the similarity of a neighborhood with respect to a given household, we
            define a neighborhood as the adjacent houses within some radius and then calculate the proportion of
            households that belong to the “same” group and the proportion of households belonging to the “other” group.
            Depending on a household’s tolerance level, the household can then either decide to move to a new
            neighborhood or to stay.'''),
            ],
            style={
                'font-size': '1.1rem',
                'margin': 'auto',
                'max-width': '750px',
                'text-align': 'left',
            }),
        html.Br(),

        # interactive tool: example neighborhood similarity calculation
        html.Div(
            [
                html.Hr(),
                html.Br(),
                html.H4('Figure 2: Sample Similarity Calculation'),
                html.Br(),
                dbc.Row([

                    # left column
                    dbc.Col([html.Div(id='sample-calc-grid')], width=6),

                    # right column
                    dbc.Col([
                        html.Div(
                            '''We calculate the comfort of the center household, marked by the X,
                        by counting the number of similar and dissimilar households in the surrounding
                        neighborhood. In this example, assume that a household would prefer to live
                        in a neighborhood where at least 51% of her neighbors are like her.'''
                        ),
                        html.Br(),
                        dbc.Row([
                            dbc.Col([
                                html.Div('Select neighborhood:',
                                         style={'color': 'grey'}),
                                dcc.Dropdown(
                                    id='radius-input',
                                    options=[{
                                        'label': "Radius {}".format(i),
                                        'value': i
                                    } for i in range(1, 5)],
                                    value=2,
                                    clearable=False,
                                ),
                            ],
                                    width=5),
                            dbc.Col('', width=1),
                            dbc.Col([
                                html.Div([
                                    dt.DataTable(id='sample-table',
                                                 columns=sample_columns,
                                                 style_cell_conditional=
                                                 sample_style_cell_conditional,
                                                 style_data_conditional=
                                                 sample_style_data_conditional,
                                                 style_as_list_view=True)
                                ])
                            ],
                                    width=6),
                        ]),
                        html.Br(),
                        html.Div(id='sample-conclusion',
                                 style={'font-weight': 'bold'})
                    ],
                            width=6),
                ]),
                html.Br(),
                html.Hr(),
                html.Br(),
            ],
            style={
                'margin': 'auto',
                'text-align': 'left',
                'max-width': '900px'
            }),
        html.Div(
            [
                html.
                P('''Using this setting, we can plan our simulation. Below we present the methodology
            at three levels of abstraction, ranging from a qualitative description to technical code.'''
                  ),
                html.Br(),
                html.Br(),
                html.Div([
                    dcc.Tabs(id='methodology-tabs',
                             value='tab-1',
                             children=[
                                 dcc.Tab(label='Intuition',
                                         value='tab-1',
                                         selected_style=custom_tab_selected),
                                 dcc.Tab(label='Pseudocode',
                                         value='tab-2',
                                         selected_style=custom_tab_selected),
                                 dcc.Tab(label='Code',
                                         value='tab-3',
                                         selected_style=custom_tab_selected)
                             ]),
                    html.Br(),
                    html.Br(),
                    html.Div(id='methodology-content'),
                ],
                         style={
                             'border': '4px solid #26BE81',
                             'padding': '5%'
                         }),
                html.Br(),
                html.Br(),
                html.H3('''Results and Analysis'''),
                html.Br(),
                html.Div([
                    html.
                    P('''Our analysis proceeds using the methodology described above, which is based around the
                simple premise that households might have a preference to live in a neighborhood that reflects their
                ethnic identity. When that preference is very strong, a White household might only be content if 90%
                of their neighbors are also White. On the other hand, if the preference is relatively weak then a
                Hispanic household might be perfectly content in a neighborhood that is only 20% Hispanic. '''
                      ),
                    html.
                    P('''Before we run the experiment it is an opportune time, and also good research practice,
                to ask what are our expectations (do we have any hypotheses)? Without overthinking the question,
                here are two uneducated though reasonable guesses on what we might observe from the simulation:'''
                      ),
                    html.Ul([
                        html.Li(
                            dcc.Markdown(
                                '''*Inclusive racial attitudes should lead to integrated neighborhoods.* If
                    households have a low in-group preference, then we expect to see more mixed neighborhoods over time.
                    Conversely, if households have a high in-group preference, then we would expect to see more
                    segregated neighborhoods.''')),
                        html.Li(
                            dcc.Markdown(
                                '''*The level of diversity in a neighborhood is likely to be equal to the average
                    preference level.* If the average household preference is 55%, then we might expect that that the
                    average neighborhood will be composed of a 55-45 split between the two groups (or replace 55% with
                    any percentage and matching split)'''))
                    ]),
                    html.
                    P('''Below we run our simulation using a small 16x32 grid with around 512 households.
                Each household has a relatively inclusive in-group preference of 40%.'''
                      ),
                ]),
                html.Br(),
                html.Br(),
            ],
            style={
                'font-size': '1.1rem',
                'margin': 'auto',
                'max-width': '750px',
                'text-align': 'left',
            }),
        html.Div([
            html.Hr(),
            html.H4('Figure 3: Migration Simulation'),
            dbc.Row([
                dbc.Col([
                    html.Img(src='/assets/test_gif.gif'),
                ], width=7),
                dbc.Col([
                    html.
                    H5('''From an initial integrated state, two populations eventually segregate over
                    time.'''),
                    html.Br(),
                    html.
                    P('''Each square represents a household that considers whether to remain or move to a different
                    spot in the grid (black squares are empty homes and households can move into them).
                    Households make the decision based on a simple logic: Stay if at least 40% of
                    its neighbors are a similar color, or else move otherwise. Even though everyone is content
                    to be a minority and live in an integrated neighborhood, over time the grid becomes
                    segregated with a clear separation between the two groups in comparison to the starting state.'''
                      )
                ],
                        width=5),
            ]),
            html.Hr(),
        ],
                 style={
                     'margin': 'auto',
                     'text-align': 'left',
                     'max-width': '1100px'
                 }),
        html.Br(),
        html.Br(),
        html.Div(
            [
                html.
                P('''The simulation shows that a segregated outcome results in the end even though 1)
            the landscape starts from an integrated state and 2) all the households are not averse to living
            in a mixed community. '''),
                html.
                P('''Why does this occur? Even though the households were placed at random, by chance a small number
            of households might find themselves as an uncomfortable minority (<40% average similarity in this case).
            When these households move out of their neighborhood, or new households move into a
            neighborhood, this will in turn have a small impact that causes a small number of household to want to move
            in the next period. Each time a household moves, it has cascading effects that compel other households to
            move later on until the end result is a system characterized by homogeneous neighborhoods. '''
                  ),
                html.
                P('''We rerun the simulation while varying the in-group preference levels in order to investigate
            whether more inclusive attitudes are associated with more integrated outcomes. At each preference level
            that we test, we run multiple simulations and record the average outcome by calculating the average
            similarity of the neighborhood from the point-of-view of each household.'''
                  ),
                html.
                P('''In the below chart (Figure 4) we see that below a 25% preference level, the neighborhoods in the
            last period are mostly heterogenous with an average similarity that doesn’t change from the initial
            integrated state. '''),
                html.
                P('''For preference levels above 25% however, the system crosses a tipping point and the end states
            start to show more segregated outcomes, rising to average neighborhood similarity of 90% given a 50% in-group
            preference level. Note that under our simulation the average similarity will never grow to 100% given that
            households on the border between two segregated neighbors will still count some out-of-group members in
            their neighborhood.'''),
                html.Br(),
                html.Br(),
                html.
                H4('''Figure 4: Outcomes for Various In-group Preference Levels'''
                   ),
                html.Br(),
                dcc.Graph(figure=figure4),
                html.Br(),
                html.Br(),
                html.
                P('''These results are consistent with our original prediction that rising in-group preference
            levels are associated with higher rates of homogeneous neighborhoods. Our predictions however underestimated
            the level of in-group preference that was needed to generate segregated neighborhoods.'''
                  ),
                html.
                P('''We present two more charts to show how the systems evolved over the simulation iterations.
            Figure 5 shows that the average similarity at each time step and illustrates the rate of segregation.
            Relatedly, Figure 6 shows the percentage of the population that is unhappy in their neighborhood over
            time. '''),
                html.Br(),
                html.Br(),
            ],
            style={
                'font-size': '1.1rem',
                'margin': 'auto',
                'max-width': '750px',
                'text-align': 'left',
            }),
        html.Div(
            [
                dbc.Row([
                    dbc.Col([
                        html.H4('''Figure 5: Mean Similarity Over Time'''),
                        dcc.Graph(figure=figure5)
                    ],
                            width=6),
                    dbc.Col([
                        html.H4('''Figure 6: Discontents Over Time '''),
                        dcc.Graph(figure=figure6)
                    ],
                            width=6)
                ])
            ],
            style={
                'font-size': '1.1rem',
                'margin': 'auto',
                'max-width': '1100px',
                'text-align': 'left',
            }),
        html.Br(),
        html.Br(),
        html.Div(
            [
                html.
                P('''Careful observation of Figure 5 shows the average similarity rises faster for medium levels of
            in-group preference than for stronger levels. For example, the series for an in-group preference of 40%
            crosses the 75% average similarity level before the series for the 50% in-group preference. This is
            mostly a function of the simulation setup and the frictions that occur when many households are seeking
            to move but only a limited number of vacant households are available. '''
                  ),
                html.
                P('''For example, a 60% in-group preference level will eventually produce a higher average similarity
            than a 50% in-group preference but the process moves considerably slower, as seen in Figure 5. Taken to an
            extreme, a 99% in-group preference will paradoxically never approach a segregated state in this simulation
            because households will never be content, will always be moving, and the system will never stabilize enough
            to allow the formation of homogeneous neighborhoods. '''),
                html.Br(),
                html.Br(),
                html.H4('''Conclusion: Thoughts on Segregation'''),
                html.
                P('''If we take this simple simulation’s conclusions seriously, we may come around to a pessimistic
            view that even if we were to eliminate all forms of structural discrimination, we’d find that those were not
            necessary to produce segregation and that preferences alone are totally sufficient.'''
                  ),
                html.P([
                    html.Span(
                        '''As stated earlier however, this paper is not intended to speak to the full complexity of
            segregation nor on the efficacy of potential corrections. Ultimately though, the Schelling model
            shows that preferences may be an important part of the conversation insofar that preferences can possibly
            “explain” residential segregation. As summarized by '''),
                    html.Span(
                        html.A(
                            '''Clark and Fosset:''',
                            href='https://www.pnas.org/content/105/11/4109')),
                ]),
                html.Div(
                    [
                        dcc.Markdown(
                            '''*The more important distinction in the literature is the distinction between preferences and
            discrimination… policy options for promoting integration differ dramatically for these two
            factors.*'''),
                        dcc.Markdown(
                            '''*Discrimination is prohibited by law and is subject to a variety of legal remedies. Preferences
            are outside the purview of fair housing law and remedies, if sought, will necessarily be fundamentally
            different. In view of this, it is crucial to gain a better understanding of the impact preferences may have
            on segregation.*'''),
                    ],
                    style={
                        'background-color': 'lightyellow',
                        'border': '2px solid black',
                        'border-radius': '20px',
                        'padding': '6px'
                    }),
                html.Br(),
                html.Br(),
                html.H4('''Conclusion: Thoughts on ABM'''),
                html.
                P('''The segregation model presented here is relatively simple, a version 1.0 if you will, that was
            first presented in the 1970s. As that was a time before personal computers, it is especially impressive
            to think that the initial research was developed by flipping coins and moving pieces around a
            board by hand. With the benefit of computational power, researchers have since expanded on this framework
            in numerous ways including:'''),
                html.Ul([
                    html.
                    Li('''Expanding the number of ethnic groups from two to many.'''
                       ),
                    html.
                    Li('''Modelling heterogenous preference levels across households-not everyone has the same
                in-group preference level.'''),
                    html.
                    Li('''Drawing richer models of landscapes by incorporating inclusive or exclusive community
                focal points such as commercial centers or churches.'''),
                    html.
                    Li('''Modelling dynamic household preferences that evolve over time and in reaction to their
                environment.'''),
                    html.
                    Li('''Incorporating other household motivations based on income, neighborhood affordability
                and non preference-based factors.''')
                ]),
                html.
                P('''Outside of modeling segregation, ABM has also spread with varying degrees of success across
            other fields such biology and physics. As of 2021, ABM has most recently and notably been used in
            epidemiology to model the spread of the coronavirus across communities and forecast transmission,
            hospitalization and fatality scenarios.'''),
                html.
                P('''Within finance and economics however, ABM has arguably not produced a large body of insights,
            though it does maintain its own group of advocates and there are notable achievements. For example, ABM
            can be used to explain the existence of so-called "fat-tails" in asset returns and volatility clustering
            as the systemic outcome of interactions between fundamental and technical traders. In economics, ABM may
            also explain economic contractions as the endogenous outcome of economic actors rather than modeling
            recessions as external shocks. We think that these are interesting applications of ABM with novel results.
            We hope to cover these in depth in the future.'''),
                html.Br(),
                html.Br(),
                html.P([
                    html.Span(['Github ']),
                    html.Span([
                        html.
                        A('''website ''',
                          href=
                          'https://github.com/jbortfeld/QuantView/blob/master/apps/schelling_segregation.py'
                          )
                    ]),
                    html.Span('and '),
                    html.Span(
                        html.
                        A('analysis.',
                          href=
                          'https://github.com/jbortfeld/QuantView/tree/master/notebooks/Segregation/abm.ipynb'
                          )),
                ]),
            ],
            style={
                'font-size': '1.1rem',
                'margin': 'auto',
                'max-width': '750px',
                'text-align': 'left',
            }),
        html.Br(),
        html.Br(),
    ]
Beispiel #17
0
                                          colorscale=colors,
                                          symbol='triangle-up'),
                              name='test data')

    return train_scatter, auc_curve, confusion, contours, test_scatter


# Control Panel
panel = html.Section(className='card',
                     style=(dict(padding=20)),
                     children=[
                         html.P('Dataset size'),
                         dcc.Slider(id='dataset-size',
                                    min=100,
                                    max=1000,
                                    value=500,
                                    step=100),
                         html.P('Noise'),
                         dcc.Slider(id='noise',
                                    min=0.0,
                                    max=1,
                                    value=0.3,
                                    step=0.1),
                     ])

DEFAULT_LAYOUT = go.Layout(legend=dict(orientation='h'),
                           margin=dict(l=10, r=10, t=5, b=50))

# Application Layout using Boostrap CSS grid system
app.layout = html.Div(className="container-fluid",
                      children=[
                          html.Nav(className='navbar',
Beispiel #18
0
 id='Block_home_Page',
 children=[
     html.Section(
         id='home_page_left',
         children=[
             html.Br(),
             html.
             H2('Welcome to the API who analyse emotions in your sentences'
                ),
             html.Br(),
             modal,
             html.Br(),
             html.Br(),
             html.Br(),
             html.Br(),
             dcc.Textarea(
                 id='text_box_home',
                 placeholder=
                 'Enter your text and show the predicted emotion',
                 #style={'width': '95%', 'color':'#91dfd2'}
             ),
             html.Br(),
             html.Div(id='div_submit_button',
                      children=[
                          html.Button('Submit',
                                      id='submit_button',
                                      n_clicks=0),
                      ]),
             html.Div(id='output_container'),
         ]),
     html.Section(
         id='home_page_right',
Beispiel #19
0
                               className="mr-1",
                               style={'textAlign': 'center'}),
                    justify="center",
                    form=True),
        ],
                 style={
                     "padding-left": "4rem",
                     "padding-right": "4rem",
                     "text-size": "4rem"
                 },
                 className='pretty_container six columns'),
        html.Section(id="slideshow",
                     children=[
                         html.Div(id="slideshow-container",
                                  children=[
                                      html.Div(id="image"),
                                      dcc.Interval(id='interval',
                                                   interval=6000),
                                  ]),
                     ],
                     className='pretty_container six columns')
    ]),
],
                 className="twelve columns")

### Photo Carousel
Photo1 = app.get_asset_url('FieldStation.jpg')
Photo2 = app.get_asset_url('HarrisSampling.jpg')
Photo3 = app.get_asset_url('Tank.jpg')


@app.callback(Output('image', 'children'), [Input('interval', 'n_intervals')])
Beispiel #20
0
def get_imprint_layout(app):
    return html.Div(children=[
        get_header(app),
        html.Section(
            className="legal",
            children=[
                html.Div(children=[
                    html.Div(
                        className="legal__wrap",
                        children=[
                            html.H2("Imprint"),
                            html.P([
                                "Publisher:",
                                html.Br(),
                                "This website is operated by the Reiner Lemoine Institut gGmbH",
                                html.Br(),
                                html.Br(),
                                "Management:",
                                html.Br(),
                                "Dr. Kathrin Goldammer",
                                html.Br(),
                                html.Br(),
                                "Postal address:",
                                html.Br(),
                                "Reiner Lemoine Institut gGmbH",
                                html.Br(),
                                "Rudower Chaussee 12",
                                html.Br(),
                                "12489 Berlin",
                                html.Br(),
                                html.Br(),
                                "Telephone +49 (0)30 1208 434 0",
                                html.Br(),
                                "Fax +49 (0)30 1208 434 99",
                                html.Br(),
                                html.Br(),
                                "Handelsregister Berlin – HRB 124659 B",
                                html.Br(),
                                html.Br(),
                                "Tax number: 27/602/55211",
                                html.Br(),
                                html.Br(),
                                "VAT-Id.: DE274491408",
                                html.Br(),
                                html.Br(),
                                "Disclaimer:",
                                html.Br(),
                                html.Br(),
                                "1. Haftungshinweis",
                                html.Br(),
                                "Die Inhalte sind mit größter Sorgfalt recherchiert. Dennoch übernimmt der Autor keinerlei Gewähr für die Aktualität, Korrektheit, Vollständigkeit oder Qualität der bereitgestellten Informationen. Haftungsansprüche gegen den Autor, welche sich auf Schäden materieller oder ideeller Art beziehen die durch die Nutzung oder Nichtnutzung der dargebotenen Informationen bzw. durch die Nutzung fehlerhafter und unvollständiger Informationen verursacht wurden, sind grundsätzlich ausgeschlossen, sofern seitens des Autors kein nachweislich vorsätzliches oder grob fahrlässiges Verschulden vorliegt. Alle Angebote sind freibleibend und unverbindlich. Der Autor behält es sich ausdrücklich vor, Teile der Seiten oder das gesamte Angebot ohne gesonderte Ankündigung zu verändern, zu ergänzen, zu löschen oder die Veröffentlichung zeitweise oder endgültig einzustellen.",
                                html.Br(),
                                html.Br(),
                                "2. Verweise und Links",
                                html.Br(),
                                "Bei direkten oder indirekten Verweisen auf fremde Internetseiten („Links”), die außerhalb des Verantwortungsbereiches des Autors liegen, würde eine Haftungsverpflichtung ausschließlich in dem Fall in Kraft treten, in dem der Autor von den Inhalten Kenntnis hat und es ihm technisch möglich und zumutbar wäre, die Nutzung im Falle rechtswidriger Inhalte zu verhindern. Der Autor erklärt daher ausdrücklich, dass zum Zeitpunkt der Linksetzung die entsprechenden verlinkten Seiten frei von illegalen Inhalten waren. Der Autor hat keinerlei Einfluss auf die aktuelle und zukünftige Gestaltung und auf die Inhalte der gelinkten/verknüpften Seiten. Deshalb distanziert er sich hiermit ausdrücklich von allen Inhalten aller gelinkten /verknüpften Seiten, die nach der Linksetzung verändert wurden. Diese Feststellung gilt für alle innerhalb des eigenen Internetangebotes gesetzten Links und Verweise sowie für Fremdeinträge in vom Autor eingerichteten Gästebüchern, Diskussionsforen und Mailinglisten. Für illegale, fehlerhafte oder unvollständige Inhalte und insbesondere für Schäden, die aus der Nutzung oder Nichtnutzung solcherart dargebotener Informationen entstehen, haftet allein der Anbieter der Seite, auf welche verwiesen wurde, nicht derjenige, der über Links auf die jeweilige Veröffentlichung lediglich verweist.",
                                html.Br(),
                                html.Br(),
                                "3. Urheber- und Kennzeichenrecht",
                                html.Br(),
                                "Der Autor ist bestrebt, in allen Publikationen die Urheberrechte der verwendeten Grafiken, Tondokumente, Videosequenzen und Texte zu beachten, von ihm selbst erstellte Grafiken, Tondokumente, Videosequenzen und Texte zu nutzen oder auf lizenzfreie Grafiken, Tondokumente, Videosequenzen und Texte zurückzugreifen. Alle innerhalb des Internetangebotes genannten und ggf. durch Dritte geschützten Marken- und Warenzeichen unterliegen uneingeschränkt den Bestimmungen des jeweils gültigen Kennzeichenrechts und den Besitzrechten der jeweiligen eingetragenen Eigentümer. Allein aufgrund der bloßen Nennung ist nicht der Schluss zu ziehen, dass Markenzeichen nicht durch Rechte Dritter geschützt sind! Das Copyright für veröffentlichte, vom Autor selbst erstellte Objekte bleibt allein beim Autor der Seiten. Eine Vervielfältigung oder Verwendung solcher Grafiken, Tondokumente, Videosequenzen und Texte in anderen elektronischen oder gedruckten Publikationen ist ohne ausdrückliche Zustimmung des Autors nicht gestattet.",
                                html.Br(),
                                html.Br(),
                                "4. Rechtswirksamkeit dieses Haftungsausschlusses",
                                html.Br(),
                                "Dieser Haftungsausschluss ist als Teil des Internetangebotes zu betrachten, von dem aus auf diese Seite verwiesen wurde. Sofern Teile oder einzelne Formulierungen dieses Textes der geltenden Rechtslage nicht, nicht mehr oder nicht vollständig entsprechen sollten, bleiben die übrigen Teile des Dokumentes in ihrem Inhalt und ihrer Gültigkeit davon unberührt.",
                            ]),
                        ]),
                    get_footer()
                ])
            ],
        )
    ])
Beispiel #21
0
 html.Section(
     style={},
     children=[
         html.Article(
             style={
                 'display': 'flex',
                 'justify-content': 'space-around',
                 'margin-top': '9vh',
                 'margin-bottom': '8vh'
             },
             children=[
                 html.Div(
                     style={
                         'height': '40vh',
                         'width': '23vw'
                     },
                     children=[
                         html.P(style={
                             'text-align': 'center',
                             'color': '#DCDCDC',
                         },
                                children=[
                                    'Cercle des corrélations F1 et F2'
                                ]),
                         html.Img(
                             src=app.get_asset_url('../assets/F1.png'),
                             style={
                                 'height': '40vh',
                                 'width': '23vw'
                             })
                     ]),
                 html.Div(style={
                     'height': '40vh',
                     'width': '23vw'
                 },
                          children=[
                              html.P(
                                  style={
                                      'text-align': 'center',
                                      'color': '#DCDCDC',
                                  },
                                  children=[
                                      'Cercle des corrélations F3 et F4'
                                  ]),
                              html.Img(src=app.get_asset_url(
                                  '../assets/F3-F4.png'),
                                       style={
                                           'height': '40vh',
                                           'width': '23vw'
                                       })
                          ]),
                 html.Div(style={
                     'height': '40vh',
                     'width': '23vw'
                 },
                          children=[
                              html.P(
                                  style={
                                      'text-align': 'center',
                                      'color': '#DCDCDC',
                                  },
                                  children=[
                                      'Cercle des corrélations F5 et F6'
                                  ]),
                              html.Img(src=app.get_asset_url(
                                  '../assets/F5-F6.png'),
                                       style={
                                           'height': '40vh',
                                           'width': '23vw'
                                       })
                          ]),
                 html.Div(style={
                     'height': '40vh',
                     'width': '23vw',
                 },
                          children=[
                              html.P(
                                  style={
                                      'text-align': 'center',
                                      'color': '#DCDCDC',
                                  },
                                  children=[
                                      'Cercle des corrélations F7 et F8'
                                  ]),
                              html.Img(src=app.get_asset_url(
                                  '../assets/F7-F8.png'),
                                       style={
                                           'height': '40vh',
                                           'width': '23vw'
                                       })
                          ]),
             ]),
         html.H2(style={
             'text-align': 'center',
             'color': '#DCDCDC',
             'margin-top': '10vh',
             'margin-bottom': '3vh'
         },
                 children=["Eboulis des valeurs propres"]),
         html.Article(style={},
                      children=[
                          html.Div(style={
                              'height': '70vh',
                              'width': '62vw',
                              'margin-top': '10vh'
                          },
                                   children=[
                                       dcc.Graph(figure=fig2_1),
                                   ]),
                          html.Div(style={}, children=[modal])
                      ])
     ])
Beispiel #22
0
 html.Section(style={
     'height': '70vh',
     'display': 'flex',
     'justify-content': 'space-around'
 },
              children=[
                  html.Article(style={
                      'backgroundColor': '#181B1E',
                      'height': '70vh',
                      'width': '66vw',
                      'padding-top': '1.2vh',
                      'border-radius': '15px'
                  },
                               children=[
                                   dcc.Graph(figure=fig),
                               ]),
                  html.Article(style={
                      'backgroundColor': '#212529',
                      'height': '70vh',
                      'width': '30vw'
                  },
                               children=[
                                   html.Div(style={
                                       'backgroundColor': '#181B1E',
                                       'height': '33vh',
                                       'width': '30vw',
                                       'border-radius': '15px'
                                   },
                                            children=[]),
                                   html.Div(style={
                                       'backgroundColor': '#181B1E',
                                       'margin-top': '4vh',
                                       'height': '33vh',
                                       'width': '30vw',
                                       'border-radius': '15px'
                                   },
                                            children=[])
                               ]),
              ]),
        html.Section([

            # Line 1 : KPIS - World
            html.Div(
                id='world_line_1',
                children=[
                    html.Div(children=[
                        '­Ъџе Confirmed',
                        html.Br(), world['total_confirmed']
                    ],
                             id='confirmed_world_total',
                             className='mini_container'),
                    html.Div(children=[
                        '­ЪЈА Recovered',
                        html.Br(), world['total_recovered']
                    ],
                             id='recovered_world_total',
                             className='mini_container'),
                    html.Div(children=[
                        ' Рџ░№ИЈ Victims',
                        html.Br(), world['total_deaths']
                    ],
                             id='deaths_world_total',
                             className='mini_container'),
                ],
            ),
            # html.Br(),
            links,

            # Line 2 : MAP - WORLD
            html.Div(
                id='world_line_2',
                children=[
                    dcc.Graph(id='world_map',
                              figure=world['figure'],
                              config={'scrollZoom': False}),
                ],
            ),
            # html.Br(),
        ]),
Beispiel #24
0
page_1_layout = html.Section([
    #######################################################################
    # cabecera
    #######################################################################
    html.Header ([
        html.Div ([
            html.Div ([],className='fa fa-bars tooltips')
        ],className='sidebar-toggle-box')
        ,html.A ([
            html.B ([
                html.Img(src='assets/usuario.jpg', className='img-circle logo')
                ,'CNC'
                ,html.Span (' ECAR')
            ])
        ],href='',className='logo')
        ,html.Div ([
            html.Ul ([
                html.Li (
                    html.A ([
                        dcc.Link('DASHBOARD', href='/')
                    ],className='logout')
                )
            ],className='nav pull-right top-menu')
        ],className='top-menu')
        ,html.Div ([
            html.Ul ([
                html.Li (
                    html.A ([
                        dcc.Link('MODEL', href='/page-2')
                    ],className='logout')
                )
            ],className='nav pull-right top-menu')
        ],className='top-menu')
        ,html.Div ([
            html.Ul ([
                html.Li (
                    html.A ([
                        dcc.Link('INFORMACIÓN', href='/page-3')
                    ],className='logout')
                )
            ],className='nav pull-right top-menu')
        ],className='top-menu')
    ],className='header black-bg')
    #######################################################################
    # sidebar
    #######################################################################
    ,html.Section ([
        html.Section ([
            ###############################################################
            # contenido
            ###############################################################
            html.Div ([
                    #######################################################
                    # background
                    #######################################################
                    html.Img(src='assets/background.jpg', className='background_img')
            ],className='centered')
            ,html.Div ([
                html.Div (className='col-md-1')
                ###########################################################
                # Andres
                ##########################################################
                ,html.Div ([
                    html.Img(src='assets/andres.jpg', className='team_img grayscale')
                    ,html.H3('Andres Lopez', className='centered')
                    ,html.P ([
                        'Engineer'
                    ],className='opacity')
                    ,textos.about_01
                    ,html.Div([
                        html.A ([
                            html.I(className='fa fa-envelope')
                            ,html.Span('CONTACT')
                        ], href='mailto:[email protected]', className='contact')
                    ], className='centered')
                ],className='col-md-2 about')
                ###########################################################
                # Angelica
                ##########################################################
                ,html.Div ([
                    html.Img(src='assets/angelica.jpg', className='team_img grayscale')
                    ,html.H3('Angelica Castillo', className='centered')
                    ,html.P ([
                        'Statistician'
                    ],className='opacity')
                    ,textos.about_02
                    ,html.Div([
                        html.A ([
                            html.I(className='fa fa-envelope')
                            ,html.Span('CONTACT')
                        ], href='mailto:[email protected]', className='contact')
                    ], className='centered')
                ],className='col-md-2 about')
                ###########################################################
                # Yesica
                ##########################################################
                ,html.Div ([
                    html.Img(src='assets/yesica.jpg', className='team_img grayscale')
                    ,html.H3('Yesica Salas', className='centered')
                    ,html.P ([
                        'Mathematician'
                    ],className='opacity')
                    ,textos.about_03
                    ,html.Div([
                        html.A ([
                            html.I(className='fa fa-envelope')
                            ,html.Span('CONTACT')
                        ], href='mailto:[email protected]', className='contact')
                    ], className='centered')
                ],className='col-md-2 about')
                ###########################################################
                # Mildreck
                ##########################################################
                ,html.Div ([
                    html.Img(src='assets/mildreck.jpg', className='team_img grayscale')
                    ,html.H3('Mildreck Cubillos', className='centered')
                    ,html.P ([
                        'Economist'
                    ],className='opacity')
                    ,textos.about_04
                    ,html.Div([
                        html.A ([
                            html.I(className='fa fa-envelope')
                            ,html.Span('CONTACT')
                        ], href='mailto:[email protected]', className='contact')
                    ], className='centered')
                ],className='col-md-2 about')
                ###########################################################
                # Camilo
                ##########################################################
                ,html.Div ([
                    html.Img(src='assets/camilo.jpg', className='team_img grayscale')
                    ,html.H3('Camilo Amezquita', className='centered')
                    ,html.P ([
                        'Engineer'
                    ],className='opacity')
                    ,textos.about_05
                    ,html.Div([
                        html.A ([
                            html.I(className='fa fa-envelope')
                            ,html.Span('CONTACT')
                        ], href='mailto:[email protected]', className='contact')
                    ], className='centered')
                ],className='col-md-2 about')
                ,html.Div (className='col-md-1')
            ],className='row')
        ],className='wrapper')
        ###################################################################
        # pie de pagina
        ###################################################################
        ,html.Footer ([
            html.Div ([
                html.P ([
                    'Copyright 2020'
                    ,html.Strong(' CNC ')
                    ,'Todos los derechos reservados'
                ])
                ,html.A ([
                    html.I ([
                    ],className='fa fa-angle-up')
                ],href='index.py#', className='go-top')
            ],className='text-center')
        ],className='site-footer2')
    ],id='main-content2')
],id='container')
Beispiel #25
0
def create_app(results_json, path_sim_output=None):
    r"""Initializes the app and calls all the other functions, resulting in the web app as well as pdf.

    This function specifies the layout of the web app, loads the external styling sheets, prepares the necessary data
    from the json results file, calls all the helper functions on the data, resulting in the auto-report.

    Parameters
    ----------
    results_json: json results file
        This file is the result of the simulation and contains all the data necessary to generate the auto-report.

    path_sim_output: str
        Path to the mvs simulation's output files' folder
        Default: output path saved in the result_json

    Returns
    -------
    app: instance of the Dash class within the dash library
        This app holds together all the html elements wrapped in Python, necessary for the rendering of the auto-report.
    """

    if path_sim_output is None:
        path_sim_output = results_json[SIMULATION_SETTINGS][PATH_OUTPUT_FOLDER]

    # create a "report" folder containing an "asset" folder
    asset_folder = os.path.abspath(copy_report_assets(path_sim_output))

    # external CSS stylesheets
    external_stylesheets = [
        {
            "href":
            "https://cdnjs.cloudflare.com/ajax/libs/foundation/6.6.3/css/foundation.min.css",
            "rel": "stylesheet",
            "integrity": "sha256-ogmFxjqiTMnZhxCqVmcqTvjfe1Y/ec4WaRj/aQPvn+I=",
            "crossorigin": "anonymous",
            "media": "screen",
        },
    ]

    app = dash.Dash(
        assets_folder=asset_folder,
        external_stylesheets=external_stylesheets,
    )

    # Reading the relevant user-inputs from the JSON_WITH_RESULTS.json file into Pandas dataframes

    # .iloc[0] is used as PROJECT_DATA includes LES_ENERGY_VECTOR_S, which can have multiple entries.
    # Pased to a DF, we have multiple rows - for eah sector one row.
    # This messes up reading the data from the DF later, so we only take one row which then contains all relevant data.
    dfprojectData = pd.DataFrame.from_dict(results_json[PROJECT_DATA]).iloc[0]
    dfeconomicData = pd.DataFrame.from_dict(
        results_json[ECONOMIC_DATA]).loc[VALUE]

    # Obtaining the latlong of the project location
    latlong = (
        float(dfprojectData.latitude),
        float(dfprojectData.longitude),
    )
    # Determining the geographical location of the project
    geo_dict_path = os.path.join(asset_folder, "geolocation")
    if os.path.exists(geo_dict_path):
        with open(geo_dict_path, "rb") as handle:
            geo_dict = pickle.load(handle)
    else:
        geoList = rg.search(latlong)
        geo_dict = geoList[0]
        with open(geo_dict_path, "wb") as handle:
            pickle.dump(geo_dict, handle, protocol=pickle.HIGHEST_PROTOCOL)

    location = geo_dict["name"]

    leaflet_map_path = os.path.join(asset_folder, "proj_map.html")
    static_map_path = os.path.join(asset_folder, "proj_map_static.png")

    # Add a dynamic leaflet map to the dash app
    if not os.path.exists(leaflet_map_path):
        mapy = folium.Map(location=latlong, zoom_start=14)
        tooltip = "Click here for more info"
        folium.Marker(
            latlong,
            popup="Location of the project",
            tooltip=tooltip,
            icon=folium.Icon(color="red", icon="glyphicon glyphicon-flash"),
        ).add_to(mapy)
        mapy.save(leaflet_map_path)

    # Adds a static map for the PDF report
    MAP_STATIC = None
    if not os.path.exists(static_map_path):
        longitude = latlong[1]
        latitude = latlong[0]
        coords = longitude, latitude

        map_static = staticmap.StaticMap(600, 600, 80)
        marker = staticmap.CircleMarker(coords, "#13074f", 15)
        map_static.add_marker(marker)
        try:
            map_image = map_static.render(zoom=14)
            map_image.save(static_map_path)
            MAP_STATIC = encode_image_file(static_map_path)
        except RuntimeError as e:
            if "could not download" in repr(e):
                logging.warning(
                    "You might not be connected to internet, skipping the download of "
                    "location map for the report")

    dict_projectdata = {
        "Country": dfprojectData.country,
        "Project ID": dfprojectData.project_id,
        "Scenario ID": dfprojectData.scenario_id,
        "Currency": dfeconomicData.currency,
        "Project Location": location,
        "Discount Factor": dfeconomicData.discount_factor,
        "Tax": dfeconomicData.tax,
    }

    df_projectData = pd.DataFrame(list(dict_projectdata.items()),
                                  columns=["Label", "Value"])

    dict_simsettings = {
        "Evaluated period":
        results_json[SIMULATION_SETTINGS][EVALUATED_PERIOD][VALUE],
        "Start date":
        results_json[SIMULATION_SETTINGS][START_DATE],
        "Timestep length":
        results_json[SIMULATION_SETTINGS][TIMESTEP][VALUE],
    }

    df_simsettings = pd.DataFrame(list(dict_simsettings.items()),
                                  columns=["Setting", "Value"])

    projectName = (results_json[PROJECT_DATA][PROJECT_NAME] + " (ID: " +
                   str(results_json[PROJECT_DATA][PROJECT_ID]) + ")")

    scenarioName = (results_json[PROJECT_DATA][SCENARIO_NAME] + " (ID: " +
                    str(results_json[PROJECT_DATA][SCENARIO_ID]) + ")")

    simDate = time.strftime("%Y-%m-%d")

    ELAND_LOGO = encode_image_file(
        os.path.join(asset_folder, "logo-eland-original.jpg"))

    ENERGY_SYSTEM_GRAPH = encode_image_file(
        results_json[PATHS_TO_PLOTS][PLOTS_ES])

    # Determining the sectors which were simulated

    sectors = list(results_json[PROJECT_DATA][LES_ENERGY_VECTOR_S].keys())
    sec_list = """"""
    for sec in sectors:
        sec_list += "\n" + f"\u2022 {sec.upper()}"

    df_comp = convert_components_to_dataframe(results_json)
    df_scalar_matrix = convert_scalar_matrix_to_dataframe(results_json)
    df_cost_matrix = convert_cost_matrix_to_dataframe(results_json)
    df_kpi_scalars = convert_scalars_to_dataframe(results_json)
    df_kpi_sectors = convert_kpi_sector_to_dataframe(results_json)

    # Obtain the scenario description text provided by the user from the JSON results file
    scenario_description = results_json[PROJECT_DATA].get(
        SCENARIO_DESCRIPTION, "")

    # App layout and populating it with different elements
    app.layout = html.Div(
        id="main-div",
        className="grid-x align-center",
        children=[
            html.Div(
                className="cell small-10 small_offset-1 header_title_logo",
                children=[
                    html.Img(
                        id="mvslogo",
                        src="data:image/png;base64,{}".format(
                            ELAND_LOGO.decode()),
                        width="500px",
                    ),
                    html.H1("MULTI VECTOR SIMULATION - REPORT SHEET"),
                ],
            ),
            html.Section(
                className="cell small-10 small_offset-1 grid-x",
                children=[
                    insert_headings("Information"),
                    html.Div(
                        className="cell imp_info",
                        children=[
                            html.
                            P(f"MVS Release: {version_num} ({version_date})"),
                            html.P(f"Simulation date: {simDate}"),
                            html.Div(
                                className="cell imp_info2",
                                children=[
                                    html.Span(
                                        "Project name   : ",
                                        style={"font-weight": "bold"},
                                    ),
                                    f"{projectName}",
                                ],
                            ),
                            html.Div(
                                className="cell imp_info2",
                                children=[
                                    html.Span(
                                        "Scenario name  : ",
                                        style={"font-weight": "bold"},
                                    ),
                                    f"{scenarioName}",
                                ],
                            ),
                            html.Div(
                                className="cell imp_info2",
                                children=[]
                                if scenario_description == "" else [
                                    html.Span(
                                        "Scenario description  : ",
                                        style={"font-weight": "bold"},
                                    ),
                                    f"{scenario_description}",
                                ],
                            ),
                            html.Div(
                                className="blockoftext",
                                children=[
                                    "The energy system with the ",
                                    html.Span(f"{projectName}",
                                              style={"font-style": "italic"}),
                                    " for the scenario ",
                                    html.Span(
                                        f"{scenarioName}",
                                        style={"font-style": "italic"},
                                    ),
                                    " was simulated with the Multi-Vector simulation tool MVS 0.0x developed from the E-LAND toolbox "
                                    "developed in the scope of the Horizon 2020 European research project. The tool was developed by "
                                    "Reiner Lemoine Institute and utilizes the OEMOF framework.",
                                ],
                            ),
                        ],
                    ),
                ],
            ),
            html.Section(
                className="cell small-10 small_offset-1 grid-x",
                style={"pageBreakBefore": "always"},
                children=[
                    insert_headings("Input Data"),
                    insert_subsection(
                        title="Project Data",
                        content=[
                            insert_body_text(
                                "The most important simulation data will be presented below. "
                                "Detailed settings, costs, and technological parameters can "
                                "be found in the appendix."),
                            html.Div(
                                className="grid-x",
                                id="location-map-div",
                                children=[
                                    html.Div(
                                        className=
                                        "cell small-6 location-map-column",
                                        children=[
                                            html.H4(["Project Location"]),
                                            html.Iframe(
                                                srcDoc=open(
                                                    leaflet_map_path,
                                                    "r",
                                                ).read(),
                                                height="400",
                                            ),
                                            html.Div(
                                                className=
                                                "staticimagepdf print-only",
                                                children=[
                                                    insert_body_text(
                                                        "The blue dot in the below map indicates "
                                                        "the location of the project."
                                                    ),
                                                    html.Img(
                                                        id="staticmapimage",
                                                        src="" if
                                                        MAP_STATIC is None else
                                                        "data:image/png;base64,{}"
                                                        .format(MAP_STATIC.
                                                                decode()),
                                                        width="400px",
                                                        style={
                                                            "marginLeft":
                                                            "30px"
                                                        },
                                                        alt=
                                                        "Map of the location",
                                                    ),
                                                ],
                                            ),
                                        ],
                                    ),
                                    html.Div(
                                        className=
                                        "cell small-6 location-map-column",
                                        children=make_dash_data_table(
                                            df_projectData,
                                            "Project at a Glance"),
                                    ),
                                ],
                            ),
                            make_dash_data_table(df_simsettings,
                                                 "Simulation Settings"),
                            html.Div(
                                className="grid-x",
                                id="energy-system-graph-div",
                                children=[
                                    html.H4(["Energy system"]),
                                    html.Img(
                                        src="data:image/png;base64,{}".format(
                                            ENERGY_SYSTEM_GRAPH.decode()),
                                        alt="Energy System Graph",
                                        style={"maxWidth": "100%"},
                                    ),
                                ],
                            ),
                        ],
                    ),
                    html.Div(children=create_demands_section(
                        output_JSON_file=results_json, sectors=sectors)),
                    insert_subsection(
                        title="Resources",
                        content=ready_timeseries_plots(results_json,
                                                       data_type=RESOURCES),
                    ),
                    insert_subsection(
                        title="Energy System Components",
                        content=[
                            insert_body_text(
                                "The energy system is comprised of "
                                "the following components:"),
                            make_dash_data_table(df_comp),
                        ],
                    ),
                ],
            ),
            html.Section(
                className="cell small-10 small_offset-1 grid-x",
                style={"pageBreakBefore": "always"},
                children=[
                    html.H2(className="cell", children="Simulation Results"),
                    insert_subsection(
                        title="Dispatch & Energy Flows",
                        content=[
                            insert_body_text(
                                "The capacity optimization of components that were to be used resulted in:"
                            ),
                            make_dash_data_table(df_scalar_matrix),
                            insert_body_text(
                                "With this, the demands are met with the following dispatch schedules:"
                            ),
                            html.Div(children=ready_flows_plots(
                                dict_values=results_json, )),
                            html.Div(
                                className="add-cap-plot",
                                children=ready_capacities_plots(
                                    dict_values=results_json),
                            ),
                            insert_body_text(
                                "This results in the following KPI of the dispatch per energy sector:"
                            ),
                            make_dash_data_table(df_kpi_sectors),
                        ],
                    ),
                    insert_subsection(
                        title="Economic Evaluation",
                        content=[
                            insert_body_text(
                                "The following installation and operation costs "
                                "result from capacity and dispatch optimization:"
                            ),
                            make_dash_data_table(df_cost_matrix),
                            html.Div(
                                className="add-pie-plots",
                                children=ready_costs_pie_plots(
                                    dict_values=results_json,
                                    only_print=False,
                                ),
                            ),
                        ],
                    ),
                    insert_subsection(
                        title=
                        "Energy System: Key Performance Indicators (KPIs)",
                        content=[
                            insert_body_text(
                                f"In the following the key performance indicators of the of {projectName}, "
                                f"scenario {scenarioName} are displayed. For more information on their definition, "
                                f"please reference `mvs-eland.readthedocs.io`."
                            ),
                            make_dash_data_table(df_kpi_scalars),
                        ],
                    ),
                ],
            ),
            html.Section(
                className="cell small-10 small_offset-1 grid-x",
                children=[
                    html.Div(
                        className="cell",
                        children=[
                            insert_headings(heading_text="Logging Messages"),
                        ],
                    ),
                    html.Div(children=[
                        insert_subsection(
                            title="Warning Messages",
                            content=insert_log_messages(
                                log_dict=results_json[SIMULATION_RESULTS][LOGS]
                                [WARNINGS]),
                        ),
                        insert_subsection(
                            title="Error Messages",
                            content=insert_log_messages(
                                log_dict=results_json[SIMULATION_RESULTS][LOGS]
                                [ERRORS]),
                        ),
                    ]),
                ],
            ),
        ],
    )
    return app
                                        for f in FILTERS
                                    },
                                ),
                            ],
                        ),
                    ],
                ),
                html.Div(
                    className="results-page__body",
                    children=[
                        # dcc.Tabs(id="tabs", value='dashboard', children=[
                        #     dcc.Tab(label='Dashboard', value='dashboard'),
                        #     dcc.Tab(label='Giving map', value='giving-map'),
                        # ]),
                        html.Section(
                            className="results-page__body__content",
                            id="dashboard-output",
                        ),
                        html.Section(
                            className="results-page__body__whats-next",
                            id="whats-next",
                            children=[],
                        ),
                        footer(app.server),
                    ],
                ),
            ],
        ),
    ],
)

Beispiel #27
0
                external_scripts=external_scripts)

app.layout = html.Div([
    html.Div(
        id="main",
        className="scroll-container",
        children=[
            dcc.Location(id="loc"),
            html.Section(
                id="intro",
                className="section section-intro",
                children=[
                    html.Div(
                        className="text-center",
                        children=[
                            html.
                            H4("Have you ever wondered how bad can people make plots?"
                               ),
                            html.H4("Shockingly, very bad."),
                            html.Button(id="start-button",
                                        children="Check it out")
                        ])
                ]),
            html.Section(
                id="plots",
                className="section",
                children=[
                    html.
                    H3(className="header-center",
                       children=
                       "Choose plot you want to see. Even if it is ugly as... you know."
Beispiel #28
0
# Configure navbar menu
navbar = html.Div([
    html.Ul([
        html.Li([dcc.Link('First', href='/first')], className='active'),
        html.Li([dcc.Link('Second', href='/second')]),
        html.Li([dcc.Link('Third', href='/third')]),
    ],
            className='nav navbar-nav')
],
                  className='navbar navbar-inverse navbar-static-top',
                  role='navigation')

body = html.Div([
    html.Div([html.H2("hello world!")], className='wrapper'),
    html.Section([
        html.Ul([html.Li(["Header"], className='header')],
                className='sidebar-menu')
    ])
],
                className="hold-transition skin-blue sidebar-mini")

# external_stylesheets = [dbc.themes.CERULEAN]
# external_stylesheets = ['https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic"']
app = dash.Dash(__name__)

app.layout = html.Div([navbar, body])

if __name__ == "__main__":
    app.run_server(port=8051)
Beispiel #29
0
def init_regression(server):
    options = [
        'year', 'ratings_count', 'labels_count', 'reviews_count', 'is_natural',
        'winery_ratings_count', 'winery_ratings_average',
        'winery_labels_count', 'winery_wines_count', 'users_count',
        'regions_count', 'wines_count', 'wineries_count', 'median_price',
        'bold', 'tannic', 'sweet', 'oaky', 'black fruit', 'red fruit',
        'earthy', 'spices', 'ageing', 'yeasty', 'dried fruit', 'citrus',
        'tree fruit', 'vegetal', 'floral', 'tropical', 'beef', 'lamb', 'veal',
        'poultry', 'pork', 'shellfish', 'vegetarian', 'game', 'spicy-food',
        'types'
    ]  #Mangler total flavors

    dict_options = [
        'year', 'ratings_count', 'labels_count', 'reviews_count', 'is_natural',
        'winery_ratings_count', 'winery_ratings_average',
        'winery_labels_count', 'winery_wines_count', 'users_count',
        'regions_count', 'wines_count', 'wineries_count', 'median_price',
        'bold', 'tannic', 'sweet', 'oaky', 'black fruit', 'red fruit',
        'earthy', 'spices', 'ageing', 'yeasty', 'dried fruit', 'citrus',
        'tree fruit', 'vegetal', 'floral', 'types', 'foods'
    ]  #Mangler total flavors

    TASTES = [
        'tropical', 'beef', 'lamb', 'veal', 'poultry', 'pork', 'shellfish',
        'vegetarian', 'game', 'spicy-food'
    ]

    UPPER_WIDTH = 1
    UPPER_TEXT_WIDTH = 6
    SUBSECTION_WIDTHS = '13%'

    predictor_app = Dash(
        server=server,
        title='Beyond The Grape Predictor',
        update_title=None,
        routes_pathname_prefix='/predict/',
        external_stylesheets=[dbc.themes.BOOTSTRAP, 'styles.css'],
        external_scripts=[dbc.themes.BOOTSTRAP, 'styles.css'])

    pipeline = load("app/static/models/xbg_wine_model.joblib")

    foods = dbc.FormGroup(
        [
            dbc.Label("Foods", html_for="food-checklist-row", width=2),
            dbc.Col(
                dcc.Checklist(options=[{
                    'label': 'Beef',
                    'value': 'beef'
                }, {
                    'label': 'Chicken',
                    'value': 'chicken'
                }, {
                    'label': 'Pork',
                    'value': 'pork'
                }, {
                    'label': 'Lamb',
                    'value': 'lamb'
                }, {
                    'label': 'Veal',
                    'value': 'veal'
                }, {
                    'label': 'Poultry',
                    'value': 'poultry'
                }, {
                    'label': 'Shellfish',
                    'value': 'shellfish'
                }, {
                    'label': 'Vegetarian',
                    'value': 'vegetarian'
                }, {
                    'label': 'Game',
                    'value': 'game'
                }, {
                    'label': 'Spicy food',
                    'value': 'spicy-food'
                }, {
                    'label': 'Tropical',
                    'value': 'tropical'
                }],
                              value=['beef', 'chicken', 'pork'],
                              id='food-checklist-row',
                              labelStyle={
                                  'display': 'inline-block',
                                  'margin': '5px'
                              }),
                width=7,
            ),
        ],
        row=True,
    )

    types = dbc.FormGroup(
        [
            dbc.Label("Wine type", html_for="types", width=2),
            dbc.Col(
                dcc.RadioItems(options=[
                    {
                        'label': 'Red',
                        'value': 'red'
                    },
                    {
                        'label': 'White',
                        'value': 'white'
                    },
                ],
                               value='red',
                               id='types',
                               labelStyle={
                                   'display': 'inline-block',
                                   'margin': '5px'
                               }),
                width=7,
            ),
        ],
        row=True,
    )

    # ---------------------------------------------------- Mapping ----------------------------------------------------

    predictor_app.layout = html.Div(
        [
            html.Section([
                html.Div([
                    html.H1('Beyond The Grape rating predictor',
                            className='mx-auto my-0 text-uppercase',
                            style={
                                'text-align': 'center',
                                'color': 'darkslategrey'
                            })
                ],
                         style={'margin': '3%'}),
                html.Div(
                    [

                        # ---------------------------------------------------- Section 1 ----------------------------------------------------
                        dbc.Form([foods, types]),
                        html.Div(
                            [
                                dbc.Form(
                                    [
                                        numeric_form_group(
                                            'year', 'Year', UPPER_TEXT_WIDTH,
                                            UPPER_WIDTH, 2002, 1960, 2020, 1),
                                        numeric_form_group(
                                            'median_price', 'Price',
                                            UPPER_TEXT_WIDTH, UPPER_WIDTH, 550,
                                            50, 6000, 50),
                                        numeric_form_group('ratings_count',
                                                           '# Ratings',
                                                           UPPER_TEXT_WIDTH,
                                                           UPPER_WIDTH,
                                                           2000,
                                                           0,
                                                           step=100),
                                        numeric_form_group('labels_count',
                                                           '# Labels',
                                                           UPPER_TEXT_WIDTH,
                                                           UPPER_WIDTH,
                                                           20,
                                                           1,
                                                           step=1),
                                        numeric_form_group('reviews_count',
                                                           '# Reviews',
                                                           UPPER_TEXT_WIDTH,
                                                           UPPER_WIDTH,
                                                           1000,
                                                           0,
                                                           step=50)
                                    ],
                                    style={
                                        'float': 'left',
                                        'margin': '1%',
                                        'width': SUBSECTION_WIDTHS
                                    }),

                                # ---------------------------------------------------- Section 2 ----------------------------------------------------
                                dbc.Form(
                                    [
                                        numeric_form_group(
                                            'tannic', 'Tannic',
                                            UPPER_TEXT_WIDTH, UPPER_WIDTH, 30,
                                            0, 100, 1),
                                        numeric_form_group(
                                            'sweet', 'Sweet', UPPER_TEXT_WIDTH,
                                            UPPER_WIDTH, 30, 0, 100, 1),
                                        numeric_form_group(
                                            'bold', 'Bold', UPPER_TEXT_WIDTH,
                                            UPPER_WIDTH, 30, 0, 100, 1),
                                        numeric_form_group(
                                            'black fruit', 'Black Fruit',
                                            UPPER_TEXT_WIDTH, UPPER_WIDTH, 0.2,
                                            0, 1, 0.1),
                                        numeric_form_group(
                                            'red fruit', 'Red Fruit',
                                            UPPER_TEXT_WIDTH, UPPER_WIDTH, 0.2,
                                            0, 1, 0.1),
                                    ],
                                    style={
                                        'float': 'left',
                                        'margin': '1%',
                                        'width': SUBSECTION_WIDTHS
                                    }),
                                # ---------------------------------------------------- Section 3 ----------------------------------------------------
                                dbc.Form(
                                    [
                                        numeric_form_group(
                                            'earthy', 'Earthy',
                                            UPPER_TEXT_WIDTH, UPPER_WIDTH, 0.2,
                                            0, 1, 0.1),
                                        numeric_form_group(
                                            'is_natural', 'Is Natural',
                                            UPPER_TEXT_WIDTH, UPPER_WIDTH, 0,
                                            0, 1, 1),
                                        numeric_form_group(
                                            'winery_ratings_count',
                                            '# Winery Ratings',
                                            UPPER_TEXT_WIDTH,
                                            UPPER_WIDTH,
                                            1000,
                                            0,
                                            step=100),
                                        numeric_form_group(
                                            'winery_ratings_average',
                                            'winery_ratings_average',
                                            UPPER_TEXT_WIDTH, UPPER_WIDTH, 4,
                                            0, 5, 0.1),
                                        numeric_form_group(
                                            'winery_labels_count',
                                            '# winery Labels',
                                            UPPER_TEXT_WIDTH, UPPER_WIDTH, 20,
                                            0, 10000, 10),
                                    ],
                                    style={
                                        'float': 'left',
                                        'margin': '1%',
                                        'width': SUBSECTION_WIDTHS
                                    }),
                                # ---------------------------------------------------- Section 4 ----------------------------------------------------
                                dbc.Form(
                                    [
                                        numeric_form_group(
                                            'winery_wines_count',
                                            '#Winery Wines', UPPER_TEXT_WIDTH,
                                            UPPER_WIDTH, 20, 0, 10000, 10),
                                        numeric_form_group('users_count',
                                                           '# Users',
                                                           UPPER_TEXT_WIDTH,
                                                           UPPER_WIDTH,
                                                           600,
                                                           0,
                                                           step=100),
                                        numeric_form_group('regions_count',
                                                           '# Regions',
                                                           UPPER_TEXT_WIDTH,
                                                           UPPER_WIDTH,
                                                           7,
                                                           0,
                                                           step=1),
                                        numeric_form_group('wines_count',
                                                           'Wines count',
                                                           UPPER_TEXT_WIDTH,
                                                           UPPER_WIDTH,
                                                           40,
                                                           0,
                                                           step=10),
                                        numeric_form_group('wineries_count',
                                                           'Wineries count',
                                                           UPPER_TEXT_WIDTH,
                                                           UPPER_WIDTH,
                                                           80,
                                                           0,
                                                           step=10)
                                    ],
                                    style={
                                        'float': 'left',
                                        'margin': '1%',
                                        'width': SUBSECTION_WIDTHS
                                    }),
                                # ---------------------------------------------------- Section 5 ----------------------------------------------------
                                dbc.Form(
                                    [
                                        numeric_form_group(
                                            'oaky', 'Oaky', UPPER_TEXT_WIDTH,
                                            UPPER_WIDTH, 0.2, 0, 1, 0.1),
                                        numeric_form_group(
                                            'spices', 'Spices',
                                            UPPER_TEXT_WIDTH, UPPER_WIDTH, 0.2,
                                            0, 1, 0.1),
                                        numeric_form_group(
                                            'ageing', 'Ageing',
                                            UPPER_TEXT_WIDTH, UPPER_WIDTH, 0.2,
                                            0, 1, 0.1),
                                        numeric_form_group(
                                            'yeasty', 'Yeasty',
                                            UPPER_TEXT_WIDTH, UPPER_WIDTH, 0.2,
                                            0, 1, 0.1),
                                        numeric_form_group(
                                            'dried fruit', 'Dried Fruit',
                                            UPPER_TEXT_WIDTH, UPPER_WIDTH, 0.2,
                                            0, 1, 0.1)
                                    ],
                                    style={
                                        'float': 'left',
                                        'margin': '1%',
                                        'width': SUBSECTION_WIDTHS
                                    }),
                                # ---------------------------------------------------- Section 6 ----------------------------------------------------
                                dbc.Form(
                                    [
                                        numeric_form_group(
                                            'citrus', 'Citrus',
                                            UPPER_TEXT_WIDTH, UPPER_WIDTH, 0.2,
                                            0, 1, 0.1),
                                        numeric_form_group(
                                            'tree fruit', 'Tree Fruit',
                                            UPPER_TEXT_WIDTH, UPPER_WIDTH, 0.2,
                                            0, 1, 0.1),
                                        numeric_form_group(
                                            'vegetal', 'Vegetal',
                                            UPPER_TEXT_WIDTH, UPPER_WIDTH, 0.2,
                                            0, 1, 0.1),
                                        numeric_form_group(
                                            'floral', 'Floral',
                                            UPPER_TEXT_WIDTH, UPPER_WIDTH, 0.2,
                                            0, 1, 0.1)
                                    ],
                                    style={
                                        'text-align': 'left',
                                        'margin': '1%',
                                        'width': SUBSECTION_WIDTHS
                                    }),
                            ],
                            style={
                                'display': 'flex',
                                'justify-content': 'center'
                            }),
                    ],
                    style={'text-align': 'center'}),
                html.Div([html.P('')], style={'margin': '5%'}),
            ]),
            html.H2('        '),
            html.H2(id="output_pred",
                    className="predictions_container",
                    style={
                        'text-align': 'center',
                        'margin': '150px',
                        'color': 'darkslategrey'
                    }),
        ],
        style={
            'background-image': 'url("assets/background.jpg")',
            'height': '100vh',
            'background-size': 'cover'
        })

    #Init callback of input fields
    @predictor_app.callback(
        dash.dependencies.Output('output_pred', 'children'),
        [  #dash.dependencies.Input('submit_button', 'n_clicks'),
            dash.dependencies.Input('year', 'value'),
            dash.dependencies.Input('ratings_count', 'value'),
            dash.dependencies.Input('labels_count', 'value'),
            dash.dependencies.Input('reviews_count', 'value'),
            dash.dependencies.Input('is_natural', 'value'),
            dash.dependencies.Input('winery_ratings_count', 'value'),
            dash.dependencies.Input('winery_ratings_average', 'value'),
            dash.dependencies.Input('winery_labels_count', 'value'),
            dash.dependencies.Input('winery_wines_count', 'value'),
            dash.dependencies.Input('users_count', 'value'),
            dash.dependencies.Input('regions_count', 'value'),
            dash.dependencies.Input('wines_count', 'value'),
            dash.dependencies.Input('wineries_count', 'value'),
            dash.dependencies.Input('median_price', 'value'),
            dash.dependencies.Input('bold', 'value'),
            dash.dependencies.Input('tannic', 'value'),
            dash.dependencies.Input('sweet', 'value'),
            dash.dependencies.Input('oaky', 'value'),
            dash.dependencies.Input('black fruit', 'value'),
            dash.dependencies.Input('red fruit', 'value'),
            dash.dependencies.Input('earthy', 'value'),
            dash.dependencies.Input('spices', 'value'),
            dash.dependencies.Input('ageing', 'value'),
            dash.dependencies.Input('yeasty', 'value'),
            dash.dependencies.Input('dried fruit', 'value'),
            dash.dependencies.Input('citrus', 'value'),
            dash.dependencies.Input('tree fruit', 'value'),
            dash.dependencies.Input('vegetal', 'value'),
            dash.dependencies.Input('floral', 'value'),
            dash.dependencies.Input('types', 'value'),
            dash.dependencies.Input('food-checklist-row', 'value'),
        ])
    def calculate_rating(*args):
        #Establish dataframe input
        d = pd.DataFrame()
        for o, i in zip(dict_options, args):
            d[o] = [i]

        for taste in TASTES:
            d[taste] = 1 if taste in list(d['foods'][0]) else 0

        d['types'] = 1 if 'red' in list(d['types'][0]) else 0
        del d['foods']

        #Ordring columns to fit XGB model
        d = d[[
            'year', 'ratings_count', 'labels_count', 'reviews_count',
            'is_natural', 'winery_ratings_count', 'winery_ratings_average',
            'winery_labels_count', 'winery_wines_count', 'users_count',
            'regions_count', 'wines_count', 'wineries_count', 'median_price',
            'bold', 'tannic', 'sweet', 'oaky', 'black fruit', 'red fruit',
            'earthy', 'spices', 'ageing', 'yeasty', 'dried fruit', 'citrus',
            'tree fruit', 'vegetal', 'floral', 'tropical', 'beef', 'lamb',
            'veal', 'poultry', 'pork', 'shellfish', 'vegetarian', 'game',
            'spicy-food', 'types'
        ]]

        print(d)  #Used for decomposition and debugging
        predictions = pipeline.predict(d)[0]
        return 'Predicted rating {}'.format(round(float(predictions), 3))

    return predictor_app.server
Beispiel #30
0
 html.Section(
     id='title-section',
     children=html.Div(
         className='screen-height',
         style = {'align-items': 'center', 'display': 'flex', 'flex-direction': 'column', 'justify-content': 'center'},
         children=[
             html.H1("Jednoosobowe działalności gospodarcze"),
             html.H2("Szczegółowa analiza rynku w latach 2011 - 2020", style = {'margin-bottom': '20px'}),
             html.Div([
                 html.Div("9 ", style = {'font-size': 60}),
                 html.Div("", style = {'width': '10px'}),
                 html.Div("lat", style = {'font-size': 25}),
                 html.Div("", style = {'width': '50px'}),
                 html.Div("280 000 ", style = {'font-size': 60}),
                 html.Div("", style = {'width': '10px'}),
                 html.Div("firm", style = {'font-size': 25}),
                 html.Div("", style = {'width': '50px'}),
                 html.Div("5 ", style = {'font-size': 60}),
                 html.Div("", style = {'width': '10px'}),
                 html.Div("wydarzeń", style = {'font-size': 25}),
             ], style = {'align-items': 'center', 'display': 'flex', 'flex-direction': 'row', 'justify-content': 'center'}),
             html.Div([
                 html.Div([
                     html.H4("Przekrój przestrzenny oraz gospodarczy działalności"),
                     html.Div([
                         html.Img(src='data:image/png;base64,{}'.format(analytics_image.decode()),
                         height=250)
                     ]),
                     html.Div("W jakim regionie firmy przetrwały najdłużej?", style = {'font-size': 18}),
                     html.Div("Które rodzaje działalności mają nawiększe szanse na sukces?", style = {'font-size': 18}),
                     html.Div("Kiedy najczęściej upadają firmy?", style = {'font-size': 18}),
                     dbc.Button(
                         id = 'analysis-button',
                         href = '#1',
                         children = "Sprawdź",
                         color = 'primary',
                         style = {'margin-top': '10px'}
                     )
                 ], style = {'align-items': 'center', 'display': 'flex', 'flex-direction': 'column', 'justify-content': 'center'}),
                 html.Div("", style = {'width': '100px'}),
                 html.Div([
                     html.H4("Predykcja życia firmy"),
                     html.Div([
                         html.Img(src='data:image/png;base64,{}'.format(prediction_image.decode()),
                         height=250)
                     ]),
                     html.Div("Jakie są Twoje szanse na sukces?", style = {'font-size': 18}),
                     html.Div("", style = {'font-size': 18}),
                     html.Div("", style = {'font-size': 18}),
                     dbc.Button(
                         id = 'prediction-button',
                         href = '#2',
                         children = "Sprawdź",
                         color = 'primary',
                         style = {'margin-top': '10px'}
                     )
                 ], style = {'align-items': 'center', 'display': 'flex', 'flex-direction': 'column', 'justify-content': 'center', 'align-self': 'flex-start'}),
             ], style = {'align-items': 'center', 'display': 'flex', 'flex-direction': 'row', 'justify-content': 'center', 
                         'padding-top': '50px'}),
         ]
     )
 ),