Exemplo n.º 1
0
#Layout of the dash app

#rendering the layout of the page on the basis of the selected url

dash_app.layout = html.Div([
    html.Div(" "),
    dcc.Location(id='url', refresh=False),
    html.Div(id='page-content')
])

#Main Page / Home page of the websote
index_page = html.Div([
    html.H1('ERM Driver Risk Management'),
    html.Img(src='/assets/Road_Safety_v1.PNG', width=1800, height=300),
    html.Br(),
    html.Br(),
    dcc.Link(html.Img(src='/assets/Overview_Image.jpg', width=300, height=300),
             href='/Overview'),
    html.Br(),
    html.Br(),
    dcc.Link(html.Img(src='/assets/DCP_Image.png', width=300, height=300),
             href='/DCP'),
    html.Br(),
    html.Br(),
    html.A('Dynamic Crash Prevention System - Azure',
           href='https://fleetmanagementdemo.azurewebsites.net/')
])


# Render the page on the basis of the url
Exemplo n.º 2
0
df = pop_data4
df = df.groupby(['State', 'Year', 'state_code'])[['Population']].sum()
df.reset_index(inplace=True)

######

app = dash.Dash(__name__,
                external_stylesheets=[dbc.themes.BOOTSTRAP],
                meta_tags=[{
                    'name': 'viewport',
                    'content': 'width=device-width, initial-scale=1.0'
                }])
