Beispiel #1
0
def generate_table(dataframe, max_rows=100, download_link=False):

    components = []
    if download_link:
        csv_string = dataframe.to_csv(index=False,
                                      encoding='utf-8',
                                      float_format='%.2f')
        link = html.A('Download CSV',
                      download="synthesis_conditions.csv",
                      href="data:text/csv;charset=utf-8," +
                      urllib.parse.quote(csv_string),
                      target="_blank",
                      className='button')
        components.append(link)

    components.append(
        html.Table(
            # Header
            [html.Tr([html.Th(col) for col in dataframe.columns])] +

            # Body
            [
                html.Tr([
                    html.Td(cell_format(dataframe.iloc[i][col]))
                    for col in dataframe.columns
                ]) for i in range(min(len(dataframe), max_rows))
            ]))

    return components
Beispiel #2
0
def get_country_table(df, year):
    return html.Div([
        html.H3('Needs -  Data from {0}'.format(year)),
        html.Table([
            html.Tr([
                html.Th([col], style={'text-align': 'center'}) for col in [
                    '',
                    html.I(className="fas fa-percent fa-lg"),
                    html.I(className="fas fa-child fa-lg"),
                    html.I(className="fas fa-box fa-lg")
                ]
            ])
        ] + [
            html.Tr([
                html.Th(col['title']),
                html.Td(df[col['type']]),
                html.
                Td(functions.format_number_col(df[col['type'] + '_children'])),
                html.Td(get_needs_kg(df, col['type']))
            ],
                    style={'color': col['color']}) for col in [
                        {
                            'title': 'Severe Wasting',
                            'type': 'severe_wasting',
                            'color': SEVERE_WASTING_COLOR
                        },
                        {
                            'title': 'Moderate Wasting',
                            'type': 'moderate_wasting',
                            'color': MODERATE_WASTING_COLOR
                        },
                        {
                            'title': 'Overall Wasting',
                            'type': 'wasting',
                            'color': WASTING_COLOR
                        },
                        {
                            'title': 'Stunting',
                            'type': 'stunting',
                            'color': STUNTING_COLOR
                        },
                        {
                            'title': 'Overweight',
                            'type': 'overweight',
                            'color': OVERWEIGHT_COLOR
                        },
                        {
                            'title': 'Underweight',
                            'type': 'underweight',
                            'color': UNDERWEIGHT_COLOR
                        },
                    ]
        ]),
        html.Div(children=[
            html.P('Source : ' + df['source'].astype(str)),
            html.P('By : ' + df['report_author'].astype(str))
        ],
                 style={'font-size': 'x-small'})
    ],
                    style={'font-size': 'small'})
Beispiel #3
0
def generate_table(dataframe, max_rows=10):
    return html.Table([
        html.Thead(html.Tr([html.Th(col) for col in dataframe.columns])),
        html.Tbody([
            html.Tr(
                [html.Td(dataframe.iloc[i][col]) for col in dataframe.columns])
            for i in range(min(len(dataframe), max_rows))
        ]),
    ])
Beispiel #4
0
def make_dash_table(old_code, new_code):
    # Line 2
    old_income = get_attribute(old_code, 'Average income of inhabitants')
    new_income = get_attribute(new_code, 'Average income of inhabitants')
    result_income = float(new_income) / float(old_income) - 1
    if result_income > 0:
        analysis_income = f"↗ {result_income:.2%} potential increase"
    elif result_income > -0.15:
        analysis_income = "Similar income"
    else:
        analysis_income = f"↘ {result_income:.2%} easier life"

    # Line 3
    attribute_name = 'Academic degree - Higher level university degree scaled'
    old_education = float(get_attribute(old_code, attribute_name))
    new_education = float(get_attribute(new_code, attribute_name))
    result_education = new_education - old_education
    analysis_education = "↗ Find more skilled fellows" if result_education > 0 else "↘ Less competitions"

    # for x in old_dict.keys():
    #    table.append(four_row_list(x, old_dict[x], new_dict[x], ""))

    # Line 4
    # url = "https://avoindata.prh.fi/bis/v1?totalResults=true&maxResults=1&resultsFrom=10000" + \
    #       "&streetAddressPostCode={:s}&companyRegistrationFrom=1950-01-01"
    # print("This part takes time (~10s). Comment this part to accelerate. \n(From line 100, reference_function.py)")
    # old_company_num = eval(requests.get(url.format(old_code)).text.split(',"previous')[0] + '}')['totalResults']
    # new_company_num = eval(requests.get(url.format(new_code)).text.split(',"previous')[0] + '}')['totalResults']
    # result_company_num = int(new_company_num) - int(old_company_num)
    # analysis_company_num = "↗ Big town with more opportunities" if result_company_num > 0 else "↘ Peaceful life"
    return html.Table(
        [
            html.Thead(
                html.Tr([
                    html.Th(),
                    html.Th("Current Location"),
                    html.Th("New Location"),
                    html.Th("Significance")
                ])),
            html.Tbody([
                html.Tr([
                    html.Td("Income"),
                    html.Td(old_income),
                    html.Td(new_income),
                    html.Td(analysis_income)
                ]),
                html.Tr([
                    html.Td("Education index"),
                    html.Td(f"{old_education:.2%}"),
                    html.Td(f"{new_education:.2%}"),
                    html.Td(analysis_education)
                ]),
                # html.Tr([html.Td("Number of companies"), html.Td(old_company_num),
                #         html.Td(new_company_num), html.Td(analysis_company_num)])
            ])
        ],
        id="insight_table")
