Пример #1
0
def simple_dict_display(title, data, font_size):
    key_style = {
        "text-align": "right",
        "color": "white",
        "font-size": font_size,
        "font-weight": "bold"
    }
    value_style = {
        "text-align": "left",
        "color": "white",
        "font-size": font_size,
    }
    title_style = {"text-align": "center"}

    cols = []
    for key, value in data.items():
        cols.append(
            dbc.Col([
                html.Span(f"{key}: ", style=key_style),
                html.Span(f"{value}", style=value_style)
            ]))
    return dbc.Row(cols,
                   justify="centre",
                   style={
                       "margin-left": "auto",
                       "margin-right": "auto"
                   })
Пример #2
0
def make_summary_table(dff):
    """Make html table to show cagr and  best and worst periods"""

    table_class = "h5 text-body text-nowrap"
    cash = html.Span([html.I(className="fa fa-money-bill-alt"), " Cash"],
                     className=table_class)
    bonds = html.Span([html.I(className="fa fa-handshake"), " Bonds"],
                      className=table_class)
    stocks = html.Span([html.I(className="fa fa-industry"), " Stocks"],
                       className=table_class)
    inflation = html.Span([html.I(className="fa fa-ambulance"), " Inflation"],
                          className=table_class)

    start_yr = dff["Year"].iat[0]
    end_yr = dff["Year"].iat[-1]

    df_table = pd.DataFrame({
        "": [cash, bonds, stocks, inflation],
        f"Rate of Return (CAGR) from {start_yr} to {end_yr}": [
            cagr(dff["all_cash"]),
            cagr(dff["all_bonds"]),
            cagr(dff["all_stocks"]),
            cagr(dff["inflation_only"]),
        ],
        f"Worst 1 Year Return": [
            worst(dff, "3-mon T.Bill"),
            worst(dff, "10yr T.Bond"),
            worst(dff, "S&P 500"),
            "",
        ],
    })
    return dbc.Table.from_dataframe(df_table, bordered=True, hover=True)
Пример #3
0
 def well_options(self) -> html.Div:
     return html.Div(
         style={
             "marginLeft": "20px",
             "marginRight": "0px",
             "marginBotton": "0px"
         },
         children=[
             html.Div(children=html.Label(children=[
                 html.Span("Sampling:", style={"font-weight": "bold"}),
                 dcc.Input(
                     id=self.ids("sampling"),
                     debounce=True,
                     type="number",
                     required=True,
                     value=self.sampling,
                     persistence=True,
                     persistence_type="session",
                 ),
             ])),
             html.Div(children=html.Label(children=[
                 html.Span("Nextend:", style={"font-weight": "bold"}),
                 dcc.Input(
                     id=self.ids("nextend"),
                     debounce=True,
                     type="number",
                     required=True,
                     value=self.nextend,
                     persistence=True,
                     persistence_type="session",
                 ),
             ])),
         ],
     )
Пример #4
0
def current_readings_viewer(tab, n_intervals):
    if tab != 'current-readings':
        return

    n = n_intervals or 0  # n_intervals is initially None
    n += 1

    children = []
    margin_right = cfg.value('current_readings/margin_right', '16px')
    for serial, data in now().json.items():
        b = f'{serial} [{data["report_number"]}] - {data["alias"]} @ {data["datetime"][11:]}'
        children.append(html.B(b))
        if data['error']:
            children.append(html.P(data['error']))
        elif 'temperature2' in data:
            for sensor in ['1', '2']:
                p = []
                for key in 'temperature' + sensor, 'humidity' + sensor, 'dewpoint' + sensor:
                    p.append(html.I(key + ':', style={'color': 'grey'}))
                    p.append(
                        html.Span(f'{data[key]:.2f}',
                                  style={'margin-right': margin_right}))
                children.append(html.P(p))
        else:
            p = []
            for key in ['temperature', 'humidity', 'dewpoint']:
                p.append(html.I(key + ':', style={'color': 'grey'}))
                p.append(
                    html.Span(f'{data[key]:.2f}',
                              style={'margin-right': margin_right}))
            children.append(html.P(p))
    return html.Div(
        children=children,
        style={'fontSize': cfg.value('current_readings/font_size', '24px')})