# App layout
app.layout = dbc.Container([
    dbc.Row(dbc.Col(html.Br(), width=12), ),
    dbc.Row([
        dbc.Col(html.H1("US State Population Dashboard",
                        className='text center text-primary mb-4'),
                width=9),
        dbc.Col(html.P("Created by Tom Batroney Twitter: @TomBatroney",
                       className='text right text-primary mb-4'),
                width=3)
    ]),
    dbc.Row(dbc.Col(html.Br(), width=12), ),
    dbc.Row(
        dbc.Col(dcc.Slider(id="slct_year",
                           min=1564,
                           max=2019,
                           step=1,
                           value=1564),
Exemplo n.º 3
0
def generate_component_example(component_name,
                               library_name,
                               library_short,
                               description='',
                               params=None,
                               style=None,
                               default_id=True,
                               datafile=None,
                               library_imports=None,
                               setup_code='',
                               component_wrap=None,
                               image_info=None):
    '''Generate an example for a component, with hyperlinks to the
    appropriate component-specific pages.

    :param (str) component_name: The name of the component as it is
    defined within the package.
    :param (str) library_name: The full name of the library (e.g.,
    dash_bio).
    :param (str) library_short: The short name of the library, used in an
    import statement (i.e., import library_name as library_short).
    :param (str) description: A short string describing the component.
    :param (dict) params: A dictionary that contains the parameters
    assigned to the component that is to be displayed as a live
    example; the keys correspond to the parameter names.
    :param (dict) style: A dictionary that contains any style
    options. The keys correspond to the style parameter names.
    :param (bool) default_id: Whether or not to assign a default ID to
    the component in the example code.
    :param (string) datafile: The name of the data file, if any, used
    for the component. This file should be present in the folder
    specified by the variable DATA_LOCATION_PREFIX.
    :param (list[list]) library_imports: A list for which each element
    is a list with two elements: the first element should be the full
    name of the library, and the second element should be the short
    name of the library. Contains all of the libraries necessary for
    running the example code (e.g., pandas).
    :param (str) setup_code: Any additional code required before
    rendering the component (e.g., parsing a data file).
    :param (str) component_wrap: A string that will wrap the component
    (e.g., if the component needs to be an argument for a dcc.Graph).
    The location of the component code is represented by an
    underscore (_).
    :param (dict) image_info: The URL and, if applicable, the height
    and width of the image of the component.
    :rtype (list[obj]): A list containing the entire section for the
    component in question, including the code block, component demo,
    description, and hyperlinks to the component-specific page.
    '''

    # location of all sample data
    DATA_LOCATION_PREFIX = '''https://raw.githubusercontent.com/plotly/\
dash-bio-docs-files/master/'''

    if library_imports is None:
        library_imports = []

    # parameters for initial declaration of component
    paramstring = '\n  '

    if default_id is True:
        paramstring += 'id=\'my-{}-{}\', '.format(library_short,
                                                  component_name.lower())

    if params is not None:
        for key in params.keys():
            paramstring += '{}={}, '.format(key, params[key])

    # style options
    if style is not None:
        styleString = 'style={\n  '
        for key in style.keys():
            styleString += '  \'{}\': \'{}\', '.format(key, str(style[key]))

        # remove comma and space following the last style option
        styleString = styleString[:-2]

        styleString += '\n  }, '
        paramstring += styleString

    # loading data if necessary
    if datafile is not None:
        library_imports.append(['urllib.request', 'urlreq'])
        # only decode for python 3
        decode_string = ''
        if sys.version_info >= (3, 0):
            decode_string = '.decode(\"utf-8\")'

        # add data location
        setup_code = '''\ndata = urlreq.urlopen(\n \"{}\" + \n \"{}\"\n).read(){}\n\n'''.format(
            DATA_LOCATION_PREFIX, datafile['name'], decode_string) + setup_code

        # declare data in component initialization if necessary
        if 'parameter' in datafile.keys():
            paramstring += '{}=data, '.format(datafile['parameter'])

    # pretty-print param string (spaces for indentation)
    paramstring = paramstring.replace(', ', ',\n  ')

    # remove the characters following the final parameter
    # (',\n  '), and add unindented newline at end
    if (len(paramstring) > 4):
        paramstring = paramstring[:-4] + '\n'
    # if no params were supplied, remove all newlines
    else:
        paramstring = ''

    # format component string
    component_string = '{}.{}({})'.format(library_short, component_name,
                                          paramstring)
    # wrap component if necessary
    if component_wrap is not None:
        component_string = component_wrap.replace('_', component_string)

    # add imports
    imports_string = ''
    for library in library_imports:
        if library[0] != library[1]:
            imports_string += 'import {} as {}\n'.format(
                library[0], library[1])
        else:
            imports_string += 'import {}\n'.format(library[0])

    # change urllib package if necessary (due to Python version)
    imports_string = imports_string.replace('urllib.request',
                                            'six.moves.urllib.request')

    # full code
    example_string = '''import {} as {}
{}
{}
component = {}
'''.format(library_name, library_short, imports_string, setup_code,
           component_string)

    # load the iframe if that is where the app is
    if image_info is not None:
        component_demo = imageComponentBlock(example_string, **image_info)
    else:
        component_demo = ComponentBlock(example_string)

    # full component section
    return [
        html.Hr(),
        html.H3(
            dcc.Link(component_name,
                     href=tools.relpath('/{}/{}'.format(
                         library_name.replace('_', '-'),
                         component_name.lower())),
                     id=component_name.replace(' ', '-').lower())),
        reusable_components.Markdown(description), component_demo,
        html.Br(),
        dcc.Link('More {} Examples and Reference'.format(component_name),
                 href=tools.relpath('/{}/{}'.format(
                     library_name.replace('_', '-'), component_name.lower())))
    ]
Exemplo n.º 4
0
def tab3content():
    content = html.Div([
        html.Center(html.H2("Portfolio")),

        #API key text are and button
        dbc.Row([
            dbc.Col([],width=1),
            dbc.Col(
                [dbc.Input(id="apiField", placeholder="API KEY", type="text")],
                width=5
            ),
            dbc.Col(
                [dbc.Button("Enter API", id="apiButton")],
                width=1
            )
        ]),

        #Meta card:
        # Displays API key used (when valid entered), total sell value, total buy value

        dbc.Spinner([
            dbc.Card([
                dbc.CardBody([
                    dbc.Col([],
                            id="valid_api_div",
                            style={'font-size': '16px'}),

                    dbc.Col([],
                            id="total-out",
                            style={'font-size': '16px'})
                ])
            ],
                outline=True),
        ]),

        html.Br(),
        html.Div(
            id = "personal-div",
            style={'display':'none'},
            children = [
                dbc.CardDeck([
                    dbc.Card([
                        dbc.CardBody(
                            id='personal-kits',
                            className= 'card-text',
                            children=[dbc.Label("")],
                        )],
                    style={"min-width": "870px"},
                    color="success",
                    outline=True
                    ),
                    dbc.Card([
                        dbc.CardBody(
                            id='personal-dyes',
                            children=[dbc.Label("")],
                        )],
                        style={"min-width": "700px"},
                        color="success",
                        outline=True
                    )
                ],
                )
            ]
        ),
        #Invalid key toast
        dbc.Toast(
            "Check your key",
            id="invalid-toast",
            className="mb-0",
            header="Invalid API key",
            is_open=False,
            dismissable=True,
            icon="danger",
            style={"position": "fixed", "top": 66, "right": 10, "width": 350},
            duration=3000,
        )
    ])

    return content
Exemplo n.º 5
0
def Header(app):
    return html.Div([get_header(app), html.Br([]), get_menu()])
def update_tab(tab):
    if tab == "tab1":
        return html.Div([
            html.P("Parkinson's disease :", className="p1"),
            html.
            P("Parkinson's disease is a progressive nervous system disorder that affects movement. Symptoms start gradually, sometimes starting with a barely noticeable tremor in just one hand. Tremors are common, but the disorder also commonly causes stiffness or slowing of movement.In the early stages of Parkinson's disease, your face may show little or no expression. Your arms may not swing when you walk. Your speech may become soft or slurred. Parkinson's disease symptoms worsen as your condition progresses over time.Although Parkinson's disease can't be cured, medications might significantly improve your symptoms. Occasionally, your doctor may suggest surgery to regulate certain regions of your brain and improve your symptoms."
              ),
            html.P("Symptoms:", className="p1"),
            html.Ul(children=[
                html.Li(
                    html.
                    P("Tremor. A tremor, or shaking, usually begins in a limb, often your hand or fingers. You may rub your thumb and forefinger back and forth, known as a pill-rolling tremor. Your hand may tremble when it's at rest."
                      )),
                html.Li(
                    html.
                    P("Slowed movement (bradykinesia). Over time, Parkinson's disease may slow your movement, making simple tasks difficult and time-consuming. Your steps may become shorter when you walk. It may be difficult to get out of a chair. You may drag your feet as you try to walk."
                      )),
                html.Li(
                    html.
                    P("Rigid muscles. Muscle stiffness may occur in any part of your body. The stiff muscles can be painful and limit your range of motion"
                      )),
                html.Li(
                    html.
                    P("Impaired posture and balance. Your posture may become stooped, or you may have balance problems as a result of Parkinson's disease."
                      )),
                html.Li(
                    html.
                    P("Loss of automatic movements. You may have a decreased ability to perform unconscious movements, including blinking, smiling or swinging your arms when you walk."
                      )),
                html.Li(
                    html.
                    P("Speech changes. You may speak softly, quickly, slur or hesitate before talking. Your speech may be more of a monotone rather than have the usual inflections."
                      )),
                html.Li(
                    html.
                    P("Writing changes. It may become hard to write, and your writing may appear small."
                      ))
            ],
                    className="ulp"),
            html.P("Complications:", className="p1"),
            html.Ul(children=[
                html.Li(
                    html.
                    P("Thinking difficulties. You may experience cognitive problems (dementia) and thinking difficulties. These usually occur in the later stages of Parkinson's disease. Such cognitive problems aren't very responsive to medications"
                      )),
                html.Li(
                    html.
                    P("Swallowing problems. You may develop difficulties with swallowing as your condition progresses. Saliva may accumulate in your mouth due to slowed swallowing, leading to drooling."
                      )),
                html.Li(
                    html.
                    P("Chewing and eating problems. Late-stage Parkinson's disease affects the muscles in your mouth, making chewing difficult. This can lead to choking and poor nutrition."
                      )),
                html.Li(
                    html.
                    P("Sleep problems and sleep disorders. People with Parkinson's disease often have sleep problems, including waking up frequently throughout the night, waking up early or falling asleep during the day."
                      )),
                html.Li(
                    html.
                    P("Blood pressure changes. You may feel dizzy or lightheaded when you stand due to a sudden drop in blood pressure (orthostatic hypotension)."
                      )),
                html.Li(
                    html.
                    P("Bladder problems. Parkinson's disease may cause bladder problems, including being unable to control urine or having difficulty urinating"
                      ))
            ],
                    className="ulp")
        ])

    if tab == 'tab2':
        return html.Div([
            html.P("features info:", className="p1"),
            html.P("MDVP:Fo(Hz) - Average vocal fundamental frequency"),
            html.P("MDVP:Fhi(Hz) - Maximum vocal fundamental frequency"),
            html.P("MDVP:Flo(Hz) - Minimum vocal fundamental frequency"),
            html.P("MDVP:APQ - Several measures of variation in amplitude"),
            html.
            P("NHR - Two measures of ratio of noise to tonal components in the voice"
              ),
            html.
            P("spread1,spread2,PPE - Three nonlinear measures of fundamental frequency variation"
              ),
            html.Br(),
            html.H3("Enter Average Vocal Fundamental Frequency:",
                    className="ips"),
            dcc.Input(id='fho',
                      placeholder="enter value",
                      type="number",
                      className="dccin"),
            html.H3("Enter Maximum Vocal Fundamental Frequency:",
                    className="ips"),
            dcc.Input(id='fhi',
                      placeholder='enter value',
                      type='number',
                      className="dccin"),
            html.H3("Enter Minimum Vocal Fundamental Frequency:",
                    className="ips"),
            dcc.Input(id='flo',
                      placeholder='enter value',
                      type='number',
                      className="dccin"),
            html.H3("Enter MDVP-APQ:", className="ips"),
            dcc.Input(id="apq",
                      placeholder="enter value",
                      type='number',
                      className="dccin"),
            html.H3("Enter NHR:", className="ips"),
            dcc.Input(id='nhr',
                      placeholder='enter value',
                      type='number',
                      className="dccin"),
            html.H3("Enter spread1:", className="ips"),
            dcc.Input(id='spd1',
                      placeholder='enter value',
                      type='number',
                      className="dccin"),
            html.H3("Enter spread2:", className="ips"),
            dcc.Input(id='spd2',
                      placeholder='enter value',
                      type='number',
                      className="dccin"),
            html.H3("Enter PPE:", className="ips"),
            dcc.Input(id='ppe',
                      placeholder='enter value',
                      type='number',
                      className="dccin"),
            html.Br(),
            html.Button('click me',
                        id='button',
                        n_clicks=None,
                        type='submit',
                        className="btn"),
            html.Br(),
            html.Br(),
            html.H3("Your output is:", className="out"),
            dcc.ConfirmDialog(id='err', message="Please fill all the inputs."),
            html.Div(id="my-output", className="output")
        ])
def render_content(tab):
    if tab == 'summary':
        #Summary tab should just return markdown text for now
        return(
                html.Div([
                    dcc.Markdown(dedent("""
                    
                    ## How to Use

                    To use this tool, click on either the "Data by State" or "Data by Plan" tab.
                    Unless otherwise noted, data by state shows state averages for plans weighted by
                    plan size. 

                    On the map to the left, hover over a state to see the corresponding data in charts
                    in the tabs on the right.

                    More information to come.
                    
                    """))
                ])
            )

    elif tab=='state-summary':
        #Return state summary charts
        return(
                html.Br(),
                html.Div([
                        dcc.Dropdown(
                            id='chart-metric',
                            options=[{'label': i, 'value': i} for i in measures],
                            value='Historical Funded Ratio'
                        ),
                    ]), 

            html.Div([
                dcc.Graph(id='timeseries-ratio')
            ])
        )
    else:
        #Return plan-specific charts
        return(html.Div([
            html.Br(),
                html.Div([
                        dcc.Dropdown(
                            id='chart-metric',
                            options=[{'label': i, 'value': i} for i in measures],
                            value='Historical Funded Ratio'
                        ),
                    ]), 

            html.Div([
                dcc.Graph(id='timeseries-ratio')
            ]),

            html.Div([
                dcc.Markdown(dedent("""
                Dashed lines represent individual pension plans.
                
                Solid lines represent plan-weighted state average.
                """))
            ],style={'border': 'thin lightgrey solid','textAlign':'center'})
        ]))
Exemplo n.º 8
0
styles = {
    'pre': {
        'border': 'thick grey solid',
        'overflow': 'scroll',
    }
}
################################################################################################################################################################
cheating_button = html.Div([
    dbc.Row([
        dbc.Col([
            dbc.Button("Click to view decision based on previous experience",
                       id="open-cheating-modal",
                       size="lg",
                       color="primary"),
            html.Br(),
            dbc.Modal([
                dbc.ModalHeader("Decision"),
                dbc.ModalBody(html.H3("Retail Shorts USA")),
                dbc.ModalFooter(dbc.Button("Close", id="close-cheating-modal"))
            ],
                      id="cheating-modal",
                      size="lg",
                      centered=True)
        ],
                width={"size": 11}),
    ],
            justify="center"),
    dbc.Row([dbc.Col([html.Br(), html.Br()])])
])
'''
Exemplo n.º 9
0
from app import app, server
from tabs import intro, predictCSS

style = {
    'maxWidth': '900px', 
    'margin': 'auto'}

app.title = 'Colorectal cancer survival prediction with interpretable AI'

app.layout = html.Div([
    html.A([html.Img(src='https://github.com/jebibault/ProstateCancerSurvival/blob/master/figures/logo.png?raw=true', style={'width' : '100%', 'margin-bottom': '15px', 'margin-top': '25px'})], href='http://med.stanford.edu/xinglab.html', target='_blank'),
    dcc.Markdown("## Predict colorectal cancer survival with interpretable AI"),
    html.P([
	    'This model allows you to predict the risk to die from colorectal cancer 10 year after diagnosis', 
	    html.Br(),
	    html.Br(),
	    html.Br()]),
    dcc.Tabs(id='tabs', value='tab-intro', parent_className='custom-tabs', className='custom-tabs-container', children=[
        dcc.Tab(label='About', value='tab-intro', className='custom-tab', selected_className='custom-tab--selected'),
        dcc.Tab(label='Predict cancer-specific survival', value='tab-predictCSS', className='custom-tab', selected_className='custom-tab--selected')
    ]),
    html.Div(id='tabs-content-classes'),
], style=style)

@app.callback(Output('tabs-content-classes', 'children'),
              [Input('tabs', 'value')])
def render_content(tab):
    if tab == 'tab-intro': return intro.layout
    elif tab == 'tab-predictCSS': return predictCSS.layout
def create_PCA(server):
    dash_app = dash.Dash(name='cleaning',
                         server=server,
                         url_base_pathname='/PCA/',
                         external_stylesheets=[
                             '/static/dist/css/styles.css',
                             'https://fonts.googleapis.com/css?family=Lato',
                             'https://codepen.io/chriddyp/pen/bWLwgP.css'
                         ])
    dash_app.index_string = html_layout

    dash_app.layout = html.Div(
        children=[
            #title and subtitle
            html.H1('This is where our title for this page will be'),
            html.H2('This is the subtitle'),

            #the button div
            html.Div([
                html.Div([
                    html.A(html.Button('Previous page',
                                       style={'fontSize': '12px'}),
                           href='/EDA/'),
                ],
                         className='two columns'),
                html.Div([
                    html.A(html.Button('Save and Proceed',
                                       style={'fontSize': '12px'}),
                           href='/non/',
                           id='save_button'),
                ],
                         className='two columns'),
            ],
                     className='row'),
            html.Div(
                [
                    # the left Div
                    html.Div(
                        [
                            html.Br(),
                            #dropdowns that user can select the features to explore/visualize
                            dcc.Dropdown(options=[{
                                'label': i,
                                'value': i
                            } for i in df.columns],
                                         multi=True,
                                         id='multi-dd-visual'),
                            html.Br(),
                            dcc.Dropdown(options=[{
                                'label': i,
                                'value': i
                            } for i in df.columns],
                                         multi=True,
                                         id='multi-dd-target'),
                            html.Br(),
                            dcc.RadioItems(
                                id='visual-dimension',
                                options=[{
                                    'label': i,
                                    'value': i
                                } for i in ['2D', '3D']],
                                labelStyle={'display': 'inline-block'}),
                            html.Br(),
                            html.Button(id='submit-button-state',
                                        n_clicks=0,
                                        children='Submit'),
                        ],
                        className='four columns'),

                    #the right div
                    html.Div([
                        dcc.Loading(id='loading',
                                    children=[dcc.Graph(id='fig')])
                    ],
                             className='eight columns'),
                ],
                className='row')
        ],
        id='dash-container')

    @dash_app.callback(
        dash.dependencies.Output('fig', 'figure'),
        [dash.dependencies.Input('submit-button-state', 'n_clicks')], [
            dash.dependencies.State('multi-dd-visual', 'value'),
            dash.dependencies.State('multi-dd-target', 'value'),
            dash.dependencies.State('visual-dimension', 'value'),
        ])
    def pca_graph(n_click, multi_dd_visual, multi_dd_target, visual_dimension):

        cols.append(multi_dd_visual)
        target.append(multi_dd_target)

        if n_click > 0 and visual_dimension == '2D':
            model = PCA(n_components=2)
            result = model.fit_transform(df[cols[-1]].values)
            df['D1'] = result[:, 0]
            df['D2'] = result[:, 1]
            fig = px.scatter(df, x="D1", y="D2", color=target[-1][0])
            # fig.show()
            return fig
            # print('Explained variation per principal component: {}'.format(model.explained_variance_ratio_))

        if n_click > 0 and visual_dimension == '3D':
            model = PCA(n_components=3)
            result = model.fit_transform(df[cols[-1]].values)
            df['D1'] = result[:, 0]
            df['D2'] = result[:, 1]
            df['D3'] = result[:, 2]
            fig = px.scatter_3d(df,
                                x='D1',
                                y='D2',
                                z='D3',
                                color=target[-1][0])
            # fig.show()
            return fig
            # print('Explained variation per principal component: {}'.format(model.explained_variance_ratio_))
        # layout = html.Div([
        #     html.Div([
        #         html.Label('Scatter plot\n'),
        #         dcc.Graph(figure = fig),
        #         html.Ul([html.Li(x) for x in cols])
        #     ]),
        #
        # ]),

        # if n_click > 0:
        #     print(cols)
        #     print(target)
        #
        else:
            return html.Label("Please Submit first.")

    if __name__ == '__main__':
        dash_app.run_server(debug=True)
Exemplo n.º 11
0
    [
        dbc.Tab(gains_losses, label="Gains/Losses", tab_id='gains-losses'),
        dbc.Tab(partial_stats, label="Partial Stats", tab_id='part-stats'),
        dbc.Tab(basic_stats, label="Full Stats", tab_id='full-stats')
        # dbc.Tab(
        #     html.Iframe(src=f'https://www.rbcgam.com/en/ca/products/mutual-funds/RBF900/detail',
        #     className='full-width'),
        #     label="Iframe", tab_id='iframe'
        # )
    ],
    id="tabs",
    active_tab="gains-losses",
)

page_1 = dbc.Row([
    dbc.Col(
        [
            report_title,
            html.Br(),
            html.Br(), metadata_cards,
            html.Br(), page_1_tabs,
            html.Br(),
            html.Br()
            # only here for demo purposes
        ],
        className='shadow-page')
])

page_2 = gen_p2()

app.layout = dbc.Container([page_1, page_2])
Exemplo n.º 12
0
The 'primary variable' defines the 'root table' of the query, and any aggregations to
be performed will hit this table last. Aggregations specified in the 'secondary
variables' will respect the logical structure of the DB, and may be performed in a
subquery. Some examples of OMOP variables are given here, but it is straightforward to
add more.
'''



# --------- CONSTRUCT APP ---------------------------------------------
# external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__) #, external_stylesheets=external_stylesheets)
server = app.server

custom_space = lambda x: html.Div([html.Br()], style={'line-height': f'{x}%'})

app.layout = html.Div([
    dcc.Markdown(children=introduction, style=main_text_style, className="row"),
    html.Br(),
    html.Div([
        html.Div([
                html.Div([
                    dcc.Markdown("**Standard query**:", style=tab_header_text_style,
                                 className="four columns"),
                    html.Div(dropdown_sQuery, className="six columns"),
                ], className="row"),
                html.Br(),
                html.Button(id='submit-button-standard', n_clicks=0,
                            children='Submit', className="four offset-by-four columns"),
                html.Div([dcc.Checklist(id='check-keep-nulls',
        "fontFamily": "Arial",
        "size": 10,
        'textAlign': 'center',
        'color': 'dark'
    },
    css=[{
        'selector':
        '.dash-cell div.dash-cell-value',
        'rule':
        'display: inline; white-space: inherit; overflow: inherit; text-overflow: inherit;'
    }],
)

body = dbc.Container(
    [
        html.Br(),
        dbc.Row(
            [
                dbc.Col(
                    html.Div([
                        html.Br([]),
                        html.H5("Bienvenue!",
                                style={
                                    'color': 'red',
                                    'backgroundColor': 'white'
                                }),
                        html.Br([]),
                        html.P(
                            "\
                            Vous êtes sur la page d'acceuil du tutoriel de développement de dashbord en python avec Dash. \
                            Je vous présente ici les données du trafic web d'un site internet. Ce sont notamment les accès avec  \
Exemplo n.º 14
0
def create_dashboard2(server):
    external_stylesheets = [dbc.themes.BOOTSTRAP]
    app = dash.Dash(__name__,
                    server=server,
                    url_base_pathname='/dashboard2/',
                    external_stylesheets=external_stylesheets)
    selected = []
    atc_list = get_atc()
    app.layout = html.Div(
        className='total-container',
        children=[
            dbc.Container(
                fluid=True,
                children=[
                    html.Div(className='header',
                             children=[
                                 html.H3(className='title',
                                         children="연관 약품 분석 (빈도/관련도)")
                             ]),
                    dbc.Row([
                        dbc.Col([
                            dbc.Card([
                                dbc.Label('단일/복합처방 선택'),
                                dcc.Dropdown(id='select1',
                                             className='select',
                                             options=[{
                                                 'label': '단일',
                                                 'value': 'single'
                                             }, {
                                                 'label': '복수',
                                                 'value': 'multi'
                                             }],
                                             placeholder='성분 개수',
                                             searchable=False),
                                dbc.Label('AND/OR 조건선택'),
                                dcc.Dropdown(id='select2',
                                             className='select',
                                             searchable=False),
                                dbc.Label('품목선택'),
                                dcc.Dropdown(
                                    id='elements',
                                    className='select',
                                    options=[{
                                        'label': str(a) + ' : ' + str(b),
                                        'value': str(a)
                                    } for a, b in zip(atc_list[0], atc_list[1])
                                             ],
                                    placeholder='원하는 성분 선택',
                                    disabled=False,
                                    multi=True,
                                    value=None,
                                    optionHeight=80,
                                ),
                                dbc.Label('지지도 설정'),
                                dcc.Slider(id='num',
                                           min=0.01,
                                           max=40,
                                           step=0.01,
                                           value=10,
                                           included=False,
                                           marks={
                                               i: str(i) + '%'
                                               for i in range(10, 41, 10)
                                           }),
                                html.Br(),
                                dbc.Button("연관 품목 조회",
                                           id="submit_button",
                                           n_clicks=0,
                                           color="primary",
                                           outline=True,
                                           block=True,
                                           loading_state={'is_loading': True}),
                                html.Br(),
                                dbc.Spinner(html.Div(id="alert-msg"))
                            ],
                                     body=True),
                        ],
                                md=3),
                        dbc.Col(
                            [
                                dbc.Row([
                                    dbc.Card([
                                        dbc.CardBody([
                                            dbc.Label('병용처방항목 필터링'),
                                            dcc.Dropdown(
                                                id='filter-freq-elements',
                                                options=[{
                                                    'label':
                                                    str(a) + ' : ' + str(b),
                                                    'value':
                                                    str(a)
                                                } for a, b in zip(
                                                    atc_list[0], atc_list[1])],
                                                placeholder='필터링할 성분 선택',
                                                disabled=False,
                                                multi=True)
                                        ])
                                    ],
                                             style={
                                                 'margin-bottom': '10px',
                                                 'width': '100%'
                                             }),
                                    dbc.Card(
                                        [
                                            dbc.CardBody([
                                                html.Div(
                                                    id='freq-download-button',
                                                    children=[
                                                        html.
                                                        A(html.
                                                          Button(
                                                              '다운로드',
                                                              n_clicks=0),
                                                          id='freq_csv_link',
                                                          href=
                                                          "/dashboard2/download_freq_csv"
                                                          ),
                                                        html.Span(
                                                            id='freq_len',
                                                            className=
                                                            'size_explain')
                                                    ]),
                                                dt.DataTable(
                                                    id='datatable-paging-freq',
                                                    columns=[{
                                                        'name': i,
                                                        'id': i,
                                                        'deletable': True
                                                    } for i in sorted(
                                                        df_freq.columns) if
                                                             i != 'total_set'],
                                                    page_current=0,
                                                    page_size=PAGE_SIZE,
                                                    page_action='custom',
                                                    sort_action='custom',
                                                    sort_mode='multi',
                                                    filter_action='custom',
                                                    filter_query='',
                                                    sort_by=[],
                                                    style_cell={
                                                        'whiteSpace': 'normal',
                                                        'height': 'auto'
                                                    },
                                                    style_table={
                                                        'minWidth': '100%',
                                                        'overflowX': 'auto'
                                                    })
                                            ])
                                        ],
                                        style={
                                            'width': '100%',
                                            'minHeight': '500px',
                                            'padding': '15px'
                                        })
                                ],
                                        style={'margin-bottom': '40px'
                                               }),  #,md=4
                                dbc.Row([
                                    dbc.Card([
                                        dbc.CardBody([
                                            dbc.Label('병용처방항목 필터링'),
                                            dcc.Dropdown(
                                                id='filter-asso-elements',
                                                options=[{
                                                    'label':
                                                    str(a) + ' : ' + str(b),
                                                    'value':
                                                    str(a)
                                                } for a, b in zip(
                                                    atc_list[0], atc_list[1])],
                                                placeholder='필터링할 성분 선택',
                                                disabled=False,
                                                multi=True)
                                        ])
                                    ],
                                             style={
                                                 'margin-bottom': '10px',
                                                 'width': '100%'
                                             }),
                                    dbc.Card(
                                        [
                                            dbc.CardBody([
                                                html.Div(
                                                    id='asso-download-button',
                                                    children=[
                                                        html.
                                                        A(html.
                                                          Button(
                                                              '다운로드',
                                                              n_clicks=0),
                                                          id='asso_csv_link',
                                                          href=
                                                          "/dashboard2/download_asso_csv"
                                                          ),
                                                        html.Span(
                                                            id='asso_len',
                                                            className=
                                                            'size_explain')
                                                    ]),
                                                dt.DataTable(
                                                    id='datatable-paging-asso',
                                                    columns=[
                                                        {
                                                            'name': i,
                                                            'id': i,
                                                            'deletable': True
                                                        } for i in sorted(
                                                            df_asso.columns)
                                                        if i != 'total_set'
                                                    ],
                                                    page_current=0,
                                                    page_size=PAGE_SIZE,
                                                    page_action='custom',
                                                    sort_action='custom',
                                                    sort_mode='multi',
                                                    filter_action='custom',
                                                    filter_query='',
                                                    sort_by=[],
                                                    style_cell={
                                                        'whiteSpace': 'normal',
                                                        'height': 'auto'
                                                    },
                                                    style_table={
                                                        'minWidth': '100%',
                                                        'overflowX': 'auto'
                                                    })
                                            ])
                                        ],
                                        style={
                                            'width': '100%',
                                            'minHeight': '500px',
                                            'padding': '15px'
                                        })
                                ])
                            ],
                            md=9)  #,md=5
                    ]),
                    html.Div(id='intermediate_freq', style={'display':
                                                            'none'}),
                    html.Div(id='intermediate_asso', style={'display': 'none'})
                ],
                style={"margin": "auto"})
        ])
    init_callback(app, atc_list)
    return app
Exemplo n.º 15
0
def make_text_log(subject,
                  width,
                  start_date,
                  end_date,
                  log_len=7,
                  simple_mode=True):
    text_log_df = pd.DataFrame()
    for target in targets:
        if (subject + '_' + target) not in Dataframes:
            continue

        data_to_merge = Dataframes[subject + '_' + target].copy(deep=True)
        data_to_merge['target'] = target
        data_to_merge = data_to_merge.dropna()

        text_log_df = pd.concat([text_log_df, data_to_merge],
                                axis=0,
                                ignore_index=True)

    if len(text_log_df) == 0:
        return html.Div(
            id="logs_tape_" + subject,
            className="six columns inner-row",
            style={'width': width},
            children=[build_major_title(subject)],
        )

    text_log_df.dropna(inplace=True)
    text_log_df['time'] = pd.to_datetime(text_log_df['time'])
    text_log_df.sort_values(by=['time'], inplace=True)

    logs_tape = []
    timestamps = text_log_df['time']

    timestamps = timestamps[start_date <= timestamps][timestamps < end_date]
    timestamps = timestamps.unique()
    timestamps.sort()
    timestamps = timestamps[::-1]

    for timestamp in timestamps:
        df_timestamp = text_log_df[text_log_df['time'] == timestamp]

        text = []
        for i in range(len(df_timestamp)):
            if not simple_mode:
                text.extend([
                    build_medium_title(df_timestamp.iloc[i, :]['target']),
                    build_medium_title(str(pd.to_datetime(timestamp))),
                    f"""Показатель: {df_timestamp.iloc[i, :]['actual']:0.2f}""",
                    html.Br(),
                    f"""Предсказание: {df_timestamp.iloc[i, :]['predictions']:0.2f}"""
                ])
            else:
                text.extend([
                    build_medium_title(df_timestamp.iloc[i, :]['target']),
                    build_medium_title(str(pd.to_datetime(timestamp))),
                    f"""Показатель: {df_timestamp.iloc[i, :]['actual']:0.2f}"""
                ])

        logs_tape.append(html.Div(children=[html.H6(children=text)]))

    return html.Div(
        id="logs_tape_" + subject,
        className="six columns inner-row",
        style={'width': width},
        children=[build_major_title(subject)] + logs_tape[:log_len],
    )
Exemplo n.º 16
0
country_dropdown = dcc.Dropdown(options=get_options(data.all_countries),
                                value=['All'],
                                multi=True,
                                id='country_dropdown',
                                className="dcc_control")

text_label = html.P("Text Input", className="control_label")

text_input = dcc.Input(id="text_input",
                       placeholder="Write your Text Here",
                       className="dcc_control")

products_label = html.P("Products", className="control_label")
products_dropdown = dcc.Dropdown(options=get_options(data.products),
                                 value=data.product_default,
                                 id='products_dropdown',
                                 className="dcc_control")

controls = html.Div([
    invoice_date_range_label, invoice_date_range,
    html.Br(), quantity_label, quantity_slider,
    html.Br(), unit_price_label, unit_price_slider,
    html.Br(), country_label, country_dropdown, text_label, text_input,
    html.Br(),
    html.Br(),
    html.Br(), products_label, products_dropdown
],
                    className="pretty_container four columns",
                    id="cross-filter-options")
Exemplo n.º 17
0
         html.Div(
             className='container',
             children=[
                 html.Div(
                     className="intro-img",
                     children=[
                         #html.Img(src="/assets/img/LogoM7.svg",className='img-fluid')
                         html.Img(src="/assets/img/MobilidataS2.png",
                                  className='img-fluid')
                     ]),
                 html.Div(
                     className="intro-info",
                     children=[
                         html.H2([
                             "We are",
                             html.Br(),
                             html.Span("MobiliData"),
                             html.Br(), "Team 80 DS4A v3"
                         ]),
                         html.Div(children=[
                             html.A(
                                 "Team Members",
                                 href="#team",
                                 className="btn-get-started scrollto")
                         ])
                     ])
             ])
     ]),
 html.Section(
     className="about",
     children=[
Exemplo n.º 18
0
def serve_layout():
    session_id = str(uuid.uuid4())
    print(session_id)

    ### We are counting the amount of visitors of the webpage by counting the amount of session IDs
    ### created per day without tracking any information

    visitor = open(str(UPLOAD_DIRECTORY) + "/" + str(session_id) + ".txt", "wb")

    # the style arguments for the sidebar.
    SIDEBAR_STYLE = {
        'position': 'fixed',
        'top': 0,
        'left': 0,
        'bottom': 0,
        'width': '20%',
        'padding': '20px 10px',
        'background-color': '#f8f9fa'
    }

    # the style arguments for the main content page.
    CONTENT_STYLE = {
        'margin-left': '25%',
        'margin-right': '5%',
        'top': 0,
        'padding': '20px 10px'
    }

    TEXT_STYLE = {
        'textAlign': 'center',
        'color': '#191970'
    }

    CARD_TEXT_STYLE = {
        'textAlign': 'center',
        'color': '#0074D9'
    }

    content_fourth_row = dbc.Row(
        [
            dbc.Col(
                html.Div(
                    id='final-results'
                ), md=12,
            )
        ]
    )

    content_third_row = dbc.Row(
        [
            dbc.Col(
                dcc.Graph(id='theq-chart'), md=12,
            )
        ]
    )

    content_second_row = dbc.Row(
        [
            dbc.Col(
                dcc.Graph(id='refl-chart'), md=6
            ),
            dbc.Col(
                dcc.Graph(id='S21-chart'), md=6
            ),
        ]
    )

    content_first_row = dbc.Row([
        dbc.Col(
            dbc.Card(
                [
                    dbc.CardBody(
                        [
                            html.P(id='card_text_1', children=[
                                'Abstract—We describe an algorithm capable of extracting the unloaded quality factor '
                                'and the resonant frequency of microwave resonators from vector S-parameters. Both '
                                'symmetrical (Lorentzian) and asymmetrical (Fano) transmission responses are supported. '
                                'The algorithm performs an adaptive outlier removal to discard measurement points '
                                'affected by noise or distortion. It removes the effects caused by imperfections in '
                                'he device (such as modes with close resonance frequencies or stray coupling between '
                                'the resonator ports) or the experimental setup (such as lack of isolation or '
                                'dispersion in the test-set and cables). We present an extensive assessment of the '
                                'algorithm performance based on a numerical perturbation analysis and on the evaluation '
                                'of S-parameter fitting results obtained from network analyzer measurements and '
                                'resonator equivalent circuits. Our results suggest that uncertainty is mainly caused '
                                'by factors that distort the frequency dependence of the S-parameters, such as cabling '
                                'and coupling networks and is highly dependent on the device measured. Our perturbation '
                                'analysis shows improved results with respect to those of previous publications. Our '
                                'source code is written in Python using open source packages and is publicly available '
                                'under a freeware license.'
                           ], ),
                        ]
                    )
                ]
            ),
            md=12
        ),
    ])

    content = html.Div(
        [
            html.H1(
                'Algorithm for Resonator Parameter Extraction from Symmetrical and Asymmetrical Transmission Responses',
                style=TEXT_STYLE),
            html.H4("by Patrick Krkotic, Queralt Gallardo, Nikki Tagdulang, Montse Pont and Joan M. O'Callaghan"),
            html.H5("Publication accepted in IEEE Transactions on Microwave Theory and Techniques, to be published soon"),
            html.Div(session_id, id='session-id', style={'display': 'none'}),
            html.Hr(),
            content_first_row,
            content_second_row,
            content_third_row,
            content_fourth_row,
            dcc.ConfirmDialog(
                id='confirm',
                message='The webpage is still being under development.', )
        ],
        style=CONTENT_STYLE
    )

    controls = dbc.FormGroup(
        [
            html.Br(),
            html.H3("Upload", style={'textAlign': 'center'}),
            # html.Div('Upload your data in .s2p Touchstone format.'),
            dcc.Upload(
                id="upload-data",
                children=html.Div(
                    ["Drag and drop or click to upload .s2p files."]
                ),
                style={
                    "width": "98%",
                    "height": "60px",
                    "lineHeight": "60px",
                    "borderWidth": "1px",
                    "borderStyle": "dashed",
                    "borderRadius": "5px",
                    "textAlign": "center",
                },
                multiple=True,
            ),
            html.Div(id="numberoffiles"),
            html.Ul(id="Dictionary"),
            html.Div(id="code-finished"),
            html.Div(
                [
                    dbc.Button(
                        id='button-calculate',
                        n_clicks=0,
                        children='Calculate',
                        color='primary',
                        block=True
                    ),
                    dbc.Spinner(html.Div(id='loading'), color='primary'),
                ]),
            html.Br(),
            html.H3('List of Files', style={
                'textAlign': 'center'
            }),
            dcc.Dropdown(
                id='name-dropdown',
                options=[
                ],
            ),
            html.Br(),
            html.H3('Source Code', style={
                'textAlign': 'center'
            }),
            html.Label(['The source code is available in the Git repository ', html.A('ARPE-edu', href='https://github.com/ARPE-edu/arpe')]),
            html.Br(),
            html.Img(
                src="https://upload.wikimedia.org/wikipedia/commons/thumb/9/97/Logo_UPC.svg/110px-Logo_UPC.svg.png",
                style={
                    'height': '25%',
                    'width': '25%',
                    'float': 'center',
                    'position': 'relative'
                },
            ),

            html.Img(
                src="https://www.cells.es/logo.png",
                style={
                    'height': '50%',
                    'width': '50%',
                    'float': 'center',
                    'position': 'relative'
                },
            ),
        ]
    )

    sidebar = html.Div(
        [
            html.H1('ARPE', style=TEXT_STYLE),
            html.Hr(),
            controls
        ],
        style=SIDEBAR_STYLE,
    )

    stores = html.Div([
        dcc.Store(id='tdict', storage_type='session'),
    ])

    layout = html.Div([sidebar, content, stores])

    return layout
Exemplo n.º 19
0
def create_layout(app):
    return html.Div(
        [
            #header(app),
            html.Div(
                [
                    "证券研究报告"
                ],
                className = "header",
            ),
    
            html.Div(
                [
                    html.Div(
                        [
                            html.Div(["公司研究/公告点评"], id = "title_part1",),
                            html.Div(["2020年06月07日"], id = "title_part2",),
                        ],
                        id = "title_left",
                    ),
                    html.Div(
                        [
                            html.Div(
                                [
                                    html.Div(["交运设备/汽车整车 II"], id = "title_part3",),
                                ],
                                id = "category",
                            ),
                        ],
                        id = "title_right",
                    ),
                ],
                className = "title",
            ),
            html.Div(
                [
                    html.Div(
                        [
                            html.Div(
                                [
                                   
                                    html.Div(
                                        [
                                           "投资评级:买入(维持评级)"
                                        ],
                                        className = "section_title",
                                    ),
                                    html.Div(
                                        [
                                        
                                            html.Div(
                                                [
                                                    html.P(["当前价格(元):"]),
                                                    html.P(["合理价格区间(元): "]),
                                                ],
                                                id = "subsect1_left",
                                            ),
                                            html.Div(
                                                [
                                                    html.P(["18.23"]),
                                                    html.P(["24.64~26.40"]),
                                                ],
                                                id = "subsect1_right",
                                            ),
                                            html.Div([], id = "border_bot"),
                                            html.Div(
                                                [
                                                    html.Div(["林志轩"], className = "staff_name"),
                                                    html.Div(["研究员"], className = "staff_position"),
                                                    html.Div(["刘千琳"], className = "staff_name"),
                                                    html.Div(["研究员"], className = "staff_position"),
                                                    html.Div(["王涛"], className = "staff_name"),
                                                    html.Div(["研究员"], className = "staff_position"),
                                                    html.Div(["邢重阳"], className = "staff_name"),
                                                    html.Div(["联系人"], className = "staff_position"),
                                                ],
                                                id = "staff_info",
                                            ),
                                            html.Div(
                                                [
                                                    html.Div(
                                                        [
                                                            "执业证书编号:S0570519060005", 
                                                            html.Br(),
                                                            "021-28972090 ",
                                                            html.Br(),
                                                            "*****@*****.**",
                                                        ], 
                                                        className = "contact_info",
                                                    ),
                                                    html.Div(
                                                        [
                                                            "执业证书编号:S0570518060004",
                                                            html.Br(),
                                                            "021-28972076",
                                                            html.Br(),
                                                            "*****@*****.**",
                                                        ], 
                                                        className = "contact_info",
                                                    ),
                                                    html.Div(
                                                        [
                                                            "执业证书编号:S0570519110001",
                                                            html.Br(),
                                                            "021-28972053",
                                                            html.Br(),
                                                            "*****@*****.**",
                                                        ], 
                                                        className = "contact_info",
                                                    ),
                                                    html.Div(
                                                        [
                                                            "021-38476205 ",
                                                            html.Br(),
                                                            "*****@*****.**"
                                                        ], 
                                                        className = "contact_info",
                                                    ),
                                                ],
                                                id = "staff_contact",
                                            ),
                                        ],
                                        id = "subsect1",
                                    ),
                                ],
                                className = "block1",
                            ),
                           
                            html.Div(
                                [
                                    html.Div(
                                        [
                                            "相关研究"
                                        ],
                                        className = "section_title",
                                    ),
                                    html.Div(
                                        [
                                            "1《上汽集团(600104 SH,买入): 19 盈利下滑 29%,龙头整装再出发》2020.01"
                                        ],
                                        className = "study_details",
                                    ),
                                    html.Div(
                                        [
                                            "2《上汽集团(600104 SH,买入): 产量同比提 升,批发销量跌幅收窄》2019.09"
                                        ],
                                        className = "study_details",
                                    ),
                                    html.Div(
                                        [
                                            "3《上汽集团(600104 SH,买入): Q2 终端折扣 大,业绩略低于预期》2019.08"
                                        ],
                                        className = "study_details",
                                    ),
                                ],
                                className = "block2",
                            ),
                            html.Div(
                                [
                                    html.Div(
                                        [
                                            "一年股价走势图"
                                        ],
                                        className = "section_title",
                                    ),
                                    
                                    html.Div(
                                        [
                                            html.Img(src=app.get_asset_url('stocks.png')),
                                        ],
                                        className = "stocks_graph",
                                    ),
                                ],
                                className = "block3",
                            ),
                        ],
                        className = "col_left",
                    ),
                    html.Div(
                        [
                            html.Div(
                                [
                                "5月国内销量转正,上汽大众待改善"
                                   
                                ],
                                className = "cr_title",
                            ),
                            html.Div(
                                [
                                    "上汽集团(600104)"
                                ],
                                className = "cr_title2",
                            ),
                            html.Div(
                                [
                                    "5月国内销量增速转正,批发销量增速或弱于行业"
                                ],
                                className = "para_title",
                            ),
                            html.Div(
                                [
                                    "6月5日,公司发布5月销量情况。5月公司实现批发销量47.3万台,同比-1.6%,其中国内销量45.6万台,同比+0.3%。根据中汽协预测,5月汽车 销量同比+11%,上汽销量增速弱于行业,主要原因是受海外疫情影响,出口销量大幅下滑,同时上汽大众销量下滑。我们认为随着疫情结束,汽车需 求有望逐步恢复,Q2 汽车行业批发销量有望转正。随着行业恢复和公司战 略调整进一步深入,公司销量和归母净利润有望逐季恢复,预计 20-22 年 EPS 分别为 1.76、1.98、2.17 元,维持“买入”评级。"
                                ],
                                className = "para_body",
                            ),
                            html.P(),
                            html.Div(
                                [
                                    "上汽通用五菱销量改善明显,上汽通用、自主跌幅收窄"
                                ],
                                className = "para_title",
                            ),
                            html.Div(
                                [
                                    "5 月,上汽大众批发销量 13 万台,同比-15%,上汽通用批发销量 13.6 万 台,同比-3.6%,上汽自主批发销量 5.2 万台,同比-5%,上汽通用五菱批 发销量 12 万台,同比+11%;上汽大通销量 1.6 万台,同比+61%;上汽红 岩销量 10109 台,同比+110%。上汽集团开展了“五五”购物节促销活动, 商用车销量增长迅速,国内批发销量转正。上汽通用五菱战略转型后推出 了较多新车型,销量情况有明显改善。上汽通用三缸机车型逐步转回四缸 机,销量跌幅收窄。上汽自主新车 RX5 Plus 新车上市,销量跌幅收窄。细 分市场竞争激烈,上汽大众销量仍有下滑。"
                                ],
                                className = "para_body",
                            ),
                            html.P(),
                            html.Div(
                                [
                                    "上汽通用三缸机逐步转回四缸机,上汽自主 RX5 Plus 开启预售"
                                ],
                                className = "para_title",
                            ),
                            html.Div(
                                [
                                    "2019 年上汽通用批发销量同比-19%,其中一个原因是三缸机车型不受国 内消费者欢迎,上汽通用英朗、威朗等 13 个车型有三缸机版本。从 2020 年 4 月开始,上汽通用逐步将三缸机车型转回四缸,英朗和科鲁泽已经转 为四缸车型。5 月 4 日,RX5 Plus 开启预售,该车型是上汽自主主力车型 rx5 中期改款,新车共推出三个版本,官方预售价 12.28~13.98 万元。我 们认为新车在前脸设计、内饰设计和智能网联配置上有较大改善,RX5 Plus 有望帮助上汽自主提升 10~15 万紧凑型 SUV 细分领域市占率,上汽自主 销量有望逐季改善。"
                                ],
                                className = "para_body",
                            ),
                            html.P(),
                            html.Div(
                                [
                                    "销量和利润有望逐季改善,维持“买入”评级"
                                ],
                                className = "para_title",
                            ),
                            html.Div(
                                [
                                    "上汽通用和上汽通用五菱销量情况正在逐步改善。2020 年 Q4 上汽大众 MEB 工厂有望投产,上汽大众有望在新能源汽车领域取得突破。2021 年 上汽奥迪投产在望,公司进一步布局豪华车领域,未来发展值得期待。我 们预计公司 2020-22 年分别实现归母净利 205、231、254 亿元,EPS 分 别为 1.76、1.98、2.17 元,同行业可比公司 20 年平均估值 16.8XPE, 考虑到公司业绩弹性略弱于可比公司,维持公司 20 年 14~15XPE 估值, 维持目标价 24.64~26.4 元,维持“买入”评级。 "
                                ],
                                className = "para_body",
                            ),
                            html.P(),
                            html.Div(
                                [
                                    "风险提示:我国汽车销量增速不及预期,公司海外市场拓展不及预期。"
                                ],
                                className = "para_body",
                            ),
                        ],
                        className = "col_right",
                    ),
                    html.Div(
                        [
                            
                            html.Div(
                                [   
                                    html.Div(
                                        [
                                            "公司基本资料"
                                        ],
                                        className = "section_title",
                                    ),
                                    
                                    html.Div(
                                        [
                                            html.Table(make_dash_table(stocks_asset)),
                                        ],
                                        id = "table1",
                                    ),
                                ],
                                id = "block4",
                            ),
                            
                            html.Div(
                                [
                                    html.Div(
                                        [
                                            "经营预测指标与估值"
                                        ],
                                        className = "section_title",
                                    ),
                                    html.Table(make_dash_table(accounting)),
                                ],
                                id = "block5",
                            ),
                        ],
                        className = "col_bot",
                    ),
                ],
                className = "body",
            ),
        ],
        className = "page",
    )
Exemplo n.º 20
0
def genResult(src, user, iframe, **kwargs):
    tabs = html.Div([
        html.Div('', className='tile is-3'),
        html.Div([
            html.Div([
                html.Ul([
                    html.Li(
                        [
                            html.A('视频词云'),
                        ],
                        className='is-active',
                        id='tabsCloud',
                    ),
                    html.Li([
                        html.A('短文本主题建模'),
                    ], id='tabsLDA'),
                    html.Li([
                        html.A('文章统计', ),
                    ], id='tabsOther'),
                ])
            ],
                     className='tabs is-centered is-medium',
                     style={'width': '100%'}),
        ],
                 className='tile is-6')
    ],
                    className='tile is-ancestor',
                    style={'marginBottom': '1rem'})
    # tabs = html.Div([
    #             html.Ul([
    #                 html.Li([
    #                     html.A('视频词云'),
    #                 ], className='is-active', id='tabsCloud', ),
    #                 html.Li([
    #                     html.A('LDA主题分析'),
    #                 ], id='tabsLDA'),
    #                 html.Li([
    #                     html.A('文章统计', ),
    #                 ],id='tabsOther'),
    #             ])
    #         ], className='tabs is-centered is-medium', style={'margin': '0 25% 2rem 25%'}),
    tabsColud = html.Div([
        html.Img(src=src,
                 className='',
                 style={
                     'max-width': '600px',
                     'min-width': '300px'
                 }),
    ],
                         className='wcImg',
                         id='userWC'),
    tabsLDA = html.Div([
        html.Iframe(src=iframe,
                    style={
                        'height': '130vh',
                        'width': '100%',
                        'overflow': 'hidden'
                    }),
    ],
                       className='wcImg',
                       id='userLDA',
                       style={'display': 'none'}),
    tabsOther = html.Div([
        html.Div(genTongji(**kwargs), style={'width': '100%'}),
    ],
                         className='',
                         id='userOther',
                         style={
                             'display': 'none',
                             'width': '100%'
                         }),
    userInfo = html.Div([
        html.Div('', className='tile is-3'),
        html.Div([
            html.Div([
                html.Article([
                    html.Figure([
                        html.P([html.Img(src=user.avatar)],
                               className='image is-64x64')
                    ],
                                className='media-left'),
                    html.Div([
                        html.Div([
                            html.P([
                                html.Strong(user.nickname,
                                            id='recordNickName'),
                                html.Small(' | ' + user.user_id,
                                           style={'whiteSpace': 'pre'}),
                                html.P(user.user_id,
                                       style={'display': 'none'},
                                       id='recordUserId'),
                                html.Br(),
                                html.Div(user.signature)
                            ])
                        ],
                                 className='content'),
                        html.Div([
                            html.Div([
                                html.Div([
                                    html.Span('作品: ',
                                              style={'whiteSpace': 'pre'}),
                                    html.Span(
                                        format(user.aweme_count, ',') if user.
                                        aweme_count else '未知'),
                                ],
                                         className='level-item'),
                                html.Div([
                                    html.Span('获赞: ',
                                              style={'whiteSpace': 'pre'}),
                                    html.Span(
                                        format(user.total_favorited, ',')
                                        if user.total_favorited else '未知'),
                                ],
                                         className='level-item'),
                                html.Div([
                                    html.Span('粉丝: ',
                                              style={'whiteSpace': 'pre'}),
                                    html.Span(
                                        format(user.aweme_fans, ',') if user.
                                        aweme_fans else '未知'),
                                ],
                                         className='level-item'),
                            ],
                                     className='level-left')
                        ],
                                 className='level is-mobile')
                    ],
                             className='media-content'),
                    html.Div([
                        html.Button(
                            '相似用户',
                            className='button is-primary is-outlined is-small',
                            id='searchSimalar')
                    ],
                             className='media-right')
                ],
                             className='media'),
            ],
                     className='box',
                     style={'width': '100%'}),
        ],
                 className='tile is-6 search_input')
    ],
                        className='tile is-ancestor',
                        style={'marginBottom': '1rem'}),

    fig = [userInfo, tabs, tabsColud, tabsLDA, tabsOther]
    return fig
Exemplo n.º 21
0
def init_attacker(server):
    app = dash.Dash(
        server=server,
        url_base_pathname=URL_BASE,
        suppress_callback_exceptions=True,
    )

    app.layout = html.Div(children = [
        html.H1(
            children = 'Fantasy Premier League Attack/Midfield Dashboard',
            style = {
                'textAlign':'center',
                'color':'#28D0B4',
            }
        ),
        html.Div(
            children = 'This interactive web app can be a toolkit for you to select and optimise your player selection based on their previous year\'s performances',
            style = {
                'color':'#28D0B4',
            }
        ),

        html.Div(
            id = 'stats-menu',
            className = 'dropdowns',
            children = [
                dcc.Dropdown(
                    id = 'yaxis',
                    className = 'ydropdown',
                    options = [
                        {'label':'Players','value':'player'},
                        {'label':'Games','value':'games'},
                        {'label':'Minutes','value':'minutes'},
                        {'label':'Total 90s','value':'minutes_90s'},
                        {'label':'Goals per90','value':'goals_per90'},
                        {'label':'Assists per90','value':'assists_per90'},
                        {'label':'Penalties Attempted','value':'pens_att'},
                        {'label':'Penalty Conversion %','value':'pen_conv'},
                        {'label':'Yellow Cards','value':'cards_yellow'},
                        {'label':'Red Cards','value':'cards_red'},
                        {'label':'Goals & Assists per90','value':'goals_assists_per90'},
                        {'label':'Goals + Assists - Penalties per90','value':'goals_assists_pen_per90'},
                        {'label':'Expected Goals per90','value':'xg_per90'},
                        {'label':'Expected Assists per90','value':'xa_per90'},
                        {'label':'xG & xA per90','value':'xg_xa_per90'},
                        {'label':'Non-Penalty Expected goals per90','value':'npxg_per90'},
                        {'label':'npxG + xA per90','value':'npxg_xa_per90'},
                        {'label':'xG_net','value':'xg_net'},
                        {'label':'Cost','value':'cost'},
                        {'label':'Points earned','value':'points'},
                        {'label':'Points per game','value':'ppg'},
                        {'label':'Points per cost','value':'ppc'}
                    ],
                    placeholder = 'Choose statistics for Y axis',
                    searchable = True,
                    value = 'points'
                ),
                dcc.Dropdown(
                    id = 'xaxis',
                    className = 'xdropdown',
                    options = [
                        {'label':'Players','value':'player'},
                        {'label':'Games','value':'games'},
                        {'label':'Minutes','value':'minutes'},
                        {'label':'Total 90s','value':'minutes_90s'},
                        {'label':'Goals per90','value':'goals_per90'},
                        {'label':'Assists per90','value':'assists_per90'},
                        {'label':'Penalties Attempted','value':'pens_att'},
                        {'label':'Penalty Conversion %','value':'pen_conv'},
                        {'label':'Yellow Cards','value':'cards_yellow'},
                        {'label':'Red Cards','value':'cards_red'},
                        {'label':'Goals & Assists per90','value':'goals_assists_per90'},
                        {'label':'Goals + Assists - Penalties per90','value':'goals_assists_pen_per90'},
                        {'label':'Expected Goals per90','value':'xg_per90'},
                        {'label':'Expected Assists per90','value':'xa_per90'},
                        {'label':'xG & xA per90','value':'xg_xa_per90'},
                        {'label':'Non-Penalty Expected goals per90','value':'npxg_per90'},
                        {'label':'npxG + xA per90','value':'npxg_xa_per90'},
                        {'label':'xG_net','value':'xg_net'},
                        {'label':'Cost','value':'cost'},
                        {'label':'Points earned','value':'points'},
                        {'label':'Points per game','value':'ppg'},
                        {'label':'Points per cost','value':'ppc'}
                    ],
                    placeholder = 'Choose statistics for X axis',
                    searchable = True,
                    value= 'player'
                ),
                dcc.RadioItems(
                    id='plot',
                    className = 'plot-select',
                    options=[{'label': 'Bar Plot', 'value': 'bar'},
                            {'label': 'Scatter Plot', 'value': 'scatter'},
                    ],
                    value='scatter'
                ),
            ]
        ),

        dcc.Graph(
            id='stats-graph',
            className = 'graph',
            style = {
                'marginTop':40,
            }
        ),

        html.Div(className = 'info-panel',children=[
            html.H5(children = 'Some of the stats used',style ={'marginBottom':-2}),
            dcc.Markdown('''
            '''
            ),
            html.A(' - Statisfy -  A collections of Basic Football Analytics',href='https://github.com/sidthakur08/statisfy'),
            html.Br(),
            html.A(' - Contact me on Twitter :)',href = 'https://twitter.com/sidtweetsnow',target='_blank'),
            html.Br(),
        ]),

        html.Div(className = 'link-name', children = [
            html.A('Link to the github repository',href = "https://github.com/sidthakur08/fpl_explore",target='_blank')
        ]),
        html.Br(),
        html.Br(),
        html.Br(),
    ])

    init_attacker_callbacks(app)

    return app.server
Exemplo n.º 22
0
                dcc.Link(_page,
                         href=PAGES_HREF[_page],
                         className="active item"))
        else:
            menu_list.append(
                dcc.Link(_page, href=PAGES_HREF[_page], className="item"))
    menu = html.Div([menu_list], className="ui tabular menu")
    return menu


layout = html.Div([
    print_button(),
    html.Div([
        get_logo(),
        get_header(),
        html.Br([]),
        get_menu2(page_id),
    ]),
    html.P(children='''
        Chào mừng bạn đã đến với trang chủ của trang
    '''),
    html.Div(children='''
        Trang này dùng dữ liệu có sẵn từ kết quả thi tốt nghiệp THPT 2018 để vẽ vài biểu đồ
    '''),
    dcc.Graph(id='histogram-graph-hcmc-physics',
              figure={
                  'data': [
                      go.Histogram(x=data_wrapper["TP.HCM"]['LÝ'],
                                   histnorm='probability')
                  ],
                  'layout': {
Exemplo n.º 23
0
# the whole site is partitioned in 12 column parts.
# if you want to define two columns, you use respectively 6 parts:
# html.Div([html.Div([], classnames='six columns), html.Div([], className='six columns')], classname='row')

app.layout = html.Div(
    style={'backgroundColor': 'silver'},
    children=[

        #title
        html.
        H1(children=
           'Interactive Dashboard for Data Visualization of Quality Data in Car Manufacturing Plants'
           ),

        #line breaks
        html.Br(),
        html.Br(),

        # description text for dashboard (such that it only covers one part of website)
        html.Div([
            html.Div([
                html.Div(
                    'In production lines mistakes are made by humans and machines that lead to defects on the produced cars. Information about the defects and the reparation processes are saved in datasests, which are analyzed by car manufacturers.',
                    style={'fontSize': 20}),
                html.Br()
            ],
                     className="six columns"),
            html.Div([html.Br()], className="six columns")
        ],
                 className="row"),
        html.Div(
Exemplo n.º 24
0
def num_analysis(n_clicks, input, *args):
    if input is None or input == '':
        return html.H5('')
    elif use_df is None:
        return html.H5('目的変数が選択されていません。')
    else:
        # 統計量一覧表の描画
        if input == 'AAA':
            describe = processed_df[num_cols].describe().round(4).reset_index()
            return [
                dash_table.DataTable(column_selectable='multi',
                                     fixed_rows={
                                         'headers': True,
                                         'data': 0
                                     },
                                     data=df_processor(describe)[0],
                                     columns=df_processor(describe)[1],
                                     style_table={
                                         'overflowX': 'scroll',
                                         'overflowY': 'scroll',
                                         'maxHeight': '350px',
                                         'maxWidht': '800px'
                                     },
                                     style_header={
                                         'fontWeight': 'bold',
                                         'textAlign': 'center'
                                     }),
                html.Br()
            ]
        # ペアプロットの描画
        elif input == 'BBB':
            fig = px.scatter_matrix(processed_df,
                                    dimensions=num_cols,
                                    color=target_column)
            fig.update_layout(dragmode='select',
                              width=1000,
                              height=600,
                              hovermode='closest')
            return [
                dcc.Graph(figure=fig,
                          style={
                              'textAlign': 'center',
                              'padding': '20px'
                          }),
                html.Br()
            ]
        # 相関係数(ヒートマップ)の描画
        elif input == 'CCC':
            corr = processed_df[num_cols].corr().round(4)
            fig = ff.create_annotated_heatmap(z=corr.values,
                                              x=list(corr.columns),
                                              y=list(corr.index),
                                              colorscale='Oranges',
                                              hoverinfo='none')
            return [
                dcc.Graph(figure=fig,
                          style={
                              'textAlign': 'center',
                              'padding': '20px'
                          }),
                html.Br()
            ]
Exemplo n.º 25
0
        html.Div([
            html.H4(children='Clinical Dashboard',
                    style={
                        'color': colors[14],
                        'backgroundColor': "#18191c"
                    }),
            html.Div(id='table_data'),
            dcc.Interval(id='update_table', interval=480 * 1000, n_intervals=0)
        ],
                 className='container')
    ],
             className='row'),
    html.Div([
        html.Div([
            'Resources',
            html.Br(),
            html.A("Tableau Clinical Dashboard",
                   href='https://public.tableau.com/profile/jacob.sosine1#!/'),
            html.Br(),
            html.A('JakeSosine github', href='https://github.com/jakesosine'),
            html.Br(),
            html.Br(), 'Created by ',
            html.A('@87JTS', href='https://twitter.com/87Jts')
        ],
                 className='container',
                 style={'color': colors[15]},
                 id='footer')
    ],
             className='row')
],
                      style={'backgroundColor': "#18191c"},
Exemplo n.º 26
0
def model_training(n_clicks, C, *args):
    if n_clicks == 0:
        return html.H5('開始ボタンを押すと、学習が始まります')
    else:
        # データの分割
        X = processed_df.drop(target_column, axis=1)
        y = processed_df.loc[:, target_column]
        if y.dtype == 'object':
            y = y.apply(lambda x: 1
                        if x == list(y.value_counts().index)[0] else 0)
        X_tr, X_va, y_tr, y_va = train_test_split(X,
                                                  y,
                                                  test_size=0.2,
                                                  random_state=928)
        # 学習+推論
        model = LogisticRegression(C=10**C, class_weight='balanced')
        model.fit(X_tr, y_tr)
        y_pred_tr = model.predict_proba(X_tr)[:, 1]
        y_pred_va = model.predict_proba(X_va)[:, 1]
        # ROC曲線の描画
        fig1 = go.Figure()
        fig1.add_shape(type='line',
                       line=dict(dash='dash'),
                       x0=0,
                       x1=1,
                       y0=0,
                       y1=1)
        fpr_tr, tpr_tr, _ = roc_curve(y_tr, y_pred_tr)
        fpr_va, tpr_va, _ = roc_curve(y_va, y_pred_va)
        fig1.add_trace(
            go.Scatter(x=fpr_tr, y=tpr_tr, name="train", mode='lines'))
        fig1.add_trace(
            go.Scatter(x=fpr_va, y=tpr_va, name="valid", mode='lines'))
        fig1.update_layout(title='ROC曲線',
                           xaxis_title='False Positive Rate',
                           yaxis_title='True Positive Rate',
                           yaxis=dict(scaleanchor="x", scaleratio=1),
                           xaxis=dict(constrain='domain'),
                           width=500,
                           height=500)
        # 回帰係数の描画
        fig2 = go.Figure(data=go.Bar(x=X_tr.columns, y=model.coef_.flatten()),
                         layout=go.Layout(title='変数重要度(回帰係数)',
                                          xaxis=dict(title='カラム名')))
        # AUCスコアと合わせて出力
        return [
            html.Div([
                dcc.Graph(figure=fig1,
                          style={
                              'float': 'left',
                              'padding': '20px',
                              'height': '500px'
                          }),
                dcc.Graph(figure=fig2,
                          style={
                              'float': 'left',
                              'padding': '20px',
                              'height': '500px'
                          })
            ]),
            html.H5('AUC(train):{}'.format(
                roc_auc_score(y_true=y_tr, y_score=y_pred_tr))),
            html.H5('AUC(valid):{}'.format(
                roc_auc_score(y_true=y_va, y_score=y_pred_va))),
            html.Br()
        ]
Exemplo n.º 27
0
import imageio
from dash_slicer import VolumeSlicer


app = dash.Dash(__name__, update_title=None)

vol = imageio.volread("imageio:stent.npz")
vol = vol[::3,:,:]
spacing = 3, 1, 1

slicer0 = VolumeSlicer(app, vol, spacing=spacing, axis=0)
slicer1 = VolumeSlicer(app, vol, spacing=spacing, axis=1)

slicer0.graph.config["scrollZoom"] = False
slicer1.graph.config["scrollZoom"] = False

app.layout = html.Div(
    style={
        "display": "grid",
        "gridTemplateColumns": "33% 33%",
    },
    children=[
        html.Div([slicer0.graph, html.Br(), slicer0.slider, *slicer0.stores]),
        html.Div([slicer1.graph, html.Br(), slicer1.slider, *slicer1.stores]),
    ],
)


if __name__ == "__main__":
    app.run_server(debug=True, dev_tools_props_check=False)
Exemplo n.º 28
0
def dt_model_train(n_clicks):
    c = db.get('dt.model_class')
    var = db.get('dt.model_variables')
    train = db.get('dt.model_train')
    if c is None and var is None and train is None:
        div = ""
    elif train is None or train < 0 or train > 100:
        div = common.error_msg('Training % should be between 0 - 100 !!')
    elif (not c is None) and (not var is None) and (not train is None):

        try:
            cols = [] + var
            cols.append(c)
            df = db.get('dt.data')
            df = df[cols].astype(str)
            train_df, test_df = common.split_df(df, c, train)

            distinct_count_df_total = get_distinct_count_df(df, c, 'Total Count')
            distinct_count_df_train = get_distinct_count_df(train_df, c, 'Training Count')
            distinct_count_df_test = get_distinct_count_df(test_df, c, 'Testing Count')

            distinct_count_df = distinct_count_df_total.join(distinct_count_df_train.set_index('Class'), on='Class')
            distinct_count_df = distinct_count_df.join(distinct_count_df_test.set_index('Class'), on='Class')

            training_set = train_df.values.tolist()
            model = DecisionTree()
            tree = model.learn(training_set, cols, c)
            print(tree)

            test_set = test_df.values.tolist()
            y_predict = model.predict(test_set)
            cc_percentage = model.score(test_set, y_predict) * 100

            summary = {}
            summary['Total Training Data'] = len(train_df)
            summary['Total Testing Data'] = len(test_df)
            summary['Total Number of Features in Dataset'] = len(var)
            summary['Model Accuracy %'] = round(cc_percentage, 2)
            summary['Features'] = str(var)
            summary_df = pd.DataFrame(summary.items(), columns=['Parameters', 'Value'])

            db.put('dt.data_train', train_df)
            db.put('dt.data_test', test_df)
            db.put('dt.model_summary', summary)
            db.put('dt.model_instance', model)
            #confusion_df = get_confusion_matrix(test_df, c, var, instanceOfLR)
        except Exception as e:
            traceback.print_exc()
            return common.error_msg("Exception during training model: " + str(e))

        div = html.Div([
            html.H2('Class Grouping in Data:'),
            dbc.Table.from_dataframe(distinct_count_df, striped=True, bordered=True, hover=True, style = common.table_style),
            html.H2('Tree:'),
            html.H2(str(tree)),
            html.Br(),
            html.H2('Model Parameters & Summary:'),
            dbc.Table.from_dataframe(summary_df, striped=True, bordered=True, hover=True, style = common.table_style),
            html.Br(),
            #html.H2('Confusion Matrix (Precision & Recall):'),
            #dbc.Table.from_dataframe(confusion_df, striped=True, bordered=True, hover=True, style = common.table_style),
            html.Br(),
            html.H2('Prediction/Classification:'),
            html.P('Features to be Predicted (comma separated): ' + ','.join(var), style = {'font-size': '16px'}),
            dbc.Input(id="dt-prediction-data", placeholder=','.join(var), type="text"),
            html.Br(),
            dbc.Button("Predict", color="primary", id = 'dt-predict'),
            html.Div([], id = "dt-prediction")
            ])
    else:
        div = common.error_msg('Select Proper Model Parameters!!')
    return div
            marks={i: str(i)
                   for i in range(0, 101, 5)},
            tooltip={'placement': 'bottom'}),
 html.Hr(),
 html.Label('Podaj wartość kredytu:'),
 dcc.Input(id='input-1', type='number'),
 html.Hr(),
 html.Label('Podaj swój wiek:'),
 dcc.Slider(id='slider-2',
            min=18,
            max=90,
            step=1,
            marks={i: str(i)
                   for i in range(18, 91, 3)},
            tooltip={'placement': 'bottom'}),
 html.Br(),
 html.Label('Płeć:'),
 html.Div([
     dcc.RadioItems(id='radioitems-1',
                    options=[{
                        'label': i,
                        'value': j
                    } for i, j in zip(['mężczyzna', 'kobieta'], [1, 0])
                             ])
 ],
          style={
              'width': '20%',
              'textAlign': 'left'
          }),
 html.Br(),
 html.Label('Zawód:'),
Exemplo n.º 30
0
           className="lead"),
    html.P(
        'These two graphs show total crimes commited by race and the percent of those'
        ' crimes by total population of that race. You can change the type of crime below.',
        className="lead"),
    html.Hr(className="my-2"),
    html.Div(style={'textAlign': 'center'},
             children=[
                 dcc.Dropdown(id='crime_choice',
                              options=[{
                                  'label': i + ' ',
                                  'value': i
                              } for i in data['Crime'].unique()],
                              value='Aggravated Assault')
             ]),
    html.Br(),
    html.Br(),
    html.Br(),
    html.Br()
])


def make_plotly_total_sums():
    df = grouped_data.merge(
        data[['Year', 'Code', 'Race', 'Population_Totals']],
        on=['Year', 'Code',
            'Race']).drop_duplicates().groupby(['Year',
                                                'Race']).sum().reset_index()

    fig = px.line(x=df['Year'],
                  y=df['Count'] / df['Population_Totals'],