def generate_table(dataframe):
    return html.Table([
        html.Thead(html.Tr([html.Th(col) for col in dataframe.columns])),
        html.Tbody([
            html.Tr(
                [html.Td(dataframe.iloc[i][col]) for col in dataframe.columns])
            for i in range(len(dataframe))
        ])
    ])
Beispiel #6
0
def get_about_html():
    text = """
           This is the implementation of our Data Science Project. The aim of this project is to provide 
           suggestions on suitable relocation areas in Finland, based on housing prices and demographics.
           """
    return html.Div([
        html.H1("About"),
        html.H3(text, id="about_text"),
        html.H1("Team"),
        html.Table([
            html.Thead(
                html.Tr([
                    html.Th("Letizia"),
                    html.Th("Taige"),
                    html.Th("Roope"),
                    html.Th("Trang"),
                    html.Th("Thong")
                ])),
            html.Tbody(
                html.Tr([
                    html.Td(
                        html.A(html.Img(
                            src=
                            "https://avatars1.githubusercontent.com/u/45148109?s=200&v=4",
                            alt="Letizia"),
                               href="https://github.com/letiziaia")),
                    html.Td(
                        html.A(html.Img(
                            src=
                            "https://avatars2.githubusercontent.com/u/16875716?s=200&v=4",
                            alt="Taige"),
                               href="https://github.com/xiaoxiaobt")),
                    html.Td(
                        html.A(html.Img(
                            src=
                            "https://avatars2.githubusercontent.com/u/43811718?s=200&v=4",
                            alt="Roope"),
                               href="https://github.com/rooperuu")),
                    html.Td(
                        html.A(html.Img(
                            src=
                            "https://avatars3.githubusercontent.com/u/55182434?s=200&v=4",
                            alt="Trang"),
                               href="https://github.com/trangmng")),
                    html.Td(
                        html.A(html.Img(
                            src=
                            "https://avatars0.githubusercontent.com/u/32213097?s=200&v=4",
                            alt="Thong"),
                               href="https://github.com/trananhthong"))
                ]))
        ],
                   id="team_table")
    ],
                    id="about_info")
def df_to_table(df):
    """Transforms a dataFrame into an html table for Dash
    """
    return html.Table(
        # Header
        [html.Tr([html.Th(col) for col in df.columns])] +

        # Body
        [
            html.Tr([html.Td(df.iloc[i][col]) for col in df.columns])
            for i in range(len(df))
        ])
Beispiel #8
0
    def append(self, data, report, label):
        """Append a row to the table.

        Parameters
        ----------
        data : :class:`numpy.ndarray`
            The data.
        report : :class:`.CalibrationReport`
            The report.
        label : :class:`str`
            The label to insert in the first column of the table.
        """
        tab = data.dtype.names[1]
        values = data[tab]
        report_number = '<uncorrected>' if tab == 'dewpoint' else report.number
        nrows = len(self._table)
        if values.size > 0:

            # if the max or min values are outside of the range that was used
            # in the calibration report then change the colour of the row
            style, mx, mn = None, np.max(values), np.min(values)
            if tab != 'dewpoint':
                r = getattr(report, tab)
                if mx > r['max'] or mn < r['min']:
                    style = dict(backgroundColor='#FF0000')

            self._table.append(
                html.Tr([
                    html.Td(label, style=style),
                    html.Td(report_number, style=style),
                    html.Td(tab.title() if not style else tab.title() + ' [value out of range]', style=style),
                    html.Td(f'{np.average(values):.1f}', style=style),
                    html.Td(f'{np.std(values):.1f}', style=style),
                    html.Td(f'{np.median(values):.1f}', style=style),
                    html.Td(f'{mx:.1f}', style=style),
                    html.Td(f'{mn:.1f}', style=style),
                    html.Td(f'{values.size}', style=style),
                ], style=dict(backgroundColor='#F2F2F2' if nrows % 2 else '#FFFFFF'))
            )
        else:
            self._table.append(
                html.Tr([
                    html.Td(label),
                    html.Td(report_number),
                    html.Td(tab.title()),
                    html.Td(''),
                    html.Td(''),
                    html.Td(''),
                    html.Td(''),
                    html.Td(''),
                    html.Td('0'),
                ], style=dict(backgroundColor='#F2F2F2' if nrows % 2 else '#FFFFFF'))
            )