Пример #5
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")
Пример #6
0
 def layout(self, spa, message='404 Not Found'):
     return html.Div([
         html.Div([
             html.Div([
                 html.Div([
                     html.H1('Oops!'),
                     html.H2(message),
                     html.Div(
                         'Sorry, an error has occurred, Requested page not found!',
                         className='error-details'),
                     html.Div([
                         dcc.Link([
                             html.Span(className='fa fa-home'),
                             ' Take Me Home'
                         ],
                                  href='/',
                                  className='btn btn-secondary btn-lg'),
                         dcc.Link([
                             html.Span(className='fa fa-envelope'),
                             ' Contact Support'
                         ],
                                  href='/support',
                                  className='btn btn-secondary btn-lg'),
                     ],
                              className='error-actions')
                 ],
                          className='error-template')
             ],
                      className='col-md-12')
         ],
                  className='row')
     ],
                     className='container')
Пример #7
0
def vector_selector(get_uuid: Callable,
                    vectormodel: SimulationTimeSeriesModel) -> html.Div:
    first_vector_group: str = ("Field" if "Field" in list(
        vectormodel.vector_groups.keys()) else list(
            vectormodel.vector_groups.keys())[0])
    return html.Div(
        style={"margin": "10px 0px"},
        children=[
            html.Span(wcc.Label("Vector type")),
            html.Div(
                id=get_uuid("vtype-container"),
                children=[
                    dcc.RadioItems(
                        id={
                            "id": get_uuid("vtype-select"),
                            "state": "initial"
                        },
                        options=[{
                            "label": i,
                            "value": i
                        } for i in vectormodel.vector_groups],
                        value=first_vector_group,
                        labelStyle={
                            "display": "inline-block",
                            "margin-right": "10px"
                        },
                    )
                ],
            ),
            html.Div(
                style={"margin-top": "5px"},
                children=[
                    html.Span(wcc.Label("Vector")),
                    html.Div(
                        id=get_uuid("vshort-container"),
                        children=[
                            wcc.Dropdown(
                                id=get_uuid("vshort-select"),
                                options=[{
                                    "label": i,
                                    "value": i
                                } for i in vectormodel.
                                         vector_groups[first_vector_group]
                                         ["shortnames"]],
                                value=vectormodel.vector_groups[
                                    first_vector_group]["shortnames"][0],
                                placeholder="Select a vector...",
                                clearable=False,
                            ),
                        ],
                    ),
                ],
            ),
            html.Div(id=get_uuid("vitems-container"), children=[]),
            html.Div(id=get_uuid("vector-select"), style={"display": "none"}),
            html.Div(id=get_uuid("clickdata-store"), style={"display":
                                                            "none"}),
        ],
    )
Пример #8
0
def update_metrics(n):
    lon, lat, alt = satellite.get_lonlatalt(datetime.datetime.now())
    style = {'padding': '5px', 'fontSize': '16px'}
    return [
        html.Span('Longitude: {0:.2f}'.format(lon), style=style),
        html.Span('Latitude: {0:.2f}'.format(lat), style=style),
        html.Span('Altitude: {0:0.2f}'.format(alt), style=style),
        html.Span('Intervals: {0:0.2f}'.format(n), style=style),
    ]
Пример #9
0
def ror_component(acct_names, min_date, max_date, name=None, sim_symbol=None):
    ror = total_rate_of_return(acct_names, min_date, max_date, sim_symbol)
    db_t = np.log(2) / np.log(1 + ror / 100)
    txt_color = "green" if ror > 0 else "red"
    name_span = [html.Span(f"{name}: ")] if name else []
    return html.Div(
        name_span
        + [
            html.Span(f"{ror:.2f}%", style={"color": txt_color}),
            html.Span(f" (Doubling time: {db_t:.1f} years)"),
        ]
    )