Beispiel #9
0
def show_document(match: dict):
    url = f"/pdf/{match['pdf']}"
    iframe = dbc.Row(
        dbc.Col(html.Iframe(src=url, style={
            "width": "100%",
            "height": "100%"
        })),
        style={
            "resize": "vertical",
            "overflow-y": "hidden",
            "height": "1000px",
            "min-height": "100px",
        },
    )
    title = match["title"].replace("_", " ")
    title = " ".join([w.capitalize() for w in title.split()])
    title = dbc.Row(dbc.Col(html.H3(title)))
    date = html.A(
        match["date"],
        id={
            "type": "link_date",
            "date": match["date"]
        },
        href="#",
        n_clicks=0,
        style={
            "text-decoration": "none",
            "color": "inherit"
        },
    )
    tags = html.P([
        dbc.Badge(
            tag,
            id={
                "type": "link_tag",
                "tag": tag
            },
            href="#",
            n_clicks=0,
            color="primary",
            className="mr-1",
        ) for tag in match["tags"]
    ])
    data = dbc.Table(
        [
            html.Tbody([
                html.Tr([html.Td("Date"), html.Td(date)]),
                html.Tr([html.Td("Tags"), html.Td(tags)]),
            ])
        ],
        striped=True,
    )
    return dbc.Row([dbc.Col([title, data], width=4), dbc.Col(iframe)])
Beispiel #10
0
def generate_table(dataframe, max_rows=10):
    """
    This is a helper function which generates a Dash HTML table
    from a pandas dataframe
    """
    return html.Table([
        html.Thead(html.Tr([html.Th(col) for col in dataframe.columns])),
        html.Tbody([
            html.Tr(
                [html.Td(dataframe.iloc[i][col]) for col in dataframe.columns])
            for i in range(min(len(dataframe), max_rows))
        ])
    ])
def generate_table(dataframe, max_rows=50):
    return html.Table(
        # Header
        [
            html.Tr([html.Th(dataframe.index.name)] +
                    [html.Th(col) for col in dataframe.columns])
        ] +

        # Body
        [
            html.Tr([html.Td(dataframe.index[i])] + [
                html.Td('{:,.0f}'.format(dataframe.iloc[i][col]))
                for col in dataframe.columns
            ]) for i in range(min(len(dataframe), max_rows))
        ])
Beispiel #12
0
def get_table(rows: List[List[Any]],
              header: Optional[List[str]] = None) -> html.Table:
    """
    Create a HTML table from a list of elements.
    :param rows: list of list of cell contents
    :return: html.Table
    """
    contents = []
    for row in rows:
        contents.append(html.Tr([html.Td(item) for item in row]))
    if not header:
        return html.Table([html.Tbody(contents)], className="table")
    else:
        header = html.Thead([html.Tr([html.Th(item) for item in header])])
        return html.Table([header, html.Tbody(contents)], className="table")
Beispiel #13
0
def get_tenders_table():
    return html.Table([
        html.Tbody(
            [
                html.Tr([
                    html.Th(tender['date']),
                    html.Td(tender['tender_id']),
                    html.Td(tender['supplier'],
                            style=get_style(tender['supplier'])),
                    html.Td(tender['product'],
                            style={'color': get_color(tender['product_type'])
                                   }),
                    html.
                    Td(functions.format_number(tender['amount_usd']) + ' USD'),
                    html.Td(display_original_amount(tender)),
                    html.Td(tender['destination'])
                ]) for index, tender in csv_reader.get_wfp_tender_awards().
                sort_values(['date'], ascending=False).iterrows()
            ],
            style={
                'display': 'block',
                'height': '500px',
                'overflow-y': 'scroll',
                'overflow-x': 'hidden'
            })
    ],
                      style={'font-size': 'x-small'})
Beispiel #14
0
def get_controls(id, desc, range, default_weight=0.0):  # pylint: disable=redefined-builtin,redefined-outer-name
    """Get controls for one variable.

    This includes
     * the description
     * range
     * weight
    """
    label = dcc.Input(id=id + "_label",
                      type='text',
                      value=desc,
                      className="label")
    range_low = dcc.Input(id=id + "_low",
                          type='number',
                          value=range[0],
                          className="range")
    range_high = dcc.Input(id=id + "_high",
                           type='number',
                           value=range[1],
                           className="range")
    slider = dcc.Slider(id=id + "_weight",
                        min=weight_range[0],
                        max=weight_range[1],
                        value=default_weight,
                        step=0.01,
                        className="slider")
    #grid = dcc.Input(id=id + "_grid", type='number', value=ngrid)
    return html.Tr([
        html.Td(label),
        html.Td([range_low, html.Span('to'), range_high]),
        html.Td([html.Span(slider),
                 html.Span('', id=id + "_weight_label")])
    ],
                   id=id + "_tr")
Beispiel #15
0
def create_and_plot_sample(distribution: str, size: int, *parameters) -> tuple:
    """Create a sample of the specified distribution using the provided
    parameters, then plot a histogram & violin-plot, and compute descriptive
    statistics.

    Parameters
    ----------
    distribution : str
        The name of the currently selected distribution
    size : int
        The set sample size
    *parameters : int, float
        1 or 2 parameter values, depending on the distribution

    Returns
    -------
    tuple
        A histogram, a violin_plot, an ecdf-plot, a table of summary
        statistics, the currently specified parameters and a csv file with the
        sample data for download.
    """
    sample = process_random_sample(distribution, size, parameters)

    histogram = plotting.plot_histogram(sample["data"], distribution)
    violin_plot = plotting.plot_violin(sample["data"], distribution)
    ecdf_plot = plotting.plot_ecdf(sample["data"], distribution)

    summary_statistics = sample["summary_statistics"]
    summary_statistics_table = [html.Th("Summary Statistics")] + [
        html.Tr([html.Td(f"{name}:"), html.Td(value)])
        for name, value in summary_statistics.items()
    ]

    parameters = sample["parameters"]
    param_dict = {
        distribution_data[distribution].get(f"param{idx}"): value
        for idx, value in enumerate(parameters, start=1)
    }
    param_dict["Sample Size"] = size
    parameter_info = [
        html.H3("Parameters: "),
        html.P([
            ", ".join([f"{key}: {value}" for key, value in param_dict.items()])
        ]),
    ]

    sample_csv_download = {
        "content": sample["data"].to_csv(index=False),
        "filename": f"{distribution}-sample.csv",
        "type": "text/csv",
    }
    return (
        histogram,
        violin_plot,
        ecdf_plot,
        summary_statistics_table,
        parameter_info,
        sample_csv_download,
    )
Beispiel #16
0
    def update_calibration(self, n):
        header = html.Tr(children=[
            html.Th("Frequency (MHz)"),
            html.Th("Max (dBW)"),
        ],
                         style={"text-align": "left"})

        settings_row = html.Tr(children=[
            html.Td("[current settings]"),
            html.Td(""),
        ])

        for device, calibration in zip(self.device, self.calibration):
            header.children.append(html.Th(f"SDR {device} (dB)"))
            settings_row.children.append(html.Td(f"{calibration:.2f}"))

        table = html.Table(children=[header, settings_row],
                           style={
                               "width": "100%",
                               "text-align": "left"
                           })

        for freq, avgs in sorted(self.calibrations.items(),
                                 key=lambda item: max(item[1])):
            ordered_avgs = [
                avgs[d] + old if d in avgs else float("-inf")
                for d, old in zip(self.device, self.calibration)
            ]
            freq_max = max(ordered_avgs)

            row = html.Tr(children=[
                html.Td(f"{freq/1000/1000:.3f}"),
                html.Td(f"{freq_max:.2f}")
            ])
            for avg in ordered_avgs:
                row.children.append(html.Td(f"{avg - freq_max:.2f}"))

            table.children.append(row)

        return html.Div([
            html.H2("Calibration Table"),
            table,
        ],
                        style={"break-inside": "avoid-column"})
Beispiel #17
0
 def __init__(self):
     """Create the HTML table for the webapp."""
     self._table = [
         html.Tr([
             html.Th('OMEGA logger'),
             html.Th('Report No.'),
             html.Th('Description'),
             html.Th('Average'),
             html.Th('Stdev'),
             html.Th('Median'),
             html.Th('Max'),
             html.Th('Min'),
             html.Th('# Points')]
         )]
Beispiel #18
0
def generate_table(dataframe: List[output_column]) -> html.Table:
    return html.Table(
        # Header
        [
            html.Tr([
                html.Th(col["name"], style={"textAlign": "center"})
                for col in dataframe
            ])
        ] +
        # Body
        [
            html.
            Tr([col_align(col["values"][i], col["name"]) for col in dataframe])
            for i in range(len(ROWS))
        ])
Beispiel #19
0
 def show_props(*args):
     # return 'Something yet!'
     # print('show props')
     return html.Table(
         [
             html.Tr(
                 [
                     html.Td(prop),
                     html.Td(
                         json.dumps(val) if val is not None else "None", id=prop
                     ),
                 ]
             )
             for prop, val in zip(props, args)
         ]
     )
Beispiel #20
0
def get_data_list(data: Dict[str, str]):
    """
    Show a formatted table of data items.
    :param data: dictionary of label, value pairs
    :return: html.Div
    """
    contents = []
    for title, value in data.items():
        if isinstance(title, str):
            title = Label(title)
        contents.append(
            html.Tr([
                html.Td(title, style={"vertical-align": "middle"}),
                html.Td(value, style={"vertical-align": "middle"}),
            ]))
    return html.Table([html.Tbody(contents)], className="table")