Пример #10
0
def realization_filters(
    uuid: str, tab: str, volumemodel: InplaceVolumesModel
) -> html.Div:
    reals = volumemodel.realizations
    return html.Div(
        style={"margin-top": "15px"},
        children=[
            html.Div(
                style={"display": "inline-flex"},
                children=[
                    html.Span(
                        "Realizations: ",
                        style={"font-weight": "bold"},
                    ),
                    html.Span(
                        id={"id": uuid, "tab": tab, "element": "real_text"},
                        style={"margin-left": "10px"},
                        children=f"{min(reals)}-{max(reals)}",
                    ),
                ],
            ),
            wcc.RadioItems(
                id={"id": uuid, "tab": tab, "element": "real-selector-option"},
                options=[
                    {"label": "Range", "value": "range"},
                    {"label": "Select", "value": "select"},
                ],
                value="range",
                vertical=False,
            ),
            wcc.RangeSlider(
                wrapper_id={"id": uuid, "tab": tab, "element": "real-slider-wrapper"},
                id={
                    "id": uuid,
                    "tab": tab,
                    "component_type": "range",
                },
                value=[min(reals), max(reals)],
                min=min(reals),
                max=max(reals),
                marks={str(i): {"label": str(i)} for i in [min(reals), max(reals)]},
            ),
            html.Div(
                style={"display": "none"},
                children=wcc.Select(
                    id={"id": uuid, "tab": tab, "selector": "REAL", "type": "REAL"},
                    options=[{"label": i, "value": i} for i in reals],
                    value=reals,
                ),
            ),
        ],
    )
Пример #11
0
 def layout(self) -> html.Div:
     return html.Div(children=[
         html.Span(
             "Here is some blue text to explain... ",
             id=self.uuid("blue_text"),
             style={"color": "blue"},
         ),
         html.Span(
             " ...and here is some red text that also needs an explanation.",
             id=self.uuid("red_text"),
             style={"color": "red"},
         ),
     ])
Пример #12
0
    def _make_search_box(self, search_term=None):

        search_field = dcc.Input(
            id=self.id("input"),
            className="input",
            type="text",
            value=search_term,
            placeholder="Enter a formula or mp-id…",
        )
        search_button = Button(
            [Icon(kind="search"), html.Span(), "Search"],
            kind="primary",
            id=self.id("button"),
        )
        search = Field(
            [Control(search_field),
             Control(search_button)],
            addons=True,
            style={"marginBottom": "0"},
        )

        return html.Div([
            html.Label("Search Materials Project:", className="mpc-label"),
            search
        ])
Пример #13
0
    def dataset_info(self) -> html.Div:
        max_pc, min_pc = self.datamodel.pc_scaling_min_max
        wvol, hcvol = self.datamodel.vol_diff_total

        number_style = {
            "font-weight": "bold",
            "font-size": "17px",
            "margin-left": "20px",
        }
        data = [
            ("HC Volume difference:", f"{hcvol:.2f} %"),
            ("Water Volume difference:", f"{wvol:.2f} %"),
            ("Maximum Capillary Pressure scaling:", f"{max_pc:.1f}"),
            ("Minimum Capillary Pressure scaling:", f"{min_pc:.3g}"),
        ]

        return wcc.Frame(
            style={"height": "90%"},
            children=[
                wcc.Header("Information", style=LayoutStyle.HEADER),
                self.information_dialog,
                wcc.Header("Key numbers", style=LayoutStyle.HEADER),
                html.Div([
                    html.Div([text, html.Span(num, style=number_style)])
                    for text, num in data
                ]),
            ],
        )
 def layout(self) -> html.Div:
     return html.Div(
         id=self.ids("layout"),
         children=[
             html.Span("Parameter distribution:",
                       style={"font-weight": "bold"}),
             html.Div(
                 style=self.set_grid_layout("8fr 1fr 2fr"),
                 children=[
                     dcc.Dropdown(
                         id=self.ids("parameter"),
                         options=[{
                             "value": col,
                             "label": col
                         } for col in self.parameter_columns],
                         value=self.parameter_columns[0],
                         clearable=False,
                         persistence=True,
                         persistence_type="session",
                     ),
                     self.make_buttons(self.ids("prev-btn"),
                                       self.ids("next-btn")),
                 ],
             ),
             wsc.PriorPosteriorDistribution(id=self.ids("graph")),
         ],
     )