def _generate_table_from_df(cls,
                            df,
                            float_format=None,
                            columns=None,
                            header=True,
                            index=False,
                            index_label=None,
                            date_format=None,
                            **table_kwargs):
    """
    Generate a Table component from a dataframe.

    Parameters
    ----------
    df : pandas.DataFrame
        DataFrame to render as a table.
    float_format : str, optional
        Format to use for floating point numbers.
    columns : sequence, optional
        Columns to render.
    header : boolean or list(str) or dict(str: str), optional
        Write out the column names. If a list of strings is given it is assumed
        to be aliases for the columns names (and hence must be the same length
        as df.columns). A dict can be passed to rename some columns, the format
        is {'<current_name>': '<new_name>'}. The dictionary need not have an
        entry for every column.
    index : boolean, optional
        Render the row names (index).
    index_label : str, optional
        Column label for index column if desired. If None is passed, but both
        header and index are True, then the index name is used.
    date_format : str, optional
        Format string for datetime objects.
    **table_kwargs : Keyword arguments
        Additional arguments to pass to the table component. See
        dash_bootstrap_components.Table for details.
    """
    import numpy as np
    import pandas as pd

    if columns is not None:
        df = df.loc[:, columns]

    if float_format is not None:
        for c in df.select_dtypes(["float"]).columns:
            df[c] = df[c].map(lambda x: "{1:{0}}".format(float_format, x))

    if date_format is not None:
        for c in df.select_dtypes(["datetime"]).columns:
            df[c] = df[c].map(lambda x: x.strftime(date_format))

    if index:
        df = df.reset_index()
        if index_label is not None:
            df = df.rename(columns={"index": index_label})

    if header:
        if isinstance(header, (tuple, list, np.ndarray, pd.Index)):
            try:
                df.columns = header
            except ValueError:
                raise ValueError(
                    "If specifying column names with a sequence, the number "
                    "of names must exactly match the number of columns.")
        elif isinstance(header, dict):
            df = df.rename(columns=header)

        # Get the actual headers
        n_levels = df.columns.nlevels
        header_values = [
            list(df.columns.get_level_values(level))
            for level in range(n_levels)
        ]

        # The sizes of consecutive header groups at each level
        header_spans = [[
            len(list(group)) for _, group in groupby(level_values)
        ] for level_values in header_values]

        # The positions of header changes for each level as an integer
        header_breaks = [[
            sum(level_spans[:i]) for i in range(1,
                                                len(level_spans) + 1)
        ] for level_spans in header_spans]

        # Include breaks from higher levels
        header_breaks = [
            sorted(set(reduce(add, header_breaks[:level])).union({0}))
            for level in range(1, n_levels + 1)
        ]

        # Go from header break positions back to cell spans
        header_spans = [
            reversed([
                level_breaks[i] - level_breaks[i - 1]
                for i in range(len(level_breaks) - 1, 0, -1)
            ]) for level_breaks in header_breaks
        ]

        table = [
            html.Thead([
                html.Tr(children=[
                    html.Th(
                        header_values[level][pos],
                        colSpan=span,
                    ) for pos, span in zip(header_breaks[level],
                                           header_spans[level])
                ]) for level in range(n_levels)
            ])
        ]
    else:
        table = []
    table.append(
        html.Tbody([
            html.Tr([html.Td(df.iloc[i, j]) for j in range(len(df.columns))])
            for i in range(len(df))
        ]))
    return cls(table, **table_kwargs)
Beispiel #22
0
    def __init__(self, pipeline) -> None:
        inputs, outputs = pipeline.connectors
        number_inputs = len(inputs)
        number_outputs = len(outputs)
        total_connectors = number_inputs + number_outputs

        sources, nodes, targets = pipeline.nodes
        num_sources = len(sources)
        num_nodes = len(nodes)
        num_targets = len(targets)
        number_nodes = num_sources + num_nodes + num_targets

        super().__init__(
            className='div-info-table',
            children=[
                dhtml.Table(
                    className='table-info-primary',
                    children=[
                        dhtml.Tr(children=[
                            dhtml.Td(children=[f'Total Nodes: {number_nodes}'])
                        ]),
                        dhtml.Tr(children=[
                            dhtml.Td(children=[
                                dhtml.Table(
                                    className='table-info-secondary',
                                    children=[
                                        dhtml.Tr(children=[
                                            dhtml.Td(children=['Source:']),
                                            dhtml.Td(
                                                children=[f'{num_sources}'])
                                        ]),
                                        dhtml.Tr(children=[
                                            dhtml.Td(children=['Inline:']),
                                            dhtml.Td(children=[f'{num_nodes}'])
                                        ]),
                                        dhtml.Tr(children=[
                                            dhtml.Td(children=['Target:']),
                                            dhtml.Td(
                                                children=[f'{num_targets}'])
                                        ])
                                    ])
                            ])
                        ]),
                        dhtml.Tr(children=[
                            dhtml.Td(children=[
                                f'Total Connectors: {total_connectors}'
                            ])
                        ]),
                        dhtml.Tr(children=[
                            dhtml.Td(children=[
                                dhtml.Table(
                                    className='table-info-secondary',
                                    children=[
                                        dhtml.Tr(children=[
                                            dhtml.Td(children=['Input:']),
                                            dhtml.Td(
                                                children=[f'{number_inputs}'])
                                        ]),
                                        dhtml.Tr(children=[
                                            dhtml.Td(children=['Output:']),
                                            dhtml.Td(
                                                children=[f'{number_outputs}'])
                                        ])
                                    ])
                            ])
                        ])
                    ])
            ])
from dash import dcc
from dash import html
from dash.dependencies import Input, Output

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div([
    dcc.Input(
        id='num-multi',
        type='number',
        value=5
    ),
    html.Table([
        html.Tr([html.Td(['x', html.Sup(2)]), html.Td(id='square')]),
        html.Tr([html.Td(['x', html.Sup(3)]), html.Td(id='cube')]),
        html.Tr([html.Td([2, html.Sup('x')]), html.Td(id='twos')]),
        html.Tr([html.Td([3, html.Sup('x')]), html.Td(id='threes')]),
        html.Tr([html.Td(['x', html.Sup('x')]), html.Td(id='x^x')]),
    ]),
])


@app.callback(
    Output('square', 'children'),
    Output('cube', 'children'),
    Output('twos', 'children'),
    Output('threes', 'children'),
    Output('x^x', 'children'),
    Input('num-multi', 'value'))
Beispiel #24
0
def get_statistic_results(ticker_analysis):
    rounding = 4

    rows = [
        html.Tr([
            html.Td("Tasa de Crecimiento Anual Compuesto (CAGR)"),
            html.Td(f"{round(ticker_analysis.cagr, rounding)} %")
        ]),
        html.Tr([
            html.Td("Retorno de comprar y mantener"),
            html.Td(
                f"{round(ticker_analysis.buy_and_hold_return, rounding)} %")
        ]),
        html.Tr([
            html.Td("Máximo Drawdown Histórico"),
            html.Td(f"{round(ticker_analysis.max_dd, rounding)} %")
        ]),
        html.Tr([
            html.Td("Media Diaria"),
            html.Td(f"{round(ticker_analysis.mean_daily_return, rounding)} %")
        ]),
        html.Tr([
            html.Td("Desviación Típica Diaria"),
            html.Td(f"{round(ticker_analysis.std_daily_return, rounding)} %")
        ]),
        html.Tr([
            html.Td("Máxima Pérdida Diaria"),
            html.Td(f"{round(ticker_analysis.min_return, rounding)} %")
        ]),
        html.Tr([
            html.Td("Máximo Beneficio Diario"),
            html.Td(f"{round(ticker_analysis.max_return, rounding)} %")
        ]),
        html.Tr([
            html.Td("Número de Días Analizados"),
            html.Td(f"{ticker_analysis.trading_days}")
        ]),
        html.Tr([
            html.Td("Coeficiente de Asimetría"),
            html.Td(f"{round(ticker_analysis.skewness, rounding)}")
        ]),
        html.Tr([
            html.Td("Curtosis"),
            html.Td(f"{round(ticker_analysis.kurtosis, rounding)}")
        ]),
        html.Tr([
            html.Td("VaR Modelo Gaussiano NC-95%"),
            html.Td(f"{round(ticker_analysis.var_gauss_95, rounding)} %")
        ]),
        html.Tr([
            html.Td("VaR Modelo Gaussiano NC-99%"),
            html.Td(f"{round(ticker_analysis.var_gauss_99, rounding)} %")
        ]),
        html.Tr([
            html.Td("VaR Modelo Gaussiano NC-99.7%"),
            html.Td(f"{round(ticker_analysis.var_gauss_99_7, rounding)} %")
        ]),
        html.Tr([
            html.Td("VaR Modelo Histórico NC-95%"),
            html.Td(f"{round(ticker_analysis.var_historic_95, rounding)} %")
        ]),
        html.Tr([
            html.Td("VaR Modelo Histórico NC-99%"),
            html.Td(f"{round(ticker_analysis.var_historic_99, rounding)} %")
        ]),
        html.Tr([
            html.Td("VaR Modelo Histórico NC-99.7%"),
            html.Td(f"{round(ticker_analysis.var_historic_99_7, rounding)} %")
        ]),
        html.Tr([
            html.Td("Volatilidad Anualizada"),
            html.Td(f"{round(ticker_analysis.vam, rounding)} %")
        ]),
        html.Tr([
            html.
            Td(f"Mínima volatilidad anualizada registrada el {ticker_analysis.min_vol_date()}"
               ),
            html.
            Td(f"{round(ticker_analysis.historic_vol_14_days_annualized().min(), rounding)} %"
               )
        ]),
        html.Tr([
            html.
            Td(f"Máxima volatilidad anualizada registrada el {ticker_analysis.max_vol_date()}"
               ),
            html.
            Td(f"{round(ticker_analysis.historic_vol_14_days_annualized().max(), rounding)} %"
               )
        ]),
        html.Tr([
            html.Td("Rango Medio días Negativos"),
            html.Td(f"{round(ticker_analysis.dn, rounding)} %")
        ]),
        html.Tr([
            html.Td("Rango Medio días Positivos"),
            html.Td(f"{round(ticker_analysis.dp, rounding)} %")
        ]),
        html.Tr([
            html.Td("Ratio RDN/RDP"),
            html.Td(
                f"{round(ticker_analysis.pos_neg_days_ratio(), rounding)} %")
        ])
    ]

    return dbc.Table([html.Tbody(rows)],
                     bordered=True,
                     dark=True,
                     hover=True,
                     responsive=True,
                     striped=True)