Пример #15
0
 def plot_options_layout(self) -> wcc.FlexBox:
     """Row layout of dropdowns for plot options"""
     return wcc.FlexBox(children=[
         html.Div(children=html.Label(children=[
             html.Span("Response:", style={"font-weight": "bold"}),
             dcc.Dropdown(
                 id=self.ids("response"),
                 options=[{
                     "label": volume_description(i),
                     "value": i
                 } for i in self.responses],
                 value=self.initial_response if self.initial_response in
                 self.responses else self.responses[0],
                 clearable=False,
                 persistence=True,
                 persistence_type="session",
             ),
         ])),
         html.Div(children=html.Label(children=[
             html.Span("Plot type:", style={"font-weight": "bold"}),
             dcc.Dropdown(
                 id=self.ids("plot-type"),
                 options=[{
                     "label": i,
                     "value": i
                 } for i in self.plot_types],
                 value=self.initial_plot,
                 clearable=False,
                 persistence=True,
                 persistence_type="session",
             ),
         ])),
         html.Div(children=html.Label(children=[
             html.Span("Group by:", style={"font-weight": "bold"}),
             dcc.Dropdown(
                 id=self.ids("group"),
                 options=[{
                     "label": i.lower().capitalize(),
                     "value": i
                 } for i in self.selectors],
                 value=self.initial_group,
                 placeholder="Not grouped",
                 persistence=True,
                 persistence_type="session",
             ),
         ])),
     ], )
Пример #16
0
 def __init__(
     self,
     tag,
     tag_type="primary",
     tag_addon=None,
     tag_addon_type="primary",
     size="normal",
     *args,
     **kwargs,
 ):
     _update_css_class(kwargs, "tags")
     tags = [html.Span(tag, className=f"tag is-{tag_type} is-{size}")]
     if tag_addon:
         tags.append(
             html.Span(tag_addon,
                       className=f"tag is-{tag_addon_type} is-{size}"))
         kwargs["className"] += " has-addons"
     super().__init__(tags, *args, **kwargs)
Пример #17
0
def LabeledSlider(app,
                  label,
                  id,
                  min_val,
                  max_val,
                  units='',
                  help_text='',
                  max_width=500,
                  mark_gap=None,
                  marks={},
                  **kwargs):
    """As well as wrapping the Slider with a label, this function adds a dynamic label
    that displays the currently selected value, along with its units ('units').  In order
    to implement this functionality, this function needs access to the main Dash 'app'
    object so that an appropriate callback can be established.
    This function also simplifies the creation of evenly-spaced marks on the Slider by allowing
    you to specify a 'mark_gap' which is the spacing between evenly-spaced marks that start
    at the minimum Slider value ('min_val') and progress to the maximum Slider value ('max_val').
    If you do not pass a value for 'mark_gap', you should provide Slider marks in the 'marks'
    dictionary, which is the conventional method of supplying Slider markers.
    'max_width' specifies the maximum width of the Div containing all of these components.
    """

    # Make the Mark dictionary
    if mark_gap:
        mark_vals = np.arange(min_val, max_val + mark_gap, mark_gap)
        final_marks = {}
        for v in mark_vals:
            if v == int(v):
                v = int(v)
            final_marks[v] = str(v)
    else:
        final_marks = marks

    component = html.Div(id=f'div-{id}',
                         style={
                             'maxWidth': max_width,
                             'marginBottom': '4rem'
                         },
                         children=[
                             make_label(
                                 label, id, help_text,
                                 html.Span('',
                                           id=f'cur-val-{id}',
                                           style={'marginLeft': 5})),
                             dcc.Slider(id=id,
                                        marks=final_marks,
                                        min=min_val,
                                        max=max_val,
                                        **kwargs)
                         ])

    @app.callback(Output(f'cur-val-{id}', 'children'), [Input(id, 'value')])
    def set_cur_val(val):
        return f'Value = {val} {units}'

    return component
Пример #18
0
def make_label(label, id, help_text, trailing_item=None):
    """This function returns a HTML Paragraph that contains a text
    label ('label'), possibly a help icon with pop-up help ('help_text'), and possibly
    another HTML component ('trailing_item').  The 'id' is used to assign
    an id of 'label-{id}' to the Span holding the label.
    """
    label_items = [html.Span(label, id=f'label-{id}')]
    if len(help_text.strip()):
        label_items.append(html.I(className="fas fa-question-circle"))
    if trailing_item:
        label_items.append(trailing_item)
    return html.P(children=label_items, title=help_text)
Пример #19
0
 def update_preview(transformation_data, input_structure):
     if (not transformation_data) or (not input_structure):
         return html.Div()
     input_structure = self.from_data(input_structure)
     output_structure, error = apply_transformation(
         transformation_data, input_structure)
     if len(output_structure) > 64:
         warning = html.Span(
             f"The transformed crystal structure has {len(output_structure)} atoms "
             f"and might take a moment to display.")
     return self.get_preview_layout(input_structure,
                                    output_structure)
Пример #20
0
    def update_value_box(acct_names, min_date, max_date):
        if not acct_names:
            return "..."
        min_date, max_date = pd.to_datetime(min_date), pd.to_datetime(max_date)

        all_traces = calculate_traces(acct_names, min_date, max_date)

        min_val = np.round(all_traces.loc[min_date, "_total"], 2)
        max_val = np.round(all_traces.loc[max_date, "_total"], 2)

        change = np.round(max_val - min_val, 2)
        sign = "+" if change > 0 else "-"

        chg_color = "green" if change > 0 else "red"
        components = [
            html.Span(f"${min_val:,.2f} \u2192 ${max_val:,.2f} ("),
            html.Span(f"{sign}${abs(change):,.2f}", style={"color": chg_color}),
        ]
        if min_val > 0:
            # Calculate an annualized change iff we have a finite percent change
            pct_change = np.abs(change / min_val)
            n_years = (max_date - min_date).total_seconds() / (365 * 86400)
            ann_chg = np.power(1 + pct_change, 1 / n_years) - 1
            components.extend(
                [
                    html.Span(", "),
                    html.Span(f"{sign}{ann_chg:.2%}", style={"color": chg_color}),
                    html.Span(" annualized"),
                ]
            )
        components.append(html.Span(")"))
        return components
Пример #21
0
    def _sub_layouts(self):

        # this is a very custom component based on Bulma css stlyes
        upload_layout = html.Div(
            html.Label(
                [
                    html.Span(
                        [
                            Icon(kind="upload"),
                            html.Span(
                                "Choose a file to upload or drag and drop",
                                className="file-label",
                            ),
                        ],
                        className="file-cta",
                    ),
                    # TODO: CSS fix style and un-hide file name
                    html.Span(
                        id=self.id("upload_label"),
                        className="file-name",
                        style={"display": "none"},
                    ),
                ],
                className="file-label",
            ),
            className="file is-boxed",
            # TODO: CSS set sensible max-width, don't hard-code
            style={"max-width": "312px"},
        )

        upload = html.Div([
            html.Label("Load from your computer: ", className="mpc-label"),
            dcc.Upload(upload_layout,
                       id=self.id("upload_data"),
                       multiple=False),
            html.Div(id=self.id("error_message_container")),
        ])

        return {"upload": upload}
Пример #22
0
def get_tooltip(
    tooltip_label: Any,
    tooltip_text: str,
    underline: bool = True,
    tooltip_id: str = "",
    wrapper_class: str = None,
    **kwargs,
):
    """
    Uses the tooltip component from dash-mp-components to add a tooltip, typically for help text.
    This component uses react-tooltip under the hood.
    :param tooltip_label: text or component to display and apply hover behavior to
    :param tooltip_text: text to show on hover
    :param tooltip_id: unique id of the tooltip (will generate one if not supplied)
    :param wrapper_class: class to add to the span that wraps all the returned tooltip components (label + content)
    :param kwargs: additional props added to Tooltip component. See the components js file in dash-mp-components for a full list of props. 
    :return: html.Span
    """
    if not tooltip_id:
        tooltip_id = uuid4().hex

    tooltip_class = "tooltip-label" if underline else None
    return html.Span(
        [
            html.Span(
                tooltip_label,
                className=tooltip_class,
                **{
                    "data-tip": True,
                    "data-for": tooltip_id
                },
            ),
            mpc.Tooltip(tooltip_text, id=tooltip_id, **kwargs),
        ],
        className=wrapper_class,
    )