Beispiel #25
0
        html.Td(label),
        html.Td([range_low, html.Span('to'), range_high]),
        html.Td([html.Span(slider),
                 html.Span('', id=id + "_weight_label")])
    ],
                   id=id + "_tr")


controls_dict = collections.OrderedDict()
for k, v in list(variables.items()):
    controls = get_controls(k, v['label'], v['range'])
    controls_dict[k] = controls

head_row = html.Tr([
    html.Th('Variable'),
    html.Th('Range'),
    html.Th('Importance'),
])
controls_html = html.Table([head_row] + list(controls_dict.values()),
                           id='controls')
label_states = [
    dash.dependencies.State(k + "_label", 'value') for k in var_ids
]
low_states = [dash.dependencies.State(k + "_low", 'value') for k in var_ids]
high_states = [dash.dependencies.State(k + "_high", 'value') for k in var_ids]
weight_states = [
    dash.dependencies.State(k + "_weight", 'value') for k in var_ids
]

inp_nvars = html.Tr([
    html.Td('Number of variables: '),
Beispiel #26
0
# the styles for the main content position it to the right of the sidebar and
# add some padding.
CONTENT_STYLE = {
    "margin-left": "18rem",
    "margin-right": "2rem",
    "padding": "2rem 1rem",
}

cmp_upload = dbc.Alert(
    dbc.Table(
        html.Tr(
            [
                html.Td(dcc.Upload("Drag and Drop or ")),
                html.Td(
                    html.Div(
                        dbc.Button(dcc.Upload(html.A("Upload File")), color="primary")
                    ),
                ),
            ]
        ),
        borderless=False,
        # color="dark",
    ),
    color="dark",
)

sidebar = html.Div(
    [
        html.P("A simple sidebar layout with navigation links", className="lead"),
        dbc.Nav(
            [
Beispiel #27
0
import dash_bootstrap_components as dbc
from dash import html

from .util import make_subheading

table_header = html.Thead(
    html.Tr([
        html.Th("#"),
        html.Th("First name"),
        html.Th("Last name"),
    ]))

table_body = html.Tbody([
    html.Tr([
        html.Th("1", scope="row"),
        html.Td("Tom"),
        html.Td("Cruise"),
    ]),
    html.Tr([
        html.Th("2", scope="row"),
        html.Td("Jodie"),
        html.Td("Foster"),
    ]),
    html.Tr([
        html.Th("3", scope="row"),
        html.Td("Chadwick"),
        html.Td("Boseman"),
    ]),
])

table = html.Div(
Beispiel #28
0
def update_alarms(tab, n_intervals, type_connection, sta):
    # COUNTING THE ALARMS WHATEVER THE TAB
    i = 0
    try:

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

        bs_ongoing = bs_alarms.find('ongoing')

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

    except FileNotFoundError:
        pass

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

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

                table_body = [html.Tbody(states_xat_table)]

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

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

                table_body = [html.Tbody(states_soh_table)]

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

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

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

            bs_ongoing = bs_alarms.find('ongoing')

            # display all the ongoing alarms
            nc_alarms_inside = []

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

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

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

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

            table_body = [html.Tbody(nc_alarms_inside)]

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

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

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

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

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

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

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

            table_body = [html.Tbody(c_alarms_inside)]

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

        return [html.Div(id='tabs-content-inline', children=c_alarms_list),
                html.Div(id='number-alarms', children=i, hidden=True)]
Beispiel #29
0
# -*- coding: utf-8 -*-
import datetime

from dash import html

from datasources import hdx_connect

layout = html.Div(children=[
    html.H3('Data Sources'),
    html.Table([
        html.Thead([
            html.Tr([
                html.Th('Dataset'),
                html.Th('Source'),
                html.Th('Type'),
                html.Th('Files'),
                html.Th('Last Update')
            ])
        ]),
        html.Tbody([
            html.Tr([
                html.Td('Joint Malnutrition Estimate (UNICEF, WB, WHO)'),
                html.Td(
                    html.A('Humanitarian Data Exchange',
                           href='https://data.humdata.org/',
                           target='_blank')),
                html.Td('CSV File'),
                html.Td(
                    html.A(
                        'https://data.humdata.org/dataset/'
                        'child-malnutrition-joint-country-dataset-unicef-who-world-bank-group-2017',
Beispiel #30
0
def process_fmu(fmu_filename):

    basename, _ = os.path.splitext(fmu_filename)
    pickle_filename = basename + '.p'
    fmu_hash = os.path.basename(basename)

    try:
        model_description = read_model_description(fmu_filename,
                                                   validate=False)
    except Exception as e:
        alert = dbc.Alert([
            html.I(className='fas fa-times me-3'),
            f"Failed to read model description. {e}"
        ],
                          id='alert',
                          color='danger',
                          className='mt-3')
        with open(pickle_filename, 'wb') as f:
            pickle.dump([alert], f)
        return

    platforms = supported_platforms(fmu_filename)

    with zipfile.ZipFile(fmu_filename, 'r') as zf:
        nl = filter(lambda n: not n.endswith('/'), zf.namelist())

    fmi_types = []

    if model_description.modelExchange:
        fmi_types.append('Model Exchange')

    if model_description.coSimulation:
        fmi_types.append('Co-Simulation')

    def na(attr):
        value = getattr(model_description, attr)
        if value:
            return value
        else:
            return html.Span('n/a', className='text-muted')

    rows = [
        dbc.Row([
            dbc.Col(html.Span("FMI Version"), width=4),
            dbc.Col(html.Span(model_description.fmiVersion), width=8),
        ],
                className='py-1'),
        dbc.Row([
            dbc.Col("FMI Type", width=4),
            dbc.Col(', '.join(fmi_types), width=8),
        ],
                className='py-1'),
        dbc.Row([
            dbc.Col("Model Name", width=4),
            dbc.Col(model_description.modelName, width=8),
        ],
                className='py-1'),
        dbc.Row([
            dbc.Col("Platforms", width=4),
            dbc.Col(', '.join(platforms), width=8),
        ],
                className='py-1'),
        dbc.Row([
            dbc.Col(html.Span("Continuous States"), width=4),
            dbc.Col(html.Span(model_description.numberOfContinuousStates),
                    width=8),
        ],
                className='py-1'),
        dbc.Row([
            dbc.Col(html.Span("Event Indicators"), width=4),
            dbc.Col(html.Span(model_description.numberOfEventIndicators),
                    width=8),
        ],
                className='py-1'),
        dbc.Row([
            dbc.Col(html.Span("Model Variables"), width=4),
            dbc.Col(html.Span(len(model_description.modelVariables)), width=8),
        ],
                className='py-1'),
        dbc.Row([
            dbc.Col(html.Span("Generation Date"), width=4),
            dbc.Col(na('generationDateAndTime'), width=8)
        ],
                className='py-1'),
        dbc.Row([
            dbc.Col(html.Span("Generation Tool"), width=4),
            dbc.Col(na('generationTool'), width=8)
        ],
                className='py-1'),
        dbc.Row([
            dbc.Col(html.Span("Description"), width=4),
            dbc.Col(na('description'), width=8)
        ],
                className='py-1'),
        dbc.Row([
            dbc.Col(html.Span("SHA256"), width=4),
            dbc.Col(html.Span(fmu_hash), width=8),
        ],
                className='py-1'),
        dbc.Row([
            dbc.Col(html.Span("File Size"), width=4),
            dbc.Col(html.Span(f'{os.path.getsize(fmu_filename)} bytes'),
                    width=8),
        ],
                className='py-1'),
    ]

    try:
        problems = validate_fmu(fmu_filename)
    except Exception as e:
        problems = [str(e)]

    if problems:
        alert = dbc.Alert([
            html.P([
                html.I(className='fas fa-exclamation-circle me-3'),
                f"Validation failed. {len(problems)} {'problem was' if len(problems) == 1 else 'problems were'} found:"
            ]),
            html.Ul([html.Li(problem) for problem in problems])
        ],
                          id='alert',
                          color='danger',
                          className='mt-3')
    else:
        alert = dbc.Alert([
            html.I(className='fas fa-check me-3'),
            "Validation passed. No problems found."
        ],
                          id='alert',
                          color='success',
                          className='mt-3')

    variables = []

    table_header = [
        html.Thead(
            html.Tr([
                html.Th("Type"),
                html.Th("Name"),
                html.Th("Causality"),
                html.Th("Start", className='text-right'),
                html.Th("Unit"),
                html.Th("Description")
            ]))
    ]

    for variable in model_description.modelVariables:

        unit = variable.unit

        if unit is None and variable.declaredType is not None:
            unit = variable.declaredType.unit

        if variable.type == 'Boolean':
            color = '#c900c9'
        elif variable.type == 'Binary':
            color = '#ab0000'
        elif variable.type.startswith(('Int', 'Enum')):
            color = '#c78f00'
        elif variable.type.startswith(('Real', 'Float')):
            color = '#0000bf'
        else:  # String
            color = '#00a608'

        variables.append(
            html.Tr([
                html.Td(
                    html.Small(variable.type,
                               style={
                                   'color': color,
                                   'border': '1px solid ' + color,
                                   'border-radius': '1em',
                                   'padding': '0 0.5em 0 0.5em',
                               })),
                html.Td(variable.name),
                # html.Td(variable.variability),
                html.Td(variable.causality),
                html.Td(variable.start, className='text-right'),
                html.Td(unit),
                html.Td(variable.description, className='text-muted')
            ]))

    table = dbc.Table(table_header + [html.Tbody(variables)],
                      borderless=True,
                      size='sm')

    tabs = dbc.Tabs([
        dbc.Tab(rows, label="Model Info", className='p-4'),
        dbc.Tab(table, label="Variables", className='p-4'),
        dbc.Tab(html.Pre('\n'.join(nl)), label="Files", className='p-4'),
    ],
                    id='tabs')

    with open(pickle_filename, 'wb') as f:
        pickle.dump([alert, tabs], f)