Пример #23
0
 def well_layout(self) -> html.Div:
     return html.Div(children=html.Label(children=[
         html.Span("Well:", style={"font-weight": "bold"}),
         dcc.Dropdown(
             id=self.ids("wells"),
             options=[{
                 "label": Path(well).stem,
                 "value": well
             } for well in self.wellfiles],
             value=self.wellfiles[0],
             clearable=False,
             persistence=True,
             persistence_type="session",
         ),
     ]), )
Пример #24
0
def date_selector(get_uuid: Callable,
                  vectormodel: SimulationTimeSeriesModel) -> html.Div:
    dates = vectormodel.dates
    return html.Div(
        style={"margin": "10px 0px"},
        children=[
            html.Div(
                style={"display": "inline-flex"},
                children=[
                    html.Span(wcc.Label("Date:")),
                    html.Span(
                        html.Label(
                            "date",
                            id=get_uuid("date-selected"),
                            style={"margin-left": "10px"},
                        ), ),
                ],
            ),
            wcc.Slider(
                id=get_uuid("date-slider"),
                value=len(dates) - 1,
                min=0,
                max=len(dates) - 1,
                included=False,
                marks={
                    idx: {
                        "label": dates[idx],
                        "style": {
                            "white-space": "nowrap",
                        },
                    }
                    for idx in [0, len(dates) - 1]
                },
            ),
        ],
    )
Пример #25
0
def update_figure(window_value, activity, file):
    changed_id = [p['prop_id'] for p in dash.callback_context.triggered][0]
    process_map = ''
    div_similarity = []
    if 'window-slider' in changed_id and window_value >= 0:
        window_value += 1  # because slider starts on 0 but windows on 1
        process_map = framework.get_model(file, window_value, get_user_id(), activity)
        if window_value > 1:
            previous_process_map = framework.get_model(file, window_value - 1, get_user_id(), activity)
        if framework.get_total_of_windows(
                activity) > 1:  # if there is only one window the metrics manager is not initialized
            if framework.get_metrics_status() == IPDDProcessingStatus.IDLE:
                metrics = framework.get_metrics_manager(activity).get_metrics_info(window_value)
                for metric in metrics:
                    div_similarity.append(html.Span(f'{metric.metric_name}: '))
                    div_similarity.append(html.Span("{:.2f}".format(metric.value), className='font-weight-bold'))

                    for additional_info in metric.get_additional_info():
                        strType, strList = additional_info.get_status_info()
                        div_similarity.append(html.Div([
                            html.Span(f'{strType}', className='font-italic'),
                            html.Span(f'{strList}', className='font-weight-bold')
                        ]))
    return process_map, html.Div(div_similarity)
Пример #26
0
 def __init__(self) -> None:
     super().__init__(
         className='div-logo',
         children=[
             dhtml.
             A(target=DOC_URL,
               className='display-inline',
               children=[
                   dhtml.Img(
                       className='logo',
                       src=
                       'https://mwvgroup.github.io/Egon/assets/images/logo.svg'
                   ),
                   dhtml.Span(className='logo-text', children=['Egon'])
               ])
         ])
Пример #27
0
def cite_me(doi: str = None,
            manual_ref: str = None,
            cite_text: str = "Cite me") -> html.Div:
    """
    Create a button to show users how to cite a particular resource.
    :param doi: DOI
    :param manual_ref: If DOI not available
    :param cite_text: Text to show as button label
    :return: A button
    """
    if doi:
        if doi in DOI_CACHE:
            ref = DOI_CACHE[doi]
        else:
            try:
                ref = content_negotiation(ids=doi, format="text",
                                          style="ieee")[3:]
                DOI_CACHE[doi] = ref
                dumpfn(DOI_CACHE, MODULE_PATH / "apps/assets/doi_cache.json")
            except Exception as exc:
                print("Error retrieving DOI", doi, exc)
                ref = f"DOI: {doi}"
        tooltip_text = f"If this analysis is useful, please cite {ref}"
    elif manual_ref:
        warnings.warn("Please use the DOI if available.")
        tooltip_text = (f"If this analysis is useful, please cite the "
                        f"relevant publication: {manual_ref}")
    else:
        tooltip_text = (f"If this analysis is useful, please cite the "
                        f"relevant publication (publication pending).")

    reference_button = html.A(
        [
            Button(
                [Icon(kind="book"), html.Span(cite_text)],
                size="small",
                kind="link",
                style={"height": "1.5rem"},
            )
        ],
        href=f"https://dx.doi.org/{doi}",
        target="_blank",
    )

    with_tooltip = get_tooltip(reference_button, tooltip_text, underline=False)

    return with_tooltip
Пример #28
0
def filter_dropdowns(
    uuid: str,
    volumemodel: InplaceVolumesModel,
    tab: str,
    hide_selectors: Optional[list] = None,
) -> html.Div:
    """Makes dropdowns for each selector"""
    dropdowns_layout: List[html.Div] = []
    hide_selectors = ["SENSNAME", "SENSTYPE", "SENSCASE"] + (
        hide_selectors if hide_selectors is not None else []
    )
    selectors = [
        x
        for x in volumemodel.selectors
        if x not in volumemodel.region_selectors + ["REAL"]
    ]
    for selector in selectors:
        dropdowns_layout.append(
            create_filter_select(
                selector,
                elements=list(volumemodel.dataframe[selector].unique()),
                filter_type="undef",
                uuid=uuid,
                tab=tab,
                hide=selector in hide_selectors,
            )
        )
    # Make region filters
    dropdowns_layout.append(
        html.Span("Region filters: ", style={"font-weight": "bold"})
    )
    if all(x in volumemodel.region_selectors for x in ["FIPNUM", "ZONE", "REGION"]):
        dropdowns_layout.append(fipnum_vs_zone_region_switch(uuid, tab))

    for selector in volumemodel.region_selectors:
        dropdowns_layout.append(
            create_filter_select(
                selector,
                elements=list(volumemodel.dataframe[selector].unique()),
                filter_type="region",
                uuid=uuid,
                tab=tab,
                hide=selector == "FIPNUM" and len(volumemodel.region_selectors) > 1,
            )
        )
    return html.Div(dropdowns_layout)
Пример #29
0
 def seismic_layout(self) -> html.Div:
     return html.Div(
         style={} if self.segyfiles else {"display": "none"},
         children=html.Label(children=[
             html.Span("Seismic:", style={"font-weight": "bold"}),
             dcc.Dropdown(
                 id=self.ids("cube"),
                 options=[{
                     "label": Path(segy).stem,
                     "value": segy
                 } for segy in self.segyfiles] if self.segyfiles else None,
                 value=self.segyfiles[0] if self.segyfiles else None,
                 clearable=False,
                 persistence=True,
                 persistence_type="session",
             ),
         ]),
     )
Пример #30
0
def subplot_xaxis_range(uuid: str, tab: str) -> html.Div:
    axis_matches_layout = []
    for axis in ["X axis", "Y axis"]:
        axis_matches_layout.append(
            html.Div(
                children=wcc.Checklist(
                    id={"id": uuid, "tab": tab, "selector": f"{axis} matches"},
                    options=[{"label": f"Equal {axis} range", "value": "Equal"}],
                    value=["Equal"],
                )
            )
        )
    return html.Div(
        children=[
            html.Span("Subplot options:", style={"font-weight": "bold"}),
            html.Div(style={"margin-bottom": "10px"}, children=axis_matches_layout),
        ]
    )